diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index 7ebdcc514f..44f0d8e9a0 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -401,6 +401,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](egg.js/egg.js.d.ts) [Egg.js](https://github.com/mikeflynn/egg.js) by [Markus Peloso](https://github.com/ToastHawaii)
* [:link:](ejs-locals/ejs-locals.d.ts) [ejs-locals](https://github.com/randometc/ejs-locals) by [jt000](https://github.com/jt000)
* [:link:](ejs/ejs.d.ts) [ejs.js](http://ejs.co) by [Ben Liddicott](https://github.com/benliddicott/DefinitelyTyped)
+* [:link:](elasticsearch/elasticsearch.d.ts) [elasticsearch](https://www.elastic.co) by [Casper Skydt](https://github.com/CasperSkydt/DefinitelyTyped), [Blake Smith](https://github.com/bfsmith/DefinitelyTyped)
* [:link:](jquery.elang/jquery.elang.d.ts) [eLang](https://github.com/sumegizoltan/ELang) by [Zoltan Sumegi](https://github.com/sumegizoltan)
* [:link:](github-electron/github-electron.d.ts) [Electron](http://electron.atom.io) by [jedmao](https://github.com/jedmao), [rhysd](https://rhysd.github.io), [Milan Burda](https://github.com/miniak)
* [:link:](electron-builder/electron-builder.d.ts) [electron-builder](https://github.com/loopline-systems/electron-builder) by [Maxime LUCE](https://github.com/SomaticIT)
diff --git a/amcharts/AmCharts.d.ts b/amcharts/AmCharts.d.ts
index bbd732bb1c..4f5dbe90f7 100644
--- a/amcharts/AmCharts.d.ts
+++ b/amcharts/AmCharts.d.ts
@@ -27,6 +27,9 @@ declare namespace AmCharts {
/** Clears all the charts on page, removes listeners and intervals. */
function clear();
+ /** Handle ready event */
+ function ready(Function): void;
+
/** Create chart by params. */
function makeChart(selector: string, params: any, delay?: number): AmChart;
diff --git a/angular-es/angular-es.d.ts b/angular-es/angular-es.d.ts
index 10979ae15c..0972b42da0 100644
--- a/angular-es/angular-es.d.ts
+++ b/angular-es/angular-es.d.ts
@@ -45,12 +45,12 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Component: (component: iComponent) => ngESDecorator;
+ function Component(component: iComponent): ngESDecorator;
/**
* Register config block
*/
- var Config: () => ngESDecorator;
+ function Config(): ngESDecorator;
/**
* Register constant
@@ -59,7 +59,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Constant: (name: string) => ngESDecorator;
+ function Constant(name: string): ngESDecorator;
/**
* Register controller
@@ -68,7 +68,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Controller: (name: string) => ngESDecorator;
+ function Controller(name: string): ngESDecorator;
/**
* Register decorator
@@ -77,7 +77,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Decorator: (name: string) => ngESDecorator;
+ function Decorator(name: string): ngESDecorator;
/**
* Register directive
@@ -86,7 +86,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Directive: (name: string) => ngESDecorator;
+ function Directive(name: string): ngESDecorator;
/**
* Register factory
@@ -95,7 +95,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Factory: (name: string) => ngESDecorator;
+ function Factory(name: string): ngESDecorator;
/**
* Register filter
@@ -104,7 +104,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Filter: (name: string) => ngESDecorator;
+ function Filter(name: string): ngESDecorator;
/**
* Add $inject property to target
@@ -113,7 +113,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Inject: (...dependencies: Array) => ngESDecorator;
+ function Inject(...dependencies: Array): ngESDecorator;
/**
* Inject dependencies as properties to target
@@ -122,7 +122,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var InjectAsProperty: (...dependencies: Array) => ngESDecorator;
+ function InjectAsProperty(...dependencies: Array): ngESDecorator;
/**
* Attach target to the specified module
@@ -131,7 +131,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Module: (name: string) => ngESDecorator;
+ function Module(name: string): ngESDecorator;
/**
* Register provider
@@ -140,14 +140,14 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Provider: (name: string) => ngESDecorator;
+ function Provider(name: string): ngESDecorator;
/**
* Register run block
*
* @returns {ngESDecorator} - decorated class
*/
- var Run: () => ngESDecorator;
+ function Run(): ngESDecorator;
/**
* Register service
@@ -156,7 +156,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Service: (name: string) => ngESDecorator;
+ function Service(name: string): ngESDecorator;
/**
* Register value
@@ -165,7 +165,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Value: (name: string) => ngESDecorator;
+ function Value(name: string): ngESDecorator;
export {
Component,
diff --git a/angular-jwt/angular-jwt-tests.ts b/angular-jwt/angular-jwt-tests.ts
index 3a6b7d6bf1..818899e829 100644
--- a/angular-jwt/angular-jwt-tests.ts
+++ b/angular-jwt/angular-jwt-tests.ts
@@ -15,3 +15,18 @@ var $jwtInterceptor: ng.jwt.IJwtInterceptor;
$jwtInterceptor.tokenGetter = () => {
return expToken;
}
+
+
+var authManager: ng.jwt.IAuthManagerServiceProvider;
+
+// Indicate the user is authenticated
+authManager.authenticate();
+
+// Indicate the user is unauthenticated
+authManager.unauthenticate();
+
+// Keep the user authenticated
+authManager.checkAuthOnRefresh();
+
+// Redirect the user on unauthorized requests
+authManager.redirectWhenUnauthenticated();
\ No newline at end of file
diff --git a/angular-jwt/angular-jwt.d.ts b/angular-jwt/angular-jwt.d.ts
index eb02cf24df..d1f9eb085f 100644
--- a/angular-jwt/angular-jwt.d.ts
+++ b/angular-jwt/angular-jwt.d.ts
@@ -27,4 +27,11 @@ declare namespace angular.jwt {
interface IJwtInterceptor {
tokenGetter(...params : any[]): string;
}
+
+ interface IAuthManagerServiceProvider {
+ authenticate(): void;
+ unauthenticate(): void;
+ checkAuthOnRefresh(): void;
+ redirectWhenUnauthenticated(): void;
+ }
}
diff --git a/angular-material/angular-material-tests.ts b/angular-material/angular-material-tests.ts
index 4464c599e3..c3ebcbaf99 100644
--- a/angular-material/angular-material-tests.ts
+++ b/angular-material/angular-material-tests.ts
@@ -127,15 +127,30 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia
instance.isOpen();
instance.isLockedOpen();
});
+
+ $scope['onClose'] = $mdSidenav(componentId).onClose(() => {});
});
myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService) => {
$scope['openToast'] = () => $mdToast.show($mdToast.simple().textContent('Hello!'));
+
+ $scope['customToast'] = () => {
+ var options = {
+ hideDelay: 3000,
+ position: 'top right',
+ controller : 'ToastCtrl',
+ templateUrl : 'toast-template.html',
+ toastClass: 'my-class'
+ };
+
+ $mdToast.show(options);
+ }
});
myApp.controller('PanelController', ($scope: ng.IScope, $mdPanel: ng.material.IPanelService) => {
$scope['createPanel'] = () => {
var config = {
+ id: 'myPanel',
template: '
Hello!
',
hasBackdrop: true,
disableParentScroll: true,
diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts
index 23da7bceb2..66852586da 100644
--- a/angular-material/angular-material.d.ts
+++ b/angular-material/angular-material.d.ts
@@ -22,7 +22,7 @@ declare namespace angular.material {
clickOutsideToClose?: boolean;
disableBackdrop?: boolean;
escapeToClose?: boolean;
- resolve?: {[index: string]: angular.IPromise};
+ resolve?: {[index: string]: () => angular.IPromise};
controllerAs?: string;
parent?: Function|string|Object; // default: root node
disableParentScroll?: boolean; // default: true
@@ -53,7 +53,7 @@ declare namespace angular.material {
controller(controller?: string|Function): T;
locals(locals?: {[index: string]: any}): T;
bindToController(bindToController?: boolean): T; // default: false
- resolve(resolve?: {[index: string]: angular.IPromise}): T;
+ resolve(resolve?: {[index: string]: () => angular.IPromise}): T;
controllerAs(controllerAs?: string): T;
parent(parent?: string|Element|JQuery): T; // default: root node
onComplete(onComplete?: Function): T;
@@ -91,7 +91,7 @@ declare namespace angular.material {
controller?: string|Function;
locals?: {[index: string]: any};
bindToController?: boolean; // default: false
- resolve?: {[index: string]: angular.IPromise}
+ resolve?: {[index: string]: () => angular.IPromise}
controllerAs?: string;
parent?: string|Element|JQuery; // default: root node
onShowing?: Function;
@@ -132,6 +132,7 @@ declare namespace angular.material {
close(): angular.IPromise;
isOpen(): boolean;
isLockedOpen(): boolean;
+ onClose(onClose: Function): void;
}
interface ISidenavService {
@@ -162,10 +163,11 @@ declare namespace angular.material {
preserveScope?: boolean; // default: false
hideDelay?: number; // default (ms): 3000
position?: string; // any combination of 'bottom'/'left'/'top'/'right'/'fit'; default: 'bottom left'
+ toastClass?: string;
controller?: string|Function;
locals?: {[index: string]: any};
bindToController?: boolean; // default: false
- resolve?: {[index: string]: angular.IPromise}
+ resolve?: {[index: string]: () => angular.IPromise}
controllerAs?: string;
parent?: string|Element|JQuery; // default: root node
}
@@ -291,13 +293,14 @@ declare namespace angular.material {
}
interface IPanelConfig {
+ id?: string;
template?: string;
templateUrl?: string;
controller?: string|Function;
controllerAs?: string;
bindToController?: boolean; // default: true
locals?: {[index: string]: any};
- resolve?: {[index: string]: angular.IPromise}
+ resolve?: {[index: string]: () => angular.IPromise}
attachTo?: string|JQuery|Element;
propagateContainerEvents?: boolean;
panelClass?: string;
diff --git a/angular-ui-scroll/angular-ui-scroll.d.ts b/angular-ui-scroll/angular-ui-scroll.d.ts
index 168c6ba271..5f24c8ec38 100644
--- a/angular-ui-scroll/angular-ui-scroll.d.ts
+++ b/angular-ui-scroll/angular-ui-scroll.d.ts
@@ -42,9 +42,10 @@ declare namespace angular.ui {
*/
topVisibleScope: ng.IRepeatScope;
/**
- * calling this method reinitializes and reloads the scroller content.
+ * calling this method reinitializes and reloads the scroller content.
+ * @param startIndex is an integer indicating what item index the scroller will use to start the load process.
*/
- reload(): void;
+ reload(startIndex?: number): void;
/**
* Replaces the item in the buffer at the given index with the new items.
*
diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts
index 441a7e1d3d..f7e803c1c8 100644
--- a/angularjs/angular-resource.d.ts
+++ b/angularjs/angular-resource.d.ts
@@ -42,15 +42,20 @@ declare namespace angular.resource {
(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
- actions?: any, options?: IResourceOptions): IResourceClass>;
+ actions?: IActionHash, options?: IResourceOptions): IResourceClass>;
(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
- actions?: any, options?: IResourceOptions): U;
+ actions?: IActionHash, options?: IResourceOptions): U;
(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
- actions?: any, options?: IResourceOptions): IResourceClass;
+ actions?: IActionHash, options?: IResourceOptions): IResourceClass;
+ }
+
+ // Hash of action descriptors allows custom action names
+ interface IActionHash {
+ [action: string]: IActionDescriptor
}
// Just a reference to facilitate describing new actions
@@ -186,6 +191,12 @@ declare namespace angular {
/** creating a resource service factory */
factory(name: string, resourceServiceFactoryFunction: angular.resource.IResourceServiceFactoryFunction): IModule;
}
+
+ namespace auto {
+ interface IInjectorService {
+ get(name: '$resource'): ng.resource.IResourceService;
+ }
+ }
}
interface Array
diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts
index 111ba86cce..1831bc0493 100644
--- a/angularjs/angular.d.ts
+++ b/angularjs/angular.d.ts
@@ -1,6 +1,6 @@
// Type definitions for Angular JS 1.5
// Project: http://angularjs.org
-// Definitions by: Diego Vilar
+// Definitions by: Diego Vilar , Georgii Dolzhykov
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -125,6 +125,7 @@ declare namespace angular {
isFunction(value: any): value is Function;
isNumber(value: any): value is number;
isObject(value: any): value is Object;
+ isObject(value: any): value is T;
isString(value: any): value is string;
isUndefined(value: any): boolean;
lowercase(str: string): string;
@@ -238,7 +239,6 @@ declare namespace angular {
* @param directiveFactory An injectable directive factory function.
*/
directive(name: string, inlineAnnotatedFunction: any[]): IModule;
- directive(name: string, injectionFunction: Function): IModule;
directive(object: Object): IModule;
/**
* Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider.
@@ -1412,6 +1412,16 @@ declare namespace angular {
* Absolute or relative URL of the resource that is being requested.
*/
url: string;
+ /**
+ * Event listeners to be bound to the XMLHttpRequest object.
+ * To bind events to the XMLHttpRequest upload object, use uploadEventHandlers. The handler will be called in the context of a $apply block.
+ */
+ eventHandlers?: { [type: string]: EventListenerOrEventListenerObject };
+ /**
+ * Event listeners to be bound to the XMLHttpRequest upload object.
+ * To bind events to the XMLHttpRequest object, use eventHandlers. The handler will be called in the context of a $apply block.
+ */
+ uploadEventHandlers?: { [type: string]: EventListenerOrEventListenerObject };
}
interface IHttpHeadersGetter {
diff --git a/atom/atom.d.ts b/atom/atom.d.ts
index 389d6ef16e..ac899ba5ac 100644
--- a/atom/atom.d.ts
+++ b/atom/atom.d.ts
@@ -946,9 +946,14 @@ declare namespace AtomCore {
registry: any;
repository: Object;
scopeName: string;
+ tokenizeLines: (text: string) => any;
// TBD
}
+
+ interface IGrammars {
+ grammarForScopeName(scope: string): IGrammar;
+ }
interface IPane /* extends Theorist.Model */ {
itemForURI: (uri:string)=>IEditor;
@@ -1302,6 +1307,7 @@ declare namespace AtomCore {
deserializers:IDeserializerManager;
config: IConfig;
commands: ICommandRegistry;
+ grammars: IGrammars;
keymaps: IKeymapManager;
keymap: IKeymapManager;
packages: IPackageManager;
diff --git a/autobind-decorator/autobind-decorator-tests.ts b/autobind-decorator/autobind-decorator-tests.ts
new file mode 100644
index 0000000000..e428604802
--- /dev/null
+++ b/autobind-decorator/autobind-decorator-tests.ts
@@ -0,0 +1,43 @@
+///
+
+import autobind = require('autobind-decorator');
+
+class Test {
+ public static what: string = 'static';
+
+ @autobind
+ public static test(): void {
+ console.log(this.what);
+ }
+
+ public constructor(public what: string) {
+ this.what = what;
+ }
+
+ @autobind
+ public test(): void {
+ console.warn(this.what);
+ }
+}
+
+const tester: Test = new Test('bind');
+const { test } = tester;
+tester.test(); // warns 'bind'.
+test(); // warns 'bind'.
+Test.test(); // logs 'static'.
+
+@autobind
+class Component {
+ public constructor(private someMember: string) {
+ this.someMember = someMember;
+ }
+
+ public someMethod(): void {
+ console.error(this.someMember);
+ }
+}
+
+const component: Component = new Component('React vs Angular2');
+const { someMethod } = component;
+component.someMethod(); // errors 'React vs Angular2'
+someMethod(); // errors 'React vs Angular2'
diff --git a/autobind-decorator/autobind-decorator.d.ts b/autobind-decorator/autobind-decorator.d.ts
new file mode 100644
index 0000000000..51ba89c9bf
--- /dev/null
+++ b/autobind-decorator/autobind-decorator.d.ts
@@ -0,0 +1,10 @@
+// Type definitions for autobind-decorator v1.3.3
+// Project: https://github.com/andreypopp/autobind-decorator
+// Definitions by: Ivo Stratev
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+declare module 'autobind-decorator' {
+ function autobind(target: TFunction): TFunction | void;
+ function autobind(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor | void;
+ export = autobind;
+}
diff --git a/autobind-decorator/autobind-decorator.ts.tscparams b/autobind-decorator/autobind-decorator.ts.tscparams
new file mode 100644
index 0000000000..1ee3d05cb6
--- /dev/null
+++ b/autobind-decorator/autobind-decorator.ts.tscparams
@@ -0,0 +1 @@
+--experimentalDecorators
diff --git a/aws-lambda/aws-lambda-tests.ts b/aws-lambda/aws-lambda-tests.ts
index 8b9f53a8ab..f562b59d3d 100644
--- a/aws-lambda/aws-lambda-tests.ts
+++ b/aws-lambda/aws-lambda-tests.ts
@@ -4,55 +4,29 @@ import lambda = require('aws-lambda');
var str: string;
var date: Date;
-var sns: lambda.SNS;
-var kinesis: lambda.Kinesis;
-var recordsList: lambda.Record[];
var anyObj: any;
var num: number;
-var identity: lambda.Identity;
+var identity: lambda.CognitoIdentity;
var error: Error;
-
-/* Records */
-var records: lambda.Records;
-
-recordsList = records.Records;
-
-/* Record */
-var record: lambda.Record;
-
-str = record.EventVersion;
-str = record.EventSubscriptionArn;
-str = record.EnventSource;
-sns = record.Sns;
-kinesis = record.kinesis;
-
-/* SNS */
-str = sns.Type;
-str = sns.MessageId;
-str = sns.TopicArn;
-str = sns.Subject;
-str = sns.Message;
-date = sns.Timestamp;
-
-/* Kinesis */
-var kinesis: lambda.Kinesis;
-
-str = kinesis.data;
+var b: boolean;
+var clientCtx: lambda.ClientContext;
/* Context */
var context: lambda.Context;
-context.log(str, anyObj);
-context.fail(str);
-context.succeed(str);
-context.succeed(anyObj);
-context.succeed(str, anyObj);
+b = context.callbackWaitsForEmptyEventLoop;
+str = context.functionName;
+str = context.functionVersion;
+str = context.invokedFunctionArn;
+num = context.memoryLimitInMB;
str = context.awsRequestId;
-num = context.getRemainingTimeInMillis();
+str = context.logGroupName;
+str = context.logStreamName;
identity = context.identity;
+clientCtx = context.clientContext;
-/* Identity */
-var identity: lambda.Identity;
+/* CognitoIdentity */
+var identity: lambda.CognitoIdentity;
str = identity.cognitoIdentityId;
str = identity.cognitoIdentityPoolId;
diff --git a/aws-lambda/aws-lambda.d.ts b/aws-lambda/aws-lambda.d.ts
index 081c6e0e3e..c9a66a3783 100644
--- a/aws-lambda/aws-lambda.d.ts
+++ b/aws-lambda/aws-lambda.d.ts
@@ -1,55 +1,68 @@
// Type definitions for AWS Lambda
// Project: http://docs.aws.amazon.com/lambda
-// Definitions by: Michael Skarum
+// Definitions by: James Darbyshire , Michael Skarum , Stef Heyenrath
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "aws-lambda" {
+ // Context
+ // http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
+ interface Context {
+ // Properties
+ callbackWaitsForEmptyEventLoop: boolean;
+ functionName: string;
+ functionVersion: string;
+ invokedFunctionArn: string;
+ memoryLimitInMB: number;
+ awsRequestId: string;
+ logGroupName: string;
+ logStreamName: string;
+ identity?: CognitoIdentity;
+ clientContext?: ClientContext;
+
+ // Functions
+ getRemainingTimeInMillis(): number;
- export interface Records {
- Records: Record[];
- }
- interface Record {
- EventVersion: string;
- EventSubscriptionArn: string;
- EnventSource: string;
- Sns: SNS;
- kinesis: Kinesis;
- }
- interface SNS {
- Type: string;
- MessageId: string;
- TopicArn: string;
- Subject: string;
- Message: string;
- Timestamp: Date;
- }
-
- interface Kinesis {
- data: string;
- }
-
- export interface Context {
+ // Functions for compatibility with earlier Node.js Runtime v0.10.42
log(message: string, object: any): void;
fail(message: string): void;
succeed(message: string): void;
succeed(object: any): void;
- succeed(message: string, object: any): void;
- awsRequestId: string;
- getRemainingTimeInMillis(): number;
- /** Information about the Amazon Cognito identity provider when invoked through the AWS Mobile SDK. It can be null. */
- identity?: Identity;
+ succeed(message: string, object: any): void;
}
-
- interface Identity {
+
+ interface CognitoIdentity {
cognitoIdentityId: string;
cognitoIdentityPoolId: string;
}
-
+
+ interface ClientContext {
+ client: ClientContextClient;
+ Custom?: any;
+ env: ClientContextEnv;
+ }
+
+ interface ClientContextClient {
+ installationId: string;
+ appTitle: string;
+ appVersionName: string;
+ appVersionCode: string;
+ appPackageName: string;
+ }
+
+ interface ClientContextEnv {
+ platformVersion: string;
+ platform: string;
+ make: string;
+ model: string;
+ locale: string;
+ }
+
/**
* Optional callback parameter.
+ * http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
*
- * @param error – an optional parameter that you can use to provide results of the failed Lambda function execution.
- * @param result – an optional parameter that you can use to provide the result of a successful function execution. The result provided must be JSON.stringify compatible.
+ * @param error – an optional parameter that you can use to provide results of the failed Lambda function execution.
+ * @param result – an optional parameter that you can use to provide the result of a successful function execution. The result provided must be JSON.stringify compatible.
*/
export type Callback = (error?: Error, result?: any) => void;
}
\ No newline at end of file
diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts
index cb35f34e97..09ec2f6267 100644
--- a/aws-sdk/aws-sdk.d.ts
+++ b/aws-sdk/aws-sdk.d.ts
@@ -226,7 +226,7 @@ declare module "aws-sdk" {
constructor(options?: any);
endpoint: Endpoint;
- getObject(params: s3.GetObjectRequest, callback: (err: Error, data: any) => void): void;
+ getObject(params: s3.GetObjectRequest, callback?: (err: Error, data: any) => void): any;
putObject(params: s3.PutObjectRequest, callback: (err: Error, data: any) => void): void;
deleteObject(params: s3.DeleteObjectRequest, callback: (err: Error, data: any) => void): void;
headObject(params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void;
@@ -235,6 +235,12 @@ declare module "aws-sdk" {
upload(params?: s3.PutObjectRequest, options?: s3.UploadOptions, callback?: (err: Error, data: any) => void): void;
listObjects(params: s3.ListObjectRequest, callback: (err: Error, data: s3.ListObjectResponse) => void): void;
listObjectsV2(params: s3.ListObjectV2Request, callback: (err: Error, data: s3.ListObjectV2Response) => void): void;
+ waitFor(state: string, params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void;
+
+ createMultipartUpload(params: any, callback: (err: Error, data: any) => void): void;
+ uploadPart(params: any, callback: (err: Error, data: any) => void): void;
+ listParts(params: any, callback: (err: Error, data: any) => void): void;
+ completeMultipartUpload(params: any, callback: (err: Error, data: any) => void): void;
}
export class STS {
diff --git a/axe-core/axe-core-tests.ts b/axe-core/axe-core-tests.ts
new file mode 100644
index 0000000000..7decb865c2
--- /dev/null
+++ b/axe-core/axe-core-tests.ts
@@ -0,0 +1,91 @@
+///
+
+var context:any = document
+var $fixture:any = {}
+
+// axe.a11yCheck config
+axe.a11yCheck(context, {}, (results) => {
+ // axe's results object
+ console.log(results.passes.length)
+ console.log(results.violations.length)
+});
+// axe.a11yCheck include/exclude
+axe.a11yCheck({include: [['#id1'], ['#id2']]}, {}, (results) => {
+ console.log(results)
+})
+axe.a11yCheck({exclude: [$fixture[0]]}, {}, (results) => {
+ console.log(results)
+})
+var tagConfigRunOnly: axe.RunOnly = {
+ type: 'tag',
+ values: ['wcag2a']
+}
+var tagConfig = {
+ runOnly: tagConfigRunOnly
+}
+axe.a11yCheck(context, tagConfig, (results) => {
+ console.log(results)
+})
+var includeExcludeTagsRunOnly: axe.RunOnly = {
+ type: 'tags',
+ value: {
+ include: ['wcag2a', 'wcag2aa'],
+ exclude: ['experimental']
+ }
+}
+var includeExcludeTagsConfig = {
+ runOnly: includeExcludeTagsRunOnly
+}
+axe.a11yCheck(context, includeExcludeTagsConfig, (results) => {
+ console.log(results)
+})
+var someRulesConfig = {
+ rules: {
+ "color-contrast": {enabled: 'false'},
+ "heading-order": {enabled: 'true'}
+ }
+}
+axe.a11yCheck(context, someRulesConfig, (results) => {
+ console.log(results)
+})
+
+// axe.configure
+var spec: axe.Spec = {
+ branding: {
+ brand: 'foo',
+ application: 'bar'
+ },
+ reporter: 'v1',
+ checks: [{
+ id: 'custom-check',
+ evaluate: function() {
+ return true
+ }
+ }],
+ rules: [{
+ id: 'custom-rule',
+ any: ['custom-check']
+ }]
+}
+axe.configure(spec)
+
+axe.reset()
+
+axe.getRules(['wcag2aa'])
+typeof axe.getRules() === 'object'
+
+// Plugins
+var pluginSrc: axe.AxePlugin = {
+ id: 'doStuff',
+ run: (data:any, callback:Function) => {
+ callback()
+ },
+ commands: [{
+ id: 'run-doStuff',
+ callback: (data:any, callback:Function) => {
+ axe.plugins['doStuff'].run(data, callback)
+ }
+ }]
+}
+axe.registerPlugin(pluginSrc)
+axe.cleanup()
diff --git a/axe-core/axe-core.d.ts b/axe-core/axe-core.d.ts
new file mode 100644
index 0000000000..98818e75cc
--- /dev/null
+++ b/axe-core/axe-core.d.ts
@@ -0,0 +1,159 @@
+// Type definitions for axe-core 2.0.5
+// Project: https://github.com/dequelabs/axe-core
+// Definitions by: Marcy Sutton
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+declare namespace axe {
+
+ export type ImpactValue = "minor" | "moderate" | "serious" | "critical";
+
+ export type TagValue = "wcag2a" | "wcag2aa" | "section508" | "best-practice";
+
+ export type ReporterVersion = "v1" | "v2";
+
+ export type RunOnlyType = "rule" | "rules" | "tag" | "tags";
+
+ export interface ElementContext {
+ node?: Object,
+ selector?: string,
+ include?: any[],
+ exclude?: any[]
+ }
+ export interface RunOnly {
+ type: RunOnlyType,
+ value?: {
+ include?: string[],
+ exclude?: string[]
+ }
+ values?: TagValue[]
+ }
+ export interface AxeResults {
+ url: string,
+ timestamp: string,
+ passes: Pass[],
+ violations: Violation[]
+ }
+ export interface Pass {
+ description: string,
+ help: string,
+ helpUrl: string,
+ id: string,
+ impact: ImpactValue,
+ tags: TagValue[],
+ nodes: NodeResult[]
+ }
+ export interface Violation {
+ description: string,
+ help: string,
+ helpUrl: string,
+ id: string,
+ impact: ImpactValue,
+ tags: TagValue[],
+ nodes: NodeResult[]
+ }
+ export interface NodeResult {
+ html: string,
+ impact: ImpactValue,
+ target: string[],
+ any: CheckResult[],
+ all: CheckResult[],
+ none: CheckResult[]
+ }
+ export interface CheckResult {
+ id: string,
+ impact: string,
+ message: string,
+ data: any,
+ relatedNodes?: RelatedNode[]
+ }
+ export interface RelatedNode {
+ target: string[],
+ html: string
+ }
+ export interface Spec {
+ branding?: {
+ brand: string,
+ application: string
+ },
+ reporter?: ReporterVersion,
+ checks?: Check[],
+ rules?: Rule[]
+ }
+ export interface Check {
+ id: string,
+ evaluate: Function,
+ after?: Function,
+ options?: any,
+ matches?: string,
+ enabled?: boolean
+ }
+ export interface Rule {
+ id: string,
+ selector?: string,
+ excludeHidden?: boolean,
+ enabled?: boolean,
+ pageLevel?: boolean,
+ any?: string[],
+ all?: string[],
+ none?: string[],
+ tags?: string[],
+ matches?: string
+ }
+ export interface AxePlugin {
+ id: string,
+ run(...args:any[]): any,
+ commands: {
+ id: string,
+ callback(...args:any[]): void
+ }[],
+ cleanup?(callback:Function): void
+ }
+
+ export let plugins: any
+
+ /**
+ * Starts analysis on the current document and its subframes
+ *
+ * @param {Object} context The `Context` specification object @see Context
+ * @param {Array} options Options passed into rules or checks, temporarily modifyint them.
+ * @param {Function} callback The function to invoke when analysis is complete.
+ * @returns {Object} results The aXe results object
+ */
+ export function a11yCheck(context: ElementContext, options: {runOnly?: RunOnly, rules?: Object}, callback: (results:AxeResults) => void): AxeResults
+
+ /**
+ * Method for configuring the data format used by aXe. Helpful for adding new
+ * rules, which must be registered with the library to execute.
+ * @param {Spec} Spec Object with valid `branding`, `reporter`, `checks` and `rules` data
+ */
+ export function configure(spec: Spec): void
+
+ /**
+ * Searches and returns rules that contain a tag in the list of tags.
+ * @param {Array} tags Optional array of tags
+ * @return {Array} Array of rules
+ */
+ export function getRules(tags?: string[]): Object[]
+
+ /**
+ * Restores the default axe configuration
+ */
+ export function reset(): void
+
+ /**
+ * Function to register a plugin configuration in document and its subframes
+ * @param {Object} plugin A plugin configuration object
+ */
+ export function registerPlugin(plugin: AxePlugin): void
+
+ /**
+ * Function to clean up plugin configuration in document and its subframes
+ */
+ export function cleanup(): void
+
+}
+
+// axe is also available as a module
+declare module "axe-core" {
+ export = axe;
+}
diff --git a/azure-mobile-apps/azure-mobile-apps-tests.ts b/azure-mobile-apps/azure-mobile-apps-tests.ts
index 093932c2fb..302f732889 100644
--- a/azure-mobile-apps/azure-mobile-apps-tests.ts
+++ b/azure-mobile-apps/azure-mobile-apps-tests.ts
@@ -72,6 +72,13 @@ table.read.use([function () {}, function () {}]);
table.read.use(function () {}, function () {});
table.use(function () {}).use(function () {}).read(function () {}).use(function () {})
+table.access = undefined;
+table.access = 'authenticated';
+table.read.access = 'anonymous';
+table.update.access = 'disabled';
+table.delete.access = 'authenticated';
+table.insert.access = 'authenticated';
+
// Express.Table, instantiated from the static require('azure-mobile-apps').table()
// This is going to be interesting if we ever support more than one provider
var table2 = mobileApps.table();
@@ -84,4 +91,14 @@ mobileApps.logger.debug('a debug message')
// Query
queries.create('table').where({ x: 10 }).select('col1,col2');
-mobileApps.query.create('table');
\ No newline at end of file
+mobileApps.query.create('table');
+
+// custom sql query
+mobileApp.api.add('query', { authorize: true, get: (req, res, next) => {
+ req.azureMobile.data.execute({
+ sql: "SELECT * FROM TODOITEM WHERE COMPLETE = :complete",
+ parameters: [
+ { name: 'complete', value: 1 }
+ ]
+ }).then(x => {});
+}, delete: function () {} });
diff --git a/azure-mobile-apps/azure-mobile-apps.d.ts b/azure-mobile-apps/azure-mobile-apps.d.ts
index 0a42fa9ecf..a17e41e2d6 100644
--- a/azure-mobile-apps/azure-mobile-apps.d.ts
+++ b/azure-mobile-apps/azure-mobile-apps.d.ts
@@ -47,6 +47,7 @@ declare namespace Azure.MobileApps {
interface Table {
authorize?: boolean;
+ access?: AccessType;
autoIncrement?: boolean;
dynamicSchema?: boolean;
name: string;
@@ -66,8 +67,11 @@ declare namespace Azure.MobileApps {
(operationHandler: (context: Context) => void): Table;
use(...middleware: Middleware[]): Table;
use(middleware: Middleware[]): Table;
+ access: AccessType;
}
+ type AccessType = 'anonymous' | 'authenticated' | 'disabled';
+
interface Tables {
configuration: Configuration;
add(name: string, definition?: Table | TableDefinition): void;
@@ -215,7 +219,7 @@ declare namespace Azure.MobileApps {
item: any;
req: Express.Request;
res: Express.Response;
- data: (table: TableDefinition) => Data.Table;
+ data: ContextData;
tables: (tableName: string) => Data.Table;
user: User;
push: typeof nh;
@@ -223,6 +227,21 @@ declare namespace Azure.MobileApps {
execute(): Thenable;
}
+ interface ContextData {
+ (table: TableDefinition): Data.Table;
+ execute(q: SqlQueryDefinition): Thenable;
+ }
+
+ interface SqlQueryDefinition {
+ sql: string;
+ parameters?: SqlParameterDefinition[];
+ }
+
+ interface SqlParameterDefinition {
+ name: string;
+ value: any;
+ }
+
interface TableDefinition {
authorize?: boolean;
autoIncrement?: boolean;
diff --git a/azure-mobile-services-client/AzureMobileServicesClient.d.ts b/azure-mobile-services-client/AzureMobileServicesClient.d.ts
index afd6014598..6fa0f9c475 100644
--- a/azure-mobile-services-client/AzureMobileServicesClient.d.ts
+++ b/azure-mobile-services-client/AzureMobileServicesClient.d.ts
@@ -17,7 +17,7 @@ declare namespace Microsoft.WindowsAzure {
login(provider: string, token: string): asyncPromise;
login(provider: string, callback: (error: any, user: User) => void ): void;
login(provider: string): asyncPromise;
- logout(): void;
+ logout(): asyncPromise;
getTable(tableName: string): MobileServiceTable;
withFilter(serviceFilter: (request: any, next: (request: any, callback: (error: any, response: any) => void) => void, callback: (error: any, response: any) => void) => void): MobileServiceClient;
/**
diff --git a/backlog-js/backlog-js-tests.ts b/backlog-js/backlog-js-tests.ts
new file mode 100644
index 0000000000..979eb57ca4
--- /dev/null
+++ b/backlog-js/backlog-js-tests.ts
@@ -0,0 +1,88 @@
+///
+
+import * as backlogjs from 'backlog-js';
+
+const host = 'example.backlog.jp';
+const apiKey = 'apiKey';
+const clientId = 'clientId';
+const clientSecret = 'clientSecret';
+const redirectUri = 'redirectUri';
+const state = 'state';
+const code = 'code';
+const refreshToken = 'refreshToken';
+const configure = { host, apiKey }
+const credentials = { clientId, clientSecret }
+
+const oauth2 = new backlogjs.OAuth2(credentials);
+oauth2.getAuthorizationURL({ host, redirectUri, state });
+oauth2.getAccessToken({ host, code, redirectUri }).then(data => {}).catch(err => {});
+oauth2.refreshAccessToken({ host, refreshToken }).then(data => {}).catch(err => {});
+
+const backlog = new backlogjs.Backlog(configure);
+backlog.getSpace().then(data => { }).catch(err => { });
+backlog.getSpaceActivities({
+ activityTypeId: [
+ backlogjs.Option.ActivityType.IssueCreated,
+ backlogjs.Option.ActivityType.IssueUpdated
+ ],
+ minId: 1,
+ maxId: 2,
+ count: 3,
+ order: "asc"
+}).then(data => { }).catch(err => { });
+backlog.getSpaceDiskUsage().then(data => { }).catch(err => { });
+backlog.getSpaceIcon().then(data => { }).catch(err => { });
+backlog.postSpaceAttachment(new FormData()).then(data => { }).catch(err => { });
+backlog.getUsers().then(data => { }).catch(err => { });
+backlog.getUser(1).then(data => { }).catch(err => { });
+backlog.postUser({
+ userId: 'string',
+ password: 'string',
+ name: 'string',
+ mailAddress: 'string',
+ roleType: backlogjs.Option.User.RoleType.Admin
+}).then(data => { }).catch(err => { });
+backlog.patchUser(1, {
+ password: 'string',
+ name: 'string',
+ mailAddress: 'string',
+ roleType: backlogjs.Option.User.RoleType.Admin
+}).then(data => { }).catch(err => { });
+backlog.deleteUser(1).then(data => { }).catch(err => { });
+backlog.getMyself().then(data => { }).catch(err => { });
+backlog.getUserActivities(1, {
+ activityTypeId: [
+ backlogjs.Option.ActivityType.IssueCreated,
+ backlogjs.Option.ActivityType.IssueUpdated
+ ],
+ minId: 1,
+ maxId: 2,
+ count: 3,
+ order: "asc"
+}).then(data => { }).catch(err => { });
+backlog.getUserStars(1, {
+ minId: 1,
+ maxId: 2,
+ count: 3,
+ order: "asc"
+}).then(data => { }).catch(err => { });
+backlog.getUserStarsCount(1, {
+ since: 'YYYY-MM-DD',
+ until: 'YYYY-MM-DD'
+}).then(data => { }).catch(err => { });
+backlog.getRecentlyViewedIssues({
+ order: 'asc',
+ offset: 1,
+ count: 2
+}).then(data => { }).catch(err => { });
+backlog.getRecentlyViewedProjects({
+ order: 'asc',
+ offset: 1,
+ count: 2
+}).then(data => { }).catch(err => { });
+backlog.getRecentlyViewedWikis({
+ order: 'asc',
+ offset: 1,
+ count: 2
+}).then(data => { }).catch(err => { });
+backlog.getUserIcon(1).then(data => {}).catch(err => {});
diff --git a/backlog-js/backlog-js.d.ts b/backlog-js/backlog-js.d.ts
new file mode 100644
index 0000000000..353e7e90cd
--- /dev/null
+++ b/backlog-js/backlog-js.d.ts
@@ -0,0 +1,695 @@
+// Type definitions for backlog-js 0.9.0
+// Project: https://github.com/nulab/backlog-js
+// Definitions by: Yuichi Watanabe
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+///
+///
+///
+
+declare module 'backlog-js' {
+
+ class Request {
+ private configure;
+ constructor(configure: {
+ host: string;
+ apiKey?: string;
+ accessToken?: string;
+ timeout?: number;
+ });
+ get(path: string, params?: any): Promise;
+ post(path: string, params?: any): Promise;
+ put(path: string, params: any): Promise;
+ patch(path: string, params: any): Promise;
+ delete(path: string, params?: any): Promise;
+ request(options: {
+ method: string;
+ path: string;
+ params?: Params | FormData;
+ }): Promise;
+ checkStatus(response: IResponse): Promise;
+ parseJSON(response: IResponse): Promise;
+ private toFormData(params);
+ private toQueryString(params);
+ webAppBaseURL: string;
+ restBaseURL: string;
+ }
+
+ type Params = {
+ [index: string]: number | string | number[] | string[];
+ };
+
+ export class Backlog extends Request {
+ constructor(configure: {
+ host: string;
+ apiKey?: string;
+ accessToken?: string;
+ timeout?: number;
+ });
+ getSpace(): Promise;
+ getSpaceActivities(params: Option.Space.GetActivitiesParams): Promise;
+ getSpaceNotification(): Promise;
+ putSpaceNotification(params: Option.Space.PutSpaceNotificationParams): Promise;
+ getSpaceDiskUsage(): Promise;
+ getSpaceIcon(): Promise;
+ postSpaceAttachment(form: FormData): Promise;
+ getUsers(): Promise;
+ getUser(userId: number): Promise;
+ postUser(params: Option.User.PostUserParams): Promise;
+ patchUser(userId: number, params: Option.User.PatchUserParams): Promise;
+ deleteUser(userId: number): Promise;
+ getMyself(): Promise;
+ getUserActivities(userId: number, params: Option.User.GetUserActivitiesParams): Promise;
+ getUserStars(userId: number, params: Option.User.GetUserStarsParams): Promise;
+ getUserStarsCount(userId: number, params: Option.User.GetUserStarsCountParams): Promise;
+ getRecentlyViewedIssues(params: Option.User.GetRecentlyViewedParams): Promise;
+ getRecentlyViewedProjects(params: Option.User.GetRecentlyViewedParams): Promise;
+ getRecentlyViewedWikis(params: Option.User.GetRecentlyViewedParams): Promise;
+ getUserIcon(userId: number): Promise;
+ getGroups(params: Option.Group.GetGroupsParams): Promise;
+ postGroups(params: Option.Group.PostGroupsParams): Promise;
+ getGroup(groupId: number): Promise;
+ patchGroup(groupId: number, params: Option.Group.PatchGroupParams): Promise;
+ deleteGroup(groupId: number): Promise;
+ getStatuses(): Promise;
+ getResolutions(): Promise;
+ getPriorities(): Promise;
+ postProject(params: Option.Project.PostProjectParams): Promise;
+ getProjects(params?: Option.Project.GetProjectsParams): Promise;
+ getProject(projectIdOrKey: string): Promise;
+ patchProject(projectIdOrKey: string, params: Option.Project.PatchProjectParams): Promise;
+ deleteProject(projectIdOrKey: string): Promise;
+ getProjectActivities(projectIdOrKey: string, params: Option.Space.GetActivitiesParams): Promise;
+ getProjectUsers(projectIdOrKey: string): Promise;
+ deleteProjectUsers(projectIdOrKey: string, params: Option.Project.DeleteProjectUsersParams): Promise;
+ postProjectAdministrators(projectIdOrKey: string, params: Option.Project.PostProjectAdministrators): Promise;
+ getProjectAdministrators(projectIdOrKey: string): Promise;
+ deleteProjectAdministrators(projectIdOrKey: string, params: Option.Project.DeleteProjectAdministrators): Promise;
+ getIssueTypes(projectIdOrKey: string): Promise;
+ postIssueType(projectIdOrKey: string, params: Option.Project.PostIssueTypeParams): Promise;
+ patchIssueType(projectIdOrKey: string, id: number, params: Option.Project.PatchIssueTypeParams): Promise;
+ deleteIssueType(projectIdOrKey: string, id: number, params: Option.Project.DeleteIssueTypeParams): Promise;
+ getCategories(projectIdOrKey: string): Promise;
+ postCategories(projectIdOrKey: string, params: Option.Project.PostCategoriesParams): Promise;
+ patchCategories(projectIdOrKey: string, id: number, params: Option.Project.PatchCategoriesParams): Promise;
+ deleteCategories(projectIdOrKey: string, id: number): Promise;
+ getVersions(projectIdOrKey: string): Promise;
+ postVersions(projectIdOrKey: string, params: Option.Project.PostVersionsParams): Promise;
+ patchVersions(projectIdOrKey: string, id: number, params: Option.Project.PatchVersionsParams): Promise;
+ deleteVersions(projectIdOrKey: string, id: number): Promise;
+ getCustomFields(projectIdOrKey: string): Promise;
+ postCustomField(projectIdOrKey: string, params: Option.Project.PostCustomFieldParams | Option.Project.PostCustomFieldWithNumericParams | Option.Project.PostCustomFieldWithDateParams | Option.Project.PostCustomFieldWithListParams): Promise;
+ patchCustomField(projectIdOrKey: string, id: number, params: Option.Project.PatchCustomFieldParams | Option.Project.PatchCustomFieldWithNumericParams | Option.Project.PatchCustomFieldWithDateParams | Option.Project.PatchCustomFieldWithListParams): Promise;
+ deleteCustomField(projectIdOrKey: string, id: number): Promise;
+ postCustomFieldItem(projectIdOrKey: string, id: number, params: Option.Project.PostCustomFieldItemParams): Promise;
+ patchCustomFieldItem(projectIdOrKey: string, id: number, itemId: number, params: Option.Project.PatchCustomFieldItemParams): Promise;
+ deleteCustomFieldItem(projectIdOrKey: string, id: number, params: Option.Project.PostCustomFieldItemParams): Promise;
+ getSharedFiles(projectIdOrKey: string, path: string, params: Option.Project.GetSharedFilesParams): Promise;
+ getProjectsDiskUsage(projectIdOrKey: string): Promise;
+ getWebhooks(projectIdOrKey: string): Promise;
+ postWebhook(projectIdOrKey: string, params: Option.Project.PostWebhookParams): Promise;
+ getWebhook(projectIdOrKey: string, webhookId: string): Promise;
+ patchWebhook(projectIdOrKey: string, webhookId: string, params: Option.Project.PatchWebhookParams): Promise;
+ deleteWebhook(projectIdOrKey: string, webhookId: string): Promise;
+ postIssue(params: Option.Issue.PostIssueParams): Promise;
+ patchIssue(issueIdOrKey: string, params: Option.Issue.PatchIssueParams): Promise;
+ getIssues(params?: Option.Issue.GetIssuesParams): Promise;
+ getIssue(issueIdOrKey: string): Promise;
+ getIssuesCount(params?: Option.Issue.GetIssuesParams): Promise;
+ deleteIssuesCount(issueIdOrKey: string): Promise;
+ getIssueComments(issueIdOrKey: string, params: Option.Issue.GetIssueCommentsParams): Promise;
+ postIssueComments(issueIdOrKey: string, params: Option.Issue.PostIssueCommentsParams): Promise;
+ getIssueCommentsCount(issueIdOrKey: string): Promise;
+ getIssueComment(issueIdOrKey: string, commentId: number): Promise;
+ patchIssueComment(issueIdOrKey: string, commentId: number, params: Option.Issue.PatchIssueCommentParams): Promise;
+ getIssueCommentNotifications(issueIdOrKey: string, commentId: number): Promise;
+ postIssueCommentNotifications(issueIdOrKey: string, commentId: number, prams: Option.Issue.IssueCommentNotifications): Promise;
+ getIssueAttachments(issueIdOrKey: string): Promise;
+ deleteIssueAttachment(issueIdOrKey: string, attachmentId: string): Promise;
+ getIssueSharedFiles(issueIdOrKey: string): Promise;
+ linkIssueSharedFiles(issueIdOrKey: string, params: Option.Issue.LinkIssueSharedFilesParams): Promise;
+ unlinkIssueSharedFile(issueIdOrKey: string, id: number): Promise;
+ getWikis(projectIdOrKey: number): Promise;
+ getWikisCount(projectIdOrKey: number): Promise;
+ getWikisTags(projectIdOrKey: number): Promise;
+ postWiki(params: Option.Wiki.PostWikiParams): Promise;
+ getWiki(wikiId: number): Promise;
+ patchWiki(wikiId: number, params: Option.Wiki.PatchWikiParams): Promise;
+ deleteWiki(wikiId: number, mailNotify: boolean): Promise;
+ getWikisAttachments(wikiId: number): Promise;
+ postWikisAttachments(wikiId: number, attachmentId: number[]): Promise;
+ deleteWikisAttachments(wikiId: number, attachmentId: number): Promise;
+ getWikisSharedFiles(wikiId: number): Promise;
+ linkWikisSharedFiles(wikiId: number, fileId: number[]): Promise;
+ unlinkWikisSharedFiles(wikiId: number, id: number): Promise;
+ getWikisHistory(wikiId: number, params: Option.Wiki.GetWikisHistoryParams): Promise;
+ getWikisStars(wikiId: number): Promise;
+ postStar(params: Option.Project.PostStarParams): Promise;
+ getNotifications(params: Option.Notification.GetNotificationsParams): Promise;
+ getNotificationsCount(params: Option.Notification.GetNotificationsCountParams): Promise;
+ resetNotificationsMarkAsRead(): Promise;
+ markAsReadNotification(id: number): Promise;
+ getGitRepositories(projectIdOrKey: string): Promise;
+ getGitRepository(projectIdOrKey: string, repoIdOrName: string): Promise;
+ getPullRequests(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.GetPullRequestsParams): Promise;
+ getPullRequestsCount(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.GetPullRequestsParams): Promise;
+ postPullRequest(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.PostPullRequestParams): Promise;
+ getPullRequest(projectIdOrKey: string, repoIdOrName: string, number: number): Promise;
+ patchPullRequest(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.PatchPullRequestParams): Promise;
+ getPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.GetPullRequestCommentsParams): Promise;
+ postPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.PostPullRequestCommentsParams): Promise;
+ getPullRequestCommentsCount(projectIdOrKey: string, repoIdOrName: string, number: number): Promise;
+ patchPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, commentId: number, params: Option.PullRequest.PatchPullRequestCommentsParams): Promise;
+ getPullRequestAttachments(projectIdOrKey: string, repoIdOrName: string, number: number): Promise;
+ deletePullRequestAttachment(projectIdOrKey: string, repoIdOrName: string, number: number, attachmentId: number): Promise;
+ getProjectIcon(projectIdOrKey: string): Promise;
+ getSharedFile(projectIdOrKey: string, sharedFileId: number): Promise;
+ getIssueAttachment(issueIdOrKey: string, attachmentId: number): Promise;
+ getWikiAttachment(wikiId: number, attachmentId: number): Promise;
+ getPullRequestAttachment(projectIdOrKey: string, repoIdOrName: string, number: number, attachmentId: number): Promise;
+ private download(path);
+ private upload(path, params);
+ private parseFileData(response);
+ }
+
+ export class OAuth2 {
+ private credentials;
+ private timeout;
+ constructor(credentials: Option.OAuth2.Credentials, timeout?: number);
+ getAuthorizationURL(options: {
+ host: string;
+ redirectUri?: string;
+ state?: string;
+ }): string;
+ getAccessToken(options: {
+ host: string;
+ code: string;
+ redirectUri?: string;
+ }): Promise;
+ refreshAccessToken(options: {
+ host: string;
+ refreshToken: string;
+ }): Promise;
+ }
+
+ import { PassThrough } from 'stream';
+ export namespace Entity {
+ export namespace File {
+ export type FileData = NodeFileData | BrowserFileData;
+ export interface NodeFileData {
+ body: PassThrough;
+ url: string;
+ filename: string;
+ }
+ export interface BrowserFileData {
+ body: any;
+ url: string;
+ blob?: () => Promise;
+ }
+ }
+ export namespace OAuth2 {
+ export interface AccessToken {
+ access_token: string;
+ token_type: string;
+ expires_in: number;
+ refresh_token: string;
+ }
+ }
+ }
+
+
+ export namespace Option {
+ export type Order = "asc" | "desc";
+ export enum ActivityType {
+ Undefined = -1,
+ IssueCreated = 1,
+ IssueUpdated = 2,
+ IssueCommented = 3,
+ IssueDeleted = 4,
+ WikiCreated = 5,
+ WikiUpdated = 6,
+ WikiDeleted = 7,
+ FileAdded = 8,
+ FileUpdated = 9,
+ FileDeleted = 10,
+ SvnCommitted = 11,
+ GitPushed = 12,
+ GitRepositoryCreated = 13,
+ IssueMultiUpdated = 14,
+ ProjectUserAdded = 15,
+ ProjectUserRemoved = 16,
+ NotifyAdded = 17,
+ PullRequestAdded = 18,
+ PullRequestUpdated = 19,
+ PullRequestCommented = 20,
+ PullRequestMerged = 21,
+ }
+ export namespace Notification {
+ export interface GetNotificationsParams {
+ minId?: number;
+ maxId?: number;
+ count?: number;
+ order?: Order;
+ }
+ export interface GetNotificationsCountParams {
+ alreadyRead: boolean;
+ resourceAlreadyRead: boolean;
+ }
+ }
+ export namespace Space {
+ export interface GetActivitiesParams {
+ activityTypeId?: ActivityType[];
+ minId?: number;
+ maxId?: number;
+ count?: number;
+ order?: Order;
+ }
+ export interface PutSpaceNotificationParams {
+ content: string;
+ }
+ }
+ export namespace User {
+ export interface PostUserParams {
+ userId: string;
+ password: string;
+ name: string;
+ mailAddress: string;
+ roleType: RoleType;
+ }
+ export interface PatchUserParams {
+ password?: string;
+ name?: string;
+ mailAddress?: string;
+ roleType?: RoleType;
+ }
+ export enum RoleType {
+ Admin = 1,
+ User = 2,
+ Reporter = 3,
+ Viewer = 4,
+ GuestReporter = 5,
+ GuestViewer = 6,
+ }
+ export interface GetUserActivitiesParams {
+ activityTypeId?: ActivityType[];
+ minId?: number;
+ maxId?: number;
+ count?: number;
+ order?: Order;
+ }
+ export interface GetUserStarsParams {
+ minId?: number;
+ maxId?: number;
+ count?: number;
+ order?: Order;
+ }
+ export interface GetUserStarsCountParams {
+ since?: string;
+ until?: string;
+ }
+ export interface GetRecentlyViewedParams {
+ order?: Order;
+ offset?: number;
+ count?: number;
+ }
+ }
+ export namespace Group {
+ export interface GetGroupsParams {
+ order?: Order;
+ offset?: number;
+ count?: number;
+ }
+ export interface PostGroupsParams {
+ name: string;
+ members?: string[];
+ }
+ export interface PatchGroupParams {
+ name?: string;
+ members?: string[];
+ }
+ }
+ export namespace Project {
+ export type TextFormattingRule = "backlog" | "markdown";
+ export interface PostProjectParams {
+ name: string;
+ key: string;
+ chartEnabled: boolean;
+ projectLeaderCanEditProjectLeader?: boolean;
+ subtaskingEnabled: boolean;
+ textFormattingRule: TextFormattingRule;
+ }
+ export interface PatchProjectParams {
+ name?: string;
+ key?: string;
+ chartEnabled?: boolean;
+ subtaskingEnabled?: boolean;
+ projectLeaderCanEditProjectLeader?: boolean;
+ textFormattingRule?: TextFormattingRule;
+ archived?: boolean;
+ }
+ export interface GetProjectsParams {
+ archived?: boolean;
+ all?: boolean;
+ }
+ export interface DeleteProjectUsersParams {
+ userId: number;
+ }
+ export interface PostProjectAdministrators {
+ userId: number;
+ }
+ export interface DeleteProjectAdministrators {
+ userId: number;
+ }
+ export type IssueTypeColor = "#e30000" | "#990000" | "#934981" | "#814fbc" | "#2779ca" | "#007e9a" | "#7ea800" | "#ff9200" | "#ff3265" | "#666665";
+ export interface PostIssueTypeParams {
+ name: string;
+ color: IssueTypeColor;
+ }
+ export interface PatchIssueTypeParams {
+ name?: string;
+ color?: IssueTypeColor;
+ }
+ export interface DeleteIssueTypeParams {
+ substituteIssueTypeId: number;
+ }
+ export interface PostCategoriesParams {
+ name: string;
+ }
+ export interface PatchCategoriesParams {
+ name: string;
+ }
+ export interface PostVersionsParams {
+ name: string;
+ description: string;
+ startDate: string;
+ releaseDueDate: string;
+ }
+ export interface PatchVersionsParams {
+ name: string;
+ description?: string;
+ startDate?: string;
+ releaseDueDate?: string;
+ archived?: boolean;
+ }
+ export interface PostCustomFieldParams {
+ typeId: FieldType;
+ name: string;
+ applicableIssueTypes?: number[];
+ description?: string;
+ required?: boolean;
+ }
+ export interface PostCustomFieldWithNumericParams extends PostCustomFieldParams {
+ min?: number;
+ max?: number;
+ initialValue?: number;
+ unit?: string;
+ }
+ export interface PostCustomFieldWithDateParams extends PostCustomFieldParams {
+ min?: string;
+ max?: string;
+ initialValueType?: number;
+ initialDate?: string;
+ initialShift?: number;
+ }
+ export interface PostCustomFieldWithListParams extends PostCustomFieldParams {
+ items?: string[];
+ allowInput?: boolean;
+ allowAddItem?: boolean;
+ }
+ export interface PatchCustomFieldParams {
+ name?: string;
+ applicableIssueTypes?: number[];
+ description?: string;
+ required?: boolean;
+ }
+ export interface PatchCustomFieldWithNumericParams extends PatchCustomFieldParams {
+ min?: number;
+ max?: number;
+ initialValue?: number;
+ unit?: string;
+ }
+ export interface PatchCustomFieldWithDateParams extends PatchCustomFieldParams {
+ min?: string;
+ max?: string;
+ initialValueType?: number;
+ initialDate?: string;
+ initialShift?: number;
+ }
+ export interface PatchCustomFieldWithListParams extends PatchCustomFieldParams {
+ items?: string[];
+ allowInput?: boolean;
+ allowAddItem?: boolean;
+ }
+ export interface PostCustomFieldItemParams {
+ name: string;
+ }
+ export interface PatchCustomFieldItemParams {
+ name: string;
+ }
+ export interface GetSharedFilesParams {
+ order?: Order;
+ offset?: number;
+ count?: number;
+ }
+ export interface PostWebhookParams {
+ name?: string;
+ description?: string;
+ hookUrl?: string;
+ allEvent?: boolean;
+ activityTypeIds?: number[];
+ }
+ export interface PatchWebhookParams {
+ name?: string;
+ description?: string;
+ hookUrl?: string;
+ allEvent?: boolean;
+ activityTypeIds?: number[];
+ }
+ export enum FieldType {
+ Text = 1,
+ TextArea = 2,
+ Numeric = 3,
+ Date = 4,
+ SingleList = 5,
+ MultipleList = 6,
+ CheckBox = 7,
+ Radio = 8,
+ }
+ export interface PostStarParams {
+ issueId?: number;
+ commentId?: number;
+ wikiId?: number;
+ pullRequestId?: number;
+ pullRequestCommentId?: number;
+ }
+ }
+ export namespace Issue {
+ export interface PostIssueParams {
+ projectId: number;
+ summary: string;
+ priorityId: number;
+ issueTypeId: number;
+ parentIssueId?: number;
+ description?: string;
+ startDate?: string;
+ dueDate?: string;
+ estimatedHours?: number;
+ actualHours?: number;
+ categoryId?: number[];
+ versionId?: number[];
+ milestoneId?: number[];
+ assigneeId?: number;
+ notifiedUserId?: number[];
+ attachmentId?: number[];
+ [customField_: string]: any;
+ }
+ export interface PatchIssueParams {
+ summary?: string;
+ parentIssueId?: number;
+ description?: string;
+ statusId?: number;
+ resolutionId?: number;
+ startDate?: string;
+ dueDate?: string;
+ estimatedHours?: number;
+ actualHours?: number;
+ issueTypeId?: number;
+ categoryId?: number[];
+ versionId?: number[];
+ milestoneId?: number[];
+ priorityId?: number;
+ assigneeId?: number;
+ notifiedUserId?: number[];
+ attachmentId?: number[];
+ comment?: string;
+ [customField_: string]: any;
+ }
+ export interface GetIssuesParams {
+ projectId?: number[];
+ issueTypeId?: number[];
+ categoryId?: number[];
+ versionId?: number[];
+ milestoneId?: number[];
+ statusId?: number[];
+ priorityId?: number[];
+ assigneeId?: number[];
+ createdUserId?: number[];
+ resolutionId?: number[];
+ parentChild?: ParentChildType;
+ attachment?: boolean;
+ sharedFile?: boolean;
+ sort?: SortKey;
+ order?: Order;
+ offset?: number;
+ count?: number;
+ createdSince?: string;
+ createdUntil?: string;
+ updatedSince?: string;
+ updatedUntil?: string;
+ startDateSince?: string;
+ startDateUntil?: string;
+ dueDateSince?: string;
+ dueDateUntil?: string;
+ id?: number[];
+ parentIssueId?: number[];
+ keyword: string;
+ [customField_: string]: any;
+ }
+ export enum ParentChildType {
+ All = 0,
+ NotChild = 1,
+ Child = 2,
+ NotChildNotParent = 3,
+ Parent = 4,
+ }
+ export type SortKey = "issueType" | "category" | "version" | "milestone" | "summary" | "status" | "priority" | "attachment" | "sharedFile" | "created" | "createdUser" | "updated" | "updatedUser" | "assignee" | "startDate" | "dueDate" | "estimatedHours" | "actualHours" | "childIssue";
+ export interface GetIssueCommentsParams {
+ minId?: number;
+ maxId?: number;
+ count?: number;
+ order?: Order;
+ }
+ export interface PostIssueCommentsParams {
+ content: string;
+ notifiedUserId?: number[];
+ attachmentId?: number[];
+ }
+ export interface PatchIssueCommentParams {
+ content: string;
+ }
+ export interface IssueCommentNotifications {
+ notifiedUserId: number[];
+ }
+ export interface LinkIssueSharedFilesParams {
+ fileId: number[];
+ }
+ }
+ export namespace PullRequest {
+ export interface GetPullRequestsParams {
+ statusId?: number[];
+ assigneeId?: number[];
+ issueId?: number[];
+ createdUserId?: number[];
+ offset?: number;
+ count?: number;
+ }
+ export interface PostPullRequestParams {
+ summary: string;
+ description: string;
+ base: string;
+ branch: string;
+ issueId?: number;
+ assigneeId?: number;
+ notifiedUserId?: number[];
+ attachmentId?: number[];
+ }
+ export interface PatchPullRequestParams {
+ summary?: string;
+ description?: string;
+ issueId?: number;
+ assigneeId?: number;
+ notifiedUserId?: number[];
+ comment?: string[];
+ }
+ export interface GetPullRequestCommentsParams {
+ minId?: number;
+ maxId?: number;
+ count?: number;
+ order?: Order;
+ }
+ export interface PostPullRequestCommentsParams {
+ content: string;
+ notifiedUserId?: number[];
+ }
+ export interface PatchPullRequestCommentsParams {
+ content: string;
+ }
+ }
+ export namespace Wiki {
+ export interface PostWikiParams {
+ projectId: number;
+ name: string;
+ content: string;
+ mailNotify?: boolean;
+ }
+ export interface PatchWikiParams {
+ name?: string;
+ content?: string;
+ mailNotify?: boolean;
+ }
+ export interface GetWikisHistoryParams {
+ minId?: number;
+ maxId?: number;
+ count?: number;
+ order?: Order;
+ }
+ }
+ export namespace OAuth2 {
+ export interface Credentials {
+ clientId: string;
+ clientSecret: string;
+ }
+ }
+ }
+
+ export namespace Error {
+ export class BacklogError extends global.Error {
+ private _name;
+ private _url;
+ private _status;
+ private _body;
+ private _response;
+ constructor(name: BacklogErrorNameType, response: IResponse, body?: {
+ errors: BacklogErrorMessage[];
+ });
+ name: BacklogErrorNameType;
+ url: string;
+ status: number;
+ body: {
+ errors: BacklogErrorMessage[];
+ };
+ response: IResponse;
+ }
+ export class BacklogApiError extends BacklogError {
+ constructor(response: IResponse, body?: {
+ errors: BacklogErrorMessage[];
+ });
+ }
+ export class BacklogAuthError extends BacklogError {
+ constructor(response: IResponse, body?: {
+ errors: BacklogErrorMessage[];
+ });
+ }
+ export class UnexpectedError extends BacklogError {
+ constructor(response: IResponse);
+ }
+ export interface BacklogErrorMessage {
+ message: string;
+ code: number;
+ errorInfo: string;
+ moreInfo: string;
+ }
+ export type BacklogErrorNameType = 'BacklogApiError' | 'BacklogAuthError' | 'UnexpectedError';
+ }
+
+}
diff --git a/bluebird/bluebird-tests.ts b/bluebird/bluebird-tests.ts
index 59cef89b1a..d7995438c1 100644
--- a/bluebird/bluebird-tests.ts
+++ b/bluebird/bluebird-tests.ts
@@ -82,6 +82,7 @@ var voidProm: Promise;
var fooProm: Promise;
var barProm: Promise;
+var barOrVoidProm: Promise;
var fooOrBarProm: Promise;
var bazProm: Promise;
@@ -221,12 +222,12 @@ barProm = fooProm.then((value: Foo) => {
}, (reason: any) => {
return barProm;
});
-barProm = fooProm.then((value: Foo) => {
+barOrVoidProm = fooProm.then((value: Foo) => {
return bar;
}, (reason: any) => {
return;
});
-barProm = fooProm.then((value: Foo) => {
+barOrVoidProm = fooProm.then((value: Foo) => {
return bar;
}, (reason: any) => {
return voidProm;
diff --git a/bluebird/bluebird.d.ts b/bluebird/bluebird.d.ts
index 042347f096..35b506542a 100644
--- a/bluebird/bluebird.d.ts
+++ b/bluebird/bluebird.d.ts
@@ -47,8 +47,10 @@ class Bluebird implements Bluebird.Thenable, Bluebird.Inspection {
/**
* Promises/A+ `.then()`. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise.
*/
- then(onFulfill: (value: R) => U | Bluebird.Thenable, onReject?: (error: any) => U | Bluebird.Thenable): Bluebird;
- then(onFulfill: (value: R) => U | Bluebird.Thenable, onReject?: (error: any) => void | Bluebird.Thenable): Bluebird;
+ then(onFulfill: (value: R) => U1 | Bluebird.Thenable, onReject: (error: any) => U2 | Bluebird.Thenable): Bluebird;
+ then(onFulfill: (value: R) => U | Bluebird.Thenable, onReject: (error: any) => U | Bluebird.Thenable): Bluebird;
+ then(onFulfill: (value: R) => U | Bluebird.Thenable): Bluebird;
+ then(): Bluebird;
/**
* This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler.
diff --git a/braintree-web/braintree-web-tests.ts b/braintree-web/braintree-web-tests.ts
new file mode 100644
index 0000000000..40b34df418
--- /dev/null
+++ b/braintree-web/braintree-web-tests.ts
@@ -0,0 +1,432 @@
+///
+
+let version: string = braintree.VERSION;
+
+let clientToken: string = "eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiOiI0YjlhYzVmYmI4ZTNkYzQzMmFkZjJhNzBlNjZlMWNjY2M5ODRkYzE4ZTM4YmY4NjYzZTM5NjM3NWZjYmQzY2U5fGNyZWF0ZWRfYXQ9MjAxNi0wOS0wOFQwNTowMzo0MC4xNjk1NTUwMzUrMDAwMFx1MDAyNm1lcmNoYW50X2lkPTM0OHBrOWNnZjNiZ3l3MmJcdTAwMjZwdWJsaWNfa2V5PTJuMjQ3ZHY4OWJxOXZtcHIiLCJjb25maWdVcmwiOiJodHRwczovL2FwaS5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tOjQ0My9tZXJjaGFudHMvMzQ4cGs5Y2dmM2JneXcyYi9jbGllbnRfYXBpL3YxL2NvbmZpZ3VyYXRpb24iLCJjaGFsbGVuZ2VzIjpbXSwiZW52aXJvbm1lbnQiOiJzYW5kYm94IiwiY2xpZW50QXBpVXJsIjoiaHR0cHM6Ly9hcGkuc2FuZGJveC5icmFpbnRyZWVnYXRld2F5LmNvbTo0NDMvbWVyY2hhbnRzLzM0OHBrOWNnZjNiZ3l3MmIvY2xpZW50X2FwaSIsImFzc2V0c1VybCI6Imh0dHBzOi8vYXNzZXRzLmJyYWludHJlZWdhdGV3YXkuY29tIiwiYXV0aFVybCI6Imh0dHBzOi8vYXV0aC52ZW5tby5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tIiwiYW5hbHl0aWNzIjp7InVybCI6Imh0dHBzOi8vY2xpZW50LWFuYWx5dGljcy5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tLzM0OHBrOWNnZjNiZ3l3MmIifSwidGhyZWVEU2VjdXJlRW5hYmxlZCI6dHJ1ZSwicGF5cGFsRW5hYmxlZCI6dHJ1ZSwicGF5cGFsIjp7ImRpc3BsYXlOYW1lIjoiQWNtZSBXaWRnZXRzLCBMdGQuIChTYW5kYm94KSIsImNsaWVudElkIjpudWxsLCJwcml2YWN5VXJsIjoiaHR0cDovL2V4YW1wbGUuY29tL3BwIiwidXNlckFncmVlbWVudFVybCI6Imh0dHA6Ly9leGFtcGxlLmNvbS90b3MiLCJiYXNlVXJsIjoiaHR0cHM6Ly9hc3NldHMuYnJhaW50cmVlZ2F0ZXdheS5jb20iLCJhc3NldHNVcmwiOiJodHRwczovL2NoZWNrb3V0LnBheXBhbC5jb20iLCJkaXJlY3RCYXNlVXJsIjpudWxsLCJhbGxvd0h0dHAiOnRydWUsImVudmlyb25tZW50Tm9OZXR3b3JrIjp0cnVlLCJlbnZpcm9ubWVudCI6Im9mZmxpbmUiLCJ1bnZldHRlZE1lcmNoYW50IjpmYWxzZSwiYnJhaW50cmVlQ2xpZW50SWQiOiJtYXN0ZXJjbGllbnQzIiwiYmlsbGluZ0FncmVlbWVudHNFbmFibGVkIjp0cnVlLCJtZXJjaGFudEFjY291bnRJZCI6ImFjbWV3aWRnZXRzbHRkc2FuZGJveCIsImN1cnJlbmN5SXNvQ29kZSI6IlVTRCJ9LCJjb2luYmFzZUVuYWJsZWQiOmZhbHNlLCJtZXJjaGFudElkIjoiMzQ4cGs5Y2dmM2JneXcyYiIsInZlbm1vIjoib2ZmIn0=";
+
+braintree.client.create({
+ authorization: clientToken
+}, function (error: BraintreeError, clientInstance: any) {
+
+ var form: HTMLFormElement = document.getElementById('my-form-id') as HTMLFormElement;
+ var data: { creditCard: BraintreeWeb.CreditCardInfo } = {
+ creditCard: {
+ number: form['cc-number'].value,
+ cvv: form['cc-cvv'].value,
+ expirationDate: form['cc-date'].value,
+ billingAddress: {
+ postalCode: form['cc-postal'].value
+ }
+ }
+ };
+
+ clientInstance.request({
+ endpoint: 'payment_methods/credit_cards',
+ method: 'post',
+ data: data
+ }, function (requestErr: BraintreeError, response: { creditCards: any[]; }) {
+ if (requestErr) { throw new Error(requestErr.message); }
+
+ console.log('Got nonce:', response.creditCards[0].nonce);
+ });
+
+ braintree.hostedFields.create({
+ client: clientInstance,
+ styles: {
+ 'input': {
+ 'font-size': '16pt',
+ 'color': '#3A3A3A'
+ },
+
+ '.number': {
+ 'font-family': 'monospace'
+ },
+ '.valid': {
+ 'color': 'green'
+ }
+ },
+ fields: {
+ number: {
+ selector: '#card-number'
+ },
+ cvv: {
+ selector: '#cvv'
+ },
+ expirationDate: {
+ selector: '#expiration-date'
+ }
+ }
+ }, function (hostedFieldsErr?: BraintreeError, hostedFieldsInstance?: any) {
+
+ if (hostedFieldsErr) {
+ // Handle error in Hosted Fields creation
+ console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`);
+ return;
+ }
+
+ let form = new HTMLFormElement();
+
+ form.addEventListener('submit', function (event: Event) {
+ event.preventDefault();
+
+ hostedFieldsInstance.tokenize(function (tokenizeErr: BraintreeError, payload: BraintreeWeb.HostedFieldsTokenizePayload) {
+ if (tokenizeErr) {
+ // Handle error in Hosted Fields tokenization
+ switch (tokenizeErr.code) {
+ case 'HOSTED_FIELDS_FIELDS_EMPTY':
+ console.error('All fields are empty! Please fill out the form.');
+ break;
+ case 'HOSTED_FIELDS_FIELDS_INVALID':
+ console.error('Some fields are invalid:', tokenizeErr.details.invalidFieldKeys);
+ break;
+ case 'HOSTED_FIELDS_FAILED_TOKENIZATION':
+ console.error('Tokenization failed server side. Is the card valid?');
+ break;
+ case 'HOSTED_FIELDS_TOKENIZATION_NETWORK_ERROR':
+ console.error('Network error occurred when tokenizing.');
+ break;
+ default:
+ console.error('Something bad happened!', tokenizeErr);
+ }
+ return;
+ }
+
+ // Put `payload.nonce` into the `payment-method-nonce` input, and then
+ // submit the form. Alternatively, you could send the nonce to your server
+ // with AJAX.
+ (document.querySelector('input[name="payment-method-nonce"]') as HTMLInputElement).value = payload.nonce;
+ form.submit();
+ });
+ }, false);
+
+ hostedFieldsInstance.on('focus', function (event: BraintreeWeb.HostedFieldsStateObject) {
+ console.log(event.emittedBy, 'has been focused');
+ });
+
+ hostedFieldsInstance.teardown(function (teardownErr: BraintreeError) {
+ if (teardownErr) {
+ console.error('Could not tear down Hosted Fields!');
+ } else {
+ console.info('Hosted Fields has been torn down!');
+ }
+ });
+
+ hostedFieldsInstance.tokenize({
+ vault: true
+ }, function (tokenizeErr: BraintreeError, payload: BraintreeWeb.HostedFieldsTokenizePayload) {
+ if (tokenizeErr) {
+ console.error(tokenizeErr);
+ } else {
+ console.log('Got nonce:', payload.nonce);
+ }
+ });
+
+ hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: BraintreeError) {
+ if (addClassErr) {
+ console.error(addClassErr);
+ }
+ });
+
+ hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: BraintreeError) {
+ if (addClassErr) {
+ console.error(addClassErr);
+ return;
+ }
+
+ // some time later...
+ hostedFieldsInstance.removeClass('number', 'custom-class');
+ });
+
+ hostedFieldsInstance.setPlaceholder('number', '4111 1111 1111 1111', function (placeholderErr: BraintreeError) {
+ if (placeholderErr) {
+ console.error(placeholderErr);
+ }
+ });
+
+ hostedFieldsInstance.on('cardTypeChange', function (event: BraintreeWeb.HostedFieldsStateObject) {
+ // Update the placeholder value if there is only one possible card type
+ if (event.cards.length === 1) {
+ braintree.hostedFields.setPlaceholder('cvv', event.cards[0].code.name, function (placeholderErr: BraintreeError) {
+ if (placeholderErr) {
+ // Handle errors, such as invalid field name
+ console.error(placeholderErr);
+ }
+ });
+ }
+ });
+
+ hostedFieldsInstance.clear('number', function (clearErr: BraintreeError) {
+ if (clearErr) {
+ console.error(clearErr);
+ }
+ });
+
+ hostedFieldsInstance.clear('number');
+ hostedFieldsInstance.clear('cvv');
+ hostedFieldsInstance.clear('expirationDate');
+
+ var state = braintree.hostedFields.getState();
+
+ var formValid = Object.keys(state.fields).every(function (key) {
+ return state.fields[key].isValid;
+ });
+ });
+
+ braintree.applePay.create({ client: clientInstance }, function (createErr?: BraintreeError, applePayInstance?: any) {
+ if (createErr) {
+ // Handle error in client creation
+ console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`);
+
+ return;
+ }
+
+ let request = {
+ countryCode: 'US',
+ currencyCode: 'USD',
+ supportedNetworks: ['visa', 'masterCard'],
+ merchantCapabilities: ['supports3DS'],
+ total: { label: 'Your Label', amount: '10.00' },
+ };
+
+ var paymentRequest = braintree.applePay.createPaymentRequest(request);
+
+ console.log(paymentRequest);
+ // { total: { }, countryCode: 'US', currencyCode: 'USD', merchantCapabilities: [ ], supportedNetworks: [ ] }
+ });
+
+ braintree.applePay.create({ client: clientInstance }, function (createErr, applePayInstance) {
+ let request = {
+ countryCode: 'US',
+ currencyCode: 'USD',
+ supportedNetworks: ['visa', 'masterCard'],
+ merchantCapabilities: ['supports3DS'],
+ total: { label: 'Your Label', amount: '10.00' },
+ };
+
+ var session = new ApplePaySession(1, request);
+
+ session.onvalidatemerchant = function (event: { validationURL: string }) {
+ braintree.applePay.performValidation({
+ validationURL: event.validationURL
+ }, function (err, validationData) {
+ if (err) {
+ console.error(err);
+ session.abort();
+ return;
+ }
+ session.completeMerchantValidation(validationData);
+ });
+ };
+ });
+
+ braintree.applePay.create({ client: clientInstance }, function (createErr, applePayInstance) {
+ let request = {
+ countryCode: 'US',
+ currencyCode: 'USD',
+ supportedNetworks: ['visa', 'masterCard'],
+ merchantCapabilities: ['supports3DS'],
+ total: { label: 'Your Label', amount: '10.00' },
+ };
+
+ var session = new ApplePaySession(1, request);
+
+ session.onpaymentauthorized = function (event) {
+ braintree.applePay.tokenize({
+ token: event.payment.token
+ }, function (err, tokenizedPayload) {
+ if (err) {
+ session.completePayment(ApplePayStatusCodes.STATUS_FAILURE);
+ return;
+ }
+ session.completePayment(ApplePayStatusCodes.STATUS_SUCCESS);
+
+ // Send the tokenizedPayload to your server.
+ });
+ };
+ });
+
+ braintree.paypal.create({
+ client: clientInstance
+ }, function (createErr, paypalInstance) {
+ if (createErr) {
+ if (createErr.code === 'PAYPAL_BROWSER_NOT_SUPPORTED') {
+ console.error('This browser is not supported.');
+ } else {
+ console.error('Error!', createErr);
+ }
+ }
+
+ let button = new HTMLButtonElement();
+
+ button.addEventListener('click', function () {
+ // Disable the button so that we don't attempt to open multiple popups.
+ button.setAttribute('disabled', 'disabled');
+
+ // Because PayPal tokenization opens a popup, this must be called
+ // as a result of a user action, such as a button click.
+ paypalInstance.tokenize({
+ flow: 'vault' // Required
+ // Any other tokenization options
+ }, function (tokenizeErr: BraintreeError, payload: BraintreeWeb.PayPalTokenizePayload) {
+ button.removeAttribute('disabled');
+
+ if (tokenizeErr) {
+ // Handle tokenization errors or premature flow closure
+
+ switch (tokenizeErr.code) {
+ case 'PAYPAL_POPUP_CLOSED':
+ console.error('Customer closed PayPal popup.');
+ break;
+ case 'PAYPAL_ACCOUNT_TOKENIZATION_FAILED':
+ console.error('PayPal tokenization failed. See details:', tokenizeErr.details);
+ break;
+ case 'PAYPAL_FLOW_FAILED':
+ console.error('Unable to initialize PayPal flow. Are your options correct?', tokenizeErr.details);
+ break;
+ default:
+ console.error('Error!', tokenizeErr);
+ }
+ } else {
+ // Submit payload.nonce to your server
+ }
+ });
+ });
+ });
+
+ braintree.unionpay.create({ client: clientInstance }, function (createErr, unionpayInstance) {
+ if (createErr) {
+ console.error(createErr);
+ return;
+ }
+
+ unionpayInstance.fetchCapabilities({
+ card: {
+ number: '4111111111111111'
+ }
+ }, function (fetchErr: BraintreeError, cardCapabilities: BraintreeWeb.UnionPayFetchCapabilitiesPayload) {
+ if (fetchErr) {
+ console.error(fetchErr);
+ return;
+ }
+
+ if (cardCapabilities.isUnionPay) {
+ if (cardCapabilities.unionPay && !cardCapabilities.unionPay.isSupported) {
+ // Braintree cannot process this UnionPay card.
+ // Ask the user for a different card.
+ return;
+ }
+
+ if (cardCapabilities.isDebit) {
+ // CVV and expiration date are not required
+ } else {
+ // CVV and expiration date are required
+ }
+
+ // Show mobile phone number field for enrollment
+ }
+ });
+
+ unionpayInstance.enroll({
+ card: {
+ number: '4111111111111111',
+ expirationMonth: '12',
+ expirationYear: '2038'
+ },
+ mobile: {
+ countryCode: '62',
+ number: '111111111111'
+ }
+ }, function (enrollErr: BraintreeError, response: BraintreeWeb.UnionPayEnrollPayload) {
+ if (enrollErr) {
+ console.error(enrollErr);
+ return;
+ }
+
+ if (response.smsCodeRequired) {
+ // If smsCodeRequired, wait for SMS auth code from customer
+ // Then use response.enrollmentId during {@link UnionPay#tokenize}
+ } else {
+ // SMS code is not required from the user.
+ // {@link UnionPay#tokenize} can be called immediately
+ }
+ });
+
+ let enrollResponse: {
+ enrollmentId: string
+ };
+
+ unionpayInstance.tokenize({
+ card: {
+ number: '4111111111111111',
+ expirationMonth: '12',
+ expirationYear: '2038',
+ cvv: '123'
+ },
+ enrollmentId: enrollResponse.enrollmentId, // Returned from enroll
+ smsCode: '11111' // Received by customer's phone, if SMS enrollment was required. Otherwise it should be omitted
+ }, function (tokenizeErr: BraintreeError, response: BraintreeWeb.UnionPayTokenizePayload) {
+ if (tokenizeErr) {
+ console.error(tokenizeErr);
+ return;
+ }
+
+ // Send response.nonce to your server
+ });
+
+ unionpayInstance.teardown(function (teardownErr: BraintreeError) {
+ if (teardownErr) {
+ console.error('Could not tear down UnionPay.');
+ } else {
+ console.log('UnionPay has been torn down.');
+ }
+ });
+ });
+});
+
+let existingNonce = "fake-valid-nonce";
+let submitNonceToServer: (nonce: string) => void;
+
+braintree.threeDSecure.verifyCard({
+ nonce: existingNonce,
+ amount: 123.45,
+ addFrame: function (err, iframe) {
+ // Set up your UI and add the iframe.
+ let my3DSContainer = document.createElement('div');
+ my3DSContainer.appendChild(iframe);
+ document.body.appendChild(my3DSContainer);
+ },
+ removeFrame: function () {
+ let my3DSContainer = document.createElement('div');
+
+ // Remove UI that you added in addFrame.
+ document.body.removeChild(my3DSContainer);
+ }
+}, function (err: BraintreeError, payload: BraintreeWeb.ThreeDSecureVerifyPayload) {
+ if (err) {
+ console.error(err);
+ return;
+ }
+
+ if (payload.liabilityShifted) {
+ // Liablity has shifted
+ submitNonceToServer(payload.nonce);
+ } else if (payload.liabilityShiftPossible) {
+ // Liablity may still be shifted
+ // Decide if you want to submit the nonce
+ } else {
+ // Liablity has not shifted and will not shift
+ // Decide if you want to submit the nonce
+ }
+});
+
+braintree.threeDSecure.cancelVerifyCard(function (err: BraintreeError, verifyPayload: BraintreeWeb.ThreeDSecureVerifyPayload) {
+ if (err) {
+ // Handle error
+ console.log(err.message); // No verification payload available
+ return;
+ }
+
+ verifyPayload.nonce; // The nonce returned from the 3ds lookup call
+ verifyPayload.liabilityShifted; // boolean
+ verifyPayload.liabilityShiftPossible; // boolean
+});
\ No newline at end of file
diff --git a/braintree-web/braintree-web.d.ts b/braintree-web/braintree-web.d.ts
new file mode 100644
index 0000000000..2cf2d89467
--- /dev/null
+++ b/braintree-web/braintree-web.d.ts
@@ -0,0 +1,1738 @@
+// Type definitions for Braintree-web v3.0.2
+// Project: https://github.com/braintree/braintree-web
+// Definitions by: Guy Shahine
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+/**
+ * @module braintree-web/american-express
+ * @description This module is for use with Amex Express Checkout. To accept American Express cards, use Hosted Fields.
+ */
+declare namespace BraintreeWeb {
+ export interface AmericanExpress {
+ /**
+ * @static
+ * @function create
+ * @param {object} options Creation options:
+ * @param {Client} options.client A {@link Client} instance.
+ * @param {callback} callback The second argument, `data`, is the {@link AmericanExpress} instance.
+ * @returns {void}
+ */
+ create: (options: { client: Client }, callback: callback) => void;
+
+ /**
+ * @description The current version of the SDK, i.e. `3.0.2`.
+ * @type {string}
+ */
+ VERSION: string;
+ }
+
+ /**
+ * @class
+ * @param {object} options Options
+ * @description You cannot use this constructor directly. Use {@link module:braintree-web/american-express.create|braintree.american-express.create} instead.
+ * @classdesc This class allows you use a nonce to interact with American Express Checkout. To accept American Express cards, use Hosted Fields.
+ */
+ export class AmericanExpress {
+ /**
+ * @class
+ * @param {object} options Options
+ * @description You cannot use this constructor directly. Use {@link module:braintree-web/american-express.create|braintree.american-express.create} instead.
+ * @classdesc This class allows you use a nonce to interact with American Express Checkout. To accept American Express cards, use Hosted Fields.
+ */
+ constructor(options: any);
+
+ /**
+ * Gets the rewards balance associated with a Braintree nonce.
+ * @public
+ * @param {object} options Request options
+ * @param {string} options.nonce An existing Braintree nonce.
+ * @param {callback} callback The second argument, data, is the returned server data.
+ * @returns {void}
+ * @example
+ * var americanExpress = require('braintree-web/american-express');
+ *
+ * americanExpress.create({client: clientInstance}, function (createErr, americanExpressInstance) {
+ * var options = {nonce: existingBraintreeNonce};
+ * americanExpressInstance.getRewardsBalance(options, function (getErr, payload) {
+ * if (getErr || payload.error) {
+ * // Handle error
+ * return;
+ * }
+ *
+ * console.log('Rewards amount: ' + payload.rewardsAmount);
+ * });
+ * });
+ */
+ public getRewardsBalance(options: { nonce: string }, callback: callback): void;
+
+ /**
+ * Gets the Express Checkout nonce profile given a nonce from American Express.
+ * @public
+ * @param {object} options Request options
+ * @param {string} options.nonce An existing nonce from American Express (note that this is not a nonce from Braintree).
+ * @param {callback} callback The second argument, data, is the returned server data.
+ * @returns {void}
+ * @example
+ * var americanExpress = require('braintree-web/american-express');
+ *
+ * americanExpress.create({client: clientInstance}, function (createErr, americanExpressInstance) {
+ * var options = {nonce: existingAmericanExpressNonce};
+ * americanExpressInstance.getExpressCheckoutProfile(options, function (getErr, payload) {
+ * if (getErr) {
+ * // Handle error
+ * return;
+ * }
+ *
+ * console.log('Number of cards: ' + payload.amexExpressCheckoutCards.length);
+ * });
+ * });
+ */
+ public getExpressCheckoutProfile(options: { nonce: string }, callback: callback): void;
+ }
+}
+
+
+// more info https://developer.apple.com/reference/applepayjs/1916082-applepay_js_data_types/paymentrequest
+
+// billingContact
+// Billing contact information for the user.
+// countryCode
+//Required.The merchant’s two- letter ISO 3166 country code.
+// currencyCode
+// Required.The three- letter ISO 4217 currency code for the payment.
+// lineItems
+//A set of line items that explain recurring payments and additional charges.
+// merchantCapabilities
+// Required.The payment capabilities supported by the merchant.The value must be one or more of supports3DS, supportsEMV, supportsCredit, or supportsDebit.
+// requiredBillingContactFields
+// The billing information that is required from the user.The value must be one or more of postalAddress, phone, email, or name.
+// requiredShippingContactFields
+// The shipping information that is required from the user.The value must be one or more of postalAddress, phone, email, or name.
+// shippingContact
+// Shipping contact information for the user.
+// shippingMethods
+//A set of available shipping methods.Totals for all shipping methods must be non- negative to pass validation.
+// shippingType
+// How the items are to be shipped.This property is optional.If specified, it must be one or more of shipping, delivery, storePickup, or servicePickup.The default value is shipping.
+// supportedNetworks
+// Required.The payment networks supported by the merchant.The value must be one or more of amex, discover, interac, masterCard, privateLabel, or visa.
+// total
+// Required.The total amount for the payment.The total must be greater than zero and have a label to pass validation.
+interface ApplePayPaymentRequest {
+ total: {
+ label: string;
+ amount: string;
+ };
+ countryCode: string;
+ currencyCode: string;
+ supportedNetworks: string[];
+ merchantCapabilities: string[];
+
+ billingContact?: any;
+ shippingContact?: any;
+ shippingMethods?: any;
+ shippingType?: any;
+ requiredBillingContactFields?: any;
+ requiredShippingContactFields?: any;
+}
+
+declare enum ApplePayStatusCodes {
+ // The requested action succeeded.
+ STATUS_SUCCESS = 1,
+ // The requested action failed.
+ STATUS_FAILURE,
+ // The billing address is not valid.
+ STATUS_INVALID_BILLING_POSTAL_ADDRESS,
+ // The shipping address is not valid.
+ STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,
+ // The shipping contact information is not valid.
+ STATUS_INVALID_SHIPPING_CONTACT,
+ // The required PIN information was not provided. Cards on the China Union Pay payment network may require a PIN to authenticate the transaction.
+ STATUS_PIN_REQUIRED,
+ // The PIN information is not valid.Cards on the China Union Pay network may require a PIN.
+ STATUS_PIN_INCORRECT,
+ // The maximum number of tries for a PIN has been reached and the user has been locked out. Cards on the China Union Pay network may require a PIN.
+ STATUS_PIN_LOCKOUT,
+}
+
+interface ApplePayPayload {
+ merchantIdentifier: string;
+ domainName: string;
+ displayName: string;
+}
+
+declare class ApplePaySession {
+ constructor(version: number, request: ApplePayPaymentRequest);
+
+ canMakePayments(): boolean;
+
+ canMakePaymentsWithActiveCard(merchantIdentifier: string): boolean;
+
+ completeMerchantValidation(merchantSession: any): void;
+
+ abort(): void;
+
+ begin(): void;
+
+ completePayment(status: ApplePayStatusCodes): void;
+
+ completePaymentMethodSelection(newTotal: any, newLineItems: any): void;
+
+ completeShippingContactSelection(status: ApplePayStatusCodes, newShippingMethods: any, newTotal: any, newLineItems: any): void;
+
+ completeShippingMethodSelection(status: ApplePayStatusCodes, newTotal: any, newLineItems: any): void;
+
+ supportsVersion(version: number): boolean;
+
+ oncancel: (event: any) => void;
+
+ onpaymentauthorized: (event: any) => void;
+
+ onpaymentmethodselected: (event: any) => void;
+
+ onshippingcontactselected: (event: any) => void;
+
+ onshippingmethodselected: (event: any) => void;
+
+ onvalidatemerchant: (event: any) => void;
+}
+
+/**
+ * @module braintree-web/apple-pay
+ * @description Accept Apple Pay on the Web. *This component is currently in beta and is subject to change.*
+ */
+declare namespace BraintreeWeb {
+ export interface ApplePay {
+ /**
+ * @static
+ * @function create
+ * @param {object} options Creation options:
+ * @param {Client} options.client A {@link Client} instance.
+ * @param {callback} callback The second argument, `data`, is the {@link ApplePay} instance.
+ * @returns {void}
+ */
+ create: (options: { client: Client }, callback: callback) => void;
+
+ /**
+ * @description The current version of the SDK, i.e. `3.0.2`.
+ * @type {string}
+ */
+ VERSION: string;
+ }
+
+ /**
+ * @class
+ * @param {object} options Options
+ * @description You cannot use this constructor directly. Use {@link module:braintree-web/apple-pay.create|braintree.apple-pay.create} instead.
+ * @classdesc This class represents an Apple Pay component. Instances of this class have methods for validating the merchant server and tokenizing payments.
+ */
+ export class ApplePay {
+ /**
+ * @class
+ * @param {object} options Options
+ * @description You cannot use this constructor directly. Use {@link module:braintree-web/apple-pay.create|braintree.apple-pay.create} instead.
+ * @classdesc This class represents an Apple Pay component. Instances of this class have methods for validating the merchant server and tokenizing payments.
+ */
+ constructor(options: any);
+
+ /**
+ * Merges a payment request with Braintree defaults
+ * The following properties are assigned to `paymentRequest` if not already defined
+ * - countryCode
+ * - currencyCode
+ * - merchantCapabilities
+ * - supportedNetworks
+ * @public
+ * @param {external:ApplePayPaymentRequest} paymentRequest The payment request details to apply on top of those from Braintree.
+ * @returns {external:ApplePayPaymentRequest} The decorated `paymentRequest`.
+ * @example
+ * var applePay = require('braintree-web/apple-pay');
+ *
+ * applePay.create({client: clientInstance}, function (createErr, applePayInstance) {
+ * // ...
+ * var paymentRequest = applePay.createPaymentRequest({
+ * total: {
+ * label: 'My Company',
+ * amount: '19.99'
+ * });
+ *
+ * console.log(paymentRequest);
+ * // { total: { }, countryCode: 'US', currencyCode: 'USD', merchantCapabilities: [ ], supportedNetworks: [ ] }
+ *
+ */
+ public createPaymentRequest(paymentRequest: ApplePayPaymentRequest): ApplePayPaymentRequest
+
+ /**
+ * Validates the merchant website, as required by ApplePaySession before payment can be authorized.
+ * @public
+ * @param {object} options Options
+ * @param {string} options.validationURL The validationURL fram an ApplePayValidateMerchantEvent.
+ * @param {string} [options.displayName]
+ * - The canonical name for your store.
+ * - The system may display this name to the user.
+ * - Use a 128-character or less, UTF-8 string.
+ * - Do not localize the name.
+ * @param {string} [options.merchantIdentifier]
+ * Your Apple merchant identifier. This is the Apple Merchant ID created on the Apple Developer Portal.
+ * Defaults to the merchant identifier specified in the Braintree Control Panel.
+ * You can use this field to override the merchant identifier for this transaction.
+ * @param {callback} callback The second argument, data, is the Apple Pay merchant session object.
+ * Pass the merchant session to your Apple Pay session's completeMerchantValidation method.
+ * @returns {void}
+ * @example
+ * var applePay = require('braintree-web/apple-pay');
+ *
+ * applePay.create({client: clientInstance}, function (createErr, applePayInstance) {
+ * var session = new ApplePaySession(1, {
+ * // This should be the payment request object that
+ * // contains the information needed to display the payment sheet.
+ * });
+ *
+ * session.onvalidatemerchant = function (event) {
+ * applePay.performValidation({
+ * validationURL: event.validationURL
+ * }, function(err, validationData) {
+ * if (err) {
+ * console.error(err);
+ * session.abort();
+ * return;
+ * }
+ * session.completeMerchantValidation(validationData);
+ * });
+ * };
+ * });
+ */
+ public performValidation(options: { validationURL: string, displayName?: string, merchantIdentifier?: string }, callback: callback): void;
+
+ /**
+ * Tokenizes an Apple Pay payment.
+ * @public
+ * @param {object} options Options
+ * @param {object} options.token The `payment.token` property of an {@link external:ApplePayPaymentAuthorizedEvent}
+ * @param {callback} callback The second argument, data, is the tokenized payload.
+ * @returns {void}
+ * @example
+ * var applePay = require('braintree-web/apple-pay');
+ *
+ * applePay.create({client: clientInstance}, function (createErr, applePayInstance) {
+ * var session = new ApplePaySession(1, { });
+ *
+ * session.onpaymentauthorized = function (event) {
+ * applePay.tokenize({
+ * token: event.payment.token
+ * }, function (err, tokenizedPayload) {
+ * if (err) {
+ * session.completePayment(ApplePaySession.STATUS_FAILURE);
+ * return;
+ * }
+ * session.completePayment(ApplePaySession.STATUS_SUCCESS);
+ *
+ * // Send the tokenizedPayload to your server.
+ * });
+ * };
+ * });
+ */
+ public tokenize(options: { token: any }, callback: callback): void;
+
+ }
+}
+
+/** @module braintree-web/client */
+declare namespace BraintreeWeb {
+ /**
+ * This object is returned by {@link Client#getConfiguration|getConfiguration}. This information is used extensively by other Braintree modules to properly configure themselves.
+ * @typedef {object} Client~configuration
+ * @property {object} client The braintree-web/client parameters.
+ * @property {string} client.authorization A tokenizationKey or clientToken.
+ * @property {object} gatewayConfiguration Gateway-supplied configuration.
+ * @property {object} analyticsMetadata Analytics-specific data.
+ * @property {string} analyticsMetadata.sessionId Uniquely identifies a browsing session.
+ * @property {string} analyticsMetadata.sdkVersion The braintree.js version.
+ * @property {string} analyticsMetadata.merchantAppId Identifies the merchant's web app.
+ */
+ interface ClientAnalyticsMetadata {
+ sessionId: string;
+ sdkVersion: string;
+ merchantAppId: string;
+ }
+
+ interface Configuration {
+ client: Client;
+ gatewayConfiguration: any;
+ analyticsMetadata: ClientAnalyticsMetadata;
+ }
+
+ interface CreditCardInfo {
+ number: string;
+ cvv: string;
+ expirationDate: string;
+ billingAddress: {
+ postalCode?: string;
+ }
+ }
+
+ export interface Client {
+ authorization: string;
+
+ /**
+ * @function
+ * @description This function is the entry point for the braintree.client module. It is used for creating {@link Client} instances that service communication to Braintree servers.
+ * @param {object} options Object containing all {@link Client} options:
+ * @param {string} options.authorization A tokenizationKey or clientToken.
+ * @param {callback} callback The second argument, data, is the {@link Client} instance.
+ * @returns {void}
+ * @example
+ * var createClient = require('braintree-web/client').create;
+ *
+ * createClient({
+ * authorization: CLIENT_AUTHORIZATION
+ * }, function (createErr, clientInstance) {
+ * ...
+ * });
+ * @static
+ */
+ create: (options: { authorization: string }, callback: callback) => void;
+
+ /**
+ * @description The current version of the SDK, i.e. `3.0.2`.
+ * @type {string}
+ */
+ VERSION: string;
+ }
+
+ /**
+ * @class
+ * @param {Client~configuration} configuration Options
+ * @description Do not use this constructor directly. Use {@link module:braintree-web/client.create|braintree.client.create} instead.
+ * @classdesc This class is required by many other Braintree components. It serves as the base API layer that communicates with our servers. It is also capable of being used to formulate direct calls to our servers, such as direct credit card tokenization. See {@link Client#request}.
+ */
+ export class Client {
+ /**
+ * @class
+ * @param {Client~configuration} configuration Options
+ * @description Do not use this constructor directly. Use {@link module:braintree-web/client.create|braintree.client.create} instead.
+ * @classdesc This class is required by many other Braintree components. It serves as the base API layer that communicates with our servers. It is also capable of being used to formulate direct calls to our servers, such as direct credit card tokenization. See {@link Client#request}.
+ */
+ constructor(configuration: Configuration);
+
+
+ /**
+ * Returns a copy of the configuration values.
+ * @public
+ * @returns {Client~configuration} configuration
+ */
+ public getConfiguration(): Configuration;
+
+ /**
+ * Used by other modules to formulate all network requests to the Braintree gateway. It is also capable of being used directly from your own form to tokenize credit card information. However, be sure to satisfy PCI compliance if you use direct card tokenization.
+ * @public
+ * @param {object} options Request options:
+ * @param {string} options.method HTTP method. i.e. "get" or "post"
+ * @param {string} options.endpoint Enpoint path. i.e. "payment_methods"
+ * @param {object} options.data Data to send with the request
+ * @param {string} [options.timeout=60000] Timeout limit
+ * @param {callback} callback The second argument, data, is the returned server data.
+ * @example
+ *
Direct Credit Card Tokenization
+ * var createClient = require('braintree-web/client').create;
+ *
+ * createClient({
+ * authorization: CLIENT_AUTHORIZATION
+ * }, function (createErr, clientInstance) {
+ * var form = document.getElementById('my-form-id');
+ * var data = {
+ * creditCard: {
+ * number: form['cc-number'].value,
+ * cvv: form['cc-cvv'].value,
+ * expirationDate: form['cc-date'].value,
+ * billingAddress: {
+ * postalCode: form['cc-postal'].value
+ * }
+ * }
+ * };
+ *
+ * // Warning: For a merchant to be eligible for the easiest level of PCI compliance (SAQ A),
+ * // payment fields cannot be hosted on your checkout page.
+ * // For an alternative to the following, use Hosted Fields.
+ * clientInstance.request({
+ * endpoint: 'payment_methods/credit_cards',
+ * method: 'post',
+ * data: data
+ * }, function (requestErr, response) {
+ * if (requestErr) { throw new Error(requestErr); }
+ *
+ * console.log('Got nonce:', response.creditCards[0].nonce);
+ * });
+ * });
+ * @returns {void}
+ */
+ public request(options: { method: string, endpoint: string, data: any, timeout?: number }, callback: callback): void;
+
+ }
+}
+
+/** @module braintree-web/data-collector */
+declare namespace BraintreeWeb {
+ export interface DataCollector {
+ /**
+ * @static
+ * @function create
+ * @param {object} options Creation options:
+ * @param {Client} options.client A {@link Client} instance.
+ * @param {boolean} [options.kount] If true, Kount fraud data collection is enabled.
+ * @param {boolean} [options.paypal] If true, PayPal fraud data collection is enabled.
+ * @param {callback} callback The second argument, `data`, is the {@link DataCollector} instance.
+ * @returns {void}
+ */
+ create: (options: { client: Client, kount: boolean, paypal: boolean }, callback: callback) => void;
+
+ /**
+ * @description The current version of the SDK, i.e. `3.0.2`.
+ * @type {string}
+ */
+ VERSION: string;
+ }
+
+ /**
+ * @class
+ * @global
+ * @name DataCollector
+ * @description Do not use this constructor directly. Use {@link module:braintree-web/data-collector.create|braintree-web.data-collector.create} instead.
+ * @classdesc This class is used for advanced fraud integration with PayPal and Kount. Instances of this class have {@link DataCollector#deviceData|deviceData} which is used to correlate user sessions with server transactions.
+ */
+ export class DataCollector {
+ /**
+ * @class
+ * @global
+ * @name DataCollector
+ * @description Do not use this constructor directly. Use {@link module:braintree-web/data-collector.create|braintree-web.data-collector.create} instead.
+ * @classdesc This class is used for advanced fraud integration with PayPal and Kount. Instances of this class have {@link DataCollector#deviceData|deviceData} which is used to correlate user sessions with server transactions.
+ */
+ constructor();
+
+ /**
+ * @memberof DataCollector
+ * @name deviceData
+ * @type string
+ * @description JSON string to pass with server transactions.
+ * @instance
+ */
+ deviceData: string;
+
+ /**
+ * @memberof DataCollector
+ * @name teardown
+ * @function
+ * @description Cleanly remove all event handlers and DOM nodes that were added.
+ * @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully.
+ * @instance
+ * @returns {void}
+ */
+ teardown(callback?: callback): void;
+
+ }
+}
+
+/** @module braintree-web/hosted-fields */
+declare namespace BraintreeWeb {
+ /**
+ * Fields used in {@link module:braintree-web/hosted-fields~fieldOptions fields options}
+ * @typedef {object} field
+ * @property {string} selector A CSS selector to find the container where the hosted field will be inserted.
+ * @property {string} [placeholder] Will be used as the `placeholder` attribute of the input. If `placeholder` is not natively supported by the browser, it will be polyfilled.
+ * @property {boolean} [formatInput=true] - Enable or disable automatic formatting on this field. Note: Input formatting does not work properly on Android and iOS, so input formatting is automatically disabled on those browsers.
+ */
+ interface HostedFieldsField {
+ selector: string;
+ placeholder?: string;
+ formatInput?: boolean;
+ }
+
+ /**
+ * An object that has {@link module:braintree-web/hosted-fields~field field objects} for each field. Used in {@link module:braintree-web/hosted-fields~create create}.
+ * @typedef {object} fieldOptions
+ * @property {field} [number] A field for card number.
+ * @property {field} [expirationDate] A field for expiration date in `MM/YYYY` format. This should not be used with the `expirationMonth` and `expirationYear` properties.
+ * @property {field} [expirationMonth] A field for expiration month in `MM` format. This should be used with the `expirationYear` property.
+ * @property {field} [expirationYear] A field for expiration year in `YYYY` format. This should be used with the `expirationMonth` property.
+ * @property {field} [cvv] A field for 3 or 4 digit CVV or CID.
+ * @property {field} [postalCode] A field for postal or region code.
+ */
+ interface HostedFieldFieldOptions {
+ number: HostedFieldsField;
+ expirationDate?: HostedFieldsField;
+ expirationMonth?: HostedFieldsField;
+ expirationYear?: HostedFieldsField;
+ cvv: HostedFieldsField;
+ postalCode?: HostedFieldsField;
+ }
+
+ /**
+ * @typedef {object} HostedFields~hostedFieldsCard
+ * @description Information about the card type, sent in {@link HostedFields~stateObject|stateObjects}.
+ * @property {string} type The code-friendly representation of the card type. It will be one of the following strings:
+ * - `american-express`
+ * - `diners-club`
+ * - `discover`
+ * - `jcb`
+ * - `maestro`
+ * - `master-card`
+ * - `unionpay`
+ * - `visa`
+ * @property {string} niceType The pretty-printed card type. It will be one of the following strings:
+ * - `American Express`
+ * - `Diners Club`
+ * - `Discover`
+ * - `JCB`
+ * - `Maestro`
+ * - `MasterCard`
+ * - `UnionPay`
+ * - `Visa`
+ * @property {object} code
+ * This object contains data relevant to the security code requirements of the card brand.
+ * For example, on a Visa card there will be a CVV of 3 digits, whereas an
+ * American Express card requires a 4-digit CID.
+ * @property {string} code.name "CVV""CID""CVC"
+ * @property {number} code.size The expected length of the security code. Typically, this is 3 or 4.
+ */
+
+ interface HostedFieldsCardCode {
+ name: string;
+ size: number;
+ }
+
+ interface HostedFieldsHostedFieldsCard {
+ type: string;
+ niceType: string;
+ code: HostedFieldsCardCode;
+ }
+
+ /**
+ * @typedef {object} HostedFields~hostedFieldsFieldData
+ * @description Data about Hosted Fields fields, sent in {@link HostedFields~stateObject|stateObjects}.
+ * @property {HTMLElement} container Reference to the container DOM element on your page associated with the current event.
+ * @property {boolean} isFocused Whether or not the input is currently focused.
+ * @property {boolean} isEmpty Whether or not the user has entered a value in the input.
+ * @property {boolean} isPotentiallyValid
+ * A determination based on the future validity of the input value.
+ * This is helpful when a user is entering a card number and types "41".
+ * While that value is not valid for submission, it is still possible for
+ * it to become a fully qualified entry. However, if the user enters "4x"
+ * it is clear that the card number can never become valid and isPotentiallyValid will
+ * return false.
+ * @property {boolean} isValid Whether or not the value of the associated input is fully qualified for submission.
+ */
+ interface HostedFieldsHostedFieldsFieldData {
+ container: HTMLElement;
+ isFocused: boolean;
+ isEmpty: boolean;
+ isPotentiallyValid: boolean;
+ isValid: boolean;
+ }
+
+ /**
+ * @typedef {object} HostedFields~stateObject
+ * @description The event payload sent from {@link HostedFields#on|on} or {@link HostedFields#getState|getState}.
+ * @property {HostedFields~hostedFieldsCard[]} cards
+ * This will return an array of potential {@link HostedFields~hostedFieldsCard|cards}. If the card type has been determined, the array will contain only one card.
+ * Internally, Hosted Fields uses credit-card-type,
+ * an open-source card detection library.
+ * @property {string} emittedBy
+ * The name of the field associated with an event. This will not be included if returned by {@link HostedFields#getState|getState}. It will be one of the following strings:
+ * - `"number"`
+ * - `"cvv"`
+ * - `"expirationDate"`
+ * - `"expirationMonth"`
+ * - `"expirationYear"`
+ * - `"postalCode"`
+ * @property {object} fields
+ * @property {?HostedFields~hostedFieldsFieldData} fields.number {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the number field, if it is present.
+ * @property {?HostedFields~hostedFieldsFieldData} fields.cvv {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the CVV field, if it is present.
+ * @property {?HostedFields~hostedFieldsFieldData} fields.expirationDate {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the expiration date field, if it is present.
+ * @property {?HostedFields~hostedFieldsFieldData} fields.expirationMonth {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the expiration month field, if it is present.
+ * @property {?HostedFields~hostedFieldsFieldData} fields.expirationYear {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the expiration year field, if it is present.
+ * @property {?HostedFields~hostedFieldsFieldData} fields.postalCode {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the postal code field, if it is present.
+ */
+ interface HostedFieldsFieldDataFields {
+ number: HostedFieldsHostedFieldsFieldData;
+ cvv: HostedFieldsHostedFieldsFieldData;
+ expirationDate: HostedFieldsHostedFieldsFieldData;
+ expirationMonth: HostedFieldsHostedFieldsFieldData;
+ expirationYear: HostedFieldsHostedFieldsFieldData;
+ postalCode: HostedFieldsHostedFieldsFieldData;
+ }
+
+ interface HostedFieldsStateObject {
+ cards: HostedFieldsHostedFieldsCard[];
+ emittedBy: string;
+ fields: HostedFieldsFieldDataFields;
+ }
+
+ /**
+ * @typedef {object} HostedFields~tokenizePayload
+ * @property {string} nonce The payment method nonce.
+ * @property {object} details Additional account details.
+ * @property {string} details.cardType Type of card, ex: Visa, MasterCard.
+ * @property {string} details.lastTwo Last two digits of card number.
+ * @property {string} description A human-readable description.
+ * @property {string} type The payment method type, always `CreditCard`.
+ */
+ interface HostedFieldsAccountDetails {
+ cardType: string;
+ lastTwo: string;
+ }
+
+ interface HostedFieldsTokenizePayload {
+ nonce: string;
+ details: HostedFieldsAccountDetails;
+ type: string;
+ description: string;
+ }
+
+ export interface HostedFields {
+ /**
+ * @static
+ * @function create
+ * @param {object} options Creation options:
+ * @param {Client} options.client A {@link Client} instance.
+ * @param {fieldOptions} options.fields A {@link module:braintree-web/hosted-fields~fieldOptions set of options for each field}.
+ * @param {styleOptions} options.styles {@link module:braintree-web/hosted-fields~styleOptions Styles} applied to each field.
+ * @param {callback} callback The second argument, `data`, is the {@link HostedFields} instance.
+ * @returns {void}
+ * @example
+ * braintree.hostedFields.create({
+ * client: clientInstance,
+ * styles: {
+ * 'input': {
+ * 'font-size': '16pt',
+ * 'color': '#3A3A3A'
+ * },
+ * '.number': {
+ * 'font-family': 'monospace'
+ * },
+ * '.valid': {
+ * 'color': 'green'
+ * }
+ * },
+ * fields: {
+ * number: {
+ * selector: '#card-number'
+ * },
+ * cvv: {
+ * selector: '#cvv'
+ * },
+ * expirationDate: {
+ * selector: '#expiration-date'
+ * }
+ * }
+ * }, callback);
+ */
+ create: (options: { client: Client, fields: HostedFieldFieldOptions, styles: any }, callback: callback) => void;
+
+
+ /**
+ * An object that represents CSS that will be applied in each hosted field. This object looks similar to CSS. Typically, these styles involve fonts (such as `font-family` or `color`).
+ *
+ * These are the CSS properties that Hosted Fields supports. Any other CSS should be specified on your page and outside of any Braintree configuration. Trying to set unsupported properties will fail and put a warning in the console.
+ *
+ * `color` `font-family` `font-size-adjust` `font-size` `font-stretch` `font-style` `font-variant-alternates` `font-variant-caps` `font-variant-east-asian` `font-variant-ligatures` `font-variant-numeric` `font-variant` `font-weight` `font` `line-height` `opacity` `outline` `text-shadow` `transition` `-moz-osx-font-smoothing` `-moz-tap-highlight-color` `-moz-transition` `-webkit-font-smoothing` `-webkit-tap-highlight-color` `-webkit-transition`
+ * @typedef {object} styleOptions
+ */
+ styleOptions: any;
+
+ /**
+ * @description The current version of the SDK, i.e. `3.0.2`.
+ * @type {string}
+ */
+ VERSION: string;
+ }
+
+ /**
+ * @class HostedFields
+ * @param {object} options The Hosted Fields {@link module:braintree-web/hosted-fields.create create} options.
+ * @description Do not use this constructor directly. Use {@link module:braintree-web/hosted-fields.create|braintree-web.hosted-fields.create} instead.
+ * @classdesc This class represents a Hosted Fields component produced by {@link module:braintree-web/hosted-fields.create|braintree-web/hosted-fields.create}. Instances of this class have methods for interacting with the input fields within Hosted Fields' iframes.
+ */
+ export class HostedFields {
+ /**
+ * @class HostedFields
+ * @param {object} options The Hosted Fields {@link module:braintree-web/hosted-fields.create create} options.
+ * @description Do not use this constructor directly. Use {@link module:braintree-web/hosted-fields.create|braintree-web.hosted-fields.create} instead.
+ * @classdesc This class represents a Hosted Fields component produced by {@link module:braintree-web/hosted-fields.create|braintree-web/hosted-fields.create}. Instances of this class have methods for interacting with the input fields within Hosted Fields' iframes.
+ */
+ constructor(options: any);
+
+ /**
+ * @name HostedFields#on
+ * @function
+ * @param {string} event The name of the event to which you are subscribing.
+ * @param {function} handler A callback to handle the event.
+ * @description Subscribes a handler function to a named event. `event` should be {@link HostedFields#event:blur|blur}, {@link HostedFields#event:focus|focus}, {@link HostedFields#event:empty|empty}, {@link HostedFields#event:notEmpty|notEmpty}, {@link HostedFields#event:cardTypeChange|cardTypeChange}, or {@link HostedFields#event:validityChange|validityChange}. Events will emit a {@link HostedFields~stateObject|stateObject}.
+ * @example
+ *
Listening to a Hosted Field event, in this case 'focus'
+ * hostedFields.create({ ... }, function (createErr, hostedFieldsInstance) {
+ * hostedFieldsInstance.on('focus', function (event) {
+ * console.log(event.emittedBy, 'has been focused');
+ * });
+ * });
+ * @returns {void}
+ */
+ on(event: string, handler: (() => any)): void;
+
+ /**
+ * Cleanly tear down anything set up by {@link module:braintree-web/hosted-fields.create|create}
+ * @public
+ * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if teardown completes successfully.
+ * @example
+ * hostedFieldsInstance.teardown(function (teardownErr) {
+ * if (teardownErr) {
+ * console.error('Could not tear down Hosted Fields!');
+ * } else {
+ * console.info('Hosted Fields has been torn down!');
+ * }
+ * });
+ * @returns {void}
+ */
+ public teardown(callback?: callback): void;
+
+ /**
+ * Tokenizes fields and returns a nonce payload.
+ * @public
+ * @param {object} [options] All tokenization options for the Hosted Fields component.
+ * @param {boolean} [options.vault=false] When true, will vault the tokenized card. Cards will only be vaulted when using a client created with a client token that includes a customer ID.
+ * @param {callback} callback The second argument, data, is a {@link HostedFields~tokenizePayload|tokenizePayload}
+ * @example
Tokenize a card
+ * hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
+ * if (tokenizeErr) {
+ * switch (tokenizeErr.code) {
+ * case 'HOSTED_FIELDS_FIELDS_EMPTY':
+ * console.error('All fields are empty! Please fill out the form.');
+ * break;
+ * case 'HOSTED_FIELDS_FIELDS_INVALID':
+ * console.error('Some fields are invalid:', tokenizeErr.details.invalidFieldKeys);
+ * break;
+ * case 'HOSTED_FIELDS_FAILED_TOKENIZATION':
+ * console.error('Tokenization failed server side. Is the card valid?');
+ * break;
+ * case 'HOSTED_FIELDS_TOKENIZATION_NETWORK_ERROR':
+ * console.error('Network error occurred when tokenizing.');
+ * break;
+ * default:
+ * console.error('Something bad happened!', tokenizeErr);
+ * }
+ * } else {
+ * console.log('Got nonce:', payload.nonce);
+ * }
+ * });
+ * @example
Tokenize and vault a card
+ * hostedFieldsInstance.tokenize({
+ * vault: true
+ * }, function (tokenizeErr, payload) {
+ * if (tokenizeErr) {
+ * console.error(tokenizeErr);
+ * } else {
+ * console.log('Got nonce:', payload.nonce);
+ * }
+ * });
+ * @returns {void}
+ */
+ public tokenize(options?: { vault: boolean }, callback?: callback): void;
+
+ /**
+ * Add a class to a {@link module:braintree-web/hosted-fields~field field}. Useful for updating field styles when events occur elsewhere in your checkout.
+ * @public
+ * @param {string} field The field you wish to add a class to. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}.
+ * @param {string} classname The class to be added.
+ * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the class is added successfully.
+ *
+ * @example
+ * hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr) {
+ * if (addClassErr) {
+ * console.error(addClassErr);
+ * }
+ * });
+ * @returns {void}
+ */
+ public addClass(field: string, classname: string, callback?: callback): void;
+
+ /**
+ * Removes a class to a {@link module:braintree-web/hosted-fields~field field}. Useful for updating field styles when events occur elsewhere in your checkout.
+ * @public
+ * @param {string} field The field you wish to remove a class from. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}.
+ * @param {string} classname The class to be removed.
+ * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the class is removed successfully.
+ *
+ * @example
+ * hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr) {
+ * if (addClassErr) {
+ * console.error(addClassErr);
+ * return;
+ * }
+ *
+ * // some time later...
+ * hostedFieldsInstance.removeClass('number', 'custom-class');
+ * });
+ * @returns {void}
+ */
+ public removeClass(field: string, classname: string, callback?: callback): void;
+
+ /**
+ * Sets the placeholder of a {@link module:braintree-web/hosted-fields~field field}.
+ * @public
+ * @param {string} field The field whose placeholder you wish to change. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}.
+ * @param {string} placeholder Will be used as the `placeholder` attribute of the input.
+ * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the placeholder updated successfully.
+ *
+ * @example
+ * hostedFieldsInstance.setPlaceholder('number', '4111 1111 1111 1111', function (placeholderErr) {
+ * if (placeholderErr) {
+ * console.error(placeholderErr);
+ * }
+ * });
+ *
+ * @example
Update CVV field on card type change
+ * hostedFieldsInstance.on('cardTypeChange', function (event) {
+ * // Update the placeholder value if there is only one possible card type
+ * if (event.cards.length === 1) {
+ * hostedFields.setPlaceholder('cvv', event.cards[0].code.name, function (placeholderErr) {
+ * if (placeholderErr) {
+ * // Handle errors, such as invalid field name
+ * console.error(placeholderErr);
+ * }
+ * });
+ * }
+ * });
+ * @returns {void}
+ */
+ public setPlaceholder(field: string, placeholder: string, callback?: callback): void;
+
+ /**
+ * Clear the value of a {@link module:braintree-web/hosted-fields~field field}.
+ * @public
+ * @param {string} field The field whose placeholder you wish to clear. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}.
+ * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the field cleared successfully.
+ * @returns {void}
+ * @example
+ * hostedFieldsInstance.clear('number', function (clearErr) {
+ * if (clearErr) {
+ * console.error(clearErr);
+ * }
+ * });
+ *
+ * @example
Clear several fields
+ * hostedFieldsInstance.clear('number');
+ * hostedFieldsInstance.clear('cvv');
+ * hostedFieldsInstance.clear('expirationDate');
+ */
+ public clear(field: string, callback?: callback): void;
+
+ /**
+ * Returns an {@link HostedFields~stateObject|object} that includes the state of all fields and possible card types.
+ * @public
+ * @returns {object} {@link HostedFields~stateObject|stateObject}
+ * @example
Check if all fields are valid
+ * var state = hostedFields.getState();
+ *
+ * var formValid = Object.keys(state.fields).every(function (key) {
+ * return state.fields[key].isValid;
+ * });
+ */
+ public getState(): any;
+ }
+}
+
+/** @module braintree-web/paypal */
+declare namespace BraintreeWeb {
+ /**
+ * @typedef {object} PayPal~tokenizeReturn
+ * @property {Function} close A handle to close the PayPal checkout flow.
+ */
+ interface PayPalTokenizeReturn {
+ close: (() => any);
+ }
+
+ /**
+ * @typedef {object} PayPal~tokenizePayload
+ * @property {string} nonce The payment method nonce.
+ * @property {string} type The payment method type, always `PayPalAccount`.
+ * @property {object} details Additional PayPal account details.
+ * @property {string} details.email User's email address.
+ * @property {string} details.payerId User's payer ID, the unique identifier for each PayPal account.
+ * @property {string} details.firstName User's given name.
+ * @property {string} details.lastName User's surname.
+ * @property {?string} details.countryCode User's 2 character country code.
+ * @property {?string} details.phone User's phone number (e.g. 555-867-5309).
+ * @property {?object} details.shippingAddress User's shipping address details, only available if shipping address is enabled.
+ * @property {string} details.shippingAddress.recipientName Recipient of postage.
+ * @property {string} details.shippingAddress.line1 Street number and name.
+ * @property {string} details.shippingAddress.line2 Extended address.
+ * @property {string} details.shippingAddress.city City or locality.
+ * @property {string} details.shippingAddress.state State or region.
+ * @property {string} details.shippingAddress.postalCode Postal code.
+ * @property {string} details.shippingAddress.countryCode 2 character country code (e.g. US).
+ * @property {?object} details.billingAddress User's billing address details.
+ * You will also need to enable the PayPal Billing Address Request feature in your PayPal account.
+ * To enable this feature, [contact PayPal](https://developers.braintreepayments.com/support/guides/paypal/setup-guide#contacting-paypal-support).
+ * @property {string} details.billingAddress.line1 Street number and name.
+ * @property {string} details.billingAddress.line2 Extended address.
+ * @property {string} details.billingAddress.city City or locality.
+ * @property {string} details.billingAddress.state State or region.
+ * @property {string} details.billingAddress.postalCode Postal code.
+ * @property {string} details.billingAddress.countryCode 2 character country code (e.g. US).
+ */
+ interface PayPalShippingAddress {
+ recipientName: string;
+ line1: string;
+ line2: string;
+ city: string;
+ state: string;
+ postalCode: string;
+ countryCode: string;
+ }
+
+ interface PayPalBillingAddress {
+ line1: string;
+ line2: string;
+ city: string;
+ state: string;
+ postalCode: string;
+ countryCode: string;
+ }
+
+ interface PayPalAccountDetails {
+ email: string;
+ payerId: string;
+ firstName: string;
+ lastName: string;
+ countryCode: string;
+ phone: string;
+ shippingAddress: PayPalShippingAddress;
+ billingAddress: PayPalBillingAddress;
+ }
+
+ interface PayPalTokenizePayload {
+ nonce: string;
+ type: string;
+ details: PayPalAccountDetails;
+ }
+
+ export interface PayPal {
+ /**
+ * @static
+ * @function create
+ * @param {object} options Creation options:
+ * @param {Client} options.client A {@link Client} instance.
+ * @param {callback} callback The second argument, `data`, is the {@link PayPal} instance.
+ * @example
+ * braintree.paypal.create(
+ * client: clientInstance
+ * }, function (createErr, paypalInstance) {
+ * if (createErr) {
+ * if (createErr.code === 'PAYPAL_BROWSER_NOT_SUPPORTED') {
+ * console.error('This browser is not supported.');
+ * } else {
+ * console.error('Error!', createErr);
+ * }
+ * }
+ * }
+ * @returns {void}
+ */
+ create: (options: { client: Client }, callback: callback) => void;
+
+ /**
+ * @description The current version of the SDK, i.e. `3.0.2`.
+ * @type {string}
+ */
+ VERSION: string;
+ }
+
+ /**
+ * @class
+ * @param {object} options see {@link module:braintree-web/paypal.create|paypal.create}
+ * @classdesc This class represents a PayPal component. Instances of this class have methods for launching auth dialogs and other programmatic interactions with the PayPal component.
+ */
+ export class PayPal {
+ /**
+ * @class
+ * @param {object} options see {@link module:braintree-web/paypal.create|paypal.create}
+ * @classdesc This class represents a PayPal component. Instances of this class have methods for launching auth dialogs and other programmatic interactions with the PayPal component.
+ */
+ constructor(options: any);
+
+ /**
+ * Launches the PayPal login flow and returns a nonce payload. Only one PayPal login flow should be active at a time. One way to achieve this is to disable your PayPal button while the flow is open.
+ * @public
+ * @param {object} options All tokenization options for the PayPal component.
+ * @param {string} options.flow Set to 'checkout' for one-time payment flow, or 'vault' for Vault flow. If 'vault' is used with a client token generated with a customer id, the PayPal account will be added to that customer as a saved payment method.
+ * @param {string} [options.intent=authorize]
+ * Checkout flows only.
+ * * `authorize` - Submits the transaction for authorization but not settlement.
+ * * `sale` - Payment will be immediately submitted for settlement upon creating a transaction.
+ * @param {boolean} [options.offerCredit=false] Offers the customer PayPal Credit if they qualify. Checkout flows only.
+ * @param {string} [options.useraction]
+ * Changes the call-to-action in the PayPal flow. By default the final button will show the localized
+ * word for "Continue" and implies that the final amount billed is not yet known.
+ *
+ * Setting this option to `commit` changes the button text to "Pay Now" and page text will convey to
+ * the user that billing will take place immediately.
+ * @param {string|number} [options.amount] The amount of the transaction. Required when using the Checkout flow.
+ * @param {string} [options.currency] The currency code of the amount, such as 'USD'. Required when using the Checkout flow.
+ * @param {string} [options.displayName] The merchant name displayed inside of the PayPal lightbox; defaults to the company name on your Braintree account
+ * @param {string} [options.locale=en_US] Use this option to change the language, links, and terminology used in the PayPal flow to suit the country and language of your customer.
+ * @param {boolean} [options.enableShippingAddress=false] Returns a shipping address object in {@link PayPal#tokenize}.
+ * @param {object} [options.shippingAddressOverride] Allows you to pass a shipping address you have already collected into the PayPal payment flow.
+ * @param {string} options.shippingAddressOverride.line1 Street address.
+ * @param {string} [options.shippingAddressOverride.line2] Street address (extended).
+ * @param {string} options.shippingAddressOverride.city City.
+ * @param {string} options.shippingAddressOverride.state State.
+ * @param {string} options.shippingAddressOverride.postalCode Postal code.
+ * @param {string} options.shippingAddressOverride.countryCode Country.
+ * @param {string} [options.shippingAddressOverride.phone] Phone number.
+ * @param {string} [options.shippingAddressOverride.recipientName] Recipient's name.
+ * @param {boolean} [options.shippingAddressEditable=true] Set to false to disable user editing of the shipping address.
+ * @param {string} [options.billingAgreementDescription] Use this option to set the description of the preapproved payment agreement visible to customers in their PayPal profile during Vault flows. Max 255 characters.
+ * @param {callback} callback The second argument, data, is a {@link PayPal~tokenizePayload|tokenizePayload}.
+ * @example
+ * button.addEventListener('click', function () {
+ * // Disable the button so that we don't attempt to open multiple popups.
+ * button.setAttribute('disabled', 'disabled');
+ *
+ * // Because PayPal tokenization opens a popup, this must be called
+ * // as a result of a user action, such as a button click.
+ * paypalInstance.tokenize({
+ * flow: 'vault' // Required
+ * // Any other tokenization options
+ * }, function (tokenizeErr, payload) {
+ * button.removeAttribute('disabled');
+ *
+ * if (tokenizeErr) {
+ * // Handle tokenization errors or premature flow closure
+ *
+ * switch (tokenizeErr.code) {
+ * case 'PAYPAL_POPUP_CLOSED':
+ * console.error('Customer closed PayPal popup.');
+ * break;
+ * case 'PAYPAL_ACCOUNT_TOKENIZATION_FAILED':
+ * console.error('PayPal tokenization failed. See details:', tokenizeErr.details);
+ * break;
+ * case 'PAYPAL_FLOW_FAILED':
+ * console.error('Unable to initialize PayPal flow. Are your options correct?', tokenizeErr.details);
+ * break;
+ * default:
+ * console.error('Error!', tokenizeErr);
+ * }
+ * } else {
+ * // Submit payload.nonce to your server
+ * }
+ * });
+ * });
+ * @returns {PayPal~tokenizeReturn} A handle to close the PayPal checkout frame.
+ */
+ public tokenize(options: { flow: string, intent: string, offerCredit: boolean, useraction: string, amount: (string | number), currency: string, displayName: string, locale: string, enableShippingAddress: boolean, shippingAddressOverride: PayPalShippingAddress, shippingAddressEditable: boolean, billingAgreementDescription: string }, callback: callback): PayPalTokenizeReturn;
+
+ /**
+ * Cleanly tear down anything set up by {@link module:braintree-web/paypal.create|create}.
+ * @public
+ * @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully.
+ * @returns {void}
+ */
+ public teardown(callback?: () => void): void;
+
+ }
+}
+
+/** @module braintree-web/three-d-secure */
+declare namespace BraintreeWeb {
+ /**
+ * @typedef {object} ThreeDSecure~verifyPayload
+ * @property {string} nonce The new payment method nonce produced by the 3D Secure lookup. The original nonce passed into {@link ThreeDSecure#verifyCard|verifyCard} was consumed. This new nonce should be used to transact on your server.
+ * @property {object} details Additional account details.
+ * @property {string} details.cardType Type of card, ex: Visa, MasterCard.
+ * @property {string} details.lastTwo Last two digits of card number.
+ * @property {string} description A human-readable description.
+ * @property {boolean} liabilityShiftPossible Indicates whether the card was eligible for 3D Secure.
+ * @property {boolean} liabilityShifted Indicates whether the liability for fraud has been shifted away from the merchant.
+ */
+ interface ThreeDSecureAccountDetails {
+ cardType: string;
+ lastTwo: string;
+ }
+
+ interface ThreeDSecureVerifyPayload {
+ nonce: string;
+ details: ThreeDSecureAccountDetails;
+ description: string;
+ liabilityShiftPossible: boolean;
+ liabilityShifted: boolean;
+ }
+
+ export interface ThreeDSecure {
+ /**
+ * @static
+ * @function create
+ * @param {object} options Creation options:
+ * @param {Client} options.client A {@link Client} instance.
+ * @param {callback} callback The second argument, `data`, is the {@link ThreeDSecure} instance.
+ * @returns {void}
+ * @example
+ * braintree.threeDSecure.create({
+ * client: client
+ * }, callback);
+ */
+ create: (options: { client: Client }, callback: callback) => void;
+
+ /**
+ * @description The current version of the SDK, i.e. `3.0.2`.
+ * @type {string}
+ */
+ VERSION: string;
+ }
+
+ /**
+ * @class
+ * @param {object} options 3D Secure {@link module:braintree-web/three-d-secure.create create} options
+ * @description Do not use this constructor directly. Use {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create} instead.
+ * @classdesc This class represents a ThreeDSecure component produced by {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create}. Instances of this class have a method for launching a 3D Secure authentication flow.
+ */
+ export class ThreeDSecure {
+ /**
+ * @class
+ * @param {object} options 3D Secure {@link module:braintree-web/three-d-secure.create create} options
+ * @description Do not use this constructor directly. Use {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create} instead.
+ * @classdesc This class represents a ThreeDSecure component produced by {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create}. Instances of this class have a method for launching a 3D Secure authentication flow.
+ */
+ constructor(options: any);
+
+
+ /**
+ * @callback ThreeDSecure~addFrameCallback
+ * @param {?BraintreeError} [err] `null` or `undefined` if there was no error.
+ * @param {HTMLIFrameElement} iframe An iframe element containing the bank's authentication page that you must put on your page.
+ * @description The callback used for options.addFrame in {@link ThreeDSecure#verifyCard|verifyCard}.
+ * @returns {void}
+ */
+ addFrameCallback: (err?: BraintreeError, iframe?: HTMLIFrameElement) => void;
+
+ /**
+ * @callback ThreeDSecure~removeFrameCallback
+ * @description The callback used for options.removeFrame in {@link ThreeDSecure#verifyCard|verifyCard}.
+ * @returns {void}
+ */
+ removeFrameCallback: () => void;
+
+ /**
+ * Launch the 3D Secure login flow, returning a nonce payload.
+ * @public
+ * @param {object} options Options for card verification.
+ * @param {string} options.nonce A nonce referencing the card to be verified. For example, this can be a nonce that was returned by Hosted Fields.
+ * @param {number} options.amount The amount of the transaction in the current merchant account's currency. For example, if you are running a transaction of $123.45 US dollars, `amount` would be 123.45.
+ * @param {errback} options.addFrame This {@link ThreeDSecure~addFrameCallback|addFrameCallback} will be called when the bank frame needs to be added to your page.
+ * @param {callback} options.removeFrame This {@link ThreeDSecure~removeFrameCallback|removeFrameCallback} will be called when the bank frame needs to be removed from your page.
+ * @param {errback} callback The second argument, data, is a {@link ThreeDSecure~verifyPayload|verifyPayload}
+ * @returns {void}
+ * @example
+ *
Verifying an existing nonce with 3DS
+ * var my3DSContainer;
+ *
+ * threeDSecure.verifyCard({
+ * nonce: existingNonce,
+ * amount: 123.45,
+ * addFrame: function (err, iframe) {
+ * // Set up your UI and add the iframe.
+ * my3DSContainer = document.createElement('div');
+ * my3DSContainer.appendChild(iframe);
+ * document.body.appendChild(my3DSContainer);
+ * },
+ * removeFrame: function () {
+ * // Remove UI that you added in addFrame.
+ * document.body.removeChild(my3DSContainer);
+ * }
+ * }, function (err, payload) {
+ * if (err) {
+ * console.error(err);
+ * return;
+ * }
+ *
+ * if (payload.liabilityShifted) {
+ * // Liablity has shifted
+ * submitNonceToServer(payload.nonce);
+ * } else if (payload.liabilityShiftPossible) {
+ * // Liablity may still be shifted
+ * // Decide if you want to submit the nonce
+ * } else {
+ * // Liablity has not shifted and will not shift
+ * // Decide if you want to submit the nonce
+ * }
+ * });
+ */
+ public verifyCard(options: { nonce: string, amount: number, addFrame: (err?: BraintreeError, iframe?: HTMLIFrameElement) => void, removeFrame: () => void }, callback: callback): void;
+
+ /**
+ * Cancel the 3DS flow and return the verification payload if available.
+ * @public
+ * @param {errback} callback The second argument is a {@link ThreeDSecure~verifyPayload|verifyPayload}. If there is no verifyPayload (the initial lookup did not complete), an error will be returned.
+ * @returns {void}
+ * @example
+ * threeDSecure.cancelVerifyCard(function (err, verifyPayload) {
+ * if (err) {
+ * // Handle error
+ * console.log(err.message); // No verification payload available
+ * return;
+ * }
+ *
+ * verifyPayload.nonce; // The nonce returned from the 3ds lookup call
+ * verifyPayload.liabilityShifted; // boolean
+ * verifyPayload.liabilityShiftPossible; // boolean
+ * });
+ */
+ public cancelVerifyCard(callback: callback): void;
+
+ /**
+ * Cleanly tear down anything set up by {@link module:braintree-web/three-d-secure.create|create}
+ * @public
+ * @param {errback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully.
+ * @returns {void}
+ */
+ public teardown(callback?: callback): void;
+ }
+}
+
+/**
+ * @module braintree-web/unionpay
+ * @description This module allows you to accept UnionPay payments. *It is currently in beta and is subject to change.*
+ */
+declare namespace BraintreeWeb {
+ /**
+ * @typedef {object} UnionPay~tokenizePayload
+ * @property {string} nonce The payment method nonce.
+ * @property {string} type Always CreditCard.
+ * @property {object} details Additional account details:
+ * @property {string} details.cardType Type of card, ex: Visa, MasterCard.
+ * @property {string} details.lastTwo Last two digits of card number.
+ * @property {string} description A human-readable description.
+ */
+ interface UnionPayAccountDetails {
+ cardType: string;
+ lastTwo: string;
+ description: string;
+ }
+
+ interface UnionPayTokenizePayload {
+ nonce: string;
+ type: string;
+ details: UnionPayAccountDetails;
+ }
+
+ /**
+ * @typedef {object} UnionPay~enrollPayload
+ * @property {string} enrollmentId UnionPay enrollment ID. This value should be passed to `tokenize`.
+ * @property {boolean} smsCodeRequired UnionPay `smsCodeRequired` flag.
+ *
true - the user will receive an SMS code that needs to be supplied for tokenization.
+ * false - the card can be immediately tokenized.
+ */
+ interface UnionPayEnrollPayload {
+ enrollmentId: string;
+ smsCodeRequired: boolean;
+ }
+
+ /**
+ * @typedef {object} UnionPay~fetchCapabilitiesPayload
+ * @property {boolean} isUnionPay Determines if this card is a UnionPay card.
+ * @property {boolean} isDebit Determines if this card is a debit card. This property is only present if `isUnionPay` is `true`.
+ * @property {object} unionPay UnionPay specific properties. This property is only present if `isUnionPay` is `true`.
+ * @property {boolean} unionPay.supportsTwoStepAuthAndCapture Determines if the card allows for an authorization, but settling the transaction later.
+ * @property {boolean} unionPay.isSupported Determines if Braintree can process this UnionPay card. When false, Braintree cannot process this card and the user should use a different card.
+ */
+
+ interface UnionPayProperties {
+ supportsTwoStepAuthAndCapture: boolean;
+ isSupported: boolean;
+ }
+
+ interface UnionPayFetchCapabilitiesPayload {
+ isUnionPay: boolean;
+ isDebit: boolean;
+ unionPay: UnionPayProperties;
+ }
+
+ export interface UnionPay {
+ /**
+ * @static
+ * @function create
+ * @param {object} options Creation options:
+ * @param {Client} options.client A {@link Client} instance.
+ * @param {callback} callback The second argument, `data`, is the {@link UnionPay} instance.
+ * @returns {void}
+ * @example
+ * braintree.unionpay.create({ client: clientInstance }, function (createErr, unionpayInstance) {
+ * if (createErr) {
+ * console.error(createErr);
+ * return;
+ * }
+ * // ...
+ * });
+ */
+ create: (options: { client: Client }, callback: callback) => void;
+
+ /**
+ * @description The current version of the SDK, i.e. `3.0.2`.
+ * @type {string}
+ */
+ VERSION: string;
+ }
+
+ /**
+ * @class
+ * @param {object} options See {@link module:braintree-web/unionpay.create|unionpay.create}.
+ * @description You cannot use this constructor directly. Use {@link module:braintree-web/unionpay.create|braintree-web.unionpay.create} instead.
+ * @classdesc This class represents a UnionPay component. Instances of this class have methods for {@link UnionPay#fetchCapabilities fetching capabilities} of UnionPay cards, {@link UnionPay#enroll enrolling} a UnionPay card, and {@link UnionPay#tokenize tokenizing} a UnionPay card.
+ */
+ export class UnionPay {
+ /**
+ * @class
+ * @param {object} options See {@link module:braintree-web/unionpay.create|unionpay.create}.
+ * @description You cannot use this constructor directly. Use {@link module:braintree-web/unionpay.create|braintree-web.unionpay.create} instead.
+ * @classdesc This class represents a UnionPay component. Instances of this class have methods for {@link UnionPay#fetchCapabilities fetching capabilities} of UnionPay cards, {@link UnionPay#enroll enrolling} a UnionPay card, and {@link UnionPay#tokenize tokenizing} a UnionPay card.
+ */
+ constructor(options: any);
+
+ /**
+ * Fetches the capabilities of a card, including whether or not the SMS enrollment process is required.
+ * @public
+ * @param {object} options UnionPay {@link UnionPay#fetchCapabilities fetchCapabilities} options
+ * @param {object} [options.card] The card from which to fetch capabilities. Note that this will only have one property, `number`. Required if you are not using the `hostedFields` option.
+ * @param {string} options.card.number Card number.
+ * @param {HostedFields} [options.hostedFields] The Hosted Fields instance used to collect card data. Required if you are not using the `card` option.
+ * @param {callback} callback The second argument, data, is a {@link UnionPay#fetchCapabilitiesPayload fetchCapabilitiesPayload}.
+ * @example
With raw card data
+ * unionpayInstance.fetchCapabilities({
+ * card: {
+ * number: '4111111111111111'
+ * }
+ * }, function (fetchErr, cardCapabilities) {
+ * if (fetchErr) {
+ * console.error(fetchErr);
+ * return;
+ * }
+ *
+ * if (cardCapabilities.isUnionPay) {
+ * if (cardCapabilities.unionPay && !cardCapabilities.unionPay.isSupported) {
+ * // Braintree cannot process this UnionPay card.
+ * // Ask the user for a different card.
+ * return;
+ * }
+ *
+ * if (cardCapabilities.isDebit) {
+ * // CVV and expiration date are not required
+ * } else {
+ * // CVV and expiration date are required
+ * }
+ *
+ * // Show mobile phone number field for enrollment
+ * }
+ * });
+ * @example
With Hosted Fields
+ * // Fetch capabilities on `blur` inside of the Hosted Fields `create` callback
+ * hostedFieldsInstance.on('blur', function (event) {
+ * // Only attempt to fetch capabilities when a valid card number has been entered
+ * if (event.emittedBy === 'number' && event.fields.number.isValid) {
+ * unionpayInstance.fetchCapabilities({
+ * hostedFields: hostedFieldsInstance
+ * }, function (fetchErr, cardCapabilities) {
+ * if (fetchErr) {
+ * console.error(fetchErr);
+ * return;
+ * }
+ *
+ * if (cardCapabilities.isUnionPay) {
+ * if (cardCapabilities.unionPay && !cardCapabilities.unionPay.isSupported) {
+ * // Braintree cannot process this UnionPay card.
+ * // Ask the user for a different card.
+ * return;
+ * }
+ * if (cardCapabilities.isDebit) {
+ * // CVV and expiration date are not required
+ * // Hide the containers with your `cvv` and `expirationDate` fields
+ * } else {
+ * // CVV and expiration date are required
+ * }
+ * } else {
+ * // Not a UnionPay card
+ * // When form is complete, tokenize using your Hosted Fields instance
+ * }
+ *
+ * // Show your own mobile country code and phone number inputs for enrollment
+ * });
+ * });
+ * });
+ * @returns {void}
+ */
+ public fetchCapabilities(options: { card: any, hostedFields: HostedFields }, callback: callback): void;
+
+ /**
+ * Enrolls a UnionPay card. Use {@link UnionPay#fetchCapabilities|fetchCapabilities} to determine if the SMS enrollment process is required.
+ * @public
+ * @param {object} options UnionPay enrollment options:
+ * @param {object} [options.card] The card to enroll. Required if you are not using the `hostedFields` option.
+ * @param {string} options.card.number The card number.
+ * @param {string} [options.card.expirationDate] The card's expiration date. May be in the form `MM/YY` or `MM/YYYY`. When defined `expirationMonth` and `expirationYear` are ignored.
+ * @param {string} [options.card.expirationMonth] The card's expiration month. This should be used with the `expirationYear` parameter. When `expirationDate` is defined this parameter is ignored.
+ * @param {string} [options.card.expirationYear] The card's expiration year. This should be used with the `expirationMonth` parameter. When `expirationDate` is defined this parameter is ignored.
+ * @param {HostedFields} [options.hostedFields] The Hosted Fields instance used to collect card data. Required if you are not using the `card` option.
+ * @param {object} options.mobile The mobile information collected from the customer.
+ * @param {string} options.mobile.countryCode The country code of the customer's mobile phone number.
+ * @param {string} options.mobile.number The customer's mobile phone number.
+ * @param {callback} callback The second argument, data, is a {@link UnionPay~enrollPayload|enrollPayload}.
+ * @example
With raw card data
+ * unionpayInstance.enroll({
+ * card: {
+ * number: '4111111111111111',
+ * expirationMonth: '12',
+ * expirationYear: '2038'
+ * },
+ * mobile: {
+ * countryCode: '62',
+ * number: '111111111111'
+ * }
+ * }, function (enrollErr, response) {
+ * if (enrollErr) {
+ * console.error(enrollErr);
+ * return;
+ * }
+ *
+ * if (response.smsCodeRequired) {
+ * // If smsCodeRequired, wait for SMS auth code from customer
+ * // Then use response.enrollmentId during {@link UnionPay#tokenize}
+ * } else {
+ * // SMS code is not required from the user.
+ * // {@link UnionPay#tokenize} can be called immediately
+ * });
+ * @example
With Hosted Fields
+ * unionpayInstance.enroll({
+ * hostedFields: hostedFields,
+ * mobile: {
+ * countryCode: '62',
+ * number: '111111111111'
+ * }
+ * }, function (enrollErr, response) {
+ * if (enrollErr) {
+ * console.error(enrollErr);
+ * return;
+ * }
+ *
+ * if (response.smsCodeRequired) {
+ * // If smsCodeRequired, wait for SMS auth code from customer
+ * // Then use response.enrollmentId during {@link UnionPay#tokenize}
+ * } else {
+ * // SMS code is not required from the user.
+ * // {@link UnionPay#tokenize} can be called immediately
+ * }
+ * });
+ * @returns {void}
+ */
+ public enroll(options: { card: any, hostedFields: HostedFields, mobile: any }, callback: callback): void;
+
+ /**
+ * Tokenizes a UnionPay card and returns a nonce payload.
+ * @public
+ * @param {object} options UnionPay tokenization options:
+ * @param {object} [options.card] The card to enroll. Required if you are not using the `hostedFields` option.
+ * @param {string} options.card.number The card number.
+ * @param {string} [options.card.expirationDate] The card's expiration date. May be in the form `MM/YY` or `MM/YYYY`. When defined `expirationMonth` and `expirationYear` are ignored.
+ * @param {string} [options.card.expirationMonth] The card's expiration month. This should be used with the `expirationYear` parameter. When `expirationDate` is defined this parameter is ignored.
+ * @param {string} [options.card.expirationYear] The card's expiration year. This should be used with the `expirationMonth` parameter. When `expirationDate` is defined this parameter is ignored.
+ * @param {string} [options.card.cvv] The card's security number.
+ * @param {HostedFields} [options.hostedFields] The Hosted Fields instance used to collect card data. Required if you are not using the `card` option.
+ * @param {string} options.enrollmentId The enrollment ID from {@link UnionPay#enroll}.
+ * @param {string} [options.smsCode] The SMS code received from the user if {@link UnionPay#enroll} payload have `smsCodeRequired`. if `smsCodeRequired` is false, smsCode should not be passed.
+ * @param {callback} callback The second argument, data, is a {@link UnionPay~tokenizePayload|tokenizePayload}.
+ * @example
With raw card data
+ * unionpayInstance.tokenize({
+ * card: {
+ * number: '4111111111111111',
+ * expirationMonth: '12',
+ * expirationYear: '2038',
+ * cvv: '123'
+ * },
+ * enrollmentId: enrollResponse.enrollmentId, // Returned from enroll
+ * smsCode: '11111' // Received by customer's phone, if SMS enrollment was required. Otherwise it should be omitted
+ * }, function (tokenizeErr, response) {
+ * if (tokenizeErr) {
+ * console.error(tokenizeErr);
+ * return;
+ * }
+ *
+ * // Send response.nonce to your server
+ * });
+ * @example
With Hosted Fields
+ * unionpayInstance.tokenize({
+ * hostedFields: hostedFieldsInstance,
+ * enrollmentId: enrollResponse.enrollmentId, // Returned from enroll
+ * smsCode: '11111' // Received by customer's phone, if SMS enrollment was required. Otherwise it should be omitted
+ * }, function (tokenizeErr, response) {
+ * if (tokenizeErr) {
+ * console.error(tokenizeErr);
+ * return;
+ * }
+ *
+ * // Send response.nonce to your server
+ * });
+ * @returns {void}
+ */
+ public tokenize(options: { card: any, hostedFields: HostedFields, enrollmentId: string, smsCode: string }, callback: callback): void;
+
+ /**
+ * Cleanly tear down anything set up by {@link module:braintree-web/unionpay.create|create}. This only needs to be called when using UnionPay with Hosted Fields.
+ * @public
+ * @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully.
+ * @example
+ * unionpayInstance.teardown(function (teardownErr) {
+ * if (teardownErr) {
+ * console.error('Could not tear down UnionPay.');
+ * } else {
+ * console.log('UnionPay has been torn down.');
+ * }
+ * });
+ * @returns {void}
+ */
+ public teardown(callback?: callback): void;
+
+ }
+}
+
+declare namespace BraintreeError {
+ /**
+ * Enum for {@link BraintreeError} types.
+ * @name BraintreeError.types
+ * @enum
+ * @readonly
+ * @memberof BraintreeError
+ * @property {string} CUSTOMER An error caused by the customer.
+ * @property {string} MERCHANT An error that is actionable by the merchant.
+ * @property {string} NETWORK An error due to a network problem.
+ * @property {string} INTERNAL An error caused by Braintree code.
+ * @property {string} UNKNOWN An error where the origin is unknown.
+ */
+ export enum Types {
+ CUSTOMER,
+ MERCHANT,
+ NETWORK,
+ INTERNAL,
+ UNKNOWN
+ }
+}
+
+/**
+ * @class
+ * @global
+ * @param {object} options Construction options
+ * @classdesc This class is used to report error conditions, frequently as the first parameter to callbacks throughout the Braintree SDK.
+ * @description You cannot use this constructor directly. Interact with instances of this class through {@link callback callbacks}.
+ */
+declare class BraintreeError {
+ /**
+ * @class
+ * @global
+ * @param {object} options Construction options
+ * @classdesc This class is used to report error conditions, frequently as the first parameter to callbacks throughout the Braintree SDK.
+ * @description You cannot use this constructor directly. Interact with instances of this class through {@link callback callbacks}.
+ */
+ constructor(options: any);
+
+ /**
+ * @type {string}
+ * @description A code that corresponds to specific errors.
+ */
+ code: string;
+
+ /**
+ * @type {string}
+ * @description A short description of the error.
+ */
+ message: string;
+
+ /**
+ * @type {BraintreeError.types}
+ * @description The type of error.
+ */
+ type: BraintreeError.Types;
+
+ /**
+ * @type {object=}
+ * @description Additional information about the error, such as an underlying network error response.
+ */
+ details: any;
+}
+
+declare namespace BraintreeWeb {
+ /**
+ * @global
+ * @callback callback
+ * @param {?BraintreeError} [err] `null` or `undefined` if there was no error.
+ * @param {?any} [data] The successful result of the asynchronous function call (if data exists).
+ * @description The Node.js-style callback pattern used throughout the SDK.
+ * @returns {void}
+ */
+ type callback = (err?: BraintreeError, data?: any) => void;
+}
+
+/**
+ * @module braintree-web
+ * @description This is the top-level module exported by the Braintree JavaScript SDK. In a browser environment, this will be the global braintree object. In a CommonJS environment (like Browserify or Webpack), it will be the default export of the braintree-web package. In AMD environments (like RequireJS), it can be `require`d like other modules.
+ * @example
+ *