Merge remote-tracking branch 'upstream/master' into relay-modern

This commit is contained in:
voxmatt
2017-10-01 10:15:46 -07:00
892 changed files with 266599 additions and 16853 deletions
+11 -2
View File
@@ -88,6 +88,7 @@ First, [fork](https://guides.github.com/activities/forking/) this repository, in
* `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>`.
- Or if there are more people, it can be multiline
```typescript
@@ -145,7 +146,7 @@ For a good example package, see [base64-js](https://github.com/DefinitelyTyped/D
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`:
* `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`.
@@ -284,6 +285,14 @@ 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.
@@ -297,7 +306,7 @@ When `dts-gen` is used to scaffold a scoped package, the `paths` property has to
"@foo/bar": ["foo__bar"]
}
}
```
```
#### The file history in GitHub looks incomplete.
+12
View File
@@ -318,6 +318,12 @@
"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": "Linq.JS",
"typingsPackageName": "linq",
@@ -732,6 +738,12 @@
"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",
@@ -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,15 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": 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" }
+5 -7
View File
@@ -44,16 +44,14 @@ 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;
}
}
@@ -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": "*"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": 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]
}
}
@@ -19,6 +19,7 @@ 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();
@@ -26,3 +27,31 @@ let rs = cmd.Execute();
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);
})();
+205 -126
View File
@@ -1,7 +1,8 @@
// Type definitions for Microsoft ActiveX Data Objects 6.1
// Type definitions for Microsoft ActiveX Data Objects 6.0 Library - ADODB 6.1
// Project: https://msdn.microsoft.com/en-us/library/jj249010.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
declare namespace ADODB {
const enum ADCPROP_ASYNCTHREADPRIORITY_ENUM {
@@ -9,19 +10,19 @@ declare namespace ADODB {
adPriorityBelowNormal = 2,
adPriorityHighest = 5,
adPriorityLowest = 1,
adPriorityNormal = 3
adPriorityNormal = 3,
}
const enum ADCPROP_AUTORECALC_ENUM {
adRecalcAlways = 1,
adRecalcUpFront = 0
adRecalcUpFront = 0,
}
const enum ADCPROP_UPDATECRITERIA_ENUM {
adCriteriaAllCols = 1,
adCriteriaKey = 0,
adCriteriaTimeStamp = 3,
adCriteriaUpdCols = 2
adCriteriaUpdCols = 2,
}
const enum ADCPROP_UPDATERESYNC_ENUM {
@@ -30,20 +31,20 @@ declare namespace ADODB {
adResyncConflicts = 2,
adResyncInserts = 8,
adResyncNone = 0,
adResyncUpdates = 4
adResyncUpdates = 4,
}
const enum AffectEnum {
adAffectAll = 3,
adAffectAllChapters = 4,
adAffectCurrent = 1,
adAffectGroup = 2
adAffectGroup = 2,
}
const enum BookmarkEnum {
adBookmarkCurrent = 0,
adBookmarkFirst = 1,
adBookmarkLast = 2
adBookmarkLast = 2,
}
const enum CommandTypeEnum {
@@ -53,7 +54,7 @@ declare namespace ADODB {
adCmdTableDirect = 512,
adCmdText = 1,
adCmdUnknown = 8,
adCmdUnspecified = -1
adCmdUnspecified = -1,
}
const enum CompareEnum {
@@ -61,7 +62,7 @@ declare namespace ADODB {
adCompareGreaterThan = 2,
adCompareLessThan = 0,
adCompareNotComparable = 4,
adCompareNotEqual = 3
adCompareNotEqual = 3,
}
const enum ConnectModeEnum {
@@ -73,33 +74,33 @@ declare namespace ADODB {
adModeShareDenyWrite = 8,
adModeShareExclusive = 12,
adModeUnknown = 0,
adModeWrite = 2
adModeWrite = 2,
}
const enum ConnectOptionEnum {
adAsyncConnect = 16,
adConnectUnspecified = -1
adConnectUnspecified = -1,
}
const enum ConnectPromptEnum {
adPromptAlways = 1,
adPromptComplete = 2,
adPromptCompleteRequired = 3,
adPromptNever = 4
adPromptNever = 4,
}
const enum CopyRecordOptionsEnum {
adCopyAllowEmulation = 4,
adCopyNonRecursive = 2,
adCopyOverWrite = 1,
adCopyUnspecified = -1
adCopyUnspecified = -1,
}
const enum CursorLocationEnum {
adUseClient = 3,
adUseClientBatch = 3,
adUseNone = 1,
adUseServer = 2
adUseServer = 2,
}
const enum CursorOptionEnum {
@@ -115,7 +116,7 @@ declare namespace ADODB {
adResync = 131072,
adSeek = 4194304,
adUpdate = 16809984,
adUpdateBatch = 65536
adUpdateBatch = 65536,
}
const enum CursorTypeEnum {
@@ -123,7 +124,7 @@ declare namespace ADODB {
adOpenForwardOnly = 0,
adOpenKeyset = 1,
adOpenStatic = 3,
adOpenUnspecified = -1
adOpenUnspecified = -1,
}
const enum DataTypeEnum {
@@ -166,14 +167,14 @@ declare namespace ADODB {
adVariant = 12,
adVarNumeric = 139,
adVarWChar = 202,
adWChar = 130
adWChar = 130,
}
const enum EditModeEnum {
adEditAdd = 2,
adEditDelete = 4,
adEditInProgress = 1,
adEditNone = 0
adEditNone = 0,
}
const enum ErrorValueEnum {
@@ -240,7 +241,7 @@ declare namespace ADODB {
adErrVolumeNotFound = 3733,
adErrWriteFile = 3004,
adwrnSecurityDialog = 3717,
adwrnSecurityDialogHeader = 3718
adwrnSecurityDialogHeader = 3718,
}
const enum EventReasonEnum {
@@ -258,7 +259,7 @@ declare namespace ADODB {
adRsnUndoAddNew = 5,
adRsnUndoDelete = 6,
adRsnUndoUpdate = 4,
adRsnUpdate = 3
adRsnUpdate = 3,
}
const enum EventStatusEnum {
@@ -266,7 +267,7 @@ declare namespace ADODB {
adStatusCantDeny = 3,
adStatusErrorsOccurred = 2,
adStatusOK = 1,
adStatusUnwantedEvent = 5
adStatusUnwantedEvent = 5,
}
const enum ExecuteOptionEnum {
@@ -276,7 +277,7 @@ declare namespace ADODB {
adExecuteNoRecords = 128,
adExecuteRecord = 2048,
adExecuteStream = 1024,
adOptionUnspecified = -1
adOptionUnspecified = -1,
}
const enum FieldAttributeEnum {
@@ -296,12 +297,12 @@ declare namespace ADODB {
adFldRowVersion = 512,
adFldUnknownUpdatable = 8,
adFldUnspecified = -1,
adFldUpdatable = 4
adFldUpdatable = 4,
}
const enum FieldEnum {
adDefaultStream = -1,
adRecordURL = -2
adRecordURL = -2,
}
const enum FieldStatusEnum {
@@ -334,7 +335,7 @@ declare namespace ADODB {
adFieldSignMismatch = 5,
adFieldTruncated = 4,
adFieldUnavailable = 8,
adFieldVolumeNotFound = 21
adFieldVolumeNotFound = 21,
}
const enum FilterGroupEnum {
@@ -343,11 +344,11 @@ declare namespace ADODB {
adFilterFetchedRecords = 3,
adFilterNone = 0,
adFilterPendingRecords = 1,
adFilterPredicate = 4
adFilterPredicate = 4,
}
const enum GetRowsOptionEnum {
adGetRowsRest = -1
adGetRowsRest = -1,
}
const enum IsolationLevelEnum {
@@ -359,13 +360,13 @@ declare namespace ADODB {
adXactReadUncommitted = 256,
adXactRepeatableRead = 65536,
adXactSerializable = 1048576,
adXactUnspecified = -1
adXactUnspecified = -1,
}
const enum LineSeparatorEnum {
adCR = 13,
adCRLF = -1,
adLF = 10
adLF = 10,
}
const enum LockTypeEnum {
@@ -373,19 +374,19 @@ declare namespace ADODB {
adLockOptimistic = 3,
adLockPessimistic = 2,
adLockReadOnly = 1,
adLockUnspecified = -1
adLockUnspecified = -1,
}
const enum MarshalOptionsEnum {
adMarshalAll = 0,
adMarshalModifiedOnly = 1
adMarshalModifiedOnly = 1,
}
const enum MoveRecordOptionsEnum {
adMoveAllowEmulation = 4,
adMoveDontUpdateLinks = 2,
adMoveOverWrite = 1,
adMoveUnspecified = -1
adMoveUnspecified = -1,
}
const enum ObjectStateEnum {
@@ -393,13 +394,13 @@ declare namespace ADODB {
adStateConnecting = 2,
adStateExecuting = 4,
adStateFetching = 8,
adStateOpen = 1
adStateOpen = 1,
}
const enum ParameterAttributesEnum {
adParamLong = 128,
adParamNullable = 64,
adParamSigned = 16
adParamSigned = 16,
}
const enum ParameterDirectionEnum {
@@ -407,24 +408,24 @@ declare namespace ADODB {
adParamInputOutput = 3,
adParamOutput = 2,
adParamReturnValue = 4,
adParamUnknown = 0
adParamUnknown = 0,
}
const enum PersistFormatEnum {
adPersistADTG = 0,
adPersistXML = 1
adPersistXML = 1,
}
const enum PositionEnum {
adPosBOF = -2,
adPosEOF = -3,
adPosUnknown = -1
adPosUnknown = -1,
}
const enum PositionEnum_Param {
adPosBOF = -2,
adPosEOF = -3,
adPosUnknown = -1
adPosUnknown = -1,
}
const enum PropertyAttributesEnum {
@@ -432,7 +433,7 @@ declare namespace ADODB {
adPropOptional = 2,
adPropRead = 512,
adPropRequired = 1,
adPropWrite = 1024
adPropWrite = 1024,
}
const enum RecordCreateOptionsEnum {
@@ -441,7 +442,7 @@ declare namespace ADODB {
adCreateOverwrite = 67108864,
adCreateStructDoc = -2147483648,
adFailIfNotExists = -1,
adOpenIfExists = 33554432
adOpenIfExists = 33554432,
}
const enum RecordOpenOptionsEnum {
@@ -451,7 +452,7 @@ declare namespace ADODB {
adOpenExecuteCommand = 65536,
adOpenOutput = 8388608,
adOpenRecordUnspecified = -1,
adOpenSource = 8388608
adOpenSource = 8388608,
}
const enum RecordStatusEnum {
@@ -472,23 +473,23 @@ declare namespace ADODB {
adRecPendingChanges = 128,
adRecPermissionDenied = 65536,
adRecSchemaViolation = 131072,
adRecUnmodified = 8
adRecUnmodified = 8,
}
const enum RecordTypeEnum {
adCollectionRecord = 1,
adSimpleRecord = 0,
adStructDoc = 2
adStructDoc = 2,
}
const enum ResyncEnum {
adResyncAllValues = 2,
adResyncUnderlyingValues = 1
adResyncUnderlyingValues = 1,
}
const enum SaveOptionsEnum {
adSaveCreateNotExist = 1,
adSaveCreateOverWrite = 2
adSaveCreateOverWrite = 2,
}
const enum SchemaEnum {
@@ -537,17 +538,17 @@ declare namespace ADODB {
adSchemaUsagePrivileges = 15,
adSchemaViewColumnUsage = 24,
adSchemaViews = 23,
adSchemaViewTableUsage = 25
adSchemaViewTableUsage = 25,
}
const enum SearchDirection {
adSearchBackward = -1,
adSearchForward = 1
adSearchForward = 1,
}
const enum SearchDirectionEnum {
adSearchBackward = -1,
adSearchForward = 1
adSearchForward = 1,
}
const enum SeekEnum {
@@ -556,44 +557,46 @@ declare namespace ADODB {
adSeekBefore = 32,
adSeekBeforeEQ = 16,
adSeekFirstEQ = 1,
adSeekLastEQ = 2
adSeekLastEQ = 2,
}
const enum StreamOpenOptionsEnum {
adOpenStreamAsync = 1,
adOpenStreamFromRecord = 4,
adOpenStreamUnspecified = -1
adOpenStreamUnspecified = -1,
}
const enum StreamReadEnum {
adReadAll = -1,
adReadLine = -2
adReadLine = -2,
}
const enum StreamTypeEnum {
adTypeBinary = 1,
adTypeText = 2
adTypeText = 2,
}
const enum StreamWriteEnum {
adWriteChar = 0,
adWriteLine = 1,
stWriteChar = 0,
stWriteLine = 1
stWriteLine = 1,
}
const enum StringFormatEnum {
adClipString = 2
adClipString = 2,
}
const enum XactAttributeEnum {
adXactAbortRetaining = 262144,
adXactAsyncPhaseOne = 524288,
adXactCommitRetaining = 131072,
adXactSyncPhaseOne = 1048576
adXactSyncPhaseOne = 1048576,
}
interface Command {
class Command {
private 'ADODB.Command_typekey': Command;
private constructor();
ActiveConnection: Connection;
Cancel(): void;
CommandStream: any;
@@ -611,7 +614,7 @@ declare namespace ADODB {
Dialect: string;
/** @param number [Options=-1] */
Execute(RecordsAffected?: any, Parameters?: any, Options?: number): Recordset;
Execute(RecordsAffected?: number, Parameters?: SafeArray, Options?: number): Recordset;
Name: string;
NamedParameters: boolean;
readonly Parameters: Parameters;
@@ -620,7 +623,9 @@ declare namespace ADODB {
readonly State: number;
}
interface Connection {
class Connection {
private 'ADODB.Connection_typekey': Connection;
private constructor();
Attributes: number;
BeginTrans(): number;
Cancel(): void;
@@ -653,7 +658,9 @@ declare namespace ADODB {
readonly Version: string;
}
interface Error {
class Error {
private 'ADODB.Error_typekey': Error;
private constructor();
readonly Description: string;
readonly HelpContext: number;
readonly HelpFile: string;
@@ -663,14 +670,18 @@ declare namespace ADODB {
readonly SQLState: string;
}
interface Errors {
class Errors {
private 'ADODB.Errors_typekey': Errors;
private constructor();
Clear(): void;
readonly Count: number;
Item(Index: any): Error;
Refresh(): void;
}
interface Field {
class Field {
private 'ADODB.Field_typekey': Field;
private constructor();
readonly ActualSize: number;
AppendChunk(Data: any): void;
Attributes: number;
@@ -688,7 +699,10 @@ declare namespace ADODB {
Value: any;
}
interface Fields {
class Fields {
private 'ADODB.Fields_typekey': Fields;
private constructor();
/**
* @param number [DefinedSize=0]
* @param ADODB.FieldAttributeEnum [Attrib=-1]
@@ -711,7 +725,9 @@ declare namespace ADODB {
Update(): void;
}
interface Parameter {
class Parameter {
private 'ADODB.Parameter_typekey': Parameter;
private constructor();
AppendChunk(Val: any): void;
Attributes: number;
Direction: ParameterDirectionEnum;
@@ -724,7 +740,9 @@ declare namespace ADODB {
Value: any;
}
interface Parameters {
class Parameters {
private 'ADODB.Parameters_typekey': Parameters;
private constructor();
Append(Object: any): void;
readonly Count: number;
Delete(Index: any): void;
@@ -732,20 +750,26 @@ declare namespace ADODB {
Refresh(): void;
}
interface Properties {
class Properties {
private 'ADODB.Properties_typekey': Properties;
private constructor();
readonly Count: number;
Item(Index: any): Property;
Refresh(): void;
}
interface Property {
class Property {
private 'ADODB.Property_typekey': Property;
private constructor();
Attributes: number;
readonly Name: string;
readonly Type: DataTypeEnum;
Value: any;
}
interface Record {
class Record {
private 'ADODB.Record_typekey': Record;
private constructor();
ActiveConnection: any;
Cancel(): void;
Close(): void;
@@ -794,7 +818,9 @@ declare namespace ADODB {
readonly State: ObjectStateEnum;
}
interface Recordset {
class Recordset {
private 'ADODB.Recordset_typekey': Recordset;
private constructor();
_xClone(): Recordset;
/** @param ADODB.AffectEnum [AffectRecords=3] */
@@ -895,13 +921,15 @@ declare namespace ADODB {
readonly Status: number;
StayInSync: boolean;
Supports(CursorOptions: CursorOptionEnum): boolean;
Update(Fields?: any, Values?: any): void;
Update(Fields?: string | SafeArray<string | number>, Values?: any): void;
/** @param ADODB.AffectEnum [AffectRecords=3] */
UpdateBatch(AffectRecords?: AffectEnum): void;
}
interface Stream {
class Stream {
private 'ADODB.Stream_typekey': Stream;
private constructor();
Cancel(): void;
Charset: string;
Close(): void;
@@ -941,67 +969,118 @@ declare namespace ADODB {
/** @param ADODB.StreamWriteEnum [Options=0] */
WriteText(Data: string, Options?: StreamWriteEnum): void;
}
namespace EventHelperTypes {
type Connection_ExecuteComplete_ArgNames = ['RecordsAffected', 'pError', 'adStatus', 'pCommand', 'pRecordset', 'pConnection'];
type Connection_WillConnect_ArgNames = ['ConnectionString', 'UserID', 'Password', 'Options', 'adStatus', 'pConnection'];
type Connection_WillExecute_ArgNames = ['Source', 'CursorType', 'LockType', 'Options', 'adStatus', 'pCommand', 'pRecordset', 'pConnection'];
interface Connection_ExecuteComplete_Parameter {
adStatus: EventStatusEnum;
readonly pCommand: Command;
readonly pConnection: Connection;
readonly pError: Error;
readonly pRecordset: Recordset;
readonly RecordsAffected: number;
}
interface Connection_WillConnect_Parameter {
adStatus: EventStatusEnum;
ConnectionString: string;
Options: number;
Password: string;
readonly pConnection: Connection;
UserID: string;
}
interface Connection_WillExecute_Parameter {
adStatus: EventStatusEnum;
CursorType: CursorTypeEnum;
LockType: LockTypeEnum;
Options: number;
readonly pCommand: Command;
readonly pConnection: Connection;
readonly pRecordset: Recordset;
Source: string;
}
}
}
interface ActiveXObject {
on(obj: ADODB.Connection, event: 'BeginTransComplete', argNames: ['TransactionLevel', 'pError', 'adStatus', 'pConnection'], handler: (
this: ADODB.Connection, parameter: {
TransactionLevel: number, pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pConnection: ADODB.Connection}) => void): void;
on(obj: ADODB.Connection, event: 'Disconnect', argNames: ['adStatus', 'pConnection'], handler: (
this: ADODB.Connection, parameter: {
adStatus: ADODB.EventStatusEnum, pConnection: ADODB.Connection}) => void): void;
on(obj: ADODB.Connection, event: 'ExecuteComplete', argNames: ['RecordsAffected', 'pError', 'adStatus', 'pCommand', 'pRecordset', 'pConnection'], handler: (
this: ADODB.Connection, parameter: {
RecordsAffected: number, pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pCommand: ADODB.Command, pRecordset: ADODB.Recordset, pConnection: ADODB.Connection}) => void): void;
on(obj: ADODB.Connection, event: 'InfoMessage' | 'CommitTransComplete' | 'RollbackTransComplete' | 'ConnectComplete', argNames: ['pError', 'adStatus', 'pConnection'], handler: (
this: ADODB.Connection, parameter: {
pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pConnection: ADODB.Connection}) => void): void;
on(obj: ADODB.Connection, event: 'WillConnect', argNames: ['ConnectionString', 'UserID', 'Password', 'Options', 'adStatus', 'pConnection'], handler: (
this: ADODB.Connection, parameter: {
ConnectionString: string, UserID: string, Password: string, Options: number, adStatus: ADODB.EventStatusEnum, pConnection: ADODB.Connection}) => void): void;
on(obj: ADODB.Connection, event: 'WillExecute', argNames: ['Source', 'CursorType', 'LockType', 'Options', 'adStatus', 'pCommand', 'pRecordset', 'pConnection'], handler: (
this: ADODB.Connection, parameter: {
Source: string, CursorType: ADODB.CursorTypeEnum, LockType: ADODB.LockTypeEnum, Options: number, adStatus: ADODB.EventStatusEnum, pCommand: ADODB.Command,
pRecordset: ADODB.Recordset, pConnection: ADODB.Connection}) => void): void;
on(obj: ADODB.Recordset, event: 'EndOfRecordset', argNames: ['fMoreData', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
fMoreData: boolean, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'FetchComplete', argNames: ['pError', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'FetchProgress', argNames: ['Progress', 'MaxProgress', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
Progress: number, MaxProgress: number, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'FieldChangeComplete', argNames: ['cFields', 'Fields', 'pError', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
cFields: number, Fields: any, pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'RecordChangeComplete', argNames: ['adReason', 'cRecords', 'pError', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
adReason: ADODB.EventReasonEnum, cRecords: number, pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'RecordsetChangeComplete' | 'MoveComplete', argNames: ['adReason', 'pError', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
adReason: ADODB.EventReasonEnum, pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'WillChangeField', argNames: ['cFields', 'Fields', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
cFields: number, Fields: any, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'WillChangeRecord', argNames: ['adReason', 'cRecords', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
adReason: ADODB.EventReasonEnum, cRecords: number, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'WillChangeRecordset' | 'WillMove', argNames: ['adReason', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
adReason: ADODB.EventReasonEnum, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void;
on(
obj: ADODB.Connection, event: 'BeginTransComplete', argNames: ['TransactionLevel', 'pError', 'adStatus', 'pConnection'], handler: (
this: ADODB.Connection, parameter: {
readonly TransactionLevel: number, readonly pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, readonly pConnection: ADODB.Connection}) => void): void;
on(
obj: ADODB.Connection, event: 'CommitTransComplete' | 'ConnectComplete' | 'InfoMessage' | 'RollbackTransComplete', argNames: ['pError', 'adStatus', 'pConnection'],
handler: (this: ADODB.Connection, parameter: {readonly pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, readonly pConnection: ADODB.Connection}) => void): void;
on(
obj: ADODB.Connection, event: 'Disconnect', argNames: ['adStatus', 'pConnection'], handler: (
this: ADODB.Connection, parameter: {adStatus: ADODB.EventStatusEnum, readonly pConnection: ADODB.Connection}) => void): void;
on(
obj: ADODB.Connection, event: 'ExecuteComplete', argNames: ADODB.EventHelperTypes.Connection_ExecuteComplete_ArgNames, handler: (
this: ADODB.Connection, parameter: ADODB.EventHelperTypes.Connection_ExecuteComplete_Parameter) => void): void;
on(
obj: ADODB.Connection, event: 'WillConnect', argNames: ADODB.EventHelperTypes.Connection_WillConnect_ArgNames, handler: (
this: ADODB.Connection, parameter: ADODB.EventHelperTypes.Connection_WillConnect_Parameter) => void): void;
on(
obj: ADODB.Connection, event: 'WillExecute', argNames: ADODB.EventHelperTypes.Connection_WillExecute_ArgNames, handler: (
this: ADODB.Connection, parameter: ADODB.EventHelperTypes.Connection_WillExecute_Parameter) => void): void;
on(
obj: ADODB.Recordset, event: 'EndOfRecordset', argNames: ['fMoreData', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {fMoreData: boolean, adStatus: ADODB.EventStatusEnum, readonly pRecordset: ADODB.Recordset}) => void): void;
on(
obj: ADODB.Recordset, event: 'FetchComplete', argNames: ['pError', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {readonly pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, readonly pRecordset: ADODB.Recordset}) => void): void;
on(
obj: ADODB.Recordset, event: 'FetchProgress', argNames: ['Progress', 'MaxProgress', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {readonly Progress: number, readonly MaxProgress: number, adStatus: ADODB.EventStatusEnum, readonly pRecordset: ADODB.Recordset}) => void): void;
on(
obj: ADODB.Recordset, event: 'FieldChangeComplete', argNames: ['cFields', 'Fields', 'pError', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
readonly cFields: number, readonly Fields: any, readonly pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, readonly pRecordset: ADODB.Recordset}) => void): void;
on(
obj: ADODB.Recordset, event: 'MoveComplete' | 'RecordsetChangeComplete', argNames: ['adReason', 'pError', 'adStatus', 'pRecordset'],
handler: (
this: ADODB.Recordset, parameter: {
readonly adReason: ADODB.EventReasonEnum, readonly pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, readonly pRecordset: ADODB.Recordset}) => void): void;
on(
obj: ADODB.Recordset, event: 'RecordChangeComplete', argNames: ['adReason', 'cRecords', 'pError', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
readonly adReason: ADODB.EventReasonEnum, readonly cRecords: number, readonly pError: ADODB.Error,
adStatus: ADODB.EventStatusEnum, readonly pRecordset: ADODB.Recordset}) => void): void;
on(
obj: ADODB.Recordset, event: 'WillChangeField', argNames: ['cFields', 'Fields', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {readonly cFields: number, readonly Fields: any, adStatus: ADODB.EventStatusEnum, readonly pRecordset: ADODB.Recordset}) => void): void;
on(
obj: ADODB.Recordset, event: 'WillChangeRecord', argNames: ['adReason', 'cRecords', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
readonly adReason: ADODB.EventReasonEnum, readonly cRecords: number, adStatus: ADODB.EventStatusEnum, readonly pRecordset: ADODB.Recordset}) => void): void;
on(
obj: ADODB.Recordset, event: 'WillChangeRecordset' | 'WillMove', argNames: ['adReason', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {readonly adReason: ADODB.EventReasonEnum, adStatus: ADODB.EventStatusEnum, readonly pRecordset: ADODB.Recordset}) => void): void;
set(obj: ADODB.Recordset, propertyName: 'Collect', parameterTypes: [any], newValue: any): void;
new(progid: 'ADODB.Command'): ADODB.Command;
new(progid: 'ADODB.Connection'): ADODB.Connection;
new(progid: 'ADODB.Parameter'): ADODB.Parameter;
new(progid: 'ADODB.Record'): ADODB.Record;
new(progid: 'ADODB.Recordset'): ADODB.Recordset;
new(progid: 'ADODB.Stream'): ADODB.Stream;
new<K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
}
interface ActiveXObjectNameMap {
'ADODB.Command': ADODB.Command;
'ADODB.Connection': ADODB.Connection;
'ADODB.Parameter': ADODB.Parameter;
'ADODB.Record': ADODB.Record;
'ADODB.Recordset': ADODB.Recordset;
'ADODB.Stream': ADODB.Stream;
}
interface EnumeratorConstructor {
new(col: ADODB.Errors): ADODB.Error;
new(col: ADODB.Fields): ADODB.Field;
new(col: ADODB.Parameters): ADODB.Parameter;
new(col: ADODB.Properties): ADODB.Property;
new(col: ADODB.Errors): Enumerator<ADODB.Error>;
new(col: ADODB.Fields): Enumerator<ADODB.Field>;
new(col: ADODB.Parameters): Enumerator<ADODB.Parameter>;
new(col: ADODB.Properties): Enumerator<ADODB.Property>;
}
interface SafeArray<T = any> {
_brand: SafeArray<T>;
}
+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": "*"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": 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]
}
}
+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": "*"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": 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": "*"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": 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;
})();
+105882
View File
File diff suppressed because it is too large Load Diff
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-libreoffice-tests.ts"
]
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false],
"ban-types": 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
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-msforms-tests.ts"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
}
}
@@ -0,0 +1,6 @@
let htmlfile = new ActiveXObject('htmlfile');
let htmldoc = htmlfile.createDocumentFromUrl('https://msdn.microsoft.com/en-us/library/aa741317(v=vs.85).aspx', 'null');
let length = htmldoc.all.length;
for (let i = 0; i < length; i++) {
WScript.Echo((htmldoc.all.item(i) as MSHTML.IHTMLElement).tagName);
}
+36500
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-mshtml-tests.ts"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
}
}
@@ -0,0 +1,329 @@
// https://msdn.microsoft.com/en-us/library/ms764708(v=vs.85).aspx
(() => {
const dom = new ActiveXObject('Msxml2.DOMDocument.6.0');
dom.async = false;
dom.resolveExternals = false;
dom.loadXML('<a>A</a>');
WScript.Echo(`dom: ${dom.xml}`);
})();
// https://msdn.microsoft.com/en-us/library/ms766390(v=vs.85).aspx
(() => {
const doc = new ActiveXObject('Msxml2.DOMDocument.6.0');
doc.load('test.xml');
WScript.Echo(`doc: ${doc.xml}`);
})();
const MakeDOM = () => {
try {
const dom = new ActiveXObject('Msxml2.DOMDocument.6.0');
dom.async = false;
dom.validateOnParse = false;
dom.resolveExternals = false;
return dom;
} catch (e) {
WScript.Echo(e.description);
}
};
const LoadDOM = (file: string) => {
try {
const dom = MakeDOM()!;
dom.load(file);
return dom;
} catch (e) {
WScript.Echo(e.description);
}
};
// https://msdn.microsoft.com/en-us/library/ms759105(v=vs.85).aspx
(() => {
const doc = new ActiveXObject('Msxml2.DOMDocument.6.0');
doc.async = false;
doc.resolveExternals = false;
doc.validateOnParse = false;
const xml = `
<?xml version='1.0'?>
<doc title='test'>
<page num='1'>
<para title='Saved at last'>
This XML data is finally saved.
</para>
</page>
<page num='2'>
<para>
This page is intentionally left blank.
</para>
</page>
</doc>
`;
doc.loadXML(xml);
doc.save('saved.xml');
})();
// https://msdn.microsoft.com/en-us/library/ms764656(v=vs.85).aspx
(() => {
const doc = LoadDOM('test.xml')!;
const xsl = (LoadDOM('test.xsl')! as any) as MSXML2.IXMLDOMNode;
const str = doc.transformNode(xsl);
WScript.Echo('\ndoc.transformNode:\n' + str);
const out = MakeDOM()!;
doc.transformNodeToObject(xsl, out);
WScript.Echo('\ndoc.transformNodeToObject:\n' + out.xml);
})();
// https://msdn.microsoft.com/en-us/library/ms763685(v=vs.85).aspx
(() => {
const dom = MakeDOM()!;
// Create a processing instruction targeted for xml.
let node = dom.createProcessingInstruction("xml", "version='1.0'") as any;
dom.appendChild(node);
// Create a processing instruction targeted for xml-stylesheet.
node = dom.createProcessingInstruction("xml-stylesheet", "type='text/xml' href='test.xsl'");
dom.appendChild(node);
// Create a comment for the document.
node = dom.createComment("sample xml file created using XML DOM object.");
dom.appendChild(node);
// Create the root element.
const root = dom.createElement("root") as any;
// Create a "created" attribute for the root element and assign the "using dom" character data as the attribute value.
const attr = dom.createAttribute("created") as any;
attr.value = "using dom";
root.setAttributeNode(attr);
// Add the root element to the DOM instance.
dom.appendChild(root);
// Insert a newline + tab.
root.appendChild(dom.createTextNode("\n\t"));
// Create more nodes and add them to the root element just created.
// Add a text node as <node1>.
node = dom.createElement("node1");
node.text = "some character data";
root.appendChild(node);
// Add a newline + tab.
root.appendChild(dom.createTextNode("\n\t"));
// Add a CDATA section as <node2>.
node = dom.createElement("node2");
const cd = dom.createCDATASection("some mark-up text");
node.appendChild(cd);
root.appendChild(node);
// Create an element (<node3>) to hold three empty subelements.
node = dom.createElement("node3");
// Create a document fragment to be added to <node3>.
const frag = dom.createDocumentFragment();
// Add a newline + tab + tab as a text node and an empty subnode.
frag.appendChild(dom.createTextNode("\n\t\t") as any);
frag.appendChild(dom.createElement("subNode1") as any);
// Add a newline + tab + tab as a text node and an empty subnode.
frag.appendChild(dom.createTextNode("\n\t\t") as any);
frag.appendChild(dom.createElement("subNode2") as any);
// Add a newline + tab + tab as a text node and an empty subnode.
frag.appendChild(dom.createTextNode("\n\t\t") as any);
frag.appendChild(dom.createElement("subNode3") as any);
// Add a newline + tab.
frag.appendChild(dom.createTextNode("\n\t") as any);
node.appendChild(frag);
root.appendChild(node);
// Add a newline.
root.appendChild(dom.createTextNode("\n"));
// Save the XML document to a file.
dom.save("dynamDom.xml");
})();
// https://msdn.microsoft.com/en-us/library/ms757050(v=vs.85).aspx
(() => {
const dom = LoadDOM("stocks.xml")!;
try {
// Query a single node.
const oNode = dom.selectSingleNode("//stock[1]/*");
if (oNode != null) {
WScript.Echo(`Result from selectSingleNode:\n\tNode, <${oNode.nodeName}>:\n\t${oNode.xml}\n\n`);
}
// Query a node-set.
WScript.Echo("Results from selectNodes:\n");
const oNodes = dom.selectNodes("//stock[1]/*");
for (let i = 0; i < oNodes.length; i++) {
const nextNode = oNodes.nextNode;
if (nextNode == null) { continue; }
WScript.Echo(`Node (${i}), <${oNode.nodeName} + ">:\n\t${oNode.xml}`);
}
} catch (e) {
WScript.Echo(e.description);
}
})();
// https://msdn.microsoft.com/en-us/library/ms757064(v=vs.85).aspx
(() => {
const xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0");
xhr.open("GET", "http://localhost/sxh/contact.asp?SearchID=John Doe", false);
xhr.send();
const doc = xhr.responseXML;
WScript.Echo(doc.xml);
})();
const xmlValidation = (fn: (x: MSXML2.DOMDocument60) => void) => {
// Create and initialize the DOMDocument object
const x = new ActiveXObject("Msxml2.DOMDocument.6.0");
x.async = false;
x.validateOnParse = true;
x.resolveExternals = true;
fn(x);
let msg: string;
if (x.parseError.errorCode !== 0) {
msg = `
Validation failed on ${x.url}
=====================
Reason: ${x.parseError.reason}
Source: ${x.parseError.srcText}
Line: ${x.parseError.line}`;
} else {
msg = `
Validation succeeded for ${x.url}
======================
${x.xml}
`;
}
return msg;
};
// https://msdn.microsoft.com/en-us/library/ms766449(v=vs.85).aspx
(() => {
const validateFile = (filename: string) => xmlValidation(x => x.load(filename));
let sOutput = validateFile("nn-valid.xml");
sOutput = sOutput + validateFile("nn-notValid.xml");
WScript.Echo(sOutput);
})();
// https://msdn.microsoft.com/en-us/library/ms767542(v=vs.85).aspx
(() => {
const validateFile = (filename: string) => xmlValidation(x => {
// Configure DOM properties for namespace selection.
x.setProperty("SelectionLanguage", "XPath");
const ns = "xmlns:x='urn:book'";
x.setProperty("SelectionNamespaces", ns);
// Load and validate the specified file into the DOM.
x.load(filename);
});
let sOutput = validateFile("sl-valid.xml");
sOutput = sOutput + validateFile("sl-notValid.xml");
WScript.Echo(sOutput);
})();
// https://msdn.microsoft.com/en-us/library/ms766439(v=vs.85).aspx
(() => {
const validateFile = (filename: string) => xmlValidation(xd => {
// Create a schema cache and add books.xsd to it.
const xs = new ActiveXObject('Msxml2.XMLSchemaCache');
xs.add("urn:books", "sc.xsd");
// Assign the schema cache to the DOMDocument's schemas collection.
xd.schemas = xs;
xd.load(filename);
});
let sOutput = validateFile("sc-valid.xml");
sOutput = sOutput + validateFile("sc-notValid.xml");
WScript.Echo(sOutput);
})();
// https://msdn.microsoft.com/en-us/library/ms767636(v=vs.85).aspx
(() => {
const validateFile = (filename: string) => xmlValidation(x => {
x.setProperty("UseInlineSchema", true);
x.load(filename);
});
let sOutput = validateFile("valid.xml");
sOutput = sOutput + validateFile("notValid.xml");
WScript.Echo(sOutput);
})();
// https://msdn.microsoft.com/en-us/library/ms757833(v=vs.85).aspx
(() => {
// Load an XML document into a DOM instance.
const oXMLDoc = LoadDOM("books.xml")!;
// Load the schema for the xml document.
const oXSDDoc = LoadDOM("books.xsd")!;
// Create a schema cache instance.
const oSCache = new ActiveXObject("Msxml2.XMLSchemaCache.6.0");
// Add the just-loaded schema definition to the schema collection
oSCache.add("urn:books", oXSDDoc);
// Assign the schema to the XML document's schema collection
oXMLDoc.schemas = oSCache;
// Validate the entire DOM.
WScript.Echo("Validating DOM...");
let oError = oXMLDoc.validate();
let msg: string;
if (oError.errorCode !== 0) {
msg = `\tXMLDoc is not valid because
${oError.reason}`;
} else {
msg = `\tXMLDoc is validated:
${oXMLDoc.xml}`;
}
WScript.Echo(msg);
// Validate all //books nodes, node by node.
WScript.Echo("Validating all book nodes, '//book', one by one ...");
let oNodes = oXMLDoc.selectNodes("//book");
for (let i = 0; i < oNodes.length; i++) {
const oNode = oNodes.item(i);
oError = oXMLDoc.validateNode(oNode);
if (oError.errorCode !== 0) {
msg = `\t<${oNode.nodeName}>(${i}) is not valid because
${oError.reason}`;
} else {
msg = `\t<${oNode.nodeName}>(${i}) is a valid node`;
}
WScript.Echo(msg);
}
// validate all children of all book node, //book/*, node by node
oNodes = oXMLDoc.selectNodes("//book/*");
WScript.Echo('Validating all children of all book nodes, "//book/*, one by one...');
for (let i = 0; i < oNodes.length; i++) {
const oNode = oNodes.item(i);
oError = oXMLDoc.validateNode(oNode);
if (oError.errorCode !== 0) {
msg = `\t<${oNode.nodeName}>(${i}) is not valud because
${oError.reason}`;
} else {
msg = `\t<${oNode.nodeName}>(${i}) is a valid node`;
}
WScript.Echo(msg);
}
})();
+2798
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-msxml2-tests.ts"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
}
}
@@ -0,0 +1,19 @@
/// <reference types="activex-word" />
let app = new ActiveXObject('Word.Application');
let dlg = app.FileDialog(Office.MsoFileDialogType.msoFileDialogFolderPicker);
dlg.AllowMultiSelect = true;
dlg.Title = 'Select one or more folders';
dlg.Execute();
let enumerator = new Enumerator(dlg.SelectedItems);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
WScript.Echo(enumerator.item);
}
let enumerator2 = new Enumerator(app.COMAddIns);
enumerator2.moveFirst();
while (!enumerator2.atEnd()) {
const item = enumerator2.item();
WScript.Echo(`COM Addin: ${item.Description} -- ${item.ProgId}`);
}
+6865
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-office-tests.ts"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
}
}
@@ -0,0 +1,59 @@
/// <reference types="activex-word" />
let obj0 = new ActiveXObject('DOCSITE.DocSiteControl');
let obj1 = new ActiveXObject('RECIP.RecipCtl');
let obj2 = new ActiveXObject('Outlook.Application');
let obj3 = new ActiveXObject('Outlook.OlkBusinessCardControl');
let obj4 = new ActiveXObject('Outlook.OlkCategoryStrip');
let obj5 = new ActiveXObject('Outlook.OlkCheckBox');
let obj6 = new ActiveXObject('Outlook.OlkComboBox');
let obj7 = new ActiveXObject('Outlook.OlkCommandButton');
let obj8 = new ActiveXObject('Outlook.OlkContactPhoto');
let obj9 = new ActiveXObject('Outlook.OlkDateControl');
let obj10 = new ActiveXObject('Outlook.OlkFrameHeader');
let obj11 = new ActiveXObject('Outlook.OlkInfoBar');
let obj12 = new ActiveXObject('Outlook.OlkLabel');
let obj13 = new ActiveXObject('Outlook.OlkListBox');
let obj14 = new ActiveXObject('Outlook.OlkOptionButton');
let obj15 = new ActiveXObject('Outlook.OlkPageControl');
let obj16 = new ActiveXObject('Outlook.OlkSenderPhoto');
let obj17 = new ActiveXObject('Outlook.OlkTextBox');
let obj18 = new ActiveXObject('Outlook.OlkTimeControl');
let obj19 = new ActiveXObject('Outlook.OlkTimeZone');
// ---------
let app = new ActiveXObject('Outlook.Application');
// https://msdn.microsoft.com/VBA/office-shared-vba/articles/getting-started-with-vba-in-office
(() => {
// create a message in Outlook
const message = app.CreateItem(Outlook.OlItemType.olMailItem);
message.Subject = 'Hello, world!';
message.Display();
// copying a contact from Outlook to Word
const currentItem = app.ActiveInspector().CurrentItem as Outlook.ContactItem;
const wdApp = new ActiveXObject('Word.Application');
const doc = wdApp.Documents.Add();
doc.Range().InsertAfter(`${currentItem.FullName} from ${currentItem.CompanyName}`);
})();
+5892
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-outlook-tests.ts"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
}
}
@@ -0,0 +1,21 @@
const collectionToArray = <T>(col: any) => {
const results: T[] = [];
const enumerator = new Enumerator<T>(col);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
results.push(enumerator.item());
}
return results;
};
// -- https://msdn.microsoft.com/VBA/office-shared-vba/articles/getting-started-with-vba-in-office
const app = new ActiveXObject('PowerPoint.Application');
(() => {
// delete empty textboxes in PowerPoint
collectionToArray<PowerPoint.Slide>(app.ActivePresentation.Slides).forEach(slide => {
collectionToArray<PowerPoint.Shape>(slide.Shapes).filter(shape =>
shape.Type === Office.MsoShapeType.msoTextBox
&& shape.TextFrame.TextRange.Text.trim() === ''
).forEach(shape => shape.Delete());
});
})();
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-powerpoint-tests.ts"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
}
}
@@ -0,0 +1,3 @@
let obj0 = new ActiveXObject('StdFont');
let obj1 = new ActiveXObject('StdPicture');
+92
View File
@@ -0,0 +1,92 @@
// Type definitions for OLE Automation - stdole 2.0
// Project: https://msdn.microsoft.com/en-us/library/hh272953.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
declare namespace stdole {
type IPictureDisp = StdPicture;
type OLE_COLOR = number;
type OLE_XPOS_CONTAINER = number;
type OLE_YPOS_CONTAINER = number;
const enum LoadPictureConstants {
Color = 4,
Default = 0,
Monochrome = 1,
VgaColor = 2,
}
const enum OLE_TRISTATE {
Checked = 1,
Gray = 2,
Unchecked = 0,
}
interface DISPPARAMS {
readonly cArgs: number;
readonly cNamedArgs: number;
readonly rgdispidNamedArgs: number;
readonly rgvarg: any;
}
interface EXCEPINFO {
readonly bstrDescription: string;
readonly bstrHelpFile: string;
readonly bstrSource: string;
readonly dwHelpContext: number;
readonly pfnDeferredFillIn: undefined;
readonly pvReserved: undefined;
readonly scode: any;
readonly wCode: number;
readonly wReserved: number;
}
interface GUID {
readonly Data1: number;
readonly Data2: number;
readonly Data3: number;
readonly Data4: SafeArray<number>;
}
class StdFont {
private 'stdole.StdFont_typekey': StdFont;
private constructor();
readonly Bold: boolean;
readonly Charset: number;
readonly Italic: boolean;
readonly Name: string;
readonly Size: number;
readonly Strikethrough: boolean;
readonly Underline: boolean;
readonly Weight: number;
}
class StdPicture {
private 'stdole.StdPicture_typekey': StdPicture;
private constructor();
readonly Handle: number;
readonly Height: number;
readonly hPal: number;
Render(hdc: number, x: number, y: number, cx: number, cy: number, xSrc: number, ySrc: number, cxSrc: number, cySrc: number, prcWBounds: undefined): void;
readonly Type: number;
readonly Width: number;
}
}
interface ActiveXObject {
on(obj: stdole.StdFont, event: 'FontChanged', argNames: ['PropertyName'], handler: (this: stdole.StdFont, parameter: {readonly PropertyName: string}) => void): void;
new<K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
}
interface ActiveXObjectNameMap {
StdFont: stdole.StdFont;
StdPicture: stdole.StdPicture;
}
interface SafeArray<T = any> {
_brand: SafeArray<T>;
}
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-stdole-tests.ts"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
}
}
@@ -0,0 +1,22 @@
/// <reference types="activex-word" />
const collectionToArray = <T>(col: any) => {
const results: T[] = [];
const enumerator = new Enumerator<T>(col);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
results.push(enumerator.item());
}
return results;
};
const app = new ActiveXObject('Word.Application');
const projects = collectionToArray<VBIDE.VBProject>(app.VBE.VBProjects);
projects.forEach(project => {
WScript.Echo(`Name: ${project.Name}`);
collectionToArray<VBIDE.Reference>(project.References)
.forEach(reference => {
WScript.Echo(` ${reference.Name} ${reference.Major}.${reference.Minor} -- ${reference.FullPath}`);
});
});
+423
View File
@@ -0,0 +1,423 @@
// Type definitions for Microsoft Visual Basic for Applications Extensibility 5.3 - VBIDE 14.0
// Project: https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/collections-visual-basic-add-in-model
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="activex-office" />
declare namespace VBIDE {
const enum vbext_CodePaneview {
vbext_cv_FullModuleView = 1,
vbext_cv_ProcedureView = 0,
}
const enum vbext_ComponentType {
vbext_ct_ActiveXDesigner = 11,
vbext_ct_ClassModule = 2,
vbext_ct_Document = 100,
vbext_ct_MSForm = 3,
vbext_ct_StdModule = 1,
}
const enum vbext_ProcKind {
vbext_pk_Get = 3,
vbext_pk_Let = 1,
vbext_pk_Proc = 0,
vbext_pk_Set = 2,
}
const enum vbext_ProjectProtection {
vbext_pp_locked = 1,
vbext_pp_none = 0,
}
const enum vbext_ProjectType {
vbext_pt_HostProject = 100,
vbext_pt_StandAlone = 101,
}
const enum vbext_RefKind {
vbext_rk_Project = 1,
vbext_rk_TypeLib = 0,
}
const enum vbext_VBAMode {
vbext_vm_Break = 1,
vbext_vm_Design = 2,
vbext_vm_Run = 0,
}
const enum vbext_WindowState {
vbext_ws_Maximize = 2,
vbext_ws_Minimize = 1,
vbext_ws_Normal = 0,
}
const enum vbext_WindowType {
vbext_wt_Browser = 2,
vbext_wt_CodeWindow = 0,
vbext_wt_Designer = 1,
vbext_wt_Find = 8,
vbext_wt_FindReplace = 9,
vbext_wt_Immediate = 5,
vbext_wt_LinkedWindowFrame = 11,
vbext_wt_Locals = 4,
vbext_wt_MainWindow = 12,
vbext_wt_ProjectWindow = 6,
vbext_wt_PropertyWindow = 7,
vbext_wt_Toolbox = 10,
vbext_wt_ToolWindow = 15,
vbext_wt_Watch = 3,
}
const enum vbextFileTypes {
vbextFileTypeBinary = 10,
vbextFileTypeClass = 2,
vbextFileTypeDesigners = 12,
vbextFileTypeDocObject = 9,
vbextFileTypeExe = 4,
vbextFileTypeForm = 0,
vbextFileTypeFrx = 5,
vbextFileTypeGroupProject = 11,
vbextFileTypeModule = 1,
vbextFileTypeProject = 3,
vbextFileTypePropertyPage = 8,
vbextFileTypeRes = 6,
vbextFileTypeUserControl = 7,
}
class AddIn {
private 'VBIDE.AddIn_typekey': AddIn;
private constructor();
readonly Collection: Addins;
Connect: boolean;
Description: string;
readonly Guid: string;
Object: any;
readonly ProgId: string;
readonly VBE: VBE;
}
class Addins {
private 'VBIDE.Addins_typekey': Addins;
private constructor();
readonly Count: number;
Item(index: any): AddIn;
readonly Parent: any;
Update(): void;
readonly VBE: VBE;
}
class Application {
private 'VBIDE.Application_typekey': Application;
private constructor();
readonly Version: string;
}
class CodeModule {
private 'VBIDE.CodeModule_typekey': CodeModule;
private constructor();
AddFromFile(FileName: string): void;
AddFromString(String: string): void;
readonly CodePane: CodePane;
readonly CountOfDeclarationLines: number;
readonly CountOfLines: number;
CreateEventProc(EventName: string, ObjectName: string): number;
/** @param number [Count=1] */
DeleteLines(StartLine: number, Count?: number): void;
/**
* @param boolean [WholeWord=false]
* @param boolean [MatchCase=false]
* @param boolean [PatternSearch=false]
*/
Find(Target: string, StartLine: number, StartColumn: number, EndLine: number, EndColumn: number, WholeWord?: boolean, MatchCase?: boolean, PatternSearch?: boolean): boolean;
InsertLines(Line: number, String: string): void;
Lines(StartLine: number, Count: number): string;
Name: string;
readonly Parent: VBComponent;
ProcBodyLine(ProcName: string, ProcKind: vbext_ProcKind): number;
ProcCountLines(ProcName: string, ProcKind: vbext_ProcKind): number;
ProcOfLine(Line: number, ProcKind: vbext_ProcKind): string;
ProcStartLine(ProcName: string, ProcKind: vbext_ProcKind): number;
ReplaceLine(Line: number, String: string): void;
readonly VBE: VBE;
}
class CodePane {
private 'VBIDE.CodePane_typekey': CodePane;
private constructor();
readonly CodeModule: CodeModule;
readonly CodePaneView: vbext_CodePaneview;
readonly Collection: CodePanes;
readonly CountOfVisibleLines: number;
GetSelection(StartLine: number, StartColumn: number, EndLine: number, EndColumn: number): void;
SetSelection(StartLine: number, StartColumn: number, EndLine: number, EndColumn: number): void;
Show(): void;
TopLine: number;
readonly VBE: VBE;
readonly Window: Window;
}
class CodePanes {
private 'VBIDE.CodePanes_typekey': CodePanes;
private constructor();
readonly Count: number;
Current: CodePane;
Item(index: any): CodePane;
readonly Parent: VBE;
readonly VBE: VBE;
}
class CommandBarEvents {
private 'VBIDE.CommandBarEvents_typekey': CommandBarEvents;
private constructor();
}
class Component {
private 'VBIDE.Component_typekey': Component;
private constructor();
readonly Application: Application;
IsDirty: boolean;
Name: string;
readonly Parent: Components;
}
class Components {
private 'VBIDE.Components_typekey': Components;
private constructor();
Add(ComponentType: vbext_ComponentType): Component;
readonly Application: Application;
readonly Count: number;
Import(FileName: string): Component;
Item(index: any): Component;
readonly Parent: VBProject;
Remove(Component: Component): void;
readonly VBE: VBE;
}
class Events {
private 'VBIDE.Events_typekey': Events;
private constructor();
CommandBarEvents(CommandBarControl: any): CommandBarEvents;
ReferencesEvents(VBProject: VBProject): ReferencesEvents;
}
class LinkedWindows {
private 'VBIDE.LinkedWindows_typekey': LinkedWindows;
private constructor();
Add(Window: Window): void;
readonly Count: number;
Item(index: any): Window;
readonly Parent: Window;
Remove(Window: Window): void;
readonly VBE: VBE;
}
class ProjectTemplate {
private 'VBIDE.ProjectTemplate_typekey': ProjectTemplate;
private constructor();
readonly Application: Application;
readonly Parent: Application;
}
class Properties {
private 'VBIDE.Properties_typekey': Properties;
private constructor();
readonly Application: Application;
readonly Count: number;
Item(index: any): Property;
readonly Parent: any;
readonly VBE: VBE;
}
class Property {
private 'VBIDE.Property_typekey': Property;
private constructor();
readonly Application: Application;
readonly Collection: Properties;
IndexedValue(Index1: any, Index2?: any, Index3?: any, Index4?: any): any;
readonly Name: string;
readonly NumIndices: number;
Object: any;
readonly Parent: Properties;
Value: any;
readonly VBE: VBE;
}
class Reference {
private 'VBIDE.Reference_typekey': Reference;
private constructor();
readonly BuiltIn: boolean;
readonly Collection: References;
readonly Description: string;
readonly FullPath: string;
readonly Guid: string;
readonly IsBroken: boolean;
readonly Major: number;
readonly Minor: number;
readonly Name: string;
readonly Type: vbext_RefKind;
readonly VBE: VBE;
}
class References {
private 'VBIDE.References_typekey': References;
private constructor();
AddFromFile(FileName: string): Reference;
AddFromGuid(Guid: string, Major: number, Minor: number): Reference;
readonly Count: number;
Item(index: any): Reference;
readonly Parent: VBProject;
Remove(Reference: Reference): void;
readonly VBE: VBE;
}
class ReferencesEvents {
private 'VBIDE.ReferencesEvents_typekey': ReferencesEvents;
private constructor();
}
class VBComponent {
private 'VBIDE.VBComponent_typekey': VBComponent;
private constructor();
Activate(): void;
readonly CodeModule: CodeModule;
readonly Collection: VBComponents;
readonly Designer: any;
readonly DesignerID: string;
DesignerWindow(): Window;
Export(FileName: string): void;
readonly HasOpenDesigner: boolean;
Name: string;
readonly Properties: Properties;
readonly Saved: boolean;
readonly Type: vbext_ComponentType;
readonly VBE: VBE;
}
class VBComponents {
private 'VBIDE.VBComponents_typekey': VBComponents;
private constructor();
Add(ComponentType: vbext_ComponentType): VBComponent;
AddCustom(ProgId: string): VBComponent;
/** @param number [index=0] */
AddMTDesigner(index?: number): VBComponent;
readonly Count: number;
Import(FileName: string): VBComponent;
Item(index: any): VBComponent;
readonly Parent: VBProject;
Remove(VBComponent: VBComponent): void;
readonly VBE: VBE;
}
class VBE {
private 'VBIDE.VBE_typekey': VBE;
private constructor();
ActiveCodePane: CodePane;
ActiveVBProject: VBProject;
readonly ActiveWindow: Window;
readonly Addins: Addins;
readonly CodePanes: CodePanes;
readonly CommandBars: Office.CommandBars;
readonly Events: Events;
readonly MainWindow: Window;
readonly SelectedVBComponent: VBComponent;
readonly VBProjects: VBProjects;
readonly Version: string;
readonly Windows: Windows;
}
class VBProject {
private 'VBIDE.VBProject_typekey': VBProject;
private constructor();
readonly Application: Application;
BuildFileName: string;
readonly Collection: VBProjects;
Description: string;
readonly FileName: string;
HelpContextID: number;
HelpFile: string;
MakeCompiledFile(): void;
readonly Mode: vbext_VBAMode;
Name: string;
readonly Parent: Application;
readonly Protection: vbext_ProjectProtection;
readonly References: References;
SaveAs(FileName: string): void;
readonly Saved: boolean;
readonly Type: vbext_ProjectType;
readonly VBComponents: VBComponents;
readonly VBE: VBE;
}
class VBProjects {
private 'VBIDE.VBProjects_typekey': VBProjects;
private constructor();
Add(Type: vbext_ProjectType): VBProject;
readonly Count: number;
Item(index: any): VBProject;
Open(bstrPath: string): VBProject;
readonly Parent: VBE;
Remove(lpc: VBProject): void;
readonly VBE: VBE;
}
class Window {
private 'VBIDE.Window_typekey': Window;
private constructor();
readonly Caption: string;
Close(): void;
readonly Collection: Windows;
Height: number;
readonly HWnd: number;
Left: number;
readonly LinkedWindowFrame: Window;
readonly LinkedWindows: LinkedWindows;
SetFocus(): void;
Top: number;
readonly Type: vbext_WindowType;
readonly VBE: VBE;
Visible: boolean;
Width: number;
WindowState: vbext_WindowState;
}
class Windows {
private 'VBIDE.Windows_typekey': Windows;
private constructor();
readonly Count: number;
CreateToolWindow(AddInInst: AddIn, ProgId: string, Caption: string, GuidPosition: string, DocObj: any): Window;
Item(index: any): Window;
readonly Parent: Application;
readonly VBE: VBE;
}
}
interface ActiveXObject {
on(
obj: VBIDE.CommandBarEvents, event: 'Click', argNames: ['CommandBarControl', 'handled', 'CancelDefault'], handler: (
this: VBIDE.CommandBarEvents, parameter: {readonly CommandBarControl: any, readonly handled: boolean, readonly CancelDefault: boolean}) => void): void;
on(obj: VBIDE.References, event: 'ItemAdded' | 'ItemRemoved', argNames: ['Reference'], handler: (this: VBIDE.References, parameter: {readonly Reference: VBIDE.Reference}) => void): void;
on(
obj: VBIDE.ReferencesEvents, event: 'ItemAdded' | 'ItemRemoved', argNames: ['Reference'], handler: (
this: VBIDE.ReferencesEvents, parameter: {readonly Reference: VBIDE.Reference}) => void): void;
}
interface EnumeratorConstructor {
new(col: VBIDE.Addins): Enumerator<VBIDE.AddIn>;
new(col: VBIDE.CodePanes): Enumerator<VBIDE.CodePane>;
new(col: VBIDE.Components): Enumerator<VBIDE.Component>;
new(col: VBIDE.LinkedWindows | VBIDE.Windows): Enumerator<VBIDE.Window>;
new(col: VBIDE.Properties): Enumerator<VBIDE.Property>;
new(col: VBIDE.References): Enumerator<VBIDE.Reference>;
new(col: VBIDE.VBComponents): Enumerator<VBIDE.VBComponent>;
new(col: VBIDE.VBProjects): Enumerator<VBIDE.VBProject>;
}
interface SafeArray<T = any> {
_brand: SafeArray<T>;
}
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-vbide-tests.ts"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
}
}
+351
View File
@@ -0,0 +1,351 @@
const collectionToArray = <T>(col: any) => {
const results: T[] = [];
const enumerator = new Enumerator<T>(col);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
results.push(enumerator.item());
}
return results;
};
const app = new ActiveXObject('Word.Application');
// https://msdn.microsoft.com/en-us/vba/word-vba/articles/modifying-a-portion-of-a-document
app.Selection.Words.Item(1).Copy();
app.ActiveDocument.Paragraphs.Item(1).Range.Copy();
app.ActiveDocument.Words.Item(1).Case = Word.WdCharacterCase.wdUpperCase;
app.Selection.Sections.Item(1).PageSetup.BottomMargin = app.InchesToPoints(0.5);
app.ActiveDocument.Content.ParagraphFormat.Space2();
const activeDoc = app.ActiveDocument;
(() => {
const rngTenCharacters = activeDoc.Range(0, 10);
const rngThreeWords = activeDoc.Range(activeDoc.Words.Item(1).Start, activeDoc.Words.Item(3).End);
const rngParagraphs = activeDoc.Range(
activeDoc.Paragraphs.Item(2).Range.Start,
activeDoc.Paragraphs.Item(3).Range.End
);
})();
// https://msdn.microsoft.com/en-us/vba/word-vba/articles/working-with-range-objects
(() => {
// using the Range method
let rngDoc = activeDoc.Range(0, 10);
rngDoc.Bold = true;
rngDoc = activeDoc.Range(0, 0);
rngDoc.InsertBefore('Hello');
rngDoc = activeDoc.Range(
activeDoc.Paragraphs.Item(2).Range.Start,
activeDoc.Paragraphs.Item(3).Range.End
);
// using the Range property
const rngParagraphs = activeDoc.Paragraphs.Item(1).Range;
activeDoc.Paragraphs.Item(2).Range.Select();
rngParagraphs.Bold = true;
rngParagraphs.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
rngParagraphs.Font.Name = 'Stencil';
rngParagraphs.Font.Size = 15;
// redefine a Range object
let rngParagraph = app.Selection.Range;
rngParagraph.SetRange(rngParagraph.Start, rngParagraph.End + 10);
rngParagraph = activeDoc.Paragraphs.Item(2).Range;
rngParagraph.SetRange(rngParagraph.Start, activeDoc.Paragraphs.Item(3).Range.End);
rngParagraph.Select();
app.Selection.Font.Italic = true;
})();
// https://msdn.microsoft.com/en-us/vba/word-vba/articles/displaying-built-in-word-dialog-boxes
(() => {
// showing a built-in dialog box
app.Dialogs.Item(Word.WdWordDialog.wdDialogFileOpen).Show();
app.Dialogs.Item(Word.WdWordDialog.wdDialogFilePrint).Show();
let dlg = app.Dialogs.Item(Word.WdWordDialog.wdDialogFormatBordersAndShading);
dlg.DefaultTab = Word.WdWordDialogTab.wdDialogFormatBordersAndShadingTabBorders;
dlg.Show();
dlg = app.Dialogs.Item(Word.WdWordDialog.wdDialogToolsOptionsUserInfo);
dlg.Display();
if ((dlg as any).Name !== '') { dlg.Execute(); }
// returning and changing dialog box settings
const dlgParagraph = app.Dialogs.Item(Word.WdWordDialog.wdDialogFormatParagraph);
WScript.Echo(`Right indent = ${(dlgParagraph as any).RightIndent}`);
dlg = app.Dialogs.Item(Word.WdWordDialog.wdDialogFormatParagraph);
(dlg as any).KeepWithNext = 1;
dlg.Execute();
// use of the Update method -- https://msdn.microsoft.com/en-us/vba/word-vba/articles/dialog-update-method-word
dlg = app.Dialogs.Item(Word.WdWordDialog.wdDialogFormatFont);
app.Selection.Font.Name = 'Arial';
dlg.Update();
dlg.Show();
// checking how a dialog box was closed
if (app.Dialogs.Item(Word.WdWordDialog.wdDialogInsertBreak).Show() === -1) {
app.StatusBar = 'Break inserted';
}
})();
// https://msdn.microsoft.com/en-us/vba/word-vba/articles/applying-formatting-to-text
(() => {
// Applying formatting to the selection
let font = app.Selection.Font;
font.Name = 'Times New Roman';
font.Size = 14;
font.AllCaps = true;
const paragraphFormat = app.Selection.ParagraphFormat;
paragraphFormat.LeftIndent = app.InchesToPoints(0.5);
paragraphFormat.Space1();
// Applying formatting to a range
let rngFormat = activeDoc.Range(
activeDoc.Paragraphs.Item(1).Range.Start,
activeDoc.Paragraphs.Item(3).Range.End
);
rngFormat.Font.Name = 'Arial';
rngFormat.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify;
// Inserting text and applying character and paragraph formatting
rngFormat = activeDoc.Range(0, 0);
rngFormat.InsertAfter('Title');
rngFormat.InsertParagraphAfter();
font = rngFormat.Font;
font.Name = 'Tahoma';
font.Size = 24;
font.Bold = true;
let paragraph = activeDoc.Paragraphs.Item(1);
paragraph.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
paragraph.SpaceAfter = app.InchesToPoints(0.5);
// Toggling the space before a paragraph between 12 points and none
paragraph = app.Selection.Paragraphs.Item(1);
paragraph.SpaceBefore = paragraph.SpaceBefore > 0 ? 0 : 6;
// Toggle bold formatting
app.Selection.Font.Bold = Word.WdConstants.wdToggle;
// Increase margins by .5 inches
const pageSetup = activeDoc.PageSetup;
pageSetup.LeftMargin += app.InchesToPoints(.5);
pageSetup.RightMargin += app.InchesToPoints(.5);
})();
// Assigning ranges -- https://msdn.microsoft.com/en-us/vba/word-vba/articles/assigning-ranges
(() => {
let rng1 = activeDoc.Words.Item(1);
const rng2 = activeDoc.Words.Item(2);
// unlike VBA, Javascript doesn't have the notion of default properties
// after this line, rng1 and rng2 will refer to the same Range object
rng1 = rng2;
// changes to the Range will be visible via both variables
rng1.MoveStart(Word.WdUnits.wdParagraph);
// using the Duplicate property creates a copy of the original Range
rng1 = rng2.Duplicate;
})();
// Editing text -- https://msdn.microsoft.com/en-us/vba/word-vba/articles/editing-text
(() => {
// Determining whether text is selected
if (app.Selection.Type === Word.WdSelectionType.wdSelectionIP) {
app.Selection.Font.Engrave = true;
} else {
WScript.Echo('You need to select some text');
}
// Collapsing a section or range
app.Selection.Collapse(Word.WdCollapseDirection.wdCollapseStart);
const rngWords = activeDoc.Words.Item(1);
rngWords.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
rngWords.Text = '(This is a test.)';
// Extending a selection or range
app.Selection.MoveEnd(Word.WdUnits.wdWord, 3);
const rngParagraphs = activeDoc.Paragraphs.Item(1).Range;
rngParagraphs.MoveEnd(Word.WdUnits.wdParagraph, 2);
// Changing text
activeDoc.Words.Item(1).Text = 'The ';
const rngFirstParagraph = activeDoc.Paragraphs.Item(1).Range;
rngFirstParagraph.Delete();
rngFirstParagraph.InsertAfter('New text');
rngFirstParagraph.InsertParagraphAfter();
})();
// finding and replacing text or formatting -- https://msdn.microsoft.com/en-us/vba/word-vba/articles/finding-and-replacing-text-or-formatting
(() => {
// Finding text and selecting it
const find = app.Selection.Find;
find.Forward = true;
find.Wrap = Word.WdFindWrap.wdFindStop;
find.Text = 'Hello';
find.Execute();
// Finding text without changing the selection
const find2 = app.ActiveDocument.Content.Find;
find2.Text = 'blue';
find2.Forward = true;
find2.Execute();
if (find2.Found) { find2.Parent.Bold = true; }
// Using the Replacement object
const find3 = app.Selection.Find;
find3.ClearFormatting;
find3.Text = 'Hi';
find3.Replacement.ClearFormatting();
find3.Replacement.Text = 'Hello';
find3.Forward = true;
find3.Wrap = Word.WdFindWrap.wdFindContinue;
find3.Execute(undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, Word.WdReplace.wdReplaceAll);
const find4 = app.ActiveDocument.Content.Find;
find4.ClearFormatting();
find4.Format = true;
find4.Font.Bold = true;
find4.Replacement.ClearFormatting();
find4.Replacement.Font.Bold = false;
find4.Execute("", undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, Word.WdReplace.wdReplaceAll);
})();
// looping through a collection -- https://msdn.microsoft.com/en-us/vba/word-vba/articles/looping-through-a-collection
(() => {
collectionToArray<Word.Document>(app.Documents)
.forEach(openDocument => WScript.Echo(openDocument.Name));
const strMarks = collectionToArray<Word.Bookmark>(activeDoc.Bookmarks)
.map(bookmark => bookmark.Name);
collectionToArray<Word.Field>(activeDoc.Fields)
.filter(dateField => dateField.Code.Text.indexOf('Date', 1) !== -1)
.forEach(dateField => dateField.Update());
const exists = collectionToArray<Word.AutoTextEntry>(activeDoc.AttachedTemplate.AutoTextEntries)
.some(autotextEntry => autotextEntry.Name === 'Filename');
if (exists) {
WScript.Echo('The Filename AutoText entry exists.');
}
})();
// inserting text in a document -- https://msdn.microsoft.com/en-us/vba/word-vba/articles/inserting-text-in-a-document
(() => {
activeDoc.Content.InsertAfter(' The end.');
app.Selection.InsertBefore('new text');
})();
// referring to the active document element -- https://msdn.microsoft.com/en-us/vba/word-vba/articles/referring-to-the-active-document-element
(() => {
app.Selection.Paragraphs.Item(1).Borders.Enable = true;
app.Selection.Paragraphs.Borders.Enable = true;
if (app.Selection.Tables.Count >= 1) {
app.Selection.Tables.Item(1).Rows.Item(1).Shading.Texture = Word.WdTextureIndex.wdTexture10Percent;
} else {
WScript.Echo('Selection doesn\'t include a table');
}
if (app.Selection.Tables.Count >= 1) {
collectionToArray<Word.Table>(app.Selection.Tables)
.forEach(table => table.Rows.Item(1).Shading.Texture = Word.WdTextureIndex.wdTexture30Percent);
}
})();
// returning an object from a collection -- https://msdn.microsoft.com/en-us/vba/word-vba/articles/returning-an-object-from-a-collection-word
(() => {
// no default properties in Javascript; we can't write app.Documents(1)
const docFirst = app.Documents.Item(1);
app.Documents.Item('Sales.doc').Activate();
WScript.Echo(app.ActiveDocument.Name);
app.ActiveDocument.Bookmarks.Item(1).Select();
WScript.Echo(app.Selection.Text);
// predefined index values;
const border = app.Selection.Paragraphs.Item(1).Borders.Item(Word.WdBorderType.wdBorderBottom);
border.LineStyle = Word.WdLineStyle.wdLineStyleSingle;
border.LineWidth = Word.WdLineWidth.wdLineWidth300pt;
border.Color = Word.WdColor.wdColorBlue;
})();
// returning text from a document -- https://msdn.microsoft.com/en-us/vba/word-vba/articles/returning-text-from-a-document
(() => {
const find = app.Selection.Find;
find.ClearFormatting();
find.Style = Word.WdBuiltinStyle.wdStyleHeading1;
find.Format = true;
find.Forward = true;
find.Wrap = Word.WdFindWrap.wdFindStop;
find.Text = "";
find.Execute();
if (find.Found) {
WScript.Echo(app.Selection.Text);
}
WScript.Echo(app.Selection.Text);
WScript.Echo(activeDoc.Words.Item(1).Text);
if (activeDoc.Bookmarks.Count > 0) {
WScript.Echo(activeDoc.Bookmarks.Item(1).Range.Text);
}
})();
// selecting text in a document -- https://msdn.microsoft.com/en-us/vba/word-vba/articles/selecting-text-in-a-document
(() => {
activeDoc.Tables.Item(1).Select();
activeDoc.Fields.Item(1).Select();
const rngParagraphs = activeDoc.Range(
activeDoc.Paragraphs.Item(1).Range.Start,
activeDoc.Paragraphs.Item(4).Range.End
);
rngParagraphs.Select();
})();
// storing values when a macro ends -- https://msdn.microsoft.com/en-us/vba/word-vba/articles/storing-values-when-a-macro-ends
(() => {
// document variables
activeDoc.Variables.Add('Age', 12);
const i = parseInt(activeDoc.Variables.Item('Age').Value, 10);
// document properties
activeDoc.CustomDocumentProperties.Add('YourName', false, Office.MsoDocProperties.msoPropertyTypeString);
activeDoc.AttachedTemplate.AutoTextEntries.Add('MyText', app.Selection.Range);
// no method assignment in Javascript
ActiveXObject.set(app.System, 'PrivateProfileString', ['C:\\My Documents\\Macro.ini', 'DocTracker', 'DocNum'], '1');
const docNum = parseInt(app.System.PrivateProfileString('C:\\My Documents\\Macro.ini', 'DocTracker', 'DocNum'), 10);
const section = 'HKEY_CURRENT_USER\\Software\\Microsoft\\Office\\12.0\\Word\Options';
const programDir = app.System.PrivateProfileString('', section, 'PROGRAMDIR');
WScript.Echo(`The program directory for Word is ${programDir}`);
ActiveXObject.set(app.System, 'PrivateProfileString', ['', section, 'DOC-PATH'], 'C:\\My Documents');
})();
+12613
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-word-tests.ts"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
}
}
+7 -6
View File
@@ -8,7 +8,8 @@ declare var AuthenticationContext: adal.AuthenticationContextStatic;
declare var Logging: adal.Logging;
declare module 'adal' {
export = { AuthenticationContext, Logging };
export const AuthenticationContext: adal.AuthenticationContextStatic;
export const Logging: adal.Logging;
}
declare namespace adal {
@@ -47,15 +48,15 @@ declare namespace adal {
stateResponse: string;
requestType: string;
}
interface Logging {
log: (message: string) => void;
level: LoggingLevel;
}
enum LoggingLevel {
ERROR = 0,
WARNING = 1,
WARNING = 1,
INFO = 2,
VERBOSE = 3
}
@@ -67,7 +68,7 @@ declare namespace adal {
interface AuthenticationContext {
instance: string;
config: Config;
config: Config;
/**
* Gets initial Idtoken for the app backend
@@ -162,7 +163,7 @@ declare namespace adal {
getResourceForEndpoint(endpoint: string): string;
/**
* Handles redirection after login operation.
* Handles redirection after login operation.
* Gets access token from url and saves token to the (local/session) storage
* or saves error in case unsuccessful login.
*/
+130 -82
View File
@@ -1,85 +1,133 @@
/// <reference types="node" />
declare const _null: symbol;
export { _null as null };
export function noop(): void;
export function identity<T>(x: T): T;
export function truly(): true;
export function falsely(): false;
export const ok: "OK";
export const bad: "BAD";
export const exts: [".js", ".tjs", ".ajs"];
export function log(...args: any[]): void;
export function fatal(...args: any[]): void;
export function error(...args: any[]): void;
export function warn(...args: any[]): void;
export function info(...args: any[]): void;
export function debug(...args: any[]): void;
export function trace(...args: any[]): void;
export function o(...props: any[]): object;
export const Date: typeof global.Date;
export const hrtime: typeof global.process.hrtime;
export const setTimeout: typeof global.setTimeout;
export const setInterval: typeof global.setInterval;
export const setImmediate: typeof global.setImmediate;
export const clearTimeout: typeof global.clearTimeout;
export const clearInterval: typeof global.clearInterval;
export const clearImmediate: typeof global.clearImmediate;
interface LazifyOptions {
configurable: boolean;
declare namespace adone {
const _null: symbol;
export { _null as null };
export function noop(): void;
export function identity<T>(x: T): T;
export function truly(): true;
export function falsely(): false;
export const ok: "OK";
export const bad: "BAD";
export const exts: [".js", ".tjs", ".ajs"];
export function log(...args: any[]): void;
export function fatal(...args: any[]): void;
export function error(...args: any[]): void;
export function warn(...args: any[]): void;
export function info(...args: any[]): void;
export function debug(...args: any[]): void;
export function trace(...args: any[]): void;
export function o(...props: any[]): object;
export const Date: typeof global.Date;
export const hrtime: typeof global.process.hrtime;
export const setTimeout: typeof global.setTimeout;
export const setInterval: typeof global.setInterval;
export const setImmediate: typeof global.setImmediate;
export const clearTimeout: typeof global.clearTimeout;
export const clearInterval: typeof global.clearInterval;
export const clearImmediate: typeof global.clearImmediate;
namespace I {
interface LazifyOptions {
/**
* Whether the new properties are configurable, false by default
*/
configurable?: boolean;
/**
* Whether the new properties are writable, false by default
*/
writable?: boolean;
/**
* A custom mapper for values, by default returns the exported object (module.exports),
* but if the object is a transpiled es module and the default export is defined,
* it returns the default export
*
* @param key property
* @param mod module.exports
*/
mapper?(key: string, mod: any): any;
}
}
/**
* Extends the given object(or creates a new one) with the given lazyfied properties
*/
export function lazify(modules: object, obj?: object, require?: (path: string) => any, options?: I.LazifyOptions): object;
/**
* Defines or extends the private part of the given object with the given lazyfied properties
*/
export function lazifyPrivate(modules: object, obj?: object, require?: (path: string) => any, options?: I.LazifyOptions): object;
/**
* Defines the private part of the given object with the given modules
*/
export function definePrivate(modules: object, obj: object): object;
/**
* Returns the private part of the given object
*/
export function private(obj: object): any;
namespace I {
interface Tag {
set(Class: object, tag: string): void;
has(obj: object, tag: string): boolean;
define(tag: string, predicate?: string): void;
SUBSYSTEM: symbol;
APPLICATION: symbol;
TRANSFORM: symbol;
CORE_STREAM: symbol;
LOGGER: symbol;
LONG: symbol;
BIGNUMBER: symbol;
EXBUFFER: symbol;
EXDATE: symbol;
CONFIGURATION: symbol;
GENESIS_NETRON: symbol;
GENESIS_PEER: symbol;
NETRON: symbol;
NETRON_PEER: symbol;
NETRON_ADAPTER: symbol;
NETRON_DEFINITION: symbol;
NETRON_DEFINITIONS: symbol;
NETRON_REFERENCE: symbol;
NETRON_INTERFACE: symbol;
NETRON_STUB: symbol;
NETRON_REMOTESTUB: symbol;
NETRON_STREAM: symbol;
FAST_STREAM: symbol;
FAST_FS_STREAM: symbol;
FAST_FS_MAP_STREAM: symbol;
}
}
export const tag: I.Tag;
export function bind(libName: string): object;
export function getAssetAbsolutePath(relPath: string): string;
export function loadAsset(relPath: string): string | Buffer;
export function require(path: string): object;
export const package: object;
namespace I {
interface Runtime {
term: object; // TODO
logger: object; // TODO
app: object; // TODO
}
}
export const runtime: I.Runtime;
export const homePath: string;
export const rootPath: string;
export const etcPath: string;
export const config: object;
export const emptyBuffer: Buffer;
export const assert: assertion.I.AssertFunction;
export const expect: assertion.I.ExpectFunction;
export const std: typeof nodestd;
}
export function lazify(modules: object, obj?: object, require?: (path: string) => any, options?: LazifyOptions): object;
interface Tag {
set(Class: object, tag: string): void;
has(obj: object, tag: string): boolean;
define(tag: string, predicate?: string): void;
SUBSYSTEM: symbol;
APPLICATION: symbol;
TRANSFORM: symbol;
CORE_STREAM: symbol;
LOGGER: symbol;
LONG: symbol;
BIGNUMBER: symbol;
EXBUFFER: symbol;
EXDATE: symbol;
CONFIGURATION: symbol;
GENESIS_NETRON: symbol;
GENESIS_PEER: symbol;
NETRON: symbol;
NETRON_PEER: symbol;
NETRON_ADAPTER: symbol;
NETRON_DEFINITION: symbol;
NETRON_DEFINITIONS: symbol;
NETRON_REFERENCE: symbol;
NETRON_INTERFACE: symbol;
NETRON_STUB: symbol;
NETRON_REMOTESTUB: symbol;
NETRON_STREAM: symbol;
FAST_STREAM: symbol;
FAST_FS_STREAM: symbol;
FAST_FS_MAP_STREAM: symbol;
}
export const tag: Tag;
export function run(App: object, ignoreArgs?: boolean): Promise<void>;
export function bind(libName: string): object;
export function getAssetAbsolutePath(relPath: string): string;
export function loadAsset(relPath: string): string | Buffer;
export function require(path: string): object;
export const package: object;
import * as std from "./glosses/std";
export { std };
export * from "./glosses/common";
export * from "./glosses/math";
export * from "./glosses/utils";
export * from "./glosses/assertion";
export * from "./glosses/promise";
export * from "./glosses/shani";
import "./glosses/shani-global";
export const assert: adone.assertion.I.AssertFunction;
export const expect: adone.assertion.I.ExpectFunction;
export as namespace adone;
+5
View File
@@ -0,0 +1,5 @@
declare namespace adone {
namespace application {
function run(app: object, ignoreArgs?: boolean): Promise<void>;
}
}
+670
View File
@@ -0,0 +1,670 @@
declare namespace adone {
/**
* Various archivers
*/
namespace archive {
/**
* tar archiver
*/
namespace tar {
namespace I {
interface Header {
/**
* File path
*/
name: string;
/**
* Type of entry, file by default
*/
type: "file" | "directory" | "link" | "symlink" | "block-device" | "character-device" | "fifo" | "contiguous-file";
/**
* Entry mode, 0755 for dirs and 0644 by default
*/
mode: number;
/**
* Last modified date for entry, now by default
*/
mtime: number;
/**
* Entry size, 0 by default
*/
size: number;
/**
* Linked file name
*/
linkname: string;
/**
* uid for entry owner, 0 by default
*/
uid: number;
/**
* gid for entry owner, 9 by default
*/
gid: number;
/**
* uname of entry owner, null by default
*/
uname: string;
/**
* gname of entry owner, null by default
*/
gname: string;
/**
* device minor versio, 0 by default
*/
devmajor: number;
/**
* device minor version, 0 by default
*/
devminor: number;
}
type Optional<T> = {
[P in keyof T]?: T[P];
};
interface OptionalHeader extends Optional<Header> {
/**
* File path
*/
name: string;
}
interface CommonOptions {
/**
* Entries filter
*/
ignore?(name: string): boolean;
/**
* Header mapper, called for each each entry
*/
map?(header: Header): Header | undefined;
/**
* Set the dmode and fmode to writable
*/
readable?: boolean;
/**
* Set the dmode and fmode to writable
*/
writable?: boolean;
/**
* Strip the parts of paths of files
*/
strip?: number;
/**
* Ensure that packed directories have the corresponding modes
*/
dmode?: number;
/**
* Ensure that packed files have the corresponding modes
*/
fmode?: number;
/**
* A custom umask, process.umask() by default
*/
umask?: number;
}
interface PackOptions extends CommonOptions {
/**
* Input read stream modifier, called for each entry
*/
mapStream?(stream: fs.I.ReadStream, header: Header): nodestd.stream.Readable;
/**
* Pack the contents of the symlink instead of the link itself, false by default
*/
dereference?: boolean;
/**
* Specifies which entries to pack, all by default
*/
entries?: string[];
/**
* Whether to sort entries before packing
*/
sort?: boolean;
/**
* set false to ignore errors due to unsupported entry types (like device files), true by default
*/
strict?: boolean;
/**
* A custom initial pack stream
*/
pack?: RawPackStream;
}
type Writable = nodestd.stream.Writable;
interface LinkSink extends Writable {
linkname: string;
}
interface UnpackOptions extends CommonOptions {
/**
* Input read stream modifier, called for each entry
*/
mapStream?(stream: UnpackSourceStream, header: Header): nodestd.stream.Readable;
/**
* Whether to change time properties of files
*/
utimes?: boolean;
/**
* Whether to change owner of the files
*/
chown?: boolean;
/**
* A custom unpack stream
*/
unpack?: RawUnpackStream;
/**
* Copies a file if cannot create a link
*/
hardlinkAsFilesFallback?: boolean;
}
interface UnpackSourceStream extends nodestd.stream.PassThrough {
_parent: RawUnpackStream;
}
}
/**
* Represents a raw tar unpack stream
*/
class RawPackStream extends nodestd.stream.Readable {
entry(header: I.OptionalHeader, buffer: Buffer, callback?: (err: any) => void): I.Writable;
entry(header: I.OptionalHeader & { type: "symblink", linkname: string }, callback?: (err: any) => void): I.Writable;
entry(header: I.OptionalHeader & { type: "symlink" }, callback?: (err: any) => void): I.LinkSink;
entry(header: I.OptionalHeader, callback?: (err: any) => void): I.Writable;
finalize(): void;
destroy(err?: any): void;
}
/**
* Represents a raw writable unpack stream
*/
class RawUnpackStream extends nodestd.stream.Writable {
on(event: string, listener: (...args: any[]) => void): this;
on(event: "entry", listener: (header: I.Header, stream: I.UnpackSourceStream, next: (err?: any) => void) => void): this;
on(event: "close", listener: () => void): this;
on(event: "drain", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "finish", listener: () => void): this;
on(event: "pipe", listener: (src: nodestd.stream.Readable) => void): this;
on(event: "unpipe", listener: (src: nodestd.stream.Readable) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "entry", listener: (header: I.Header, stream: I.UnpackSourceStream, next: (err?: any) => void) => void): this;
once(event: "close", listener: () => void): this;
once(event: "drain", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: "finish", listener: () => void): this;
once(event: "pipe", listener: (src: nodestd.stream.Readable) => void): this;
once(event: "unpipe", listener: (src: nodestd.stream.Readable) => void): this;
}
/**
* Creates a pack stream for the files from the given directory
*
* @param cwd directory to pack
*/
function packStream(cwd: string, options?: I.PackOptions): RawPackStream;
/**
* Creates an unpack stream to the given direcotry
*
* @param cwd direcotry to unpack to
*/
function unpackStream(cwd: string, options?: I.UnpackOptions): RawUnpackStream;
}
/**
* zip archiver
*/
namespace zip {
/**
* zip packer
*/
namespace pack {
class ZipFile {
/**
* A readable stream that will produce the contents of the zip file
*/
outputStream: nodestd.stream.Readable;
/**
* Adds a file from the file system at realPath into the zipfile as metadataPath
*
* @param path path to the file
* @param metadataPath path to the file inside the archive
*/
addFile(path: string, metadataPath: string, options?: {
/**
* Overrides the value that will be obtained from stat
*/
mtime?: number,
/**
* Overrides the value that will be obtained from stat
*/
mode?: number,
/**
* If true, the file data will be deflated (compression method 8).
*
* If false, the file data will be stored (compression method 0)
*/
compress?: boolean,
/**
* Use ZIP64 format in this entry's Data Descriptor and Central Directory Record
* regardless of if it's required or not (this may be useful for testing.).
* Otherwise, packer will use ZIP64 format where necessary.
*/
forceZip64Format?: boolean
}): this;
/**
* Adds a file to the zip file whose content is read from readStream
*
* @param stream a readable stream for the file
* @param metadataPath path to the file inside the archive
*/
addReadStream(stream: nodestd.stream.Readable, metadataPath: string, options?: {
/**
* Defines modified date, now by default
*/
mtime?: number,
/**
* Defines file mode, 0o100664 by default
*/
mode?: number,
/**
* If true, the file data will be deflated (compression method 8).
*
* If false, the file data will be stored (compression method 0)
*/
compress?: boolean,
/**
* Use ZIP64 format in this entry's Data Descriptor and Central Directory Record
* regardless of if it's required or not (this may be useful for testing.).
* Otherwise, packer will use ZIP64 format where necessary.
*/
forceZip64Format?: boolean,
/**
* If given, it will be checked against the actual number of bytes in the readStream,
* and an error will be emitted if there is a mismatch
*/
size?: number
}): this;
/**
* Adds a file to the zip file whose content is buffer
*
* @param buffer the file's contents, must be at most 0x3fffffff bytes long
* @param metadataPath path to the file inside the archive
*/
addBuffer(buffer: Buffer, metadataPath: string, options?: {
/**
* Defines modified date, now by default
*/
mtime?: number,
/**
* Defines file mode, 0o100664 by default
*/
mode?: number,
/**
* If true, the file data will be deflated (compression method 8).
*
* If false, the file data will be stored (compression method 0)
*/
compress?: boolean,
/**
* Use ZIP64 format in this entry's Data Descriptor and Central Directory Record
* regardless of if it's required or not (this may be useful for testing.).
* Otherwise, packer will use ZIP64 format where necessary.
*/
forceZip64Format?: boolean
}): this;
/**
* Adds an entry to the zip file that indicates a directory should be created,
* even if no other items in the zip file are contained in the directory
*/
addEmptyDirectory(metadataPath: string, options?: {
/**
* Defines modified date, now by default
*/
mtime?: number,
/**
* Defines file mode, 0o40775 by default
*/
mode?: number
}): this;
/**
* Indicates that no more files will be added via addFile(), addReadStream(), or addBuffer().
* Some time after calling this function, outputStream will be ended.
*
* @returns the final guessed size of the file, can be -1 if it is hard to guess before processing. This will happend
* only if compression is enabled, or a stream with no size hint given
*/
end(options?: {
/**
* If true, packet will include the ZIP64 End of Central Directory Locator and ZIP64 End of Central Directory Record
* regardless of whether or not they are required (this may be useful for testing.).
* Otherwise, packer will include these structures if necessary
*/
forceZip64Format?: boolean
}): Promise<number>;
}
}
/**
* zip unpacker
*/
namespace unpack {
namespace I {
interface ExtraField {
id: number;
data: Buffer;
}
interface Entry<StringType> {
versionMadeBy: number;
versionNeededToExtract: number;
generalPurposeBitFlag: number;
compressionMethod: number;
lastModFileTime: number;
lastModFileDate: number;
crc32: number;
compressedSize: number;
uncompressedSize: number;
fileNameLength: number;
extraFieldLength: number;
fileCommentLength: number;
internalFileAttributes: number;
externalFileAttributes: number;
relativeOffsetOfLocalHeader: number;
/**
* The bytes for the file name are decoded with UTF-8 if generalPurposeBitFlag & 0x800, otherwise with CP437.
* Alternatively, this field may be populated from the Info-ZIP Unicode Path Extra Field (see extraFields).
*/
fileName: StringType;
extraFields: ExtraField[];
/**
* Comment decoded with the charset indicated by generalPurposeBitFlag & 0x800 as with the fileName
*/
fileComment: StringType;
getLastModDate(): adone.I.datetime.Datetime;
/**
* Whether this entry is encrypted with "Traditional Encryption"
*/
isEncrypted(): boolean;
/**
* Whether the entry is compressed
*/
isCompressed(): boolean;
}
interface ZipFile<StringType> extends event.EventEmitter {
/**
* true until close() is called; then it's false
*/
isOpen: boolean;
/**
* Total number of central directory records
*/
entryCount: number;
/**
* Always decoded with CP437 per the spec
*/
comment: StringType;
/**
* Causes all future calls to openReadStream() to fail,
* and closes the fd after all streams created by openReadStream() have emitted their end events
*/
close(): void;
readEntry(): Promise<void>;
/**
* Opens a read stream for the given entry
*/
openReadStream(entry: Entry<StringType>, options?: {
/**
* The option must be omitted when the entry is not compressed (see isCompressed()),
* and either true (or omitted) or false when the entry is compressed.
* Specifying decompress: false for a compressed entry causes the read stream
* to provide the raw compressed file data without going through a zlib inflate transform
*/
decompress?: boolean,
/**
* The option must be null (or omitted) for non-encrypted entries,
* and false for encrypted entries. Omitting the option for an encrypted entry will result in an err.
*/
decrypt?: boolean,
/**
* The start byte offset (inclusive) into this entry's file data
*/
start?: number,
/**
* The end byte offset (exclusive) into this entry's file data
*/
end?: number,
}): Promise<nodestd.stream.Readable>;
/**
* Emitted for each entry.
*
* If decodeStrings is true, entries emitted via this event have already passed file name validation
*
* If validateEntrySizes is true and this entry's compressionMethod is 0 (stored without compression),
* this entry has already passed entry size validation
*/
on(event: "entry", listener: (entry: Entry<StringType>) => void): this;
/**
* Emitted after the last entry event has been emitted
*/
on(event: "end", listener: () => void): this;
/**
* Emitted after the fd is actually closed
*/
on(event: "close", listener: () => void): this;
/**
* Emitted in the case of errors with reading the zip file
*/
on(event: "error", listener: (err: any) => void): this;
/**
* Emitted for each entry.
*
* If decodeStrings is true, entries emitted via this event have already passed file name validation
*
* If validateEntrySizes is true and this entry's compressionMethod is 0 (stored without compression),
* this entry has already passed entry size validation
*/
once(event: "entry", listener: (entry: Entry<StringType>) => void): this;
/**
* Emitted after the last entry event has been emitted
*/
once(event: "end", listener: () => void): this;
/**
* Emitted after the fd is actually closed
*/
once(event: "close", listener: () => void): this;
/**
* Emitted in the case of errors with reading the zip file
*/
once(event: "error", listener: (err: any) => void): this;
}
interface CommonOptions {
/**
* Indicates that entries should be read only when readEntry() is called.
* If lazyEntries is false, entry events will be emitted as fast as possible
* to allow pipe()-ing file data from all entries in parallel.
*
* Default is false
*/
lazyEntries?: boolean;
/**
* Causes unpacker to decode strings with CP437 or UTF-8 as required by the spec.
*
* When turned off zipfile.comment, entry.fileName, and entry.fileComment will be Buffer,
* any Info-ZIP Unicode Path Extra Field will be ignored, automatic file name validation will not be performed
*/
decodeStrings?: boolean;
/**
* Ensures that an entry's reported uncompressed size matches its actual uncompressed size
*/
validateEntrySizes?: boolean;
}
interface PathOptions extends CommonOptions {
/**
* Autocloses the file after the last entry reading or when an error occurs
*
* Default is true
*/
autoClose?: boolean;
}
interface FdOptions extends CommonOptions {
/**
* Autocloses the file after the last entry reading or when an error occurs
*
* Default is false
*/
autoClose?: boolean;
}
type BufferOptions = CommonOptions;
interface RandomAccessReaderOptions extends CommonOptions {
/**
* Autocloses the file after the last entry reading or when an error occurs
*
* Default is true
*/
autoClose?: boolean;
}
}
/**
* Opens a file and creates a zipfile unpacker
*/
function open(path: string, options: I.PathOptions & { decodeStrings: false }): I.ZipFile<Buffer>;
/**
* Opens a file and creates a zipfile unpacker
*/
function open(path: string, options?: I.PathOptions): I.ZipFile<string>;
/**
* Creates a zipfile unpacker for the given fd
*/
function fromFd(fd: number, options: I.FdOptions & { decodeStrings: false }): I.ZipFile<Buffer>;
/**
* Creates a zipfile unpacker for the given fd
*/
function fromFd(fd: number, options?: I.FdOptions): I.ZipFile<string>;
/**
* Creates a zipfile unpacker for the given buffer
*/
function fromBuffer(buffer: Buffer, options: I.BufferOptions & { decodeStrings: false }): I.ZipFile<Buffer>;
/**
* Creates a zipfile unpacker for the given buffer
*/
function fromBuffer(buffer: Buffer, options?: I.BufferOptions): I.ZipFile<string>;
/**
* Creates a zipfile unpacker for the given random access reader.
* This method of reading a zip file allows clients to implement their own back-end file system
*
* @param totalSize Indicates the total file size of the zip file
*/
function fromRandomAccessReader(
reader: fs.AbstractRandomAccessReader,
totalSize: number,
options: I.RandomAccessReaderOptions & { decodeStrings: false }
): I.ZipFile<Buffer>;
/**
* Creates a zipfile unpacker for the given random access reader.
* This method of reading a zip file allows clients to implement their own back-end file system
*
* @param totalSize Indicates the total file size of the zip file
*/
function fromRandomAccessReader(
reader: fs.AbstractRandomAccessReader,
totalSize: number,
options?: I.RandomAccessReaderOptions
): I.ZipFile<string>;
/**
* Returns null or a String error message depending on the validity of fileName
*/
function validateFileName(filename: string): string | null;
}
}
}
}
+1067 -1067
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-465
View File
@@ -1,465 +0,0 @@
/**
* predicates
*/
export namespace is {
function _null(obj: any): boolean;
export { _null as null };
export function undefined(obj: any): boolean;
export function exist(obj: any): boolean;
export function nil(obj: any): boolean;
export function number(obj: any): boolean;
export function numeral(obj: any): boolean;
export function infinite(obj: any): boolean;
export function odd(obj: any): boolean;
export function even(obj: any): boolean;
export function float(obj: any): boolean;
export function negativeZero(obj: any): boolean;
export function string(obj: any): boolean;
export function emptyString(obj: any): boolean;
export function substring(substring: string, string: string, offset?: number): boolean;
export function prefix(prefix: string, string: string): boolean;
export function suffix(suffix: string, string: string): boolean;
export function boolean(obj: any): boolean;
export function json(obj: any): boolean;
export function object(obj: any): boolean;
export function plainObject(obj: any): boolean;
function _class(obj: any): boolean;
export { _class as class };
export function emptyObject(obj: any): boolean;
export function propertyOwned(obj: any, field: string): boolean;
export function propertyDefined(obj: any, field: string): boolean;
export function conforms(obj: object, schema: object, strict?: boolean): boolean;
export function arrayLikeObject(obj: any): boolean;
export function inArray<T>(value: T, array: any[], offset?: number, comparator?: (a: T, b: T) => boolean): boolean;
export function sameType(value: any, other: any): boolean;
export function primitive(obj: any): boolean;
export function equalArrays(left: any[], right: any[]): boolean;
export function deepEqual(left: any, right: any): boolean;
export function shallowEqual(left: any, right: any): boolean;
export function stream(obj: any): boolean;
export function writableStream(obj: any): boolean;
export function readableStream(obj: any): boolean;
export function duplexStream(obj: any): boolean;
export function transformStream(obj: any): boolean;
export function utf8(obj: Buffer): boolean;
export function win32PathAbsolute(path: string): boolean;
export function posixPathAbsolute(path: string): boolean;
export function pathAbsolute(path: string): boolean;
export function glob(str: string): boolean;
export function dotfile(str: string): boolean;
function _function(obj: any): boolean;
export { _function as function };
export function asyncFunction(obj: any): boolean;
export function promise(obj: any): boolean;
export function validDate(str: string): boolean;
export function buffer(obj: any): boolean;
export function callback(obj: any): boolean;
export function generator(obj: any): boolean;
export function nan(obj: any): boolean;
export function finite(obj: any): boolean;
export function integer(obj: any): boolean;
export function safeInteger(obj: any): boolean;
export function array(obj: any): boolean;
export function uint8Array(obj: any): boolean;
export function configuration(obj: any): boolean;
export function long(obj: any): boolean;
export function bigNumber(obj: any): boolean;
export function exbuffer(obj: any): boolean;
export function exdate(obj: any): boolean;
export function transform(obj: any): boolean;
export function subsystem(obj: any): boolean;
export function application(obj: any): boolean;
export function logger(obj: any): boolean;
export function coreStream(obj: any): boolean;
export function fastStream(obj: any): boolean;
export function fastFSStream(obj: any): boolean;
export function fastFSMapStream(obj: any): boolean;
export function genesisNetron(obj: any): boolean;
export function genesisPeer(obj: any): boolean;
export function netronAdapter(obj: any): boolean;
export function netron(obj: any): boolean;
export function netronPeer(obj: any): boolean;
export function netronDefinition(obj: any): boolean;
export function netronDefinitions(obj: any): boolean;
export function netronReference(obj: any): boolean;
export function netronInterface(obj: any): boolean;
export function netronContext(obj: any): boolean;
export function netronIMethod(netronInterface: object, name: string): boolean;
export function netronIProperty(netronInterface: any, name: string): boolean;
export function netronStub(obj: any): boolean;
export function netronRemoteStub(obj: any): boolean;
export function netronStream(obj: any): boolean;
export function iterable(obj: any): boolean;
export const windows: boolean;
export const linux: boolean;
export const freebsd: boolean;
export const darwin: boolean;
export const sunos: boolean;
export function uppercase(str: string): boolean;
export function lowercase(str: string): boolean;
export function digits(str: string): boolean;
export function identifier(str: string): boolean;
export function binaryExtension(str: string): boolean;
export function binaryPath(str: string): boolean;
export function ip4(str: string): boolean;
export function ip6(str: string): boolean;
export function arrayBuffer(obj: any): boolean;
export function arrayBufferView(obj: any): boolean;
export function date(obj: any): boolean;
export function error(obj: any): boolean;
export function map(obj: any): boolean;
export function regexp(obj: any): boolean;
export function set(obj: any): boolean;
export function symbol(obj: any): boolean;
export function validUTF8(obj: any): boolean;
}
export namespace x {
class Exception extends Error {
constructor(message?: string | Error, captureStackTrace?: boolean);
}
class Runtime extends Exception { }
class IncompleteBufferError extends Exception { }
class NotImplemented extends Exception { }
class IllegalState extends Exception { }
class NotValid extends Exception { }
class Unknown extends Exception { }
class NotExists extends Exception { }
class Exists extends Exception { }
class Empty extends Exception { }
class InvalidAccess extends Exception { }
class NotSupported extends Exception { }
class InvalidArgument extends Exception { }
class InvalidNumberOfArguments extends Exception { }
class NotFound extends Exception { }
class Timeout extends Exception { }
class Incorrect extends Exception { }
class NotAllowed extends Exception { }
class LimitExceeded extends Exception { }
class Encoding extends Exception { }
class Network extends Exception { }
class Bind extends Exception { }
class Connect extends Exception { }
class Database extends Exception { }
class DatabaseInitialization extends Exception { }
class DatabaseOpen extends Exception { }
class DatabaseRead extends Exception { }
class DatabaseWrite extends Exception { }
class NetronIllegalState extends Exception { }
class NetronPeerDisconnected extends Exception { }
class NetronTimeout extends Exception { }
}
export class EventEmitter {
static listenerCount(emitter: EventEmitter, event: string | symbol): number;
static defaultMaxListeners: number;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeAllListeners(event?: string | symbol): this;
setMaxListeners(n: number): this;
getMaxListeners(): number;
listeners(event: string | symbol): Array<(...args: any[]) => any>;
emit(event: string | symbol, ...args: any[]): boolean;
eventNames(): Array<string | symbol>;
listenerCount(type: string | symbol): number;
}
export class AsyncEmitter extends EventEmitter {
constructor(concurrency?: number);
setConcurrency(max?: number): this;
emitParallel(event: string, ...args: any[]): Promise<any[]>;
emitSerial(event: string, ...args: any[]): Promise<any[]>;
emitReduce(event: string, ...args: any[]): Promise<any>;
emitReduceRight(event: string, ...args: any[]): Promise<any>;
subscribe(event: string, listener: (...args: any[]) => void, once?: boolean): () => void;
}
declare namespace I {
type Long = adone.math.Long;
type Longable = adone.math.I.Longable;
namespace ExBuffer {
interface Varint32 {
value: number;
length: number;
}
interface Varint64 {
value: Long;
length: number;
}
interface String {
string: string;
length: number;
}
type Wrappable = string | ExBuffer | Buffer | Uint8Array | ArrayBuffer;
type METRICS = "b" | "c";
}
}
export class ExBuffer {
constructor(capacity?: number, noAssert?: boolean);
readBitSet(offset?: number): number[];
read(length: number, offset?: number): ExBuffer;
readInt8(offset?: number): number;
readUInt8(offset?: number): number;
readInt16LE(offset?: number): number;
readUInt16LE(offset?: number): number;
readInt16BE(offset?: number): number;
readUInt16BE(offset?: number): number;
readInt32LE(offset?: number): number;
readUInt32LE(offset?: number): number;
readInt32BE(offset?: number): number;
readUInt32BE(offset?: number): number;
readInt64LE(offset?: number): adone.math.Long;
readUInt64LE(offset?: number): adone.math.Long;
readInt64BE(offset?: number): adone.math.Long;
readUInt64BE(offset?: number): adone.math.Long;
readFloatLE(offset?: number): number;
readFloatBE(offset?: number): number;
readDoubleLE(offset?: number): number;
readDoubleBE(offset?: number): number;
write(source: I.ExBuffer.Wrappable, offset?: number, length?: number, encoding?: string): this;
writeBitSet(value: number[]): this;
writeBitSet(value: number[], offset: number): number;
writeInt8(value: number, offset?: number): this;
writeUInt8(value: number, offset?: number): this;
writeInt16LE(value: number, offset?: number): this;
writeInt16BE(value: number, offset?: number): this;
writeUInt16LE(value: number, offset?: number): this;
writeUInt16BE(value: number, offset?: number): this;
writeInt32LE(value: number, offset?: number): this;
writeInt32BE(value: number, offset?: number): this;
writeUInt32LE(value: number, offset?: number): this;
writeUInt32BE(value: number, offset?: number): this;
writeInt64LE(value: I.Longable, offset?: number): this;
writeInt64BE(value: I.Longable, offset?: number): this;
writeUInt64LE(value: I.Longable, offset?: number): this;
writeUInt64BE(value: I.Longable, offset?: number): this;
writeFloatLE(value: number, offset?: number): this;
writeFloatBE(value: number, offset?: number): this;
writeDoubleLE(value: number, offset?: number): this;
writeDoubleBE(value: number, offset?: number): this;
writeVarint32(value: number): this;
writeVarint32(value: number, offset: number): number;
writeVarint32ZigZag(value: number): this;
writeVarint32ZigZag(value: number, offset: number): number;
readVarint32(): number;
readVarint32(offset: number): I.ExBuffer.Varint32;
readVarint32ZigZag(): number;
readVarint32ZigZag(offset: number): I.ExBuffer.Varint32;
writeVarint64(value: I.Longable): this;
writeVarint64(value: I.Longable, offset: number): number;
writeVarint64ZigZag(value: I.Longable): this;
writeVarint64ZigZag(value: I.Longable, offset: number): number;
readVarint64(): I.Long;
readVarint64(offset: number): I.ExBuffer.Varint64;
readVarint64ZigZag(): adone.math.Long;
readVarint64ZigZag(offset: number): I.ExBuffer.Varint64;
writeCString(str: string): this;
writeCString(str: string, offset: number): number;
readCString(): string;
readCString(offset: number): I.ExBuffer.String;
writeString(str: string): this;
writeString(str: string, offset: number): number;
readString(length: number, metrics?: I.ExBuffer.METRICS): string;
readString(length: number, metrics: I.ExBuffer.METRICS, offset: number): I.ExBuffer.String;
readString(length: number, offset: number): I.ExBuffer.String;
writeVString(str: string): this;
writeVString(str: string, offset: number): number;
readVString(): string;
readVString(offset: number): I.ExBuffer.String;
appendTo(target: ExBuffer, offset?: number): this;
assert(assert?: boolean): this;
capacity(): number;
clear(): this;
compact(begin?: number, end?: number): this;
copy(begin?: number, end?: number): ExBuffer;
copyTo(target: ExBuffer, targetOffset?: number, souceOffset?: number, sourceLimit?: number): this | ExBuffer;
ensureCapacity(capacity: number): this;
fill(value: string | number, begin?: number, end?: number): this;
flip(): this;
mark(offset?: number): this;
prepend(source: I.ExBuffer.Wrappable, encoding?: string, offset?: number): this;
prepend(source: I.ExBuffer.Wrappable, offset: number): this;
prependTo(target: ExBuffer, offset?: number): this;
remaining(): number;
reset(): this;
resize(capacity: number): this;
reverse(begin?: number, end?: number): this;
skip(length: number): this;
slice(begin?: number, end?: number): ExBuffer;
toBuffer(forceCopy?: boolean, begin?: number, end?: number): Buffer;
toArrayBuffer(): ArrayBuffer;
toString(encoding?: string, begin?: number, end?: number): string;
toBase64(begin?: number, end?: number): string;
toBinary(begin?: number, end?: number): string;
toDebug(columns?: boolean): string;
toHex(begin?: number, end?: number): string;
toUTF8(begin?: number, end?: number): string;
static accessor(): typeof Buffer;
static allocate(capacity?: number, noAssert?: boolean): ExBuffer;
static concat(buffers: I.ExBuffer.Wrappable[], encoding?: string, noAssert?: boolean): ExBuffer;
static type(): typeof Buffer;
static wrap(buffer: I.ExBuffer.Wrappable, encoding?: string, noAssert?: boolean): ExBuffer;
static calculateVarint32(value: number): number;
static zigZagEncode32(n: number): number;
static zigZagDecode32(n: number): number;
static calculateVarint64(value: number | string): number;
static zigZagEncode64(value: number | string | I.Long): I.Long;
static zigZagDecode64(value: number | string | I.Long): I.Long;
static calculateUTF8Chars(str: string): number;
static calculateString(str: string): number;
static fromBase64(str: string): ExBuffer;
static btoa(str: string): string;
static atob(b64: string): string;
static fromBinary(str: string): ExBuffer;
static fromDebug(str: string, noAssert?: boolean): ExBuffer;
static fromHex(str: string, noAssert?: boolean): ExBuffer;
static fromUTF8(str: string, noAssert?: boolean): ExBuffer;
static DEFAULT_CAPACITY: number;
static DEFAULT_NOASSERT: boolean;
static MAX_VARINT32_BYTES: number;
static MAX_VARINT64_BYTES: number;
static METRICS_CHARS: string;
static METRICS_BYTES: string;
}
File diff suppressed because it is too large Load Diff
+1032
View File
File diff suppressed because it is too large Load Diff
+1394
View File
File diff suppressed because it is too large Load Diff
+38
View File
@@ -0,0 +1,38 @@
declare namespace adone {
namespace event {
class EventEmitter {
static listenerCount(emitter: EventEmitter, event: string | symbol): number;
static defaultMaxListeners: number;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeAllListeners(event?: string | symbol): this;
setMaxListeners(n: number): this;
getMaxListeners(): number;
listeners(event: string | symbol): Array<(...args: any[]) => any>;
emit(event: string | symbol, ...args: any[]): boolean;
eventNames(): Array<string | symbol>;
listenerCount(type: string | symbol): number;
}
class AsyncEmitter extends EventEmitter {
constructor(concurrency?: number);
setConcurrency(max?: number): this;
emitParallel(event: string, ...args: any[]): Promise<any[]>;
emitSerial(event: string, ...args: any[]): Promise<any[]>;
emitReduce(event: string, ...args: any[]): Promise<any>;
emitReduceRight(event: string, ...args: any[]): Promise<any>;
subscribe(event: string, listener: (...args: any[]) => void, once?: boolean): () => void;
}
}
}
+37
View File
@@ -0,0 +1,37 @@
declare namespace adone {
namespace x {
class Exception extends Error {
constructor(message?: string | Error, captureStackTrace?: boolean);
}
class Runtime extends Exception { }
class IncompleteBufferError extends Exception { }
class NotImplemented extends Exception { }
class IllegalState extends Exception { }
class NotValid extends Exception { }
class Unknown extends Exception { }
class NotExists extends Exception { }
class Exists extends Exception { }
class Empty extends Exception { }
class InvalidAccess extends Exception { }
class NotSupported extends Exception { }
class InvalidArgument extends Exception { }
class InvalidNumberOfArguments extends Exception { }
class NotFound extends Exception { }
class Timeout extends Exception { }
class Incorrect extends Exception { }
class NotAllowed extends Exception { }
class LimitExceeded extends Exception { }
class Encoding extends Exception { }
class Network extends Exception { }
class Bind extends Exception { }
class Connect extends Exception { }
class Database extends Exception { }
class DatabaseInitialization extends Exception { }
class DatabaseOpen extends Exception { }
class DatabaseRead extends Exception { }
class DatabaseWrite extends Exception { }
class NetronIllegalState extends Exception { }
class NetronPeerDisconnected extends Exception { }
class NetronTimeout extends Exception { }
}
}
+745
View File
@@ -0,0 +1,745 @@
declare namespace adone {
/**
* Filesystem Automation Streaming Templates/Transforms
*/
namespace fast {
// File is based on vinyl typings
// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/vinyl/index.d.ts
namespace I {
interface FileConstructorOptions {
/**
* The current workring directory of the file. Default: process.cwd()
*/
cwd?: string;
/**
* Full path to the file
*/
path?: string;
/**
* Stores the path history
*/
history?: string[];
/**
* The result of a fs.Stat call
*/
stat?: fs.I.Stats;
/**
* File contents
*/
contents?: null | Buffer | nodestd.stream.Readable;
/**
* Used for relative pathing. Typically where a glob starts. Default: options.cwd
*/
base?: string;
symlink?: string;
}
interface FileCloneOptions {
contents?: boolean;
deep?: boolean;
}
interface FileConstructor {
new(options: FileConstructorOptions & { contents: Buffer }): BufferFile;
new(options: FileConstructorOptions & { contents: nodestd.stream.Readable }): StreamFile;
new(options?: FileConstructorOptions): NullFile;
prototype: File;
}
interface File {
/**
* Gets and sets the contents of the file
*/
contents: null | Buffer | nodestd.stream.Readable;
/**
* Gets and sets current working directory. Will always be normalized and have trailing separators removed.
*/
cwd: string;
/**
* Gets and sets base directory. Used for relative pathing (typically where a glob starts).
*/
base: string;
/**
* Gets and sets the absolute pathname string or `undefined`. Setting to a different value
* appends the new path to `file.history`. If set to the same value as the current path, it
* is ignored. All new values are normalized and have trailing separators removed.
*/
path: string;
stat: fs.I.Stats;
/**
* Gets the result of `path.relative(file.base, file.path)`. Or sets a new relative path for file.base
*/
relative: string;
/**
* Gets and sets the dirname of `file.path`. Will always be normalized and have trailing
* separators removed.
*/
dirname: string;
/**
* Gets and sets the basename of `file.path`.
*/
basename: string;
/**
* Gets and sets extname of `file.path`.
*/
extname: string;
/**
* Gets and sets stem (filename without suffix) of `file.path`.
*/
stem: string;
/**
* Array of `file.path` values the file has had, from `file.history[0]` (original)
* through `file.history[file.history.length - 1]` (current). `file.history` and its elements
* should normally be treated as read-only and only altered indirectly by setting `file.path`.
*/
readonly history: ReadonlyArray<string>;
/**
* Gets and sets the path where the file points to if it's a symbolic link. Will always
* be normalized and have trailing separators removed.
*/
symlink: string;
/**
* Returns a new File object with all attributes cloned.
*/
clone(options: FileCloneOptions & { contents: true }): this;
clone(options?: FileCloneOptions): File;
isBuffer(): boolean;
isStream(): boolean;
isNull(): boolean;
isDirectory(): boolean;
isSymbolic(): boolean;
}
interface NullFile extends File {
contents: null;
}
interface BufferFile extends File {
contents: Buffer;
//
}
interface StreamFile extends File {
contents: nodestd.stream.Readable;
}
type DirectoryFile = File;
type SymbolicFile = File;
/* tslint:disable-next-line:no-empty-interface */
interface Stream<S, T = File> extends stream.CoreStream<S, T> {
//
}
}
export const File: I.FileConstructor;
namespace I {
type CoreStreamSource = stream.I.CoreStream.Source<any, File>;
interface LocalStreamConstructorOptions {
/**
* Whether to read files. Default: true
*/
read?: boolean;
/**
* Read files as buffers. Default: true
*/
buffer?: boolean;
/**
* Read files as streams
*/
stream?: boolean;
/**
* Current working directory for files. Default: process.cwd()
*/
cwd?: string;
}
interface LocalStreamConstructor {
new(source: CoreStreamSource | File[], options: LocalStreamConstructorOptions & { read: false }): LocalStream<NullFile>;
new(source: CoreStreamSource | File[], options: LocalStreamConstructorOptions & { stream: true }): LocalStream<StreamFile>;
new(source: CoreStreamSource | File[], options?: LocalStreamConstructorOptions): LocalStream<BufferFile>;
prototype: LocalStream<File>;
}
interface LocalStreamDestOptions {
/**
* Mode that is used for writing
*/
mode?: number;
/**
* Flag that is used for writing
*/
flag?: fs.I.Flag;
/**
* Current working directory for files, dest is resolved using this cwd. Default: constuctor cwd or process.cwd()
*/
cwd?: string;
/**
* Whether to push written files into the stream
*/
produceFiles?: boolean;
/**
* Whether to inherit the source file's mode (access properties)
*/
originMode?: boolean;
/**
* Whether to inherit the source file's time properties (atime, mtime)
*/
originTimes?: boolean;
/**
* Whether to inherit the source file's uid and gid
*/
originOwner?: boolean;
}
interface LocalStream<T> extends Stream<File, T> {
/**
* Writes all files into the given directory
*
* @param directory directory where to write files
*/
dest(directory: string, options?: LocalStreamDestOptions): this;
/**
* Writes all files into the given directory using the given callback
*
* @param getDirectory callback that returns a directory for each file
*/
dest(getDirectory: (file: T) => string, options?: LocalStreamDestOptions): this;
}
}
export const LocalStream: I.LocalStreamConstructor;
namespace I {
interface SrcOptions extends LocalStreamConstructorOptions {
/**
* Used for relative pathing of files. Typically where a glob starts.
*/
base?: string;
/**
* Whether to match dotted files (hidden). Default: true
*/
dot?: boolean;
/**
* Whether to lstat instead of stat when stating. Default: false
*/
links?: boolean;
}
}
/**
* @param globs Source file/files
*/
function src(globs: string | string[], options: I.SrcOptions & { read: false }): I.LocalStream<I.NullFile>;
function src(globs: string | string[], options: I.SrcOptions & { stream: true }): I.LocalStream<I.StreamFile>;
function src(globs: string | string[], options?: I.SrcOptions): I.LocalStream<I.BufferFile>;
namespace I {
type WatcherConstructorOptions = fs.I.Watcher.ConstructorOptions;
interface WatchOptions extends WatcherConstructorOptions, LocalStreamConstructorOptions {
/**
* Used for relative pathing of files. Typically where a glob starts.
*/
base?: string;
/**
* Whether to match dotted files (hidden). Default: true
*/
dot?: boolean;
/**
* Whether to resume the stream on the next tick. Default: true
*/
resume?: boolean;
}
}
/**
* @param globs Source file/files
*/
function watch(globs: string | string[], options: I.WatchOptions & { read: false }): I.LocalStream<I.NullFile>;
function watch(globs: string | string[], options: I.WatchOptions & { stream: true }): I.LocalStream<I.StreamFile>;
function watch(globs: string | string[], options?: I.WatchOptions): I.LocalStream<I.BufferFile>;
namespace I {
interface LocalMapStream<T> extends Stream<File, T> {
dest(options?: LocalStreamDestOptions): this;
}
interface Mapping {
/**
* Source file/files
*/
from: string;
/**
* Destination directory
*/
to: string;
}
interface MapOptions extends LocalStreamConstructorOptions {
/**
* Used for relative pathing of files. Typically where a glob starts.
*/
base?: string;
/**
* Whether to match dotted files (hidden). Default: true
*/
dot?: boolean;
}
type WatchMapOptions = MapOptions & WatcherConstructorOptions;
type MapSource = Mapping | Mapping[];
}
/**
* The same as fast.src, but source and dest paths are defined in one place
*/
function map(mappings: I.MapSource, options: I.MapOptions & { read: false }): I.LocalMapStream<I.NullFile>;
function map(mappings: I.MapSource, options: I.MapOptions & { stream: true }): I.LocalMapStream<I.StreamFile>;
function map(mappings: I.MapSource, options?: I.MapOptions): I.LocalMapStream<I.BufferFile>;
function watchMap(mappings: I.MapSource, options: I.WatchMapOptions & { read: false }): I.LocalMapStream<I.NullFile>;
function watchMap(mappings: I.MapSource, options: I.WatchMapOptions & { stream: true }): I.LocalMapStream<I.StreamFile>;
function watchMap(mappings: I.MapSource, options?: I.WatchMapOptions): I.LocalMapStream<I.BufferFile>;
// plugins
namespace I {
namespace plugin.compressor {
type Compressor = "gz" | "deflate" | "brotli" | "lzma" | "xz" | "snappy"; // TODO keyof adone.compressor ?
}
interface Stream<S, T> {
/**
* Compresses all files using the given compressor
*/
compress(this: {}, type: plugin.compressor.Compressor, options?: {
/**
* Whether to rename files, adds corresponding extname
*/
rename?: boolean,
[key: string]: any
}): this;
/**
* Decompresses all files using the given compressor
*/
decompress(type: plugin.compressor.Compressor, options?: object): this;
}
namespace plugin.archive {
type Archiver = "tar" | "zip"; // TODO keyof adone.archive ?
}
interface Stream<S, T> {
/**
* Packs all files into one archive of the given type
*/
pack(type: plugin.archive.Archiver, options?: object): this;
/**
* Unpacks the incoming files using the given archive type
*/
unpack(type: plugin.archive.Archiver, options?: object): this;
/**
* transpiles files
*/
transpile(options: object): this; // TODO adone.js.transpiler options
/**
* Deletes lines from files
*/
deleteLines(filters: RegExp | RegExp[]): this;
/**
* sets new filename
*/
rename(filename: string): this;
rename(handle: {
dirname?: string,
prefix?: string,
basename?: string,
extname?: string
}): this;
rename(handler: (handle: {
dirname: string,
basename: string,
extname: string
}) => void): this;
/**
* concats all files into one
*/
concat(file: string | { path: string }, options?: {
newLine?: string
}): this;
// flatten(options?: {
// newPath?: string,
// includeParents?: number | [number, number],
// subPath?: number | [number, number],
// }): this;
}
namespace plugin.sourcemaps {
interface WriteOptions<T> {
/**
* By default the source maps include the source code. Pass false to use the original files
*/
includeContent?: boolean;
/**
* By default a comment containing / referencing the source map is added.
* Set this to false to disable the comment (e.g. if you want to load the source maps by header)
*/
addComment?: boolean;
/**
* Sets the charset for inline source maps
*/
charset?: fs.I.Encoding;
/**
* Set the location where the source files are hosted (use this when includeContent is set to false)
*/
sourceRoot?: string | ((file: T) => string);
/**
* Function that is called for every source and receives the default source path as a parameter and the original file
*/
mapSources?(path: string, file: T): string;
mapSourcesAbsolute?: boolean;
/**
* This option allows to rename the map file.
* It takes a function that is called for every map and receives the default map path as a parameter
*/
mapFile?(file: T): string;
/**
* Set the destination path
*/
destPath?: string;
/**
* Clone options
*/
clone?: FileCloneOptions;
/**
* Specify a prefix to be prepended onto the source map URL when writing external source maps.
*/
sourceMappingURLPrefix?: string | ((file: T) => string);
/**
* The output of the function must be the full URL to the source map (in function of the output file)
*/
sourceMappingURL?(file: T): string;
}
}
interface Stream<S, T> {
sourcemapsInit(options?: {
/**
* Whether to load existing sourcemaps
*/
loadMaps?: boolean,
/**
* Whether to generate initial sourcemaps instead of using empty sourcemap
*/
identityMap?: boolean,
largeFile?: boolean
}): this;
/**
*
*
* @param dest destination directory
*/
sourcemapsWrite(dest: string, options?: plugin.sourcemaps.WriteOptions<T>): this;
sourcemapsWrite(options?: plugin.sourcemaps.WriteOptions<T>): this;
}
namespace plugin.wrap {
interface Options {
/**
* Set to explicit false value to disable automatic JSON, JSON5 and YAML parsing
*/
parse?: boolean;
escape?: RegExp;
evaluate?: RegExp;
imports?: object;
interpolate?: RegExp;
sourceURL?: string;
variable?: string;
}
interface TemplateFunctionData<T> extends Options {
file: T;
contents: object;
[custom: string]: any;
}
}
interface Stream<S, T> {
/**
* Wraps contents
*/
wrap(
template: { src: string } | string | ((data: plugin.wrap.TemplateFunctionData<T>) => string),
data?: object | ((file: T) => object),
options?: plugin.wrap.Options | ((file: T) => plugin.wrap.Options)
): this;
/**
* Replaces contents
*/
replace(search: string, replacement: string | ((search: string) => string)): this;
replace(search: RegExp, replacement: string): this;
replace(search: Array<string | RegExp>, replacement: Array<string | ((search: string) => string)>): this;
/**
* Static asset revisioning by appending content hash to filenames
*/
revisionHash(options?: {
manifest: {
path?: string,
merge?: boolean
transformer?: {
parse(str: string): any;
stringify(obj: any): string;
}
}
}): this;
/**
* Rewrite occurrences of filenames which have been renamed by revisionHash
*/
revisionHashReplace(options?: {
/**
* Use canonical Uris when replacing filePaths,
* i.e. when working with filepaths with non forward slash (/) path separators
* we replace them with forward slash.
* Default: true
*/
canonicalUris?: boolean,
/**
* Add the prefix string to each replacement
*/
prefix?: string,
/**
* Only substitute in new filenames in files of these types
* Default: ['.js', '.css', '.html', '.hbs']
*/
replaceExtensions?: string[],
/**
* Read JSON manifests written out by revisionHash
*/
manifest?: File[] | stream.CoreStream<any, File>,
/**
* Modify the name of the unreved files before using them
*/
modifyUnreved?(path: string): string,
/**
* Modify the name of the reved files before using them
*/
modifyReved?(path: string): string
}): this;
}
namespace plugin.chmod {
interface Access {
/**
* Whether to have read access
*/
read?: boolean;
/**
* Whether to have write access
*/
write?: boolean;
/**
* Whether to ahve execute access
*/
execute?: boolean;
}
interface Mode {
/**
* Owner properties
*/
owner?: Access;
/**
* Group properties
*/
group?: Access;
/**
* Others properties
*/
others?: Access;
}
}
interface Stream<S, T> {
/**
* Changes file mode
*/
chmod(mode?: number | plugin.chmod.Mode, dirMode?: number | plugin.chmod.Mode): this;
}
namespace plugin.notify {
interface Options<T> {
notifier?: object; // TODO adone.notifier
host?: string;
appName?: string;
port?: number;
/**
* Filter out files
*/
filter?(file: T): boolean;
/**
* Whether to emit an error when the stream emits an error. Default: false
*/
emitError?: boolean;
/**
* Whether to notify on the last file. Default: false
*/
onLast?: boolean;
/**
* Whether to debounce notifications. Accepts a number as timeout or debounce options
* Default: undefined
*/
debounce?: number | util.I.DebounceOptions & {
/**
* debounce timeout
*/
timeout: number
};
/**
* Object passed to the lodash template, for additional properties passed to the template
*/
templateOptions?: object;
/**
* Whether to use console notifications (print a message to console)
*/
console?: boolean;
/**
* Whether to use GUI notifications (notify-send/toaster/etc)
*/
gui?: boolean;
/**
* Notification title
*/
title?: string | ((file: T) => string);
/**
* Notification subtitle
*/
subtitle?: string | ((file: T) => string);
open?: string | ((file: T) => string);
/**
* Notification message
*/
message?: string | ((file: T) => string);
}
interface OnErrorOptions<T> extends Options<T> {
/**
* Whether to end the stream when an error occurs
*/
endStream?: boolean;
}
type OptionsArg<T, O> = string | O | (() => O);
}
interface Stream<S, T> {
/**
* Notify about passing through files
*/
notify(options?: plugin.notify.OptionsArg<T, plugin.notify.Options<T>>): this;
/**
* Notify about errors
*/
notifyError(options?: plugin.notify.OptionsArg<T, plugin.notify.OnErrorOptions<T>>): this;
}
}
namespace plugin {
namespace notify {
/**
* Creates a callback that can be used as a reporter for errors
*/
function onError<T = any>(options?: I.plugin.notify.OptionsArg<T, I.plugin.notify.OnErrorOptions<T>>): (error: T) => void;
}
}
}
}
+1728
View File
File diff suppressed because it is too large Load Diff
+553
View File
@@ -0,0 +1,553 @@
declare namespace adone {
/**
* predicates
*/
namespace is {
/**
* Checks whether the given object is `null`
*/
function _null(obj: any): boolean;
export { _null as null };
/**
* Checks whether the given object is `undefined`
*/
export function undefined(obj: any): boolean;
/**
* Checks whether the given object is nither `undefined` nor `null`
*/
export function exist(obj: any): boolean;
/**
* Checks whether the given object is either `undefined` or `null`
*/
export function nil(obj: any): boolean;
/**
* Checks whether the given object is a number
*/
export function number(obj: any): boolean;
/**
* Checks whether the given object is a finite number or a string represents a finite number
*/
export function numeral(obj: any): boolean;
/**
* Checks whether the given object is either +Infinity or -Inginity
*/
export function infinite(obj: any): boolean;
/**
* Checks whether the given object is an odd number
*/
export function odd(obj: any): boolean;
/**
* Checks whether the given object is an even number
*/
export function even(obj: any): boolean;
/**
* Checks whether the given object is a float
*/
export function float(obj: any): boolean;
/**
* Checks whether the given object is -0
*/
export function negativeZero(obj: any): boolean;
/**
* Checks whether the given object is a string
*/
export function string(obj: any): boolean;
/**
* Checks whether the given object is an empty string
*/
export function emptyString(obj: any): boolean;
/**
* Checks whether the first string is a substring of the second string from the given offset
*/
export function substring(substring: string, string: string, offset?: number): boolean;
/**
* Checks whether `string` starts from `prefix`
*/
export function prefix(prefix: string, string: string): boolean;
/**
* Checks whether `strin` ends with `prefix`
*/
export function suffix(suffix: string, string: string): boolean;
/**
* Checks whether the given object is a boolean
*/
export function boolean(obj: any): boolean;
/**
* Checks whether the given object is a string with ".json" extension or an object
*/
export function json(obj: any): boolean;
/**
* Checks whether the given object is not a primitive, i.e. neither `undefined` nor `null` nor number nor string nor boolean nor symbol)
*/
export function object(obj: any): boolean;
/**
* Checks whether the given object is a plain object, i.e. created by Object
*/
export function plainObject(obj: any): boolean;
/**
* Checks whether the given object is an adone namespace
*/
export function namespace(obj: any): boolean;
/**
* Checks whether the given object is a class
*/
function _class(obj: any): boolean;
export { _class as class };
/**
* Checks whether the given object is empty, i.e. it is an object(not a primitive), and Object.keys returns an empty array
*/
export function emptyObject(obj: any): boolean;
/**
* Checks whether the given object has the given owned property
*/
export function propertyOwned(obj: any, field: string): boolean;
/**
* Checks whether the given object has the given property
*/
export function propertyDefined(obj: any, field: string): boolean;
/**
* Checks whether the given object conforms to `schema`.
*/
export function conforms(obj: object, schema: object, strict?: boolean): boolean;
/**
* Checks whether the given object is like an array, i.e. it is not a primitive, not a function and has length
*/
export function arrayLikeObject(obj: any): boolean;
/**
* Checks whether the given array has the given value
*/
export function inArray<T>(value: T, array: any[], offset?: number, comparator?: (a: T, b: T) => boolean): boolean;
/**
* Checks whether the given objects has same type
*/
export function sameType(value: any, other: any): boolean;
/**
* Checks whether the given object is a primitive, i.e. it is either `undefined` or `null` or number or boolean or string or symbol
*/
export function primitive(obj: any): boolean;
/**
* Checks whether the given arrays are equal
*/
export function equalArrays(left: any[], right: any[]): boolean;
/**
* Checks whether the given objects are deep equal
*/
export function deepEqual(left: any, right: any): boolean;
export function shallowEqual(left: any, right: any): boolean;
/**
* Checks whether the given object is a stream, i.e. an object and has a pipe method
*/
export function stream(obj: any): boolean;
/**
* Checks whether the given object is a writable stream, i.e. a stream that has _writableState
*/
export function writableStream(obj: any): boolean;
/**
* Checks whether the given object is a readable stream, i.e. a stream that has _readableState
*/
export function readableStream(obj: any): boolean;
/**
* Checks whether the given object is a duplex stream, i.e. a readable and writable stream
*/
export function duplexStream(obj: any): boolean;
/**
* Checks whether the given object is a transform stream, i.e. a stream that has _transformState
*/
export function transformStream(obj: any): boolean;
/**
* Checks whether the given buffer is in utf8
*/
export function utf8(obj: Buffer): boolean;
/**
* Checks whether the given path is an absolute win32 path
*/
export function win32PathAbsolute(path: string): boolean;
/**
* Checks whether the given path is an absolute posix path
*/
export function posixPathAbsolute(path: string): boolean;
/**
* Checks whether the given path is an absolute path
*/
export function pathAbsolute(path: string): boolean;
/**
* Checks whether the given string is a glob
*/
export function glob(str: string): boolean;
/**
* Checks whether the given path is not a dot-file path (.secret)
*/
export function dotfile(str: string): boolean;
/**
* Checks whether the given object is a function
*/
function _function(obj: any): boolean;
export { _function as function };
/**
* Checks whether the given object is an async function
*/
export function asyncFunction(obj: any): boolean;
/**
* Checks whether the given object is a promise
*/
export function promise(obj: any): boolean;
/**
* Checks whether the given string is a valid date-string
*/
export function validDate(str: string): boolean;
/**
* Checks whether the given object is a buffer
*/
export function buffer(obj: any): boolean;
/**
* Checks whether the given object is a callback function, i.e. it has a common function name
*/
export function callback(obj: any): boolean;
/**
* Checks whether the given object is a generator function
*/
export function generator(obj: any): boolean;
/**
* Checks whether the given object is NaN
*/
export function nan(obj: any): boolean;
/**
* Checks whether the given object is a finite number
*/
export function finite(obj: any): boolean;
/**
* Checks whether the given object is an integer
*/
export function integer(obj: any): boolean;
/**
* Checks whether the given object is a safe integer
*/
export function safeInteger(obj: any): boolean;
/**
* Checks whether the given object is an array
*/
export function array(obj: any): boolean;
/**
* Checks whether the given object is a Uint8 array
*/
export function uint8Array(obj: any): boolean;
/**
* Checks whether the given object is an adone configuration
*/
export function configuration(obj: any): boolean;
/**
* Checks whether the given object is an instance of adone.math.Long
*/
export function long(obj: any): boolean;
/**
* Checks whether the given object is an instance of adone.math.BigNumber
*/
export function bigNumber(obj: any): boolean;
/**
* Checks whether the given object is an instance of adone.collection.ByteArray
*/
export function byteArray(obj: any): boolean;
/**
* Checks whether the given object is an instance of adone.datetime
*/
export function datetime(obj: any): boolean;
export function transform(obj: any): boolean;
/**
* Checks whether the given object is an adone subsystem
*/
export function subsystem(obj: any): boolean;
/**
* Checks whether the given object is an adone application
*/
export function application(obj: any): boolean;
/**
* Checks whether the given object is an adone logger
*/
export function logger(obj: any): boolean;
/**
* Checks whether the given object is a core stream
*/
export function coreStream(obj: any): boolean;
/**
* Checks whether the given object is a fast local map stream
*/
export function fastLocalMapStream(obj: any): boolean;
/**
* Checks whether the given object is a fast local stream
*/
export function fastLocalStream(obj: any): boolean;
/**
* Checks whether the given object is a fast stream
*/
export function fastStream(obj: any): boolean;
/**
* Checks whether the given object is a genesis netron
*/
export function genesisNetron(obj: any): boolean;
/**
* Checks whether the given object is a genesis peer
*/
export function genesisPeer(obj: any): boolean;
/**
* Checks whether the given object is a netron adapter
*/
export function netronAdapter(obj: any): boolean;
/**
* Checks whether the given object is a netron instance
*/
export function netron(obj: any): boolean;
/**
* Checks whether the given object is a netron peer instance
*/
export function netronPeer(obj: any): boolean;
/**
* Checks whether the given object is a netron definition
*/
export function netronDefinition(obj: any): boolean;
/**
* Checks whether the given object represents netron definitions
*/
export function netronDefinitions(obj: any): boolean;
/**
* Checks whether the given object is a netron reference
*/
export function netronReference(obj: any): boolean;
/**
* Checks whether the given object is a netron interface
*/
export function netronInterface(obj: any): boolean;
/**
* Checks whether the given object is a netron context
*/
export function netronContext(obj: any): boolean;
/**
* Checks whether the given netron interface has `name` method
*/
export function netronIMethod(netronInterface: object, name: string): boolean;
/**
* Checks whether the given netron interface has `name` property
*/
export function netronIProperty(netronInterface: any, name: string): boolean;
/**
* Checks whether the given object is a netron stub
*/
export function netronStub(obj: any): boolean;
/**
* Checks whether the given object is a netron remote stub
*/
export function netronRemoteStub(obj: any): boolean;
/**
* Checks whether the given object is a netron stream
*/
export function netronStream(obj: any): boolean;
/**
* Checks whether the given object is iterable, has defined Symbol.iterator property
*/
export function iterable(obj: any): boolean;
/**
* true if the OS is Windows
*/
export const windows: boolean;
/**
* true if the OS is Linux
*/
export const linux: boolean;
/**
* true is the OS is FreeBSD
*/
export const freebsd: boolean;
/**
* true is the os is macOS
*/
export const darwin: boolean;
/**
* true is the os is SunOS
*/
export const sunos: boolean;
/**
* Checks whether the given string is uppercased
*/
export function uppercase(str: string): boolean;
/**
* Checks whether the given string is lowercased
*/
export function lowercase(str: string): boolean;
/**
* Checks whether the given string includes only digits
*/
export function digits(str: string): boolean;
/**
* Checks whether the given string is a valid js identifier
*/
export function identifier(str: string): boolean;
/**
* Checks whether the given string is a binary extension (7z, zip, mp3, etc)
*/
export function binaryExtension(str: string): boolean;
/**
* Checks whether the given string is a path to a binary file
*/
export function binaryPath(str: string): boolean;
/**
* Checks whether the given string is an IPv4 address
*/
export function ip4(str: string): boolean;
/**
* Checks whether the given string is an IPv6 address
*/
export function ip6(str: string): boolean;
/**
* Checks whether the given object is an array buffer
*/
export function arrayBuffer(obj: any): boolean;
/**
* Checks whether the given object is an array buffer view
*/
export function arrayBufferView(obj: any): boolean;
/**
* Checks whether the given object is a date
*/
export function date(obj: any): boolean;
/**
* Checks whether the given object is an error, instance of Error
*/
export function error(obj: any): boolean;
/**
* Checks whether the given object is a map
*/
export function map(obj: any): boolean;
/**
* Checks whether the given object is a regexp
*/
export function regexp(obj: any): boolean;
/**
* Checks whether the given object is a set
*/
export function set(obj: any): boolean;
/**
* Checks whether the given object is a symbol
*/
export function symbol(obj: any): boolean;
/**
* Checks whether the given buffer a valid UTF-8 encoded text
*/
export function validUTF8(obj: Buffer): boolean;
/**
* Checks whether the given object is a vault valuable
*/
export function vaultValuable(obj: any): boolean;
/**
* Checks whether the given object is an adone task
*/
export function task(obj: any): boolean;
}
}
-118
View File
@@ -1,118 +0,0 @@
/**
* math related things
*/
export namespace math {
namespace I {
interface LowHighBits {
low: number;
high: number;
}
type Longable = math.Long | number | string | LowHighBits;
}
export class Long {
constructor(low?: number, high?: number, unsigned?: boolean);
toInt(): number;
toNumber(): number;
toString(radix?: number): string;
getHighBits(): number;
getHighBitsUnsigned(): number;
getLowBits(): number;
getLowBitsUnsigned(): number;
getNumBitsAbs(): number;
isZero(): boolean;
isNegative(): boolean;
isPositive(): boolean;
isOdd(): boolean;
isEven(): boolean;
equals(other: I.Longable): boolean;
lessThan(other: I.Longable): boolean;
lessThanOrEqual(other: I.Longable): boolean;
greaterThan(other: I.Longable): boolean;
greaterThanOrEqual(other: I.Longable): boolean;
compare(other: I.Longable): number;
negate(): Long;
add(addend: I.Longable): Long;
sub(subtrahend: I.Longable): Long;
mul(multiplier: I.Longable): Long;
div(divisor: I.Longable): Long;
mod(divisor: I.Longable): Long;
not(): Long;
and(other: I.Longable): Long;
or(other: I.Longable): Long;
xor(other: I.Longable): Long;
shl(numBits: number | Long): Long;
shr(numBits: number | Long): Long;
shru(numBits: number | Long): Long;
toSigned(): Long;
toUnsigned(): Long;
toBytes(le?: boolean): number[];
toBytesLE(): number[];
toBytesBE(): number[];
static fromInt(value: number, unsigned?: boolean): Long;
static fromNumber(value?: number, unsigned?: boolean): Long;
static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long;
static fromString(str: string, unsigned?: boolean, radix?: number): Long;
static fromString(str: string, radix?: number): Long;
static fromValue(val: I.Longable): Long;
static MIN_VALUE: Long;
static MAX_VALUE: Long;
static MAX_UNSIGNED_VALUE: Long;
static ZERO: Long;
static UZERO: Long;
static ONE: Long;
static UONE: Long;
static NEG_ONE: Long;
}
}
+759
View File
@@ -0,0 +1,759 @@
/// <reference path="./matrix.d.ts" />
/// <reference path="./simd.d.ts" />
declare namespace adone {
/**
* math related things
*/
namespace math {
namespace I {
interface LowHighBits {
/**
* The low (signed) 32 bits of the long
*/
low: number;
/**
* The high (signed) 32 bits of the long
*/
high: number;
}
type Longable = Long | number | string | LowHighBits;
}
/**
* Represents a 64 bit two's-complement integer
*/
class Long {
low: number;
high: number;
unsigned: boolean;
/**
* @param low The low (signed) 32 bits of the long
* @param high The high (signed) 32 bits of the long
* @param unsigned Whether unsigned or not, defaults to false for signed
*/
constructor(low?: number, high?: number, unsigned?: boolean);
/**
* Converts the Long to a 32 bit integer, assuming it is a 32 bit integer
*/
toInt(): number;
/**
* Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa)
*/
toNumber(): number;
/**
* Converts the Long to a string written in the specified radix
*
* @param radix Radix (2-36), 10 by default
*/
toString(radix?: number): string;
inspect(): string;
/**
* Gets the high 32 bits as a signed integer
*/
getHighBits(): number;
/**
* Gets the high 32 bits as an unsigned integer
*/
getHighBitsUnsigned(): number;
/**
* Gets the low 32 bits as a signed integer
*/
getLowBits(): number;
/**
* Gets the low 32 bits as an unsigned integer
*/
getLowBitsUnsigned(): number;
/**
* Gets the number of bits needed to represent the absolute value of this Long
*/
getNumBitsAbs(): number;
/**
* Tests if this Long's value equals zero
*/
isZero(): boolean;
/**
* Tests if this Long's value is negative
*/
isNegative(): boolean;
/**
* Tests if this Long's value is positive
*/
isPositive(): boolean;
/**
* Tests if this Long's value is odd
*/
isOdd(): boolean;
/**
* Tests if this Long's value is even
*/
isEven(): boolean;
/**
* Tests if this Long's value equals the specified's
*/
equals(other: I.Longable): boolean;
/**
* Tests if this Long's value is less than the specified's
*/
lessThan(other: I.Longable): boolean;
/**
* Tests if this Long's value is less than or equal the specified's
*/
lessThanOrEqual(other: I.Longable): boolean;
/**
* Tests if this Long's value is greater than the specified's
*/
greaterThan(other: I.Longable): boolean;
/**
* Tests if this Long's value is greater than or equal the specified's
*/
greaterThanOrEqual(other: I.Longable): boolean;
/**
* Compares this Long's value with the specified's.
* Returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater
*/
compare(other: I.Longable): number;
/**
* Negates this Long's value
*/
negate(): Long;
/**
* Returns the sum of this and the specified Long
*/
add(addend: I.Longable): Long;
/**
* Returns the difference of this and the specified Long
*/
sub(subtrahend: I.Longable): Long;
/**
* Returns the product of this and the specified Long
*/
mul(multiplier: I.Longable): Long;
/**
* Returns this Long divided by the specified
*/
div(divisor: I.Longable): Long;
/**
* Returns this Long modulo the specified
*/
mod(divisor: I.Longable): Long;
/**
* Returns the bitwise NOT of this Long
*/
not(): Long;
/**
* Returns the bitwise AND of this Long and the specified
*/
and(other: I.Longable): Long;
/**
* Returns the bitwise OR of this Long and the specifieds
*/
or(other: I.Longable): Long;
/**
* Returns the bitwise XOR of this Long and the given one
*/
xor(other: I.Longable): Long;
/**
* Returns this Long with bits shifted to the left by the given amount
*/
shl(numBits: number | Long): Long;
/**
* Returns this Long with bits arithmetically shifted to the right by the given amount
*/
shr(numBits: number | Long): Long;
/**
* Returns this Long with bits logically shifted to the right by the given amount
*/
shru(numBits: number | Long): Long;
/**
* Converts this Long to signed
*/
toSigned(): Long;
/**
* Converts this Long to unsigned
*/
toUnsigned(): Long;
/**
* Converts this Long to an array of bytes, big-endian by default
*
* @param le Whether to return an array in little-endian format
*/
toBytes(le?: boolean): number[];
/**
* Converts this Long to an array of bytes in little-endian format
*/
toBytesLE(): number[];
/**
* Converts this Long to an array of bytes in big-endian format
*/
toBytesBE(): number[];
/**
* Returns a Long representing the given 32 bit integer value
*/
static fromInt(value: number, unsigned?: boolean): Long;
/**
* Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned
*/
static fromNumber(value?: number, unsigned?: boolean): Long;
/**
* Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is assumed to use 32 bits
*/
static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long;
/**
* Returns a Long representation of the given string, written using the specified radix
*/
static fromString(str: string, unsigned?: boolean, radix?: number): Long;
/**
* Returns a Long representation of the given string, written using the specified radix
*/
static fromString(str: string, radix?: number): Long;
/**
* Converts the specified value to a Long
*/
static fromValue(val: I.Longable): Long;
/**
* Minimum signed value
*/
static MIN_VALUE: Long;
/**
* Maximum signed value
*/
static MAX_VALUE: Long;
/**
* Maximum unsigned value
*/
static MAX_UNSIGNED_VALUE: Long;
/**
* Signed zero
*/
static ZERO: Long;
/**
* Unsigned zero
*/
static UZERO: Long;
/**
* Signed one
*/
static ONE: Long;
/**
* Unsigned one
*/
static UONE: Long;
/**
* Signed negative one
*/
static NEG_ONE: Long;
}
namespace I.BigNumber {
interface BufferConvertOptions {
endian?: 1 | -1 | "big" | "little";
size?: "auto" | number;
}
}
/**
* Represents a number of arbitrary precision
*/
class BigNumber {
/**
* Creates a BigNumber from the given value, the base is 10
*/
constructor(n: number | string | BigNumber);
/**
* Creates a BigNumber from the given string and base
*/
constructor(n: string, base: number);
/**
* Converts the number to a string in the given base
*/
toString(base?: number): string;
/**
* Converts the bignum into a Number.
* If the bignum is too big you'll lose precision or you'll get ±Infinity.
*/
toNumber(): number;
/**
* Returns a new Buffer with the data from the bignum.
*/
toBuffer(opts?: I.BigNumber.BufferConvertOptions): Buffer;
/**
* Returns a new bignum containing the instance value plus n
*/
add(n: number | string | BigNumber): BigNumber;
/**
* Return a new bignum containing the instance value minus n
*/
sub(n: number | string | BigNumber): BigNumber;
/**
* Returns a new bignum containing the instance value multiplied by n
*/
mul(n: number | string | BigNumber): BigNumber;
/**
* Returns a new bignum containing the instance value integrally divided by n
*/
div(n: number | string | BigNumber): BigNumber;
/**
* Returns a new bignum with the absolute value of the instance
*/
abs(): BigNumber;
/**
* Returns a new bignum with the negative of the instance value
*/
neg(): BigNumber;
/**
* Compares the instance value to n.
*
* Returns a positive integer if > n, a negative integer if < n, and 0 if == n
*/
cmp(n: number | string | BigNumber): number;
/**
* Checks whether the instance value is greater than n (> n).
*/
gt(n: number | string | BigNumber): boolean;
/**
* Checks whether the instance value is greater than or equal to n (>= n).
*/
ge(n: number | string | BigNumber): boolean;
/**
* Checks whether the instance value is equal to n (== n).
*/
eq(n: number | string | BigNumber): boolean;
/**
* Checks whether the instance value is less than n (< n).
*/
lt(n: number | string | BigNumber): boolean;
/**
* Checks whether the instance value is less than or equal to n (<= n).
*/
le(n: number | string | BigNumber): boolean;
/**
* Returns a new bignum with the instance value bitwise AND (&)-ed with n.
*/
and(n: number | string | BigNumber): BigNumber;
/**
* Returns a new bignum with the instance value bitwise inclusive-OR (|)-ed with n.
*/
or(n: number | string | BigNumber): BigNumber;
/**
* Returns a new bignum with the instance value bitwise exclusive-OR (^)-ed with n.
*/
xor(n: number | string | BigNumber): BigNumber;
/**
* Returns a new bignum with the instance value modulo n.
*/
mod(n: number | string | BigNumber): BigNumber;
/**
* Returns a new bignum with the instance value raised to the nth power.
*/
pow(n: number | string | BigNumber): BigNumber;
/**
* Returns a new bignum with the instance value raised to the nth power modulo m.
*/
powm(n: number | string | BigNumber, m: number | string | BigNumber): BigNumber;
/**
* Computes the multiplicative inverse modulo m.
*/
invertm(m: number | string | BigNumber): BigNumber;
/**
* Returns a random number from 0 to this -1
*/
rand(): BigNumber;
/**
* Returns a random number from this to upperBound - 1
*/
rand(upperBound: number | string | BigNumber): BigNumber;
/**
* Checks whether the bignum is:
*
* - certainly prime (true)
*
* - probably prime ('maybe')
*
* - certainly composite (false)
*/
probPrime(): boolean | "maybe";
/**
* Returns the next prime number after this bignum
*/
nextPrime(): BigNumber;
/**
* Returns a new bignum that is the square root. This truncates.
*/
sqrt(): BigNumber;
/**
* Returns a new bignum that is the nth root. This truncates.
*/
root(n: number | string | BigNumber): BigNumber;
/**
* Returns a new bignum that is the 2^n multiple. Equivalent of the << operator.
*/
shiftLeft(n: number | string | BigNumber): BigNumber;
/**
* Returns a new bignum of the value integer divided by 2^n. Equivalent of the >> operator.
*/
shiftRight(n: number | string | BigNumber): BigNumber;
/**
* Returns the greatest common divisor of the current bignum with n as a new bignum.
*/
gcd(n: number | string | BigNumber): BigNumber;
/**
* Returns the Jacobi symbol (or Legendre symbol if n is prime) of the current bignum (= a) over n.
* Note that n must be odd and >= 3. 0 <= a < n.
* Returns -1 or 1
*/
jacobi(n: number | string | BigNumber): number;
/**
* Returns the number of bits used to represent the current bignum
*/
bitLength(): number;
/**
* Checks whether the bit at the given index is set
*/
isBitSet(n: number): boolean;
/**
* Generates a probable prime number of length bits.
*
* @param bits the number of bits
* @param safe If true, it will be a "safe" prime of the form p=2p'+1 where p' is also prime. Default: true
*/
static prime(bits: number, safe?: boolean): BigNumber;
/**
* Creates a new bignum from a Buffer.
*/
static fromBuffer(buf: Buffer, opts?: I.BigNumber.BufferConvertOptions): BigNumber;
/**
* One
*/
static ONE: BigNumber;
/**
* Zero
*/
static ZERO: BigNumber;
}
/**
* Represents a set of bits
*/
class BitSet {
/**
* Creates a new bitset of n bits
*/
constructor(n: number);
/**
* Creates a new bitset from a dehydrated bitset
*/
constructor(key: string);
/**
* Checks whether a bit at a specific index is set
*/
get(idx: number): boolean;
/**
* Sets a single bit.
* Returns true if set was successfull
*/
set(idx: number): boolean;
/**
* Sets a range of bits.
* Returns true if set was successfull
*/
setRange(from: number, to: number): boolean;
/**
* Unsets a single bit.
* Returns true if unset was successfull
*/
unset(idx: number): boolean;
/**
* Unsets a range of bits.
* Returns true if unset was successfull
*/
unsetRange(from: number, to: number): boolean;
/**
* Toggles a single bit
*/
toggle(idx: number): boolean;
/**
* Toggles a range of bits
*/
toggleRange(from: number, to: number): boolean;
/**
* Clears the entire bitset
*/
clear(): boolean;
/**
* Clones the set
*/
clone(): BitSet;
/**
* Turns the bitset into a comma separated string that skips leading & trailing 0 words.
* Ends with the number of leading 0s and MAX_BIT.
* Useful if you need the bitset to be an object key (eg dynamic programming).
* Can rehydrate by passing the result into the constructor
*/
dehydrate(): string;
/**
* Performs a bitwise AND on 2 bitsets or 1 bitset and 1 index.
* Both bitsets must have the same number of words, no length check is performed to prevent and overflow.
*/
and(value: number | BitSet): BitSet;
/**
* Performs a bitwise OR on 2 bitsets or 1 bitset and 1 index.
* Both bitsets must have the same number of words, no length check is performed to prevent and overflow.
*/
or(value: number | BitSet): BitSet;
/**
* Performs a bitwise XOR on 2 bitsets or 1 bitset and 1 index.
* Both bitsets must have the same number of words, no length check is performed to prevent and overflow.
*/
xor(value: number | BitSet): BitSet;
/**
* Runs a custom function on every set bit.
* Faster than iterating over the entire bitset with a get().
* If the callback returns `false` it stops iterating.
*/
forEach(callback: ((idx: number) => void | boolean)): void;
/**
* Performs a circular shift bitset by an offset
*
* @param n number of positions that the bitset that will be shifted to the right. Using a negative number will result in a left shift.
*/
circularShift(n: number): BitSet;
/**
* Gets the cardinality (count of set bits) for the entire bitset
*/
getCardinality(): number;
/**
* Gets the indices of all set bits
*/
getIndices(): number[];
/**
* Checks if one bitset is subset of another.
*/
isSubsetOf(other: BitSet): boolean;
/**
* Quickly determines if a bitset is empty
*/
isEmpty(): boolean;
/**
* Quickly determines if both bitsets are equal (faster than checking if the XOR of the two is === 0).
* Both bitsets must have the same number of words, no length check is performed to prevent and overflow.
*/
isEqual(other: BitSet): boolean;
/**
* Gets a string representation of the entire bitset, including leading 0s
*/
toString(): string;
/**
* Finds first set bit (useful for processing queues, breadth-first tree searches, etc.).
* Returns -1 if not found
*
* @param startWord the word to start with (only used internally by nextSetBit)
*/
ffs(startWord?: number): number;
/**
* Finds first zero (unset bit).
* Returns -1 if not found
*
* @param startWord the word to start with (only used internally by nextUnsetBit)
*/
ffz(startWord?: number): number;
/**
* Finds last set bit.
* Returns -1 if not found
*
* @param startWord the word to start with (only used internally by previousSetBit)
*/
fls(startWord?: number): number;
/**
* Finds last zero (unset bit).
* Returns -1 if not found
*
* @param startWord the word to start with (only used internally by previousUnsetBit)
*/
flz(startWord?: number): number;
/**
* Finds first set bit, starting at a given index.
* Return -1 if not found
*
* @param idx the starting index for the next set bit
*/
nextSetBit(idx: number): number;
/**
* Finds first unset bit, starting at a given index.
* Return -1 if not found
*
* @param idx the starting index for the next unset bit
*/
nextUnsetBit(idx: number): number;
/**
* Finds last set bit, up to a given index.
* Returns -1 if not found
*
* @param idx the starting index for the next unset bit (going in reverse)
*/
previousSetBit(idx: number): number;
/**
* Finds last unset bit, up to a given index.
* Returns -1 if not found
*/
previousUnsetBit(idx: number): number;
/**
* Converts the bitset to a math.Long number
*/
toLong(): Long;
/**
* Reads an unsigned integer of the given bits from the given offset
*
* @param bits number of bits, 1 by default
* @param offset offset, 0 by default
*/
readUInt(bits?: number, offset?: number): number;
/**
* Writes the given unsigned integer
*
* @param val integer
* @param bits number of bits to write, 1 by default
* @param offset write offset, 0 by default
*/
writeUInt(val: number, bits?: number, offset?: number): void;
/**
* Creates a new BitSet from the given math.Long number
*/
static fromLong(l: Long): BitSet;
}
/**
* Returns a random number from min to max - 1
*
* @param min lower bound, default is 0
* @param max upper bound, default is 0xFFFFFFFF
*/
function random(min?: number, max?: number): number;
}
}
File diff suppressed because it is too large Load Diff
+2053
View File
File diff suppressed because it is too large Load Diff
+113 -98
View File
@@ -1,114 +1,129 @@
/**
* promise helpers
*/
export namespace promise {
namespace I {
interface Deferred<T> {
/**
* Resolves the promise
*/
resolve(value?: T): void;
declare namespace adone {
/**
* promise helpers
*/
namespace promise {
namespace I {
interface Deferred<T = any> {
/**
* Resolves the promise
*/
resolve(value?: T): void;
/**
* Rejects the promise
*/
reject(value?: any): void;
/**
* Rejects the promise
*/
reject(value?: any): void;
promise: Promise<T>;
promise: Promise<T>;
}
}
}
/**
* Creates a promise and returns an interface to control the state
*/
export function defer<T>(): I.Deferred<T>;
/**
* Creates a promise and returns an interface to control the state
*/
export function defer(): I.Deferred;
/**
* Creates a promise that will be resolved after given milliseconds
*
* @param ms delay in milliseconds
* @param value resolving value
*/
export function delay<T>(ms: number, value?: T): Promise<T>;
/**
* Creates a promise that will be resolved after given milliseconds
*
* @param ms delay in milliseconds
* @param value resolving value
*/
export function delay<T>(ms: number, value?: T): Promise<T>;
/**
* Creates a promise that will be rejected after given milliseconds if the given promise is not fulfilled
*
* @param ms timeout in milliseconds
*/
export function timeout<T>(promise: Promise<T>, ms: number): Promise<T>;
/**
* Creates a promise that will be rejected after given milliseconds if the given promise is not fulfilled
*
* @param ms timeout in milliseconds
*/
export function timeout<T>(promise: Promise<T>, ms: number): Promise<T>;
/**
* Converts a promise to node.js style callback
*/
export function nodeify<T>(promise: Promise<T>, callback: (err?: any, value?: T) => void): Promise<T>;
/**
* Converts a promise to node.js style callback
*/
export function nodeify<T>(promise: Promise<T>, callback: (err?: any, value?: T) => void): Promise<T>;
namespace I {
interface PromisifyOptions {
/**
* Context to bind to new function
*/
context?: object;
/**
* Converts a function that returns promises to a node.js style callback function
*
* @param {Function} fn Function
* @returns {Promise} the original promise
*/
export function callbackify<R>(fn: () => Promise<R>): (callback: (err?: any, result?: R) => void) => Promise<R>;
export function callbackify<T, R>(fn: (a: T) => Promise<R>): (a: T, callback: (err?: any, result?: R) => void) => Promise<R>;
export function callbackify<T1, T2, R>(fn: (a: T1, b: T2) => Promise<R>): (a: T1, b: T2, callback: (err?: any, result?: R) => void) => Promise<R>;
export function callbackify<T1, T2, T3, R>(fn: (a: T1, b: T2, c: T3) => Promise<R>): (a: T1, b: T2, c: T3, callback: (err?: any, result?: R) => void) => Promise<R>;
export function callbackify<T1, T2, T3, T4, R>(fn: (a: T1, b: T2, c: T3, d: T4) => Promise<R>): (a: T1, b: T2, c: T3, d: T4, callback: (err?: any, result?: R) => void) => Promise<R>;
export function callbackify<R>(fn: (...args: any[]) => Promise<R>): (...args: any[]) => Promise<R>;
namespace I {
interface PromisifyOptions {
/**
* Context to bind to new function
*/
context?: object;
}
}
}
/**
* Converts a callback function to a promise-based function
*/
export function promisify<R>(fn: (callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): () => Promise<R>;
export function promisify<T, R>(fn: (a: T, callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): (a: T) => Promise<R>;
export function promisify<T>(fn: (a: T, callback: (err?: any) => void) => void, options?: I.PromisifyOptions): (a: T) => Promise<void>;
export function promisify<T1, T2, R>(fn: (a: T1, b: T2, callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2) => Promise<R>;
export function promisify<T1, T2>(fn: (a: T1, b: T2, callback: (err?: any) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2) => Promise<void>;
export function promisify<T1, T2, T3, R>(fn: (a: T1, b: T2, c: T3, callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2, c: T3) => Promise<R>;
export function promisify<T1, T2, T3>(fn: (a: T1, b: T2, c: T3, callback: (err?: any) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2, c: T3) => Promise<void>;
export function promisify<T1, T2, T3, T4, R>(
fn: (a: T1, b: T2, c: T3, d: T4, callback: (err?: any, result?: R) => void) => void,
options?: I.PromisifyOptions
): (a: T1, b: T2, c: T3, d: T4) => Promise<R>;
export function promisify<T1, T2, T3, T4>(
fn: (a: T1, b: T2, c: T3, d: T4, callback: (err?: any) => void) => void,
options?: I.PromisifyOptions
): (a: T1, b: T2, c: T3, d: T4) => Promise<void>;
export function promisify<T1, T2, T3, T4, T5, R>(
fn: (a: T1, b: T2, c: T3, d: T4, e: T5, callback: (err?: any, result?: R) => void) => void,
options?: I.PromisifyOptions
): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise<R>;
export function promisify<T1, T2, T3, T4, T5>(
fn: (a: T1, b: T2, c: T3, d: T4, callback: (err?: any) => void) => void,
options?: I.PromisifyOptions
): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise<void>;
export function promisify(fn: (...args: any[]) => void, options?: I.PromisifyOptions): (...args: any[]) => Promise<any>;
/**
* Converts a callback function to a promise-based function
*/
export function promisify<R>(fn: (callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): () => Promise<R>;
export function promisify<T, R>(fn: (a: T, callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): (a: T) => Promise<R>;
export function promisify<T>(fn: (a: T, callback: (err?: any) => void) => void, options?: I.PromisifyOptions): (a: T) => Promise<void>;
export function promisify<T1, T2, R>(fn: (a: T1, b: T2, callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2) => Promise<R>;
export function promisify<T1, T2>(fn: (a: T1, b: T2, callback: (err?: any) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2) => Promise<void>;
export function promisify<T1, T2, T3, R>(fn: (a: T1, b: T2, c: T3, callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2, c: T3) => Promise<R>;
export function promisify<T1, T2, T3>(fn: (a: T1, b: T2, c: T3, callback: (err?: any) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2, c: T3) => Promise<void>;
export function promisify<T1, T2, T3, T4, R>(
fn: (a: T1, b: T2, c: T3, d: T4, callback: (err?: any, result?: R) => void) => void,
options?: I.PromisifyOptions
): (a: T1, b: T2, c: T3, d: T4) => Promise<R>;
export function promisify<T1, T2, T3, T4>(
fn: (a: T1, b: T2, c: T3, d: T4, callback: (err?: any) => void) => void,
options?: I.PromisifyOptions
): (a: T1, b: T2, c: T3, d: T4) => Promise<void>;
export function promisify<T1, T2, T3, T4, T5, R>(
fn: (a: T1, b: T2, c: T3, d: T4, e: T5, callback: (err?: any, result?: R) => void) => void,
options?: I.PromisifyOptions
): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise<R>;
export function promisify<T1, T2, T3, T4, T5>(
fn: (a: T1, b: T2, c: T3, d: T4, e: T5, callback: (err?: any) => void) => void,
options?: I.PromisifyOptions
): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise<void>;
export function promisify(fn: (...args: any[]) => void, options?: I.PromisifyOptions): (...args: any[]) => Promise<any>;
namespace I {
interface PromisifyAllOptions {
/**
* Suffix to use for keys
*/
suffix?: string;
namespace I {
interface PromisifyAllOptions {
/**
* Suffix to use for keys
*/
suffix?: string;
/**
* Function to filter keys
*/
/**
* Function to filter keys
*/
filter?(key: string): boolean;
/**
* Context to bind to new functions
*/
context?: object;
filter?(key: string): boolean;
/**
* Context to bind to new functions
*/
context?: object;
}
}
/**
* Promisifies entire object
*/
export function promisifyAll(source: object, options?: I.PromisifyAllOptions): object;
/**
* Executes a function after promise fulfillment
*
* @returns the original promise
*/
function _finally<T>(promise: Promise<T>, onFinally?: (...args: any[]) => void): Promise<T>;
export { _finally as finally };
}
/**
* Promisifies entire object
*/
export function promisifyAll(source: object, options?: I.PromisifyAllOptions): object;
/**
* Executes a function after promise fulfillment
*
* @returns the original promise
*/
function _finally<T>(promise: Promise<T>, onFinally?: (...args: any[]) => void): Promise<T>;
export { _finally as finally };
}
+1646 -1618
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -63,3 +63,5 @@ export {
timers,
dgram,
};
export as namespace nodestd;

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