Merge with master

This commit is contained in:
Matt Lewis
2017-12-18 10:19:33 +00:00
22324 changed files with 1482031 additions and 585830 deletions
+1 -1
View File
@@ -1,9 +1,9 @@
root = true
[*]
indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true
[{*.json,*.yml}]
indent_style = space
indent_size = 2
+3760
View File
File diff suppressed because it is too large Load Diff
+4
View File
@@ -1,5 +1,9 @@
If you know how to fix the issue, make a pull request instead.
- [ ] I tried using the `@types/xxxx` package and had problems.
- [ ] I tried using the latest stable version of tsc. https://www.npmjs.com/package/typescript
- [ ] I have a question that is inappropriate for [StackOverflow](https://stackoverflow.com/). (Please ask any appropriate questions there).
- [ ] [Mention](https://github.com/blog/821-mention-somebody-they-re-notified) the authors (see `Definitions by:` in `index.d.ts`) so they can respond.
- Authors: @....
If you do not mention the authors the issue will be ignored.
+2 -2
View File
@@ -12,12 +12,12 @@ If adding a new definition:
- [ ] The package does not provide its own types, and you can not add them.
- [ ] If this is for an NPM package, match the name. If not, do not conflict with the name of an NPM package.
- [ ] Create it with `dts-gen --dt`, not by basing it on an existing project.
- [ ] `tslint.json` should be present, and `tsconfig.json` should have `noImplicitAny`, `noImplicitThis`, and `strictNullChecks` set to `true`.
- [ ] `tslint.json` should be present, and `tsconfig.json` should have `noImplicitAny`, `noImplicitThis`, `strictNullChecks`, and `strictFunctionTypes` set to `true`.
If changing an existing definition:
- [ ] Provide a URL to documentation or source code which provides context for the suggested changes: <<url here>>
- [ ] Increase the version number in the header if appropriate.
- [ ] If you are making substantial changes, consider adding a `tslint.json` containing `{ "extends": "../tslint.json" }`.
- [ ] If you are making substantial changes, consider adding a `tslint.json` containing `{ "extends": "dtslint/dt.json" }`.
If removing a declaration:
- [ ] If a package was never on DefinitelyTyped, you don't need to do anything. (If you wrote a package and provided types, you don't need to register it with us.)
+10 -2
View File
@@ -12,7 +12,6 @@
*.map
*.swp
.DS_Store
npm-debug.log
_Resharper.DefinitelyTyped
bin
@@ -25,19 +24,28 @@ Properties
# test folder
_infrastructure/tests/build
# IntelliJ based IDEs
.idea
*.iml
*.js.map
!*.js/
!scripts/new-package.js
!scripts/not-needed.js
!scripts/lint.js
# npm
node_modules
package-lock.json
npm-debug.log
# Sublime
.sublimets
.settings/launch.json
# Visual Studio Code
.settings/launch.json
.vs
.vscode
# yarn
yarn.lock
+1 -1
View File
@@ -1,6 +1,6 @@
language: node_js
node_js:
- node
- 8
sudo: false
+68 -15
View File
@@ -1,4 +1,4 @@
# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.png?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
[![Join the chat at https://gitter.im/borisyankov/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
@@ -38,7 +38,7 @@ or just look for any ".d.ts" files in the package and manually include them with
These can be used by TypeScript 1.0.
* [Typings](https://github.com/typings/typings)
* ~~[NuGet](http://nuget.org/Tpackages?q=DefinitelyTyped)~~ (use preferred alternatives, nuget DT type publishing has been turned off)
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (use preferred alternatives, nuget DT type publishing has been turned off)
* Manually download from the `master` branch of this repository
You may need to add manual [references](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).
@@ -71,7 +71,9 @@ Add to your `tsconfig.json`:
Create `types/foo/index.d.ts` containing declarations for the module "foo".
You should now be able import from `"foo"` in your code and it will route to the new type definition.
Then build *and* run the code to make sure your type definition actually corresponds to what happens at runtime.
Once you've tested your definitions with real code, make a PR contributing the definition by copying `types/foo` to `DefinitelyTyped/foo` and adding a `tsconfig.json` and `foo-tests.ts`.
Once you've tested your definitions with real code, make a [PR](#make-a-pull-request)
then follow the instructions to [edit an existing package](#edit-an-existing-package) or
[create a new package](#create-a-new-package).
### Make a pull request
@@ -83,11 +85,19 @@ First, [fork](https://guides.github.com/activities/forking/) this repository, in
#### Edit an existing package
* `cd my-package-to-edit`
* `cd types/my-package-to-edit`
* Make changes. Remember to edit tests.
* 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>`.
* `npm install -g typescript@2.0` and run `tsc`.
- Or if there are more people, it can be multiline
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* If there is a `tslint.json`, run `npm run lint package-name`. Otherwise, run `tsc` in the package directory.
When you make a PR to edit an existing package, `dt-bot` should @-mention previous authors.
If it doesn't, you can do so yourself in the comment associated with the PR.
@@ -124,6 +134,7 @@ For a good example package, see [base64-js](https://github.com/DefinitelyTyped/D
* First, follow advice from the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html).
* Formatting: Either use all tabs, or always use 4 spaces.
* `function sum(nums: number[]): number`: Use `ReadonlyArray` if a function does not write to its parameters.
* `interface Foo { new(): Foo; }`:
This defines a type of objects that are new-able. You probably want `declare class Foo { constructor(); }`.
* `const Class: { new(): IClass; }`:
@@ -134,6 +145,10 @@ For a good example package, see [base64-js](https://github.com/DefinitelyTyped/D
Example where a type parameter is acceptable: `function id<T>(value: T): T;`.
Example where it is not acceptable: `function parseJson<T>(json: string): T;`.
Exception: `new Map<string, number>()` is OK.
* Using the types `Function` and `Object` is almost never a good idea. In 99% of cases it's possible to specify a more specific type. Examples are `(x: number) => number` for [functions](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) and `{ x: number, y: number }` for objects. If there is no certainty at all about the type, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) is the right choice, not `Object`. If the only known fact about the type is that it's some object, use the type [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), not `Object` or `{ [key: string]: any }`.
* `var foo: string | any`:
When `any` is used in a union type, the resulting type is still `any`. So while the `string` portion of this type annotation may _look_ useful, it in fact offers no additional typechecking over simply using `any`.
Depending on the intention, acceptable alternatives could be `any`, `string`, or `string | object`.
#### Removing a package
@@ -153,21 +168,33 @@ 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": "../tslint.json" }`. All new packages must be linted.
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:
```js
{
"extends": "../tslint.json",
"extends": "dtslint/dt.json",
"rules": {
// This package uses the Function type, and it will take effort to fix.
"forbidden-types": false
"ban-types": false
}
}
```
(To indicate that a lint rule truly does not apply, use `// tslint:disable rule-name` or better, `//tslint:disable-next-line rule-name`.)
To assert that an expression is of a given type, use `$ExpectType`. To assert that an expression causes a compile error, use `$ExpectError`.
```js
// $ExpectType void
f(1);
// $ExpectError
f("one");
```
For more details, see [dtslint](https://github.com/Microsoft/dtslint#write-tests) readme.
Test by running `npm run lint package-name` where `package-name` is the name of your package.
This script uses [dtslint](https://github.com/Microsoft/dtslint).
@@ -177,18 +204,20 @@ This script uses [dtslint](https://github.com/Microsoft/dtslint).
#### What exactly is the relationship between this repository and the `@types` packages on NPM?
The `master` branch is automatically published to the `@types` scope on NPM thanks to [types-publisher](https://github.com/Microsoft/types-publisher).
This usually happens within an hour of changes being merged.
#### I've submitted a pull request. How long until it is merged?
It depends, but most pull requests will be merged within a week. PRs that have been approved by an author listed in the definition's header are usually merged more quickly; PRs for new definitions will take more time as they require more review from maintainers. Each PR is reviewed by a TypeScript or DefinitelyTyped team member before being merged, so please be patient as human factors may cause delays. Check the [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) to see progress as maintainers work through the open PRs.
#### My PR is merged; when will the `@types` NPM package be updated?
NPM packages should update within a few hours. If it's been more than 24 hours, ping @RyanCavanaugh and @andy-ms on the PR to investigate.
#### I'm writing a definition that depends on another definition. Should I use `<reference types="" />` or an import?
If the module you're referencing is an external module (uses `export`), use an import.
If the module you're referencing is an ambient module (uses `declare module`, or just declares globals), use `<reference types="" />`.
#### What do I do about older versions of typings?
Currently we don't support this, though it is [planned](https://github.com/Microsoft/types-publisher/issues/3).
If you're adding a new major version of a library, you can copy `index.d.ts` to `foo-v2.3.d.ts` and edit `index.d.ts` to be the new version.
#### I notice some packages having a `package.json` here.
Usually you won't need this. When publishing a package we will normally automatically create a `package.json` for it.
@@ -214,7 +243,7 @@ If default imports work in your environment, consider turning on the [`--allowSy
Do not change the type definition if it is accurate.
For an NPM package, `export =` is accurate if `node -p 'require("foo")'` is the export, and `export default` is accurate if `node -p 'require("foo").default'` is the export.
#### I want to use features from TypeScript 2.1.
#### I want to use features from TypeScript 2.1 or above.
Then you will have to add a comment to the last line of your definition header (after `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// TypeScript Version: 2.1`.
@@ -256,6 +285,30 @@ transitively `react-router-bootstrap` (which depends on `react-router`) also add
Also, `/// <reference types=".." />` will not work with path mapping, so dependencies must use `import`.
#### How do I write definitions for packages that can be used globally and as a module?
The TypeScript handbook contains excellent [general information about writing definitions](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), and also [this example definition file](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) which shows how to create a definition using ES6-style module syntax, while also specifying objects made available to the global scope. This technique is demonstrated practically in the [definition for big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), which is a library that can be loaded globally via script tag on a web page, or imported via require or ES6-style imports.
To test how your definition can be used both when referenced globally or as an imported module, create a `test` folder, and place two test files in there. Name one `YourLibraryName-global.test.ts` and the other `YourLibraryName-module.test.ts`. The *global* test file should exercise the definition according to how it would be used in a script loaded on a web page where the library is available on the global scope - in this scenario you should not specify an import statement. The *module* test file should exercise the definition according to how it would be used when imported (including the `import` statement(s)). If you specify a `files` property in your `tsconfig.json` file, be sure to include both test files. A [practical example of this](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) is also available on the big.js definition.
Please note that it is not required to fully exercise the definition in each test file - it is sufficient to test only the globally-accessible elements on the global test file and fully exercise the definition in the module test file, or vice versa.
#### What about scoped packages?
Types for a scoped package `@foo/bar` should go in `types/foo__bar`. Note the double underscore.
When `dts-gen` is used to scaffold a scoped package, the `paths` property has to be manually adapted in the generated
`tsconfig.json` to correctly reference the scoped package:
```json
{
"paths":{
"@foo/bar": ["foo__bar"]
}
}
```
#### The file history in GitHub looks incomplete.
GitHub doesn't [support](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) file history for renamed files. Use [`git log --follow`](https://www.git-scm.com/docs/git-log) instead.
-1380
View File
File diff suppressed because it is too large Load Diff
-388
View File
@@ -1,388 +0,0 @@
/*
* Test file for node-jose. At this time these tests were taken verbatim
* from the documentation on the NPM page at
* https://www.npmjs.com/package/node-jose
* This file definitely needs to be cleaned up and more tests added to
* test the entirety of the definition file.
*/
import * as jose from 'node-jose';
let keystore = jose.JWK.createKeyStore();
let buf = new Buffer('a');
jose.JWK.asKeyStore("{key: somekey}").
then(function (result) {
// {result} is a jose.JWK.KeyStore
keystore = result;
});
let output = keystore.toJSON();
output = keystore.toJSON(true);
// by 'kid'
let kid: string = "someID";
let key = keystore.get(kid);
// ... and by 'kty'
key = keystore.get(kid, { kty: 'RSA' });
// ... and by 'use'
key = keystore.get(kid, { use: 'enc' });
// ... and by 'alg'
key = keystore.get(kid, { use: 'RSA-OAEP' });
// ... and by 'kty' and 'use'
key = keystore.get(kid, { kty: 'RSA', use: 'enc' });
// same as above, but with a single {props} argument
key = keystore.get({ kid: kid, kty: 'RSA', use: 'enc' });
// searching for keys
let everything = keystore.all();
// filter by 'kid'
everything = keystore.all({ kid: kid });
// filter by 'kty'
everything = keystore.all({ kty: 'RSA' });
// filter by 'use'
everything = keystore.all({ use: 'enc' });
// filter by 'alg'
everything = keystore.all({ alg: 'RSA-OAEP' });
// filter by 'kid' + 'kty' + 'alg'
everything = keystore.all({ kid: kid, kty: 'RSA', alg: 'RSA-OAEP' });
// input is either a:
// * jose.JWK.Key to copy from; or
// * JSON object representing a JWK; or
keystore.add({}).
then(function (result) {
// {result} is a jose.JWK.Key
key = result;
});
// input is either a:
// * String serialization of a JSON JWK/(base64-encoded) PEM/(binary-encoded) DER
// * Buffer of a JSON JWK/(base64-encoded) PEM/(binary-encoded) DER
// form is either a:
// * "json" for a JSON stringified JWK
// * "private" for a DER encoded 'raw' private key
// * "pkcs8" for a DER encoded (unencrypted!) PKCS8 private key
// * "public" for a DER encoded SPKI public key (alternate to 'spki')
// * "spki" for a DER encoded SPKI public key
// * "pkix" for a DER encoded PKIX X.509 certificate
// * "x509" for a DER encoded PKIX X.509 certificate
// * "pem" for a PEM encoded of PKCS8 / SPKI / PKIX
keystore.add(buf, "json").
then(function (result) {
// {result} is a jose.JWK.Key
key = result;
});
// first argument is the key type (kty)
// second is the key size (in bits) or named curve ('crv') for "EC"
keystore.generate("oct", 256).
then(function (result) {
// {result} is a jose.JWK.Key
key = result;
});
// ... with properties
var props = {
kid: 'gBdaS-G8RLax2qgObTD94w',
alg: 'A256GCM',
use: 'enc'
};
keystore.generate("oct", 256, props).
then(function (result) {
// {result} is a jose.JWK.Key
key = result;
});
keystore.remove(key);
// NOTE: key.keystore does not change!!
// where input is either a:
// * jose.JWK.Key instance
// * JSON Object representation of a JWK
jose.JWK.asKey({}).
then(function (result) {
// {result} is a jose.JWK.Key
// {result.keystore} is a unique jose.JWK.KeyStore
key = result;
});
// where input is either a:
// * String serialization of a JSON JWK/(base64-encoded) PEM/(binary-encoded) DER
// * Buffer of a JSON JWK/(base64-encoded) PEM/(binary-encoded) DER
// form is either a:
// * "json" for a JSON stringified JWK
// * "pkcs8" for a DER encoded (unencrypted!) PKCS8 private key
// * "spki" for a DER encoded SPKI public key
// * "pkix" for a DER encoded PKIX X.509 certificate
// * "x509" for a DER encoded PKIX X.509 certificate
// * "pem" for a PEM encoded of PKCS8 / SPKI / PKIX
jose.JWK.asKey({}, 'json').
then(function (result) {
// {result} is a jose.JWK.Key
// {result.keystore} is a unique jose.JWK.KeyStore
key = result;
});
output = key.toJSON();
output = key.toJSON(true);
// where hash is a supported algorithm, currently one of:
// * SHA-1
// * SHA-256
// * SHA-384
// * SHA-512
key.thumbprint('SHA-1').
then(function (print) {
// {print} is a Buffer containing the thumbprint binary value
});
// {input} is a Buffer
jose.JWS.createSign(key).
update(buf).
final().
then(function (result) {
// {result} is a JSON object -- JWS using the JSON General Serialization
});
jose.JWS.createSign({ format: 'flattened' }, key).
update(buf).
final().
then(function (result) {
// {result} is a JSON object -- JWS using the JSON Flattened Serialization
});
jose.JWS.createSign({ format: 'compact' }, key).
update(buf).
final().
then(function (result) {
// {result} is a String -- JWS using the Compact Serialization
});
jose.JWS.createSign({ alg: 'PS256' }, key).
update(buf).
final().
then(function (result) {
// ....
});
jose.JWS.createSign({ fields: { cty: 'jwk+json' } }, key).
update(buf).
final().
then(function (result) {
// ....
});
jose.JWS.createSign(key).
update(buf, "utf8").
final().
then(function (result) {
// ....
});
// {keys} is an Array of jose.JWK.Key instances
jose.JWS.createSign([key, key]).
update(buf).
final().
then(function (result) {
// ....
});
jose.JWS.createVerify(keystore).
verify("some.jws.object").
then(function (result) {
// {result} is a Object with:
// * header: the combined 'protected' and 'unprotected' header members
// * payload: Buffer of the signed content
// * signature: Buffer of the verified signature
// * key: The key used to verify the signature
});
// {key} can be:
// * jose.JWK.Key
// * JSON object representing a JWK
jose.JWS.createVerify(key).
verify('some.jws.object').
then(function (result) {
// ...
});
jose.JWS.createVerify().
verify('some.jws.key').
then(function (result) {
// ...
});
var opts = {
handlers: {
"exp": true
}
};
jose.JWS.createVerify(key, opts).
verify('some.jws.key').
then(function (result) {
// ...
});
var opts2 = {
handlers: {
"exp": function (jws: any) {
// {jws} is the JWS verify output, pre-verification
jws.header.exp = new Date(jws.header.exp);
}
}
};
jose.JWS.createVerify(key, opts2).
verify('some.jws.key').
then(function (result) {
// ...
});
var opts3 = {
handlers: {
"exp": {
complete: function (jws: any) {
// {jws} is the JWS verify output, post-verification
jws.header.exp = new Date(jws.header.exp);
}
}
}
};
jose.JWS.createVerify(key, opts3).
verify('some.jws.key').
then(function (result) {
// ...
});
//Encryption
// {input} is a Buffer
jose.JWE.createEncrypt(key).
update(buf).
final().
then(function (result) {
// {result} is a JSON Object -- JWE using the JSON General Serialization
});
jose.JWE.createEncrypt({ format: 'compact' }, key).
update(buf).
final().
then(function (result) {
// {result} is a String -- JWE using the Compact Serialization
});
jose.JWE.createEncrypt({ format: 'flattened' }, key).
update(buf).
final().
then(function (result) {
// {result} is a JSON Object -- JWE using the JSON Flattened Serialization
});
jose.JWE.createEncrypt({ zip: true }, key).
update(buf).
final().
then(function (result) {
// ....
});
jose.JWE.createEncrypt({ fields: { cty: 'jwk+json' } }, key).
update(buf).
final().
then(function (result) {
// ....
});
// {keys} is an Array of jose.JWK.Key instances
jose.JWE.createEncrypt([key, key]).
update(buf).
final().
then(function (result) {
// ....
});
jose.JWE.createDecrypt(keystore).
decrypt('some.jwe').
then(function (result) {
// {result} is a Object with:
// * header: the combined 'protected' and 'unprotected' header members
// * protected: an array of the member names from the "protected" member
// * key: Key used to decrypt
// * payload: Buffer of the decrypted content
// * plaintext: Buffer of the decrypted content (alternate)
});
jose.JWE.createDecrypt(key).
decrypt('some.jwe').
then(function (result) {
// ....
});
var opts4 = {
handlers: {
"exp": true
}
};
jose.JWE.createDecrypt(key, opts4).
decrypt('some.jwe').
then(function (result) {
// ...
});
//To perform additional (pre-decrypt) processing on a crit header member:
var opts5 = {
handlers: {
"exp": function (jwe: any) {
// {jwe} is the JWE decrypt output, pre-decryption
jwe.header.exp = new Date(jwe.header.exp);
}
}
};
jose.JWE.createDecrypt(key, opts5).
decrypt('some.jwe').
then(function (result) {
// ...
});
//To perform additional (post-decrypt) processing on a crit header member:
var opts6 = {
handlers: {
"exp": {
complete: function (jwe: any) {
// {jwe} is the JWE decrypt output, post-decryption
jwe.header.exp = new Date(jwe.header.exp);
}
}
}
};
jose.JWE.createDecrypt(key, opts6).
decrypt('some.jwe').
then(function (result) {
// ...
});
var buff = jose.util.asBuffer('input');
var output2 = jose.util.base64url.encode(buf);
// explicit encoding
output2 = jose.util.base64url.encode(buf, "utf8");
// implied "utf8" encoding
output2 = jose.util.base64url.encode(buf);
var output3 = jose.util.base64url.decode('input');
// argument is size (in bytes)
var rnd = jose.util.randomBytes(32);
-22
View File
@@ -1,22 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"node-jose-tests.ts"
]
}
+426
View File
@@ -1,29 +1,113 @@
{
"packages": [
{
"libraryName": "3d-bin-packing",
"typingsPackageName": "3d-bin-packing",
"sourceRepoURL": "https://github.com/betterwaysystems/packer",
"asOfVersion": "1.1.3"
},
{
"libraryName": "ag-grid",
"typingsPackageName": "ag-grid",
"sourceRepoURL": "https://github.com/ceolter/ag-grid",
"asOfVersion": "3.2.0"
},
{
"libraryName": "ajv",
"typingsPackageName": "ajv",
"sourceRepoURL": "https://github.com/epoberezkin/ajv",
"asOfVersion": "1.0.0"
},
{
"libraryName": "angular-ui-router-default",
"typingsPackageName": "angular-ui-router-default",
"sourceRepoURL": "https://github.com/nonplus/angular-ui-router-default",
"asOfVersion": "0.0.5"
},
{
"libraryName": "angular-ui-router-uib-modal",
"typingsPackageName": "angular-ui-router-uib-modal",
"sourceRepoURL": "https://github.com/nonplus/angular-ui-router-uib-modal",
"asOfVersion": "0.0.11"
},
{
"libraryName": "antd",
"typingsPackageName": "antd",
"sourceRepoURL": "https://github.com/ant-design/ant-design",
"asOfVersion": "1.0.0"
},
{
"libraryName": "anydb-sql",
"typingsPackageName": "anydb-sql",
"sourceRepoURL": "https://github.com/doxout/anydb-sql",
"asOfVersion": "0.6.46"
},
{
"libraryName": "apn",
"typingsPackageName": "apn",
"sourceRepoURL": "https://github.com/node-apn/node-apn",
"asOfVersion": "2.1.2"
},
{
"libraryName": "Argon2",
"typingsPackageName": "argon2",
"sourceRepoURL": "https://github.com/ranisalt/node-argon2",
"asOfVersion": "0.15.0"
},
{
"libraryName": "askmethat-rating",
"typingsPackageName": "askmethat-rating",
"sourceRepoURL": "https://github.com/AlexTeixeira/Askmethat-Rating",
"asOfVersion": "0.4.0"
},
{
"libraryName": "autobind-decorator",
"typingsPackageName": "autobind-decorator",
"sourceRepoURL": "https://github.com/andreypopp/autobind-decorator",
"asOfVersion": "2.1.0"
},
{
"libraryName": "aws-sdk",
"typingsPackageName": "aws-sdk",
"sourceRepoURL": "https://github.com/aws/aws-sdk-js",
"asOfVersion": "2.7.0"
},
{
"libraryName": "axe-core",
"typingsPackageName": "axe-core",
"sourceRepoURL": "https://github.com/dequelabs/axe-core",
"asOfVersion": "2.0.7"
},
{
"libraryName": "axios",
"typingsPackageName": "axios",
"sourceRepoURL": "https://github.com/mzabriskie/axios",
"asOfVersion": "0.14.0"
},
{
"libraryName": "azure-mobile-apps",
"typingsPackageName": "azure-mobile-apps",
"sourceRepoURL": "https://github.com/Azure/azure-mobile-apps-node/",
"asOfVersion": "3.0.0"
},
{
"libraryName": "BabylonJS",
"typingsPackageName": "babylonjs",
"sourceRepoURL": "http://www.babylonjs.com/",
"asOfVersion": "2.4.1"
},
{
"libraryName": "base64url",
"typingsPackageName": "base64url",
"sourceRepoURL": "https://github.com/brianloveswords/base64url",
"asOfVersion": "2.0.0"
},
{
"libraryName": "BigInteger.js",
"typingsPackageName": "big-integer",
"sourceRepoURL": "https://github.com/peterolson/BigInteger.js",
"asOfVersion": "0.0.31"
},
{
"libraryName": "Bugsnag Browser",
"typingsPackageName": "bugsnag-js",
@@ -36,6 +120,12 @@
"sourceRepoURL": "https://github.com/blakeembrey/camel-case",
"asOfVersion": "1.2.1"
},
{
"libraryName": "chalk",
"typingsPackageName": "chalk",
"sourceRepoURL": "https://github.com/chalk/chalk",
"asOfVersion": "2.2.0"
},
{
"libraryName": "change-case",
"typingsPackageName": "change-case",
@@ -48,6 +138,12 @@
"sourceRepoURL": "https://github.com/mapbox/cheap-ruler",
"asOfVersion": "2.5.0"
},
{
"libraryName": "commander",
"typingsPackageName": "commander",
"sourceRepoURL": "https://github.com/tj/commander.js",
"asOfVersion": "2.12.2"
},
{
"libraryName": "constant-case",
"typingsPackageName": "constant-case",
@@ -60,6 +156,12 @@
"sourceRepoURL": "https://github.com/date-fns/date-fns",
"asOfVersion": "2.6.0"
},
{
"libraryName": "DevExtreme",
"typingsPackageName": "devextreme",
"sourceRepoURL": "http://js.devexpress.com/",
"asOfVersion": "16.2.1"
},
{
"libraryName": "Dexie.js",
"typingsPackageName": "dexie",
@@ -84,6 +186,48 @@
"sourceRepoURL": "https://github.com/bterlson/ecmarkup",
"asOfVersion": "3.4.0"
},
{
"libraryName": "electron",
"typingsPackageName": "electron",
"sourceRepoURL": "https://github.com/electron/electron",
"asOfVersion": "1.6.10"
},
{
"libraryName": "electron-builder",
"typingsPackageName": "electron-builder",
"sourceRepoURL": "https://github.com/loopline-systems/electron-builder",
"asOfVersion": "2.8.0"
},
{
"libraryName": "error-stack-parser",
"typingsPackageName": "error-stack-parser",
"sourceRepoURL": "https://github.com/stacktracejs/error-stack-parser",
"asOfVersion": "2.0.0"
},
{
"libraryName": "eventemitter2",
"typingsPackageName": "eventemitter2",
"sourceRepoURL": "https://github.com/asyncly/EventEmitter2",
"asOfVersion": "4.1.0"
},
{
"libraryName": "EventEmitter3",
"typingsPackageName": "eventemitter3",
"sourceRepoURL": "https://github.com/primus/eventemitter3",
"asOfVersion": "2.0.2"
},
{
"libraryName": "express-validator",
"typingsPackageName": "express-validator",
"sourceRepoURL": "https://github.com/ctavan/express-validator",
"asOfVersion": "3.0.0"
},
{
"libraryName": "JSON-Patch",
"typingsPackageName": "fast-json-patch",
"sourceRepoURL": "https://github.com/Starcounter-Jack/JSON-Patch",
"asOfVersion": "1.1.5"
},
{
"libraryName": "FastSimplexNoise",
"typingsPackageName": "fast-simplex-noise",
@@ -96,6 +240,12 @@
"sourceRepoURL": "http://fineuploader.com/",
"asOfVersion": "5.14.0"
},
{
"libraryName": "flatpickr",
"typingsPackageName": "flatpickr",
"sourceRepoURL": "https://github.com/chmln/flatpickr",
"asOfVersion": "3.1.2"
},
{
"libraryName": "gaea-model",
"typingsPackageName": "gaea-model",
@@ -108,6 +258,12 @@
"sourceRepoURL": "https://github.com/mikedeboer/node-github",
"asOfVersion": "7.1.0"
},
{
"libraryName": "gulp-typescript",
"typingsPackageName": "gulp-typescript",
"sourceRepoURL": "https://github.com/ivogabe/gulp-typescript",
"asOfVersion": "2.13.0"
},
{
"libraryName": "Facebook's Immutable",
"typingsPackageName": "immutable",
@@ -162,12 +318,66 @@
"sourceRepoURL": "https://github.com/blakeembrey/is-upper-case",
"asOfVersion": "1.1.2"
},
{
"libraryName": "jpush-react-native",
"typingsPackageName": "jpush-react-native",
"sourceRepoURL": "https://github.com/jpush/jpush-react-native",
"asOfVersion": "2.0.0"
},
{
"libraryName": "jquery.ajaxfile",
"typingsPackageName": "jquery.ajaxfile",
"sourceRepoURL": "https://github.com/fpellet/jquery.ajaxFile",
"asOfVersion": "0.2.29"
},
{
"libraryName": "js-data",
"typingsPackageName": "js-data",
"sourceRepoURL": "https://github.com/js-data/js-data",
"asOfVersion": "3.0.0"
},
{
"libraryName": "JSNLog",
"typingsPackageName": "jsnlog",
"sourceRepoURL": "https://github.com/mperdeck/jsnlog.js",
"asOfVersion": "2.17.2"
},
{
"libraryName": "jsonschema",
"typingsPackageName": "jsonschema",
"sourceRepoURL": "https://github.com/tdegrunt/jsonschema",
"asOfVersion": "1.1.1"
},
{
"libraryName": "jsplumb",
"typingsPackageName": "jsplumb",
"sourceRepoURL": "https://github.com/jsplumb/jsPlumb",
"asOfVersion": "2.5.7"
},
{
"libraryName": "knockout-paging",
"typingsPackageName": "knockout-paging",
"sourceRepoURL": "https://github.com/ErikSchierboom/knockout-paging",
"asOfVersion": "0.3.1"
},
{
"libraryName": "knockout-pre-rendered",
"typingsPackageName": "knockout-pre-rendered",
"sourceRepoURL": "https://github.com/ErikSchierboom/knockout-pre-rendered",
"asOfVersion": "0.7.1"
},
{
"libraryName": "lambda-phi",
"typingsPackageName": "lambda-phi",
"sourceRepoURL": "https://github.com/elitechance/lambda-phi",
"asOfVersion": "1.0.1"
},
{
"libraryName": "left-pad",
"typingsPackageName": "left-pad",
"sourceRepoURL": "https://github.com/stevemao/left-pad",
"asOfVersion": "1.2.0"
},
{
"libraryName": "Linq.JS",
"typingsPackageName": "linq",
@@ -186,6 +396,18 @@
"sourceRepoURL": "https://github.com/localForage/localForage",
"asOfVersion": "0.0.34"
},
{
"libraryName": "lodash-decorators",
"typingsPackageName": "lodash-decorators",
"sourceRepoURL": "https://github.com/steelsojka/lodash-decorators",
"asOfVersion": "4.0.0"
},
{
"libraryName": "log4js",
"typingsPackageName": "log4js",
"sourceRepoURL": "https://github.com/nomiddlename/log4js-node",
"asOfVersion": "2.3.5"
},
{
"libraryName": "lower-case",
"typingsPackageName": "lower-case",
@@ -204,18 +426,36 @@
"sourceRepoURL": "http://maquettejs.org/",
"asOfVersion": "2.1.6"
},
{
"libraryName": "mendixmodelsdk",
"typingsPackageName": "mendixmodelsdk",
"sourceRepoURL": "http://www.mendix.com",
"asOfVersion": "0.8.1"
},
{
"libraryName": "mobservable",
"typingsPackageName": "mobservable",
"sourceRepoURL": "github.com/mweststrate/mobservable",
"asOfVersion": "1.2.5"
},
{
"libraryName": "mobservable-react",
"typingsPackageName": "mobservable-react",
"sourceRepoURL": "https://github.com/mweststrate/mobservable-react",
"asOfVersion": "1.0.0"
},
{
"libraryName": "Moment",
"typingsPackageName": "moment",
"sourceRepoURL": "https://github.com/moment/moment",
"asOfVersion": "2.13.0"
},
{
"libraryName": "MQTT",
"typingsPackageName": "mqtt",
"sourceRepoURL": "https://github.com/mqttjs/MQTT.js",
"asOfVersion": "2.5.0"
},
{
"libraryName": "ng-table",
"typingsPackageName": "ng-table",
@@ -234,12 +474,24 @@
"sourceRepoURL": "https://github.com/foretagsplatsen/numbro/",
"asOfVersion": "1.9.3"
},
{
"libraryName": "Onsen UI",
"typingsPackageName": "onsenui",
"sourceRepoURL": "http://onsen.io",
"asOfVersion": "2.0.0"
},
{
"libraryName": "param-case",
"typingsPackageName": "param-case",
"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",
@@ -252,18 +504,42 @@
"sourceRepoURL": "https://github.com/blakeembrey/path-case",
"asOfVersion": "1.1.2"
},
{
"libraryName": "path-to-regexp",
"typingsPackageName": "path-to-regexp",
"sourceRepoURL": "https://github.com/pillarjs/path-to-regexp",
"asOfVersion": "1.7.0"
},
{
"libraryName": "pg-promise",
"typingsPackageName": "pg-promise",
"sourceRepoURL": "https://github.com/vitaly-t/pg-promise",
"asOfVersion": "5.4.3"
},
{
"libraryName": "pixi-spine",
"typingsPackageName": "pixi-spine",
"sourceRepoURL": "https://github.com/pixijs/pixi-spine",
"asOfVersion": "1.4.2"
},
{
"libraryName": "pkcs11js",
"typingsPackageName": "pkcs11js",
"sourceRepoURL": "https://github.com/PeculiarVentures/pkcs11js",
"asOfVersion": "1.0.4"
},
{
"libraryName": "poly2tri.js",
"typingsPackageName": "poly2tri",
"sourceRepoURL": "https://github.com/r3mi/poly2tri.js",
"asOfVersion": "1.4.0"
},
{
"libraryName": "popper.js",
"typingsPackageName": "popper.js",
"sourceRepoURL": "https://github.com/FezVrasta/popper.js/",
"asOfVersion": "1.11.0"
},
{
"libraryName": "Prando",
"typingsPackageName": "prando",
@@ -276,18 +552,60 @@
"sourceRepoURL": "https://github.com/angular/protractor",
"asOfVersion": "4.0.0"
},
{
"libraryName": "qiniu",
"typingsPackageName": "qiniu",
"sourceRepoURL": "https://github.com/qiniu/nodejs-sdk",
"asOfVersion": "7.0.1"
},
{
"libraryName": "Raven JS",
"typingsPackageName": "raven-js",
"sourceRepoURL": "https://github.com/getsentry/raven-js",
"asOfVersion": "3.10.0"
},
{
"libraryName": "raw-body",
"typingsPackageName": "raw-body",
"sourceRepoURL": "https://github.com/stream-utils/raw-body",
"asOfVersion": "2.3.0"
},
{
"libraryName": "react-day-picker",
"typingsPackageName": "react-day-picker",
"sourceRepoURL": "https://github.com/gpbl/react-day-picker",
"asOfVersion": "5.3.0"
},
{
"libraryName": "react-native-elements",
"typingsPackageName": "react-native-elements",
"sourceRepoURL": "https://github.com/react-native-training/react-native-elements",
"asOfVersion": "0.18.0"
},
{
"libraryName": "realm",
"typingsPackageName": "realm",
"sourceRepoURL": "https://github.com/realm/realm-js",
"asOfVersion": "1.13.0"
},
{
"libraryName": "Redux",
"typingsPackageName": "redux",
"sourceRepoURL": "https://github.com/reactjs/redux",
"asOfVersion": "3.6.0"
},
{
"libraryName": "redux-batched-actions",
"typingsPackageName": "redux-batched-actions",
"sourceRepoURL": "https://github.com/tshelburne/redux-batched-actions",
"asOfVersion": "0.1.5"
},
{
"libraryName": "redux-devtools-extension",
"typingsPackageName": "redux-devtools-extension",
"sourceRepoURL": "https://github.com/zalmoxisus/redux-devtools-extension",
"asOfVersion": "2.13.2"
},
{
"libraryName": "redux-persist",
"typingsPackageName": "redux-persist",
@@ -312,12 +630,60 @@
"sourceRepoURL": "https://github.com/gaearon/redux-thunk",
"asOfVersion": "2.1.0"
},
{
"libraryName": "reselect",
"typingsPackageName": "reselect",
"sourceRepoURL": "https://github.com/rackt/reselect",
"asOfVersion": "2.2.0"
},
{
"libraryName": "rest-io",
"typingsPackageName": "rest-io",
"sourceRepoURL": "https://github.com/EnoF/rest-io",
"asOfVersion": "4.1.0"
},
{
"libraryName": "route-recognizer",
"typingsPackageName": "route-recognizer",
"sourceRepoURL": "https://github.com/tildeio/route-recognizer",
"asOfVersion": "0.3.0"
},
{
"libraryName": "router5",
"typingsPackageName": "router5",
"sourceRepoURL": "https://github.com/router5/router5",
"asOfVersion": "5.0.0"
},
{
"libraryName": "samchon",
"typingsPackageName": "samchon",
"sourceRepoURL": "https://github.com/samchon/framework",
"asOfVersion": "2.0.22"
},
{
"libraryName": "samchon-framework",
"typingsPackageName": "samchon-framework",
"sourceRepoURL": "https://github.com/samchon/framework",
"asOfVersion": "2.0.21"
},
{
"libraryName": "samchon-library",
"typingsPackageName": "samchon-library",
"sourceRepoURL": "https://github.com/samchon/framework",
"asOfVersion": "0.1.0"
},
{
"libraryName": "node-scanf",
"typingsPackageName": "scanf",
"sourceRepoURL": "https://github.com/Lellansin/node-scanf",
"asOfVersion": "0.7.3"
},
{
"libraryName": "sendgrid",
"typingsPackageName": "sendgrid",
"sourceRepoURL": "https://github.com/sendgrid/sendgrid-nodejs",
"asOfVersion": "4.3.0"
},
{
"libraryName": "sentence-case",
"typingsPackageName": "sentence-case",
@@ -348,18 +714,42 @@
"sourceRepoURL": "https://github.com/JMPerez/spotify-web-api-js",
"asOfVersion": "0.21.0"
},
{
"libraryName": "striptags",
"typingsPackageName": "striptags",
"sourceRepoURL": "https://github.com/ericnorris/striptags",
"asOfVersion": "3.1.1"
},
{
"libraryName": "Sugar",
"typingsPackageName": "sugar",
"sourceRepoURL": "https://github.com/andrewplummer/Sugar",
"asOfVersion": "2.0.2"
},
{
"libraryName": "svg.js",
"typingsPackageName": "svg.js",
"sourceRepoURL": "http://www.svgjs.com/",
"asOfVersion": "2.3.1"
},
{
"libraryName": "swap-case",
"typingsPackageName": "swap-case",
"sourceRepoURL": "https://github.com/blakeembrey/swap-case",
"asOfVersion": "1.1.2"
},
{
"libraryName": "Tabris.js",
"typingsPackageName": "tabris",
"sourceRepoURL": "http://tabrisjs.com",
"asOfVersion": "1.8.0"
},
{
"libraryName": "tcomb",
"typingsPackageName": "tcomb",
"sourceRepoURL": "http://gcanti.github.io/tcomb/guide/index.html",
"asOfVersion": "2.6.0"
},
{
"libraryName": "title-case",
"typingsPackageName": "title-case",
@@ -372,6 +762,12 @@
"sourceRepoURL": "https://github.com/cbowdon/TsMonad",
"asOfVersion": "0.5.0"
},
{
"libraryName": "tstl",
"typingsPackageName": "tstl",
"sourceRepoURL": "https://github.com/samchon/tstl",
"asOfVersion": "1.5.7"
},
{
"libraryName": "TypeScript",
"typingsPackageName": "typescript",
@@ -384,6 +780,12 @@
"sourceRepoURL": "https://github.com/Microsoft/TypeScript",
"asOfVersion": "2.0.0"
},
{
"libraryName": "uk.co.workingedge.phonegap.plugin.istablet",
"typingsPackageName": "uk.co.workingedge.phonegap.plugin.istablet",
"sourceRepoURL": "https://github.com/dpa99c/phonegap-istablet",
"asOfVersion": "1.1.3"
},
{
"libraryName": "upper-case",
"typingsPackageName": "upper-case",
@@ -396,6 +798,12 @@
"sourceRepoURL": "https://github.com/blakeembrey/upper-case-first",
"asOfVersion": "1.1.2"
},
{
"libraryName": "vso-node-api",
"typingsPackageName": "vso-node-api",
"sourceRepoURL": "https://github.com/Microsoft/vso-node-api",
"asOfVersion": "4.0.0"
},
{
"libraryName": "vuejs",
"typingsPackageName": "vue",
@@ -408,12 +816,24 @@
"sourceRepoURL": "https://github.com/vuejs/vue-router",
"asOfVersion": "2.0.0"
},
{
"libraryName": "webcola",
"typingsPackageName": "webcola",
"sourceRepoURL": "https://github.com/tgdwyer/WebCola",
"asOfVersion": "3.2.0"
},
{
"libraryName": "x2js",
"typingsPackageName": "x2js",
"sourceRepoURL": "https://code.google.com/p/x2js/",
"asOfVersion": "3.1.0"
},
{
"libraryName": "xlsx",
"typingsPackageName": "xlsx",
"sourceRepoURL": "https://github.com/sheetjs/js-xlsx",
"asOfVersion": "0.0.36"
},
{
"libraryName": "xml-js",
"typingsPackageName": "xml-js",
@@ -425,6 +845,12 @@
"typingsPackageName": "xmpp-jid",
"sourceRepoURL": "github.com/node-xmpp/node-xmpp/",
"asOfVersion": "1.2.0"
},
{
"libraryName": "Zone.js",
"typingsPackageName": "zone.js",
"sourceRepoURL": "https://github.com/angular/zone.js",
"asOfVersion": "0.5.12"
}
]
}
+3 -3
View File
@@ -17,11 +17,11 @@
"scripts": {
"compile-scripts": "tsc -p scripts",
"not-needed": "node scripts/not-needed.js",
"test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed --nProcesses 1",
"lint": "dtslint --dt types"
"test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed",
"lint": "dtslint types"
},
"devDependencies": {
"dtslint": "Microsoft/dtslint#production",
"dtslint": "github:Microsoft/dtslint#production",
"types-publisher": "Microsoft/types-publisher#production"
}
}
+11 -2
View File
@@ -31,7 +31,7 @@ function fixTslint(dir: string): void {
if (!fs.existsSync(target)) return;
let json = JSON.parse(fs.readFileSync(target, 'utf-8'));
json = fix(json);
const text = Object.keys(json).length === 1 ? '{ "extends": "../tslint.json" }' : JSON.stringify(json, undefined, 4);
const text = Object.keys(json).length === 1 ? '{ "extends": "dtslint/dt.json" }' : JSON.stringify(json, undefined, 4);
fs.writeFileSync(target, text + "\n", "utf-8");
}
@@ -39,7 +39,16 @@ function fix(config: any): any {
const out: any = {};
for (const key in config) {
let value = config[key];
out[key] = value;
out[key] = key === "rules" ? fixRules(value) : value;
}
return out;
}
function fixRules(rules: any): any {
const out: any = {};
for (const key in rules) {
out[key] = rules[key];
}
return out;
}
-4
View File
@@ -5,10 +5,6 @@
import * as fs from 'fs';
import * as path from 'path';
function repeat(s: string, count: number) {
return Array(count + 1).join(s);
}
const home = path.join(__dirname, '..');
for (const dirName of fs.readdirSync(home)) {
@@ -1,50 +0,0 @@
import packer = require("3d-bin-packing");
import samchon = require("samchon");
function main(): void
{
///////////////////////////
// CONSTRUCT OBJECTS
///////////////////////////
let wrapperArray: bws.packer.WrapperArray = new packer.WrapperArray();
let instanceArray: bws.packer.InstanceArray = new packer.InstanceArray();
// Wrappers
wrapperArray.push
(
new packer.Wrapper("Large", 1000, 40, 40, 15, 0),
new packer.Wrapper("Medium", 700, 20, 20, 10, 0),
new packer.Wrapper("Small", 500, 15, 15, 8, 0)
);
///////
// Each Instance is repeated #15
///////
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Eraser", 1, 2, 5));
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Book", 15, 30, 3));
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Drink", 3, 3, 10));
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Umbrella", 5, 5, 20));
// Wrappers also can be packed into another Wrapper.
instanceArray.insert(instanceArray.end(), 15, new packer.Wrapper("Notebook-Box", 2000, 30, 40, 4, 2));
instanceArray.insert(instanceArray.end(), 15, new packer.Wrapper("Tablet-Box", 2500, 20, 28, 2, 0));
///////////////////////////
// BEGINS PACKING
///////////////////////////
// CONSTRUCT PACKER
let my_packer: bws.packer.Packer = new packer.Packer(wrapperArray, instanceArray);
///////
// PACK (OPTIMIZE)
let result: bws.packer.WrapperArray = my_packer.optimize();
///////
///////////////////////////
// TRACE PACKING RESULT
///////////////////////////
let xml: samchon.library.XML = result.toXML();
console.log(xml.toString());
}
main();
-1383
View File
File diff suppressed because it is too large Load Diff
-23
View File
@@ -1,23 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"3d-bin-packing-tests.ts"
]
}
+13
View File
@@ -0,0 +1,13 @@
import abbrev = require('abbrev');
let abbrs: { [abbreviation: string]: string; };
abbrs = abbrev();
abbrs = abbrev('foo', 'fool', 'folding', 'flop');
abbrs = abbrev(['foo', 'fool', 'folding', 'flop']);
abbrev.monkeyPatch();
abbrs = [].abbrev();
const roArr: ReadonlyArray<string> = [];
abbrs = roArr.abbrev();
abbrs = ({}).abbrev();
+27
View File
@@ -0,0 +1,27 @@
// Type definitions for abbrev 1.1
// Project: https://github.com/isaacs/abbrev-js#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = abbrev;
declare function abbrev(words: string[]): {[abbreviation: string]: string};
declare function abbrev(...words: string[]): {[abbreviation: string]: string};
declare namespace abbrev {
function monkeyPatch(): void;
}
declare global {
interface Array<T> {
abbrev(): {[abbreviation: string]: string};
}
interface ReadonlyArray<T> {
abbrev(): {[abbreviation: string]: string};
}
interface Object {
abbrev(): {[abbreviation: string]: string};
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"abbrev-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+3 -3
View File
@@ -1,6 +1,6 @@
// Type definitions for Ably Realtime and Rest client library 0.9
// Project: https://www.ably.io/
// Definitions by: Ably <https://github.com/ably/>
// Definitions by: Ably <https://github.com/ably>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export namespace ablyLib {
@@ -287,7 +287,7 @@ export namespace ablyLib {
}
// Common Listeners
type paginatedResultCallback<T> = (error: ErrorInfo, results: PaginatedResult<T> ) => void;
type paginatedResultCallback<T> = (error: ErrorInfo, results: PaginatedResult<T>) => void;
type standardCallback = (error: ErrorInfo, results: any) => void;
type messageCallback<T> = (message: T) => void;
type errorCallback = (error: ErrorInfo) => void;
@@ -410,7 +410,7 @@ export namespace ablyLib {
state: ConnectionState;
close: () => void;
connect: () => void;
ping: (callback?: (error: ErrorInfo, responseTime: number ) => void ) => void;
ping: (callback?: (error: ErrorInfo, responseTime: number) => void) => void;
}
class Stats {
+1
View File
@@ -7,6 +7,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+6 -1
View File
@@ -1 +1,6 @@
{ "extends": "../tslint.json" }
{
"extends": "dtslint/dt.json",
"rules": {
"no-any-union": false
}
}
+1
View File
@@ -7,6 +7,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+1 -1
View File
@@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "dtslint/dt.json" }
+1
View File
@@ -7,6 +7,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+79
View File
@@ -0,0 +1,79 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
}
+2 -1
View File
@@ -2,6 +2,7 @@
// Project: https://github.com/sathomas/acc-wizard
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
interface AccWizardOptions {
/**
@@ -110,4 +111,4 @@ interface AccWizardOptions {
*/
interface JQuery {
accwizard(options?: AccWizardOptions): void;
}
}
+1
View File
@@ -8,6 +8,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+79
View File
@@ -0,0 +1,79 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
}
@@ -0,0 +1,25 @@
// https://github.com/opentable/accept-language-parser/blob/v1.4.1/index.js
import * as AcceptLanguageParser from 'accept-language-parser';
const l1: AcceptLanguageParser.Language = {
code: 'en',
script: 'Latn',
region: 'GB',
quality: 0.9
};
const l2: AcceptLanguageParser.Language = {
code: 'en',
quality: 0.9
};
const l3: AcceptLanguageParser.Language = {
code: 'en',
script: null,
quality: 0.9
};
const parsed1: AcceptLanguageParser.Language[] = AcceptLanguageParser.parse('');
const pick1: string | null = AcceptLanguageParser.pick([''], '');
const pick2: string | null = AcceptLanguageParser.pick([''], [l1, l2, l3]);
+17
View File
@@ -0,0 +1,17 @@
// Type definitions for accept-language-parser 1.4
// Project: https://github.com/opentable/accept-language-parser
// Definitions by: Niklas Wulf <https://github.com/kampfgnom>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
// https://github.com/opentable/accept-language-parser/blob/v1.4.1/index.js
export function parse(acceptLanguage: string): Language[];
export function pick(supportedLanguages: string[], acceptLanguage: string | Language[]): string | null;
export interface Language {
code: string;
script?: string | null;
region?: string;
quality: 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",
"accept-language-parser-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+11 -12
View File
@@ -1,13 +1,14 @@
// Type definitions for accepts 1.3
// Project: https://github.com/jshttp/accepts
// Definitions by: Stefan Reichel <https://github.com/bomret>
// Brice BERNARD <https://github.com/brikou>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace accepts {
interface Headers {
[key: string]: string | string[];
}
/// <reference types="node" />
import { IncomingMessage } from "http";
declare namespace accepts {
interface Accepts {
/**
* Return the first accepted charset. If nothing in `charsets` is accepted, then `false` is returned.
@@ -44,19 +45,17 @@ declare namespace accepts {
/**
* Return the first accepted type (and it is returned as the same text as what appears in the `types` array). If nothing in `types` is accepted, then `false` is returned.
* If no types are supplied, return the entire set of acceptable types.
*
* The `types` array can contain full MIME types or file extensions. Any value that is not a full MIME types is passed to `require('mime-types').lookup`.
*/
type(types: string[]): string | false;
type(...types: string[]): string | false;
/**
* Return the types that the request accepts, in the order of the client's preference (most preferred first).
*/
types(): string[];
type(types: string[]): string[] | string | false;
type(...types: string[]): string[] | string | false;
types(types: string[]): string[] | string | false;
types(...types: string[]): string[] | string | false;
}
}
declare function accepts(req: { headers: accepts.Headers }): accepts.Accepts;
declare function accepts(req: IncomingMessage): accepts.Accepts;
export = accepts;
+1
View File
@@ -7,6 +7,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+1 -1
View File
@@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "dtslint/dt.json" }
+3
View File
@@ -3,6 +3,9 @@
// Default usage:
accounting.formatMoney(12345678); // $12,345,678.00
// Stringified usage:
accounting.formatMoney('$4394958309392.9401'); // $4,394,958,309,392.94
// European formatting (custom symbol and separators), could also use options object as second param:
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
+7 -6
View File
@@ -1,6 +1,7 @@
// Type definitions for accounting.js 0.3
// Project: http://josscrowcroft.github.io/accounting.js/
// Definitions by: Sergey Gerasimov <https://github.com/gerich-home/>
// Type definitions for accounting.js 0.4
// Project: http://openexchangerates.github.io/accounting.js/
// Definitions by: Sergey Gerasimov <https://github.com/gerich-home>
// Christopher Eck <https://github.com/chrisleck>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace accounting {
@@ -30,9 +31,9 @@ declare namespace accounting {
}
interface Static {
// format any number into currency
formatMoney(number: number, symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string;
formatMoney(number: number, options: CurrencySettings<string> | CurrencySettings<CurrencyFormat>): string;
// format any number or stringified number into currency
formatMoney(number: number | string, symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string;
formatMoney(number: number | string, options: CurrencySettings<string> | CurrencySettings<CurrencyFormat>): string;
formatMoney(numbers: number[], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string[];
formatMoney(numbers: number[], options: CurrencySettings<string> | CurrencySettings<CurrencyFormat>): string[];
+1
View File
@@ -7,6 +7,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+1 -1
View File
@@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "dtslint/dt.json" }
+65 -11
View File
@@ -345,18 +345,47 @@ declare namespace AceAjax {
insert(position: Position, text: string): any;
/**
* Inserts the elements in `lines` into the document, starting at the row index given by `row`. This method also triggers the `'change'` event.
* @param row The index of the row to insert at
* @param lines An array of strings
**/
* @deprecated Use the insertFullLines method instead.
*/
insertLines(row: number, lines: string[]): any;
/**
* Inserts a new line into the document at the current row's `position`. This method also triggers the `'change'` event.
* @param position The position to insert at
**/
* Inserts the elements in `lines` into the document as full lines (does not merge with existing line), starting at the row index given by `row`. This method also triggers the `"change"` event.
* @param {Number} row The index of the row to insert at
* @param {Array} lines An array of strings
* @returns {Object} Contains the final row and column, like this:
* ```
* {row: endRow, column: 0}
* ```
* If `lines` is empty, this function returns an object containing the current row, and column, like this:
* ```
* {row: row, column: 0}
* ```
*
**/
insertFullLines(row: number, lines: string[]): any;
/**
* @deprecated Use insertMergedLines(position, ['', '']) instead.
*/
insertNewLine(position: Position): any;
/**
* Inserts the elements in `lines` into the document, starting at the position index given by `row`. This method also triggers the `"change"` event.
* @param {Number} row The index of the row to insert at
* @param {Array} lines An array of strings
* @returns {Object} Contains the final row and column, like this:
* ```
* {row: endRow, column: 0}
* ```
* If `lines` is empty, this function returns an object containing the current row, and column, like this:
* ```
* {row: row, column: 0}
* ```
*
**/
insertMergedLines(row: number, lines: string[]): any;
/**
* Inserts `text` into the `position` at the current row. This method also triggers the `'change'` event.
* @param position The position to insert at
@@ -379,12 +408,19 @@ declare namespace AceAjax {
removeInLine(row: number, startColumn: number, endColumn: number): any;
/**
* Removes a range of full lines. This method also triggers the `'change'` event.
* @param firstRow The first row to be removed
* @param lastRow The last row to be removed
**/
* @deprecated Use the removeFullLines method instead.
*/
removeLines(firstRow: number, lastRow: number): string[];
/**
* Removes a range of full lines. This method also triggers the `"change"` event.
* @param {Number} firstRow The first row to be removed
* @param {Number} lastRow The last row to be removed
* @returns {[String]} Returns all the removed lines.
*
**/
removeFullLines(firstRow: number, lastRow: number): string[];
/**
* Removes the new line between `row` and the row immediately following it. This method also triggers the `'change'` event.
* @param row The row to check
@@ -475,6 +511,8 @@ declare namespace AceAjax {
expandFold(arg: any): void;
foldAll(startRow?: number, endRow?: number, depth?: number): void
unfold(arg1: any, arg2: boolean): void;
screenToDocumentColumn(row: number, column: number): void;
@@ -1039,6 +1077,12 @@ declare namespace AceAjax {
addEventListener(ev: 'change', callback: (ev: EditorChangeEvent) => any): void;
addEventListener(ev: string, callback: Function): void;
off(ev: string, callback: Function): void;
removeListener(ev: string, callback: Function): void;
removeEventListener(ev: string, callback: Function): void;
inMultiSelectMode: boolean;
selectMoreLines(n: number): void;
@@ -2164,8 +2208,16 @@ declare namespace AceAjax {
**/
export interface Selection {
on(ev: string, callback: Function): void;
addEventListener(ev: string, callback: Function): void;
off(ev: string, callback: Function): void;
removeListener(ev: string, callback: Function): void;
removeEventListener(ev: string, callback: Function): void;
moveCursorWordLeft(): void;
moveCursorWordRight(): void;
@@ -2644,6 +2696,8 @@ declare namespace AceAjax {
lineHeight: number;
setScrollMargin(top:number, bottom:number, left: number, right: number): void;
screenToTextCoordinates(left: number, top: number): void;
/**
+1
View File
@@ -15,6 +15,7 @@ const aceVirtualRendererTests = {
var renderer = new AceAjax.VirtualRenderer(el);
renderer.setPadding(0);
renderer.setScrollMargin(0,0,0,0)
renderer.setSession(new AceAjax.EditSession("1234"));
var r = renderer.scroller.getBoundingClientRect();
+1
View File
@@ -8,6 +8,7 @@
"noImplicitAny": false,
"noImplicitThis": false,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+79
View File
@@ -0,0 +1,79 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
}
+5 -1
View File
@@ -2,6 +2,7 @@
// Project: https://github.com/optimalbits/node_acl
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="bluebird" />
/// <reference types="node"/>
@@ -49,7 +50,10 @@ interface Acl {
allowedPermissions: (userId: Value, resources: strings, cb?: AnyCallback) => Promise<void>;
isAllowed: (userId: Value, resources: strings, permissions: strings, cb?: AllowedCallback) => Promise<boolean>;
areAnyRolesAllowed: (roles: strings, resource: strings, permissions: strings, cb?: AllowedCallback) => Promise<any>;
whatResources: (roles: strings, permissions: strings, cb?: AnyCallback) => Promise<any>;
whatResources: {
(roles: strings, cb?: AnyCallback): Promise<any>;
(roles: strings, permissions: strings, cb?: AnyCallback): Promise<any>;
}
permittedResources: (roles: strings, permissions: strings, cb?: Function) => Promise<void>;
middleware: (numPathComponents?: number, userId?: Value | GetUserId, actions?: strings) => express.RequestHandler;
}
+12
View File
@@ -66,6 +66,18 @@ acl.isAllowed('joed', 'blogs', 'view', (err, res) => {
}
});
acl.whatResources('foo', (err, res) => {
if (res) {
console.log(res);
}
});
acl.whatResources('foo', 'view', (err, res) => {
if (res) {
console.log(res);
}
});
acl.isAllowed('jsmith', 'blogs', ['edit','view','delete'])
.then((result) => {
console.dir('jsmith is allowed blogs ' + result);
+1
View File
@@ -7,6 +7,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+79
View File
@@ -0,0 +1,79 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
}
+12 -17
View File
@@ -1,13 +1,13 @@
import acorn = require('acorn');
import * as ESTree from 'estree';
declare var token: acorn.Token;
declare var tokens: acorn.Token[];
declare var comment: acorn.Comment;
declare var comments: acorn.Comment[];
declare var program: ESTree.Program;
var any: any;
var string: string;
declare let token: acorn.Token;
declare let tokens: acorn.Token[];
declare let comment: acorn.Comment;
declare let comments: acorn.Comment[];
declare let program: ESTree.Program;
let any: any;
let string: string;
// acorn
string = acorn.version;
@@ -32,16 +32,12 @@ const parser = new acorn.Parser({}, 'export default ""', 0);
const node = new acorn.Node(parser, 1, 1);
class LooseParser {
constructor(input: string, options = {}) {
}
constructor(input: string, options = {}) {}
// this means you can extend LooseParser
test() {
}
test() {}
}
acorn.addLooseExports(function () {
acorn.addLooseExports(() => {
return {
type: 'Program',
sourceType: 'script',
@@ -50,7 +46,7 @@ acorn.addLooseExports(function () {
type: 'EmptyStatement'
}
]
}
};
}, LooseParser, {});
acorn.parseExpressionAt('string', 2);
@@ -63,8 +59,7 @@ acorn.isIdentifierChar(56);
acorn.getLineInfo('string', 56);
acorn.plugins['test'] = function (p: acorn.Parser, config: any) {
}
acorn.plugins['test'] = (p: acorn.Parser, config: any) => {};
acorn.tokenizer('console.log("hello world)', {locations: true}).getToken();
acorn.tokenizer('console.log("hello world)', {locations: true})[Symbol.iterator]().next();
+9 -14
View File
@@ -1,10 +1,8 @@
// Type definitions for Acorn v4.0.3
// Type definitions for Acorn 4.0
// Project: https://github.com/marijnh/acorn
// Definitions by: RReverser <https://github.com/RReverser>, e-cloud <https://github.com/e-cloud>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="estree" />
export as namespace acorn;
export = acorn;
import * as ESTree from 'estree';
@@ -181,7 +179,7 @@ declare namespace acorn {
_typeof: TokenType;
_void: TokenType;
_delete: TokenType;
}
};
class TokContext {
constructor(token: string, isExpr: boolean, preserveSpace: boolean, override: (p: Parser) => void);
@@ -230,19 +228,18 @@ declare namespace acorn {
const version: string;
interface IParse {
(input: string, options?: Options): ESTree.Program;
}
// TODO: rename type.
type IParse = (input: string, options?: Options) => ESTree.Program;
const parse: IParse;
function parseExpressionAt(input: string, pos?: number, options?: Options): ESTree.Expression;
interface ITokenizer {
getToken() : Token,
[Symbol.iterator](): Iterator<Token>
getToken(): Token;
[Symbol.iterator](): Iterator<Token>;
}
function tokenizer(input: string, options: Options): ITokenizer;
let parse_dammit: IParse | undefined;
@@ -250,12 +247,10 @@ declare namespace acorn {
let pluginsLoose: PluginsObject | undefined;
interface ILooseParserClass {
new (input: string, options?: Options): ILooseParser
new (input: string, options?: Options): ILooseParser;
}
interface ILooseParser {
}
interface ILooseParser {}
function addLooseExports(parse: IParse, parser: ILooseParserClass, plugins: PluginsObject): void;
}
+1
View File
@@ -7,6 +7,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+9
View File
@@ -0,0 +1,9 @@
{
"extends": "dtslint/dt.json",
"rules": {
"export-just-namespace": false,
"interface-name": false,
"no-empty-interface": false,
"no-unnecessary-class": false
}
}
+1
View File
@@ -8,6 +8,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+79
View File
@@ -0,0 +1,79 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
}
+13
View File
@@ -0,0 +1,13 @@
License Notices:
The API definitions are from Actions on Google reference site [1] and actions-on-google library [2].
The actions-on-google library is licensed under the Apache 2.0 License [3].
The code documentation is reproduced from work created and shared by Google [4]
and used according to terms described in the Creative Commons 3.0 Attribution License [5].
[1] https://developers.google.com/actions/
[2] https://github.com/actions-on-google/actions-on-google-nodejs
[3] http://www.apache.org/licenses/LICENSE-2.0
[4] https://developers.google.com/readme/policies/
[5] http://creativecommons.org/licenses/by/3.0/
@@ -0,0 +1,33 @@
import { ActionsSdkApp, ActionsSdkAppOptions, DialogflowApp, DialogflowAppOptions, AssistantApp,
Responses, Transactions } from 'actions-on-google';
import * as express from 'express';
function testActionsSdk(request: express.Request, response: express.Response) {
const app = new ActionsSdkApp({request, response});
const actionMap = new Map();
actionMap.set(app.StandardIntents.MAIN, () => {
const richResponse: Responses.RichResponse = app.buildRichResponse()
.addSimpleResponse('Hello world')
.addSuggestions(['foo', 'bar']);
app.ask(richResponse);
});
app.handleRequest(actionMap);
}
function testDialogflow(request: express.Request, response: express.Response) {
const app = new DialogflowApp({request, response});
const actionMap = new Map();
actionMap.set(app.StandardIntents.MAIN, () => {
const order: Transactions.Order = app.buildOrder('foo');
app.askForTransactionDecision(order, {
type: app.Transactions.PaymentType.PAYMENT_CARD,
displayName: 'VISA-1234',
deliveryAddressRequired: true
});
});
app.handleRequest(actionMap);
}
const expressApp = express();
expressApp.get('/actionssdk', testActionsSdk);
expressApp.get('/dialogflow', testDialogflow);
+415
View File
@@ -0,0 +1,415 @@
import * as express from 'express';
import { AssistantApp } from './assistant-app';
import { Carousel, List, RichResponse, SimpleResponse } from './response-builder';
// ---------------------------------------------------------------------------
// Actions SDK support
// ---------------------------------------------------------------------------
export interface ActionsSdkAppOptions {
/** Express HTTP request object. */
request: express.Request;
/** Express HTTP response object. */
response: express.Response;
/** Function callback when session starts. */
sessionStarted?(): any;
}
/**
* This is the class that handles the conversation API directly from Assistant,
* providing implementation for all the methods available in the API.
*/
export class ActionsSdkApp extends AssistantApp {
/**
* Constructor for ActionsSdkApp object.
* To be used in the Actions SDK HTTP endpoint logic.
*
* @example
* const ActionsSdkApp = require('actions-on-google').ActionsSdkApp;
* const app = new ActionsSdkApp({request: request, response: response,
* sessionStarted:sessionStarted});
*
* @actionssdk
*/
constructor(options: ActionsSdkAppOptions);
/**
* @deprecated
* Validates whether request is from Assistant through signature verification.
* Uses Google-Auth-Library to verify authorization token against given
* Google Cloud Project ID. Auth token is given in request header with key,
* "Authorization".
*
* @example
* const app = new ActionsSdkApp({request, response});
* app.isRequestFromAssistant('nodejs-cloud-test-project-1234')
* .then(() => {
* app.ask('Hey there, thanks for stopping by!');
* })
* .catch(err => {
* response.status(400).send();
* });
*
* @param projectId Google Cloud Project ID for the Assistant app.
* @return Promise resolving with google-auth-library LoginTicket
* if request is from a valid source, otherwise rejects with the error reason
* for an invalid token.
* @actionssdk
*/
isRequestFromAssistant(projectId: string): Promise<object>;
/**
* Validates whether request is from Google through signature verification.
* Uses Google-Auth-Library to verify authorization token against given
* Google Cloud Project ID. Auth token is given in request header with key,
* "Authorization".
*
* @example
* const app = new ActionsSdkApp({request, response});
* app.isRequestFromGoogle('nodejs-cloud-test-project-1234')
* .then(() => {
* app.ask('Hey there, thanks for stopping by!');
* })
* .catch(err => {
* response.status(400).send();
* });
*
* @param projectId Google Cloud Project ID for the Assistant app.
* @return Promise resolving with google-auth-library LoginTicket
* if request is from a valid source, otherwise rejects with the error reason
* for an invalid token.
* @actionssdk
*/
isRequestFromGoogle(projectId: string): Promise<object>;
/**
* Gets the request Conversation API version.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
* const apiVersion = app.getApiVersion();
*
* @return Version value or null if no value.
* @actionssdk
*/
getApiVersion(): string;
/**
* Gets the user's raw input query.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
* app.tell('You said ' + app.getRawInput());
*
* @return User's raw query or null if no value.
* @actionssdk
*/
getRawInput(): string;
/**
* Gets previous JSON dialog state that the app sent to Assistant.
* Alternatively, use the app.data field to store JSON values between requests.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
* const dialogState = app.getDialogState();
*
* @return JSON object provided to the Assistant in the previous
* user turn or {} if no value.
* @actionssdk
*/
getDialogState(): any;
/**
* Gets the "versionLabel" specified inside the Action Package.
* Used by app to do version control.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
* const actionVersionLabel = app.getActionVersionLabel();
*
* @return The specified version label or null if unspecified.
* @actionssdk
*/
getActionVersionLabel(): string;
/**
* Gets the unique conversation ID. It's a new ID for the initial query,
* and stays the same until the end of the conversation.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
* const conversationId = app.getConversationId();
*
* @return Conversation ID or null if no value.
* @actionssdk
*/
getConversationId(): string;
/**
* Get the current intent. Alternatively, using a handler Map with
* {@link AssistantApp#handleRequest|handleRequest}, the client library will
* automatically handle the incoming intents.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
*
* function responseHandler (app) {
* const intent = app.getIntent();
* switch (intent) {
* case app.StandardIntents.MAIN:
* const inputPrompt = app.buildInputPrompt(false, 'Welcome to action snippets! Say anything.');
* app.ask(inputPrompt);
* break;
*
* case app.StandardIntents.TEXT:
* app.tell('You said ' + app.getRawInput());
* break;
* }
* }
*
* app.handleRequest(responseHandler);
*
* @return Intent id or null if no value.
* @actionssdk
*/
getIntent(): string;
/**
* Get the argument value by name from the current intent. If the argument
* is not a text argument, the entire argument object is returned.
*
* Note: If incoming request is using an API version under 2 (e.g. 'v1'),
* the argument object will be in Proto2 format (snake_case, etc).
*
* @param argName Name of the argument.
* @return Argument value matching argName
* or null if no matching argument.
* @actionssdk
*/
getArgument(argName: string): string;
/**
* Returns the option key user chose from options response.
*
* @example
* const app = new App({request: req, response: res});
*
* function pickOption (app) {
* if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
* app.askWithCarousel('Which of these looks good?',
* app.buildCarousel().addItems(
* app.buildOptionItem('another_choice', ['Another choice']).
* setTitle('Another choice').setDescription('Choose me!')));
* } else {
* app.ask('What would you like?');
* }
* }
*
* function optionPicked (app) {
* app.ask('You picked ' + app.getSelectedOption());
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.TEXT, pickOption);
* actionMap.set(app.StandardIntents.OPTION, optionPicked);
*
* app.handleRequest(actionMap);
*
* @return Option key of selected item. Null if no option selected or
* if current intent is not OPTION intent.
* @actionssdk
*/
getSelectedOption(): string;
/**
* Asks to collect user's input; all user's queries need to be sent to
* the app.
* {@link https://developers.google.com/actions/policies/general-policies#user_experience|The guidelines when prompting the user for a response must be followed at all times}.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
*
* function mainIntent (app) {
* const inputPrompt = app.buildInputPrompt(true, '<speak>Hi! <break time="1"/> ' +
* 'I can read out an ordinal like ' +
* '<say-as interpret-as="ordinal">123</say-as>. Say a number.</speak>',
* ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']);
* app.ask(inputPrompt);
* }
*
* function rawInput (app) {
* if (app.getRawInput() === 'bye') {
* app.tell('Goodbye!');
* } else {
* const inputPrompt = app.buildInputPrompt(true, '<speak>You said, <say-as interpret-as="ordinal">' +
* app.getRawInput() + '</say-as></speak>',
* ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']);
* app.ask(inputPrompt);
* }
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.MAIN, mainIntent);
* actionMap.set(app.StandardIntents.TEXT, rawInput);
*
* app.handleRequest(actionMap);
*
* @param inputPrompt Holding initial and
* no-input prompts.
* @param dialogState JSON object the app uses to hold dialog state that
* will be circulated back by App.
* @return The response that is sent to Assistant to ask user to provide input.
* @actionssdk
*/
ask(inputPrompt: object | SimpleResponse | RichResponse, dialogState?: object): express.Response | null;
/**
* Asks to collect user's input with a list.
*
* @example
* const app = new ActionsSdkApp({request, response});
*
* function welcomeIntent (app) {
* app.askWithlist('Which of these looks good?',
* app.buildList('List title')
* .addItems([
* app.buildOptionItem(SELECTION_KEY_ONE,
* ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2'])
* .setTitle('Number one'),
* app.buildOptionItem(SELECTION_KEY_TWO,
* ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2'])
* .setTitle('Number two'),
* ]));
* }
*
* function optionIntent (app) {
* if (app.getSelectedOption() === SELECTION_KEY_ONE) {
* app.tell('Number one is a great choice!');
* } else {
* app.tell('Number two is a great choice!');
* }
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.TEXT, welcomeIntent);
* actionMap.set(app.StandardIntents.OPTION, optionIntent);
* app.handleRequest(actionMap);
*
* @param inputPrompt Holding initial and
* no-input prompts. Cannot contain basic card.
* @param list List built with {@link AssistantApp#buildList|buildList}.
* @param dialogState JSON object the app uses to hold dialog state that
* will be circulated back by Assistant.
* @return The response that is sent to Assistant to ask user to provide input.
* @actionssdk
*/
askWithList(inputPrompt: object | SimpleResponse | RichResponse, list: List, dialogState?: object): express.Response | null;
/**
* Asks to collect user's input with a carousel.
*
* @example
* const app = new ActionsSdkApp({request, response});
*
* function welcomeIntent (app) {
* app.askWithCarousel('Which of these looks good?',
* app.buildCarousel()
* .addItems([
* app.buildOptionItem(SELECTION_KEY_ONE,
* ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2'])
* .setTitle('Number one'),
* app.buildOptionItem(SELECTION_KEY_TWO,
* ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2'])
* .setTitle('Number two'),
* ]));
* }
*
* function optionIntent (app) {
* if (app.getSelectedOption() === SELECTION_KEY_ONE) {
* app.tell('Number one is a great choice!');
* } else {
* app.tell('Number two is a great choice!');
* }
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.TEXT, welcomeIntent);
* actionMap.set(app.StandardIntents.OPTION, optionIntent);
* app.handleRequest(actionMap);
*
* @param inputPrompt Holding initial and
* no-input prompts. Cannot contain basic card.
* @param carousel Carousel built with
* {@link AssistantApp#buildCarousel|buildCarousel}.
* @param dialogState JSON object the app uses to hold dialog state that
* will be circulated back by Assistant.
* @return The response that is sent to Assistant to ask user to provide input.
* @actionssdk
*/
askWithCarousel(inputPrompt: object | SimpleResponse | RichResponse, carousel: Carousel, dialogState?: object): express.Response | null;
/**
* Tells Assistant to render the speech response and close the mic.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
*
* function mainIntent (app) {
* const inputPrompt = app.buildInputPrompt(true, '<speak>Hi! <break time="1"/> ' +
* 'I can read out an ordinal like ' +
* '<say-as interpret-as="ordinal">123</say-as>. Say a number.</speak>',
* ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']);
* app.ask(inputPrompt);
* }
*
* function rawInput (app) {
* if (app.getRawInput() === 'bye') {
* app.tell('Goodbye!');
* } else {
* const inputPrompt = app.buildInputPrompt(true, '<speak>You said, <say-as interpret-as="ordinal">' +
* app.getRawInput() + '</say-as></speak>',
* ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']);
* app.ask(inputPrompt);
* }
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.MAIN, mainIntent);
* actionMap.set(app.StandardIntents.TEXT, rawInput);
*
* app.handleRequest(actionMap);
*
* @param textToSpeech Final response.
* Spoken response can be SSML.
* @return The HTTP response that is sent back to Assistant.
* @actionssdk
*/
tell(textToSpeech: string | SimpleResponse | RichResponse): express.Response | null;
/**
* Builds the {@link https://developers.google.com/actions/reference/conversation#InputPrompt|InputPrompt object}
* from initial prompt and no-input prompts.
*
* The App needs one initial prompt to start the conversation. If there is no user response,
* the App re-opens the mic and renders the no-input prompts three times
* (one for each no-input prompt that was configured) to help the user
* provide the right response.
*
* Note: we highly recommend app to provide all the prompts required here in order to ensure a
* good user experience.
*
* @example
* const inputPrompt = app.buildInputPrompt(false, 'Welcome to action snippets! Say a number.',
* ['Say any number', 'Pick a number', 'What is the number?']);
* app.ask(inputPrompt);
*
* @param isSsml Indicates whether the text to speech is SSML or not.
* @param initialPrompt The initial prompt the App asks the user.
* @param noInputs Array of re-prompts when the user does not respond (max 3).
* @return.
* @actionssdk
*/
buildInputPrompt(isSsml: boolean, initialPrompt: string, noInputs?: string[]): object;
}
File diff suppressed because it is too large Load Diff
+571
View File
@@ -0,0 +1,571 @@
import * as express from 'express';
import { AssistantApp } from './assistant-app';
import { Carousel, List, RichResponse, SimpleResponse } from './response-builder';
// ---------------------------------------------------------------------------
// Dialogflow support
// ---------------------------------------------------------------------------
/**
* Dialogflow {@link https://dialogflow.com/docs/concept-contexts|Context}.
*/
export interface Context {
/** Full name of the context. */
name: string;
/**
* Parameters carried within this context.
* See {@link https://dialogflow.com/docs/concept-actions#section-extracting-values-from-contexts|here}.
*/
parameters: object;
/** Remaining number of intents */
lifespan: number;
}
export interface DialogflowAppOptions {
/** Express HTTP request object. */
request: express.Request;
/** Express HTTP response object. */
response: express.Response;
/**
* Function callback when session starts.
* Only called if webhook is enabled for welcome/triggering intents, and
* called from Web Simulator or Google Home device (i.e., not Dialogflow simulator).
*/
sessionStarted?(): any;
}
/**
* This is the class that handles the communication with Dialogflow's fulfillment API.
*/
export class DialogflowApp extends AssistantApp {
/**
* Constructor for DialogflowApp object.
* To be used in the Dialogflow fulfillment webhook logic.
*
* @example
* const DialogflowApp = require('actions-on-google').DialogflowApp;
* const app = new DialogflowApp({request: request, response: response,
* sessionStarted:sessionStarted});
*
* @dialogflow
*/
constructor(options: DialogflowAppOptions);
/**
* @deprecated
* Verifies whether the request comes from Dialogflow.
*
* @param key The header key specified by the developer in the
* Dialogflow Fulfillment settings of the app.
* @param value The private value specified by the developer inside the
* fulfillment header.
* @return True if the request comes from Dialogflow.
* @dialogflow
*/
isRequestFromApiAi(key: string, value: string): boolean;
/**
* Verifies whether the request comes from Dialogflow.
*
* @param key The header key specified by the developer in the
* Dialogflow Fulfillment settings of the app.
* @param value The private value specified by the developer inside the
* fulfillment header.
* @return True if the request comes from Dialogflow.
* @dialogflow
*/
isRequestFromDialogflow(key: string, value: string): boolean;
/**
* Get the current intent. Alternatively, using a handler Map with
* {@link AssistantApp#handleRequest|handleRequest},
* the client library will automatically handle the incoming intents.
* 'Intent' in the Dialogflow context translates into the current action.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
*
* function responseHandler (app) {
* const intent = app.getIntent();
* switch (intent) {
* case WELCOME_INTENT:
* app.ask('Welcome to action snippets! Say a number.');
* break;
*
* case NUMBER_INTENT:
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* break;
* }
* }
*
* app.handleRequest(responseHandler);
*
* @return Intent id or null if no value (action name).
* @dialogflow
*/
getIntent(): string;
/**
* Get the argument value by name from the current intent. If the argument
* is included in originalRequest, and is not a text argument, the entire
* argument object is returned.
*
* Note: If incoming request is using an API version under 2 (e.g. 'v1'),
* the argument object will be in Proto2 format (snake_case, etc).
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const WELCOME_INTENT = 'input.welcome';
* const NUMBER_INTENT = 'input.number';
*
* function welcomeIntent (app) {
* app.ask('Welcome to action snippets! Say a number.');
* }
*
* function numberIntent (app) {
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @param argName Name of the argument.
* @return Argument value matching argName
* or null if no matching argument.
* @dialogflow
*/
getArgument(argName: string): object;
/**
* Get the context argument value by name from the current intent. Context
* arguments include parameters collected in previous intents during the
* lifespan of the given context. If the context argument has an original
* value, usually representing the underlying entity value, that will be given
* as part of the return object.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const WELCOME_INTENT = 'input.welcome';
* const NUMBER_INTENT = 'input.number';
* const OUT_CONTEXT = 'output_context';
* const NUMBER_ARG = 'myNumberArg';
*
* function welcomeIntent (app) {
* const parameters = {};
* parameters[NUMBER_ARG] = '42';
* app.setContext(OUT_CONTEXT, 1, parameters);
* app.ask('Welcome to action snippets! Ask me for your number.');
* }
*
* function numberIntent (app) {
* const number = app.getContextArgument(OUT_CONTEXT, NUMBER_ARG);
* // number === { value: 42 }
* app.tell('Your number is ' + number.value);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @param contextName Name of the context.
* @param argName Name of the argument.
* @return Object containing value property and optional original
* property matching context argument. Null if no matching argument.
* @dialogflow
*/
getContextArgument(contextName: string, argName: string): object;
/**
* Returns the RichResponse constructed in Dialogflow response builder.
*
* @example
* const app = new App({request: req, response: res});
*
* function tellFact (app) {
* let fact = 'Google was founded in 1998';
*
* if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
* app.ask(app.getIncomingRichResponse().addSimpleResponse('Here\'s a ' +
* 'fact for you. ' + fact + ' Which one do you want to hear about ' +
* 'next, Google\'s history or headquarters?'));
* } else {
* app.ask('Here\'s a fact for you. ' + fact + ' Which one ' +
* 'do you want to hear about next, Google\'s history or headquarters?');
* }
* }
*
* const actionMap = new Map();
* actionMap.set('tell.fact', tellFact);
*
* app.handleRequest(actionMap);
*
* @return RichResponse created in Dialogflow. If no RichResponse was
* created, an empty RichResponse is returned.
* @dialogflow
*/
getIncomingRichResponse(): RichResponse;
/**
* Returns the List constructed in Dialogflow response builder.
*
* @example
* const app = new App({request: req, response: res});
*
* function pickOption (app) {
* if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
* app.askWithList('Which of these looks good?',
* app.getIncomingList().addItems(
* app.buildOptionItem('another_choice', ['Another choice']).
* setTitle('Another choice')));
* } else {
* app.ask('What would you like?');
* }
* }
*
* const actionMap = new Map();
* actionMap.set('pick.option', pickOption);
*
* app.handleRequest(actionMap);
*
* @return List created in Dialogflow. If no List was created, an empty
* List is returned.
* @dialogflow
*/
getIncomingList(): List;
/**
* Returns the Carousel constructed in Dialogflow response builder.
*
* @example
* const app = new App({request: req, response: res});
*
* function pickOption (app) {
* if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
* app.askWithCarousel('Which of these looks good?',
* app.getIncomingCarousel().addItems(
* app.buildOptionItem('another_choice', ['Another choice']).
* setTitle('Another choice').setDescription('Choose me!')));
* } else {
* app.ask('What would you like?');
* }
* }
*
* const actionMap = new Map();
* actionMap.set('pick.option', pickOption);
*
* app.handleRequest(actionMap);
*
* @return Carousel created in Dialogflow. If no Carousel was created,
* an empty Carousel is returned.
* @dialogflow
*/
getIncomingCarousel(): Carousel;
/**
* Returns the option key user chose from options response.
*
* @example
* const app = new App({request: req, response: res});
*
* function pickOption (app) {
* if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
* app.askWithCarousel('Which of these looks good?',
* app.getIncomingCarousel().addItems(
* app.buildOptionItem('another_choice', ['Another choice']).
* setTitle('Another choice').setDescription('Choose me!')));
* } else {
* app.ask('What would you like?');
* }
* }
*
* function optionPicked (app) {
* app.ask('You picked ' + app.getSelectedOption());
* }
*
* const actionMap = new Map();
* actionMap.set('pick.option', pickOption);
* actionMap.set('option.picked', optionPicked);
*
* app.handleRequest(actionMap);
*
* @return Option key of selected item. Null if no option selected or
* if current intent is not OPTION intent.
* @dialogflow
*/
getSelectedOption(): string;
/**
* Asks to collect the user's input.
* {@link https://developers.google.com/actions/policies/general-policies#user_experience|The guidelines when prompting the user for a response must be followed at all times}.
*
* NOTE: Due to a bug, if you specify the no-input prompts,
* the mic is closed after the 3rd prompt, so you should use the 3rd prompt
* for a bye message until the bug is fixed.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const WELCOME_INTENT = 'input.welcome';
* const NUMBER_INTENT = 'input.number';
*
* function welcomeIntent (app) {
* app.ask('Welcome to action snippets! Say a number.',
* ['Say any number', 'Pick a number', 'We can stop here. See you soon.']);
* }
*
* function numberIntent (app) {
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @param inputPrompt The input prompt
* response.
* @param noInputs Array of re-prompts when the user does not respond (max 3).
* @return HTTP response.
* @dialogflow
*/
ask(inputPrompt: string | SimpleResponse | RichResponse, noInputs?: string[]): express.Response | null;
/**
* Asks to collect the user's input with a list.
*
* @example
* const app = new DialogflowApp({request, response});
* const WELCOME_INTENT = 'input.welcome';
* const OPTION_INTENT = 'option.select';
*
* function welcomeIntent (app) {
* app.askWithList('Which of these looks good?',
* app.buildList('List title')
* .addItems([
* app.buildOptionItem(SELECTION_KEY_ONE,
* ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2'])
* .setTitle('Title of First List Item'),
* app.buildOptionItem(SELECTION_KEY_TWO,
* ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2'])
* .setTitle('Title of Second List Item'),
* ]));
* }
*
* function optionIntent (app) {
* if (app.getSelectedOption() === SELECTION_KEY_ONE) {
* app.tell('Number one is a great choice!');
* } else {
* app.tell('Number two is a great choice!');
* }
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(OPTION_INTENT, optionIntent);
* app.handleRequest(actionMap);
*
* @param inputPrompt The input prompt
* response.
* @param.list List built with {@link AssistantApp#buildList|buildList}
* @return HTTP response.
* @dialogflow
*/
askWithList(inputPrompt: string | RichResponse | SimpleResponse, list: List): express.Response | null;
/**
* Asks to collect the user's input with a carousel.
*
* @example
* const app = new DialogflowApp({request, response});
* const WELCOME_INTENT = 'input.welcome';
* const OPTION_INTENT = 'option.select';
*
* function welcomeIntent (app) {
* app.askWithCarousel('Which of these looks good?',
* app.buildCarousel()
* .addItems([
* app.buildOptionItem(SELECTION_KEY_ONE,
* ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2'])
* .setTitle('Number one'),
* app.buildOptionItem(SELECTION_KEY_TWO,
* ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2'])
* .setTitle('Number two'),
* ]));
* }
*
* function optionIntent (app) {
* if (app.getSelectedOption() === SELECTION_KEY_ONE) {
* app.tell('Number one is a great choice!');
* } else {
* app.tell('Number two is a great choice!');
* }
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(OPTION_INTENT, optionIntent);
* app.handleRequest(actionMap);
*
* @param inputPrompt The input prompt
* response.
* @param carousel Carousel built with
* {@link AssistantApp#buildCarousel|buildCarousel}.
* @return HTTP response.
* @dialogflow
*/
askWithCarousel(inputPrompt: string | RichResponse | SimpleResponse, carousel: Carousel): express.Response | null;
/**
* Tells the Assistant to render the speech response and close the mic.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const WELCOME_INTENT = 'input.welcome';
* const NUMBER_INTENT = 'input.number';
*
* function welcomeIntent (app) {
* app.ask('Welcome to action snippets! Say a number.');
* }
*
* function numberIntent (app) {
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @param speechResponse Final response.
* Spoken response can be SSML.
* @return The response that is sent back to Assistant.
* @dialogflow
*/
tell(speechResponse: string | SimpleResponse | RichResponse): express.Response | null;
/**
* Set a new context for the current intent.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const CONTEXT_NUMBER = 'number';
* const NUMBER_ARGUMENT = 'myNumber';
*
* function welcomeIntent (app) {
* app.setContext(CONTEXT_NUMBER);
* app.ask('Welcome to action snippets! Say a number.');
* }
*
* function numberIntent (app) {
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @param name Name of the context. Dialogflow converts to lowercase.
* @param [lifespan=1] Context lifespan.
* @param parameters Context JSON parameters.
* @return Null if the context name is not defined.
* @dialogflow
*/
setContext(name: string, lifespan?: number, parameters?: any): null | undefined;
/**
* Returns the incoming contexts for this intent.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const CONTEXT_NUMBER = 'number';
* const NUMBER_ARGUMENT = 'myNumber';
*
* function welcomeIntent (app) {
* app.setContext(CONTEXT_NUMBER);
* app.ask('Welcome to action snippets! Say a number.');
* }
*
* function numberIntent (app) {
* let contexts = app.getContexts();
* // contexts === [{
* // name: 'number',
* // lifespan: 0,
* // parameters: {
* // myNumber: '23',
* // myNumber.original: '23'
* // }
* // }]
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @return Empty if no active contexts.
* @dialogflow
*/
getContexts(): Context[];
/**
* Returns the incoming context by name for this intent.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const CONTEXT_NUMBER = 'number';
* const NUMBER_ARGUMENT = 'myNumber';
*
* function welcomeIntent (app) {
* app.setContext(CONTEXT_NUMBER);
* app.ask('Welcome to action snippets! Say a number.');
* }
*
* function numberIntent (app) {
* let context = app.getContext(CONTEXT_NUMBER);
* // context === {
* // name: 'number',
* // lifespan: 0,
* // parameters: {
* // myNumber: '23',
* // myNumber.original: '23'
* // }
* // }
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @param name The name of the Context to retrieve.
* @return Context value matching name
* or null if no matching context.
* @dialogflow
*/
getContext(name: string): object;
/**
* Gets the user's raw input query.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* app.tell('You said ' + app.getRawInput());
*
* @return User's raw query or null if no value.
* @dialogflow
*/
getRawInput(): string;
}
+24
View File
@@ -0,0 +1,24 @@
// Type definitions for actions-on-google 1.6
// Project: https://github.com/actions-on-google/actions-on-google-nodejs
// Definitions by: Joel Hegg <https://github.com/joelhegg>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
/**
* The Actions on Google client library.
* https://developers.google.com/actions/
*/
import * as Transactions from './transactions';
import * as Responses from './response-builder';
export { AssistantApp } from './assistant-app';
export { ActionsSdkApp, ActionsSdkAppOptions } from './actions-sdk-app';
export { DialogflowApp, DialogflowAppOptions } from './dialogflow-app';
export { Transactions };
export { Responses };
// Backwards compatibility
export { AssistantApp as Assistant } from './assistant-app';
export { ActionsSdkApp as ActionsSdkAssistant } from './actions-sdk-app';
export { DialogflowApp as ApiAiAssistant } from './dialogflow-app';
export { DialogflowApp as ApiAiApp } from './dialogflow-app';
+404
View File
@@ -0,0 +1,404 @@
/**
* A collection of response builders.
*/
import { OrderUpdate } from './transactions';
/**
* Simple Response type.
*/
export interface SimpleResponse {
/** Speech to be spoken to user. SSML allowed. */
speech: string;
/** Optional text to be shown to user */
displayText?: string;
}
/**
* Suggestions to show with response.
*/
export interface Suggestion {
/** Text of the suggestion. */
title: string;
}
/**
* Link Out Suggestion. Used in rich response as a suggestion chip which, when
* selected, links out to external URL.
*/
export interface LinkOutSuggestion {
/** Text shown on the suggestion chip. */
title: string;
/** String URL to open. */
url: string;
}
/**
* Image type shown on visual elements.
*/
export interface Image {
/** Image source URL. */
url: string;
/** Text to replace for image for accessibility. */
accessibilityText: string;
/** Width of the image. */
width: number;
/** Height of the image. */
height: number;
}
/**
* Basic Card Button. Shown below basic cards. Open a URL when selected.
*/
export interface Button {
/** Text shown on the button. */
title: string;
/** Action to take when selected. */
openUrlAction: {
/** String URL to open. */
url: string;
};
}
/**
* Option info. Provides unique identifier for a given OptionItem.
*/
export interface OptionInfo {
/** Unique string ID for this option. */
key: string;
/** Synonyms that can be used by the user to indicate this option if they do not use the key. */
synonyms: string[];
}
export interface StructuredResponse {
orderUpdate: OrderUpdate;
}
export interface RichResponseItemBasicCard {
basicCard: BasicCard;
}
export interface RichResponseItemSimpleResponse {
simpleResponse: SimpleResponse;
}
export interface RichResponseItemStructuredResponse {
structuredResponse: StructuredResponse;
}
export type RichResponseItem = RichResponseItemBasicCard | RichResponseItemSimpleResponse | RichResponseItemStructuredResponse;
/**
* Class for initializing and constructing Rich Responses with chainable interface.
*/
export class RichResponse {
/**
* Constructor for RichResponse. Accepts optional RichResponse to clone.
*
* @param richResponse Optional RichResponse to clone.
*/
constructor(richResponse?: RichResponse);
/**
* Ordered list of either SimpleResponse objects or BasicCard objects.
* First item must be SimpleResponse. There can be at most one card.
*/
items: RichResponseItem[];
/**
* Ordered list of text suggestions to display. Optional.
*/
suggestions: Suggestion[];
/**
* Link Out Suggestion chip for this rich response. Optional.
*/
linkOutSuggestion?: LinkOutSuggestion;
/**
* Adds a SimpleResponse to list of items.
*
* @param simpleResponse Simple response to present to
* user. If just a string, display text will not be set.
* @return Returns current constructed RichResponse.
*/
addSimpleResponse(simpleResponse: string | SimpleResponse): RichResponse;
/**
* Adds a BasicCard to list of items.
*
* @param basicCard Basic card to include in response.
* @return Returns current constructed RichResponse.
*/
addBasicCard(basicCard: BasicCard): RichResponse;
/**
* Adds a single suggestion or list of suggestions to list of items.
*
* @param suggestions Either a single string suggestion
* or list of suggestions to add.
* @return Returns current constructed RichResponse.
*/
addSuggestions(suggestions: string | string[]): RichResponse;
/**
* Returns true if the given suggestion text is valid to be added to the suggestion list. A valid
* text string is not longer than 25 characters.
* @param suggestionText Text to validate as suggestion.
* @return True if the text is valid, false otherwise.s
*/
isValidSuggestionText(suggestionText: string): boolean;
/**
* Sets the suggestion link for this rich response.
*
* @param destinationName Name of the link out destination.
* @param suggestionUrl - String URL to open when suggestion is used.
* @return Returns current constructed RichResponse.
*/
addSuggestionLink(destinationName: string, suggestionUrl: string): RichResponse;
/**
* Adds an order update to this response. Use after a successful transaction
* decision to confirm the order.
*
* @param orderUpdate OrderUpdate object to add.
* @return Returns current constructed RichResponse.
*/
addOrderUpdate(orderUpdate: OrderUpdate): RichResponse;
}
/**
* Class for initializing and constructing Basic Cards with chainable interface.
*/
export class BasicCard {
/**
* Constructor for BasicCard. Accepts optional BasicCard to clone.
*
* @param basicCard Optional BasicCard to clone.
*/
constructor(basicCard?: BasicCard);
/**
* Title of the card. Optional.
*/
title?: string;
/**
* Body text to show on the card. Required, unless image is present.
*/
formattedText: string;
/**
* Subtitle of the card. Optional.
*/
subtitle?: string;
/**
* Image to show on the card. Optional.
*/
image?: Image;
/**
* Ordered list of buttons to show below card. Optional.
*/
buttons: Button[];
/**
* Sets the title for this Basic Card.
*
* @param title Title to show on card.
* @return Returns current constructed BasicCard.
*/
setTitle(title: string): BasicCard;
/**
* Sets the subtitle for this Basic Card.
*
* @param subtitle Subtitle to show on card.
* @return Returns current constructed BasicCard.
*/
setSubtitle(subtitle: string): BasicCard;
/**
* Sets the body text for this Basic Card.
*
* @param bodyText Body text to show on card.
* @return Returns current constructed BasicCard.
*/
setBodyText(bodyText: string): BasicCard;
/**
* Sets the image for this Basic Card.
*
* @param url Image source URL.
* @param accessibilityText Text to replace for image for
* accessibility.
* @param width Width of the image.
* @param height Height of the image.
* @return Returns current constructed BasicCard.
*/
setImage(url: string, accessibilityText: string, width?: number, height?: number): BasicCard;
/**
* Adds a button below card.
*
* @param text Text to show on button.
* @param url URL to open when button is selected.
* @return Returns current constructed BasicCard.
*/
addButton(text: string, url: string): BasicCard;
}
/**
* Class for initializing and constructing Lists with chainable interface.
*/
export class List {
/**
* Constructor for List. Accepts optional List to clone, string title, or
* list of items to copy.
*
* @param list Either a list to clone, a title
* to set for a new List, or an array of OptionItem to initialize a new
* list.
*/
constructor(list?: List | string | OptionItem[]);
/**
* Title of the list. Optional.
*/
title?: string;
/**
* List of 2-20 items to show in this list. Required.
*/
items: OptionItem[];
/**
* Sets the title for this List.
*
* @param title Title to show on list.
* @return Returns current constructed List.
*/
setTitle(title: string): List;
/**
* Adds a single item or list of items to the list.
*
* @param optionItems OptionItems to add.
* @return Returns current constructed List.
*/
addItems(optionItems: OptionItem | OptionItem[]): List;
}
/**
* Class for initializing and constructing Carousel with chainable interface.
*/
export class Carousel {
/**
* Constructor for Carousel. Accepts optional Carousel to clone or list of
* items to copy.
*
* @param carousel Either a carousel to clone
* or an array of OptionItem to initialize a new carousel
*/
constructor(carousel?: Carousel | OptionItem[]);
/**
* List of 2-20 items to show in this carousel. Required.
*/
items: OptionItem[];
/**
* Adds a single item or list of items to the carousel.
*
* @param optionItems OptionItems to add.
* @return Returns current constructed Carousel.
*/
addItems(optionItems: OptionItem | OptionItem[]): Carousel;
}
/**
* Class for initializing and constructing Option Items with chainable interface.
*/
export class OptionItem {
/**
* Constructor for OptionItem. Accepts optional OptionItem to clone.
*
* @param optionItem Optional OptionItem to clone.
*/
constructor(optionItem?: OptionItem);
/**
* Option info of the option item. Required.
*/
optionInfo: OptionInfo;
/**
* Title of the option item. Required.
*/
title: string;
/**
* Description text of the item. Optional.
*/
description?: string;
/**
* Image to show on item. Optional.
*/
image?: Image;
/**
* Sets the title for this Option Item.
*
* @param title Title to show on item.
* @return Returns current constructed OptionItem.
*/
setTitle(title: string): OptionItem;
/**
* Sets the description for this Option Item.
*
* @param description Description to show on item.
* @return Returns current constructed OptionItem.
*/
setDescription(description: string): OptionItem;
/**
* Sets the image for this Option Item.
*
* @param url Image source URL.
* @param accessibilityText Text to replace for image for
* accessibility.
* @param width Width of the image.
* @param height Height of the image.
* @return Returns current constructed OptionItem.
*/
setImage(url: string, accessibilityText: string, width?: number, height?: number): OptionItem;
/**
* Sets the key for the OptionInfo of this Option Item. This will be returned
* as an argument in the resulting actions.intent.OPTION intent.
*
* @param key Key to uniquely identify this item.
* @return Returns current constructed OptionItem.
*/
setKey(key: string): OptionItem;
/**
* Adds a single synonym or list of synonyms to item.
*
* @param synonyms Either a single string synonyms
* or list of synonyms to add.
* @return Returns current constructed OptionItem.
*/
addSynonyms(synonyms: string | string[]): OptionItem;
}
/**
* Check if given text contains SSML.
* @param text Text to check.
* @return True if text contains SSML, false otherwise.
*/
export function isSsml(text: string): boolean;
File diff suppressed because it is too large Load Diff
+28
View File
@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"assistant-app.d.ts",
"actions-sdk-app.d.ts",
"dialogflow-app.d.ts",
"response-builder.d.ts",
"transactions.d.ts",
"actions-on-google-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
@@ -0,0 +1,25 @@
let app = new ActiveXObject('Access.Application');
app.UserControl = true;
// opens a form
app.DoCmd.OpenForm('MyForm', Access.AcFormView.acNormal, '', 'LastName="Smith"');
// change the contents of a textbox
// tslint:disable-next-line:no-unnecessary-type-assertion
let textbox = app.Forms.Item('MyForm').Controls.Item('MyTextBox') as Access.TextBox;
textbox.Text = 'Not Smith';
// save the current record on the active form
app.RunCommand(Access.AcCommand.acCmdSaveRecord);
// close the form
app.DoCmd.Close(Access.AcObjectType.acForm, 'MyForm');
// open a report for printing
app.DoCmd.OpenReport('MyReport');
// open the same report in Design View
app.DoCmd.OpenReport('MyReport', Access.AcView.acViewDesign);
// run a VBA macro
app.Run('MyMacro', 'argument1', 2);
+8925
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-access-tests.ts"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
}
}
@@ -0,0 +1,57 @@
let obj0 = new ActiveXObject('ADODB.Command');
let obj1 = new ActiveXObject('ADODB.Connection');
let obj2 = new ActiveXObject('ADODB.Parameter');
let obj3 = new ActiveXObject('ADODB.Record');
let obj4 = new ActiveXObject('ADODB.Recordset');
let obj5 = new ActiveXObject('ADODB.Stream');
// open connection to an Excel file
let pathToExcelFile = 'C:\\path\\to\\excel\\file.xlsx';
let conn = new ActiveXObject('ADODB.Connection');
conn.Provider = 'Microsoft.ACE.OLEDB.12.0';
conn.ConnectionString = `Data Source="${pathToExcelFile}";Extended Properties="Excel 12.0;HDR=Yes"`;
conn.Open();
// create a Command to access the data
let cmd = new ActiveXObject('ADODB.Command');
cmd.ActiveConnection = conn;
cmd.CommandText = 'SELECT DISTINCT LastName, CityName FROM [Sheet1$]';
// get a Recordset
let rs = cmd.Execute();
// build a string from the Recordset
let s = rs.GetString(ADODB.StringFormatEnum.adClipString, -1, '\t', '\n', '(NULL)');
rs.Close();
WScript.Echo(s);
// create a disconnected recordset -- https://support.microsoft.com/en-us/help/184397/how-to-create-ado-disconnected-recordsets-in-vba-c-java
(() => {
conn = new ActiveXObject('ADODB.Connection');
conn.Open(); // pass connection details here
rs = new ActiveXObject('ADODB.Recordset');
rs.CursorLocation = ADODB.CursorLocationEnum.adUseClient;
rs.Open('SELECT * FROM Table1', conn, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockBatchOptimistic);
rs.ActiveConnection = null;
const v = rs.Fields.Item(0).Value;
conn.Close();
})();
// helper function
const toSafeArray = <T>(...items: T[]): SafeArray<T> => {
const dict = new ActiveXObject('Scripting.Dictionary');
items.forEach((x, index) => dict.Add(index, x));
return dict.Items() as SafeArray<T>;
};
// update with SafeArray
(() => {
const fields = toSafeArray('FirstName', 'LastName', 'DOB');
const values = toSafeArray<any>('Plony', 'Almony', new Date(1980, 1, 1).getVarDate());
rs.Update(fields, values);
})();
+1086
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-adodb-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+154
View File
@@ -0,0 +1,154 @@
let engine = new ActiveXObject('DAO.DBEngine.120');
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();
// 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);
// 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
const findRecordCount = (dbs: DAO.Database, sql: string) => {
let count = 0;
const rstRecords = dbs.OpenRecordset(sql);
if (!rstRecords.EOF) {
rstRecords.MoveLast();
count = rstRecords.RecordCount;
}
rstRecords.Close();
return count;
};
// 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;
}
rstShippers.MoveNext();
}
}
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));
}
}
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 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);
}
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
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);
}
return hireDate;
};
// manipulate multiple fields with DAO -- https://msdn.microsoft.com/VBA/Access-VBA/articles/manipulate-multivalued-fields-with-dao
const browseMultiValueField = () => {
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;
if (childRs.EOF) { continue; }
childRs.MoveFirst();
while (!childRs.EOF) {
WScript.Echo('\t' + childRs.Fields.Item('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');
while (!rstEmployees.EOF) {
if (rstEmployees.Fields.Item('Title').Value === 'Sales Representative') {
rstEmployees.Edit();
rstEmployees.Fields.Item('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
const changeTitleWithTransaction = (commitTransaction: boolean) => {
const currentWorkspace = engine.Workspaces.Item(0);
rstEmployees = dbsNorthwind.OpenRecordset('Employees');
currentWorkspace.BeginTrans();
while (!rstEmployees.EOF) {
if (rstEmployees.Fields.Item('Title').Value === 'Sales Representative') {
rstEmployees.Edit();
rstEmployees.Fields.Item('Title').Value = 'Account Executive';
rstEmployees.Update();
}
rstEmployees.MoveNext();
}
if (commitTransaction) {
currentWorkspace.CommitTrans();
} else {
currentWorkspace.Rollback();
}
rstEmployees.Close();
currentWorkspace.Close();
};
+910
View File
@@ -0,0 +1,910 @@
// Type definitions for Microsoft Office 14.0 Access Database Engine Object Library - DAO 14.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
declare namespace DAO {
const enum _DAOSuppHelp {
KeepLocal = 0,
LogMessages = 0,
Replicable = 0,
ReplicableBool = 0,
V1xNullBehavior = 0,
}
const enum CollatingOrderEnum {
dbSortArabic = 1025,
dbSortChineseSimplified = 2052,
dbSortChineseTraditional = 1028,
dbSortCyrillic = 1049,
dbSortCzech = 1029,
dbSortDutch = 1043,
dbSortGeneral = 1033,
dbSortGreek = 1032,
dbSortHebrew = 1037,
dbSortHindi = 1081,
dbSortHungarian = 1038,
dbSortIcelandic = 1039,
dbSortJapanese = 1041,
dbSortJapaneseRadicalStrokeCount = 263185,
dbSortKorean = 1042,
dbSortNeutral = 1024,
dbSortNorwdan = 1030,
dbSortPDXIntl = 1033,
dbSortPDXNor = 1030,
dbSortPDXSwe = 1053,
dbSortPolish = 1045,
dbSortSlovenian = 1060,
dbSortSpanish = 1034,
dbSortSwedFin = 1053,
dbSortThai = 1054,
dbSortTurkish = 1055,
dbSortUndefined = -1,
}
const enum CommitTransOptionsEnum {
dbForceOSFlush = 1,
}
const enum CursorDriverEnum {
dbUseClientBatchCursor = 3,
dbUseDefaultCursor = -1,
dbUseNoCursor = 4,
dbUseODBCCursor = 1,
dbUseServerCursor = 2,
}
const enum DatabaseTypeEnum {
dbDecrypt = 4,
dbEncrypt = 2,
dbVersion10 = 1,
dbVersion11 = 8,
dbVersion120 = 128,
dbVersion140 = 256,
dbVersion20 = 16,
dbVersion30 = 32,
dbVersion40 = 64,
}
const enum DataTypeEnum {
dbAttachment = 101,
dbBigInt = 16,
dbBinary = 9,
dbBoolean = 1,
dbByte = 2,
dbChar = 18,
dbComplexByte = 102,
dbComplexDecimal = 108,
dbComplexDouble = 106,
dbComplexGUID = 107,
dbComplexInteger = 103,
dbComplexLong = 104,
dbComplexSingle = 105,
dbComplexText = 109,
dbCurrency = 5,
dbDate = 8,
dbDecimal = 20,
dbDouble = 7,
dbFloat = 21,
dbGUID = 15,
dbInteger = 3,
dbLong = 4,
dbLongBinary = 11,
dbMemo = 12,
dbNumeric = 19,
dbSingle = 6,
dbText = 10,
dbTime = 22,
dbTimeStamp = 23,
dbVarBinary = 17,
}
const enum DriverPromptEnum {
dbDriverComplete = 0,
dbDriverCompleteRequired = 3,
dbDriverNoPrompt = 1,
dbDriverPrompt = 2,
}
const enum EditModeEnum {
dbEditAdd = 2,
dbEditInProgress = 1,
dbEditNone = 0,
}
const enum FieldAttributeEnum {
dbAutoIncrField = 16,
dbDescending = 1,
dbFixedField = 1,
dbHyperlinkField = 32768,
dbSystemField = 8192,
dbUpdatableField = 32,
dbVariableField = 2,
}
const enum IdleEnum {
dbFreeLocks = 1,
dbRefreshCache = 8,
}
const enum LanguageConstants {
dbLangArabic = ';LANGID=0x0401;CP=1256;COUNTRY=0',
dbLangChineseSimplified = ';LANGID=0x0804;CP=936;COUNTRY=0',
dbLangChineseTraditional = ';LANGID=0x0404;CP=950;COUNTRY=0',
dbLangCyrillic = ';LANGID=0x0419;CP=1251;COUNTRY=0',
dbLangCzech = ';LANGID=0x0405;CP=1250;COUNTRY=0',
dbLangDutch = ';LANGID=0x0413;CP=1252;COUNTRY=0',
dbLangGeneral = ';LANGID=0x0409;CP=1252;COUNTRY=0',
dbLangGreek = ';LANGID=0x0408;CP=1253;COUNTRY=0',
dbLangHebrew = ';LANGID=0x040D;CP=1255;COUNTRY=0',
dbLangHindi = ';LANGID=0x00000439;CP=65001;COUNTRY=0',
dbLangHungarian = ';LANGID=0x040E;CP=1250;COUNTRY=0',
dbLangIcelandic = ';LANGID=0x040F;CP=1252;COUNTRY=0',
dbLangJapanese = ';LANGID=0x0411;CP=932;COUNTRY=0',
dbLangJapaneseRadicalStrokeCount = ';LANGID=0x00040411;CP=65001;COUNTRY=0',
dbLangKorean = ';LANGID=0x0412;CP=949;COUNTRY=0',
dbLangNordic = ';LANGID=0x041D;CP=1252;COUNTRY=0',
dbLangNorwDan = ';LANGID=0x0406;CP=1252;COUNTRY=0',
dbLangPolish = ';LANGID=0x0415;CP=1250;COUNTRY=0',
dbLangSlovenian = ';LANGID=0x0424;CP=1250;COUNTRY=0',
dbLangSpanish = ';LANGID=0x040A;CP=1252;COUNTRY=0',
dbLangSwedFin = ';LANGID=0x041D;CP=1252;COUNTRY=0',
dbLangThai = ';LANGID=0x041E;CP=874;COUNTRY=0',
dbLangTurkish = ';LANGID=0x041F;CP=1254;COUNTRY=0',
}
const enum LockTypeEnum {
dbOptimistic = 3,
dbOptimisticBatch = 5,
dbOptimisticValue = 1,
dbPessimistic = 2,
}
const enum ParameterDirectionEnum {
dbParamInput = 1,
dbParamInputOutput = 3,
dbParamOutput = 2,
dbParamReturnValue = 4,
}
const enum PermissionEnum {
dbSecCreate = 1,
dbSecDBAdmin = 8,
dbSecDBCreate = 1,
dbSecDBExclusive = 4,
dbSecDBOpen = 2,
dbSecDelete = 65536,
dbSecDeleteData = 128,
dbSecFullAccess = 1048575,
dbSecInsertData = 32,
dbSecNoAccess = 0,
dbSecReadDef = 4,
dbSecReadSec = 131072,
dbSecReplaceData = 64,
dbSecRetrieveData = 20,
dbSecWriteDef = 65548,
dbSecWriteOwner = 524288,
dbSecWriteSec = 262144,
}
const enum QueryDefStateEnum {
dbQPrepare = 1,
dbQUnprepare = 2,
}
const enum QueryDefTypeEnum {
dbQAction = 240,
dbQAppend = 64,
dbQCompound = 160,
dbQCrosstab = 16,
dbQDDL = 96,
dbQDelete = 32,
dbQMakeTable = 80,
dbQProcedure = 224,
dbQSelect = 0,
dbQSetOperation = 128,
dbQSPTBulk = 144,
dbQSQLPassThrough = 112,
dbQUpdate = 48,
}
const enum RecordsetOptionEnum {
dbAppendOnly = 8,
dbConsistent = 32,
dbDenyRead = 2,
dbDenyWrite = 1,
dbExecDirect = 2048,
dbFailOnError = 128,
dbForwardOnly = 256,
dbInconsistent = 16,
dbReadOnly = 4,
dbRunAsync = 1024,
dbSeeChanges = 512,
dbSQLPassThrough = 64,
}
const enum RecordsetTypeEnum {
dbOpenDynamic = 16,
dbOpenDynaset = 2,
dbOpenForwardOnly = 8,
dbOpenSnapshot = 4,
dbOpenTable = 1,
}
const enum RecordStatusEnum {
dbRecordDBDeleted = 4,
dbRecordDeleted = 3,
dbRecordModified = 1,
dbRecordNew = 2,
dbRecordUnmodified = 0,
}
const enum RelationAttributeEnum {
dbRelationDeleteCascade = 4096,
dbRelationDontEnforce = 2,
dbRelationInherited = 4,
dbRelationLeft = 16777216,
dbRelationRight = 33554432,
dbRelationUnique = 1,
dbRelationUpdateCascade = 256,
}
const enum ReplicaTypeEnum {
dbRepMakePartial = 1,
dbRepMakeReadOnly = 2,
}
const enum SetOptionEnum {
dbExclusiveAsyncDelay = 60,
dbFlushTransactionTimeout = 66,
dbImplicitCommitSync = 59,
dbLockDelay = 63,
dbLockRetry = 57,
dbMaxBufferSize = 8,
dbMaxLocksPerFile = 62,
dbPageTimeout = 6,
dbPasswordEncryptionAlgorithm = 81,
dbPasswordEncryptionKeyLength = 82,
dbPasswordEncryptionProvider = 80,
dbRecycleLVs = 65,
dbSharedAsyncDelay = 61,
dbUserCommitSync = 58,
}
const enum SynchronizeTypeEnum {
dbRepExportChanges = 1,
dbRepImpExpChanges = 4,
dbRepImportChanges = 2,
dbRepSyncInternet = 16,
}
const enum TableDefAttributeEnum {
dbAttachedODBC = 536870912,
dbAttachedTable = 1073741824,
dbAttachExclusive = 65536,
dbAttachSavePWD = 131072,
dbHiddenObject = 1,
dbSystemObject = -2147483646,
}
const enum UpdateCriteriaEnum {
dbCriteriaAllCols = 4,
dbCriteriaDeleteInsert = 16,
dbCriteriaKey = 1,
dbCriteriaModValues = 2,
dbCriteriaTimestamp = 8,
dbCriteriaUpdate = 32,
}
const enum UpdateTypeEnum {
dbUpdateBatch = 4,
dbUpdateCurrentRecord = 2,
dbUpdateRegular = 1,
}
const enum WorkspaceTypeEnum {
dbUseJet = 2,
dbUseODBC = 1,
}
class Connection {
private 'DAO.Connection_typekey': Connection;
private constructor();
Cancel(): void;
Close(): void;
readonly Connect: string;
CreateQueryDef(Name?: any, SQLText?: any): QueryDef;
readonly Database: Database;
Execute(Query: string, Options?: any): void;
readonly hDbc: number;
readonly Name: string;
OpenRecordset(Name: string, Type?: any, Options?: any, LockEdit?: any): Recordset;
readonly QueryDefs: QueryDefs;
QueryTimeout: number;
readonly RecordsAffected: number;
readonly Recordsets: Recordsets;
readonly StillExecuting: boolean;
readonly Transactions: boolean;
readonly Updatable: boolean;
}
class Connections {
private 'DAO.Connections_typekey': Connections;
private constructor();
readonly Count: number;
Item(Item: any): Connection;
Refresh(): void;
}
class Container {
private 'DAO.Container_typekey': Container;
private constructor();
readonly AllPermissions: number;
readonly Documents: Documents;
Inherit: boolean;
readonly Name: string;
Owner: string;
Permissions: number;
readonly Properties: Properties;
UserName: string;
}
class Containers {
private 'DAO.Containers_typekey': Containers;
private constructor();
readonly Count: number;
Item(Item: any): Container;
Refresh(): void;
}
class Database {
private 'DAO.Database_typekey': Database;
private constructor();
Close(): void;
readonly CollatingOrder: number;
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;
DesignMasterID: string;
Execute(Query: string, Options?: any): void;
MakeReplica(PathName: string, Description: string, Options?: any): void;
readonly Name: string;
NewPassword(bstrOld: string, bstrNew: string): void;
OpenRecordset(Name: string, Type?: any, Options?: any, LockEdit?: any): Recordset;
PopulatePartial(DbPathName: string): void;
readonly Properties: Properties;
readonly QueryDefs: QueryDefs;
QueryTimeout: number;
readonly RecordsAffected: number;
readonly Recordsets: Recordsets;
readonly Relations: Relations;
readonly ReplicaID: string;
Synchronize(DbPathName: string, ExchangeType?: any): void;
readonly TableDefs: TableDefs;
readonly Transactions: boolean;
readonly Updatable: boolean;
readonly Version: string;
}
class Databases {
private 'DAO.Databases_typekey': Databases;
private constructor();
readonly Count: number;
Item(Item: any): Database;
Refresh(): void;
}
class DBEngine {
private 'DAO.DBEngine_typekey': DBEngine;
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 Document {
private 'DAO.Document_typekey': Document;
private constructor();
readonly AllPermissions: number;
readonly Container: string;
CreateProperty(Name?: any, Type?: any, Value?: any, DDL?: any): Property;
readonly DateCreated: any;
readonly LastUpdated: any;
readonly Name: string;
Owner: string;
Permissions: number;
readonly Properties: Properties;
UserName: string;
}
class Documents {
private 'DAO.Documents_typekey': Documents;
private constructor();
readonly Count: number;
Item(Item: any): Document;
Refresh(): void;
}
class Error {
private 'DAO.Error_typekey': Error;
private constructor();
readonly Description: string;
readonly HelpContext: number;
readonly HelpFile: string;
readonly Number: number;
readonly Source: string;
}
class Errors {
private 'DAO.Errors_typekey': Errors;
private constructor();
readonly Count: number;
Item(Item: any): Error;
Refresh(): void;
}
class Field {
private 'DAO.Field_typekey': Field;
private constructor();
AllowZeroLength: boolean;
AppendChunk(Val: any): void;
Attributes: number;
readonly CollatingOrder: number;
readonly CollectionIndex: number;
CreateProperty(Name?: any, Type?: any, Value?: any, DDL?: any): Property;
readonly DataUpdatable: boolean;
DefaultValue: any;
readonly FieldSize: number;
ForeignName: string;
GetChunk(Offset: number, Bytes: number): any;
Name: string;
OrdinalPosition: number;
readonly OriginalValue: any;
readonly Properties: Properties;
Required: boolean;
Size: number;
readonly SourceField: string;
readonly SourceTable: string;
Type: number;
ValidateOnSet: boolean;
ValidationRule: string;
ValidationText: string;
Value: any;
readonly VisibleValue: any;
}
class Fields {
private 'DAO.Fields_typekey': Fields;
private constructor();
Append(Object: any): void;
readonly Count: number;
Delete(Name: string): void;
Item(Item: any): Field;
Refresh(): void;
}
class Group {
private 'DAO.Group_typekey': Group;
private constructor();
CreateUser(Name?: any, PID?: any, Password?: any): 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;
readonly Count: number;
Delete(Name: string): void;
Item(Item: any): Group;
Refresh(): void;
}
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;
readonly DistinctCount: number;
Fields: any;
readonly Foreign: boolean;
IgnoreNulls: boolean;
Name: string;
Primary: boolean;
readonly Properties: Properties;
Required: boolean;
Unique: boolean;
}
class Indexes {
private 'DAO.Indexes_typekey': Indexes;
private constructor();
Append(Object: any): void;
readonly Count: number;
Delete(Name: string): void;
Item(Item: any): Index;
Refresh(): void;
}
class Parameter {
private 'DAO.Parameter_typekey': Parameter;
private constructor();
Direction: number;
readonly Name: string;
readonly Properties: Properties;
Type: number;
Value: any;
}
class Parameters {
private 'DAO.Parameters_typekey': Parameters;
private constructor();
readonly Count: number;
Item(Item: any): Parameter;
Refresh(): void;
}
/** 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;
readonly Count: number;
Delete(Name: string): void;
Item(Item: any): Property;
Refresh(): void;
}
class Property {
private 'DAO.Property_typekey': Property;
private constructor();
readonly Inherited: boolean;
Name: string;
readonly Properties: Properties;
Type: number;
Value: any;
}
class QueryDef {
private 'DAO.QueryDef_typekey': QueryDef;
private constructor();
CacheSize: number;
Cancel(): void;
Close(): void;
Connect: string;
CreateProperty(Name?: any, Type?: any, Value?: any, DDL?: any): Property;
readonly DateCreated: any;
Execute(Options?: any): void;
readonly Fields: Fields;
readonly hStmt: number;
readonly LastUpdated: any;
MaxRecords: number;
Name: string;
ODBCTimeout: number;
OpenRecordset(Type?: any, Options?: any, LockEdit?: any): Recordset;
readonly Parameters: Parameters;
Prepare: any;
readonly Properties: Properties;
readonly RecordsAffected: number;
ReturnsRecords: boolean;
SQL: string;
readonly StillExecuting: boolean;
readonly Type: number;
readonly Updatable: boolean;
}
class QueryDefs {
private 'DAO.QueryDefs_typekey': QueryDefs;
private constructor();
Append(Object: any): void;
readonly Count: number;
Delete(Name: string): void;
Item(Item: any): QueryDef;
Refresh(): void;
}
class Recordset {
private 'DAO.Recordset_typekey': Recordset;
private constructor();
AbsolutePosition: number;
AddNew(): void;
readonly BatchCollisionCount: number;
readonly BatchCollisions: any;
BatchSize: number;
readonly BOF: boolean;
Bookmark: SafeArray<number>;
readonly Bookmarkable: boolean;
CacheSize: number;
CacheStart: SafeArray<number>;
Cancel(): void;
/** @param number [UpdateType=1] */
CancelUpdate(UpdateType?: number): void;
Clone(): Recordset;
Close(): void;
Collect(Item: any): any;
Connection: Connection;
CopyQueryDef(): QueryDef;
readonly DateCreated: any;
Delete(): void;
Edit(): void;
readonly EditMode: number;
readonly EOF: boolean;
readonly Fields: Fields;
FillCache(Rows?: any, StartBookmark?: any): void;
Filter: string;
FindFirst(Criteria: string): void;
FindLast(Criteria: string): void;
FindNext(Criteria: string): void;
FindPrevious(Criteria: string): void;
GetRows(NumRows?: any): any;
readonly hStmt: number;
Index: string;
readonly LastModified: SafeArray<number>;
readonly LastUpdated: any;
LockEdits: boolean;
Move(Rows: number, StartBookmark?: any): void;
MoveFirst(): void;
/** @param number [Options=0] */
MoveLast(Options?: number): void;
MoveNext(): void;
MovePrevious(): void;
readonly Name: string;
NextRecordset(): boolean;
readonly NoMatch: boolean;
readonly ODBCFetchCount: number;
readonly ODBCFetchDelay: number;
OpenRecordset(Type?: any, Options?: any): Recordset;
readonly Parent: Database;
PercentPosition: number;
readonly Properties: Properties;
readonly RecordCount: number;
readonly RecordStatus: number;
Requery(NewQueryDef?: any): void;
readonly Restartable: boolean;
Seek(
Comparison: string, Key1: any, Key2?: any, Key3?: any, Key4?: any, Key5?: any, Key6?: any, Key7?: any, Key8?: any, Key9?: any, Key10?: any, Key11?: any, Key12?: any, Key13?: any): void;
Sort: string;
readonly StillExecuting: boolean;
readonly Transactions: boolean;
readonly Type: number;
readonly Updatable: boolean;
/**
* @param number [UpdateType=1]
* @param boolean [Force=false]
*/
Update(UpdateType?: number, Force?: boolean): void;
UpdateOptions: number;
readonly ValidationRule: string;
readonly ValidationText: string;
}
class Recordsets {
private 'DAO.Recordsets_typekey': Recordsets;
private constructor();
readonly Count: number;
Item(Item: any): Recordset;
Refresh(): void;
}
class Relation {
private 'DAO.Relation_typekey': Relation;
private constructor();
Attributes: number;
CreateField(Name?: any, Type?: any, Size?: any): Field;
readonly Fields: Fields;
ForeignTable: string;
Name: string;
PartialReplica: boolean;
readonly Properties: Properties;
Table: string;
}
class Relations {
private 'DAO.Relations_typekey': Relations;
private constructor();
Append(Object: any): void;
readonly Count: number;
Delete(Name: string): void;
Item(Item: any): Relation;
Refresh(): void;
}
class TableDef {
private 'DAO.TableDef_typekey': TableDef;
private constructor();
Attributes: number;
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;
readonly Fields: Fields;
readonly Indexes: Indexes;
readonly LastUpdated: any;
Name: string;
OpenRecordset(Type?: any, Options?: any): Recordset;
readonly Properties: Properties;
readonly RecordCount: number;
RefreshLink(): void;
ReplicaFilter: any;
SourceTableName: string;
readonly Updatable: boolean;
ValidationRule: string;
ValidationText: string;
}
class TableDefs {
private 'DAO.TableDefs_typekey': TableDefs;
private constructor();
Append(Object: any): void;
readonly Count: number;
Delete(Name: string): void;
Item(Item: any): TableDef;
Refresh(): void;
}
class User {
private 'DAO.User_typekey': User;
private constructor();
CreateGroup(Name?: any, PID?: any): Group;
readonly Groups: Groups;
Name: string;
NewPassword(bstrOld: string, bstrNew: string): void;
readonly Password: string;
readonly PID: string;
readonly Properties: Properties;
}
class Users {
private 'DAO.Users_typekey': Users;
private constructor();
Append(Object: any): void;
readonly Count: number;
Delete(Name: string): void;
Item(Item: any): User;
Refresh(): void;
}
class Workspace {
private 'DAO.Workspace_typekey': Workspace;
private constructor();
BeginTrans(): void;
Close(): void;
/** @param number [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;
readonly Databases: Databases;
DefaultCursorDriver: number;
readonly Groups: Groups;
readonly hEnv: number;
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;
readonly Properties: Properties;
Rollback(): void;
readonly Type: number;
readonly UserName: string;
readonly Users: Users;
}
class Workspaces {
private 'DAO.Workspaces_typekey': Workspaces;
private constructor();
Append(Object: any): void;
readonly Count: number;
Delete(Name: string): void;
Item(Item: any): Workspace;
Refresh(): void;
}
}
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.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>;
}
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-dao-tests.ts"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
}
}
@@ -1,18 +0,0 @@
//open connection to an Excel file
var pathToExcelFile = 'C:\\path\\to\\excel\\file.xlsx';
var conn = new ActiveXObject('ADODB.Connection');
conn.Provider = 'Microsoft.ACE.OLEDB.12.0';
conn.ConnectionString =
'Data Source="' + pathToExcelFile + '";' +
'Extended Properties="Excel 12.0;HDR=Yes"';
conn.Open();
//create a Command to access the data
var cmd = new ActiveXObject('ADODB.Command');
cmd.CommandText = 'SELECT DISTINCT LastName, CityName FROM [Sheet1$]';
//get a Recordset
var rs = cmd.Execute();
//build a string from the Recordset
var s = rs.GetString(ADODB.StringFormatEnum.adClipString, -1, '\t', '\n', '(NULL)');
rs.Close();
WScript.Echo(s);
-834
View File
@@ -1,834 +0,0 @@
// Type definitions for Microsoft ActiveX Data Objects
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms675532(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace ADODB {
//Enums
const enum ADCPROP_ASYNCTHREADPRIORITY_ENUM {
adPriorityAboveNormal = 4,
adPriorityBelowNormal = 2,
adPriorityHighest = 5,
adPriorityLowest = 1,
adPriorityNormal = 3
}
const enum ADCPROP_AUTORECALC_ENUM {
adRecalcAlways = 1,
adRecalcUpFront = 0
}
const enum ADCPROP_UPDATECRITERIA_ENUM {
adCriteriaAllCols = 1,
adCriteriaKey = 0,
adCriteriaTimeStamp = 3,
adCriteriaUpdCols = 2
}
const enum ADCPROP_UPDATERESYNC_ENUM {
adResyncAll = 15,
adResyncAutoIncrement = 1,
adResyncConflicts = 2,
adResyncInserts = 8,
adResyncNone = 0,
adResyncUpdates = 4
}
const enum AffectEnum {
adAffectAll = 3,
adAffectAllChapters = 4,
adAffectCurrent = 1,
adAffectGroup = 2
}
const enum BookmarkEnum {
adBookmarkCurrent = 0,
adBookmarkFirst = 1,
adBookmarkLast = 2
}
const enum CommandTypeEnum {
adCmdFile = 256,
adCmdStoredProc = 4,
adCmdTable = 2,
adCmdTableDirect = 512,
adCmdText = 1,
adCmdUnknown = 8,
adCmdUnspecified = -1
}
const enum CompareEnum {
adCompareEqual = 1,
adCompareGreaterThan = 2,
adCompareLessThan = 0,
adCompareNotComparable = 4,
adCompareNotEqual = 3
}
const enum ConnectModeEnum {
adModeRead = 1,
adModeReadWrite = 3,
adModeRecursive = 4194304,
adModeShareDenyNone = 16,
adModeShareDenyRead = 4,
adModeShareDenyWrite = 8,
adModeShareExclusive = 12,
adModeUnknown = 0,
adModeWrite = 2
}
const enum ConnectOptionEnum {
adAsyncConnect = 16,
adConnectUnspecified = -1
}
const enum ConnectPromptEnum {
adPromptAlways = 1,
adPromptComplete = 2,
adPromptCompleteRequired = 3,
adPromptNever = 4
}
const enum CopyRecordOptionsEnum {
adCopyAllowEmulation = 4,
adCopyNonRecursive = 2,
adCopyOverWrite = 1,
adCopyUnspecified = -1
}
const enum CursorLocationEnum {
adUseClient = 3,
adUseClientBatch = 3,
adUseNone = 1,
adUseServer = 2
}
const enum CursorOptionEnum {
adAddNew = 16778240,
adApproxPosition = 16384,
adBookmark = 8192,
adDelete = 16779264,
adFind = 524288,
adHoldRecords = 256,
adIndex = 8388608,
adMovePrevious = 512,
adNotify = 262144,
adResync = 131072,
adSeek = 4194304,
adUpdate = 16809984,
adUpdateBatch = 65536
}
const enum CursorTypeEnum {
adOpenDynamic = 2,
adOpenForwardOnly = 0,
adOpenKeyset = 1,
adOpenStatic = 3,
adOpenUnspecified = -1
}
const enum DataTypeEnum {
adArray = 8192,
adBigInt = 20,
adBinary = 128,
adBoolean = 11,
adBSTR = 8,
adChapter = 136,
adChar = 129,
adCurrency = 6,
adDate = 7,
adDBDate = 133,
adDBTime = 134,
adDBTimeStamp = 135,
adDecimal = 14,
adDouble = 5,
adEmpty = 0,
adError = 10,
adFileTime = 64,
adGUID = 72,
adIDispatch = 9,
adInteger = 3,
adIUnknown = 13,
adLongVarBinary = 205,
adLongVarChar = 201,
adLongVarWChar = 203,
adNumeric = 131,
adPropVariant = 138,
adSingle = 4,
adSmallInt = 2,
adTinyInt = 16,
adUnsignedBigInt = 21,
adUnsignedInt = 19,
adUnsignedSmallInt = 18,
adUnsignedTinyInt = 17,
adUserDefined = 132,
adVarBinary = 204,
adVarChar = 200,
adVariant = 12,
adVarNumeric = 139,
adVarWChar = 202,
adWChar = 130
}
const enum EditModeEnum {
adEditAdd = 2,
adEditDelete = 4,
adEditInProgress = 1,
adEditNone = 0
}
const enum ErrorValueEnum {
adErrBoundToCommand = 3707,
adErrCannotComplete = 3732,
adErrCantChangeConnection = 3748,
adErrCantChangeProvider = 3220,
adErrCantConvertvalue = 3724,
adErrCantCreate = 3725,
adErrCatalogNotSet = 3747,
adErrColumnNotOnThisRow = 3726,
adErrConnectionStringTooLong = 3754,
adErrDataConversion = 3421,
adErrDataOverflow = 3721,
adErrDelResOutOfScope = 3738,
adErrDenyNotSupported = 3750,
adErrDenyTypeNotSupported = 3751,
adErrFeatureNotAvailable = 3251,
adErrFieldsUpdateFailed = 3749,
adErrIllegalOperation = 3219,
adErrIntegrityViolation = 3719,
adErrInTransaction = 3246,
adErrInvalidArgument = 3001,
adErrInvalidConnection = 3709,
adErrInvalidParamInfo = 3708,
adErrInvalidTransaction = 3714,
adErrInvalidURL = 3729,
adErrItemNotFound = 3265,
adErrNoCurrentRecord = 3021,
adErrNotExecuting = 3715,
adErrNotReentrant = 3710,
adErrObjectClosed = 3704,
adErrObjectInCollection = 3367,
adErrObjectNotSet = 3420,
adErrObjectOpen = 3705,
adErrOpeningFile = 3002,
adErrOperationCancelled = 3712,
adErrOutOfSpace = 3734,
adErrPermissionDenied = 3720,
adErrPropConflicting = 3742,
adErrPropInvalidColumn = 3739,
adErrPropInvalidOption = 3740,
adErrPropInvalidValue = 3741,
adErrPropNotAllSettable = 3743,
adErrPropNotSet = 3744,
adErrPropNotSettable = 3745,
adErrPropNotSupported = 3746,
adErrProviderFailed = 3000,
adErrProviderNotFound = 3706,
adErrProviderNotSpecified = 3753,
adErrReadFile = 3003,
adErrResourceExists = 3731,
adErrResourceLocked = 3730,
adErrResourceOutOfScope = 3735,
adErrSchemaViolation = 3722,
adErrSignMismatch = 3723,
adErrStillConnecting = 3713,
adErrStillExecuting = 3711,
adErrTreePermissionDenied = 3728,
adErrUnavailable = 3736,
adErrUnsafeOperation = 3716,
adErrURLDoesNotExist = 3727,
adErrURLNamedRowDoesNotExist = 3737,
adErrVolumeNotFound = 3733,
adErrWriteFile = 3004,
adwrnSecurityDialog = 3717,
adwrnSecurityDialogHeader = 3718
}
const enum EventReasonEnum {
adRsnAddNew = 1,
adRsnClose = 9,
adRsnDelete = 2,
adRsnFirstChange = 11,
adRsnMove = 10,
adRsnMoveFirst = 12,
adRsnMoveLast = 15,
adRsnMoveNext = 13,
adRsnMovePrevious = 14,
adRsnRequery = 7,
adRsnResynch = 8,
adRsnUndoAddNew = 5,
adRsnUndoDelete = 6,
adRsnUndoUpdate = 4,
adRsnUpdate = 3
}
const enum EventStatusEnum {
adStatusCancel = 4,
adStatusCantDeny = 3,
adStatusErrorsOccurred = 2,
adStatusOK = 1,
adStatusUnwantedEvent = 5
}
const enum ExecuteOptionEnum {
adAsyncExecute = 16,
adAsyncFetch = 32,
adAsyncFetchNonBlocking = 64,
adExecuteNoRecords = 128,
adExecuteRecord = 2048,
adExecuteStream = 1024,
adOptionUnspecified = -1
}
const enum FieldAttributeEnum {
adFldCacheDeferred = 4096,
adFldFixed = 16,
adFldIsChapter = 8192,
adFldIsCollection = 262144,
adFldIsDefaultStream = 131072,
adFldIsNullable = 32,
adFldIsRowURL = 65536,
adFldKeyColumn = 32768,
adFldLong = 128,
adFldMayBeNull = 64,
adFldMayDefer = 2,
adFldNegativeScale = 16384,
adFldRowID = 256,
adFldRowVersion = 512,
adFldUnknownUpdatable = 8,
adFldUnspecified = -1,
adFldUpdatable = 4
}
const enum FieldEnum {
adDefaultStream = -1,
adRecordURL = -2
}
const enum FieldStatusEnum {
adFieldAlreadyExists = 26,
adFieldBadStatus = 12,
adFieldCannotComplete = 20,
adFieldCannotDeleteSource = 23,
adFieldCantConvertValue = 2,
adFieldCantCreate = 7,
adFieldDataOverflow = 6,
adFieldDefault = 13,
adFieldDoesNotExist = 16,
adFieldIgnore = 15,
adFieldIntegrityViolation = 10,
adFieldInvalidURL = 17,
adFieldIsNull = 3,
adFieldOK = 0,
adFieldOutOfSpace = 22,
adFieldPendingChange = 262144,
adFieldPendingDelete = 131072,
adFieldPendingInsert = 65536,
adFieldPendingUnknown = 524288,
adFieldPendingUnknownDelete = 1048576,
adFieldPermissionDenied = 9,
adFieldReadOnly = 24,
adFieldResourceExists = 19,
adFieldResourceLocked = 18,
adFieldResourceOutOfScope = 25,
adFieldSchemaViolation = 11,
adFieldSignMismatch = 5,
adFieldTruncated = 4,
adFieldUnavailable = 8,
adFieldVolumeNotFound = 21
}
const enum FilterGroupEnum {
adFilterAffectedRecords = 2,
adFilterConflictingRecords = 5,
adFilterFetchedRecords = 3,
adFilterNone = 0,
adFilterPendingRecords = 1,
adFilterPredicate = 4
}
const enum GetRowsOptionEnum {
adGetRowsRest = -1
}
const enum IsolationLevelEnum {
adXactBrowse = 256,
adXactChaos = 16,
adXactCursorStability = 4096,
adXactIsolated = 1048576,
adXactReadCommitted = 4096,
adXactReadUncommitted = 256,
adXactRepeatableRead = 65536,
adXactSerializable = 1048576,
adXactUnspecified = -1
}
const enum LineSeparatorEnum {
adCR = 13,
adCRLF = -1,
adLF = 10
}
const enum LockTypeEnum {
adLockBatchOptimistic = 4,
adLockOptimistic = 3,
adLockPessimistic = 2,
adLockReadOnly = 1,
adLockUnspecified = -1
}
const enum MarshalOptionsEnum {
adMarshalAll = 0,
adMarshalModifiedOnly = 1
}
const enum MoveRecordOptionsEnum {
adMoveAllowEmulation = 4,
adMoveDontUpdateLinks = 2,
adMoveOverWrite = 1,
adMoveUnspecified = -1
}
const enum ObjectStateEnum {
adStateClosed = 0,
adStateConnecting = 2,
adStateExecuting = 4,
adStateFetching = 8,
adStateOpen = 1
}
const enum ParameterAttributesEnum {
adParamLong = 128,
adParamNullable = 64,
adParamSigned = 16
}
const enum ParameterDirectionEnum {
adParamInput = 1,
adParamInputOutput = 3,
adParamOutput = 2,
adParamReturnValue = 4,
adParamUnknown = 0
}
const enum PersistFormatEnum {
adPersistADTG = 0,
adPersistXML = 1
}
const enum PositionEnum {
adPosBOF = -2,
adPosEOF = -3,
adPosUnknown = -1
}
const enum PositionEnum_Param {
adPosBOF = -2,
adPosEOF = -3,
adPosUnknown = -1
}
const enum PropertyAttributesEnum {
adPropNotSupported = 0,
adPropOptional = 2,
adPropRead = 512,
adPropRequired = 1,
adPropWrite = 1024
}
const enum RecordCreateOptionsEnum {
adCreateCollection = 8192,
adCreateNonCollection = 0,
adCreateOverwrite = 67108864,
adCreateStructDoc = -2147483648,
adFailIfNotExists = -1,
adOpenIfExists = 33554432
}
const enum RecordOpenOptionsEnum {
adDelayFetchFields = 32768,
adDelayFetchStream = 16384,
adOpenAsync = 4096,
adOpenExecuteCommand = 65536,
adOpenOutput = 8388608,
adOpenRecordUnspecified = -1,
adOpenSource = 8388608
}
const enum RecordStatusEnum {
adRecCanceled = 256,
adRecCantRelease = 1024,
adRecConcurrencyViolation = 2048,
adRecDBDeleted = 262144,
adRecDeleted = 4,
adRecIntegrityViolation = 4096,
adRecInvalid = 16,
adRecMaxChangesExceeded = 8192,
adRecModified = 2,
adRecMultipleChanges = 64,
adRecNew = 1,
adRecObjectOpen = 16384,
adRecOK = 0,
adRecOutOfMemory = 32768,
adRecPendingChanges = 128,
adRecPermissionDenied = 65536,
adRecSchemaViolation = 131072,
adRecUnmodified = 8
}
const enum RecordTypeEnum {
adCollectionRecord = 1,
adSimpleRecord = 0,
adStructDoc = 2
}
const enum ResyncEnum {
adResyncAllValues = 2,
adResyncUnderlyingValues = 1
}
const enum SaveOptionsEnum {
adSaveCreateNotExist = 1,
adSaveCreateOverWrite = 2
}
const enum SchemaEnum {
adSchemaActions = 41,
adSchemaAsserts = 0,
adSchemaCatalogs = 1,
adSchemaCharacterSets = 2,
adSchemaCheckConstraints = 5,
adSchemaCollations = 3,
adSchemaColumnPrivileges = 13,
adSchemaColumns = 4,
adSchemaColumnsDomainUsage = 11,
adSchemaCommands = 42,
adSchemaConstraintColumnUsage = 6,
adSchemaConstraintTableUsage = 7,
adSchemaCubes = 32,
adSchemaDBInfoKeywords = 30,
adSchemaDBInfoLiterals = 31,
adSchemaDimensions = 33,
adSchemaForeignKeys = 27,
adSchemaFunctions = 40,
adSchemaHierarchies = 34,
adSchemaIndexes = 12,
adSchemaKeyColumnUsage = 8,
adSchemaLevels = 35,
adSchemaMeasures = 36,
adSchemaMembers = 38,
adSchemaPrimaryKeys = 28,
adSchemaProcedureColumns = 29,
adSchemaProcedureParameters = 26,
adSchemaProcedures = 16,
adSchemaProperties = 37,
adSchemaProviderSpecific = -1,
adSchemaProviderTypes = 22,
adSchemaReferentialConstraints = 9,
adSchemaReferentialContraints = 9,
adSchemaSchemata = 17,
adSchemaSets = 43,
adSchemaSQLLanguages = 18,
adSchemaStatistics = 19,
adSchemaTableConstraints = 10,
adSchemaTablePrivileges = 14,
adSchemaTables = 20,
adSchemaTranslations = 21,
adSchemaTrustees = 39,
adSchemaUsagePrivileges = 15,
adSchemaViewColumnUsage = 24,
adSchemaViews = 23,
adSchemaViewTableUsage = 25
}
const enum SearchDirection {
adSearchBackward = -1,
adSearchForward = 1
}
const enum SearchDirectionEnum {
adSearchBackward = -1,
adSearchForward = 1
}
const enum SeekEnum {
adSeekAfter = 8,
adSeekAfterEQ = 4,
adSeekBefore = 32,
adSeekBeforeEQ = 16,
adSeekFirstEQ = 1,
adSeekLastEQ = 2
}
const enum StreamOpenOptionsEnum {
adOpenStreamAsync = 1,
adOpenStreamFromRecord = 4,
adOpenStreamUnspecified = -1
}
const enum StreamReadEnum {
adReadAll = -1,
adReadLine = -2
}
const enum StreamTypeEnum {
adTypeBinary = 1,
adTypeText = 2
}
const enum StreamWriteEnum {
adWriteChar = 0,
adWriteLine = 1,
stWriteChar = 0,
stWriteLine = 1
}
const enum StringFormatEnum {
adClipString = 2
}
const enum XactAttributeEnum {
adXactAbortRetaining = 262144,
adXactAsyncPhaseOne = 524288,
adXactCommitRetaining = 131072,
adXactSyncPhaseOne = 1048576
}
//Interfaces
interface Command {
ActiveConnection: Connection;
Cancel: () => void;
CommandStream: any /*VT_UNKNOWN*/;
CommandText: string;
CommandTimeout: number;
CommandType: CommandTypeEnum;
CreateParameter: (Name?: string, Type?: DataTypeEnum, Direction?: ParameterDirectionEnum, Size?: number, Value?: any) => Parameter;
Dialect: string;
Execute: (RecordsAffected?: any, Parameters?: any, Options?: number) => Recordset;
Name: string;
NamedParameters: boolean;
Parameters: Parameters;
Prepared: boolean;
Properties: Properties;
State: number;
}
interface Connection {
Attributes: number;
BeginTrans: () => number;
Cancel: () => void;
Close: () => void;
CommandTimeout: number;
CommitTrans: () => void;
ConnectionString: string;
ConnectionTimeout: number;
CursorLocation: CursorLocationEnum;
DefaultDatabase: string;
Errors: Errors;
Execute: (CommandText: string, RecordsAffected: any, Options?: number) => Recordset;
IsolationLevel: IsolationLevelEnum;
Mode: ConnectModeEnum;
Open: (ConnectionString?: string, UserID?: string, Password?: string, Options?: number) => void;
OpenSchema: (Schema: SchemaEnum, Restrictions?: any, SchemaID?: any) => Recordset;
Properties: Properties;
Provider: string;
RollbackTrans: () => void;
State: number;
Version: string;
}
interface Error {
Description: string;
HelpContext: number;
HelpFile: string;
NativeError: number;
Number: number;
Source: string;
SQLState: string;
}
interface Errors {
Clear: () => void;
Count: number;
Item: (Index: any) => Error;
Refresh: () => void;
}
interface Field {
ActualSize: number;
AppendChunk: (Data: any) => void;
Attributes: number;
DataFormat: any /*VT_UNKNOWN*/;
DefinedSize: number;
GetChunk: (Length: number) => any;
Name: string;
NumericScale: number;
OriginalValue: any;
Precision: number;
Properties: Properties;
Status: number;
Type: DataTypeEnum;
UnderlyingValue: any;
Value: any;
}
interface Fields {
_Append: (Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum) => void;
Append: (Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum, FieldValue?: any) => void;
CancelUpdate: () => void;
Count: number;
Delete: (Index: any) => void;
Item: (Index: any) => Field;
Refresh: () => void;
Resync: (ResyncValues?: ResyncEnum) => void;
Update: () => void;
}
interface Parameter {
AppendChunk: (Val: any) => void;
Attributes: number;
Direction: ParameterDirectionEnum;
Name: string;
NumericScale: number;
Precision: number;
Properties: Properties;
Size: number;
Type: DataTypeEnum;
Value: any;
}
interface Parameters {
Append: (Object: any /*VT_DISPATCH*/) => void;
Count: number;
Delete: (Index: any) => void;
Item: (Index: any) => Parameter;
Refresh: () => void;
}
interface Properties {
Count: number;
Item: (Index: any) => Property;
Refresh: () => void;
}
interface Property {
Attributes: number;
Name: string;
Type: DataTypeEnum;
Value: any;
}
interface Record {
ActiveConnection: any;
Cancel: () => void;
Close: () => void;
CopyRecord: (Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: CopyRecordOptionsEnum, Async?: boolean) => string;
DeleteRecord: (Source?: string, Async?: boolean) => void;
Fields: Fields;
GetChildren: () => Recordset;
Mode: ConnectModeEnum;
MoveRecord: (Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: MoveRecordOptionsEnum, Async?: boolean) => string;
Open: (Source: any, ActiveConnection: any, Mode?: ConnectModeEnum, CreateOptions?: RecordCreateOptionsEnum, Options?: RecordOpenOptionsEnum, UserName?: string, Password?: string) => void;
ParentURL: string;
Properties: Properties;
RecordType: RecordTypeEnum;
Source: any;
State: ObjectStateEnum;
}
interface Recordset {
_xClone: () => Recordset;
_xResync: (AffectRecords?: AffectEnum) => void;
_xSave: (FileName?: string, PersistFormat?: PersistFormatEnum) => void;
AbsolutePage: PositionEnum;
AbsolutePosition: PositionEnum;
ActiveCommand: any /*VT_DISPATCH*/;
ActiveConnection: any /*VT_DISPATCH*/;
AddNew: (FieldList?: any, Values?: any) => void;
BOF: boolean;
Bookmark: any;
CacheSize: number;
Cancel: () => void;
CancelBatch: (AffectRecords?: AffectEnum) => void;
CancelUpdate: () => void;
Clone: (LockType?: LockTypeEnum) => Recordset;
Close: () => void;
Collect: (Index: any) => any; //Also has setter with parameters
CompareBookmarks: (Bookmark1: any, Bookmark2: any) => CompareEnum;
CursorLocation: CursorLocationEnum;
CursorType: CursorTypeEnum;
DataMember: string;
DataSource: any /*VT_UNKNOWN*/;
Delete: (AffectRecords?: AffectEnum) => void;
EditMode: EditModeEnum;
EOF: boolean;
Fields: Fields;
Filter: any;
Find: (Criteria: string, SkipRecords?: number, SearchDirection?: SearchDirectionEnum, Start?: any) => void;
GetRows: (Rows?: number, Start?: any, Fields?: any) => any;
GetString: (StringFormat?: StringFormatEnum, NumRows?: number, ColumnDelimeter?: string, RowDelimeter?: string, NullExpr?: string) => string;
Index: string;
LockType: LockTypeEnum;
MarshalOptions: MarshalOptionsEnum;
MaxRecords: number;
Move: (NumRecords: number, Start?: any) => void;
MoveFirst: () => void;
MoveLast: () => void;
MoveNext: () => void;
MovePrevious: () => void;
NextRecordset: (RecordsAffected?: any) => Recordset;
Open: (Source: any, ActiveConnection: any, CursorType?: CursorTypeEnum, LockType?: LockTypeEnum, Options?: number) => void;
PageCount: number;
PageSize: number;
Properties: Properties;
RecordCount: number;
Requery: (Options?: number) => void;
Resync: (AffectRecords?: AffectEnum, ResyncValues?: ResyncEnum) => void;
Save: (Destination: any, PersistFormat?: PersistFormatEnum) => void;
Seek: (KeyValues: any, SeekOption?: SeekEnum) => void;
Sort: string;
Source: any /*VT_DISPATCH*/;
State: number;
Status: number;
StayInSync: boolean;
Supports: (CursorOptions: CursorOptionEnum) => boolean;
Update: (Fields?: any, Values?: any) => void;
UpdateBatch: (AffectRecords?: AffectEnum) => void;
}
interface Stream {
Cancel: () => void;
Charset: string;
Close: () => void;
CopyTo: (DestStream: Stream, CharNumber?: number) => void;
EOS: boolean;
Flush: () => void;
LineSeparator: LineSeparatorEnum;
LoadFromFile: (FileName: string) => void;
Mode: ConnectModeEnum;
Open: (Source: any, Mode?: ConnectModeEnum, Options?: StreamOpenOptionsEnum, UserName?: string, Password?: string) => void;
Position: number;
Read: (NumBytes?: number) => any;
ReadText: (NumChars?: number) => string;
SaveToFile: (FileName: string, Options?: SaveOptionsEnum) => void;
SetEOS: () => void;
Size: number;
SkipLine: () => void;
State: ObjectStateEnum;
Type: StreamTypeEnum;
Write: (Buffer: any) => void;
WriteText: (Data: string, Options?: StreamWriteEnum) => void;
}
}
interface ActiveXObject {
new (progID: 'ADODB.Connection'): ADODB.Connection;
new (progID: 'ADODB.Record'): ADODB.Record;
new (progID: 'ADODB.Stream'): ADODB.Stream;
new (progID: 'ADODB.Command'): ADODB.Command;
new (progID: 'ADODB.Recordset'): ADODB.Recordset;
new (progID: 'ADODB.Parameter'): ADODB.Parameter;
}
-24
View File
@@ -1,24 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-data-objects-tests.ts"
]
}
+320
View File
@@ -0,0 +1,320 @@
/// <reference types="activex-msforms" />
/// <reference types="activex-scripting" />
// some helpers
const toSafeArray = <T>(...items: T[]): SafeArray<T> => {
const dict = new ActiveXObject('Scripting.Dictionary');
items.forEach((x, index) => dict.Add(index, x));
return dict.Items() as SafeArray<T>;
};
const inCollection = <T = any>(collection: { Item(index: any): T }, index: string | number): T | undefined => {
let item: T | undefined;
try {
item = collection.Item(index);
} catch (error) { }
return item;
};
const app = new ActiveXObject('Excel.Application');
// create a workbook -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/create-a-workbook
const newBook = app.Workbooks.Add();
newBook.Title = 'All Sales';
newBook.Subject = 'Sales';
newBook.SaveAs('allsales.xls');
// create or replace a worksheet -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/create-or-replace-a-worksheet
const newOrExistingWorksheet = () => {
const mySheetName = 'Sheet4';
let mySheet = inCollection(newBook.Worksheets, mySheetName) as Excel.Worksheet | undefined;
if (!mySheet) {
WScript.Echo(`The sheet named "${mySheetName} doesn't exist, but will be created.`);
mySheet = app.Worksheets.Add() as Excel.Worksheet;
mySheet.Name = mySheetName;
}
};
const replaceWorksheet = () => {
const mySheetName = 'Sheet4';
app.DisplayAlerts = false;
let mySheet = inCollection<Excel.Worksheet | Excel.Chart | Excel.DialogSheet>(app.Worksheets, mySheetName);
if (mySheet) { mySheet.Delete(); }
app.DisplayAlerts = true;
mySheet = app.Worksheets.Add() as Excel.Worksheet;
mySheet.Name = mySheetName;
WScript.Echo(`The sheet named "${mySheetName} has been replaced.`);
};
// referencing multiple sheets -- https://msdn.microsoft.com/VBA/Excel-VBA/articles/sheets-object-excel
const moveMultipleSheets = () => {
app.Worksheets.Item(toSafeArray<string | number>(1, 'Sheet2')).Move(4);
};
// sort worksheets alphanumerically by name -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/sort-worksheets-alphanumerically-by-name
const sortSheetsTabName = () => {
app.ScreenUpdating = false;
const sheets = app.ActiveWorkbook.Sheets;
const sheetCount = sheets.Count;
for (let i = 0; i < sheetCount; i += 1) {
const sheetI = sheets.Item(i);
for (let j = i; j < sheetCount; j += 1) {
const sheetJ = sheets.Item(j);
if (sheetJ.Name < sheetI.Name) { sheetJ.Move(sheetI); }
}
}
app.ScreenUpdating = true;
};
// fill a value down into blank cells in a column -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/fill-a-value-down-into-blank-cells-in-a-column
const fillCellsFromAbove = () => {
app.ScreenUpdating = false;
const columnA = app.Columns.Item(1);
try {
columnA.SpecialCells(Excel.XlCellType.xlCellTypeBlanks).Formula = '=R[-1]C';
columnA.Value = columnA.Value;
} catch (error) { }
app.ScreenUpdating = true;
};
// hide and unhide columns -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/hide-and-unhide-columns
const setColumnVisibility = (visible: boolean) => {
const book = app.Workbooks.Item(1);
const sheet = inCollection<Excel.Worksheet | Excel.Chart | Excel.DialogSheet>(book.Worksheets, 'Sheet1');
if (!sheet) { return; }
// search the four columns for any constants
const checkWithin = (sheet as Excel.Worksheet).Range('A1:D1').SpecialCells(Excel.XlCellType.xlCellTypeConstants);
let find = checkWithin.Find('X');
if (!find) { return; }
const address = find.Address();
// hide the column, and then find the next X
do {
find.EntireColumn.Hidden = visible;
find = checkWithin.FindNext(find);
} while (find && find.Address() !== address);
};
// highlighting the active cell, row, or column -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/highlight-the-active-cell-row-or-column
(() => {
const wks = app.ActiveSheet as Excel.Worksheet;
// highlight active cell
ActiveXObject.on(wks, 'SelectionChange', ['Target'], function(this: Excel.Worksheet, prm) {
app.ScreenUpdating = false;
// clear the color of all the cells
this.Cells.Interior.ColorIndex = 0;
// highlight the actie cell
prm.Target.Interior.ColorIndex = 8;
app.ScreenUpdating = true;
});
// highlight entire row and column that contain active cell
ActiveXObject.on(wks, 'SelectionChange', ['Target'], function(this: Excel.Worksheet, prm) {
if (prm.Target.Cells.Count > 1) { return; }
app.ScreenUpdating = false;
// clear the color of all the cells in the row and column of the active cell
this.Cells.Interior.ColorIndex = 0;
prm.Target.EntireRow.Interior.ColorIndex = 8;
prm.Target.EntireColumn.Interior.ColorIndex = 8;
app.ScreenUpdating = true;
});
})();
// referencing cells -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/reference-cells-and-ranges
(() => {
const wks = app.ActiveSheet as Excel.Worksheet;
// all the cells on a worksheet
wks.Cells.ClearContents();
// using A1 notation
wks.Range('A1').Font.Bold = true;
wks.Range('A1:D5').Font.Bold = true;
wks.Range('C5:D9,G9:H16').Font.Bold = true;
wks.Range('A:A').Font.Bold = true;
wks.Range('1:1').Font.Bold = true;
wks.Range('A:C').Font.Bold = true;
wks.Range('1:5').Font.Bold = true;
wks.Range('1:1,3:3,8:8').Font.Bold = true;
wks.Range('A:A,C:C,F:F').Font.Bold = true;
// using index numbers
wks.Cells.Item(6, 1).Value2 = 10;
// Value is also a property with parameters
ActiveXObject.set(wks.Cells.Item(6, 1), 'Value', 10);
// iterating through cells using index numbers
for (let counter = 1; counter < 20; counter += 1) {
ActiveXObject.set(wks.Cells.Item(counter, 1), 'Value', 10);
}
// relative to other cells
wks.Cells.Item(1, 1).Font.Underline = Excel.XlUnderlineStyle.xlUnderlineStyleDouble;
// using a Range object
const rng = wks.Cells.Item('A1:D5');
rng.Formula = '=RAND()';
rng.Font.Bold = true;
// refer to multiple ranges, using Union
const r1 = wks.Range('A1:A10');
const r2 = wks.Range('B4:B20');
const union = app.Union(r1, r2);
union.Font.Bold = true;
// refer to multiple ranges using Areas
WScript.Echo(union.Areas.Count);
})();
// looping through a range of cells -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/looping-through-a-range-of-cells
(() => {
const wks = app.ActiveSheet as Excel.Worksheet;
// using for
for (let x = 1; x < 20; x++) {
const currentCell = wks.Cells.Item(x, 1);
if (Math.abs(currentCell.Value()) < 0.01) {
// because Value is typed as a method on the Excel.Range class, we have to treat it as a setter with parameters
ActiveXObject.set(currentCell, 'Value', 0);
}
}
// using Enumerator
let enumerator = new Enumerator(wks.Cells.Item('A1:D10'));
enumerator.moveFirst();
while (!enumerator.atEnd()) {
const currentCell = enumerator.item();
if (Math.abs(currentCell.Value) < 0.01) {
currentCell.Value = 0;
}
enumerator.moveNext();
}
// using CurrentRegion
enumerator = new Enumerator(app.ActiveCell.CurrentRegion);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
const cell = enumerator.item();
if (Math.abs(cell.Value) < 0.01) {
cell.Value = 0;
}
enumerator.moveNext();
}
})();
// using selection -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/selecting-and-activating-cells
(() => {
const wks = app.ActiveWorkbook.Worksheets.Item(1) as Excel.Worksheet;
// make a worksheet the active worksheet; otherwise code which uses the selection will fail
wks.Select();
// select a cell
wks.Range("A1").Select();
app.ActiveCell.Font.Bold = true;
// activate a cell; only a single cell can be active at any given time
wks.Range("B1").Activate();
// working with 3-D ranges -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/working-with-3-d-ranges
app.Sheets.Item(toSafeArray("Sheet2", "Sheet3", "Sheet4")).Select();
app.Range("A1:H1").Select();
(app.Selection as Excel.Range).Borders.Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlDouble;
// alternatively, use FillAcrossSheets to fill formatting and data across sheets
const book = app.ActiveWorkbook;
const wks2 = book.Sheets.Item("Sheet2") as Excel.Worksheet;
const rng = wks2.Range("A1:H1");
rng.Borders.Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlDouble;
book.Sheets.FillAcrossSheets(rng);
})();
// prevent duplicate entry -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/prevent-duplicate-entries-in-a-range
(() => {
const book = app.Workbooks.Item(1);
ActiveXObject.on(book, 'SheetChange', ['Sh', 'Target'], function(this, prm) {
const EvalRange = this.ActiveSheet.Range("A1:B20");
// If the cell where the value was entered is not in the defined range, if the value pasted is larger than a single cell, or if no value was entered in the cell, then exit the macro
if (
(app.Intersect(prm.Target, EvalRange) == null) ||
(prm.Target.Cells.Count > 1)
// VBA has a function called IsEmpty; not sure what the equivalent is in Javascript
) { return; }
// If the value entered already exists in the defined range on the current worksheet, undo and exit
if (app.WorksheetFunction.CountIf(EvalRange, prm.Target.Value()) > 1) {
app.EnableEvents = false;
app.Undo();
app.EnableEvents = true;
return;
}
const enumerator = new Enumerator(book.Worksheets);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
const wks = enumerator.item() as Excel.Worksheet;
if (wks.Name === prm.Target.Name) { continue; }
// If the value entered already exists in the defined range on the current worksheet, undo the entry.
if (app.WorksheetFunction.CountIf(wks.Range('A1:B20'), prm.Target.Value()) === 0) { continue; }
app.EnableEvents = false;
app.Undo();
app.EnableEvents = true;
}
});
})();
// add a unique list of values to a combobox -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/add-a-unique-list-of-values-to-a-combo-box
(() => {
(() => {
// using the AdvancedFilter property
const book = app.ThisWorkbook;
const sheet = book.Worksheets.Item("Sheet1") as Excel.Worksheet;
const dataRange = sheet.Range('A1', sheet.Range("A100").End(Excel.XlDirection.xlUp));
dataRange.AdvancedFilter(Excel.XlFilterAction.xlFilterCopy, undefined, sheet.Range('L1'), true);
const data = sheet.Range("L2", sheet.Range('L100').End(Excel.XlDirection.xlUp)).Value() as SafeArray;
sheet.Range('L1', sheet.Range('L100').End(Excel.XlDirection.xlUp)).ClearContents();
const combobox = sheet.OLEObjects('ComboBox1').Object as MSForms.ComboBox2;
combobox.Clear();
ActiveXObject.set(combobox, 'List', [], data);
combobox.ListIndex = -1;
})();
(() => {
// using a Dictionary
const sheet = app.ThisWorkbook.Sheets.Item('Sheet2') as Excel.Worksheet;
const data = sheet.Range('A2', sheet.Range('A100').End(Excel.XlDirection.xlUp)).Value2 as SafeArray;
const arr = new VBArray(data).toArray();
const dict = new ActiveXObject('Scripting.Dictionary');
arr.forEach(x => ActiveXObject.set(dict, 'Item', [x], true));
const combobox = sheet.OLEObjects('ComboBox1').Object as MSForms.ComboBox2;
combobox.Clear();
const enumerator = new Enumerator(dict.Items());
enumerator.moveFirst();
while (!enumerator.atEnd()) {
combobox.AddItem(enumerator.item());
}
})();
})();
// 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);
}
})();
+9550
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-excel-tests.ts"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
}
}
@@ -0,0 +1,5 @@
let obj0 = new ActiveXObject('InfoPath.Application');
let obj1 = new ActiveXObject('InfoPath.ExternalApplication');
let obj2 = new ActiveXObject('InfoPath.Editor');
+1198
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-infopath-tests.ts"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
}
}
@@ -0,0 +1,171 @@
(() => {
// https://wiki.openoffice.org/wiki/Documentation/DevGuide/ProUNO/Bridge/Automation_Bridge
// This is a JScript example
// The service manager is always the starting point
// If there is no office running then an office is started up
const serviceManager = new ActiveXObject('com.sun.star.ServiceManager');
// Create the CoreReflection service that is later used to create structs
const coreReflection = serviceManager.createInstance("com.sun.star.reflection.CoreReflection");
// Create the Desktop
const desktop = serviceManager.defaultContext.getByName('/singleton/com.sun.star.frame.theDesktop');
// Open a new empty writer document
const args: any[] = [];
const document = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, args); // as com.sun.star.text.TextDocument;
// Create a text object
const text = document.Text;
// Create a cursor object
const cursor = (text.createTextCursor() as any) as com.sun.star.text.TextCursor;
// Inserting some Text
text.insertString(cursor, "The first line in the newly created text document.\n", false);
// Inserting a second line
text.insertString(cursor, "Now we're in the second line", false);
// Create instance of a text table with 4 columns and 4 rows
const table = document.createInstance("com.sun.star.text.TextTable");
table.initialize(4, 4);
// Insert the table
text.insertTextContent(cursor, table, false);
// Get first row
const rows = table.Rows;
const row = rows.getByIndex(0) as com.sun.star.table.TableRow;
// Set the table background color
((table as any) as com.sun.star.beans.XPropertySet).setPropertyValue("BackTransparent", false);
((table as any) as com.sun.star.beans.XPropertySet).setPropertyValue("BackColor", 13421823);
// Set a different background color for the first row
row.setPropertyValue("BackTransparent", false);
row.setPropertyValue("BackColor", 6710932);
// Fill the first table row
insertIntoCell("A1", "FirstColumn", table); // insertIntoCell is a helper function, see below
insertIntoCell("B1", "SecondColumn", table);
insertIntoCell("C1", "ThirdColumn", table);
insertIntoCell("D1", "SUM", table);
table.getCellByName("A2").setValue(22.5);
table.getCellByName("B2").setValue(5615.3);
table.getCellByName("C2").setValue(-2315.7);
table.getCellByName("D2").setFormula("sum ");
table.getCellByName("A3").setValue(21.5);
table.getCellByName("B3").setValue(615.3);
table.getCellByName("C3").setValue(- 315.7);
table.getCellByName("D3").setFormula("sum ");
table.getCellByName("A4").setValue(121.5);
table.getCellByName("B4").setValue(-615.3);
table.getCellByName("C4").setValue(415.7);
table.getCellByName("D4").setFormula("sum ");
// Change the CharColor and add a Shadow
cursor.setPropertyValue("CharColor", 255);
cursor.setPropertyValue("CharShadowed", true);
// Create a paragraph break
// The second argument is a com::sun::star::text::ControlCharacter::PARAGRAPH_BREAK constant
text.insertControlCharacter(cursor, 0, false);
// Inserting colored Text.
text.insertString(cursor, " This is a colored Text - blue with shadow\n", false);
// Create a paragraph break ( ControlCharacter::PARAGRAPH_BREAK).
text.insertControlCharacter(cursor, 0, false);
// Create a TextFrame.
const textFrame = document.createInstance("com.sun.star.text.TextFrame");
// Create a Size struct.
const size = createStruct("com.sun.star.awt.Size"); // helper function, see below
size.Width = 15000;
size.Height = 400;
textFrame.setSize(size);
// TextContentAnchorType.AS_CHARACTER = 1
textFrame.setPropertyValue("AnchorType", com.sun.star.text.TextContentAnchorType.AS_CHARACTER);
// insert the frame
text.insertTextContent(cursor, textFrame, false);
// Get the text object of the frame
const objFrameText = textFrame.Text;
// Create a cursor object
const objFrameTextCursor = objFrameText.createTextCursor();
// Inserting some Text
objFrameText.insertString(objFrameTextCursor, "The first line in the newly created text frame.", false);
objFrameText.insertString(objFrameTextCursor, "\nWith this second line the height of the frame raises.", false);
// Create a paragraph break
// The second argument is a com::sun::star::text::ControlCharacter::PARAGRAPH_BREAK constant
objFrameText.insertControlCharacter(cursor, 0, false);
// Change the CharColor and add a Shadow
cursor.setPropertyValue("CharColor", 65536);
cursor.setPropertyValue("CharShadowed", false);
// Insert another string
text.insertString(cursor, " That's all for now !!", false);
function insertIntoCell(strCellName: string, strText: string, objTable: com.sun.star.text.TextTable) {
const objCellText = objTable.getCellByName(strCellName) as com.sun.star.table.Cell;
const objCellCursor = (objCellText.createTextCursor() as any) as com.sun.star.text.TextCursor;
objCellCursor.setPropertyValue("CharColor", 16777215);
objCellText.insertString(objCellCursor, strText, false);
}
function createStruct<K extends keyof LibreOffice.StructNameMap>(strTypeName: K): LibreOffice.StructNameMap[K] {
const classSize = coreReflection.forName(strTypeName);
const aStruct: [LibreOffice.StructNameMap[K]] = [] as any;
classSize.createObject(aStruct);
return aStruct[0];
}
})();
(() => {
// This shows some specific features of the Automation bridge
const serviceManager = new ActiveXObject('com.sun.star.ServiceManager');
// singleton access
const desktop = serviceManager.defaultContext.getByName('/singleton/com.sun.star.frame.theDesktop');
// defaultContext property implements XNameAccess
// sequence is returned as a safearray
const elementNames = new VBArray(serviceManager.defaultContext.getElementNames()).toArray().join('\n');
WScript.Echo(elementNames);
// get/set methods exposed as properties -- getText => Text, getViewData/setViewData => ViewData
const document = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, []);
const viewData = document.ViewData;
WScript.Echo(viewData.Count);
const text = document.Text;
WScript.Echo(text);
})();
(() => {
// Forces use of tuple type for out parameters
// Instantiating via reflection
const serviceManager = new ActiveXObject('com.sun.star.ServiceManager');
const coreReflection = serviceManager.defaultContext.getByName('/singleton/com.sun.star.reflection.theCoreReflection');
const classInfo = coreReflection.forName('com.sun.star.accessibility.Accessible');
const accessible: [com.sun.star.accessibility.XAccessible] = [] as any;
classInfo.createObject(accessible);
accessible[0].acquire();
// Get a struct via Bridge_GetStruct
const size = serviceManager.Bridge_GetStruct('com.sun.star.awt.Size');
size.Height = 110;
size.Width = 120;
})();
+105881
View File
File diff suppressed because it is too large Load Diff
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-libreoffice-tests.ts"
]
}
+10
View File
@@ -0,0 +1,10 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false],
"ban-types": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-unnecessary-qualifier": false
}
}
@@ -0,0 +1 @@
let obj0 = new ActiveXObject('Forms.Image');
+3757
View File
File diff suppressed because it is too large Load Diff

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