Type-safe emscripten interface.

This commit is contained in:
Florian Dold 2015-12-13 23:47:30 +01:00
parent e370cd9ef6
commit 441f41decc
12 changed files with 16468 additions and 3886 deletions

View File

@ -14,510 +14,157 @@
You should have received a copy of the GNU General Public License along with
TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
"use strict";
/* According to emscripten's design, we need our emscripted library to be executed
with a 'window' object as its global scope.
Note: that holds on emscripten's functions too, that is they need to be *explicitly*
run with some 'window' object as their global scope. In practice, given a function
'foo' pointing to some emscripted function, that is accomplished by the mean of 'call()'
or 'apply()' methods; so, being 'someWin' a 'window' object, the statements
foo.call('someWin', arg1, .., argN) or foo.apply('someWin', ['arg1', .., 'argN']) will
execute foo(arg1, .., argN) with 'someWin' as its global scope.
See http://www.bennadel.com/blog/2265-changing-the-execution-context-of-javascript
-functions-using-call-and-apply.htm. */
/* The naming convention is such that:
- 'GCfunctionName' takes its code from GNUNET_CRYPTO_function_name
- 'GCALLfunctionName' takes its code from GNUNET_CRYPTO_function_name and returns
a pointer that must be deallocated using 'WRgnunetFree' (that takes its code from
'GNUNET_free' in the wrapper)
- 'GSfunctionName' and 'GSALLfunctionName' comply to the same convention respect to
GNUNET_STRINGS_* realm.
- 'TWRfunctionName' takes its code from 'TALER_function_name' in the wrapper.
- 'TWRALLfunctionName' takes its code from 'TALER_ALL_function_name' in the wrapper
and returns a pointer that must be deallocated using 'TWRgnunetFree' (or a function
provided by some emscripted routine) (the 'wrapper' is an additional layer written in
C that does some struct(s) manipulations where that is uncovenient to do from JavaScript.
Currently located at '../../emscripten/testcases/wrap.c')
- The same applies to 'TfunctionName' and 'TALLfunctionName', to indicate that the
respective functions come from (the emscripted version of) TALER_* realm. */
// Size of a native pointer.
const PTR_SIZE = 4;
// shortcut to emscr's 'malloc'
function emscMalloc(size) {
var ptr = Module._malloc(size);
return ptr;
let getEmsc = Module.cwrap;
var emsc = {
free: (ptr) => Module._free(ptr),
get_value: getEmsc('TALER_WR_get_value', 'number', ['number']),
get_fraction: getEmsc('TALER_WR_get_fraction', 'number', ['number']),
get_currency: getEmsc('TALER_WR_get_currency', 'string', ['number']),
amount_add: getEmsc('TALER_amount_add', 'void', ['number', 'number', 'number']),
amount_subtract: getEmsc('TALER_amount_subtract', 'void', ['number', 'number', 'number']),
amount_normalize: getEmsc('TALER_amount_normalize', 'void', ['number']),
amount_cmp: getEmsc('TALER_amount_cmp', 'number', ['number', 'number'])
};
var emscAlloc = {
get_amount: getEmsc('TALER_WRALL_get_amount', 'number', ['number', 'number', 'number', 'string']),
eddsa_key_create: getEmsc('GNUNET_CRYPTO_eddsa_key_create', 'number'),
eddsa_public_key_from_private: getEmsc('TALER_WRALL_eddsa_public_key_from_private', 'number', ['number']),
malloc: (size) => Module._malloc(size),
};
class ArenaObject {
constructor(arena) {
this.nativePtr = 0;
if (!arena)
arena = defaultArena;
arena.put(this);
this.arena = arena;
}
}
/* shortcut to emscr's 'free'. This function is problematic:
it randomly stops working giving 'emscFree is not a function'
error */
function emscFree(ptr) {
Module._free(ptr);
class Arena {
constructor() {
this.heap = [];
}
put(obj) {
this.heap.push(obj);
}
destroy(obj) {
// XXX: todo
}
}
var getEmsc = Module.cwrap;
var TWRhelloWorld = getEmsc('TALER_WR_hello_world', 'void', []);
var TWRverifyConfirmation = getEmsc('TALER_WR_verify_confirmation',
'number',
['number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number']);
var TWRgetValue = getEmsc('TALER_WR_get_value',
'number',
['number']);
var TWRgetFraction = getEmsc('TALER_WR_get_fraction',
'number',
['number']);
var TWRgetCurrency = getEmsc('TALER_WR_get_currency',
'string',
['number']);
var TWRmultiplyAmounts = getEmsc('TALER_WR_multiply_amounts',
'number',
['number',
'number'] );
var TWRmultiplyAmount = getEmsc('TALER_WR_multiply_amount',
'number',
['number',
'number'] );
var TWRALLrsaPublicKeyHash = getEmsc('TALER_WRALL_rsa_public_key_hash',
'number',
['number']);
var TWRverifyDenom = getEmsc('TALER_WR_verify_denom',
'number',
['number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number']);
var TWRverifyDenoms = getEmsc('TALER_WR_verify_denoms',
'number',
['number',
'number',
'number',
'number',
'number']);
var TWRverifySignKey = getEmsc('TALER_WR_verify_sign_key',
'number',
['number',
'number',
'number',
'number',
'number',
'number']);
var TWRALLgetEncodingFromRsaSignature = getEmsc('TALER_WRALL_get_encoding_from_rsa_signature',
'number',
['number']);
var TamountCmp = getEmsc('TALER_amount_cmp',
'number',
['number',
'number']);
var DWRdumpAmount = getEmsc('DEBUG_WR_dump_amount',
'void'
['number']);
var DWRtestStringCmp = getEmsc('DEBUG_WR_test_string_cmp',
'number',
['number',
'string']);
var TWRALLgetAmount = getEmsc('TALER_WRALL_get_amount',
'number',
['number',
'number',
'number',
'string']);
var DWRgetPurpose = getEmsc('DEBUG_WR_get_purpose',
'number',
['number']);
var TWReddsaVerify = getEmsc('TALER_WR_eddsa_verify',
'number',
['string',
'number',
'number',
'number']);
var TWRALLmakeEddsaSignature = getEmsc('TALER_WRALL_make_eddsa_signature',
'number',
['number',
'number']);
var TWRALLamountAdd = getEmsc('TALER_WRALL_amount_add',
'number',
['number',
'number',
'number',
'number',
'number',
'number',
'string']);
var TamountSubtract = getEmsc('TALER_amount_subtract',
'number',
['number',
'number',
'number']);
var TamountAdd = getEmsc('TALER_amount_add',
'number',
['number',
'number',
'number']);
var TWRALLeddsaPublicKeyFromPrivate = getEmsc('TALER_WRALL_eddsa_public_key_from_private',
'number',
['number']);
var TWRALLeddsaPublicKeyFromPrivString = getEmsc('TALER_WRALL_eddsa_public_key_from_priv_string',
'number',
['string']);
var TWRALLsignDepositPermission = getEmsc('TALER_WRALL_sign_deposit_permission',
'number',
['number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number']);
var TWRALLeddsaPrivateKeyFromString = getEmsc('TALER_WRALL_eddsa_private_key_from_string',
'number',
['string']);
var TWRALLrsaPublicKeyDecodeFromString = getEmsc('TALER_WRALL_rsa_public_key_decode_from_string',
'number',
['string']);
var TWRALLecdhePublicKeyFromPrivateKey = getEmsc('TALER_WRALL_ecdhe_public_key_from_private_key',
'number',
['number']);
var TWRALLeccEcdh = getEmsc('TALER_WRALL_ecc_ecdh',
'number',
['number',
'number',
'number']);
var TWRALLmakeWithdrawBundle = getEmsc('TALER_WRALL_make_withdraw_bundle',
'number',
['number',
'number',
'number',
'number',
'number',
'number']);
var WRALLmakePurpose = getEmsc('WRALL_make_purpose',
'number',
['string',
'number',
'number',
'number']);
var GCALLrsaSignatureDecode = getEmsc('GNUNET_CRYPTO_rsa_signature_decode',
'number',
['number',
'number']);
var GCALLrsaSignatureEncode = getEmsc('GNUNET_CRYPTO_rsa_signature_encode',
'number',
['number',
'number']);
var GCALLrsaPublicKeyEncode = getEmsc('GNUNET_CRYPTO_rsa_public_key_encode',
'number',
['number',
'number']);
var GCALLrsaPublicKeyDecode = getEmsc('GNUNET_CRYPTO_rsa_public_key_decode',
'number',
['number',
'number']);
var GCALLrsaPrivateKeyGetPublic = getEmsc('GNUNET_CRYPTO_rsa_private_key_get_public',
'number',
['number']);
var GCALLrsaPrivateKeyCreate = getEmsc('GNUNET_CRYPTO_rsa_private_key_create',
'number',
['number']);
var GCALLrsaBlindingKeyCreate = getEmsc('GNUNET_CRYPTO_rsa_blinding_key_create',
'number',
['number']);
var GCALLrsaBlindingKeyEncode = getEmsc('GNUNET_CRYPTO_rsa_blinding_key_encode',
'number',
['number', 'number']);
var GCrsaBlindingKeyFree = getEmsc('GNUNET_CRYPTO_rsa_blinding_key_free',
'void',
['number']);
var GCrsaPublicKeyFree = getEmsc('GNUNET_CRYPTO_rsa_public_key_free',
'void',
['number']);
var GCrsaPrivateKeyFree = getEmsc('GNUNET_CRYPTO_rsa_private_key_free',
'void',
['number']);
var GCALLrsaBlind = getEmsc('GNUNET_CRYPTO_rsa_blind',
'number',
['number',
'number',
'number',
'number']);
var GCALLrsaUnblind = getEmsc('GNUNET_CRYPTO_rsa_unblind',
'number',
['number',
'number',
'number']);
var GCALLrsaSign = getEmsc('GNUNET_CRYPTO_rsa_sign',
'number',
['number',
'number',
'number']);
var GCrsaVerify = getEmsc('GNUNET_CRYPTO_rsa_verify',
'number',
['number',
'number',
'number']);
var GCrsaSignatureFree = getEmsc('GNUNET_CRYPTO_rsa_signature_free',
'void',
['number']);
var GChkdf = getEmsc('GNUNET_CRYPTO_hkdf',
'number',
['number',
'number',
'number',
'number',
'number',
'number',
'number',
'number']);
var TWRALLgenKeyFromBlob = getEmsc('TALER_WRALL_gen_key_from_blob',
'number',
['string',
'number',
'number']);
var DWRtestString = getEmsc('DEBUG_WR_test_string',
'void',
['number',
'number',
'string']);
var GCsymmetricDecrypt = getEmsc('GNUNET_CRYPTO_symmetric_decrypt',
'number',
['number',
'number',
'number',
'number',
'number']);
var GCsymmetricEncrypt = getEmsc('GNUNET_CRYPTO_symmetric_encrypt',
'number',
['number',
'number',
'number',
'number',
'number']);
/* returns a pointer to a symmetric session key strucure and takes a salt, a
(pointer to) binary data used to generate the key, and the length of that
data */
var TWRALLgenSymmetricKey = getEmsc('TALER_WRALL_gen_symmetric_key',
'number',
['string',
'number',
'number']);
/* returns a pointer to a init. vector strucure and takes a salt, a
(pointer to) binary data used to generate the key, and the length of that
data */
var TWRALLgenInitVector = getEmsc('TALER_WRALL_gen_init_vector',
'number',
['string',
'number',
'number']);
// return key material from ECC keys
var GCeccEcdh = getEmsc('GNUNET_CRYPTO_ecc_ecdh',
'number',
['number',
'number',
'number']);
// return a pointer to a freshly allocated EddsaPublicKey structure
/* var WRALLeddsaPublicKey = getEmsc('WRALL_eddsa_public_key',
'number'); */
// return a pointer to a freshly allocated EcdhePublicKey structure
/* var WRALLecdhePublicKey = getEmsc('WRALL_ecdhe_public_key',
'number'); */
/* generates a new eddsa private key, returning a pointer to EddsaPrivateKey
structure */
var GCALLeddsaKeyCreate = getEmsc('GNUNET_CRYPTO_eddsa_key_create',
'number');
/* extract eddsa public key from a pointer to a EddsaPrivateKey structure
and put it in second argument */
var GCeddsaKeyGetPublic = getEmsc('GNUNET_CRYPTO_eddsa_key_get_public',
'void',
['number',
'number']);
/* generates a new ecdhe private key, returning a pointer to EcdhePrivateKey
structure */
var GCALLecdheKeyCreate = getEmsc('GNUNET_CRYPTO_ecdhe_key_create',
'number');
/* extract eddsa public key from a pointer to a EddsaPrivateKey structure and
put it in second argument */
var GCecdheKeyGetPublic = getEmsc('GNUNET_CRYPTO_ecdhe_key_get_public',
'void',
['number',
'number']);
// what to sign, the reason to sign, the location to store the signature
var GCeddsaSign = getEmsc('GNUNET_CRYPTO_eddsa_sign',
'int',
['number',
'number',
'number']);
/* get reference to the emscripted primitive: the first parameter is a
pointer (note that it points to the emscripten's heap) to the data being
encoded, the second is its length */
var GSALLdataToStringAlloc = getEmsc('GNUNET_STRINGS_data_to_string_alloc',
'number',
['number',
'number']);
// import GNUnet's memory deallocator
var TWRgnunetFree = getEmsc('TALER_WR_GNUNET_free',
'void',
['number']);
// GNUnet's base32 decoder
var GSstringToData = getEmsc('GNUNET_STRINGS_string_to_data',
'number',
['number',
'number',
'number',
'number']);
// get absolute time. Returned value has to be freed by gnunetFree
var TWRALLgetCurrentTime = getEmsc('TALER_WRALL_get_current_time',
'number');
// prettyfy time
var TWRgetFancyTime = getEmsc('TALER_WR_get_fancy_time',
'string',
['number']);
var TWRALLhash = getEmsc('TALER_WRALL_hash',
'number',
['number',
'number']);
/* computes the hashcode of the value pointed to by 'val' and sets the
pointer to the location holding the hashcode (which has to be previously
allocated and is a reflection of GNUNET_HashCode type). The returned
pointer has to be freed by gnunetFree.
Its interface is hash('val', 'valSize', 'hashedBuf') */
var GChash = getEmsc('GNUNET_CRYPTO_hash',
'void',
['number',
'number',
'number']);
/* this test just takes the private key to sign a dummy hardcoded
message. Return a pointer to the signed message (to be freed) */
var TWRALLsignTest = getEmsc('TALER_WRALL_sign_test',
'number',
['number']);
/* this test just takes the public key and the signed dummy
message. Return GNUNET_OK (=1) if it succeeds, otherwise
GNUNET_SYSERR (=-1) */
var WRverifyTest = getEmsc('WR_verify_test',
'number',
['number']);
let d2s = getEmsc('GNUNET_STRINGS_data_to_string_alloc',
'string',
['number', 'number']);
let sizeof_EddsaPrivateKey = 32;
let sizeof_EddsaPublicKey = 32;
function createEddsaKeyPair() {
let privPtr = GCALLeddsaKeyCreate();
let pubPtr = emscMalloc(sizeof_EddsaPublicKey);
GCeddsaKeyGetPublic(privPtr, pubPtr);
let privStr = d2s(privPtr, sizeof_EddsaPrivateKey);
let pubStr = d2s(pubPtr, sizeof_EddsaPublicKey);
return {priv: privStr, pub: pubStr};
// Arena to track allocations that do not use an explicit arena.
var defaultArena = new Arena();
class Amount extends ArenaObject {
constructor(args, arena) {
super(arena);
if (args) {
this.nativePtr = emscAlloc.get_amount(args.value, 0, args.fraction, args.currency);
}
else {
this.nativePtr = emscAlloc.get_amount(0, 0, 0, "");
}
}
destroy() {
if (this.nativePtr != 0) {
emsc.free(this.nativePtr);
}
}
get value() {
return emsc.get_value(this.nativePtr);
}
get fraction() {
return emsc.get_fraction(this.nativePtr);
}
get currency() {
return emsc.get_currency(this.nativePtr);
}
toJson() {
return {
value: emsc.get_value(this.nativePtr),
fraction: emsc.get_fraction(this.nativePtr),
currency: emsc.get_currency(this.nativePtr)
};
}
/**
* Add an amount to this amount.
*/
add(a) {
let res = emsc.amount_add(this.nativePtr, a.nativePtr, this.nativePtr);
if (res < 1) {
// Overflow
return false;
}
return true;
}
/**
* Perform saturating subtraction on amounts.
*/
sub(a) {
let res = emsc.amount_subtract(this.nativePtr, a.nativePtr, this.nativePtr);
if (res == 0) {
// Underflow
return false;
}
if (res > 0) {
return true;
}
throw "Incompatible currencies";
}
cmp(a) {
return emsc.amount_cmp(this.nativePtr, a.nativePtr);
}
normalize() {
emsc.amount_normalize(this.nativePtr);
}
}
function createRsaBlindingKey() {
let blindFac = GCALLrsaBlindingKeyCreate(1024);
let bufPtr = emscMalloc(PTR_SIZE);
let size = GCALLrsaBlindingKeyEncode (blindFac, bufPtr);
let key = d2s(Module.getValue(bufPtr, '*'), size);
emscFree(bufPtr);
return key;
class EddsaPrivateKey extends ArenaObject {
static create(a) {
let k = new EddsaPrivateKey(a);
k.nativePtr = emscAlloc.eddsa_key_create();
return k;
}
destroy() {
// TODO
}
getPublicKey() {
let pk = new EddsaPublicKey(this.arena);
pk.nativePtr = emscAlloc.eddsa_public_key_from_private(this.nativePtr);
return pk;
}
encode() {
throw "not implemented";
}
}
class EddsaPublicKey extends ArenaObject {
destroy() {
// TODO
}
encode() {
throw "not implemented";
}
}
class RsaBlindingKey extends ArenaObject {
destroy() {
// TODO
}
}
class HashCode extends ArenaObject {
destroy() {
// TODO
}
}
class ByteArray extends ArenaObject {
destroy() {
// TODO
}
}
class RsaPublicKey extends ArenaObject {
destroy() {
// TODO
}
}
function rsaBlind(hashCode, blindingKey, pkey, arena) {
return null;
}

View File

@ -0,0 +1,240 @@
/*
This file is part of TALER
Copyright (C) 2014, 2015 Christian Grothoff (and other contributing authors)
TALER is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation; either version 3, or (at your option) any later version.
TALER is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
"use strict";
declare var Module : any;
// Size of a native pointer.
const PTR_SIZE = 4;
let getEmsc = Module.cwrap;
var emsc = {
free: (ptr) => Module._free(ptr),
get_value: getEmsc('TALER_WR_get_value',
'number',
['number']),
get_fraction: getEmsc('TALER_WR_get_fraction',
'number',
['number']),
get_currency: getEmsc('TALER_WR_get_currency',
'string',
['number']),
amount_add: getEmsc('TALER_amount_add',
'void',
['number', 'number', 'number']),
amount_subtract: getEmsc('TALER_amount_subtract',
'void',
['number', 'number', 'number']),
amount_normalize: getEmsc('TALER_amount_normalize',
'void',
['number']),
amount_cmp: getEmsc('TALER_amount_cmp',
'number',
['number', 'number'])
};
var emscAlloc = {
get_amount: getEmsc('TALER_WRALL_get_amount',
'number',
['number', 'number', 'number', 'string']),
eddsa_key_create: getEmsc('GNUNET_CRYPTO_eddsa_key_create',
'number'),
eddsa_public_key_from_private: getEmsc('TALER_WRALL_eddsa_public_key_from_private',
'number',
['number']),
malloc: (size : number) => Module._malloc(size),
};
abstract class ArenaObject {
nativePtr: number;
arena: Arena;
abstract destroy(): void;
constructor(arena?: Arena) {
this.nativePtr = 0;
if (!arena)
arena = defaultArena;
arena.put(this);
this.arena = arena;
}
}
class Arena {
heap: Array<ArenaObject>;
constructor () {
this.heap = [];
}
put(obj) {
this.heap.push(obj);
}
destroy(obj) {
// XXX: todo
}
}
// Arena to track allocations that do not use an explicit arena.
var defaultArena = new Arena();
class Amount extends ArenaObject {
constructor(args?: any, arena?: Arena) {
super(arena);
if (args) {
this.nativePtr = emscAlloc.get_amount(args.value, 0, args.fraction, args.currency);
} else {
this.nativePtr = emscAlloc.get_amount(0, 0, 0, "");
}
}
destroy() {
if (this.nativePtr != 0) {
emsc.free(this.nativePtr);
}
}
get value() {
return emsc.get_value(this.nativePtr);
}
get fraction() {
return emsc.get_fraction(this.nativePtr);
}
get currency() {
return emsc.get_currency(this.nativePtr);
}
toJson() {
return {
value: emsc.get_value(this.nativePtr),
fraction: emsc.get_fraction(this.nativePtr),
currency: emsc.get_currency(this.nativePtr)
};
}
/**
* Add an amount to this amount.
*/
add(a) {
let res = emsc.amount_add(this.nativePtr, a.nativePtr, this.nativePtr);
if (res < 1) {
// Overflow
return false;
}
return true;
}
/**
* Perform saturating subtraction on amounts.
*/
sub(a) {
let res = emsc.amount_subtract(this.nativePtr, a.nativePtr, this.nativePtr);
if (res == 0) {
// Underflow
return false;
}
if (res > 0) {
return true;
}
throw "Incompatible currencies";
}
cmp(a) {
return emsc.amount_cmp(this.nativePtr, a.nativePtr);
}
normalize() {
emsc.amount_normalize(this.nativePtr);
}
}
class EddsaPrivateKey extends ArenaObject {
static create(a?: Arena): EddsaPrivateKey {
let k = new EddsaPrivateKey(a);
k.nativePtr = emscAlloc.eddsa_key_create();
return k;
}
destroy() {
// TODO
}
getPublicKey(): EddsaPublicKey {
let pk = new EddsaPublicKey(this.arena);
pk.nativePtr = emscAlloc.eddsa_public_key_from_private(this.nativePtr);
return pk;
}
encode(): string {
throw "not implemented";
}
}
class EddsaPublicKey extends ArenaObject {
destroy() {
// TODO
}
encode(): string {
throw "not implemented";
}
}
class RsaBlindingKey extends ArenaObject {
destroy() {
// TODO
}
}
class HashCode extends ArenaObject {
destroy() {
// TODO
}
}
class ByteArray extends ArenaObject {
destroy() {
// TODO
}
}
class RsaPublicKey extends ArenaObject {
destroy() {
// TODO
}
}
function rsaBlind(hashCode: HashCode,
blindingKey: RsaBlindingKey,
pkey: RsaPublicKey,
arena?: Arena): ByteArray
{
return null;
}

File diff suppressed because one or more lines are too long

View File

@ -1,322 +1,257 @@
/// <reference path="../decl/urijs/URIjs.d.ts" />
/// <reference path="../decl/chrome/chrome.d.ts" />
'use strict';
const DB_NAME = "taler";
const DB_VERSION = 1;
/**
* Return a promise that resolves
* to the taler wallet db.
*/
function openTalerDb(cont) {
return new Promise((resolve, reject) => {
let req = indexedDB.open(DB_NAME, DB_VERSION);
req.addEventListener("error", (e) => {
reject(e);
function openTalerDb() {
return new Promise((resolve, reject) => {
let req = indexedDB.open(DB_NAME, DB_VERSION);
req.onerror = (e) => {
reject(e);
};
req.onsuccess = (e) => {
resolve(e.target.result);
};
req.onupgradeneeded = (event) => {
let db = event.target.result;
console.log("DB: upgrade needed: oldVersion = " + event.oldVersion);
db = event.target.result;
switch (event.oldVersion) {
case 0:
db.createObjectStore("mints", { keyPath: "baseUrl" });
db.createObjectStore("reserves", { keyPath: "reserve_pub" });
db.createObjectStore("denoms", { keyPath: "denom_pub" });
db.createObjectStore("coins", { keyPath: "coin_pub" });
db.createObjectStore("withdrawals", { keyPath: "id", autoIncrement: true });
db.createObjectStore("transactions", { keyPath: "id", autoIncrement: true });
break;
}
};
});
req.addEventListener("success", (e) => {
resolve(e.target.result);
});
req.addEventListener("upgradeneeded", (e) => {
let db = e.target.result;
console.log ("DB: upgrade needed: oldVersion = " + event.oldVersion);
db = event.target.result;
switch (event.oldVersion) {
case 0: // DB does not exist yet
db.createObjectStore("mints", { keyPath: "baseUrl" });
db.createObjectStore("reserves", { keyPath: "reserve_pub"});
db.createObjectStore("denoms", { keyPath: "denom_pub" });
db.createObjectStore("coins", { keyPath: "coin_pub" });
db.createObjectStore("withdrawals", { keyPath: "id", autoIncrement: true });
db.createObjectStore("transactions", { keyPath: "id", autoIncrement: true });
break;
}
});
});
}
function canonicalizeBaseUrl(url) {
let x = new URI(url);
if (!x.protocol()) {
x.protocol("https");
}
x.path(x.path() + "/").normalizePath();
x.fragment();
x.query();
return x.href()
let x = new URI(url);
if (!x.protocol()) {
x.protocol("https");
}
x.path(x.path() + "/").normalizePath();
x.fragment();
x.query();
return x.href();
}
function confirmReserve(db, detail, sendResponse) {
console.log('detail: ' + JSON.stringify(detail));
let keypair = createEddsaKeyPair();
let form = new FormData();
let now = (new Date()).toString();
form.append(detail.field_amount, detail.amount_str);
form.append(detail.field_reserve_pub, keypair.pub);
form.append(detail.field_mint, detail.mint);
// XXX: set bank-specified fields.
let myRequest = new XMLHttpRequest();
console.log("making request to " + detail.post_url);
myRequest.open('post', detail.post_url);
myRequest.send(form);
let mintBaseUrl = canonicalizeBaseUrl(detail.mint);
myRequest.addEventListener('readystatechange', (e) => {
if (myRequest.readyState == XMLHttpRequest.DONE) {
let resp = {};
resp.status = myRequest.status;
resp.text = myRequest.responseText;
let reserveRecord = {
reserve_pub: keypair.pub,
reserve_priv: keypair.priv,
mint_base_url: mintBaseUrl,
created: now,
last_query: null,
current_amount: null,
// XXX: set to actual amount
initial_amount: null
};
// XXX: insert into db.
switch (myRequest.status) {
case 200:
resp.success = true;
// We can't show the page directly, so
// we show some generic page from the wallet.
resp.backlink = chrome.extension.getURL("pages/reserve-success.html");
let tx = db.transaction(['reserves'], 'readwrite');
tx.objectStore('reserves').add(reserveRecord);
tx.addEventListener('complete', (e) => {
console.log('tx complete, pk was ' + reserveRecord.reserve_pub);
sendResponse(resp);
var mint;
updateMintFromUrl(db, reserveRecord.mint_base_url)
.then((m) => { mint = m; return updateReserve(db, keypair.pub, mint); })
.then((reserve) => depleteReserve(db, reserve, mint));
});
break;
default:
resp.success = false;
sendResponse(resp);
}
}
});
// Allow async response
return true;
console.log('detail: ' + JSON.stringify(detail));
let reservePriv = EddsaPrivateKey.create();
let reservePub = reservePriv.getPublicKey();
let form = new FormData();
let now = (new Date()).toString();
form.append(detail.field_amount, detail.amount_str);
form.append(detail.field_reserve_pub, reservePub.encode());
form.append(detail.field_mint, detail.mint);
// XXX: set bank-specified fields.
let myRequest = new XMLHttpRequest();
console.log("making request to " + detail.post_url);
myRequest.open('post', detail.post_url);
myRequest.send(form);
let mintBaseUrl = canonicalizeBaseUrl(detail.mint);
myRequest.addEventListener('readystatechange', (e) => {
if (myRequest.readyState == XMLHttpRequest.DONE) {
// TODO: extract as interface
let resp = {
status: myRequest.status,
text: myRequest.responseText,
success: undefined,
backlink: undefined
};
let reserveRecord = {
reserve_pub: reservePub.encode(),
reserve_priv: reservePriv.encode(),
mint_base_url: mintBaseUrl,
created: now,
last_query: null,
current_amount: null,
// XXX: set to actual amount
initial_amount: null
};
// XXX: insert into db.
switch (myRequest.status) {
case 200:
resp.success = true;
// We can't show the page directly, so
// we show some generic page from the wallet.
resp.backlink = chrome.extension.getURL("pages/reserve-success.html");
let tx = db.transaction(['reserves'], 'readwrite');
tx.objectStore('reserves').add(reserveRecord);
tx.addEventListener('complete', (e) => {
console.log('tx complete, pk was ' + reserveRecord.reserve_pub);
sendResponse(resp);
var mint;
updateMintFromUrl(db, reserveRecord.mint_base_url)
.then((m) => { mint = m; return updateReserve(db, reservePub, mint); })
.then((reserve) => depleteReserve(db, reserve, mint));
});
break;
default:
resp.success = false;
sendResponse(resp);
}
}
});
// Allow async response
return true;
}
function sumAmounts() {
let v = 0;
let f = 0;
let c;
let xs = arguments;
if (xs.length == 0) {
throw "no arguments given";
}
for (let x of xs) {
v = (v + x.value) + Math.floor((f + x.value) / 10e6);
f = (f + x.fraction) % 10e6;
c = x.currency;
}
return {value: v, fraction:f, currency: c};
}
function subtractAmount(a1, a2) {
if (compareAmount(a1, a2) < 0) {
throw "negative result";
}
let r = {
currency: a1.currency,
value: a1.value,
fraction: a1.fraction
};
if (a2.fraction > a1.fraction) {
r.value--;
r.fraction += 1000000;
}
r.value -= a2.value;
r.fraction -= a2.fraction;
return r;
}
function compareAmount(a1, a2) {
if (a1.currency !== a2.currency) {
throw "can't compare different currencies";
}
let v1 = [a1.value + Math.floor(a1.fraction / 10e6), a1.fraction % 10e6];
let v2 = [a2.value + Math.floor(a2.fraction / 10e6), a2.fraction % 10e6];
for (let i in v1) {
if (v1[i] < v2[i]) {
return -1;
}
if (v1[i] > v2[i]) {
return 1;
}
}
return 0;
}
function copy(o) {
return JSON.parse(JSON.stringify(o));
return JSON.parse(JSON.stringify(o));
}
function rankDenom(o1, o2) {
return (-1) * compareAmount(o1.value, o2.value);
return (-1) * o1.cmp(o2);
}
function withdraw(denom, reserve, mint) {
let wd = {};
wd.denom_pub = denom.denom_pub;
wd.reserve_pub = reserve.reserve_pub;
let coin_key = createEddsaKeyPair();
// create RSA blinding key
// blind coin
// generate signature
let wd = {
denom_pub: denom.denom_pub,
reserve_pub: reserve.reserve_pub,
};
let coinPub = EddsaPrivateKey.create();
// create RSA blinding key
// blind coin
// generate signature
}
/**
* Withdraw coins from a reserve until it is empty.
*/
function depleteReserve(db, reserve, mint) {
let denoms = copy(mint.keys.denoms);
let remaining = copy(reserve.current_amount);
denoms.sort(rankDenom);
for (let i = 0; i < 1000; i++) {
let found = false;
for (let d of denoms) {
let cost = sumAmounts(d.value, d.fee_withdraw);
if (compareAmount (remaining, cost) < 0) {
continue;
}
found = true;
remaining = subtractAmount(remaining, cost);
withdraw(d, reserve, mint);
}
if (!found) {
break;
}
}
}
function updateReserve(db, reservePub, mint) {
let reserve;
return new Promise((resolve, reject) => {
let tx = db.transaction(['reserves']);
tx.objectStore('reserves').get(reservePub).onsuccess = (e) => {
let reserve = e.target.result;
let reqUrl = URI("reserve/status").absoluteTo(mint.baseUrl);
reqUrl.query({'reserve_pub': reservePub});
let myRequest = new XMLHttpRequest();
console.log("making request to " + reqUrl.href());
myRequest.open('get', reqUrl.href());
myRequest.send();
myRequest.addEventListener('readystatechange', (e) => {
if (myRequest.readyState == XMLHttpRequest.DONE) {
if (myRequest.status != 200) {
reject();
return;
}
let reserveInfo = JSON.parse(myRequest.responseText);
console.log("got response " + JSON.stringify(reserveInfo));
reserve.current_amount = reserveInfo.balance;
let tx = db.transaction(['reserves'], 'readwrite');
console.log("putting updated reserve " + JSON.stringify(reserve));
tx.objectStore('reserves').put(reserve);
tx.oncomplete = (e) => {
resolve(reserve);
};
let denoms = copy(mint.keys.denoms);
let remaining = new Amount(reserve.current_amount);
denoms.sort(rankDenom);
for (let i = 0; i < 1000; i++) {
let found = false;
for (let d of denoms) {
let cost = new Amount();
cost.add(new Amount(d.value));
cost.add(new Amount(d.fee_withdraw));
if (remaining.cmp(cost) < 0) {
continue;
}
found = true;
remaining.sub(cost);
withdraw(d, reserve, mint);
}
});
};
});
if (!found) {
break;
}
}
}
function updateReserve(db, reservePub, mint) {
let reserve;
return new Promise((resolve, reject) => {
let tx = db.transaction(['reserves']);
tx.objectStore('reserves').get(reservePub).onsuccess = (e) => {
let reserve = e.target.result;
let reqUrl = URI("reserve/status").absoluteTo(mint.baseUrl);
reqUrl.query({ 'reserve_pub': reservePub });
let myRequest = new XMLHttpRequest();
console.log("making request to " + reqUrl.href());
myRequest.open('get', reqUrl.href());
myRequest.send();
myRequest.addEventListener('readystatechange', (e) => {
if (myRequest.readyState == XMLHttpRequest.DONE) {
if (myRequest.status != 200) {
reject();
return;
}
let reserveInfo = JSON.parse(myRequest.responseText);
console.log("got response " + JSON.stringify(reserveInfo));
reserve.current_amount = reserveInfo.balance;
let tx = db.transaction(['reserves'], 'readwrite');
console.log("putting updated reserve " + JSON.stringify(reserve));
tx.objectStore('reserves').put(reserve);
tx.oncomplete = (e) => {
resolve(reserve);
};
}
});
};
});
}
/**
* Update or add mint DB entry by fetching the /keys information.
* Optionally link the reserve entry to the new or existing
* mint entry in then DB.
*/
function updateMintFromUrl(db, baseUrl) {
console.log("base url is " + baseUrl);
let reqUrl = URI("keys").absoluteTo(baseUrl);
let myRequest = new XMLHttpRequest();
myRequest.open('get', reqUrl.href());
myRequest.send();
return new Promise((resolve, reject) => {
myRequest.addEventListener('readystatechange', (e) => {
console.log("state change to " + myRequest.readyState);
if (myRequest.readyState == XMLHttpRequest.DONE) {
if (myRequest.status == 200) {
console.log("got /keys");
let mintKeysJson = JSON.parse(myRequest.responseText);
if (!mintKeysJson) {
console.log("keys invalid");
reject();
} else {
let mint = {};
mint.baseUrl = baseUrl;
mint.keys = mintKeysJson;
let tx = db.transaction(['mints'], 'readwrite');
tx.objectStore('mints').put(mint);
tx.oncomplete = (e) => {
resolve(mint);
};
}
} else {
console.log("/keys request failed with status " + myRequest.status);
// XXX: also write last error to DB to show in the UI
reject();
}
}
console.log("base url is " + baseUrl);
let reqUrl = URI("keys").absoluteTo(baseUrl);
let myRequest = new XMLHttpRequest();
myRequest.open('get', reqUrl.href());
myRequest.send();
return new Promise((resolve, reject) => {
myRequest.addEventListener('readystatechange', (e) => {
console.log("state change to " + myRequest.readyState);
if (myRequest.readyState == XMLHttpRequest.DONE) {
if (myRequest.status == 200) {
console.log("got /keys");
let mintKeysJson = JSON.parse(myRequest.responseText);
if (!mintKeysJson) {
console.log("keys invalid");
reject();
}
else {
let mint = {
baseUrl: baseUrl,
keys: mintKeysJson
};
let tx = db.transaction(['mints'], 'readwrite');
tx.objectStore('mints').put(mint);
tx.oncomplete = (e) => {
resolve(mint);
};
}
}
else {
console.log("/keys request failed with status " + myRequest.status);
// XXX: also write last error to DB to show in the UI
reject();
}
}
});
});
});
}
function dumpDb(db, detail, sendResponse) {
let dump = {};
dump.name = db.name;
dump.version = db.version;
dump.stores = {};
console.log("stores: " + JSON.stringify(db.objectStoreNames));
let tx = db.transaction(db.objectStoreNames);
tx.addEventListener('complete', (e) => {
sendResponse(dump);
});
for (let i = 0; i < db.objectStoreNames.length; i++) {
let name = db.objectStoreNames[i];
let storeDump = {};
dump.stores[name] = storeDump;
let store = tx.objectStore(name).openCursor().addEventListener('success', (e) => {
let cursor = event.target.result;
if (cursor) {
storeDump[cursor.key] = cursor.value;
cursor.continue();
}
let dump = {
name: db.name,
version: db.version,
stores: {}
};
console.log("stores: " + JSON.stringify(db.objectStoreNames));
let tx = db.transaction(db.objectStoreNames);
tx.addEventListener('complete', (e) => {
sendResponse(dump);
});
}
return true;
for (let i = 0; i < db.objectStoreNames.length; i++) {
let name = db.objectStoreNames[i];
let storeDump = {};
dump.stores[name] = storeDump;
let store = tx.objectStore(name).openCursor().addEventListener('success', (e) => {
let cursor = e.target.result;
if (cursor) {
storeDump[cursor.key] = cursor.value;
cursor.continue();
}
});
}
return true;
}
openTalerDb().then((db) => {
console.log("db loaded");
chrome.runtime.onMessage.addListener(
function (req, sender, onresponse) {
let dispatch = {
"confirm-reserve": confirmReserve,
"dump-db": dumpDb
}
return dispatch[req.type](db, req.detail, onresponse);
console.log("db loaded");
chrome.runtime.onMessage.addListener(function (req, sender, onresponse) {
let dispatch = {
"confirm-reserve": confirmReserve,
"dump-db": dumpDb
};
return dispatch[req.type](db, req.detail, onresponse);
});
});

View File

@ -0,0 +1,282 @@
/// <reference path="../decl/urijs/URIjs.d.ts" />
/// <reference path="../decl/chrome/chrome.d.ts" />
'use strict';
const DB_NAME = "taler";
const DB_VERSION = 1;
/**
* Return a promise that resolves
* to the taler wallet db.
*/
function openTalerDb() {
return new Promise((resolve, reject) => {
let req = indexedDB.open(DB_NAME, DB_VERSION);
req.onerror = (e) => {
reject(e);
};
req.onsuccess = (e : any) => {
resolve(e.target.result);
};
req.onupgradeneeded = (event : any) => {
let db = event.target.result;
console.log ("DB: upgrade needed: oldVersion = " + event.oldVersion);
db = event.target.result;
switch (event.oldVersion) {
case 0: // DB does not exist yet
db.createObjectStore("mints", { keyPath: "baseUrl" });
db.createObjectStore("reserves", { keyPath: "reserve_pub"});
db.createObjectStore("denoms", { keyPath: "denom_pub" });
db.createObjectStore("coins", { keyPath: "coin_pub" });
db.createObjectStore("withdrawals", { keyPath: "id", autoIncrement: true });
db.createObjectStore("transactions", { keyPath: "id", autoIncrement: true });
break;
}
};
});
}
function canonicalizeBaseUrl(url) {
let x = new URI(url);
if (!x.protocol()) {
x.protocol("https");
}
x.path(x.path() + "/").normalizePath();
x.fragment();
x.query();
return x.href()
}
function confirmReserve(db, detail, sendResponse) {
console.log('detail: ' + JSON.stringify(detail));
let reservePriv = EddsaPrivateKey.create();
let reservePub = reservePriv.getPublicKey();
let form = new FormData();
let now = (new Date()).toString();
form.append(detail.field_amount, detail.amount_str);
form.append(detail.field_reserve_pub, reservePub.encode());
form.append(detail.field_mint, detail.mint);
// XXX: set bank-specified fields.
let myRequest = new XMLHttpRequest();
console.log("making request to " + detail.post_url);
myRequest.open('post', detail.post_url);
myRequest.send(form);
let mintBaseUrl = canonicalizeBaseUrl(detail.mint);
myRequest.addEventListener('readystatechange', (e) => {
if (myRequest.readyState == XMLHttpRequest.DONE) {
// TODO: extract as interface
let resp = {
status: myRequest.status,
text: myRequest.responseText,
success: undefined,
backlink: undefined
};
let reserveRecord = {
reserve_pub: reservePub.encode(),
reserve_priv: reservePriv.encode(),
mint_base_url: mintBaseUrl,
created: now,
last_query: null,
current_amount: null,
// XXX: set to actual amount
initial_amount: null
};
// XXX: insert into db.
switch (myRequest.status) {
case 200:
resp.success = true;
// We can't show the page directly, so
// we show some generic page from the wallet.
resp.backlink = chrome.extension.getURL("pages/reserve-success.html");
let tx = db.transaction(['reserves'], 'readwrite');
tx.objectStore('reserves').add(reserveRecord);
tx.addEventListener('complete', (e) => {
console.log('tx complete, pk was ' + reserveRecord.reserve_pub);
sendResponse(resp);
var mint;
updateMintFromUrl(db, reserveRecord.mint_base_url)
.then((m) => { mint = m; return updateReserve(db, reservePub, mint); })
.then((reserve) => depleteReserve(db, reserve, mint));
});
break;
default:
resp.success = false;
sendResponse(resp);
}
}
});
// Allow async response
return true;
}
function copy(o) {
return JSON.parse(JSON.stringify(o));
}
function rankDenom(o1: Amount, o2: Amount) {
return (-1) * o1.cmp(o2);
}
function withdraw(denom, reserve, mint) {
let wd = {
denom_pub: denom.denom_pub,
reserve_pub: reserve.reserve_pub,
};
let coinPub = EddsaPrivateKey.create();
// create RSA blinding key
// blind coin
// generate signature
}
/**
* Withdraw coins from a reserve until it is empty.
*/
function depleteReserve(db, reserve, mint) {
let denoms = copy(mint.keys.denoms);
let remaining = new Amount(reserve.current_amount);
denoms.sort(rankDenom);
for (let i = 0; i < 1000; i++) {
let found = false;
for (let d of denoms) {
let cost = new Amount();
cost.add(new Amount(d.value));
cost.add(new Amount(d.fee_withdraw));
if (remaining.cmp(cost) < 0) {
continue;
}
found = true;
remaining.sub(cost);
withdraw(d, reserve, mint);
}
if (!found) {
break;
}
}
}
function updateReserve(db, reservePub, mint) {
let reserve;
return new Promise((resolve, reject) => {
let tx = db.transaction(['reserves']);
tx.objectStore('reserves').get(reservePub).onsuccess = (e) => {
let reserve = e.target.result;
let reqUrl = URI("reserve/status").absoluteTo(mint.baseUrl);
reqUrl.query({'reserve_pub': reservePub});
let myRequest = new XMLHttpRequest();
console.log("making request to " + reqUrl.href());
myRequest.open('get', reqUrl.href());
myRequest.send();
myRequest.addEventListener('readystatechange', (e) => {
if (myRequest.readyState == XMLHttpRequest.DONE) {
if (myRequest.status != 200) {
reject();
return;
}
let reserveInfo = JSON.parse(myRequest.responseText);
console.log("got response " + JSON.stringify(reserveInfo));
reserve.current_amount = reserveInfo.balance;
let tx = db.transaction(['reserves'], 'readwrite');
console.log("putting updated reserve " + JSON.stringify(reserve));
tx.objectStore('reserves').put(reserve);
tx.oncomplete = (e) => {
resolve(reserve);
};
}
});
};
});
}
/**
* Update or add mint DB entry by fetching the /keys information.
* Optionally link the reserve entry to the new or existing
* mint entry in then DB.
*/
function updateMintFromUrl(db, baseUrl) {
console.log("base url is " + baseUrl);
let reqUrl = URI("keys").absoluteTo(baseUrl);
let myRequest = new XMLHttpRequest();
myRequest.open('get', reqUrl.href());
myRequest.send();
return new Promise((resolve, reject) => {
myRequest.addEventListener('readystatechange', (e) => {
console.log("state change to " + myRequest.readyState);
if (myRequest.readyState == XMLHttpRequest.DONE) {
if (myRequest.status == 200) {
console.log("got /keys");
let mintKeysJson = JSON.parse(myRequest.responseText);
if (!mintKeysJson) {
console.log("keys invalid");
reject();
} else {
let mint = {
baseUrl: baseUrl,
keys: mintKeysJson
};
let tx = db.transaction(['mints'], 'readwrite');
tx.objectStore('mints').put(mint);
tx.oncomplete = (e) => {
resolve(mint);
};
}
} else {
console.log("/keys request failed with status " + myRequest.status);
// XXX: also write last error to DB to show in the UI
reject();
}
}
});
});
}
function dumpDb(db, detail, sendResponse) {
let dump = {
name: db.name,
version: db.version,
stores: {}
};
console.log("stores: " + JSON.stringify(db.objectStoreNames));
let tx = db.transaction(db.objectStoreNames);
tx.addEventListener('complete', (e) => {
sendResponse(dump);
});
for (let i = 0; i < db.objectStoreNames.length; i++) {
let name = db.objectStoreNames[i];
let storeDump = {};
dump.stores[name] = storeDump;
let store = tx.objectStore(name).openCursor().addEventListener('success', (e) => {
let cursor = e.target.result;
if (cursor) {
storeDump[cursor.key] = cursor.value;
cursor.continue();
}
});
}
return true;
}
openTalerDb().then((db) => {
console.log("db loaded");
chrome.runtime.onMessage.addListener(
function (req, sender, onresponse) {
let dispatch = {
"confirm-reserve": confirmReserve,
"dump-db": dumpDb
}
return dispatch[req.type](db, req.detail, onresponse);
});
});

8231
extension/decl/chrome/chrome.d.ts vendored Executable file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,548 @@
// Type definitions for File System API
// Project: http://www.w3.org/TR/file-system-api/
// Definitions by: Kon <http://phyzkit.net/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../filewriter/filewriter.d.ts" />
interface LocalFileSystem {
/**
* Used for storage with no guarantee of persistence.
*/
TEMPORARY:number;
/**
* Used for storage that should not be removed by the user agent without application or user permission.
*/
PERSISTENT:number;
/**
* Requests a filesystem in which to store application data.
* @param type Whether the filesystem requested should be persistent, as defined above. Use one of TEMPORARY or PERSISTENT.
* @param size This is an indicator of how much storage space, in bytes, the application expects to need.
* @param successCallback The callback that is called when the user agent provides a filesystem.
* @param errorCallback A callback that is called when errors happen, or when the request to obtain the filesystem is denied.
*/
requestFileSystem(type:number, size:number, successCallback:FileSystemCallback, errorCallback?:ErrorCallback):void;
/**
* Allows the user to look up the Entry for a file or directory referred to by a local URL.
* @param url A URL referring to a local file in a filesystem accessable via this API.
* @param successCallback A callback that is called to report the Entry to which the supplied URL refers.
* @param errorCallback A callback that is called when errors happen, or when the request to obtain the Entry is denied.
*/
resolveLocalFileSystemURL(url:string, successCallback:EntryCallback, errorCallback?:ErrorCallback):void;
/**
* see requestFileSystem.
*/
webkitRequestFileSystem(type:number, size:number, successCallback:FileSystemCallback, errorCallback?:ErrorCallback):void;
}
interface LocalFileSystemSync {
/**
* Used for storage with no guarantee of persistence.
*/
TEMPORARY:number;
/**
* Used for storage that should not be removed by the user agent without application or user permission.
*/
PERSISTENT:number;
/**
* Requests a filesystem in which to store application data.
* @param type Whether the filesystem requested should be persistent, as defined above. Use one of TEMPORARY or PERSISTENT.
* @param size This is an indicator of how much storage space, in bytes, the application expects to need.
*/
requestFileSystemSync(type:number, size:number):FileSystemSync;
/**
* Allows the user to look up the Entry for a file or directory referred to by a local URL.
* @param url A URL referring to a local file in a filesystem accessable via this API.
*/
resolveLocalFileSystemSyncURL(url:string):EntrySync;
/**
* see requestFileSystemSync
*/
webkitRequestFileSystemSync(type:number, size:number):FileSystemSync;
}
interface Metadata {
/**
* This is the time at which the file or directory was last modified.
* @readonly
*/
modificationTime:Date;
/**
* The size of the file, in bytes. This must return 0 for directories.
* @readonly
*/
size:number;
}
interface Flags {
/**
* Used to indicate that the user wants to create a file or directory if it was not previously there.
*/
create?:boolean;
/**
* By itself, exclusive must have no effect. Used with create, it must cause getFile and getDirectory to fail if the target path already exists.
*/
exclusive?:boolean;
}
/**
* This interface represents a file system.
*/
interface FileSystem{
/**
* This is the name of the file system. The specifics of naming filesystems is unspecified, but a name must be unique across the list of exposed file systems.
* @readonly
*/
name: string;
/**
* The root directory of the file system.
* @readonly
*/
root: DirectoryEntry;
}
interface Entry {
/**
* Entry is a file.
*/
isFile:boolean;
/**
* Entry is a directory.
*/
isDirectory:boolean;
/**
* Look up metadata about this entry.
* @param successCallback A callback that is called with the time of the last modification.
* @param errorCallback ErrorCallback A callback that is called when errors happen.
*/
getMetadata(successCallback:MetadataCallback, errorCallback?:ErrorCallback):void;
/**
* The name of the entry, excluding the path leading to it.
*/
name:string;
/**
* The full absolute path from the root to the entry.
*/
fullPath:string;
/**
* The file system on which the entry resides.
*/
filesystem:FileSystem;
/**
* Move an entry to a different location on the file system. It is an error to try to:
*
* <ui>
* <li>move a directory inside itself or to any child at any depth;</li>
* <li>move an entry into its parent if a name different from its current one isn't provided;</li>
* <li>move a file to a path occupied by a directory;</li>
* <li>move a directory to a path occupied by a file;</li>
* <li>move any element to a path occupied by a directory which is not empty.</li>
* <ul>
*
* A move of a file on top of an existing file must attempt to delete and replace that file.
* A move of a directory on top of an existing empty directory must attempt to delete and replace that directory.
*/
moveTo(parent:DirectoryEntry, newName?:string, successCallback?:EntryCallback, errorCallback?:ErrorCallback):string;
/**
* Copy an entry to a different location on the file system. It is an error to try to:
*
* <ul>
* <li> copy a directory inside itself or to any child at any depth;</li>
* <li> copy an entry into its parent if a name different from its current one isn't provided;</li>
* <li> copy a file to a path occupied by a directory;</li>
* <li> copy a directory to a path occupied by a file;</li>
* <li> copy any element to a path occupied by a directory which is not empty.</li>
* <li> A copy of a file on top of an existing file must attempt to delete and replace that file.</li>
* <li> A copy of a directory on top of an existing empty directory must attempt to delete and replace that directory.</li>
* </ul>
*
* Directory copies are always recursive--that is, they copy all contents of the directory.
*/
copyTo(parent:DirectoryEntry, newName?:string, successCallback?:EntryCallback, errorCallback?:ErrorCallback):string;
/**
* Returns a URL that can be used to identify this entry. Unlike the URN defined in [FILE-API-ED], it has no specific expiration; as it describes a location on disk, it should be valid at least as long as that location exists.
*/
toURL():string;
/**
* Deletes a file or directory. It is an error to attempt to delete a directory that is not empty. It is an error to attempt to delete the root directory of a filesystem.
* @param successCallback A callback that is called on success.
* @param errorCallback A callback that is called when errors happen.
*/
remove(successCallback:VoidCallback, errorCallback?:ErrorCallback):void;
/**
* Look up the parent DirectoryEntry containing this Entry. If this Entry is the root of its filesystem, its parent is itself.
* @param successCallback A callback that is called to return the parent Entry.
* @param errorCallback A callback that is called when errors happen.
*/
getParent(successCallback:DirectoryEntryCallback, errorCallback?:ErrorCallback):void;
}
/**
* This interface represents a directory on a file system.
*/
interface DirectoryEntry extends Entry {
/**
* Creates a new DirectoryReader to read Entries from this Directory.
*/
createReader():DirectoryReader;
/**
* Creates or looks up a file.
* @param path Either an absolute path or a relative path from this DirectoryEntry to the file to be looked up or created. It is an error to attempt to create a file whose immediate parent does not yet exist.
* @param options
* <ul>
* <li>If create and exclusive are both true, and the path already exists, getFile must fail.</li>
* <li>If create is true, the path doesn't exist, and no other error occurs, getFile must create it as a zero-length file and return a corresponding FileEntry.</li>
* <li>If create is not true and the path doesn't exist, getFile must fail.</li>
* <li>If create is not true and the path exists, but is a directory, getFile must fail.</li>
* <li>Otherwise, if no other error occurs, getFile must return a FileEntry corresponding to path.</li>
* </ul>
* @param successCallback A callback that is called to return the File selected or created.
* @param errorCallback A callback that is called when errors happen.
*/
getFile(path:string, options?:Flags, successCallback?:FileEntryCallback, errorCallback?:ErrorCallback):void;
/**
* Creates or looks up a directory.
* @param path Either an absolute path or a relative path from this DirectoryEntry to the directory to be looked up or created. It is an error to attempt to create a directory whose immediate parent does not yet exist.
* @param options
* <ul>
* <li>If create and exclusive are both true and the path already exists, getDirectory must fail.</li>
* <li>If create is true, the path doesn't exist, and no other error occurs, getDirectory must create and return a corresponding DirectoryEntry.</li>
* <li>If create is not true and the path doesn't exist, getDirectory must fail.</li>
* <li>If create is not true and the path exists, but is a file, getDirectory must fail.</li>
* <li>Otherwise, if no other error occurs, getDirectory must return a DirectoryEntry corresponding to path.</li>
* </ul>
* @param successCallback A callback that is called to return the DirectoryEntry selected or created.
* @param errorCallback A callback that is called when errors happen.
*
*/
getDirectory(path:string, options?:Flags, successCallback?:DirectoryEntryCallback, errorCallback?:ErrorCallback):void;
/**
* Deletes a directory and all of its contents, if any. In the event of an error [e.g. trying to delete a directory that contains a file that cannot be removed], some of the contents of the directory may be deleted. It is an error to attempt to delete the root directory of a filesystem.
* @param successCallback A callback that is called on success.
* @param errorCallback A callback that is called when errors happen.
*/
removeRecursively(successCallback:VoidCallback, errorCallback?:ErrorCallback):void;
}
/**
* This interface lets a user list files and directories in a directory. If there are no additions to or deletions from a directory between the first and last call to readEntries, and no errors occur, then:
* <ul>
* <li> A series of calls to readEntries must return each entry in the directory exactly once.</li>
* <li> Once all entries have been returned, the next call to readEntries must produce an empty array.</li>
* <li> If not all entries have been returned, the array produced by readEntries must not be empty.</li>
* <li> The entries produced by readEntries must not include the directory itself ["."] or its parent [".."].</li>
* </ul>
*/
interface DirectoryReader {
/**
* Read the next block of entries from this directory.
* @param successCallback Called once per successful call to readEntries to deliver the next previously-unreported set of Entries in the associated Directory. If all Entries have already been returned from previous invocations of readEntries, successCallback must be called with a zero-length array as an argument.
* @param errorCallback A callback indicating that there was an error reading from the Directory.
*/
readEntries(successCallback:EntriesCallback, errorCallback?:ErrorCallback):void;
}
/**
* This interface represents a file on a file system.
*/
interface FileEntry extends Entry {
/**
* Creates a new FileWriter associated with the file that this FileEntry represents.
* @param successCallback A callback that is called with the new FileWriter.
* @param errorCallback A callback that is called when errors happen.
*/
createWriter(successCallback:FileWriterCallback, errorCallback?:ErrorCallback):void;
/**
* Returns a File that represents the current state of the file that this FileEntry represents.
* @param successCallback A callback that is called with the File.
* @param errorCallback A callback that is called when errors happen.
*/
file(successCallback:FileCallback, errorCallback?:ErrorCallback):void;
}
/**
* When requestFileSystem() succeeds, the following callback is made.
*/
interface FileSystemCallback {
/**
* @param filesystem The file systems to which the app is granted access.
*/
(filesystem:FileSystem):void;
}
/**
* This interface is the callback used to look up Entry objects.
*/
interface EntryCallback {
/**
* @param entry
*/
(entry:Entry):void;
}
/**
* This interface is the callback used to look up FileEntry objects.
*/
interface FileEntryCallback {
/**
* @param entry
*/
(entry:FileEntry):void;
}
/**
* This interface is the callback used to look up DirectoryEntry objects.
*/
interface DirectoryEntryCallback {
/**
* @param entry
*/
(entry:DirectoryEntry):void;
}
/**
* When readEntries() succeeds, the following callback is made.
*/
interface EntriesCallback {
(entries:Entry[]):void;
}
/**
* This interface is the callback used to look up file and directory metadata.
*/
interface MetadataCallback {
(metadata:Metadata):void;
}
/**
* This interface is the callback used to create a FileWriter.
*/
interface FileWriterCallback {
(fileWriter:FileWriter):void;
}
/**
* This interface is the callback used to obtain a File.
*/
interface FileCallback {
(file:File):void;
}
/**
* This interface is the generic callback used to indicate success of an asynchronous method.
*/
interface VoidCallback {
():void;
}
/**
* When an error occurs, the following callback is made.
*/
interface ErrorCallback {
(err:DOMError):void;
}
/**
* This interface represents a file system.
*/
interface FileSystemSync {
/**
* This is the name of the file system. The specifics of naming filesystems is unspecified, but a name must be unique across the list of exposed file systems.
*/
name:string;
/**
* root The root directory of the file system.
*/
root:DirectoryEntrySync;
}
/**
* An abstract interface representing entries in a file system, each of which may be a FileEntrySync or DirectoryEntrySync.
*/
interface EntrySync{
/**
* EntrySync is a file.
* @readonly
*/
isFile:boolean;
/**
* EntrySync is a directory.
* @readonly
*/
isDirectory:boolean;
/**
* Look up metadata about this entry.
*/
getMetadata():Metadata;
/**
* The name of the entry, excluding the path leading to it.
*/
name:string;
/**
* The full absolute path from the root to the entry.
*/
fullPath:string;
/**
* The file system on which the entry resides.
*/
filesystem:FileSystemSync;
/**
* Move an entry to a different location on the file system. It is an error to try to:
* <ul>
* <li> move a directory inside itself or to any child at any depth;</li>
* <li> move an entry into its parent if a name different from its current one isn't provided;</li>
* <li> move a file to a path occupied by a directory;</li>
* <li> move a directory to a path occupied by a file;</li>
* <li> move any element to a path occupied by a directory which is not empty.</li>
* </ui>
* A move of a file on top of an existing file must attempt to delete and replace that file. A move of a directory on top of an existing empty directory must attempt to delete and replace that directory.
* @param parent The directory to which to move the entry.
* @param newName The new name of the entry. Defaults to the EntrySync's current name if unspecified.
*/
moveTo(parent:DirectoryEntrySync, newName?:string):EntrySync;
/**
* Copy an entry to a different location on the file system. It is an error to try to:
* <ul>
* <li> copy a directory inside itself or to any child at any depth;</li>
* <li> copy an entry into its parent if a name different from its current one isn't provided;</li>
* <li> copy a file to a path occupied by a directory;</li>
* <li> copy a directory to a path occupied by a file;</li>
* <li> copy any element to a path occupied by a directory which is not empty.</li>
* </ui>
* A copy of a file on top of an existing file must attempt to delete and replace that file.
* A copy of a directory on top of an existing empty directory must attempt to delete and replace that directory.
* Directory copies are always recursive--that is, they copy all contents of the directory.
*/
copyTo(parent:DirectoryEntrySync, newName?:string):EntrySync;
/**
* Returns a URL that can be used to identify this entry. Unlike the URN defined in [FILE-API-ED], it has no specific expiration; as it describes a location on disk, it should be valid at least as long as that location exists.
*/
toURL():string;
/**
* Deletes a file or directory. It is an error to attempt to delete a directory that is not empty. It is an error to attempt to delete the root directory of a filesystem.
*/
remove ():void;
/**
* Look up the parent DirectoryEntrySync containing this Entry. If this EntrySync is the root of its filesystem, its parent is itself.
*/
getParent():DirectoryEntrySync;
}
/**
* This interface represents a directory on a file system.
*/
interface DirectoryEntrySync extends EntrySync {
/**
* Creates a new DirectoryReaderSync to read EntrySyncs from this DirectorySync.
*/
createReader():DirectoryReaderSync;
/**
* Creates or looks up a directory.
* @param path Either an absolute path or a relative path from this DirectoryEntrySync to the file to be looked up or created. It is an error to attempt to create a file whose immediate parent does not yet exist.
* @param options
* <ul>
* <li> If create and exclusive are both true and the path already exists, getFile must fail.</li>
* <li> If create is true, the path doesn't exist, and no other error occurs, getFile must create it as a zero-length file and return a corresponding FileEntry.</li>
* <li> If create is not true and the path doesn't exist, getFile must fail.</li>
* <li> If create is not true and the path exists, but is a directory, getFile must fail.</li>
* <li> Otherwise, if no other error occurs, getFile must return a FileEntrySync corresponding to path.</li>
* </ul>
*/
getFile(path:string, options?:Flags):FileEntrySync;
/**
* Creates or looks up a directory.
* @param path Either an absolute path or a relative path from this DirectoryEntrySync to the directory to be looked up or created. It is an error to attempt to create a directory whose immediate parent does not yet exist.
* @param options
* <ul>
* <li> If create and exclusive are both true and the path already exists, getDirectory must fail.</li>
* <li> If create is true, the path doesn't exist, and no other error occurs, getDirectory must create and return a corresponding DirectoryEntry.</li>
* <li> If create is not true and the path doesn't exist, getDirectory must fail.</li>
* <li> If create is not true and the path exists, but is a file, getDirectory must fail.</li>
* <li> Otherwise, if no other error occurs, getDirectory must return a DirectoryEntrySync corresponding to path.</li>
* </ul>
*/
getDirectory(path:string, options?:Flags):DirectoryEntrySync;
/**
* Deletes a directory and all of its contents, if any. In the event of an error [e.g. trying to delete a directory that contains a file that cannot be removed], some of the contents of the directory may be deleted. It is an error to attempt to delete the root directory of a filesystem.
*/
removeRecursively():void;
}
/**
* This interface lets a user list files and directories in a directory. If there are no additions to or deletions from a directory between the first and last call to readEntries, and no errors occur, then:
* <ul>
* <li> A series of calls to readEntries must return each entry in the directory exactly once.</li>
* <li> Once all entries have been returned, the next call to readEntries must produce an empty array.</li>
* <li> If not all entries have been returned, the array produced by readEntries must not be empty.</li>
* <li> The entries produced by readEntries must not include the directory itself ["."] or its parent [".."].</li>
* </ul>
*/
interface DirectoryReaderSync {
/**
* Read the next block of entries from this directory.
*/
readEntries():EntrySync[];
}
/**
* This interface represents a file on a file system.
*/
interface FileEntrySync extends EntrySync {
/**
* Creates a new FileWriterSync associated with the file that this FileEntrySync represents.
*/
createWriter():FileWriterSync;
/**
* Returns a File that represents the current state of the file that this FileEntrySync represents.
*/
file():File;
}
interface Window extends LocalFileSystem, LocalFileSystemSync{
}
interface WorkerGlobalScope extends LocalFileSystem, LocalFileSystemSync{
}

View File

@ -0,0 +1,176 @@
// Type definitions for File API: Writer
// Project: http://www.w3.org/TR/file-writer-api/
// Definitions by: Kon <http://phyzkit.net/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/**
* This interface provides methods to monitor the asynchronous writing of blobs to disk using progress events [PROGRESS-EVENTS] and event handler attributes.
* This interface is specified to be used within the context of the global object (Window [HTML5]) and within Web Workers (WorkerUtils [WEBWORKERS-ED]).
*/
interface FileSaver extends EventTarget {
/**
* When the abort method is called, user agents must run the steps below:
* <ol>
* <li> If readyState == DONE or readyState == INIT, terminate this overall series of steps without doing anything else. </li>
* <li> Set readyState to DONE. </li>
* <li> If there are any tasks from the object's FileSaver task source in one of the task queues, then remove those tasks. </li>
* <li> Terminate the write algorithm being processed. </li>
* <li> Set the error attribute to a DOMError object of type "AbortError". </li>
* <li> Fire a progress event called abort </li>
* <li> Fire a progress event called writeend </li>
* <li> Terminate this algorithm. </li>
* </ol>
*/
abort():void;
/**
* The blob is being written.
* @readonly
*/
INIT:number;
/**
* The object has been constructed, but there is no pending write.
* @readonly
*/
WRITING:number;
/**
* The entire Blob has been written to the file, an error occurred during the write, or the write was aborted using abort(). The FileSaver is no longer writing the blob.
* @readonly
*/
DONE:number;
/**
* The FileSaver object can be in one of 3 states. The readyState attribute, on getting, must return the current state, which must be one of the following values:
* <ul>
* <li>INIT</li>
* <li>WRITING</li>
* <li>DONE</li>
* <ul>
* @readonly
*/
readyState:number;
/**
* The last error that occurred on the FileSaver.
* @readonly
*/
error:DOMError;
/**
* Handler for writestart events
*/
onwritestart:Function;
/**
* Handler for progress events.
*/
onprogress:Function;
/**
* Handler for write events.
*/
onwrite:Function;
/**
* Handler for abort events.
*/
onabort:Function;
/**
* Handler for error events.
*/
onerror:Function;
/**
* Handler for writeend events.
*/
onwriteend:Function;
}
declare var FileSaver: {
/**
* When the FileSaver constructor is called, the user agent must return a new FileSaver object with readyState set to INIT.
* This constructor must be visible when the script's global object is either a Window object or an object implementing the WorkerUtils interface.
*/
new(data:Blob): FileSaver;
}
/**
* This interface expands on the FileSaver interface to allow for multiple write actions, rather than just saving a single Blob.
*/
interface FileWriter extends FileSaver {
/**
* The byte offset at which the next write to the file will occur. This must be no greater than length.
* A newly-created FileWriter must have position set to 0.
*/
position:number;
/**
* The length of the file. If the user does not have read access to the file, this must be the highest byte offset at which the user has written.
*/
length:number;
/**
* Write the supplied data to the file at position.
* @param data The blob to write.
*/
write(data:Blob):void;
/**
* Seek sets the file position at which the next write will occur.
* @param offset If nonnegative, an absolute byte offset into the file. If negative, an offset back from the end of the file.
*/
seek(offset:number):void;
/**
* Changes the length of the file to that specified. If shortening the file, data beyond the new length must be discarded. If extending the file, the existing data must be zero-padded up to the new length.
* @param size The size to which the length of the file is to be adjusted, measured in bytes.
*/
truncate(size:number):void;
}
/**
* This interface lets users write, truncate, and append to files using simple synchronous calls.
* This interface is specified to be used only within Web Workers (WorkerUtils [WEBWORKERS]).
*/
interface FileWriterSync {
/**
* The byte offset at which the next write to the file will occur. This must be no greater than length.
*/
position:number;
/**
* The length of the file. If the user does not have read access to the file, this must be the highest byte offset at which the user has written.
*/
length:number;
/**
* Write the supplied data to the file at position. Upon completion, position will increase by data.size.
* @param data The blob to write.
*/
write(data:Blob):void;
/**
* Seek sets the file position at which the next write will occur.
* @param offset An absolute byte offset into the file. If offset is greater than length, length is used instead. If offset is less than zero, length is added to it, so that it is treated as an offset back from the end of the file. If it is still less than zero, zero is used.
*/
seek(offset:number):void;
/**
* Changes the length of the file to that specified. If shortening the file, data beyond the new length must be discarded. If extending the file, the existing data must be zero-padded up to the new length.
* Upon successful completion:
* <ul>
* <li>length must be equal to size.</li>
* <li>position must be the lesser of
* <ul>
* <li>its pre-truncate value,</li>
* <li>size.</li>
* </ul>
* </li>
* </ul>
* @param size The size to which the length of the file is to be adjusted, measured in bytes.
*/
truncate(size:number):void;
}

3190
extension/decl/jquery/jquery.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

236
extension/decl/urijs/URIjs.d.ts vendored Normal file
View File

@ -0,0 +1,236 @@
// Type definitions for URI.js 1.15.1
// Project: https://github.com/medialize/URI.js
// Definitions by: RodneyJT <https://github.com/RodneyJT>, Brian Surowiec <https://github.com/xt0rted>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
declare module uri {
interface URI {
absoluteTo(path: string): URI;
absoluteTo(path: URI): URI;
addFragment(fragment: string): URI;
addQuery(qry: string): URI;
addQuery(qry: Object): URI;
addSearch(qry: string): URI;
addSearch(key: string, value:any): URI;
addSearch(qry: Object): URI;
authority(): string;
authority(authority: string): URI;
clone(): URI;
directory(): string;
directory(dir: boolean): string;
directory(dir: string): URI;
domain(): string;
domain(domain: boolean): string;
domain(domain: string): URI;
duplicateQueryParameters(val: boolean): URI;
equals(): boolean;
equals(url: string): boolean;
filename(): string;
filename(file: boolean): string;
filename(file: string): URI;
fragment(): string;
fragment(fragment: string): URI;
fragmentPrefix(prefix: string): URI;
hash(): string;
hash(hash: string): URI;
host(): string;
host(host: string): URI;
hostname(): string;
hostname(hostname: string): URI;
href(): string;
href(url: string): void;
is(qry: string): boolean;
iso8859(): URI;
normalize(): URI;
normalizeFragment(): URI;
normalizeHash(): URI;
normalizeHostname(): URI;
normalizePath(): URI;
normalizePathname(): URI;
normalizePort(): URI;
normalizeProtocol(): URI;
normalizeQuery(): URI;
normalizeSearch(): URI;
password(): string;
password(pw: string): URI;
path(): string;
path(path: boolean): string;
path(path: string): URI;
pathname(): string;
pathname(path: boolean): string;
pathname(path: string): URI;
port(): string;
port(port: string): URI;
protocol(): string;
protocol(protocol: string): URI;
query(): string;
query(qry: string): URI;
query(qry: boolean): Object;
query(qry: Object): URI;
readable(): string;
relativeTo(path: string): URI;
removeQuery(qry: string): URI;
removeQuery(qry: Object): URI;
removeSearch(qry: string): URI;
removeSearch(qry: Object): URI;
resource(): string;
resource(resource: string): URI;
scheme(): string;
scheme(protocol: string): URI;
search(): string;
search(qry: string): URI;
search(qry: boolean): any;
search(qry: Object): URI;
segment(): string[];
segment(segments: string[]): URI;
segment(position: number): string;
segment(position: number, level: string): URI;
segment(segment: string): URI;
setQuery(key: string, value: string): URI;
setQuery(qry: Object): URI;
setSearch(key: string, value: string): URI;
setSearch(qry: Object): URI;
subdomain(): string;
subdomain(subdomain: string): URI;
suffix(): string;
suffix(suffix: boolean): string;
suffix(suffix: string): URI;
tld(): string;
tld(tld: boolean): string;
tld(tld: string): URI;
unicode(): URI;
userinfo(): string;
userinfo(userinfo: string): URI;
username(): string;
username(uname: string): URI;
valueOf(): string;
}
interface URIOptions {
protocol?: string;
username?: string;
password?: string;
hostname?: string;
port?: string;
path?: string;
query?: string;
fragment?: string;
}
interface URIStatic {
(): URI;
(value: string | URIOptions | HTMLElement): URI;
new (): URI;
new (value: string | URIOptions | HTMLElement): URI;
addQuery(data: Object, prop: string, value: string): Object;
addQuery(data: Object, qryObj: Object): Object;
build(parts: {
protocol: string;
username: string;
password: string;
hostname: string;
port: string;
path: string;
query: string;
fragment: string;
}): string;
buildAuthority(parts: {
username?: string;
password?: string;
hostname?: string;
port?: string;
}): string;
buildHost(parts: {
hostname?: string;
port?: string;
}): string;
buildQuery(qry: Object): string;
buildQuery(qry: Object, duplicates: boolean): string;
buildUserinfo(parts: {
username?: string;
password?: string;
}): string;
commonPath(path1: string, path2: string): string;
decode(str: string): string;
decodeQuery(qry: string): string;
encode(str: string): string;
encodeQuery(qry: string): string;
encodeReserved(str: string): string;
expand(template: string, vals: Object): URI;
iso8859(): void;
parse(url: string): {
protocol: string;
username: string;
password: string;
hostname: string;
port: string;
path: string;
query: string;
fragment: string;
};
parseAuthority(url: string, parts: {
username?: string;
password?: string;
hostname?: string;
port?: string;
}): string;
parseHost(url: string, parts: {
hostname?: string;
port?: string;
}): string;
parseQuery(url: string): Object;
parseUserinfo(url: string, parts: {
username?: string;
password?: string;
}): string;
removeQuery(data: Object, prop: string, value: string): Object;
removeQuery(data: Object, props: string[]): Object;
removeQuery(data: Object, props: Object): Object;
unicode(): void;
withinString(source: string, func: (url: string) => string): string;
}
}
interface JQuery {
uri(): uri.URI;
}
declare var URI: uri.URIStatic;
declare module 'URI' {
export = URI;
}
declare module 'urijs' {
export = URI;
}

199
extension/decl/webrtc/MediaStream.d.ts vendored Normal file
View File

@ -0,0 +1,199 @@
// Type definitions for WebRTC
// Project: http://dev.w3.org/2011/webrtc/
// Definitions by: Ken Smith <https://github.com/smithkl42/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Taken from http://dev.w3.org/2011/webrtc/editor/getusermedia.html
// version: W3C Editor's Draft 29 June 2015
interface ConstrainBooleanParameters {
exact?: boolean;
ideal?: boolean;
}
interface NumberRange {
max?: number;
min?: number;
}
interface ConstrainNumberRange extends NumberRange {
exact?: number;
ideal?: number;
}
interface ConstrainStringParameters {
exact?: string | string[];
ideal?: string | string[];
}
interface MediaStreamConstraints {
video?: boolean | MediaTrackConstraints;
audio?: boolean | MediaTrackConstraints;
}
declare module W3C {
type LongRange = NumberRange;
type DoubleRange = NumberRange;
type ConstrainBoolean = boolean | ConstrainBooleanParameters;
type ConstrainNumber = number | ConstrainNumberRange;
type ConstrainLong = ConstrainNumber;
type ConstrainDouble = ConstrainNumber;
type ConstrainString = string | string[] | ConstrainStringParameters;
}
interface MediaTrackConstraints extends MediaTrackConstraintSet {
advanced?: MediaTrackConstraintSet[];
}
interface MediaTrackConstraintSet {
width?: W3C.ConstrainLong;
height?: W3C.ConstrainLong;
aspectRatio?: W3C.ConstrainDouble;
frameRate?: W3C.ConstrainDouble;
facingMode?: W3C.ConstrainString;
volume?: W3C.ConstrainDouble;
sampleRate?: W3C.ConstrainLong;
sampleSize?: W3C.ConstrainLong;
echoCancellation?: W3C.ConstrainBoolean;
latency?: W3C.ConstrainDouble;
deviceId?: W3C.ConstrainString;
groupId?: W3C.ConstrainString;
}
interface MediaTrackSupportedConstraints {
width?: boolean;
height?: boolean;
aspectRatio?: boolean;
frameRate?: boolean;
facingMode?: boolean;
volume?: boolean;
sampleRate?: boolean;
sampleSize?: boolean;
echoCancellation?: boolean;
latency?: boolean;
deviceId?: boolean;
groupId?: boolean;
}
interface MediaStream extends EventTarget {
id: string;
active: boolean;
onactive: EventListener;
oninactive: EventListener;
onaddtrack: (event: MediaStreamTrackEvent) => any;
onremovetrack: (event: MediaStreamTrackEvent) => any;
clone(): MediaStream;
stop(): void;
getAudioTracks(): MediaStreamTrack[];
getVideoTracks(): MediaStreamTrack[];
getTracks(): MediaStreamTrack[];
getTrackById(trackId: string): MediaStreamTrack;
addTrack(track: MediaStreamTrack): void;
removeTrack(track: MediaStreamTrack): void;
}
interface MediaStreamTrackEvent extends Event {
track: MediaStreamTrack;
}
declare enum MediaStreamTrackState {
"live",
"ended"
}
interface MediaStreamTrack extends EventTarget {
id: string;
kind: string;
label: string;
enabled: boolean;
muted: boolean;
remote: boolean;
readyState: MediaStreamTrackState;
onmute: EventListener;
onunmute: EventListener;
onended: EventListener;
onoverconstrained: EventListener;
clone(): MediaStreamTrack;
stop(): void;
getCapabilities(): MediaTrackCapabilities;
getConstraints(): MediaTrackConstraints;
getSettings(): MediaTrackSettings;
applyConstraints(constraints: MediaTrackConstraints): Promise<void>;
}
interface MediaTrackCapabilities {
width: number | W3C.LongRange;
height: number | W3C.LongRange;
aspectRatio: number | W3C.DoubleRange;
frameRate: number | W3C.DoubleRange;
facingMode: string;
volume: number | W3C.DoubleRange;
sampleRate: number | W3C.LongRange;
sampleSize: number | W3C.LongRange;
echoCancellation: boolean[];
latency: number | W3C.DoubleRange;
deviceId: string;
groupId: string;
}
interface MediaTrackSettings {
width: number;
height: number;
aspectRatio: number;
frameRate: number;
facingMode: string;
volume: number;
sampleRate: number;
sampleSize: number;
echoCancellation: boolean;
latency: number;
deviceId: string;
groupId: string;
}
interface MediaStreamError {
name: string;
message: string;
constraintName: string;
}
interface NavigatorGetUserMedia {
(constraints: MediaStreamConstraints,
successCallback: (stream: MediaStream) => void,
errorCallback: (error: MediaStreamError) => void): void;
}
interface Navigator {
getUserMedia: NavigatorGetUserMedia;
webkitGetUserMedia: NavigatorGetUserMedia;
mozGetUserMedia: NavigatorGetUserMedia;
msGetUserMedia: NavigatorGetUserMedia;
mediaDevices: MediaDevices;
}
interface MediaDevices {
getSupportedConstraints(): MediaTrackSupportedConstraints;
getUserMedia(constraints: MediaStreamConstraints): Promise<MediaStream>;
enumerateDevices(): Promise<MediaDeviceInfo[]>;
}
interface MediaDeviceInfo {
label: string;
id: string;
kind: string;
facing: string;
}

9
extension/tsconfig.json Normal file
View File

@ -0,0 +1,9 @@
{
"compilerOptions": {
"target": "es6"
},
"files": [
"background/wallet.ts",
"background/emscriptif.ts"
]
}