Merge pull request #1 from borisyankov/master

update from original
This commit is contained in:
Marcel van de Kamp
2015-08-30 16:15:08 +02:00
901 changed files with 400476 additions and 33159 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
language: node_js
node_js:
- "0.10"
- "iojs-v2"
sudo: false
+283 -58
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,115 @@
/// <reference path="PayPal-Cordova-Plugin.d.ts"/>
var item: PayPalItem;
item = new PayPalItem("name", 10, "25.00", "USD");
item = new PayPalItem("name", 10, "25.00", "USD", null);
item = new PayPalItem("name", 10, "25.00", "USD", "SKU_ID");
var item_name: string = item.name;
var item_quantity: number = item.quantity;
var item_price: string = item.price;
var item_currency: string = item.currency;
var item_sku: string = item.sku;
var paymentDetails: PayPalPaymentDetails;
paymentDetails = new PayPalPaymentDetails("10.50", "2.50", "1.25");
var paymentDetails_subtotal: string = paymentDetails.subtotal;
var paymentDetails_shipping: string = paymentDetails.shipping;
var paymentDetails_tax: string = paymentDetails.tax;
var shippingAddress: PayPalShippingAddress;
shippingAddress = new PayPalShippingAddress("name", "line1", "line2", "city", "state", "postalCode", "countryCode");
var shippingAddress_recipientName: string = shippingAddress.recipientName;
var shippingAddress_line1: string = shippingAddress.line1;
var shippingAddress_line2: string = shippingAddress.line2;
var shippingAddress_city: string = shippingAddress.city;
var shippingAddress_state: string = shippingAddress.state;
var shippingAddress_postalCode: string = shippingAddress.postalCode;
var shippingAddress_countryCode: string = shippingAddress.countryCode;
var payment: PayPalPayment;
payment = new PayPalPayment("10.00", "USD", "description", "Auth");
payment = new PayPalPayment("10.00", "USD", "description", "Auth", paymentDetails);
var payment_amount: string = payment.amount;
var payment_currency: string = payment.currency;
var payment_shortDescription: string = payment.shortDescription;
var payment_intent: string = payment.intent;
var payment_details: PayPalPaymentDetails = payment.details;
var payment_invoiceNumber: string = payment.invoiceNumber;
var payment_custom: string = payment.custom;
var payment_softDescriptor: string = payment.softDescriptor;
var payment_bnCode: string = payment.bnCode;
var payment_items: PayPalItem[] = [item, item, item];
var payment_shippingAddress: PayPalShippingAddress = shippingAddress;
var configOptions: PayPalConfigurationOptions = {
defaultUserEmail: "email",
defaultUserPhoneCountryCode: "countryCode",
defaultUserPhoneNumber: "phoneNumber",
merchantName: "merchantName",
merchantPrivacyPolicyURL: "merchantPrivacyPolicyURL",
merchantUserAgreementURL: "merchantUserAgreementURL",
acceptCreditCards: true,
payPalShippingAddressOption: 10,
rememberUser: true,
languageOrLocale: "languageOrLocal",
disableBlurWhenBackgrounding: true,
presentingInPopover: true,
forceDefaultsInSandbox: true,
sandboxUserPassword: "sandboxUserPassword",
sandboxUserPin: "sandboxUserPin"
};
var config: PayPalConfiguration;
config = new PayPalConfiguration();
config = new PayPalConfiguration(null);
config = new PayPalConfiguration(configOptions);
var config_defaultUserEmail: string = config.defaultUserEmail;
var config_defaultUserPhoneCountryCode: string = config.defaultUserPhoneCountryCode;
var config_defaultUserPhoneNumber: string = config.defaultUserPhoneNumber;
var config_merchantName: string = config.merchantName;
var config_merchantPrivacyPolicyURL: string = config.merchantPrivacyPolicyURL;
var config_merchantUserAgreementURL: string = config.merchantUserAgreementURL;
var config_acceptCreditCards: boolean = config.acceptCreditCards;
var config_payPalShippingAddressOption: number = config.payPalShippingAddressOption;
var config_rememberUser: boolean = config.rememberUser;
var config_languageOrLocale: string = config.languageOrLocale;
var config_disableBlurWhenBackgrounding: boolean = config.disableBlurWhenBackgrounding;
var config_presentingInPopover: boolean = config.presentingInPopover;
var config_forceDefaultsInSandbox: boolean = config.forceDefaultsInSandbox;
var config_sandboxUserPasword: string = config.sandboxUserPassword;
var config_sandboxUserPin: string = config.sandboxUserPin;
var clientIds: PayPalCordovaPlugin.PayPalClientIds = {
PayPalEnvironmentProduction: "",
PayPalEnvironmentSandbox: ""
};
var apiModule: PayPalCordovaPlugin.PayPalMobileStatic = PayPalMobile;
apiModule.version((result: string) => {});
apiModule.init(clientIds, () => {});
apiModule.prepareToRender("environment", config, () => {});
apiModule.renderSinglePaymentUI(payment, (result: any) => {}, (cancelReason: string) => {});
apiModule.applicationCorrelationIDForEnvironment("environment", (applicationCorrelationId: string) => {});
apiModule.clientMetadataID((clientMetadataId: string) => {});
apiModule.renderFuturePaymentUI((result: any) => {}, (cancelReason: string) => {});
apiModule.renderProfileSharingUI(["openid", "profile", "email"], (result: any) => {}, (cancelReason: string) => {});
+615
View File
@@ -0,0 +1,615 @@
// Type definitions for PayPal-Cordova-Plugin 3.1.10
// Project: https://github.com/paypal/PayPal-Cordova-Plugin
// Definitions by: Justin Unterreiner <https://github.com/Justin-Credible>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
//#region paypal-mobile-js-helper.js
/**
* The PayPalItem class defines an optional itemization for a payment.
*
* @see https://developer.paypal.com/docs/api/#item-object for more details.
*/
declare class PayPalItem {
/**
* @param name Name of the item. 127 characters max.
* @param quantity Number of units. 10 characters max.
* @param price Unit price for this item 10 characters max.
* May be negative for "coupon" etc.
* @param currency ISO standard currency code.
* @param sku The stock keeping unit for this item. 50 characters max (optional).
*/
constructor(name: string, quantity: number, price: string, currency: string, sku?: string);
/**
* Name of the item. 127 characters max.
*/
name: string;
/**
* Number of units. 10 characters max.
*/
quantity: number;
/**
* Unit price for this item 10 characters max.
* May be negative for "coupon" etc.
*/
price: string;
/**
* ISO standard currency code.
*/
currency: string;
/**
* The stock keeping unit for this item. 50 characters max (optional).
*/
sku: string;
}
/**
* The PayPalPaymentDetails class defines optional amount details.
*
* @see https://developer.paypal.com/webapps/developer/docs/api/#details-object for more details.
*/
declare class PayPalPaymentDetails {
/**
* @param subtotal Sub-total (amount) of items being paid for. 10 characters max with support for 2 decimal places.
* @param shipping Amount charged for shipping. 10 characters max with support for 2 decimal places.
* @param tax Amount charged for tax. 10 characters max with support for 2 decimal places.
*/
constructor(subtotal: string, shipping: string, tax: string);
/**
* Sub-total (amount) of items being paid for. 10 characters max with support for 2 decimal places.
*/
subtotal: string;
/**
* Amount charged for shipping. 10 characters max with support for 2 decimal places.
*/
shipping: string;
/**
* Amount charged for tax. 10 characters max with support for 2 decimal places.
*/
tax: string;
}
/**
* Convenience constructor. Returns a PayPalPayment with the specified amount, currency code, and short description.
*/
declare class PayPalPayment {
/**
* @param amount The amount of the payment.
* @param currencyCode The ISO 4217 currency for the payment.
* @param shortDescription A short descripton of the payment.
* @param intent • "Sale" for an immediate payment.
* • "Auth" for payment authorization only, to be captured separately at a later time.
* • "Order" for taking an order, with authorization and capture to be done separately at a later time.
* @param details PayPalPaymentDetails object (optional).
*/
constructor(amount: string, currency: string, shortDescription: string, intent: string, details?: PayPalPaymentDetails);
/**
* The amount of the payment.
*/
amount: string;
/**
* The ISO 4217 currency for the payment.
*/
currency: string;
/**
* A short descripton of the payment.
*/
shortDescription: string;
/**
* • "Sale" for an immediate payment.
* • "Auth" for payment authorization only, to be captured separately at a later time.
* • "Order" for taking an order, with authorization and capture to be done separately at a later time.
*/
intent: string;
/**
* PayPalPaymentDetails object (optional).
*/
details: PayPalPaymentDetails;
/**
* Optional invoice number, for your tracking purposes. (up to 256 characters).
*/
invoiceNumber: string;
/**
* Optional text, for your tracking purposes. (up to 256 characters).
*/
custom: string;
/**
* Optional text which will appear on the customer's credit card statement. (up to 22 characters).
*/
softDescriptor: string;
/**
* Optional Build Notation code ("BN code"), obtained from partnerprogram@paypal.com, for your tracking purposes.
*/
bnCode: string;
/**
* Optional array of PayPalItem objects.
* @see PayPalItem
* @note If you provide one or more items, be sure that the various prices correctly sum to the payment `amount` or to `paymentDetails.subtotal`.
*/
items: PayPalItem[];
/**
* Optional customer shipping address, if your app wishes to provide this to the SDK.
* @note make sure to set `payPalShippingAddressOption` in PayPalConfiguration to 1 or 3.
*/
shippingAddress: PayPalShippingAddress;
}
declare class PayPalShippingAddress {
/**
* @param recipientName Name of the recipient at this address. 50 characters max.
* @param line1 Line 1 of the address (e.g., Number, street, etc). 100 characters max.
* @param line2 Line 2 of the address (e.g., Suite, apt #, etc). 100 characters max. Optional.
* @param city City name. 50 characters max.
* @param state 2-letter code for US states, and the equivalent for other countries. 100 characters max. Required in certain countries.
* @param postalCode ZIP code or equivalent is usually required for countries that have them. 20 characters max. Required in certain countries.
* @param countryCode 2-letter country code. 2 characters max.
*/
constructor(recipientName: string, line1: string, line2: string, city: string, state: string, postalCode: string, countryCode: string);
/**
* Name of the recipient at this address. 50 characters max.
*/
recipientName: string;
/**
* Line 1 of the address (e.g., Number, street, etc). 100 characters max.
*/
line1: string;
/**
* Line 2 of the address (e.g., Suite, apt #, etc). 100 characters max. Optional.
*/
line2: string;
/**
* City name. 50 characters max.
*/
city: string;
/**
* 2-letter code for US states, and the equivalent for other countries. 100 characters max. Required in certain countries.
*/
state: string;
/**
* ZIP code or equivalent is usually required for countries that have them. 20 characters max. Required in certain countries.
*/
postalCode: string;
/**
* 2-letter country code. 2 characters max.
*/
countryCode: string;
}
declare class PayPalConfiguration {
/**
* @param options A set of options to use. Any options not specified will assume default values.
*/
constructor(options?: PayPalConfigurationOptions);
/**
* Will be overridden by email used in most recent PayPal login.
*/
defaultUserEmail: string;
/**
* Will be overridden by phone country code used in most recent PayPal login
*/
defaultUserPhoneCountryCode: string;
/**
* Will be overridden by phone number used in most recent PayPal login.
* @note If you set defaultUserPhoneNumber, be sure to also set defaultUserPhoneCountryCode.
*/
defaultUserPhoneNumber: string;
/**
* Your company name, as it should be displayed to the user
* when requesting consent via a PayPalFuturePaymentViewController.
*/
merchantName: string;
/**
* URL of your company's privacy policy, which will be offered to the user
* when requesting consent via a PayPalFuturePaymentViewController.
*/
merchantPrivacyPolicyURL: string;
/**
* URL of your company's user agreement, which will be offered to the user
* when requesting consent via a PayPalFuturePaymentViewController.
*/
merchantUserAgreementURL: string;
/**
* If set to false, the SDK will only support paying with PayPal, not with credit cards.
* This applies only to single payments (via PayPalPaymentViewController).
* Future payments (via PayPalFuturePaymentViewController) always use PayPal.
* Defaults to true.
*/
acceptCreditCards: boolean;
/**
* For single payments, options for the shipping address.
*
* - 0 - PayPalShippingAddressOptionNone: no shipping address applies.
*
* - 1 - PayPalShippingAddressOptionProvided: shipping address will be provided by your app,
* in the shippingAddress property of PayPalPayment.
*
* - 2 - PayPalShippingAddressOptionPayPal: user will choose from shipping addresses on file
* for their PayPal account.
*
* - 3 - PayPalShippingAddressOptionBoth: user will choose from the shipping address provided by your app,
* in the shippingAddress property of PayPalPayment, plus the shipping addresses on file for the user's PayPal account.
*
* Defaults to 0 (PayPalShippingAddressOptionNone).
*/
payPalShippingAddressOption: number;
/**
* If set to true, then if the user pays via their PayPal account,
* the SDK will remember the user's PayPal username or phone number;
* if the user pays via their credit card, then the SDK will remember
* the PayPal Vault token representing the user's credit card.
*
* If set to false, then any previously-remembered username, phone number, or
* credit card token will be erased, and subsequent payment information will
* not be remembered.
*
* Defaults to true.
*/
rememberUser: boolean;
/**
* If not set, or if set to nil, defaults to the device's current language setting.
*
* Can be specified as a language code ("en", "fr", "zh-Hans", etc.) or as a locale ("en_AU", "fr_FR", "zh-Hant_HK", etc.).
* If the library does not contain localized strings for a specified locale, then will fall back to the language. E.g., "es_CO" -> "es".
* If the library does not contain localized strings for a specified language, then will fall back to American English.
*
* If you specify only a language code, and that code matches the device's currently preferred language,
* then the library will attempt to use the device's current region as well.
* E.g., specifying "en" on a device set to "English" and "United Kingdom" will result in "en_GB".
*
* These localizations are currently included:
* da,de,en,en_AU,en_GB,en_SV,es,es_MX,fr,he,it,ja,ko,nb,nl,pl,pt,pt_BR,ru,sv,tr,zh-Hans,zh-Hant_HK,zh-Hant_TW.
*/
languageOrLocale: string;
/**
* Normally, the SDK blurs the screen when the app is backgrounded,
* to obscure credit card or PayPal account details in the iOS-saved screenshot.
* If your app already does its own blurring upon backgrounding, you might choose to disable this.
* Defaults to false.
*/
disableBlurWhenBackgrounding: boolean;
/**
* If you will present the SDK's view controller within a popover, then set this property to true.
* Defaults to false. (iOS only)
*/
presentingInPopover: boolean;
/**
* Sandbox credentials can be difficult to type on a mobile device. Setting this flag to true will
* cause the sandboxUserPassword and sandboxUserPin to always be pre-populated into login fields.
*
* This setting will have no effect if the operation mode is production.
* Defaults to false.
*/
forceDefaultsInSandbox: boolean;
/**
* Password to use for sandbox if 'forceDefaultsInSandbox' is set.
*/
sandboxUserPassword: string;
/**
* PIN to use for sandbox if 'forceDefaultsInSandbox' is set.
*/
sandboxUserPin: string;
}
/**
* Describes the options that can be passed into the PayPalConfiguration class constructor.
*/
interface PayPalConfigurationOptions {
/**
* Will be overridden by email used in most recent PayPal login.
*/
defaultUserEmail?: string;
/**
* Will be overridden by phone country code used in most recent PayPal login
*/
defaultUserPhoneCountryCode?: string;
/**
* Will be overridden by phone number used in most recent PayPal login.
* @note If you set defaultUserPhoneNumber, be sure to also set defaultUserPhoneCountryCode.
*/
defaultUserPhoneNumber?: string;
/**
* Your company name, as it should be displayed to the user
* when requesting consent via a PayPalFuturePaymentViewController.
*/
merchantName?: string;
/**
* URL of your company's privacy policy, which will be offered to the user
* when requesting consent via a PayPalFuturePaymentViewController.
*/
merchantPrivacyPolicyURL?: string;
/**
* URL of your company's user agreement, which will be offered to the user
* when requesting consent via a PayPalFuturePaymentViewController.
*/
merchantUserAgreementURL?: string;
/**
* If set to false, the SDK will only support paying with PayPal, not with credit cards.
* This applies only to single payments (via PayPalPaymentViewController).
* Future payments (via PayPalFuturePaymentViewController) always use PayPal.
* Defaults to true.
*/
acceptCreditCards?: boolean;
/**
* For single payments, options for the shipping address.
*
* - 0 - PayPalShippingAddressOptionNone?: no shipping address applies.
*
* - 1 - PayPalShippingAddressOptionProvided?: shipping address will be provided by your app,
* in the shippingAddress property of PayPalPayment.
*
* - 2 - PayPalShippingAddressOptionPayPal?: user will choose from shipping addresses on file
* for their PayPal account.
*
* - 3 - PayPalShippingAddressOptionBoth?: user will choose from the shipping address provided by your app,
* in the shippingAddress property of PayPalPayment, plus the shipping addresses on file for the user's PayPal account.
*
* Defaults to 0 (PayPalShippingAddressOptionNone).
*/
payPalShippingAddressOption?: number;
/**
* If set to true, then if the user pays via their PayPal account,
* the SDK will remember the user's PayPal username or phone number;
* if the user pays via their credit card, then the SDK will remember
* the PayPal Vault token representing the user's credit card.
*
* If set to false, then any previously-remembered username, phone number, or
* credit card token will be erased, and subsequent payment information will
* not be remembered.
*
* Defaults to true.
*/
rememberUser?: boolean;
/**
* If not set, or if set to nil, defaults to the device's current language setting.
*
* Can be specified as a language code ("en", "fr", "zh-Hans", etc.) or as a locale ("en_AU", "fr_FR", "zh-Hant_HK", etc.).
* If the library does not contain localized strings for a specified locale, then will fall back to the language. E.g., "es_CO" -> "es".
* If the library does not contain localized strings for a specified language, then will fall back to American English.
*
* If you specify only a language code, and that code matches the device's currently preferred language,
* then the library will attempt to use the device's current region as well.
* E.g., specifying "en" on a device set to "English" and "United Kingdom" will result in "en_GB".
*
* These localizations are currently included:
* da,de,en,en_AU,en_GB,en_SV,es,es_MX,fr,he,it,ja,ko,nb,nl,pl,pt,pt_BR,ru,sv,tr,zh-Hans,zh-Hant_HK,zh-Hant_TW.
*/
languageOrLocale?: string;
/**
* Normally, the SDK blurs the screen when the app is backgrounded,
* to obscure credit card or PayPal account details in the iOS-saved screenshot.
* If your app already does its own blurring upon backgrounding, you might choose to disable this.
* Defaults to false.
*/
disableBlurWhenBackgrounding?: boolean;
/**
* If you will present the SDK's view controller within a popover, then set this property to true.
* Defaults to false. (iOS only)
*/
presentingInPopover?: boolean;
/**
* Sandbox credentials can be difficult to type on a mobile device. Setting this flag to true will
* cause the sandboxUserPassword and sandboxUserPin to always be pre-populated into login fields.
*
* This setting will have no effect if the operation mode is production.
* Defaults to false.
*/
forceDefaultsInSandbox?: boolean;
/**
* Password to use for sandbox if 'forceDefaultsInSandbox' is set.
*/
sandboxUserPassword?: string;
/**
* PIN to use for sandbox if 'forceDefaultsInSandbox' is set.
*/
sandboxUserPin?: string;
}
//#endregion
//#region cdv-plugin-paypal-mobile-sdk.js
declare module PayPalCordovaPlugin {
export interface PayPalClientIds {
PayPalEnvironmentProduction: string;
PayPalEnvironmentSandbox: string;
}
/**
* Represents the portion of an object that is common to all responses.
*/
export interface BaseResult {
client: Client;
response_type: string;
}
/**
* Represents the client portion of the response.
*/
export interface Client {
paypal_sdk_version: string;
environment: string;
platform: string;
product_name: string;
}
/**
* Represents the response for a successful callback from renderSinglePaymentUI().
*/
export interface SinglePaymentResult extends BaseResult {
response: {
intent: string;
id: string;
state: string;
authorization_id: string;
create_time: string;
};
}
/**
* Represents the response for a successful callback from renderFuturePaymentUI().
*/
export interface FuturePaymentResult extends BaseResult {
response: {
code: string;
};
}
export interface PayPalMobileStatic {
/**
* Retrieve the version of the PayPal iOS SDK library. Useful when contacting support.
*
* @param completionCallback a callback function accepting a string
*/
version(completionCallback: (result: string) => void): void;
/**
* You MUST call this method to initialize the PayPal Mobile SDK.
*
* The PayPal Mobile SDK can operate in different environments to facilitate development and testing.
*
* @param clientIdsForEnvironments set of client ids for environments
* Example: var clientIdsForEnvironments = {
* PayPalEnvironmentProduction : @"my-client-id-for-Production",
* PayPalEnvironmentSandbox : @"my-client-id-for-Sandbox"
* }
* @param completionCallback a callback function on success
*/
init(clientIdsForEnvironments: PayPalCordovaPlugin.PayPalClientIds, completionCallback: () => void): void;
/**
* You must preconnect to PayPal to prepare the device for processing payments.
* This improves the user experience, by making the presentation of the
* UI faster. The preconnect is valid for a limited time, so
* the recommended time to preconnect is on page load.
*
* @param environment available options are "PayPalEnvironmentNoNetwork", "PayPalEnvironmentProduction" and "PayPalEnvironmentSandbox"
* @param configuration PayPalConfiguration object, for Future Payments merchantName, merchantPrivacyPolicyURL
* and merchantUserAgreementURL must be set be set
* @param completionCallback a callback function on success
*/
prepareToRender(environment: string, configuration: PayPalConfiguration, completionCallback: () => void): void;
/**
* Start PayPal UI to collect payment from the user.
* See https://developer.paypal.com/webapps/developer/docs/integration/mobile/ios-integration-guide/
* for more documentation of the params.
*
* @param payment PayPalPayment object
* @param completionCallback a callback function accepting a js object, called when the user has completed payment
* @param cancelCallback a callback function accepting a reason string, called when the user cancels the payment
*/
renderSinglePaymentUI(payment: PayPalPayment, completionCallback: (result: PayPalCordovaPlugin.SinglePaymentResult) => void, cancelCallback: (cancelReason: string) => void): void;
/**
* @deprecated
* Once a user has consented to future payments, when the user subsequently initiates a PayPal payment
* from their device to be completed by your server, PayPal uses a Correlation ID to verify that the
* payment is originating from a valid, user-consented device+application.
* This helps reduce fraud and decrease declines.
* This method MUST be called prior to initiating a pre-consented payment (a "future payment") from a mobile device.
* Pass the result to your server, to include in the payment request sent to PayPal.
* Do not otherwise cache or store this value.
*
* @param environment available options are "PayPalEnvironmentNoNetwork", "PayPalEnvironmentProduction" and "PayPalEnvironmentSandbox"
* @param callback applicationCorrelationID Your server will send this to PayPal in a 'Paypal-Application-Correlation-Id' header.
*/
applicationCorrelationIDForEnvironment(environment: string, completionCallback: (applicationCorrelationId: string) => void): void;
/**
* Once a user has consented to future payments, when the user subsequently initiates a PayPal payment
* from their device to be completed by your server, PayPal uses a Correlation ID to verify that the
* payment is originating from a valid, user-consented device+application.
* This helps reduce fraud and decrease declines.
* This method MUST be called prior to initiating a pre-consented payment (a "future payment") from a mobile device.
* Pass the result to your server, to include in the payment request sent to PayPal.
* Do not otherwise cache or store this value.
*
* @param callback clientMetadataID Your server will send this to PayPal in a 'PayPal-Client-Metadata-Id' header.
*/
clientMetadataID(completionCallback: (clientMetadataId: string) => void): void;
/**
* Please Read Docs on Future Payments at https://github.com/paypal/PayPal-iOS-SDK#future-payments
*
* @param completionCallback a callback function accepting a js object with future payment authorization
* @param cancelCallback a callback function accepting a reason string, called when the user canceled without agreement
*/
renderFuturePaymentUI(completionCallback: (result: PayPalCordovaPlugin.FuturePaymentResult) => void, cancelCallback: (cancelReason: string) => void): void;
/**
* Please Read Docs on Profile Sharing at https://github.com/paypal/PayPal-iOS-SDK#profile-sharing
*
* @param scopes scopes Set of requested scope-values. Accepted scopes are: openid, profile, address, email, phone, futurepayments and paypalattributes
* See https://developer.paypal.com/docs/integration/direct/identity/attributes/ for more details
* @param completionCallback a callback function accepting a js object with future payment authorization
* @param cancelCallback a callback function accepting a reason string, called when the user canceled without agreement
*/
renderProfileSharingUI(scopes: string[], completionCallback: (result: any) => void, cancelCallback: (cancelReason: string) => void): void;
}
}
declare var PayPalMobile: PayPalCordovaPlugin.PayPalMobileStatic;
//#endregion
+10
View File
@@ -0,0 +1,10 @@
/// <reference path="_debugger.d.ts"/>
import _debugger = require("_debugger");
var {Client} = _debugger;
var client = new Client();
client.connect(8888, 'localhost');
client.listbreakpoints((err, res) => {
});
+135
View File
@@ -0,0 +1,135 @@
// Type definitions for Node.js debugger API
// Project: http://nodejs.org/
// Definitions by: Basarat Ali Syed <https://github.com/basarat>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts"/>
declare module NodeJS {
export module _debugger {
export interface Packet {
raw: string;
headers: string[];
body: Message;
}
export interface Message {
seq: number;
type: string;
}
export interface RequestInfo {
command: string;
arguments: any;
}
export interface Request extends Message, RequestInfo {
}
export interface Event extends Message {
event: string;
body?: any;
}
export interface Response extends Message {
request_seq: number;
success: boolean;
/** Contains error message if success === false. */
message?: string;
/** Contains message body if success === true. */
body?: any;
}
export interface BreakpointMessageBody {
type: string;
target: number;
line: number;
}
export class Protocol {
res: Packet;
state: string;
execute(data: string): void;
serialize(rq: Request): string;
onResponse: (pkt: Packet) => void;
}
export var NO_FRAME: number;
export var port: number;
export interface ScriptDesc {
name: string;
id: number;
isNative?: boolean;
handle?: number;
type: string;
lineOffset?: number;
columnOffset?: number;
lineCount?: number;
}
export interface Breakpoint {
id: number;
scriptId: number;
script: ScriptDesc;
line: number;
condition?: string;
scriptReq?: string;
}
export interface RequestHandler {
(err: boolean, body: Message, res: Packet): void;
request_seq?: number;
}
export interface ResponseBodyHandler {
(err: boolean, body?: any): void;
request_seq?: number;
}
export interface ExceptionInfo {
text: string;
}
export interface BreakResponse {
script?: ScriptDesc;
exception?: ExceptionInfo;
sourceLine: number;
sourceLineText: string;
sourceColumn: number;
}
export function SourceInfo(body: BreakResponse): string;
export interface ClientInstance extends EventEmitter {
protocol: Protocol;
scripts: ScriptDesc[];
handles: ScriptDesc[];
breakpoints: Breakpoint[];
currentSourceLine: number;
currentSourceColumn: number;
currentSourceLineText: string;
currentFrame: number;
currentScript: string;
connect(port: number, host: string): void;
req(req: any, cb: RequestHandler): void;
reqFrameEval(code: string, frame: number, cb: RequestHandler): void;
mirrorObject(obj: any, depth: number, cb: ResponseBodyHandler): void;
setBreakpoint(rq: BreakpointMessageBody, cb: RequestHandler): void;
clearBreakpoint(rq: Request, cb: RequestHandler): void;
listbreakpoints(cb: RequestHandler): void;
reqSource(from: number, to: number, cb: RequestHandler): void;
reqScripts(cb: any): void;
reqContinue(cb: RequestHandler): void;
}
export var Client : {
new (): ClientInstance
}
}
}
declare module "_debugger"{
export = NodeJS._debugger;
}
+13 -1
View File
@@ -47,7 +47,19 @@ interface AccWizardOptions {
nextText: string;
/**
* @summary Text for back button
* @summary Text for back button.
* @type {string}
*/
backText: string;
/**
* @summary HTML input type for next button. (default: "submit")
* @type {string}
*/
nextType: string;
/**
* @summary HTML input type for back button. (default: "reset")
* @type {string}
*/
backType: string;
+38 -1
View File
@@ -18,7 +18,9 @@ declare module AceAjax {
bindKey:any;
exec:Function;
exec: Function;
readOnly?: boolean;
}
export interface CommandManager {
@@ -1063,6 +1065,31 @@ declare module AceAjax {
onChangeMode(e?);
execCommand(command:string, args?: any);
/**
* Sets a Configuration Option
**/
setOption(optionName: any, optionValue: any);
/**
* Sets Configuration Options
**/
setOptions(keyValueTuples: any);
/**
* Get a Configuration Option
**/
getOption(name: any):any;
/**
* Get Configuration Options
**/
getOptions():any;
/**
* Get rid of console warning by setting this to Infinity
**/
$blockScrolling:number;
/**
* Sets a new key handler, such as "vim" or "windows".
@@ -2584,6 +2611,16 @@ declare module AceAjax {
* Returns `true` if there are redo operations left to perform.
**/
hasRedo(): boolean;
/**
* Returns `true` if the dirty counter is 0
**/
isClean(): boolean;
/**
* Sets dirty counter to 0
**/
markClean(): void;
}
var UndoManager: {
+1 -2
View File
@@ -1,4 +1,4 @@
/// <reference path='acl-mongodbBackend.d.ts'/>
/// <reference path='acl.d.ts'/>
// https://github.com/OptimalBits/node_acl/blob/master/Readme.md
import Acl = require('acl');
@@ -14,4 +14,3 @@ acl.allow('guest', 'blogs', 'view');
// allow function accepts arrays as any parameter
acl.allow('member', 'blogs', ['edit','view', 'delete']);
-22
View File
@@ -1,22 +0,0 @@
// Type definitions for node_acl 0.4.7
// Project: https://github.com/optimalbits/node_acl
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="acl.d.ts" />
/// <reference path="../mongodb/mongodb.d.ts" />
declare module "acl" {
import mongo = require('mongodb');
interface AclStatic {
mongodbBackend: MongodbBackendStatic;
}
interface MongodbBackend extends Backend<Callback> { }
interface MongodbBackendStatic {
new(db: mongo.Db, prefix: string, useSingle: boolean): MongodbBackend;
new(db: mongo.Db, prefix: string): MongodbBackend;
new(db: mongo.Db): MongodbBackend;
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
/// <reference path='acl-redisBackend.d.ts'/>
/// <reference path='acl.d.ts'/>
// https://github.com/OptimalBits/node_acl/blob/master/Readme.md
import Acl = require('acl');
-21
View File
@@ -1,21 +0,0 @@
// Type definitions for node_acl 0.4.7
// Project: https://github.com/optimalbits/node_acl
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="acl.d.ts" />
/// <reference path='../redis/redis.d.ts'/>
declare module "acl" {
import redis = require('redis');
interface AclStatic {
redisBackend: RedisBackendStatic;
}
interface RedisBackend extends Backend<redis.RedisClient> { }
interface RedisBackendStatic {
new(redis: redis.RedisClient, prefix: string): RedisBackend;
new(redis: redis.RedisClient): RedisBackend;
}
}
+30
View File
@@ -6,6 +6,9 @@
/// <reference path="../bluebird/bluebird.d.ts" />
/// <reference path='../node/node.d.ts'/>
/// <reference path='../redis/redis.d.ts'/>
/// <reference path="../mongodb/mongodb.d.ts" />
declare module "acl" {
import http = require('http');
import Promise = require("bluebird");
@@ -115,6 +118,33 @@ declare module "acl" {
end: () => void;
}
// for redis backend
import redis = require('redis');
interface AclStatic {
redisBackend: RedisBackendStatic;
}
interface RedisBackend extends Backend<redis.RedisClient> { }
interface RedisBackendStatic {
new(redis: redis.RedisClient, prefix: string): RedisBackend;
new(redis: redis.RedisClient): RedisBackend;
}
// for mongodb backend
import mongo = require('mongodb');
interface AclStatic {
mongodbBackend: MongodbBackendStatic;
}
interface MongodbBackend extends Backend<Callback> { }
interface MongodbBackendStatic {
new(db: mongo.Db, prefix: string, useSingle: boolean): MongodbBackend;
new(db: mongo.Db, prefix: string): MongodbBackend;
new(db: mongo.Db): MongodbBackend;
}
var _: AclStatic;
export = _;
}
+1 -1
View File
@@ -14,7 +14,7 @@ var string: string;
// acorn
string = acorn.version;
program = acorn.parse('code');
program = acorn.parse('code', {range: true, onToken: tokens, onComment: comments});
program = acorn.parse('code', {ranges: true, onToken: tokens, onComment: comments});
program = acorn.parse('code', {
ranges: true,
onToken: (token) => tokens.push(token),
+143
View File
@@ -0,0 +1,143 @@
/**
* Created by shearerbeard on 6/28/15.
*/
///<reference path="alt.d.ts"/>
///<reference path="../es6-promise/es6-promise.d.ts" />
import Alt = require("alt");
import Promise = require("es6-promise");
//New alt instance
var alt = new Alt();
//Interfaces for our Action Types
interface TestActionsGenerate {
notifyTest(str:string):void;
}
interface TestActionsExplicit {
doTest(str:string):void;
success():void;
error():void;
loading():void;
}
//Create abstracts to inherit ghost methods
class AbstractActions implements AltJS.ActionsClass {
constructor( alt:AltJS.Alt){}
actions:any;
dispatch: ( ...payload:Array<any>) => void;
generateActions:( ...actions:Array<string>) => void;
}
class AbstractStoreModel<S> implements AltJS.StoreModel<S> {
bindActions:( ...actions:Array<Object>) => void;
bindAction:( ...args:Array<any>) => void;
bindListeners:(obj:any)=> void;
exportPublicMethods:(config:{[key:string]:(...args:Array<any>) => any}) => any;
exportAsync:( source:any) => void;
waitFor:any;
exportConfig:any;
getState:() => S;
}
class GenerateActionsClass extends AbstractActions {
constructor(config:AltJS.Alt) {
this.generateActions("notifyTest");
super(config);
}
}
class ExplicitActionsClass extends AbstractActions {
doTest(str:string) {
this.dispatch(str);
}
success() {
this.dispatch();
}
error() {
this.dispatch();
}
loading() {
this.dispatch();
}
}
var generatedActions = alt.createActions<TestActionsGenerate>(GenerateActionsClass);
var explicitActions = alt.createActions<ExplicitActionsClass>(ExplicitActionsClass);
interface AltTestState {
hello:string;
}
var testSource:AltJS.Source = {
fakeLoad():AltJS.SourceModel<string> {
return {
remote() {
return new Promise.Promise<string>((res:any, rej:any) => {
setTimeout(() => {
if(true) {
res("stuff");
} else {
rej("Things have broken");
}
}, 250)
});
},
local() {
return "local";
},
success: explicitActions.success,
error: explicitActions.error,
loading:explicitActions.loading
};
}
};
class TestStore extends AbstractStoreModel<AltTestState> implements AltTestState {
hello:string = "world";
constructor() {
super();
this.bindAction(generatedActions.notifyTest, this.onTest);
this.bindActions(explicitActions);
this.exportAsync(testSource);
this.exportPublicMethods({
split: this.split
});
}
onTest(str:string) {
this.hello = str;
}
onDoTest(str:string) {
this.hello = str;
}
split():string[] {
return this.hello.split("");
}
}
interface ExtendedTestStore extends AltJS.AltStore<AltTestState> {
fakeLoad():string;
split():Array<string>;
}
var testStore = <ExtendedTestStore>alt.createStore<AltTestState>(TestStore);
function testCallback(state:AltTestState) {
console.log(state);
}
//Listen allows a typed state callback
testStore.listen(testCallback);
testStore.unlisten(testCallback);
//State generic passes to derived store
var name:string = testStore.getState().hello;
var nameChars:Array<string> = testStore.split();
generatedActions.notifyTest("types");
explicitActions.doTest("more types");
export var result = testStore.getState();
+167
View File
@@ -0,0 +1,167 @@
// Type definitions for Alt 0.16.10
// Project: https://github.com/goatslacker/alt
// Definitions by: Michael Shearer <https://github.com/Shearerbeard>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path="../react/react.d.ts"/>
///<reference path="../es6-promise/es6-promise.d.ts" />
declare module AltJS {
interface StoreReduce {
action:any;
data: any;
}
export interface StoreModel<S> {
//Actions
bindAction?( action:Action<any>, handler:ActionHandler):void;
bindActions?(actions:ActionsClass):void;
//Methods/Listeners
exportPublicMethods?(exportConfig:any):void;
bindListeners?(config:{[methodName:string]:Action<any> | Actions}):void;
exportAsync?(source:Source):void;
registerAsync?(datasource:Source):void;
//state
setState?(state:S):void;
setState?(stateFn:(currentState:S, nextState:S) => S):void;
getState?():S;
waitFor?(store:AltStore<any>):void;
//events
onSerialize?(fn:(data:any) => any):void;
onDeserialize?(fn:(data:any) => any):void;
on?(event:AltJS.lifeCycleEvents, callback:() => any):void;
emitChange?():void;
waitFor?(storeOrStores:AltStore<any> | Array<AltStore<any>>):void;
otherwise?(data:any, action:AltJS.Action<any>):void;
observe?(alt:Alt):any;
reduce?(state:any, config:StoreReduce):Object;
preventDefault?():void;
afterEach?(payload:Object, state:Object):void;
beforeEach?(payload:Object, state:Object):void;
// TODO: Embed dispatcher interface in def
dispatcher?:any;
//instance
getInstance?():AltJS.AltStore<S>;
alt?:Alt;
displayName?:string;
}
export type Source = {[name:string]: () => SourceModel<any>};
export interface SourceModel<S> {
local(state:any):any;
remote(state:any):Promise<S>;
shouldFetch?(fetchFn:(...args:Array<any>) => boolean):void;
loading?:(args:any) => void;
success?:(state:S) => void;
error?:(args:any) => void;
interceptResponse?(response:any, action:Action<any>, ...args:Array<any>):any;
}
export interface AltStore<S> {
getState():S;
listen(handler:(state:S) => any):() => void;
unlisten(handler:(state:S) => any):void;
emitChange():void;
}
export enum lifeCycleEvents {
bootstrap,
snapshot,
init,
rollback,
error
}
export type Actions = {[action:string]:Action<any>};
export interface Action<T> {
( args:T):void;
defer(data:any):void;
}
export interface ActionsClass {
generateActions?( ...action:Array<string>):void;
dispatch( ...payload:Array<any>):void;
actions?:Actions;
}
type StateTransform = (store:StoreModel<any>) => AltJS.AltStore<any>;
interface AltConfig {
dispatcher?:any;
serialize?:(serializeFn:(data:Object) => string) => void;
deserialize?:(deserializeFn:(serialData:string) => Object) => void;
storeTransforms?:Array<StateTransform>;
batchingFunction?:(callback:( ...data:Array<any>) => any) => void;
}
class Alt {
constructor(config?:AltConfig);
actions:Actions;
bootstrap(jsonData:string):void;
takeSnapshot( ...storeNames:Array<string>):string;
flush():Object;
recycle( ...stores:Array<AltJS.AltStore<any>>):void;
rollback():void;
dispatch(action?:AltJS.Action<any>, data?:Object, details?:any):void;
//Actions methods
addActions(actionsName:string, ActionsClass: ActionsClassConstructor):void;
createActions<T>(ActionsClass: ActionsClassConstructor, exportObj?: Object):T;
createActions<T>(ActionsClass: ActionsClassConstructor, exportObj?: Object, ...constructorArgs:Array<any>):T;
generateActions<T>( ...actions:Array<string>):T;
getActions(actionsName:string):AltJS.Actions;
//Stores methods
addStore(name:string, store:StoreModel<any>, saveStore?:boolean):void;
createStore<S>(store:StoreModel<S>, name?:string):AltJS.AltStore<S>;
getStore(name:string):AltJS.AltStore<any>;
}
export interface AltFactory {
new(config?:AltConfig):Alt;
}
type ActionsClassConstructor = new (alt:Alt) => AltJS.ActionsClass;
type ActionHandler = ( ...data:Array<any>) => any;
type ExportConfig = {[key:string]:(...args:Array<any>) => any};
}
declare module "alt/utils/chromeDebug" {
function chromeDebug(alt:AltJS.Alt):void;
export = chromeDebug;
}
declare module "alt/AltContainer" {
import React = require("react");
interface ContainerProps {
store?:AltJS.AltStore<any>;
stores?:Array<AltJS.AltStore<any>>;
inject?:{[key:string]:any};
actions?:{[key:string]:Object};
render?:(...props:Array<any>) => React.ReactElement<any>;
flux?:AltJS.Alt;
transform?:(store:AltJS.AltStore<any>, actions:any) => any;
shouldComponentUpdate?:(props:any) => boolean;
component?:React.Component<any, any>;
}
type AltContainer = React.ReactElement<ContainerProps>;
var AltContainer:React.ComponentClass<ContainerProps>;
export = AltContainer;
}
declare module "alt" {
var alt:AltJS.AltFactory;
export = alt;
}
+2 -1
View File
@@ -29,6 +29,7 @@ interface amplifyDecoders {
interface amplifyAjaxSettings extends JQueryAjaxSettings {
cache?: any;
dataMap?: {} | ((data: any) => {});
decoder?: any /* string or amplifyDecoder */;
}
@@ -50,7 +51,7 @@ interface amplifyRequest {
* success (optional): Function to invoke on success.
* error (optional): Function to invoke on error.
*/
(settings: amplifyRequestSettings);
(settings: amplifyRequestSettings): any;
/***
* Define a resource.
+21
View File
@@ -0,0 +1,21 @@
/// <reference path="amqplib.d.ts" />
import amqp = require("amqplib");
var msg = "Hello World";
amqp.connect("amqp://localhost")
.then(connection => {
return connection.createChannel()
.tap(channel => channel.checkQueue("myQueue"))
.then(channel => channel.sendToQueue("myQueue", new Buffer(msg)))
.ensure(() => connection.close());
});
amqp.connect("amqp://localhost")
.then(connection => {
return connection.createChannel()
.tap(channel => channel.checkQueue("myQueue"))
.then(channel => channel.consume("myQueue", newMsg => console.log("New Message: " + newMsg.content.toString())))
.ensure(() => connection.close());
});
+144
View File
@@ -0,0 +1,144 @@
// Type definitions for amqplib 0.3.x
// Project: https://github.com/squaremo/amqp.node
// Definitions by: Michael Nahkies <https://github.com/mnahkies>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../when/when.d.ts" />
/// <reference path="../node/node.d.ts" />
declare module "amqplib" {
import events = require("events");
import when = require("when");
interface Connection extends events.EventEmitter {
close(): when.Promise<void>;
createChannel(): when.Promise<Channel>;
createConfirmChannel(): when.Promise<Channel>;
}
module Replies {
interface Empty {
}
interface AssertQueue {
queue: string;
messageCount: number;
consumerCount: number;
}
interface DeleteQueue {
messageCount: number;
}
interface AssertExchange {
exchange: string;
}
interface Consume {
consumerTag: string;
}
}
module Options {
interface AssertQueue {
exclusive?: boolean;
durable?: boolean;
autoDelete?: boolean;
arguments?: any;
messageTtl?: number;
expires?: number;
deadLetterExchange?: string;
maxLength?: number;
}
interface DeleteQueue {
ifUnused?: boolean;
ifEmpty?: boolean;
}
interface AssertExchange {
durable?: boolean;
internal?: boolean;
autoDelete?: boolean;
alternateExchange?: string;
arguments?: any;
}
interface DeleteExchange {
ifUnused?: boolean;
}
interface Publish {
expiration?: string;
userId?: string;
CC?: string | string[];
mandatory?: boolean;
persistent?: boolean;
deliveryMode?: boolean | number;
BCC?: string | string[];
contentType?: string;
contentEncoding?: string;
headers?: Object;
priority?: number;
correlationId?: string;
replyTo?: string;
messageId?: string;
timestamp?: number;
type?: string;
appId?: string;
}
interface Consume {
consumerTag?: string;
noLocal?: boolean;
noAck?: boolean;
exclusive?: boolean;
priority?: number;
arguments?: Object;
}
interface Get {
noAck?: boolean;
}
}
interface Message {
content: Buffer;
fields: Object;
properties: Object;
}
interface Channel extends events.EventEmitter {
close(): when.Promise<void>;
assertQueue(queue: string, options?: Options.AssertQueue): when.Promise<Replies.AssertQueue>;
checkQueue(queue: string): when.Promise<Replies.AssertQueue>;
deleteQueue(queue: string, options?: Options.DeleteQueue): when.Promise<Replies.DeleteQueue>;
purgeQueue(queue: string): when.Promise<Replies.DeleteQueue>;
bindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
unbindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
assertExchange(exchange: string, type: string, options?: Options.AssertExchange): when.Promise<Replies.AssertExchange>;
checkExchange(exchange: string): when.Promise<Replies.Empty>;
deleteExchange(exchange: string, options?: Options.DeleteExchange): when.Promise<Replies.Empty>;
bindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
unbindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean;
consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): when.Promise<Replies.Consume>;
cancel(consumerTag: string): when.Promise<Replies.Empty>;
get(queue: string, options?: Options.Get): when.Promise<Message | boolean>;
ack(message: Message, allUpTo?: boolean): void;
ackAll(): void;
nack(message: Message, allUpTo?: boolean, requeue?: boolean): void;
nackAll(requeue?: boolean): void;
reject(message: Message, requeue?: boolean): void;
prefetch(count: number, global?: boolean): when.Promise<Replies.Empty>;
recover(): when.Promise<Replies.Empty>;
}
function connect(url: string, socketOptions?: any): when.Promise<Connection>;
}
+2 -26
View File
@@ -3,30 +3,6 @@
// Definitions by: John Reilly <https://github.com/johnnyreilly>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
/// <reference path="../ng-file-upload/ng-file-upload.d.ts" />
declare module angular.angularFileUpload {
interface IUploadService {
http<T>(config: IRequestConfig): IUploadPromise<T>;
upload<T>(config: IFileUploadConfig): IUploadPromise<T>;
}
interface IUploadPromise<T> extends IHttpPromise<T> {
abort(): IUploadPromise<T>;
progress(callback: IHttpPromiseCallback<T>): IUploadPromise<T>;
xhr(callback: IHttpPromiseCallback<T>): IUploadPromise<T>;
}
interface IFileUploadConfig extends IRequestConfig {
file: File;
fileName?: string;
}
interface IFileProgressEvent extends ProgressEvent {
config: IFileUploadConfig;
}
}
// THIS FILE WILL REMOVE IF angular-file-upload.d.ts incoming.
+108
View File
@@ -0,0 +1,108 @@
/// <reference path="angular-formly.d.ts" />
var app = angular.module('app', ['formly']);
interface IScope extends ng.IScope {
to: { label: string; }
}
class FormConfig {
constructor(formlyConfig: AngularFormly.IFormlyConfig, formlyValidationMessages: AngularFormly.IValidationMessages) {
formlyConfig.setWrapper({
name: 'validation',
types: ['input', 'customInput'],
templateUrl: 'my-messages.html'
});
formlyValidationMessages.addStringMessage('required', 'This field is required');
formlyConfig.setType({
name: 'customInput',
extends: 'input'
});
}
}
class AppController {
fields: AngularFormly.IFieldConfigurationObject[];
constructor() {
var vm = this;
vm.fields = [
{
key: 'firstName',
type: 'customInput',
templateOptions: {
required: true,
label: 'First Name',
foo: 'hi'
}
},
{
key: 'email',
type: 'input',
templateOptions: {
label: 'Email',
required: true,
type: 'email',
maxlength: 10,
minlength: 6,
placeholder: 'example@example.com'
}
},
{
key: 'ip',
type: 'input',
validators: {
ipAddress: {
expression: function(viewValue, modelValue) {
var value = modelValue || viewValue;
return /(\d{1,3}\.){3}\d{1,3}/.test(value);
},
message: '$viewValue + " is not a valid IP Address"'
}
},
templateOptions: {
label: 'IP Address',
required: true,
type: 'text',
placeholder: '127.0.0.1',
},
validation: {
messages: {
required: function($viewValue: any, $modelValue: any, scope: AngularFormly.ITemplateScope) {
return scope.to.label + ' is required'
}
}
}
},
{
key: 'mac',
type: 'input',
templateOptions: {
label: 'MAC Address',
required: true,
placeholder: '49-8A-BD-4E-00-1D',
pattern: '([0-9A-F]{2}[:-]){5}([0-9A-F]{2})'
}
},
{
type: 'checkbox',
key: 'checked',
templateOptions: {
label: 'Check this'
}
},
{
key: 'checked2',
type: 'checkbox',
wrapper: null,
templateOptions: {
label: 'no wrapper here...'
}
}
]
}
}
app.controller("AppController", AppController);
+574
View File
@@ -0,0 +1,574 @@
// Type definitions for angular-formly 6.18.0
// Project: https://github.com/formly-js/angular-formly
// Definitions by: Scott Hatcher <https://github.com/scatcher>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module 'AngularFormly' {
export = AngularFormly;
}
declare module AngularFormly {
interface IFieldGroup {
data?: Object;
className?: string;
elementAttributes?: { [key: string]: string };
fieldGroup: IFieldConfigurationObject[];
form?: Object;
hide?: boolean;
hideExpression?: string | IExpresssionFunction;
key?: string | number;
model?: string | Object;
options?: IFormOptionsAPI
}
interface IFormOptionsAPI {
data?: Object;
fieldTransform?: Function;
formState?: Object;
removeChromeAutoComplete?: boolean;
resetModel?: Function;
templateManipulators?: ITemplateManipulators;
updateInitialValue?: Function;
wrapper?: string | string[];
}
/**
* see http://docs.angular-formly.com/docs/formly-expressions#expressionproperties-validators--messages
*/
interface IExpresssionFunction {
($viewValue: any, $modelValue: any, scope: ITemplateScope): any;
}
interface IModelOptions {
updateOn?: string;
debounce?: number;
allowInvalid?: boolean;
getterSetter?: string;
timezone?: string;
}
interface ITemplateManipulator {
(template: string | HTMLElement, options: Object, scope: ITemplateScope): string | HTMLElement;
}
interface ITemplateManipulators {
preWrapper?: ITemplateManipulator[];
postWrapper?: ITemplateManipulator[];
}
/**
* see http://docs.angular-formly.com/docs/ngmodelattrstemplatemanipulator
*/
interface ITemplateOptions {
// both attribute or regular attribute
disabled?: boolean;
maxlength?: number;
minlength?: number;
pattern?: string;
required?: boolean;
//attribute only
max?: number;
min?: number;
placeholder?: number | string;
tabindex?: number;
type?: string;
//expression types
onBlur?: string;
onChange?: string;
onClick?: string;
onFocus?: string;
onKeydown?: string;
onKeypress?: string;
onKeyup?: string;
//Bootstrap types
label?: string;
description?: string;
[key: string]: any;
}
/**
* see http://docs.angular-formly.com/docs/field-configuration-object#validators-object
*/
interface IValidator {
expression: string | IExpresssionFunction;
message?: string | IExpresssionFunction;
}
/**
* An object which has at least two properties called expression and listener. The watch.expression
* is added to the formly-form directive's scope (to allow it to run even when hide is true). You
* can specify a type ($watchCollection or $watchGroup) via the watcher.type property (defaults to
* $watch) and whether you want it to be a deep watch via the watcher.deep property (defaults to false).
*
* see http://docs.angular-formly.com/docs/field-configuration-object#watcher-objectarray-of-watches
*/
interface IWatcher {
deep?: boolean; //Defaults to false
expression?: string | { (field: string, scope: ITemplateScope): boolean };
listener: (field: string, newValue: any, oldValue: any, scope: ITemplateScope, stopWatching: Function) => void;
type?: string; //Defaults to $watch but can be set to $watchCollection or $watchGroup
}
// see http://docs.angular-formly.com/docs/field-configuration-object
interface IFieldConfigurationObject {
/**
* Added in 6.18.0
*
* Demo
* see http://angular-formly.com/#/example/other/unique-value-async-validation
*/
asyncValidators?: {
[key: string]: string | IExpresssionFunction | IValidator;
}
/**
* This is a great way to add custom behavior to a specific field. It is injectable with the $scope of the
* field, and anything else you have in your injector.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#controller-controller-name-as-string--controller-f
*/
controller?: string | Function;
/**
* This is reserved for the developer. You have our guarantee to be able to use this and not worry about
* future versions of formly overriding your usage and preventing you from upgrading :-)
*
* see http://docs.angular-formly.com/docs/field-configuration-object#data-object
*/
data?: Object;
/**
* Use defaultValue to initialize it the model. If this is provided and the value of the
* model at compile-time is undefined, then the value of the model will be assigned to defaultValue.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#defaultvalue-any
*/
defaultValue?: any;
/**
* You can specify your own class that will be applied to the formly-field directive (or ng-form of
* a fieldGroup).
*
* see http://docs.angular-formly.com/docs/field-configuration-object#classname-string
*/
className?: string;
elementAttributes?: string;
/**
* An object where the key is a property to be set on the main field config and the value is an
* expression used to assign that property. The value is a formly expressions. The returned value is
* wrapped in $q.when so you can return a promise from your function :-)
*
* see http://docs.angular-formly.com/docs/field-configuration-object#expressionproperties-object
*/
expressionProperties?: {
[key: string]: string | IExpresssionFunction | IValidator;
}
/**
* Uses ng-if. Whether to hide the field. Defaults to false. If you wish this to be conditional, use
* hideExpression. See below.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#hide-boolean
*/
hide?: boolean
/**
* This is similar to expressionProperties with a slight difference. You should (hopefully) never
* notice the difference with the most common use case. This is available due to limitations with
* expressionProperties and ng-if not working together very nicely.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#hideexpression-string--function
*/
hideExpression?: string | IExpresssionFunction;
/**
* This allows you to specify the id of your field (which will be used for its name as well unless
* a name is provided). Note, you can also override the id generation code using the formlyConfig
* extra called getFieldId.
*
* AVOID THIS
* If you don't have to do this, don't. Specifying IDs makes it harder to re-use things and it's
* just extra work. Part of the beauty that angular-formly provides is the fact that you don't need
* to concern yourself with making sure that this is unique.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#id-string
*/
id?: string;
initialValue?: any;
/**
* Can be set instead of type or template to use a custom html template form field. Works
* just like a directive templateUrl and uses the $templateCache
*
* see http://docs.angular-formly.com/docs/field-configuration-object#key-string
*/
key?: string | number;
/**
* This allows you to specify a link function. It is invoked after your template has finished compiling.
* You are passed the normal arguments for a normal link function.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#link-link-function
*/
link?: ng.IDirectiveLinkFn;
/**
* By default, the model passed to the formly-field directive is the same as the model passed to the
* formly-form. However, if the field has a model specified, then it is used for that field (and that
* field only). In addition, a deep watch is added to the formly-field directive's scope to run the
* expressionProperties when the specified model changes.
*
* Note, the formly-form directive will allow you to specify a string which is an (almost) formly
* expression which allows you to define the model as relative to the scope of the form.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#model-object--string
*/
model?: Object | string;
/**
* Allows you to take advantage of ng-model-options directive. Formly's built-in templateManipulator (see
* below) will add this attribute to your ng-model element automatically if this property exists. Note,
* if you use the getter/setter option, formly's templateManipulator will change the value of ng-model
* to options.value which is a getterSetter that formly adds to field options.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#modeloptions
*/
modelOptions?: IModelOptions;
/**
* If you wish to, you can specify a specific name for your ng-model. This is useful if you're posting
* the form to a server using techniques of yester-year.
*
* AVOID THIS
* If you don't have to do this, don't. It's just extra work. Part of the beauty that angular-formly
* provides is the fact that you don't need to concern yourself with stuff like this.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#name-string
*/
name?: string;
/**
* This is used by ngModelAttrsTemplateManipulator to automatically add attributes to the ng-model element
* of field templates. You will likely not use this often. This object is a little complex, but extremely
* powerful. It's best to explain this api via an example. For more information, see the guide on ngModelAttrs.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#ngmodelattrs-object
*/
ngModelAttrs?: {
attribute?: any;
bound?: any;
expression?: any;
value?: any;
};
/**
* Used to tell angular-formly to not attempt to add the formControl property to your object. This is useful
* for things like validation, but not necessary if your "field" doesn't use ng-model (if it's just a horizontal
* line for example). Defaults to undefined.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#noformcontrol-boolean
*/
noFormControl?: boolean;
/**
* Allows you to specify extra types to get options from. Duplicate options are overridden in later priority
* (index 1 will override index 0 properties). Also, these are applied after the type's defaultOptions and
* hence will override any duplicates of those properties as well.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#optionstypes-string--array-of-strings
*/
optionsTypes?: string | string[];
/**
* Can be set instead of type or templateUrl to use a custom html
* template form field. Recommended to be used with one-liners mostly
* (like a directive), or if you're using webpack with the ability to require templates :-)
*
* If a function is passed, it is invoked with the field configuration object and can return
* either a string for the template or a promise that resolves to a string.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#template-string--function
*/
template?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise<string> };
/**
* Allows you to specify custom template manipulators for this specific field. (use defaultOptions in a
* type configuration if you want it to apply to all fields of a certain type).
*
* see http://docs.angular-formly.com/docs/field-configuration-object#templatemanipulator-object-of-arrays-of-functions
*/
templateManipulators?: ITemplateManipulators;
/**
* This is reserved for the templates. Any template-specific options go in here. Look at your specific
* template implementation to know the options required for this.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#templateoptions-object
*/
templateOptions?: ITemplateOptions;
/**
* Can be set instead of type or template to use a custom html template form field. Works
* just like a directive templateUrl and uses the $templateCache
*
* see http://docs.angular-formly.com/docs/field-configuration-object#templateurl-string--function
*/
templateUrl?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise<string> };
/**
* The type of field to be rendered. This is the recommended method
* for defining fields. Types must be pre-defined using formlyConfig.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#type-string
*/
type?: string;
/**
* An object with a few useful properties mostly handy when used in combination with ng-messages
*/
validation?: {
/**
* This is set by angular-formly. This is a boolean indicating whether an error message should be shown. Because
* you generally only want to show error messages when the user has interacted with a specific field, this value
* is set to true based on this rule: field invalid && (field touched || validation.show) (with slight difference
* for pre-angular 1.3 because it doesn't have touched support).
*/
errorExistsAndShouldBeVisible?: boolean;
/**
* A map of Formly Expressions mapped to message names. This is really useful when you're using ng-messages
* like in this example.
*/
messages?: {
[key: string]: IExpresssionFunction | string;
}
/**
* A boolean you as the developer can set to specify to force options.validation.errorExistsAndShouldBeVisible
* to be set to true when there are $errors. This is useful when you're trying to call the user's attention to
* some fields for some reason.
*/
show?: boolean;
}
/**
* An object where the keys are the name of the validator and the values are Formly Expressions;
*
* Async Validation
* All function validators can return true/false/Promise. A validator passes if it returns true or a promise
* that is resolved. A validator fails if it returns false or a promise that is rejected.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#validators-object
*/
validators?: {
[key: string]: string | IExpresssionFunction | IValidator;
}
/**
* This is a getter/setter function for the value that your field is representing. Useful when using getterSetter: true
* in the modelOptions (in fact, if you don't disable the ngModelAttrsTemplateManipulator that comes built-in with formly,
* it will automagically change your field's ng-model attribute to use options.value.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#value-gettersetter-function
*/
value?(): any; //Getter
value?(val: any): void; //Setter
/**
* An object which has at least two properties called expression and listener. The watch.expression is added
* to the formly-form directive's scope (to allow it to run even when hide is true). You can specify a type
* ($watchCollection or $watchGroup) via the watcher.type property (defaults to $watch) and whether you want
* it to be a deep watch via the watcher.deep property (defaults to false).
*
* see http://docs.angular-formly.com/docs/field-configuration-object#watcher-objectarray-of-watches
*/
watcher?: IWatcher | IWatcher[];
/**
* This makes reference to setWrapper in formlyConfig. It is expected to be the name of the wrapper. If
* given an array, the formly field template will be wrapped by the first wrapper, then the second, then
* the third, etc. You can also specify these as part of a type (which is the recommended approach).
* Specifying this property will override the wrappers for the type for this field.
*
* http://docs.angular-formly.com/docs/field-configuration-object#wrapper-string--array-of-strings
*/
wrapper?: string | string[];
//ALL PROPERTIES BELOW ARE ADDED (So you should not be setting them yourself.)
/**
* This is the NgModelController for the field. It provides you with awesome stuff like $errors :-)
*
* see http://docs.angular-formly.com/docs/field-configuration-object#formcontrol-ngmodelcontroller
*/
formControl?: ng.IFormController | ng.IFormController[];
/**
* Will reset the field's model and the field control to the last initialValue. This is used by the
* formly-form's options.resetModel function.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#resetmodel-function
*/
resetModel?: () => void;
/**
* It is not likely that you'll ever want to invoke this function. It simply runs the expressionProperties expressions.
* It is used internally and you shouldn't have to use it, but you can if you want to, and any breaking changes to the
* way it works will result in a major version change, so you can rely on its api.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#runexpressions-function
*/
runExpressions?: () => void;
/**
* Will reset the field's initialValue to the current state of the model. Useful if you load the model asynchronously.
* Invoke this when the model gets set. This is used by the formly-form's options.updateInitialValue function.
*
* see http://docs.angular-formly.com/docs/field-configuration-object#updateinitialvalue-function
*/
updateInitialValue?: () => void;
}
/**
*
*
* see http://docs.angular-formly.com/docs/custom-templates#section-formlyconfig-settype-options
*/
interface ITypeOptions {
apiCheck?: { [key: string]: Function };
apiCheckFunction?: string; //'throw' or 'warn
apiCheckInstance?: any;
apiCheckOptions?: Object;
defaultOptions?: IFieldConfigurationObject | Function;
controller?: Function | string | any[];
data?: Object;
extends?: string;
link?: ng.IDirectiveLinkFn;
overwriteOk?: boolean;
name: string;
template?: Function | string;
templateUrl?: Function | string;
validateOptions?: Function;
wrapper?: string | string[];
}
interface IWrapperOptions {
apiCheck?: { [key: string]: Function };
apiCheckFunction?: string; //'throw' or 'warn
apiCheckInstance?: any;
apiCheckOptions?: Object;
overwriteOk?: boolean;
name?: string;
template?: string;
templateUrl?: string;
types?: string[];
validateOptions?: Function;
}
interface IFormlyConfig {
setType(typeOptions: ITypeOptions): void;
setWrapper(wrapperOptions: IWrapperOptions): void;
}
interface ITemplateScopeOptions {
formControl: ng.IFormController | ng.IFormController[];
templateOptions: ITemplateOptions;
validation: Object;
}
/**
* see http://docs.angular-formly.com/docs/custom-templates#templates-scope
*/
interface ITemplateScope {
options: ITemplateScopeOptions;
//Shortcut to options.formControl
fc: ng.IFormController | ng.IFormController[];
//all the fields for the form
fields: IFieldConfigurationObject[];
//the form controller the field is in
form: any;
//The object passed as options.formState to the formly-form directive. Use this to share state between fields.
formState: Object;
//The id of the field. You shouldn't have to use this.
id: string;
//The index of the field the form is on (in ng-repeat)
index: number;
//the model of the form (or the model specified by the field if it was specified).
model: Object | string;
//Shortcut to options.validation.errorExistsAndShouldBeVisible
showError: boolean;
//Shortcut to options.templateOptions
to: ITemplateOptions;
}
/**
* see http://docs.angular-formly.com/docs/formlyvalidationmessages#addtemplateoptionvaluemessage
*/
interface IValidationMessages {
addTemplateOptionValueMessage(name: string, prop: string, prefix: string, suffix: string, alternate: string): void;
addStringMessage(name: string, string: string): void;
messages: { [key: string]: ($viewValue: any, $modelValue: any, scope: ITemplateScope) => string };
}
}
+1 -1
View File
@@ -6,7 +6,7 @@
/// <reference path='../angularjs/angular.d.ts' />
declare module angular.local.storage {
interface ILocalStorageServiceProvider extends IServiceProvider {
interface ILocalStorageServiceProvider extends angular.IServiceProvider {
/**
* Setter for the prefix
* You should set a prefix to avoid overwriting any local storage variables from the rest of your app
@@ -124,3 +124,18 @@ $localForage.iterate(function (value, key) {
}
}).then(function (data) {
});
$localForage.bind($rootScope, 'key').then(function(data) {
});
$localForage.bind($rootScope, {key: 'key'}).then(function(data) {
});
$localForage.bind($rootScope, {key: 'key', defaultValue: 'defaultValue'}).then(function(data) {
});
$localForage.bind($rootScope, {key: 'key', scopeKey: 'scopeKey'}).then(function(data) {
});
$localForage.bind($rootScope, {key: 'key', name: 'name'}).then(function(data) {
});
+5 -5
View File
@@ -46,14 +46,14 @@ declare module angular.localForage {
iterate<T>(iteratorCallback:(value:string | number, key:string)=>T):angular.IPromise<T>;
bind($scope:ng.IScope, key:string):void;
bind($scope:ng.IScope, key:string):angular.IPromise<any>;
bind($scope:ng.IScope, config:{
key:string;
defaultValue:any;
scopeKey:string;
name:string;
}):void;
defaultValue?:any;
scopeKey?:string;
name?:string;
}):angular.IPromise<any>;
unbind($scope:ng.IScope, key:string, scopeKey?:string):void;
+204
View File
@@ -0,0 +1,204 @@
// Type definitions for Angular Material 0.9.0-rc1+ (angular.material module)
// Project: https://github.com/angular/material
// Definitions by: Matt Traynham <https://github.com/mtraynham>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.material {
interface MDBottomSheetOptions {
templateUrl?: string;
template?: string;
scope?: angular.IScope; // default: new child scope
preserveScope?: boolean; // default: false
controller?: string|Function;
locals?: {[index: string]: any};
targetEvent?: MouseEvent;
resolve?: {[index: string]: angular.IPromise<any>}
controllerAs?: string;
parent?: string|Element|JQuery; // default: root node
disableParentScroll?: boolean; // default: true
}
interface MDBottomSheetService {
show(options: MDBottomSheetOptions): angular.IPromise<any>;
hide(response?: any): void;
cancel(response?: any): void;
}
interface MDPresetDialog<T> {
title(title: string): T;
content(content: string): T;
ok(ok: string): T;
theme(theme: string): T;
}
interface MDAlertDialog extends MDPresetDialog<MDAlertDialog> {
}
interface MDConfirmDialog extends MDPresetDialog<MDConfirmDialog> {
cancel(cancel: string): MDConfirmDialog;
}
interface MDDialogOptions {
templateUrl?: string;
template?: string;
targetEvent?: MouseEvent;
scope?: angular.IScope; // default: new child scope
preserveScope?: boolean; // default: false
disableParentScroll?: boolean; // default: true
hasBackdrop?: boolean // default: true
clickOutsideToClose?: boolean; // default: false
escapeToClose?: boolean; // default: true
focusOnOpen?: boolean; // default: true
controller?: string|Function;
locals?: {[index: string]: any};
bindToController?: boolean; // default: false
resolve?: {[index: string]: angular.IPromise<any>}
controllerAs?: string;
parent?: string|Element|JQuery; // default: root node
onComplete?: Function;
}
interface MDDialogService {
show(dialog: MDDialogOptions|MDAlertDialog|MDConfirmDialog): angular.IPromise<any>;
confirm(): MDConfirmDialog;
alert(): MDAlertDialog;
hide(response?: any): void;
cancel(response?: any): void;
}
interface MDIcon {
(id: string): angular.IPromise<Element>; // id is a unique ID or URL
}
interface MDIconProvider {
icon(id: string, url: string, iconSize?: string): MDIconProvider; // iconSize default: '24px'
iconSet(id: string, url: string, iconSize?: string): MDIconProvider; // iconSize default: '24px'
defaultIconSet(url: string, iconSize?: string): MDIconProvider; // iconSize default: '24px'
defaultIconSize(iconSize: string): MDIconProvider; // default: '24px'
}
interface MDMedia {
(media: string): boolean;
}
interface MDSidenavObject {
toggle(): angular.IPromise<void>;
open(): angular.IPromise<void>;
close(): angular.IPromise<void>;
isOpen(): boolean;
isLockedOpen(): boolean;
}
interface MDSidenavService {
(component: string): MDSidenavObject;
}
interface MDToastPreset<T> {
content(content: string): T;
action(action: string): T;
highlightAction(highlightAction: boolean): T;
capsule(capsule: boolean): T;
theme(theme: string): T;
hideDelay(delay: number): T;
position(position: string): T;
}
interface MDSimpleToastPreset extends MDToastPreset<MDSimpleToastPreset> {
}
interface MDToastOptions {
templateUrl?: string;
template?: string;
scope?: angular.IScope; // default: new child scope
preserveScope?: boolean; // default: false
hideDelay?: number; // default (ms): 3000
position?: string; // any combination of 'bottom'/'left'/'top'/'right'/'fit'; default: 'bottom left'
controller?: string|Function;
locals?: {[index: string]: any};
bindToController?: boolean; // default: false
resolve?: {[index: string]: angular.IPromise<any>}
controllerAs?: string;
parent?: string|Element|JQuery; // default: root node
}
interface MDToastService {
show(optionsOrPreset: MDToastOptions|MDToastPreset<any>): angular.IPromise<any>;
showSimple(): angular.IPromise<any>;
simple(): MDSimpleToastPreset;
build(): MDToastPreset<any>;
updateContent(): void;
hide(response?: any): void;
cancel(response?: any): void;
}
interface MDPalette {
0?: string;
50?: string;
100?: string;
200?: string;
300?: string;
400?: string;
500?: string;
600?: string;
700?: string;
800?: string;
900?: string;
A100?: string;
A200?: string;
A400?: string;
A700?: string;
contrastDefaultColor?: string;
contrastDarkColors?: string|string[];
contrastLightColors?: string|string[];
}
interface MDThemeHues {
default?: string;
'hue-1'?: string;
'hue-2'?: string;
'hue-3'?: string;
}
interface MDThemePalette {
name: string;
hues: MDThemeHues;
}
interface MDThemeColors {
accent: MDThemePalette;
background: MDThemePalette;
primary: MDThemePalette;
warn: MDThemePalette;
}
interface MDThemeGrayScalePalette {
1: string;
2: string;
3: string;
4: string;
name: string;
}
interface MDTheme {
name: string;
isDark: boolean;
colors: MDThemeColors;
foregroundPalette: MDThemeGrayScalePalette;
foregroundShadow: string;
accentPalette(name: string, hues?: MDThemeHues): MDTheme;
primaryPalette(name: string, hues?: MDThemeHues): MDTheme;
warnPalette(name: string, hues?: MDThemeHues): MDTheme;
backgroundPalette(name: string, hues?: MDThemeHues): MDTheme;
dark(isDark?: boolean): MDTheme;
}
interface MDThemingProvider {
theme(name: string, inheritFrom?: string): MDTheme;
definePalette(name: string, palette: MDPalette): MDThemingProvider;
extendPalette(name: string, palette: MDPalette): MDPalette;
setDefaultTheme(theme: string): void;
alwaysWatchTheme(alwaysWatch: boolean): void;
}
}
+11 -11
View File
@@ -3,11 +3,11 @@
var myApp = angular.module('testModule', ['ngMaterial']);
myApp.config((
$mdThemingProvider: ng.material.MDThemingProvider,
$mdIconProvider: ng.material.MDIconProvider) => {
$mdThemingProvider: ng.material.IThemingProvider,
$mdIconProvider: ng.material.IIconProvider) => {
$mdThemingProvider.alwaysWatchTheme(true);
var neonRedMap: ng.material.MDPalette = $mdThemingProvider.extendPalette('red', {
var neonRedMap: ng.material.IPalette = $mdThemingProvider.extendPalette('red', {
'500': 'ff0000'
});
// Register the new color palette map with the name <code>neonRed</code>
@@ -27,7 +27,7 @@ myApp.config((
.icon('work:chair', 'my/app/chair.svg'); // Register icon in a specific set
});
myApp.controller('BottomSheetController', ($scope: ng.IScope, $mdBottomSheet: ng.material.MDBottomSheetService) => {
myApp.controller('BottomSheetController', ($scope: ng.IScope, $mdBottomSheet: ng.material.IBottomSheetService) => {
$scope['openBottomSheet'] = () => {
$mdBottomSheet.show({
template: '<md-bottom-sheet>Hello!</md-bottom-sheet>'
@@ -37,7 +37,7 @@ myApp.controller('BottomSheetController', ($scope: ng.IScope, $mdBottomSheet: ng
$scope['cancelBottomSheet'] = $mdBottomSheet.cancel.bind($mdBottomSheet, 'cancel');
});
myApp.controller('DialogController', ($scope: ng.IScope, $mdDialog: ng.material.MDDialogService) => {
myApp.controller('DialogController', ($scope: ng.IScope, $mdDialog: ng.material.IDialogService) => {
$scope['openDialog'] = () => {
$mdDialog.show({
template: '<md-dialog>Hello!</md-dialog>'
@@ -55,8 +55,8 @@ myApp.controller('DialogController', ($scope: ng.IScope, $mdDialog: ng.material.
class IconDirective implements ng.IDirective {
private $mdIcon: ng.material.MDIcon;
constructor($mdIcon: ng.material.MDIcon) {
private $mdIcon: ng.material.IIcon;
constructor($mdIcon: ng.material.IIcon) {
this.$mdIcon = $mdIcon;
}
@@ -69,9 +69,9 @@ class IconDirective implements ng.IDirective {
});
}
}
myApp.directive('icon-directive', ($mdIcon: ng.material.MDIcon) => new IconDirective($mdIcon));
myApp.directive('icon-directive', ($mdIcon: ng.material.IIcon) => new IconDirective($mdIcon));
myApp.controller('MediaController', ($scope: ng.IScope, $mdMedia: ng.material.MDMedia) => {
myApp.controller('MediaController', ($scope: ng.IScope, $mdMedia: ng.material.IMedia) => {
$scope.$watch(() => $mdMedia('lg'), (big: boolean) => {
$scope['bigScreen'] = big;
});
@@ -80,7 +80,7 @@ myApp.controller('MediaController', ($scope: ng.IScope, $mdMedia: ng.material.MD
$scope['anotherCustom'] = $mdMedia('max-width: 300px');
});
myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.material.MDSidenavService) => {
myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.material.ISidenavService) => {
var componentId = 'left';
$scope['toggle'] = () => $mdSidenav(componentId).toggle();
$scope['open'] = () => $mdSidenav(componentId).open();
@@ -89,6 +89,6 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia
$scope['isLockedOpen'] = $mdSidenav(componentId).isLockedOpen();
});
myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.MDToastService) => {
myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService) => {
$scope['openToast'] = () => $mdToast.show($mdToast.simple().content('Hello!'));
});
+73 -53
View File
@@ -1,4 +1,4 @@
// Type definitions for Angular Material 0.9.0-rc1+ (angular.material module)
// Type definitions for Angular Material 0.10.1-rc1+ (angular.material module)
// Project: https://github.com/angular/material
// Definitions by: Matt Traynham <https://github.com/mtraynham>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -6,7 +6,7 @@
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.material {
interface MDBottomSheetOptions {
interface IBottomSheetOptions {
templateUrl?: string;
template?: string;
scope?: angular.IScope; // default: new child scope
@@ -20,27 +20,45 @@ declare module angular.material {
disableParentScroll?: boolean; // default: true
}
interface MDBottomSheetService {
show(options: MDBottomSheetOptions): angular.IPromise<any>;
interface IBottomSheetService {
show(options: IBottomSheetOptions): angular.IPromise<any>;
hide(response?: any): void;
cancel(response?: any): void;
}
interface MDPresetDialog<T> {
interface IPresetDialog<T> {
title(title: string): T;
content(content: string): T;
ok(ok: string): T;
theme(theme: string): T;
templateUrl(templateUrl?: string): T;
template(template?: string): T;
targetEvent(targetEvent?: MouseEvent): T;
scope(scope?: angular.IScope): T; // default: new child scope
preserveScope(preserveScope?: boolean): T; // default: false
disableParentScroll(disableParentScroll?: boolean): T; // default: true
hasBackdrop(hasBackdrop?: boolean): T; // default: true
clickOutsideToClose(clickOutsideToClose?: boolean): T; // default: false
escapeToClose(escapeToClose?: boolean): T; // default: true
focusOnOpen(focusOnOpen?: boolean): T; // default: true
controller(controller?: string|Function): T;
locals(locals?: {[index: string]: any}): T;
bindToController(bindToController?: boolean): T; // default: false
resolve(resolve?: {[index: string]: angular.IPromise<any>}): T;
controllerAs(controllerAs?: string): T;
parent(parent?: string|Element|JQuery): T; // default: root node
onComplete(onComplete?: Function): T;
ariaLabel(ariaLabel: string): T;
}
interface MDAlertDialog extends MDPresetDialog<MDAlertDialog> {
interface IAlertDialog extends IPresetDialog<IAlertDialog> {
}
interface MDConfirmDialog extends MDPresetDialog<MDConfirmDialog> {
cancel(cancel: string): MDConfirmDialog;
interface IConfirmDialog extends IPresetDialog<IConfirmDialog> {
cancel(cancel: string): IConfirmDialog;
}
interface MDDialogOptions {
interface IDialogOptions {
templateUrl?: string;
template?: string;
targetEvent?: MouseEvent;
@@ -60,30 +78,31 @@ declare module angular.material {
onComplete?: Function;
}
interface MDDialogService {
show(dialog: MDDialogOptions|MDAlertDialog|MDConfirmDialog): angular.IPromise<any>;
confirm(): MDConfirmDialog;
alert(): MDAlertDialog;
interface IDialogService {
show(dialog: IDialogOptions|IAlertDialog|IConfirmDialog): angular.IPromise<any>;
confirm(): IConfirmDialog;
alert(): IAlertDialog;
hide(response?: any): void;
cancel(response?: any): void;
}
interface MDIcon {
interface IIcon {
(id: string): angular.IPromise<Element>; // id is a unique ID or URL
}
interface MDIconProvider {
icon(id: string, url: string, iconSize?: string): MDIconProvider; // iconSize default: '24px'
iconSet(id: string, url: string, iconSize?: string): MDIconProvider; // iconSize default: '24px'
defaultIconSet(url: string, iconSize?: string): MDIconProvider; // iconSize default: '24px'
defaultIconSize(iconSize: string): MDIconProvider; // default: '24px'
interface IIconProvider {
icon(id: string, url: string, viewBoxSize?: number): IIconProvider; // viewBoxSize default: 24
iconSet(id: string, url: string, viewBoxSize?: number): IIconProvider; // viewBoxSize default: 24
defaultIconSet(url: string, viewBoxSize?: number): IIconProvider; // viewBoxSize default: 24
defaultViewBoxSize(viewBoxSize: number): IIconProvider; // default: 24
defaultFontSet(name: string): IIconProvider;
}
interface MDMedia {
interface IMedia {
(media: string): boolean;
}
interface MDSidenavObject {
interface ISidenavObject {
toggle(): angular.IPromise<void>;
open(): angular.IPromise<void>;
close(): angular.IPromise<void>;
@@ -91,11 +110,11 @@ declare module angular.material {
isLockedOpen(): boolean;
}
interface MDSidenavService {
(component: string): MDSidenavObject;
interface ISidenavService {
(component: string): ISidenavObject;
}
interface MDToastPreset<T> {
interface IToastPreset<T> {
content(content: string): T;
action(action: string): T;
highlightAction(highlightAction: boolean): T;
@@ -103,12 +122,13 @@ declare module angular.material {
theme(theme: string): T;
hideDelay(delay: number): T;
position(position: string): T;
parent(parent?: string|Element|JQuery): T; // default: root node
}
interface MDSimpleToastPreset extends MDToastPreset<MDSimpleToastPreset> {
interface ISimpleToastPreset extends IToastPreset<ISimpleToastPreset> {
}
interface MDToastOptions {
interface IToastOptions {
templateUrl?: string;
template?: string;
scope?: angular.IScope; // default: new child scope
@@ -123,17 +143,17 @@ declare module angular.material {
parent?: string|Element|JQuery; // default: root node
}
interface MDToastService {
show(optionsOrPreset: MDToastOptions|MDToastPreset<any>): angular.IPromise<any>;
showSimple(): angular.IPromise<any>;
simple(): MDSimpleToastPreset;
build(): MDToastPreset<any>;
interface IToastService {
show(optionsOrPreset: IToastOptions|IToastPreset<any>): angular.IPromise<any>;
showSimple(content: string): angular.IPromise<any>;
simple(): ISimpleToastPreset;
build(): IToastPreset<any>;
updateContent(): void;
hide(response?: any): void;
cancel(response?: any): void;
}
interface MDPalette {
interface IPalette {
0?: string;
50?: string;
100?: string;
@@ -154,26 +174,26 @@ declare module angular.material {
contrastLightColors?: string|string[];
}
interface MDThemeHues {
interface IThemeHues {
default?: string;
'hue-1'?: string;
'hue-2'?: string;
'hue-3'?: string;
}
interface MDThemePalette {
interface IThemePalette {
name: string;
hues: MDThemeHues;
hues: IThemeHues;
}
interface MDThemeColors {
accent: MDThemePalette;
background: MDThemePalette;
primary: MDThemePalette;
warn: MDThemePalette;
interface IThemeColors {
accent: IThemePalette;
background: IThemePalette;
primary: IThemePalette;
warn: IThemePalette;
}
interface MDThemeGrayScalePalette {
interface IThemeGrayScalePalette {
1: string;
2: string;
3: string;
@@ -181,23 +201,23 @@ declare module angular.material {
name: string;
}
interface MDTheme {
interface ITheme {
name: string;
isDark: boolean;
colors: MDThemeColors;
foregroundPalette: MDThemeGrayScalePalette;
colors: IThemeColors;
foregroundPalette: IThemeGrayScalePalette;
foregroundShadow: string;
accentPalette(name: string, hues?: MDThemeHues): MDTheme;
primaryPalette(name: string, hues?: MDThemeHues): MDTheme;
warnPalette(name: string, hues?: MDThemeHues): MDTheme;
backgroundPalette(name: string, hues?: MDThemeHues): MDTheme;
dark(isDark?: boolean): MDTheme;
accentPalette(name: string, hues?: IThemeHues): ITheme;
primaryPalette(name: string, hues?: IThemeHues): ITheme;
warnPalette(name: string, hues?: IThemeHues): ITheme;
backgroundPalette(name: string, hues?: IThemeHues): ITheme;
dark(isDark?: boolean): ITheme;
}
interface MDThemingProvider {
theme(name: string, inheritFrom?: string): MDTheme;
definePalette(name: string, palette: MDPalette): MDThemingProvider;
extendPalette(name: string, palette: MDPalette): MDPalette;
interface IThemingProvider {
theme(name: string, inheritFrom?: string): ITheme;
definePalette(name: string, palette: IPalette): IThemingProvider;
extendPalette(name: string, palette: IPalette): IPalette;
setDefaultTheme(theme: string): void;
alwaysWatchTheme(alwaysWatch: boolean): void;
}
@@ -0,0 +1,12 @@
/// <reference path="angular-notifications.d.ts" />
var myapp = angular.module("myapp", ["notifications"]);
myapp.controller("MyController", ["$scope", "notifications",
function ($scope:ng.IScope, notifications:angular.notifications.INotificationFactory) { // <-- Inject notifications
var userData = {'some': 'data', 'optional': true};
notifications.info("Something happened", "here is the content of what happened", userData);
}
]);
+82
View File
@@ -0,0 +1,82 @@
// Type definitions for angular-notifications
// Project: https://github.com/DerekRies/angular-notifications
// Definitions by: Tomasz Ducin <https://github.com/ducin/DefinitelyTyped>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.notifications {
interface IAnimation {
duration: number;
enabled: boolean;
}
interface ISettings {
info: IAnimation;
warning: IAnimation;
error: IAnimation;
success: IAnimation;
progress: IAnimation;
custom: IAnimation;
details: boolean;
localStorage: boolean;
html5Mode: boolean;
html5DefaultIcon: string;
}
interface INotification {
type: string;
image: string;
icon: string;
title: string;
content: string;
timestamp: string;
userData: string;
}
interface INotificationFactory extends angular.IModule {
/* ========== SETTINGS RELATED METHODS =============*/
disableHtml5Mode(): void;
disableType(notificationType: string): void;
enableHtml5Mode(): void;
enableType(notificationType: string): void;
getSettings(): ISettings;
toggleType(notificationType: string): void;
toggleHtml5Mode(): void;
requestHtml5ModePermissions(): boolean;
/* ============ QUERYING RELATED METHODS ============*/
getAll(): Array<INotification>;
getQueue(): Array<INotification>;
/* ============== NOTIFICATION METHODS ==============*/
info(title: string): INotification;
info(title: string, content: string): INotification;
info(title: string, content: string, userData: any): INotification;
error(title: string): INotification;
error(title: string, content: string): INotification;
error(title: string, content: string, userData: any): INotification;
success(title: string): INotification;
success(title: string, content: string): INotification;
success(title: string, content: string, userData: any): INotification;
warning(title: string): INotification;
warning(title: string, content: string): INotification;
warning(title: string, content: string, userData: any): INotification;
awesomeNotify(type: string, icon: string, title: string, content: string, userData: any): INotification;
notify(image: string, title: string, content: string, userData: any): INotification;
makeNotification(type: string, image: string, icon: string, title: string, content: string, userData: any): INotification;
/* ============ PERSISTENCE METHODS ============ */
save(): void;
restore(): void;
clear(): void;
}
}
@@ -0,0 +1,208 @@
/// <reference path="angular-odata-resources.d.ts" />
interface IMyResource extends OData.IResource<IMyResource> { };
interface IMyResourceClass extends OData.IResourceClass<IMyResource> { };
///////////////////////////////////////
// IActionDescriptor
///////////////////////////////////////
var actionDescriptor: OData.IActionDescriptor;
actionDescriptor.url = '/api/test-url/'
actionDescriptor.headers = { header: 'value' };
actionDescriptor.isArray = true;
actionDescriptor.method = 'method action';
actionDescriptor.params = { key: 'value' };
///////////////////////////////////////
// IResourceClass
///////////////////////////////////////
var resourceClass: IMyResourceClass;
var resource: IMyResource;
var resourceArray: OData.IResourceArray<IMyResource>;
resource = resourceClass.delete();
resource = resourceClass.delete({ key: 'value' });
resource = resourceClass.delete({ key: 'value' }, function() { });
resource = resourceClass.delete(function() { });
resource = resourceClass.delete(function() { }, function() { });
resource = resourceClass.delete({ key: 'value' }, { key: 'value' });
resource = resourceClass.delete({ key: 'value' }, { key: 'value' }, function() { });
resource = resourceClass.delete({ key: 'value' }, { key: 'value' }, function() { }, function() { });
resource.$promise.then(function(data: IMyResource) { });
resource = resourceClass.get();
resource = resourceClass.get({ key: 'value' });
resource = resourceClass.get({ key: 'value' }, function() { });
resource = resourceClass.get(function() { });
resource = resourceClass.get(function() { }, function() { });
resource = resourceClass.get({ key: 'value' }, { key: 'value' });
resource = resourceClass.get({ key: 'value' }, { key: 'value' }, function() { });
resource = resourceClass.get({ key: 'value' }, { key: 'value' }, function() { }, function() { });
resourceArray = resourceClass.query();
resourceArray = resourceClass.query({ key: 'value' });
resourceArray = resourceClass.query({ key: 'value' }, function() { });
resourceArray = resourceClass.query(function() { });
resourceArray = resourceClass.query(function() { }, function() { });
resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' });
resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' }, function() { });
resourceArray = resourceClass.query({ key: 'value' }, { key: 'value' }, function() { }, function() { });
resourceArray.push(resource);
resourceArray.$promise.then(function(data: OData.IResourceArray<IMyResource>) { });
resource = resourceClass.remove();
resource = resourceClass.remove({ key: 'value' });
resource = resourceClass.remove({ key: 'value' }, function() { });
resource = resourceClass.remove(function() { });
resource = resourceClass.remove(function() { }, function() { });
resource = resourceClass.remove({ key: 'value' }, { key: 'value' });
resource = resourceClass.remove({ key: 'value' }, { key: 'value' }, function() { });
resource = resourceClass.remove({ key: 'value' }, { key: 'value' }, function() { }, function() { });
resource = resourceClass.save();
resource = resourceClass.save({ key: 'value' });
resource = resourceClass.save({ key: 'value' }, function() { });
resource = resourceClass.save(function() { });
resource = resourceClass.save(function() { }, function() { });
resource = resourceClass.save({ key: 'value' }, { key: 'value' });
resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function() { });
resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function() { }, function() { });
///////////////////////////////////////
// IResource
///////////////////////////////////////
var promise: angular.IPromise<IMyResource>;
var arrayPromise: angular.IPromise<IMyResource[]>;
promise = resource.$delete();
promise = resource.$delete({ key: 'value' });
promise = resource.$delete({ key: 'value' }, function() { });
promise = resource.$delete(function() { });
promise = resource.$delete(function() { }, function() { });
promise = resource.$delete({ key: 'value' }, function() { }, function() { });
promise.then(function(data: IMyResource) { });
promise = resource.$get();
promise = resource.$get({ key: 'value' });
promise = resource.$get({ key: 'value' }, function() { });
promise = resource.$get(function() { });
promise = resource.$get(function() { }, function() { });
promise = resource.$get({ key: 'value' }, function() { }, function() { });
arrayPromise = resourceArray[0].$query();
arrayPromise = resourceArray[0].$query({ key: 'value' });
arrayPromise = resourceArray[0].$query({ key: 'value' }, function() { });
arrayPromise = resourceArray[0].$query(function() { });
arrayPromise = resourceArray[0].$query(function() { }, function() { });
arrayPromise = resourceArray[0].$query({ key: 'value' }, function() { }, function() { });
arrayPromise.then(function(data: OData.IResourceArray<IMyResource>) { });
promise = resource.$remove();
promise = resource.$remove({ key: 'value' });
promise = resource.$remove({ key: 'value' }, function() { });
promise = resource.$remove(function() { });
promise = resource.$remove(function() { }, function() { });
promise = resource.$remove({ key: 'value' }, function() { }, function() { });
promise = resource.$save();
promise = resource.$save({ key: 'value' });
promise = resource.$save({ key: 'value' }, function() { });
promise = resource.$save(function() { });
promise = resource.$save(function() { }, function() { });
promise = resource.$save({ key: 'value' }, function() { }, function() { });
///////////////////////////////////////
// IResourceService
///////////////////////////////////////
var resourceService: OData.IResourceService;
resourceClass = resourceService<IMyResource, IMyResourceClass>('test');
resourceClass = resourceService<IMyResource>('test');
resourceClass = resourceService('test');
///////////////////////////////////////
// IModule
///////////////////////////////////////
var mod: ng.IModule;
var resourceServiceFactoryFunction: OData.IResourceServiceFactoryFunction<IMyResource>;
var resourceService: OData.IResourceService;
resourceClass = resourceServiceFactoryFunction<IMyResourceClass>(resourceService);
resourceServiceFactoryFunction = function(resourceService: OData.IResourceService) { return <any>resourceClass; };
mod = mod.factory('factory name', resourceServiceFactoryFunction);
///////////////////////////////////////
// IResource
///////////////////////////////////////
///////////////////////////////////////
// IResourceServiceProvider
///////////////////////////////////////
var resourceServiceProvider: OData.IResourceServiceProvider;
resourceServiceProvider.defaults.stripTrailingSlashes = false;
///////////////////////////////////////
// OData
///////////////////////////////////////
interface User extends OData.IResource<User> {
name: string;
}
var resourceService: OData.IResourceService;
var odataResourceClass = resourceService<User>("my/url", {}, {}, { odata: { method: 'POST' } });
var Value: OData.ValueFactory;
var Property: OData.PropertyFactory;
var Predicate: OData.PredicateFactory;
var users = odataResourceClass.odata().query();
users[0].name;
users[0].$save;
users[0].$update;
var user = odataResourceClass.odata()
.filter(new Value("1", OData.ValueTypes.Int32), new Property("abc"))
.filter("Name", "John")
.filter("Age", ">", 20)
.skip(10)
.take(20)
.orderBy("Name", "desc")
.single();
user.$save();
var predicate1 = new Predicate("a", "b");
var predicate2 = new Predicate("c", "d");
var predicate3 = new Predicate("Age", '>', 10);
var combination1 = Predicate.or([predicate1, predicate2]);
var combination2 = Predicate.and([combination1, predicate2]);
var predicate = new Predicate("FirstName", "John")
.or(new Predicate("LastName", '!=', "Doe"))
.and(new Predicate("Age", '>', 10));
users = odataResourceClass.odata()
.withInlineCount()
.query();
var countResult = odataResourceClass.odata().count();
var total = countResult.result;
var usersSelect1 = odataResourceClass.odata()
.select('name', 'user');
var usersSelect2 = odataResourceClass.odata()
.select(['name', 'user']);
+325
View File
@@ -0,0 +1,325 @@
// Type definitions for OData Angular Resources
// Project: https://github.com/devnixs/ODataAngularResources
// Definitions by: Raphael ATALLAH <http://raphael.atallah.me>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module OData {
/**
* Currently supported options for the $resource factory options argument.
*/
interface IResourceOptions {
/**
* If true then the trailing slashes from any calculated URL will be stripped (defaults to true)
*/
stripTrailingSlashes?: boolean;
odata?: {
url?: string;
method?: string;
};
}
///////////////////////////////////////////////////////////////////////////
// ResourceService
// see http://docs.angularjs.org/api/ngResource.$resource
// Most part of the following definitions were achieved by analyzing the
// actual implementation, since the documentation doesn't seem to cover
// that deeply.
///////////////////////////////////////////////////////////////////////////
interface IResourceService {
(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: any, options?: IResourceOptions): IResourceClass<IResource<any>>;
<T, U>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: any, options?: IResourceOptions): U;
<T>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: any, options?: IResourceOptions): IResourceClass<T>;
}
// Just a reference to facilitate describing new actions
interface IActionDescriptor {
url?: string;
method: string;
isArray?: boolean;
params?: any;
headers?: any;
}
// Baseclass for everyresource with default actions.
// If you define your new actions for the resource, you will need
// to extend this interface and typecast the ResourceClass to it.
//
// In case of passing the first argument as anything but a function,
// it's gonna be considered data if the action method is POST, PUT or
// PATCH (in other words, methods with body). Otherwise, it's going
// to be considered as parameters to the request.
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L461-L465
//
// Only those methods with an HTTP body do have 'data' as first parameter:
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L463
// More specifically, those methods are POST, PUT and PATCH:
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L432
//
// Also, static calls always return the IResource (or IResourceArray) retrieved
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L549
interface IResourceClass<T> {
new(dataOrParams? : any) : IResource<T>;
get(): IResource<T>;
get(params: Object): IResource<T>;
get(success: Function, error?: Function): IResource<T>;
get(params: Object, success: Function, error?: Function): IResource<T>;
get(params: Object, data: Object, success?: Function, error?: Function): IResource<T>;
query(): IResourceArray<T>;
query(params: Object): IResourceArray<T>;
query(success: Function, error?: Function): IResourceArray<T>;
query(params: Object, success: Function, error?: Function): IResourceArray<T>;
query(params: Object, data: Object, success?: Function, error?: Function): IResourceArray<T>;
save(): IResource<T>;
save(data: Object): IResource<T>;
save(success: Function, error?: Function): IResource<T>;
save(data: Object, success: Function, error?: Function): IResource<T>;
save(params: Object, data: Object, success?: Function, error?: Function): IResource<T>;
update(): IResource<T>;
update(data: Object): IResource<T>;
update(success: Function, error?: Function): IResource<T>;
update(data: Object, success: Function, error?: Function): IResource<T>;
update(params: Object, data: Object, success?: Function, error?: Function): IResource<T>;
remove(): IResource<T>;
remove(params: Object): IResource<T>;
remove(success: Function, error?: Function): IResource<T>;
remove(params: Object, success: Function, error?: Function): IResource<T>;
remove(params: Object, data: Object, success?: Function, error?: Function): IResource<T>;
delete(): IResource<T>;
delete(params: Object): IResource<T>;
delete(success: Function, error?: Function): IResource<T>;
delete(params: Object, success: Function, error?: Function): IResource<T>;
delete(params: Object, data: Object, success?: Function, error?: Function): IResource<T>;
odata(): OData.Provider<T>;
}
// Instance calls always return the the promise of the request which retrieved the object
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L546
interface IResource<T> {
$get(): angular.IPromise<T>;
$get(params?: Object, success?: Function, error?: Function): angular.IPromise<T>;
$get(success: Function, error?: Function): angular.IPromise<T>;
$query(): angular.IPromise<IResourceArray<T>>;
$query(params?: Object, success?: Function, error?: Function): angular.IPromise<IResourceArray<T>>;
$query(success: Function, error?: Function): angular.IPromise<IResourceArray<T>>;
$save(): angular.IPromise<T>;
$save(params?: Object, success?: Function, error?: Function): angular.IPromise<T>;
$save(success: Function, error?: Function): angular.IPromise<T>;
$update(): angular.IPromise<T>;
$update(params?: Object, success?: Function, error?: Function): angular.IPromise<T>;
$update(success: Function, error?: Function): angular.IPromise<T>;
$remove(): angular.IPromise<T>;
$remove(params?: Object, success?: Function, error?: Function): angular.IPromise<T>;
$remove(success: Function, error?: Function): angular.IPromise<T>;
$delete(): angular.IPromise<T>;
$delete(params?: Object, success?: Function, error?: Function): angular.IPromise<T>;
$delete(success: Function, error?: Function): angular.IPromise<T>;
/** the promise of the original server interaction that created this instance. **/
$promise: angular.IPromise<T>;
$resolved: boolean;
}
/**
* Really just a regular Array object with $promise and $resolve attached to it
*/
interface IResourceArray<T> extends Array<T> {
/** the promise of the original server interaction that created this collection. **/
$promise: angular.IPromise<IResourceArray<T>>;
$resolved: boolean;
}
/** when creating a resource factory via IModule.factory */
interface IResourceServiceFactoryFunction<T> {
($resource: OData.IResourceService): IResourceClass<T>;
<U extends IResourceClass<T>>($resource: OData.IResourceService): U;
}
// IResourceServiceProvider used to configure global settings
interface IResourceServiceProvider extends angular.IServiceProvider {
defaults: IResourceOptions;
}
interface IExecutable {
execute(noParenthesis?: any): string;
}
class Global {
static $inject: string[];
constructor(ODataBinaryOperation: any, ODataProvider: any, ODataValue: any, ODataProperty: any, ODataMethodCall: any, ODataPredicate: any, ODataOrderByStatement: any);
Provider: Provider<any>;
BinaryOperation: typeof BinaryOperation;
Value: typeof Value;
Property: typeof Property;
Func: typeof MethodCall;
Predicate: typeof Predicate;
OrderBy: typeof OrderByStatement;
}
interface BinaryOperationFactory {
new (propertyOrPredicate: any, valueOrOperator?: any, value?: any): BinaryOperation;
}
class BinaryOperation implements IExecutable {
private operandA;
private operandB;
private filterOperator;
constructor(propertyOrPredicate: any, valueOrOperator?: any, value?: any);
execute(noParenthesis?: any): string;
or(propertyOrPredicate: any, operatorOrValue?: any, value?: any): BinaryOperation;
and(propertyOrPredicate: any, operatorOrValue?: any, value?: any): BinaryOperation;
}
interface MethodCallFactory {
new (methodName: string, ...args: any[]): MethodCall;
}
class MethodCall implements IExecutable {
private methodName;
private params;
execute(): string;
constructor(methodName: string, ...args: any[]);
}
class Operators {
operators: {
'eq': string[];
'ne': string[];
'gt': string[];
'ge': string[];
'lt': string[];
'le': string[];
'and': string[];
'or': string[];
'not': string[];
'add': string[];
'sub': string[];
'mul': string[];
'div': string[];
'mod': string[];
};
private rtrim;
private trim(value);
convert(from: string): any;
}
interface OrderByStatementFactory {
new (propertyName: string, sortOrder?: string): OrderByStatement;
}
class OrderByStatement implements IExecutable {
private propertyName;
private direction;
execute(): string;
constructor(propertyName: string, sortOrder?: string);
}
interface PredicateFactory {
new (propertyOrValueOrPredicate: any, valueOrOperator?: any, value?: any): Predicate;
or(orStatements: any[]): IExecutable;
create(propertyOrPredicate: any, operatorOrValue?: any, value?: any): IExecutable;
and(andStatements: any): IExecutable;
}
class Predicate extends BinaryOperation {
constructor(propertyOrValueOrPredicate: any, valueOrOperator?: any, value?: any);
static or(orStatements: any[]): IExecutable;
static create(propertyOrPredicate: any, operatorOrValue?: any, value?: any): IExecutable;
static and(andStatements: any): IExecutable;
}
interface PropertyFactory {
new (value: string): Property;
}
class Property implements IExecutable {
private value;
constructor(value: string);
execute(): string;
}
interface ProviderFactory {
new <T>(callback: ProviderCallback<T>): Provider<T>;
}
interface ProviderCallback<T> {
(queryString: string, success: () => any, error: () => any): T[];
(queryString: string, success: () => any, error: () => any, isSingleElement?: boolean, forceSingleElement?: boolean): T;
}
interface ICountResult{
result: number;
$promise: angular.IPromise<any>;
}
class Provider<T> {
private callback;
private filters;
private sortOrders;
private takeAmount;
private skipAmount;
private expandables;
constructor(callback: ProviderCallback<T>);
filter(operand1: any, operand2?: any, operand3?: any): Provider<T>;
orderBy(arg1: string, arg2?: string): Provider<T>;
take(amount: number): Provider<T>;
skip(amount: number): Provider<T>;
private execute();
query(success?: ((p:T[])=>void), error?: (()=>void)): T[];
single(success?: ((p:T)=>void), error?: (()=>void)): T;
get(key: any, success?: ((p:T)=>void), error?: (()=>void)): T;
expand(...params: string[]): Provider<T>;
expand(params: string[]): Provider<T>;
select(...params: string[]): Provider<T>;
select(params: string[]): Provider<T>;
count(success?: (result: ICountResult) => any, error?: () => any):ICountResult;
withInlineCount(): Provider<T>;
}
interface ValueFactory {
new (value: any, type?: string): Value;
}
class ValueTypes {
static Boolean: string;
static Byte: string;
static DateTime: string;
static Decimal: string;
static Double: string;
static Single: string;
static Guid: string;
static Int32: string;
static String: string;
}
class Value {
private value;
private type;
private illegalChars;
private escapeIllegalChars(haystack);
private generateDate(date);
executeWithUndefinedType(): any;
executeWithType(): any;
execute(): string;
constructor(value: any, type?: string);
}
}
@@ -374,7 +374,7 @@ function TestElementArrayFinder() {
var b: boolean = elementArrayFinder.isPending();
var locator: webdriver.Locator = elementArrayFinder.locator();
var findersArray: protractor.ElementFinder[] = elementArrayFinder.asElementFinders_();
var findersArrayPromise: protractor.promise.Promise<protractor.ElementFinder[]> = elementArrayFinder.asElementFinders_();
var driverElementArray: webdriver.WebElement[] = elementArrayFinder.getWebElements();
var elementFinder: protractor.ElementFinder = elementArrayFinder.get(42);
+16 -2
View File
@@ -927,7 +927,7 @@ declare module protractor {
* @return {Array.<ElementFinder>} Return a promise, which resolves to a list
* of ElementFinders specified by the locator.
*/
asElementFinders_(): ElementFinder[];
asElementFinders_(): webdriver.promise.Promise<ElementFinder[]>;
/**
* Create a shallow copy of ElementArrayFinder.
@@ -1228,7 +1228,21 @@ declare module protractor {
row(index: number): LocatorWithColumn;
}
interface IProtractorLocatorStrategy extends webdriver.ILocatorStrategy {
interface IProtractorLocatorStrategy {
/**
* webdriver's By is an enum of locator functions, so we must set it to
* a prototype before inheriting from it.
*/
className: typeof webdriver.By.className;
css: typeof webdriver.By.css;
id: typeof webdriver.By.id;
linkText: typeof webdriver.By.linkText;
js: typeof webdriver.By.js;
name: typeof webdriver.By.name;
partialLinkText: typeof webdriver.By.partialLinkText;
tagName: typeof webdriver.By.tagName;
xpath: typeof webdriver.By.xpath;
/**
* Add a locator to this instance of ProtractorBy. This locator can then be
* used with element(by.locatorName(args)).
@@ -0,0 +1,77 @@
/// <reference path='angular-signalr-hub.d.ts' />
/// <reference path='../angularjs/angular.d.ts' />
angular
.module('app', ['SignalR'])
.factory('Employees', ngSignalrTest.EmployeesFactory);
module ngSignalrTest {
export class EmployeesFactory {
static $inject = ['$rootScope', 'Hub', '$timeout'];
private hub: ngSignalr.Hub;
public all: Array<Employee>;
constructor($rootScope: ng.IRootScopeService, Hub: ngSignalr.HubFactory, $timeout: ng.ITimeoutService) {
// declaring the hub connection
this.hub = new Hub('employee', {
// client-side methods
listeners: {
'lockEmployee': (id: number) => {
var employee = this.find(id);
employee.Locked = true;
$rootScope.$apply();
},
'unlockEmployee': (id: number) => {
var employee = this.find(id);
employee.Locked = false;
$rootScope.$apply();
}
},
// server-side methods
methods: ['lock', 'unlock'],
// query params sent on initial connection
queryParams:{
'token': 'exampletoken'
},
// handle connection error
errorHandler: (message: string) => {
console.error(message);
},
stateChanged: (state: SignalRStateChange) => {
// your code here
}
});
}
private find(id: number) {
for (var i = 0; i < this.all.length; i++) {
if (this.all[i].Id === id) return this.all[i];
}
return null;
}
public edit = (employee: Employee) => {
employee.Edit = true;
this.hub.invoke('lock', employee.Id);
};
public done = (employee: Employee) => {
employee.Edit = false;
this.hub.invoke('unlock', employee.Id);
}
}
interface Employee {
Id: number;
Name: string;
Email: string;
Salary: number;
Edit: boolean;
Locked: boolean;
}
}
+73
View File
@@ -0,0 +1,73 @@
// Type definitions for angular-signalr-hub v1.5.0
// Project: https://github.com/JustMaier/angular-signalr-hub
// Definitions by: Adam Santaniello <https://github.com/AdamSantaniello>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path='../signalr/signalr.d.ts' />
declare module ngSignalr {
interface HubFactory {
/**
* Creates a new Hub connection
*/
new(hubName: string, options: HubOptions) : Hub
}
class Hub {
hubName: string;
connection: SignalR;
proxy: HubProxy;
on(event: string, fn: ((...args: any[]) => void)): void;
invoke(method: string, ...args: any[]): JQueryDeferred<any>;
disconnect(): void;
connect(): JQueryPromise<any>;
}
interface HubOptions {
/**
* Collection of client side callbacks
*/
listeners?: { [index: string] : (...args: any[]) => void };
/**
* String array of server side methods which the client can call
*/
methods?: Array<string>;
/**
* Sets the root path for the SignalR web service
*/
rootPath?: string;
/**
* Object representing additional query params to be sent on connection
*/
queryParams?: { [index: string] : string };
/**
* Function to handle hub connection errors
*/
errorHandler?: (error: string) => void;
/**
* Enable/disable logging
*/
logging?: boolean;
/**
* Use a shared global connection or create a new one just for this hub, defaults to true
*/
useSharedConnection?: boolean;
/**
* Sets transport method (e.g 'longPolling' or ['webSockets', 'longPolling'] )
*/
transport?: any;
/**
* Function to handle hub connection state changed event
*/
stateChanged?: (state: SignalRStateChange) => void;
}
}
+43
View File
@@ -0,0 +1,43 @@
/// <reference path='../angularjs/angular.d.ts' />
/// <reference path='angular-storage.d.ts' />
// Samples taken from the a0-angular-storage Readme.md
var app = angular.module('angular-storage-tests', ['angular-storage']);
angular.module('angular-storage-tests')
.controller('StoreController', function(store: angular.a0.storage.IStoreService) {
var myObj = {
name: 'mgonto'
};
store.set('obj', myObj);
var myNewObject = store.get('obj');
console.log('Should be true: ', angular.equals(myNewObject, myObj));
store.remove('obj');
store.set('number', 2);
console.log('Should be true: ', typeof(store.get('number')) === 'number');
})
.factory('Auth0Store', function(store: angular.a0.storage.IStoreService) {
return store.getNamespacedStore('auth0');
})
.controller('NamespacedStoreController', function(Auth0Store: angular.a0.storage.INamespacedStoreService) {
var myObj = {
name: 'mgonto'
};
// This will be saved in localStorage as auth0.obj
Auth0Store.set('obj', myObj);
// This will look for auth0.obj
var myNewObject = Auth0Store.get('obj');
console.log('Should be true: ', angular.equals(myNewObject, myObj));
});;
+53
View File
@@ -0,0 +1,53 @@
// Type definitions for angular-storage v0.0.11
// Project: https://github.com/auth0/angular-storage
// Definitions by: Matthew DeKrey <https://github.com/mdekrey>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module angular.a0.storage {
interface IStoreService extends INamespacedStoreService {
/**
* Returns a namespaced store
*
* @param {String} namespace - The namespace
* @param {String} storage - The name of the storage service. Defaults to local storage.
* @param {String} delimiter - The delimiter to use to separate the namespace and the keys.
* @returns {INamespacedStoreService}
*/
getNamespacedStore(namespace: string, storage?: string, delimiter?: string): INamespacedStoreService;
}
interface INamespacedStoreService {
/**
* Sets a new value to the storage with the key name. It can be any object.
*
* @param {String} name - The key name for the location of the value
* @param value - The value to store
*/
set(name: string, value: any): void;
/**
* Returns the saved value with they key name.
*
* @param {String} name - The key name for the location of the value
* @returns The saved value; if you saved an object, you get an object
*/
get(name: string): any;
/**
* Deletes the saved value with the key name
*
* @param {String} name - The key name for the location of the value to remove
*/
remove(name: string): void;
}
interface IStoreProvider {
/**
* Sets the storage.
*
* @param {String} storage - The storage name
*/
setStore(storage: string): void;
}
}
+76
View File
@@ -0,0 +1,76 @@
/// <reference path="angular-toasty.d.ts" />
interface AngularToastyTestControllerScope extends ng.IScope {
button:string;
options:toasty.IToastyConfig;
runToasts(): void;
runQuickToasts(): void;
newToast(): void;
clearToasts(): void;
}
class AngularToastyTestController {
static $inject = ['$scope', 'toasty'];
constructor($scope:AngularToastyTestControllerScope, toasty:toasty.IToastyService) {
var options: toasty.IToastyConfig = {
title: 'Toast It!',
msg: 'Mmmm, tasties...',
showClose: true,
clickToClose: false,
timeout: 5000,
sound: true,
html: false,
shake: false,
theme: 'bootstrap',
onAdd: function () {
console.log('Toasty ' + this.id + ' has been added!', this);
},
onRemove: function () {
console.log('Toasty ' + this.id + ' has been removed!', this);
},
onClick: function () {
console.log('Toasty ' + this.id + ' has been clicked!', this);
}
};
$scope.runToasts = function () {
toasty(options);
toasty.default(options);
toasty.info(options);
toasty.success(options);
toasty.wait(options);
toasty.error(options);
toasty.warning(options);
};
$scope.runQuickToasts = function () {
var title = 'Toast it!'
toasty(title);
toasty.default(title);
toasty.info(title);
toasty.success(title);
toasty.wait(title);
toasty.error(title);
toasty.warning(title);
};
$scope.clearToasts = function () {
toasty.clear();
};
}
};
angular
.module('main', ['angular-toasty'])
.config(['toastyConfigProvider', (toastyConfigProvider:toasty.IToastyConfigProvider) => {
toastyConfigProvider.setConfig({
title: 'global',
limit: 10,
sound: false,
shake: true
});
}])
.controller('MainController', AngularToastyTestController);
+251
View File
@@ -0,0 +1,251 @@
// Type definitions for Angular Toasty v1.0.2
// Project: https://github.com/invertase/angular-toasty
// Definitions by: Dominik Muench <https://github.com/muenchdo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module toasty {
interface IToastyService {
/**
* Create a toast with the given options and type.
* @param options
* @param type
*/
(options: IToastyConfig, type?: string): void;
/**
* Create a default "quick toast" with the given title.
* @param title
*/
(title: string|number): void;
/**
* Create a default toast with the given options.
* @param options
*/
default(options: IToastyConfig): void;
/**
* Create a default "quick toast" with the given title.
* @param title
*/
default(title: string|number): void;
/**
* Create an info toast with the given options.
* @param options
*/
info(options: IToastyConfig): void;
/**
* Create an info "quick toast" with the given title.
* @param title
*/
info(title: string|number): void;
/**
* Create a wait toast with the given options.
* @param options
*/
wait(options: IToastyConfig): void;
/**
* Create a wait "quick toast" with the given title.
* @param title
*/
wait(title: string|number): void;
/**
* Create a success toast with the given options.
* @param options
*/
success(options: IToastyConfig): void;
/**
* Create a success "quick toast" with the given title.
* @param title
*/
success(title: string|number): void;
/**
* Create an error toast with the given options.
* @param options
*/
error(options: IToastyConfig): void;
/**
* Create an error "quick toast" with the given title.
* @param title
*/
error(title: string|number): void;
/**
* Create a warning toast with the given options.
* @param options
*/
warning(options: IToastyConfig): void;
/**
* Create a warning "quick toast" with the given title.
* @param title
*/
warning(title: string|number): void;
/**
* Clear toast(s).
* @param id Optional ID to clear a specific toast.
*/
clear(id?: number): void;
/**
* Get the global config.
*/
getGlobalConfig(): IGlobalConfig;
}
interface IToastyConfig {
/**
* The toast's title.
*/
title: string;
/**
* The toast's message.
*/
msg?: string;
/**
* Whether to show the 'X' icon to close the toast.
*/
showClose?: boolean;
/**
* Whether clicking the toast closes it.
*/
clickToClose?: boolean;
/**
* How long (in milliseconds) the toast shows before it's removed. Set to false to disable.
*/
timeout?: number;
/**
* Whether to play a sound when a toast is added.
*/
sound?: boolean;
/**
* Whether HTML is allowed in toasts.
*/
html?: boolean;
/**
* Whether to shake the toasts.
*/
shake?: boolean;
/**
* What theme to use.
* - 'default'
* - 'material'
* - 'bootstrap'
*/
theme?: string;
/**
* The toast's type:
* - 'default'
* - 'info'
* - 'success'
* - 'wait'
* - 'error'
* - 'warning'
*/
type?: string;
/**
* Add event handler.
*/
onAdd?: Function;
/**
* Remove event handler.
*/
onRemove?: Function;
/**
* Click event handler.
*/
onClick?: Function;
}
interface IGlobalConfig {
/**
* Maximum number of toasts to show at once.
*/
limit?: number;
/**
* The toast's title.
*/
title?: string;
/**
* The toast's message.
*/
msg?: string;
/**
* Whether to show the 'X' icon to close the toast.
*/
showClose?: boolean;
/**
* Whether clicking the toast closes it.
*/
clickToClose?: boolean;
/**
* The window position where the toast pops up.
*
*/
position?: string;
/**
* How long (in miliseconds) the toast shows before it's removed. Set to false to disable.
*/
timeout?: number|boolean;
/**
* Whether to play a sound when a toast is added.
*/
sound?: boolean;
/**
* Whether HTML is allowed in toast.
*/
html?: boolean;
/**
* Whether to shake the toast.
*/
shake?: boolean;
/**
* What theme to use.
* - 'default'
* - 'material'
* - 'bootstrap'
*/
theme?: string;
}
interface IToastyConfigProvider {
setConfig(override: IGlobalConfig): void;
$get(): IGlobalConfig;
}
}
@@ -2,6 +2,14 @@
var app = angular.module('at', ['pascalprecht.translate']);
app.factory('customLoader', ($q:angular.IQService) => {
return (options:any) => {
var dfd:angular.IDeferred<string> = $q.defer();
dfd.resolve('whatever you wanted to translate, I simply know nothing about the language with the key ' + options.key);
return dfd.promise;
}
});
app.config(($translateProvider: angular.translate.ITranslateProvider) => {
$translateProvider.translations('en', {
TITLE: 'Hello',
@@ -16,6 +24,8 @@ app.config(($translateProvider: angular.translate.ITranslateProvider) => {
BUTTON_LANG_DE: 'deutsch'
});
$translateProvider.preferredLanguage('en');
$translateProvider.useLoader('customLoader');
});
interface Scope extends ng.IScope {
+7 -2
View File
@@ -5,10 +5,15 @@
/// <reference path="../angularjs/angular.d.ts" />
declare module "angular-translate" {
var _: string;
export = _;
}
declare module angular.translate {
interface ITranslationTable {
[key: string]: string;
[key: string]: any;
}
interface ILanguageKeyAlias {
@@ -88,7 +93,7 @@ declare module angular.translate {
storageKey(key: string): void; // JeroMiya - the library should probably return ITranslateProvider but it doesn't here
useUrlLoader(url: string): ITranslateProvider;
useStaticFilesLoader(options: IStaticFilesLoaderOptions): ITranslateProvider;
useLoader(loaderFactory: string, options: any): ITranslateProvider;
useLoader(loaderFactory: string, options?: any): ITranslateProvider;
useLocalStorage(): ITranslateProvider;
useCookieStorage(): ITranslateProvider;
useStorage(storageFactory: any): ITranslateProvider;
@@ -7,6 +7,7 @@ testApp.config((
$buttonConfig: ng.ui.bootstrap.IButtonConfig,
$datepickerConfig: ng.ui.bootstrap.IDatepickerConfig,
$datepickerPopupConfig: ng.ui.bootstrap.IDatepickerPopupConfig,
$modalProvider: ng.ui.bootstrap.IModalProvider,
$paginationConfig: ng.ui.bootstrap.IPaginationConfig,
$pagerConfig: ng.ui.bootstrap.IPagerConfig,
$progressConfig: ng.ui.bootstrap.IProgressConfig,
@@ -30,19 +31,25 @@ testApp.config((
/**
* $datepickerConfig tests
*/
$datepickerConfig.dayFormat = 'd';
$datepickerConfig.dayHeaderFormat = 'E';
$datepickerConfig.dayTitleFormat = 'dd-MM-yyyy';
$datepickerConfig.datepickerMode = 'month';
$datepickerConfig.formatDay = 'd';
$datepickerConfig.formatDayHeader = 'E';
$datepickerConfig.formatDayTitle = 'dd-MM-yyyy';
$datepickerConfig.formatMonth = 'M';
$datepickerConfig.formatMonthTitle = 'yy';
$datepickerConfig.formatYear = 'y';
$datepickerConfig.maxDate = '1389586124979';
$datepickerConfig.maxMode = 'month';
$datepickerConfig.minDate = '1389586124979';
$datepickerConfig.monthFormat = 'M';
$datepickerConfig.monthTitleFormat = 'yy';
$datepickerConfig.minMode = 'month';
$datepickerConfig.shortcutPropagation = true;
$datepickerConfig.showWeeks = false;
$datepickerConfig.startingDay = 1;
$datepickerConfig.yearFormat = 'y';
$datepickerConfig.yearRange = 10;
/**
* $datepickerPopupConfig tests
*/
@@ -51,9 +58,18 @@ testApp.config((
$datepickerPopupConfig.clearText = 'Reset Selection';
$datepickerPopupConfig.closeOnDateSelection = false;
$datepickerPopupConfig.closeText = 'Finished';
$datepickerPopupConfig.dateFormat = 'dd-MM-yyyy';
$datepickerPopupConfig.datepickerPopup = 'dd-MM-yyyy';
$datepickerPopupConfig.datepickerPopupTemplateUrl = 'template.html';
$datepickerPopupConfig.datepickerTemplateUrl = 'template.html';
$datepickerPopupConfig.html5Types.date = 'MM-dd-yyyy';
$datepickerPopupConfig.onOpenFocus = false;
$datepickerPopupConfig.showButtonBar = false;
$datepickerPopupConfig.toggleWeeksText = 'Show Weeks';
/**
* $modalProvider tests
*/
$modalProvider.options.animation = false;
/**
@@ -64,9 +80,13 @@ testApp.config((
$paginationConfig.firstText = 'First Page';
$paginationConfig.itemsPerPage = 25;
$paginationConfig.lastText = 'Last Page';
$paginationConfig.maxSize = 13;
$paginationConfig.numPages = 13;
$paginationConfig.nextText = 'Next Page';
$paginationConfig.previousText = 'Previous Page';
$paginationConfig.rotate = false;
$paginationConfig.templateUrl = 'template.html';
$paginationConfig.totalItems = 13;
/**
@@ -91,6 +111,7 @@ testApp.config((
$ratingConfig.max = 10;
$ratingConfig.stateOff = 'rating-state-off';
$ratingConfig.stateOn = 'rating-state-on';
$ratingConfig.titles = ['1', '2', '3', '4', '5'];
/**
@@ -102,6 +123,8 @@ testApp.config((
$timepickerConfig.mousewheel = false;
$timepickerConfig.readonlyInput = true;
$timepickerConfig.showMeridian = false;
$timepickerConfig.arrowkeys = false;
$timepickerConfig.showSpinners = false;
/**
* $tooltipProvider tests
@@ -110,7 +133,9 @@ testApp.config((
placement: 'bottom',
animation: false,
popupDelay: 1000,
appendtoBody: true
appendToBody: true,
trigger: 'mouseenter hover',
useContentExp: true,
});
$tooltipProvider.setTriggers({
'customOpenTrigger': 'customCloseTrigger'
@@ -129,10 +154,14 @@ testApp.controller('TestCtrl', (
* test the $modal service
*/
var modalInstance = $modal.open({
animation: false,
backdrop: 'static',
backdropClass: 'modal-backdrop-test',
bindToController: true,
controller: 'ModalTestCtrl',
controllerAs: 'vm',
keyboard: true,
openedClass: 'modal-open my-modal',
resolve: {
items: ()=> {
return [1, 2, 3, 4, 5];
@@ -141,7 +170,6 @@ testApp.controller('TestCtrl', (
scope: $scope,
template: "<div>i'm a template!</div>",
templateUrl: '/templates/modal.html',
backdropClass: 'modal-backdrop-test',
windowClass: 'modal-test'
});
@@ -149,12 +177,23 @@ testApp.controller('TestCtrl', (
$log.log('modal opened');
});
modalInstance.rendered.then(() => {
$log.log('modal rendered');
});
modalInstance.result.then((closeResult:any)=> {
$log.log('modal closed', closeResult);
}, (dismissResult:any)=> {
$log.log('modal dismissed', dismissResult);
});
$modal.open({
backdrop: 'static'
});
$modal.open({
templateUrl: () => '/templates/modal.html'
});
/**
* test the $modalStack service
+157 -69
View File
@@ -1,4 +1,4 @@
// Type definitions for Angular UI Bootstrap 0.11.0
// Type definitions for Angular UI Bootstrap 0.13.3
// Project: https://github.com/angular-ui/bootstrap
// Definitions by: Brian Surowiec <https://github.com/xt0rted>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -36,42 +36,63 @@ declare module angular.ui.bootstrap {
*
* @default 'dd'
*/
dayFormat?: string;
formatDay?: string;
/**
* Format of month in year.
*
* @default 'MMM'
*/
monthFormat?: string;
formatMonth?: string;
/**
* Format of year in year range.
*
* @default 'yyyy'
*/
yearFormat?: string;
formatYear?: string;
/**
* Format of day in week header.
*
* @default 'EEE'
*/
dayHeaderFormat?: string;
formatDayHeader?: string;
/**
* Format of title when selecting day.
*
* @default 'MMM yyyy'
*/
dayTitleFormat?: string;
formatDayTitle?: string;
/**
* Format of title when selecting month.
*
* @default 'yyyy'
*/
monthTitleFormat?: string;
formatMonthTitle?: string;
/**
* Current mode of the datepicker (day|month|year). Can be used to initialize datepicker to specific mode.
*
* @default 'day'
*/
datepickerMode?: string;
/**
* Set a lower limit for mode.
*
* @default 'day'
*/
minMode?: string;
/**
* Set an upper limit for mode.
*
* @default 'year'
*/
maxMode?: string;
/**
* Whether to display week numbers.
@@ -107,6 +128,13 @@ declare module angular.ui.bootstrap {
* @default null
*/
maxDate?: any;
/**
* An option to disable or enable shortcut's event propagation
*
* @default false
*/
shortcutPropagation?: boolean;
}
interface IDatepickerPopupConfig {
@@ -115,7 +143,30 @@ declare module angular.ui.bootstrap {
*
* @default 'yyyy-MM-dd'
*/
dateFormat?: string;
datepickerPopup?: string;
/**
* Allows overriding of default template of the popup.
*
* @default 'template/datepicker/popup.html'
*/
datepickerPopupTemplateUrl?: string;
/**
* Allows overriding of default template of the datepicker used in popup.
*
* @default 'template/datepicker/popup.html'
*/
datepickerTemplateUrl?: string;
/**
* Allows overriding of the default format for html5 date inputs.
*/
html5Types?: {
date?: string;
'datetime-local'?: string;
month?: string;
};
/**
* The text to display for the current day button.
@@ -124,13 +175,6 @@ declare module angular.ui.bootstrap {
*/
currentText?: string;
/**
* The text to display for the toggling week numbers button.
*
* @default 'Weeks'
*/
toggleWeeksText?: string;
/**
* The text to display for the clear button.
*
@@ -165,9 +209,23 @@ declare module angular.ui.bootstrap {
* @default true
*/
showButtonBar?: boolean;
/**
* Whether to focus the datepicker popup upon opening.
*
* @default true
*/
onOpenFocus?: boolean;
}
interface IModalProvider {
/**
* Default options all modals will use.
*/
options: IModalSettings;
}
interface IModalService {
/**
* @param {IModalSettings} options
@@ -178,47 +236,52 @@ declare module angular.ui.bootstrap {
interface IModalServiceInstance {
/**
* a method that can be used to close a modal, passing a result
* A method that can be used to close a modal, passing a result. If `preventDefault` is called on the `modal.closing` event then the modal will remain open.
*/
close(result?: any): void;
/**
* a method that can be used to dismiss a modal, passing a reason
* A method that can be used to dismiss a modal, passing a reason. If `preventDefault` is called on the `modal.closing` event then the modal will remain open.
*/
dismiss(reason?: any): void;
/**
* a promise that is resolved when a modal is closed and rejected when a modal is dismissed
* A promise that is resolved when a modal is closed and rejected when a modal is dismissed.
*/
result: angular.IPromise<any>;
/**
* a promise that is resolved when a modal gets opened after downloading content's template and resolving all variables
* A promise that is resolved when a modal gets opened after downloading content's template and resolving all variables.
*/
opened: angular.IPromise<any>;
/**
* A promise that is resolved when a modal is rendered.
*/
rendered: angular.IPromise<any>;
}
interface IModalScope extends angular.IScope {
/**
* Those methods make it easy to close a modal window without a need to create a dedicated controller
* Dismiss the dialog without assigning a value to the promise output. If `preventDefault` is called on the `modal.closing` event then the modal will remain open.
*
* @returns true if the modal was closed; otherwise false
*/
$dismiss(reason?: any): boolean;
/**
* Dismiss the dialog without assigning a value to the promise output
* Close the dialog resolving the promise to the given value. If `preventDefault` is called on the `modal.closing` event then the modal will remain open.
*
* @returns true if the modal was closed; otherwise false
*/
$dismiss(reason?: any): void;
/**
* Close the dialog resolving the promise to the given value
*/
$close(result?: any): void;
$close(result?: any): boolean;
}
interface IModalSettings {
/**
* a path to a template representing modal's content
*/
templateUrl?: string;
templateUrl?: string | (() => string);
/**
* inline template representing the modal's content
@@ -243,11 +306,25 @@ declare module angular.ui.bootstrap {
*/
controllerAs?: string;
/**
* When used with controllerAs and set to true, it will bind the controller properties onto the $scope directly.
*
* @default false
*/
bindToController?: boolean;
/**
* members that will be resolved and passed to the controller as locals; it is equivalent of the `resolve` property for AngularJS routes
*/
resolve?: any;
/**
* Set to false to disable animations on new modal/backdrop. Does not toggle animations for modals/backdrops that are already displayed.
*
* @default true
*/
animation?: boolean;
/**
* controls the presence of a backdrop
* Allowed values:
@@ -257,10 +334,12 @@ declare module angular.ui.bootstrap {
*
* @default true
*/
backdrop?: any;
backdrop?: boolean | string;
/**
* indicates whether the dialog should be closable by hitting the ESC key, defaults to true
* indicates whether the dialog should be closable by hitting the ESC key
*
* @default true
*/
keyboard?: boolean;
@@ -275,7 +354,7 @@ declare module angular.ui.bootstrap {
windowClass?: string;
/**
* optional size of modal window. Allowed values: 'sm' (small) or 'lg' (large). Requires Bootstrap 3.1.0 or later
* Optional suffix of modal window class. The value used is appended to the `modal-` class, i.e. a value of `sm` gives `modal-sm`.
*/
size?: string;
@@ -283,6 +362,13 @@ declare module angular.ui.bootstrap {
* a path to a template overriding modal's window template
*/
windowTemplateUrl?: string;
/**
* The class added to the body element when the modal is opened.
*
* @default 'model-open'
*/
openedClass?: string;
}
interface IModalStackService {
@@ -319,11 +405,6 @@ declare module angular.ui.bootstrap {
interface IPaginationConfig {
/**
* Current page number. First page is 1.
*/
page?: number;
/**
* Total number of items in all pages.
*/
@@ -357,13 +438,6 @@ declare module angular.ui.bootstrap {
*/
rotate?: boolean;
/**
* An optional expression called when a page is selected having the page number as argument.
*
* @default null
*/
onSelectPage?(page: number): void;
/**
* Whether to display Previous / Next buttons.
*
@@ -405,6 +479,13 @@ declare module angular.ui.bootstrap {
* @default 'Last'
*/
lastText?: string;
/**
* Override the template for the component with a custom provided template.
*
* @default 'template/pagination/pagination.html'
*/
templateUrl?: string;
}
interface IPagerConfig {
@@ -415,16 +496,6 @@ declare module angular.ui.bootstrap {
*/
align?: boolean;
/**
* Current page number. First page is 1.
*/
page?: number;
/**
* Total number of items in all pages.
*/
totalItems?: number;
/**
* Maximum number of items per page. A value less than one indicates all items on one page.
*
@@ -432,20 +503,6 @@ declare module angular.ui.bootstrap {
*/
itemsPerPage?: number;
/**
* An optional expression assigned the total number of pages to display.
*
* @default angular.noop
*/
numPages?: number;
/**
* An optional expression called when a page is selected having the page number as argument.
*
* @default null
*/
onSelectPage?(page: number): void;
/**
* Text for Previous button.
*
@@ -520,6 +577,13 @@ declare module angular.ui.bootstrap {
* @default: null
*/
stateOff?: string;
/**
* An array of strings defining titles for all icons.
*
* @default: ["one", "two", "three", "four", "five"]
*/
titles?: Array<string>;
}
@@ -565,6 +629,20 @@ declare module angular.ui.bootstrap {
* @default true
*/
mousewheel?: boolean;
/**
* Whether the user can use up/down arrowkeys inside the hours & minutes input to increase or decrease it's values.
*
* @default true
*/
arrowkeys?: boolean;
/**
* Shows spinner arrows above and below the inputs.
*
* @default true
*/
showSpinners?: boolean;
}
@@ -577,7 +655,7 @@ declare module angular.ui.bootstrap {
placement?: string;
/**
* Should it fade in and out?
* Should the modal fade in and out?
*
* @default true
*/
@@ -598,11 +676,18 @@ declare module angular.ui.bootstrap {
appendToBody?: boolean;
/**
* Determines the default open triggers for tooltips and popovers
* What should trigger a show of the tooltip? Supports a space separated list of event names.
*
* @default 'mouseenter' for tooltip, 'click' for popover
*/
trigger?: string;
/**
* Should an expression on the scope be used to load the content?
*
* @default false
*/
useContentExp?: boolean;
}
interface ITooltipProvider {
@@ -618,6 +703,9 @@ declare module angular.ui.bootstrap {
}
/**
* WARNING: $transition is now deprecated. Use $animate from ngAnimate instead.
*/
interface ITransitionService {
/**
* The browser specific animation event name.
+62 -3
View File
@@ -14,12 +14,28 @@ myApp.config((
var matcher: ng.ui.IUrlMatcher = $urlMatcherFactory.compile("/foo/:bar?param1");
$urlMatcherFactory.caseInsensitive(false);
var isCaseInsensitive = $urlMatcherFactory.caseInsensitive();
$urlMatcherFactory.defaultSquashPolicy("nosquash");
$urlMatcherFactory.strictMode(true);
var isStrictMode = $urlMatcherFactory.strictMode();
$urlMatcherFactory.type("myType2", {
encode: function (item: any) { return item; },
decode: function (item: any) { return item; },
is: function (item: any) { return true; }
});
$urlMatcherFactory.type("fullType", {
decode: (val) => parseInt(val, 10),
encode: (val) => val && val.toString(),
equals: (a, b) => this.is(a) && a === b,
is: (val) => angular.isNumber(val) && isFinite(val) && val % 1 === 0,
pattern: /\d+/
});
var obj: Object = matcher.exec('/user/bob', { x:'1', q:'hello' });
var concat: ng.ui.IUrlMatcher = matcher.concat('/test');
var str: string = matcher.format({ id:'bob', q:'yes' });
@@ -50,7 +66,7 @@ myApp.config((
.state('state1.list', {
url: "/list",
templateUrl: "partials/state1.list.html",
controller: function ($scope: MyAppScope) {
controller: function ($scope: MyAppScope) {
$scope.items = ["A", "List", "Of", "Items"];
}
})
@@ -61,7 +77,7 @@ myApp.config((
.state('state2.list', {
url: "/list",
templateUrl: "partials/state2.list.html",
controller: function ($scope: MyAppScope) {
controller: function ($scope: MyAppScope) {
$scope.things = ["A", "Set", "Of", "Things"];
}
})
@@ -70,7 +86,14 @@ myApp.config((
url: "/list",
templateUrl: "partials/state3.list.html",
controller: function ($scope: MyAppScope) {
$scope.things = ["A", "Set", "Of", "Things"];
$scope.things = ["A", "Set", "Of", "Things"];
}
})
.state('state4', {
url: "/state4",
templateUrl: function($stateParams: ng.ui.IStateParamsService){
//Logic could go here based on $stateParams
return "partials/state4.html";
}
})
.state('index', {
@@ -148,6 +171,10 @@ class UrlLocatorTestService implements IUrlLocatorTestService {
this.$state.get("myState");
this.$state.get();
this.$state.reload();
// Accesses the currently resolved values for the current state
// http://stackoverflow.com/questions/28026620/is-there-a-way-to-access-resolved-state-dependencies-besides-injecting-them-into/28027023#28027023
var resolvedValues = this.$state.$current.locals.globals;
}
}
@@ -166,3 +193,35 @@ module UiViewScrollProviderTests {
$uiViewScrollProvider.useAnchorScroll();
}]);
}
interface ITestUserService {
isLoggedIn: () => boolean;
handleLogin: () => ng.IPromise<{}>;
}
module UrlRouterProviderTests {
var app = angular.module("urlRouterProviderTests", ["ui.router"]);
app.config(($urlRouterProvider: ng.ui.IUrlRouterProvider) => {
// Prevent $urlRouter from automatically intercepting URL changes;
// this allows you to configure custom behavior in between
// location changes and route synchronization:
$urlRouterProvider.deferIntercept();
}).run(($rootScope: ng.IRootScopeService, $urlRouter: ng.ui.IUrlRouterService, UserService: ITestUserService) => {
$rootScope.$on('$locationChangeSuccess', e => {
// UserService is an example service for managing user state
if (UserService.isLoggedIn()) return;
// Prevent $urlRouter's default handler from firing
e.preventDefault();
UserService.handleLogin().then(() => {
// Once the user has logged in, sync the current URL to the router:
$urlRouter.sync();
});
});
// Configures $urlRouter's listener *after* your custom listener
$urlRouter.listen();
});
}
+137 -7
View File
@@ -5,6 +5,12 @@
/// <reference path="../angularjs/angular.d.ts" />
// Support for AMD require
declare module 'angular-ui-router' {
var _: string;
export = _;
}
declare module angular.ui {
interface IState {
@@ -16,11 +22,11 @@ declare module angular.ui {
/**
* String URL path to template file OR Function, returns URL path string
*/
templateUrl?: string | {(): string};
templateUrl?: string | {(params: IStateParamsService): string};
/**
* Function, returns HTML content string
*/
templateProvider?: Function;
templateProvider?: Function | Array<any>;
/**
* A controller paired to the state. Function OR name as String
*/
@@ -41,7 +47,7 @@ declare module angular.ui {
/**
* A url with optional parameters. When a state is navigated or transitioned to, the $stateParams service will be populated with any parameters that were passed.
*/
url?: string;
url?: string | IUrlMatcher;
/**
* A map which optionally configures parameters declared in the url, or defines additional non-url parameters. Only use this within a state if you are not using url. Otherwise you can specify your parameters within the url. When a state is navigated or transitioned to, the $stateParams service will be populated with any parameters that were passed.
*/
@@ -53,12 +59,12 @@ declare module angular.ui {
abstract?: boolean;
/**
* Callback function for when a state is entered. Good way to trigger an action or dispatch an event, such as opening a dialog.
* If minifying your scripts, make sure to explictly annotate this function, because it won't be automatically annotated by your build tools.
* If minifying your scripts, make sure to explicitly annotate this function, because it won't be automatically annotated by your build tools.
*/
onEnter?: Function|(string|Function)[];
/**
* Callback functions for when a state is entered and exited. Good way to trigger an action or dispatch an event, such as opening a dialog.
* If minifying your scripts, make sure to explictly annotate this function, because it won't be automatically annotated by your build tools.
* If minifying your scripts, make sure to explicitly annotate this function, because it won't be automatically annotated by your build tools.
*/
onExit?: Function|(string|Function)[];
/**
@@ -66,7 +72,7 @@ declare module angular.ui {
*/
data?: any;
/**
* Boolean (default true). If false will not retrigger the same state just because a search/query parameter has changed. Useful for when you'd like to modify $location.search() without triggering a reload.
* Boolean (default true). If false will not re-trigger the same state just because a search/query parameter has changed. Useful for when you'd like to modify $location.search() without triggering a reload.
*/
reloadOnSearch?: boolean;
}
@@ -85,9 +91,70 @@ declare module angular.ui {
}
interface IUrlMatcherFactory {
/**
* Creates a UrlMatcher for the specified pattern.
*
* @param pattern {string} The URL pattern.
*
* @returns {IUrlMatcher} The UrlMatcher.
*/
compile(pattern: string): IUrlMatcher;
/**
* Returns true if the specified object is a UrlMatcher, or false otherwise.
*
* @param o {any} The object to perform the type check against.
*
* @returns {boolean} Returns true if the object matches the IUrlMatcher interface, by implementing all the same methods.
*/
isMatcher(o: any): boolean;
type(name: string, definition: any, definitionFn?: any): any;
/**
* Returns a type definition for the specified name
*
* @param name {string} The type definition name
*
* @returns {IType} The type definition
*/
type(name: string): IType;
/**
* Registers a custom Type object that can be used to generate URLs with typed parameters.
*
* @param {IType} definition The type definition.
* @param {any[]} inlineAnnotedDefinitionFn A function that is injected before the app runtime starts. The result of this function is merged into the existing definition.
*
* @returns {IUrlMatcherFactory} Returns $urlMatcherFactoryProvider.
*/
type(name: string, definition: IType, inlineAnnotedDefinitionFn?: any[]): IUrlMatcherFactory;
/**
* Registers a custom Type object that can be used to generate URLs with typed parameters.
*
* @param {IType} definition The type definition.
* @param {any[]} inlineAnnotedDefinitionFn A function that is injected before the app runtime starts. The result of this function is merged into the existing definition.
*
* @returns {IUrlMatcherFactory} Returns $urlMatcherFactoryProvider.
*/
type(name: string, definition: IType, definitionFn?: (...args:any[]) => IType): IUrlMatcherFactory;
/**
* Defines whether URL matching should be case sensitive (the default behavior), or not.
*
* @param value {boolean} false to match URL in a case sensitive manner; otherwise true;
*
* @returns {boolean} the current value of caseInsensitive
*/
caseInsensitive(value?: boolean): boolean;
/**
* Sets the default behavior when generating or matching URLs with default parameter values
*
* @param value {string} A string that defines the default parameter URL squashing behavior. nosquash: When generating an href with a default parameter value, do not squash the parameter value from the URL slash: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the parameter is surrounded by slashes, squash (remove) one slash from the URL any other string, e.g. "~": When generating an href with a default parameter value, squash (remove) the parameter value from the URL and replace it with this string.
*/
defaultSquashPolicy(value: string): void;
/**
* Defines whether URLs should match trailing slashes, or not (the default behavior).
*
* @param value {boolean} false to match trailing slashes in URLs, otherwise true.
*
* @returns {boolean} the current value of strictMode
*/
strictMode(value?: boolean): boolean;
}
interface IUrlRouterProvider extends angular.IServiceProvider {
@@ -105,6 +172,14 @@ declare module angular.ui {
otherwise(path: string): IUrlRouterProvider;
rule(handler: Function): IUrlRouterProvider;
rule(handler: any[]): IUrlRouterProvider;
/**
* Disables (or enables) deferring location change interception.
*
* If you wish to customize the behavior of syncing the URL (for example, if you wish to defer a transition but maintain the current URL), call this method at configuration time. Then, at run time, call $urlRouter.listen() after you have configured your own $locationChangeSuccess event handler.
*
* @param {boolean} defer Indicates whether to defer location change interception. Passing no parameter is equivalent to true.
*/
deferIntercept(defer?: boolean): void;
}
interface IStateOptions {
@@ -165,6 +240,17 @@ declare module angular.ui {
current: IState;
params: IStateParamsService;
reload(): void;
$current: IResolvedState;
}
interface IResolvedState {
locals: {
/**
* Currently resolved "resolve" values from the current state
*/
globals: { [key: string]: any; };
};
}
interface IStateParamsService {
@@ -183,6 +269,7 @@ declare module angular.ui {
*
*/
sync(): void;
listen(): void;
}
interface IUiViewScrollProvider {
@@ -192,4 +279,47 @@ declare module angular.ui {
*/
useAnchorScroll(): void;
}
interface IType {
/**
* Converts a parameter value (from URL string or transition param) to a custom/native value.
*
* @param val {string} The URL parameter value to decode.
* @param key {string} The name of the parameter in which val is stored. Can be used for meta-programming of Type objects.
*
* @returns {any} Returns a custom representation of the URL parameter value.
*/
decode(val: string, key: string): any;
/**
* Encodes a custom/native type value to a string that can be embedded in a URL. Note that the return value does not need to be URL-safe (i.e. passed through encodeURIComponent()), it only needs to be a representation of val that has been coerced to a string.
*
* @param val {any} The value to encode.
* @param key {string} The name of the parameter in which val is stored. Can be used for meta-programming of Type objects.
*
* @returns {string} Returns a string representation of val that can be encoded in a URL.
*/
encode(val: any, key: string): string;
/**
* Determines whether two decoded values are equivalent.
*
* @param a {any} A value to compare against.
* @param b {any} A value to compare against.
*
* @returns {boolean} Returns true if the values are equivalent/equal, otherwise false.
*/
equals? (a: any, b: any): boolean;
/**
* Detects whether a value is of a particular type. Accepts a native (decoded) value and determines whether it matches the current Type object.
*
* @param val {any} The value to check.
* @param key {any} Optional. If the type check is happening in the context of a specific UrlMatcher object, this is the name of the parameter in which val is stored. Can be used for meta-programming of Type objects.
*
* @returns {boolean} Returns true if the value matches the type, otherwise false.
*/
is(val: any, key: string): boolean;
/**
* The regular expression pattern used to match values of this type when coming from a substring of a URL.
*/
pattern?: RegExp;
}
}
@@ -0,0 +1,93 @@
/// <reference path="angular-ui-scroll.d.ts" />
var myApp = angular.module('application', ['ui.scroll', 'ui.scroll.jqlite']);
module application {
interface IItem {
id: number;
content: string;
}
class DatasourceTest implements ng.ui.IScrollDatasource<IItem> {
get(index: number, count: number, success: (results: IItem[]) => void): void {
var ret = new Array<IItem>();
for (var i=0; i < count; i++) {
ret.push({id: i, content: 'item ' + i.toString()});
}
success(ret);
}
}
function factory(): any {
return DatasourceTest;
}
myApp.factory('DatasourceTest', factory);
// demo/examples/adapter
myApp.controller('mainController', ['$scope', 'DatasourceTest', function($scope: ng.IScope, datasource: DatasourceTest) {
var firstListAdapter: ng.ui.IScrollAdapter, secondListAdapter: ng.ui.IScrollAdapter;
$scope['datasource'] = datasource;
$scope['updateList1'] = (): void => {
firstListAdapter.applyUpdates( (item: IItem, scope: ng.IRepeatScope) => {
return item.content += ' *';
})
};
$scope['removeFromList1'] = (): void => {
firstListAdapter.applyUpdates( (item: IItem, scope: ng.IRepeatScope) => {
if (scope.$index % 2 === 0) {
return []
}
})
};
var idList1: number = 1000;
$scope['addToList1'] = (): void => {
firstListAdapter.applyUpdates((item: IItem, scope: ng.IRepeatScope) => {
var newItem: IItem;
newItem = void 0;
if (scope.$index === 2) {
newItem = {
id: idList1,
content: 'a new one #' + idList1
};
idList1++;
return [item, newItem];
}
});
};
$scope['updateList2'] = (): void => {
secondListAdapter.applyUpdates((item: IItem, scope: ng.IRepeatScope) => {
return item.content += ' *';
});
};
$scope['removeFromList2'] = (): void => {
secondListAdapter.applyUpdates((item: IItem, scope: ng.IRepeatScope) => {
if (scope.$index % 2 !== 0) {
return [];
}
});
};
var idList2: number = 2000;
$scope['addToList2'] = (): void => {
secondListAdapter.applyUpdates((item: IItem, scope: ng.IRepeatScope) => {
var newItem: IItem;
newItem = void 0;
if (scope.$index === 4) {
newItem = {
id: idList2,
content: 'a new one #' + idList1
};
idList2++;
return [item, newItem];
}
});
};
}]);
}
+85
View File
@@ -0,0 +1,85 @@
// Type definitions for Angular JS 1.3.1+ (ui.scroll module)
// Project: https://github.com/angular-ui/ui-scroll
// Definitions by: Mark Nadig <https://github.com/marknadig>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.ui {
interface IScrollDatasource<T> {
/**
* The datasource object implements methods and properties to be used by the directive to access the data
*
* @param index indicates the first data row requested
*
* @param count indicates number of data rows requested
*
* @param success function to call when the data are retrieved. The implementation of the service has to call
* this function when the data are retrieved and pass it an array of the items retrieved. If no items are
* retrieved, an empty array has to be passed.
*
* Important: Make sure to respect the index and count parameters of the request. The array passed to the
* success method should have exactly count elements unless it hit eof/bof
*/
get(index: number, count: number, success: (results: Array<T>) => any): void;
}
interface IScrollAdapter {
/**
* a boolean value indicating whether there are any pending load requests.
*/
isLoading: boolean;
/**
* a reference to the item currently in the topmost visible position.
*/
topVisible: any;
/**
* a reference to the DOM element currently in the topmost visible position.
*/
topVisibleElement: ng.IAugmentedJQueryStatic;
/**
* a reference to the scope created for the item currently in the topmost visible position.
*/
topVisibleScope: ng.IRepeatScope;
/**
* calling this method reinitializes and reloads the scroller content.
*/
reload(): void;
/**
* Replaces the item in the buffer at the given index with the new items.
*
* @param index provides position of the item to be affected in the dataset (not in the buffer). If the item with
* the given index currently is not in the buffer no updates will be applied. $index property of the item $scope
* can be used to access the index value for a given item
*
* @param newItems is an array of items to replace the affected item. If the array is empty ([]) the item will
* be deleted, otherwise the items in the array replace the item. If the newItem array contains the old item,
* the old item stays in place.
*/
applyUpdates(index: number, newItems: any[]): void;
/**
* Replaces the item in the buffer at the given index with the new items.
*
* @param updater is a function to be applied to every item currently in the buffer. The function will receive
* 3 parameters: item, scope, and element. Here item is the item to be affected, scope is the item $scope, and
* element is the html element for the item. The return value of the function should be an array of items.
* Similarly to the newItem parameter (see above), if the array is empty([]), the item is deleted, otherwise
* the item is replaced by the items in the array. If the return value is not an array, the item remains
* unaffected, unless some updates were made to the item in the updater function. This can be thought of as
* in place update.
*/
applyUpdates(updater: (item: any, scope: ng.IRepeatScope) => any): void;
/**
* Adds new items after the last item in the buffer
*
* @param newItems provides an array of items to be appended.
*/
append(newItems: any[]): void;
/**
* Adds new items before the first item in the buffer
*
* @param newItems provides an array of items to be prepended.
*/
prepend(newItems: any[]): void;
}
}
+13
View File
@@ -0,0 +1,13 @@
/// <reference path="angular-ui-tree.d.ts" />
var treeNode: AngularUITree.ITreeNode = {
id: 0,
nodes: [],
title: "test"
};
var treeNode2: AngularUITree.ITreeNode = {
id: "0",
nodes: [treeNode],
title: "test2"
};
+15
View File
@@ -0,0 +1,15 @@
// Type definitions for angular-ui-tree v2.8.0
// Project: https://github.com/angular-ui-tree/angular-ui-tree
// Definitions by: Calvin Fernandez <https://github.com/CalvinFernandez>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module AngularUITree {
/**
* Node in list
*/
interface ITreeNode {
id: number | string;
nodes: ITreeNode[];
title: string;
}
}
@@ -0,0 +1,8 @@
/// <reference path="angular.throttle.d.ts" />
/// <reference path='../angularjs/angular.d.ts' />
var throttledFn = angular.throttle(function (someArg:any) {
return someArg;
}, 100);
var result = throttledFn(10);
+12
View File
@@ -0,0 +1,12 @@
// Type definitions for angular.throttle
// Project: https://github.com/BaggersIO/angular.throttle
// Definitions by: Stefan Steinhart <https://github.com/reppners>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path='../angularjs/angular.d.ts' />
declare module angular {
interface IAngularStatic {
throttle:( fn:Function, throttle:number, options?:{leading?:boolean; trailing?:boolean;} ) => Function;
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+14 -8
View File
@@ -1,7 +1,7 @@
/// <reference path="angular2.d.ts"/>
/// <reference path="router.d.ts"/>
// Use Typescript 1.4 style imports
import ng = require("angular2/angular2");
import {Component, View, Directive, bootstrap, bind, NgFor, NgIf} from "angular2/angular2";
class Service {
@@ -14,15 +14,15 @@ class Cmp {
static annotations: any[];
}
Cmp.annotations = [
ng.Component({
Component({
selector: 'cmp',
injectables: [Service, ng.bind(Service2).toValue(null)]
injectables: [Service, bind(Service2).toValue(null)]
}),
ng.View({
View({
template: '{{greeting}} world!',
directives: [ng.NgFor, ng.NgIf]
directives: [NgFor, NgIf]
}),
ng.Directive({
Directive({
selector: '[tooltip]',
properties: [
'text: tooltip'
@@ -34,4 +34,10 @@ Cmp.annotations = [
})
];
ng.bootstrap(Cmp);
@Component({selector: 'cmp2'})
@View({templateUrl: '/index.html'})
class Cmp2 {
}
bootstrap(Cmp);
+1
View File
@@ -0,0 +1 @@
--experimentalDecorators --target ES5
+4698 -3548
View File
File diff suppressed because it is too large Load Diff
+352
View File
@@ -0,0 +1,352 @@
// Type definitions for Angular v2.0.0-alpha.30
// Project: http://angular.io/
// Definitions by: angular team <https://github.com/angular/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ***********************************************************
// This file is generated by the Angular build process.
// Please do not create manual edits or send pull requests
// modifying this file.
// ***********************************************************
///<reference path="./angular2-2.0.0-alpha.30.d.ts"/>
/**
* @module
* @public
* @description
* Maps application URLs into application states, to support deep-linking and navigation.
*/
declare module ng {
/**
* # Router
* The router is responsible for mapping URLs to components.
*
* You can see the state of the router by inspecting the read-only field `router.navigating`.
* This may be useful for showing a spinner, for instance.
*
* ## Concepts
* Routers and component instances have a 1:1 correspondence.
*
* The router holds reference to a number of "outlets." An outlet is a placeholder that the
* router dynamically fills in depending on the current URL.
*
* When the router navigates from a URL, it must first recognizes it and serialize it into an
* `Instruction`.
* The router uses the `RouteRegistry` to get an `Instruction`.
*
* @exportedAs angular2/router
*/
class Router {
navigating: boolean;
lastNavigationAttempt: string;
previousUrl: string;
registry: RouteRegistry;
parent: Router;
hostComponent: any;
/**
* Constructs a child router. You probably don't need to use this unless you're writing a reusable
* component.
*/
childRouter(hostComponent: any): Router;
/**
* Register an object to notify of route changes. You probably don't need to use this unless
* you're writing a reusable component.
*/
registerOutlet(outlet: RouterOutlet): Promise<boolean>;
/**
* Dynamically update the routing configuration and trigger a navigation.
*
* # Usage
*
* ```
* router.config({ 'path': '/', 'component': IndexCmp});
* ```
*
* Or:
*
* ```
* router.config([
* { 'path': '/', 'component': IndexComp },
* { 'path': '/user/:id', 'component': UserComp },
* ]);
* ```
*/
config(config: StringMap<string, any>| List<StringMap<string, any>>): Promise<any>;
/**
* Navigate to a URL. Returns a promise that resolves when navigation is complete.
*
* If the given URL begins with a `/`, router will navigate absolutely.
* If the given URL does not begin with `/`, the router will navigate relative to this component.
*/
navigate(url: string): Promise<any>;
/**
* Subscribe to URL updates from the router
*/
subscribe(onNext: any): void;
/**
* Updates this router and all descendant routers according to the given instruction
*/
commit(instruction: Instruction): Promise<any>;
/**
* Removes the contents of this router's outlet and all descendant outlets
*/
deactivate(): Promise<any>;
/**
* Given a URL, returns an instruction representing the component graph
*/
recognize(url: string): Promise<Instruction>;
/**
* Navigates to either the last URL successfully navigated to, or the last URL requested if the
* router has yet to successfully navigate.
*/
renavigate(): Promise<any>;
/**
* Generate a URL from a component name and optional map of parameters. The URL is relative to the
* app's base href.
*/
generate(linkParams: List<any>): string;
}
class RootRouter extends Router {
commit(instruction: any): Promise<any>;
}
/**
* A router outlet is a placeholder that Angular dynamically fills based on the application's route.
*
* ## Use
*
* ```
* <router-outlet></router-outlet>
* ```
*/
class RouterOutlet {
/**
* Given an instruction, update the contents of this outlet.
*/
activate(instruction: Instruction): Promise<any>;
deactivate(): Promise<any>;
canDeactivate(instruction: Instruction): Promise<boolean>;
}
/**
* The RouterLink directive lets you link to specific parts of your app.
*
* Consider the following route configuration:
*
* ```
* @RouteConfig({
* path: '/user', component: UserCmp, as: 'user'
* });
* class MyComp {}
* ```
*
* When linking to this `user` route, you can write:
*
* ```
* <a [router-link]="['./user']">link to user component</a>
* ```
*
* RouterLink expects the value to be an array of route names, followed by the params
* for that level of routing. For instance `['/team', {teamId: 1}, 'user', {userId: 2}]`
* means that we want to generate a link for the `team` route with params `{teamId: 1}`,
* and with a child route `user` with params `{userId: 2}`.
*
* The first route name should be prepended with `/`, `./`, or `../`.
* If the route begins with `/`, the router will look up the route from the root of the app.
* If the route begins with `./`, the router will instead look in the current component's
* children for the route. And if the route begins with `../`, the router will look at the
* current component's parent.
*
* @exportedAs angular2/router
*/
class RouterLink {
visibleHref: string;
routeParams: void;
onClick(): boolean;
}
class RouteParams {
params: StringMap<string, string>;
get(param: string): string;
}
/**
* The RouteRegistry holds route configurations for each component in an Angular app.
* It is responsible for creating Instructions from URLs, and generating URLs based on route and
* parameters.
*/
class RouteRegistry {
/**
* Given a component and a configuration object, add the route to this registry
*/
config(parentComponent: any, config: StringMap<string, any>): void;
/**
* Reads the annotations of a component and configures the registry based on them
*/
configFromComponent(component: any): void;
/**
* Given a URL and a parent component, return the most specific instruction for navigating
* the application into the state specified by the url
*/
recognize(url: string, parentComponent: any): Promise<Instruction>;
/**
* Given a normalized list with component names and params like: `['user', {id: 3 }]`
* generates a url with a leading slash relative to the provided `parentComponent`.
*/
generate(linkParams: List<any>, parentComponent: any): string;
}
class LocationStrategy {
path(): string;
pushState(ctx: any, title: string, url: string): void;
forward(): void;
back(): void;
onPopState(fn: any): void;
getBaseHref(): string;
}
class HashLocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
class HTML5LocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
/**
* This is the service that an application developer will directly interact with.
*
* Responsible for normalizing the URL against the application's base href.
* A normalized URL is absolute from the URL host, includes the application's base href, and has no
* trailing slash:
* - `/my/app/user/123` is normalized
* - `my/app/user/123` **is not** normalized
* - `/my/app/user/123/` **is not** normalized
*/
class Location {
path(): string;
normalize(url: string): string;
normalizeAbsolutely(url: string): string;
go(url: string): void;
forward(): void;
back(): void;
subscribe(onNext: any, onThrow?: any, onReturn?: any): void;
}
var appBaseHrefToken : OpaqueToken ;
class Instruction {
reuseComponentsFrom(oldInstruction: Instruction): void;
params(): StringMap<string, string>;
hasChild(): boolean;
}
/**
* Responsible for performing each step of navigation.
* "Steps" are conceptually similar to "middleware"
*/
class Pipeline {
steps: List<Function>;
process(instruction: Instruction): Promise<any>;
}
var routerDirectives : List<any> ;
var routerInjectables : List<any> ;
var RouteConfig:any;
}
declare module "angular2/router" {
export = ng;
}
+459
View File
@@ -0,0 +1,459 @@
// Type definitions for Angular v2.0.0-alpha.31
// Project: http://angular.io/
// Definitions by: angular team <https://github.com/angular/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ***********************************************************
// This file is generated by the Angular build process.
// Please do not create manual edits or send pull requests
// modifying this file.
// ***********************************************************
///<reference path="./angular2.d.ts"/>
/**
* @module
* @description
* Maps application URLs into application states, to support deep-linking and navigation.
*/
declare module ng {
interface List<T> extends Array<T> {}
interface Map<K,V> {}
interface StringMap<K,V> extends Map<K,V> {}
export class Instruction {
// "capturedUrl" is the part of the URL captured by this instruction
// "accumulatedUrl" is the part of the URL captured by this instruction and all children
accumulatedUrl: string;
reuse: boolean;
specificity: number;
private _params: StringMap<string, string>;
constructor (component: any, capturedUrl: string,
_recognizer: PathRecognizer, child: Instruction);
params(): StringMap<string, string>;
}
class TouchMap {
map: StringMap<string, string>;
keys: StringMap<string, boolean>;
constructor(map: StringMap<string, any>);
get(key: string): string;
getUnused(): StringMap<string, any>;
}
export class Segment {
name: string;
regex: string;
generate(params: TouchMap): string;
}
export class PathRecognizer {
segments: List<Segment>;
regex: RegExp;
specificity: number;
terminal: boolean;
path: string;
handler: RouteHandler;
constructor(path: string, handler: RouteHandler);
parseParams(url: string): StringMap<string, string>;
generate(params: StringMap<string, any>): string;
resolveComponentType(): Promise<any>;
}
export interface RouteHandler {
componentType: Function;
resolveComponentType(): Promise<any>;
}
/**
* # Router
* The router is responsible for mapping URLs to components.
*
* You can see the state of the router by inspecting the read-only field `router.navigating`.
* This may be useful for showing a spinner, for instance.
*
* ## Concepts
* Routers and component instances have a 1:1 correspondence.
*
* The router holds reference to a number of "outlets." An outlet is a placeholder that the
* router dynamically fills in depending on the current URL.
*
* When the router navigates from a URL, it must first recognizes it and serialize it into an
* `Instruction`.
* The router uses the `RouteRegistry` to get an `Instruction`.
*/
class Router {
navigating: boolean;
lastNavigationAttempt: string;
registry: RouteRegistry;
parent: Router;
hostComponent: any;
/**
* Constructs a child router. You probably don't need to use this unless you're writing a reusable
* component.
*/
childRouter(hostComponent: any): Router;
/**
* Register an object to notify of route changes. You probably don't need to use this unless
* you're writing a reusable component.
*/
registerOutlet(outlet: RouterOutlet): Promise<boolean>;
/**
* Dynamically update the routing configuration and trigger a navigation.
*
* # Usage
*
* ```
* router.config({ 'path': '/', 'component': IndexCmp});
* ```
*
* Or:
*
* ```
* router.config([
* { 'path': '/', 'component': IndexComp },
* { 'path': '/user/:id', 'component': UserComp },
* ]);
* ```
*/
config(config: StringMap<string, any>| List<StringMap<string, any>>): Promise<any>;
/**
* Navigate to a URL. Returns a promise that resolves when navigation is complete.
*
* If the given URL begins with a `/`, router will navigate absolutely.
* If the given URL does not begin with `/`, the router will navigate relative to this component.
*/
navigate(url: string): Promise<any>;
/**
* Updates this router and all descendant routers according to the given instruction
*/
commit(instruction: Instruction): Promise<any>;
/**
* Subscribe to URL updates from the router
*/
subscribe(onNext: any): void;
/**
* Removes the contents of this router's outlet and all descendant outlets
*/
deactivate(instruction: Instruction): Promise<any>;
/**
* Given a URL, returns an instruction representing the component graph
*/
recognize(url: string): Promise<Instruction>;
/**
* Navigates to either the last URL successfully navigated to, or the last URL requested if the
* router has yet to successfully navigate.
*/
renavigate(): Promise<any>;
/**
* Generate a URL from a component name and optional map of parameters. The URL is relative to the
* app's base href.
*/
generate(linkParams: List<any>): string;
}
class RootRouter extends Router {
commit(instruction: any): Promise<any>;
}
/**
* A router outlet is a placeholder that Angular dynamically fills based on the application's route.
*
* ## Use
*
* ```
* <router-outlet></router-outlet>
* ```
*/
class RouterOutlet {
childRouter: Router;
/**
* Given an instruction, update the contents of this outlet.
*/
commit(instruction: Instruction): Promise<any>;
/**
* Called by Router during recognition phase
*/
canDeactivate(nextInstruction: Instruction): Promise<boolean>;
/**
* Called by Router during recognition phase
*/
canReuse(nextInstruction: Instruction): Promise<boolean>;
deactivate(nextInstruction: Instruction): Promise<any>;
}
/**
* The RouterLink directive lets you link to specific parts of your app.
*
* Consider the following route configuration:
*
* ```
* @RouteConfig({
* path: '/user', component: UserCmp, as: 'user'
* });
* class MyComp {}
* ```
*
* When linking to this `user` route, you can write:
*
* ```
* <a [router-link]="['./user']">link to user component</a>
* ```
*
* RouterLink expects the value to be an array of route names, followed by the params
* for that level of routing. For instance `['/team', {teamId: 1}, 'user', {userId: 2}]`
* means that we want to generate a link for the `team` route with params `{teamId: 1}`,
* and with a child route `user` with params `{userId: 2}`.
*
* The first route name should be prepended with `/`, `./`, or `../`.
* If the route begins with `/`, the router will look up the route from the root of the app.
* If the route begins with `./`, the router will instead look in the current component's
* children for the route. And if the route begins with `../`, the router will look at the
* current component's parent.
*/
class RouterLink {
visibleHref: string;
routeParams: void;
onClick(): boolean;
}
class RouteParams {
params: StringMap<string, string>;
get(param: string): string;
}
/**
* The RouteRegistry holds route configurations for each component in an Angular app.
* It is responsible for creating Instructions from URLs, and generating URLs based on route and
* parameters.
*/
class RouteRegistry {
/**
* Given a component and a configuration object, add the route to this registry
*/
config(parentComponent: any, config: StringMap<string, any>): void;
/**
* Reads the annotations of a component and configures the registry based on them
*/
configFromComponent(component: any): void;
/**
* Given a URL and a parent component, return the most specific instruction for navigating
* the application into the state specified by the url
*/
recognize(url: string, parentComponent: any): Promise<Instruction>;
/**
* Given a normalized list with component names and params like: `['user', {id: 3 }]`
* generates a url with a leading slash relative to the provided `parentComponent`.
*/
generate(linkParams: List<any>, parentComponent: any): string;
}
class LocationStrategy {
path(): string;
pushState(ctx: any, title: string, url: string): void;
forward(): void;
back(): void;
onPopState(fn: any): void;
getBaseHref(): string;
}
class HashLocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
class HTML5LocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
/**
* This is the service that an application developer will directly interact with.
*
* Responsible for normalizing the URL against the application's base href.
* A normalized URL is absolute from the URL host, includes the application's base href, and has no
* trailing slash:
* - `/my/app/user/123` is normalized
* - `my/app/user/123` **is not** normalized
* - `/my/app/user/123/` **is not** normalized
*/
class Location {
path(): string;
normalize(url: string): string;
normalizeAbsolutely(url: string): string;
go(url: string): void;
forward(): void;
back(): void;
subscribe(onNext: any, onThrow?: any, onReturn?: any): void;
}
var appBaseHrefToken : OpaqueToken ;
/**
* Responsible for performing each step of navigation.
* "Steps" are conceptually similar to "middleware"
*/
class Pipeline {
steps: List<Function>;
process(instruction: Instruction): Promise<any>;
}
/**
* Defines route lifecycle method [onActivate]
*/
interface OnActivate {
onActivate(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
/**
* Defines route lifecycle method [onDeactivate]
*/
interface OnDeactivate {
onDeactivate(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
/**
* Defines route lifecycle method [onReuse]
*/
interface OnReuse {
onReuse(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
/**
* Defines route lifecycle method [canDeactivate]
*/
interface CanDeactivate {
canDeactivate(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
/**
* Defines route lifecycle method [canReuse]
*/
interface CanReuse {
canReuse(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
var CanActivate:any;
var routerDirectives : List<any> ;
var routerInjectables : List<any> ;
var RouteConfig:any;
}
declare module "angular2/router" {
export = ng;
}
+469
View File
@@ -0,0 +1,469 @@
// Type definitions for Angular v2.0.0-alpha.34
// Project: http://angular.io/
// Definitions by: angular team <https://github.com/angular/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ***********************************************************
// This file is generated by the Angular build process.
// Please do not create manual edits or send pull requests
// modifying this file.
// ***********************************************************
///<reference path="./angular2-2.0.0-alpha.34.d.ts"/>
/**
* @module
* @description
* Maps application URLs into application states, to support deep-linking and navigation.
*/
declare module ng {
/**
* # Router
* The router is responsible for mapping URLs to components.
*
* You can see the state of the router by inspecting the read-only field `router.navigating`.
* This may be useful for showing a spinner, for instance.
*
* ## Concepts
* Routers and component instances have a 1:1 correspondence.
*
* The router holds reference to a number of "outlets." An outlet is a placeholder that the
* router dynamically fills in depending on the current URL.
*
* When the router navigates from a URL, it must first recognizes it and serialize it into an
* `Instruction`.
* The router uses the `RouteRegistry` to get an `Instruction`.
*/
class Router {
navigating: boolean;
lastNavigationAttempt: string;
registry: RouteRegistry;
parent: Router;
hostComponent: any;
/**
* Constructs a child router. You probably don't need to use this unless you're writing a reusable
* component.
*/
childRouter(hostComponent: any): Router;
/**
* Register an object to notify of route changes. You probably don't need to use this unless
* you're writing a reusable component.
*/
registerOutlet(outlet: RouterOutlet): Promise<boolean>;
/**
* Dynamically update the routing configuration and trigger a navigation.
*
* # Usage
*
* ```
* router.config([
* { 'path': '/', 'component': IndexComp },
* { 'path': '/user/:id', 'component': UserComp },
* ]);
* ```
*/
config(definitions: List<RouteDefinition>): Promise<any>;
/**
* Navigate to a URL. Returns a promise that resolves when navigation is complete.
*
* If the given URL begins with a `/`, router will navigate absolutely.
* If the given URL does not begin with `/`, the router will navigate relative to this component.
*/
navigate(url: string, _skipLocationChange?: boolean): Promise<any>;
/**
* Updates this router and all descendant routers according to the given instruction
*/
commit(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
/**
* Subscribe to URL updates from the router
*/
subscribe(onNext: (value: any) => void): void;
/**
* Removes the contents of this router's outlet and all descendant outlets
*/
deactivate(instruction: Instruction): Promise<any>;
/**
* Given a URL, returns an instruction representing the component graph
*/
recognize(url: string): Promise<Instruction>;
/**
* Navigates to either the last URL successfully navigated to, or the last URL requested if the
* router has yet to successfully navigate.
*/
renavigate(): Promise<any>;
/**
* Generate a URL from a component name and optional map of parameters. The URL is relative to the
* app's base href.
*/
generate(linkParams: List<any>): string;
}
class RootRouter extends Router {
commit(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
}
/**
* A router outlet is a placeholder that Angular dynamically fills based on the application's route.
*
* ## Use
*
* ```
* <router-outlet></router-outlet>
* ```
*/
class RouterOutlet {
childRouter: Router;
/**
* Given an instruction, update the contents of this outlet.
*/
commit(instruction: Instruction): Promise<any>;
/**
* Called by Router during recognition phase
*/
canDeactivate(nextInstruction: Instruction): Promise<boolean>;
/**
* Called by Router during recognition phase
*/
canReuse(nextInstruction: Instruction): Promise<boolean>;
deactivate(nextInstruction: Instruction): Promise<any>;
}
/**
* The RouterLink directive lets you link to specific parts of your app.
*
* Consider the following route configuration:
*
* ```
* @RouteConfig([
* { path: '/user', component: UserCmp, as: 'user' }
* ]);
* class MyComp {}
* ```
*
* When linking to this `user` route, you can write:
*
* ```
* <a [router-link]="['./user']">link to user component</a>
* ```
*
* RouterLink expects the value to be an array of route names, followed by the params
* for that level of routing. For instance `['/team', {teamId: 1}, 'user', {userId: 2}]`
* means that we want to generate a link for the `team` route with params `{teamId: 1}`,
* and with a child route `user` with params `{userId: 2}`.
*
* The first route name should be prepended with `/`, `./`, or `../`.
* If the route begins with `/`, the router will look up the route from the root of the app.
* If the route begins with `./`, the router will instead look in the current component's
* children for the route. And if the route begins with `../`, the router will look at the
* current component's parent.
*/
class RouterLink {
visibleHref: string;
routeParams: void;
onClick(): boolean;
}
class RouteParams {
params: StringMap<string, string>;
get(param: string): string;
}
/**
* The RouteRegistry holds route configurations for each component in an Angular app.
* It is responsible for creating Instructions from URLs, and generating URLs based on route and
* parameters.
*/
class RouteRegistry {
/**
* Given a component and a configuration object, add the route to this registry
*/
config(parentComponent: any, config: RouteDefinition, isRootLevelRoute?: boolean): void;
/**
* Reads the annotations of a component and configures the registry based on them
*/
configFromComponent(component: any, isRootComponent?: boolean): void;
/**
* Given a URL and a parent component, return the most specific instruction for navigating
* the application into the state specified by the url
*/
recognize(url: string, parentComponent: any): Promise<Instruction>;
/**
* Given a normalized list with component names and params like: `['user', {id: 3 }]`
* generates a url with a leading slash relative to the provided `parentComponent`.
*/
generate(linkParams: List<any>, parentComponent: any): string;
}
class LocationStrategy {
path(): string;
pushState(ctx: any, title: string, url: string): void;
forward(): void;
back(): void;
onPopState(fn: (_: any) => any): void;
getBaseHref(): string;
}
class HashLocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
class HTML5LocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
/**
* This is the service that an application developer will directly interact with.
*
* Responsible for normalizing the URL against the application's base href.
* A normalized URL is absolute from the URL host, includes the application's base href, and has no
* trailing slash:
* - `/my/app/user/123` is normalized
* - `my/app/user/123` **is not** normalized
* - `/my/app/user/123/` **is not** normalized
*/
class Location {
path(): string;
normalize(url: string): string;
normalizeAbsolutely(url: string): string;
go(url: string): void;
forward(): void;
back(): void;
subscribe(onNext: (value: any) => void, onThrow?: (exception: any) => void, onReturn?: () => void): void;
}
const appBaseHrefToken : OpaqueToken ;
/**
* Responsible for performing each step of navigation.
* "Steps" are conceptually similar to "middleware"
*/
class Pipeline {
steps: List<Function>;
process(instruction: Instruction): Promise<any>;
}
/**
* Defines route lifecycle method [onActivate]
*/
interface OnActivate {
onActivate(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
/**
* Defines route lifecycle method [onDeactivate]
*/
interface OnDeactivate {
onDeactivate(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
/**
* Defines route lifecycle method [onReuse]
*/
interface OnReuse {
onReuse(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
/**
* Defines route lifecycle method [canDeactivate]
*/
interface CanDeactivate {
canDeactivate(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
/**
* Defines route lifecycle method [canReuse]
*/
interface CanReuse {
canReuse(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
var CanActivate : (hook: (next: Instruction, prev: Instruction) => Promise<boolean>| boolean) => ClassDecorator ;
/**
* An `Instruction` represents the component hierarchy of the application based on a given route
*/
class Instruction {
accumulatedUrl: string;
reuse: boolean;
specificity: number;
component: any;
capturedUrl: string;
child: Instruction;
params(): StringMap<string, string>;
}
const routerDirectives : List<any> ;
var routerInjectables : List<any> ;
class Route implements RouteDefinition {
path: string;
component: Type;
as: string;
loader: Function;
redirectTo: string;
}
class Redirect implements RouteDefinition {
path: string;
redirectTo: string;
as: string;
}
class AsyncRoute implements RouteDefinition {
path: string;
loader: Function;
as: string;
}
interface RouteDefinition {
path: string;
component?: Type | ComponentDefinition;
loader?: Function;
redirectTo?: string;
as?: string;
}
var RouteConfig : (configs: List<RouteDefinition>) => ClassDecorator ;
interface ComponentDefinition {
type: string;
loader?: Function;
component?: Type;
}
}
declare module "angular2/router" {
export = ng;
}
+689
View File
@@ -0,0 +1,689 @@
// Type definitions for Angular v2.0.0-alpha.35
// Project: http://angular.io/
// Definitions by: angular team <https://github.com/angular/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ***********************************************************
// This file is generated by the Angular build process.
// Please do not create manual edits or send pull requests
// modifying this file.
// ***********************************************************
// angular2/router depends transitively on these libraries.
// If you don't have them installed you can install them using TSD
// https://github.com/DefinitelyTyped/tsd
///<reference path="./angular2.d.ts"/>
/**
* @module
* @description
* Maps application URLs into application states, to support deep-linking and navigation.
*/
declare module ngRouter {
/**
* # Router
* The router is responsible for mapping URLs to components.
*
* You can see the state of the router by inspecting the read-only field `router.navigating`.
* This may be useful for showing a spinner, for instance.
*
* ## Concepts
* Routers and component instances have a 1:1 correspondence.
*
* The router holds reference to a number of "outlets." An outlet is a placeholder that the
* router dynamically fills in depending on the current URL.
*
* When the router navigates from a URL, it must first recognizes it and serialize it into an
* `Instruction`.
* The router uses the `RouteRegistry` to get an `Instruction`.
*/
class Router {
navigating: boolean;
lastNavigationAttempt: string;
registry: RouteRegistry;
parent: Router;
hostComponent: any;
/**
* Constructs a child router. You probably don't need to use this unless you're writing a reusable
* component.
*/
childRouter(hostComponent: any): Router;
/**
* Register an object to notify of route changes. You probably don't need to use this unless
* you're writing a reusable component.
*/
registerOutlet(outlet: RouterOutlet): Promise<boolean>;
/**
* Dynamically update the routing configuration and trigger a navigation.
*
* # Usage
*
* ```
* router.config([
* { 'path': '/', 'component': IndexComp },
* { 'path': '/user/:id', 'component': UserComp },
* ]);
* ```
*/
config(definitions: List<RouteDefinition>): Promise<any>;
/**
* Navigate to a URL. Returns a promise that resolves when navigation is complete.
*
* If the given URL begins with a `/`, router will navigate absolutely.
* If the given URL does not begin with `/`, the router will navigate relative to this component.
*/
navigate(url: string, _skipLocationChange?: boolean): Promise<any>;
/**
* Navigate via the provided instruction. Returns a promise that resolves when navigation is
* complete.
*/
navigateInstruction(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
/**
* Updates this router and all descendant routers according to the given instruction
*/
commit(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
/**
* Subscribe to URL updates from the router
*/
subscribe(onNext: (value: any) => void): void;
/**
* Removes the contents of this router's outlet and all descendant outlets
*/
deactivate(instruction: Instruction): Promise<any>;
/**
* Given a URL, returns an instruction representing the component graph
*/
recognize(url: string): Promise<Instruction>;
/**
* Navigates to either the last URL successfully navigated to, or the last URL requested if the
* router has yet to successfully navigate.
*/
renavigate(): Promise<any>;
/**
* Generate a URL from a component name and optional map of parameters. The URL is relative to the
* app's base href.
*/
generate(linkParams: List<any>): Instruction;
}
class RootRouter extends Router {
commit(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
}
/**
* A router outlet is a placeholder that Angular dynamically fills based on the application's route.
*
* ## Use
*
* ```
* <router-outlet></router-outlet>
* ```
*/
class RouterOutlet {
childRouter: Router;
name: string;
/**
* Given an instruction, update the contents of this outlet.
*/
commit(instruction: Instruction): Promise<any>;
/**
* Called by Router during recognition phase
*/
canDeactivate(nextInstruction: Instruction): Promise<boolean>;
/**
* Called by Router during recognition phase
*/
canReuse(nextInstruction: Instruction): Promise<boolean>;
deactivate(nextInstruction: Instruction): Promise<any>;
}
/**
* The RouterLink directive lets you link to specific parts of your app.
*
* Consider the following route configuration:
*
* ```
* @RouteConfig([
* { path: '/user', component: UserCmp, as: 'user' }
* ]);
* class MyComp {}
* ```
*
* When linking to this `user` route, you can write:
*
* ```
* <a [router-link]="['./user']">link to user component</a>
* ```
*
* RouterLink expects the value to be an array of route names, followed by the params
* for that level of routing. For instance `['/team', {teamId: 1}, 'user', {userId: 2}]`
* means that we want to generate a link for the `team` route with params `{teamId: 1}`,
* and with a child route `user` with params `{userId: 2}`.
*
* The first route name should be prepended with `/`, `./`, or `../`.
* If the route begins with `/`, the router will look up the route from the root of the app.
* If the route begins with `./`, the router will instead look in the current component's
* children for the route. And if the route begins with `../`, the router will look at the
* current component's parent.
*/
class RouterLink {
visibleHref: string;
routeParams: void;
onClick(): boolean;
}
class RouteParams {
params: StringMap<string, string>;
get(param: string): string;
}
/**
* The RouteRegistry holds route configurations for each component in an Angular app.
* It is responsible for creating Instructions from URLs, and generating URLs based on route and
* parameters.
*/
class RouteRegistry {
/**
* Given a component and a configuration object, add the route to this registry
*/
config(parentComponent: any, config: RouteDefinition): void;
/**
* Reads the annotations of a component and configures the registry based on them
*/
configFromComponent(component: any): void;
/**
* Given a URL and a parent component, return the most specific instruction for navigating
* the application into the state specified by the url
*/
recognize(url: string, parentComponent: any): Promise<Instruction>;
/**
* Given a normalized list with component names and params like: `['user', {id: 3 }]`
* generates a url with a leading slash relative to the provided `parentComponent`.
*/
generate(linkParams: List<any>, parentComponent: any): Instruction;
}
class LocationStrategy {
path(): string;
pushState(ctx: any, title: string, url: string): void;
forward(): void;
back(): void;
onPopState(fn: (_: any) => any): void;
getBaseHref(): string;
}
class HashLocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
class HTML5LocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
/**
* This is the service that an application developer will directly interact with.
*
* Responsible for normalizing the URL against the application's base href.
* A normalized URL is absolute from the URL host, includes the application's base href, and has no
* trailing slash:
* - `/my/app/user/123` is normalized
* - `my/app/user/123` **is not** normalized
* - `/my/app/user/123/` **is not** normalized
*/
class Location {
path(): string;
normalize(url: string): string;
normalizeAbsolutely(url: string): string;
go(url: string): void;
forward(): void;
back(): void;
subscribe(onNext: (value: any) => void, onThrow?: (exception: any) => void, onReturn?: () => void): void;
}
const APP_BASE_HREF : OpaqueToken ;
/**
* Responsible for performing each step of navigation.
* "Steps" are conceptually similar to "middleware"
*/
class Pipeline {
steps: List<Function>;
process(instruction: Instruction): Promise<any>;
}
/**
* Defines route lifecycle method [onActivate], which is called by the router at the end of a
* successful route navigation.
*
* For a single component's navigation, only one of either [onActivate] or [onReuse] will be called,
* depending on the result of [canReuse].
*
* If `onActivate` returns a promise, the route change will wait until the promise settles to
* instantiate and activate child components.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements OnActivate {
* onActivate(next, prev) {
* this.log = 'Finished navigating from ' + prev.urlPath + ' to ' + next.urlPath;
* }
* }
* ```
*/
interface OnActivate {
onActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [onDeactivate], which is called by the router before destroying
* a component as part of a route change.
*
* If `onDeactivate` returns a promise, the route change will wait until the promise settles.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse() {
* return true;
* }
*
* onReuse(next, prev) {
* this.params = next.params;
* }
* }
* ```
*/
interface OnDeactivate {
onDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [onReuse], which is called by the router at the end of a
* successful route navigation when [canReuse] is implemented and returns or resolves to true.
*
* For a single component's navigation, only one of either [onActivate] or [onReuse] will be called,
* depending on the result of [canReuse].
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse() {
* return true;
* }
*
* onReuse(next, prev) {
* this.params = next.params;
* }
* }
* ```
*/
interface OnReuse {
onReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canDeactivate], which is called by the router to determine
* if a component can be removed as part of a navigation.
*
* If `canDeactivate` returns or resolves to `false`, the navigation is cancelled.
*
* If `canDeactivate` throws or rejects, the navigation is also cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanDeactivate {
* canDeactivate(next, prev) {
* return askUserIfTheyAreSureTheyWantToQuit();
* }
* }
* ```
*/
interface CanDeactivate {
canDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canReuse], which is called by the router to determine whether a
* component should be reused across routes, or whether to destroy and instantiate a new component.
*
* If `canReuse` returns or resolves to `true`, the component instance will be reused.
*
* If `canReuse` throws or rejects, the navigation will be cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse(next, prev) {
* return next.params.id == prev.params.id;
* }
*
* onReuse(next, prev) {
* this.id = next.params.id;
* }
* }
* ```
*/
interface CanReuse {
canReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canActivate], which is called by the router to determine
* if a component can be instantiated as part of a navigation.
*
* Note that unlike other lifecycle hooks, this one uses an annotation rather than an interface.
* This is because [canActivate] is called before the component is instantiated.
*
* If `canActivate` returns or resolves to `false`, the navigation is cancelled.
*
* If `canActivate` throws or rejects, the navigation is also cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'control-panel-cmp'
* })
* @CanActivate(() => checkIfUserIsLoggedIn())
* class ControlPanelCmp {
* // ...
* }
* ```
*/
var CanActivate : (hook: (next: ComponentInstruction, prev: ComponentInstruction) => Promise<boolean>| boolean) =>
ClassDecorator ;
/**
* `Instruction` is a tree of `ComponentInstructions`, with all the information needed
* to transition each component in the app to a given route, including all auxiliary routes.
*
* This is a public API.
*/
class Instruction {
component: ComponentInstruction;
child: Instruction;
auxInstruction: StringMap<string, Instruction>;
replaceChild(child: Instruction): Instruction;
}
/**
* A `ComponentInstruction` represents the route state for a single component. An `Instruction` is
* composed of a tree of these `ComponentInstruction`s.
*
* `ComponentInstructions` is a public API. Instances of `ComponentInstruction` are passed
* to route lifecycle hooks, like {@link CanActivate}.
*/
class ComponentInstruction {
reuse: boolean;
urlPath: string;
urlParams: List<string>;
params: StringMap<string, any>;
componentType: void;
resolveComponentType(): Promise<Type>;
specificity: void;
terminal: void;
routeData(): Object;
}
class Url {
path: string;
child: Url;
auxiliary: List<Url>;
params: StringMap<string, any>;
toString(): string;
segmentToString(): string;
}
class OpaqueToken {
toString(): string;
}
/**
* Runtime representation of a type.
*
* In JavaScript a Type is a constructor function.
*/
interface Type extends Function {
new(args: any): any;
}
const routerDirectives : List<any> ;
var routerInjectables : List<any> ;
class Route implements RouteDefinition {
data: any;
path: string;
component: Type;
as: string;
loader: Function;
redirectTo: string;
}
class Redirect implements RouteDefinition {
path: string;
redirectTo: string;
as: string;
loader: Function;
data: any;
}
class AuxRoute implements RouteDefinition {
data: any;
path: string;
component: Type;
as: string;
loader: Function;
redirectTo: string;
}
class AsyncRoute implements RouteDefinition {
data: any;
path: string;
loader: Function;
as: string;
}
interface RouteDefinition {
path: string;
component?: Type | ComponentDefinition;
loader?: Function;
redirectTo?: string;
as?: string;
data?: any;
}
const ROUTE_DATA : OpaqueToken ;
var RouteConfig : (configs: List<RouteDefinition>) => ClassDecorator ;
interface ComponentDefinition {
type: string;
loader?: Function;
component?: Type;
}
}
declare module "angular2/router" {
export = ngRouter;
}
+689
View File
@@ -0,0 +1,689 @@
// Type definitions for Angular v2.0.0-alpha.35
// Project: http://angular.io/
// Definitions by: angular team <https://github.com/angular/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ***********************************************************
// This file is generated by the Angular build process.
// Please do not create manual edits or send pull requests
// modifying this file.
// ***********************************************************
// angular2/router depends transitively on these libraries.
// If you don't have them installed you can install them using TSD
// https://github.com/DefinitelyTyped/tsd
///<reference path="./angular2.d.ts"/>
/**
* @module
* @description
* Maps application URLs into application states, to support deep-linking and navigation.
*/
declare module ngRouter {
/**
* # Router
* The router is responsible for mapping URLs to components.
*
* You can see the state of the router by inspecting the read-only field `router.navigating`.
* This may be useful for showing a spinner, for instance.
*
* ## Concepts
* Routers and component instances have a 1:1 correspondence.
*
* The router holds reference to a number of "outlets." An outlet is a placeholder that the
* router dynamically fills in depending on the current URL.
*
* When the router navigates from a URL, it must first recognizes it and serialize it into an
* `Instruction`.
* The router uses the `RouteRegistry` to get an `Instruction`.
*/
class Router {
navigating: boolean;
lastNavigationAttempt: string;
registry: RouteRegistry;
parent: Router;
hostComponent: any;
/**
* Constructs a child router. You probably don't need to use this unless you're writing a reusable
* component.
*/
childRouter(hostComponent: any): Router;
/**
* Register an object to notify of route changes. You probably don't need to use this unless
* you're writing a reusable component.
*/
registerOutlet(outlet: RouterOutlet): Promise<boolean>;
/**
* Dynamically update the routing configuration and trigger a navigation.
*
* # Usage
*
* ```
* router.config([
* { 'path': '/', 'component': IndexComp },
* { 'path': '/user/:id', 'component': UserComp },
* ]);
* ```
*/
config(definitions: List<RouteDefinition>): Promise<any>;
/**
* Navigate to a URL. Returns a promise that resolves when navigation is complete.
*
* If the given URL begins with a `/`, router will navigate absolutely.
* If the given URL does not begin with `/`, the router will navigate relative to this component.
*/
navigate(url: string, _skipLocationChange?: boolean): Promise<any>;
/**
* Navigate via the provided instruction. Returns a promise that resolves when navigation is
* complete.
*/
navigateInstruction(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
/**
* Updates this router and all descendant routers according to the given instruction
*/
commit(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
/**
* Subscribe to URL updates from the router
*/
subscribe(onNext: (value: any) => void): void;
/**
* Removes the contents of this router's outlet and all descendant outlets
*/
deactivate(instruction: Instruction): Promise<any>;
/**
* Given a URL, returns an instruction representing the component graph
*/
recognize(url: string): Promise<Instruction>;
/**
* Navigates to either the last URL successfully navigated to, or the last URL requested if the
* router has yet to successfully navigate.
*/
renavigate(): Promise<any>;
/**
* Generate a URL from a component name and optional map of parameters. The URL is relative to the
* app's base href.
*/
generate(linkParams: List<any>): Instruction;
}
class RootRouter extends Router {
commit(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
}
/**
* A router outlet is a placeholder that Angular dynamically fills based on the application's route.
*
* ## Use
*
* ```
* <router-outlet></router-outlet>
* ```
*/
class RouterOutlet {
childRouter: Router;
name: string;
/**
* Given an instruction, update the contents of this outlet.
*/
commit(instruction: Instruction): Promise<any>;
/**
* Called by Router during recognition phase
*/
canDeactivate(nextInstruction: Instruction): Promise<boolean>;
/**
* Called by Router during recognition phase
*/
canReuse(nextInstruction: Instruction): Promise<boolean>;
deactivate(nextInstruction: Instruction): Promise<any>;
}
/**
* The RouterLink directive lets you link to specific parts of your app.
*
* Consider the following route configuration:
*
* ```
* @RouteConfig([
* { path: '/user', component: UserCmp, as: 'user' }
* ]);
* class MyComp {}
* ```
*
* When linking to this `user` route, you can write:
*
* ```
* <a [router-link]="['./user']">link to user component</a>
* ```
*
* RouterLink expects the value to be an array of route names, followed by the params
* for that level of routing. For instance `['/team', {teamId: 1}, 'user', {userId: 2}]`
* means that we want to generate a link for the `team` route with params `{teamId: 1}`,
* and with a child route `user` with params `{userId: 2}`.
*
* The first route name should be prepended with `/`, `./`, or `../`.
* If the route begins with `/`, the router will look up the route from the root of the app.
* If the route begins with `./`, the router will instead look in the current component's
* children for the route. And if the route begins with `../`, the router will look at the
* current component's parent.
*/
class RouterLink {
visibleHref: string;
routeParams: void;
onClick(): boolean;
}
class RouteParams {
params: StringMap<string, string>;
get(param: string): string;
}
/**
* The RouteRegistry holds route configurations for each component in an Angular app.
* It is responsible for creating Instructions from URLs, and generating URLs based on route and
* parameters.
*/
class RouteRegistry {
/**
* Given a component and a configuration object, add the route to this registry
*/
config(parentComponent: any, config: RouteDefinition): void;
/**
* Reads the annotations of a component and configures the registry based on them
*/
configFromComponent(component: any): void;
/**
* Given a URL and a parent component, return the most specific instruction for navigating
* the application into the state specified by the url
*/
recognize(url: string, parentComponent: any): Promise<Instruction>;
/**
* Given a normalized list with component names and params like: `['user', {id: 3 }]`
* generates a url with a leading slash relative to the provided `parentComponent`.
*/
generate(linkParams: List<any>, parentComponent: any): Instruction;
}
class LocationStrategy {
path(): string;
pushState(ctx: any, title: string, url: string): void;
forward(): void;
back(): void;
onPopState(fn: (_: any) => any): void;
getBaseHref(): string;
}
class HashLocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
class HTML5LocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
/**
* This is the service that an application developer will directly interact with.
*
* Responsible for normalizing the URL against the application's base href.
* A normalized URL is absolute from the URL host, includes the application's base href, and has no
* trailing slash:
* - `/my/app/user/123` is normalized
* - `my/app/user/123` **is not** normalized
* - `/my/app/user/123/` **is not** normalized
*/
class Location {
path(): string;
normalize(url: string): string;
normalizeAbsolutely(url: string): string;
go(url: string): void;
forward(): void;
back(): void;
subscribe(onNext: (value: any) => void, onThrow?: (exception: any) => void, onReturn?: () => void): void;
}
const APP_BASE_HREF : OpaqueToken ;
/**
* Responsible for performing each step of navigation.
* "Steps" are conceptually similar to "middleware"
*/
class Pipeline {
steps: List<Function>;
process(instruction: Instruction): Promise<any>;
}
/**
* Defines route lifecycle method [onActivate], which is called by the router at the end of a
* successful route navigation.
*
* For a single component's navigation, only one of either [onActivate] or [onReuse] will be called,
* depending on the result of [canReuse].
*
* If `onActivate` returns a promise, the route change will wait until the promise settles to
* instantiate and activate child components.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements OnActivate {
* onActivate(next, prev) {
* this.log = 'Finished navigating from ' + prev.urlPath + ' to ' + next.urlPath;
* }
* }
* ```
*/
interface OnActivate {
onActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [onDeactivate], which is called by the router before destroying
* a component as part of a route change.
*
* If `onDeactivate` returns a promise, the route change will wait until the promise settles.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse() {
* return true;
* }
*
* onReuse(next, prev) {
* this.params = next.params;
* }
* }
* ```
*/
interface OnDeactivate {
onDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [onReuse], which is called by the router at the end of a
* successful route navigation when [canReuse] is implemented and returns or resolves to true.
*
* For a single component's navigation, only one of either [onActivate] or [onReuse] will be called,
* depending on the result of [canReuse].
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse() {
* return true;
* }
*
* onReuse(next, prev) {
* this.params = next.params;
* }
* }
* ```
*/
interface OnReuse {
onReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canDeactivate], which is called by the router to determine
* if a component can be removed as part of a navigation.
*
* If `canDeactivate` returns or resolves to `false`, the navigation is cancelled.
*
* If `canDeactivate` throws or rejects, the navigation is also cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanDeactivate {
* canDeactivate(next, prev) {
* return askUserIfTheyAreSureTheyWantToQuit();
* }
* }
* ```
*/
interface CanDeactivate {
canDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canReuse], which is called by the router to determine whether a
* component should be reused across routes, or whether to destroy and instantiate a new component.
*
* If `canReuse` returns or resolves to `true`, the component instance will be reused.
*
* If `canReuse` throws or rejects, the navigation will be cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse(next, prev) {
* return next.params.id == prev.params.id;
* }
*
* onReuse(next, prev) {
* this.id = next.params.id;
* }
* }
* ```
*/
interface CanReuse {
canReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canActivate], which is called by the router to determine
* if a component can be instantiated as part of a navigation.
*
* Note that unlike other lifecycle hooks, this one uses an annotation rather than an interface.
* This is because [canActivate] is called before the component is instantiated.
*
* If `canActivate` returns or resolves to `false`, the navigation is cancelled.
*
* If `canActivate` throws or rejects, the navigation is also cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'control-panel-cmp'
* })
* @CanActivate(() => checkIfUserIsLoggedIn())
* class ControlPanelCmp {
* // ...
* }
* ```
*/
var CanActivate : (hook: (next: ComponentInstruction, prev: ComponentInstruction) => Promise<boolean>| boolean) =>
ClassDecorator ;
/**
* `Instruction` is a tree of `ComponentInstructions`, with all the information needed
* to transition each component in the app to a given route, including all auxiliary routes.
*
* This is a public API.
*/
class Instruction {
component: ComponentInstruction;
child: Instruction;
auxInstruction: StringMap<string, Instruction>;
replaceChild(child: Instruction): Instruction;
}
/**
* A `ComponentInstruction` represents the route state for a single component. An `Instruction` is
* composed of a tree of these `ComponentInstruction`s.
*
* `ComponentInstructions` is a public API. Instances of `ComponentInstruction` are passed
* to route lifecycle hooks, like {@link CanActivate}.
*/
class ComponentInstruction {
reuse: boolean;
urlPath: string;
urlParams: List<string>;
params: StringMap<string, any>;
componentType: void;
resolveComponentType(): Promise<Type>;
specificity: void;
terminal: void;
routeData(): Object;
}
class Url {
path: string;
child: Url;
auxiliary: List<Url>;
params: StringMap<string, any>;
toString(): string;
segmentToString(): string;
}
class OpaqueToken {
toString(): string;
}
/**
* Runtime representation of a type.
*
* In JavaScript a Type is a constructor function.
*/
interface Type extends Function {
new(args: any): any;
}
const routerDirectives : List<any> ;
var routerInjectables : List<any> ;
class Route implements RouteDefinition {
data: any;
path: string;
component: Type;
as: string;
loader: Function;
redirectTo: string;
}
class Redirect implements RouteDefinition {
path: string;
redirectTo: string;
as: string;
loader: Function;
data: any;
}
class AuxRoute implements RouteDefinition {
data: any;
path: string;
component: Type;
as: string;
loader: Function;
redirectTo: string;
}
class AsyncRoute implements RouteDefinition {
data: any;
path: string;
loader: Function;
as: string;
}
interface RouteDefinition {
path: string;
component?: Type | ComponentDefinition;
loader?: Function;
redirectTo?: string;
as?: string;
data?: any;
}
const ROUTE_DATA : OpaqueToken ;
var RouteConfig : (configs: List<RouteDefinition>) => ClassDecorator ;
interface ComponentDefinition {
type: string;
loader?: Function;
component?: Type;
}
}
declare module "angular2/router" {
export = ngRouter;
}
+135 -20
View File
@@ -1,6 +1,6 @@
// Type definitions for Angular JS 1.3 (ngAnimate module)
// Project: http://angularjs.org
// Definitions by: Michel Salib <https://github.com/michelsalib>, Adi Dahiya <https://github.com/adidahiya>, Raphael Schweizer <https://github.com/rasch>
// Definitions by: Michel Salib <https://github.com/michelsalib>, Adi Dahiya <https://github.com/adidahiya>, Raphael Schweizer <https://github.com/rasch>, Cody Schaaf <https://github.com/codyschaaf>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
@@ -10,15 +10,22 @@ declare module "angular-animate" {
export = _;
}
///////////////////////////////////////////////////////////////////////////////
// ngAnimate module (angular-animate.js)
///////////////////////////////////////////////////////////////////////////////
/**
* ngAnimate module (angular-animate.js)
*/
declare module angular.animate {
interface IAnimateFactory extends Function {
enter?: (element: ng.IAugmentedJQuery, doneFn: Function) => IAnimateCssRunner|void;
leave?: (element: ng.IAugmentedJQuery, doneFn: Function) => IAnimateCssRunner|void;
addClass?: (element: ng.IAugmentedJQuery, className: string, doneFn: Function) => IAnimateCssRunner|void;
removeClass?: (element: ng.IAugmentedJQuery, className: string, doneFn: Function) => IAnimateCssRunner|void;
setClass?: (element: ng.IAugmentedJQuery, className: string, doneFn: Function) => IAnimateCssRunner|void;
}
///////////////////////////////////////////////////////////////////////////
// AnimateService
// see http://docs.angularjs.org/api/ngAnimate/service/$animate
///////////////////////////////////////////////////////////////////////////
/**
* AnimateService
* see http://docs.angularjs.org/api/ngAnimate/service/$animate
*/
interface IAnimateService extends angular.IAnimateService {
/**
* Globally enables / disables animations.
@@ -113,10 +120,10 @@ declare module angular.animate {
cancel(animationPromise: IPromise<void>): void;
}
///////////////////////////////////////////////////////////////////////////
// AngularProvider
// see http://docs.angularjs.org/api/ngAnimate/provider/$animateProvider
///////////////////////////////////////////////////////////////////////////
/**
* AngularProvider
* see http://docs.angularjs.org/api/ngAnimate/provider/$animateProvider
*/
interface IAnimateProvider {
/**
* Registers a new injectable animation factory function.
@@ -135,12 +142,120 @@ declare module angular.animate {
classNameFilter(expression?: RegExp): RegExp;
}
///////////////////////////////////////////////////////////////////////////
// Angular Animation Options
// see https://docs.angularjs.org/api/ngAnimate/#applying-directive-specific-styles-to-an-animation
///////////////////////////////////////////////////////////////////////////
interface IAnimationOptions {
to?: Object;
from?: Object;
}
/**
* Angular Animation Options
* see https://docs.angularjs.org/api/ngAnimate/#applying-directive-specific-styles-to-an-animation
*/
interface IAnimationOptions {
/**
* The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition.
*/
to?: Object;
/**
* The starting CSS styles (a key/value object) that will be applied at the start of the animation.
*/
from?: Object;
/**
* The DOM event (e.g. enter, leave, move). When used, a generated CSS class of ng-EVENT and
* ng-EVENT-active will be applied to the element during the animation. Multiple events can be provided when
* spaces are used as a separator. (Note that this will not perform any DOM operation.)
*/
event?: string;
/**
* The CSS easing value that will be applied to the transition or keyframe animation (or both).
*/
easing?: string;
/**
* The raw CSS transition style that will be used (e.g. 1s linear all).
*/
transition?: string;
/**
* The raw CSS keyframe animation style that will be used (e.g. 1s my_animation linear).
*/
keyframe?: string;
/**
* A space separated list of CSS classes that will be added to the element and spread across the animation.
*/
addClass?: string;
/**
* A space separated list of CSS classes that will be removed from the element and spread across
* the animation.
*/
removeClass?: string;
/**
* A number value representing the total duration of the transition and/or keyframe (note that a value
* of 1 is 1000ms). If a value of 0 is provided then the animation will be skipped entirely.
*/
duration?: number;
/**
* A number value representing the total delay of the transition and/or keyframe (note that a value of
* 1 is 1000ms). If a value of true is used then whatever delay value is detected from the CSS classes will be
* mirrored on the elements styles (e.g. by setting delay true then the style value of the element will be
* transition-delay: DETECTED_VALUE). Using true is useful when you want the CSS classes and inline styles to
* all share the same CSS delay value.
*/
delay?: number;
/**
* A numeric time value representing the delay between successively animated elements (Click here to
* learn how CSS-based staggering works in ngAnimate.)
*/
stagger?: number;
/**
* The numeric index representing the stagger item (e.g. a value of 5 is equal to the sixth item
* in the stagger; therefore when a stagger option value of 0.1 is used then there will be a stagger delay of 600ms)
* applyClassesEarly - Whether or not the classes being added or removed will be used when detecting the animation.
* This is set by $animate when enter/leave/move animations are fired to ensure that the CSS classes are resolved in time.
* (Note that this will prevent any transitions from occuring on the classes being added and removed.)
*/
staggerIndex?: number;
}
interface IAnimateCssRunner {
/**
* Starts the animation
*
* @returns The animation runner with a done function for supplying a callback.
*/
start(): IAnimateCssRunnerStart;
/**
* Ends (aborts) the animation
*/
end(): void;
}
interface IAnimateCssRunnerStart extends IPromise<void> {
/**
* Allows you to add done callbacks to the running animation
*
* @param callbackFn: the callback function to be run
*/
done(callbackFn: (animationFinished: boolean) => void): void;
}
/**
* AnimateCssService
* see http://docs.angularjs.org/api/ngAnimate/service/$animateCss
*/
interface IAnimateCssService {
(element: JQuery, animateCssOptions: IAnimationOptions): IAnimateCssRunner;
}
}
declare module angular {
interface IModule {
animate(cssSelector: string, animateFactory: angular.animate.IAnimateFactory): IModule;
}
}
+34 -11
View File
@@ -11,23 +11,23 @@ declare module "angular-cookies" {
export = _;
}
///////////////////////////////////////////////////////////////////////////////
// ngCookies module (angular-cookies.js)
///////////////////////////////////////////////////////////////////////////////
/**
* ngCookies module (angular-cookies.js)
*/
declare module angular.cookies {
///////////////////////////////////////////////////////////////////////////
// CookieService
// see http://docs.angularjs.org/api/ngCookies.$cookies
///////////////////////////////////////////////////////////////////////////
/**
* CookieService
* see http://docs.angularjs.org/api/ngCookies.$cookies
*/
interface ICookiesService {
[index: string]: any;
}
///////////////////////////////////////////////////////////////////////////
// CookieStoreService
// see http://docs.angularjs.org/api/ngCookies.$cookieStore
///////////////////////////////////////////////////////////////////////////
/**
* CookieStoreService
* see http://docs.angularjs.org/api/ngCookies.$cookieStore
*/
interface ICookiesService {
get(key: string): string;
getObject(key: string): any;
@@ -37,4 +37,27 @@ declare module angular.cookies {
remove(key: string, options?: any): void;
}
/**
* CookieStoreService DEPRECATED
* see https://code.angularjs.org/1.2.26/docs/api/ngCookies/service/$cookieStore
*/
interface ICookieStoreService {
/**
* Returns the value of given cookie key
* @param key Id to use for lookup
*/
get(key: string): any;
/**
* Sets a value for given cookie key
* @param key Id for the value
* @param value Value to be stored
*/
put(key: string, value: any): void;
/**
* Remove given cookie
* @param key Id of the key-value pair to delete
*/
remove(key: string): void;
}
}
+100 -2
View File
@@ -126,18 +126,35 @@ requestHandler = httpBackendService.expect('GET', /test.local/, function (data:
requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data', function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expectDELETE('http://test.local');
requestHandler = httpBackendService.expectDELETE('http://test.local', { header: 'value' });
requestHandler = httpBackendService.expectDELETE(/test.local/, { header: 'value' });
requestHandler = httpBackendService.expectDELETE((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectGET('http://test.local');
requestHandler = httpBackendService.expectGET('http://test.local', { header: 'value' });
requestHandler = httpBackendService.expectGET(/test.local/, { header: 'value' });
requestHandler = httpBackendService.expectGET((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectHEAD('http://test.local');
requestHandler = httpBackendService.expectHEAD('http://test.local', { header: 'value' });
requestHandler = httpBackendService.expectHEAD(/test.local/, { header: 'value' });
requestHandler = httpBackendService.expectHEAD((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectJSONP('http://test.local');
requestHandler = httpBackendService.expectJSONP(/test.local/);
requestHandler = httpBackendService.expectJSONP((url: string) => { return true; });
requestHandler = httpBackendService.expectPATCH('http://test.local');
requestHandler = httpBackendService.expectPATCH('http://test.local', 'response data');
@@ -157,6 +174,15 @@ requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: st
requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPOST('http://test.local');
requestHandler = httpBackendService.expectPOST('http://test.local', 'response data');
@@ -176,6 +202,15 @@ requestHandler = httpBackendService.expectPOST(/test.local/, function (data: str
requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPUT('http://test.local');
requestHandler = httpBackendService.expectPUT('http://test.local', 'response data');
@@ -195,6 +230,15 @@ requestHandler = httpBackendService.expectPUT(/test.local/, function (data: stri
requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.when('GET', 'http://test.local');
requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data');
@@ -222,18 +266,35 @@ requestHandler = httpBackendService.when('GET', /test.local/, function (data: st
requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' });
requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data', function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.whenDELETE('http://test.local');
requestHandler = httpBackendService.whenDELETE('http://test.local', { header: 'value' });
requestHandler = httpBackendService.whenDELETE(/test.local/, { header: 'value' });
requestHandler = httpBackendService.whenDELETE((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenGET('http://test.local');
requestHandler = httpBackendService.whenGET('http://test.local', { header: 'value' });
requestHandler = httpBackendService.whenGET(/test.local/, { header: 'value' });
requestHandler = httpBackendService.whenGET((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenHEAD('http://test.local');
requestHandler = httpBackendService.whenHEAD('http://test.local', { header: 'value' });
requestHandler = httpBackendService.whenHEAD(/test.local/, { header: 'value' });
requestHandler = httpBackendService.whenHEAD((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenJSONP('http://test.local');
requestHandler = httpBackendService.whenJSONP(/test.local/);
requestHandler = httpBackendService.whenJSONP((url: string) => { return true; });
requestHandler = httpBackendService.whenPATCH('http://test.local');
requestHandler = httpBackendService.whenPATCH('http://test.local', 'response data');
@@ -253,6 +314,15 @@ requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: stri
requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPOST('http://test.local');
requestHandler = httpBackendService.whenPOST('http://test.local', 'response data');
@@ -272,6 +342,15 @@ requestHandler = httpBackendService.whenPOST(/test.local/, function (data: strin
requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPUT('http://test.local');
requestHandler = httpBackendService.whenPUT('http://test.local', 'response data');
@@ -291,15 +370,34 @@ requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string
requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, { key: 'value' }, { header: 'value' });
///////////////////////////////////////
// IRequestHandler
///////////////////////////////////////
var expectedData = { key: 'value'};
requestHandler.passThrough();
requestHandler.respond(function () { });
requestHandler.passThrough().passThrough();
requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']);
requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']).respond({});
requestHandler.respond((method, url, data, headers) => { return [404, { key: 'value' }, { header: 'value' }, 'responseText']; });
requestHandler.respond('data');
requestHandler.respond('data').respond({});
requestHandler.respond(expectedData);
requestHandler.respond({ key: 'value' });
requestHandler.respond({ key: 'value' }, { header: 'value' });
requestHandler.respond(404);
requestHandler.respond({ key: 'value' }, { header: 'value' }, 'responseText');
requestHandler.respond(404, 'data');
requestHandler.respond(404, 'data').respond({});
requestHandler.respond(404, { key: 'value' });
requestHandler.respond(404, { key: 'value' }, { header: 'value' });
requestHandler.respond(404, { key: 'value' }, { header: 'value' }, 'responseText');
+204 -130
View File
@@ -1,6 +1,6 @@
// Type definitions for Angular JS 1.3 (ngMock, ngMockE2E module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Tony Curtis <http://github.com/daltin>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
@@ -15,12 +15,6 @@ declare module "angular-mocks/ngAnimateMock" {
export = _;
}
///////////////////////////////////////////////////////////////////////////////
// functions attached to global object (window)
///////////////////////////////////////////////////////////////////////////////
declare var module: (...modules: any[]) => any;
declare var inject: (...fns: Function[]) => any;
///////////////////////////////////////////////////////////////////////////////
// ngMock module (angular-mocks.js)
///////////////////////////////////////////////////////////////////////////////
@@ -33,30 +27,32 @@ declare module angular {
interface IAngularStatic {
mock: IMockStatic;
}
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.inject
interface IInjectStatic {
(...fns: Function[]): any;
(...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works
strictDi(val?: boolean): void;
}
interface IMockStatic {
// see http://docs.angularjs.org/api/angular.mock.dump
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.dump
dump(obj: any): string;
// see http://docs.angularjs.org/api/angular.mock.inject
inject: {
(...fns: Function[]): any;
(...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works
strictDi(val?: boolean): void;
}
inject: IInjectStatic
// see http://docs.angularjs.org/api/angular.mock.module
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.module
module(...modules: any[]): any;
// see http://docs.angularjs.org/api/angular.mock.TzDate
// see https://docs.angularjs.org/api/ngMock/type/angular.mock.TzDate
TzDate(offset: number, timestamp: number): Date;
TzDate(offset: number, timestamp: string): Date;
}
///////////////////////////////////////////////////////////////////////////
// ExceptionHandlerService
// see http://docs.angularjs.org/api/ngMock.$exceptionHandler
// see http://docs.angularjs.org/api/ngMock.$exceptionHandlerProvider
// see https://docs.angularjs.org/api/ngMock/service/$exceptionHandler
// see https://docs.angularjs.org/api/ngMock/provider/$exceptionHandlerProvider
///////////////////////////////////////////////////////////////////////////
interface IExceptionHandlerProvider extends IServiceProvider {
mode(mode: string): void;
@@ -64,7 +60,7 @@ declare module angular {
///////////////////////////////////////////////////////////////////////////
// TimeoutService
// see http://docs.angularjs.org/api/ngMock.$timeout
// see https://docs.angularjs.org/api/ngMock/service/$timeout
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface ITimeoutService {
@@ -75,7 +71,7 @@ declare module angular {
///////////////////////////////////////////////////////////////////////////
// IntervalService
// see http://docs.angularjs.org/api/ngMock.$interval
// see https://docs.angularjs.org/api/ngMock/service/$interval
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface IIntervalService {
@@ -84,7 +80,7 @@ declare module angular {
///////////////////////////////////////////////////////////////////////////
// LogService
// see http://docs.angularjs.org/api/ngMock.$log
// see https://docs.angularjs.org/api/ngMock/service/$log
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface ILogService {
@@ -98,142 +94,220 @@ declare module angular {
///////////////////////////////////////////////////////////////////////////
// HttpBackendService
// see http://docs.angularjs.org/api/ngMock.$httpBackend
// see https://docs.angularjs.org/api/ngMock/service/$httpBackend
///////////////////////////////////////////////////////////////////////////
interface IHttpBackendService {
/**
* Flushes all pending requests using the trained responses.
* @param count Number of responses to flush (in the order they arrived). If undefined, all pending requests will be flushed.
*/
flush(count?: number): void;
/**
* Resets all request expectations, but preserves all backend definitions.
*/
resetExpectations(): void;
/**
* Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception.
*/
verifyNoOutstandingExpectation(): void;
/**
* Verifies that there are no outstanding requests that need to be flushed.
*/
verifyNoOutstandingRequest(): void;
expect(method: string, url: string, data?: string, headers?: Object): mock.IRequestHandler;
expect(method: string, url: string, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
expect(method: string, url: string, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expect(method: string, url: string, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: string, data?: Object, headers?: Object): mock.IRequestHandler;
expect(method: string, url: string, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler;
/**
* Creates a new request expectation.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expect(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)) :mock.IRequestHandler;
expectDELETE(url: string, headers?: Object): mock.IRequestHandler;
expectDELETE(url: RegExp, headers?: Object): mock.IRequestHandler;
expectGET(url: string, headers?: Object): mock.IRequestHandler;
expectGET(url: RegExp, headers?: Object): mock.IRequestHandler;
expectHEAD(url: string, headers?: Object): mock.IRequestHandler;
expectHEAD(url: RegExp, headers?: Object): mock.IRequestHandler;
expectJSONP(url: string): mock.IRequestHandler;
expectJSONP(url: RegExp): mock.IRequestHandler;
/**
* Creates a new request expectation for DELETE requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
expectPATCH(url: string, data?: string, headers?: Object): mock.IRequestHandler;
expectPATCH(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
expectPATCH(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expectPATCH(url: string, data?: Object, headers?: Object): mock.IRequestHandler;
expectPATCH(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
expectPATCH(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
expectPATCH(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expectPATCH(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for GET requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectGET(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
expectPOST(url: string, data?: string, headers?: Object): mock.IRequestHandler;
expectPOST(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
expectPOST(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expectPOST(url: string, data?: Object, headers?: Object): mock.IRequestHandler;
expectPOST(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
expectPOST(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
expectPOST(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expectPOST(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for HEAD requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for JSONP requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
*/
expectJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler;
expectPUT(url: string, data?: string, headers?: Object): mock.IRequestHandler;
expectPUT(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
expectPUT(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expectPUT(url: string, data?: Object, headers?: Object): mock.IRequestHandler;
expectPUT(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
expectPUT(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
expectPUT(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expectPUT(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for PATCH requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expectPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
when(method: string, url: string, data?: string, headers?: Object): mock.IRequestHandler;
when(method: string, url: string, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
when(method: string, url: string, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
when(method: string, url: string, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: string, data?: Object, headers?: Object): mock.IRequestHandler;
when(method: string, url: string, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
when(method: string, url: RegExp, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
when(method: string, url: RegExp, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
when(method: string, url: RegExp, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
when(method: string, url: RegExp, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler;
/**
* Creates a new request expectation for POST requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expectPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
whenDELETE(url: string, headers?: Object): mock.IRequestHandler;
whenDELETE(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
whenDELETE(url: RegExp, headers?: Object): mock.IRequestHandler;
whenDELETE(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
/**
* Creates a new request expectation for PUT requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expectPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
whenGET(url: string, headers?: Object): mock.IRequestHandler;
whenGET(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
whenGET(url: RegExp, headers?: Object): mock.IRequestHandler;
whenGET(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
/**
* Creates a new backend definition.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
when(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
whenHEAD(url: string, headers?: Object): mock.IRequestHandler;
whenHEAD(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
whenHEAD(url: RegExp, headers?: Object): mock.IRequestHandler;
whenHEAD(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
/**
* Creates a new backend definition for DELETE requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
whenJSONP(url: string): mock.IRequestHandler;
whenJSONP(url: RegExp): mock.IRequestHandler;
/**
* Creates a new backend definition for GET requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenGET(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
whenPATCH(url: string, data?: string, headers?: Object): mock.IRequestHandler;
whenPATCH(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
whenPATCH(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
whenPATCH(url: string, data?: Object, headers?: Object): mock.IRequestHandler;
whenPATCH(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
whenPATCH(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
whenPATCH(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
whenPATCH(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
/**
* Creates a new backend definition for HEAD requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
whenPOST(url: string, data?: string, headers?: Object): mock.IRequestHandler;
whenPOST(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
whenPOST(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
whenPOST(url: string, data?: Object, headers?: Object): mock.IRequestHandler;
whenPOST(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
whenPOST(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
whenPOST(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
whenPOST(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
/**
* Creates a new backend definition for JSONP requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler;
whenPUT(url: string, data?: string, headers?: Object): mock.IRequestHandler;
whenPUT(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
whenPUT(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
whenPUT(url: string, data?: Object, headers?: Object): mock.IRequestHandler;
whenPUT(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
whenPUT(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
whenPUT(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
whenPUT(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
/**
* Creates a new backend definition for PATCH requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for POST requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for PUT requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
}
export module mock {
// returned interface by the the mocked HttpBackendService expect/when methods
interface IRequestHandler {
respond(func: Function): void;
respond(status: number, data?: any, headers?: any): void;
respond(data: any, headers?: any): void;
/**
* Controls the response for a matched request using a function to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param func Function that receives the request HTTP method, url, data, and headers and returns an array containing response status (number), data, headers, and status text.
*/
respond(func: ((method: string, url: string, data: string | Object, headers: Object) => [number, string | Object, Object, string])): IRequestHandler;
// Available wehn ngMockE2E is loaded
passThrough(): void;
/**
* Controls the response for a matched request using supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param status HTTP status code to add to the response.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
* @param responseText Response text to add to the response.
*/
respond(status: number, data: string | Object, headers?: Object, responseText?: string): IRequestHandler;
/**
* Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
* @param responseText Response text to add to the response.
*/
respond(data: string | Object, headers?: Object, responseText?: string): IRequestHandler;
// Available when ngMockE2E is loaded
/**
* Any request matching a backend definition or expectation with passThrough handler will be passed through to the real backend (an XHR request will be made to the server.)
*/
passThrough(): IRequestHandler;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// functions attached to global object (window)
///////////////////////////////////////////////////////////////////////////////
//Use `angular.mock.module` instead of `module`, as `module` conflicts with commonjs.
//declare var module: (...modules: any[]) => any;
declare var inject: angular.IInjectStatic;
+1 -1
View File
@@ -147,7 +147,7 @@ declare module angular.resource {
}
// IResourceServiceProvider used to configure global settings
interface IResourceServiceProvider extends ng.IServiceProvider {
interface IResourceServiceProvider extends angular.IServiceProvider {
defaults: IResourceOptions;
}
Executable → Regular
+206 -2
View File
@@ -30,7 +30,7 @@ class AuthService {
'$rootScope', '$injector', <any>function($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) {
var $http: ng.IHttpService; //initialized later because of circular dependency problem
function retry(config: ng.IRequestConfig, deferred: ng.IDeferred<any>) {
$http = $http || $injector.get('$http');
$http = $http || $injector.get<ng.IHttpService>('$http');
$http(config).then(function (response) {
deferred.resolve(response);
});
@@ -242,6 +242,72 @@ foo.then((x) => {
x.toFixed();
});
// $q signature tests
module TestQ {
interface TResult {
a: number;
b: string;
c: boolean;
}
var tResult: TResult;
var promiseTResult: angular.IPromise<TResult>;
var $q: angular.IQService;
var promiseAny: angular.IPromise<any>;
// $q constructor
{
let result: angular.IPromise<TResult>;
result = new $q<TResult>((resolve: (value: TResult) => any) => {});
result = new $q<TResult>((resolve: (value: TResult) => any, reject: (value: any) => any) => {});
result = $q<TResult>((resolve: (value: TResult) => any) => {});
result = $q<TResult>((resolve: (value: TResult) => any, reject: (value: any) => any) => {});
}
// $q.all
{
let result: angular.IPromise<any[]>;
result = $q.all([promiseAny, promiseAny]);
}
{
let result: angular.IPromise<TResult[]>;
result = $q.all<TResult>([promiseAny, promiseAny]);
}
{
let result: angular.IPromise<{[id: string]: any;}>;
result = $q.all({a: promiseAny, b: promiseAny});
}
{
let result: angular.IPromise<{a: number; b: string;}>;
result = $q.all<{a: number; b: string;}>({a: promiseAny, b: promiseAny});
}
// $q.defer
{
let result: angular.IDeferred<TResult>;
result = $q.defer<TResult>();
}
// $q.reject
{
let result: angular.IPromise<any>;
result = $q.reject();
result = $q.reject('');
}
// $q.when
{
let result: angular.IPromise<void>;
result = $q.when();
}
{
let result: angular.IPromise<TResult>;
result = $q.when<TResult>(tResult);
result = $q.when<TResult>(promiseTResult);
}
}
var httpFoo: ng.IHttpPromise<number>;
httpFoo.then((x) => {
@@ -260,6 +326,104 @@ httpFoo.success((data, status, headers, config) => {
hs["content-type"].charAt(1);
});
// Deferred signature tests
module TestDeferred {
var any: any;
interface TResult {
a: number;
b: string;
c: boolean;
}
var tResult: TResult;
var deferred: angular.IDeferred<TResult>;
// deferred.resolve
{
let result: void;
result = <void>deferred.resolve();
result = <void>deferred.resolve(tResult);
}
// deferred.reject
{
let result: void;
result = deferred.reject();
result = deferred.reject(any);
}
// deferred.notify
{
let result: void;
result = deferred.notify();
result = deferred.notify(any);
}
// deferred.promise
{
let result: angular.IPromise<TResult>;
result = deferred.promise;
}
}
// Promise signature tests
module TestPromise {
var result: any;
var any: any;
interface TResult {
a: number;
b: string;
c: boolean;
}
interface TOther {
d: number;
e: string;
f: boolean;
}
var tresult: TResult;
var tresultPromise: ng.IPromise<TResult>;
var tother: TOther;
var totherPromise: ng.IPromise<TOther>;
var promise: angular.IPromise<TResult>;
// promise.then
result = <angular.IPromise<any>>promise.then((result) => any);
result = <angular.IPromise<any>>promise.then((result) => any, (any) => any);
result = <angular.IPromise<any>>promise.then((result) => any, (any) => any, (any) => any);
result = <angular.IPromise<TResult>>promise.then((result) => result);
result = <angular.IPromise<TResult>>promise.then((result) => result, (any) => any);
result = <angular.IPromise<TResult>>promise.then((result) => result, (any) => any, (any) => any);
result = <angular.IPromise<TResult>>promise.then((result) => tresultPromise);
result = <angular.IPromise<TResult>>promise.then((result) => tresultPromise, (any) => any);
result = <angular.IPromise<TResult>>promise.then((result) => tresultPromise, (any) => any, (any) => any);
result = <angular.IPromise<TOther>>promise.then((result) => tother);
result = <angular.IPromise<TOther>>promise.then((result) => tother, (any) => any);
result = <angular.IPromise<TOther>>promise.then((result) => tother, (any) => any, (any) => any);
result = <angular.IPromise<TOther>>promise.then((result) => totherPromise);
result = <angular.IPromise<TOther>>promise.then((result) => totherPromise, (any) => any);
result = <angular.IPromise<TOther>>promise.then((result) => totherPromise, (any) => any, (any) => any);
// promise.catch
result = <angular.IPromise<any>>promise.catch((err) => any);
result = <angular.IPromise<TResult>>promise.catch((err) => tresult);
result = <angular.IPromise<TOther>>promise.catch((err) => tother);
// promise.finally
result = <angular.IPromise<TResult>>promise.finally(() => any);
result = <angular.IPromise<TResult>>promise.finally(() => tresult);
result = <angular.IPromise<TResult>>promise.finally(() => tother);
}
function test_angular_forEach() {
var values: { [key: string]: string } = { name: 'misko', gender: 'male' };
var log: string[] = [];
@@ -275,16 +439,56 @@ var scope: ng.IScope = element.scope();
var isolateScope: ng.IScope = element.isolateScope();
// $timeout signature tests
module TestTimeout {
interface TResult {
a: number;
b: string;
c: boolean;
}
var fnTResult: (...args: any[]) => TResult;
var promiseAny: angular.IPromise<any>;
var $timeout: angular.ITimeoutService;
// $timeout
{
let result: angular.IPromise<any>;
result = $timeout();
}
{
let result: angular.IPromise<void>;
result = $timeout(1);
result = $timeout(1, true);
}
{
let result: angular.IPromise<TResult>;
result = $timeout(fnTResult);
result = $timeout(fnTResult, 1);
result = $timeout(fnTResult, 1, true);
result = $timeout(fnTResult, 1, true, 1);
result = $timeout(fnTResult, 1, true, 1, '');
result = $timeout(fnTResult, 1, true, 1, '', true);
}
// $timeout.cancel
{
let result: boolean;
result = $timeout.cancel();
result = $timeout.cancel(promiseAny);
}
}
function test_IAttributes(attributes: ng.IAttributes){
return attributes;
}
test_IAttributes({
$normalize: function (classVal){},
$addClass: function (classVal){},
$removeClass: function(classVal){},
$set: function(key, value){},
$observe: function(name, fn){
$observe: function(name: any, fn: any){
return fn;
},
$attr: {}
Vendored Executable → Regular
+74 -50
View File
@@ -237,8 +237,8 @@ declare module angular {
forEach(obj: any, iterator: (value: any, key: any) => any, context?: any): any;
fromJson(json: string): any;
identity(arg?: any): any;
injector(modules?: any[]): auto.IInjectorService;
identity<T>(arg?: T): T;
injector(modules?: any[], strictDi?: boolean): auto.IInjectorService;
isArray(value: any): boolean;
isDate(value: any): boolean;
isDefined(value: any): boolean;
@@ -249,12 +249,12 @@ declare module angular {
isString(value: any): boolean;
isUndefined(value: any): boolean;
lowercase(str: string): string;
/**
* Deeply extends the destination object dst by copying own enumerable properties from the src object(s) to dst. You can specify multiple src objects. If you want to preserve original objects, you can do so by passing an empty object as the target: var object = angular.merge({}, object1, object2).
*
*
* Unlike extend(), merge() recursively descends into object properties of source objects, performing a deep copy.
*
*
* @param dst Destination object.
* @param src Source object(s).
*/
@@ -419,6 +419,15 @@ declare module angular {
*/
[name: string]: any;
/**
* Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with x- or data-) to its normalized, camelCase form.
*
* Also there is special case for Moz prefix starting with upper case letter.
*
* For further information check out the guide on @see https://docs.angularjs.org/guide/directive#matching-directives
*/
$normalize(name: string): void;
/**
* Adds the CSS class value specified by the classVal parameter to the
* element. If animations are enabled then an animation will be triggered
@@ -444,7 +453,7 @@ declare module angular {
* following compilation. The observer is then invoked whenever the
* interpolated value changes.
*/
$observe(name: string, fn: (value?: any) => any): Function;
$observe<T>(name: string, fn: (value?: T) => any): Function;
/**
* A map of DOM element attribute names to the normalized name. This is needed
@@ -524,11 +533,14 @@ declare module angular {
}
interface IModelValidators {
[index: string]: (modelValue: any, viewValue: string) => boolean;
/**
* viewValue is any because it can be an object that is called in the view like $viewValue.name:$viewValue.subName
*/
[index: string]: (modelValue: any, viewValue: any) => boolean;
}
interface IAsyncModelValidators {
[index: string]: (modelValue: any, viewValue: string) => IPromise<any>;
[index: string]: (modelValue: any, viewValue: any) => IPromise<any>;
}
interface IModelParser {
@@ -560,11 +572,11 @@ declare module angular {
/**
* Dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners.
*
*
* The event life cycle starts at the scope on which $broadcast was called. All listeners listening for name event on this scope get notified. Afterwards, the event propagates to all direct and indirect scopes of the current scope and calls all registered listeners along the way. The event cannot be canceled.
*
*
* Any exception emitted from the listeners will be passed onto the $exceptionHandler service.
*
*
* @param name Event name to broadcast.
* @param args Optional one or more arguments which will be passed onto the event listeners.
*/
@@ -577,7 +589,7 @@ declare module angular {
* The event life cycle starts at the scope on which $emit was called. All listeners listening for name event on this scope get notified. Afterwards, the event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.
*
* Any exception emitted from the listeners will be passed onto the $exceptionHandler service.
*
*
* @param name Event name to emit.
* @param args Optional one or more arguments which will be passed onto the event listeners.
*/
@@ -605,12 +617,12 @@ declare module angular {
$on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function;
$watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function;
$watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function;
$watch<T>(watchExpression: string, listener?: (newValue: T, oldValue: T, scope: IScope) => any, objectEquality?: boolean): Function;
$watch(watchExpression: (scope: IScope) => any, listener?: string, objectEquality?: boolean): Function;
$watch(watchExpression: (scope: IScope) => any, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function;
$watch<T>(watchExpression: (scope: IScope) => T, listener?: (newValue: T, oldValue: T, scope: IScope) => any, objectEquality?: boolean): Function;
$watchCollection(watchExpression: string, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function;
$watchCollection(watchExpression: (scope: IScope) => any, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function;
$watchCollection<T>(watchExpression: string, listener: (newValue: T, oldValue: T, scope: IScope) => any): Function;
$watchCollection<T>(watchExpression: (scope: IScope) => T, listener: (newValue: T, oldValue: T, scope: IScope) => any): Function;
$watchGroup(watchExpressions: any[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function;
$watchGroup(watchExpressions: { (scope: IScope): any }[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function;
@@ -713,8 +725,9 @@ declare module angular {
// see http://docs.angularjs.org/api/ng.$timeout
///////////////////////////////////////////////////////////////////////////
interface ITimeoutService {
(func: Function, delay?: number, invokeApply?: boolean): IPromise<any>;
cancel(promise: IPromise<any>): boolean;
(delay?: number, invokeApply?: boolean): IPromise<void>;
<T>(fn: (...args: any[]) => T, delay?: number, invokeApply?: boolean, ...args: any[]): IPromise<T>;
cancel(promise?: IPromise<any>): boolean;
}
///////////////////////////////////////////////////////////////////////////
@@ -757,16 +770,16 @@ declare module angular {
/**
* $filter - $filterProvider - service in module ng
*
*
* Filters are used for formatting data displayed to the user.
*
*
* see https://docs.angularjs.org/api/ng/service/$filter
*/
interface IFilterService {
/**
* Usage:
* $filter(name);
*
*
* @param name Name of the filter function to retrieve
*/
(name: string): Function;
@@ -774,15 +787,15 @@ declare module angular {
/**
* $filterProvider - $filter - provider in module ng
*
*
* Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To achieve this a filter definition consists of a factory function which is annotated with dependencies and is responsible for creating a filter function.
*
*
* see https://docs.angularjs.org/api/ng/provider/$filterProvider
*/
interface IFilterProvider extends IServiceProvider {
/**
* register(name);
*
*
* @param name Name of the filter function, or an object map of filters where the keys are the filter names and the values are the filter factories. Note: Filter names must be valid angular Expressions identifiers, such as uppercase or orderBy. Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace your filters, then you can use capitalization (myappSubsectionFilterx) or underscores (myapp_subsection_filterx).
*/
register(name: string | {}): IServiceProvider;
@@ -850,7 +863,7 @@ declare module angular {
warn: ILogCall;
}
interface ILogProvider {
interface ILogProvider extends IServiceProvider {
debugEnabled(): boolean;
debugEnabled(enabled: boolean): ILogProvider;
}
@@ -984,9 +997,10 @@ declare module angular {
* See http://docs.angularjs.org/api/ng/service/$q
*/
interface IQService {
new (resolver: (resolve: IQResolveReject<any>) => any): IPromise<any>;
new (resolver: (resolve: IQResolveReject<any>, reject: IQResolveReject<any>) => any): IPromise<any>;
new <T>(resolver: (resolve: IQResolveReject<T>) => any): IPromise<T>;
new <T>(resolver: (resolve: IQResolveReject<T>, reject: IQResolveReject<any>) => any): IPromise<T>;
<T>(resolver: (resolve: IQResolveReject<T>) => any): IPromise<T>;
<T>(resolver: (resolve: IQResolveReject<T>, reject: IQResolveReject<any>) => any): IPromise<T>;
/**
* Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
@@ -995,7 +1009,7 @@ declare module angular {
*
* @param promises An array of promises.
*/
all(promises: IPromise<any>[]): IPromise<any[]>;
all<T>(promises: IPromise<any>[]): IPromise<T[]>;
/**
* Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
*
@@ -1004,6 +1018,7 @@ declare module angular {
* @param promises A hash of promises.
*/
all(promises: { [id: string]: IPromise<any>; }): IPromise<{ [id: string]: any; }>;
all<T extends {}>(promises: { [id: string]: IPromise<any>; }): IPromise<T>;
/**
* Creates a Deferred object which represents a task which will finish in the future.
*/
@@ -1033,10 +1048,10 @@ declare module angular {
interface IPromise<T> {
/**
* Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected.
*
* The successCallBack may return IPromise<void> for when a $q.reject() needs to be returned
* This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method.
*/
then<TResult>(successCallback: (promiseValue: T) => IHttpPromise<TResult>|IPromise<TResult>|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise<TResult>;
then<TResult>(successCallback: (promiseValue: T) => IHttpPromise<TResult>|IPromise<TResult>|TResult|IPromise<void>, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise<TResult>;
/**
* Shorthand for promise.then(null, errorCallback)
@@ -1048,7 +1063,7 @@ declare module angular {
*
* Because finally is a reserved word in JavaScript and reserved keywords are not supported as property names by ES3, you'll need to invoke the method like promise['finally'](callback) to make your code IE8 and Android 2.x compatible.
*/
finally<TResult>(finallyCallback: () => any): IPromise<TResult>;
finally(finallyCallback: () => any): IPromise<T>;
}
interface IDeferred<T> {
@@ -1064,6 +1079,7 @@ declare module angular {
///////////////////////////////////////////////////////////////////////////
interface IAnchorScrollService {
(): void;
(hash: string): void;
yOffset: any;
}
@@ -1073,31 +1089,31 @@ declare module angular {
/**
* $cacheFactory - service in module ng
*
*
* Factory that constructs Cache objects and gives access to them.
*
*
* see https://docs.angularjs.org/api/ng/service/$cacheFactory
*/
interface ICacheFactoryService {
/**
* Factory that constructs Cache objects and gives access to them.
*
*
* @param cacheId Name or id of the newly created cache.
* @param optionsMap Options object that specifies the cache behavior. Properties:
*
*
* capacity — turns the cache into LRU cache.
*/
(cacheId: string, optionsMap?: { capacity?: number; }): ICacheObject;
/**
* Get information about all the caches that have been created.
* Get information about all the caches that have been created.
* @returns key-value map of cacheId to the result of calling cache#info
*/
info(): any;
/**
* Get access to a cache object by the cacheId used when it was created.
*
*
* @param cacheId Name or id of a cache to access.
*/
get(cacheId: string): ICacheObject;
@@ -1105,9 +1121,9 @@ declare module angular {
/**
* $cacheFactory.Cache - type in module ng
*
*
* A cache object used to store and retrieve data, primarily used by $http and the script directive to cache templates and other data.
*
*
* see https://docs.angularjs.org/api/ng/type/$cacheFactory.Cache
*/
interface ICacheObject {
@@ -1130,9 +1146,9 @@ declare module angular {
/**
* Inserts a named entry into the Cache object to be retrieved later, and incrementing the size of the cache if the key was not already present in the cache. If behaving like an LRU cache, it will also remove stale entries from the set.
*
*
* It will not insert undefined values into the cache.
*
*
* @param key the key under which the cached data is stored.
* @param value the value to store alongside the key. If it is undefined, the key will not be stored.
*/
@@ -1140,14 +1156,14 @@ declare module angular {
/**
* Retrieves named data stored in the Cache object.
*
*
* @param key the key of the data to be retrieved
*/
get(key: string): any;
get<T>(key: string): T;
/**
* Removes an entry from the Cache object.
*
*
* @param key the key of the entry to be removed
*/
remove(key: string): void;
@@ -1162,7 +1178,7 @@ declare module angular {
*/
destroy(): void;
}
///////////////////////////////////////////////////////////////////////////
// CompileService
// see http://docs.angularjs.org/api/ng.$compile
@@ -1214,8 +1230,8 @@ declare module angular {
///////////////////////////////////////////////////////////////////////////
interface IControllerService {
// Although the documentation doesn't state this, locals are optional
(controllerConstructor: Function, locals?: any): any;
(controllerName: string, locals?: any): any;
(controllerConstructor: Function, locals?: any, bindToController?: any): any;
(controllerName: string, locals?: any, bindToController?: any): any;
}
interface IControllerProvider extends IServiceProvider {
@@ -1414,6 +1430,12 @@ declare module angular {
* https://docs.angularjs.org/api/ng/service/$http#defaults
*/
interface IHttpProviderDefaults {
cache?: boolean;
/**
* Transform function or an array of such functions. The transform function takes the http request body and
* headers and returns its transformed (typically serialized) version.
*/
transformRequest?: ((data: any, headersGetter?: any) => any)|((data: any, headersGetter?: any) => any)[];
xsrfCookieName?: string;
xsrfHeaderName?: string;
withCredentials?: boolean;
@@ -1521,6 +1543,8 @@ declare module angular {
interface ISCEDelegateProvider extends IServiceProvider {
resourceUrlBlacklist(blacklist: any[]): void;
resourceUrlWhitelist(whitelist: any[]): void;
resourceUrlBlacklist(): any[];
resourceUrlWhitelist(): any[];
}
/**
@@ -1566,7 +1590,7 @@ declare module angular {
scope: IScope,
instanceElement: IAugmentedJQuery,
instanceAttributes: IAttributes,
controller: any,
controller: {},
transclude: ITranscludeFunction
): void;
}
@@ -1661,9 +1685,9 @@ declare module angular {
interface IInjectorService {
annotate(fn: Function): string[];
annotate(inlineAnnotatedFunction: any[]): string[];
get(name: string): any;
get<T>(name: string): T;
has(name: string): boolean;
instantiate(typeConstructor: Function, locals?: any): any;
instantiate<T>(typeConstructor: Function, locals?: any): T;
invoke(inlineAnnotatedFunction: any[]): any;
invoke(func: Function, context?: any, locals?: any): any;
}
+25
View File
@@ -0,0 +1,25 @@
/// <reference path="angulartics.d.ts" />
/// <reference path="../angularjs/angular.d.ts" />
module Analytics {
angular.module("angulartics.app", ["angulartics"])
.config(["$analyticsProvider", ($analyticsProvider: Angulartics.IAnalyticsServiceProvider) => {
angulartics.waitForVendorApi("location", 1000, (message: string) => {
console.log(message);
});
$analyticsProvider.virtualPageviews(false);
$analyticsProvider.firstPageview(false);
$analyticsProvider.withAutoBase(true);
$analyticsProvider.developerMode(true);
$analyticsProvider.registerEventTrack((action: string, properties?: any) => {
console.log(action);
});
$analyticsProvider.registerPageTrack((path: string, locationObj: ng.ILocationService) => {
console.log("viewed " + path);
});
}]);
}
+39
View File
@@ -0,0 +1,39 @@
// Type definitions for Angulartics v0.19.2
// Project: http://luisfarzati.github.io/angulartics/
// Definitions by: Steven Fan <https://github.com/stevenfan>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
interface Angulartics {
waitForVendorApi(objectName: string, delay: number, containsField?: any, registerFn?: any, onTimeout?: boolean): void;
}
declare module Angulartics {
interface IAnalyticsService {
eventTrack(eventName: string, properties?: any): any;
pageTrack(path: string, location?: ng.ILocationService): any;
setAlias(alias: string): any;
setUsername(username: string): any;
setUserProperties(properties: any): any;
setSuperProperties(properties: any): any;
}
interface IAnalyticsServiceProvider extends angular.IServiceProvider {
virtualPageviews(value: boolean): void;
firstPageview(value: boolean): void;
withBase(value: boolean): void;
withAutoBase(value: boolean): void;
developerMode(value: boolean): void;
registerPageTrack(callback: (path: string, location?: ng.ILocationService) => any): void;
registerEventTrack(callback: (eventName: string, properties?: any) => any): void;
registerSetAlias(callback: (alias: string) => any): void
registerSetUsername(callback: (username: string) => any): void
registerSetUserProperties(callback: (userProperties: any) => any): void
registerSetSuperProperties(callback: (superProperties: any) => any): void
}
}
declare var angulartics:Angulartics;
@@ -0,0 +1,11 @@
/// <reference path="api-error-handler.d.ts" />
import errorHandler = require('api-error-handler');
import express = require('express');
var api = express.Router();
api.get('/users/:userid', function (req, res, next) {
});
api.use(errorHandler());
+14
View File
@@ -0,0 +1,14 @@
// Type definitions for api-error-handler v1.0.0
// Project: https://github.com/expressjs/api-error-handler
// Definitions by: Tanguy Krotoff <https://github.com/tkrotoff>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
declare module 'api-error-handler' {
import express = require('express');
function apiErrorHandler(options?: any): express.ErrorRequestHandler;
export = apiErrorHandler;
}
+146
View File
@@ -0,0 +1,146 @@
///<reference path="apn.d.ts"/>
import apn = require("apn");
//Hand made TypeScript tests
//==========================
//Create with a hex string
var device1 = new apn.Device("ca11ab1e");
//Create with a Buffer
var device2 = new apn.Device(new Buffer("ca55e77e"));
//Create the notification
var notification = new apn.Notification();
notification.alert = {
title: "The Title",
body: "This is the body",
};
notification.badge = 5;
//Fluid api
notification.setAlertTitle("The Title")
.setAlertText("This is the body")
.setLaunchImage("LaunchImage");
//Establish the connection
var connection = new apn.Connection({
cert: "path/to/cert.pem",
key: "path/to/cert.pem"
});
//Testing some specialized event listeners
connection.on("error", (error) => {
console.log("push error", error.name, error.message);
});
connection.on("transmissionError", (errorCode, notification, device) => {
console.log("push failed", errorCode, "notification", notification.alert, "device id: ", device.toString());
});
//Send it using hex string
connection.pushNotification(notification, "ba5eba11");
//Send it using Buffer
connection.pushNotification(notification, new Buffer("5ca1ab1e"));
//Send it using Device
connection.pushNotification(notification, device1);
//Connecting to feedback service
var feedbackService = new apn.Feedback({
cert: "path/to/cert.pem",
key: "path/to/cert.pem",
interval: 0
});
feedbackService.on("error", (error:Error) => {
console.log("push feedback error", error.name, error.message);
});
function processFeedbackData(device:apn.Device, time:number) {
}
feedbackService.on("feedback", (feedbackData) => {
feedbackData.forEach((data) => {
processFeedbackData(data.device, data.time);
})
});
feedbackService.start();
//Original examples from apn package
//==================================
//sending-to-multiple-devices.js
//------------------------------
var tokens = ["<insert token here>", "<insert token here>"];
if(tokens[0] === "<insert token here>") {
console.log("Please set token to a valid device token for the push notification service");
process.exit();
}
// Create a connection to the service using mostly default parameters.
var service = new apn.connection({ production: false });
service.on("connected", function() {
console.log("Connected");
});
service.on("transmitted", function(notification, device) {
console.log("Notification transmitted to:" + device.token.toString("hex"));
});
service.on("transmissionError", function(errCode, notification, device) {
console.error("Notification caused error: " + errCode + " for device ", device, notification);
if (errCode === 8) {
console.log("A error code of 8 indicates that the device token is invalid. This could be for a number of reasons - are you using the correct environment? i.e. Production vs. Sandbox");
}
});
service.on("timeout", function () {
console.log("Connection Timeout");
});
service.on("disconnected", function() {
console.log("Disconnected from APNS");
});
service.on("socketError", console.error);
// If you plan on sending identical paylods to many devices you can do something like this.
function pushNotificationToMany() {
console.log("Sending the same notification each of the devices with one call to pushNotification.");
var note = new apn.notification();
note.setAlertText("Hello, from node-apn!");
note.badge = 1;
service.pushNotification(note, tokens);
}
pushNotificationToMany();
// If you have a list of devices for which you want to send a customised notification you can create one and send it to and individual device.
function pushSomeNotifications() {
console.log("Sending a tailored notification to %d devices", tokens.length);
tokens.forEach(function(token, i) {
var note = new apn.notification();
note.setAlertText("Hello, from node-apn! You are number: " + i);
note.badge = i;
service.pushNotification(note, token);
});
}
pushSomeNotifications();
//feedback.js
//-----------
function handleFeedback(feedbackData:apn.FeedbackData[]) {
feedbackData.forEach(function(feedbackItem) {
console.log("Device: " + feedbackItem.device.toString() + " has been unreachable, since: " + feedbackItem.time);
});
}
// Setup a connection to the feedback service using a custom interval (10 seconds)
var feedback = new apn.feedback({ production: false, interval: 10 });
feedback.on("feedback", handleFeedback);
feedback.on("feedbackError", console.error);
+364
View File
@@ -0,0 +1,364 @@
// Type definitions for node-apn
// Project: https://github.com/argon/node-apn
// Definitions by: Zenorbi <https://github.com/zenorbi>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path="../node/node.d.ts"/>
declare module "apn" {
import events = require("events");
import net = require("net");
export interface ConnectionOptions {
/**
* The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`)
*/
cert?:string|Buffer;
/**
* The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`)
*/
key?:string|Buffer;
/**
* An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048).
*/
ca?:(string|Buffer)[];
/**
* File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will always be used instead of certificate and key above.
*/
pfx?:string|Buffer;
/**
* The passphrase for the connection key, if required
*/
passphrase?:string;
/**
* Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly)
*/
production?:boolean;
/**
* Enable when you are using a VoIP certificate to enable paylods up to 4096 bytes.
*/
voip?:boolean;
/**
* Gateway port (Defaults to: `2195`)
*/
port?:number;
/**
* Reject Unauthorized property to be passed through to tls.connect() (Defaults to `true`)
*/
rejectUnauthorized?:boolean;
/**
* Number of notifications to cache for error purposes (See "Handling Errors" below, (Defaults to: `1000`)
*/
cacheLength?:number;
/**
* Whether the cache should grow in response to messages being lost after errors. (Will still emit a 'cacheTooSmall' event) (Defaults to: `true`)
*/
autoAdjustCache?:boolean;
/**
* The maximum number of connections to create for sending messages. (Defaults to: `1`)
*/
maxConnections?:number;
/**
* The duration of time the module should wait, in milliseconds, when trying to establish a connection to Apple before failing. 0 = Disabled. {Defaults to: `10000`}
*/
connectTimeout?:number;
/**
* The duration the socket should stay alive with no activity in milliseconds. 0 = Disabled. (Defaults to: `3600000` - 1h)
*/
connectionTimeout?:number;
/**
* The maximum number of connection failures that will be tolerated before `apn` will "terminate". (Defaults to: 10)
*/
connectionRetryLimit?:number;
/**
* Whether to buffer notifications and resend them after failure. (Defaults to: `true`)
*/
buffersNotifications?:number;
/**
* Whether to aggresively empty the notification buffer while connected - if set to true node-apn may enter a tight loop under heavy load while delivering notifications. (Defaults to: `false`)
*/
fastMode?:boolean;
}
export class Connection extends events.EventEmitter {
constructor(options:ConnectionOptions);
/**
* This is the business end of the module. Create a `Notification` object and pass it in, along with a single recipient or an array of them and node-apn will take care of the rest, delivering the notification to each recipient.
*
* A "recipient" is either a `Device` object, a `String`, or a `Buffer` containing the device token. `Device` objects are used internally and will be created if necessary. Where applicable, all events will return a `Device` regardless of the type passed to this method.
*/
pushNotification(notification:Notification, recipient:Device|string|Buffer|(Device|string|Buffer)[]):void;
/**
* Used to manually adjust the "cacheLength" property in the options. This is ideal if you choose to use the `cacheTooSmall` event to tweak your environment. It is safe for increasing and reducing cache size.
*/
setCacheLength(newLength:number):void;
/**
* Indicate to node-apn that when the queue of pending notifications is fully drained that it should close all open connections. This will mean that if there are no other pending resources (open sockets, running timers, etc.) the application will terminate. If notifications are pushed after the connection has completely shutdown a new connection will be established and, if applicable, `shutdown` will need to be called again.
*/
shutdown():void;
/**
* Emitted when an error occurs during initialisation of the module, usually due to a problem with the keys and certificates.
*/
on(event: "error", listener: (error:Error) => void):Connection;
/**
* Emitted when the connection socket experiences an error. This may be useful for debugging but no action should be necessary.
*/
on(event: "socketError", listener: (error:Error) => void):Connection;
/**
* Emitted when a notification has been sent to Apple - not a guarantee that it has been accepted by Apple, an error relating to it may occur later on. A notification may also be "transmitted" several times if a preceding notification caused an error requiring retransmission.
*/
on(event: "transmitted", listener: (notification:Notification, decive:Device) => void):Connection;
/**
* Emitted when all pending notifications have been transmitted to Apple and the pending queue is empty. This may be called more than once if a notification error occurs and notifications must be re-sent.
*/
on(event: "completed", listener: () => void):Connection;
/**
* Emitted when Apple returns a notification as invalid but the notification has already been expunged from the cache - usually due to high throughput and indicates that notifications will be getting lost. The parameter is an estimate of how many notifications have been lost. You should experiment with increasing the cache size or enabling ```autoAdjustCache``` if you see this frequently.
*
* **Note**: With ```autoAdjustCache``` enabled this event will still be emitted when an adjustment is triggered.
*/
on(event: "cacheTooSmall", listener: (sizeDifference:number) => void):Connection;
/**
* Emitted when a connection to Apple is successfully established. The parameter indicates the number of open connections. No action is required as the connection is managed internally.
*/
on(event: "connected", listener: (openSockets:net.Socket[]) => void):Connection;
/**
* Emitted when the connection to Apple has been closed, this could be for numerous reasons, for example an error has occurred or the connection has timed out. The parameter is the same as for `connected` and again, no action is required.
*/
on(event: "disconnected", listener: (openSockets:net.Socket[]) => void):Connection;
/**
* Emitted when the connectionTimeout option has been specified and no activity has occurred on a socket for a specified duration. The socket will be closed immediately after this event and a `disconnected` event will also be emitted.
*/
on(event: "timeout", listener: () => void):Connection;
/**
* Emitted when a message has been received from Apple stating that a notification was invalid or if an internal error occurred before that notification could be pushed to Apple. If the notification is still in the cache it will be passed as the second argument, otherwise null. Where possible the associated `Device` object will be passed as a third parameter, however in cases where the token supplied to the module cannot be parsed into a `Buffer` the supplied value will be returned.
* Error codes smaller than 512 correspond to those returned by Apple as per their [docs][errors]. Other errors are applicable to `node-apn` itself. Definitions can be found in `lib/errors.js`.
*/
on(event: "transmissionError", listener: (errorCode:number, notification:Notification, device:Device|Buffer) => void):Connection;
on(event: string, listener: Function):Connection;
}
export interface NotificationAlertOptions {
title?:string;
body:string;
"title-loc-key"?:string;
"title-loc-args"?:string[];
"action-loc-key"?:string;
"loc-key"?:string;
"loc-args"?:string[];
"launch-image"?:string;
}
export class Notification {
/**
* The maximum number of retries which should be performed when sending a notification if an error occurs. A value of 0 will only allow one attempt at sending (0 retries). Set to -1 to disable (default).
*/
public retryLimit:number;
/**
* The UNIX timestamp representing when the notification should expire. This does not contribute to the 2048 byte payload size limit. An expiry of 0 indicates that the notification expires immediately.
*/
public expiry:number;
/**
* From Apple's Documentation, Provide one of the following values:
*
* - 10 - The push message is sent immediately. (Default)
* > The push notification must trigger an alert, sound, or badge on the device. It is an error use this priority for a push that contains only the content-available key.
* - 5 - The push message is sent at a time that conserves power on the device receiving it.
*/
public priority:number;
/**
* The encoding to use when transmitting the notification to APNS, defaults to `utf8`. `utf16le` is also possible but as each character is represented by a minimum of 2 bytes, will at least halve the possible payload size. If in doubt leave as default.
*/
public encoding:string;
/**
* This object represents the root JSON object that you can add custom information for your application to. The properties below will only be added to the payload (under `aps`) when the notification is prepared for sending.
*/
public payload:any;
/**
* The value to specify for `payload.aps.badge`
*/
public badge:number;
/**
* The value to specify for `payload.aps.sound`
*/
public sound:string;
/**
* The value to specify for `payload.aps.alert` can be either a `String` or an `Object` as outlined by the payload documentation.
*/
public alert:string|NotificationAlertOptions;
/**
* Setting this to true will specify "content-available" in the payload when it is compiled.
*/
public newsstandAvailable:boolean;
/**
* Setting this to true will specify "content-available" in the payload when it is compiled.
*/
public contentAvailable:boolean;
/**
* The value to specify for the `mdm` field where applicable.
*/
public mdm:string|Object;
/**
* The value to specify for `payload.aps['url-args']`. This used for Safari Push NOtifications and should be an array of values in accordance with the Web Payload Documentation.
*/
public urlArgs:string[];
/**
* When this parameter is set and `notification#trim()` is called it will attempt to truncate the string at the nearest space.
*/
public truncateAtWordEnd:boolean;
/**
* You can optionally pass in an object representing the payload, or configure properties on the returned object.
*/
constructor(payload?:any);
/**
* Set the `aps.alert` text body. This will use the most space-efficient means.
*/
setAlertText(alertText:string):Notification;
/**
* Set the `title` property of the `aps.alert` object - used with Safari Push Notifications
*/
setAlertTitle(alertTitle:string):Notification;
/**
* Set the `action` property of the `aps.alert` object - used with Safari Push Notifications
*/
setAlertAction(alertAction:string):Notification;
/**
* Set the `action-loc-key` property of the `aps.alert` object.
*/
setActionLocKey(key:string):Notification;
/**
* Set the `loc-key` property of the `aps.alert` object.
*/
setLocKey(key:string):Notification;
/**
* Set the `loc-args` property of the `aps.alert` object.
*/
setLocArgs(args:string[]):Notification;
/**
* Set the `launch-image` property of the `aps.alert` object.
*/
setLaunchImage(image:string):Notification;
/**
* Set the `mdm` property on the payload.
*/
setMDM(mdm:string|Object):Notification;
/**
* Set the `content-available` property of the `aps` object.
*/
setNewsstandAvailable(available:boolean):Notification;
/**
* Set the `content-available` property of the `aps` object.
*/
setContentAvailable(available:boolean):Notification;
/**
* Set the `url-args` property of the `aps` object.
*/
setUrlArgs(urlArgs:string[]):Notification;
/**
* Attempt to automatically trim the notification alert text body to meet the payload size limit of 2048 bytes.
*/
trim():number;
}
export class Device {
public token:Buffer;
/**
* `deviceToken` can be a `Buffer` or a `String` containing a "hex" representation of the token. Throws an error if the deviceToken supplied is invalid.
*/
constructor(deviceToken:string|Buffer);
}
export interface FeedbackOptions {
/**
* The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`)
*/
cert?:string|Buffer;
/**
* The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`)
*/
key?:string|Buffer;
/**
* An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048).
*/
ca?:(string|Buffer)[];
/**
* File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will be used instead of certificate and key above.
*/
pfx?:string|Buffer;
/**
* The passphrase for the connection key, if required
*/
passphrase?:string;
/**
* Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly)
*/
production?:boolean;
/**
* Feedback server port (Defaults to: `2196`)
*/
port?:number;
/**
* Sets the behaviour for triggering the `feedback` event. When `true` the event will be triggered once per connection with an array of timestamp and device token tuples. Otherwise a `feedback` event will be emitted once per token received. (Defaults to: true)
*/
batchFeedback?:boolean;
/**
* The maximum number of tokens to pass when emitting the event - a value of 0 will cause all tokens to be passed after connection is reset. After this number of tokens are received the `feedback` event will be emitted. (Only applies when `batchFeedback` is enabled)
*/
batchSize?:number;
/**
* How often to automatically poll the feedback service. Set to `0` to disable. (Defaults to: `3600`)
*/
interval?:number;
}
export interface FeedbackData {
time:number;
device:Device;
}
/**
* Connection to the Apple Push Notification Feedback Service and if `interval` isn't disabled automatically begins polling the service. Many of the options are the same as `apn.Connection()`
*/
export class Feedback {
constructor(options:FeedbackOptions);
/**
* Trigger a query of the feedback service. If `interval` is non-zero then this method will be called automatically.
*/
start():void;
/**
* You can cancel the interval by calling `feedback.cancel()`. If you do not wish to have the service automatically queried then set `interval` to 0 and use `feedback.start()` to manually invoke it one time.
*/
cancel():void;
/**
* Emitted when an error occurs initialising the module. Usually caused by failing to load the certificates.
*/
on(event: "error", listener: (error:Error) => void):Feedback;
/**
* Emitted when an error occurs receiving or processing the feedback and in the case of a socket error occurring. These errors are usually informational and node-apn will automatically recover.
*/
on(event: "feedbackError", listener: (error:Error) => void):Feedback;
/**
* Emitted when data has been received from the feedback service, typically once per connection. `feedbackData` is an array of objects, each containing the `time` returned by the server (epoch time) and the `device` a `Buffer` containing the device token.
*/
on(event: "feedback", listener: (feedbackData:FeedbackData[]) => void):Feedback;
on(event: string, listener: Function):Feedback;
}
export enum Errors {
"noErrorsEncountered"= 0,
"processingError"= 1,
"missingDeviceToken"= 2,
"missingTopic"= 3,
"missingPayload"= 4,
"invalidTokenSize"= 5,
"invalidTopicSize"= 6,
"invalidPayloadSize"= 7,
"invalidToken"= 8,
"apnsShutdown"= 10,
"none"= 255,
"retryLimitExceeded"= 512,
"moduleInitialisationFailed"= 513,
"connectionRetryLimitExceeded"= 514, // When a connection is unable to be established. Usually because of a network / SSL error this will be emitted
"connectionTerminated"= 515
}
//Lowercase aliases
export {Connection as connection};
export {Device as device};
export {Errors as error};
export {Feedback as feedback};
export {Notification as notification};
}
+36 -4
View File
@@ -4,21 +4,25 @@
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface AutoCollectConsole {
constructor(client: Client): AutoCollectConsole;
enable(isEnabled: boolean): void;
isInitialized(): boolean;
}
interface AutoCollectExceptions {
constructor(client:Client): AutoCollectExceptions;
isInitialized(): boolean;
enable(isEnabled:boolean): void;
}
interface AutoCollectPerformance {
constructor(client: Client): AutoCollectPerformance;
enable(isEnabled: boolean): void;
isInitialized(): boolean;
}
interface AutoCollectRequests {
constructor(client: Client): AutoCollectRequests;
enable(isEnabled: boolean): void;
isInitialized(): boolean;
}
@@ -85,14 +89,17 @@ declare module ContractsModule {
sampleRate: string;
internalSdkVersion: string;
internalAgentVersion: string;
constructor(): ContextTagKeys;
}
interface Domain {
ver: number;
properties: any;
constructor(): Domain;
}
interface Data<TDomain extends ContractsModule.Domain> {
baseType: string;
baseData: TDomain;
constructor(): Data<TDomain>;
}
interface Envelope {
ver: number;
@@ -112,18 +119,21 @@ declare module ContractsModule {
[key: string]: string;
};
data: Data<Domain>;
constructor(): Envelope;
}
interface EventData extends ContractsModule.Domain {
ver: number;
name: string;
properties: any;
measurements: any;
constructor(): EventData;
}
interface MessageData extends ContractsModule.Domain {
ver: number;
message: string;
severityLevel: ContractsModule.SeverityLevel;
properties: any;
constructor(): MessageData;
}
interface ExceptionData extends ContractsModule.Domain {
ver: number;
@@ -134,6 +144,7 @@ declare module ContractsModule {
crashThreadId: number;
properties: any;
measurements: any;
constructor(): ExceptionData;
}
interface StackFrame {
level: number;
@@ -141,6 +152,7 @@ declare module ContractsModule {
assembly: string;
fileName: string;
line: number;
constructor(): StackFrame;
}
interface ExceptionDetails {
id: number;
@@ -150,6 +162,7 @@ declare module ContractsModule {
hasFullStack: boolean;
stack: string;
parsedStack: StackFrame[];
constructor(): ExceptionDetails;
}
interface DataPoint {
name: string;
@@ -159,11 +172,13 @@ declare module ContractsModule {
min: number;
max: number;
stdDev: number;
constructor(): DataPoint;
}
interface MetricData extends ContractsModule.Domain {
ver: number;
metrics: DataPoint[];
properties: any;
constructor(): MetricData;
}
interface PageViewData extends ContractsModule.EventData {
ver: number;
@@ -172,6 +187,7 @@ declare module ContractsModule {
duration: string;
properties: any;
measurements: any;
constructor(): PageViewData;
}
interface PageViewPerfData extends ContractsModule.PageViewData {
ver: number;
@@ -185,6 +201,7 @@ declare module ContractsModule {
domProcessing: string;
properties: any;
measurements: any;
constructor(): PageViewPerfData;
}
interface RemoteDependencyData extends ContractsModule.Domain {
ver: number;
@@ -202,6 +219,7 @@ declare module ContractsModule {
commandName: string;
dependencyTypeName: string;
properties: any;
constructor(): RemoteDependencyData;
}
interface AjaxCallData extends ContractsModule.PageViewData {
ver: number;
@@ -218,6 +236,7 @@ declare module ContractsModule {
success: boolean;
properties: any;
measurements: any;
constructor(): AjaxCallData;
}
interface RequestData extends ContractsModule.Domain {
ver: number;
@@ -231,10 +250,12 @@ declare module ContractsModule {
url: string;
properties: any;
measurements: any;
constructor(): RequestData;
}
interface SessionStateData extends ContractsModule.Domain {
ver: number;
state: ContractsModule.SessionState;
constructor(): SessionStateData;
}
interface PerformanceCounterData extends ContractsModule.Domain {
ver: number;
@@ -248,6 +269,7 @@ declare module ContractsModule {
stdDev: number;
value: number;
properties: any;
constructor(): PerformanceCounterData;
}
}
@@ -309,10 +331,14 @@ interface Client {
* Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators.
* To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the
* telemetry bandwidth by aggregating multiple measurements and sending the resulting average at intervals.
* @param name A string that identifies the metric.
* @param value The value of the metric
* @param name A string that identifies the metric.
* @param value The value of the metric
* @param count the number of samples used to get this value
* @param min the min sample for this set
* @param max the max sample for this set
* @param stdDev the standard deviation of the set
*/
trackMetric(name: string, value: number): void;
trackMetric(name: string, value: number, count?:number, min?: number, max?: number, stdDev?: number): void;
trackRequest(request: any /* http.ServerRequest */, response: any /* http.ServerResponse */, properties?: {
[key: string]: string;
}): void;
@@ -381,10 +407,16 @@ declare class ApplicationInsights {
private static _performance;
private static _requests;
private static _isStarted;
/**
* Initializes a client with the given instrumentation key, if this is not specified, the value will be
* read from the environment variable APPINSIGHTS_INSTRUMENTATIONKEY
* @returns {ApplicationInsights/Client} a new client
*/
static getClient(instrumentationKey?: string): Client;
/**
* Initializes the default client of the client and sets the default configuration
* @param instrumentationKey the instrumentation key to use. Optional, if this is not specified, the value will be
* read from the environment variable APPINSIGHTS_INSTRUMENTATION_KEY
* read from the environment variable APPINSIGHTS_INSTRUMENTATIONKEY
* @returns {ApplicationInsights} this interface
*/
static setup(instrumentationKey?: string): typeof ApplicationInsights;
+2151 -1245
View File
File diff suppressed because it is too large Load Diff
+121 -16
View File
@@ -5,8 +5,19 @@ var fs, path;
function callback() {}
async.map(['file1', 'file2', 'file3'], fs.stat, function (err, results) { });
async.mapSeries(['file1', 'file2', 'file3'], fs.stat, function (err, results) { });
async.mapLimit(['file1', 'file2', 'file3'], 2, fs.stat, function (err, results) { });
async.filter(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.filterSeries(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.filterLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { });
async.select(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.selectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.selectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { });
async.reject(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.rejectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.rejectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { });
async.parallel([
function () { },
@@ -25,6 +36,11 @@ async.map(data, asyncProcess, function (err, results) {
});
var openFiles = ['file1', 'file2'];
var openFilesObj = {
file1: "fileOne",
file2: "fileTwo"
}
var saveFile = function () { }
async.each(openFiles, saveFile, function (err) { });
async.eachSeries(openFiles, saveFile, function (err) { });
@@ -32,18 +48,34 @@ async.eachSeries(openFiles, saveFile, function (err) { });
var documents, requestApi;
async.eachLimit(documents, 20, requestApi, function (err) { });
async.map(['file1', 'file2', 'file3'], fs.stat, function (err, results) { });
async.filter(['file1', 'file2', 'file3'], path.exists, function (results) { });
// forEachOf* functions. May accept array or object.
function forEachOfIterator(item, key, forEachOfIteratorCallback) {
console.log("ForEach: item=" + item + ", key=" + key);
forEachOfIteratorCallback();
}
async.forEachOf(openFiles, forEachOfIterator, function (err) { });
async.forEachOf(openFilesObj, forEachOfIterator, function (err) { });
async.forEachOfSeries(openFiles, forEachOfIterator, function (err) { });
async.forEachOfSeries(openFilesObj, forEachOfIterator, function (err) { });
async.forEachOfLimit(openFiles, 2, forEachOfIterator, function (err) { });
async.forEachOfLimit(openFilesObj, 2, forEachOfIterator, function (err) { });
var process;
async.reduce([1, 2, 3], 0, function (memo, item, callback) {
var numArray = [1, 2, 3];
function reducer(memo, item, callback) {
process.nextTick(function () {
callback(null, memo + item)
});
}, function (err, result) { });
}
async.reduce(numArray, 0, reducer, function (err, result) { });
async.inject(numArray, 0, reducer, function (err, result) { });
async.foldl(numArray, 0, reducer, function (err, result) { });
async.reduceRight(numArray, 0, reducer, function (err, result) { });
async.foldr(numArray, 0, reducer, function (err, result) { });
async.detect(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.detectSeries(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.detectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { });
async.sortBy(['file1', 'file2', 'file3'], function (file, callback) {
fs.stat(file, function (err, stats) {
@@ -52,10 +84,18 @@ async.sortBy(['file1', 'file2', 'file3'], function (file, callback) {
}, function (err, results) { });
async.some(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.someLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { });
async.any(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.every(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.everyLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { });
async.all(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.concat(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { });
async.concatSeries(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { });
// Control Flow //
async.series([
function (callback) {
@@ -77,7 +117,6 @@ async.series<string>([
],
function (err, results) { });
async.series({
one: function (callback) {
setTimeout(function () {
@@ -173,21 +212,47 @@ async.parallel<number>({
}, 100);
},
},
function (err, results) { });
function (err, results) { });
var count = 0;
async.whilst(
function () { return count < 5; },
function (callback) {
count++;
setTimeout(callback, 1000);
async.parallelLimit({
one: function (callback) {
setTimeout(function () {
callback(null, 1);
}, 200);
},
function (err) { }
two: function (callback) {
setTimeout(function () {
callback(null, 2);
}, 100);
},
},
2,
function (err, results) { }
);
function whileFn(callback) {
count++;
setTimeout(callback, 1000);
}
function whileTest() { return count < 5; }
var count = 0;
async.whilst(whileTest, whileFn, function (err) { });
async.until(whileTest, whileFn, function (err) { });
async.doWhilst(whileFn, whileTest, function (err) { });
async.doUntil(whileFn, whileTest, function (err) { });
async.during(function (testCallback) { testCallback(new Error(), false); }, function (callback) { callback() }, function (error) { console.log(error) });
async.doDuring(function (callback) { callback() }, function (testCallback) { testCallback(new Error(), false); }, function (error) { console.log(error) });
async.forever(function (errBack) {
errBack(new Error("Not going on forever."));
},
function (error) {
console.log(error);
}
);
async.waterfall([
function (callback) {
callback(null, 'one', 'two');
@@ -279,6 +344,26 @@ q2.unshift(['task3', 'task4', 'task5'], function (error) {
console.log('Finished tasks');
});
// create a cargo object with payload 2
var cargo = async.cargo(function (tasks, callback) {
for (var i = 0; i < tasks.length; i++) {
console.log('hello ' + tasks[i].name);
}
callback();
}, 2);
// add some items
cargo.push({ name: 'foo' }, function (err) {
console.log('finished processing foo');
});
cargo.push({ name: 'bar' }, function (err) {
console.log('finished processing bar');
});
cargo.push({ name: 'baz' }, function (err) {
console.log('finished processing baz');
});
var filename = '';
async.auto({
get_data: function (callback) { },
@@ -291,6 +376,9 @@ async.auto({
email_link: ['write_file', <any>function (callback, results) { }]
});
async.retry(3, function (callback, results) { }, function (err, result) { });
async.retry({ times: 3, interval: 200 }, function (callback, results) { }, function (err, result) { });
async.parallel([
function (callback) { },
@@ -336,3 +424,20 @@ var slow_fn = function (name, callback) {
};
var fn = async.memoize(slow_fn);
fn('some name', function () {});
async.unmemoize(fn);
async.ensureAsync(function () { });
async.constant(42);
async.asyncify(function () { });
async.log(function (name, callback) {
setTimeout(function () {
callback(null, 'hello ' + name);
}, 0);
}, "world"
);
async.dir(function (name, callback) {
setTimeout(function () {
callback(null, { hello: name });
}, 1000);
}, "world");
+165 -122
View File
@@ -1,122 +1,165 @@
// Type definitions for Async 0.9.2
// Project: https://github.com/caolan/async
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface Dictionary<T> { [key: string]: T; }
interface ErrorCallback { (err?: Error): void; }
interface AsyncResultCallback<T> { (err: Error, result: T): void; }
interface AsyncResultArrayCallback<T> { (err: Error, results: T[]): void; }
interface AsyncResultObjectCallback<T> { (err: Error, results: Dictionary<T>): void; }
interface AsyncIterator<T> { (item: T, callback: ErrorCallback): void; }
interface AsyncResultIterator<T, R> { (item: T, callback: AsyncResultCallback<R>): void; }
interface AsyncMemoIterator<T, R> { (memo: R, item: T, callback: AsyncResultCallback<R>): void; }
interface AsyncWorker<T> { (task: T, callback: ErrorCallback): void; }
interface AsyncFunction<T> { (callback: AsyncResultCallback<T>): void; }
interface AsyncVoidFunction { (callback: ErrorCallback): void; }
interface AsyncQueue<T> {
length(): number;
concurrency: number;
started: boolean;
paused: boolean;
push(task: T, callback?: ErrorCallback): void;
push(task: T[], callback?: ErrorCallback): void;
unshift(task: T, callback?: ErrorCallback): void;
unshift(task: T[], callback?: ErrorCallback): void;
saturated: () => any;
empty: () => any;
drain: () => any;
running(): number;
idle(): boolean;
pause(): void;
resume(): void;
kill(): void;
}
interface AsyncPriorityQueue<T> {
length(): number;
concurrency: number;
started: boolean;
paused: boolean;
push(task: T, priority: number, callback?: AsyncResultArrayCallback<T>): void;
push(task: T[], priority: number, callback?: AsyncResultArrayCallback<T>): void;
saturated: () => any;
empty: () => any;
drain: () => any;
running(): number;
idle(): boolean;
pause(): void;
resume(): void;
kill(): void;
}
interface Async {
// Collections
each<T>(arr: T[], iterator: AsyncIterator<T>, callback: ErrorCallback): void;
eachSeries<T>(arr: T[], iterator: AsyncIterator<T>, callback: ErrorCallback): void;
eachLimit<T>(arr: T[], limit: number, iterator: AsyncIterator<T>, callback: ErrorCallback): void;
map<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback: AsyncResultArrayCallback<R>): any;
mapSeries<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback: AsyncResultArrayCallback<R>): any;
mapLimit<T, R>(arr: T[], limit: number, iterator: AsyncResultIterator<T, R>, callback: AsyncResultArrayCallback<R>): any;
filter<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (results: T[]) => any): any;
select<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (results: T[]) => any): any;
filterSeries<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (results: T[]) => any): any;
selectSeries<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (results: T[]) => any): any;
reject<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (results: T[]) => any): any;
rejectSeries<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (results: T[]) => any): any;
reduce<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
inject<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
foldl<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
reduceRight<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
foldr<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
detect<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: AsyncResultArrayCallback<T>): any;
detectSeries<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: AsyncResultArrayCallback<T>): any;
sortBy<T, V>(arr: T[], iterator: AsyncResultIterator<T, V>, callback: AsyncResultArrayCallback<T>): any;
some<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: AsyncResultArrayCallback<T>): any;
any<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: AsyncResultArrayCallback<T>): any;
every<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (result: boolean) => any): any;
all<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (result: boolean) => any): any;
concat<T, R>(arr: T[], iterator: AsyncResultIterator<T, R[]>, callback: AsyncResultArrayCallback<R>): any;
concatSeries<T, R>(arr: T[], iterator: AsyncResultIterator<T, R[]>, callback: AsyncResultArrayCallback<R>): any;
// Control Flow
series<T>(tasks: Array<AsyncFunction<T>>, callback?: AsyncResultArrayCallback<T>): void;
series<T>(tasks: Dictionary<AsyncFunction<T>>, callback?: AsyncResultObjectCallback<T>): void;
parallel<T>(tasks: Array<AsyncFunction<T>>, callback?: AsyncResultArrayCallback<T>): void;
parallel<T>(tasks: Dictionary<AsyncFunction<T>>, callback?: AsyncResultObjectCallback<T>): void;
parallelLimit<T>(tasks: Array<AsyncFunction<T>>, limit: number, callback?: AsyncResultArrayCallback<T>): void;
parallelLimit<T>(tasks: Dictionary<AsyncFunction<T>>, limit: number, callback?: AsyncResultObjectCallback<T>): void;
whilst(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void;
until(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void;
waterfall(tasks: Function[], callback?: (err: any, ...arguments: any[]) => void): void;
queue<T>(worker: AsyncWorker<T>, concurrency: number): AsyncQueue<T>;
priorityQueue<T>(worker: AsyncWorker<T>, concurrency: number): AsyncPriorityQueue<T>;
auto(tasks: any, callback?: AsyncResultArrayCallback<any>): void;
iterator(tasks: Function[]): Function;
apply(fn: Function, ...arguments: any[]): AsyncFunction<any>;
nextTick(callback: Function): void;
times<R> (n: number, iterator: AsyncResultIterator<number, R>, callback: AsyncResultArrayCallback<R>): void;
timesSeries<R> (n: number, iterator: AsyncResultIterator<number, R>, callback: AsyncResultArrayCallback<R>): void;
// Utils
memoize(fn: Function, hasher?: Function): Function;
unmemoize(fn: Function): Function;
log(fn: Function, ...arguments: any[]): void;
dir(fn: Function, ...arguments: any[]): void;
noConflict(): Async;
}
declare var async: Async;
declare module "async" {
export = async;
}
// Type definitions for Async 1.4.2
// Project: https://github.com/caolan/async
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Arseniy Maximov <https://github.com/kern0>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface Dictionary<T> { [key: string]: T; }
interface ErrorCallback { (err?: Error): void; }
interface AsyncResultCallback<T> { (err: Error, result: T): void; }
interface AsyncResultArrayCallback<T> { (err: Error, results: T[]): void; }
interface AsyncResultObjectCallback<T> { (err: Error, results: Dictionary<T>): void; }
interface AsyncFunction<T> { (callback: (err: Error, result?: T) => void): void; }
interface AsyncIterator<T> { (item: T, callback: ErrorCallback): void; }
interface AsyncForEachOfIterator<T> { (item: T, key: number, callback: ErrorCallback): void; }
interface AsyncResultIterator<T, R> { (item: T, callback: AsyncResultCallback<R>): void; }
interface AsyncMemoIterator<T, R> { (memo: R, item: T, callback: AsyncResultCallback<R>): void; }
interface AsyncBooleanIterator<T> { (item: T, callback: (truthValue: boolean) => void): void; }
interface AsyncWorker<T> { (task: T, callback: ErrorCallback): void; }
interface AsyncVoidFunction { (callback: ErrorCallback): void; }
interface AsyncQueue<T> {
length(): number;
started: boolean;
running(): number;
idle(): boolean;
concurrency: number;
push(task: T, callback?: ErrorCallback): void;
push(task: T[], callback?: ErrorCallback): void;
unshift(task: T, callback?: ErrorCallback): void;
unshift(task: T[], callback?: ErrorCallback): void;
saturated: () => any;
empty: () => any;
drain: () => any;
paused: boolean;
pause(): void
resume(): void;
kill(): void;
}
interface AsyncPriorityQueue<T> {
length(): number;
concurrency: number;
started: boolean;
paused: boolean;
push(task: T, priority: number, callback?: AsyncResultArrayCallback<T>): void;
push(task: T[], priority: number, callback?: AsyncResultArrayCallback<T>): void;
saturated: () => any;
empty: () => any;
drain: () => any;
running(): number;
idle(): boolean;
pause(): void;
resume(): void;
kill(): void;
}
interface AsyncCargo {
length(): number;
payload: number;
push(task: any, callback? : Function): void;
push(task: any[], callback? : Function): void;
saturated(): void;
empty(): void;
drain(): void;
idle(): boolean;
pause(): void;
resume(): void;
kill(): void;
}
interface Async {
// Collections
each<T>(arr: T[], iterator: AsyncIterator<T>, callback?: ErrorCallback): void;
eachSeries<T>(arr: T[], iterator: AsyncIterator<T>, callback?: ErrorCallback): void;
eachLimit<T>(arr: T[], limit: number, iterator: AsyncIterator<T>, callback?: ErrorCallback): void;
forEachOf(obj: any, iterator: (item: any, key: [string|number], callback?: ErrorCallback) => void, callback: ErrorCallback): void;
forEachOf<T>(obj: T[], iterator: AsyncForEachOfIterator<T>, callback?: ErrorCallback): void;
forEachOfSeries(obj: any, iterator: (item: any, key: [string|number], callback?: ErrorCallback) => void, callback: ErrorCallback): void;
forEachOfSeries<T>(obj: T[], iterator: AsyncForEachOfIterator<T>, callback?: ErrorCallback): void;
forEachOfLimit(obj: any, limit: number, iterator: (item: any, key: [string|number], callback?: ErrorCallback) => void, callback: ErrorCallback): void;
forEachOfLimit<T>(obj: T[], limit: number, iterator: AsyncForEachOfIterator<T>, callback?: ErrorCallback): void;
map<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
mapSeries<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
mapLimit<T, R>(arr: T[], limit: number, iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
filter<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback?: (results: T[]) => any): any;
select<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback?: (results: T[]) => any): any;
filterSeries<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback?: (results: T[]) => any): any;
selectSeries<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback?: (results: T[]) => any): any;
filterLimit<T>(arr: T[], limit: number, iterator: AsyncResultIterator<T, boolean>, callback?: (results: T[]) => any): any;
selectLimit<T>(arr: T[], limit: number, iterator: AsyncResultIterator<T, boolean>, callback?: (results: T[]) => any): any;
reject<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback?: (results: T[]) => any): any;
rejectSeries<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback?: (results: T[]) => any): any;
rejectLimit<T>(arr: T[], limit: number, iterator: AsyncResultIterator<T, boolean>, callback?: (results: T[]) => any): any;
reduce<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
inject<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
foldl<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
reduceRight<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
foldr<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
detect<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: T) => void): any;
detectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: T) => void): any;
detectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: T) => void): any;
sortBy<T, V>(arr: T[], iterator: AsyncResultIterator<T, V>, callback?: AsyncResultArrayCallback<T>): any;
some<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
someLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
any<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
every<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => any): any;
everyLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => any): any;
all<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => any): any;
concat<T, R>(arr: T[], iterator: AsyncResultIterator<T, R[]>, callback?: AsyncResultArrayCallback<R>): any;
concatSeries<T, R>(arr: T[], iterator: AsyncResultIterator<T, R[]>, callback?: AsyncResultArrayCallback<R>): any;
// Control Flow
series<T>(tasks: AsyncFunction<T>[], callback?: AsyncResultArrayCallback<T>): void;
series<T>(tasks: Dictionary<AsyncFunction<T>>, callback?: AsyncResultObjectCallback<T>): void;
parallel<T>(tasks: Array<AsyncFunction<T>>, callback?: AsyncResultArrayCallback<T>): void;
parallel<T>(tasks: Dictionary<AsyncFunction<T>>, callback?: AsyncResultObjectCallback<T>): void;
parallelLimit<T>(tasks: Array<AsyncFunction<T>>, limit: number, callback?: AsyncResultArrayCallback<T>): void;
parallelLimit<T>(tasks: Dictionary<AsyncFunction<T>>, limit: number, callback?: AsyncResultObjectCallback<T>): void;
whilst(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void;
until(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void;
during(test: (testCallback : (error: Error, truth: boolean) => void) => void, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doDuring(fn: AsyncVoidFunction, test: (testCallback: (error: Error, truth: boolean) => void) => void, callback: (err: any) => void): void;
forever(next: (errCallback : (err: Error) => void) => void, errBack: (err: Error) => void) : void;
waterfall(tasks: Function[], callback?: (err: Error, result: any) => void): void;
compose(...fns: Function[]): void;
seq(...fns: Function[]): void;
applyEach(fns: Function[], argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
applyEachSeries(fns: Function[], argsAndCallback: any[]): void; // applyEachSeries(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
queue<T>(worker: AsyncWorker<T>, concurrency?: number): AsyncQueue<T>;
priorityQueue<T>(worker: AsyncWorker<T>, concurrency: number): AsyncPriorityQueue<T>;
cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo;
auto(tasks: any, callback?: (error: Error, results: any) => void): void;
retry<T>(opts: number, task: (callback : AsyncResultCallback<T>, results: any) => void, callback: (error: Error, results: any) => void): void;
retry<T>(opts: { times: number, interval: number }, task: (callback: AsyncResultCallback<T>, results : any) => void, callback: (error: Error, results: any) => void): void;
iterator(tasks: Function[]): Function;
apply(fn: Function, ...arguments: any[]): AsyncFunction<any>;
nextTick(callback: Function): void;
setImmediate(callback: Function): void;
times<T> (n: number, iterator: AsyncResultIterator<number, T>, callback: AsyncResultArrayCallback<T>): void;
timesSeries<T>(n: number, iterator: AsyncResultIterator<number, T>, callback: AsyncResultArrayCallback<T>): void;
timesLimit<T>(n: number, limit: number, iterator: AsyncResultIterator<number, T>, callback: AsyncResultArrayCallback<T>): void;
// Utils
memoize(fn: Function, hasher?: Function): Function;
unmemoize(fn: Function): Function;
ensureAsync(fn: (... argsAndCallback: any[]) => void): Function;
constant(...values: any[]): Function;
asyncify(fn: Function): Function;
wrapSync(fn: Function): Function;
log(fn: Function, ...arguments: any[]): void;
dir(fn: Function, ...arguments: any[]): void;
noConflict(): Async;
}
declare var async: Async;
declare module "async" {
export = async;
}
+3
View File
@@ -0,0 +1,3 @@
[*.ts]
indent_style = tab
indent_size = 4
+20
View File
@@ -0,0 +1,20 @@
/// <reference path="./atom-keymap.d.ts" />
import { KeymapManager, ICompleteMatchEvent } from "atom-keymap";
var manager = new KeymapManager();
manager.add('some/unique/path', {
'.workspace': {
'ctrl-x': 'package:do-something',
'ctrl-y': 'package:do-something-else'
},
'.mini.editor': {
'enter': 'core:confirm'
}
});
manager.onDidMatchBinding((event: ICompleteMatchEvent): void => {
console.log(event.binding.command);
})
manager.destroy();
+135
View File
@@ -0,0 +1,135 @@
// Type definitions for atom-keymap v5.1.5
// Project: https://github.com/atom/atom-keymap/
// Definitions by: Vadim Macagon <https://github.com/enlight/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../event-kit/event-kit.d.ts" />
declare module AtomKeymap {
type Disposable = AtomEventKit.Disposable;
/** Instance side of KeyBinding class. */
interface KeyBinding {
enabled: boolean;
source: string;
command: string;
keystrokes: string;
keystrokeCount: number;
selector: string;
specificity: number;
matches(keystroke: string): boolean;
compare(keyBinding: KeyBinding): number;
}
interface ICompleteMatchEvent {
/** Keystrokes that matched the binding. */
keystrokes: string;
/** Binding that was matched to the keystrokes. */
binding: KeyBinding;
/** DOM element that was the target of the most recent `KeyboardEvent`. */
keyboardEventTarget: Element;
}
interface IPartialMatchEvent {
/** Keystrokes that matched the binding. */
keystrokes: string;
/** Bindings that were partially matched to the keystrokes. */
partiallyMatchedBindings: KeyBinding[];
/** DOM element that was the target of the most recent `KeyboardEvent`. */
keyboardEventTarget: Element;
}
interface IFailedMatchEvent {
/** Keystrokes that failed to match a binding. */
keystrokes: string;
/** DOM element that was the target of the most recent `KeyboardEvent`. */
keyboardEventTarget: Element;
}
interface IKeymapLoadEvent {
/** Path to a keymap file. */
path: string;
}
/** Static side of KeymapManager class. */
interface KeymapManagerStatic {
prototype: KeymapManager;
new (options?: { defaultTarget?: Element }): KeymapManager;
}
/** Instance side of KeymapManager class. */
interface KeymapManager {
constructor: KeymapManagerStatic;
/** Unwatches all watched paths. */
destroy(): void;
// Event Subscription
/** Sets callback to invoke when one or more keystrokes completely match a key binding. */
onDidMatchBinding(callback: (event: ICompleteMatchEvent) => void): Disposable;
/** Sets callback to invoke when one or more keystrokes partially match a binding. */
onDidPartiallyMatchBindings(callback: (event: IPartialMatchEvent) => void): Disposable;
/** Sets callback to invoke when one or more keystrokes fail to match any bindings. */
onDidFailToMatchBinding(callback: (event: IFailedMatchEvent) => void): Disposable;
/** Sets callback to invoke when a keymap file is reloaded. */
onDidReloadKeymap(callback: (event: IKeymapLoadEvent) => void): Disposable;
/** Sets callback to invoke when a keymap file is unloaded. */
onDidUnloadKeymap(callback: (event: IKeymapLoadEvent) => void): Disposable;
/** Sets callback to invoke when a keymap file could not to be loaded. */
onDidFailToReadFile(callback: (error: Error) => void): Disposable;
// Adding and Removing Bindings
/** Adds sets of key bindings grouped by CSS selector. */
add(source: string, keyBindingsBySelector: any): Disposable;
// Accessing Bindings
getKeyBindings(): KeyBinding[];
findKeyBindings(params?: {
keystrokes: string; // e.g. 'ctrl-x ctrl-s'
command: string; // e.g. 'editor:backspace'
target?: Element;
}): KeyBinding[];
// Managing Keymap Files
/**
* Loads the key bindings from the given path.
*
* @param bindingsPath A path to a file or a directory. If the path is a directory all files
* inside it will be loaded.
*/
loadKeymap(bindingsPath: string, options?: { watch: boolean }): void;
/**
* Starts watching the given file/directory for changes, reloading any keymaps at that location
* when changes are detected.
*
* @param filePath A path to a file or a directory.
*/
watchKeymap(filePath: string): void;
// Managing Keyboard Events
/**
* Dispatches a custom event associated with the matching key binding for the given
* `KeyboardEvent` if one can be found.
*/
handleKeyboardEvent(event: KeyboardEvent): void;
/** Translates a keydown event to a keystroke string. */
keystrokeForKeyboardEvent(event: KeyboardEvent): string;
/**
* @return The number of milliseconds allowed before pending states caused by partial matches of
* multi-keystroke bindings are terminated.
*/
getPartialMatchTimeout(): number;
}
/** Allows commands to be associated with keystrokes in a context-sensitive way.*/
var KeymapManager: KeymapManagerStatic;
}
declare module 'atom-keymap' {
export = AtomKeymap;
}
+130 -23
View File
@@ -25,15 +25,36 @@ interface Window {
declare module AtomCore {
// https://atom.io/docs/v0.84.0/advanced/view-system
// https://atom.io/docs/v0.84.0/advanced/view-system
interface IWorkspaceViewStatic {
new ():IWorkspaceView;
version: number;
configDefaults:any;
content():any;
}
interface Decoration {
destroy(): void;
}
/**
* Represents a buffer annotation that remains logically stationary even as the buffer changes. This is used
* to represent cursors, folds, snippet targets, misspelled words, any anything else that needs to track a
* logical location in the buffer over time.
*/
interface Marker {
/**
* Destroys the marker, causing it to emit the 'destroyed' event. Once destroyed, a marker cannot be
* restored by undo/redo operations.
*/
destroy(): void;
/**
* Gets the screen range of the display marker.
*/
getScreenRange(): Range;
}
interface IWorkspaceView extends View {
// Delegator.includeInto(WorkspaceView);
@@ -143,6 +164,12 @@ declare module AtomCore {
highlightLines():boolean;
}
interface ICommandRegistry {
add(selector: string, name: string, callback: (event: any) => void): void; // selector:'atom-editor'|'atom-workspace'
findCommands(params: Object): Object[];
dispatch(selector: any, name:string): void;
}
interface ICommandPanel {
// TBD
}
@@ -344,11 +371,20 @@ declare module AtomCore {
foldForMarker(marker:any):any;
}
interface IViewRegistry {
getView(selector:any):any;
}
interface ICursorStatic {
new (arg:{editor:IEditor; marker:IDisplayBufferMarker; id: number;}):ICursor;
}
interface ScopeDescriptor {
scopes: string[];
}
interface ICursor /* extends Theorist.Model */ {
getScopeDescriptor(): ScopeDescriptor;
screenPosition:any;
bufferPosition:any;
goalColumn:any;
@@ -413,6 +449,7 @@ declare module AtomCore {
isAtEndOfLine():boolean;
getScopes():string[];
hasPrecedingCharactersOnLine():boolean;
getMarker(): Marker;
}
interface ILanguageMode {
@@ -561,11 +598,16 @@ declare module AtomCore {
subscribeToDisplayBuffer():void;
getViewClass():any; // return type are EditorView
destroyed():void;
isDestroyed():boolean;
copy():IEditor;
getTitle():string;
getLongTitle():string;
setVisible(visible:boolean):void;
setMini(mini:any):void;
setScrollTop(scrollTop:any):void;
getScrollTop():number;
setScrollLeft(scrollLeft:any):void;
getScrollLeft():number;
setEditorWidthInChars(editorWidthInChars:any):void;
getSoftWrapColumn():number;
getSoftTabs():boolean;
@@ -717,7 +759,7 @@ declare module AtomCore {
getSelectedBufferRanges():TextBuffer.IRange[];
getSelectedText():string;
getTextInBufferRange(range:TextBuffer.IRange):string;
setTextInBufferRange(range:TextBuffer.IRange, text:string):any;
setTextInBufferRange(range:TextBuffer.IRange | any[], text:string):any;
getCurrentParagraphBufferRange():TextBuffer.IRange;
getWordUnderCursor(options?:any):string;
moveCursorUp(lineCount?:number):void;
@@ -760,6 +802,7 @@ declare module AtomCore {
selectToPreviousWordBoundary():ISelection[];
selectToNextWordBoundary():ISelection[];
selectLine():ISelection[];
selectLinesContainingCursors():ISelection[];
addSelectionBelow():ISelection[];
addSelectionAbove():ISelection[];
splitSelectionsIntoLines():any[];
@@ -841,14 +884,43 @@ declare module AtomCore {
getVerticalScrollbarWidth():any;
setVerticalScrollbarWidth(width:any):any;
// deprecated joinLine():any;
onDidChange(callback: Function): Disposable;
onDidDestroy(callback: Function): Disposable;
onDidStopChanging(callback: Function): Disposable;
onDidChangeCursorPosition(callback: Function): Disposable;
onDidSave(callback: (event: { path: string }) => void): Disposable;
decorateMarker(marker: Marker, options: any): Decoration;
getLastCursor(): ICursor;
}
interface IGrammar {
bundledPackage: boolean;
emitter: any;
fileTypes: [string];
firstLineRegex: any;
foldingStopMarker: any;
includedGrammarScopes: [any];
initialRule: any;
injectionSelector: any;
injections: any;
maxTokensPerLine: Number;
name: string;
packageName: string;
path: string;
rawPatterns: [any];
rawRepository: any;
registration: Disposable;
registry: any;
repository: Object;
scopeName: string;
// TBD
}
interface IPane /* extends Theorist.Model */ {
itemForURI: (uri:string)=>IEditor;
items:any[];
activeItem:any;
@@ -856,6 +928,7 @@ declare module AtomCore {
deserializeParams(params:any):any;
getViewClass():any; // return type are PaneView
isActive():boolean;
isDestroyed():boolean;
focus():void;
blur():void;
activate():void;
@@ -886,7 +959,6 @@ declare module AtomCore {
saveItem(item:any, nextAction:Function):void;
saveItemAs(item:any, nextAction:Function):void;
saveItems():any[];
itemForURI(uri:any):any;
activateItemForURI(uri:any):any;
copyActiveItem():void;
splitLeft(params:any):IPane;
@@ -898,7 +970,7 @@ declare module AtomCore {
findOrCreateRightmostSibling():IPane;
}
// https://atom.io/docs/v0.84.0/advanced/serialization
// https://atom.io/docs/v0.84.0/advanced/serialization
interface ISerializationStatic<T> {
deserialize(data:ISerializationInfo):T;
new (data:T): ISerialization;
@@ -934,7 +1006,9 @@ declare module AtomCore {
// Serializable.includeInto(Project);
path:string;
rootDirectory:PathWatcher.IDirectory;
/** deprecated */
rootDirectory?:PathWatcher.IDirectory;
rootDirectories:PathWatcher.IDirectory[];
serializeParams():any;
deserializeParams(params:any):any;
@@ -964,26 +1038,52 @@ declare module AtomCore {
replace(regex:any, replacementText:any, filePaths:any, iterator:any):Q.Promise<any>;
buildEditorForBuffer(buffer:any, editorOptions:any):IEditor;
eachBuffer(...args:any[]):any;
onDidChangePaths(callback: Function): Disposable;
}
interface IWorkspaceStatic {
new():IWorkspace;
}
interface IWorkspacePanelOptions{
item:any;
visible?:boolean;
priority?:number;
}
interface Panel{
getItem():any;
getPriority():any;
isVisible():boolean;
show():void;
hide():void;
}
interface IWorkspace {
addBottomPanel(options:IWorkspacePanelOptions):Panel;
addLeftPanel(options:IWorkspacePanelOptions):Panel;
addRightPanel(options:IWorkspacePanelOptions):Panel;
addTopPanel(options:IWorkspacePanelOptions):Panel;
addModalPanel(options:IWorkspacePanelOptions):Panel;
addOpener(opener: Function): any;
deserializeParams(params:any):any;
serializeParams():{paneContainer:any;fullScreen:boolean;};
eachEditor(callback:Function):void;
getEditors():IEditor[];
eachEditor(callback: Function): void;
getTextEditors():IEditor[];
open(uri:string, options:any):Q.Promise<View>;
openLicense():void;
openSync(uri:string, options:any):any;
openURIInPane(uri:string, pane:any, options:any):Q.Promise<View>;
openUriInPane(uri: string, pane: any, options: any): Q.Promise<View>;
observeTextEditors(callback: Function): Disposable;
reopenItemSync():any;
registerOpener(opener:(urlToOpen:string)=>any):void;
unregisterOpener(opener:Function):void;
getOpeners():any;
getActivePane(): IPane;
getActivePaneItem(): IPane;
getActiveTextEditor(): IEditor;
getPanes():any;
saveAll():void;
activateNextPane():any;
@@ -1000,6 +1100,8 @@ declare module AtomCore {
itemOpened(item:any):void;
onPaneItemDestroyed(item:any):void;
destroyed():void;
onDidChangeActivePaneItem(item:any):Disposable;
}
interface IAtomSettings {
@@ -1041,7 +1143,7 @@ declare module AtomCore {
// TBD
}
interface IPackage {
interface IPackage {
mainModulePath: string;
mainModule: any;
enable(): void;
@@ -1053,8 +1155,8 @@ declare module AtomCore {
reset(): void;
activate(): Q.Promise<any[]>;
activateNow(): void;
// TBD
}
// TBD
}
interface IPackageManager extends Emissary.IEmitter {
packageDirPaths:string[];
@@ -1098,6 +1200,13 @@ declare module AtomCore {
getAvailablePackageMetadata():any[];
}
interface INotifications {
addInfo: Function;
addError: Function;
addSuccess: Function;
addWarning: Function;
}
interface IThemeManager {
// TBD
}
@@ -1111,7 +1220,8 @@ declare module AtomCore {
}
interface IClipboard {
// TBD
write(text:string, metadata?:any):any;
read():string;
}
interface ISyntax {
@@ -1150,13 +1260,6 @@ declare module AtomCore {
dispose():void
}
class CommandRegistry {
add(target:string, commandName:string, callback:Function):Disposable
findCommands(params:Object):Object[]
dispatch(target:any,commandName:string):void
}
// https://atom.io/docs/api/v0.106.0/api/classes/Atom.html
/* Global Atom class : instance members */
interface IAtom {
@@ -1166,14 +1269,17 @@ declare module AtomCore {
mode:string;
deserializers:IDeserializerManager;
config: IConfig;
commands: ICommandRegistry;
keymaps: IKeymapManager;
keymap: IKeymapManager;
packages: IPackageManager;
themes: IThemeManager;
contextManu: IContextMenuManager;
menu: IMenuManager;
notifications: INotifications; // https://github.com/atom/notifications
clipboard:IClipboard;
syntax:ISyntax;
views: IViewRegistry;
windowEventHandler: IWindowEventHandler;
// really exists? start
@@ -1187,8 +1293,6 @@ declare module AtomCore {
workspace: IWorkspace;
// really exists? end
commands: CommandRegistry;
initialize:Function;
// registerRepresentationClass:Function;
// registerRepresentationClasses:Function;
@@ -1243,6 +1347,8 @@ declare module AtomCore {
getUserInitScriptPath:Function;
requireUserInitScript:Function;
requireWithGlobals:Function;
services: any; // TODO: New services api
}
interface IBufferedNodeProcessStatic {
@@ -1718,6 +1824,7 @@ declare module "atom" {
cancelling:boolean;
items:any[];
list:JQuery;
filterEditorView: JQuery;
previouslyFocusedElement:JQuery;
@@ -1753,7 +1860,7 @@ declare module "atom" {
confirmSelection():any;
viewForItem(item:any):JQuery; // You must override this method!
viewForItem(item:any):JQuery|string|HTMLElement|View; // You must override this method!
confirmed(item:any):any; // You must override this method!
getFilterKey():any;
+1
View File
@@ -27,6 +27,7 @@ interface Auth0LockOptions {
forceJSONP?: boolean;
gravatar?: boolean;
integratedWindowsLogin?: boolean;
icon?: string;
loginAfterSignup?: boolean;
popup?: boolean;
popupOptions?: Auth0LockPopupOptions;
+4 -8
View File
@@ -9,13 +9,9 @@ interface Window {
token: string;
}
interface Location {
origin: string;
}
/** This is the interface for the main Auth0 client. */
interface Auth0Static {
new(options: Auth0ClientOptions): Auth0Static;
changePassword(options: any, callback?: Function): void;
decodeJwt(jwt: string): any;
@@ -37,10 +33,10 @@ interface Auth0Static {
interface Auth0ClientOptions {
clientID: string;
callbackURL: string;
callbackOnLoactionHash?: boolean;
callbackOnLocationHash?: boolean;
domain: string;
forceJSONP?: boolean;
}
}
/** Represents a normalized UserProfile. */
interface Auth0UserProfile {
@@ -128,6 +124,6 @@ interface Auth0DelegationToken {
declare var Auth0: Auth0Static;
declare module "Auth0" {
declare module "auth0" {
export = Auth0
}
+17
View File
@@ -0,0 +1,17 @@
/// <reference path="auto-launch.d.ts" />
import AutoLaunch = require('auto-launch');
var a1 = new AutoLaunch({
name: 'Foo',
});
var a2 = new AutoLaunch({
name: 'Foo',
path: '/Applications/Foo.app',
isHidden: true,
});
a1.enable();
a2.disable();
var enabled: boolean = a1.isEnabled();
+41
View File
@@ -0,0 +1,41 @@
// Type definitions for auto-launch 0.1.18
// Project: https://github.com/Teamwork/node-auto-launch
// Definitions by: rhysd <https://github.com/rhysd>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface AutoLaunchOption {
/**
* Application name.
*/
name: string;
/**
* Hidden on launch or not. Default is false.
*/
isHidden?: boolean;
/**
* Path to application directory.
* Default is process.execPath.
*/
path?: string;
}
declare class AutoLaunch {
constructor(opts: AutoLaunchOption);
/**
* Enables to launch at start up
*/
enable(callback?: (err: Error) => void): void;
/**
* Disables to launch at start up
*/
disable(callback?: (err: Error) => void): void;
/**
* Returns if auto start up is enabled
*/
isEnabled(callback?: (err: Error) => void): boolean;
}
declare module "auto-launch" {
var al: typeof AutoLaunch;
export = al;
}
+3 -1
View File
@@ -1,5 +1,7 @@
/// <reference path="autobahn.d.ts"/>
import autobahn = require("autobahn");
class MyClass {
add2Count: number = 0;
session: autobahn.Session;
@@ -44,4 +46,4 @@ function test_client() {
};
connection.open();
}
}
+153 -148
View File
@@ -1,195 +1,200 @@
// Type definitions for AutobahnJS v0.9.6
// Type definitions for AutobahnJS v0.9.6
// Project: http://autobahn.ws/js/
// Definitions by: Elad Zelingher <https://github.com/darkl/>
// Definitions by: Elad Zelingher <https://github.com/darkl/>, Andy Hawkins <https://github.com/a904guy/,http://a904guy.com/,http://www.bmbsqd.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../when/when.d.ts" />
declare module autobahn {
export class Session {
id: number;
realm: string;
isOpen: boolean;
features: any;
caller_disclose_me: boolean;
publisher_disclose_me: boolean;
subscriptions: ISubscription[][];
registrations: IRegistration[];
export class Session {
id: number;
realm: string;
isOpen: boolean;
features: any;
caller_disclose_me: boolean;
publisher_disclose_me: boolean;
subscriptions: ISubscription[][];
registrations: IRegistration[];
constructor(transport: ITransport, defer: DeferFactory, challenge: OnChallengeHandler);
constructor(transport: ITransport, defer: DeferFactory, challenge: OnChallengeHandler);
join(realm: string, authmethods: string[], authid: string): void;
join(realm: string, authmethods: string[], authid: string): void;
leave(reason: string, message: string): void;
leave(reason: string, message: string): void;
call<TResult>(procedure: string, args?: any[], kwargs?: any, options?: ICallOptions): When.Promise<TResult>;
call<TResult>(procedure: string, args?: any[], kwargs?: any, options?: ICallOptions): When.Promise<TResult>;
publish(topic: string, args?: any[], kwargs?: any, options?: IPublishOptions): When.Promise<IPublication>;
publish(topic: string, args?: any[], kwargs?: any, options?: IPublishOptions): When.Promise<IPublication>;
subscribe(topic: string, handler: SubscribeHandler, options?: ISubscribeOptions): When.Promise<ISubscription>;
subscribe(topic: string, handler: SubscribeHandler, options?: ISubscribeOptions): When.Promise<ISubscription>;
register(procedure: string, endpoint: RegisterEndpoint, options?: IRegisterOptions): When.Promise<IRegistration>;
register(procedure: string, endpoint: RegisterEndpoint, options?: IRegisterOptions): When.Promise<IRegistration>;
unsubscribe(subscription: ISubscription): When.Promise<any>;
unsubscribe(subscription: ISubscription): When.Promise<any>;
unregister(registration: IRegistration): When.Promise<any>;
unregister(registration: IRegistration): When.Promise<any>;
prefix(prefix: string, uri: string): void;
prefix(prefix: string, uri: string): void;
resolve(curie: string): string;
resolve(curie: string): string;
onjoin: (roleFeatures: any) => void;
onleave: (reason: string, details: any) => void;
}
onjoin: (roleFeatures: any) => void;
onleave: (reason: string, details: any) => void;
}
interface IInvocation {
caller?: number;
progress?: boolean;
procedure: string;
}
interface IInvocation {
caller?: number;
progress?: boolean;
procedure: string;
}
interface IEvent {
publication: number;
publisher?: number;
topic: string;
}
interface IEvent {
publication: number;
publisher?: number;
topic: string;
}
interface IResult {
args: any[];
kwargs: any;
}
interface IResult {
args: any[];
kwargs: any;
}
interface IError {
error: string;
args: any[];
kwargs: any;
}
interface IError {
error: string;
args: any[];
kwargs: any;
}
type SubscribeHandler = (args?: any[], kwargs?: any, details?: IEvent) => void;
type SubscribeHandler = (args?: any[], kwargs?: any, details?: IEvent) => void;
interface ISubscription {
topic: string;
handler: SubscribeHandler;
options: ISubscribeOptions;
session: Session;
id: number;
active: boolean;
unsubscribe(): When.Promise<any>;
}
interface ISubscription {
topic: string;
handler: SubscribeHandler;
options: ISubscribeOptions;
session: Session;
id: number;
active: boolean;
unsubscribe(): When.Promise<any>;
}
type RegisterEndpoint = (args?: any[], kwargs?: any, details?: IInvocation) => void;
type RegisterEndpoint = (args?: any[], kwargs?: any, details?: IInvocation) => void;
interface IRegistration {
procedure: string;
endpoint: RegisterEndpoint;
options: IRegisterOptions;
session: Session;
id: number;
active: boolean;
unregister(): When.Promise<any>;
}
interface IRegistration {
procedure: string;
endpoint: RegisterEndpoint;
options: IRegisterOptions;
session: Session;
id: number;
active: boolean;
unregister(): When.Promise<any>;
}
interface IPublication {
id: number;
}
interface IPublication {
id: number;
}
interface ICallOptions {
timeout?: number;
receive_progress?: boolean;
disclose_me?: boolean;
}
interface ICallOptions {
timeout?: number;
receive_progress?: boolean;
disclose_me?: boolean;
}
interface IPublishOptions {
exclude?: number[];
eligible?: number[];
disclose_me? : Boolean;
}
interface IPublishOptions {
exclude?: number[];
eligible?: number[];
disclose_me? : Boolean;
}
interface ISubscribeOptions {
match? : string;
}
interface ISubscribeOptions {
match? : string;
}
interface IRegisterOptions {
disclose_caller?: boolean;
}
interface IRegisterOptions {
disclose_caller?: boolean;
}
export class Connection {
constructor(options?: IConnectionOptions);
export class Connection {
constructor(options?: IConnectionOptions);
open(): void;
open(): void;
close(reason: string, message: string): void;
close(reason: string, message: string): void;
onopen: (session: Session, details: any) => void;
onclose: (reason: string, details: any) => boolean;
}
onopen: (session: Session, details: any) => void;
onclose: (reason: string, details: any) => boolean;
}
interface ITransportDefinition {
url?: string;
protocols?: string[];
type: string;
}
interface ITransportDefinition {
url?: string;
protocols?: string[];
type: string;
}
type DeferFactory = () => any;
type DeferFactory = () => any;
type OnChallengeHandler = (session: Session, method: string, extra: any) => When.Promise<string>;
type OnChallengeHandler = (session: Session, method: string, extra: any) => When.Promise<string>;
interface IConnectionOptions {
use_es6_promises?: boolean;
// use explicit deferred factory, e.g. jQuery.Deferred or Q.defer
use_deferred?: DeferFactory;
transports?: ITransportDefinition[];
retry_if_unreachable?: boolean;
max_retries?: number;
initial_retry_delay?: number;
max_retry_delay?: number;
retry_delay_growth?: number;
retry_delay_jitter?: number;
url?: string;
protocols?: string[];
onchallenge?: (session: Session, method: string, extra: any) => OnChallengeHandler;
realm?: string;
authmethods?: string[];
authid?: string;
}
interface IConnectionOptions {
use_es6_promises?: boolean;
// use explicit deferred factory, e.g. jQuery.Deferred or Q.defer
use_deferred?: DeferFactory;
transports?: ITransportDefinition[];
retry_if_unreachable?: boolean;
max_retries?: number;
initial_retry_delay?: number;
max_retry_delay?: number;
retry_delay_growth?: number;
retry_delay_jitter?: number;
url?: string;
protocols?: string[];
onchallenge?: (session: Session, method: string, extra: any) => OnChallengeHandler;
realm?: string;
authmethods?: string[];
authid?: string;
}
interface ICloseEventDetails {
wasClean: boolean;
reason: string;
code: number;
}
interface ICloseEventDetails {
wasClean: boolean;
reason: string;
code: number;
}
interface ITransport {
onopen: () => void;
onmessage: (message: any[]) => void;
onclose: (details: ICloseEventDetails) => void;
interface ITransport {
onopen: () => void;
onmessage: (message: any[]) => void;
onclose: (details: ICloseEventDetails) => void;
send(message: any[]): void;
close(errorCode: number, reason?: string): void;
}
send(message: any[]): void;
close(errorCode: number, reason?: string): void;
}
interface ITransportFactory {
//constructor(options: any);
type: string;
create(): ITransport;
}
interface ITransportFactory {
//constructor(options: any);
type: string;
create(): ITransport;
}
interface ITransports {
register(name: string, factory: any): void;
isRegistered(name: string): boolean;
get(name: string): any;
list(): any[];
}
interface ITransports {
register(name: string, factory: any): void;
isRegistered(name: string): boolean;
get(name: string): any;
list(): any[];
}
interface ILog {
debug(...args: any[]): void;
}
interface ILog {
debug(...args: any[]): void;
}
interface IUtil {
assert(condition: boolean, message: string): void;
}
interface IUtil {
assert(condition: boolean, message: string): void;
}
var util: IUtil;
var log: ILog;
var transports: ITransports;
}
var util: IUtil;
var log: ILog;
var transports: ITransports;
}
declare module "autobahn" {
export = autobahn;
}
@@ -0,0 +1,79 @@
/// <reference path="../backbone/backbone.d.ts" />
/// <reference path="backbone-associations.d.ts" />
// borrowed from the Backbone.Associations tutorials
// separated out into modules to avoid namespace clashes
module Backbone.Associations.Tests {
module OneToOne {
class EmployeeWithManager extends Backbone.AssociatedModel {
constructor(options?) {
this.relations = [
{
type: Backbone.One, //nature of the relationship
key: 'manager', // attribute of Employee
relatedModel: 'Employee' //AssociatedModel for attribute key
}
];
super(options);
}
defaults() {
return {
age: 0,
fname: "",
lname: "",
manager: null
};
}
}
}
module OneToMany {
class Location extends Backbone.AssociatedModel {
defaults() {
return {
add1: "",
add2: null,
zip: "",
state: ""
};
}
}
class Locations extends Backbone.Collection<Location> {
comparator(c: Backbone.Model) {
return c.get("Number");
}
}
class Project extends Backbone.AssociatedModel {
constructor(options?) {
this.relations = [
{
type: Backbone.Many, //nature of the relation
key: 'locations', //attribute of Project
collectionType: Locations, //Collection to be used.
relatedModel: Location //Optional
}
];
super(options);
}
defaults() {
return {
name: "",
number: 0,
locations: []
}
}
}
function reverseAssociationTest() {
var local = new Location({ state: "Hertfordshire" });
var project = new Project({ name: "The Old Pond Project" });
local.set("oddRelationTo", project);
var parents = project.parents;
}
}
}
+75
View File
@@ -0,0 +1,75 @@
// Type definitions for Backbone-associations 0.6.4
// Project: https://github.com/dhruvaray/backbone-associations/
// Definitions by: Craig Brett <https://github.com/craigbrett17/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../backbone/backbone.d.ts" />
declare module Backbone {
export module Associations {
/** Defines a 1:Many relationship type */
export var Many: string;
/** Defines a 1:1 relationship type */
export var One: string;
/** Defines a special relationship to itself */
export var Self: string;
// these seem to be used internally, but can't see a reason not to include them just in case
export var SEPARATOR: string;
export function getSeparator(): any;
export function setSeparator(value: any): void;
export var EVENTS_BUBBLE: boolean;
export var EVENTS_WILDCARD: boolean;
export var EVENTS_NC: boolean;
interface IRelation {
/** The type of model for this relationship */
relatedModel: string|typeof Backbone.Associations.AssociatedModel;
/** The key for this relationship on this model */
key: string;
// meh, no string enums in TS. Just have to trust the user not to be a fool
/** The cardinality of this relationship. */
type: string;
/** Determines the type of collection used. If used, the relatedModel property is ignored */
collectionType?: typeof Backbone.Collection|string;
/** If set to true, then the attribute will not be serialized in toJSON() calls. Defaults to false */
isTransient?: boolean;
/** Specify remoteKey to serialize the key to a different key name in toJSON() calls. Useful in ROR nested-attributes like scenarios. */
remoteKey?: string;
/** the attributes to serialize when calling toJSON */
serialize?: string[];
/** A transformation function to convert the value before it is assigned to the key on the relatedModel */
map?: (...args: any[]) => any;
}
/** A Backbone model with special provision for handling relations to other models */
export class AssociatedModel extends Backbone.Model {
/** Relations with their associated model */
relations: IRelation[];
_proxyCalls: any;
/** Reverse association lookup for objects that contain this object */
parents: any[];
/** Cleans up any parent relations on other AssociatedModels */
cleanup(): void;
}
}
// copies of properties also put onto the Backbone scope
/** Defines a 1:Many relationship type */
export var Many: string;
/** Defines a 1:1 relationship type */
export var One: string;
/** Defines a special relationship to itself */
export var Self: string;
// I'm sure this should be doable with imports or type aliases, but doesn't seem to work
/** A Backbone model with special provision for handling relations to other models */
export class AssociatedModel extends Backbone.Model {
/** Relations with their associated model */
relations: Associations.IRelation[];
_proxyCalls: any;
/** Reverse association lookup for objects that contain this object */
parents: any[];
/** Cleans up any parent relations on other AssociatedModels */
cleanup(): void;
}
}
+1
View File
@@ -11,6 +11,7 @@ declare module Backbone {
interface LayoutOptions<TModel extends Model> extends ViewOptions<TModel> {
template?: string;
views?: { [viewName: string]: View<TModel> };
}
interface LayoutManagerOptions {
+13 -15
View File
@@ -148,7 +148,7 @@ declare module Backbone {
unset(attribute: string, options?: Silenceable): Model;
validate(attributes: any, options?: any): any;
private _validate(attrs: any, options: any): boolean;
private _validate(attributes: any, options: any): boolean;
// mixins from underscore
@@ -173,23 +173,21 @@ declare module Backbone {
models: TModel[];
length: number;
constructor(models?: TModel[], options?: any);
initialize(models?: TModel[], options?: any): void;
constructor(models?: TModel[] | Object[], options?: any);
initialize(models?: TModel[] | Object[], options?: any): void;
fetch(options?: CollectionFetchOptions): JQueryXHR;
comparator(element: TModel): number;
comparator(compare: TModel, to?: TModel): number;
add(model: TModel, options?: AddOptions): Collection<TModel>;
add(models: TModel[], options?: AddOptions): Collection<TModel>;
add(model: {}|TModel, options?: AddOptions): TModel;
add(models: ({}|TModel)[], options?: AddOptions): TModel[];
at(index: number): TModel;
/**
* Get a model from a collection, specified by an id, a cid, or by passing in a model.
**/
get(id: number): TModel;
get(id: string): TModel;
get(id: Model): TModel;
get(id: number|string|Model): TModel;
create(attributes: any, options?: ModelSaveOptions): TModel;
pluck(attribute: string): any[];
push(model: TModel, options?: AddOptions): TModel;
@@ -201,10 +199,10 @@ declare module Backbone {
shift(options?: Silenceable): TModel;
sort(options?: Silenceable): Collection<TModel>;
unshift(model: TModel, options?: AddOptions): TModel;
where(properies: any): TModel[];
where(properties: any): TModel[];
findWhere(properties: any): TModel;
private _prepareModel(attrs?: any, options?: any): any;
private _prepareModel(attributes?: any, options?: any): any;
private _removeReference(model: TModel): void;
private _onModelEvent(event: string, model: TModel, collection: Collection<TModel>, options: any): void;
@@ -247,6 +245,7 @@ declare module Backbone {
select(iterator: any, context?: any): any[];
size(): number;
shuffle(): any[];
slice(min: number, max?: number): TModel[];
some(iterator: (element: TModel, index: number) => boolean, context?: any): boolean;
sortBy(iterator: (element: TModel, index: number) => number, context?: any): TModel[];
sortBy(attribute: string, context?: any): TModel[];
@@ -277,8 +276,7 @@ declare module Backbone {
constructor(options?: RouterOptions);
initialize(options?: RouterOptions): void;
route(route: string, name: string, callback?: Function): Router;
route(route: RegExp, name: string, callback?: Function): Router;
route(route: string|RegExp, name: string, callback?: Function): Router;
navigate(fragment: string, options?: NavigateOptions): Router;
navigate(fragment: string, trigger?: boolean): Router;
@@ -311,7 +309,8 @@ declare module Backbone {
interface ViewOptions<TModel extends Model> {
model?: TModel;
collection?: Backbone.Collection<TModel>;
// TODO: quickfix, this can't be fixed easy. The collection does not need to have the same model as the parent view.
collection?: Backbone.Collection<any>;
el?: any;
id?: string;
className?: string;
@@ -340,8 +339,7 @@ declare module Backbone {
model: TModel;
collection: Collection<TModel>;
//template: (json, options?) => string;
setElement(element: HTMLElement, delegate?: boolean): View<TModel>;
setElement(element: JQuery, delegate?: boolean): View<TModel>;
setElement(element: HTMLElement|JQuery, delegate?: boolean): View<TModel>;
id: string;
cid: string;
className: string;

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