Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Kamil Rojewski
2018-06-04 08:46:59 +02:00
25679 changed files with 1905709 additions and 726238 deletions
+1 -1
View File
@@ -1,9 +1,9 @@
root = true
[*]
indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true
[{*.json,*.yml}]
indent_style = space
indent_size = 2
+5
View File
@@ -1,2 +1,7 @@
# Auto detect text files and perform LF normalization
* text=auto
# Checkout NPM package files with forced LF lineendings
# to prevent git conflicts when running npm commands
package.json text eol=lf
package-lock.json text eol=lf
+4480
View File
File diff suppressed because it is too large Load Diff
+4
View File
@@ -1,5 +1,9 @@
If you know how to fix the issue, make a pull request instead.
- [ ] I tried using the `@types/xxxx` package and had problems.
- [ ] I tried using the latest stable version of tsc. https://www.npmjs.com/package/typescript
- [ ] I have a question that is inappropriate for [StackOverflow](https://stackoverflow.com/). (Please ask any appropriate questions there).
- [ ] [Mention](https://github.com/blog/821-mention-somebody-they-re-notified) the authors (see `Definitions by:` in `index.d.ts`) so they can respond.
- Authors: @....
If you do not mention the authors the issue will be ignored.
+4 -3
View File
@@ -2,6 +2,7 @@ Please fill in this template.
- [ ] Use a meaningful title for the pull request. Include the name of the package modified.
- [ ] Test the change in your own code. (Compile and run.)
- [ ] Add or edit tests to reflect the change. (Run with `npm test`.)
- [ ] Follow the advice from the [readme](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#make-a-pull-request).
- [ ] Avoid [common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#common-mistakes).
- [ ] Run `npm run lint package-name` (or `tsc` if no `tslint.json` is present).
@@ -9,15 +10,15 @@ Please fill in this template.
Select one of these and delete the others:
If adding a new definition:
- [ ] The package does not provide its own types, and you can not add them.
- [ ] The package does not already provide its own types, or cannot have its `.d.ts` files generated via `--declaration`
- [ ] If this is for an NPM package, match the name. If not, do not conflict with the name of an NPM package.
- [ ] Create it with `dts-gen --dt`, not by basing it on an existing project.
- [ ] `tslint.json` should be present, and `tsconfig.json` should have `noImplicitAny`, `noImplicitThis`, and `strictNullChecks` set to `true`.
- [ ] `tslint.json` should be present, and `tsconfig.json` should have `noImplicitAny`, `noImplicitThis`, `strictNullChecks`, and `strictFunctionTypes` set to `true`.
If changing an existing definition:
- [ ] Provide a URL to documentation or source code which provides context for the suggested changes: <<url here>>
- [ ] Increase the version number in the header if appropriate.
- [ ] If you are making substantial changes, consider adding a `tslint.json` containing `{ "extends": "dslint/dt.json" }`.
- [ ] If you are making substantial changes, consider adding a `tslint.json` containing `{ "extends": "dtslint/dt.json" }`.
If removing a declaration:
- [ ] If a package was never on DefinitelyTyped, you don't need to do anything. (If you wrote a package and provided types, you don't need to register it with us.)
+10 -2
View File
@@ -12,7 +12,6 @@
*.map
*.swp
.DS_Store
npm-debug.log
_Resharper.DefinitelyTyped
bin
@@ -25,19 +24,28 @@ Properties
# test folder
_infrastructure/tests/build
# IntelliJ based IDEs
.idea
*.iml
*.js.map
!*.js/
!scripts/new-package.js
!scripts/not-needed.js
!scripts/lint.js
# npm
node_modules
package-lock.json
npm-debug.log
# Sublime
.sublimets
.settings/launch.json
# Visual Studio Code
.settings/launch.json
.vs
.vscode
# yarn
yarn.lock
+1 -1
View File
@@ -1,6 +1,6 @@
language: node_js
node_js:
- node
- 8
sudo: false
+336
View File
@@ -0,0 +1,336 @@
# 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.
Si realiza cambios importantes, no olvide [actualizar una versión principal](#quiero-actualizar-un-paquete-a-una-nueva-versión-principal).
* También puede que quieras añadirte la sección "Definitions by" en el encabezado del paquete.
- 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)
+69 -10
View File
@@ -1,4 +1,4 @@
# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.png?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
# 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)
@@ -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
@@ -38,7 +38,7 @@ or just look for any ".d.ts" files in the package and manually include them with
These can be used by TypeScript 1.0.
* [Typings](https://github.com/typings/typings)
* ~~[NuGet](http://nuget.org/Tpackages?q=DefinitelyTyped)~~ (use preferred alternatives, nuget DT type publishing has been turned off)
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (use preferred alternatives, nuget DT type publishing has been turned off)
* Manually download from the `master` branch of this repository
You may need to add manual [references](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).
@@ -87,7 +87,9 @@ First, [fork](https://guides.github.com/activities/forking/) this repository, in
* `cd types/my-package-to-edit`
* Make changes. Remember to edit tests.
If you make breaking changes, do not forget to [update a major version](#i-want-to-update-a-package-to-a-new-major-version).
* You may also want to add yourself to "Definitions by" section of the package header.
- This will cause you to be notified (via your GitHub username) whenever someone makes a pull request or issue about the package.
- Do this by adding your name to the end of the line, as in `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
- Or if there are more people, it can be multiline
```typescript
@@ -96,7 +98,7 @@ First, [fork](https://guides.github.com/activities/forking/) this repository, in
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* `npm install -g typescript@2.0` and run `tsc`.
* If there is a `tslint.json`, run `npm run lint package-name`. Otherwise, run `tsc` in the package directory.
When you make a PR to edit an existing package, `dt-bot` should @-mention previous authors.
If it doesn't, you can do so yourself in the comment associated with the PR.
@@ -104,7 +106,7 @@ If it doesn't, you can do so yourself in the comment associated with the PR.
#### Create a new package
If you are the library author, or can make a pull request to the library, [bundle types](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) instead of publishing to DefinitelyTyped.
If you are the library author and your package is written in TypeScript, [bundle the autogenerated declaration files](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) in your package instead of publishing to DefinitelyTyped.
If you are adding typings for an NPM package, create a directory with the same name.
If the package you are adding typings for is not on NPM, make sure the name you choose for it does not conflict with the name of a package on NPM.
@@ -119,7 +121,7 @@ Your package should have this structure:
| tsconfig.json | This allows you to run `tsc` within the package. |
| tslint.json | Enables linting. |
Generate these by running `npm install -g dts-gen` and `dts-gen --dt --name my-package-name --template module`.
Generate these by running `npx dts-gen --dt --name my-package-name --template module` if you have npm ≥ 5.2.0, `npm install -g dts-gen` and `dts-gen --dt --name my-package-name --template module` otherwise.
See all options at [dts-gen](https://github.com/Microsoft/dts-gen).
You may edit the `tsconfig.json` to add new files, to add `"target": "es6"` (needed for async functions), to add to `"lib"`, or to add the `"jsx"` compiler option.
@@ -133,6 +135,7 @@ For a good example package, see [base64-js](https://github.com/DefinitelyTyped/D
* First, follow advice from the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html).
* Formatting: Either use all tabs, or always use 4 spaces.
* `function sum(nums: number[]): number`: Use `ReadonlyArray` if a function does not write to its parameters.
* `interface Foo { new(): Foo; }`:
This defines a type of objects that are new-able. You probably want `declare class Foo { constructor(); }`.
* `const Class: { new(): IClass; }`:
@@ -143,6 +146,10 @@ For a good example package, see [base64-js](https://github.com/DefinitelyTyped/D
Example where a type parameter is acceptable: `function id<T>(value: T): T;`.
Example where it is not acceptable: `function parseJson<T>(json: string): T;`.
Exception: `new Map<string, number>()` is OK.
* Using the types `Function` and `Object` is almost never a good idea. In 99% of cases it's possible to specify a more specific type. Examples are `(x: number) => number` for [functions](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) and `{ x: number, y: number }` for objects. If there is no certainty at all about the type, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) is the right choice, not `Object`. If the only known fact about the type is that it's some object, use the type [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), not `Object` or `{ [key: string]: any }`.
* `var foo: string | any`:
When `any` is used in a union type, the resulting type is still `any`. So while the `string` portion of this type annotation may _look_ useful, it in fact offers no additional typechecking over simply using `any`.
Depending on the intention, acceptable alternatives could be `any`, `string`, or `string | object`.
#### Removing a package
@@ -177,6 +184,18 @@ If a `tslint.json` turns rules off, this is because that hasn't been fixed yet.
(To indicate that a lint rule truly does not apply, use `// tslint:disable rule-name` or better, `//tslint:disable-next-line rule-name`.)
To assert that an expression is of a given type, use `$ExpectType`. To assert that an expression causes a compile error, use `$ExpectError`.
```js
// $ExpectType void
f(1);
// $ExpectError
f("one");
```
For more details, see [dtslint](https://github.com/Microsoft/dtslint#write-tests) readme.
Test by running `npm run lint package-name` where `package-name` is the name of your package.
This script uses [dtslint](https://github.com/Microsoft/dtslint).
@@ -186,7 +205,14 @@ This script uses [dtslint](https://github.com/Microsoft/dtslint).
#### What exactly is the relationship between this repository and the `@types` packages on NPM?
The `master` branch is automatically published to the `@types` scope on NPM thanks to [types-publisher](https://github.com/Microsoft/types-publisher).
This usually happens within an hour of changes being merged.
#### I've submitted a pull request. How long until it is merged?
It depends, but most pull requests will be merged within a week. PRs that have been approved by an author listed in the definition's header are usually merged more quickly; PRs for new definitions will take more time as they require more review from maintainers. Each PR is reviewed by a TypeScript or DefinitelyTyped team member before being merged, so please be patient as human factors may cause delays. Check the [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) to see progress as maintainers work through the open PRs.
#### My PR is merged; when will the `@types` NPM package be updated?
NPM packages should update within a few hours. If it's been more than 24 hours, ping @RyanCavanaugh and @andy-ms on the PR to investigate.
#### I'm writing a definition that depends on another definition. Should I use `<reference types="" />` or an import?
@@ -214,7 +240,8 @@ If types are part of a web standard, they should be contributed to [TSJS-lib-gen
#### A package uses `export =`, but I prefer to use default imports. Can I change `export =` to `export default`?
If default imports work in your environment, consider turning on the [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) compiler option.
If you are using TypeScript 2.7 or later, use `--esModuleInterop` in your project.
Otherwise, if default imports work in your environment (e.g. Webpack, SystemJS, esm), consider turning on the [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) compiler option.
Do not change the type definition if it is accurate.
For an NPM package, `export =` is accurate if `node -p 'require("foo")'` is the export, and `export default` is accurate if `node -p 'require("foo").default'` is the export.
@@ -231,7 +258,7 @@ When it graduates draft mode, we may remove it from DefinitelyTyped and deprecat
#### I want to update a package to a new major version
Before making your change, please create a new subfolder with the current version e.g. `v2`, and copy existing files to it. You will need to:
If you intend to continue updating the older version of the package, you may create a new subfolder with the current version e.g. `v2`, and copy existing files to it. If so, you will need to:
1. Update the relative paths in `tsconfig.json` as well as `tslint.json`.
2. Add path mapping rules to ensure that tests are running against the intended version.
@@ -254,21 +281,53 @@ For example [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/Defi
}
```
Please note that unless upgrading something backwards-compatible like `node`, all packages depending of the updated package need a path mapping to it, as well as packages depending on *those*.
If there are other packages on DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. You will also need to do this for packages depending on packages depending on the old version.
For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`;
transitively `react-router-bootstrap` (which depends on `react-router`) also adds a path mapping in its [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json).
Also, `/// <reference types=".." />` will not work with path mapping, so dependencies must use `import`.
#### How do I write definitions for packages that can be used globally and as a module?
The TypeScript handbook contains excellent [general information about writing definitions](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), and also [this example definition file](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) which shows how to create a definition using ES6-style module syntax, while also specifying objects made available to the global scope. This technique is demonstrated practically in the [definition for big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), which is a library that can be loaded globally via script tag on a web page, or imported via require or ES6-style imports.
To test how your definition can be used both when referenced globally or as an imported module, create a `test` folder, and place two test files in there. Name one `YourLibraryName-global.test.ts` and the other `YourLibraryName-module.test.ts`. The *global* test file should exercise the definition according to how it would be used in a script loaded on a web page where the library is available on the global scope - in this scenario you should not specify an import statement. The *module* test file should exercise the definition according to how it would be used when imported (including the `import` statement(s)). If you specify a `files` property in your `tsconfig.json` file, be sure to include both test files. A [practical example of this](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) is also available on the big.js definition.
Please note that it is not required to fully exercise the definition in each test file - it is sufficient to test only the globally-accessible elements on the global test file and fully exercise the definition in the module test file, or vice versa.
#### What about scoped packages?
Types for a scoped package `@foo/bar` should go in `types/foo__bar`. Note the double underscore.
When `dts-gen` is used to scaffold a scoped package, the `paths` property has to be manually adapted in the generated
`tsconfig.json` to correctly reference the scoped package:
```json
{
"paths":{
"@foo/bar": ["foo__bar"]
}
}
```
#### The file history in GitHub looks incomplete.
GitHub doesn't [support](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) file history for renamed files. Use [`git log --follow`](https://www.git-scm.com/docs/git-log) instead.
#### Should I add an empty namespace to a package that doesn't export a module to use ES6 style imports?
Some packages, like [chai-http](https://github.com/chaijs/chai-http), export a function.
Importing this module with an ES6 style import in the form `import * as foo from "foo";` leads to the error:
> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct
This error can be suppressed by merging the function declaration with an empty namespace of the same name, but this practice is discouraged.
This is a commonly cited [Stack Overflow answer](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) regarding this matter.
It is more appropriate to import the module using the `import foo = require("foo");` syntax, or to use a default import like `import foo from "foo";` if using the `--allowSyntheticDefaultImports` flag if your module runtime supports an interop scheme for non-ECMAScript modules as such.
## License
File diff suppressed because it is too large Load Diff
+25 -25
View File
@@ -1,27 +1,27 @@
{
"private": true,
"name": "definitely-typed",
"version": "0.0.1",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped",
"repository": {
"type": "git",
"url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues"
},
"engines": {
"node": ">=7.8.0"
},
"scripts": {
"compile-scripts": "tsc -p scripts",
"not-needed": "node scripts/not-needed.js",
"test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed --nProcesses 1",
"lint": "dtslint types"
},
"devDependencies": {
"dtslint": "Microsoft/dtslint#production",
"types-publisher": "Microsoft/types-publisher#production"
}
"private": true,
"name": "definitely-typed",
"version": "0.0.2",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped",
"repository": {
"type": "git",
"url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues"
},
"engines": {
"node": ">=7.8.0"
},
"scripts": {
"compile-scripts": "tsc -p scripts",
"not-needed": "node scripts/not-needed.js",
"test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed",
"lint": "dtslint types"
},
"devDependencies": {
"dtslint": "github:Microsoft/dtslint#production",
"types-publisher": "Microsoft/types-publisher#production"
}
}
+10 -1
View File
@@ -39,7 +39,16 @@ function fix(config: any): any {
const out: any = {};
for (const key in config) {
let value = config[key];
out[key] = value;
out[key] = key === "rules" ? fixRules(value) : value;
}
return out;
}
function fixRules(rules: any): any {
const out: any = {};
for (const key in rules) {
out[key] = rules[key];
}
return out;
}
+1 -5
View File
@@ -5,11 +5,7 @@
import * as fs from 'fs';
import * as path from 'path';
function repeat(s: string, count: number) {
return Array(count + 1).join(s);
}
const home = path.join(__dirname, '..');
const home = path.join(__dirname, "..", "types");
for (const dirName of fs.readdirSync(home)) {
if (dirName.startsWith(".") || dirName === "node_modules" || dirName === "scripts") {
@@ -1,50 +0,0 @@
import packer = require("3d-bin-packing");
import samchon = require("samchon");
function main(): void
{
///////////////////////////
// CONSTRUCT OBJECTS
///////////////////////////
let wrapperArray: bws.packer.WrapperArray = new packer.WrapperArray();
let instanceArray: bws.packer.InstanceArray = new packer.InstanceArray();
// Wrappers
wrapperArray.push
(
new packer.Wrapper("Large", 1000, 40, 40, 15, 0),
new packer.Wrapper("Medium", 700, 20, 20, 10, 0),
new packer.Wrapper("Small", 500, 15, 15, 8, 0)
);
///////
// Each Instance is repeated #15
///////
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Eraser", 1, 2, 5));
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Book", 15, 30, 3));
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Drink", 3, 3, 10));
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Umbrella", 5, 5, 20));
// Wrappers also can be packed into another Wrapper.
instanceArray.insert(instanceArray.end(), 15, new packer.Wrapper("Notebook-Box", 2000, 30, 40, 4, 2));
instanceArray.insert(instanceArray.end(), 15, new packer.Wrapper("Tablet-Box", 2500, 20, 28, 2, 0));
///////////////////////////
// BEGINS PACKING
///////////////////////////
// CONSTRUCT PACKER
let my_packer: bws.packer.Packer = new packer.Packer(wrapperArray, instanceArray);
///////
// PACK (OPTIMIZE)
let result: bws.packer.WrapperArray = my_packer.optimize();
///////
///////////////////////////
// TRACE PACKING RESULT
///////////////////////////
let xml: samchon.library.XML = result.toXML();
console.log(xml.toString());
}
main();
-1383
View File
File diff suppressed because it is too large Load Diff
-23
View File
@@ -1,23 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"3d-bin-packing-tests.ts"
]
}
@@ -0,0 +1,5 @@
import drawTriangle = require("a-big-triangle");
const gl = new WebGLRenderingContext();
drawTriangle(gl); // $ExpectType void
+8
View File
@@ -0,0 +1,8 @@
// Type definitions for a-big-triangle 1.0
// Project: https://github.com/mikolalysenko/a-big-triangle
// Definitions by: Mathias Paumgarten <https://github.com/MathiasPaumgarten>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function createABigTriangle(gl: WebGLRenderingContext): void;
export = createABigTriangle;
+24
View File
@@ -0,0 +1,24 @@
{
"files": [
"index.d.ts",
"a-big-triangle-tests.ts"
],
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
}
}
+13
View File
@@ -0,0 +1,13 @@
import abbrev = require('abbrev');
let abbrs: { [abbreviation: string]: string; };
abbrs = abbrev();
abbrs = abbrev('foo', 'fool', 'folding', 'flop');
abbrs = abbrev(['foo', 'fool', 'folding', 'flop']);
abbrev.monkeyPatch();
abbrs = [].abbrev();
const roArr: ReadonlyArray<string> = [];
abbrs = roArr.abbrev();
abbrs = ({}).abbrev();
+27
View File
@@ -0,0 +1,27 @@
// Type definitions for abbrev 1.1
// Project: https://github.com/isaacs/abbrev-js#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = abbrev;
declare function abbrev(words: string[]): {[abbreviation: string]: string};
declare function abbrev(...words: string[]): {[abbreviation: string]: string};
declare namespace abbrev {
function monkeyPatch(): void;
}
declare global {
interface Array<T> {
abbrev(): {[abbreviation: string]: string};
}
interface ReadonlyArray<T> {
abbrev(): {[abbreviation: string]: string};
}
interface Object {
abbrev(): {[abbreviation: 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",
"abbrev-tests.ts"
]
}
-253
View File
@@ -1,253 +0,0 @@
import * as Ably from 'ably';
declare const console: { log(message: any): void };
const ApiKey = 'appId.keyId:secret';
const client = new Ably.Realtime(ApiKey);
const restClient = new Ably.Rest(ApiKey);
// Connection
// Successful connection:
client.connection.on('connected', () => {
// successful connection
});
// Failed connection:
client.connection.on('failed', () => {
// failed connection
});
// Subscribing to a channel
const channel = client.channels.get('test');
channel.subscribe(message => {
message.name; // 'greeting'
message.data; // 'Hello World!'
});
// Only certain events:
channel.subscribe('myEvent', message => {
message.name; // 'myEvent'
message.data; // 'myData'
});
// Publishing to a channel
// Publish a single message with name and data
channel.publish('greeting', 'Hello World!');
// Optionally, you can use a callback to be notified of success or failure
channel.publish('greeting', 'Hello World!', err => {
if (err) {
console.log('publish failed with error ' + err);
} else {
console.log('publish succeeded');
}
});
// Publish several messages at once
channel.publish([{name: 'greeting', data: 'Hello World!'}], () => { });
// Querying the History
channel.history((err, messagesPage) => {
messagesPage.items; // array of Message
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(nextPage => { nextPage; }); // retrieves the next page as PaginatedResult
});
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
channel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards'}, (err, messagesPage) => {
console.log(messagesPage.items.length);
});
// Presence on a channel
// Getting presence:
channel.presence.get(presenceSet => {
presenceSet; // array of PresenceMessages
});
// Note that presence#get on a realtime channel does not return a PaginatedResult, as the library maintains a local copy of the presence set.
// Entering (and leaving) the presence set:
channel.presence.enter('my status', err => {
// now I am entered
});
channel.presence.update('new status', err => {
// my presence data is updated
});
channel.presence.leave(null, err => {
// I've left the presence set
});
channel.presence.enterClient('myClientId', 'status', err => {
});
// and similiarly, updateClient and leaveClient
// Querying the Presence History
channel.presence.history((err, messagesPage) => { // PaginatedResult
messagesPage.items; // array of PresenceMessage
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(nextPage => { }); // retrieves the next page as PaginatedResult
});
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
channel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {});
// Symmetrical end-to-end encrypted payloads on a channel
// When a 128 bit or 256 bit key is provided to the library, the data attributes of all messages are encrypted and decrypted automatically using that key.
// The secret key is never transmitted to Ably. See https://www.ably.io/documentation/realtime/encryption
// Generate a random 256-bit key for demonstration purposes (in
// practice you need to create one and distribute it to clients yourselves)
Ably.Realtime.Crypto.generateRandomKey((err, key) => {
const channel = client.channels.get('channelName', { cipher: { key } });
channel.subscribe(message => {
message.name; // 'name is not encrypted'
message.data; // 'sensitive data is encrypted'
});
channel.publish('name is not encrypted', 'sensitive data is encrypted');
});
// You can also change the key on an existing channel using setOptions (which takes a callback which is called after the new encryption settings have taken effect):
channel.setOptions({cipher: {key: '<KEY>'}}, () => {
// New encryption settings are in effect
});
// Using the REST API
const restChannel = restClient.channels.get('test');
// Publishing to a channel
// Publish a single message with name and data
restChannel.publish('greeting', 'Hello World!');
// Optionally, you can use a callback to be notified of success or failure
restChannel.publish('greeting', 'Hello World!', err => {
if (err) {
console.log('publish failed with error ' + err);
} else {
console.log('publish succeeded');
}
});
// Publish several messages at once
restChannel.publish([{name: 'greeting', data: 'Hello World!'}], () => {});
// Querying the History
restChannel.history((err, messagesPage) => {
messagesPage; // PaginatedResult
messagesPage.items; // array of Message
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(nextPage => {}); // retrieves the next page as PaginatedResult
});
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
restChannel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {});
// Presence on a channel
restChannel.presence.get((err, presencePage) => { // PaginatedResult
presencePage.items; // array of PresenceMessage
presencePage.items[0].data; // payload for first message
presencePage.items.length; // number of messages in the current page of members
presencePage.hasNext(); // true if there are further pages
presencePage.isLast(); // true if this page is the last page
presencePage.next(nextPage => {}); // retrieves the next page as PaginatedResult
});
// Querying the Presence History
restChannel.presence.history((err, messagesPage) => { // PaginatedResult
messagesPage.items; // array of PresenceMessage
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(nextPage => { }); // retrieves the next page as PaginatedResult
});
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
restChannel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {});
// Generate Token and Token Request
// See https://www.ably.io/documentation/general/authentication for an explanation of Ably's authentication mechanism.
// Requesting a token:
client.auth.requestToken((err, tokenDetails) => {
// tokenDetails is instance of TokenDetails
// see https://www.ably.io/documentation/rest/authentication/#token-details for its properties
// Now we have the token, we can send it to someone who can instantiate a client with it:
const clientUsingToken = new Ably.Realtime(tokenDetails.token);
});
// requestToken can take two optional params
// tokenParams: https://www.ably.io/documentation/rest/authentication/#token-params
// authOptions: https://www.ably.io/documentation/rest/authentication/#auth-options
client.auth.requestToken({}, {}, (err, tokenDetails) => { });
// Creating a token request (for example, on a server in response to a request by a client using the authCallback or authUrl mechanisms):
client.auth.createTokenRequest((err, tokenRequest) => {
// now send the tokenRequest back to the client, which will
// use it to request a token and connect to Ably
});
// createTokenRequest can take two optional params
// tokenParams: https://www.ably.io/documentation/rest/authentication/#token-params
// authOptions: https://www.ably.io/documentation/rest/authentication/#auth-options
client.auth.createTokenRequest({}, {}, (err, tokenRequest) => { });
// Fetching your application's stats
client.stats({ limit: 50 }, (err, statsPage) => { // statsPage as PaginatedResult
statsPage.items; // array of Stats
statsPage.items[0].inbound.rest.messages.count; // total messages published over REST
statsPage.items.length; // number of stats in the current page of history
statsPage.hasNext(); // true if there are wrther pages
statsPage.isLast(); // true if this page is the last page
statsPage.next((nextPage) => {}); // retrieves the next page as PaginatedResult
});
// Fetching the Ably service time
client.time({}, (err, time) => {}); // time is in ms since epoch
// Getting decoded Message objects from JSON
const messages = Ably.Realtime.Message.fromEncodedArray([{ id: 'foo' }]);
console.log(messages[0].id);
const message = Ably.Rest.Message.fromEncoded({ id: 'foo' });
console.log(message.id);
// Getting decoded PresenceMessage objects from JSON
const presenceMessages = Ably.Realtime.PresenceMessage.fromEncodedArray([{ id: 'foo' }]);
console.log(presenceMessages[0].action);
const presenceMessage = Ably.Rest.PresenceMessage.fromEncoded({ id: 'foo' });
console.log(presenceMessage.action);
-473
View File
@@ -1,473 +0,0 @@
// Type definitions for Ably Realtime and Rest client library 0.9
// Project: https://www.ably.io/
// Definitions by: Ably <https://github.com/ably/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export namespace ablyLib {
namespace ChannelState {
type INITIALIZED = 'initialized';
type ATTACHING = 'attaching';
type ATTACHED = "attached";
type DETACHING = "detaching";
type DETACHED = "detached";
type SUSPENDED = "suspended";
type FAILED = "failed";
}
type ChannelState = ChannelState.FAILED | ChannelState.INITIALIZED | ChannelState.SUSPENDED | ChannelState.ATTACHED | ChannelState.ATTACHING | ChannelState.DETACHED | ChannelState.DETACHING;
namespace ConnectionState {
type INITIALIZED = "initialized";
type CONNECTING = "connecting";
type CONNECTED = "connected";
type DISCONNECTED = "disconnected";
type SUSPENDED = "suspended";
type CLOSING = "closing";
type CLOSED = "closed";
type FAILED = "failed";
}
type ConnectionState = ConnectionState.INITIALIZED | ConnectionState.CONNECTED | ConnectionState.CONNECTING | ConnectionState.DISCONNECTED |
ConnectionState.SUSPENDED | ConnectionState.CLOSED | ConnectionState.CLOSING | ConnectionState.FAILED;
namespace ConnectionEvent {
type INITIALIZED = "initialized";
type CONNECTING = "connecting";
type CONNECTED = "connected";
type DISCONNECTED = "disconnected";
type SUSPENDED = "suspended";
type CLOSING = "closing";
type CLOSED = "closed";
type FAILED = "failed";
type UPDATE = "update";
}
type ConnectionEvent = ConnectionEvent.INITIALIZED | ConnectionEvent.CONNECTED | ConnectionEvent.CONNECTING | ConnectionEvent.DISCONNECTED |
ConnectionEvent.SUSPENDED | ConnectionEvent.CLOSED | ConnectionEvent.CLOSING | ConnectionEvent.FAILED | ConnectionEvent.UPDATE;
namespace PresenceAction {
type ABSENT = "absent";
type PRESENT = "present";
type ENTER = "enter";
type LEAVE = "leave";
type UPDATE = "update";
}
type PresenceAction = PresenceAction.ABSENT | PresenceAction.PRESENT | PresenceAction.ENTER | PresenceAction.LEAVE | PresenceAction.UPDATE;
namespace StatsIntervalGranularity {
type MINUTE = "minute";
type HOUR = "hour";
type DAY = "day";
type MONTH = "month";
}
type StatsIntervalGranularity = StatsIntervalGranularity.MINUTE | StatsIntervalGranularity.HOUR | StatsIntervalGranularity.DAY | StatsIntervalGranularity.MONTH;
namespace HTTPMethods {
type POST = "POST";
type GET = "GET";
}
type HTTPMethods = HTTPMethods.GET | HTTPMethods.POST;
// Interfaces
interface ClientOptions extends AuthOptions {
/**
* When true will automatically connect to Ably when library is instanced. This is true by default
*/
autoConnect?: boolean;
/**
* Optional clientId that can be used to specify the identity for this client. In most cases
* it is preferable to instead specift a clientId in the token issued to this client.
*/
clientId?: string;
defaultTokenParams?: TokenParams;
/**
* When true, messages published on channels by this client will be echoed back to this client.
* This is true by default
*/
echoMessages?: boolean;
/**
* Use this only if you have been provided a dedicated environment by Ably
*/
environment?: string;
/**
* Logger configuration
*/
log?: LogInfo;
port?: number;
/**
* When true, messages will be queued whilst the connection is disconnected. True by default.
*/
queueMessages?: boolean;
restHost?: string;
realtimeHost?: string;
fallbackHosts?: string[];
/**
* Can be used to explicitly recover a connection.
* See https://www.ably.io/documentation/realtime/connection#connection-state-recovery
*/
recover?: standardCallback | string;
/**
* Use a non-secure connection connection. By default, a TLS connection is used to connect to Ably
*/
tls?: boolean;
tlsPort?: number;
/**
* When true, the more efficient MsgPack binary encoding is used.
* When false, JSON text encoding is used.
*/
useBinaryProtocol?: boolean;
}
interface AuthOptions {
/**
* A function which is called when a new token is required.
* The role of the callback is to either generate a signed TokenRequest which may then be submitted automatically
* by the library to the Ably REST API requestToken; or to provide a valid token in as a TokenDetails object.
*/
authCallback?(data: TokenParams, callback: (error: ErrorInfo | string, tokenRequestOrDetails: TokenDetails | TokenRequest | string) => void): void;
authHeaders?: { [index: string]: string };
authMethod?: HTTPMethods;
authParams?: { [index: string]: string };
/**
* A URL that the library may use to obtain a token string (in plain text format), or a signed TokenRequest or TokenDetails (in JSON format).
*/
authUrl?: string;
key?: string;
queryTime?: boolean;
token?: TokenDetails | string;
tokenDetails?: TokenDetails;
useTokenAuth?: boolean;
}
interface TokenParams {
capability?: string;
clientId?: string;
nonce?: string;
timestamp?: number;
ttl?: number;
}
interface CipherParams {
algorithm: string;
key: any;
keyLength: number;
mode: string;
}
interface ErrorInfo {
code: number;
message: string;
statusCode: number;
}
interface StatsMessageCount {
count: number;
data: number;
}
interface StatsMessageTypes {
all: StatsMessageCount;
messages: StatsMessageCount;
presence: StatsMessageCount;
}
interface StatsRequestCount {
failed: number;
refused: number;
succeeded: number;
}
interface StatsResourceCount {
mean: number;
min: number;
opened: number;
peak: number;
refused: number;
}
interface StatsConnectionTypes {
all: StatsResourceCount;
plain: StatsResourceCount;
tls: StatsResourceCount;
}
interface StatsMessageTraffic {
all: StatsMessageTypes;
realtime: StatsMessageTypes;
rest: StatsMessageTypes;
webhook: StatsMessageTypes;
}
interface TokenDetails {
capability: string;
clientId?: string;
expires: number;
issued: number;
token: string;
}
interface TokenRequest {
capability: string;
clientId?: string;
keyName: string;
mac: string;
nonce: string;
timestamp: number;
ttl?: number;
}
interface ChannelOptions {
cipher: any;
}
interface RestPresenceHistoryParams {
start?: number;
end?: number;
direction?: string;
limit?: number;
}
interface RestPresenceParams {
limit?: number;
clientId?: string;
connectionId?: string;
}
interface RealtimePresenceParams {
waitForSync?: boolean;
clientId?: string;
connectionId?: string;
}
interface RealtimePresenceHistoryParams {
start?: number;
end?: number;
direction?: string;
limit?: number;
untilAttach?: boolean;
}
interface LogInfo {
/**
* A number controlling the verbosity of the output. Valid values are: 0 (no logs), 1 (errors only),
* 2 (errors plus connection and channel state changes), 3 (high-level debug output), and 4 (full debug output).
*/
level?: number;
/**
* A function to handle each line of log output. If handler is not specified, console.log is used.
*/
handler?(...args: any[]): void;
}
interface ChannelEvent {
state: ChannelState;
}
interface ChannelStateChange {
current: ChannelState;
previous: ChannelState;
reason?: ErrorInfo;
resumed: boolean;
}
interface ConnectionStateChange {
current: ConnectionState;
previous: ConnectionState;
reason?: ErrorInfo;
retryIn?: number;
}
// Common Listeners
type paginatedResultCallback<T> = (error: ErrorInfo, results: PaginatedResult<T> ) => void;
type standardCallback = (error: ErrorInfo, results: any) => void;
type messageCallback<T> = (message: T) => void;
type errorCallback = (error: ErrorInfo) => void;
type channelEventCallback = (channelEvent: ChannelEvent, changeStateChange: ChannelStateChange) => void;
type connectionEventCallback = (connectionEvent: ConnectionEvent, connectionStateChange: ConnectionStateChange) => void;
type timeCallback = (error: ErrorInfo, time: number) => void;
type realtimePresenceGetCallback = (error: ErrorInfo, messages: PresenceMessage[]) => void;
type tokenDetailsCallback = (error: ErrorInfo, Results: TokenDetails) => void;
type tokenRequestCallback = (error: ErrorInfo, Results: TokenRequest) => void;
type fromEncoded<T> = (JsonObject: any, channelOptions?: ChannelOptions) => T;
type fromEncodedArray<T> = (JsonArray: any[], channelOptions?: ChannelOptions) => T[];
// Internal Classes
class EventEmitter<T> {
on: (eventOrCallback: string | T, callback?: T) => void;
once: (eventOrCallback: string | T, callback?: T) => void;
off: (eventOrCallback?: string | T, callback?: T) => void;
}
// Classes
class Auth {
clientId: string;
authorize: (tokenParams?: TokenParams | tokenDetailsCallback, authOptions?: AuthOptions | tokenDetailsCallback, callback?: tokenDetailsCallback) => void;
createTokenRequest: (tokenParams?: TokenParams | tokenRequestCallback, authOptions?: AuthOptions | tokenRequestCallback, callback?: tokenRequestCallback) => void;
requestToken: (TokenParams?: TokenParams | tokenDetailsCallback, authOptions?: AuthOptions | tokenDetailsCallback, callback?: tokenDetailsCallback) => void;
}
class Presence {
get: (params: RestPresenceParams | paginatedResultCallback<PresenceMessage>, callback?: paginatedResultCallback<PresenceMessage>) => void;
history: (params: RestPresenceHistoryParams | paginatedResultCallback<PresenceMessage>, callback?: paginatedResultCallback<PresenceMessage>) => void;
}
class RealtimePresence {
syncComplete: () => boolean;
get: (Params: realtimePresenceGetCallback | RealtimePresenceParams, callback?: realtimePresenceGetCallback) => void;
history: (ParamsOrCallback: RealtimePresenceHistoryParams | paginatedResultCallback<PresenceMessage>, callback?: paginatedResultCallback<PresenceMessage>) => void;
subscribe: (presenceOrCallback: PresenceAction | messageCallback<PresenceMessage>, listener?: messageCallback<PresenceMessage>) => void;
unsubscribe: (presence?: PresenceAction, listener?: messageCallback<PresenceMessage>) => void;
enter: (data?: errorCallback | any, callback?: errorCallback) => void;
update: (data?: errorCallback | any, callback?: errorCallback) => void;
leave: (data?: errorCallback | any, callback?: errorCallback) => void;
enterClient: (clientId: string, data?: errorCallback | any, callback?: errorCallback) => void;
updateClient: (clientId: string, data?: errorCallback | any, callback?: errorCallback) => void;
leaveClient: (clientId: string, data?: errorCallback | any, callback?: errorCallback) => void;
}
class Channel {
name: string;
presence: Presence;
history: (paramsOrCallback?: RestPresenceHistoryParams | paginatedResultCallback<Message>, callback?: paginatedResultCallback<Message>) => void;
publish: (messagesOrName: any, messagedataOrCallback?: errorCallback | any, callback?: errorCallback) => void;
}
class RealtimeChannel extends EventEmitter<channelEventCallback> {
name: string;
errorReason: ErrorInfo;
state: ChannelState;
presence: RealtimePresence;
attach: (callback?: standardCallback) => void;
detach: (callback?: standardCallback) => void;
history: (paramsOrCallback?: RealtimePresenceHistoryParams | paginatedResultCallback<Message>, callback?: paginatedResultCallback<Message>) => void;
subscribe: (eventOrCallback: messageCallback<Message> | string, listener?: messageCallback<Message>) => void;
unsubscribe: (eventOrCallback?: messageCallback<Message> | string, listener?: messageCallback<Message>) => void;
publish: (messagesOrName: any, messageDataOrCallback?: errorCallback | any, callback?: errorCallback) => void;
setOptions: (options: any, callback?: errorCallback) => void;
}
class Channels<T> {
get: (name: string, channelOptions?: ChannelOptions) => T;
release: (name: string) => void;
}
class Message {
constructor();
static fromEncoded: fromEncoded<Message>;
static fromEncodedArray: fromEncodedArray<Message>;
clientId: string;
connectionId: string;
data: any;
encoding: string;
extras: any;
id: string;
name: string;
timestamp: number;
}
interface MessageStatic {
fromEncoded: fromEncoded<Message>;
fromEncodedArray: fromEncodedArray<Message>;
}
class PresenceMessage {
constructor();
static fromEncoded: fromEncoded<PresenceMessage>;
static fromEncodedArray: fromEncodedArray<PresenceMessage>;
action: PresenceAction;
clientId: string;
connectionId: string;
data: any;
encoding: string;
id: string;
timestamp: number;
}
interface PresenceMessageStatic {
fromEncoded: fromEncoded<PresenceMessage>;
fromEncodedArray: fromEncodedArray<PresenceMessage>;
}
interface Crypto {
generateRandomKey(callback: (error: ErrorInfo, key: string) => void): void;
}
class Connection extends EventEmitter<connectionEventCallback> {
errorReason: ErrorInfo;
id: string;
key: string;
recoveryKey: string;
serial: number;
state: ConnectionState;
close: () => void;
connect: () => void;
ping: (callback?: (error: ErrorInfo, responseTime: number ) => void ) => void;
}
class Stats {
all: StatsMessageTypes;
apiRequests: StatsRequestCount;
channels: StatsResourceCount;
connections: StatsConnectionTypes;
inbound: StatsMessageTraffic;
intervalId: string;
outbound: StatsMessageTraffic;
persisted: StatsMessageTypes;
tokenRequests: StatsRequestCount;
}
class PaginatedResult<T> {
items: T[];
first: (results: paginatedResultCallback<T>) => void;
next: (results: paginatedResultCallback<T>) => void;
current: (results: paginatedResultCallback<T>) => void;
hasNext: () => boolean;
isLast: () => boolean;
}
class HttpPaginatedResponse extends PaginatedResult<any> {
items: string[];
statusCode: number;
success: boolean;
errorCode: number;
errorMessage: string;
headers: any;
}
}
export class Rest {
constructor(options: ablyLib.ClientOptions | string);
static Crypto: ablyLib.Crypto;
static Message: ablyLib.MessageStatic;
static PresenceMessage: ablyLib.PresenceMessageStatic;
auth: ablyLib.Auth;
channels: ablyLib.Channels<ablyLib.Channel>;
request: (method: string, path: string, params?: any, body?: any[] | any, headers?: any, callback?: (error: ablyLib.ErrorInfo, response: ablyLib.HttpPaginatedResponse) => void) => void;
stats: (paramsOrCallback?: ablyLib.paginatedResultCallback<ablyLib.Stats> | any, callback?: ablyLib.paginatedResultCallback<ablyLib.Stats>) => void;
time: (paramsOrCallback?: ablyLib.timeCallback | any, callback?: ablyLib.timeCallback) => void;
}
export class Realtime {
constructor(options: ablyLib.ClientOptions | string);
static Crypto: ablyLib.Crypto;
static Message: ablyLib.MessageStatic;
static PresenceMessage: ablyLib.PresenceMessageStatic;
auth: ablyLib.Auth;
channels: ablyLib.Channels<ablyLib.RealtimeChannel>;
clientId: string;
connection: ablyLib.Connection;
request: (method: string, path: string, params?: any, body?: any[] | any, headers?: any, callback?: (error: ablyLib.ErrorInfo, response: ablyLib.HttpPaginatedResponse) => void) => void;
stats: (paramsOrCallback?: ablyLib.paginatedResultCallback<ablyLib.Stats> | any, callback?: ablyLib.paginatedResultCallback<ablyLib.Stats>) => void;
close: () => void;
connect: () => void;
time: (paramsOrCallback?: ablyLib.timeCallback | any, callback?: ablyLib.timeCallback) => void;
}
-22
View File
@@ -1,22 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"ably-tests.ts"
]
}
+1
View File
@@ -7,6 +7,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+1
View File
@@ -7,6 +7,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+79
View File
@@ -0,0 +1,79 @@
{
"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
}
}
+2 -1
View File
@@ -2,6 +2,7 @@
// Project: https://github.com/sathomas/acc-wizard
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
interface AccWizardOptions {
/**
@@ -110,4 +111,4 @@ interface AccWizardOptions {
*/
interface JQuery {
accwizard(options?: AccWizardOptions): void;
}
}
+1
View File
@@ -8,6 +8,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+79
View File
@@ -0,0 +1,79 @@
{
"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
}
}
@@ -0,0 +1,31 @@
// https://github.com/opentable/accept-language-parser/blob/v1.5.0/index.js
import * as AcceptLanguageParser from 'accept-language-parser';
const l1: AcceptLanguageParser.Language = {
code: 'en',
script: 'Latn',
region: 'GB',
quality: 0.9
};
const l2: AcceptLanguageParser.Language = {
code: 'en',
quality: 0.9
};
const l3: AcceptLanguageParser.Language = {
code: 'en',
script: null,
quality: 0.9
};
const parsed1: AcceptLanguageParser.Language[] = AcceptLanguageParser.parse('');
const pick1: string | null = AcceptLanguageParser.pick([''], '');
const pick2: string | null = AcceptLanguageParser.pick([''], [l1, l2, l3]);
const pick3: string | null = AcceptLanguageParser.pick([''], '', {});
const pick4: string | null = AcceptLanguageParser.pick([''], '', { loose: true });
const pickOptions: AcceptLanguageParser.PickOptions = {
loose: true
};
+25
View File
@@ -0,0 +1,25 @@
// Type definitions for accept-language-parser 1.5
// Project: https://github.com/opentable/accept-language-parser
// Definitions by: Niklas Wulf <https://github.com/kampfgnom>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
// https://github.com/opentable/accept-language-parser/blob/v1.4.1/index.js
export function parse(acceptLanguage: string): Language[];
export function pick(
supportedLanguages: string[],
acceptLanguage: string | Language[],
options?: PickOptions
): string | null;
export interface Language {
code: string;
script?: string | null;
region?: string;
quality: number;
}
export interface PickOptions {
loose?: boolean;
}
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"accept-language-parser-tests.ts"
]
}
+53 -15
View File
@@ -1,62 +1,100 @@
// Type definitions for accepts 1.3
// Project: https://github.com/jshttp/accepts
// Definitions by: Stefan Reichel <https://github.com/bomret>
// Brice BERNARD <https://github.com/brikou>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace accepts {
interface Headers {
[key: string]: string | string[];
}
/// <reference types="node" />
import { IncomingMessage } from "http";
declare namespace accepts {
interface Accepts {
/**
* Return the first accepted charset. If nothing in `charsets` is accepted, then `false` is returned.
* If no charsets are supplied, all accepted charsets are returned, in the order of the client's preference
* (most preferred first).
*/
charset(): string[];
charset(charsets: string[]): string | false;
charset(...charsets: string[]): string | false;
/**
* Return the charsets that the request accepts, in the order of the client's preference (most preferred first).
* Return the first accepted charset. If nothing in `charsets` is accepted, then `false` is returned.
* If no charsets are supplied, all accepted charsets are returned, in the order of the client's preference
* (most preferred first).
*/
charsets(): string[];
charsets(charsets: string[]): string | false;
charsets(...charsets: string[]): string | false;
/**
* Return the first accepted encoding. If nothing in `encodings` is accepted, then `false` is returned.
* If no encodings are supplied, all accepted encodings are returned, in the order of the client's preference
* (most preferred first).
*/
encoding(): string[];
encoding(encodings: string[]): string | false;
encoding(...encodings: string[]): string | false;
/**
* Return the encodings that the request accepts, in the order of the client's preference (most preferred first).
* Return the first accepted encoding. If nothing in `encodings` is accepted, then `false` is returned.
* If no encodings are supplied, all accepted encodings are returned, in the order of the client's preference
* (most preferred first).
*/
encodings(): string[];
encodings(encodings: string[]): string | false;
encodings(...encodings: string[]): string | false;
/**
* Return the first accepted language. If nothing in `languages` is accepted, then `false` is returned.
* If no languaes are supplied, all accepted languages are returned, in the order of the client's preference
* (most preferred first).
*/
language(): string[];
language(languages: string[]): string | false;
language(...languages: string[]): string | false;
/**
* Return the languages that the request accepts, in the order of the client's preference (most preferred first).
* Return the first accepted language. If nothing in `languages` is accepted, then `false` is returned.
* If no languaes are supplied, all accepted languages are returned, in the order of the client's preference
* (most preferred first).
*/
languages(): string[];
languages(languages: string[]): string | false;
languages(...languages: string[]): string | false;
/**
* Return the first accepted language. If nothing in `languages` is accepted, then `false` is returned.
* If no languaes are supplied, all accepted languages are returned, in the order of the client's preference
* (most preferred first).
*/
lang(): string[];
lang(languages: string[]): string | false;
lang(...languages: string[]): string | false;
/**
* Return the first accepted language. If nothing in `languages` is accepted, then `false` is returned.
* If no languaes are supplied, all accepted languages are returned, in the order of the client's preference
* (most preferred first).
*/
langs(): string[];
langs(languages: string[]): string | false;
langs(...languages: string[]): string | false;
/**
* Return the first accepted type (and it is returned as the same text as what appears in the `types` array). If nothing in `types` is accepted, then `false` is returned.
* If no types are supplied, return the entire set of acceptable types.
*
* The `types` array can contain full MIME types or file extensions. Any value that is not a full MIME types is passed to `require('mime-types').lookup`.
*/
type(types: string[]): string | false;
type(...types: string[]): string | false;
/**
* Return the types that the request accepts, in the order of the client's preference (most preferred first).
*/
types(): string[];
type(types: string[]): string[] | string | false;
type(...types: string[]): string[] | string | false;
types(types: string[]): string[] | string | false;
types(...types: string[]): string[] | string | false;
}
}
declare function accepts(req: { headers: accepts.Headers }): accepts.Accepts;
declare function accepts(req: IncomingMessage): accepts.Accepts;
export = accepts;
+1
View File
@@ -7,6 +7,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+3
View File
@@ -3,6 +3,9 @@
// Default usage:
accounting.formatMoney(12345678); // $12,345,678.00
// Stringified usage:
accounting.formatMoney('$4394958309392.9401'); // $4,394,958,309,392.94
// European formatting (custom symbol and separators), could also use options object as second param:
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
+7 -6
View File
@@ -1,6 +1,7 @@
// Type definitions for accounting.js 0.3
// Project: http://josscrowcroft.github.io/accounting.js/
// Definitions by: Sergey Gerasimov <https://github.com/gerich-home/>
// Type definitions for accounting.js 0.4
// Project: http://openexchangerates.github.io/accounting.js/
// Definitions by: Sergey Gerasimov <https://github.com/gerich-home>
// Christopher Eck <https://github.com/chrisleck>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace accounting {
@@ -30,9 +31,9 @@ declare namespace accounting {
}
interface Static {
// format any number into currency
formatMoney(number: number, symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string;
formatMoney(number: number, options: CurrencySettings<string> | CurrencySettings<CurrencyFormat>): string;
// format any number or stringified number into currency
formatMoney(number: number | string, symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string;
formatMoney(number: number | string, options: CurrencySettings<string> | CurrencySettings<CurrencyFormat>): string;
formatMoney(numbers: number[], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string[];
formatMoney(numbers: number[], options: CurrencySettings<string> | CurrencySettings<CurrencyFormat>): string[];
+1
View File
@@ -7,6 +7,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+22
View File
@@ -0,0 +1,22 @@
import AceDiff = require('ace-diff');
new AceDiff(); // $ExpectError
const aceDiffConstructorOpts = {
element: '.acediff',
left: { content: 'left content' },
right: { content: 'right content' },
};
new AceDiff(aceDiffConstructorOpts); // $ExpectType AceDiff
const differ = new AceDiff(aceDiffConstructorOpts);
differ.getEditors(); // $ExpectType { left: any; right: any; }
differ.setOptions(); // $ExpectError
const aceDiffOpts = {
diffGranularity: 'broad' as 'broad', // workaround: cast to avoid https://github.com/Microsoft/TypeScript/issues/11465#issuecomment-252453037
};
differ.setOptions(aceDiffOpts); // $ExpectType void
differ.getNumDiffs(); // $ExpectType number
differ.diff(); // $ExpectType void
differ.destroy(); // $ExpectType void
+52
View File
@@ -0,0 +1,52 @@
// Type definitions for ace-diff 2.1
// Project: https://ace-diff.github.io/ace-diff/
// Definitions by: Mike Dodge <https://github.com/innovation-team>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export as namespace AceDiff;
export = AceDiff;
declare class AceDiff {
constructor(opts: AceDiff.AceDiffConstructorOpts);
getEditors(): {
left: any;
right: any;
};
setOptions(options: AceDiff.AceDiffOpts): void;
getNumDiffs(): number;
diff(): void;
destroy(): void;
}
declare namespace AceDiff {
interface AceDiffLROpts {
content?: string | null;
mode?: string;
theme?: string;
editable?: boolean;
copyLinkEnabled?: boolean;
}
interface AceDiffConstructorOpts extends AceDiffOpts {
element: string | HTMLElement;
left: AceDiffLROpts;
right: AceDiffLROpts;
}
interface AceDiffOpts {
mode?: string;
theme?: string;
diffGranularity?: 'specific' | 'broad';
showDiffs?: boolean;
showConnectors?: boolean;
maxDiffs?: number;
left?: AceDiffLROpts;
right?: AceDiffLROpts;
classes?: {
diff: string;
connector: string;
newCodeConnectorLinkContent: string;
deletedCodeConnectorLinkContent: string;
};
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"ace-diff-tests.ts"
]
}
+127 -35
View File
@@ -52,6 +52,10 @@ declare namespace AceAjax {
export interface TokenInfo {
value: string;
index?: number;
start?: number;
}
export interface Position {
@@ -97,6 +101,29 @@ declare namespace AceAjax {
transformAction(state: any, action: any, editor: any, session: any, param: any): any;
}
export interface OptionProvider {
/**
* Sets a Configuration Option
**/
setOption(optionName: string, optionValue: any): void;
/**
* Sets Configuration Options
**/
setOptions(keyValueTuples: any): void;
/**
* Get a Configuration Option
**/
getOption(name: string):any;
/**
* Get Configuration Options
**/
getOptions():any;
}
////////////////
/// Ace
////////////////
@@ -345,18 +372,47 @@ declare namespace AceAjax {
insert(position: Position, text: string): any;
/**
* Inserts the elements in `lines` into the document, starting at the row index given by `row`. This method also triggers the `'change'` event.
* @param row The index of the row to insert at
* @param lines An array of strings
**/
* @deprecated Use the insertFullLines method instead.
*/
insertLines(row: number, lines: string[]): any;
/**
* Inserts a new line into the document at the current row's `position`. This method also triggers the `'change'` event.
* @param position The position to insert at
**/
* Inserts the elements in `lines` into the document as full lines (does not merge with existing line), starting at the row index given by `row`. This method also triggers the `"change"` event.
* @param {Number} row The index of the row to insert at
* @param {Array} lines An array of strings
* @returns {Object} Contains the final row and column, like this:
* ```
* {row: endRow, column: 0}
* ```
* If `lines` is empty, this function returns an object containing the current row, and column, like this:
* ```
* {row: row, column: 0}
* ```
*
**/
insertFullLines(row: number, lines: string[]): any;
/**
* @deprecated Use insertMergedLines(position, ['', '']) instead.
*/
insertNewLine(position: Position): any;
/**
* Inserts the elements in `lines` into the document, starting at the position index given by `row`. This method also triggers the `"change"` event.
* @param {Number} row The index of the row to insert at
* @param {Array} lines An array of strings
* @returns {Object} Contains the final row and column, like this:
* ```
* {row: endRow, column: 0}
* ```
* If `lines` is empty, this function returns an object containing the current row, and column, like this:
* ```
* {row: row, column: 0}
* ```
*
**/
insertMergedLines(row: number, lines: string[]): any;
/**
* Inserts `text` into the `position` at the current row. This method also triggers the `'change'` event.
* @param position The position to insert at
@@ -379,12 +435,19 @@ declare namespace AceAjax {
removeInLine(row: number, startColumn: number, endColumn: number): any;
/**
* Removes a range of full lines. This method also triggers the `'change'` event.
* @param firstRow The first row to be removed
* @param lastRow The last row to be removed
**/
* @deprecated Use the removeFullLines method instead.
*/
removeLines(firstRow: number, lastRow: number): string[];
/**
* Removes a range of full lines. This method also triggers the `"change"` event.
* @param {Number} firstRow The first row to be removed
* @param {Number} lastRow The last row to be removed
* @returns {[String]} Returns all the removed lines.
*
**/
removeFullLines(firstRow: number, lastRow: number): string[];
/**
* Removes the new line between `row` and the row immediately following it. This method also triggers the `'change'` event.
* @param row The row to check
@@ -455,7 +518,7 @@ declare namespace AceAjax {
* Stores all the data about [[Editor `Editor`]] state providing easy way to change editors state.
* `EditSession` can be attached to only one [[Document `Document`]]. Same `Document` can be attached to several `EditSession`s.
**/
export interface IEditSession {
export interface IEditSession extends OptionProvider {
selection: Selection;
@@ -475,6 +538,8 @@ declare namespace AceAjax {
expandFold(arg: any): void;
foldAll(startRow?: number, endRow?: number, depth?: number): void
unfold(arg1: any, arg2: boolean): void;
screenToDocumentColumn(row: number, column: number): void;
@@ -537,7 +602,7 @@ declare namespace AceAjax {
* @param row The row number to retrieve from
* @param column The column number to retrieve from
**/
getTokenAt(row: number, column: number): TokenInfo;
getTokenAt(row: number, column: number): TokenInfo|null;
/**
* Sets the undo manager.
@@ -1032,13 +1097,19 @@ declare namespace AceAjax {
* The `Editor` manages the [[EditSession]] (which manages [[Document]]s), as well as the [[VirtualRenderer]], which draws everything to the screen.
* Event sessions dealing with the mouse and keyboard are bubbled up from `Document` to the `Editor`, which decides what to do with them.
**/
export interface Editor {
export interface Editor extends OptionProvider {
on(ev: string, callback: (e: any) => any): void;
addEventListener(ev: 'change', callback: (ev: EditorChangeEvent) => any): void;
addEventListener(ev: string, callback: Function): void;
off(ev: string, callback: Function): void;
removeListener(ev: string, callback: Function): void;
removeEventListener(ev: string, callback: Function): void;
inMultiSelectMode: boolean;
selectMoreLines(n: number): void;
@@ -1065,26 +1136,6 @@ declare namespace AceAjax {
execCommand(command:string, args?: any): void;
/**
* Sets a Configuration Option
**/
setOption(optionName: any, optionValue: any): void;
/**
* Sets Configuration Options
**/
setOptions(keyValueTuples: any): void;
/**
* Get a Configuration Option
**/
getOption(name: any):any;
/**
* Get Configuration Options
**/
getOptions():any;
/**
* Get rid of console warning by setting this to Infinity
**/
@@ -2164,8 +2215,16 @@ declare namespace AceAjax {
**/
export interface Selection {
on(ev: string, callback: Function): void;
addEventListener(ev: string, callback: Function): void;
off(ev: string, callback: Function): void;
removeListener(ev: string, callback: Function): void;
removeEventListener(ev: string, callback: Function): void;
moveCursorWordLeft(): void;
moveCursorWordRight(): void;
@@ -2636,7 +2695,7 @@ declare namespace AceAjax {
/**
* The class that is responsible for drawing everything you see on the screen!
**/
export interface VirtualRenderer {
export interface VirtualRenderer extends OptionProvider {
scroller: any;
@@ -2644,6 +2703,8 @@ declare namespace AceAjax {
lineHeight: number;
setScrollMargin(top:number, bottom:number, left: number, right: number): void;
screenToTextCoordinates(left: number, top: number): void;
/**
@@ -2978,6 +3039,37 @@ declare namespace AceAjax {
**/
new(container: HTMLElement, theme?: string): VirtualRenderer;
}
export interface Completer {
/**
* Provides possible completion results asynchronously using the given callback.
* @param editor The editor to associate with
* @param session The `EditSession` to refer to
* @param pos An object containing the row and column
* @param prefix The prefixing string before the current position
* @param callback Function to provide the results or error
*/
getCompletions: (editor: Editor, session: IEditSession, pos: Position, prefix: string, callback: CompletionCallback) => void;
/**
* Provides tooltip information about a completion result.
* @param item The completion result
*/
getDocTooltip?: (item: Completion) => void;
}
export interface Completion {
value: string;
meta: string;
type?: string;
caption?: string;
snippet?: any;
score?: number;
exactMatch?: number;
docHTML?: string;
}
export type CompletionCallback = (error: Error, results: Completion[]) => void;
}
declare var ace: AceAjax.Ace;
+1
View File
@@ -15,6 +15,7 @@ const aceVirtualRendererTests = {
var renderer = new AceAjax.VirtualRenderer(el);
renderer.setPadding(0);
renderer.setScrollMargin(0,0,0,0)
renderer.setSession(new AceAjax.EditSession("1234"));
var r = renderer.scroller.getBoundingClientRect();
+1
View File
@@ -8,6 +8,7 @@
"noImplicitAny": false,
"noImplicitThis": false,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+79
View File
@@ -0,0 +1,79 @@
{
"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
}
}
+5 -1
View File
@@ -2,6 +2,7 @@
// Project: https://github.com/optimalbits/node_acl
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="bluebird" />
/// <reference types="node"/>
@@ -49,7 +50,10 @@ interface Acl {
allowedPermissions: (userId: Value, resources: strings, cb?: AnyCallback) => Promise<void>;
isAllowed: (userId: Value, resources: strings, permissions: strings, cb?: AllowedCallback) => Promise<boolean>;
areAnyRolesAllowed: (roles: strings, resource: strings, permissions: strings, cb?: AllowedCallback) => Promise<any>;
whatResources: (roles: strings, permissions: strings, cb?: AnyCallback) => Promise<any>;
whatResources: {
(roles: strings, cb?: AnyCallback): Promise<any>;
(roles: strings, permissions: strings, cb?: AnyCallback): Promise<any>;
}
permittedResources: (roles: strings, permissions: strings, cb?: Function) => Promise<void>;
middleware: (numPathComponents?: number, userId?: Value | GetUserId, actions?: strings) => express.RequestHandler;
}
+12
View File
@@ -66,6 +66,18 @@ acl.isAllowed('joed', 'blogs', 'view', (err, res) => {
}
});
acl.whatResources('foo', (err, res) => {
if (res) {
console.log(res);
}
});
acl.whatResources('foo', 'view', (err, res) => {
if (res) {
console.log(res);
}
});
acl.isAllowed('jsmith', 'blogs', ['edit','view','delete'])
.then((result) => {
console.dir('jsmith is allowed blogs ' + result);
+1
View File
@@ -7,6 +7,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+79
View File
@@ -0,0 +1,79 @@
{
"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
}
}
+12 -17
View File
@@ -1,13 +1,13 @@
import acorn = require('acorn');
import * as ESTree from 'estree';
declare var token: acorn.Token;
declare var tokens: acorn.Token[];
declare var comment: acorn.Comment;
declare var comments: acorn.Comment[];
declare var program: ESTree.Program;
var any: any;
var string: string;
declare let token: acorn.Token;
declare let tokens: acorn.Token[];
declare let comment: acorn.Comment;
declare let comments: acorn.Comment[];
declare let program: ESTree.Program;
let any: any;
let string: string;
// acorn
string = acorn.version;
@@ -32,16 +32,12 @@ const parser = new acorn.Parser({}, 'export default ""', 0);
const node = new acorn.Node(parser, 1, 1);
class LooseParser {
constructor(input: string, options = {}) {
}
constructor(input: string, options = {}) {}
// this means you can extend LooseParser
test() {
}
test() {}
}
acorn.addLooseExports(function () {
acorn.addLooseExports(() => {
return {
type: 'Program',
sourceType: 'script',
@@ -50,7 +46,7 @@ acorn.addLooseExports(function () {
type: 'EmptyStatement'
}
]
}
};
}, LooseParser, {});
acorn.parseExpressionAt('string', 2);
@@ -63,8 +59,7 @@ acorn.isIdentifierChar(56);
acorn.getLineInfo('string', 56);
acorn.plugins['test'] = function (p: acorn.Parser, config: any) {
}
acorn.plugins['test'] = (p: acorn.Parser, config: any) => {};
acorn.tokenizer('console.log("hello world)', {locations: true}).getToken();
acorn.tokenizer('console.log("hello world)', {locations: true})[Symbol.iterator]().next();
+9 -14
View File
@@ -1,10 +1,8 @@
// Type definitions for Acorn v4.0.3
// Type definitions for Acorn 4.0
// Project: https://github.com/marijnh/acorn
// Definitions by: RReverser <https://github.com/RReverser>, e-cloud <https://github.com/e-cloud>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="estree" />
export as namespace acorn;
export = acorn;
import * as ESTree from 'estree';
@@ -181,7 +179,7 @@ declare namespace acorn {
_typeof: TokenType;
_void: TokenType;
_delete: TokenType;
}
};
class TokContext {
constructor(token: string, isExpr: boolean, preserveSpace: boolean, override: (p: Parser) => void);
@@ -230,19 +228,18 @@ declare namespace acorn {
const version: string;
interface IParse {
(input: string, options?: Options): ESTree.Program;
}
// TODO: rename type.
type IParse = (input: string, options?: Options) => ESTree.Program;
const parse: IParse;
function parseExpressionAt(input: string, pos?: number, options?: Options): ESTree.Expression;
interface ITokenizer {
getToken() : Token,
[Symbol.iterator](): Iterator<Token>
getToken(): Token;
[Symbol.iterator](): Iterator<Token>;
}
function tokenizer(input: string, options: Options): ITokenizer;
let parse_dammit: IParse | undefined;
@@ -250,12 +247,10 @@ declare namespace acorn {
let pluginsLoose: PluginsObject | undefined;
interface ILooseParserClass {
new (input: string, options?: Options): ILooseParser
new (input: string, options?: Options): ILooseParser;
}
interface ILooseParser {
}
interface ILooseParser {}
function addLooseExports(parse: IParse, parser: ILooseParserClass, plugins: PluginsObject): void;
}
+1
View File
@@ -7,6 +7,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+9
View File
@@ -0,0 +1,9 @@
{
"extends": "dtslint/dt.json",
"rules": {
"export-just-namespace": false,
"interface-name": false,
"no-empty-interface": false,
"no-unnecessary-class": false
}
}
+1
View File
@@ -8,6 +8,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+79
View File
@@ -0,0 +1,79 @@
{
"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
}
}
+13
View File
@@ -0,0 +1,13 @@
License Notices:
The API definitions are from Actions on Google reference site [1] and actions-on-google library [2].
The actions-on-google library is licensed under the Apache 2.0 License [3].
The code documentation is reproduced from work created and shared by Google [4]
and used according to terms described in the Creative Commons 3.0 Attribution License [5].
[1] https://developers.google.com/actions/
[2] https://github.com/actions-on-google/actions-on-google-nodejs
[3] http://www.apache.org/licenses/LICENSE-2.0
[4] https://developers.google.com/readme/policies/
[5] http://creativecommons.org/licenses/by/3.0/
@@ -0,0 +1,33 @@
import { ActionsSdkApp, ActionsSdkAppOptions, DialogflowApp, DialogflowAppOptions, AssistantApp,
Responses, Transactions } from 'actions-on-google';
import express = require('express');
function testActionsSdk(request: express.Request, response: express.Response) {
const app = new ActionsSdkApp({request, response});
const actionMap = new Map();
actionMap.set(app.StandardIntents.MAIN, () => {
const richResponse: Responses.RichResponse = app.buildRichResponse()
.addSimpleResponse('Hello world')
.addSuggestions(['foo', 'bar']);
app.ask(richResponse);
});
app.handleRequest(actionMap);
}
function testDialogflow(request: express.Request, response: express.Response) {
const app = new DialogflowApp({request, response});
const actionMap = new Map();
actionMap.set(app.StandardIntents.MAIN, () => {
const order: Transactions.Order = app.buildOrder('foo');
app.askForTransactionDecision(order, {
type: app.Transactions.PaymentType.PAYMENT_CARD,
displayName: 'VISA-1234',
deliveryAddressRequired: true
});
});
app.handleRequest(actionMap);
}
const expressApp = express();
expressApp.get('/actionssdk', testActionsSdk);
expressApp.get('/dialogflow', testDialogflow);
+427
View File
@@ -0,0 +1,427 @@
import * as express from 'express';
import { AssistantApp } from './assistant-app';
import { Carousel, List, RichResponse, SimpleResponse } from './response-builder';
// ---------------------------------------------------------------------------
// Actions SDK support
// ---------------------------------------------------------------------------
export interface ActionsSdkAppOptions {
/** Express HTTP request object. */
request: express.Request;
/** Express HTTP response object. */
response: express.Response;
/** Function callback when session starts. */
sessionStarted?(): any;
}
/**
* This is the class that handles the conversation API directly from Assistant,
* providing implementation for all the methods available in the API.
*/
export class ActionsSdkApp extends AssistantApp {
/**
* Constructor for ActionsSdkApp object.
* To be used in the Actions SDK HTTP endpoint logic.
*
* @example
* const ActionsSdkApp = require('actions-on-google').ActionsSdkApp;
* const app = new ActionsSdkApp({request: request, response: response,
* sessionStarted:sessionStarted});
*
* @actionssdk
*/
constructor(options: ActionsSdkAppOptions);
/**
* @deprecated
* Validates whether request is from Assistant through signature verification.
* Uses Google-Auth-Library to verify authorization token against given
* Google Cloud Project ID. Auth token is given in request header with key,
* "Authorization".
*
* @example
* const app = new ActionsSdkApp({request, response});
* app.isRequestFromAssistant('nodejs-cloud-test-project-1234')
* .then(() => {
* app.ask('Hey there, thanks for stopping by!');
* })
* .catch(err => {
* response.status(400).send();
* });
*
* @param projectId Google Cloud Project ID for the Assistant app.
* @return Promise resolving with google-auth-library LoginTicket
* if request is from a valid source, otherwise rejects with the error reason
* for an invalid token.
* @actionssdk
*/
isRequestFromAssistant(projectId: string): Promise<object>;
/**
* Validates whether request is from Google through signature verification.
* Uses Google-Auth-Library to verify authorization token against given
* Google Cloud Project ID. Auth token is given in request header with key,
* "Authorization".
*
* @example
* const app = new ActionsSdkApp({request, response});
* app.isRequestFromGoogle('nodejs-cloud-test-project-1234')
* .then(() => {
* app.ask('Hey there, thanks for stopping by!');
* })
* .catch(err => {
* response.status(400).send();
* });
*
* @param projectId Google Cloud Project ID for the Assistant app.
* @return Promise resolving with google-auth-library LoginTicket
* if request is from a valid source, otherwise rejects with the error reason
* for an invalid token.
* @actionssdk
*/
isRequestFromGoogle(projectId: string): Promise<object>;
/**
* Gets the request Conversation API version.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
* const apiVersion = app.getApiVersion();
*
* @return Version value or null if no value.
* @actionssdk
*/
getApiVersion(): string;
/**
* Gets the user's raw input query.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
* app.tell('You said ' + app.getRawInput());
*
* @return User's raw query or null if no value.
* @actionssdk
*/
getRawInput(): string;
/**
* Gets previous JSON dialog state that the app sent to Assistant.
* Alternatively, use the app.data field to store JSON values between requests.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
* const dialogState = app.getDialogState();
*
* @return JSON object provided to the Assistant in the previous
* user turn or {} if no value.
* @actionssdk
*/
getDialogState(): any;
/**
* Gets the "versionLabel" specified inside the Action Package.
* Used by app to do version control.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
* const actionVersionLabel = app.getActionVersionLabel();
*
* @return The specified version label or null if unspecified.
* @actionssdk
*/
getActionVersionLabel(): string;
/**
* Gets the unique conversation ID. It's a new ID for the initial query,
* and stays the same until the end of the conversation.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
* const conversationId = app.getConversationId();
*
* @return Conversation ID or null if no value.
* @actionssdk
*/
getConversationId(): string;
/**
* Get the current intent. Alternatively, using a handler Map with
* {@link AssistantApp#handleRequest|handleRequest}, the client library will
* automatically handle the incoming intents.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
*
* function responseHandler (app) {
* const intent = app.getIntent();
* switch (intent) {
* case app.StandardIntents.MAIN:
* const inputPrompt = app.buildInputPrompt(false, 'Welcome to action snippets! Say anything.');
* app.ask(inputPrompt);
* break;
*
* case app.StandardIntents.TEXT:
* app.tell('You said ' + app.getRawInput());
* break;
* }
* }
*
* app.handleRequest(responseHandler);
*
* @return Intent id or null if no value.
* @actionssdk
*/
getIntent(): string;
/**
* Get the argument value by name from the current intent. If the argument
* is not a text argument, the entire argument object is returned.
*
* Note: If incoming request is using an API version under 2 (e.g. 'v1'),
* the argument object will be in Proto2 format (snake_case, etc).
*
* @param argName Name of the argument.
* @return Argument value matching argName
* or null if no matching argument.
* @actionssdk
*/
getArgument(argName: string): string;
/**
* Returns the option key user chose from options response.
*
* @example
* const app = new App({request: req, response: res});
*
* function pickOption (app) {
* if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
* app.askWithCarousel('Which of these looks good?',
* app.buildCarousel().addItems(
* app.buildOptionItem('another_choice', ['Another choice']).
* setTitle('Another choice').setDescription('Choose me!')));
* } else {
* app.ask('What would you like?');
* }
* }
*
* function optionPicked (app) {
* app.ask('You picked ' + app.getSelectedOption());
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.TEXT, pickOption);
* actionMap.set(app.StandardIntents.OPTION, optionPicked);
*
* app.handleRequest(actionMap);
*
* @return Option key of selected item. Null if no option selected or
* if current intent is not OPTION intent.
* @actionssdk
*/
getSelectedOption(): string;
/**
* Asks to collect user's input; all user's queries need to be sent to the app.
* {@link https://developers.google.com/actions/policies/general-policies#user_experience|
* The guidelines when prompting the user for a response must be followed at all times}.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
*
* const noInputs = [
* `I didn't hear a number`,
* `If you're still there, what's the number?`,
* 'What is the number?'
* ];
*
* function mainIntent (app) {
* const ssml = '<speak>Hi! <break time="1"/> ' +
* 'I can read out an ordinal like ' +
* '<say-as interpret-as="ordinal">123</say-as>. Say a number.</speak>';
* const inputPrompt = app.buildInputPrompt(true, ssml, noInputs);
* app.ask(inputPrompt);
* }
*
* function rawInput (app) {
* if (app.getRawInput() === 'bye') {
* app.tell('Goodbye!');
* } else {
* const ssml = '<speak>You said, <say-as interpret-as="ordinal">' +
* app.getRawInput() + '</say-as></speak>';
* const inputPrompt = app.buildInputPrompt(true, ssml, noInputs);
* app.ask(inputPrompt);
* }
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.MAIN, mainIntent);
* actionMap.set(app.StandardIntents.TEXT, rawInput);
*
* app.handleRequest(actionMap);
*
* @param inputPrompt Holding initial and
* no-input prompts.
* @param dialogState JSON object the app uses to hold dialog state that
* will be circulated back by App.
* @return The response that is sent to Assistant to ask user to provide input.
* @actionssdk
*/
ask(inputPrompt: object | SimpleResponse | RichResponse, dialogState?: object): express.Response | null;
/**
* Asks to collect user's input with a list.
*
* @example
* const app = new ActionsSdkApp({request, response});
*
* function welcomeIntent (app) {
* app.askWithList('Which of these looks good?',
* app.buildList('List title')
* .addItems([
* app.buildOptionItem(SELECTION_KEY_ONE,
* ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2'])
* .setTitle('Number one'),
* app.buildOptionItem(SELECTION_KEY_TWO,
* ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2'])
* .setTitle('Number two'),
* ]));
* }
*
* function optionIntent (app) {
* if (app.getSelectedOption() === SELECTION_KEY_ONE) {
* app.tell('Number one is a great choice!');
* } else {
* app.tell('Number two is a great choice!');
* }
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.TEXT, welcomeIntent);
* actionMap.set(app.StandardIntents.OPTION, optionIntent);
* app.handleRequest(actionMap);
*
* @param inputPrompt Holding initial and
* no-input prompts. Cannot contain basic card.
* @param list List built with {@link AssistantApp#buildList|buildList}.
* @param dialogState JSON object the app uses to hold dialog state that
* will be circulated back by Assistant.
* @return The response that is sent to Assistant to ask user to provide input.
* @actionssdk
*/
askWithList(inputPrompt: object | SimpleResponse | RichResponse, list: List, dialogState?: object): express.Response | null;
/**
* Asks to collect user's input with a carousel.
*
* @example
* const app = new ActionsSdkApp({request, response});
*
* function welcomeIntent (app) {
* app.askWithCarousel('Which of these looks good?',
* app.buildCarousel()
* .addItems([
* app.buildOptionItem(SELECTION_KEY_ONE,
* ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2'])
* .setTitle('Number one'),
* app.buildOptionItem(SELECTION_KEY_TWO,
* ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2'])
* .setTitle('Number two'),
* ]));
* }
*
* function optionIntent (app) {
* if (app.getSelectedOption() === SELECTION_KEY_ONE) {
* app.tell('Number one is a great choice!');
* } else {
* app.tell('Number two is a great choice!');
* }
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.TEXT, welcomeIntent);
* actionMap.set(app.StandardIntents.OPTION, optionIntent);
* app.handleRequest(actionMap);
*
* @param inputPrompt Holding initial and
* no-input prompts. Cannot contain basic card.
* @param carousel Carousel built with
* {@link AssistantApp#buildCarousel|buildCarousel}.
* @param dialogState JSON object the app uses to hold dialog state that
* will be circulated back by Assistant.
* @return The response that is sent to Assistant to ask user to provide input.
* @actionssdk
*/
askWithCarousel(inputPrompt: object | SimpleResponse | RichResponse, carousel: Carousel, dialogState?: object): express.Response | null;
/**
* Tells Assistant to render the speech response and close the mic.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
*
* const noInputs = [
* `I didn't hear a number`,
* `If you're still there, what's the number?`,
* 'What is the number?'
* ];
*
* function mainIntent (app) {
* const ssml = '<speak>Hi! <break time="1"/> ' +
* 'I can read out an ordinal like ' +
* '<say-as interpret-as="ordinal">123</say-as>. Say a number.</speak>';
* const inputPrompt = app.buildInputPrompt(true, ssml, noInputs);
* app.ask(inputPrompt);
* }
*
* function rawInput (app) {
* if (app.getRawInput() === 'bye') {
* app.tell('Goodbye!');
* } else {
* const ssml = '<speak>You said, <say-as interpret-as="ordinal">' +
* app.getRawInput() + '</say-as></speak>';
* const inputPrompt = app.buildInputPrompt(true, ssml, noInputs);
* app.ask(inputPrompt);
* }
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.MAIN, mainIntent);
* actionMap.set(app.StandardIntents.TEXT, rawInput);
*
* app.handleRequest(actionMap);
*
* @param textToSpeech Final response.
* Spoken response can be SSML.
* @return The HTTP response that is sent back to Assistant.
* @actionssdk
*/
tell(textToSpeech: string | SimpleResponse | RichResponse): express.Response | null;
/**
* Builds the {@link https://developers.google.com/actions/reference/conversation#InputPrompt|InputPrompt object}
* from initial prompt and no-input prompts.
*
* The App needs one initial prompt to start the conversation. If there is no user response,
* the App re-opens the mic and renders the no-input prompts three times
* (one for each no-input prompt that was configured) to help the user
* provide the right response.
*
* Note: we highly recommend app to provide all the prompts required here in order to ensure a
* good user experience.
*
* @example
* const inputPrompt = app.buildInputPrompt(false, 'Welcome to action snippets! Say a number.',
* ['Say any number', 'Pick a number', 'What is the number?']);
* app.ask(inputPrompt);
*
* @param isSsml Indicates whether the text to speech is SSML or not.
* @param initialPrompt The initial prompt the App asks the user.
* @param noInputs Array of re-prompts when the user does not respond (max 3).
* @return.
* @actionssdk
*/
buildInputPrompt(isSsml: boolean, initialPrompt: string, noInputs?: string[]): object;
}
File diff suppressed because it is too large Load Diff
+572
View File
@@ -0,0 +1,572 @@
import * as express from 'express';
import { AssistantApp } from './assistant-app';
import { Carousel, List, RichResponse, SimpleResponse } from './response-builder';
// ---------------------------------------------------------------------------
// Dialogflow support
// ---------------------------------------------------------------------------
/**
* Dialogflow {@link https://dialogflow.com/docs/concept-contexts|Context}.
*/
export interface Context {
/** Full name of the context. */
name: string;
/**
* Parameters carried within this context.
* See {@link https://dialogflow.com/docs/concept-actions#section-extracting-values-from-contexts|here}.
*/
parameters: object;
/** Remaining number of intents */
lifespan: number;
}
export interface DialogflowAppOptions {
/** Express HTTP request object. */
request: express.Request;
/** Express HTTP response object. */
response: express.Response;
/**
* Function callback when session starts.
* Only called if webhook is enabled for welcome/triggering intents, and
* called from Web Simulator or Google Home device (i.e., not Dialogflow simulator).
*/
sessionStarted?(): any;
}
/**
* This is the class that handles the communication with Dialogflow's fulfillment API v1.
* Doesn't currently support Dialogflow's fulfillment API v2.
*/
export class DialogflowApp extends AssistantApp {
/**
* Constructor for DialogflowApp object.
* To be used in the Dialogflow fulfillment webhook logic.
*
* @example
* const DialogflowApp = require('actions-on-google').DialogflowApp;
* const app = new DialogflowApp({request: request, response: response,
* sessionStarted:sessionStarted});
*
* @dialogflow
*/
constructor(options: DialogflowAppOptions);
/**
* @deprecated
* Verifies whether the request comes from Dialogflow.
*
* @param key The header key specified by the developer in the
* Dialogflow Fulfillment settings of the app.
* @param value The private value specified by the developer inside the
* fulfillment header.
* @return True if the request comes from Dialogflow.
* @dialogflow
*/
isRequestFromApiAi(key: string, value: string): boolean;
/**
* Verifies whether the request comes from Dialogflow.
*
* @param key The header key specified by the developer in the
* Dialogflow Fulfillment settings of the app.
* @param value The private value specified by the developer inside the
* fulfillment header.
* @return True if the request comes from Dialogflow.
* @dialogflow
*/
isRequestFromDialogflow(key: string, value: string): boolean;
/**
* Get the current intent. Alternatively, using a handler Map with
* {@link AssistantApp#handleRequest|handleRequest},
* the client library will automatically handle the incoming intents.
* 'Intent' in the Dialogflow context translates into the current action.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
*
* function responseHandler (app) {
* const intent = app.getIntent();
* switch (intent) {
* case WELCOME_INTENT:
* app.ask('Welcome to action snippets! Say a number.');
* break;
*
* case NUMBER_INTENT:
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* break;
* }
* }
*
* app.handleRequest(responseHandler);
*
* @return Intent id or null if no value (action name).
* @dialogflow
*/
getIntent(): string;
/**
* Get the argument value by name from the current intent. If the argument
* is included in originalRequest, and is not a text argument, the entire
* argument object is returned.
*
* Note: If incoming request is using an API version under 2 (e.g. 'v1'),
* the argument object will be in Proto2 format (snake_case, etc).
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const WELCOME_INTENT = 'input.welcome';
* const NUMBER_INTENT = 'input.number';
*
* function welcomeIntent (app) {
* app.ask('Welcome to action snippets! Say a number.');
* }
*
* function numberIntent (app) {
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @param argName Name of the argument.
* @return Argument value matching argName
* or null if no matching argument.
* @dialogflow
*/
getArgument(argName: string): object;
/**
* Get the context argument value by name from the current intent. Context
* arguments include parameters collected in previous intents during the
* lifespan of the given context. If the context argument has an original
* value, usually representing the underlying entity value, that will be given
* as part of the return object.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const WELCOME_INTENT = 'input.welcome';
* const NUMBER_INTENT = 'input.number';
* const OUT_CONTEXT = 'output_context';
* const NUMBER_ARG = 'myNumberArg';
*
* function welcomeIntent (app) {
* const parameters = {};
* parameters[NUMBER_ARG] = '42';
* app.setContext(OUT_CONTEXT, 1, parameters);
* app.ask('Welcome to action snippets! Ask me for your number.');
* }
*
* function numberIntent (app) {
* const number = app.getContextArgument(OUT_CONTEXT, NUMBER_ARG);
* // number === { value: 42 }
* app.tell('Your number is ' + number.value);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @param contextName Name of the context.
* @param argName Name of the argument.
* @return Object containing value property and optional original
* property matching context argument. Null if no matching argument.
* @dialogflow
*/
getContextArgument(contextName: string, argName: string): object;
/**
* Returns the RichResponse constructed in Dialogflow response builder.
*
* @example
* const app = new App({request: req, response: res});
*
* function tellFact (app) {
* let fact = 'Google was founded in 1998';
*
* if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
* app.ask(app.getIncomingRichResponse().addSimpleResponse('Here\'s a ' +
* 'fact for you. ' + fact + ' Which one do you want to hear about ' +
* 'next, Google\'s history or headquarters?'));
* } else {
* app.ask('Here\'s a fact for you. ' + fact + ' Which one ' +
* 'do you want to hear about next, Google\'s history or headquarters?');
* }
* }
*
* const actionMap = new Map();
* actionMap.set('tell.fact', tellFact);
*
* app.handleRequest(actionMap);
*
* @return RichResponse created in Dialogflow. If no RichResponse was
* created, an empty RichResponse is returned.
* @dialogflow
*/
getIncomingRichResponse(): RichResponse;
/**
* Returns the List constructed in Dialogflow response builder.
*
* @example
* const app = new App({request: req, response: res});
*
* function pickOption (app) {
* if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
* app.askWithList('Which of these looks good?',
* app.getIncomingList().addItems(
* app.buildOptionItem('another_choice', ['Another choice']).
* setTitle('Another choice')));
* } else {
* app.ask('What would you like?');
* }
* }
*
* const actionMap = new Map();
* actionMap.set('pick.option', pickOption);
*
* app.handleRequest(actionMap);
*
* @return List created in Dialogflow. If no List was created, an empty
* List is returned.
* @dialogflow
*/
getIncomingList(): List;
/**
* Returns the Carousel constructed in Dialogflow response builder.
*
* @example
* const app = new App({request: req, response: res});
*
* function pickOption (app) {
* if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
* app.askWithCarousel('Which of these looks good?',
* app.getIncomingCarousel().addItems(
* app.buildOptionItem('another_choice', ['Another choice']).
* setTitle('Another choice').setDescription('Choose me!')));
* } else {
* app.ask('What would you like?');
* }
* }
*
* const actionMap = new Map();
* actionMap.set('pick.option', pickOption);
*
* app.handleRequest(actionMap);
*
* @return Carousel created in Dialogflow. If no Carousel was created,
* an empty Carousel is returned.
* @dialogflow
*/
getIncomingCarousel(): Carousel;
/**
* Returns the option key user chose from options response.
*
* @example
* const app = new App({request: req, response: res});
*
* function pickOption (app) {
* if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
* app.askWithCarousel('Which of these looks good?',
* app.getIncomingCarousel().addItems(
* app.buildOptionItem('another_choice', ['Another choice']).
* setTitle('Another choice').setDescription('Choose me!')));
* } else {
* app.ask('What would you like?');
* }
* }
*
* function optionPicked (app) {
* app.ask('You picked ' + app.getSelectedOption());
* }
*
* const actionMap = new Map();
* actionMap.set('pick.option', pickOption);
* actionMap.set('option.picked', optionPicked);
*
* app.handleRequest(actionMap);
*
* @return Option key of selected item. Null if no option selected or
* if current intent is not OPTION intent.
* @dialogflow
*/
getSelectedOption(): string;
/**
* Asks to collect the user's input.
* {@link https://developers.google.com/actions/policies/general-policies#user_experience|The guidelines when prompting the user for a response must be followed at all times}.
*
* NOTE: Due to a bug, if you specify the no-input prompts,
* the mic is closed after the 3rd prompt, so you should use the 3rd prompt
* for a bye message until the bug is fixed.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const WELCOME_INTENT = 'input.welcome';
* const NUMBER_INTENT = 'input.number';
*
* function welcomeIntent (app) {
* app.ask('Welcome to action snippets! Say a number.',
* ['Say any number', 'Pick a number', 'We can stop here. See you soon.']);
* }
*
* function numberIntent (app) {
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @param inputPrompt The input prompt
* response.
* @param noInputs Array of re-prompts when the user does not respond (max 3).
* @return HTTP response.
* @dialogflow
*/
ask(inputPrompt: string | SimpleResponse | RichResponse, noInputs?: string[]): express.Response | null;
/**
* Asks to collect the user's input with a list.
*
* @example
* const app = new DialogflowApp({request, response});
* const WELCOME_INTENT = 'input.welcome';
* const OPTION_INTENT = 'option.select';
*
* function welcomeIntent (app) {
* app.askWithList('Which of these looks good?',
* app.buildList('List title')
* .addItems([
* app.buildOptionItem(SELECTION_KEY_ONE,
* ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2'])
* .setTitle('Title of First List Item'),
* app.buildOptionItem(SELECTION_KEY_TWO,
* ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2'])
* .setTitle('Title of Second List Item'),
* ]));
* }
*
* function optionIntent (app) {
* if (app.getSelectedOption() === SELECTION_KEY_ONE) {
* app.tell('Number one is a great choice!');
* } else {
* app.tell('Number two is a great choice!');
* }
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(OPTION_INTENT, optionIntent);
* app.handleRequest(actionMap);
*
* @param inputPrompt The input prompt
* response.
* @param.list List built with {@link AssistantApp#buildList|buildList}
* @return HTTP response.
* @dialogflow
*/
askWithList(inputPrompt: string | RichResponse | SimpleResponse, list: List): express.Response | null;
/**
* Asks to collect the user's input with a carousel.
*
* @example
* const app = new DialogflowApp({request, response});
* const WELCOME_INTENT = 'input.welcome';
* const OPTION_INTENT = 'option.select';
*
* function welcomeIntent (app) {
* app.askWithCarousel('Which of these looks good?',
* app.buildCarousel()
* .addItems([
* app.buildOptionItem(SELECTION_KEY_ONE,
* ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2'])
* .setTitle('Number one'),
* app.buildOptionItem(SELECTION_KEY_TWO,
* ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2'])
* .setTitle('Number two'),
* ]));
* }
*
* function optionIntent (app) {
* if (app.getSelectedOption() === SELECTION_KEY_ONE) {
* app.tell('Number one is a great choice!');
* } else {
* app.tell('Number two is a great choice!');
* }
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(OPTION_INTENT, optionIntent);
* app.handleRequest(actionMap);
*
* @param inputPrompt The input prompt
* response.
* @param carousel Carousel built with
* {@link AssistantApp#buildCarousel|buildCarousel}.
* @return HTTP response.
* @dialogflow
*/
askWithCarousel(inputPrompt: string | RichResponse | SimpleResponse, carousel: Carousel): express.Response | null;
/**
* Tells the Assistant to render the speech response and close the mic.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const WELCOME_INTENT = 'input.welcome';
* const NUMBER_INTENT = 'input.number';
*
* function welcomeIntent (app) {
* app.ask('Welcome to action snippets! Say a number.');
* }
*
* function numberIntent (app) {
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @param speechResponse Final response.
* Spoken response can be SSML.
* @return The response that is sent back to Assistant.
* @dialogflow
*/
tell(speechResponse: string | SimpleResponse | RichResponse): express.Response | null;
/**
* Set a new context for the current intent.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const CONTEXT_NUMBER = 'number';
* const NUMBER_ARGUMENT = 'myNumber';
*
* function welcomeIntent (app) {
* app.setContext(CONTEXT_NUMBER);
* app.ask('Welcome to action snippets! Say a number.');
* }
*
* function numberIntent (app) {
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @param name Name of the context. Dialogflow converts to lowercase.
* @param [lifespan=1] Context lifespan.
* @param parameters Context JSON parameters.
* @return Null if the context name is not defined.
* @dialogflow
*/
setContext(name: string, lifespan?: number, parameters?: any): null | undefined;
/**
* Returns the incoming contexts for this intent.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const CONTEXT_NUMBER = 'number';
* const NUMBER_ARGUMENT = 'myNumber';
*
* function welcomeIntent (app) {
* app.setContext(CONTEXT_NUMBER);
* app.ask('Welcome to action snippets! Say a number.');
* }
*
* function numberIntent (app) {
* let contexts = app.getContexts();
* // contexts === [{
* // name: 'number',
* // lifespan: 0,
* // parameters: {
* // myNumber: '23',
* // myNumber.original: '23'
* // }
* // }]
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @return Empty if no active contexts.
* @dialogflow
*/
getContexts(): Context[];
/**
* Returns the incoming context by name for this intent.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const CONTEXT_NUMBER = 'number';
* const NUMBER_ARGUMENT = 'myNumber';
*
* function welcomeIntent (app) {
* app.setContext(CONTEXT_NUMBER);
* app.ask('Welcome to action snippets! Say a number.');
* }
*
* function numberIntent (app) {
* let context = app.getContext(CONTEXT_NUMBER);
* // context === {
* // name: 'number',
* // lifespan: 0,
* // parameters: {
* // myNumber: '23',
* // myNumber.original: '23'
* // }
* // }
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @param name The name of the Context to retrieve.
* @return Context value matching name
* or null if no matching context.
* @dialogflow
*/
getContext(name: string): object;
/**
* Gets the user's raw input query.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* app.tell('You said ' + app.getRawInput());
*
* @return User's raw query or null if no value.
* @dialogflow
*/
getRawInput(): string;
}
+24
View File
@@ -0,0 +1,24 @@
// Type definitions for actions-on-google 1.10
// Project: https://github.com/actions-on-google/actions-on-google-nodejs
// Definitions by: Joel Hegg <https://github.com/joelhegg>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
/**
* The Actions on Google client library.
* https://developers.google.com/actions/
*/
import * as Transactions from './transactions';
import * as Responses from './response-builder';
export { AssistantApp } from './assistant-app';
export { ActionsSdkApp, ActionsSdkAppOptions } from './actions-sdk-app';
export { DialogflowApp, DialogflowAppOptions } from './dialogflow-app';
export { Transactions };
export { Responses };
// Backwards compatibility
export { AssistantApp as Assistant } from './assistant-app';
export { ActionsSdkApp as ActionsSdkAssistant } from './actions-sdk-app';
export { DialogflowApp as ApiAiAssistant } from './dialogflow-app';
export { DialogflowApp as ApiAiApp } from './dialogflow-app';
+743
View File
@@ -0,0 +1,743 @@
/**
* A collection of response builders.
*/
import { OrderUpdate } from './transactions';
/**
* List of possible options to display the image in a BasicCard.
* When the aspect ratio of an image is not the same as the surface,
* this attribute changes how the image is displayed in the card.
*/
export enum ImageDisplays {
/**
* Pads the gaps between the image and image frame with a blurred copy of the
* same image.
*/
DEFAULT,
/**
* Fill the gap between the image and image container with white bars.
*/
WHITE,
/**
* Image is scaled such that the image width matches the container width. This may crop the top
* and bottom of the image if the scaled image height is greater than the container height. This
* is similar to "Zoom Mode" on a widescreen TV when playing a 4:3 video.
*/
CROPPED
}
/**
* Values related to supporting media.
*/
export namespace MediaValues {
/**
* Type of the media within a MediaResponse.
*/
enum Type {
/**
* Unspecified.
*/
MEDIA_TYPE_UNSPECIFIED,
/**
* Audio stream.
*/
AUDIO
}
/**
* List of media control status' returned.
*/
enum Status {
/**
* Unspecified.
*/
UNSPECIFIED,
/**
* Finished.
*/
FINISHED
}
/**
* List of possible item types.
*/
enum ImageType {
/**
* Icon.
*/
ICON,
/**
* Large image.
*/
LARGE
}
}
/**
* Simple Response type.
*/
export interface SimpleResponse {
/** Speech to be spoken to user. SSML allowed. */
speech: string;
/** Optional text to be shown to user */
displayText?: string;
}
/**
* Suggestions to show with response.
*/
export interface Suggestion {
/** Text of the suggestion. */
title: string;
}
/**
* Link Out Suggestion. Used in rich response as a suggestion chip which, when
* selected, links out to external URL.
*/
export interface LinkOutSuggestion {
/** Text shown on the suggestion chip. */
title: string;
/** String URL to open. */
url: string;
}
/**
* Image type shown on visual elements.
*/
export interface Image {
/** Image source URL. */
url: string;
/** Text to replace for image for accessibility. */
accessibilityText: string;
/** Width of the image. */
width: number;
/** Height of the image. */
height: number;
}
/**
* Basic Card Button. Shown below basic cards. Open a URL when selected.
*/
export interface Button {
/** Text shown on the button. */
title: string;
/** Action to take when selected. */
openUrlAction: {
/** String URL to open. */
url: string;
};
}
/**
* Option info. Provides unique identifier for a given OptionItem.
*/
export interface OptionInfo {
/** Unique string ID for this option. */
key: string;
/** Synonyms that can be used by the user to indicate this option if they do not use the key. */
synonyms: string[];
}
export interface StructuredResponse {
orderUpdate: OrderUpdate;
}
export interface ItemBasicCard {
basicCard: BasicCard;
}
export interface ItemSimpleResponse {
simpleResponse: SimpleResponse;
}
export interface ItemStructuredResponse {
structuredResponse: StructuredResponse;
}
export type RichResponseItem = ItemBasicCard | ItemSimpleResponse | ItemStructuredResponse;
/**
* Class for initializing and constructing Rich Responses with chainable interface.
*/
export class RichResponse {
/**
* Constructor for RichResponse. Accepts optional RichResponse to clone.
*
* @param richResponse Optional RichResponse to clone.
*/
constructor(richResponse?: RichResponse);
/**
* Ordered list of either SimpleResponse objects or BasicCard objects.
* First item must be SimpleResponse. There can be at most one card.
*/
items: RichResponseItem[];
/**
* Ordered list of text suggestions to display. Optional.
*/
suggestions: Suggestion[];
/**
* Link Out Suggestion chip for this rich response. Optional.
*/
linkOutSuggestion?: LinkOutSuggestion;
/**
* Adds a SimpleResponse to list of items.
*
* @param simpleResponse Simple response to present to
* user. If just a string, display text will not be set.
* @return Returns current constructed RichResponse.
*/
addSimpleResponse(simpleResponse: string | SimpleResponse): RichResponse;
/**
* Adds a BasicCard to list of items.
*
* @param basicCard Basic card to include in response.
* @return Returns current constructed RichResponse.
*/
addBasicCard(basicCard: BasicCard): RichResponse;
/**
* Adds media to this response.
*
* @param mediaResponse MediaResponse to include in response.
* @return Returns current constructed RichResponse.
*/
addMediaResponse(mediaResponse: MediaResponse): RichResponse;
/**
* Adds a Browse Carousel to list of items.
*
* @param browseCarousel Browse Carousel to present to user
* @return Returns current constructed RichResponse.
*/
addBrowseCarousel(browseCarousel: string | BrowseCarousel): RichResponse;
/**
* Adds a single suggestion or list of suggestions to list of items.
*
* @param suggestions Either a single string suggestion
* or list of suggestions to add.
* @return Returns current constructed RichResponse.
*/
addSuggestions(suggestions: string | string[]): RichResponse;
/**
* Returns true if the given suggestion text is valid to be added to the suggestion list. A valid
* text string is not longer than 25 characters.
* @param suggestionText Text to validate as suggestion.
* @return True if the text is valid, false otherwise.s
*/
isValidSuggestionText(suggestionText: string): boolean;
/**
* Sets the suggestion link for this rich response. The destination site must be verified
* (https://developers.google.com/actions/console/brand-verification).
*
* @param destinationName Name of the link out destination.
* @param suggestionUrl - String URL to open when suggestion is used.
* @return Returns current constructed RichResponse.
*/
addSuggestionLink(destinationName: string, suggestionUrl: string): RichResponse;
/**
* Adds an order update to this response. Use after a successful transaction
* decision to confirm the order.
*
* @param orderUpdate OrderUpdate object to add.
* @return Returns current constructed RichResponse.
*/
addOrderUpdate(orderUpdate: OrderUpdate): RichResponse;
}
/**
* Class for initializing and constructing Basic Cards with chainable interface.
*/
export class BasicCard {
/**
* Constructor for BasicCard. Accepts optional BasicCard to clone.
*
* @param basicCard Optional BasicCard to clone.
*/
constructor(basicCard?: BasicCard);
/**
* Title of the card. Optional.
*/
title?: string;
/**
* Body text to show on the card. Required, unless image is present.
*/
formattedText: string;
/**
* Subtitle of the card. Optional.
*/
subtitle?: string;
/**
* Image to show on the card. Optional.
*/
image?: Image;
/**
* Ordered list of buttons to show below card. Optional.
*/
buttons: Button[];
/**
* Sets the title for this Basic Card.
*
* @param title Title to show on card.
* @return Returns current constructed BasicCard.
*/
setTitle(title: string): BasicCard;
/**
* Sets the subtitle for this Basic Card.
*
* @param subtitle Subtitle to show on card.
* @return Returns current constructed BasicCard.
*/
setSubtitle(subtitle: string): BasicCard;
/**
* Sets the body text for this Basic Card.
*
* @param bodyText Body text to show on card.
* @return Returns current constructed BasicCard.
*/
setBodyText(bodyText: string): BasicCard;
/**
* Sets the image for this Basic Card.
*
* @param url Image source URL.
* @param accessibilityText Text to replace for image for
* accessibility.
* @param width Width of the image.
* @param height Height of the image.
* @return Returns current constructed BasicCard.
*/
setImage(url: string, accessibilityText: string, width?: number, height?: number): BasicCard;
/**
* Sets the display options for the image in this Basic Card.
* Use one of the image display constants. If none is chosen,
* ImageDisplays.DEFAULT will be enforced.
*
* @param option The option for displaying the image.
* @return Returns current constructed BasicCard.
*/
setImageDisplay(option: ImageDisplays): BasicCard;
/**
* Adds a button below card.
*
* @param text Text to show on button.
* @param url URL to open when button is selected.
* @return Returns current constructed BasicCard.
*/
addButton(text: string, url: string): BasicCard;
}
/**
* Class for initializing and constructing Lists with chainable interface.
*/
export class List {
/**
* Constructor for List. Accepts optional List to clone, string title, or
* list of items to copy.
*
* @param list Either a list to clone, a title
* to set for a new List, or an array of OptionItem to initialize a new
* list.
*/
constructor(list?: List | string | OptionItem[]);
/**
* Title of the list. Optional.
*/
title?: string;
/**
* List of 2-20 items to show in this list. Required.
*/
items: OptionItem[];
/**
* Sets the title for this List.
*
* @param title Title to show on list.
* @return Returns current constructed List.
*/
setTitle(title: string): List;
/**
* Adds a single item or list of items to the list.
*
* @param optionItems OptionItems to add.
* @return Returns current constructed List.
*/
addItems(optionItems: OptionItem | OptionItem[]): List;
}
/**
* Class for initializing and constructing BrowseCarousel with chainable interface.
*/
export class BrowseCarousel {
/**
* Constructor for BrowseCarousel. Accepts optional BrowseCarousel to
* clone or list of items to copy.
*
* @param carousel Either a carousel to clone
* or an array of BrowseItem to initialize a new carousel
*/
constructor(carousel?: BrowseCarousel | BrowseItem[]);
/**
* List of 2-20 items to show in this carousel. Required.
*/
items: BrowseItem[];
/**
* Adds a single item or list of items to the carousel.
*
* @param browseItems BrowseItems to add.
* @return Returns current constructed BrowseCarousel.
*/
addItems(browseItems: BrowseItem | BrowseItem[]): BrowseCarousel;
/**
* Sets the display options for the images in this carousel.
* Use one of the image display constants. If none is chosen,
* ImageDisplays.DEFAULT will be enforced.
*
* @param option The option for displaying the image.
* @return Returns current constructed BrowseCarousel.
*/
setImageDisplay(option: ImageDisplays): BrowseCarousel;
}
/**
* Class for initializing and constructing Carousel with chainable interface.
*/
export class Carousel {
/**
* Constructor for Carousel. Accepts optional Carousel to clone or list of
* items to copy.
*
* @param carousel Either a carousel to clone
* or an array of OptionItem to initialize a new carousel
*/
constructor(carousel?: Carousel | OptionItem[]);
/**
* List of 2-20 items to show in this carousel. Required.
*/
items: OptionItem[];
/**
* Adds a single item or list of items to the carousel.
*
* @param optionItems OptionItems to add.
* @return Returns current constructed Carousel.
*/
addItems(optionItems: OptionItem | OptionItem[]): Carousel;
/**
* Sets the display options for the images in this carousel.
* Use one of the image display constants. If none is chosen,
* ImageDisplays.DEFAULT will be enforced.
*
* @param option The option for displaying the image.
* @return Returns current constructed Carousel.
*/
setImageDisplay(option: ImageDisplays): Carousel;
}
/**
* Class for initializing and constructing Option Items with chainable interface.
*/
export class BrowseItem {
/**
* Constructor for BrowseItem. Accepts a title and URL for the Browse Item
* card.
*
* @param title The title of the Browse Item card.
* @param url The URL of the link opened by clicking the Browse Item card.
*/
constructor(title?: string, url?: string);
/**
* Title of the browse item. Required.
*/
title: string;
/**
* Description text of the item. Optional.
*/
description?: string;
/**
* Footer text of the item. Optional.
*/
footer?: string;
/**
* Image to show on item. Optional.
*/
image?: Image;
/**
* Url to that clicking the card opens. Optional.
*/
openUrlAction?: object;
/**
* @return Returns the possible valid values for URL type hints
*/
urlTypeHints(): object;
/**
* Sets the title for this Browse Item.
*
* @param title Title to show on item.
* @return Returns current constructed BrowseItem.
*/
setTitle(title: string): BrowseItem;
/**
* Sets the description for this Browse Item.
*
* @param description Description to show on item.
* @return Returns current constructed BrowseItem.
*/
setDescription(description: string): BrowseItem;
/**
* Sets the footer for this Browse Item.
*
* @param footerText text to show on item.
* @return Returns current constructed BrowseItem.
*/
setFooter(footerText: string): BrowseItem;
/**
* Sets the image for this Browse Item.
*
* @param url Image source URL.
* @param accessibilityText Text to replace for image for accessibility.
* @param width Width of the image.
* @param height Height of the image.
* @return Returns current constructed BrowseItem.
*/
setImage(url: string, accessibilityText: string, width?: number, height?: number): BrowseItem;
/**
* Sets the Open URL action - which includes the url and possibly the typeHint
*
* @param url Image source URL.
* @param urlTypeHint One of the typeHints enumerated by this.urlTypeHints()
* @return Returns the current constructed BrowseItem
*/
setOpenUrlAction(url: string, urlTypeHint?: string): BrowseItem;
/**
* Sets the URL target of the BrowseItem card
*
* @param url Image source URL.
* @return Returns the current constructed BrowseItem
*/
setUrl(url: string): BrowseItem;
/**
* Sets the URL type hint for the BrowseItem card
*
* @param urlTypeHint One of the typeHints enumerated by this.urlTypeHints()
* @return Returns the current constructed BrowseItem
*/
setUrlTypeHint(urlTypeHint: string): BrowseItem;
}
/**
* Class for initializing and constructing Option Items with chainable interface.
*/
export class OptionItem {
/**
* Constructor for OptionItem. Accepts optional OptionItem to clone.
*
* @param optionItem Optional OptionItem to clone.
*/
constructor(optionItem?: OptionItem);
/**
* Option info of the option item. Required.
*/
optionInfo: OptionInfo;
/**
* Title of the option item. Required.
*/
title: string;
/**
* Description text of the item. Optional.
*/
description?: string;
/**
* Image to show on item. Optional.
*/
image?: Image;
/**
* Sets the title for this Option Item.
*
* @param title Title to show on item.
* @return Returns current constructed OptionItem.
*/
setTitle(title: string): OptionItem;
/**
* Sets the description for this Option Item.
*
* @param description Description to show on item.
* @return Returns current constructed OptionItem.
*/
setDescription(description: string): OptionItem;
/**
* Sets the image for this Option Item.
*
* @param url Image source URL.
* @param accessibilityText Text to replace for image for
* accessibility.
* @param width Width of the image.
* @param height Height of the image.
* @return Returns current constructed OptionItem.
*/
setImage(url: string, accessibilityText: string, width?: number, height?: number): OptionItem;
/**
* Sets the key for the OptionInfo of this Option Item. This will be returned
* as an argument in the resulting actions.intent.OPTION intent.
*
* @param key Key to uniquely identify this item.
* @return Returns current constructed OptionItem.
*/
setKey(key: string): OptionItem;
/**
* Adds a single synonym or list of synonyms to item.
*
* @param synonyms Either a single string synonyms
* or list of synonyms to add.
* @return Returns current constructed OptionItem.
*/
addSynonyms(synonyms: string | string[]): OptionItem;
}
/**
* Class for initializing and constructing MediaResponse with chainable interface.
*/
export class MediaResponse {
/**
* Constructor for MediaResponse.
* @param mediaType Type of the media which defaults to MediaValues.Type.AUDIO
*/
constructor(mediaType: MediaValues.Type);
/**
* Array of MediaObject held in the MediaResponse.
*/
mediaObjects: MediaObject[];
/**
* Type of the media within this MediaResponse
*/
mediaType: MediaValues.Type;
/**
* Adds a single media file or list of media files to the cart.
*
* @param items Single or Array of MediaObject to add.
* @return Returns current constructed MediaResponse.
*/
addMediaObjects(items: MediaObject | MediaObject[]): MediaResponse;
}
/**
* Class for initializing and constructing MediaObject with chainable interface.
*/
export class MediaObject {
/**
* Constructor for MediaObject.
*
* @param name Name of the MediaObject.
* @param contentUrl URL of the MediaObject.
*/
constructor(name: string, contentUrl: string);
/**
* Name of the MediaObject.
*/
name: string;
/**
* MediaObject URL.
*/
contentUrl: string;
/**
* Description of the MediaObject.
*/
description?: string;
/**
* Large image.
*/
largeImage?: Image;
/**
* Icon image.
*/
icon?: Image;
/**
* Set the description of the item.
*
* @param description Description of the item.
* @return Returns current constructed MediaObject.
*/
setDescription(description: string): MediaObject;
/**
* Sets the image for this item.
*
* @param url Image source URL.
* @param type Type of image (LARGE or ICON).
* @return Returns current constructed MediaObject.
*/
setImage(url: string, type: MediaValues.ImageType): MediaObject;
}
/**
* Check if given text contains SSML.
* @param text Text to check.
* @return True if text contains SSML, false otherwise.
*/
export function isSsml(text: string): boolean;
/**
* Check if given text contains SSML, allowing for whitespace padding.
* @param text Text to check.
* @return True if text contains possibly whitespace padded SSML, false otherwise.
*/
export function isPaddedSsml(text: string): boolean;
File diff suppressed because it is too large Load Diff
+28
View File
@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"assistant-app.d.ts",
"actions-sdk-app.d.ts",
"dialogflow-app.d.ts",
"response-builder.d.ts",
"transactions.d.ts",
"actions-on-google-tests.ts"
]
}
@@ -0,0 +1,27 @@
/// <reference types="windows-script-host" />
let app = new ActiveXObject('Access.Application');
app.UserControl = true;
// opens a form
app.DoCmd.OpenForm('MyForm', Access.AcFormView.acNormal, '', 'LastName="Smith"');
// change the contents of a textbox
// tslint:disable-next-line:no-unnecessary-type-assertion
let textbox = app.Forms('MyForm').Controls('MyTextBox') as Access.TextBox;
textbox.Text = 'Not Smith';
// save the current record on the active form
app.RunCommand(Access.AcCommand.acCmdSaveRecord);
// close the form
app.DoCmd.Close(Access.AcObjectType.acForm, 'MyForm');
// open a report for printing
app.DoCmd.OpenReport('MyReport');
// open the same report in Design View
app.DoCmd.OpenReport('MyReport', Access.AcView.acViewDesign);
// run a VBA macro
app.Run('MyMacro', 'argument1', 2);
+8212
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-access-tests.ts"
]
}
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "dtslint/dt.json",
"rules": {
"no-const-enum": false,
"max-line-length": false
}
}
+429
View File
@@ -0,0 +1,429 @@
// Note -- running these tests under cscript requires some ES5 polyfills
/// <reference types="windows-script-host" />
/// <reference types="activex-scripting" />
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;
};
const toSafeArray = <T>(...items: T[]): SafeArray<T> => {
const dict: Scripting.Dictionary<number, T> = new ActiveXObject('Scripting.Dictionary');
items.forEach((x, index) => dict.Add(index, x));
return dict.Items();
};
const toConnectionString = (o: { [index: string]: any }) => {
o.Provider = o.Provider || 'sqloledb';
o['Data Source'] = o['Data Source'] || 'Server';
o['Integrated Security'] = o['Integrated Security'] || 'SSPI';
const parts: string[] = [];
for (const key in o) {
let val = o[key];
if (typeof val === 'string') { val = `'${val}'`; }
parts.push(`${key}=${val}`);
}
return parts.join(';');
};
const printLine = () => WScript.Echo(new Array(26).join('-'));
{
// open connection to an Excel file
const pathToExcelFile = 'C:\\path\\to\\excel\\file.xlsx';
const conn = new ActiveXObject('ADODB.Connection');
conn.ConnectionString = toConnectionString({
Provider: 'Microsoft.ACE.OLEDB.12.0',
'Data Source': pathToExcelFile,
'Extended Properties': "Excel 12.0;HDR=Yes"
});
conn.Open();
// create a Command to access the data
const cmd = new ActiveXObject('ADODB.Command');
cmd.ActiveConnection = conn;
cmd.CommandText = 'SELECT DISTINCT LastName, CityName FROM [Sheet1$]';
// get a Recordset
const rs = cmd.Execute() as ADODB.Recordset;
// build a string from the Recordset
const s = rs.GetString(ADODB.StringFormatEnum.adClipString, -1, '\t', '\n', '(NULL)');
rs.Close();
WScript.Echo(s);
}
// create a disconnected recordset -- https://support.microsoft.com/en-us/help/184397/how-to-create-ado-disconnected-recordsets-in-vba-c-java
{
const conn = new ActiveXObject('ADODB.Connection');
conn.Open(); // pass connection details here
const rs = new ActiveXObject('ADODB.Recordset');
rs.CursorLocation = ADODB.CursorLocationEnum.adUseClient;
rs.Open('SELECT * FROM Table1', conn, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockBatchOptimistic);
rs.ActiveConnection = null;
const v = rs(0).Value;
conn.Close();
}
// update with SafeArray
{
const rs = new ActiveXObject('ADODB.Recordset');
rs.Open(); // missing connection details here
const fields = toSafeArray('FirstName', 'LastName', 'DOB');
const values = toSafeArray<any>('Plony', 'Almony', new Date(1980, 1, 1).getVarDate());
rs.Update(fields, values);
rs.Close();
}
const withConnection = (initialCatalog: string, fn: (conn: ADODB.Connection) => void) => {
let conn: ADODB.Connection | null = new ActiveXObject('ADODB.Connection');
const connectionString = toConnectionString({
'Initial Catalog': initialCatalog
});
try {
conn.Open(connectionString);
fn(conn);
} catch (e) {
WScript.Echo(e.message);
} finally {
if (conn.State === ADODB.ObjectStateEnum.adStateOpen) {
conn.Close();
}
conn = null;
}
};
const withRs = (catalogOrConnection: string | ADODB.Connection, tableOrCommand: string | ADODB.Command, fn: (rs: ADODB.Recordset) => void,
type: ADODB.CursorTypeEnum = ADODB.CursorTypeEnum.adOpenUnspecified,
location: ADODB.CursorLocationEnum = ADODB.CursorLocationEnum.adUseNone,
lockType: ADODB.LockTypeEnum = ADODB.LockTypeEnum.adLockOptimistic
) => {
let connection = catalogOrConnection;
if (typeof connection === 'string') {
// expand catalog to full connection string
connection = toConnectionString({
'Initial Catalog': connection
});
}
let rs: ADODB.Recordset | null = null;
try {
if (typeof tableOrCommand === 'string') {
rs = new ActiveXObject('ADODB.Recordset');
rs.CursorLocation = location;
rs.LockType = lockType;
rs.Open(tableOrCommand, connection, type, lockType, ADODB.CommandTypeEnum.adCmdTable);
} else {
tableOrCommand.ActiveConnection = connection;
rs = tableOrCommand.Execute() as ADODB.Recordset;
}
fn(rs);
} catch (e) {
WScript.Echo(e.message);
} finally {
if (rs && rs.State === ADODB.ObjectStateEnum.adStateOpen) {
rs.Close();
}
rs = null;
}
};
const withEmployees = (fn: (rs: ADODB.Recordset) => void, type: ADODB.CursorTypeEnum) =>
withRs('Northwind', 'Employees', fn, type, ADODB.CursorLocationEnum.adUseClient);
// https://msdn.microsoft.com/en-us/library/jj249882.aspx
{
withConnection('Northwind', conn => {
withEmployees(rs => {
const FName = 'first name';
const LName = 'last name';
rs.AddNew();
rs('FirstName').Value = FName;
rs('LastName').Value = LName;
rs.Update();
WScript.Echo('New record added.');
}, ADODB.CursorTypeEnum.adOpenKeyset);
});
}
// https://msdn.microsoft.com/en-us/library/jj249434.aspx
{
withConnection('Northwind', conn => {
withEmployees(rs => {
// Set PageSize to five to display names and hire dates of five employees at a time
rs.PageSize = 5;
const pageCount = rs.PageCount;
WScript.Echo(`There are ${pageCount} pages, each containing ${rs.PageSize} or fewer records`.trim());
for (let i = 1; i <= pageCount; i++) {
rs.AbsolutePage = i;
for (let iRecord = 1; iRecord <= rs.PageSize; iRecord++) {
// First column in row contains page number on
// first record of each page. Otherwise, the column
// contains a non-breaking space.
const page = iRecord === 1 ? `Page ${i} of ${rs.PageCount}` : '';
// First and last name are in first column.
const name = `${rs('FirstName')} ${rs('LastName')}`;
// Hire date in second column.
const hireDate = new Date(rs('HireDate').Value as VarDate).toString();
// Write the row
WScript.Echo([page, name, hireDate].join('\t'));
// Get next record.
rs.MoveNext();
if (rs.EOF) { break; }
}
}
}, ADODB.CursorTypeEnum.adOpenStatic);
});
}
// https://msdn.microsoft.com/en-us/library/jj250117.aspx
{
withConnection('Northwind', conn => {
withEmployees(rs => {
WScript.Echo(['AbsolutePosition', 'Name', 'Hire Date'].join('\t'));
while (!rs.EOF) {
// First column in row contains AbsolutePosition value.
const recordCount = `${rs.AbsolutePosition} of ${rs.RecordCount}`;
// First and last name are in first column.
const name = `${rs('FirstName')} ${rs('LastName')}`;
// Hire date in second column.
const hireDate = new Date(rs('HireDate').Value as VarDate).toString();
WScript.Echo([recordCount, name, hireDate].join('\t'));
}
}, ADODB.CursorTypeEnum.adOpenStatic);
});
}
// https://msdn.microsoft.com/en-us/library/jj249824.aspx
{
withConnection('Northwind', conn => {
WScript.Echo('Enter city name, and press ENTER:');
const cityName = WScript.StdIn.ReadLine();
const cmdContact = new ActiveXObject('ADODB.Command');
cmdContact.CommandText = 'SELECT ContactName FROM Customers WHERE City = ?';
cmdContact.ActiveConnection = conn;
// create parameter and insert variable value
const param = cmdContact.CreateParameter('CityName', ADODB.DataTypeEnum.adChar, ADODB.ParameterDirectionEnum.adParamInput, 30, cityName);
cmdContact.Parameters.Append(param);
let rsContact: ADODB.Recordset | null = null;
try {
// Open a recordset using the command object
rsContact = cmdContact.Execute() as ADODB.Recordset;
while (!rsContact.EOF) {
WScript.Echo(rsContact('ContactName'));
rsContact.MoveNext();
}
} catch (e) {
WScript.Echo(e.message);
} finally {
if (rsContact && rsContact.State === ADODB.ObjectStateEnum.adStateOpen) {
rsContact.Close();
}
}
});
}
// https://msdn.microsoft.com/en-us/library/jj249056.aspx
// https://msdn.microsoft.com/en-us/library/jj249494.aspx
{
WScript.Echo('Enter royalty value, and press ENTER:');
const iRoyalty = parseInt(WScript.StdIn.ReadLine(), 10);
if (iRoyalty > -1) {
withConnection('pubs', conn => {
const cmdByRoyalty = new ActiveXObject('ADODB.Command');
cmdByRoyalty.CommandText = 'byroyalty';
cmdByRoyalty.CommandType = ADODB.CommandTypeEnum.adCmdStoredProc;
cmdByRoyalty.CommandTimeout = 15;
// The stored procedure called above is as follows:
/*
CREATE PROCEDURE byroyalty
@percentage int
AS
SELECT au_id from titleauthor
WHERE titleauthor.royaltyper = @percentage
GO
*/
const prmByRoyalty = new ActiveXObject('ADODB.Parameter');
prmByRoyalty.Type = ADODB.DataTypeEnum.adInteger;
prmByRoyalty.Size = 3;
prmByRoyalty.Direction = ADODB.ParameterDirectionEnum.adParamInput;
prmByRoyalty.Value = iRoyalty;
cmdByRoyalty.Parameters.Append(prmByRoyalty);
// open byRoyalty recordset via Command
withRs(conn, cmdByRoyalty, rsByRoyalty => {
// open authors recordset directly
withRs(conn, 'Authors', rsAuthor => {
while (!rsByRoyalty.EOF) {
// set filter
rsAuthor.Filter = `au_id='${rsByRoyalty('au_id')}'`;
// write author name
WScript.Echo(`${rsAuthor('au_fname')} ${rsAuthor('au_lname')}`);
}
// get next record
rsByRoyalty.MoveNext();
});
});
});
}
}
// https://msdn.microsoft.com/en-us/library/jj250032.aspx
{
withRs('Northwind', 'Suppliers', rsSuppliers => {
WScript.Echo(['Field Value', 'Defined Size', 'Actual Size'].join('\t'));
while (!rsSuppliers.EOF) {
const fld = rsSuppliers('CompanyName');
WScript.Echo([fld.Value, fld.DefinedSize, fld.ActualSize].join('\t'));
}
rsSuppliers.MoveNext();
});
}
// https://msdn.microsoft.com/en-us/library/jj249928.aspx
{
withRs('Northwind', 'Customers', rs => {
const loop20 = () => {
const start = new Date().getTime();
// loop through the recordset 20 times
for (let i = 0; i < 20; i++) {
rs.MoveFirst();
while (!rs.EOF) {
// do something with the record
const strTemp = rs('CompanyName').Value as string;
rs.MoveNext();
}
}
const end = new Date().getTime();
return end - start;
};
const noCache = loop20();
// cache records in groups of 30
rs.MoveFirst();
rs.CacheSize = 30;
const cache = loop20();
WScript.Echo(`No cache: ${noCache}; with cache: ${cache}`);
}, ADODB.CursorTypeEnum.adOpenUnspecified, ADODB.CursorLocationEnum.adUseClient);
}
// https://msdn.microsoft.com/en-us/library/jj249157.aspx
{
const printAuthorRecordset = (caption: string, rs: ADODB.Recordset) => {
printLine();
WScript.Echo(`**${caption}**`);
while (!rs.EOF) {
// write current row's data
const name = `${rs('au_fname')} ${rs('au_lname')}`;
WScript.Echo(name);
// get next record
rs.MoveNext;
}
};
WScript.Echo('Enter last name of author to find (e.g., Ringer) and then press ENTER:');
const lastName = WScript.StdIn.ReadLine() || '';
if (lastName.length > 0) {
withConnection('pubs', conn => {
// command object parameters
const cmdAuthor = new ActiveXObject('ADODB.Command');
cmdAuthor.CommandText = 'SELECT * FROM Authors WHERE au_name = ?';
const lastNameParameter = cmdAuthor.CreateParameter('Last Name', ADODB.DataTypeEnum.adChar, ADODB.ParameterDirectionEnum.adParamInput, 20, lastName);
cmdAuthor.Parameters.Append(lastNameParameter);
cmdAuthor.ActiveConnection = conn;
// recordset from command.execute
const rsAuthor = cmdAuthor.Execute() as ADODB.Recordset;
// recordset from connection.execute
const rsAuthor2 = conn.Execute('SELECT * FROM Authors') as ADODB.Recordset;
const errs = collectionToArray(conn.Errors);
if (errs.length > 0) {
for (const err of errs) {
WScript.Echo(err);
}
}
conn.Errors.Clear();
printAuthorRecordset('Command.Execute results', rsAuthor);
printAuthorRecordset('Connection.Execute results', rsAuthor2);
});
}
}
// https://msdn.microsoft.com/en-us/library/jj249466.aspx
{
withConnection('Northwind', conn => {
const sql = 'SELECT * FROM Customers';
withRs(conn, sql, rs => {
rs.MoveFirst();
if (rs.RecordCount === 0) {
WScript.Echo(`No records matched for '${sql}'`);
return;
}
// print headings for each field name
WScript.Echo(collectionToArray(rs.Fields).map(fld => fld.Name).join('\t'));
// JScript doesn't support multi-dimensional arrays
// so we'll convert the returned array to a single
// dimensional JScript array and then display the data.
const safeArray = rs.GetRows();
const data = new VBArray(safeArray).toArray();
const fieldCount = rs.Fields.Count;
data.forEach((cellValue, index) => {
const currentField = index % fieldCount;
// don't print tab character for first and last columns
if (currentField > 0 && currentField < fieldCount - 1) {
WScript.StdOut.Write('\t');
}
const displayValue = cellValue === null ? '-null-' : cellValue;
if (currentField === fieldCount - 1) {
WScript.StdOut.WriteLine(displayValue);
} else {
WScript.StdOut.Write(displayValue);
}
});
}, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.CursorLocationEnum.adUseClient, ADODB.LockTypeEnum.adLockOptimistic);
});
}
+1124
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-adodb-tests.ts"
]
}
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "dtslint/dt.json",
"rules": {
"no-const-enum": false,
"max-line-length": false
}
}
File diff suppressed because it is too large Load Diff
+332
View File
@@ -0,0 +1,332 @@
// Type definitions for Microsoft ADO Extensions 6.0 for DDL and Security - ADOX 6.0
// Project: https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/adox-object-model
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
/// <reference types="activex-interop" />
/// <reference types="activex-adodb" />
declare namespace ADOX {
const enum ActionEnum {
adAccessDeny = 3,
adAccessGrant = 1,
adAccessRevoke = 4,
adAccessSet = 2,
}
const enum AllowNullsEnum {
adIndexNullsAllow = 0,
adIndexNullsDisallow = 1,
adIndexNullsIgnore = 2,
adIndexNullsIgnoreAny = 4,
}
const enum ColumnAttributesEnum {
adColFixed = 1,
adColNullable = 2,
}
const enum InheritTypeEnum {
adInheritBoth = 3,
adInheritContainers = 2,
adInheritNone = 0,
adInheritNoPropogate = 4,
adInheritObjects = 1,
}
const enum KeyTypeEnum {
adKeyForeign = 2,
adKeyPrimary = 1,
adKeyUnique = 3,
}
const enum ObjectTypeEnum {
adPermObjColumn = 2,
adPermObjDatabase = 3,
adPermObjProcedure = 4,
adPermObjProviderSpecific = -1,
adPermObjTable = 1,
adPermObjView = 5,
}
const enum RightsEnum {
adRightCreate = 16384,
adRightDelete = 65536,
adRightDrop = 256,
adRightExclusive = 512,
adRightExecute = 536870912,
adRightFull = 268435456,
adRightInsert = 32768,
adRightMaximumAllowed = 33554432,
adRightNone = 0,
adRightRead = -2147483648,
adRightReadDesign = 1024,
adRightReadPermissions = 131072,
adRightReference = 8192,
adRightUpdate = 1073741824,
adRightWithGrant = 4096,
adRightWriteDesign = 2048,
adRightWriteOwner = 524288,
adRightWritePermissions = 262144,
}
const enum RuleEnum {
adRICascade = 1,
adRINone = 0,
adRISetDefault = 3,
adRISetNull = 2,
}
const enum SortOrderEnum {
adSortAscending = 1,
adSortDescending = 2,
}
class Catalog {
private constructor();
private 'ADOX.Catalog_typekey': Catalog;
/** Can be set to a Connection object or a string. Returns the active Connection object, or `null` */
ActiveConnection: string | ADODB.Connection | null;
/**
* The **Create** method creates and opens a new ADO Connection to the data source specified in _ConnectString_. If successful, the new **Connection** object is assigned to the **ActiveConnection** property.
*
* An error will occur if the provider does not support creating new catalogs.
*
* @param ConnectString Connection string
*/
Create(ConnectString: string): void;
/**
* @param ObjectTypeId Specifies the GUID for a provider object type not defined by the OLE DB specification
*/
GetObjectOwner(ObjectName: string, ObjectType: ObjectTypeEnum.adPermObjProviderSpecific, ObjectTypeId: any): string;
GetObjectOwner(ObjectName: string, ObjectType: ObjectTypeEnum): string;
readonly Groups: Groups;
readonly Procedures: Procedures;
/**
* @param UserName Specifies the name of the **User** or **Group** to own the object
* @param ObjectTypeId Specifies the GUID for a provider object type that is not defined by the OLE DB specification
*/
SetObjectOwner(ObjectName: string, ObjectType: ObjectTypeEnum.adPermObjProviderSpecific, UserName: string, ObjectTypeId: any): void;
SetObjectOwner(ObjectName: string, ObjectType: ObjectTypeEnum, UserName: string): void;
readonly Tables: Tables;
readonly Users: Users;
readonly Views: Views;
}
class Column {
private constructor();
private 'ADOX.Column_typekey': Column;
Attributes: ColumnAttributesEnum;
DefinedSize: number;
Name: string;
NumericScale: number;
ParentCatalog: Catalog;
Precision: number;
readonly Properties: ADODB.Properties;
RelatedColumn: string;
SortOrder: SortOrderEnum;
Type: ADODB.DataTypeEnum;
}
interface Columns {
/**
* @param Type [Type=202]
* @param DefinedSize [DefinedSize=0]
*/
Append(Item: Column | string, Type?: ADODB.DataTypeEnum, DefinedSize?: number): void;
readonly Count: number;
Delete(Item: string | number): void;
Item(Item: string | number): Column;
Refresh(): void;
(Item: string | number): Column;
}
class Group {
private constructor();
private 'ADOX.Group_typekey': Group;
/**
* @param Name Specifies the name of the object for which to set permissions. Pass `null` if you want to get the permissions for the object container.
* @param ObjectTypeId Specifies the GUID for a provider object type not defined by the OLE DB specification.
*/
GetPermissions(Name: string | null, ObjectType: ObjectTypeEnum.adPermObjProviderSpecific, ObjectTypeId: any): RightsEnum;
GetPermissions(Name: string | null, ObjectType: ObjectTypeEnum): RightsEnum;
Name: string;
ParentCatalog: Catalog;
readonly Properties: ADODB.Properties;
/**
* @param Rights A bitmask of one or more of the **RightsEnum** constants, that indicates the rights to set.
* @param Inherit [Inherit=0]
* @param ObjectTypeId Specifies the GUID for a provider object type not defined by the OLE DB specification.
*/
SetPermissions(Name: string, ObjectType: ObjectTypeEnum.adPermObjProviderSpecific, Action: ActionEnum, Rights: RightsEnum, Inherit: InheritTypeEnum, ObjectTypeId: any): void;
SetPermissions(Name: string, ObjectType: ObjectTypeEnum, Action: ActionEnum, Rights: RightsEnum, Inherit?: InheritTypeEnum): void;
readonly Users: Users;
}
interface Groups {
Append(Item: Group | string): void;
readonly Count: number;
Delete(Item: string | number): void;
Item(Item: string | number): Group;
Refresh(): void;
(Item: string | number): Group;
}
class Index {
private constructor();
private 'ADOX.Index_typekey': Index;
Clustered: boolean;
readonly Columns: Columns;
IndexNulls: AllowNullsEnum;
Name: string;
PrimaryKey: boolean;
readonly Properties: ADODB.Properties;
Unique: boolean;
}
// tslint:disable-next-line:interface-name
interface Indexes {
Append(Item: Index | string, Columns?: string | SafeArray<string>): void; // is this actually two overloads, one with [Index] and one with [string,string | SafeArray<string>]?
readonly Count: number;
Delete(Item: string | number): void;
Item(Item: string | number): Index;
Refresh(): void;
(Item: string | number): Index;
}
class Key {
private constructor();
private 'ADOX.Key_typekey': Key;
readonly Columns: Columns;
DeleteRule: RuleEnum;
Name: string;
RelatedTable: string;
Type: KeyTypeEnum;
UpdateRule: RuleEnum;
}
interface Keys {
/**
* @param Type [Type=1]
* @param RelatedTable [RelatedTable='']
* @param RelatedColumn [RelatedColumn='']
*/
Append(Item: Key | string, Type?: KeyTypeEnum, Column?: string | SafeArray<string>, RelatedTable?: string, RelatedColumn?: string): void;
readonly Count: number;
Delete(Item: string | number): void;
Item(Item: string | number): Key;
Refresh(): void;
(Item: string | number): Key;
}
class Procedure {
private constructor();
private 'ADOX.Procedure_typekey': Procedure;
Command: ADODB.Command;
readonly DateCreated: VarDate | null;
readonly DateModified: VarDate | null;
readonly Name: string;
}
interface Procedures {
Append(Name: string, Command: ADODB.Command): void;
readonly Count: number;
Delete(Item: string | number): void;
Item(Item: string | number): Procedure;
Refresh(): void;
(Item: string | number): Procedure;
}
class Table {
private constructor();
private 'ADOX.Table_typekey': Table;
readonly Columns: Columns;
readonly DateCreated: VarDate;
readonly DateModified: VarDate;
readonly Indexes: Indexes;
readonly Keys: Keys;
Name: string;
ParentCatalog: Catalog;
readonly Properties: ADODB.Properties;
readonly Type: string;
}
interface Tables {
Append(Item: Table | string): void;
readonly Count: number;
Delete(Item: string | number): void;
Item(Item: string | number): Table;
Refresh(): void;
(Item: string | number): Table;
}
class User {
private constructor();
private 'ADOX.User_typekey': User;
ChangePassword(OldPassword: string, NewPassword: string): void;
/**
* @param Name Specifies the name of the object for which to set permissions. Pass `null` if you want to get the permissions for the object container.
* @param ObjectTypeId Specifies the GUID for a provider object type not defined by the OLE DB specification.
*/
GetPermissions(Name: string | null, ObjectType: ObjectTypeEnum.adPermObjProviderSpecific, ObjectTypeId: any): RightsEnum;
GetPermissions(Name: string | null, ObjectType: ObjectTypeEnum): RightsEnum;
readonly Groups: Groups;
Name: string;
ParentCatalog: Catalog;
readonly Properties: ADODB.Properties;
/**
* @param Rights A bitmask of one or more of the **RightsEnum** constants, that indicates the rights to set.
* @param Inherit [Inherit=0]
* @param ObjectTypeId Specifies the GUID for a provider object type not defined by the OLE DB specification.
*/
SetPermissions(Name: string, ObjectType: ObjectTypeEnum.adPermObjProviderSpecific, Action: ActionEnum, Rights: RightsEnum, Inherit: InheritTypeEnum, ObjectTypeId: any): void;
SetPermissions(Name: string, ObjectType: ObjectTypeEnum, Action: ActionEnum, Rights: RightsEnum, Inherit?: InheritTypeEnum): void;
}
interface Users {
/** @param Password [Password=''] */
Append(Item: User | string, Password?: string): void;
readonly Count: number;
Delete(Item: string | number): void;
Item(Item: string | number): User;
Refresh(): void;
(Item: string | number): User;
}
class View {
private constructor();
private 'ADOX.View_typekey': View;
Command: ADODB.Command;
readonly DateCreated: VarDate;
readonly DateModified: VarDate;
readonly Name: string;
}
interface Views {
Append(Name: string, Command: ADODB.Command): void;
readonly Count: number;
Delete(Item: string | number): void;
Item(Item: string | number): View;
Refresh(): void;
(Item: string | number): View;
}
}
interface ActiveXObjectNameMap {
'ADOX.Catalog': ADOX.Catalog;
'ADOX.Column': ADOX.Column;
'ADOX.Group': ADOX.Group;
'ADOX.Index': ADOX.Index;
'ADOX.Key': ADOX.Key;
'ADOX.Table': ADOX.Table;
'ADOX.User': ADOX.User;
}
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-adox-tests.ts"
]
}
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "dtslint/dt.json",
"rules": {
"no-const-enum": false,
"max-line-length": false
}
}
+183
View File
@@ -0,0 +1,183 @@
/// <reference types="windows-script-host" />
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;
};
const dbOpenSnapshot = DAO.RecordsetTypeEnum.dbOpenSnapshot;
let engine = new ActiveXObject('DAO.DBEngine');
let dbsNorthwind = engine.OpenDatabase('c:\\path\\to\\northwind.mdb');
// https://msdn.microsoft.com/VBA/Access-VBA/articles/add-a-record-to-a-dao-recordset
{
// adding a record to a recordset
const rstShippers = dbsNorthwind.OpenRecordset('Shippers');
rstShippers.AddNew();
rstShippers('CompanyName').Value = 'Global Parcel Service';
// Set remaining fields
rstShippers.Update();
rstShippers.Close();
}
// https://msdn.microsoft.com/VBA/Access-VBA/articles/build-sql-statements-that-include-variables-and-controls
{
// create a QueryDef with the given SQL
let sql = 'SELECT * FROM Orders WHERE OrderDate > #3-31-2006#';
let qdf = dbsNorthwind.CreateQueryDef('Second quarter', sql);
// using parameters
sql = `
PARAMETERS QuarterStart DATETIME
SELECT *
FROM Orders
WHERE OrderDate > QuarterStart
`;
qdf = dbsNorthwind.CreateQueryDef('Second quarter (parameters)', sql);
WScript.Echo(`Field names: ${collectionToArray(qdf.Fields).map(fld => fld.Name).join(', ')}`);
}
// https://msdn.microsoft.com/VBA/Access-VBA/articles/count-the-number-of-records-in-a-dao-recordset
/** Count the number of records in a Recordset */
const findRecordCount = (dbs: DAO.Database, sql: string) => {
let count = 0;
const rstRecords = dbs.OpenRecordset(sql);
if (!rstRecords.EOF) {
rstRecords.MoveLast();
count = rstRecords.RecordCount;
}
rstRecords.Close();
return count;
};
// https://msdn.microsoft.com/VBA/Access-VBA/articles/delete-a-record-from-a-dao-recordset
{
// delete records from a Recordset
const rstShippers = dbsNorthwind.OpenRecordset('SELECT * FROM Shippers ORDER BY CompanyName, ShipperID', DAO.RecordsetTypeEnum.dbOpenDynaset);
if (!rstShippers.EOF) {
let name = rstShippers('CompanyName').Value;
rstShippers.MoveNext();
while (!rstShippers.EOF) {
const recordName: string = rstShippers('CompanyName').Value;
if (recordName === name) {
rstShippers.Delete();
} else {
name = recordName;
}
rstShippers.MoveNext();
}
}
rstShippers.Close();
}
// https://msdn.microsoft.com/VBA/Access-VBA/articles/extract-data-from-a-record-in-a-dao-recordset
{
// copy entire records to an array
const rstEmployees = dbsNorthwind.OpenRecordset('SELECT FirstName, LastName, Title FROM Employees', dbOpenSnapshot);
const records = new VBArray<string>(rstEmployees.GetRows(3));
const recordCount = records.ubound(2) + 1;
const columnCount = records.ubound(1) + 1;
for (let row = 0; row < recordCount; row += 1) {
for (let column = 0; column < columnCount; column += 1) {
WScript.Echo(records.getItem(column, row));
}
}
if (rstEmployees.EOF) { WScript.Echo('At end of recordset'); }
rstEmployees.Close();
}
// find a record in a dynaset-type or snapshot-type DAO Recordset -- https://msdn.microsoft.com/en-us/vba/access-vba/articles/find-a-record-in-a-dynaset-type-or-snapshot-type-dao-recordset
{
const orders: number[] = [];
const rstOrders = dbsNorthwind.OpenRecordset('SELECT * FROM Orders ORDER BY OrderID', dbOpenSnapshot);
const rstOrderDetails = dbsNorthwind.OpenRecordset('SELECT * FROM [Order Details] ORDER BY OrderID', dbOpenSnapshot);
if (!rstOrders.EOF && !rstOrderDetails.EOF) {
while (!rstOrders.EOF) {
const orderID = rstOrders('OrderID').Value;
rstOrderDetails.FindFirst(`OrderID=${orderID}`);
if (rstOrderDetails.NoMatch) {
orders.push(orderID);
}
rstOrders.MoveNext();
}
}
rstOrders.Close();
rstOrderDetails.Close();
WScript.Echo(orders.join('\n'));
}
// https://msdn.microsoft.com/VBA/Access-VBA/articles/find-a-record-in-a-table-type-dao-recordset
/** Find a record in a table-type DAO Recordset */
const getHireDate = (employeeID: number) => {
let hireDate: Date | undefined;
const rstEmployees = dbsNorthwind.OpenRecordset('Employees');
rstEmployees.Index = 'PrimaryKey';
rstEmployees.Seek('=', employeeID);
if (!rstEmployees.NoMatch) {
hireDate = new Date(rstEmployees('HireDate').Value as VarDate);
}
return hireDate;
};
// https://msdn.microsoft.com/VBA/Access-VBA/articles/manipulate-multivalued-fields-with-dao
{
// manipulate multiple fields with DAO
const rs = dbsNorthwind.OpenRecordset('Tasks');
rs.MoveFirst();
while (!rs.EOF) {
WScript.Echo(rs('TaskName').Value);
const childRs = rs('AssignedTo').Value as DAO.Recordset;
if (childRs.EOF) { continue; }
childRs.MoveFirst();
while (!childRs.EOF) {
WScript.Echo('\t' + childRs('Value').Value);
}
}
}
// https://msdn.microsoft.com/VBA/Access-VBA/articles/modify-an-existing-record-in-a-dao-recordset
{
// modifying an existing record in a DAO Recordset
const rstEmployees = dbsNorthwind.OpenRecordset('Employees');
while (!rstEmployees.EOF) {
if (rstEmployees('Title').Value === 'Sales Representative') {
rstEmployees.Edit();
rstEmployees('Title').Value = 'Account Executive';
rstEmployees.Update();
}
rstEmployees.MoveNext();
}
rstEmployees.Close();
}
// https://msdn.microsoft.com/VBA/Access-VBA/articles/use-transactions-in-a-dao-recordset
/** using transactions in a DAO Recordset */
const changeTitleWithTransaction = (commitTransaction: boolean) => {
const currentWorkspace = engine.Workspaces(0);
const rstEmployees = dbsNorthwind.OpenRecordset('Employees');
currentWorkspace.BeginTrans();
while (!rstEmployees.EOF) {
if (rstEmployees('Title').Value === 'Sales Representative') {
rstEmployees.Edit();
rstEmployees('Title').Value = 'Account Executive';
rstEmployees.Update();
}
rstEmployees.MoveNext();
}
if (commitTransaction) {
currentWorkspace.CommitTrans();
} else {
currentWorkspace.Rollback();
}
rstEmployees.Close();
currentWorkspace.Close();
};
+898
View File
@@ -0,0 +1,898 @@
// Type definitions for Microsoft Office 16.0 Access Database Engine Object Library - DAO 16.0
// Project: https://msdn.microsoft.com/en-us/library/dn124645.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
/// <reference types="activex-interop" />
declare namespace DAO {
const enum _DAOSuppHelp {
KeepLocal = 0,
LogMessages = 0,
Replicable = 0,
ReplicableBool = 0,
V1xNullBehavior = 0,
}
const enum CollatingOrderEnum {
dbSortArabic = 1025,
dbSortChineseSimplified = 2052,
dbSortChineseTraditional = 1028,
dbSortCyrillic = 1049,
dbSortCzech = 1029,
dbSortDutch = 1043,
dbSortGeneral = 1033,
dbSortGreek = 1032,
dbSortHebrew = 1037,
dbSortHindi = 1081,
dbSortHungarian = 1038,
dbSortIcelandic = 1039,
dbSortJapanese = 1041,
dbSortJapaneseRadicalStrokeCount = 263185,
dbSortKorean = 1042,
dbSortNeutral = 1024,
dbSortNorwdan = 1030,
dbSortPDXIntl = 1033,
dbSortPDXNor = 1030,
dbSortPDXSwe = 1053,
dbSortPolish = 1045,
dbSortSlovenian = 1060,
dbSortSpanish = 1034,
dbSortSwedFin = 1053,
dbSortThai = 1054,
dbSortTurkish = 1055,
dbSortUndefined = -1,
}
const enum CommitTransOptionsEnum {
dbForceOSFlush = 1,
}
const enum CursorDriverEnum {
dbUseClientBatchCursor = 3,
dbUseDefaultCursor = -1,
dbUseNoCursor = 4,
dbUseODBCCursor = 1,
dbUseServerCursor = 2,
}
const enum DatabaseTypeEnum {
/** @deprecated */
dbDecrypt = 4,
/** @deprecated */
dbEncrypt = 2,
dbVersion10 = 1,
dbVersion11 = 8,
dbVersion120 = 128,
dbVersion140 = 256,
dbVersion150 = 512,
dbVersion20 = 16,
dbVersion30 = 32,
dbVersion40 = 64,
}
const enum DataTypeEnum {
dbAttachment = 101,
dbBigInt = 16,
dbBinary = 9,
dbBoolean = 1,
dbByte = 2,
dbChar = 18,
dbComplexByte = 102,
dbComplexDecimal = 108,
dbComplexDouble = 106,
dbComplexGUID = 107,
dbComplexInteger = 103,
dbComplexLong = 104,
dbComplexSingle = 105,
dbComplexText = 109,
dbCurrency = 5,
dbDate = 8,
dbDecimal = 20,
dbDouble = 7,
dbFloat = 21,
dbGUID = 15,
dbInteger = 3,
dbLong = 4,
dbLongBinary = 11,
dbMemo = 12,
dbNumeric = 19,
dbSingle = 6,
dbText = 10,
dbTime = 22,
dbTimeStamp = 23,
dbVarBinary = 17,
}
const enum DriverPromptEnum {
dbDriverComplete = 0,
dbDriverCompleteRequired = 3,
dbDriverNoPrompt = 1,
dbDriverPrompt = 2,
}
const enum EditModeEnum {
dbEditAdd = 2,
dbEditInProgress = 1,
dbEditNone = 0,
}
const enum FieldAttributeEnum {
dbAutoIncrField = 16,
dbDescending = 1,
dbFixedField = 1,
dbHyperlinkField = 32768,
dbSystemField = 8192,
dbUpdatableField = 32,
dbVariableField = 2,
}
const enum IdleEnum {
dbFreeLocks = 1,
dbRefreshCache = 8,
}
const enum ISAMStatsEnum {
DiskReads = 0,
DiskWrites = 1,
LocksPlaced = 4,
LocksReleased = 5,
ReadsFromCache = 2,
ReadsFromReadAheadCache = 3,
}
const enum LanguageConstants {
dbLangArabic = ';LANGID=0x0401;CP=1256;COUNTRY=0',
dbLangChineseSimplified = ';LANGID=0x0804;CP=936;COUNTRY=0',
dbLangChineseTraditional = ';LANGID=0x0404;CP=950;COUNTRY=0',
dbLangCyrillic = ';LANGID=0x0419;CP=1251;COUNTRY=0',
dbLangCzech = ';LANGID=0x0405;CP=1250;COUNTRY=0',
dbLangDutch = ';LANGID=0x0413;CP=1252;COUNTRY=0',
dbLangGeneral = ';LANGID=0x0409;CP=1252;COUNTRY=0',
dbLangGreek = ';LANGID=0x0408;CP=1253;COUNTRY=0',
dbLangHebrew = ';LANGID=0x040D;CP=1255;COUNTRY=0',
dbLangHindi = ';LANGID=0x00000439;CP=65001;COUNTRY=0',
dbLangHungarian = ';LANGID=0x040E;CP=1250;COUNTRY=0',
dbLangIcelandic = ';LANGID=0x040F;CP=1252;COUNTRY=0',
dbLangJapanese = ';LANGID=0x0411;CP=932;COUNTRY=0',
dbLangJapaneseRadicalStrokeCount = ';LANGID=0x00040411;CP=65001;COUNTRY=0',
dbLangKorean = ';LANGID=0x0412;CP=949;COUNTRY=0',
dbLangNordic = ';LANGID=0x041D;CP=1252;COUNTRY=0',
dbLangNorwDan = ';LANGID=0x0406;CP=1252;COUNTRY=0',
dbLangPolish = ';LANGID=0x0415;CP=1250;COUNTRY=0',
dbLangSlovenian = ';LANGID=0x0424;CP=1250;COUNTRY=0',
dbLangSpanish = ';LANGID=0x040A;CP=1252;COUNTRY=0',
dbLangSwedFin = ';LANGID=0x041D;CP=1252;COUNTRY=0',
dbLangThai = ';LANGID=0x041E;CP=874;COUNTRY=0',
dbLangTurkish = ';LANGID=0x041F;CP=1254;COUNTRY=0',
}
const enum LockTypeEnum {
dbOptimistic = 3,
dbOptimisticBatch = 5,
dbOptimisticValue = 1,
dbPessimistic = 2,
}
const enum ParameterDirectionEnum {
dbParamInput = 1,
dbParamInputOutput = 3,
dbParamOutput = 2,
dbParamReturnValue = 4,
}
const enum PermissionEnum {
dbSecCreate = 1,
dbSecDBAdmin = 8,
dbSecDBCreate = 1,
dbSecDBExclusive = 4,
dbSecDBOpen = 2,
dbSecDelete = 65536,
dbSecDeleteData = 128,
dbSecFullAccess = 1048575,
dbSecInsertData = 32,
dbSecNoAccess = 0,
dbSecReadDef = 4,
dbSecReadSec = 131072,
dbSecReplaceData = 64,
dbSecRetrieveData = 20,
dbSecWriteDef = 65548,
dbSecWriteOwner = 524288,
dbSecWriteSec = 262144,
}
const enum QueryDefStateEnum {
dbQPrepare = 1,
dbQUnprepare = 2,
}
const enum QueryDefTypeEnum {
dbQAction = 240,
dbQAppend = 64,
dbQCompound = 160,
dbQCrosstab = 16,
dbQDDL = 96,
dbQDelete = 32,
dbQMakeTable = 80,
dbQProcedure = 224,
dbQSelect = 0,
dbQSetOperation = 128,
dbQSPTBulk = 144,
dbQSQLPassThrough = 112,
dbQUpdate = 48,
}
const enum RecordsetOptionEnum {
dbAppendOnly = 8,
dbConsistent = 32,
dbDenyRead = 2,
dbDenyWrite = 1,
dbExecDirect = 2048,
dbFailOnError = 128,
dbForwardOnly = 256,
dbInconsistent = 16,
dbReadOnly = 4,
dbRunAsync = 1024,
dbSeeChanges = 512,
dbSQLPassThrough = 64,
}
const enum RecordsetTypeEnum {
dbOpenDynamic = 16,
dbOpenDynaset = 2,
dbOpenForwardOnly = 8,
dbOpenSnapshot = 4,
dbOpenTable = 1,
}
const enum RecordStatusEnum {
dbRecordDBDeleted = 4,
dbRecordDeleted = 3,
dbRecordModified = 1,
dbRecordNew = 2,
dbRecordUnmodified = 0,
}
const enum RelationAttributeEnum {
dbRelationDeleteCascade = 4096,
dbRelationDontEnforce = 2,
dbRelationInherited = 4,
dbRelationLeft = 16777216,
dbRelationRight = 33554432,
dbRelationUnique = 1,
dbRelationUpdateCascade = 256,
}
const enum ReplicaTypeEnum {
dbRepMakePartial = 1,
dbRepMakeReadOnly = 2,
}
const enum SetOptionEnum {
dbExclusiveAsyncDelay = 60,
dbFlushTransactionTimeout = 66,
dbImplicitCommitSync = 59,
dbLockDelay = 63,
dbLockRetry = 57,
dbMaxBufferSize = 8,
dbMaxLocksPerFile = 62,
dbPageTimeout = 6,
dbPasswordEncryptionAlgorithm = 81,
dbPasswordEncryptionKeyLength = 82,
dbPasswordEncryptionProvider = 80,
dbRecycleLVs = 65,
dbSharedAsyncDelay = 61,
dbUserCommitSync = 58,
}
const enum SynchronizeTypeEnum {
dbRepExportChanges = 1,
dbRepImpExpChanges = 4,
dbRepImportChanges = 2,
dbRepSyncInternet = 16,
}
const enum TableDefAttributeEnum {
dbAttachedODBC = 536870912,
dbAttachedTable = 1073741824,
dbAttachExclusive = 65536,
dbAttachSavePWD = 131072,
dbHiddenObject = 1,
dbSystemObject = -2147483646,
}
const enum UpdateCriteriaEnum {
dbCriteriaAllCols = 4,
dbCriteriaDeleteInsert = 16,
dbCriteriaKey = 1,
dbCriteriaModValues = 2,
dbCriteriaTimestamp = 8,
dbCriteriaUpdate = 32,
}
const enum UpdateTypeEnum {
dbUpdateBatch = 4,
dbUpdateCurrentRecord = 2,
dbUpdateRegular = 1,
}
const enum WorkspaceTypeEnum {
dbUseJet = 2,
dbUseODBC = 1,
}
type Bookmark = SafeArray<number>;
class ComplexType {
private 'DAO.ComplexType_typekey': ComplexType;
private constructor();
readonly Fields: Fields;
}
class Connection {
private 'DAO.Connection_typekey': Connection;
private constructor();
Cancel(): void;
Close(): void;
readonly Connect: string;
CreateQueryDef(Name?: string, SQLText?: string): QueryDef;
readonly Database: Database;
Execute(Query: string, Options?: RecordsetOptionEnum): void;
readonly hDbc: number;
readonly Name: string;
OpenRecordset(Name: string, Type?: RecordsetTypeEnum, Options?: RecordsetOptionEnum, LockEdit?: LockTypeEnum): Recordset;
readonly QueryDefs: QueryDefs;
QueryTimeout: number;
readonly RecordsAffected: number;
readonly Recordsets: Recordsets;
readonly StillExecuting: boolean;
readonly Transactions: boolean;
readonly Updatable: boolean;
}
interface Connections {
readonly Count: number;
Item(Item: number | string): Connection;
Refresh(): void;
(Item: number | string): Connection;
}
class Container {
private 'DAO.Container_typekey': Container;
private constructor();
readonly AllPermissions: number;
readonly Documents: Documents;
Inherit: boolean;
readonly Name: string;
Owner: string;
Permissions: number;
readonly Properties: Properties;
UserName: string;
}
interface Containers {
readonly Count: number;
Item(Item: number | string): Container;
Refresh(): void;
(Item: number | string): Container;
}
class Database {
private 'DAO.Database_typekey': Database;
private constructor();
Close(): void;
readonly CollatingOrder: number;
Connect: string;
readonly Connection: Connection;
readonly Containers: Containers;
CreateProperty(Name?: string, Type?: DataTypeEnum, Value?: any, DDL?: boolean): Property;
CreateQueryDef(Name?: string, SQLText?: string): QueryDef;
CreateRelation(Name?: string, Table?: string, ForeignTable?: string, Attributes?: RelationAttributeEnum): Relation;
CreateTableDef(Name?: string, Attributes?: TableDefAttributeEnum, SourceTableName?: string, Connect?: string): TableDef;
DesignMasterID: string;
Execute(Query: string, Options?: RecordsetOptionEnum): void;
MakeReplica(PathName: string, Description: string, Options?: ReplicaTypeEnum): void;
readonly Name: string;
NewPassword(bstrOld: string, bstrNew: string): void;
OpenRecordset(Name: string, Type?: RecordsetTypeEnum, Options?: RecordsetOptionEnum, LockEdit?: LockTypeEnum): Recordset;
PopulatePartial(DbPathName: string): void;
readonly Properties: Properties;
readonly QueryDefs: QueryDefs;
QueryTimeout: number;
readonly RecordsAffected: number;
readonly Recordsets: Recordsets;
readonly Relations: Relations;
readonly ReplicaID: string;
Synchronize(DbPathName: string, ExchangeType?: SynchronizeTypeEnum): void;
readonly TableDefs: TableDefs;
readonly Transactions: boolean;
readonly Updatable: boolean;
readonly Version: string;
}
interface Databases {
readonly Count: number;
Item(Item: number | string): Database;
Refresh(): void;
(Item: number | string): Database;
}
class DBEngine {
private 'DAO.DBEngine_typekey': DBEngine;
private constructor();
BeginTrans(): void;
/** @param Option [Option=0] */
CommitTrans(Option?: number): void;
/**
* Compact a closed database
*
* @param DstLocale Specify one of the following:
* * the locale, using one of the language constants
* * the password, in the form `;pwd=MyNewPassword'`
* * both the constant and a password, e.g. `dbLangGreek + ';pwd=MyNewPassword'`
*
* @param Options `dbEncrypt` and `dbDecrypt` are deprecated, and unsupported for ACCDB
* @param password Deprecated, and unsupported for ACCDB
*/
CompactDatabase(SrcName: string, DstName: string, DstLocale?: LanguageConstants | string, Options?: DatabaseTypeEnum, password?: string): void;
/**
* @param Locale Specify one of the following:
* * the locale, using one of the language constants
* * the password, in the form `;pwd=MyNewPassword'`
* * both the constant and a password, e.g. `dbLangGreek + ';pwd=MyNewPassword'`
*/
CreateDatabase(Name: string, Locale: LanguageConstants | string, Option?: DatabaseTypeEnum): Database;
CreateWorkspace(Name: string, UserName: string, Password: string, UseType?: WorkspaceTypeEnum): Workspace;
readonly DefaultPassword: string;
DefaultType: number;
readonly DefaultUser: string;
readonly Errors: Errors;
Idle(Action?: IdleEnum): void;
IniPath: string;
/** Returns various statistics from the Jet engine */
ISAMStats(StatNum: ISAMStatsEnum, Reset?: boolean): number;
LoginTimeout: number;
/**
* @param Connect ODBC connection string; prepend with `ODBC;`
*/
OpenConnection(Name: string, Options?: DriverPromptEnum | RecordsetOptionEnum.dbRunAsync, ReadOnly?: boolean, Connect?: string): Connection;
OpenDatabase(Name: string, Exclusive?: boolean, ReadOnly?: boolean, Connect?: string): Database;
readonly Properties: Properties;
RegisterDatabase(Dsn: string, Driver: string, Silent: boolean, Attributes: string): void;
RepairDatabase(Name: string): void;
Rollback(): void;
SetOption(Option: SetOptionEnum, Value: any): void;
SystemDB: string;
readonly Version: string;
readonly Workspaces: Workspaces;
}
class Document {
private 'DAO.Document_typekey': Document;
private constructor();
readonly AllPermissions: number;
readonly Container: string;
CreateProperty(Name?: string, Type?: DataTypeEnum, Value?: any, DDL?: boolean): Property;
readonly DateCreated: VarDate;
readonly LastUpdated: VarDate;
readonly Name: string;
Owner: string;
Permissions: number;
readonly Properties: Properties;
UserName: string;
}
interface Documents {
readonly Count: number;
Item(Item: number | string): Document;
Refresh(): void;
(Item: number | string): Document;
}
class Error {
private 'DAO.Error_typekey': Error;
private constructor();
readonly Description: string;
readonly HelpContext: number;
readonly HelpFile: string;
readonly Number: number;
readonly Source: string;
}
interface Errors {
readonly Count: number;
Item(Item: any): Error;
Refresh(): void;
(Item: any): Error;
}
class Field {
private constructor();
private 'DAO.Field2_typekey': Field;
AllowZeroLength: boolean;
AppendChunk(Val: any): void;
AppendOnly: boolean;
Attributes: number;
readonly CollatingOrder: number;
readonly CollectionIndex: number;
readonly ComplexType: ComplexType;
CreateProperty(Name?: string, Type?: DataTypeEnum, Value?: any, DDL?: boolean): Property;
readonly DataUpdatable: boolean;
DefaultValue: any;
Expression: string;
readonly FieldSize: number;
ForeignName: string;
GetChunk(Offset: number, Bytes: number): any;
readonly IsComplex: boolean;
LoadFromFile(FileName: string): void;
Name: string;
OrdinalPosition: number;
readonly OriginalValue: any;
readonly Properties: Properties;
Required: boolean;
SaveToFile(FileName: string): void;
Size: number;
readonly SourceField: string;
readonly SourceTable: string;
Type: number;
ValidateOnSet: boolean;
ValidationRule: string;
ValidationText: string;
Value: any;
readonly VisibleValue: any;
}
interface Fields {
Append(Field: Field): void;
readonly Count: number;
Delete(Name: string): void;
Item(Item: number | string): Field;
Refresh(): void;
(Item: number | string): Field;
}
class Group {
private 'DAO.Group_typekey': Group;
private constructor();
CreateUser(Name?: string, PID?: string, Password?: string): User;
Name: string;
readonly PID: string;
readonly Properties: Properties;
readonly Users: Users;
}
interface Groups {
Append(Group: Group): void;
readonly Count: number;
Delete(Name: string): void;
Item(Item: number | string): Group;
Refresh(): void;
(Item: number | string): Group;
}
class Index {
private 'DAO.Index_typekey': Index;
private constructor();
Clustered: boolean;
CreateField(Name?: string): Field;
CreateProperty(Name?: string, Type?: DataTypeEnum, Value?: any, DDL?: boolean): Property;
readonly DistinctCount: number;
Fields: Fields;
readonly Foreign: boolean;
IgnoreNulls: boolean;
Name: string;
Primary: boolean;
readonly Properties: Properties;
Required: boolean;
Unique: boolean;
}
// tslint:disable-next-line:interface-name
interface Indexes {
Append(Index: Index): void;
readonly Count: number;
Delete(Name: string): void;
Item(Item: number | string): Index;
Refresh(): void;
(Item: number | string): Index;
}
class Parameter {
private 'DAO.Parameter_typekey': Parameter;
private constructor();
Direction: number;
readonly Name: string;
readonly Properties: Properties;
Type: number;
Value: any;
}
interface Parameters {
readonly Count: number;
Item(Item: number | string): Parameter;
Refresh(): void;
(Item: number | string): Parameter;
}
interface Properties {
Append(Property: Property): void;
readonly Count: number;
Delete(Name: string): void;
Item(Item: number | string): Property;
Refresh(): void;
(Item: number | string): Property;
}
class Property {
private 'DAO.Property_typekey': Property;
private constructor();
readonly Inherited: boolean;
Name: string;
readonly Properties: Properties;
Type: number;
Value: any;
}
class QueryDef {
private 'DAO.QueryDef_typekey': QueryDef;
private constructor();
CacheSize: number;
Cancel(): void;
Close(): void;
Connect: string;
CreateProperty(Name?: string, Type?: DataTypeEnum, Value?: any, DDL?: boolean): Property;
readonly DateCreated: VarDate;
Execute(Options?: RecordsetOptionEnum): void;
readonly Fields: Fields;
readonly hStmt: number;
readonly LastUpdated: VarDate;
MaxRecords: number;
Name: string;
ODBCTimeout: number;
OpenRecordset(Type?: RecordsetTypeEnum, Options?: RecordsetOptionEnum, LockEdit?: LockTypeEnum): Recordset;
readonly Parameters: Parameters;
Prepare: QueryDefStateEnum;
readonly Properties: Properties;
readonly RecordsAffected: number;
ReturnsRecords: boolean;
SQL: string;
readonly StillExecuting: boolean;
readonly Type: QueryDefTypeEnum;
readonly Updatable: boolean;
}
interface QueryDefs {
Append(QueryDef: QueryDef): void;
readonly Count: number;
Delete(Name: string): void;
Item(Item: number | string): QueryDef;
Refresh(): void;
(Item: number | string): QueryDef;
}
interface Recordset {
AbsolutePosition: number;
AddNew(): void;
readonly BatchCollisionCount: number;
readonly BatchCollisions: SafeArray<Bookmark>;
BatchSize: number;
readonly BOF: boolean;
Bookmark: Bookmark;
readonly Bookmarkable: boolean;
CacheSize: number;
CacheStart: Bookmark;
Cancel(): void;
/** @param UpdateType [UpdateType=1] */
CancelUpdate(UpdateType?: number): void;
Clone(): Recordset;
Close(): void;
Collect(Item: any): any;
Connection: Connection;
CopyQueryDef(): QueryDef;
readonly DateCreated: VarDate;
Delete(): void;
Edit(): void;
readonly EditMode: EditModeEnum;
readonly EOF: boolean;
readonly Fields: Fields;
FillCache(Rows?: number, StartBookmark?: string): void;
Filter: string;
FindFirst(Criteria: string): void;
FindLast(Criteria: string): void;
FindNext(Criteria: string): void;
FindPrevious(Criteria: string): void;
GetRows(NumRows?: number): any;
readonly hStmt: number;
Index: string;
readonly LastModified: Bookmark;
readonly LastUpdated: VarDate;
LockEdits: boolean;
Move(Rows: number, StartBookmark?: Bookmark): void;
MoveFirst(): void;
/** @param Options [Options=0] */
MoveLast(Options?: number): void;
MoveNext(): void;
MovePrevious(): void;
readonly Name: string;
NextRecordset(): boolean;
readonly NoMatch: boolean;
readonly ODBCFetchCount: number;
readonly ODBCFetchDelay: number;
OpenRecordset(Type?: RecordsetTypeEnum, Options?: RecordsetOptionEnum): Recordset;
readonly Parent: Database;
PercentPosition: number;
readonly Properties: Properties;
readonly RecordCount: number;
readonly RecordStatus: number;
Requery(NewQueryDef?: QueryDef): void;
readonly Restartable: boolean;
Seek(Comparison: string, Key1: any, Key2?: any, Key3?: any, Key4?: any, Key5?: any, Key6?: any, Key7?: any, Key8?: any, Key9?: any, Key10?: any, Key11?: any, Key12?: any, Key13?: any): void;
Sort: string;
readonly StillExecuting: boolean;
readonly Transactions: boolean;
readonly Type: RecordsetTypeEnum;
readonly Updatable: boolean;
/**
* @param UpdateType [UpdateType=1]
* @param Force [Force=false]
*/
Update(UpdateType?: UpdateTypeEnum, Force?: boolean): void;
UpdateOptions: UpdateCriteriaEnum;
readonly ValidationRule: string;
readonly ValidationText: string;
(FieldIndex: number | string): Field;
}
interface Recordsets {
readonly Count: number;
Item(Item: number | string): Recordset;
Refresh(): void;
(Item: number | string): Recordset;
}
class Relation {
private 'DAO.Relation_typekey': Relation;
private constructor();
Attributes: RelationAttributeEnum;
CreateField(Name?: string): Field;
readonly Fields: Fields;
ForeignTable: string;
Name: string;
PartialReplica: boolean;
readonly Properties: Properties;
Table: string;
}
interface Relations {
Append(Relation: Relation): void;
readonly Count: number;
Delete(Name: string): void;
Item(Item: number | string): Relation;
Refresh(): void;
(Item: number | string): Relation;
}
class TableDef {
private 'DAO.TableDef_typekey': TableDef;
private constructor();
Attributes: TableDefAttributeEnum;
readonly ConflictTable: string;
Connect: string;
CreateField(Name?: string, Type?: DataTypeEnum, Size?: number): Field;
CreateIndex(Name?: string): Index;
CreateProperty(Name?: string, Type?: DataTypeEnum, Value?: any, DDL?: boolean): Property;
readonly DateCreated: VarDate;
readonly Fields: Fields;
readonly Indexes: Indexes;
readonly LastUpdated: VarDate;
Name: string;
OpenRecordset(Type?: RecordsetTypeEnum, Options?: RecordsetOptionEnum): Recordset;
readonly Properties: Properties;
readonly RecordCount: number;
RefreshLink(): void;
ReplicaFilter: string | boolean;
SourceTableName: string;
readonly Updatable: boolean;
ValidationRule: string;
ValidationText: string;
}
interface TableDefs {
Append(TableDef: TableDef): void;
readonly Count: number;
Delete(Name: string): void;
Item(Item: number | string): TableDef;
Refresh(): void;
(Item: number | string): TableDef;
}
class User {
private 'DAO.User_typekey': User;
private constructor();
CreateGroup(Name?: string, PID?: string): Group;
readonly Groups: Groups;
Name: string;
NewPassword(bstrOld: string, bstrNew: string): void;
readonly Password: string;
readonly PID: string;
readonly Properties: Properties;
}
interface Users {
Append(User: User): void;
readonly Count: number;
Delete(Name: string): void;
Item(Item: number | string): User;
Refresh(): void;
(Item: number | string): User;
}
class Workspace {
private 'DAO.Workspace_typekey': Workspace;
private constructor();
BeginTrans(): void;
Close(): void;
/** @param Options [Options=0] */
CommitTrans(Options?: number): void;
readonly Connections: Connections;
/**
* @param Connect Specify one of the following:
* * the locale, using one of the language constants
* * the password, in the form `;pwd=MyNewPassword'`
* * both the constant and a password, e.g. `dbLangGreek + ';pwd=MyNewPassword'`
*/
CreateDatabase(Name: string, Connect: string, Option?: DatabaseTypeEnum): Database;
CreateGroup(Name?: string, PID?: string): Group;
CreateUser(Name?: string, PID?: string, Password?: string): User;
readonly Databases: Databases;
DefaultCursorDriver: number;
readonly Groups: Groups;
readonly hEnv: number;
IsolateODBCTrans: number;
LoginTimeout: number;
Name: string;
/**
* @param Connect ODBC connection string; prepend with `ODBC;`
*/
OpenConnection(Name: string, Options?: DriverPromptEnum | RecordsetOptionEnum.dbRunAsync, ReadOnly?: boolean, Connect?: string): Connection;
OpenDatabase(Name: string, Exclusive?: boolean, ReadOnly?: boolean, Connect?: string): Database;
readonly Properties: Properties;
Rollback(): void;
readonly Type: number;
readonly UserName: string;
readonly Users: Users;
}
interface Workspaces {
Append(Workspace: Workspace): void;
readonly Count: number;
Delete(Name: string): void;
Item(Item: number | string): Workspace;
Refresh(): void;
(Item: number | string): Workspace;
}
}
interface ActiveXObjectNameMap {
'DAO.DBEngine': DAO.DBEngine;
'DAO.Field': DAO.Field;
'DAO.Group': DAO.Group;
'DAO.Index': DAO.Index;
'DAO.PrivateDBEngine': DAO.DBEngine;
'DAO.QueryDef': DAO.QueryDef;
'DAO.Relation': DAO.Relation;
'DAO.TableDef': DAO.TableDef;
'DAO.User': DAO.User;
}
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-dao-tests.ts"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"no-const-enum": false
}
}
@@ -1,18 +0,0 @@
//open connection to an Excel file
var pathToExcelFile = 'C:\\path\\to\\excel\\file.xlsx';
var conn = new ActiveXObject('ADODB.Connection');
conn.Provider = 'Microsoft.ACE.OLEDB.12.0';
conn.ConnectionString =
'Data Source="' + pathToExcelFile + '";' +
'Extended Properties="Excel 12.0;HDR=Yes"';
conn.Open();
//create a Command to access the data
var cmd = new ActiveXObject('ADODB.Command');
cmd.CommandText = 'SELECT DISTINCT LastName, CityName FROM [Sheet1$]';
//get a Recordset
var rs = cmd.Execute();
//build a string from the Recordset
var s = rs.GetString(ADODB.StringFormatEnum.adClipString, -1, '\t', '\n', '(NULL)');
rs.Close();
WScript.Echo(s);
-834
View File
@@ -1,834 +0,0 @@
// Type definitions for Microsoft ActiveX Data Objects
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms675532(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace ADODB {
//Enums
const enum ADCPROP_ASYNCTHREADPRIORITY_ENUM {
adPriorityAboveNormal = 4,
adPriorityBelowNormal = 2,
adPriorityHighest = 5,
adPriorityLowest = 1,
adPriorityNormal = 3
}
const enum ADCPROP_AUTORECALC_ENUM {
adRecalcAlways = 1,
adRecalcUpFront = 0
}
const enum ADCPROP_UPDATECRITERIA_ENUM {
adCriteriaAllCols = 1,
adCriteriaKey = 0,
adCriteriaTimeStamp = 3,
adCriteriaUpdCols = 2
}
const enum ADCPROP_UPDATERESYNC_ENUM {
adResyncAll = 15,
adResyncAutoIncrement = 1,
adResyncConflicts = 2,
adResyncInserts = 8,
adResyncNone = 0,
adResyncUpdates = 4
}
const enum AffectEnum {
adAffectAll = 3,
adAffectAllChapters = 4,
adAffectCurrent = 1,
adAffectGroup = 2
}
const enum BookmarkEnum {
adBookmarkCurrent = 0,
adBookmarkFirst = 1,
adBookmarkLast = 2
}
const enum CommandTypeEnum {
adCmdFile = 256,
adCmdStoredProc = 4,
adCmdTable = 2,
adCmdTableDirect = 512,
adCmdText = 1,
adCmdUnknown = 8,
adCmdUnspecified = -1
}
const enum CompareEnum {
adCompareEqual = 1,
adCompareGreaterThan = 2,
adCompareLessThan = 0,
adCompareNotComparable = 4,
adCompareNotEqual = 3
}
const enum ConnectModeEnum {
adModeRead = 1,
adModeReadWrite = 3,
adModeRecursive = 4194304,
adModeShareDenyNone = 16,
adModeShareDenyRead = 4,
adModeShareDenyWrite = 8,
adModeShareExclusive = 12,
adModeUnknown = 0,
adModeWrite = 2
}
const enum ConnectOptionEnum {
adAsyncConnect = 16,
adConnectUnspecified = -1
}
const enum ConnectPromptEnum {
adPromptAlways = 1,
adPromptComplete = 2,
adPromptCompleteRequired = 3,
adPromptNever = 4
}
const enum CopyRecordOptionsEnum {
adCopyAllowEmulation = 4,
adCopyNonRecursive = 2,
adCopyOverWrite = 1,
adCopyUnspecified = -1
}
const enum CursorLocationEnum {
adUseClient = 3,
adUseClientBatch = 3,
adUseNone = 1,
adUseServer = 2
}
const enum CursorOptionEnum {
adAddNew = 16778240,
adApproxPosition = 16384,
adBookmark = 8192,
adDelete = 16779264,
adFind = 524288,
adHoldRecords = 256,
adIndex = 8388608,
adMovePrevious = 512,
adNotify = 262144,
adResync = 131072,
adSeek = 4194304,
adUpdate = 16809984,
adUpdateBatch = 65536
}
const enum CursorTypeEnum {
adOpenDynamic = 2,
adOpenForwardOnly = 0,
adOpenKeyset = 1,
adOpenStatic = 3,
adOpenUnspecified = -1
}
const enum DataTypeEnum {
adArray = 8192,
adBigInt = 20,
adBinary = 128,
adBoolean = 11,
adBSTR = 8,
adChapter = 136,
adChar = 129,
adCurrency = 6,
adDate = 7,
adDBDate = 133,
adDBTime = 134,
adDBTimeStamp = 135,
adDecimal = 14,
adDouble = 5,
adEmpty = 0,
adError = 10,
adFileTime = 64,
adGUID = 72,
adIDispatch = 9,
adInteger = 3,
adIUnknown = 13,
adLongVarBinary = 205,
adLongVarChar = 201,
adLongVarWChar = 203,
adNumeric = 131,
adPropVariant = 138,
adSingle = 4,
adSmallInt = 2,
adTinyInt = 16,
adUnsignedBigInt = 21,
adUnsignedInt = 19,
adUnsignedSmallInt = 18,
adUnsignedTinyInt = 17,
adUserDefined = 132,
adVarBinary = 204,
adVarChar = 200,
adVariant = 12,
adVarNumeric = 139,
adVarWChar = 202,
adWChar = 130
}
const enum EditModeEnum {
adEditAdd = 2,
adEditDelete = 4,
adEditInProgress = 1,
adEditNone = 0
}
const enum ErrorValueEnum {
adErrBoundToCommand = 3707,
adErrCannotComplete = 3732,
adErrCantChangeConnection = 3748,
adErrCantChangeProvider = 3220,
adErrCantConvertvalue = 3724,
adErrCantCreate = 3725,
adErrCatalogNotSet = 3747,
adErrColumnNotOnThisRow = 3726,
adErrConnectionStringTooLong = 3754,
adErrDataConversion = 3421,
adErrDataOverflow = 3721,
adErrDelResOutOfScope = 3738,
adErrDenyNotSupported = 3750,
adErrDenyTypeNotSupported = 3751,
adErrFeatureNotAvailable = 3251,
adErrFieldsUpdateFailed = 3749,
adErrIllegalOperation = 3219,
adErrIntegrityViolation = 3719,
adErrInTransaction = 3246,
adErrInvalidArgument = 3001,
adErrInvalidConnection = 3709,
adErrInvalidParamInfo = 3708,
adErrInvalidTransaction = 3714,
adErrInvalidURL = 3729,
adErrItemNotFound = 3265,
adErrNoCurrentRecord = 3021,
adErrNotExecuting = 3715,
adErrNotReentrant = 3710,
adErrObjectClosed = 3704,
adErrObjectInCollection = 3367,
adErrObjectNotSet = 3420,
adErrObjectOpen = 3705,
adErrOpeningFile = 3002,
adErrOperationCancelled = 3712,
adErrOutOfSpace = 3734,
adErrPermissionDenied = 3720,
adErrPropConflicting = 3742,
adErrPropInvalidColumn = 3739,
adErrPropInvalidOption = 3740,
adErrPropInvalidValue = 3741,
adErrPropNotAllSettable = 3743,
adErrPropNotSet = 3744,
adErrPropNotSettable = 3745,
adErrPropNotSupported = 3746,
adErrProviderFailed = 3000,
adErrProviderNotFound = 3706,
adErrProviderNotSpecified = 3753,
adErrReadFile = 3003,
adErrResourceExists = 3731,
adErrResourceLocked = 3730,
adErrResourceOutOfScope = 3735,
adErrSchemaViolation = 3722,
adErrSignMismatch = 3723,
adErrStillConnecting = 3713,
adErrStillExecuting = 3711,
adErrTreePermissionDenied = 3728,
adErrUnavailable = 3736,
adErrUnsafeOperation = 3716,
adErrURLDoesNotExist = 3727,
adErrURLNamedRowDoesNotExist = 3737,
adErrVolumeNotFound = 3733,
adErrWriteFile = 3004,
adwrnSecurityDialog = 3717,
adwrnSecurityDialogHeader = 3718
}
const enum EventReasonEnum {
adRsnAddNew = 1,
adRsnClose = 9,
adRsnDelete = 2,
adRsnFirstChange = 11,
adRsnMove = 10,
adRsnMoveFirst = 12,
adRsnMoveLast = 15,
adRsnMoveNext = 13,
adRsnMovePrevious = 14,
adRsnRequery = 7,
adRsnResynch = 8,
adRsnUndoAddNew = 5,
adRsnUndoDelete = 6,
adRsnUndoUpdate = 4,
adRsnUpdate = 3
}
const enum EventStatusEnum {
adStatusCancel = 4,
adStatusCantDeny = 3,
adStatusErrorsOccurred = 2,
adStatusOK = 1,
adStatusUnwantedEvent = 5
}
const enum ExecuteOptionEnum {
adAsyncExecute = 16,
adAsyncFetch = 32,
adAsyncFetchNonBlocking = 64,
adExecuteNoRecords = 128,
adExecuteRecord = 2048,
adExecuteStream = 1024,
adOptionUnspecified = -1
}
const enum FieldAttributeEnum {
adFldCacheDeferred = 4096,
adFldFixed = 16,
adFldIsChapter = 8192,
adFldIsCollection = 262144,
adFldIsDefaultStream = 131072,
adFldIsNullable = 32,
adFldIsRowURL = 65536,
adFldKeyColumn = 32768,
adFldLong = 128,
adFldMayBeNull = 64,
adFldMayDefer = 2,
adFldNegativeScale = 16384,
adFldRowID = 256,
adFldRowVersion = 512,
adFldUnknownUpdatable = 8,
adFldUnspecified = -1,
adFldUpdatable = 4
}
const enum FieldEnum {
adDefaultStream = -1,
adRecordURL = -2
}
const enum FieldStatusEnum {
adFieldAlreadyExists = 26,
adFieldBadStatus = 12,
adFieldCannotComplete = 20,
adFieldCannotDeleteSource = 23,
adFieldCantConvertValue = 2,
adFieldCantCreate = 7,
adFieldDataOverflow = 6,
adFieldDefault = 13,
adFieldDoesNotExist = 16,
adFieldIgnore = 15,
adFieldIntegrityViolation = 10,
adFieldInvalidURL = 17,
adFieldIsNull = 3,
adFieldOK = 0,
adFieldOutOfSpace = 22,
adFieldPendingChange = 262144,
adFieldPendingDelete = 131072,
adFieldPendingInsert = 65536,
adFieldPendingUnknown = 524288,
adFieldPendingUnknownDelete = 1048576,
adFieldPermissionDenied = 9,
adFieldReadOnly = 24,
adFieldResourceExists = 19,
adFieldResourceLocked = 18,
adFieldResourceOutOfScope = 25,
adFieldSchemaViolation = 11,
adFieldSignMismatch = 5,
adFieldTruncated = 4,
adFieldUnavailable = 8,
adFieldVolumeNotFound = 21
}
const enum FilterGroupEnum {
adFilterAffectedRecords = 2,
adFilterConflictingRecords = 5,
adFilterFetchedRecords = 3,
adFilterNone = 0,
adFilterPendingRecords = 1,
adFilterPredicate = 4
}
const enum GetRowsOptionEnum {
adGetRowsRest = -1
}
const enum IsolationLevelEnum {
adXactBrowse = 256,
adXactChaos = 16,
adXactCursorStability = 4096,
adXactIsolated = 1048576,
adXactReadCommitted = 4096,
adXactReadUncommitted = 256,
adXactRepeatableRead = 65536,
adXactSerializable = 1048576,
adXactUnspecified = -1
}
const enum LineSeparatorEnum {
adCR = 13,
adCRLF = -1,
adLF = 10
}
const enum LockTypeEnum {
adLockBatchOptimistic = 4,
adLockOptimistic = 3,
adLockPessimistic = 2,
adLockReadOnly = 1,
adLockUnspecified = -1
}
const enum MarshalOptionsEnum {
adMarshalAll = 0,
adMarshalModifiedOnly = 1
}
const enum MoveRecordOptionsEnum {
adMoveAllowEmulation = 4,
adMoveDontUpdateLinks = 2,
adMoveOverWrite = 1,
adMoveUnspecified = -1
}
const enum ObjectStateEnum {
adStateClosed = 0,
adStateConnecting = 2,
adStateExecuting = 4,
adStateFetching = 8,
adStateOpen = 1
}
const enum ParameterAttributesEnum {
adParamLong = 128,
adParamNullable = 64,
adParamSigned = 16
}
const enum ParameterDirectionEnum {
adParamInput = 1,
adParamInputOutput = 3,
adParamOutput = 2,
adParamReturnValue = 4,
adParamUnknown = 0
}
const enum PersistFormatEnum {
adPersistADTG = 0,
adPersistXML = 1
}
const enum PositionEnum {
adPosBOF = -2,
adPosEOF = -3,
adPosUnknown = -1
}
const enum PositionEnum_Param {
adPosBOF = -2,
adPosEOF = -3,
adPosUnknown = -1
}
const enum PropertyAttributesEnum {
adPropNotSupported = 0,
adPropOptional = 2,
adPropRead = 512,
adPropRequired = 1,
adPropWrite = 1024
}
const enum RecordCreateOptionsEnum {
adCreateCollection = 8192,
adCreateNonCollection = 0,
adCreateOverwrite = 67108864,
adCreateStructDoc = -2147483648,
adFailIfNotExists = -1,
adOpenIfExists = 33554432
}
const enum RecordOpenOptionsEnum {
adDelayFetchFields = 32768,
adDelayFetchStream = 16384,
adOpenAsync = 4096,
adOpenExecuteCommand = 65536,
adOpenOutput = 8388608,
adOpenRecordUnspecified = -1,
adOpenSource = 8388608
}
const enum RecordStatusEnum {
adRecCanceled = 256,
adRecCantRelease = 1024,
adRecConcurrencyViolation = 2048,
adRecDBDeleted = 262144,
adRecDeleted = 4,
adRecIntegrityViolation = 4096,
adRecInvalid = 16,
adRecMaxChangesExceeded = 8192,
adRecModified = 2,
adRecMultipleChanges = 64,
adRecNew = 1,
adRecObjectOpen = 16384,
adRecOK = 0,
adRecOutOfMemory = 32768,
adRecPendingChanges = 128,
adRecPermissionDenied = 65536,
adRecSchemaViolation = 131072,
adRecUnmodified = 8
}
const enum RecordTypeEnum {
adCollectionRecord = 1,
adSimpleRecord = 0,
adStructDoc = 2
}
const enum ResyncEnum {
adResyncAllValues = 2,
adResyncUnderlyingValues = 1
}
const enum SaveOptionsEnum {
adSaveCreateNotExist = 1,
adSaveCreateOverWrite = 2
}
const enum SchemaEnum {
adSchemaActions = 41,
adSchemaAsserts = 0,
adSchemaCatalogs = 1,
adSchemaCharacterSets = 2,
adSchemaCheckConstraints = 5,
adSchemaCollations = 3,
adSchemaColumnPrivileges = 13,
adSchemaColumns = 4,
adSchemaColumnsDomainUsage = 11,
adSchemaCommands = 42,
adSchemaConstraintColumnUsage = 6,
adSchemaConstraintTableUsage = 7,
adSchemaCubes = 32,
adSchemaDBInfoKeywords = 30,
adSchemaDBInfoLiterals = 31,
adSchemaDimensions = 33,
adSchemaForeignKeys = 27,
adSchemaFunctions = 40,
adSchemaHierarchies = 34,
adSchemaIndexes = 12,
adSchemaKeyColumnUsage = 8,
adSchemaLevels = 35,
adSchemaMeasures = 36,
adSchemaMembers = 38,
adSchemaPrimaryKeys = 28,
adSchemaProcedureColumns = 29,
adSchemaProcedureParameters = 26,
adSchemaProcedures = 16,
adSchemaProperties = 37,
adSchemaProviderSpecific = -1,
adSchemaProviderTypes = 22,
adSchemaReferentialConstraints = 9,
adSchemaReferentialContraints = 9,
adSchemaSchemata = 17,
adSchemaSets = 43,
adSchemaSQLLanguages = 18,
adSchemaStatistics = 19,
adSchemaTableConstraints = 10,
adSchemaTablePrivileges = 14,
adSchemaTables = 20,
adSchemaTranslations = 21,
adSchemaTrustees = 39,
adSchemaUsagePrivileges = 15,
adSchemaViewColumnUsage = 24,
adSchemaViews = 23,
adSchemaViewTableUsage = 25
}
const enum SearchDirection {
adSearchBackward = -1,
adSearchForward = 1
}
const enum SearchDirectionEnum {
adSearchBackward = -1,
adSearchForward = 1
}
const enum SeekEnum {
adSeekAfter = 8,
adSeekAfterEQ = 4,
adSeekBefore = 32,
adSeekBeforeEQ = 16,
adSeekFirstEQ = 1,
adSeekLastEQ = 2
}
const enum StreamOpenOptionsEnum {
adOpenStreamAsync = 1,
adOpenStreamFromRecord = 4,
adOpenStreamUnspecified = -1
}
const enum StreamReadEnum {
adReadAll = -1,
adReadLine = -2
}
const enum StreamTypeEnum {
adTypeBinary = 1,
adTypeText = 2
}
const enum StreamWriteEnum {
adWriteChar = 0,
adWriteLine = 1,
stWriteChar = 0,
stWriteLine = 1
}
const enum StringFormatEnum {
adClipString = 2
}
const enum XactAttributeEnum {
adXactAbortRetaining = 262144,
adXactAsyncPhaseOne = 524288,
adXactCommitRetaining = 131072,
adXactSyncPhaseOne = 1048576
}
//Interfaces
interface Command {
ActiveConnection: Connection;
Cancel: () => void;
CommandStream: any /*VT_UNKNOWN*/;
CommandText: string;
CommandTimeout: number;
CommandType: CommandTypeEnum;
CreateParameter: (Name?: string, Type?: DataTypeEnum, Direction?: ParameterDirectionEnum, Size?: number, Value?: any) => Parameter;
Dialect: string;
Execute: (RecordsAffected?: any, Parameters?: any, Options?: number) => Recordset;
Name: string;
NamedParameters: boolean;
Parameters: Parameters;
Prepared: boolean;
Properties: Properties;
State: number;
}
interface Connection {
Attributes: number;
BeginTrans: () => number;
Cancel: () => void;
Close: () => void;
CommandTimeout: number;
CommitTrans: () => void;
ConnectionString: string;
ConnectionTimeout: number;
CursorLocation: CursorLocationEnum;
DefaultDatabase: string;
Errors: Errors;
Execute: (CommandText: string, RecordsAffected: any, Options?: number) => Recordset;
IsolationLevel: IsolationLevelEnum;
Mode: ConnectModeEnum;
Open: (ConnectionString?: string, UserID?: string, Password?: string, Options?: number) => void;
OpenSchema: (Schema: SchemaEnum, Restrictions?: any, SchemaID?: any) => Recordset;
Properties: Properties;
Provider: string;
RollbackTrans: () => void;
State: number;
Version: string;
}
interface Error {
Description: string;
HelpContext: number;
HelpFile: string;
NativeError: number;
Number: number;
Source: string;
SQLState: string;
}
interface Errors {
Clear: () => void;
Count: number;
Item: (Index: any) => Error;
Refresh: () => void;
}
interface Field {
ActualSize: number;
AppendChunk: (Data: any) => void;
Attributes: number;
DataFormat: any /*VT_UNKNOWN*/;
DefinedSize: number;
GetChunk: (Length: number) => any;
Name: string;
NumericScale: number;
OriginalValue: any;
Precision: number;
Properties: Properties;
Status: number;
Type: DataTypeEnum;
UnderlyingValue: any;
Value: any;
}
interface Fields {
_Append: (Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum) => void;
Append: (Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum, FieldValue?: any) => void;
CancelUpdate: () => void;
Count: number;
Delete: (Index: any) => void;
Item: (Index: any) => Field;
Refresh: () => void;
Resync: (ResyncValues?: ResyncEnum) => void;
Update: () => void;
}
interface Parameter {
AppendChunk: (Val: any) => void;
Attributes: number;
Direction: ParameterDirectionEnum;
Name: string;
NumericScale: number;
Precision: number;
Properties: Properties;
Size: number;
Type: DataTypeEnum;
Value: any;
}
interface Parameters {
Append: (Object: any /*VT_DISPATCH*/) => void;
Count: number;
Delete: (Index: any) => void;
Item: (Index: any) => Parameter;
Refresh: () => void;
}
interface Properties {
Count: number;
Item: (Index: any) => Property;
Refresh: () => void;
}
interface Property {
Attributes: number;
Name: string;
Type: DataTypeEnum;
Value: any;
}
interface Record {
ActiveConnection: any;
Cancel: () => void;
Close: () => void;
CopyRecord: (Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: CopyRecordOptionsEnum, Async?: boolean) => string;
DeleteRecord: (Source?: string, Async?: boolean) => void;
Fields: Fields;
GetChildren: () => Recordset;
Mode: ConnectModeEnum;
MoveRecord: (Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: MoveRecordOptionsEnum, Async?: boolean) => string;
Open: (Source: any, ActiveConnection: any, Mode?: ConnectModeEnum, CreateOptions?: RecordCreateOptionsEnum, Options?: RecordOpenOptionsEnum, UserName?: string, Password?: string) => void;
ParentURL: string;
Properties: Properties;
RecordType: RecordTypeEnum;
Source: any;
State: ObjectStateEnum;
}
interface Recordset {
_xClone: () => Recordset;
_xResync: (AffectRecords?: AffectEnum) => void;
_xSave: (FileName?: string, PersistFormat?: PersistFormatEnum) => void;
AbsolutePage: PositionEnum;
AbsolutePosition: PositionEnum;
ActiveCommand: any /*VT_DISPATCH*/;
ActiveConnection: any /*VT_DISPATCH*/;
AddNew: (FieldList?: any, Values?: any) => void;
BOF: boolean;
Bookmark: any;
CacheSize: number;
Cancel: () => void;
CancelBatch: (AffectRecords?: AffectEnum) => void;
CancelUpdate: () => void;
Clone: (LockType?: LockTypeEnum) => Recordset;
Close: () => void;
Collect: (Index: any) => any; //Also has setter with parameters
CompareBookmarks: (Bookmark1: any, Bookmark2: any) => CompareEnum;
CursorLocation: CursorLocationEnum;
CursorType: CursorTypeEnum;
DataMember: string;
DataSource: any /*VT_UNKNOWN*/;
Delete: (AffectRecords?: AffectEnum) => void;
EditMode: EditModeEnum;
EOF: boolean;
Fields: Fields;
Filter: any;
Find: (Criteria: string, SkipRecords?: number, SearchDirection?: SearchDirectionEnum, Start?: any) => void;
GetRows: (Rows?: number, Start?: any, Fields?: any) => any;
GetString: (StringFormat?: StringFormatEnum, NumRows?: number, ColumnDelimeter?: string, RowDelimeter?: string, NullExpr?: string) => string;
Index: string;
LockType: LockTypeEnum;
MarshalOptions: MarshalOptionsEnum;
MaxRecords: number;
Move: (NumRecords: number, Start?: any) => void;
MoveFirst: () => void;
MoveLast: () => void;
MoveNext: () => void;
MovePrevious: () => void;
NextRecordset: (RecordsAffected?: any) => Recordset;
Open: (Source: any, ActiveConnection: any, CursorType?: CursorTypeEnum, LockType?: LockTypeEnum, Options?: number) => void;
PageCount: number;
PageSize: number;
Properties: Properties;
RecordCount: number;
Requery: (Options?: number) => void;
Resync: (AffectRecords?: AffectEnum, ResyncValues?: ResyncEnum) => void;
Save: (Destination: any, PersistFormat?: PersistFormatEnum) => void;
Seek: (KeyValues: any, SeekOption?: SeekEnum) => void;
Sort: string;
Source: any /*VT_DISPATCH*/;
State: number;
Status: number;
StayInSync: boolean;
Supports: (CursorOptions: CursorOptionEnum) => boolean;
Update: (Fields?: any, Values?: any) => void;
UpdateBatch: (AffectRecords?: AffectEnum) => void;
}
interface Stream {
Cancel: () => void;
Charset: string;
Close: () => void;
CopyTo: (DestStream: Stream, CharNumber?: number) => void;
EOS: boolean;
Flush: () => void;
LineSeparator: LineSeparatorEnum;
LoadFromFile: (FileName: string) => void;
Mode: ConnectModeEnum;
Open: (Source: any, Mode?: ConnectModeEnum, Options?: StreamOpenOptionsEnum, UserName?: string, Password?: string) => void;
Position: number;
Read: (NumBytes?: number) => any;
ReadText: (NumChars?: number) => string;
SaveToFile: (FileName: string, Options?: SaveOptionsEnum) => void;
SetEOS: () => void;
Size: number;
SkipLine: () => void;
State: ObjectStateEnum;
Type: StreamTypeEnum;
Write: (Buffer: any) => void;
WriteText: (Data: string, Options?: StreamWriteEnum) => void;
}
}
interface ActiveXObject {
new (progID: 'ADODB.Connection'): ADODB.Connection;
new (progID: 'ADODB.Record'): ADODB.Record;
new (progID: 'ADODB.Stream'): ADODB.Stream;
new (progID: 'ADODB.Command'): ADODB.Command;
new (progID: 'ADODB.Recordset'): ADODB.Recordset;
new (progID: 'ADODB.Parameter'): ADODB.Parameter;
}
-24
View File
@@ -1,24 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-data-objects-tests.ts"
]
}
@@ -0,0 +1,44 @@
const collectionToArray = <T>(col: any) => { // tslint:disable-line no-unnecessary-generics
const results: T[] = [];
const enumerator = new Enumerator<T>(col);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
results.push(enumerator.item());
enumerator.moveNext();
}
return results;
};
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787925(v=vs.85).aspx
(() => {
const enumUsers = (label: string) => {
const volume = new ActiveXObject('Microsoft.DiskQuota');
volume.Initialize(label, true);
collectionToArray<DiskQuotaTypeLibrary.DIDiskQuotaUser>(volume).forEach(x => {
// Use the QuotaUser object to retrieve or set one or more of the user's disk quota properties
});
};
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787916(v=vs.85).aspx
(() => {
const volume = new ActiveXObject('Microsoft.DiskQuota');
volume.Initialize('MYDISK', true);
ActiveXObject.on(volume, 'OnUserNameChanged', ['pUser'], p => {
// Code to handle the event.
});
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787904(v=vs.85).aspx
(() => {
const dqc = new ActiveXObject('Microsoft.DiskQuota');
dqc.Initialize('MYDISK', true);
const findName = (name: string) => {
try {
return dqc.FindUser(name);
} catch { }
try {
return dqc.FindUser(dqc.TranslateLogonNameToSID(name));
} catch { }
};
})();
+149
View File
@@ -0,0 +1,149 @@
// Type definitions for DiskQuotaTypeLibrary 1.0
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/bb773938(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
/// <reference types="activex-interop" />
declare namespace DiskQuotaTypeLibrary {
// tslint:disable-next-line no-const-enum
const enum AccountStatusConstants {
dqAcctDeleted = 2,
dqAcctInvalid = 3,
dqAcctResolved = 0,
dqAcctUnavailable = 1,
dqAcctUnknown = 4,
dqAcctUnresolved = 5,
}
// tslint:disable-next-line no-const-enum
const enum QuotaStateConstants {
dqStateDisable = 0,
dqStateEnforce = 2,
dqStateTrack = 1,
}
// tslint:disable-next-line no-const-enum
const enum UserNameResolutionConstants {
dqResolveAsync = 2,
dqResolveNone = 0,
dqResolveSync = 1,
}
/** Automation interface for DiskQuotaUser */
class DIDiskQuotaUser {
private 'DiskQuotaTypeLibrary.DIDiskQuotaUser_typekey': DIDiskQuotaUser;
private constructor();
/** Name of user's account container */
readonly AccountContainerName: string;
/** Status of user's account */
readonly AccountStatus: AccountStatusConstants;
/** User's display name */
readonly DisplayName: string;
/** Unique ID number */
readonly ID: number;
/** Invalidate data cached in user object */
Invalidate(): void;
/** User's logon account name */
readonly LogonName: string;
/** User's quota limit (bytes) */
QuotaLimit: number;
/** User's quota limit (text) */
readonly QuotaLimitText: string;
/** User's quota warning threshold (bytes) */
QuotaThreshold: number;
/** User's quota warning threshold (text) */
readonly QuotaThresholdText: string;
/** Quota charged to user (bytes) */
readonly QuotaUsed: number;
/** Quota charged to user (text) */
readonly QuotaUsedText: string;
}
/** Microsoft Disk Quota */
class DiskQuotaControl {
private 'DiskQuotaTypeLibrary.DiskQuotaControl_typekey': DiskQuotaControl;
private constructor();
/** Add a user quota entry by Name */
AddUser(LogonName: string): DIDiskQuotaUser;
/** Default quota limit applied to new volume users (byte value) */
DefaultQuotaLimit: number;
/** Default quota limit applied to new volume users (text string) */
readonly DefaultQuotaLimitText: string;
/** Default warning threshold applied to new volume users (byte value) */
DefaultQuotaThreshold: number;
/** Default warning threshold applied to new volume users (text string) */
readonly DefaultQuotaThresholdText: string;
/** Delete a user quota entry */
DeleteUser(pUser: DIDiskQuotaUser): void;
/** Find a user quota entry by Name */
FindUser(LogonName: string): DIDiskQuotaUser;
/** Promote a user quota entry to the head of the name resolution queue */
GiveUserNameResolutionPriority(pUser: DIDiskQuotaUser): void;
/** Initialize the quota control object for a specified volume */
Initialize(path: string, bReadWrite: boolean): void;
/** Invalidate the cache of user name information */
InvalidateSidNameCache(): void;
/** Write event log entry when user exceeds quota limit */
LogQuotaLimit: boolean;
/** Write event log entry when user exceeds quota warning threshold */
LogQuotaThreshold: boolean;
/** Indicates if quota information is out of date */
readonly QuotaFileIncomplete: boolean;
/** Indicates if quota information is being rebuilt */
readonly QuotaFileRebuilding: boolean;
/** State of the volume's disk quota system */
QuotaState: QuotaStateConstants;
/** Terminate the user name resolution thread */
ShutdownNameResolution(): void;
/** Translates a user logon name to a security ID */
TranslateLogonNameToSID(LogonName: string): string;
/** Control the resolution of user Security IDs to user Names */
UserNameResolution: UserNameResolutionConstants;
}
}
interface ActiveXObject {
on(
obj: DiskQuotaTypeLibrary.DiskQuotaControl, event: 'OnUserNameChanged', argNames: ['pUser'], handler: (
this: DiskQuotaTypeLibrary.DiskQuotaControl, parameter: {readonly pUser: DiskQuotaTypeLibrary.DIDiskQuotaUser}) => void): void;
}
interface ActiveXObjectNameMap {
'Microsoft.DiskQuota': DiskQuotaTypeLibrary.DiskQuotaControl;
}
interface EnumeratorConstructor {
new(col: DiskQuotaTypeLibrary.DiskQuotaControl): Enumerator<DiskQuotaTypeLibrary.DIDiskQuotaUser>;
}
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-diskquota-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+327
View File
@@ -0,0 +1,327 @@
/// <reference types="windows-script-host" />
/// <reference types="activex-msforms" />
/// <reference types="activex-scripting" />
// some helpers
const toSafeArray = <T>(...items: T[]): SafeArray<T> => {
const dict: Scripting.Dictionary<number, T> = new ActiveXObject('Scripting.Dictionary');
items.forEach((x, index) => dict.Add(index, x));
return dict.Items();
};
const inCollection = <T = any>(collection: { Item(index: any): T }, index: string | number): T | undefined => {
let item: T | undefined;
try {
item = collection.Item(index);
} catch (error) { }
return item;
};
const app = new ActiveXObject('Excel.Application');
// create a workbook -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/create-a-workbook
const newBook = app.Workbooks.Add();
newBook.Title = 'All Sales';
newBook.Subject = 'Sales';
newBook.SaveAs('allsales.xls');
// create or replace a worksheet -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/create-or-replace-a-worksheet
const newOrExistingWorksheet = () => {
const mySheetName = 'Sheet4';
let mySheet = inCollection(newBook.Worksheets, mySheetName) as Excel.Worksheet | undefined;
if (!mySheet) {
WScript.Echo(`The sheet named "${mySheetName} doesn't exist, but will be created.`);
mySheet = app.Worksheets.Add() as Excel.Worksheet;
mySheet.Name = mySheetName;
}
};
const replaceWorksheet = () => {
const mySheetName = 'Sheet4';
app.DisplayAlerts = false;
let mySheet = inCollection<Excel.Worksheet | Excel.Chart | Excel.DialogSheet>(app.Worksheets, mySheetName);
if (mySheet) { mySheet.Delete(); }
app.DisplayAlerts = true;
mySheet = app.Worksheets.Add() as Excel.Worksheet;
mySheet.Name = mySheetName;
WScript.Echo(`The sheet named "${mySheetName} has been replaced.`);
};
// referencing multiple sheets -- https://msdn.microsoft.com/VBA/Excel-VBA/articles/sheets-object-excel
const moveMultipleSheets = () => {
app.Worksheets.Item(toSafeArray<string | number>(1, 'Sheet2')).Move(4);
};
// sort worksheets alphanumerically by name -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/sort-worksheets-alphanumerically-by-name
const sortSheetsTabName = () => {
app.ScreenUpdating = false;
const sheets = app.ActiveWorkbook.Sheets;
const sheetCount = sheets.Count;
for (let i = 0; i < sheetCount; i += 1) {
const sheetI = sheets.Item(i);
for (let j = i; j < sheetCount; j += 1) {
const sheetJ = sheets.Item(j);
if (sheetJ.Name < sheetI.Name) { sheetJ.Move(sheetI); }
}
}
app.ScreenUpdating = true;
};
// fill a value down into blank cells in a column -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/fill-a-value-down-into-blank-cells-in-a-column
const fillCellsFromAbove = () => {
app.ScreenUpdating = false;
const columnA = app.Columns.Item(1);
try {
columnA.SpecialCells(Excel.XlCellType.xlCellTypeBlanks).Formula = '=R[-1]C';
columnA.Value = columnA.Value;
} catch (error) { }
app.ScreenUpdating = true;
};
// hide and unhide columns -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/hide-and-unhide-columns
const setColumnVisibility = (visible: boolean) => {
const book = app.Workbooks.Item(1);
const sheet = inCollection<Excel.Worksheet | Excel.Chart | Excel.DialogSheet>(book.Worksheets, 'Sheet1');
if (!sheet) { return; }
// search the four columns for any constants
const checkWithin = (sheet as Excel.Worksheet).Range('A1:D1').SpecialCells(Excel.XlCellType.xlCellTypeConstants);
let find = checkWithin.Find('X');
if (!find) { return; }
const address = find.Address();
// hide the column, and then find the next X
do {
find.EntireColumn.Hidden = visible;
find = checkWithin.FindNext(find);
} while (find && find.Address() !== address);
};
// highlighting the active cell, row, or column -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/highlight-the-active-cell-row-or-column
(() => {
const wks = app.ActiveSheet as Excel.Worksheet;
// highlight active cell
ActiveXObject.on(wks, 'SelectionChange', ['Target'], function(this: Excel.Worksheet, prm) {
app.ScreenUpdating = false;
// clear the color of all the cells
this.Cells.Interior.ColorIndex = 0;
// highlight the actie cell
prm.Target.Interior.ColorIndex = 8;
app.ScreenUpdating = true;
});
// highlight entire row and column that contain active cell
ActiveXObject.on(wks, 'SelectionChange', ['Target'], function(this: Excel.Worksheet, prm) {
if (prm.Target.Cells.Count > 1) { return; }
app.ScreenUpdating = false;
// clear the color of all the cells in the row and column of the active cell
this.Cells.Interior.ColorIndex = 0;
prm.Target.EntireRow.Interior.ColorIndex = 8;
prm.Target.EntireColumn.Interior.ColorIndex = 8;
app.ScreenUpdating = true;
});
})();
// referencing cells -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/reference-cells-and-ranges
(() => {
const wks = app.ActiveSheet as Excel.Worksheet;
// all the cells on a worksheet
wks.Cells.ClearContents();
// using A1 notation
wks.Range('A1').Font.Bold = true;
wks.Range('A1:D5').Font.Bold = true;
wks.Range('C5:D9,G9:H16').Font.Bold = true;
wks.Range('A:A').Font.Bold = true;
wks.Range('1:1').Font.Bold = true;
wks.Range('A:C').Font.Bold = true;
wks.Range('1:5').Font.Bold = true;
wks.Range('1:1,3:3,8:8').Font.Bold = true;
wks.Range('A:A,C:C,F:F').Font.Bold = true;
// using index numbers
wks.Cells.Item(6, 1).Value2 = 10;
// Value is also a property with parameters
ActiveXObject.set(wks.Cells.Item(6, 1), 'Value', 10);
// iterating through cells using index numbers
for (let counter = 1; counter < 20; counter += 1) {
ActiveXObject.set(wks.Cells.Item(counter, 1), 'Value', 10);
}
// relative to other cells
wks.Cells.Item(1, 1).Font.Underline = Excel.XlUnderlineStyle.xlUnderlineStyleDouble;
// using a Range object
const rng = wks.Cells.Item('A1:D5');
rng.Formula = '=RAND()';
rng.Font.Bold = true;
// refer to multiple ranges, using Union
const r1 = wks.Range('A1:A10');
const r2 = wks.Range('B4:B20');
const union = app.Union(r1, r2);
union.Font.Bold = true;
// refer to multiple ranges using Areas
WScript.Echo(union.Areas.Count);
})();
// looping through a range of cells -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/looping-through-a-range-of-cells
(() => {
const wks = app.ActiveSheet as Excel.Worksheet;
// using for
for (let x = 1; x < 20; x++) {
const currentCell = wks.Cells.Item(x, 1);
if (Math.abs(currentCell.Value()) < 0.01) {
// because Value is typed as a method on the Excel.Range class, we have to treat it as a setter with parameters
ActiveXObject.set(currentCell, 'Value', 0);
}
}
// using Enumerator
let enumerator = new Enumerator(wks.Cells.Item('A1:D10'));
enumerator.moveFirst();
while (!enumerator.atEnd()) {
const currentCell = enumerator.item();
if (Math.abs(currentCell.Value) < 0.01) {
currentCell.Value = 0;
}
enumerator.moveNext();
}
// using CurrentRegion
enumerator = new Enumerator(app.ActiveCell.CurrentRegion);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
const cell = enumerator.item();
if (Math.abs(cell.Value) < 0.01) {
cell.Value = 0;
}
enumerator.moveNext();
}
})();
// using selection -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/selecting-and-activating-cells
(() => {
const wks = app.ActiveWorkbook.Worksheets.Item(1) as Excel.Worksheet;
// make a worksheet the active worksheet; otherwise code which uses the selection will fail
wks.Select();
// select a cell
wks.Range("A1").Select();
app.ActiveCell.Font.Bold = true;
// activate a cell; only a single cell can be active at any given time
wks.Range("B1").Activate();
// working with 3-D ranges -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/working-with-3-d-ranges
app.Sheets.Item(toSafeArray("Sheet2", "Sheet3", "Sheet4")).Select();
app.Range("A1:H1").Select();
(app.Selection as Excel.Range).Borders.Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlDouble;
// alternatively, use FillAcrossSheets to fill formatting and data across sheets
const book = app.ActiveWorkbook;
const wks2 = book.Sheets.Item("Sheet2") as Excel.Worksheet;
const rng = wks2.Range("A1:H1");
rng.Borders.Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlDouble;
book.Sheets.FillAcrossSheets(rng);
})();
// prevent duplicate entry -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/prevent-duplicate-entries-in-a-range
(() => {
const book = app.Workbooks.Item(1);
ActiveXObject.on(book, 'SheetChange', ['Sh', 'Target'], function(this, prm) {
const EvalRange = this.ActiveSheet.Range("A1:B20");
// If the cell where the value was entered is not in the defined range, if the value pasted is larger than a single cell, or if no value was entered in the cell, then exit the macro
if (
(app.Intersect(prm.Target, EvalRange) == null) ||
(prm.Target.Cells.Count > 1)
// VBA has a function called IsEmpty; not sure what the equivalent is in Javascript
) { return; }
// If the value entered already exists in the defined range on the current worksheet, undo and exit
if (app.WorksheetFunction.CountIf(EvalRange, prm.Target.Value()) > 1) {
app.EnableEvents = false;
app.Undo();
app.EnableEvents = true;
return;
}
const enumerator = new Enumerator(book.Worksheets);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
const wks = enumerator.item() as Excel.Worksheet;
if (wks.Name === prm.Target.Name) { continue; }
// If the value entered already exists in the defined range on the current worksheet, undo the entry.
if (app.WorksheetFunction.CountIf(wks.Range('A1:B20'), prm.Target.Value()) === 0) { continue; }
app.EnableEvents = false;
app.Undo();
app.EnableEvents = true;
}
});
})();
// add a unique list of values to a combobox -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/add-a-unique-list-of-values-to-a-combo-box
(() => {
(() => {
// using the AdvancedFilter property
const book = app.ThisWorkbook;
const sheet = book.Worksheets.Item("Sheet1") as Excel.Worksheet;
const dataRange = sheet.Range('A1', sheet.Range("A100").End(Excel.XlDirection.xlUp));
dataRange.AdvancedFilter(Excel.XlFilterAction.xlFilterCopy, undefined, sheet.Range('L1'), true);
const data = sheet.Range("L2", sheet.Range('L100').End(Excel.XlDirection.xlUp)).Value() as SafeArray;
sheet.Range('L1', sheet.Range('L100').End(Excel.XlDirection.xlUp)).ClearContents();
const combobox = sheet.OLEObjects('ComboBox1').Object as MSForms.ComboBox;
combobox.Clear();
ActiveXObject.set(combobox, 'List', [], data);
combobox.ListIndex = -1;
})();
(() => {
// using a Dictionary
const sheet = app.ThisWorkbook.Sheets.Item('Sheet2') as Excel.Worksheet;
const data = sheet.Range('A2', sheet.Range('A100').End(Excel.XlDirection.xlUp)).Value2 as SafeArray;
const arr = new VBArray(data).toArray();
const dict = new ActiveXObject('Scripting.Dictionary');
arr.forEach(x => ActiveXObject.set(dict, 'Item', [x], true));
const combobox = sheet.OLEObjects('ComboBox1').Object as MSForms.ComboBox;
combobox.Clear();
// iterate over keys using Enumerator
const enumerator = new Enumerator(dict);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
combobox.AddItem(enumerator.item());
enumerator.moveNext();
}
// alternatively, make a JS array out of the keys, and iterate using forEach
// new VBArray(dict.Keys()).toArray().forEach(x => combobox.AddItem(x));
})();
})();
// animating a sparkline -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/animate-a-sparkline
(() => {
const wks = app.ActiveSheet as Excel.Worksheet;
const oSparkGroup = wks.Cells.SparklineGroups.Item(1);
// Set the data source to the first year of data
oSparkGroup.ModifySourceData('B2:M4');
// Loop through the data points for the subsequent two years
for (let i = 1; i <= 24; i++) {
// Move the reference for the sparkline group over one cell
oSparkGroup.ModifySourceData(wks.Range(oSparkGroup.SourceData).Offset(0, 1).Address());
WScript.Sleep(1000);
}
})();
+9786
View File
File diff suppressed because it is too large Load Diff

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