Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Steven Masala
2017-03-20 16:23:22 +01:00
14 changed files with 2 additions and 3463 deletions
-20
View File
@@ -1,22 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto
# Custom for Visual Studio
*.cs diff=csharp
*.sln merge=union
*.csproj merge=union
*.vbproj merge=union
*.fsproj merge=union
*.dbproj merge=union
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain
-1
View File
@@ -1 +0,0 @@
Please see the [contribution guide](http://definitelytyped.org/guides/contributing.html) at [definitelytyped.org](http://definitelytyped.org/guides/contributing.html) for information on how to contribute to DefinitelyTyped.
-1893
View File
File diff suppressed because it is too large Load Diff
-210
View File
@@ -1,210 +0,0 @@
{
"name": "definitely-typed",
"version": "0.0.1",
"dependencies": {
"assertion-error": {
"version": "1.0.1",
"from": "assertion-error@>=1.0.0 <2.0.0",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.0.1.tgz"
},
"balanced-match": {
"version": "0.3.0",
"from": "balanced-match@>=0.3.0 <0.4.0",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-0.3.0.tgz"
},
"bluebird": {
"version": "3.3.4",
"from": "bluebird@>=3.3.1 <4.0.0",
"resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.3.4.tgz"
},
"brace-expansion": {
"version": "1.1.3",
"from": "brace-expansion@>=1.0.0 <2.0.0",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.3.tgz"
},
"concat-map": {
"version": "0.0.1",
"from": "concat-map@0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz"
},
"core-util-is": {
"version": "1.0.2",
"from": "core-util-is@>=1.0.0 <1.1.0",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz"
},
"findup-sync": {
"version": "0.3.0",
"from": "findup-sync@>=0.3.0 <0.4.0",
"resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-0.3.0.tgz",
"dependencies": {
"glob": {
"version": "5.0.15",
"from": "glob@>=5.0.0 <5.1.0",
"resolved": "https://registry.npmjs.org/glob/-/glob-5.0.15.tgz"
}
}
},
"git-wrapper": {
"version": "0.1.1",
"from": "git-wrapper@>=0.1.1 <0.2.0",
"resolved": "https://registry.npmjs.org/git-wrapper/-/git-wrapper-0.1.1.tgz"
},
"glob": {
"version": "7.0.3",
"from": "glob@>=7.0.0 <8.0.0",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.0.3.tgz"
},
"hoek": {
"version": "3.0.4",
"from": "hoek@>=3.0.0 <4.0.0",
"resolved": "https://registry.npmjs.org/hoek/-/hoek-3.0.4.tgz"
},
"inflight": {
"version": "1.0.4",
"from": "inflight@>=1.0.4 <2.0.0",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.4.tgz"
},
"inherits": {
"version": "2.0.1",
"from": "inherits@>=2.0.0 <3.0.0",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz"
},
"isarray": {
"version": "0.0.1",
"from": "isarray@0.0.1",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz"
},
"isemail": {
"version": "2.1.0",
"from": "isemail@>=2.0.0 <3.0.0",
"resolved": "https://registry.npmjs.org/isemail/-/isemail-2.1.0.tgz"
},
"joi": {
"version": "8.0.4",
"from": "joi@>=8.0.4 <9.0.0",
"resolved": "https://registry.npmjs.org/joi/-/joi-8.0.4.tgz"
},
"joi-assert": {
"version": "0.0.3",
"from": "joi-assert@>=0.0.3 <0.0.4",
"resolved": "https://registry.npmjs.org/joi-assert/-/joi-assert-0.0.3.tgz"
},
"jsonparse": {
"version": "0.0.5",
"from": "jsonparse@0.0.5",
"resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-0.0.5.tgz"
},
"JSONStream": {
"version": "0.8.4",
"from": "JSONStream@>=0.8.4 <0.9.0",
"resolved": "https://registry.npmjs.org/JSONStream/-/JSONStream-0.8.4.tgz"
},
"lazy.js": {
"version": "0.4.2",
"from": "lazy.js@>=0.4.2 <0.5.0",
"resolved": "https://registry.npmjs.org/lazy.js/-/lazy.js-0.4.2.tgz"
},
"manticore": {
"version": "0.2.4",
"from": "manticore@>=0.2.4 <0.3.0",
"resolved": "https://registry.npmjs.org/manticore/-/manticore-0.2.4.tgz",
"dependencies": {
"bluebird": {
"version": "1.2.4",
"from": "bluebird@>=1.2.4 <2.0.0",
"resolved": "https://registry.npmjs.org/bluebird/-/bluebird-1.2.4.tgz"
}
}
},
"minimatch": {
"version": "3.0.0",
"from": "minimatch@>=2.0.0 <3.0.0||>=3.0.0 <4.0.0",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.0.tgz"
},
"minimist": {
"version": "0.0.10",
"from": "minimist@>=0.0.1 <0.1.0",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.10.tgz"
},
"moment": {
"version": "2.12.0",
"from": "moment@>=2.0.0 <3.0.0",
"resolved": "https://registry.npmjs.org/moment/-/moment-2.12.0.tgz"
},
"once": {
"version": "1.3.3",
"from": "once@>=1.3.0 <2.0.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.3.3.tgz"
},
"optimist": {
"version": "0.6.1",
"from": "optimist@>=0.6.1 <0.7.0",
"resolved": "https://registry.npmjs.org/optimist/-/optimist-0.6.1.tgz"
},
"parsimmon": {
"version": "0.7.0",
"from": "parsimmon@>=0.7.0 <0.8.0",
"resolved": "https://registry.npmjs.org/parsimmon/-/parsimmon-0.7.0.tgz"
},
"path-is-absolute": {
"version": "1.0.0",
"from": "path-is-absolute@>=1.0.0 <2.0.0",
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.0.tgz"
},
"pjs": {
"version": "5.1.1",
"from": "pjs@>=5.0.0 <6.0.0",
"resolved": "https://registry.npmjs.org/pjs/-/pjs-5.1.1.tgz"
},
"readable-stream": {
"version": "1.0.33",
"from": "readable-stream@>=1.0.17 <1.1.0",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.33.tgz"
},
"string_decoder": {
"version": "0.10.31",
"from": "string_decoder@>=0.10.0 <0.11.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz"
},
"through": {
"version": "2.3.8",
"from": "through@>=2.2.7 <3.0.0",
"resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz"
},
"through2": {
"version": "0.5.1",
"from": "through2@>=0.5.1 <0.6.0",
"resolved": "https://registry.npmjs.org/through2/-/through2-0.5.1.tgz"
},
"topo": {
"version": "2.0.0",
"from": "topo@>=2.0.0 <3.0.0",
"resolved": "https://registry.npmjs.org/topo/-/topo-2.0.0.tgz"
},
"type-detect": {
"version": "0.1.2",
"from": "type-detect@>=0.1.2 <0.2.0",
"resolved": "https://registry.npmjs.org/type-detect/-/type-detect-0.1.2.tgz"
},
"wordwrap": {
"version": "0.0.3",
"from": "wordwrap@>=0.0.2 <0.1.0",
"resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.3.tgz"
},
"wrappy": {
"version": "1.0.1",
"from": "wrappy@>=1.0.0 <2.0.0",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.1.tgz"
},
"xregexp": {
"version": "3.1.0",
"from": "xregexp@>=3.0.0 <4.0.0",
"resolved": "https://registry.npmjs.org/xregexp/-/xregexp-3.1.0.tgz"
},
"xtend": {
"version": "3.0.0",
"from": "xtend@>=3.0.0 <3.1.0",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-3.0.0.tgz"
}
}
}
-108
View File
@@ -1,108 +0,0 @@
// Type definitions for PaymentRequest
// Project: https://www.w3.org/TR/payment-request/
// Definitions by: Adam Cmiel <https://github.com/adamcmiel>, Eiji Kitamura <https://github.com/agektmr>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface PaymentRequest extends EventTarget {
new (methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest;
show(): PromiseLike<PaymentResponse>;
abort(): PromiseLike<void>;
canMakePayment(): Promise<boolean>;
readonly paymentRequestID: string;
readonly shippingAddress?: PaymentAddress;
readonly shippingOption?: string;
readonly shippingType?: string;
onshippingaddresschange: PaymentUpdateEventListener;
onshippingoptionchange: PaymentUpdateEventListener;
}
interface PaymentMethodData {
supportedMethods: string[];
data?: {
supportedNetworks: string[];
supportedTypes: string[];
};
}
interface PaymentCurrencyAmount {
currency: string;
value: string;
currencySystem?:string;
}
interface PaymentDetails {
total: PaymentItem;
displayItems?: PaymentItem[];
shippingOptions?: PaymentShippingOption[];
modifiers?: PaymentDetailsModifier[];
error?: string;
}
interface PaymentDetailsModifier {
supportedMethods: string[];
total?: PaymentItem;
additionalDisplayItems?: PaymentItem[];
data?: Object;
}
interface PaymentOptions {
requestShipping?: boolean;
requestPayerEmail?: boolean;
requestPayerPhone?: boolean;
requestPayerName?: boolean;
shippingType?: 'shipping' | 'delivery' | 'pickup';
}
interface PaymentItem {
label: string;
amount: PaymentCurrencyAmount;
pending?: boolean;
}
interface PaymentAddress {
readonly country: string;
readonly addressLine: string[];
readonly region: string;
readonly city: string;
readonly dependentLocality: string;
readonly postalCode: string;
readonly sortingCode: string;
readonly languageCode: string;
readonly organization: string;
readonly recipient: string;
readonly phone: string;
}
interface PaymentShippingOption {
id: string;
label: string;
amount: PaymentCurrencyAmount;
selected?: boolean;
}
interface PaymentResponse {
readonly paymentRequestID: string;
readonly methodName: string;
readonly details: Object;
readonly shippingAddress?: PaymentAddress;
readonly shippingOption?: string;
readonly payerEmail?: string;
readonly payerPhone?: string;
readonly payerName?: string;
complete(result?: '' | 'success' | 'fail'): PromiseLike<void>;
toJSON(): Object;
}
interface PaymentUpdateEventListener extends EventListener {
(evt: PaymentRequestUpdateEvent): void;
}
interface PaymentRequestUpdateEvent extends Event {
updateWith(d: PromiseLike<PaymentDetails>): void;
}
interface Window {
PaymentRequest?: PaymentRequest;
}
-116
View File
@@ -1,116 +0,0 @@
/// Code examples derived from
/// https://developers.google.com/web/fundamentals/discovery-and-monetization/payment-request/
async function makeRequest() {
if (!window.PaymentRequest) {
return Promise.reject(new Error("PaymentRequest not available"))
}
const methodData = [
{
supportedMethods: ["visa", "mastercard"]
}
]
const details: PaymentDetails = {
displayItems: [
{
label: "Original donation amount",
amount: { currency: "USD", value : "65.00" }, // US$65.00
},
{
label: "Friends and family discount",
amount: { currency: "USD", value : "-10.00" }, // -US$10.00
}
],
total: {
label: "Total",
amount: { currency: "USD", value : "55.00" }, // US$55.00
}
}
const options: PaymentOptions = {
requestShipping: true,
requestPayerEmail: true,
requestPayerPhone: true,
requestPayerName: true,
shippingType: 'delivery'
}
const request = new window.PaymentRequest(methodData, details, options)
request.addEventListener("shippingaddresschange", (e: any) => {
e.updateWith(((details, addr) => {
if (addr.country === 'US') {
var shippingOption = {
id: '',
label: '',
amount: {currency: 'USD', value: '0.00'},
selected: true
};
if (addr.region === 'US') {
shippingOption.id = 'us';
shippingOption.label = 'Standard shipping in US';
shippingOption.amount.value = '0.00';
details.total.amount.value = '55.00';
} else {
shippingOption.id = 'others';
shippingOption.label = 'International shipping';
shippingOption.amount.value = '10.00';
details.total.amount.value = '65.00';
}
if (details.displayItems.length === 2) {
details.displayItems.splice(1, 0, shippingOption);
} else {
details.displayItems.splice(1, 1, shippingOption);
}
details.shippingOptions = [shippingOption];
} else {
details.shippingOptions = [];
}
return Promise.resolve(details);
})(details, request.shippingAddress));
})
let canMakePayment = await request.canMakePayment()
if (canMakePayment) {
return request.show()
} else {
throw 'can not make payment on this environment.'
}
}
async function processPayment(): Promise<PaymentResponse> {
let paymentResponse: PaymentResponse;
try {
paymentResponse = await makeRequest()
} catch (error) {
location.href = '/checkout';
return;
}
var paymentData = {
// payment method string
method: paymentResponse.methodName,
// payment details as you requested
details: paymentResponse.details,
// shipping address information
address: paymentResponse.shippingAddress,
// shipping option
shippingOption: paymentResponse.shippingOption
}
// make call to backend to process payment data
const ok = await Promise.resolve(true)
if (ok) {
paymentResponse.complete("success")
} else {
paymentResponse.complete("fail")
}
}
function onShippingAddressChange(e: any) {
}
document.querySelector("#pay").addEventListener("click", processPayment)
-24
View File
@@ -1,24 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"target": "es6",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"paymentrequest-tests.ts"
]
}
-831
View File
@@ -1,831 +0,0 @@
// Type definitions for service_worker_api 0.0
// Project: https://developer.mozilla.org/fr/docs/Web/API/ServiceWorker_API
// Definitions by: Tristan Caron <https://github.com/tristancaron>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// TypeScript Version: 2.1
/// <reference types="whatwg-fetch" />
/**
* An CacheOptions object allowing you to set specific control options for the
* matching done in the match operation.
*
* @property [ignoreSearch] A Boolean that specifies whether the matching
* process should ignore the query string in the url. If set to true,
* the ?value=bar part of http://foo.com/?value=bar would be ignored when
* performing a match. It defaults to false.
*
* @property [ignoreMethod] A Boolean that, when set to true, prevents matching
* operations from validating the Request http method (normally only GET
* and HEAD are allowed.) It defaults to false.
*
* @property [ignoreVary] A Boolean that when set to true tells the matching
* operation not to perform VARY header matching — i.e. if the URL matches you
* will get a match regardless of the Response object having a VARY header or
* not. It defaults to false.
*
* @property [cacheName] A DOMString that represents a specific cache to search
* within. Note that this option is ignored by Cache.match().
*/
interface CacheOptions {
ignoreSearch?: boolean;
ignoreMethod?: boolean;
ignoreVary?: boolean;
cacheName?: string;
}
/**
* Represents the storage for Request / Response object pairs that are cached as
* part of the ServiceWorker life cycle.
*/
interface Cache {
/**
* Returns a Promise that resolves to the response associated with the first
* matching request in the Cache object.
*
* @param request The Request you are attempting to find in the Cache.
* @param [options] An object that sets options for the match operation.
*/
match(request: Request | string, options?: CacheOptions): Promise<Response>;
/**
* Returns a Promise that resolves to an array of all matching responses in
* the Cache object.
*
* @param request The Request you are attempting to find in the Cache.
* @param [options] An object that sets options for the match operation.
*/
matchAll(request: Request | string, options?: CacheOptions): Promise<Response[]>;
/**
* Returns a Promise that resolves to a new Cache entry whose key
* is the request.
*
* @param request The Request you want to add to the cache.
*/
add(request: Request | string): Promise<void>;
/**
* Returns a Promise that resolves to a new array of Cache entries whose
* keys are the requests.
*
* @param request An array of Request objects you want to add to the cache.
*/
addAll(requests: Array<Request | string>): Promise<void>;
/**
* Adds additional key/value pairs to the current Cache object.
*
* @param request The Request you want to add to the cache.
* @param response The response you want to match up to the request.
*/
put(request: Request, response: Response): Promise<void>;
/**
* Finds the Cache entry whose key is the request, and if found, deletes the
* Cache entry and returns a Promise that resolves to true. If no Cache
* entry is found, it returns false.
*
* @param request The Request you are looking to delete.
* @param [options] An object that sets options for the match operation.
*/
delete(request: Request | string, options?: CacheOptions): Promise<boolean>;
/**
* Returns a Promise that resolves to an array of Cache keys.
*
* @param request The Request want to return, if a specific key is desired.
* @param [options] An object that sets options for the match operation.
*/
keys(request?: Request, options?: CacheOptions): Promise<Request[]>;
}
/**
* Represents the storage for Cache objects. It provides a master directory of
* all the named caches that a ServiceWorker can access and maintains a mapping
* of string names to corresponding Cache objects.
*/
interface CacheStorage {
/**
* Checks if a given Request is a key in any of the Cache objects that the
* CacheStorage object tracks and returns a Promise that resolves
* to that match.
*
* @param request The Request you are looking for a match for in the CacheStorage.
* @param [options] An object that sets options for the match operation.
*/
match(request: Request | string, options?: CacheOptions): Promise<Response>;
/**
* Returns a Promise that resolves to true if a Cache object matching
* the cacheName exists.
*
* @param cacheName The Request you are looking for a match for in the
* CacheStorage.
*/
has(cacheName: string): Promise<boolean>;
/**
* Returns a Promise that resolves to the Cache object matching
* the cacheName.
*
* @param cacheName The name of the cache you want to open.
*/
open(cacheName: string): Promise<Cache>;
/**
* Finds the Cache object matching the cacheName, and if found, deletes the
* Cache object and returns a Promise that resolves to true. If no
* Cache object is found, it returns false.
*
* @param cacheName The name of the cache you want to delete.
*/
delete(cacheName: string): Promise<boolean>;
/**
* Returns a Promise that will resolve with an array containing strings
* corresponding to all of the named Cache objects tracked by the
* CacheStorage. Use this method to iterate over a list of all the
* Cache objects.
*/
keys(): Promise<string[]>;
}
/**
* Represents the scope of a service worker client. A service worker client is
* either a document in a browser context or a SharedWorker, which is controlled
* by an active worker.
*/
interface ServiceWorkerClient {
/**
* Allows a service worker client to send a message to a ServiceWorker.
*
* @param message The message to send to the service worker.
* @param [transfer] A transferable object such as, for example, a reference
* to a port.
*/
postMessage(message: any, transfer?: any): void;
/**
* Indicates the type of browsing context of the current client.
* This value can be one of auxiliary, top-level, nested, or none.
*/
readonly frameType: string;
/**
* Returns the id of the Client object.
*/
readonly id: string;
/**
* The URL of the current service worker client.
*/
readonly url: string;
}
interface WindowClient extends ServiceWorkerClient {
/**
* Gives user input focus to the current client.
*/
focus(): Promise<WindowClient>;
/**
* A boolean that indicates whether the current client has focus.
*/
readonly focused: boolean;
/**
* Indicates the visibility of the current client. This value can be one of
* hidden, visible, prerender, or unloaded.
*/
readonly visibilityState: string;
}
interface ServiceWorkerClientsMatchOptions {
includeUncontrolled?: boolean;
type?: string;
}
/**
* Represents a container for a list of Client objects; the main way to access
* the active service worker clients at the current origin.
*/
interface ServiceWorkerClients {
/**
* Gets a service worker client matching a given id and returns it in a Promise.
* @param clientId The ID of the client you want to get.
*/
get(clientId: string): Promise<ServiceWorkerClient>;
/**
* Gets a list of service worker clients and returns them in a Promise.
* Include the options parameter to return all service worker clients whose
* origin is the same as the associated service worker's origin. If options
* are not included, the method returns only the service worker clients
* controlled by the service worker.
*
* @param [options] An options object allowing you to set options for the matching operation.
*/
matchAll(options?: ServiceWorkerClientsMatchOptions): Promise<ServiceWorkerClient[]>;
/**
* Opens a service worker Client in a new browser window.
*
* @param url A string representing the URL of the client you want to open
* in the window.
*/
openWindow(url: string): Promise<WindowClient>;
/**
* Allows an active Service Worker to set itself as the active worker for a
* client page when the worker and the page are in the same scope.
*/
claim(): Promise<void>;
}
/**
* Represents a service worker. Multiple browsing contexts (e.g. pages, workers,
* etc.) can be associated with the same ServiceWorker object.
*/
interface ServiceWorker extends Worker {
/**
* Returns the ServiceWorker serialized script URL defined as part of
* ServiceWorkerRegistration. The URL must be on the same origin as the
* document that registers the ServiceWorker.
*/
readonly scriptURL: string;
/**
* Returns the state of the service worker. It returns one of the following
* values: installing, installed, activating, activated, or redundant.
*/
readonly state: string;
/**
* An EventListener property called whenever an event of type statechange
* is fired; it is basically fired anytime the ServiceWorker.state changes.
*/
onstatechange: (statechangeevent: Event) => void;
}
/**
* The PushMessageData interface of the Push API provides
* methods which let you retrieve the push data sent by a server in various formats.
*/
interface PushMessageData {
/**
* Extracts the data as an ArrayBuffer object.
*/
arrayBuffer(): ArrayBuffer;
/**
* Extracts the data as a Blob object.
*/
blob(): Blob;
/**
* Extracts the data as a JSON object.
*/
json(): any;
json<T>(): T;
/**
* Extracts the data as a plain text string.
*/
text(): string;
}
/**
* The PushSubscription interface provides a subcription's URL endpoint and
* subscription ID.
*/
interface PushSubscription {
/**
* The endpoint associated with the push subscription.
*/
readonly endpoint: any;
/**
* The subscription ID associated with the push subscription.
*/
readonly subscriptionId: any;
}
/**
* Object containing optional subscribe parameters.
*/
interface PushSubscriptionOptions {
/**
* A boolean indicating that the returned push subscription will only be used for
* messages whose effect is made visible to the user.
*/
readonly userVisibleOnly: boolean;
/**
* A public key your push server will use to send messages to client apps via a push server.
* This value is part of a signing key pair generated by your application server and usable
* with elliptic curve digital signature (ECDSA) over the P-256 curve.
*/
readonly applicationServerKey?: Uint8Array;
}
/**
* The PushManager interface provides a way to receive notifications from
* third-party servers as well as request URLs for push notifications.
* This interface has replaced functionality offered by the obsolete
* PushRegistrationManager.
*/
interface PushManager {
/**
* Returns a promise that resolves to a PushSubscription with details of a
* new push subscription.
*
* @param [options] An object containing optional configuration parameters.
*/
subscribe(options?: PushSubscriptionOptions): Promise<PushSubscription>;
/**
* Returns a promise that resolves to a PushSubscription details of
* the retrieved push subscription.
*/
getSubscription(): Promise<PushSubscription>;
/**
* Returns a promise that resolves to the PushPermissionStatus of the
* requesting webapp, which will be one of granted, denied, or default.
*/
hasPermission(): Promise<any>;
}
/////// Service Worker Events ///////
/**
* Extends the lifetime of the install and activate events dispatched on the
* ServiceWorkerGlobalScope as part of the service worker lifecycle. This
* ensures that any functional events (like FetchEvent) are not dispatched to
* the ServiceWorker until it upgrades database schemas, deletes outdated cache
* entries, etc.
*/
interface ExtendableEvent extends Event {
/**
* Extends the lifetime of the event.
* It is intended to be called in the install EventHandler for the
* installing worker and on the active EventHandler for the active worker.
*
* @param promise
*/
waitUntil(promise: Promise<any>): void;
}
/**
* The parameter passed into the ServiceWorkerGlobalScope.onfetch handler,
* FetchEvent represents a fetch action that is dispatched on the
* ServiceWorkerGlobalScope of a ServiceWorker. It contains information about
* the request and resulting response, and provides the FetchEvent.respondWith()
* method, which allows us to provide an arbitrary response back to the
* controlled page.
*/
interface FetchEvent extends Event {
/**
* Returns a Boolean that is true if the event was dispatched with the
* user's intention for the page to reload, and false otherwise. Typically,
* pressing the refresh button in a browser is a reload, while clicking a
* link and pressing the back button is not.
*/
readonly isReload: boolean;
/**
* Returns the Request that triggered the event handler.
*/
readonly request: Request;
/**
* Returns the Client that the current service worker is controlling.
*/
readonly client: ServiceWorkerClient;
/**
* Returns the id of the client that the current service worker is controlling.
*/
readonly clientId: string;
/**
* Resolves by returning a Response or a network error to Fetch.
*
* @param all Any custom response-generating code.
*/
respondWith(all: any): Response;
}
/**
* The ExtendableMessageEvent interface of the ServiceWorker API represents
* the event object of a message event fired on
* a service worker (when a channel message is received on
* the ServiceWorkerGlobalScope from another context)
* — extends the lifetime of such events.
*/
interface ExtendableMessageEvent extends ExtendableEvent {
/**
* Returns the event's data. It can be any data type.
*/
readonly data: any;
/**
* Returns the origin of the ServiceWorkerClient that sent the message
*/
readonly origin: string;
/**
* Represents, in server-sent events, the last event ID of the event source.
*/
readonly lastEventId: string;
/**
* Returns a reference to the service worker that sent the message.
*/
readonly source: ServiceWorkerClient;
/**
* Returns the array containing the MessagePort objects
* representing the ports of the associated message channel.
*/
readonly ports: MessagePort[];
}
/**
* The parameter passed into the oninstall handler, the InstallEvent interface
* represents an install action that is dispatched on the
* ServiceWorkerGlobalScope of a ServiceWorker. As a child of ExtendableEvent,
* it ensures that functional events such as FetchEvent are not dispatched
* during installation.
*/
interface InstallEvent extends ExtendableEvent {
/**
* Returns the ServiceWorker that is currently actively controlling the page.
*/
readonly activeWorker: ServiceWorker;
}
/**
* The parameter passed into the onnotificationclick handler,
* the NotificationEvent interface represents
* a notification click event that is dispatched on
* the ServiceWorkerGlobalScope of a ServiceWorker.
*/
interface NotificationEvent extends ExtendableEvent {
/**
* Returns a Notification object representing
* the notification that was clicked to fire the event.
*/
notification: any; // need to be replaced with `Notification` when possible
/**
* Returns the string ID of the notification button the user clicked.
* This value returns undefined if the user clicked
* the notification somewhere other than an action button,
* or the notification does not have a button.
*/
action: string;
}
/**
* The PushEvent interface of the Push API represents
* a push message that has been received.
* This event is sent to the global scope of a ServiceWorker.
* It contains the information sent from an application server to a PushSubscription.
*/
interface PushEvent extends ExtendableEvent {
/**
* Returns a reference to a PushMessageData object containing
* data sent to the PushSubscription.
*/
readonly data: PushMessageData;
}
interface ServiceWorkerContainerEventMap {
"message": MessageEvent;
"error": ErrorEvent;
"controllerchange": Event;
}
interface ServiceWorkerEventMap {
"activate": ExtendableEvent;
"fetch": FetchEvent;
"install": InstallEvent;
// "message": ExtendableMessageEvent;
"message": MessageEvent;
"notificationclick": NotificationEvent;
"push": PushEvent;
"pushsubscriptionchang": PushEvent;
}
/**
* Represents a service worker registration.
*/
interface ServiceWorkerRegistration extends EventTarget {
/**
* Returns a unique identifier for a service worker registration.
* This must be on the same origin as the document that registers
* the ServiceWorker.
*/
readonly scope: any;
/**
* Returns a service worker whose state is installing. This is initially
* set to null.
*/
readonly installing: ServiceWorker;
/**
* Returns a service worker whose state is installed. This is initially
* set to null.
*/
readonly waiting: ServiceWorker;
/**
* Returns a service worker whose state is either activating or activated.
* This is initially set to null. An active worker will control a
* ServiceWorkerClient if the client's URL falls within the scope of the
* registration (the scope option set when ServiceWorkerContainer.register
* is first called).
*/
readonly active: ServiceWorker;
/**
* Returns an interface to for managing push subscriptions, including
* subcribing, getting an anctive subscription, and accessing push
* permission status.
*/
readonly pushManager: PushManager;
/**
* An EventListener property called whenever an event of type updatefound
* is fired; it is fired any time the ServiceWorkerRegistration.installing
* property acquires a new service worker.
*/
onupdatefound: () => void;
/**
* Allows you to update a service worker.
*/
update(): void;
/**
* Unregisters the service worker registration and returns a promise
* (see Promise). The service worker will finish any ongoing operations
* before it is unregistered.
*/
unregister(): Promise<boolean>;
/**
* Returns a Promise that resolves to an array of Notification objects.
* @param [options] An options object that can contain options to filter the notifications returned.
*/
getNotifications(options?: ServiceWorkerGetNotificationOptions): Promise<any[]>; // need to be replaced with `Notification[]` when possible
/**
* Displays the notification with the requested title.
* @param [title] The title that must be shown within the notification
* @param [options] An object that allows to configure the notification.
*/
showNotification(title: string, options?: ServiceWorkerNotificationOptions): Promise<NotificationEvent>;
}
/**
* An options object to provide options upon a ServiceWorkerRegistration.
* @param [scope] A USVString representing a URL that defines a service worker's registration scope; what range of
* URLs a service worker can control. This is usually a relative URL, and it defaults to '/' when not specified.
*/
interface ServiceWorkerRegisterOptions {
scope: string;
}
/**
* Action to display in a notification.
* @param [action] A DOMString identifying a user action to be displayed on the notification.
* @param [title] A DOMString containing action text to be shown to the user.
* @param [icon] A USVString containg the URL of an icon to display with the action.
*/
interface NotificationAction { // TODO: Maybe need to moved if NotificationApi types are defined
action: string;
title: string;
icon?: string;
}
/**
* Object that allows to configure a notification.
* @param [actions] An array of actions to display in the notification.
* Appropriate responses are built using event.action within the notificationclick event.
* @param [badge] The URL of an image to represent the notification when there is not enough space to display the
* notification itself such as, for example, the Android Notification Bar. On Android devices, the badge should
* accommodate devices up to 4x resolution, about 96 by 96 px, and the image will be automatically masked.
* @param [body] A string representing an extra content to display within the notification.
* @param [dir] The direction of the notification; it can be auto, ltr, or rtl.
* @param [icon] The URL of an image to be used as an icon by the notification.
* @param [image] A USVSTring containing the URL of an image to be displayed in the notification.
* @param [lang] Specify the lang used within the notification. This string must be a valid BCP 47 language tag.
* @param [renotify] A boolean that indicates whether to supress vibrations and audible alerts when resusing a tag
* value. The default is false.
* @param [requireInteraction] Indicates that on devices with sufficiently large screens, a notification should remain
* active until the user clicks or dismisses it. If this value is absent or false, the desktop version of Chrome
* will auto-minimize notifications after approximately twenty seconds. The default value is false.
* @param [tag] An ID for a given notification that allows you to find, replace, or remove the notification using
* script if necessary.
* @param [vibrate] A vibration pattern to run with the display of the notification. A vibration pattern can be an
* array with as few as one member. The values are times in milliseconds where the even indices (0, 2, 4, etc.) indicate
* how long to vibrate and the odd indices indicate how long to pause. For example [300, 100, 400] would vibrate
* 300ms, pause 100ms, then vibrate 400ms.
* @param [data] Arbitrary data that you want associated with the notification. This can be of any data type.
*/
interface ServiceWorkerNotificationOptions {
actions?: NotificationAction[];
badge?: string;
body?: string;
dir?: 'auto' | 'ltr' | 'rtl';
icon?: string;
lang?: string;
renotify?: boolean;
requireInteraction?: boolean;
tag?: string;
vibrate?: number[];
data?: any;
}
/**
* An options object that can contain options to filter notifications.
* @param [tag] A DOMString representing a notification tag. If specified, only notifications that have this tag
* will be returned.
*/
interface ServiceWorkerGetNotificationOptions {
tag: string;
}
/**
* Provides an object representing the service worker as an overall unit in the
* network ecosystem, including facilities to register, unregister and update
* service workers, and access the state of service workers
* and their registrations.
*/
interface ServiceWorkerContainer extends EventTarget {
/**
* Returns a ServiceWorker object if its state is activated (the same object
* returned by ServiceWorkerRegistration.active). This property returns null
* if the request is a force refresh (Shift + refresh) or if there is no
* active worker.
*/
readonly controller: ServiceWorker;
/**
* Defines whether a service worker is ready to control a page or not.
* It returns a Promise that will never reject, which resolves to a
* ServiceWorkerRegistration with an ServiceWorkerRegistration.active worker.
*/
readonly ready: Promise<ServiceWorkerRegistration>;
/**
* An event handler fired whenever a controllerchange event occurs — when
* the document's associated ServiceWorkerRegistration acquires a new
* ServiceWorkerRegistration.active worker.
*/
oncontrollerchange: (controllerchangeevent: Event) => void;
/**
* An event handler fired whenever an error event occurs in the associated
* service workers.
*/
onerror: (errorevent: ErrorEvent) => void;
/**
* An event handler fired whenever a message event occurs — when incoming
* messages are received to the ServiceWorkerContainer object (e.g. via a
* MessagePort.postMessage() call.)
*/
onmessage: (messageevent: MessageEvent) => void;
/**
* Creates or updates a ServiceWorkerRegistration for the given scriptURL.
*
* @param scriptURL The URL of the service worker script.
* @param [options] An options object to provide options upon registration.
*/
register(scriptURL: string, options?: ServiceWorkerRegisterOptions): Promise<ServiceWorkerRegistration>;
/**
* Gets a ServiceWorkerRegistration object whose scope URL matches the
* provided document URL. If the method can't return a
* ServiceWorkerRegistration, it returns a Promise.
*
* @param [scope] A unique identifier for a service worker registration — the
* scope URL of the registration object you want to return. This is usually
* a relative URL.
*/
getRegistration(scope?: string): Promise<ServiceWorkerRegistration>;
/**
* Returns all ServiceWorkerRegistrations associated with a
* ServiceWorkerContainer in an array. If the method can't return
* ServiceWorkerRegistrations, it returns a Promise.
*/
getRegistrations(): Promise<ServiceWorkerRegistration[]>;
addEventListener<K extends keyof ServiceWorkerContainerEventMap>(
type: K,
listener: (event: ServiceWorkerContainerEventMap[K]) => any,
useCapture?: boolean
): void;
}
interface ServiceWorkerGlobalScope extends EventTarget {
/**
* Contains the CacheStorage object associated with the service worker.
*/
readonly caches: CacheStorage;
/**
* Contains the Clients object associated with the service worker.
*/
readonly clients: ServiceWorkerClients;
/**
* Contains the ServiceWorkerRegistration object that represents the
* service worker's registration.
*/
readonly registration: ServiceWorkerRegistration;
/**
* An event handler fired whenever an activate event occurs — when a
* ServiceWorkerRegistration acquires a new ServiceWorkerRegistration.active
* worker.
*/
onactivate: (activateevent: ExtendableEvent) => void;
/**
* An event handler fired whenever a fetch event occurs — when a fetch()
* is called.
*/
onfetch: (fetchevent: FetchEvent) => void;
/**
* An event handler fired whenever an install event occurs — when a
* ServiceWorkerRegistration acquires a new
* ServiceWorkerRegistration.installing worker.
*/
oninstall: (installevent: InstallEvent) => void;
/**
* An event handler fired whenever a message event occurs — when incoming
* messages are received. Controlled pages can use the
* MessagePort.postMessage() method to send messages to service workers.
* The service worker can optionally send a response back via the
* MessagePort exposed in event.data.port, corresponding to the controlled
* page.
*
* `onmessage` is actually fired with `ExtendableMessageEvent`, but
* since we are merging the interface into `Window`, we should
* make sure it's compatible with `window.onmessage`
*/
// onmessage: (messageevent: ExtendableMessageEvent) => void;
onmessage: (messageevent: MessageEvent) => void;
/**
* An event handler fired whenever a notificationclick event occurs — when
* a user clicks on a displayed notification.
*/
onnotificationclick: (notificationclickevent: NotificationEvent) => void;
/**
* An event handler fired whenever a push event occurs — when a server
* push notification is received.
*/
onpush: (onpushevent: PushEvent) => void;
/**
* An event handler fired whenever a pushsubscriptionchange event occurs —
* when a push subscription has been invalidated, or is about to be
* invalidated (e.g. when a push service sets an expiration time).
*/
onpushsubscriptionchange: (pushsubscriptionchangeevent: PushEvent) => void;
/**
* Allows the current service worker registration to progress from waiting
* to active state while service worker clients are using it.
*/
skipWaiting(): Promise<void>;
addEventListener<K extends keyof ServiceWorkerEventMap>(
type: K,
listener: (event: ServiceWorkerEventMap[K]) => any,
useCapture?: boolean
): void;
}
interface Navigator {
/**
* Returns a ServiceWorkerContainer object, which provides access to
* registration, removal, upgrade, and communication with the ServiceWorker
* objects for the associated document.
*/
serviceWorker: ServiceWorkerContainer;
}
// tslint:disable-next-line no-empty-interface
interface Window extends ServiceWorkerGlobalScope {}
@@ -1,206 +0,0 @@
var OFFLINE_CACHE = "cache_test";
var OFFLINE_URL = "localhost";
self.addEventListener('fetch', (event: FetchEvent) => {
if (event.request.method === 'GET' &&
event.request.headers.get('accept').indexOf('text/html') !== -1) {
console.log('Handling fetch event for', event.request.url);
event.respondWith(
self.fetch(event.request).catch(e => {
console.error('Fetch failed; returning offline page instead.', e);
return self.caches.open(OFFLINE_CACHE).then((cache: Cache) => {
return cache.match(OFFLINE_URL);
});
})
);
}
});
self.caches.open('v1').then((cache: Cache) => {
cache.matchAll('/images/').then((response: Response[]) => {
response.forEach((element, index, array) => {
cache.delete(element.url);
});
});
});
self.addEventListener('install', (event: InstallEvent) => {
event.waitUntil(
self.caches.open('v1').then((cache: Cache) => {
return cache.add('/sw-test/index.html');
})
);
});
self.addEventListener('install', (event: InstallEvent) => {
event.waitUntil(
self.caches.open('v1').then(cache => {
return cache.addAll([
'/sw-test/',
'/sw-test/index.html',
'/sw-test/style.css',
'/sw-test/app.js',
'/sw-test/image-list.js',
'/sw-test/star-wars-logo.jpg',
'/sw-test/gallery/',
'/sw-test/gallery/bountyHunters.jpg',
'/sw-test/gallery/myLittleVader.jpg',
'/sw-test/gallery/snowTroopers.jpg'
]);
})
);
});
self.addEventListener('fetch', (event: FetchEvent) => {
var cachedResponse = self.caches.match(event.request).then(response => {
if (response) {
return response;
}
}).catch(() => {
return self.fetch(event.request).then(response => {
return self.caches.open('v1').then(cache => {
cache.put(event.request, response.clone());
return response;
});
});
}).catch(() => {
return self.caches.match('/sw-test/gallery/myLittleVader.jpg');
});
event.respondWith(cachedResponse);
});
self.caches.open('v1').then(cache => {
cache.match('/images/image.png').then(response => {
cache.delete(response.url);
});
});
self.caches.open('v1').then(cache => {
cache.keys().then(response => {
response.forEach((element, index, array) => {
cache.delete(element);
});
});
});
self.caches.has('v1').then(() => {
self.caches.delete('v1').then(() => {
console.log('done');
});
});
self.addEventListener('activate', (event: ExtendableEvent) => {
var cacheWhitelist = ['v2'];
event.waitUntil(
self.caches.keys().then(keyList => {
for (var item of keyList) {
if (cacheWhitelist.indexOf(item) === -1) {
return self.caches.delete(item);
}
}
})
);
});
function sendMessage(message: any) {
return new Promise((resolve, reject) => {
var messageChannel = new MessageChannel();
messageChannel.port1.onmessage = event => {
if (event.data.error) {
reject(event.data.error);
} else {
resolve(event.data);
}
};
navigator.serviceWorker.controller.postMessage(message, [messageChannel.port2]);
});
}
self.addEventListener('message', (evt: ExtendableMessageEvent) => {
evt.ports[0].postMessage(evt.source.id);
});
sendMessage('test').then((clientId: string) => {
console.log(clientId);
});
self.clients.matchAll({type: "test"}).then(clients => {
for (var cli of clients) {
if (cli.url === 'index.html') {
self.clients.openWindow(cli.url);
// or do something else involving the matching client
}
}
});
self.addEventListener('activate', (e: ExtendableEvent) => {
e.waitUntil(self.clients.claim());
});
navigator.serviceWorker.register('service-worker.js', {scope: './'}).then(registration => {
// At this point, registration has taken place.
// The service worker will not handle requests until this page and any
// other instances of this page (in other tabs, etc.) have been
// closed/reloaded.
var serviceWorker: ServiceWorker;
if (registration.installing) {
serviceWorker = registration.installing;
} else if (registration.waiting) {
serviceWorker = registration.waiting;
} else if (registration.active) {
serviceWorker = registration.active;
}
if (serviceWorker) {
console.log(serviceWorker.state);
serviceWorker.addEventListener('statechange', (e: any) => {
console.log(e.target.state);
});
}
}).catch(error => {
// Something went wrong during registration. The service-worker.js file
// might be unavailable or contain a syntax error.
});
navigator.serviceWorker.getRegistration('/app').then((registration: ServiceWorkerRegistration) => {
console.log(registration);
});
navigator.serviceWorker.getRegistrations().then((registrations: ServiceWorkerRegistration[]) => {
console.log(registrations);
});
self.registration.unregister();
self.addEventListener('install', (event: ExtendableEvent) => {
event.waitUntil(self.skipWaiting());
});
self.addEventListener('notificationclick', (event: NotificationEvent) => {
console.log('On notification click: ', event.notification.tag);
event.notification.close();
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(self.clients.matchAll({
type: "window"
}).then(clientList => {
if (self.clients.openWindow)
return self.clients.openWindow('/');
}));
});
navigator.serviceWorker.ready.then(function(registration) {
registration.showNotification('Notification Sample', {
body: 'This is a sample notification!',
icon: '/sw-test/star-wars-logo.jpg',
tag: 'notification-sample'
});
});
self.registration.getNotifications({tag: 'notification-sample'})
.then(function(notifications) {
console.log(notifications);
});
-23
View File
@@ -1,23 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"service_worker_api-tests.ts"
]
}
-1
View File
@@ -1 +0,0 @@
{ "extends": "../tslint.json" }
-5
View File
@@ -1,5 +0,0 @@
{
"dependencies": {
"immutable": "^3.8.1"
}
}
+1 -23
View File
@@ -1,7 +1,6 @@
// tests taken from https://github.com/cognitect-labs/transducers-js
import * as t from 'transducers-js';
import * as _ from "lodash";
var map = t.map,
filter = t.filter,
@@ -14,7 +13,7 @@ function inc(n: number) { return n + 1; };
function isEven(n: number) { return n % 2 === 0; };
var xf = comp(map(inc), filter(isEven));
console.log(into([], xf, [0, 1, 2, 3, 4])); // [2, 4]
into([], xf, [0, 1, 2, 3, 4]); // [2, 4]
// integration
@@ -24,27 +23,6 @@ var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
toFn = t.toFn;
arr.reduce(toFn(xf, apush), []); // native
_(arr).reduce(toFn(xf, apush), []); // underscore or lodash
// immutable-js
import * as Immutable from 'immutable';
function sum(a: number, b: number): number { return a + b; };
var transduce = t.transduce;
var largeVector = Immutable.List();
for (var i = 0; i < 1000000; i++) {
largeVector = largeVector.push(i);
}
// built in Immutable-js functionality
largeVector.map(inc).filter(isEven).reduce(sum);
// faster with transducers
var xf = comp(map(inc), filter(isEven));
transduce(xf, sum, 0, largeVector);
// source examples
+1 -2
View File
@@ -2,8 +2,7 @@
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,