Merge pull request #12 from DefinitelyTyped/master

Update to latest
This commit is contained in:
Dolan
2018-04-19 20:12:32 +01:00
committed by GitHub
2102 changed files with 220261 additions and 64067 deletions
+5
View File
@@ -1,2 +1,7 @@
# Auto detect text files and perform LF normalization
* text=auto
# Checkout NPM package files with forced LF lineendings
# to prevent git conflicts when running npm commands
package.json text eol=lf
package-lock.json text eol=lf
+258 -121
View File
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -2,6 +2,7 @@ Please fill in this template.
- [ ] Use a meaningful title for the pull request. Include the name of the package modified.
- [ ] Test the change in your own code. (Compile and run.)
- [ ] Add or edit tests to reflect the change. (Run with `npm test`.)
- [ ] Follow the advice from the [readme](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#make-a-pull-request).
- [ ] Avoid [common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#common-mistakes).
- [ ] Run `npm run lint package-name` (or `tsc` if no `tslint.json` is present).
@@ -9,7 +10,7 @@ Please fill in this template.
Select one of these and delete the others:
If adding a new definition:
- [ ] The package does not provide its own types, and you can not add them.
- [ ] The package does not already provide its own types, or cannot have its `.d.ts` files generated via `--declaration`
- [ ] If this is for an NPM package, match the name. If not, do not conflict with the name of an NPM package.
- [ ] Create it with `dts-gen --dt`, not by basing it on an existing project.
- [ ] `tslint.json` should be present, and `tsconfig.json` should have `noImplicitAny`, `noImplicitThis`, `strictNullChecks`, and `strictFunctionTypes` set to `true`.
+3 -2
View File
@@ -105,7 +105,7 @@ If it doesn't, you can do so yourself in the comment associated with the PR.
#### Create a new package
If you are the library author, or can make a pull request to the library, [bundle types](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) instead of publishing to DefinitelyTyped.
If you are the library author and your package is written in TypeScript, [bundle the autogenerated declaration files](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) in your package instead of publishing to DefinitelyTyped.
If you are adding typings for an NPM package, create a directory with the same name.
If the package you are adding typings for is not on NPM, make sure the name you choose for it does not conflict with the name of a package on NPM.
@@ -239,7 +239,8 @@ If types are part of a web standard, they should be contributed to [TSJS-lib-gen
#### A package uses `export =`, but I prefer to use default imports. Can I change `export =` to `export default`?
If default imports work in your environment, consider turning on the [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) compiler option.
If you are using TypeScript 2.7 or later, use `--esModuleInterop` in your project.
Otherwise, if default imports work in your environment (e.g. Webpack, SystemJS, esm), consider turning on the [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) compiler option.
Do not change the type definition if it is accurate.
For an NPM package, `export =` is accurate if `node -p 'require("foo")'` is the export, and `export default` is accurate if `node -p 'require("foo").default'` is the export.
+30
View File
@@ -174,6 +174,12 @@
"sourceRepoURL": "https://github.com/MikeMcl/bignumber.js/",
"asOfVersion": "5.0.0"
},
{
"libraryName": "bingmaps",
"typingsPackageName": "bingmaps",
"sourceRepoURL": "https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions",
"asOfVersion": "2.0.15"
},
{
"libraryName": "botvs",
"typingsPackageName": "botvs",
@@ -204,6 +210,12 @@
"sourceRepoURL": "https://github.com/blakeembrey/camel-case",
"asOfVersion": "1.2.1"
},
{
"libraryName": "catalog",
"typingsPackageName": "catalog",
"sourceRepoURL": "https://github.com/interactivethings/catalog",
"asOfVersion": "3.5.0"
},
{
"libraryName": "chalk",
"typingsPackageName": "chalk",
@@ -228,6 +240,12 @@
"sourceRepoURL": "https://github.com/saltyrtc/chunked-dc-js",
"asOfVersion": "0.2.2"
},
{
"libraryName": "colors.js (colors)",
"typingsPackageName": "colors",
"sourceRepoURL": "https://github.com/Marak/colors.js",
"asOfVersion": "1.2.1"
},
{
"libraryName": "commander",
"typingsPackageName": "commander",
@@ -1134,6 +1152,12 @@
"sourceRepoURL": "https://github.com/react-ga/react-ga",
"asOfVersion": "2.3.0"
},
{
"libraryName": "react-native-collapsible",
"typingsPackageName": "react-native-collapsible",
"sourceRepoURL": "https://github.com/oblador/react-native-collapsible",
"asOfVersion": "0.11.0"
},
{
"libraryName": "react-native-elements",
"typingsPackageName": "react-native-elements",
@@ -1260,6 +1284,12 @@
"sourceRepoURL": "https://github.com/router5/router5",
"asOfVersion": "5.0.0"
},
{
"libraryName": "rrule",
"typingsPackageName": "rrule",
"sourceRepoURL": "https://github.com/jakubroztocil/rrule",
"asOfVersion": "2.2.9"
},
{
"libraryName": "rvo2",
"typingsPackageName": "rvo2",
+5 -1
View File
@@ -52,6 +52,10 @@ declare namespace AceAjax {
export interface TokenInfo {
value: string;
index?: number;
start?: number;
}
export interface Position {
@@ -575,7 +579,7 @@ declare namespace AceAjax {
* @param row The row number to retrieve from
* @param column The column number to retrieve from
**/
getTokenAt(row: number, column: number): TokenInfo;
getTokenAt(row: number, column: number): TokenInfo|null;
/**
* Sets the undo manager.
+332 -5
View File
@@ -1,6 +1,7 @@
import * as express from 'express';
import { BasicCard, Carousel, ImageDisplays, List, OptionItem, RichResponse } from './response-builder';
import { BasicCard, BrowseCarousel, BrowseItem, Carousel, ImageDisplays, List, MediaObject,
MediaResponse, MediaValues, OptionItem, RichResponse, SimpleResponse } from './response-builder';
import { ActionPaymentTransactionConfig, Cart, GooglePaymentTransactionConfig, LineItem,
Location, Order, OrderUpdate, TransactionDecision, TransactionValues } from './transactions';
@@ -30,6 +31,8 @@ export enum StandardIntents {
DELIVERY_ADDRESS,
/** App fires TRANSACTION_DECISION intent when action asks for transaction decision. */
TRANSACTION_DECISION,
/** App fires PLACE intent when action asks for place. */
PLACE,
/** App fires CONFIRMATION intent when requesting affirmation from user. */
CONFIRMATION,
/** App fires DATETIME intent when requesting date/time from user. */
@@ -45,7 +48,11 @@ export enum StandardIntents {
/** App fires REGISTER_UPDATE intent when requesting user to register for proactive updates. */
REGISTER_UPDATE,
/** App receives CONFIGURE_UPDATES intent to indicate a REGISTER_UPDATE intent should be sent. */
CONFIGURE_UPDATES
CONFIGURE_UPDATES,
/** App fires LINK intent to request user to open to link. */
LINK,
/** App receives MEDIA_STATUS intent when the MediaResponse status is updated from user. */
MEDIA_STATUS
}
/**
@@ -101,6 +108,10 @@ export enum BuiltInArgNames {
* Transactions decision argument.
*/
TRANSACTION_DECISION_VALUE,
/**
* Place value argument.
*/
PLACE,
/**
* Confirmation argument.
*/
@@ -126,7 +137,11 @@ export enum BuiltInArgNames {
*/
NEW_SURFACE,
/** Update registration value argument. */
REGISTER_UPDATE
REGISTER_UPDATE,
/** Link request result argument. */
LINK,
/** MediaStatus value argument. */
MEDIA_STATUS
}
/**
@@ -173,6 +188,14 @@ export enum SurfaceCapabilities {
* The ability to output on a screen
*/
SCREEN_OUTPUT,
/**
* The ability to output a MediaResponse
*/
MEDIA_RESPONSE_AUDIO,
/**
* The ability to open a web URL
*/
WEB_BROWSER
}
/**
@@ -223,6 +246,18 @@ export enum SignInStatus {
ERROR
}
/**
* SKU (Stock Keeping Units) types for Play Package Entitlements.
*/
export enum EntitlementSkuTypes {
/** In app purchase */
IN_APP,
/** In app subscription */
SUBSCRIPTION,
/** Paid app. */
APP
}
/**
* Possible update trigger time context frequencies.
*/
@@ -259,10 +294,15 @@ export interface UserName {
familyName: string;
}
export interface LocationCoordinates {
latitude: number;
longitude: number;
}
/**
* User's permissioned device location.
* Location information.
*/
export interface DeviceLocation {
export interface Location {
/** Coordinates: {latitude, longitude}. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */
coordinates: Coordinates;
/** Full, formatted street address. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */
@@ -273,6 +313,22 @@ export interface DeviceLocation {
city: string;
}
/**
* User's permissioned device location.
*/
export type DeviceLocation = Location;
/**
* Place information.
*/
export interface Place extends Location {
/**
* Used with Places API to fetch details of a place.
* See {@link https://developers.google.com/places/web-service/place-id}
*/
placeId: string;
}
/**
* Coordinates containing latitude and longitude
*/
@@ -309,6 +365,33 @@ export interface User {
userStorage: string;
}
/**
* Google Play Android App Package Entitlements.
*/
export interface PackageEntitlement {
/** Name of the Android app package. */
packageName: string;
/** List of entitlements for a given app. */
entitlements: Entitlement[];
}
/**
* A user's digital entitlement.
*/
export interface Entitlement {
/** Product SKU. Matches getSku() in Google Play InApp Billing API. */
sku: string;
/** The type of SKU. One of EntitlementSkuType. */
skuType: string;
/** For in app purchases/subscriptions, relevant details. */
inAppDetails: {
/** JSON data of the in app purchase. */
inAppPurchaseData: object;
/** Matches IN_APP_DATA_SIGNATURE from getPurchases() method in Play InApp Billing API. */
inAppDataSignature: object;
};
}
/**
* Actions on Google Surface.
*/
@@ -437,6 +520,16 @@ export class AssistantApp {
*/
readonly Transactions: typeof TransactionValues;
/**
* Values related to supporting {@link Media}.
*/
readonly Media: typeof MediaValues;
/**
* SKU (Stock Keeping Units) types for Play Package Entitlements.
*/
readonly EntitlementSkuTypes: typeof EntitlementSkuTypes;
/**
* Possible update trigger time context frequencies.
*/
@@ -923,6 +1016,80 @@ export class AssistantApp {
*/
askForDeliveryAddress(reason: string, dialogState?: object): express.Response | null;
/**
* Asks user to provide a geo-located place, possibly using contextual information,
* like a store near the user's location or a contact's address.
*
* Developer provides custom text prompts to tailor the request handled by Google.
*
* @example
* // For DialogflowApp:
*
* // Dialogflow Actions
* const Actions = {
* WELCOME: 'input.welcome',
* PLACE: 'get.place' // Create Dialogflow Action with actions_intent_PLACE event
* };
*
* const app = new DialogflowApp({request, response});
*
* function handleWelcome (app) {
* const requestPrompt = 'Where do you want to get picked up?';
* const permissionContext = 'To find a place to pick you up';
* app.askForPlace(requestPrompt, permissionContext);
* }
*
* function handlePlace (app) {
* const place = app.getPlace();
* if (place) {
* app.tell(`Ah, I see. You want to get picked up at ${place.address}`);
* } else {
* app.tell(`Sorry, I couldn't find where you want to get picked up`);
* }
* }
*
* const actionMap = new Map();
* actionMap.set(Actions.WELCOME, handleWelcome);
* actionMap.set(Actions.PLACE, handlePlace);
* app.handleRequest(actionMap);
*
* // For ActionsSdkApp:
* const app = new ActionsSdkApp({ request, response });
*
* function handleWelcome (app) {
* const requestPrompt = 'Where do you want to get picked up?';
* const permissionContext = 'To find a place to pick you up';
* app.askForPlace(requestPrompt, permissionContext);
* }
*
* function handlePlace (app) {
* const place = app.getPlace();
* if (place) {
* app.tell(`Ah, I see. You want to get picked up at ${place.address}`);
* } else {
* app.tell(`Sorry, I couldn't find where you want to get picked up`);
* }
* }
*
* const actionsMap = new Map();
* actionsMap.set(app.StandardIntents.MAIN, handleWelcome);
* actionsMap.set(app.StandardIntents.PLACE, handlePlace);
* app.handleRequest(actionsMap);
*
* @param requestPrompt This is the initial response by location sub-dialog.
* For example: "Where do you want to get picked up?"
* @param permissionContext This is the context for seeking permissions.
* For example: "To find a place to pick you up"
* Prompt to user: "*To find a place to pick you up*, I just need to check your location.
* Can I get that from Google?".
* @param dialogState JSON object the app uses to hold dialog state that
* will be circulated back by Assistant.
* @return HTTP response.
* @actionssdk
* @dialogflow
*/
askForPlace(requestPrompt: string, permissionContext: string, dialogState?: object): express.Response | null;
/**
* Asks user for a confirmation.
*
@@ -1131,6 +1298,72 @@ export class AssistantApp {
*/
askToRegisterDailyUpdate(intent: string, intentArguments: IntentArgument[], dialogState?: object): express.Response | null;
/**
* Requests the user to transfer to a linked out Android app intent. Using this feature
* requires verifying the linked app in the (Actions console)[console.actions.google.com].
*
* @example
* // For DialogflowApp:
*
* // Dialogflow Actions
* const WELCOME_ACTION = 'input.welcome';
* const HANDLE_LINK = 'handle.link'; // Create Dialogflow Action with actions_intent_LINK event
*
* const app = new DialogflowApp({ request, response });
*
* console.log('Request headers: ' + JSON.stringify(request.headers));
* console.log('Request body: ' + JSON.stringify(request.body));
*
* function requestLink (app) {
* app.askToDeepLink('Great! Looks like we can do that in the app.', 'Google',
* 'example://gizmos', 'com.example.gizmos', 'handle this for you');
* }
*
* function handleLink (app) {
* const linkStatus = app.getLinkStatus();
* app.tell('Okay maybe we can take care of that another time.');
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_ACTION, requestLink);
* actionMap.set(HANDLE_LINK, handleLink);
* app.handleRequest(actionMap);
*
* // For ActionsSdkApp
* const app = new ActionsSdkApp({ request, response });
*
* console.log('Request headers: ' + JSON.stringify(request.headers));
* console.log('Request body: ' + JSON.stringify(request.body));
*
* function requestLink (app) {
* app.askToDeepLink('Great! Looks like we can do that in the app.', 'Google',
* 'example://gizmos', 'com.example.gizmos', 'handle this for you.');
* }
*
* function handleLink (app) {
* const linkStatus = app.getLinkStatus();
* app.tell('Okay maybe we can take care of that another time.');
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.MAIN, requestLink);
* actionMap.set(app.StandardIntents.LINK, handleLink);
* app.handleRequest(actionMap);
*
* @param prompt A simple response to prepend to the link request.
* @param destinationName The name of the link destination.
* @param url URL of Android deep link.
* @param packageName Android app package name to which to link.
* @param reason The reason to transfer the user. This may be appended to a
* Google-specified prompt.
* @param dialogState JSON object the app uses to hold dialog state that
* will be circulated back by Assistant. Used in {@link ActionsSdkApp}.
* @return HTTP response.
* @dialogflow
* @actionssdk
*/
askToDeepLink(prompt: string | SimpleResponse | null, destinationName: string, url: string, packageName: string, reason?: string | null, dialogState?: object): express.Response | null;
/**
* Gets the {@link User} object.
* The user object contains information about the user, including
@@ -1209,6 +1442,20 @@ export class AssistantApp {
*/
getLastSeen(): Date | null;
/**
* Get the the list of all digital goods that your user purchased from
* your published Android apps. To enable this feature, see the instructions
* in the (documentation)[https://developers.google.com/actions/identity/digital-goods].
*
* @example
* const app = new DialogflowApp({request, response});
* const packageEntitlements = app.getPackageEntitlements();
*
* @return The list of digital goods purchased by the user in
* any verified Android app package. Null if no Package Entitlements present in the request.
*/
getPackageEntitlements(): PackageEntitlement[] | null;
/**
* If granted permission to device's location in previous intent, returns device's
* location (see {@link AssistantApp#askForPermissions|askForPermissions}).
@@ -1273,6 +1520,15 @@ export class AssistantApp {
*/
getTransactionDecision(): TransactionDecision;
/**
* Gets the user provided place. Use after askForPlace.
*
* @return Place information given by the user. Null if no place given.
* @dialogflow
* @actionssdk
*/
getPlace(): Place | null;
/**
* Gets confirmation decision. Use after askForConfirmation.
*
@@ -1304,6 +1560,31 @@ export class AssistantApp {
*/
getSignInStatus(): string;
/**
* Get status of MEDIA_STATUS intent.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
*
* function mediaStatusIntent (app) {
* const status = app.getMediaStatus();
* if (status === app.Media.Status.FINISHED) {
* app.tell('Oh, I see you are done playing the media!');
* } else {
* app.tell(`I don't understand the current media status: ${status}`);
* }
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.MEDIA_STATUS, mediaStatusIntent);
* app.handleRequest(actionMap);
*
* @return Result of media status intent.
* @dialogflow
* @actionssdk
*/
getMediaStatus(): MediaValues.Status | null;
/**
* Returns true if user device has a given surface capability.
*
@@ -1464,6 +1745,16 @@ export class AssistantApp {
*/
isUpdateRegistered(): boolean;
/**
* Returns the status of a link request. Used with
* {@link AssistantApp#askToDeepLink}
*
* @return The status code of the request to link.
* @dialogflow
* @actionssdk
*/
getLinkStatus(): number;
// ---------------------------------------------------------------------------
// Response Builders
// ---------------------------------------------------------------------------
@@ -1500,6 +1791,13 @@ export class AssistantApp {
*/
buildCarousel(): Carousel;
/**
* Constructs a Browse Carousel with chainable property setters.
*
* @return Constructed Browse Carousel.
*/
buildBrowseCarousel(): BrowseCarousel;
/**
* Constructs OptionItem with chainable property setters.
*
@@ -1512,6 +1810,15 @@ export class AssistantApp {
*/
buildOptionItem(key?: string, synonyms?: string | string[]): OptionItem;
/**
* Constructs BrowseItem for the Browse Carousel with chainable property setters.
*
* @param title The displayed title of the Browse Carousel card.
* @param url The URL linked to by clicking the card.
* @return Constructed BrowseItem.
*/
buildBrowseItem(title?: string, url?: string): BrowseItem;
// ---------------------------------------------------------------------------
// Transaction Builders
// ---------------------------------------------------------------------------
@@ -1552,4 +1859,24 @@ export class AssistantApp {
* @return Constructed OrderUpdate.
*/
buildOrderUpdate(orderId: string, isGoogleOrderId: boolean): OrderUpdate;
// ---------------------------------------------------------------------------
// Media Builders
// ---------------------------------------------------------------------------
/**
* Constructs Media Response with chainable property setters.
*
* @return Constructed Media Response.
*/
buildMediaResponse(): MediaResponse;
/**
* Constructs MediaObject with chainable property setters.
*
* @param name Name of media file.
* @param contentUrl Location of media file.
* @return Constructed MediaObject.
*/
buildMediaObject(name: string, contentUrl: string): MediaObject;
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for actions-on-google 1.8
// Type definitions for actions-on-google 1.10
// Project: https://github.com/actions-on-google/actions-on-google-nodejs
// Definitions by: Joel Hegg <https://github.com/joelhegg>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+298
View File
@@ -27,6 +27,53 @@ export enum ImageDisplays {
CROPPED
}
/**
* Values related to supporting media.
*/
export namespace MediaValues {
/**
* Type of the media within a MediaResponse.
*/
enum Type {
/**
* Unspecified.
*/
MEDIA_TYPE_UNSPECIFIED,
/**
* Audio stream.
*/
AUDIO
}
/**
* List of media control status' returned.
*/
enum Status {
/**
* Unspecified.
*/
UNSPECIFIED,
/**
* Finished.
*/
FINISHED
}
/**
* List of possible item types.
*/
enum ImageType {
/**
* Icon.
*/
ICON,
/**
* Large image.
*/
LARGE
}
}
/**
* Simple Response type.
*/
@@ -155,6 +202,22 @@ export class RichResponse {
*/
addBasicCard(basicCard: BasicCard): RichResponse;
/**
* Adds media to this response.
*
* @param mediaResponse MediaResponse to include in response.
* @return Returns current constructed RichResponse.
*/
addMediaResponse(mediaResponse: MediaResponse): RichResponse;
/**
* Adds a Browse Carousel to list of items.
*
* @param browseCarousel Browse Carousel to present to user
* @return Returns current constructed RichResponse.
*/
addBrowseCarousel(browseCarousel: string | BrowseCarousel): RichResponse;
/**
* Adds a single suggestion or list of suggestions to list of items.
*
@@ -325,6 +388,43 @@ export class List {
addItems(optionItems: OptionItem | OptionItem[]): List;
}
/**
* Class for initializing and constructing BrowseCarousel with chainable interface.
*/
export class BrowseCarousel {
/**
* Constructor for BrowseCarousel. Accepts optional BrowseCarousel to
* clone or list of items to copy.
*
* @param carousel Either a carousel to clone
* or an array of BrowseItem to initialize a new carousel
*/
constructor(carousel?: BrowseCarousel | BrowseItem[]);
/**
* List of 2-20 items to show in this carousel. Required.
*/
items: BrowseItem[];
/**
* Adds a single item or list of items to the carousel.
*
* @param browseItems BrowseItems to add.
* @return Returns current constructed BrowseCarousel.
*/
addItems(browseItems: BrowseItem | BrowseItem[]): BrowseCarousel;
/**
* Sets the display options for the images in this carousel.
* Use one of the image display constants. If none is chosen,
* ImageDisplays.DEFAULT will be enforced.
*
* @param option The option for displaying the image.
* @return Returns current constructed BrowseCarousel.
*/
setImageDisplay(option: ImageDisplays): BrowseCarousel;
}
/**
* Class for initializing and constructing Carousel with chainable interface.
*/
@@ -350,6 +450,120 @@ export class Carousel {
* @return Returns current constructed Carousel.
*/
addItems(optionItems: OptionItem | OptionItem[]): Carousel;
/**
* Sets the display options for the images in this carousel.
* Use one of the image display constants. If none is chosen,
* ImageDisplays.DEFAULT will be enforced.
*
* @param option The option for displaying the image.
* @return Returns current constructed Carousel.
*/
setImageDisplay(option: ImageDisplays): Carousel;
}
/**
* Class for initializing and constructing Option Items with chainable interface.
*/
export class BrowseItem {
/**
* Constructor for BrowseItem. Accepts a title and URL for the Browse Item
* card.
*
* @param title The title of the Browse Item card.
* @param url The URL of the link opened by clicking the Browse Item card.
*/
constructor(title?: string, url?: string);
/**
* Title of the browse item. Required.
*/
title: string;
/**
* Description text of the item. Optional.
*/
description?: string;
/**
* Footer text of the item. Optional.
*/
footer?: string;
/**
* Image to show on item. Optional.
*/
image?: Image;
/**
* Url to that clicking the card opens. Optional.
*/
openUrlAction?: object;
/**
* @return Returns the possible valid values for URL type hints
*/
urlTypeHints(): object;
/**
* Sets the title for this Browse Item.
*
* @param title Title to show on item.
* @return Returns current constructed BrowseItem.
*/
setTitle(title: string): BrowseItem;
/**
* Sets the description for this Browse Item.
*
* @param description Description to show on item.
* @return Returns current constructed BrowseItem.
*/
setDescription(description: string): BrowseItem;
/**
* Sets the footer for this Browse Item.
*
* @param footerText text to show on item.
* @return Returns current constructed BrowseItem.
*/
setFooter(footerText: string): BrowseItem;
/**
* Sets the image for this Browse Item.
*
* @param url Image source URL.
* @param accessibilityText Text to replace for image for accessibility.
* @param width Width of the image.
* @param height Height of the image.
* @return Returns current constructed BrowseItem.
*/
setImage(url: string, accessibilityText: string, width?: number, height?: number): BrowseItem;
/**
* Sets the Open URL action - which includes the url and possibly the typeHint
*
* @param url Image source URL.
* @param urlTypeHint One of the typeHints enumerated by this.urlTypeHints()
* @return Returns the current constructed BrowseItem
*/
setOpenUrlAction(url: string, urlTypeHint?: string): BrowseItem;
/**
* Sets the URL target of the BrowseItem card
*
* @param url Image source URL.
* @return Returns the current constructed BrowseItem
*/
setUrl(url: string): BrowseItem;
/**
* Sets the URL type hint for the BrowseItem card
*
* @param urlTypeHint One of the typeHints enumerated by this.urlTypeHints()
* @return Returns the current constructed BrowseItem
*/
setUrlTypeHint(urlTypeHint: string): BrowseItem;
}
/**
@@ -430,6 +644,90 @@ export class OptionItem {
addSynonyms(synonyms: string | string[]): OptionItem;
}
/**
* Class for initializing and constructing MediaResponse with chainable interface.
*/
export class MediaResponse {
/**
* Constructor for MediaResponse.
* @param mediaType Type of the media which defaults to MediaValues.Type.AUDIO
*/
constructor(mediaType: MediaValues.Type);
/**
* Array of MediaObject held in the MediaResponse.
*/
mediaObjects: MediaObject[];
/**
* Type of the media within this MediaResponse
*/
mediaType: MediaValues.Type;
/**
* Adds a single media file or list of media files to the cart.
*
* @param items Single or Array of MediaObject to add.
* @return Returns current constructed MediaResponse.
*/
addMediaObjects(items: MediaObject | MediaObject[]): MediaResponse;
}
/**
* Class for initializing and constructing MediaObject with chainable interface.
*/
export class MediaObject {
/**
* Constructor for MediaObject.
*
* @param name Name of the MediaObject.
* @param contentUrl URL of the MediaObject.
*/
constructor(name: string, contentUrl: string);
/**
* Name of the MediaObject.
*/
name: string;
/**
* MediaObject URL.
*/
contentUrl: string;
/**
* Description of the MediaObject.
*/
description?: string;
/**
* Large image.
*/
largeImage?: Image;
/**
* Icon image.
*/
icon?: Image;
/**
* Set the description of the item.
*
* @param description Description of the item.
* @return Returns current constructed MediaObject.
*/
setDescription(description: string): MediaObject;
/**
* Sets the image for this item.
*
* @param url Image source URL.
* @param type Type of image (LARGE or ICON).
* @return Returns current constructed MediaObject.
*/
setImage(url: string, type: MediaValues.ImageType): MediaObject;
}
/**
* Check if given text contains SSML.
* @param text Text to check.
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://msdn.microsoft.com/en-us/library/dn142571.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
// TypeScript Version: 2.6
/// <reference types="activex-office" />
/// <reference types="activex-dao" />
+414 -45
View File
@@ -1,57 +1,426 @@
let obj0 = new ActiveXObject('ADODB.Command');
// Note -- running these tests under cscript requires some ES5 polyfills
let obj1 = new ActiveXObject('ADODB.Connection');
const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
const results: T[] = [];
const enumerator = new Enumerator<T>(col);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
results.push(enumerator.item());
enumerator.moveNext();
}
return results;
};
let obj2 = new ActiveXObject('ADODB.Parameter');
let obj3 = new ActiveXObject('ADODB.Record');
let obj4 = new ActiveXObject('ADODB.Recordset');
let obj5 = new ActiveXObject('ADODB.Stream');
// open connection to an Excel file
let pathToExcelFile = 'C:\\path\\to\\excel\\file.xlsx';
let conn = new ActiveXObject('ADODB.Connection');
conn.Provider = 'Microsoft.ACE.OLEDB.12.0';
conn.ConnectionString = `Data Source="${pathToExcelFile}";Extended Properties="Excel 12.0;HDR=Yes"`;
conn.Open();
// create a Command to access the data
let cmd = new ActiveXObject('ADODB.Command');
cmd.ActiveConnection = conn;
cmd.CommandText = 'SELECT DISTINCT LastName, CityName FROM [Sheet1$]';
// get a Recordset
let rs = cmd.Execute();
// build a string from the Recordset
let s = rs.GetString(ADODB.StringFormatEnum.adClipString, -1, '\t', '\n', '(NULL)');
rs.Close();
WScript.Echo(s);
// create a disconnected recordset -- https://support.microsoft.com/en-us/help/184397/how-to-create-ado-disconnected-recordsets-in-vba-c-java
(() => {
conn = new ActiveXObject('ADODB.Connection');
conn.Open(); // pass connection details here
rs = new ActiveXObject('ADODB.Recordset');
rs.CursorLocation = ADODB.CursorLocationEnum.adUseClient;
rs.Open('SELECT * FROM Table1', conn, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockBatchOptimistic);
rs.ActiveConnection = null;
const v = rs.Fields.Item(0).Value;
conn.Close();
})();
// helper function
const toSafeArray = <T>(...items: T[]): SafeArray<T> => {
const dict = new ActiveXObject('Scripting.Dictionary');
items.forEach((x, index) => dict.Add(index, x));
return dict.Items() as SafeArray<T>;
};
const toConnectionString = (o: { [index: string]: any }) => {
o.Provider = o.Provider || 'sqloledb';
o['Data Source'] = o['Data Source'] || 'Server';
o['Integrated Security'] = o['Integrated Security'] || 'SSPI';
const parts: string[] = [];
for (const key in o) {
let val = o[key];
if (typeof val === 'string') { val = `'${val}'`; }
parts.push(`${key}=${val}`);
}
return parts.join(';');
};
const printLine = () => WScript.Echo(new Array(26).join('-'));
{
// open connection to an Excel file
const pathToExcelFile = 'C:\\path\\to\\excel\\file.xlsx';
const conn = new ActiveXObject('ADODB.Connection');
conn.ConnectionString = toConnectionString({
Provider: 'Microsoft.ACE.OLEDB.12.0',
'Data Source': pathToExcelFile,
'Extended Properties': "Excel 12.0;HDR=Yes"
});
conn.Open();
// create a Command to access the data
const cmd = new ActiveXObject('ADODB.Command');
cmd.ActiveConnection = conn;
cmd.CommandText = 'SELECT DISTINCT LastName, CityName FROM [Sheet1$]';
// get a Recordset
const rs = cmd.Execute() as ADODB.Recordset;
// build a string from the Recordset
const s = rs.GetString(ADODB.StringFormatEnum.adClipString, -1, '\t', '\n', '(NULL)');
rs.Close();
WScript.Echo(s);
}
// create a disconnected recordset -- https://support.microsoft.com/en-us/help/184397/how-to-create-ado-disconnected-recordsets-in-vba-c-java
{
const conn = new ActiveXObject('ADODB.Connection');
conn.Open(); // pass connection details here
const rs = new ActiveXObject('ADODB.Recordset');
rs.CursorLocation = ADODB.CursorLocationEnum.adUseClient;
rs.Open('SELECT * FROM Table1', conn, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockBatchOptimistic);
rs.ActiveConnection = null;
const v = rs(0).Value;
conn.Close();
}
// update with SafeArray
(() => {
{
const rs = new ActiveXObject('ADODB.Recordset');
rs.Open(); // missing connection details here
const fields = toSafeArray('FirstName', 'LastName', 'DOB');
const values = toSafeArray<any>('Plony', 'Almony', new Date(1980, 1, 1).getVarDate());
rs.Update(fields, values);
})();
rs.Close();
}
const withConnection = (initialCatalog: string, fn: (conn: ADODB.Connection) => void) => {
let conn: ADODB.Connection | null = new ActiveXObject('ADODB.Connection');
const connectionString = toConnectionString({
'Initial Catalog': initialCatalog
});
try {
conn.Open(connectionString);
fn(conn);
} catch (e) {
WScript.Echo(e.message);
} finally {
if (conn.State === ADODB.ObjectStateEnum.adStateOpen) {
conn.Close();
}
conn = null;
}
};
const withRs = (catalogOrConnection: string | ADODB.Connection, tableOrCommand: string | ADODB.Command, fn: (rs: ADODB.Recordset) => void,
type: ADODB.CursorTypeEnum = ADODB.CursorTypeEnum.adOpenUnspecified,
location: ADODB.CursorLocationEnum = ADODB.CursorLocationEnum.adUseNone,
lockType: ADODB.LockTypeEnum = ADODB.LockTypeEnum.adLockOptimistic
) => {
let connection = catalogOrConnection;
if (typeof connection === 'string') {
// expand catalog to full connection string
connection = toConnectionString({
'Initial Catalog': connection
});
}
let rs: ADODB.Recordset | null = null;
try {
if (typeof tableOrCommand === 'string') {
rs = new ActiveXObject('ADODB.Recordset');
rs.CursorLocation = location;
rs.LockType = lockType;
rs.Open(tableOrCommand, connection, type, lockType, ADODB.CommandTypeEnum.adCmdTable);
} else {
tableOrCommand.ActiveConnection = connection;
rs = tableOrCommand.Execute() as ADODB.Recordset;
}
fn(rs);
} catch (e) {
WScript.Echo(e.message);
} finally {
if (rs && rs.State === ADODB.ObjectStateEnum.adStateOpen) {
rs.Close();
}
rs = null;
}
};
const withEmployees = (fn: (rs: ADODB.Recordset) => void, type: ADODB.CursorTypeEnum) =>
withRs('Northwind', 'Employees', fn, type, ADODB.CursorLocationEnum.adUseClient);
// https://msdn.microsoft.com/en-us/library/jj249882.aspx
{
withConnection('Northwind', conn => {
withEmployees(rs => {
const FName = 'first name';
const LName = 'last name';
rs.AddNew();
rs('FirstName').Value = FName;
rs('LastName').Value = LName;
rs.Update();
WScript.Echo('New record added.');
}, ADODB.CursorTypeEnum.adOpenKeyset);
});
}
// https://msdn.microsoft.com/en-us/library/jj249434.aspx
{
withConnection('Northwind', conn => {
withEmployees(rs => {
// Set PageSize to five to display names and hire dates of five employees at a time
rs.PageSize = 5;
const pageCount = rs.PageCount;
WScript.Echo(`There are ${pageCount} pages, each containing ${rs.PageSize} or fewer records`.trim());
for (let i = 1; i <= pageCount; i++) {
rs.AbsolutePage = i;
for (let iRecord = 1; iRecord <= rs.PageSize; iRecord++) {
// First column in row contains page number on
// first record of each page. Otherwise, the column
// contains a non-breaking space.
const page = iRecord === 1 ? `Page ${i} of ${rs.PageCount}` : '';
// First and last name are in first column.
const name = `${rs('FirstName')} ${rs('LastName')}`;
// Hire date in second column.
const hireDate = new Date(rs('HireDate').Value as VarDate).toString();
// Write the row
WScript.Echo([page, name, hireDate].join('\t'));
// Get next record.
rs.MoveNext();
if (rs.EOF) { break; }
}
}
}, ADODB.CursorTypeEnum.adOpenStatic);
});
}
// https://msdn.microsoft.com/en-us/library/jj250117.aspx
{
withConnection('Northwind', conn => {
withEmployees(rs => {
WScript.Echo(['AbsolutePosition', 'Name', 'Hire Date'].join('\t'));
while (!rs.EOF) {
// First column in row contains AbsolutePosition value.
const recordCount = `${rs.AbsolutePosition} of ${rs.RecordCount}`;
// First and last name are in first column.
const name = `${rs('FirstName')} ${rs('LastName')}`;
// Hire date in second column.
const hireDate = new Date(rs('HireDate').Value as VarDate).toString();
WScript.Echo([recordCount, name, hireDate].join('\t'));
}
}, ADODB.CursorTypeEnum.adOpenStatic);
});
}
// https://msdn.microsoft.com/en-us/library/jj249824.aspx
{
withConnection('Northwind', conn => {
WScript.Echo('Enter city name, and press ENTER:');
const cityName = WScript.StdIn.ReadLine();
const cmdContact = new ActiveXObject('ADODB.Command');
cmdContact.CommandText = 'SELECT ContactName FROM Customers WHERE City = ?';
cmdContact.ActiveConnection = conn;
// create parameter and insert variable value
const param = cmdContact.CreateParameter('CityName', ADODB.DataTypeEnum.adChar, ADODB.ParameterDirectionEnum.adParamInput, 30, cityName);
cmdContact.Parameters.Append(param);
let rsContact: ADODB.Recordset | null = null;
try {
// Open a recordset using the command object
rsContact = cmdContact.Execute() as ADODB.Recordset;
while (!rsContact.EOF) {
WScript.Echo(rsContact('ContactName'));
rsContact.MoveNext();
}
} catch (e) {
WScript.Echo(e.message);
} finally {
if (rsContact && rsContact.State === ADODB.ObjectStateEnum.adStateOpen) {
rsContact.Close();
}
}
});
}
// https://msdn.microsoft.com/en-us/library/jj249056.aspx
// https://msdn.microsoft.com/en-us/library/jj249494.aspx
{
WScript.Echo('Enter royalty value, and press ENTER:');
const iRoyalty = parseInt(WScript.StdIn.ReadLine(), 10);
if (iRoyalty > -1) {
withConnection('pubs', conn => {
const cmdByRoyalty = new ActiveXObject('ADODB.Command');
cmdByRoyalty.CommandText = 'byroyalty';
cmdByRoyalty.CommandType = ADODB.CommandTypeEnum.adCmdStoredProc;
cmdByRoyalty.CommandTimeout = 15;
// The stored procedure called above is as follows:
/*
CREATE PROCEDURE byroyalty
@percentage int
AS
SELECT au_id from titleauthor
WHERE titleauthor.royaltyper = @percentage
GO
*/
const prmByRoyalty = new ActiveXObject('ADODB.Parameter');
prmByRoyalty.Type = ADODB.DataTypeEnum.adInteger;
prmByRoyalty.Size = 3;
prmByRoyalty.Direction = ADODB.ParameterDirectionEnum.adParamInput;
prmByRoyalty.Value = iRoyalty;
cmdByRoyalty.Parameters.Append(prmByRoyalty);
// open byRoyalty recordset via Command
withRs(conn, cmdByRoyalty, rsByRoyalty => {
// open authors recordset directly
withRs(conn, 'Authors', rsAuthor => {
while (!rsByRoyalty.EOF) {
// set filter
rsAuthor.Filter = `au_id='${rsByRoyalty('au_id')}'`;
// write author name
WScript.Echo(`${rsAuthor('au_fname')} ${rsAuthor('au_lname')}`);
}
// get next record
rsByRoyalty.MoveNext();
});
});
});
}
}
// https://msdn.microsoft.com/en-us/library/jj250032.aspx
{
withRs('Northwind', 'Suppliers', rsSuppliers => {
WScript.Echo(['Field Value', 'Defined Size', 'Actual Size'].join('\t'));
while (!rsSuppliers.EOF) {
const fld = rsSuppliers('CompanyName');
WScript.Echo([fld.Value, fld.DefinedSize, fld.ActualSize].join('\t'));
}
rsSuppliers.MoveNext();
});
}
// https://msdn.microsoft.com/en-us/library/jj249928.aspx
{
withRs('Northwind', 'Customers', rs => {
const loop20 = () => {
const start = new Date().getTime();
// loop through the recordset 20 times
for (let i = 0; i < 20; i++) {
rs.MoveFirst();
while (!rs.EOF) {
// do something with the record
const strTemp = rs('CompanyName').Value as string;
rs.MoveNext();
}
}
const end = new Date().getTime();
return end - start;
};
const noCache = loop20();
// cache records in groups of 30
rs.MoveFirst();
rs.CacheSize = 30;
const cache = loop20();
WScript.Echo(`No cache: ${noCache}; with cache: ${cache}`);
}, ADODB.CursorTypeEnum.adOpenUnspecified, ADODB.CursorLocationEnum.adUseClient);
}
// https://msdn.microsoft.com/en-us/library/jj249157.aspx
{
const printAuthorRecordset = (caption: string, rs: ADODB.Recordset) => {
printLine();
WScript.Echo(`**${caption}**`);
while (!rs.EOF) {
// write current row's data
const name = `${rs('au_fname')} ${rs('au_lname')}`;
WScript.Echo(name);
// get next record
rs.MoveNext;
}
};
WScript.Echo('Enter last name of author to find (e.g., Ringer) and then press ENTER:');
const lastName = WScript.StdIn.ReadLine() || '';
if (lastName.length > 0) {
withConnection('pubs', conn => {
// command object parameters
const cmdAuthor = new ActiveXObject('ADODB.Command');
cmdAuthor.CommandText = 'SELECT * FROM Authors WHERE au_name = ?';
const lastNameParameter = cmdAuthor.CreateParameter('Last Name', ADODB.DataTypeEnum.adChar, ADODB.ParameterDirectionEnum.adParamInput, 20, lastName);
cmdAuthor.Parameters.Append(lastNameParameter);
cmdAuthor.ActiveConnection = conn;
// recordset from command.execute
const rsAuthor = cmdAuthor.Execute() as ADODB.Recordset;
// recordset from connection.execute
const rsAuthor2 = conn.Execute('SELECT * FROM Authors') as ADODB.Recordset;
const errs = collectionToArray(conn.Errors);
if (errs.length > 0) {
for (const err of errs) {
WScript.Echo(err);
}
}
conn.Errors.Clear();
printAuthorRecordset('Command.Execute results', rsAuthor);
printAuthorRecordset('Connection.Execute results', rsAuthor2);
});
}
}
// https://msdn.microsoft.com/en-us/library/jj249466.aspx
{
withConnection('Northwind', conn => {
const sql = 'SELECT * FROM Customers';
withRs(conn, sql, rs => {
rs.MoveFirst();
if (rs.RecordCount === 0) {
WScript.Echo(`No records matched for '${sql}'`);
return;
}
// print headings for each field name
WScript.Echo(collectionToArray(rs.Fields).map(fld => fld.Name).join('\t'));
// JScript doesn't support multi-dimensional arrays
// so we'll convert the returned array to a single
// dimensional JScript array and then display the data.
const safeArray = rs.GetRows();
const data = new VBArray(safeArray).toArray();
const fieldCount = rs.Fields.Count;
data.forEach((cellValue, index) => {
const currentField = index % fieldCount;
// don't print tab character for first and last columns
if (currentField > 0 && currentField < fieldCount - 1) {
WScript.StdOut.Write('\t');
}
const displayValue = cellValue === null ? '-null-' : cellValue;
if (currentField === fieldCount - 1) {
WScript.StdOut.WriteLine(displayValue);
} else {
WScript.StdOut.Write(displayValue);
}
});
}, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.CursorLocationEnum.adUseClient, ADODB.LockTypeEnum.adLockOptimistic);
});
}
+219 -182
View File
@@ -2,7 +2,7 @@
// 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
// TypeScript Version: 2.6
declare namespace ADODB {
const enum ADCPROP_ASYNCTHREADPRIORITY_ENUM {
@@ -594,10 +594,19 @@ declare namespace ADODB {
adXactSyncPhaseOne = 1048576,
}
class Bookmark {
private 'ADODB.Bookmark_typekey': Bookmark;
private constructor();
}
class Command {
private 'ADODB.Command_typekey': Command;
private constructor();
ActiveConnection: Connection;
/**
* Sets or returns a String value that contains a definition for a connection if the connection is closed, or a Variant containing the current Connection object if the connection is open. Default is a null object reference.
*/
ActiveConnection: string | Connection | null;
Cancel(): void;
CommandStream: any;
CommandText: string;
@@ -605,28 +614,40 @@ declare namespace ADODB {
CommandType: CommandTypeEnum;
/**
* @param string [Name='']
* @param ADODB.DataTypeEnum [Type=0]
* @param ADODB.ParameterDirectionEnum [Direction=1]
* @param number [Size=0]
* @param Name [Name='']
* @param Type [Type=0]
* @param Direction [Direction=1]
* @param Size [Size=0]
*/
CreateParameter(Name?: string, Type?: DataTypeEnum, Direction?: ParameterDirectionEnum, Size?: number, Value?: any): Parameter;
Dialect: string;
/** @param number [Options=-1] */
Execute(RecordsAffected?: number, Parameters?: SafeArray, Options?: number): Recordset;
/**
* @param Options [Options=-1]
*
* The **RecordsAffected** parameter is meant to take a variable to be modified by reference, which is not supported by Javascript
*
* The return value is as follows:
*
* * If the **adExecuteNoRecords** option is passed in, the method will return `null`. Otherwise:
* * If the command specifies a row-returning query, then the method will return a new read-only, forward-only **Recordset** object with the results.
* * If the command isn't intended to return results (e.g. an `UPDATE` statement), a closed empty **Recordset** will be returned.
*/
Execute(RecordsAffected?: undefined, Parameters?: SafeArray, Options?: number): Recordset | null;
Name: string;
NamedParameters: boolean;
readonly Parameters: Parameters;
Prepared: boolean;
readonly Properties: Properties;
readonly State: number;
readonly State: ObjectStateEnum;
}
class Connection {
private 'ADODB.Connection_typekey': Connection;
private constructor();
Attributes: number;
/** Sum of one or more of the values in the **XactAttributeEnum** enum */
Attributes: XactAttributeEnum;
BeginTrans(): number;
Cancel(): void;
Close(): void;
@@ -638,23 +659,45 @@ declare namespace ADODB {
DefaultDatabase: string;
readonly Errors: Errors;
/** @param number [Options=-1] */
Execute(CommandText: string, RecordsAffected: any, Options?: number): Recordset;
/**
* @param Options [Options=-1]
*
* The **RecordsAffected** parameter is meant to take a variable to be modified by reference, which is not supported by Javascript
*
* The return value is as follows:
*
* * If the **adExecuteNoRecords** option is passed in, the method will return `null`. Otherwise:
* * If **CommandText** specifies a row-returning query, then the method will return a new read-only, forward-only **Recordset** object with the results
* * If **CommandText** isn't intended to return results (e.g. an `UPDATE` statement), a closed empty **Recordset** will be returned.
*/
Execute(CommandText: string, RecordsAffected?: undefined, Options?: CommandTypeEnum | ExecuteOptionEnum): Recordset | null;
IsolationLevel: IsolationLevelEnum;
Mode: ConnectModeEnum;
/**
* @param string [ConnectionString='']
* @param string [UserID='']
* @param string [Password='']
* @param number [Options=-1]
* @param ConnectionString [ConnectionString='']
* @param UserID [UserID='']
* @param Password [Password='']
* @param Options [Options=-1]
*/
Open(ConnectionString?: string, UserID?: string, Password?: string, Options?: number): void;
OpenSchema(Schema: SchemaEnum, Restrictions?: any, SchemaID?: any): Recordset;
/**
* Returns a Recordset object that contains schema information
* @param Schema Type of schema query to run
* @param Restrictions A SafeArray of query constraints; depends on the [type of the schema query](https://msdn.microsoft.com/en-us/library/jj249359.aspx)
*/
OpenSchema(Schema: SchemaEnum, Restrictions?: SafeArray<string>): Recordset;
/**
* Returns a Recordset object that contains schema information, for a provider-specific schema query type
* @param SchemaID The GUID for a provider-schema query not defined by the OLE DB specification.
*/
OpenSchema(Schema: SchemaEnum.adSchemaProviderSpecific, Restrictions: SafeArray<string>, SchemaID: string): Recordset;
readonly Properties: Properties;
Provider: string;
RollbackTrans(): void;
readonly State: number;
readonly State: ObjectStateEnum;
readonly Version: string;
}
@@ -670,13 +713,12 @@ declare namespace ADODB {
readonly SQLState: string;
}
class Errors {
private 'ADODB.Errors_typekey': Errors;
private constructor();
interface Errors {
Clear(): void;
readonly Count: number;
Item(Index: any): Error;
Refresh(): void;
(Index: any): Error;
}
class Field {
@@ -684,7 +726,9 @@ declare namespace ADODB {
private constructor();
readonly ActualSize: number;
AppendChunk(Data: any): void;
Attributes: number;
/** Sum of one or more of the values in the **FieldAttributeEnum** enum */
Attributes: FieldAttributeEnum;
DataFormat: any;
DefinedSize: number;
GetChunk(Length: number): any;
@@ -699,37 +743,37 @@ declare namespace ADODB {
Value: any;
}
class Fields {
private 'ADODB.Fields_typekey': Fields;
private constructor();
interface Fields {
/**
* @param number [DefinedSize=0]
* @param ADODB.FieldAttributeEnum [Attrib=-1]
* @param DefinedSize [DefinedSize=0]
* @param Attrib [Attrib=-1]
*/
_Append(Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum): void;
/**
* @param number [DefinedSize=0]
* @param ADODB.FieldAttributeEnum [Attrib=-1]
* @param DefinedSize [DefinedSize=0]
* @param Attrib [Attrib=-1]
*/
Append(Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum, FieldValue?: any): void;
CancelUpdate(): void;
readonly Count: number;
Delete(Index: any): void;
Item(Index: any): Field;
Delete(Index: string | number): void;
Item(Index: string | number): Field;
Refresh(): void;
/** @param ADODB.ResyncEnum [ResyncValues=2] */
/** @param ResyncValues [ResyncValues=2] */
Resync(ResyncValues?: ResyncEnum): void;
Update(): void;
(Index: string | number): Field;
}
class Parameter {
private 'ADODB.Parameter_typekey': Parameter;
private constructor();
AppendChunk(Val: any): void;
Attributes: number;
/** Sum of one or more of the values in the **ParameterAttributesEnum** enum */
Attributes: ParameterAttributesEnum;
Direction: ParameterDirectionEnum;
Name: string;
NumericScale: number;
@@ -740,28 +784,28 @@ declare namespace ADODB {
Value: any;
}
class Parameters {
private 'ADODB.Parameters_typekey': Parameters;
private constructor();
interface Parameters {
Append(Object: any): void;
readonly Count: number;
Delete(Index: any): void;
Item(Index: any): Parameter;
Delete(Index: string | number): void;
Item(Index: string | number): Parameter;
Refresh(): void;
(Index: string | number): Parameter;
}
class Properties {
private 'ADODB.Properties_typekey': Properties;
private constructor();
interface Properties {
readonly Count: number;
Item(Index: any): Property;
Item(Index: string | number): Property;
Refresh(): void;
(Index: string | number): Property;
}
class Property {
private 'ADODB.Property_typekey': Property;
private constructor();
Attributes: number;
/** Sum of one or more of the values in the **PropertyAttributesEnum** enum */
Attributes: PropertyAttributesEnum;
readonly Name: string;
readonly Type: DataTypeEnum;
Value: any;
@@ -770,23 +814,27 @@ declare namespace ADODB {
class Record {
private 'ADODB.Record_typekey': Record;
private constructor();
ActiveConnection: any;
/**
* Sets or returns a String value that contains a definition for a connection if the connection is closed, or a Variant containing the current Connection object if the connection is open. Default is a null object reference.
*/
ActiveConnection: string | Connection | null;
Cancel(): void;
Close(): void;
/**
* @param string [Source='']
* @param string [Destination='']
* @param string [UserName='']
* @param string [Password='']
* @param ADODB.CopyRecordOptionsEnum [Options=-1]
* @param boolean [Async=false]
* @param Source [Source='']
* @param Destination [Destination='']
* @param UserName [UserName='']
* @param Password [Password='']
* @param Options [Options=-1]
* @param Async [Async=false]
*/
CopyRecord(Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: CopyRecordOptionsEnum, Async?: boolean): string;
/**
* @param string [Source='']
* @param boolean [Async=false]
* @param Source [Source='']
* @param Async [Async=false]
*/
DeleteRecord(Source?: string, Async?: boolean): void;
readonly Fields: Fields;
@@ -794,137 +842,174 @@ declare namespace ADODB {
Mode: ConnectModeEnum;
/**
* @param string [Source='']
* @param string [Destination='']
* @param string [UserName='']
* @param string [Password='']
* @param ADODB.MoveRecordOptionsEnum [Options=-1]
* @param boolean [Async=false]
* @param Source [Source='']
* @param Destination [Destination='']
* @param UserName [UserName='']
* @param Password [Password='']
* @param Options [Options=-1]
* @param Async [Async=false]
*/
MoveRecord(Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: MoveRecordOptionsEnum, Async?: boolean): string;
/**
* @param ADODB.ConnectModeEnum [Mode=0]
* @param ADODB.RecordCreateOptionsEnum [CreateOptions=-1]
* @param ADODB.RecordOpenOptionsEnum [Options=-1]
* @param string [UserName='']
* @param string [Password='']
* Source may be:
* * A URL. If the protocol for the URL is http, then the Internet Provider will be invoked by default. If the URL points to a node that contains an executable script (such as an .ASP page), then a Record containing the source rather than the executed contents is opened by default. Use the Options argument to modify this behavior.
* * A Record object. A Record object opened from another Record will clone the original Record object.
* * A Command object. The opened Record object represents the single row returned by executing the Command. If the results contain more than a single row, the contents of the first row are placed in the record and an error may be added to the Errors collection.
* * A SQL SELECT statement. The opened Record object represents the single row returned by executing the contents of the string. If the results contain more than a single row, the contents of the first row are placed in the record and an error may be added to the Errors collection.
* * A table name.
*
* @param Mode [Mode=0]
* @param CreateOptions [CreateOptions=-1]
* @param Options [Options=-1]
* @param UserName [UserName='']
* @param Password [Password='']
*/
Open(Source: any, ActiveConnection: any, Mode?: ConnectModeEnum, CreateOptions?: RecordCreateOptionsEnum, Options?: RecordOpenOptionsEnum, UserName?: string, Password?: string): void;
Open(Source?: string | Record | Recordset | Command, ActiveConnection?: string | Connection, Mode?: ConnectModeEnum, CreateOptions?: RecordCreateOptionsEnum, Options?: RecordOpenOptionsEnum, UserName?: string, Password?: string): void;
readonly ParentURL: string;
readonly Properties: Properties;
readonly RecordType: RecordTypeEnum;
Source: any;
Source: string | Recordset | Command;
readonly State: ObjectStateEnum;
}
class Recordset {
private 'ADODB.Recordset_typekey': Recordset;
private constructor();
interface Recordset {
_xClone(): Recordset;
/** @param ADODB.AffectEnum [AffectRecords=3] */
/** @param AffectRecords [AffectRecords=3] */
_xResync(AffectRecords?: AffectEnum): void;
/**
* @param string [FileName='']
* @param ADODB.PersistFormatEnum [PersistFormat=0]
* @param FileName [FileName='']
* @param PersistFormat [PersistFormat=0]
*/
_xSave(FileName?: string, PersistFormat?: PersistFormatEnum): void;
AbsolutePage: PositionEnum;
AbsolutePosition: PositionEnum;
readonly ActiveCommand: any;
ActiveConnection: any;
AddNew(FieldList?: any, Values?: any): void;
readonly ActiveCommand?: Command;
/**
* Sets or returns a String value that contains a definition for a connection if the connection is closed, or a Variant containing the current Connection object if the connection is open. Default is a null object reference.
*/
ActiveConnection: string | Connection | null;
AddNew(): void;
AddNew(Fields: SafeArray<string | number>, Values: SafeArray): void;
AddNew(Field: string, Value: any): void;
readonly BOF: boolean;
Bookmark: any;
Bookmark: Bookmark;
CacheSize: number;
Cancel(): void;
/** @param ADODB.AffectEnum [AffectRecords=3] */
/** @param AffectRecords [AffectRecords=3] */
CancelBatch(AffectRecords?: AffectEnum): void;
CancelUpdate(): void;
/** @param ADODB.LockTypeEnum [LockType=-1] */
/** @param LockType [LockType=-1] */
Clone(LockType?: LockTypeEnum): Recordset;
Close(): void;
Collect(Index: any): any;
CompareBookmarks(Bookmark1: any, Bookmark2: any): CompareEnum;
CompareBookmarks(Bookmark1: Bookmark, Bookmark2: Bookmark): CompareEnum;
CursorLocation: CursorLocationEnum;
CursorType: CursorTypeEnum;
DataMember: string;
DataSource: any;
/** @param ADODB.AffectEnum [AffectRecords=1] */
/** @param AffectRecords [AffectRecords=1] */
Delete(AffectRecords?: AffectEnum): void;
readonly EditMode: EditModeEnum;
readonly EOF: boolean;
readonly Fields: Fields;
Filter: any;
/**
* @param number [SkipRecords=0]
* @param ADODB.SearchDirectionEnum [SearchDirection=1]
* Sets or returns one of the following:
* * Criteria string — a string made up of one or more individual clauses concatenated with AND or OR operators.
* * Array of bookmarks — an array of unique bookmark values that point to records in the Recordset object.
* * A FilterGroupEnum value
*/
Find(Criteria: string, SkipRecords?: number, SearchDirection?: SearchDirectionEnum, Start?: any): void;
/** @param number [Rows=-1] */
GetRows(Rows?: number, Start?: any, Fields?: any): any;
Filter: string | SafeArray<Bookmark> | FilterGroupEnum;
/**
* @param ADODB.StringFormatEnum [StringFormat=2]
* @param number [NumRows=-1]
* @param string [ColumnDelimeter='']
* @param string [RowDelimeter='']
* @param string [NullExpr='']
* @param SkipRecords [SkipRecords=0]
* @param SearchDirection [SearchDirection=1]
*/
Find(Criteria: string, SkipRecords?: number, SearchDirection?: SearchDirectionEnum, Start?: Bookmark): void;
/** @param Rows [Rows=-1] */
GetRows(Rows?: number, Start?: string | Bookmark | BookmarkEnum, Fields?: string | SafeArray<string | number>): SafeArray;
/**
* @param StringFormat [StringFormat=2]
* @param NumRows [NumRows=-1]
* @param ColumnDelimeter [ColumnDelimeter='']
* @param RowDelimeter [RowDelimeter='']
* @param NullExpr [NullExpr='']
*/
GetString(StringFormat?: StringFormatEnum, NumRows?: number, ColumnDelimeter?: string, RowDelimeter?: string, NullExpr?: string): string;
Index: string;
LockType: LockTypeEnum;
MarshalOptions: MarshalOptionsEnum;
MaxRecords: number;
Move(NumRecords: number, Start?: any): void;
Move(NumRecords: number, Start?: string | Bookmark | BookmarkEnum): void;
MoveFirst(): void;
MoveLast(): void;
MoveNext(): void;
MovePrevious(): void;
NextRecordset(RecordsAffected?: any): Recordset;
/** Since Javascript doesn't support byref parameters, the RecordsAffected parameter cannot be used */
NextRecordset(): Recordset;
/**
* @param ADODB.CursorTypeEnum [CursorType=-1]
* @param ADODB.LockTypeEnum [LockType=-1]
* @param number [Options=-1]
* @param CursorType [CursorType=-1]
* @param LockType [LockType=-1]
* @param Options [Options=-1]
*/
Open(Source: any, ActiveConnection: any, CursorType?: CursorTypeEnum, LockType?: LockTypeEnum, Options?: number): void;
Open(Source: Command, ActiveConnection: null, CursorType?: CursorTypeEnum, LockType?: LockTypeEnum, Options?: CommandTypeEnum | ExecuteOptionEnum): void;
Open(Source?: Stream): void;
/**
* @param CursorType [CursorType=-1]
* @param LockType [LockType=-1]
* @param Options [Options=-1]
*/
Open(Source: string, ActiveConnection: string | Connection, CursorType?: CursorTypeEnum, LockType?: LockTypeEnum, Options?: CommandTypeEnum | ExecuteOptionEnum): void;
readonly PageCount: number;
PageSize: number;
readonly Properties: Properties;
readonly RecordCount: number;
/** @param number [Options=-1] */
/** @param Options [Options=-1] */
Requery(Options?: number): void;
/**
* @param ADODB.AffectEnum [AffectRecords=3]
* @param ADODB.ResyncEnum [ResyncValues=2]
* @param AffectRecords [AffectRecords=3]
* @param ResyncValues [ResyncValues=2]
*/
Resync(AffectRecords?: AffectEnum, ResyncValues?: ResyncEnum): void;
/** @param ADODB.PersistFormatEnum [PersistFormat=0] */
Save(Destination: any, PersistFormat?: PersistFormatEnum): void;
/** @param PersistFormat [PersistFormat=0] */
Save(Destination: string | Stream, PersistFormat?: PersistFormatEnum): void;
/** @param ADODB.SeekEnum [SeekOption=1] */
/**
* @param SeekOption [SeekOption=1]
*
* For a single-column index, pass in a single value to seek in the column of the index
*
* For a multi-column index, pass in a SafeArray containing the multiple values to seek in the columns of the index.
*/
Seek(KeyValues: any, SeekOption?: SeekEnum): void;
Sort: string;
Source: any;
readonly State: number;
Source: string | Command;
readonly State: ObjectStateEnum;
readonly Status: number;
StayInSync: boolean;
Supports(CursorOptions: CursorOptionEnum): boolean;
Update(Fields?: string | SafeArray<string | number>, Values?: any): void;
Update(): void;
Update(Fields: SafeArray<string | number>, Values: SafeArray): void;
Update(Field: string, Value: any): void;
/** @param ADODB.AffectEnum [AffectRecords=3] */
/** @param AffectRecords [AffectRecords=3] */
UpdateBatch(AffectRecords?: AffectEnum): void;
(FieldIndex: string | number): Field;
}
class Stream {
@@ -934,7 +1019,7 @@ declare namespace ADODB {
Charset: string;
Close(): void;
/** @param number [CharNumber=-1] */
/** @param CharNumber [CharNumber=-1] */
CopyTo(DestStream: Stream, CharNumber?: number): void;
readonly EOS: boolean;
Flush(): void;
@@ -943,21 +1028,21 @@ declare namespace ADODB {
Mode: ConnectModeEnum;
/**
* @param ADODB.ConnectModeEnum [Mode=0]
* @param ADODB.StreamOpenOptionsEnum [Options=-1]
* @param string [UserName='']
* @param string [Password='']
* @param Mode [Mode=0]
* @param Options [Options=-1]
* @param UserName [UserName='']
* @param Password [Password='']
*/
Open(Source: any, Mode?: ConnectModeEnum, Options?: StreamOpenOptionsEnum, UserName?: string, Password?: string): void;
Open(Source?: string | Record, Mode?: ConnectModeEnum, Options?: StreamOpenOptionsEnum, UserName?: string, Password?: string): void;
Position: number;
/** @param number [NumBytes=-1] */
/** @param NumBytes [NumBytes=-1] */
Read(NumBytes?: number): any;
/** @param number [NumChars=-1] */
/** @param NumChars [NumChars=-1] */
ReadText(NumChars?: number): string;
/** @param ADODB.SaveOptionsEnum [Options=1] */
/** @param Options [Options=1] */
SaveToFile(FileName: string, Options?: SaveOptionsEnum): void;
SetEOS(): void;
readonly Size: number;
@@ -966,7 +1051,7 @@ declare namespace ADODB {
Type: StreamTypeEnum;
Write(Buffer: any): void;
/** @param ADODB.StreamWriteEnum [Options=0] */
/** @param Options [Options=0] */
WriteText(Data: string, Options?: StreamWriteEnum): void;
}
@@ -1009,60 +1094,23 @@ declare namespace ADODB {
}
interface ActiveXObject {
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<K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
on(obj: ADODB.Connection, event: 'BeginTransComplete', argNames: ['TransactionLevel', 'pError', 'adStatus', 'pConnection'], handler: (this: ADODB.Connection, parameter: {readonly TransactionLevel: number, readonly pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, readonly pConnection: ADODB.Connection}) => void): void;
on(obj: ADODB.Connection, event: 'CommitTransComplete' | 'ConnectComplete' | 'InfoMessage' | 'RollbackTransComplete', argNames: ['pError', 'adStatus', 'pConnection'], handler: (this: ADODB.Connection, parameter: {readonly pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, readonly pConnection: ADODB.Connection}) => void): void;
on(obj: ADODB.Connection, event: 'Disconnect', argNames: ['adStatus', 'pConnection'], handler: (this: ADODB.Connection, parameter: {adStatus: ADODB.EventStatusEnum, readonly pConnection: ADODB.Connection}) => void): void;
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;
}
interface ActiveXObjectNameMap {
@@ -1073,14 +1121,3 @@ interface ActiveXObjectNameMap {
'ADODB.Recordset': ADODB.Recordset;
'ADODB.Stream': ADODB.Stream;
}
interface EnumeratorConstructor {
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>;
}
+2 -1
View File
@@ -1,6 +1,7 @@
{
"extends": "dtslint/dt.json",
"rules": {
"no-const-enum": false
"no-const-enum": false,
"max-line-length": false
}
}
File diff suppressed because it is too large Load Diff
+335
View File
@@ -0,0 +1,335 @@
// Type definitions for Microsoft ADO Extensions 6.0 for DDL and Security - ADOX 6.0
// Project: https://docs.microsoft.com/en-us/sql/ado/reference/adox-api/adox-object-model
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
/// <reference types="activex-adodb" />
declare namespace ADOX {
const enum ActionEnum {
adAccessDeny = 3,
adAccessGrant = 1,
adAccessRevoke = 4,
adAccessSet = 2,
}
const enum AllowNullsEnum {
adIndexNullsAllow = 0,
adIndexNullsDisallow = 1,
adIndexNullsIgnore = 2,
adIndexNullsIgnoreAny = 4,
}
const enum ColumnAttributesEnum {
adColFixed = 1,
adColNullable = 2,
}
const enum InheritTypeEnum {
adInheritBoth = 3,
adInheritContainers = 2,
adInheritNone = 0,
adInheritNoPropogate = 4,
adInheritObjects = 1,
}
const enum KeyTypeEnum {
adKeyForeign = 2,
adKeyPrimary = 1,
adKeyUnique = 3,
}
const enum ObjectTypeEnum {
adPermObjColumn = 2,
adPermObjDatabase = 3,
adPermObjProcedure = 4,
adPermObjProviderSpecific = -1,
adPermObjTable = 1,
adPermObjView = 5,
}
const enum RightsEnum {
adRightCreate = 16384,
adRightDelete = 65536,
adRightDrop = 256,
adRightExclusive = 512,
adRightExecute = 536870912,
adRightFull = 268435456,
adRightInsert = 32768,
adRightMaximumAllowed = 33554432,
adRightNone = 0,
adRightRead = -2147483648,
adRightReadDesign = 1024,
adRightReadPermissions = 131072,
adRightReference = 8192,
adRightUpdate = 1073741824,
adRightWithGrant = 4096,
adRightWriteDesign = 2048,
adRightWriteOwner = 524288,
adRightWritePermissions = 262144,
}
const enum RuleEnum {
adRICascade = 1,
adRINone = 0,
adRISetDefault = 3,
adRISetNull = 2,
}
const enum SortOrderEnum {
adSortAscending = 1,
adSortDescending = 2,
}
class Catalog {
private constructor();
private 'ADOX.Catalog_typekey': Catalog;
/** Can be set to a Connection object or a string. Returns the active Connection object, or `null` */
ActiveConnection: string | ADODB.Connection | null;
/**
* The **Create** method creates and opens a new ADO Connection to the data source specified in _ConnectString_. If successful, the new **Connection** object is assigned to the **ActiveConnection** property.
*
* An error will occur if the provider does not support creating new catalogs.
*
* @param ConnectString Connection string
*/
Create(ConnectString: string): void;
/**
* @param ObjectTypeId Specifies the GUID for a provider object type not defined by the OLE DB specification
*/
GetObjectOwner(ObjectName: string, ObjectType: ObjectTypeEnum.adPermObjProviderSpecific, ObjectTypeId: any): string;
GetObjectOwner(ObjectName: string, ObjectType: ObjectTypeEnum): string;
readonly Groups: Groups;
readonly Procedures: Procedures;
/**
* @param UserName Specifies the name of the **User** or **Group** to own the object
* @param ObjectTypeId Specifies the GUID for a provider object type that is not defined by the OLE DB specification
*/
SetObjectOwner(ObjectName: string, ObjectType: ObjectTypeEnum.adPermObjProviderSpecific, UserName: string, ObjectTypeId: any): void;
SetObjectOwner(ObjectName: string, ObjectType: ObjectTypeEnum, UserName: string): void;
readonly Tables: Tables;
readonly Users: Users;
readonly Views: Views;
}
class Column {
private constructor();
private 'ADOX.Column_typekey': Column;
Attributes: ColumnAttributesEnum;
DefinedSize: number;
Name: string;
NumericScale: number;
ParentCatalog: Catalog;
Precision: number;
readonly Properties: ADODB.Properties;
RelatedColumn: string;
SortOrder: SortOrderEnum;
Type: ADODB.DataTypeEnum;
}
interface Columns {
/**
* @param Type [Type=202]
* @param DefinedSize [DefinedSize=0]
*/
Append(Item: Column | string, Type?: ADODB.DataTypeEnum, DefinedSize?: number): void;
readonly Count: number;
Delete(Item: string | number): void;
Item(Item: string | number): Column;
Refresh(): void;
(Item: string | number): Column;
}
class Group {
private constructor();
private 'ADOX.Group_typekey': Group;
/**
* @param Name Specifies the name of the object for which to set permissions. Pass `null` if you want to get the permissions for the object container.
* @param ObjectTypeId Specifies the GUID for a provider object type not defined by the OLE DB specification.
*/
GetPermissions(Name: string | null, ObjectType: ObjectTypeEnum.adPermObjProviderSpecific, ObjectTypeId: any): RightsEnum;
GetPermissions(Name: string | null, ObjectType: ObjectTypeEnum): RightsEnum;
Name: string;
ParentCatalog: Catalog;
readonly Properties: ADODB.Properties;
/**
* @param Rights A bitmask of one or more of the **RightsEnum** constants, that indicates the rights to set.
* @param Inherit [Inherit=0]
* @param ObjectTypeId Specifies the GUID for a provider object type not defined by the OLE DB specification.
*/
SetPermissions(Name: string, ObjectType: ObjectTypeEnum.adPermObjProviderSpecific, Action: ActionEnum, Rights: RightsEnum, Inherit: InheritTypeEnum, ObjectTypeId: any): void;
SetPermissions(Name: string, ObjectType: ObjectTypeEnum, Action: ActionEnum, Rights: RightsEnum, Inherit?: InheritTypeEnum): void;
readonly Users: Users;
}
interface Groups {
Append(Item: Group | string): void;
readonly Count: number;
Delete(Item: string | number): void;
Item(Item: string | number): Group;
Refresh(): void;
(Item: string | number): Group;
}
class Index {
private constructor();
private 'ADOX.Index_typekey': Index;
Clustered: boolean;
readonly Columns: Columns;
IndexNulls: AllowNullsEnum;
Name: string;
PrimaryKey: boolean;
readonly Properties: ADODB.Properties;
Unique: boolean;
}
// tslint:disable-next-line:interface-name
interface Indexes {
Append(Item: Index | string, Columns?: string | SafeArray<string>): void; // is this actually two overloads, one with [Index] and one with [string,string | SafeArray<string>]?
readonly Count: number;
Delete(Item: string | number): void;
Item(Item: string | number): Index;
Refresh(): void;
(Item: string | number): Index;
}
class Key {
private constructor();
private 'ADOX.Key_typekey': Key;
readonly Columns: Columns;
DeleteRule: RuleEnum;
Name: string;
RelatedTable: string;
Type: KeyTypeEnum;
UpdateRule: RuleEnum;
}
interface Keys {
/**
* @param Type [Type=1]
* @param RelatedTable [RelatedTable='']
* @param RelatedColumn [RelatedColumn='']
*/
Append(Item: Key | string, Type?: KeyTypeEnum, Column?: string | SafeArray<string>, RelatedTable?: string, RelatedColumn?: string): void;
readonly Count: number;
Delete(Item: string | number): void;
Item(Item: string | number): Key;
Refresh(): void;
(Item: string | number): Key;
}
class Procedure {
private constructor();
private 'ADOX.Procedure_typekey': Procedure;
Command: ADODB.Command;
readonly DateCreated: VarDate | null;
readonly DateModified: VarDate | null;
readonly Name: string;
}
interface Procedures {
Append(Name: string, Command: ADODB.Command): void;
readonly Count: number;
Delete(Item: string | number): void;
Item(Item: string | number): Procedure;
Refresh(): void;
(Item: string | number): Procedure;
}
class Table {
private constructor();
private 'ADOX.Table_typekey': Table;
readonly Columns: Columns;
readonly DateCreated: VarDate;
readonly DateModified: VarDate;
readonly Indexes: Indexes;
readonly Keys: Keys;
Name: string;
ParentCatalog: Catalog;
readonly Properties: ADODB.Properties;
readonly Type: string;
}
interface Tables {
Append(Item: Table | string): void;
readonly Count: number;
Delete(Item: string | number): void;
Item(Item: string | number): Table;
Refresh(): void;
(Item: string | number): Table;
}
class User {
private constructor();
private 'ADOX.User_typekey': User;
ChangePassword(OldPassword: string, NewPassword: string): void;
/**
* @param Name Specifies the name of the object for which to set permissions. Pass `null` if you want to get the permissions for the object container.
* @param ObjectTypeId Specifies the GUID for a provider object type not defined by the OLE DB specification.
*/
GetPermissions(Name: string | null, ObjectType: ObjectTypeEnum.adPermObjProviderSpecific, ObjectTypeId: any): RightsEnum;
GetPermissions(Name: string | null, ObjectType: ObjectTypeEnum): RightsEnum;
readonly Groups: Groups;
Name: string;
ParentCatalog: Catalog;
readonly Properties: ADODB.Properties;
/**
* @param Rights A bitmask of one or more of the **RightsEnum** constants, that indicates the rights to set.
* @param Inherit [Inherit=0]
* @param ObjectTypeId Specifies the GUID for a provider object type not defined by the OLE DB specification.
*/
SetPermissions(Name: string, ObjectType: ObjectTypeEnum.adPermObjProviderSpecific, Action: ActionEnum, Rights: RightsEnum, Inherit: InheritTypeEnum, ObjectTypeId: any): void;
SetPermissions(Name: string, ObjectType: ObjectTypeEnum, Action: ActionEnum, Rights: RightsEnum, Inherit?: InheritTypeEnum): void;
}
interface Users {
/** @param Password [Password=''] */
Append(Item: User | string, Password?: string): void;
readonly Count: number;
Delete(Item: string | number): void;
Item(Item: string | number): User;
Refresh(): void;
(Item: string | number): User;
}
class View {
private constructor();
private 'ADOX.View_typekey': View;
Command: ADODB.Command;
readonly DateCreated: VarDate;
readonly DateModified: VarDate;
readonly Name: string;
}
interface Views {
Append(Name: string, Command: ADODB.Command): void;
readonly Count: number;
Delete(Item: string | number): void;
Item(Item: string | number): View;
Refresh(): void;
(Item: string | number): View;
}
}
interface ActiveXObject {
new<K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
}
interface ActiveXObjectNameMap {
'ADOX.Catalog': ADOX.Catalog;
'ADOX.Column': ADOX.Column;
'ADOX.Group': ADOX.Group;
'ADOX.Index': ADOX.Index;
'ADOX.Key': ADOX.Key;
'ADOX.Table': ADOX.Table;
'ADOX.User': ADOX.User;
}
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+22
View File
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-adox-tests.ts"
]
}
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "dtslint/dt.json",
"rules": {
"no-const-enum": false,
"max-line-length": false
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://msdn.microsoft.com/en-us/library/jj602751.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// TypeScript Version: 2.6
/// <reference types="activex-adodb" />
/// <reference types="activex-msxml2" />
+21 -18
View File
@@ -11,6 +11,9 @@ const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
return results;
};
WScript.Echo('Hello, world');
WScript.Quit();
// source -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms630826(v=vs.85).aspx
{
const cd = new ActiveXObject('WIA.CommonDialog');
@@ -51,7 +54,7 @@ const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
{
const dev = cd.ShowSelectDevice();
if (dev) {
collectionToArray(dev.Properties).forEach(p => {
for (const p of collectionToArray(dev.Properties)) {
let s = `${p.Name} (${p.PropertyID}) = `;
if (p.IsVector) {
s += '[vector of data]';
@@ -84,7 +87,7 @@ const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
}
WScript.Echo(s);
});
}
}
}
@@ -112,7 +115,7 @@ const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
{
const img = cd.ShowAcquireImage();
if (img) {
collectionToArray(img.Properties).forEach(p => {
for (const p of collectionToArray(img.Properties)) {
let contents = '';
if (p.IsVector) {
contents = '[vector data not emitted]';
@@ -124,7 +127,7 @@ const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
contents = p.Value;
}
WScript.Echo(`${p.Name} (${p.PropertyID}) = ${contents}`);
});
}
}
}
@@ -133,12 +136,12 @@ const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
const dev = cd.ShowSelectDevice();
if (dev) {
const actionEvent = WIA.WiaEventFlag.ActionEvent;
collectionToArray(dev.Events).forEach(e => {
for (const e of collectionToArray(dev.Events)) {
const msg = (e.Type & actionEvent) === actionEvent ?
`${e.Name} is an Action event` :
`${e.Name} is not an Action event`;
WScript.Echo(msg);
});
}
}
}
@@ -208,14 +211,14 @@ Frame count = ${img.FrameCount}}
// Create an imageprocess object and enumerate filters
{
const ip = new ActiveXObject('WIA.ImageProcess');
collectionToArray(ip.FilterInfos).forEach(fi => {
for (const fi of collectionToArray(ip.FilterInfos)) {
const s = [
fi.Name,
new Array(51).join('='),
fi.Description
].join('\n');
WScript.Echo(s);
});
}
}
// Create an imageprocess object and create one of each available filter
@@ -269,11 +272,11 @@ Frame count = ${img.FrameCount}}
WScript.Echo(s);
};
collectionToArray(ip.FilterInfos).forEach(fi => {
for (const fi of collectionToArray(ip.FilterInfos)) {
ip.Filters.Add(fi.FilterID);
listProperties(ip.Filters(1));
ip.Filters.Remove(1);
});
}
}
// List the supported transfer formats
@@ -308,14 +311,14 @@ Frame count = ${img.FrameCount}}
{
const dev = cd.ShowSelectDevice();
if (dev) {
collectionToArray(dev.Items).forEach(item => {
for (const item of collectionToArray(dev.Items)) {
let s: string = item.Properties("Item Name").Value;
if (item.Properties.Exists("Item Time Stamp")) {
const v: WIA.Vector = item.Properties("Item Time Stamp").Value;
if (v.Count === 8) { s += ` (${v.Date})`; }
}
WScript.Echo(s);
});
}
}
}
@@ -340,16 +343,16 @@ Frame count = ${img.FrameCount}}
}
// List all available devices by name and deviceid
collectionToArray(dm.DeviceInfos).forEach(di => {
for (const di of collectionToArray(dm.DeviceInfos)) {
const name: string = di.Properties("Name").Value;
WScript.Echo(`${name} (${di.DeviceID})`);
});
}
// Display all the properties for the selected device
{
const dev = cd.ShowSelectDevice();
if (dev) {
collectionToArray(dev.Properties).forEach(p => {
for (const p of collectionToArray(dev.Properties)) {
const name = `${p.Name} (${p.PropertyID})`;
let contents: string;
if (p.IsVector) {
@@ -360,7 +363,7 @@ Frame count = ${img.FrameCount}}
contents = p.Value;
}
WScript.Echo(`${name} = ${contents}`);
});
}
}
}
@@ -430,7 +433,7 @@ Frame count = ${img.FrameCount}}
if (args[0] === 'connect') {
const deviceID = args[1].substr(12);
const device = dm.DeviceInfos(deviceID).Connect();
collectionToArray(device.Items).forEach(item => {
for (const item of collectionToArray(device.Items)) {
const img = item.Transfer();
img.SaveFile(`C:\\${item.Properties('Item Name').Value}.${img.FileExtension}`);
@@ -445,7 +448,7 @@ Frame count = ${img.FrameCount}}
WScript.Echo(error);
}
}
});
}
WScript.Quit();
}
break;
+11 -9
View File
@@ -1,10 +1,6 @@
import AuthenticationContext, {
AuthenticationContextOptions,
TokenCallback,
UserCallback
} from "adal-angular";
import AuthenticationContext = require("adal-angular");
const onLogin: TokenCallback = (errorDescription, idToken, error) => {
const onLogin: AuthenticationContext.TokenCallback = (errorDescription, idToken, error) => {
if (error) {
console.error(errorDescription, error);
return;
@@ -14,7 +10,7 @@ const onLogin: TokenCallback = (errorDescription, idToken, error) => {
}
};
const onToken: TokenCallback = (errorDesc, token, error) => {
const onToken: AuthenticationContext.TokenCallback = (errorDesc, token, error) => {
if (error) {
console.error(error);
return;
@@ -22,7 +18,7 @@ const onToken: TokenCallback = (errorDesc, token, error) => {
console.log('Making request with token:', token);
};
const onUser: UserCallback = (error, user) => {
const onUser: AuthenticationContext.UserCallback = (error, user) => {
if (error) {
console.error(error);
return;
@@ -57,7 +53,7 @@ const acquireAnAccessToken = () => {
);
};
const config: AuthenticationContextOptions = {
const config: AuthenticationContext.Options = {
clientId: "7cee0f68-5051-41f6-9e45-80463d21d65d",
redirectUri: "http://localhost:16969/",
instance: "https://login.microsoftonline.com/",
@@ -70,6 +66,7 @@ const config: AuthenticationContextOptions = {
};
const authenticationContext = new AuthenticationContext(config);
window.Logging.level = authenticationContext.CONSTANTS.LOGGING_LEVEL.ERROR;
if (authenticationContext.isCallback(window.location.hash)) {
authenticationContext.handleWindowCallback();
@@ -79,6 +76,11 @@ if (authenticationContext.isCallback(window.location.hash)) {
acquireAnAccessToken();
}
const injectedContext = AuthenticationContext.inject({
clientId: "7cee0f68-5051-41f6-9e45-80463d21d65d",
});
injectedContext.handleWindowCallback();
setTimeout(() => {
authenticationContext.logOut();
}, 60000);
+242 -139
View File
@@ -1,142 +1,28 @@
// Type definitions for adal-angular 1.0
// Project: https://github.com/AzureAD/azure-activedirectory-library-for-js#readme
// Definitions by: Daniel Perez Alvarez <https://github.com/unindented>
// Anthony Ciccarello <https://github.com/aciccarello>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export enum LoggingLevel {
ERROR = 0,
WARNING = 1,
INFO = 2,
VERBOSE = 3
}
// In module contexts the class constructor function is the exported object
export = AuthenticationContext;
export type RequestType = "LOGIN" | "RENEW_TOKEN" | "UNKNOWN";
// This class is defined globally in not in a module context
declare class AuthenticationContext {
instance: string;
config: AuthenticationContext.Options;
callback: AuthenticationContext.TokenCallback;
popUp: boolean;
isAngular: boolean;
export type ResponseType = "id_token token" | "token";
/**
* Enum for request type
*/
REQUEST_TYPE: AuthenticationContext.RequestType;
RESPONSE_TYPE: AuthenticationContext.ResponseType;
CONSTANTS: AuthenticationContext.Constants;
export interface RequestInfo {
/**
* Object comprising of fields such as id_token/error, session_state, state, e.t.c.
*/
parameters: any;
/**
* Request type.
*/
requestType: RequestType;
/**
* Whether state is valid.
*/
stateMatch: boolean;
/**
* Unique guid used to match the response with the request.
*/
stateResponse: string;
/**
* Whether `requestType` contains `id_token`, `access_token` or error.
*/
valid: boolean;
}
export interface UserInfo {
/**
* Username assigned from UPN or email.
*/
userName: string;
/**
* Properties parsed from `id_token`.
*/
profile: any;
}
export type TokenCallback = (
errorDesc: string | null,
token: string,
error: any
) => void;
export type UserCallback = (errorDesc: string | null, user: UserInfo) => void;
export interface AuthenticationContextOptions {
/**
* Client ID assigned to your app by Azure Active Directory.
*/
clientId: string;
/**
* Endpoint at which you expect to receive tokens.Defaults to `window.location.href`.
*/
redirectUri: string;
/**
* Azure Active Directory instance. Defaults to `https://login.microsoftonline.com/`.
*/
instance?: string;
/**
* Your target tenant. Defaults to `common`.
*/
tenant?: string;
/**
* Query parameters to add to the authentication request.
*/
extraQueryParameter?: string;
/**
* Unique identifier used to map the request with the response. Defaults to RFC4122 version 4 guid (128 bits).
*/
correlationId?: string;
/**
* User defined function of handling the navigation to Azure AD authorization endpoint in case of login.
*/
displayCall?: (url: string) => void;
/**
* Set this to true to enable login in a popup winodow instead of a full redirect. Defaults to `false`.
*/
popUp?: boolean;
/**
* Set this to the resource to request on login. Defaults to `clientId`.
*/
loginResource?: string;
/**
* Set this to redirect the user to a custom login page.
*/
localLoginUrl?: string;
/**
* Redirects to start page after login. Defaults to `true`.
*/
navigateToLoginRequestUrl?: boolean;
/**
* Set this to redirect the user to a custom logout page.
*/
logOutUri?: string;
/**
* Redirects the user to postLogoutRedirectUri after logout. Defaults to `redirectUri`.
*/
postLogoutRedirectUri?: string;
/**
* Sets browser storage to either 'localStorage' or sessionStorage'. Defaults to `sessionStorage`.
*/
cacheLocation?: "localStorage" | "sessionStorage";
/**
* Array of keywords or URIs. Adal will attach a token to outgoing requests that have these keywords or URIs.
*/
endpoints?: { [resource: string]: string };
/**
* Array of keywords or URIs. Adal will not attach a token to outgoing requests that have these keywords or URIs.
*/
anonymousEndpoints?: string[];
/**
* If the cached token is about to be expired in the expireOffsetSeconds (in seconds), Adal will renew the token instead of using the cached token. Defaults to 300 seconds.
*/
expireOffsetSeconds?: number;
/**
* The number of milliseconds of inactivity before a token renewal response from AAD should be considered timed out. Defaults to 6 seconds.
*/
loadFrameTimeout?: number;
/**
* Callback to be invoked when a token is acquired.
*/
callback?: TokenCallback;
}
export default class AuthenticationContext {
constructor(options: AuthenticationContextOptions);
constructor(options: AuthenticationContext.Options);
/**
* Initiates the login process by redirecting the user to Azure AD authorization endpoint.
*/
@@ -153,7 +39,7 @@ export default class AuthenticationContext {
/**
* If user object exists, returns it. Else creates a new user object by decoding `id_token` from the cache.
*/
getCachedUser(): UserInfo;
getCachedUser(): AuthenticationContext.UserInfo;
/**
* Adds the passed callback to the array of callbacks for the specified resource.
* @param resource A URI that identifies the resource for which the token is requested.
@@ -163,14 +49,14 @@ export default class AuthenticationContext {
registerCallback(
expectedState: string,
resource: string,
callback: TokenCallback
callback: AuthenticationContext.TokenCallback
): void;
/**
* Acquires token from the cache if it is not expired. Otherwise sends request to AAD to obtain a new token.
* @param resource Resource URI identifying the target resource.
* @param callback The callback provided by the caller. It will be called with token or error.
*/
acquireToken(resource: string, callback: TokenCallback): void;
acquireToken(resource: string, callback: AuthenticationContext.TokenCallback): void;
/**
* Acquires token (interactive flow using a popup window) by sending request to AAD to obtain a new token.
* @param resource Resource URI identifying the target resource.
@@ -182,7 +68,7 @@ export default class AuthenticationContext {
resource: string,
extraQueryParameters: string | null | undefined,
claims: string | null | undefined,
callback: TokenCallback
callback: AuthenticationContext.TokenCallback
): void;
/**
* Acquires token (interactive flow using a redirect) by sending request to AAD to obtain a new token. In this case the callback passed in the authentication request constructor will be called.
@@ -217,7 +103,7 @@ export default class AuthenticationContext {
* Calls the passed in callback with the user object or error message related to the user.
* @param callback The callback provided by the caller. It will be called with user or error.
*/
getUser(callback: UserCallback): void;
getUser(callback: AuthenticationContext.UserCallback): void;
/**
* Checks if the URL fragment contains access token, id token or error description.
* @param hash Hash passed from redirect page.
@@ -230,11 +116,11 @@ export default class AuthenticationContext {
/**
* Creates a request info object from the URL fragment and returns it.
*/
getRequestInfo(hash: string): RequestInfo;
getRequestInfo(hash: string): AuthenticationContext.RequestInfo;
/**
* Saves token or error received in the response from AAD in the cache. In case of `id_token`, it also creates the user object.
*/
saveTokenFromHash(requestInfo: RequestInfo): void;
saveTokenFromHash(requestInfo: AuthenticationContext.RequestInfo): void;
/**
* Gets resource for given endpoint if mapping is provided with config.
* @param endpoint Resource URI identifying the target resource.
@@ -252,7 +138,7 @@ export default class AuthenticationContext {
* @param message Message to log.
* @param error Error to log.
*/
log(level: LoggingLevel, message: string, error: any): void;
log(level: AuthenticationContext.LoggingLevel, message: string, error: any): void;
/**
* Logs messages when logging level is set to 0.
* @param message Message to log.
@@ -274,4 +160,221 @@ export default class AuthenticationContext {
* @param message Message to log.
*/
verbose(message: string): void;
/**
* Logs Pii messages when Logging Level is set to 0 and window.piiLoggingEnabled is set to true.
* @param message Message to log.
* @param error Error to log.
*/
errorPii(message: string, error: any): void;
/**
* Logs Pii messages when Logging Level is set to 1 and window.piiLoggingEnabled is set to true.
* @param message Message to log.
*/
warnPii(message: string): void;
/**
* Logs messages when Logging Level is set to 2 and window.piiLoggingEnabled is set to true.
* @param message Message to log.
*/
infoPii(message: string): void;
/**
* Logs messages when Logging Level is set to 3 and window.piiLoggingEnabled is set to true.
* @param message Message to log.
*/
verbosePii(message: string): void;
}
declare namespace AuthenticationContext {
function inject(config: Options): AuthenticationContext;
type LoggingLevel = 0 | 1 | 2 | 3;
type RequestType = "LOGIN" | "RENEW_TOKEN" | "UNKNOWN";
type ResponseType = "id_token token" | "token";
interface RequestInfo {
/**
* Object comprising of fields such as id_token/error, session_state, state, e.t.c.
*/
parameters: any;
/**
* Request type.
*/
requestType: RequestType;
/**
* Whether state is valid.
*/
stateMatch: boolean;
/**
* Unique guid used to match the response with the request.
*/
stateResponse: string;
/**
* Whether `requestType` contains `id_token`, `access_token` or error.
*/
valid: boolean;
}
interface UserInfo {
/**
* Username assigned from UPN or email.
*/
userName: string;
/**
* Properties parsed from `id_token`.
*/
profile: any;
}
type TokenCallback = (
errorDesc: string | null,
token: string | null,
error: any
) => void;
type UserCallback = (errorDesc: string | null, user: UserInfo | null) => void;
/**
* Configuration options for Authentication Context
*/
interface Options {
/**
* Client ID assigned to your app by Azure Active Directory.
*/
clientId: string;
/**
* Endpoint at which you expect to receive tokens.Defaults to `window.location.href`.
*/
redirectUri?: string;
/**
* Azure Active Directory instance. Defaults to `https://login.microsoftonline.com/`.
*/
instance?: string;
/**
* Your target tenant. Defaults to `common`.
*/
tenant?: string;
/**
* Query parameters to add to the authentication request.
*/
extraQueryParameter?: string;
/**
* Unique identifier used to map the request with the response. Defaults to RFC4122 version 4 guid (128 bits).
*/
correlationId?: string;
/**
* User defined function of handling the navigation to Azure AD authorization endpoint in case of login.
*/
displayCall?: (url: string) => void;
/**
* Set this to true to enable login in a popup winodow instead of a full redirect. Defaults to `false`.
*/
popUp?: boolean;
/**
* Set this to the resource to request on login. Defaults to `clientId`.
*/
loginResource?: string;
/**
* Set this to redirect the user to a custom login page.
*/
localLoginUrl?: string;
/**
* Redirects to start page after login. Defaults to `true`.
*/
navigateToLoginRequestUrl?: boolean;
/**
* Set this to redirect the user to a custom logout page.
*/
logOutUri?: string;
/**
* Redirects the user to postLogoutRedirectUri after logout. Defaults to `redirectUri`.
*/
postLogoutRedirectUri?: string;
/**
* Sets browser storage to either 'localStorage' or sessionStorage'. Defaults to `sessionStorage`.
*/
cacheLocation?: "localStorage" | "sessionStorage";
/**
* Array of keywords or URIs. Adal will attach a token to outgoing requests that have these keywords or URIs.
*/
endpoints?: { [resource: string]: string };
/**
* Array of keywords or URIs. Adal will not attach a token to outgoing requests that have these keywords or URIs.
*/
anonymousEndpoints?: string[];
/**
* If the cached token is about to be expired in the expireOffsetSeconds (in seconds), Adal will renew the token instead of using the cached token. Defaults to 300 seconds.
*/
expireOffsetSeconds?: number;
/**
* The number of milliseconds of inactivity before a token renewal response from AAD should be considered timed out. Defaults to 6 seconds.
*/
loadFrameTimeout?: number;
/**
* Callback to be invoked when a token is acquired.
*/
callback?: TokenCallback;
}
interface LoggingConfig {
level: LoggingLevel;
log: (message: string) => void;
piiLoggingEnabled: boolean;
}
/**
* Enum for storage constants
*/
interface Constants {
ACCESS_TOKEN: 'access_token';
EXPIRES_IN: 'expires_in';
ID_TOKEN: 'id_token';
ERROR_DESCRIPTION: 'error_description';
SESSION_STATE: 'session_state';
STORAGE: {
TOKEN_KEYS: 'adal.token.keys';
ACCESS_TOKEN_KEY: 'adal.access.token.key';
EXPIRATION_KEY: 'adal.expiration.key';
STATE_LOGIN: 'adal.state.login';
STATE_RENEW: 'adal.state.renew';
NONCE_IDTOKEN: 'adal.nonce.idtoken';
SESSION_STATE: 'adal.session.state';
USERNAME: 'adal.username';
IDTOKEN: 'adal.idtoken';
ERROR: 'adal.error';
ERROR_DESCRIPTION: 'adal.error.description';
LOGIN_REQUEST: 'adal.login.request';
LOGIN_ERROR: 'adal.login.error';
RENEW_STATUS: 'adal.token.renew.status';
};
RESOURCE_DELIMETER: '|';
LOADFRAME_TIMEOUT: '6000';
TOKEN_RENEW_STATUS_CANCELED: 'Canceled';
TOKEN_RENEW_STATUS_COMPLETED: 'Completed';
TOKEN_RENEW_STATUS_IN_PROGRESS: 'In Progress';
LOGGING_LEVEL: {
ERROR: 0;
WARN: 1;
INFO: 2;
VERBOSE: 3;
};
LEVEL_STRING_MAP: {
0: 'ERROR:';
1: 'WARNING:';
2: 'INFO:';
3: 'VERBOSE:';
};
POPUP_WIDTH: 483;
POPUP_HEIGHT: 600;
}
}
declare global {
interface Window {
Logging: AuthenticationContext.LoggingConfig;
}
}
+3 -2
View File
@@ -15,10 +15,11 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",
"adal-angular-tests.ts"
]
}
}
+9
View File
@@ -1,4 +1,7 @@
/// <reference types="node" />
/// <reference types="lodash" />
/// <reference types="benchmark" />
/// <reference types="async" />
declare namespace adone {
const _null: symbol;
@@ -104,4 +107,10 @@ declare namespace adone {
export const expect: assertion.I.ExpectFunction;
export const std: typeof nodestd;
export const lodash: _.LoDashStatic;
export const benchmark: typeof tbenchmark;
export const async: typeof tasync;
}
+3
View File
@@ -0,0 +1,3 @@
export * from "async";
export as namespace tasync;
+5
View File
@@ -0,0 +1,5 @@
import Benchmark = require("benchmark");
export { Benchmark };
export as namespace tbenchmark;
+14
View File
@@ -103,6 +103,13 @@ declare namespace adone.collection {
*/
readUInt16BE(offset?: number): number;
/**
* Reads a 24bit unsigned be integer
*
* @param offset Offset to read from
*/
readUInt24BE(offset?: number): number;
/**
* Reads a 32bit signed le integer
*
@@ -260,6 +267,13 @@ declare namespace adone.collection {
*/
writeUInt16BE(value: number, offset?: number): this;
/**
* Writes a 24bit unsigned be integer
*
* @param offset Offset to write at
*/
writeUInt24BE(value: number, offset?: number): this;
/**
* Writes a 32bit signed le integer
*
+8 -3
View File
@@ -4,13 +4,18 @@ declare namespace adone.collection {
*/
class FastLRU<K = any, V = any> {
/**
* @param size Cache size, unlimited by default
* @param size
*/
constructor(size?: number, options?: {
constructor(options?: {
/**
* Cache size, unlimited by default
*/
maxSize?: number;
/**
* Function that is called when a value is deleted
*/
dispose?(key: K, value: V): void
dispose?(key: K, value: V): void;
});
/**
+1 -1
View File
@@ -16,7 +16,7 @@
/// <reference path="./refcounted_cache.d.ts" />
/// <reference path="./set.d.ts" />
/// <reference path="./stack.d.ts" />
/// <reference path="./timedout_map.d.ts" />
/// <reference path="./time_map.d.ts" />
declare namespace adone {
/**
+2 -7
View File
@@ -6,7 +6,7 @@ declare namespace adone.collection {
* The maximum size of the cache, checked by applying the length function to all values in the cache.
* Default is Infinity
*/
max?: number;
maxSize?: number;
/**
* Maximum age in ms. Items are not pro-actively pruned out as they age,
@@ -85,11 +85,6 @@ declare namespace adone.collection {
* Represent an LRU cache
*/
class LRU<K = any, V = any> {
/**
* Creates an LRU cache of the given size
*/
constructor(max: number);
/**
* Creates an LRU cache with the given options
*/
@@ -98,7 +93,7 @@ declare namespace adone.collection {
/**
* The length of the cache, setter resizes the cache
*/
max: number;
maxSize: number;
/**
* stale setting
+1 -1
View File
@@ -1,6 +1,6 @@
declare namespace adone.collection {
class NSCache<T = any> {
constructor(size: number, namespaces: string[]);
constructor(maxSize: number, namespaces: string[]);
resize(newSize: number): void;
@@ -2,7 +2,7 @@ declare namespace adone.collection {
/**
* Represents a Map that keeps keys only for a specified interval of time
*/
class TimedoutMap<K = any, V = any> extends Map<K, V> {
class TimeMap<K = any, V = any> extends Map<K, V> {
/**
* @param timeout maximum age of the keys, 1000 by default
* @param callback callback that is called with each key when the timeout is passed
+38 -26
View File
@@ -1158,37 +1158,35 @@ declare namespace adone {
*/
function watch(paths: string | string[], options?: I.Watcher.ConstructorOptions): Watcher;
namespace is {
/**
* Returns true if the given path refers to a file
*/
function file(path: string): Promise<boolean>;
/**
* Returns true if the given path refers to a file
*/
function isFile(path: string): Promise<boolean>;
/**
* Returns true if the given path refers to a file
*/
function fileSync(path: string): boolean;
/**
* Returns true if the given path refers to a file
*/
function isFileSync(path: string): boolean;
/**
* Returns true if the given path refers to a direcotry
*/
function directory(path: string): Promise<boolean>;
/**
* Returns true if the given path refers to a direcotry
*/
function isDirectory(path: string): Promise<boolean>;
/**
* Returns true if the given path refers to a direcotry
*/
function directorySync(path: string): boolean;
/**
* Returns true if the given path refers to a direcotry
*/
function isDirectorySync(path: string): boolean;
/**
* Returns true if the given path refers to an executable file
*/
function executable(path: string): Promise<boolean>;
/**
* Returns true if the given path refers to an executable file
*/
function isExecutable(path: string): Promise<boolean>;
/**
* Returns true if the given path refers to an executable file
*/
function executableSync(path: string): boolean;
}
/**
* Returns true if the given path refers to an executable file
*/
function isExecutableSync(path: string): boolean;
namespace I.Which {
interface Options {
@@ -1920,5 +1918,19 @@ declare namespace adone {
* Creates a new TailWatcher instance with the given arguments
*/
function watchTail(filename: string, options?: I.TailWatcher.ConstructorOptions): TailWatcher;
namespace I {
interface WriteFileAtomicOptions {
chown?: {
gid?: number;
uid?: number;
};
encoding?: string | null;
fsync?: boolean;
mode?: number;
}
}
function writeFileAtomic(filename: string, data: Buffer | string | Uint8Array, options?: I.WriteFileAtomicOptions): Promise<void>;
}
}
+16 -17
View File
@@ -490,12 +490,17 @@ declare namespace adone {
/**
* Checks whether the given string is an IPv4 address
*/
export function ip4(str: string): boolean;
export function ip4(str: string, options?: adone.regex.I.IP.Options): boolean;
/**
* Checks whether the given string is an IPv6 address
*/
export function ip6(str: string): boolean;
export function ip6(str: string, options?: adone.regex.I.IP.Options): boolean;
/**
* Checks whether the given string is IPv4 or IPv6 address
*/
export function ip(str: string, options?: adone.regex.I.IP.Options): boolean;
/**
* Checks whether the given object is an array buffer
@@ -628,21 +633,6 @@ declare namespace adone {
requireTld?: boolean
}): obj is string;
/**
* Checks whether the given object is a valid IPv4 address
*/
export function ip(obj: any, version: 4): boolean;
/**
* Checks whether the given object is a valid IPv6 address
*/
export function ip(obj: any, version: 6): boolean;
/**
* Checks whether the given object in a valid IPv4 or IPv6 address
*/
export function ip(obj: any): boolean;
/**
* Checks whether the given object is a valid UUIDv1 identifier
*/
@@ -676,5 +666,14 @@ declare namespace adone {
export function emitter(obj: any): obj is event.Emitter;
export function asyncEmitter(obj: any): obj is event.AsyncEmitter;
export const openbsd: boolean;
export const aix: boolean;
/**
* Checks whether the given object is adone.multi.address.Multiaddr
*/
export function multiAddress(obj: any): boolean; // TODO: obj is adone.multi.address.Multiaddr
}
}
+227
View File
@@ -0,0 +1,227 @@
declare namespace adone.math {
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;
}
}
+225
View File
@@ -0,0 +1,225 @@
declare namespace adone.math {
/**
* 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;
}
}
File diff suppressed because it is too large Load Diff
+20 -742
View File
@@ -1,3 +1,7 @@
/// <reference path="./bignumber.d.ts" />
/// <reference path="./bitset.d.ts" />
/// <reference path="./decimal.d.ts" />
/// <reference path="./long.d.ts" />
/// <reference path="./matrix.d.ts" />
/// <reference path="./simd.d.ts" />
@@ -6,748 +10,6 @@ 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
*
@@ -755,5 +17,21 @@ declare namespace adone {
* @param max upper bound, default is 0xFFFFFFFF
*/
function random(min?: number, max?: number): number;
/**
* Returns the maximum value from the given array
*
* @param array array of values
* @param score function to calculate the element score value
*/
function max<T>(array: T[], score?: (x: T) => any): T;
/**
* Returns the minimum value from the given array
*
* @param array array of values
* @param score function to calculate the element score value
*/
function min<T>(array: T[], score?: (x: T) => any): T;
}
}
+293
View File
@@ -0,0 +1,293 @@
declare namespace adone.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;
}
}
+10 -2
View File
@@ -2,9 +2,17 @@ declare namespace adone {
namespace regex {
function filename(): RegExp;
function ip4(): RegExp;
namespace I.IP {
interface Options {
exact?: boolean;
}
}
function ip6(): RegExp;
function ip(options?: I.IP.Options): RegExp;
function ip4(options?: I.IP.Options): RegExp;
function ip6(options?: I.IP.Options): RegExp;
function protocol(): RegExp;
@@ -56,6 +56,11 @@ namespace adoneTests.collection.ByteArray {
const b: number = buffer.readUInt16BE(10);
}
namespace readUInt24BE {
const a: number = buffer.readUInt24BE();
const b: number = buffer.readUInt24BE(10);
}
namespace readInt32LE {
const a: number = buffer.readInt32LE();
const b: number = buffer.readInt32LE(10);
@@ -162,6 +167,11 @@ namespace adoneTests.collection.ByteArray {
const b: adone.collection.ByteArray = buffer.writeUInt16BE(10, 10);
}
namespace writeUInt24BE {
const a: adone.collection.ByteArray = buffer.writeUInt24BE(10);
const b: adone.collection.ByteArray = buffer.writeUInt24BE(10, 10);
}
namespace writeInt32LE {
const a: adone.collection.ByteArray = buffer.writeInt32LE(10);
const b: adone.collection.ByteArray = buffer.writeInt32LE(10, 10);
@@ -6,8 +6,8 @@ namespace adoneTests.collection.FastLRU {
} = adone;
new FastLRU();
new FastLRU(100);
new FastLRU<string, number>(100, { dispose: (key: string, value: number) => null });
new FastLRU({ maxSize: 100 });
new FastLRU<string, number>({ maxSize: 100, dispose: (key: string, value: number) => null });
{ const a: number = new FastLRU().size; }
{ const a: number | undefined = new FastLRU<string, number>().get("key"); }
new FastLRU<string, number>().set("key", 123);
+3 -4
View File
@@ -8,15 +8,14 @@ namespace adoneTests.collection.LRU {
type LRU = adone.collection.LRU;
new LRU();
new LRU(100);
new LRU({ maxSize: 100 });
new LRU({});
new LRU({ max: 100 });
new LRU<string, number>({ dispose: (key: string, value: number) => null });
new LRU<string, number>({ maxAge: 100 });
new LRU<string, number>({ noDisposeOnSet: false });
new LRU<string, number>({ stale: true });
{ const a: number = new LRU<string, number>().max; }
{ new LRU<string, number>().max = 100; }
{ const a: number = new LRU<string, number>().maxSize; }
{ new LRU<string, number>().maxSize = 100; }
{ const a: boolean = new LRU<string, number>().allowStale; }
{ new LRU<string, number>().allowStale = false; }
{ const a: number = new LRU<string, number>().maxAge; }
@@ -0,0 +1,22 @@
namespace adoneTests.collection.TimedoutMap {
const {
collection: {
TimeMap
}
} = adone;
type TimeMap<K = any, V = any> = adone.collection.TimeMap<K, V>;
new TimeMap();
new TimeMap(1000);
new TimeMap<string, number>(1000, (key: string) => null);
{
const a: TimeMap<string, number> = new TimeMap<string, number>().forEach((value: number, key: string) => null);
}
{
const a: TimeMap<string, number> = new TimeMap<string, number>().forEach(function (value: number, key: string) {
const a: number = this.a;
}, { a: 1 });
}
{ const a: boolean = new TimeMap<string, number>().delete("123"); }
}
@@ -1,22 +0,0 @@
namespace adoneTests.collection.TimedoutMap {
const {
collection: {
TimedoutMap
}
} = adone;
type TimedoutMap<K = any, V = any> = adone.collection.TimedoutMap<K, V>;
new TimedoutMap();
new TimedoutMap(1000);
new TimedoutMap<string, number>(1000, (key: string) => null);
{
const a: TimedoutMap<string, number> = new TimedoutMap<string, number>().forEach((value: number, key: string) => null);
}
{
const a: TimedoutMap<string, number> = new TimedoutMap<string, number>().forEach(function (value: number, key: string) {
const a: number = this.a;
}, { a: 1 });
}
{ const a: boolean = new TimedoutMap<string, number>().delete("123"); }
}
+19 -7
View File
@@ -602,13 +602,12 @@ namespace fsTests {
}
namespace isTests {
const { is } = fs;
is.file("hello").then((x: boolean) => {});
{ const a: boolean = is.fileSync("hello"); }
is.directory("hello").then((x: boolean) => {});
{ const a: boolean = is.directorySync("hello"); }
is.executable("hello").then((x: boolean) => {});
{ const a: boolean = is.executableSync("hello"); }
fs.isFile("hello").then((x: boolean) => {});
{ const a: boolean = fs.isFileSync("hello"); }
fs.isDirectory("hello").then((x: boolean) => {});
{ const a: boolean = fs.isDirectorySync("hello"); }
fs.isExecutable("hello").then((x: boolean) => {});
{ const a: boolean = fs.isExecutableSync("hello"); }
}
namespace whichTests {
@@ -944,4 +943,17 @@ namespace fsTests {
fs.watchTail("file", { separator: /\n/ });
fs.watchTail("file", { useWatchFile: true });
}
namespace writeFileAtomicTests {
fs.writeFileAtomic("a", "b").then(() => {});
fs.writeFileAtomic("a", Buffer.from("b")).then(() => {});
fs.writeFileAtomic("a", new Uint8Array(10)).then(() => {});
fs.writeFileAtomic("a", "a", {}).then(() => {});
fs.writeFileAtomic("a", "a", { chown: {} }).then(() => {});
fs.writeFileAtomic("a", "a", { chown: { gid: 0 } }).then(() => {});
fs.writeFileAtomic("a", "a", { chown: { uid: 0 } }).then(() => {});
fs.writeFileAtomic("a", "a", { encoding: "utf8" }).then(() => {});
fs.writeFileAtomic("a", "a", { fsync: false }).then(() => {});
fs.writeFileAtomic("a", "a", { mode: 0o666 }).then(() => {});
}
}
+9
View File
@@ -336,6 +336,8 @@ namespace isTests {
{ const a: boolean = is.freebsd; }
{ const a: boolean = is.darwin; }
{ const a: boolean = is.sunos; }
{ const a: boolean = is.openbsd; }
{ const a: boolean = is.aix; }
{ const a: boolean = is.uppercase("abc"); }
{ const a: boolean = is.lowercase("abc"); }
{ const a: boolean = is.digits("012"); }
@@ -343,7 +345,11 @@ namespace isTests {
{ const a: boolean = is.binaryExtension("mp3"); }
{ const a: boolean = is.binaryPath("a.mp3"); }
{ const a: boolean = is.ip4("192.168.1.1"); }
{ const a: boolean = is.ip4("192.168.1.1", { exact: true }); }
{ const a: boolean = is.ip6("::192.168.1.1"); }
{ const a: boolean = is.ip6("::192.168.1.1", { exact: true }); }
{ const a: boolean = is.ip("::192.168.1.1"); }
{ const a: boolean = is.ip("::192.168.1.1", { exact: true }); }
{
const a: boolean = is.arrayBuffer({});
const b: any = 2;
@@ -490,4 +496,7 @@ namespace isTests {
b.charCodeAt(0);
}
}
{
const a: boolean = is.multiAddress(2);
}
}
+154
View File
@@ -0,0 +1,154 @@
namespace mathTests.bignumberTests {
const {
math: {
BigNumber
}
} = adone;
type BigNumber = adone.math.BigNumber;
new BigNumber(10);
new BigNumber("10");
new BigNumber(new BigNumber(10));
new BigNumber("10", 2);
{ const a: string = new BigNumber(1).toString(); }
{ const a: string = new BigNumber(1).toString(2); }
{ const a: number = new BigNumber(1).toNumber(); }
{ const a: Buffer = new BigNumber(1).toBuffer(); }
{ const a: Buffer = new BigNumber(1).toBuffer({}); }
{ const a: Buffer = new BigNumber(1).toBuffer({ endian: 1 }); }
{ const a: Buffer = new BigNumber(1).toBuffer({ endian: -1 }); }
{ const a: Buffer = new BigNumber(1).toBuffer({ endian: "big" }); }
{ const a: Buffer = new BigNumber(1).toBuffer({ endian: "little" }); }
{ const a: Buffer = new BigNumber(1).toBuffer({ size: 1 }); }
{ const a: Buffer = new BigNumber(1).toBuffer({ size: "auto" }); }
{ const a: BigNumber = new BigNumber(10).add(1); }
{ const a: BigNumber = new BigNumber(10).add("1"); }
{ const a: BigNumber = new BigNumber(10).add(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).sub(1); }
{ const a: BigNumber = new BigNumber(10).sub("1"); }
{ const a: BigNumber = new BigNumber(10).sub(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).mul(1); }
{ const a: BigNumber = new BigNumber(10).mul("1"); }
{ const a: BigNumber = new BigNumber(10).mul(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).div(1); }
{ const a: BigNumber = new BigNumber(10).div("1"); }
{ const a: BigNumber = new BigNumber(10).div(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).abs(); }
{ const a: BigNumber = new BigNumber(10).neg(); }
{ const a: number = new BigNumber(10).cmp(1); }
{ const a: number = new BigNumber(10).cmp("1"); }
{ const a: number = new BigNumber(10).cmp(new BigNumber(1)); }
{ const a: boolean = new BigNumber(10).gt(1); }
{ const a: boolean = new BigNumber(10).gt("1"); }
{ const a: boolean = new BigNumber(10).gt(new BigNumber(10)); }
{ const a: boolean = new BigNumber(10).ge(1); }
{ const a: boolean = new BigNumber(10).ge("1"); }
{ const a: boolean = new BigNumber(10).ge(new BigNumber(10)); }
{ const a: boolean = new BigNumber(10).eq(1); }
{ const a: boolean = new BigNumber(10).eq("1"); }
{ const a: boolean = new BigNumber(10).eq(new BigNumber(10)); }
{ const a: boolean = new BigNumber(10).lt(1); }
{ const a: boolean = new BigNumber(10).lt("1"); }
{ const a: boolean = new BigNumber(10).lt(new BigNumber(10)); }
{ const a: boolean = new BigNumber(10).le(1); }
{ const a: boolean = new BigNumber(10).le("1"); }
{ const a: boolean = new BigNumber(10).le(new BigNumber(10)); }
{ const a: BigNumber = new BigNumber(10).and(1); }
{ const a: BigNumber = new BigNumber(10).and("1"); }
{ const a: BigNumber = new BigNumber(10).and(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).or(1); }
{ const a: BigNumber = new BigNumber(10).or("1"); }
{ const a: BigNumber = new BigNumber(10).or(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).xor(1); }
{ const a: BigNumber = new BigNumber(10).xor("1"); }
{ const a: BigNumber = new BigNumber(10).xor(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).mod(1); }
{ const a: BigNumber = new BigNumber(10).mod("1"); }
{ const a: BigNumber = new BigNumber(10).mod(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).pow(1); }
{ const a: BigNumber = new BigNumber(10).pow("1"); }
{ const a: BigNumber = new BigNumber(10).pow(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).powm(1, 1); }
{ const a: BigNumber = new BigNumber(10).powm("1", 1); }
{ const a: BigNumber = new BigNumber(10).powm(new BigNumber(1), 1); }
{ const a: BigNumber = new BigNumber(10).powm(1, "1"); }
{ const a: BigNumber = new BigNumber(10).powm("1", "1"); }
{ const a: BigNumber = new BigNumber(10).powm(new BigNumber(1), "1"); }
{ const a: BigNumber = new BigNumber(10).powm(1, new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).powm("1", new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).powm(new BigNumber(1), new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).invertm(1); }
{ const a: BigNumber = new BigNumber(10).invertm("1"); }
{ const a: BigNumber = new BigNumber(10).invertm(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).rand(); }
{ const a: BigNumber = new BigNumber(10).rand(1); }
{ const a: BigNumber = new BigNumber(10).rand("1"); }
{ const a: BigNumber = new BigNumber(10).rand(new BigNumber(1)); }
{ const a: boolean | "maybe" = new BigNumber(10).probPrime(); }
{ const a: BigNumber = new BigNumber(10).nextPrime(); }
{ const a: BigNumber = new BigNumber(10).sqrt(); }
{ const a: BigNumber = new BigNumber(10).root(1); }
{ const a: BigNumber = new BigNumber(10).root("1"); }
{ const a: BigNumber = new BigNumber(10).root(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).shiftLeft(1); }
{ const a: BigNumber = new BigNumber(10).shiftLeft("1"); }
{ const a: BigNumber = new BigNumber(10).shiftLeft(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).shiftRight(1); }
{ const a: BigNumber = new BigNumber(10).shiftRight("1"); }
{ const a: BigNumber = new BigNumber(10).shiftRight(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).gcd(1); }
{ const a: BigNumber = new BigNumber(10).gcd("1"); }
{ const a: BigNumber = new BigNumber(10).gcd(new BigNumber(1)); }
{ const a: number = new BigNumber(10).jacobi(1); }
{ const a: number = new BigNumber(10).jacobi("1"); }
{ const a: number = new BigNumber(10).jacobi(new BigNumber(1)); }
{ const a: number = new BigNumber(10).bitLength(); }
{ const a: boolean = new BigNumber(10).isBitSet(10); }
{ const a: BigNumber = BigNumber.prime(10); }
{ const a: BigNumber = BigNumber.prime(10, true); }
{ const a: BigNumber = BigNumber.fromBuffer(Buffer.alloc(10)); }
{ const a: BigNumber = BigNumber.fromBuffer(Buffer.alloc(10), { endian: "little" }); }
{ const a: BigNumber = BigNumber.fromBuffer(Buffer.alloc(10), { endian: -1 }); }
{ const a: BigNumber = BigNumber.fromBuffer(Buffer.alloc(10), { endian: 1 }); }
{ const a: BigNumber = BigNumber.fromBuffer(Buffer.alloc(10), { endian: "big" }); }
{ const a: BigNumber = BigNumber.fromBuffer(Buffer.alloc(10), { size: "auto" }); }
{ const a: BigNumber = BigNumber.ONE; }
{ const a: BigNumber = BigNumber.ZERO; }
}
+62
View File
@@ -0,0 +1,62 @@
namespace mathTests.bitsetTests {
const {
math: {
BitSet
}
} = adone;
type BitSet = adone.math.BitSet;
new BitSet(10);
new BitSet(new BitSet(10).dehydrate());
{ const a: boolean = new BitSet(10).get(0); }
{ const a: boolean = new BitSet(10).set(0); }
{ const a: boolean = new BitSet(10).setRange(0, 10); }
{ const a: boolean = new BitSet(10).unset(0); }
{ const a: boolean = new BitSet(10).unsetRange(0, 10); }
{ const a: boolean = new BitSet(10).toggle(0); }
{ const a: boolean = new BitSet(10).toggleRange(0, 10); }
{ const a: boolean = new BitSet(10).clear(); }
{ const a: BitSet = new BitSet(10).clone(); }
{ const a: string = new BitSet(10).dehydrate(); }
{ const a: BitSet = new BitSet(10).and(1); }
{ const a: BitSet = new BitSet(10).and(new BitSet(10)); }
{ const a: BitSet = new BitSet(10).or(1); }
{ const a: BitSet = new BitSet(10).or(new BitSet(10)); }
{ const a: BitSet = new BitSet(10).xor(1); }
{ const a: BitSet = new BitSet(10).xor(new BitSet(10)); }
new BitSet(10).forEach((x: number) => {});
new BitSet(10).forEach((x: number) => false);
{ const a: BitSet = new BitSet(10).circularShift(10); }
{ const a: number = new BitSet(10).getCardinality(); }
{ const a: number[] = new BitSet(10).getIndices(); }
{ const a: boolean = new BitSet(10).isSubsetOf(new BitSet(10)); }
{ const a: boolean = new BitSet(10).isEmpty(); }
{ const a: boolean = new BitSet(10).isEqual(new BitSet(10)); }
{ const a: string = new BitSet(10).toString(); }
{ const a: number = new BitSet(10).ffs(); }
{ const a: number = new BitSet(10).ffs(1); }
{ const a: number = new BitSet(10).ffz(); }
{ const a: number = new BitSet(10).ffz(1); }
{ const a: number = new BitSet(10).fls(); }
{ const a: number = new BitSet(10).fls(1); }
{ const a: number = new BitSet(10).flz(); }
{ const a: number = new BitSet(10).flz(1); }
{ const a: number = new BitSet(10).nextSetBit(1); }
{ const a: number = new BitSet(10).nextUnsetBit(1); }
{ const a: number = new BitSet(10).previousSetBit(1); }
{ const a: number = new BitSet(10).previousUnsetBit(1); }
{ const a: number = new BitSet(10).readUInt(); }
{ const a: number = new BitSet(10).readUInt(1); }
{ const a: number = new BitSet(10).readUInt(1, 2); }
{ new BitSet(10).writeUInt(1); }
{ new BitSet(10).writeUInt(1, 2); }
{ new BitSet(10).writeUInt(1, 2, 3); }
{ const a: BitSet = BitSet.fromLong(new adone.math.Long(10, 20)); }
}
+445
View File
@@ -0,0 +1,445 @@
namespace mathTests.decimalTest {
const {
math: {
Decimal
}
} = adone;
type Decimal = adone.math.Decimal;
new Decimal(0);
new Decimal("0");
new Decimal(new Decimal(0));
new Decimal(0).e.toExponential();
new Decimal(0).d[0].toExponential();
new Decimal(0).s.toExponential();
const d = new Decimal(0);
{ const a: Decimal = d.abs(); }
{ const a: Decimal = d.absoluteValue(); }
{ const a: Decimal = d.ceil(); }
{ const a: number = d.comparedTo(1); }
{ const a: number = d.comparedTo("1"); }
{ const a: number = d.comparedTo(d); }
{ const a: number = d.cmp(1); }
{ const a: number = d.cmp("1"); }
{ const a: number = d.cmp(d); }
{ const a: Decimal = d.cos(); }
{ const a: Decimal = d.cosine(); }
{ const a: Decimal = d.cubeRoot(); }
{ const a: Decimal = d.cbrt(); }
{ const a: number = d.decimalPlaces(); }
{ const a: number = d.dp(); }
{ const a: Decimal = d.dividedBy(1); }
{ const a: Decimal = d.dividedBy("1"); }
{ const a: Decimal = d.dividedBy(d); }
{ const a: Decimal = d.div(1); }
{ const a: Decimal = d.div("1"); }
{ const a: Decimal = d.div(d); }
{ const a: Decimal = d.dividedToIntegerBy(1); }
{ const a: Decimal = d.dividedToIntegerBy("1"); }
{ const a: Decimal = d.dividedToIntegerBy(d); }
{ const a: Decimal = d.divToInt(1); }
{ const a: Decimal = d.divToInt("1"); }
{ const a: Decimal = d.divToInt(d); }
{ const a: boolean = d.equals(1); }
{ const a: boolean = d.equals("1"); }
{ const a: boolean = d.equals(d); }
{ const a: boolean = d.eq(1); }
{ const a: boolean = d.eq("1"); }
{ const a: boolean = d.eq(d); }
{ const a: Decimal = d.floor(); }
{ const a: boolean = d.greaterThan(1); }
{ const a: boolean = d.greaterThan("1"); }
{ const a: boolean = d.greaterThan(d); }
{ const a: boolean = d.gt(1); }
{ const a: boolean = d.gt("1"); }
{ const a: boolean = d.gt(d); }
{ const a: boolean = d.greaterThanOrEqualTo(1); }
{ const a: boolean = d.greaterThanOrEqualTo("1"); }
{ const a: boolean = d.greaterThanOrEqualTo(d); }
{ const a: boolean = d.gte(1); }
{ const a: boolean = d.gte("1"); }
{ const a: boolean = d.gte(d); }
{ const a: Decimal = d.hyperbolicCosine(); }
{ const a: Decimal = d.cosh(); }
{ const a: Decimal = d.hyperbolicSine(); }
{ const a: Decimal = d.sinh(); }
{ const a: Decimal = d.hyperbolicTangent(); }
{ const a: Decimal = d.tanh(); }
{ const a: Decimal = d.inverseCosine(); }
{ const a: Decimal = d.acos(); }
{ const a: Decimal = d.inverseHyperbolicCosine(); }
{ const a: Decimal = d.acosh(); }
{ const a: Decimal = d.inverseHyperbolicSine(); }
{ const a: Decimal = d.asinh(); }
{ const a: Decimal = d.inverseHyperbolicTangent(); }
{ const a: Decimal = d.atanh(); }
{ const a: Decimal = d.inverseSine(); }
{ const a: Decimal = d.asin(); }
{ const a: Decimal = d.inverseTangent(); }
{ const a: Decimal = d.atan(); }
{ const a: boolean = d.isFinite(); }
{ const a: boolean = d.isInteger(); }
{ const a: boolean = d.isInt(); }
{ const a: boolean = d.isNaN(); }
{ const a: boolean = d.isNegative(); }
{ const a: boolean = d.isNeg(); }
{ const a: boolean = d.isPositive(); }
{ const a: boolean = d.isPos(); }
{ const a: boolean = d.isZero(); }
{ const a: boolean = d.lessThan(1); }
{ const a: boolean = d.lessThan("1"); }
{ const a: boolean = d.lessThan(d); }
{ const a: boolean = d.lt(1); }
{ const a: boolean = d.lt("1"); }
{ const a: boolean = d.lt(d); }
{ const a: boolean = d.lessThanOrEqualTo(1); }
{ const a: boolean = d.lessThanOrEqualTo("1"); }
{ const a: boolean = d.lessThanOrEqualTo(d); }
{ const a: boolean = d.lte(1); }
{ const a: boolean = d.lte("1"); }
{ const a: boolean = d.lte(d); }
{ const a: Decimal = d.logarithm(); }
{ const a: Decimal = d.logarithm(1); }
{ const a: Decimal = d.logarithm("1"); }
{ const a: Decimal = d.logarithm(d); }
{ const a: Decimal = d.log(); }
{ const a: Decimal = d.log(1); }
{ const a: Decimal = d.log("1"); }
{ const a: Decimal = d.log(d); }
{ const a: Decimal = d.minus(1); }
{ const a: Decimal = d.minus("1"); }
{ const a: Decimal = d.minus(d); }
{ const a: Decimal = d.sub(1); }
{ const a: Decimal = d.sub("1"); }
{ const a: Decimal = d.sub(d); }
{ const a: Decimal = d.modulo(1); }
{ const a: Decimal = d.modulo("1"); }
{ const a: Decimal = d.modulo(d); }
{ const a: Decimal = d.mod(1); }
{ const a: Decimal = d.mod("1"); }
{ const a: Decimal = d.mod(d); }
{ const a: Decimal = d.naturalExponential(); }
{ const a: Decimal = d.exp(); }
{ const a: Decimal = d.naturalLogarithm(); }
{ const a: Decimal = d.ln(); }
{ const a: Decimal = d.negated(); }
{ const a: Decimal = d.neg(); }
{ const a: Decimal = d.plus(1); }
{ const a: Decimal = d.plus("1"); }
{ const a: Decimal = d.plus(d); }
{ const a: Decimal = d.add(1); }
{ const a: Decimal = d.add("1"); }
{ const a: Decimal = d.add(d); }
{ const a: number = d.precision(); }
{ const a: number = d.precision(true); }
{ const a: number = d.sd(); }
{ const a: number = d.sd(true); }
{ const a: Decimal = d.round(); }
{ const a: Decimal = d.sine(); }
{ const a: Decimal = d.sin(); }
{ const a: Decimal = d.squareRoot(); }
{ const a: Decimal = d.sqrt(); }
{ const a: Decimal = d.tangent(); }
{ const a: Decimal = d.tan(); }
{ const a: Decimal = d.times(1); }
{ const a: Decimal = d.times("1"); }
{ const a: Decimal = d.times(d); }
{ const a: Decimal = d.mul(1); }
{ const a: Decimal = d.mul("1"); }
{ const a: Decimal = d.mul(d); }
{ const a: string = d.toBinary(); }
{ const a: string = d.toBinary(1); }
{ const a: string = d.toBinary(1, 1); }
{ const a: Decimal = d.toDecimalPlaces(); }
{ const a: Decimal = d.toDecimalPlaces(1); }
{ const a: Decimal = d.toDecimalPlaces(1, 1); }
{ const a: Decimal = d.toDP(); }
{ const a: Decimal = d.toDP(1); }
{ const a: Decimal = d.toDP(1, 1); }
{ const a: string = d.toExponential(); }
{ const a: string = d.toExponential(1); }
{ const a: string = d.toExponential(1, 1); }
{ const a: string = d.toFixed(); }
{ const a: string = d.toFixed(1); }
{ const a: string = d.toFixed(1, 1); }
{ const a: Decimal[] = d.toFraction(); }
{ const a: Decimal[] = d.toFraction(1); }
{ const a: Decimal[] = d.toFraction("1"); }
{ const a: Decimal[] = d.toFraction(d); }
{ const a: string = d.toHexadecimal(); }
{ const a: string = d.toHexadecimal(1); }
{ const a: string = d.toHexadecimal(1, 1); }
{ const a: string = d.toHex(); }
{ const a: string = d.toHex(1); }
{ const a: string = d.toHex(1, 1); }
{ const a: string = d.toJSON(); }
{ const a: Decimal = d.toNearest(); }
{ const a: Decimal = d.toNearest(1); }
{ const a: Decimal = d.toNearest("1"); }
{ const a: Decimal = d.toNearest(d); }
{ const a: Decimal = d.toNearest(d, 1); }
{ const a: number = d.toNumber(); }
{ const a: string = d.toOctal(); }
{ const a: string = d.toOctal(1); }
{ const a: string = d.toOctal(1, 1); }
{ const a: Decimal = d.toPower(1); }
{ const a: Decimal = d.toPower("1"); }
{ const a: Decimal = d.toPower(d); }
{ const a: Decimal = d.pow(1); }
{ const a: Decimal = d.pow("1"); }
{ const a: Decimal = d.pow(d); }
{ const a: string = d.toPrecision(); }
{ const a: string = d.toPrecision(1); }
{ const a: string = d.toPrecision(1, 1); }
{ const a: Decimal = d.toSignificantDigits(); }
{ const a: Decimal = d.toSignificantDigits(1); }
{ const a: Decimal = d.toSignificantDigits(1, 1); }
{ const a: Decimal = d.toSD(); }
{ const a: Decimal = d.toSD(1); }
{ const a: Decimal = d.toSD(1, 1); }
{ const a: string = d.toString(); }
{ const a: Decimal = d.truncated(); }
{ const a: Decimal = d.trunc(); }
{ const a: string = d.valueOf(); }
{ const a: Decimal = Decimal.abs(1); }
{ const a: Decimal = Decimal.abs("1"); }
{ const a: Decimal = Decimal.abs(d); }
{ const a: Decimal = Decimal.acos(1); }
{ const a: Decimal = Decimal.acos("1"); }
{ const a: Decimal = Decimal.acos(d); }
{ const a: Decimal = Decimal.acosh(1); }
{ const a: Decimal = Decimal.acosh("1"); }
{ const a: Decimal = Decimal.acosh(d); }
{ const a: Decimal = Decimal.asin(1); }
{ const a: Decimal = Decimal.asin("1"); }
{ const a: Decimal = Decimal.asin(d); }
{ const a: Decimal = Decimal.asinh(1); }
{ const a: Decimal = Decimal.asinh("1"); }
{ const a: Decimal = Decimal.asinh(d); }
{ const a: Decimal = Decimal.atan(1); }
{ const a: Decimal = Decimal.atan("1"); }
{ const a: Decimal = Decimal.atan(d); }
{ const a: Decimal = Decimal.atan2(1, 1); }
{ const a: Decimal = Decimal.atan2("1", "1"); }
{ const a: Decimal = Decimal.atan2(d, d); }
{ const a: Decimal = Decimal.cbrt(1); }
{ const a: Decimal = Decimal.cbrt("1"); }
{ const a: Decimal = Decimal.cbrt(d); }
{ const a: typeof Decimal = Decimal.clone({}); }
{ const a: typeof Decimal = Decimal.clone({ crypto: true }); }
{ const a: typeof Decimal = Decimal.clone({ defaults: true }); }
{ const a: typeof Decimal = Decimal.clone({ maxE: 1 }); }
{ const a: typeof Decimal = Decimal.clone({ minE: 1 }); }
{ const a: typeof Decimal = Decimal.clone({ modulo: 1 }); }
{ const a: typeof Decimal = Decimal.clone({ precision: 1 }); }
{ const a: typeof Decimal = Decimal.clone({ rounding: 1 }); }
{ const a: typeof Decimal = Decimal.clone({ toExpNeg: 1 }); }
{ const a: typeof Decimal = Decimal.clone({ toExpPos: 1 }); }
{ const a: typeof Decimal = Decimal.clone({}); }
{ const a: typeof Decimal = Decimal.config({ crypto: true }); }
{ const a: typeof Decimal = Decimal.config({ defaults: true }); }
{ const a: typeof Decimal = Decimal.config({ maxE: 1 }); }
{ const a: typeof Decimal = Decimal.config({ minE: 1 }); }
{ const a: typeof Decimal = Decimal.config({ modulo: 1 }); }
{ const a: typeof Decimal = Decimal.config({ precision: 1 }); }
{ const a: typeof Decimal = Decimal.config({ rounding: 1 }); }
{ const a: typeof Decimal = Decimal.config({ toExpNeg: 1 }); }
{ const a: typeof Decimal = Decimal.config({ toExpPos: 1 }); }
{ const a: typeof Decimal = Decimal.set({ crypto: true }); }
{ const a: typeof Decimal = Decimal.set({ defaults: true }); }
{ const a: typeof Decimal = Decimal.set({ maxE: 1 }); }
{ const a: typeof Decimal = Decimal.set({ minE: 1 }); }
{ const a: typeof Decimal = Decimal.set({ modulo: 1 }); }
{ const a: typeof Decimal = Decimal.set({ precision: 1 }); }
{ const a: typeof Decimal = Decimal.set({ rounding: 1 }); }
{ const a: typeof Decimal = Decimal.set({ toExpNeg: 1 }); }
{ const a: typeof Decimal = Decimal.set({ toExpPos: 1 }); }
{ const a: Decimal = Decimal.cos(1); }
{ const a: Decimal = Decimal.cos("1"); }
{ const a: Decimal = Decimal.cos(d); }
{ const a: Decimal = Decimal.div(1, 1); }
{ const a: Decimal = Decimal.div("1", "1"); }
{ const a: Decimal = Decimal.div(d, d); }
{ const a: Decimal = Decimal.exp(1); }
{ const a: Decimal = Decimal.exp("1"); }
{ const a: Decimal = Decimal.exp(d); }
{ const a: Decimal = Decimal.floor(1); }
{ const a: Decimal = Decimal.floor("1"); }
{ const a: Decimal = Decimal.floor(d); }
{ const a: Decimal = Decimal.hypot(1); }
{ const a: Decimal = Decimal.hypot("1"); }
{ const a: Decimal = Decimal.hypot(d); }
{ const a: Decimal = Decimal.hypot(1, 1); }
{ const a: Decimal = Decimal.hypot("1", "1"); }
{ const a: Decimal = Decimal.hypot(d, d); }
{ const a: Decimal = Decimal.hypot(1, 1, 1); }
{ const a: Decimal = Decimal.hypot("1", "1", "1"); }
{ const a: Decimal = Decimal.hypot(d, d, d); }
{ const a: Decimal = Decimal.hypot(1, 1, 1, 1, 1, 1, 1, 1, 1, d, 1, 1, 1, "1", d); }
{ const a: boolean = Decimal.isDecimal(d); }
{ const a: Decimal = Decimal.ln(1); }
{ const a: Decimal = Decimal.ln("1"); }
{ const a: Decimal = Decimal.ln(d); }
{ const a: Decimal = Decimal.log(1); }
{ const a: Decimal = Decimal.log("1"); }
{ const a: Decimal = Decimal.log(d); }
{ const a: Decimal = Decimal.log(1, 2); }
{ const a: Decimal = Decimal.log("1", 2); }
{ const a: Decimal = Decimal.log(d, 2); }
{ const a: Decimal = Decimal.log2(1); }
{ const a: Decimal = Decimal.log2("1"); }
{ const a: Decimal = Decimal.log2(d); }
{ const a: Decimal = Decimal.log10(1); }
{ const a: Decimal = Decimal.log10("1"); }
{ const a: Decimal = Decimal.log10(d); }
{ const a: Decimal = Decimal.min(1, "1", 1, d); }
{ const a: Decimal = Decimal.max(1, "1", 1, d); }
{ const a: Decimal = Decimal.mul(1, 1); }
{ const a: Decimal = Decimal.mul("1", "1"); }
{ const a: Decimal = Decimal.mul(d, d); }
{ const a: Decimal = Decimal.pow(1, 1); }
{ const a: Decimal = Decimal.pow("1", "1"); }
{ const a: Decimal = Decimal.pow(d, d); }
{ const a: Decimal = Decimal.random(); }
{ const a: Decimal = Decimal.random(1); }
{ const a: Decimal = Decimal.round(1); }
{ const a: Decimal = Decimal.round("1"); }
{ const a: Decimal = Decimal.round(d); }
{ const a: Decimal = Decimal.sign(1); }
{ const a: Decimal = Decimal.sign("1"); }
{ const a: Decimal = Decimal.sign(d); }
{ const a: Decimal = Decimal.sin(1); }
{ const a: Decimal = Decimal.sin("1"); }
{ const a: Decimal = Decimal.sin(d); }
{ const a: Decimal = Decimal.sinh(1); }
{ const a: Decimal = Decimal.sinh("1"); }
{ const a: Decimal = Decimal.sinh(d); }
{ const a: Decimal = Decimal.sqrt(1); }
{ const a: Decimal = Decimal.sqrt("1"); }
{ const a: Decimal = Decimal.sqrt(d); }
{ const a: Decimal = Decimal.sub(1, 1); }
{ const a: Decimal = Decimal.sub("1", "1"); }
{ const a: Decimal = Decimal.sub(d, d); }
{ const a: Decimal = Decimal.tan(1); }
{ const a: Decimal = Decimal.tan("1"); }
{ const a: Decimal = Decimal.tan(d); }
{ const a: Decimal = Decimal.tanh(1); }
{ const a: Decimal = Decimal.tanh("1"); }
{ const a: Decimal = Decimal.tanh(d); }
{ const a: Decimal = Decimal.trunc(1); }
{ const a: Decimal = Decimal.trunc("1"); }
{ const a: Decimal = Decimal.trunc(d); }
{ const a: number = Decimal.precision; }
{ const a: number = Decimal.rounding; }
{ const a: number = Decimal.toExpNeg; }
{ const a: number = Decimal.minE; }
{ const a: boolean = Decimal.crypto; }
{ const a: number = Decimal.modulo; }
{ const a: number = Decimal.ROUND_UP; }
{ const a: number = Decimal.ROUND_DOWN; }
{ const a: number = Decimal.ROUND_CEIL; }
{ const a: number = Decimal.ROUND_FLOOR; }
{ const a: number = Decimal.ROUND_HALF_UP; }
{ const a: number = Decimal.ROUND_HALF_DOWN; }
{ const a: number = Decimal.ROUND_HALF_EVEN; }
{ const a: number = Decimal.ROUND_HALF_CEIL; }
{ const a: number = Decimal.ROUND_HALF_FLOOR; }
{ const a: number = Decimal.EUCLID; }
}
+21 -465
View File
@@ -1,469 +1,7 @@
namespace mathTests {
const { math } = adone;
namespace LongTests {
new math.Long();
new math.Long(0);
new math.Long(0, 0);
new math.Long(0, 0, true);
namespace toInt {
const a: number = new math.Long().toInt();
}
namespace toNumber {
const a: number = new math.Long().toNumber();
}
namespace toString {
const a: string = new math.Long().toString();
const b: string = new math.Long().toString(16);
}
namespace getHighBits {
const a: number = new math.Long().getHighBits();
}
namespace getLowBits {
const a: number = new math.Long().getLowBits();
}
namespace getLowBitsUnsigned {
const a: number = new math.Long().getLowBitsUnsigned();
}
namespace getHighBitsUnsigned {
const a: number = new math.Long().getHighBitsUnsigned();
}
namespace getNumBitsAbs {
const a: number = new math.Long().getNumBitsAbs();
}
namespace isZero {
const a: boolean = new math.Long().isZero();
}
namespace isNegative {
const a: boolean = new math.Long().isNegative();
}
namespace isPositive {
const a: boolean = new math.Long().isPositive();
}
namespace isOdd {
const a: boolean = new math.Long().isOdd();
}
namespace isEven {
const a: boolean = new math.Long().isEven();
}
namespace equals {
const a = new math.Long();
const b: boolean = a.equals(new math.Long());
const c: boolean = a.equals(1);
const d: boolean = a.equals("1");
const e: boolean = a.equals({ low: 0, high: 0 });
}
namespace lessThan {
const a = new math.Long();
const b: boolean = a.lessThan(new math.Long());
const c: boolean = a.lessThan(1);
const d: boolean = a.lessThan("1");
const e: boolean = a.lessThan({ low: 0, high: 0 });
}
namespace lessThanOrEqual {
const a = new math.Long();
const b: boolean = a.lessThanOrEqual(new math.Long());
const c: boolean = a.lessThanOrEqual(1);
const d: boolean = a.lessThanOrEqual("1");
const e: boolean = a.lessThanOrEqual({ low: 0, high: 0 });
}
namespace greaterThan {
const a = new math.Long();
const b: boolean = a.greaterThan(new math.Long());
const c: boolean = a.greaterThan(1);
const d: boolean = a.greaterThan("1");
const e: boolean = a.greaterThan({ low: 0, high: 0 });
}
namespace greaterThanOrEqual {
const a = new math.Long();
const b: boolean = a.greaterThanOrEqual(new math.Long());
const c: boolean = a.greaterThanOrEqual(1);
const d: boolean = a.greaterThanOrEqual("1");
const e: boolean = a.greaterThanOrEqual({ low: 0, high: 0 });
}
namespace compareTests {
const a = new math.Long();
const b: number = a.compare(new math.Long());
const c: number = a.compare(1);
const d: number = a.compare("1");
const e: number = a.compare({ low: 0, high: 0 });
}
namespace negate {
const a: adone.math.Long = new math.Long().negate();
}
namespace add {
const a = new math.Long();
const b: adone.math.Long = a.add(new math.Long());
const c: adone.math.Long = a.add(1);
const d: adone.math.Long = a.add("1");
const e: adone.math.Long = a.add({ low: 0, high: 0 });
}
namespace sub {
const a = new math.Long();
const b: adone.math.Long = a.sub(new math.Long());
const c: adone.math.Long = a.sub(1);
const d: adone.math.Long = a.sub("1");
const e: adone.math.Long = a.sub({ low: 0, high: 0 });
}
namespace mul {
const a = new math.Long();
const b: adone.math.Long = a.mul(new math.Long());
const c: adone.math.Long = a.mul(1);
const d: adone.math.Long = a.mul("1");
const e: adone.math.Long = a.mul({ low: 0, high: 0 });
}
namespace div {
const a = new math.Long();
const b: adone.math.Long = a.div(new math.Long());
const c: adone.math.Long = a.div(1);
const d: adone.math.Long = a.div("1");
const e: adone.math.Long = a.div({ low: 0, high: 0 });
}
namespace mod {
const a = new math.Long();
const b: adone.math.Long = a.mod(new math.Long());
const c: adone.math.Long = a.mod(1);
const d: adone.math.Long = a.mod("1");
const e: adone.math.Long = a.mod({ low: 0, high: 0 });
}
namespace not {
const a: adone.math.Long = new math.Long().not();
}
namespace and {
const a = new math.Long();
const b: adone.math.Long = a.and(new math.Long());
const c: adone.math.Long = a.and(1);
const d: adone.math.Long = a.and("1");
const e: adone.math.Long = a.and({ low: 0, high: 0 });
}
namespace or {
const a = new math.Long();
const b: adone.math.Long = a.or(new math.Long());
const c: adone.math.Long = a.or(1);
const d: adone.math.Long = a.or("1");
const e: adone.math.Long = a.or({ low: 0, high: 0 });
}
namespace xor {
const a = new math.Long();
const b: adone.math.Long = a.xor(new math.Long());
const c: adone.math.Long = a.xor(1);
const d: adone.math.Long = a.xor("1");
const e: adone.math.Long = a.xor({ low: 0, high: 0 });
}
namespace shl {
const a = new math.Long();
const b: adone.math.Long = a.shl(new math.Long());
const c: adone.math.Long = a.shl(1);
}
namespace shr {
const a = new math.Long();
const b: adone.math.Long = a.shr(new math.Long());
const c: adone.math.Long = a.shr(1);
}
namespace shru {
const a = new math.Long();
const b: adone.math.Long = a.shr(new math.Long());
const c: adone.math.Long = a.shr(1);
}
namespace toSigned {
const a: adone.math.Long = new math.Long().toSigned();
}
namespace toUnsigned {
const a: adone.math.Long = new math.Long().toUnsigned();
}
namespace toBytes {
const a: number[] = new math.Long().toBytes();
}
namespace toBytesLE {
const a: number[] = new math.Long().toBytesLE();
}
namespace static {
namespace fromInt {
const a: adone.math.Long = math.Long.fromInt(123);
const b: adone.math.Long = math.Long.fromInt(123, true);
}
namespace fromNumber {
const a: adone.math.Long = math.Long.fromNumber(123);
const b: adone.math.Long = math.Long.fromNumber(123, true);
}
namespace fromBits {
const a: adone.math.Long = math.Long.fromBits(0, 0);
const b: adone.math.Long = math.Long.fromBits(123, 0, true);
}
namespace fromString {
const a: adone.math.Long = math.Long.fromString("123");
const b: adone.math.Long = math.Long.fromString("123", true);
const c: adone.math.Long = math.Long.fromString("123", 16);
const d: adone.math.Long = math.Long.fromString("123", true, 16);
}
namespace fromValue {
const a: adone.math.Long = math.Long.fromValue(new math.Long());
const b: adone.math.Long = math.Long.fromValue(1);
const c: adone.math.Long = math.Long.fromValue("1");
const e: adone.math.Long = math.Long.fromValue({ low: 0, high: 0 });
}
namespace constants {
const a: adone.math.Long = math.Long.MIN_VALUE;
const b: adone.math.Long = math.Long.MAX_VALUE;
const c: adone.math.Long = math.Long.MAX_UNSIGNED_VALUE;
const d: adone.math.Long = math.Long.ZERO;
const e: adone.math.Long = math.Long.UZERO;
const f: adone.math.Long = math.Long.ONE;
const g: adone.math.Long = math.Long.UONE;
const h: adone.math.Long = math.Long.NEG_ONE;
}
}
}
namespace BigNumberTests {
const { BigNumber } = math;
type BigNumber = adone.math.BigNumber;
new BigNumber(10);
new BigNumber("10");
new BigNumber(new BigNumber(10));
new BigNumber("10", 2);
{ const a: string = new BigNumber(1).toString(); }
{ const a: string = new BigNumber(1).toString(2); }
{ const a: number = new BigNumber(1).toNumber(); }
{ const a: Buffer = new BigNumber(1).toBuffer(); }
{ const a: Buffer = new BigNumber(1).toBuffer({}); }
{ const a: Buffer = new BigNumber(1).toBuffer({ endian: 1 }); }
{ const a: Buffer = new BigNumber(1).toBuffer({ endian: -1 }); }
{ const a: Buffer = new BigNumber(1).toBuffer({ endian: "big" }); }
{ const a: Buffer = new BigNumber(1).toBuffer({ endian: "little" }); }
{ const a: Buffer = new BigNumber(1).toBuffer({ size: 1 }); }
{ const a: Buffer = new BigNumber(1).toBuffer({ size: "auto" }); }
{ const a: BigNumber = new BigNumber(10).add(1); }
{ const a: BigNumber = new BigNumber(10).add("1"); }
{ const a: BigNumber = new BigNumber(10).add(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).sub(1); }
{ const a: BigNumber = new BigNumber(10).sub("1"); }
{ const a: BigNumber = new BigNumber(10).sub(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).mul(1); }
{ const a: BigNumber = new BigNumber(10).mul("1"); }
{ const a: BigNumber = new BigNumber(10).mul(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).div(1); }
{ const a: BigNumber = new BigNumber(10).div("1"); }
{ const a: BigNumber = new BigNumber(10).div(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).abs(); }
{ const a: BigNumber = new BigNumber(10).neg(); }
{ const a: number = new BigNumber(10).cmp(1); }
{ const a: number = new BigNumber(10).cmp("1"); }
{ const a: number = new BigNumber(10).cmp(new BigNumber(1)); }
{ const a: boolean = new BigNumber(10).gt(1); }
{ const a: boolean = new BigNumber(10).gt("1"); }
{ const a: boolean = new BigNumber(10).gt(new BigNumber(10)); }
{ const a: boolean = new BigNumber(10).ge(1); }
{ const a: boolean = new BigNumber(10).ge("1"); }
{ const a: boolean = new BigNumber(10).ge(new BigNumber(10)); }
{ const a: boolean = new BigNumber(10).eq(1); }
{ const a: boolean = new BigNumber(10).eq("1"); }
{ const a: boolean = new BigNumber(10).eq(new BigNumber(10)); }
{ const a: boolean = new BigNumber(10).lt(1); }
{ const a: boolean = new BigNumber(10).lt("1"); }
{ const a: boolean = new BigNumber(10).lt(new BigNumber(10)); }
{ const a: boolean = new BigNumber(10).le(1); }
{ const a: boolean = new BigNumber(10).le("1"); }
{ const a: boolean = new BigNumber(10).le(new BigNumber(10)); }
{ const a: BigNumber = new BigNumber(10).and(1); }
{ const a: BigNumber = new BigNumber(10).and("1"); }
{ const a: BigNumber = new BigNumber(10).and(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).or(1); }
{ const a: BigNumber = new BigNumber(10).or("1"); }
{ const a: BigNumber = new BigNumber(10).or(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).xor(1); }
{ const a: BigNumber = new BigNumber(10).xor("1"); }
{ const a: BigNumber = new BigNumber(10).xor(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).mod(1); }
{ const a: BigNumber = new BigNumber(10).mod("1"); }
{ const a: BigNumber = new BigNumber(10).mod(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).pow(1); }
{ const a: BigNumber = new BigNumber(10).pow("1"); }
{ const a: BigNumber = new BigNumber(10).pow(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).powm(1, 1); }
{ const a: BigNumber = new BigNumber(10).powm("1", 1); }
{ const a: BigNumber = new BigNumber(10).powm(new BigNumber(1), 1); }
{ const a: BigNumber = new BigNumber(10).powm(1, "1"); }
{ const a: BigNumber = new BigNumber(10).powm("1", "1"); }
{ const a: BigNumber = new BigNumber(10).powm(new BigNumber(1), "1"); }
{ const a: BigNumber = new BigNumber(10).powm(1, new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).powm("1", new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).powm(new BigNumber(1), new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).invertm(1); }
{ const a: BigNumber = new BigNumber(10).invertm("1"); }
{ const a: BigNumber = new BigNumber(10).invertm(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).rand(); }
{ const a: BigNumber = new BigNumber(10).rand(1); }
{ const a: BigNumber = new BigNumber(10).rand("1"); }
{ const a: BigNumber = new BigNumber(10).rand(new BigNumber(1)); }
{ const a: boolean | "maybe" = new BigNumber(10).probPrime(); }
{ const a: BigNumber = new BigNumber(10).nextPrime(); }
{ const a: BigNumber = new BigNumber(10).sqrt(); }
{ const a: BigNumber = new BigNumber(10).root(1); }
{ const a: BigNumber = new BigNumber(10).root("1"); }
{ const a: BigNumber = new BigNumber(10).root(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).shiftLeft(1); }
{ const a: BigNumber = new BigNumber(10).shiftLeft("1"); }
{ const a: BigNumber = new BigNumber(10).shiftLeft(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).shiftRight(1); }
{ const a: BigNumber = new BigNumber(10).shiftRight("1"); }
{ const a: BigNumber = new BigNumber(10).shiftRight(new BigNumber(1)); }
{ const a: BigNumber = new BigNumber(10).gcd(1); }
{ const a: BigNumber = new BigNumber(10).gcd("1"); }
{ const a: BigNumber = new BigNumber(10).gcd(new BigNumber(1)); }
{ const a: number = new BigNumber(10).jacobi(1); }
{ const a: number = new BigNumber(10).jacobi("1"); }
{ const a: number = new BigNumber(10).jacobi(new BigNumber(1)); }
{ const a: number = new BigNumber(10).bitLength(); }
{ const a: boolean = new BigNumber(10).isBitSet(10); }
{ const a: BigNumber = BigNumber.prime(10); }
{ const a: BigNumber = BigNumber.prime(10, true); }
{ const a: BigNumber = BigNumber.fromBuffer(Buffer.alloc(10)); }
{ const a: BigNumber = BigNumber.fromBuffer(Buffer.alloc(10), { endian: "little" }); }
{ const a: BigNumber = BigNumber.fromBuffer(Buffer.alloc(10), { endian: -1 }); }
{ const a: BigNumber = BigNumber.fromBuffer(Buffer.alloc(10), { endian: 1 }); }
{ const a: BigNumber = BigNumber.fromBuffer(Buffer.alloc(10), { endian: "big" }); }
{ const a: BigNumber = BigNumber.fromBuffer(Buffer.alloc(10), { size: "auto" }); }
{ const a: BigNumber = BigNumber.ONE; }
{ const a: BigNumber = BigNumber.ZERO; }
}
namespace bitSetTests {
const { BitSet } = math;
type BitSet = adone.math.BitSet;
new BitSet(10);
new BitSet(new BitSet(10).dehydrate());
{ const a: boolean = new BitSet(10).get(0); }
{ const a: boolean = new BitSet(10).set(0); }
{ const a: boolean = new BitSet(10).setRange(0, 10); }
{ const a: boolean = new BitSet(10).unset(0); }
{ const a: boolean = new BitSet(10).unsetRange(0, 10); }
{ const a: boolean = new BitSet(10).toggle(0); }
{ const a: boolean = new BitSet(10).toggleRange(0, 10); }
{ const a: boolean = new BitSet(10).clear(); }
{ const a: BitSet = new BitSet(10).clone(); }
{ const a: string = new BitSet(10).dehydrate(); }
{ const a: BitSet = new BitSet(10).and(1); }
{ const a: BitSet = new BitSet(10).and(new BitSet(10)); }
{ const a: BitSet = new BitSet(10).or(1); }
{ const a: BitSet = new BitSet(10).or(new BitSet(10)); }
{ const a: BitSet = new BitSet(10).xor(1); }
{ const a: BitSet = new BitSet(10).xor(new BitSet(10)); }
new BitSet(10).forEach((x: number) => {});
new BitSet(10).forEach((x: number) => false);
{ const a: BitSet = new BitSet(10).circularShift(10); }
{ const a: number = new BitSet(10).getCardinality(); }
{ const a: number[] = new BitSet(10).getIndices(); }
{ const a: boolean = new BitSet(10).isSubsetOf(new BitSet(10)); }
{ const a: boolean = new BitSet(10).isEmpty(); }
{ const a: boolean = new BitSet(10).isEqual(new BitSet(10)); }
{ const a: string = new BitSet(10).toString(); }
{ const a: number = new BitSet(10).ffs(); }
{ const a: number = new BitSet(10).ffs(1); }
{ const a: number = new BitSet(10).ffz(); }
{ const a: number = new BitSet(10).ffz(1); }
{ const a: number = new BitSet(10).fls(); }
{ const a: number = new BitSet(10).fls(1); }
{ const a: number = new BitSet(10).flz(); }
{ const a: number = new BitSet(10).flz(1); }
{ const a: number = new BitSet(10).nextSetBit(1); }
{ const a: number = new BitSet(10).nextUnsetBit(1); }
{ const a: number = new BitSet(10).previousSetBit(1); }
{ const a: number = new BitSet(10).previousUnsetBit(1); }
{ const a: number = new BitSet(10).readUInt(); }
{ const a: number = new BitSet(10).readUInt(1); }
{ const a: number = new BitSet(10).readUInt(1, 2); }
{ new BitSet(10).writeUInt(1); }
{ new BitSet(10).writeUInt(1, 2); }
{ new BitSet(10).writeUInt(1, 2, 3); }
{ const a: BitSet = BitSet.fromLong(new adone.math.Long(10, 20)); }
}
const {
math
} = adone;
namespace randomTests {
const { random } = math;
@@ -471,4 +9,22 @@ namespace mathTests {
random(100);
random(0, 10);
}
namespace maxTests {
const { max } = math;
max([]);
{ const a: number = max([1, 2, 3]); }
{ const a: string = max(["1", "2", "3"]); }
{ const a: string = max(["1", "2", "3"], (a) => a.length); }
{ const a: number = max([1, 2, 3], (a) => a.toExponential()); }
}
namespace minTests {
const { min } = math;
min([]);
{ const a: number = min([1, 2, 3]); }
{ const a: string = min(["1", "2", "3"]); }
{ const a: string = min(["1", "2", "3"], (a) => a.length); }
{ const a: number = min([1, 2, 3], (a) => a.toExponential()); }
}
}
+261
View File
@@ -0,0 +1,261 @@
namespace mathTests.longTests {
const {
math: {
Long
}
} = adone;
new Long();
new Long(0);
new Long(0, 0);
new Long(0, 0, true);
namespace toInt {
const a: number = new Long().toInt();
}
namespace toNumber {
const a: number = new Long().toNumber();
}
namespace toString {
const a: string = new Long().toString();
const b: string = new Long().toString(16);
}
namespace getHighBits {
const a: number = new Long().getHighBits();
}
namespace getLowBits {
const a: number = new Long().getLowBits();
}
namespace getLowBitsUnsigned {
const a: number = new Long().getLowBitsUnsigned();
}
namespace getHighBitsUnsigned {
const a: number = new Long().getHighBitsUnsigned();
}
namespace getNumBitsAbs {
const a: number = new Long().getNumBitsAbs();
}
namespace isZero {
const a: boolean = new Long().isZero();
}
namespace isNegative {
const a: boolean = new Long().isNegative();
}
namespace isPositive {
const a: boolean = new Long().isPositive();
}
namespace isOdd {
const a: boolean = new Long().isOdd();
}
namespace isEven {
const a: boolean = new Long().isEven();
}
namespace equals {
const a = new Long();
const b: boolean = a.equals(new Long());
const c: boolean = a.equals(1);
const d: boolean = a.equals("1");
const e: boolean = a.equals({ low: 0, high: 0 });
}
namespace lessThan {
const a = new Long();
const b: boolean = a.lessThan(new Long());
const c: boolean = a.lessThan(1);
const d: boolean = a.lessThan("1");
const e: boolean = a.lessThan({ low: 0, high: 0 });
}
namespace lessThanOrEqual {
const a = new Long();
const b: boolean = a.lessThanOrEqual(new Long());
const c: boolean = a.lessThanOrEqual(1);
const d: boolean = a.lessThanOrEqual("1");
const e: boolean = a.lessThanOrEqual({ low: 0, high: 0 });
}
namespace greaterThan {
const a = new Long();
const b: boolean = a.greaterThan(new Long());
const c: boolean = a.greaterThan(1);
const d: boolean = a.greaterThan("1");
const e: boolean = a.greaterThan({ low: 0, high: 0 });
}
namespace greaterThanOrEqual {
const a = new Long();
const b: boolean = a.greaterThanOrEqual(new Long());
const c: boolean = a.greaterThanOrEqual(1);
const d: boolean = a.greaterThanOrEqual("1");
const e: boolean = a.greaterThanOrEqual({ low: 0, high: 0 });
}
namespace compareTests {
const a = new Long();
const b: number = a.compare(new Long());
const c: number = a.compare(1);
const d: number = a.compare("1");
const e: number = a.compare({ low: 0, high: 0 });
}
namespace negate {
const a: adone.math.Long = new Long().negate();
}
namespace add {
const a = new Long();
const b: adone.math.Long = a.add(new Long());
const c: adone.math.Long = a.add(1);
const d: adone.math.Long = a.add("1");
const e: adone.math.Long = a.add({ low: 0, high: 0 });
}
namespace sub {
const a = new Long();
const b: adone.math.Long = a.sub(new Long());
const c: adone.math.Long = a.sub(1);
const d: adone.math.Long = a.sub("1");
const e: adone.math.Long = a.sub({ low: 0, high: 0 });
}
namespace mul {
const a = new Long();
const b: adone.math.Long = a.mul(new Long());
const c: adone.math.Long = a.mul(1);
const d: adone.math.Long = a.mul("1");
const e: adone.math.Long = a.mul({ low: 0, high: 0 });
}
namespace div {
const a = new Long();
const b: adone.math.Long = a.div(new Long());
const c: adone.math.Long = a.div(1);
const d: adone.math.Long = a.div("1");
const e: adone.math.Long = a.div({ low: 0, high: 0 });
}
namespace mod {
const a = new Long();
const b: adone.math.Long = a.mod(new Long());
const c: adone.math.Long = a.mod(1);
const d: adone.math.Long = a.mod("1");
const e: adone.math.Long = a.mod({ low: 0, high: 0 });
}
namespace not {
const a: adone.math.Long = new Long().not();
}
namespace and {
const a = new Long();
const b: adone.math.Long = a.and(new Long());
const c: adone.math.Long = a.and(1);
const d: adone.math.Long = a.and("1");
const e: adone.math.Long = a.and({ low: 0, high: 0 });
}
namespace or {
const a = new Long();
const b: adone.math.Long = a.or(new Long());
const c: adone.math.Long = a.or(1);
const d: adone.math.Long = a.or("1");
const e: adone.math.Long = a.or({ low: 0, high: 0 });
}
namespace xor {
const a = new Long();
const b: adone.math.Long = a.xor(new Long());
const c: adone.math.Long = a.xor(1);
const d: adone.math.Long = a.xor("1");
const e: adone.math.Long = a.xor({ low: 0, high: 0 });
}
namespace shl {
const a = new Long();
const b: adone.math.Long = a.shl(new Long());
const c: adone.math.Long = a.shl(1);
}
namespace shr {
const a = new Long();
const b: adone.math.Long = a.shr(new Long());
const c: adone.math.Long = a.shr(1);
}
namespace shru {
const a = new Long();
const b: adone.math.Long = a.shr(new Long());
const c: adone.math.Long = a.shr(1);
}
namespace toSigned {
const a: adone.math.Long = new Long().toSigned();
}
namespace toUnsigned {
const a: adone.math.Long = new Long().toUnsigned();
}
namespace toBytes {
const a: number[] = new Long().toBytes();
}
namespace toBytesLE {
const a: number[] = new Long().toBytesLE();
}
namespace static {
namespace fromInt {
const a: adone.math.Long = Long.fromInt(123);
const b: adone.math.Long = Long.fromInt(123, true);
}
namespace fromNumber {
const a: adone.math.Long = Long.fromNumber(123);
const b: adone.math.Long = Long.fromNumber(123, true);
}
namespace fromBits {
const a: adone.math.Long = Long.fromBits(0, 0);
const b: adone.math.Long = Long.fromBits(123, 0, true);
}
namespace fromString {
const a: adone.math.Long = Long.fromString("123");
const b: adone.math.Long = Long.fromString("123", true);
const c: adone.math.Long = Long.fromString("123", 16);
const d: adone.math.Long = Long.fromString("123", true, 16);
}
namespace fromValue {
const a: adone.math.Long = Long.fromValue(new Long());
const b: adone.math.Long = Long.fromValue(1);
const c: adone.math.Long = Long.fromValue("1");
const e: adone.math.Long = Long.fromValue({ low: 0, high: 0 });
}
namespace constants {
const a: adone.math.Long = Long.MIN_VALUE;
const b: adone.math.Long = Long.MAX_VALUE;
const c: adone.math.Long = Long.MAX_UNSIGNED_VALUE;
const d: adone.math.Long = Long.ZERO;
const e: adone.math.Long = Long.UZERO;
const f: adone.math.Long = Long.ONE;
const g: adone.math.Long = Long.UONE;
const h: adone.math.Long = Long.NEG_ONE;
}
}
}
+4
View File
@@ -7,7 +7,11 @@ namespace adoneTests.regex {
regex.filename().test("a");
regex.idn().test("a");
regex.ip4().test("a");
regex.ip4({ exact: true }).test("a");
regex.ip6().test("a");
regex.ip6({ exact: true }).test("a");
regex.ip().test("a");
regex.ip({ exact: true }).test("a");
regex.protocol().test("a");
regex.punycode().test("a");
regex.shebang().test("a");
+16
View File
@@ -54,4 +54,20 @@ namespace AdoneRootTests {
obj = adone.package;
{ const a: typeof adone.assertion.assert = adone.assert; }
{ const a: typeof adone.assertion.expect = adone.expect; }
namespace lodashTests {
adone.lodash.get({}, "a");
adone.lodash.defaults({}, {});
adone.lodash.zip([]);
}
namespace benchmarkTests {
const b = new adone.benchmark.Benchmark.Suite();
b.add(() => {}).add("", () => {}).run();
}
namespace asyncTests {
adone.async.all([], () => {});
adone.async.forEach([], () => {});
}
}
+12 -2
View File
@@ -22,6 +22,8 @@
"files": [
"adone-tests.ts",
"adone.d.ts",
"async.d.ts",
"benchmark.d.ts",
"glosses/archives.d.ts",
"glosses/assertion.d.ts",
"glosses/collections/array_set.d.ts",
@@ -43,7 +45,7 @@
"glosses/collections/refcounted_cache.d.ts",
"glosses/collections/set.d.ts",
"glosses/collections/stack.d.ts",
"glosses/collections/timedout_map.d.ts",
"glosses/collections/time_map.d.ts",
"glosses/compressors.d.ts",
"glosses/crypto/asn1.d.ts",
"glosses/crypto/ed25519.d.ts",
@@ -57,7 +59,11 @@
"glosses/fast.d.ts",
"glosses/fs.d.ts",
"glosses/is.d.ts",
"glosses/math/bignumber.d.ts",
"glosses/math/bitset.d.ts",
"glosses/math/decimal.d.ts",
"glosses/math/index.d.ts",
"glosses/math/long.d.ts",
"glosses/math/matrix.d.ts",
"glosses/math/simd.d.ts",
"glosses/meta.d.ts",
@@ -110,7 +116,7 @@
"test/glosses/collections/refcounted_cache.ts",
"test/glosses/collections/set.ts",
"test/glosses/collections/stack.ts",
"test/glosses/collections/timedout_map.ts",
"test/glosses/collections/time_map.ts",
"test/glosses/compressors.ts",
"test/glosses/crypto/asn1.ts",
"test/glosses/crypto/ed25519.ts",
@@ -123,7 +129,11 @@
"test/glosses/fast.ts",
"test/glosses/fs.ts",
"test/glosses/is.ts",
"test/glosses/math/bignumber.ts",
"test/glosses/math/bitset.ts",
"test/glosses/math/decimal.ts",
"test/glosses/math/index.ts",
"test/glosses/math/long.ts",
"test/glosses/math/matrix.ts",
"test/glosses/math/simd.ts",
"test/glosses/meta.ts",
+3 -6
View File
@@ -16,16 +16,13 @@
declare var AFRAME: AFrame.AFrameGlobal;
declare var hasNativeWebVRImplementation: boolean;
interface NodeSelector {
querySelector(selectors: 'a-scene'): AFrame.Scene;
interface Document {
createElement(tagName: string): AFrame.Entity;
querySelector(selectors: 'a-scene'): AFrame.Scene;
querySelector<T extends AFrame.Entity<any>>(selectors: string): T;
querySelectorAll(selectors: string): NodeListOf<AFrame.Entity<any> | Element>;
}
interface Document {
createElement(tagName: string): AFrame.Entity;
}
// Interfaces
declare namespace AFrame {
interface ObjectMap<T = any> {
+3 -3
View File
@@ -5,8 +5,8 @@ var mongoConnectionString = "mongodb://127.0.0.1/agenda";
var agenda = new Agenda({ db: { address: mongoConnectionString } });
agenda.define('delete old users', (job, done) => {
agenda.define<{ foo: Error }>('delete old users', (job, done) => {
done(job.attrs.data.foo)
});
agenda.on('ready', () => {
@@ -62,7 +62,7 @@ agenda.schedule('tomorrow at noon', ['printAnalyticsReport', 'sendNotifications'
agenda.now('do the hokey pokey');
var job = agenda.create('printAnalyticsReport', { userCount: 100 });
var job = agenda.create<{ userCount: number }>('printAnalyticsReport', { userCount: 100 });
job.save(function(err) {
console.log("Job successfully saved");
});
+31 -26
View File
@@ -1,6 +1,7 @@
// Type definitions for Agenda v1.0.0
// Project: https://github.com/rschmukler/agenda
// Type definitions for Agenda v1.0.3
// Project: https://github.com/agenda/agenda
// Definitions by: Meir Gottlieb <https://github.com/meirgottlieb>
// Jeff Principe <https://github.com/princjef>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -89,14 +90,14 @@ declare class Agenda extends EventEmitter {
* @param name The name of the job.
* @param data Data to associated with the job.
*/
create(name: string, data?: any): Agenda.Job;
create<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(name: string, data?: T): Agenda.Job<T>;
/**
* Find all Jobs matching `query` and pass same back in cb().
* @param query
* @param cb
*/
jobs(query: any, cb: ResultCallback<Agenda.Job[]>): void;
jobs<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(query: any, cb: ResultCallback<Agenda.Job<T>[]>): void;
/**
* Removes all jobs in the database without defined behaviors. Useful if you change a definition name and want
@@ -113,8 +114,8 @@ declare class Agenda extends EventEmitter {
* @param options The options for the job.
* @param handler The handler to execute.
*/
define(name: string, handler: (job: Agenda.Job, done: (err?: Error) => void) => void): void;
define(name: string, options: Agenda.JobOptions, handler: (job: Agenda.Job, done: (err?: Error) => void) => void): void;
define<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(name: string, handler: (job: Agenda.Job<T>, done: (err?: Error) => void) => void): void;
define<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(name: string, options: Agenda.JobOptions, handler: (job: Agenda.Job<T>, done: (err?: Error) => void) => void): void;
/**
* Runs job name at the given interval. Optionally, data and options can be passed in.
@@ -124,8 +125,8 @@ declare class Agenda extends EventEmitter {
* @param options An optional argument that will be passed to job.repeatEvery.
* @param cb An optional callback function which will be called when the job has been persisted in the database.
*/
every(interval: number | string, names: string, data?: any, options?: any, cb?: ResultCallback<Agenda.Job>): Agenda.Job;
every(interval: number | string, names: string[], data?: any, options?: any, cb?: ResultCallback<Agenda.Job[]>): Agenda.Job[];
every<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(interval: number | string, names: string, data?: T, options?: any, cb?: ResultCallback<Agenda.Job<T>>): Agenda.Job<T>;
every<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(interval: number | string, names: string[], data?: T, options?: any, cb?: ResultCallback<Agenda.Job<T>[]>): Agenda.Job<T>[];
/**
* Schedules a job to run name once at a given time.
@@ -134,8 +135,8 @@ declare class Agenda extends EventEmitter {
* @param data An optional argument that will be passed to the processing function under job.attrs.data.
* @param cb An optional callback function which will be called when the job has been persisted in the database.
*/
schedule(when: Date | string, names: string, data?: any, cb?: ResultCallback<Agenda.Job>): Agenda.Job;
schedule(when: Date | string, names: string[], data?: any, cb?: ResultCallback<Agenda.Job[]>): Agenda.Job[];
schedule<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(when: Date | string, names: string, data?: T, cb?: ResultCallback<Agenda.Job<T>>): Agenda.Job<T>;
schedule<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(when: Date | string, names: string[], data?: T, cb?: ResultCallback<Agenda.Job<T>[]>): Agenda.Job<T>[];
/**
* Schedules a job to run name once immediately.
@@ -143,7 +144,7 @@ declare class Agenda extends EventEmitter {
* @param data An optional argument that will be passed to the processing function under job.attrs.data.
* @param cb An optional callback function which will be called when the job has been persisted in the database.
*/
now(name: string, data?: any, cb?: ResultCallback<Agenda.Job>): Agenda.Job;
now<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(name: string, data?: T, cb?: ResultCallback<Agenda.Job<T>>): Agenda.Job<T>;
/**
* Cancels any jobs matching the passed mongodb-native query, and removes them from the database.
@@ -242,10 +243,14 @@ declare namespace Agenda {
}
}
interface JobAttributesData {
[key: string]: any;
}
/**
* The database record associated with a job.
*/
interface JobAttributes {
interface JobAttributes<T extends JobAttributesData = JobAttributesData> {
/**
* The record identity.
*/
@@ -264,7 +269,7 @@ declare namespace Agenda {
/**
* The job details.
*/
data: { [name: string]: any };
data: T;
/**
* The priority of the job.
@@ -330,12 +335,12 @@ declare namespace Agenda {
/**
* A scheduled job.
*/
interface Job {
interface Job<T extends JobAttributesData = JobAttributesData> {
/**
* The database record associated with the job.
*/
attrs: JobAttributes;
attrs: JobAttributes<T>;
/**
* The agenda that created the job.
@@ -348,54 +353,54 @@ declare namespace Agenda {
* @param options An optional argument that can include a timezone field. The timezone should be a string as
* accepted by moment-timezone and is considered when using an interval in the cron string format.
*/
repeatEvery(interval: string | number, options?: { timezone?: string }): Job
repeatEvery(interval: string | number, options?: { timezone?: string }): Job<T>
/**
* Specifies a time when the job should repeat. [Possible values](https://github.com/matthewmueller/date#examples).
* @param time
*/
repeatAt(time: string): Job
repeatAt(time: string): Job<T>
/**
* Disables the job.
*/
disable(): Job;
disable(): Job<T>;
/**
* Enables the job.
*/
enable(): Job;
enable(): Job<T>;
/**
* Ensure that only one instance of this job exists with the specified properties
* @param value The properties associated with the job that must be unqiue.
* @param opts
*/
unique(value: any, opts?: { insertOnly?: boolean }): Job;
unique(value: any, opts?: { insertOnly?: boolean }): Job<T>;
/**
* Specifies the next time at which the job should run.
* @param time The next time at which the job should run.
*/
schedule(time: string | Date): Job;
schedule(time: string | Date): Job<T>;
/**
* Specifies the priority weighting of the job.
* @param value The priority of the job (lowest|low|normal|high|highest|number).
*/
priority(value: string | number): Job;
priority(value: string | number): Job<T>;
/**
* Sets job.attrs.failedAt to now, and sets job.attrs.failReason to reason.
* @param reason A message or Error object that indicates why the job failed.
*/
fail(reason: string | Error): Job;
fail(reason: string | Error): Job<T>;
/**
* Runs the given job and calls callback(err, job) upon completion. Normally you never need to call this manually
* @param cb Called when the job is completed.
*/
run(cb?: ResultCallback<Job>): Job;
run(cb?: ResultCallback<Job<T>>): Job<T>;
/**
* Returns true if the job is running; otherwise, returns false.
@@ -406,7 +411,7 @@ declare namespace Agenda {
* Saves the job into the database.
* @param cb Called when the job is saved.
*/
save(cb?: ResultCallback<Job>): Job;
save(cb?: ResultCallback<Job<T>>): Job<T>;
/**
* Removes the job from the database and cancels the job.
@@ -424,7 +429,7 @@ declare namespace Agenda {
/**
* Calculates next time the job should run
*/
computeNextRunAt(): Job;
computeNextRunAt(): Job<T>;
}
interface JobOptions {
+2 -11
View File
@@ -805,11 +805,7 @@ declare namespace algoliasearch {
* @param err() error callback
* https://www.algolia.com/doc/api-reference/api-methods/search-for-facet-values/
*/
searchForFacetValues({
facetName,
facetQuery,
...qp,
}: {
searchForFacetValues(options: {
facetName: string;
facetQuery: string;
} & AlgoliaQueryParameters): Promise<any>;
@@ -820,12 +816,7 @@ declare namespace algoliasearch {
* @param err() error callback
* https://www.algolia.com/doc/api-reference/api-methods/search-for-facet-values/
*/
searchForFacetValues(
{
facetName,
facetQuery,
...qp,
}: {
searchForFacetValues(options: {
facetName: string;
facetQuery: string;
} & AlgoliaQueryParameters,
+57
View File
@@ -0,0 +1,57 @@
import Message = require('amp-message');
// $ExpectType Message
new Message(new Buffer('aaa'));
// $ExpectType Message
new Message([new Buffer('aaa'), new Buffer('bbb')]);
const message = new Message([new Buffer('aaa'), new Buffer('bbb')]);
// $ExpectType string
message.inspect();
// $ExpectType Buffer
message.toBuffer();
// $ExpectType number
message.push(new Buffer('ccc'));
// $ExpectType Buffer | undefined
message.pop();
// $ExpectType Buffer | undefined
message.shift();
// $ExpectType number
message.unshift(new Buffer('ddd'));
// $ExpectError
new Message();
// $ExpectError
new Message(1);
// $ExpectError
new Message({});
// $ExpectError
new Message('aaa');
// $ExpectError
message.push(1);
// $ExpectError
message.push({});
// $ExpectError
message.push('aaa');
// $ExpectError
message.unshift(1);
// $ExpectError
message.unshift({});
// $ExpectError
message.unshift('aaa');
+25
View File
@@ -0,0 +1,25 @@
// Type definitions for amp-message 0.1
// Project: https://github.com/visionmedia/node-amp-message
// Definitions by: Vilim Stubičan <https://github.com/jewbre>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
/// <reference types="node" />
declare class Message {
constructor(args: Buffer | Buffer[]);
inspect(): string;
toBuffer(): Buffer;
push(...items: Buffer[]): number;
pop(): Buffer | undefined;
shift(): Buffer | undefined;
unshift(...items: Buffer[]): number;
}
export = Message;
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"amp-message-tests.ts"
]
}
+44
View File
@@ -0,0 +1,44 @@
import { decode, encode, Stream } from 'amp';
// $ExpectType Buffer[]
decode(new Buffer('something'));
// $ExpectType Buffer
encode([new Buffer('something'), new Buffer('something')]);
// $ExpectError
decode('');
// $ExpectError
decode(1);
// $ExpectError
decode();
// $ExpectError
encode('');
// $ExpectError
encode(1);
// $ExpectError
encode();
// $ExpectType Stream
new Stream({});
// $ExpectType Stream
new Stream({
highWaterMark: 1,
decodeStrings: true,
objectMode: true,
destroy: (error?: Error) => {
return 'handle error';
},
final: (callback: (error?: Error) => void) => {
// do nothing
}
});
// $ExpectError
new Stream({somethingNoneExisting: true});
+19
View File
@@ -0,0 +1,19 @@
// Type definitions for amp 0.3
// Project: https://github.com/visionmedia/node-amp
// Definitions by: Vilim Stubičan <https://github.com/jewbre>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
/// <reference types="node" />
import * as stream from 'stream';
export function decode(buf: Buffer): Buffer[];
export function encode(args: Buffer[]): Buffer;
export class Stream extends stream.Writable {
constructor(opts: stream.WritableOptions);
_write(chunk: any, encoding: string, fn: () => void): void;
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"amp-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1 -1
View File
@@ -1,6 +1,6 @@
// Type definitions for amqplib 0.5
// Project: https://github.com/squaremo/amqp.node
// Definitions by: Michael Nahkies <https://github.com/mnahkies>, Ab Reitsma <https://github.com/abreits>, Nicolás Fantone <https://github.com/nfantone>
// Definitions by: Michael Nahkies <https://github.com/mnahkies>, Ab Reitsma <https://github.com/abreits>, Nicolás Fantone <https://github.com/nfantone>, Nick Zelei <https://github.com/zelein>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
+48 -2
View File
@@ -141,6 +141,52 @@ export namespace Options {
export interface Message {
content: Buffer;
fields: any;
properties: any;
fields: MessageFields;
properties: MessageProperties;
}
export interface MessageFields {
deliveryTag: number;
redelivered: boolean;
exchange: string;
routingKey: string;
messageCount: string;
}
export interface MessageProperties {
contentType: any | undefined;
contentEncoding: any | undefined;
headers: MessagePropertyHeaders;
deliveryMode: any | undefined;
priority: any | undefined;
correlationId: any | undefined;
replyTo: any | undefined;
expiration: any | undefined;
messageId: any | undefined;
timestamp: any | undefined;
type: any | undefined;
userId: any | undefined;
appId: any | undefined;
clusterId: any | undefined;
}
export interface MessagePropertyHeaders {
"x-first-death-exchange"?: string;
"x-first-death-queue"?: string;
"x-first-death-reason"?: string;
"x-death"?: XDeath[];
[key: string]: any;
}
export interface XDeath {
count: number;
reason: "rejected" | "expired" | "maxlen";
queue: string;
time: {
"!": "timestamp";
value: number;
};
exchange: string;
"original-expiration"?: any;
"routing-keys": string[];
}
@@ -8,7 +8,8 @@ myApp.config((
$mdAriaProvider: ng.material.IAriaProvider,
$mdThemingProvider: ng.material.IThemingProvider,
$mdIconProvider: ng.material.IIconProvider,
$mdProgressCircularProvider: ng.material.IProgressCircularProvider) => {
$mdProgressCircularProvider: ng.material.IProgressCircularProvider,
$mdDialogProvider: ng.material.IDialogProvider) => {
$mdThemingProvider.alwaysWatchTheme(true);
const neonRedMap: ng.material.IPalette = $mdThemingProvider.extendPalette('red', {
500: 'ff0000'
@@ -56,6 +57,23 @@ myApp.config((
// Globally disables all ARIA warnings.
$mdAriaProvider.disableWarnings();
// Add custom dialog preset
$mdDialogProvider.addPreset('testPreset', {
methods: ['entityName'],
options: () => {
return {
template:
'<md-dialog>' +
'This is a custom preset' +
'</md-dialog>',
controllerAs: 'dialog',
bindToController: true,
clickOutsideToClose: true,
escapeToClose: true
};
}
});
});
myApp.controller('BottomSheetController', ($scope: TestScope, $mdBottomSheet: ng.material.IBottomSheetService, $q: ng.IQService) => {
@@ -192,6 +210,11 @@ myApp.controller('DialogController', ($scope: TestScope, $mdDialog: ng.material.
onComplete: (scope, element) => { },
onRemoving: (element, removePromise) => { },
});
// Show custom dialog preset
$mdDialog.show(
$mdDialog['testPreset']().entityName('Product #6')
);
});
class IconDirective implements ng.IDirective {
+10 -1
View File
@@ -125,6 +125,11 @@ declare module 'angular' {
}
interface IDialogService {
// indexer used to call preset dialog created with $mdDialogProvider
// see: https://material.angularjs.org/latest/api/service/$mdDialog#custom-presets
// tslint:disable-next-line:ban-types
[presetName: string]: Function;
show(dialog: IDialogOptions | IAlertDialog | IConfirmDialog | IPromptDialog): IPromise<any>;
confirm(): IConfirmDialog;
alert(): IAlertDialog;
@@ -133,6 +138,10 @@ declare module 'angular' {
cancel(response?: any): void;
}
interface IDialogProvider {
addPreset(presetName: string, presetOptions: { methods?: ReadonlyArray<string>, options: () => IDialogOptions }): IDialogProvider;
}
type IIcon = (id: string) => IPromise<Element>; // id is a unique ID or URL
interface IIconProvider {
@@ -223,7 +232,7 @@ declare module 'angular' {
contrastDefaultColor?: string;
contrastDarkColors?: string | string[];
contrastLightColors?: string | string[];
contrastStrongLightColors?: string|string[];
contrastStrongLightColors?: string | string[];
}
interface IThemeHues {
+2 -1
View File
@@ -40,7 +40,8 @@ $routeProvider
}
})
.otherwise({ redirectTo: '/' })
.otherwise({ redirectTo: ($routeParams?: ng.route.IRouteParamsService, $locationPath?: string, $locationSearch?: any) => "" });
.otherwise({ redirectTo: ($routeParams?: ng.route.IRouteParamsService, $locationPath?: string, $locationSearch?: any) => "" })
.otherwise("/");
var current: ng.route.ICurrentRoute;
+1 -1
View File
@@ -138,7 +138,7 @@ declare module 'angular' {
*
* @params Mapping information to be assigned to $route.current.
*/
otherwise(params: IRoute): IRouteProvider;
otherwise(params: IRoute | string): IRouteProvider;
/**
* Adds a new route definition to the $route service.
*
+2 -2
View File
@@ -1,5 +1,5 @@
import * as React from "react";
import { StyleSheet, css, StyleSheetServer, StyleSheetTestUtils } from "aphrodite";
import { StyleSheet, css, StyleSheetServer, StyleSheetTestUtils, FontFamily } from "aphrodite";
const styles = StyleSheet.create({
red: {
@@ -20,7 +20,7 @@ const styles = StyleSheet.create({
}
});
const coolFont = {
const coolFont: FontFamily = {
fontFamily: "CoolFont",
fontStyle: "normal",
fontWeight: "normal",
+25 -2
View File
@@ -4,13 +4,36 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
import * as React from "react";
import * as CSS from "csstype";
type BaseCSSProperties = CSS.Properties<number | string>;
type FontFamily =
| BaseCSSProperties['fontFamily']
| CSS.FontFace;
// Replace with Exclude once on 2.8+
type Diff<T extends string, U extends string> = (
& { [P in T]: P }
& { [P in U]: never }
& { [x: string]: never }
)[T];
type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>;
type CSSProperties = Omit<BaseCSSProperties, 'fontFamily'> & {
fontFamily?: FontFamily | FontFamily[];
};
// For pseudo selectors and media queries
interface OpenCSSProperties extends CSSProperties {
[k: string]: CSSProperties[keyof CSSProperties] | CSSProperties;
}
/**
* Aphrodite style declaration
*/
export interface StyleDeclaration {
[key: string]: React.CSSProperties;
[key: string]: OpenCSSProperties;
}
interface StyleSheetStatic {
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"csstype": "^2.2.0"
}
}
+1 -1
View File
@@ -64,6 +64,6 @@ archiver.setModule(() => {});
archiver.pointer();
archiver.use(() => {});
archiver.finalize().then();
archiver.finalize();
archiver.symlink('./path', './target');
+1 -1
View File
@@ -35,7 +35,7 @@ declare namespace archiver {
directory(dirpath: string, destpath: false | string, data?: EntryData | EntryDataFunction): this;
file(filename: string, data: EntryData): this;
glob(pattern: string, options?: glob.IOptions, data?: EntryData): this;
finalize(): Promise<void>;
finalize(): void;
setFormat(format: string): this;
setModule(module: Function): this;
+9
View File
@@ -0,0 +1,9 @@
import arrayUnique = require("array-unique");
arrayUnique([1, 1, 2, 3, 3]);
arrayUnique(["foo", "foo", "bar", "foo"]);
arrayUnique.immutable([1, 1, 2, 3, 3]);
arrayUnique.immutable(["foo", "foo", "bar", "foo"]);
+12
View File
@@ -0,0 +1,12 @@
// Type definitions for array-unique 0.3
// Project: https://github.com/jonschlinkert/array-unique
// Definitions by: Michaël St-Georges <https://github.com/CSLTech>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function arrayUnique<T>(arr: T[]): T[];
declare namespace arrayUnique {
function immutable<T>(arr: ReadonlyArray<T>): T[];
}
export = arrayUnique;
@@ -2,7 +2,7 @@
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5"
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
@@ -18,7 +18,6 @@
},
"files": [
"index.d.ts",
"colors-tests.ts",
"safe.d.ts"
"array-unique-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1 -1
View File
@@ -1,4 +1,4 @@
import arrify = require("arrify");
import * as arrify from 'arrify';
arrify(null);
arrify<number>(null);
+1
View File
@@ -14,4 +14,5 @@
* arrify([2, 3]) // returns [2, 3]
*/
declare function arrify<T>(val: undefined | null | T | T[]): T[];
declare namespace arrify {}
export = arrify;
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://github.com/sporto/assets-webpack-plugin
// Definitions by: Michael Strobel <https://github.com/kryops>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
// TypeScript Version: 2.3
import * as webpack from 'webpack';
+2 -1
View File
@@ -1,4 +1,5 @@
import { Options, RetryFunction, retry } from 'async-retry';
import { Options, RetryFunction } from 'async-retry';
import retry = require("async-retry");
const o: Options = {
retries: 1,
+18 -10
View File
@@ -1,17 +1,25 @@
// Type definitions for async-retry 1.1
// Type definitions for async-retry 1.2
// Project: https://github.com/zeit/async-retry#readme
// Definitions by: Albert Wu <https://github.com/albertywu>
// Pablo Rodríguez <https://github.com/MeLlamoPablo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export function retry<A>(fn: RetryFunction<A>, opts: Options): Promise<A>;
declare function AsyncRetry<A>(
fn: AsyncRetry.RetryFunction<A>,
opts: AsyncRetry.Options
): Promise<A>;
export interface Options {
retries?: number;
factor?: number;
minTimeout?: number;
maxTimeout?: number;
randomize?: boolean;
onRetry?: (e: Error) => any;
declare namespace AsyncRetry {
interface Options {
retries?: number;
factor?: number;
minTimeout?: number;
maxTimeout?: number;
randomize?: boolean;
onRetry?: (e: Error) => any;
}
type RetryFunction<A> = (bail: (e: Error) => A, attempt: number) => A|Promise<A>;
}
export type RetryFunction<A> = (bail: (e: Error) => A, attempt: number) => A|Promise<A>;
export = AsyncRetry;
+21 -43
View File
@@ -7,6 +7,7 @@
export as namespace async;
export interface Dictionary<T> { [key: string]: T; }
export type IterableCollection<T> = T[] | IterableIterator<T> | Dictionary<T>
export interface ErrorCallback<T> { (err?: T): void; }
export interface AsyncBooleanResultCallback<E> { (err?: E, truthValue?: boolean): void; }
@@ -36,11 +37,9 @@ export interface AsyncQueue<T> {
running(): number;
idle(): boolean;
concurrency: number;
push<E>(task: T, callback?: ErrorCallback<E>): void;
push<E>(task: T | T[], callback?: ErrorCallback<E>): void;
push<R,E>(task: T, callback?: AsyncResultCallback<R, E>): void;
push<E>(task: T[], callback?: ErrorCallback<E>): void;
unshift<E>(task: T, callback?: ErrorCallback<E>): void;
unshift<E>(task: T[], callback?: ErrorCallback<E>): void;
unshift<E>(task: T | T[], callback?: ErrorCallback<E>): void;
saturated: () => any;
empty: () => any;
drain: () => any;
@@ -62,8 +61,7 @@ export interface AsyncPriorityQueue<T> {
concurrency: number;
started: boolean;
paused: boolean;
push<R,E>(task: T, priority: number, callback?: AsyncResultArrayCallback<R, E>): void;
push<R,E>(task: T[], priority: number, callback?: AsyncResultArrayCallback<R, E>): void;
push<R,E>(task: T | T[], priority: number, callback?: AsyncResultArrayCallback<R, E>): void;
saturated: () => any;
empty: () => any;
drain: () => any;
@@ -86,7 +84,6 @@ export interface AsyncCargo {
length(): number;
payload?: number;
push(task: any, callback? : Function): void;
push(task: any[], callback? : Function): void;
saturated(): void;
empty(): void;
drain(): void;
@@ -97,39 +94,28 @@ export interface AsyncCargo {
}
// Collections
export function each<T, E>(arr: T[] | IterableIterator<T>, iterator: AsyncIterator<T, E>, callback?: ErrorCallback<E>): void;
export function each<T, E>(arr: Dictionary<T>, iterator: AsyncIterator<T, E>, callback?: ErrorCallback<E>): void;
export function each<T, E>(arr: IterableCollection<T>, iterator: AsyncIterator<T, E>, callback?: ErrorCallback<E>): void;
export const eachSeries: typeof each;
export function eachLimit<T, E>(arr: T[] | IterableIterator<T>, limit: number, iterator: AsyncIterator<T, E>, callback?: ErrorCallback<E>): void;
export function eachLimit<T, E>(arr: Dictionary<T>, limit: number, iterator: AsyncIterator<T, E>, callback?: ErrorCallback<E>): void;
export function eachLimit<T, E>(arr: IterableCollection<T>, limit: number, iterator: AsyncIterator<T, E>, callback?: ErrorCallback<E>): void;
export const forEach: typeof each;
export const forEachSeries: typeof each;
export const forEachLimit: typeof eachLimit;
export function forEachOf<T, E>(obj: T[] | IterableIterator<T>, iterator: AsyncForEachOfIterator<T, E>, callback?: ErrorCallback<E>): void;
export function forEachOf<T, E>(obj: Dictionary<T>, iterator: AsyncForEachOfIterator<T, E>, callback?: ErrorCallback<E>): void;
export function forEachOf<T, E>(obj: IterableCollection<T>, iterator: AsyncForEachOfIterator<T, E>, callback?: ErrorCallback<E>): void;
export const forEachOfSeries: typeof forEachOf;
export function forEachOfLimit<T, E>(obj: T[] | IterableIterator<T>, limit: number, iterator: AsyncForEachOfIterator<T, E>, callback?: ErrorCallback<E>): void;
export function forEachOfLimit<T, E>(obj: Dictionary<T>, limit: number, iterator: AsyncForEachOfIterator<T, E>, callback?: ErrorCallback<E>): void;
export function forEachOfLimit<T, E>(obj: IterableCollection<T>, limit: number, iterator: AsyncForEachOfIterator<T, E>, callback?: ErrorCallback<E>): void;
export const eachOf: typeof forEachOf;
export const eachOfSeries: typeof forEachOf;
export const eachOfLimit: typeof forEachOfLimit;
export function map<T, R, E>(arr: T[] | IterableIterator<T>, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function map<T, R, E>(arr: Dictionary<T>, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;
export const mapSeries: typeof map;
export function mapLimit<T, R, E>(
arr: T[] | Dictionary<T> | IterableIterator<T>,
limit: number,
iterator: AsyncResultIterator<T, R, E>,
callback?: AsyncResultArrayCallback<R, E>
): void;
export function mapLimit<T, R, E>(arr: IterableCollection<T>, limit: number, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function mapValuesLimit<T, R, E>(obj: Dictionary<T>, limit: number, iteratee: (value: T, key: string, callback: AsyncResultCallback<R, E>) => void, callback: AsyncResultObjectCallback<R, E>): void;
export function mapValues<T, R, E>(obj: Dictionary<T>, iteratee: (value: T, key: string, callback: AsyncResultCallback<R, E>) => void, callback: AsyncResultObjectCallback<R, E>): void;
export const mapValuesSeries: typeof mapValues;
export function filter<T, E>(arr: T[] | IterableIterator<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultArrayCallback<T, E>): void;
export function filter<T, E>(arr: Dictionary<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultArrayCallback<T, E>): void;
export function filter<T, E>(arr: IterableCollection<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultArrayCallback<T, E>): void;
export const filterSeries: typeof filter;
export function filterLimit<T, E>(arr: T[] | IterableIterator<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultArrayCallback<T, E>): void;
export function filterLimit<T, E>(arr: Dictionary<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultArrayCallback<T, E>): void;
export function filterLimit<T, E>(arr: IterableCollection<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultArrayCallback<T, E>): void;
export const select: typeof filter;
export const selectSeries: typeof filter;
export const selectLimit: typeof filterLimit;
@@ -141,36 +127,28 @@ export const inject: typeof reduce;
export const foldl: typeof reduce;
export const reduceRight: typeof reduce;
export const foldr: typeof reduce;
export function detect<T, E>(arr: T[] | IterableIterator<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultCallback<T, E>): void;
export function detect<T, E>(arr: Dictionary<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultCallback<T, E>): void;
export function detect<T, E>(arr: IterableCollection<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultCallback<T, E>): void;
export const detectSeries: typeof detect;
export function detectLimit<T, E>(arr: T[] | IterableIterator<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultCallback<T, E>): void;
export function detectLimit<T, E>(arr: Dictionary<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultCallback<T, E>): void;
export function detectLimit<T, E>(arr: IterableCollection<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultCallback<T, E>): void;
export const find: typeof detect;
export const findSeries: typeof detect;
export const findLimit: typeof detectLimit;
export function sortBy<T, V, E>(arr: T[] | IterableIterator<T>, iterator: AsyncResultIterator<T, V, E>, callback?: AsyncResultArrayCallback<T, E>): void;
export function some<T, E>(arr: T[] | IterableIterator<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export function some<T, E>(arr: Dictionary<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export function some<T, E>(arr: IterableCollection<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export const someSeries: typeof some;
export function someLimit<T, E>(arr: T[] | IterableIterator<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export function someLimit<T, E>(arr: Dictionary<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export function someLimit<T, E>(arr: IterableCollection<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export const any: typeof some;
export const anySeries: typeof someSeries;
export const anyLimit: typeof someLimit;
export function every<T, E>(arr: T[] | IterableIterator<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export function every<T, E>(arr: Dictionary<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export function every<T, E>(arr: IterableCollection<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export const everySeries: typeof every;
export function everyLimit<T, E>(arr: T[] | IterableIterator<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export function everyLimit<T, E>(arr: Dictionary<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export function everyLimit<T, E>(arr: IterableCollection<T>, limit: number, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncBooleanResultCallback<E>): void;
export const all: typeof every;
export const allSeries: typeof every;
export const allLimit: typeof everyLimit;
export function concat<T, R, E>(arr: T[] | IterableIterator<T>, iterator: AsyncResultIterator<T, R[], E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function concat<T, R, E>(arr: Dictionary<T>, iterator: AsyncResultIterator<T, R[], E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function concatLimit<T, R, E>(arr: T[] | IterableIterator<T>, limit: number, iterator: AsyncResultIterator<T, R[], E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function concatLimit<T, R, E>(arr: Dictionary<T>, limit: number,iterator: AsyncResultIterator<T, R[], E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function concat<T, R, E>(arr: IterableCollection<T>, iterator: AsyncResultIterator<T, R[], E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function concatLimit<T, R, E>(arr: IterableCollection<T>, limit: number, iterator: AsyncResultIterator<T, R[], E>, callback?: AsyncResultArrayCallback<R, E>): void;
export const concatSeries: typeof concat;
// Control Flow
@@ -190,8 +168,8 @@ export function forever<E>(next: (next : ErrorCallback<E>) => void, errBack: Err
export function waterfall<T, E>(tasks: Function[], callback?: AsyncResultCallback<T, E | Error>): void;
export function compose(...fns: Function[]): Function;
export function seq(...fns: Function[]): Function;
export function applyEach(fns: Function[], argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
export function applyEachSeries(fns: Function[], argsAndCallback: any[]): void; // applyEachSeries(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
export function applyEach(fns: Function[], ...argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
export function applyEachSeries(fns: Function[], ...argsAndCallback: any[]): void; // applyEachSeries(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
export function queue<T, E>(worker: AsyncWorker<T, E>, concurrency?: number): AsyncQueue<T>;
export function queue<T, R, E>(worker: AsyncResultIterator<T, R, E>, concurrency?: number): AsyncQueue<T>;
export function priorityQueue<T, E>(worker: AsyncWorker<T, E>, concurrency: number): AsyncPriorityQueue<T>;
+2
View File
@@ -2,6 +2,7 @@
// Project: https://github.com/Atmosphere/atmosphere-javascript
// Definitions by: Kai Toedter <https://github.com/toedter>
// Fedor Kirpichev <https://github.com/Mory1879>
// Jorge Beltran <https://github.com/Scipion>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Use this typings in future instead of deprecated 'atmosphere'.
@@ -65,6 +66,7 @@ declare namespace Atmosphere {
maxReconnectOnClose?: number;
enableProtocol?: boolean;
pollingInterval?: number;
webSocketUrl?: string;
onError?: (response?:Response) => void;
onClose?: (response?:Response) => void;
+40 -8
View File
@@ -43,7 +43,7 @@ declare let marker: Atom.Marker;
declare let markers: Atom.Marker[];
declare let markerLayer: Atom.MarkerLayer;
declare let notification: Atom.Notification;
declare let notifications: Atom.Notification[];
declare let notifications: ReadonlyArray<Atom.Notification>;
declare let pack: Atom.Package;
declare let packs: Atom.Package[];
declare let pane: Atom.Pane;
@@ -56,10 +56,12 @@ declare let posArr: Atom.Point[];
declare let project: Atom.Project;
declare let range: Atom.Range;
declare let ranges: Atom.Range[];
declare let readonlyStrs: ReadonlyArray<string>;
declare let registry: Atom.GrammarRegistry;
declare let repository: Atom.GitRepository;
declare let repositories: Atom.GitRepository[];
declare let scopeDescriptor: Atom.ScopeDescriptor;
declare let scopes: ReadonlyArray<string>;
declare let selection: Atom.Selection;
declare let selections: Atom.Selection[];
declare let styleManager: Atom.StyleManager;
@@ -86,6 +88,10 @@ function testAtomEnvironment() {
{ label: "Undo", command: "core:undo" },
{ label: "Redo", command: "core:redo" },
],
after: ["test"],
before: ["test"],
afterGroupContaining: ["test"],
beforeGroupContaining: ["test"]
}],
});
@@ -188,6 +194,10 @@ function testAtomEnvironment() {
// Messaging the User
atom.beep();
atom.confirm({ defaultId: 42 }, (response, checked) => {
num = response;
bool = checked;
});
atom.confirm({ message: "Test" });
atom.confirm({ message: "Test", buttons: [ "a", "b" ], detailedMessage: "Test" });
num = atom.confirm({ message: "Test", detailedMessage: "Test", buttons: {
@@ -270,13 +280,19 @@ function testCommandRegistry() {
"test-function2": (event) => {},
});
atom.commands.add("test", "test:function", {
didDispatch: (event) => event.stopImmediatePropagation(),
didDispatch: (event) => {
event.stopImmediatePropagation();
},
description: "A Command Test",
displayName: "Command: Test",
});
atom.commands.add("atom-text-editor", {
"test-function": (event) => event.currentTarget.getModel(),
"test-function2": (event) => event.currentTarget.getComponent(),
"test-function": (event) => {
event.currentTarget.getModel();
},
"test-function2": (event) => {
event.currentTarget.getComponent();
}
});
atom.commands.add("atom-workspace", {
"test-command": {
@@ -345,7 +361,7 @@ function testConfig() {
const allConfigValues = atom.config.getAll("test");
for (const { scopeDescriptor, value } of allConfigValues) {
scopeDescriptor.scopes;
scopes = scopeDescriptor.getScopesArray();
}
atom.config.getAll("test", { scope: scopeDescriptor });
atom.config.getAll("test", { excludeSources: ["test"] });
@@ -719,6 +735,9 @@ function testDisplayMarker() {
// DisplayMarkerLayer =========================================================
function testDisplayMarkerLayer() {
// Properties
str = displayMarkerLayer.id;
// Lifecycle
displayMarkerLayer.destroy();
displayMarkerLayer.clear();
@@ -850,6 +869,7 @@ function testDock() {
subscription = dock.onDidDestroyPaneItem(event => {
event.index && event.item && event.pane;
});
subscription = dock.onDidChangeHovered(hovered => bool = hovered);
// Pane Items
objs = dock.getPaneItems();
@@ -953,7 +973,8 @@ function testFile() {
// Reading and Writing
async function readFile() {
str = await file.read();
const res = await file.read();
if (res !== null) str = res;
}
const stream = file.createReadStream();
@@ -1274,6 +1295,9 @@ function testMarker() {
// MarkerLayer ================================================================
function testMarkerLayer() {
// Properties
str = markerLayer.id;
// Lifecycle
markerLayer = markerLayer.copy();
bool = markerLayer.destroy();
@@ -1368,6 +1392,7 @@ function testNotification() {
function testNotificationManager() {
// Events
atom.notifications.onDidAddNotification(notification => notification.dismiss());
atom.notifications.onDidClearNotifications(() => undefined);
// Adding Notifications
atom.notifications.addSuccess("Test");
@@ -1402,6 +1427,9 @@ function testNotificationManager() {
// Getting Notifications
notifications = atom.notifications.getNotifications();
// Managing Notifications
atom.notifications.clear();
}
// Package ====================================================================
@@ -1826,7 +1854,7 @@ function testRange() {
}
// ScopeDescriptor ============================================================
strs = scopeDescriptor.getScopesArray();
readonlyStrs = scopeDescriptor.getScopesArray();
// Selection ==================================================================
function testSelection() {
@@ -2212,6 +2240,7 @@ function testTextBuffer() {
num = buffer.createCheckpoint();
bool = buffer.revertToCheckpoint(42);
bool = buffer.groupChangesSinceCheckpoint(42);
bool = buffer.groupLastChanges();
buffer.getChangesSinceCheckpoint(42);
// Search And Replace
@@ -2299,6 +2328,7 @@ function testTextBuffer() {
num = buffer.getLastRow();
pos = buffer.getFirstPosition();
pos = buffer.getEndPosition();
num = buffer.getLength();
num = buffer.getMaxCharacterIndex();
range = buffer.rangeForRow(42, true);
num = buffer.characterIndexForPosition(pos);
@@ -2693,6 +2723,8 @@ function testTextEditor() {
editor.moveToNextSubwordBoundary();
editor.moveToBeginningOfNextParagraph();
editor.moveToBeginningOfPreviousParagraph();
editor.selectLargerSyntaxNode();
editor.selectSmallerSyntaxNode();
cursor = editor.getLastCursor();
str = editor.getWordUnderCursor();
@@ -3282,7 +3314,7 @@ const pathWatcherPromise = Atom.watchPath("/var/test", {}, (events) => {
for (const event of events) {
str = event.path;
str = event.action;
if (event.oldPath) str = event.oldPath;
if (event.action === "renamed") str = event.oldPath;
}
});
+20 -4
View File
@@ -34,7 +34,7 @@ export interface SuggestionInsertedEvent {
* An autocompletion suggestion for the user.
* Primary data type for the Atom Autocomplete+ service.
*/
export interface Suggestion<T extends { text: string }|{ snippet: string }> {
export interface SuggestionBase {
/**
* A string that will show in the UI for this suggestion.
* When not set, snippet || text is displayed.
@@ -91,14 +91,20 @@ export interface Suggestion<T extends { text: string }|{ snippet: string }> {
* When specified, a More.. link will be displayed in the description area.
*/
descriptionMoreURL?: string;
/**
* (experimental) Description with Markdown formatting.
* Takes precedence over plaintext description.
*/
descriptionMarkdown?: string;
}
export interface TextSuggestion extends Suggestion<TextSuggestion> {
export interface TextSuggestion extends SuggestionBase {
/** The text which will be inserted into the editor, in place of the prefix. */
text: string;
}
export interface SnippetSuggestion extends Suggestion<SnippetSuggestion> {
export interface SnippetSuggestion extends SuggestionBase {
/**
* A snippet string. This will allow users to tab through function arguments
* or other options.
@@ -106,7 +112,8 @@ export interface SnippetSuggestion extends Suggestion<SnippetSuggestion> {
snippet: string;
}
export type Suggestions = Array<TextSuggestion|SnippetSuggestion>;
export type AnySuggestion = TextSuggestion|SnippetSuggestion;
export type Suggestions = AnySuggestion[];
/** The interface that all Autocomplete+ providers must implement. */
export interface AutocompleteProvider {
@@ -154,4 +161,13 @@ export interface AutocompleteProvider {
/** Will be called if your provider is being destroyed by autocomplete+ */
dispose?(): void;
/**
* (experimental) Is called when a suggestion is selected by the user for
* the purpose of loading more information about the suggestion. Return a
* Promise of the new suggestion to replace it with or return null if
* no change is needed.
*/
getSuggestionDetailsOnSelect?:
(suggestion: AnySuggestion) => Promise<AnySuggestion | null> | AnySuggestion | null;
}
+267 -107
View File
@@ -1,4 +1,4 @@
// Type definitions for Atom 1.24
// Type definitions for Atom 1.26
// Project: https://github.com/atom/atom
// Definitions by: GlenCFL <https://github.com/GlenCFL>
// smhxx <https://github.com/smhxx>
@@ -7,9 +7,8 @@
// TypeScript Version: 2.3
// NOTE: only those classes exported within this file should be retain that status below.
// https://github.com/atom/atom/blob/v1.24.0/exports/atom.js
// https://github.com/atom/atom/blob/v1.26.0/exports/atom.js
/// <reference types="jquery" />
/// <reference types="node" />
import { ReadStream, WriteStream } from "fs";
@@ -40,58 +39,58 @@ export function watchPath(rootPath: string, options: {}, eventCallback: (events:
export interface AtomEnvironment {
// Properties
/** A CommandRegistry instance. */
commands: CommandRegistry;
readonly commands: CommandRegistry;
/** A Config instance. */
config: Config;
readonly config: Config;
/** A Clipboard instance. */
clipboard: Clipboard;
readonly clipboard: Clipboard;
/** A ContextMenuManager instance. */
contextMenu: ContextMenuManager;
readonly contextMenu: ContextMenuManager;
/** A MenuManager instance. */
menu: MenuManager;
readonly menu: MenuManager;
/** A KeymapManager instance. */
keymaps: KeymapManager;
readonly keymaps: KeymapManager;
/** A TooltipManager instance. */
tooltips: TooltipManager;
readonly tooltips: TooltipManager;
/** A NotificationManager instance. */
notifications: NotificationManager;
readonly notifications: NotificationManager;
/** A Project instance. */
project: Project;
readonly project: Project;
/** A GrammarRegistry instance. */
grammars: GrammarRegistry;
readonly grammars: GrammarRegistry;
/** A HistoryManager instance. */
history: HistoryManager;
readonly history: HistoryManager;
/** A PackageManager instance. */
packages: PackageManager;
readonly packages: PackageManager;
/** A ThemeManager instance. */
themes: ThemeManager;
readonly themes: ThemeManager;
/** A StyleManager instance. */
styles: StyleManager;
readonly styles: StyleManager;
/** A DeserializerManager instance. */
deserializers: DeserializerManager;
readonly deserializers: DeserializerManager;
/** A ViewRegistry instance. */
views: ViewRegistry;
readonly views: ViewRegistry;
/** A Workspace instance. */
workspace: Workspace;
readonly workspace: Workspace;
/** A TextEditorRegistry instance. */
textEditors: TextEditorRegistry;
readonly textEditors: TextEditorRegistry;
// Event Subscription
/** Invoke the given callback whenever ::beep is called. */
@@ -205,7 +204,27 @@ export interface AtomEnvironment {
beep(): void;
/**
* A flexible way to open a dialog akin to an alert dialog.
* A flexible way to open a dialog akin to an alert dialog. If a callback
* is provided, then the confirmation will work asynchronously, which is
* recommended.
*
* If the dialog is closed (via `Esc` key or `X` in the top corner) without
* selecting a button the first button will be clicked unless a "Cancel" or "No"
* button is provided.
*
* Returns the chosen button index number if the buttons option was an array.
* @param response The index of the button that was clicked.
* @param checkboxChecked The checked state of the checkbox if `checkboxLabel` was set.
* Otherwise false.
*/
confirm(options: ConfirmationOptions, callback: (response: number,
checkboxChecked: boolean) => void): void;
/**
* A flexible way to open a dialog akin to an alert dialog. If a callback
* is provided, then the confirmation will work asynchronously, which is
* recommended.
*
* If the dialog is closed (via `Esc` key or `X` in the top corner) without
* selecting a button the first button will be clicked unless a "Cancel" or "No"
* button is provided.
@@ -219,7 +238,10 @@ export interface AtomEnvironment {
}): void;
/**
* A flexible way to open a dialog akin to an alert dialog.
* A flexible way to open a dialog akin to an alert dialog. If a callback
* is provided, then the confirmation will work asynchronously, which is
* recommended.
*
* If the dialog is closed (via `Esc` key or `X` in the top corner) without
* selecting a button the first button will be clicked unless a "Cancel" or "No"
* button is provided.
@@ -265,11 +287,11 @@ export interface CommandRegistryTargetMap extends HTMLElementTagNameMap {
}
export type CommandRegistryListener<TargetType extends EventTarget> = {
didDispatch(event: CommandEvent<TargetType>): void,
displayName?: string,
description?: string,
hiddenInCommandPalette?: boolean,
} | ((event: CommandEvent<TargetType>) => void);
didDispatch(event: CommandEvent<TargetType>): void | Promise<void>,
displayName?: string,
description?: string,
hiddenInCommandPalette?: boolean,
} | ((event: CommandEvent<TargetType>) => void | Promise<void>);
/**
* Associates listener functions with commands in a context-sensitive way
@@ -306,9 +328,10 @@ export interface CommandRegistry {
/**
* Simulate the dispatch of a command on a DOM node.
* @return Whether or not there was a matching command for the target.
* @return Either a Promise that resolves after all handlers complete or null if
* no handlers were matched.
*/
dispatch(target: Node, commandName: string): boolean;
dispatch(target: Node, commandName: string): Promise<void> | null;
/** Invoke the given callback before dispatching a command event. */
onWillDispatch(callback: (event: CommandEvent) => void): Disposable;
@@ -447,7 +470,7 @@ export interface Config {
*/
export interface Decoration {
/** The identifier for this Decoration. */
id: number;
readonly id: number;
// Construction and Destruction
/**
@@ -654,6 +677,9 @@ export interface DisplayMarker {
* This API is experimental and subject to change on any release.
*/
export interface DisplayMarkerLayer {
/** The identifier for the underlying MarkerLayer. */
readonly id: string;
// Lifecycle
/** Destroy this layer. */
destroy(): void;
@@ -837,7 +863,7 @@ export interface LayerDecoration {
*/
export interface Marker {
/** The identifier for this Marker. */
id: number;
readonly id: number;
// Lifecycle
/**
@@ -949,6 +975,9 @@ export interface Marker {
/** Experimental: A container for a related set of markers. */
export interface MarkerLayer {
/** The identifier for this MarkerLayer. */
readonly id: string;
// Lifecycle
/** Create a copy of this layer with markers in the same state and locations. */
copy(): MarkerLayer;
@@ -1030,13 +1059,13 @@ export class Notification {
/** A notification manager used to create Notifications to be shown to the user. */
export interface NotificationManager {
// Properties
notifications: Notification[];
// Events
/** Invoke the given callback after a notification has been added. */
onDidAddNotification(callback: (notification: Notification) => void): Disposable;
/** Invoke the given callback after the notifications have been cleared. */
onDidClearNotifications(callback: () => void): Disposable;
// Adding Notifications
/** Add a success notification. */
addSuccess(message: string, options?: NotificationOptions): Notification;
@@ -1055,7 +1084,11 @@ export interface NotificationManager {
// Getting Notifications
/** Get all the notifications. */
getNotifications(): Notification[];
getNotifications(): ReadonlyArray<Notification>;
// Managing Notifications
/** Clear all the notifications. */
clear(): void;
}
/** Represents a point in a buffer in row/column coordinates. */
@@ -1267,8 +1300,7 @@ export class Range {
* including cursor and selection positions, folds, and soft wraps.
*/
export class TextEditor {
id: number;
buffer: TextBuffer;
readonly id: number;
// NOTE: undocumented within the public API. Don't go down the rabbit hole.
constructor(options?: object);
@@ -1497,7 +1529,7 @@ export class TextEditor {
/** Set the text in the given Range in buffer coordinates. */
setTextInBufferRange(range: RangeCompatible, text: string, options?:
{ normalizeLineEndings?: boolean, undo?: "skip" }): Range;
TextEditOptions): Range;
/* For each selection, replace the selected text with the given text. */
insertText(text: string, options?: TextInsertionOptions): Range|false;
@@ -2132,6 +2164,12 @@ export class TextEditor {
*/
selectToBeginningOfPreviousParagraph(): void;
/** For each selection, select the syntax node that contains that selection. */
selectLargerSyntaxNode(): void;
/** Undo the effect a preceding call to `::selectLargerSyntaxNode`. */
selectSmallerSyntaxNode(): void;
/** Select the range of the given marker if it is valid. */
selectMarker(marker: DisplayMarker): Range|undefined;
@@ -2342,7 +2380,10 @@ export class TextEditor {
/** Unfold all existing folds. */
unfoldAll(): void;
/** Fold all foldable lines at the given indent level. */
/**
* Fold all foldable lines at the given indent level.
* @param level A zero-indexed number.
*/
foldAllAtIndentLevel(level: number): void;
/**
@@ -2526,7 +2567,7 @@ export type TooltipPlacement =
/** Associates tooltips with HTML elements or selectors. */
export interface TooltipManager {
/** Add a tooltip to the given element. */
add(target: HTMLElement, options: {
add(target: HTMLElement | JQueryCompatible, options: {
item?: object,
} | {
title?: string|(() => string),
@@ -2975,7 +3016,7 @@ export interface WorkspaceCenter {
* Node's ChildProcess.
*/
export class BufferedProcess {
process?: ChildProcess;
readonly process?: ChildProcess;
constructor(options: ProcessOptions);
@@ -3443,6 +3484,12 @@ export interface Dock {
/** Invoke the given callback when a pane item is destroyed. */
onDidDestroyPaneItem(callback: (event: PaneItemObservedEvent) => void): Disposable;
/**
* Invoke the given callback when the hovered state of the dock changes.
* @param hovered Is the dock now hovered?
*/
onDidChangeHovered(callback: (hovered: boolean) => void): Disposable;
// Pane Items
/** Get all pane items in the dock. */
getPaneItems(): object[];
@@ -3547,7 +3594,7 @@ export class File {
// Reading and Writing
/** Reads the contents of the file. */
read(flushCache?: boolean): Promise<string>;
read(flushCache?: boolean): Promise<string | null>;
/** Returns a stream to read the content of the file. */
createReadStream(): ReadStream;
@@ -4043,10 +4090,10 @@ export interface MenuManager {
*/
export interface Package {
/** The name of the Package. */
name: string;
readonly name: string;
/** The path to the Package on disk. */
path: string;
readonly path: string;
// Event Subscription
/** Invoke the given callback when all packages have been activated. */
@@ -4368,7 +4415,7 @@ export interface Pane {
*/
export interface Panel<T = object> {
/** Whether or not the Panel is visible. */
visible: boolean;
readonly visible: boolean;
// Construction and Destruction
/** Destroy and remove this panel from the UI. */
@@ -4489,10 +4536,8 @@ export interface Project {
* syntax tree to a token including all scope names for the entire path.
*/
export interface ScopeDescriptor {
scopes: string[];
/** Returns all scopes for this descriptor. */
getScopesArray(): string[];
getScopesArray(): ReadonlyArray<string>;
}
/** Represents a selection in the TextEditor. */
@@ -4885,13 +4930,13 @@ export class Task {
*/
export class TextBuffer {
/** The unique identifier for this buffer. */
id: string;
readonly id: string;
/** The number of retainers for the buffer. */
refcount: number;
readonly refcount: number;
/** Whether or not the bufffer has been destroyed. */
destroyed: boolean;
readonly destroyed: boolean;
/** Create a new buffer backed by the given file path. */
static load(filePath: string, params?: BufferLoadOptions): Promise<TextBuffer>;
@@ -5059,7 +5104,10 @@ export class TextBuffer {
/** Get the text of the last line of the buffer, without its line ending. */
getLastLine(): string;
/** Get the text of the line at the given row, without its line ending. */
/**
* Get the text of the line at the given 0-indexed row, without its line ending.
* @param row A number representing the row.
*/
lineForRow(row: number): string|undefined;
/** Get the line ending for the given 0-indexed row. */
@@ -5097,24 +5145,29 @@ export class TextBuffer {
setTextViaDiff(text: string): void;
/** Set the text in the given range. */
setTextInRange(range: RangeCompatible, text: string, options?:
{ normalizeLineEndings?: boolean, undo?: "skip" }): Range;
setTextInRange(range: RangeCompatible, text: string, options?: TextEditOptions): Range;
/** Insert text at the given position. */
insert(position: PointCompatible, text: string, options?:
{ normalizeLineEndings?: boolean, undo?: "skip" }): Range;
insert(position: PointCompatible, text: string, options?: TextEditOptions): Range;
/** Append text to the end of the buffer. */
append(text: string, options?: { normalizeLineEndings?: boolean, undo?:
"skip" }): Range;
append(text: string, options?: TextEditOptions): Range;
/** Delete the text in the given range. */
delete(range: RangeCompatible): Range;
/** Delete the line associated with a specified row. */
/**
* Delete the line associated with a specified 0-indexed row.
* @param row A number representing the row to delete.
*/
deleteRow(row: number): Range;
/** Delete the lines associated with the specified row range. */
/**
* Delete the lines associated with the specified 0-indexed row range.
*
* If the row range is out of bounds, it will be clipped. If the `startRow`
* is greater than the `endRow`, they will be reordered.
*/
deleteRows(startRow: number, endRow: number): Range;
// Markers
@@ -5153,10 +5206,16 @@ export class TextBuffer {
getMarkerCount(): number;
// History
/** Undo the last operation. If a transaction is in progress, aborts it. */
/**
* Undo the last operation. If a transaction is in progress, aborts it.
* @return A boolean of whether or not a change was made.
*/
undo(): boolean;
/** Redo the last operation. */
/**
* Redo the last operation.
* @return A boolean of whether or not a change was made.
*/
redo(): boolean;
/** Batch multiple operations as a single undo/redo step. */
@@ -5164,37 +5223,44 @@ export class TextBuffer {
transact<T>(fn: () => T): T;
/**
* Call within a transaction to terminate the function's execution and
* revert any changes performed up to the abortion.
* Abort the currently running transaction.
*
* Only intended to be called within the `fn` option to `::transact`.
*/
abortTransaction(): void;
/**
* Clear the undo stack. When calling this method within a transaction,
* the ::onDidChangeText event will not be triggered because the information
* describing the changes is lost.
*/
/** Clear the undo stack. */
clearUndoStack(): void;
/**
* Create a pointer to the current state of the buffer for use with
* ::revertToCheckpoint and ::groupChangesSinceCheckpoint.
* `::revertToCheckpoint` and `::groupChangesSinceCheckpoint`.
* @return A checkpoint ID value.
*/
createCheckpoint(): number;
/**
* Revert the buffer to the state it was in when the given checkpoint was created.
* Returns a boolean indicating whether the operation succeeded.
* @return A boolean indicating whether the operation succeeded.
*/
revertToCheckpoint(checkpoint: number): boolean;
/**
* Group all changes since the given checkpoint into a single transaction for
* purposes of undo/redo.
* Returns a boolean indicating whether the operation succeeded.
* @return A boolean indicating whether the operation succeeded.
*/
groupChangesSinceCheckpoint(checkpoint: number): boolean;
/**
* Group the last two text changes for purposes of undo/redo.
*
* This operation will only succeed if there are two changes on the undo stack.
* It will not group past the beginning of an open transaction.
* @return A boolean indicating whether the operation succeeded.
*/
groupLastChanges(): boolean;
/**
* Returns a list of changes since the given checkpoint.
* If the given checkpoint is no longer present in the undo history, this method
@@ -5284,17 +5350,26 @@ export class TextBuffer {
/** Get the maximal position in the buffer, where new text would be appended. */
getEndPosition(): Point;
/** Get the length of the buffer's text. */
getLength(): number;
/** Get the length of the buffer in characters. */
getMaxCharacterIndex(): number;
/** Get the range for the given row. */
rangeForRow(row: number, includeNewline: boolean): Range;
/**
* Get the range for the given row.
* @param row A number representing a 0-indexed row.
* @param includeNewline A boolean indicating whether or not to include the
* newline, which results in a range that extends to the start of the next line.
* (default: false)
*/
rangeForRow(row: number, includeNewline?: boolean): Range;
/**
* Convert a position in the buffer in row/column coordinates to an absolute
* character offset, inclusive of line ending characters.
*/
characterIndexForPosition(position: Point|[number, number]): number;
characterIndexForPosition(position: PointCompatible): number;
/**
* Convert an absolute character offset, inclusive of newlines, to a position
@@ -5569,19 +5644,28 @@ export interface FileSavedEvent {
path: string;
}
export type FilesystemChangeEvent = Array<{
export interface FilesystemChangeBasic<
Action extends "created"|"modified"|"deleted"|"renamed"
= "created"|"modified"|"deleted"
> {
/** A string describing the filesystem action that occurred. */
action: "created"|"modified"|"deleted"|"renamed";
action: Action;
/** The absolute path to the filesystem entry that was acted upon. */
path: string;
}
export interface FilesystemChangeRename extends FilesystemChangeBasic<"renamed"> {
/**
* For rename events, a string containing the filesystem entry's former
* absolute path.
*/
oldPath?: string;
}>;
oldPath: string;
}
export type FilesystemChange = FilesystemChangeBasic|FilesystemChangeRename;
export type FilesystemChangeEvent = FilesystemChange[];
export interface FullKeybindingMatchEvent {
/** The string of keystrokes that matched the binding. */
@@ -5744,7 +5828,7 @@ export interface TextEditorObservedEvent {
// information under certain contexts.
// NOTE: the config schema with these defaults can be found here:
// https://github.com/atom/atom/blob/v1.24.0/src/config-schema.js
// https://github.com/atom/atom/blob/v1.26.0/src/config-schema.js
/**
* Allows you to strongly type Atom configuration variables. Additional key:value
* pairings merged into this interface will result in configuration values under
@@ -6030,7 +6114,60 @@ export interface BuildEnvironmentOptions {
enablePersistence?: boolean;
}
export interface ContextMenuOptions {
export interface ConfirmationOptions {
/** The type of the confirmation prompt. */
type?: "none"|"info"|"error"|"question"|"warning";
/** The text for the buttons. */
buttons?: ReadonlyArray<string>;
/** The index for the button to be selected by default in the prompt. */
defaultId?: number;
/** The title for the prompt. */
title?: string;
/** The content of the message box. */
message?: string;
/** Additional information regarding the message. */
detail?: string;
/** If provided, the message box will include a checkbox with the given label. */
checkboxLabel?: string;
/** Initial checked state of the checkbox. false by default. */
checkboxChecked?: boolean;
/** An Electron NativeImage to use as the prompt's icon. */
icon?: object;
/**
* The index of the button to be used to cancel the dialog, via the `Esc` key.
* By default this is assigned to the first button with "cancel" or "no" as the
* label. If no such labeled buttons exist and this option is not set, 0 will be
* used as the return value or callback response.
*
* This option is ignored on Windows.
*/
cancelId?: number;
/**
* On Windows, Electron will try to figure out which one of the buttons are
* common buttons (like `Cancel` or `Yes`), and show the others as command links
* in the dialog. This can make the dialog appear in the style of modern Windows
* apps. If you don't like this behavior, you can set noLink to true.
*/
noLink?: boolean;
/**
* Normalize the keyboard access keys across platforms.
* Atom defaults this to true.
*/
normalizeAccessKeys?: boolean;
}
export interface ContextMenuItemOptions {
/** The menu item's label. */
label?: string;
@@ -6049,12 +6186,6 @@ export interface ContextMenuOptions {
/** An array of additional items. */
submenu?: ReadonlyArray<ContextMenuOptions>;
/**
* If you want to create a separator, provide an item with type: 'separator'
* and no other keys.
*/
type?: "separator";
/** Whether the menu item should appear in the menu. Defaults to true. */
visible?: boolean;
@@ -6069,8 +6200,28 @@ export interface ContextMenuOptions {
* given context menu deployment.
*/
shouldDisplay?(event: Event): void;
/** Place this menu item before the menu items representing the given commands. */
before?: ReadonlyArray<string>;
/** Place this menu item after the menu items representing the given commands. */
after?: ReadonlyArray<string>;
/**
* Place this menu item's group before the containing group of the menu items
* representing the given commands.
*/
beforeGroupContaining?: ReadonlyArray<string>;
/**
* Place this menu item's group after the containing group of the menu items
* representing the given commands.
*/
afterGroupContaining?: ReadonlyArray<string>;
}
export type ContextMenuOptions = ContextMenuItemOptions | { type: "separator" };
export interface CopyMarkerOptions {
/** Whether or not the marker should be tailed. */
tailed?: boolean;
@@ -6343,7 +6494,18 @@ export interface SpawnProcessOptions {
shell?: boolean | string;
}
export interface TextInsertionOptions {
export interface TextEditOptions {
/** If true, all line endings will be normalized to match the editor's current mode. */
normalizeLineEndings?: boolean;
/**
* If skip, skips the undo stack for this operation.
* @deprecated Call groupLastChanges() on the TextBuffer afterward instead.
*/
undo?: "skip";
}
export interface TextInsertionOptions extends TextEditOptions {
/** If true, selects the newly added text. */
select?: boolean;
@@ -6366,12 +6528,6 @@ export interface TextInsertionOptions {
* true, this behavior is suppressed.
*/
preserveTrailingLineIndentation?: boolean;
/** If true, all line endings will be normalized to match the editor's current mode. */
normalizeLineEndings?: boolean;
/** If skip, skips the undo stack for this operation. */
undo?: "skip";
}
/** The options for a Bootstrap 3 Tooltip class, which Atom uses a variant of. */
@@ -6497,6 +6653,10 @@ export interface DisposableLike {
dispose(): void;
}
export interface JQueryCompatible<Element extends Node = HTMLElement> extends Iterable<Element> {
jquery: string;
}
/** The types usable when constructing a point via the Point::fromObject method. */
export type PointCompatible = PointLike|[number, number];
@@ -6744,11 +6904,11 @@ export interface TokenizeLineResult {
* jQuery, which is an expensive dependency we want to eliminate.
*/
export interface Tooltip {
options: TooltipOptions;
enabled: boolean;
timeout: number;
hoverState: "in"|"out"|null;
element: JQuery|HTMLElement;
readonly options: TooltipOptions;
readonly enabled: boolean;
readonly timeout: number;
readonly hoverState: "in"|"out"|null;
readonly element: HTMLElement;
getTitle(): string;
getTooltipElement(): HTMLElement;
@@ -6765,11 +6925,11 @@ export interface ViewModel {
}
export interface WindowLoadSettings {
appVersion: string;
atomHome: string;
devMode: boolean;
resourcePath: string;
safeMode: boolean;
env?: { [key: string]: string|undefined };
profileStartup?: boolean;
readonly appVersion: string;
readonly atomHome: string;
readonly devMode: boolean;
readonly resourcePath: string;
readonly safeMode: boolean;
readonly env?: { [key: string]: string|undefined };
readonly profileStartup?: boolean;
}
+14
View File
@@ -117,6 +117,20 @@ const authOptions : Auth0LockConstructorOptions = {
new Auth0Lock(CLIENT_ID, DOMAIN, authOptions);
// test "other" properties
const otherOptions : Auth0LockConstructorOptions = {
clientBaseUrl: "http://www.example.com",
configurationBaseUrl: "https://cdn.auth0.com",
languageBaseUrl: "http://www.example.com",
hashCleanup: false,
leeway: 30,
_enableImpersonation: true,
_enableIdPInitiatedLogin: false
};
new Auth0Lock(CLIENT_ID, DOMAIN, otherOptions);
// test multi-variant example
const multiVariantOptions : Auth0LockConstructorOptions = {
+10 -3
View File
@@ -1,4 +1,4 @@
// Type definitions for auth0-lock 10.16
// Type definitions for auth0-lock 11.4
// Project: http://auth0.com
// Definitions by: Brian Caruso <https://github.com/carusology>
// Dan Caddigan <https://github.com/goldcaddy77>
@@ -118,18 +118,24 @@ interface Auth0LockConstructorOptions {
auth?: Auth0LockAuthOptions;
autoclose?: boolean;
autofocus?: boolean;
avatar?: Auth0LockAvatarOptions;
avatar?: Auth0LockAvatarOptions | null;
clientBaseUrl?: string;
closable?: boolean;
configurationBaseUrl?: string;
container?: string;
defaultADUsernameFromEmailPrefix?: string;
defaultDatabaseConnection?: string;
defaultEnterpriseConnection?: string;
forgotPasswordLink?: string;
hashCleanup?: boolean;
initialScreen?: "login" | "signUp" | "forgotPassword";
language?: string;
languageBaseUrl?: string;
languageDictionary?: any;
leeway?: number;
loginAfterSignUp?: boolean;
mustAcceptTerms?: boolean;
oidcConformant?: boolean;
popupOptions?: Auth0LockPopupOptions;
prefill?: { email?: string, username?: string};
rememberLastLogin?: boolean;
@@ -137,7 +143,8 @@ interface Auth0LockConstructorOptions {
socialButtonStyle?: "big" | "small";
theme?: Auth0LockThemeOptions;
usernameStyle?: string;
oidcConformant?: boolean;
_enableImpersonation?: boolean;
_enableIdPInitiatedLogin?: boolean;
}
interface Auth0LockFlashMessageOptions {
+3 -3
View File
@@ -25,7 +25,7 @@ declare namespace autobahn {
leave(reason: string, message: string): void;
call<TResult>(procedure: string, args?: any[], kwargs?: any, options?: ICallOptions): When.Promise<TResult>;
call<TResult>(procedure: string, args?: any[] | any, kwargs?: any, options?: ICallOptions): When.Promise<TResult>;
publish(topic: string, args?: any[], kwargs?: any, options?: IPublishOptions): When.Promise<IPublication>;
@@ -96,7 +96,7 @@ declare namespace autobahn {
kwargs: any;
}
type SubscribeHandler = (args?: any[], kwargs?: any, details?: IEvent) => void;
type SubscribeHandler = (args?: any[] | any, kwargs?: any, details?: IEvent) => void;
interface ISubscription {
topic: string;
@@ -206,7 +206,7 @@ declare namespace autobahn {
type DeferFactory = () => When.Promise<any>;
type OnChallengeHandler = (session: Session, method: string, extra: any) => string;
type OnChallengeHandler = (session: Session, method: string, extra: any) => string | When.Promise<string>;
interface IConnectionOptions {
use_es6_promises?: boolean;
+69 -3
View File
@@ -260,9 +260,27 @@ statement = {
};
statement = {
Sid: str,
Action: [str, str],
Effect: str,
Resource: [str, str]
Resource: [str, str],
Condition: {
condition1: { key: "value" },
condition2: [{
key1: "value",
key2: "value"
}, {
key3: "value"
}]
},
Principal: [str, str],
NotPrincipal: [str, str]
};
statement = {
Effect: str,
NotAction: str,
NotResource: str
};
policyDocument = {
@@ -270,6 +288,11 @@ policyDocument = {
Statement: [statement]
};
policyDocument = {
Version: str,
Statement: [statement, statement]
};
authResponse = {
principalId: str,
policyDocument,
@@ -572,6 +595,28 @@ const CloudFrontResponseEvent: AWSLambda.CloudFrontResponseEvent = {
]
};
/* Kinesis Data Stream Events */
declare let kinesisStreamEvent: AWSLambda.KinesisStreamEvent;
declare let kinesisStreamRecord: AWSLambda.KinesisStreamRecord;
declare let kinesisStreamRecordPayload: AWSLambda.KinesisStreamRecordPayload;
kinesisStreamRecord = kinesisStreamEvent.Records[0];
str = kinesisStreamRecord.awsRegion;
str = kinesisStreamRecord.eventID;
str = kinesisStreamRecord.eventName;
str = kinesisStreamRecord.eventSource;
str = kinesisStreamRecord.eventSourceARN;
str = kinesisStreamRecord.eventVersion;
str = kinesisStreamRecord.invokeIdentityArn;
kinesisStreamRecordPayload = kinesisStreamRecord.kinesis;
num = kinesisStreamRecordPayload.approximateArrivalTimestamp;
str = kinesisStreamRecordPayload.data;
str = kinesisStreamRecordPayload.kinesisSchemaVersion;
str = kinesisStreamRecordPayload.partitionKey;
str = kinesisStreamRecordPayload.sequenceNumber;
/* Compatibility functions */
context.done();
context.done(error);
@@ -585,8 +630,27 @@ context.fail(str);
/* Handler */
let handler: AWSLambda.Handler = (event: any, context: AWSLambda.Context, cb: AWSLambda.Callback) => { };
// async methods return Promise, test assignability
let asyncHandler: AWSLambda.Handler = async (event: any, context: AWSLambda.Context, cb: AWSLambda.Callback) => { };
/* In node8.10 runtime, handlers may return a promise for the result value, so existing async
* handlers that return Promise<void> before calling the callback will now have a `null` result.
* Be safe and make that badly typed with a major verson bump to 8.10 so users expect the breaking change,
* since the upgrade effort should be pretty low in most cases, and it points them at a nicer solution.
*/
// $ExpectError
let legacyAsyncHandler: AWSLambda.APIGatewayProxyHandler = async (
event: AWSLambda.APIGatewayProxyEvent,
context: AWSLambda.Context,
cb: AWSLambda.Callback<AWSLambda.APIGatewayProxyResult>,
) => {
cb(null, { statusCode: 200, body: 'No longer valid' });
};
let node8AsyncHandler: AWSLambda.APIGatewayProxyHandler = async (
event: AWSLambda.APIGatewayProxyEvent,
context: AWSLambda.Context,
cb: AWSLambda.Callback<AWSLambda.APIGatewayProxyResult>,
) => {
return { statusCode: 200, body: 'Is now valid!' };
};
let inferredHandler: AWSLambda.S3Handler = (event, context, cb) => {
// $ExpectType S3Event
@@ -661,3 +725,5 @@ let customHandler: AWSLambda.Handler<CustomEvent, CustomResult> = (event, contex
// $ExpectError
cb(null, { resultString: bool });
};
let kinesisStreamHandler: AWSLambda.KinesisStreamHandler = (event: AWSLambda.KinesisStreamEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => { };
+68 -10
View File
@@ -1,4 +1,4 @@
// Type definitions for AWS Lambda
// Type definitions for AWS Lambda 8.10
// Project: http://docs.aws.amazon.com/lambda
// Definitions by: James Darbyshire <https://github.com/darbio/aws-lambda-typescript>
// Michael Skarum <https://github.com/skarum>
@@ -16,6 +16,8 @@
// Danilo Raisi <https://github.com/daniloraisi>
// Simon Buchan <https://github.com/simonbuchan>
// David Hayden <https://github.com/Haydabase>
// Chris Redekop <https://github.com/repl-chris>
// Aneil Mallavarapu <https://github.com/aneilbaboo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -90,7 +92,7 @@ export interface AttributeValue {
// Context
// http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_StreamRecord.html
export interface StreamRecord {
ApproximateCreationTime?: number;
ApproximateCreationDateTime?: number;
Keys?: { [key: string]: AttributeValue };
NewImage?: { [key: string]: AttributeValue };
OldImage?: { [key: string]: AttributeValue };
@@ -437,28 +439,52 @@ export interface CustomAuthorizerResult {
principalId: string;
policyDocument: PolicyDocument;
context?: AuthResponseContext;
usageIdentifierKey?: string;
}
export type AuthResponse = CustomAuthorizerResult;
/**
* API Gateway CustomAuthorizer AuthResponse.PolicyDocument.
* http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output
* https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-output.html
* https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition
*/
export interface PolicyDocument {
Version: string;
Statement: [Statement];
Id?: string;
Statement: Statement[];
}
/**
* API Gateway CustomAuthorizer AuthResponse.PolicyDocument.Condition.
* https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-policy-language-overview.html
* https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html
*/
export interface ConditionBlock {
[condition: string]: Condition | Condition[];
}
export interface Condition {
[key: string]: string | string[];
}
/**
* API Gateway CustomAuthorizer AuthResponse.PolicyDocument.Statement.
* http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output
* https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-policy-language-overview.html
* https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html
*/
export interface Statement {
Action: string | string[];
export type Statement = BaseStatement & StatementAction & StatementResource;
export interface BaseStatement {
Effect: string;
Resource: string | string[];
Sid?: string;
Condition?: ConditionBlock;
Principal?: string | string[];
NotPrincipal?: string | string[];
}
export type StatementAction = { Action: string | string[] } | { NotAction: string | string[] };
export type StatementResource = { Resource: string | string[] } | { NotResource: string | string[] };
/**
* API Gateway CustomAuthorizer AuthResponse.PolicyDocument.Statement.
* http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output
@@ -529,6 +555,31 @@ export interface CloudFrontRequestEvent {
export type CloudFrontResponseResult = undefined | null | CloudFrontResultResponse;
// Kinesis Streams
// https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-kinesis-streams
export interface KinesisStreamRecordPayload {
approximateArrivalTimestamp: number;
data: string;
kinesisSchemaVersion: string;
partitionKey: string;
sequenceNumber: string;
}
export interface KinesisStreamRecord {
awsRegion: string;
eventID: string;
eventName: string;
eventSource: string;
eventSourceARN: string;
eventVersion: string;
invokeIdentityArn: string;
kinesis: KinesisStreamRecordPayload;
}
export interface KinesisStreamEvent {
Records: KinesisStreamRecord[];
}
/**
* AWS Lambda handler function.
* http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
@@ -536,8 +587,13 @@ export type CloudFrontResponseResult = undefined | null | CloudFrontResultRespon
* @param event – event data.
* @param context – runtime information of the Lambda function that is executing.
* @param callback – optional callback to return information to the caller, otherwise return value is null.
* @return In the node8.10 runtime, a promise for the lambda result.
*/
export type Handler<TEvent = any, TResult = any> = (event: TEvent, context: Context, callback: Callback<TResult>) => void;
export type Handler<TEvent = any, TResult = any> = (
event: TEvent,
context: Context,
callback: Callback<TResult>,
) => void | Promise<TResult>;
/**
* Optional callback parameter.
@@ -595,7 +651,9 @@ export type CloudFrontRequestCallback = Callback<CloudFrontRequestResult>;
export type CloudFrontResponseHandler = Handler<CloudFrontResponseEvent, CloudFrontResponseResult>;
export type CloudFrontResponseCallback = Callback<CloudFrontResponseResult>;
// TODO: Kinesis (should be very close to DynamoDB stream?)
export type KinesisStreamHandler = Handler<KinesisStreamEvent, void>;
// TODO: Kinesis Firehose
export type CustomAuthorizerHandler = Handler<CustomAuthorizerEvent, CustomAuthorizerResult>;
export type CustomAuthorizerCallback = Callback<CustomAuthorizerResult>;
+173
View File
@@ -0,0 +1,173 @@
import * as axon from 'axon';
import { Socket as NetSocket } from 'net';
const PubEmitterSocket = axon.PubEmitterSocket;
const PubSocket = axon.PubSocket;
const RepSocket = axon.RepSocket;
const ReqSocket = axon.ReqSocket;
const Socket = axon.Socket;
const SubSocket = axon.SubSocket;
const pubSocket = new PubSocket();
const pubEmitterSocket = new PubEmitterSocket();
const repSocket = new RepSocket();
const reqSocket = new ReqSocket();
const netSocket = new NetSocket();
const socket = new Socket();
const subSocket = new SubSocket();
// $ExpectType PubSocket
pubSocket.send('anything');
// $ExpectType PubSocket
pubSocket.send('anything', {w: 100, h: 200});
// $ExpectType PubSocket
pubEmitterSocket.send('anything');
// $ExpectType PubSocket
pubEmitterSocket.send('anything', {w: 100, h: 200});
// $ExpectType Socket
pubEmitterSocket.bind(3000);
// $ExpectError
pubEmitterSocket.bind({a, b, c});
// $ExpectError
pubEmitterSocket.bind();
// $ExpectType Socket
pubEmitterSocket.connect(3000);
// $ExpectError
pubEmitterSocket.connect({a, b, c});
// $ExpectError
pubEmitterSocket.connect();
// $ExpectType (args: Buffer | Buffer[]) => void
repSocket.onmessage(netSocket);
// $ExpectError
repSocket.onmessage();
// $ExpectError
repSocket.onmessage('');
// $ExpectError
repSocket.onmessage(1);
// $ExpectError
repSocket.onmessage({});
// $ExpectType string
reqSocket.id();
// $ExpectType (args: Buffer | Buffer[]) => void
reqSocket.onmessage();
// $ExpectType void
reqSocket.send('anything');
// $ExpectType void
reqSocket.send('anything', {w: 100, h: 200});
// $ExpectType Socket
socket.set('name', 'aaa');
// $ExpectError
socket.set(1, 'aaa');
// $ExpectError
socket.set({}, 'aaa');
// $ExpectError
socket.set('name');
// $ExpectType any
socket.get('name');
// $ExpectError
socket.get(1);
// $ExpectError
socket.get({});
// $ExpectType Socket
socket.enable('name');
// $ExpectError
socket.enable(1);
// $ExpectError
socket.enable({});
// $ExpectType Socket
socket.disable('name');
// $ExpectError
socket.disable(1);
// $ExpectError
socket.disable({});
// $ExpectType boolean
socket.enabled('name');
// $ExpectError
socket.enabled(1);
// $ExpectError
socket.enabled({});
// $ExpectType boolean
socket.disabled('name');
// $ExpectError
socket.disabled(1);
// $ExpectError
socket.disabled({});
// $ExpectType boolean
subSocket.hasSubscriptions();
// $ExpectType boolean
subSocket.matches('name');
// $ExpectError
subSocket.matches(1);
// $ExpectError
subSocket.matches({});
// $ExpectType RegExp
subSocket.subscribe(/some regex/);
// $ExpectType RegExp
subSocket.subscribe('some string');
// $ExpectError
subSocket.subscribe(1);
// $ExpectError
subSocket.subscribe({});
// $ExpectError
subSocket.subscribe();
// $ExpectType void
subSocket.unsubscribe(/some regex/);
// $ExpectType void
subSocket.unsubscribe('some string');
// $ExpectError
subSocket.unsubscribe(1);
// $ExpectError
subSocket.unsubscribe({});
// $ExpectError
subSocket.unsubscribe();
+134
View File
@@ -0,0 +1,134 @@
// Type definitions for axon 2.0
// Project: https://github.com/visionmedia/axon#readme
// Definitions by: Vilim Stubičan <https://github.com/jewbre>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
/// <reference types="node" />
import { EventEmitter } from "events";
import { Socket as NetSocket } from "net";
export class Socket extends EventEmitter {
set(name: string, val: any): Socket;
get(name: string): any;
enable(name: string): Socket;
disable(name: string): Socket;
enabled(name: string): boolean;
disabled(name: string): boolean;
use(plugin: (socket: Socket) => any): Socket;
pack(args: Buffer | Buffer[]): Buffer;
closeSockets(): void;
close(): void;
closeServer(fn: () => any): void;
address(): { port: number; family: string; address: string; string: string } | undefined;
removeSocket(sock: Socket): void;
addSocket(sock: Socket): void;
handleErrors(sock: Socket): void;
onmessage(sock: NetSocket): (args: Buffer | Buffer[]) => void;
connect(port: ConnectionPort, host?: string | (() => void), fn?: () => void): Socket;
onconnect(sock: Socket): void;
bind(port: ConnectionPort, host?: string | (() => void), fn?: () => void): Socket;
}
export class SubSocket extends Socket {
hasSubscriptions(): boolean;
matches(topic: string): boolean;
onmessage(sock: NetSocket): (args: Buffer | Buffer[]) => void;
subscribe(re: RegExp | string): RegExp;
unsubscribe(re: RegExp | string): void;
clearSubscriptions(): void;
/**
* @throws {Error}
*/
send(): void;
}
export class SubEmitterSocket {
onmessage(): (args: Buffer | Buffer[]) => void;
on(event: string, fn: (...args: any[]) => void): SubEmitterSocket;
off(event: string): SubEmitterSocket;
bind(port: ConnectionPort, host?: string | (() => void), fn?: () => void): Socket;
connect(port: ConnectionPort, host?: string | (() => void), fn?: () => void): Socket;
close(): void;
}
export class PubSocket extends Socket {
send(...args: any[]): PubSocket;
}
export class PubEmitterSocket {
sock: PubSocket;
send(...args: any[]): PubSocket;
bind(port: ConnectionPort, host?: string | (() => void), fn?: () => void): Socket;
connect(port: ConnectionPort, host?: string | (() => void), fn?: () => void): Socket;
close(): void;
}
export class PushSocket extends Socket {
send(...args: any[]): void;
enqueue(msg: any): void;
}
export class ReqSocket extends Socket {
id(): string;
onmessage(): (args: Buffer | Buffer[]) => void;
send(...args: any[]): void;
}
export class RepSocket extends Socket {
onmessage(sock: NetSocket): (args: Buffer | Buffer[]) => void;
}
export class PullSocket extends Socket {
/**
* @throws {Error}
*/
send(): void;
}
export type ConnectionPort =
number
| string
| { protocol?: string, hostname?: string, pathname: string, port: string | number };
export function socket(type: string, options?: any): Socket;
export const types: {
[propName: string]: { new(): PubEmitterSocket | SubEmitterSocket | PushSocket | PullSocket | PubSocket | SubSocket | ReqSocket | RepSocket | Socket };
};
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"axon-tests.ts"
]
}

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