Merge branch 'master' of ssh://github.com/DefinitelyTyped/DefinitelyTyped into feature/updateReactRouterNative

This commit is contained in:
Almir Kadric
2018-03-05 01:16:21 +09:00
658 changed files with 41769 additions and 19019 deletions
+327 -141
View File
File diff suppressed because it is too large Load Diff
+335
View File
@@ -0,0 +1,335 @@
# 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)
> El repositorio de definiciones de TypeScript de alta calidad.
Vea también el sitio web [definitelytyped.org](http://definitelytyped.org), aunque la información en este README está más actualizada.
## ¿Qué son los `declaration files`?
Vea el [Manual de TypeScript](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html).
## ¿Cómo los obtengo?
### npm
Este es el método preferido. Solo está disponible para usuarios TypeScript 2.0+. Por ejemplo:
```sh
npm install --save-dev @types/node
```
Los types deberían ser incluidos automaticamente 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".
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="" />`.
### Otros métodos
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
Tal vez debas añadir manualmente las [referencias](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).
## ¿Cómo puedo contribuir?
¡DefinitelyTyped solo trabaja gracias a contribuidores como tú!
### Prueba
Antes de compartir tu mejora con el mundo, úselo usted mismo.
#### Prueba editando un paquete existente
Para agregar nuevas funciones puedes usar el [module augmentation](http://www.typescriptlang.org/docs/handbook/declaration-merging.html).
También puedes editar directamente los types en `node_modules/@types/foo/index.d.ts`, o copiarlos de ahí y seguir los pasos explicados a continuación.
#### Prueba un nuevo paquete
Añade a tu `tsconfig.json`:
```json
"baseUrl": "types",
"typeRoots": ["types"],
```
(También puedes usar `src/types`.)
Crea un `types/foo/index.d.ts` que contenga declaraciones del módulo "foo".
Ahora deberías poder importar desde `"foo"` a tu código y te enviara a un nuevo tipo de definición.
Entonces compila *y* ejecuta el código para asegurarte que el tipo de definición en realidad corresponde a lo que suceda en el momento de la ejecución.
Una vez que hayas probado tus definiciones con el código real, haz un [PR](#make-a-pull-request)
luego sigue las instrucciones para [editar un paquete existente](#edit-an-existing-package) o
[crear un nuevo paquete](#create-a-new-package).
### Haz un pull request
Una vez que hayas probado tu paquete, podrás compartirlo en DefinitelyTyped.
Primero, haz un [fork](https://guides.github.com/activities/forking/) en este repositorio, instala [node](https://nodejs.org/), y luego ejecuta la `npm install`.
#### Editar un paquete existente
* `cd types/my-package-to-edit`
* Haz cambios. Recuerda editar las pruebas.
* También puede que quieras añadirte 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
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* Si hay un `tslint.json`, ejecuta `npm run lint package-name`. De lo contrario, ejecuta `tsc` en el directorio del paquete.
Cuando hagas un PR para editar un paquete existente, `dt-bot` deberá @-mencionar a los autores previos.
Si no lo hace, puedes hacerlo en el comentario asociado con el PR.
#### Crear un nuevo paquete
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.
(Puedes usar `npm info foo` para verificar la existencia del paquete `foo`.)
Tu paquete debería tener esta estructura:
| Archivo | Propósito |
| --- | --- |
| index.d.ts | Este contiene los typings del paquete. |
| foo-tests.ts | Este contiene una muestra del código con el que se realiza la prueba de escritura. Este código *no* es ejecutable, pero sí es type-checked. |
| tsconfig.json | Este permite ejecutar `tsc` dentro del paquete. |
| tslint.json | Permite linting. |
Generalas ejecutando `npm install -g dts-gen` y `dts-gen --dt --name my-package-name --template module`.
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.
Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js).
#### Errores comunes
* 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.
* `interface Foo { new(): Foo; }`:
Este define el tipo de objeto que esten nuevos. Probablemente quieras `declare class Foo { constructor(); }`.
* `const Class: { new(): IClass; }`:
Prefiere usar una declaración de clase `class Class { constructor(); }` En vez de una nueva constante.
* `getMeAT<T>(): T`:
Si un tipo de parámetro no aparece en los tipos de ningún parámetro, no tienes una función genérica, solo tienes un afirmación del tipo disfrazado.
Prefiera utilizar una afirmación de tipo real, p.ej. `getMeAT() as number`.
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 }`.
* `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`.
#### Remover un paquete
Cuando un paquete [bundles](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) sus propios tipos, estos tipos deberán ser removidos de DefinitelyTyped para evitar que generen confusión.
Se puede remover ejecutando `npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]`.
- `typingsPackageName`: Este es el nombre del directorio que tienes que eliminar.
- `asOfVersion`: Un stub será publicado a `@types/foo` con esta versión. Debería ser más grande que cualquier versión publicada actualmente.
- `sourceRepoURL`: Esto debería señalar el repositorio que contiene los typings.
- `libraryName`: Un nombre descriptivo de la librería, p.ej. "Angular 2" en vez de "angular2". (Si es omitido, será idéntico a "typingsPackageName".)
Cualquier otro paquete en DefinitelyTyped que referencie el paquete eliminado deberá ser actualizado para referenciar los tipos bundled. para hacer esto, añade `package.json` con `"dependencies": { "foo": "x.y.z" }`.
Si un paquete nunca estuvo en DefinitelyTyped, no será necesario añadirlo a `notNeededPackages.json`.
#### Lint
Para realizar el lint a un paquete, solo añade `tslint.json` al paquete que contiene `{ "extends": "dtslint/dt.json" }`. Todos los paquetes nuevos deberán pasar por el proceso de linted.
Si el `tslint.json` deshabilita algunas reglas esto se debe a que aún no se ha acomodado. Por ejemplo:
```js
{
"extends": "dtslint/dt.json",
"rules": {
// This package uses the Function type, and it will take effort to fix.
"ban-types": false
}
}
```
(Para indicar que la regla lint realmente no es utilizada, usa `// tslint:disable rule-name` o mejor, `//tslint:disable-next-line rule-name`.)
Para afirmar que una expresión es de un tipo dado, utilice `$ExpectType`. Para afirmar que una expresión causa un error de compilación, utilice `$ExpectError`.
```js
// $ExpectType void
f(1);
// $ExpectError
f("one");
```
Para más detalles, vea el [dtslint](https://github.com/Microsoft/dtslint#write-tests) readme.
Realiza una prueba ejecutando `npm run lint package-name` donde `package-name` es el nombre de tu paquete.
Este script utiliza [dtslint](https://github.com/Microsoft/dtslint).
## FAQ
#### ¿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).
#### 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.
#### Mi PR ha sido merged; ¿cuándo será actualizado el paquete de `@types` NPM?
Los paquetes NPM deberán ser actualizados en unas cuantas horas. Si ha pasado más de 24 horas, menciona a @RyanCavanaugh y/o a @andy-ms en el PR para investigar.
#### 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 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.
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.
#### Algunos paquetes no tienen `tslint.json`, y algunos `tsconfig.json` no contienen `"noImplicitAny": true`, `"noImplicitThis": true`, o `"strictNullChecks": true`.
Entonces están equivocados. Puedes ayudar enviando un pull request para arreglarlos.
#### Puedo pedir una definition?
Aquí están las [definiciones solicitadas actualmente](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest).
#### ¿Qué pasa con las type definitions para el DOM?
Si las types son parte de los estándares web, estas deberán ser contribuidas a [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) para que se hagan parte de la librería predeterminada `lib.dom.d.ts`.
#### Un paquete utiliza `export =`, pero prefiero utilizar las import predeterminadas. ¿Puedo cambiar `export =` por `export default`?
Si la import predeterminada trabaja en tu ambiente, considera hacer un cambio en la opción de compilación [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) opción compilar.
No cambies la type definition si es preciso.
Para un paquete NPM, `export =` es exacto si `node -p 'require("foo")'` es la export, y `export default` es exacto si `node -p 'require("foo").default'` es el export.
#### Quiero usar las características de TypeScript 2.1 o superior.
Entonces deberás añadir un comentario a la última línea de la definición en el encabezado (despues de `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// TypeScript Version: 2.1`.
#### Quiero añadir un DOM API que no está presente en TypeScript por defecto.
Esto puede pertenecer a [TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme). Vea las guías allí.
Si el estándar sigue siendo un borrador, este pertenece aquí.
Utilice un nombre que empiece con `dom-` e incluya un link al estándar como el "Project" con el link en el encabezado.
Cuando ya no sea un borrador, lo podremos eliminar desde DefinitelyType y hacer obsoleto el paquete `@types` asociado.
#### Quiero actualizar un paquete a una nueva versión principal
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.
Por ejemplo [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) se ve así:
```json
{
"compilerOptions": {
"baseUrl": "../../",
"typeRoots": ["../../"],
"paths": {
"history": [ "history/v2" ]
},
},
"files": [
"index.d.ts",
"history-tests.ts"
]
}
```
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.
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`.
#### ¿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.
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.
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.
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:
```json
{
"paths":{
"@foo/bar": ["foo__bar"]
}
}
```
#### El historial de archivos en GitHub parece incompleto.
GitHub no le hace [support](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) historial de archivos para archivos renombrados. Utilice [`git log --follow`](https://www.git-scm.com/docs/git-log) en su lugar.
#### Debería añadir un namespace que no exporte un módulo que utilice que utilice imports estilo ES6?
Algunos paquetes, como [chai-http](https://github.com/chaijs/chai-http), exportan una función.
importar este módulo con un ES6 style import de forma `import * as foo from "foo";` conduce al error:
> error ts2497: El módulo 'foo' se resuelve en una entidad que no es un módulo y no se puede importar mediante esta construcción
Este error puede ser suprimido al unir la declaración de una función con un namespace vacío del mismo nombre pero esta práctica no es recomendable.
Esto es un citado común [Respuestas de Stack Overflow](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) con respecto a este asunto.
Es más apropiado importar este módulo utilizando la sintaxis `import foo = require("foo");`, o utilizando una importación predeterminada como `import foo from "foo";` si usas la bandera `--allowSyntheticDefaultImports` si la ejecución de tu módulo soporta un esquema de interoperación para módulos no ECMAScript como tal.
## Licencia
Este proyecto es licenciado bajo la licencia MIT.
Los derechos de autor de cada archivo de definición son respectivos de cada contribuidor listado al comienzo de cada archivo de definición.
[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon)
+1 -1
View File
@@ -6,12 +6,12 @@
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)*
## What are declaration files?
See the [TypeScript handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html).
## How do I get them?
### npm
+6
View File
@@ -24,6 +24,12 @@
"sourceRepoURL": "https://github.com/epoberezkin/ajv",
"asOfVersion": "1.0.0"
},
{
"libraryName": "angular-touchspin",
"typingsPackageName": "angular-touchspin",
"sourceRepoURL": "https://github.com/nkovacic/angular-touchspin",
"asOfVersion": "1.8.2"
},
{
"libraryName": "angular-ui-router-default",
"typingsPackageName": "angular-ui-router-default",
+492 -66
View File
@@ -1,79 +1,505 @@
// Note -- running these tests under cscript requires some ES5 polyfills
const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
const results: T[] = [];
const enumerator = new Enumerator<T>(col);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
results.push(enumerator.item());
enumerator.moveNext();
}
return results;
};
// source -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms630826(v=vs.85).aspx
{
const cd = new ActiveXObject('WIA.CommonDialog');
const dm = new ActiveXObject('WIA.DeviceManager');
// Convert a file
let commonDialog = new ActiveXObject('WIA.CommonDialog');
let img = commonDialog.ShowAcquireImage();
// Download new items as they are created
{
dm.RegisterEvent(WIA.EventID.wiaEventItemCreated, WIA.Miscellaneous.wiaAnyDeviceID);
ActiveXObject.on(dm, 'OnEvent', ['EventID', 'DeviceID', 'ItemID'], x => {
const dev = dm.DeviceInfos(x.DeviceID).Connect();
const itm = dev.GetItem(x.ItemID);
const img = cd.ShowTransfer(itm);
const v = img.FileData;
// Picture type not available in Javascript
});
}
// when DefinitelyTyped supports Typescript 2.4 -- end of July 2017, replace these:
let jpegFormatID = '{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}';
if (img.FormatID !== jpegFormatID) {
const ip = new ActiveXObject('WIA.ImageProcess');
ip.Filters.Add(ip.FilterInfos.Item('Convert').FilterID);
ip.Filters.Item(1).Properties.Item('FormatID').Value = jpegFormatID;
img = ip.Apply(img);
}
// with this:
/*if (img.FormatID !== WIA.FormatID.wiaFormatJPEG) {
let ip = new ActiveXObject('WIA.ImageProcess');
ip.Filters.Add(ip.FilterInfos.Item('Convert').FilterID);
ip.Filters.Item(1).Properties.Item('FormatID').Value = WIA.FormatID.wiaFormatJPEG;
img = ip.Apply(img);
}*/
// Take a picture
let dev = commonDialog.ShowSelectDevice();
if (dev.Type === WIA.WiaDeviceType.CameraDeviceType) {
// when DefinitelyTyped supports Typescript 2.4 -- end of July 2017, replace these:
const commandID = '{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}';
const itm = dev.ExecuteCommand(commandID);
// with this:
// let itm = dev.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture);
}
// Display detailed property information
dev = commonDialog.ShowSelectDevice();
let e = new Enumerator<WIA.Property>(dev.Properties); // no foreach over ActiveX collections
e.moveFirst();
while (!e.atEnd()) {
const p = e.item();
let s = `${p.Name} (${p.PropertyID}) = `;
if (p.IsVector) {
s += '[vector of data]';
} else {
s += p.Value;
if (p.SubType !== WIA.WiaSubType.UnspecifiedSubType) {
if (p.Value !== p.SubTypeDefault) {
s += ` (Default = ${p.SubTypeDefault})`;
}
// Convert a file
{
let img = cd.ShowAcquireImage();
if (img && img.FormatID !== WIA.FormatID.wiaFormatJPEG) {
const ip = new ActiveXObject('WIA.ImageProcess');
ip.Filters.Add(ip.FilterInfos('Convert').FilterID);
ip.Filters(1).Properties('FormatID').Value = WIA.FormatID.wiaFormatJPEG;
img = ip.Apply(img);
}
}
if (p.IsReadOnly) {
s += ' [READ ONLY]';
} else {
switch (p.SubType) {
case WIA.WiaSubType.FlagSubType:
case WIA.WiaSubType.ListSubType:
if (p.SubType === WIA.WiaSubType.FlagSubType) {
s += ' [valid flags include: ';
// Take a picture
{
const dev = cd.ShowSelectDevice();
if (dev && dev.Type === WIA.WiaDeviceType.CameraDeviceType) {
const item = dev.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture);
}
}
// Display detailed property information
{
const dev = cd.ShowSelectDevice();
if (dev) {
collectionToArray(dev.Properties).forEach(p => {
let s = `${p.Name} (${p.PropertyID}) = `;
if (p.IsVector) {
s += '[vector of data]';
} else {
s += ' [valid values include: ';
}
const count = p.SubTypeValues.Count;
for (let i = 1; i <= count; i++) {
s += p.SubTypeValues.Item(i);
if (i < count) {
s += ', ';
s += p.Value;
if (p.SubType !== WIA.WiaSubType.UnspecifiedSubType
&& p.Value !== p.SubTypeDefault) {
s += ` (Default = ${p.SubTypeDefault})`;
}
}
s += ']';
break;
case WIA.WiaSubType.RangeSubType:
s += ` [valid values in the range from ${p.SubTypeMin} to ${p.SubTypeMax} in increments of ${p.SubTypeStep}]`;
break;
if (p.IsReadOnly) {
s += ' [READ ONLY]';
} else {
switch (p.SubType) {
case WIA.WiaSubType.FlagSubType:
case WIA.WiaSubType.ListSubType:
const count = p.SubTypeValues.Count;
const items: string[] = [];
for (let i = 1; i <= count; i++) {
items.push(p.SubTypeValues(i));
}
const descr = p.SubType === WIA.WiaSubType.FlagSubType ? 'flags' : 'values';
s += ` [valid ${descr} include: ${items.join(',')}]`;
break;
case WIA.WiaSubType.RangeSubType:
s += ` [valid values in the range from ${p.SubTypeMin} to ${p.SubTypeMax} in increments of ${p.SubTypeStep}]`;
break;
}
}
WScript.Echo(s);
});
}
}
WScript.Echo(s);
// Determine whether the selected device is a camera
{
const dev = cd.ShowSelectDevice();
if (dev && dev.Type === WIA.WiaDeviceType.CameraDeviceType) {
WScript.Echo('Selectd device is a camera');
}
}
// Count root - level images for transfer
{
const dev = cd.ShowSelectDevice();
if (dev) {
const count = collectionToArray(dev.Items).filter(f => {
const imageFlag = WIA.WiaItemFlag.ImageItemFlag;
return (f.Properties('Item Flags').Value & imageFlag) === imageFlag;
}).length;
WScript.Echo(`Selected device has ${count} top-level images`);
}
}
// Display all imagefile properties
{
const img = cd.ShowAcquireImage();
if (img) {
collectionToArray(img.Properties).forEach(p => {
let contents = '';
if (p.IsVector) {
contents = '[vector data not emitted]';
} else if (p.Type === WIA.WiaImagePropertyType.RationalImagePropertyType) {
contents = `${p.Value.Nunerator}/${p.Value.Denominator}`;
} else if (p.Type === WIA.WiaImagePropertyType.StringImagePropertyType) {
contents = `"${p.Value}"`;
} else {
contents = p.Value;
}
WScript.Echo(`${p.Name} (${p.PropertyID}) = ${contents}`);
});
}
}
// Determine the event type
{
const dev = cd.ShowSelectDevice();
if (dev) {
const actionEvent = WIA.WiaEventFlag.ActionEvent;
collectionToArray(dev.Events).forEach(e => {
const msg = (e.Type & actionEvent) === actionEvent ?
`${e.Name} is an Action event` :
`${e.Name} is not an Action event`;
WScript.Echo(msg);
});
}
}
// Set rational numerator and denominator
{
const r = new ActiveXObject('WIA.Rational');
r.Numerator = 1;
r.Denominator = 3;
WScript.Echo(`1/3 = ${r.Value}`);
r.Numerator = 2;
r.Denominator = 6;
WScript.Echo(`2/6 = ${r.Value}`);
}
// Create and initialize a vector object
{
const v: WIA.Vector<number> = new ActiveXObject('WIA.Vector');
v.SetFromString('This is a test', true, false);
// when iterated using Enumerator / collectionToArray, each item comes back as an Automation Byte
// https://stackoverflow.com/questions/48757982/wia-vector-returns-something-which-is-not-a-number
// so the following falls, because fromCharCode is expecting a number
// collectionToArray(v).forEach(item => WScript.Echo(String.fromCharCode(item)));
// Instead, use the Vector's Item method, or the Vector's default property:
for (let i = 1; i <= v.Count; i++) {
WScript.Echo(String.fromCharCode(v(i)));
}
}
// Display detailed image information
{
const img = new ActiveXObject('WIA.ImageFile');
img.LoadFile('c:\\windows\\web\\Screen\\img102.jpg');
let s = `
Width = ${img.Width}
Height = ${img.Height}
Depth = ${img.PixelDepth}
Horizontal resolution = ${img.HorizontalResolution}
Vertical resolution = ${img.VerticalResolution}
Frame count = ${img.FrameCount}}
`.trim();
let arr: string[] = [];
if (img.IsIndexedPixelFormat) { arr.push('Pixel data contains palette indexes'); }
if (img.IsAlphaPixelFormat) { arr.push('Pixel data has alpha information'); }
if (img.IsExtendedPixelFormat) { arr.push('Pixel data has extended color information (16 bit/channel)'); }
if (img.IsAnimated) { arr.push('Image is animated'); }
const propertyTests = [40091, 40092, 40093, 40094, 40095]
.filter(n => img.Properties.Exists(n))
.map(n => {
const prp = img.Properties(n);
return `${prp.Name} = ${prp.Value.String}`;
});
arr = arr.concat(propertyTests);
if (arr.length) {
s += '\n' + arr.join('\n');
}
WScript.Echo(s);
}
// Create an imageprocess object and enumerate filters
{
const ip = new ActiveXObject('WIA.ImageProcess');
collectionToArray(ip.FilterInfos).forEach(fi => {
const s = [
fi.Name,
new Array(51).join('='),
fi.Description
].join('\n');
WScript.Echo(s);
});
}
// Create an imageprocess object and create one of each available filter
{
const ip = new ActiveXObject('WIA.ImageProcess');
const stringValue = (v: any) => {
if (typeof v === 'string') { return `"${v}"`; }
return v;
};
const listValues = (v: any) => collectionToArray(v).join(', ');
const listProperties = (filter: WIA.Filter) => {
let s = [
`${filter.Name} (${filter.FilterID})`,
new Array(51).join('='),
filter.Description,
new Array(51).join('=')
].map(line => line + '\n').join('');
s += collectionToArray(filter.Properties).map(p => {
let contents: string;
switch (typeof p.Value) {
// these case clauses replace the IsObject function in VB6/VBScript
case 'boolean':
case 'string':
case 'number':
contents = stringValue(p.Value);
default:
switch (p.SubType) {
case WIA.WiaSubType.FlagSubType:
contents = ` // [valid values formed by using the OR operator with the following bit flags: ${listValues(p.SubTypeValues)}]`;
break;
case WIA.WiaSubType.ListSubType:
contents = ` // [valid values from the following list: ${listValues(p.SubTypeValues)}]`;
break;
case WIA.WiaSubType.RangeSubType:
contents = ` // [valid values between ${p.SubTypeMin} and ${p.SubTypeMax}, with a step of ${p.SubTypeStep}]`;
break;
default:
contents = '';
break;
}
}
return `ip.Filters(1).Properties("${p.Name}") = ${contents}`;
}).join('\n');
WScript.Echo(s);
};
collectionToArray(ip.FilterInfos).forEach(fi => {
ip.Filters.Add(fi.FilterID);
listProperties(ip.Filters(1));
ip.Filters.Remove(1);
});
}
// List the supported transfer formats
{
const stringFormat = (fld: string) => {
switch (fld) {
case WIA.FormatID.wiaFormatBMP: return 'BMP';
case WIA.FormatID.wiaFormatPNG: return 'PNG';
case WIA.FormatID.wiaFormatGIF: return 'GIF';
case WIA.FormatID.wiaFormatJPEG: return 'JPEG';
case WIA.FormatID.wiaFormatTIFF: return 'TIFF';
default: return 'Unknown';
}
};
const dev = cd.ShowSelectDevice();
const items = dev && cd.ShowSelectItems(dev, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true);
if (items) {
WScript.Echo(collectionToArray(items(1).Formats).map(stringFormat).join(', '));
}
}
// Enumerate supported commands in commands collection
{
const dev = cd.ShowSelectDevice();
if (dev && collectionToArray(dev.Commands).some(dc => dc.CommandID === WIA.CommandID.wiaCommandTakePicture)) {
WScript.Echo('Selected device supports the TakePicture command');
}
}
// Enumerate root - level items and display their names
{
const dev = cd.ShowSelectDevice();
if (dev) {
collectionToArray(dev.Items).forEach(item => {
let s: string = item.Properties("Item Name").Value;
if (item.Properties.Exists("Item Time Stamp")) {
const v: WIA.Vector = item.Properties("Item Time Stamp").Value;
if (v.Count === 8) { s += ` (${v.Date})`; }
}
WScript.Echo(s);
});
}
}
// Determine the number of items returned by ShowSelectItems
{
const dev = cd.ShowSelectDevice();
const items = dev && cd.ShowSelectItems(dev, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true);
if (items) {
WScript.Echo(`You selected ${items.Count} items`);
}
}
// Enumerate all the supported events for the selected device
{
const dev = cd.ShowSelectDevice();
if (dev) {
const msg = collectionToArray(dev.Events)
.map(e => `\n${e.Name} (${e.EventID}): ${e.Description}`)
.join('');
WScript.Echo('The selected device supports the following events: ' + msg);
}
}
// List all available devices by name and deviceid
collectionToArray(dm.DeviceInfos).forEach(di => {
const name: string = di.Properties("Name").Value;
WScript.Echo(`${name} (${di.DeviceID})`);
});
// Display all the properties for the selected device
{
const dev = cd.ShowSelectDevice();
if (dev) {
collectionToArray(dev.Properties).forEach(p => {
const name = `${p.Name} (${p.PropertyID})`;
let contents: string;
if (p.IsVector) {
contents = '[vector of data]';
} else if (p.Type === WIA.WiaPropertyType.StringPropertyType) {
contents = `"${p.Value}"`;
} else {
contents = p.Value;
}
WScript.Echo(`${name} = ${contents}`);
});
}
}
// Enumerate the supported commands
{
const dev = cd.ShowSelectDevice();
const items = dev && cd.ShowSelectItems(dev, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true);
if (items) {
const msg = collectionToArray(items(1).Commands)
.map(c => `${c.Name}: ${c.Description}\n`)
.join('');
WScript.Echo(`The selected item supports the following commands:\n${msg}`);
}
}
// Create an imagefile object that contains a blank page
{
// This fails with the error: `The Vector's Type is not compatible with this operation`
/*const c = 0xFF0000FF;
const v: WIA.Vector<number> = new ActiveXObject('WIA.Vector');
for (let i = 0; i < 4; i++) {
v.Add(c);
}
const img = v.ImageFile(2, 2);
img.SaveFile('C:\\test.' + img.FileExtension);*/
}
interface WshArgumentsBase<TKey = number | string> {
Item(index: TKey): string;
(index: TKey): string;
length: number;
Count(): number;
}
interface WshArguments extends WshArgumentsBase { // not sure if WshArguments takes a string as well, or only a number
Named: WshArgumentsBase<string>;
Unnamed: WshArgumentsBase<number>;
ShowUsage(): void;
}
// Implement a windows script host script that runs automatically
{
const args = collectionToArray(WScript.Arguments as WshArguments)
.map(arg => arg.toLowerCase());
switch (args.length) {
case 1:
case 2:
const command = `${WScript.FullName} "${WScript.ScriptFullName}" connect`;
const name = 'QuickTransfer';
const title = 'Quick Scripting Transfer';
const icon = `${WScript.FullName}, 0`;
const eventID = WIA.EventID.wiaEventDeviceConnected;
const deviceID = args.length === 2 ? args[1] : WIA.Miscellaneous.wiaAnyDeviceID;
if (args[0] === 'register') {
WScript.Echo('Registering event handler');
dm.RegisterPersistentEvent(command, name, title, icon, eventID, deviceID);
WScript.Quit();
} else if (args[0] === 'unregister') {
WScript.Echo('Unregistering event handler');
dm.UnregisterPersistentEvent(command, name, title, icon, eventID, deviceID);
WScript.Quit();
}
break;
case 3:
if (args[0] === 'connect') {
const deviceID = args[1].substr(12);
const device = dm.DeviceInfos(deviceID).Connect();
collectionToArray(device.Items).forEach(item => {
const img = item.Transfer();
img.SaveFile(`C:\\${item.Properties('Item Name').Value}.${img.FileExtension}`);
// Uncomment the following lines to remove the picture from the camera after transfer
for (let i = 1; i < device.Items.Count; i++) {
const item2 = device.Items(i);
if (item2.ItemID !== item.ItemID) { continue; }
try {
// some cameras don't support deleting a picture
device.Items.Remove(i);
} catch (error) {
WScript.Echo(error);
}
}
});
WScript.Quit();
}
break;
}
const usage = `
Usage:
To register, type:
${WScript.ScriptName} register [<device id>]
To unregister, type:
${WScript.ScriptName} unregister [<device id>]
Available device ids:
${collectionToArray(dm.DeviceInfos)
.map(device => `${device.DeviceID} '${device.Properties("Name").Value}'`)
.join('\n')}
`.trim();
WScript.Echo(usage);
}
// Count the number of child items available for transfer
{
const device = cd.ShowSelectDevice();
const items = device && cd.ShowSelectItems(device, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true);
const item = items && items(1);
if (item) {
const count = collectionToArray(item.Items).filter(childItem => {
const flags = childItem.Properties('Item Flags').Value as number;
return (flags & WIA.WiaItemFlag.TransferItemFlag) === WIA.WiaItemFlag.TransferItemFlag;
}).length;
WScript.Echo(`Selected device has ${count} child items that can be transferred.`);
}
}
// Use a vector object
{
const v: WIA.Vector<number | string> = new ActiveXObject('WIA.Vector');
v.Add(1);
v.Add(42);
v.Add(3);
v.Remove(1);
v.Remove(2);
WScript.Echo(`v(1) = ${v(1)}`);
v.Clear();
v.Add('This');
v.Add('is');
v.Add('Cool');
v.Remove(1);
v.Remove(2);
WScript.Echo(`v(1) = ${v(1)}`);
}
}
+196 -148
View File
@@ -2,22 +2,20 @@
// 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
// Typescript Version: 2.4
// TypeScript Version: 2.6
declare namespace WIA {
/** String versions of globally unique identifiers (GUIDs) that identify common Device and Item commands. */
// uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017)
/*const enum CommandID {
const enum CommandID {
wiaCommandChangeDocument = '{04E725B0-ACAE-11D2-A093-00C04F72DC3C}',
wiaCommandDeleteAllItems = '{E208C170-ACAD-11D2-A093-00C04F72DC3C}',
wiaCommandSynchronize = '{9B26B7B2-ACAD-11D2-A093-00C04F72DC3C}',
wiaCommandTakePicture = '{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}',
wiaCommandUnloadDocument = '{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}'
}*/
wiaCommandUnloadDocument = '{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}',
}
/** String versions of globally unique identifiers (GUIDs) that identify DeviceManager events. */
// uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017)
/*const enum EventID {
const enum EventID {
wiaEventDeviceConnected = '{A28BBADE-64B6-11D2-A231-00C04FA31809}',
wiaEventDeviceDisconnected = '{143E4E83-6497-11D2-A231-00C04FA31809}',
wiaEventItemCreated = '{4C8F4EF5-E14F-11D2-B326-00C04F68CE61}',
@@ -30,50 +28,48 @@ declare namespace WIA {
wiaEventScanImage3 = '{154E27BE-B617-4653-ACC5-0FD7BD4C65CE}',
wiaEventScanImage4 = '{A65B704A-7F3C-4447-A75D-8A26DFCA1FDF}',
wiaEventScanOCRImage = '{9D095B89-37D6-4877-AFED-62A297DC6DBE}',
wiaEventScanPrintImage = '{B441F425-8C6E-11D2-977A-0000F87A926F}'
}*/
wiaEventScanPrintImage = '{B441F425-8C6E-11D2-977A-0000F87A926F}',
}
/** String versions of globally unique identifiers (GUIDs) that indicate the file format of an image. */
// uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017)
/*const enum FormatID {
const enum FormatID {
wiaFormatBMP = '{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}',
wiaFormatGIF = '{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}',
wiaFormatJPEG = '{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}',
wiaFormatPNG = '{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}',
wiaFormatTIFF = '{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}'
}*/
wiaFormatTIFF = '{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}',
}
/** Miscellaneous string constants */
// uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017)
/*const enum Miscellaneous {
const enum Miscellaneous {
wiaAnyDeviceID = '*',
wiaIDUnknown = '{00000000-0000-0000-0000-000000000000}'
}*/
wiaIDUnknown = '{00000000-0000-0000-0000-000000000000}',
}
/**
* The WiaDeviceType enumeration specifies the type of device attached to a user's computer. Use the Type property on the DeviceInfo object or the Device
* object to obtain these values from the device.
* object to obtain these values from the device.
*/
const enum WiaDeviceType {
CameraDeviceType = 2,
ScannerDeviceType = 1,
UnspecifiedDeviceType = 0,
VideoDeviceType = 3
VideoDeviceType = 3,
}
/**
* A DeviceEvent's type is composed of bits from the WiaEventFlags enumeration. You can test a DeviceEvent's type by using the AND operation with DeviceEv
* ent.Type and a member from the WiaEventFlags enumeration.
* A DeviceEvent's type is composed of bits from the WiaEventFlags enumeration. You can test a DeviceEvent's type by using the AND operation with
* DeviceEvent.Type and a member from the WiaEventFlags enumeration.
*/
const enum WiaEventFlag {
ActionEvent = 2,
NotificationEvent = 1
NotificationEvent = 1,
}
/** The WiaImageBias enumeration helps specify what type of data the image is intended to represent. */
const enum WiaImageBias {
MaximizeQuality = 131072,
MinimizeSize = 65536
MinimizeSize = 65536,
}
/** The WiaImageIntent enumeration helps specify what type of data the image is intended to represent. */
@@ -81,12 +77,12 @@ declare namespace WIA {
ColorIntent = 1,
GrayscaleIntent = 2,
TextIntent = 4,
UnspecifiedIntent = 0
UnspecifiedIntent = 0,
}
/**
* The WiaImagePropertyType enumeration specifies the type of the value of an image property. Image properties can be found in the Properties collection o
* f an ImageFile object.
* The WiaImagePropertyType enumeration specifies the type of the value of an image property. Image properties can be found in the Properties collection
* of an ImageFile object.
*/
const enum WiaImagePropertyType {
ByteImagePropertyType = 1001,
@@ -103,12 +99,12 @@ declare namespace WIA {
VectorOfUndefinedImagePropertyType = 1100,
VectorOfUnsignedIntegersImagePropertyType = 1102,
VectorOfUnsignedLongsImagePropertyType = 1104,
VectorOfUnsignedRationalsImagePropertyType = 1106
VectorOfUnsignedRationalsImagePropertyType = 1106,
}
/**
* An Item's type is composed of bits from the WiaItemFlags enumeration. You can test an Item's type by using the AND operation with Item.Properties("Item
* Flags") and a member from the WiaItemFlags enumeration.
* An Item's type is composed of bits from the WiaItemFlags enumeration. You can test an Item's type by using the AND operation with
* Item.Properties("Item Flags") and a member from the WiaItemFlags enumeration.
*/
const enum WiaItemFlag {
AnalyzeItemFlag = 16,
@@ -129,12 +125,12 @@ declare namespace WIA {
StorageItemFlag = 4096,
TransferItemFlag = 8192,
VideoItemFlag = 65536,
VPanoramaItemFlag = 1024
VPanoramaItemFlag = 1024,
}
/**
* The WiaPropertyType enumeration specifies the type of the value of an item property. Item properties can be found in the Properties collection of a Dev
* ice or Item object.
* The WiaPropertyType enumeration specifies the type of the value of an item property. Item properties can be found in the Properties collection of a
* Device or Item object.
*/
const enum WiaPropertyType {
BooleanPropertyType = 1,
@@ -173,28 +169,31 @@ declare namespace WIA {
VectorOfUnsignedIntegersPropertyType = 104,
VectorOfUnsignedLargeIntegersPropertyType = 109,
VectorOfUnsignedLongsPropertyType = 106,
VectorOfVariantsPropertyType = 119
VectorOfVariantsPropertyType = 119,
}
/**
* The WiaSubType enumeration specifies more detail about the property value. Use the SubType property on the Property object to obtain these values for t
* he property.
* The WiaSubType enumeration specifies more detail about the property value. Use the SubType property on the Property object to obtain these values for
* the property.
*/
const enum WiaSubType {
FlagSubType = 3,
ListSubType = 2,
RangeSubType = 1,
UnspecifiedSubType = 0
UnspecifiedSubType = 0,
}
/**
* The CommonDialog control is an invisible-at-runtime control that contains all the methods that display a User Interface. A CommonDialog control can be
* created using "WIA.CommonDialog" in a call to CreateObject or by dropping a CommonDialog on a form.
* created using "WIA.CommonDialog" in a call to CreateObject or by dropping a CommonDialog on a form.
*/
interface CommonDialog {
class CommonDialog {
private constructor();
private 'WIA.CommonDialog_typekey': CommonDialog;
/**
* Displays one or more dialog boxes that enable the user to acquire an image from a hardware device for image acquisition and returns an ImageFile object
* on success, otherwise Nothing
* Displays one or more dialog boxes that enable the user to acquire an image from a hardware device for image acquisition and returns an ImageFile
* object on success, otherwise Nothing
* @param WIA.WiaDeviceType [DeviceType=0]
* @param WIA.WiaImageIntent [Intent=0]
* @param WIA.WiaImageBias [Bias=131072]
@@ -203,11 +202,11 @@ declare namespace WIA {
* @param boolean [UseCommonUI=true]
* @param boolean [CancelError=false]
*/
ShowAcquireImage(
DeviceType?: WiaDeviceType, Intent?: WiaImageIntent, Bias?: WiaImageBias, FormatID?: string, AlwaysSelectDevice?: boolean, UseCommonUI?: boolean, CancelError?: boolean): ImageFile;
ShowAcquireImage(DeviceType?: WiaDeviceType, Intent?: WiaImageIntent, Bias?: WiaImageBias, FormatID?: string, AlwaysSelectDevice?: boolean, UseCommonUI?: boolean,
CancelError?: boolean): ImageFile | null;
/** Launches the Windows Scanner and Camera Wizard and returns Nothing. Future versions may return a collection of ImageFile objects. */
ShowAcquisitionWizard(Device: Device): any;
ShowAcquisitionWizard(Device: Device): null;
/**
* Displays the properties dialog box for the specified Device
@@ -222,38 +221,41 @@ declare namespace WIA {
ShowItemProperties(Item: Item, CancelError?: boolean): void;
/** Launches the Photo Printing Wizard with the absolute path of a specific file or Vector of absolute paths to files */
ShowPhotoPrintingWizard(Files: any): void;
ShowPhotoPrintingWizard(Files: string | Vector<string>): void;
/**
* Displays a dialog box that enables the user to select a hardware device for image acquisition. Returns the selected Device object on success, otherwise
* Nothing
* Displays a dialog box that enables the user to select a hardware device for image acquisition. Returns the selected Device object on success,
* otherwise Nothing
* @param WIA.WiaDeviceType [DeviceType=0]
* @param boolean [AlwaysSelectDevice=false]
* @param boolean [CancelError=false]
*/
ShowSelectDevice(DeviceType?: WiaDeviceType, AlwaysSelectDevice?: boolean, CancelError?: boolean): Device;
ShowSelectDevice(DeviceType?: WiaDeviceType, AlwaysSelectDevice?: boolean, CancelError?: boolean): Device | null;
/**
* Displays a dialog box that enables the user to select an item for transfer from a hardware device for image acquisition. Returns the selection as an It
* ems collection on success, otherwise Nothing
* Displays a dialog box that enables the user to select an item for transfer from a hardware device for image acquisition. Returns the selection as an
* Items collection on success, otherwise Nothing
* @param WIA.WiaImageIntent [Intent=0]
* @param WIA.WiaImageBias [Bias=131072]
* @param boolean [SingleSelect=true]
* @param boolean [UseCommonUI=true]
* @param boolean [CancelError=false]
*/
ShowSelectItems(Device: Device, Intent?: WiaImageIntent, Bias?: WiaImageBias, SingleSelect?: boolean, UseCommonUI?: boolean, CancelError?: boolean): Items;
ShowSelectItems(Device: Device, Intent?: WiaImageIntent, Bias?: WiaImageBias, SingleSelect?: boolean, UseCommonUI?: boolean, CancelError?: boolean): Items | null;
/**
* Displays a progress dialog box while transferring the specified Item to the local machine. See Item.Transfer for additional information.
* @param string [FormatID='{00000000-0000-0000-0000-000000000000}']
* @param boolean [CancelError=false]
*/
ShowTransfer(Item: Item, FormatID?: string, CancelError?: boolean): any;
ShowTransfer(Item: Item, FormatID?: string, CancelError?: boolean): ImageFile;
}
/** The Device object represents an active connection to an imaging device. */
interface Device {
class Device {
private constructor();
private 'WIA.Device_typekey': Device;
/** A collection of all commands for this imaging device */
readonly Commands: DeviceCommands;
@@ -264,8 +266,8 @@ declare namespace WIA {
readonly Events: DeviceEvents;
/**
* Issues the command specified by CommandID to the imaging device. CommandIDs are device dependent. Valid CommandIDs for this Device are contained in the
* Commands collection.
* Issues the command specified by CommandID to the imaging device. CommandIDs are device dependent. Valid CommandIDs for this Device are contained in
* the Commands collection.
*/
ExecuteCommand(CommandID: string): Item;
@@ -280,13 +282,13 @@ declare namespace WIA {
/** Returns the Type of Device */
readonly Type: WiaDeviceType;
/** Returns the underlying IWiaItem interface for this Device object */
readonly WiaItem: any;
}
/** The DeviceCommand object describes a CommandID that can be used when calling ExecuteCommand on a Device or Item object. */
interface DeviceCommand {
class DeviceCommand {
private constructor();
private 'WIA.DeviceCommand_typekey': DeviceCommand;
/** Returns the commandID for this Command */
readonly CommandID: string;
@@ -298,8 +300,8 @@ declare namespace WIA {
}
/**
* The DeviceCommands object is a collection of all the supported DeviceCommands for an imaging device. See the Commands property of a Device or Item obje
* ct for more details on determining the collection of supported device commands.
* The DeviceCommands object is a collection of all the supported DeviceCommands for an imaging device. See the Commands property of a Device or Item
* object for more details on determining the collection of supported device commands.
*/
interface DeviceCommands {
/** Returns the number of members in the collection */
@@ -307,10 +309,16 @@ declare namespace WIA {
/** Returns the specified item in the collection by position */
Item(Index: number): DeviceCommand;
/** Returns the specified item in the collection by position */
(Index: number): DeviceCommand;
}
/** The DeviceEvent object describes an EventID that can be used when calling RegisterEvent or RegisterPersistentEvent on a DeviceManager object. */
interface DeviceEvent {
class DeviceEvent {
private constructor();
private 'WIA.DeviceEvent_typekey': DeviceEvent;
/** Returns the event Description */
readonly Description: string;
@@ -325,8 +333,8 @@ declare namespace WIA {
}
/**
* The DeviceEvents object is a collection of all the supported DeviceEvent for an imaging device. See the Events property of a Device object for more det
* ails on determining the collection of supported device events.
* The DeviceEvents object is a collection of all the supported DeviceEvent for an imaging device. See the Events property of a Device object for more
* details on determining the collection of supported device events.
*/
interface DeviceEvents {
/** Returns the number of members in the collection */
@@ -334,13 +342,19 @@ declare namespace WIA {
/** Returns the specified item in the collection by position */
Item(Index: number): DeviceEvent;
/** Returns the specified item in the collection by position */
(Index: number): DeviceEvent;
}
/**
* The DeviceInfo object is a container that describes the unchanging (static) properties of an imaging device that is currently connected to the computer
* .
* The DeviceInfo object is a container that describes the unchanging (static) properties of an imaging device that is currently connected to the
* computer.
*/
interface DeviceInfo {
class DeviceInfo {
private constructor();
private 'WIA.DeviceInfo_typekey': DeviceInfo;
/** Establish a connection with this device and return a Device object */
Connect(): Device;
@@ -355,59 +369,68 @@ declare namespace WIA {
}
/**
* The DeviceInfos object is a collection of all the imaging devices currently connected to the computer. See the DeviceInfos property on the DeviceManage
* r object for detail on accessing the DeviceInfos object.
* The DeviceInfos object is a collection of all the imaging devices currently connected to the computer. See the DeviceInfos property on the
* DeviceManager object for detail on accessing the DeviceInfos object.
*/
interface DeviceInfos {
/** Returns the number of members in the collection */
readonly Count: number;
/** Returns the specified item in the collection either by position or Device ID */
Item(Index: any): DeviceInfo;
Item(Index: number | string): DeviceInfo;
/** Returns the specified item in the collection either by position or Device ID */
(Index: number | string): DeviceInfo;
}
/**
* The DeviceManager control is an invisible-at-runtime control that manages the imaging devices connected to the computer. A DeviceManager control can be
* created using "WIA.DeviceManager" in a call to CreateObject or by dropping a DeviceManager on a form.
* The DeviceManager control is an invisible-at-runtime control that manages the imaging devices connected to the computer. A DeviceManager control can
* be created using "WIA.DeviceManager" in a call to CreateObject or by dropping a DeviceManager on a form.
*/
interface DeviceManager {
class DeviceManager {
private constructor();
private 'WIA.DeviceManager_typekey': DeviceManager;
/** A collection of all imaging devices connected to this computer */
readonly DeviceInfos: DeviceInfos;
/**
* Registers the specified EventID for the specified DeviceID. If DeviceID is "*" then OnEvent will be called whenever the event specified occurs for any
* device. Otherwise, OnEvent will only be called if the event specified occurs on the device specified.
* device. Otherwise, OnEvent will only be called if the event specified occurs on the device specified.
* @param string [DeviceID='*']
*/
RegisterEvent(EventID: string, DeviceID?: string): void;
/**
* Registers the specified Command to launch when the specified EventID for the specified DeviceID occurs. Command can be either a ClassID or the full pat
* h name and the appropriate command-line arguments needed to invoke the application.
* Registers the specified Command to launch when the specified EventID for the specified DeviceID occurs. Command can be either a ClassID or the full
* path name and the appropriate command-line arguments needed to invoke the application.
* @param string [DeviceID='*']
*/
RegisterPersistentEvent(Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string): void;
/**
* Unregisters the specified EventID for the specified DeviceID. UnregisterEvent should only be called for EventID and DeviceID for which you called Regis
* terEvent.
* Unregisters the specified EventID for the specified DeviceID. UnregisterEvent should only be called for EventID and DeviceID for which you called
* RegisterEvent.
* @param string [DeviceID='*']
*/
UnregisterEvent(EventID: string, DeviceID?: string): void;
/**
* Unregisters the specified Command for the specified EventID for the specified DeviceID. UnregisterPersistentEvent should only be called for the Command
* , Name, Description, Icon, EventID and DeviceID for which you called RegisterPersistentEvent.
* Unregisters the specified Command for the specified EventID for the specified DeviceID. UnregisterPersistentEvent should only be called for the
* Command, Name, Description, Icon, EventID and DeviceID for which you called RegisterPersistentEvent.
* @param string [DeviceID='*']
*/
UnregisterPersistentEvent(Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string): void;
}
/**
* The Filter object represents a unit of modification on an ImageFile. To use a Filter, add it to the Filters collection, then set the filter's propertie
* s and finally use the Apply method of the ImageProcess object to filter an ImageFile.
* The Filter object represents a unit of modification on an ImageFile. To use a Filter, add it to the Filters collection, then set the filter's
* properties and finally use the Apply method of the ImageProcess object to filter an ImageFile.
*/
interface Filter {
class Filter {
private constructor();
private 'WIA.Filter_typekey': Filter;
/** Returns a Description of what the filter does */
readonly Description: string;
@@ -422,10 +445,13 @@ declare namespace WIA {
}
/**
* The FilterInfo object is a container that describes a Filter object without requiring a Filter to be Added to the process chain. See the FilterInfos pr
* operty on the ImageProcess object for details on accessing FilterInfo objects.
* The FilterInfo object is a container that describes a Filter object without requiring a Filter to be Added to the process chain. See the FilterInfos
* property on the ImageProcess object for details on accessing FilterInfo objects.
*/
interface FilterInfo {
class FilterInfo {
private constructor();
private 'WIA.FilterInfo_typekey': FilterInfo;
/** Returns a technical Description of what the filter does and how to use it in a filter chain */
readonly Description: string;
@@ -437,15 +463,18 @@ declare namespace WIA {
}
/**
* The FilterInfos object is a collection of all the available FilterInfo objects. See the FilterInfos property on the ImageProcess object for detail on a
* ccessing the FilterInfos object.
* The FilterInfos object is a collection of all the available FilterInfo objects. See the FilterInfos property on the ImageProcess object for detail on
* accessing the FilterInfos object.
*/
interface FilterInfos {
/** Returns the number of members in the collection */
readonly Count: number;
/** Returns the specified item in the collection either by position or name */
Item(Index: any): FilterInfo;
Item(Index: number | string): FilterInfo;
/** Returns the specified item in the collection either by position or name */
(Index: number | string): FilterInfo;
}
/** The Filters object is a collection of the Filters that will be applied to an ImageFile when you call the Apply method on the ImageProcess object. */
@@ -464,11 +493,14 @@ declare namespace WIA {
/** Removes the designated filter */
Remove(Index: number): void;
/** Returns the specified item in the collection by position or FilterID */
(Index: number): Filter;
}
/**
* The Formats object is a collection of supported FormatIDs that you can use when calling Transfer on an Item object or ShowTransfer on a CommonDialog ob
* ject for this Item.
* The Formats object is a collection of supported FormatIDs that you can use when calling Transfer on an Item object or ShowTransfer on a CommonDialog
* object for this Item.
*/
interface Formats {
/** Returns the number of members in the collection */
@@ -476,13 +508,19 @@ declare namespace WIA {
/** Returns the specified item in the collection by position */
Item(Index: number): string;
/** Returns the specified item in the collection by position */
(Index: number): string;
}
/**
* The ImageFile object is a container for images transferred to your computer when you call Transfer or ShowTransfer. It also supports image files throug
* h LoadFile. An ImageFile object can be created using "WIA.ImageFile" in a call to CreateObject.
* The ImageFile object is a container for images transferred to your computer when you call Transfer or ShowTransfer. It also supports image files
* through LoadFile. An ImageFile object can be created using "WIA.ImageFile" in a call to CreateObject.
*/
interface ImageFile {
class ImageFile {
private constructor();
private 'WIA.ImageFile_typekey': ImageFile;
/** Returns/Sets the current frame in the image */
ActiveFrame: number;
@@ -539,7 +577,10 @@ declare namespace WIA {
}
/** The ImageProcess object manages the filter chain. An ImageProcess object can be created using "WIA.ImageProcess" in a call to CreateObject. */
interface ImageProcess {
class ImageProcess {
private constructor();
private 'WIA.ImageProcess_typekey': ImageProcess;
/** Takes the specified ImageFile and returns the new ImageFile with all the filters applied on success */
Apply(Source: ImageFile): ImageFile;
@@ -551,10 +592,13 @@ declare namespace WIA {
}
/**
* The Item object is a container for an item on an imaging device object. See the Items property on the Device or Item object for details on accessing It
* em objects.
* The Item object is a container for an item on an imaging device object. See the Items property on the Device or Item object for details on accessing
* Item objects.
*/
interface Item {
class Item {
private constructor();
private 'WIA.Item_typekey': Item;
/** A collection of all commands for this item */
readonly Commands: DeviceCommands;
@@ -574,17 +618,15 @@ declare namespace WIA {
readonly Properties: Properties;
/**
* Returns an ImageFile object, in this version, in the format specified in FormatID if supported, otherwise using the preferred format for this imaging d
* evice. Future versions may return a collection of ImageFile objects.
* Returns an ImageFile object, in this version, in the format specified in FormatID if supported, otherwise using the preferred format for this imaging
* device. Future versions may return a collection of ImageFile objects.
* @param string [FormatID='{00000000-0000-0000-0000-000000000000}']
*/
Transfer(FormatID?: string): any;
/** Returns the underlying IWiaItem interface for this Item object */
readonly WiaItem: any;
Transfer(FormatID?: string): ImageFile;
}
/** The Items object contains a collection of Item objects. See the Items property on the Device or Item object for details on accessing the Items object. */
// tslint:disable-next-line interface-name
interface Items {
/** Adds a new Item with the specified Name and Flags. The Flags value is created by using the OR operation with members of the WiaItemFlags enumeration. */
Add(Name: string, Flags: number): void;
@@ -597,28 +639,37 @@ declare namespace WIA {
/** Removes the designated Item */
Remove(Index: number): void;
/** Returns the specified item in the collection by position */
(Index: number): Item;
}
/**
* The Properties object is a collection of all the Property objects associated with a given Device, DeviceInfo, Filter, ImageFile or Item object. See the
* Properties property on any of these objects for detail on accessing the Properties object.
* The Properties object is a collection of all the Property objects associated with a given Device, DeviceInfo, Filter, ImageFile or Item object. See
* the Properties property on any of these objects for detail on accessing the Properties object.
*/
interface Properties {
/** Returns the number of members in the collection */
readonly Count: number;
/** Indicates whether the specified Property exists in the collection */
Exists(Index: any): boolean;
Exists(Index: number | string): boolean;
/** Returns the specified item in the collection either by position or name. */
Item(Index: any): Property;
Item(Index: number | string): Property;
/** Returns the specified item in the collection either by position or name. */
(Index: number | string): Property;
}
/**
* The Property object is a container for a property associated with a Device, DeviceInfo, Filter, ImageFile or Item object. See the Properties property o
* n any of these objects for details on accessing Property objects.
* The Property object is a container for a property associated with a Device, DeviceInfo, Filter, ImageFile or Item object. See the Properties property
* on any of these objects for details on accessing Property objects.
*/
interface Property {
class Property {
private constructor();
private 'WIA.Property_typekey': Property;
/** Indicates whether the Property Value is read only */
readonly IsReadOnly: boolean;
@@ -657,10 +708,13 @@ declare namespace WIA {
}
/**
* The Rational object is a container for the rational values found in Exif tags. It is a supported element type of the Vector object and may be created u
* sing "WIA.Rational" in a call to CreateObject.
* The Rational object is a container for the rational values found in Exif tags. It is a supported element type of the Vector object and may be created
* using "WIA.Rational" in a call to CreateObject.
*/
interface Rational {
class Rational {
private constructor();
private 'WIA.Rational_typekey': Rational;
/** Returns/Sets the Rational Value Denominator */
Denominator: number;
@@ -672,19 +726,19 @@ declare namespace WIA {
}
/**
* The Vector object is a collection of values of the same type. It is used throughout the library in many different ways. The Vector object may be create
* d using "WIA.Vector" in a call to CreateObject.
* The Vector object is a collection of values of the same type. It is used throughout the library in many different ways. The Vector object may be
* created using "WIA.Vector" in a call to CreateObject.
*/
interface Vector {
interface Vector<TItem = any> {
/**
* If Index is not zero, Inserts a new element into the Vector collection before the specified Index. If Index is zero, Appends a new element to the Vecto
* r collection.
* If Index is not zero, Inserts a new element into the Vector collection before the specified Index. If Index is zero, Appends a new element to the
* Vector collection.
* @param number [Index=0]
*/
Add(Value: any, Index?: number): void;
Add(Value: TItem, Index?: number): void;
/** Returns/Sets the Vector of Bytes as an array of bytes */
BinaryData: any;
BinaryData: SafeArray;
/** Removes all elements. */
Clear(): void;
@@ -696,30 +750,30 @@ declare namespace WIA {
Date: VarDate;
/**
* Used to get the Thumbnail property of an ImageFile which is an image file, The thumbnail property of an Item which is RGB data, or creating an ImageFil
* e from raw ARGB data. Returns an ImageFile object on success. See the Picture method for more details.
* Used to get the Thumbnail property of an ImageFile which is an image file, The thumbnail property of an Item which is RGB data, or creating an
* ImageFile from raw ARGB data. Returns an ImageFile object on success. See the Picture method for more details.
* @param number [Width=0]
* @param number [Height=0]
*/
ImageFile(Width?: number, Height?: number): ImageFile;
/** Returns/Sets the specified item in the vector by position */
Item(Index: number): any;
/** Returns the specified item in the vector by position */
Item(Index: number): TItem;
/**
* If the Vector of Bytes contains an image file, then Width and Height are ignored. Otherwise a Vector of Bytes must be RGB data and a Vector of Longs mu
* st be ARGB data. Returns a Picture object on success. See the ImageFile method for more details.
* If the Vector of Bytes contains an image file, then Width and Height are ignored. Otherwise a Vector of Bytes must be RGB data and a Vector of Longs
* must be ARGB data. Returns a Picture object on success. See the ImageFile method for more details.
* @param number [Width=0]
* @param number [Height=0]
*/
Picture(Width?: number, Height?: number): any;
/** Removes the designated element and returns it if successful */
Remove(Index: number): any;
Remove(Index: number): TItem | null;
/**
* Stores the string Value into the Vector of Bytes including the NULL terminator. Value may be truncated unless Resizable is True. The string will be sto
* red as an ANSI string unless Unicode is True, in which case it will be stored as a Unicode string.
* Stores the string Value into the Vector of Bytes including the NULL terminator. Value may be truncated unless Resizable is True. The string will be
* stored as an ANSI string unless Unicode is True, in which case it will be stored as a Unicode string.
* @param boolean [Resizable=true]
* @param boolean [Unicode=true]
*/
@@ -730,30 +784,24 @@ declare namespace WIA {
* @param boolean [Unicode=true]
*/
String(Unicode?: boolean): string;
/** Returns the specified item in the vector by position */
(Index: number): TItem;
}
}
interface ActiveXObject {
new<K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
on(obj: WIA.DeviceManager, event: 'OnEvent', argNames: ['EventID', 'DeviceID', 'ItemID'], handler: (
this: WIA.DeviceManager, parameter: {
EventID: string, DeviceID: string, ItemID: string}) => void): void;
set(obj: WIA.Vector, propertyName: 'Item', parameterTypes: [number], newValue: any): void;
new(progid: 'WIA.CommonDialog'): WIA.CommonDialog;
new(progid: 'WIA.DeviceManager'): WIA.DeviceManager;
new(progid: 'WIA.ImageFile'): WIA.ImageFile;
new(progid: 'WIA.ImageProcess'): WIA.ImageProcess;
new(progid: 'WIA.Rational'): WIA.Rational;
new(progid: 'WIA.Vector'): WIA.Vector;
this: WIA.DeviceManager, parameter: { readonly EventID: string, readonly DeviceID: string, readonly ItemID: string }) => void): void;
set<TItem>(obj: WIA.Vector<TItem>, propertyName: 'Item', parameterTypes: [number], newValue: TItem): void;
}
interface EnumeratorConstructor {
new(col: WIA.DeviceCommands): WIA.DeviceCommand;
new(col: WIA.DeviceEvents): WIA.DeviceEvent;
new(col: WIA.DeviceInfos): WIA.DeviceInfo;
new(col: WIA.FilterInfos): WIA.FilterInfo;
new(col: WIA.Filters): WIA.Filter;
new(col: WIA.Formats): string;
new(col: WIA.Items): WIA.Item;
new(col: WIA.Properties): WIA.Property;
new(col: WIA.Vector): any;
interface ActiveXObjectNameMap {
'WIA.CommonDialog': WIA.CommonDialog;
'WIA.DeviceManager': WIA.DeviceManager;
'WIA.ImageFile': WIA.ImageFile;
'WIA.ImageProcess': WIA.ImageProcess;
'WIA.Rational': WIA.Rational;
'WIA.Vector': WIA.Vector;
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"rules":{
"no-const-enum": false
}
}
+12 -40
View File
@@ -7,16 +7,15 @@ declare namespace adone {
export function identity<T>(x: T): T;
export function truly(): true;
export function falsely(): false;
export const ok: "OK";
export const bad: "BAD";
export const exts: [".js", ".tjs", ".ajs"];
export const ok: "ok";
export const bad: "bad";
export function log(...args: any[]): void;
export function fatal(...args: any[]): void;
export function error(...args: any[]): void;
export function warn(...args: any[]): void;
export function info(...args: any[]): void;
export function debug(...args: any[]): void;
export function trace(...args: any[]): void;
export function logFatal(...args: any[]): void;
export function logError(...args: any[]): void;
export function logWarn(...args: any[]): void;
export function logInfo(...args: any[]): void;
export function logDebug(...args: any[]): void;
export function logTrace(...args: any[]): void;
export function o(...props: any[]): object;
export const Date: typeof global.Date;
export const hrtime: typeof global.process.hrtime;
@@ -76,35 +75,9 @@ declare namespace adone {
set(Class: object, tag: string): void;
has(obj: object, tag: string): boolean;
define(tag: string, predicate?: string): void;
SUBSYSTEM: symbol;
APPLICATION: symbol;
TRANSFORM: symbol;
CORE_STREAM: symbol;
LOGGER: symbol;
LONG: symbol;
BIGNUMBER: symbol;
EXBUFFER: symbol;
EXDATE: symbol;
CONFIGURATION: symbol;
GENESIS_NETRON: symbol;
GENESIS_PEER: symbol;
NETRON: symbol;
NETRON_PEER: symbol;
NETRON_ADAPTER: symbol;
NETRON_DEFINITION: symbol;
NETRON_DEFINITIONS: symbol;
NETRON_REFERENCE: symbol;
NETRON_INTERFACE: symbol;
NETRON_STUB: symbol;
NETRON_REMOTESTUB: symbol;
NETRON_STREAM: symbol;
FAST_STREAM: symbol;
FAST_FS_STREAM: symbol;
FAST_FS_MAP_STREAM: symbol;
}
}
export const tag: I.Tag;
export function bind(libName: string): object;
export function getAssetAbsolutePath(relPath: string): string;
export function loadAsset(relPath: string): string | Buffer;
export function require(path: string): object;
@@ -122,11 +95,10 @@ declare namespace adone {
export const runtime: I.Runtime;
export const homePath: string;
export const rootPath: string;
export const etcPath: string;
export const config: object;
export const emptyBuffer: Buffer;
export const ROOT_PATH: string;
export const ETC_PATH: string;
export const configuration: object;
export const EMPTY_BUFFER: Buffer;
export const assert: assertion.I.AssertFunction;
export const expect: assertion.I.ExpectFunction;
+1 -1
View File
@@ -1019,7 +1019,7 @@ declare namespace adone {
}
}
class AssertionError extends exception.Exception {
class AssertionError extends error.Exception {
constructor(message?: string, props?: object, ssf?: object)
}
+2
View File
@@ -27,5 +27,7 @@ declare namespace adone.collection {
* Removes and returns an element from the beginning
*/
pop(): T | undefined;
static from<T>(iterable: Iterable<T>, length?: number): Queue<T>;
}
}
+1 -1
View File
@@ -582,7 +582,7 @@ declare namespace adone {
/**
* Represents a YAML exception
*/
class Exception extends adone.exception.Exception {
class Exception extends adone.error.Exception {
reason: string;
mark: Mark;
@@ -1,5 +1,5 @@
declare namespace adone {
namespace exception {
namespace error {
class Exception extends Error {
constructor(message?: string | Error, captureStackTrace?: boolean);
}
+10
View File
@@ -0,0 +1,10 @@
/// <reference path="./json.d.ts" />
/// <reference path="./size.d.ts" />
/// <reference path="./table.d.ts" />
/// <reference path="./time.d.ts" />
declare namespace adone {
namespace pretty {
//
}
}
+16
View File
@@ -0,0 +1,16 @@
declare namespace adone.pretty {
namespace I {
interface JSONOptions {
emptyArrayMsg?: string;
keysColor?: string;
dashColor?: string;
numberColor?: string;
stringColor?: string;
defaultIndentation?: number;
noColor?: boolean;
noAlign?: boolean;
}
}
function json(data: any, options?: I.JSONOptions, indentation?: number): string;
}
+3
View File
@@ -0,0 +1,3 @@
declare namespace adone.pretty {
function size(num: number, space?: string): string;
}
+38
View File
@@ -0,0 +1,38 @@
declare namespace adone.pretty {
namespace I {
interface TableColumn {
id: string;
header?: string;
align?: "right" | "center" | "left";
width?: string | number;
maxWidth?: number | string;
wordwrap?: "soft" | "hard" | adone.text.I.WordWrapOptions;
handle?: (item: object) => string;
format?: string | ((val: any, item: object) => string);
style?: string | ((val: any, str: string) => string);
}
type TableModel = TableColumn[];
interface TableStyle {
"padding-left"?: number;
"padding-right"?: number;
head?: string[];
broder?: string[];
compact?: boolean;
}
interface TableOptions {
model: TableModel;
noHeader?: boolean;
borderless?: boolean;
style?: TableStyle;
width?: number | string;
countAnsiEscapeCodes?: boolean;
}
type TableData = Array<{ [id: string]: any }>;
}
function table(data: I.TableData, options: I.TableOptions): string;
}
+11
View File
@@ -0,0 +1,11 @@
declare namespace adone.pretty {
namespace I {
interface TimeOptions {
msDecimalDigits?: number;
secDecimalDigits?: number;
verbose?: boolean;
compact?: boolean;
}
}
function time(ms: number, options?: I.TimeOptions): string;
}
-1
View File
@@ -1,4 +1,3 @@
/// <reference path="./pretties.d.ts" />
/// <reference path="./spinners.d.ts" />
/// <reference path="./table.d.ts" />
/// <reference path="./unicode.d.ts" />
-55
View File
@@ -1,55 +0,0 @@
declare namespace adone.text {
namespace pretty {
namespace I {
interface JSONOptions {
emptyArrayMsg?: string;
keysColor?: string;
dashColor?: string;
numberColor?: string;
stringColor?: string;
defaultIndentation?: number;
noColor?: boolean;
noAlign?: boolean;
}
}
function json(data: any, options?: I.JSONOptions, indentation?: number): string;
namespace I {
interface TableColumn {
id: string;
header?: string;
align?: "right" | "center" | "left";
width?: string | number;
maxWidth?: number | string;
wordwrap?: "soft" | "hard" | adone.text.I.WordWrapOptions;
handle?: (item: object) => string;
format?: string | ((val: any, item: object) => string);
style?: string | ((val: any, str: string) => string);
}
type TableModel = TableColumn[];
interface TableStyle {
"padding-left"?: number;
"padding-right"?: number;
head?: string[];
broder?: string[];
compact?: boolean;
}
interface TableOptions {
model: TableModel;
noHeader?: boolean;
borderless?: boolean;
style?: TableStyle;
width?: number | string;
countAnsiEscapeCodes?: boolean;
}
type TableData = Array<{ [id: string]: any }>;
}
function table(data: I.TableData, options: I.TableOptions): string;
}
}
+1 -12
View File
@@ -86,17 +86,6 @@ declare namespace adone {
function invertObject(source: object, options?: I.KeysOptions): object;
namespace I {
interface HumanizeTimeOptions {
msDecimalDigits?: number;
secDecimalDigits?: number;
verbose?: boolean;
compact?: boolean;
}
}
function humanizeTime(ms: number, options?: I.HumanizeTimeOptions): string;
function humanizeSize(num: number, space?: string): string;
function parseSize(str: string | number): number | null;
namespace I {
@@ -547,7 +536,7 @@ declare namespace adone {
namespace throttle {
namespace I {
interface Options {
max?: number;
concurrency?: number;
interval?: number;
ordered?: boolean;
waitForReturn?: boolean;
+204
View File
@@ -0,0 +1,204 @@
declare namespace adone {
namespace vault {
namespace I {
interface VaultConstructorOptions {
// TODO: leveldb options
location: string;
ValuableClass?: object;
}
interface VaultClearOptions {
hosts?: boolean;
tags?: boolean;
}
interface VaultToJSONOptions {
valuable?: ValuableToJSONOptions;
includeStats?: boolean;
}
interface ValuableToJSONOptions {
includeId?: boolean;
includeEntryId?: boolean;
entriesAsArray?: boolean;
tags?: "normal" | "onlyName" | "onlyId" | "none";
}
interface VaultJSONStats {
location: string;
created: number;
updated: number;
}
}
class Vault<T extends Valuable = Valuable> {
constructor(options: I.VaultConstructorOptions);
open(): Promise<void>;
close(): Promise<void>;
location(): string;
create(name: string, tags?: string[]): Promise<T>;
get(name: string): Promise<T>;
release(name: string): void;
delete(name: string): Promise<void>;
clear(options?: I.VaultClearOptions): Promise<number>;
has(name: string): boolean;
keys(): string[];
values(): Promise<any[]>;
entries(): Promise<{ [key: string]: any }>;
toJSON(options: I.VaultToJSONOptions & { valuable: object, includeStats: true }): Promise<{
valuables: object[],
stats: I.VaultJSONStats
}>;
toJSON(options: I.VaultToJSONOptions & { valuable: object }): Promise<{
valuables: object[]
}>;
toJSON(options: I.VaultToJSONOptions & { includeStats: true }): Promise<{
stats: I.VaultJSONStats
}>;
toJSON(): {};
addTag(tag: string, vid?: number): Promise<number| null>;
deleteTag(tag: string): Promise<boolean>;
tags(ids?: number[], opts?: { privateProps?: boolean }): object[];
tagNames(ids?: number[]): string[];
getNotes(): string;
setNotes(notes: string): Promise<void>;
}
namespace I {
interface ValueableEntriesOptions {
entriesAsArray?: boolean;
includeEntryId?: boolean;
}
interface ValuableEntry {
name: string;
value: any;
type: string;
}
interface ValuableClearOptions {
includeNotes?: boolean;
includeTags?: boolean;
}
interface ValuableJSON {
name: string;
notes: string;
entries: I.ValuableEntry[];
}
}
class Valuable {
constructor(vaule: Vault, id: number, metaData: object, tags: object[]);
name(): string;
internalId(): number;
getNotes(): string;
setNotes(notes: string): Promise<void>;
set(name: string, value: any, type?: string): Promise<number>;
setMulti(entries: object): Promise<void>;
get(name: string): Promise<any>;
type(name: string): any;
has(name: string): boolean;
keys(): string[];
entries(opts: I.ValueableEntriesOptions & { entriesAsArray: true }): Promise<I.ValuableEntry[]>;
entries(opts: I.ValueableEntriesOptions & { entriesAsArray: true, includeEntryId: true }): Promise<Array<I.ValuableEntry & { id: number }>>;
entries(opts?: I.ValueableEntriesOptions): Promise<object>;
delete(name: string): Promise<number>;
clear(opts?: I.ValuableClearOptions): Promise<number>;
toJSON(opts?: I.ValuableToJSONOptions): object; // TODO
fromJSON(json: object): Promise<number>;
addTag(tag: string): Promise<void>;
hasTag(tag: string): boolean;
deleteTag(tag: string): Promise<boolean>;
deleteAllTags(): Promise<void>;
tags(): object[];
}
function open(options?: I.VaultConstructorOptions): Promise<Vault>;
namespace I {
interface SlicedValuable {
name(): string;
internalId(): number;
getNotes(): string;
setNotes(notes: string): Promise<number>;
set(name: string, value: any, type?: string): Promise<number>;
setMulti(entries: object): Promise<void>;
get(name: string): Promise<any>;
type(name: string): any;
has(name: string): boolean;
keys(): string[];
entries(opts: I.ValueableEntriesOptions & { entriesAsArray: true }): Promise<I.ValuableEntry[]>;
entries(opts: I.ValueableEntriesOptions & { entriesAsArray: true, includeEntryId: true }): Promise<Array<I.ValuableEntry & { id: number }>>;
entries(opts?: I.ValueableEntriesOptions): Promise<object>;
delete(name: string): Promise<number>;
toJSON(opts?: I.ValuableToJSONOptions): object;
fromJSON(json: object): Promise<number>;
addTag(tag: string): Promise<void>;
hasTag(tag: string): boolean;
deleteTag(tag: string): Promise<boolean>;
deleteAllTags(): Promise<void>;
tags(): object[];
}
}
function slice(valuable: Valuable, prefix: string | string[], separator?: string): I.SlicedValuable;
}
}
+3 -1
View File
@@ -14,7 +14,7 @@
/// <reference path="./glosses/data.d.ts" />
/// <reference path="./glosses/datetime.d.ts" />
/// <reference path="./glosses/events.d.ts" />
/// <reference path="./glosses/exceptions.d.ts" />
/// <reference path="./glosses/errors.d.ts" />
/// <reference path="./glosses/fake.d.ts" />
/// <reference path="./glosses/fast.d.ts" />
/// <reference path="./glosses/fs.d.ts" />
@@ -22,6 +22,7 @@
/// <reference path="./glosses/math/index.d.ts" />
/// <reference path="./glosses/meta.d.ts" />
/// <reference path="./glosses/net/index.d.ts" />
/// <reference path="./glosses/pretty/index.d.ts" />
/// <reference path="./glosses/promise.d.ts" />
/// <reference path="./glosses/regex.d.ts" />
/// <reference path="./glosses/semver.d.ts" />
@@ -33,6 +34,7 @@
/// <reference path="./glosses/templating/index.d.ts" />
/// <reference path="./glosses/text/index.d.ts" />
/// <reference path="./glosses/utils.d.ts" />
/// <reference path="./glosses/vault.d.ts" />
declare const _adone: typeof adone;
+3 -3
View File
@@ -3,9 +3,9 @@ namespace assertionTests {
namespace assertionInterface {
namespace exception {
const a: adone.exception.Exception = new assertion.AssertionError();
const b: adone.exception.Exception = new assertion.AssertionError("hello");
const c: adone.exception.Exception = new assertion.AssertionError("hello", { actual: 2, expected: 3 }, () => {});
const a: adone.error.Exception = new assertion.AssertionError();
const b: adone.error.Exception = new assertion.AssertionError("hello");
const c: adone.error.Exception = new assertion.AssertionError("hello", { actual: 2, expected: 3 }, () => {});
}
namespace config {
@@ -14,4 +14,15 @@ namespace adoneTests.collection.Queue {
{ const a: boolean = new Queue().full; }
{ const a: number = new Queue().length; }
{ const a: boolean = new Queue().empty; }
{
const q = Queue.from([1, 2, 3]);
const a: number | undefined = q.pop();
}
{
const q = Queue.from((function*() {
yield 42;
})());
const a: number | undefined = q.pop();
}
}
+36
View File
@@ -0,0 +1,36 @@
namespace ErrorsTests {
{ const a: Error = new adone.error.Exception(); }
{ const a: Error = new adone.error.Exception("message"); }
{ const a: Error = new adone.error.Exception(new Error()); }
{ const a: Error = new adone.error.Exception(new Error(), true); }
{ const a: adone.error.Exception = new adone.error.Runtime(); }
{ const a: adone.error.Exception = new adone.error.IncompleteBufferError(); }
{ const a: adone.error.Exception = new adone.error.NotImplemented(); }
{ const a: adone.error.Exception = new adone.error.IllegalState(); }
{ const a: adone.error.Exception = new adone.error.NotValid(); }
{ const a: adone.error.Exception = new adone.error.Unknown(); }
{ const a: adone.error.Exception = new adone.error.NotExists(); }
{ const a: adone.error.Exception = new adone.error.Exists(); }
{ const a: adone.error.Exception = new adone.error.Empty(); }
{ const a: adone.error.Exception = new adone.error.InvalidAccess(); }
{ const a: adone.error.Exception = new adone.error.NotSupported(); }
{ const a: adone.error.Exception = new adone.error.InvalidArgument(); }
{ const a: adone.error.Exception = new adone.error.InvalidNumberOfArguments(); }
{ const a: adone.error.Exception = new adone.error.NotFound(); }
{ const a: adone.error.Exception = new adone.error.Timeout(); }
{ const a: adone.error.Exception = new adone.error.Incorrect(); }
{ const a: adone.error.Exception = new adone.error.NotAllowed(); }
{ const a: adone.error.Exception = new adone.error.LimitExceeded(); }
{ const a: adone.error.Exception = new adone.error.Encoding(); }
{ const a: adone.error.Exception = new adone.error.Network(); }
{ const a: adone.error.Exception = new adone.error.Bind(); }
{ const a: adone.error.Exception = new adone.error.Connect(); }
{ const a: adone.error.Exception = new adone.error.Database(); }
{ const a: adone.error.Exception = new adone.error.DatabaseInitialization(); }
{ const a: adone.error.Exception = new adone.error.DatabaseOpen(); }
{ const a: adone.error.Exception = new adone.error.DatabaseRead(); }
{ const a: adone.error.Exception = new adone.error.DatabaseWrite(); }
{ const a: adone.error.Exception = new adone.error.NetronIllegalState(); }
{ const a: adone.error.Exception = new adone.error.NetronPeerDisconnected(); }
{ const a: adone.error.Exception = new adone.error.NetronTimeout(); }
}
-36
View File
@@ -1,36 +0,0 @@
namespace ExcetpionsTests {
{ const a: Error = new adone.exception.Exception(); }
{ const a: Error = new adone.exception.Exception("message"); }
{ const a: Error = new adone.exception.Exception(new Error()); }
{ const a: Error = new adone.exception.Exception(new Error(), true); }
{ const a: adone.exception.Exception = new adone.exception.Runtime(); }
{ const a: adone.exception.Exception = new adone.exception.IncompleteBufferError(); }
{ const a: adone.exception.Exception = new adone.exception.NotImplemented(); }
{ const a: adone.exception.Exception = new adone.exception.IllegalState(); }
{ const a: adone.exception.Exception = new adone.exception.NotValid(); }
{ const a: adone.exception.Exception = new adone.exception.Unknown(); }
{ const a: adone.exception.Exception = new adone.exception.NotExists(); }
{ const a: adone.exception.Exception = new adone.exception.Exists(); }
{ const a: adone.exception.Exception = new adone.exception.Empty(); }
{ const a: adone.exception.Exception = new adone.exception.InvalidAccess(); }
{ const a: adone.exception.Exception = new adone.exception.NotSupported(); }
{ const a: adone.exception.Exception = new adone.exception.InvalidArgument(); }
{ const a: adone.exception.Exception = new adone.exception.InvalidNumberOfArguments(); }
{ const a: adone.exception.Exception = new adone.exception.NotFound(); }
{ const a: adone.exception.Exception = new adone.exception.Timeout(); }
{ const a: adone.exception.Exception = new adone.exception.Incorrect(); }
{ const a: adone.exception.Exception = new adone.exception.NotAllowed(); }
{ const a: adone.exception.Exception = new adone.exception.LimitExceeded(); }
{ const a: adone.exception.Exception = new adone.exception.Encoding(); }
{ const a: adone.exception.Exception = new adone.exception.Network(); }
{ const a: adone.exception.Exception = new adone.exception.Bind(); }
{ const a: adone.exception.Exception = new adone.exception.Connect(); }
{ const a: adone.exception.Exception = new adone.exception.Database(); }
{ const a: adone.exception.Exception = new adone.exception.DatabaseInitialization(); }
{ const a: adone.exception.Exception = new adone.exception.DatabaseOpen(); }
{ const a: adone.exception.Exception = new adone.exception.DatabaseRead(); }
{ const a: adone.exception.Exception = new adone.exception.DatabaseWrite(); }
{ const a: adone.exception.Exception = new adone.exception.NetronIllegalState(); }
{ const a: adone.exception.Exception = new adone.exception.NetronPeerDisconnected(); }
{ const a: adone.exception.Exception = new adone.exception.NetronTimeout(); }
}
+19
View File
@@ -0,0 +1,19 @@
namespace adoneTests.pretty.json {
const {
json
} = adone.pretty;
let str: string;
str = json({});
str = json({}, {});
str = json({}, {}, 1);
str = json({}, { dashColor: "green" });
str = json({}, { defaultIndentation: 10 });
str = json({}, { emptyArrayMsg: "asdas" });
str = json({}, { keysColor: "green" });
str = json({}, { noAlign: true });
str = json({}, { noColor: true });
str = json({}, { numberColor: "green" });
str = json({}, { stringColor: "green" });
}
+12
View File
@@ -0,0 +1,12 @@
namespace adoneTests.pretty.size {
const {
pretty: {
size
}
} = adone;
let str: string;
str = size(12345);
str = size(12345, "");
}
+177
View File
@@ -0,0 +1,177 @@
namespace adoneTests.pretty.table {
const {
table
} = adone.pretty;
let str: string;
str = table([], {
model: []
});
str = table([], {
borderless: true,
model: []
});
str = table([], {
countAnsiEscapeCodes: true,
model: []
});
str = table([], {
noHeader: true,
model: []
});
str = table([], {
style: {
"padding-left": 1
},
model: []
});
str = table([], {
style: {
"padding-right": 1
},
model: []
});
str = table([], {
style: {
broder: ["a"]
},
model: []
});
str = table([], {
style: {
compact: true
},
model: []
});
str = table([], {
style: {
head: ["a"]
},
model: []
});
str = table([], {
width: 100,
model: []
});
str = table([], {
width: "100%",
model: []
});
str = table([], {
model: [{
id: "ads",
align: "center"
}]
});
str = table([], {
model: [{
id: "ads",
format: "%s"
}]
});
str = table([], {
model: [{
id: "ads",
format(val: any, item: object) {
return "2";
}
}]
});
str = table([], {
model: [{
id: "ads",
handle(item: object) {
return "a";
}
}]
});
str = table([], {
model: [{
id: "ads",
header: "he"
}]
});
str = table([], {
model: [{
id: "ads",
maxWidth: "100%"
}]
});
str = table([], {
model: [{
id: "ads",
maxWidth: 100
}]
});
str = table([], {
model: [{
id: "ads",
style: "asd"
}]
});
str = table([], {
model: [{
id: "ads",
style(val: any, str: string) {
return "1";
}
}]
});
str = table([], {
model: [{
id: "ads",
width: 100
}]
});
str = table([], {
model: [{
id: "ads",
width: "100%"
}]
});
str = table([], {
model: [{
id: "ads",
wordwrap: "soft"
}]
});
str = table([], {
model: [{
id: "ads",
wordwrap: "hard"
}]
});
str = table([], {
model: [{
id: "ads",
wordwrap: {
countAnsiEscapeCodes: true
}
}]
});
str = table([], {
model: [{
id: "ads",
wordwrap: {
join: true
}
}]
});
str = table([], {
model: [{
id: "ads",
wordwrap: {
mode: "soft"
}
}]
});
str = table([], {
model: [{
id: "ads",
wordwrap: {
mode: "hard"
}
}]
});
}
+14
View File
@@ -0,0 +1,14 @@
namespace adoneTests.pretty.time {
const {
time
} = adone.pretty;
let str: string;
str = time(12345);
str = time(12345, {});
str = time(12345, { compact: true });
str = time(12345, { msDecimalDigits: 2 });
str = time(12345, { secDecimalDigits: 2 });
str = time(12345, { verbose: true });
}
-203
View File
@@ -1,203 +0,0 @@
namespace adoneTests.text.pretty {
const {
text: {
pretty
}
} = adone;
let str: string;
namespace json {
const {
json
} = pretty;
str = json({});
str = json({}, {});
str = json({}, {}, 1);
str = json({}, { dashColor: "green" });
str = json({}, { defaultIndentation: 10 });
str = json({}, { emptyArrayMsg: "asdas" });
str = json({}, { keysColor: "green" });
str = json({}, { noAlign: true });
str = json({}, { noColor: true });
str = json({}, { numberColor: "green" });
str = json({}, { stringColor: "green" });
}
namespace table {
const {
table
} = pretty;
str = table([], {
model: []
});
str = table([], {
borderless: true,
model: []
});
str = table([], {
countAnsiEscapeCodes: true,
model: []
});
str = table([], {
noHeader: true,
model: []
});
str = table([], {
style: {
"padding-left": 1
},
model: []
});
str = table([], {
style: {
"padding-right": 1
},
model: []
});
str = table([], {
style: {
broder: ["a"]
},
model: []
});
str = table([], {
style: {
compact: true
},
model: []
});
str = table([], {
style: {
head: ["a"]
},
model: []
});
str = table([], {
width: 100,
model: []
});
str = table([], {
width: "100%",
model: []
});
str = table([], {
model: [{
id: "ads",
align: "center"
}]
});
str = table([], {
model: [{
id: "ads",
format: "%s"
}]
});
str = table([], {
model: [{
id: "ads",
format(val: any, item: object) {
return "2";
}
}]
});
str = table([], {
model: [{
id: "ads",
handle(item: object) {
return "a";
}
}]
});
str = table([], {
model: [{
id: "ads",
header: "he"
}]
});
str = table([], {
model: [{
id: "ads",
maxWidth: "100%"
}]
});
str = table([], {
model: [{
id: "ads",
maxWidth: 100
}]
});
str = table([], {
model: [{
id: "ads",
style: "asd"
}]
});
str = table([], {
model: [{
id: "ads",
style(val: any, str: string) {
return "1";
}
}]
});
str = table([], {
model: [{
id: "ads",
width: 100
}]
});
str = table([], {
model: [{
id: "ads",
width: "100%"
}]
});
str = table([], {
model: [{
id: "ads",
wordwrap: "soft"
}]
});
str = table([], {
model: [{
id: "ads",
wordwrap: "hard"
}]
});
str = table([], {
model: [{
id: "ads",
wordwrap: {
countAnsiEscapeCodes: true
}
}]
});
str = table([], {
model: [{
id: "ads",
wordwrap: {
join: true
}
}]
});
str = table([], {
model: [{
id: "ads",
wordwrap: {
mode: "soft"
}
}]
});
str = table([], {
model: [{
id: "ads",
wordwrap: {
mode: "hard"
}
}]
});
}
}
+1 -15
View File
@@ -195,20 +195,6 @@ namespace utilTests {
const e: object = util.invertObject({}, { onlyEnumerable: true });
}
namespace humanizeTime {
const a: string = util.humanizeTime(12345);
const b: string = util.humanizeTime(12345, {});
const c: string = util.humanizeTime(12345, { compact: true });
const d: string = util.humanizeTime(12345, { msDecimalDigits: 2 });
const e: string = util.humanizeTime(12345, { secDecimalDigits: 2 });
const f: string = util.humanizeTime(12345, { verbose: true });
}
namespace humanizeSize {
const a: string = util.humanizeSize(12345);
const b: string = util.humanizeSize(12345, "");
}
namespace parseSize {
const a: number | null = util.parseSize(123);
const b: number | null = util.parseSize("123Kb");
@@ -486,7 +472,7 @@ namespace utilTests {
const c: (a: number, b: string) => Promise<string> = util.throttle.create((a: number, b: string) => String(a) + b);
const d = util.throttle.create(() => { }, {});
const e = util.throttle.create(() => { }, { interval: 1000 });
const f = util.throttle.create(() => { }, { max: 10 });
const f = util.throttle.create(() => { }, { concurrency: 10 });
const g = util.throttle.create(() => { }, { ordered: true });
const h = util.throttle.create(() => { }, { waitForReturn: true });
const i = util.throttle.create(() => { }, { onDone() {} });
+203
View File
@@ -0,0 +1,203 @@
namespace adoneTests.vault {
const {
is,
vault
} = adone;
let num: number;
let bool: boolean;
let obj: object;
let str: string;
namespace Vault {
const {
Vault
} = vault;
new Vault({
location: "a"
});
new Vault({
location: "a",
ValuableClass: vault.Valuable
});
const v = new Vault({
location: "a"
});
v.addTag("hello").then((x) => {
if (!is.null(x)) {
num = x;
}
});
v.clear().then((x) => {
num = x;
});
v.close().then();
v.create("hello").then((x) => {
x.set("a", "b");
});
v.create("hello", ["a", "b"]).then((x) => {
x.set("a", "b");
});
v.delete("a").then();
v.deleteTag("a").then((x) => {
bool = x;
});
v.entries().then((x) => {
obj = x;
});
v.get("a").then((x) => {
x.set("a", "b");
});
str = v.getNotes();
bool = v.has("a");
str = v.keys()[0];
str = v.location();
v.open().then(() => {});
v.release("name");
v.setNotes("asd").then();
str = v.tagNames()[0];
str = v.tagNames([1])[0];
obj = v.tags()[0];
obj = v.toJSON();
v.toJSON({ valuable: { includeId: true } }).then((x) => {
obj = x.valuables[0];
});
v.toJSON({ includeStats: true }).then((x) => {
num = x.stats.created;
num = x.stats.updated;
str = x.stats.location;
});
v.values().then((x) => {
x[0];
});
}
namespace Valuable {
new vault.Vault({ location: "a" }).get("a").then((v) => {
v.addTag("a").then();
v.clear().then((x) => {
num = x;
});
v.clear({ includeNotes: true }).then((x) => {
num = x;
});
v.clear({ includeTags: true }).then((x) => {
num = x;
});
v.delete("a").then((x) => {
num = x;
});
v.deleteAllTags();
v.entries().then((x) => {
obj = x;
});
v.entries({ entriesAsArray: true }).then((x) => {
obj = x;
});
v.entries({ includeEntryId: true }).then((x) => {
obj = x;
});
v.fromJSON({}).then((x) => {
num = x;
});
v.get("a").then();
str = v.getNotes();
bool = v.has("a");
bool = v.hasTag("a");
num = v.internalId();
str = v.keys()[0];
str = v.name();
v.set("a", "b").then((x) => {
num = x;
});
v.set("a", "b", "wtf").then((x) => {
num = x;
});
v.setMulti({ a: "1", b: "2" }).then();
v.setNotes("a").then();
obj = v.tags();
obj = v.toJSON();
obj = v.toJSON({ entriesAsArray: true });
obj = v.toJSON({ includeEntryId: true });
obj = v.toJSON({ includeId: false });
obj = v.toJSON({ tags: "normal" });
obj = v.toJSON({ tags: "none" });
obj = v.toJSON({ tags: "onlyId" });
obj = v.toJSON({ tags: "onlyName" });
v.type("a");
});
}
namespace slice {
new vault.Vault({ location: "a" }).get("a").then((valuable) => {
vault.slice(valuable, "s");
vault.slice(valuable, ["s"]);
vault.slice(valuable, ["s"], "a");
vault.slice(valuable, ["s"], "a");
const v = vault.slice(valuable, "s");
v.addTag("a").then();
v.delete("a").then((x) => {
num = x;
});
v.deleteAllTags().then();
v.deleteTag("a").then((x) => {
bool = x;
});
v.entries().then((x) => {
obj = x;
});
v.entries({}).then((x) => {
obj = x;
});
v.entries({ entriesAsArray: true }).then((x) => {
obj = x;
});
v.entries({ includeEntryId: true }).then((x) => {
obj = x;
});
v.fromJSON({}).then((x) => {
num = x;
});
v.get("a").then();
str = v.getNotes();
bool = v.has("a");
bool = v.hasTag("a");
num = v.internalId();
str = v.keys()[0];
str = v.name();
v.set("a", "b").then((x) => {
num = x;
});
v.set("a", "b", "wtf").then((x) => {
num = x;
});
v.setMulti({}).then();
v.setNotes("a").then((x) => {
num = x;
});
obj = v.tags()[0];
obj = v.toJSON();
obj = v.toJSON({});
obj = v.toJSON({ entriesAsArray: true });
obj = v.toJSON({ includeEntryId: true });
obj = v.toJSON({ includeId: true });
obj = v.toJSON({ tags: "none" });
obj = v.toJSON({ tags: "normal" });
obj = v.toJSON({ tags: "onlyId" });
obj = v.toJSON({ tags: "onlyName" });
v.type("a");
});
}
namespace open {
vault.open({ location: "a" }).then((x) => {
x.get("a").then((x) => x.setMulti({}));
});
vault.open({ location: "a", ValuableClass: vault.Valuable }).then((x) => {
x.get("a").then((x) => x.setMulti({}));
});
}
}
+32 -47
View File
@@ -1,23 +1,32 @@
namespace AdoneRootTests {
{ const a: symbol = adone.null; }
let num: number;
let sym: symbol;
let str: string;
let numarr: number[];
let obj: object;
let bool: boolean;
sym = adone.null;
adone.noop();
{ const a: number = adone.identity(2); }
{ const a: string = adone.identity("2"); }
{ const a: number[] = adone.identity([1, 2]); }
{ adone.truly() === true; }
{ adone.falsely() === false; }
{ const a: string = adone.ok; }
{ const a: string = adone.bad; }
{ const a: string[] = adone.exts; }
num = adone.identity(2);
str = adone.identity("3");
numarr = adone.identity([1, 2]);
adone.truly() === true;
adone.falsely() === false;
str = adone.ok;
str = adone.bad;
adone.log();
adone.fatal();
adone.error();
adone.warn();
adone.info();
adone.debug();
adone.trace();
{ const a: object = adone.o(); }
{ const a: object = adone.o({}); }
adone.logFatal();
adone.logError();
adone.logWarn();
adone.logInfo();
adone.logDebug();
adone.logTrace();
obj = adone.o();
obj = adone.o({});
{ const a: typeof Date = adone.Date; }
{ const a: typeof process.hrtime = adone.hrtime; }
{ const a: typeof global.setTimeout = adone.setTimeout; }
@@ -26,6 +35,7 @@ namespace AdoneRootTests {
{ const a: typeof clearInterval = adone.clearInterval; }
{ const a: typeof global.setImmediate = adone.setImmediate; }
{ const a: typeof clearImmediate = adone.clearImmediate; }
adone.lazify({});
adone.lazify({}, {});
adone.lazify({}, {}, () => { });
@@ -33,40 +43,15 @@ namespace AdoneRootTests {
adone.lazify({}, {}, () => { }, { configurable: true });
adone.lazify({}, {}, () => { }, { writable: false });
adone.lazify({}, {}, () => { }, { mapper: (key: string, obj: any) => null });
adone.tag.set({}, "123");
{ const a: boolean = adone.tag.has({}, "123"); }
bool = adone.tag.has({}, "123");
adone.tag.define("12");
adone.tag.define("123", "456");
{ const a: symbol = adone.tag.SUBSYSTEM; }
{ const a: symbol = adone.tag.APPLICATION; }
{ const a: symbol = adone.tag.TRANSFORM; }
{ const a: symbol = adone.tag.CORE_STREAM; }
{ const a: symbol = adone.tag.LOGGER; }
{ const a: symbol = adone.tag.LONG; }
{ const a: symbol = adone.tag.BIGNUMBER; }
{ const a: symbol = adone.tag.EXBUFFER; }
{ const a: symbol = adone.tag.EXDATE; }
{ const a: symbol = adone.tag.CONFIGURATION; }
{ const a: symbol = adone.tag.GENESIS_NETRON; }
{ const a: symbol = adone.tag.GENESIS_PEER; }
{ const a: symbol = adone.tag.NETRON; }
{ const a: symbol = adone.tag.NETRON_PEER; }
{ const a: symbol = adone.tag.NETRON_ADAPTER; }
{ const a: symbol = adone.tag.NETRON_DEFINITION; }
{ const a: symbol = adone.tag.NETRON_DEFINITIONS; }
{ const a: symbol = adone.tag.NETRON_REFERENCE; }
{ const a: symbol = adone.tag.NETRON_INTERFACE; }
{ const a: symbol = adone.tag.NETRON_STUB; }
{ const a: symbol = adone.tag.NETRON_REMOTESTUB; }
{ const a: symbol = adone.tag.NETRON_STREAM; }
{ const a: symbol = adone.tag.FAST_STREAM; }
{ const a: symbol = adone.tag.FAST_FS_STREAM; }
{ const a: symbol = adone.tag.FAST_FS_MAP_STREAM; }
{ const a: object = adone.bind("library"); } // hmm
{ const a: string = adone.getAssetAbsolutePath("asset"); }
str = adone.getAssetAbsolutePath("asset");
{ const a: Buffer | string = adone.loadAsset("asset"); }
{ const a: object = adone.require("path"); }
{ const a: object = adone.package; }
obj = adone.require("path");
obj = adone.package;
{ const a: typeof adone.assertion.assert = adone.assert; }
{ const a: typeof adone.assertion.expect = adone.expect; }
}
+14 -5
View File
@@ -16,7 +16,8 @@
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"experimentalDecorators": true
"experimentalDecorators": true,
"esModuleInterop": true
},
"files": [
"adone-tests.ts",
@@ -51,7 +52,7 @@
"glosses/data.d.ts",
"glosses/datetime.d.ts",
"glosses/events.d.ts",
"glosses/exceptions.d.ts",
"glosses/errors.d.ts",
"glosses/fake.d.ts",
"glosses/fast.d.ts",
"glosses/fs.d.ts",
@@ -63,6 +64,10 @@
"glosses/net/http/client.d.ts",
"glosses/net/http/index.d.ts",
"glosses/net/index.d.ts",
"glosses/pretty/json.d.ts",
"glosses/pretty/size.d.ts",
"glosses/pretty/table.d.ts",
"glosses/pretty/time.d.ts",
"glosses/promise.d.ts",
"glosses/regex.d.ts",
"glosses/semver.d.ts",
@@ -78,11 +83,11 @@
"glosses/templating/index.d.ts",
"glosses/templating/nunjucks.d.ts",
"glosses/text/index.d.ts",
"glosses/text/pretties.d.ts",
"glosses/text/spinners.d.ts",
"glosses/text/table.d.ts",
"glosses/text/unicode.d.ts",
"glosses/utils.d.ts",
"glosses/vault.d.ts",
"index.d.ts",
"test/glosses/application.ts",
"test/glosses/archives.ts",
@@ -113,7 +118,7 @@
"test/glosses/data.ts",
"test/glosses/datetime.ts",
"test/glosses/events.ts",
"test/glosses/exceptions.ts",
"test/glosses/errors.ts",
"test/glosses/fake.ts",
"test/glosses/fast.ts",
"test/glosses/fs.ts",
@@ -123,6 +128,10 @@
"test/glosses/math/simd.ts",
"test/glosses/meta.ts",
"test/glosses/net/http/client.ts",
"test/glosses/pretty/json.ts",
"test/glosses/pretty/size.ts",
"test/glosses/pretty/table.ts",
"test/glosses/pretty/time.ts",
"test/glosses/promise.ts",
"test/glosses/regex.ts",
"test/glosses/semver.ts",
@@ -136,11 +145,11 @@
"test/glosses/templating/dot.ts",
"test/glosses/templating/nunjucks.ts",
"test/glosses/text/index.ts",
"test/glosses/text/pretties.ts",
"test/glosses/text/spinners.ts",
"test/glosses/text/table.ts",
"test/glosses/text/unicode.ts",
"test/glosses/utils.ts",
"test/glosses/vault.ts",
"test/index-import.ts",
"test/index.ts"
]
+6 -1
View File
@@ -1,10 +1,10 @@
import Agenda = require("agenda");
import { Db, Server } from "mongodb";
var mongoConnectionString = "mongodb://127.0.0.1/agenda";
var agenda = new Agenda({ db: { address: mongoConnectionString } });
agenda.define('delete old users', (job, done) => {
});
@@ -102,4 +102,9 @@ job.remove(function(err) {
if (!err) console.log("Successfully removed job from collection");
})
class ExtendedAgenda extends Agenda {
async start() { }
}
const extendedAgenda: ExtendedAgenda = new ExtendedAgenda()
.mongo(new Db('some-database', new Server('host.name', 0)))
+9 -9
View File
@@ -31,57 +31,57 @@ declare class Agenda extends EventEmitter {
/**
* Connect to the specified MongoDB server and database.
*/
database(url: string, collection?: string, options?: any, cb?: ResultCallback<Collection>): Agenda;
database(url: string, collection?: string, options?: any, cb?: ResultCallback<Collection>): this;
/**
* Initialize agenda with an existing MongoDB connection.
*/
mongo(db: Db, collection?: string, cb?: ResultCallback<Collection>): Agenda;
mongo(db: Db, collection?: string, cb?: ResultCallback<Collection>): this;
/**
* Sets the agenda name.
*/
name(value: string): Agenda;
name(value: string): this;
/**
* Sets the interval with which the queue is checked. A number in milliseconds or a frequency string.
*/
processEvery(interval: string | number): Agenda;
processEvery(interval: string | number): this;
/**
* Takes a number which specifies the max number of jobs that can be running at any given moment. By default it
* is 20.
* @param value The value to set.
*/
maxConcurrency(value: number): Agenda;
maxConcurrency(value: number): this;
/**
* Takes a number which specifies the default number of a specific job that can be running at any given moment.
* By default it is 5.
* @param value The value to set.
*/
defaultConcurrency(value: number): Agenda;
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
* 0 for no max.
* @param value The value to set.
*/
lockLimit(value: number): Agenda;
lockLimit(value: number): this;
/**
* Takes a number which specifies the default number of a specific job that can be locked at any given moment.
* By default it is 0 for no max.
* @param value The value to set.
*/
defaultLockLimit(value: number): Agenda;
defaultLockLimit(value: number): this;
/**
* Takes a number which specifies the default lock lifetime in milliseconds. By default it is 10 minutes. This
* can be overridden by specifying the lockLifetime option to a defined job.
* @param value The value to set.
*/
defaultLockLifetime(value: number): Agenda;
defaultLockLifetime(value: number): this;
/**
* Returns an instance of a jobName with data. This does NOT save the job in the database. See below to learn
@@ -0,0 +1,28 @@
import * as ampHtmlValidator from "amphtml-validator";
(async () => {
const validator = await ampHtmlValidator.getInstance();
const result = validator.validateString("<html></html>");
const { status, errors } = result;
if (status === "FAIL" || status === "UNKNOWN") {
const errs = errors.map(err => {
const {
severity,
line,
col,
message,
specUrl,
category,
code,
params
} = err;
return err;
});
}
})();
(() => {
const validator = ampHtmlValidator.newInstance("");
const result = validator.validateString("<html></html>");
const { status, errors } = result;
})();
+156
View File
@@ -0,0 +1,156 @@
// Type definitions for amphtml-validator 1.0
// Project: https://github.com/ampproject/amphtml/tree/master/validator/nodejs
// Definitions by: Kevin Tjiam <https://github.com/kevincharm>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="node" />
import { Context, Script } from "vm";
export interface ValidationError {
severity: ValidationErrorSeverity;
line: number;
col: number;
message: string;
specUrl: string | null;
category: ErrorCategoryCode;
code: ValidationErrorCode;
params: string[];
}
export interface ValidationResult {
status: ValidationResultStatus;
errors: ValidationError[];
}
export class Validator extends Script {
sandbox: Context;
validateString(stringToValidate: string): ValidationResult;
}
export function getInstance(
validatorJs?: string,
userAgent?: string
): Promise<Validator>;
export function newInstance(validatorJsContents: string): Validator;
/**
* Enums from protobufs
* https://github.com/ampproject/amphtml/blob/master/validator/validator.proto
*/
export type ValidationResultStatus = "UNKNOWN" | "PASS" | "FAIL";
export type ValidationErrorSeverity = "UNKNOWN_SEVERITY" | "ERROR" | "WARNING";
export type ErrorCategoryCode =
| "UNKNOWN"
| "GENERIC"
| "DISALLOWED_HTML_WITH_AMP_EQUIVALENT"
| "DISALLOWED_HTML"
| "AUTHOR_STYLESHEET_PROBLEM"
| "MANDATORY_AMP_TAG_MISSING_OR_INCORRECT"
| "AMP_TAG_PROBLEM"
| "CUSTOM_JAVASCRIPT_DISALLOWED"
| "AMP_LAYOUT_PROBLEM"
| "AMP_HTML_TEMPLATE_PROBLEM"
| "DEPRECATION";
export type ValidationErrorCode =
| "UNKNOWN_CODE"
| "MANDATORY_TAG_MISSING"
| "TAG_REQUIRED_BY_MISSING"
| "WARNING_TAG_REQUIRED_BY_MISSING"
| "WARNING_EXTENSION_UNUSED"
| "EXTENSION_UNUSED"
| "WARNING_EXTENSION_DEPRECATED_VERSION"
| "ATTR_REQUIRED_BUT_MISSING"
| "DISALLOWED_TAG"
| "GENERAL_DISALLOWED_TAG"
| "DISALLOWED_SCRIPT_TAG"
| "DISALLOWED_ATTR"
| "DISALLOWED_STYLE_ATTR"
| "INVALID_ATTR_VALUE"
| "DUPLICATE_ATTRIBUTE"
| "ATTR_VALUE_REQUIRED_BY_LAYOUT"
| "IMPLIED_LAYOUT_INVALID"
| "SPECIFIED_LAYOUT_INVALID"
| "MANDATORY_ATTR_MISSING"
| "MANDATORY_ONEOF_ATTR_MISSING"
| "DUPLICATE_DIMENSION"
| "DUPLICATE_UNIQUE_TAG"
| "DUPLICATE_UNIQUE_TAG_WARNING"
| "WRONG_PARENT_TAG"
| "STYLESHEET_TOO_LONG"
| "MANDATORY_CDATA_MISSING_OR_INCORRECT"
| "CDATA_VIOLATES_BLACKLIST"
| "NON_WHITESPACE_CDATA_ENCOUNTERED"
| "DEPRECATED_ATTR"
| "DEPRECATED_TAG"
| "MANDATORY_PROPERTY_MISSING_FROM_ATTR_VALUE"
| "INVALID_PROPERTY_VALUE_IN_ATTR_VALUE"
| "MISSING_URL"
| "INVALID_URL"
| "INVALID_URL_PROTOCOL"
| "DISALLOWED_DOMAIN"
| "DISALLOWED_RELATIVE_URL"
| "DISALLOWED_PROPERTY_IN_ATTR_VALUE"
| "MUTUALLY_EXCLUSIVE_ATTRS"
| "UNESCAPED_TEMPLATE_IN_ATTR_VALUE"
| "TEMPLATE_PARTIAL_IN_ATTR_VALUE"
| "TEMPLATE_IN_ATTR_NAME"
| "INCONSISTENT_UNITS_FOR_WIDTH_AND_HEIGHT"
| "DISALLOWED_TAG_ANCESTOR"
| "MANDATORY_LAST_CHILD_TAG"
| "MANDATORY_TAG_ANCESTOR"
| "MANDATORY_TAG_ANCESTOR_WITH_HINT"
| "ATTR_DISALLOWED_BY_IMPLIED_LAYOUT"
| "ATTR_DISALLOWED_BY_SPECIFIED_LAYOUT"
| "INCORRECT_NUM_CHILD_TAGS"
| "INCORRECT_MIN_NUM_CHILD_TAGS"
| "DISALLOWED_CHILD_TAG_NAME"
| "DISALLOWED_FIRST_CHILD_TAG_NAME"
| "DISALLOWED_MANUFACTURED_BODY"
| "CHILD_TAG_DOES_NOT_SATISFY_REFERENCE_POINT"
| "MANDATORY_REFERENCE_POINT_MISSING"
| "DUPLICATE_REFERENCE_POINT"
| "TAG_NOT_ALLOWED_TO_HAVE_SIBLINGS"
| "TAG_REFERENCE_POINT_CONFLICT"
| "CHILD_TAG_DOES_NOT_SATISFY_REFERENCE_POINT_SINGULAR"
| "BASE_TAG_MUST_PRECEED_ALL_URLS"
| "MISSING_REQUIRED_EXTENSION"
| "ATTR_MISSING_REQUIRED_EXTENSION"
| "DOCUMENT_TOO_COMPLEX"
| "INVALID_UTF8"
| "CSS_SYNTAX"
| "CSS_SYNTAX_INVALID_AT_RULE"
| "CSS_SYNTAX_STRAY_TRAILING_BACKSLASH"
| "CSS_SYNTAX_UNTERMINATED_COMMENT"
| "CSS_SYNTAX_UNTERMINATED_STRING"
| "CSS_SYNTAX_BAD_URL"
| "CSS_SYNTAX_EOF_IN_PRELUDE_OF_QUALIFIED_RULE"
| "CSS_SYNTAX_INVALID_DECLARATION"
| "CSS_SYNTAX_INCOMPLETE_DECLARATION"
| "CSS_SYNTAX_ERROR_IN_PSEUDO_SELECTOR"
| "CSS_SYNTAX_MISSING_SELECTOR"
| "CSS_SYNTAX_NOT_A_SELECTOR_START"
| "CSS_SYNTAX_UNPARSED_INPUT_REMAINS_IN_SELECTOR"
| "CSS_SYNTAX_MISSING_URL"
| "CSS_SYNTAX_INVALID_URL"
| "CSS_SYNTAX_INVALID_URL_PROTOCOL"
| "CSS_SYNTAX_DISALLOWED_DOMAIN"
| "CSS_SYNTAX_DISALLOWED_RELATIVE_URL"
| "CSS_SYNTAX_INVALID_ATTR_SELECTOR"
| "CSS_SYNTAX_INVALID_PROPERTY"
| "CSS_SYNTAX_INVALID_PROPERTY_NOLIST"
| "CSS_SYNTAX_QUALIFIED_RULE_HAS_NO_DECLARATIONS"
| "CSS_SYNTAX_DISALLOWED_QUALIFIED_RULE_MUST_BE_INSIDE_KEYFRAME"
| "CSS_SYNTAX_DISALLOWED_KEYFRAME_INSIDE_KEYFRAME"
| "CSS_SYNTAX_MALFORMED_MEDIA_QUERY"
| "CSS_SYNTAX_DISALLOWED_MEDIA_TYPE"
| "CSS_SYNTAX_DISALLOWED_MEDIA_FEATURE"
| "CSS_SYNTAX_DISALLOWED_PROPERTY_VALUE"
| "CSS_SYNTAX_DISALLOWED_PROPERTY_VALUE_WITH_HINT"
| "CSS_SYNTAX_PROPERTY_DISALLOWED_WITHIN_AT_RULE"
| "CSS_SYNTAX_PROPERTY_DISALLOWED_TOGETHER_WITH"
| "CSS_SYNTAX_PROPERTY_REQUIRES_QUALIFICATION";
+16
View File
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": ["../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": ["index.d.ts", "amphtml-validator-tests.ts"]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1
View File
@@ -96,6 +96,7 @@ export interface ConnectionOptions {
authMechanism?: string;
vhost?: string;
noDelay?: boolean;
heartbeat?: number;
ssl?: {
enabled: boolean;
keyFile?: string;
+16
View File
@@ -0,0 +1,16 @@
anchors.add();
anchors.add('h1');
anchors.add().add('h2');
anchors.remove();
anchors.remove('h1');
anchors.remove().remove('h2');
anchors.removeAll();
const headerAnchors = new AnchorJS();
const footerAnchors = new AnchorJS({
placement: 'right',
});
footerAnchors.remove('.links');
+41
View File
@@ -0,0 +1,41 @@
// Type definitions for anchor-js 4.1
// Project: https://github.com/bryanbraun/anchorjs
// Definitions by: Brian Surowiec <https://github.com/xt0rted>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace anchorjs {
interface Anchor {
options: AnchorOptions;
add(selector?: string): Anchor;
remove(selector?: string): Anchor;
removeAll(): void;
}
type AnchorPlacement = 'left' | 'right';
type AnchorVisibility = 'always' | 'hover' | 'touch';
interface AnchorOptions {
arialabel?: string;
class?: string;
icons?: string;
placement?: AnchorPlacement;
truncate?: number;
visible?: AnchorVisibility;
}
interface AnchorStatic {
new(options?: AnchorOptions): Anchor;
}
}
declare const anchors: anchorjs.Anchor;
declare const AnchorJS: anchorjs.AnchorStatic;
export = AnchorJS;
export as namespace AnchorJS;
declare global {
const anchors: anchorjs.Anchor;
}
+23
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",
"anchor-js-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
@@ -0,0 +1,40 @@
import * as angular from 'angular';
angular
.module('app', ['ngDesktopNotification'])
.config(['desktopNotificationProvider', (desktopNotificationProvider: angular.desktopNotification.IDesktopNotificationProvider) => {
desktopNotificationProvider.config({
autoClose: true,
duration: 5,
showOnPageHidden: false,
});
}])
.controller('AppController', ['desktopNotification', (desktopNotification: angular.desktopNotification.IDesktopNotificationService) => {
// Check support and permission
const isNotificationSupported = desktopNotification.isSupported();
const currentNotificationPermission = desktopNotification.currentPermission();
if (currentNotificationPermission === desktopNotification.permissions.granted) {
// Permission granted
}
// Request permission
desktopNotification.requestPermission().then(
// Permission granted
(permission) => {
// Show notification
desktopNotification.show(
"Notification title",
{
tag: "tag",
body: "Notification body",
icon: "https://www.iconurl.com/icon-name.icon-extension",
onClick: () => {
// Notification clicked
}
});
},
() => {
// No permission granted
});
}]);
+174
View File
@@ -0,0 +1,174 @@
// Type definitions for angular-desktop-notification 1.1
// Project: https://github.com/jmsanpascual/angular-desktop-notification#readme
// Definitions by: Davide Donadello <https://github.com/Dona278>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import * as angular from 'angular';
declare var _: string;
export = _;
declare module 'angular' {
namespace desktopNotification {
/**
* All options available during show notification according to https://developer.mozilla.org/en-US/docs/Web/API/notification
*/
interface AugmentedNotificationOptions extends NotificationOptions {
/**
* The badge property of the Notification interface returns the URL of the image used to represent the notification
* when there is not enough space to display the notification itself.
*
* This is an experimental technology
* Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/badge
*/
badge?: USVString;
/**
* The data read-only property of the Notification interface returns a structured clone of the notification's data,
* as specified in the data option of the Notification() constructor
*
* Note: This feature is available in Web Workers.
* Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/data
*/
data?: any;
/**
* The image read-only property of the Notification interface contains the URL of an image to be displayed as part of
* the notification, as specified in the image option of the Notification() constructor.
*
* Note: This feature is available in Web Workers.
* Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/image
*/
image?: USVString;
/**
* The renotify read-only property of the Notification interface specifies whether the user should be notified after a
* new notification replaces an old one, as specified in the renotify option of the Notification() constructor
*
* Note: This property is not currently supported in any browser.
* Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/renotify
*/
renotify?: boolean;
/**
* The requireInteraction read-only property of the Notification interface returns a Boolean indicating that a notification
* should remain active until the user clicks or dismisses it, rather than closing automatically.
*
* Note: This can be set when the notification is first created by setting the requireInteraction option to true in the
* options object of the Notification.Notification() constructor.
* Note: This feature is available in Web Workers.
* Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/requireInteraction
*/
requireInteraction?: boolean;
/**
* The silent read-only property of the Notification interface specifies whether the notification should be silent, i.e. no
* sounds or vibrations should be issued, regardless of the device settings. This is specified in the renotify option of the
* Notification() constructor.
*
* Note: This feature is available in Web Workers.
* Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/silent
*/
silent?: boolean;
/**
* The timestamp read-only property of the Notification interface returns a DOMTimeStamp, as specified in the timestamp option of the
* Notification() constructor.
*
* The notification's timestamp can represent the time, in milliseconds since 00:00:00 UTC on 1 January 1970, of the event for which
* the notification was created, or it can be an arbitrary timestamp that you want associated with the notification. For example, a
* timestamp for an upcoming meeting could be set in the future, whereas a timestamp for a missed message could be set in the past.
*
* Note: This feature is available in Web Workers
* Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/timestamp
*/
timestamp?: number;
/**
* The title read-only property of the Notification interface indicates the title of the notification, as specified in the title parameter
* of the Notification() constructor.
*
* Note: This feature is available in Web Workers.
* Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/title
*/
title?: string;
/**
* The vibrate read-only property of the Notification interface specifies a a vibration pattern for the device's vibration hardware to emit
* when the notification fires. This is specified in the vibrate option of the Notification() constructor.
*
* Note: This property is not currently supported in any browser.
* Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/vibrate
*/
vibrate?: boolean;
/**
* The onclick property of the Notification interface specifies an event listener to receive click events.
* These events occur when the user clicks on a displayed Notification.
*
* The default behavior is to move the focus to the viewport of the notification's related browsing context.
* If you don't want that behaviour, call preventDefault() on the event object.
*/
onClick?: (event: MouseEvent) => void;
/**
* The onerror property of the Notification interface specifies an event listener to receive error events.
* These events occur when something goes wrong with a Notification (in many cases an error preventing the notification from being displayed.)
*
* A function which serves as the event handler for the error event. When an error occurs, the specified function will be called.
* If null, no error handler is in effect.
*/
onError?: EventListener;
}
// tslint:disable-next-line interface-name
interface IDesktopNotificationOptions {
autoClose?: boolean;
duration?: number;
showOnPageHidden?: boolean;
}
// tslint:disable-next-line interface-name
interface IDesktopNotificationProvider {
/**
* Set the default app-wide configuration for desktopNotification
*/
config(options: IDesktopNotificationOptions): void;
}
// tslint:disable-next-line interface-name
interface IDesktopNotificationService {
permissions: {
default: 'default',
denied: 'denied',
granted: 'granted',
};
/**
* This method returns true if the browser supports the Notification API, false otherwise
*/
isSupported(): boolean;
/**
* This method will get the current permission set in the browser which could be one of the ff.
* - desktopNotification.permissions.default
* - desktopNotification.permissions.denied
* - desktopNotification.permissions.granted
*/
currentPermission(): NotificationPermission;
/**
* This method returns a $q promise, if the user allowed the notification the successCallback will be executed,
* errorCallback will be executed otherwise
*/
requestPermission(): IPromise<NotificationPermission>;
/**
* This method will display the notification using the parameter values.
* See all available options here at https://developer.mozilla.org/en-US/docs/Web/API/notification#Instance_properties
*/
show(title: string, options?: NotificationOptions | AugmentedNotificationOptions): void;
}
}
}
@@ -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,
"esModuleInterop": true
},
"files": [
"index.d.ts",
"angular-desktop-notification-tests.ts"
]
}
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
@@ -1,29 +0,0 @@
import angularTouchSpin = require("angular-touchspin");
import * as angular from 'angular';
angular
.module('touchspin-tests', ['nk.touchspin'])
.config(function(touchspinConfigProvider: angular.touchspin.ITouchSpinConfigProvider) {
touchspinConfigProvider.defaults(<angular.touchspin.ITouchSpinOptions>{
min: 0,
max: 0,
step: 0,
decimals: 0,
stepInterval: 0,
forceStepDivisibility: '', // none | floor | round | ceil
stepIntervalDelay: 0,
verticalButtons: true,
verticalUpClass: '',
verticalDownClass: '',
initVal: 0,
prefix: '',
postfix: '',
prefixExtraClass: '',
postfixExtraClass: '',
mousewheel: true,
buttonDownClass: '',
buttonUpClass: '',
buttonDownTxt: '',
buttonUpTxt: ''
});
});
-43
View File
@@ -1,43 +0,0 @@
// Type definitions for Angular Touchspin v1.0.0
// Project: https://github.com/nkovacic/angular-touchspin
// Definitions by: Niko Kovačič <https://github.com/nkovacic>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="angular" />
declare let angularTouchSpin: string;
export = angularTouchSpin;
declare module "angular" {
namespace touchspin {
interface ITouchSpinOptions {
min?: number;
max?: number;
step?: number;
decimals?: number;
stepInterval?: number;
forceStepDivisibility?: string; // none | floor | round | ceil
stepIntervalDelay?: number;
verticalButtons?: boolean;
verticalUpClass?: string;
verticalDownClass?: string;
initVal?: number;
prefix?: string;
postfix?: string;
prefixExtraClass?: string;
postfixExtraClass?: string;
mousewheel?: boolean;
buttonDownClass?: string;
buttonUpClass?: string;
buttonDownTxt?: string;
buttonUpTxt?: string;
}
interface ITouchSpinConfig extends ITouchSpinOptions { }
interface ITouchSpinConfigProvider {
defaults(touchSpinOptions: ITouchSpinOptions): void;
}
}
}
+1
View File
@@ -71,6 +71,7 @@ declare module 'angular' {
isReady(): boolean;
onReady(): angular.IPromise<void>;
resolveClientLocale(): string;
getAvailableLanguageKeys(): string[];
}
interface ITranslateProvider extends angular.IServiceProvider {
+3 -3
View File
@@ -1,5 +1,5 @@
import * as anybar from 'anybar'
import anybar = require('anybar');
anybar('red', { port: 123 })
anybar('red', { port: 123 });
anybar('green')
anybar('green');
+4 -5
View File
@@ -1,10 +1,9 @@
// Type definitions for anybar 2.0.1
// Type definitions for anybar 2.0
// Project: https://github.com/sindresorhus/anybar
// Definitions by: Chris Khoo <https://github.com/khoomeister>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
declare namespace anybar { }
declare function anybar(color: string, options?: { port: number }): void;
declare function anybar(color: string, options?: { port: number }): void
export = anybar
export = anybar;
+1 -1
View File
@@ -20,4 +20,4 @@
"index.d.ts",
"anybar-tests.ts"
]
}
}
+1 -77
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"
}
+6
View File
@@ -0,0 +1,6 @@
import * as rootDir from 'app-root-dir';
let appRootPath: string;
rootDir.set('__dirname');
appRootPath = rootDir.get();
+20
View File
@@ -0,0 +1,20 @@
// Type definitions for app-root-dir 0.1
// Project: https://github.com/philidem/node-app-root-dir
// Definitions by: shaochenyang <https://github.com/chenyang-biu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface AppRootDir {
// Get the application's root directory
get(): string;
/**
* Set the application's root directory
* this will set a global so that no matter
* how many instances of app-root-dir module are installed,
* they will all return the same directory
*/
set(dirname: string): void;
}
declare const AppRootDir: AppRootDir;
export = AppRootDir;
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"app-root-dir-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+4 -4
View File
@@ -1,4 +1,3 @@
import * as AsyncLock from "async-lock";
const lock = new AsyncLock();
@@ -6,9 +5,9 @@ lock.acquire("key", (done) => {
done();
}, (err, ret) => { /* ... */ });
lock.acquire("key", (done) => {
done();
}).then(() => { /* ... */ });
lock.acquire("key", (done) => { done(); })
.then(() => { /* ... */ })
.catch(() => { /* ... */ });
lock.acquire("key", () => "stringValue")
// Check returned value's type is inherited properly
@@ -23,6 +22,7 @@ lock.acquire([ "key1", "key2" ], (done) => {
}, (err, ret) => { /* ... */ });
lock.isBusy();
lock.isBusy('key');
const lock2 = new AsyncLock({ timeout : 5000 });
const lock3 = new AsyncLock({ maxPending : 5000 });
+7 -8
View File
@@ -1,13 +1,12 @@
// Type definitions for async-lock
// Type definitions for async-lock 1.1
// Project: https://github.com/rain1017/async-lock
// Definitions by: Elisée MAURER <https://github.com/elisee>, Alejandro <https://github.com/afharo>
// Definitions by: Elisée MAURER <https://github.com/elisee>
// Alejandro <https://github.com/afharo>
// Anatoly <https://github.com/rhymmor>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
interface AsyncLockDoneCallback<T> {
(err?: Error, ret?: T): void;
}
type AsyncLockDoneCallback<T> = (err?: Error, ret?: T) => void;
interface AsyncLockOptions {
timeout?: number;
@@ -21,13 +20,13 @@ declare class AsyncLock {
acquire<T>(key: string | string[],
fn: (() => T | PromiseLike<T>) | ((done: AsyncLockDoneCallback<T>) => any),
opts?: AsyncLockOptions): PromiseLike<T>;
opts?: AsyncLockOptions): Promise<T>;
acquire<T>(key: string | string[],
fn: (done: AsyncLockDoneCallback<T>) => any,
cb: AsyncLockDoneCallback<T>,
opts?: AsyncLockOptions): void;
isBusy(): boolean;
isBusy(key?: string): boolean;
}
declare namespace AsyncLock { }
+1 -75
View File
@@ -1,77 +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,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": 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"
}
@@ -0,0 +1,38 @@
import Button, { ButtonGroup, themeNamespace } from "@atlaskit/button";
import * as React from "react";
import { render } from "react-dom";
declare const container: Element;
render(
<ButtonGroup appearance="primary">
<Button
appearance="danger"
ariaControls="some-aria-controls"
ariaExpanded={true}
ariaHaspopup={true}
className="some-class-name"
component={Button}
form="some-form"
href="some-href"
iconAfter={<div />}
iconBefore={<div />}
id="some-id"
innerRef={() => {}}
isDisabled={true}
isSelected={true}
key="some-key"
onClick={event => event.currentTarget.formMethod}
ref="some-ref"
shouldFitContainer={true}
spacing="compact"
tabIndex={88}
target="some-target"
type="button"
>
{themeNamespace}
</Button>
</ButtonGroup>,
container
);
+93
View File
@@ -0,0 +1,93 @@
// Type definitions for @atlaskit/button 6.4
// Project: https://bitbucket.org/atlassian/atlaskit-mk-2/
// Definitions by: Jimmy Luong <https://github.com/dijimsta>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
import {
Component,
ReactNode,
ReactElement,
ComponentClass,
MouseEventHandler
} from "react";
export type ButtonAppearances =
| "default"
| "danger"
| "link"
| "primary"
| "subtle"
| "subtle-link"
| "warning"
| "help";
export interface ButtonProps {
/** The base styling to apply to the button. */
readonly appearance?: ButtonAppearances;
/** Pass aria-controls to underlying html button. */
readonly ariaControls?: string;
/** Pass aria-expanded to underlying html button. */
readonly ariaExpanded?: boolean;
/** Pass aria-haspopup to underlying html button. */
readonly ariaHaspopup?: boolean;
/** This button's child nodes. */
readonly children?: ReactNode;
/** Add a classname to the button. */
readonly className?: string;
/** A custom component to use instead of the default button. */
readonly component?: ComponentClass<any>;
/** Name property of a linked form that the button submits when clicked. */
readonly form?: string;
/** Provides a url for buttons being used as a link. */
readonly href?: string;
/** Places an icon within the button, after the button's text. */
readonly iconAfter?: ReactElement<any>;
/** Places an icon within the button, before the button's text. */
readonly iconBefore?: ReactElement<any>;
/** Pass a reference on to the styled component */
readonly innerRef?: (instance: any) => void;
/** Provide a unique id to the button. */
readonly id?: string;
/** Set if the button is disabled. */
readonly isDisabled?: boolean;
/** Change the style to indicate the button is selected. */
readonly isSelected?: boolean;
/** Handler to be called on click. */
readonly onClick?: MouseEventHandler<HTMLButtonElement>;
/** Set the amount of padding in the button. */
readonly spacing?: ButtonSpacing;
/** Assign specific tabIndex order to the underlying html button. */
readonly tabIndex?: number;
/** Pass target down to a link within the button component, if a href is provided. */
readonly target?: string;
/** Set whether it is a button or a form submission. */
readonly type?: ButtonType;
/** Option to fit button width to its parent width */
readonly shouldFitContainer?: boolean;
}
export type ButtonType = "button" | "submit";
export type ButtonSpacing = "compact" | "default" | "none";
export interface ButtonState {
readonly isActive: boolean;
readonly isFocus: boolean;
readonly isHover: boolean;
}
declare class Button extends Component<ButtonProps, ButtonState> {}
export interface ButtonGroupProps {
/** The appearance to apply to all buttons. */
readonly appearance?: ButtonAppearances;
/** The buttons to render. */
readonly children: ReactNode;
}
export class ButtonGroup extends Component<ButtonGroupProps> {}
export const themeNamespace: string;
export default Button;
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6", "dom"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": ["../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"jsx": "react",
"paths": {
"@atlaskit/button": ["atlaskit__button"]
}
},
"files": ["index.d.ts", "atlaskit__button-tests.tsx"]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+12 -1
View File
@@ -5,6 +5,10 @@
import { Disposable, Point, Range, TextEditor } from "../index";
export interface Config {
name: string;
}
export interface ReplacementSolution {
title?: string;
position: Range;
@@ -60,6 +64,9 @@ export interface Message {
* do things like HTTP requests.
*/
description?: string|(() => Promise<string>|string);
/** Optionally override the displayed linter name. Defaults to provider name. */
linterName?: string;
}
export interface IndieDelegate {
@@ -73,10 +80,14 @@ export interface IndieDelegate {
dispose(): void;
}
export type LintResult = Message[] | null;
export interface LinterProvider {
name: string;
scope: "file"|"project";
lintsOnChange: boolean;
grammarScopes: string[];
lint(textEditor: TextEditor): Message[]|null|Promise<Message[]|null>;
lint(editor: TextEditor): LintResult | Promise<LintResult>;
}
export type IndieProvider = (register: (config: Config) => IndieDelegate) => void;
+9 -1
View File
@@ -631,7 +631,15 @@ let apiGtwProxyHandler: AWSLambda.APIGatewayProxyHandler = (event: AWSLambda.API
let proxyHandler: AWSLambda.ProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.ProxyCallback) => { };
apiGtwProxyHandler = proxyHandler;
let cloudFrontRequestHandler: AWSLambda.CloudFrontRequestHandler = (event: AWSLambda.CloudFrontRequestEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontRequestCallback) => { };
let cloudFrontRequestHandler: AWSLambda.CloudFrontRequestHandler = (event: AWSLambda.CloudFrontRequestEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontRequestCallback) => {
cb();
cb(null);
cb(new Error(''));
cb(null, { clientIp: str, method: str, uri: str, querystring: str, headers: { } });
cb(null, { status: str });
// $ExpectError
cb(null, { });
};
let cloudFrontResponseHandler: AWSLambda.CloudFrontResponseHandler = (event: AWSLambda.CloudFrontResponseEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontResponseCallback) => { };
+2 -1
View File
@@ -15,6 +15,7 @@
// Palmi Valgeirsson <https://github.com/palmithor>
// Danilo Raisi <https://github.com/daniloraisi>
// Simon Buchan <https://github.com/simonbuchan>
// David Hayden <https://github.com/Haydabase>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -516,7 +517,7 @@ export interface CloudFrontResponseEvent {
}>;
}
export type CloudFrontRequestResult = undefined | null | CloudFrontResultResponse;
export type CloudFrontRequestResult = undefined | null | CloudFrontResultResponse | CloudFrontRequest;
export interface CloudFrontRequestEvent {
Records: Array<{
+1 -1
View File
@@ -422,7 +422,7 @@ export interface ExportNamedDeclaration extends Node {
type: "ExportNamedDeclaration";
declaration: Declaration;
specifiers: ExportSpecifier[];
source: StringLiteral;
source: StringLiteral | null;
}
export interface ExportSpecifier extends Node {
@@ -0,0 +1,26 @@
import codeFrame, { codeFrameColumns } from "@babel/code-frame";
const code = `
const number = 1;
var string = 'foo';
function print(name: string) {
console.log(string + name);
}
`;
codeFrame(code, 5, 22);
codeFrame(code, 5, 22, { forceColor: true });
codeFrame(code, 2, 2, { highlightCode: true });
codeFrameColumns(code, { start: { line: 5, column: 22 } });
codeFrameColumns(
code,
{ start: { line: 5, column: 22 } },
{ forceColor: true }
);
codeFrameColumns(
code,
{ start: { line: 2, column: 2 } },
{ highlightCode: true }
);
+54
View File
@@ -0,0 +1,54 @@
// Type definitions for @babel/code-frame 7.0
// Project: https://github.com/babel/babel/tree/master/packages/babel-code-frame
// Definitions by: Mohsen Azimi <https://github.com/mohsen1>
// Forbes Lindesay <https://github.com/ForbesLindesay>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export interface SourceLocation {
start: { line: number; column?: number };
end?: { line: number; column?: number };
}
export function codeFrameColumns(
rawLines: string,
location: SourceLocation,
options?: BabelCodeFrameOptions
): string;
export interface BabelCodeFrameOptions {
/** Syntax highlight the code as JavaScript for terminals. default: false */
highlightCode?: boolean;
/** The number of lines to show above the error. default: 2 */
linesAbove?: number;
/** The number of lines to show below the error. default: 3 */
linesBelow?: number;
/**
* Forcibly syntax highlight the code as JavaScript (for non-terminals);
* overrides highlightCode.
* default: false
*/
forceColor?: boolean;
/**
* Pass in a string to be displayed inline (if possible) next to the
* highlighted location in the code. If it can't be positioned inline,
* it will be placed above the code frame.
* default: nothing
*/
message?: string;
}
/**
* Generate errors that contain a code frame that point to source locations.
*
* @param rawLines Raw lines to frame
* @param lineNumber Line number (1 indexed)
* @param colNumber Column number
* @param options Additional options
*
* @returns Framed code
*/
export default function codeFrame(
rawLines: string,
lineNumber: number,
colNumber: number,
options?: BabelCodeFrameOptions
): string;
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": ["../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"paths": {
"@babel/code-frame": ["babel__code-frame"]
}
},
"files": ["index.d.ts", "babel__code-frame-tests.ts"]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+8
View File
@@ -0,0 +1,8 @@
import * as base64topdf from 'base64topdf';
base64topdf.base64Encode('index.ts'); // $ExpectType void
base64topdf.base64Decode('decodethis', 'test.b64'); // $ExpectType void
base64topdf.rtfToText('rtf'); // $ExpectType string
base64topdf.textToRtf('text'); // $ExpectType string
base64topdf.strToBase64('str'); // $ExpectType string
base64topdf.base64ToStr('base64'); // $ExpectType string
+13
View File
@@ -0,0 +1,13 @@
// Type definitions for base64topdf 1.1
// Project: https://github.com/rpsankar001
// Definitions by: Lucas Riondel <https://github.com/lucasriondel>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export as namespace base64topdf;
export function base64Encode(file: string): void;
export function base64Decode(base64str: string, file: string): void;
export function rtfToText(rtfStr: string): string;
export function textToRtf(textStr: string): string;
export function strToBase64(str: string): string;
export function base64ToStr(base64Str: string): string;
+23
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",
"base64topdf-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1
View File
@@ -295,6 +295,7 @@ export const Big: BigConstructor;
export type Big_ = Big;
export type BigConstructor_ = BigConstructor;
export type BigSource_ = BigSource;
export default Big;
declare global {
namespace BigJs {
@@ -0,0 +1,12 @@
/*
This file contains tests for the named export definitions of big.js.
Import the default Big constructor from 'big.js'
*/
import Big from 'big.js';
function constructorTests() {
const x = new Big(9); // '9'
}
+2 -1
View File
@@ -19,6 +19,7 @@
"files": [
"index.d.ts",
"test/big.js-module-tests.ts",
"test/big.js-global-tests.ts"
"test/big.js-global-tests.ts",
"test/big.js-import-default-tests.ts"
]
}
+1
View File
@@ -58,6 +58,7 @@ interface DatepickerOptions {
daysOfWeekHighlighted?:string|number[];
defaultViewDate?:Date|string|DatepickerViewDate;
updateViewDate?:boolean;
enableOnReadonly?: boolean;
}
interface DatepickerViewDate {
+189 -33
View File
@@ -1,48 +1,204 @@
$('body').off('.data-api');
$('body').off('.alert.data-api');
// --------------------------------------------------------------------------------------
// Alert
// --------------------------------------------------------------------------------------
$(".btn.danger").button("toggle").addClass("fat");
$("#myModal").modal();
$("#myModal").modal({ keyboard: false });
$("#myModal").modal('show');
$("#alert").alert();
$('#myModal').on('show', (e) => e.preventDefault());
$("#alert").alert("close");
$('#myModal').modal({ keyboard: false });
$('#myModal').modal('toggle');
$("#alert").on("close.bs.alert", () => {});
$('.dropdown-toggle').dropdown();
// --------------------------------------------------------------------------------------
// Button
// --------------------------------------------------------------------------------------
$('#navbar').scrollspy();
$('body').scrollspy({ target: '#navbar-example' });
// $("#button").button(); // must fail
$('#element').tooltip('show');
$("#button").button("toggle");
$('#element').popover('show');
// --------------------------------------------------------------------------------------
// Carousel
// --------------------------------------------------------------------------------------
$(".alert").alert();
$(".alert").alert('close');
$("#carousel").carousel();
$('.nav-tabs').button();
$().button('toggle');
$("#carousel").carousel("pause");
$(".collapse").collapse();
$("#carousel").carousel(100);
$('#myCollapsible').collapse({ toggle: false });
$('.carousel').carousel();
$('.carousel').carousel({ interval: 2000 });
$('.typeahead').typeahead({
matcher: item => true,
sorter: (items: any[]) => items,
updater: item => item,
highlighter: item => ""
$("#carousel").carousel({
interval: 5000,
keyboard: true,
pause: "hover",
wrap: true,
});
$('#navbar').affix();
$("#carousel").carousel({
pause: false,
});
$('.item').emulateTransitionEnd(2000);
$("#carousel").on("slide.bs.carousel", function(ev) {
const that: HTMLElement = this;
const from: number = ev.from;
const to: number = ev.to;
const direction: string = ev.direction;
const data: undefined = ev.data;
});
$.support.transition = false;
console.log(($.support.transition as any as TransitionEventNames).end === "transitionend");
// --------------------------------------------------------------------------------------
// Dropdown
// --------------------------------------------------------------------------------------
$("#dropdown").dropdown();
$("#dropdown").dropdown("update");
$("#dropdown").on("hide.bs.dropdown", () => {});
$("#dropdown").dropdown({
offset: 10,
flip: false,
boundary: "window",
});
$("#dropdown").dropdown({
offset: "10px",
});
$("#dropdown").dropdown({
offset(offsets: BootstrapOffsetsExtend) {
if (!this.flip)
return { popper: { left: 100 } };
return {};
},
});
$("#dropdown").dropdown({
boundary: document.body,
});
// --------------------------------------------------------------------------------------
// Modal
// --------------------------------------------------------------------------------------
$("#modal").modal();
$("#modal").modal("show");
$("#modal").on("hide.bs.modal", () => {});
$("#modal").modal({
backdrop: false,
focus: false,
keyboard: false,
show: false,
});
$("#modal").modal({
backdrop: "static",
});
// --------------------------------------------------------------------------------------
// Tooltip
// --------------------------------------------------------------------------------------
$("#tooltip").tooltip();
$("#tooltip").tooltip("show");
$("#tooltip").on("hide.bs.tooltip", () => {});
$("#tooltip").tooltip({
animation: false,
});
$("#tooltip").tooltip({
container: "#container",
});
$("#tooltip").tooltip({
container: document.getElementById("#container") as HTMLElement,
});
$("#tooltip").tooltip({
container: false,
});
$("#tooltip").tooltip({
delay: 250,
});
$("#tooltip").tooltip({
delay: {show: 500, hide: 100},
});
$("#tooltip").tooltip({
html: true,
});
$("#tooltip").tooltip({
placement: "auto",
});
$("#tooltip").tooltip({
placement(this, tooltip, trigger) {
console.log(this.tip === tooltip);
console.log(this.element === trigger);
console.log(this.config.html);
return "left";
},
});
$("#tooltip").tooltip({
selector: "[rel=\"tooltip\"]",
});
$("#tooltip").tooltip({
selector: false,
});
$("#tooltip").tooltip({
template: '<div class="tooltip empty" role="tooltip"></div>',
});
$("#tooltip").tooltip({
title: "Hello world",
});
$("#tooltip").tooltip({
title: document.getElementById("title-element") as HTMLElement,
});
$("#tooltip").tooltip({
title(this: Element) {
return this.textContent as string;
},
});
$("#tooltip").tooltip({
trigger: "focus hover",
});
$("#tooltip").tooltip({
offset: 10,
});
$("#tooltip").tooltip({
offset: "10px",
});
$("#tooltip").tooltip({
fallbackPlacement: "clockwise",
});
$("#tooltip").tooltip({
fallbackPlacement: ["flip", "clockwise"],
});
$("#tooltip").tooltip({
boundary: "scrollParent",
});
$("#tooltip").tooltip({
boundary: document.body,
});
Vendored Regular → Executable
+268 -102
View File
@@ -1,133 +1,299 @@
// Type definitions for Bootstrap 3.3.5
// Project: http://twitter.github.com/bootstrap/
// Definitions by: Boris Yankov <https://github.com/borisyankov>
// Type definitions for Bootstrap 4.0
// Project: https://github.com/twbs/bootstrap/
// Definitions by: denisname <https://github.com/denisname>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// TODO: collapse, tab (list-group, navs), popovers, scrollspy
/// <reference types="jquery"/>
/// <reference types="jquery" />
interface ModalOptions {
backdrop?: boolean|string;
keyboard?: boolean;
show?: boolean;
remote?: string;
// --------------------------------------------------------------------------
// Some Types and Interfaces
// --------------------------------------------------------------------------
type BootstrapPlacement = "auto" | "top" | "bottom" | "left" | "right";
type PopperBehavior = "flip" | "clockwise" | "counterclockwise";
interface BootstrapDelay {
show: number;
hide: number;
}
interface ModalOptionsBackdropString {
backdrop?: string; // for "static"
keyboard?: boolean;
show?: boolean;
remote?: string;
interface BootstrapTooltipInstance {
config: BootstrapTooltipOption;
element: Element;
tip: HTMLElement;
}
interface ScrollSpyOptions {
offset?: number;
target?: string;
interface BootstrapOffsetExtend {
top?: number;
left?: number;
width?: number;
height?: number;
}
interface TooltipOptions {
animation?: boolean;
html?: boolean;
placement?: string | Function;
selector?: string;
title?: string | Function;
trigger?: string;
template?: string;
delay?: number | Object;
container?: string | boolean;
viewport?: string | Function | Object;
interface BootstrapOffsetsExtend {
popper?: BootstrapOffsetExtend;
reference?: BootstrapOffsetExtend;
}
interface PopoverOptions {
animation?: boolean;
html?: boolean;
placement?: string | Function;
selector?: string;
trigger?: string;
title?: string | Function;
template?: string;
content?: any;
delay?: number | Object;
container?: string | boolean;
viewport?: string | Function | Object;
}
// --------------------------------------------------------------------------------------
// Options Interfaces
// --------------------------------------------------------------------------------------
interface CollapseOptions {
parent?: any;
toggle?: boolean;
}
interface CarouselOptions {
interface BootstrapCarouselOption {
/**
* The amount of time to delay between automatically cycling an item. If false, carousel will not automatically cycle.
*
* @default 5000
*/
interval?: number;
pause?: string;
wrap?: boolean;
/**
* Whether the carousel should react to keyboard events.
*
* @default true
*/
keyboard?: boolean;
/**
* If set to "hover", pauses the cycling of the carousel on mouseenter and resumes the cycling of the carousel on mouseleave.
* If set to false, hovering over the carousel won't pause it.
* On touch-enabled devices, when set to "hover", cycling will pause on touchend (once the user finished interacting with the carousel)
* for two intervals, before automatically resuming. Note that this is in addition to the above mouse behavior.
*
* @default "hover"
*/
pause?: "hover" | false;
/**
* Whether the carousel should cycle continuously or have hard stops.
*
* @default true
*/
wrap?: boolean;
}
interface TypeaheadOptions {
source?: any;
items?: number;
minLength?: number;
matcher?: (item: any) => boolean;
sorter?: (items: any[]) => any[];
updater?: (item: any) => any;
highlighter?: (item: any) => string;
interface BootstrapDropdownOption {
/**
* Offset of the dropdown relative to its target.
* For more information refer to Popper.js's offset docs.
*
* @default 0
*/
offset?: number | string | ((this: BootstrapDropdownOption, offset: BootstrapOffsetsExtend) => BootstrapOffsetsExtend);
/**
* Allow Dropdown to flip in case of an overlapping on the reference element.
* For more information refer to Popper.js's flip docs.
*
* @default true
*/
flip?: boolean;
/**
* Overflow constraint boundary of the dropdown menu.
* Accepts the values of 'viewport', 'window', 'scrollParent', or an HTMLElement reference (JavaScript only).
* For more information refer to Popper.js's preventOverflow docs.
*
* @default "scrollParent"
*/
boundary?: "viewport" | "window" | "scrollParent" | HTMLElement;
}
interface AffixOptions {
offset?: number | Function | Object;
target?: any;
interface BootstrapModalOption {
/**
* Includes a modal-backdrop element.
* Alternatively, specify static for a backdrop which doesn't close the modal on click.
*
* @default true
*/
backdrop?: boolean | "static";
/**
* Closes the modal when escape key is pressed.
*
* @default true
*/
keyboard?: boolean;
/**
* Puts the focus on the modal when initialized.
*
* @default true
*/
focus?: boolean;
/**
* Shows the modal when initialized.
*
* @default true
*/
show?: boolean;
}
interface TransitionEventNames {
end: string;
interface BootstrapTooltipOption {
/**
* Apply a CSS fade transition to the tooltip.
*
* @default true
*/
animation?: boolean;
/**
* Appends the tooltip to a specific element. Example: `container: 'body'`.
* This option is particularly useful in that it allows you to position the tooltip
* in the flow of the document near the triggering element - which will prevent
* the tooltip from floating away from the triggering element during a window resize.
*
* @default false
*/
container?: string | Element | false;
/**
* Delay showing and hiding the tooltip (ms) - does not apply to manual trigger type.
* If a number is supplied, delay is applied to both hide/show.
* Object structure is: `delay: { "show": 500, "hide": 100 }`.
*
* @default 0
*/
delay?: number | BootstrapDelay;
/**
* Allow HTML in the tooltip.
* If true, HTML tags in the tooltip's title will be rendered in the tooltip.
* If false, jQuery's text method will be used to insert content into the DOM.
* Use text if you're worried about XSS attacks.
*
* @default false
*/
html?: boolean;
/**
* How to position the tooltip - auto | top | bottom | left | right.
* When auto is specified, it will dynamically reorient the tooltip.
* When a function is used to determine the placement, it is called with
* the tooltip DOM node as its first argument and the triggering element DOM node as its second.
* The this context is set to the tooltip instance.
*
* @default "top"
*/
placement?: BootstrapPlacement | ((this: BootstrapTooltipInstance, tooltip: HTMLElement, trigger: Element) => BootstrapPlacement);
/**
* If a selector is provided, tooltip objects will be delegated to the specified targets.
* In practice, this is used to enable dynamic HTML content to have popovers added.
*
* @default false
*/
selector?: string | false;
/**
* Base HTML to use when creating the tooltip. The tooltip's title will be injected into
* the `.tooltip-inner`. The `.arrow` will become the tooltip's arrow.
* The outermost wrapper element should have the `.tooltip` class and `role="tooltip"`.
*
* @default '<div class="tooltip" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>'
*/
template?: string;
/**
* Default title value if title attribute isn't present.
* If a function is given, it will be called with its this reference set to the element
* that the tooltip is attached to.
*
* @default ""
*/
title?: string | Element | ((this: Element) => string);
/**
* How tooltip is triggered - click | hover | focus | manual. You may pass multiple triggers; separate them with a space.
* 'manual' indicates that the tooltip will be triggered programmatically via the .tooltip('show'), .tooltip('hide') and
* .tooltip('toggle') methods; this value cannot be combined with any other trigger.
* 'hover' on its own will result in tooltips that cannot be triggered via the keyboard, and should only be used if
* alternative methods for conveying the same information for keyboard users is present.
*
* @default "hover focus"
*/
trigger?: string;
/**
* Offset of the tooltip relative to its target.
* For more information refer to Popper.js's offset docs.
*
* @default 0
*/
offset?: number | string;
/**
* Allow to specify which position Popper will use on fallback.
* For more information refer to Popper.js's behavior docs.
*
* @default "flip"
*/
fallbackPlacement?: PopperBehavior | PopperBehavior[];
/**
* Overflow constraint boundary of the tooltip.
* Accepts the values of 'viewport', 'window', 'scrollParent',
* or an HTMLElement reference (JavaScript only).
* For more information refer to Popper.js's preventOverflow docs.
*
* @default "scrollParent"
*/
boundary?: "viewport" | "window" | "scrollParent" | HTMLElement;
}
interface JQuery {
modal(options?: ModalOptions): JQuery;
modal(options?: ModalOptionsBackdropString): JQuery;
modal(command: string, relatedTarget?: Element): JQuery;
// --------------------------------------------------------------------------------------
// Events
// --------------------------------------------------------------------------------------
dropdown(): JQuery;
dropdown(command: string): JQuery;
interface BootstrapCarouselEventHandler<TElement> extends JQuery.Event<TElement, undefined> {
/**
* The direction in which the carousel is sliding.
*/
direction: "left" | "right";
scrollspy(command: string): JQuery;
scrollspy(options?: ScrollSpyOptions): JQuery;
/**
* The index of the current item.
*/
from: number;
tab(): JQuery;
tab(command: string): JQuery;
tooltip(options?: TooltipOptions): JQuery;
tooltip(command: string): JQuery;
popover(options?: PopoverOptions): JQuery;
popover(command: string): JQuery;
alert(): JQuery;
alert(command: string): JQuery;
button(): JQuery;
button(command: string): JQuery;
collapse(options?: CollapseOptions): JQuery;
collapse(command: string): JQuery;
carousel(options?: CarouselOptions): JQuery;
carousel(command: string): JQuery;
carousel(index: number): JQuery;
typeahead(options?: TypeaheadOptions): JQuery;
affix(options?: AffixOptions): JQuery;
affix(command: string): JQuery;
emulateTransitionEnd(duration: number): JQuery;
/**
* The index of the next item.
*/
to: number;
}
interface JQuerySupport {
transition: boolean | TransitionEventNames;
}
type BootstrapAlertEvent = "close.bs.alert" | "closed.bs.alert";
type BootstrapCarouselEvent = "slide.bs.carousel" | "slid.bs.carousel";
type BootstrapDropdownEvent = "show.bs.dropdown" | "shown.bs.dropdown" | "hide.bs.dropdown" | "hidden.bs.dropdown";
type BootstrapModalEvent = "show.bs.modal" | "shown.bs.modal" | "hide.bs.modal" | "hidden.bs.modal";
type BootstrapTooltipEvent = "show.bs.tooltip" | "shown.bs.tooltip" | "hide.bs.tooltip" | "hidden.bs.tooltip" | "inserted.bs.tooltip";
declare module "bootstrap" {
// --------------------------------------------------------------------------------------
// jQuery
// --------------------------------------------------------------------------------------
interface JQuery<TElement extends Node = HTMLElement> extends Iterable<TElement> {
alert(action?: "close" | "dispose"): this;
button(action: "toggle" | "dispose"): this;
carousel(action: "cycle" | "pause" | number | "prev" | "next" | "dispose"): this;
carousel(options?: BootstrapCarouselOption): this;
dropdown(action: "toggle" | "update" | "dispose"): this;
dropdown(options?: BootstrapDropdownOption): this;
modal(action: "toggle" | "show" | "hide" | "handleUpdate" | "dispose"): this;
modal(options?: BootstrapModalOption): this;
tooltip(action: "show" | "hide" | "toggle" | "dispose" | "enable" | "disable" | "toggleEnabled" | "update"): this;
tooltip(options?: BootstrapTooltipOption): this;
on(events: BootstrapCarouselEvent, handler: JQuery.EventHandlerBase<TElement, BootstrapCarouselEventHandler<TElement>>): this;
on(events: BootstrapAlertEvent | BootstrapDropdownEvent | BootstrapModalEvent | BootstrapTooltipEvent,
handler: JQuery.EventHandler<TElement>): this;
}
Regular → Executable
+3 -2
View File
@@ -7,7 +7,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",
Regular → Executable
+1 -79
View File
@@ -1,79 +1 @@
{
"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" }
+48
View File
@@ -0,0 +1,48 @@
$('body').off('.data-api');
$('body').off('.alert.data-api');
$(".btn.danger").button("toggle").addClass("fat");
$("#myModal").modal();
$("#myModal").modal({ keyboard: false });
$("#myModal").modal('show');
$('#myModal').on('show', (e) => e.preventDefault());
$('#myModal').modal({ keyboard: false });
$('#myModal').modal('toggle');
$('.dropdown-toggle').dropdown();
$('#navbar').scrollspy();
$('body').scrollspy({ target: '#navbar-example' });
$('#element').tooltip('show');
$('#element').popover('show');
$(".alert").alert();
$(".alert").alert('close');
$('.nav-tabs').button();
$().button('toggle');
$(".collapse").collapse();
$('#myCollapsible').collapse({ toggle: false });
$('.carousel').carousel();
$('.carousel').carousel({ interval: 2000 });
$('.typeahead').typeahead({
matcher: item => true,
sorter: (items: any[]) => items,
updater: item => item,
highlighter: item => ""
});
$('#navbar').affix();
$('.item').emulateTransitionEnd(2000);
$.support.transition = false;
console.log(($.support.transition as any as TransitionEventNames).end === "transitionend");
+133
View File
@@ -0,0 +1,133 @@
// Type definitions for Bootstrap 3.3.5
// Project: http://twitter.github.com/bootstrap/
// Definitions by: Boris Yankov <https://github.com/borisyankov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="jquery"/>
interface ModalOptions {
backdrop?: boolean|string;
keyboard?: boolean;
show?: boolean;
remote?: string;
}
interface ModalOptionsBackdropString {
backdrop?: string; // for "static"
keyboard?: boolean;
show?: boolean;
remote?: string;
}
interface ScrollSpyOptions {
offset?: number;
target?: string;
}
interface TooltipOptions {
animation?: boolean;
html?: boolean;
placement?: string | Function;
selector?: string;
title?: string | Function;
trigger?: string;
template?: string;
delay?: number | Object;
container?: string | boolean;
viewport?: string | Function | Object;
}
interface PopoverOptions {
animation?: boolean;
html?: boolean;
placement?: string | Function;
selector?: string;
trigger?: string;
title?: string | Function;
template?: string;
content?: any;
delay?: number | Object;
container?: string | boolean;
viewport?: string | Function | Object;
}
interface CollapseOptions {
parent?: any;
toggle?: boolean;
}
interface CarouselOptions {
interval?: number;
pause?: string;
wrap?: boolean;
keyboard?: boolean;
}
interface TypeaheadOptions {
source?: any;
items?: number;
minLength?: number;
matcher?: (item: any) => boolean;
sorter?: (items: any[]) => any[];
updater?: (item: any) => any;
highlighter?: (item: any) => string;
}
interface AffixOptions {
offset?: number | Function | Object;
target?: any;
}
interface TransitionEventNames {
end: string;
}
interface JQuery {
modal(options?: ModalOptions): JQuery;
modal(options?: ModalOptionsBackdropString): JQuery;
modal(command: string, relatedTarget?: Element): JQuery;
dropdown(): JQuery;
dropdown(command: string): JQuery;
scrollspy(command: string): JQuery;
scrollspy(options?: ScrollSpyOptions): JQuery;
tab(): JQuery;
tab(command: string): JQuery;
tooltip(options?: TooltipOptions): JQuery;
tooltip(command: string): JQuery;
popover(options?: PopoverOptions): JQuery;
popover(command: string): JQuery;
alert(): JQuery;
alert(command: string): JQuery;
button(): JQuery;
button(command: string): JQuery;
collapse(options?: CollapseOptions): JQuery;
collapse(command: string): JQuery;
carousel(options?: CarouselOptions): JQuery;
carousel(command: string): JQuery;
carousel(index: number): JQuery;
typeahead(options?: TypeaheadOptions): JQuery;
affix(options?: AffixOptions): JQuery;
affix(command: string): JQuery;
emulateTransitionEnd(duration: number): JQuery;
}
interface JQuerySupport {
transition: boolean | TransitionEventNames;
}
declare module "bootstrap" {
}
+29
View File
@@ -0,0 +1,29 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": [
"../../"
],
"types": [],
"paths": {
"bootstrap": [
"bootstrap/v3"
]
},
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"bootstrap-tests.ts"
]
}
+3
View File
@@ -1,5 +1,8 @@
import * as bson from 'bson';
// enable hex string caching
bson.ObjectID.cacheHexString = true
let BSON = new bson.BSON();
let Long = bson.Long;
+2
View File
@@ -135,6 +135,8 @@ export class ObjectID {
constructor(id?: string | number | ObjectID);
/** The generation time of this ObjectID instance */
generationTime: number;
/** If true cache the hex string representation of ObjectID */
static cacheHexString?: boolean;
/**
* Creates an ObjectID from a hex string representation of an ObjectID.
* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring.
-5
View File
@@ -456,11 +456,6 @@ declare namespace Bull {
*/
getFailed(start?: number, end?: number): Promise<Job[]>;
/**
* Returns a promise that will return an array with the waiting jobs between start and end.
*/
getWaiting(start?: number, end?: number): Promise<Job[]>;
/**
* Returns JobInformation of repeatable jobs (ordered descending). Provide a start and/or an end
* index to limit the number of results. Start defaults to 0, end to -1 and asc to false.
+8 -2
View File
@@ -1,8 +1,15 @@
import bytes = require('bytes');
// 1024*1024 = 1048576
console.log(bytes(undefined));
console.log(bytes(null));
console.log(bytes(104857));
console.log(bytes(104857, { thousandsSeparator: ' ' }));
console.log(bytes(104857, { decimalPlaces: 2 }));
console.log(bytes(104857, { fixedDecimals: true }));
console.log(bytes(104857, { unitSeparator: '-' }));
console.log(bytes(104857, { unit: 'GB' }));
console.log(bytes.format(104857));
console.log(bytes.format(104857, { thousandsSeparator: ' ' }));
@@ -10,8 +17,7 @@ console.log(bytes.format(104857, { decimalPlaces: 2 }));
console.log(bytes.format(104857, { fixedDecimals: true }));
console.log(bytes.format(104857, { unitSeparator: '-' }));
console.log(bytes.format(104857, { unit: 'GB' }));
console.log(bytes('1024kb'));
console.log(bytes(1024));
console.log(bytes('1024kb'));
console.log(bytes.parse('1024kb'));
console.log(bytes.parse(1024));
+16 -40
View File
@@ -1,66 +1,42 @@
// Type definitions for bytes v2.5.0
// Type definitions for bytes 3.0
// Project: https://github.com/visionmedia/bytes.js
// Definitions by: Zhiyuan Wang <https://github.com/danny8002>
// Rickard Laurin <https://github.com/believer>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface BytesOptions {
decimalPlaces?: number,
thousandsSeparator?: string,
unitSeparator?: string,
fixedDecimals?: boolean,
unit?: string
decimalPlaces?: number;
thousandsSeparator?: string;
unitSeparator?: string;
fixedDecimals?: boolean;
unit?: string;
}
/**
*Convert the given value in bytes into a string.
*
* @param {number} value
* @param {{
* thousandsSeparator: [string]
* }} [options] bytes options.
*
* @returns {string}
*/
declare function bytes(value: number, options?: { thousandsSeparator: string }): string;
/**
*Parse string to an integer in bytes.
*
* @param {string} value
* @returns {number}
* Convert the given value in bytes into a string.
*/
declare function bytes(value: number, options?: BytesOptions): string;
/**
* Parse string to an integer in bytes.
*/
declare function bytes(value: string): number;
declare namespace bytes {
/**
* Format the given value in bytes into a string.
*
* If the value is negative, take Math.abs(). If it is a float,
* it is rounded.
*
* @param {number} value
* @param {BytesFormatOptions} [options]
* If the value is negative, it is kept as such.
* If it is a float, it is rounded.
*/
function format(value: number, options?: BytesOptions): string;
/**
* Just return the input number value.
*
* @param {number} value
* @return {number}
*/
function parse(value: number): number;
/**
* Parse the string value into an integer in bytes.
*
* If no unit is given, it is assumed the value is in bytes.
*
* @param {string} value
* @return {number}
*/
function parse(value: string): number;
function parse(value: string | number): number;
}
export = bytes;
+1 -77
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"
}
@@ -0,0 +1,45 @@
import confetti = require("canvas-confetti");
confetti.Promise = null;
confetti();
confetti({
particleCount: 150
});
confetti({
spread: 180
});
confetti({
particleCount: 100,
startVelocity: 30,
spread: 360,
origin: {
x: Math.random(),
// since they fall down, start a bit higher than random
y: Math.random() - 0.2
}
});
confetti({
particleCount: 100,
spread: 70,
origin: {
y: 0.6
}
});
function r(min: number, max: number) {
return Math.random() * (max - min) + min;
}
confetti({
angle: r(55, 125),
spread: r(50, 70),
particleCount: r(50, 100),
origin: {
y: 0.6
}
});
+86
View File
@@ -0,0 +1,86 @@
// Type definitions for canvas-confetti 0.0
// Project: https://github.com/catdad/canvas-confetti#readme
// Definitions by: Martin Tracey <https://github.com/matracey>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* `confetti` takes a single optional object. When `window.Promise` is available, it will return a Promise to let you know when it is done. When promises are not available (like in IE), it will return
* `null`. You can polyfill promises using any of the popular polyfills. You can also provide a custom promise implementation to `confetti` through:
*
* `const MyPromise = require('some-promise-lib');
* const confetti = require('canvas-confetti');
* confetti.Promise = MyPromise;`
*
* If you call `confetti` multiple times before it is done, it
* will return the same promise every time. Internally, the same canvas element will be reused, continuing the existing animation with the new confetti added. The promise returned by each call to
* `confetti` will resolve once all animations are done.
*
*/
declare function confetti(options?: confetti.Options): Promise<null> | null;
declare namespace confetti {
/**
* You can polyfill promises using any of the popular polyfills. You can also provide a promise implementation to `confetti` through this property.
*/
let Promise: any;
interface Options {
/**
* The number of confetti to launch. More is always fun... but be cool, there's a lot of math involved.
* @default 50
*/
particleCount?: number;
/**
* The angle in which to launch the confetti, in degrees. 90 is straight up.
* @default 90
*/
angle?: number;
/**
* How far off center the confetti can go, in degrees. 45 means the confetti will launch at the defined angle plus or minus 22.5 degrees.
* @default 45
*/
spread?: number;
/**
* How fast the confetti will start going, in pixels.
* @default 45
*/
startVelocity?: number;
/**
* How quickly the confetti will lose speed. Keep this number between 0 and 1, otherwise the confetti will gain speed. Better yet, just never change it.
* @default 0.9
*/
decay?: number;
/**
* How many times the confetti will move. This is abstract... but play with it if the confetti disappear too quickly for you.
* @default 200
*/
ticks?: number;
/**
* Where to start firing confetti from. Feel free to launch off-screen if you'd like.
*/
origin?: Origin;
/**
* An array of color strings, in the HEX format... you know, like #bada55.
*/
colors?: string[];
/**
* The confetti should be on top, after all. But if you have a crazy high page, you can set it even higher.
* @default 100
*/
zIndex?: number;
}
interface Origin {
/**
* The x position on the page, with 0 being the left edge and 1 being the right edge.
* @default 0.5
*/
x?: number;
/**
* The y position on the page, with 0 being the left edge and 1 being the right edge.
* @default 0.5
*/
y?: number;
}
}
export = confetti;

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