mirror of
https://github.com/gosticks/DefinitelyTyped.git
synced 2026-10-05 07:17:04 +00:00
+1
-1
@@ -5,5 +5,5 @@ indent_size = 4
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
|
||||
[{*.json,*.yml}]
|
||||
[{*.json,*.yml,*.ts,*.tsx,*.md}]
|
||||
indent_style = space
|
||||
|
||||
+5722
-4251
File diff suppressed because it is too large
Load Diff
@@ -46,6 +46,10 @@ npm-debug.log
|
||||
.settings/launch.json
|
||||
.vs
|
||||
.vscode
|
||||
.history
|
||||
|
||||
# yarn
|
||||
yarn.lock
|
||||
|
||||
# pnpm
|
||||
shrinkwrap.yaml
|
||||
|
||||
+20
-19
@@ -22,15 +22,15 @@ Este es el método preferido. Solo está disponible para usuarios TypeScript 2.0
|
||||
npm install --save-dev @types/node
|
||||
```
|
||||
|
||||
Los types deberían ser incluidos automaticamente por el compilador.
|
||||
Los types deberían ser incluidos automáticamente por el compilador.
|
||||
Vea más en el [manual](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html).
|
||||
|
||||
Para un paquete NPM "foo", Estos `typings` estarán en "@types/foo".
|
||||
Para un paquete NPM "foo", estos `typings` estarán en "@types/foo".
|
||||
Si no puedes encontrar tu paquete, búscalo en [TypeSearch](https://microsoft.github.io/TypeSearch/).
|
||||
|
||||
Si aún no puedes encontrarlo, comprueba si el paquete ya [incluye](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) los typings.
|
||||
Esto es provisto usualmente en el campo `"types"` o `"typings"` en el `package.json`,
|
||||
o solo busca por cualquier archivo ".d.ts" en el paquete e incluyelo manualmente con un `/// <reference path="" />`.
|
||||
o solo busca por cualquier archivo ".d.ts" en el paquete e inclúyelo manualmente con un `/// <reference path="" />`.
|
||||
|
||||
|
||||
### Otros métodos
|
||||
@@ -39,7 +39,7 @@ Estos pueden ser utilizados por TypeScript 1.0.
|
||||
|
||||
* [Typings](https://github.com/typings/typings)
|
||||
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (use las alternativas preferidas, la publicación DT type de nuget ha sido desactivada)
|
||||
* Descarguelo manualmente desde la `master` branch de este repositorio
|
||||
* Descárguelo manualmente desde la `master` branch de este repositorio
|
||||
|
||||
Tal vez debas añadir manualmente las [referencias](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).
|
||||
|
||||
@@ -87,7 +87,8 @@ Primero, haz un [fork](https://guides.github.com/activities/forking/) en este re
|
||||
|
||||
* `cd types/my-package-to-edit`
|
||||
* Haz cambios. Recuerda editar las pruebas.
|
||||
* También puede que quieras añadirte la sección "Definitions by" en el encabezado del paquete.
|
||||
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ñadirle la sección "Definitions by" en el encabezado del paquete.
|
||||
- Esto hará que seas notificado (a través de tu nombre de usuario en GitHub) cada vez que alguien haga un pull request o issue sobre el paquete.
|
||||
- Haz esto añadiendo tu nombre al final de la línea, así como en `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
|
||||
- O si hay más personas, puede ser multiline
|
||||
@@ -108,7 +109,7 @@ Si no lo hace, puedes hacerlo en el comentario asociado con el PR.
|
||||
Si eres el autor de la librería, o puedes hacer un pull request a la biblioteca, [bundle types](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) en vez de publicarlo en DefinitelyTyped.
|
||||
|
||||
Si estás agregando typings para un paquete NPM, crea un directorio con el mismo nombre.
|
||||
Si el paquete al que le estás agregando typings no es para NPM, asegurate de que el nombre que escojas no genere problemas con el nombre del paquete en NPM.
|
||||
Si el paquete al que le estás agregando typings no es para NPM, asegúrate de que el nombre que escojas no genere problemas con el nombre del paquete en NPM.
|
||||
(Puedes usar `npm info foo` para verificar la existencia del paquete `foo`.)
|
||||
|
||||
Tu paquete debería tener esta estructura:
|
||||
@@ -125,7 +126,7 @@ Ve todas las opciones en [dts-gen](https://github.com/Microsoft/dts-gen).
|
||||
|
||||
También puedes configurar el `tsconfig.json` para añadir nuevos archivos, para agregar un `"target": "es6"` (necesitado por las funciones asíncronas), para agregar a la `"lib"`, o para agregar la opción de compilación `"jsx"`.
|
||||
|
||||
Los miembros de DefinitelyTyped frecuentemente monitorean nuevos PRs, pero ten en mente que la cantidad de PRs podrian ralentizar el proceso.
|
||||
Los miembros de DefinitelyTyped frecuentemente monitorean nuevos PRs, pero ten en mente que la cantidad de PRs podrían ralentizar el proceso.
|
||||
|
||||
Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js).
|
||||
|
||||
@@ -134,7 +135,7 @@ Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTy
|
||||
|
||||
* Primero, sigue el consejo del [manual](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html).
|
||||
* Formatear: Ya sea utilizar todo en tabs, o siempre utiliza 4 espacios.
|
||||
* `function sum(nums: number[]): number`: Utiliza `ReadonlyArray` si una funcion no escribe a sus parámetros.
|
||||
* `function sum(nums: number[]): number`: Utiliza `ReadonlyArray` si una función no escribe a sus parámetros.
|
||||
* `interface Foo { new(): Foo; }`:
|
||||
Este define el tipo de objeto que esten nuevos. Probablemente quieras `declare class Foo { constructor(); }`.
|
||||
* `const Class: { new(): IClass; }`:
|
||||
@@ -145,7 +146,7 @@ Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTy
|
||||
Un ejemplo donde un tipo de parámetro es aceptable: `function id<T>(value: T): T;`.
|
||||
Un ejemplo donde no es aceptable: `function parseJson<T>(json: string): T;`.
|
||||
Una excepción: `new Map<string, number>()` está bien.
|
||||
* Utilizando los tipos `Function` y `Object` casi nunca es una buena idea. En 99% de los casos es posible especificar un tipo más especifico. Los ejemplos son `(x: number) => number` para [funciones](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) y `{ x: number, y: number }` para objetos. Si no hay certeza en lo absoluto del tipo, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) es la opción correcta, no `Object`. Si el único hecho conocido sobre el tipo es que es un objecto, usa el tipo [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), no `Object` o `{ [key: string]: any }`.
|
||||
* Utilizando los tipos `Function` y `Object` casi nunca es una buena idea. En 99% de los casos es posible especificar un tipo más específico. Los ejemplos son `(x: number) => number` para [funciones](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) y `{ x: number, y: number }` para objetos. Si no hay certeza en lo absoluto del tipo, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) es la opción correcta, no `Object`. Si el único hecho conocido sobre el tipo es que es un objecto, usa el tipo [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), no `Object` o `{ [key: string]: any }`.
|
||||
* `var foo: string | any`:
|
||||
Cuando es usado `any` en un tipo de unión, el tipo resultante todavía es `any`. Así que mientras la porción `string` de este tipo de anotación puede _verse_ útil, de hecho, no ofrece ningún typechecking adicional más que un simple `any`.
|
||||
Dependiendo de la intención, una alternativa aceptable puede ser `any`, `string`, o `string | object`.
|
||||
@@ -203,11 +204,11 @@ Este script utiliza [dtslint](https://github.com/Microsoft/dtslint).
|
||||
|
||||
#### ¿Cuál es exactamente la relación entre este repositorio y los paquetes de `@types` en NPM?
|
||||
|
||||
La `master` branch es automaticamente publicada en el alcance de los `@types` en NPM gracias a los [types-publisher](https://github.com/Microsoft/types-publisher).
|
||||
La `master` branch es automáticamente publicada en el alcance de los `@types` en NPM gracias a los [types-publisher](https://github.com/Microsoft/types-publisher).
|
||||
|
||||
#### He enviado un pull request. ¿Cuánto tardará en ser merged?
|
||||
|
||||
Esto depende, pero la mayoría de los pull requests serán merged en alrededor de una semana. PRs que hayan sido aprovados por un autor listado en el encabezado de las definiciones usualmente son merged más rápidamente; PRs para nuevas definiciones tomarán más tiempo ya que requieren más revisiones de los mantenedores. Cada PR es revisado por un miembro de TypeScript o DefinitelyTyped antes de ser merged, por favor se paciente debido a que factores humanos pueden causar retrasos. Revisa el [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) para ver el progreso mientras los mantenedores trabajan on los PRs abiertos.
|
||||
Esto depende, pero la mayoría de los pull requests serán merged en alrededor de una semana. PRs que hayan sido aprobados por un autor listado en el encabezado de las definiciones usualmente son merged más rápidamente; PRs para nuevas definiciones tomarán más tiempo ya que requieren más revisiones de los mantenedores. Cada PR es revisado por un miembro de TypeScript o DefinitelyTyped antes de ser merged, por favor sé paciente debido a que factores humanos pueden causar retrasos. Revisa el [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) para ver el progreso mientras los mantenedores trabajan en los PRs abiertos.
|
||||
|
||||
#### Mi PR ha sido merged; ¿cuándo será actualizado el paquete de `@types` NPM?
|
||||
|
||||
@@ -215,12 +216,12 @@ Los paquetes NPM deberán ser actualizados en unas cuantas horas. Si ha pasado m
|
||||
|
||||
#### Estoy escribiendo una definición que depende de otra definición. Debería utilizar `<reference types="" />` o una import?
|
||||
|
||||
Si el modulo al cual te estás refiriendo es un módulo externo (utiliza `export`), utilice una import.
|
||||
Si el módulo al cual te estás refiriendo es un módulo externo (utiliza `export`), utilice una import.
|
||||
Si el módulo al cual te refieres es un módulo ambiente (utiliza `declare module`, o simplemente declara las globales), utilice `<reference types="" />`.
|
||||
|
||||
#### He notado que algunos paquetes aquí tienen `package.json`.
|
||||
|
||||
Normalmente no lo necesitaras. Cuando publicas un paquete normalmente nosotros automáticamente crearemos un `package.json` para eso.
|
||||
Normalmente no lo necesitarás. Cuando publicas un paquete normalmente nosotros automáticamente crearemos un `package.json` para eso.
|
||||
Un `package.json` puede ser incluido por el bien de especificar dependencias. Aquí tienen un [ejemplo](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json).
|
||||
No aceptamos otros campos, tales como `"description"`, para que sean definidos manualmente.
|
||||
Además, si necesitas referencia a una versión anterior de typings, debes hacerlo añadiendo `"dependencies": { "@types/foo": "x.y.z" }` al package.json.
|
||||
@@ -259,7 +260,7 @@ Cuando ya no sea un borrador, lo podremos eliminar desde DefinitelyType y hacer
|
||||
Si planeas continuar actualizando la versión anterior del paquete, puedes crear una subcarpeta con la versión actual p.ej. `v2`, y copia los archivos existentes. Si es así, necesitarás:
|
||||
|
||||
1. Actualiza las rutas relativas en `tsconfig.json` al igual que `tslint.json`.
|
||||
2. Añadir reglas de mapeo de rutas para asegurart de que la prueba se está ejecutando contra la versión prevista.
|
||||
2. Añadir reglas de mapeo de rutas para asegurarte de que la prueba se está ejecutando contra la versión prevista.
|
||||
|
||||
Por ejemplo [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) se ve así:
|
||||
|
||||
@@ -279,24 +280,24 @@ Por ejemplo [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/Defi
|
||||
}
|
||||
```
|
||||
|
||||
Si hay otros paquetes en DefinitelyTyped que son incompatibles con la nueva versión, necesitaras mapear las rutas a la versión anterior. También deberá hacer esto para los paquetes que dependen de paquetes que dependen de una version anterior.
|
||||
Si hay otros paquetes en DefinitelyTyped que son incompatibles con la nueva versión, necesitarás mapear las rutas a la versión anterior. También deberá hacer esto para los paquetes que dependen de paquetes que dependen de una version anterior.
|
||||
|
||||
Por ejemplo, `react-router` depende de `history@2`, así que [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) tiene una ruta mapeada a "history": `[ "history/v2" ]`;
|
||||
transitivo así mismo, `react-router-bootstrap` (que depende de `react-router`) también añade una ruta mapeada en su [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json).
|
||||
|
||||
Además, `/// <reference types=".." />` no trabajara con rutas mapeadas, así que las dependencias deberán utilizar `import`.
|
||||
Además, `/// <reference types=".." />` no trabajará con rutas mapeadas, así que las dependencias deberán utilizar `import`.
|
||||
|
||||
#### ¿Cómo escribo definitions para paquetes que pueden ser usados globalmente y como un módulo?
|
||||
|
||||
El manual de TypeScript contiene excelente [información general para escribir definiciones](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), ademas [este archivo de definiciones de ejemplo](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) el cual muestra como crear una definición utilizando la sintaxis de módulo en ES6, asi como también especificando objetos que son disponibles en el alcance global. Esta técnica es demostrada practicamente en la [definición para big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), el cual es una librería que puede ser cargada globalmente a travéz de una etiqueta script en una página web, o importada via require o imports estilo ES6.
|
||||
El manual de TypeScript contiene excelente [información general para escribir definiciones](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), además [este archivo de definiciones de ejemplo](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) el cual muestra como crear una definición utilizando la sintaxis de módulo en ES6, asi como también especificando objetos que son disponibles en el alcance global. Esta técnica es demostrada prácticamente en la [definición para big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), el cual es una librería que puede ser cargada globalmente a través de una etiqueta script en una página web, o importada vía require o imports estilo ES6.
|
||||
|
||||
Para probar como puede ser usada tu definición cuando se refieren globalmente o como un módulo importado, crea una carpeta `test`, y coloca dos archivos de prueba en él. nombra uno `YourLibraryName-global.test.ts` y el otro `YourLibraryName-module.test.ts`. El archivo de prueba _global_ debe ejercer la definición de acuerdo como va a ser usado en un script cargado en una página web donde la librería estará disponible en el alcance global - en este escenario no debes de especificar la sentencia de import. El archivo _módulo_ de prueba debe de ejercer la definición de acuerdo a como va a ser utilizado cuando sea importado (incluyendo las sentencias `import`). Si especificas un propiedad `files` en tu archivo tsconfig.json, asegurate de incluir ambos archivos de prueba. Un [ejemplo práctico de esto](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) es también disponible en la definición de big.js.
|
||||
Para probar como puede ser usada tu definición cuando se refieren globalmente o como un módulo importado, crea una carpeta `test`, y coloca dos archivos de prueba en él. nombra uno `YourLibraryName-global.test.ts` y el otro `YourLibraryName-module.test.ts`. El archivo de prueba _global_ debe ejercer la definición de acuerdo como va a ser usado en un script cargado en una página web donde la librería estará disponible en el alcance global - en este escenario no debes de especificar la sentencia de import. El archivo _módulo_ de prueba debe de ejercer la definición de acuerdo a como va a ser utilizado cuando sea importado (incluyendo las sentencias `import`). Si especificas una propiedad `files` en tu archivo tsconfig.json, asegurate de incluir ambos archivos de prueba. Un [ejemplo práctico de esto](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) es también disponible en la definición de big.js.
|
||||
|
||||
Por favor tenga en cuenta que no es necesario para ejercer plenamente la definición en cada archivo de prueba - Es suficiente con probar solo los elementos globalmente accesibles en la prueba de archivos globales y ejercer la definición en el módulo del archivo de prueba, o viceversa.
|
||||
|
||||
#### ¿Qué pasa con paquetes scoped?
|
||||
|
||||
Types para un paquete scoped `@foo/bar` deberán ir en `types/foo__bar`. tenga en cuenta el doble guion bajo.
|
||||
Types para un paquete scoped `@foo/bar` deberán ir en `types/foo__bar`. tenga en cuenta el doble guión bajo.
|
||||
|
||||
Cuando `dts-gen` es utilizado como scaffold en un paquete scoped, las propiedades `paths` deberán ser adaptadas manualmente en el paquete generado
|
||||
`tsconfig.json` para referenciar correctamente el paquete scoped:
|
||||
|
||||
+338
@@ -0,0 +1,338 @@
|
||||
# DefinitelyTyped [](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
|
||||
|
||||
[](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
> 이 저장소는 고품질의 타입스크립트(TypeScript) 자료형 정의(Type definition)를 위한 저장소입니다.
|
||||
|
||||
이 문서가 가장 최신 내용을 담고있긴 하지만, [공식 사이트(definitelytyped.org)](http://definitelytyped.org)도 확인해보시면 좋습니다.
|
||||
|
||||
## 선언 파일(Declaration file)이 뭔가요?
|
||||
|
||||
[타입스크립트 안내서(TypeScript handbook)](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html)를 읽어보세요.
|
||||
|
||||
## 선언 파일(Declaration file)을 어떻게 받을 수 있나요??
|
||||
|
||||
### npm 사용하기
|
||||
|
||||
아래 방법은 타입스크립트(TypeScript) 2.0+ 이상의 버전을 사용하는 사람들만 사용할 수 있는 방법이기는 합니다만, 이 방법을 사용하기를 장려합니다.
|
||||
|
||||
```sh
|
||||
npm install --save-dev @types/node
|
||||
```
|
||||
|
||||
`node` 를 위한 자료형(Typing)이 컴파일 과정에 자동으로 포함될 겁니다.
|
||||
더 자세한 내용은 [안내서(Handbook)](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html)에서 확인해보실 수 있습니다.
|
||||
|
||||
NPM 의 "foo" 패키지에 대응되는 자료형 패키지는 "@types/foo" 입니다.
|
||||
원하시는 패키지를 찾을 수 없는 경우, [타입서치(TypeSearch)](https://microsoft.github.io/TypeSearch/) 사이트에서 한 번 찾아보세요.
|
||||
|
||||
타입서치(TypeSearch)에서도 찾을 수 없는 경우, 찾고 있는 패키지가 자료형(Typing)을
|
||||
[함께 제공](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html)하고 있지는 않은지 확인해보세요.
|
||||
패키지에 포함된 자료형(Typing)은 주로 `package.json` 파일의 `"types"` 나 `"typings"` 필드(Field)를 통해 제공되지만,
|
||||
`/// <reference path="" />` 같은 주석을 사용하여 패키지 안의 ".d.ts" 파일들을 직접 가져와야 할 수도 있습니다.
|
||||
|
||||
|
||||
### 그 외의 방법들
|
||||
|
||||
타입스크립트(TypeScript) 1.0 버전에서 사용할 수 있는 방법은 다음과 같습니다.
|
||||
|
||||
* [Typings](https://github.com/typings/typings) 을 사용하기
|
||||
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped) 을 사용하기~~ (다른 방법을 사용해주세요. NuGet 은 더 이상 DT 자료형(Typing)을 제공하지 않습니다.)
|
||||
* 이 저장소의 `master` 브랜치를 직접 내려받기
|
||||
|
||||
위 방법을 사용할 경우 수동으로 [참조(Reference)](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html)를 추가해주어야 할 수 있습니다.
|
||||
|
||||
|
||||
## 어떻게 이곳에 기여할 수 있나요?
|
||||
|
||||
여러분과 같은 많은 기여자들의 도움 덕분에 이 저장소가 돌아가고 있습니다. 감사합니다.
|
||||
|
||||
### 테스트
|
||||
|
||||
여러분이 만든 자료형 선언(Type declation)을 세상에 공유하기에 앞서, 여러분이 스스로 여러분의 자료형 선언(Type declation)을 사용하고 확인해주세요.
|
||||
|
||||
#### 이미 존재하는 자료형 패키지를 임시로 수정하기
|
||||
|
||||
이미 존재하는 패키지의 자료형 선언(Type declaration)에 새로운 기능을 추가하려면 [모듈 증강(module augmentation)](http://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation)를 사용할 수 있습니다.
|
||||
물론 `node_modules/@types/foo/index.d.ts` 를 직접 수정하실 수도 있으며, 이 파일을 복사한 다음 아래의 과정을 따라하실 수도 있습니다.
|
||||
|
||||
|
||||
#### 새 자료형 패키지를 임시로 추가하기
|
||||
|
||||
사용하고 계신 `tsconfig.json` 에 다음 내용을 추가해주세요.
|
||||
|
||||
```json
|
||||
"baseUrl": "types",
|
||||
"typeRoots": ["types"],
|
||||
```
|
||||
|
||||
(`types` 대신 `src/types` 을 사용하실 수도 있습니다.)
|
||||
그리고 "foo" 모듈(Module)에 대한 선언(Declaration)을 포함하는 `types/foo/index.d.ts` 파일을 만들어주세요.
|
||||
이제 코드 안에서 여러분의 새 자료형 선언(Type declaration)을 사용하는 `"foo"` 모듈(Module)을 임포트(Import)하실 수 있을 겁니다.
|
||||
코드를 컴파일하고 실행시켜서 여러분의 자료형(Typing)이 실행 중에 실제로 벌어지는 일과 잘 맞아떨어지는지 확인해주세요.
|
||||
실제 코드를 통한 확인이 끝나면, [풀 리퀘스트(Pull request)](#풀-리퀘스트pull-request-만들기)를 만들어주세요.
|
||||
[이미 존재하는 패키지를 수정](#이미-존재하는-패키지를-수정하기)하거나 [새 패키지를 만들기](#새-패키지-만들기)위한 과정들을 따라하시면 됩니다.
|
||||
|
||||
|
||||
### 풀 리퀘스트(Pull request) 만들기
|
||||
|
||||
여러분의 자료형 선언이 잘 작동하는지 확인하셨다면, DefinitelyTyped 에 공유해주세요.
|
||||
|
||||
우선, 이 저장소를 [포크(fork)](https://guides.github.com/activities/forking/)해 주시고, [node](https://nodejs.org/) 를 설치하신 뒤, `npm install` 명령을 실행해주세요.
|
||||
|
||||
|
||||
#### 이미 존재하는 패키지를 수정하기
|
||||
|
||||
* `cd types/my-package-to-edit` 명령을 실행합니다.
|
||||
* 자료형(Typing) 파일들을 수정합니다. 테스트를 추가하는 것도 잊지마세요!
|
||||
만약 브레이킹 체인지(Breaking change)를 만드셨다면, [메이저 버전(major version)](#i-want-to-update-a-package-to-a-new-major-version)을 꼭 올려주세요.
|
||||
* 패키지 머릿주석의 "Definitions by" 부분에 여러분의 이름을 추가하실 수도 있습니다.
|
||||
- 이름을 추가하시면 다른 사람들이 그 패키지에 대한 풀 리퀘스트(Pull request)나 이슈(Issue)를 만들 때 여러분에게 알람이 갑니다.
|
||||
- `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>` 와 같이 여러분의 이름을 줄의 맨 마지막에 추가할 수 있습니다.
|
||||
- 사람이 너무 많을 경우엔, 다음과 같이 여러 줄로 쓰실 수도 있습니다.
|
||||
```typescript
|
||||
// Definitions by: Alice <https://github.com/alice>
|
||||
// Bob <https://github.com/bob>
|
||||
// Steve <https://github.com/steve>
|
||||
// John <https://github.com/john>
|
||||
```
|
||||
* `tslint.json` 파일이 있는 경우에는, `npm run lint package-name` 명령을 실행시키고 결과를 확인해주세요. 그렇지 않은 경우에는, 해당 패키지가 있는 디렉토리 안에서 `tsc` 명령을 실행시키고 결과를 확인해주세요.
|
||||
|
||||
이미 존재하는 패키지에 대한 풀 리퀘스트(Pull request)를 만들었을 경우에는, `dt-bot` 이 이전 저자들을 자동으로 호출하는지 확인해주세요.
|
||||
그렇지 않은 경우에는, 여러분이 직접 풀 리퀘스트(Pull request)와 관계있는 사람들을 호출할 수도 있습니다.
|
||||
|
||||
|
||||
#### 새 패키지를 만들기
|
||||
|
||||
만약 라이브러리를 만드는 중이고 라이브러리가 타입스크립트(TypeScript)로 쓰여있다면, DefinitelyTyped 에 선언(Declaration)을 올리는 대신 패키지에 [자동생성된 선언(Declaration) 파일을 포함](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html)시킬 수 있습니다.
|
||||
|
||||
NPM 패키지를 위한 자료형(Typing) 패키지를 만드시려면, 패키지의 이름과 같은 이름의 디렉토리를 만들어주세요.
|
||||
NPM 에 올라가 있지 않은 패키지를 위한 자료형(Typing) 패키지를 만드시려면, 그 패키지가 NPM 에 올라와 있는 패키지와 이름이 겹치지 않는지 확인해주세요.
|
||||
(`npm info foo` 명령어를 사용하여 `foo` 패키지가 NPM 에 있는지 확인할 수 있습니다.)
|
||||
|
||||
새 자료형 패키지는 다음과 같은 구조로 구성되어있어야만 합니다.
|
||||
|
||||
| 파일 이름 | 용도 |
|
||||
| --- | --- |
|
||||
| index.d.ts | 패키지를 위한 자료형(Typing)을 포함하는 파일입니다. |
|
||||
| foo-tests.ts | 자료형(Typing)의 테스트를 위한 파일입니다. 이 파일의 코드는 실행되지는 않지만, 자료형 검사(Type checking)를 통과해야 합니다. |
|
||||
| tsconfig.json | `tsc` 명령을 돌릴 수 있게 해주는 파일입니다. |
|
||||
| tslint.json | 린터(Linter)를 사용할 수 있게 해주는 파일입니다. |
|
||||
|
||||
이 파일들은, npm ≥ 5.2.0 에서는 `npx dts-gen --dt --name my-package-name --template module` 명령으로,
|
||||
그 이하 경우에는 `npm install -g dts-gen` 와 `dts-gen --dt --name my-package-name --template module` 명령으로 만들 수 있습니다.
|
||||
`dts-gen` 의 모든 옵션(Option)을 보고싶으시면 [dts-gen](https://github.com/Microsoft/dts-gen) 저장소를 확인해주세요.
|
||||
|
||||
자료형(Typing) 패키지에 새 파일을 추가하거나, `async` 키워드를 사용하기 위해 `"target"` 을 `"es6"` 로 설정하거나, `"lib"` 를 추가하거나, `jsx` 지원을 추가하기 위해서 `tsconfig.json` 파일을 변경해야 할 수도 있습니다.
|
||||
|
||||
DefinitelyTyped 의 관리자들이 주기적으로 새로운 풀 리퀘스트(Pull request)들을 확인하기는 하지만,
|
||||
다른 풀 리퀘스트(Pull request)가 많을 경우 확인이 느려질 수 있다는 걸 알아주세요.
|
||||
|
||||
[base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js) 패키지는 좋은 예시 중 하나입니다.
|
||||
|
||||
|
||||
#### 많이 저지르는 실수들
|
||||
|
||||
* 우선, [안내서(Handbook)](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html)에 나와있는 내용들을 따라주세요.
|
||||
* 코드에서는 모든 곳에서 탭(Tab)을 사용하거나, 항상 4 개의 띄어쓰기를 사용해주세요.
|
||||
* `function sum(nums: number[]): number`의 경우, 만약 함수가 인자를 변경하지 않는다면 `ReadonlyArray` 를 사용해주세요.
|
||||
* `interface Foo { new(): Foo; }`의 경우,
|
||||
이런 선언은 이 형(Type)을 가진 객체(Object)에 `new` 를 사용할 수 있도록 만듭니다. 많은 경우 여러분은 `declare class Foo { constructor(); }` 를 사용하려는 것일 겁니다.
|
||||
* `const Class: { new(): IClass; }`의 경우,
|
||||
`new` 를 사용할 수 있는 상수를 만드는 대신, `class Class { constructor(); }` 와 같이 클래스 선언(Class declaration)을 사용하는 게 더 좋습니다.
|
||||
* `getMeAT<T>(): T`의 경우,
|
||||
만일 자료형 매개변수(Type parameter)가 함수의 매개변수에 등장하지 않는다면, 그런 제너릭(Generic) 함수를 사용할 필요가 없습니다.
|
||||
그 제너릭(Generic) 함수는 단순히 자료형 단언(Type assertion)을 위장시킨 것뿐입니다. 이 경우 `getMeAT() as number` 와 같이 진짜 자료형 단언(Type assertion) 을 사용하는 게 더 좋습니다.
|
||||
다음은 괜찮은 제너릭(Generic)의 예시입니다. `function id<T>(value: T): T;`.
|
||||
다음은 문제가 있는 제너릭(Generic)의 예시입니다. `function parseJson<T>(json: string): T;`.
|
||||
예외적으로, `new Map<string, number>()` 와 같은 경우는 괜찮습니다.
|
||||
* `Function` 이나 `Object` 와 같은 형(Type)을 사용하는 것은 대부분의 경우 문제를 일으킵니다. 99% 의 경우 더 구체적인 형(Type)을 사용하는게 가능합니다. [함수(Function)](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) 를 위해서는 `(x: number) => number` 와 같은, 객체를 위해서는 `{ x: number, y: number }` 와 같은 형(Type)들을 사용할 수 있습니다. 형(Type)에 대한 정보가 전혀 없을 경우에는, `Object` 형(Type)이 아니라 [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) 형(Type)을 사용해야 합니다. 만일 어떤 형(Type)이 객체라는 사실만 알고 있는 경우, `Object` 나 `{ [key: string]: any }` 가 아니라 [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type) 를 사용해주세요.
|
||||
* `var foo: string | any`의 경우,
|
||||
`any` 가 합 자료형(Union type)의 안에서 사용될 경우, 결과 형(Type)은 언제나 `any` 가 됩니다. 따라서 형(Type)의 `string` 부분이 유용해 보인다 하더라도, 사실은 자료형 검사(Type checking)의 측면에서 `any` 와 다른 것이 없습니다.
|
||||
대신, `any`, `string`, 나 `string | object` 중 하나를 필요에 맞게 골라서 사용해주세요.
|
||||
|
||||
|
||||
#### 패키지 삭제하기
|
||||
|
||||
패키지가 스스로의 형(Type)을 [포함](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html)하게 되면, DefinitelyTyped 에 있는 자료형(Typing) 패키지를 삭제하는 것이 좋습니다.
|
||||
|
||||
`npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]` 명령어를 사용하여 자료형(Typing) 패키지를 삭제할 수 있습니다.
|
||||
- `typingsPackageName` 는 삭제할 디렉토리의 이름입니다.
|
||||
- `asOfVersion` 는 새 스텁(Stub) 용 `@types/foo` 를 퍼블리시(Publish)할 버전입니다. 이 버전은 현재 NPM 에 올라간 버전보다 더 높은 버전이어야 합니다.
|
||||
- `sourceRepoURL` 는 자료형(Typing)을 포함하게 된 저장소의 주소입니다.
|
||||
- `libraryName` 는 패키지의 이름을 읽기 쉽게 쓴 것입니다. 즉, "angular2" 대신에 "Angular 2" 와 같이 쓰는 것이 좋습니다. (생략했을 경우에는 "typingsPackageName" 와 같은 것으로 취급됩니다.)
|
||||
|
||||
DefinitelyTyped 의 다른 패키지들이 삭제된 자료형(Typing) 패키지를 사용하고 있을 경우, 형(Type)을 포함하기 시작한 원래 패키지를 사용하도록 수정해야합니다. 삭제된 자료형(Typing) 패키지를 사용하는 각 DefinitelyTyped 패키지들의 `package.json` 파일에 `"dependencies": { "foo": "x.y.z" }` 를 추가해주시면 됩니다.
|
||||
|
||||
DefinitelyTyped 에 한 번도 올라온 적 없는 패키지가 형(Type)을 포함하게 되었다면, `notNeededPackages.json` 파일에 추가할 필요도 없습니다.
|
||||
|
||||
|
||||
#### 린트(Lint)하기
|
||||
|
||||
자료형(Typing) 패키지를 린트(Lint)하려면, 패키지 디렉토리에 `{ "extends": "dtslint/dt.json" }` 를 포함하고 있는 `tslint.json` 파일을 추가해주시면 됩니다. 모든 새 패키지는 해당 파일을 가지고 있어야 합니다.
|
||||
고쳐야 하지만 아직 고쳐지지 않은 린트(Lint) 결과가 있을 때에만 `tslint.json` 에서 린트 규칙(Lint rule)을 사용하지 않도록 설정할 수 있습니다. 예를 들어,
|
||||
|
||||
```js
|
||||
{
|
||||
"extends": "dtslint/dt.json",
|
||||
"rules": {
|
||||
// 이 패키지는 Function 형을 사용하고 있으며, 고치는 게 쉽지 않다.
|
||||
"ban-types": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
(린트 규칙(Lint rule)이 절대로 적용되서는 안되는 경우에는, `// tslint:disable rule-name` 나 `//tslint:disable-next-line rule-name` 를 사용하는 것이 좋습니다. 후자가 더 나은 방식입니다.)
|
||||
|
||||
어떤 표현식(Expression)이 특정한 형(Type)을 가진다고 단언(Assert)하고 싶을 때에는 `$ExpectType` 를 사용하시면 됩니다. 어떤 표현식(Expression)이 컴파일에 실패해야하는 경우에는 `$ExpectError` 를 하시면 됩니다.
|
||||
|
||||
```js
|
||||
// $ExpectType void
|
||||
f(1);
|
||||
|
||||
// $ExpectError
|
||||
f("one");
|
||||
```
|
||||
|
||||
[dtslint](https://github.com/Microsoft/dtslint#write-tests) 저장소의 README 파일에서 더 자세한 내용을 확인하실 수 있습니다.
|
||||
|
||||
이런 테스트들은 `npm run lint package-name` 명령으로 실행해볼 수 있습니다. 이 때, `package-name` 은 테스트하고 싶은 패키지의 이름입니다.
|
||||
테스트 스크립트는 [dtslint](https://github.com/Microsoft/dtslint) 를 사용하고 있습니다.
|
||||
|
||||
|
||||
## 자주 하는 질문들
|
||||
|
||||
#### 이 저장소와 `@types` 패키지들이 대체 무슨 관계가 있는 건가요?
|
||||
|
||||
`master` 브랜치(Branch)의 내용들이 [types-publisher](https://github.com/Microsoft/types-publisher) 를 사용해 자동으로 `@types` 퍼블리시(Publish)됩니다.
|
||||
|
||||
#### 풀 리퀘스트(Pull request)를 제출했습니다. 이게 합쳐질 때까지 얼마나 걸리나요?
|
||||
|
||||
상황에 따라 다르지만, 대부분의 풀 리퀘스트(Pull request)들은 일주일 안에 합쳐집니다. 머릿주석에 있는 저자 중 한명에 의해 승인된 풀 리퀘스트(Pull request)는 보통 더 빨리 합쳐집니다. 새로운 패키지에 대한 풀 리퀘스트(Pull request)는 관리자의 세세한 코드 리뷰를 필요로 하기 때문에 더 오래 걸리는 경우가 많습니다. 각 PR 들은 합쳐지기 전에 TypeScript or DefinitelyTyped 팀 구성원의 코드 리뷰를 받아야 하며, 이는 사람이 하는 일이기 때문에 느려질 수도 있으니 양해를 바랍니다. [풀 리퀘스트 번다운 보드(PR Burndown Board)](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen)에서 열린 풀 리퀘스트에 대한 관리자들의 진행도를 확인하실 수 있습니다.
|
||||
|
||||
#### 내 풀 리퀘스트(Pull request)는 합쳐졌습니다. 언제 NPM 에 `@types` 패키지가 갱신되나요?
|
||||
|
||||
NPM 의 패키지들은 수시간 안에 갱신될 겁니다. 만약 24 시간이 지나도 갱신되지 않으면, 문제를 파악하기 위해 @RyanCavanaugh 나 @andy-ms 를 풀 리퀘스트(Pull request)에서 호출해주세요.
|
||||
|
||||
#### 다른 자료형 정의(Type definition)에 의존하는 자료형 정의(Type definition)을 만들고 있습니다. `<reference types="" />` 와 임포트(import) 중 무엇을 사용해야하나요?
|
||||
|
||||
외부 모듈(`export` 를 사용하는 모듈)을 사용할 경우, 임포트(import)를 사용해주세요.
|
||||
환경과 관련된 모듈(ambient module)(`declare module` 를 쓰거나 전역 변수들을 선언한 모듈)을 사용할 경우, `<reference types="" />` 를 사용해주세요.
|
||||
|
||||
#### `package.json` 파일이 가끔 보이던데?
|
||||
|
||||
일반적으로는 `package.json` 파일을 사용할 필요가 없습니다. 패키지가 퍼블리시(Publish)될 때 패키지를 위한 `package.json` 파일은 자동으로 생성됩니다.
|
||||
가끔 보이는 `package.json` 파일은 의존하는 것들을 표시하기 위해 사용됩니다. [예시](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json)를 한 번 보세요.
|
||||
의존성을 제외한 다른 필드(Field)들, 그러니까 `"description"` 같은 것들은 사용해서는 안됩니다.
|
||||
옛날 `@types` 패키지를 사용하고 싶으실 경우에도 `"dependencies": { "@types/foo": "x.y.z" }` 와 같은 내용을 `package.json` 파일에 넣으셔야 합니다.
|
||||
|
||||
#### 어떤 패키지들에 `tslint.json` 이 없거나, `tsconfig.json` 에 `"noImplicitAny": true`, `"noImplicitThis": true`, 나 `"strictNullChecks": true` 가 없어요.
|
||||
|
||||
그럼 그 패키지들이 잘못된 겁니다. 고쳐서 풀 리퀘스트(Pull request)를 제출해주시면 고맙겠습니다.
|
||||
|
||||
#### 자료형 정의(Type definition)을 요청할 수 있나요?
|
||||
|
||||
이미 요청된 자료형 정의(Type definition)들을 [여기서](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest) 보실 수 있습니다.
|
||||
|
||||
#### DOM 을 위한 자료형 정의(Type definitions)는요?
|
||||
|
||||
웹 표준(Web standard)과 관련이 있는 자료형(Typing)들은 [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) 저장소에 기여해서 고치실 수 있습니다. 고쳐진 자료형(Typing)은 `lib.dom.d.ts` 파일에 포함될 겁니다.
|
||||
|
||||
#### 어떤 패키지가 `export =` 를 쓰고 있는데, 저는 디폴트 임포트(Default import)가 더 좋습니다. `export =` 를 `export default` 로 바꿔도 되나요?
|
||||
|
||||
타입스크립트(TypeScript) 2.7 이상을 사용하고 계시면 프로젝트 안에서 `--esModuleInterop` 를 사용해주세요.
|
||||
그 이하의 경우, 디폴트 임포트(Default import)가 동작하는 환경(Webpack, SystemJS, esm)에서 작업 중이시면 [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) 를 사용하는 걸 고려해보세요.
|
||||
자료형 정의(Type definition)가 맞는 경우에는 자료형 정의(Type definition)을 수정하지 마세요.
|
||||
NPM 패키지의 경우, `node -p 'require("foo")'` 가 원하는 값이라면 `export =` 이 맞고, `node -p 'require("foo").default'` 이 원하는 값이라면 `export default` 이 맞습니다.
|
||||
|
||||
#### 자료형 선언(Type declaration)에서 타입스크립트(TypeScript) 2.1 이상의 기능을 사용하고 싶습니다.
|
||||
|
||||
정의(Definition) 머릿주석(`// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`) 뒤에 `// TypeScript Version: 2.1` 를 추가해주시면 됩니다.
|
||||
|
||||
#### 타입스크립트(TypeScript)에 기본으로 포함되지 않은 DOM API 를 추가하고 싶어요.
|
||||
|
||||
[TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme) 저장소가 관련되어있을 가능성이 있습니다. 해당 저장소의 안내를 따라주세요.
|
||||
해당 표준이 아직 초안인 상태라면, 이 저장소와 관련된 일입니다.
|
||||
`dom-` 으로 시작하는 패키지를 만드신 뒤, "Project" 머릿주석 부분에 해당 표준의 링크를 써 주세요.
|
||||
다만 표준이 초안을 벗어나면 DefinitelyTyped 에서 삭제되고 `@types` 패키지가 지원이 중단된(Deprecated) 것으로 표시될 수도 있습니다.
|
||||
|
||||
#### 패키지를 새 메이저 버전(major version)에 맞게 갱신하고 싶어요.
|
||||
|
||||
옛날 버전도 계속해서 수정할 예정이라면, 이전 버전에 해당하는 새 디렉토리(예를 들어 `2.` 버전을 위해서는 `v2`)를 만들고 현재 파일들을 그 디렉토리로 옮겨야 합니다. 새 디렉토리로 옮긴 뒤에는
|
||||
|
||||
1. `tsconfig.json` 와 `tslint.json` 에 포함된 상대경로들을 수정해주어야 합니다.
|
||||
2. 경로 대응 규칙(Path mapping rule)을 추가하여 테스트가 올바른 버전을 검사하도록 해야합니다.
|
||||
|
||||
예를 들어, [history 패키지의 2 버전의 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) 파일은 다음과 같이 생겼습니다.
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"baseUrl": "../../",
|
||||
"typeRoots": ["../../"],
|
||||
"paths": {
|
||||
"history": [ "history/v2" ]
|
||||
},
|
||||
},
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"history-tests.ts"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
수정 중인 패키지에 의존하는 DefinitelyTyped 의 다른 패키지들이 새 버전과 호환되지 않을 경우, 그 패키지들에도 옛날 버전으로의 경로 대응 규칙(Path mapping rule)을 추가해주어야 합니다. 수정 중인 패키지에 의존하는 패키지에 의존하는 패키지들에도 똑같은 작업을 해 주셔야 합니다.
|
||||
|
||||
예를 들어, `react-router` 패키지는 `history@2` 패키지에 의존하고 있기 때문에, [react-router 패키지의 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) 파일이 `"history": [ "history/v2" ]` 와 같은 경로 대응 규칙(Path mapping rule)을 가지고 있는 걸 볼 수 있습니다.
|
||||
이어서 (`react-router` 패키지에 의존하는 패키지인) `react-router-bootstrap` 또한 [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json) 파일 안에 경로 대응 규칙(Path mapping rule)을 가지고 있는 것을 보실 수 있습니다.
|
||||
|
||||
`/// <reference types=".." />` 에서는 경로 대응 규칙(Path mapping rule)이 동작하지 않기 때문에, DefinitelyTyped 패키지로에 의존할 때에는 임포트(import) 를 사용해야 합니다.
|
||||
|
||||
#### 전역적으로도 모듈로도 사용될 수 있는 패키지의 자료형 선언(Type declaration)은 어떻게 쓰나요?
|
||||
|
||||
타입스크립트 안내서(TypeScript Handbook)은 [선언(Declaration)을 쓰는 방법에 대한 전반적인 정보](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html)와 [예시들](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html)을 포함하고 있습니다. 이 내용에는 ES6 식의 모듈 문법을 사용할 수 있는 자료형 선언(Type declaration)을 만드는 방법과 객체를 전역에서 사용할 수 있도록 하는 방법이 포함되어 있습니다. [big.js 패키지의 자료형 선언(Type declaration)](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts)이 실례입니다. 이 패키지는 웹 페이지의 스크립트 태그를 사용해 불러올 수 있으며, 또한 ES6 식의 임포트(Import) 구문을 사용해서 불러올 수도 있습니다.
|
||||
|
||||
여러분의 패키지가 임포트(Import) 구문을 사용했을 때와 전역적으로 불렀을 때를 테스트 해보고 싶다면, `test` 디렉토리를 추가하고 `YourLibraryName-global.test.ts` 그리고 `YourLibraryName-module.test.ts` 라는 이름으로 테스트 파일 두 개를 추가해주세요. **전역(Global)** 테스트 파일은 웹 페이지에서 전역적으로 사용될 때를 테스트하는 파일입니다. 이 파일에서는 임포트(Import) 구문을 사용하지 않아야 합니다. **모듈(Module)** 테스트 파일은 임포트(Import) 구문을 사용할 때를 테스트 하는 파일입니다. 만약 여러분의 `tsconfig.json` 파일이 `files` 필드(Field)를 가지고 있다면, 이 필드(Field)는 반드시 두 테스트 파일을 모두 포함해야 합니다. [이 방식을 사용하는 실례](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) 또한 big.js 패키지의 자료형 선언(Type declaration)에서 확인해보실 수 있습니다.
|
||||
|
||||
각각의 테스트 파일에 모든 상황을 테스트할 필요는 없다는 걸 잊지마세요. 전역 테스트 파일에서는 전역적으로 사용될 때만 테스트하고, 모듈 테스트 파일에서 나머지 상황들을 모두 테스트 할 수 있으며, 그 반대의 경우도 괜찮습니다.
|
||||
|
||||
#### 지역 패키지(Scoped package)의 경우는 어떻게 하죠?
|
||||
|
||||
`@foo/bar` 패키지와 같은 지역 패키지(Scoped package)를 위한 자료형 패키지(Type package)는 `types/foo__bar` 디렉토리에 추가하면 됩니다. 밑줄 문자가 두 번 있는 것에 주의하세요.
|
||||
|
||||
지역 패키지(Scoped package)를 위한 자료형 패키지(Type package)를 생성하기 위해 `dts-gen` 를 사용한 경우에는,
|
||||
다음과 같이 생성된 `tsconfig.json` 안에 지역 패키지(Scoped package)를 위한 적절한 경로 대응 규칙(Path mapping rule)을 추가해주어야 합니다.
|
||||
|
||||
```json
|
||||
{
|
||||
"paths":{
|
||||
"@foo/bar": ["foo__bar"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### 깃헙(GitHub)이 보여주는 파일 히스토리(History)가 불완전해요.
|
||||
|
||||
깃헙은 이름이 바뀐 파일의 히스토리(History)를 [지원하지 않습니다](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames). 대신 [`git log --follow`](https://www.git-scm.com/docs/git-log) 명령을 사용하세요.
|
||||
|
||||
#### ES6 에서 사용하는 임포트(Import)를 사용하기 위해 모듈을 익스포트(Export)하지 않는 패키지들에 빈 이름공간을 추가해야 하나요?
|
||||
|
||||
[chai-http](https://github.com/chaijs/chai-http) 패키지와 같은 몇몇 패키지들은 함수를 익스포트(Export)합니다.
|
||||
|
||||
이런 패키지들을 `import * as foo from "foo";` 와 같이 임포트(Import)하면 다음과 같은 오류가 발생합니다.
|
||||
|
||||
> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct
|
||||
|
||||
이 오류는 함수의 이름과 똑같은 빈 이름공간(Namespace)을 정의해서 없앨 수 있으나, 좋은 방법은 아닙니다.
|
||||
[스택오버플로(Stack Overflow)의 이 질문의 답변](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this)이 이 문제와 관련되어 자주 언급됩니다.
|
||||
|
||||
`import foo = require("foo");` 를 사용하여 모듈을 임포트(Import)하거나, 환경에서 ES6 모듈 변환(Module interop)을 지원한다면 `--allowSyntheticDefaultImports` 와 함께 `import foo from "foo";` 같은 디폴트 임포트(Default import)를 사용하는 것이 더 나은 방법입니다.
|
||||
|
||||
## 라이센스
|
||||
|
||||
이 프로젝트는 MIT license 가 적용되어 있습니다.
|
||||
|
||||
각 자료형 정의(Type definition) 파일들의 저작권은 각 기여자들에게 있으며, 기여자들은 해당 자료형 정의(Type definition) 파일들의 맨 위에 나열되어 있습니다.
|
||||
|
||||
[](https://github.com/igrigorik/ga-beacon)
|
||||
@@ -1,12 +1,23 @@
|
||||
# DefinitelyTyped [](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
|
||||
|
||||
[](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
# DefinitelyTyped
|
||||
|
||||
> The repository for *high quality* TypeScript type definitions.
|
||||
|
||||
Also see the [definitelytyped.org](http://definitelytyped.org) website, although information in this README is more up-to-date.
|
||||
|
||||
*[You can also read this README in Spanish!](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md)*
|
||||
*You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md), [Korean](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md), and [Russian](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ru.md)!*
|
||||
|
||||
## Current status
|
||||
|
||||
This section tracks the health of the repository and publishing process.
|
||||
It may be helpful for contributors experiencing any issues with their PRs and packages.
|
||||
|
||||
* All packages are type-checking/linting cleanly: [](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
|
||||
* All packages are being published to npm in under 10,000 seconds: [](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13)
|
||||
* [typescript-bot](https://github.com/typescript-bot) has been active on DefinitelyTyped [](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14)
|
||||
|
||||
If anything here seems wrong, or any of the above are failing, please raise an issue in [the DefinitelyTyped Gitter channel](https://gitter.im/DefinitelyTyped/DefinitelyTyped).
|
||||
|
||||
[](https://gitter.im/DefinitelyTyped/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
## What are declaration files?
|
||||
|
||||
@@ -54,7 +65,7 @@ Before you share your improvement with the world, use it yourself.
|
||||
|
||||
#### Test editing an existing package
|
||||
|
||||
To add new features you can use [module augmentation](http://www.typescriptlang.org/docs/handbook/declaration-merging.html).
|
||||
To add new features you can use [module augmentation](http://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation).
|
||||
You can also directly edit the types in `node_modules/@types/foo/index.d.ts`, or copy them from there and follow the steps below.
|
||||
|
||||
|
||||
@@ -87,6 +98,7 @@ 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>`.
|
||||
@@ -120,7 +132,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.
|
||||
@@ -168,8 +180,14 @@ If a package was never on DefinitelyTyped, it does not need to be added to `notN
|
||||
|
||||
#### Lint
|
||||
|
||||
To lint a package, just add a `tslint.json` to that package containing `{ "extends": "dtslint/dt.json" }`. All new packages must be linted.
|
||||
If a `tslint.json` turns rules off, this is because that hasn't been fixed yet. For example:
|
||||
All new packages must be linted. To lint a package, add a `tslint.json` to that package containing
|
||||
```js
|
||||
{
|
||||
"extends": "dtslint/dt.json"
|
||||
}
|
||||
```
|
||||
|
||||
This should be the only content in a finished project's `tslint.json` file. If a `tslint.json` turns rules off, this is because that hasn't been fixed yet. For example:
|
||||
|
||||
```js
|
||||
{
|
||||
@@ -248,6 +266,41 @@ For an NPM package, `export =` is accurate if `node -p 'require("foo")'` is the
|
||||
|
||||
Then you will have to add a comment to the last line of your definition header (after `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// TypeScript Version: 2.1`.
|
||||
|
||||
#### I want to use features from TypeScript 3.1 or above.
|
||||
|
||||
You will need to use the `typesVersions` feature of TypeScript 3.1 and above. You can find a detailed explanation
|
||||
of this feature in the [official TypeScript documentation](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-1.html#version-selection-with-typesversions).
|
||||
|
||||
Here's a short explanation to get you started:
|
||||
|
||||
1. You'll have to add a `package.json` file to your package definition, with the following contents:
|
||||
|
||||
```json
|
||||
{
|
||||
"private": true,
|
||||
"types": "index",
|
||||
"typesVersions": {
|
||||
">=3.1.0-0": { "*": ["ts3.1/*"] }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
2. Create the sub-directory mentioned in the `typesVersions` field inside your types directory (`ts3.1/` in this example)
|
||||
and add the types and tests specific for the new TypeScript version. You don't need the typical definition header
|
||||
in any of the files from the `ts3.1/` directory.
|
||||
|
||||
3. Set the `baseUrl` and `typeRoots` options in `ts3.1/tsconfig.json` to the correct paths, they should look something like this:
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"baseUrl": "../../",
|
||||
"typeRoots": ["../../"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You can look [here](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/debounce-promise) and [here](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/create-html-element) for examples.
|
||||
|
||||
#### I want to add a DOM API not present in TypeScript by default.
|
||||
|
||||
This may belong in [TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme). See the guidelines there.
|
||||
|
||||
+353
@@ -0,0 +1,353 @@
|
||||
<!-- markdownlint-disable MD001 MD012 MD026 -->
|
||||
|
||||
# DefinitelyTyped [](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
|
||||
|
||||
[](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
> Репозиторий для *высококачественных* определений типов TypeScript.
|
||||
|
||||
Также посетите веб-сайт [definitelytyped.org](http://definitelytyped.org), хотя информация в этом README более свежая.
|
||||
|
||||
*Вы также можете прочитать этот README на [английском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md), [испанском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md) и [корейском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md).*
|
||||
|
||||
## Что такое файлы декларации (файлы описания/объявления типов)?
|
||||
|
||||
Смотрите [руководство по TypeScript](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html).
|
||||
|
||||
## Как их получить?
|
||||
|
||||
### npm
|
||||
|
||||
Это предпочтительный метод. Это доступно только для пользователей TypeScript 2.0+. Например:
|
||||
|
||||
```sh
|
||||
npm install --save-dev @types/node
|
||||
```
|
||||
|
||||
Затем типы должны автоматически включаться компилятором.
|
||||
Подробнее смотрите в [справочнике](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html).
|
||||
|
||||
Для пакета NPM "foo", описания будут находиться в "@types/foo".
|
||||
Если вы не можете найти свой пакет, ищите его в [TypeSearch](https://microsoft.github.io/TypeSearch/).
|
||||
|
||||
Если вы все еще не можете найти его, проверьте [включает](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) ли пакет собственную типизацию.
|
||||
Обычно это отражается в поле `"types"` или `"typings"` файла `package.json`, или просто ищите любые файлы ".d.ts" в пакете и вручную включайте их в `/// <reference path="" />`.
|
||||
|
||||
|
||||
### Другие методы
|
||||
|
||||
Эти методы могут быть использованы TypeScript 1.0.
|
||||
|
||||
* [Typings](https://github.com/typings/typings)
|
||||
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (используйте предпочтительные альтернативы, публикация типа nuget DT отключена)
|
||||
* Вручную загрузите из ветки `master` этого репозитория
|
||||
|
||||
Возможно, вам придется добавить ручные [ссылки](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).
|
||||
|
||||
|
||||
## Как я могу внести свой вклад?
|
||||
|
||||
DefinitelyTyped работает только благодаря вкладу таких пользователей, как вы!
|
||||
|
||||
### Тестирование
|
||||
|
||||
Прежде чем поделиться своим улучшением с миром, используйте его сами.
|
||||
|
||||
#### Тестирование редактирования существующего пакета
|
||||
|
||||
Для добавления новых функций вы можете использовать [разрешение модулей](http://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation).
|
||||
Вы также можете напрямую редактировать типы в `node_modules/@types/foo/index.d.ts`, или скопировать их оттуда и выполнить следующие шаги.
|
||||
|
||||
|
||||
#### Тестирование ногово пакета
|
||||
|
||||
Добавьте к вашему `tsconfig.json`:
|
||||
|
||||
```json
|
||||
"baseUrl": "types",
|
||||
"typeRoots": ["types"],
|
||||
```
|
||||
|
||||
(Вы также можете использовать `src/types`.)
|
||||
Создайте `types/foo/index.d.ts` содержащие объявления для модуля "foo".
|
||||
Теперь вы сможете импортировать из `"foo"` в свой код, и он будет направлен к новому определению типа.
|
||||
Затем запустите сборку (build) *и* запустите код, чтобы убедиться, что ваше определение типа действительно соответствует тому, что происходит во время выполнения.
|
||||
После того как вы проверили свои определения с реальным кодом, создайте [Запрос на принятие изменений (PR)](#make-a-pull-request)
|
||||
и следуйте инструкциям [чтобы отредактировать существующий](#edit-an-existing-package) или
|
||||
[создать новый пакет](#create-a-new-package).
|
||||
|
||||
|
||||
### Запрос на принятие изменений (PR)
|
||||
|
||||
После того, как вы проверили ваш пакет, вы можете поделиться им с DefinitelyTyped.
|
||||
|
||||
Во-первых, [разветвите](https://guides.github.com/activities/forking/) этот репозиторий, установите [node](https://nodejs.org/), и запустите `npm install`.
|
||||
|
||||
|
||||
#### Изменение существующего пакета
|
||||
|
||||
* `cd types/my-package-to-edit`
|
||||
* Внесите изменения. Не забудьте отредактировать тесты.
|
||||
Если вы вносите критические изменения, не забудьте [обновить основную версию](#i-want-to-update-a-package-to-a-new-major-version).
|
||||
* Вы также можете добавить себя в раздел "Definitions by" заголовка пакета.
|
||||
* Это приведет к тому, что вы будете уведомлены (через ваше имя пользователя GitHub) о том, что кто-то делает запрос на принятие изменений (PR) или проблему с пакетом.
|
||||
* Сделайте это, добавив свое имя в конец строки, например `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
|
||||
* Или, если есть больше людей, это может быть многострочным
|
||||
|
||||
```typescript
|
||||
// Definitions by: Alice <https://github.com/alice>
|
||||
// Bob <https://github.com/bob>
|
||||
// Steve <https://github.com/steve>
|
||||
// John <https://github.com/john>
|
||||
```
|
||||
|
||||
* Если есть `tslint.json`, запустите `npm run lint package-name`. В противном случае запустите `tsc` в директории пакета.
|
||||
|
||||
Когда вы создаете PR для редактирования существующего пакета, `dt-bot` должен @-уведомить
|
||||
предыдущих авторов. Если этого не произойдет, вы можете сделать это самостоятельно в комментарии, связанном с PR.
|
||||
|
||||
|
||||
#### Созданое нового пакета
|
||||
|
||||
Если вы являетесь автором библиотеки и ваш пакет написан на TypeScript, [свяжите автоматически сгенерированные файлы объявлений](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) в вашем пакете, а не публикуйте в DefinitelyTyped.
|
||||
|
||||
Если вы добавляете типизацию для пакета NPM, создайте директорию с тем же именем.
|
||||
Если пакет, для которого вы добавляете типизацию, отсутствует в NPM, убедитесь, что выбранное вами имя не конфликтует с именем пакета в NPM.
|
||||
(Вы можете использовать `npm info foo` чтобы проверить наличие пакета `foo`.)
|
||||
|
||||
Ваш пакет должен иметь такую структуру:
|
||||
|
||||
| Файл | Назначение |
|
||||
| ------------- | ---------------------------------------------------------------------------------------------------- |
|
||||
| index.d.ts | Содержит типизацию для пакета. |
|
||||
| foo-tests.ts | Содержит пример кода, который проверяет типизацию. Этот код *не* запускается, но он проверен на тип. |
|
||||
| tsconfig.json | Позволяет вам запускать `tsc` внутри пакета. |
|
||||
| tslint.json | Включает linting. |
|
||||
|
||||
Создайте их, запустив `npx dts-gen --dt --name my-package-name --template module` если у вас npm ≥ 5.2.0, `npm install -g dts-gen` и `dts-gen --dt --name my-package-name --template module` в противном случае.
|
||||
Посмотреть все варианты на [dts-gen](https://github.com/Microsoft/dts-gen).
|
||||
|
||||
Вы можете отредактировать `tsconfig.json` чтобы добавить новые файлы, добавить `"target": "es6"` (необходимо для асинхронных функций), добавить в `"lib"`, или добавить опцию компилятора `"jsx"`.
|
||||
|
||||
Члены группы DefinitelyTyped регулярно следят за новыми PR, но имейте в виду, что количество других PR может замедлить ход событий.
|
||||
|
||||
Хороший пример пакета смотрите [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js).
|
||||
|
||||
|
||||
#### Распространенные ошибки
|
||||
|
||||
* Сначала следуйте советам из справочника [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html).
|
||||
* Форматирование: либо используйте все табы, либо всегда используйте 4 пробела.
|
||||
* `function sum(nums: number[]): number`: используйте `ReadonlyArray` если функция не записывает свои параметры.
|
||||
* `interface Foo { new(): Foo; }`:
|
||||
Это определяет тип объектов, с методом `new`. Вы, вероятно, хотите объявить `declare class Foo { constructor(); }`.
|
||||
* `const Class: { new(): IClass; }`:
|
||||
Предпочитайте использовать объявление класса `class Class { constructor(); }` вместо `new`.
|
||||
* `getMeAT<T>(): T`:
|
||||
Если параметр типа не отображается в типах каких-либо параметров, у вас нет универсальной функции, а просто замаскированное утверждение типа.
|
||||
Предпочитайте использовать утверждение реального типа, например, `getMeAT() as number`.
|
||||
Пример, где допустим параметр типа: `function id<T>(value: T): T;`.
|
||||
Пример, где это недопустимо: `function parseJson<T>(json: string): T;`.
|
||||
Исключение: `new Map<string, number>()` все ОК.
|
||||
* Использование типов `Function` and `Object` почти никогда не является хорошей идеей. В 99% случаев можно указать более конкретный тип. Примеры: `(x: number) => number` для [функций](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) and `{ x: number, y: number }` для объектов. Если нет никакой уверенности в типе, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) является правильным выбором, а не `Object`. Если единственным известным фактом о типе является то, что это какой-то объект, используйте тип [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), а не `Object` или `{ [key: string]: any }`.
|
||||
* `var foo: string | any`:
|
||||
когда `any` используется в типе объединения, результирующий тип все еще `any`. Таким образом, хотя `string` часть аннотации этого типа может _выглядеть_ полезной, на самом деле она не предлагает никакой дополнительной проверки типов по сравнению с простым использованием `any`.
|
||||
В зависимости от намерения, приемлемыми альтернативами могут быть `any`, `string`, или `string | object`.
|
||||
|
||||
|
||||
#### Удаление пакета
|
||||
|
||||
Когда пакет [объединяет](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) свои собственные типы, типы должны быть удалены из DefinitelyTyped чтобы избежать путаницы.
|
||||
|
||||
Вы можете удалить его, запустив `npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]`.
|
||||
|
||||
* `typingsPackageName`: название директории, который нужно удалить.
|
||||
* `asOfVersion`: заглушка будет опубликована в `@types/foo` с этой версией. Должна быть выше, чем любая опубликованная на данный момент версия
|
||||
* `sourceRepoURL`: Это должно указывать на репозиторий, который содержит типизации.
|
||||
* `libraryName`: описательное имя библиотеки, например, "Angular 2" вместо "angular2". (Если опущено, будет идентично "typingsPackageName".)
|
||||
|
||||
Любые другие пакеты в DefinitelyTyped которые ссылаются на удаленный пакет, должны быть обновлены для ссылки на связанные типы. Для этого добавьте в `package.json` ссыклу `"dependencies": { "foo": "x.y.z" }`.
|
||||
|
||||
Если пакет никогда не был в DefinitelyTyped, его не нужно добавлять в `notNeededPackages.json`.
|
||||
|
||||
|
||||
#### Lint
|
||||
|
||||
Все новые пакеты должны быть проанализированы lint. Для этого добавьте `tslint.json` в этот пакет, содержащий
|
||||
|
||||
```js
|
||||
{
|
||||
"extends": "dtslint/dt.json"
|
||||
}
|
||||
```
|
||||
|
||||
Это должно быть единственным содержимым в файле `tslint.json` готового проекта. Если `tslint.json` отключает правила, это потому, что это еще не исправлено. Например:
|
||||
|
||||
```js
|
||||
{
|
||||
"extends": "dtslint/dt.json",
|
||||
"rules": {
|
||||
// This package uses the Function type, and it will take effort to fix.
|
||||
"ban-types": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
(Чтобы указать, что правило lint действительно не применяется, используйте `// tslint:disable rule-name` или лучше, `//tslint:disable-next-line rule-name`.)
|
||||
|
||||
Чтобы проверить, что выражение имеет заданный тип, используйте `$ExpectType`. Чтобы проверить, что выражение вызывает ошибку компиляции, используйте `$ExpectError`.
|
||||
|
||||
```js
|
||||
// $ExpectType void
|
||||
f(1);
|
||||
|
||||
// $ExpectError
|
||||
f("one");
|
||||
```
|
||||
|
||||
Для получения дополнительной информации см. [dtslint](https://github.com/Microsoft/dtslint#write-tests) readme.
|
||||
|
||||
Протестируйте, запустив `npm run lint package-name` где `package-name` - это имя вашего пакета.
|
||||
Этот скрипт использует [dtslint](https://github.com/Microsoft/dtslint).
|
||||
|
||||
|
||||
## Часто задаваемые вопросы
|
||||
|
||||
#### Какая связь между этим репозиторием и пакетами `@types` в NPM?
|
||||
|
||||
Ветвь `master` автоматически публикуется в область `@types` на NPM благодаря [types-publisher](https://github.com/Microsoft/types-publisher).
|
||||
|
||||
#### Я отправил PR. Когда он сольется?
|
||||
|
||||
Это зависит, но большинство запросов на получение данных будут объединены в течение недели. PR, утвержденные автором, указанным в заголовке определения, обычно объединяются быстрее; PR для новых определений займет больше времени, так как они требуют большего количества проверок от сопровождающих. Каждый PR проверяется членом команды TypeScript или DefinitelyTyped перед объединением, поэтому будьте терпеливы, так как человеческий фактор может вызвать задержки. Посмотрите на [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) чтобы увидеть, как сопровождающие работают через открытые PR.
|
||||
|
||||
#### Мой PR слит; когда будет обновлен пакет `@types` NPM?
|
||||
|
||||
Пакеты NPM должны обновиться в течение нескольких часов. Если прошло более 24 часов, пингуйте @RyanCavanaugh и @andy-ms в PR, чтобы расследовать.
|
||||
|
||||
#### Я пишу определение, которое зависит от другого определения. Должен ли я использовать `<reference types="" />` или import?
|
||||
|
||||
Если модуль, на который вы ссылаетесь, является внешним модулем (использует `export`), используйте import.
|
||||
Если модуль, на который вы ссылаетесь, является окружающим модулем (использует `declare module`, или просто объявляет глобальные переменные), используйте `<reference types="" />`.
|
||||
|
||||
#### Я заметил, что у некоторых пакетов есть `package.json`.
|
||||
|
||||
Обычно вам это не нужно. При публикации пакета мы обычно автоматически создаем `package.json`.
|
||||
`package.json` может быть включен для определения зависимостей. Вот [пример](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json).
|
||||
Мы не разрешаем определять другие поля, такие как "description", вручную.
|
||||
Кроме того, если вам нужно сослаться на более старую версию типизаций, вы должны сделать это, добавив в `package.json` строки `"dependencies": { "@types/foo": "x.y.z" }`.
|
||||
|
||||
#### В некоторых пакетах отсутствует `tslint.json`, а в некоторых `tsconfig.json` отсутствует `"noImplicitAny": true`, `"noImplicitThis": true`, или `"strictNullChecks": true`.
|
||||
|
||||
Тогда они не правы. Вы можете помочь, отправив PR, чтобы исправить их.
|
||||
|
||||
#### Могу ли я запросить определение?
|
||||
|
||||
Вот [текущие запрошенные определения](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest).
|
||||
|
||||
#### Как насчет определений типов для DOM?
|
||||
|
||||
Если типы являются частью веб-стандарта, они должны быть добавлены в [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) чтобы они могли стать частью `lib.dom.d.ts` по умолчанию.
|
||||
|
||||
#### Пакет использует export `export =`, но я предпочитаю использовать импорт по умолчанию. Могу ли я изменить `export =` на `export default`?
|
||||
|
||||
Если вы используете TypeScript 2.7 или более позднюю версию, используйте `--esModuleInterop` в вашем проекте.
|
||||
В противном случае, если импорт по умолчанию работает в вашей среде (например, Webpack, SystemJS, esm), рассмотрите возможность включения опции компилятора [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html).
|
||||
Не меняйте определение типа, если оно точное.
|
||||
Для пакета NPM, `export =` является точным, если `node -p 'require("foo")'` является экспортом, а `export default` является точным, если `node -p 'require("foo").default'` является экспортом.
|
||||
|
||||
#### Я хочу использовать функции из TypeScript 2.1 или выше.
|
||||
|
||||
В таком случае вам нужно будет добавить комментарий к последней строке заголовка вашего определения (после `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// TypeScript Version: 2.1`.
|
||||
|
||||
#### Я хочу добавить DOM API, отсутствующий в TypeScript по умолчанию.
|
||||
|
||||
Это может принадлежать [TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme). Смотрите инструкции там.
|
||||
Если стандарт все еще является черновиком, добавляйте сюда.
|
||||
Используйте имя, начинающееся с `dom-` и включите ссылку на стандарт в качестве ссылки "Project" в заголовке.
|
||||
Когда он завершает черновой режим, мы можем удалить его из DefinitelyTyped и объявить устаревшим связанный пакет `@types`.
|
||||
|
||||
#### Я хочу обновить пакет новой старшей версии
|
||||
|
||||
Если вы намерены продолжить обновление старой версии пакета, вы можете создать новую подпапку с текущей версией, например, `v2` и скопируйте в него существующие файлы. Если это так, вам необходимо:
|
||||
|
||||
1. Обновите относительные пути в `tsconfig.json` а также в `tslint.json`.
|
||||
2. Добавьте правила сопоставления путей, чтобы убедиться, что тесты выполняются для предполагаемой версии.
|
||||
|
||||
Например [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like:
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"baseUrl": "../../",
|
||||
"typeRoots": ["../../"],
|
||||
"paths": {
|
||||
"history": [ "history/v2" ]
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"history-tests.ts"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Если в DefinitelyTyped есть другие пакеты, несовместимые с новой версией, вам нужно будет добавить сопоставления путей к старой версии. Вам также нужно будет сделать это для пакетов в зависимости от пакетов в зависимости от старой версии.
|
||||
|
||||
Например, `react-router` зависит от `history@2`, поэтому [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) есть сопоставление пути с `"history": [ "history/v2" ]`;
|
||||
транзитивно `react-router-bootstrap` (который зависит от `react-router`) также добавляет отображение пути в свой [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json).
|
||||
|
||||
Также, `/// <reference types=".." />` не будет работать с отображением пути, поэтому зависимости должны использовать `import`.
|
||||
|
||||
#### Как мне написать определения для пакетов, которые могут использоваться и глобально и в качестве модуля?
|
||||
|
||||
Руководство TypeScript содержит отличную [общую информацию о написании определений](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), а также [этот пример файла определения](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) , в котором показано, как создать определение с использованием синтаксиса модуля в стиле ES6, а также указаны объекты, доступные для глобальной области. Этот метод демонстрируется практически в определении для [definition for big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), библиотекой, которую можно загружать глобально с помощью тега скрипта на веб-странице или импортировать с помощью импорта по требованию или в стиле ES6.
|
||||
|
||||
Чтобы проверить, как ваше определение может использоваться как при глобальных ссылках, так и в качестве импортированного модуля, создайте тестовую папку `test`, и поместите туда два тестовых файла. Назовите один `YourLibraryName-global.test.ts` а другой `YourLibraryName-module.test.ts`. *Глобальный* тестовый файл должен использовать определение в соответствии с тем, как он будет использоваться в скрипте, загруженном на веб-страницу, где библиотека доступна в глобальной области видимости - в этом сценарии не следует указывать оператор импорта. Тестовый файл *модуля* должен использовать определение в соответствии с тем, как оно будет использоваться при импорте (включая оператор(ы) `import`). Если вы указали свойство `files` в файле `tsconfig.json`, обязательно включите оба тестовых файла. [Практический пример этого](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) также доступен в определении big.js.
|
||||
|
||||
Обратите внимание, что не требуется полностью использовать определение в каждом тестовом файле - достаточно протестировать только глобально доступные элементы в глобальном тестовом файле и полностью выполнить определение в тестовом файле модуля, или наоборот.
|
||||
|
||||
#### А как насчет областных пакетов?
|
||||
|
||||
Типы для пакета с областью `@foo/bar` должны указываться в `types/foo__bar`. Обратите внимание на двойное подчеркивание.
|
||||
|
||||
Когда `dts-gen` используется для компоновки пакета с областью действия, свойство `paths` должно быть вручную адаптировано в сгенерированном файле
|
||||
`tsconfig.json` для правильной ссылки на пакет с областью действия:
|
||||
|
||||
```json
|
||||
{
|
||||
"paths":{
|
||||
"@foo/bar": ["foo__bar"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### История файлов в GitHub выглядит неполной.
|
||||
|
||||
GitHub не [поддерживает](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) историю файлов для переименованных файлов. Вместо этого используйте [`git log --follow`](https://www.git-scm.com/docs/git-log).
|
||||
|
||||
#### Должен ли я добавить пустой namespace в пакет, который не экспортирует модуль для использования импорта в стиле ES6?
|
||||
|
||||
Некоторые пакеты, такие как [chai-http](https://github.com/chaijs/chai-http), экспортируют функцию.
|
||||
|
||||
Импорт этого модуля с импортом в стиле ES6 в форме `import * as foo from "foo";` приводит к ошибке:
|
||||
|
||||
> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct
|
||||
|
||||
Эту ошибку можно устранить, объединив объявление функции с пустым namespace'ом с тем же именем, но это не рекомендуется.
|
||||
Это часто цитируемый [ответ с Stack Overflow](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) по этому вопросу.
|
||||
|
||||
Более целесообразно импортировать модуль, используя `import foo = require("foo");` синтаксис или использовать импорт по умолчанию, такой как `import foo from "foo";` при использовании флага `--allowSyntheticDefaultImports`, если среда выполнения вашего модуля поддерживает схему взаимодействия для модулей не-ECMAScript как таковых.
|
||||
|
||||
## Лицензия
|
||||
|
||||
Этот проект лицензирован по лицензии MIT.
|
||||
|
||||
Авторские права на файлы определений принадлежат каждому участнику, указанному в начале каждого файла определения.
|
||||
|
||||
[](https://github.com/igrigorik/ga-beacon)
|
||||
|
||||
[](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) В среднем пакеты публикуются на npm менее чем за 10000 секунд?
|
||||
|
||||
[](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Был ли typescript-bot активным на DefinitelyTyped в последние два часа?
|
||||
+194
-14
@@ -124,7 +124,7 @@
|
||||
"libraryName": "axe-core",
|
||||
"typingsPackageName": "axe-core",
|
||||
"sourceRepoURL": "https://github.com/dequelabs/axe-core",
|
||||
"asOfVersion": "2.0.7"
|
||||
"asOfVersion": "3.0.3"
|
||||
},
|
||||
{
|
||||
"libraryName": "axios",
|
||||
@@ -144,6 +144,12 @@
|
||||
"sourceRepoURL": "https://github.com/Azure/azure-mobile-apps-node/",
|
||||
"asOfVersion": "3.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "@babel/parser",
|
||||
"typingsPackageName": "babel__parser",
|
||||
"sourceRepoURL": "https://github.com/babel/babel",
|
||||
"asOfVersion": "7.1.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "BabylonJS",
|
||||
"typingsPackageName": "babylonjs",
|
||||
@@ -156,12 +162,6 @@
|
||||
"sourceRepoURL": "https://github.com/brianloveswords/base64url",
|
||||
"asOfVersion": "2.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "better-scroll",
|
||||
"typingsPackageName": "better-scroll",
|
||||
"sourceRepoURL": "https://github.com/ustbhuangyi/better-scroll",
|
||||
"asOfVersion": "1.5.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "BigInteger.js",
|
||||
"typingsPackageName": "big-integer",
|
||||
@@ -180,6 +180,12 @@
|
||||
"sourceRepoURL": "https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions",
|
||||
"asOfVersion": "2.0.15"
|
||||
},
|
||||
{
|
||||
"libraryName": "bitwise",
|
||||
"typingsPackageName": "bitwise",
|
||||
"sourceRepoURL": "https://github.com/dodekeract/bitwise",
|
||||
"asOfVersion": "2.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "botvs",
|
||||
"typingsPackageName": "botvs",
|
||||
@@ -396,6 +402,18 @@
|
||||
"sourceRepoURL": "https://github.com/MikeMcl/decimal.js",
|
||||
"asOfVersion": "7.4.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "deepmerge",
|
||||
"typingsPackageName": "deepmerge",
|
||||
"sourceRepoURL": "git@github.com:KyleAMathews/deepmerge.git",
|
||||
"asOfVersion": "2.2.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "delay",
|
||||
"typingsPackageName": "delay",
|
||||
"sourceRepoURL": "https://github.com/sindresorhus/delay",
|
||||
"asOfVersion": "3.1.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "DevExtreme",
|
||||
"typingsPackageName": "devextreme",
|
||||
@@ -528,6 +546,12 @@
|
||||
"sourceRepoURL": "https://github.com/code-chris/extended-listbox",
|
||||
"asOfVersion": "4.0.1"
|
||||
},
|
||||
{
|
||||
"libraryName": "fast-diff",
|
||||
"typingsPackageName": "fast-diff",
|
||||
"sourceRepoURL": "https://github.com/jhchen/fast-diff",
|
||||
"asOfVersion": "1.2.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "JSON-Patch",
|
||||
"typingsPackageName": "fast-json-patch",
|
||||
@@ -570,6 +594,12 @@
|
||||
"sourceRepoURL": "https://github.com/acdlite/flux-standard-action",
|
||||
"asOfVersion": "1.1.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "fork-ts-checker-webpack-plugin",
|
||||
"typingsPackageName": "fork-ts-checker-webpack-plugin",
|
||||
"sourceRepoURL": "https://github.com/Realytics/fork-ts-checker-webpack-plugin",
|
||||
"asOfVersion": "0.4.5"
|
||||
},
|
||||
{
|
||||
"libraryName": "Foundation Sites",
|
||||
"typingsPackageName": "foundation-sites",
|
||||
@@ -606,6 +636,18 @@
|
||||
"sourceRepoURL": "https://github.com/mikedeboer/node-github",
|
||||
"asOfVersion": "7.1.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "gitlab",
|
||||
"typingsPackageName": "gitlab",
|
||||
"sourceRepoURL": "https://github.com/jdalrymple/node-gitlab",
|
||||
"asOfVersion": "2.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "Google Cloud Storage",
|
||||
"typingsPackageName": "google-cloud__storage",
|
||||
"sourceRepoURL": "https://github.com/googleapis/nodejs-storage",
|
||||
"asOfVersion": "2.3.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "graphene-pk11",
|
||||
"typingsPackageName": "graphene-pk11",
|
||||
@@ -642,6 +684,12 @@
|
||||
"sourceRepoURL": "https://handsontable.com/",
|
||||
"asOfVersion": "0.35.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "hibp",
|
||||
"typingsPackageName": "hibp",
|
||||
"sourceRepoURL": "https://github.com/wKovacs64/hibp",
|
||||
"asOfVersion": "7.3.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "homeworks",
|
||||
"typingsPackageName": "homeworks",
|
||||
@@ -660,6 +708,12 @@
|
||||
"sourceRepoURL": "https://github.com/ashtuchkin/iconv-lite",
|
||||
"asOfVersion": "0.4.14"
|
||||
},
|
||||
{
|
||||
"libraryName": "ids",
|
||||
"typingsPackageName": "ids",
|
||||
"sourceRepoURL": "https://github.com/bpmn-io/ids",
|
||||
"asOfVersion": "0.2.2"
|
||||
},
|
||||
{
|
||||
"libraryName": "immutability-helper",
|
||||
"typingsPackageName": "immutability-helper",
|
||||
@@ -672,6 +726,12 @@
|
||||
"sourceRepoURL": "https://github.com/facebook/immutable-js",
|
||||
"asOfVersion": "3.8.7"
|
||||
},
|
||||
{
|
||||
"libraryName": "interactjs",
|
||||
"typingsPackageName": "interact.js",
|
||||
"sourceRepoURL": "https://github.com/taye/interact.js",
|
||||
"asOfVersion": "1.3.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "inversify",
|
||||
"typingsPackageName": "inversify",
|
||||
@@ -900,12 +960,24 @@
|
||||
"sourceRepoURL": "https://github.com/blakeembrey/lower-case-first",
|
||||
"asOfVersion": "1.0.1"
|
||||
},
|
||||
{
|
||||
"libraryName": "mali",
|
||||
"typingsPackageName": "mali",
|
||||
"sourceRepoURL": "https://github.com/malijs/mali",
|
||||
"asOfVersion": "0.9.2"
|
||||
},
|
||||
{
|
||||
"libraryName": "maquette",
|
||||
"typingsPackageName": "maquette",
|
||||
"sourceRepoURL": "http://maquettejs.org/",
|
||||
"asOfVersion": "2.1.6"
|
||||
},
|
||||
{
|
||||
"libraryName": "maxmind",
|
||||
"typingsPackageName": "maxmind",
|
||||
"sourceRepoURL": "https://github.com/runk/node-maxmind",
|
||||
"asOfVersion": "2.0.5"
|
||||
},
|
||||
{
|
||||
"libraryName": "mendixmodelsdk",
|
||||
"typingsPackageName": "mendixmodelsdk",
|
||||
@@ -942,6 +1014,12 @@
|
||||
"sourceRepoURL": "https://github.com/mweststrate/mobservable-react",
|
||||
"asOfVersion": "1.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "Mobx Cookie",
|
||||
"typingsPackageName": "mobx-cookie",
|
||||
"sourceRepoURL": "https://github.com/will-stone/mobx-cookie",
|
||||
"asOfVersion": "1.1.1"
|
||||
},
|
||||
{
|
||||
"libraryName": "Moment",
|
||||
"typingsPackageName": "moment",
|
||||
@@ -960,6 +1038,12 @@
|
||||
"sourceRepoURL": "https://github.com/mqttjs/MQTT.js",
|
||||
"asOfVersion": "2.5.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "nano",
|
||||
"typingsPackageName": "nano",
|
||||
"sourceRepoURL": "https://github.com/apache/couchdb-nano",
|
||||
"asOfVersion": "7.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "ng-table",
|
||||
"typingsPackageName": "ng-table",
|
||||
@@ -984,6 +1068,12 @@
|
||||
"sourceRepoURL": "https://github.com/paularmstrong/normalizr",
|
||||
"asOfVersion": "2.0.18"
|
||||
},
|
||||
{
|
||||
"libraryName": "Nuka Carousel",
|
||||
"typingsPackageName": "nuka-carousel",
|
||||
"sourceRepoURL": "https://github.com/FormidableLabs/nuka-carousel/",
|
||||
"asOfVersion": "4.4.6"
|
||||
},
|
||||
{
|
||||
"libraryName": "Numbro",
|
||||
"typingsPackageName": "numbro",
|
||||
@@ -1002,12 +1092,6 @@
|
||||
"sourceRepoURL": "https://github.com/blakeembrey/param-case",
|
||||
"asOfVersion": "1.1.2"
|
||||
},
|
||||
{
|
||||
"libraryName": "parse5",
|
||||
"typingsPackageName": "parse5",
|
||||
"sourceRepoURL": "https://github.com/inikulin/parse5",
|
||||
"asOfVersion": "3.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "pascal-case",
|
||||
"typingsPackageName": "pascal-case",
|
||||
@@ -1140,6 +1224,24 @@
|
||||
"sourceRepoURL": "https://github.com/gpbl/react-day-picker",
|
||||
"asOfVersion": "5.3.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-dnd",
|
||||
"typingsPackageName": "react-dnd",
|
||||
"sourceRepoURL": "https://github.com/react-dnd/react-dnd",
|
||||
"asOfVersion": "3.0.2"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-dnd-html5-backend",
|
||||
"typingsPackageName": "react-dnd-html5-backend",
|
||||
"sourceRepoURL": "https://github.com/react-dnd/react-dnd",
|
||||
"asOfVersion": "3.0.2"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-dnd-test-backend",
|
||||
"typingsPackageName": "react-dnd-test-backend",
|
||||
"sourceRepoURL": "https://github.com/react-dnd/react-dnd",
|
||||
"asOfVersion": "3.0.2"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-flip-move",
|
||||
"typingsPackageName": "react-flip-move",
|
||||
@@ -1152,6 +1254,18 @@
|
||||
"sourceRepoURL": "https://github.com/react-ga/react-ga",
|
||||
"asOfVersion": "2.3.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-i18next",
|
||||
"typingsPackageName": "react-i18next",
|
||||
"sourceRepoURL": "https://github.com/i18next/react-i18next",
|
||||
"asOfVersion": "8.1.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-monaco-editor",
|
||||
"typingsPackageName": "react-monaco-editor",
|
||||
"sourceRepoURL": "https://github.com/superRaytin/react-monaco-editor",
|
||||
"asOfVersion": "0.16.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-native-collapsible",
|
||||
"typingsPackageName": "react-native-collapsible",
|
||||
@@ -1176,18 +1290,36 @@
|
||||
"sourceRepoURL": "https://github.com/idehub/react-native-google-analytics-bridge",
|
||||
"asOfVersion": "5.3.3"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-native-linear-gradient",
|
||||
"typingsPackageName": "react-native-linear-gradient",
|
||||
"sourceRepoURL": "https://github.com/react-native-community/react-native-linear-gradient",
|
||||
"asOfVersion": "2.4.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-native-modal",
|
||||
"typingsPackageName": "react-native-modal",
|
||||
"sourceRepoURL": "https://github.com/react-native-community/react-native-modal",
|
||||
"asOfVersion": "4.1.1"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-native-navigation",
|
||||
"typingsPackageName": "react-native-navigation",
|
||||
"sourceRepoURL": "https://github.com/wix/react-native-navigation",
|
||||
"asOfVersion": "2.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-split-pane",
|
||||
"typingsPackageName": "react-split-pane",
|
||||
"sourceRepoURL": "https://github.com/tomkp/react-split-pane",
|
||||
"asOfVersion": "0.1.67"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-svg",
|
||||
"typingsPackageName": "react-svg",
|
||||
"sourceRepoURL": "https://github.com/tanem/react-svg",
|
||||
"asOfVersion": "5.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "realm",
|
||||
"typingsPackageName": "realm",
|
||||
@@ -1207,7 +1339,7 @@
|
||||
"asOfVersion": "0.1.5"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-bootstrap",
|
||||
"libraryName": "redux-bootstrap",
|
||||
"typingsPackageName": "redux-bootstrap",
|
||||
"sourceRepoURL": "https://github.com/remojansen/redux-bootstrap",
|
||||
"asOfVersion": "1.1.0"
|
||||
@@ -1218,6 +1350,12 @@
|
||||
"sourceRepoURL": "https://github.com/zalmoxisus/redux-devtools-extension",
|
||||
"asOfVersion": "2.13.2"
|
||||
},
|
||||
{
|
||||
"libraryName": "redux-little-router",
|
||||
"typingsPackageName": "redux-little-router",
|
||||
"sourceRepoURL": "https://github.com/FormidableLabs/redux-little-router",
|
||||
"asOfVersion": "15.1.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "redux-persist",
|
||||
"typingsPackageName": "redux-persist",
|
||||
@@ -1356,6 +1494,12 @@
|
||||
"sourceRepoURL": "https://github.com/zeh/simplesignal",
|
||||
"asOfVersion": "1.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "sip.js",
|
||||
"typingsPackageName": "sip.js",
|
||||
"sourceRepoURL": "https://github.com/onsip/SIP.js",
|
||||
"asOfVersion": "0.12.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "smooth-scrollbar",
|
||||
"typingsPackageName": "smooth-scrollbar",
|
||||
@@ -1386,6 +1530,12 @@
|
||||
"sourceRepoURL": "https://github.com/mozilla/source-map",
|
||||
"asOfVersion": "0.5.7"
|
||||
},
|
||||
{
|
||||
"libraryName": "Spectacle",
|
||||
"typingsPackageName": "spectacle",
|
||||
"sourceRepoURL": "http://github.com/FormidableLabs/spectacle/",
|
||||
"asOfVersion": "5.2.3"
|
||||
},
|
||||
{
|
||||
"libraryName": "Spin.js",
|
||||
"typingsPackageName": "spin.js",
|
||||
@@ -1482,6 +1632,12 @@
|
||||
"sourceRepoURL": "https://github.com/samchon/tstl",
|
||||
"asOfVersion": "1.5.7"
|
||||
},
|
||||
{
|
||||
"libraryName": "typed.js",
|
||||
"typingsPackageName": "typed.js",
|
||||
"sourceRepoURL": "https://github.com/mattboldt/typed.js",
|
||||
"asOfVersion": "2.0.9"
|
||||
},
|
||||
{
|
||||
"libraryName": "TypeScript",
|
||||
"typingsPackageName": "typescript",
|
||||
@@ -1506,6 +1662,12 @@
|
||||
"sourceRepoURL": "https://github.com/dpa99c/phonegap-launch-navigator",
|
||||
"asOfVersion": "4.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "Universal Router",
|
||||
"typingsPackageName": "universal-router",
|
||||
"sourceRepoURL": "https://github.com/kriasoft/universal-router",
|
||||
"asOfVersion": "8.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "upper-case",
|
||||
"typingsPackageName": "upper-case",
|
||||
@@ -1530,6 +1692,12 @@
|
||||
"sourceRepoURL": "https://github.com/ansman/validate.js",
|
||||
"asOfVersion": "0.11.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "vega",
|
||||
"typingsPackageName": "vega",
|
||||
"sourceRepoURL": "https://github.com/vega/vega",
|
||||
"asOfVersion": "3.2.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "vso-node-api",
|
||||
"typingsPackageName": "vso-node-api",
|
||||
@@ -1560,6 +1728,12 @@
|
||||
"sourceRepoURL": "https://github.com/tgdwyer/WebCola",
|
||||
"asOfVersion": "3.2.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "WebdriverIO",
|
||||
"typingsPackageName": "webdriverio",
|
||||
"sourceRepoURL": "git@github.com:webdriverio/webdriverio.git",
|
||||
"asOfVersion": "5.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "webgme",
|
||||
"typingsPackageName": "webgme",
|
||||
@@ -1572,6 +1746,12 @@
|
||||
"sourceRepoURL": "http://webix.com",
|
||||
"asOfVersion": "5.1.1"
|
||||
},
|
||||
{
|
||||
"libraryName": "winston",
|
||||
"typingsPackageName": "winston",
|
||||
"sourceRepoURL": "https://github.com/winstonjs/winston.git",
|
||||
"asOfVersion": "2.4.4"
|
||||
},
|
||||
{
|
||||
"libraryName": "wolfy87-eventemitter",
|
||||
"typingsPackageName": "wolfy87-eventemitter",
|
||||
|
||||
+26
-25
@@ -1,27 +1,28 @@
|
||||
{
|
||||
"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",
|
||||
"lint": "dtslint types"
|
||||
},
|
||||
"devDependencies": {
|
||||
"dtslint": "github:Microsoft/dtslint#production",
|
||||
"types-publisher": "Microsoft/types-publisher#production"
|
||||
}
|
||||
"private": true,
|
||||
"name": "definitely-typed",
|
||||
"version": "0.0.3",
|
||||
"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": "github:Microsoft/types-publisher#production"
|
||||
},
|
||||
"dependencies": {}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import drawTriangle = require("a-big-triangle");
|
||||
|
||||
const gl = new WebGLRenderingContext();
|
||||
|
||||
drawTriangle(gl); // $ExpectType void
|
||||
Vendored
+8
@@ -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;
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import A11yDialog = require('a11y-dialog');
|
||||
|
||||
const dialogEl = new A11yDialog(document.getElementById("test"));
|
||||
const dialogElTwo = new A11yDialog(document.getElementById("test"), document.getElementById("testContainer"));
|
||||
const dialogElThree = new A11yDialog(document.getElementById("test"), "dummy-element");
|
||||
|
||||
dialogEl.show();
|
||||
dialogEl.hide();
|
||||
dialogElTwo.destroy();
|
||||
dialogElThree.create();
|
||||
|
||||
// Test out interfaces that extends Element.
|
||||
dialogEl.on("show", (el: HTMLElement) => {
|
||||
el.textContent;
|
||||
});
|
||||
|
||||
// Test out element and event.
|
||||
dialogEl.on("create", (el: HTMLElement, evt) => {
|
||||
el.textContent;
|
||||
|
||||
evt.target;
|
||||
});
|
||||
|
||||
dialogEl.on('hide', () => {
|
||||
const t = 5;
|
||||
});
|
||||
|
||||
dialogEl.off("show", (el: HTMLElement) => {
|
||||
el.textContent;
|
||||
});
|
||||
Vendored
+31
@@ -0,0 +1,31 @@
|
||||
// Type definitions for a11y-dialog 5.2
|
||||
// Project: https://github.com/edenspiekermann/a11y-dialog
|
||||
// Definitions by: Yuto <https://github.com/Goyatuzo>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.8
|
||||
|
||||
type DialogEvents = "show" | "hide" | "destroy" | "create";
|
||||
declare class A11yDialog {
|
||||
constructor(el: Element | null, containers?: NodeList | Element | string | null);
|
||||
/**
|
||||
* Shows the dialog.
|
||||
*/
|
||||
show(): void;
|
||||
/**
|
||||
* Hides the dialog.
|
||||
*/
|
||||
hide(): void;
|
||||
/**
|
||||
* Unbind click listeners from dialog openers and closers and remove all bound custom event listeners registered with `.on()`
|
||||
*/
|
||||
destroy(): void;
|
||||
/**
|
||||
* Bind click listeners to dialog openers and closers.
|
||||
*/
|
||||
create(el?: Element | null, containers?: NodeList | Element | string | null): void;
|
||||
|
||||
on(evt: DialogEvents, callback: (dialogElement: any, event: Event) => void): void;
|
||||
off(evt: DialogEvents, callback: (dialogElement: any, event: Event) => void): void;
|
||||
}
|
||||
|
||||
export = A11yDialog;
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es6",
|
||||
"dom"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true,
|
||||
"baseUrl": "../",
|
||||
"typeRoots": [
|
||||
"../"
|
||||
],
|
||||
"types": [],
|
||||
"noEmit": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"jsx": "react"
|
||||
},
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"a11y-dialog-tests.ts"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { AbstractLevelDOWN } from 'abstract-leveldown';
|
||||
|
||||
const test = (levelDown: AbstractLevelDOWN<any, string>) => {
|
||||
levelDown.put("key", "value", (err?) => { });
|
||||
levelDown.put(1, "value", { something: true }, (err?) => { });
|
||||
|
||||
levelDown.get("key", (err?) => { });
|
||||
levelDown.get(1, { something: true }, (err?) => { });
|
||||
};
|
||||
// $ExpectType void
|
||||
test(new AbstractLevelDOWN('here'));
|
||||
// $ExpectType void
|
||||
test(AbstractLevelDOWN('there'));
|
||||
// $ExpectType void
|
||||
test(new AbstractLevelDOWN<any, string>('here'));
|
||||
// $ExpectType void
|
||||
test(AbstractLevelDOWN<any, string>('there'));
|
||||
Vendored
+114
@@ -0,0 +1,114 @@
|
||||
// Type definitions for abstract-leveldown 5.0
|
||||
// Project: https://github.com/Level/abstract-leveldown
|
||||
// Definitions by: Meirion Hughes <https://github.com/MeirionHughes>
|
||||
// Daniel Byrne <https://github.com/danwbyrne>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.3
|
||||
|
||||
export interface AbstractOptions {
|
||||
readonly [k: string]: any;
|
||||
}
|
||||
|
||||
export type ErrorCallback = (err: Error | undefined) => void;
|
||||
export type ErrorValueCallback<V> = (err: Error | undefined, value: V) => void;
|
||||
export type ErrorKeyValueCallback<K, V> = (err: Error | undefined, key: K, value: V) => void;
|
||||
|
||||
export interface AbstractOpenOptions extends AbstractOptions {
|
||||
createIfMissing?: boolean;
|
||||
errorIfExists?: boolean;
|
||||
}
|
||||
|
||||
export interface AbstractGetOptions extends AbstractOptions {
|
||||
asBuffer?: boolean;
|
||||
}
|
||||
|
||||
export interface AbstractLevelDOWN<K = any, V = any> extends AbstractOptions {
|
||||
open(cb: ErrorCallback): void;
|
||||
open(options: AbstractOpenOptions, cb: ErrorCallback): void;
|
||||
|
||||
close(cb: ErrorCallback): void;
|
||||
|
||||
get(key: K, cb: ErrorValueCallback<V>): void;
|
||||
get(key: K, options: AbstractGetOptions, cb: ErrorValueCallback<V>): void;
|
||||
|
||||
put(key: K, value: V, cb: ErrorCallback): void;
|
||||
put(key: K, value: V, options: AbstractOptions, cb: ErrorCallback): void;
|
||||
|
||||
del(key: K, cb: ErrorCallback): void;
|
||||
del(key: K, options: AbstractOptions, cb: ErrorCallback): void;
|
||||
|
||||
batch(): AbstractChainedBatch<K, V>;
|
||||
batch(array: ReadonlyArray<AbstractBatch<K, V>>, cb: ErrorCallback): AbstractChainedBatch<K, V>;
|
||||
batch(
|
||||
array: ReadonlyArray<AbstractBatch<K, V>>,
|
||||
options: AbstractOptions,
|
||||
cb: ErrorCallback,
|
||||
): AbstractChainedBatch<K, V>;
|
||||
|
||||
iterator(options?: AbstractIteratorOptions<K>): AbstractIterator<K, V>;
|
||||
}
|
||||
|
||||
export interface AbstractLevelDOWNConstructor {
|
||||
// tslint:disable-next-line no-unnecessary-generics
|
||||
new <K = any, V = any>(location: string): AbstractLevelDOWN<K, V>;
|
||||
// tslint:disable-next-line no-unnecessary-generics
|
||||
<K = any, V = any>(location: string): AbstractLevelDOWN<K, V>;
|
||||
}
|
||||
|
||||
export interface AbstractIteratorOptions<K = any> extends AbstractOptions {
|
||||
gt?: K;
|
||||
gte?: K;
|
||||
lt?: K;
|
||||
lte?: K;
|
||||
reverse?: boolean;
|
||||
limit?: number;
|
||||
keys?: boolean;
|
||||
values?: boolean;
|
||||
keyAsBuffer?: boolean;
|
||||
valueAsBuffer?: boolean;
|
||||
}
|
||||
|
||||
export type AbstractBatch<K = any, V = any> = PutBatch<K, V> | DelBatch<K, V>;
|
||||
|
||||
export interface PutBatch<K = any, V = any> {
|
||||
readonly type: 'put';
|
||||
readonly key: K;
|
||||
readonly value: V;
|
||||
}
|
||||
|
||||
export interface DelBatch<K = any, V = any> {
|
||||
readonly type: 'del';
|
||||
readonly key: K;
|
||||
}
|
||||
|
||||
export interface AbstractChainedBatch<K = any, V = any> extends AbstractOptions {
|
||||
put: (key: K, value: V) => this;
|
||||
del: (key: K) => this;
|
||||
clear: () => this;
|
||||
write(cb: ErrorCallback): any;
|
||||
write(options: any, cb: ErrorCallback): any;
|
||||
}
|
||||
|
||||
export interface AbstractChainedBatchConstructor {
|
||||
// tslint:disable-next-line no-unnecessary-generics
|
||||
new <K = any, V = any>(db: any): AbstractChainedBatch<K, V>;
|
||||
// tslint:disable-next-line no-unnecessary-generics
|
||||
<K = any, V = any>(db: any): AbstractChainedBatch<K, V>;
|
||||
}
|
||||
|
||||
export interface AbstractIterator<K, V> extends AbstractOptions {
|
||||
db: AbstractLevelDOWN<K, V>;
|
||||
next(cb: ErrorKeyValueCallback<K, V>): this;
|
||||
end(cb: ErrorCallback): void;
|
||||
}
|
||||
|
||||
export interface AbstractIteratorConstructor {
|
||||
// tslint:disable-next-line no-unnecessary-generics
|
||||
new <K = any, V = any>(db: any): AbstractIterator<K, V>;
|
||||
// tslint:disable-next-line no-unnecessary-generics
|
||||
<K = any, V = any>(db: any): AbstractIterator<K, V>;
|
||||
}
|
||||
|
||||
export const AbstractLevelDOWN: AbstractLevelDOWNConstructor;
|
||||
export const AbstractIterator: AbstractIteratorConstructor;
|
||||
export const AbstractChainedBatch: AbstractChainedBatchConstructor;
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es6"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true,
|
||||
"baseUrl": "../",
|
||||
"typeRoots": [
|
||||
"../"
|
||||
],
|
||||
"types": [],
|
||||
"noEmit": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"abstract-leveldown-tests.ts"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "dtslint/dt.json"
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// https://github.com/opentable/accept-language-parser/blob/v1.4.1/index.js
|
||||
// https://github.com/opentable/accept-language-parser/blob/v1.5.0/index.js
|
||||
|
||||
import * as AcceptLanguageParser from 'accept-language-parser';
|
||||
|
||||
@@ -20,6 +20,18 @@ const l3: AcceptLanguageParser.Language = {
|
||||
quality: 0.9
|
||||
};
|
||||
|
||||
type Lang = "en-US" | "ko-KR";
|
||||
const enUs: Lang = "en-US";
|
||||
const koKr: Lang = "ko-KR";
|
||||
|
||||
const parsed1: AcceptLanguageParser.Language[] = AcceptLanguageParser.parse('');
|
||||
const pick1: string | null = AcceptLanguageParser.pick([''], '');
|
||||
const pick2: string | null = AcceptLanguageParser.pick([''], [l1, l2, l3]);
|
||||
const pick3: string | null = AcceptLanguageParser.pick([''], '', {});
|
||||
const pick4: string | null = AcceptLanguageParser.pick([''], '', { loose: true });
|
||||
const pick5: Lang | null = AcceptLanguageParser.pick<Lang>([enUs, koKr], [l1, l2, l3]);
|
||||
const pick6: Lang | null = AcceptLanguageParser.pick([enUs, koKr], [l1, l2, l3]);
|
||||
|
||||
const pickOptions: AcceptLanguageParser.PickOptions = {
|
||||
loose: true
|
||||
};
|
||||
|
||||
+12
-3
@@ -1,13 +1,18 @@
|
||||
// Type definitions for accept-language-parser 1.4
|
||||
// Type definitions for accept-language-parser 1.5
|
||||
// Project: https://github.com/opentable/accept-language-parser
|
||||
// Definitions by: Niklas Wulf <https://github.com/kampfgnom>
|
||||
// Wooram Jun <https://github.com/chatoo2412>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.1
|
||||
|
||||
// https://github.com/opentable/accept-language-parser/blob/v1.4.1/index.js
|
||||
// https://github.com/opentable/accept-language-parser/blob/v1.5.0/index.js
|
||||
|
||||
export function parse(acceptLanguage: string): Language[];
|
||||
export function pick(supportedLanguages: string[], acceptLanguage: string | Language[]): string | null;
|
||||
export function pick<T extends string>(
|
||||
supportedLanguages: T[],
|
||||
acceptLanguage: string | Language[],
|
||||
options?: PickOptions
|
||||
): T | null;
|
||||
|
||||
export interface Language {
|
||||
code: string;
|
||||
@@ -15,3 +20,7 @@ export interface Language {
|
||||
region?: string;
|
||||
quality: number;
|
||||
}
|
||||
|
||||
export interface PickOptions {
|
||||
loose?: boolean;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import * as accept from 'accept';
|
||||
|
||||
accept.charsets("iso-8859-5, unicode-1-1;q=0.8"); // charset === "iso-8859-5"
|
||||
accept.charset("iso-8859-5, unicode-1-1;q=0.8", ["unicode-1-1"]); // charset === "unicode-1-1"
|
||||
|
||||
accept.encoding("gzip, deflate, sdch"); // encoding === "gzip"
|
||||
accept.encoding("gzip, deflate, sdch", ["deflate", "identity"]);
|
||||
|
||||
const encodings = accept.encodings("compress;q=0.5, gzip;q=1.0"); // encodings === ["gzip", "compress", "identity"]
|
||||
encodings.lastIndexOf('');
|
||||
|
||||
accept.language("en;q=0.7, en-GB;q=0.8");
|
||||
accept.language("en;q=0.7, en-GB;q=0.8", ["en-gb"]); // language === "en-GB"
|
||||
const languages = accept.languages("da, en;q=0.7, en-GB;q=0.8"); // languages === ["da", "en-GB", "en"]
|
||||
languages.lastIndexOf('');
|
||||
|
||||
accept.mediaType("text/plain, application/json;q=0.5, text/html, */*;q=0.1");
|
||||
accept.mediaType("text/plain, application/json;q=0.5, text/html, */*;q=0.1", ["application/json", "text/html"]);
|
||||
const mediaTypes = accept.mediaTypes("text/plain, application/json;q=0.5, text/html, */*;q=0.1");
|
||||
// mediaTypes === ["text/plain", "text/html", "application/json", "*/*"]
|
||||
mediaTypes.lastIndexOf('');
|
||||
const headers = {
|
||||
accept: 'text/plain, application/json;q=0.5, text/html, */*;q=0.1',
|
||||
'accept-language': 'da, en;q=0.7, en-GB;q=0.8'
|
||||
};
|
||||
|
||||
const all = accept.parseAll(headers);
|
||||
all.charsets.length;
|
||||
all.encodings.length;
|
||||
all.languages.length;
|
||||
all.mediaTypes.length;
|
||||
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
// Type definitions for accept 3.1
|
||||
// Project: https://github.com/hapijs/accept#readme
|
||||
// Definitions by: feinoujc <https://github.com/feinoujc>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.1
|
||||
|
||||
export function charset(charsetHeader?: string, preferences?: string[]): string;
|
||||
export function charsets(charsetHeader?: string): string[];
|
||||
export function encoding(encodingHeader?: string, preferences?: string[]): string;
|
||||
export function encodings(encodingHeader?: string): string[];
|
||||
export function language(languageHeader?: string, preferences?: string[]): string;
|
||||
export function languages(languageHeader?: string): string[];
|
||||
export function mediaType(mediaTypeHeader?: string, preferences?: string[]): string;
|
||||
export function mediaTypes(mediaTypeHeader?: string): string[];
|
||||
export function parseAll(
|
||||
headers: Record<string, string | string[] | undefined>
|
||||
): {
|
||||
charsets: string[];
|
||||
encodings: string[];
|
||||
languages: string[];
|
||||
mediaTypes: string[];
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es6"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true,
|
||||
"baseUrl": "../",
|
||||
"typeRoots": [
|
||||
"../"
|
||||
],
|
||||
"types": [],
|
||||
"noEmit": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"accept-tests.ts"
|
||||
]
|
||||
}
|
||||
@@ -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
|
||||
Vendored
+52
@@ -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;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
Vendored
+70
-25
@@ -101,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
|
||||
////////////////
|
||||
@@ -495,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;
|
||||
|
||||
@@ -526,6 +549,16 @@ declare namespace AceAjax {
|
||||
getFoldsInRange(range: Range): any;
|
||||
|
||||
highlight(text: string): void;
|
||||
|
||||
|
||||
/**
|
||||
* Highlight lines from `startRow` to `EndRow`.
|
||||
* @param startRow Define the start line of the highlight
|
||||
* @param endRow Define the end line of the highlight
|
||||
* @param clazz Set the CSS class for the marker
|
||||
* @param inFront Set to `true` to establish a front marker
|
||||
**/
|
||||
highlightLines(startRow:number, endRow: number, clazz: string, inFront: boolean): Range;
|
||||
|
||||
/**
|
||||
* Sets the `EditSession` to point to a new `Document`. If a `BackgroundTokenizer` exists, it also points to `doc`.
|
||||
@@ -809,8 +842,9 @@ declare namespace AceAjax {
|
||||
|
||||
/**
|
||||
* [Sets the value of the distance between the left of the editor and the leftmost part of the visible content.]{: #EditSession.setScrollLeft}
|
||||
* @param scrollLeft The new scroll left value
|
||||
**/
|
||||
setScrollLeft(): void;
|
||||
setScrollLeft(scrollLeft: number): void;
|
||||
|
||||
/**
|
||||
* [Returns the value of the distance between the left of the editor and the leftmost part of the visible content.]{: #EditSession.getScrollLeft}
|
||||
@@ -1074,7 +1108,7 @@ 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;
|
||||
|
||||
@@ -1113,26 +1147,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
|
||||
**/
|
||||
@@ -1219,7 +1233,7 @@ declare namespace AceAjax {
|
||||
/**
|
||||
* Returns `true` if the current `textInput` is in focus.
|
||||
**/
|
||||
isFocused(): void;
|
||||
isFocused(): boolean;
|
||||
|
||||
/**
|
||||
* Blurs the current `textInput`.
|
||||
@@ -2692,7 +2706,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;
|
||||
|
||||
@@ -3036,6 +3050,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;
|
||||
|
||||
@@ -18,6 +18,23 @@ function createFoldTestSession() {
|
||||
return session;
|
||||
}
|
||||
|
||||
function createScrollTestRenderer(): AceAjax.VirtualRenderer | null {
|
||||
var el = document.createElement("div");
|
||||
|
||||
if (!el.getBoundingClientRect) {
|
||||
console.log("Skipping test: This test only runs in the browser");
|
||||
return null;
|
||||
}
|
||||
|
||||
el.style.left = "20px";
|
||||
el.style.top = "30px";
|
||||
el.style.width = "300px";
|
||||
el.style.height = "100px";
|
||||
document.body.appendChild(el);
|
||||
|
||||
return new AceAjax.VirtualRenderer(el);
|
||||
}
|
||||
|
||||
function assertArray(a, b) {
|
||||
assert.equal(a + "", b + "");
|
||||
assert.ok(a.length == b.length);
|
||||
@@ -915,5 +932,25 @@ const aceEditSessionTests = {
|
||||
session = new AceAjax.EditSession(new Array(30).join("\n"));
|
||||
session.documentToScreenPosition(2, 0);
|
||||
session.documentToScreenPosition(2, 0);
|
||||
},
|
||||
|
||||
"test setScrollTop()": function() {
|
||||
var renderer = createScrollTestRenderer();
|
||||
var session = new AceAjax.EditSession(["1", "2", "3", "2", "3", "4"]);
|
||||
renderer.setSession(session);
|
||||
assert.equal(renderer.getScrollTop(), 0);
|
||||
session.setScrollTop(40);
|
||||
assert.equal(renderer.getScrollTop(), 40);
|
||||
renderer.getScrollTop()
|
||||
},
|
||||
|
||||
"test setScrollLeft()": function() {
|
||||
var renderer = createScrollTestRenderer();
|
||||
var session = new AceAjax.EditSession(["1", "2", "3", "2", "3", "4"]);
|
||||
renderer.setSession(session);
|
||||
assert.equal(renderer.getScrollLeft(), 0);
|
||||
session.setScrollLeft(40);
|
||||
assert.equal(renderer.getScrollLeft(), 40);
|
||||
renderer.getScrollLeft()
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
@@ -123,7 +123,7 @@ const aceSelectionTests = {
|
||||
},
|
||||
|
||||
"test: moveCursor word left with umlauts": function () {
|
||||
var session = new AceAjax.EditSession(" Fu� F��e");
|
||||
var session = new AceAjax.EditSession(" Fu¢ F¢¢e");
|
||||
|
||||
var selection = session.getSelection();
|
||||
selection.moveCursorTo(0, 9)
|
||||
|
||||
Vendored
+1
-2
@@ -2,9 +2,8 @@
|
||||
// Project: https://github.com/optimalbits/node_acl
|
||||
// Definitions by: Qubo <https://github.com/tkQubo>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.3
|
||||
// TypeScript Version: 2.8
|
||||
|
||||
/// <reference types="bluebird" />
|
||||
/// <reference types="node"/>
|
||||
/// <reference types="express"/>
|
||||
|
||||
|
||||
Vendored
+1
-3
@@ -246,9 +246,7 @@ declare namespace acorn {
|
||||
let LooseParser: ILooseParserClass | undefined;
|
||||
let pluginsLoose: PluginsObject | undefined;
|
||||
|
||||
interface ILooseParserClass {
|
||||
new (input: string, options?: Options): ILooseParser;
|
||||
}
|
||||
type ILooseParserClass = new (input: string, options?: Options) => ILooseParser;
|
||||
|
||||
interface ILooseParser {}
|
||||
|
||||
|
||||
Vendored
+10
-4
@@ -1,13 +1,15 @@
|
||||
// Type definitions for ActionCable
|
||||
// Project: https://github.com/rails/rails/tree/master/actioncable
|
||||
// Type definitions for ActionCable 5.2
|
||||
// Project: https://github.com/rails/rails/tree/master/actioncable/app/assets/javascripts
|
||||
// Definitions by: Vincent Zhu <https://github.com/zhu1230>
|
||||
// Jared Szechy <https://github.com/szechyjs>
|
||||
// Definitions: https://github.com/zhu1230/DefinitelyTyped
|
||||
// TypeScript Version: 2.3
|
||||
|
||||
declare module ActionCable {
|
||||
interface Channel {
|
||||
unsubscribe(): void;
|
||||
perform(action: string, data: {}): void;
|
||||
send(data: Object): boolean;
|
||||
send(data: any): boolean;
|
||||
}
|
||||
|
||||
interface Subscriptions {
|
||||
@@ -16,12 +18,16 @@ declare module ActionCable {
|
||||
|
||||
interface Cable {
|
||||
subscriptions: Subscriptions;
|
||||
send(data: any): void;
|
||||
connect(): void;
|
||||
disconnect(): void;
|
||||
ensureActiveConnection(): void;
|
||||
}
|
||||
|
||||
interface CreateMixin {
|
||||
connected(): void;
|
||||
disconnected(): void;
|
||||
received(obj: Object): void;
|
||||
received(obj: any): void;
|
||||
[key: string]: Function;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import activeWin = require('active-win');
|
||||
|
||||
// $ExpectType Promise<Result>
|
||||
activeWin();
|
||||
// $ExpectType Result
|
||||
activeWin.sync();
|
||||
|
||||
let win = {
|
||||
title: 'Unicorns - Google Search',
|
||||
id: 5762,
|
||||
owner: {
|
||||
name: 'Google Chrome',
|
||||
processId: 310,
|
||||
},
|
||||
};
|
||||
|
||||
win = activeWin.sync();
|
||||
Vendored
+30
@@ -0,0 +1,30 @@
|
||||
// Type definitions for active-win 4.0
|
||||
// Project: https://github.com/sindresorhus/active-win#readme
|
||||
// Definitions by: BendingBender <https://github.com/BendingBender>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
|
||||
export = activeWin;
|
||||
|
||||
declare function activeWin(): Promise<activeWin.Result>;
|
||||
|
||||
declare namespace activeWin {
|
||||
function sync(): Result;
|
||||
|
||||
interface Result {
|
||||
title: string;
|
||||
id: number;
|
||||
bounds?: {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
owner: {
|
||||
name: string;
|
||||
processId: number;
|
||||
bundleId?: number;
|
||||
path?: string;
|
||||
};
|
||||
memoryUsage?: number;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es6"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true,
|
||||
"baseUrl": "../",
|
||||
"typeRoots": [
|
||||
"../"
|
||||
],
|
||||
"types": [],
|
||||
"noEmit": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"active-win-tests.ts"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import ActiveDirectory = require("activedirectory2");
|
||||
|
||||
const ad = new ActiveDirectory({
|
||||
url: 'ldap://192.168.199.10',
|
||||
baseDN: 'OU=MyUsers,DC=mydomain,DC=com',
|
||||
username: 'service-user@mydomain.com',
|
||||
password: 'xxxxx000pw'
|
||||
});
|
||||
|
||||
ad.authenticate("test@mydomain.com", "yyyy111pw", (err, authed) => {
|
||||
console.log("hello");
|
||||
console.log(err);
|
||||
console.log(authed);
|
||||
});
|
||||
Vendored
+151
@@ -0,0 +1,151 @@
|
||||
// Type definitions for activedirectory2 1.2
|
||||
// Project: https://github.com/jsumners/node-activedirectory#readme
|
||||
// Definitions by: pas <https://github.com/pasthelod>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.5
|
||||
|
||||
import { Filter } from "ldapjs";
|
||||
|
||||
interface ADProperties {
|
||||
url: string;
|
||||
baseDN: string;
|
||||
username: string;
|
||||
password: string;
|
||||
pageSize?: 1000;
|
||||
entryParser?: (entry: object, raw: string, cb: (entry: object) => void) => void;
|
||||
referrals?: {
|
||||
enabled: false,
|
||||
exclude: [
|
||||
'ldaps?://ForestDnsZones\\..*/.*',
|
||||
'ldaps?://DomainDnsZones\\..*/.*',
|
||||
'ldaps?://.*/CN=Configuration,.*'
|
||||
]
|
||||
};
|
||||
attributes?: {
|
||||
user: [
|
||||
'dn', 'distinguishedName',
|
||||
'userPrincipalName', 'sAMAccountName', 'mail',
|
||||
'lockoutTime', 'whenCreated', 'pwdLastSet', 'userAccountControl',
|
||||
'employeeID', 'sn', 'givenName', 'initials', 'cn', 'displayName',
|
||||
'comment', 'description'
|
||||
],
|
||||
group: [
|
||||
'dn', 'cn', 'description', 'distinguishedName', 'objectCategory'
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
interface LDAPjsReqProps {
|
||||
url: string;
|
||||
tlsOptions: {
|
||||
host?: string;
|
||||
key?: string;
|
||||
cert?: string;
|
||||
ca?: string;
|
||||
rejectUnauthorized: boolean;
|
||||
};
|
||||
socketPath?: string;
|
||||
log?: any;
|
||||
timeout?: number;
|
||||
idleTimeout?: number;
|
||||
connectionTimeout?: number;
|
||||
strictDN?: boolean;
|
||||
}
|
||||
|
||||
type MembershipType = 'all'|'user'|'group';
|
||||
|
||||
interface ReqProps extends LDAPjsReqProps {
|
||||
baseDN?: string;
|
||||
bindDN?: string;
|
||||
bindCredentials?: string;
|
||||
scope?: 'base' | 'one' | 'sub';
|
||||
filter: string | Filter;
|
||||
attributes: AttributeSpec;
|
||||
sizeLimit: 0;
|
||||
timeLimit: 10;
|
||||
includeMembership: MembershipType[];
|
||||
}
|
||||
|
||||
interface AttributeSpec {
|
||||
user: UserAttributes[];
|
||||
group: GroupAttributes[];
|
||||
}
|
||||
|
||||
type GroupAttributes =
|
||||
| 'distinguishedName'
|
||||
| 'objectCategory'
|
||||
| 'cn'
|
||||
| 'description';
|
||||
|
||||
type UserAttributes =
|
||||
| 'distinguishedName'
|
||||
| 'userPrincipalName'
|
||||
| 'sAMAccountName'
|
||||
| 'mail'
|
||||
| 'lockoutTime'
|
||||
| 'whenCreated'
|
||||
| 'pwdLastSet'
|
||||
| 'userAccountControl'
|
||||
| 'employeeID'
|
||||
| 'sn'
|
||||
| 'givenName'
|
||||
| 'initials'
|
||||
| 'cn'
|
||||
| 'displayName'
|
||||
| 'comment'
|
||||
| 'description';
|
||||
|
||||
interface FindResult {
|
||||
groups: object[];
|
||||
users: object[];
|
||||
other: object[];
|
||||
}
|
||||
|
||||
declare class ActiveDirectory {
|
||||
constructor(props: ADProperties);
|
||||
authenticate(
|
||||
username: string,
|
||||
password: string,
|
||||
callback: (err: string, authenticated: boolean) => void
|
||||
): void;
|
||||
isUserMemberOf(
|
||||
opts: ReqProps,
|
||||
username: string,
|
||||
groupName: string,
|
||||
callback: (err: object, res: boolean) => void
|
||||
): void;
|
||||
find(
|
||||
opts: string | ReqProps,
|
||||
callback: (err: object, results: FindResult) => void
|
||||
): void;
|
||||
findDeletedObjects(
|
||||
opts: string | ReqProps,
|
||||
callback: (err: object, results: object[]) => void
|
||||
): void;
|
||||
findUser(
|
||||
opts: string | ReqProps,
|
||||
username: string,
|
||||
callback: (err: object, user: object) => void
|
||||
): void;
|
||||
findUsers(
|
||||
opts: string | ReqProps,
|
||||
callback: (err: object, users: object[]) => void
|
||||
): void;
|
||||
findGroup(
|
||||
opts: string | ReqProps,
|
||||
groupName: string,
|
||||
callback: (err: object, group: object) => void
|
||||
): void;
|
||||
findGroups(
|
||||
opts: string | ReqProps,
|
||||
groupName: string,
|
||||
callback: (err: object, groups: object[]) => void
|
||||
): void;
|
||||
getRootDSE(
|
||||
url: string,
|
||||
attributes: string[],
|
||||
callback: (err: object, result: object) => void
|
||||
): void;
|
||||
}
|
||||
|
||||
export = ActiveDirectory;
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"activedirectory2-tests.ts"
|
||||
],
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es6",
|
||||
"es2015.iterable"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true,
|
||||
"baseUrl": "../",
|
||||
"typeRoots": [
|
||||
"../"
|
||||
],
|
||||
"types": [],
|
||||
"noEmit": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import * as ActiveStorage from 'activestorage';
|
||||
|
||||
ActiveStorage.start();
|
||||
|
||||
const delegate: ActiveStorage.DirectUploadDelegate = {
|
||||
directUploadWillCreateBlobWithXHR(xhr) {
|
||||
console.log(xhr.status);
|
||||
},
|
||||
|
||||
directUploadWillStoreFileWithXHR(xhr) {
|
||||
console.log(xhr.status);
|
||||
},
|
||||
};
|
||||
|
||||
const d = new ActiveStorage.DirectUpload(
|
||||
new File([], 'blank.txt'),
|
||||
'/rails/active_storage/direct_uploads',
|
||||
delegate
|
||||
);
|
||||
|
||||
d.create((error, blob) => {
|
||||
if (error) {
|
||||
console.log(error.message);
|
||||
} else {
|
||||
const { byte_size, checksum, content_type, filename, signed_id } = blob;
|
||||
console.log({ byte_size, checksum, content_type, filename, signed_id });
|
||||
}
|
||||
});
|
||||
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
// Type definitions for ActiveStorage 5.2
|
||||
// Project: https://github.com/rails/rails/tree/master/activestorage/app/javascipt
|
||||
// Definitions by: Cameron Bothner <https://github.com/cbothner>
|
||||
// Definitions: https://github.com/cbothner/DefinitelyTyped
|
||||
// TypeScript Version: 2.1
|
||||
|
||||
export as namespace ActiveStorage
|
||||
|
||||
export function start(): void;
|
||||
|
||||
export class DirectUpload {
|
||||
id: number;
|
||||
file: File;
|
||||
url: string;
|
||||
|
||||
constructor(file: File, url: string, delegate: DirectUploadDelegate)
|
||||
|
||||
create(callback: (error: Error, blob: Blob) => void): void;
|
||||
}
|
||||
|
||||
export interface DirectUploadDelegate {
|
||||
directUploadWillCreateBlobWithXHR?: (xhr: XMLHttpRequest) => void;
|
||||
|
||||
directUploadWillStoreFileWithXHR?: (xhr: XMLHttpRequest) => void;
|
||||
}
|
||||
|
||||
export interface Blob {
|
||||
byte_size: number;
|
||||
checksum: string;
|
||||
content_type: string;
|
||||
filename: string;
|
||||
signed_id: string;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": ["es6", "dom"],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true,
|
||||
"baseUrl": "../",
|
||||
"typeRoots": ["../"],
|
||||
"types": [],
|
||||
"noEmit": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"files": ["index.d.ts", "activestorage-tests.ts"]
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
/// <reference types="windows-script-host" />
|
||||
|
||||
let app = new ActiveXObject('Access.Application');
|
||||
app.UserControl = true;
|
||||
|
||||
@@ -6,7 +8,7 @@ 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.Item('MyForm').Controls.Item('MyTextBox') as Access.TextBox;
|
||||
let textbox = app.Forms('MyForm').Controls('MyTextBox') as Access.TextBox;
|
||||
textbox.Text = 'Not Smith';
|
||||
|
||||
// save the current record on the active form
|
||||
|
||||
Vendored
+794
-1507
File diff suppressed because it is too large
Load Diff
@@ -2,8 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es5",
|
||||
"scripthost"
|
||||
"es5"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"extends": "dtslint/dt.json",
|
||||
"rules": {
|
||||
"no-const-enum": false
|
||||
"no-const-enum": false,
|
||||
"max-line-length": false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
// 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);
|
||||
@@ -12,9 +15,9 @@ const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
|
||||
};
|
||||
|
||||
const toSafeArray = <T>(...items: T[]): SafeArray<T> => {
|
||||
const dict = new ActiveXObject('Scripting.Dictionary');
|
||||
const dict: Scripting.Dictionary<number, T> = new ActiveXObject('Scripting.Dictionary');
|
||||
items.forEach((x, index) => dict.Add(index, x));
|
||||
return dict.Items() as SafeArray<T>;
|
||||
return dict.Items();
|
||||
};
|
||||
|
||||
const toConnectionString = (o: { [index: string]: any }) => {
|
||||
|
||||
Vendored
+2
-1
@@ -4,6 +4,8 @@
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.6
|
||||
|
||||
/// <reference types="activex-interop" />
|
||||
|
||||
declare namespace ADODB {
|
||||
const enum ADCPROP_ASYNCTHREADPRIORITY_ENUM {
|
||||
adPriorityAboveNormal = 4,
|
||||
@@ -1094,7 +1096,6 @@ declare namespace ADODB {
|
||||
}
|
||||
|
||||
interface ActiveXObject {
|
||||
new<K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
|
||||
on(obj: ADODB.Connection, event: 'BeginTransComplete', argNames: ['TransactionLevel', 'pError', 'adStatus', 'pConnection'], handler: (this: ADODB.Connection, parameter: {readonly TransactionLevel: number, readonly pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, readonly pConnection: ADODB.Connection}) => void): void;
|
||||
on(obj: ADODB.Connection, event: 'CommitTransComplete' | 'ConnectComplete' | 'InfoMessage' | 'RollbackTransComplete', argNames: ['pError', 'adStatus', 'pConnection'], handler: (this: ADODB.Connection, parameter: {readonly pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, readonly pConnection: ADODB.Connection}) => void): void;
|
||||
on(obj: ADODB.Connection, event: 'Disconnect', argNames: ['adStatus', 'pConnection'], handler: (this: ADODB.Connection, parameter: {adStatus: ADODB.EventStatusEnum, readonly pConnection: ADODB.Connection}) => void): void;
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es5",
|
||||
"scripthost"
|
||||
"es5"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
/// <reference types="windows-script-host" />
|
||||
|
||||
const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
|
||||
const results: T[] = [];
|
||||
const enumerator = new Enumerator<T>(col);
|
||||
|
||||
Vendored
+1
-4
@@ -4,6 +4,7 @@
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.6
|
||||
|
||||
/// <reference types="activex-interop" />
|
||||
/// <reference types="activex-adodb" />
|
||||
|
||||
declare namespace ADOX {
|
||||
@@ -320,10 +321,6 @@ declare namespace ADOX {
|
||||
}
|
||||
}
|
||||
|
||||
interface ActiveXObject {
|
||||
new<K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
|
||||
}
|
||||
|
||||
interface ActiveXObjectNameMap {
|
||||
'ADOX.Catalog': ADOX.Catalog;
|
||||
'ADOX.Column': ADOX.Column;
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": ["es5", "scripthost"],
|
||||
"lib": [
|
||||
"es5"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
"strictNullChecks": true,
|
||||
|
||||
@@ -1,27 +1,50 @@
|
||||
let engine = new ActiveXObject('DAO.DBEngine.120');
|
||||
/// <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');
|
||||
|
||||
// adding a record to a recordset -- https://msdn.microsoft.com/VBA/Access-VBA/articles/add-a-record-to-a-dao-recordset
|
||||
let rstShippers = dbsNorthwind.OpenRecordset('Shippers');
|
||||
rstShippers.AddNew();
|
||||
rstShippers.Fields.Item('CompanyName').Value = 'Global Parcel Service';
|
||||
// Set remaining fields
|
||||
rstShippers.Update();
|
||||
rstShippers.Close();
|
||||
// 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();
|
||||
}
|
||||
|
||||
// create a QueryDef with the given SQL -- https://msdn.microsoft.com/VBA/Access-VBA/articles/build-sql-statements-that-include-variables-and-controls
|
||||
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);
|
||||
// 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(', ')}`);
|
||||
}
|
||||
|
||||
// count the number of records in a Recordset -- https://msdn.microsoft.com/VBA/Access-VBA/articles/count-the-number-of-records-in-a-dao-recordset
|
||||
// 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);
|
||||
@@ -33,113 +56,119 @@ const findRecordCount = (dbs: DAO.Database, sql: string) => {
|
||||
return count;
|
||||
};
|
||||
|
||||
// delete records from a Recordset -- https://msdn.microsoft.com/VBA/Access-VBA/articles/delete-a-record-from-a-dao-recordset
|
||||
rstShippers = dbsNorthwind.OpenRecordset('SELECT * FROM Shippers ORDER BY CompanyName, ShipperID', DAO.RecordsetTypeEnum.dbOpenDynaset);
|
||||
if (!rstShippers.EOF) {
|
||||
let name = rstShippers.Fields.Item('CompanyName').Value;
|
||||
rstShippers.MoveNext();
|
||||
while (!rstShippers.EOF) {
|
||||
const recordName: string = rstShippers.Fields.Item('CompanyName').Value;
|
||||
if (recordName === name) {
|
||||
rstShippers.Delete();
|
||||
} else {
|
||||
name = recordName;
|
||||
}
|
||||
// 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();
|
||||
}
|
||||
rstShippers.Close();
|
||||
|
||||
// copy entire records to an array -- https://msdn.microsoft.com/VBA/Access-VBA/articles/extract-data-from-a-record-in-a-dao-recordset
|
||||
let rstEmployees = dbsNorthwind.OpenRecordset('SELECT FirstName, LastName, Title FROM Employees', DAO.RecordsetTypeEnum.dbOpenSnapshot);
|
||||
let records = new VBArray<string>(rstEmployees.GetRows(3));
|
||||
let recordCount = records.ubound(2) + 1;
|
||||
let 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));
|
||||
// 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();
|
||||
}
|
||||
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 findOrdersWithoutDetails = () => {
|
||||
{
|
||||
const orders: number[] = [];
|
||||
const rstOrders = dbsNorthwind.OpenRecordset('SELECT * FROM Orders ORDER BY OrderID', DAO.RecordsetTypeEnum.dbOpenSnapshot);
|
||||
const rstOrderDetails = dbsNorthwind.OpenRecordset('SELECT * FROM [Order Details] ORDER BY OrderID', DAO.RecordsetTypeEnum.dbOpenSnapshot);
|
||||
const rstOrders = dbsNorthwind.OpenRecordset('SELECT * FROM Orders ORDER BY OrderID', dbOpenSnapshot);
|
||||
const rstOrderDetails = dbsNorthwind.OpenRecordset('SELECT * FROM [Order Details] ORDER BY OrderID', dbOpenSnapshot);
|
||||
|
||||
const closeRecordsets = () => {
|
||||
rstOrders.Close();
|
||||
rstOrderDetails.Close();
|
||||
};
|
||||
if (rstOrders.EOF || rstOrderDetails.EOF) {
|
||||
closeRecordsets();
|
||||
return;
|
||||
}
|
||||
|
||||
while (!rstOrders.EOF) {
|
||||
const orderID = rstOrders.Fields.Item('OrderID').Value;
|
||||
rstOrderDetails.FindFirst(`OrderID=${orderID}`);
|
||||
if (rstOrderDetails.NoMatch) {
|
||||
orders.push(orderID);
|
||||
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.MoveNext();
|
||||
}
|
||||
closeRecordsets();
|
||||
return orders;
|
||||
};
|
||||
|
||||
// find a record in a table-type DAO Recordset -- https://msdn.microsoft.com/VBA/Access-VBA/articles/find-a-record-in-a-table-type-dao-recordset
|
||||
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.Fields.Item('HireDate').Value as VarDate);
|
||||
hireDate = new Date(rstEmployees('HireDate').Value as VarDate);
|
||||
}
|
||||
return hireDate;
|
||||
};
|
||||
|
||||
// manipulate multiple fields with DAO -- https://msdn.microsoft.com/VBA/Access-VBA/articles/manipulate-multivalued-fields-with-dao
|
||||
const browseMultiValueField = () => {
|
||||
// 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.Fields.Item('TaskName').Value);
|
||||
const childRs = rs.Fields.Item('AssignedTo').Value as DAO.Recordset;
|
||||
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.Fields.Item('Value').Value);
|
||||
WScript.Echo('\t' + childRs('Value').Value);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// modifying an existing record in a DAO Recordset -- https://msdn.microsoft.com/VBA/Access-VBA/articles/modify-an-existing-record-in-a-dao-recordset
|
||||
const changeTitleWithoutTransaction = () => {
|
||||
rstEmployees = dbsNorthwind.OpenRecordset('Employees');
|
||||
// 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.Fields.Item('Title').Value === 'Sales Representative') {
|
||||
if (rstEmployees('Title').Value === 'Sales Representative') {
|
||||
rstEmployees.Edit();
|
||||
rstEmployees.Fields.Item('Title').Value = 'Account Executive';
|
||||
rstEmployees('Title').Value = 'Account Executive';
|
||||
rstEmployees.Update();
|
||||
}
|
||||
rstEmployees.MoveNext();
|
||||
}
|
||||
rstEmployees.Close();
|
||||
};
|
||||
}
|
||||
|
||||
// using transactions in a DAO Recordset -- https://msdn.microsoft.com/VBA/Access-VBA/articles/use-transactions-in-a-dao-recordset
|
||||
// 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.Item(0);
|
||||
rstEmployees = dbsNorthwind.OpenRecordset('Employees');
|
||||
const currentWorkspace = engine.Workspaces(0);
|
||||
const rstEmployees = dbsNorthwind.OpenRecordset('Employees');
|
||||
currentWorkspace.BeginTrans();
|
||||
while (!rstEmployees.EOF) {
|
||||
if (rstEmployees.Fields.Item('Title').Value === 'Sales Representative') {
|
||||
if (rstEmployees('Title').Value === 'Sales Representative') {
|
||||
rstEmployees.Edit();
|
||||
rstEmployees.Fields.Item('Title').Value = 'Account Executive';
|
||||
rstEmployees('Title').Value = 'Account Executive';
|
||||
rstEmployees.Update();
|
||||
}
|
||||
rstEmployees.MoveNext();
|
||||
|
||||
Vendored
+199
-211
@@ -1,8 +1,10 @@
|
||||
// Type definitions for Microsoft Office 14.0 Access Database Engine Object Library - DAO 14.0
|
||||
// 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.4
|
||||
// TypeScript Version: 2.6
|
||||
|
||||
/// <reference types="activex-interop" />
|
||||
|
||||
declare namespace DAO {
|
||||
const enum _DAOSuppHelp {
|
||||
@@ -56,12 +58,15 @@ declare namespace DAO {
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -128,6 +133,15 @@ declare namespace DAO {
|
||||
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',
|
||||
@@ -308,18 +322,26 @@ declare namespace DAO {
|
||||
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?: any, SQLText?: any): QueryDef;
|
||||
CreateQueryDef(Name?: string, SQLText?: string): QueryDef;
|
||||
readonly Database: Database;
|
||||
Execute(Query: string, Options?: any): void;
|
||||
Execute(Query: string, Options?: RecordsetOptionEnum): void;
|
||||
readonly hDbc: number;
|
||||
readonly Name: string;
|
||||
OpenRecordset(Name: string, Type?: any, Options?: any, LockEdit?: any): Recordset;
|
||||
OpenRecordset(Name: string, Type?: RecordsetTypeEnum, Options?: RecordsetOptionEnum, LockEdit?: LockTypeEnum): Recordset;
|
||||
readonly QueryDefs: QueryDefs;
|
||||
QueryTimeout: number;
|
||||
readonly RecordsAffected: number;
|
||||
@@ -329,12 +351,11 @@ declare namespace DAO {
|
||||
readonly Updatable: boolean;
|
||||
}
|
||||
|
||||
class Connections {
|
||||
private 'DAO.Connections_typekey': Connections;
|
||||
private constructor();
|
||||
interface Connections {
|
||||
readonly Count: number;
|
||||
Item(Item: any): Connection;
|
||||
Item(Item: number | string): Connection;
|
||||
Refresh(): void;
|
||||
(Item: number | string): Connection;
|
||||
}
|
||||
|
||||
class Container {
|
||||
@@ -350,12 +371,11 @@ declare namespace DAO {
|
||||
UserName: string;
|
||||
}
|
||||
|
||||
class Containers {
|
||||
private 'DAO.Containers_typekey': Containers;
|
||||
private constructor();
|
||||
interface Containers {
|
||||
readonly Count: number;
|
||||
Item(Item: any): Container;
|
||||
Item(Item: number | string): Container;
|
||||
Refresh(): void;
|
||||
(Item: number | string): Container;
|
||||
}
|
||||
|
||||
class Database {
|
||||
@@ -366,16 +386,16 @@ declare namespace DAO {
|
||||
Connect: string;
|
||||
readonly Connection: Connection;
|
||||
readonly Containers: Containers;
|
||||
CreateProperty(Name?: any, Type?: any, Value?: any, DDL?: any): Property;
|
||||
CreateQueryDef(Name?: any, SQLText?: any): QueryDef;
|
||||
CreateRelation(Name?: any, Table?: any, ForeignTable?: any, Attributes?: any): Relation;
|
||||
CreateTableDef(Name?: any, Attributes?: any, SourceTableName?: any, Connect?: any): TableDef;
|
||||
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?: any): void;
|
||||
MakeReplica(PathName: string, Description: string, Options?: any): void;
|
||||
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?: any, Options?: any, LockEdit?: any): Recordset;
|
||||
OpenRecordset(Name: string, Type?: RecordsetTypeEnum, Options?: RecordsetOptionEnum, LockEdit?: LockTypeEnum): Recordset;
|
||||
PopulatePartial(DbPathName: string): void;
|
||||
readonly Properties: Properties;
|
||||
readonly QueryDefs: QueryDefs;
|
||||
@@ -384,19 +404,18 @@ declare namespace DAO {
|
||||
readonly Recordsets: Recordsets;
|
||||
readonly Relations: Relations;
|
||||
readonly ReplicaID: string;
|
||||
Synchronize(DbPathName: string, ExchangeType?: any): void;
|
||||
Synchronize(DbPathName: string, ExchangeType?: SynchronizeTypeEnum): void;
|
||||
readonly TableDefs: TableDefs;
|
||||
readonly Transactions: boolean;
|
||||
readonly Updatable: boolean;
|
||||
readonly Version: string;
|
||||
}
|
||||
|
||||
class Databases {
|
||||
private 'DAO.Databases_typekey': Databases;
|
||||
private constructor();
|
||||
interface Databases {
|
||||
readonly Count: number;
|
||||
Item(Item: any): Database;
|
||||
Item(Item: number | string): Database;
|
||||
Refresh(): void;
|
||||
(Item: number | string): Database;
|
||||
}
|
||||
|
||||
class DBEngine {
|
||||
@@ -404,26 +423,51 @@ declare namespace DAO {
|
||||
private constructor();
|
||||
BeginTrans(): void;
|
||||
|
||||
/** @param number [Option=0] */
|
||||
/** @param Option [Option=0] */
|
||||
CommitTrans(Option?: number): void;
|
||||
CompactDatabase(SrcName: string, DstName: string, DstLocale?: any, Options?: any, SrcLocale?: any): void;
|
||||
CreateDatabase(Name: string, Locale: string, Option?: any): Database;
|
||||
CreateWorkspace(Name: string, UserName: string, Password: string, UseType?: any): Workspace;
|
||||
|
||||
/**
|
||||
* 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?: any): void;
|
||||
Idle(Action?: IdleEnum): void;
|
||||
IniPath: string;
|
||||
ISAMStats(StatNum: number, Reset?: any): number;
|
||||
|
||||
/** Returns various statistics from the Jet engine */
|
||||
ISAMStats(StatNum: ISAMStatsEnum, Reset?: boolean): number;
|
||||
LoginTimeout: number;
|
||||
OpenConnection(Name: string, Options?: any, ReadOnly?: any, Connect?: any): Connection;
|
||||
OpenDatabase(Name: string, Options?: any, ReadOnly?: any, Connect?: any): Database;
|
||||
|
||||
/**
|
||||
* @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: number, Value: any): void;
|
||||
SetOption(Option: SetOptionEnum, Value: any): void;
|
||||
SystemDB: string;
|
||||
readonly Version: string;
|
||||
readonly Workspaces: Workspaces;
|
||||
@@ -434,9 +478,9 @@ declare namespace DAO {
|
||||
private constructor();
|
||||
readonly AllPermissions: number;
|
||||
readonly Container: string;
|
||||
CreateProperty(Name?: any, Type?: any, Value?: any, DDL?: any): Property;
|
||||
readonly DateCreated: any;
|
||||
readonly LastUpdated: any;
|
||||
CreateProperty(Name?: string, Type?: DataTypeEnum, Value?: any, DDL?: boolean): Property;
|
||||
readonly DateCreated: VarDate;
|
||||
readonly LastUpdated: VarDate;
|
||||
readonly Name: string;
|
||||
Owner: string;
|
||||
Permissions: number;
|
||||
@@ -444,12 +488,11 @@ declare namespace DAO {
|
||||
UserName: string;
|
||||
}
|
||||
|
||||
class Documents {
|
||||
private 'DAO.Documents_typekey': Documents;
|
||||
private constructor();
|
||||
interface Documents {
|
||||
readonly Count: number;
|
||||
Item(Item: any): Document;
|
||||
Item(Item: number | string): Document;
|
||||
Refresh(): void;
|
||||
(Item: number | string): Document;
|
||||
}
|
||||
|
||||
class Error {
|
||||
@@ -462,33 +505,38 @@ declare namespace DAO {
|
||||
readonly Source: string;
|
||||
}
|
||||
|
||||
class Errors {
|
||||
private 'DAO.Errors_typekey': Errors;
|
||||
private constructor();
|
||||
interface Errors {
|
||||
readonly Count: number;
|
||||
Item(Item: any): Error;
|
||||
Refresh(): void;
|
||||
(Item: any): Error;
|
||||
}
|
||||
|
||||
class Field {
|
||||
private 'DAO.Field_typekey': Field;
|
||||
private constructor();
|
||||
private 'DAO.Field2_typekey': Field;
|
||||
AllowZeroLength: boolean;
|
||||
AppendChunk(Val: any): void;
|
||||
AppendOnly: boolean;
|
||||
Attributes: number;
|
||||
readonly CollatingOrder: number;
|
||||
readonly CollectionIndex: number;
|
||||
CreateProperty(Name?: any, Type?: any, Value?: any, DDL?: any): Property;
|
||||
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;
|
||||
@@ -500,44 +548,42 @@ declare namespace DAO {
|
||||
readonly VisibleValue: any;
|
||||
}
|
||||
|
||||
class Fields {
|
||||
private 'DAO.Fields_typekey': Fields;
|
||||
private constructor();
|
||||
Append(Object: any): void;
|
||||
interface Fields {
|
||||
Append(Field: Field): void;
|
||||
readonly Count: number;
|
||||
Delete(Name: string): void;
|
||||
Item(Item: any): Field;
|
||||
Item(Item: number | string): Field;
|
||||
Refresh(): void;
|
||||
(Item: number | string): Field;
|
||||
}
|
||||
|
||||
class Group {
|
||||
private 'DAO.Group_typekey': Group;
|
||||
private constructor();
|
||||
CreateUser(Name?: any, PID?: any, Password?: any): User;
|
||||
CreateUser(Name?: string, PID?: string, Password?: string): User;
|
||||
Name: string;
|
||||
readonly PID: string;
|
||||
readonly Properties: Properties;
|
||||
readonly Users: Users;
|
||||
}
|
||||
|
||||
class Groups {
|
||||
private 'DAO.Groups_typekey': Groups;
|
||||
private constructor();
|
||||
Append(Object: any): void;
|
||||
interface Groups {
|
||||
Append(Group: Group): void;
|
||||
readonly Count: number;
|
||||
Delete(Name: string): void;
|
||||
Item(Item: any): Group;
|
||||
Item(Item: number | string): Group;
|
||||
Refresh(): void;
|
||||
(Item: number | string): Group;
|
||||
}
|
||||
|
||||
class Index {
|
||||
private 'DAO.Index_typekey': Index;
|
||||
private constructor();
|
||||
Clustered: boolean;
|
||||
CreateField(Name?: any, Type?: any, Size?: any): Field;
|
||||
CreateProperty(Name?: any, Type?: any, Value?: any, DDL?: any): Property;
|
||||
CreateField(Name?: string): Field;
|
||||
CreateProperty(Name?: string, Type?: DataTypeEnum, Value?: any, DDL?: boolean): Property;
|
||||
readonly DistinctCount: number;
|
||||
Fields: any;
|
||||
Fields: Fields;
|
||||
readonly Foreign: boolean;
|
||||
IgnoreNulls: boolean;
|
||||
Name: string;
|
||||
@@ -547,14 +593,14 @@ declare namespace DAO {
|
||||
Unique: boolean;
|
||||
}
|
||||
|
||||
class Indexes {
|
||||
private 'DAO.Indexes_typekey': Indexes;
|
||||
private constructor();
|
||||
Append(Object: any): void;
|
||||
// tslint:disable-next-line:interface-name
|
||||
interface Indexes {
|
||||
Append(Index: Index): void;
|
||||
readonly Count: number;
|
||||
Delete(Name: string): void;
|
||||
Item(Item: any): Index;
|
||||
Item(Item: number | string): Index;
|
||||
Refresh(): void;
|
||||
(Item: number | string): Index;
|
||||
}
|
||||
|
||||
class Parameter {
|
||||
@@ -567,53 +613,20 @@ declare namespace DAO {
|
||||
Value: any;
|
||||
}
|
||||
|
||||
class Parameters {
|
||||
private 'DAO.Parameters_typekey': Parameters;
|
||||
private constructor();
|
||||
interface Parameters {
|
||||
readonly Count: number;
|
||||
Item(Item: any): Parameter;
|
||||
Item(Item: number | string): Parameter;
|
||||
Refresh(): void;
|
||||
(Item: number | string): Parameter;
|
||||
}
|
||||
|
||||
/** DAO 3.0 DBEngine (private) */
|
||||
class PrivDBEngine {
|
||||
private 'DAO.PrivDBEngine_typekey': PrivDBEngine;
|
||||
private constructor();
|
||||
BeginTrans(): void;
|
||||
|
||||
/** @param number [Option=0] */
|
||||
CommitTrans(Option?: number): void;
|
||||
CompactDatabase(SrcName: string, DstName: string, DstLocale?: any, Options?: any, SrcLocale?: any): void;
|
||||
CreateDatabase(Name: string, Locale: string, Option?: any): Database;
|
||||
CreateWorkspace(Name: string, UserName: string, Password: string, UseType?: any): Workspace;
|
||||
readonly DefaultPassword: string;
|
||||
DefaultType: number;
|
||||
readonly DefaultUser: string;
|
||||
readonly Errors: Errors;
|
||||
Idle(Action?: any): void;
|
||||
IniPath: string;
|
||||
ISAMStats(StatNum: number, Reset?: any): number;
|
||||
LoginTimeout: number;
|
||||
OpenConnection(Name: string, Options?: any, ReadOnly?: any, Connect?: any): Connection;
|
||||
OpenDatabase(Name: string, Options?: any, ReadOnly?: any, Connect?: any): Database;
|
||||
readonly Properties: Properties;
|
||||
RegisterDatabase(Dsn: string, Driver: string, Silent: boolean, Attributes: string): void;
|
||||
RepairDatabase(Name: string): void;
|
||||
Rollback(): void;
|
||||
SetOption(Option: number, Value: any): void;
|
||||
SystemDB: string;
|
||||
readonly Version: string;
|
||||
readonly Workspaces: Workspaces;
|
||||
}
|
||||
|
||||
class Properties {
|
||||
private 'DAO.Properties_typekey': Properties;
|
||||
private constructor();
|
||||
Append(Object: any): void;
|
||||
interface Properties {
|
||||
Append(Property: Property): void;
|
||||
readonly Count: number;
|
||||
Delete(Name: string): void;
|
||||
Item(Item: any): Property;
|
||||
Item(Item: number | string): Property;
|
||||
Refresh(): void;
|
||||
(Item: number | string): Property;
|
||||
}
|
||||
|
||||
class Property {
|
||||
@@ -633,81 +646,78 @@ declare namespace DAO {
|
||||
Cancel(): void;
|
||||
Close(): void;
|
||||
Connect: string;
|
||||
CreateProperty(Name?: any, Type?: any, Value?: any, DDL?: any): Property;
|
||||
readonly DateCreated: any;
|
||||
Execute(Options?: any): void;
|
||||
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: any;
|
||||
readonly LastUpdated: VarDate;
|
||||
MaxRecords: number;
|
||||
Name: string;
|
||||
ODBCTimeout: number;
|
||||
OpenRecordset(Type?: any, Options?: any, LockEdit?: any): Recordset;
|
||||
OpenRecordset(Type?: RecordsetTypeEnum, Options?: RecordsetOptionEnum, LockEdit?: LockTypeEnum): Recordset;
|
||||
readonly Parameters: Parameters;
|
||||
Prepare: any;
|
||||
Prepare: QueryDefStateEnum;
|
||||
readonly Properties: Properties;
|
||||
readonly RecordsAffected: number;
|
||||
ReturnsRecords: boolean;
|
||||
SQL: string;
|
||||
readonly StillExecuting: boolean;
|
||||
readonly Type: number;
|
||||
readonly Type: QueryDefTypeEnum;
|
||||
readonly Updatable: boolean;
|
||||
}
|
||||
|
||||
class QueryDefs {
|
||||
private 'DAO.QueryDefs_typekey': QueryDefs;
|
||||
private constructor();
|
||||
Append(Object: any): void;
|
||||
interface QueryDefs {
|
||||
Append(QueryDef: QueryDef): void;
|
||||
readonly Count: number;
|
||||
Delete(Name: string): void;
|
||||
Item(Item: any): QueryDef;
|
||||
Item(Item: number | string): QueryDef;
|
||||
Refresh(): void;
|
||||
(Item: number | string): QueryDef;
|
||||
}
|
||||
|
||||
class Recordset {
|
||||
private 'DAO.Recordset_typekey': Recordset;
|
||||
private constructor();
|
||||
interface Recordset {
|
||||
AbsolutePosition: number;
|
||||
AddNew(): void;
|
||||
readonly BatchCollisionCount: number;
|
||||
readonly BatchCollisions: any;
|
||||
readonly BatchCollisions: SafeArray<Bookmark>;
|
||||
BatchSize: number;
|
||||
readonly BOF: boolean;
|
||||
Bookmark: SafeArray<number>;
|
||||
Bookmark: Bookmark;
|
||||
readonly Bookmarkable: boolean;
|
||||
CacheSize: number;
|
||||
CacheStart: SafeArray<number>;
|
||||
CacheStart: Bookmark;
|
||||
Cancel(): void;
|
||||
|
||||
/** @param number [UpdateType=1] */
|
||||
/** @param UpdateType [UpdateType=1] */
|
||||
CancelUpdate(UpdateType?: number): void;
|
||||
Clone(): Recordset;
|
||||
Close(): void;
|
||||
Collect(Item: any): any;
|
||||
Connection: Connection;
|
||||
CopyQueryDef(): QueryDef;
|
||||
readonly DateCreated: any;
|
||||
readonly DateCreated: VarDate;
|
||||
Delete(): void;
|
||||
Edit(): void;
|
||||
readonly EditMode: number;
|
||||
readonly EditMode: EditModeEnum;
|
||||
readonly EOF: boolean;
|
||||
readonly Fields: Fields;
|
||||
FillCache(Rows?: any, StartBookmark?: any): void;
|
||||
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?: any): any;
|
||||
GetRows(NumRows?: number): any;
|
||||
readonly hStmt: number;
|
||||
Index: string;
|
||||
readonly LastModified: SafeArray<number>;
|
||||
readonly LastUpdated: any;
|
||||
readonly LastModified: Bookmark;
|
||||
readonly LastUpdated: VarDate;
|
||||
LockEdits: boolean;
|
||||
Move(Rows: number, StartBookmark?: any): void;
|
||||
Move(Rows: number, StartBookmark?: Bookmark): void;
|
||||
MoveFirst(): void;
|
||||
|
||||
/** @param number [Options=0] */
|
||||
/** @param Options [Options=0] */
|
||||
MoveLast(Options?: number): void;
|
||||
MoveNext(): void;
|
||||
MovePrevious(): void;
|
||||
@@ -716,45 +726,44 @@ declare namespace DAO {
|
||||
readonly NoMatch: boolean;
|
||||
readonly ODBCFetchCount: number;
|
||||
readonly ODBCFetchDelay: number;
|
||||
OpenRecordset(Type?: any, Options?: any): Recordset;
|
||||
OpenRecordset(Type?: RecordsetTypeEnum, Options?: RecordsetOptionEnum): Recordset;
|
||||
readonly Parent: Database;
|
||||
PercentPosition: number;
|
||||
readonly Properties: Properties;
|
||||
readonly RecordCount: number;
|
||||
readonly RecordStatus: number;
|
||||
Requery(NewQueryDef?: any): void;
|
||||
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;
|
||||
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: number;
|
||||
readonly Type: RecordsetTypeEnum;
|
||||
readonly Updatable: boolean;
|
||||
|
||||
/**
|
||||
* @param number [UpdateType=1]
|
||||
* @param boolean [Force=false]
|
||||
* @param UpdateType [UpdateType=1]
|
||||
* @param Force [Force=false]
|
||||
*/
|
||||
Update(UpdateType?: number, Force?: boolean): void;
|
||||
UpdateOptions: number;
|
||||
Update(UpdateType?: UpdateTypeEnum, Force?: boolean): void;
|
||||
UpdateOptions: UpdateCriteriaEnum;
|
||||
readonly ValidationRule: string;
|
||||
readonly ValidationText: string;
|
||||
(FieldIndex: number | string): Field;
|
||||
}
|
||||
|
||||
class Recordsets {
|
||||
private 'DAO.Recordsets_typekey': Recordsets;
|
||||
private constructor();
|
||||
interface Recordsets {
|
||||
readonly Count: number;
|
||||
Item(Item: any): Recordset;
|
||||
Item(Item: number | string): Recordset;
|
||||
Refresh(): void;
|
||||
(Item: number | string): Recordset;
|
||||
}
|
||||
|
||||
class Relation {
|
||||
private 'DAO.Relation_typekey': Relation;
|
||||
private constructor();
|
||||
Attributes: number;
|
||||
CreateField(Name?: any, Type?: any, Size?: any): Field;
|
||||
Attributes: RelationAttributeEnum;
|
||||
CreateField(Name?: string): Field;
|
||||
readonly Fields: Fields;
|
||||
ForeignTable: string;
|
||||
Name: string;
|
||||
@@ -763,55 +772,53 @@ declare namespace DAO {
|
||||
Table: string;
|
||||
}
|
||||
|
||||
class Relations {
|
||||
private 'DAO.Relations_typekey': Relations;
|
||||
private constructor();
|
||||
Append(Object: any): void;
|
||||
interface Relations {
|
||||
Append(Relation: Relation): void;
|
||||
readonly Count: number;
|
||||
Delete(Name: string): void;
|
||||
Item(Item: any): Relation;
|
||||
Item(Item: number | string): Relation;
|
||||
Refresh(): void;
|
||||
(Item: number | string): Relation;
|
||||
}
|
||||
|
||||
class TableDef {
|
||||
private 'DAO.TableDef_typekey': TableDef;
|
||||
private constructor();
|
||||
Attributes: number;
|
||||
Attributes: TableDefAttributeEnum;
|
||||
readonly ConflictTable: string;
|
||||
Connect: string;
|
||||
CreateField(Name?: any, Type?: any, Size?: any): Field;
|
||||
CreateIndex(Name?: any): Index;
|
||||
CreateProperty(Name?: any, Type?: any, Value?: any, DDL?: any): Property;
|
||||
readonly DateCreated: any;
|
||||
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: any;
|
||||
readonly LastUpdated: VarDate;
|
||||
Name: string;
|
||||
OpenRecordset(Type?: any, Options?: any): Recordset;
|
||||
OpenRecordset(Type?: RecordsetTypeEnum, Options?: RecordsetOptionEnum): Recordset;
|
||||
readonly Properties: Properties;
|
||||
readonly RecordCount: number;
|
||||
RefreshLink(): void;
|
||||
ReplicaFilter: any;
|
||||
ReplicaFilter: string | boolean;
|
||||
SourceTableName: string;
|
||||
readonly Updatable: boolean;
|
||||
ValidationRule: string;
|
||||
ValidationText: string;
|
||||
}
|
||||
|
||||
class TableDefs {
|
||||
private 'DAO.TableDefs_typekey': TableDefs;
|
||||
private constructor();
|
||||
Append(Object: any): void;
|
||||
interface TableDefs {
|
||||
Append(TableDef: TableDef): void;
|
||||
readonly Count: number;
|
||||
Delete(Name: string): void;
|
||||
Item(Item: any): TableDef;
|
||||
Item(Item: number | string): TableDef;
|
||||
Refresh(): void;
|
||||
(Item: number | string): TableDef;
|
||||
}
|
||||
|
||||
class User {
|
||||
private 'DAO.User_typekey': User;
|
||||
private constructor();
|
||||
CreateGroup(Name?: any, PID?: any): Group;
|
||||
CreateGroup(Name?: string, PID?: string): Group;
|
||||
readonly Groups: Groups;
|
||||
Name: string;
|
||||
NewPassword(bstrOld: string, bstrNew: string): void;
|
||||
@@ -820,14 +827,13 @@ declare namespace DAO {
|
||||
readonly Properties: Properties;
|
||||
}
|
||||
|
||||
class Users {
|
||||
private 'DAO.Users_typekey': Users;
|
||||
private constructor();
|
||||
Append(Object: any): void;
|
||||
interface Users {
|
||||
Append(User: User): void;
|
||||
readonly Count: number;
|
||||
Delete(Name: string): void;
|
||||
Item(Item: any): User;
|
||||
Item(Item: number | string): User;
|
||||
Refresh(): void;
|
||||
(Item: number | string): User;
|
||||
}
|
||||
|
||||
class Workspace {
|
||||
@@ -836,12 +842,19 @@ declare namespace DAO {
|
||||
BeginTrans(): void;
|
||||
Close(): void;
|
||||
|
||||
/** @param number [Options=0] */
|
||||
/** @param Options [Options=0] */
|
||||
CommitTrans(Options?: number): void;
|
||||
readonly Connections: Connections;
|
||||
CreateDatabase(Name: string, Connect: string, Option?: any): Database;
|
||||
CreateGroup(Name?: any, PID?: any): Group;
|
||||
CreateUser(Name?: any, PID?: any, Password?: any): User;
|
||||
|
||||
/**
|
||||
* @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;
|
||||
@@ -849,8 +862,12 @@ declare namespace DAO {
|
||||
IsolateODBCTrans: number;
|
||||
LoginTimeout: number;
|
||||
Name: string;
|
||||
OpenConnection(Name: string, Options?: any, ReadOnly?: any, Connect?: any): Connection;
|
||||
OpenDatabase(Name: string, Options?: any, ReadOnly?: any, Connect?: any): Database;
|
||||
|
||||
/**
|
||||
* @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;
|
||||
@@ -858,53 +875,24 @@ declare namespace DAO {
|
||||
readonly Users: Users;
|
||||
}
|
||||
|
||||
class Workspaces {
|
||||
private 'DAO.Workspaces_typekey': Workspaces;
|
||||
private constructor();
|
||||
Append(Object: any): void;
|
||||
interface Workspaces {
|
||||
Append(Workspace: Workspace): void;
|
||||
readonly Count: number;
|
||||
Delete(Name: string): void;
|
||||
Item(Item: any): Workspace;
|
||||
Item(Item: number | string): Workspace;
|
||||
Refresh(): void;
|
||||
(Item: number | string): Workspace;
|
||||
}
|
||||
}
|
||||
|
||||
interface ActiveXObject {
|
||||
new<K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
|
||||
}
|
||||
|
||||
interface ActiveXObjectNameMap {
|
||||
'DAO.DBEngine': DAO.DBEngine;
|
||||
'DAO.DBEngine.120': DAO.DBEngine;
|
||||
'DAO.Field': DAO.Field;
|
||||
'DAO.Group': DAO.Group;
|
||||
'DAO.Index': DAO.Index;
|
||||
'DAO.PrivateDBEngine': DAO.PrivDBEngine;
|
||||
'DAO.PrivateDBEngine': DAO.DBEngine;
|
||||
'DAO.QueryDef': DAO.QueryDef;
|
||||
'DAO.Relation': DAO.Relation;
|
||||
'DAO.TableDef': DAO.TableDef;
|
||||
'DAO.User': DAO.User;
|
||||
}
|
||||
|
||||
interface EnumeratorConstructor {
|
||||
new(col: DAO.Connections): Enumerator<DAO.Connection>;
|
||||
new(col: DAO.Containers): Enumerator<DAO.Container>;
|
||||
new(col: DAO.Databases): Enumerator<DAO.Database>;
|
||||
new(col: DAO.Documents): Enumerator<DAO.Document>;
|
||||
new(col: DAO.Errors): Enumerator<DAO.Error>;
|
||||
new(col: DAO.Fields): Enumerator<DAO.Field>;
|
||||
new(col: DAO.Groups): Enumerator<DAO.Group>;
|
||||
new(col: DAO.Indexes): Enumerator<DAO.Index>;
|
||||
new(col: DAO.Parameters): Enumerator<DAO.Parameter>;
|
||||
new(col: DAO.Properties): Enumerator<DAO.Property>;
|
||||
new(col: DAO.QueryDefs): Enumerator<DAO.QueryDef>;
|
||||
new(col: DAO.Recordsets): Enumerator<DAO.Recordset>;
|
||||
new(col: DAO.Relations): Enumerator<DAO.Relation>;
|
||||
new(col: DAO.TableDefs): Enumerator<DAO.TableDef>;
|
||||
new(col: DAO.Users): Enumerator<DAO.User>;
|
||||
new(col: DAO.Workspaces): Enumerator<DAO.Workspace>;
|
||||
}
|
||||
|
||||
interface SafeArray<T = any> {
|
||||
_brand: SafeArray<T>;
|
||||
}
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es5",
|
||||
"scripthost"
|
||||
"es5"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
|
||||
Vendored
+3
-6
@@ -2,7 +2,9 @@
|
||||
// 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.5
|
||||
// TypeScript Version: 2.6
|
||||
|
||||
/// <reference types="activex-interop" />
|
||||
|
||||
declare namespace DiskQuotaTypeLibrary {
|
||||
// tslint:disable-next-line no-const-enum
|
||||
@@ -136,7 +138,6 @@ interface ActiveXObject {
|
||||
on(
|
||||
obj: DiskQuotaTypeLibrary.DiskQuotaControl, event: 'OnUserNameChanged', argNames: ['pUser'], handler: (
|
||||
this: DiskQuotaTypeLibrary.DiskQuotaControl, parameter: {readonly pUser: DiskQuotaTypeLibrary.DIDiskQuotaUser}) => void): void;
|
||||
new<K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
|
||||
}
|
||||
|
||||
interface ActiveXObjectNameMap {
|
||||
@@ -146,7 +147,3 @@ interface ActiveXObjectNameMap {
|
||||
interface EnumeratorConstructor {
|
||||
new(col: DiskQuotaTypeLibrary.DiskQuotaControl): Enumerator<DiskQuotaTypeLibrary.DIDiskQuotaUser>;
|
||||
}
|
||||
|
||||
interface SafeArray<T = any> {
|
||||
_brand: SafeArray<T>;
|
||||
}
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es5",
|
||||
"scripthost"
|
||||
"es5"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
/// <reference types="windows-script-host" />
|
||||
/// <reference types="activex-msforms" />
|
||||
/// <reference types="activex-scripting" />
|
||||
|
||||
// some helpers
|
||||
const toSafeArray = <T>(...items: T[]): SafeArray<T> => {
|
||||
const dict = new ActiveXObject('Scripting.Dictionary');
|
||||
const dict: Scripting.Dictionary<number, T> = new ActiveXObject('Scripting.Dictionary');
|
||||
items.forEach((x, index) => dict.Add(index, x));
|
||||
return dict.Items() as SafeArray<T>;
|
||||
return dict.Items();
|
||||
};
|
||||
const inCollection = <T = any>(collection: { Item(index: any): T }, index: string | number): T | undefined => {
|
||||
let item: T | undefined;
|
||||
@@ -15,6 +16,17 @@ const inCollection = <T = any>(collection: { Item(index: any): T }, index: strin
|
||||
return item;
|
||||
};
|
||||
|
||||
{
|
||||
let app1: Excel.Application | null = new ActiveXObject('Excel.Application');
|
||||
app1.Visible = true;
|
||||
const book1 = app1.Workbooks.Add();
|
||||
|
||||
app1.Quit();
|
||||
app1 = null;
|
||||
|
||||
WScript.Quit();
|
||||
}
|
||||
|
||||
const app = new ActiveXObject('Excel.Application');
|
||||
|
||||
// create a workbook -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/create-a-workbook
|
||||
@@ -26,7 +38,7 @@ 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;
|
||||
let mySheet = inCollection<Excel.Worksheet>(newBook.Worksheets, mySheetName);
|
||||
if (!mySheet) {
|
||||
WScript.Echo(`The sheet named "${mySheetName} doesn't exist, but will be created.`);
|
||||
mySheet = app.Worksheets.Add() as Excel.Worksheet;
|
||||
@@ -36,7 +48,7 @@ const newOrExistingWorksheet = () => {
|
||||
const replaceWorksheet = () => {
|
||||
const mySheetName = 'Sheet4';
|
||||
app.DisplayAlerts = false;
|
||||
let mySheet = inCollection<Excel.Worksheet | Excel.Chart | Excel.DialogSheet>(app.Worksheets, mySheetName);
|
||||
let mySheet = inCollection<Excel.Worksheet>(app.Worksheets, mySheetName);
|
||||
if (mySheet) { mySheet.Delete(); }
|
||||
app.DisplayAlerts = true;
|
||||
mySheet = app.Worksheets.Add() as Excel.Worksheet;
|
||||
@@ -45,9 +57,7 @@ const replaceWorksheet = () => {
|
||||
};
|
||||
|
||||
// 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);
|
||||
};
|
||||
const moveMultipleSheets = () => app.Worksheets(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 = () => {
|
||||
@@ -55,9 +65,9 @@ const sortSheetsTabName = () => {
|
||||
const sheets = app.ActiveWorkbook.Sheets;
|
||||
const sheetCount = sheets.Count;
|
||||
for (let i = 0; i < sheetCount; i += 1) {
|
||||
const sheetI = sheets.Item(i);
|
||||
const sheetI = sheets(i);
|
||||
for (let j = i; j < sheetCount; j += 1) {
|
||||
const sheetJ = sheets.Item(j);
|
||||
const sheetJ = sheets(j);
|
||||
if (sheetJ.Name < sheetI.Name) { sheetJ.Move(sheetI); }
|
||||
}
|
||||
}
|
||||
@@ -67,7 +77,7 @@ const sortSheetsTabName = () => {
|
||||
// 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);
|
||||
const columnA = app.Columns(1);
|
||||
try {
|
||||
columnA.SpecialCells(Excel.XlCellType.xlCellTypeBlanks).Formula = '=R[-1]C';
|
||||
columnA.Value = columnA.Value;
|
||||
@@ -77,7 +87,7 @@ const fillCellsFromAbove = () => {
|
||||
|
||||
// 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 book = app.Workbooks(1);
|
||||
const sheet = inCollection<Excel.Worksheet | Excel.Chart | Excel.DialogSheet>(book.Worksheets, 'Sheet1');
|
||||
if (!sheet) { return; }
|
||||
|
||||
@@ -96,7 +106,7 @@ const setColumnVisibility = (visible: boolean) => {
|
||||
};
|
||||
|
||||
// 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
|
||||
@@ -119,10 +129,10 @@ const setColumnVisibility = (visible: boolean) => {
|
||||
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
|
||||
@@ -140,20 +150,19 @@ const setColumnVisibility = (visible: boolean) => {
|
||||
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);
|
||||
wks.Cells(6, 1).Value2 = 10;
|
||||
wks.Cells(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);
|
||||
wks.Cells(counter, 1).Value = 10;
|
||||
}
|
||||
|
||||
// relative to other cells
|
||||
wks.Cells.Item(1, 1).Font.Underline = Excel.XlUnderlineStyle.xlUnderlineStyleDouble;
|
||||
wks.Cells(1, 1).Font.Underline = Excel.XlUnderlineStyle.xlUnderlineStyleDouble;
|
||||
|
||||
// using a Range object
|
||||
const rng = wks.Cells.Item('A1:D5');
|
||||
const rng = wks.Cells('A1:D5');
|
||||
rng.Formula = '=RAND()';
|
||||
rng.Font.Bold = true;
|
||||
|
||||
@@ -165,23 +174,22 @@ const setColumnVisibility = (visible: boolean) => {
|
||||
|
||||
// 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);
|
||||
const currentCell = wks.Cells(x, 1);
|
||||
if (Math.abs(currentCell.Value) < 0.01) {
|
||||
currentCell.Value = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// using Enumerator
|
||||
let enumerator = new Enumerator(wks.Cells.Item('A1:D10'));
|
||||
let enumerator = new Enumerator(wks.Cells('A1:D10'));
|
||||
enumerator.moveFirst();
|
||||
while (!enumerator.atEnd()) {
|
||||
const currentCell = enumerator.item();
|
||||
@@ -201,11 +209,11 @@ const setColumnVisibility = (visible: boolean) => {
|
||||
}
|
||||
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;
|
||||
{
|
||||
const wks = app.ActiveWorkbook.Worksheets(1);
|
||||
|
||||
// make a worksheet the active worksheet; otherwise code which uses the selection will fail
|
||||
wks.Select();
|
||||
@@ -218,24 +226,24 @@ const setColumnVisibility = (visible: boolean) => {
|
||||
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.Sheets(toSafeArray("Sheet2", "Sheet3", "Sheet4")).Select();
|
||||
app.Range("A1:H1").Select();
|
||||
(app.Selection as Excel.Range).Borders.Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlDouble;
|
||||
(app.Selection as Excel.Range).Borders(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 wks2 = book.Worksheets("Sheet2");
|
||||
const rng = wks2.Range("A1:H1");
|
||||
rng.Borders.Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlDouble;
|
||||
rng.Borders(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);
|
||||
{
|
||||
const book = app.Workbooks(1);
|
||||
|
||||
ActiveXObject.on(book, 'SheetChange', ['Sh', 'Target'], function(this, prm) {
|
||||
const EvalRange = this.ActiveSheet.Range("A1:B20");
|
||||
const EvalRange = (this.ActiveSheet as Excel.Worksheet).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 (
|
||||
@@ -252,10 +260,11 @@ const setColumnVisibility = (visible: boolean) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// const enumerator = new Enumerator<Excel.Worksheet | Excel.Chart | Excel.DialogSheet>(book.Worksheets);
|
||||
const enumerator = new Enumerator(book.Worksheets);
|
||||
enumerator.moveFirst();
|
||||
while (!enumerator.atEnd()) {
|
||||
const wks = enumerator.item() as Excel.Worksheet;
|
||||
const wks = enumerator.item();
|
||||
if (wks.Name === prm.Target.Name) { continue; }
|
||||
|
||||
// If the value entered already exists in the defined range on the current worksheet, undo the entry.
|
||||
@@ -266,55 +275,70 @@ const setColumnVisibility = (visible: boolean) => {
|
||||
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 sheet = book.Worksheets("Sheet1");
|
||||
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.ComboBox2;
|
||||
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 sheet = app.ThisWorkbook.Sheets('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));
|
||||
for (const x of arr) {
|
||||
ActiveXObject.set(dict, 'Item', [x], true);
|
||||
}
|
||||
|
||||
const combobox = sheet.OLEObjects('ComboBox1').Object as MSForms.ComboBox2;
|
||||
const combobox = sheet.OLEObjects('ComboBox1').Object as MSForms.ComboBox;
|
||||
combobox.Clear();
|
||||
const enumerator = new Enumerator(dict.Items());
|
||||
|
||||
// iterate over keys using Enumerator
|
||||
const enumerator = new Enumerator(dict);
|
||||
enumerator.moveFirst();
|
||||
while (!enumerator.atEnd()) {
|
||||
combobox.AddItem(enumerator.item());
|
||||
enumerator.moveNext();
|
||||
}
|
||||
})();
|
||||
})();
|
||||
|
||||
// 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);
|
||||
// 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(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);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
const formats = new VBArray(app.ClipboardFormats).toArray();
|
||||
for (const format of formats) {
|
||||
WScript.Echo(format);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+2148
-1760
File diff suppressed because it is too large
Load Diff
@@ -2,8 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es5",
|
||||
"scripthost"
|
||||
"es5"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
{
|
||||
"extends": "dtslint/dt.json"
|
||||
"extends": "dtslint/dt.json",
|
||||
"rules": {
|
||||
"no-const-enum": false,
|
||||
"max-line-length": false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/// <reference types="activex-iwshruntimelibrary" />
|
||||
/// <reference types="windows-script-host" />
|
||||
/// <reference types="activex-scripting" />
|
||||
|
||||
const collectionToArray = <T>(col: { Item(index: any): T } | SafeArray<T>) => {
|
||||
const collectionToArray = <T>(col: { Item(index: any): T }): T[] => {
|
||||
const results: T[] = [];
|
||||
const enumerator = new Enumerator<T>(col);
|
||||
enumerator.moveFirst();
|
||||
@@ -12,9 +13,9 @@ const collectionToArray = <T>(col: { Item(index: any): T } | SafeArray<T>) => {
|
||||
};
|
||||
|
||||
const toSafeArray = <T>(...items: T[]): SafeArray<T> => {
|
||||
const dict = new ActiveXObject('Scripting.Dictionary');
|
||||
const dict: Scripting.Dictionary<number, T> = new ActiveXObject('Scripting.Dictionary');
|
||||
items.forEach((x, index) => dict.Add(index, x));
|
||||
return dict.Items() as SafeArray<T>;
|
||||
return dict.Items();
|
||||
};
|
||||
|
||||
const VB = {
|
||||
@@ -422,7 +423,7 @@ the job?
|
||||
document.GroupBroadcastReceipts = true;
|
||||
|
||||
const jobIDs = document.Submit('');
|
||||
collectionToArray(jobIDs).forEach(jobID => WScript.Echo(`The job ID is ${jobID}`));
|
||||
new VBArray(jobIDs).toArray().forEach(jobID => WScript.Echo(`The job ID is ${jobID}`));
|
||||
|
||||
while (recipients.Count > 0) {
|
||||
recipients.Remove(1);
|
||||
|
||||
Vendored
-1
@@ -2011,7 +2011,6 @@ interface ActiveXObject {
|
||||
this: FAXCOMEXLib.FaxServer, parameter: {readonly riid: stdole.GUID, ppvObj: undefined}) => void): void;
|
||||
on(obj: FAXCOMEXLib.FaxAccount, event: 'AddRef' | 'Release', handler: (this: FAXCOMEXLib.FaxAccount, parameter: {}) => void): void;
|
||||
on(obj: FAXCOMEXLib.FaxServer, event: 'AddRef' | 'Release', handler: (this: FAXCOMEXLib.FaxServer, parameter: {}) => void): void;
|
||||
new<K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
|
||||
}
|
||||
|
||||
interface ActiveXObjectNameMap {
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es5",
|
||||
"scripthost"
|
||||
"es5"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
|
||||
Vendored
-1
@@ -1168,7 +1168,6 @@ interface ActiveXObject {
|
||||
on(obj: InfoPath.Button, event: 'AddRef' | 'Release', handler: (this: InfoPath.Button, parameter: {}) => void): void;
|
||||
on(obj: InfoPath.DataDOM, event: 'AddRef' | 'Release', handler: (this: InfoPath.DataDOM, parameter: {}) => void): void;
|
||||
on(obj: InfoPath.XDocument, event: 'AddRef' | 'Release', handler: (this: InfoPath.XDocument, parameter: {}) => void): void;
|
||||
new<K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
|
||||
}
|
||||
|
||||
interface ActiveXObjectNameMap {
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es5",
|
||||
"scripthost"
|
||||
"es5"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/// <reference types="activex-scripting" />
|
||||
|
||||
const dict: Scripting.Dictionary<string, number> = new ActiveXObject('Scripting.Dictionary');
|
||||
dict.Add('one', 1);
|
||||
dict.Add('two', 2);
|
||||
dict.Add('three', 3);
|
||||
|
||||
const keyEnumerator = new Enumerator(dict);
|
||||
keyEnumerator.moveFirst();
|
||||
while (!keyEnumerator.atEnd()) {
|
||||
const item = dict(keyEnumerator.item());
|
||||
const power = Math.pow(item, 2);
|
||||
}
|
||||
|
||||
const keysArray = new VBArray(dict.Keys()).toArray();
|
||||
const itemsArray = new VBArray(dict.Items()).toArray();
|
||||
for (let i = 0; i < keysArray.length; i++) {
|
||||
const key = keysArray[i];
|
||||
const item = itemsArray[i];
|
||||
}
|
||||
Vendored
+110
@@ -0,0 +1,110 @@
|
||||
// Type definitions for Javascript Automation interop 0.0
|
||||
// Project: https://msdn.microsoft.com/en-us/library/ff521046(v=vs.85).aspx
|
||||
// Definitions by: Zev Spitz <https://github.com/zspitz>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.6
|
||||
|
||||
// tslint:disable-next-line no-empty-interface
|
||||
interface ActiveXObjectNameMap { }
|
||||
|
||||
interface ActiveXObject {
|
||||
new <K extends keyof ActiveXObjectNameMap>(progid: K): ActiveXObjectNameMap[K];
|
||||
new(s: string): any;
|
||||
}
|
||||
declare var ActiveXObject: ActiveXObject;
|
||||
|
||||
/**
|
||||
* Represents an Automation SAFEARRAY
|
||||
*/
|
||||
declare class SafeArray<T = any> {
|
||||
private constructor();
|
||||
private SafeArray_typekey: SafeArray<T>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows enumerating over a COM collection, which may not have indexed item access.
|
||||
*/
|
||||
interface Enumerator<T = any> {
|
||||
/**
|
||||
* Returns true if the current item is the last one in the collection, or the collection is empty,
|
||||
* or the current item is undefined.
|
||||
*/
|
||||
atEnd(): boolean;
|
||||
|
||||
/**
|
||||
* Returns the current item in the collection
|
||||
*/
|
||||
item(): T;
|
||||
|
||||
/**
|
||||
* Resets the current item in the collection to the first item. If there are no items in the collection,
|
||||
* the current item is set to undefined.
|
||||
*/
|
||||
moveFirst(): void;
|
||||
|
||||
/**
|
||||
* Moves the current item to the next item in the collection. If the enumerator is at the end of
|
||||
* the collection or the collection is empty, the current item is set to undefined.
|
||||
*/
|
||||
moveNext(): void;
|
||||
}
|
||||
|
||||
interface EnumeratorConstructor {
|
||||
new <T = any>(collection: { Item(index: any): T }): Enumerator<T>;
|
||||
}
|
||||
|
||||
declare var Enumerator: EnumeratorConstructor;
|
||||
|
||||
/**
|
||||
* Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions.
|
||||
*/
|
||||
interface VBArray<T = any> {
|
||||
/**
|
||||
* Returns the number of dimensions (1-based).
|
||||
*/
|
||||
dimensions(): number;
|
||||
|
||||
/**
|
||||
* Takes an index for each dimension in the array, and returns the item at the corresponding location.
|
||||
*/
|
||||
getItem(dimension1Index: number, ...dimensionNIndexes: number[]): T;
|
||||
|
||||
/**
|
||||
* Returns the smallest available index for a given dimension.
|
||||
* @param dimension 1-based dimension (defaults to 1)
|
||||
*/
|
||||
lbound(dimension?: number): number;
|
||||
|
||||
/**
|
||||
* Returns the largest available index for a given dimension.
|
||||
* @param dimension 1-based dimension (defaults to 1)
|
||||
*/
|
||||
ubound(dimension?: number): number;
|
||||
|
||||
/**
|
||||
* Returns a Javascript array with all the elements in the VBArray. If there are multiple dimensions,
|
||||
* each successive dimension is appended to the end of the array.
|
||||
* Example: [[1,2,3],[4,5,6]] becomes [1,2,3,4,5,6]
|
||||
*/
|
||||
toArray(): T[];
|
||||
}
|
||||
|
||||
interface VBArrayConstructor {
|
||||
new <T = any>(safeArray: SafeArray<T>): VBArray<T>;
|
||||
}
|
||||
|
||||
declare var VBArray: VBArrayConstructor;
|
||||
|
||||
/** Automation date (VT_DATE) */
|
||||
declare class VarDate {
|
||||
private constructor();
|
||||
private VarDate_typekey: VarDate;
|
||||
}
|
||||
|
||||
interface DateConstructor {
|
||||
new(vd: VarDate): Date;
|
||||
}
|
||||
|
||||
interface Date {
|
||||
getVarDate: () => VarDate;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"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-interop-tests.ts"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "dtslint/dt.json"
|
||||
}
|
||||
@@ -1,3 +1,16 @@
|
||||
/// <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 wshn = new ActiveXObject('WScript.Network');
|
||||
|
||||
// https://msdn.microsoft.com/en-us/library/s6wt333f(v=vs.84).aspx
|
||||
|
||||
+122
-33
@@ -1,14 +1,15 @@
|
||||
// Type definitions for Windows Script Host Object Model - IWshRuntimeLibrary 1.0
|
||||
// Project: https://msdn.microsoft.com/en-us/library/9bbdkx3k(v=vs.84).aspx
|
||||
// Type definitions for Windows Script Host Runtime Object Model 0.0
|
||||
// Project: https://msdn.microsoft.com/en-us/library/9bbdkx3k.aspx
|
||||
// Definitions by: Zev Spitz <https://github.com/zspitz>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.6
|
||||
|
||||
/// <reference types="activex-interop" />
|
||||
|
||||
declare namespace IWshRuntimeLibrary {
|
||||
type WindowStyle = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
|
||||
type ShortcutWindowStyle = 1 | 3 | 7;
|
||||
|
||||
// tslint:disable-next-line no-const-enum
|
||||
const enum ButtonType {
|
||||
OK,
|
||||
OKCancel,
|
||||
@@ -19,7 +20,6 @@ declare namespace IWshRuntimeLibrary {
|
||||
CancelTryagainContinue
|
||||
}
|
||||
|
||||
// tslint:disable-next-line no-const-enum
|
||||
const enum EventType {
|
||||
AuditFailure = 5,
|
||||
AuditSuccess = 4,
|
||||
@@ -29,7 +29,6 @@ declare namespace IWshRuntimeLibrary {
|
||||
Warning = 2
|
||||
}
|
||||
|
||||
// tslint:disable-next-line no-const-enum
|
||||
const enum IconType {
|
||||
Stop = 16,
|
||||
QuestionMark = 32,
|
||||
@@ -37,7 +36,6 @@ declare namespace IWshRuntimeLibrary {
|
||||
InformationMark = 64,
|
||||
}
|
||||
|
||||
// tslint:disable-next-line no-const-enum
|
||||
const enum PopupType {
|
||||
SecondButtonDefault = 256,
|
||||
ThirdButtonDefault = 512,
|
||||
@@ -46,7 +44,6 @@ declare namespace IWshRuntimeLibrary {
|
||||
RTL = 1048576,
|
||||
}
|
||||
|
||||
// tslint:disable-next-line no-const-enum
|
||||
const enum PopupSelection {
|
||||
NoButton = -1,
|
||||
OK = 1,
|
||||
@@ -60,14 +57,12 @@ declare namespace IWshRuntimeLibrary {
|
||||
Continue = 11,
|
||||
}
|
||||
|
||||
// tslint:disable-next-line no-const-enum
|
||||
const enum WshExecStatus {
|
||||
WshFailed = 2,
|
||||
WshFinished = 1,
|
||||
WshRunning = 0,
|
||||
}
|
||||
|
||||
// tslint:disable-next-line no-const-enum
|
||||
const enum WshWindowStyle {
|
||||
WshHide = 0,
|
||||
WshMaximizedFocus = 3,
|
||||
@@ -77,24 +72,91 @@ declare namespace IWshRuntimeLibrary {
|
||||
WshNormalNoFocus = 4,
|
||||
}
|
||||
|
||||
class TextStream {
|
||||
private 'IWshRuntimeLibrary.TextStream_typekey': TextStream;
|
||||
private constructor();
|
||||
readonly AtEndOfLine: boolean;
|
||||
readonly AtEndOfStream: boolean;
|
||||
Close(): void;
|
||||
readonly Column: number;
|
||||
readonly Line: number;
|
||||
Read(Characters: number): string;
|
||||
ReadAll(): string;
|
||||
ReadLine(): string;
|
||||
Skip(Characters: number): void;
|
||||
SkipLine(): void;
|
||||
Write(Text: string): void;
|
||||
WriteBlankLines(Lines: number): void;
|
||||
class TextStreamBase {
|
||||
/**
|
||||
* The column number of the current character position in an input stream.
|
||||
*/
|
||||
Column: number;
|
||||
|
||||
/** @param string [Text=''] */
|
||||
WriteLine(Text?: string): void;
|
||||
/**
|
||||
* The current line number in an input stream.
|
||||
*/
|
||||
Line: number;
|
||||
|
||||
/**
|
||||
* Closes a text stream.
|
||||
* It is not necessary to close standard streams; they close automatically when the process ends. If
|
||||
* you close a standard stream, be aware that any other pointers to that standard stream become invalid.
|
||||
*/
|
||||
Close(): void;
|
||||
}
|
||||
|
||||
class TextStreamWriter extends TextStreamBase {
|
||||
private 'IWshRuntimeLibrary.TextStreamWriter_typekey': TextStreamWriter;
|
||||
private constructor();
|
||||
|
||||
/**
|
||||
* Sends a string to an output stream.
|
||||
*/
|
||||
Write(s: string): void;
|
||||
|
||||
/**
|
||||
* Sends a specified number of blank lines (newline characters) to an output stream.
|
||||
*/
|
||||
WriteBlankLines(intLines: number): void;
|
||||
|
||||
/**
|
||||
* Sends a string followed by a newline character to an output stream.
|
||||
*/
|
||||
WriteLine(s: string): void;
|
||||
}
|
||||
|
||||
class TextStreamReader extends TextStreamBase {
|
||||
private 'IWshRuntimeLibrary.TextStreamReader_typekey': TextStreamReader;
|
||||
private constructor();
|
||||
|
||||
/**
|
||||
* Returns a specified number of characters from an input stream, starting at the current pointer position.
|
||||
* Does not return until the ENTER key is pressed.
|
||||
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
|
||||
*/
|
||||
Read(characters: number): string;
|
||||
|
||||
/**
|
||||
* Returns all characters from an input stream.
|
||||
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
|
||||
*/
|
||||
ReadAll(): string;
|
||||
|
||||
/**
|
||||
* Returns an entire line from an input stream.
|
||||
* Although this method extracts the newline character, it does not add it to the returned string.
|
||||
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
|
||||
*/
|
||||
ReadLine(): string;
|
||||
|
||||
/**
|
||||
* Skips a specified number of characters when reading from an input text stream.
|
||||
* Can only be used on a stream in reading mode; causes an error in writing or appending mode.
|
||||
* @param characters Positive number of characters to skip forward. (Backward skipping is not supported.)
|
||||
*/
|
||||
Skip(characters: number): void;
|
||||
|
||||
/**
|
||||
* Skips the next line when reading from an input text stream.
|
||||
* Can only be used on a stream in reading mode, not writing or appending mode.
|
||||
*/
|
||||
SkipLine(): void;
|
||||
|
||||
/**
|
||||
* Indicates whether the stream pointer position is at the end of a line.
|
||||
*/
|
||||
AtEndOfLine: boolean;
|
||||
|
||||
/**
|
||||
* Indicates whether the stream pointer position is at the end of a stream.
|
||||
*/
|
||||
AtEndOfStream: boolean;
|
||||
}
|
||||
|
||||
/** Generic Collection Object */
|
||||
@@ -109,7 +171,7 @@ declare namespace IWshRuntimeLibrary {
|
||||
interface WshEnvironment {
|
||||
Count(): number;
|
||||
Item(Name: string): string;
|
||||
readonly length: number;
|
||||
readonly Length: number;
|
||||
Remove(Name: string): void;
|
||||
(Name: string): string;
|
||||
}
|
||||
@@ -121,9 +183,9 @@ declare namespace IWshRuntimeLibrary {
|
||||
readonly ExitCode: number;
|
||||
readonly ProcessID: number;
|
||||
readonly Status: WshExecStatus;
|
||||
readonly StdErr: TextStream;
|
||||
readonly StdIn: TextStream;
|
||||
readonly StdOut: TextStream;
|
||||
readonly StdErr: TextStreamWriter;
|
||||
readonly StdIn: TextStreamReader;
|
||||
readonly StdOut: TextStreamWriter;
|
||||
Terminate(): void;
|
||||
}
|
||||
|
||||
@@ -336,13 +398,40 @@ declare namespace IWshRuntimeLibrary {
|
||||
TargetPath: string;
|
||||
}
|
||||
}
|
||||
declare namespace WSHControllerLibrary {
|
||||
class WSHController {
|
||||
private 'WSHControllerLibrary.WSHController_typekey': WSHController;
|
||||
private constructor();
|
||||
CreateScript(Command: string, Server?: any): any;
|
||||
}
|
||||
}
|
||||
|
||||
interface ActiveXObject {
|
||||
set(obj: IWshRuntimeLibrary.WshEnvironment, propertyName: 'Item', parameterTypes: [string], newValue: string): void;
|
||||
new <K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
|
||||
declare namespace ScriptSigner {
|
||||
class Signer {
|
||||
private 'ScriptSigner.Signer_typekey': Signer;
|
||||
private constructor();
|
||||
|
||||
/** @param Store [Store='my'] */
|
||||
Sign(FileExtension: string, Text: string, Certificate: string, Store?: string): string;
|
||||
|
||||
/** @param Store [Store='my'] */
|
||||
SignFile(FileName: string, Certificate: string, Store?: string): void;
|
||||
|
||||
/** @param ShowUI [ShowUI=false] */
|
||||
Verify(FileExtension: string, Text: string, ShowUI?: boolean): boolean;
|
||||
|
||||
/** @param ShowUI [ShowUI=false] */
|
||||
VerifyFile(FileName: string, ShowUI?: boolean): boolean;
|
||||
}
|
||||
}
|
||||
|
||||
interface ActiveXObjectNameMap {
|
||||
'WSHController': WSHControllerLibrary.WSHController;
|
||||
'Scripting.Signer': ScriptSigner.Signer;
|
||||
'WScript.Network': IWshRuntimeLibrary.WshNetwork;
|
||||
'WScript.Shell': IWshRuntimeLibrary.WshShell;
|
||||
}
|
||||
|
||||
interface ActiveXObject {
|
||||
set(obj: IWshRuntimeLibrary.WshEnvironment, propertyName: 'Item', parameterTypes: [string], newValue: string): void;
|
||||
}
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"activex-helpers": "*"
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es5",
|
||||
"scripthost"
|
||||
"es5"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
@@ -21,4 +20,4 @@
|
||||
"index.d.ts",
|
||||
"activex-iwshruntimelibrary-tests.ts"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
{
|
||||
"extends": "dtslint/dt.json"
|
||||
"extends": "dtslint/dt.json",
|
||||
"rules": {
|
||||
"no-const-enum": false
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
/// <reference types="windows-script-host" />
|
||||
|
||||
(() => {
|
||||
// https://wiki.openoffice.org/wiki/Documentation/DevGuide/ProUNO/Bridge/Automation_Bridge
|
||||
|
||||
|
||||
Vendored
+3
-4
@@ -2,7 +2,9 @@
|
||||
// Project: https://api.libreoffice.org/
|
||||
// Definitions by: Zev Spitz <https://github.com/zspitz>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.3
|
||||
// TypeScript Version: 2.6
|
||||
|
||||
/// <reference types="activex-interop" />
|
||||
|
||||
declare class type {
|
||||
private typekey: type;
|
||||
@@ -12,9 +14,6 @@ declare class sequence<T = any> {
|
||||
private typekey: sequence<T>;
|
||||
}
|
||||
|
||||
// tslint:disable-next-line no-empty-interface
|
||||
interface SafeArray<T = any> {}
|
||||
|
||||
declare namespace com.sun.star {
|
||||
namespace accessibility {
|
||||
/**
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es5",
|
||||
"scripthost"
|
||||
"es5"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
|
||||
Vendored
+119
-2305
File diff suppressed because it is too large
Load Diff
@@ -2,8 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es5",
|
||||
"scripthost"
|
||||
"es5"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"extends": "dtslint/dt.json",
|
||||
"rules": {
|
||||
"no-const-enum": false
|
||||
"no-const-enum": false,
|
||||
"max-line-length": false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
/// <reference types="windows-script-host" />
|
||||
|
||||
let htmlfile = new ActiveXObject('htmlfile');
|
||||
let htmldoc = htmlfile.createDocumentFromUrl('https://msdn.microsoft.com/en-us/library/aa741317(v=vs.85).aspx', 'null');
|
||||
let length = htmldoc.all.length;
|
||||
|
||||
Vendored
+834
-1755
File diff suppressed because it is too large
Load Diff
@@ -2,8 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es5",
|
||||
"scripthost"
|
||||
"es5"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"extends": "dtslint/dt.json",
|
||||
"rules": {
|
||||
"no-const-enum": false
|
||||
"no-const-enum": false,
|
||||
"max-line-length": false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
/// <reference types="windows-script-host" />
|
||||
|
||||
// https://msdn.microsoft.com/en-us/library/ms764708(v=vs.85).aspx
|
||||
(() => {
|
||||
{
|
||||
const dom = new ActiveXObject('Msxml2.DOMDocument.6.0');
|
||||
dom.async = false;
|
||||
dom.resolveExternals = false;
|
||||
dom.loadXML('<a>A</a>');
|
||||
WScript.Echo(`dom: ${dom.xml}`);
|
||||
})();
|
||||
}
|
||||
|
||||
// https://msdn.microsoft.com/en-us/library/ms766390(v=vs.85).aspx
|
||||
(() => {
|
||||
{
|
||||
const doc = new ActiveXObject('Msxml2.DOMDocument.6.0');
|
||||
doc.load('test.xml');
|
||||
WScript.Echo(`doc: ${doc.xml}`);
|
||||
})();
|
||||
}
|
||||
|
||||
const MakeDOM = () => {
|
||||
try {
|
||||
@@ -37,7 +39,7 @@ const LoadDOM = (file: string) => {
|
||||
};
|
||||
|
||||
// https://msdn.microsoft.com/en-us/library/ms759105(v=vs.85).aspx
|
||||
(() => {
|
||||
{
|
||||
const doc = new ActiveXObject('Msxml2.DOMDocument.6.0');
|
||||
doc.async = false;
|
||||
doc.resolveExternals = false;
|
||||
@@ -60,10 +62,10 @@ const LoadDOM = (file: string) => {
|
||||
`;
|
||||
doc.loadXML(xml);
|
||||
doc.save('saved.xml');
|
||||
})();
|
||||
}
|
||||
|
||||
// https://msdn.microsoft.com/en-us/library/ms764656(v=vs.85).aspx
|
||||
(() => {
|
||||
{
|
||||
const doc = LoadDOM('test.xml')!;
|
||||
const xsl = (LoadDOM('test.xsl')! as any) as MSXML2.IXMLDOMNode;
|
||||
|
||||
@@ -73,10 +75,10 @@ const LoadDOM = (file: string) => {
|
||||
const out = MakeDOM()!;
|
||||
doc.transformNodeToObject(xsl, out);
|
||||
WScript.Echo('\ndoc.transformNodeToObject:\n' + out.xml);
|
||||
})();
|
||||
}
|
||||
|
||||
// https://msdn.microsoft.com/en-us/library/ms763685(v=vs.85).aspx
|
||||
(() => {
|
||||
{
|
||||
const dom = MakeDOM()!;
|
||||
|
||||
// Create a processing instruction targeted for xml.
|
||||
@@ -148,10 +150,10 @@ const LoadDOM = (file: string) => {
|
||||
|
||||
// Save the XML document to a file.
|
||||
dom.save("dynamDom.xml");
|
||||
})();
|
||||
}
|
||||
|
||||
// https://msdn.microsoft.com/en-us/library/ms757050(v=vs.85).aspx
|
||||
(() => {
|
||||
{
|
||||
const dom = LoadDOM("stocks.xml")!;
|
||||
try {
|
||||
// Query a single node.
|
||||
@@ -172,17 +174,17 @@ const LoadDOM = (file: string) => {
|
||||
} catch (e) {
|
||||
WScript.Echo(e.description);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
// https://msdn.microsoft.com/en-us/library/ms757064(v=vs.85).aspx
|
||||
(() => {
|
||||
{
|
||||
const xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0");
|
||||
xhr.open("GET", "http://localhost/sxh/contact.asp?SearchID=John Doe", false);
|
||||
xhr.send();
|
||||
|
||||
const doc = xhr.responseXML;
|
||||
WScript.Echo(doc.xml);
|
||||
})();
|
||||
}
|
||||
|
||||
const xmlValidation = (fn: (x: MSXML2.DOMDocument60) => void) => {
|
||||
// Create and initialize the DOMDocument object
|
||||
@@ -212,16 +214,16 @@ ${x.xml}
|
||||
};
|
||||
|
||||
// https://msdn.microsoft.com/en-us/library/ms766449(v=vs.85).aspx
|
||||
(() => {
|
||||
{
|
||||
const validateFile = (filename: string) => xmlValidation(x => x.load(filename));
|
||||
|
||||
let sOutput = validateFile("nn-valid.xml");
|
||||
sOutput = sOutput + validateFile("nn-notValid.xml");
|
||||
WScript.Echo(sOutput);
|
||||
})();
|
||||
}
|
||||
|
||||
// https://msdn.microsoft.com/en-us/library/ms767542(v=vs.85).aspx
|
||||
(() => {
|
||||
{
|
||||
const validateFile = (filename: string) => xmlValidation(x => {
|
||||
// Configure DOM properties for namespace selection.
|
||||
x.setProperty("SelectionLanguage", "XPath");
|
||||
@@ -235,10 +237,10 @@ ${x.xml}
|
||||
let sOutput = validateFile("sl-valid.xml");
|
||||
sOutput = sOutput + validateFile("sl-notValid.xml");
|
||||
WScript.Echo(sOutput);
|
||||
})();
|
||||
}
|
||||
|
||||
// https://msdn.microsoft.com/en-us/library/ms766439(v=vs.85).aspx
|
||||
(() => {
|
||||
{
|
||||
const validateFile = (filename: string) => xmlValidation(xd => {
|
||||
// Create a schema cache and add books.xsd to it.
|
||||
const xs = new ActiveXObject('Msxml2.XMLSchemaCache');
|
||||
@@ -253,10 +255,10 @@ ${x.xml}
|
||||
let sOutput = validateFile("sc-valid.xml");
|
||||
sOutput = sOutput + validateFile("sc-notValid.xml");
|
||||
WScript.Echo(sOutput);
|
||||
})();
|
||||
}
|
||||
|
||||
// https://msdn.microsoft.com/en-us/library/ms767636(v=vs.85).aspx
|
||||
(() => {
|
||||
{
|
||||
const validateFile = (filename: string) => xmlValidation(x => {
|
||||
x.setProperty("UseInlineSchema", true);
|
||||
x.load(filename);
|
||||
@@ -265,10 +267,10 @@ ${x.xml}
|
||||
let sOutput = validateFile("valid.xml");
|
||||
sOutput = sOutput + validateFile("notValid.xml");
|
||||
WScript.Echo(sOutput);
|
||||
})();
|
||||
}
|
||||
|
||||
// https://msdn.microsoft.com/en-us/library/ms757833(v=vs.85).aspx
|
||||
(() => {
|
||||
{
|
||||
// Load an XML document into a DOM instance.
|
||||
const oXMLDoc = LoadDOM("books.xml")!;
|
||||
|
||||
@@ -326,4 +328,4 @@ ${oError.reason}`;
|
||||
}
|
||||
WScript.Echo(msg);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
Vendored
+38
-41
@@ -2,7 +2,9 @@
|
||||
// Project: https://msdn.microsoft.com/en-us/library/ms763742.aspx
|
||||
// Definitions by: Zev Spitz <https://github.com/zspitz>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.3
|
||||
// TypeScript Version: 2.6
|
||||
|
||||
/// <reference types="activex-interop" />
|
||||
|
||||
declare namespace MSXML2 {
|
||||
/** Schema Object Model Content Types */
|
||||
@@ -424,7 +426,7 @@ declare namespace MSXML2 {
|
||||
createEntityReference(name: string): IXMLDOMEntityReference;
|
||||
|
||||
/** create a node of the specified node type and name */
|
||||
createNode(type: any, name: string, namespaceURI: string): IXMLDOMNode;
|
||||
createNode(type: DOMNodeType.NODE_ATTRIBUTE | DOMNodeType.NODE_CDATA_SECTION | DOMNodeType.NODE_COMMENT | DOMNodeType.NODE_DOCUMENT_FRAGMENT | DOMNodeType.NODE_TEXT | DOMNodeType.NODE_ELEMENT | DOMNodeType.NODE_ENTITY_REFERENCE | DOMNodeType.NODE_PROCESSING_INSTRUCTION, name: string, namespaceURI: string): IXMLDOMNode;
|
||||
|
||||
/** create a processing instruction node */
|
||||
createProcessingInstruction(target: string, data: string): IXMLDOMProcessingInstruction;
|
||||
@@ -433,7 +435,7 @@ declare namespace MSXML2 {
|
||||
createTextNode(data: string): IXMLDOMText;
|
||||
|
||||
/** the data type of the node */
|
||||
dataType: any;
|
||||
dataType: string | null;
|
||||
|
||||
/** pointer to the definition of the node in the DTD or schema */
|
||||
readonly definition: IXMLDOMNode;
|
||||
@@ -497,7 +499,7 @@ declare namespace MSXML2 {
|
||||
readonly nodeTypeString: string;
|
||||
|
||||
/** value stored in the node */
|
||||
nodeValue: any;
|
||||
nodeValue: string | null;
|
||||
|
||||
/** register an ondataavailable event handler */
|
||||
readonly ondataavailable: any;
|
||||
@@ -795,8 +797,7 @@ declare namespace MSXML2 {
|
||||
getAllResponseHeaders(ppwszHeaders: string): void;
|
||||
GetCookie(pwszUrl: string, pwszName: string, dwFlags: number, pcCookies: number, ppCookies: tagXHR_COOKIE): void;
|
||||
getResponseHeader(pwszHeader: string, ppwszValue: string): void;
|
||||
open(
|
||||
pwszMethod: string, pwszUrl: string, pStatusCallback: IXMLHTTPRequest2Callback, pwszUserName: string, pwszPassword: string, pwszProxyUserName: string, pwszProxyPassword: string): void;
|
||||
open(pwszMethod: string, pwszUrl: string, pStatusCallback: IXMLHTTPRequest2Callback, pwszUserName: string, pwszPassword: string, pwszProxyUserName: string, pwszProxyPassword: string): void;
|
||||
send(pBody: ISequentialStream, cbBody: number): void;
|
||||
SetCookie(pCookie: tagXHR_COOKIE, pdwCookieState: number): void;
|
||||
SetCustomResponseStream(pSequentialStream: ISequentialStream): void;
|
||||
@@ -805,11 +806,11 @@ declare namespace MSXML2 {
|
||||
}
|
||||
|
||||
/** IMXNamespacePrefixes interface */
|
||||
class IMXNamespacePrefixes {
|
||||
private 'MSXML2.IMXNamespacePrefixes_typekey': IMXNamespacePrefixes;
|
||||
private constructor();
|
||||
// tslint:disable-next-line:interface-name
|
||||
interface IMXNamespacePrefixes {
|
||||
item(index: number): string;
|
||||
readonly length: number;
|
||||
(index: number): string;
|
||||
}
|
||||
|
||||
/** XML Schema */
|
||||
@@ -848,21 +849,21 @@ declare namespace MSXML2 {
|
||||
}
|
||||
|
||||
/** XML Schema Item Collection */
|
||||
class ISchemaItemCollection {
|
||||
private 'MSXML2.ISchemaItemCollection_typekey': ISchemaItemCollection;
|
||||
private constructor();
|
||||
// tslint:disable-next-line:interface-name
|
||||
interface ISchemaItemCollection {
|
||||
item(index: number): ISchemaItem;
|
||||
itemByName(name: string): ISchemaItem;
|
||||
itemByQName(name: string, namespaceURI: string): ISchemaItem;
|
||||
readonly length: number;
|
||||
(index: number): ISchemaItem;
|
||||
}
|
||||
|
||||
/** XML Schema String Collection */
|
||||
class ISchemaStringCollection {
|
||||
private 'MSXML2.ISchemaStringCollection_typekey': ISchemaStringCollection;
|
||||
private constructor();
|
||||
// tslint:disable-next-line:interface-name
|
||||
interface ISchemaStringCollection {
|
||||
item(index: number): string;
|
||||
readonly length: number;
|
||||
(index: number): string;
|
||||
}
|
||||
|
||||
class ISequentialStream {
|
||||
@@ -1960,10 +1961,8 @@ declare namespace MSXML2 {
|
||||
hasFeature(feature: string, version: string): boolean;
|
||||
}
|
||||
|
||||
class IXMLDOMNamedNodeMap {
|
||||
private 'MSXML2.IXMLDOMNamedNodeMap_typekey': IXMLDOMNamedNodeMap;
|
||||
private constructor();
|
||||
|
||||
// tslint:disable-next-line:interface-name
|
||||
interface IXMLDOMNamedNodeMap {
|
||||
/** lookup item by name */
|
||||
getNamedItem(name: string): IXMLDOMNode;
|
||||
|
||||
@@ -1990,6 +1989,9 @@ declare namespace MSXML2 {
|
||||
|
||||
/** set item by name */
|
||||
setNamedItem(newItem: IXMLDOMNode): IXMLDOMNode;
|
||||
|
||||
/** collection of nodes */
|
||||
(index: number): IXMLDOMNode;
|
||||
}
|
||||
|
||||
/** Core DOM node interface */
|
||||
@@ -2090,10 +2092,8 @@ declare namespace MSXML2 {
|
||||
readonly xml: string;
|
||||
}
|
||||
|
||||
class IXMLDOMNodeList {
|
||||
private 'MSXML2.IXMLDOMNodeList_typekey': IXMLDOMNodeList;
|
||||
private constructor();
|
||||
|
||||
// tslint:disable-next-line:interface-name
|
||||
interface IXMLDOMNodeList {
|
||||
/** collection of nodes */
|
||||
item(index: number): IXMLDOMNode;
|
||||
|
||||
@@ -2105,6 +2105,9 @@ declare namespace MSXML2 {
|
||||
|
||||
/** reset the position of iterator */
|
||||
reset(): void;
|
||||
|
||||
/** collection of nodes */
|
||||
(index: number): IXMLDOMNode;
|
||||
}
|
||||
|
||||
/** structure for reporting parser errors */
|
||||
@@ -2238,10 +2241,8 @@ declare namespace MSXML2 {
|
||||
}
|
||||
|
||||
/** XML Schemas Collection */
|
||||
class IXMLDOMSchemaCollection {
|
||||
private 'MSXML2.IXMLDOMSchemaCollection_typekey': IXMLDOMSchemaCollection;
|
||||
private constructor();
|
||||
|
||||
// tslint:disable-next-line:interface-name
|
||||
interface IXMLDOMSchemaCollection {
|
||||
/** add a new schema */
|
||||
add(namespaceURI: string, var_1: any): void;
|
||||
|
||||
@@ -2259,6 +2260,9 @@ declare namespace MSXML2 {
|
||||
|
||||
/** remove schema by namespaceURI */
|
||||
remove(namespaceURI: string): void;
|
||||
|
||||
/** Get namespaceURI for schema by index */
|
||||
(index: number): string;
|
||||
}
|
||||
|
||||
class IXMLDOMText {
|
||||
@@ -2403,7 +2407,7 @@ declare namespace MSXML2 {
|
||||
|
||||
/**
|
||||
* set <xsl:param> values
|
||||
* @param string [namespaceURI='']
|
||||
* @param namespaceURI [namespaceURI='0']
|
||||
*/
|
||||
addParameter(baseName: string, parameter: any, namespaceURI?: string): void;
|
||||
|
||||
@@ -2424,7 +2428,7 @@ declare namespace MSXML2 {
|
||||
|
||||
/**
|
||||
* set XSL mode and it's namespace
|
||||
* @param string [namespaceURI='']
|
||||
* @param namespaceURI [namespaceURI='0']
|
||||
*/
|
||||
setStartMode(mode: string, namespaceURI?: string): void;
|
||||
|
||||
@@ -2487,7 +2491,7 @@ declare namespace MSXML2 {
|
||||
popContext(): void;
|
||||
pushContext(): void;
|
||||
|
||||
/** @param boolean [fDeep=true] */
|
||||
/** @param fDeep [fDeep=true] */
|
||||
pushNodeContext(contextNode: IXMLDOMNode, fDeep?: boolean): void;
|
||||
reset(): void;
|
||||
}
|
||||
@@ -2730,10 +2734,7 @@ declare namespace MSXML2 {
|
||||
}
|
||||
|
||||
/** XML Schema Cache 6.0 */
|
||||
class XMLSchemaCache60 {
|
||||
private 'MSXML2.XMLSchemaCache60_typekey': XMLSchemaCache60;
|
||||
private constructor();
|
||||
|
||||
interface XMLSchemaCache60 {
|
||||
/** add a new schema */
|
||||
add(namespaceURI: string, var_1: any): void;
|
||||
|
||||
@@ -2755,6 +2756,9 @@ declare namespace MSXML2 {
|
||||
remove(namespaceURI: string): void;
|
||||
validate(): void;
|
||||
validateOnLoad: boolean;
|
||||
|
||||
/** Get namespaceURI for schema by index */
|
||||
(index: number): string;
|
||||
}
|
||||
|
||||
/** XSL Stylesheet Cache 6.0 */
|
||||
@@ -2773,7 +2777,6 @@ declare namespace MSXML2 {
|
||||
interface ActiveXObject {
|
||||
on(obj: MSXML2.DOMDocument60, event: 'ondataavailable' | 'onreadystatechange', handler: (this: MSXML2.DOMDocument60, parameter: {}) => void): void;
|
||||
on(obj: MSXML2.FreeThreadedDOMDocument60, event: 'ondataavailable' | 'onreadystatechange', handler: (this: MSXML2.FreeThreadedDOMDocument60, parameter: {}) => void): void;
|
||||
new<K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
|
||||
}
|
||||
|
||||
interface ActiveXObjectNameMap {
|
||||
@@ -2787,12 +2790,6 @@ interface ActiveXObjectNameMap {
|
||||
'Msxml2.SAXXMLReader': MSXML2.SAXXMLReader60;
|
||||
'Msxml2.ServerXMLHTTP': MSXML2.ServerXMLHTTP60;
|
||||
'Msxml2.XMLHTTP': MSXML2.XMLHTTP60;
|
||||
'Msxml2.XMLHTTP.6.0': MSXML2.XMLHTTP60;
|
||||
'Msxml2.XMLSchemaCache': MSXML2.XMLSchemaCache60;
|
||||
'Msxml2.XMLSchemaCache.6.0': MSXML2.XMLSchemaCache60;
|
||||
'Msxml2.XSLTemplate': MSXML2.XSLTemplate60;
|
||||
}
|
||||
|
||||
interface SafeArray<T = any> {
|
||||
_brand: SafeArray<T>;
|
||||
}
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es5",
|
||||
"scripthost"
|
||||
"es5"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"extends": "dtslint/dt.json",
|
||||
"rules": {
|
||||
"no-const-enum": false
|
||||
"no-const-enum": false,
|
||||
"max-line-length": false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,27 @@
|
||||
/// <reference types="windows-script-host" />
|
||||
/// <reference types="activex-word" />
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
let app = new ActiveXObject('Word.Application');
|
||||
app.Visible = true;
|
||||
let dlg = app.FileDialog(Office.MsoFileDialogType.msoFileDialogFolderPicker);
|
||||
dlg.AllowMultiSelect = true;
|
||||
dlg.Title = 'Select one or more folders';
|
||||
dlg.Execute();
|
||||
let enumerator = new Enumerator(dlg.SelectedItems);
|
||||
enumerator.moveFirst();
|
||||
while (!enumerator.atEnd()) {
|
||||
WScript.Echo(enumerator.item);
|
||||
for (const item of collectionToArray(dlg.SelectedItems)) {
|
||||
WScript.Echo(item);
|
||||
}
|
||||
|
||||
let enumerator2 = new Enumerator(app.COMAddIns);
|
||||
enumerator2.moveFirst();
|
||||
while (!enumerator2.atEnd()) {
|
||||
const item = enumerator2.item();
|
||||
for (const item of collectionToArray(app.COMAddIns)) {
|
||||
WScript.Echo(`COM Addin: ${item.Description} -- ${item.ProgId}`);
|
||||
}
|
||||
|
||||
Vendored
+604
-512
File diff suppressed because it is too large
Load Diff
@@ -2,8 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es5",
|
||||
"scripthost"
|
||||
"es5"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user