diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..10f4d43 Binary files /dev/null and b/.DS_Store differ diff --git a/.gitmodules b/.gitmodules index 451e301..423b24c 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,4 @@ -[submodule "Type-R"] - path = Type-R +[submodule "submodules/Type-R"] + path = submodules/Type-R url = https://github.com/Volicon/Type-R.git + branch = master diff --git a/README.md b/README.md index 653bbb9..aa8a71c 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,341 @@ -# NestedTypes model framework +NestedTypes 2.0 is BackboneJS compatibility layer for the [Type-R](https://volicon.github.io/Type-R/Getting_Started.html) data framework. Type-R is Model/Collection core written from the scratch with the TypeScript and has no side dependencies. -Version 2.0 RC is here. Rewritten from the scratch with TypeScript, based on new `Type-R` observing serializer core. +NestedTypes adds support for REST (standard BackboneJS API), Underscore methods, and Backbone 1.1 classes. + +> If you're upgrading from the version 1.3, *[there are compatibility issues](/docs/compatibility.md)*. +> Mostly due to the fact that the Type-R and NestedTypes 2.0 is built around the concept of [aggregation trees](https://volicon.github.io/Type-R/API_by_feature/Aggregation_tree.html). +> NestedTypes 1.3 code won't work without refactoring. + +# Important Notice + +Staring with v2.0 Type-R includes generic I/O abstraction which is far superior to the legacy BackboneJS I/O. +NestedTypes & NestedReact will be maintained as the BackboneJS compatibility layer as long as Verizon/Volicon systems have legacy Backbone code. Therefore: + +- NestedTypes docs won't be updated. Use [Type-R](https://volicon.github.io/Type-R) documentation as you primary source of documentation. +- Functional-wise, there's no reason to prefer NestedTypes over the Type-R any more. If you don't need BackboneJS backward compatibility, move to the [Type-R](https://volicon.github.io/Type-R) which doesn't have any legacy dependencies like jQuery and underscore. + +# Features + +Post-backbone data framework. 10 times faster, first-class support for nested models and collections and relations by id. - ES6 classes support. -- 2-4 times faster than version 1.3 in all browsers (huge performance gain for IE11). -- Strict ownerhip policy. - -## TODO - -- [x] Underscore tests passes. -- [x] REST IO test passes. -- [x] NestedReact works with 2.0 on given examples. -- [x] Created NestedReact 1.0 alpha build with all ES6 features promised. -- [x] Alphas are deployed to Volicon Observer. -- [x] Volicon Observer works! -- [ ] 1.3 -> 2.0 Migration Guide -- [ ] 2.0 New Features Guide -- [ ] Updated API docs \ No newline at end of file +- Deeply observable changes. +- First-class support for [aggregation](https://volicon.github.io/Type-R/API_by_feature/Aggregation_tree.html) and [relations by id](https://volicon.github.io/Type-R/API_by_feature/id-references_and_Stores.html). +- Attribute type annotations and dynamic type safety. +- More than 10 times faster than BackboneJS and 2-4 times faster than NestedTypes 1.3 in all browsers. + +# Installation & Requirements + +All modern JS engines are supported (IE10+, Safari, Firefox, Edge, Chrome, nodejs). May work in IE9 but not tested. + +`npm install nestedtypes` + +`underscore` and `jquery` are hard dependencies. + +For lighter framework version without dependencies and Backbone compatibility shim check out [Type-R](https://github.com/Volicon/Type-R). + +# Quick API Reference + +Central concept in NestedTypes is `Record` type, which is the JS class with following capabilities: + +- Class members are deeply observable. +- It is serializable to JSON by default. +- Class members are typed and their changes are guardered with run-time type checks. + +`Model` is the `Record` subclass representing REST API endpoint. Models, records, and their collections +are used as building blocks to describe both application's UI state and its data layer. + +`Record` definition looks like normal ES6 class definition, but it's mandatory to declare +attributes. It looks like this: + +```javascript +import { define, Record } from 'nestedtypes' + +@define // <- decorator to perform class transformation +class User extends Model { + urlRoot : '/api/users', + + static attributes = { // <- attributes declaration + name : '', // <- can be either default value + email : String, // <- or any JS type constructor + isActive : true, + lastLogin : Date.value( null ) // <- or both + } +} + +const user = new User({ id : 5 }); // <- constructor takes optional attributes hash as an argument +user.fetch().done( () => { // GET /api/users/5 + user.name = 'John'; + user.save(); // PUT /api/users/5 +}); +``` + +## Record's Attributes Type Annotations Basics + +All record's attributes must be declared with `static attributes = { [ attrName ] : TypeAnnotation }` member. +Type annotation can be one of the following: + +- `attrName : Constructor`. Such as `attrName : Date`. +- `attrName : Constructor.value( defaultValue )`. Such as `lastLogin : Date.value( null )`. +- `attrName : defaultValue`. In this case, attribute type will be inferred from the value, so `isActive : true` has the same effect as `isActive : Boolean.value( true )`. + +Record attributes can be accessed directly, like `user.name = x`. When attribute is assigned, the type of the the value is +checked and being converted to the declared type with its constructor invocation if it's necessary. + +For the assignments like `user.isActive = x`, where `isActive` is declared as `Boolean` + +- it is assigned as is if `x` is `null` or boolean. +- for primitive types, it's converted with plain constructor invokation like `Boolean( x )`. +- For non-primitives convertion will invoke constructor with `new`, like `new Date( x )`. + +If it's impossible to convert the value it may be assigned with `NaN` or `Invalid Date` (or depending on the type update will be rejected), +and there will be an error in the console. + +Therefore, *it's guaranteed* that Record attributes always have declared type. + +## Collections + +Every model has corresponding `Collection` type declared implicitly. Collections +implements [Backbone Collection API](http://backbonejs.org/#Collection). + +```javascript +var users = new User.Collection(); + +users.fetch().done( () => { + console.log( users.length ); +}); +``` + +When Record is extended, its collection is extended too. The creation of implicit Colleciton type is equivalent to this: + +```javascript +@define +class Users extends Record.Collection {} + +@define +class User extends Record { + static Collection = Users; + // ... +} +``` + +You can use this pattern when you need to add custom members to the record's collection. + +## Nested Records and Collections + +Nested records and collections are declared with mentioning constructor in attribute type annotation. +All changes in nested objects are deeply observable; any change in children will cause change events in a parent. + +Records and collections emiting the [standard set of Backbone events](http://backbonejs.org/#Events-catalog), with following differences: + +- Collections does not bubble `change:[attribute]` event from the model by default (`change` event is bubbled); + event bubbling needs to be enabled for every particular event with `static itemEvents = { 'change:attr1' : true, ... }` declaration. +- Collections have `changes` event which is semantically similar to the model's `change`. + +### Transactions + +Record's `change` event (and collection's `changes` event) are _transactional_. Whatever some changes +are made as the reaction on any of change event, it won't cause additional `change` event for the owner. + +Also, you can explicitly group the sequence of changes to the single transaction: + +```javascript + some.record.transaction( record => { + record.a = 1; + record.b = 2; + ... + }); // some.record will emit single 'change' event if there was any changes. + + // Execute collection.each in the scope of transaction. + todoCollection.updateEach( item => item.done = true ); // One 'changes' event will be emitted. +``` + +### Aggregation + +Record can aggregate other records and collections in its attributes. + +```javascript +@define +class Team extends Record { + static attributes = { + members : User.Collection + leader : User + } +} + +const team = new Team(); +team.members.add( new User({ name : 'John' }) ); +``` + +Aggregated members are: + +- serialized as nested JSON. +- following operations recursively when the operation happens to its owner. + +Aggregated members forms the tree of exclusive ownership. The same record or collection instance cannot be aggregated in two places at the same time, +and this rule is checked and enforced. + +### Shared nested objects + +Records may have nested members which belongs to different ownership trees. +Special type annotations are required to mark attribute as shared. + +- `RecordType.shared` or `CollectionType.shared`. Reference to collection or record which may be aggregated somewhere else. `null` by default. +- `CollectionType.Refs` constructor. Collection of records which may be aggregated somewhere else. Defaults to empty collection. + +`CollectionType.Refs` is an equivalent to `CollectionType.shared.value( [] )` when used as attribute type annotation. + +Shared types are: + +- not a part of record's ownership tree. +- not serialized. +- Not a subject of recursive operations. They are empty by default, not cloned, not validated, and not disposed when the corresponding operation applied to the parent. + +In all other aspects, they are indistinguishable from aggregated records and collections. + +```javascript +@define +class Team extends Record { + static attributes = { + members : User.Collection.Refs + leader : User.shared + } +} +``` + +### Relationship by `id` + +It's possible to create serializable reference to the shared object which is represented in JSON as a record's id (or array of ids). +Special type annotation is required to point out the master collection which will be used to resolve ids to the records. + +- `RecordType.from( masterCollection )` represents an id reference to the model. +- `CollectionType.subsetOf( masterCollection )` represents the collection of models id references. + +id-reference types behaves as shared types, but: + +- they are serializable as an object id (or array of ids for collections). +- they are not observable (internal changes do not trigger change events on the record). + +`masterCollection` reference may be either: + +- direct reference to the globally available collection. +- function returning the reference to the collection. +- string, which is the *symbolic reference* to collection (dot-separated path to the collection taken relative to the record's `this`). + +```javascript +class Team extends Record { + static attributes = { + members : User.Collection, + leader : User.from( 'members' ) // <- leader is serializable reference to the record from members collection. + } +} +``` + +#### Owner-references + +`^` symbol in symbolic reference represents `getOwner()` call and returns the record owner. +Collections are skipped. + +Following example expects that `Team` record will be aggregated (alone or in a collection) together +with `users` collection. + +```javascript +class Team extends Record { + static attributes = { + members : User.Collection.subsetOf( '^users' ), + leader : User.from( 'members' ) + } +} +``` + +#### Tilda-References and Stores + +Symbolic reference staring with `~` is resolved relative to the record called _store_, +which is located with `record.getStore()` method. +For instance, reference `~users` will be resolved as `this.getStore().users`. + +`getStore()` uses following store location algorithm: + +1. It traverse an ownership tree upwards and return the first `Store` model it has found. +2. If none of the record's owners is the Store, it returns global store from `Nested.store`. + +`Store` is the subclass of the `Record` and behaves as a regular Record. +Therefore, resolution of id references depends on the context and you may have as many stores as you like. + +Following example expects that there's `users` collection in some upper record which is inherited from Store, +or (if there are none) in the global store: + +```javascript +class Team extends Record { + static attributes = { + members : User.Collection.subsetOf( '~users' ), + leader : User.from( 'members' ) + } +} +``` + +## Attribute has-annotations + +It's possible to control different aspects of record's attribute behavior through additional metadata. +All of them starts with a keyword `.has` added to the constructor type. + +Object describing an attribute is called *metatype*. Operations on metatypes are immutable (returns new metatype), +and can be chained. + +```javascript +// Declare Month metatype. +const Month = Number.value( 1 ).has.check( x => x > 0 && x <= 12 ); +``` + +#### attribute : Type.has.toJSON( false | ( x, name ) => json ) + +Override default serializer for the attribute. `false` option will exclude attribute from serialization. + +#### attribute : Type.has.parse( ( json, name ) => data ) + +Override default JSON parser for the attribute. + +#### attribute : Type.has.get( ( value, name ) => value ) + +Get hook which may transform attribute value on read. Get hooks can be chained. + +#### attribute : Type.has.set( ( value, name ) => value ) + +Set hook which may transform attribute value before it's assigned. Set hooks can be chained. + +#### attribute : RecordOrCollectionType.has.changeEvents( false ) + +When nested attribute is changed, don't mark the owner as changed. + +#### attribute : Type.has.events({ [ event ] : handler | handlerName }) + +Listen to the specified events from the attribute. handler can be either function or +the name of the record's method. + +#### attribute : Type.has.check( x => boolean, errorMsg? : any ) + +Attach check to the attribute. Checks can be chained. Attribute is valid whenever check function returns truthy value. + +errorMessage is optional. + +#### attribute : Type.isRequired + +Similar to `Type.has.check( x => x, 'Required' )`. + +## Validation + +Validation is performed recursively on ownership tree. Record and collection shares the same validation API. + +#### record.validate() + +Override it to add custom record-level validation. Method shoudl return truthy value in case of validation error. + +For attribute level checks see `Type.has.check` annotation. + +#### record.isValid() : boolean + +Checks whenever record is valid. + +#### record.validationError + +Return validation error object or null if there are no errors. diff --git a/Type-R b/Type-R deleted file mode 160000 index 67c0b7c..0000000 --- a/Type-R +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 67c0b7ca39b9ff86d7089f325450e0d56a1f194f diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 0000000..9146234 --- /dev/null +++ b/dist/index.js @@ -0,0 +1,2 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("underscore"),require("jquery")):"function"==typeof define&&define.amd?define(["exports","underscore","jquery"],e):e(t.Nested={},t._,t.$)}(this,function(s,f,t){"use strict";var r=function(t,e){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function a(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var u=function(){return(u=Object.assign||function(t){for(var e,n=1,r=arguments.length;n").attr(t);this.setElement(e,!1)}}});var or=/\((.*?)\)/g,sr=/(\(\?)?:\w+/g,ar=/\*\w+/g,ur=/[\-{}\[\]+?.,\\\^$|#\s]/g;function cr(){this.handlers=[],this.checkUrl=f.bind(this.checkUrl,this),"undefined"!=typeof window&&(this.location=window.location,this.history=window.history)}f.extend(ir.prototype,{initialize:function(){},route:function(n,r,i){f.isRegExp(n)||(n=this._routeToRegExp(n)),f.isFunction(r)&&(i=r,r=""),i||(i=this[r]);var o=this;return tr.history.route(n,function(t){var e=o._extractParameters(n,t);!1!==o.execute(i,e,r)&&(o.trigger.apply(o,["route:"+r].concat(e)),o.trigger("route",r,e),tr.history.trigger("route",o,r,e))}),this},execute:function(t,e,n){t&&t.apply(this,e)},navigate:function(t,e){return tr.history.navigate(t,e),this},_bindRoutes:function(){if(this.routes){this.routes=f.result(this,"routes");for(var t,e=f.keys(this.routes);null!=(t=e.pop());)this.route(t,this.routes[t])}},_routeToRegExp:function(t){return t=t.replace(ur,"\\$&").replace(or,"(?:$1)?").replace(sr,function(t,e){return e?t:"([^/?]+)"}).replace(ar,"([^?]*?)"),new RegExp("^"+t+"(?:\\?([\\s\\S]*))?$")},_extractParameters:function(t,e){var n=t.exec(e).slice(1);return f.map(n,function(t,e){return e===n.length-1?t||null:t?decodeURIComponent(t):null})}});var hr=/^[#\/]|\s+$/g,lr=/^\/+|\/+$/g,pr=/#.*$/;cr.started=!1,f.extend(cr.prototype,{interval:50,atRoot:function(){return this.location.pathname.replace(/[^\/]$/,"$&/")===this.root&&!this.getSearch()},matchRoot:function(){return this.decodeFragment(this.location.pathname).slice(0,this.root.length-1)+"/"===this.root},decodeFragment:function(t){return decodeURI(t.replace(/%25/g,"%2525"))},getSearch:function(){var t=this.location.href.replace(/#.*/,"").match(/\?.+/);return t?t[0]:""},getHash:function(t){var e=(t||this).location.href.match(/#(.*)$/);return e?e[1]:""},getPath:function(){var t=this.decodeFragment(this.location.pathname+this.getSearch()).slice(this.root.length-1);return"/"===t.charAt(0)?t.slice(1):t},getFragment:function(t){return null==t&&(t=this._usePushState||!this._wantsHashChange?this.getPath():this.getHash()),t.replace(hr,"")},start:function(t){if(cr.started)throw new Error("Backbone.history has already been started");if(cr.started=!0,this.options=f.extend({root:"/"},this.options,t),this.root=this.options.root,this._wantsHashChange=!1!==this.options.hashChange,this._hasHashChange="onhashchange"in window&&(void 0===document.documentMode||7= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\r\n if (m) return m.call(o);\r\n return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n","/**\n * Simple overridable logging stubs, writing to `console` by default.\n * Node.js users might want to redirect logging somewhere.\n * \n * This is the singleton avaliable globally through `Object.log` or \n * exported [[log]] variable.\n */\n\n /** Similar to underscore `_.defaults` */\nexport function defaults< T >( dest : T, ...sources : Object[] ) : T\nexport function defaults< T >( dest : T, source : Object ) : T {\n for( var name in source ) {\n if( source.hasOwnProperty( name ) && !dest.hasOwnProperty( name ) ) {\n dest[ name ] = source[ name ];\n }\n }\n\n if( arguments.length > 2 ){\n for( let i = 2; i < arguments.length; i++ ){\n const other = arguments[ i ];\n other && defaults( dest, other );\n }\n }\n\n return dest;\n}\n\n// Logger is the function.\nexport type Logger = ( level : LogLevel, error : string, props? : object ) => void;\n\nexport type LogLevel = 'none' | 'error' | 'warn' | 'info' | 'debug' | 'log';\n\nconst levelToNumber = {\n none : 0, error : 1, warn : 2, info : 3, log : 4, debug : 5\n}\n\nexport interface Log extends Logger {\n level : number\n throw : number\n stop : number\n logger : Logger\n}\n\nexport const log : Log = function( a_level : LogLevel, a_msg : string, a_props : object ){\n let levelAsNumber = levelToNumber[ a_level ], msg, props, level;\n\n if( levelAsNumber === void 0 && !a_props ){\n levelAsNumber = 4;\n msg = a_level;\n props = a_msg;\n level = 'log';\n }\n else{\n msg = a_msg, level = a_level, props = a_props;\n }\n\n if( levelAsNumber <= log.level ){\n if( levelAsNumber <= log.throw || !log.logger ){\n const error = new Error( msg );\n (error as any).props = props;\n throw error;\n }\n else{\n log.logger( level, msg, props );\n \n if( levelAsNumber <= log.stop ){\n debugger;\n }\n }\n }\n}\n\ndeclare var process: any;\n\nlog.level = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'production' ? 1 : 2;\nlog.throw = 0;\nlog.stop = 0;\n\n\nlet toString = typeof window === 'undefined' ? \n function toString( something ){\n if( something && typeof something === 'object' ){\n const value = something.__inner_state__ || something,\n isTransactional = Boolean( something.__inner_state__ ),\n isArray = Array.isArray( value );\n\n const keys = Object.keys( value ).join( ', ' ),\n body = isArray ? `[ length = ${ value.length } ]` : `{ ${ keys } }`;\n\n return something.constructor.name + ' ' + body;\n }\n\n return something;\n } : function toString( x ){ return x; };\n\nif( typeof console !== 'undefined' ) {\n log.logger = function _console( level : LogLevel, error : string, props : object ){\n const args = [ error ];\n for( let name in props ){\n args.push( `\\n\\t${name}:`, toString( props[ name ] ) );\n }\n\n console[ level ].apply( console, args );\n }\n}\n\n/** Check if value is raw JSON */\nexport function isValidJSON( value : any ) : boolean {\n if( value === null ){\n return true;\n }\n\n switch( typeof value ){\n case 'number' :\n case 'string' :\n case 'boolean' :\n return true;\n\n case 'object':\n var proto = Object.getPrototypeOf( value );\n\n if( proto === Object.prototype || proto === Array.prototype ){\n return every( value, isValidJSON );\n }\n }\n\n return false;\n}\n\n/** Get the base class constructor function.\n * @param Class Subclass constructor function.\n * @returns Base class constructor function.\n */\nexport function getBaseClass( Class : Function ) {\n return Object.getPrototypeOf( Class.prototype ).constructor\n}\n\nexport function assignToClassProto( Class, definition : T, ...names : K[] ) : void {\n for( let name of names ){\n const value = definition[ name ];\n value === void 0 || ( Class.prototype[ name ] = value );\n }\n}\n\n/** Checks whenever given object is an empty hash `{}` */\nexport function isEmpty( obj : {} ) : boolean {\n if( obj ){\n for( let key in obj ){\n if( obj.hasOwnProperty( key ) ){\n return false;\n }\n }\n }\n\n return true;\n}\n\nexport type Iteratee = ( value : any, key? : string | number ) => any;\n\n/** @hidden */\nfunction someArray( arr : any[], fun : Iteratee ) : any {\n let result;\n\n for( let i = 0; i < arr.length; i++ ){\n if( result = fun( arr[ i ], i ) ){\n return result;\n }\n }\n}\n\n/** @hidden */\nfunction someObject( obj : {}, fun : Iteratee ) : any {\n let result;\n\n for( let key in obj ){\n if( obj.hasOwnProperty( key ) ){\n if( result = fun( obj[ key ], key ) ){\n return result;\n }\n }\n }\n}\n\n/** Similar to underscore `_.some` */\nexport function some( obj, fun : Iteratee ) : any {\n if( Object.getPrototypeOf( obj ) === ArrayProto ){\n return someArray( obj, fun );\n }\n else{\n return someObject( obj, fun );\n }\n}\n\n/** Similar to underscore `_.every` */\nexport function every( obj : { }, predicate : Iteratee ) : boolean {\n return !some( obj, x => !predicate( x ) );\n}\n\n/** Similar to `getOwnPropertyDescriptor`, but traverse the whole prototype chain. */\nexport function getPropertyDescriptor( obj : {}, prop : string ) : PropertyDescriptor {\n let desc : PropertyDescriptor;\n\n for( let proto = obj; !desc && proto; proto = Object.getPrototypeOf( proto ) ) {\n desc = Object.getOwnPropertyDescriptor( proto, prop );\n }\n\n return desc;\n}\n\n/** Similar to underscore `_.omit` */\nexport function omit( source : {}, ...rest : string[] ) : {}\nexport function omit( source ) : {} {\n const dest = {}, discard = {};\n\n for( let i = 1; i < arguments.length; i ++ ){\n discard[ arguments[ i ] ] = true;\n }\n\n for( var name in source ) {\n if( !discard.hasOwnProperty( name ) && source.hasOwnProperty( name ) ) {\n dest[ name ] = source[ name ];\n }\n }\n\n return dest;\n}\n\n/** map `source` object properties with a given function, and assign the result to the `dest` object.\n * When `fun` returns `undefined`, skip this value. \n */\nexport function transform< A, B >( dest : { [ key : string ] : A }, source : { [ key : string ] : B }, fun : ( value : B, key : string ) => A | void ) : { [ key : string ] : A } {\n for( var name in source ) {\n if( source.hasOwnProperty( name ) ) {\n var value = fun( source[ name ], name );\n value === void 0 || ( dest[ name ] = < A >value );\n }\n }\n\n return dest;\n}\n\n/** @hidden */\nexport function fastAssign< A >( dest : A, source : {} ) : A {\n for( var name in source ) {\n dest[ name ] = source[ name ];\n }\n\n return dest;\n}\n\n/** @hidden */\nexport function fastDefaults< A >( dest : A, source : {} ) : A {\n for( var name in source ) {\n if( dest[ name ] === void 0 ){\n dest[ name ] = source[ name ];\n }\n }\n\n return dest;\n}\n\n/** Similar to underscore `_.extend` and `Object.assign` */\nexport function assign< T >( dest : T, ...sources : Object[] ) : T\nexport function assign< T >( dest : T, source : Object ) : T {\n for( var name in source ) {\n if( source.hasOwnProperty( name ) ) {\n dest[ name ] = source[ name ];\n }\n }\n\n if( arguments.length > 2 ){\n for( let i = 2; i < arguments.length; i++ ){\n const other = arguments[ i ];\n other && assign( dest, other );\n }\n }\n\n return dest;\n}\n\n/** Similar to underscore `_.keys` */\nexport function keys( o : any ) : string[]{\n return o ? Object.keys( o ) : [];\n}\n\n/** Similar to underscore `_.once` */\nexport function once( func : Function ) : Function {\n var memo, first = true;\n return function() {\n if ( first ) {\n first = false;\n memo = func.apply(this, arguments);\n func = null;\n }\n return memo;\n };\n}\n\n/** @hidden */\nconst ArrayProto = Array.prototype,\n DateProto = Date.prototype,\n ObjectProto = Object.prototype;\n\n/**\n * Determine whenever two values are not equal, deeply traversing \n * arrays and plain JS objects (hashes). Dates are compared by enclosed timestamps, all other\n * values are compared with strict comparison.\n */\nexport function notEqual( a : any, b : any) : boolean {\n if( a === b ) return false;\n\n if( a && b && typeof a == 'object' && typeof b == 'object' ) {\n const protoA = Object.getPrototypeOf( a );\n\n if( protoA !== Object.getPrototypeOf( b ) ) return true;\n\n switch( protoA ){\n case DateProto : return +a !== +b;\n case ArrayProto : return arraysNotEqual( a, b );\n case ObjectProto :\n case null:\n return objectsNotEqual( a, b );\n }\n }\n\n return true;\n}\n\n/** @hidden */\nfunction objectsNotEqual( a, b ) {\n const keysA = Object.keys( a );\n\n if( keysA.length !== Object.keys( b ).length ) return true;\n\n for( let i = 0; i < keysA.length; i++ ) {\n const key = keysA[ i ];\n\n if( !b.hasOwnProperty( key ) || notEqual( a[ key ], b[ key ] ) ) {\n return true;\n }\n }\n\n return false;\n}\n\n/** @hidden */\nfunction arraysNotEqual( a, b ) {\n if( a.length !== b.length ) return true;\n\n for( let i = 0; i < a.length; i++ ) {\n if( notEqual( a[ i ], b[ i ] ) ) return true;\n }\n\n return false;\n}\n\n/**\n * Create an object without Object prototype members except hasOwnProperty.\n * @param obj - optional parameter to populate the hash map from.\n */\nconst HashProto = Object.create( null );\nHashProto.hasOwnProperty = ObjectProto.hasOwnProperty;\n\nexport function hashMap( obj? ){\n const hash = Object.create( HashProto );\n return obj ? assign( hash, obj ) : hash;\n}","/*****************************************************************\n * Mixins engine and @define metaprogramming class extensions\n *\n * Vlad Balin & Volicon, (c) 2016-2017\n */\nimport { log, assign, omit, hashMap, getPropertyDescriptor, getBaseClass, defaults, transform } from './tools'\nimport { __extends } from 'tslib'\n\nexport interface Subclass< T > extends MixableConstructor {\n new ( ...args ) : T\n prototype : T\n}\n\nexport interface MixableConstructor extends Function{\n __super__? : object;\n mixins? : MixinsState;\n onExtend? : ( BaseClass : Function ) => void;\n onDefine? : ( definition : object, BaseClass : Function ) => void;\n define? : ( definition? : object, statics? : object ) => MixableConstructor;\n extend? : ( definition? : T, statics? : object ) => Subclass;\n}\n\nexport interface MixableDefinition {\n mixins? : Mixin[]\n}\n\n/**\n * Base class, holding metaprogramming class extensions.\n * Supports mixins and Class.define metaprogramming method.\n */\nexport class Mixable {\n static onExtend : ( BaseClass : Function ) => void;\n static onDefine : ( definition : object, BaseClass : Function ) => object; \n static __super__ : object\n static mixins : MixinsState;\n\n /** \n * Must be called after inheritance and before 'define'.\n */\n static define( protoProps : MixableDefinition = {}, staticProps? : object ) : MixableConstructor {\n const BaseClass : MixableConstructor = getBaseClass( this );\n\n // Assign statics.\n staticProps && assign( this, staticProps );\n\n // Extract and apply mixins from the definition.\n const { mixins, ...defineMixin } = protoProps;\n mixins && this.mixins.merge( mixins );\n\n // Unshift definition to the the prototype.\n this.mixins.mergeObject( this.prototype, defineMixin, true );\n\n // Unshift definition from statics to the prototype.\n this.mixins.mergeObject( this.prototype, this.mixins.getStaticDefinitions( BaseClass ), true );\n\n // Call onDefine hook, if it's present.\n this.onDefine && this.onDefine( this.mixins.definitions, BaseClass );\n \n // Apply merge rules to inherited members. No mixins can be added after this point.\n this.mixins.mergeInheritedMembers( BaseClass );\n\n return this;\n }\n\n /** Backbone-compatible extend method to be used in ES5 and for backward compatibility */\n static extend< T extends object>(spec? : T, statics? : {} ) : Subclass< T > {\n let TheSubclass : Subclass< T >;\n\n // 1. Create the subclass (ES5 compatibility shim).\n // If constructor function is given...\n if( spec && spec.hasOwnProperty( 'constructor' ) ){\n // ...we need to manually call internal TypeScript __extend function. Hack! Hack!\n TheSubclass = spec.constructor as any;\n __extends( TheSubclass, this );\n }\n // Otherwise, create the subclall in usual way.\n else{\n TheSubclass = class Subclass extends this {} as any;\n }\n\n predefine( TheSubclass );\n spec && TheSubclass.define( spec, statics );\n\n return TheSubclass;\n }\n}\n\n/** @decorator `@predefine` for forward definitions. Can be used with [[Mixable]] classes only.\n * Forwards the call to the [[Mixable.predefine]];\n */\nexport function predefine( Constructor : MixableConstructor ) : void {\n const BaseClass : MixableConstructor = getBaseClass( Constructor );\n\n // Legacy systems support\n Constructor.__super__ = BaseClass.prototype;\n \n // Initialize mixins structures...\n Constructor.define || MixinsState.get( Mixable ).populate( Constructor );\n\n // Make sure Ctor.mixins are ready before the callback...\n MixinsState.get( Constructor );\n\n // Call extend hook.\n Constructor.onExtend && Constructor.onExtend( BaseClass );\n}\n\n/** @decorator `@define` for metaprogramming magic. Can be used with [[Mixable]] classes only.\n * Forwards the call to [[Mixable.define]].\n */\nexport function define( ClassOrDefinition : Function ) : void;\nexport function define( ClassOrDefinition : object ) : ClassDecorator;\nexport function define( ClassOrDefinition : object | MixableConstructor ){\n // @define class\n if( typeof ClassOrDefinition === 'function' ){\n predefine( ClassOrDefinition );\n ClassOrDefinition.define();\n }\n // @define({ prop : val, ... }) class\n else{\n return function( Ctor : MixableConstructor ){\n predefine( Ctor );\n Ctor.define( ClassOrDefinition );\n }\n }\n}\n\nexport function definitions( rules : MixinMergeRules ) : ClassDecorator {\n return ( Class : Function ) => {\n const mixins = MixinsState.get( Class );\n mixins.definitionRules = defaults( hashMap(), rules, mixins.definitionRules );\n }\n}\n\n// Create simple property list decorator\nexport function propertyListDecorator( listName: string ) : PropertyDecorator {\n return function propList(proto, name : string) {\n const list = proto.hasOwnProperty( listName ) ?\n proto[ listName ] : (proto[ listName ] = (proto[ listName ] || []).slice()); \n\n list.push(name);\n }\n}\n\nexport function definitionDecorator( definitionKey, value ){\n return ( proto : object, name : string ) => {\n MixinsState\n .get( proto.constructor )\n .mergeObject( proto, {\n [ definitionKey ] : {\n [ name ] : value\n }\n });\n }\n}\n\nexport class MixinsState {\n mergeRules : MixinMergeRules;\n definitionRules : MixinMergeRules;\n definitions : object = {};\n appliedMixins : Mixin[];\n\n // Return mixins state for the class. Initialize if it's not exist.\n static get( Class ) : MixinsState {\n const { mixins } = Class;\n \n return mixins && Class === mixins.Class ? mixins :\n Class.mixins = new MixinsState( Class );\n }\n\n constructor( public Class : MixableConstructor ){\n const { mixins } = getBaseClass( Class );\n\n this.mergeRules = ( mixins && mixins.mergeRules ) || hashMap();\n this.definitionRules = ( mixins && mixins.definitionRules ) || hashMap();\n this.appliedMixins = ( mixins && mixins.appliedMixins ) || [];\n }\n\n getStaticDefinitions( BaseClass : Function ){\n const definitions = hashMap(),\n { Class } = this;\n\n return transform( definitions, this.definitionRules, ( rule, name ) =>{\n if( BaseClass[ name ] !== Class[ name ]){\n return Class[ name ];\n }\n });\n }\n\n merge( mixins : Mixin[] ){\n const proto = this.Class.prototype,\n { mergeRules } = this;\n\n // Copy applied mixins array as it's going to be updated.\n const appliedMixins = this.appliedMixins = this.appliedMixins.slice();\n\n // Apply mixins in sequence...\n for( let mixin of mixins ) {\n // Mixins array should be flattened.\n if( Array.isArray( mixin ) ) {\n this.merge( mixin );\n }\n // Don't apply mixins twice.\n else if( appliedMixins.indexOf( mixin ) < 0 ){\n appliedMixins.push( mixin );\n\n // For constructors, merge _both_ static and prototype members.\n if( typeof mixin === 'function' ){\n // Merge static members\n this.mergeObject( this.Class, mixin );\n\n // merge definitionRules and mergeRules\n const sourceMixins = ( mixin as any ).mixins;\n if( sourceMixins ){\n this.mergeRules = defaults( hashMap(), this.mergeRules, sourceMixins.mergeRules );\n this.definitionRules = defaults( hashMap(), this.definitionRules, sourceMixins.definitionRules );\n this.appliedMixins = this.appliedMixins.concat( sourceMixins.appliedMixins );\n }\n\n // Prototypes are merged according with rules.\n this.mergeObject( proto, mixin.prototype );\n }\n // Handle plain object mixins.\n else {\n this.mergeObject( proto, mixin );\n }\n }\n }\n }\n\n populate( ...ctors : Function[] ){\n for( let Ctor of ctors ) {\n MixinsState.get( Ctor ).merge([ this.Class ]);\n }\n }\n\n mergeObject( dest : object, source : object, unshift? : boolean ) {\n forEachOwnProp( source, name => {\n const sourceProp = Object.getOwnPropertyDescriptor( source, name );\n let rule : MixinMergeRule;\n\n if( rule = this.definitionRules[ name ] ){\n assignProperty( this.definitions, name, sourceProp, rule, unshift );\n }\n\n if( !rule || rule === mixinRules.protoValue ){\n assignProperty( dest, name, sourceProp, this.mergeRules[ name ], unshift );\n }\n });\n }\n\n mergeInheritedMembers( BaseClass : Function ){\n const { mergeRules, Class } = this;\n\n if( mergeRules ){\n const proto = Class.prototype,\n baseProto = BaseClass.prototype;\n\n for( let name in mergeRules ) {\n const rule = mergeRules[ name ];\n\n if( proto.hasOwnProperty( name ) && name in baseProto ){\n proto[ name ] = resolveRule( proto[ name ], baseProto[ name ], rule );\n }\n }\n }\n }\n}\n\nconst dontMix = {\n function : hashMap({\n length : true,\n prototype : true,\n caller : true,\n arguments : true,\n name : true,\n __super__ : true\n }),\n \n object : hashMap({\n constructor : true\n }) \n}\n\nfunction forEachOwnProp( object : object, fun : ( name : string ) => void ){\n const ignore = dontMix[ typeof object ];\n\n for( let name of Object.keys( object ) ) {\n ignore[ name ] || fun( name );\n }\n}\n\nexport interface MixinMergeRules {\n [ name : string ] : MixinMergeRule\n}\n\nexport type MixinMergeRule = ( a : any, b : any ) => any\nexport type Mixin = { [ key : string ] : any } | Function\n\n// @mixins( A, B, ... ) decorator.\nexport interface MixinRulesDecorator {\n ( rules : MixinMergeRules ) : ClassDecorator\n value( a : object, b : object) : object;\n protoValue( a : object, b : object) : object;\n merge( a : object, b : object ) : object;\n pipe( a: Function, b : Function ) : Function;\n defaults( a: Function, b : Function ) : Function;\n classFirst( a: Function, b : Function ) : Function;\n classLast( a: Function, b : Function ) : Function;\n every( a: Function, b : Function ) : Function;\n some( a: Function, b : Function ) : Function;\n}\n\nexport const mixins = ( ...list : Mixin[] ) => (\n ( Class : Function ) => MixinsState.get( Class ).merge( list )\n);\n\n// @mixinRules({ name : rule, ... }) decorator.\nexport const mixinRules = ( ( rules : MixinMergeRules ) => (\n ( Class : Function ) => {\n const mixins = MixinsState.get( Class );\n mixins.mergeRules = defaults( rules, mixins.mergeRules );\n }\n) ) as MixinRulesDecorator;\n\n// Pre-defined mixin merge rules\n\nmixinRules.value = ( a, b ) => a;\n\nmixinRules.protoValue = ( a, b ) => a;\n\n// Recursively merge members\nmixinRules.merge = ( a, b ) => defaults( {}, a, b );\n\n // Execute methods in pipe, with the class method executed last.\nmixinRules.pipe = ( a, b ) => (\n function( x : any ) : any {\n return a.call( this, b.call( this, x ) );\n }\n);\n\n // Assume methods return an object, and merge results with defaults (class method executed first)\nmixinRules.defaults = ( a : Function, b : Function ) => (\n function() : object {\n return defaults( a.apply( this, arguments ), b.apply( this, arguments ) );\n }\n);\n\n// Execute methods in sequence staring with the class method.\nmixinRules.classFirst = ( a : Function, b : Function ) => (\n function() : void {\n a.apply( this, arguments );\n b.apply( this, arguments );\n }\n);\n\n // Execute methods in sequence ending with the class method.\nmixinRules.classLast = ( a : Function, b : Function ) => (\n function() : void {\n b.apply( this, arguments );\n a.apply( this, arguments );\n }\n)\n\n // Execute methods in sequence returning the first falsy result.\nmixinRules.every = ( a : Function, b : Function ) =>(\n function() : any {\n return a.apply( this, arguments ) && b.apply( this, arguments );\n }\n);\n // Execute methods in sequence returning the first truthy result.\nmixinRules.some = ( a : Function, b : Function ) =>(\n function() : any {\n return a.apply( this, arguments ) || b.apply( this, arguments );\n }\n);\n\n/**\n * Helpers\n */\n\nfunction assignProperty( dest : object, name : string, sourceProp : PropertyDescriptor, rule : MixinMergeRule, unshift? : boolean ){\n// Destination prop is defined, thus the merge rules must be applied.\n if( dest.hasOwnProperty( name ) ){\n const destProp = Object.getOwnPropertyDescriptor( dest, name );\n\n if( destProp.configurable && 'value' in destProp ){\n dest[ name ] = unshift ?\n resolveRule( sourceProp.value, destProp.value, rule ) :\n resolveRule( destProp.value, sourceProp.value, rule ) ;\n }\n }\n // If destination is empty, just copy the prop over.\n else{\n Object.defineProperty( dest, name, sourceProp );\n }\n}\n\nfunction resolveRule( dest, source, rule : MixinMergeRule ){\n // When destination is empty, take the source.\n if( dest === void 0 ) return source;\n\n // In these cases we take non-empty destination:\n if( !rule || source === void 0 ) return dest;\n\n // In other cases we must merge values.\n return rule( dest, source );\n}","import { once as _once } from './tools'\n\n/*******************\n * Prebuilt events map, used for optimized bulk event subscriptions.\n *\n * const events = new EventMap({\n * 'change' : true, // Resend this event from self as it is.\n * 'change:attr' : 'localTargetFunction',\n * 'executedInTargetContext' : function(){ ... }\n * 'executedInNativeContext' : '^props.handler'\n * })\n */\n/** @hidden */\nexport interface EventsDefinition {\n [ events : string ] : Function | string | boolean\n}\n\n/** @hidden */\nexport class EventMap {\n handlers : EventDescriptor[] = [];\n\n constructor( map? : EventsDefinition | EventMap ){\n if( map ){\n if( map instanceof EventMap ){\n this.handlers = map.handlers.slice();\n }\n else{\n map && this.addEventsMap( map );\n }\n }\n }\n\n merge( map : EventMap ){\n this.handlers = this.handlers.concat( map.handlers );\n }\n\n addEventsMap( map : EventsDefinition ){\n for( let names in map ){\n this.addEvent( names, map[ names ] )\n }\n }\n\n bubbleEvents( names : string ){\n for( let name of names.split( eventSplitter ) ){\n this.addEvent( name, getBubblingHandler( name ) );\n }\n }\n\n addEvent( names : string, callback : Function | string | boolean ){\n const { handlers } = this;\n\n for( let name of names.split( eventSplitter ) ){\n handlers.push( new EventDescriptor( name, callback ) );\n }\n }\n\n subscribe( target : {}, source : EventSource ){\n for( let event of this.handlers ){\n on( source, event.name, event.callback, target );\n }\n }\n\n unsubscribe( target : {}, source : EventSource ){\n for( let event of this.handlers ){\n off( source, event.name, event.callback, target );\n }\n }\n}\n\n/** @hidden */\nexport class EventDescriptor {\n callback : Function\n\n constructor(\n public name : string,\n callback : Function | string | boolean\n ){\n if( callback === true ){\n this.callback = getBubblingHandler( name );\n }\n else if( typeof callback === 'string' ){\n this.callback =\n function localCallback(){\n const handler = this[ callback ];\n handler && handler.apply( this, arguments );\n };\n }\n else{\n this.callback = callback;\n }\n }\n}\n\n/** @hidden */\nconst _bubblingHandlers = {};\n\n/** @hidden */\nfunction getBubblingHandler( event : string ){\n return _bubblingHandlers[ event ] || (\n _bubblingHandlers[ event ] = function( a?, b?, c?, d?, e? ){\n if( d !== void 0 || e !== void 0 ) trigger5( this, event, a, b, c, d, e );\n if( c !== void 0 ) trigger3( this, event, a, b, c );\n else trigger2( this, event, a, b );\n }\n );\n}\n\n/** @hidden */\nexport interface HandlersByEvent {\n [ name : string ] : EventHandler\n}\n\n/** @hidden */\nexport class EventHandler {\n constructor( public callback : Callback, public context : any, public next = null ){}\n}\n\n/** @hidden */\nfunction listOff( _events : HandlersByEvent, name : string, callback : Callback, context : any ){\n const head = _events[ name ];\n\n let filteredHead, prev;\n\n for( let ev = head; ev; ev = ev.next ){\n // Element must be kept\n if( ( callback && callback !== ev.callback && callback !== ev.callback._callback ) ||\n ( context && context !== ev.context ) ){\n \n prev = ev;\n filteredHead || ( filteredHead = ev );\n }\n // Element must be skipped\n else{\n if( prev ) prev.next = ev.next;\n }\n }\n\n if( head !== filteredHead ) _events[ name ] = filteredHead;\n}\n\n/** @hidden */\nfunction listSend2( head : EventHandler, a, b ){\n for( let ev = head; ev; ev = ev.next ) ev.callback.call( ev.context, a, b );\n}\n\n/** @hidden */\nfunction listSend3( head : EventHandler, a, b, c ){\n for( let ev = head; ev; ev = ev.next ) ev.callback.call( ev.context, a, b, c );\n}\n\n/** @hidden */\nfunction listSend4( head : EventHandler, a, b, c, d ){\n for( let ev = head; ev; ev = ev.next ) ev.callback.call( ev.context, a, b, c, d );\n}\n\n/** @hidden */\nfunction listSend5( head : EventHandler, a, b, c, d, e ){\n for( let ev = head; ev; ev = ev.next ) ev.callback.call( ev.context, a, b, c, d, e );\n}\n\n/** @hidden */\nfunction listSend6( head : EventHandler, a, b, c, d, e, f ){\n for( let ev = head; ev; ev = ev.next ) ev.callback.call( ev.context, a, b, c, d, e, f );\n}\n\n/** @hidden */\nexport interface Callback extends Function {\n _callback? : Function\n}\n\n/** @hidden */\nexport function on( source : EventSource, name : string, callback : Callback, context? : any ) : void {\n if( callback ){\n const _events = source._events || ( source._events = Object.create( null ) );\n _events[ name ] = new EventHandler( callback, context, _events[ name ] );\n }\n}\n\n/** @hidden */\nexport function once( source : EventSource, name : string, callback : Callback, context? : any ) : void {\n if( callback ){\n const once : Callback = _once( function(){\n off( source, name, once );\n callback.apply(this, arguments);\n });\n\n once._callback = callback;\n on( source, name, once, context );\n }\n}\n\n/** @hidden */\nexport function off( source : EventSource, name? : string, callback? : Callback, context? : any ) : void {\n const { _events } = source;\n if( _events ){\n if( callback || context ) {\n if( name ){\n listOff( _events, name, callback, context );\n }\n else{\n for( let name in _events ){\n listOff( _events, name, callback, context );\n }\n }\n }\n else if( name ){\n _events[ name ] = void 0;\n }\n else{\n source._events = void 0;\n }\n }\n}\n\n/** @hidden */\nexport interface EventSource {\n _events : HandlersByEvent\n}\n\n/** @hidden */\nconst eventSplitter = /\\s+/;\n\n/** @hidden */\nexport function strings( api : ApiEntry, source : EventSource, events : string, callback : Callback, context ){\n if( eventSplitter.test( events ) ){\n const names = events.split( eventSplitter );\n for( let name of names ) api( source, name, callback, context );\n }\n else api( source, events, callback, context );\n}\n\n/** @hidden */\nexport type ApiEntry = ( source : EventSource, event : string, callback : Callback, context? : any ) => void\n\n/*********************************\n * Event-triggering API\n */\n\n/** @hidden */\nexport function trigger2( self : EventSource, name : string, a, b ) : void {\n const { _events } = self;\n if( _events ){\n const queue = _events[ name ],\n { all } = _events;\n\n listSend2( queue, a, b );\n listSend3( all, name, a, b );\n }\n};\n\n/** @hidden */\nexport function trigger3( self : EventSource, name : string, a, b, c ) : void{\n const { _events } = self;\n if( _events ){\n const queue = _events[ name ],\n { all } = _events;\n\n listSend3( queue, a, b, c );\n listSend4( all, name, a, b, c );\n }\n};\n\n/** @hidden */\nexport function trigger5( self : EventSource, name : string, a, b, c, d, e ) : void{\n const { _events } = self;\n if( _events ){\n const queue = _events[ name ],\n { all } = _events;\n\n listSend5( queue, a, b, c, d, e );\n listSend6( all, name, a, b, c, d, e );\n }\n};","import { define, mixins, Mixable, Mixin, MixableConstructor, MixinsState, mixinRules, definitions, MixinMergeRules } from './mixins'\nimport { omit, transform } from './tools'\nimport { EventMap, EventsDefinition, EventSource, HandlersByEvent } from './eventsource'\nimport * as _eventsApi from './eventsource'\n\nconst { EventHandler, strings, on, off, once, trigger5, trigger2, trigger3 } = _eventsApi;\n\n/** @hidden */\nconst eventSplitter = /\\s+/;\n\n/** @hidden */\nlet _idCount = 0;\n\n/** @hidden */\nfunction uniqueId() : string {\n return 'l' + _idCount++;\n}\n\nexport { EventMap, EventsDefinition }\n\nexport interface MessengerDefinition {\n _localEvents? : EventMap\n localEvents? : EventsDefinition\n properties? : PropertyMap\n [ name : string ] : any\n}\n\nexport interface PropertyMap {\n [ name : string ] : Property\n}\n\nexport type Property = PropertyDescriptor | ( () => any )\n\n/** @hidden */\nexport interface MessengersByCid {\n [ cid : string ] : Messenger\n}\n\n/** @hidden */\nexport type CallbacksByEvents = { [ events : string ] : Function }\n\n/*************************\n * Messenger is mixable class with capabilities of sending and receiving synchronous events.\n * This class itself can serve as both mixin and base class.\n */\n\n@define\n@definitions({\n properties : mixinRules.merge,\n localEvents : mixinRules.merge\n})\nexport abstract class Messenger implements Mixable, EventSource {\n // Define extendable mixin static properties.\n static __super__ : object;\n static mixins : MixinsState;\n static onExtend : ( BaseClass : Function ) => void;\n static define : ( definition? : MessengerDefinition, statics? : object ) => MixableConstructor;\n static extend : ( definition? : MessengerDefinition, statics? : object ) => MixableConstructor;\n static onDefine({ localEvents, _localEvents, properties } : MessengerDefinition, BaseClass? : typeof Mixable ){\n // Handle localEvents definition\n if( localEvents || _localEvents ){\n const eventsMap = new EventMap( this.prototype._localEvents );\n\n localEvents && eventsMap.addEventsMap( localEvents );\n _localEvents && eventsMap.merge( _localEvents );\n \n this.prototype._localEvents = eventsMap;\n }\n\n // Handle properties definitions...\n if( properties ){\n Object.defineProperties( this.prototype, transform( {}, properties, toPropertyDescriptor ) );\n }\n }\n\n /** @hidden */ \n _events : HandlersByEvent = void 0;\n\n /** @hidden */ \n _listeningTo : MessengersByCid = void 0\n\n /** Unique client-only id. */\n cid : string\n\n /** @hidden Prototype-only property to manage automatic local events subscription */ \n _localEvents : EventMap\n\n /** @hidden */ \n constructor(){\n this.cid = uniqueId();\n this.initialize.apply( this, arguments );\n\n // TODO: local events subscribe?\n }\n\n /** Method is called at the end of the constructor */\n initialize() : void {}\n \n on( events : string | CallbacksByEvents, callback, context? ) : this {\n if( typeof events === 'string' ) strings( on, this, events, callback, context );\n else for( let name in events ) strings( on, this, name, events[ name ], context || callback );\n\n return this;\n }\n\n once( events : string | CallbacksByEvents, callback, context? ) : this {\n if( typeof events === 'string' ) strings( once, this, events, callback, context );\n else for( let name in events ) strings( once, this, name, events[ name ], context || callback );\n\n return this;\n }\n\n off( events? : string | CallbacksByEvents, callback?, context? ) : this {\n if( !events ) off( this, void 0, callback, context );\n else if( typeof events === 'string' ) strings( off, this, events, callback, context );\n else for( let name in events ) strings( off, this, name, events[ name ], context || callback );\n\n return this;\n }\n\n // Trigger one or many events, firing all bound callbacks. Callbacks are\n // passed the same arguments as `trigger` is, apart from the event name\n // (unless you're listening on `\"all\"`, which will cause your callback to\n // receive the true name of the event as the first argument).\n trigger(name : string, a?, b?, c?, d?, e? ) : this {\n if( d !== void 0 || e !== void 0 ) trigger5( this, name, a, b, c, d, e );\n else if( c !== void 0 ) trigger3( this, name, a, b, c );\n else trigger2( this, name, a, b );\n return this;\n }\n\n listenTo( source : Messenger, a : string | CallbacksByEvents, b? : Function ) : this {\n if( source ){\n addReference( this, source );\n source.on( a, !b && typeof a === 'object' ? this : b, this );\n }\n\n return this;\n }\n\n listenToOnce( source : Messenger, a : string | CallbacksByEvents, b? : Function ) : this {\n if( source ){\n addReference( this, source );\n source.once( a, !b && typeof a === 'object' ? this : b, this );\n }\n\n return this;\n }\n\n stopListening( a_source? : Messenger, a? : string | CallbacksByEvents, b? : Function ) : this {\n const { _listeningTo } = this;\n if( _listeningTo ){\n const removeAll = !( a || b ),\n second = !b && typeof a === 'object' ? this : b;\n\n if( a_source ){\n const source = _listeningTo[ a_source.cid ];\n if( source ){\n if( removeAll ) delete _listeningTo[ a_source.cid ];\n source.off( a, second, this );\n }\n }\n else if( a_source == null ){\n for( let cid in _listeningTo ) _listeningTo[ cid ].off( a, second, this );\n\n if( removeAll ) ( this._listeningTo = void 0 );\n }\n }\n\n return this;\n }\n\n /**\n * Destructor. Stops messenger from listening to all objects,\n * and stop others from listening to the messenger. \n */\n _disposed : boolean\n\n dispose() : void {\n if( this._disposed ) return;\n\n this.stopListening();\n this.off();\n\n this._disposed = true;\n }\n}\n\n/**\n * Backbone 1.2 API conformant Events mixin.\n */\nexport const Events : Messenger = omit( Messenger.prototype, 'constructor', 'initialize' );\n\n/**\n * Messenger Private Helpers \n */\n\nfunction toPropertyDescriptor( x : Property ) : PropertyDescriptor {\n if( x ){\n return typeof x === 'function' ? { get : < () => any >x } : x;\n }\n}\n\n/** @hidden */\nfunction addReference( listener : Messenger, source : Messenger ){\n const listeningTo = listener._listeningTo || (listener._listeningTo = Object.create( null ) ),\n cid = source.cid || ( source.cid = uniqueId() );\n\n listeningTo[ cid ] = source;\n}","// (c) 2016 Vlad Balin and Volicon\n// MixtureJS may be freely distributed under the MIT license. \n\nimport * as tools from './tools'\nexport { tools }\nexport * from './mixins'\nexport * from './events'\nimport * as eventsApi from './eventsource'\nexport { eventsApi }\n\nimport { Mixable, MixableConstructor } from './mixins'\n\ndeclare global {\n interface ObjectConstructor {\n /** Polyfill for Object.assign */\n assign< T >( dest : T, ...sources : Object[] ) : T\n\n /** Global logging interface, for console debugging. */\n log : tools.Log\n\n /** ES5 Object.extend */\n extend( protoProps : {}, staticProps : {} ) : MixableConstructor\n }\n}\n\nObject.extend = ( protoProps, staticProps ) => Mixable.extend( protoProps, staticProps );\nObject.assign || ( Object.assign = tools.assign );\nObject.log = tools.log;","export interface ChildrenErrors {\n [ key : string ] : ValidationError | any\n} \n\nexport interface Validatable {\n _validateNested( errors : ChildrenErrors ) : number;\n validate( self : any ) : any\n get( key : string ) : any\n}\n\n// Validation error object.\nexport class ValidationError {\n // Invalid nested object keys \n nested : ChildrenErrors \n length : number\n\n // Local error\n error : any\n\n constructor( obj : Validatable ){\n this.length = obj._validateNested( this.nested = {} );\n\n if( this.error = obj.validate( obj ) ){\n this.length++;\n }\n }\n\n each( iteratee : ( value : any, key : string ) => void ) : void {\n const { error, nested } = this;\n\n if( error ) iteratee( error, null );\n\n for( const key in nested ){\n iteratee( nested[ key ], key );\n }\n }\n\n eachError( iteratee : ( error : any, key : string, object : Validatable ) => void, object : Validatable ) : void {\n this.each( ( value : any, key : string ) => {\n if( value instanceof ValidationError ){\n (value).eachError( iteratee, object.get( key ) );\n }\n else{\n iteratee( value, key, object );\n }\n });\n }\n}","/**\n * Some sketches for reference resolution.\n *\n * \n * a : Model.from( '~collection' )\n * \n * We need two functions. One for get, and one for compile. \n */\nexport interface Traversable {\n getStore() : Traversable\n getOwner() : Traversable\n get( key : string ) : any \n}\n\nconst referenceMask = /\\^|(store\\.[^.]+)|([^.]+)/g;\n\n// Compile reference to function\nexport type ResolveReference = ( root : Traversable ) => any; \n\nexport class CompiledReference {\n resolve : ResolveReference\n tail : string\n local : boolean\n\n constructor( reference : string, splitTail : boolean = false ){\n const path = reference\n .match( referenceMask )\n .map( key => {\n if( key === '^' || key === 'owner' ) return 'getOwner()';\n\n if( key[ 0 ] === '~' ) return `getStore().get(\"${ key.substr( 1 ) }\")`;\n\n if( key.indexOf( 'store.' ) === 0 ) return `getStore().get(\"${ key.substr( 6 ) }\")`;\n \n return key;\n } );\n \n this.tail = splitTail && path.pop();\n this.local = !path.length;\n \n this.resolve = new Function( 'self', `\n var v = self.${ path.shift() };\n \n ${ path.map( x => `\n v = v && v.${ x };\n `).join('')}\n\n return v;\n ` );\n }\n}\n\nexport function resolveReference( root : Traversable, reference : string, action : ( object, key : string ) => any ) : any {\n const path = reference.match( referenceMask ),\n skip = path.length - 1;\n \n let self = root;\n\n for( var i = 0; i < skip; i++ ){\n const key = path[ i ];\n switch( key ){\n case '~' : self = self.getStore(); break;\n case '^' : self = self.getOwner(); break;\n default : self = self.get( key );\n }\n\n // Do nothing if object on the path doesn't exist.\n if( !self ) return;\n }\n\n return action( self, path[ skip ] );\n}","export interface IONode {\n _endpoint : IOEndpoint\n _ioPromise : IOPromise< this >\n}\n\nexport interface IOPromise extends Promise {\n abort? : () => void\n}\n\nexport interface IOEndpoint {\n list( options : IOOptions, collection? ) : IOPromise\n create( json : any, options : IOOptions, record? ) : IOPromise\n update( id : string | number, json :any, options : IOOptions, record? ) : IOPromise\n read( id : string | number, options : IOOptions, record? ) : IOPromise\n destroy( id : string | number, options : IOOptions, record? ) : IOPromise\n subscribe( events : IOEvents, collection? ) : IOPromise\n unsubscribe( events : IOEvents, collection? ) : void\n}\n\nexport interface IOOptions {\n ioUpdate? : boolean\n}\n\nexport interface IOEvents {\n updated? : ( json : any ) => void\n removed? : ( json : any ) => void\n}\n\nexport function getOwnerEndpoint( self ) : IOEndpoint {\n // Check if we are the member of the collection...\n const { collection } = self;\n if( collection ){\n return getOwnerEndpoint( collection );\n }\n\n // Now, if we're the member of the model...\n if( self._owner ){\n const { _endpoints } = self._owner;\n return _endpoints && _endpoints[ self._ownerKey ];\n }\n}\n\n/**\n * Create abortable promise.\n * Adds `promise.abort()` function which rejects the promise by default\n * initialize() function takes third optional argument `abort : ( resolve, reject ) => void`,\n * which can be used to add custom abort handling.\n */\ndeclare var Promise: PromiseConstructorLike;\n\nexport function createIOPromise( initialize : InitIOPromise ) : IOPromise{\n let resolve, reject, onAbort;\n\n function abort( fn ){\n onAbort = fn;\n }\n\n const promise : IOPromise = new Promise( ( a_resolve, a_reject ) =>{\n reject = a_reject;\n resolve = a_resolve;\n initialize( resolve, reject, abort );\n }) as IOPromise;\n\n promise.abort = () => {\n onAbort ? onAbort( resolve, reject ) : reject( new Error( \"I/O Aborted\" ) );\n }\n\n return promise;\n}\n\nexport type InitIOPromise = ( resolve : ( x? : any ) => void, reject : ( x? : any ) => void, abort? : ( fn : Function ) => void ) => void;\n\nexport function startIO( self : IONode, promise : IOPromise, options : IOOptions, thenDo : ( json : any ) => any ) : IOPromise {\n // Stop pending I/O first...\n abortIO( self );\n\n // Mark future update transaction as IO transaction.\n options.ioUpdate = true;\n\n self._ioPromise = promise\n .then( resp => {\n self._ioPromise = null;\n \n const result = thenDo ? thenDo( resp ) : resp;\n \n triggerAndBubble( self, 'sync', self, resp, options );\n \n return result;\n } ) \n .catch( err => {\n self._ioPromise = null;\n\n console.error( err );\n \n triggerAndBubble( self, 'error', self, err, options );\n \n throw err;\n } ) as IOPromise;\n\n self._ioPromise.abort = promise.abort;\n\n return self._ioPromise;\n}\n\nexport function abortIO( self : IONode ){\n if( self._ioPromise && self._ioPromise.abort ){\n self._ioPromise.abort();\n self._ioPromise = null;\n }\n}\n\nexport function triggerAndBubble( eventSource, ...args ){\n eventSource.trigger.apply( eventSource, args );\n const { collection } = eventSource;\n collection && collection.trigger.apply( collection, args ); \n}","import { Messenger, CallbacksByEvents, MessengersByCid, MixinsState, MixinMergeRules, MessengerDefinition, tools, mixins, mixinRules, definitions, eventsApi, define, Subclass } from './object-plus'\nimport { ValidationError, Validatable, ChildrenErrors } from './validation'\nimport { Traversable, resolveReference } from './traversable'\nimport { IOEndpoint, IOPromise, IONode, abortIO } from './io-tools'\n\nconst { assign } = tools,\n { trigger2, trigger3, on, off } = eventsApi;\n/***\n * Abstract class implementing ownership tree, tho-phase transactions, and validation. \n * 1. createTransaction() - apply changes to an object tree, and if there are some events to send, transaction object is created.\n * 2. transaction.commit() - send and process all change events, and close transaction.\n */\n\n/** @private */\nexport interface TransactionalDefinition extends MessengerDefinition {\n endpoint? : IOEndpoint\n}\n\nexport enum ItemsBehavior {\n share = 0b0001,\n listen = 0b0010,\n persistent = 0b0100\n}\n\n// Transactional object interface\n@define\n@definitions({\n endpoint : mixinRules.value\n})\n@mixins( Messenger )\nexport abstract class Transactional implements Messenger, IONode, Validatable, Traversable {\n // Mixins are hard in TypeScript. We need to copy type signatures over...\n // Here goes 'Mixable' mixin.\n static endpoint : IOEndpoint;\n static __super__ : object;\n static mixins : MixinsState;\n static define : ( definition? : TransactionalDefinition, statics? : object ) => typeof Transactional;\n static extend : ( definition? : T, statics? : object ) => any;\n\n static onDefine( definitions : TransactionalDefinition, BaseClass : typeof Transactional ){\n if( definitions.endpoint ) this.prototype._endpoint = definitions.endpoint;\n Messenger.onDefine.call( this, definitions, BaseClass );\n };\n\n static onExtend( BaseClass : typeof Transactional ) : void {\n // Make sure we don't inherit class factories.\n if( BaseClass.create === this.create ) {\n this.create = Transactional.create;\n }\n }\n\n // Define extendable mixin static properties.\n static create( a : any, b? : any ) : Transactional {\n return new (this as any)( a, b );\n }\n\n /** Generic class factory. May be overridden for abstract classes. Not inherited. */\n on : ( events : string | CallbacksByEvents, callback, context? ) => this\n once : ( events : string | CallbacksByEvents, callback, context? ) => this\n off : ( events? : string | CallbacksByEvents, callback?, context? ) => this\n trigger : (name : string, a?, b?, c?, d?, e? ) => this\n\n stopListening : ( source? : Messenger, a? : string | CallbacksByEvents, b? : Function ) => this\n listenTo : ( source : Messenger, a : string | CallbacksByEvents, b? : Function ) => this\n listenToOnce : ( source : Messenger, a : string | CallbacksByEvents, b? : Function ) => this\n \n _disposed : boolean;\n\n // State accessor. \n readonly __inner_state__ : any;\n\n // Shared modifier (used by collections of shared models)\n _shared? : number; \n \n dispose() : void {\n if( this._disposed ) return;\n \n abortIO( this );\n this._owner = void 0;\n this._ownerKey = void 0;\n this.off();\n this.stopListening();\n this._disposed = true;\n }\n\n // Must be called at the end of the constructor in the subclass.\n initialize() : void {}\n\n /** @private */\n _events : eventsApi.HandlersByEvent = void 0;\n\n /** @private */\n _listeningTo : MessengersByCid\n\n /** @private */\n _localEvents : eventsApi.EventMap\n\n cid : string\n cidPrefix : string\n\n static shared : any;\n\n // Unique version token replaced on change\n /** @private */\n _changeToken : {} = {}\n\n // true while inside of the transaction\n /** @private */\n _transaction : boolean = false;\n\n // Holds current transaction's options, when in the middle of transaction and there're changes but is an unsent change event\n /** @private */\n _isDirty : TransactionOptions = null;\n\n // Backreference set by owner (Record, Collection, or other object)\n /** @private */\n _owner : Owner = void 0;\n\n // Key supplied by owner. Used by record to identify attribute key.\n // Only collections doesn't set the key, which is used to distinguish collections.\n /** @private */ \n _ownerKey : string = void 0;\n\n // Name of the change event\n /** @private */\n _changeEventName : string\n\n /**\n * Subsribe for the changes.\n */\n onChanges( handler : Function, target? : Messenger ){\n on( this, this._changeEventName, handler, target );\n }\n\n /**\n * Unsubscribe from changes.\n */\n offChanges( handler? : Function, target? : Messenger ){\n off( this, this._changeEventName, handler, target );\n }\n\n /**\n * Listen to changes event. \n */\n listenToChanges( target : Transactional, handler ){\n this.listenTo( target, target._changeEventName, handler );\n }\n\n constructor( cid : string | number ){\n this.cid = this.cidPrefix + cid;\n }\n\n // Deeply clone ownership subtree\n abstract clone( options? : CloneOptions ) : this\n \n // Execute given function in the scope of ad-hoc transaction.\n transaction( fun : ( self : this ) => void, options : TransactionOptions = {} ) : void{\n const isRoot = transactionApi.begin( this );\n const update = fun.call( this, this );\n update && this.set( update );\n isRoot && transactionApi.commit( this );\n }\n\n // Loop through the members in the scope of transaction.\n // Transactional version of each()\n updateEach( iteratee : ( val : any, key : string | number ) => void, options? : TransactionOptions ){\n const isRoot = transactionApi.begin( this );\n this.each( iteratee );\n isRoot && transactionApi.commit( this );\n }\n\n // Apply bulk in-place object update in scope of ad-hoc transaction \n set( values : any, options? : TransactionOptions ) : this {\n if( values ){ \n const transaction = this._createTransaction( values, options );\n transaction && transaction.commit();\n } \n\n return this;\n }\n\n // Assign transactional object \"by value\", copying aggregated items.\n assignFrom( source : Transactional | Object ) : this {\n // Need to delay change events until change token willl by synced.\n this.transaction( () =>{\n this.set( ( source ).__inner_state__ || source, { merge : true } );\n\n // Synchronize change tokens\n const { _changeToken } = source as any;\n \n if( _changeToken ){\n this._changeToken = _changeToken;\n } \n });\n\n return this;\n }\n\n // Apply bulk object update without any notifications, and return open transaction.\n // Used internally to implement two-phase commit.\n // Returns null if there are no any changes.\n /** @private */ \n abstract _createTransaction( values : any, options? : TransactionOptions ) : Transaction | void\n \n // Parse function applied when 'parse' option is set for transaction.\n parse( data : any, options? : TransactionOptions ) : any { return data }\n\n // Convert object to the serializable JSON structure\n abstract toJSON( options? : object ) : {}\n\n /*******************\n * Traversals and member access\n */\n \n // Get object member by its key.\n abstract get( key : string ) : any\n\n // Get object member by symbolic reference.\n deepGet( reference : string ) : any {\n return resolveReference( this, reference, ( object, key ) => object.get ? object.get( key ) : object[ key ] );\n }\n\n //_isCollection : boolean\n\n // Return owner skipping collections.\n getOwner() : Owner {\n return this._owner;\n }\n\n // Store used when owner chain store lookup failed. Static value in the prototype. \n /** @private */\n _defaultStore : Transactional\n\n // Locate the closest store. Store object stops traversal by overriding this method. \n getStore() : Transactional {\n const { _owner } = this;\n return _owner ? _owner.getStore() : this._defaultStore;\n }\n\n\n /***************************************************\n * Iteration API\n */\n\n // Loop through the members. Must be efficiently implemented in container class.\n abstract each( iteratee : ( val : any, key : string | number ) => void, context? : any )\n\n // Map members to an array\n map( iteratee : ( val : any, key : string | number ) => T, context? : any ) : T[]{\n const arr : T[] = [],\n fun = context !== void 0 ? ( v, k ) => iteratee.call( context, v, k ) : iteratee;\n \n this.each( ( val, key ) => {\n const result = fun( val, key );\n if( result !== void 0 ) arr.push( result );\n } );\n\n return arr;\n }\n\n _endpoint : IOEndpoint\n _ioPromise : IOPromise\n\n hasPendingIO() : IOPromise { return this._ioPromise; }\n\n fetch( options? : object ) : IOPromise { throw new Error( \"Not implemented\" ); }\n\n getEndpoint() : IOEndpoint {\n return getOwnerEndpoint( this ) || this._endpoint;\n }\n\n // Map members to an object\n mapObject( iteratee : ( val : any, key : string | number ) => T, context? : any ) : { [ key : string ] : T }{\n const obj : { [ key : string ] : T } = {},\n fun = context !== void 0 ? ( v, k ) => iteratee.call( context, v, k ) : iteratee;\n \n this.each( ( val, key ) => {\n const result = iteratee( val, key );\n if( result !== void 0 ) obj[ key ] = result;\n } );\n\n return obj;\n }\n \n /*********************************\n * Validation API\n */\n\n // Lazily evaluated validation error\n /** @private */\n _validationError : ValidationError = void 0\n\n // Validate ownership tree and return valudation error \n get validationError() : ValidationError {\n const error = this._validationError || ( this._validationError = new ValidationError( this ) );\n return error.length ? error : null; \n }\n\n // Validate nested members. Returns errors count.\n /** @private */\n abstract _validateNested( errors : ChildrenErrors ) : number\n\n // Object-level validator. Returns validation error.\n validate( obj? : Transactional ) : any {}\n\n // Return validation error (or undefined) for nested object with the given key. \n getValidationError( key : string ) : any {\n var error = this.validationError;\n return ( key ? error && error.nested[ key ] : error ) || null;\n }\n\n // Get validation error for the given symbolic reference.\n deepValidationError( reference : string ) : any {\n return resolveReference( this, reference, ( object, key ) => object.getValidationError( key ) );\n }\n\n // Iterate through all validation errors across the ownership tree.\n eachValidationError( iteratee : ( error : any, key : string, object : Transactional ) => void ) : void {\n const { validationError } = this;\n validationError && validationError.eachError( iteratee, this );\n }\n\n // Check whenever member with a given key is valid. \n isValid( key : string ) : boolean {\n return !this.getValidationError( key );\n }\n\n valueOf() : Object { return this.cid; }\n toString(){ return this.cid; }\n\n // Get class name for an object instance. Works fine with ES6 classes definitions (not in IE).\n getClassName() : string {\n const { name } = this.constructor;\n if( name !== 'Subclass' ) return name;\n }\n\n // Logging interface for run time errors and warnings.\n abstract _log( level : string, text : string, value : any ) : void;\n}\n\nexport interface CloneOptions {\n // 'Pin store' shall assign this._defaultStore = this.getStore();\n pinStore? : boolean\n}\n\n// Owner must accept children update events. It's an only way children communicates with an owner.\n/** @private */\nexport interface Owner extends Traversable, Messenger {\n _onChildrenChange( child : Transactional, options : TransactionOptions ) : void;\n getOwner() : Owner\n getStore() : Transactional\n}\n\n// Transaction object used for two-phase commit protocol.\n// Must be implemented by subclasses.\n// Transaction must be created if there are actual changes and when markIsDirty returns true.\n/** @private */ \nexport interface Transaction {\n // Object transaction is being made on.\n object : Transactional\n\n // Send out change events, process update triggers, and close transaction.\n // Nested transactions must be marked with isNested flag (it suppress owner notification).\n commit( initiator? : Transactional )\n}\n\n// Options for distributed transaction \nexport interface TransactionOptions {\n // Invoke parsing \n parse? : boolean\n\n // Suppress change notifications and update triggers\n silent? : boolean\n\n // Update existing transactional members in place, or skip the update (ignored by models)\n merge? : boolean // =true\n\n // Should collections remove elements in set (ignored by models) \n remove? : boolean // =true\n\n // Always replace enclosed objects with new instances\n reset? : boolean // = false\n\n // Do not dispose aggregated members\n unset? : boolean\n\n validate? : boolean\n\n // `true` if the transaction is initiated as a result of IO operation\n ioUpdate? : boolean\n\n // The hint for IOEndpoint\n // If `true`, `record.save()` will behave as \"upsert\" operation for the records having id.\n upsert? : boolean\n}\n\n/**\n * Low-level transactions API. Must be used like this:\n * const isRoot = begin( record );\n * ...\n * isRoot && commit( record, options );\n * \n * When committing nested transaction, the flag must be set to true. \n * commit( object, options, isNested ) \n */\n\nexport const transactionApi = {\n // Start transaction. Return true if it's the root one.\n /** @private */\n begin( object : Transactional ) : boolean {\n return object._transaction ? false : ( object._transaction = true ); \n },\n\n // Mark object having changes inside of the current transaction.\n // Returns true whenever there notifications are required.\n /** @private */\n markAsDirty( object : Transactional, options : TransactionOptions ) : boolean {\n // If silent option is in effect, don't set isDirty flag.\n const dirty = !options.silent;\n if( dirty ) object._isDirty = options;\n \n // Reset version token.\n object._changeToken = {};\n\n // Object is changed, so validation must happen again. Clear the cache.\n object._validationError = void 0;\n\n return dirty;\n },\n\n // Commit transaction. Send out change event and notify owner. Returns true if there were changes.\n // Must be executed for the root transaction only.\n /** @private */\n commit( object : Transactional, initiator? : Transactional ){\n let originalOptions = object._isDirty;\n\n if( originalOptions ){\n // Send the sequence of change events, handling chained handlers.\n while( object._isDirty ){\n const options = object._isDirty;\n object._isDirty = null; \n trigger3( object, object._changeEventName, object, options, initiator );\n }\n \n // Mark transaction as closed.\n object._transaction = false;\n\n // Notify owner on changes out of transaction scope. \n const { _owner } = object; \n if( _owner && _owner !== initiator ){ // If it's the nested transaction, owner is already aware there are some changes.\n _owner._onChildrenChange( object, originalOptions );\n }\n }\n else{\n // No changes. Silently close transaction.\n object._isDirty = null;\n object._transaction = false;\n }\n },\n\n /************************************\n * Ownership management\n */\n\n // Add reference to the record.\n /** @private */\n aquire( owner : Owner, child : Transactional, key? : string ) : boolean {\n if( !child._owner ){\n child._owner = owner;\n child._ownerKey = key;\n return true;\n }\n\n return child._owner === owner;\n },\n\n // Remove reference to the record.\n /** @private */\n free( owner : Owner, child : Transactional ) : void {\n if( owner === child._owner ){\n child._owner = void 0;\n child._ownerKey = void 0;\n }\n }\n}\n\nfunction getOwnerEndpoint( self : Transactional ) : IOEndpoint {\n // Check if we are the member of the collection...\n const { collection } = self as any;\n if( collection ){\n return getOwnerEndpoint( collection );\n }\n\n // Now, if we're the member of the model...\n if( self._owner ){\n const { _endpoints } = self._owner as any;\n return _endpoints && _endpoints[ self._ownerKey ];\n }\n}\n","import { Transactional, Transaction, TransactionOptions, Owner, transactionApi } from \"../../transactions\"\nconst { begin : _begin, markAsDirty : _markAsDirty, commit } = transactionApi;\n\nimport { eventsApi } from '../../object-plus'\nconst { trigger3 } = eventsApi;\n\nexport interface ConstructorsMixin {\n Attributes : AttributesConstructor\n AttributesCopy : AttributesCopyConstructor\n}\n\nexport interface ConstructorOptions extends TransactionOptions{\n clone? : boolean\n}\n\nexport type AttributesConstructor = new ( record : AttributesContainer, values : object, options : TransactionOptions ) => AttributesValues;\nexport type AttributesCopyConstructor = new ( values : object ) => AttributesValues;\n\nexport interface AttributesContainer extends Transactional, Owner, ConstructorsMixin {\n // Attribute descriptors.\n _attributes : AttributesDescriptors\n\n // Attribute values.\n attributes : AttributesValues\n\n // Previous attribute values.\n _previousAttributes : AttributesValues\n\n // Changed attributes cache. \n _changedAttributes : AttributesValues\n}\n\nexport interface AttributesValues {\n [ name : string ] : any\n}\n\nexport interface AttributesDescriptors {\n [ name : string ] : AttributeUpdatePipeline\n}\n\nexport interface AttributeUpdatePipeline{\n doUpdate( value, record : AttributesContainer, options : TransactionOptions, nested? : Transaction[] ) : boolean\n}\n\n // Optimized single attribute transactional update. To be called from attributes setters\n // options.silent === false, parse === false. \nexport function setAttribute( record : AttributesContainer, name : string, value : any ) : void {\n // Open the transaction.\n const isRoot = begin( record ),\n options = {};\n\n // Update attribute. \n if( record._attributes[ name ].doUpdate( value, record, options ) ){\n // Notify listeners on changes.\n markAsDirty( record, options );\n trigger3( record, 'change:' + name, record, record.attributes[ name ], options );\n }\n\n // Close the transaction.\n isRoot && commit( record );\n}\n\nfunction begin( record : AttributesContainer ){\n if( _begin( record ) ){\n record._previousAttributes = new record.AttributesCopy( record.attributes );\n record._changedAttributes = null;\n return true;\n }\n \n return false;\n}\n\nfunction markAsDirty( record : AttributesContainer, options : TransactionOptions ){\n // Need to recalculate changed attributes, when we have nested set in change:attr handler\n if( record._changedAttributes ){\n record._changedAttributes = null;\n }\n\n return _markAsDirty( record, options );\n}\n\n/**\n * TODO: There's an opportunity to create an optimized pipeline for primitive types and Date, which makes the majority\n * of attributes. It might create the major speedup.\n * \n * Create the dedicated pipeline for owned and shared attributes as well.\n * \n * Three elements of the pipeline:\n * - from constructor\n * - from assignment\n * - from `set`\n */\n\nexport const UpdateRecordMixin = {\n// Need to override it here, since begin/end transaction brackets are overriden. \n transaction( this : AttributesContainer, fun : ( self : AttributesContainer ) => void, options : TransactionOptions = {} ) : void{\n const isRoot = begin( this );\n fun.call( this, this );\n isRoot && commit( this );\n },\n \n // Handle nested changes. TODO: propagateChanges == false, same in transaction.\n _onChildrenChange( child : Transactional, options : TransactionOptions ) : void {\n const { _ownerKey } = child,\n attribute = this._attributes[ _ownerKey ];\n\n if( !attribute /* TODO: Must be an opposite, likely the bug */ || attribute.propagateChanges ) this.forceAttributeChange( _ownerKey, options );\n },\n\n // Simulate attribute change \n forceAttributeChange( key : string, options : TransactionOptions = {} ){\n // Touch an attribute in bounds of transaction\n const isRoot = begin( this );\n\n if( markAsDirty( this, options ) ){\n trigger3( this, 'change:' + key, this, this.attributes[ key ], options );\n }\n \n isRoot && commit( this );\n },\n\n _createTransaction( this : AttributesContainer, a_values : {}, options : TransactionOptions = {} ) : Transaction {\n const isRoot = begin( this ),\n changes : string[] = [],\n nested : RecordTransaction[]= [],\n { _attributes } = this,\n values = options.parse ? this.parse( a_values, options ) : a_values;\n\n let unknown;\n\n if( shouldBeAnObject( this, values ) ){\n for( let name in values ){\n const spec = _attributes[ name ];\n\n if( spec ){\n if( spec.doUpdate( values[ name ], this, options, nested ) ){\n changes.push( name );\n }\n }\n else{\n unknown || ( unknown = [] );\n unknown.push( `'${ name }'` );\n }\n }\n\n if( unknown ){\n // this._log( 'warn', `Undefined attributes ${ unknown.join(', ')} are ignored!`, values );\n }\n }\n \n if( changes.length && markAsDirty( this, options ) ){\n return new RecordTransaction( this, isRoot, nested, changes );\n }\n \n // No changes, but there might be silent attributes with open transactions.\n for( let pendingTransaction of nested ){\n pendingTransaction.commit( this );\n }\n\n isRoot && commit( this );\n }\n};\n\n// One of the main performance tricks of Type-R.\n// Create loop unrolled constructors for internal attribute hash,\n// so the hidden class JIT optimization will be engaged and they will become static structs.\n// It dramatically improves record performance.\nexport function constructorsMixin( attrDefs : AttributesDescriptors ) : ConstructorsMixin {\n const attrs = Object.keys( attrDefs );\n\n const AttributesCopy : AttributesCopyConstructor = new Function( 'values', `\n ${ attrs.map( attr =>`\n this.${ attr } = values.${ attr };\n `).join( '' ) }\n `) as any;\n\n AttributesCopy.prototype = Object.prototype;\n\n const Attributes : AttributesConstructor = new Function( 'record', 'values', 'options', `\n var _attrs = record._attributes;\n\n ${ attrs.map( attr =>`\n this.${ attr } = _attrs.${ attr }.doInit( values.${ attr }, record, options );\n `).join( '' ) }\n `) as any;\n\n Attributes.prototype = Object.prototype;\n\n return { Attributes, AttributesCopy };\n}\n\nexport function shouldBeAnObject( record : AttributesContainer, values : object ){\n if( values && values.constructor === Object ) return true;\n\n record._log( 'warn', 'update with non-object is ignored!', { values } );\n return false;\n}\n\n// Transaction class. Implements two-phase transactions on object's tree. \n// Transaction must be created if there are actual changes and when markIsDirty returns true. \nexport class RecordTransaction implements Transaction {\n // open transaction\n constructor( public object : AttributesContainer,\n public isRoot : boolean,\n public nested : Transaction[],\n public changes : string[] ){}\n\n // commit transaction\n commit( initiator? : AttributesContainer ) : void {\n const { nested, object, changes } = this;\n\n // Commit all pending nested transactions...\n for( let transaction of nested ){ \n transaction.commit( object );\n }\n\n // Notify listeners on attribute changes...\n // Transaction is never created when silent option is set, so just send events out.\n const { attributes, _isDirty } = object;\n for( let key of changes ){\n trigger3( object, 'change:' + key, object, attributes[ key ], _isDirty );\n }\n\n this.isRoot && commit( object, initiator );\n }\n}","import { setAttribute, AttributesContainer, AttributeUpdatePipeline, RecordTransaction } from './updates'\nimport { tools } from '../../object-plus'\nimport { Owner, Transactional, TransactionOptions } from '../../transactions'\nimport { IOEndpoint } from '../../io-tools'\n\nconst { notEqual, assign} = tools;\n\ndeclare global {\n interface Function {\n _attribute : typeof AnyType\n }\n}\n\nexport type Transform = ( this : AnyType, next : any, prev : any, record : AttributesContainer, options : TransactionOptions ) => any;\nexport type ChangeHandler = ( this : AnyType, next : any, prev : any, record : AttributesContainer, options : TransactionOptions ) => void;\n\nexport interface AttributeOptions {\n _attribute? : typeof AnyType\n validate? : ( record : AttributesContainer, value : any, key : string ) => any\n isRequired? : boolean\n changeEvents? : boolean\n\n endpoint? : IOEndpoint\n\n type? : Function\n value? : any\n hasCustomDefault? : boolean\n\n parse? : Parse\n toJSON? : AttributeToJSON\n \n getHooks? : GetHook[]\n transforms? : Transform[]\n changeHandlers? : ChangeHandler[]\n\n _onChange? : ChangeAttrHandler\n}\n\nexport type Parse = ( value : any, key : string ) => any;\nexport type GetHook = ( value : any, key : string ) => any;\nexport type AttributeToJSON = ( value : any, key : string ) => any\nexport type AttributeParse = ( value : any, key : string ) => any\nexport type ChangeAttrHandler = ( ( value : any, attr : string ) => void ) | string;\n\n// TODO: interface differs from options, do something obout it\nconst emptyOptions : TransactionOptions = {};\n\n/**\n * Typeless attribute. Is the base class for all other attributes.\n */\nexport class AnyType implements AttributeUpdatePipeline {\n // Factory method to create attribute from options \n static create( options : AttributeOptions, name : string ) : AnyType {\n const type = options.type,\n AttributeCtor = options._attribute || ( type ? type._attribute : AnyType );\n\n return new AttributeCtor( name, options );\n }\n /**\n * Update pipeline functions\n * =========================\n *\n * Stage 0. canBeUpdated( value )\n * - presence of this function implies attribute's ability to update in place.\n */\n canBeUpdated( prev, next, options : TransactionOptions ) : any {}\n\n /**\n * Stage 1. Transform stage\n */\n transform( next : any, prev : any, model : AttributesContainer, options : TransactionOptions ) : any { return next; }\n\n // convert attribute type to `this.type`.\n convert( next : any, prev : any, model : AttributesContainer, options : TransactionOptions ) : any { return next; }\n\n /**\n * Stage 2. Check if attr value is changed\n */\n isChanged( a : any, b : any ) : boolean {\n return notEqual( a, b );\n }\n\n /**\n * Stage 3. Handle attribute change\n */\n handleChange( next : any, prev : any, model : AttributesContainer, options : TransactionOptions ) {}\n\n /**\n * End update pipeline definitions.\n */\n\n // create empty object passing backbone options to constructor...\n create() { return void 0; }\n\n // generic clone function for typeless attributes\n // Must be overriden in sublass\n clone( value : any, record : AttributesContainer ) {\n return value;\n }\n\n dispose( record : AttributesContainer, value : any ) : void {\n this.handleChange( void 0, value, record, emptyOptions );\n }\n\n validate( record : AttributesContainer, value : any, key : string ){}\n\n toJSON( value, key, options? : object ) {\n return value && value.toJSON ? value.toJSON( options ) : value;\n }\n\n createPropertyDescriptor() : PropertyDescriptor | void {\n const { name, getHook } = this;\n\n if( name !== 'id' ){\n return {\n // call to optimized set function for single argument.\n set( value ){\n setAttribute( this, name, value );\n },\n\n // attach get hook to the getter function, if it present\n get : (\n getHook ?\n function() {\n return getHook.call( this, this.attributes[ name ], name );\n } :\n function() { return this.attributes[ name ]; }\n )\n }\n }\n }\n\n value : any\n\n // Used as global default value for the given metatype\n static defaultValue : any;\n\n type : Function\n\n initialize( name : string, options : TransactionOptions ){}\n\n options : AttributeOptions\n\n doInit( value, record : AttributesContainer, options : TransactionOptions ){\n const v = value === void 0 ? this.defaultValue() : value,\n x = this.transform( v, void 0, record, options );\n \n this.handleChange( x, void 0, record, options );\n return x;\n }\n\n doUpdate( value, record : AttributesContainer, options : TransactionOptions, nested? : RecordTransaction[] ){\n const { name } = this,\n { attributes } = record,\n prev = attributes[ name ];\n\n const next = this.transform( value, prev, record, options );\n attributes[ name ] = next;\n\n if( this.isChanged( next, prev ) ) {\n // Do the rest of the job after assignment\n this.handleChange( next, prev, record, options );\n return true;\n }\n\n return false;\n }\n\n propagateChanges : boolean\n\n _log( level : tools.LogLevel, text : string, value, record : AttributesContainer ){\n tools.log( level, `[Attribute Update Error] ${ record.getClassName() }.${ this.name }: ` + text, {\n 'Record' : record,\n 'Attribute definition' : this,\n 'Prev. value' : record.attributes[ this.name ],\n 'New value' : value\n });\n }\n\n defaultValue(){\n return this.value;\n }\n\n constructor( public name : string, a_options : AttributeOptions ) { \n // Save original options...\n this.options = a_options;\n\n // Clone options.\n const options : AttributeOptions = assign( { getHooks : [], transforms : [], changeHandlers : [] }, a_options );\n options.getHooks = options.getHooks.slice();\n options.transforms = options.transforms.slice();\n options.changeHandlers = options.changeHandlers.slice();\n\n const {\n value, type, parse, toJSON, changeEvents,\n validate, getHooks, transforms, changeHandlers\n } = options;\n\n // Initialize default value...\n this.value = value;\n this.type = type;\n\n // TODO: An opportunity to optimize for attribute subtype.\n if( !options.hasCustomDefault && type ){\n this.defaultValue = this.create;\n }\n else if( tools.isValidJSON( value ) ){ \n // JSON literals must be deep copied.\n this.defaultValue = new Function( `return ${ JSON.stringify( value ) };` ) as any;\n }\n else{\n this.defaultValue = this.defaultValue;\n }\n\n // Changes must be bubbled when they are not disabled for an attribute and transactional object.\n this.propagateChanges = changeEvents !== false;\n\n this.toJSON = toJSON === void 0 ? this.toJSON : toJSON;\n\n this.validate = validate || this.validate;\n \n if( options.isRequired ){\n this.validate = wrapIsRequired( this.validate );\n }\n\n /**\n * Assemble pipelines...\n */\n\n // `convert` is default transform, which is always present...\n transforms.unshift( this.convert );\n\n // Get hook from the attribute will be used first...\n if( this.get ) getHooks.unshift( this.get );\n\n // let subclasses configure the pipeline...\n this.initialize.call( this, options );\n\n // let attribute spec configure the pipeline...\n if( getHooks.length ){\n const getHook = this.getHook = getHooks.reduce( chainGetHooks );\n\n const { validate } = this;\n this.validate = function( record : AttributesContainer, value : any, key : string ){\n return validate.call( this, record, getHook.call( record, value, key ), key );\n }\n }\n \n this.transform = transforms.length ? transforms.reduce( chainTransforms ) : this.transform;\n \n this.handleChange = changeHandlers.length ? changeHandlers.reduce( chainChangeHandlers ) : this.handleChange;\n\n // Attribute-level parse transform are attached as update hooks modifiers...\n const { doInit, doUpdate } = this;\n this.doInit = parse ? function( value, record : AttributesContainer, options : TransactionOptions ){\n return doInit.call( this, options.parse && value !== void 0 ? parse.call( record, value, this.name ) : value, record, options );\n } : doInit;\n\n this.doUpdate = parse ? function( value, record : AttributesContainer, options : TransactionOptions, nested? : RecordTransaction[] ){\n return doUpdate.call( this, options.parse && value !== void 0 ? parse.call( record, value, this.name ) : value, record, options, nested );\n } : doUpdate;\n }\n\n getHook : ( value, key : string ) => any = null\n get : ( value, key : string ) => any\n}\n\n\nfunction chainGetHooks( prevHook : GetHook, nextHook : GetHook ) : GetHook {\n return function( value, name ) {\n return nextHook.call( this, prevHook.call( this, value, name ), name );\n }\n}\n\nfunction chainTransforms( prevTransform : Transform, nextTransform : Transform ) : Transform {\n return function( next, prev, record, options ) {\n return nextTransform.call( this, prevTransform.call( this, next, prev, record, options ), prev, record, options );\n }\n}\n\nfunction chainChangeHandlers( prevHandler : ChangeHandler, nextHandler : ChangeHandler ) : ChangeHandler {\n return function( next, prev, record, options ) {\n prevHandler.call( this, next, prev, record, options );\n nextHandler.call( this, next, prev, record, options );\n }\n}\n\nfunction wrapIsRequired( validate ){\n return function( record : AttributesContainer, value : any, key : string ){\n return value ? validate.call( this, record, value, key ) : 'Required';\n }\n}","import { AnyType } from './any'\nimport { Owner, transactionApi, Transactional, ItemsBehavior, TransactionOptions } from '../../transactions'\nimport { tools } from '../../object-plus'\nimport { AttributesContainer, ConstructorOptions } from './updates'\nimport { ValidationError } from '../../validation'\n\nconst { free, aquire } = transactionApi;\n\nexport class AggregatedType extends AnyType {\n type : typeof Transactional\n\n clone( value : Transactional ) : Transactional {\n return value ? value.clone() : value;\n }\n\n toJSON( x, key : string, options : object ){ return x && x.toJSON( options ); }\n\n doInit( value, record : AttributesContainer, options : ConstructorOptions ){\n const v = options.clone ? this.clone( value ) : (\n value === void 0 ? this.defaultValue() : value\n );\n\n const x = this.transform( v, void 0, record, options );\n this.handleChange( x, void 0, record, options );\n return x;\n }\n\n doUpdate( value, record, options, nested : any[] ){ // Last to things can be wrapped to an object, either transaction or ad-hoc\n const key = this.name, { attributes } = record; \n const prev = attributes[ key ];\n let update;\n\n // This can be moved to transactional attribute. And chained with the rest.\n if( update = this.canBeUpdated( prev, value, options ) ) { // todo - skip empty updates.\n const nestedTransaction = prev._createTransaction( update, options );\n if( nestedTransaction ){\n if( nested ){\n nested.push( nestedTransaction );\n }\n else{\n nestedTransaction.commit( record );\n }\n\n if( this.propagateChanges ) return true;\n }\n\n return false;\n }\n\n const next = this.transform( value, prev, record, options );\n attributes[ key ] = next;\n\n if( this.isChanged( next, prev ) ) { // Primitives and nested comparison can be inlined.\n // Do the rest of the job after assignment\n this.handleChange( next, prev, record, options );\n\n return true;\n }\n\n return false;\n }\n\n canBeUpdated( prev : Transactional, next : any, options : TransactionOptions ) : any {\n // If an object already exists, and new value is of incompatible type, let object handle the update.\n if( prev && next != null ){\n if( next instanceof this.type ){\n // In case if merge option explicitly specified, force merge.\n if( options.merge ) return next.__inner_state__;\n }\n else{\n return next;\n }\n }\n }\n\n convert( next : any, prev : any, record : AttributesContainer, options : TransactionOptions ) : Transactional {\n // Invoke class factory to handle abstract classes\n if( next == null ) return next;\n \n if( next instanceof this.type ){\n if( next._shared && !( next._shared & ItemsBehavior.persistent ) ) { // TODO: think more about shared types assignment compatibility. \n this._log( 'error', 'aggregated collection attribute is assigned with shared collection', next, record );\n }\n\n // With explicit 'merge' option we need to clone an object if its previous value was 'null'.\n // This is an only case we could be here when merge === true.\n return options.merge ? next.clone() : next;\n }\n\n return this.type.create( next, options );\n }\n\n dispose ( record : AttributesContainer, value : Transactional ){\n if( value ){\n this.handleChange( void 0, value, record, {} );\n }\n }\n\n validate( record : AttributesContainer, value : Transactional ) : ValidationError {\n var error = value && value.validationError;\n if( error ) return error;\n }\n\n create() : Transactional {\n return (this.type).create(); // this the subclass of Transactional here.\n }\n\n initialize( options ){\n options.changeHandlers.unshift( this._handleChange );\n }\n\n _handleChange( next : Transactional, prev : Transactional, record : AttributesContainer, options : TransactionOptions ){\n if( prev ){\n free( record, prev );\n options.unset || prev.dispose();\n } \n \n if( next && !aquire( record, next, this.name ) ){\n this._log( 'error', 'aggregated attribute assigned with object already having an owner', next, record );\n }\n }\n}","/**\n * Type spec engine. Declare attributes using chainable syntax,\n * and returns object with spec.\n */\nimport { Transactional } from '../../transactions'\nimport { ChangeAttrHandler, AttributeOptions, Parse } from './any'\nimport { AttributesContainer } from './updates'\nimport { EventMap, EventsDefinition, definitionDecorator, tools } from '../../object-plus'\nimport { IOEndpoint } from '../../io-tools'\n\nconst { assign } = tools;\n\nexport interface AttributeCheck {\n ( value : any, key : string ) : boolean\n error? : any\n}\n\nexport class ChainableAttributeSpec {\n options : AttributeOptions;\n\n constructor( options : AttributeOptions ) {\n // Shallow copy options, fill it with defaults.\n this.options = { getHooks : [], transforms : [], changeHandlers : []};\n if( options ) assign( this.options, options );\n }\n\n check( check : AttributeCheck, error : any ) : ChainableAttributeSpec {\n function validate( model, value, name ){\n if( !check.call( model, value, name ) ){\n const msg = error || check.error || name + ' is not valid';\n return typeof msg === 'function' ? msg.call( model, name ) : msg;\n }\n }\n\n const prev = this.options.validate;\n\n return this.metadata({\n validate : prev ? (\n function( model, value, name ){\n return prev( model, value, name ) || validate( model, value, name );\n }\n ) : validate\n });\n }\n\n get asProp(){\n return definitionDecorator( 'attributes', this );\n }\n\n get as(){ return this.asProp; }\n\n get isRequired() : ChainableAttributeSpec {\n return this.metadata({ isRequired : true }); \n }\n\n endpoint( endpoint : IOEndpoint ){\n return this.metadata({ endpoint });\n }\n\n watcher( ref : string | ( ( value : any, key : string ) => void ) ) : ChainableAttributeSpec {\n return this.metadata({ _onChange : ref });\n }\n\n // Attribute-specific parse transform\n parse( fun : Parse ) : ChainableAttributeSpec {\n return this.metadata({ parse : fun });\n }\n\n toJSON( fun ) : ChainableAttributeSpec {\n return this.metadata({\n toJSON : typeof fun === 'function' ? fun : ( fun ? ( x, k, o ) => x && x.toJSON( o ) : emptyFunction ) \n });\n }\n\n // Attribute get hook.\n get( fun ) : ChainableAttributeSpec {\n return this.metadata({\n getHooks : this.options.getHooks.concat( fun )\n });\n }\n\n // Attribute set hook.\n set( fun ) : ChainableAttributeSpec {\n function handleSetHook( next, prev, record : AttributesContainer, options ) {\n if( this.isChanged( next, prev ) ) {\n const changed = fun.call( record, next, this.name );\n return changed === void 0 ? prev : this.convert( changed, prev, record, options );\n }\n\n return prev;\n }\n\n return this.metadata({\n transforms : this.options.transforms.concat( handleSetHook )\n });\n }\n\n changeEvents( events : boolean ) : ChainableAttributeSpec {\n return this.metadata({ changeEvents : events });\n }\n\n // Subsribe to events from an attribute.\n events( map : EventsDefinition ) : ChainableAttributeSpec {\n const eventMap = new EventMap( map );\n\n function handleEventsSubscribtion( next, prev, record : AttributesContainer ){\n prev && prev.trigger && eventMap.unsubscribe( record, prev );\n\n next && next.trigger && eventMap.subscribe( record, next );\n }\n\n return this.metadata({\n changeHandlers : this.options.changeHandlers.concat( handleEventsSubscribtion )\n });\n }\n\n // Creates a copy of the spec.\n get has() : ChainableAttributeSpec {\n return this;\n }\n\n metadata( options : AttributeOptions ) : ChainableAttributeSpec {\n const cloned = new ChainableAttributeSpec( this.options );\n assign( cloned.options, options );\n return cloned;\n }\n\n value( x ) : ChainableAttributeSpec {\n return this.metadata({ value : x, hasCustomDefault : true });\n }\n\n static from( spec : any ) : ChainableAttributeSpec {\n let attrSpec : ChainableAttributeSpec;\n\n if( typeof spec === 'function' ) {\n attrSpec = spec.has;\n }\n else if( spec && spec instanceof ChainableAttributeSpec ) {\n attrSpec = spec;\n }\n else{\n // Infer type from value.\n const type = inferType( spec );\n \n // Transactional types inferred from values must have shared type. \n if( type && type.prototype instanceof Transactional ){\n attrSpec = (type).shared.value( spec );\n }\n // All others will be created in regular way.\n else{\n attrSpec = new ChainableAttributeSpec({ type : type, value : spec, hasCustomDefault : true });\n }\n }\n \n return attrSpec;\n }\n}\n\nfunction emptyFunction(){}\n\nexport function type( this : void, spec : ChainableAttributeSpec | Function ) : ChainableAttributeSpec {\n return spec instanceof ChainableAttributeSpec ? spec : new ChainableAttributeSpec( {\n type : spec,\n value : spec._attribute.defaultValue,\n hasCustomDefault : spec._attribute.defaultValue !== void 0\n } );;\n}\n\ndeclare global {\n interface Function{\n value : ( x : any ) => ChainableAttributeSpec;\n isRequired : ChainableAttributeSpec;\n asProp : PropertyDecorator\n has : ChainableAttributeSpec;\n }\n}\n\nFunction.prototype.value = function( x ) {\n return new ChainableAttributeSpec( { type : this, value : x, hasCustomDefault : true } );\n};\n\nObject.defineProperty( Function.prototype, 'isRequired', {\n get() { return this._isRequired || this.has.isRequired; },\n set( x ){ this._isRequired = x; }\n});\n\nObject.defineProperty( Function.prototype, 'asProp', {\n get() { return this.has.asProp; },\n});\n\nObject.defineProperty( Function.prototype, 'has', {\n get() {\n // workaround for sinon.js and other libraries overriding 'has'\n return this._has || type( this );\n },\n\n set( value ) { this._has = value; }\n} );\n\nfunction inferType( value : {} ) : Function {\n switch( typeof value ) {\n case 'number' :\n return Number;\n case 'string' :\n return String;\n case 'boolean' :\n return Boolean;\n case 'undefined' :\n return void 0;\n case 'object' :\n return value ? value.constructor : void 0;\n }\n}\n","/**\n * Date attribute type.\n * \n * Implements validation, cross-browser compatibility fixes, variety of Date serialization formats,\n * and optimized update pipeline.\n */\nimport { AnyType } from './any'\nimport { tools } from '../../object-plus'\nimport { AttributesContainer } from './updates'\nimport { TransactionOptions } from '../../transactions'\nimport { ChainableAttributeSpec } from './attrDef'\n\nconst DateProto = Date.prototype;\n\n// Date Attribute\n/** @private */\nexport class DateType extends AnyType {\n create(){\n return new Date();\n }\n \n convert( next : any, a, record ){\n if( next == null || next instanceof Date ) return next;\n\n const date = new Date( next ),\n timestamp = date.getTime();\n\n if( timestamp !== timestamp ){\n this._log( 'warn', 'assigned with Invalid Date', next, record );\n }\n\n return date;\n }\n\n validate( model, value, name ) {\n if( value != null ){\n const timestamp = value.getTime(); \n if( timestamp !== timestamp ) return name + ' is Invalid Date';\n }\n }\n\n toJSON( value ) { return value && value.toISOString(); }\n\n isChanged( a, b ) { return ( a && a.getTime() ) !== ( b && b.getTime() ); }\n\n doInit( value, record : AttributesContainer, options : TransactionOptions ){\n // Date don't have handleChanges step.\n return this.transform( value === void 0 ? this.defaultValue() : value, void 0, record, options );\n }\n\n doUpdate( value, record, options, nested ){\n const { name } = this,\n { attributes } = record,\n prev = attributes[ name ];\n \n // Date don't have handleChanges step.\n return this.isChanged( prev , attributes[ name ] = this.transform( value, prev, record, options ) );\n }\n\n clone( value ) { return value && new Date( value.getTime() ); }\n dispose(){}\n}\n\nDate._attribute = DateType;\n\nconst msDatePattern = /\\/Date\\(([0-9]+)\\)\\//;\n\nexport class MSDateType extends DateType {\n convert( next ) {\n if( typeof next === 'string' ){\n const msDate = msDatePattern.exec( next );\n if( msDate ){\n return new Date( Number( msDate[ 1 ] ) );\n }\n }\n\n return DateType.prototype.convert.apply( this, arguments );\n }\n\n toJSON( value ) { return value && `/Date(${ value.getTime() })/`; }\n}\n\nexport class TimestampType extends DateType {\n toJSON( value ) { return value && value.getTime(); }\n}\n\ndeclare global {\n interface DateConstructor {\n microsoft : ChainableAttributeSpec\n timestamp : ChainableAttributeSpec\n }\n}\n\nObject.defineProperties( Date, {\n microsoft : {\n get(){\n return new ChainableAttributeSpec({\n type : Date,\n _attribute : MSDateType\n })\n }\n },\n\n timestamp : {\n get(){\n return new ChainableAttributeSpec({\n type : Date,\n _attribute : TimestampType\n })\n }\n }\n});\n\n// If ISO date is not supported by date constructor (such as in Safari), polyfill it.\nfunction supportsDate( date ){\n return !isNaN( ( new Date( date ) ).getTime() );\n}\n\nif( !supportsDate('2011-11-29T15:52:30.5') ||\n !supportsDate('2011-11-29T15:52:30.52') ||\n !supportsDate('2011-11-29T15:52:18.867') ||\n !supportsDate('2011-11-29T15:52:18.867Z') ||\n !supportsDate('2011-11-29T15:52:18.867-03:30') ){\n\n DateType.prototype.convert = function( value ){\n return value == null || value instanceof Date ? value : new Date( safeParseDate( value ) );\n }\n}\n\nconst numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ],\n isoDatePattern = /^(\\d{4}|[+\\-]\\d{6})(?:-(\\d{2})(?:-(\\d{2}))?)?(?:T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{3}))?)?(?:(Z)|([+\\-])(\\d{2})(?::(\\d{2}))?)?)?$/;\n\nfunction safeParseDate( date : string ) : number {\n var timestamp, struct : any[], minutesOffset = 0;\n\n if( ( struct = isoDatePattern.exec( date )) ) {\n // avoid NaN timestamps caused by undefined values being passed to Date.UTC\n for( var i = 0, k; ( k = numericKeys[ i ] ); ++i ) {\n struct[ k ] = +struct[ k ] || 0;\n }\n\n // allow undefined days and months\n struct[ 2 ] = (+struct[ 2 ] || 1) - 1;\n struct[ 3 ] = +struct[ 3 ] || 1;\n\n if( struct[ 8 ] !== 'Z' && struct[ 9 ] !== undefined ) {\n minutesOffset = struct[ 10 ] * 60 + struct[ 11 ];\n\n if( struct[ 9 ] === '+' ) {\n minutesOffset = 0 - minutesOffset;\n }\n }\n\n timestamp =\n Date.UTC( struct[ 1 ], struct[ 2 ], struct[ 3 ], struct[ 4 ], struct[ 5 ] + minutesOffset, struct[ 6 ],\n struct[ 7 ] );\n }\n else {\n timestamp = Date.parse( date );\n }\n\n return timestamp;\n}","/**\n * Built-in JSON types attributes: Object, Array, Number, String, Boolean, and immutable class.\n * \n * Adds type assertions, default validation, and optimized update pipeline.\n */\n\nimport { AnyType } from './any'\nimport { tools } from '../../object-plus'\nimport { AttributesContainer } from './updates'\nimport { TransactionOptions } from '../../transactions'\n\n/**\n * Custom class must be immutable class which implements toJSON() method\n * with a constructor taking json.\n */\nclass ImmutableClassType extends AnyType {\n type : new ( value? : any ) => {}\n\n create(){\n return new this.type();\n }\n\n convert( next : any ) : any {\n return next == null || next instanceof this.type ? next : new this.type( next );\n }\n\n toJSON( value, key? : string, options? : object ){\n return value && value.toJSON ? value.toJSON( options ) : value;\n }\n\n clone( value ) {\n return new this.type( this.toJSON( value ) );\n }\n\n isChanged( a, b ){\n return a !== b;\n }\n}\n\nFunction.prototype._attribute = ImmutableClassType;\n\n/**\n * Optimized attribute of primitive type.\n * \n * Primitives has specialized simplified pipeline.\n */\nexport class PrimitiveType extends AnyType {\n type : NumberConstructor | StringConstructor | BooleanConstructor\n\n dispose(){}\n create() { return this.type(); }\n\n toJSON( value ) { return value; }\n\n convert( next ) { return next == null ? next : this.type( next ); }\n\n isChanged( a, b ) { return a !== b; }\n\n clone( value ) { return value; }\n\n doInit( value, record : AttributesContainer, options : TransactionOptions ){\n return this.transform( value === void 0 ? this.value : value, void 0, record, options );\n }\n\n doUpdate( value, record, options, nested ){\n const { name } = this,\n { attributes } = record,\n prev = attributes[ name ];\n \n return prev !== ( attributes[ name ] = this.transform( value, prev, record, options ) );\n }\n\n initialize(){\n if( !this.options.hasCustomDefault ){\n this.value = this.type();\n }\n }\n}\n\nBoolean._attribute = String._attribute = PrimitiveType;\n\n// Number type with special validation algothim.\n/** @private */ \nexport class NumericType extends PrimitiveType {\n type : NumberConstructor\n\n create(){\n return 0;\n }\n\n convert( next, prev?, record? ) {\n const num = next == null ? next : this.type( next );\n\n if( num !== num ){\n this._log( 'warn', 'assigned with Invalid Number', next, record );\n }\n \n return num;\n }\n\n validate( model, value, name ) {\n // Whatever is not symmetrically serializable to JSON, is not valid by default.\n if( value != null && !isFinite( value ) ) {\n return name + ' is not valid number';\n }\n }\n}\n\nNumber._attribute = NumericType;\n\n/**\n * Add Number.integer attrubute type\n */\ndeclare global {\n interface NumberConstructor {\n integer : Function\n }\n\n interface Window {\n Integer : Function;\n }\n}\n\nfunction Integer( x ){\n return x ? Math.round( x ) : 0;\n}\nInteger._attribute = NumericType;\nNumber.integer = Integer;\n\n\nif( typeof window !== 'undefined' ){\n window.Integer = Number.integer;\n}\n\n/**\n * Compatibility wrapper for Array type.\n * @private\n */ \nexport class ArrayType extends AnyType {\n toJSON( value ) { return value; }\n dispose(){}\n create(){ return []; }\n\n convert( next, prev, record ) {\n // Fix incompatible constructor behaviour of Array...\n if( next == null || Array.isArray( next ) ) return next;\n\n this._log( 'warn', 'assignment of non-array to Array attribute is ignored', next, record );\n\n return [];\n }\n\n clone( value ){\n return value && value.slice();\n }\n}\n\nArray._attribute = ArrayType;\n\nexport class ObjectType extends AnyType {\n create(){ return {}; }\n\n convert( next, prev, record ) {\n if( next == null || typeof next === 'object' ) return next;\n \n this._log( 'warn', 'assignment of non-object to Object attribute is ignored', next, record );\n return {};\n }\n}\n\nObject._attribute = ObjectType;\n\nexport function doNothing(){}\n\nexport class FunctionType extends AnyType {\n // Functions are not serialized.\n toJSON( value ) { return void 0; }\n create(){ return doNothing; }\n dispose(){}\n\n convert( next, prev, record ) {\n // Fix incompatible constructor behaviour of Function...\n if( next == null || typeof next === 'function' ) return next;\n\n this._log( 'warn', 'assigned with non-function', next, record );\n\n return doNothing;\n }\n\n // Functions are not cloned.\n clone( value ){ return value; }\n}\n\nFunction._attribute = FunctionType;","import { AnyType } from './any'\nimport { AttributesContainer, ConstructorOptions } from './updates'\nimport { ItemsBehavior, Owner, transactionApi, Transactional, TransactionOptions } from '../../transactions' \nimport { tools, eventsApi } from '../../object-plus'\n\nconst { on, off } = eventsApi,\n { free, aquire } = transactionApi;\n\n/************************\n * Shared attribute definition.\n * - Not serialized.\n * - Listening to the changes.\n * - Doesn't take ownership when assigned with object of proper type.\n * - Takes ownership on objects which are converted.\n */\n\nconst shareAndListen = ItemsBehavior.listen | ItemsBehavior.share;\n\n/** @private */\nexport class SharedType extends AnyType {\n type : typeof Transactional\n\n doInit( value, record : AttributesContainer, options : ConstructorOptions ){\n const v = options.clone ? this.clone( value, record ) : (\n value === void 0 ? this.defaultValue() : value\n );\n\n const x = this.transform( v, void 0, record, options );\n this.handleChange( x, void 0, record, options );\n return x;\n }\n\n doUpdate( value, record, options, nested : any[] ){ // Last to things can be wrapped to an object, either transaction or ad-hoc\n const key = this.name, { attributes } = record; \n const prev = attributes[ key ];\n let update;\n\n // This can be moved to transactional attribute. And chained with the rest.\n if( update = this.canBeUpdated( prev, value, options ) ) { // todo - skip empty updates.\n const nestedTransaction = prev._createTransaction( update, options );\n if( nestedTransaction ){\n if( nested ){\n nested.push( nestedTransaction );\n }\n else{\n nestedTransaction.commit( record );\n }\n\n if( this.propagateChanges ) return true;\n }\n\n return false;\n }\n\n const next = this.transform( value, prev, record, options );\n attributes[ key ] = next;\n\n if( this.isChanged( next, prev ) ) { // Primitives and nested comparison can be inlined.\n // Do the rest of the job after assignment\n this.handleChange( next, prev, record, options );\n\n return true;\n }\n\n return false;\n }\n\n clone( value : Transactional, record : AttributesContainer ) : Transactional {\n // References are not cloned.\n if( !value || value._owner !== record ) return value;\n\n // Implicitly created objects are cloned.\n const clone = value.clone();\n aquire( record, clone, this.name );\n return clone;\n }\n\n // Do not serialize by default.\n toJSON(){}\n\n canBeUpdated( prev : Transactional, next : any, options : TransactionOptions ) : any {\n // If an object already exists, and new value is of incompatible type, let object handle the update.\n if( prev && next != null && !( next instanceof this.type ) ){\n return next;\n }\n }\n\n convert( next : any, prev : any, record : AttributesContainer, options : TransactionOptions ) : Transactional {\n if( next == null || next instanceof this.type ) return next;\n\n // Convert type using implicitly created rtransactional object.\n const implicitObject = new ( this.type as any )( next, options, shareAndListen );\n\n // To prevent a leak, we need to take an ownership on it.\n aquire( record, implicitObject, this.name );\n\n return implicitObject;\n }\n\n // Refs are always valid.\n validate( model, value, name ){}\n\n // They are always created as null.\n create() : Transactional {\n return null;\n }\n\n // Listening to the change events\n _handleChange( next : Transactional, prev : Transactional, record : AttributesContainer, options ){\n if( prev ){\n // If there was an implicitly created object, remove an ownership.\n if( prev._owner === record ){\n free( record, prev );\n options.unset || prev.dispose();\n }\n else{\n off( prev, prev._changeEventName, this._onChange, record );\n }\n } \n \n if( next ){\n // No need to take an ownership for an implicit object - already done in convert or clone.\n if( next._owner !== record ){\n on( next, next._changeEventName, this._onChange, record );\n }\n } \n }\n\n dispose( record : AttributesContainer, value : Transactional ){\n if( value ){\n this.handleChange( void 0, value, record, {} );\n }\n }\n\n _onChange : ( child : Transactional, options : TransactionOptions, initiator : Transactional ) => void \n\n initialize( options ){\n // Create change event handler which knows current attribute name. \n const attribute = this;\n this._onChange = this.propagateChanges ? function( child, options, initiator ){\n this === initiator || this.forceAttributeChange( attribute.name, options );\n } : ignore;\n\n options.changeHandlers.unshift( this._handleChange );\n }\n}\n\nfunction ignore(){}","import { tools as _, eventsApi } from '../../object-plus'\n\nexport * from './any'\nexport * from './owned'\nexport * from './date'\nexport * from './basic'\nexport * from './shared'\nexport * from './updates'\nexport * from './attrDef'\n\nimport { AnyType } from './any'\nimport { ConstructorsMixin, constructorsMixin } from './updates'\nimport { ChainableAttributeSpec } from './attrDef'\nimport { CompiledReference } from '../../traversable'\nimport { IOEndpoint } from '../../io-tools'\n\nexport interface RecordAttributesMixin extends ConstructorsMixin {\n // Attributes descriptors\n _attributes : AttributeDescriptors\n _attributesArray : AnyType[]\n \n // Attribute's property descriptors\n properties : PropertyDescriptorMap\n\n // Event map for record's local events.\n _localEvents? : eventsApi.EventMap,\n\n _endpoints : { [ name : string ] : IOEndpoint }\n}\n\nexport interface AttributeDescriptors {\n [ name : string ] : AnyType\n}\n\n// Create record mixin from the given record's attributes definition\nexport default function( attributesDefinition : object, baseClassAttributes : AttributeDescriptors ) : RecordAttributesMixin {\n const myAttributes = _.transform( {} as AttributeDescriptors, attributesDefinition, createAttribute ),\n allAttributes = _.defaults( {} as AttributeDescriptors, myAttributes, baseClassAttributes );\n\n const ConstructorsMixin = constructorsMixin( allAttributes );\n\n return {\n ...ConstructorsMixin,\n _attributes : new ConstructorsMixin.AttributesCopy( allAttributes ),\n _attributesArray : Object.keys( allAttributes ).map( key => allAttributes[ key ] ),\n properties : _.transform( {}, myAttributes, x => x.createPropertyDescriptor() ),\n ...localEventsMixin( myAttributes ),\n _endpoints : _.transform( {}, allAttributes, attrDef => attrDef.options.endpoint )\n } \n}\n\n// Create attribute from the type spec.\nexport function createAttribute( spec : any, name : string ) : AnyType {\n return AnyType.create( ChainableAttributeSpec.from( spec ).options, name );\n}\n\nexport function createSharedTypeSpec( Constructor : Function, Attribute : typeof AnyType ){\n if( !Constructor.hasOwnProperty( 'shared' ) ){\n Object.defineProperty( Constructor, 'shared', {\n get(){\n return new ChainableAttributeSpec({\n value : null,\n type : Constructor,\n _attribute : Attribute\n });\n }\n });\n }\n}\n\ninterface LocalEventsMixin {\n _localEvents? : eventsApi.EventMap\n}\n\nfunction localEventsMixin( attrSpecs : AttributeDescriptors ) : LocalEventsMixin {\n let _localEvents : eventsApi.EventMap;\n\n for( var key in attrSpecs ){\n const attribute = attrSpecs[ key ],\n { _onChange } = attribute.options; \n\n if( _onChange ){\n _localEvents || ( _localEvents = new eventsApi.EventMap() );\n\n _localEvents.addEvent( 'change:' + key,\n typeof _onChange === 'string' ?\n createWatcherFromRef( _onChange, key ) : \n wrapWatcher( _onChange, key ) );\n }\n }\n\n return _localEvents ? { _localEvents } : {};\n}\n\nfunction wrapWatcher( watcher, key ){\n return function( record, value ){\n watcher.call( record, value, key );\n } \n}\n\nfunction createWatcherFromRef( ref : string, key : string ){\n const { local, resolve, tail } = new CompiledReference( ref, true );\n return local ?\n function( record, value ){\n record[ tail ]( value, key );\n } :\n function( record, value ){\n resolve( record )[ tail ]( value, key );\n }\n}","import { getOwnerEndpoint, startIO, IOOptions, IOEndpoint, IOPromise, IONode } from '../io-tools'\n\nexport interface IORecord extends IONode {\n getEndpoint() : IOEndpoint\n save( options? : IOOptions ) : IOPromise\n fetch( options? : IOOptions ) : IOPromise\n destroy( options? : IOOptions ) : IOPromise\n toJSON( options? : object ) : any\n isNew() : boolean\n id : string | number\n set( json : object, options : object )\n}\n\nexport const IORecordMixin = {\n save( this : IORecord, options : IOOptions = {} ){\n const endpoint = this.getEndpoint(),\n json = this.toJSON( options );\n\n return startIO(\n this,\n this.isNew() ?\n endpoint.create( json, options, this ) :\n endpoint.update( this.id, json, options, this ),\n options,\n\n update => {\n this.set( update, { parse : true, ...options } );\n }\n );\n },\n\n fetch( options : IOOptions = {} ){\n return startIO(\n this,\n this.getEndpoint().read( this.id, options, this ),\n options,\n\n json => this.set( json, { parse : true, ...options } )\n );\n },\n\n destroy( options : IOOptions = {} ){ \n return startIO(\n this,\n this.getEndpoint().destroy( this.id, options, this ),\n options,\n\n () => {\n const { collection } = this;\n if( collection ){\n collection.remove( this, options );\n }\n else{\n this.dispose();\n }\n\n return this;\n }\n )\n }\n}","/**\n * Record core implementing transactional updates.\n * The root of all definitions. \n */\n\nimport { tools, eventsApi, Mixable, definitions, mixins, mixinRules, define } from '../object-plus'\n\nimport { CloneOptions, Transactional, TransactionalDefinition, Transaction, TransactionOptions, Owner } from '../transactions'\nimport { ChildrenErrors } from '../validation'\n\nimport { Collection } from '../collection'\n\nimport { AnyType, AggregatedType, setAttribute, UpdateRecordMixin, \n AttributesValues, AttributesContainer,\n ConstructorsMixin, AttributesConstructor, AttributesCopyConstructor } from './attributes'\n\nimport { IORecord, IORecordMixin } from './io-mixin'\nimport { IOPromise, IOEndpoint } from '../io-tools'\n\nconst { assign, isEmpty, log } = tools;\n\n/*******************************************************\n * Record core implementation\n */\n\nexport interface ConstructorOptions extends TransactionOptions{\n clone? : boolean\n}\n\n// Client unique id counter\nlet _cidCounter : number = 0;\n\n/***************************************************************\n * Record Definition as accepted by Record.define( definition )\n */\nexport interface RecordDefinition extends TransactionalDefinition {\n idAttribute? : string\n attributes? : AttributesValues\n collection? : object\n Collection? : typeof Transactional\n}\n\n@define({\n // Default client id prefix \n cidPrefix : 'm',\n\n // Name of the change event\n _changeEventName : 'change',\n\n // Default id attribute name\n idAttribute : 'id'\n})\n@definitions({\n defaults : mixinRules.merge,\n attributes : mixinRules.merge,\n collection : mixinRules.merge,\n Collection : mixinRules.value,\n idAttribute : mixinRules.protoValue\n})\nexport class Record extends Transactional implements IORecord, AttributesContainer {\n // Hack\n static onDefine( definition, BaseClass ){}\n\n static Collection : typeof Collection;\n static DefaultCollection : typeof Collection;\n\n static from : ( collectionReference : any ) => any;\n \n static defaults( attrs : AttributesValues ) : typeof Record {\n return this.extend({ attributes : attrs });\n }\n \n static attributes : AttributesValues\n\n /********************\n * IO Methods\n */\n _endpoints : { [ name : string ] : IOEndpoint }\n\n // Save record\n save( options? : object ) : IOPromise { throw new Error( 'Implemented by mixin' ); }\n\n // Destroy record\n destroy( options? : object ) : IOPromise { throw new Error( 'Implemented by mixin' ); }\n\n /***********************************\n * Core Members\n */\n // Previous attributes\n _previousAttributes : {}\n\n previousAttributes(){ return new this.AttributesCopy( this._previousAttributes ); } \n\n // Current attributes \n attributes : AttributesValues\n\n // Polymorphic accessor for aggregated attribute's canBeUpdated().\n get __inner_state__(){ return this.attributes; }\n\n // Lazily evaluated changed attributes hash\n _changedAttributes : AttributesValues\n\n get changed(){\n let changed = this._changedAttributes;\n\n if( !changed ){\n const prev = this._previousAttributes;\n changed = {};\n\n const { _attributes, attributes } = this;\n\n for( let attr of this._attributesArray ){\n const key = attr.name,\n value = attributes[ key ];\n\n if( attr.isChanged( value, prev[ key ] ) ){\n changed[ key ] = value;\n }\n }\n\n this._changedAttributes = changed;\n }\n\n return changed; \n }\n\n changedAttributes( diff? : {} ) : boolean | {} {\n if( !diff ) return this.hasChanged() ? assign( {}, this.changed ) : false;\n\n var val, changed : {} | boolean = false,\n old = this._transaction ? this._previousAttributes : this.attributes,\n attrSpecs = this._attributes;\n\n for( var attr in diff ){\n if( !attrSpecs[ attr ].isChanged( old[ attr ], ( val = diff[ attr ] ) ) ) continue;\n (changed || (changed = {}))[ attr ] = val;\n }\n\n return changed; \n }\n\n hasChanged( key? : string ) : boolean {\n const { _previousAttributes } = this;\n if( !_previousAttributes ) return false;\n\n return key ?\n this._attributes[ key ].isChanged( this.attributes[ key ], _previousAttributes[ key ] ) :\n !isEmpty( this.changed );\n }\n\n previous( key : string ) : any {\n if( key ){\n const { _previousAttributes } = this;\n if( _previousAttributes ) return _previousAttributes[ key ];\n }\n \n return null;\n }\n\n isNew() : boolean {\n return this.id == null;\n }\n\n has( key : string ) : boolean {\n return this[ key ] != void 0;\n }\n\n // Return attribute value, setting an attribute to undefined.\n // TODO: If attribute was aggregated, don't dispose it.\n unset( key : string, options? ) : any {\n const value = this[ key ];\n this.set({ [ key ] : void 0 }, { unset : true, ...options });\n return value;\n }\n\n // Undocumented. Move to NestedTypes?\n clear( options? ) : this {\n const nullify = options && options.nullify;\n\n this.transaction( () =>{\n this.forEachAttr( this.attributes, ( value, key ) => this[ key ] = nullify ? null : void 0 );\n }, options );\n\n return this;\n }\n\n // Returns Record owner skipping collections. TODO: Move out\n getOwner() : Owner {\n const owner : any = this._owner;\n\n // If there are no key, owner must be transactional object, and it's the collection.\n // We don't expect that collection can be the member of collection, so we're skipping just one level up. An optimization.\n return this._ownerKey ? owner : owner && owner._owner;\n }\n\n /***********************************\n * Identity managements\n */\n\n // Id attribute name ('id' by default)\n idAttribute : string;\n\n // Fixed 'id' property pointing to id attribute\n get id() : string | number { return this.attributes[ this.idAttribute ]; }\n set id( x : string | number ){ setAttribute( this, this.idAttribute, x ); }\n\n /***********************************\n * Dynamically compiled stuff\n */\n\n // Attributes specifications \n _attributes : { [ key : string ] : AnyType }\n _attributesArray : AnyType[]\n\n // Attributes object copy constructor\n Attributes : AttributesConstructor\n AttributesCopy : AttributesCopyConstructor\n\n // forEach function for traversing through attributes, with protective default implementation\n // Overriden by dynamically compiled loop unrolled function in define.ts\n forEachAttr( attrs : {}, iteratee : ( value : any, key? : string, spec? : AnyType ) => void ) : void {\n const { _attributes } = this;\n let unknown : string[];\n\n for( let name in attrs ){\n const spec = _attributes[ name ];\n\n if( spec ){\n iteratee( attrs[ name ], name, spec );\n }\n else{\n unknown || ( unknown = [] );\n unknown.push( `'${ name }'` );\n }\n }\n\n if( unknown ){\n this._log( 'warn', `attributes ${ unknown.join(', ')} are not defined`,{\n attributes : attrs\n } );\n }\n }\n\n each( iteratee : ( value? : any, key? : string ) => void, context? : any ){\n const fun = context !== void 0 ? ( v, k ) => iteratee.call( context, v, k ) : iteratee,\n { attributes } = this;\n\n for( const key in this.attributes ){\n const value = attributes[ key ];\n if( value !== void 0 ) fun( value, key );\n }\n }\n\n // Get array of attribute keys (Record) or record ids (Collection) \n keys() : string[] {\n const keys : string[] = [];\n\n this.each( ( value, key ) => value === void 0 || keys.push( key ) );\n\n return keys;\n }\n\n // Get array of attribute values (Record) or records (Collection)\n values() : any[] {\n return this.map( value => value );\n }\n\n // Create record default values, optionally augmenting given values.\n defaults( values = {} ){\n const defaults = {},\n { _attributesArray } = this;\n\n for( let attr of _attributesArray ){\n const key = attr.name,\n value = values[ key ];\n\n defaults[ key ] = value === void 0 ? attr.defaultValue() : value;\n }\n\n return defaults;\n }\n\n /***************************************************\n * Record construction\n */\n // Create record, optionally setting an owner\n constructor( a_values? : {}, a_options? : ConstructorOptions ){\n super( _cidCounter++ );\n this.attributes = {};\n \n const options = a_options || {},\n values = ( options.parse ? this.parse( a_values, options ) : a_values ) || {};\n\n if( log.level > 1 ) typeCheck( this, values );\n\n this._previousAttributes = this.attributes = new this.Attributes( this, values, options );\n\n this.initialize( a_values, a_options );\n\n if( this._localEvents ) this._localEvents.subscribe( this, this );\n }\n\n // Initialization callback, to be overriden by the subclasses \n initialize( values?, options? ){}\n\n // Deeply clone record, optionally setting new owner.\n clone( options : CloneOptions = {} ) : this {\n const copy : this = new (this.constructor)( this.attributes, { clone : true } );\n \n if( options.pinStore ) copy._defaultStore = this.getStore();\n\n return copy;\n }\n\n // Deprecated, every clone is the deep one now.\n deepClone() : this { return this.clone() };\n\n // Validate attributes.\n _validateNested( errors : ChildrenErrors ) : number {\n var length = 0;\n\n this.forEachAttr( this.attributes, ( value, name, attribute ) => {\n const error = attribute.validate( this, value, name );\n\n if( error ){\n errors[ name ] = error;\n length++;\n }\n } );\n\n return length;\n }\n\n // Get attribute by key\n get( key : string ) : any {\n return this[ key ];\n }\n\n /**\n * Serialization control\n */\n\n // Default record-level serializer, to be overriden by subclasses \n toJSON( options? : object ) : any {\n const json = {};\n\n this.forEachAttr( this.attributes, ( value, key : string, { toJSON } ) =>{\n // If attribute serialization is not disabled, and its value is not undefined...\n if( value !== void 0 ){\n // ...serialize it according to its spec.\n const asJson = toJSON.call( this, value, key, options );\n\n // ...skipping undefined values. Such an attributes are excluded.\n if( asJson !== void 0 ) json[ key ] = asJson; \n }\n });\n\n return json;\n }\n \n // Default record-level parser, to be overriden by the subclasses.\n parse( data, options? : TransactionOptions ){\n return data;\n }\n\n // DEPRECATED: Attributes-level parse. Is moved to attribute descriptors.\n _parse( data ){ return data; }\n\n /**\n * Transactional control\n */\n\n deepSet( name : string, value : any, options? ){\n // Operation might involve series of nested object updates, thus it's wrapped in transaction.\n this.transaction( () => {\n const path = name.split( '.' ),\n l = path.length - 1,\n attr = path[ l ];\n\n let model = this;\n\n // Locate the model, traversing the path.\n for( let i = 0; i < l; i++ ){\n const key = path[ i ];\n\n // There might be collections in path, so use `get`.\n let next = model.get ? model.get( key ) : model[ key ];\n\n // Create models, if they are not exist.\n if( !next ){\n const attrSpecs = model._attributes;\n if( attrSpecs ){\n // If current object is model, create default attribute\n var newModel = attrSpecs[ key ].create();\n\n // If created object is model, nullify attributes when requested\n if( options && options.nullify && newModel._attributes ){\n newModel.clear( options );\n }\n\n model[ key ] = next = newModel;\n }\n // Silently fail in other case.\n else return;\n }\n \n model = next;\n }\n\n // Set model attribute.\n if( model.set ){\n model.set({ [ attr ] : value }, options );\n }\n else{\n model[ attr ] = value;\n }\n });\n\n return this;\n }\n \n // Returns owner without the key (usually it's collection)\n get collection() : any {\n return this._ownerKey ? null : this._owner;\n }\n\n // Dispose object and all childrens\n dispose(){\n if( this._disposed ) return;\n \n this.forEachAttr( this.attributes, ( value, key, attribute ) => {\n attribute.dispose( this, value );\n });\n\n super.dispose();\n }\n\n _log( level : tools.LogLevel, text : string, props : object ) : void {\n tools.log( level, '[Record] ' + text, {\n 'Record' : this,\n 'Attributes definition:' : this._attributes,\n ...props\n });\n }\n\n getClassName() : string {\n return super.getClassName() || 'Record';\n }\n\n // Dummies to \n _createTransaction( values : object, options : TransactionOptions ) : Transaction { return void 0; }\n // Simulate attribute change \n forceAttributeChange : ( key : string, options : TransactionOptions ) => void\n _onChildrenChange : ( child : Transactional, options : TransactionOptions ) => void\n};\n\nassign( Record.prototype, UpdateRecordMixin, IORecordMixin );\n\n/***********************************************\n * Helper functions\n */\n\nclass BaseRecordAttributes {\n id : string | number\n\n constructor( record : Record, x : AttributesValues, options : TransactionOptions ) {\n this.id = x.id;\n }\n}\n\nRecord.prototype.Attributes = BaseRecordAttributes;\n\nclass BaseRecordAttributesCopy {\n id : string | number\n\n constructor( x : AttributesValues ) {\n this.id = x.id;\n }\n}\n\nRecord.prototype.AttributesCopy = BaseRecordAttributesCopy;\n\nconst IdAttribute = AnyType.create({ value : void 0 }, 'id' );\nRecord.prototype._attributes = { id : IdAttribute };\nRecord.prototype._attributesArray = [ IdAttribute ];\nRecord._attribute = AggregatedType;\n\nimport { shouldBeAnObject } from './attributes'\n\nfunction typeCheck( record : Record, values : object ){\n if( shouldBeAnObject( record, values ) ){\n const { _attributes } = record;\n let unknown : string[];\n\n for( let name in values ){\n if( !_attributes[ name ] ){\n unknown || ( unknown = [] );\n unknown.push( `'${ name }'` );\n }\n }\n\n if( unknown ){\n record._log( 'warn', `undefined attributes ${ unknown.join(', ')} are ignored.`, { values } );\n }\n }\n}","import { Record, RecordDefinition } from './record'\nimport { Mixable, tools, predefine, define, MixinsState } from '../object-plus'\nimport compile, { ChainableAttributeSpec } from './attributes'\nimport { Transactional } from '../transactions'\n\nimport { createSharedTypeSpec, AggregatedType, MSDateType, TimestampType, NumericType, SharedType } from './attributes'\n\nexport * from './attributes'\nexport { Record }\n\nconst { assign, defaults, omit, getBaseClass } = tools;\n\nRecord.onExtend = function( this : typeof Record, BaseClass : typeof Record ){\n Transactional.onExtend.call( this, BaseClass );\n\n // Create the default collection\n const Class = this;\n\n @predefine class DefaultCollection extends BaseClass.Collection {\n static model = Class;\n }\n\n this.DefaultCollection = DefaultCollection;\n\n // If there are no collection defined in statics, use the default collection.\n // It will appear in onDefine's definition, overriding all other settings.\n if( Class.Collection === BaseClass.Collection ){\n this.Collection = DefaultCollection;\n }\n\n // Create Class.shared modifier\n createSharedTypeSpec( this, SharedType );\n}\n\nRecord.onDefine = function( definition : RecordDefinition, BaseClass : typeof Record ){\n const baseProto : Record = BaseClass.prototype;\n\n // Compile attributes spec, creating definition mixin.\n const { properties, _localEvents, ...dynamicMixin } = compile( this.attributes = getAttributes( definition ), baseProto._attributes );\n assign( this.prototype, dynamicMixin );\n \n definition.properties = defaults( definition.properties || {}, properties );\n definition._localEvents = _localEvents;\n \n Transactional.onDefine.call( this, definition, BaseClass );\n\n // Finalize the definition of the default collection.\n this.DefaultCollection.define( definition.collection || {} );\n\n // assign collection from the definition.\n this.Collection = definition.Collection;\n this.Collection.prototype.model = this;\n\n if( definition.endpoint ) this.Collection.prototype._endpoint = definition.endpoint; \n}\n\nRecord._attribute = AggregatedType;\ncreateSharedTypeSpec( Record, SharedType );\n\nfunction getAttributes({ defaults, attributes, idAttribute } : RecordDefinition ) {\n const definition = attributes || defaults || {};\n \n // If there is an undeclared idAttribute, add its definition as untyped generic attribute.\n if( idAttribute && !( idAttribute in definition ) ){\n definition[ idAttribute ] = void 0;\n }\n\n return definition;\n}\n\ndeclare var Reflect;\n\nexport function attr( proto : object, attrName : string ) : void;\nexport function attr( spec : any ) : PropertyDecorator;\nexport function attr( proto, attrName? : string ) : any {\n if( attrName ){\n // Called without the spec. Extract the type.\n if( typeof Reflect !== 'undefined' && Reflect.getMetadata ){\n Reflect\n .getMetadata( \"design:type\", proto, attrName )\n .asProp( proto, attrName );\n }\n else{\n proto._log( 'error', 'Add import \"reflect-metadata\"; as the first line of your app.' );\n }\n }\n else{\n return ChainableAttributeSpec.from( proto ).asProp;\n }\n}\n\nexport function prop( spec ) : any {\n return spec.asProp;\n}","import { Record } from '../record'\nimport { Owner, Transaction, ItemsBehavior,\n TransactionOptions, Transactional, transactionApi } from '../transactions'\n\nimport { eventsApi, tools } from '../object-plus'\n\nconst { EventMap, trigger2, trigger3, on, off } = eventsApi,\n { commit, markAsDirty } = transactionApi,\n _aquire = transactionApi.aquire, _free = transactionApi.free;\n\n/** @private */\nexport interface CollectionCore extends Transactional, Owner {\n _byId : IdIndex\n models : Record[]\n model : typeof Record\n idAttribute : string // TODO: Refactor inconsistent idAttribute usage\n _comparator : Comparator\n get( objOrId : string | Record | Object ) : Record \n _itemEvents? : eventsApi.EventMap\n _shared : number\n _aggregationError : Record[]\n\n _log( level : string, text : string, value : any ) : void\n}\n\n// Collection's manipulation methods elements\nexport type Elements = ( Object | Record )[];\n\nexport interface CollectionOptions extends TransactionOptions {\n sort? : boolean\n}\n\nexport type Comparator = ( a : Record, b : Record ) => number; \n\n/** @private */\nexport function dispose( collection : CollectionCore ) : Record[]{\n const { models } = collection;\n\n collection.models = [];\n collection._byId = {};\n\n freeAll( collection, models );\n return models;\n}\n\n/** @private */\nexport function convertAndAquire( collection : CollectionCore, attrs : {} | Record, options : CollectionOptions ){\n const { model } = collection;\n \n let record : Record;\n\n if( collection._shared ){\n record = attrs instanceof model ? attrs : model.create( attrs, options );\n\n if( collection._shared & ItemsBehavior.listen ){\n on( record, record._changeEventName, collection._onChildrenChange, collection );\n }\n }\n else{\n record = attrs instanceof model ? ( options.merge ? attrs.clone() : attrs ) : model.create( attrs, options );\n\n if( !_aquire( collection, record ) ){\n const errors = collection._aggregationError || ( collection._aggregationError = [] );\n errors.push( record );\n }\n } \n\n // Subscribe for events...\n const { _itemEvents } = collection;\n _itemEvents && _itemEvents.subscribe( collection, record );\n\n return record;\n}\n\n/** @private */\nexport function free( owner : CollectionCore, child : Record, unset? : boolean ) : void {\n if( owner._shared ){\n if( owner._shared & ItemsBehavior.listen ){\n off( child, child._changeEventName, owner._onChildrenChange, owner );\n }\n }\n else{\n _free( owner, child );\n unset || child.dispose();\n }\n\n const { _itemEvents } = owner;\n _itemEvents && _itemEvents.unsubscribe( owner, child );\n}\n\n/** @private */\nexport function freeAll( collection : CollectionCore, children : Record[] ) : Record[] {\n for( let child of children ){\n free( collection, child );\n }\n\n return children;\n}\n\n/**\n * Silently sort collection, if its required. Returns true if sort happened.\n * @private\n */ \nexport function sortElements( collection : CollectionCore, options : CollectionOptions ) : boolean {\n let { _comparator } = collection;\n if( _comparator && options.sort !== false ){\n collection.models.sort( _comparator );\n return true;\n }\n\n return false;\n}\n\n/**********************************\n * Collection Index\n * @private \n */\nexport interface IdIndex {\n [ id : string ] : Record\n}\n\n/** @private Add record */ \nexport function addIndex( index : IdIndex, model : Record ) : void {\n index[ model.cid ] = model;\n var id = model.id;\n \n if( id || id === 0 ){\n index[ id ] = model;\n }\n}\n\n/** @private Remove record */ \nexport function removeIndex( index : IdIndex, model : Record ) : void {\n delete index[ model.cid ];\n var id = model.id;\n if( id || id === 0 ){\n delete index[ id ];\n }\n}\n\nexport function updateIndex( index : IdIndex, model : Record ){\n delete index[ model.previous( model.idAttribute ) ];\n\n const { id } = model;\n id == null || ( index[ id ] = model );\n}\n\n/***\n * In Collections, transactions appears only when\n * add remove or change events might be emitted.\n * reset doesn't require transaction.\n * \n * Transaction holds information regarding events, and knows how to emit them.\n * \n * Two major optimization cases.\n * 1) Population of an empty collection\n * 2) Update of the collection (no or little changes) - it's crucial to reject empty transactions.\n */\n\n\n// Transaction class. Implements two-phase transactions on object's tree.\n/** @private */ \nexport class CollectionTransaction implements Transaction {\n // open transaction\n constructor( public object : CollectionCore,\n public isRoot : boolean,\n public added : Record[],\n public removed : Record[],\n public nested : Transaction[],\n public sorted : boolean ){}\n\n // commit transaction\n commit( initiator? : Transactional ){\n const { nested, object } = this,\n { _isDirty } = object;\n\n // Commit all nested transactions...\n for( let transaction of nested ){\n transaction.commit( object );\n }\n\n if( object._aggregationError ){\n logAggregationError( object );\n }\n\n // Just trigger 'change' on collection, it must be already triggered for models during nested commits.\n // ??? TODO: do it in nested transactions loop? This way appears to be more correct. \n for( let transaction of nested ){\n trigger2( object, 'change', transaction.object, _isDirty );\n }\n\n // Notify listeners on attribute changes...\n const { added, removed } = this;\n\n // Trigger `add` events for both model and collection.\n for( let record of added ){\n trigger3( record, 'add', record, object, _isDirty );\n trigger3( object, 'add', record, object, _isDirty );\n }\n\n // Trigger `remove` events for both model and collection.\n for( let record of removed ){\n trigger3( record, 'remove', record, object, _isDirty );\n trigger3( object, 'remove', record, object, _isDirty );\n }\n\n if( this.sorted ){\n trigger2( object, 'sort', object, _isDirty );\n }\n\n if( added.length || removed.length ){\n trigger2( object, 'update', object, _isDirty );\n }\n\n this.isRoot && commit( object, initiator );\n }\n}\n\nexport function logAggregationError( collection : CollectionCore ){\n collection._log( 'error', 'added records already have an owner', collection._aggregationError );\n collection._aggregationError = void 0;\n}","import { Transaction, transactionApi } from '../transactions'\nimport { CollectionTransaction, logAggregationError, sortElements, convertAndAquire, free, CollectionOptions, addIndex, updateIndex, CollectionCore } from './commons'\nimport { Record } from '../record'\n\nconst { begin, commit, markAsDirty } = transactionApi;\n\nexport interface AddOptions extends CollectionOptions {\n at? : number \n}\n\n/** @private */\nexport function addTransaction( collection : CollectionCore, items : any[], options : AddOptions, merge? : boolean ){\n const isRoot = begin( collection ),\n nested : Transaction[]= [];\n\n var added = appendElements( collection, items, nested, options, merge );\n\n if( added.length || nested.length ){\n let needSort = sortOrMoveElements( collection, added, options );\n if( markAsDirty( collection, options ) ){\n return new CollectionTransaction( collection, isRoot, added, [], nested, needSort );\n }\n\n if( collection._aggregationError ) logAggregationError( collection );\n }\n\n // No changes...\n isRoot && commit( collection );\n};\n\n// Handle sort or insert at options for add operation. Reurns true if sort happened.\n/** @private */ \nfunction sortOrMoveElements( collection : CollectionCore, added : Record[], options : AddOptions ) : boolean {\n let at = options.at;\n\n // if `at` option is given, it overrides sorting option...\n if( at != null ){\n // Take an original collection's length. \n const length = collection.models.length - added.length;\n\n // Crazy Backbone rules about `at` index. I don't know what that guys smoke.\n at = Number( at );\n if( at < 0 ) at += length + 1;\n if( at < 0 ) at = 0;\n if( at > length ) at = length;\n\n // Move added elements to desired position. In place.\n moveElements( collection.models, at, added );\n return false;\n }\n\n return sortElements( collection, options );\n}\n\n/** @private */\nfunction moveElements( source : any[], at : number, added : any[] ) : void {\n for( var j = source.length - 1, i = j - added.length; i >= at; i--, j-- ){\n source[ j ] = source[ i ];\n }\n\n for( i = 0, j = at; i < added.length; i++, j++ ){\n source[ j ] = added[ i ];\n }\n}\n\n// append data to model and index\n/** @private */\nfunction appendElements( collection : CollectionCore, a_items : any[], nested : Transaction[], a_options : AddOptions, forceMerge : boolean ){\n var { _byId, models } = collection,\n merge = ( forceMerge || a_options.merge ) && !collection._shared,\n parse = a_options.parse,\n idAttribute = collection.model.prototype.idAttribute,\n prevLength = models.length;\n\n for( const item of a_items ){\n let model = item ? _byId[ item[ idAttribute ] ] || _byId[ item.cid ] : null;\n\n if( model ){\n if( merge && item !== model ){\n var attrs = item.attributes || item;\n const transaction = model._createTransaction( attrs, a_options );\n transaction && nested.push( transaction );\n\n if( model.hasChanged( idAttribute ) ){\n updateIndex( _byId, model );\n }\n }\n }\n else{\n model = convertAndAquire( collection, item, a_options );\n models.push( model );\n addIndex( _byId, model );\n }\n }\n\n return models.slice( prevLength );\n}\n","import { Transaction, transactionApi } from '../transactions'\nimport { CollectionTransaction, logAggregationError, IdIndex, convertAndAquire, free, sortElements, CollectionOptions, addIndex, CollectionCore, Elements, freeAll } from './commons'\nimport { Record } from '../record'\n\nconst { begin, commit, markAsDirty } = transactionApi;\n\n/** @private */\nconst silentOptions = { silent : true };\n\n/** @private */\nexport function emptySetTransaction( collection : CollectionCore, items : Elements, options : CollectionOptions, silent? : boolean ){\n const isRoot = begin( collection );\n\n const added = _reallocateEmpty( collection, items, options );\n\n if( added.length ){\n const needSort = sortElements( collection, options );\n\n if( markAsDirty( collection, silent ? silentOptions : options ) ){\n // 'added' is the reference to this.models. Need to copy it.\n return new CollectionTransaction( collection, isRoot, added.slice(), [], [], needSort );\n }\n\n if( collection._aggregationError ) logAggregationError( collection );\n }\n\n // No changes...\n isRoot && commit( collection );\n};\n\n/** @private */\nexport function setTransaction( collection, items, options ){\n const isRoot = begin( collection ),\n nested = [];\n\n var previous = collection.models,\n added = _reallocate( collection, items, nested, options );\n\n const reusedCount = collection.models.length - added.length,\n removed = reusedCount < previous.length ? (\n reusedCount ? _garbageCollect( collection, previous ) :\n freeAll( collection, previous )\n ) : []; \n \n const addedOrChanged = nested.length || added.length,\n // As we are reallocating models array, it needs to be sorted even if there are no changes.\n sorted = ( sortElements( collection, options ) && addedOrChanged ) || added.length || options.sorted;\n\n if( addedOrChanged || removed.length || sorted ){\n if( markAsDirty( collection, options ) ){ \n return new CollectionTransaction( collection, isRoot, added, removed, nested, sorted );\n }\n\n if( collection._aggregationError ) logAggregationError( collection );\n }\n\n isRoot && commit( collection );\n};\n\n// Remove references to all previous elements, which are not present in collection.\n// Returns an array with removed elements.\n/** @private */\nfunction _garbageCollect( collection : CollectionCore, previous : Record[] ) : Record[]{\n const { _byId } = collection,\n removed = [];\n\n // Filter out removed models and remove them from the index...\n for( let record of previous ){\n if( !_byId[ record.cid ] ){\n removed.push( record );\n free( collection, record );\n }\n }\n\n return removed;\n}\n\n// reallocate model and index\n/** @private */\nfunction _reallocate( collection : CollectionCore, source : any[], nested : Transaction[], options ){\n var models = Array( source.length ),\n _byId : IdIndex = {},\n merge = ( options.merge == null ? true : options.merge ) && !collection._shared,\n _prevById = collection._byId,\n prevModels = collection.models, \n idAttribute = collection.model.prototype.idAttribute,\n toAdd = [],\n orderKept = true;\n\n // for each item in source set...\n for( var i = 0, j = 0; i < source.length; i++ ){\n var item = source[ i ],\n model : Record = null;\n\n if( item ){\n var id = item[ idAttribute ],\n cid = item.cid;\n\n if( _byId[ id ] || _byId[ cid ] ) continue;\n\n model = _prevById[ id ] || _prevById[ cid ];\n }\n\n if( model ){\n if( merge && item !== model ){\n if( orderKept && prevModels[ j ] !== model ) orderKept = false;\n\n var attrs = item.attributes || item;\n const transaction = model._createTransaction( attrs, options );\n transaction && nested.push( transaction );\n }\n }\n else{\n model = convertAndAquire( collection, item, options );\n toAdd.push( model );\n }\n\n models[ j++ ] = model;\n addIndex( _byId, model );\n }\n\n models.length = j;\n collection.models = models;\n collection._byId = _byId;\n\n if( !orderKept ) options.sorted = true;\n\n return toAdd;\n}\n\n/** @private */\nfunction _reallocateEmpty( self, source, options ){\n var len = source ? source.length : 0,\n models = Array( len ),\n _byId : IdIndex = {},\n idAttribute = self.model.prototype.idAttribute;\n\n for( var i = 0, j = 0; i < len; i++ ){\n var src = source[ i ];\n\n if( src && ( _byId[ src[ idAttribute ] ] || _byId[ src.cid ] ) ){\n continue;\n }\n\n var model = convertAndAquire( self, src, options );\n models[ j++ ] = model;\n addIndex( _byId, model );\n }\n\n models.length = j;\n self._byId = _byId;\n\n return self.models = models;\n}","/*************\n * Remove items from collections.\n * \n * Cannot be a part of two-phase transaction on object tree.\n * Can be executed in the scope of ad-hoc transaction or from the trigger, though.\n *\n * Implemented with low-level API. \n * Most frequent operation - single element remove. Thus, it have the fast-path.\n */\n\nimport { Record } from '../record'\nimport { free, CollectionCore, CollectionTransaction, removeIndex } from './commons'\nimport { eventsApi } from '../object-plus'\nimport { TransactionOptions, transactionApi } from '../transactions' \n\nconst { trigger2, trigger3 } = eventsApi,\n { markAsDirty, begin, commit } = transactionApi;\n\n/** @private */\nexport function removeOne( collection : CollectionCore, el : Record | {} | string, options : TransactionOptions ) : Record {\n var model : Record = collection.get( el );\n\n if( model ){\n const isRoot = begin( collection ),\n models = collection.models;\n\n // Remove model form the collection. \n models.splice( models.indexOf( model ), 1 );\n removeIndex( collection._byId, model );\n \n // Mark transaction as dirty. \n const notify = markAsDirty( collection, options );\n\n // Send out events.\n if( notify ){\n trigger3( model, 'remove', model, collection, options );\n trigger3( collection, 'remove', model, collection, options );\n } \n\n free( collection, model, options.unset );\n\n notify && trigger2( collection, 'update', collection, options );\n\n // Commit transaction.\n isRoot && commit( collection );\n\n return model;\n }\n};\n\n/** Optimized for removing many elements\n * 1. Remove elements from the index, checking for duplicates\n * 2. Create new models array matching index\n * 3. Send notifications and remove references\n */\n\n/** @private */\nexport function removeMany( collection : CollectionCore, toRemove : any[], options ){\n const removed = _removeFromIndex( collection, toRemove, options.unset );\n if( removed.length ){\n const isRoot = begin( collection );\n\n _reallocate( collection, removed.length );\n\n if( markAsDirty( collection, options ) ){\n const transaction = new CollectionTransaction( collection, isRoot, [], removed, [], false );\n transaction.commit();\n }\n else{\n // Commit transaction.\n isRoot && commit( collection );\n }\n }\n\n return removed;\n};\n\n// remove models from the index...\n/** @private */\nfunction _removeFromIndex( collection, toRemove, unset : boolean ){\n var removed = Array( toRemove.length ),\n _byId = collection._byId;\n\n for( var i = 0, j = 0; i < toRemove.length; i++ ){\n var model = collection.get( toRemove[ i ] );\n if( model ){\n removed[ j++ ] = model;\n removeIndex( _byId, model );\n free( collection, model, unset );\n }\n }\n\n removed.length = j;\n\n return removed;\n}\n\n// Allocate new models array removing models not present in the index.\n/** @private */\nfunction _reallocate( collection, removed ){\n var prev = collection.models,\n models = collection.models = Array( prev.length - removed ),\n _byId = collection._byId;\n\n for( var i = 0, j = 0; i < prev.length; i++ ){\n var model = prev[ i ];\n\n if( _byId[ model.cid ] ){\n models[ j++ ] = model;\n }\n }\n\n models.length = j;\n}","import { define, tools, eventsApi, EventMap, definitions, mixinRules, EventsDefinition, Mixable } from '../object-plus'\nimport { ItemsBehavior, transactionApi, Transactional, CloneOptions, Transaction, TransactionOptions, TransactionalDefinition, Owner } from '../transactions'\nimport { Record, SharedType, AggregatedType, createSharedTypeSpec } from '../record'\n\nimport { IdIndex, free, sortElements, dispose, Elements, CollectionCore, addIndex, removeIndex, updateIndex, Comparator, CollectionTransaction } from './commons'\nimport { addTransaction, AddOptions } from './add'\nimport { setTransaction, emptySetTransaction } from './set'\nimport { removeOne, removeMany } from './remove'\nimport { IOPromise, startIO } from '../io-tools'\n\nconst { trigger2, on, off } = eventsApi,\n { begin, commit, markAsDirty } = transactionApi,\n { omit, log, assign, defaults, assignToClassProto } = tools;\n\nlet _count = 0;\n\nexport type GenericComparator = string | ( ( x : Record ) => number ) | ( ( a : Record, b : Record ) => number ); \n\nexport interface CollectionOptions extends TransactionOptions {\n comparator? : GenericComparator\n model? : typeof Record\n}\n\nexport type Predicate = ( val : R, key : number ) => boolean | object;\n\nexport interface CollectionDefinition extends TransactionalDefinition {\n model? : typeof Record,\n itemEvents? : EventsDefinition\n _itemEvents? : EventMap\n}\n\nconst slice = Array.prototype.slice;\n\nclass CollectionRefsType extends SharedType {\n static defaultValue = [];\n}\n\n@define({\n // Default client id prefix \n cidPrefix : 'c',\n model : Record,\n _changeEventName : 'changes',\n _aggregationError : null\n})\n@definitions({\n comparator : mixinRules.value,\n model : mixinRules.protoValue,\n itemEvents : mixinRules.merge\n})\nexport class Collection< R extends Record = Record> extends Transactional implements CollectionCore {\n _shared : number\n _aggregationError : R[]\n\n static Subset : typeof Collection\n static Refs : typeof Collection\n static _SubsetOf : typeof Collection\n \n createSubset( models : ElementsArg, options ){\n const SubsetOf = (this.constructor).subsetOf( this ).options.type,\n subset = new SubsetOf( models, options );\n \n subset.resolve( this );\n return subset;\n }\n\n static onExtend( BaseClass : typeof Transactional ){\n // Cached subset collection must not be inherited.\n const Ctor = this;\n this._SubsetOf = null;\n\n function RefsCollection( a, b, listen? ){\n Ctor.call( this, a, b, ItemsBehavior.share | ( listen ? ItemsBehavior.listen : 0 ) );\n }\n\n Mixable.mixins.populate( RefsCollection );\n \n RefsCollection.prototype = this.prototype;\n RefsCollection._attribute = CollectionRefsType;\n\n this.Refs = this.Subset = RefsCollection;\n\n Transactional.onExtend.call( this, BaseClass );\n createSharedTypeSpec( this, SharedType );\n }\n \n static onDefine( definition : CollectionDefinition, BaseClass : any ){\n if( definition.itemEvents ){\n const eventsMap = new EventMap( BaseClass.prototype._itemEvents );\n eventsMap.addEventsMap( definition.itemEvents );\n this.prototype._itemEvents = eventsMap;\n }\n\n if( definition.comparator !== void 0 ) this.prototype.comparator = definition.comparator;\n\n Transactional.onDefine.call( this, definition );\n }\n\n static subsetOf : ( collectionReference : any ) => any;\n \n _itemEvents : EventMap\n\n /***********************************\n * Core Members\n */\n // Array of the records\n models : R[]\n\n // Polymorphic accessor for aggregated attribute's canBeUpdated().\n get __inner_state__(){ return this.models; }\n\n // Index by id and cid\n _byId : { [ id : string ] : R }\n\n set comparator( x : GenericComparator ){\n let compare;\n\n switch( typeof x ){\n case 'string' :\n this._comparator = ( a, b ) => {\n const aa = a[ x ], bb = b[ x ];\n if( aa === bb ) return 0;\n return aa < bb ? -1 : + 1;\n } \n break;\n case 'function' :\n if( x.length === 1 ){\n this._comparator = ( a, b ) => {\n const aa = (x).call( this, a ), bb = (x).call( this, b );\n if( aa === bb ) return 0;\n return aa < bb ? -1 : + 1;\n }\n }\n else{\n this._comparator = ( a, b ) => (x).call( this, a, b );\n }\n break;\n \n default :\n this._comparator = null;\n }\n }\n \n // TODO: Improve typing\n getStore() : Transactional {\n return this._store || ( this._store = this._owner ? this._owner.getStore() : this._defaultStore );\n }\n\n _store : Transactional\n\n get comparator(){ return this._comparator; }\n _comparator : ( a : R, b : R ) => number\n\n _onChildrenChange( record : R, options : TransactionOptions = {}, initiator? : Transactional ){\n // Ignore updates from nested transactions.\n if( initiator === this ) return;\n\n const { idAttribute } = this;\n\n if( record.hasChanged( idAttribute ) ){\n updateIndex( this._byId, record );\n }\n\n const isRoot = begin( this );\n\n if( markAsDirty( this, options ) ){\n // Forward change event from the record.\n trigger2( this, 'change', record, options )\n }\n\n isRoot && commit( this );\n }\n\n get( objOrId : string | R | Object ) : R {\n if( objOrId == null ) return;\n\n if( typeof objOrId === 'object' ){\n const id = objOrId[ this.idAttribute ];\n return ( id !== void 0 && this._byId[ id ] ) || this._byId[ (objOrId).cid ];\n }\n else{\n return this._byId[ objOrId ];\n } \n }\n\n each( iteratee : ( val : R, key : number ) => void, context? : any ){\n const fun = bindContext( iteratee, context ),\n { models } = this;\n\n for( let i = 0; i < models.length; i++ ){\n fun( models[ i ], i ); \n }\n }\n\n forEach( iteratee : ( val : R, key? : number ) => void, context? : any ){\n return this.each( iteratee, context );\n }\n\n every( iteratee : Predicate, context? : any ) : boolean {\n const fun = toPredicateFunction( iteratee, context ),\n { models } = this;\n\n for( let i = 0; i < models.length; i++ ){\n if( !fun( models[ i ], i ) ) return false;\n }\n\n return true;\n }\n\n filter( iteratee : Predicate, context? : any ) : R[] {\n const fun = toPredicateFunction( iteratee, context ),\n { models } = this;\n\n return this.map( ( x, i ) => fun( x, i ) ? x : void 0 );\n }\n\n find( iteratee : Predicate, context? : any ) : R {\n const fun = toPredicateFunction( iteratee, context ),\n { models } = this;\n\n for( let i = 0; i < models.length; i++ ){\n if( fun( models[ i ], i ) ) return models[ i ];\n }\n\n return null;\n }\n\n some( iteratee : Predicate, context? : any ) : boolean {\n return Boolean( this.find( iteratee, context ) );\n }\n\n map< T >( iteratee : ( val : R, key : number ) => T, context? : any ) : T[]{\n const fun = bindContext( iteratee, context ),\n { models } = this,\n mapped = Array( models.length );\n\n let j = 0;\n\n for( let i = 0; i < models.length; i++ ){\n const x = fun( models[ i ], i );\n x === void 0 || ( mapped[ j++ ] = x ); \n }\n\n mapped.length = j;\n\n return mapped;\n }\n\n _validateNested( errors : {} ) : number {\n // Don't validate if not aggregated.\n if( this._shared ) return 0;\n\n let count = 0;\n\n this.each( record => {\n const error = record.validationError;\n if( error ){\n errors[ record.cid ] = error;\n count++;\n }\n });\n\n return count;\n }\n\n model : typeof Record\n\n // idAttribute extracted from the model type.\n idAttribute : string\n\n constructor( records? : ( R | {} )[], options : CollectionOptions = {}, shared? : number ){\n super( _count++ );\n this.models = [];\n this._byId = {};\n \n this.comparator = this.comparator;\n\n if( options.comparator !== void 0 ){\n this.comparator = options.comparator;\n options.comparator = void 0;\n }\n \n this.model = this.model;\n \n if( options.model ){\n this.model = options.model;\n options.model = void 0;\n }\n\n this.idAttribute = this.model.prototype.idAttribute; //TODO: Remove?\n\n this._shared = shared || 0;\n\n if( records ){\n const elements = toElements( this, records, options );\n emptySetTransaction( this, elements, options, true );\n }\n\n this.initialize.apply( this, arguments );\n\n if( this._localEvents ) this._localEvents.subscribe( this, this );\n }\n\n initialize(){}\n\n get length() : number { return this.models.length; }\n first() : R { return this.models[ 0 ]; }\n last() : R { return this.models[ this.models.length - 1 ]; }\n at( a_index : number ) : R {\n const index = a_index < 0 ? a_index + this.models.length : a_index; \n return this.models[ index ];\n }\n\n // Deeply clone collection, optionally setting new owner.\n clone( options : CloneOptions = {} ) : this {\n const models = this._shared & ItemsBehavior.share ? this.models : this.map( model => model.clone() ),\n copy : this = new (this.constructor)( models, { model : this.model, comparator : this.comparator }, this._shared );\n \n if( options.pinStore ) copy._defaultStore = this.getStore();\n \n return copy;\n }\n\n toJSON( options? : object ) : any {\n return this.models.map( model => model.toJSON( options ) );\n }\n\n // Apply bulk in-place object update in scope of ad-hoc transaction \n set( elements : ElementsArg = [], options : TransactionOptions = {} ) : this {\n if( (options).add !== void 0 ){\n this._log( 'warn', \"Collection.set doesn't support 'add' option, behaving as if options.add === true.\", options );\n }\n\n // Handle reset option here - no way it will be populated from the top as nested transaction.\n if( options.reset ){\n this.reset( elements, options )\n }\n else{\n const transaction = this._createTransaction( elements, options );\n transaction && transaction.commit();\n } \n\n return this; \n }\n\n /**\n * Enable or disable live updates.\n * \n * `true` enables full collection synchronization.\n * `false` cancel live updates.\n * `json => true | false` - filter updates\n */\n liveUpdates( enabled : LiveUpdatesOption ) : IOPromise {\n if( enabled ){\n this.liveUpdates( false );\n\n const filter = typeof enabled === 'function' ? enabled : () => true;\n\n this._liveUpdates = {\n updated : json => {\n filter( json ) && this.add( json, { parse : true, merge : true } );\n },\n\n removed : id => this.remove( id )\n };\n\n return this.getEndpoint().subscribe( this._liveUpdates, this ).then( () => this );\n }\n else{\n if( this._liveUpdates ){\n this.getEndpoint().unsubscribe( this._liveUpdates, this );\n this._liveUpdates = null;\n }\n }\n }\n\n _liveUpdates : object\n\n fetch( a_options : { liveUpdates? : LiveUpdatesOption } & TransactionOptions = {} ) : IOPromise {\n const options = { parse : true, ...a_options },\n endpoint = this.getEndpoint();\n\n return startIO(\n this,\n endpoint.list( options, this ),\n options,\n\n json => {\n let result : any = this.set( json, { parse : true, ...options } as TransactionOptions );\n \n if( options.liveUpdates ){\n result = this.liveUpdates( options.liveUpdates );\n }\n\n return result;\n }\n );\n }\n\n dispose() : void {\n if( this._disposed ) return;\n\n const aggregated = !this._shared;\n\n for( let record of this.models ){\n free( this, record );\n\n if( aggregated ) record.dispose();\n }\n\n this.liveUpdates( false );\n\n super.dispose();\n }\n\n reset( a_elements? : ElementsArg, options : TransactionOptions = {} ) : R[] {\n const isRoot = begin( this ),\n previousModels = this.models;\n\n // Make all changes required, but be silent.\n if( a_elements ){ \n emptySetTransaction( this, toElements( this, a_elements, options ), options, true );\n }\n else{\n this._byId = {};\n this.models = [];\n }\n\n markAsDirty( this, options );\n\n options.silent || trigger2( this, 'reset', this, defaults( { previousModels : previousModels }, options ) );\n\n // Dispose models which are not in the updated collection.\n const { _byId } = this;\n \n for( let toDispose of previousModels ){\n _byId[ toDispose.cid ] || free( this, toDispose );\n }\n\n isRoot && commit( this );\n return this.models;\n }\n\n // Add elements to collection.\n add( a_elements : ElementsArg , options : AddOptions = {} ){\n const elements = toElements( this, a_elements, options ),\n transaction = this.models.length ?\n addTransaction( this, elements, options ) :\n emptySetTransaction( this, elements, options );\n\n if( transaction ){\n transaction.commit();\n return transaction.added;\n }\n }\n\n // Remove elements. \n remove( recordsOrIds : any, options : CollectionOptions = {} ) : R[] | R {\n if( recordsOrIds ){\n return Array.isArray( recordsOrIds ) ?\n removeMany( this, recordsOrIds, options ) as R[]:\n removeOne( this, recordsOrIds, options ) as R;\n }\n\n return [];\n }\n\n // Apply bulk object update without any notifications, and return open transaction.\n // Used internally to implement two-phase commit. \n _createTransaction( a_elements : ElementsArg, options : TransactionOptions = {} ) : CollectionTransaction | void {\n const elements = toElements( this, a_elements, options );\n\n if( this.models.length ){\n return options.remove === false ?\n addTransaction( this, elements, options, true ) :\n setTransaction( this, elements, options );\n }\n else{\n return emptySetTransaction( this, elements, options );\n }\n }\n\n static _attribute = AggregatedType;\n\n /***********************************\n * Collection manipulation methods\n */\n\n pluck( key : keyof R ) : any[] {\n return this.models.map( model => model[ key ] );\n }\n\n sort( options : TransactionOptions = {} ) : this {\n if( sortElements( this, options ) ){\n const isRoot = begin( this );\n \n if( markAsDirty( this, options ) ){\n trigger2( this, 'sort', this, options );\n }\n\n isRoot && commit( this );\n }\n\n return this;\n }\n\n // Add a model to the end of the collection.\n push(model : ElementsArg, options : CollectionOptions ) {\n return this.add(model, assign({at: this.length}, options));\n }\n\n // Remove a model from the end of the collection.\n pop( options : CollectionOptions ) : R {\n var model = this.at(this.length - 1);\n this.remove(model, { unset : true, ...options });\n return model;\n }\n\n // Remove and return given model.\n // TODO: do not dispose the model for aggregated collection.\n unset( modelOrId : R | string, options? ) : R {\n const value = this.get( modelOrId );\n this.remove( modelOrId, { unset : true, ...options } );\n return value;\n }\n\n // Add a model to the beginning of the collection.\n unshift(model : ElementsArg, options : CollectionOptions ) {\n return this.add(model, assign({at: 0}, options));\n }\n\n // Remove a model from the beginning of the collection.\n shift( options? : CollectionOptions ) : R {\n var model = this.at(0);\n this.remove( model, { unset : true, ...options } );\n return model;\n }\n\n // Slice out a sub-array of models from the collection.\n slice() : R[] {\n return slice.apply(this.models, arguments);\n }\n\n indexOf( modelOrId : any ) : number {\n const record = this.get( modelOrId );\n return this.models.indexOf( record );\n }\n\n modelId( attrs : {} ) : any {\n return attrs[ this.model.prototype.idAttribute ];\n }\n\n // Toggle model in collection.\n toggle( model : R, a_next? : boolean ) : boolean {\n var prev = Boolean( this.get( model ) ),\n next = a_next === void 0 ? !prev : Boolean( a_next );\n\n if( prev !== next ){\n if( prev ){\n this.remove( model );\n }\n else{\n this.add( model );\n }\n }\n\n return next;\n }\n\n _log( level : tools.LogLevel, text : string, value ) : void {\n tools.log( level, `[Collection Update] ${ this.model.prototype.getClassName() }.${ this.getClassName() }: ` + text, {\n Argument : value,\n 'Attributes spec' : this.model.prototype._attributes\n });\n }\n\n getClassName() : string {\n return super.getClassName() || 'Collection';\n }\n}\n\nexport type LiveUpdatesOption = boolean | ( ( x : any ) => boolean );\n\nexport type ElementsArg = Object | Record | Object[] | Record[];\n\n// TODO: make is safe for parse to return null (?)\nfunction toElements( collection : Collection, elements : ElementsArg, options : CollectionOptions ) : Elements {\n const parsed = options.parse ? collection.parse( elements, options ) : elements; \n return Array.isArray( parsed ) ? parsed : [ parsed ];\n}\n\ncreateSharedTypeSpec( Collection, SharedType );\n\nRecord.Collection = Collection;\n\nfunction bindContext( fun : Function, context? : any ){\n return context !== void 0 ? ( v, k ) => fun.call( context, v, k ) : fun;\n}\n\nfunction toPredicateFunction( iteratee : Predicate, context : any ){\n if( typeof iteratee === 'object' ){\n // Wrap object to the predicate...\n return x => {\n for( let key in iteratee as any ){\n if( iteratee[ key ] !== x[ key ] )\n return false;\n }\n\n return true;\n }\n }\n \n return bindContext( iteratee, context );\n\n}","import { Collection } from '../collection'\nimport { Record } from '../record'\nimport { CompiledReference } from '../traversable'\n\nexport type CollectionReference = ( () => Collection ) | Collection | string; \n\n/** @private */\nexport function parseReference( collectionRef : CollectionReference ) : ( root : Record ) => Collection {\n switch( typeof collectionRef ){\n case 'function' :\n return root => (collectionRef).call( root );\n case 'object' :\n return () => collectionRef;\n case 'string' :\n const { resolve } = new CompiledReference( collectionRef );\n return resolve;\n }\n}","import { AnyType, AttributeOptions } from '../record'\nimport { parseReference, CollectionReference } from './commons'\nimport { Collection } from '../collection'\nimport { Record } from '../record'\n\nimport { ChainableAttributeSpec } from '../record'\n\n/********\n * Reference to model by id.\n * \n * Untyped attribute. Holds model id, when unresolved. When resolved, is substituted\n * with a real model.\n * \n * No model changes are detected and counted as owner's change. That's intentional.\n */\n\n/** @private */\ntype RecordRefValue = Record | string;\n\n/** @private */\nclass RecordRefType extends AnyType {\n // It is always serialized as an id, whenever it's resolved or not. \n toJSON( value : RecordRefValue ){\n return value && typeof value === 'object' ? value.id : value;\n }\n\n // Wne \n clone( value : RecordRefValue ){\n return value && typeof value === 'object' ? value.id : value;\n }\n\n // Model refs by id are equal when their ids are equal.\n isChanged( a : RecordRefValue, b : RecordRefValue){\n var aId = a && ( (a).id == null ? a : (a).id ),\n bId = b && ( (b).id == null ? b : (b).id );\n\n return aId !== bId;\n }\n\n // Refs are always valid.\n validate( model, value, name ){}\n}\n\nRecord.from = function from( masterCollection : CollectionReference ) : ChainableAttributeSpec {\n const getMasterCollection = parseReference( masterCollection );\n\n const typeSpec = new ChainableAttributeSpec({\n value : null,\n _attribute : RecordRefType\n });\n \n return typeSpec\n .get( function( objOrId : RecordRefValue, name : string ) : Record {\n if( typeof objOrId === 'object' ) return objOrId;\n\n // So, we're dealing with an id reference. Resolve it.\n const collection = getMasterCollection( this );\n let record : Record = null;\n\n // If master collection exists and is not empty...\n if( collection && collection.length ){\n // Silently update attribute with record from this collection.\n record = collection.get( objOrId ) || null;\n this.attributes[ name ] = record;\n\n // Subscribe for events manually. delegateEvents won't be invoked.\n record && this._attributes[ name ].handleChange( record, null, this, {} );\n }\n\n return record;\n });\n};","import { Collection, CollectionOptions } from '../collection'\nimport { tools, eventsApi, define } from '../object-plus'\nimport { Record, AggregatedType } from '../record'\nimport { parseReference, CollectionReference } from './commons'\nimport { ChainableAttributeSpec } from '../record'\nimport { Transactional, ItemsBehavior, TransactionOptions, transactionApi } from '../transactions'\n\nconst { fastDefaults } = tools;\n\ntype RecordsIds = ( string | number )[];\n\nCollection.subsetOf = function subsetOf( masterCollection : CollectionReference ) : ChainableAttributeSpec {\n const SubsetOf = this._SubsetOf || ( this._SubsetOf = defineSubsetCollection( this ) ),\n getMasterCollection = parseReference( masterCollection ),\n typeSpec = new ChainableAttributeSpec({\n type : SubsetOf\n });\n\n return typeSpec.get(\n function( refs ){\n !refs || refs.resolvedWith || refs.resolve( getMasterCollection( this ) );\n return refs;\n }\n );\n};\n\nconst subsetOfBehavior = ItemsBehavior.share | ItemsBehavior.persistent;\n\nfunction defineSubsetCollection( CollectionConstructor : typeof Collection ) {\n @define class SubsetOfCollection extends CollectionConstructor {\n refs : any[];\n resolvedWith : Collection = null;\n\n _attribute : AggregatedType\n\n get __inner_state__(){ return this.refs || this.models; }\n\n constructor( recordsOrIds?, options? ){\n super( [], options, subsetOfBehavior );\n this.refs = toArray( recordsOrIds );\n }\n\n // Remove should work fine as it already accepts ids. Add won't...\n add( a_elements, options = {} ){\n const { resolvedWith } = this,\n toAdd = toArray( a_elements );\n \n if( resolvedWith ){\n // If the collection is resolved already, everything is simple.\n return super.add( resolveRefs( resolvedWith, toAdd ), options );\n }\n else{\n // Collection is not resolved yet. So, we prepare the delayed computation.\n if( toAdd.length ){\n const isRoot = transactionApi.begin( this );\n\n // Save elements to resolve in future...\n this.refs = this.refs ? this.refs.concat( toAdd ) : toAdd.slice();\n\n transactionApi.markAsDirty( this, options );\n\n // And throw the 'changes' event.\n isRoot && transactionApi.commit( this );\n }\n }\n }\n\n reset( a_elements?, options = {} ){\n const { resolvedWith } = this,\n elements = toArray( a_elements );\n \n return resolvedWith ?\n // Collection is resolved, so parse ids and forward the call to set.\n super.reset( resolveRefs( resolvedWith, elements ), options ) :\n // Collection is not resolved yet. So, we prepare the delayed computation.\n delaySet( this, elements, options ) || [];\n }\n\n _createTransaction( a_elements, options? ){\n const { resolvedWith } = this,\n elements = toArray( a_elements );\n \n return resolvedWith ?\n // Collection is resolved, so parse ids and forward the call to set.\n super._createTransaction( resolveRefs( resolvedWith, elements ), options ) :\n // Collection is not resolved yet. So, we prepare the delayed computation.\n delaySet( this, elements, options );\n }\n\n // Serialized as an array of model ids.\n toJSON() : RecordsIds {\n return this.refs ?\n this.refs.map( objOrId => objOrId.id || objOrId ) :\n this.models.map( model => model.id );\n }\n\n // Subset is always valid.\n _validateNested(){ return 0; }\n\n get length() : number {\n return this.models.length || ( this.refs ? this.refs.length : 0 );\n }\n\n // Must be shallow copied on clone.\n clone( owner? ){\n var Ctor = (this).constructor,\n copy = new Ctor( [], {\n model : this.model,\n comparator : this.comparator\n });\n\n if( this.resolvedWith ){\n // TODO: bug here. \n copy.resolvedWith = this.resolvedWith;\n copy.refs = null;\n copy.reset( this.models, { silent : true } );\n }\n else{\n copy.refs = this.refs.slice();\n }\n\n return copy;\n }\n\n // Clean up the custom parse method possibly defined in the base class.\n parse( raw : any ) : Record[] {\n return raw;\n }\n\n resolve( collection : Collection ) : this {\n if( collection && collection.length ){\n this.resolvedWith = collection;\n\n if( this.refs ){\n this.reset( this.refs, { silent : true } );\n this.refs = null;\n }\n }\n\n return this;\n }\n\n getModelIds() : RecordsIds { return this.toJSON(); }\n\n toggle( modelOrId : any, val : boolean ) : boolean {\n return super.toggle( this.resolvedWith.get( modelOrId ), val );\n }\n\n addAll() : Record[] {\n if( this.resolvedWith ){\n this.set( this.resolvedWith.models );\n return this.models;\n }\n\n throw new Error( \"Cannot add elemens because the subset collection is not resolved yet.\" );\n }\n\n toggleAll() : Record[] {\n return this.length ? this.reset() : this.addAll();\n }\n }\n\n // Clean up all custom item events to prevent memory leaks.\n SubsetOfCollection.prototype._itemEvents = void 0;\n\n return SubsetOfCollection;\n}\n\nfunction resolveRefs( master, elements ){\n const records = [];\n \n for( let el of elements ){\n const record = master.get( el );\n if( record ) records.push( record );\n }\n\n return records;\n}\n\nfunction delaySet( collection, elements, options ) : void {\n if( tools.notEqual( collection.refs, elements ) ){\n const isRoot = transactionApi.begin( collection );\n\n // Save elements to resolve in future...\n collection.refs = elements.slice();\n\n transactionApi.markAsDirty( collection, options );\n \n // And throw the 'changes' event.\n isRoot && transactionApi.commit( collection );\n }\n}\n\nfunction toArray( elements ){\n return elements ? ( \n Array.isArray( elements ) ? elements : [ elements ]\n ) : [];\n}","import { Record } from '../record'\nimport { Transactional } from '../transactions'\nimport { startIO, IOPromise } from '../io-tools'\n\nlet _store : Store = null;\n\nexport class Store extends Record {\n getStore() : Store { return this; }\n \n // delegate item lookup to owner, and to the global store if undefined\n get( name : string ) : any {\n // Lookup for resource in the current store. \n let local = this[ name ];\n\n // If something is found or it's the global store, return result.\n if( local || this === this._defaultStore ) return local;\n\n // Forward failed lookup to owner or global store.\n return this._owner ? this._owner.get( name ) : this._defaultStore.get( name ); \n }\n\n static get global(){ return _store; }\n static set global( store : Store ){\n if( _store ){\n _store.dispose();\n }\n\n Transactional.prototype._defaultStore = _store = store;\n }\n}\n\nStore.global = new Store();","// Polyfill for IE10. Should fix problems with babel and statics inheritance.\nimport { tools } from './object-plus'\n\ndeclare global {\n interface ObjectConstructor {\n setPrototypeOf( target : Object, proto : Object );\n }\n}\n\nObject.setPrototypeOf || ( Object.setPrototypeOf = tools.defaults );\n\n/**\n * Export everything \n */\n\nexport * from './object-plus'\nexport * from './collection'\nexport * from './relations'\nexport * from './record'\nexport * from './transactions'\n\nexport * from './io-tools'\n\n// Exported module itself is the global event bus.\nimport { Events } from './object-plus/'\nexport const { on, off, trigger, once, listenTo, stopListening, listenToOnce } = Events;\n\nimport { Collection } from './collection'\n\n// Define synonims for NestedTypes backward compatibility.\nimport { Record as Model } from './record' \nimport { define, Mixable as Class } from './object-plus/'\nexport { Model, Class };\n\nexport function attributes( attrDefs ) : typeof Model {\n @define class DefaultRecord extends Model {\n static attributes = attrDefs;\n }\n\n return DefaultRecord;\n}\n\nimport { ChainableAttributeSpec } from './record'\n\n/** Typeless attribute declaration with default value. */ \nexport function value( x : any ) : ChainableAttributeSpec {\n return new ChainableAttributeSpec({ value : x });\n}\n\n/** Wrap model or collection method in transaction. */\nexport function transaction< F extends Function >( method : F ) : F {\n return function( ...args ){\n let result;\n \n this.transaction( () => {\n result = method.apply( this, args );\n });\n \n return result;\n }\n}","/*******\n * Backbone Backward compatibility shim for View, Router, and History.\n * Based on 1.2.3, converted to browser-only ES6 modules thing. \n */\n\n// Backbone.js 1.2.3\n// (c) 2010-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n// Backbone may be freely distributed under the MIT license.\nimport * as _ from 'underscore'\nimport * as jQuery from 'jquery'\n\n// Initial Setup\n// -------------\ndeclare global {\n interface Window {\n Backbone : any\n }\n\n function attachEvent( a, b );\n function detachEvent( a, b );\n}\n\n// Save the previous value of the `Backbone` variable, so that it can be\n// restored later on, if `noConflict` is used.\nconst previousBackbone = window.Backbone;\n\n// Create a local reference to a common array method we'll want to use later.\nconst slice = Array.prototype.slice;\n\n// For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns\n// the `$` variable.\nconst exported = {\n $ : jQuery,\n history : null,\n VERSION : '1.2.3',\n View, History, Router, noConflict\n}\n\nexport default exported;\n\n// Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable\n// to its previous owner. Returns a reference to this Backbone object.\nfunction noConflict() {\n window.Backbone = previousBackbone;\n return this;\n};\n\n// Backbone.View\n// -------------\n\n// Backbone Views are almost more convention than they are actual code. A View\n// is simply a JavaScript object that represents a logical chunk of UI in the\n// DOM. This might be a single item, an entire list, a sidebar or panel, or\n// even the surrounding frame which wraps your whole app. Defining a chunk of\n// UI as a **View** allows you to define your DOM events declaratively, without\n// having to worry about render order ... and makes it easy for the view to\n// react to specific changes in the state of your models.\n\n// Creating a Backbone.View creates its initial element outside of the DOM,\n// if an existing element is not provided...\nexport function View(options) {\n this.cid = _.uniqueId('view');\n options || (options = {});\n _.extend(this, _.pick(options, viewOptions));\n this._ensureElement();\n this.initialize.apply(this, arguments);\n this.delegateEvents();\n};\n\n// Cached regex to split keys for `delegate`.\nvar delegateEventSplitter = /^(\\S+)\\s*(.*)$/;\n\n// List of view options to be merged as properties.\nvar viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];\n\n// Set up all inheritable **Backbone.View** properties and methods.\n_.extend(View.prototype, {\n\n // The default `tagName` of a View's element is `\"div\"`.\n tagName: 'div',\n\n // jQuery delegate for element lookup, scoped to DOM elements within the\n // current view. This should be preferred to global lookups where possible.\n $: function (selector) {\n return this.$el.find(selector);\n },\n\n // Initialize is an empty function by default. Override it with your own\n // initialization logic.\n initialize: function () { },\n\n // **render** is the core function that your view should override, in order\n // to populate its element (`this.el`), with the appropriate HTML. The\n // convention is for **render** to always return `this`.\n render: function () {\n return this;\n },\n\n // Remove this view by taking the element out of the DOM, and removing any\n // applicable Backbone.Events listeners.\n remove: function () {\n this.$el.remove();\n this.stopListening();\n return this;\n },\n\n // Change the view's element (`this.el` property), including event\n // re-delegation.\n setElement: function (element, delegate) {\n if (this.$el) this.undelegateEvents();\n this.$el = element instanceof exported.$ ? element : exported.$(element);\n this.el = this.$el[0];\n if (delegate !== false) this.delegateEvents();\n return this;\n },\n\n // Set callbacks, where `this.events` is a hash of\n //\n // *{\"event selector\": \"callback\"}*\n //\n // {\n // 'mousedown .title': 'edit',\n // 'click .button': 'save',\n // 'click .open': function(e) { ... }\n // }\n //\n // pairs. Callbacks will be bound to the view, with `this` set properly.\n // Uses event delegation for efficiency.\n // Omitting the selector binds the event to `this.el`.\n // This only works for delegate-able events: not `focus`, `blur`, and\n // not `change`, `submit`, and `reset` in Internet Explorer.\n delegateEvents: function (events) {\n if (!(events || (events = _.result(this, 'events')))) return this;\n this.undelegateEvents();\n for (var key in events) {\n var method = events[key];\n if (!_.isFunction(method)) method = this[events[key]];\n if (!method) continue;\n\n var match = key.match(delegateEventSplitter);\n var eventName = match[1], selector = match[2];\n method = _.bind(method, this);\n eventName += '.delegateEvents' + this.cid;\n if (selector === '') {\n this.$el.on(eventName, method);\n } else {\n this.$el.on(eventName, selector, method);\n }\n }\n return this;\n },\n\n // Clears all callbacks previously bound to the view with `delegateEvents`.\n // You usually don't need to use this, but may wish to if you have multiple\n // Backbone views attached to the same DOM element.\n undelegateEvents: function () {\n this.$el.off('.delegateEvents' + this.cid);\n return this;\n },\n\n // Ensure that the View has a DOM element to render into.\n // If `this.el` is a string, pass it through `$()`, take the first\n // matching element, and re-assign it to `el`. Otherwise, create\n // an element from the `id`, `className` and `tagName` properties.\n _ensureElement: function () {\n if (!this.el) {\n var attrs = _.extend({}, _.result(this, 'attributes'));\n if (this.id) attrs.id = _.result(this, 'id');\n if (this.className) attrs['class'] = _.result(this, 'className');\n var $el = exported.$('<' + _.result(this, 'tagName') + '>').attr(attrs);\n this.setElement($el, false);\n } else {\n this.setElement(_.result(this, 'el'), false);\n }\n }\n\n});\n\n// Backbone.Router\n// ---------------\n\n// Routers map faux-URLs to actions, and fire events when routes are\n// matched. Creating a new one sets its `routes` hash, if not set statically.\nexport function Router(options) {\n options || (options = {});\n if (options.routes) this.routes = options.routes;\n this._bindRoutes();\n this.initialize.apply(this, arguments);\n}\n\n// Cached regular expressions for matching named param parts and splatted\n// parts of route strings.\nvar optionalParam = /\\((.*?)\\)/g;\nvar namedParam = /(\\(\\?)?:\\w+/g;\nvar splatParam = /\\*\\w+/g;\nvar escapeRegExp = /[\\-{}\\[\\]+?.,\\\\\\^$|#\\s]/g;\n\n// Set up all inheritable **Backbone.Router** properties and methods.\n_.extend(Router.prototype, {\n\n // Initialize is an empty function by default. Override it with your own\n // initialization logic.\n initialize: function () { },\n\n // Manually bind a single named route to a callback. For example:\n //\n // this.route('search/:query/p:num', 'search', function(query, num) {\n // ...\n // });\n //\n route: function (route, name, callback) {\n if (!_.isRegExp(route)) route = this._routeToRegExp(route);\n if (_.isFunction(name)) {\n callback = name;\n name = '';\n }\n if (!callback) callback = this[name];\n var router = this;\n exported.history.route(route, function (fragment) {\n var args = router._extractParameters(route, fragment);\n if (router.execute(callback, args, name) !== false) {\n router.trigger.apply(router, ['route:' + name].concat(args));\n router.trigger('route', name, args);\n exported.history.trigger('route', router, name, args);\n }\n });\n return this;\n },\n\n // Execute a route handler with the provided parameters. This is an\n // excellent place to do pre-route setup or post-route cleanup.\n execute: function (callback, args, name) {\n if (callback) callback.apply(this, args);\n },\n\n // Simple proxy to `Backbone.history` to save a fragment into the history.\n navigate: function (fragment, options) {\n exported.history.navigate(fragment, options);\n return this;\n },\n\n // Bind all defined routes to `Backbone.history`. We have to reverse the\n // order of the routes here to support behavior where the most general\n // routes can be defined at the bottom of the route map.\n _bindRoutes: function () {\n if (!this.routes) return;\n this.routes = _.result(this, 'routes');\n var route, routes = _.keys(this.routes);\n while ((route = routes.pop()) != null) {\n this.route(route, this.routes[route]);\n }\n },\n\n // Convert a route string into a regular expression, suitable for matching\n // against the current location hash.\n _routeToRegExp: function (route) {\n route = route.replace(escapeRegExp, '\\\\$&')\n .replace(optionalParam, '(?:$1)?')\n .replace(namedParam, function (match, optional) {\n return optional ? match : '([^/?]+)';\n })\n .replace(splatParam, '([^?]*?)');\n return new RegExp('^' + route + '(?:\\\\?([\\\\s\\\\S]*))?$');\n },\n\n // Given a route, and a URL fragment that it matches, return the array of\n // extracted decoded parameters. Empty or unmatched parameters will be\n // treated as `null` to normalize cross-browser behavior.\n _extractParameters: function (route, fragment) {\n var params = route.exec(fragment).slice(1);\n return _.map(params, function (param, i) {\n // Don't decode the search params.\n if (i === params.length - 1) return param || null;\n return param ? decodeURIComponent(param) : null;\n });\n }\n\n});\n\n// Backbone.History\n// ----------------\n\n// Handles cross-browser history management, based on either\n// [pushState](http://diveintohtml5.info/history.html) and real URLs, or\n// [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)\n// and URL fragments. If the browser supports neither (old IE, natch),\n// falls back to polling.\nexport function History() {\n this.handlers = [];\n this.checkUrl = _.bind(this.checkUrl, this);\n\n // Ensure that `History` can be used outside of the browser.\n if (typeof window !== 'undefined') {\n this.location = window.location;\n this.history = window.history;\n }\n};\n\n// Cached regex for stripping a leading hash/slash and trailing space.\nvar routeStripper = /^[#\\/]|\\s+$/g;\n\n// Cached regex for stripping leading and trailing slashes.\nvar rootStripper = /^\\/+|\\/+$/g;\n\n// Cached regex for stripping urls of hash.\nvar pathStripper = /#.*$/;\n\n// Has the history handling already been started?\n(History as any).started = false;\n\n// Set up all inheritable **Backbone.History** properties and methods.\n_.extend(History.prototype, {\n\n // The default interval to poll for hash changes, if necessary, is\n // twenty times a second.\n interval: 50,\n\n // Are we at the app root?\n atRoot: function () {\n var path = this.location.pathname.replace(/[^\\/]$/, '$&/');\n return path === this.root && !this.getSearch();\n },\n\n // Does the pathname match the root?\n matchRoot: function () {\n var path = this.decodeFragment(this.location.pathname);\n var root = path.slice(0, this.root.length - 1) + '/';\n return root === this.root;\n },\n // Unicode characters in `location.pathname` are percent encoded so they're\n // decoded for comparison. `%25` should not be decoded since it may be part\n // of an encoded parameter.\n decodeFragment: function (fragment) {\n return decodeURI(fragment.replace(/%25/g, '%2525'));\n },\n // In IE6, the hash fragment and search params are incorrect if the\n // fragment contains `?`.\n getSearch: function () {\n var match = this.location.href.replace(/#.*/, '').match(/\\?.+/);\n return match ? match[0] : '';\n },\n // Gets the true hash value. Cannot use location.hash directly due to bug\n // in Firefox where location.hash will always be decoded.\n getHash: function (window) {\n var match = (window || this).location.href.match(/#(.*)$/);\n return match ? match[1] : '';\n },\n\n // Get the pathname and search params, without the root.\n getPath: function () {\n var path = this.decodeFragment(\n this.location.pathname + this.getSearch()\n ).slice(this.root.length - 1);\n return path.charAt(0) === '/' ? path.slice(1) : path;\n },\n\n // Get the cross-browser normalized URL fragment from the path or hash.\n getFragment: function (fragment) {\n if (fragment == null) {\n if (this._usePushState || !this._wantsHashChange) {\n fragment = this.getPath();\n } else {\n fragment = this.getHash();\n }\n }\n return fragment.replace(routeStripper, '');\n },\n\n // Start the hash change handling, returning `true` if the current URL matches\n // an existing route, and `false` otherwise.\n start: function (options) {\n if ((History as any).started) throw new Error('Backbone.history has already been started');\n (History as any).started = true;\n\n // Figure out the initial configuration. Do we need an iframe?\n // Is pushState desired ... is it available?\n this.options = _.extend({ root: '/' }, this.options, options);\n this.root = this.options.root;\n this._wantsHashChange = this.options.hashChange !== false;\n this._hasHashChange = 'onhashchange' in window && ((document as any).documentMode === void 0 || (document as any).documentMode > 7);\n this._useHashChange = this._wantsHashChange && this._hasHashChange;\n this._wantsPushState = !!this.options.pushState;\n this._hasPushState = !!(this.history && this.history.pushState);\n this._usePushState = this._wantsPushState && this._hasPushState;\n this.fragment = this.getFragment();\n\n // Normalize root to always include a leading and trailing slash.\n this.root = ('/' + this.root + '/').replace(rootStripper, '/');\n\n\n\n\n // Transition from hashChange to pushState or vice versa if both are\n // requested.\n if (this._wantsHashChange && this._wantsPushState) {\n\n // If we've started off with a route from a `pushState`-enabled\n // browser, but we're currently in a browser that doesn't support it...\n if (!this._hasPushState && !this.atRoot()) {\n var root = this.root.slice(0, -1) || '/';\n this.location.replace(root + '#' + this.getPath());\n // Return immediately as browser will do redirect to new url\n return true;\n\n // Or if we've started out with a hash-based route, but we're currently\n // in a browser where it could be `pushState`-based instead...\n } else if (this._hasPushState && this.atRoot()) {\n this.navigate(this.getHash(), { replace: true });\n }\n\n }\n\n // Proxy an iframe to handle location events if the browser doesn't\n // support the `hashchange` event, HTML5 history, or the user wants\n // `hashChange` but not `pushState`.\n if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) {\n this.iframe = document.createElement('iframe');\n this.iframe.src = 'javascript:0';\n this.iframe.style.display = 'none';\n this.iframe.tabIndex = -1;\n var body = document.body;\n // Using `appendChild` will throw on IE < 9 if the document is not ready.\n var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow;\n iWindow.document.open();\n iWindow.document.close();\n iWindow.location.hash = '#' + this.fragment;\n }\n\n // Add a cross-platform `addEventListener` shim for older browsers.\n var addEventListener = window.addEventListener || function (eventName, listener) {\n return attachEvent('on' + eventName, listener);\n };\n // Depending on whether we're using pushState or hashes, and whether\n // 'onhashchange' is supported, determine how we check the URL state.\n if (this._usePushState) {\n addEventListener('popstate', this.checkUrl, false);\n } else if (this._useHashChange && !this.iframe) {\n addEventListener('hashchange', this.checkUrl, false);\n } else if (this._wantsHashChange) {\n this._checkUrlInterval = setInterval(this.checkUrl, this.interval);\n }\n if (!this.options.silent) return this.loadUrl();\n },\n\n // Disable Backbone.history, perhaps temporarily. Not useful in a real app,\n // but possibly useful for unit testing Routers.\n stop: function () {\n // Add a cross-platform `removeEventListener` shim for older browsers.\n var removeEventListener = window.removeEventListener || function (eventName, listener) {\n return detachEvent('on' + eventName, listener);\n };\n // Remove window listeners.\n if (this._usePushState) {\n removeEventListener('popstate', this.checkUrl, false);\n } else if (this._useHashChange && !this.iframe) {\n removeEventListener('hashchange', this.checkUrl, false);\n }\n // Clean up the iframe if necessary.\n if (this.iframe) {\n document.body.removeChild(this.iframe);\n this.iframe = null;\n }\n // Some environments will throw when clearing an undefined interval.\n if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);\n (History as any).started = false;\n },\n\n // Add a route to be tested when the fragment changes. Routes added later\n // may override previous routes.\n route: function (route, callback) {\n this.handlers.unshift({ route: route, callback: callback });\n },\n\n // Checks the current URL to see if it has changed, and if it has,\n // calls `loadUrl`, normalizing across the hidden iframe.\n checkUrl: function (e) {\n var current = this.getFragment();\n // If the user pressed the back button, the iframe's hash will have\n // changed and we should use that for comparison.\n if (current === this.fragment && this.iframe) {\n current = this.getHash(this.iframe.contentWindow);\n }\n if (current === this.fragment) return false;\n if (this.iframe) this.navigate(current);\n this.loadUrl();\n },\n\n // Attempt to load the current URL fragment. If a route succeeds with a\n // match, returns `true`. If no defined routes matches the fragment,\n // returns `false`.\n loadUrl: function (fragment) {\n // If the root doesn't match, no routes can match either.\n if (!this.matchRoot()) return false;\n fragment = this.fragment = this.getFragment(fragment);\n return _.some(this.handlers, function (handler) {\n if (handler.route.test(fragment)) {\n handler.callback(fragment);\n return true;\n }\n });\n },\n\n // Save a fragment into the hash history, or replace the URL state if the\n // 'replace' option is passed. You are responsible for properly URL-encoding\n // the fragment in advance.\n //\n // The options object can contain `trigger: true` if you wish to have the\n // route callback be fired (not usually desirable), or `replace: true`, if\n // you wish to modify the current URL without adding an entry to the history.\n navigate: function (fragment, options) {\n if (!(History as any).started) return false;\n if (!options || options === true) options = { trigger: !!options };\n\n // Normalize the fragment.\n fragment = this.getFragment(fragment || '');\n\n // Don't include a trailing slash on the root.\n var root = this.root;\n if (fragment === '' || fragment.charAt(0) === '?') {\n root = root.slice(0, -1) || '/';\n }\n var url = root + fragment;\n // Strip the hash and decode for matching.\n fragment = this.decodeFragment(fragment.replace(pathStripper, ''));\n\n if (this.fragment === fragment) return;\n this.fragment = fragment;\n\n\n // If pushState is available, we use it to set the fragment as a real URL.\n if (this._usePushState) {\n this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);\n\n // If hash changes haven't been explicitly disabled, update the hash\n // fragment to store history.\n } else if (this._wantsHashChange) {\n this._updateHash(this.location, fragment, options.replace);\n if (this.iframe && (fragment !== this.getHash(this.iframe.contentWindow))) {\n var iWindow = this.iframe.contentWindow;\n // Opening and closing the iframe tricks IE7 and earlier to push a\n // history entry on hash-tag change. When replace is true, we don't\n // want this.\n if (!options.replace) {\n iWindow.document.open();\n iWindow.document.close();\n }\n\n this._updateHash(iWindow.location, fragment, options.replace);\n }\n\n // If you've told us that you explicitly don't want fallback hashchange-\n // based history, then `navigate` becomes a page refresh.\n } else {\n return this.location.assign(url);\n }\n if (options.trigger) return this.loadUrl(fragment);\n },\n\n // Update the hash location, either replacing the current entry, or adding\n // a new one to the browser history.\n _updateHash: function (location, fragment, replace) {\n if (replace) {\n var href = location.href.replace(/(javascript:|#).*$/, '');\n location.replace(href + '#' + fragment);\n } else {\n // Some browsers require that `hash` contains a leading #.\n location.hash = '#' + fragment;\n }\n }\n\n});\n\n// Create the default Backbone.history.\nexported.history = new History;\n\n","/**\n * Backbone.js 1.2.3 REST implementation\n * (c) 2010-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n * Backbone may be freely distributed under the MIT license.\n *\n * With validation patches - NestedTypes validation semantic is applied. (c) Vlad Balin, 2015.\n */\nimport * as _ from 'underscore'\nimport Backbone from './backbone'\n\nimport { tools } from './type-r'\nconst { defaults } = tools;\n\nexport type LazyValue< T > = () => T | T;\n\n// Map from CRUD to HTTP for our default `Backbone.sync` implementation.\nexport type Method = 'create' | 'update' | 'patch' | 'delete' | 'read' \n\nexport interface Restful {\n trigger( event : string, model, xhr, options )\n collection? : { trigger( event : string, model, xhr, options ) }\n toJSON( options : any ) : {}\n _xhr : JQueryXHR\n sync( method : string, object : Restful, options : SyncOptions )\n}\n\nexport interface SyncOptions {\n url? : LazyValue< string >\n data? : any\n attrs? : {}\n beforeSend? : ( xhr ) => any\n\n success? : ( resp : any ) => void\n error? : ( xhr?, textStatus?, errorThrown? ) => void\n\n textStatus? : string\n errorThrown? : any\n xhr? : any\n context? : {}\n}\n\nconst methodMap = {\n 'create' : 'POST',\n 'update' : 'PUT',\n 'patch' : 'PATCH',\n 'delete' : 'DELETE',\n 'read' : 'GET'\n};\n\nconst exported = {\n $ : Backbone.$,\n \n errorPromise : error => {\n var x = $.Deferred();\n x.reject( error );\n return x;\n },\n\n // Set the default implementation of `Backbone.ajax` to proxy through to `$`.\n // Override this if you'd like to use a different library.\n ajax : function( options : {} ){\n return $.ajax.apply( $, arguments );\n },\n\n sync,\n\n // Throw an error when a URL is needed, and none is supplied.\n urlError : function(){\n throw new Error( 'A \"url\" property or function must be specified' );\n }\n};\n\nexport default exported;\n\n // Backbone.sync\n // -------------\n\n // Override this function to change the manner in which Backbone persists\n // models to the server. You will be passed the type of request, and the\n // model in question. By default, makes a RESTful Ajax request\n // to the model's `url()`. Some possible customizations could be:\n //\n // * Use `setTimeout` to batch rapid-fire updates into a single request.\n // * Send up the models as XML instead of JSON.\n // * Persist models via WebSockets instead of Ajax.\n\nfunction sync( method : Method, model : Restful, options : SyncOptions = {} ) : JQueryXHR{\n var type = methodMap[ method ];\n\n // Default JSON-request options.\n var params : any = { type : type, dataType : 'json' };\n\n // Ensure that we have a URL.\n if( !options.url ){\n params.url = _.result( model, 'url' ) || exported.urlError();\n }\n\n // Ensure that we have the appropriate request data.\n if( options.data == null && model && (method === 'create' || method === 'update' || method === 'patch') ){\n params.contentType = 'application/json';\n params.data = JSON.stringify( options.attrs || model.toJSON( options ) );\n }\n\n // Don't process data on a non-GET request.\n if( params.type !== 'GET' ){\n params.processData = false;\n }\n\n // Pass along `textStatus` and `errorThrown` from jQuery.\n var error = options.error;\n options.error = function( xhr, textStatus, errorThrown ){\n options.textStatus = textStatus;\n options.errorThrown = errorThrown;\n if( error ) error.call( options.context, xhr, textStatus, errorThrown );\n };\n\n // Make the request, allowing the user to override any Ajax options.\n var xhr = options.xhr = exported.ajax( _.extend( params, options ) );\n model.trigger( 'request', model, xhr, options );\n model.collection && model.collection.trigger( 'request', model, xhr, options );\n return xhr;\n}","import Sync, { SyncOptions, Restful, LazyValue } from './sync'\n\nimport * as _ from 'underscore'\nimport * as Backbone from './backbone'\n\nimport { define, Model, Collection, tools, definitions, mixinRules } from './type-r'\nconst { defaults } = tools;\n\nconst transactionalProto = tools.getBaseClass( Model ).prototype;\n\nexport interface RestOptions extends SyncOptions {\n wait? : boolean\n patch? : boolean\n reset? : boolean\n validate? : boolean\n}\n\n@define({\n itemEvents : {\n destroy( model ){ this.remove( model ); }\n } \n})\nexport class RestCollection extends Collection implements Restful {\n _xhr : JQueryXHR\n\n dispose(){\n if( this._xhr && this._xhr.abort ) this._xhr.abort();\n super.dispose();\n }\n\n model : typeof RestModel\n url() : string { return this.model.prototype.urlRoot || ''; }\n\n _invalidate( options : { validate? : boolean } ) : boolean {\n var error;\n if( options.validate && ( error = this.validationError ) ){\n this.trigger( 'invalid', this, error, _.extend( { validationError : error }, options ) );\n return true;\n }\n }\n\n // Fetch the default set of models for this collection, resetting the\n // collection when they arrive. If `reset: true` is passed, the response\n // data will be passed through the `reset` method instead of `set`.\n fetch( options : RestOptions ) : any {\n options = _.extend( { parse : true }, options );\n var success = options.success;\n var collection = this;\n options.success = function( resp ){\n var method = options.reset ? 'reset' : 'set';\n collection[ method ]( resp, options );\n if( collection._invalidate( options ) ) return false;\n\n if( success ) success.call( options.context, collection, resp, options );\n collection.trigger( 'sync', collection, resp, options );\n };\n\n wrapError( this, options );\n return _sync( 'read', this, options );\n }\n\n create( a_model, options : any = {} ) : RestModel {\n const model : RestModel = a_model instanceof RestModel ?\n a_model :\n this.model.create( a_model, options );\n\n // Hack! For the situation when model instance is given, aquire it. \n model._owner || ( model._owner = this );\n\n options.wait || this.add([ model ], options );\n\n var collection = this;\n var success = options.success;\n options.success = ( model, resp, callbackOpts ) =>{\n if( options.wait ) this.add( [ model ], defaults({ parse : false }, callbackOpts ) );\n if( success ) success.call( callbackOpts.context, model, resp, callbackOpts );\n };\n\n model.save( null, options );\n return model;\n }\n\n // Proxy `Backbone.sync` by default -- but override this if you need\n // custom syncing semantics for *this* particular model.\n sync(){\n return Sync.sync.apply( this, arguments );\n }\n};\n\n@define({\n urlRoot : ''\n})\n@definitions({\n urlRoot : mixinRules.protoValue\n})\nexport class RestModel extends Model implements Restful {\n static Collection : typeof Collection = RestCollection as any;\n \n _xhr : JQueryXHR\n\n urlRoot : string\n\n /** @private */\n _invalidate( options : { validate? : boolean } ) : boolean {\n var error;\n if( options.validate && ( error = this.validationError ) ){\n triggerAndBubble( this, 'invalid', this, error, _.extend( { validationError : error }, options ) );\n return true;\n }\n }\n\n dispose(){\n if( this._xhr && this._xhr.abort ) this._xhr.abort();\n super.dispose();\n }\n\n // Fetch the model from the server, merging the response with the model's\n // local attributes. Any changed attributes will trigger a \"change\" event.\n fetch( options? : RestOptions ) : any {\n options = _.extend( { parse : true }, options );\n var model = this;\n var success = options.success;\n options.success = function( serverAttrs ){\n model.set( serverAttrs, options );\n if( model._invalidate( options ) ) return false;\n\n if( success ) success.call( options.context, model, serverAttrs, options );\n triggerAndBubble( model, 'sync', model, serverAttrs, options );\n };\n\n wrapError( this, options );\n return _sync( 'read', this, options );\n }\n\n // Proxy `Backbone.sync` by default -- but override this if you need\n // custom syncing semantics for *this* particular model.\n sync( method : string, self : this, options : SyncOptions ) : any\n sync() : JQueryXHR {\n return Sync.sync.apply( this, arguments );\n }\n\n // Set a hash of model attributes, and sync the model to the server.\n // If the server returns an attributes hash that differs, the model's\n // state will be `set` again.\n save( attrs? : {}, options? : RestOptions ) : any\n save( key : string, value : any, options? : RestOptions ) : any\n save( key, val, a_options? : RestOptions ) : any {\n // Handle both `\"key\", value` and `{key: value}` -style arguments.\n let attrs, originalOptions;\n\n if( key == null || typeof key === 'object' ){\n attrs = key;\n originalOptions = val || {};\n }\n else{\n (attrs = {})[ key ] = val;\n originalOptions = a_options || {};\n }\n\n const options = _.extend( { validate : true, parse : true }, originalOptions ),\n wait = options.wait;\n\n // If we're not waiting and attributes exist, save acts as\n // `set(attr).save(null, opts)` with validation. Otherwise, check if\n // the model will be valid when the attributes, if any, are set.\n if( attrs && !wait ){\n this.set( attrs, originalOptions );\n }\n\n if( this._invalidate( options ) ){\n if( attrs && wait ) this.set( attrs, originalOptions );\n return Sync.errorPromise( this.validationError );\n }\n\n // After a successful server-side save, the client is (optionally)\n // updated with the server-side state.\n var model = this;\n var success = options.success;\n var attributes = this.attributes;\n options.success = serverAttrs => {\n // Ensure attributes are restored during synchronous saves.\n model.attributes = attributes;\n if( wait ) serverAttrs = _.extend( {}, attrs, serverAttrs );\n\n if( serverAttrs ){\n // When server sends string, polimorphyc Model set screws up.\n transactionalProto.set.call( this, serverAttrs, options );\n if( model._invalidate( options ) ) return false;\n }\n\n if( success ) success.call( options.context, model, serverAttrs, options );\n triggerAndBubble( model, 'sync', model, serverAttrs, options );\n };\n\n wrapError( this, options );\n\n // Set temporary attributes if `{wait: true}` to properly find new ids.\n if( attrs && wait ) this.attributes = _.extend( {}, attributes, attrs );\n\n var method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');\n if( method === 'patch' && !options.attrs ) options.attrs = attrs;\n var xhr = _sync( method, this, options );\n\n // Restore attributes.\n this.attributes = attributes;\n\n return xhr;\n }\n\n // Destroy this model on the server if it was already persisted.\n // Optimistically removes the model from its collection, if it has one.\n // If `wait: true` is passed, waits for the server to respond before removal.\n destroy( options : RestOptions ) : any {\n options = options ? _.clone( options ) : {};\n var model = this;\n var success = options.success;\n var wait = options.wait;\n\n var destroy = function(){\n model.stopListening(); // TBD: figure out whenever we need to dispose the model.\n model.trigger( 'destroy', model, model.collection, options );\n };\n\n options.success = function( resp ){\n if( wait ) destroy();\n if( success ) success.call( options.context, model, resp, options );\n if( !model.isNew() ) triggerAndBubble( model, 'sync', model, resp, options );\n };\n\n var xhr : JQueryXHR;\n\n if( this.isNew() ){\n _.defer( options.success );\n }\n else{\n wrapError( this, options );\n xhr = _sync( 'delete', this, options );\n }\n\n if( !wait ) destroy();\n \n return xhr || false;\n }\n\n // Default URL for the model's representation on the server -- if you're\n // using Backbone's restful methods, override this to change the endpoint\n // that will be called.\n url() : string {\n var base =\n _.result( this, 'urlRoot' ) ||\n _.result( this.collection, 'url' ) ||\n Sync.urlError();\n\n if( this.isNew() ) return base;\n\n var id = this.get( this.idAttribute );\n\n return base.replace( /[^\\/]$/, '$&/' ) + encodeURIComponent( id );\n }\n\n set( key : string, value : any, options? : object ) : this\n set( attrs : {}, options? : object ) : this\n set( a, b?, c? ) : this {\n if( typeof a === 'string' ){\n if( c ){\n return super.set({ [ a ] : b }, c );\n }\n else{\n this[ a ] = b;\n return this;\n } \n }\n else{\n return super.set( a, b );\n }\n }\n}\n\nfunction _sync( method : string, _this : Restful, options ) : JQueryXHR {\n // Abort and pending IO request. Just one is allowed at the time.\n _this._xhr && _this._xhr.abort && _this._xhr.abort();\n const xhr = _this._xhr = _this.sync( method, _this, options );\n xhr && xhr.always && xhr.always( function(){ _this._xhr = void 0; });\n return xhr;\n}\n\n// Wrap an optional error callback with a fallback error event.\nfunction wrapError( model : any, options : RestOptions ){\n var error = options.error;\n options.error = function( resp ){\n if( error ) error.call( options.context, model, resp, options );\n triggerAndBubble( model, 'error', model, resp, options );\n };\n}\n\nfunction triggerAndBubble( model : any, ...args : any[] ){\n model.trigger.apply( model, args );\n const { collection } = model;\n collection && collection.trigger.apply( collection, args ); \n}","import * as _ from 'underscore'\n\nexport const ModelMixin = {\n pick( ...args : any[] ){\n return _.pick( this, args );\n },\n\n escape( attr ){\n return _.escape( this[ attr ] );\n },\n\n matches( attrs ){\n return !!_.iteratee( attrs, this )( this );\n },\n\n omit( ...keys : string[] ) : {} {\n return this.mapObject( ( value, key ) => {\n if( keys.indexOf( key ) < 0 ){\n return value;\n }\n });\n },\n\n invert(){\n const inverted = {};\n this.each( ( value, key ) => inverted[ value ] = key );\n return inverted;\n },\n\n pairs(){\n return this.map( ( value, key ) => [ key, value ] );\n },\n\n isEmpty(){\n return !this.values().length;\n },\n\n chain(){\n return _.chain( this.mapObject( x => x ) );\n }\n};\n\nexport const CollectionMixin = {\n where(attrs, first) {\n return this[first ? 'find' : 'filter'](attrs);\n },\n\n findWhere(attrs) {\n return this.where(attrs, true);\n }\n};\n\naddUnderscoreMethods( CollectionMixin, 'models', {\n forEach : 3, each : 3, map : 3, collect : 3, reduce : 4,\n foldl : 4, inject : 4, reduceRight : 4, foldr : 4, find : 3, findIndex : 3, findLastIndex : 3, detect : 3, filter : 3,\n select : 3, reject : 3, every : 3, all : 3, some : 3, any : 3, include : 3, includes : 3,\n contains : 3, invoke : 0, max : 3, min : 3, toArray : 1, size : 1, first : 3,\n head : 3, take : 3, initial : 3, rest : 3, tail : 3, drop : 3, last : 3,\n without : 0, difference : 0, indexOf : 3, shuffle : 1, lastIndexOf : 3,\n isEmpty : 1, chain : 1, sample : 3, partition : 3, groupBy : 3, countBy : 3,\n sortBy : 3, indexBy : 3\n});\n\nfunction addUnderscoreMethods(Mixin, attribute, methods ) {\n _.each(methods, function(length, method) {\n if (_[method]) Mixin[method] = addMethod(length, method, attribute);\n });\n}\n\n// Proxy Backbone class methods to Underscore functions, wrapping the model's\n// `attributes` object or collection's `models` array behind the scenes.\n//\n// collection.filter(function(model) { return model.get('age') > 10 });\n// collection.each(this.addView);\n//\n// `Function#apply` can be slow so we use the method's arg count, if we know it.\nfunction addMethod(length, method, attribute) {\n switch (length) {\n case 1: return function() {\n return _[method](this[attribute]);\n };\n case 2: return function(value) {\n return _[method](this[attribute], value);\n };\n case 3: return function(iteratee, context) {\n var value = this[ attribute ],\n callback = cb(iteratee, this);\n\n return arguments.length > 1 ?\n _[method]( value, callback, context)\n : _[method]( value, callback );\n };\n case 4: return function(iteratee, defaultVal, context) {\n var value = this[ attribute ],\n callback = cb(iteratee, this);\n\n return arguments.length > 1 ?\n _[method]( value, callback, defaultVal, context )\n : _[method](value, callback );\n };\n default: return function( ...args : any[] ) {\n args.unshift(this[attribute]);\n return _[method].apply(_, args);\n };\n }\n}\n\n// Support `collection.sortBy('attr')` and `collection.findWhere({id: 1})`.\nfunction cb(iteratee, instance) {\n switch( typeof iteratee ){\n case 'function' : return iteratee;\n case 'string' : return model => model.get( iteratee );\n case 'object' :\n if( !(iteratee instanceof instance.model )) return _.matches( iteratee ); \n }\n\n return iteratee;\n}","import Backbone from './backbone'\nimport * as _ from 'underscore'\nimport { mixins, mixinRules, define, Store } from './type-r'\nimport { RestModel, RestCollection } from './rest'\n\n@define({\n getStore : Store.prototype.getStore,\n get : Store.prototype.get,\n})\nexport class RestStore extends RestModel {}\n\n@define\nexport class LazyStore extends RestStore {\n _resolved : {} = {}\n\n initialize(){\n this.each( ( element, name ) => {\n if( !element ) return;\n\n element.store = this;\n\n var fetch = element.fetch;\n\n if( fetch ){\n const self = this;\n element.fetch = function() {\n return self._resolved[ name ] = fetch.apply( this, arguments );\n }\n }\n\n if( element instanceof RestCollection && element.length ){\n this._resolved[name] = true;\n }\n });\n }\n\n // fetch specified items, or all items if called without arguments.\n // returns jquery promise\n fetch( ...args : any[] /* hack, inheritance here violates LSP */) : any {\n var xhr = [],\n objsToFetch = args.length ? args : this.keys();\n\n for( let name of objsToFetch ){\n var attr = this.attributes[name];\n attr && attr.fetch && xhr.push( attr.fetch() );\n }\n\n const { $ } = Backbone;\n return $ && $.when && $.when.apply( $, xhr );\n }\n\n // fetch specified items, or all items if called without arguments.\n // returns first jquery promise.\n fetchOnce( ...args : string[] ) : JQueryXHR {\n var xhr = [],\n self = this,\n objsToFetch = args.length ? args : this.keys();\n\n for( let name of objsToFetch ){\n var attr = self.attributes[ name ];\n xhr.push( self._resolved[ name ] || attr && attr.fetch && attr.fetch());\n }\n\n const { $ } = Backbone;\n return $ && $.when && $.when.apply( $, xhr );\n }\n\n clear( ...args : string[] ) : this {\n var objsToClear = args.length ? args : this.keys();\n\n for( let name of objsToClear ){\n var element = this.attributes[ name ];\n\n if( element instanceof RestCollection ){\n element.reset();\n }\n else if( element instanceof Store ){\n element.clear();\n }\n else if( element instanceof RestModel ){\n element.set( element.defaults() )\n }\n\n this._resolved[ name ] = false;\n }\n\n return this;\n }\n\n static onDefine( definitions, BaseClass ){\n var attributes = definitions.defaults || definitions.attributes;\n\n // add automatic fetching on first element's access\n _.each( attributes, ( Type : Function, name ) => {\n if( Type.has ){\n attributes[name] = Type.has\n .set( function( value ){\n if( !value || !value.length ){\n const resolved = this._resolved || ( this._resolved = {} ); \n resolved[name] = false;\n }\n \n return value;\n })\n } \n });\n\n RestModel.onDefine.call( this, definitions, BaseClass );\n }\n} \n ","/**\n * Extend Type-R namespace\n */\nimport * as TypeR from './type-r'\nexport * from './type-r'\n\n/**\n * Prepare backbone View, Router, History, and Events. \n */\nimport Backbone from './backbone'\nimport { RestCollection, RestModel } from './rest'\nimport { Store as BaseStore, tools, MixinsState } from './type-r'\nimport Sync from './sync'\n\nimport { ModelMixin, CollectionMixin } from './underscore-mixin'\nimport { RestStore, LazyStore } from './rest-store'\n\n/**\n * Prepare \n */\n\nexport const Class : typeof TypeR.Messenger = TypeR.Messenger;\n\nconst Nested : typeof TypeR & typeof Backbone = Object.create( TypeR, tools.defaults({\n 'sync' : linkProperty( Sync, 'sync' ),\n 'errorPromise' : linkProperty( Sync, 'errorPromise' ),\n 'ajax' : linkProperty( Sync, 'ajax' ),\n 'history' : linkProperty( Backbone, 'history' ),\n 'store' : linkProperty( BaseStore, 'global' ),\n '$' : {\n get(){ return Backbone.$; },\n set( value ){ (Backbone).$ = (Sync).$ = value; }\n }\n },\n toProps( { Backbone, Class, Model : RestModel, Collection : RestCollection, LazyStore, Store : RestStore, defaults } ),\n toProps( Backbone )\n));\n\nexport default Nested;\n\nexport { Backbone, RestStore, LazyStore, RestCollection as Collection, RestModel as Model };\n\nexport function defaults( x ) : typeof Nested.Record {\n return Nested.Model.defaults( x );\n}\n\nexport * from './backbone';\n\nMixinsState.get( Nested.Mixable ).merge([ Nested.Events ]);\nNested.Messenger.mixins.populate( Backbone.View, Backbone.Router, Backbone.History );\nNested.Record.mixins.merge([ ModelMixin ]);\nNested.Record.Collection.mixins.merge([ CollectionMixin ]);\n\n/**\n * Local utilities\n */\nfunction linkProperty( Namespace, name ){\n return {\n get(){ return Namespace[ name ]; },\n set( value ){ Namespace[ name ] = value; }\n };\n}\n\nfunction toProps( obj ){\n return tools.transform({}, obj, x => ({ value : x }) );\n} "],"names":["extendStatics","d","b","Object","setPrototypeOf","__proto__","Array","p","hasOwnProperty","__extends","__","this","constructor","prototype","create","__assign","assign","t","s","i","n","arguments","length","call","apply","__rest","e","indexOf","getOwnPropertySymbols","__decorate","decorators","target","key","desc","c","r","getOwnPropertyDescriptor","Reflect","decorate","defineProperty","defaults","dest","source","name","other","levelToNumber","none","error","warn","info","log","debug","a_level","a_msg","a_props","msg","props","level","levelAsNumber","throw","logger","Error","stop","process","env","NODE_ENV","toString","window","something","value","__inner_state__","isArray","Boolean","keys_1","keys","join","body","x","isValidJSON","proto","getPrototypeOf","every","getBaseClass","Class","isEmpty","obj","some","fun","ArrayProto","arr","result","someArray","someObject","predicate","omit","discard","transform","once","func","memo","first","console","args","name_1","push","DateProto","Date","ObjectProto","notEqual","a","protoA","arraysNotEqual","keysA","objectsNotEqual","HashProto","hashMap","hash","definition","_i","names","names_1","_a","name_2","prop","o","Mixable","protoProps","staticProps","BaseClass","mixins","defineMixin","merge","mergeObject","getStaticDefinitions","onDefine","definitions","mergeInheritedMembers","spec","statics","TheSubclass","tslib_1.__extends","predefine","define","Constructor","__super__","MixinsState","get","populate","onExtend","ClassOrDefinition","Ctor","rules","definitionRules","propertyListDecorator","listName","slice","definitionDecorator","definitionKey","mergeRules","appliedMixins","rule","mixins_1","mixin","sourceMixins","concat","ctors","ctors_1","unshift","object","ignore","dontMix","forEachOwnProp","sourceProp","_this","assignProperty","mixinRules","protoValue","baseProto","resolveRule","function","caller","list","destProp","configurable","pipe","classFirst","classLast","map","EventMap","handlers","addEventsMap","addEvent","split","eventSplitter","getBubblingHandler","callback","EventDescriptor","event_1","on","event_2","off","handler","_bubblingHandlers","event","trigger5","trigger3","trigger2","context","next","listOff","_events","filteredHead","prev","head","ev","_callback","listSend3","EventHandler","once_1","_once","name_3","strings","api","events","test","self","queue","all","listSend2","listSend4","listSend5","f","listSend6","_idCount","uniqueId","cid","initialize","Messenger","localEvents","_localEvents","properties","eventsMap","defineProperties","toPropertyDescriptor","addReference","a_source","_listeningTo","removeAll","second","_disposed","stopListening","Events","listener","extend","tools.assign","tools.log","_validateNested","nested","validate","ValidationError","iteratee","each","eachError","referenceMask","reference","splitTail","path","match","substr","tail","pop","local","resolve","Function","shift","resolveReference","root","action","skip","getStore","getOwner","getOwnerEndpoint","collection","_owner","_endpoints","_ownerKey","createIOPromise","reject","onAbort","abort","fn","promise","Promise","a_resolve","a_reject","startIO","options","thenDo","abortIO","ioUpdate","_ioPromise","then","resp","triggerAndBubble","catch","err","eventSource","trigger","ItemsBehavior","cidPrefix","Transactional","endpoint","_endpoint","Transactional_1","_changeEventName","listenTo","isRoot","transactionApi","begin","update","set","commit","values","transaction","_createTransaction","_changeToken","data","_defaultStore","v","k","val","_validationError","validationError","getValidationError","_transaction","markAsDirty","dirty","silent","_isDirty","initiator","originalOptions","_onChildrenChange","aquire","owner","child","free","_begin","_markAsDirty","setAttribute","record","_attributes","doUpdate","attributes","_previousAttributes","AttributesCopy","_changedAttributes","UpdateRecordMixin","attribute","propagateChanges","forceAttributeChange","a_values","unknown","changes","parse","shouldBeAnObject","RecordTransaction","nested_1","constructorsMixin","attrDefs","attrs","attr","Attributes","_log","nested_2","changes_1","_b","emptyOptions","a_options","getHooks","transforms","changeHandlers","type","toJSON","changeEvents","hasCustomDefault","defaultValue","tools.isValidJSON","JSON","stringify","isRequired","convert","getHook_1","getHook","reduce","chainGetHooks","validate_1","chainTransforms","handleChange","chainChangeHandlers","doInit","AnyType","_attribute","model","isChanged","text","getClassName","Record","Attribute definition","Prev. value","New value","prevHook","nextHook","prevTransform","nextTransform","prevHandler","nextHandler","AggregatedType","clone","canBeUpdated","nestedTransaction","_shared","persistent","_handleChange","unset","dispose","ChainableAttributeSpec","check","metadata","asProp","ref","_onChange","emptyFunction","changed","eventMap","unsubscribe","subscribe","cloned","attrSpec","has","type_1","Number","String","inferType","shared","_isRequired","_has","DateType","date","timestamp","getTime","toISOString","msDatePattern","MSDateType","msDate","exec","TimestampType","supportsDate","isNaN","microsoft","struct","minutesOffset","isoDatePattern","numericKeys","undefined","UTC","safeParseDate","ImmutableClassType","PrimitiveType","NumericType","num","isFinite","Integer","Math","round","integer","ArrayType","ObjectType","doNothing","FunctionType","shareAndListen","listen","share","SharedType","implicitObject","attributesDefinition","baseClassAttributes","myAttributes","_.transform","createAttribute","allAttributes","_.defaults","ConstructorsMixin","_attributesArray","createPropertyDescriptor","attrSpecs","eventsApi.EventMap","createWatcherFromRef","wrapWatcher","localEventsMixin","attrDef","from","createSharedTypeSpec","Attribute","watcher","IORecordMixin","save","getEndpoint","json","isNew","id","fetch","read","destroy","remove","_cidCounter","_super","typeCheck","diff","hasChanged","old","nullify","forEachAttr","idAttribute","_attributesArray_1","copy","pinStore","errors","asJson","l","newModel","clear","Attributes definition:","Collection","BaseRecordAttributes","BaseRecordAttributesCopy","IdAttribute","attrName","getMetadata","DefaultCollection","dynamicMixin","_aquire","_free","convertAndAquire","_aggregationError","_itemEvents","sortElements","_comparator","sort","models","addIndex","index","removeIndex","updateIndex","previous","added","removed","sorted","CollectionTransaction","logAggregationError","added_1","_d","removed_1","_e","addTransaction","items","a_items","forceMerge","_byId","prevLength","a_items_1","item","appendElements","needSort","at","length_1","j","moveElements","sortOrMoveElements","silentOptions","emptySetTransaction","len","src","_reallocateEmpty","setTransaction","_prevById","prevModels","toAdd","orderKept","_reallocate","reusedCount","previous_1","_garbageCollect","children","children_1","freeAll","addedOrChanged","removeMany","toRemove","_removeFromIndex","begin$4","_count","CollectionRefsType","records","comparator","toElements","subset","subsetOf","RefsCollection","_SubsetOf","Refs","Subset","itemEvents","aa","bb","_store","objOrId","bindContext","toPredicateFunction","find","mapped","count","a_index","elements","add","reset","enabled","liveUpdates","filter_1","_liveUpdates","updated","tslib_1.__assign","aggregated","a_elements","previousModels","previousModels_1","toDispose","recordsOrIds","el","splice","notify","removeOne","modelOrId","a_next","Argument","Attributes spec","parsed","parseReference","collectionRef","RecordRefType","masterCollection","getMasterCollection","SubsetOf","subsetOfBehavior","refs","toArray","SubsetOfCollection","resolvedWith","resolveRefs","delaySet","raw","toggle","addAll","master","elements_1","tools.notEqual","Store","store","global","tools.defaults","listenToOnce","DefaultRecord","Model","method","previousBackbone","Backbone","exported","$","jQuery","history","VERSION","View","History","Router","noConflict","_.uniqueId","_.extend","_.pick","viewOptions","_ensureElement","delegateEvents","delegateEventSplitter","routes","_bindRoutes","tagName","selector","$el","render","setElement","element","delegate","undelegateEvents","_.result","_.isFunction","eventName","_.bind","className","optionalParam","namedParam","splatParam","escapeRegExp","checkUrl","location","route","_.isRegExp","_routeToRegExp","router","fragment","_extractParameters","execute","navigate","_.keys","replace","optional","RegExp","params","_.map","param","decodeURIComponent","routeStripper","rootStripper","pathStripper","started","interval","atRoot","pathname","getSearch","matchRoot","decodeFragment","decodeURI","href","getHash","getPath","charAt","getFragment","_usePushState","_wantsHashChange","start","hashChange","_hasHashChange","document","documentMode","_useHashChange","_wantsPushState","pushState","_hasPushState","iframe","createElement","style","display","tabIndex","iWindow","insertBefore","firstChild","contentWindow","open","close","addEventListener","attachEvent","_checkUrlInterval","setInterval","loadUrl","removeEventListener","detachEvent","removeChild","clearInterval","current","_.some","url","title","_updateHash","methodMap","patch","delete","errorPromise","Deferred","ajax","sync","dataType","urlError","contentType","processData","xhr","textStatus","errorThrown","transactionalProto","tools.getBaseClass","RestCollection","_xhr","urlRoot","success","_invalidate","wrapError","_sync","a_model","RestModel","wait","callbackOpts","_this_1","Sync","serverAttrs","_.clone","_.defer","base","encodeURIComponent","always","Mixin","methods","ModelMixin","pick","escape","_.escape","matches","_.iteratee","mapObject","invert","inverted","pairs","chain","_.chain","CollectionMixin","where","findWhere","cb","instance","_.matches","forEach","collect","foldl","inject","reduceRight","foldr","findIndex","findLastIndex","detect","filter","select","any","include","includes","contains","invoke","max","min","size","take","initial","rest","drop","last","without","difference","shuffle","lastIndexOf","sample","partition","groupBy","countBy","sortBy","indexBy","_.each","_","defaultVal","addMethod","RestStore","LazyStore","self_1","_resolved","objsToFetch_1","when","objsToFetch_2","objsToClear_1","Type","TypeR.Messenger","Nested","TypeR","linkProperty","BaseStore","toProps","Namespace","tools.transform"],"mappings":"mQAgBA,IAAIA,EAAgB,SAASC,EAAGC,GAI5B,OAHAF,EAAgBG,OAAOC,gBAClB,CAAEC,UAAW,cAAg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c7E,GAAM,QACrCzB,aAAiBsG,GAAc7E,GAAM,gBACrCvB,KAAiBoG,GAAc7E,GAAM,QACrClI,QAAiB+M,GAAcnN,GAAU,WACzCR,MAAiB2N,GAAcC,GAAW,UAC1ClN,EAAM,CACFlhB,eAAO,OAAOghB,GAASE,GACvBpW,aAAK3P,GAAe6lB,GAAUE,EAAUoI,GAAMpI,EAAI/lB,KAG1DkzB,GAAS,CAAErN,YAAU/kB,SAAO4kB,MAAQqI,GAAWhR,WAAawQ,GAAgB8E,aAAWjN,MAAQgN,GAAWj0B,cAC1G+0B,GAASrN,eAOG1nB,GAAUqC,GACtB,OAAOsyB,GAAOpN,MAAMvnB,SAAUqC,GAalC,SAASwyB,GAAcG,EAAW70B,GAC9B,MAAO,CACHuG,eAAO,OAAOsuB,EAAW70B,IACzBqR,aAAK3P,GAASmzB,EAAW70B,GAAS0B,IAI1C,SAASkzB,GAASlyB,GACd,OAAOoyB,EAAgB,GAAIpyB,EAAK,SAAAR,GAAK,OAAGR,MAAQQ,KAhBpDoE,EAAYC,IAAKiuB,GAAOtvB,SAAUM,MAAM,CAAEgvB,GAAOxnB,SACjDwnB,GAAOtoB,UAAU5G,OAAOkB,SAAU+gB,GAASM,KAAMN,GAASQ,OAAQR,GAASO,SAC3E0M,GAAO7d,OAAOrR,OAAOE,MAAM,CAAE8qB,KAC7BkE,GAAO7d,OAAO8H,WAAWnZ,OAAOE,MAAM,CAAE0rB"} \ No newline at end of file diff --git a/docs/compatibility.md b/docs/compatibility.md new file mode 100644 index 0000000..53bbf35 --- /dev/null +++ b/docs/compatibility.md @@ -0,0 +1,37 @@ +## Compatibility with NestedTypes 1.3 + +Major difference is the ownership policy, which is now enforced. +Because of that, NestedTypes 1.3 code will not work without modifications. + +### Refactoring Guide + +## Watch out for aggregation errors! + +Read the [Type-R documentation](https://volicon.github.io/Type-R/API_by_feature/Aggregation_tree.html) about aggregation and shared references. + +The majority of the refactoring required is adding `Model.shared` and `Collection.Refs` in places where the UI state has references to shared objects. + +Errors will appear when you are trying to assign parts of one aggregation tree to another. They will look like this: + +`[Model Update] Aggregated 'User.name : ModelType' attribute is assigned with an object which is aggregated somewhere else.` + +`[Model Update] Aggregated 'User.name : CollectionType' attribute is assigned with a shared Collection.Set.` + +`[Collection Update] Aggregating [[ Model.name : ] CollectionType ] collection is updated with models which are aggregated somewhere else.` + +## Old API Deprecations +- `modelOrCollection.clone()` now performs deep cloning. `modelOrCollection.deepClone()` is deprecated. + +### API changes + +- model `change:attr` events are not bubbled up by collection by default. Explicit `itemEvents` spec is required. Performance reasons. +- `object.trigger( 'a b' )` is not supported. Use `object.trigger( 'a' ).trigger( 'b' )`. Performance reasons. Not to mention that when you doing so you are most likely doing something wrong. +- `model.collection` is not set inside of `model.initialize()`. +- Collection.set `add` option is not supported. Period. But `remove` option works. +- Collection.subsetOf: + - `.justOne( x )` method is deprecated. Use `.set([ x ])` instead. + - `.removeAll()` method is deprecated. Use `.reset()` instead. +- Types of models and collection default valus are now inferred to `shared` types. +- Symbolic references - `store.x` syntax is deprecated, use `~x` instead. +- `Integer` -> `Number.integer` +- `Date` attribute doesn't parse MS format. Use `Date.microsoft`. \ No newline at end of file diff --git a/docs/hardrefs.md b/docs/hardrefs.md deleted file mode 100644 index 6ab3bc4..0000000 --- a/docs/hardrefs.md +++ /dev/null @@ -1,13 +0,0 @@ -Model.take( ref ) or Collection.take( ref ) - -- Resolved with ref value, evaluated on first read attempt -- Non-serializable by default -- Non-assignable -- Assugnment with `null` delete cached ref value, forcing ref evaluation next time. -- Change events bubble up by default - -Valid ref values: -- store reference -- model reference relative to `this` -- direct reference to object -- function, returning the value diff --git a/docs/stores.md b/docs/stores.md deleted file mode 100644 index 2bcd540..0000000 --- a/docs/stores.md +++ /dev/null @@ -1,170 +0,0 @@ -# Stores design guidlines - -- Store - is generalization of the session/api, and group of linked collections. -- Store consists of a bunch of collections and models, drives reference resolution, - and define the protocol for their fetching, saving, and real-time updates. -- There might be multiple stores in the system. They are linked in hierarchy, - performing look-ups for missing items in upper stores. - -Main store in the system - is 'session' object. It: -- can perform login and logout -- knows information about current session (user, activity, etc) -- may know some additional data -- performs real-time updates. - -(!) There might be special reference resolution algorithm, knowing about stores. - If item is not present in store, it will perform look-up in the parent store. (!) - -(!) Store hierarchy might be either explicit (store inside of the store), - or implicit (store requires another store definition). (!) - (!) Implicit is better, cause it guaranteed that solely reused code - will be correct. It forces singleton stores, though (!) - -(!) We might override 'get' for the store, and use 'get' in reference resolution. - It will allow us ti build 'vocabulary chain' (!) - -(!) Idea about store assigning itself to collections is not good. Impossible to - handle deep references. - -(!) Idea for generic ownership information might be not that bad. Lookup for closest - store can be optimized by caching nearest store reference in lower level nodes. - Let's say, inside of collections (and other stores). - -Ideally, it would be great to have an abitily to create multiple instances of -the same store dynamically. - -Ideally, if the same models and collections might be used in different stores. - -Ideally, stores defines I/O protocol, while models provide serialization mechanics. - -In this ideal world, there are multiple types of stores will exists: -- Store, consisting of independent REST api points. That's what store we have now do. -- Read-only store, loading its content in one REST operation, and pull itself for updates. - In fact, it's regular model. -- Store, loading and updating itself in real time through WS. That's interesting. - For that, models and collections must delegate sync to store. - - To generalize it, store is the model/collection which handles I/O. And there - is special kind of model (store), handling other stores. - - There must be some general way of distinguishing stores from regular models. - Store-capable model/collection must be able to participate as member too. - - For example: - // create collection store, where both model and collection is capable of saving themselves. - var collection = new Model.Collection.Store(); - collection.fetch(); - - -And in this sense, every model and especially collection now is store. What we -can do for the start - delegate I/O to the collection. Pair model/collection -defines simplest store. - -(?) What about defining that stores using JSX (?) -var my = ( - ) - -Bad. What about using JSX for linking stores with HTML? - - - ... - - - -(!) It might render inner stuff when everything is loaded, fetch data, and update -subtree when specified models are changed. Or, lower level: - - - - - -Good! (!) - -(!) What about combining it with fetch? - - - - -It might be very good idea (!) In fact, very-very good. -- it hides everything when data are not ready. -- render when everything is complete -- updates when selected events are fired. - -Declarative spec of data dependency, in render, always better. - -## Examples - -Two kinds of stores. 'Live' r/o, and REST r/w. - -'session' store, used as read-only 'live' store, the master one. -it includes 'users' store, containing schema for users and roles. - -separate store for editing encoders, as REST R/W store. - -var Admin = Store.extend({ - defaults : { - roles : Role.Collection, - users : User.Collection, - channelSets : ChannelSet.Collection - }, - - master : api -}); - -In this case, store lookup algorithm is totally dynamic. -When ref starts with 'store.', it resolve it traversing ownership to the first -available store, and using `deepGet` in order to resolve the rest of the reference. - -resolved store reference is cached in collections. - -'store.my.path' -> function(); -```javascript -function resolveStore(){ - // if we're owned by collection, ask it for the store. - if( this.collection ) return this.collection.resolveStore(); - - // if we're owned by the model, ask it for the store. - if( this._owner ) return this._owner.resolveStore(); - - // otherwise, use global store. - return this._defaultStore; -} - -// in collection -function resolveStore(){ - return this._store || ( this._store = this._owner ? this._owner.resolveStore() : this._defaultStore ); -} - -// in store -function resolveStore(){ - return this; -} - -// updated compile function... -function compile( str ){ - var path = str.split( '.' ); - if( path[ 0 ] === 'store' ){ - path[ 0 ] = 'resolveStore()'; - path[ 1 ] = 'get("' + path[ 1 ] + '")'; - } - - return new Function( 'self', 'return self.' + path.join( '.' ) + ';' ); -} - -// store's get function... -function get( attr ){ - if( this.__attributes[ attr ] ) return this[ attr ]; - - if( this._owner ) return this._owner.get( attr ); -} - -``` - -This algori - -Stores, used mainly for lookups and information display: - -Encoder-related information. Must be updated in real time. -encoders, probes, probeGroups, channelSets - -users, roles, channelSets diff --git a/docs/typespecs.md b/docs/typespecs.md new file mode 100644 index 0000000..87438bd --- /dev/null +++ b/docs/typespecs.md @@ -0,0 +1,305 @@ +# Quick API Reference + +Central concept in NestedTypes is `Record` type, which is the JS class with following capabilities: + +- Class members are deeply observable. +- It is serializable to JSON by default. +- Class members are typed and their changes are guardered with run-time type checks. + +`Model` is the `Record` subclass representing REST API endpoint. Models, records, and their collections +are used as building blocks to describe both application's UI state and its data layer. + +`Record` definition looks like normal ES6 class definition, but it's mandatory to declare +attributes. It looks like this: + +```javascript +import { define, Record } from 'nestedtypes' + +@define // <- decorator to perform class transformation +class User extends Model { + urlRoot : '/api/users', + + static attributes = { // <- attributes declaration + name : '', // <- can be either default value + email : String, // <- or any JS type constructor + isActive : true, + lastLogin : Date.value( null ) // <- or both + } +} + +const user = new User({ id : 5 }); // <- constructor takes optional attributes hash as an argument +user.fetch().done( () => { // GET /api/users/5 + user.name = 'John'; + user.save(); // PUT /api/users/5 +}); +``` + +## Record's Attributes Type Annotations Basics + +All record's attributes must be declared with `static attributes = { [ attrName ] : TypeAnnotation }` member. +Type annotation can be one of the following: + +- `attrName : Constructor`. Such as `attrName : Date`. +- `attrName : Constructor.value( defaultValue )`. Such as `lastLogin : Date.value( null )`. +- `attrName : defaultValue`. In this case, attribute type will be inferred from the value, so `isActive : true` has the same effect as `isActive : Boolean.value( true )`. + +Record attributes can be accessed directly, like `user.name = x`. When attribute is assigned, the type of the the value is +checked and being converted to the declared type with its constructor invocation if it's necessary. + +For the assignments like `user.isActive = x`, where `isActive` is declared as `Boolean` + +- it is assigned as is if `x` is `null` or boolean. +- for primitive types, it's converted with plain constructor invokation like `Boolean( x )`. +- For non-primitives convertion will invoke constructor with `new`, like `new Date( x )`. + +If it's impossible to convert the value it may be assigned with `NaN` or `Invalid Date` (or depending on the type update will be rejected), +and there will be an error in the console. + +Therefore, *it's guaranteed* that Record attributes always have declared type. + +## Collections + +Every model has corresponding `Collection` type declared implicitly. Collections +implements [Backbone Collection API](http://backbonejs.org/#Collection). + +```javascript +var users = new User.Collection(); + +users.fetch().done( () => { + console.log( users.length ); +}); +``` + +When Record is extended, its collection is extended too. The creation of implicit Colleciton type is equivalent to this: + +```javascript +@define +class Users extends Record.Collection {} + +@define +class User extends Record { + static Collection = Users; + // ... +} +``` + +You can use this pattern when you need to add custom members to the record's collection. + +## Nested Records and Collections + +Nested records and collections are declared with mentioning constructor in attribute type annotation. +All changes in nested objects are deeply observable; any change in children will cause change events in a parent. + +Records and collections emiting the [standard set of Backbone events](http://backbonejs.org/#Events-catalog), with following differences: + +- Collections does not bubble `change:[attribute]` event from the model by default (`change` event is bubbled); + event bubbling needs to be enabled for every particular event with `static itemEvents = { 'change:attr1' : true, ... }` declaration. +- Collections have `changes` event which is semantically similar to the model's `change`. + +### Transactions + +Record's `change` event (and collection's `changes` event) are _transactional_. Whatever some changes +are made as the reaction on any of change event, it won't cause additional `change` event for the owner. + +Also, you can explicitly group the sequence of changes to the single transaction: + +```javascript + some.record.transaction( record => { + record.a = 1; + record.b = 2; + ... + }); // some.record will emit single 'change' event if there was any changes. + + // Execute collection.each in the scope of transaction. + todoCollection.updateEach( item => item.done = true ); // One 'changes' event will be emitted. +``` + +### Aggregation + +Record can aggregate other records and collections in its attributes. + +```javascript +@define +class Team extends Record { + static attributes = { + members : User.Collection + leader : User + } +} + +const team = new Team(); +team.members.add( new User({ name : 'John' }) ); +``` + +Aggregated members are: + +- serialized as nested JSON. +- following operations recursively when the operation happens to its owner. + +Aggregated members forms the tree of exclusive ownership. The same record or collection instance cannot be aggregated in two places at the same time, +and this rule is checked and enforced. + +### Shared nested objects + +Records may have nested members which belongs to different ownership trees. +Special type annotations are required to mark attribute as shared. + +- `RecordType.shared` or `CollectionType.shared`. Reference to collection or record which may be aggregated somewhere else. `null` by default. +- `CollectionType.Refs` constructor. Collection of records which may be aggregated somewhere else. Defaults to empty collection. + +`CollectionType.Refs` is an equivalent to `CollectionType.shared.value( [] )` when used as attribute type annotation. + +Shared types are: + +- not a part of record's ownership tree. +- not serialized. +- Not a subject of recursive operations. They are empty by default, not cloned, not validated, and not disposed when the corresponding operation applied to the parent. + +In all other aspects, they are indistinguishable from aggregated records and collections. + +```javascript +@define +class Team extends Record { + static attributes = { + members : User.Collection.Refs + leader : User.shared + } +} +``` + +### Relationship by `id` + +It's possible to create serializable reference to the shared object which is represented in JSON as a record's id (or array of ids). +Special type annotation is required to point out the master collection which will be used to resolve ids to the records. + +- `RecordType.from( masterCollection )` represents an id reference to the model. +- `CollectionType.subsetOf( masterCollection )` represents the collection of models id references. + +id-reference types behaves as shared types, but: + +- they are serializable as an object id (or array of ids for collections). +- they are not observable (internal changes do not trigger change events on the record). + +`masterCollection` reference may be either: + +- direct reference to the globally available collection. +- function returning the reference to the collection. +- string, which is the *symbolic reference* to collection (dot-separated path to the collection taken relative to the record's `this`). + +```javascript +class Team extends Record { + static attributes = { + members : User.Collection, + leader : User.from( 'members' ) // <- leader is serializable reference to the record from members collection. + } +} +``` + +#### Owner-references + +`^` symbol in symbolic reference represents `getOwner()` call and returns the record owner. +Collections are skipped. + +Following example expects that `Team` record will be aggregated (alone or in a collection) together +with `users` collection. + +```javascript +class Team extends Record { + static attributes = { + members : User.Collection.subsetOf( '^users' ), + leader : User.from( 'members' ) + } +} +``` + +#### Tilda-References and Stores + +Symbolic reference staring with `~` is resolved relative to the record called _store_, +which is located with `record.getStore()` method. +For instance, reference `~users` will be resolved as `this.getStore().users`. + +`getStore()` uses following store location algorithm: + +1. It traverse an ownership tree upwards and return the first `Store` model it has found. +2. If none of the record's owners is the Store, it returns global store from `Nested.store`. + +`Store` is the subclass of the `Record` and behaves as a regular Record. +Therefore, resolution of id references depends on the context and you may have as many stores as you like. + +Following example expects that there's `users` collection in some upper record which is inherited from Store, +or (if there are none) in the global store: + +```javascript +class Team extends Record { + static attributes = { + members : User.Collection.subsetOf( '~users' ), + leader : User.from( 'members' ) + } +} +``` + +## Attribute has-annotations + +It's possible to control different aspects of record's attribute behavior through additional metadata. +All of them starts with a keyword `.has` added to the constructor type. + +Object describing an attribute is called *metatype*. Operations on metatypes are immutable (returns new metatype), +and can be chained. + +```javascript +// Declare Month metatype. +const Month = Number.value( 1 ).has.check( x => x > 0 && x <= 12 ); +``` + +#### attribute : Type.has.toJSON( false | ( x, name ) => json ) + +Override default serializer for the attribute. `false` option will exclude attribute from serialization. + +#### attribute : Type.has.parse( ( json, name ) => data ) + +Override default JSON parser for the attribute. + +#### attribute : Type.has.get( ( value, name ) => value ) + +Get hook which may transform attribute value on read. Get hooks can be chained. + +#### attribute : Type.has.set( ( value, name ) => value ) + +Set hook which may transform attribute value before it's assigned. Set hooks can be chained. + +#### attribute : RecordOrCollectionType.has.changeEvents( false ) + +When nested attribute is changed, don't mark the owner as changed. + +#### attribute : Type.has.events({ [ event ] : handler | handlerName }) + +Listen to the specified events from the attribute. handler can be either function or +the name of the record's method. + +#### attribute : Type.has.check( x => boolean, errorMsg? : any ) + +Attach check to the attribute. Checks can be chained. Attribute is valid whenever check function returns truthy value. + +errorMessage is optional. + +#### attribute : Type.isRequired + +Similar to `Type.has.check( x => x, 'Required' )`. + +## Validation + +Validation is performed recursively on ownership tree. Record and collection shares the same validation API. + +#### record.validate() + +Override it to add custom record-level validation. Method shoudl return truthy value in case of validation error. + +For attribute level checks see `Type.has.check` annotation. + +#### record.isValid() : boolean + +Checks whenever record is valid. + +#### record.validationError + +Return validation error object or null if there are no errors. diff --git a/endpoints/attributes/dist/index.js b/endpoints/attributes/dist/index.js new file mode 100644 index 0000000..e773bce --- /dev/null +++ b/endpoints/attributes/dist/index.js @@ -0,0 +1,2 @@ +!function(t,o){"object"==typeof exports&&"undefined"!=typeof module?o(exports):"function"==typeof define&&define.amd?define(["exports"],o):o(t.attributesIO={})}(this,function(t){"use strict";function o(){return new e}var e=function(){function t(){}return t.prototype.create=function(t,o){throw new Error("Method is not supported.")},t.prototype.update=function(t,o,e){throw new Error("Method is not supported.")},t.prototype.read=function(t,o,e){var r=e.keys().filter(function(t){return e[t]&&e[t].fetch}).map(function(t){return e[t].fetch(o)}),n=Promise.all(r).then(function(){});return n.abort=function(){r.forEach(function(t){return t.abort&&t.abort()})},n},t.prototype.destroy=function(t,o){throw new Error("Method is not supported.")},t.prototype.list=function(t){throw new Error("Method is not supported.")},t.prototype.subscribe=function(t){},t.prototype.unsubscribe=function(t){},t}();t.create=o,t.attributesIO=o,t.AttributesEndpoint=e,Object.defineProperty(t,"__esModule",{value:!0})}); +//# sourceMappingURL=index.js.map diff --git a/endpoints/attributes/dist/index.js.map b/endpoints/attributes/dist/index.js.map new file mode 100644 index 0000000..42998ae --- /dev/null +++ b/endpoints/attributes/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import { IOEndpoint, IOOptions, IOPromise } from 'type-r'\n\nexport function create(){\n return new AttributesEndpoint();\n}\n\nexport { create as attributesIO };\n\nexport class AttributesEndpoint implements IOEndpoint {\n create( json, options : IOOptions ) : IOPromise {\n throw new Error( 'Method is not supported.' ); \n }\n\n update( id, json, options : IOOptions ) : IOPromise {\n throw new Error( 'Method is not supported.' ); \n }\n\n read( id, options : IOOptions, record ) : IOPromise {\n const names = record.keys().filter( name => record[ name ] && record[ name ].fetch ),\n promises = names.map( name => record[ name ].fetch( options ) ),\n promise : IOPromise = Promise.all( promises ).then( () => {} );\n\n promise.abort = function(){\n promises.forEach( x => x.abort && x.abort() );\n }\n\n return promise;\n }\n\n destroy( id, options : IOOptions ) : IOPromise {\n throw new Error( 'Method is not supported.' ); \n }\n\n list( options? : IOOptions ) : IOPromise {\n throw new Error( 'Method is not supported.' );\n }\n\n subscribe( events ) : any {}\n unsubscribe( events) : any {}\n}\n\ndeclare var Promise;"],"names":["create","AttributesEndpoint","json","options","Error","id","record","promises","keys","filter","name","fetch","map","promise","Promise","all","then","abort","forEach","x","events"],"mappings":"wMAEgBA,IACZ,OAAO,IAAIC,mBAKf,cA+BA,OA9BIA,mBAAA,SAAQC,EAAMC,GACV,MAAM,IAAIC,MAAO,6BAGrBH,mBAAA,SAAQI,EAAIH,EAAMC,GACd,MAAM,IAAIC,MAAO,6BAGrBH,iBAAA,SAAMI,EAAIF,EAAqBG,GAC3B,IACIC,EADUD,EAAOE,OAAOC,OAAQ,SAAAC,GAAQ,OAAAJ,EAAQI,IAAUJ,EAAQI,GAAOC,QACxDC,IAAK,SAAAF,GAAQ,OAAAJ,EAAQI,GAAOC,MAAOR,KACpDU,EAA2BC,QAAQC,IAAKR,GAAWS,KAAM,cAM7D,OAJAH,EAAQI,MAAQ,WACZV,EAASW,QAAS,SAAAC,GAAK,OAAAA,EAAEF,OAASE,EAAEF,WAGjCJ,GAGXZ,oBAAA,SAASI,EAAIF,GACT,MAAM,IAAIC,MAAO,6BAGrBH,iBAAA,SAAME,GACF,MAAM,IAAIC,MAAO,6BAGrBH,sBAAA,SAAWmB,KACXnB,wBAAA,SAAamB"} \ No newline at end of file diff --git a/endpoints/attributes/lib/index.d.ts b/endpoints/attributes/lib/index.d.ts new file mode 100644 index 0000000..b609a30 --- /dev/null +++ b/endpoints/attributes/lib/index.d.ts @@ -0,0 +1,12 @@ +import { IOEndpoint, IOOptions, IOPromise } from 'type-r'; +export declare function create(): AttributesEndpoint; +export { create as attributesIO }; +export declare class AttributesEndpoint implements IOEndpoint { + create(json: any, options: IOOptions): IOPromise; + update(id: any, json: any, options: IOOptions): IOPromise; + read(id: any, options: IOOptions, record: any): IOPromise; + destroy(id: any, options: IOOptions): IOPromise; + list(options?: IOOptions): IOPromise; + subscribe(events: any): any; + unsubscribe(events: any): any; +} diff --git a/endpoints/attributes/lib/index.js b/endpoints/attributes/lib/index.js new file mode 100644 index 0000000..ffe324e --- /dev/null +++ b/endpoints/attributes/lib/index.js @@ -0,0 +1,32 @@ +export function create() { + return new AttributesEndpoint(); +} +export { create as attributesIO }; +var AttributesEndpoint = (function () { + function AttributesEndpoint() { + } + AttributesEndpoint.prototype.create = function (json, options) { + throw new Error('Method is not supported.'); + }; + AttributesEndpoint.prototype.update = function (id, json, options) { + throw new Error('Method is not supported.'); + }; + AttributesEndpoint.prototype.read = function (id, options, record) { + var names = record.keys().filter(function (name) { return record[name] && record[name].fetch; }), promises = names.map(function (name) { return record[name].fetch(options); }), promise = Promise.all(promises).then(function () { }); + promise.abort = function () { + promises.forEach(function (x) { return x.abort && x.abort(); }); + }; + return promise; + }; + AttributesEndpoint.prototype.destroy = function (id, options) { + throw new Error('Method is not supported.'); + }; + AttributesEndpoint.prototype.list = function (options) { + throw new Error('Method is not supported.'); + }; + AttributesEndpoint.prototype.subscribe = function (events) { }; + AttributesEndpoint.prototype.unsubscribe = function (events) { }; + return AttributesEndpoint; +}()); +export { AttributesEndpoint }; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/endpoints/attributes/lib/index.js.map b/endpoints/attributes/lib/index.js.map new file mode 100644 index 0000000..808ca6c --- /dev/null +++ b/endpoints/attributes/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,MAAM;IAClB,OAAO,IAAI,kBAAkB,EAAE,CAAC;AACpC,CAAC;AAED,OAAO,EAAE,MAAM,IAAI,YAAY,EAAE,CAAC;AAElC;IAAA;IA+BA,CAAC;IA9BG,mCAAM,GAAN,UAAQ,IAAI,EAAE,OAAmB;QAC7B,MAAM,IAAI,KAAK,CAAE,0BAA0B,CAAE,CAAC;IAClD,CAAC;IAED,mCAAM,GAAN,UAAQ,EAAE,EAAE,IAAI,EAAE,OAAmB;QACjC,MAAM,IAAI,KAAK,CAAE,0BAA0B,CAAE,CAAC;IAClD,CAAC;IAED,iCAAI,GAAJ,UAAM,EAAE,EAAE,OAAmB,EAAE,MAAM;QACjC,IAAM,KAAK,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC,MAAM,CAAE,UAAA,IAAI,IAAI,OAAA,MAAM,CAAE,IAAI,CAAE,IAAI,MAAM,CAAE,IAAI,CAAE,CAAC,KAAK,EAAtC,CAAsC,CAAE,EAChF,QAAQ,GAAG,KAAK,CAAC,GAAG,CAAE,UAAA,IAAI,IAAI,OAAA,MAAM,CAAE,IAAI,CAAE,CAAC,KAAK,CAAE,OAAO,CAAE,EAA/B,CAA+B,CAAE,EAC/D,OAAO,GAAoB,OAAO,CAAC,GAAG,CAAE,QAAQ,CAAE,CAAC,IAAI,CAAE,cAAO,CAAC,CAAE,CAAC;QAExE,OAAO,CAAC,KAAK,GAAG;YACZ,QAAQ,CAAC,OAAO,CAAE,UAAA,CAAC,IAAI,OAAA,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,KAAK,EAAE,EAApB,CAAoB,CAAE,CAAC;QAClD,CAAC,CAAA;QAED,OAAO,OAAO,CAAC;IACnB,CAAC;IAED,oCAAO,GAAP,UAAS,EAAE,EAAE,OAAmB;QAC5B,MAAM,IAAI,KAAK,CAAE,0BAA0B,CAAE,CAAC;IAClD,CAAC;IAED,iCAAI,GAAJ,UAAM,OAAoB;QACtB,MAAM,IAAI,KAAK,CAAE,0BAA0B,CAAE,CAAC;IAClD,CAAC;IAED,sCAAS,GAAT,UAAW,MAAM,IAAU,CAAC;IAC5B,wCAAW,GAAX,UAAa,MAAM,IAAS,CAAC;IACjC,yBAAC;AAAD,CAAC,AA/BD,IA+BC"} \ No newline at end of file diff --git a/endpoints/attributes/package.json b/endpoints/attributes/package.json new file mode 100644 index 0000000..a4874da --- /dev/null +++ b/endpoints/attributes/package.json @@ -0,0 +1,13 @@ +{ + "name": "attributesIO", + "main": "./dist/index.js", + "jsnext:main": "./lib/index.js", + "module": "./lib/index.js", + "types": "./lib/index.d.ts", + "scripts": { + "build":"../../node_modules/.bin/tsc && ../../node_modules/.bin/rollup --config" + }, + "author": "Vlad Balin", + "license": "MIT" +} + \ No newline at end of file diff --git a/endpoints/attributes/rollup.config.js b/endpoints/attributes/rollup.config.js new file mode 100644 index 0000000..7d925d1 --- /dev/null +++ b/endpoints/attributes/rollup.config.js @@ -0,0 +1,19 @@ +import resolve from 'rollup-plugin-node-resolve'; +import { uglify } from 'rollup-plugin-uglify'; +import sourcemaps from 'rollup-plugin-sourcemaps'; + +export default { + input : 'lib/index.js', + + output : { + file : 'dist/index.js', + format : 'umd', + name : 'attributesIO', + sourcemap: true + }, + plugins: [ + resolve(), //for support of `import X from "directory"` rather than verbose `import X from "directory/index"` + sourcemaps(), + uglify() + ] +}; \ No newline at end of file diff --git a/endpoints/attributes/src/index.ts b/endpoints/attributes/src/index.ts new file mode 100644 index 0000000..3fce12e --- /dev/null +++ b/endpoints/attributes/src/index.ts @@ -0,0 +1,42 @@ +import { IOEndpoint, IOOptions, IOPromise } from 'type-r' + +export function create(){ + return new AttributesEndpoint(); +} + +export { create as attributesIO }; + +export class AttributesEndpoint implements IOEndpoint { + create( json, options : IOOptions ) : IOPromise { + throw new Error( 'Method is not supported.' ); + } + + update( id, json, options : IOOptions ) : IOPromise { + throw new Error( 'Method is not supported.' ); + } + + read( id, options : IOOptions, record ) : IOPromise { + const names = record.keys().filter( name => record[ name ] && record[ name ].fetch ), + promises = names.map( name => record[ name ].fetch( options ) ), + promise : IOPromise = Promise.all( promises ).then( () => {} ); + + promise.abort = function(){ + promises.forEach( x => x.abort && x.abort() ); + } + + return promise; + } + + destroy( id, options : IOOptions ) : IOPromise { + throw new Error( 'Method is not supported.' ); + } + + list( options? : IOOptions ) : IOPromise { + throw new Error( 'Method is not supported.' ); + } + + subscribe( events ) : any {} + unsubscribe( events) : any {} +} + +declare var Promise; \ No newline at end of file diff --git a/endpoints/attributes/tsconfig.json b/endpoints/attributes/tsconfig.json new file mode 100644 index 0000000..671840d --- /dev/null +++ b/endpoints/attributes/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "es5", + "module":"es6", + "declaration": true, + "importHelpers": true, + "moduleResolution": "node", + "sourceMap": true, + "outDir": "./lib", + "noImplicitAny": false, + "removeComments":true, + "experimentalDecorators": true, + "baseUrl": ".", + "paths" : { + "type-r":[ "../../lib" ] + } + }, + "files":[ + "./src/index.ts" + ] + } \ No newline at end of file diff --git a/endpoints/localStorage/dist/index.js b/endpoints/localStorage/dist/index.js new file mode 100644 index 0000000..05713f3 --- /dev/null +++ b/endpoints/localStorage/dist/index.js @@ -0,0 +1,2 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("type-r")):"function"==typeof define&&define.amd?define(["exports","type-r"],e):e(t.localStorageIO={},t.Nested)}(this,function(t,e){"use strict";function o(t){return new r(t)}var r=function(){function t(t){this.key=t}return t.prototype.resolve=function(o){return e.createIOPromise(function(t,e){setTimeout(function(){t(o)},0)})},t.prototype.reject=function(o){return e.createIOPromise(function(t,e){setTimeout(function(){return e(o)},0)})},t.prototype.create=function(t,e){var o=this.index;return o.push(t.id=String(o[0]++)),this.index=o,this.set(t),this.resolve({id:t.id})},t.prototype.set=function(t){localStorage.setItem(this.key+"#"+t.id,JSON.stringify(t))},t.prototype.get=function(t){return JSON.parse(localStorage.getItem(this.key+"#"+t))},t.prototype.update=function(t,e,o){return e.id=t,this.set(e),this.resolve({})},t.prototype.read=function(t,e){var o=this.get(t);return o?this.resolve(o):this.reject("Not found")},t.prototype.destroy=function(e,t){return this.get(e)?(localStorage.removeItem(this.key+"#"+e),this.index=this.index.filter(function(t){return t!==e}),this.resolve({})):this.reject("Not found")},Object.defineProperty(t.prototype,"index",{get:function(){return JSON.parse(localStorage.getItem(this.key))||[0]},set:function(t){localStorage.setItem(this.key,JSON.stringify(t))},enumerable:!0,configurable:!0}),t.prototype.list=function(t){var e=this;this.index;return this.resolve(this.index.slice(1).map(function(t){return e.get(t)}))},t.prototype.subscribe=function(t){},t.prototype.unsubscribe=function(t){},t}();t.create=o,t.localStorageIO=o,t.LocalStorageEndpoint=r,Object.defineProperty(t,"__esModule",{value:!0})}); +//# sourceMappingURL=index.js.map diff --git a/endpoints/localStorage/dist/index.js.map b/endpoints/localStorage/dist/index.js.map new file mode 100644 index 0000000..47128c4 --- /dev/null +++ b/endpoints/localStorage/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import { IOEndpoint, IOOptions, IOPromise, createIOPromise } from 'type-r'\n\nexport type Index = number[];\n\nexport function create( key : string ){\n return new LocalStorageEndpoint( key );\n}\n\nexport { create as localStorageIO }\n\nexport class LocalStorageEndpoint implements IOEndpoint {\n constructor( public key : string ){\n }\n\n resolve( value ){\n return createIOPromise( ( resolve, reject ) => {\n setTimeout( () =>{\n resolve( value )\n }, 0 );\n });\n }\n \n reject( value ){\n return createIOPromise( ( resolve, reject ) => {\n setTimeout( () => reject( value ), 0 );\n });\n }\n\n create( json, options : IOOptions ) {\n const { index } = this;\n index.push( json.id = String( ( index[ 0 ] as number )++ ) );\n this.index = index;\n this.set( json );\n return this.resolve({ id : json.id });\n }\n\n set( json ){\n localStorage.setItem( this.key + '#' + json.id, JSON.stringify( json ) );\n }\n\n get( id ){\n return JSON.parse( localStorage.getItem( this.key + '#' + id ) );\n }\n\n update( id, json, options : IOOptions ) {\n json.id = id;\n this.set( json );\n return this.resolve( {} );\n }\n\n read( id, options : IOOptions ){\n const existing = this.get( id );\n return existing ?\n this.resolve( existing ) : \n this.reject( \"Not found\" );\n }\n\n destroy( id, options : IOOptions ){\n const existing = this.get( id );\n if( existing ){\n localStorage.removeItem( this.key + '#' + id );\n this.index = this.index.filter( x => x !== id );\n return this.resolve( {} );\n }\n else{\n return this.reject( \"Not found\" );\n }\n }\n\n get index() : ( string | number )[]{\n return JSON.parse( localStorage.getItem( this.key ) ) || [ 0 ];\n }\n\n set index( x ){\n localStorage.setItem( this.key, JSON.stringify( x ) );\n }\n\n list( options? : IOOptions ) {\n const { index } = this; \n return this.resolve( this.index.slice( 1 ).map( id => this.get( id ) ) );\n }\n\n subscribe( events ) : any {}\n unsubscribe( events) : any {}\n}"],"names":["create","key","LocalStorageEndpoint","this","value","createIOPromise","resolve","reject","setTimeout","json","options","index","push","id","String","set","localStorage","setItem","JSON","stringify","parse","getItem","existing","get","removeItem","filter","x","Object","slice","map","_this","events"],"mappings":"gPAIgBA,EAAQC,GACpB,OAAO,IAAIC,EAAsBD,oBAMjC,WAAoBA,GAAAE,SAAAF,EAyExB,OAtEIC,oBAAA,SAASE,GACL,OAAOC,kBAAiB,SAAEC,EAASC,GAC/BC,WAAY,WACRF,EAASF,IACV,MAIXF,mBAAA,SAAQE,GACJ,OAAOC,kBAAiB,SAAEC,EAASC,GAC/BC,WAAY,WAAM,OAAAD,EAAQH,IAAS,MAI3CF,mBAAA,SAAQO,EAAMC,GACF,IAAAC,aAIR,OAHAA,EAAMC,KAAMH,EAAKI,GAAKC,OAAUH,EAAO,OACvCR,KAAKQ,MAAQA,EACbR,KAAKY,IAAKN,GACHN,KAAKG,QAAQ,CAAEO,GAAKJ,EAAKI,MAGpCX,gBAAA,SAAKO,GACDO,aAAaC,QAASd,KAAKF,IAAM,IAAMQ,EAAKI,GAAIK,KAAKC,UAAWV,KAGpEP,gBAAA,SAAKW,GACD,OAAOK,KAAKE,MAAOJ,aAAaK,QAASlB,KAAKF,IAAM,IAAMY,KAG9DX,mBAAA,SAAQW,EAAIJ,EAAMC,GAGd,OAFAD,EAAKI,GAAKA,EACVV,KAAKY,IAAKN,GACHN,KAAKG,QAAS,KAGzBJ,iBAAA,SAAMW,EAAIH,GACN,IAAMY,EAAWnB,KAAKoB,IAAKV,GAC3B,OAAOS,EACHnB,KAAKG,QAASgB,GACdnB,KAAKI,OAAQ,cAGrBL,oBAAA,SAASW,EAAIH,GAET,OADiBP,KAAKoB,IAAKV,IAEvBG,aAAaQ,WAAYrB,KAAKF,IAAM,IAAMY,GAC1CV,KAAKQ,MAAQR,KAAKQ,MAAMc,OAAQ,SAAAC,GAAK,OAAAA,IAAMb,IACpCV,KAAKG,QAAS,KAGdH,KAAKI,OAAQ,cAI5BoB,sBAAIzB,yBAAJ,WACI,OAAOgB,KAAKE,MAAOJ,aAAaK,QAASlB,KAAKF,OAAW,CAAE,QAG/D,SAAWyB,GACPV,aAAaC,QAASd,KAAKF,IAAKiB,KAAKC,UAAWO,qCAGpDxB,iBAAA,SAAMQ,GAAN,sBAEI,OAAOP,KAAKG,QAASH,KAAKQ,MAAMiB,MAAO,GAAIC,IAAK,SAAAhB,GAAM,OAAAiB,EAAKP,IAAKV,OAGpEX,sBAAA,SAAW6B,KACX7B,wBAAA,SAAa6B"} \ No newline at end of file diff --git a/endpoints/localStorage/lib/index.d.ts b/endpoints/localStorage/lib/index.d.ts new file mode 100644 index 0000000..fc903e4 --- /dev/null +++ b/endpoints/localStorage/lib/index.d.ts @@ -0,0 +1,20 @@ +import { IOEndpoint, IOOptions, IOPromise } from 'type-r'; +export declare type Index = number[]; +export declare function create(key: string): LocalStorageEndpoint; +export { create as localStorageIO }; +export declare class LocalStorageEndpoint implements IOEndpoint { + key: string; + constructor(key: string); + resolve(value: any): IOPromise; + reject(value: any): IOPromise; + create(json: any, options: IOOptions): IOPromise; + set(json: any): void; + get(id: any): any; + update(id: any, json: any, options: IOOptions): IOPromise; + read(id: any, options: IOOptions): IOPromise; + destroy(id: any, options: IOOptions): IOPromise; + index: (string | number)[]; + list(options?: IOOptions): IOPromise; + subscribe(events: any): any; + unsubscribe(events: any): any; +} diff --git a/endpoints/localStorage/lib/index.js b/endpoints/localStorage/lib/index.js new file mode 100644 index 0000000..be38960 --- /dev/null +++ b/endpoints/localStorage/lib/index.js @@ -0,0 +1,77 @@ +import { createIOPromise } from 'type-r'; +export function create(key) { + return new LocalStorageEndpoint(key); +} +export { create as localStorageIO }; +var LocalStorageEndpoint = (function () { + function LocalStorageEndpoint(key) { + this.key = key; + } + LocalStorageEndpoint.prototype.resolve = function (value) { + return createIOPromise(function (resolve, reject) { + setTimeout(function () { + resolve(value); + }, 0); + }); + }; + LocalStorageEndpoint.prototype.reject = function (value) { + return createIOPromise(function (resolve, reject) { + setTimeout(function () { return reject(value); }, 0); + }); + }; + LocalStorageEndpoint.prototype.create = function (json, options) { + var index = this.index; + index.push(json.id = String(index[0]++)); + this.index = index; + this.set(json); + return this.resolve({ id: json.id }); + }; + LocalStorageEndpoint.prototype.set = function (json) { + localStorage.setItem(this.key + '#' + json.id, JSON.stringify(json)); + }; + LocalStorageEndpoint.prototype.get = function (id) { + return JSON.parse(localStorage.getItem(this.key + '#' + id)); + }; + LocalStorageEndpoint.prototype.update = function (id, json, options) { + json.id = id; + this.set(json); + return this.resolve({}); + }; + LocalStorageEndpoint.prototype.read = function (id, options) { + var existing = this.get(id); + return existing ? + this.resolve(existing) : + this.reject("Not found"); + }; + LocalStorageEndpoint.prototype.destroy = function (id, options) { + var existing = this.get(id); + if (existing) { + localStorage.removeItem(this.key + '#' + id); + this.index = this.index.filter(function (x) { return x !== id; }); + return this.resolve({}); + } + else { + return this.reject("Not found"); + } + }; + Object.defineProperty(LocalStorageEndpoint.prototype, "index", { + get: function () { + return JSON.parse(localStorage.getItem(this.key)) || [0]; + }, + set: function (x) { + localStorage.setItem(this.key, JSON.stringify(x)); + }, + enumerable: true, + configurable: true + }); + LocalStorageEndpoint.prototype.list = function (options) { + var _this = this; + var index = this.index; + return this.resolve(this.index.slice(1).map(function (id) { return _this.get(id); })); + }; + LocalStorageEndpoint.prototype.subscribe = function (events) { }; + LocalStorageEndpoint.prototype.unsubscribe = function (events) { }; + return LocalStorageEndpoint; +}()); +export { LocalStorageEndpoint }; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/endpoints/localStorage/lib/index.js.map b/endpoints/localStorage/lib/index.js.map new file mode 100644 index 0000000..c59ee9f --- /dev/null +++ b/endpoints/localStorage/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoC,eAAe,EAAE,MAAM,QAAQ,CAAA;AAI1E,MAAM,UAAU,MAAM,CAAE,GAAY;IAChC,OAAO,IAAI,oBAAoB,CAAE,GAAG,CAAE,CAAC;AAC3C,CAAC;AAED,OAAO,EAAE,MAAM,IAAI,cAAc,EAAE,CAAA;AAEnC;IACI,8BAAoB,GAAY;QAAZ,QAAG,GAAH,GAAG,CAAS;IAChC,CAAC;IAED,sCAAO,GAAP,UAAS,KAAK;QACV,OAAO,eAAe,CAAE,UAAE,OAAO,EAAE,MAAM;YACrC,UAAU,CAAE;gBACR,OAAO,CAAE,KAAK,CAAE,CAAA;YACpB,CAAC,EAAE,CAAC,CAAE,CAAC;QACX,CAAC,CAAC,CAAC;IACP,CAAC;IAED,qCAAM,GAAN,UAAQ,KAAK;QACT,OAAO,eAAe,CAAE,UAAE,OAAO,EAAE,MAAM;YACrC,UAA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jC,2BAAC;AAAD,CAAC,AA1ED,IA0EC"} \ No newline at end of file diff --git a/endpoints/localStorage/package.json b/endpoints/localStorage/package.json new file mode 100644 index 0000000..1d5d208 --- /dev/null +++ b/endpoints/localStorage/package.json @@ -0,0 +1,13 @@ +{ + "name": "localStorageIO", + "main": "./dist/index.js", + "jsnext:main": "./lib/index.js", + "module": "./lib/index.js", + "types": "./lib/index.d.ts", + "scripts": { + "build":"../../node_modules/.bin/tsc && ../../node_modules/.bin/rollup --config" + }, + "author": "Vlad Balin", + "license": "MIT" +} + \ No newline at end of file diff --git a/endpoints/localStorage/rollup.config.js b/endpoints/localStorage/rollup.config.js new file mode 100644 index 0000000..5d87a27 --- /dev/null +++ b/endpoints/localStorage/rollup.config.js @@ -0,0 +1,23 @@ +import resolve from 'rollup-plugin-node-resolve'; +import { uglify } from 'rollup-plugin-uglify'; +import sourcemaps from 'rollup-plugin-sourcemaps'; + +export default { + input : 'lib/index.js', + external : "type-r", + + output : { + file : 'dist/index.js', + format : 'umd', + name : 'localStorageIO', + sourcemap: true, + globals : { + "type-r":"Nested" + } + }, + plugins: [ + resolve(), //for support of `import X from "directory"` rather than verbose `import X from "directory/index"` + sourcemaps(), + uglify() + ] +}; \ No newline at end of file diff --git a/endpoints/localStorage/src/index.ts b/endpoints/localStorage/src/index.ts new file mode 100644 index 0000000..d024c3c --- /dev/null +++ b/endpoints/localStorage/src/index.ts @@ -0,0 +1,85 @@ +import { IOEndpoint, IOOptions, IOPromise, createIOPromise } from 'type-r' + +export type Index = number[]; + +export function create( key : string ){ + return new LocalStorageEndpoint( key ); +} + +export { create as localStorageIO } + +export class LocalStorageEndpoint implements IOEndpoint { + constructor( public key : string ){ + } + + resolve( value ){ + return createIOPromise( ( resolve, reject ) => { + setTimeout( () =>{ + resolve( value ) + }, 0 ); + }); + } + + reject( value ){ + return createIOPromise( ( resolve, reject ) => { + setTimeout( () => reject( value ), 0 ); + }); + } + + create( json, options : IOOptions ) { + const { index } = this; + index.push( json.id = String( ( index[ 0 ] as number )++ ) ); + this.index = index; + this.set( json ); + return this.resolve({ id : json.id }); + } + + set( json ){ + localStorage.setItem( this.key + '#' + json.id, JSON.stringify( json ) ); + } + + get( id ){ + return JSON.parse( localStorage.getItem( this.key + '#' + id ) ); + } + + update( id, json, options : IOOptions ) { + json.id = id; + this.set( json ); + return this.resolve( {} ); + } + + read( id, options : IOOptions ){ + const existing = this.get( id ); + return existing ? + this.resolve( existing ) : + this.reject( "Not found" ); + } + + destroy( id, options : IOOptions ){ + const existing = this.get( id ); + if( existing ){ + localStorage.removeItem( this.key + '#' + id ); + this.index = this.index.filter( x => x !== id ); + return this.resolve( {} ); + } + else{ + return this.reject( "Not found" ); + } + } + + get index() : ( string | number )[]{ + return JSON.parse( localStorage.getItem( this.key ) ) || [ 0 ]; + } + + set index( x ){ + localStorage.setItem( this.key, JSON.stringify( x ) ); + } + + list( options? : IOOptions ) { + const { index } = this; + return this.resolve( this.index.slice( 1 ).map( id => this.get( id ) ) ); + } + + subscribe( events ) : any {} + unsubscribe( events) : any {} +} \ No newline at end of file diff --git a/endpoints/localStorage/tsconfig.json b/endpoints/localStorage/tsconfig.json new file mode 100644 index 0000000..671840d --- /dev/null +++ b/endpoints/localStorage/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "es5", + "module":"es6", + "declaration": true, + "importHelpers": true, + "moduleResolution": "node", + "sourceMap": true, + "outDir": "./lib", + "noImplicitAny": false, + "removeComments":true, + "experimentalDecorators": true, + "baseUrl": ".", + "paths" : { + "type-r":[ "../../lib" ] + } + }, + "files":[ + "./src/index.ts" + ] + } \ No newline at end of file diff --git a/endpoints/memory/dist/index.js b/endpoints/memory/dist/index.js new file mode 100644 index 0000000..0deb6e0 --- /dev/null +++ b/endpoints/memory/dist/index.js @@ -0,0 +1,2 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("type-r")):"function"==typeof define&&define.amd?define(["exports","type-r"],e):e(t.memoryIO={},t.Nested)}(this,function(t,e){"use strict";function i(t,e){return void 0===t&&(t=[]),void 0===e&&(e=50),new r(t,e)}var r=function(){function t(t,e){this.delay=e,this.index=[0],this.items={};for(var i=0,r=t;i {\n setTimeout( () => resolve( value ), this.delay );\n });\n }\n \n reject( value ){\n return createIOPromise( ( resolve, reject ) => {\n setTimeout( () => reject( value ), this.delay );\n });\n }\n\n constructor( init : object[], public delay : number ){\n for( let obj of init ){\n this.create( obj, {} );\n }\n }\n\n index : Index = [ 0 ];\n items = {};\n\n generateId( a_id ){\n // Update index counter...\n const id = Number( a_id );\n if( !isNaN( id ) ){\n this.index[ 0 ] = Math.max( this.index[ 0 ] as number, id );\n }\n\n // Return id...\n return a_id || String( ( this.index[ 0 ] as number ) ++ );\n }\n\n create( json, options ) {\n const id = json.id = this.generateId( json.id );\n this.index.push( id );\n this.items[ id ] = json;\n return this.resolve({ id });\n }\n\n update( id, json, options ) {\n this.items[ id ] = json;\n return this.resolve( {} );\n }\n\n read( id, options ){\n const existing = this.items[ id ];\n return existing ?\n this.resolve( existing ) : \n this.reject( \"Not found\" );\n }\n\n destroy( id, options ){\n const existing = this.items[ id ];\n if( existing ){\n delete this.items[ id ];\n this.index = this.index.filter( x => x !== id );\n return this.resolve( {} );\n }\n else{\n return this.reject( \"Not found\" );\n }\n }\n\n list( options? : object ) {\n return this.resolve( this.index.slice( 1 ).map( id => this.items[ id ]) );\n }\n\n subscribe( events ) : any {}\n unsubscribe( events) : any {}\n}"],"names":["create","init","delay","MemoryEndpoint","this","init_1","_i","obj","value","createIOPromise","resolve","reject","setTimeout","_this","a_id","id","Number","isNaN","index","Math","max","String","json","options","generateId","push","items","existing","filter","x","slice","map","events"],"mappings":"0OAIgBA,EAAQC,EAAWC,GAC/B,oBADoBD,mBAAWC,MACxB,IAAIC,EAAgBF,EAAMC,oBAkBjC,WAAaD,EAAwBC,GAAAE,WAAAF,EAMrCE,WAAgB,CAAE,GAClBA,WAAQ,GANJ,IAAgB,QAAAC,IAAAC,WA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file diff --git a/endpoints/memory/lib/index.d.ts b/endpoints/memory/lib/index.d.ts new file mode 100644 index 0000000..70233f1 --- /dev/null +++ b/endpoints/memory/lib/index.d.ts @@ -0,0 +1,20 @@ +import { IOEndpoint, IOPromise } from 'type-r'; +export declare type Index = (number | string)[]; +export declare function create(init?: any[], delay?: number): MemoryEndpoint; +export { create as memoryIO }; +export declare class MemoryEndpoint implements IOEndpoint { + delay: number; + resolve(value: any): IOPromise; + reject(value: any): IOPromise; + constructor(init: object[], delay: number); + index: Index; + items: {}; + generateId(a_id: any): any; + create(json: any, options: any): IOPromise; + update(id: any, json: any, options: any): IOPromise; + read(id: any, options: any): IOPromise; + destroy(id: any, options: any): IOPromise; + list(options?: object): IOPromise; + subscribe(events: any): any; + unsubscribe(events: any): any; +} diff --git a/endpoints/memory/lib/index.js b/endpoints/memory/lib/index.js new file mode 100644 index 0000000..6576c3b --- /dev/null +++ b/endpoints/memory/lib/index.js @@ -0,0 +1,73 @@ +import { createIOPromise } from 'type-r'; +export function create(init, delay) { + if (init === void 0) { init = []; } + if (delay === void 0) { delay = 50; } + return new MemoryEndpoint(init, delay); +} +export { create as memoryIO }; +var MemoryEndpoint = (function () { + function MemoryEndpoint(init, delay) { + this.delay = delay; + this.index = [0]; + this.items = {}; + for (var _i = 0, init_1 = init; _i < init_1.length; _i++) { + var obj = init_1[_i]; + this.create(obj, {}); + } + } + MemoryEndpoint.prototype.resolve = function (value) { + var _this = this; + return createIOPromise(function (resolve, reject) { + setTimeout(function () { return resolve(value); }, _this.delay); + }); + }; + MemoryEndpoint.prototype.reject = function (value) { + var _this = this; + return createIOPromise(function (resolve, reject) { + setTimeout(function () { return reject(value); }, _this.delay); + }); + }; + MemoryEndpoint.prototype.generateId = function (a_id) { + var id = Number(a_id); + if (!isNaN(id)) { + this.index[0] = Math.max(this.index[0], id); + } + return a_id || String(this.index[0]++); + }; + MemoryEndpoint.prototype.create = function (json, options) { + var id = json.id = this.generateId(json.id); + this.index.push(id); + this.items[id] = json; + return this.resolve({ id: id }); + }; + MemoryEndpoint.prototype.update = function (id, json, options) { + this.items[id] = json; + return this.resolve({}); + }; + MemoryEndpoint.prototype.read = function (id, options) { + var existing = this.items[id]; + return existing ? + this.resolve(existing) : + this.reject("Not found"); + }; + MemoryEndpoint.prototype.destroy = function (id, options) { + var existing = this.items[id]; + if (existing) { + delete this.items[id]; + this.index = this.index.filter(function (x) { return x !== id; }); + return this.resolve({}); + } + else { + return this.reject("Not found"); + } + }; + MemoryEndpoint.prototype.list = function (options) { + var _this = this; + return this.resolve(this.index.slice(1).map(function (id) { return _this.items[id]; })); + }; + MemoryEndpoint.prototype.subscribe = function (events) { }; + MemoryEndpoint.prototype.unsubscribe = function (events) { }; + return MemoryEndpoint; +}()); +export { MemoryEndpoint }; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/endpoints/memory/lib/index.js.map b/endpoints/memory/lib/index.js.map new file mode 100644 index 0000000..9722c43 --- /dev/null +++ b/endpoints/memory/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAyB,eAAe,EAAE,MAAM,QAAQ,CAAA;AAI/D,MAAM,UAAU,MAAM,CAAE,IAAS,EAAE,KAAU;IAArB,qBAAA,EAAA,SAAS;IAAE,sBAAA,EAAA,UAAU;IACzC,OAAO,IAAI,cAAc,CAAE,IAAI,EAAE,KAAK,CAAE,CAAC;AAC7C,CAAC;AAED,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,CAAC;AAE9B;IAaI,wBAAa,IAAe,EAAS,KAAc;QAAd,UAAK,GAAL,KAAK,CAAS;QAMnD,UAAK,GAAW,CAAE,CAAC,CAAE,CAAC;QACtB,UAAK,GAAG,EAAE,CAAC;QANP,KAAgB,UAAI,EAAJ,aAAI,EAAJ,kBAAI,EAAJ,IAAI,EAAE;YAAjB,IAAI,GAAG,aAAA;YACR,IAAI,CAAC,MAAM,CAAE,GAAG,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CAAC;IACjC,qBAAC;AAAD,CAAC,AAtED,IAsEC"} \ No newline at end of file diff --git a/endpoints/memory/package.json b/endpoints/memory/package.json new file mode 100644 index 0000000..4696909 --- /dev/null +++ b/endpoints/memory/package.json @@ -0,0 +1,13 @@ +{ + "name": "memoryIO", + "main": "./dist/index.js", + "jsnext:main": "./lib/index.js", + "module": "./lib/index.js", + "types": "./lib/index.d.ts", + "scripts": { + "build":"../../node_modules/.bin/tsc && ../../node_modules/.bin/rollup --config" + }, + "author": "Vlad Balin", + "license": "MIT" +} + \ No newline at end of file diff --git a/endpoints/memory/rollup.config.js b/endpoints/memory/rollup.config.js new file mode 100644 index 0000000..12452a1 --- /dev/null +++ b/endpoints/memory/rollup.config.js @@ -0,0 +1,23 @@ +import resolve from 'rollup-plugin-node-resolve'; +import { uglify } from 'rollup-plugin-uglify'; +import sourcemaps from 'rollup-plugin-sourcemaps'; + +export default { + input : 'lib/index.js', + external : "type-r", + + output : { + file : 'dist/index.js', + format : 'umd', + name : 'memoryIO', + sourcemap: true, + globals : { + "type-r":"Nested" + } + }, + plugins: [ + resolve(), //for support of `import X from "directory"` rather than verbose `import X from "directory/index"` + sourcemaps(), + uglify() + ] +}; \ No newline at end of file diff --git a/endpoints/memory/src/index.ts b/endpoints/memory/src/index.ts new file mode 100644 index 0000000..f898f80 --- /dev/null +++ b/endpoints/memory/src/index.ts @@ -0,0 +1,81 @@ +import { IOEndpoint, IOPromise, createIOPromise } from 'type-r' + +export type Index = ( number | string )[]; + +export function create( init = [], delay = 50 ){ + return new MemoryEndpoint( init, delay ); +} + +export { create as memoryIO }; + +export class MemoryEndpoint implements IOEndpoint { + resolve( value ){ + return createIOPromise( ( resolve, reject ) => { + setTimeout( () => resolve( value ), this.delay ); + }); + } + + reject( value ){ + return createIOPromise( ( resolve, reject ) => { + setTimeout( () => reject( value ), this.delay ); + }); + } + + constructor( init : object[], public delay : number ){ + for( let obj of init ){ + this.create( obj, {} ); + } + } + + index : Index = [ 0 ]; + items = {}; + + generateId( a_id ){ + // Update index counter... + const id = Number( a_id ); + if( !isNaN( id ) ){ + this.index[ 0 ] = Math.max( this.index[ 0 ] as number, id ); + } + + // Return id... + return a_id || String( ( this.index[ 0 ] as number ) ++ ); + } + + create( json, options ) { + const id = json.id = this.generateId( json.id ); + this.index.push( id ); + this.items[ id ] = json; + return this.resolve({ id }); + } + + update( id, json, options ) { + this.items[ id ] = json; + return this.resolve( {} ); + } + + read( id, options ){ + const existing = this.items[ id ]; + return existing ? + this.resolve( existing ) : + this.reject( "Not found" ); + } + + destroy( id, options ){ + const existing = this.items[ id ]; + if( existing ){ + delete this.items[ id ]; + this.index = this.index.filter( x => x !== id ); + return this.resolve( {} ); + } + else{ + return this.reject( "Not found" ); + } + } + + list( options? : object ) { + return this.resolve( this.index.slice( 1 ).map( id => this.items[ id ]) ); + } + + subscribe( events ) : any {} + unsubscribe( events) : any {} +} \ No newline at end of file diff --git a/endpoints/memory/tsconfig.json b/endpoints/memory/tsconfig.json new file mode 100644 index 0000000..671840d --- /dev/null +++ b/endpoints/memory/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "es5", + "module":"es6", + "declaration": true, + "importHelpers": true, + "moduleResolution": "node", + "sourceMap": true, + "outDir": "./lib", + "noImplicitAny": false, + "removeComments":true, + "experimentalDecorators": true, + "baseUrl": ".", + "paths" : { + "type-r":[ "../../lib" ] + } + }, + "files":[ + "./src/index.ts" + ] + } \ No newline at end of file diff --git a/endpoints/proxy/README.md b/endpoints/proxy/README.md new file mode 100644 index 0000000..2553a4a --- /dev/null +++ b/endpoints/proxy/README.md @@ -0,0 +1,15 @@ +# Proxy Endpoint + +Create IO endpoint from the Record class. This endpoint is designed for use on the server side data layer managed by Type-R. + +Assuming that you have Type-R records with endpoints working with the database, you can create an endpoint which will use +Record subclass as a transport. + + import { proxyIO } from 'type-r/endpoint/proxy' + + ... + + const usersIO = proxyIO( User ); + +This endpoint can be connected to the RESTful endpoint API on the server side which will serve JSON to the restfulIO endpoint on the client. +An advantage of this approach is that JSON schema will be transparently validated on the server side by the Type-R. \ No newline at end of file diff --git a/endpoints/proxy/dist/index.js b/endpoints/proxy/dist/index.js new file mode 100644 index 0000000..f246141 --- /dev/null +++ b/endpoints/proxy/dist/index.js @@ -0,0 +1,2 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.proxyIO={})}(this,function(t){"use strict";function i(i,u,c,s){return new(c||(c=Promise))(function(t,e){function n(t){try{o(s.next(t))}catch(t){e(t)}}function r(t){try{o(s.throw(t))}catch(t){e(t)}}function o(e){e.done?t(e.value):new c(function(t){t(e.value)}).then(n,r)}o((s=s.apply(i,u||[])).next())})}function u(n,r){var o,i,u,t,c={label:0,sent:function(){if(1&u[0])throw u[1];return u[1]},trys:[],ops:[]};return t={next:e(0),throw:e(1),return:e(2)},"function"==typeof Symbol&&(t[Symbol.iterator]=function(){return this}),t;function e(e){return function(t){return function(e){if(o)throw new TypeError("Generator is already executing.");for(;c;)try{if(o=1,i&&(u=2&e[0]?i.return:e[0]?i.throw||((u=i.return)&&u.call(i),0):i.next)&&!(u=u.call(i,e[1])).done)return u;switch(i=0,u&&(e=[2&e[0],u.value]),e[0]){case 0:case 1:u=e;break;case 4:return c.label++,{value:e[1],done:!1};case 5:c.label++,i=e[1],e=[0];continue;case 7:e=c.ops.pop(),c.trys.pop();continue;default:if(!(u=0<(u=c.trys).length&&u[u.length-1])&&(6===e[0]||2===e[0])){c=0;continue}if(3===e[0]&&(!u||e[1]>u[0]&&e[1]= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\r\n if (m) return m.call(o);\r\n return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n","import { IOEndpoint, IOOptions, IOPromise, createIOPromise, Record } from 'type-r'\n\nexport function proxyIO( record : typeof Record ){\n return new ProxyEndpoint( record );\n}\n\nexport class ProxyEndpoint implements IOEndpoint {\n Record : typeof Record\n \n get endpoint(){\n return this.Record.prototype._endpoint;\n }\n\n constructor( record : typeof Record ){\n this.Record = record;\n\n // Create proxy methods...\n const source = Object.getPrototypeOf( this.endpoint );\n\n Object.keys( source ).forEach( key => {\n if( !this[ key ] && typeof source[ key ] === 'function' ){\n this[ key ] = function(){\n return source[ key ].apply( this.endpoint, arguments );\n }\n }\n });\n }\n\n async subscribe( events, target ){\n return this.endpoint.subscribe( events, target );\n }\n\n unsubscribe( events, target ){\n this.endpoint.unsubscribe( events, target );\n }\n\n async list( options ){\n const coll = new this.Record.Collection();\n await coll.fetch( options );\n return coll.toJSON();\n }\n\n async update( id, json, options ){\n json.id = id;\n const doc : any = new this.Record( json, { parse : true });\n await doc.save( options );\n return { _cas : doc._cas };\n }\n\n async create( json, options ){\n const doc : any = new this.Record( json, { parse : true });\n await doc.save( options );\n return { id : doc.id, _cas : doc._cas, _type : doc._type };\n }\n\n async read( id, options : object ){\n const doc = new this.Record({ id });\n await doc.fetch( options );\n return doc.toJSON();\n }\n\n async destroy( id : string, options : object ){\n await this.endpoint.destroy( id, options );\n return {};\n }\n}\n"],"names":["__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","value","step","next","e","rejected","result","done","then","apply","__generator","body","f","y","t","g","_","label","sent","trys","ops","verb","throw","return","Symbol","iterator","this","n","v","op","TypeError","call","pop","length","push","record","Record","source","Object","getPrototypeOf","endpoint","keys","forEach","key","_this","arguments","ProxyEndpoint","prototype","_endpoint","events","target","subscribe","unsubscribe","options","coll","Collection","fetch","_a","toJSON","id","json","doc","parse","save","_cas","_type","destroy"],"mappings":"0LAiEO,SAASA,EAAUC,EAASC,EAAYC,EAAGC,GAC9C,OAAO,IAAKD,IAAMA,EAAIE,UAAU,SAAUC,EAASC,GAC/C,SAASC,EAAUC,GAAS,IAAMC,EAAKN,EAAUO,KAAKF,IAAW,MAAOG,GAAKL,EAAOK,IACpF,SAASC,EAASJ,GAAS,IAAMC,EAAKN,EAAiB,MAAEK,IAAW,MAAOG,GAAKL,EAAOK,I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,KAAKc,SAASY,YAAaH,EAAQC,IAGjCJ,iBAAN,SAAYO,iGAER,UADMC,EAAO,IAAI5B,KAAKU,OAAOmB,YAClBC,MAAOH,WAClB,OADAI,YACOH,EAAKI,gBAGVZ,mBAAN,SAAca,EAAIC,EAAMP,iGAGpB,OAFAO,EAAKD,GAAKA,MACJE,EAAY,IAAInC,KAAKU,OAAQwB,EAAM,CAAEE,OAAQ,KACzCC,KAAMV,WAChB,OADAI,YACO,CAAEO,KAAOH,EAAIG,aAGlBlB,mBAAN,SAAcc,EAAMP,iGAEhB,UADMQ,EAAY,IAAInC,KAAKU,OAAQwB,EAAM,CAAEE,OAAQ,KACzCC,KAAMV,WAChB,OADAI,YACO,CAAEE,GAAKE,EAAIF,GAAIK,KAAOH,EAAIG,KAAMC,MAAQJ,EAAII,cAGjDnB,iBAAN,SAAYa,EAAIN,iGAEZ,UADMQ,EAAM,IAAInC,KAAKU,OAAO,CAAEuB,QACpBH,MAAOH,WACjB,OADAI,YACOI,EAAIH,gBAGTZ,oBAAN,SAAea,EAAaN,2FACxB,SAAM3B,KAAKc,SAAS0B,QAASP,EAAIN,WACjC,OADAI,YACO,kCA7DUtB,GACrB,OAAO,IAAIW,EAAeX"} \ No newline at end of file diff --git a/endpoints/proxy/lib/index.d.ts b/endpoints/proxy/lib/index.d.ts new file mode 100644 index 0000000..9da8245 --- /dev/null +++ b/endpoints/proxy/lib/index.d.ts @@ -0,0 +1,20 @@ +import { IOEndpoint, Record } from 'type-r'; +export declare function proxyIO(record: typeof Record): ProxyEndpoint; +export declare class ProxyEndpoint implements IOEndpoint { + Record: typeof Record; + readonly endpoint: IOEndpoint; + constructor(record: typeof Record); + subscribe(events: any, target: any): Promise; + unsubscribe(events: any, target: any): void; + list(options: any): Promise; + update(id: any, json: any, options: any): Promise<{ + _cas: any; + }>; + create(json: any, options: any): Promise<{ + id: any; + _cas: any; + _type: any; + }>; + read(id: any, options: object): Promise; + destroy(id: string, options: object): Promise<{}>; +} diff --git a/endpoints/proxy/lib/index.js b/endpoints/proxy/lib/index.js new file mode 100644 index 0000000..c64d416 --- /dev/null +++ b/endpoints/proxy/lib/index.js @@ -0,0 +1,111 @@ +import * as tslib_1 from "tslib"; +export function proxyIO(record) { + return new ProxyEndpoint(record); +} +var ProxyEndpoint = (function () { + function ProxyEndpoint(record) { + var _this = this; + this.Record = record; + var source = Object.getPrototypeOf(this.endpoint); + Object.keys(source).forEach(function (key) { + if (!_this[key] && typeof source[key] === 'function') { + _this[key] = function () { + return source[key].apply(this.endpoint, arguments); + }; + } + }); + } + Object.defineProperty(ProxyEndpoint.prototype, "endpoint", { + get: function () { + return this.Record.prototype._endpoint; + }, + enumerable: true, + configurable: true + }); + ProxyEndpoint.prototype.subscribe = function (events, target) { + return tslib_1.__awaiter(this, void 0, void 0, function () { + return tslib_1.__generator(this, function (_a) { + return [2, this.endpoint.subscribe(events, target)]; + }); + }); + }; + ProxyEndpoint.prototype.unsubscribe = function (events, target) { + this.endpoint.unsubscribe(events, target); + }; + ProxyEndpoint.prototype.list = function (options) { + return tslib_1.__awaiter(this, void 0, void 0, function () { + var coll; + return tslib_1.__generator(this, function (_a) { + switch (_a.label) { + case 0: + coll = new this.Record.Collection(); + return [4, coll.fetch(options)]; + case 1: + _a.sent(); + return [2, coll.toJSON()]; + } + }); + }); + }; + ProxyEndpoint.prototype.update = function (id, json, options) { + return tslib_1.__awaiter(this, void 0, void 0, function () { + var doc; + return tslib_1.__generator(this, function (_a) { + switch (_a.label) { + case 0: + json.id = id; + doc = new this.Record(json, { parse: true }); + return [4, doc.save(options)]; + case 1: + _a.sent(); + return [2, { _cas: doc._cas }]; + } + }); + }); + }; + ProxyEndpoint.prototype.create = function (json, options) { + return tslib_1.__awaiter(this, void 0, void 0, function () { + var doc; + return tslib_1.__generator(this, function (_a) { + switch (_a.label) { + case 0: + doc = new this.Record(json, { parse: true }); + return [4, doc.save(options)]; + case 1: + _a.sent(); + return [2, { id: doc.id, _cas: doc._cas, _type: doc._type }]; + } + }); + }); + }; + ProxyEndpoint.prototype.read = function (id, options) { + return tslib_1.__awaiter(this, void 0, void 0, function () { + var doc; + return tslib_1.__generator(this, function (_a) { + switch (_a.label) { + case 0: + doc = new this.Record({ id: id }); + return [4, doc.fetch(options)]; + case 1: + _a.sent(); + return [2, doc.toJSON()]; + } + }); + }); + }; + ProxyEndpoint.prototype.destroy = function (id, options) { + return tslib_1.__awaiter(this, void 0, void 0, function () { + return tslib_1.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4, this.endpoint.destroy(id, options)]; + case 1: + _a.sent(); + return [2, {}]; + } + }); + }); + }; + return ProxyEndpoint; +}()); +export { ProxyEndpoint }; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/endpoints/proxy/lib/index.js.map b/endpoints/proxy/lib/index.js.map new file mode 100644 index 0000000..8e8919f --- /dev/null +++ b/endpoints/proxy/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAEA,MAAM,UAAU,OAAO,CAAE,MAAsB;IAC3C,OAAO,IAAI,aAAa,CAAE,MAAM,CAAE,CAAC;AACvC,CAAC;AAED;IAOI,uBAAa,MAAsB;QAAnC,iBAaC;QAZG,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QAGrB,IAAM,MAAM,GAAG,MAAM,CAAC,cAAc,CAAE,IAAI,CAAC,QAAQ,CAAE,CAAC;QAEtD,MAAM,CAAC,IAAI,CAAE,MAAM,CAAE,CAAC,OAAO,CAAE,UAAA,GAAG;YAC9B,IAAI,CAAC,KAAI,CAAE,GAAG,CAAE,IAAI,OAAO,MAAM,CAAE,GAAG,CAAE,KAAK,UAAU,EAAE;gBACrD,KAAI,CAAE,GAAG,CAAE,GAAG;oBACV,OAAO,MAAM,CAAE,GAAG,CAAE,CAAC,KAAK,CAAE,IAAI,CAAC,QAAQ,EAAE,SAAS,CAAE,CAAC;gBAC3D,CAAC,CAAA;aACJ;QACL,CAAC,C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BAC1B,WAAO,EAAE,EAAE,EAAG,GAAG,CAAC,EAAE,EAAE,IAAI,EAAG,GAAG,CAAC,IAAI,EAAE,KAAK,EAAG,GAAG,CAAC,KAAK,EAAE,EAAC;;;;KAC9D;IAEK,4BAAI,GAAV,UAAY,EAAE,EAAE,OAAgB;;;;;;wBACtB,GAAG,GAAG,IAAI,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,IAAA,EAAE,CAAC,CAAC;wBACpC,WAAM,GAAG,CAAC,KAAK,CAAE,OAAO,CAAE,EAAA;;wBAA1B,SAA0B,CAAC;wBAC3B,WAAO,GAAG,CAAC,MAAM,EAAE,EAAC;;;;KACvB;IAEK,+BAAO,GAAb,UAAe,EAAW,EAAE,OAAgB;;;;4BACxC,WAAM,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAE,EAAE,EAAE,OAAO,CAAE,EAAA;;wBAA1C,SAA0C,CAAC;wBAC3C,WAAO,EAAE,EAAC;;;;KACb;IACL,oBAAC;AAAD,CAAC,AA3DD,IA2DC"} \ No newline at end of file diff --git a/endpoints/proxy/package.json b/endpoints/proxy/package.json new file mode 100644 index 0000000..dd09c6c --- /dev/null +++ b/endpoints/proxy/package.json @@ -0,0 +1,13 @@ +{ + "name": "proxyIO", + "main": "./dist/index.js", + "jsnext:main": "./lib/index.js", + "module": "./lib/index.js", + "types": "./lib/index.d.ts", + "scripts": { + "build":"../../node_modules/.bin/tsc && ../../node_modules/.bin/rollup --config" + }, + "author": "Vlad Balin", + "license": "MIT" +} + \ No newline at end of file diff --git a/endpoints/proxy/rollup.config.js b/endpoints/proxy/rollup.config.js new file mode 100644 index 0000000..79c1e75 --- /dev/null +++ b/endpoints/proxy/rollup.config.js @@ -0,0 +1,23 @@ +import resolve from 'rollup-plugin-node-resolve'; +import { uglify } from 'rollup-plugin-uglify'; +import sourcemaps from 'rollup-plugin-sourcemaps'; + +export default { + input : 'lib/index.js', + external : "type-r", + + output : { + file : 'dist/index.js', + format : 'umd', + name : 'proxyIO', + sourcemap: true, + globals : { + "type-r":"Nested" + } + }, + plugins: [ + resolve(), //for support of `import X from "directory"` rather than verbose `import X from "directory/index"` + sourcemaps(), + uglify() + ] +}; \ No newline at end of file diff --git a/endpoints/proxy/src/index.ts b/endpoints/proxy/src/index.ts new file mode 100644 index 0000000..a748997 --- /dev/null +++ b/endpoints/proxy/src/index.ts @@ -0,0 +1,66 @@ +import { IOEndpoint, IOOptions, IOPromise, createIOPromise, Record } from 'type-r' + +export function proxyIO( record : typeof Record ){ + return new ProxyEndpoint( record ); +} + +export class ProxyEndpoint implements IOEndpoint { + Record : typeof Record + + get endpoint(){ + return this.Record.prototype._endpoint; + } + + constructor( record : typeof Record ){ + this.Record = record; + + // Create proxy methods... + const source = Object.getPrototypeOf( this.endpoint ); + + Object.keys( source ).forEach( key => { + if( !this[ key ] && typeof source[ key ] === 'function' ){ + this[ key ] = function(){ + return source[ key ].apply( this.endpoint, arguments ); + } + } + }); + } + + async subscribe( events, target ){ + return this.endpoint.subscribe( events, target ); + } + + unsubscribe( events, target ){ + this.endpoint.unsubscribe( events, target ); + } + + async list( options ){ + const coll = new this.Record.Collection(); + await coll.fetch( options ); + return coll.toJSON(); + } + + async update( id, json, options ){ + json.id = id; + const doc : any = new this.Record( json, { parse : true }); + await doc.save( options ); + return { _cas : doc._cas }; + } + + async create( json, options ){ + const doc : any = new this.Record( json, { parse : true }); + await doc.save( options ); + return { id : doc.id, _cas : doc._cas, _type : doc._type }; + } + + async read( id, options : object ){ + const doc = new this.Record({ id }); + await doc.fetch( options ); + return doc.toJSON(); + } + + async destroy( id : string, options : object ){ + await this.endpoint.destroy( id, options ); + return {}; + } +} diff --git a/endpoints/proxy/tsconfig.json b/endpoints/proxy/tsconfig.json new file mode 100644 index 0000000..671840d --- /dev/null +++ b/endpoints/proxy/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "es5", + "module":"es6", + "declaration": true, + "importHelpers": true, + "moduleResolution": "node", + "sourceMap": true, + "outDir": "./lib", + "noImplicitAny": false, + "removeComments":true, + "experimentalDecorators": true, + "baseUrl": ".", + "paths" : { + "type-r":[ "../../lib" ] + } + }, + "files":[ + "./src/index.ts" + ] + } \ No newline at end of file diff --git a/endpoints/restful/dist/index.js b/endpoints/restful/dist/index.js new file mode 100644 index 0000000..0cb26e1 --- /dev/null +++ b/endpoints/restful/dist/index.js @@ -0,0 +1,2 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.restfulIO={})}(this,function(t){"use strict";var c=function(){return(c=Object.assign||function(t){for(var e,r=1,n=arguments.length;r= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\r\n if (m) return m.call(o);\r\n return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n","import { IOEndpoint, IOOptions, IOPromise, createIOPromise } from 'type-r'\n\nexport function create( url : string, fetchOptions? : Partial ){\n return new RestfulEndpoint( url, fetchOptions );\n}\n\nexport { create as restfulIO }\n\nexport interface RestfulIOOptions extends IOOptions {\n params? : object,\n options? : RequestInit\n}\n\nexport type RestfulFetchOptions = /* subset of RequestInit */{\n cache?: RequestCache;\n credentials?: RequestCredentials;\n mode?: RequestMode;\n redirect?: RequestRedirect;\n referrerPolicy?: ReferrerPolicy;\n}\n\nexport class RestfulEndpoint implements IOEndpoint {\n\n constructor( public url : string, public fetchOptions? : Partial ) {\n }\n\n public static defaultFetchOptions : RestfulFetchOptions = {\n cache: \"no-cache\",\n credentials: \"same-origin\",\n mode: \"cors\",\n redirect: \"error\",\n }\n\n create( json, options : RestfulIOOptions, record ) {\n return this.request( 'POST', this.collectionUrl( record, options ), options, json );\n }\n\n update( id, json, options : RestfulIOOptions, record ) {\n return this.request( 'PUT', this.objectUrl( record, id, options ), options, json );\n }\n\n read( id, options : IOOptions, record ){\n return this.request( 'GET', this.objectUrl( record, id, options ), options );\n }\n\n destroy( id, options : RestfulIOOptions, record ){\n return this.request( 'DELETE', this.objectUrl( record, id, options ), options );\n }\n\n list( options : RestfulIOOptions, collection ) {\n return this.request( 'GET', this.collectionUrl( collection, options ), options );\n }\n\n subscribe( events ) : any {}\n unsubscribe( events ) : any {}\n\n\n protected isRelativeUrl( url ) {\n return url.indexOf( './' ) === 0;\n }\n\n protected removeTrailingSlash( url : string ) {\n const endsWithSlash = url.charAt( url.length - 1 ) === '/';\n return endsWithSlash ? url.substr( 0, url.length - 1 ) : url;\n }\n\n protected getRootUrl( recordOrCollection ) {\n const { url } = this\n if( this.isRelativeUrl( url ) ) {\n const owner = recordOrCollection.getOwner(),\n ownerUrl = owner.getEndpoint().getUrl( owner );\n\n return this.removeTrailingSlash( ownerUrl ) + '/' + url.substr( 2 )\n } else {\n return url;\n }\n }\n\n protected getUrl( record ) {\n const url = this.getRootUrl( record );\n return record.isNew()\n ? url\n : this.removeTrailingSlash( url ) + '/' + record.id\n }\n\n protected objectUrl( record, id, options ){\n return appendParams( this.getUrl( record ), options.params );\n }\n\n protected collectionUrl( collection, options ){\n return appendParams( this.getRootUrl( collection ), options.params );\n }\n\n protected buildRequestOptions( method : string, options? : RequestInit, body? ) : RequestInit {\n const mergedOptions : RequestInit = Object.assign( {},\n RestfulEndpoint.defaultFetchOptions,\n this.fetchOptions,\n options\n );\n\n const {headers, ...rest} = mergedOptions,\n resultOptions : RequestInit = {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...headers\n },\n ...rest\n };\n\n if( body ) {\n resultOptions.body = JSON.stringify( body );\n }\n return resultOptions;\n }\n\n protected request( method : string, url : string, {options} : RestfulIOOptions, body? ) : Promise {\n\n return fetch( url, this.buildRequestOptions( method, options, body ) )\n .then( response => {\n if( response.ok ) {\n return response.json()\n } else {\n throw new Error( response.statusText )\n }\n } );\n }\n}\n\nfunction appendParams( url, params? ) {\n var esc = encodeURIComponent;\n return params\n ? url + '?' + Object.keys( params )\n .map( k => esc( k ) + '=' + esc( params[ k ] ) )\n .join( '&' )\n : url;\n}\n\n\n"],"names":["__assign","Object","assign","t","s","i","n","arguments","length","p","prototype","hasOwnProperty","call","apply","this","create","url","fetchOptions","RestfulEndpoint","json","options","record","request","collectionUrl","id","objectUrl","collection","events","indexOf","charAt","substr","recordOrCollection","isRelativeUrl","owner","getOwner","ownerUrl","getEndpoint","getUrl","removeTrailingSlash","getRootUrl","isNew","appendParams","params","method","body","mergedOptions","defaultFetchOptions","headers","rest","e","getOwnPropertySymbols","resultOptions","Content-Type","JSON","stringify","_a","fetch","buildRequestOptions","then","response","ok","Error","statusText","cache","credentials","mode","redirect","esc","encodeURIComponent","keys","map","k","join"],"mappings":"4LA6BO,IAAIA,EAAW,WAQlB,OAPAA,EAAWC,OAAOC,QAAU,SAAkBC,GAC1C,IAAK,IAAIC,EAAGC,EAAI,EAAGC,EAAIC,UAAUC,OAAQH,EAAIC,EAAGD,IAE5C,IAAK,IAAII,KADTL,EAAIG,UAAUF,GACOJ,OAAOS,UAAUC,eAAeC,KAAKR,EAAGK,KAAIN,EAAEM,GAAKL,EAAEK,IAE9E,OAAON,IAEKU,MAAMC,KAAMP,qBCnChBQ,EAAQC,EAAcC,GAClC,OAAO,IAAIC,EAAiBF,EAAKC,oBAoBjC,WAAoBD,EAAqBC,GAArBH,SAAAE,EAAqBF,kBAAAG,EAwG7C,OA9FIC,mBAAA,SAAQC,EAAMC,EAA4BC,GACtC,OAAOP,KAAKQ,QAAS,OAAQR,KAAKS,cAAeF,EAAQD,GAAWA,EAASD,IAGjFD,mBAAA,SAAQM,EAAIL,EAAMC,EAA4BC,GAC1C,OAAOP,KAAKQ,QAAS,MAAOR,KAAKW,UAAWJ,EAAQG,EAAIJ,GAAWA,EAASD,IAGhFD,iBAAA,SAAMM,EAAIJ,EAAqBC,GAC3B,OAAOP,KAAKQ,QAAS,MAAOR,KAAKW,UAAWJ,EAAQG,EAAIJ,GAAWA,IAGvEF,oBAAA,SAASM,EAAIJ,EAA4BC,GACrC,OAAOP,KAAKQ,QAAS,SAAUR,KAAKW,UAAWJ,EAAQG,EAAIJ,GAAWA,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7C,EAAI,EAAb,IAAgBI,EAAIR,OAAOiD,sBAAsB9C,GAAIC,EAAII,EAAED,OAAQH,IAAS4C,EAAErB,QAAQnB,EAAEJ,IAAM,IAC1FF,EAAEM,EAAEJ,IAAMD,EAAEK,EAAEJ,KACtB,OAAOF,kBCsDGgD,KACIR,SACAI,WACIK,eAAgB,oBACbL,IAEJC,GAMb,OAHIJ,IACAO,EAAcP,KAAOS,KAAKC,UAAWV,IAElCO,GAGDjC,oBAAV,SAAmByB,EAAiB3B,EAAcuC,EAA8BX,OAA7BxB,YAE/C,OAAOoC,MAAOxC,EAAKF,KAAK2C,oBAAqBd,EAAQvB,EAASwB,IACzDc,KAAM,SAAAC,GACH,GAAIA,EAASC,GACT,OAAOD,EAASxC,OAEhB,MAAM,IAAI0C,MAAOF,EAASG,eAjG5B5C,sBAA4C,CACtD6C,MAAO,WACPC,YAAa,cACbC,KAAM,OACNC,SAAU,cAmGlB,SAASzB,EAAczB,EAAK0B,GACxB,IAAIyB,EAAMC,mBACV,OAAO1B,EACD1B,EAAM,IAAMf,OAAOoE,KAAM3B,GACR4B,IAAK,SAAAC,GAAK,OAAAJ,EAAKI,GAAM,IAAMJ,EAAKzB,EAAQ6B,MACxCC,KAAM,KACvBxD"} \ No newline at end of file diff --git a/endpoints/restful/lib/index.d.ts b/endpoints/restful/lib/index.d.ts new file mode 100644 index 0000000..efc1284 --- /dev/null +++ b/endpoints/restful/lib/index.d.ts @@ -0,0 +1,35 @@ +import { IOEndpoint, IOOptions } from 'type-r'; +export declare function create(url: string, fetchOptions?: Partial): RestfulEndpoint; +export { create as restfulIO }; +export interface RestfulIOOptions extends IOOptions { + params?: object; + options?: RequestInit; +} +export declare type RestfulFetchOptions = { + cache?: RequestCache; + credentials?: RequestCredentials; + mode?: RequestMode; + redirect?: RequestRedirect; + referrerPolicy?: ReferrerPolicy; +}; +export declare class RestfulEndpoint implements IOEndpoint { + url: string; + fetchOptions?: Partial; + constructor(url: string, fetchOptions?: Partial); + static defaultFetchOptions: RestfulFetchOptions; + create(json: any, options: RestfulIOOptions, record: any): Promise; + update(id: any, json: any, options: RestfulIOOptions, record: any): Promise; + read(id: any, options: IOOptions, record: any): Promise; + destroy(id: any, options: RestfulIOOptions, record: any): Promise; + list(options: RestfulIOOptions, collection: any): Promise; + subscribe(events: any): any; + unsubscribe(events: any): any; + protected isRelativeUrl(url: any): boolean; + protected removeTrailingSlash(url: string): string; + protected getRootUrl(recordOrCollection: any): string; + protected getUrl(record: any): string; + protected objectUrl(record: any, id: any, options: any): any; + protected collectionUrl(collection: any, options: any): any; + protected buildRequestOptions(method: string, options?: RequestInit, body?: any): RequestInit; + protected request(method: string, url: string, { options }: RestfulIOOptions, body?: any): Promise; +} diff --git a/endpoints/restful/lib/index.js b/endpoints/restful/lib/index.js new file mode 100644 index 0000000..2326cba --- /dev/null +++ b/endpoints/restful/lib/index.js @@ -0,0 +1,94 @@ +import * as tslib_1 from "tslib"; +export function create(url, fetchOptions) { + return new RestfulEndpoint(url, fetchOptions); +} +export { create as restfulIO }; +var RestfulEndpoint = (function () { + function RestfulEndpoint(url, fetchOptions) { + this.url = url; + this.fetchOptions = fetchOptions; + } + RestfulEndpoint.prototype.create = function (json, options, record) { + return this.request('POST', this.collectionUrl(record, options), options, json); + }; + RestfulEndpoint.prototype.update = function (id, json, options, record) { + return this.request('PUT', this.objectUrl(record, id, options), options, json); + }; + RestfulEndpoint.prototype.read = function (id, options, record) { + return this.request('GET', this.objectUrl(record, id, options), options); + }; + RestfulEndpoint.prototype.destroy = function (id, options, record) { + return this.request('DELETE', this.objectUrl(record, id, options), options); + }; + RestfulEndpoint.prototype.list = function (options, collection) { + return this.request('GET', this.collectionUrl(collection, options), options); + }; + RestfulEndpoint.prototype.subscribe = function (events) { }; + RestfulEndpoint.prototype.unsubscribe = function (events) { }; + RestfulEndpoint.prototype.isRelativeUrl = function (url) { + return url.indexOf('./') === 0; + }; + RestfulEndpoint.prototype.removeTrailingSlash = function (url) { + var endsWithSlash = url.charAt(url.length - 1) === '/'; + return endsWithSlash ? url.substr(0, url.length - 1) : url; + }; + RestfulEndpoint.prototype.getRootUrl = function (recordOrCollection) { + var url = this.url; + if (this.isRelativeUrl(url)) { + var owner = recordOrCollection.getOwner(), ownerUrl = owner.getEndpoint().getUrl(owner); + return this.removeTrailingSlash(ownerUrl) + '/' + url.substr(2); + } + else { + return url; + } + }; + RestfulEndpoint.prototype.getUrl = function (record) { + var url = this.getRootUrl(record); + return record.isNew() + ? url + : this.removeTrailingSlash(url) + '/' + record.id; + }; + RestfulEndpoint.prototype.objectUrl = function (record, id, options) { + return appendParams(this.getUrl(record), options.params); + }; + RestfulEndpoint.prototype.collectionUrl = function (collection, options) { + return appendParams(this.getRootUrl(collection), options.params); + }; + RestfulEndpoint.prototype.buildRequestOptions = function (method, options, body) { + var mergedOptions = Object.assign({}, RestfulEndpoint.defaultFetchOptions, this.fetchOptions, options); + var headers = mergedOptions.headers, rest = tslib_1.__rest(mergedOptions, ["headers"]), resultOptions = tslib_1.__assign({ method: method, headers: tslib_1.__assign({ 'Content-Type': 'application/json' }, headers) }, rest); + if (body) { + resultOptions.body = JSON.stringify(body); + } + return resultOptions; + }; + RestfulEndpoint.prototype.request = function (method, url, _a, body) { + var options = _a.options; + return fetch(url, this.buildRequestOptions(method, options, body)) + .then(function (response) { + if (response.ok) { + return response.json(); + } + else { + throw new Error(response.statusText); + } + }); + }; + RestfulEndpoint.defaultFetchOptions = { + cache: "no-cache", + credentials: "same-origin", + mode: "cors", + redirect: "error", + }; + return RestfulEndpoint; +}()); +export { RestfulEndpoint }; +function appendParams(url, params) { + var esc = encodeURIComponent; + return params + ? url + '?' + Object.keys(params) + .map(function (k) { return esc(k) + '=' + esc(params[k]); }) + .join('&') + : url; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/endpoints/restful/lib/index.js.map b/endpoints/restful/lib/index.js.map new file mode 100644 index 0000000..5b7705d --- /dev/null +++ b/endpoints/restful/lib/index.js.map @@ -0,0 +1 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AE,CAAC;IACZ,CAAC;IApGa,mCAAmB,GAAyB;QACtD,KAAK,EAAE,UAAU;QACjB,WAAW,EAAE,aAAa;QAC1B,IAAI,EAAE,MAAM;QACZ,QAAQ,EAAE,OAAO;KACpB,CAAA;IAgGL,sBAAC;CAAA,AA1GD,IA0GC;SA1GY,eAAe;AA4G5B,SAAS,YAAY,CAAE,GAAG,EAAE,MAAO;IAC/B,IAAI,GAAG,GAAG,kBAAkB,CAAC;IAC7B,OAAO,MAAM;QACT,CAAC,CAAC,GAAG,GAAG,GAAG,GAAG,MAAM,CAAC,IAAI,CAAE,MAAM,CAAE;aAChB,GAAG,CAAE,UAAA,CAAC,IAAI,OAAA,GAAG,CAAE,CAAC,CAAE,GAAG,GAAG,GAAG,GAAG,CAAE,MAAM,CAAE,CAAC,CAAE,CAAE,EAAnC,CAAmC,CAAE;aAC/C,IAAI,CAAE,GAAG,CAAE;QAC9B,CAAC,CAAC,GAAG,CAAC;AACd,CAAC"} \ No newline at end of file diff --git a/endpoints/restful/package.json b/endpoints/restful/package.json new file mode 100644 index 0000000..39ed8d4 --- /dev/null +++ b/endpoints/restful/package.json @@ -0,0 +1,13 @@ +{ + "name": "restfulIO", + "main": "./dist/index.js", + "jsnext:main": "./lib/index.js", + "module": "./lib/index.js", + "types": "./lib/index.d.ts", + "scripts": { + "build":"../../node_modules/.bin/tsc && ../../node_modules/.bin/rollup --config" + }, + "author": "Ivan Terpugov", + "license": "MIT" +} + \ No newline at end of file diff --git a/endpoints/restful/rollup.config.js b/endpoints/restful/rollup.config.js new file mode 100644 index 0000000..5789d78 --- /dev/null +++ b/endpoints/restful/rollup.config.js @@ -0,0 +1,23 @@ +import resolve from 'rollup-plugin-node-resolve'; +import { uglify } from 'rollup-plugin-uglify'; +import sourcemaps from 'rollup-plugin-sourcemaps'; + +export default { + input : 'lib/index.js', + external : "type-r", + + output : { + file : 'dist/index.js', + format : 'umd', + name : 'restfulIO', + sourcemap: true, + globals : { + "type-r":"Nested" + } + }, + plugins: [ + resolve(), //for support of `import X from "directory"` rather than verbose `import X from "directory/index"` + sourcemaps(), + uglify() + ] +}; \ No newline at end of file diff --git a/endpoints/restful/src/index.ts b/endpoints/restful/src/index.ts new file mode 100644 index 0000000..653513a --- /dev/null +++ b/endpoints/restful/src/index.ts @@ -0,0 +1,139 @@ +import { IOEndpoint, IOOptions, IOPromise, createIOPromise } from 'type-r' + +export function create( url : string, fetchOptions? : Partial ){ + return new RestfulEndpoint( url, fetchOptions ); +} + +export { create as restfulIO } + +export interface RestfulIOOptions extends IOOptions { + params? : object, + options? : RequestInit +} + +export type RestfulFetchOptions = /* subset of RequestInit */{ + cache?: RequestCache; + credentials?: RequestCredentials; + mode?: RequestMode; + redirect?: RequestRedirect; + referrerPolicy?: ReferrerPolicy; +} + +export class RestfulEndpoint implements IOEndpoint { + + constructor( public url : string, public fetchOptions? : Partial ) { + } + + public static defaultFetchOptions : RestfulFetchOptions = { + cache: "no-cache", + credentials: "same-origin", + mode: "cors", + redirect: "error", + } + + create( json, options : RestfulIOOptions, record ) { + return this.request( 'POST', this.collectionUrl( record, options ), options, json ); + } + + update( id, json, options : RestfulIOOptions, record ) { + return this.request( 'PUT', this.objectUrl( record, id, options ), options, json ); + } + + read( id, options : IOOptions, record ){ + return this.request( 'GET', this.objectUrl( record, id, options ), options ); + } + + destroy( id, options : RestfulIOOptions, record ){ + return this.request( 'DELETE', this.objectUrl( record, id, options ), options ); + } + + list( options : RestfulIOOptions, collection ) { + return this.request( 'GET', this.collectionUrl( collection, options ), options ); + } + + subscribe( events ) : any {} + unsubscribe( events ) : any {} + + + protected isRelativeUrl( url ) { + return url.indexOf( './' ) === 0; + } + + protected removeTrailingSlash( url : string ) { + const endsWithSlash = url.charAt( url.length - 1 ) === '/'; + return endsWithSlash ? url.substr( 0, url.length - 1 ) : url; + } + + protected getRootUrl( recordOrCollection ) { + const { url } = this + if( this.isRelativeUrl( url ) ) { + const owner = recordOrCollection.getOwner(), + ownerUrl = owner.getEndpoint().getUrl( owner ); + + return this.removeTrailingSlash( ownerUrl ) + '/' + url.substr( 2 ) + } else { + return url; + } + } + + protected getUrl( record ) { + const url = this.getRootUrl( record ); + return record.isNew() + ? url + : this.removeTrailingSlash( url ) + '/' + record.id + } + + protected objectUrl( record, id, options ){ + return appendParams( this.getUrl( record ), options.params ); + } + + protected collectionUrl( collection, options ){ + return appendParams( this.getRootUrl( collection ), options.params ); + } + + protected buildRequestOptions( method : string, options? : RequestInit, body? ) : RequestInit { + const mergedOptions : RequestInit = Object.assign( {}, + RestfulEndpoint.defaultFetchOptions, + this.fetchOptions, + options + ); + + const {headers, ...rest} = mergedOptions, + resultOptions : RequestInit = { + method, + headers: { + 'Content-Type': 'application/json', + ...headers + }, + ...rest + }; + + if( body ) { + resultOptions.body = JSON.stringify( body ); + } + return resultOptions; + } + + protected request( method : string, url : string, {options} : RestfulIOOptions, body? ) : Promise { + + return fetch( url, this.buildRequestOptions( method, options, body ) ) + .then( response => { + if( response.ok ) { + return response.json() + } else { + throw new Error( response.statusText ) + } + } ); + } +} + +function appendParams( url, params? ) { + var esc = encodeURIComponent; + return params + ? url + '?' + Object.keys( params ) + .map( k => esc( k ) + '=' + esc( params[ k ] ) ) + .join( '&' ) + : url; +} + + diff --git a/endpoints/restful/tsconfig.json b/endpoints/restful/tsconfig.json new file mode 100644 index 0000000..671840d --- /dev/null +++ b/endpoints/restful/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "es5", + "module":"es6", + "declaration": true, + "importHelpers": true, + "moduleResolution": "node", + "sourceMap": true, + "outDir": "./lib", + "noImplicitAny": false, + "removeComments":true, + "experimentalDecorators": true, + "baseUrl": ".", + "paths" : { + "type-r":[ "../../lib" ] + } + }, + "files":[ + "./src/index.ts" + ] + } \ No newline at end of file diff --git a/lib/backbone.d.ts b/lib/backbone.d.ts new file mode 100644 index 0000000..418cf8c --- /dev/null +++ b/lib/backbone.d.ts @@ -0,0 +1,22 @@ +/// +declare global { + interface Window { + Backbone: any; + } + function attachEvent(a: any, b: any): any; + function detachEvent(a: any, b: any): any; +} +declare const exported: { + $: JQueryStatic; + history: any; + VERSION: string; + View: typeof View; + History: typeof History; + Router: typeof Router; + noConflict: typeof noConflict; +}; +export default exported; +declare function noConflict(): any; +export declare function View(options: any): void; +export declare function Router(options: any): void; +export declare function History(): void; diff --git a/lib/backbone.js b/lib/backbone.js new file mode 100644 index 0000000..a9a2d5b --- /dev/null +++ b/lib/backbone.js @@ -0,0 +1,350 @@ +import * as _ from 'underscore'; +import * as jQuery from 'jquery'; +var previousBackbone = window.Backbone; +var slice = Array.prototype.slice; +var exported = { + $: jQuery, + history: null, + VERSION: '1.2.3', + View: View, History: History, Router: Router, noConflict: noConflict +}; +export default exported; +function noConflict() { + window.Backbone = previousBackbone; + return this; +} +; +export function View(options) { + this.cid = _.uniqueId('view'); + options || (options = {}); + _.extend(this, _.pick(options, viewOptions)); + this._ensureElement(); + this.initialize.apply(this, arguments); + this.delegateEvents(); +} +; +var delegateEventSplitter = /^(\S+)\s*(.*)$/; +var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; +_.extend(View.prototype, { + tagName: 'div', + $: function (selector) { + return this.$el.find(selector); + }, + initialize: function () { }, + render: function () { + return this; + }, + remove: function () { + this.$el.remove(); + this.stopListening(); + return this; + }, + setElement: function (element, delegate) { + if (this.$el) + this.undelegateEvents(); + this.$el = element instanceof exported.$ ? element : exported.$(element); + this.el = this.$el[0]; + if (delegate !== false) + this.delegateEvents(); + return this; + }, + delegateEvents: function (events) { + if (!(events || (events = _.result(this, 'events')))) + return this; + this.undelegateEvents(); + for (var key in events) { + var method = events[key]; + if (!_.isFunction(method)) + method = this[events[key]]; + if (!method) + continue; + var match = key.match(delegateEventSplitter); + var eventName = match[1], selector = match[2]; + method = _.bind(method, this); + eventName += '.delegateEvents' + this.cid; + if (selector === '') { + this.$el.on(eventName, method); + } + else { + this.$el.on(eventName, selector, method); + } + } + return this; + }, + undelegateEvents: function () { + this.$el.off('.delegateEvents' + this.cid); + return this; + }, + _ensureElement: function () { + if (!this.el) { + var attrs = _.extend({}, _.result(this, 'attributes')); + if (this.id) + attrs.id = _.result(this, 'id'); + if (this.className) + attrs['class'] = _.result(this, 'className'); + var $el = exported.$('<' + _.result(this, 'tagName') + '>').attr(attrs); + this.setElement($el, false); + } + else { + this.setElement(_.result(this, 'el'), false); + } + } +}); +export function Router(options) { + options || (options = {}); + if (options.routes) + this.routes = options.routes; + this._bindRoutes(); + this.initialize.apply(this, arguments); +} +var optionalParam = /\((.*?)\)/g; +var namedParam = /(\(\?)?:\w+/g; +var splatParam = /\*\w+/g; +var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; +_.extend(Router.prototype, { + initialize: function () { }, + route: function (route, name, callback) { + if (!_.isRegExp(route)) + route = this._routeToRegExp(route); + if (_.isFunction(name)) { + callback = name; + name = ''; + } + if (!callback) + callback = this[name]; + var router = this; + exported.history.route(route, function (fragment) { + var args = router._extractParameters(route, fragment); + if (router.execute(callback, args, name) !== false) { + router.trigger.apply(router, ['route:' + name].concat(args)); + router.trigger('route', name, args); + exported.history.trigger('route', router, name, args); + } + }); + return this; + }, + execute: function (callback, args, name) { + if (callback) + callback.apply(this, args); + }, + navigate: function (fragment, options) { + exported.history.navigate(fragment, options); + return this; + }, + _bindRoutes: function () { + if (!this.routes) + return; + this.routes = _.result(this, 'routes'); + var route, routes = _.keys(this.routes); + while ((route = routes.pop()) != null) { + this.route(route, this.routes[route]); + } + }, + _routeToRegExp: function (route) { + route = route.replace(escapeRegExp, '\\$&') + .replace(optionalParam, '(?:$1)?') + .replace(namedParam, function (match, optional) { + return optional ? match : '([^/?]+)'; + }) + .replace(splatParam, '([^?]*?)'); + return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$'); + }, + _extractParameters: function (route, fragment) { + var params = route.exec(fragment).slice(1); + return _.map(params, function (param, i) { + if (i === params.length - 1) + return param || null; + return param ? decodeURIComponent(param) : null; + }); + } +}); +export function History() { + this.handlers = []; + this.checkUrl = _.bind(this.checkUrl, this); + if (typeof window !== 'undefined') { + this.location = window.location; + this.history = window.history; + } +} +; +var routeStripper = /^[#\/]|\s+$/g; +var rootStripper = /^\/+|\/+$/g; +var pathStripper = /#.*$/; +History.started = false; +_.extend(History.prototype, { + interval: 50, + atRoot: function () { + var path = this.location.pathname.replace(/[^\/]$/, '$&/'); + return path === this.root && !this.getSearch(); + }, + matchRoot: function () { + var path = this.decodeFragment(this.location.pathname); + var root = path.slice(0, this.root.length - 1) + '/'; + return root === this.root; + }, + decodeFragment: function (fragment) { + return decodeURI(fragment.replace(/%25/g, '%2525')); + }, + getSearch: function () { + var match = this.location.href.replace(/#.*/, '').match(/\?.+/); + return match ? match[0] : ''; + }, + getHash: function (window) { + var match = (window || this).location.href.match(/#(.*)$/); + return match ? match[1] : ''; + }, + getPath: function () { + var path = this.decodeFragment(this.location.pathname + this.getSearch()).slice(this.root.length - 1); + return path.charAt(0) === '/' ? path.slice(1) : path; + }, + getFragment: function (fragment) { + if (fragment == null) { + if (this._usePushState || !this._wantsHashChange) { + fragment = this.getPath(); + } + else { + fragment = this.getHash(); + } + } + return fragment.replace(routeStripper, ''); + }, + start: function (options) { + if (History.started) + throw new Error('Backbone.history has already been started'); + History.started = true; + this.options = _.extend({ root: '/' }, this.options, options); + this.root = this.options.root; + this._wantsHashChange = this.options.hashChange !== false; + this._hasHashChange = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7); + this._useHashChange = this._wantsHashChange && this._hasHashChange; + this._wantsPushState = !!this.options.pushState; + this._hasPushState = !!(this.history && this.history.pushState); + this._usePushState = this._wantsPushState && this._hasPushState; + this.fragment = this.getFragment(); + this.root = ('/' + this.root + '/').replace(rootStripper, '/'); + if (this._wantsHashChange && this._wantsPushState) { + if (!this._hasPushState && !this.atRoot()) { + var root = this.root.slice(0, -1) || '/'; + this.location.replace(root + '#' + this.getPath()); + return true; + } + else if (this._hasPushState && this.atRoot()) { + this.navigate(this.getHash(), { replace: true }); + } + } + if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) { + this.iframe = document.createElement('iframe'); + this.iframe.src = 'javascript:0'; + this.iframe.style.display = 'none'; + this.iframe.tabIndex = -1; + var body = document.body; + var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow; + iWindow.document.open(); + iWindow.document.close(); + iWindow.location.hash = '#' + this.fragment; + } + var addEventListener = window.addEventListener || function (eventName, listener) { + return attachEvent('on' + eventName, listener); + }; + if (this._usePushState) { + addEventListener('popstate', this.checkUrl, false); + } + else if (this._useHashChange && !this.iframe) { + addEventListener('hashchange', this.checkUrl, false); + } + else if (this._wantsHashChange) { + this._checkUrlInterval = setInterval(this.checkUrl, this.interval); + } + if (!this.options.silent) + return this.loadUrl(); + }, + stop: function () { + var removeEventListener = window.removeEventListener || function (eventName, listener) { + return detachEvent('on' + eventName, listener); + }; + if (this._usePushState) { + removeEventListener('popstate', this.checkUrl, false); + } + else if (this._useHashChange && !this.iframe) { + removeEventListener('hashchange', this.checkUrl, false); + } + if (this.iframe) { + document.body.removeChild(this.iframe); + this.iframe = null; + } + if (this._checkUrlInterval) + clearInterval(this._checkUrlInterval); + History.started = false; + }, + route: function (route, callback) { + this.handlers.unshift({ route: route, callback: callback }); + }, + checkUrl: function (e) { + var current = this.getFragment(); + if (current === this.fragment && this.iframe) { + current = this.getHash(this.iframe.contentWindow); + } + if (current === this.fragment) + return false; + if (this.iframe) + this.navigate(current); + this.loadUrl(); + }, + loadUrl: function (fragment) { + if (!this.matchRoot()) + return false; + fragment = this.fragment = this.getFragment(fragment); + return _.some(this.handlers, function (handler) { + if (handler.route.test(fragment)) { + handler.callback(fragment); + return true; + } + }); + }, + navigate: function (fragment, options) { + if (!History.started) + return false; + if (!options || options === true) + options = { trigger: !!options }; + fragment = this.getFragment(fragment || ''); + var root = this.root; + if (fragment === '' || fragment.charAt(0) === '?') { + root = root.slice(0, -1) || '/'; + } + var url = root + fragment; + fragment = this.decodeFragment(fragment.replace(pathStripper, '')); + if (this.fragment === fragment) + return; + this.fragment = fragment; + if (this._usePushState) { + this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url); + } + else if (this._wantsHashChange) { + this._updateHash(this.location, fragment, options.replace); + if (this.iframe && (fragment !== this.getHash(this.iframe.contentWindow))) { + var iWindow = this.iframe.contentWindow; + if (!options.replace) { + iWindow.document.open(); + iWindow.document.close(); + } + this._updateHash(iWindow.location, fragment, options.replace); + } + } + else { + return this.location.assign(url); + } + if (options.trigger) + return this.loadUrl(fragment); + }, + _updateHash: function (location, fragment, replace) { + if (replace) { + var href = location.href.replace(/(javascript:|#).*$/, ''); + location.replace(href + '#' + fragment); + } + else { + location.hash = '#' + fragment; + } + } +}); +exported.history = new History; +//# sourceMappingURL=backbone.js.map \ No newline at end of file diff --git a/lib/backbone.js.map b/lib/backbone.js.map new file mode 100644 index 0000000..f7aab9c --- /dev/null +++ b/lib/backbone.js.map @@ -0,0 +1 @@ +{"version":3,"file":"backbone.js","sourceRoot":"","sources":["../src/backbone.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,CAAC,MAAM,YAAY,CAAA;AAC/B,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAA;AAehC,IAAM,gBAAgB,GAAG,MAAM,CAAC,QAAQ,CAAC;AAGzC,IAAM,KAAK,GAAG,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC;AAIpC,IAAM,QAAQ,GAAG;IACf,CAAC,EAAG,MAAM;IACV,OAAO,EAAG,IAAI;IACd,OAAO,EAAG,OAAO;IACjB,IAAI,MAAA,EAAE,OAAO,SAAA,EAAE,MAAM,QAAA,EAAE,UAAU,YAAA;CAClC,CAAA;AAED,eAAe,QAAQ,CAAC;AAIxB,SAAS,UAAU;IACjB,MAAM,CAAC,QAAQ,GAAG,gBAAgB,CAAC;IACnC,OAAO,IAAI,CAAC;AACd,CAAC;AAAA,CAAC;AAeF,MAAM,UAAU,IAAI,CAAC,OAAO;IAC1B,IAAI,CAAC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newline at end of file diff --git a/lib/index.d.ts b/lib/index.d.ts new file mode 100644 index 0000000..9413514 --- /dev/null +++ b/lib/index.d.ts @@ -0,0 +1,11 @@ +import * as TypeR from './type-r'; +export * from './type-r'; +import Backbone from './backbone'; +import { RestCollection, RestModel } from './rest'; +import { RestStore, LazyStore } from './rest-store'; +export declare const Class: typeof TypeR.Messenger; +declare const Nested: typeof TypeR & typeof Backbone; +export default Nested; +export { Backbone, RestStore, LazyStore, RestCollection as Collection, RestModel as Model }; +export declare function defaults(x: any): typeof Nested.Record; +export * from './backbone'; diff --git a/lib/index.js b/lib/index.js new file mode 100644 index 0000000..34670b7 --- /dev/null +++ b/lib/index.js @@ -0,0 +1,40 @@ +import * as TypeR from './type-r'; +export * from './type-r'; +import Backbone from './backbone'; +import { RestCollection, RestModel } from './rest'; +import { Store as BaseStore, tools, MixinsState } from './type-r'; +import Sync from './sync'; +import { ModelMixin, CollectionMixin } from './underscore-mixin'; +import { RestStore, LazyStore } from './rest-store'; +export var Class = TypeR.Messenger; +var Nested = Object.create(TypeR, tools.defaults({ + 'sync': linkProperty(Sync, 'sync'), + 'errorPromise': linkProperty(Sync, 'errorPromise'), + 'ajax': linkProperty(Sync, 'ajax'), + 'history': linkProperty(Backbone, 'history'), + 'store': linkProperty(BaseStore, 'global'), + '$': { + get: function () { return Backbone.$; }, + set: function (value) { Backbone.$ = Sync.$ = value; } + } +}, toProps({ Backbone: Backbone, Class: Class, Model: RestModel, Collection: RestCollection, LazyStore: LazyStore, Store: RestStore, defaults: defaults }), toProps(Backbone))); +export default Nested; +export { Backbone, RestStore, LazyStore, RestCollection as Collection, RestModel as Model }; +export function defaults(x) { + return Nested.Model.defaults(x); +} +export * from './backbone'; +MixinsState.get(Nested.Mixable).merge([Nested.Events]); +Nested.Messenger.mixins.populate(Backbone.View, Backbone.Router, Backbone.History); +Nested.Record.mixins.merge([ModelMixin]); +Nested.Record.Collection.mixins.merge([CollectionMixin]); +function linkProperty(Namespace, name) { + return { + get: function () { return Namespace[name]; }, + set: function (value) { Namespace[name] = value; } + }; +} +function toProps(obj) { + return tools.transform({}, obj, function (x) { return ({ value: x }); }); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib/index.js.map b/lib/index.js.map new file mode 100644 index 0000000..8e163b2 --- /dev/null +++ b/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,KAAK,MAAM,UAAU,CAAA;AACjC,cAAc,UAAU,CAAA;AAKxB,OAAO,QAAQ,MAAM,YAAY,CAAA;AACjC,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAA;AAClD,OAAO,EAAE,KAAK,IAAI,SAAS,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAA;AACjE,OAAO,IAAI,MAAM,QAAQ,CAAA;AAEzB,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAChE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AAMnD,MAAM,CAAC,IAAM,KAAK,GAA4B,KAAK,CAAC,SAAS,CAAC;AAE9D,IAAM,MAAM,GAAoC,MAAM,CAAC,MAAM,CAAE,KAAK,EAAE,KAAK,CAAC,QAAQ,CAAC;IAC7E,MAAM,EAAW,YAAY,CAAE,IAAI,EAAE,MAAM,CAAE;IAC7C,cAAc,EAAG,YAAY,CAAE,IAAI,EAAE,cAAc,CAAE;IACrD,MAAM,EAAW,YAAY,CAAE,IAAI,EAAE,MAAM,CAAE;IAC7C,SAAS,EAAQ,YAAY,CAAE,QAAQ,EAAE,SAAS,CAAE;IACpD,OAAO,EAAU,YAAY,CAAE,SAAS,EAAE,QAAQ,CAAE;IACpD,GAAG,EAAG;QACF,GAAG,gBAAI,OAAO,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;QAC3B,GAAG,YAAE,KAAK,IAAU,QAAS,C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;AACN,CAAC;AAED,SAAS,OAAO,CAAE,GAAG;IACjB,OAAO,KAAK,CAAC,SAAS,CAAC,EAAE,EAAE,GAAG,EAAE,UAAA,CAAC,IAAI,OAAA,CAAC,EAAE,KAAK,EAAG,CAAC,EAAE,CAAC,EAAf,CAAe,CAAE,CAAC;AAC3D,CAAC"} \ No newline at end of file diff --git a/lib/rest-store.d.ts b/lib/rest-store.d.ts new file mode 100644 index 0000000..e8ddb1b --- /dev/null +++ b/lib/rest-store.d.ts @@ -0,0 +1,12 @@ +/// +import { RestModel } from './rest'; +export declare class RestStore extends RestModel { +} +export declare class LazyStore extends RestStore { + _resolved: {}; + initialize(): void; + fetch(...args: any[]): any; + fetchOnce(...args: string[]): JQueryXHR; + clear(...args: string[]): this; + static onDefine(definitions: any, BaseClass: any): void; +} diff --git a/lib/rest-store.js b/lib/rest-store.js new file mode 100644 index 0000000..8fe2e1b --- /dev/null +++ b/lib/rest-store.js @@ -0,0 +1,117 @@ +import * as tslib_1 from "tslib"; +import Backbone from './backbone'; +import * as _ from 'underscore'; +import { define, Store } from './type-r'; +import { RestModel, RestCollection } from './rest'; +var RestStore = (function (_super) { + tslib_1.__extends(RestStore, _super); + function RestStore() { + return _super !== null && _super.apply(this, arguments) || this; + } + RestStore = tslib_1.__decorate([ + define({ + getStore: Store.prototype.getStore, + get: Store.prototype.get, + }) + ], RestStore); + return RestStore; +}(RestModel)); +export { RestStore }; +var LazyStore = (function (_super) { + tslib_1.__extends(LazyStore, _super); + function LazyStore() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this._resolved = {}; + return _this; + } + LazyStore.prototype.initialize = function () { + var _this = this; + this.each(function (element, name) { + if (!element) + return; + element.store = _this; + var fetch = element.fetch; + if (fetch) { + var self_1 = _this; + element.fetch = function () { + return self_1._resolved[name] = fetch.apply(this, arguments); + }; + } + if (element instanceof RestCollection && element.length) { + _this._resolved[name] = true; + } + }); + }; + LazyStore.prototype.fetch = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var xhr = [], objsToFetch = args.length ? args : this.keys(); + for (var _a = 0, objsToFetch_1 = objsToFetch; _a < objsToFetch_1.length; _a++) { + var name_1 = objsToFetch_1[_a]; + var attr = this.attributes[name_1]; + attr && attr.fetch && xhr.push(attr.fetch()); + } + var $ = Backbone.$; + return $ && $.when && $.when.apply($, xhr); + }; + LazyStore.prototype.fetchOnce = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var xhr = [], self = this, objsToFetch = args.length ? args : this.keys(); + for (var _a = 0, objsToFetch_2 = objsToFetch; _a < objsToFetch_2.length; _a++) { + var name_2 = objsToFetch_2[_a]; + var attr = self.attributes[name_2]; + xhr.push(self._resolved[name_2] || attr && attr.fetch && attr.fetch()); + } + var $ = Backbone.$; + return $ && $.when && $.when.apply($, xhr); + }; + LazyStore.prototype.clear = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var objsToClear = args.length ? args : this.keys(); + for (var _a = 0, objsToClear_1 = objsToClear; _a < objsToClear_1.length; _a++) { + var name_3 = objsToClear_1[_a]; + var element = this.attributes[name_3]; + if (element instanceof RestCollection) { + element.reset(); + } + else if (element instanceof Store) { + element.clear(); + } + else if (element instanceof RestModel) { + element.set(element.defaults()); + } + this._resolved[name_3] = false; + } + return this; + }; + LazyStore.onDefine = function (definitions, BaseClass) { + var attributes = definitions.defaults || definitions.attributes; + _.each(attributes, function (Type, name) { + if (Type.has) { + attributes[name] = Type.has + .set(function (value) { + if (!value || !value.length) { + var resolved = this._resolved || (this._resolved = {}); + resolved[name] = false; + } + return value; + }); + } + }); + RestModel.onDefine.call(this, definitions, BaseClass); + }; + LazyStore = tslib_1.__decorate([ + define + ], LazyStore); + return LazyStore; +}(RestStore)); +export { LazyStore }; +//# sourceMappingURL=rest-store.js.map \ No newline at end of file diff --git a/lib/rest-store.js.map b/lib/rest-store.js.map new file mode 100644 index 0000000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K,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE;wBACzB,IAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,IAAI,CAAE,IAAI,CAAC,SAAS,GAAG,EAAE,CAAE,CAAC;wBAC3D,QAAQ,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;qBAC1B;oBAED,OAAO,KAAK,CAAC;gBACjB,CAAC,CAAC,CAAA;aACT;QACL,CAAC,CAAC,CAAC;QAEH,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAE,IAAI,EAAE,WAAW,EAAE,SAAS,CAAE,CAAC;IAC5D,CAAC;IAhGQ,SAAS;QADrB,MAAM;OACM,SAAS,CAiGrB;IAAD,gBAAC;CAAA,AAjGD,CAA+B,SAAS,GAiGvC;SAjGY,SAAS"} \ No newline at end of file diff --git a/lib/rest.d.ts b/lib/rest.d.ts new file mode 100644 index 0000000..9fa9219 --- /dev/null +++ b/lib/rest.d.ts @@ -0,0 +1,38 @@ +/// +import { SyncOptions, Restful } from './sync'; +import { Model, Collection } from './type-r'; +export interface RestOptions extends SyncOptions { + wait?: boolean; + patch?: boolean; + reset?: boolean; + validate?: boolean; +} +export declare class RestCollection extends Collection implements Restful { + _xhr: JQueryXHR; + dispose(): void; + model: typeof RestModel; + url(): string; + _invalidate(options: { + validate?: boolean; + }): boolean; + fetch(options: RestOptions): any; + create(a_model: any, options?: any): RestModel; + sync(): any; +} +export declare class RestModel extends Model implements Restful { + static Collection: typeof Collection; + _xhr: JQueryXHR; + urlRoot: string; + _invalidate(options: { + validate?: boolean; + }): boolean; + dispose(): void; + fetch(options?: RestOptions): any; + sync(method: string, self: this, options: SyncOptions): any; + save(attrs?: {}, options?: RestOptions): any; + save(key: string, value: any, options?: RestOptions): any; + destroy(options: RestOptions): any; + url(): string; + set(key: string, value: any, options?: object): this; + set(attrs: {}, options?: object): this; +} diff --git a/lib/rest.js b/lib/rest.js new file mode 100644 index 0000000..2fa428f --- /dev/null +++ b/lib/rest.js @@ -0,0 +1,243 @@ +import * as tslib_1 from "tslib"; +import Sync from './sync'; +import * as _ from 'underscore'; +import { define, Model, Collection, tools, definitions, mixinRules } from './type-r'; +var defaults = tools.defaults; +var transactionalProto = tools.getBaseClass(Model).prototype; +var RestCollection = (function (_super) { + tslib_1.__extends(RestCollection, _super); + function RestCollection() { + return _super !== null && _super.apply(this, arguments) || this; + } + RestCollection.prototype.dispose = function () { + if (this._xhr && this._xhr.abort) + this._xhr.abort(); + _super.prototype.dispose.call(this); + }; + RestCollection.prototype.url = function () { return this.model.prototype.urlRoot || ''; }; + RestCollection.prototype._invalidate = function (options) { + var error; + if (options.validate && (error = this.validationError)) { + this.trigger('invalid', this, error, _.extend({ validationError: error }, options)); + return true; + } + }; + RestCollection.prototype.fetch = function (options) { + options = _.extend({ parse: true }, options); + var success = options.success; + var collection = this; + options.success = function (resp) { + var method = options.reset ? 'reset' : 'set'; + collection[method](resp, options); + if (collection._invalidate(options)) + return false; + if (success) + success.call(options.context, collection, resp, options); + collection.trigger('sync', collection, resp, options); + }; + wrapError(this, options); + return _sync('read', this, options); + }; + RestCollection.prototype.create = function (a_model, options) { + var _this_1 = this; + if (options === void 0) { options = {}; } + var model = a_model instanceof RestModel ? + a_model : + this.model.create(a_model, options); + model._owner || (model._owner = this); + options.wait || this.add([model], options); + var collection = this; + var success = options.success; + options.success = function (model, resp, callbackOpts) { + if (options.wait) + _this_1.add([model], defaults({ parse: false }, callbackOpts)); + if (success) + success.call(callbackOpts.context, model, resp, callbackOpts); + }; + model.save(null, options); + return model; + }; + RestCollection.prototype.sync = function () { + return Sync.sync.apply(this, arguments); + }; + RestCollection = tslib_1.__decorate([ + define({ + itemEvents: { + destroy: function (model) { this.remove(model); } + } + }) + ], RestCollection); + return RestCollection; +}(Collection)); +export { RestCollection }; +; +var RestModel = (function (_super) { + tslib_1.__extends(RestModel, _super); + function RestModel() { + return _super !== null && _super.apply(this, arguments) || this; + } + RestModel.prototype._invalidate = function (options) { + var error; + if (options.validate && (error = this.validationError)) { + triggerAndBubble(this, 'invalid', this, error, _.extend({ validationError: error }, options)); + return true; + } + }; + RestModel.prototype.dispose = function () { + if (this._xhr && this._xhr.abort) + this._xhr.abort(); + _super.prototype.dispose.call(this); + }; + RestModel.prototype.fetch = function (options) { + options = _.extend({ parse: true }, options); + var model = this; + var success = options.success; + options.success = function (serverAttrs) { + model.set(serverAttrs, options); + if (model._invalidate(options)) + return false; + if (success) + success.call(options.context, model, serverAttrs, options); + triggerAndBubble(model, 'sync', model, serverAttrs, options); + }; + wrapError(this, options); + return _sync('read', this, options); + }; + RestModel.prototype.sync = function () { + return Sync.sync.apply(this, arguments); + }; + RestModel.prototype.save = function (key, val, a_options) { + var _this_1 = this; + var attrs, originalOptions; + if (key == null || typeof key === 'object') { + attrs = key; + originalOptions = val || {}; + } + else { + (attrs = {})[key] = val; + originalOptions = a_options || {}; + } + var options = _.extend({ validate: true, parse: true }, originalOptions), wait = options.wait; + if (attrs && !wait) { + this.set(attrs, originalOptions); + } + if (this._invalidate(options)) { + if (attrs && wait) + this.set(attrs, originalOptions); + return Sync.errorPromise(this.validationError); + } + var model = this; + var success = options.success; + var attributes = this.attributes; + options.success = function (serverAttrs) { + model.attributes = attributes; + if (wait) + serverAttrs = _.extend({}, attrs, serverAttrs); + if (serverAttrs) { + transactionalProto.set.call(_this_1, serverAttrs, options); + if (model._invalidate(options)) + return false; + } + if (success) + success.call(options.context, model, serverAttrs, options); + triggerAndBubble(model, 'sync', model, serverAttrs, options); + }; + wrapError(this, options); + if (attrs && wait) + this.attributes = _.extend({}, attributes, attrs); + var method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); + if (method === 'patch' && !options.attrs) + options.attrs = attrs; + var xhr = _sync(method, this, options); + this.attributes = attributes; + return xhr; + }; + RestModel.prototype.destroy = function (options) { + options = options ? _.clone(options) : {}; + var model = this; + var success = options.success; + var wait = options.wait; + var destroy = function () { + model.stopListening(); + model.trigger('destroy', model, model.collection, options); + }; + options.success = function (resp) { + if (wait) + destroy(); + if (success) + success.call(options.context, model, resp, options); + if (!model.isNew()) + triggerAndBubble(model, 'sync', model, resp, options); + }; + var xhr; + if (this.isNew()) { + _.defer(options.success); + } + else { + wrapError(this, options); + xhr = _sync('delete', this, options); + } + if (!wait) + destroy(); + return xhr || false; + }; + RestModel.prototype.url = function () { + var base = _.result(this, 'urlRoot') || + _.result(this.collection, 'url') || + Sync.urlError(); + if (this.isNew()) + return base; + var id = this.get(this.idAttribute); + return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id); + }; + RestModel.prototype.set = function (a, b, c) { + var _a; + if (typeof a === 'string') { + if (c) { + return _super.prototype.set.call(this, (_a = {}, _a[a] = b, _a), c); + } + else { + this[a] = b; + return this; + } + } + else { + return _super.prototype.set.call(this, a, b); + } + }; + RestModel.Collection = RestCollection; + RestModel = tslib_1.__decorate([ + define({ + urlRoot: '' + }), + definitions({ + urlRoot: mixinRules.protoValue + }) + ], RestModel); + return RestModel; +}(Model)); +export { RestModel }; +function _sync(method, _this, options) { + _this._xhr && _this._xhr.abort && _this._xhr.abort(); + var xhr = _this._xhr = _this.sync(method, _this, options); + xhr && xhr.always && xhr.always(function () { _this._xhr = void 0; }); + return xhr; +} +function wrapError(model, options) { + var error = options.error; + options.error = function (resp) { + if (error) + error.call(options.context, model, resp, options); + triggerAndBubble(model, 'error', model, resp, options); + }; +} +function triggerAndBubble(model) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + model.trigger.apply(model, args); + var collection = model.collection; + collection && collection.trigger.apply(collection, args); +} +//# sourceMappingURL=rest.js.map \ No newline at end of file diff --git a/lib/rest.js.map b/lib/rest.js.map new file mode 100644 index 0000000..5aeb5c1 --- /dev/null +++ b/lib/rest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rest.js","sourceRoot":"","sources":["../src/rest.ts"],"names":[],"mappings":";AAAA,OAAO,IAAyC,MAAM,QAAQ,CAAA;AAE9D,OAAO,KAAK,CAAC,MAAM,YA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KAAK,EAAE,IAAI,CAAE,CAAC;IAC3B,IAAA,6BAAU,CAAW;IAC7B,UAAU,IAAI,UAAU,CAAC,OAAO,CAAC,KAAK,CAAE,UAAU,EAAE,IAAI,CAAE,CAAC;AAC/D,CAAC"} \ No newline at end of file diff --git a/lib/sync.d.ts b/lib/sync.d.ts new file mode 100644 index 0000000..4d9ffa5 --- /dev/null +++ b/lib/sync.d.ts @@ -0,0 +1,33 @@ +/// +export declare type LazyValue = () => T | T; +export declare type Method = 'create' | 'update' | 'patch' | 'delete' | 'read'; +export interface Restful { + trigger(event: string, model: any, xhr: any, options: any): any; + collection?: { + trigger(event: string, model: any, xhr: any, options: any): any; + }; + toJSON(options: any): {}; + _xhr: JQueryXHR; + sync(method: string, object: Restful, options: SyncOptions): any; +} +export interface SyncOptions { + url?: LazyValue; + data?: any; + attrs?: {}; + beforeSend?: (xhr: any) => any; + success?: (resp: any) => void; + error?: (xhr?: any, textStatus?: any, errorThrown?: any) => void; + textStatus?: string; + errorThrown?: any; + xhr?: any; + context?: {}; +} +declare const exported: { + $: JQueryStatic; + errorPromise: (error: any) => JQueryDeferred<{}>; + ajax: (options: {}) => any; + sync: typeof sync; + urlError: () => never; +}; +export default exported; +declare function sync(method: Method, model: Restful, options?: SyncOptions): JQueryXHR; diff --git a/lib/sync.js b/lib/sync.js new file mode 100644 index 0000000..80dc21d --- /dev/null +++ b/lib/sync.js @@ -0,0 +1,54 @@ +import * as _ from 'underscore'; +import Backbone from './backbone'; +import { tools } from './type-r'; +var defaults = tools.defaults; +var methodMap = { + 'create': 'POST', + 'update': 'PUT', + 'patch': 'PATCH', + 'delete': 'DELETE', + 'read': 'GET' +}; +var exported = { + $: Backbone.$, + errorPromise: function (error) { + var x = $.Deferred(); + x.reject(error); + return x; + }, + ajax: function (options) { + return $.ajax.apply($, arguments); + }, + sync: sync, + urlError: function () { + throw new Error('A "url" property or function must be specified'); + } +}; +export default exported; +function sync(method, model, options) { + if (options === void 0) { options = {}; } + var type = methodMap[method]; + var params = { type: type, dataType: 'json' }; + if (!options.url) { + params.url = _.result(model, 'url') || exported.urlError(); + } + if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { + params.contentType = 'application/json'; + params.data = JSON.stringify(options.attrs || model.toJSON(options)); + } + if (params.type !== 'GET') { + params.processData = false; + } + var error = options.error; + options.error = function (xhr, textStatus, errorThrown) { + options.textStatus = textStatus; + options.errorThrown = errorThrown; + if (error) + error.call(options.context, xhr, textStatus, errorThrown); + }; + var xhr = options.xhr = exported.ajax(_.extend(params, options)); + model.trigger('request', model, xhr, options); + model.collection && model.collection.trigger('request', model, xhr, options); + return xhr; +} +//# sourceMappingURL=sync.js.map \ No newline at end of file diff --git a/lib/sync.js.map b/lib/sync.js.map new file mode 100644 index 0000000..186b85d --- /dev/null +++ b/lib/sync.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sync.js","sourceRoot":"","sources":["../src/sync.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,CAAC,MAAM,YAAY,CAAA;AAC/B,OAAO,QAAQ,MAAM,YAAY,CAAA;AAEjC,OAAO,EAAE,KAAK,EAAE,MAAM,UAAU,CAAA;AACxB,IAAA,yBAAQ,CAAW;AA8B3B,IAAM,SAAS,GAAG;IACd,QAAQ,EAAG,MAAM;IACjB,QAAQ,EAAG,KAAK;IAChB,OAAO,EAAI,OAAO;IAClB,QAAQ,EAAG,QAAQ;IACnB,MAAM,EAAK,KAAK;CACnB,CAAC;AAEF,IAAM,QAAQ,GAAG;IACb,CAAC,EAAG,QAAQ,CAAC,CAAC;IAEd,YAAY,EAAG,UAAA,KAAK;QAChB,IAAI,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,CAAC;QACrB,CAAC,CAAC,MAAM,CAAE,KAAK,CAAE,CAAC;QAClB,OAAO,CAAC,CAAC;IACb,CAAC;IAID,IAAI,EAAG,UAAU,OAAY;QACzB,OAAO,CAAC,CAAC,IAAI,CAAC,KAAK,CAAE,CAAC,EAAE,SAAS,C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AO,EAAE,GAAG,EAAE,UAAU,EAAE,WAAW,CAAE,CAAC;IAC5E,CAAC,CAAC;IAGF,IAAI,GAAG,GAAG,OAAO,CAAC,GAAG,GAAG,QAAQ,CAAC,IAAI,CAAE,CAAC,CAAC,MAAM,CAAE,MAAM,EAAE,OAAO,CAAE,CAAE,CAAC;IACrE,KAAK,CAAC,OAAO,CAAE,SAAS,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,CAAE,CAAC;IAChD,KAAK,CAAC,UAAU,IAAI,KAAK,CAAC,UAAU,CAAC,OAAO,CAAE,SAAS,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,CAAE,CAAC;IAC/E,OAAO,GAAG,CAAC;AACf,CAAC"} \ No newline at end of file diff --git a/lib/type-r/collection/add.d.ts b/lib/type-r/collection/add.d.ts new file mode 100644 index 0000000..8f60a13 --- /dev/null +++ b/lib/type-r/collection/add.d.ts @@ -0,0 +1,5 @@ +import { CollectionTransaction, CollectionOptions, CollectionCore } from './commons'; +export interface AddOptions extends CollectionOptions { + at?: number; +} +export declare function addTransaction(collection: CollectionCore, items: any[], options: AddOptions, merge?: boolean): CollectionTransaction; diff --git a/lib/type-r/collection/add.js b/lib/type-r/collection/add.js new file mode 100644 index 0000000..0593299 --- /dev/null +++ b/lib/type-r/collection/add.js @@ -0,0 +1,65 @@ +import { transactionApi } from '../transactions'; +import { CollectionTransaction, logAggregationError, sortElements, convertAndAquire, addIndex, updateIndex } from './commons'; +var begin = transactionApi.begin, commit = transactionApi.commit, markAsDirty = transactionApi.markAsDirty; +export function addTransaction(collection, items, options, merge) { + var isRoot = begin(collection), nested = []; + var added = appendElements(collection, items, nested, options, merge); + if (added.length || nested.length) { + var needSort = sortOrMoveElements(collection, added, options); + if (markAsDirty(collection, options)) { + return new CollectionTransaction(collection, isRoot, added, [], nested, needSort); + } + if (collection._aggregationError) + logAggregationError(collection); + } + isRoot && commit(collection); +} +; +function sortOrMoveElements(collection, added, options) { + var at = options.at; + if (at != null) { + var length_1 = collection.models.length - added.length; + at = Number(at); + if (at < 0) + at += length_1 + 1; + if (at < 0) + at = 0; + if (at > length_1) + at = length_1; + moveElements(collection.models, at, added); + return false; + } + return sortElements(collection, options); +} +function moveElements(source, at, added) { + for (var j = source.length - 1, i = j - added.length; i >= at; i--, j--) { + source[j] = source[i]; + } + for (i = 0, j = at; i < added.length; i++, j++) { + source[j] = added[i]; + } +} +function appendElements(collection, a_items, nested, a_options, forceMerge) { + var _byId = collection._byId, models = collection.models, merge = (forceMerge || a_options.merge) && !collection._shared, parse = a_options.parse, idAttribute = collection.model.prototype.idAttribute, prevLength = models.length; + for (var _i = 0, a_items_1 = a_items; _i < a_items_1.length; _i++) { + var item = a_items_1[_i]; + var model = item ? _byId[item[idAttribute]] || _byId[item.cid] : null; + if (model) { + if (merge && item !== model) { + var attrs = item.attributes || item; + var transaction = model._createTransaction(attrs, a_options); + transaction && nested.push(transaction); + if (model.hasChanged(idAttribute)) { + updateIndex(_byId, model); + } + } + } + else { + model = convertAndAquire(collection, item, a_options); + models.push(model); + addIndex(_byId, model); + } + } + return models.slice(prevLength); +} +//# sourceMappingURL=add.js.map \ No newline at end of file diff --git a/lib/type-r/collection/add.js.map b/lib/type-r/collection/add.js.map new file mode 100644 index 0000000..e35a823 --- /dev/null +++ b/lib/type-r/collection/add.js.map @@ -0,0 +1 @@ +{"version":3,"file":"add.js","sourceRoot":"","sources":["../../../src/type-r/collection/add.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAC7D,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,YAAY,EAAE,gBAAgB,EAA2B,QAAQ,EAAE,WAAW,EAAkB,MAAM,WAAW,CAAA;AAG9J,IAAA,4BAAK,EAAE,8BAAM,EAAE,wCAAW,CAAoB;AAOtD,MAAM,UAAU,cAAc,CAAE,UAA2B,EAAE,KAAa,EAAE,OAAoB,EAAE,KAAgB;IAC9G,IAAM,MAAM,GAAG,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IAAI,KAAK,GAAG,IAAI,CAAC,UAAU,IAAI,IAAI,CAAC;gBACpC,IAAM,WAAW,GAAG,KAAK,CAAC,kBAAkB,CAAE,KAAK,EAAE,SAAS,CAAE,CAAC;gBACjE,WAAW,IAAI,MAAM,CAAC,IAAI,CAAE,WAAW,CAAE,CAAC;gBAE1C,IAAI,KAAK,CAAC,UAAU,CAAE,WAAW,CAAE,EAAE;oBACjC,WAAW,CAAE,KAAK,EAAE,KAAK,CAAE,CAAC;iBAC/B;aACJ;SACJ;aACG;YACA,KAAK,GAAG,gBAAgB,CAAE,UAAU,EAAE,IAAI,EAAE,SAAS,CAAE,CAAC;YACxD,MAAM,CAAC,IAAI,CAAE,KAAK,CAAE,CAAC;YACrB,QAAQ,CAAE,KAAK,EAAE,KAAK,CAAE,CAAC;SAC5B;KACJ;IAED,OAAO,MAAM,CAAC,KAAK,CAAE,UAAU,CAAE,CAAC;AACtC,CAAC"} \ No newline at end of file diff --git a/lib/type-r/collection/commons.d.ts b/lib/type-r/collection/commons.d.ts new file mode 100644 index 0000000..cde26ca --- /dev/null +++ b/lib/type-r/collection/commons.d.ts @@ -0,0 +1,42 @@ +import { Record } from '../record'; +import { Owner, Transaction, TransactionOptions, Transactional } from '../transactions'; +import { eventsApi } from '../object-plus'; +export interface CollectionCore extends Transactional, Owner { + _byId: IdIndex; + models: Record[]; + model: typeof Record; + idAttribute: string; + _comparator: Comparator; + get(objOrId: string | Record | Object): Record; + _itemEvents?: eventsApi.EventMap; + _shared: number; + _aggregationError: Record[]; + _log(level: string, text: string, value: any): void; +} +export declare type Elements = (Object | Record)[]; +export interface CollectionOptions extends TransactionOptions { + sort?: boolean; +} +export declare type Comparator = (a: Record, b: Record) => number; +export declare function dispose(collection: CollectionCore): Record[]; +export declare function convertAndAquire(collection: CollectionCore, attrs: {} | Record, options: CollectionOptions): Record; +export declare function free(owner: CollectionCore, child: Record, unset?: boolean): void; +export declare function freeAll(collection: CollectionCore, children: Record[]): Record[]; +export declare function sortElements(collection: CollectionCore, options: CollectionOptions): boolean; +export interface IdIndex { + [id: string]: Record; +} +export declare function addIndex(index: IdIndex, model: Record): void; +export declare function removeIndex(index: IdIndex, model: Record): void; +export declare function updateIndex(index: IdIndex, model: Record): void; +export declare class CollectionTransaction implements Transaction { + object: CollectionCore; + isRoot: boolean; + added: Record[]; + removed: Record[]; + nested: Transaction[]; + sorted: boolean; + constructor(object: CollectionCore, isRoot: boolean, added: Record[], removed: Record[], nested: Transaction[], sorted: boolean); + commit(initiator?: Transactional): void; +} +export declare function logAggregationError(collection: CollectionCore): void; diff --git a/lib/type-r/collection/commons.js b/lib/type-r/collection/commons.js new file mode 100644 index 0000000..19816a2 --- /dev/null +++ b/lib/type-r/collection/commons.js @@ -0,0 +1,126 @@ +import { ItemsBehavior, transactionApi } from '../transactions'; +import { eventsApi } from '../object-plus'; +var EventMap = eventsApi.EventMap, trigger2 = eventsApi.trigger2, trigger3 = eventsApi.trigger3, on = eventsApi.on, off = eventsApi.off, commit = transactionApi.commit, markAsDirty = transactionApi.markAsDirty, _aquire = transactionApi.aquire, _free = transactionApi.free; +export function dispose(collection) { + var models = collection.models; + collection.models = []; + collection._byId = {}; + freeAll(collection, models); + return models; +} +export function convertAndAquire(collection, attrs, options) { + var model = collection.model; + var record; + if (collection._shared) { + record = attrs instanceof model ? attrs : model.create(attrs, options); + if (collection._shared & ItemsBehavior.listen) { + on(record, record._changeEventName, collection._onChildrenChange, collection); + } + } + else { + record = attrs instanceof model ? (options.merge ? attrs.clone() : attrs) : model.create(attrs, options); + if (!_aquire(collection, record)) { + var errors = collection._aggregationError || (collection._aggregationError = []); + errors.push(record); + } + } + var _itemEvents = collection._itemEvents; + _itemEvents && _itemEvents.subscribe(collection, record); + return record; +} +export function free(owner, child, unset) { + if (owner._shared) { + if (owner._shared & ItemsBehavior.listen) { + off(child, child._changeEventName, owner._onChildrenChange, owner); + } + } + else { + _free(owner, child); + unset || child.dispose(); + } + var _itemEvents = owner._itemEvents; + _itemEvents && _itemEvents.unsubscribe(owner, child); +} +export function freeAll(collection, children) { + for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { + var child = children_1[_i]; + free(collection, child); + } + return children; +} +export function sortElements(collection, options) { + var _comparator = collection._comparator; + if (_comparator && options.sort !== false) { + collection.models.sort(_comparator); + return true; + } + return false; +} +export function addIndex(index, model) { + index[model.cid] = model; + var id = model.id; + if (id || id === 0) { + index[id] = model; + } +} +export function removeIndex(index, model) { + delete index[model.cid]; + var id = model.id; + if (id || id === 0) { + delete index[id]; + } +} +export function updateIndex(index, model) { + delete index[model.previous(model.idAttribute)]; + var id = model.id; + id == null || (index[id] = model); +} +var CollectionTransaction = (function () { + function CollectionTransaction(object, isRoot, added, removed, nested, sorted) { + this.object = object; + this.isRoot = isRoot; + this.added = added; + this.removed = removed; + this.nested = nested; + this.sorted = sorted; + } + CollectionTransaction.prototype.commit = function (initiator) { + var _a = this, nested = _a.nested, object = _a.object, _isDirty = object._isDirty; + for (var _i = 0, nested_1 = nested; _i < nested_1.length; _i++) { + var transaction = nested_1[_i]; + transaction.commit(object); + } + if (object._aggregationError) { + logAggregationError(object); + } + for (var _b = 0, nested_2 = nested; _b < nested_2.length; _b++) { + var transaction = nested_2[_b]; + trigger2(object, 'change', transaction.object, _isDirty); + } + var _c = this, added = _c.added, removed = _c.removed; + for (var _d = 0, added_1 = added; _d < added_1.length; _d++) { + var record = added_1[_d]; + trigger3(record, 'add', record, object, _isDirty); + trigger3(object, 'add', record, object, _isDirty); + } + for (var _e = 0, removed_1 = removed; _e < removed_1.length; _e++) { + var record = removed_1[_e]; + trigger3(record, 'remove', record, object, _isDirty); + trigger3(object, 'remove', record, object, _isDirty); + } + if (this.sorted) { + trigger2(object, 'sort', object, _isDirty); + } + if (added.length || removed.length) { + trigger2(object, 'update', object, _isDirty); + } + this.isRoot && commit(object, initiator); + }; + return CollectionTransaction; +}()); +export { CollectionTransaction }; +export function logAggregationError(collection) { + collection._log('error', 'added records already have an owner', collection._aggregationError); + collection._aggregationError = void 0; +} +//# sourceMappingURL=commons.js.map \ No newline at end of file diff --git a/lib/type-r/collection/commons.js.map b/lib/type-r/collection/commons.js.map new file mode 100644 index 0000000..4ad1a34 --- /dev/null +++ b/lib/type-r/collection/commons.js.map @@ -0,0 +1 @@ +{"version":3,"file":"commons.js","sourceRoot":"","sources":["../../../src/type-r/collection/commons.ts"],"names":[],"mappings":"AACA,OAAO,EAAsB,aAAa,EACC,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAElF,OAAO,EAAE,SAAS,EAAS,MAAM,gBAAgB,CAAA;AAEzC,IAAA,6BAAQ,EAAE,6BAAQ,EAAE,6BAAQ,EAAE,iBAAE,EAAE,mBAAG,EACrC,8BAAM,EAAE,wCAAW,EACrB,OAAO,GAAG,cAAc,CAAC,MAAM,EAAE,KAAK,GAAG,cAAc,CAAC,IAAI,CAAC;AA2BnE,MAAM,UAAU,OAAO,CAAE,UAA2B;IACxC,IAAA,0BAAM,CAAgB;IAE9B,UAAU,CAAC,MAAM,GAAG,EAAE,CAAC;IACvB,UAAU,CAAC,KAAK,GAAI,EAAE,CAAC;IAEvB,OAAO,CAAE,UAAU,EAAE,MAAM,CAAE,CAAC;IAC9B,OAAO,MAAM,CAAC;AAClB,CAAC;AAGD,MAAM,UAAU,gBAAgB,CAAE,UAA2B,EAAE,KAAmB,EAAE,OAA2B;IACnG,IAAA,wBAAK,CAAgB;IAE7B,IAAI,MAAe,CAAC;IAEpB,IAAI,UAAU,CAAC,OAAO,EAAE;QACpB,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAS,KAAK,CAAC,MAAM,CAAE,KAAK,EAAE,OAAO,CAAE,CAAC;QAEjF,IAAI,UAAU,CAAC,OAAO,GAAG,aAAa,CAAC,MAAM,EAAE;YAC3C,EAAE,CAAE,MAAM,EAAE,MAAM,CAAC,gBAAgB,EAAE,UAAU,CAAC,iBAAiB,EAAE,UAAU,CAAE,CAAC;SACnF;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AQ,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAE,CAAC;SAC1D;QAED,IAAI,IAAI,CAAC,MAAM,EAAE;YACb,QAAQ,CAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAE,CAAC;SAChD;QAED,IAAI,KAAK,CAAC,MAAM,IAAI,OAAO,CAAC,MAAM,EAAE;YAChC,QAAQ,CAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,CAAE,CAAC;SAClD;QAED,IAAI,CAAC,MAAM,IAAI,MAAM,CAAE,MAAM,EAAE,SAAS,CAAE,CAAC;IAC/C,CAAC;IACL,4BAAC;AAAD,CAAC,AAtDD,IAsDC;;AAED,MAAM,UAAU,mBAAmB,CAAE,UAA2B;IAC5D,UAAU,CAAC,IAAI,CAAE,OAAO,EAAE,qCAAqC,EAAE,UAAU,CAAC,iBAAiB,CAAE,CAAC;IAChG,UAAU,CAAC,iBAAiB,GAAG,KAAK,CAAC,CAAC;AAC1C,CAAC"} \ No newline at end of file diff --git a/lib/type-r/collection/index.d.ts b/lib/type-r/collection/index.d.ts new file mode 100644 index 0000000..b347d6d --- /dev/null +++ b/lib/type-r/collection/index.d.ts @@ -0,0 +1,85 @@ +import { tools, EventMap, EventsDefinition } from '../object-plus'; +import { Transactional, CloneOptions, TransactionOptions, TransactionalDefinition } from '../transactions'; +import { Record, AggregatedType } from '../record'; +import { CollectionCore, CollectionTransaction } from './commons'; +import { AddOptions } from './add'; +import { IOPromise } from '../io-tools'; +export declare type GenericComparator = string | ((x: Record) => number) | ((a: Record, b: Record) => number); +export interface CollectionOptions extends TransactionOptions { + comparator?: GenericComparator; + model?: typeof Record; +} +export declare type Predicate = (val: R, key: number) => boolean | object; +export interface CollectionDefinition extends TransactionalDefinition { + model?: typeof Record; + itemEvents?: EventsDefinition; + _itemEvents?: EventMap; +} +export declare class Collection extends Transactional implements CollectionCore { + _shared: number; + _aggregationError: R[]; + static Subset: typeof Collection; + static Refs: typeof Collection; + static _SubsetOf: typeof Collection; + createSubset(models: ElementsArg, options: any): any; + static onExtend(BaseClass: typeof Transactional): void; + static onDefine(definition: CollectionDefinition, BaseClass: any): void; + static subsetOf: (collectionReference: any) => any; + _itemEvents: EventMap; + models: R[]; + readonly __inner_state__: R[]; + _byId: { + [id: string]: R; + }; + comparator: GenericComparator; + getStore(): Transactional; + _store: Transactional; + _comparator: (a: R, b: R) => number; + _onChildrenChange(record: R, options?: TransactionOptions, initiator?: Transactional): void; + get(objOrId: string | R | Object): R; + each(iteratee: (val: R, key: number) => void, context?: any): void; + forEach(iteratee: (val: R, key?: number) => void, context?: any): void; + every(iteratee: Predicate, context?: any): boolean; + filter(iteratee: Predicate, context?: any): R[]; + find(iteratee: Predicate, context?: any): R; + some(iteratee: Predicate, context?: any): boolean; + map(iteratee: (val: R, key: number) => T, context?: any): T[]; + _validateNested(errors: {}): number; + model: typeof Record; + idAttribute: string; + constructor(records?: (R | {})[], options?: CollectionOptions, shared?: number); + initialize(): void; + readonly length: number; + first(): R; + last(): R; + at(a_index: number): R; + clone(options?: CloneOptions): this; + toJSON(options?: object): any; + set(elements?: ElementsArg, options?: TransactionOptions): this; + liveUpdates(enabled: LiveUpdatesOption): IOPromise; + _liveUpdates: object; + fetch(a_options?: { + liveUpdates?: LiveUpdatesOption; + } & TransactionOptions): IOPromise; + dispose(): void; + reset(a_elements?: ElementsArg, options?: TransactionOptions): R[]; + add(a_elements: ElementsArg, options?: AddOptions): Record[]; + remove(recordsOrIds: any, options?: CollectionOptions): R[] | R; + _createTransaction(a_elements: ElementsArg, options?: TransactionOptions): CollectionTransaction | void; + static _attribute: typeof AggregatedType; + pluck(key: keyof R): any[]; + sort(options?: TransactionOptions): this; + push(model: ElementsArg, options: CollectionOptions): Record[]; + pop(options: CollectionOptions): R; + unset(modelOrId: R | string, options?: any): R; + unshift(model: ElementsArg, options: CollectionOptions): Record[]; + shift(options?: CollectionOptions): R; + slice(): R[]; + indexOf(modelOrId: any): number; + modelId(attrs: {}): any; + toggle(model: R, a_next?: boolean): boolean; + _log(level: tools.LogLevel, text: string, value: any): void; + getClassName(): string; +} +export declare type LiveUpdatesOption = boolean | ((x: any) => boolean); +export declare type ElementsArg = Object | Record | Object[] | Record[]; diff --git a/lib/type-r/collection/index.js b/lib/type-r/collection/index.js new file mode 100644 index 0000000..7cbebb6 --- /dev/null +++ b/lib/type-r/collection/index.js @@ -0,0 +1,438 @@ +import * as tslib_1 from "tslib"; +import { define, tools, eventsApi, EventMap, definitions, mixinRules, Mixable } from '../object-plus'; +import { ItemsBehavior, transactionApi, Transactional } from '../transactions'; +import { Record, SharedType, AggregatedType, createSharedTypeSpec } from '../record'; +import { free, sortElements, updateIndex } from './commons'; +import { addTransaction } from './add'; +import { setTransaction, emptySetTransaction } from './set'; +import { removeOne, removeMany } from './remove'; +import { startIO } from '../io-tools'; +var trigger2 = eventsApi.trigger2, on = eventsApi.on, off = eventsApi.off, begin = transactionApi.begin, commit = transactionApi.commit, markAsDirty = transactionApi.markAsDirty, omit = tools.omit, log = tools.log, assign = tools.assign, defaults = tools.defaults, assignToClassProto = tools.assignToClassProto; +var _count = 0; +var slice = Array.prototype.slice; +var CollectionRefsType = (function (_super) { + tslib_1.__extends(CollectionRefsType, _super); + function CollectionRefsType() { + return _super !== null && _super.apply(this, arguments) || this; + } + CollectionRefsType.defaultValue = []; + return CollectionRefsType; +}(SharedType)); +var Collection = (function (_super) { + tslib_1.__extends(Collection, _super); + function Collection(records, options, shared) { + if (options === void 0) { options = {}; } + var _this = _super.call(this, _count++) || this; + _this.models = []; + _this._byId = {}; + _this.comparator = _this.comparator; + if (options.comparator !== void 0) { + _this.comparator = options.comparator; + options.comparator = void 0; + } + _this.model = _this.model; + if (options.model) { + _this.model = options.model; + options.model = void 0; + } + _this.idAttribute = _this.model.prototype.idAttribute; + _this._shared = shared || 0; + if (records) { + var elements = toElements(_this, records, options); + emptySetTransaction(_this, elements, options, true); + } + _this.initialize.apply(_this, arguments); + if (_this._localEvents) + _this._localEvents.subscribe(_this, _this); + return _this; + } + Collection_1 = Collection; + Collection.prototype.createSubset = function (models, options) { + var SubsetOf = this.constructor.subsetOf(this).options.type, subset = new SubsetOf(models, options); + subset.resolve(this); + return subset; + }; + Collection.onExtend = function (BaseClass) { + var Ctor = this; + this._SubsetOf = null; + function RefsCollection(a, b, listen) { + Ctor.call(this, a, b, ItemsBehavior.share | (listen ? ItemsBehavior.listen : 0)); + } + Mixable.mixins.populate(RefsCollection); + RefsCollection.prototype = this.prototype; + RefsCollection._attribute = CollectionRefsType; + this.Refs = this.Subset = RefsCollection; + Transactional.onExtend.call(this, BaseClass); + createSharedTypeSpec(this, SharedType); + }; + Collection.onDefine = function (definition, BaseClass) { + if (definition.itemEvents) { + var eventsMap = new EventMap(BaseClass.prototype._itemEvents); + eventsMap.addEventsMap(definition.itemEvents); + this.prototype._itemEvents = eventsMap; + } + if (definition.comparator !== void 0) + this.prototype.comparator = definition.comparator; + Transactional.onDefine.call(this, definition); + }; + Object.defineProperty(Collection.prototype, "__inner_state__", { + get: function () { return this.models; }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Collection.prototype, "comparator", { + get: function () { return this._comparator; }, + set: function (x) { + var _this = this; + var compare; + switch (typeof x) { + case 'string': + this._comparator = function (a, b) { + var aa = a[x], bb = b[x]; + if (aa === bb) + return 0; + return aa < bb ? -1 : +1; + }; + break; + case 'function': + if (x.length === 1) { + this._comparator = function (a, b) { + var aa = x.call(_this, a), bb = x.call(_this, b); + if (aa === bb) + return 0; + return aa < bb ? -1 : +1; + }; + } + else { + this._comparator = function (a, b) { return x.call(_this, a, b); }; + } + break; + default: + this._comparator = null; + } + }, + enumerable: true, + configurable: true + }); + Collection.prototype.getStore = function () { + return this._store || (this._store = this._owner ? this._owner.getStore() : this._defaultStore); + }; + Collection.prototype._onChildrenChange = function (record, options, initiator) { + if (options === void 0) { options = {}; } + if (initiator === this) + return; + var idAttribute = this.idAttribute; + if (record.hasChanged(idAttribute)) { + updateIndex(this._byId, record); + } + var isRoot = begin(this); + if (markAsDirty(this, options)) { + trigger2(this, 'change', record, options); + } + isRoot && commit(this); + }; + Collection.prototype.get = function (objOrId) { + if (objOrId == null) + return; + if (typeof objOrId === 'object') { + var id = objOrId[this.idAttribute]; + return (id !== void 0 && this._byId[id]) || this._byId[objOrId.cid]; + } + else { + return this._byId[objOrId]; + } + }; + Collection.prototype.each = function (iteratee, context) { + var fun = bindContext(iteratee, context), models = this.models; + for (var i = 0; i < models.length; i++) { + fun(models[i], i); + } + }; + Collection.prototype.forEach = function (iteratee, context) { + return this.each(iteratee, context); + }; + Collection.prototype.every = function (iteratee, context) { + var fun = toPredicateFunction(iteratee, context), models = this.models; + for (var i = 0; i < models.length; i++) { + if (!fun(models[i], i)) + return false; + } + return true; + }; + Collection.prototype.filter = function (iteratee, context) { + var fun = toPredicateFunction(iteratee, context), models = this.models; + return this.map(function (x, i) { return fun(x, i) ? x : void 0; }); + }; + Collection.prototype.find = function (iteratee, context) { + var fun = toPredicateFunction(iteratee, context), models = this.models; + for (var i = 0; i < models.length; i++) { + if (fun(models[i], i)) + return models[i]; + } + return null; + }; + Collection.prototype.some = function (iteratee, context) { + return Boolean(this.find(iteratee, context)); + }; + Collection.prototype.map = function (iteratee, context) { + var fun = bindContext(iteratee, context), models = this.models, mapped = Array(models.length); + var j = 0; + for (var i = 0; i < models.length; i++) { + var x = fun(models[i], i); + x === void 0 || (mapped[j++] = x); + } + mapped.length = j; + return mapped; + }; + Collection.prototype._validateNested = function (errors) { + if (this._shared) + return 0; + var count = 0; + this.each(function (record) { + var error = record.validationError; + if (error) { + errors[record.cid] = error; + count++; + } + }); + return count; + }; + Collection.prototype.initialize = function () { }; + Object.defineProperty(Collection.prototype, "length", { + get: function () { return this.models.length; }, + enumerable: true, + configurable: true + }); + Collection.prototype.first = function () { return this.models[0]; }; + Collection.prototype.last = function () { return this.models[this.models.length - 1]; }; + Collection.prototype.at = function (a_index) { + var index = a_index < 0 ? a_index + this.models.length : a_index; + return this.models[index]; + }; + Collection.prototype.clone = function (options) { + if (options === void 0) { options = {}; } + var models = this._shared & ItemsBehavior.share ? this.models : this.map(function (model) { return model.clone(); }), copy = new this.constructor(models, { model: this.model, comparator: this.comparator }, this._shared); + if (options.pinStore) + copy._defaultStore = this.getStore(); + return copy; + }; + Collection.prototype.toJSON = function (options) { + return this.models.map(function (model) { return model.toJSON(options); }); + }; + Collection.prototype.set = function (elements, options) { + if (elements === void 0) { elements = []; } + if (options === void 0) { options = {}; } + if (options.add !== void 0) { + this._log('warn', "Collection.set doesn't support 'add' option, behaving as if options.add === true.", options); + } + if (options.reset) { + this.reset(elements, options); + } + else { + var transaction = this._createTransaction(elements, options); + transaction && transaction.commit(); + } + return this; + }; + Collection.prototype.liveUpdates = function (enabled) { + var _this = this; + if (enabled) { + this.liveUpdates(false); + var filter_1 = typeof enabled === 'function' ? enabled : function () { return true; }; + this._liveUpdates = { + updated: function (json) { + filter_1(json) && _this.add(json, { parse: true, merge: true }); + }, + removed: function (id) { return _this.remove(id); } + }; + return this.getEndpoint().subscribe(this._liveUpdates, this).then(function () { return _this; }); + } + else { + if (this._liveUpdates) { + this.getEndpoint().unsubscribe(this._liveUpdates, this); + this._liveUpdates = null; + } + } + }; + Collection.prototype.fetch = function (a_options) { + var _this = this; + if (a_options === void 0) { a_options = {}; } + var options = tslib_1.__assign({ parse: true }, a_options), endpoint = this.getEndpoint(); + return startIO(this, endpoint.list(options, this), options, function (json) { + var result = _this.set(json, tslib_1.__assign({ parse: true }, options)); + if (options.liveUpdates) { + result = _this.liveUpdates(options.liveUpdates); + } + return result; + }); + }; + Collection.prototype.dispose = function () { + if (this._disposed) + return; + var aggregated = !this._shared; + for (var _i = 0, _a = this.models; _i < _a.length; _i++) { + var record = _a[_i]; + free(this, record); + if (aggregated) + record.dispose(); + } + this.liveUpdates(false); + _super.prototype.dispose.call(this); + }; + Collection.prototype.reset = function (a_elements, options) { + if (options === void 0) { options = {}; } + var isRoot = begin(this), previousModels = this.models; + if (a_elements) { + emptySetTransaction(this, toElements(this, a_elements, options), options, true); + } + else { + this._byId = {}; + this.models = []; + } + markAsDirty(this, options); + options.silent || trigger2(this, 'reset', this, defaults({ previousModels: previousModels }, options)); + var _byId = this._byId; + for (var _i = 0, previousModels_1 = previousModels; _i < previousModels_1.length; _i++) { + var toDispose = previousModels_1[_i]; + _byId[toDispose.cid] || free(this, toDispose); + } + isRoot && commit(this); + return this.models; + }; + Collection.prototype.add = function (a_elements, options) { + if (options === void 0) { options = {}; } + var elements = toElements(this, a_elements, options), transaction = this.models.length ? + addTransaction(this, elements, options) : + emptySetTransaction(this, elements, options); + if (transaction) { + transaction.commit(); + return transaction.added; + } + }; + Collection.prototype.remove = function (recordsOrIds, options) { + if (options === void 0) { options = {}; } + if (recordsOrIds) { + return Array.isArray(recordsOrIds) ? + removeMany(this, recordsOrIds, options) : + removeOne(this, recordsOrIds, options); + } + return []; + }; + Collection.prototype._createTransaction = function (a_elements, options) { + if (options === void 0) { options = {}; } + var elements = toElements(this, a_elements, options); + if (this.models.length) { + return options.remove === false ? + addTransaction(this, elements, options, true) : + setTransaction(this, elements, options); + } + else { + return emptySetTransaction(this, elements, options); + } + }; + Collection.prototype.pluck = function (key) { + return this.models.map(function (model) { return model[key]; }); + }; + Collection.prototype.sort = function (options) { + if (options === void 0) { options = {}; } + if (sortElements(this, options)) { + var isRoot = begin(this); + if (markAsDirty(this, options)) { + trigger2(this, 'sort', this, options); + } + isRoot && commit(this); + } + return this; + }; + Collection.prototype.push = function (model, options) { + return this.add(model, assign({ at: this.length }, options)); + }; + Collection.prototype.pop = function (options) { + var model = this.at(this.length - 1); + this.remove(model, tslib_1.__assign({ unset: true }, options)); + return model; + }; + Collection.prototype.unset = function (modelOrId, options) { + var value = this.get(modelOrId); + this.remove(modelOrId, tslib_1.__assign({ unset: true }, options)); + return value; + }; + Collection.prototype.unshift = function (model, options) { + return this.add(model, assign({ at: 0 }, options)); + }; + Collection.prototype.shift = function (options) { + var model = this.at(0); + this.remove(model, tslib_1.__assign({ unset: true }, options)); + return model; + }; + Collection.prototype.slice = function () { + return slice.apply(this.models, arguments); + }; + Collection.prototype.indexOf = function (modelOrId) { + var record = this.get(modelOrId); + return this.models.indexOf(record); + }; + Collection.prototype.modelId = function (attrs) { + return attrs[this.model.prototype.idAttribute]; + }; + Collection.prototype.toggle = function (model, a_next) { + var prev = Boolean(this.get(model)), next = a_next === void 0 ? !prev : Boolean(a_next); + if (prev !== next) { + if (prev) { + this.remove(model); + } + else { + this.add(model); + } + } + return next; + }; + Collection.prototype._log = function (level, text, value) { + tools.log(level, "[Collection Update] " + this.model.prototype.getClassName() + "." + this.getClassName() + ": " + text, { + Argument: value, + 'Attributes spec': this.model.prototype._attributes + }); + }; + Collection.prototype.getClassName = function () { + return _super.prototype.getClassName.call(this) || 'Collection'; + }; + var Collection_1; + Collection._attribute = AggregatedType; + Collection = Collection_1 = tslib_1.__decorate([ + define({ + cidPrefix: 'c', + model: Record, + _changeEventName: 'changes', + _aggregationError: null + }), + definitions({ + comparator: mixinRules.value, + model: mixinRules.protoValue, + itemEvents: mixinRules.merge + }) + ], Collection); + return Collection; +}(Transactional)); +export { Collection }; +function toElements(collection, elements, options) { + var parsed = options.parse ? collection.parse(elements, options) : elements; + return Array.isArray(parsed) ? parsed : [parsed]; +} +createSharedTypeSpec(Collection, SharedType); +Record.Collection = Collection; +function bindContext(fun, context) { + return context !== void 0 ? function (v, k) { return fun.call(context, v, k); } : fun; +} +function toPredicateFunction(iteratee, context) { + if (typeof iteratee === 'object') { + return function (x) { + for (var key in iteratee) { + if (iteratee[key] !== x[key]) + return false; + } + return true; + }; + } + return bindContext(iteratee, context); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib/type-r/collection/index.js.map b/lib/type-r/collection/index.js.map new file mode 100644 index 0000000..0834f87 --- /dev/null +++ b/lib/type-r/collection/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/type-r/collection/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CAAE,GAAc,EAAE,OAAc;IAChD,OAAO,OAAO,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,UAAE,CAAC,EAAE,CAAC,IAAM,OAAA,GAAG,CAAC,IAAI,CAAE,OAAO,EAAE,CAAC,EAAE,CAAC,CAAE,EAAzB,CAAyB,CAAC,CAAC,CAAC,GAAG,CAAC;AAC5E,CAAC;AAED,SAAS,mBAAmB,CAAK,QAAuB,EAAE,OAAa;IACnE,IAAI,OAAO,QAAQ,KAAK,QAAQ,EAAE;QAE9B,OAAO,UAAA,CAAC;YACJ,KAAK,IAAI,GAAG,IAAI,QAAe,EAAE;gBAC7B,IAAI,QAAQ,CAAE,GAAG,CAAE,KAAK,CAAC,CAAE,GAAG,CAAE;oBAC5B,OAAO,KAAK,CAAC;aACpB;YAED,OAAO,IAAI,CAAC;QAChB,CAAC,CAAA;KACJ;IAED,OAAO,WAAW,CAAE,QAAQ,EAAE,OAAO,CAAE,CAAC;AAE5C,CAAC"} \ No newline at end of file diff --git a/lib/type-r/collection/remove.d.ts b/lib/type-r/collection/remove.d.ts new file mode 100644 index 0000000..ffaa6b4 --- /dev/null +++ b/lib/type-r/collection/remove.d.ts @@ -0,0 +1,5 @@ +import { Record } from '../record'; +import { CollectionCore } from './commons'; +import { TransactionOptions } from '../transactions'; +export declare function removeOne(collection: CollectionCore, el: Record | {} | string, options: TransactionOptions): Record; +export declare function removeMany(collection: CollectionCore, toRemove: any[], options: any): any[]; diff --git a/lib/type-r/collection/remove.js b/lib/type-r/collection/remove.js new file mode 100644 index 0000000..c17aa4f --- /dev/null +++ b/lib/type-r/collection/remove.js @@ -0,0 +1,62 @@ +import { free, CollectionTransaction, removeIndex } from './commons'; +import { eventsApi } from '../object-plus'; +import { transactionApi } from '../transactions'; +var trigger2 = eventsApi.trigger2, trigger3 = eventsApi.trigger3, markAsDirty = transactionApi.markAsDirty, begin = transactionApi.begin, commit = transactionApi.commit; +export function removeOne(collection, el, options) { + var model = collection.get(el); + if (model) { + var isRoot = begin(collection), models = collection.models; + models.splice(models.indexOf(model), 1); + removeIndex(collection._byId, model); + var notify = markAsDirty(collection, options); + if (notify) { + trigger3(model, 'remove', model, collection, options); + trigger3(collection, 'remove', model, collection, options); + } + free(collection, model, options.unset); + notify && trigger2(collection, 'update', collection, options); + isRoot && commit(collection); + return model; + } +} +; +export function removeMany(collection, toRemove, options) { + var removed = _removeFromIndex(collection, toRemove, options.unset); + if (removed.length) { + var isRoot = begin(collection); + _reallocate(collection, removed.length); + if (markAsDirty(collection, options)) { + var transaction = new CollectionTransaction(collection, isRoot, [], removed, [], false); + transaction.commit(); + } + else { + isRoot && commit(collection); + } + } + return removed; +} +; +function _removeFromIndex(collection, toRemove, unset) { + var removed = Array(toRemove.length), _byId = collection._byId; + for (var i = 0, j = 0; i < toRemove.length; i++) { + var model = collection.get(toRemove[i]); + if (model) { + removed[j++] = model; + removeIndex(_byId, model); + free(collection, model, unset); + } + } + removed.length = j; + return removed; +} +function _reallocate(collection, removed) { + var prev = collection.models, models = collection.models = Array(prev.length - removed), _byId = collection._byId; + for (var i = 0, j = 0; i < prev.length; i++) { + var model = prev[i]; + if (_byId[model.cid]) { + models[j++] = model; + } + } + models.length = j; +} +//# sourceMappingURL=remove.js.map \ No newline at end of file diff --git a/lib/type-r/collection/remove.js.map b/lib/type-r/collection/remove.js.map new file mode 100644 index 0000000..5744a0a --- /dev/null +++ b/lib/type-r/collection/remove.js.map @@ -0,0 +1 @@ +{"version":3,"file":"remove.js","sourceRoot":"","sources":["../../../src/type-r/collection/remove.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,IAAI,EAAkB,qBAAqB,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AACpF,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAC1C,OAAO,EAAsB,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAE5D,IAAA,6BAAQ,EAAE,6BAAQ,EACpB,wCAAW,EAAE,4BAAK,EAAE,8BAAM,CAAoB;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AC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACzC,IAAI,KAAK,GAAG,IAAI,CAAE,CAAC,CAAE,CAAC;QAEtB,IAAI,KAAK,CAAE,KAAK,CAAC,GAAG,CAAE,EAAE;YACpB,MAAM,CAAE,CAAC,EAAE,CAAE,GAAG,KAAK,CAAC;SACzB;KACJ;IAED,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;AACtB,CAAC"} \ No newline at end of file diff --git a/lib/type-r/collection/set.d.ts b/lib/type-r/collection/set.d.ts new file mode 100644 index 0000000..eb0830a --- /dev/null +++ b/lib/type-r/collection/set.d.ts @@ -0,0 +1,3 @@ +import { CollectionTransaction, CollectionOptions, CollectionCore, Elements } from './commons'; +export declare function emptySetTransaction(collection: CollectionCore, items: Elements, options: CollectionOptions, silent?: boolean): CollectionTransaction; +export declare function setTransaction(collection: any, items: any, options: any): CollectionTransaction; diff --git a/lib/type-r/collection/set.js b/lib/type-r/collection/set.js new file mode 100644 index 0000000..99efd26 --- /dev/null +++ b/lib/type-r/collection/set.js @@ -0,0 +1,94 @@ +import { transactionApi } from '../transactions'; +import { CollectionTransaction, logAggregationError, convertAndAquire, free, sortElements, addIndex, freeAll } from './commons'; +var begin = transactionApi.begin, commit = transactionApi.commit, markAsDirty = transactionApi.markAsDirty; +var silentOptions = { silent: true }; +export function emptySetTransaction(collection, items, options, silent) { + var isRoot = begin(collection); + var added = _reallocateEmpty(collection, items, options); + if (added.length) { + var needSort = sortElements(collection, options); + if (markAsDirty(collection, silent ? silentOptions : options)) { + return new CollectionTransaction(collection, isRoot, added.slice(), [], [], needSort); + } + if (collection._aggregationError) + logAggregationError(collection); + } + isRoot && commit(collection); +} +; +export function setTransaction(collection, items, options) { + var isRoot = begin(collection), nested = []; + var previous = collection.models, added = _reallocate(collection, items, nested, options); + var reusedCount = collection.models.length - added.length, removed = reusedCount < previous.length ? (reusedCount ? _garbageCollect(collection, previous) : + freeAll(collection, previous)) : []; + var addedOrChanged = nested.length || added.length, sorted = (sortElements(collection, options) && addedOrChanged) || added.length || options.sorted; + if (addedOrChanged || removed.length || sorted) { + if (markAsDirty(collection, options)) { + return new CollectionTransaction(collection, isRoot, added, removed, nested, sorted); + } + if (collection._aggregationError) + logAggregationError(collection); + } + isRoot && commit(collection); +} +; +function _garbageCollect(collection, previous) { + var _byId = collection._byId, removed = []; + for (var _i = 0, previous_1 = previous; _i < previous_1.length; _i++) { + var record = previous_1[_i]; + if (!_byId[record.cid]) { + removed.push(record); + free(collection, record); + } + } + return removed; +} +function _reallocate(collection, source, nested, options) { + var models = Array(source.length), _byId = {}, merge = (options.merge == null ? true : options.merge) && !collection._shared, _prevById = collection._byId, prevModels = collection.models, idAttribute = collection.model.prototype.idAttribute, toAdd = [], orderKept = true; + for (var i = 0, j = 0; i < source.length; i++) { + var item = source[i], model = null; + if (item) { + var id = item[idAttribute], cid = item.cid; + if (_byId[id] || _byId[cid]) + continue; + model = _prevById[id] || _prevById[cid]; + } + if (model) { + if (merge && item !== model) { + if (orderKept && prevModels[j] !== model) + orderKept = false; + var attrs = item.attributes || item; + var transaction = model._createTransaction(attrs, options); + transaction && nested.push(transaction); + } + } + else { + model = convertAndAquire(collection, item, options); + toAdd.push(model); + } + models[j++] = model; + addIndex(_byId, model); + } + models.length = j; + collection.models = models; + collection._byId = _byId; + if (!orderKept) + options.sorted = true; + return toAdd; +} +function _reallocateEmpty(self, source, options) { + var len = source ? source.length : 0, models = Array(len), _byId = {}, idAttribute = self.model.prototype.idAttribute; + for (var i = 0, j = 0; i < len; i++) { + var src = source[i]; + if (src && (_byId[src[idAttribute]] || _byId[src.cid])) { + continue; + } + var model = convertAndAquire(self, src, options); + models[j++] = model; + addIndex(_byId, model); + } + models.length = j; + self._byId = _byId; + return self.models = models; +} +//# sourceMappingURL=set.js.map \ No newline at end of file diff --git a/lib/type-r/collection/set.js.map b/lib/type-r/collection/set.js.map new file mode 100644 index 0000000..7da33d2 --- /dev/null +++ b/lib/type-r/collection/set.js.map @@ -0,0 +1 @@ +{"version":3,"file":"set.js","sourceRoot":"","sources":["../../../src/type-r/collection/set.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAC7D,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAW,gBAAgB,EAAE,IAAI,EAAE,YAAY,EAAqB,QAAQ,EAA4B,OAAO,EAAE,MAAM,WAAW,CAAA;AAG7K,IAAA,4BAAK,EAAE,8BAAM,EAAE,wCAAW,CAAoB;AAGtD,IAAM,aAAa,GAAG,EAAE,MAAM,EAAG,IAAI,EAAE,CAAC;AAGxC,MAAM,UAAU,mBAAmB,CAAE,UAA2B,EAAE,KAAgB,EAAE,OAA2B,EAAE,MAAiB;IAC9H,IAAM,MAAM,GAAG,KAAK,CAAE,UAAU,CAAE,CAAC;IAEnC,IAAM,KAAK,GAAG,gBAAgB,CAAE,UAAU,EAAE,KAAK,EAAE,OAAO,CAAE,CAAC;IAE7D,IAAI,KAAK,CAAC,MAAM,EAAE;QACd,IAAM,QAAQ,GAAG,YAAY,CAAE,UAAU,EAAE,OAAO,CAAE,CAAC;QAErD,IAAI,WAAW,CAAE,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,OAAO,CAAE,EAAE;YAE7D,OAAO,IAAI,qBAAqB,CAAE,UAAU,EAAE,MAAM,EAAE,KAAK,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,QAAQ,CAAE,CAAC;SAC3F;QAED,IAAI,UAAU,CAAC,iBAAiB;YAAG,mBAAmB,CAAE,UAAU,CAAE,CAAC;KACxE;IAGD,MAAM,IAAI,MAAM,CAAE,UAAU,CAAE,CAAC;AACnC,CAAC;AAAA,CAAC;AAGF,MAAM,UAAU,cAAc,CAAE,UAAU,EAAE,KAAK,EAAE,OAAO;IACtD,IAAM,MAAM,GAAG,K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AAI,GAAG,GAAG,MAAM,CAAE,CAAC,CAAE,CAAC;QAEtB,IAAI,GAAG,IAAI,CAAE,KAAK,CAAE,GAAG,CAAE,WAAW,CAAE,CAAE,IAAI,KAAK,CAAE,GAAG,CAAC,GAAG,CAAE,CAAE,EAAE;YAC5D,SAAS;SACZ;QAED,IAAI,KAAK,GAAG,gBAAgB,CAAE,IAAI,EAAE,GAAG,EAAE,OAAO,CAAE,CAAC;QACnD,MAAM,CAAE,CAAC,EAAE,CAAE,GAAG,KAAK,CAAC;QACtB,QAAQ,CAAE,KAAK,EAAE,KAAK,CAAE,CAAC;KAC5B;IAED,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;IAClB,IAAI,CAAC,KAAK,GAAM,KAAK,CAAC;IAEtB,OAAO,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;AAChC,CAAC"} \ No newline at end of file diff --git a/lib/type-r/index.d.ts b/lib/type-r/index.d.ts new file mode 100644 index 0000000..9ef1ba6 --- /dev/null +++ b/lib/type-r/index.d.ts @@ -0,0 +1,19 @@ +declare global { + interface ObjectConstructor { + setPrototypeOf(target: Object, proto: Object): any; + } +} +export * from './object-plus'; +export * from './collection'; +export * from './relations'; +export * from './record'; +export * from './transactions'; +export * from './io-tools'; +export declare const on: any, off: any, trigger: any, once: any, listenTo: any, stopListening: any, listenToOnce: any; +import { Record as Model } from './record'; +import { Mixable as Class } from './object-plus/'; +export { Model, Class }; +export declare function attributes(attrDefs: any): typeof Model; +import { ChainableAttributeSpec } from './record'; +export declare function value(x: any): ChainableAttributeSpec; +export declare function transaction(method: F): F; diff --git a/lib/type-r/index.js b/lib/type-r/index.js new file mode 100644 index 0000000..57d167b --- /dev/null +++ b/lib/type-r/index.js @@ -0,0 +1,48 @@ +import * as tslib_1 from "tslib"; +var _a; +import { tools } from './object-plus'; +Object.setPrototypeOf || (Object.setPrototypeOf = tools.defaults); +export * from './object-plus'; +export * from './collection'; +export * from './relations'; +export * from './record'; +export * from './transactions'; +export * from './io-tools'; +import { Events } from './object-plus/'; +export var on = (_a = Events, _a.on), off = _a.off, trigger = _a.trigger, once = _a.once, listenTo = _a.listenTo, stopListening = _a.stopListening, listenToOnce = _a.listenToOnce; +import { Record as Model } from './record'; +import { define, Mixable as Class } from './object-plus/'; +export { Model, Class }; +export function attributes(attrDefs) { + var DefaultRecord = (function (_super) { + tslib_1.__extends(DefaultRecord, _super); + function DefaultRecord() { + return _super !== null && _super.apply(this, arguments) || this; + } + DefaultRecord.attributes = attrDefs; + DefaultRecord = tslib_1.__decorate([ + define + ], DefaultRecord); + return DefaultRecord; + }(Model)); + return DefaultRecord; +} +import { ChainableAttributeSpec } from './record'; +export function value(x) { + return new ChainableAttributeSpec({ value: x }); +} +export function transaction(method) { + return function () { + var _this = this; + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var result; + this.transaction(function () { + result = method.apply(_this, args); + }); + return result; + }; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib/type-r/index.js.map b/lib/type-r/index.js.map new file mode 100644 index 0000000..e88cf93 --- /dev/null +++ b/lib/type-r/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/type-r/index.ts"],"names":[],"mappings":";;AACA,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAA;AAQrC,MAAM,CAAC,cAAc,IAAI,CAAE,MAAM,CAAC,cAAc,GAAG,KAAK,CAAC,QAAQ,CAAE,CAAC;AAMpE,cAAc,eAAe,CAAA;AAC7B,cAAc,cAAc,CAAA;AAC5B,cAAc,aAAa,CAAA;AAC3B,cAAc,UAAU,CAAA;AACxB,cAAc,gBAAgB,CAAA;AAE9B,cAAc,YAAY,CAAA;AAG1B,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AACvC,MAAM,CAAS,IAAA,yBAAE,EAAE,YAAG,EAAE,oBAAO,EAAE,cAAI,EAAE,sBAAQ,EAAE,gCAAa,EAAE,8BAAY,CAAiB;AAK7F,OAAO,EAAE,MAAM,IAAI,KAAK,EAAE,MAAM,UAAU,CAAA;AAC1C,OAAO,EAAE,MAAM,EAAE,OAAO,IAAI,KAAK,EAAE,MAAM,gBAAgB,CAAA;AACzD,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;AAExB,MAAM,UAAU,UAAU,CAAE,QAAQ;IACxB;QAA4B,yCAAK;QAAjC;;QAER,CAAC;QADU,wBAAU,GAAG,QAAQ,CAAC;QADnB,aAAa;YAA1B,MAAM;WAAO,aAAa,CAE1B;QAAD,oBAAC;KAAA,AAFO,CAA4B,KAAK,GAExC;IAED,OAAO,aAAa,CAAC;AACzB,CAAC;AAED,OAAO,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAA;AAGjD,MAAM,UAAU,KAAK,CAAE,CAAO;IAC1B,OAAO,IAAI,sBAAsB,CAAC,EAAE,KAAK,EAAG,CAAC,EAAE,CAAC,CAAC;AACrD,CAAC;AAGD,MAAM,UAAU,WAAW,CAAwB,MAAU;IACzD,OAAY;QAAA,iBAQX;QARqB,cAAO;aAAP,UAAO,EAAP,qBAAO,EAAP,IAAO;YAAP,yBAAO;;QACzB,IAAI,MAAM,CAAC;QAEX,IAAI,CAAC,WAAW,CAAE;YACd,MAAM,GAAG,MAAM,CAAC,KAAK,CAAE,KAAI,EAAE,IAAI,CAAE,CAAC;QACxC,CAAC,CAAC,CAAC;QAEH,OAAO,MAAM,CAAC;IAClB,CAAC,CAAA;AACL,CAAC"} \ No newline at end of file diff --git a/lib/type-r/io-tools.d.ts b/lib/type-r/io-tools.d.ts new file mode 100644 index 0000000..9e6c5c2 --- /dev/null +++ b/lib/type-r/io-tools.d.ts @@ -0,0 +1,29 @@ +export interface IONode { + _endpoint: IOEndpoint; + _ioPromise: IOPromise; +} +export interface IOPromise extends Promise { + abort?: () => void; +} +export interface IOEndpoint { + list(options: IOOptions, collection?: any): IOPromise; + create(json: any, options: IOOptions, record?: any): IOPromise; + update(id: string | number, json: any, options: IOOptions, record?: any): IOPromise; + read(id: string | number, options: IOOptions, record?: any): IOPromise; + destroy(id: string | number, options: IOOptions, record?: any): IOPromise; + subscribe(events: IOEvents, collection?: any): IOPromise; + unsubscribe(events: IOEvents, collection?: any): void; +} +export interface IOOptions { + ioUpdate?: boolean; +} +export interface IOEvents { + updated?: (json: any) => void; + removed?: (json: any) => void; +} +export declare function getOwnerEndpoint(self: any): IOEndpoint; +export declare function createIOPromise(initialize: InitIOPromise): IOPromise; +export declare type InitIOPromise = (resolve: (x?: any) => void, reject: (x?: any) => void, abort?: (fn: Function) => void) => void; +export declare function startIO(self: IONode, promise: IOPromise, options: IOOptions, thenDo: (json: any) => any): IOPromise; +export declare function abortIO(self: IONode): void; +export declare function triggerAndBubble(eventSource: any, ...args: any[]): void; diff --git a/lib/type-r/io-tools.js b/lib/type-r/io-tools.js new file mode 100644 index 0000000..ae0d2b4 --- /dev/null +++ b/lib/type-r/io-tools.js @@ -0,0 +1,60 @@ +export function getOwnerEndpoint(self) { + var collection = self.collection; + if (collection) { + return getOwnerEndpoint(collection); + } + if (self._owner) { + var _endpoints = self._owner._endpoints; + return _endpoints && _endpoints[self._ownerKey]; + } +} +export function createIOPromise(initialize) { + var resolve, reject, onAbort; + function abort(fn) { + onAbort = fn; + } + var promise = new Promise(function (a_resolve, a_reject) { + reject = a_reject; + resolve = a_resolve; + initialize(resolve, reject, abort); + }); + promise.abort = function () { + onAbort ? onAbort(resolve, reject) : reject(new Error("I/O Aborted")); + }; + return promise; +} +export function startIO(self, promise, options, thenDo) { + abortIO(self); + options.ioUpdate = true; + self._ioPromise = promise + .then(function (resp) { + self._ioPromise = null; + var result = thenDo ? thenDo(resp) : resp; + triggerAndBubble(self, 'sync', self, resp, options); + return result; + }) + .catch(function (err) { + self._ioPromise = null; + console.error(err); + triggerAndBubble(self, 'error', self, err, options); + throw err; + }); + self._ioPromise.abort = promise.abort; + return self._ioPromise; +} +export function abortIO(self) { + if (self._ioPromise && self._ioPromise.abort) { + self._ioPromise.abort(); + self._ioPromise = null; + } +} +export function triggerAndBubble(eventSource) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + eventSource.trigger.apply(eventSource, args); + var collection = eventSource.collection; + collection && collection.trigger.apply(collection, args); +} +//# sourceMappingURL=io-tools.js.map \ No newline at end of file diff --git a/lib/type-r/io-tools.js.map b/lib/type-r/io-tools.js.map new file mode 100644 index 0000000..634522b --- /dev/null +++ b/lib/type-r/io-tools.js.map @@ -0,0 +1 @@ +{"version":3,"file":"io-tools.js","sourceRoot":"","sources":["../../src/type-r/io-tools.ts"],"names":[],"mappings":"AA4BA,MAAM,UAAU,gBAAgB,CAAE,IAAI;IAE1B,IAAA,4BAAU,CAAU;IAC5B,IAAI,UAAU,EAAE;QACZ,OAAO,gBAAgB,CAAE,UAAU,CAAE,CAAC;KACzC;IAGD,IAAI,IAAI,CAAC,MAAM,EAAE;QACL,IAAA,mCAAU,CAAiB;QACnC,OAAO,UAAU,IAAI,UAAU,CAAE,IAAI,CAAC,SAAS,CAAE,CAAC;KACrD;AACL,CAAC;AAUD,MAAM,UAAU,eAAe,CAAE,UAA0B;IACvD,IAAI,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC;IAE7B,SAAS,KAAK,CAAE,EAAE;QACd,OAAO,GAAG,EAAE,CAAC;IACjB,CAAC;IAED,IAAM,OAAO,GAAoB,IAAI,OAAO,CAAE,UAAE,SAAS,EAAE,QAAQ;QAC/D,MAAM,GAAG,QAAQ,CAAC;QAClB,OAAO,GAAG,SAAS,CAAC;QACpB,UAAU,CAAE,OAAO,EAAE,MAAM,EAAE,KAAK,CAAE,CAAC;IACzC,CAAC,CAAmB,CAAC;IAErB,OAAO,CAAC,KAAK,GAAG;QACZ,OAAO,CAAC,CAAC,CAAC,OAAO,CAAE,OAAO,EAAE,MAAM,CAAE,CAAC,CAAC,CAAC,MAAM,CAAE,IAAI,KAAK,CAAE,aAAa,CAAE,CAAE,C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QAAP,6BAAO;;IAClD,WAAW,CAAC,OAAO,CAAC,KAAK,CAAE,WAAW,EAAE,IAAI,CAAE,CAAC;IACvC,IAAA,mCAAU,CAAiB;IACnC,UAAU,IAAI,UAAU,CAAC,OAAO,CAAC,KAAK,CAAE,UAAU,EAAE,IAAI,CAAE,CAAC;AAC/D,CAAC"} \ No newline at end of file diff --git a/lib/type-r/object-plus/events.d.ts b/lib/type-r/object-plus/events.d.ts new file mode 100644 index 0000000..1b5a5d8 --- /dev/null +++ b/lib/type-r/object-plus/events.d.ts @@ -0,0 +1,43 @@ +import { Mixable, MixableConstructor, MixinsState } from './mixins'; +import { EventMap, EventsDefinition, EventSource, HandlersByEvent } from './eventsource'; +export { EventMap, EventsDefinition }; +export interface MessengerDefinition { + _localEvents?: EventMap; + localEvents?: EventsDefinition; + properties?: PropertyMap; + [name: string]: any; +} +export interface PropertyMap { + [name: string]: Property; +} +export declare type Property = PropertyDescriptor | (() => any); +export interface MessengersByCid { + [cid: string]: Messenger; +} +export declare type CallbacksByEvents = { + [events: string]: Function; +}; +export declare abstract class Messenger implements Mixable, EventSource { + static __super__: object; + static mixins: MixinsState; + static onExtend: (BaseClass: Function) => void; + static define: (definition?: MessengerDefinition, statics?: object) => MixableConstructor; + static extend: (definition?: MessengerDefinition, statics?: object) => MixableConstructor; + static onDefine({ localEvents, _localEvents, properties }: MessengerDefinition, BaseClass?: typeof Mixable): void; + _events: HandlersByEvent; + _listeningTo: MessengersByCid; + cid: string; + _localEvents: EventMap; + constructor(); + initialize(): void; + on(events: string | CallbacksByEvents, callback: any, context?: any): this; + once(events: string | CallbacksByEvents, callback: any, context?: any): this; + off(events?: string | CallbacksByEvents, callback?: any, context?: any): this; + trigger(name: string, a?: any, b?: any, c?: any, d?: any, e?: any): this; + listenTo(source: Messenger, a: string | CallbacksByEvents, b?: Function): this; + listenToOnce(source: Messenger, a: string | CallbacksByEvents, b?: Function): this; + stopListening(a_source?: Messenger, a?: string | CallbacksByEvents, b?: Function): this; + _disposed: boolean; + dispose(): void; +} +export declare const Events: Messenger; diff --git a/lib/type-r/object-plus/events.js b/lib/type-r/object-plus/events.js new file mode 100644 index 0000000..221066c --- /dev/null +++ b/lib/type-r/object-plus/events.js @@ -0,0 +1,130 @@ +import * as tslib_1 from "tslib"; +import { define, mixinRules, definitions } from './mixins'; +import { omit, transform } from './tools'; +import { EventMap } from './eventsource'; +import * as _eventsApi from './eventsource'; +var EventHandler = _eventsApi.EventHandler, strings = _eventsApi.strings, on = _eventsApi.on, off = _eventsApi.off, once = _eventsApi.once, trigger5 = _eventsApi.trigger5, trigger2 = _eventsApi.trigger2, trigger3 = _eventsApi.trigger3; +var eventSplitter = /\s+/; +var _idCount = 0; +function uniqueId() { + return 'l' + _idCount++; +} +export { EventMap }; +var Messenger = (function () { + function Messenger() { + this._events = void 0; + this._listeningTo = void 0; + this.cid = uniqueId(); + this.initialize.apply(this, arguments); + } + Messenger.onDefine = function (_a, BaseClass) { + var localEvents = _a.localEvents, _localEvents = _a._localEvents, properties = _a.properties; + if (localEvents || _localEvents) { + var eventsMap = new EventMap(this.prototype._localEvents); + localEvents && eventsMap.addEventsMap(localEvents); + _localEvents && eventsMap.merge(_localEvents); + this.prototype._localEvents = eventsMap; + } + if (properties) { + Object.defineProperties(this.prototype, transform({}, properties, toPropertyDescriptor)); + } + }; + Messenger.prototype.initialize = function () { }; + Messenger.prototype.on = function (events, callback, context) { + if (typeof events === 'string') + strings(on, this, events, callback, context); + else + for (var name_1 in events) + strings(on, this, name_1, events[name_1], context || callback); + return this; + }; + Messenger.prototype.once = function (events, callback, context) { + if (typeof events === 'string') + strings(once, this, events, callback, context); + else + for (var name_2 in events) + strings(once, this, name_2, events[name_2], context || callback); + return this; + }; + Messenger.prototype.off = function (events, callback, context) { + if (!events) + off(this, void 0, callback, context); + else if (typeof events === 'string') + strings(off, this, events, callback, context); + else + for (var name_3 in events) + strings(off, this, name_3, events[name_3], context || callback); + return this; + }; + Messenger.prototype.trigger = function (name, a, b, c, d, e) { + if (d !== void 0 || e !== void 0) + trigger5(this, name, a, b, c, d, e); + else if (c !== void 0) + trigger3(this, name, a, b, c); + else + trigger2(this, name, a, b); + return this; + }; + Messenger.prototype.listenTo = function (source, a, b) { + if (source) { + addReference(this, source); + source.on(a, !b && typeof a === 'object' ? this : b, this); + } + return this; + }; + Messenger.prototype.listenToOnce = function (source, a, b) { + if (source) { + addReference(this, source); + source.once(a, !b && typeof a === 'object' ? this : b, this); + } + return this; + }; + Messenger.prototype.stopListening = function (a_source, a, b) { + var _listeningTo = this._listeningTo; + if (_listeningTo) { + var removeAll = !(a || b), second = !b && typeof a === 'object' ? this : b; + if (a_source) { + var source = _listeningTo[a_source.cid]; + if (source) { + if (removeAll) + delete _listeningTo[a_source.cid]; + source.off(a, second, this); + } + } + else if (a_source == null) { + for (var cid in _listeningTo) + _listeningTo[cid].off(a, second, this); + if (removeAll) + (this._listeningTo = void 0); + } + } + return this; + }; + Messenger.prototype.dispose = function () { + if (this._disposed) + return; + this.stopListening(); + this.off(); + this._disposed = true; + }; + Messenger = tslib_1.__decorate([ + define, + definitions({ + properties: mixinRules.merge, + localEvents: mixinRules.merge + }) + ], Messenger); + return Messenger; +}()); +export { Messenger }; +export var Events = omit(Messenger.prototype, 'constructor', 'initialize'); +function toPropertyDescriptor(x) { + if (x) { + return typeof x === 'function' ? { get: x } : x; + } +} +function addReference(listener, source) { + var listeningTo = listener._listeningTo || (listener._listeningTo = Object.create(null)), cid = source.cid || (source.cid = uniqueId()); + listeningTo[cid] = source; +} +//# sourceMappingURL=events.js.map \ No newline at end of file diff --git a/lib/type-r/object-plus/events.js.map b/lib/type-r/object-plus/events.js.map new file mode 100644 index 0000000..728985f --- /dev/null +++ b/lib/type-r/object-plus/events.js.map @@ -0,0 +1 @@ +{"version":3,"file":"events.js","sourceRoot":"","sources":["../../../src/type-r/object-plus/events.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,MAAM,EAA2D,UAAU,EAAE,WAAW,EAAmB,MAAM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A4I/B,MAAM,CAAC,IAAM,MAAM,GAA2B,IAAI,CAAE,SAAS,CAAC,SAAS,EAAE,aAAa,EAAE,YAAY,CAAE,CAAC;AAMvG,SAAS,oBAAoB,CAAE,CAAY;IACvC,IAAI,CAAC,EAAE;QACH,OAAO,OAAO,CAAC,KAAK,UAAU,CAAC,CAAC,CAAC,EAAE,GAAG,EAAgB,CAAC,EAAE,CAAC,CAAC,CAAsB,CAAC,CAAC;KACtF;AACL,CAAC;AAGD,SAAS,YAAY,CAAE,QAAoB,EAAE,MAAkB;IACzD,IAAM,WAAW,GAAG,QAAQ,CAAC,YAAY,IAAI,CAAC,QAAQ,CAAC,YAAY,GAAG,MAAM,CAAC,MAAM,CAAE,IAAI,CAAE,CAAE,EACvF,GAAG,GAAG,MAAM,CAAC,GAAG,IAAI,CAAE,MAAM,CAAC,GAAG,GAAG,QAAQ,EAAE,CAAE,CAAC;IAEtD,WAAW,CAAE,GAAG,CAAE,GAAG,MAAM,CAAC;AAClC,CAAC"} \ No newline at end of file diff --git a/lib/type-r/object-plus/eventsource.d.ts b/lib/type-r/object-plus/eventsource.d.ts new file mode 100644 index 0000000..9f5b1a3 --- /dev/null +++ b/lib/type-r/object-plus/eventsource.d.ts @@ -0,0 +1,41 @@ +export interface EventsDefinition { + [events: string]: Function | string | boolean; +} +export declare class EventMap { + handlers: EventDescriptor[]; + constructor(map?: EventsDefinition | EventMap); + merge(map: EventMap): void; + addEventsMap(map: EventsDefinition): void; + bubbleEvents(names: string): void; + addEvent(names: string, callback: Function | string | boolean): void; + subscribe(target: {}, source: EventSource): void; + unsubscribe(target: {}, source: EventSource): void; +} +export declare class EventDescriptor { + name: string; + callback: Function; + constructor(name: string, callback: Function | string | boolean); +} +export interface HandlersByEvent { + [name: string]: EventHandler; +} +export declare class EventHandler { + callback: Callback; + context: any; + next: any; + constructor(callback: Callback, context: any, next?: any); +} +export interface Callback extends Function { + _callback?: Function; +} +export declare function on(source: EventSource, name: string, callback: Callback, context?: any): void; +export declare function once(source: EventSource, name: string, callback: Callback, context?: any): void; +export declare function off(source: EventSource, name?: string, callback?: Callback, context?: any): void; +export interface EventSource { + _events: HandlersByEvent; +} +export declare function strings(api: ApiEntry, source: EventSource, events: string, callback: Callback, context: any): void; +export declare type ApiEntry = (source: EventSource, event: string, callback: Callback, context?: any) => void; +export declare function trigger2(self: EventSource, name: string, a: any, b: any): void; +export declare function trigger3(self: EventSource, name: string, a: any, b: any, c: any): void; +export declare function trigger5(self: EventSource, name: string, a: any, b: any, c: any, d: any, e: any): void; diff --git a/lib/type-r/object-plus/eventsource.js b/lib/type-r/object-plus/eventsource.js new file mode 100644 index 0000000..ed39014 --- /dev/null +++ b/lib/type-r/object-plus/eventsource.js @@ -0,0 +1,204 @@ +import { once as _once } from './tools'; +var EventMap = (function () { + function EventMap(map) { + this.handlers = []; + if (map) { + if (map instanceof EventMap) { + this.handlers = map.handlers.slice(); + } + else { + map && this.addEventsMap(map); + } + } + } + EventMap.prototype.merge = function (map) { + this.handlers = this.handlers.concat(map.handlers); + }; + EventMap.prototype.addEventsMap = function (map) { + for (var names in map) { + this.addEvent(names, map[names]); + } + }; + EventMap.prototype.bubbleEvents = function (names) { + for (var _i = 0, _a = names.split(eventSplitter); _i < _a.length; _i++) { + var name_1 = _a[_i]; + this.addEvent(name_1, getBubblingHandler(name_1)); + } + }; + EventMap.prototype.addEvent = function (names, callback) { + var handlers = this.handlers; + for (var _i = 0, _a = names.split(eventSplitter); _i < _a.length; _i++) { + var name_2 = _a[_i]; + handlers.push(new EventDescriptor(name_2, callback)); + } + }; + EventMap.prototype.subscribe = function (target, source) { + for (var _i = 0, _a = this.handlers; _i < _a.length; _i++) { + var event_1 = _a[_i]; + on(source, event_1.name, event_1.callback, target); + } + }; + EventMap.prototype.unsubscribe = function (target, source) { + for (var _i = 0, _a = this.handlers; _i < _a.length; _i++) { + var event_2 = _a[_i]; + off(source, event_2.name, event_2.callback, target); + } + }; + return EventMap; +}()); +export { EventMap }; +var EventDescriptor = (function () { + function EventDescriptor(name, callback) { + this.name = name; + if (callback === true) { + this.callback = getBubblingHandler(name); + } + else if (typeof callback === 'string') { + this.callback = + function localCallback() { + var handler = this[callback]; + handler && handler.apply(this, arguments); + }; + } + else { + this.callback = callback; + } + } + return EventDescriptor; +}()); +export { EventDescriptor }; +var _bubblingHandlers = {}; +function getBubblingHandler(event) { + return _bubblingHandlers[event] || (_bubblingHandlers[event] = function (a, b, c, d, e) { + if (d !== void 0 || e !== void 0) + trigger5(this, event, a, b, c, d, e); + if (c !== void 0) + trigger3(this, event, a, b, c); + else + trigger2(this, event, a, b); + }); +} +var EventHandler = (function () { + function EventHandler(callback, context, next) { + if (next === void 0) { next = null; } + this.callback = callback; + this.context = context; + this.next = next; + } + return EventHandler; +}()); +export { EventHandler }; +function listOff(_events, name, callback, context) { + var head = _events[name]; + var filteredHead, prev; + for (var ev = head; ev; ev = ev.next) { + if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || + (context && context !== ev.context)) { + prev = ev; + filteredHead || (filteredHead = ev); + } + else { + if (prev) + prev.next = ev.next; + } + } + if (head !== filteredHead) + _events[name] = filteredHead; +} +function listSend2(head, a, b) { + for (var ev = head; ev; ev = ev.next) + ev.callback.call(ev.context, a, b); +} +function listSend3(head, a, b, c) { + for (var ev = head; ev; ev = ev.next) + ev.callback.call(ev.context, a, b, c); +} +function listSend4(head, a, b, c, d) { + for (var ev = head; ev; ev = ev.next) + ev.callback.call(ev.context, a, b, c, d); +} +function listSend5(head, a, b, c, d, e) { + for (var ev = head; ev; ev = ev.next) + ev.callback.call(ev.context, a, b, c, d, e); +} +function listSend6(head, a, b, c, d, e, f) { + for (var ev = head; ev; ev = ev.next) + ev.callback.call(ev.context, a, b, c, d, e, f); +} +export function on(source, name, callback, context) { + if (callback) { + var _events = source._events || (source._events = Object.create(null)); + _events[name] = new EventHandler(callback, context, _events[name]); + } +} +export function once(source, name, callback, context) { + if (callback) { + var once_1 = _once(function () { + off(source, name, once_1); + callback.apply(this, arguments); + }); + once_1._callback = callback; + on(source, name, once_1, context); + } +} +export function off(source, name, callback, context) { + var _events = source._events; + if (_events) { + if (callback || context) { + if (name) { + listOff(_events, name, callback, context); + } + else { + for (var name_3 in _events) { + listOff(_events, name_3, callback, context); + } + } + } + else if (name) { + _events[name] = void 0; + } + else { + source._events = void 0; + } + } +} +var eventSplitter = /\s+/; +export function strings(api, source, events, callback, context) { + if (eventSplitter.test(events)) { + var names = events.split(eventSplitter); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name_4 = names_1[_i]; + api(source, name_4, callback, context); + } + } + else + api(source, events, callback, context); +} +export function trigger2(self, name, a, b) { + var _events = self._events; + if (_events) { + var queue = _events[name], all = _events.all; + listSend2(queue, a, b); + listSend3(all, name, a, b); + } +} +; +export function trigger3(self, name, a, b, c) { + var _events = self._events; + if (_events) { + var queue = _events[name], all = _events.all; + listSend3(queue, a, b, c); + listSend4(all, name, a, b, c); + } +} +; +export function trigger5(self, name, a, b, c, d, e) { + var _events = self._events; + if (_events) { + var queue = _events[name], all = _events.all; + listSend5(queue, a, b, c, d, e); + listSend6(all, name, a, b, c, d, e); + } +} +; +//# sourceMappingURL=eventsource.js.map \ No newline at end of file diff --git a/lib/type-r/object-plus/eventsource.js.map b/lib/type-r/object-plus/eventsource.js.map new file mode 100644 index 0000000..521a46e --- /dev/null +++ b/lib/type-r/object-plus/eventsource.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eventsource.js","sourceRoot":"","sources":["../../../src/type-r/object-plus/eventsource.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,KAAK,EAAE,MAAM,SAAS,CAAA;AAkBvC;IAGI,kBAAa,GAAkC;QAF/C,aAAQ,GAAuB,EAAE,CAAC;QAG9B,IAAI,GAAG,EAAE;YACL,IAAI,GAAG,YAAY,QAAQ,EAAE;gBACzB,IAAI,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;aACxC;iBACG;g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AO,CAAU;IACzB,IAAI,OAAO,EAAE;QACH,IAAA,KAAK,GAAG,OAAO,CAAE,IAAI,CAAE,EACvB,iBAAG,CAAa;QAEtB,SAAS,CAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAE,CAAC;QAC5B,SAAS,CAAE,GAAG,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAE,CAAC;KACnC;AACL,CAAC;AAAA,CAAC;AAGF,MAAM,UAAU,QAAQ,CAAE,IAAkB,EAAE,IAAa,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IAC9D,IAAA,sBAAO,CAAU;IACzB,IAAI,OAAO,EAAE;QACH,IAAA,KAAK,GAAG,OAAO,CAAE,IAAI,CAAE,EACvB,iBAAG,CAAa;QAEtB,SAAS,CAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAE,CAAC;QAClC,SAAS,CAAE,GAAG,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAE,CAAC;KACzC;AACL,CAAC;AAAA,CAAC"} \ No newline at end of file diff --git a/lib/type-r/object-plus/index.d.ts b/lib/type-r/object-plus/index.d.ts new file mode 100644 index 0000000..e45e6bd --- /dev/null +++ b/lib/type-r/object-plus/index.d.ts @@ -0,0 +1,14 @@ +import * as tools from './tools'; +export { tools }; +export * from './mixins'; +export * from './events'; +import * as eventsApi from './eventsource'; +export { eventsApi }; +import { MixableConstructor } from './mixins'; +declare global { + interface ObjectConstructor { + assign(dest: T, ...sources: Object[]): T; + log: tools.Log; + extend(protoProps: {}, staticProps: {}): MixableConstructor; + } +} diff --git a/lib/type-r/object-plus/index.js b/lib/type-r/object-plus/index.js new file mode 100644 index 0000000..a5fc26a --- /dev/null +++ b/lib/type-r/object-plus/index.js @@ -0,0 +1,11 @@ +import * as tools from './tools'; +export { tools }; +export * from './mixins'; +export * from './events'; +import * as eventsApi from './eventsource'; +export { eventsApi }; +import { Mixable } from './mixins'; +Object.extend = function (protoProps, staticProps) { return Mixable.extend(protoProps, staticProps); }; +Object.assign || (Object.assign = tools.assign); +Object.log = tools.log; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib/type-r/object-plus/index.js.map b/lib/type-r/object-plus/index.js.map new file mode 100644 index 0000000..2f40fa1 --- /dev/null +++ b/lib/type-r/object-plus/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/type-r/object-plus/index.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,KAAK,MAAM,SAAS,CAAA;AAChC,OAAO,EAAE,KAAK,EAAE,CAAA;AAChB,cAAc,UAAU,CAAA;AACxB,cAAc,UAAU,CAAA;AACxB,OAAO,KAAK,SAAS,MAAM,eAAe,CAAA;AAC1C,OAAO,EAAE,SAAS,EAAE,CAAA;AAEpB,OAAO,EAAE,OAAO,EAAsB,MAAM,UAAU,CAAA;AAetD,MAAM,CAAC,MAAM,GAAG,UAAE,UAAU,EAAE,WAAW,IAAM,OAAA,OAAO,CAAC,MAAM,CAAE,UAAU,EAAE,WAAW,CAAE,EAAzC,CAAyC,CAAC;AACzF,MAAM,CAAC,MAAM,IAAI,CAAE,MAAM,CAAC,MAAM,GAAG,KAAK,CAAC,MAAM,CAAE,CAAC;AAClD,MAAM,CAAC,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC"} \ No newline at end of file diff --git a/lib/type-r/object-plus/mixins.d.ts b/lib/type-r/object-plus/mixins.d.ts new file mode 100644 index 0000000..aa9c750 --- /dev/null +++ b/lib/type-r/object-plus/mixins.d.ts @@ -0,0 +1,66 @@ +export interface Subclass extends MixableConstructor { + new (...args: any[]): T; + prototype: T; +} +export interface MixableConstructor extends Function { + __super__?: object; + mixins?: MixinsState; + onExtend?: (BaseClass: Function) => void; + onDefine?: (definition: object, BaseClass: Function) => void; + define?: (definition?: object, statics?: object) => MixableConstructor; + extend?: (definition?: T, statics?: object) => Subclass; +} +export interface MixableDefinition { + mixins?: Mixin[]; +} +export declare class Mixable { + static onExtend: (BaseClass: Function) => void; + static onDefine: (definition: object, BaseClass: Function) => object; + static __super__: object; + static mixins: MixinsState; + static define(protoProps?: MixableDefinition, staticProps?: object): MixableConstructor; + static extend(spec?: T, statics?: {}): Subclass; +} +export declare function predefine(Constructor: MixableConstructor): void; +export declare function define(ClassOrDefinition: Function): void; +export declare function define(ClassOrDefinition: object): ClassDecorator; +export declare function definitions(rules: MixinMergeRules): ClassDecorator; +export declare function propertyListDecorator(listName: string): PropertyDecorator; +export declare function definitionDecorator(definitionKey: any, value: any): (proto: object, name: string) => void; +export declare class MixinsState { + Class: MixableConstructor; + mergeRules: MixinMergeRules; + definitionRules: MixinMergeRules; + definitions: object; + appliedMixins: Mixin[]; + static get(Class: any): MixinsState; + constructor(Class: MixableConstructor); + getStaticDefinitions(BaseClass: Function): { + [key: string]: any; + }; + merge(mixins: Mixin[]): void; + populate(...ctors: Function[]): void; + mergeObject(dest: object, source: object, unshift?: boolean): void; + mergeInheritedMembers(BaseClass: Function): void; +} +export interface MixinMergeRules { + [name: string]: MixinMergeRule; +} +export declare type MixinMergeRule = (a: any, b: any) => any; +export declare type Mixin = { + [key: string]: any; +} | Function; +export interface MixinRulesDecorator { + (rules: MixinMergeRules): ClassDecorator; + value(a: object, b: object): object; + protoValue(a: object, b: object): object; + merge(a: object, b: object): object; + pipe(a: Function, b: Function): Function; + defaults(a: Function, b: Function): Function; + classFirst(a: Function, b: Function): Function; + classLast(a: Function, b: Function): Function; + every(a: Function, b: Function): Function; + some(a: Function, b: Function): Function; +} +export declare const mixins: (...list: Mixin[]) => (Class: Function) => void; +export declare const mixinRules: MixinRulesDecorator; diff --git a/lib/type-r/object-plus/mixins.js b/lib/type-r/object-plus/mixins.js new file mode 100644 index 0000000..83e5980 --- /dev/null +++ b/lib/type-r/object-plus/mixins.js @@ -0,0 +1,245 @@ +import * as tslib_1 from "tslib"; +import { assign, hashMap, getBaseClass, defaults, transform } from './tools'; +import { __extends } from 'tslib'; +var Mixable = (function () { + function Mixable() { + } + Mixable.define = function (protoProps, staticProps) { + if (protoProps === void 0) { protoProps = {}; } + var BaseClass = getBaseClass(this); + staticProps && assign(this, staticProps); + var mixins = protoProps.mixins, defineMixin = tslib_1.__rest(protoProps, ["mixins"]); + mixins && this.mixins.merge(mixins); + this.mixins.mergeObject(this.prototype, defineMixin, true); + this.mixins.mergeObject(this.prototype, this.mixins.getStaticDefinitions(BaseClass), true); + this.onDefine && this.onDefine(this.mixins.definitions, BaseClass); + this.mixins.mergeInheritedMembers(BaseClass); + return this; + }; + Mixable.extend = function (spec, statics) { + var TheSubclass; + if (spec && spec.hasOwnProperty('constructor')) { + TheSubclass = spec.constructor; + __extends(TheSubclass, this); + } + else { + TheSubclass = (function (_super) { + tslib_1.__extends(Subclass, _super); + function Subclass() { + return _super !== null && _super.apply(this, arguments) || this; + } + return Subclass; + }(this)); + } + predefine(TheSubclass); + spec && TheSubclass.define(spec, statics); + return TheSubclass; + }; + return Mixable; +}()); +export { Mixable }; +export function predefine(Constructor) { + var BaseClass = getBaseClass(Constructor); + Constructor.__super__ = BaseClass.prototype; + Constructor.define || MixinsState.get(Mixable).populate(Constructor); + MixinsState.get(Constructor); + Constructor.onExtend && Constructor.onExtend(BaseClass); +} +export function define(ClassOrDefinition) { + if (typeof ClassOrDefinition === 'function') { + predefine(ClassOrDefinition); + ClassOrDefinition.define(); + } + else { + return function (Ctor) { + predefine(Ctor); + Ctor.define(ClassOrDefinition); + }; + } +} +export function definitions(rules) { + return function (Class) { + var mixins = MixinsState.get(Class); + mixins.definitionRules = defaults(hashMap(), rules, mixins.definitionRules); + }; +} +export function propertyListDecorator(listName) { + return function propList(proto, name) { + var list = proto.hasOwnProperty(listName) ? + proto[listName] : (proto[listName] = (proto[listName] || []).slice()); + list.push(name); + }; +} +export function definitionDecorator(definitionKey, value) { + return function (proto, name) { + var _a, _b; + MixinsState + .get(proto.constructor) + .mergeObject(proto, (_a = {}, + _a[definitionKey] = (_b = {}, + _b[name] = value, + _b), + _a)); + }; +} +var MixinsState = (function () { + function MixinsState(Class) { + this.Class = Class; + this.definitions = {}; + var mixins = getBaseClass(Class).mixins; + this.mergeRules = (mixins && mixins.mergeRules) || hashMap(); + this.definitionRules = (mixins && mixins.definitionRules) || hashMap(); + this.appliedMixins = (mixins && mixins.appliedMixins) || []; + } + MixinsState.get = function (Class) { + var mixins = Class.mixins; + return mixins && Class === mixins.Class ? mixins : + Class.mixins = new MixinsState(Class); + }; + MixinsState.prototype.getStaticDefinitions = function (BaseClass) { + var definitions = hashMap(), Class = this.Class; + return transform(definitions, this.definitionRules, function (rule, name) { + if (BaseClass[name] !== Class[name]) { + return Class[name]; + } + }); + }; + MixinsState.prototype.merge = function (mixins) { + var proto = this.Class.prototype, mergeRules = this.mergeRules; + var appliedMixins = this.appliedMixins = this.appliedMixins.slice(); + for (var _i = 0, mixins_1 = mixins; _i < mixins_1.length; _i++) { + var mixin = mixins_1[_i]; + if (Array.isArray(mixin)) { + this.merge(mixin); + } + else if (appliedMixins.indexOf(mixin) < 0) { + appliedMixins.push(mixin); + if (typeof mixin === 'function') { + this.mergeObject(this.Class, mixin); + var sourceMixins = mixin.mixins; + if (sourceMixins) { + this.mergeRules = defaults(hashMap(), this.mergeRules, sourceMixins.mergeRules); + this.definitionRules = defaults(hashMap(), this.definitionRules, sourceMixins.definitionRules); + this.appliedMixins = this.appliedMixins.concat(sourceMixins.appliedMixins); + } + this.mergeObject(proto, mixin.prototype); + } + else { + this.mergeObject(proto, mixin); + } + } + } + }; + MixinsState.prototype.populate = function () { + var ctors = []; + for (var _i = 0; _i < arguments.length; _i++) { + ctors[_i] = arguments[_i]; + } + for (var _a = 0, ctors_1 = ctors; _a < ctors_1.length; _a++) { + var Ctor = ctors_1[_a]; + MixinsState.get(Ctor).merge([this.Class]); + } + }; + MixinsState.prototype.mergeObject = function (dest, source, unshift) { + var _this = this; + forEachOwnProp(source, function (name) { + var sourceProp = Object.getOwnPropertyDescriptor(source, name); + var rule; + if (rule = _this.definitionRules[name]) { + assignProperty(_this.definitions, name, sourceProp, rule, unshift); + } + if (!rule || rule === mixinRules.protoValue) { + assignProperty(dest, name, sourceProp, _this.mergeRules[name], unshift); + } + }); + }; + MixinsState.prototype.mergeInheritedMembers = function (BaseClass) { + var _a = this, mergeRules = _a.mergeRules, Class = _a.Class; + if (mergeRules) { + var proto = Class.prototype, baseProto = BaseClass.prototype; + for (var name_1 in mergeRules) { + var rule = mergeRules[name_1]; + if (proto.hasOwnProperty(name_1) && name_1 in baseProto) { + proto[name_1] = resolveRule(proto[name_1], baseProto[name_1], rule); + } + } + } + }; + return MixinsState; +}()); +export { MixinsState }; +var dontMix = { + function: hashMap({ + length: true, + prototype: true, + caller: true, + arguments: true, + name: true, + __super__: true + }), + object: hashMap({ + constructor: true + }) +}; +function forEachOwnProp(object, fun) { + var ignore = dontMix[typeof object]; + for (var _i = 0, _a = Object.keys(object); _i < _a.length; _i++) { + var name_2 = _a[_i]; + ignore[name_2] || fun(name_2); + } +} +export var mixins = function () { + var list = []; + for (var _i = 0; _i < arguments.length; _i++) { + list[_i] = arguments[_i]; + } + return (function (Class) { return MixinsState.get(Class).merge(list); }); +}; +export var mixinRules = (function (rules) { return (function (Class) { + var mixins = MixinsState.get(Class); + mixins.mergeRules = defaults(rules, mixins.mergeRules); +}); }); +mixinRules.value = function (a, b) { return a; }; +mixinRules.protoValue = function (a, b) { return a; }; +mixinRules.merge = function (a, b) { return defaults({}, a, b); }; +mixinRules.pipe = function (a, b) { return (function (x) { + return a.call(this, b.call(this, x)); +}); }; +mixinRules.defaults = function (a, b) { return (function () { + return defaults(a.apply(this, arguments), b.apply(this, arguments)); +}); }; +mixinRules.classFirst = function (a, b) { return (function () { + a.apply(this, arguments); + b.apply(this, arguments); +}); }; +mixinRules.classLast = function (a, b) { return (function () { + b.apply(this, arguments); + a.apply(this, arguments); +}); }; +mixinRules.every = function (a, b) { return (function () { + return a.apply(this, arguments) && b.apply(this, arguments); +}); }; +mixinRules.some = function (a, b) { return (function () { + return a.apply(this, arguments) || b.apply(this, arguments); +}); }; +function assignProperty(dest, name, sourceProp, rule, unshift) { + if (dest.hasOwnProperty(name)) { + var destProp = Object.getOwnPropertyDescriptor(dest, name); + if (destProp.configurable && 'value' in destProp) { + dest[name] = unshift ? + resolveRule(sourceProp.value, destProp.value, rule) : + resolveRule(destProp.value, sourceProp.value, rule); + } + } + else { + Object.defineProperty(dest, name, sourceProp); + } +} +function resolveRule(dest, source, rule) { + if (dest === void 0) + return source; + if (!rule || source === void 0) + return dest; + return rule(dest, source); +} +//# sourceMappingURL=mixins.js.map \ No newline at end of file diff --git a/lib/type-r/object-plus/mixins.js.map b/lib/type-r/object-plus/mixins.js.map new file mode 100644 index 0000000..d592232 --- /dev/null +++ b/lib/type-r/object-plus/mixins.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mixins.js","sourceRoot":"","sources":["../../../src/type-r/object-plus/mixins.ts"],"names":[],"mappings":";AAKA,OAAO,EAAO,MAAM,EAAQ,OAAO,EAAyB,YAAY,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;AAC9G,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAA;AAwBjC;IAAA;IAuDA,CAAC;IA9CU,cAAM,GAAb,UAAe,UAAmC,EAAE,WAAqB;QAA1D,2BAAA,EAAA,eAAmC;QAC9C,IAAM,SAAS,GAAwB,YAAY,CAAE,IAAI,CAAE,CAAC;QAG5D,WAAW,IAAI,MAAM,CAAE,IAAI,EAAE,WAAW,CAAE,CAAC;QAGnC,IAAA,0BAAM,EAAE,oDAAc,CAAgB;QAC9C,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,KAAK,CAAE,MAAM,CAAE,CAAC;QAGtC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAE,IAAI,CAAC,SAAS,EAAE,WAAW,EAAE,I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I,IAAI,MAAM,KAAK,KAAK,CAAC;QAAG,OAAO,IAAI,CAAC;IAG7C,OAAO,IAAI,CAAE,IAAI,EAAE,MAAM,CAAE,CAAC;AAChC,CAAC"} \ No newline at end of file diff --git a/lib/type-r/object-plus/tools.d.ts b/lib/type-r/object-plus/tools.d.ts new file mode 100644 index 0000000..0600e13 --- /dev/null +++ b/lib/type-r/object-plus/tools.d.ts @@ -0,0 +1,33 @@ +export declare function defaults(dest: T, ...sources: Object[]): T; +export declare type Logger = (level: LogLevel, error: string, props?: object) => void; +export declare type LogLevel = 'none' | 'error' | 'warn' | 'info' | 'debug' | 'log'; +export interface Log extends Logger { + level: number; + throw: number; + stop: number; + logger: Logger; +} +export declare const log: Log; +export declare function isValidJSON(value: any): boolean; +export declare function getBaseClass(Class: Function): any; +export declare function assignToClassProto(Class: any, definition: T, ...names: K[]): void; +export declare function isEmpty(obj: {}): boolean; +export declare type Iteratee = (value: any, key?: string | number) => any; +export declare function some(obj: any, fun: Iteratee): any; +export declare function every(obj: {}, predicate: Iteratee): boolean; +export declare function getPropertyDescriptor(obj: {}, prop: string): PropertyDescriptor; +export declare function omit(source: {}, ...rest: string[]): {}; +export declare function transform(dest: { + [key: string]: A; +}, source: { + [key: string]: B; +}, fun: (value: B, key: string) => A | void): { + [key: string]: A; +}; +export declare function fastAssign(dest: A, source: {}): A; +export declare function fastDefaults(dest: A, source: {}): A; +export declare function assign(dest: T, ...sources: Object[]): T; +export declare function keys(o: any): string[]; +export declare function once(func: Function): Function; +export declare function notEqual(a: any, b: any): boolean; +export declare function hashMap(obj?: any): any; diff --git a/lib/type-r/object-plus/tools.js b/lib/type-r/object-plus/tools.js new file mode 100644 index 0000000..2330693 --- /dev/null +++ b/lib/type-r/object-plus/tools.js @@ -0,0 +1,249 @@ +export function defaults(dest, source) { + for (var name in source) { + if (source.hasOwnProperty(name) && !dest.hasOwnProperty(name)) { + dest[name] = source[name]; + } + } + if (arguments.length > 2) { + for (var i = 2; i < arguments.length; i++) { + var other = arguments[i]; + other && defaults(dest, other); + } + } + return dest; +} +var levelToNumber = { + none: 0, error: 1, warn: 2, info: 3, log: 4, debug: 5 +}; +export var log = function (a_level, a_msg, a_props) { + var levelAsNumber = levelToNumber[a_level], msg, props, level; + if (levelAsNumber === void 0 && !a_props) { + levelAsNumber = 4; + msg = a_level; + props = a_msg; + level = 'log'; + } + else { + msg = a_msg, level = a_level, props = a_props; + } + if (levelAsNumber <= log.level) { + if (levelAsNumber <= log.throw || !log.logger) { + var error = new Error(msg); + error.props = props; + throw error; + } + else { + log.logger(level, msg, props); + if (levelAsNumber <= log.stop) { + debugger; + } + } + } +}; +log.level = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'production' ? 1 : 2; +log.throw = 0; +log.stop = 0; +var toString = typeof window === 'undefined' ? + function toString(something) { + if (something && typeof something === 'object') { + var value = something.__inner_state__ || something, isTransactional = Boolean(something.__inner_state__), isArray = Array.isArray(value); + var keys_1 = Object.keys(value).join(', '), body = isArray ? "[ length = " + value.length + " ]" : "{ " + keys_1 + " }"; + return something.constructor.name + ' ' + body; + } + return something; + } : function toString(x) { return x; }; +if (typeof console !== 'undefined') { + log.logger = function _console(level, error, props) { + var args = [error]; + for (var name_1 in props) { + args.push("\n\t" + name_1 + ":", toString(props[name_1])); + } + console[level].apply(console, args); + }; +} +export function isValidJSON(value) { + if (value === null) { + return true; + } + switch (typeof value) { + case 'number': + case 'string': + case 'boolean': + return true; + case 'object': + var proto = Object.getPrototypeOf(value); + if (proto === Object.prototype || proto === Array.prototype) { + return every(value, isValidJSON); + } + } + return false; +} +export function getBaseClass(Class) { + return Object.getPrototypeOf(Class.prototype).constructor; +} +export function assignToClassProto(Class, definition) { + var names = []; + for (var _i = 2; _i < arguments.length; _i++) { + names[_i - 2] = arguments[_i]; + } + for (var _a = 0, names_1 = names; _a < names_1.length; _a++) { + var name_2 = names_1[_a]; + var value = definition[name_2]; + value === void 0 || (Class.prototype[name_2] = value); + } +} +export function isEmpty(obj) { + if (obj) { + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + return false; + } + } + } + return true; +} +function someArray(arr, fun) { + var result; + for (var i = 0; i < arr.length; i++) { + if (result = fun(arr[i], i)) { + return result; + } + } +} +function someObject(obj, fun) { + var result; + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + if (result = fun(obj[key], key)) { + return result; + } + } + } +} +export function some(obj, fun) { + if (Object.getPrototypeOf(obj) === ArrayProto) { + return someArray(obj, fun); + } + else { + return someObject(obj, fun); + } +} +export function every(obj, predicate) { + return !some(obj, function (x) { return !predicate(x); }); +} +export function getPropertyDescriptor(obj, prop) { + var desc; + for (var proto = obj; !desc && proto; proto = Object.getPrototypeOf(proto)) { + desc = Object.getOwnPropertyDescriptor(proto, prop); + } + return desc; +} +export function omit(source) { + var dest = {}, discard = {}; + for (var i = 1; i < arguments.length; i++) { + discard[arguments[i]] = true; + } + for (var name in source) { + if (!discard.hasOwnProperty(name) && source.hasOwnProperty(name)) { + dest[name] = source[name]; + } + } + return dest; +} +export function transform(dest, source, fun) { + for (var name in source) { + if (source.hasOwnProperty(name)) { + var value = fun(source[name], name); + value === void 0 || (dest[name] = value); + } + } + return dest; +} +export function fastAssign(dest, source) { + for (var name in source) { + dest[name] = source[name]; + } + return dest; +} +export function fastDefaults(dest, source) { + for (var name in source) { + if (dest[name] === void 0) { + dest[name] = source[name]; + } + } + return dest; +} +export function assign(dest, source) { + for (var name in source) { + if (source.hasOwnProperty(name)) { + dest[name] = source[name]; + } + } + if (arguments.length > 2) { + for (var i = 2; i < arguments.length; i++) { + var other = arguments[i]; + other && assign(dest, other); + } + } + return dest; +} +export function keys(o) { + return o ? Object.keys(o) : []; +} +export function once(func) { + var memo, first = true; + return function () { + if (first) { + first = false; + memo = func.apply(this, arguments); + func = null; + } + return memo; + }; +} +var ArrayProto = Array.prototype, DateProto = Date.prototype, ObjectProto = Object.prototype; +export function notEqual(a, b) { + if (a === b) + return false; + if (a && b && typeof a == 'object' && typeof b == 'object') { + var protoA = Object.getPrototypeOf(a); + if (protoA !== Object.getPrototypeOf(b)) + return true; + switch (protoA) { + case DateProto: return +a !== +b; + case ArrayProto: return arraysNotEqual(a, b); + case ObjectProto: + case null: + return objectsNotEqual(a, b); + } + } + return true; +} +function objectsNotEqual(a, b) { + var keysA = Object.keys(a); + if (keysA.length !== Object.keys(b).length) + return true; + for (var i = 0; i < keysA.length; i++) { + var key = keysA[i]; + if (!b.hasOwnProperty(key) || notEqual(a[key], b[key])) { + return true; + } + } + return false; +} +function arraysNotEqual(a, b) { + if (a.length !== b.length) + return true; + for (var i = 0; i < a.length; i++) { + if (notEqual(a[i], b[i])) + return true; + } + return false; +} +var HashProto = Object.create(null); +HashProto.hasOwnProperty = ObjectProto.hasOwnProperty; +export function hashMap(obj) { + var hash = Object.create(HashProto); + return obj ? assign(hash, obj) : hash; +} +//# sourceMappingURL=tools.js.map \ No newline at end of file diff --git a/lib/type-r/object-plus/tools.js.map b/lib/type-r/object-plus/tools.js.map new file mode 100644 index 0000000..60ddc54 --- /dev/null +++ b/lib/type-r/object-plus/tools.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tools.js","sourceRoot":"","sources":["../../../src/type-r/object-plus/tools.ts"],"names":[],"mappings":"AAUA,MAAM,UAAU,QAAQ,CAAO,IAAQ,EAAE,MAAe;IACpD,KAAK,IAAI,IAAI,IAAI,MAAM,EAAG;QACtB,IAAI,MAAM,CAAC,cAAc,CAAE,IAAI,CAAE,IAAI,CAAC,IAAI,CAAC,cAAc,CAAE,IAAI,CAAE,EAAG;YAChE,IAAI,CAAE,IAAI,CAAE,GAAG,MAAM,CAAE,IAAI,CAAE,CAAC;SACjC;KACJ;IAED,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE;QACtB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACvC,IAAM,KAAK,GAAG,SAAS,CAAE,CAAC,CAAE,CAAC;Y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M,EAAE,CAAC,EAAE,EAAG;QACpC,IAAM,GAAG,GAAG,KAAK,CAAE,CAAC,CAAE,CAAC;QAEvB,IAAI,CAAC,CAAC,CAAC,cAAc,CAAE,GAAG,CAAE,IAAI,QAAQ,CAAE,CAAC,CAAE,GAAG,CAAE,EAAE,CAAC,CAAE,GAAG,CAAE,CAAE,EAAG;YAC7D,OAAO,IAAI,CAAC;SACf;KACJ;IAED,OAAO,KAAK,CAAC;AACjB,CAAC;AAGD,SAAS,cAAc,CAAE,CAAC,EAAE,CAAC;IACzB,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM;QAAG,OAAO,IAAI,CAAC;IAExC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,EAAG;QAChC,IAAI,QAAQ,CAAE,CAAC,CAAE,CAAC,CAAE,EAAE,CAAC,CAAE,CAAC,CAAE,CAAE;YAAG,OAAO,IAAI,CAAC;KAChD;IAED,OAAO,KAAK,CAAC;AACjB,CAAC;AAMD,IAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAE,IAAI,CAAE,CAAC;AACxC,SAAS,CAAC,cAAc,GAAG,WAAW,CAAC,cAAc,CAAC;AAEtD,MAAM,UAAU,OAAO,CAAE,GAAI;IACzB,IAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAE,SAAS,CAAE,CAAC;IACxC,OAAO,GAAG,CAAC,CAAC,CAAC,MAAM,CAAE,IAAI,EAAE,GAAG,CAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAC5C,CAAC"} \ No newline at end of file diff --git a/lib/type-r/record/attributes/any.d.ts b/lib/type-r/record/attributes/any.d.ts new file mode 100644 index 0000000..97bfb5b --- /dev/null +++ b/lib/type-r/record/attributes/any.d.ts @@ -0,0 +1,60 @@ +import { AttributesContainer, AttributeUpdatePipeline, RecordTransaction } from './updates'; +import { tools } from '../../object-plus'; +import { TransactionOptions } from '../../transactions'; +import { IOEndpoint } from '../../io-tools'; +declare global { + interface Function { + _attribute: typeof AnyType; + } +} +export declare type Transform = (this: AnyType, next: any, prev: any, record: AttributesContainer, options: TransactionOptions) => any; +export declare type ChangeHandler = (this: AnyType, next: any, prev: any, record: AttributesContainer, options: TransactionOptions) => void; +export interface AttributeOptions { + _attribute?: typeof AnyType; + validate?: (record: AttributesContainer, value: any, key: string) => any; + isRequired?: boolean; + changeEvents?: boolean; + endpoint?: IOEndpoint; + type?: Function; + value?: any; + hasCustomDefault?: boolean; + parse?: Parse; + toJSON?: AttributeToJSON; + getHooks?: GetHook[]; + transforms?: Transform[]; + changeHandlers?: ChangeHandler[]; + _onChange?: ChangeAttrHandler; +} +export declare type Parse = (value: any, key: string) => any; +export declare type GetHook = (value: any, key: string) => any; +export declare type AttributeToJSON = (value: any, key: string) => any; +export declare type AttributeParse = (value: any, key: string) => any; +export declare type ChangeAttrHandler = ((value: any, attr: string) => void) | string; +export declare class AnyType implements AttributeUpdatePipeline { + name: string; + static create(options: AttributeOptions, name: string): AnyType; + canBeUpdated(prev: any, next: any, options: TransactionOptions): any; + transform(next: any, prev: any, model: AttributesContainer, options: TransactionOptions): any; + convert(next: any, prev: any, model: AttributesContainer, options: TransactionOptions): any; + isChanged(a: any, b: any): boolean; + handleChange(next: any, prev: any, model: AttributesContainer, options: TransactionOptions): void; + create(): any; + clone(value: any, record: AttributesContainer): any; + dispose(record: AttributesContainer, value: any): void; + validate(record: AttributesContainer, value: any, key: string): void; + toJSON(value: any, key: any, options?: object): any; + createPropertyDescriptor(): PropertyDescriptor | void; + value: any; + static defaultValue: any; + type: Function; + initialize(name: string, options: TransactionOptions): void; + options: AttributeOptions; + doInit(value: any, record: AttributesContainer, options: TransactionOptions): any; + doUpdate(value: any, record: AttributesContainer, options: TransactionOptions, nested?: RecordTransaction[]): boolean; + propagateChanges: boolean; + _log(level: tools.LogLevel, text: string, value: any, record: AttributesContainer): void; + defaultValue(): any; + constructor(name: string, a_options: AttributeOptions); + getHook: (value: any, key: string) => any; + get: (value: any, key: string) => any; +} diff --git a/lib/type-r/record/attributes/any.js b/lib/type-r/record/attributes/any.js new file mode 100644 index 0000000..afecd90 --- /dev/null +++ b/lib/type-r/record/attributes/any.js @@ -0,0 +1,141 @@ +import { setAttribute } from './updates'; +import { tools } from '../../object-plus'; +var notEqual = tools.notEqual, assign = tools.assign; +var emptyOptions = {}; +var AnyType = (function () { + function AnyType(name, a_options) { + this.name = name; + this.getHook = null; + this.options = a_options; + var options = assign({ getHooks: [], transforms: [], changeHandlers: [] }, a_options); + options.getHooks = options.getHooks.slice(); + options.transforms = options.transforms.slice(); + options.changeHandlers = options.changeHandlers.slice(); + var value = options.value, type = options.type, parse = options.parse, toJSON = options.toJSON, changeEvents = options.changeEvents, validate = options.validate, getHooks = options.getHooks, transforms = options.transforms, changeHandlers = options.changeHandlers; + this.value = value; + this.type = type; + if (!options.hasCustomDefault && type) { + this.defaultValue = this.create; + } + else if (tools.isValidJSON(value)) { + this.defaultValue = new Function("return " + JSON.stringify(value) + ";"); + } + else { + this.defaultValue = this.defaultValue; + } + this.propagateChanges = changeEvents !== false; + this.toJSON = toJSON === void 0 ? this.toJSON : toJSON; + this.validate = validate || this.validate; + if (options.isRequired) { + this.validate = wrapIsRequired(this.validate); + } + transforms.unshift(this.convert); + if (this.get) + getHooks.unshift(this.get); + this.initialize.call(this, options); + if (getHooks.length) { + var getHook_1 = this.getHook = getHooks.reduce(chainGetHooks); + var validate_1 = this.validate; + this.validate = function (record, value, key) { + return validate_1.call(this, record, getHook_1.call(record, value, key), key); + }; + } + this.transform = transforms.length ? transforms.reduce(chainTransforms) : this.transform; + this.handleChange = changeHandlers.length ? changeHandlers.reduce(chainChangeHandlers) : this.handleChange; + var _a = this, doInit = _a.doInit, doUpdate = _a.doUpdate; + this.doInit = parse ? function (value, record, options) { + return doInit.call(this, options.parse && value !== void 0 ? parse.call(record, value, this.name) : value, record, options); + } : doInit; + this.doUpdate = parse ? function (value, record, options, nested) { + return doUpdate.call(this, options.parse && value !== void 0 ? parse.call(record, value, this.name) : value, record, options, nested); + } : doUpdate; + } + AnyType.create = function (options, name) { + var type = options.type, AttributeCtor = options._attribute || (type ? type._attribute : AnyType); + return new AttributeCtor(name, options); + }; + AnyType.prototype.canBeUpdated = function (prev, next, options) { }; + AnyType.prototype.transform = function (next, prev, model, options) { return next; }; + AnyType.prototype.convert = function (next, prev, model, options) { return next; }; + AnyType.prototype.isChanged = function (a, b) { + return notEqual(a, b); + }; + AnyType.prototype.handleChange = function (next, prev, model, options) { }; + AnyType.prototype.create = function () { return void 0; }; + AnyType.prototype.clone = function (value, record) { + return value; + }; + AnyType.prototype.dispose = function (record, value) { + this.handleChange(void 0, value, record, emptyOptions); + }; + AnyType.prototype.validate = function (record, value, key) { }; + AnyType.prototype.toJSON = function (value, key, options) { + return value && value.toJSON ? value.toJSON(options) : value; + }; + AnyType.prototype.createPropertyDescriptor = function () { + var _a = this, name = _a.name, getHook = _a.getHook; + if (name !== 'id') { + return { + set: function (value) { + setAttribute(this, name, value); + }, + get: (getHook ? + function () { + return getHook.call(this, this.attributes[name], name); + } : + function () { return this.attributes[name]; }) + }; + } + }; + AnyType.prototype.initialize = function (name, options) { }; + AnyType.prototype.doInit = function (value, record, options) { + var v = value === void 0 ? this.defaultValue() : value, x = this.transform(v, void 0, record, options); + this.handleChange(x, void 0, record, options); + return x; + }; + AnyType.prototype.doUpdate = function (value, record, options, nested) { + var name = this.name, attributes = record.attributes, prev = attributes[name]; + var next = this.transform(value, prev, record, options); + attributes[name] = next; + if (this.isChanged(next, prev)) { + this.handleChange(next, prev, record, options); + return true; + } + return false; + }; + AnyType.prototype._log = function (level, text, value, record) { + tools.log(level, "[Attribute Update Error] " + record.getClassName() + "." + this.name + ": " + text, { + 'Record': record, + 'Attribute definition': this, + 'Prev. value': record.attributes[this.name], + 'New value': value + }); + }; + AnyType.prototype.defaultValue = function () { + return this.value; + }; + return AnyType; +}()); +export { AnyType }; +function chainGetHooks(prevHook, nextHook) { + return function (value, name) { + return nextHook.call(this, prevHook.call(this, value, name), name); + }; +} +function chainTransforms(prevTransform, nextTransform) { + return function (next, prev, record, options) { + return nextTransform.call(this, prevTransform.call(this, next, prev, record, options), prev, record, options); + }; +} +function chainChangeHandlers(prevHandler, nextHandler) { + return function (next, prev, record, options) { + prevHandler.call(this, next, prev, record, options); + nextHandler.call(this, next, prev, record, options); + }; +} +function wrapIsRequired(validate) { + return function (record, value, key) { + return value ? validate.call(this, record, value, key) : 'Required'; + }; +} +//# sourceMappingURL=any.js.map \ No newline at end of file diff --git a/lib/type-r/record/attributes/any.js.map b/lib/type-r/record/attributes/any.js.map new file mode 100644 index 0000000..f423035 --- /dev/null +++ b/lib/type-r/record/attributes/any.js.map @@ -0,0 +1 @@ +{"version":3,"file":"any.js","sourceRoot":"","sources":["../../../../src/type-r/record/attributes/any.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAmE,MAAM,WAAW,CAAA;AACzG,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAA;AAIjC,IAAA,yBAAQ,EAAE,qBAAM,CAAU;AAwClC,IAAM,YAAY,GAAwB,EAAE,CAAC;AAK7C;IAqII,iBAAoB,IAAa,EAAE,SAA4B;QAA3C,SAAI,GAAJ,IAAI,CAAS;QAgFjC,YAAO,GAAoC,IAAI,CAAA;QA9E3C,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;QAGzB,IAAM,OAAO,GAAsB,MAAM,CAAE,EAAE,QAAQ,EAAG,EAAE,EAAE,UAAU,EAAG,EAAE,EAAE,cAAc,EAAG,EAAE,EAAE,EAAE,SAAS,CAAE,CAAC;QAChH,OAAO,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;QAC5C,OAAO,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;QAChD,OAAO,CAAC,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC,KA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,IAAI,CAAE,IAAI,EAAE,KAAK,EAAE,IAAI,CAAE,EAAE,IAAI,CAAE,CAAC;IAC3E,CAAC,CAAA;AACL,CAAC;AAED,SAAS,eAAe,CAAE,aAAyB,EAAE,aAAyB;IAC1E,OAAO,UAAU,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO;QACxC,OAAO,aAAa,CAAC,IAAI,CAAE,IAAI,EAAE,aAAa,CAAC,IAAI,CAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAE,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAE,CAAC;IACtH,CAAC,CAAA;AACL,CAAC;AAED,SAAS,mBAAmB,CAAE,WAA2B,EAAE,WAA2B;IAClF,OAAO,UAAU,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO;QACxC,WAAW,CAAC,IAAI,CAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAE,CAAC;QACtD,WAAW,CAAC,IAAI,CAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAE,CAAC;IAC1D,CAAC,CAAA;AACL,CAAC;AAED,SAAS,cAAc,CAAE,QAAQ;IAC7B,OAAO,UAAU,MAA4B,EAAE,KAAW,EAAE,GAAY;QACpE,OAAO,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,CAAE,CAAC,CAAC,CAAC,UAAU,CAAC;IAC1E,CAAC,CAAA;AACL,CAAC"} \ No newline at end of file diff --git a/lib/type-r/record/attributes/attrDef.d.ts b/lib/type-r/record/attributes/attrDef.d.ts new file mode 100644 index 0000000..23a59ff --- /dev/null +++ b/lib/type-r/record/attributes/attrDef.d.ts @@ -0,0 +1,36 @@ +import { AttributeOptions, Parse } from './any'; +import { EventsDefinition } from '../../object-plus'; +import { IOEndpoint } from '../../io-tools'; +export interface AttributeCheck { + (value: any, key: string): boolean; + error?: any; +} +export declare class ChainableAttributeSpec { + options: AttributeOptions; + constructor(options: AttributeOptions); + check(check: AttributeCheck, error: any): ChainableAttributeSpec; + readonly asProp: (proto: object, name: string) => void; + readonly as: (proto: object, name: string) => void; + readonly isRequired: ChainableAttributeSpec; + endpoint(endpoint: IOEndpoint): ChainableAttributeSpec; + watcher(ref: string | ((value: any, key: string) => void)): ChainableAttributeSpec; + parse(fun: Parse): ChainableAttributeSpec; + toJSON(fun: any): ChainableAttributeSpec; + get(fun: any): ChainableAttributeSpec; + set(fun: any): ChainableAttributeSpec; + changeEvents(events: boolean): ChainableAttributeSpec; + events(map: EventsDefinition): ChainableAttributeSpec; + readonly has: ChainableAttributeSpec; + metadata(options: AttributeOptions): ChainableAttributeSpec; + value(x: any): ChainableAttributeSpec; + static from(spec: any): ChainableAttributeSpec; +} +export declare function type(this: void, spec: ChainableAttributeSpec | Function): ChainableAttributeSpec; +declare global { + interface Function { + value: (x: any) => ChainableAttributeSpec; + isRequired: ChainableAttributeSpec; + asProp: PropertyDecorator; + has: ChainableAttributeSpec; + } +} diff --git a/lib/type-r/record/attributes/attrDef.js b/lib/type-r/record/attributes/attrDef.js new file mode 100644 index 0000000..df6595f --- /dev/null +++ b/lib/type-r/record/attributes/attrDef.js @@ -0,0 +1,163 @@ +import { Transactional } from '../../transactions'; +import { EventMap, definitionDecorator, tools } from '../../object-plus'; +var assign = tools.assign; +var ChainableAttributeSpec = (function () { + function ChainableAttributeSpec(options) { + this.options = { getHooks: [], transforms: [], changeHandlers: [] }; + if (options) + assign(this.options, options); + } + ChainableAttributeSpec.prototype.check = function (check, error) { + function validate(model, value, name) { + if (!check.call(model, value, name)) { + var msg = error || check.error || name + ' is not valid'; + return typeof msg === 'function' ? msg.call(model, name) : msg; + } + } + var prev = this.options.validate; + return this.metadata({ + validate: prev ? (function (model, value, name) { + return prev(model, value, name) || validate(model, value, name); + }) : validate + }); + }; + Object.defineProperty(ChainableAttributeSpec.prototype, "asProp", { + get: function () { + return definitionDecorator('attributes', this); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ChainableAttributeSpec.prototype, "as", { + get: function () { return this.asProp; }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ChainableAttributeSpec.prototype, "isRequired", { + get: function () { + return this.metadata({ isRequired: true }); + }, + enumerable: true, + configurable: true + }); + ChainableAttributeSpec.prototype.endpoint = function (endpoint) { + return this.metadata({ endpoint: endpoint }); + }; + ChainableAttributeSpec.prototype.watcher = function (ref) { + return this.metadata({ _onChange: ref }); + }; + ChainableAttributeSpec.prototype.parse = function (fun) { + return this.metadata({ parse: fun }); + }; + ChainableAttributeSpec.prototype.toJSON = function (fun) { + return this.metadata({ + toJSON: typeof fun === 'function' ? fun : (fun ? function (x, k, o) { return x && x.toJSON(o); } : emptyFunction) + }); + }; + ChainableAttributeSpec.prototype.get = function (fun) { + return this.metadata({ + getHooks: this.options.getHooks.concat(fun) + }); + }; + ChainableAttributeSpec.prototype.set = function (fun) { + function handleSetHook(next, prev, record, options) { + if (this.isChanged(next, prev)) { + var changed = fun.call(record, next, this.name); + return changed === void 0 ? prev : this.convert(changed, prev, record, options); + } + return prev; + } + return this.metadata({ + transforms: this.options.transforms.concat(handleSetHook) + }); + }; + ChainableAttributeSpec.prototype.changeEvents = function (events) { + return this.metadata({ changeEvents: events }); + }; + ChainableAttributeSpec.prototype.events = function (map) { + var eventMap = new EventMap(map); + function handleEventsSubscribtion(next, prev, record) { + prev && prev.trigger && eventMap.unsubscribe(record, prev); + next && next.trigger && eventMap.subscribe(record, next); + } + return this.metadata({ + changeHandlers: this.options.changeHandlers.concat(handleEventsSubscribtion) + }); + }; + Object.defineProperty(ChainableAttributeSpec.prototype, "has", { + get: function () { + return this; + }, + enumerable: true, + configurable: true + }); + ChainableAttributeSpec.prototype.metadata = function (options) { + var cloned = new ChainableAttributeSpec(this.options); + assign(cloned.options, options); + return cloned; + }; + ChainableAttributeSpec.prototype.value = function (x) { + return this.metadata({ value: x, hasCustomDefault: true }); + }; + ChainableAttributeSpec.from = function (spec) { + var attrSpec; + if (typeof spec === 'function') { + attrSpec = spec.has; + } + else if (spec && spec instanceof ChainableAttributeSpec) { + attrSpec = spec; + } + else { + var type_1 = inferType(spec); + if (type_1 && type_1.prototype instanceof Transactional) { + attrSpec = type_1.shared.value(spec); + } + else { + attrSpec = new ChainableAttributeSpec({ type: type_1, value: spec, hasCustomDefault: true }); + } + } + return attrSpec; + }; + return ChainableAttributeSpec; +}()); +export { ChainableAttributeSpec }; +function emptyFunction() { } +export function type(spec) { + return spec instanceof ChainableAttributeSpec ? spec : new ChainableAttributeSpec({ + type: spec, + value: spec._attribute.defaultValue, + hasCustomDefault: spec._attribute.defaultValue !== void 0 + }); + ; +} +Function.prototype.value = function (x) { + return new ChainableAttributeSpec({ type: this, value: x, hasCustomDefault: true }); +}; +Object.defineProperty(Function.prototype, 'isRequired', { + get: function () { return this._isRequired || this.has.isRequired; }, + set: function (x) { this._isRequired = x; } +}); +Object.defineProperty(Function.prototype, 'asProp', { + get: function () { return this.has.asProp; }, +}); +Object.defineProperty(Function.prototype, 'has', { + get: function () { + return this._has || type(this); + }, + set: function (value) { this._has = value; } +}); +function inferType(value) { + switch (typeof value) { + case 'number': + return Number; + case 'string': + return String; + case 'boolean': + return Boolean; + case 'undefined': + return void 0; + case 'object': + return value ? value.constructor : void 0; + } +} +//# sourceMappingURL=attrDef.js.map \ No newline at end of file diff --git a/lib/type-r/record/attributes/attrDef.js.map b/lib/type-r/record/attributes/attrDef.js.map new file mode 100644 index 0000000..c7347d9 --- /dev/null +++ b/lib/type-r/record/attributes/attrDef.js.map @@ -0,0 +1 @@ +{"version":3,"file":"attrDef.js","sourceRoot":"","sources":["../../../../src/type-r/record/attributes/attrDef.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAGlD,OAAO,EAAE,QAAQ,EAAoB,mBAAmB,EAAE,KAAK,EAAE,MA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,CAAC,KAAK,CAAC,CAAC;KACvD;AACL,CAAC"} \ No newline at end of file diff --git a/lib/type-r/record/attributes/basic.d.ts b/lib/type-r/record/attributes/basic.d.ts new file mode 100644 index 0000000..d47677a --- /dev/null +++ b/lib/type-r/record/attributes/basic.d.ts @@ -0,0 +1,48 @@ +import { AnyType } from './any'; +import { AttributesContainer } from './updates'; +import { TransactionOptions } from '../../transactions'; +export declare class PrimitiveType extends AnyType { + type: NumberConstructor | StringConstructor | BooleanConstructor; + dispose(): void; + create(): string | number | boolean; + toJSON(value: any): any; + convert(next: any): any; + isChanged(a: any, b: any): boolean; + clone(value: any): any; + doInit(value: any, record: AttributesContainer, options: TransactionOptions): any; + doUpdate(value: any, record: any, options: any, nested: any): boolean; + initialize(): void; +} +export declare class NumericType extends PrimitiveType { + type: NumberConstructor; + create(): number; + convert(next: any, prev?: any, record?: any): any; + validate(model: any, value: any, name: any): string; +} +declare global { + interface NumberConstructor { + integer: Function; + } + interface Window { + Integer: Function; + } +} +export declare class ArrayType extends AnyType { + toJSON(value: any): any; + dispose(): void; + create(): any[]; + convert(next: any, prev: any, record: any): any; + clone(value: any): any; +} +export declare class ObjectType extends AnyType { + create(): {}; + convert(next: any, prev: any, record: any): any; +} +export declare function doNothing(): void; +export declare class FunctionType extends AnyType { + toJSON(value: any): any; + create(): typeof doNothing; + dispose(): void; + convert(next: any, prev: any, record: any): any; + clone(value: any): any; +} diff --git a/lib/type-r/record/attributes/basic.js b/lib/type-r/record/attributes/basic.js new file mode 100644 index 0000000..f802b0c --- /dev/null +++ b/lib/type-r/record/attributes/basic.js @@ -0,0 +1,142 @@ +import * as tslib_1 from "tslib"; +import { AnyType } from './any'; +var ImmutableClassType = (function (_super) { + tslib_1.__extends(ImmutableClassType, _super); + function ImmutableClassType() { + return _super !== null && _super.apply(this, arguments) || this; + } + ImmutableClassType.prototype.create = function () { + return new this.type(); + }; + ImmutableClassType.prototype.convert = function (next) { + return next == null || next instanceof this.type ? next : new this.type(next); + }; + ImmutableClassType.prototype.toJSON = function (value, key, options) { + return value && value.toJSON ? value.toJSON(options) : value; + }; + ImmutableClassType.prototype.clone = function (value) { + return new this.type(this.toJSON(value)); + }; + ImmutableClassType.prototype.isChanged = function (a, b) { + return a !== b; + }; + return ImmutableClassType; +}(AnyType)); +Function.prototype._attribute = ImmutableClassType; +var PrimitiveType = (function (_super) { + tslib_1.__extends(PrimitiveType, _super); + function PrimitiveType() { + return _super !== null && _super.apply(this, arguments) || this; + } + PrimitiveType.prototype.dispose = function () { }; + PrimitiveType.prototype.create = function () { return this.type(); }; + PrimitiveType.prototype.toJSON = function (value) { return value; }; + PrimitiveType.prototype.convert = function (next) { return next == null ? next : this.type(next); }; + PrimitiveType.prototype.isChanged = function (a, b) { return a !== b; }; + PrimitiveType.prototype.clone = function (value) { return value; }; + PrimitiveType.prototype.doInit = function (value, record, options) { + return this.transform(value === void 0 ? this.value : value, void 0, record, options); + }; + PrimitiveType.prototype.doUpdate = function (value, record, options, nested) { + var name = this.name, attributes = record.attributes, prev = attributes[name]; + return prev !== (attributes[name] = this.transform(value, prev, record, options)); + }; + PrimitiveType.prototype.initialize = function () { + if (!this.options.hasCustomDefault) { + this.value = this.type(); + } + }; + return PrimitiveType; +}(AnyType)); +export { PrimitiveType }; +Boolean._attribute = String._attribute = PrimitiveType; +var NumericType = (function (_super) { + tslib_1.__extends(NumericType, _super); + function NumericType() { + return _super !== null && _super.apply(this, arguments) || this; + } + NumericType.prototype.create = function () { + return 0; + }; + NumericType.prototype.convert = function (next, prev, record) { + var num = next == null ? next : this.type(next); + if (num !== num) { + this._log('warn', 'assigned with Invalid Number', next, record); + } + return num; + }; + NumericType.prototype.validate = function (model, value, name) { + if (value != null && !isFinite(value)) { + return name + ' is not valid number'; + } + }; + return NumericType; +}(PrimitiveType)); +export { NumericType }; +Number._attribute = NumericType; +function Integer(x) { + return x ? Math.round(x) : 0; +} +Integer._attribute = NumericType; +Number.integer = Integer; +if (typeof window !== 'undefined') { + window.Integer = Number.integer; +} +var ArrayType = (function (_super) { + tslib_1.__extends(ArrayType, _super); + function ArrayType() { + return _super !== null && _super.apply(this, arguments) || this; + } + ArrayType.prototype.toJSON = function (value) { return value; }; + ArrayType.prototype.dispose = function () { }; + ArrayType.prototype.create = function () { return []; }; + ArrayType.prototype.convert = function (next, prev, record) { + if (next == null || Array.isArray(next)) + return next; + this._log('warn', 'assignment of non-array to Array attribute is ignored', next, record); + return []; + }; + ArrayType.prototype.clone = function (value) { + return value && value.slice(); + }; + return ArrayType; +}(AnyType)); +export { ArrayType }; +Array._attribute = ArrayType; +var ObjectType = (function (_super) { + tslib_1.__extends(ObjectType, _super); + function ObjectType() { + return _super !== null && _super.apply(this, arguments) || this; + } + ObjectType.prototype.create = function () { return {}; }; + ObjectType.prototype.convert = function (next, prev, record) { + if (next == null || typeof next === 'object') + return next; + this._log('warn', 'assignment of non-object to Object attribute is ignored', next, record); + return {}; + }; + return ObjectType; +}(AnyType)); +export { ObjectType }; +Object._attribute = ObjectType; +export function doNothing() { } +var FunctionType = (function (_super) { + tslib_1.__extends(FunctionType, _super); + function FunctionType() { + return _super !== null && _super.apply(this, arguments) || this; + } + FunctionType.prototype.toJSON = function (value) { return void 0; }; + FunctionType.prototype.create = function () { return doNothing; }; + FunctionType.prototype.dispose = function () { }; + FunctionType.prototype.convert = function (next, prev, record) { + if (next == null || typeof next === 'function') + return next; + this._log('warn', 'assigned with non-function', next, record); + return doNothing; + }; + FunctionType.prototype.clone = function (value) { return value; }; + return FunctionType; +}(AnyType)); +export { FunctionType }; +Function._attribute = FunctionType; +//# sourceMappingURL=basic.js.map \ No newline at end of file diff --git a/lib/type-r/record/attributes/basic.js.map b/lib/type-r/record/attributes/basic.js.map new file mode 100644 index 0000000..5452804 --- /dev/null +++ b/lib/type-r/record/attributes/basic.js.map @@ -0,0 +1 @@ +{"version":3,"file":"basic.js","sourceRoot":"","sources":["../../../../src/type-r/record/attributes/basic.ts"],"names":[],"mappings":";AAMA,OAAO,EAAE,OAAO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AAO,KAAK,IAAI,OAAO,KAAK,CAAC,CAAC,CAAC;IACnC,mBAAC;AAAD,CAAC,AAjBD,CAAkC,OAAO,GAiBxC;;AAED,QAAQ,CAAC,UAAU,GAAG,YAAY,CAAC"} \ No newline at end of file diff --git a/lib/type-r/record/attributes/date.d.ts b/lib/type-r/record/attributes/date.d.ts new file mode 100644 index 0000000..3d82bfb --- /dev/null +++ b/lib/type-r/record/attributes/date.d.ts @@ -0,0 +1,28 @@ +import { AnyType } from './any'; +import { AttributesContainer } from './updates'; +import { TransactionOptions } from '../../transactions'; +import { ChainableAttributeSpec } from './attrDef'; +export declare class DateType extends AnyType { + create(): Date; + convert(next: any, a: any, record: any): any; + validate(model: any, value: any, name: any): string; + toJSON(value: any): any; + isChanged(a: any, b: any): boolean; + doInit(value: any, record: AttributesContainer, options: TransactionOptions): any; + doUpdate(value: any, record: any, options: any, nested: any): boolean; + clone(value: any): Date; + dispose(): void; +} +export declare class MSDateType extends DateType { + convert(next: any): any; + toJSON(value: any): string; +} +export declare class TimestampType extends DateType { + toJSON(value: any): any; +} +declare global { + interface DateConstructor { + microsoft: ChainableAttributeSpec; + timestamp: ChainableAttributeSpec; + } +} diff --git a/lib/type-r/record/attributes/date.js b/lib/type-r/record/attributes/date.js new file mode 100644 index 0000000..d0b6a7d --- /dev/null +++ b/lib/type-r/record/attributes/date.js @@ -0,0 +1,125 @@ +import * as tslib_1 from "tslib"; +import { AnyType } from './any'; +import { ChainableAttributeSpec } from './attrDef'; +var DateProto = Date.prototype; +var DateType = (function (_super) { + tslib_1.__extends(DateType, _super); + function DateType() { + return _super !== null && _super.apply(this, arguments) || this; + } + DateType.prototype.create = function () { + return new Date(); + }; + DateType.prototype.convert = function (next, a, record) { + if (next == null || next instanceof Date) + return next; + var date = new Date(next), timestamp = date.getTime(); + if (timestamp !== timestamp) { + this._log('warn', 'assigned with Invalid Date', next, record); + } + return date; + }; + DateType.prototype.validate = function (model, value, name) { + if (value != null) { + var timestamp = value.getTime(); + if (timestamp !== timestamp) + return name + ' is Invalid Date'; + } + }; + DateType.prototype.toJSON = function (value) { return value && value.toISOString(); }; + DateType.prototype.isChanged = function (a, b) { return (a && a.getTime()) !== (b && b.getTime()); }; + DateType.prototype.doInit = function (value, record, options) { + return this.transform(value === void 0 ? this.defaultValue() : value, void 0, record, options); + }; + DateType.prototype.doUpdate = function (value, record, options, nested) { + var name = this.name, attributes = record.attributes, prev = attributes[name]; + return this.isChanged(prev, attributes[name] = this.transform(value, prev, record, options)); + }; + DateType.prototype.clone = function (value) { return value && new Date(value.getTime()); }; + DateType.prototype.dispose = function () { }; + return DateType; +}(AnyType)); +export { DateType }; +Date._attribute = DateType; +var msDatePattern = /\/Date\(([0-9]+)\)\//; +var MSDateType = (function (_super) { + tslib_1.__extends(MSDateType, _super); + function MSDateType() { + return _super !== null && _super.apply(this, arguments) || this; + } + MSDateType.prototype.convert = function (next) { + if (typeof next === 'string') { + var msDate = msDatePattern.exec(next); + if (msDate) { + return new Date(Number(msDate[1])); + } + } + return DateType.prototype.convert.apply(this, arguments); + }; + MSDateType.prototype.toJSON = function (value) { return value && "/Date(" + value.getTime() + ")/"; }; + return MSDateType; +}(DateType)); +export { MSDateType }; +var TimestampType = (function (_super) { + tslib_1.__extends(TimestampType, _super); + function TimestampType() { + return _super !== null && _super.apply(this, arguments) || this; + } + TimestampType.prototype.toJSON = function (value) { return value && value.getTime(); }; + return TimestampType; +}(DateType)); +export { TimestampType }; +Object.defineProperties(Date, { + microsoft: { + get: function () { + return new ChainableAttributeSpec({ + type: Date, + _attribute: MSDateType + }); + } + }, + timestamp: { + get: function () { + return new ChainableAttributeSpec({ + type: Date, + _attribute: TimestampType + }); + } + } +}); +function supportsDate(date) { + return !isNaN((new Date(date)).getTime()); +} +if (!supportsDate('2011-11-29T15:52:30.5') || + !supportsDate('2011-11-29T15:52:30.52') || + !supportsDate('2011-11-29T15:52:18.867') || + !supportsDate('2011-11-29T15:52:18.867Z') || + !supportsDate('2011-11-29T15:52:18.867-03:30')) { + DateType.prototype.convert = function (value) { + return value == null || value instanceof Date ? value : new Date(safeParseDate(value)); + }; +} +var numericKeys = [1, 4, 5, 6, 7, 10, 11], isoDatePattern = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/; +function safeParseDate(date) { + var timestamp, struct, minutesOffset = 0; + if ((struct = isoDatePattern.exec(date))) { + for (var i = 0, k; (k = numericKeys[i]); ++i) { + struct[k] = +struct[k] || 0; + } + struct[2] = (+struct[2] || 1) - 1; + struct[3] = +struct[3] || 1; + if (struct[8] !== 'Z' && struct[9] !== undefined) { + minutesOffset = struct[10] * 60 + struct[11]; + if (struct[9] === '+') { + minutesOffset = 0 - minutesOffset; + } + } + timestamp = + Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]); + } + else { + timestamp = Date.parse(date); + } + return timestamp; +} +//# sourceMappingURL=date.js.map \ No newline at end of file diff --git a/lib/type-r/record/attributes/date.js.map b/lib/type-r/record/attributes/date.js.map new file mode 100644 index 0000000..2c2b09a --- /dev/null +++ b/lib/type-r/record/attributes/date.js.map @@ -0,0 +1 @@ +{"version":3,"file":"date.js","sourceRoot":"","sources":["../../../../src/type-r/record/attributes/date.ts"],"names":[],"mappings":";AAMA,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAA;AAI/B,OAAO,EAAE,sBAAsB,EAAE,MAAM,WAAW,CAAA;AAElD,IAAM,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;AAIjC;IAA8B,oCAAO;IAArC;;IA6CA,CAAC;IA5CG,yBAAM,GAAN;QACI,OAAO,IAAI,IAAI,EAAE,CAAC;IACtB,CAAC;IAED,0BAAO,GAAP,UAAS,IAAU,EAAE,CAAC,EAAE,MAAM;QAC1B,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI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1C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAE,CAAC,GAAG,WAAW,CAAE,CAAC,CAAE,CAAE,EAAE,EAAE,CAAC,EAAG;YAC/C,MAAM,CAAE,CAAC,CAAE,GAAG,CAAC,MAAM,CAAE,CAAC,CAAE,IAAI,CAAC,CAAC;SACnC;QAGD,MAAM,CAAE,CAAC,CAAE,GAAG,CAAC,CAAC,MAAM,CAAE,CAAC,CAAE,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;QACtC,MAAM,CAAE,CAAC,CAAE,GAAG,CAAC,MAAM,CAAE,CAAC,CAAE,IAAI,CAAC,CAAC;QAEhC,IAAI,MAAM,CAAE,CAAC,CAAE,KAAK,GAAG,IAAI,MAAM,CAAE,CAAC,CAAE,KAAK,SAAS,EAAG;YACnD,aAAa,GAAG,MAAM,CAAE,EAAE,CAAE,GAAG,EAAE,GAAG,MAAM,CAAE,EAAE,CAAE,CAAC;YAEjD,IAAI,MAAM,CAAE,CAAC,CAAE,KAAK,GAAG,EAAG;gBACtB,aAAa,GAAG,CAAC,GAAG,aAAa,CAAC;aACrC;SACJ;QAED,SAAS;YACL,IAAI,CAAC,GAAG,CAAE,MAAM,CAAE,CAAC,CAAE,EAAE,MAAM,CAAE,CAAC,CAAE,EAAE,MAAM,CAAE,CAAC,CAAE,EAAE,MAAM,CAAE,CAAC,CAAE,EAAE,MAAM,CAAE,CAAC,CAAE,GAAG,aAAa,EAAE,MAAM,CAAE,CAAC,CAAE,EAC9F,MAAM,CAAE,CAAC,CAAE,CAAE,CAAC;KAC7B;SACI;QACD,SAAS,GAAG,IAAI,CAAC,KAAK,CAAE,IAAI,CAAE,CAAC;KAClC;IAED,OAAO,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/lib/type-r/record/attributes/index.d.ts b/lib/type-r/record/attributes/index.d.ts new file mode 100644 index 0000000..256e999 --- /dev/null +++ b/lib/type-r/record/attributes/index.d.ts @@ -0,0 +1,26 @@ +import { eventsApi } from '../../object-plus'; +export * from './any'; +export * from './owned'; +export * from './date'; +export * from './basic'; +export * from './shared'; +export * from './updates'; +export * from './attrDef'; +import { AnyType } from './any'; +import { ConstructorsMixin } from './updates'; +import { IOEndpoint } from '../../io-tools'; +export interface RecordAttributesMixin extends ConstructorsMixin { + _attributes: AttributeDescriptors; + _attributesArray: AnyType[]; + properties: PropertyDescriptorMap; + _localEvents?: eventsApi.EventMap; + _endpoints: { + [name: string]: IOEndpoint; + }; +} +export interface AttributeDescriptors { + [name: string]: AnyType; +} +export default function (attributesDefinition: object, baseClassAttributes: AttributeDescriptors): RecordAttributesMixin; +export declare function createAttribute(spec: any, name: string): AnyType; +export declare function createSharedTypeSpec(Constructor: Function, Attribute: typeof AnyType): void; diff --git a/lib/type-r/record/attributes/index.js b/lib/type-r/record/attributes/index.js new file mode 100644 index 0000000..c43ff9d --- /dev/null +++ b/lib/type-r/record/attributes/index.js @@ -0,0 +1,63 @@ +import * as tslib_1 from "tslib"; +import { tools as _, eventsApi } from '../../object-plus'; +export * from './any'; +export * from './owned'; +export * from './date'; +export * from './basic'; +export * from './shared'; +export * from './updates'; +export * from './attrDef'; +import { AnyType } from './any'; +import { constructorsMixin } from './updates'; +import { ChainableAttributeSpec } from './attrDef'; +import { CompiledReference } from '../../traversable'; +export default function (attributesDefinition, baseClassAttributes) { + var myAttributes = _.transform({}, attributesDefinition, createAttribute), allAttributes = _.defaults({}, myAttributes, baseClassAttributes); + var ConstructorsMixin = constructorsMixin(allAttributes); + return tslib_1.__assign({}, ConstructorsMixin, { _attributes: new ConstructorsMixin.AttributesCopy(allAttributes), _attributesArray: Object.keys(allAttributes).map(function (key) { return allAttributes[key]; }), properties: _.transform({}, myAttributes, function (x) { return x.createPropertyDescriptor(); }) }, localEventsMixin(myAttributes), { _endpoints: _.transform({}, allAttributes, function (attrDef) { return attrDef.options.endpoint; }) }); +} +export function createAttribute(spec, name) { + return AnyType.create(ChainableAttributeSpec.from(spec).options, name); +} +export function createSharedTypeSpec(Constructor, Attribute) { + if (!Constructor.hasOwnProperty('shared')) { + Object.defineProperty(Constructor, 'shared', { + get: function () { + return new ChainableAttributeSpec({ + value: null, + type: Constructor, + _attribute: Attribute + }); + } + }); + } +} +function localEventsMixin(attrSpecs) { + var _localEvents; + for (var key in attrSpecs) { + var attribute = attrSpecs[key], _onChange = attribute.options._onChange; + if (_onChange) { + _localEvents || (_localEvents = new eventsApi.EventMap()); + _localEvents.addEvent('change:' + key, typeof _onChange === 'string' ? + createWatcherFromRef(_onChange, key) : + wrapWatcher(_onChange, key)); + } + } + return _localEvents ? { _localEvents: _localEvents } : {}; +} +function wrapWatcher(watcher, key) { + return function (record, value) { + watcher.call(record, value, key); + }; +} +function createWatcherFromRef(ref, key) { + var _a = new CompiledReference(ref, true), local = _a.local, resolve = _a.resolve, tail = _a.tail; + return local ? + function (record, value) { + record[tail](value, key); + } : + function (record, value) { + resolve(record)[tail](value, key); + }; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib/type-r/record/attributes/index.js.map b/lib/type-r/record/attributes/index.js.map new file mode 100644 index 0000000..4047447 --- /dev/null +++ b/lib/type-r/record/attributes/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/type-r/record/attributes/index.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,KAAK,IAAI,CAAC,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAA;AAEzD,cAAc,OAAO,CAAA;AACrB,cAAc,SAAS,CAAA;AACvB,cAAc,QAAQ,CAAA;AACtB,cAAc,SAAS,CAAA;AACvB,cAAc,UAAU,CAAA;AACxB,cAAc,WAAW,CAAA;AACzB,cAAc,WAAW,CAAA;AAEzB,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAA;AAC/B,OAAO,EAAqB,iBAAiB,EAAE,MAAM,WAAW,CAAA;AAChE,OAAO,EAAE,sBAAsB,EAAE,MAAM,WAAW,CAAA;AAClD,OAAO,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AU,MAAM,EAAE,KAAK;YACnB,OAAO,CAAE,MAAM,CAAE,CAAE,IAAI,CAAE,CAAE,KAAK,EAAE,GAAG,CAAE,CAAC;QAC5C,CAAC,CAAA;AACT,CAAC"} \ No newline at end of file diff --git a/lib/type-r/record/attributes/owned.d.ts b/lib/type-r/record/attributes/owned.d.ts new file mode 100644 index 0000000..78bd0c7 --- /dev/null +++ b/lib/type-r/record/attributes/owned.d.ts @@ -0,0 +1,18 @@ +import { AnyType } from './any'; +import { Transactional, TransactionOptions } from '../../transactions'; +import { AttributesContainer, ConstructorOptions } from './updates'; +import { ValidationError } from '../../validation'; +export declare class AggregatedType extends AnyType { + type: typeof Transactional; + clone(value: Transactional): Transactional; + toJSON(x: any, key: string, options: object): any; + doInit(value: any, record: AttributesContainer, options: ConstructorOptions): any; + doUpdate(value: any, record: any, options: any, nested: any[]): boolean; + canBeUpdated(prev: Transactional, next: any, options: TransactionOptions): any; + convert(next: any, prev: any, record: AttributesContainer, options: TransactionOptions): Transactional; + dispose(record: AttributesContainer, value: Transactional): void; + validate(record: AttributesContainer, value: Transactional): ValidationError; + create(): Transactional; + initialize(options: any): void; + _handleChange(next: Transactional, prev: Transactional, record: AttributesContainer, options: TransactionOptions): void; +} diff --git a/lib/type-r/record/attributes/owned.js b/lib/type-r/record/attributes/owned.js new file mode 100644 index 0000000..ac7b8c5 --- /dev/null +++ b/lib/type-r/record/attributes/owned.js @@ -0,0 +1,96 @@ +import * as tslib_1 from "tslib"; +import { AnyType } from './any'; +import { transactionApi, ItemsBehavior } from '../../transactions'; +var free = transactionApi.free, aquire = transactionApi.aquire; +var AggregatedType = (function (_super) { + tslib_1.__extends(AggregatedType, _super); + function AggregatedType() { + return _super !== null && _super.apply(this, arguments) || this; + } + AggregatedType.prototype.clone = function (value) { + return value ? value.clone() : value; + }; + AggregatedType.prototype.toJSON = function (x, key, options) { return x && x.toJSON(options); }; + AggregatedType.prototype.doInit = function (value, record, options) { + var v = options.clone ? this.clone(value) : (value === void 0 ? this.defaultValue() : value); + var x = this.transform(v, void 0, record, options); + this.handleChange(x, void 0, record, options); + return x; + }; + AggregatedType.prototype.doUpdate = function (value, record, options, nested) { + var key = this.name, attributes = record.attributes; + var prev = attributes[key]; + var update; + if (update = this.canBeUpdated(prev, value, options)) { + var nestedTransaction = prev._createTransaction(update, options); + if (nestedTransaction) { + if (nested) { + nested.push(nestedTransaction); + } + else { + nestedTransaction.commit(record); + } + if (this.propagateChanges) + return true; + } + return false; + } + var next = this.transform(value, prev, record, options); + attributes[key] = next; + if (this.isChanged(next, prev)) { + this.handleChange(next, prev, record, options); + return true; + } + return false; + }; + AggregatedType.prototype.canBeUpdated = function (prev, next, options) { + if (prev && next != null) { + if (next instanceof this.type) { + if (options.merge) + return next.__inner_state__; + } + else { + return next; + } + } + }; + AggregatedType.prototype.convert = function (next, prev, record, options) { + if (next == null) + return next; + if (next instanceof this.type) { + if (next._shared && !(next._shared & ItemsBehavior.persistent)) { + this._log('error', 'aggregated collection attribute is assigned with shared collection', next, record); + } + return options.merge ? next.clone() : next; + } + return this.type.create(next, options); + }; + AggregatedType.prototype.dispose = function (record, value) { + if (value) { + this.handleChange(void 0, value, record, {}); + } + }; + AggregatedType.prototype.validate = function (record, value) { + var error = value && value.validationError; + if (error) + return error; + }; + AggregatedType.prototype.create = function () { + return this.type.create(); + }; + AggregatedType.prototype.initialize = function (options) { + options.changeHandlers.unshift(this._handleChange); + }; + AggregatedType.prototype._handleChange = function (next, prev, record, options) { + if (prev) { + free(record, prev); + options.unset || prev.dispose(); + } + if (next && !aquire(record, next, this.name)) { + this._log('error', 'aggregated attribute assigned with object already having an owner', next, record); + } + }; + return AggregatedType; +}(AnyType)); +export { AggregatedType }; +//# sourceMappingURL=owned.js.map \ No newline at end of file diff --git a/lib/type-r/record/attributes/owned.js.map b/lib/type-r/record/attributes/owned.js.map new file mode 100644 index 0000000..f194824 --- /dev/null +++ b/lib/type-r/record/attributes/owned.js.map @@ -0,0 +1 @@ +{"version":3,"file":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AAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,CAAE,EAAE;YAC5C,IAAI,CAAC,IAAI,CAAE,OAAO,EAAE,mEAAmE,EAAE,IAAI,EAAE,MAAM,CAAE,CAAC;SAC3G;IACL,CAAC;IACL,qBAAC;AAAD,CAAC,AAjHD,CAAoC,OAAO,GAiH1C"} \ No newline at end of file diff --git a/lib/type-r/record/attributes/shared.d.ts b/lib/type-r/record/attributes/shared.d.ts new file mode 100644 index 0000000..2632212 --- /dev/null +++ b/lib/type-r/record/attributes/shared.d.ts @@ -0,0 +1,18 @@ +import { AnyType } from './any'; +import { AttributesContainer, ConstructorOptions } from './updates'; +import { Transactional, TransactionOptions } from '../../transactions'; +export declare class SharedType extends AnyType { + type: typeof Transactional; + doInit(value: any, record: AttributesContainer, options: ConstructorOptions): any; + doUpdate(value: any, record: any, options: any, nested: any[]): boolean; + clone(value: Transactional, record: AttributesContainer): Transactional; + toJSON(): void; + canBeUpdated(prev: Transactional, next: any, options: TransactionOptions): any; + convert(next: any, prev: any, record: AttributesContainer, options: TransactionOptions): Transactional; + validate(model: any, value: any, name: any): void; + create(): Transactional; + _handleChange(next: Transactional, prev: Transactional, record: AttributesContainer, options: any): void; + dispose(record: AttributesContainer, value: Transactional): void; + _onChange: (child: Transactional, options: TransactionOptions, initiator: Transactional) => void; + initialize(options: any): void; +} diff --git a/lib/type-r/record/attributes/shared.js b/lib/type-r/record/attributes/shared.js new file mode 100644 index 0000000..db297e6 --- /dev/null +++ b/lib/type-r/record/attributes/shared.js @@ -0,0 +1,100 @@ +import * as tslib_1 from "tslib"; +import { AnyType } from './any'; +import { ItemsBehavior, transactionApi } from '../../transactions'; +import { eventsApi } from '../../object-plus'; +var on = eventsApi.on, off = eventsApi.off, free = transactionApi.free, aquire = transactionApi.aquire; +var shareAndListen = ItemsBehavior.listen | ItemsBehavior.share; +var SharedType = (function (_super) { + tslib_1.__extends(SharedType, _super); + function SharedType() { + return _super !== null && _super.apply(this, arguments) || this; + } + SharedType.prototype.doInit = function (value, record, options) { + var v = options.clone ? this.clone(value, record) : (value === void 0 ? this.defaultValue() : value); + var x = this.transform(v, void 0, record, options); + this.handleChange(x, void 0, record, options); + return x; + }; + SharedType.prototype.doUpdate = function (value, record, options, nested) { + var key = this.name, attributes = record.attributes; + var prev = attributes[key]; + var update; + if (update = this.canBeUpdated(prev, value, options)) { + var nestedTransaction = prev._createTransaction(update, options); + if (nestedTransaction) { + if (nested) { + nested.push(nestedTransaction); + } + else { + nestedTransaction.commit(record); + } + if (this.propagateChanges) + return true; + } + return false; + } + var next = this.transform(value, prev, record, options); + attributes[key] = next; + if (this.isChanged(next, prev)) { + this.handleChange(next, prev, record, options); + return true; + } + return false; + }; + SharedType.prototype.clone = function (value, record) { + if (!value || value._owner !== record) + return value; + var clone = value.clone(); + aquire(record, clone, this.name); + return clone; + }; + SharedType.prototype.toJSON = function () { }; + SharedType.prototype.canBeUpdated = function (prev, next, options) { + if (prev && next != null && !(next instanceof this.type)) { + return next; + } + }; + SharedType.prototype.convert = function (next, prev, record, options) { + if (next == null || next instanceof this.type) + return next; + var implicitObject = new this.type(next, options, shareAndListen); + aquire(record, implicitObject, this.name); + return implicitObject; + }; + SharedType.prototype.validate = function (model, value, name) { }; + SharedType.prototype.create = function () { + return null; + }; + SharedType.prototype._handleChange = function (next, prev, record, options) { + if (prev) { + if (prev._owner === record) { + free(record, prev); + options.unset || prev.dispose(); + } + else { + off(prev, prev._changeEventName, this._onChange, record); + } + } + if (next) { + if (next._owner !== record) { + on(next, next._changeEventName, this._onChange, record); + } + } + }; + SharedType.prototype.dispose = function (record, value) { + if (value) { + this.handleChange(void 0, value, record, {}); + } + }; + SharedType.prototype.initialize = function (options) { + var attribute = this; + this._onChange = this.propagateChanges ? function (child, options, initiator) { + this === initiator || this.forceAttributeChange(attribute.name, options); + } : ignore; + options.changeHandlers.unshift(this._handleChange); + }; + return SharedType; +}(AnyType)); +export { SharedType }; +function ignore() { } +//# sourceMappingURL=shared.js.map \ No newline at end of file diff --git a/lib/type-r/record/attributes/shared.js.map b/lib/type-r/record/attributes/shared.js.map new file mode 100644 index 0000000..ef248a5 --- /dev/null +++ b/lib/type-r/record/attributes/shared.js.map @@ -0,0 +1 @@ +{"version":3,"file":"shared.js","sourceRoot":"","sources":["../../../../src/type-r/record/attributes/shared.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAA;AAE/B,OAAO,EAAE,aAAa,EAAS,cAAc,EAAqC,MAAM,oBAAoB,CAAA;AAC5G,OAAO,EAAS,SAAS,EAAE,MAAM,mBAAmB,CAAA;AAE5C,IAAA,iBAAE,EAAE,mBAAG,EACT,0BAAI,EAAE,8BAAM,CAAoB;AAUtC,IAAM,cAAc,GAAG,aAAa,CAAC,MAAM,GAAG,aAAa,CAAC,KAAK,CAAC;AAGlE;IAAgC,sCAAO;IAAvC;;IA8HA,CAAC;IA3HI,2BAAM,GAAN,UAAQ,KAAK,EAAE,MAA4B,EAAE,OAA4B;QACtE,IAAM,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAE,KAAK,EAAE,MAAM,CAAE,CAAC,CAAC,CAAC,CACpD,KAAK,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,KAAK,CACjD,CAAC;QAEF,IAAM,CAAC,GAAG,IAAI,CAAC,SAAS,CAAE,CAAC,EAAE,KAAK,CAAC,EAAE,MAAM,EAAE,OAAO,CAAE,CAAC;QACvD,IAAI,CAAC,YAAY,CAAE,CAAC,EAAE,KAAK,CAAC,EAAE,MAAM,EAAE,OAAO,CAAE,CAAC;QAChD,OAAO,CAAC,CAAC;IACb,CAAC;IAED,6BAAQ,GAAR,UAAU,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAc;QACtC,IAAA,GAAG,GAAG,IAAI,CAAC,IAAI,EAAI,8BAAU,CAAY;QAC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J;IACL,CAAC;IAED,4BAAO,GAAP,UAAS,MAA4B,EAAE,KAAqB;QACxD,IAAI,KAAK,EAAE;YACP,IAAI,CAAC,YAAY,CAAE,KAAK,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,CAAE,CAAC;SAClD;IACL,CAAC;IAID,+BAAU,GAAV,UAAY,OAAO;QAEf,IAAM,SAAS,GAAG,IAAI,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,gBAAgB,CAAC,CAAC,CAAC,UAAU,KAAK,EAAE,OAAO,EAAE,SAAS;YACxE,IAAI,KAAK,SAAS,IAAI,IAAI,CAAC,oBAAoB,CAAE,SAAS,CAAC,IAAI,EAAE,OAAO,CAAE,CAAC;QAC/E,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;QAEX,OAAO,CAAC,cAAc,CAAC,OAAO,CAAE,IAAI,CAAC,aAAa,CAAE,CAAC;IACzD,CAAC;IACL,iBAAC;AAAD,CAAC,AA9HD,CAAgC,OAAO,GA8HtC;;AAED,SAAS,MAAM,KAAG,CAAC"} \ No newline at end of file diff --git a/lib/type-r/record/attributes/updates.d.ts b/lib/type-r/record/attributes/updates.d.ts new file mode 100644 index 0000000..739f95d --- /dev/null +++ b/lib/type-r/record/attributes/updates.d.ts @@ -0,0 +1,42 @@ +import { Transactional, Transaction, TransactionOptions, Owner } from "../../transactions"; +export interface ConstructorsMixin { + Attributes: AttributesConstructor; + AttributesCopy: AttributesCopyConstructor; +} +export interface ConstructorOptions extends TransactionOptions { + clone?: boolean; +} +export declare type AttributesConstructor = new (record: AttributesContainer, values: object, options: TransactionOptions) => AttributesValues; +export declare type AttributesCopyConstructor = new (values: object) => AttributesValues; +export interface AttributesContainer extends Transactional, Owner, ConstructorsMixin { + _attributes: AttributesDescriptors; + attributes: AttributesValues; + _previousAttributes: AttributesValues; + _changedAttributes: AttributesValues; +} +export interface AttributesValues { + [name: string]: any; +} +export interface AttributesDescriptors { + [name: string]: AttributeUpdatePipeline; +} +export interface AttributeUpdatePipeline { + doUpdate(value: any, record: AttributesContainer, options: TransactionOptions, nested?: Transaction[]): boolean; +} +export declare function setAttribute(record: AttributesContainer, name: string, value: any): void; +export declare const UpdateRecordMixin: { + transaction(this: AttributesContainer, fun: (self: AttributesContainer) => void, options?: TransactionOptions): void; + _onChildrenChange(child: Transactional, options: TransactionOptions): void; + forceAttributeChange(key: string, options?: TransactionOptions): void; + _createTransaction(this: AttributesContainer, a_values: {}, options?: TransactionOptions): Transaction; +}; +export declare function constructorsMixin(attrDefs: AttributesDescriptors): ConstructorsMixin; +export declare function shouldBeAnObject(record: AttributesContainer, values: object): boolean; +export declare class RecordTransaction implements Transaction { + object: AttributesContainer; + isRoot: boolean; + nested: Transaction[]; + changes: string[]; + constructor(object: AttributesContainer, isRoot: boolean, nested: Transaction[], changes: string[]); + commit(initiator?: AttributesContainer): void; +} diff --git a/lib/type-r/record/attributes/updates.js b/lib/type-r/record/attributes/updates.js new file mode 100644 index 0000000..492d465 --- /dev/null +++ b/lib/type-r/record/attributes/updates.js @@ -0,0 +1,114 @@ +import { transactionApi } from "../../transactions"; +var _begin = transactionApi.begin, _markAsDirty = transactionApi.markAsDirty, commit = transactionApi.commit; +import { eventsApi } from '../../object-plus'; +var trigger3 = eventsApi.trigger3; +export function setAttribute(record, name, value) { + var isRoot = begin(record), options = {}; + if (record._attributes[name].doUpdate(value, record, options)) { + markAsDirty(record, options); + trigger3(record, 'change:' + name, record, record.attributes[name], options); + } + isRoot && commit(record); +} +function begin(record) { + if (_begin(record)) { + record._previousAttributes = new record.AttributesCopy(record.attributes); + record._changedAttributes = null; + return true; + } + return false; +} +function markAsDirty(record, options) { + if (record._changedAttributes) { + record._changedAttributes = null; + } + return _markAsDirty(record, options); +} +export var UpdateRecordMixin = { + transaction: function (fun, options) { + if (options === void 0) { options = {}; } + var isRoot = begin(this); + fun.call(this, this); + isRoot && commit(this); + }, + _onChildrenChange: function (child, options) { + var _ownerKey = child._ownerKey, attribute = this._attributes[_ownerKey]; + if (!attribute || attribute.propagateChanges) + this.forceAttributeChange(_ownerKey, options); + }, + forceAttributeChange: function (key, options) { + if (options === void 0) { options = {}; } + var isRoot = begin(this); + if (markAsDirty(this, options)) { + trigger3(this, 'change:' + key, this, this.attributes[key], options); + } + isRoot && commit(this); + }, + _createTransaction: function (a_values, options) { + if (options === void 0) { options = {}; } + var isRoot = begin(this), changes = [], nested = [], _attributes = this._attributes, values = options.parse ? this.parse(a_values, options) : a_values; + var unknown; + if (shouldBeAnObject(this, values)) { + for (var name_1 in values) { + var spec = _attributes[name_1]; + if (spec) { + if (spec.doUpdate(values[name_1], this, options, nested)) { + changes.push(name_1); + } + } + else { + unknown || (unknown = []); + unknown.push("'" + name_1 + "'"); + } + } + if (unknown) { + } + } + if (changes.length && markAsDirty(this, options)) { + return new RecordTransaction(this, isRoot, nested, changes); + } + for (var _i = 0, nested_1 = nested; _i < nested_1.length; _i++) { + var pendingTransaction = nested_1[_i]; + pendingTransaction.commit(this); + } + isRoot && commit(this); + } +}; +export function constructorsMixin(attrDefs) { + var attrs = Object.keys(attrDefs); + var AttributesCopy = new Function('values', "\n " + attrs.map(function (attr) { return "\n this." + attr + " = values." + attr + ";\n "; }).join('') + "\n "); + AttributesCopy.prototype = Object.prototype; + var Attributes = new Function('record', 'values', 'options', "\n var _attrs = record._attributes;\n\n " + attrs.map(function (attr) { return "\n this." + attr + " = _attrs." + attr + ".doInit( values." + attr + ", record, options );\n "; }).join('') + "\n "); + Attributes.prototype = Object.prototype; + return { Attributes: Attributes, AttributesCopy: AttributesCopy }; +} +export function shouldBeAnObject(record, values) { + if (values && values.constructor === Object) + return true; + record._log('warn', 'update with non-object is ignored!', { values: values }); + return false; +} +var RecordTransaction = (function () { + function RecordTransaction(object, isRoot, nested, changes) { + this.object = object; + this.isRoot = isRoot; + this.nested = nested; + this.changes = changes; + } + RecordTransaction.prototype.commit = function (initiator) { + var _a = this, nested = _a.nested, object = _a.object, changes = _a.changes; + for (var _i = 0, nested_2 = nested; _i < nested_2.length; _i++) { + var transaction = nested_2[_i]; + transaction.commit(object); + } + var attributes = object.attributes, _isDirty = object._isDirty; + for (var _b = 0, changes_1 = changes; _b < changes_1.length; _b++) { + var key = changes_1[_b]; + trigger3(object, 'change:' + key, object, attributes[key], _isDirty); + } + this.isRoot && commit(object, initiator); + }; + return RecordTransaction; +}()); +export { RecordTransaction }; +//# sourceMappingURL=updates.js.map \ No newline at end of file diff --git a/lib/type-r/record/attributes/updates.js.map b/lib/type-r/record/attributes/updates.js.map new file mode 100644 index 0000000..36937e2 --- /dev/null +++ b/lib/type-r/record/attributes/updates.js.map @@ -0,0 +1 @@ +{"version":3,"file":"updates.js","sourceRoot":"","sources":["../../../../src/type-r/record/attributes/updates.ts"],"names":[],"mappings":"AAAA,OAAO,EAAyD,cAAc,EAAE,MAAM,oBAAoB,CAAA;AAClG,IAAA,6BAAc,EAAE,yCAA0B,EAAE,8BAAM,CAAoB;AAE9E,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAA;AACrC,IAAA,6BAAQ,CAAe;AA0C/B,MAAM,UAAU,YAAY,CAAE,MAA4B,EAAE,IAAa,EAAE,KAAW;IAElF,IAAM,MAAM,GAAI,KAAK,CAAE,MAAM,CAAE,EACzB,OAAO,GAAG,EAAE,CAAC;IAGnB,IAAI,MAAM,CAAC,WAAW,CAAE,IAAI,CAAE,CAAC,QAAQ,CAAE,KAAK,EAAE,MAAM,EAAE,OAAO,CAAE,EAAE;QAE/D,WAAW,CAAE,MAAM,EAAE,OAAO,CAAE,CAAC;QAC/B,QAAQ,CAAE,MAAM,EAAE,SAAS,GAAG,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,UAAU,CAAE,IAAI,CAAE,EAAE,OAAO,CAAE,CAAC;KACpF;IAGD,MAAM,IAAI,MAAM,CAAE,MAAM,CAAE,CAAC;AAC/B,CAAC;AAED,SAAS,KAAK,CAAE,MAA4B;IACxC,IAAI,MAAM,CAAE,MAAM,CAAE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AAM,GAAN,MAAM,CAAsB;QAC5B,WAAM,GAAN,MAAM,CAAU;QAChB,WAAM,GAAN,MAAM,CAAgB;QACtB,YAAO,GAAP,OAAO,CAAW;IAAG,CAAC;IAG1C,kCAAM,GAAN,UAAQ,SAAgC;QAC9B,IAAA,SAAkC,EAAhC,kBAAM,EAAE,kBAAM,EAAE,oBAAO,CAAU;QAGzC,KAAwB,UAAM,EAAN,iBAAM,EAAN,oBAAM,EAAN,IAAM,EAAE;YAA3B,IAAI,WAAW,eAAA;YAChB,WAAW,CAAC,MAAM,CAAE,MAAM,CAAE,CAAC;SAChC;QAIO,IAAA,8BAAU,EAAE,0BAAQ,CAAY;QACxC,KAAgB,UAAO,EAAP,mBAAO,EAAP,qBAAO,EAAP,IAAO,EAAE;YAApB,IAAI,GAAG,gBAAA;YACR,QAAQ,CAAE,MAAM,EAAE,SAAS,GAAG,GAAG,EAAE,MAAM,EAAE,UAAU,CAAE,GAAG,CAAE,EAAE,QAAQ,CAAE,CAAC;SAC5E;QAED,IAAI,CAAC,MAAM,IAAI,MAAM,CAAE,MAAM,EAAE,SAAS,CAAE,CAAC;IAC/C,CAAC;IACL,wBAAC;AAAD,CAAC,AAzBD,IAyBC"} \ No newline at end of file diff --git a/lib/type-r/record/index.d.ts b/lib/type-r/record/index.d.ts new file mode 100644 index 0000000..33f3a15 --- /dev/null +++ b/lib/type-r/record/index.d.ts @@ -0,0 +1,6 @@ +import { Record } from './record'; +export * from './attributes'; +export { Record }; +export declare function attr(proto: object, attrName: string): void; +export declare function attr(spec: any): PropertyDecorator; +export declare function prop(spec: any): any; diff --git a/lib/type-r/record/index.js b/lib/type-r/record/index.js new file mode 100644 index 0000000..84b886e --- /dev/null +++ b/lib/type-r/record/index.js @@ -0,0 +1,71 @@ +import * as tslib_1 from "tslib"; +import { Record } from './record'; +import { tools, predefine } from '../object-plus'; +import compile, { ChainableAttributeSpec } from './attributes'; +import { Transactional } from '../transactions'; +import { createSharedTypeSpec, AggregatedType, SharedType } from './attributes'; +export * from './attributes'; +export { Record }; +var assign = tools.assign, defaults = tools.defaults, omit = tools.omit, getBaseClass = tools.getBaseClass; +Record.onExtend = function (BaseClass) { + Transactional.onExtend.call(this, BaseClass); + var Class = this; + var DefaultCollection = (function (_super) { + tslib_1.__extends(DefaultCollection, _super); + function DefaultCollection() { + return _super !== null && _super.apply(this, arguments) || this; + } + DefaultCollection.model = Class; + DefaultCollection = tslib_1.__decorate([ + predefine + ], DefaultCollection); + return DefaultCollection; + }(BaseClass.Collection)); + this.DefaultCollection = DefaultCollection; + if (Class.Collection === BaseClass.Collection) { + this.Collection = DefaultCollection; + } + createSharedTypeSpec(this, SharedType); +}; +Record.onDefine = function (definition, BaseClass) { + var baseProto = BaseClass.prototype; + var _a = compile(this.attributes = getAttributes(definition), baseProto._attributes), properties = _a.properties, _localEvents = _a._localEvents, dynamicMixin = tslib_1.__rest(_a, ["properties", "_localEvents"]); + assign(this.prototype, dynamicMixin); + definition.properties = defaults(definition.properties || {}, properties); + definition._localEvents = _localEvents; + Transactional.onDefine.call(this, definition, BaseClass); + this.DefaultCollection.define(definition.collection || {}); + this.Collection = definition.Collection; + this.Collection.prototype.model = this; + if (definition.endpoint) + this.Collection.prototype._endpoint = definition.endpoint; +}; +Record._attribute = AggregatedType; +createSharedTypeSpec(Record, SharedType); +function getAttributes(_a) { + var defaults = _a.defaults, attributes = _a.attributes, idAttribute = _a.idAttribute; + var definition = attributes || defaults || {}; + if (idAttribute && !(idAttribute in definition)) { + definition[idAttribute] = void 0; + } + return definition; +} +export function attr(proto, attrName) { + if (attrName) { + if (typeof Reflect !== 'undefined' && Reflect.getMetadata) { + Reflect + .getMetadata("design:type", proto, attrName) + .asProp(proto, attrName); + } + else { + proto._log('error', 'Add import "reflect-metadata"; as the first line of your app.'); + } + } + else { + return ChainableAttributeSpec.from(proto).asProp; + } +} +export function prop(spec) { + return spec.asProp; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib/type-r/record/index.js.map b/lib/type-r/record/index.js.map new file mode 100644 index 0000000..6c07e74 --- /dev/null +++ b/lib/type-r/record/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/type-r/record/index.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,MAAM,EAAoB,MAAM,UAAU,CAAA;AACnD,OAAO,EAAW,KAAK,EAAE,SAAS,EAAuB,MAAM,gBAAgB,CAAA;AAC/E,OAAO,OAAO,EAAE,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAA;AAC9D,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAE/C,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAA0C,UAAU,EAAE,MAAM,cAAc,CAAA;AAEvH,cAAc,cAAc,CAAA;AAC5B,OAAO,EAAE,MAAM,EAAE,CAAA;AAET,IAAA,qBAAM,EAAE,yBAAQ,EAAE,iBAAI,EAAE,iCAAY,CAAW;AAEvD,MAAM,CAAC,QAAQ,GAAG,UAAgC,SAAyB;IACvE,aAAa,CAAC,QAAQ,CAAC,IAAI,CAAE,IAAI,EAAE,SAAS,CAAE,CAAC;IAG/C,IAAM,KAAK,GAAG,IAAI,CAAC;IAER;QAAgC,6CAAyB;QAAzD;;QAEX,CAAC;QADU,uBAAK,GAAG,KAAK,CAAC;QADR,iBAAiB;YAAjC,SAAS;WAAO,iBAAiB,CAEjC;QAAD,wBAAC;KAAA,AAFU,CAAgC,SAAS,CAAC,UAAU,GAE9D;IAED,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;IAI3C,IAAI,KAAK,CAAC,UAAU,KAAK,SAAS,CAAC,UAAU,EAAE;QAC3C,IAAI,CAAC,UAAU,GAAG,iBAAiB,CAAC;KACvC;IAGD,oBAAoB,CAAE,IAAI,EAAE,UAAU,CAAE,CAAC;AAC7C,CAAC,CAAA;AAED,MAAM,CAAC,QAAQ,GAAG,UAAU,UAA6B,EAAE,SAAyB;IAChF,IAAM,SAAS,GAAY,S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AO,CAAC,WAAW,EAAE;YACvD,OAAO;iBACF,WAAW,CAAE,aAAa,EAAE,KAAK,EAAE,QAAQ,CAAE;iBAC7C,MAAM,CAAE,KAAK,EAAE,QAAQ,CAAE,CAAC;SAClC;aACG;YACA,KAAK,CAAC,IAAI,CAAE,OAAO,EAAE,+DAA+D,CAAE,CAAC;SAC1F;KACJ;SACG;QACA,OAAO,sBAAsB,CAAC,IAAI,CAAE,KAAK,CAAE,CAAC,MAAM,CAAC;KACtD;AACL,CAAC;AAED,MAAM,UAAU,IAAI,CAAE,IAAI;IACtB,OAAO,IAAI,CAAC,MAAM,CAAC;AACvB,CAAC"} \ No newline at end of file diff --git a/lib/type-r/record/io-mixin.d.ts b/lib/type-r/record/io-mixin.d.ts new file mode 100644 index 0000000..5bf8351 --- /dev/null +++ b/lib/type-r/record/io-mixin.d.ts @@ -0,0 +1,16 @@ +import { IOOptions, IOEndpoint, IOPromise, IONode } from '../io-tools'; +export interface IORecord extends IONode { + getEndpoint(): IOEndpoint; + save(options?: IOOptions): IOPromise; + fetch(options?: IOOptions): IOPromise; + destroy(options?: IOOptions): IOPromise; + toJSON(options?: object): any; + isNew(): boolean; + id: string | number; + set(json: object, options: object): any; +} +export declare const IORecordMixin: { + save(this: IORecord, options?: IOOptions): IOPromise; + fetch(options?: IOOptions): IOPromise; + destroy(options?: IOOptions): IOPromise; +}; diff --git a/lib/type-r/record/io-mixin.js b/lib/type-r/record/io-mixin.js new file mode 100644 index 0000000..513fc83 --- /dev/null +++ b/lib/type-r/record/io-mixin.js @@ -0,0 +1,34 @@ +import * as tslib_1 from "tslib"; +import { startIO } from '../io-tools'; +export var IORecordMixin = { + save: function (options) { + var _this = this; + if (options === void 0) { options = {}; } + var endpoint = this.getEndpoint(), json = this.toJSON(options); + return startIO(this, this.isNew() ? + endpoint.create(json, options, this) : + endpoint.update(this.id, json, options, this), options, function (update) { + _this.set(update, tslib_1.__assign({ parse: true }, options)); + }); + }, + fetch: function (options) { + var _this = this; + if (options === void 0) { options = {}; } + return startIO(this, this.getEndpoint().read(this.id, options, this), options, function (json) { return _this.set(json, tslib_1.__assign({ parse: true }, options)); }); + }, + destroy: function (options) { + var _this = this; + if (options === void 0) { options = {}; } + return startIO(this, this.getEndpoint().destroy(this.id, options, this), options, function () { + var collection = _this.collection; + if (collection) { + collection.remove(_this, options); + } + else { + _this.dispose(); + } + return _this; + }); + } +}; +//# sourceMappingURL=io-mixin.js.map \ No newline at end of file diff --git a/lib/type-r/record/io-mixin.js.map b/lib/type-r/record/io-mixin.js.map new file mode 100644 index 0000000..d9f0a9d --- /dev/null +++ b/lib/type-r/record/io-mixin.js.map @@ -0,0 +1 @@ +{"version":3,"file":"io-mixin.js","sourceRoot":"","sources":["../../../src/type-r/record/io-mixin.ts"],"names":[],"mappings":";AAAA,OAAO,EAAoB,OAAO,EAA4C,MAAM,aAAa,CAAA;AAajG,MAAM,CAAC,IAAM,aAAa,GAAG;IACzB,IAAI,YAAmB,OAAwB;QAA/C,iBAeC;QAfsB,wBAAA,EAAA,YAAwB;QAC3C,IAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,EAAE,EAC7B,IAAI,GAAG,IAAI,CAAC,MAAM,CAAE,OAAO,CAAE,CAAC;QAEpC,OAAO,OAAO,CACV,IAAI,EACJ,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;YACV,QAAQ,CAAC,MAAM,CAAE,IAAI,EAAE,OAAO,EAAE,IAAI,CAAE,CAAC,CAAC;YACxC,QAAQ,CAAC,MAAM,CAAE,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,CAAE,EACnD,OAAO,EAEP,UAAA,MAAM;YACF,KAAI,CAAC,GAAG,CAAE,MAAM,qBAAI,KAAK,EAAG,IAAI,IAAK,OAAO,EAAI,CAAC;QACrD,CAAC,CACJ,CAAC;IACN,CAAC;IAED,KAAK,YAAE,OAAwB;QAA/B,iBAQC;QARM,wBAAA,EAAA,YAAwB;QAC3B,OAAO,OAAO,CACV,IAAI,EACJ,IAAI,CAAC,WAAW,EAAE,CAAC,IAAI,CAAE,IAAI,CAAC,EAAE,EAAE,OAAO,EAAE,IAAI,CAAE,EACjD,OAAO,EAEP,UAAA,IAAI,IAAI,OAAA,KAAI,CAAC,GAAG,CAAE,IAAI,qBAAI,KAAK,EAAG,IAAI,IAAK,OAAO,EAAI,EAA9C,CAA8C,CACzD,CAAC;IACN,CAAC;IAED,OAAO,YAAE,OAAwB;QAAjC,iBAkBC;QAlBQ,wBAAA,EAAA,YAAwB;QAC7B,OAAO,OAAO,CACV,IAAI,EACJ,IAAI,CAAC,WAAW,EAAE,CAAC,OAAO,CAAE,IAAI,CAAC,EAAE,EAAE,OAAO,EAAE,IAAI,CAAE,EACpD,OAAO,EAEP;YACY,IAAA,6BAAU,CAAU;YAC5B,IAAI,UAAU,EAAE;gBACZ,UAAU,CAAC,MAAM,CAAE,KAAI,EAAE,OAAO,CAAE,CAAC;aACtC;iBACG;gBACA,KAAI,CAAC,OAAO,EAAE,CAAC;aAClB;YAED,OAAO,KAAI,CAAC;QAChB,CAAC,CACJ,CAAA;IACL,CAAC;CACJ,CAAA"} \ No newline at end of file diff --git a/lib/type-r/record/record.d.ts b/lib/type-r/record/record.d.ts new file mode 100644 index 0000000..f59ea42 --- /dev/null +++ b/lib/type-r/record/record.d.ts @@ -0,0 +1,73 @@ +import { tools } from '../object-plus'; +import { CloneOptions, Transactional, TransactionalDefinition, Transaction, TransactionOptions, Owner } from '../transactions'; +import { ChildrenErrors } from '../validation'; +import { Collection } from '../collection'; +import { AnyType, AttributesValues, AttributesContainer, AttributesConstructor, AttributesCopyConstructor } from './attributes'; +import { IORecord } from './io-mixin'; +import { IOPromise, IOEndpoint } from '../io-tools'; +export interface ConstructorOptions extends TransactionOptions { + clone?: boolean; +} +export interface RecordDefinition extends TransactionalDefinition { + idAttribute?: string; + attributes?: AttributesValues; + collection?: object; + Collection?: typeof Transactional; +} +export declare class Record extends Transactional implements IORecord, AttributesContainer { + static onDefine(definition: any, BaseClass: any): void; + static Collection: typeof Collection; + static DefaultCollection: typeof Collection; + static from: (collectionReference: any) => any; + static defaults(attrs: AttributesValues): typeof Record; + static attributes: AttributesValues; + _endpoints: { + [name: string]: IOEndpoint; + }; + save(options?: object): IOPromise; + destroy(options?: object): IOPromise; + _previousAttributes: {}; + previousAttributes(): AttributesValues; + attributes: AttributesValues; + readonly __inner_state__: AttributesValues; + _changedAttributes: AttributesValues; + readonly changed: AttributesValues; + changedAttributes(diff?: {}): boolean | {}; + hasChanged(key?: string): boolean; + previous(key: string): any; + isNew(): boolean; + has(key: string): boolean; + unset(key: string, options?: any): any; + clear(options?: any): this; + getOwner(): Owner; + idAttribute: string; + id: string | number; + _attributes: { + [key: string]: AnyType; + }; + _attributesArray: AnyType[]; + Attributes: AttributesConstructor; + AttributesCopy: AttributesCopyConstructor; + forEachAttr(attrs: {}, iteratee: (value: any, key?: string, spec?: AnyType) => void): void; + each(iteratee: (value?: any, key?: string) => void, context?: any): void; + keys(): string[]; + values(): any[]; + defaults(values?: {}): {}; + constructor(a_values?: {}, a_options?: ConstructorOptions); + initialize(values?: any, options?: any): void; + clone(options?: CloneOptions): this; + deepClone(): this; + _validateNested(errors: ChildrenErrors): number; + get(key: string): any; + toJSON(options?: object): any; + parse(data: any, options?: TransactionOptions): any; + _parse(data: any): any; + deepSet(name: string, value: any, options?: any): this; + readonly collection: any; + dispose(): void; + _log(level: tools.LogLevel, text: string, props: object): void; + getClassName(): string; + _createTransaction(values: object, options: TransactionOptions): Transaction; + forceAttributeChange: (key: string, options: TransactionOptions) => void; + _onChildrenChange: (child: Transactional, options: TransactionOptions) => void; +} diff --git a/lib/type-r/record/record.js b/lib/type-r/record/record.js new file mode 100644 index 0000000..e96e9b7 --- /dev/null +++ b/lib/type-r/record/record.js @@ -0,0 +1,309 @@ +import * as tslib_1 from "tslib"; +import { tools, definitions, mixinRules, define } from '../object-plus'; +import { Transactional } from '../transactions'; +import { AnyType, AggregatedType, setAttribute, UpdateRecordMixin } from './attributes'; +import { IORecordMixin } from './io-mixin'; +var assign = tools.assign, isEmpty = tools.isEmpty, log = tools.log; +var _cidCounter = 0; +var Record = (function (_super) { + tslib_1.__extends(Record, _super); + function Record(a_values, a_options) { + var _this = _super.call(this, _cidCounter++) || this; + _this.attributes = {}; + var options = a_options || {}, values = (options.parse ? _this.parse(a_values, options) : a_values) || {}; + if (log.level > 1) + typeCheck(_this, values); + _this._previousAttributes = _this.attributes = new _this.Attributes(_this, values, options); + _this.initialize(a_values, a_options); + if (_this._localEvents) + _this._localEvents.subscribe(_this, _this); + return _this; + } + Record_1 = Record; + Record.onDefine = function (definition, BaseClass) { }; + Record.defaults = function (attrs) { + return this.extend({ attributes: attrs }); + }; + Record.prototype.save = function (options) { throw new Error('Implemented by mixin'); }; + Record.prototype.destroy = function (options) { throw new Error('Implemented by mixin'); }; + Record.prototype.previousAttributes = function () { return new this.AttributesCopy(this._previousAttributes); }; + Object.defineProperty(Record.prototype, "__inner_state__", { + get: function () { return this.attributes; }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Record.prototype, "changed", { + get: function () { + var changed = this._changedAttributes; + if (!changed) { + var prev = this._previousAttributes; + changed = {}; + var _a = this, _attributes = _a._attributes, attributes = _a.attributes; + for (var _i = 0, _b = this._attributesArray; _i < _b.length; _i++) { + var attr = _b[_i]; + var key = attr.name, value = attributes[key]; + if (attr.isChanged(value, prev[key])) { + changed[key] = value; + } + } + this._changedAttributes = changed; + } + return changed; + }, + enumerable: true, + configurable: true + }); + Record.prototype.changedAttributes = function (diff) { + if (!diff) + return this.hasChanged() ? assign({}, this.changed) : false; + var val, changed = false, old = this._transaction ? this._previousAttributes : this.attributes, attrSpecs = this._attributes; + for (var attr in diff) { + if (!attrSpecs[attr].isChanged(old[attr], (val = diff[attr]))) + continue; + (changed || (changed = {}))[attr] = val; + } + return changed; + }; + Record.prototype.hasChanged = function (key) { + var _previousAttributes = this._previousAttributes; + if (!_previousAttributes) + return false; + return key ? + this._attributes[key].isChanged(this.attributes[key], _previousAttributes[key]) : + !isEmpty(this.changed); + }; + Record.prototype.previous = function (key) { + if (key) { + var _previousAttributes = this._previousAttributes; + if (_previousAttributes) + return _previousAttributes[key]; + } + return null; + }; + Record.prototype.isNew = function () { + return this.id == null; + }; + Record.prototype.has = function (key) { + return this[key] != void 0; + }; + Record.prototype.unset = function (key, options) { + var _a; + var value = this[key]; + this.set((_a = {}, _a[key] = void 0, _a), tslib_1.__assign({ unset: true }, options)); + return value; + }; + Record.prototype.clear = function (options) { + var _this = this; + var nullify = options && options.nullify; + this.transaction(function () { + _this.forEachAttr(_this.attributes, function (value, key) { return _this[key] = nullify ? null : void 0; }); + }, options); + return this; + }; + Record.prototype.getOwner = function () { + var owner = this._owner; + return this._ownerKey ? owner : owner && owner._owner; + }; + Object.defineProperty(Record.prototype, "id", { + get: function () { return this.attributes[this.idAttribute]; }, + set: function (x) { setAttribute(this, this.idAttribute, x); }, + enumerable: true, + configurable: true + }); + Record.prototype.forEachAttr = function (attrs, iteratee) { + var _attributes = this._attributes; + var unknown; + for (var name_1 in attrs) { + var spec = _attributes[name_1]; + if (spec) { + iteratee(attrs[name_1], name_1, spec); + } + else { + unknown || (unknown = []); + unknown.push("'" + name_1 + "'"); + } + } + if (unknown) { + this._log('warn', "attributes " + unknown.join(', ') + " are not defined", { + attributes: attrs + }); + } + }; + Record.prototype.each = function (iteratee, context) { + var fun = context !== void 0 ? function (v, k) { return iteratee.call(context, v, k); } : iteratee, attributes = this.attributes; + for (var key in this.attributes) { + var value = attributes[key]; + if (value !== void 0) + fun(value, key); + } + }; + Record.prototype.keys = function () { + var keys = []; + this.each(function (value, key) { return value === void 0 || keys.push(key); }); + return keys; + }; + Record.prototype.values = function () { + return this.map(function (value) { return value; }); + }; + Record.prototype.defaults = function (values) { + if (values === void 0) { values = {}; } + var defaults = {}, _attributesArray = this._attributesArray; + for (var _i = 0, _attributesArray_1 = _attributesArray; _i < _attributesArray_1.length; _i++) { + var attr = _attributesArray_1[_i]; + var key = attr.name, value = values[key]; + defaults[key] = value === void 0 ? attr.defaultValue() : value; + } + return defaults; + }; + Record.prototype.initialize = function (values, options) { }; + Record.prototype.clone = function (options) { + if (options === void 0) { options = {}; } + var copy = new this.constructor(this.attributes, { clone: true }); + if (options.pinStore) + copy._defaultStore = this.getStore(); + return copy; + }; + Record.prototype.deepClone = function () { return this.clone(); }; + ; + Record.prototype._validateNested = function (errors) { + var _this = this; + var length = 0; + this.forEachAttr(this.attributes, function (value, name, attribute) { + var error = attribute.validate(_this, value, name); + if (error) { + errors[name] = error; + length++; + } + }); + return length; + }; + Record.prototype.get = function (key) { + return this[key]; + }; + Record.prototype.toJSON = function (options) { + var _this = this; + var json = {}; + this.forEachAttr(this.attributes, function (value, key, _a) { + var toJSON = _a.toJSON; + if (value !== void 0) { + var asJson = toJSON.call(_this, value, key, options); + if (asJson !== void 0) + json[key] = asJson; + } + }); + return json; + }; + Record.prototype.parse = function (data, options) { + return data; + }; + Record.prototype._parse = function (data) { return data; }; + Record.prototype.deepSet = function (name, value, options) { + var _this = this; + this.transaction(function () { + var _a; + var path = name.split('.'), l = path.length - 1, attr = path[l]; + var model = _this; + for (var i = 0; i < l; i++) { + var key = path[i]; + var next = model.get ? model.get(key) : model[key]; + if (!next) { + var attrSpecs = model._attributes; + if (attrSpecs) { + var newModel = attrSpecs[key].create(); + if (options && options.nullify && newModel._attributes) { + newModel.clear(options); + } + model[key] = next = newModel; + } + else + return; + } + model = next; + } + if (model.set) { + model.set((_a = {}, _a[attr] = value, _a), options); + } + else { + model[attr] = value; + } + }); + return this; + }; + Object.defineProperty(Record.prototype, "collection", { + get: function () { + return this._ownerKey ? null : this._owner; + }, + enumerable: true, + configurable: true + }); + Record.prototype.dispose = function () { + var _this = this; + if (this._disposed) + return; + this.forEachAttr(this.attributes, function (value, key, attribute) { + attribute.dispose(_this, value); + }); + _super.prototype.dispose.call(this); + }; + Record.prototype._log = function (level, text, props) { + tools.log(level, '[Record] ' + text, tslib_1.__assign({ 'Record': this, 'Attributes definition:': this._attributes }, props)); + }; + Record.prototype.getClassName = function () { + return _super.prototype.getClassName.call(this) || 'Record'; + }; + Record.prototype._createTransaction = function (values, options) { return void 0; }; + var Record_1; + Record = Record_1 = tslib_1.__decorate([ + define({ + cidPrefix: 'm', + _changeEventName: 'change', + idAttribute: 'id' + }), + definitions({ + defaults: mixinRules.merge, + attributes: mixinRules.merge, + collection: mixinRules.merge, + Collection: mixinRules.value, + idAttribute: mixinRules.protoValue + }) + ], Record); + return Record; +}(Transactional)); +export { Record }; +; +assign(Record.prototype, UpdateRecordMixin, IORecordMixin); +var BaseRecordAttributes = (function () { + function BaseRecordAttributes(record, x, options) { + this.id = x.id; + } + return BaseRecordAttributes; +}()); +Record.prototype.Attributes = BaseRecordAttributes; +var BaseRecordAttributesCopy = (function () { + function BaseRecordAttributesCopy(x) { + this.id = x.id; + } + return BaseRecordAttributesCopy; +}()); +Record.prototype.AttributesCopy = BaseRecordAttributesCopy; +var IdAttribute = AnyType.create({ value: void 0 }, 'id'); +Record.prototype._attributes = { id: IdAttribute }; +Record.prototype._attributesArray = [IdAttribute]; +Record._attribute = AggregatedType; +import { shouldBeAnObject } from './attributes'; +function typeCheck(record, values) { + if (shouldBeAnObject(record, values)) { + var _attributes = record._attributes; + var unknown = void 0; + for (var name_2 in values) { + if (!_attributes[name_2]) { + unknown || (unknown = []); + unknown.push("'" + name_2 + "'"); + } + } + if (unknown) { + record._log('warn', "undefined attributes " + unknown.join(', ') + " are ignored.", { values: values }); + } + } +} +//# sourceMappingURL=record.js.map \ No newline at end of file diff --git a/lib/type-r/record/record.js.map b/lib/type-r/record/record.js.map new file mode 100644 index 0000000..0091207 --- /dev/null +++ b/lib/type-r/record/record.js.map @@ -0,0 +1 @@ +{"version":3,"file":"record.js","sourceRoot":"","sources":["../../../src/type-r/record/record.ts"],"names":[],"mappings":";AAKA,OAAO,EAAE,KAAK,EAAsB,WAAW,EAAW,UAAU,EAAE,MAAM,EAAE,MAA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file diff --git a/lib/type-r/relations/commons.d.ts b/lib/type-r/relations/commons.d.ts new file mode 100644 index 0000000..d084b9f --- /dev/null +++ b/lib/type-r/relations/commons.d.ts @@ -0,0 +1,4 @@ +import { Collection } from '../collection'; +import { Record } from '../record'; +export declare type CollectionReference = (() => Collection) | Collection | string; +export declare function parseReference(collectionRef: CollectionReference): (root: Record) => Collection; diff --git a/lib/type-r/relations/commons.js b/lib/type-r/relations/commons.js new file mode 100644 index 0000000..98a9ef8 --- /dev/null +++ b/lib/type-r/relations/commons.js @@ -0,0 +1,13 @@ +import { CompiledReference } from '../traversable'; +export function parseReference(collectionRef) { + switch (typeof collectionRef) { + case 'function': + return function (root) { return collectionRef.call(root); }; + case 'object': + return function () { return collectionRef; }; + case 'string': + var resolve = new CompiledReference(collectionRef).resolve; + return resolve; + } +} +//# sourceMappingURL=commons.js.map \ No newline at end of file diff --git a/lib/type-r/relations/commons.js.map b/lib/type-r/relations/commons.js.map new file mode 100644 index 0000000..b2349ff --- /dev/null +++ b/lib/type-r/relations/commons.js.map @@ -0,0 +1 @@ +{"version":3,"file":"commons.js","sourceRoot":"","sources":["../../../src/type-r/relations/commons.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAA;AAKlD,MAAM,UAAU,cAAc,CAAE,aAAmC;IAC/D,QAAQ,OAAO,aAAa,EAAE;QAC1B,KAAK,UAAU;YACX,OAAO,UAAA,IAAI,IAAI,OAAM,aAAc,CAAC,IAAI,CAAE,IAAI,CAAE,EAAjC,CAAiC,CAAC;QACrD,KAAK,QAAQ;YACT,OAAO,cAAM,OAAY,aAAa,EAAzB,CAAyB,CAAC;QAC3C,KAAK,QAAQ;YACD,IAAA,sDAAO,CAAoD;YACnE,OAAO,OAAO,CAAC;KACtB;AACL,CAAC"} \ No newline at end of file diff --git a/lib/type-r/relations/from.d.ts b/lib/type-r/relations/from.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/lib/type-r/relations/from.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/type-r/relations/from.js b/lib/type-r/relations/from.js new file mode 100644 index 0000000..81f3d21 --- /dev/null +++ b/lib/type-r/relations/from.js @@ -0,0 +1,44 @@ +import * as tslib_1 from "tslib"; +import { AnyType } from '../record'; +import { parseReference } from './commons'; +import { Record } from '../record'; +import { ChainableAttributeSpec } from '../record'; +var RecordRefType = (function (_super) { + tslib_1.__extends(RecordRefType, _super); + function RecordRefType() { + return _super !== null && _super.apply(this, arguments) || this; + } + RecordRefType.prototype.toJSON = function (value) { + return value && typeof value === 'object' ? value.id : value; + }; + RecordRefType.prototype.clone = function (value) { + return value && typeof value === 'object' ? value.id : value; + }; + RecordRefType.prototype.isChanged = function (a, b) { + var aId = a && (a.id == null ? a : a.id), bId = b && (b.id == null ? b : b.id); + return aId !== bId; + }; + RecordRefType.prototype.validate = function (model, value, name) { }; + return RecordRefType; +}(AnyType)); +Record.from = function from(masterCollection) { + var getMasterCollection = parseReference(masterCollection); + var typeSpec = new ChainableAttributeSpec({ + value: null, + _attribute: RecordRefType + }); + return typeSpec + .get(function (objOrId, name) { + if (typeof objOrId === 'object') + return objOrId; + var collection = getMasterCollection(this); + var record = null; + if (collection && collection.length) { + record = collection.get(objOrId) || null; + this.attributes[name] = record; + record && this._attributes[name].handleChange(record, null, this, {}); + } + return record; + }); +}; +//# sourceMappingURL=from.js.map \ No newline at end of file diff --git a/lib/type-r/relations/from.js.map b/lib/type-r/relations/from.js.map new file mode 100644 index 0000000..9826c37 --- /dev/null +++ b/lib/type-r/relations/from.js.map @@ -0,0 +1 @@ +{"version":3,"file":"from.js","sourceRoot":"","sources":["../../../src/type-r/relations/from.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,OAAO,EAAoB,MAAM,WAAW,CAAA;AACrD,OAAO,EAAE,cAAc,EAAuB,MAAM,WAAW,CAAA;AAE/D,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAA;AAElC,OAAO,EAAE,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O,OAAO,CAAC;QAGjD,IAAM,UAAU,GAAG,mBAAmB,CAAE,IAAI,CAAE,CAAC;QAC/C,IAAM,MAAM,GAAY,IAAI,CAAC;QAG7B,IAAI,UAAU,IAAI,UAAU,CAAC,MAAM,EAAE;YAEjC,MAAM,GAAG,UAAU,CAAC,GAAG,CAAE,OAAO,CAAE,IAAI,IAAI,CAAC;YAC3C,IAAI,CAAC,UAAU,CAAE,IAAI,CAAE,GAAG,MAAM,CAAC;YAGjC,MAAM,IAAI,IAAI,CAAC,WAAW,CAAE,IAAI,CAAE,CAAC,YAAY,CAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAE,CAAC;SAC7E;QAED,OAAO,MAAM,CAAC;IAClB,CAAC,CAAC,CAAC;AACX,CAAC,CAAC"} \ No newline at end of file diff --git a/lib/type-r/relations/index.d.ts b/lib/type-r/relations/index.d.ts new file mode 100644 index 0000000..343753e --- /dev/null +++ b/lib/type-r/relations/index.d.ts @@ -0,0 +1,3 @@ +import './from'; +import './subsetOf'; +export * from './store'; diff --git a/lib/type-r/relations/index.js b/lib/type-r/relations/index.js new file mode 100644 index 0000000..acc8e13 --- /dev/null +++ b/lib/type-r/relations/index.js @@ -0,0 +1,4 @@ +import './from'; +import './subsetOf'; +export * from './store'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib/type-r/relations/index.js.map b/lib/type-r/relations/index.js.map new file mode 100644 index 0000000..5981e4b --- /dev/null +++ b/lib/type-r/relations/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/type-r/relations/index.ts"],"names":[],"mappings":"AAAA,OAAO,QAAQ,CAAA;AACf,OAAO,YAAY,CAAA;AAEnB,cAAc,SAAS,CAAA"} \ No newline at end of file diff --git a/lib/type-r/relations/store.d.ts b/lib/type-r/relations/store.d.ts new file mode 100644 index 0000000..5f854c2 --- /dev/null +++ b/lib/type-r/relations/store.d.ts @@ -0,0 +1,6 @@ +import { Record } from '../record'; +export declare class Store extends Record { + getStore(): Store; + get(name: string): any; + static global: Store; +} diff --git a/lib/type-r/relations/store.js b/lib/type-r/relations/store.js new file mode 100644 index 0000000..916cce1 --- /dev/null +++ b/lib/type-r/relations/store.js @@ -0,0 +1,32 @@ +import * as tslib_1 from "tslib"; +import { Record } from '../record'; +import { Transactional } from '../transactions'; +var _store = null; +var Store = (function (_super) { + tslib_1.__extends(Store, _super); + function Store() { + return _super !== null && _super.apply(this, arguments) || this; + } + Store.prototype.getStore = function () { return this; }; + Store.prototype.get = function (name) { + var local = this[name]; + if (local || this === this._defaultStore) + return local; + return this._owner ? this._owner.get(name) : this._defaultStore.get(name); + }; + Object.defineProperty(Store, "global", { + get: function () { return _store; }, + set: function (store) { + if (_store) { + _store.dispose(); + } + Transactional.prototype._defaultStore = _store = store; + }, + enumerable: true, + configurable: true + }); + return Store; +}(Record)); +export { Store }; +Store.global = new Store(); +//# sourceMappingURL=store.js.map \ No newline at end of file diff --git a/lib/type-r/relations/store.js.map b/lib/type-r/relations/store.js.map new file mode 100644 index 0000000..b5ac480 --- /dev/null +++ b/lib/type-r/relations/store.js.map @@ -0,0 +1 @@ +{"version":3,"file":"store.js","sourceRoot":"","sources":["../../../src/type-r/relations/store.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAA;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAG/C,IAAI,MAAM,GAAW,IAAI,CAAC;AAE1B;IAA2B,iCAAM;IAAjC;;IAuBA,CAAC;IAtBG,wBAAQ,GAAR,cAAqB,OAAO,IAAI,CAAC,CAAC,CAAC;IAGnC,mBAAG,GAAH,UAAK,IAAa;QAEd,IAAI,KAAK,GAAG,IAAI,CAAE,IAAI,CAAE,CAAC;QAGzB,IAAI,KAAK,IAAI,IAAI,KAAK,IAAI,CAAC,aAAa;YAAG,OAAO,KAAK,CAAC;QAGxD,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAE,IAAI,CAAE,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAE,IAAI,CAAE,CAAC;IAClF,CAAC;IAED,sBAAW,eAAM;aAAjB,cAAqB,OAAO,MAAM,CAAC,CAAC,CAAC;aACrC,UAAmB,KAAa;YAC5B,IAAI,MAAM,EAAE;gBACV,MAAM,CAAC,OAAO,EAAE,CAAC;aAClB;YAED,aAAa,CAAC,SAAS,CAAC,aAAa,GAAG,MAAM,GAAG,KAAK,CAAC;QAC3D,CAAC;;;OAPoC;IAQzC,YAAC;AAAD,CAAC,AAvBD,CAA2B,MAAM,GAuBhC;;AAED,KAAK,CAAC,MAAM,GAAG,IAAI,KAAK,EAAE,CAAC"} \ No newline at end of file diff --git a/lib/type-r/relations/subsetOf.d.ts b/lib/type-r/relations/subsetOf.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/lib/type-r/relations/subsetOf.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/type-r/relations/subsetOf.js b/lib/type-r/relations/subsetOf.js new file mode 100644 index 0000000..1c6f15b --- /dev/null +++ b/lib/type-r/relations/subsetOf.js @@ -0,0 +1,144 @@ +import * as tslib_1 from "tslib"; +import { Collection } from '../collection'; +import { tools, define } from '../object-plus'; +import { parseReference } from './commons'; +import { ChainableAttributeSpec } from '../record'; +import { ItemsBehavior, transactionApi } from '../transactions'; +var fastDefaults = tools.fastDefaults; +Collection.subsetOf = function subsetOf(masterCollection) { + var SubsetOf = this._SubsetOf || (this._SubsetOf = defineSubsetCollection(this)), getMasterCollection = parseReference(masterCollection), typeSpec = new ChainableAttributeSpec({ + type: SubsetOf + }); + return typeSpec.get(function (refs) { + !refs || refs.resolvedWith || refs.resolve(getMasterCollection(this)); + return refs; + }); +}; +var subsetOfBehavior = ItemsBehavior.share | ItemsBehavior.persistent; +function defineSubsetCollection(CollectionConstructor) { + var SubsetOfCollection = (function (_super) { + tslib_1.__extends(SubsetOfCollection, _super); + function SubsetOfCollection(recordsOrIds, options) { + var _this = _super.call(this, [], options, subsetOfBehavior) || this; + _this.resolvedWith = null; + _this.refs = toArray(recordsOrIds); + return _this; + } + Object.defineProperty(SubsetOfCollection.prototype, "__inner_state__", { + get: function () { return this.refs || this.models; }, + enumerable: true, + configurable: true + }); + SubsetOfCollection.prototype.add = function (a_elements, options) { + if (options === void 0) { options = {}; } + var resolvedWith = this.resolvedWith, toAdd = toArray(a_elements); + if (resolvedWith) { + return _super.prototype.add.call(this, resolveRefs(resolvedWith, toAdd), options); + } + else { + if (toAdd.length) { + var isRoot = transactionApi.begin(this); + this.refs = this.refs ? this.refs.concat(toAdd) : toAdd.slice(); + transactionApi.markAsDirty(this, options); + isRoot && transactionApi.commit(this); + } + } + }; + SubsetOfCollection.prototype.reset = function (a_elements, options) { + if (options === void 0) { options = {}; } + var resolvedWith = this.resolvedWith, elements = toArray(a_elements); + return resolvedWith ? + _super.prototype.reset.call(this, resolveRefs(resolvedWith, elements), options) : + delaySet(this, elements, options) || []; + }; + SubsetOfCollection.prototype._createTransaction = function (a_elements, options) { + var resolvedWith = this.resolvedWith, elements = toArray(a_elements); + return resolvedWith ? + _super.prototype._createTransaction.call(this, resolveRefs(resolvedWith, elements), options) : + delaySet(this, elements, options); + }; + SubsetOfCollection.prototype.toJSON = function () { + return this.refs ? + this.refs.map(function (objOrId) { return objOrId.id || objOrId; }) : + this.models.map(function (model) { return model.id; }); + }; + SubsetOfCollection.prototype._validateNested = function () { return 0; }; + Object.defineProperty(SubsetOfCollection.prototype, "length", { + get: function () { + return this.models.length || (this.refs ? this.refs.length : 0); + }, + enumerable: true, + configurable: true + }); + SubsetOfCollection.prototype.clone = function (owner) { + var Ctor = this.constructor, copy = new Ctor([], { + model: this.model, + comparator: this.comparator + }); + if (this.resolvedWith) { + copy.resolvedWith = this.resolvedWith; + copy.refs = null; + copy.reset(this.models, { silent: true }); + } + else { + copy.refs = this.refs.slice(); + } + return copy; + }; + SubsetOfCollection.prototype.parse = function (raw) { + return raw; + }; + SubsetOfCollection.prototype.resolve = function (collection) { + if (collection && collection.length) { + this.resolvedWith = collection; + if (this.refs) { + this.reset(this.refs, { silent: true }); + this.refs = null; + } + } + return this; + }; + SubsetOfCollection.prototype.getModelIds = function () { return this.toJSON(); }; + SubsetOfCollection.prototype.toggle = function (modelOrId, val) { + return _super.prototype.toggle.call(this, this.resolvedWith.get(modelOrId), val); + }; + SubsetOfCollection.prototype.addAll = function () { + if (this.resolvedWith) { + this.set(this.resolvedWith.models); + return this.models; + } + throw new Error("Cannot add elemens because the subset collection is not resolved yet."); + }; + SubsetOfCollection.prototype.toggleAll = function () { + return this.length ? this.reset() : this.addAll(); + }; + SubsetOfCollection = tslib_1.__decorate([ + define + ], SubsetOfCollection); + return SubsetOfCollection; + }(CollectionConstructor)); + SubsetOfCollection.prototype._itemEvents = void 0; + return SubsetOfCollection; +} +function resolveRefs(master, elements) { + var records = []; + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var el = elements_1[_i]; + var record = master.get(el); + if (record) + records.push(record); + } + return records; +} +function delaySet(collection, elements, options) { + if (tools.notEqual(collection.refs, elements)) { + var isRoot = transactionApi.begin(collection); + collection.refs = elements.slice(); + transactionApi.markAsDirty(collection, options); + isRoot && transactionApi.commit(collection); + } +} +function toArray(elements) { + return elements ? (Array.isArray(elements) ? elements : [elements]) : []; +} +//# sourceMappingURL=subsetOf.js.map \ No newline at end of file diff --git a/lib/type-r/relations/subsetOf.js.map b/lib/type-r/relations/subsetOf.js.map new file mode 100644 index 0000000..2b164d9 --- /dev/null +++ b/lib/type-r/relations/subsetOf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subsetOf.js","sourceRoot":"","sources":["../../../src/type-r/relations/subsetOf.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,UAAU,EAAqB,MAAM,eAAe,CAAA;AAC7D,OAAO,EAAE,KAAK,EAAa,MAAM,EAAE,MAAM,gBA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,SAAS,WAAW,CAAE,MAAM,EAAE,QAAQ;IAClC,IAAM,OAAO,GAAG,EAAE,CAAC;IAEnB,KAAe,UAAQ,EAAR,qBAAQ,EAAR,sBAAQ,EAAR,IAAQ,EAAE;QAApB,IAAI,EAAE,iBAAA;QACP,IAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAE,EAAE,CAAE,CAAC;QAChC,IAAI,MAAM;YAAG,OAAO,CAAC,IAAI,CAAE,MAAM,CAAE,CAAC;KACvC;IAED,OAAO,OAAO,CAAC;AACnB,CAAC;AAED,SAAS,QAAQ,CAAE,UAAU,EAAE,QAAQ,EAAE,OAAO;IAC5C,IAAI,KAAK,CAAC,QAAQ,CAAE,UAAU,CAAC,IAAI,EAAE,QAAQ,CAAE,EAAE;QAC7C,IAAM,MAAM,GAAG,cAAc,CAAC,KAAK,CAAE,UAAU,CAAE,CAAC;QAGlD,UAAU,CAAC,IAAI,GAAG,QAAQ,CAAC,KAAK,EAAE,CAAC;QAEnC,cAAc,CAAC,WAAW,CAAE,UAAU,EAAE,OAAO,CAAE,CAAC;QAGlD,MAAM,IAAI,cAAc,CAAC,MAAM,CAAE,UAAU,CAAE,CAAC;KACjD;AACL,CAAC;AAED,SAAS,OAAO,CAAE,QAAQ;IACtB,OAAO,QAAQ,CAAC,CAAC,CAAC,CACd,KAAK,CAAC,OAAO,CAAE,QAAQ,CAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAE,QAAQ,CAAE,CACtD,CAAC,CAAC,CAAC,EAAE,CAAC;AACX,CAAC"} \ No newline at end of file diff --git a/lib/type-r/transactions.d.ts b/lib/type-r/transactions.d.ts new file mode 100644 index 0000000..ebfc800 --- /dev/null +++ b/lib/type-r/transactions.d.ts @@ -0,0 +1,115 @@ +import { Messenger, CallbacksByEvents, MessengersByCid, MixinsState, MessengerDefinition, eventsApi } from './object-plus'; +import { ValidationError, Validatable, ChildrenErrors } from './validation'; +import { Traversable } from './traversable'; +import { IOEndpoint, IOPromise, IONode } from './io-tools'; +export interface TransactionalDefinition extends MessengerDefinition { + endpoint?: IOEndpoint; +} +export declare enum ItemsBehavior { + share = 1, + listen = 2, + persistent = 4 +} +export declare abstract class Transactional implements Messenger, IONode, Validatable, Traversable { + static endpoint: IOEndpoint; + static __super__: object; + static mixins: MixinsState; + static define: (definition?: TransactionalDefinition, statics?: object) => typeof Transactional; + static extend: (definition?: T, statics?: object) => any; + static onDefine(definitions: TransactionalDefinition, BaseClass: typeof Transactional): void; + static onExtend(BaseClass: typeof Transactional): void; + static create(a: any, b?: any): Transactional; + on: (events: string | CallbacksByEvents, callback: any, context?: any) => this; + once: (events: string | CallbacksByEvents, callback: any, context?: any) => this; + off: (events?: string | CallbacksByEvents, callback?: any, context?: any) => this; + trigger: (name: string, a?: any, b?: any, c?: any, d?: any, e?: any) => this; + stopListening: (source?: Messenger, a?: string | CallbacksByEvents, b?: Function) => this; + listenTo: (source: Messenger, a: string | CallbacksByEvents, b?: Function) => this; + listenToOnce: (source: Messenger, a: string | CallbacksByEvents, b?: Function) => this; + _disposed: boolean; + readonly __inner_state__: any; + _shared?: number; + dispose(): void; + initialize(): void; + _events: eventsApi.HandlersByEvent; + _listeningTo: MessengersByCid; + _localEvents: eventsApi.EventMap; + cid: string; + cidPrefix: string; + static shared: any; + _changeToken: {}; + _transaction: boolean; + _isDirty: TransactionOptions; + _owner: Owner; + _ownerKey: string; + _changeEventName: string; + onChanges(handler: Function, target?: Messenger): void; + offChanges(handler?: Function, target?: Messenger): void; + listenToChanges(target: Transactional, handler: any): void; + constructor(cid: string | number); + abstract clone(options?: CloneOptions): this; + transaction(fun: (self: this) => void, options?: TransactionOptions): void; + updateEach(iteratee: (val: any, key: string | number) => void, options?: TransactionOptions): void; + set(values: any, options?: TransactionOptions): this; + assignFrom(source: Transactional | Object): this; + abstract _createTransaction(values: any, options?: TransactionOptions): Transaction | void; + parse(data: any, options?: TransactionOptions): any; + abstract toJSON(options?: object): {}; + abstract get(key: string): any; + deepGet(reference: string): any; + getOwner(): Owner; + _defaultStore: Transactional; + getStore(): Transactional; + abstract each(iteratee: (val: any, key: string | number) => void, context?: any): any; + map(iteratee: (val: any, key: string | number) => T, context?: any): T[]; + _endpoint: IOEndpoint; + _ioPromise: IOPromise; + hasPendingIO(): IOPromise; + fetch(options?: object): IOPromise; + getEndpoint(): IOEndpoint; + mapObject(iteratee: (val: any, key: string | number) => T, context?: any): { + [key: string]: T; + }; + _validationError: ValidationError; + readonly validationError: ValidationError; + abstract _validateNested(errors: ChildrenErrors): number; + validate(obj?: Transactional): any; + getValidationError(key: string): any; + deepValidationError(reference: string): any; + eachValidationError(iteratee: (error: any, key: string, object: Transactional) => void): void; + isValid(key: string): boolean; + valueOf(): Object; + toString(): string; + getClassName(): string; + abstract _log(level: string, text: string, value: any): void; +} +export interface CloneOptions { + pinStore?: boolean; +} +export interface Owner extends Traversable, Messenger { + _onChildrenChange(child: Transactional, options: TransactionOptions): void; + getOwner(): Owner; + getStore(): Transactional; +} +export interface Transaction { + object: Transactional; + commit(initiator?: Transactional): any; +} +export interface TransactionOptions { + parse?: boolean; + silent?: boolean; + merge?: boolean; + remove?: boolean; + reset?: boolean; + unset?: boolean; + validate?: boolean; + ioUpdate?: boolean; + upsert?: boolean; +} +export declare const transactionApi: { + begin(object: Transactional): boolean; + markAsDirty(object: Transactional, options: TransactionOptions): boolean; + commit(object: Transactional, initiator?: Transactional): void; + aquire(owner: Owner, child: Transactional, key?: string): boolean; + free(owner: Owner, child: Transactional): void; +}; diff --git a/lib/type-r/transactions.js b/lib/type-r/transactions.js new file mode 100644 index 0000000..6dacfe9 --- /dev/null +++ b/lib/type-r/transactions.js @@ -0,0 +1,220 @@ +import * as tslib_1 from "tslib"; +import { Messenger, tools, mixins, mixinRules, definitions, eventsApi, define } from './object-plus'; +import { ValidationError } from './validation'; +import { resolveReference } from './traversable'; +import { abortIO } from './io-tools'; +var assign = tools.assign, trigger2 = eventsApi.trigger2, trigger3 = eventsApi.trigger3, on = eventsApi.on, off = eventsApi.off; +export var ItemsBehavior; +(function (ItemsBehavior) { + ItemsBehavior[ItemsBehavior["share"] = 1] = "share"; + ItemsBehavior[ItemsBehavior["listen"] = 2] = "listen"; + ItemsBehavior[ItemsBehavior["persistent"] = 4] = "persistent"; +})(ItemsBehavior || (ItemsBehavior = {})); +var Transactional = (function () { + function Transactional(cid) { + this._events = void 0; + this._changeToken = {}; + this._transaction = false; + this._isDirty = null; + this._owner = void 0; + this._ownerKey = void 0; + this._validationError = void 0; + this.cid = this.cidPrefix + cid; + } + Transactional_1 = Transactional; + Transactional.onDefine = function (definitions, BaseClass) { + if (definitions.endpoint) + this.prototype._endpoint = definitions.endpoint; + Messenger.onDefine.call(this, definitions, BaseClass); + }; + ; + Transactional.onExtend = function (BaseClass) { + if (BaseClass.create === this.create) { + this.create = Transactional_1.create; + } + }; + Transactional.create = function (a, b) { + return new this(a, b); + }; + Transactional.prototype.dispose = function () { + if (this._disposed) + return; + abortIO(this); + this._owner = void 0; + this._ownerKey = void 0; + this.off(); + this.stopListening(); + this._disposed = true; + }; + Transactional.prototype.initialize = function () { }; + Transactional.prototype.onChanges = function (handler, target) { + on(this, this._changeEventName, handler, target); + }; + Transactional.prototype.offChanges = function (handler, target) { + off(this, this._changeEventName, handler, target); + }; + Transactional.prototype.listenToChanges = function (target, handler) { + this.listenTo(target, target._changeEventName, handler); + }; + Transactional.prototype.transaction = function (fun, options) { + if (options === void 0) { options = {}; } + var isRoot = transactionApi.begin(this); + var update = fun.call(this, this); + update && this.set(update); + isRoot && transactionApi.commit(this); + }; + Transactional.prototype.updateEach = function (iteratee, options) { + var isRoot = transactionApi.begin(this); + this.each(iteratee); + isRoot && transactionApi.commit(this); + }; + Transactional.prototype.set = function (values, options) { + if (values) { + var transaction = this._createTransaction(values, options); + transaction && transaction.commit(); + } + return this; + }; + Transactional.prototype.assignFrom = function (source) { + var _this = this; + this.transaction(function () { + _this.set(source.__inner_state__ || source, { merge: true }); + var _changeToken = source._changeToken; + if (_changeToken) { + _this._changeToken = _changeToken; + } + }); + return this; + }; + Transactional.prototype.parse = function (data, options) { return data; }; + Transactional.prototype.deepGet = function (reference) { + return resolveReference(this, reference, function (object, key) { return object.get ? object.get(key) : object[key]; }); + }; + Transactional.prototype.getOwner = function () { + return this._owner; + }; + Transactional.prototype.getStore = function () { + var _owner = this._owner; + return _owner ? _owner.getStore() : this._defaultStore; + }; + Transactional.prototype.map = function (iteratee, context) { + var arr = [], fun = context !== void 0 ? function (v, k) { return iteratee.call(context, v, k); } : iteratee; + this.each(function (val, key) { + var result = fun(val, key); + if (result !== void 0) + arr.push(result); + }); + return arr; + }; + Transactional.prototype.hasPendingIO = function () { return this._ioPromise; }; + Transactional.prototype.fetch = function (options) { throw new Error("Not implemented"); }; + Transactional.prototype.getEndpoint = function () { + return getOwnerEndpoint(this) || this._endpoint; + }; + Transactional.prototype.mapObject = function (iteratee, context) { + var obj = {}, fun = context !== void 0 ? function (v, k) { return iteratee.call(context, v, k); } : iteratee; + this.each(function (val, key) { + var result = iteratee(val, key); + if (result !== void 0) + obj[key] = result; + }); + return obj; + }; + Object.defineProperty(Transactional.prototype, "validationError", { + get: function () { + var error = this._validationError || (this._validationError = new ValidationError(this)); + return error.length ? error : null; + }, + enumerable: true, + configurable: true + }); + Transactional.prototype.validate = function (obj) { }; + Transactional.prototype.getValidationError = function (key) { + var error = this.validationError; + return (key ? error && error.nested[key] : error) || null; + }; + Transactional.prototype.deepValidationError = function (reference) { + return resolveReference(this, reference, function (object, key) { return object.getValidationError(key); }); + }; + Transactional.prototype.eachValidationError = function (iteratee) { + var validationError = this.validationError; + validationError && validationError.eachError(iteratee, this); + }; + Transactional.prototype.isValid = function (key) { + return !this.getValidationError(key); + }; + Transactional.prototype.valueOf = function () { return this.cid; }; + Transactional.prototype.toString = function () { return this.cid; }; + Transactional.prototype.getClassName = function () { + var name = this.constructor.name; + if (name !== 'Subclass') + return name; + }; + var Transactional_1; + Transactional = Transactional_1 = tslib_1.__decorate([ + define, + definitions({ + endpoint: mixinRules.value + }), + mixins(Messenger) + ], Transactional); + return Transactional; +}()); +export { Transactional }; +export var transactionApi = { + begin: function (object) { + return object._transaction ? false : (object._transaction = true); + }, + markAsDirty: function (object, options) { + var dirty = !options.silent; + if (dirty) + object._isDirty = options; + object._changeToken = {}; + object._validationError = void 0; + return dirty; + }, + commit: function (object, initiator) { + var originalOptions = object._isDirty; + if (originalOptions) { + while (object._isDirty) { + var options = object._isDirty; + object._isDirty = null; + trigger3(object, object._changeEventName, object, options, initiator); + } + object._transaction = false; + var _owner = object._owner; + if (_owner && _owner !== initiator) { + _owner._onChildrenChange(object, originalOptions); + } + } + else { + object._isDirty = null; + object._transaction = false; + } + }, + aquire: function (owner, child, key) { + if (!child._owner) { + child._owner = owner; + child._ownerKey = key; + return true; + } + return child._owner === owner; + }, + free: function (owner, child) { + if (owner === child._owner) { + child._owner = void 0; + child._ownerKey = void 0; + } + } +}; +function getOwnerEndpoint(self) { + var collection = self.collection; + if (collection) { + return getOwnerEndpoint(collection); + } + if (self._owner) { + var _endpoints = self._owner._endpoints; + return _endpoints && _endpoints[self._ownerKey]; + } +} +//# sourceMappingURL=transactions.js.map \ No newline at end of file diff --git a/lib/type-r/transactions.js.map b/lib/type-r/transactions.js.map new file mode 100644 index 0000000..33482af --- /dev/null +++ b/lib/type-r/transactions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transactions.js","sourceRoot":"","sources":["../../src/type-r/transactions.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,SAAS,EAAyF,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAY,MAAM,eAAe,CAAA;AACrM,OAAO,EAAE,eAAe,EAA+B,MAAM,cAAc,CAAA;AAC3E,OAAO,EAAe,gBAAgB,EAAE,MAAM,eAAe,CAAA;AAC7D,OAAO,EAAiC,OAAO,EAAE,MAAM,YAAY,CAAA;AAE3D,IAAA,qBAAM,EACN,6BAAQ,EAAE,6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,MAAM,IAAI,MAAM,KAAW,SAAS,EAAE;gBACtC,MAAM,CAAC,iBAAiB,CAAE,MAAM,EAAE,eAAe,CAAE,CAAC;aACvD;SACJ;aACG;YAEA,MAAM,CAAC,QAAQ,GAAG,IAAI,CAAC;YACvB,MAAM,CAAC,YAAY,GAAG,KAAK,CAAC;SAC/B;IACL,CAAC;IAQD,MAAM,EAAN,UAAQ,KAAa,EAAE,KAAqB,EAAE,GAAa;QACvD,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE;YACf,KAAK,CAAC,MAAM,GAAG,KAAK,CAAC;YACrB,KAAK,CAAC,SAAS,GAAG,GAAG,CAAC;YACtB,OAAO,IAAI,CAAC;SACf;QAED,OAAO,KAAK,CAAC,MAAM,KAAK,KAAK,CAAC;IAClC,CAAC;IAID,IAAI,EAAJ,UAAM,KAAa,EAAE,KAAqB;QACtC,IAAI,KAAK,KAAK,KAAK,CAAC,MAAM,EAAE;YACxB,KAAK,CAAC,MAAM,GAAG,KAAK,CAAC,CAAC;YACtB,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC,CAAC;SAC5B;IACL,CAAC;CACJ,CAAA;AAED,SAAS,gBAAgB,CAAE,IAAoB;IAEnC,IAAA,4BAAU,CAAiB;IACnC,IAAI,UAAU,EAAE;QACZ,OAAO,gBAAgB,CAAE,UAAU,CAAE,CAAC;KACzC;IAGD,IAAI,IAAI,CAAC,MAAM,EAAE;QACL,IAAA,mCAAU,CAAwB;QAC1C,OAAO,UAAU,IAAI,UAAU,CAAE,IAAI,CAAC,SAAS,CAAE,CAAC;KACrD;AACL,CAAC"} \ No newline at end of file diff --git a/lib/type-r/traversable.d.ts b/lib/type-r/traversable.d.ts new file mode 100644 index 0000000..88d38eb --- /dev/null +++ b/lib/type-r/traversable.d.ts @@ -0,0 +1,13 @@ +export interface Traversable { + getStore(): Traversable; + getOwner(): Traversable; + get(key: string): any; +} +export declare type ResolveReference = (root: Traversable) => any; +export declare class CompiledReference { + resolve: ResolveReference; + tail: string; + local: boolean; + constructor(reference: string, splitTail?: boolean); +} +export declare function resolveReference(root: Traversable, reference: string, action: (object: any, key: string) => any): any; diff --git a/lib/type-r/traversable.js b/lib/type-r/traversable.js new file mode 100644 index 0000000..8dda18b --- /dev/null +++ b/lib/type-r/traversable.js @@ -0,0 +1,42 @@ +var referenceMask = /\^|(store\.[^.]+)|([^.]+)/g; +var CompiledReference = (function () { + function CompiledReference(reference, splitTail) { + if (splitTail === void 0) { splitTail = false; } + var path = reference + .match(referenceMask) + .map(function (key) { + if (key === '^' || key === 'owner') + return 'getOwner()'; + if (key[0] === '~') + return "getStore().get(\"" + key.substr(1) + "\")"; + if (key.indexOf('store.') === 0) + return "getStore().get(\"" + key.substr(6) + "\")"; + return key; + }); + this.tail = splitTail && path.pop(); + this.local = !path.length; + this.resolve = new Function('self', "\n var v = self." + path.shift() + ";\n \n " + path.map(function (x) { return "\n v = v && v." + x + ";\n "; }).join('') + "\n\n return v;\n "); + } + return CompiledReference; +}()); +export { CompiledReference }; +export function resolveReference(root, reference, action) { + var path = reference.match(referenceMask), skip = path.length - 1; + var self = root; + for (var i = 0; i < skip; i++) { + var key = path[i]; + switch (key) { + case '~': + self = self.getStore(); + break; + case '^': + self = self.getOwner(); + break; + default: self = self.get(key); + } + if (!self) + return; + } + return action(self, path[skip]); +} +//# sourceMappingURL=traversable.js.map \ No newline at end of file diff --git a/lib/type-r/traversable.js.map b/lib/type-r/traversable.js.map new file mode 100644 index 0000000..a1e5492 --- /dev/null +++ b/lib/type-r/traversable.js.map @@ -0,0 +1 @@ +{"version":3,"file":"traversable.js","sourceRoot":"","sources":["../../src/type-r/traversable.ts"],"names":[],"mappings":"AAcA,IAAM,aAAa,GAAI,4BAA4B,CAAC;AAKpD;IAKI,2BAAa,SAAkB,EAAE,SAA2B;QAA3B,0BAAA,EAAA,iBAA2B;QACxD,IAAM,IAAI,GAAG,SAAS;aACL,KAAK,CAAE,aAAa,CAAE;aACtB,GAAG,CAAE,UAAA,GAAG;Y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QAAQ,EAAE,CAAC;gBAAC,MAAM;YACzC,KAAK,GAAG;gBAAG,IAAI,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;gBAAC,MAAM;YACzC,OAAS,CAAC,CAAC,IAAI,GAAG,IAAI,CAAC,GAAG,CAAE,GAAG,CAAE,CAAC;SACrC;QAGD,IAAI,CAAC,IAAI;YAAG,OAAO;KACtB;IAED,OAAO,MAAM,CAAE,IAAI,EAAE,IAAI,CAAE,IAAI,CAAE,CAAE,CAAC;AACxC,CAAC"} \ No newline at end of file diff --git a/lib/type-r/validation.d.ts b/lib/type-r/validation.d.ts new file mode 100644 index 0000000..01ffb2f --- /dev/null +++ b/lib/type-r/validation.d.ts @@ -0,0 +1,16 @@ +export interface ChildrenErrors { + [key: string]: ValidationError | any; +} +export interface Validatable { + _validateNested(errors: ChildrenErrors): number; + validate(self: any): any; + get(key: string): any; +} +export declare class ValidationError { + nested: ChildrenErrors; + length: number; + error: any; + constructor(obj: Validatable); + each(iteratee: (value: any, key: string) => void): void; + eachError(iteratee: (error: any, key: string, object: Validatable) => void, object: Validatable): void; +} diff --git a/lib/type-r/validation.js b/lib/type-r/validation.js new file mode 100644 index 0000000..20f6e3f --- /dev/null +++ b/lib/type-r/validation.js @@ -0,0 +1,29 @@ +var ValidationError = (function () { + function ValidationError(obj) { + this.length = obj._validateNested(this.nested = {}); + if (this.error = obj.validate(obj)) { + this.length++; + } + } + ValidationError.prototype.each = function (iteratee) { + var _a = this, error = _a.error, nested = _a.nested; + if (error) + iteratee(error, null); + for (var key in nested) { + iteratee(nested[key], key); + } + }; + ValidationError.prototype.eachError = function (iteratee, object) { + this.each(function (value, key) { + if (value instanceof ValidationError) { + value.eachError(iteratee, object.get(key)); + } + else { + iteratee(value, key, object); + } + }); + }; + return ValidationError; +}()); +export { ValidationError }; +//# sourceMappingURL=validation.js.map \ No newline at end of file diff --git a/lib/type-r/validation.js.map b/lib/type-r/validation.js.map new file mode 100644 index 0000000..b930f72 --- /dev/null +++ b/lib/type-r/validation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"validation.js","sourceRoot":"","sources":["../../src/type-r/validation.ts"],"names":[],"mappings":"AAWA;IAQI,yBAAa,GAAiB;QAC1B,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC,eAAe,CAAE,IAAI,CAAC,MAAM,GAAG,EAAE,CAAE,CAAC;QAEtD,IAAI,IAAI,CAAC,KAAK,GAAG,GAAG,CAAC,QAAQ,CAAE,GAAG,CAAE,EAAE;YAClC,IAAI,CAAC,MAAM,EAAE,CAAC;SACjB;IACL,CAAC;IAED,8BAAI,GAAJ,UAAM,QAAgD;QAC5C,IAAA,SAAwB,EAAtB,gBAAK,EAAE,kBAAM,CAAU;QAE/B,IAAI,KAAK;YAAG,QAAQ,CAAE,KAAK,EAAE,IAAI,CAAE,CAAC;QAEpC,KAAK,IAAM,GAAG,IAAI,MAAM,EAAE;YACtB,QAAQ,CAAE,MAAM,CAAE,GAAG,CAAE,EAAE,GAAG,CAAE,CAAC;SAClC;IACL,CAAC;IAED,mCAAS,GAAT,UAAW,QAAsE,EAAE,MAAoB;QACnG,IAAI,CAAC,IAAI,CAAE,UAAE,KAAW,EAAE,GAAY;YAClC,IAAI,KAAK,YAAY,eAAe,EAAE;gBAChB,KAAM,CAAC,SAAS,CAAE,QAAQ,EAAE,MAAM,CAAC,GAAG,CAAE,GAAG,CAAE,CAAE,CAAC;aACrE;iBACG;gBACA,QAAQ,CAAE,KAAK,EAAE,GAAG,EAAE,MAAM,CAAE,CAAC;aAClC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;IACL,sBAAC;AAAD,CAAC,AApCD,IAoCC"} \ No newline at end of file diff --git a/lib/underscore-mixin.d.ts b/lib/underscore-mixin.d.ts new file mode 100644 index 0000000..1491893 --- /dev/null +++ b/lib/underscore-mixin.d.ts @@ -0,0 +1,14 @@ +export declare const ModelMixin: { + pick(...args: any[]): any; + escape(attr: any): any; + matches(attrs: any): boolean; + omit(...keys: string[]): {}; + invert(): {}; + pairs(): any; + isEmpty(): boolean; + chain(): any; +}; +export declare const CollectionMixin: { + where(attrs: any, first: any): any; + findWhere(attrs: any): any; +}; diff --git a/lib/underscore-mixin.js b/lib/underscore-mixin.js new file mode 100644 index 0000000..44440b5 --- /dev/null +++ b/lib/underscore-mixin.js @@ -0,0 +1,106 @@ +import * as _ from 'underscore'; +export var ModelMixin = { + pick: function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return _.pick(this, args); + }, + escape: function (attr) { + return _.escape(this[attr]); + }, + matches: function (attrs) { + return !!_.iteratee(attrs, this)(this); + }, + omit: function () { + var keys = []; + for (var _i = 0; _i < arguments.length; _i++) { + keys[_i] = arguments[_i]; + } + return this.mapObject(function (value, key) { + if (keys.indexOf(key) < 0) { + return value; + } + }); + }, + invert: function () { + var inverted = {}; + this.each(function (value, key) { return inverted[value] = key; }); + return inverted; + }, + pairs: function () { + return this.map(function (value, key) { return [key, value]; }); + }, + isEmpty: function () { + return !this.values().length; + }, + chain: function () { + return _.chain(this.mapObject(function (x) { return x; })); + } +}; +export var CollectionMixin = { + where: function (attrs, first) { + return this[first ? 'find' : 'filter'](attrs); + }, + findWhere: function (attrs) { + return this.where(attrs, true); + } +}; +addUnderscoreMethods(CollectionMixin, 'models', { + forEach: 3, each: 3, map: 3, collect: 3, reduce: 4, + foldl: 4, inject: 4, reduceRight: 4, foldr: 4, find: 3, findIndex: 3, findLastIndex: 3, detect: 3, filter: 3, + select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 3, includes: 3, + contains: 3, invoke: 0, max: 3, min: 3, toArray: 1, size: 1, first: 3, + head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3, + without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3, + isEmpty: 1, chain: 1, sample: 3, partition: 3, groupBy: 3, countBy: 3, + sortBy: 3, indexBy: 3 +}); +function addUnderscoreMethods(Mixin, attribute, methods) { + _.each(methods, function (length, method) { + if (_[method]) + Mixin[method] = addMethod(length, method, attribute); + }); +} +function addMethod(length, method, attribute) { + switch (length) { + case 1: return function () { + return _[method](this[attribute]); + }; + case 2: return function (value) { + return _[method](this[attribute], value); + }; + case 3: return function (iteratee, context) { + var value = this[attribute], callback = cb(iteratee, this); + return arguments.length > 1 ? + _[method](value, callback, context) + : _[method](value, callback); + }; + case 4: return function (iteratee, defaultVal, context) { + var value = this[attribute], callback = cb(iteratee, this); + return arguments.length > 1 ? + _[method](value, callback, defaultVal, context) + : _[method](value, callback); + }; + default: return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + args.unshift(this[attribute]); + return _[method].apply(_, args); + }; + } +} +function cb(iteratee, instance) { + switch (typeof iteratee) { + case 'function': return iteratee; + case 'string': return function (model) { return model.get(iteratee); }; + case 'object': + if (!(iteratee instanceof instance.model)) + return _.matches(iteratee); + } + return iteratee; +} +//# sourceMappingURL=underscore-mixin.js.map \ No newline at end of file diff --git a/lib/underscore-mixin.js.map b/lib/underscore-mixin.js.map new file mode 100644 index 0000000..9c30642 --- /dev/null +++ b/lib/underscore-mixin.js.map @@ -0,0 +1 @@ +{"version":3,"file":"underscore-mixin.js","sourceRoot":"","sources":["../src/underscore-mixin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,YAAY,CAAA;AAE/B,MAAM,CAAC,IAAM,UAAU,GAAG;IACtB,IAAI;QAAE,cAAe;aAAf,UAAe,EAAf,qBAAe,EAAf,IAAe;YAAf,yBAAe;;QACjB,OAAO,CAAC,CAAC,IAAI,CAAE,IAAI,EAAE,IAAI,CAAE,CAAC;IAChC,CAAC;IAED,MAAM,YAAE,IAAI;QACR,OAAO,CAAC,CAAC,MAAM,CAAE,IAAI,CAAE,IAAI,CAAE,CAAE,CAAC;IACpC,CAAC;IAED,OAAO,YAAE,KAAK;QACV,OAAO,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAE,KAAK,EA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AAQ,EAAE,IAAI,CAAC,CAAC;YAElC,OAAO,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;gBACzB,CAAC,CAAC,MAAM,CAAC,CAAE,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,OAAO,CAAE;gBACjD,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,QAAQ,CAAE,CAAC;QACtC,CAAC,CAAC;QACF,OAAO,CAAC,CAAC,OAAO;YAAU,cAAe;iBAAf,UAAe,EAAf,qBAAe,EAAf,IAAe;gBAAf,yBAAe;;YACrC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;YAC9B,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;QACpC,CAAC,CAAC;KACL;AACL,CAAC;AAGD,SAAS,EAAE,CAAC,QAAQ,EAAE,QAAQ;IAC1B,QAAQ,OAAO,QAAQ,EAAE;QACrB,KAAK,UAAW,CAAC,CAAC,OAAO,QAAQ,CAAC;QAClC,KAAK,QAAS,CAAC,CAAC,OAAO,UAAA,KAAK,IAAI,OAAA,KAAK,CAAC,GAAG,CAAE,QAAQ,CAAE,EAArB,CAAqB,CAAC;QACtD,KAAK,QAAQ;YACT,IAAI,CAAC,CAAC,QAAQ,YAAY,QAAQ,CAAC,KAAK,CAAE;gBAAE,OAAO,CAAC,CAAC,OAAO,CAAE,QAAQ,CAAE,CAAC;KAChF;IAED,OAAO,QAAQ,CAAC;AACpB,CAAC"} \ No newline at end of file diff --git a/nestedtypes.js b/nestedtypes.js deleted file mode 100644 index 0ed60b7..0000000 --- a/nestedtypes.js +++ /dev/null @@ -1,4507 +0,0 @@ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(require("underscore"), require("jquery")); - else if(typeof define === 'function' && define.amd) - define(["underscore", "jquery"], factory); - else if(typeof exports === 'object') - exports["Nested"] = factory(require("underscore"), require("jquery")); - else - root["Nested"] = factory(root["_"], root["$"]); -})(this, function(__WEBPACK_EXTERNAL_MODULE_31__, __WEBPACK_EXTERNAL_MODULE_32__) { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) -/******/ return installedModules[moduleId].exports; -/******/ -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ exports: {}, -/******/ id: moduleId, -/******/ loaded: false -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.loaded = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var Nested = __webpack_require__(1); - var Backbone = __webpack_require__(30); - var rest_1 = __webpack_require__(33); - var src_1 = __webpack_require__(1); - var Sync = __webpack_require__(34); - var underscore_mixin_1 = __webpack_require__(35); - var rest_store_1 = __webpack_require__(36); - Nested.Mixable.mixins(Nested.Events); - Nested.Mixable.mixTo(Backbone.View, Backbone.Router, Backbone.History); - Nested.Model.mixins(underscore_mixin_1.UnderscoreModel); - Nested.Collection.mixins(underscore_mixin_1.UnderscoreCollection); - var assign = Nested.tools.assign; - Object.defineProperties(Nested, { - 'emulateHTTP': linkProperty(Backbone, 'emulateHTTP'), - 'emulateJSON': linkProperty(Backbone, 'emulateJSON'), - 'sync': linkProperty(Sync, 'sync'), - 'errorPromise': linkProperty(Sync, 'errorPromise'), - 'ajax': linkProperty(Sync, 'ajax'), - 'history': linkProperty(Backbone, 'history'), - 'store': linkProperty(src_1.Store, 'global'), - '$': { - get: function () { return Backbone.$; }, - set: function (value) { Backbone.$ = Sync.$ = value; } - } - }); - assign(Nested, Backbone, { - Backbone: Backbone, - Class: Nested.Messenger, - Model: rest_1.RestModel, - Collection: rest_1.RestCollection, - LazyStore: rest_store_1.LazyStore, - Store: rest_store_1.RestStore, - defaults: function (x) { - return Nested.Model.defaults(x); - } - }); - function linkProperty(Namespace, name) { - return { - get: function () { return Namespace[name]; }, - set: function (value) { Namespace[name] = value; } - }; - } - module.exports = Nested; - - -/***/ }, -/* 1 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; - } - __export(__webpack_require__(2)); - __export(__webpack_require__(7)); - __export(__webpack_require__(25)); - __export(__webpack_require__(11)); - var _1 = __webpack_require__(2); - exports.on = _1.Events.on, exports.off = _1.Events.off, exports.trigger = _1.Events.trigger, exports.once = _1.Events.once, exports.listenTo = _1.Events.listenTo, exports.stopListening = _1.Events.stopListening, exports.listenToOnce = _1.Events.listenToOnce; - var record_2 = __webpack_require__(11); - exports.Model = record_2.Record; - var _2 = __webpack_require__(2); - exports.Class = _2.Mixable; - var record_3 = __webpack_require__(11); - function value(x) { - return new record_3.ChainableAttributeSpec({ value: x }); - } - exports.value = value; - function transaction(method) { - return function () { - var _this = this; - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - var result; - this.transaction(function () { - result = method.apply(_this, args); - }); - return result; - }; - } - exports.transaction = transaction; - - -/***/ }, -/* 2 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; - } - var tools = __webpack_require__(3); - exports.tools = tools; - __export(__webpack_require__(4)); - __export(__webpack_require__(5)); - var eventsApi = __webpack_require__(6); - exports.eventsApi = eventsApi; - var mixins_2 = __webpack_require__(4); - Object.extend = function (protoProps, staticProps) { return mixins_2.Mixable.extend(protoProps, staticProps); }; - Object.assign || (Object.assign = tools.assign); - Object.log = tools.log; - - -/***/ }, -/* 3 */ -/***/ function(module, exports) { - - "use strict"; - var Log = (function () { - function Log() { - this.stops = {}; - this.throws = {}; - this.logger = typeof console !== 'undefined' ? console : null; - this.reset(); - } - Log.prototype.doLogging = function (type, args) { - var logger = this.logger, logMethod = logger && logger[type]; - if (logMethod) - logMethod.apply(logger, args); - if (this.stops[type]) - debugger; - if (this.throws[type]) - throw new Error("[" + type + "] " + args[0]); - this.counts[type]++; - }; - Log.prototype.reset = function () { - this.level = 2; - this.counts = { error: 0, warn: 0, info: 0, debug: 0 }; - this.stops = {}; - return this; - }; - Log.prototype.developer = function (trueDeveloper) { - this.level = 3; - this.stops = { error: true, warn: Boolean(trueDeveloper) }; - return this; - }; - Log.prototype.error = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - if (this.level > 0) - this.doLogging('error', args); - }; - Log.prototype.warn = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - if (this.level > 1) - this.doLogging('warn', args); - }; - Log.prototype.info = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - if (this.level > 2) - this.doLogging('info', args); - }; - Log.prototype.debug = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - if (this.level > 3) - this.doLogging('debug', args); - }; - Object.defineProperty(Log.prototype, "state", { - get: function () { - return ("\nObject.log - Object+ Logging and Debugging Utility\n--------------------------------------------------\nObject.log.counts: Number of logged events by type\n { errors : " + this.counts.error + ", warns : " + this.counts.warn + ", info : " + this.counts.info + ", debug : " + this.counts.debug + " }\n\nObject.log.level == " + this.level + " : Ignore events which are above specified level \n - 0 - logging is off;\n - 1 - Object.log.error(...) only;\n - 2 - .error() and .warn();\n - 3 - .error(), .warn(), and .info();\n - 4 - all of above plus .debug().\n\nObject.log.stops: Stops in debugger for some certain event types\n { error : " + (this.stops.error || false) + ", warn : " + (this.stops.warn || false) + ", info : " + (this.stops.info || false) + ", debug : " + (this.stops.debug || false) + " } \n\nObject.log.throws: Throws expection on some certain event types\n { error : " + (this.throws.error || false) + ", warn : " + (this.throws.warn || false) + ", info : " + (this.throws.info || false) + ", debug : " + (this.throws.debug || false) + " }\n"); - }, - enumerable: true, - configurable: true - }); - return Log; - }()); - exports.Log = Log; - exports.log = new Log(); - function isValidJSON(value) { - if (value === null) { - return true; - } - switch (typeof value) { - case 'number': - case 'string': - case 'boolean': - return true; - case 'object': - var proto = Object.getPrototypeOf(value); - if (proto === Object.prototype || proto === Array.prototype) { - return every(value, isValidJSON); - } - } - return false; - } - exports.isValidJSON = isValidJSON; - function getBaseClass(Class) { - return Object.getPrototypeOf(Class.prototype).constructor; - } - exports.getBaseClass = getBaseClass; - function getChangedStatics(Ctor) { - var names = []; - for (var _i = 1; _i < arguments.length; _i++) { - names[_i - 1] = arguments[_i]; - } - var Base = getBaseClass(Ctor), props = {}; - for (var _a = 0, names_1 = names; _a < names_1.length; _a++) { - var name_1 = names_1[_a]; - var value = Ctor[name_1]; - if (value !== void 0 && value !== Base[name_1]) { - props[name_1] = value; - } - } - return props; - } - exports.getChangedStatics = getChangedStatics; - function isEmpty(obj) { - if (obj) { - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - return false; - } - } - } - return true; - } - exports.isEmpty = isEmpty; - function someArray(arr, fun) { - var result; - for (var i = 0; i < arr.length; i++) { - if (result = fun(arr[i], i)) { - return result; - } - } - } - function someObject(obj, fun) { - var result; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - if (result = fun(obj[key], key)) { - return result; - } - } - } - } - function some(obj, fun) { - if (Object.getPrototypeOf(obj) === ArrayProto) { - return someArray(obj, fun); - } - else { - return someObject(obj, fun); - } - } - exports.some = some; - function every(obj, predicate) { - return !some(obj, function (x) { return !predicate(x); }); - } - exports.every = every; - function getPropertyDescriptor(obj, prop) { - var desc; - for (var proto = obj; !desc && proto; proto = Object.getPrototypeOf(proto)) { - desc = Object.getOwnPropertyDescriptor(obj, prop); - } - return desc; - } - exports.getPropertyDescriptor = getPropertyDescriptor; - function omit(source) { - var dest = {}, discard = {}; - for (var i = 1; i < arguments.length; i++) { - discard[arguments[i]] = true; - } - for (var name in source) { - if (!discard.hasOwnProperty(name) && source.hasOwnProperty(name)) { - dest[name] = source[name]; - } - } - return dest; - } - exports.omit = omit; - function transform(dest, source, fun) { - for (var name in source) { - if (source.hasOwnProperty(name)) { - var value = fun(source[name], name); - value === void 0 || (dest[name] = value); - } - } - return dest; - } - exports.transform = transform; - function fastAssign(dest, source) { - for (var name in source) { - dest[name] = source[name]; - } - return dest; - } - exports.fastAssign = fastAssign; - function fastDefaults(dest, source) { - for (var name in source) { - if (dest[name] === void 0) { - dest[name] = source[name]; - } - } - return dest; - } - exports.fastDefaults = fastDefaults; - function assign(dest, source) { - for (var name in source) { - if (source.hasOwnProperty(name)) { - dest[name] = source[name]; - } - } - if (arguments.length > 2) { - for (var i = 2; i < arguments.length; i++) { - var other = arguments[i]; - other && assign(dest, other); - } - } - return dest; - } - exports.assign = assign; - function defaults(dest, source) { - for (var name in source) { - if (source.hasOwnProperty(name) && dest[name] === void 0) { - dest[name] = source[name]; - } - } - if (arguments.length > 2) { - for (var i = 2; i < arguments.length; i++) { - var other = arguments[i]; - other && defaults(dest, other); - } - } - return dest; - } - exports.defaults = defaults; - function keys(o) { - return o ? Object.keys(o) : []; - } - exports.keys = keys; - function once(func) { - var memo, first = true; - return function () { - if (first) { - first = false; - memo = func.apply(this, arguments); - func = null; - } - return memo; - }; - } - exports.once = once; - var ArrayProto = Array.prototype, DateProto = Date.prototype, ObjectProto = Object.prototype; - function notEqual(a, b) { - if (a === b) - return false; - if (a && b && typeof a == 'object' && typeof b == 'object') { - var protoA = Object.getPrototypeOf(a); - if (protoA !== Object.getPrototypeOf(b)) - return true; - switch (protoA) { - case DateProto: return +a !== +b; - case ArrayProto: return arraysNotEqual(a, b); - case ObjectProto: - case null: - return objectsNotEqual(a, b); - } - } - return true; - } - exports.notEqual = notEqual; - function objectsNotEqual(a, b) { - var keysA = Object.keys(a); - if (keysA.length !== Object.keys(b).length) - return true; - for (var i = 0; i < keysA.length; i++) { - var key = keysA[i]; - if (!b.hasOwnProperty(key) || notEqual(a[key], b[key])) { - return true; - } - } - return false; - } - function arraysNotEqual(a, b) { - if (a.length !== b.length) - return true; - for (var i = 0; i < a.length; i++) { - if (notEqual(a[i], b[i])) - return true; - } - return false; - } - - -/***/ }, -/* 4 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - var tools_1 = __webpack_require__(3); - var Mixable = (function () { - function Mixable() { - this.initialize.apply(this, arguments); - } - Mixable.prototype.initialize = function () { }; - Mixable.create = function (a, b) { - return new this(a, b); - }; - Mixable.mixins = function () { - var mixins = []; - for (var _i = 0; _i < arguments.length; _i++) { - mixins[_i - 0] = arguments[_i]; - } - var proto = this.prototype, mergeRules = this._mixinRules || {}, _appliedMixins = this._appliedMixins = (this._appliedMixins || []).slice(); - for (var _a = 0, mixins_1 = mixins; _a < mixins_1.length; _a++) { - var mixin = mixins_1[_a]; - if (mixin instanceof Array) { - return Mixable.mixins.apply(this, mixin); - } - if (_appliedMixins.indexOf(mixin) >= 0) - continue; - _appliedMixins.push(mixin); - if (typeof mixin === 'function') { - tools_1.defaults(this, mixin); - mergeProps(proto, mixin.prototype, mergeRules); - } - else { - mergeProps(proto, mixin, mergeRules); - } - } - return this; - }; - Mixable.mixTo = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { - var Ctor = args_1[_a]; - Mixable.mixins.call(Ctor, this); - } - return this; - }; - Mixable.mixinRules = function (mixinRules) { - var Base = Object.getPrototypeOf(this.prototype).constructor; - if (Base._mixinRules) { - mergeProps(mixinRules, Base._mixinRules); - } - this._mixinRules = mixinRules; - return this; - }; - Mixable.define = function (definition, staticProps) { - if (definition === void 0) { definition = {}; } - if (!this.define) { - tools_1.log.error("[Class Defininition] Class must have class extensions to use @define decorator. Use '@extendable' before @define, or extend the base class with class extensions.", definition); - return this; - } - this.predefine(); - var proto = this.prototype; - var protoProps = tools_1.omit(definition, 'properties', 'mixins', 'mixinRules'), _a = definition.properties, properties = _a === void 0 ? {} : _a, mixins = definition.mixins, mixinRules = definition.mixinRules; - tools_1.assign(proto, protoProps); - tools_1.assign(this, staticProps); - properties && Object.defineProperties(proto, tools_1.transform({}, properties, toPropertyDescriptor)); - mixinRules && this.mixinRules(mixinRules); - mixins && this.mixins(mixins); - return this; - }; - Mixable.extend = function (spec, statics) { - var Subclass; - if (spec && spec.hasOwnProperty('constructor')) { - Subclass = spec.constructor; - __extends(Subclass, this); - } - else { - Subclass = (function (_super) { - __extends(Subclass, _super); - function Subclass() { - _super.apply(this, arguments); - } - return Subclass; - }(this)); - } - return spec ? Subclass.define(spec, statics) : Subclass.predefine(); - }; - Mixable.predefine = function () { - var BaseClass = tools_1.getBaseClass(this); - if (BaseClass.create === this.create) { - this.create = Mixable.create; - } - this.__super__ = BaseClass.prototype; - return this; - }; - Mixable._mixinRules = { properties: 'merge' }; - return Mixable; - }()); - exports.Mixable = Mixable; - function toPropertyDescriptor(x) { - if (x) { - return typeof x === 'function' ? { get: x } : x; - } - } - function mixinRules(rules) { - return createDecorator('mixinRules', rules); - } - exports.mixinRules = mixinRules; - function mixins() { - var list = []; - for (var _i = 0; _i < arguments.length; _i++) { - list[_i - 0] = arguments[_i]; - } - return createDecorator('mixins', list); - } - exports.mixins = mixins; - function extendable(Type) { - Mixable.mixTo(Type); - } - exports.extendable = extendable; - function predefine(Constructor) { - Constructor.predefine(); - } - exports.predefine = predefine; - function define(spec) { - if (typeof spec === 'function') { - spec.define({}); - } - else { - return createDecorator('define', spec); - } - } - exports.define = define; - function createDecorator(name, spec) { - return function (Ctor) { - if (Ctor[name]) { - Ctor[name](spec); - } - else { - Mixable[name].call(Ctor, spec); - } - }; - } - function mergeObjects(a, b, rules) { - var x = tools_1.assign({}, a); - return mergeProps(x, b, rules); - } - var mergeFunctions = { - pipe: function (a, b) { - return function (x) { - return a.call(this, b.call(this, x)); - }; - }, - sequence: function (a, b) { - return function () { - a.apply(this, arguments); - b.apply(this, arguments); - }; - }, - reverse: function (a, b) { - return function () { - b.apply(this, arguments); - a.apply(this, arguments); - }; - }, - every: function (a, b) { - return function () { - return a.apply(this, arguments) && b.apply(this, arguments); - }; - }, - some: function (a, b) { - return function () { - return a.apply(this, arguments) || b.apply(this, arguments); - }; - } - }; - function mergeProps(target, source, rules) { - if (rules === void 0) { rules = {}; } - for (var _i = 0, _a = Object.keys(source); _i < _a.length; _i++) { - var name_1 = _a[_i]; - if (name_1 === 'constructor') - continue; - var sourceProp = Object.getOwnPropertyDescriptor(source, name_1), destProp = tools_1.getPropertyDescriptor(target, name_1), value = destProp && destProp.value; - if (value != null) { - var rule = rules[name_1]; - if (rule) { - target[name_1] = typeof rule === 'object' ? - mergeObjects(value, sourceProp.value, rule) : (rule === 'merge' ? - mergeObjects(value, sourceProp.value) : - mergeFunctions[rule](value, sourceProp.value)); - } - } - else { - Object.defineProperty(target, name_1, sourceProp); - } - } - return target; - } - exports.mergeProps = mergeProps; - - -/***/ }, -/* 5 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - var Mixins = __webpack_require__(4); - var tools = __webpack_require__(3); - var _eventsApi = __webpack_require__(6); - var events_api_1 = __webpack_require__(6); - exports.EventMap = events_api_1.EventMap; - var mixins = Mixins.mixins, define = Mixins.define, extendable = Mixins.extendable, omit = tools.omit, once = tools.once, isEmpty = tools.isEmpty, keys = tools.keys, EventHandler = _eventsApi.EventHandler, trigger0 = _eventsApi.trigger0, trigger1 = _eventsApi.trigger1, trigger2 = _eventsApi.trigger2, trigger3 = _eventsApi.trigger3; - var eventSplitter = /\s+/; - var _idCount = 0; - function uniqueId() { - return 'l' + _idCount++; - } - var Messenger = (function () { - function Messenger() { - this._events = void 0; - this._listeners = void 0; - this._listeningTo = void 0; - this.cid = uniqueId(); - this.initialize.apply(this, arguments); - } - Messenger.define = function (protoProps, staticProps) { - var spec = omit(protoProps || {}, 'localEvents'); - if (protoProps) { - var localEvents = protoProps.localEvents, _localEvents = protoProps._localEvents; - if (localEvents || _localEvents) { - var eventsMap = new events_api_1.EventMap(this.prototype._localEvents); - localEvents && eventsMap.addEventsMap(localEvents); - _localEvents && eventsMap.merge(_localEvents); - spec._localEvents = eventsMap; - } - } - return Mixins.Mixable.define.call(this, spec, staticProps); - }; - Messenger.prototype.initialize = function () { }; - Messenger.prototype.on = function (name, callback, context) { - return internalOn(this, name, callback, context); - }; - Messenger.prototype.off = function (name, callback, context) { - if (!this._events) - return this; - this._events = eventsApi(offApi, this._events, name, callback, new OffOptions(context, this._listeners)); - return this; - }; - Messenger.prototype.stopListening = function (obj, name, callback) { - var listeningTo = this._listeningTo; - if (!listeningTo) - return this; - var ids = obj ? [obj.cid] : keys(listeningTo); - for (var i = 0; i < ids.length; i++) { - var listening = listeningTo[ids[i]]; - if (!listening) - break; - listening.obj.off(name, callback, this); - } - if (isEmpty(listeningTo)) - this._listeningTo = void 0; - return this; - }; - Messenger.prototype.listenTo = function (obj, name, callback) { - if (!obj) - return this; - var id = obj.cid || (obj.cid = uniqueId()), listeningTo = this._listeningTo || (this._listeningTo = {}); - var listening = listeningTo[id]; - if (!listening) { - var thisId = this.cid || (this.cid = uniqueId()); - listening = listeningTo[id] = new ListeningTo(obj, id, thisId, listeningTo); - } - internalOn(obj, name, callback, this, listening); - return this; - }; - Messenger.prototype.once = function (name, callback, context) { - var events = eventsApi(onceMap, {}, name, callback, this.off.bind(this)); - return this.on(events, void 0, context); - }; - Messenger.prototype.listenToOnce = function (obj, name, callback) { - var events = eventsApi(onceMap, {}, name, callback, this.stopListening.bind(this, obj)); - return this.listenTo(obj, events); - }; - Messenger.prototype.trigger = function (name, a, b, c) { - if (!this._events) - return this; - switch (arguments.length) { - case 1: - trigger0(this, name); - break; - case 2: - trigger1(this, name, a); - break; - case 3: - trigger2(this, name, a, b); - break; - case 4: - trigger3(this, name, a, b, c); - break; - default: - var allArgs = Array(arguments.length); - for (var i = 0; i < allArgs.length; i++) { - allArgs[i] = arguments[i]; - } - var _events = this._events; - var queue = _events[name]; - if (queue) - _fireEventAll(queue, allArgs.slice(1)); - if (queue = _events.all) - _fireEventAll(queue, allArgs); - } - return this; - }; - Messenger.prototype.dispose = function () { - this.stopListening(); - this.off(); - }; - Messenger = __decorate([ - extendable - ], Messenger); - return Messenger; - }()); - exports.Messenger = Messenger; - var slice = Array.prototype.slice; - exports.Events = omit(Messenger.prototype, 'constructor', 'initialize'); - function eventsApi(iteratee, events, name, callback, opts) { - var i = 0, names; - if (name && typeof name === 'object') { - if (callback !== void 0 && 'context' in opts && opts.context === void 0) - opts.context = callback; - for (names = keys(name); i < names.length; i++) { - events = eventsApi(iteratee, events, names[i], name[names[i]], opts); - } - } - else if (name && eventSplitter.test(name)) { - for (names = name.split(eventSplitter); i < names.length; i++) { - events = iteratee(events, names[i], callback, opts); - } - } - else { - events = iteratee(events, name, callback, opts); - } - return events; - } - ; - var ListeningTo = (function () { - function ListeningTo(obj, objId, id, listeningTo) { - this.obj = obj; - this.objId = objId; - this.id = id; - this.listeningTo = listeningTo; - this.count = 0; - } - return ListeningTo; - }()); - function internalOn(obj, name, callback, context, listening) { - obj._events = eventsApi(onApi, obj._events || {}, name, callback, new EventHandler(context, obj, listening)); - if (listening) { - var listeners = obj._listeners || (obj._listeners = {}); - listeners[listening.id] = listening; - } - return obj; - } - ; - function onApi(events, name, callback, options) { - if (callback) { - var handlers = events[name], toAdd = [options.clone(callback)]; - events[name] = handlers ? handlers.concat(toAdd) : toAdd; - } - return events; - } - ; - var OffOptions = (function () { - function OffOptions(context, listeners) { - this.context = context; - this.listeners = listeners; - } - return OffOptions; - }()); - function offApi(events, name, callback, options) { - if (!events) - return; - var i = 0, listening; - var context = options.context, listeners = options.listeners; - if (!name && !callback && !context) { - var ids = keys(listeners); - for (; i < ids.length; i++) { - listening = listeners[ids[i]]; - delete listeners[listening.id]; - delete listening.listeningTo[listening.objId]; - } - return {}; - } - var names = name ? [name] : keys(events); - for (; i < names.length; i++) { - name = names[i]; - var handlers = events[name]; - if (!handlers) - break; - var remaining = []; - for (var j = 0; j < handlers.length; j++) { - var handler = handlers[j]; - if (callback && callback !== handler.callback && - callback !== handler.callback._callback || - context && context !== handler.context) { - remaining.push(handler); - } - else { - listening = handler.listening; - if (listening && --listening.count === 0) { - delete listeners[listening.id]; - delete listening.listeningTo[listening.objId]; - } - } - } - if (remaining.length) { - events[name] = remaining; - } - else { - delete events[name]; - } - } - return events; - } - ; - function onceMap(map, name, callback, offer) { - if (callback) { - var _once_1 = map[name] = once(function () { - offer(name, _once_1); - callback.apply(this, arguments); - }); - _once_1._callback = callback; - } - return map; - } - ; - function _fireEventAll(events, a) { - for (var _i = 0, events_1 = events; _i < events_1.length; _i++) { - var ev = events_1[_i]; - ev.callback.apply(ev.ctx, a); - } - } - - -/***/ }, -/* 6 */ -/***/ function(module, exports) { - - "use strict"; - exports.eventSplitter = /\s+/; - var EventHandler = (function () { - function EventHandler(context, ctx, listening, callback) { - this.context = context; - this.ctx = ctx; - this.listening = listening; - this.callback = callback; - } - EventHandler.prototype.clone = function (callback) { - var _a = this, context = _a.context, listening = _a.listening; - if (listening) - listening.count++; - return new EventHandler(context, context || this.ctx, listening, callback); - }; - return EventHandler; - }()); - exports.EventHandler = EventHandler; - var EventMap = (function () { - function EventMap(map) { - this.handlers = []; - if (map) { - if (map instanceof EventMap) { - this.handlers = map.handlers.slice(); - } - else { - map && this.addEventsMap(map); - } - } - } - EventMap.prototype.merge = function (map) { - this.handlers = this.handlers.concat(map.handlers); - }; - EventMap.prototype.addEventsMap = function (map) { - for (var names in map) { - this.addEvent(names, map[names]); - } - }; - EventMap.prototype.bubbleEvents = function (names) { - for (var _i = 0, _a = names.split(exports.eventSplitter); _i < _a.length; _i++) { - var name_1 = _a[_i]; - this.addEvent(name_1, getBubblingHandler(name_1)); - } - }; - EventMap.prototype.addEvent = function (names, callback) { - var handlers = this.handlers; - for (var _i = 0, _a = names.split(exports.eventSplitter); _i < _a.length; _i++) { - var name_2 = _a[_i]; - handlers.push(new EventDescriptor(name_2, callback)); - } - }; - EventMap.prototype.subscribe = function (target, source) { - var _events = source._events || (source._events = {}); - for (var _i = 0, _a = this.handlers; _i < _a.length; _i++) { - var event_1 = _a[_i]; - _on(_events, event_1.name, event_1.callback, target); - } - }; - EventMap.prototype.unsubscribe = function (target, source) { - var _events = source._events; - if (_events) { - for (var _i = 0, _a = this.handlers; _i < _a.length; _i++) { - var event_2 = _a[_i]; - _off(_events, event_2.name, event_2.callback, target); - } - } - }; - return EventMap; - }()); - exports.EventMap = EventMap; - var EventDescriptor = (function () { - function EventDescriptor(name, callback) { - this.name = name; - if (callback === true) { - this.callback = getBubblingHandler(name); - } - else if (typeof callback === 'string') { - this.callback = - function localCallback() { - var handler = this[callback]; - handler && handler.apply(this, arguments); - }; - } - else { - this.callback = callback; - } - } - return EventDescriptor; - }()); - function on(self, name, callback, context) { - var _events = self._events || (self._events = {}); - _on(_events, name, callback, context); - } - exports.on = on; - function off(self, name, callback, context) { - var _events = self._events; - _events && _off(_events, name, callback, context); - } - exports.off = off; - function trigger0(self, name) { - var _events = self._events; - if (_events) { - var queue = _events[name], all = _events.all; - if (queue) - _fireEvent0(queue); - if (all) - _fireEvent1(all, name); - } - } - exports.trigger0 = trigger0; - ; - function trigger1(self, name, a) { - var _events = self._events; - if (_events) { - var queue = _events[name], all = _events.all; - if (queue) - _fireEvent1(queue, a); - if (all) - _fireEvent2(all, name, a); - } - } - exports.trigger1 = trigger1; - ; - function trigger2(self, name, a, b) { - var _events = self._events; - if (_events) { - var queue = _events[name], all = _events.all; - if (queue) - _fireEvent2(queue, a, b); - if (all) - _fireEvent3(all, name, a, b); - } - } - exports.trigger2 = trigger2; - ; - function trigger3(self, name, a, b, c) { - var _events = self._events; - if (_events) { - var queue = _events[name], all = _events.all; - if (queue) - _fireEvent3(queue, a, b, c); - if (all) - _fireEvent4(all, name, a, b, c); - } - } - exports.trigger3 = trigger3; - ; - function _fireEvent0(events) { - for (var _i = 0, events_1 = events; _i < events_1.length; _i++) { - var ev = events_1[_i]; - ev.callback.call(ev.ctx); - } - } - function _fireEvent1(events, a) { - for (var _i = 0, events_2 = events; _i < events_2.length; _i++) { - var ev = events_2[_i]; - ev.callback.call(ev.ctx, a); - } - } - function _fireEvent2(events, a, b) { - for (var _i = 0, events_3 = events; _i < events_3.length; _i++) { - var ev = events_3[_i]; - ev.callback.call(ev.ctx, a, b); - } - } - function _fireEvent3(events, a, b, c) { - for (var _i = 0, events_4 = events; _i < events_4.length; _i++) { - var ev = events_4[_i]; - ev.callback.call(ev.ctx, a, b, c); - } - } - function _fireEvent4(events, a, b, c, d) { - for (var _i = 0, events_5 = events; _i < events_5.length; _i++) { - var ev = events_5[_i]; - ev.callback.call(ev.ctx, a, b, c, d); - } - } - function _on(_events, name, callback, context, ctx) { - var events = _events[name], handler = new EventHandler(context, ctx || context, null, callback); - if (events) { - events.push(handler); - } - else { - _events[name] = [handler]; - } - } - ; - function _off(_events, name, callback, context) { - var events = _events[name]; - if (events) { - var retain = []; - for (var _i = 0, events_6 = events; _i < events_6.length; _i++) { - var ev = events_6[_i]; - if ((callback && callback !== ev.callback) || context !== ev.context) { - retain.push(ev); - } - } - _events[name] = retain.length ? retain : void 0; - } - } - ; - var _bubblingHandlers = {}; - function getBubblingHandler(event) { - return _bubblingHandlers[event] || (_bubblingHandlers[event] = function (a, b, c) { - switch (arguments.length) { - case 0: - trigger0(this, event); - break; - case 1: - trigger1(this, event, a); - break; - case 2: - trigger2(this, event, a, b); - break; - case 3: - trigger3(this, event, a, b, c); - break; - default: - var args = [event, a, b, c]; - for (var i = 3; i < arguments.length; i++) { - args.push(arguments[i]); - } - this.trigger.apply(this, args); - } - }); - } - - -/***/ }, -/* 7 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - var object_plus_1 = __webpack_require__(2); - var transactions_1 = __webpack_require__(8); - var record_1 = __webpack_require__(11); - var commons_1 = __webpack_require__(21); - var add_1 = __webpack_require__(22); - var set_1 = __webpack_require__(23); - var remove_1 = __webpack_require__(24); - var trigger2 = object_plus_1.eventsApi.trigger2, begin = transactions_1.transactionApi.begin, commit = transactions_1.transactionApi.commit, markAsDirty = transactions_1.transactionApi.markAsDirty, omit = object_plus_1.tools.omit, log = object_plus_1.tools.log, assign = object_plus_1.tools.assign, defaults = object_plus_1.tools.defaults; - var _count = 0; - var silentOptions = { silent: true }; - var Collection = (function (_super) { - __extends(Collection, _super); - function Collection(records, options, shared) { - if (options === void 0) { options = {}; } - _super.call(this, _count++); - this.models = []; - this._byId = {}; - this.comparator = this.comparator; - if (options.comparator !== void 0) { - this.comparator = options.comparator; - options.comparator = void 0; - } - this.model = this.model; - if (options.model) { - this.model = options.model; - options.model = void 0; - } - this.idAttribute = this.model.prototype.idAttribute; - this._shared = shared || 0; - if (records) { - var elements = toElements(this, records, options); - set_1.emptySetTransaction(this, elements, options, true); - } - this.initialize.apply(this, arguments); - if (this._localEvents) - this._localEvents.subscribe(this, this); - } - Collection.prototype.createSubset = function (models, options) { - var SubsetOf = this.constructor.subsetOf(this).options.type, subset = new SubsetOf(models, options); - subset.resolve(this); - return subset; - }; - Collection.predefine = function () { - var Ctor = this; - this._SubsetOf = null; - function Subset(a, b, listen) { - Ctor.call(this, a, b, listen ? 1 : 2); - } - object_plus_1.Mixable.mixTo(Subset); - Subset.prototype = this.prototype; - Subset._attribute = record_1.TransactionalType; - Subset['of'] = function (path) { - return Ctor.subsetOf(path); - }; - this.Set = this.Subset = Subset; - transactions_1.Transactional.predefine.call(this); - record_1.createSharedTypeSpec(this, SharedCollectionType); - return this; - }; - Collection.define = function (protoProps, staticProps) { - if (protoProps === void 0) { protoProps = {}; } - var staticsDefinition = object_plus_1.tools.getChangedStatics(this, 'model', 'itemEvents'), definition = assign(staticsDefinition, protoProps); - var spec = omit(definition, 'itemEvents'); - if (definition.itemEvents) { - var eventsMap = new object_plus_1.EventMap(this.prototype._itemEvents); - eventsMap.addEventsMap(definition.itemEvents); - spec._itemEvents = eventsMap; - } - return transactions_1.Transactional.define.call(this, spec, staticProps); - }; - Object.defineProperty(Collection.prototype, "_state", { - get: function () { return this.models; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Collection.prototype, "comparator", { - get: function () { return this._comparator; }, - set: function (x) { - var _this = this; - var compare; - switch (typeof x) { - case 'string': - this._comparator = function (a, b) { - var aa = a[x], bb = b[x]; - if (aa === bb) - return 0; - return aa < bb ? -1 : +1; - }; - break; - case 'function': - if (x.length === 1) { - this._comparator = function (a, b) { - var aa = x.call(_this, a), bb = x.call(_this, b); - if (aa === bb) - return 0; - return aa < bb ? -1 : +1; - }; - } - else { - this._comparator = function (a, b) { return x.call(_this, a, b); }; - } - break; - default: - this._comparator = null; - } - }, - enumerable: true, - configurable: true - }); - Collection.prototype.getStore = function () { - return this._store || (this._store = this._owner ? this._owner.getStore() : this._defaultStore); - }; - Collection.prototype._onChildrenChange = function (record, options, initiator) { - if (options === void 0) { options = {}; } - if (initiator === this) - return; - var idAttribute = this.idAttribute; - if (record.hasChanged(idAttribute)) { - commons_1.updateIndex(this._byId, record); - } - var isRoot = begin(this); - if (markAsDirty(this, options)) { - trigger2(this, 'change', record, options); - } - isRoot && commit(this); - }; - Collection.prototype.get = function (objOrId) { - if (objOrId == null) - return; - if (typeof objOrId === 'object') { - var id = objOrId[this.idAttribute]; - return (id !== void 0 && this._byId[id]) || this._byId[objOrId.cid]; - } - else { - return this._byId[objOrId]; - } - }; - Collection.prototype.each = function (iteratee, context) { - var fun = arguments.length === 2 ? function (v, k) { return iteratee.call(context, v, k); } : iteratee, models = this.models; - for (var i = 0; i < models.length; i++) { - fun(models[i], i); - } - }; - Collection.prototype._validateNested = function (errors) { - if (this._shared) - return 0; - var count = 0; - this.each(function (record) { - var error = record.validationError; - if (error) { - errors[record.cid] = error; - count++; - } - }); - return count; - }; - Collection.prototype.initialize = function () { }; - Object.defineProperty(Collection.prototype, "length", { - get: function () { return this.models.length; }, - enumerable: true, - configurable: true - }); - Collection.prototype.first = function () { return this.models[0]; }; - Collection.prototype.last = function () { return this.models[this.models.length - 1]; }; - Collection.prototype.at = function (a_index) { - var index = a_index < 0 ? a_index + this.models.length : a_index; - return this.models[index]; - }; - Collection.prototype.clone = function (options) { - if (options === void 0) { options = {}; } - var models = this.map(function (model) { return model.clone(); }), copy = new this.constructor(models, { model: this.model, comparator: this.comparator }, this._shared); - if (options.pinStore) - copy._defaultStore = this.getStore(); - return copy; - }; - Collection.prototype.toJSON = function () { - if (!this._shared) { - return this.models.map(function (model) { return model.toJSON(); }); - } - }; - Collection.prototype.set = function (elements, options) { - if (elements === void 0) { elements = []; } - if (options === void 0) { options = {}; } - if (options.add !== void 0) { - this._log('warn', "Collection.set doesn't support 'add' option, behaving as if options.add === true.", options); - } - if (options.reset) { - this.reset(elements, options); - } - else { - var transaction = this._createTransaction(elements, options); - transaction && transaction.commit(); - } - return this; - }; - Collection.prototype.dispose = function () { - if (!this._shared) { - for (var _i = 0, _a = this.models; _i < _a.length; _i++) { - var record = _a[_i]; - if (record._owner === this) - record.dispose(); - } - } - _super.prototype.dispose.call(this); - }; - Collection.prototype.reset = function (a_elements, options) { - if (options === void 0) { options = {}; } - var isRoot = begin(this), previousModels = commons_1.dispose(this); - if (a_elements) { - set_1.emptySetTransaction(this, toElements(this, a_elements, options), options, true); - } - markAsDirty(this, options); - options.silent || trigger2(this, 'reset', this, defaults({ previousModels: previousModels }, options)); - isRoot && commit(this); - return this.models; - }; - Collection.prototype.add = function (a_elements, options) { - if (options === void 0) { options = {}; } - var elements = toElements(this, a_elements, options), transaction = this.models.length ? - add_1.addTransaction(this, elements, options) : - set_1.emptySetTransaction(this, elements, options); - if (transaction) { - transaction.commit(); - return transaction.added; - } - }; - Collection.prototype.remove = function (recordsOrIds, options) { - if (options === void 0) { options = {}; } - if (recordsOrIds) { - return Array.isArray(recordsOrIds) ? - remove_1.removeMany(this, recordsOrIds, options) : - remove_1.removeOne(this, recordsOrIds, options); - } - return []; - }; - Collection.prototype._createTransaction = function (a_elements, options) { - if (options === void 0) { options = {}; } - var elements = toElements(this, a_elements, options); - if (this.models.length) { - return options.remove === false ? - add_1.addTransaction(this, elements, options, true) : - set_1.setTransaction(this, elements, options); - } - else { - return set_1.emptySetTransaction(this, elements, options); - } - }; - Collection.prototype.pluck = function (key) { - return this.models.map(function (model) { return model[key]; }); - }; - Collection.prototype.sort = function (options) { - if (options === void 0) { options = {}; } - if (commons_1.sortElements(this, options)) { - var isRoot = begin(this); - if (markAsDirty(this, options)) { - trigger2(this, 'sort', this, options); - } - isRoot && commit(this); - } - return this; - }; - Collection.prototype.push = function (model, options) { - return this.add(model, assign({ at: this.length }, options)); - }; - Collection.prototype.pop = function (options) { - var model = this.at(this.length - 1); - this.remove(model, options); - return model; - }; - Collection.prototype.unshift = function (model, options) { - return this.add(model, assign({ at: 0 }, options)); - }; - Collection.prototype.shift = function (options) { - var model = this.at(0); - this.remove(model, options); - return model; - }; - Collection.prototype.slice = function () { - return slice.apply(this.models, arguments); - }; - Collection.prototype.indexOf = function (modelOrId) { - var record = this.get(modelOrId); - return this.models.indexOf(record); - }; - Collection.prototype.modelId = function (attrs) { - return attrs[this.model.prototype.idAttribute]; - }; - Collection.prototype.toggle = function (model, a_next) { - var prev = Boolean(this.get(model)), next = a_next === void 0 ? !prev : Boolean(a_next); - if (prev !== next) { - if (prev) { - this.remove(model); - } - else { - this.add(model); - } - } - return next; - }; - Collection.prototype._log = function (level, text, value) { - object_plus_1.tools.log[level](("[Collection Update] " + this.model.prototype.getClassName() + "." + this.getClassName() + ": ") + text, value, 'Attributes spec:', this.model.prototype._attributes); - }; - Collection.prototype.getClassName = function () { - return _super.prototype.getClassName.call(this) || 'Collection'; - }; - Collection._attribute = record_1.TransactionalType; - Collection = __decorate([ - object_plus_1.define({ - cidPrefix: 'c', - model: record_1.Record, - _changeEventName: 'changes', - _aggregationError: null - }) - ], Collection); - return Collection; - }(transactions_1.Transactional)); - exports.Collection = Collection; - function toElements(collection, elements, options) { - var parsed = options.parse ? collection.parse(elements, options) : elements; - return Array.isArray(parsed) ? parsed : [parsed]; - } - var slice = Array.prototype.slice; - var SharedCollectionType = (function (_super) { - __extends(SharedCollectionType, _super); - function SharedCollectionType() { - _super.apply(this, arguments); - } - SharedCollectionType.prototype.convert = function (value, options, prev, record) { - return value == null || value instanceof this.type ? value : new this.type(value, options, 1); - }; - return SharedCollectionType; - }(record_1.SharedRecordType)); - record_1.createSharedTypeSpec(Collection, SharedCollectionType); - record_1.Record.Collection = Collection; - - -/***/ }, -/* 8 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - var object_plus_1 = __webpack_require__(2); - var validation_1 = __webpack_require__(9); - var traversable_1 = __webpack_require__(10); - var assign = object_plus_1.tools.assign, trigger2 = object_plus_1.eventsApi.trigger2, trigger3 = object_plus_1.eventsApi.trigger3, on = object_plus_1.eventsApi.on, off = object_plus_1.eventsApi.off; - var Transactional = (function () { - function Transactional(cid) { - this._events = void 0; - this._changeToken = {}; - this._transaction = false; - this._isDirty = null; - this._owner = void 0; - this._ownerKey = void 0; - this._validationError = void 0; - this.cid = this.cidPrefix + cid; - } - Transactional.prototype.dispose = function () { - this._owner = void 0; - this._ownerKey = void 0; - this.off(); - this.stopListening(); - this._disposed = true; - }; - Transactional.prototype.initialize = function () { }; - Transactional.prototype.onChanges = function (handler, target) { - on(this, this._changeEventName, handler, target); - }; - Transactional.prototype.offChanges = function (handler, target) { - off(this, this._changeEventName, handler, target); - }; - Transactional.prototype.listenToChanges = function (target, handler) { - this.listenTo(target, target._changeEventName, handler); - }; - Transactional.prototype.transaction = function (fun, options) { - if (options === void 0) { options = {}; } - var isRoot = exports.transactionApi.begin(this); - fun.call(this, this); - isRoot && exports.transactionApi.commit(this); - }; - Transactional.prototype.updateEach = function (iteratee, options) { - var isRoot = exports.transactionApi.begin(this); - this.each(iteratee); - isRoot && exports.transactionApi.commit(this); - }; - Transactional.prototype.set = function (values, options) { - if (values) { - var transaction = this._createTransaction(values, options); - transaction && transaction.commit(); - } - return this; - }; - Transactional.prototype.parse = function (data, options) { return data; }; - Transactional.prototype.deepGet = function (reference) { - return traversable_1.resolveReference(this, reference, function (object, key) { return object.get ? object.get(key) : object[key]; }); - }; - Transactional.prototype.getOwner = function () { - return this._owner; - }; - Transactional.prototype.getStore = function () { - var _owner = this._owner; - return _owner ? _owner.getStore() : this._defaultStore; - }; - Transactional.prototype.map = function (iteratee, context) { - var arr = [], fun = arguments.length === 2 ? function (v, k) { return iteratee.call(context, v, k); } : iteratee; - this.each(function (val, key) { - var result = fun(val, key); - if (result !== void 0) - arr.push(result); - }); - return arr; - }; - Transactional.prototype.mapObject = function (iteratee, context) { - var obj = {}, fun = arguments.length === 2 ? function (v, k) { return iteratee.call(context, v, k); } : iteratee; - this.each(function (val, key) { - var result = iteratee(val, key); - if (result !== void 0) - obj[key] = result; - }); - return obj; - }; - Transactional.prototype.keys = function () { - return this.map(function (value, key) { - if (value !== void 0) - return key; - }); - }; - Transactional.prototype.values = function () { - return this.map(function (value) { return value; }); - }; - Object.defineProperty(Transactional.prototype, "validationError", { - get: function () { - var error = this._validationError || (this._validationError = new validation_1.ValidationError(this)); - return error.length ? error : null; - }, - enumerable: true, - configurable: true - }); - Transactional.prototype.validate = function (obj) { }; - Transactional.prototype.getValidationError = function (key) { - var error = this.validationError; - return (key ? error && error.nested[key] : error) || null; - }; - Transactional.prototype.deepValidationError = function (reference) { - return traversable_1.resolveReference(this, reference, function (object, key) { return object.getValidationError(key); }); - }; - Transactional.prototype.eachValidationError = function (iteratee) { - var validationError = this.validationError; - validationError && validationError.eachError(iteratee, this); - }; - Transactional.prototype.isValid = function (key) { - return !this.getValidationError(key); - }; - Transactional.prototype.valueOf = function () { return this.cid; }; - Transactional.prototype.toString = function () { return this.cid; }; - Transactional.prototype.getClassName = function () { - var name = this.constructor.name; - if (name !== 'Subclass') - return name; - }; - Transactional = __decorate([ - object_plus_1.mixins(object_plus_1.Messenger), - object_plus_1.extendable - ], Transactional); - return Transactional; - }()); - exports.Transactional = Transactional; - exports.transactionApi = { - begin: function (object) { - return object._transaction ? false : (object._transaction = true); - }, - markAsDirty: function (object, options) { - var dirty = !options.silent; - if (dirty) - object._isDirty = options; - object._changeToken = {}; - object._validationError = void 0; - return dirty; - }, - commit: function (object, initiator) { - var originalOptions = object._isDirty; - if (originalOptions) { - while (object._isDirty) { - var options = object._isDirty; - object._isDirty = null; - trigger3(object, object._changeEventName, object, options, initiator); - } - object._transaction = false; - var _owner = object._owner; - if (_owner && _owner !== initiator) { - _owner._onChildrenChange(object, originalOptions); - } - } - else { - object._isDirty = null; - object._transaction = false; - } - }, - aquire: function (owner, child, key) { - if (!child._owner) { - child._owner = owner; - child._ownerKey = key; - return true; - } - return child._owner === owner; - }, - free: function (owner, child) { - if (owner === child._owner) { - child._owner = void 0; - child._ownerKey = void 0; - } - } - }; - - -/***/ }, -/* 9 */ -/***/ function(module, exports) { - - "use strict"; - var ValidationError = (function () { - function ValidationError(obj) { - this.length = obj._validateNested(this.nested = {}); - if (this.error = obj.validate(obj)) { - this.length++; - } - } - ValidationError.prototype.each = function (iteratee) { - var _a = this, error = _a.error, nested = _a.nested; - if (error) - iteratee(error, null); - for (var key in nested) { - iteratee(nested[key], key); - } - }; - ValidationError.prototype.eachError = function (iteratee, object) { - this.each(function (value, key) { - if (value instanceof ValidationError) { - value.eachError(iteratee, object.get(key)); - } - else { - iteratee(value, key, object); - } - }); - }; - return ValidationError; - }()); - exports.ValidationError = ValidationError; - - -/***/ }, -/* 10 */ -/***/ function(module, exports) { - - "use strict"; - var referenceMask = /\^|([^.]+)/g; - var CompiledReference = (function () { - function CompiledReference(reference, splitTail) { - if (splitTail === void 0) { splitTail = false; } - var path = reference - .match(referenceMask) - .map(function (key) { - if (key === '^') - return 'getOwner()'; - if (key[0] === '~') - return "getStore().get(\"" + key.substr(1) + "\")"; - return key; - }); - this.tail = splitTail && path.pop(); - this.local = !path.length; - path.unshift('self'); - this.resolve = new Function('self', "return " + path.join('.') + ";"); - } - return CompiledReference; - }()); - exports.CompiledReference = CompiledReference; - function resolveReference(root, reference, action) { - var path = reference.match(referenceMask), skip = path.length - 1; - var self = root; - for (var i = 0; i < skip; i++) { - var key = path[i]; - switch (key) { - case '~': - self = self.getStore(); - break; - case '^': - self = self.getOwner(); - break; - default: self = self.get(key); - } - if (!self) - return; - } - return action(self, path[skip]); - } - exports.resolveReference = resolveReference; - - -/***/ }, -/* 11 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; - } - var transaction_1 = __webpack_require__(12); - exports.Record = transaction_1.Record; - var object_plus_1 = __webpack_require__(2); - var define_1 = __webpack_require__(13); - var typespec_1 = __webpack_require__(20); - exports.ChainableAttributeSpec = typespec_1.ChainableAttributeSpec; - var transactions_1 = __webpack_require__(8); - var attributes_1 = __webpack_require__(14); - __export(__webpack_require__(14)); - var assign = object_plus_1.tools.assign, defaults = object_plus_1.tools.defaults, omit = object_plus_1.tools.omit, getBaseClass = object_plus_1.tools.getBaseClass; - transaction_1.Record.define = function (protoProps, staticProps) { - if (protoProps === void 0) { protoProps = {}; } - var BaseConstructor = getBaseClass(this), baseProto = BaseConstructor.prototype, staticsDefinition = object_plus_1.tools.getChangedStatics(this, 'attributes', 'collection', 'Collection'), definition = assign(staticsDefinition, protoProps); - if ('Collection' in this && this.Collection === void 0) { - object_plus_1.tools.log.error("[Model Definition] " + this.prototype.getClassName() + ".Collection is undefined. It must be defined _before_ the model.", definition); - } - var dynamicMixin = define_1.compile(getAttributes(definition), baseProto._attributes); - if (definition.properties === false) { - dynamicMixin.properties = {}; - } - assign(dynamicMixin.properties, protoProps.properties || {}); - assign(dynamicMixin, omit(definition, 'attributes', 'collection', 'defaults', 'properties', 'forEachAttr')); - object_plus_1.Mixable.define.call(this, dynamicMixin, staticProps); - defineCollection.call(this, definition.collection || definition.Collection); - return this; - }; - transaction_1.Record.predefine = function () { - transactions_1.Transactional.predefine.call(this); - this.Collection = getBaseClass(this).Collection.extend(); - this.Collection.prototype.model = this; - createSharedTypeSpec(this, attributes_1.SharedRecordType); - return this; - }; - transaction_1.Record._attribute = attributes_1.TransactionalType; - createSharedTypeSpec(transaction_1.Record, attributes_1.SharedRecordType); - function getAttributes(_a) { - var defaults = _a.defaults, attributes = _a.attributes, idAttribute = _a.idAttribute; - var definition = typeof defaults === 'function' ? defaults() : attributes || defaults || {}; - if (idAttribute && !(idAttribute in definition)) { - definition[idAttribute] = void 0; - } - return definition; - } - function defineCollection(collection) { - if (typeof collection === 'function') { - this.Collection = collection; - this.Collection.prototype.model = this; - } - else { - this.Collection.define(collection || {}); - } - } - Object.defineProperties(Date, { - microsoft: { - get: function () { - return new typespec_1.ChainableAttributeSpec({ - type: Date, - _attribute: attributes_1.MSDateType - }); - } - }, - timestamp: { - get: function () { - return new typespec_1.ChainableAttributeSpec({ - type: Date, - _attribute: attributes_1.TimestampType - }); - } - } - }); - Number.integer = function (x) { return x ? Math.round(x) : 0; }; - Number.integer._attribute = attributes_1.NumericType; - if (typeof window !== 'undefined') { - window.Integer = Number.integer; - } - function createSharedTypeSpec(Constructor, Attribute) { - Constructor.hasOwnProperty('shared') || - Object.defineProperty(Constructor, 'shared', { - get: function () { - return new typespec_1.ChainableAttributeSpec({ - value: null, - type: Constructor, - _attribute: Attribute - }); - } - }); - } - exports.createSharedTypeSpec = createSharedTypeSpec; - - -/***/ }, -/* 12 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - var object_plus_1 = __webpack_require__(2); - var transactions_1 = __webpack_require__(8); - var trigger3 = object_plus_1.eventsApi.trigger3, assign = object_plus_1.tools.assign, isEmpty = object_plus_1.tools.isEmpty, log = object_plus_1.tools.log, free = transactions_1.transactionApi.free, aquire = transactions_1.transactionApi.aquire, commit = transactions_1.transactionApi.commit, _begin = transactions_1.transactionApi.begin, _markAsDirty = transactions_1.transactionApi.markAsDirty; - var _cidCounter = 0; - var Record = (function (_super) { - __extends(Record, _super); - function Record(a_values, a_options) { - var _this = this; - _super.call(this, _cidCounter++); - this.attributes = {}; - var options = a_options || {}, values = (options.parse ? this.parse(a_values, options) : a_values) || {}; - var attributes = options.clone ? cloneAttributes(this, values) : this.defaults(values); - this.forEachAttr(attributes, function (value, key, attr) { - var next = attributes[key] = attr.transform(value, options, void 0, _this); - attr.handleChange(next, void 0, _this); - }); - this.attributes = this._previousAttributes = attributes; - this.initialize(a_values, a_options); - if (this._localEvents) - this._localEvents.subscribe(this, this); - } - Record.define = function (protoProps, staticProps) { - return transactions_1.Transactional.define(protoProps, staticProps); - }; - Record.defaults = function (attrs) { - return this.extend({ attributes: attrs }); - }; - Record.prototype.previousAttributes = function () { return new this.Attributes(this._previousAttributes); }; - Object.defineProperty(Record.prototype, "_state", { - get: function () { return this.attributes; }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Record.prototype, "changed", { - get: function () { - var changed = this._changedAttributes; - if (!changed) { - var prev = this._previousAttributes; - changed = {}; - var _a = this, _attributes = _a._attributes, attributes = _a.attributes; - for (var _i = 0, _b = this._keys; _i < _b.length; _i++) { - var key = _b[_i]; - var value = attributes[key]; - if (_attributes[key].isChanged(value, prev[key])) { - changed[key] = value; - } - } - this._changedAttributes = changed; - } - return changed; - }, - enumerable: true, - configurable: true - }); - Record.prototype.changedAttributes = function (diff) { - if (!diff) - return this.hasChanged() ? assign({}, this.changed) : false; - var val, changed = false, old = this._transaction ? this._previousAttributes : this.attributes, attrSpecs = this._attributes; - for (var attr in diff) { - if (!attrSpecs[attr].isChanged(old[attr], (val = diff[attr]))) - continue; - (changed || (changed = {}))[attr] = val; - } - return changed; - }; - Record.prototype.hasChanged = function (key) { - var _previousAttributes = this._previousAttributes; - if (!_previousAttributes) - return false; - return key ? - this._attributes[key].isChanged(this.attributes[key], _previousAttributes[key]) : - !isEmpty(this.changed); - }; - Record.prototype.previous = function (key) { - if (key) { - var _previousAttributes = this._previousAttributes; - if (_previousAttributes) - return _previousAttributes[key]; - } - return null; - }; - Record.prototype.isNew = function () { - return this.id == null; - }; - Record.prototype.has = function (key) { - return this[key] != void 0; - }; - Record.prototype.unset = function (key, options) { - this.set(key, void 0, options); - return this; - }; - Record.prototype.clear = function (options) { - var _this = this; - var nullify = options && options.nullify; - this.transaction(function () { - _this.forEachAttr(_this.attributes, function (value, key) { return _this[key] = nullify ? null : void 0; }); - }, options); - return this; - }; - Record.prototype.getOwner = function () { - var owner = this._owner; - return this._ownerKey ? owner : owner && owner._owner; - }; - Object.defineProperty(Record.prototype, "id", { - get: function () { return this.attributes[this.idAttribute]; }, - set: function (x) { setAttribute(this, this.idAttribute, x); }, - enumerable: true, - configurable: true - }); - Record.prototype.Attributes = function (x) { this.id = x.id; }; - Record.prototype.forEachAttr = function (attrs, iteratee) { - var _attributes = this._attributes; - var unknown; - for (var name_1 in attrs) { - var spec = _attributes[name_1]; - if (spec) { - iteratee(attrs[name_1], name_1, spec); - } - else { - unknown || (unknown = []); - unknown.push("'" + name_1 + "'"); - } - } - if (unknown) { - this._log('warn', "attributes " + unknown.join(', ') + " are not defined", attrs); - } - }; - Record.prototype.each = function (iteratee, context) { - var fun = arguments.length === 2 ? function (v, k) { return iteratee.call(context, v, k); } : iteratee, _a = this, attributes = _a.attributes, _keys = _a._keys; - for (var _i = 0, _keys_1 = _keys; _i < _keys_1.length; _i++) { - var key = _keys_1[_i]; - var value = attributes[key]; - if (value !== void 0) - fun(value, key); - } - }; - Record.prototype._toJSON = function () { return {}; }; - Record.prototype._parse = function (data) { return data; }; - Record.prototype.defaults = function (values) { return {}; }; - Record.prototype.initialize = function (values, options) { }; - Record.prototype.clone = function (options) { - if (options === void 0) { options = {}; } - var copy = new this.constructor(this.attributes, { clone: true }); - if (options.pinStore) - copy._defaultStore = this.getStore(); - return copy; - }; - Record.prototype.deepClone = function () { return this.clone(); }; - ; - Record.prototype._validateNested = function (errors) { - var _this = this; - var length = 0; - this.forEachAttr(this.attributes, function (value, name, attribute) { - var error = attribute.validate(_this, value, name); - if (error) { - errors[name] = error; - length++; - } - }); - return length; - }; - Record.prototype.get = function (key) { - return this[key]; - }; - Record.prototype.toJSON = function () { - var _this = this; - var json = {}; - this.forEachAttr(this.attributes, function (value, key, _a) { - var toJSON = _a.toJSON; - if (toJSON && value !== void 0) { - var asJson = toJSON.call(_this, value, key); - if (asJson !== void 0) - json[key] = asJson; - } - }); - return json; - }; - Record.prototype.parse = function (data, options) { - return this._parse(data); - }; - Record.prototype.set = function (a, b, c) { - if (typeof a === 'string') { - if (c) { - return _super.prototype.set.call(this, (_a = {}, _a[a] = b, _a), c); - } - else { - setAttribute(this, a, b); - return this; - } - } - else { - return _super.prototype.set.call(this, a, b); - } - var _a; - }; - Record.prototype.deepSet = function (name, value, options) { - var _this = this; - this.transaction(function () { - var path = name.split('.'), l = path.length - 1, attr = path[l]; - var model = _this; - for (var i = 0; i < l; i++) { - var key = path[i]; - var next = model.get ? model.get(key) : model[key]; - if (!next) { - var attrSpecs = model._attributes; - if (attrSpecs) { - var newModel = attrSpecs[key].create(); - if (options && options.nullify && newModel._attributes) { - newModel.clear(options); - } - model[key] = next = newModel; - } - else - return; - } - model = next; - } - if (model.set) { - model.set(attr, value, options); - } - else { - model[attr] = value; - } - }); - return this; - }; - Record.prototype.transaction = function (fun, options) { - if (options === void 0) { options = {}; } - var isRoot = begin(this); - fun.call(this, this); - isRoot && commit(this); - }; - Record.prototype._createTransaction = function (a_values, options) { - var _this = this; - if (options === void 0) { options = {}; } - var isRoot = begin(this), changes = [], nested = [], attributes = this.attributes, values = options.parse ? this.parse(a_values, options) : a_values; - if (Object.getPrototypeOf(values) === Object.prototype) { - this.forEachAttr(values, function (value, key, attr) { - var prev = attributes[key]; - var update; - if (update = attr.canBeUpdated(prev, value, options)) { - var nestedTransaction = prev._createTransaction(update, options); - if (nestedTransaction) { - nested.push(nestedTransaction); - if (attr.propagateChanges) - changes.push(key); - } - return; - } - var next = attr.transform(value, options, prev, _this); - attributes[key] = next; - if (attr.isChanged(next, prev)) { - changes.push(key); - attr.handleChange(next, prev, _this); - } - }); - } - else { - this._log('error', 'incompatible argument type', values); - } - if (changes.length && markAsDirty(this, options)) { - return new RecordTransaction(this, isRoot, nested, changes); - } - for (var _i = 0, nested_1 = nested; _i < nested_1.length; _i++) { - var pendingTransaction = nested_1[_i]; - pendingTransaction.commit(this); - } - isRoot && commit(this); - }; - Record.prototype._onChildrenChange = function (child, options) { - var _ownerKey = child._ownerKey, attribute = this._attributes[_ownerKey]; - if (!attribute || attribute.propagateChanges) - this.forceAttributeChange(_ownerKey, options); - }; - Record.prototype.forceAttributeChange = function (key, options) { - if (options === void 0) { options = {}; } - var isRoot = begin(this); - if (markAsDirty(this, options)) { - trigger3(this, 'change:' + key, this, this.attributes[key], options); - } - isRoot && commit(this); - }; - Object.defineProperty(Record.prototype, "collection", { - get: function () { - return this._ownerKey ? null : this._owner; - }, - enumerable: true, - configurable: true - }); - Record.prototype.dispose = function () { - var _this = this; - this.forEachAttr(this.attributes, function (value, key) { - if (value && _this === value._owner) { - value.dispose(); - } - }); - _super.prototype.dispose.call(this); - }; - Record.prototype._log = function (level, text, value) { - object_plus_1.tools.log[level](("[Model Update] " + this.getClassName() + ": ") + text, value, 'Attributes spec:', this._attributes); - }; - Record.prototype.getClassName = function () { - return _super.prototype.getClassName.call(this) || 'Model'; - }; - Record = __decorate([ - object_plus_1.define({ - cidPrefix: 'm', - _changeEventName: 'change', - idAttribute: 'id', - _keys: ['id'] - }) - ], Record); - return Record; - }(transactions_1.Transactional)); - exports.Record = Record; - ; - function begin(record) { - if (_begin(record)) { - record._previousAttributes = new record.Attributes(record.attributes); - record._changedAttributes = null; - return true; - } - return false; - } - function markAsDirty(record, options) { - if (record._changedAttributes) { - record._changedAttributes = null; - } - return _markAsDirty(record, options); - } - function cloneAttributes(record, a_attributes) { - var attributes = new record.Attributes(a_attributes); - record.forEachAttr(attributes, function (value, name, attr) { - attributes[name] = attr.clone(value); - }); - return attributes; - } - function setAttribute(record, name, value) { - var isRoot = begin(record), options = {}, attributes = record.attributes, spec = record._attributes[name], prev = attributes[name]; - var update; - if (update = spec.canBeUpdated(prev, value, options)) { - var nestedTransaction = prev._createTransaction(update, options); - if (nestedTransaction) { - nestedTransaction.commit(record); - if (spec.propagateChanges) { - markAsDirty(record, options); - trigger3(record, 'change:' + name, record, prev, options); - } - } - } - else { - var next = spec.transform(value, options, prev, record); - attributes[name] = next; - if (spec.isChanged(next, prev)) { - spec.handleChange(next, prev, record); - markAsDirty(record, options); - trigger3(record, 'change:' + name, record, next, options); - } - } - isRoot && commit(record); - } - exports.setAttribute = setAttribute; - var RecordTransaction = (function () { - function RecordTransaction(object, isRoot, nested, changes) { - this.object = object; - this.isRoot = isRoot; - this.nested = nested; - this.changes = changes; - } - RecordTransaction.prototype.commit = function (initiator) { - var _a = this, nested = _a.nested, object = _a.object, changes = _a.changes; - for (var _i = 0, nested_2 = nested; _i < nested_2.length; _i++) { - var transaction = nested_2[_i]; - transaction.commit(object); - } - var attributes = object.attributes, _isDirty = object._isDirty; - for (var _b = 0, changes_1 = changes; _b < changes_1.length; _b++) { - var key = changes_1[_b]; - trigger3(object, 'change:' + key, object, attributes[key], _isDirty); - } - this.isRoot && commit(object, initiator); - }; - return RecordTransaction; - }()); - - -/***/ }, -/* 13 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var attributes_1 = __webpack_require__(14); - var object_plus_1 = __webpack_require__(2); - var typespec_1 = __webpack_require__(20); - var traversable_1 = __webpack_require__(10); - var defaults = object_plus_1.tools.defaults, isValidJSON = object_plus_1.tools.isValidJSON, transform = object_plus_1.tools.transform, log = object_plus_1.tools.log, EventMap = object_plus_1.eventsApi.EventMap; - function compile(rawSpecs, baseAttributes) { - var myAttributes = transform({}, rawSpecs, createAttribute), allAttributes = defaults({}, myAttributes, baseAttributes), Attributes = createCloneCtor(allAttributes), mixin = { - Attributes: Attributes, - _attributes: new Attributes(allAttributes), - properties: transform({}, myAttributes, function (x) { return x.createPropertyDescriptor(); }), - defaults: createDefaults(allAttributes), - _toJSON: createToJSON(allAttributes), - _localEvents: createEventMap(myAttributes), - _keys: Object.keys(allAttributes) - }; - var _parse = createParse(myAttributes, allAttributes); - if (_parse) { - mixin._parse = _parse; - } - if (!log.level) { - mixin.forEachAttr = createForEach(allAttributes); - } - return mixin; - } - exports.compile = compile; - function createAttribute(spec, name) { - return attributes_1.GenericAttribute.create(typespec_1.toAttributeDescriptor(spec), name); - } - function createEventMap(attrSpecs) { - var events; - for (var key in attrSpecs) { - var attribute = attrSpecs[key], _onChange = attribute.options._onChange; - if (_onChange) { - events || (events = new EventMap()); - events.addEvent('change:' + key, typeof _onChange === 'string' ? - createWatcherFromRef(_onChange, key) : - wrapWatcher(_onChange, key)); - } - } - return events; - } - function wrapWatcher(watcher, key) { - return function (record, value) { - watcher.call(record, value, key); - }; - } - function createWatcherFromRef(ref, key) { - var _a = new traversable_1.CompiledReference(ref, true), local = _a.local, resolve = _a.resolve, tail = _a.tail; - return local ? - function (record, value) { - record[tail](value, key); - } : - function (record, value) { - resolve(record)[tail](value, key); - }; - } - function createForEach(attrSpecs) { - var statements = ['var v, _a=this._attributes;']; - for (var name_1 in attrSpecs) { - statements.push("( v = a." + name_1 + " ) === void 0 || f( v, \"" + name_1 + "\", _a." + name_1 + " );"); - } - return new Function('a', 'f', statements.join('')); - } - exports.createForEach = createForEach; - function createCloneCtor(attrSpecs) { - var statements = []; - for (var name_2 in attrSpecs) { - statements.push("this." + name_2 + " = x." + name_2 + ";"); - } - var CloneCtor = new Function("x", statements.join('')); - CloneCtor.prototype = Object.prototype; - return CloneCtor; - } - exports.createCloneCtor = createCloneCtor; - function createDefaults(attrSpecs) { - var assign_f = ['var v;'], create_f = []; - function appendExpr(name, expr) { - assign_f.push("this." + name + " = ( v = a." + name + " ) === void 0 ? " + expr + " : v;"); - create_f.push("this." + name + " = " + expr + ";"); - } - for (var name_3 in attrSpecs) { - var attrSpec = attrSpecs[name_3], value = attrSpec.value, type = attrSpec.type; - if (value === void 0 && type) { - appendExpr(name_3, "i." + name_3 + ".create()"); - } - else { - if (isValidJSON(value)) { - appendExpr(name_3, JSON.stringify(value)); - } - else if (value === void 0) { - appendExpr(name_3, 'void 0'); - } - else { - appendExpr(name_3, "i." + name_3 + ".value"); - } - } - } - var CreateDefaults = new Function('i', create_f.join('')), AssignDefaults = new Function('a', 'i', assign_f.join('')); - CreateDefaults.prototype = AssignDefaults.prototype = Object.prototype; - return function (attrs) { - return attrs ? new AssignDefaults(attrs, this._attributes) : new CreateDefaults(this._attributes); - }; - } - function createParse(allAttrSpecs, attrSpecs) { - var statements = ['var a=this._attributes;'], create = false; - for (var name_4 in allAttrSpecs) { - var local = attrSpecs[name_4]; - if (local && local.parse) - create = true; - if (allAttrSpecs[name_4].parse) { - var s = "r." + name_4 + " === void 0 ||( r." + name_4 + " = a." + name_4 + ".parse.call( this, r." + name_4 + ", \"" + name_4 + "\") );"; - statements.push(s); - } - } - if (create) { - statements.push('return r;'); - return new Function('r', statements.join('')); - } - } - function createToJSON(attrSpecs) { - var statements = ["var json = {},v=this.attributes,a=this._attributes;"]; - for (var key in attrSpecs) { - var toJSON = attrSpecs[key].toJSON; - if (toJSON) { - statements.push("json." + key + " = a." + key + ".toJSON.call( this, v." + key + ", '" + key + "' );"); - } - } - statements.push("return json;"); - return new Function(statements.join('')); - } - - -/***/ }, -/* 14 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; - } - __export(__webpack_require__(15)); - __export(__webpack_require__(16)); - __export(__webpack_require__(17)); - __export(__webpack_require__(18)); - __export(__webpack_require__(19)); - - -/***/ }, -/* 15 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var transaction_1 = __webpack_require__(12); - var object_plus_1 = __webpack_require__(2); - var notEqual = object_plus_1.tools.notEqual, assign = object_plus_1.tools.assign; - var GenericAttribute = (function () { - function GenericAttribute(name, a_options) { - this.name = name; - this.getHook = null; - var options = this.options = assign({ getHooks: [], transforms: [], changeHandlers: [] }, a_options); - options.getHooks = options.getHooks.slice(); - options.transforms = options.transforms.slice(); - options.changeHandlers = options.changeHandlers.slice(); - var value = options.value, type = options.type, parse = options.parse, toJSON = options.toJSON, changeEvents = options.changeEvents, validate = options.validate, getHooks = options.getHooks, transforms = options.transforms, changeHandlers = options.changeHandlers; - this.value = value; - this.type = type; - this.propagateChanges = changeEvents !== false; - this.parse = parse; - this.toJSON = toJSON === void 0 ? this.toJSON : toJSON; - this.validate = validate || this.validate; - transforms.unshift(this.convert); - if (this.get) - getHooks.unshift(this.get); - this.initialize.call(this, options); - if (getHooks.length) { - this.getHook = getHooks.reduce(chainGetHooks); - } - if (transforms.length) { - this.transform = transforms.reduce(chainTransforms); - } - if (changeHandlers.length) { - this.handleChange = changeHandlers.reduce(chainChangeHandlers); - } - } - GenericAttribute.create = function (options, name) { - var type = options.type, AttributeCtor = options._attribute || (type ? type._attribute : GenericAttribute); - return new AttributeCtor(name, options); - }; - GenericAttribute.prototype.canBeUpdated = function (prev, next, options) { }; - GenericAttribute.prototype.transform = function (value, options, prev, model) { return value; }; - GenericAttribute.prototype.convert = function (value, options, prev, model) { return value; }; - GenericAttribute.prototype.isChanged = function (a, b) { - return notEqual(a, b); - }; - GenericAttribute.prototype.handleChange = function (next, prev, model) { }; - GenericAttribute.prototype.create = function () { return new this.type(); }; - GenericAttribute.prototype.clone = function (value) { - if (value && typeof value === 'object') { - if (value.clone) - return value.clone(); - var proto = Object.getPrototypeOf(value); - if (proto === Object.prototype || proto === Array.prototype) { - return JSON.parse(JSON.stringify(value)); - } - } - return value; - }; - GenericAttribute.prototype.validate = function (record, value, key) { }; - GenericAttribute.prototype.toJSON = function (value, key) { - return value && value.toJSON ? value.toJSON() : value; - }; - GenericAttribute.prototype.createPropertyDescriptor = function () { - var _a = this, name = _a.name, getHook = _a.getHook; - if (name !== 'id') { - return { - set: function (value) { - transaction_1.setAttribute(this, name, value); - }, - get: getHook ? - function () { - return getHook.call(this, this.attributes[name], name); - } : - function () { - return this.attributes[name]; - } - }; - } - }; - GenericAttribute.prototype.initialize = function (name, options) { }; - GenericAttribute.prototype._log = function (level, text, value, record) { - object_plus_1.tools.log[level](("[Attribute Update] " + record.getClassName() + "." + this.name + ": ") + text, value, 'Attributes spec:', record._attributes); - }; - return GenericAttribute; - }()); - exports.GenericAttribute = GenericAttribute; - transaction_1.Record.prototype._attributes = { id: GenericAttribute.create({ value: void 0 }, 'id') }; - transaction_1.Record.prototype.defaults = function (attrs) { - if (attrs === void 0) { attrs = {}; } - return { id: attrs.id }; - }; - function chainChangeHandlers(prevHandler, nextHandler) { - return function (next, prev, model) { - prevHandler.call(this, next, prev, model); - nextHandler.call(this, next, prev, model); - }; - } - function chainGetHooks(prevHook, nextHook) { - return function (value, name) { - return nextHook.call(prevHook.call(value, name), name); - }; - } - function chainTransforms(prevTransform, nextTransform) { - return function (value, options, prev, model) { - return nextTransform.call(this, prevTransform.call(this, value, options, prev, model), options, prev, model); - }; - } - - -/***/ }, -/* 16 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - var transaction_1 = __webpack_require__(12); - var generic_1 = __webpack_require__(15); - var transactions_1 = __webpack_require__(8); - var free = transactions_1.transactionApi.free, aquire = transactions_1.transactionApi.aquire; - var TransactionalType = (function (_super) { - __extends(TransactionalType, _super); - function TransactionalType() { - _super.apply(this, arguments); - } - TransactionalType.prototype.canBeUpdated = function (prev, next, options) { - if (prev && next != null) { - if (next instanceof this.type) { - if (options.merge) - return next._state; - } - else { - return next; - } - } - }; - TransactionalType.prototype.convert = function (value, options, prev, record) { - if (value == null) - return value; - if (value instanceof this.type) { - if (value._shared === 1) { - this._log('error', 'aggregated attribute is assigned with shared collection type', value, record); - } - return options.merge ? value.clone() : value; - } - return this.type.create(value, options); - }; - TransactionalType.prototype.validate = function (record, value) { - var error = value && value.validationError; - if (error) - return error; - }; - TransactionalType.prototype.create = function () { - return this.type.create(); - }; - TransactionalType.prototype.initialize = function (options) { - options.changeHandlers.unshift(this._handleChange); - }; - TransactionalType.prototype._handleChange = function (next, prev, record) { - prev && free(record, prev); - if (next && !aquire(record, next, this.name)) { - this._log('error', 'aggregated attribute assigned with object which is aggregated somewhere else', next, record); - } - }; - return TransactionalType; - }(generic_1.GenericAttribute)); - exports.TransactionalType = TransactionalType; - transaction_1.Record._attribute = TransactionalType; - - -/***/ }, -/* 17 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - var generic_1 = __webpack_require__(15); - var DateProto = Date.prototype; - var DateType = (function (_super) { - __extends(DateType, _super); - function DateType() { - _super.apply(this, arguments); - } - DateType.prototype.convert = function (value) { - if (value == null || value instanceof Date) - return value; - var date = new Date(value); - if (isNaN(+date)) - this._log('warn', 'assigned with Invalid Date', value, arguments[3]); - return date; - }; - DateType.prototype.validate = function (model, value, name) { - if (value != null && isNaN(+value)) - return name + ' is Invalid Date'; - }; - DateType.prototype.toJSON = function (value) { return value && value.toISOString(); }; - DateType.prototype.isChanged = function (a, b) { return (a && +a) !== (b && +b); }; - DateType.prototype.clone = function (value) { return value && new Date(+value); }; - return DateType; - }(generic_1.GenericAttribute)); - exports.DateType = DateType; - Date._attribute = DateType; - var msDatePattern = /\/Date\(([0-9]+)\)\//; - var MSDateType = (function (_super) { - __extends(MSDateType, _super); - function MSDateType() { - _super.apply(this, arguments); - } - MSDateType.prototype.convert = function (value) { - if (typeof value === 'string') { - var msDate = msDatePattern.exec(value); - if (msDate) { - return new Date(Number(msDate[1])); - } - } - return DateType.prototype.convert.apply(this, arguments); - }; - MSDateType.prototype.toJSON = function (value) { return value && "/Date(" + value.getTime() + ")/"; }; - return MSDateType; - }(DateType)); - exports.MSDateType = MSDateType; - var TimestampType = (function (_super) { - __extends(TimestampType, _super); - function TimestampType() { - _super.apply(this, arguments); - } - TimestampType.prototype.toJSON = function (value) { return value.getTime(); }; - return TimestampType; - }(DateType)); - exports.TimestampType = TimestampType; - function supportsDate(date) { - return !isNaN((new Date(date)).getTime()); - } - if (!supportsDate('2011-11-29T15:52:30.5') || - !supportsDate('2011-11-29T15:52:30.52') || - !supportsDate('2011-11-29T15:52:18.867') || - !supportsDate('2011-11-29T15:52:18.867Z') || - !supportsDate('2011-11-29T15:52:18.867-03:30')) { - DateType.prototype.convert = function (value) { - return value == null || value instanceof Date ? value : new Date(safeParseDate(value)); - }; - } - var numericKeys = [1, 4, 5, 6, 7, 10, 11], isoDatePattern = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/; - function safeParseDate(date) { - var timestamp, struct, minutesOffset = 0; - if ((struct = isoDatePattern.exec(date))) { - for (var i = 0, k; (k = numericKeys[i]); ++i) { - struct[k] = +struct[k] || 0; - } - struct[2] = (+struct[2] || 1) - 1; - struct[3] = +struct[3] || 1; - if (struct[8] !== 'Z' && struct[9] !== undefined) { - minutesOffset = struct[10] * 60 + struct[11]; - if (struct[9] === '+') { - minutesOffset = 0 - minutesOffset; - } - } - timestamp = - Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]); - } - else { - timestamp = Date.parse(date); - } - return timestamp; - } - - -/***/ }, -/* 18 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - var generic_1 = __webpack_require__(15); - var ConstructorType = (function (_super) { - __extends(ConstructorType, _super); - function ConstructorType() { - _super.apply(this, arguments); - } - ConstructorType.prototype.convert = function (value) { - return value == null || value instanceof this.type ? value : new this.type(value); - }; - ConstructorType.prototype.clone = function (value) { - return value.clone ? value.clone() : this.convert(JSON.parse(JSON.stringify(value))); - }; - return ConstructorType; - }(generic_1.GenericAttribute)); - Function.prototype._attribute = ConstructorType; - var PrimitiveType = (function (_super) { - __extends(PrimitiveType, _super); - function PrimitiveType() { - _super.apply(this, arguments); - } - PrimitiveType.prototype.create = function () { return this.type(); }; - PrimitiveType.prototype.toJSON = function (value) { return value; }; - PrimitiveType.prototype.convert = function (value) { return value == null ? value : this.type(value); }; - PrimitiveType.prototype.isChanged = function (a, b) { return a !== b; }; - PrimitiveType.prototype.clone = function (value) { return value; }; - return PrimitiveType; - }(generic_1.GenericAttribute)); - exports.PrimitiveType = PrimitiveType; - Boolean._attribute = String._attribute = PrimitiveType; - var NumericType = (function (_super) { - __extends(NumericType, _super); - function NumericType() { - _super.apply(this, arguments); - } - NumericType.prototype.convert = function (value) { - var num = value == null ? value : this.type(value); - if (num !== num) - this._log('warn', 'assigned with Invalid Number', value, arguments[3]); - return num; - }; - NumericType.prototype.validate = function (model, value, name) { - if (value != null && !isFinite(value)) { - return name + ' is not valid number'; - } - }; - return NumericType; - }(PrimitiveType)); - exports.NumericType = NumericType; - Number._attribute = NumericType; - var ArrayType = (function (_super) { - __extends(ArrayType, _super); - function ArrayType() { - _super.apply(this, arguments); - } - ArrayType.prototype.toJSON = function (value) { return value; }; - ArrayType.prototype.convert = function (value) { - if (value == null || Array.isArray(value)) - return value; - this._log('warn', 'assigned with non-array', value, arguments[3]); - return []; - }; - return ArrayType; - }(generic_1.GenericAttribute)); - exports.ArrayType = ArrayType; - Array._attribute = ArrayType; - - -/***/ }, -/* 19 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - var generic_1 = __webpack_require__(15); - var transactions_1 = __webpack_require__(8); - var object_plus_1 = __webpack_require__(2); - var on = object_plus_1.eventsApi.on, off = object_plus_1.eventsApi.off, free = transactions_1.transactionApi.free, aquire = transactions_1.transactionApi.aquire; - var SharedRecordType = (function (_super) { - __extends(SharedRecordType, _super); - function SharedRecordType() { - _super.apply(this, arguments); - } - SharedRecordType.prototype.clone = function (value) { - return value; - }; - SharedRecordType.prototype.canBeUpdated = function (prev, next, options) { - if (prev && next != null) { - if (next instanceof this.type) { - if (options.merge) - return next._state; - } - else { - return next; - } - } - }; - SharedRecordType.prototype.convert = function (value, options, prev, record) { - return value == null || value instanceof this.type ? value : this.type.create(value, options); - }; - SharedRecordType.prototype.validate = function (model, value, name) { }; - SharedRecordType.prototype.create = function () { - return null; - }; - SharedRecordType.prototype._handleChange = function (next, prev, record) { - prev && off(prev, prev._changeEventName, this._onChange, record); - next && on(next, next._changeEventName, this._onChange, record); - }; - SharedRecordType.prototype.initialize = function (options) { - this.toJSON = null; - if (this.propagateChanges) { - var attribute_1 = this; - this._onChange = function (child, options, initiator) { - this === initiator || this.forceAttributeChange(attribute_1.name, options); - }; - options.changeHandlers.unshift(this._handleChange); - } - }; - return SharedRecordType; - }(generic_1.GenericAttribute)); - exports.SharedRecordType = SharedRecordType; - - -/***/ }, -/* 20 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var transactions_1 = __webpack_require__(8); - var object_plus_1 = __webpack_require__(2); - var assign = object_plus_1.tools.assign; - var ChainableAttributeSpec = (function () { - function ChainableAttributeSpec(options) { - if (options === void 0) { options = {}; } - this.options = { getHooks: [], transforms: [], changeHandlers: [] }; - assign(this.options, options); - } - ChainableAttributeSpec.prototype.check = function (check, error) { - function validate(model, value, name) { - if (!check.call(model, value, name)) { - return error || check.error || name + ' is not valid'; - } - } - var prev = this.options.validate; - this.options.validate = prev ? (function (model, value, name) { - return prev(model, value, name) || validate(model, value, name); - }) : validate; - return this; - }; - ChainableAttributeSpec.prototype.watcher = function (ref) { - this.options._onChange = ref; - return this; - }; - ChainableAttributeSpec.prototype.parse = function (fun) { - this.options.parse = fun; - return this; - }; - ChainableAttributeSpec.prototype.toJSON = function (fun) { - this.options.toJSON = fun || null; - return this; - }; - ChainableAttributeSpec.prototype.get = function (fun) { - this.options.getHooks.push(fun); - return this; - }; - ChainableAttributeSpec.prototype.set = function (fun) { - this.options.transforms.push(function (next, options, prev, model) { - if (this.isChanged(next, prev)) { - var changed = fun.call(model, next, this.name); - return changed === void 0 ? prev : this.convert(changed, options, prev, model); - } - return prev; - }); - return this; - }; - ChainableAttributeSpec.prototype.changeEvents = function (events) { - this.options.changeEvents = events; - return this; - }; - ChainableAttributeSpec.prototype.events = function (map) { - var eventMap = new object_plus_1.EventMap(map); - this.options.changeHandlers.push(function (next, prev, record) { - prev && prev.trigger && eventMap.unsubscribe(record, prev); - next && next.trigger && eventMap.subscribe(record, next); - }); - return this; - }; - Object.defineProperty(ChainableAttributeSpec.prototype, "has", { - get: function () { return this; }, - enumerable: true, - configurable: true - }); - ChainableAttributeSpec.prototype.value = function (x) { - this.options.value = x; - return this; - }; - return ChainableAttributeSpec; - }()); - exports.ChainableAttributeSpec = ChainableAttributeSpec; - Function.prototype.value = function (x) { - return new ChainableAttributeSpec({ type: this, value: x }); - }; - Object.defineProperty(Function.prototype, 'has', { - get: function () { - return this._has || new ChainableAttributeSpec({ type: this }); - }, - set: function (value) { this._has = value; } - }); - function toAttributeDescriptor(spec) { - var attrSpec; - if (typeof spec === 'function') { - attrSpec = new ChainableAttributeSpec({ type: spec }); - } - else if (spec && spec instanceof ChainableAttributeSpec) { - attrSpec = spec; - } - else { - var type = inferType(spec); - if (type && type.prototype instanceof transactions_1.Transactional) { - attrSpec = type.shared.value(spec); - } - else { - attrSpec = new ChainableAttributeSpec({ type: type, value: spec }); - } - } - return attrSpec.options; - } - exports.toAttributeDescriptor = toAttributeDescriptor; - function inferType(value) { - switch (typeof value) { - case 'number': - return Number; - case 'string': - return String; - case 'boolean': - return Boolean; - case 'undefined': - return void 0; - case 'object': - return value ? value.constructor : void 0; - } - } - - -/***/ }, -/* 21 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var transactions_1 = __webpack_require__(8); - var object_plus_1 = __webpack_require__(2); - var EventMap = object_plus_1.eventsApi.EventMap, trigger2 = object_plus_1.eventsApi.trigger2, trigger3 = object_plus_1.eventsApi.trigger3, on = object_plus_1.eventsApi.on, off = object_plus_1.eventsApi.off, commit = transactions_1.transactionApi.commit, markAsDirty = transactions_1.transactionApi.markAsDirty, _aquire = transactions_1.transactionApi.aquire, _free = transactions_1.transactionApi.free; - function dispose(collection) { - var models = collection.models; - collection.models = []; - collection._byId = {}; - freeAll(collection, models); - return models; - } - exports.dispose = dispose; - function convertAndAquire(collection, attrs, options) { - var model = collection.model; - var record; - if (collection._shared) { - record = attrs instanceof model ? attrs : model.create(attrs, options); - if (collection._shared === 1) { - on(record, record._changeEventName, collection._onChildrenChange, collection); - } - } - else { - record = attrs instanceof model ? (options.merge ? attrs.clone() : attrs) : model.create(attrs, options); - if (!_aquire(collection, record)) { - var errors = collection._aggregationError || (collection._aggregationError = []); - errors.push(record); - } - } - var _itemEvents = collection._itemEvents; - _itemEvents && _itemEvents.subscribe(collection, record); - return record; - } - exports.convertAndAquire = convertAndAquire; - function free(owner, child) { - if (owner._shared) { - if (owner._shared === 1) { - off(child, child._changeEventName, owner._onChildrenChange, owner); - } - } - else { - _free(owner, child); - } - var _itemEvents = owner._itemEvents; - _itemEvents && _itemEvents.unsubscribe(owner, child); - } - exports.free = free; - function freeAll(collection, children) { - for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { - var child = children_1[_i]; - free(collection, child); - } - return children; - } - exports.freeAll = freeAll; - function sortElements(collection, options) { - var _comparator = collection._comparator; - if (_comparator && options.sort !== false) { - collection.models.sort(_comparator); - return true; - } - return false; - } - exports.sortElements = sortElements; - function addIndex(index, model) { - index[model.cid] = model; - var id = model.id; - if (id != null) { - index[id] = model; - } - } - exports.addIndex = addIndex; - function removeIndex(index, model) { - delete index[model.cid]; - var id = model.id; - if (id != null) { - delete index[id]; - } - } - exports.removeIndex = removeIndex; - function updateIndex(index, model) { - delete index[model.previous(model.idAttribute)]; - var id = model.id; - id == null || (index[id] = model); - } - exports.updateIndex = updateIndex; - var CollectionTransaction = (function () { - function CollectionTransaction(object, isRoot, added, removed, nested, sorted) { - this.object = object; - this.isRoot = isRoot; - this.added = added; - this.removed = removed; - this.nested = nested; - this.sorted = sorted; - } - CollectionTransaction.prototype.commit = function (initiator) { - var _a = this, nested = _a.nested, object = _a.object, _isDirty = object._isDirty; - for (var _i = 0, nested_1 = nested; _i < nested_1.length; _i++) { - var transaction = nested_1[_i]; - transaction.commit(object); - } - if (object._aggregationError) { - logAggregationError(object); - } - for (var _b = 0, nested_2 = nested; _b < nested_2.length; _b++) { - var transaction = nested_2[_b]; - trigger2(object, 'change', transaction.object, _isDirty); - } - var _c = this, added = _c.added, removed = _c.removed; - for (var _d = 0, added_1 = added; _d < added_1.length; _d++) { - var record = added_1[_d]; - trigger3(record, 'add', record, object, _isDirty); - trigger3(object, 'add', record, object, _isDirty); - } - for (var _e = 0, removed_1 = removed; _e < removed_1.length; _e++) { - var record = removed_1[_e]; - trigger3(record, 'remove', record, object, _isDirty); - trigger3(object, 'remove', record, object, _isDirty); - } - if (this.sorted) { - trigger2(object, 'sort', object, _isDirty); - } - if (added.length || removed.length) { - trigger2(object, 'update', object, _isDirty); - } - this.isRoot && commit(object, initiator); - }; - return CollectionTransaction; - }()); - exports.CollectionTransaction = CollectionTransaction; - function logAggregationError(collection) { - collection._log('error', 'added records already have an owner', collection._aggregationError); - collection._aggregationError = void 0; - } - exports.logAggregationError = logAggregationError; - - -/***/ }, -/* 22 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var transactions_1 = __webpack_require__(8); - var commons_1 = __webpack_require__(21); - var begin = transactions_1.transactionApi.begin, commit = transactions_1.transactionApi.commit, markAsDirty = transactions_1.transactionApi.markAsDirty; - function addTransaction(collection, items, options, merge) { - var isRoot = begin(collection), nested = []; - var added = appendElements(collection, items, nested, options, merge); - if (added.length || nested.length) { - var needSort = sortOrMoveElements(collection, added, options); - if (markAsDirty(collection, options)) { - return new commons_1.CollectionTransaction(collection, isRoot, added, [], nested, needSort); - } - if (collection._aggregationError) - commons_1.logAggregationError(collection); - } - isRoot && commit(collection); - } - exports.addTransaction = addTransaction; - ; - function sortOrMoveElements(collection, added, options) { - var at = options.at; - if (at != null) { - var length_1 = collection.models.length - added.length; - at = Number(at); - if (at < 0) - at += length_1 + 1; - if (at < 0) - at = 0; - if (at > length_1) - at = length_1; - moveElements(collection.models, at, added); - return false; - } - return commons_1.sortElements(collection, options); - } - function moveElements(source, at, added) { - for (var j = source.length - 1, i = j - added.length; i >= at; i--, j--) { - source[j] = source[i]; - } - for (i = 0, j = at; i < added.length; i++, j++) { - source[j] = added[i]; - } - } - function appendElements(collection, a_items, nested, a_options, forceMerge) { - var _byId = collection._byId, models = collection.models, merge = (forceMerge || a_options.merge) && !collection._shared, parse = a_options.parse, idAttribute = collection.model.prototype.idAttribute, prevLength = models.length; - for (var _i = 0, a_items_1 = a_items; _i < a_items_1.length; _i++) { - var item = a_items_1[_i]; - var model = item ? _byId[item[idAttribute]] || _byId[item.cid] : null; - if (model) { - if (merge && item !== model) { - var attrs = item.attributes || item; - var transaction = model._createTransaction(attrs, a_options); - transaction && nested.push(transaction); - if (model.hasChanged(idAttribute)) { - commons_1.updateIndex(_byId, model); - } - } - } - else { - model = commons_1.convertAndAquire(collection, item, a_options); - models.push(model); - commons_1.addIndex(_byId, model); - } - } - return models.slice(prevLength); - } - - -/***/ }, -/* 23 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var transactions_1 = __webpack_require__(8); - var commons_1 = __webpack_require__(21); - var begin = transactions_1.transactionApi.begin, commit = transactions_1.transactionApi.commit, markAsDirty = transactions_1.transactionApi.markAsDirty; - var silentOptions = { silent: true }; - function emptySetTransaction(collection, items, options, silent) { - var isRoot = begin(collection); - var added = _reallocateEmpty(collection, items, options); - if (added.length) { - var needSort = commons_1.sortElements(collection, options); - if (markAsDirty(collection, silent ? silentOptions : options)) { - return new commons_1.CollectionTransaction(collection, isRoot, added.slice(), [], [], needSort); - } - if (collection._aggregationError) - commons_1.logAggregationError(collection); - } - isRoot && commit(collection); - } - exports.emptySetTransaction = emptySetTransaction; - ; - function setTransaction(collection, items, options) { - var isRoot = begin(collection), nested = []; - var previous = collection.models, added = _reallocate(collection, items, nested, options); - var reusedCount = collection.models.length - added.length, removed = reusedCount < previous.length ? (reusedCount ? _garbageCollect(collection, previous) : - commons_1.freeAll(collection, previous)) : []; - var addedOrChanged = nested.length || added.length, sorted = (addedOrChanged && commons_1.sortElements(collection, options)) || added.length || options.sorted; - if (addedOrChanged || removed.length || sorted) { - if (markAsDirty(collection, options)) { - return new commons_1.CollectionTransaction(collection, isRoot, added, removed, nested, sorted); - } - if (collection._aggregationError) - commons_1.logAggregationError(collection); - } - isRoot && commit(collection); - } - exports.setTransaction = setTransaction; - ; - function _garbageCollect(collection, previous) { - var _byId = collection._byId, removed = []; - for (var _i = 0, previous_1 = previous; _i < previous_1.length; _i++) { - var record = previous_1[_i]; - if (!_byId[record.cid]) { - removed.push(record); - commons_1.free(collection, record); - } - } - return removed; - } - function _reallocate(collection, source, nested, options) { - var models = Array(source.length), _byId = {}, merge = (options.merge == null ? true : options.merge) && !collection._shared, _prevById = collection._byId, prevModels = collection.models, idAttribute = collection.model.prototype.idAttribute, toAdd = [], orderKept = true; - for (var i = 0, j = 0; i < source.length; i++) { - var item = source[i], model = null; - if (item) { - var id = item[idAttribute], cid = item.cid; - if (_byId[id] || _byId[cid]) - continue; - model = _prevById[id] || _prevById[cid]; - } - if (model) { - if (merge && item !== model) { - if (orderKept && prevModels[j] !== model) - orderKept = false; - var attrs = item.attributes || item; - var transaction = model._createTransaction(attrs, options); - transaction && nested.push(transaction); - } - } - else { - model = commons_1.convertAndAquire(collection, item, options); - toAdd.push(model); - } - models[j++] = model; - commons_1.addIndex(_byId, model); - } - models.length = j; - collection.models = models; - collection._byId = _byId; - if (!orderKept) - options.sorted = true; - return toAdd; - } - function _reallocateEmpty(self, source, options) { - var len = source ? source.length : 0, models = Array(len), _byId = {}, idAttribute = self.model.prototype.idAttribute; - for (var i = 0, j = 0; i < len; i++) { - var src = source[i]; - if (src && (_byId[src[idAttribute]] || _byId[src.cid])) { - continue; - } - var model = commons_1.convertAndAquire(self, src, options); - models[j++] = model; - commons_1.addIndex(_byId, model); - } - models.length = j; - self._byId = _byId; - return self.models = models; - } - - -/***/ }, -/* 24 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var commons_1 = __webpack_require__(21); - var object_plus_1 = __webpack_require__(2); - var transactions_1 = __webpack_require__(8); - var trigger2 = object_plus_1.eventsApi.trigger2, trigger3 = object_plus_1.eventsApi.trigger3, markAsDirty = transactions_1.transactionApi.markAsDirty, begin = transactions_1.transactionApi.begin, commit = transactions_1.transactionApi.commit; - function removeOne(collection, el, options) { - var model = collection.get(el); - if (model) { - var isRoot = begin(collection), models = collection.models; - models.splice(models.indexOf(model), 1); - commons_1.removeIndex(collection._byId, model); - var notify = markAsDirty(collection, options); - if (notify) { - trigger3(model, 'remove', model, collection, options); - trigger3(collection, 'remove', model, collection, options); - } - commons_1.free(collection, model); - notify && trigger2(collection, 'update', collection, options); - isRoot && commit(collection); - return model; - } - } - exports.removeOne = removeOne; - ; - function removeMany(collection, toRemove, options) { - var removed = _removeFromIndex(collection, toRemove); - if (removed.length) { - var isRoot = begin(collection); - _reallocate(collection, removed.length); - if (markAsDirty(collection, options)) { - var transaction = new commons_1.CollectionTransaction(collection, isRoot, [], removed, [], false); - transaction.commit(); - } - else { - isRoot && commit(collection); - } - } - return removed; - } - exports.removeMany = removeMany; - ; - function _removeFromIndex(collection, toRemove) { - var removed = Array(toRemove.length), _byId = collection._byId; - for (var i = 0, j = 0; i < toRemove.length; i++) { - var model = collection.get(toRemove[i]); - if (model) { - removed[j++] = model; - commons_1.removeIndex(_byId, model); - commons_1.free(collection, model); - } - } - removed.length = j; - return removed; - } - function _reallocate(collection, removed) { - var prev = collection.models, models = collection.models = Array(prev.length - removed), _byId = collection._byId; - for (var i = 0, j = 0; i < prev.length; i++) { - var model = prev[i]; - if (_byId[model.cid]) { - models[j++] = model; - } - } - models.length = j; - } - - -/***/ }, -/* 25 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - __webpack_require__(26); - __webpack_require__(28); - var store_1 = __webpack_require__(29); - exports.Store = store_1.Store; - - -/***/ }, -/* 26 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - var record_1 = __webpack_require__(11); - var commons_1 = __webpack_require__(27); - var record_2 = __webpack_require__(11); - var record_3 = __webpack_require__(11); - var RecordRefAttribute = (function (_super) { - __extends(RecordRefAttribute, _super); - function RecordRefAttribute() { - _super.apply(this, arguments); - } - RecordRefAttribute.prototype.toJSON = function (value) { - return value && typeof value === 'object' ? value.id : value; - }; - RecordRefAttribute.prototype.clone = function (value) { - return value && typeof value === 'object' ? value.id : value; - }; - RecordRefAttribute.prototype.isChanged = function (a, b) { - var aId = a && (a.id == null ? a : a.id), bId = b && (b.id == null ? b : b.id); - return aId !== bId; - }; - RecordRefAttribute.prototype.validate = function (model, value, name) { }; - return RecordRefAttribute; - }(record_1.GenericAttribute)); - record_2.Record.from = function from(masterCollection) { - var getMasterCollection = commons_1.parseReference(masterCollection); - var typeSpec = new record_3.ChainableAttributeSpec({ - value: null, - _attribute: RecordRefAttribute - }); - typeSpec - .get(function (objOrId, name) { - if (typeof objOrId === 'object') - return objOrId; - var collection = getMasterCollection(this); - var record = null; - if (collection && collection.length) { - record = collection.get(objOrId) || null; - this.attributes[name] = record; - record && this._attributes[name].handleChange(record, null, this); - } - return record; - }); - return typeSpec; - }; - - -/***/ }, -/* 27 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var traversable_1 = __webpack_require__(10); - function parseReference(collectionRef) { - switch (typeof collectionRef) { - case 'function': - return function (root) { return collectionRef.call(root); }; - case 'object': - return function () { return collectionRef; }; - case 'string': - var resolve = (new traversable_1.CompiledReference(collectionRef)).resolve; - return resolve; - } - } - exports.parseReference = parseReference; - - -/***/ }, -/* 28 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - var collection_1 = __webpack_require__(7); - var object_plus_1 = __webpack_require__(2); - var commons_1 = __webpack_require__(27); - var record_1 = __webpack_require__(11); - var fastDefaults = object_plus_1.tools.fastDefaults; - collection_1.Collection.subsetOf = function subsetOf(masterCollection) { - var SubsetOf = this._SubsetOf || (this._SubsetOf = defineSubsetCollection(this)), getMasterCollection = commons_1.parseReference(masterCollection), typeSpec = new record_1.ChainableAttributeSpec({ - type: SubsetOf - }); - typeSpec.get(function (refs) { - !refs || refs.resolvedWith || refs.resolve(getMasterCollection(this)); - return refs; - }); - return typeSpec; - }; - function subsetOptions(options) { - var subsetOptions = { parse: true }; - if (options) - fastDefaults(subsetOptions, options); - return subsetOptions; - } - function defineSubsetCollection(CollectionConstructor) { - var SubsetOfCollection = (function (_super) { - __extends(SubsetOfCollection, _super); - function SubsetOfCollection(recordsOrIds, options) { - _super.call(this, recordsOrIds, subsetOptions(options), 2); - this.resolvedWith = null; - } - Object.defineProperty(SubsetOfCollection.prototype, "_state", { - get: function () { return this.refs || this.models; }, - enumerable: true, - configurable: true - }); - SubsetOfCollection.prototype.add = function (elements, options) { - return _super.prototype.add.call(this, elements, subsetOptions(options)); - }; - SubsetOfCollection.prototype.reset = function (elements, options) { - return _super.prototype.reset.call(this, elements, subsetOptions(options)); - }; - SubsetOfCollection.prototype._createTransaction = function (elements, options) { - return _super.prototype._createTransaction.call(this, elements, subsetOptions(options)); - }; - SubsetOfCollection.prototype.toJSON = function () { - return this.refs ? - this.refs.map(function (objOrId) { return objOrId.id || objOrId; }) : - this.models.map(function (model) { return model.id; }); - }; - SubsetOfCollection.prototype._validateNested = function () { return 0; }; - SubsetOfCollection.prototype.clone = function (owner) { - var Ctor = this.constructor, copy = new Ctor([], { - model: this.model, - comparator: this.comparator - }); - if (this.resolvedWith) { - copy.resolvedWith = this.resolvedWith; - copy.reset(this.models, { silent: true }); - } - else { - copy.refs = this.refs; - } - return copy; - }; - SubsetOfCollection.prototype.parse = function (raw) { - var resolvedWith = this.resolvedWith, elements = Array.isArray(raw) ? raw : [raw], records = []; - if (resolvedWith) { - for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { - var element = elements_1[_i]; - var record = resolvedWith.get(element); - if (record) - records.push(record); - } - } - else if (elements.length) { - this.refs = elements; - } - return records; - }; - SubsetOfCollection.prototype.resolve = function (collection) { - if (collection && collection.length) { - this.resolvedWith = collection; - if (this.refs) { - this.reset(this.refs, { silent: true }); - this.refs = null; - } - } - return this; - }; - SubsetOfCollection.prototype.getModelIds = function () { return this.toJSON(); }; - SubsetOfCollection.prototype.toggle = function (modelOrId, val) { - return _super.prototype.toggle.call(this, this.resolvedWith.get(modelOrId), val); - }; - SubsetOfCollection.prototype.addAll = function () { - return this.reset(this.resolvedWith.models); - }; - SubsetOfCollection.prototype.toggleAll = function () { - return this.length ? this.reset() : this.addAll(); - }; - SubsetOfCollection = __decorate([ - object_plus_1.define({}) - ], SubsetOfCollection); - return SubsetOfCollection; - }(CollectionConstructor)); - return SubsetOfCollection; - } - - -/***/ }, -/* 29 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - var record_1 = __webpack_require__(11); - var transactions_1 = __webpack_require__(8); - var _store = null; - var Store = (function (_super) { - __extends(Store, _super); - function Store() { - _super.apply(this, arguments); - } - Store.prototype.getStore = function () { return this; }; - Store.prototype.get = function (name) { - var local = this[name]; - if (local || this === this._defaultStore) - return local; - return this._owner ? this._owner.get(name) : this._defaultStore.get(name); - }; - Object.defineProperty(Store, "global", { - get: function () { return _store; }, - set: function (store) { - if (_store) { - _store.dispose(); - } - transactions_1.Transactional.prototype._defaultStore = _store = store; - }, - enumerable: true, - configurable: true - }); - return Store; - }(record_1.Record)); - exports.Store = Store; - Store.global = new Store(); - - -/***/ }, -/* 30 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var _ = __webpack_require__(31); - var jQuery = __webpack_require__(32); - var previousBackbone = window.Backbone; - var slice = Array.prototype.slice; - exports.VERSION = '1.2.3'; - exports.$ = jQuery; - function noConflict() { - window.Backbone = previousBackbone; - return this; - } - exports.noConflict = noConflict; - ; - exports.emulateHTTP = false; - exports.emulateJSON = false; - function View(options) { - this.cid = _.uniqueId('view'); - options || (options = {}); - _.extend(this, _.pick(options, viewOptions)); - this._ensureElement(); - this.initialize.apply(this, arguments); - this.delegateEvents(); - } - exports.View = View; - ; - var delegateEventSplitter = /^(\S+)\s*(.*)$/; - var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; - _.extend(View.prototype, { - tagName: 'div', - $: function (selector) { - return this.$el.find(selector); - }, - initialize: function () { }, - render: function () { - return this; - }, - remove: function () { - this.$el.remove(); - this.stopListening(); - return this; - }, - setElement: function (element, delegate) { - if (this.$el) - this.undelegateEvents(); - this.$el = element instanceof exports.$ ? element : exports.$(element); - this.el = this.$el[0]; - if (delegate !== false) - this.delegateEvents(); - return this; - }, - delegateEvents: function (events) { - if (!(events || (events = _.result(this, 'events')))) - return this; - this.undelegateEvents(); - for (var key in events) { - var method = events[key]; - if (!_.isFunction(method)) - method = this[events[key]]; - if (!method) - continue; - var match = key.match(delegateEventSplitter); - var eventName = match[1], selector = match[2]; - method = _.bind(method, this); - eventName += '.delegateEvents' + this.cid; - if (selector === '') { - this.$el.on(eventName, method); - } - else { - this.$el.on(eventName, selector, method); - } - } - return this; - }, - undelegateEvents: function () { - this.$el.off('.delegateEvents' + this.cid); - return this; - }, - _ensureElement: function () { - if (!this.el) { - var attrs = _.extend({}, _.result(this, 'attributes')); - if (this.id) - attrs.id = _.result(this, 'id'); - if (this.className) - attrs['class'] = _.result(this, 'className'); - var $el = exports.$('<' + _.result(this, 'tagName') + '>').attr(attrs); - this.setElement($el, false); - } - else { - this.setElement(_.result(this, 'el'), false); - } - } - }); - function Router(options) { - options || (options = {}); - if (options.routes) - this.routes = options.routes; - this._bindRoutes(); - this.initialize.apply(this, arguments); - } - exports.Router = Router; - var optionalParam = /\((.*?)\)/g; - var namedParam = /(\(\?)?:\w+/g; - var splatParam = /\*\w+/g; - var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; - _.extend(Router.prototype, { - initialize: function () { }, - route: function (route, name, callback) { - if (!_.isRegExp(route)) - route = this._routeToRegExp(route); - if (_.isFunction(name)) { - callback = name; - name = ''; - } - if (!callback) - callback = this[name]; - var router = this; - exports.history.route(route, function (fragment) { - var args = router._extractParameters(route, fragment); - if (router.execute(callback, args, name) !== false) { - router.trigger.apply(router, ['route:' + name].concat(args)); - router.trigger('route', name, args); - exports.history.trigger('route', router, name, args); - } - }); - return this; - }, - execute: function (callback, args, name) { - if (callback) - callback.apply(this, args); - }, - navigate: function (fragment, options) { - exports.history.navigate(fragment, options); - return this; - }, - _bindRoutes: function () { - if (!this.routes) - return; - this.routes = _.result(this, 'routes'); - var route, routes = _.keys(this.routes); - while ((route = routes.pop()) != null) { - this.route(route, this.routes[route]); - } - }, - _routeToRegExp: function (route) { - route = route.replace(escapeRegExp, '\\$&') - .replace(optionalParam, '(?:$1)?') - .replace(namedParam, function (match, optional) { - return optional ? match : '([^/?]+)'; - }) - .replace(splatParam, '([^?]*?)'); - return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$'); - }, - _extractParameters: function (route, fragment) { - var params = route.exec(fragment).slice(1); - return _.map(params, function (param, i) { - if (i === params.length - 1) - return param || null; - return param ? decodeURIComponent(param) : null; - }); - } - }); - function History() { - this.handlers = []; - this.checkUrl = _.bind(this.checkUrl, this); - if (typeof window !== 'undefined') { - this.location = window.location; - this.history = window.history; - } - } - exports.History = History; - ; - var routeStripper = /^[#\/]|\s+$/g; - var rootStripper = /^\/+|\/+$/g; - var pathStripper = /#.*$/; - History.started = false; - _.extend(History.prototype, { - interval: 50, - atRoot: function () { - var path = this.location.pathname.replace(/[^\/]$/, '$&/'); - return path === this.root && !this.getSearch(); - }, - matchRoot: function () { - var path = this.decodeFragment(this.location.pathname); - var root = path.slice(0, this.root.length - 1) + '/'; - return root === this.root; - }, - decodeFragment: function (fragment) { - return decodeURI(fragment.replace(/%25/g, '%2525')); - }, - getSearch: function () { - var match = this.location.href.replace(/#.*/, '').match(/\?.+/); - return match ? match[0] : ''; - }, - getHash: function (window) { - var match = (window || this).location.href.match(/#(.*)$/); - return match ? match[1] : ''; - }, - getPath: function () { - var path = this.decodeFragment(this.location.pathname + this.getSearch()).slice(this.root.length - 1); - return path.charAt(0) === '/' ? path.slice(1) : path; - }, - getFragment: function (fragment) { - if (fragment == null) { - if (this._usePushState || !this._wantsHashChange) { - fragment = this.getPath(); - } - else { - fragment = this.getHash(); - } - } - return fragment.replace(routeStripper, ''); - }, - start: function (options) { - if (History.started) - throw new Error('Backbone.history has already been started'); - History.started = true; - this.options = _.extend({ root: '/' }, this.options, options); - this.root = this.options.root; - this._wantsHashChange = this.options.hashChange !== false; - this._hasHashChange = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7); - this._useHashChange = this._wantsHashChange && this._hasHashChange; - this._wantsPushState = !!this.options.pushState; - this._hasPushState = !!(this.history && this.history.pushState); - this._usePushState = this._wantsPushState && this._hasPushState; - this.fragment = this.getFragment(); - this.root = ('/' + this.root + '/').replace(rootStripper, '/'); - if (this._wantsHashChange && this._wantsPushState) { - if (!this._hasPushState && !this.atRoot()) { - var root = this.root.slice(0, -1) || '/'; - this.location.replace(root + '#' + this.getPath()); - return true; - } - else if (this._hasPushState && this.atRoot()) { - this.navigate(this.getHash(), { replace: true }); - } - } - if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) { - this.iframe = document.createElement('iframe'); - this.iframe.src = 'javascript:0'; - this.iframe.style.display = 'none'; - this.iframe.tabIndex = -1; - var body = document.body; - var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow; - iWindow.document.open(); - iWindow.document.close(); - iWindow.location.hash = '#' + this.fragment; - } - var addEventListener = window.addEventListener || function (eventName, listener) { - return attachEvent('on' + eventName, listener); - }; - if (this._usePushState) { - addEventListener('popstate', this.checkUrl, false); - } - else if (this._useHashChange && !this.iframe) { - addEventListener('hashchange', this.checkUrl, false); - } - else if (this._wantsHashChange) { - this._checkUrlInterval = setInterval(this.checkUrl, this.interval); - } - if (!this.options.silent) - return this.loadUrl(); - }, - stop: function () { - var removeEventListener = window.removeEventListener || function (eventName, listener) { - return detachEvent('on' + eventName, listener); - }; - if (this._usePushState) { - removeEventListener('popstate', this.checkUrl, false); - } - else if (this._useHashChange && !this.iframe) { - removeEventListener('hashchange', this.checkUrl, false); - } - if (this.iframe) { - document.body.removeChild(this.iframe); - this.iframe = null; - } - if (this._checkUrlInterval) - clearInterval(this._checkUrlInterval); - History.started = false; - }, - route: function (route, callback) { - this.handlers.unshift({ route: route, callback: callback }); - }, - checkUrl: function (e) { - var current = this.getFragment(); - if (current === this.fragment && this.iframe) { - current = this.getHash(this.iframe.contentWindow); - } - if (current === this.fragment) - return false; - if (this.iframe) - this.navigate(current); - this.loadUrl(); - }, - loadUrl: function (fragment) { - if (!this.matchRoot()) - return false; - fragment = this.fragment = this.getFragment(fragment); - return _.some(this.handlers, function (handler) { - if (handler.route.test(fragment)) { - handler.callback(fragment); - return true; - } - }); - }, - navigate: function (fragment, options) { - if (!History.started) - return false; - if (!options || options === true) - options = { trigger: !!options }; - fragment = this.getFragment(fragment || ''); - var root = this.root; - if (fragment === '' || fragment.charAt(0) === '?') { - root = root.slice(0, -1) || '/'; - } - var url = root + fragment; - fragment = this.decodeFragment(fragment.replace(pathStripper, '')); - if (this.fragment === fragment) - return; - this.fragment = fragment; - if (this._usePushState) { - this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url); - } - else if (this._wantsHashChange) { - this._updateHash(this.location, fragment, options.replace); - if (this.iframe && (fragment !== this.getHash(this.iframe.contentWindow))) { - var iWindow = this.iframe.contentWindow; - if (!options.replace) { - iWindow.document.open(); - iWindow.document.close(); - } - this._updateHash(iWindow.location, fragment, options.replace); - } - } - else { - return this.location.assign(url); - } - if (options.trigger) - return this.loadUrl(fragment); - }, - _updateHash: function (location, fragment, replace) { - if (replace) { - var href = location.href.replace(/(javascript:|#).*$/, ''); - location.replace(href + '#' + fragment); - } - else { - location.hash = '#' + fragment; - } - } - }); - exports.history = new History; - - -/***/ }, -/* 31 */ -/***/ function(module, exports) { - - module.exports = __WEBPACK_EXTERNAL_MODULE_31__; - -/***/ }, -/* 32 */ -/***/ function(module, exports) { - - module.exports = __WEBPACK_EXTERNAL_MODULE_32__; - -/***/ }, -/* 33 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - var sync_1 = __webpack_require__(34); - var _ = __webpack_require__(31); - var src_1 = __webpack_require__(1); - var defaults = src_1.tools.defaults; - var transactionalProto = src_1.tools.getBaseClass(src_1.Model).prototype; - var RestCollection = (function (_super) { - __extends(RestCollection, _super); - function RestCollection() { - _super.apply(this, arguments); - } - RestCollection.prototype.url = function () { return this.model.prototype.urlRoot || ''; }; - RestCollection.prototype._invalidate = function (options) { - var error; - if (options.validate && (error = this.validationError)) { - this.trigger('invalid', this, error, _.extend({ validationError: error }, options)); - return true; - } - }; - RestCollection.prototype.fetch = function (options) { - options = _.extend({ parse: true }, options); - var success = options.success; - var collection = this; - options.success = function (resp) { - var method = options.reset ? 'reset' : 'set'; - collection[method](resp, options); - if (collection._invalidate(options)) - return false; - if (success) - success.call(options.context, collection, resp, options); - collection.trigger('sync', collection, resp, options); - }; - wrapError(this, options); - return _sync('read', this, options); - }; - RestCollection.prototype.create = function (a_model, options) { - var _this = this; - if (options === void 0) { options = {}; } - var model = a_model instanceof RestModel ? - a_model : - this.model.create(a_model, options, this); - model._owner || (model._owner = this); - options.wait || this.add([model], options); - var collection = this; - var success = options.success; - options.success = function (model, resp, callbackOpts) { - if (options.wait) - _this.add([model], defaults({ parse: false }, callbackOpts)); - if (success) - success.call(callbackOpts.context, model, resp, callbackOpts); - }; - model.save(null, options); - return model; - }; - RestCollection.prototype.sync = function () { - return sync_1.sync.apply(this, arguments); - }; - RestCollection = __decorate([ - src_1.define({ - itemEvents: { - destroy: function (model) { this.remove(model); } - } - }) - ], RestCollection); - return RestCollection; - }(src_1.Collection)); - exports.RestCollection = RestCollection; - ; - var RestModel = (function (_super) { - __extends(RestModel, _super); - function RestModel() { - _super.apply(this, arguments); - } - RestModel.prototype._invalidate = function (options) { - var error; - if (options.validate && (error = this.validationError)) { - triggerAndBubble(this, 'invalid', this, error, _.extend({ validationError: error }, options)); - return true; - } - }; - RestModel.prototype.fetch = function (options) { - options = _.extend({ parse: true }, options); - var model = this; - var success = options.success; - options.success = function (serverAttrs) { - model.set(serverAttrs, options); - if (model._invalidate(options)) - return false; - if (success) - success.call(options.context, model, serverAttrs, options); - triggerAndBubble(model, 'sync', model, serverAttrs, options); - }; - wrapError(this, options); - return _sync('read', this, options); - }; - RestModel.prototype.sync = function () { - return sync_1.sync.apply(this, arguments); - }; - RestModel.prototype.save = function (key, val, a_options) { - var _this = this; - var attrs, originalOptions; - if (key == null || typeof key === 'object') { - attrs = key; - originalOptions = val || {}; - } - else { - (attrs = {})[key] = val; - originalOptions = a_options || {}; - } - var options = _.extend({ validate: true, parse: true }, originalOptions), wait = options.wait; - if (attrs && !wait) { - this.set(attrs, originalOptions); - } - if (this._invalidate(originalOptions)) { - if (attrs && wait) - this.set(attrs, originalOptions); - return sync_1.errorPromise(this.validationError); - } - var model = this; - var success = options.success; - var attributes = this.attributes; - options.success = function (serverAttrs) { - model.attributes = attributes; - if (wait) - serverAttrs = _.extend({}, attrs, serverAttrs); - if (serverAttrs) { - transactionalProto.set.call(_this, serverAttrs, options); - if (model._invalidate(options)) - return false; - } - if (success) - success.call(options.context, model, serverAttrs, options); - triggerAndBubble(model, 'sync', model, serverAttrs, options); - }; - wrapError(this, options); - if (attrs && wait) - this.attributes = _.extend({}, attributes, attrs); - var method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); - if (method === 'patch' && !options.attrs) - options.attrs = attrs; - var xhr = _sync(method, this, options); - this.attributes = attributes; - return xhr; - }; - RestModel.prototype.destroy = function (options) { - options = options ? _.clone(options) : {}; - var model = this; - var success = options.success; - var wait = options.wait; - var destroy = function () { - model.stopListening(); - model.trigger('destroy', model, model.collection, options); - }; - options.success = function (resp) { - if (wait) - destroy(); - if (success) - success.call(options.context, model, resp, options); - if (!model.isNew()) - triggerAndBubble(model, 'sync', model, resp, options); - }; - var xhr = false; - if (this.isNew()) { - _.defer(options.success); - } - else { - wrapError(this, options); - xhr = _sync('delete', this, options); - } - if (!wait) - destroy(); - return xhr; - }; - RestModel.prototype.url = function () { - var base = _.result(this, 'urlRoot') || - _.result(this.collection, 'url') || - sync_1.urlError(); - if (this.isNew()) - return base; - var id = this.get(this.idAttribute); - return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id); - }; - RestModel = __decorate([ - src_1.define({ - collection: RestCollection, - urlRoot: '' - }) - ], RestModel); - return RestModel; - }(src_1.Model)); - exports.RestModel = RestModel; - function _sync(method, _this, options) { - _this._xhr && _this._xhr.abort && _this._xhr.abort(); - var xhr = _this._xhr = _this.sync(method, _this, options); - xhr && xhr.always && xhr.always(function () { _this.xhr = void 0; }); - return xhr; - } - function wrapError(model, options) { - var error = options.error; - options.error = function (resp) { - if (error) - error.call(options.context, model, resp, options); - triggerAndBubble(model, 'error', model, resp, options); - }; - } - function triggerAndBubble(model) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - model.trigger.apply(model, args); - var collection = model.collection; - collection && collection.trigger.apply(collection, args); - } - - -/***/ }, -/* 34 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var _ = __webpack_require__(31); - var Backbone = __webpack_require__(30); - var src_1 = __webpack_require__(1); - var defaults = src_1.tools.defaults; - var methodMap = { - 'create': 'POST', - 'update': 'PUT', - 'patch': 'PATCH', - 'delete': 'DELETE', - 'read': 'GET' - }; - exports.$ = Backbone.$; - exports.errorPromise = function (error) { - var x = exports.$.Deferred(); - x.reject(error); - return x; - }; - exports.ajax = function () { - return exports.$.ajax.apply(exports.$, arguments); - }; - exports.sync = function (method, model, options) { - if (options === void 0) { options = {}; } - var type = methodMap[method]; - defaults(options, { - emulateHTTP: Backbone.emulateHTTP, - emulateJSON: Backbone.emulateJSON - }); - var params = { type: type, dataType: 'json' }; - if (!options.url) { - params.url = _.result(model, 'url') || urlError(); - } - if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { - params.contentType = 'application/json'; - params.data = JSON.stringify(options.attrs || model.toJSON(options)); - } - if (options.emulateJSON) { - params.contentType = 'application/x-www-form-urlencoded'; - params.data = params.data ? { model: params.data } : {}; - } - if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { - params.type = 'POST'; - if (options.emulateJSON) - params.data._method = type; - var beforeSend = options.beforeSend; - options.beforeSend = function (xhr) { - xhr.setRequestHeader('X-HTTP-Method-Override', type); - if (beforeSend) - return beforeSend.apply(this, arguments); - }; - } - if (params.type !== 'GET' && !options.emulateJSON) { - params.processData = false; - } - var error = options.error; - options.error = function (xhr, textStatus, errorThrown) { - options.textStatus = textStatus; - options.errorThrown = errorThrown; - if (error) - error.call(options.context, xhr, textStatus, errorThrown); - }; - var xhr = options.xhr = exports.ajax(_.extend(params, options)); - model.trigger('request', model, xhr, options); - model.collection && model.collection.trigger('request', model, xhr, options); - return xhr; - }; - function urlError() { - throw new Error('A "url" property or function must be specified'); - } - exports.urlError = urlError; - - -/***/ }, -/* 35 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var _ = __webpack_require__(31); - var slice = Array.prototype.slice; - exports.UnderscoreModel = { - pick: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - return _.pick(this, args); - }, - escape: function (attr) { - return _.escape(this[attr]); - }, - matches: function (attrs) { - return !!_.iteratee(attrs, this)(this); - }, - omit: function () { - var keys = []; - for (var _i = 0; _i < arguments.length; _i++) { - keys[_i - 0] = arguments[_i]; - } - return this.mapObject(function (value, key) { - if (keys.indexOf(key) < 0) { - return value; - } - }); - }, - invert: function () { - var inverted = {}; - this.each(function (value, key) { return inverted[value] = key; }); - return inverted; - }, - pairs: function () { - return this.map(function (value, key) { return [key, value]; }); - }, - isEmpty: function () { - return !this.values().length; - }, - chain: function () { - return _.chain(this.mapObject(function (x) { return x; })); - } - }; - exports.UnderscoreCollection = { - where: function (attrs, first) { - return this[first ? 'find' : 'filter'](attrs); - }, - findWhere: function (attrs) { - return this.where(attrs, true); - } - }; - addUnderscoreMethods(exports.UnderscoreCollection, 'models', { - forEach: 3, each: 3, map: 3, collect: 3, reduce: 4, - foldl: 4, inject: 4, reduceRight: 4, foldr: 4, find: 3, findIndex: 3, findLastIndex: 3, detect: 3, filter: 3, - select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 3, includes: 3, - contains: 3, invoke: 0, max: 3, min: 3, toArray: 1, size: 1, first: 3, - head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3, - without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3, - isEmpty: 1, chain: 1, sample: 3, partition: 3, groupBy: 3, countBy: 3, - sortBy: 3, indexBy: 3 - }); - function addUnderscoreMethods(Mixin, attribute, methods) { - _.each(methods, function (length, method) { - if (_[method]) - Mixin[method] = addMethod(length, method, attribute); - }); - } - function addMethod(length, method, attribute) { - switch (length) { - case 1: return function () { - return _[method](this[attribute]); - }; - case 2: return function (value) { - return _[method](this[attribute], value); - }; - case 3: return function (iteratee, context) { - var value = this[attribute], callback = cb(iteratee, this); - return arguments.length > 1 ? - _[method](value, callback, context) - : _[method](value, callback); - }; - case 4: return function (iteratee, defaultVal, context) { - var value = this[attribute], callback = cb(iteratee, this); - return arguments.length > 1 ? - _[method](value, callback, defaultVal, context) - : _[method](value, callback); - }; - default: return function () { - var args = slice.call(arguments); - args.unshift(this[attribute]); - return _[method].apply(_, args); - }; - } - } - function cb(iteratee, instance) { - switch (typeof iteratee) { - case 'function': return iteratee; - case 'string': return function (model) { return model.get(iteratee); }; - case 'object': - if (!(iteratee instanceof instance.model)) - return _.matches(iteratee); - } - return iteratee; - } - - -/***/ }, -/* 36 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - var Backbone = __webpack_require__(30); - var _ = __webpack_require__(31); - var src_1 = __webpack_require__(1); - var rest_1 = __webpack_require__(33); - var $ = Backbone.$; - var RestStore = (function (_super) { - __extends(RestStore, _super); - function RestStore() { - _super.apply(this, arguments); - } - RestStore = __decorate([ - src_1.define({}), - src_1.mixins(src_1.Store) - ], RestStore); - return RestStore; - }(rest_1.RestModel)); - exports.RestStore = RestStore; - var LazyStore = (function (_super) { - __extends(LazyStore, _super); - function LazyStore() { - _super.apply(this, arguments); - this._resolved = {}; - } - LazyStore.prototype.initialize = function () { - var _this = this; - this.each(function (element, name) { - if (!element) - return; - element.store = _this; - var fetch = element.fetch; - if (fetch) { - var self_1 = _this; - element.fetch = function () { - return self_1._resolved[name] = fetch.apply(this, arguments); - }; - } - if (element instanceof rest_1.RestCollection && element.length) { - _this._resolved[name] = true; - } - }); - }; - LazyStore.prototype.fetch = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - var xhr = [], objsToFetch = args.length ? args : this.keys(); - for (var _a = 0, objsToFetch_1 = objsToFetch; _a < objsToFetch_1.length; _a++) { - var name_1 = objsToFetch_1[_a]; - var attr = this.attributes[name_1]; - attr && attr.fetch && xhr.push(attr.fetch()); - } - return $ && $.when && $.when.apply(Backbone.$, xhr); - }; - LazyStore.prototype.fetchOnce = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - var xhr = [], self = this, objsToFetch = args.length ? args : this.keys(); - for (var _a = 0, objsToFetch_2 = objsToFetch; _a < objsToFetch_2.length; _a++) { - var name_2 = objsToFetch_2[_a]; - var attr = self.attributes[name_2]; - xhr.push(self._resolved[name_2] || attr && attr.fetch && attr.fetch()); - } - return $ && $.when && $.when.apply(Backbone.$, xhr); - }; - LazyStore.prototype.clear = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i - 0] = arguments[_i]; - } - var objsToClear = args.length ? args : this.keys(); - for (var _a = 0, objsToClear_1 = objsToClear; _a < objsToClear_1.length; _a++) { - var name_3 = objsToClear_1[_a]; - var element = this.attributes[name_3]; - if (element instanceof rest_1.RestCollection) { - element.reset(); - } - else if (element instanceof src_1.Store) { - element.clear(); - } - else if (element instanceof rest_1.RestModel) { - element.set(element.defaults()); - } - this._resolved[name_3] = false; - } - return this; - }; - LazyStore.define = function (props, staticProps) { - var attributes = props.defaults || props.attributes; - _.each(attributes, function (Type, name) { - if (Type.has) { - attributes[name] = Type.has - .get(function (value) { - if (!this._resolved[name]) { - value.fetch && value.fetch(); - } - return value; - }) - .set(function (value) { - if (!value.length) { - var resolved = this._resolved || (this._resolved = {}); - resolved[name] = false; - } - return value; - }); - } - }); - return rest_1.RestModel.define.call(this, props, staticProps); - }; - LazyStore = __decorate([ - src_1.define({}) - ], LazyStore); - return LazyStore; - }(RestStore)); - exports.LazyStore = LazyStore; - - -/***/ } -/******/ ]) -}); -; -//# sourceMappingURL=nestedtypes.js.map \ No newline at end of file diff --git a/nestedtypes.js.map b/nestedtypes.js.map deleted file mode 100644 index df4e5d6..0000000 --- a/nestedtypes.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap 71bf14833997c3bd865d","webpack:///./src/index.ts","webpack:///./type-r/src/index.ts","webpack:///./type-r/src/object-plus/index.ts","webpack:///./type-r/src/object-plus/tools.ts","webpack:///./type-r/src/object-plus/mixins.ts","webpack:///./type-r/src/object-plus/messenger.ts","webpack:///./type-r/src/object-plus/events-api.ts","webpack:///./type-r/src/collection/index.ts","webpack:///./type-r/src/transactions.ts","webpack:///./type-r/src/validation.ts","webpack:///./type-r/src/traversable.ts","webpack:///./type-r/src/record/index.ts","webpack:///./type-r/src/record/transaction.ts","webpack:///./type-r/src/record/define.ts","webpack:///./type-r/src/record/attributes/index.ts","webpack:///./type-r/src/record/attributes/generic.ts","webpack:///./type-r/src/record/attributes/owned.ts","webpack:///./type-r/src/record/attributes/date.ts","webpack:///./type-r/src/record/attributes/basic.ts","webpack:///./type-r/src/record/attributes/shared.ts","webpack:///./type-r/src/record/typespec.ts","webpack:///./type-r/src/collection/commons.ts","webpack:///./type-r/src/collection/add.ts","webpack:///./type-r/src/collection/set.ts","webpack:///./type-r/src/collection/remove.ts","webpack:///./type-r/src/relations/index.ts","webpack:///./type-r/src/relations/from.ts","webpack:///./type-r/src/relations/commons.ts","webpack:///./type-r/src/relations/subsetOf.ts","webpack:///./type-r/src/relations/store.ts","webpack:///./src/backbone.js","webpack:///external {\"commonjs\":\"underscore\",\"commonjs2\":\"underscore\",\"amd\":\"underscore\",\"root\":\"_\"}","webpack:///external {\"commonjs\":\"jquery\",\"commonjs2\":\"jquery\",\"amd\":\"jquery\",\"root\":\"$\"}","webpack:///./src/rest.ts","webpack:///./src/sync.ts","webpack:///./src/underscore-mixin.ts","webpack:///./src/rest-store.ts"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;ACVA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,uBAAe;AACf;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;;;;;;;ACnCA,KAAY,MAAM,uBAAM,CACxB,CAAC,CADsC;AAEvC,KAAY,QAAQ,uBAAM,EAC1B,CAAC,CADqC;AACtC,kCAA0C,EAC1C,CAAC,CADiD;AAClD,iCAAsB,CACtB,CAAC,CADoC;AACrC,KAAY,IAAI,uBAAM,EACtB,CAAC,CAD6B;AAC9B,8CAAsD,EACtD,CAAC,CADyE;AAC1E,wCAAqC,EAErC,CAAC,CAFkD;AAEnD,OAAM,CAAC,OAAO,CAAC,MAAM,CAAE,MA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sGvC;AAtGY,kBAAS,YAsGrB","file":"./nestedtypes.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"underscore\"), require(\"jquery\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"underscore\", \"jquery\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"Nested\"] = factory(require(\"underscore\"), require(\"jquery\"));\n\telse\n\t\troot[\"Nested\"] = factory(root[\"_\"], root[\"$\"]);\n})(this, function(__WEBPACK_EXTERNAL_MODULE_31__, __WEBPACK_EXTERNAL_MODULE_32__) {\nreturn \n\n\n/** WEBPACK FOOTER **\n ** webpack/universalModuleDefinition\n **/"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n/** WEBPACK FOOTER **\n ** webpack/bootstrap 71bf14833997c3bd865d\n **/","/**\r\n * Prepare backbone View, Router, History, and Events. \r\n */\r\nimport * as Nested from '../type-r/src'\r\nexport = Nested;\r\nimport * as Backbone from './backbone'\r\nimport { RestCollection, RestModel } from './rest'\r\nimport { Store } from '../type-r/src'\r\nimport * as Sync from './sync'\r\nimport { UnderscoreModel, UnderscoreCollection } from './underscore-mixin'\r\nimport { RestStore, LazyStore } from './rest-store'\r\n \r\nNested.Mixable.mixins( Nested.Events );\r\nNested.Mixable.mixTo( Backbone.View, Backbone.Router, Backbone.History );\r\n\r\nNested.Model.mixins( UnderscoreModel );\r\nNested.Collection.mixins( UnderscoreCollection );\r\n\r\nconst { assign } = Nested.tools;\r\n\r\n/**\r\n * Prepare \r\n */\r\n\r\n// allow sync and jQuery override\r\nObject.defineProperties( Nested, {\r\n 'emulateHTTP' : linkProperty( Backbone, 'emulateHTTP' ),\r\n 'emulateJSON' : linkProperty( Backbone, 'emulateJSON' ),\r\n 'sync' : linkProperty( Sync, 'sync' ),\r\n 'errorPromise' : linkProperty( Sync, 'errorPromise' ),\r\n 'ajax' : linkProperty( Sync, 'ajax' ),\r\n 'history' : linkProperty( Backbone, 'history' ),\r\n 'store' : linkProperty( Store, 'global' ),\r\n '$' : {\r\n get(){ return Backbone.$; },\r\n set( value ){ Backbone.$ = Sync.$ = value; }\r\n }\r\n} );\r\n\r\nassign( Nested, Backbone, {\r\n Backbone : Backbone,\r\n Class : Nested.Messenger,\r\n Model : RestModel,\r\n Collection : RestCollection,\r\n LazyStore : LazyStore,\r\n Store : RestStore,\r\n\r\n defaults( x ){\r\n return Nested.Model.defaults( x );\r\n }\r\n} );\r\n\r\nfunction linkProperty( Namespace, name ){\r\n return {\r\n get : function(){ return Namespace[ name ]; },\r\n set : function( value ){ Namespace[ name ] = value; }\r\n };\r\n}\r\n\n\n\n/** WEBPACK FOOTER **\n ** ./src/index.ts\n **/","/**\r\n * Export everything \r\n */\r\nexport * from './object-plus'\r\nexport * from './collection'\r\nexport * from './relations'\r\nexport * from './record'\r\n\r\n// Exported module itself is the global event bus.\r\nimport { Events } from './object-plus/'\r\nexport const { on, off, trigger, once, listenTo, stopListening, listenToOnce } = Events;\r\n\r\n// Define synonims for NestedTypes backward compatibility.\r\nimport { Record as Model } from './record' \r\nimport { Mixable as Class } from './object-plus/'\r\nexport { Model, Class }; \r\n\r\nimport { ChainableAttributeSpec } from './record'\r\n\r\n/** Typeless attribute declaration with default value. */ \r\nexport function value( x : any ) : ChainableAttributeSpec {\r\n return new ChainableAttributeSpec({ value : x });\r\n}\r\n\r\n/** Wrap model or collection method in transaction. */\r\nexport function transaction< F extends Function >( method : F ) : F {\r\n return function( ...args ){\r\n let result;\r\n \r\n this.transaction( () => {\r\n result = method.apply( this, args );\r\n });\r\n \r\n return result;\r\n }\r\n}\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/index.ts\n **/","import * as tools from './tools'\r\nexport { tools }\r\nexport * from './mixins'\r\nexport * from './messenger'\r\nimport * as eventsApi from './events-api'\r\nexport { eventsApi }\r\n\r\nimport { Mixable, MixableConstructor } from './mixins'\r\n\r\ndeclare global {\r\n interface ObjectConstructor {\r\n /** Polyfill for Object.assign */\r\n assign< T >( dest : T, ...sources : Object[] ) : T\r\n\r\n /** Global logging interface, for console debugging. */\r\n log : tools.Log\r\n\r\n /** ES5 Object.extend */\r\n extend( protoProps : {}, staticProps : {} ) : MixableConstructor< any >\r\n }\r\n}\r\n\r\nObject.extend = ( protoProps, staticProps ) => Mixable.extend( protoProps, staticProps );\r\nObject.assign || ( Object.assign = tools.assign );\r\nObject.log = tools.log;\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/object-plus/index.ts\n **/","/**\r\n * Simple overridable logging stubs, writing to `console` by default.\r\n * Node.js users might want to redirect logging somewhere.\r\n * \r\n * This is the singleton avaliable globally through `Object.log` or \r\n * exported [[log]] variable.\r\n */\r\nexport class Log {\r\n /** Logging level.\r\n * - *0* - turn off everything.\r\n * - *1* - `log.error()` only;\r\n * - *2* - (_default_) `log.error()` and `log.warn()`;\r\n * - *3* - `error()`, `warn()`, and `info()`;\r\n * - *4* - all of above + `debug()`.\r\n */\r\n level : number\r\n\r\n /** Stop in debugger on specified logging events. \r\n * \r\n * Object.log.stops.error = true;\r\n */\r\n stops : LogOptions = {}\r\n\r\n /** Throw exceptions for specified logging events.\r\n * \r\n * Object.log.throws.error = true;\r\n */\r\n throws : LogOptions = {}\r\n\r\n /** Logging events counter. Can be used for test assertions. */\r\n counts : { error : number, warn : number, info : number, debug : number }\r\n\r\n /** Overridable logger API. Defaults to `window.console` */\r\n logger : Logger\r\n\r\n private doLogging( type, args : any[] ){\r\n const { logger } = this,\r\n logMethod = logger && logger[ type ];\r\n\r\n if( logMethod ) logMethod.apply( logger, args );\r\n\r\n if( this.stops[ type ] ) debugger;\r\n if( this.throws[ type ] ) throw new Error( `[${ type }] ${ args[ 0 ] }` );\r\n\r\n this.counts[ type ]++;\r\n }\r\n\r\n /** Reset logger to default settings. */\r\n reset() : this {\r\n this.level = 2;\r\n this.counts = { error : 0, warn : 0, info : 0, debug : 0 };\r\n this.stops = {};\r\n return this;\r\n }\r\n\r\n /** Show info, stop on errors.\r\n * @param trueDeveloper Stop on warnings as well.\r\n */\r\n developer( trueDeveloper? : boolean ) : this {\r\n this.level = 3;\r\n this.stops = { error : true, warn : Boolean( trueDeveloper ) };\r\n return this;\r\n }\r\n\r\n /** @hidden */\r\n constructor(){\r\n this.logger = typeof console !== 'undefined' ? console : null;\r\n this.reset();\r\n }\r\n\r\n /** Similar to the `console.error`. Logging level 1. */\r\n error( ...args : any[] ) : void {\r\n if( this.level > 0 ) this.doLogging( 'error', args );\r\n }\r\n\r\n /** Similar to the `console.warn`. Logging level 2 (default). */\r\n warn( ...args : any[] ) : void {\r\n if( this.level > 1 ) this.doLogging( 'warn', args );\r\n }\r\n\r\n /** Similar to the `console.info`. Logging level 3. */\r\n info( ...args : any[] ){\r\n if( this.level > 2 ) this.doLogging( 'info', args );\r\n }\r\n\r\n /** Similar to the `console.debug`. Logging level 4. */\r\n debug( ...args : any[] ){\r\n if( this.level > 3 ) this.doLogging( 'debug', args );\r\n }\r\n\r\n /** `Object.log.state` - can be used to inspect logger state in the console. */\r\n get state() : string {\r\n return (`\r\nObject.log - Object+ Logging and Debugging Utility\r\n--------------------------------------------------\r\nObject.log.counts: Number of logged events by type\r\n { errors : ${ this.counts.error }, warns : ${ this.counts.warn }, info : ${ this.counts.info }, debug : ${ this.counts.debug } }\r\n\r\nObject.log.level == ${ this.level } : Ignore events which are above specified level \r\n - 0 - logging is off;\r\n - 1 - Object.log.error(...) only;\r\n - 2 - .error() and .warn();\r\n - 3 - .error(), .warn(), and .info();\r\n - 4 - all of above plus .debug().\r\n\r\nObject.log.stops: Stops in debugger for some certain event types\r\n { error : ${ this.stops.error || false }, warn : ${ this.stops.warn || false }, info : ${ this.stops.info || false }, debug : ${ this.stops.debug || false } } \r\n\r\nObject.log.throws: Throws expection on some certain event types\r\n { error : ${ this.throws.error || false }, warn : ${ this.throws.warn || false }, info : ${ this.throws.info || false }, debug : ${ this.throws.debug || false } }\r\n`);\r\n }\r\n}\r\n\r\n/** Interface [[Log.logger]] must implement. */\r\nexport interface Logger {\r\n error( ...args : any[] ) : void\r\n warn( ...args : any[] ) : void\r\n info( ...args : any[] ) : void\r\n debug( ...args : any[] ) : void\r\n}\r\n\r\n/** Logger options used by [[Log.stop]] and [[Log.throws]]. */\r\nexport interface LogOptions {\r\n error? : boolean\r\n warn? : boolean\r\n info? : boolean\r\n debug? : boolean\r\n}\r\n\r\n/** Logger singleton.\r\n * @see [[Log]] for API.\r\n */\r\nexport let log = new Log();\r\n\r\n/** Check if value is raw JSON */\r\nexport function isValidJSON( value : any ) : boolean {\r\n if( value === null ){\r\n return true;\r\n }\r\n\r\n switch( typeof value ){\r\n case 'number' :\r\n case 'string' :\r\n case 'boolean' :\r\n return true;\r\n\r\n case 'object':\r\n var proto = Object.getPrototypeOf( value );\r\n\r\n if( proto === Object.prototype || proto === Array.prototype ){\r\n return every( value, isValidJSON );\r\n }\r\n }\r\n\r\n return false;\r\n}\r\n\r\n/** Get the base class constructor function.\r\n * @param Class Subclass constructor function.\r\n * @returns Base class constructor function.\r\n */\r\nexport function getBaseClass( Class : Function ) {\r\n return Object.getPrototypeOf( Class.prototype ).constructor\r\n}\r\n\r\n/** Get a hash of static (constructor) properties which have not been inherited.\r\n * @param Ctor class constructor function.\r\n * @param names comma-separated list of static property names to compare.\r\n * @returns hash of listed statics which are added or overriden in the class.\r\n */\r\nexport function getChangedStatics( Ctor : Function, ...names : string[] ) : {}{\r\n const Base = getBaseClass( Ctor ),\r\n props = {};\r\n\r\n for( let name of names ){\r\n const value = Ctor[ name ];\r\n if( value !== void 0 && value !== Base[ name ] ){\r\n props[ name ] = value;\r\n }\r\n }\r\n\r\n return props;\r\n}\r\n\r\n/** Checks whenever given object is an empty hash `{}` */\r\nexport function isEmpty( obj : {} ) : boolean {\r\n if( obj ){\r\n for( let key in obj ){\r\n if( obj.hasOwnProperty( key ) ){\r\n return false;\r\n }\r\n }\r\n }\r\n\r\n return true;\r\n}\r\n\r\ntype Iteratee = ( value : any, key? : string | number ) => any;\r\n\r\n/** @hidden */\r\nfunction someArray( arr : any[], fun : Iteratee ) : any {\r\n let result;\r\n\r\n for( let i = 0; i < arr.length; i++ ){\r\n if( result = fun( arr[ i ], i ) ){\r\n return result;\r\n }\r\n }\r\n}\r\n\r\n/** @hidden */\r\nfunction someObject( obj : {}, fun : Iteratee ) : any {\r\n let result;\r\n\r\n for( let key in obj ){\r\n if( obj.hasOwnProperty( key ) ){\r\n if( result = fun( obj[ key ], key ) ){\r\n return result;\r\n }\r\n }\r\n }\r\n}\r\n\r\n/** Similar to underscore `_.some` */\r\nexport function some( obj, fun : Iteratee ) : any {\r\n if( Object.getPrototypeOf( obj ) === ArrayProto ){\r\n return someArray( obj, fun );\r\n }\r\n else{\r\n return someObject( obj, fun );\r\n }\r\n}\r\n\r\n/** Similar to underscore `_.every` */\r\nexport function every( obj : { }, predicate : Iteratee ) : boolean {\r\n return !some( obj, x => !predicate( x ) );\r\n}\r\n\r\n/** Similar to `getOwnPropertyDescriptor`, but traverse the whole prototype chain. */\r\nexport function getPropertyDescriptor( obj : {}, prop : string ) : PropertyDescriptor {\r\n let desc : PropertyDescriptor;\r\n\r\n for( let proto = obj; !desc && proto; proto = Object.getPrototypeOf( proto ) ) {\r\n desc = Object.getOwnPropertyDescriptor( obj, prop );\r\n }\r\n\r\n return desc;\r\n}\r\n\r\n/** Similar to underscore `_.omit` */\r\nexport function omit( source : {}, ...rest : string[] ) : {}\r\nexport function omit( source ) : {} {\r\n const dest = {}, discard = {};\r\n\r\n for( let i = 1; i < arguments.length; i ++ ){\r\n discard[ arguments[ i ] ] = true;\r\n }\r\n\r\n for( var name in source ) {\r\n if( !discard.hasOwnProperty( name ) && source.hasOwnProperty( name ) ) {\r\n dest[ name ] = source[ name ];\r\n }\r\n }\r\n\r\n return dest;\r\n}\r\n\r\n/** map `source` object properties with a given function, and assign the result to the `dest` object.\r\n * When `fun` returns `undefined`, skip this value. \r\n */\r\nexport function transform< A, B >( dest : { [ key : string ] : A }, source : { [ key : string ] : B }, fun : ( value : B, key : string ) => A | void ) : { [ key : string ] : A } {\r\n for( var name in source ) {\r\n if( source.hasOwnProperty( name ) ) {\r\n var value = fun( source[ name ], name );\r\n value === void 0 || ( dest[ name ] = < A >value );\r\n }\r\n }\r\n\r\n return dest;\r\n}\r\n\r\n/** @hidden */\r\nexport function fastAssign< A, B >( dest : A, source : B ) : A & B {\r\n for( var name in source ) {\r\n dest[ name ] = source[ name ];\r\n }\r\n\r\n return dest;\r\n}\r\n\r\n/** @hidden */\r\nexport function fastDefaults( dest : A, source : B ) : A & B {\r\n for( var name in source ) {\r\n if( dest[ name ] === void 0 ){\r\n dest[ name ] = source[ name ];\r\n }\r\n }\r\n\r\n return dest;\r\n}\r\n\r\n/** Similar to underscore `_.extend` and `Object.assign` */\r\nexport function assign< T >( dest : T, ...sources : Object[] ) : T\r\nexport function assign< T >( dest : T, source : Object ) : T {\r\n for( var name in source ) {\r\n if( source.hasOwnProperty( name ) ) {\r\n dest[ name ] = source[ name ];\r\n }\r\n }\r\n\r\n if( arguments.length > 2 ){\r\n for( let i = 2; i < arguments.length; i++ ){\r\n const other = arguments[ i ];\r\n other && assign( dest, other );\r\n }\r\n }\r\n\r\n return dest;\r\n}\r\n\r\n/** Similar to underscore `_.defaults` */\r\nexport function defaults< T >( dest : T, ...sources : Object[] ) : T\r\nexport function defaults< T >( dest : T, source : Object ) : T {\r\n for( var name in source ) {\r\n if( source.hasOwnProperty( name ) && dest[ name ] === void 0 ) {\r\n dest[ name ] = source[ name ];\r\n }\r\n }\r\n\r\n if( arguments.length > 2 ){\r\n for( let i = 2; i < arguments.length; i++ ){\r\n const other = arguments[ i ];\r\n other && defaults( dest, other );\r\n }\r\n }\r\n\r\n return dest;\r\n}\r\n\r\n/** Similar to underscore `_.keys` */\r\nexport function keys( o : any ) : string[]{\r\n return o ? Object.keys( o ) : [];\r\n}\r\n\r\n/** Similar to underscore `_.once` */\r\nexport function once( func : Function ) : Function {\r\n var memo, first = true;\r\n return function() {\r\n if ( first ) {\r\n first = false;\r\n memo = func.apply(this, arguments);\r\n func = null;\r\n }\r\n return memo;\r\n };\r\n}\r\n\r\nconst ArrayProto = Array.prototype,\r\n DateProto = Date.prototype,\r\n ObjectProto = Object.prototype;\r\n\r\n/**\r\n * Determine whenever two values are not equal, deeply traversing \r\n * arrays and plain JS objects (hashes). Dates are compared by enclosed timestamps, all other\r\n * values are compared with strict comparison.\r\n */\r\nexport function notEqual( a : any, b : any) : boolean {\r\n if( a === b ) return false;\r\n\r\n if( a && b && typeof a == 'object' && typeof b == 'object' ) {\r\n const protoA = Object.getPrototypeOf( a );\r\n\r\n if( protoA !== Object.getPrototypeOf( b ) ) return true;\r\n\r\n switch( protoA ){\r\n case DateProto : return +a !== +b;\r\n case ArrayProto : return arraysNotEqual( a, b );\r\n case ObjectProto :\r\n case null:\r\n return objectsNotEqual( a, b );\r\n }\r\n }\r\n\r\n return true;\r\n}\r\n\r\n/** @hidden */\r\nfunction objectsNotEqual( a, b ) {\r\n const keysA = Object.keys( a );\r\n\r\n if( keysA.length !== Object.keys( b ).length ) return true;\r\n\r\n for( let i = 0; i < keysA.length; i++ ) {\r\n const key = keysA[ i ];\r\n\r\n if( !b.hasOwnProperty( key ) || notEqual( a[ key ], b[ key ] ) ) {\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n}\r\n\r\n/** @hidden */\r\nfunction arraysNotEqual( a, b ) {\r\n if( a.length !== b.length ) return true;\r\n\r\n for( let i = 0; i < a.length; i++ ) {\r\n if( notEqual( a[ i ], b[ i ] ) ) return true;\r\n }\r\n\r\n return false;\r\n}\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/object-plus/tools.ts\n **/","/**\r\n * Mixins and @define metaprogramming class extensions\r\n * \r\n * Vlad Balin & Volicon, (c) 2016\r\n */\r\nimport { log, assign, omit, getPropertyDescriptor, getBaseClass, defaults, transform } from './tools'\r\n\r\n/**\r\n * Class definition recognized by [[Mixable.define]]\r\n */\r\nexport interface ClassDefinition {\r\n properties? : PropertyMap | boolean\r\n mixins? : Mixin[]\r\n mixinRules? : MixinRules\r\n [ name : string ] : any\r\n}\r\n\r\ninterface PropertyMap {\r\n [ name : string ] : Property\r\n}\r\n\r\ntype Property = PropertyDescriptor | ( () => any )\r\n\r\ntype Mixin = Constructor< any > | {}\r\n\r\n/**\r\n * Mixin property merge rules. Set with [[Mixable.mixinRules]] and [[mixinRules]] decorator.\r\n */\r\nexport interface MixinRules {\r\n [ propertyName : string ] : MergeRule | MixinRules\r\n}\r\n\r\n/**\r\n * Property merge rule. Defines what will happen if the same member is defined in multiple mixins and the class.\r\n * - *merge* - assume property to be an object, which members taken from mixins must be merged.\r\n * - *pipe* - property is the function `( x : T ) => T` transforming the value. Multiple functions joined in pipe.\r\n * - *sequence* - property is the function. Multiple functions will be called in sequence.\r\n * - *reverse* - same as *sequence*, but functions called in reverse sequence.\r\n * - *every* - property is the function `( ...args : any[] ) => boolean`. Resulting method will return true if every single function returns true.\r\n * - *some* - same as previous, but method will return true when at least one function returns true.\r\n */\r\nexport type MergeRule = 'merge' | 'pipe' | 'sequence' | 'reverse' | 'every' | 'some'\r\n\r\n\r\ndeclare function __extends( a, b )\r\n\r\n/**\r\n * Generic interface to reference constructor function type for any given T. \r\n */\r\nexport interface Constructor< T >{\r\n new ( ...args : any[] ) : T\r\n}\r\n\r\n/**\r\n * Generic interface to reference constructor function of any Mixable type T.\r\n */\r\nexport interface MixableConstructor< T > extends Constructor< T >{\r\n prototype : Mixable\r\n create( a : any, b? : any ) : Mixable\r\n mixins( ...mixins : ( Constructor | {} )[] ) : MixableConstructor< T >\r\n mixinRules( mixinRules : MixinRules ) : MixableConstructor< T >\r\n mixTo( ...args : Constructor[] ) : MixableConstructor< T >\r\n define( definition : ClassDefinition, staticProps? : {} ) : MixableConstructor< T >\r\n extend(spec? : ClassDefinition, statics? : {} ) : MixableConstructor< T >\r\n predefine() : MixableConstructor< T >\r\n}\r\n\r\n/**\r\n * Base class, holding metaprogramming class extensions.\r\n * Supports mixins and Class.define metaprogramming method.\r\n * \r\n * It's required to use `@define` decorator on inheritace.\r\n * \r\n * @define({ a : 1 }) // add 'a' property to A.prototype\r\n * class A extends Mixable {}\r\n * \r\n * or\r\n * @define\r\n * class A extends Mixable {}\r\n */ \r\nexport class Mixable {\r\n constructor(){ this.initialize.apply( this, arguments ); }\r\n initialize() : void {}\r\n\r\n /** Generic class factory. May be overridden for abstract classes. Not inherited. */\r\n static create( a : any, b? : any ) : Mixable {\r\n return new (this)( a, b );\r\n }\r\n\r\n /** @hidden */\r\n protected static _mixinRules : MixinRules = { properties : 'merge' };\r\n\r\n /** @hidden */\r\n static _appliedMixins : any[]\r\n\r\n /**\r\n * Attach the sequence of mixins to the class prototype.\r\n * \r\n * ```javascript\r\n * MyMixableClass.mixins( plainObjMixin, OtherConstructor, ... );\r\n * MyOtherClass.mixins([ plainObjMixin, OtherConstructor, ... ]); \r\n * ```\r\n * \r\n * @param mixins The list of class constructors or plain objects. Both static and prototype properties are mixed in for constructors.\r\n */\r\n static mixins( ...mixins : ( Mixin | Mixin[] )[] ) : typeof Mixable {\r\n const proto = this.prototype,\r\n mergeRules : MixinRules = this._mixinRules || {}, \r\n _appliedMixins = this._appliedMixins = ( this._appliedMixins || [] ).slice();\r\n\r\n // Apply mixins in sequence...\r\n for( let mixin of mixins ) {\r\n // Mixins array should be flattened. \r\n if( mixin instanceof Array ) {\r\n return Mixable.mixins.apply( this, mixin );\r\n }\r\n\r\n // Don't apply mixins twice.\r\n if( _appliedMixins.indexOf( mixin ) >= 0 ) continue;\r\n\r\n _appliedMixins.push( mixin );\r\n\r\n // For constructors, merge _both_ static and prototype members.\r\n if( typeof mixin === 'function' ){\r\n // Statics are merged by simple substitution.\r\n defaults( this, mixin );\r\n\r\n // Prototypes are merged according with a rules.\r\n mergeProps( proto, (>mixin).prototype, mergeRules );\r\n }\r\n // Handle plain object mixins.\r\n else {\r\n mergeProps( proto, mixin, mergeRules );\r\n }\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /** Inversion of control version of [[Mixable.mixin]].\r\n * `Class.mixTo( A, B, ... )` will mix static and prototype `Class` members to the given list of classes.\r\n * `Mixable.mixTo( A, B, ... )` can be used to convert any classes to mixable. \r\n */\r\n static mixTo< T >( ...args : Function[] ) : typeof Mixable {\r\n for( let Ctor of args ) {\r\n Mixable.mixins.call( Ctor, this );\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /** Define specific rules for mixin some particular class members.\r\n * mixinRules of the base class are properly merged on inheritance.\r\n */\r\n static mixinRules( mixinRules : MixinRules ) : MixableConstructor< Mixable > {\r\n const Base = Object.getPrototypeOf( this.prototype ).constructor;\r\n\r\n if( Base._mixinRules ) {\r\n mergeProps( mixinRules, Base._mixinRules );\r\n }\r\n\r\n this._mixinRules = mixinRules;\r\n return this;\r\n }\r\n\r\n /**\r\n * Main metaprogramming method. May be overriden in subclasses to customize the behavior. \r\n * - Merge definition to the class prototype.\r\n * - Add native properties with descriptors from `definition.properties` to the prototype.\r\n * - Prevents inheritance of 'create' factory method.\r\n * - Assign mixinRules static property, and merge it with parent.\r\n * - Adds mixins.\r\n */\r\n static define( definition : ClassDefinition = {}, staticProps? : {} ) : typeof Mixable {\r\n // That actually might happen when we're using @define decorator... \r\n if( !this.define ){\r\n log.error( \"[Class Defininition] Class must have class extensions to use @define decorator. Use '@extendable' before @define, or extend the base class with class extensions.\", definition );\r\n return this;\r\n }\r\n\r\n this.predefine();\r\n\r\n // Obtain references to prototype and base class.\r\n const proto = this.prototype;\r\n\r\n // Extract prototype properties from the definition.\r\n const protoProps = omit( definition, 'properties', 'mixins', 'mixinRules' ),\r\n { properties = {}, mixins, mixinRules } = definition;\r\n\r\n // Update prototype and statics.\r\n assign( proto, protoProps );\r\n assign( this, staticProps );\r\n\r\n // Define native properties.\r\n properties && Object.defineProperties( proto, transform( {}, properties, toPropertyDescriptor ) );\r\n\r\n // Apply mixins and mixin rules.\r\n mixinRules && this.mixinRules( mixinRules );\r\n mixins && this.mixins( mixins );\r\n\r\n return this;\r\n }\r\n\r\n /** Backbone-compatible extend method to be used in ES5 and for backward compatibility */\r\n static extend(spec? : ClassDefinition, statics? : {} ) : typeof Mixable {\r\n let Subclass : typeof Mixable;\r\n\r\n // 1. Create the subclass (ES5 compatibility shim).\r\n // If constructor function is given...\r\n if( spec && spec.hasOwnProperty( 'constructor' ) ){\r\n // ...we need to manually call internal TypeScript __extend function. Hack! Hack!\r\n Subclass = spec.constructor; \r\n __extends( Subclass, this );\r\n }\r\n // Otherwise, create the subclall in usual way.\r\n else{\r\n Subclass = class Subclass extends this {};\r\n }\r\n\r\n // 2. Apply definitions\r\n return spec ? Subclass.define( spec, statics ) : Subclass.predefine();\r\n }\r\n\r\n /** Do the magic necessary for forward declarations.\r\n * Can be overriden by subclasses.\r\n * Must be written in the way that it's safe to call twice.\r\n */\r\n static predefine() : typeof Mixable {\r\n const BaseClass : typeof Mixable = getBaseClass( this );\r\n\r\n // Make sure we don't inherit class factories.\r\n if( BaseClass.create === this.create ) {\r\n this.create = Mixable.create;\r\n }\r\n\r\n this.__super__ = BaseClass.prototype;\r\n\r\n return this;\r\n }\r\n\r\n /** @hidden */\r\n static __super__ : {}\r\n}\r\n \r\n/** @hidden */\r\nfunction toPropertyDescriptor( x : Property ) : PropertyDescriptor {\r\n if( x ){\r\n return typeof x === 'function' ? { get : < () => any >x } : x;\r\n }\r\n}\r\n\r\n/** @decorator `@mixinRules({ ... })`. Has the same effect as [[Mixable.mixinRules]]. Can be used with any ES6 class.\r\n * See [[MixinRules]] for rules specification.\r\n */\r\nexport function mixinRules( rules : MixinRules ) {\r\n return createDecorator( 'mixinRules', rules );\r\n}\r\n\r\n/** @decorator `@mixins( A, B, C... )`. \r\n * Has the same effect as [[Mixable.mixins]]. Can be used with any ES6 class.\r\n */ \r\nexport function mixins( ...list : {}[] ) {\r\n return createDecorator( 'mixins', list );\r\n}\r\n\r\n/** @decorator `@extendable`. Convert ES6 class to be [[Mixable]] one. */\r\nexport function extendable( Type : Function ) : void {\r\n Mixable.mixTo( Type );\r\n}\r\n\r\n/** @decorator `@predefine` for forward definitions. Can be used with [[Mixable]] classes only.\r\n * Forwards the call to the [[Mixable.predefine]]; \r\n */ \r\nexport function predefine( Constructor : MixableConstructor< any > ) : void {\r\n Constructor.predefine();\r\n}\r\n\r\n/** @decorator `@define` for metaprogramming magic. Can be used with [[Mixable]] classes only.\r\n * Forwards the call to [[Mixable.define]]. \r\n */\r\nexport function define( spec : ClassDefinition | MixableConstructor< any > ){\r\n // Handle the case when `@define` used without arguments. \r\n if( typeof spec === 'function' ){\r\n ( > spec).define({});\r\n }\r\n // Normal usage.\r\n else{\r\n return createDecorator( 'define', spec );\r\n }\r\n} \r\n\r\n// Create ES7 class decorator forwarding call to the static class member.\r\n// If there is no such a member, forward the call to Class.\r\n/** @hidden */\r\nfunction createDecorator( name : string, spec : {} ){\r\n return function( Ctor : Function ) : void {\r\n if( Ctor[ name ] ) {\r\n Ctor[ name ]( spec );\r\n }\r\n else {\r\n Mixable[ name ].call( Ctor, spec );\r\n }\r\n }\r\n}\r\n\r\n/***********************\r\n * Mixins helpers\r\n */\r\n/** @hidden */\r\nfunction mergeObjects( a : {}, b : {}, rules? : MixinRules ) : {} {\r\n const x = assign( {}, a );\r\n return mergeProps( x , b, rules );\r\n}\r\n\r\n/** @hidden */\r\ninterface IMergeFunctions {\r\n [ name : string ] : ( a : Function, b : Function ) => Function\r\n}\r\n\r\n/** @hidden */\r\nconst mergeFunctions : IMergeFunctions = {\r\n pipe< A, B, C >( a: ( x : B ) => C, b : ( x : A ) => B ) : ( x : A ) => C {\r\n return function( x : A ) : C {\r\n return a.call( this, b.call( this, x ) );\r\n }\r\n },\r\n\r\n sequence( a : Function, b : Function ){\r\n return function() : void {\r\n a.apply( this, arguments );\r\n b.apply( this, arguments );\r\n }\r\n },\r\n\r\n reverse( a : Function, b : Function ){\r\n return function() : void {\r\n b.apply( this, arguments );\r\n a.apply( this, arguments );\r\n }\r\n },\r\n\r\n every( a : Function, b : Function ){\r\n return function() {\r\n return a.apply( this, arguments ) && b.apply( this, arguments );\r\n }\r\n },\r\n\r\n some( a : Function, b : Function ){\r\n return function() {\r\n return a.apply( this, arguments ) || b.apply( this, arguments );\r\n }\r\n }\r\n};\r\n\r\n/** @hidden */\r\nexport function mergeProps< T extends {} >( target : T, source : {}, rules : MixinRules = {}) : T {\r\n for( let name of Object.keys( source ) ) {\r\n if( name === 'constructor' ) continue;\r\n \r\n const sourceProp = Object.getOwnPropertyDescriptor( source, name ),\r\n destProp = getPropertyDescriptor( target, name ), // Shouldn't be own\r\n value = destProp && destProp.value;\r\n\r\n if( value != null ) {\r\n const rule = rules[ name ];\r\n\r\n if( rule ) {\r\n target[ name ] = typeof rule === 'object' ?\r\n mergeObjects( value, sourceProp.value, rule ) :(\r\n rule === 'merge' ?\r\n mergeObjects( value, sourceProp.value ) :\r\n mergeFunctions[ rule ]( value, sourceProp.value )\r\n );\r\n }\r\n }\r\n else {\r\n Object.defineProperty( target, name, sourceProp );\r\n }\r\n }\r\n\r\n return target;\r\n}\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/object-plus/mixins.ts\n **/","import Mixins = require( './mixins' )\r\nimport tools = require( './tools' );\r\nimport _eventsApi = require( './events-api' );\r\nimport { EventMap, EventsDefinition } from './events-api'\r\n\r\nconst { mixins, define, extendable } = Mixins,\r\n { omit, once, isEmpty, keys } = tools,\r\n { EventHandler, trigger0, trigger1, trigger2, trigger3 } = _eventsApi;\r\n\r\n// Regular expression used to split event strings.\r\nconst eventSplitter = /\\s+/;\r\n\r\nlet _idCount = 0;\r\n\r\nfunction uniqueId() : string {\r\n return 'l' + _idCount++;\r\n}\r\n\r\nexport { EventMap, EventsDefinition }\r\n\r\nexport interface MessengerDefinition extends Mixins.ClassDefinition {\r\n _localEvents? : EventMap\r\n localEvents? : EventsDefinition\r\n}\r\n\r\n/*************************\r\n * Messenger is mixable class with capabilities of sending and receiving synchronous events.\r\n * This class itself can serve as both mixin and base class.\r\n */\r\n@extendable\r\nexport abstract class Messenger implements Mixins.Mixable {\r\n // Define extendable mixin static properties.\r\n static create : ( a : any, b? : any, c? : any ) => Messenger\r\n static mixins : ( ...mixins : ( Mixins.Constructor | {} )[] ) => Mixins.MixableConstructor< Messenger >\r\n static mixinRules : ( mixinRules : Mixins.MixinRules ) => Mixins.MixableConstructor< Messenger >\r\n static mixTo : ( ...args : Mixins.Constructor[] ) => Mixins.MixableConstructor< Messenger >\r\n static extend : (spec? : MessengerDefinition, statics? : {} ) => Mixins.MixableConstructor< Messenger >\r\n static predefine : () => Mixins.MixableConstructor< Messenger >\r\n\r\n /** @hidden */ \r\n _events : _eventsApi.EventsSubscription = void 0;\r\n\r\n /** @hidden */ \r\n _listeners : Listeners = void 0\r\n\r\n /** @hidden */ \r\n _listeningTo : ListeningToMap = void 0\r\n\r\n /** Unique client-only id. */\r\n cid : string\r\n\r\n // Prototype-only property to manage automatic local events subscription.\r\n /** @hidden */ \r\n _localEvents : _eventsApi.EventMap\r\n\r\n /** @private */\r\n static define( protoProps? : MessengerDefinition , staticProps? ) : typeof Messenger {\r\n const spec : MessengerDefinition = omit( protoProps || {}, 'localEvents' );\r\n\r\n if( protoProps ){\r\n const { localEvents, _localEvents } = protoProps;\r\n if( localEvents || _localEvents ){\r\n const eventsMap = new EventMap( this.prototype._localEvents );\r\n localEvents && eventsMap.addEventsMap( localEvents );\r\n _localEvents && eventsMap.merge( _localEvents );\r\n spec._localEvents = eventsMap;\r\n }\r\n }\r\n\r\n return Mixins.Mixable.define.call( this, spec, staticProps );\r\n }\r\n\r\n /** @hidden */ \r\n constructor(){\r\n this.cid = uniqueId();\r\n this.initialize.apply( this, arguments );\r\n }\r\n\r\n /** Method is called at the end of the constructor */\r\n initialize() : void {}\r\n \r\n /** Bind an event to a `callback` function. Passing `\"all\"` will bind\r\n * the callback to all events fired.\r\n */\r\n on(name, callback, context?) : this {\r\n return internalOn(this, name, callback, context);\r\n }\r\n\r\n /** Remove one or many callbacks. If `context` is null, removes all\r\n * callbacks with that function. If `callback` is null, removes all\r\n * callbacks for the event. If `name` is null, removes all bound\r\n * callbacks for all events.\r\n */\r\n off(name? : string, callback? : Function, context? ) : this {\r\n if (!this._events) return this;\r\n this._events = eventsApi(offApi, this._events, name, callback,\r\n new OffOptions(\r\n context,\r\n this._listeners )\r\n );\r\n return this;\r\n }\r\n\r\n /** Tell this object to stop listening to either specific events ... or\r\n * to every object it's currently listening to.\r\n */ \r\n stopListening( obj? : Messenger, name? : string, callback? : Function ) : this {\r\n const listeningTo = this._listeningTo;\r\n if (!listeningTo) return this;\r\n\r\n const ids = obj ? [obj.cid] : keys(listeningTo);\r\n\r\n for (let i = 0; i < ids.length; i++) {\r\n const listening = listeningTo[ids[i]];\r\n\r\n // If listening doesn't exist, this object is not currently\r\n // listening to obj. Break out early.\r\n if (!listening) break;\r\n\r\n listening.obj.off(name, callback, this);\r\n }\r\n if (isEmpty(listeningTo)) this._listeningTo = void 0;\r\n\r\n return this;\r\n }\r\n\r\n /** Inversion-of-control versions of `on`. Tell *this* object to listen to\r\n * an event in another object... keeping track of what it's listening to\r\n * for easier unbinding later.\r\n */ \r\n listenTo(obj : Messenger, name, callback? ) : this {\r\n if( !obj ) return this;\r\n \r\n const id = obj.cid || (obj.cid = uniqueId()),\r\n listeningTo = this._listeningTo || (this._listeningTo = {});\r\n\r\n let listening = listeningTo[id];\r\n\r\n // This object is not listening to any other events on `obj` yet.\r\n // Setup the necessary references to track the listening callbacks.\r\n if (!listening) {\r\n const thisId = this.cid || (this.cid = uniqueId());\r\n listening = listeningTo[id] = new ListeningTo( obj, id, thisId, listeningTo );\r\n }\r\n\r\n // Bind callbacks on obj, and keep track of them on listening.\r\n internalOn( obj, name, callback, this, listening );\r\n return this;\r\n }\r\n\r\n /** Bind an event to only be triggered a single time. After the first time\r\n * the callback is invoked, its listener will be removed. If multiple events\r\n * are passed in using the space-separated syntax, the handler will fire\r\n * once for each event, not once for a combination of all events.\r\n */ \r\n once(name, callback, context) : this {\r\n // Map the event into a `{event: once}` object.\r\n const events = eventsApi(onceMap, {}, name, callback, this.off.bind( this ));\r\n return this.on(events, void 0, context);\r\n }\r\n\r\n /** Inversion-of-control versions of `once`.*/\r\n listenToOnce(obj : Messenger, name, callback) : this {\r\n // Map the event into a `{event: once}` object.\r\n const events = eventsApi(onceMap, {}, name, callback, this.stopListening.bind( this, obj ) );\r\n return this.listenTo(obj, events);\r\n }\r\n\r\n /** Trigger one or many events, firing all bound callbacks. Callbacks are\r\n * passed the same arguments as `trigger` is, apart from the event name\r\n * (unless you're listening on `\"all\"`, which will cause your callback to\r\n * receive the true name of the event as the first argument).\r\n */ \r\n trigger(name : string, a?, b?, c? ) : this {\r\n if( !this._events ) return this;\r\n\r\n switch( arguments.length ){\r\n // Forward call to monomorphic fast-path functions.\r\n case 1 : trigger0( this, name ); break;\r\n case 2 : trigger1( this, name, a ); break;\r\n case 3 : trigger2( this, name, a, b ); break;\r\n case 4 : trigger3( this, name, a, b, c ); break;\r\n \r\n // Trigger event with more than 3 arguments.\r\n default :\r\n // Passing arguments around killing performance. Convert it to array.\r\n const allArgs = Array( arguments.length );\r\n \r\n for( let i = 0; i < allArgs.length; i++ ){\r\n allArgs[ i ] = arguments[ i ];\r\n }\r\n\r\n // Send events.\r\n const { _events } = this;\r\n let queue = _events[ name ];\r\n\r\n if( queue ) _fireEventAll( queue, allArgs.slice( 1 ) );\r\n if( queue = _events.all ) _fireEventAll( queue, allArgs ); \r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Destructor. Stops messenger from listening to all objects,\r\n * and stop others from listening to the messenger. \r\n */\r\n dispose() : void {\r\n this.stopListening();\r\n this.off();\r\n }\r\n}\r\n\r\n/** @hidden */\r\nconst slice = Array.prototype.slice;\r\n\r\n/**\r\n * Backbone 1.2 API conformant Events mixin.\r\n */\r\nexport const Events : Messenger = omit( Messenger.prototype, 'constructor', 'initialize' );\r\n\r\n// Iterates over the standard `event, callback` (as well as the fancy multiple\r\n// space-separated events `\"change blur\", callback` and jQuery-style event\r\n// maps `{event: callback}`).\r\n/** @hidden */\r\nfunction eventsApi(iteratee, events, name, callback, opts) {\r\n let i = 0, names;\r\n if (name && typeof name === 'object') {\r\n // Handle event maps.\r\n if (callback !== void 0 && 'context' in opts && opts.context === void 0) opts.context = callback;\r\n for (names = keys(name); i < names.length ; i++) {\r\n events = eventsApi(iteratee, events, names[i], name[names[i]], opts);\r\n }\r\n } else if (name && eventSplitter.test(name)) {\r\n // Handle space separated event names by delegating them individually.\r\n for (names = name.split(eventSplitter); i < names.length; i++) {\r\n events = iteratee(events, names[i], callback, opts);\r\n }\r\n } else {\r\n // Finally, standard events.\r\n events = iteratee(events, name, callback, opts);\r\n }\r\n return events;\r\n};\r\n\r\n/** @hidden */\r\nclass ListeningTo {\r\n count : number = 0\r\n constructor( public obj, public objId, public id, public listeningTo ){}\r\n}\r\n\r\n/** @hidden */\r\nexport interface ListeningToMap {\r\n [ id : string ] : ListeningTo\r\n}\r\n\r\n/** @hidden */\r\nexport interface Listeners {\r\n [ id : string ] : Messenger\r\n}\r\n\r\n// Guard the `listening` argument from the public API.\r\n/** @hidden */\r\nfunction internalOn(obj : Messenger, name, callback, context, listening? ) : Messenger {\r\n obj._events = eventsApi(onApi, obj._events || {}, name,\r\n callback, new EventHandler( context, obj, listening));\r\n\r\n if (listening) {\r\n const listeners = obj._listeners || (obj._listeners = {});\r\n listeners[listening.id] = listening;\r\n }\r\n\r\n return obj;\r\n};\r\n\r\n// The reducing API that adds a callback to the `events` object.\r\n/** @hidden */\r\nfunction onApi(events : _eventsApi.EventsSubscription, name : string, callback : Function, options) : _eventsApi.EventsSubscription {\r\n if (callback) {\r\n const handlers = events[name],\r\n toAdd = [ options.clone( callback ) ];\r\n \r\n events[name] = handlers ? handlers.concat( toAdd ) : toAdd;\r\n }\r\n \r\n return events;\r\n};\r\n\r\n/** @hidden */\r\nclass OffOptions {\r\n constructor( public context, public listeners : Listeners ){}\r\n}\r\n\r\n// The reducing API that removes a callback from the `events` object.\r\n/** @hidden */\r\nfunction offApi(events : _eventsApi.EventsSubscription, name, callback, options : OffOptions ) {\r\n if (!events) return;\r\n\r\n let i = 0, listening;\r\n const context = options.context, listeners = options.listeners;\r\n\r\n // Delete all events listeners and \"drop\" events.\r\n if (!name && !callback && !context) {\r\n const ids = keys(listeners);\r\n for (; i < ids.length; i++) {\r\n listening = listeners[ids[i]];\r\n delete listeners[listening.id];\r\n delete listening.listeningTo[listening.objId];\r\n }\r\n return {};\r\n }\r\n\r\n const names = name ? [name] : keys(events);\r\n for (; i < names.length; i++) {\r\n name = names[i];\r\n const handlers = events[name];\r\n\r\n // Bail out if there are no events stored.\r\n if (!handlers) break;\r\n\r\n // Replace events if there are any remaining. Otherwise, clean up.\r\n const remaining = [];\r\n for (let j = 0; j < handlers.length; j++) {\r\n const handler = handlers[j];\r\n if (\r\n callback && callback !== handler.callback &&\r\n callback !== handler.callback._callback ||\r\n context && context !== handler.context\r\n ) {\r\n remaining.push(handler);\r\n } else {\r\n listening = handler.listening;\r\n if (listening && --listening.count === 0) {\r\n delete listeners[listening.id];\r\n delete listening.listeningTo[listening.objId];\r\n }\r\n }\r\n }\r\n\r\n // Update tail event if the list has any events. Otherwise, clean up.\r\n if (remaining.length) {\r\n events[name] = remaining;\r\n } else {\r\n delete events[name];\r\n }\r\n }\r\n return events;\r\n};\r\n\r\n// Reduces the event callbacks into a map of `{event: onceWrapper}`.\r\n// `offer` unbinds the `onceWrapper` after it has been called.\r\n/** @hidden */\r\nfunction onceMap(map, name, callback, offer) {\r\n if (callback) {\r\n const _once : _eventsApi.Callback = map[name] = once(function() {\r\n offer(name, _once);\r\n callback.apply(this, arguments);\r\n });\r\n _once._callback = callback;\r\n }\r\n return map;\r\n};\r\n\r\n/** @hidden */\r\nfunction _fireEventAll( events : _eventsApi.EventHandler[], a ) : void {\r\n for( let ev of events )\r\n ev.callback.apply( ev.ctx, a );\r\n}\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/object-plus/messenger.ts\n **/","/**************************************************************\r\n * Low-level high-performance publish-subscrive events API.\r\n * Monomorphic, minimalistic, JIT optimized.\r\n * \r\n * Implementation is 100% structurally compatible woth a subset of Backbone 1.2 Events.\r\n * \r\n * Type-R solely depends on that API for managing events subscriptions.\r\n */\r\n\r\n/** @hide */\r\nexport const eventSplitter = /\\s+/;\r\n\r\n/** @hide Main interface object must conform to in order to send events */\r\nexport interface EventSource {\r\n _events : EventsSubscription\r\n}\r\n\r\n/** @hide Internal hash holding events subscription */\r\nexport interface EventsSubscription {\r\n all? : EventHandler[]\r\n [ eventName : string ] : EventHandler[]\r\n}\r\n\r\n/** @hide Event handler data structure, with a shape expected by Backbone 1.2 Events */\r\nexport class EventHandler {\r\n constructor(\r\n public context,\r\n public ctx,\r\n public listening : any,\r\n public callback? : Callback\r\n ){}\r\n\r\n clone( callback ){\r\n const { context, listening } = this;\r\n if (listening) listening.count++;\r\n return new EventHandler( context, context || this.ctx, listening, callback );\r\n }\r\n}\r\n\r\n/** @hide Callback structure, with a shape expected by Backbone 1.2 Events */\r\nexport interface Callback extends Function{\r\n _callback? : any\r\n}\r\n\r\n/*******************\r\n * Prebuilt events map, used for optimized bulk event subscriptions.\r\n * \r\n * const events = new EventMap({\r\n * 'change' : true, // Resend this event from self as it is.\r\n * 'change:attr' : 'localTargetFunction',\r\n * 'executedInTargetContext' : function(){ ... }\r\n * 'executedInNativeContext' : '^props.handler' \r\n * })\r\n */\r\n/** @hide */\r\nexport interface EventsDefinition {\r\n [ events : string ] : Function | string | boolean\r\n}\r\n\r\n/** @hide */\r\nexport class EventMap {\r\n handlers : EventDescriptor[] = [];\r\n\r\n constructor( map? : EventsDefinition | EventMap ){\r\n if( map ){\r\n if( map instanceof EventMap ){\r\n this.handlers = map.handlers.slice();\r\n }\r\n else{\r\n map && this.addEventsMap( map );\r\n }\r\n }\r\n }\r\n\r\n merge( map : EventMap ){\r\n this.handlers = this.handlers.concat( map.handlers );\r\n }\r\n\r\n addEventsMap( map : EventsDefinition ){\r\n for( let names in map ){\r\n this.addEvent( names, map[ names ] )\r\n }\r\n }\r\n\r\n bubbleEvents( names : string ){\r\n for( let name of names.split( eventSplitter ) ){\r\n this.addEvent( name, getBubblingHandler( name ) );\r\n }\r\n }\r\n\r\n addEvent( names : string, callback : Function | string | boolean ){\r\n const { handlers } = this; \r\n \r\n for( let name of names.split( eventSplitter ) ){\r\n handlers.push( new EventDescriptor( name, callback ) );\r\n } \r\n }\r\n\r\n subscribe( target : {}, source : EventSource ){\r\n const _events = source._events || ( source._events = {} );\r\n for( let event of this.handlers ){\r\n _on( _events, event.name, event.callback, target );\r\n }\r\n }\r\n\r\n unsubscribe( target : {}, source : EventSource ){\r\n const { _events } = source;\r\n if( _events ){\r\n for( let event of this.handlers ){\r\n _off( _events, event.name, event.callback, target );\r\n }\r\n }\r\n }\r\n}\r\n\r\n/** @hide */\r\nclass EventDescriptor {\r\n callback : Function\r\n\r\n constructor(\r\n public name : string,\r\n callback : Function | string | boolean\r\n ){\r\n if( callback === true ){\r\n this.callback = getBubblingHandler( name );\r\n }\r\n else if( typeof callback === 'string' ){\r\n this.callback = \r\n function localCallback(){\r\n const handler = this[ callback ]; \r\n handler && handler.apply( this, arguments );\r\n };\r\n }\r\n else{\r\n this.callback = callback;\r\n }\r\n }\r\n}\r\n\r\n/****************************\r\n * Subscription API \r\n */\r\n\r\n/** @hide */\r\nexport function on( self : EventSource, name : string, callback : Function, context? ){\r\n const _events = self._events || ( self._events = {} );\r\n _on( _events, name, callback, context );\r\n}\r\n\r\n/** @hide */\r\nexport function off( self : EventSource, name : string, callback : Function, context : {} ){\r\n const { _events } = self;\r\n _events && _off( _events, name, callback, context );\r\n}\r\n\r\n/*********************************\r\n * Event-triggering API \r\n */\r\n/** @hide */\r\nexport function trigger0( self : EventSource, name : string ) : void {\r\n const { _events } = self;\r\n if( _events ){\r\n const queue = _events[ name ],\r\n { all } = _events;\r\n\r\n if( queue ) _fireEvent0( queue );\r\n if( all ) _fireEvent1( all, name );\r\n }\r\n};\r\n\r\n/** @hide */\r\nexport function trigger1( self : EventSource, name : string, a : any ) : void {\r\n const { _events } = self;\r\n if( _events ){\r\n const queue = _events[ name ],\r\n { all } = _events;\r\n\r\n if( queue ) _fireEvent1( queue, a );\r\n if( all ) _fireEvent2( all, name, a );\r\n }\r\n};\r\n\r\n/** @hide */\r\nexport function trigger2( self : EventSource, name : string, a, b ) : void {\r\n const { _events } = self;\r\n if( _events ){\r\n const queue = _events[ name ],\r\n { all } = _events;\r\n\r\n if( queue ) _fireEvent2( queue, a, b );\r\n if( all ) _fireEvent3( all, name, a, b );\r\n }\r\n};\r\n\r\n/** @hide */\r\nexport function trigger3( self : EventSource, name : string, a, b, c ) : void{\r\n const { _events } = self;\r\n if( _events ){\r\n const queue = _events[ name ],\r\n { all } = _events;\r\n\r\n if( queue ) _fireEvent3( queue, a, b, c );\r\n if( all ) _fireEvent4( all, name, a, b, c );\r\n }\r\n};\r\n\r\n// Specialized functions with events triggering loops.\r\n// JS JIT loves these small functions and code duplication.\r\n/** @hide */\r\nfunction _fireEvent0( events : EventHandler[] ) : void {\r\n for( let ev of events )\r\n ev.callback.call( ev.ctx );\r\n}\r\n\r\n/** @hide */\r\nfunction _fireEvent1( events : EventHandler[], a ) : void {\r\n for( let ev of events )\r\n ev.callback.call( ev.ctx, a );\r\n}\r\n\r\n/** @hide */\r\nfunction _fireEvent2( events : EventHandler[], a, b ) : void {\r\n for( let ev of events )\r\n ev.callback.call( ev.ctx, a, b );\r\n}\r\n\r\n/** @hide */\r\nfunction _fireEvent3( events : EventHandler[], a, b, c ) : void {\r\n for( let ev of events )\r\n ev.callback.call( ev.ctx, a, b, c );\r\n}\r\n\r\n/** @hide */\r\nfunction _fireEvent4( events : EventHandler[], a, b, c, d ) : void {\r\n for( let ev of events )\r\n ev.callback.call( ev.ctx, a, b, c, d );\r\n}\r\n\r\n// Subscrive for the single event\r\n/** @hide */\r\nfunction _on( _events : EventsSubscription, name : string, callback : Function, context : Object, ctx? : Object ){\r\n const events = _events[ name ],\r\n handler = new EventHandler( context, ctx || context, null, callback );\r\n\r\n if( events ){\r\n events.push( handler );\r\n }\r\n else{\r\n _events[ name ] = [ handler ];\r\n }\r\n};\r\n\r\n// Remove all events with a given name and context, or callback, if its provided.\r\n/** @hide */ \r\nfunction _off( _events : EventsSubscription, name : string, callback : Function, context : {} ) {\r\n const events = _events[ name ];\r\n\r\n if( events ) {\r\n const retain = [];\r\n\r\n for ( let ev of events ) {\r\n if( ( callback && callback !== ev.callback ) || context !== ev.context ) {\r\n retain.push(ev);\r\n }\r\n }\r\n\r\n _events[ name ] = retain.length ? retain : void 0;\r\n }\r\n};\r\n\r\n/** @hide */\r\nconst _bubblingHandlers = {};\r\n\r\n/** @hide */\r\nfunction getBubblingHandler( event : string ){\r\n return _bubblingHandlers[ event ] || (\r\n _bubblingHandlers[ event ] = function( a, b, c ){\r\n switch( arguments.length ){\r\n // Forward call to monomorphic fast-path functions.\r\n case 0 : trigger0( this, event ); break;\r\n case 1 : trigger1( this, event, a ); break;\r\n case 2 : trigger2( this, event, a, b ); break;\r\n case 3 : trigger3( this, event, a, b, c ); break;\r\n default :\r\n const args = [ event, a, b, c ];\r\n\r\n for( let i = 3; i < arguments.length; i++ ){\r\n args.push( arguments[ i ] );\r\n }\r\n\r\n this.trigger.apply( this, args );\r\n }\r\n }\r\n );\r\n}\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/object-plus/events-api.ts\n **/","import { define, tools, eventsApi, EventMap, EventsDefinition, Mixable } from '../object-plus'\r\nimport { transactionApi, Transactional, CloneOptions, Transaction, TransactionOptions, TransactionalDefinition, Owner } from '../transactions'\r\nimport { Record, SharedRecordType, TransactionalType, createSharedTypeSpec } from '../record'\r\n\r\nimport { IdIndex, sortElements, dispose, Elements, CollectionCore, addIndex, removeIndex, updateIndex, Comparator, CollectionTransaction } from './commons'\r\nimport { addTransaction } from './add'\r\nimport { setTransaction, emptySetTransaction } from './set'\r\nimport { removeOne, removeMany } from './remove'\r\n\r\nconst { trigger2 } = eventsApi,\r\n { begin, commit, markAsDirty } = transactionApi,\r\n { omit, log, assign, defaults } = tools;\r\n\r\nlet _count = 0;\r\n\r\nconst silentOptions = { silent : true };\r\n\r\nexport type GenericComparator = string | ( ( x : Record ) => number ) | ( ( a : Record, b : Record ) => number ); \r\n\r\n\r\nexport interface CollectionOptions extends TransactionOptions {\r\n comparator? : GenericComparator\r\n model? : typeof Record\r\n}\r\n\r\ninterface CollectionDefinition extends TransactionalDefinition {\r\n model? : Record,\r\n itemEvents? : EventsDefinition\r\n _itemEvents? : EventMap\r\n}\r\n\r\n@define({\r\n // Default client id prefix \r\n cidPrefix : 'c',\r\n model : Record,\r\n _changeEventName : 'changes',\r\n _aggregationError : null\r\n})\r\nexport class Collection extends Transactional implements CollectionCore {\r\n _shared : number\r\n _aggregationError : Record[]\r\n\r\n static Subset : typeof Collection\r\n static Set : typeof Collection\r\n static _SubsetOf : typeof Collection\r\n \r\n createSubset( models, options ){\r\n const SubsetOf = (this.constructor).subsetOf( this ).options.type,\r\n subset = new SubsetOf( models, options );\r\n \r\n subset.resolve( this );\r\n return subset;\r\n }\r\n\r\n static predefine() : any {\r\n // Cached subset collection must not be inherited.\r\n const Ctor = this;\r\n this._SubsetOf = null;\r\n\r\n function Subset( a, b, listen? ){\r\n Ctor.call( this, a, b, listen ? 1 : 2 );\r\n }\r\n\r\n Mixable.mixTo( Subset );\r\n \r\n Subset.prototype = this.prototype;\r\n Subset._attribute = TransactionalType;\r\n Subset[ 'of' ] = function( path ){\r\n return Ctor.subsetOf( path );\r\n }\r\n\r\n this.Set = this.Subset = Subset;\r\n\r\n Transactional.predefine.call( this );\r\n createSharedTypeSpec( this, SharedCollectionType );\r\n return this;\r\n }\r\n \r\n static define( protoProps : CollectionDefinition = {}, staticProps? ){\r\n // Extract record definition from static members, if any.\r\n const staticsDefinition : CollectionDefinition = tools.getChangedStatics( this, 'model', 'itemEvents' ),\r\n // Definition can be made either through statics or define argument.\r\n // Merge them together, so we won't care about it below. \r\n definition = assign( staticsDefinition, protoProps );\r\n\r\n const spec : CollectionDefinition = omit( definition, 'itemEvents' );\r\n\r\n if( definition.itemEvents ){\r\n const eventsMap = new EventMap( this.prototype._itemEvents );\r\n eventsMap.addEventsMap( definition.itemEvents );\r\n spec._itemEvents = eventsMap; \r\n }\r\n\r\n return Transactional.define.call( this, spec, staticProps );\r\n }\r\n\r\n static subsetOf : ( collectionReference : any ) => any;\r\n \r\n _itemEvents : EventMap\r\n\r\n /***********************************\r\n * Core Members\r\n */\r\n // Array of the records\r\n models : Record[]\r\n\r\n // Polymorphic accessor for aggregated attribute's canBeUpdated().\r\n get _state(){ return this.models; }\r\n\r\n // Index by id and cid\r\n _byId : IdIndex\r\n\r\n set comparator( x : GenericComparator ){\r\n let compare;\r\n\r\n switch( typeof x ){\r\n case 'string' :\r\n this._comparator = ( a, b ) => {\r\n const aa = a[ x ], bb = b[ x ];\r\n if( aa === bb ) return 0;\r\n return aa < bb ? -1 : + 1;\r\n } \r\n break;\r\n case 'function' :\r\n if( x.length === 1 ){\r\n this._comparator = ( a, b ) => {\r\n const aa = (x).call( this, a ), bb = (x).call( this, b );\r\n if( aa === bb ) return 0;\r\n return aa < bb ? -1 : + 1;\r\n }\r\n }\r\n else{\r\n this._comparator = ( a, b ) => (x).call( this, a, b );\r\n }\r\n break;\r\n \r\n default :\r\n this._comparator = null;\r\n }\r\n }\r\n \r\n // TODO: Improve typing\r\n getStore() : Transactional {\r\n return this._store || ( this._store = this._owner ? this._owner.getStore() : this._defaultStore );\r\n }\r\n\r\n _store : Transactional\r\n\r\n get comparator(){ return this._comparator; }\r\n _comparator : ( a : Record, b : Record ) => number\r\n\r\n _onChildrenChange( record : Record, options : TransactionOptions = {}, initiator? : Transactional ){\r\n // Ignore updates from nested transactions.\r\n if( initiator === this ) return;\r\n\r\n const { idAttribute } = this;\r\n\r\n if( record.hasChanged( idAttribute ) ){\r\n updateIndex( this._byId, record );\r\n }\r\n\r\n const isRoot = begin( this );\r\n\r\n if( markAsDirty( this, options ) ){\r\n // Forward change event from the record.\r\n trigger2( this, 'change', record, options )\r\n }\r\n\r\n isRoot && commit( this );\r\n }\r\n\r\n get( objOrId : string | Record | Object ) : Record {\r\n if( objOrId == null ) return;\r\n\r\n if( typeof objOrId === 'object' ){\r\n const id = objOrId[ this.idAttribute ];\r\n return ( id !== void 0 && this._byId[ id ] ) || this._byId[ (objOrId).cid ];\r\n }\r\n else{\r\n return this._byId[ objOrId ];\r\n } \r\n }\r\n\r\n each( iteratee : ( val : Record, key : number ) => void, context? : any ){\r\n const fun = arguments.length === 2 ? ( v, k ) => iteratee.call( context, v, k ) : iteratee,\r\n { models } = this;\r\n\r\n for( let i = 0; i < models.length; i++ ){\r\n fun( models[ i ], i ); \r\n }\r\n }\r\n\r\n _validateNested( errors : {} ) : number {\r\n // Don't validate if not aggregated.\r\n if( this._shared ) return 0;\r\n\r\n let count = 0;\r\n\r\n this.each( record => {\r\n const error = record.validationError;\r\n if( error ){\r\n errors[ record.cid ] = error;\r\n count++;\r\n }\r\n });\r\n\r\n return count;\r\n }\r\n\r\n model : typeof Record\r\n\r\n // idAttribute extracted from the model type.\r\n idAttribute : string\r\n\r\n constructor( records? : ( Record | {} )[], options : CollectionOptions = {}, shared? : number ){\r\n super( _count++ );\r\n this.models = [];\r\n this._byId = {};\r\n \r\n this.comparator = this.comparator;\r\n\r\n if( options.comparator !== void 0 ){\r\n this.comparator = options.comparator;\r\n options.comparator = void 0;\r\n }\r\n \r\n this.model = this.model;\r\n \r\n if( options.model ){\r\n this.model = options.model;\r\n options.model = void 0;\r\n }\r\n\r\n this.idAttribute = this.model.prototype.idAttribute; //TODO: Remove?\r\n\r\n this._shared = shared || 0;\r\n\r\n if( records ){\r\n const elements = toElements( this, records, options );\r\n emptySetTransaction( this, elements, options, true );\r\n }\r\n\r\n this.initialize.apply( this, arguments );\r\n\r\n if( this._localEvents ) this._localEvents.subscribe( this, this );\r\n }\r\n\r\n initialize(){}\r\n\r\n get length() : number { return this.models.length; }\r\n first() : Record { return this.models[ 0 ]; }\r\n last() : Record { return this.models[ this.models.length - 1 ]; }\r\n at( a_index : number ) : Record {\r\n const index = a_index < 0 ? a_index + this.models.length : a_index; \r\n return this.models[ index ];\r\n }\r\n\r\n // Deeply clone collection, optionally setting new owner.\r\n clone( options : CloneOptions = {} ) : this {\r\n const models = this.map( model => model.clone() ),\r\n copy : this = new (this.constructor)( models, { model : this.model, comparator : this.comparator }, this._shared );\r\n \r\n if( options.pinStore ) copy._defaultStore = this.getStore();\r\n \r\n return copy;\r\n }\r\n\r\n toJSON() : Object[] {\r\n // Don't serialize when not aggregated\r\n if( !this._shared ){\r\n return this.models.map( model => model.toJSON() );\r\n }\r\n }\r\n\r\n // Apply bulk in-place object update in scope of ad-hoc transaction \r\n set( elements : ElementsArg = [], options : TransactionOptions = {} ) : this {\r\n if( (options).add !== void 0 ){\r\n this._log( 'warn', \"Collection.set doesn't support 'add' option, behaving as if options.add === true.\", options );\r\n }\r\n\r\n // Handle reset option here - no way it will be populated from the top as nested transaction.\r\n if( options.reset ){\r\n this.reset( elements, options )\r\n }\r\n else{\r\n const transaction = this._createTransaction( elements, options );\r\n transaction && transaction.commit();\r\n } \r\n\r\n return this; \r\n }\r\n\r\n dispose(){\r\n if( !this._shared ){\r\n for( let record of this.models ){\r\n if( record._owner === this ) record.dispose();\r\n }\r\n }\r\n\r\n super.dispose();\r\n }\r\n\r\n reset( a_elements : ElementsArg, options : TransactionOptions = {} ) : Record[] {\r\n const isRoot = begin( this ),\r\n previousModels = dispose( this );\r\n\r\n // Make all changes required, but be silent.\r\n if( a_elements ){ \r\n emptySetTransaction( this, toElements( this, a_elements, options ), options, true );\r\n }\r\n\r\n markAsDirty( this, options );\r\n\r\n options.silent || trigger2( this, 'reset', this, defaults( { previousModels : previousModels }, options ) );\r\n\r\n isRoot && commit( this );\r\n return this.models;\r\n }\r\n\r\n // Add elements to collection.\r\n add( a_elements : ElementsArg , options : TransactionOptions = {} ){\r\n const elements = toElements( this, a_elements, options ),\r\n transaction = this.models.length ?\r\n addTransaction( this, elements, options ) :\r\n emptySetTransaction( this, elements, options );\r\n\r\n if( transaction ){\r\n transaction.commit();\r\n return transaction.added;\r\n } \r\n }\r\n\r\n // Remove elements. \r\n remove( recordsOrIds : any, options : TransactionOptions = {} ) : Record[] | Record {\r\n if( recordsOrIds ){\r\n return Array.isArray( recordsOrIds ) ?\r\n removeMany( this, recordsOrIds, options ) :\r\n removeOne( this, recordsOrIds, options );\r\n }\r\n\r\n return [];\r\n }\r\n\r\n // Apply bulk object update without any notifications, and return open transaction.\r\n // Used internally to implement two-phase commit. \r\n _createTransaction( a_elements : ElementsArg, options : TransactionOptions = {} ) : CollectionTransaction {\r\n const elements = toElements( this, a_elements, options );\r\n\r\n if( this.models.length ){\r\n return options.remove === false ?\r\n addTransaction( this, elements, options, true ) :\r\n setTransaction( this, elements, options );\r\n }\r\n else{\r\n return emptySetTransaction( this, elements, options );\r\n }\r\n }\r\n\r\n static _attribute = TransactionalType;\r\n\r\n /***********************************\r\n * Collection manipulation methods\r\n */\r\n\r\n pluck( key : string ) : any[] {\r\n return this.models.map( model => model[ key ] );\r\n }\r\n\r\n sort( options : TransactionOptions = {} ) : this {\r\n if( sortElements( this, options ) ){\r\n const isRoot = begin( this );\r\n \r\n if( markAsDirty( this, options ) ){\r\n trigger2( this, 'sort', this, options );\r\n }\r\n\r\n isRoot && commit( this );\r\n }\r\n\r\n return this;\r\n }\r\n\r\n // Add a model to the end of the collection.\r\n push(model, options) {\r\n return this.add(model, assign({at: this.length}, options));\r\n }\r\n\r\n // Remove a model from the end of the collection.\r\n pop(options) {\r\n var model = this.at(this.length - 1);\r\n this.remove(model, options);\r\n return model;\r\n }\r\n\r\n // Add a model to the beginning of the collection.\r\n unshift(model, options) {\r\n return this.add(model, assign({at: 0}, options));\r\n }\r\n\r\n // Remove a model from the beginning of the collection.\r\n shift( options? : CollectionOptions ) : Record {\r\n var model = this.at(0);\r\n this.remove( model, options );\r\n return model;\r\n }\r\n\r\n // Slice out a sub-array of models from the collection.\r\n slice() : Record[] {\r\n return slice.apply(this.models, arguments);\r\n }\r\n\r\n indexOf( modelOrId : any ) : number {\r\n const record = this.get( modelOrId );\r\n return this.models.indexOf( record );\r\n }\r\n\r\n modelId( attrs : {} ) : any {\r\n return attrs[ this.model.prototype.idAttribute ];\r\n }\r\n\r\n // Toggle model in collection.\r\n toggle( model : Record, a_next? : boolean ) : boolean {\r\n var prev = Boolean( this.get( model ) ),\r\n next = a_next === void 0 ? !prev : Boolean( a_next );\r\n\r\n if( prev !== next ){\r\n if( prev ){\r\n this.remove( model );\r\n }\r\n else{\r\n this.add( model );\r\n }\r\n }\r\n\r\n return next;\r\n }\r\n\r\n _log( level : string, text : string, value ) : void {\r\n tools.log[ level ]( `[Collection Update] ${ this.model.prototype.getClassName() }.${ this.getClassName() }: ` + text, value, 'Attributes spec:', this.model.prototype._attributes );\r\n }\r\n\r\n getClassName() : string {\r\n return super.getClassName() || 'Collection';\r\n }\r\n}\r\n\r\ntype ElementsArg = Object | Record | Object[] | Record[];\r\n\r\n// TODO: make is safe for parse to return null (?)\r\nfunction toElements( collection : Collection, elements : ElementsArg, options : CollectionOptions ) : Elements {\r\n const parsed = options.parse ? collection.parse( elements, options ) : elements; \r\n return Array.isArray( parsed ) ? parsed : [ parsed ];\r\n}\r\n\r\nconst slice = Array.prototype.slice;\r\n\r\nclass SharedCollectionType extends SharedRecordType {\r\n type : typeof Collection\r\n // Shared object can never be type casted.\r\n convert( value : any, options : TransactionOptions, prev : any, record : Record ) : Transactional {\r\n return value == null || value instanceof this.type ? value : new this.type( value, options, 1 );\r\n }\r\n}\r\n\r\n\r\ncreateSharedTypeSpec( Collection, SharedCollectionType );\r\n\r\nRecord.Collection = Collection;\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/collection/index.ts\n **/","import { Messenger, Listeners, ListeningToMap, MixinRules, MessengerDefinition, tools, extendable, mixins, eventsApi, define, Constructor, MixableConstructor } from './object-plus'\r\nimport { ValidationError, Validatable, ChildrenErrors } from './validation'\r\nimport { Traversable, resolveReference } from './traversable'\r\n\r\nconst { assign } = tools,\r\n { trigger2, trigger3, on, off } = eventsApi;\r\n/***\r\n * Abstract class implementing ownership tree, tho-phase transactions, and validation. \r\n * 1. createTransaction() - apply changes to an object tree, and if there are some events to send, transaction object is created.\r\n * 2. transaction.commit() - send and process all change events, and close transaction.\r\n */\r\n\r\n/** @private */\r\nexport type TransactionalConstructor = MixableConstructor< Transactional >\r\nexport type TransactionalDefinition = MessengerDefinition\r\n\r\n// Transactional object interface\r\n\r\n@mixins( Messenger )\r\n@extendable\r\nexport abstract class Transactional implements Messenger, Validatable, Traversable {\r\n // Mixins are hard in TypeScript. We need to copy type signatures over...\r\n // Define extendable mixin static properties.\r\n static create : ( a : any, b? : any, c? : any ) => Transactional\r\n static mixins : ( ...mixins : ( Constructor | {} )[] ) => MixableConstructor< Transactional >\r\n static mixinRules : ( mixinRules : MixinRules ) => MixableConstructor< Transactional >\r\n static mixTo : ( ...args : Constructor[] ) => MixableConstructor< Transactional >\r\n static extend : (spec? : TransactionalDefinition, statics? : {} ) => MixableConstructor< Transactional >\r\n static define : (spec? : TransactionalDefinition, statics? : {} ) => MixableConstructor< Transactional >\r\n static predefine : () => typeof Messenger\r\n\r\n on : (name, callback, context?) => this\r\n off : (name? : string, callback? : Function, context? ) => this\r\n stopListening : ( obj? : Messenger, name? : string, callback? : Function ) => this\r\n listenTo : (obj : Messenger, name, callback? ) => this\r\n once : (name, callback, context) => this \r\n listenToOnce : (obj : Messenger, name, callback) => this \r\n trigger : (name : string, a?, b?, c? ) => this\r\n \r\n _disposed : boolean;\r\n \r\n dispose() : void {\r\n this._owner = void 0;\r\n this._ownerKey = void 0;\r\n this.off();\r\n this.stopListening();\r\n this._disposed = true;\r\n }\r\n\r\n initialize() : void{}\r\n\r\n /** @private */\r\n _events : eventsApi.EventsSubscription = void 0;\r\n \r\n /** @private */\r\n _listeners : Listeners\r\n\r\n /** @private */\r\n _listeningTo : ListeningToMap\r\n\r\n /** @private */\r\n _localEvents : eventsApi.EventMap\r\n\r\n cid : string\r\n cidPrefix : string\r\n\r\n static shared : any;\r\n\r\n // Unique version token replaced on change\r\n /** @private */\r\n _changeToken : {} = {}\r\n\r\n // true while inside of the transaction\r\n /** @private */\r\n _transaction : boolean = false;\r\n\r\n // Holds current transaction's options, when in the middle of transaction and there're changes but is an unsent change event\r\n /** @private */\r\n _isDirty : TransactionOptions = null;\r\n\r\n // Backreference set by owner (Record, Collection, or other object)\r\n /** @private */\r\n _owner : Owner = void 0;\r\n\r\n // Key supplied by owner. Used by record to identify attribute key.\r\n // Only collections doesn't set the key, which is used to distinguish collections.\r\n /** @private */ \r\n _ownerKey : string = void 0;\r\n\r\n // Name of the change event\r\n /** @private */\r\n _changeEventName : string\r\n\r\n /**\r\n * Subsribe for the changes.\r\n */\r\n onChanges( handler : Function, target? : Messenger ){\r\n on( this, this._changeEventName, handler, target );\r\n }\r\n\r\n /**\r\n * Unsubscribe from changes.\r\n */\r\n offChanges( handler? : Function, target? : Messenger ){\r\n off( this, this._changeEventName, handler, target );\r\n }\r\n\r\n /**\r\n * Listen to changes event. \r\n */\r\n listenToChanges( target : Transactional, handler ){\r\n this.listenTo( target, target._changeEventName, handler );\r\n }\r\n\r\n constructor( cid : string | number ){\r\n this.cid = this.cidPrefix + cid;\r\n }\r\n\r\n // Deeply clone ownership subtree\r\n abstract clone( options? : CloneOptions ) : this\r\n \r\n // Execute given function in the scope of ad-hoc transaction.\r\n transaction( fun : ( self : this ) => void, options : TransactionOptions = {} ) : void{\r\n const isRoot = transactionApi.begin( this );\r\n fun.call( this, this );\r\n isRoot && transactionApi.commit( this );\r\n }\r\n\r\n // Loop through the members in the scope of transaction.\r\n // Transactional version of each()\r\n updateEach( iteratee : ( val : any, key : string ) => void, options? : TransactionOptions ){\r\n const isRoot = transactionApi.begin( this );\r\n this.each( iteratee );\r\n isRoot && transactionApi.commit( this );\r\n }\r\n\r\n // Apply bulk in-place object update in scope of ad-hoc transaction \r\n set( values : any, options? : TransactionOptions ) : this {\r\n if( values ){ \r\n const transaction = this._createTransaction( values, options );\r\n transaction && transaction.commit();\r\n } \r\n\r\n return this;\r\n }\r\n\r\n // Apply bulk object update without any notifications, and return open transaction.\r\n // Used internally to implement two-phase commit.\r\n // Returns null if there are no any changes.\r\n /** @private */ \r\n abstract _createTransaction( values : any, options? : TransactionOptions ) : Transaction\r\n \r\n // Parse function applied when 'parse' option is set for transaction.\r\n parse( data : any, options? : TransactionOptions ) : any { return data }\r\n\r\n // Convert object to the serializable JSON structure\r\n abstract toJSON() : {}\r\n\r\n /*******************\r\n * Traversals and member access\r\n */\r\n \r\n // Get object member by its key.\r\n abstract get( key : string ) : any\r\n\r\n // Get object member by symbolic reference.\r\n deepGet( reference : string ) : any {\r\n return resolveReference( this, reference, ( object, key ) => object.get ? object.get( key ) : object[ key ] );\r\n }\r\n\r\n //_isCollection : boolean\r\n\r\n // Return owner skipping collections.\r\n getOwner() : Owner {\r\n return this._owner;\r\n }\r\n\r\n // Store used when owner chain store lookup failed. Static value in the prototype. \r\n /** @private */\r\n _defaultStore : Transactional\r\n\r\n // Locate the closest store. Store object stops traversal by overriding this method. \r\n getStore() : Transactional {\r\n const { _owner } = this;\r\n return _owner ? _owner.getStore() : this._defaultStore;\r\n }\r\n\r\n\r\n /***************************************************\r\n * Iteration API\r\n */\r\n\r\n // Loop through the members. Must be efficiently implemented in container class.\r\n abstract each( iteratee : ( val : any, key : string | number ) => void, context? : any )\r\n\r\n // Map members to an array\r\n map( iteratee : ( val : any, key : string ) => T, context? : any ) : T[]{\r\n const arr : T[] = [],\r\n fun = arguments.length === 2 ? ( v, k ) => iteratee.call( context, v, k ) : iteratee;\r\n \r\n this.each( ( val, key ) => {\r\n const result = fun( val, key );\r\n if( result !== void 0 ) arr.push( result );\r\n } );\r\n\r\n return arr;\r\n }\r\n\r\n // Map members to an object\r\n mapObject( iteratee : ( val : any, key : string | number ) => T, context? : any ) : { [ key : string ] : T }{\r\n const obj : { [ key : string ] : T } = {},\r\n fun = arguments.length === 2 ? ( v, k ) => iteratee.call( context, v, k ) : iteratee;\r\n \r\n this.each( ( val, key ) => {\r\n const result = iteratee( val, key );\r\n if( result !== void 0 ) obj[ key ] = result;\r\n } );\r\n\r\n return obj;\r\n }\r\n\r\n // Get array of attribute keys (Record) or record ids (Collection) \r\n keys() : string[] {\r\n return this.map( ( value, key ) => {\r\n if( value !== void 0 ) return key;\r\n });\r\n }\r\n\r\n // Get array of attribute values (Record) or records (Collection)\r\n values() : any[] {\r\n return this.map( value => value );\r\n }\r\n \r\n /*********************************\r\n * Validation API\r\n */\r\n\r\n // Lazily evaluated validation error\r\n /** @private */\r\n _validationError : ValidationError = void 0\r\n\r\n // Validate ownership tree and return valudation error \r\n get validationError() : ValidationError {\r\n const error = this._validationError || ( this._validationError = new ValidationError( this ) );\r\n return error.length ? error : null; \r\n }\r\n\r\n // Validate nested members. Returns errors count.\r\n /** @private */\r\n abstract _validateNested( errors : ChildrenErrors ) : number\r\n\r\n // Object-level validator. Returns validation error.\r\n validate( obj? : Transactional ) : any {}\r\n\r\n // Return validation error (or undefined) for nested object with the given key. \r\n getValidationError( key : string ) : any {\r\n var error = this.validationError;\r\n return ( key ? error && error.nested[ key ] : error ) || null;\r\n }\r\n\r\n // Get validation error for the given symbolic reference.\r\n deepValidationError( reference : string ) : any {\r\n return resolveReference( this, reference, ( object, key ) => object.getValidationError( key ) );\r\n }\r\n\r\n // Iterate through all validation errors across the ownership tree.\r\n eachValidationError( iteratee : ( error : any, key : string, object : Transactional ) => void ) : void {\r\n const { validationError } = this;\r\n validationError && validationError.eachError( iteratee, this );\r\n }\r\n\r\n // Check whenever member with a given key is valid. \r\n isValid( key : string ) : boolean {\r\n return !this.getValidationError( key );\r\n }\r\n\r\n valueOf(){ return this.cid; }\r\n toString(){ return this.cid; }\r\n\r\n // Get class name for an object instance. Works fine with ES6 classes definitions (not in IE).\r\n getClassName() : string {\r\n const { name } = this.constructor;\r\n if( name !== 'Subclass' ) return name;\r\n }\r\n\r\n // Logging interface for run time errors and warnings.\r\n abstract _log( level : string, text : string, value : any ) : void;\r\n}\r\n\r\nexport interface CloneOptions {\r\n // 'Pin store' shall assign this._defaultStore = this.getStore();\r\n pinStore? : boolean\r\n}\r\n\r\n// Owner must accept children update events. It's an only way children communicates with an owner.\r\n/** @private */\r\nexport interface Owner extends Traversable, Messenger {\r\n _onChildrenChange( child : Transactional, options : TransactionOptions ) : void;\r\n getOwner() : Owner\r\n getStore() : Transactional\r\n}\r\n\r\n// Transaction object used for two-phase commit protocol.\r\n// Must be implemented by subclasses.\r\n// Transaction must be created if there are actual changes and when markIsDirty returns true.\r\n/** @private */ \r\nexport interface Transaction {\r\n // Object transaction is being made on.\r\n object : Transactional\r\n\r\n // Send out change events, process update triggers, and close transaction.\r\n // Nested transactions must be marked with isNested flag (it suppress owner notification).\r\n commit( initiator? : Transactional )\r\n}\r\n\r\n// Options for distributed transaction \r\nexport interface TransactionOptions {\r\n // Invoke parsing \r\n parse? : boolean\r\n\r\n // Suppress change notifications and update triggers\r\n silent? : boolean\r\n\r\n // Update existing transactional members in place, or skip the update (ignored by models)\r\n merge? : boolean // =true\r\n\r\n // Should collections remove elements in set (ignored by models) \r\n remove? : boolean // =true\r\n\r\n // Always replace enclosed objects with new instances\r\n reset? : boolean // = false\r\n\r\n validate? : boolean\r\n}\r\n\r\n/**\r\n * Low-level transactions API. Must be used like this:\r\n * const isRoot = begin( record );\r\n * ...\r\n * isRoot && commit( record, options );\r\n * \r\n * When committing nested transaction, the flag must be set to true. \r\n * commit( object, options, isNested ) \r\n */\r\n\r\nexport const transactionApi = {\r\n // Start transaction. Return true if it's the root one.\r\n /** @private */\r\n begin( object : Transactional ) : boolean {\r\n return object._transaction ? false : ( object._transaction = true ); \r\n },\r\n\r\n // Mark object having changes inside of the current transaction.\r\n // Returns true whenever there notifications are required.\r\n /** @private */\r\n markAsDirty( object : Transactional, options : TransactionOptions ) : boolean {\r\n // If silent option is in effect, don't set isDirty flag.\r\n const dirty = !options.silent;\r\n if( dirty ) object._isDirty = options;\r\n \r\n // Reset version token.\r\n object._changeToken = {};\r\n\r\n // Object is changed, so validation must happen again. Clear the cache.\r\n object._validationError = void 0;\r\n\r\n return dirty;\r\n },\r\n\r\n // Commit transaction. Send out change event and notify owner. Returns true if there were changes.\r\n // Must be executed for the root transaction only.\r\n /** @private */\r\n commit( object : Transactional, initiator? : Transactional ){\r\n let originalOptions = object._isDirty;\r\n\r\n if( originalOptions ){\r\n // Send the sequence of change events, handling chained handlers.\r\n while( object._isDirty ){\r\n const options = object._isDirty;\r\n object._isDirty = null; \r\n trigger3( object, object._changeEventName, object, options, initiator );\r\n }\r\n \r\n // Mark transaction as closed.\r\n object._transaction = false;\r\n\r\n // Notify owner on changes out of transaction scope. \r\n const { _owner } = object; \r\n if( _owner && _owner !== initiator ){ // If it's the nested transaction, owner is already aware there are some changes.\r\n _owner._onChildrenChange( object, originalOptions );\r\n }\r\n }\r\n else{\r\n // No changes. Silently close transaction.\r\n object._isDirty = null;\r\n object._transaction = false;\r\n }\r\n },\r\n\r\n /************************************\r\n * Ownership management\r\n */\r\n\r\n // Add reference to the record.\r\n /** @private */\r\n aquire( owner : Owner, child : Transactional, key? : string ) : boolean {\r\n if( !child._owner ){\r\n child._owner = owner;\r\n child._ownerKey = key;\r\n return true;\r\n }\r\n\r\n return child._owner === owner;\r\n },\r\n\r\n // Remove reference to the record.\r\n /** @private */\r\n free( owner : Owner, child : Transactional ) : void {\r\n if( owner === child._owner ){\r\n child._owner = void 0;\r\n child._ownerKey = void 0;\r\n }\r\n }\r\n}\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/transactions.ts\n **/","export interface ChildrenErrors {\r\n [ key : string ] : ValidationError | any\r\n} \r\n\r\nexport interface Validatable {\r\n _validateNested( errors : ChildrenErrors ) : number;\r\n validate( self : any ) : any\r\n get( key : string ) : any\r\n}\r\n\r\n// Validation error object.\r\nexport class ValidationError {\r\n // Invalid nested object keys \r\n nested : ChildrenErrors \r\n length : number\r\n\r\n // Local error\r\n error : any\r\n\r\n constructor( obj : Validatable ){\r\n this.length = obj._validateNested( this.nested = {} );\r\n\r\n if( this.error = obj.validate( obj ) ){\r\n this.length++;\r\n }\r\n }\r\n\r\n each( iteratee : ( value : any, key : string ) => void ) : void {\r\n const { error, nested } = this;\r\n\r\n if( error ) iteratee( error, null );\r\n\r\n for( const key in nested ){\r\n iteratee( nested[ key ], key );\r\n }\r\n }\r\n\r\n eachError( iteratee : ( error : any, key : string, object : Validatable ) => void, object : Validatable ) : void {\r\n this.each( ( value : any, key : string ) => {\r\n if( value instanceof ValidationError ){\r\n (value).eachError( iteratee, object.get( key ) );\r\n }\r\n else{\r\n iteratee( value, key, object );\r\n }\r\n });\r\n }\r\n}\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/validation.ts\n **/","/**\r\n * Some sketches for reference resolution.\r\n *\r\n * \r\n * a : Model.from( '~collection' )\r\n * \r\n * We need two functions. One for get, and one for compile. \r\n */\r\nexport interface Traversable {\r\n getStore() : Traversable\r\n getOwner() : Traversable\r\n get( key : string ) : any \r\n}\r\n\r\nconst referenceMask = /\\^|([^.]+)/g;\r\n\r\n// Compile reference to function\r\nexport type ResolveReference = ( root : Traversable ) => any; \r\n\r\nexport class CompiledReference {\r\n resolve : ResolveReference\r\n tail : string\r\n local : boolean\r\n\r\n constructor( reference : string, splitTail : boolean = false ){\r\n const path = reference\r\n .match( referenceMask )\r\n .map( key => {\r\n if( key === '^' ) return 'getOwner()';\r\n\r\n if( key[ 0 ] === '~' ) return `getStore().get(\"${ key.substr( 1 ) }\")`;\r\n \r\n return key;\r\n } );\r\n \r\n this.tail = splitTail && path.pop();\r\n this.local = !path.length;\r\n\r\n path.unshift( 'self' );\r\n \r\n this.resolve = new Function( 'self', `return ${ path.join('.') };` );\r\n }\r\n}\r\n\r\nexport function resolveReference( root : Traversable, reference : string, action : ( object, key : string ) => any ) : any {\r\n const path = reference.match( referenceMask ),\r\n skip = path.length - 1;\r\n \r\n let self = root;\r\n\r\n for( var i = 0; i < skip; i++ ){\r\n const key = path[ i ];\r\n switch( key ){\r\n case '~' : self = self.getStore(); break;\r\n case '^' : self = self.getOwner(); break;\r\n default : self = self.get( key );\r\n }\r\n\r\n // Do nothing if object on the path doesn't exist.\r\n if( !self ) return;\r\n }\r\n\r\n return action( self, path[ skip ] );\r\n}\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/traversable.ts\n **/","import { Record, RecordDefinition, AttributeDescriptorMap } from './transaction'\r\nimport { Mixable, ClassDefinition, tools } from '../object-plus'\r\nimport { compile, AttributesSpec } from './define'\r\nimport { ChainableAttributeSpec } from './typespec'\r\nimport { Transactional } from '../transactions'\r\n\r\nimport { TransactionalType, MSDateType, TimestampType, NumericType, SharedRecordType } from './attributes'\r\n\r\nexport * from './attributes'\r\nexport { Record, ChainableAttributeSpec }\r\n\r\nconst { assign, defaults, omit, getBaseClass } = tools;\r\n\r\nRecord.define = function( protoProps : RecordDefinition = {}, staticProps ){\r\n const BaseConstructor : typeof Record = getBaseClass( this ),\r\n baseProto : Record = BaseConstructor.prototype,\r\n // Extract record definition from static members, if any.\r\n staticsDefinition : RecordDefinition = tools.getChangedStatics( this, 'attributes', 'collection', 'Collection' ),\r\n // Definition can be made either through statics or define argument.\r\n // Merge them together, so we won't care about it below. \r\n definition = assign( staticsDefinition, protoProps );\r\n\r\n if( 'Collection' in this && this.Collection === void 0 ){\r\n tools.log.error( `[Model Definition] ${ this.prototype.getClassName() }.Collection is undefined. It must be defined _before_ the model.`, definition );\r\n }\r\n\r\n // Compile attributes spec, creating definition mixin.\r\n const dynamicMixin = compile( getAttributes( definition ), baseProto._attributes );\r\n\r\n // Explicit 'properties' declaration overrides auto-generated attribute properties.\r\n if( definition.properties === false ){\r\n dynamicMixin.properties = {};\r\n }\r\n\r\n assign( dynamicMixin.properties, protoProps.properties || {} );\r\n\r\n // Merge in definition.\r\n assign( dynamicMixin, omit( definition, 'attributes', 'collection', 'defaults', 'properties', 'forEachAttr' ) ); \r\n Mixable.define.call( this, dynamicMixin, staticProps );\r\n defineCollection.call( this, definition.collection || definition.Collection );\r\n\r\n return this;\r\n}\r\n\r\nRecord.predefine = function(){\r\n Transactional.predefine.call( this );\r\n\r\n this.Collection = getBaseClass( this ).Collection.extend();\r\n this.Collection.prototype.model = this;\r\n\r\n createSharedTypeSpec( this, SharedRecordType );\r\n\r\n return this;\r\n}\r\n\r\nRecord._attribute = TransactionalType;\r\ncreateSharedTypeSpec( Record, SharedRecordType );\r\n\r\nfunction getAttributes({ defaults, attributes, idAttribute } : RecordDefinition ) : AttributeDescriptorMap {\r\n const definition = typeof defaults === 'function' ? (defaults)() : attributes || defaults || {};\r\n \r\n // If there is an undeclared idAttribute, add its definition as untyped generic attribute.\r\n if( idAttribute && !( idAttribute in definition ) ){\r\n definition[ idAttribute ] = void 0;\r\n }\r\n\r\n return definition;\r\n}\r\n\r\nfunction defineCollection( collection : {} ){\r\n // If collection constructor is specified, take it as it is. \r\n if( typeof collection === 'function' ) {\r\n this.Collection = collection;\r\n \r\n // Link collection with the record\r\n this.Collection.prototype.model = this;\r\n } \r\n // Otherwise, define implicitly created Collection.\r\n else{\r\n this.Collection.define( collection || {} );\r\n }\r\n}\r\n\r\n// Add extended Date attribute types.\r\ndeclare global {\r\n interface DateConstructor {\r\n microsoft\r\n timestamp\r\n }\r\n}\r\n\r\nObject.defineProperties( Date, {\r\n microsoft : {\r\n get(){\r\n return new ChainableAttributeSpec({\r\n type : Date,\r\n _attribute : MSDateType\r\n })\r\n }\r\n },\r\n\r\n timestamp : {\r\n get(){\r\n return new ChainableAttributeSpec({\r\n type : Date,\r\n _attribute : TimestampType\r\n })\r\n }\r\n }\r\n});\r\n\r\n// Add Number.integer attrubute type\r\ndeclare global {\r\n interface NumberConstructor {\r\n integer : Function\r\n }\r\n\r\n interface Window {\r\n Integer : Function;\r\n }\r\n}\r\n\r\nNumber.integer = function( x ){ return x ? Math.round( x ) : 0; }\r\nNumber.integer._attribute = NumericType;\r\n\r\nif( typeof window !== 'undefined' ){\r\n window.Integer = Number.integer;\r\n}\r\n\r\n/** @private */\r\nexport function createSharedTypeSpec( Constructor, Attribute ){\r\n Constructor.hasOwnProperty( 'shared' ) ||\r\n Object.defineProperty( Constructor, 'shared', {\r\n get(){\r\n return new ChainableAttributeSpec({\r\n value : null,\r\n type : Constructor,\r\n _attribute : Attribute\r\n });\r\n }\r\n });\r\n}\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/record/index.ts\n **/","/**\r\n * Record core implementing transactional updates.\r\n * The root of all definitions. \r\n */\r\n\r\nimport { tools, eventsApi, Mixable, ClassDefinition, Constructor, define } from '../object-plus'\r\n\r\nimport { transactionApi, CloneOptions, Transactional, Transaction, TransactionOptions, Owner } from '../transactions'\r\nimport { ChildrenErrors } from '../validation'\r\n\r\nconst { trigger3 } = eventsApi,\r\n { assign, isEmpty, log } = tools,\r\n { free, aquire, commit } = transactionApi,\r\n _begin = transactionApi.begin, _markAsDirty = transactionApi.markAsDirty;\r\n\r\n/***************************************************************\r\n * Record Definition as accepted by Record.define( definition )\r\n */\r\n\r\nexport interface RecordDefinition extends ClassDefinition {\r\n attributes? : AttributeDescriptorMap\r\n defaults? : AttributeDescriptorMap | ( () => AttributeDescriptorMap )\r\n collection? : typeof Transactional | {}\r\n Collection? : typeof Transactional\r\n}\r\n\r\nexport interface AttributeDescriptorMap {\r\n [ name : string ] : AttributeDescriptor\r\n}\r\n\r\nexport interface AttributeDescriptor {\r\n type? : Constructor< any >\r\n value? : any\r\n\r\n parse? : AttributeParse\r\n toJSON? : AttributeToJSON\r\n \r\n getHooks? : GetHook[]\r\n transforms? : Transform[]\r\n changeHandlers? : ChangeHandler[]\r\n\r\n _onChange? : ChangeAttrHandler\r\n}\r\n\r\nexport type GetHook = ( value : any, key : string ) => any;\r\n\r\nexport type ChangeAttrHandler = ( ( value : any, attr : string ) => void ) | string;\r\nexport type Transform = ( next : any, options : TransactionOptions, prev : any, record : Record ) => any;\r\nexport type ChangeHandler = ( next : any, prev : any, record : Record ) => void;\r\n\r\nexport type AttributeToJSON = ( value : any, key : string ) => any\r\nexport type AttributeParse = ( value : any, key : string ) => any\r\n\r\n/*************************************\r\n * Attribute definitions\r\n */\r\nexport interface AttributesValues {\r\n id? : string | number \r\n [ key : string ] : any\r\n}\r\n\r\nexport type CloneAttributesCtor = new ( x : AttributesValues ) => AttributesValues\r\n\r\nexport interface AttributesSpec {\r\n [ key : string ] : Attribute\r\n}\r\n\r\nexport interface Attribute extends AttributeUpdatePipeline, AttributeSerialization {\r\n clone( value : any ) : any\r\n create() : any\r\n validate( record : Record, value : any, key : string )\r\n}\r\n\r\nexport interface AttributeUpdatePipeline{\r\n canBeUpdated( prev : any, next : any, options : TransactionOptions ) : any\r\n transform : Transform\r\n isChanged( a : any, b : any ) : boolean\r\n handleChange : ChangeHandler\r\n propagateChanges : boolean\r\n}\r\n\r\nexport interface AttributeSerialization {\r\n toJSON : AttributeToJSON\r\n parse : AttributeParse\r\n}\r\n\r\n/*******************************************************\r\n * Record core implementation\r\n */\r\n\r\ninterface ConstructorOptions extends TransactionOptions{\r\n clone? : boolean\r\n}\r\n\r\n// Client unique id counter\r\nlet _cidCounter : number = 0;\r\n\r\n@define({\r\n // Default client id prefix \r\n cidPrefix : 'm',\r\n\r\n // Name of the change event\r\n _changeEventName : 'change',\r\n\r\n // Default id attribute name\r\n idAttribute : 'id',\r\n _keys : [ 'id' ]\r\n})\r\nexport class Record extends Transactional implements Owner {\r\n // Implemented at the index.ts to avoid circular dependency. Here we have just proper singature.\r\n static define( protoProps : RecordDefinition, staticProps? ) : typeof Record {\r\n return Transactional.define( protoProps, staticProps );\r\n }\r\n\r\n static predefine : () => typeof Record\r\n static Collection : typeof Transactional\r\n\r\n static from : ( collectionReference : any ) => any;\r\n \r\n static defaults( attrs : AttributeDescriptorMap ){\r\n return this.extend({ attributes : attrs });\r\n }\r\n \r\n /***********************************\r\n * Core Members\r\n */\r\n // Previous attributes\r\n _previousAttributes : {}\r\n\r\n previousAttributes(){ return new this.Attributes( this._previousAttributes ); } \r\n\r\n // Current attributes \r\n attributes : AttributesValues\r\n\r\n // Polymorphic accessor for aggregated attribute's canBeUpdated().\r\n get _state(){ return this.attributes; }\r\n\r\n // Lazily evaluated changed attributes hash\r\n _changedAttributes : AttributesValues\r\n\r\n get changed(){\r\n let changed = this._changedAttributes;\r\n\r\n if( !changed ){\r\n const prev = this._previousAttributes;\r\n changed = {};\r\n\r\n const { _attributes, attributes } = this;\r\n\r\n for( let key of this._keys ){\r\n const value = attributes[ key ];\r\n\r\n if( _attributes[ key ].isChanged( value, prev[ key ] ) ){\r\n changed[ key ] = value;\r\n }\r\n }\r\n\r\n this._changedAttributes = changed;\r\n }\r\n\r\n return changed; \r\n }\r\n\r\n changedAttributes( diff? : {} ) : boolean | {} {\r\n if( !diff ) return this.hasChanged() ? assign( {}, this.changed ) : false;\r\n\r\n var val, changed : {} | boolean = false,\r\n old = this._transaction ? this._previousAttributes : this.attributes,\r\n attrSpecs = this._attributes;\r\n\r\n for( var attr in diff ){\r\n if( !attrSpecs[ attr ].isChanged( old[ attr ], ( val = diff[ attr ] ) ) ) continue;\r\n (changed || (changed = {}))[ attr ] = val;\r\n }\r\n\r\n return changed; \r\n }\r\n\r\n hasChanged( key? : string ) : boolean {\r\n const { _previousAttributes } = this;\r\n if( !_previousAttributes ) return false;\r\n\r\n return key ?\r\n this._attributes[ key ].isChanged( this.attributes[ key ], _previousAttributes[ key ] ) :\r\n !isEmpty( this.changed );\r\n }\r\n\r\n previous( key : string ) : any {\r\n if( key ){\r\n const { _previousAttributes } = this;\r\n if( _previousAttributes ) return _previousAttributes[ key ];\r\n }\r\n \r\n return null;\r\n }\r\n\r\n isNew() : boolean {\r\n return this.id == null;\r\n }\r\n\r\n has( key : string ) : boolean {\r\n return this[ key ] != void 0;\r\n }\r\n\r\n unset( key, options? ) : this {\r\n this.set( key, void 0, options );\r\n return this; \r\n }\r\n\r\n clear( options? ) : this {\r\n const nullify = options && options.nullify;\r\n\r\n this.transaction( () =>{\r\n this.forEachAttr( this.attributes, ( value, key ) => this[ key ] = nullify ? null : void 0 );\r\n }, options );\r\n\r\n return this;\r\n }\r\n\r\n // Returns Record owner skipping collections. TODO: Move out\r\n getOwner() : Owner {\r\n const owner : any = this._owner;\r\n\r\n // If there are no key, owner must be transactional object, and it's the collection.\r\n // We don't expect that collection can be the member of collection, so we're skipping just one level up. An optimization.\r\n return this._ownerKey ? owner : owner && owner._owner;\r\n }\r\n\r\n /***********************************\r\n * Identity managements\r\n */\r\n\r\n // Id attribute name ('id' by default)\r\n idAttribute : string;\r\n\r\n // Fixed 'id' property pointing to id attribute\r\n get id() : string | number { return this.attributes[ this.idAttribute ]; }\r\n set id( x : string | number ){ setAttribute( this, this.idAttribute, x ); }\r\n\r\n /***********************************\r\n * Dynamically compiled stuff\r\n */\r\n\r\n // Attributes specifications \r\n _attributes : AttributesSpec\r\n\r\n // Attribute keys\r\n _keys : string[]\r\n\r\n // Attributes object copy constructor\r\n // Attributes : CloneAttributesCtor\r\n Attributes( x : AttributesValues ) : void { this.id = x.id; }\r\n\r\n // forEach function for traversing through attributes, with protective default implementation\r\n // Overriden by dynamically compiled loop unrolled function in define.ts\r\n forEachAttr( attrs : {}, iteratee : ( value : any, key? : string, spec? : Attribute ) => void ) : void {\r\n const { _attributes } = this;\r\n let unknown : string[];\r\n\r\n for( let name in attrs ){\r\n const spec = _attributes[ name ];\r\n\r\n if( spec ){\r\n iteratee( attrs[ name ], name, spec );\r\n }\r\n else{\r\n unknown || ( unknown = [] );\r\n unknown.push( `'${ name }'` );\r\n }\r\n }\r\n\r\n if( unknown ){\r\n this._log( 'warn', `attributes ${ unknown.join(', ')} are not defined`, attrs );\r\n }\r\n\r\n // TODO: try this versus object traversal.\r\n /*\r\n const { _attributes, _keys } = this;\r\n \r\n for( let name of _keys ){\r\n const spec = _attributes[ name ],\r\n value = attrs[ name ];\r\n\r\n value && iteratee( value, name, spec );\r\n }*/\r\n }\r\n\r\n each( iteratee : ( value? : any, key? : string ) => void, context? : any ){\r\n const fun = arguments.length === 2 ? ( v, k ) => iteratee.call( context, v, k ) : iteratee,\r\n { attributes, _keys } = this;\r\n\r\n for( const key of _keys ){\r\n const value = attributes[ key ];\r\n if( value !== void 0 ) fun( value, key );\r\n }\r\n }\r\n\r\n // Attributes-level serialization\r\n _toJSON(){ return {}; }\r\n\r\n // Attributes-level parse\r\n _parse( data ){ return data; }\r\n\r\n // Create record default values, optionally augmenting given values.\r\n defaults( values? : {} ){ return {}; }\r\n\r\n /***************************************************\r\n * Record construction\r\n */\r\n // Create record, optionally setting an owner\r\n constructor( a_values? : {}, a_options? : ConstructorOptions ){\r\n super( _cidCounter++ );\r\n this.attributes = {};\r\n \r\n const options = a_options || {},\r\n values = ( options.parse ? this.parse( a_values, options ) : a_values ) || {};\r\n\r\n // TODO: type error for wrong object.\r\n\r\n const attributes = options.clone ? cloneAttributes( this, values ) : this.defaults( values ); \r\n\r\n this.forEachAttr( attributes, ( value : any, key : string, attr : AttributeUpdatePipeline ) => {\r\n const next = attributes[ key ] = attr.transform( value, options, void 0, this );\r\n attr.handleChange( next, void 0, this );\r\n });\r\n\r\n this.attributes = this._previousAttributes = attributes;\r\n\r\n this.initialize( a_values, a_options );\r\n\r\n if( this._localEvents ) this._localEvents.subscribe( this, this );\r\n }\r\n\r\n // Initialization callback, to be overriden by the subclasses \r\n initialize( values?, options? ){}\r\n\r\n // Deeply clone record, optionally setting new owner.\r\n clone( options : CloneOptions = {} ) : this {\r\n const copy : this = new (this.constructor)( this.attributes, { clone : true } );\r\n \r\n if( options.pinStore ) copy._defaultStore = this.getStore();\r\n\r\n return copy;\r\n }\r\n\r\n // Deprecated, every clone is the deep one now.\r\n deepClone() : this { return this.clone() };\r\n\r\n // Validate attributes.\r\n _validateNested( errors : ChildrenErrors ) : number {\r\n var length = 0;\r\n\r\n this.forEachAttr( this.attributes, ( value, name, attribute ) => {\r\n const error = attribute.validate( this, value, name );\r\n\r\n if( error ){\r\n errors[ name ] = error;\r\n length++;\r\n }\r\n } );\r\n\r\n return length;\r\n }\r\n\r\n // Get attribute by key\r\n get( key : string ) : any {\r\n return this[ key ];\r\n }\r\n\r\n /**\r\n * Serialization control\r\n */\r\n\r\n // Default record-level serializer, to be overriden by subclasses \r\n toJSON() : Object {\r\n const json = {};\r\n\r\n this.forEachAttr( this.attributes, ( value, key : string, { toJSON } : AttributeSerialization ) =>{\r\n // If attribute serialization is not disabled, and its value is not undefined...\r\n if( toJSON && value !== void 0 ){\r\n // ...serialize it according to its spec.\r\n const asJson = toJSON.call( this, value, key );\r\n\r\n // ...skipping undefined values. Such an attributes are excluded.\r\n if( asJson !== void 0 ) json[ key ] = asJson; \r\n }\r\n });\r\n\r\n return json;\r\n }\r\n \r\n // Default record-level parser, to be overriden by the subclasses.\r\n parse( data, options? : TransactionOptions ){\r\n // Call dynamically compiled loop-unrolled attribute-level parse function.\r\n return this._parse( data );\r\n }\r\n\r\n /**\r\n * Transactional control\r\n */\r\n\r\n // Polimorphic set method.\r\n set( key : string, value : any, options? : TransactionOptions ) : this\r\n set( attrs : {}, options? : TransactionOptions ) : this\r\n set( a, b?, c? ) : this {\r\n if( typeof a === 'string' ){\r\n if( c ){\r\n return super.set({ [ a ] : b }, c );\r\n }\r\n else{\r\n setAttribute( this, a, b );\r\n return this;\r\n } \r\n }\r\n else{\r\n return super.set( a, b );\r\n }\r\n }\r\n\r\n deepSet( name : string, value : any, options? ){\r\n // Operation might involve series of nested object updates, thus it's wrapped in transaction.\r\n this.transaction( () => {\r\n const path = name.split( '.' ),\r\n l = path.length - 1,\r\n attr = path[ l ];\r\n\r\n let model = this;\r\n\r\n // Locate the model, traversing the path.\r\n for( let i = 0; i < l; i++ ){\r\n const key = path[ i ];\r\n\r\n // There might be collections in path, so use `get`.\r\n let next = model.get ? model.get( key ) : model[ key ];\r\n\r\n // Create models, if they are not exist.\r\n if( !next ){\r\n const attrSpecs = model._attributes;\r\n if( attrSpecs ){\r\n // If current object is model, create default attribute\r\n var newModel = attrSpecs[ key ].create();\r\n\r\n // If created object is model, nullify attributes when requested\r\n if( options && options.nullify && newModel._attributes ){\r\n newModel.clear( options );\r\n }\r\n\r\n model[ key ] = next = newModel;\r\n }\r\n // Silently fail in other case.\r\n else return;\r\n }\r\n \r\n model = next;\r\n }\r\n\r\n // Set model attribute.\r\n if( model.set ){\r\n model.set( attr, value, options );\r\n }\r\n else{\r\n model[ attr ] = value;\r\n }\r\n });\r\n\r\n return this;\r\n }\r\n\r\n // Need to override it here, since begin/end transaction brackets are overriden. \r\n transaction( fun : ( self : this ) => void, options : TransactionOptions = {} ) : void{\r\n const isRoot = begin( this );\r\n fun.call( this, this );\r\n isRoot && commit( this );\r\n }\r\n \r\n // Create transaction. TODO: Move to transaction constructor\r\n _createTransaction( a_values : {}, options : TransactionOptions = {} ) : Transaction {\r\n const isRoot = begin( this ),\r\n changes : string[] = [],\r\n nested : RecordTransaction[]= [],\r\n { attributes } = this,\r\n values = options.parse ? this.parse( a_values, options ) : a_values;\r\n\r\n if( Object.getPrototypeOf( values ) === Object.prototype ){\r\n this.forEachAttr( values, ( value, key : string, attr : AttributeUpdatePipeline ) => {\r\n const prev = attributes[ key ];\r\n let update;\r\n\r\n // handle deep update...\r\n if( update = attr.canBeUpdated( prev, value, options ) ) { // todo - skip empty updates.\r\n const nestedTransaction = prev._createTransaction( update, options );\r\n if( nestedTransaction ){\r\n nested.push( nestedTransaction );\r\n \r\n if( attr.propagateChanges ) changes.push( key );\r\n }\r\n\r\n return;\r\n }\r\n\r\n // cast and hook...\r\n const next = attr.transform( value, options, prev, this );\r\n attributes[ key ] = next;\r\n\r\n if( attr.isChanged( next, prev ) ) { \r\n changes.push( key );\r\n\r\n // Do the rest of the job after assignment\r\n attr.handleChange( next, prev, this );\r\n }\r\n } );\r\n }\r\n else{\r\n this._log( 'error', 'incompatible argument type', values );\r\n }\r\n\r\n if( changes.length && markAsDirty( this, options ) ){\r\n return new RecordTransaction( this, isRoot, nested, changes );\r\n }\r\n \r\n // No changes, but there might be silent attributes with open transactions.\r\n for( let pendingTransaction of nested ){\r\n pendingTransaction.commit( this );\r\n }\r\n\r\n isRoot && commit( this );\r\n }\r\n\r\n // Handle nested changes. TODO: propagateChanges == false, same in transaction.\r\n _onChildrenChange( child : Transactional, options : TransactionOptions ) : void {\r\n const { _ownerKey } = child,\r\n attribute = this._attributes[ _ownerKey ];\r\n\r\n if( !attribute /* TODO: Must be an opposite, likely the bug */ || attribute.propagateChanges ) this.forceAttributeChange( _ownerKey, options );\r\n }\r\n\r\n // Simulate attribute change \r\n forceAttributeChange( key : string, options : TransactionOptions = {} ){\r\n // Touch an attribute in bounds of transaction\r\n const isRoot = begin( this );\r\n\r\n if( markAsDirty( this, options ) ){\r\n trigger3( this, 'change:' + key, this, this.attributes[ key ], options );\r\n }\r\n \r\n isRoot && commit( this );\r\n }\r\n\r\n // Returns owner without the key (usually it's collection)\r\n get collection() : any {\r\n return this._ownerKey ? null : this._owner;\r\n }\r\n\r\n // Dispose object and all childrens\r\n dispose(){\r\n this.forEachAttr( this.attributes, ( value, key ) => {\r\n if( value && this === value._owner ){\r\n value.dispose(); \r\n }\r\n });\r\n\r\n super.dispose();\r\n }\r\n\r\n _log( level : string, text : string, value ) : void {\r\n tools.log[ level ]( `[Model Update] ${ this.getClassName() }: ` + text, value, 'Attributes spec:', this._attributes );\r\n }\r\n\r\n getClassName() : string {\r\n return super.getClassName() || 'Model';\r\n }\r\n};\r\n\r\n/***********************************************\r\n * Helper functions\r\n */\r\n\r\nfunction begin( record : Record ){\r\n if( _begin( record ) ){\r\n record._previousAttributes = new record.Attributes( record.attributes );\r\n record._changedAttributes = null;\r\n return true;\r\n }\r\n \r\n return false;\r\n}\r\n\r\nfunction markAsDirty( record : Record, options : TransactionOptions ){\r\n // Need to recalculate changed attributes, when we have nested set in change:attr handler\r\n if( record._changedAttributes ){\r\n record._changedAttributes = null;\r\n }\r\n\r\n return _markAsDirty( record, options );\r\n}\r\n\r\n// Deeply clone record attributes\r\nfunction cloneAttributes( record : Record, a_attributes : AttributesValues ) : AttributesValues {\r\n const attributes = new record.Attributes( a_attributes );\r\n\r\n record.forEachAttr( attributes, function( value, name, attr : Attribute ){\r\n attributes[ name ] = attr.clone( value ); //TODO: Add owner?\r\n } );\r\n\r\n return attributes;\r\n}\r\n\r\n // Optimized single attribute transactional update. To be called from attributes setters\r\n // options.silent === false, parse === false. \r\nexport function setAttribute( record : Record, name : string, value : any ) : void {\r\n const isRoot = begin( record ),\r\n options = {},\r\n { attributes } = record,\r\n spec = record._attributes[ name ],\r\n prev = attributes[ name ];\r\n\r\n let update;\r\n\r\n // handle deep update...\r\n if( update = spec.canBeUpdated( prev, value, options ) ) {\r\n //TODO: Why not just forward the transaction, without telling that it's nested?\r\n const nestedTransaction = ( prev )._createTransaction( update, options );\r\n if( nestedTransaction ){\r\n nestedTransaction.commit( record ); // <- null here, and no need to handle changes. Work with shared and aggregated.\r\n\r\n if( spec.propagateChanges ){\r\n markAsDirty( record, options );\r\n trigger3( record, 'change:' + name, record, prev, options );\r\n }\r\n }\r\n }\r\n else {\r\n // cast and hook...\r\n const next = spec.transform( value, options, prev, record );\r\n\r\n attributes[ name ] = next;\r\n\r\n if( spec.isChanged( next, prev ) ) {\r\n // Do the rest of the job after assignment\r\n spec.handleChange( next, prev, record );\r\n\r\n markAsDirty( record, options );\r\n trigger3( record, 'change:' + name, record, next, options );\r\n }\r\n }\r\n\r\n isRoot && commit( record );\r\n}\r\n\r\n// Transaction class. Implements two-phase transactions on object's tree. \r\n// Transaction must be created if there are actual changes and when markIsDirty returns true. \r\nclass RecordTransaction implements Transaction {\r\n // open transaction\r\n constructor( public object : Record,\r\n public isRoot : boolean,\r\n public nested : Transaction[],\r\n public changes : string[] ){}\r\n\r\n // commit transaction\r\n commit( initiator? : Record ) : void {\r\n const { nested, object, changes } = this;\r\n\r\n // Commit all pending nested transactions...\r\n for( let transaction of nested ){ \r\n transaction.commit( object );\r\n }\r\n\r\n // Notify listeners on attribute changes...\r\n // Transaction is never created when silent option is set, so just send events out.\r\n const { attributes, _isDirty } = object;\r\n for( let key of changes ){\r\n trigger3( object, 'change:' + key, object, attributes[ key ], _isDirty );\r\n }\r\n\r\n this.isRoot && commit( object, initiator );\r\n }\r\n}\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/record/transaction.ts\n **/","import { GenericAttribute } from './attributes';\r\nimport { Attribute, AttributesValues, AttributeDescriptorMap, CloneAttributesCtor } from './transaction'\r\nimport { tools, eventsApi } from '../object-plus'\r\nimport { toAttributeDescriptor } from './typespec'\r\nimport { CompiledReference } from '../traversable'\r\n\r\nconst { defaults, isValidJSON, transform, log } = tools,\r\n { EventMap } = eventsApi;\r\n\r\n/** @private */\r\nexport interface DynamicMixin {\r\n _attributes : AttributesSpec\r\n Attributes : CloneAttributesCtor\r\n properties : PropertyDescriptorMap\r\n forEachAttr? : ForEach\r\n defaults : Defaults\r\n _toJSON : ToJSON\r\n _parse? : Parse\r\n _localEvents : eventsApi.EventMap\r\n _keys : string[]\r\n}\r\n\r\n// Refine AttributesSpec definition.\r\n/** @private */\r\nexport interface AttributesSpec {\r\n [ key : string ] : GenericAttribute\r\n}\r\n\r\ntype ForEach = ( obj : {}, iteratee : ( val : any, key? : string, spec? : Attribute ) => void ) => void;\r\ntype Defaults = ( attrs? : {} ) => {}\r\ntype Parse = ( data : any ) => any;\r\ntype ToJSON = () => any;\r\n\r\n// Compile attributes spec\r\n/** @private */\r\nexport function compile( rawSpecs : AttributeDescriptorMap, baseAttributes : AttributesSpec ) : DynamicMixin {\r\n const myAttributes = transform( {}, rawSpecs, createAttribute ),\r\n allAttributes = defaults( {}, myAttributes, baseAttributes ),\r\n Attributes = createCloneCtor( allAttributes ),\r\n mixin : DynamicMixin = {\r\n Attributes : Attributes,\r\n _attributes : new Attributes( allAttributes ),\r\n properties : transform( {}, myAttributes, x => x.createPropertyDescriptor() ),\r\n defaults : createDefaults( allAttributes ),\r\n _toJSON : createToJSON( allAttributes ), // <- TODO: profile and check if there is any real benefit. I doubt it. \r\n _localEvents : createEventMap( myAttributes ),\r\n _keys : Object.keys( allAttributes )\r\n };\r\n\r\n const _parse = createParse( myAttributes, allAttributes );\r\n if( _parse ){\r\n mixin._parse = _parse;\r\n }\r\n\r\n // Enable optimized forEach if warnings are disabled.\r\n if( !log.level ){\r\n mixin.forEachAttr = createForEach( allAttributes );\r\n }\r\n\r\n return mixin;\r\n}\r\n\r\n// Create attribute from the type spec.\r\n/** @private */\r\nfunction createAttribute( spec, name ){\r\n return GenericAttribute.create( toAttributeDescriptor( spec ), name );\r\n}\r\n\r\n// Build events map for attribute change events.\r\n/** @private */\r\nfunction createEventMap( attrSpecs : AttributesSpec ) : eventsApi.EventMap {\r\n let events : eventsApi.EventMap;\r\n\r\n for( var key in attrSpecs ){\r\n const attribute = attrSpecs[ key ],\r\n { _onChange } = attribute.options; \r\n\r\n if( _onChange ){\r\n events || ( events = new EventMap() );\r\n\r\n events.addEvent( 'change:' + key,\r\n typeof _onChange === 'string' ?\r\n createWatcherFromRef( _onChange, key ) : \r\n wrapWatcher( _onChange, key ) );\r\n }\r\n }\r\n\r\n return events;\r\n}\r\n\r\n/** @private */\r\nfunction wrapWatcher( watcher, key ){\r\n return function( record, value ){\r\n watcher.call( record, value, key );\r\n } \r\n}\r\n\r\n/** @private */\r\nfunction createWatcherFromRef( ref : string, key : string ){\r\n const { local, resolve, tail } = new CompiledReference( ref, true );\r\n return local ?\r\n function( record, value ){\r\n record[ tail ]( value, key );\r\n } :\r\n function( record, value ){\r\n resolve( record )[ tail ]( value, key );\r\n }\r\n}\r\n\r\n/** @private */\r\nexport function createForEach( attrSpecs : AttributesSpec ) : ForEach {\r\n let statements = [ 'var v, _a=this._attributes;' ];\r\n\r\n for( let name in attrSpecs ){\r\n statements.push( `( v = a.${name} ) === void 0 || f( v, \"${name}\", _a.${name} );` );\r\n }\r\n\r\n return new Function( 'a', 'f', statements.join( '' ) );\r\n}\r\n\r\n/** @private */\r\nexport function createCloneCtor( attrSpecs : AttributesSpec ) : CloneAttributesCtor {\r\n var statements = [];\r\n\r\n for( let name in attrSpecs ){\r\n statements.push( `this.${name} = x.${name};` );\r\n }\r\n\r\n var CloneCtor = new Function( \"x\", statements.join( '' ) );\r\n CloneCtor.prototype = Object.prototype;\r\n return CloneCtor;\r\n}\r\n\r\n// Create optimized model.defaults( attrs, options ) function\r\n/** @private */\r\nfunction createDefaults( attrSpecs : AttributesSpec ) : Defaults {\r\n let assign_f = ['var v;'], create_f = [];\r\n\r\n function appendExpr( name, expr ){\r\n assign_f.push( `this.${name} = ( v = a.${name} ) === void 0 ? ${expr} : v;` );\r\n create_f.push( `this.${name} = ${expr};` );\r\n }\r\n\r\n // Compile optimized constructor function for efficient deep copy of JSON literals in defaults.\r\n for( let name in attrSpecs ){\r\n const attrSpec = attrSpecs[ name ],\r\n { value, type } = attrSpec;\r\n\r\n if( value === void 0 && type ){\r\n // if type with no value is given, create an empty object\r\n appendExpr( name, `i.${name}.create()` );//TODO: consider adding owner reference\r\n }\r\n else{\r\n // If value is given, type casting logic will do the job later, converting value to the proper type.\r\n if( isValidJSON( value ) ){\r\n // JSON literals must be deep copied.\r\n appendExpr( name, JSON.stringify( value ) );\r\n }\r\n else if( value === void 0 ){\r\n // handle undefined value separately. Usual case for model ids.\r\n appendExpr( name, 'void 0' );\r\n }\r\n else{\r\n // otherwise, copy value by reference.\r\n appendExpr( name, `i.${name}.value` );\r\n }\r\n }\r\n }\r\n\r\n const CreateDefaults : any = new Function( 'i', create_f.join( '' ) ),\r\n AssignDefaults : any = new Function( 'a', 'i', assign_f.join( '' ) );\r\n\r\n CreateDefaults.prototype = AssignDefaults.prototype = Object.prototype;\r\n\r\n // Create model.defaults( attrs, options ) function\r\n // 'attrs' will override default values, options will be passed to nested backbone types\r\n return function( attrs? : {} ){ //TODO: Consider removing of the CreateDefaults. Currently is not used. May be used in Record costructor, though.\r\n return attrs ? new AssignDefaults( attrs, this._attributes ) : new CreateDefaults( this._attributes );\r\n }\r\n}\r\n\r\n/** @private */\r\nfunction createParse( allAttrSpecs : AttributesSpec, attrSpecs : AttributesSpec ) : Parse {\r\n var statements = [ 'var a=this._attributes;' ],\r\n create = false;\r\n\r\n for( let name in allAttrSpecs ){\r\n const local = attrSpecs[ name ];\r\n\r\n // Is there any 'parse' option in local model definition?\r\n if( local && local.parse ) create = true;\r\n\r\n // Add statement for each attribute with 'parse' option.\r\n if( allAttrSpecs[ name ].parse ){\r\n const s = `r.${name} === void 0 ||( r.${name} = a.${name}.parse.call( this, r.${name}, \"${name}\") );`;\r\n statements.push( s );\r\n }\r\n }\r\n\r\n if( create ){\r\n statements.push( 'return r;' );\r\n return new Function( 'r', statements.join( '' ) );\r\n }\r\n }\r\n\r\n/** @private */\r\nfunction createToJSON( attrSpecs : AttributesSpec ) : ToJSON {\r\n let statements = [ `var json = {},v=this.attributes,a=this._attributes;` ];\r\n\r\n for( let key in attrSpecs ){\r\n const toJSON = attrSpecs[ key ].toJSON;\r\n\r\n if( toJSON ){\r\n statements.push( `json.${key} = a.${key}.toJSON.call( this, v.${ key }, '${key}' );` );\r\n }\r\n }\r\n\r\n statements.push( `return json;` );\r\n\r\n return new Function( statements.join( '' ) );\r\n}\r\n\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/record/define.ts\n **/","export * from './generic'\r\nexport * from './owned'\r\nexport * from './date'\r\nexport * from './basic'\r\nexport * from './shared'\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/record/attributes/index.ts\n **/","import { setAttribute, Record, Attribute, Transform, ChangeHandler, AttributeDescriptor } from '../transaction'\r\nimport { Constructor, tools } from '../../object-plus'\r\nimport { Owner, Transactional, TransactionOptions } from '../../transactions'\r\n\r\nconst { notEqual, assign} = tools;\r\n\r\ntype GetHook = ( value : any, key : string ) => any;\r\nexport type ChangeAttrHandler = ( ( value : any, attr : string ) => void ) | string;\r\n\r\ndeclare global {\r\n interface Function {\r\n _attribute : typeof GenericAttribute\r\n }\r\n}\r\n\r\ninterface ExtendedAttributeDescriptor extends AttributeDescriptor {\r\n _attribute? : typeof GenericAttribute\r\n validate? : ( record : Record, value : any, key : string ) => any\r\n changeEvents? : boolean\r\n} \r\n\r\nexport { ExtendedAttributeDescriptor as AttributeDescriptor }\r\n\r\n// TODO: interface differs from options, do something obout it\r\n/** @private */\r\nexport class GenericAttribute implements Attribute {\r\n // Factory method to create attribute from options \r\n static create( options : ExtendedAttributeDescriptor, name : string ) : GenericAttribute {\r\n const type = options.type,\r\n AttributeCtor = options._attribute || ( type ? type._attribute : GenericAttribute );\r\n\r\n return new AttributeCtor( name, options );\r\n }\r\n /**\r\n * Update pipeline functions\r\n * =========================\r\n *\r\n * Stage 0. canBeUpdated( value )\r\n * - presence of this function implies attribute's ability to update in place.\r\n */\r\n canBeUpdated( prev, next, options : TransactionOptions ) : any {}\r\n\r\n /**\r\n * Stage 1. Transform stage\r\n */\r\n transform( value, options : TransactionOptions, prev, model : Record ) { return value; }\r\n\r\n // convert attribute type to `this.type`.\r\n convert( value, options : TransactionOptions, prev, model : Record ) { return value; }\r\n\r\n /**\r\n * Stage 2. Check if attr value is changed\r\n */\r\n isChanged( a, b ) {\r\n return notEqual( a, b );\r\n }\r\n\r\n /**\r\n * Stage 3. Handle attribute change\r\n */\r\n handleChange( next, prev, model : Record ) {}\r\n\r\n /**\r\n * End update pipeline definitions.\r\n */\r\n\r\n // create empty object passing backbone options to constructor...\r\n create() { return new ( this.type )(); }\r\n\r\n // generic clone function for typeless attributes\r\n // Must be overriden in sublass\r\n clone( value ) {\r\n if( value && typeof value === 'object' ) {\r\n // delegate to object's clone(), if it exist...\r\n if( value.clone ) return value.clone();\r\n\r\n const proto = Object.getPrototypeOf( value );\r\n\r\n // attempt to deep copy raw objects, assuming they are JSON \r\n if( proto === Object.prototype || proto === Array.prototype ){\r\n return JSON.parse( JSON.stringify( value ) ); // FIXME! This cloning will not work for Dates.\r\n }\r\n }\r\n\r\n return value;\r\n }\r\n\r\n validate( record : Record, value : any, key : string ){}\r\n\r\n toJSON( value, key ) {\r\n return value && value.toJSON ? value.toJSON() : value;\r\n }\r\n\r\n createPropertyDescriptor() : PropertyDescriptor | void {\r\n const { name, getHook } = this;\r\n\r\n if( name !== 'id' ){\r\n return {\r\n // call to optimized set function for single argument.\r\n set( value ){\r\n setAttribute( this, name, value );\r\n },\r\n\r\n // attach get hook to the getter function, if present\r\n get : getHook ?\r\n function() {\r\n return getHook.call( this, this.attributes[ name ], name );\r\n } :\r\n function() {\r\n return this.attributes[ name ];\r\n }\r\n }\r\n }\r\n }\r\n\r\n value : any\r\n type : Constructor< any >\r\n\r\n parse : ( value, key : string ) => any\r\n\r\n initialize( name : string, options ){}\r\n\r\n options : ExtendedAttributeDescriptor\r\n\r\n propagateChanges : boolean\r\n\r\n _log( level : string, text : string, value, record : Record ){\r\n tools.log[ level ]( `[Attribute Update] ${ record.getClassName() }.${ this.name }: ` + text, value, 'Attributes spec:', record._attributes );\r\n }\r\n\r\n constructor( public name : string, a_options : ExtendedAttributeDescriptor ) {\r\n // Clone options.\r\n const options : ExtendedAttributeDescriptor = this.options = assign( { getHooks : [], transforms : [], changeHandlers : [] }, a_options );\r\n options.getHooks = options.getHooks.slice();\r\n options.transforms = options.transforms.slice();\r\n options.changeHandlers = options.changeHandlers.slice();\r\n\r\n const {\r\n value, type, parse, toJSON, changeEvents,\r\n validate, getHooks, transforms, changeHandlers\r\n } = options;\r\n\r\n this.value = value;\r\n this.type = type;\r\n\r\n // Changes must be bubbled when they are not disabled for an attribute and transactional object.\r\n this.propagateChanges = changeEvents !== false;\r\n\r\n this.parse = parse;\r\n this.toJSON = toJSON === void 0 ? this.toJSON : toJSON;\r\n\r\n this.validate = validate || this.validate; \r\n\r\n /**\r\n * Assemble pipelines...\r\n */\r\n\r\n // `convert` is default transform, which is always present...\r\n transforms.unshift( this.convert );\r\n\r\n // Get hook from the attribute will be used first...\r\n if( this.get ) getHooks.unshift( this.get );\r\n\r\n // let subclasses configure the pipeline...\r\n this.initialize.call( this, options );\r\n\r\n // let attribute spec configure the pipeline...\r\n if( getHooks.length ){\r\n this.getHook = getHooks.reduce( chainGetHooks );\r\n }\r\n \r\n if( transforms.length ){\r\n this.transform = transforms.reduce( chainTransforms );\r\n }\r\n \r\n if( changeHandlers.length ){\r\n this.handleChange = changeHandlers.reduce( chainChangeHandlers );\r\n }\r\n }\r\n\r\n getHook : ( value, key : string ) => any = null\r\n get : ( value, key : string ) => any\r\n}\r\n\r\nRecord.prototype._attributes = { id : GenericAttribute.create({ value : void 0 }, 'id' )};\r\nRecord.prototype.defaults = function( attrs : { id? : string } = {} ){ return { id : attrs.id } };\r\n\r\n/** @private */\r\nfunction chainChangeHandlers( prevHandler : ChangeHandler, nextHandler : ChangeHandler ) : ChangeHandler {\r\n return function( next, prev, model ) {\r\n prevHandler.call( this, next, prev, model );\r\n nextHandler.call( this, next, prev, model );\r\n }\r\n}\r\n\r\n/** @private */\r\nfunction chainGetHooks( prevHook : GetHook, nextHook : GetHook ) : GetHook {\r\n return function( value, name ) {\r\n return nextHook.call( prevHook.call( value, name ), name );\r\n }\r\n}\r\n\r\n/** @private */\r\nfunction chainTransforms( prevTransform : Transform, nextTransform : Transform ) : Transform {\r\n return function( value, options, prev, model ) {\r\n return nextTransform.call( this, prevTransform.call( this, value, options, prev, model ), options, prev, model );\r\n }\r\n}\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/record/attributes/generic.ts\n **/","import { Record } from '../transaction' \r\nimport { GenericAttribute } from './generic'\r\nimport { Owner, transactionApi, Transactional, TransactionOptions, TransactionalConstructor } from '../../transactions'\r\nimport { tools } from '../../object-plus' \r\n\r\nconst { free, aquire } = transactionApi;\r\n\r\nexport class TransactionalType extends GenericAttribute {\r\n type : TransactionalConstructor\r\n\r\n canBeUpdated( prev : Transactional, next : any, options : TransactionOptions ) : any {\r\n // If an object already exists, and new value is of incompatible type, let object handle the update.\r\n if( prev && next != null ){\r\n if( next instanceof this.type ){\r\n // In case if merge option explicitly specified, force merge.\r\n if( options.merge ) return next._state;\r\n }\r\n else{\r\n return next;\r\n }\r\n }\r\n }\r\n\r\n convert( value : any, options : TransactionOptions, prev : any, record : Record ) : Transactional {\r\n // Invoke class factory to handle abstract classes\r\n if( value == null ) return value;\r\n \r\n if( value instanceof this.type ){\r\n if( value._shared === 1 ){ // TODO: think more about shared types assignment compatibility. \r\n this._log( 'error', 'aggregated attribute is assigned with shared collection type', value, record );\r\n }\r\n\r\n return options.merge ? value.clone() : value; // TODO: looks like clone is never called. Remove.\r\n }\r\n\r\n return this.type.create( value, options );\r\n }\r\n\r\n validate( record : Record, value : Transactional ){\r\n var error = value && value.validationError;\r\n if( error ) return error;\r\n }\r\n\r\n create() : Transactional {\r\n return (this.type).create(); // this the subclass of Transactional here.\r\n }\r\n\r\n initialize( options ){\r\n options.changeHandlers.unshift( this._handleChange );\r\n }\r\n\r\n _handleChange( next : Transactional, prev : Transactional, record : Record ){\r\n prev && free( record, prev );\r\n \r\n if( next && !aquire( record, next, this.name ) ){\r\n this._log( 'error', 'aggregated attribute assigned with object which is aggregated somewhere else', next, record );\r\n }\r\n }\r\n}\r\n\r\nRecord._attribute = TransactionalType;\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/record/attributes/owned.ts\n **/","import { GenericAttribute } from './generic'\r\nimport { tools } from '../../object-plus'\r\n\r\nconst DateProto = Date.prototype;\r\n\r\n// Date Attribute\r\n/** @private */\r\nexport class DateType extends GenericAttribute {\r\n convert( value : any ){\r\n if( value == null || value instanceof Date ) return value;\r\n \r\n const date = new Date( value );\r\n \r\n if( isNaN( +date ) ) this._log( 'warn', 'assigned with Invalid Date', value, arguments[ 3 ] );\r\n\r\n return date;\r\n }\r\n\r\n validate( model, value, name ) {\r\n if( value != null && isNaN( +value ) ) return name + ' is Invalid Date';\r\n }\r\n\r\n toJSON( value ) { return value && value.toISOString(); }\r\n\r\n isChanged( a, b ) { return ( a && +a ) !== ( b && +b ); }\r\n\r\n clone( value ) { return value && new Date( +value ); }\r\n}\r\n\r\nDate._attribute = DateType;\r\n\r\nconst msDatePattern = /\\/Date\\(([0-9]+)\\)\\//;\r\n\r\nexport class MSDateType extends DateType {\r\n convert( value ) {\r\n if( typeof value === 'string' ){\r\n const msDate = msDatePattern.exec( value );\r\n if( msDate ){\r\n return new Date( Number( msDate[ 1 ] ) );\r\n }\r\n }\r\n\r\n return DateType.prototype.convert.apply( this, arguments );\r\n }\r\n\r\n toJSON( value ) { return value && `/Date(${ value.getTime() })/`; }\r\n}\r\n\r\nexport class TimestampType extends DateType {\r\n toJSON( value ) { return value.getTime(); }\r\n}\r\n\r\n// If ISO date is not supported by date constructor (such as in Safari), polyfill it.\r\nfunction supportsDate( date ){\r\n return !isNaN( ( new Date( date ) ).getTime() );\r\n} \r\n\r\nif( !supportsDate('2011-11-29T15:52:30.5') || \r\n !supportsDate('2011-11-29T15:52:30.52') ||\r\n !supportsDate('2011-11-29T15:52:18.867') ||\r\n !supportsDate('2011-11-29T15:52:18.867Z') ||\r\n !supportsDate('2011-11-29T15:52:18.867-03:30') ){\r\n\r\n DateType.prototype.convert = function( value ){\r\n return value == null || value instanceof Date ? value : new Date( safeParseDate( value ) );\r\n } \r\n}\r\n\r\nconst numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ],\r\n isoDatePattern = /^(\\d{4}|[+\\-]\\d{6})(?:-(\\d{2})(?:-(\\d{2}))?)?(?:T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{3}))?)?(?:(Z)|([+\\-])(\\d{2})(?::(\\d{2}))?)?)?$/;\r\n\r\nfunction safeParseDate( date : string ) : number {\r\n var timestamp, struct, minutesOffset = 0;\r\n\r\n if( ( struct = isoDatePattern.exec( date )) ) {\r\n // avoid NaN timestamps caused by undefined values being passed to Date.UTC\r\n for( var i = 0, k; ( k = numericKeys[ i ] ); ++i ) {\r\n struct[ k ] = +struct[ k ] || 0;\r\n }\r\n\r\n // allow undefined days and months\r\n struct[ 2 ] = (+struct[ 2 ] || 1) - 1;\r\n struct[ 3 ] = +struct[ 3 ] || 1;\r\n\r\n if( struct[ 8 ] !== 'Z' && struct[ 9 ] !== undefined ) {\r\n minutesOffset = struct[ 10 ] * 60 + struct[ 11 ];\r\n\r\n if( struct[ 9 ] === '+' ) {\r\n minutesOffset = 0 - minutesOffset;\r\n }\r\n }\r\n\r\n timestamp =\r\n Date.UTC( struct[ 1 ], struct[ 2 ], struct[ 3 ], struct[ 4 ], struct[ 5 ] + minutesOffset, struct[ 6 ],\r\n struct[ 7 ] );\r\n }\r\n else {\r\n timestamp = Date.parse( date );\r\n }\r\n\r\n return timestamp;\r\n}\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/record/attributes/date.ts\n **/","import { GenericAttribute } from './generic'\r\nimport { tools } from '../../object-plus'\r\n\r\n// Default attribute type for all constructor functions...\r\n/** @private */\r\nclass ConstructorType extends GenericAttribute {\r\n type : new ( value : any ) => {}\r\n\r\n convert( value ) {\r\n return value == null || value instanceof this.type ? value : new this.type( value );\r\n }\r\n\r\n clone( value ) {\r\n // delegate to clone function or deep clone through serialization\r\n return value.clone ? value.clone() : this.convert( JSON.parse( JSON.stringify( value ) ) );\r\n }\r\n}\r\n\r\nFunction.prototype._attribute = ConstructorType;\r\n\r\n// Primitive Types.\r\n/** @private */\r\nexport class PrimitiveType extends GenericAttribute {\r\n type : NumberConstructor | StringConstructor | BooleanConstructor\r\n\r\n create() { return this.type(); }\r\n\r\n toJSON( value ) { return value; }\r\n\r\n convert( value ) { return value == null ? value : this.type( value ); }\r\n\r\n isChanged( a, b ) { return a !== b; }\r\n\r\n clone( value ) { return value; }\r\n}\r\n\r\nBoolean._attribute = String._attribute = PrimitiveType;\r\n\r\n// Number type with special validation algothim.\r\n/** @private */ \r\nexport class NumericType extends PrimitiveType {\r\n type : NumberConstructor\r\n\r\n convert( value ) {\r\n const num = value == null ? value : this.type( value ); \r\n\r\n if( num !== num ) this._log( 'warn', 'assigned with Invalid Number', value, arguments[ 3 ] );\r\n \r\n return num;\r\n }\r\n\r\n validate( model, value, name ) {\r\n // Whatever is not symmetrically serializable to JSON, is not valid by default.\r\n if( value != null && !isFinite( value ) ) {\r\n return name + ' is not valid number';\r\n }\r\n }\r\n}\r\n\r\nNumber._attribute = NumericType;\r\n\r\n/**\r\n * Compatibility wrapper for Array type.\r\n * @private\r\n */ \r\nexport class ArrayType extends GenericAttribute {\r\n toJSON( value ) { return value; }\r\n\r\n convert( value ) {\r\n // Fix incompatible constructor behaviour of Array...\r\n if( value == null || Array.isArray( value ) ) return value;\r\n\r\n this._log( 'warn', 'assigned with non-array', value, arguments[ 3 ] );\r\n\r\n return [];\r\n }\r\n}\r\n\r\nArray._attribute = ArrayType;\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/record/attributes/basic.ts\n **/","import { Record } from '../transaction'\r\nimport { GenericAttribute } from './generic'\r\nimport { Owner, transactionApi, Transactional, TransactionOptions, TransactionalConstructor } from '../../transactions' \r\nimport { tools, eventsApi } from '../../object-plus'\r\n\r\nconst { on, off } = eventsApi,\r\n { free, aquire } = transactionApi;\r\n\r\n/************************\r\n * Shared attribute definition.\r\n * - Not serialized.\r\n * - Listening to the changes.\r\n * - Doesn't take ownership.\r\n */\r\n\r\n/** @private */\r\nexport class SharedRecordType extends GenericAttribute {\r\n type : TransactionalConstructor\r\n\r\n clone( value : Transactional ){\r\n return value;\r\n }\r\n\r\n // TODO: Remove shared code?\r\n canBeUpdated( prev : Transactional, next : any, options : TransactionOptions ) : any {\r\n // If an object already exists, and new value is of incompatible type, let object handle the update.\r\n if( prev && next != null ){\r\n if( next instanceof this.type ){\r\n // In case if merge option explicitly specified, force merge.\r\n if( options.merge ) return next._state;\r\n }\r\n else{\r\n return next;\r\n }\r\n }\r\n }\r\n\r\n \r\n convert( value : any, options : TransactionOptions, prev : any, record : Record ) : Transactional {\r\n return value == null || value instanceof this.type ? value : this.type.create( value, options );\r\n }\r\n\r\n // Refs are always valid.\r\n validate( model, value, name ){}\r\n\r\n // They are always created as null.\r\n create() : Transactional {\r\n return null;\r\n }\r\n\r\n // Listening to the change events\r\n _handleChange( next : Transactional, prev : Transactional, record : Record ){\r\n prev && off( prev, prev._changeEventName, this._onChange, record );\r\n next && on( next, next._changeEventName, this._onChange, record );\r\n }\r\n\r\n _onChange : ( child : Transactional, options : TransactionOptions, initiator : Transactional ) => void \r\n\r\n initialize( options ){\r\n // Shared attributes are not serialized.\r\n this.toJSON = null;\r\n if( this.propagateChanges ){\r\n // Create change event handler which knows current attribute name. \r\n const attribute = this;\r\n this._onChange = function( child, options, initiator ){\r\n this === initiator || this.forceAttributeChange( attribute.name, options );\r\n }\r\n\r\n options.changeHandlers.unshift( this._handleChange );\r\n }\r\n }\r\n}\r\n\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/record/attributes/shared.ts\n **/","/**\r\n * Type spec engine. Declare attributes using chainable syntax,\r\n * and returns object with spec.\r\n */\r\nimport { Transactional } from '../transactions'\r\nimport { ChangeAttrHandler, AttributeDescriptor } from './attributes'\r\nimport { Record } from './transaction'\r\nimport { EventMap, EventsDefinition, Constructor, tools } from '../object-plus'\r\n\r\nconst { assign } = tools;\r\n\r\nexport interface AttributeCheck {\r\n ( value : any, key : string ) : boolean\r\n error? : any\r\n}\r\n\r\nexport class ChainableAttributeSpec {\r\n options : AttributeDescriptor;\r\n\r\n constructor( options : AttributeDescriptor = {} ) {\r\n this.options = { getHooks : [], transforms : [], changeHandlers : []};\r\n assign( this.options, options );\r\n }\r\n\r\n check( check : AttributeCheck, error : any ) : this {\r\n function validate( model, value, name ){\r\n if( !check.call( model, value, name ) ){\r\n return error || check.error || name + ' is not valid';\r\n }\r\n }\r\n\r\n const prev = this.options.validate;\r\n\r\n this.options.validate = prev ? (\r\n function( model, value, name ){\r\n return prev( model, value, name ) || validate( model, value, name );\r\n }\r\n ) : validate;\r\n\r\n return this;\r\n }\r\n\r\n watcher( ref : string | ( ( value : any, key : string ) => void ) ) : this {\r\n this.options._onChange = ref;\r\n return this;\r\n }\r\n\r\n parse( fun ) : this {\r\n this.options.parse = fun;\r\n return this;\r\n }\r\n\r\n toJSON( fun ) : this{\r\n this.options.toJSON = fun || null;\r\n return this;\r\n }\r\n\r\n // Attribute get hook.\r\n get( fun ) : this {\r\n this.options.getHooks.push( fun );\r\n\r\n return this;\r\n }\r\n\r\n // Attribute set hook.\r\n set( fun ) : this {\r\n this.options.transforms.push( function( next, options, prev, model ) {\r\n if( this.isChanged( next, prev ) ) {\r\n var changed = fun.call( model, next, this.name );\r\n return changed === void 0 ? prev : this.convert( changed, options, prev, model );\r\n }\r\n\r\n return prev;\r\n } );\r\n\r\n return this;\r\n }\r\n\r\n changeEvents( events : boolean ){\r\n this.options.changeEvents = events;\r\n\r\n return this;\r\n }\r\n\r\n // Subsribe to events from an attribute.\r\n events( map : EventsDefinition ) : this {\r\n const eventMap = new EventMap( map );\r\n\r\n this.options.changeHandlers.push( function( next, prev, record : Record ){\r\n prev && prev.trigger && eventMap.unsubscribe( record, prev );\r\n\r\n next && next.trigger && eventMap.subscribe( record, next );\r\n });\r\n\r\n return this;\r\n }\r\n\r\n get has() : this { return this; }\r\n\r\n /*\r\n get isRequired() {\r\n this.options.isRequired = true;\r\n return this;\r\n }*/\r\n\r\n value( x ) : this {\r\n this.options.value = x;\r\n return this;\r\n }\r\n}\r\n\r\ndeclare global {\r\n interface Function{\r\n value : ( x : any ) => ChainableAttributeSpec;\r\n isRequired : ChainableAttributeSpec;\r\n has : ChainableAttributeSpec;\r\n }\r\n}\r\n\r\nFunction.prototype.value = function( x ) {\r\n return new ChainableAttributeSpec( { type : this, value : x } );\r\n};\r\n\r\n/*\r\nObject.defineProperty( Function.prototype, 'isRequired', {\r\n get() {\r\n return new ChainableAttributeSpec( { type : this, isRequired : true } );\r\n } \r\n});*/\r\n\r\nObject.defineProperty( Function.prototype, 'has', {\r\n get() {\r\n // workaround for sinon.js and other libraries overriding 'has'\r\n return this._has || new ChainableAttributeSpec( { type : this } );\r\n },\r\n\r\n set( value ) { this._has = value; }\r\n} );\r\n\r\nexport function toAttributeDescriptor( spec : any ) : AttributeDescriptor {\r\n let attrSpec : ChainableAttributeSpec;\r\n\r\n if( typeof spec === 'function' ) {\r\n attrSpec = new ChainableAttributeSpec({ type : spec });\r\n }\r\n else if( spec && spec instanceof ChainableAttributeSpec ) {\r\n attrSpec = spec;\r\n }\r\n else{\r\n // Infer type from value.\r\n const type = inferType( spec );\r\n\r\n // Transactional types inferred from values must have shared type. \r\n if( type && type.prototype instanceof Transactional ){\r\n attrSpec = (type).shared.value( spec );\r\n }\r\n // All others will be created in regular way.\r\n else{\r\n attrSpec = new ChainableAttributeSpec({ type : type, value : spec });\r\n }\r\n }\r\n \r\n return attrSpec.options;\r\n}\r\n\r\nfunction inferType( value : {} ) : Constructor {\r\n switch( typeof value ) {\r\n case 'number' :\r\n return Number;\r\n case 'string' :\r\n return String;\r\n case 'boolean' :\r\n return Boolean;\r\n case 'undefined' :\r\n return void 0;\r\n case 'object' :\r\n return value ? value.constructor : void 0;\r\n }\r\n}\r\n\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/record/typespec.ts\n **/","import { Record } from '../record'\r\nimport { Owner, Transaction,\r\n TransactionOptions, Transactional, transactionApi } from '../transactions'\r\n\r\nimport { eventsApi, tools } from '../object-plus'\r\n\r\nconst { EventMap, trigger2, trigger3, on, off } = eventsApi,\r\n { commit, markAsDirty } = transactionApi,\r\n _aquire = transactionApi.aquire, _free = transactionApi.free;\r\n\r\n/** @private */\r\nexport interface CollectionCore extends Transactional, Owner {\r\n _byId : IdIndex\r\n models : Record[]\r\n model : typeof Record\r\n idAttribute : string // TODO: Refactor inconsistent idAttribute usage\r\n _comparator : Comparator\r\n get( objOrId : string | Record | Object ) : Record \r\n _itemEvents? : eventsApi.EventMap\r\n _shared : number\r\n _aggregationError : Record[]\r\n\r\n _log( level : string, text : string, value )\r\n}\r\n\r\n// Collection's manipulation methods elements\r\nexport type Elements = ( Object | Record )[];\r\n\r\nexport interface CollectionOptions extends TransactionOptions {\r\n sort? : boolean\r\n}\r\n\r\nexport type Comparator = ( a : Record, b : Record ) => number; \r\n\r\n/** @private */\r\nexport function dispose( collection : CollectionCore ) : Record[]{\r\n const models = collection.models;\r\n\r\n collection.models = [];\r\n collection._byId = {};\r\n\r\n freeAll( collection, models );\r\n return models;\r\n}\r\n\r\n/** @private */\r\nexport function convertAndAquire( collection : CollectionCore, attrs : {} | Record, options ){\r\n const { model } = collection;\r\n let record : Record;\r\n\r\n if( collection._shared ){\r\n record = attrs instanceof model ? attrs : model.create( attrs, options );\r\n\r\n if( collection._shared === 1 ){\r\n on( record, record._changeEventName, collection._onChildrenChange, collection );\r\n }\r\n }\r\n else{\r\n record = attrs instanceof model ? ( options.merge ? attrs.clone() : attrs ) : model.create( attrs, options );\r\n\r\n if( !_aquire( collection, record ) ){\r\n const errors = collection._aggregationError || ( collection._aggregationError = [] );\r\n errors.push( record );\r\n }\r\n } \r\n\r\n // Subscribe for events...\r\n const { _itemEvents } = collection;\r\n _itemEvents && _itemEvents.subscribe( collection, record );\r\n\r\n return record;\r\n}\r\n\r\n/** @private */\r\nexport function free( owner : CollectionCore, child : Record ) : void {\r\n if( owner._shared ){\r\n if( owner._shared === 1 ){\r\n off( child, child._changeEventName, owner._onChildrenChange, owner );\r\n }\r\n }\r\n else{\r\n _free( owner, child );\r\n }\r\n\r\n const { _itemEvents } = owner;\r\n _itemEvents && _itemEvents.unsubscribe( owner, child );\r\n}\r\n\r\n/** @private */\r\nexport function freeAll( collection : CollectionCore, children : Record[] ) : Record[] {\r\n for( let child of children ){\r\n free( collection, child );\r\n }\r\n\r\n return children;\r\n}\r\n\r\n/**\r\n * Silently sort collection, if its required. Returns true if sort happened.\r\n * @private\r\n */ \r\nexport function sortElements( collection : CollectionCore, options : CollectionOptions ) : boolean {\r\n let { _comparator } = collection;\r\n if( _comparator && options.sort !== false ){\r\n collection.models.sort( _comparator );\r\n return true;\r\n }\r\n\r\n return false;\r\n}\r\n\r\n/**********************************\r\n * Collection Index\r\n * @private \r\n */\r\nexport interface IdIndex {\r\n [ id : string ] : Record\r\n}\r\n\r\n/** @private Add record */ \r\nexport function addIndex( index : IdIndex, model : Record ) : void {\r\n index[ model.cid ] = model;\r\n var id = model.id;\r\n \r\n if( id != null ){\r\n index[ id ] = model;\r\n }\r\n}\r\n\r\n/** @private Remove record */ \r\nexport function removeIndex( index : IdIndex, model : Record ) : void {\r\n delete index[ model.cid ];\r\n var id = model.id;\r\n if( id != null ){\r\n delete index[ id ];\r\n }\r\n}\r\n\r\nexport function updateIndex( index : IdIndex, model : Record ){\r\n delete index[ model.previous( model.idAttribute ) ];\r\n\r\n const { id } = model;\r\n id == null || ( index[ id ] = model );\r\n}\r\n\r\n/***\r\n * In Collections, transactions appears only when\r\n * add remove or change events might be emitted.\r\n * reset doesn't require transaction.\r\n * \r\n * Transaction holds information regarding events, and knows how to emit them.\r\n * \r\n * Two major optimization cases.\r\n * 1) Population of an empty collection\r\n * 2) Update of the collection (no or little changes) - it's crucial to reject empty transactions.\r\n */\r\n\r\n\r\n// Transaction class. Implements two-phase transactions on object's tree.\r\n/** @private */ \r\nexport class CollectionTransaction implements Transaction {\r\n // open transaction\r\n constructor( public object : CollectionCore,\r\n public isRoot : boolean,\r\n public added : Record[],\r\n public removed : Record[],\r\n public nested : Transaction[],\r\n public sorted : boolean ){}\r\n\r\n // commit transaction\r\n commit( initiator? : Transactional ){\r\n const { nested, object } = this,\r\n { _isDirty } = object;\r\n\r\n // Commit all nested transactions...\r\n for( let transaction of nested ){\r\n transaction.commit( object );\r\n }\r\n\r\n if( object._aggregationError ){\r\n logAggregationError( object );\r\n }\r\n\r\n // Just trigger 'change' on collection, it must be already triggered for models during nested commits.\r\n // ??? TODO: do it in nested transactions loop? This way appears to be more correct. \r\n for( let transaction of nested ){\r\n trigger2( object, 'change', transaction.object, _isDirty );\r\n }\r\n\r\n // Notify listeners on attribute changes...\r\n const { added, removed } = this;\r\n\r\n // Trigger `add` events for both model and collection.\r\n for( let record of added ){\r\n trigger3( record, 'add', record, object, _isDirty );\r\n trigger3( object, 'add', record, object, _isDirty );\r\n }\r\n\r\n // Trigger `remove` events for both model and collection.\r\n for( let record of removed ){\r\n trigger3( record, 'remove', record, object, _isDirty );\r\n trigger3( object, 'remove', record, object, _isDirty );\r\n }\r\n\r\n if( this.sorted ){\r\n trigger2( object, 'sort', object, _isDirty );\r\n }\r\n\r\n if( added.length || removed.length ){\r\n trigger2( object, 'update', object, _isDirty );\r\n }\r\n\r\n this.isRoot && commit( object, initiator );\r\n }\r\n}\r\n\r\nexport function logAggregationError( collection : CollectionCore ){\r\n collection._log( 'error', 'added records already have an owner', collection._aggregationError );\r\n collection._aggregationError = void 0;\r\n}\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/collection/commons.ts\n **/","import { Transaction, transactionApi } from '../transactions'\r\nimport { CollectionTransaction, logAggregationError, sortElements, convertAndAquire, free, CollectionOptions, addIndex, updateIndex, CollectionCore } from './commons'\r\nimport { Record } from '../record'\r\n\r\nconst { begin, commit, markAsDirty } = transactionApi;\r\n\r\ninterface AddOptions extends CollectionOptions {\r\n at? : number \r\n}\r\n\r\n/** @private */\r\nexport function addTransaction( collection : CollectionCore, items, options : AddOptions, merge? : boolean ){\r\n const isRoot = begin( collection ),\r\n nested = [];\r\n\r\n var added = appendElements( collection, items, nested, options, merge );\r\n\r\n if( added.length || nested.length ){\r\n let needSort = sortOrMoveElements( collection, added, options );\r\n if( markAsDirty( collection, options ) ){\r\n return new CollectionTransaction( collection, isRoot, added, [], nested, needSort );\r\n }\r\n\r\n if( collection._aggregationError ) logAggregationError( collection );\r\n }\r\n\r\n // No changes...\r\n isRoot && commit( collection );\r\n};\r\n\r\n// Handle sort or insert at options for add operation. Reurns true if sort happened.\r\n/** @private */ \r\nfunction sortOrMoveElements( collection : CollectionCore, added : Record[], options : AddOptions ) : boolean {\r\n let at = options.at;\r\n\r\n // if `at` option is given, it overrides sorting option...\r\n if( at != null ){\r\n // Take an original collection's length. \r\n const length = collection.models.length - added.length;\r\n\r\n // Crazy Backbone rules about `at` index. I don't know what that guys smoke.\r\n at = Number( at );\r\n if( at < 0 ) at += length + 1;\r\n if( at < 0 ) at = 0;\r\n if( at > length ) at = length;\r\n\r\n // Move added elements to desired position. In place.\r\n moveElements( collection.models, at, added );\r\n return false;\r\n }\r\n\r\n return sortElements( collection, options );\r\n}\r\n\r\n/** @private */\r\nfunction moveElements( source : any[], at : number, added : any[] ) : void {\r\n for( var j = source.length - 1, i = j - added.length; i >= at; i--, j-- ){\r\n source[ j ] = source[ i ];\r\n }\r\n\r\n for( i = 0, j = at; i < added.length; i++, j++ ){\r\n source[ j ] = added[ i ];\r\n }\r\n}\r\n\r\n// append data to model and index\r\n/** @private */\r\nfunction appendElements( collection : CollectionCore, a_items, nested : Transaction[], a_options, forceMerge : boolean ){\r\n var { _byId, models } = collection,\r\n merge = ( forceMerge || a_options.merge ) && !collection._shared,\r\n parse = a_options.parse,\r\n idAttribute = collection.model.prototype.idAttribute,\r\n prevLength = models.length;\r\n\r\n for( const item of a_items ){\r\n let model = item ? _byId[ item[ idAttribute ] ] || _byId[ item.cid ] : null;\r\n\r\n if( model ){\r\n if( merge && item !== model ){\r\n var attrs = item.attributes || item;\r\n const transaction = model._createTransaction( attrs, a_options );\r\n transaction && nested.push( transaction );\r\n\r\n if( model.hasChanged( idAttribute ) ){\r\n updateIndex( _byId, model );\r\n }\r\n }\r\n }\r\n else{\r\n model = convertAndAquire( collection, item, a_options );\r\n models.push( model );\r\n addIndex( _byId, model );\r\n }\r\n }\r\n\r\n return models.slice( prevLength );\r\n}\r\n\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/collection/add.ts\n **/","import { Transaction, transactionApi } from '../transactions'\r\nimport { CollectionTransaction, logAggregationError, IdIndex, convertAndAquire, free, sortElements, CollectionOptions, addIndex, CollectionCore, Elements, freeAll } from './commons'\r\nimport { Record } from '../record'\r\n\r\nconst { begin, commit, markAsDirty } = transactionApi;\r\n\r\n/** @private */\r\nconst silentOptions = { silent : true };\r\n\r\n/** @private */\r\nexport function emptySetTransaction( collection : CollectionCore, items : Elements, options : CollectionOptions, silent? : boolean ){\r\n const isRoot = begin( collection );\r\n\r\n const added = _reallocateEmpty( collection, items, options );\r\n\r\n if( added.length ){\r\n const needSort = sortElements( collection, options );\r\n\r\n if( markAsDirty( collection, silent ? silentOptions : options ) ){\r\n // 'added' is the reference to this.models. Need to copy it.\r\n return new CollectionTransaction( collection, isRoot, added.slice(), [], [], needSort );\r\n }\r\n\r\n if( collection._aggregationError ) logAggregationError( collection );\r\n }\r\n\r\n // No changes...\r\n isRoot && commit( collection );\r\n};\r\n\r\n/** @private */\r\nexport function setTransaction( collection, items, options ){\r\n const isRoot = begin( collection ),\r\n nested = [];\r\n\r\n var previous = collection.models,\r\n added = _reallocate( collection, items, nested, options );\r\n\r\n const reusedCount = collection.models.length - added.length,\r\n removed = reusedCount < previous.length ? (\r\n reusedCount ? _garbageCollect( collection, previous ) :\r\n freeAll( collection, previous )\r\n ) : []; \r\n \r\n const addedOrChanged = nested.length || added.length,\r\n sorted = ( addedOrChanged && sortElements( collection, options ) ) || added.length || options.sorted;\r\n\r\n if( addedOrChanged || removed.length || sorted ){\r\n if( markAsDirty( collection, options ) ){ \r\n return new CollectionTransaction( collection, isRoot, added, removed, nested, sorted );\r\n }\r\n\r\n if( collection._aggregationError ) logAggregationError( collection );\r\n }\r\n\r\n isRoot && commit( collection );\r\n};\r\n\r\n// Remove references to all previous elements, which are not present in collection.\r\n// Returns an array with removed elements.\r\n/** @private */\r\nfunction _garbageCollect( collection : CollectionCore, previous : Record[] ) : Record[]{\r\n const { _byId } = collection,\r\n removed = [];\r\n\r\n // Filter out removed models and remove them from the index...\r\n for( let record of previous ){\r\n if( !_byId[ record.cid ] ){\r\n removed.push( record );\r\n free( collection, record );\r\n }\r\n }\r\n\r\n return removed;\r\n}\r\n\r\n// reallocate model and index\r\n/** @private */\r\nfunction _reallocate( collection : CollectionCore, source : any[], nested : Transaction[], options ){\r\n var models = Array( source.length ),\r\n _byId : IdIndex = {},\r\n merge = ( options.merge == null ? true : options.merge ) && !collection._shared,\r\n _prevById = collection._byId,\r\n prevModels = collection.models, \r\n idAttribute = collection.model.prototype.idAttribute,\r\n toAdd = [],\r\n orderKept = true;\r\n\r\n // for each item in source set...\r\n for( var i = 0, j = 0; i < source.length; i++ ){\r\n var item = source[ i ],\r\n model : Record = null;\r\n\r\n if( item ){\r\n var id = item[ idAttribute ],\r\n cid = item.cid;\r\n\r\n if( _byId[ id ] || _byId[ cid ] ) continue;\r\n\r\n model = _prevById[ id ] || _prevById[ cid ];\r\n }\r\n\r\n if( model ){\r\n if( merge && item !== model ){\r\n if( orderKept && prevModels[ j ] !== model ) orderKept = false;\r\n\r\n var attrs = item.attributes || item;\r\n const transaction = model._createTransaction( attrs, options );\r\n transaction && nested.push( transaction );\r\n }\r\n }\r\n else{\r\n model = convertAndAquire( collection, item, options );\r\n toAdd.push( model );\r\n }\r\n\r\n models[ j++ ] = model;\r\n addIndex( _byId, model );\r\n }\r\n\r\n models.length = j;\r\n collection.models = models;\r\n collection._byId = _byId;\r\n\r\n if( !orderKept ) options.sorted = true;\r\n\r\n return toAdd;\r\n}\r\n\r\n/** @private */\r\nfunction _reallocateEmpty( self, source, options ){\r\n var len = source ? source.length : 0,\r\n models = Array( len ),\r\n _byId : IdIndex = {},\r\n idAttribute = self.model.prototype.idAttribute;\r\n\r\n for( var i = 0, j = 0; i < len; i++ ){\r\n var src = source[ i ];\r\n\r\n if( src && ( _byId[ src[ idAttribute ] ] || _byId[ src.cid ] ) ){\r\n continue;\r\n }\r\n\r\n var model = convertAndAquire( self, src, options );\r\n models[ j++ ] = model;\r\n addIndex( _byId, model );\r\n }\r\n\r\n models.length = j;\r\n self._byId = _byId;\r\n\r\n return self.models = models;\r\n}\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/collection/set.ts\n **/","/*************\r\n * Remove items from collections.\r\n * \r\n * Cannot be a part of two-phase transaction on object tree.\r\n * Can be executed in the scope of ad-hoc transaction or from the trigger, though.\r\n *\r\n * Implemented with low-level API. \r\n * Most frequent operation - single element remove. Thus, it have the fast-path.\r\n */\r\n\r\nimport { Record } from '../record'\r\nimport { free, CollectionCore, CollectionTransaction, removeIndex } from './commons'\r\nimport { eventsApi } from '../object-plus'\r\nimport { TransactionOptions, transactionApi } from '../transactions' \r\n\r\nconst { trigger2, trigger3 } = eventsApi,\r\n { markAsDirty, begin, commit } = transactionApi;\r\n\r\n/** @private */\r\nexport function removeOne( collection : CollectionCore, el : Record | {} | string, options : TransactionOptions ) : Record {\r\n var model : Record = collection.get( el );\r\n\r\n if( model ){\r\n const isRoot = begin( collection ),\r\n models = collection.models;\r\n\r\n // Remove model form the collection. \r\n models.splice( models.indexOf( model ), 1 );\r\n removeIndex( collection._byId, model );\r\n \r\n // Mark transaction as dirty. \r\n const notify = markAsDirty( collection, options );\r\n\r\n // Send out events.\r\n if( notify ){\r\n trigger3( model, 'remove', model, collection, options );\r\n trigger3( collection, 'remove', model, collection, options );\r\n } \r\n\r\n free( collection, model );\r\n\r\n notify && trigger2( collection, 'update', collection, options );\r\n\r\n // Commit transaction.\r\n isRoot && commit( collection );\r\n\r\n return model;\r\n }\r\n};\r\n\r\n/** Optimized for removing many elements\r\n * 1. Remove elements from the index, checking for duplicates\r\n * 2. Create new models array matching index\r\n * 3. Send notifications and remove references\r\n */\r\n\r\n/** @private */\r\nexport function removeMany( collection : CollectionCore, toRemove : any[], options ){\r\n const removed = _removeFromIndex( collection, toRemove );\r\n if( removed.length ){\r\n const isRoot = begin( collection );\r\n\r\n _reallocate( collection, removed.length );\r\n\r\n if( markAsDirty( collection, options ) ){\r\n const transaction = new CollectionTransaction( collection, isRoot, [], removed, [], false );\r\n transaction.commit();\r\n }\r\n else{\r\n // Commit transaction.\r\n isRoot && commit( collection );\r\n }\r\n }\r\n\r\n return removed;\r\n};\r\n\r\n// remove models from the index...\r\n/** @private */\r\nfunction _removeFromIndex( collection, toRemove ){\r\n var removed = Array( toRemove.length ),\r\n _byId = collection._byId;\r\n\r\n for( var i = 0, j = 0; i < toRemove.length; i++ ){\r\n var model = collection.get( toRemove[ i ] );\r\n if( model ){\r\n removed[ j++ ] = model;\r\n removeIndex( _byId, model );\r\n free( collection, model );\r\n }\r\n }\r\n\r\n removed.length = j;\r\n\r\n return removed;\r\n}\r\n\r\n// Allocate new models array removing models not present in the index.\r\n/** @private */\r\nfunction _reallocate( collection, removed ){\r\n var prev = collection.models,\r\n models = collection.models = Array( prev.length - removed ),\r\n _byId = collection._byId;\r\n\r\n for( var i = 0, j = 0; i < prev.length; i++ ){\r\n var model = prev[ i ];\r\n\r\n if( _byId[ model.cid ] ){\r\n models[ j++ ] = model;\r\n }\r\n }\r\n\r\n models.length = j;\r\n}\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/collection/remove.ts\n **/","import './from'\r\nimport './subsetOf'\r\n\r\nexport { Store } from './store'\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/relations/index.ts\n **/","import { GenericAttribute, AttributeDescriptor } from '../record'\r\nimport { parseReference, CollectionReference } from './commons'\r\nimport { Collection } from '../collection'\r\nimport { Record } from '../record'\r\n\r\nimport { ChainableAttributeSpec } from '../record'\r\n\r\n/********\r\n * Reference to model by id.\r\n * \r\n * Untyped attribute. Holds model id, when unresolved. When resolved, is substituted\r\n * with a real model.\r\n * \r\n * No model changes are detected and counted as owner's change. That's intentional.\r\n */\r\n\r\n/** @private */\r\ntype RecordRefValue = Record | string;\r\n\r\n/** @private */\r\nclass RecordRefAttribute extends GenericAttribute {\r\n // It is always serialized as an id, whenever it's resolved or not. \r\n toJSON( value : RecordRefValue ){\r\n return value && typeof value === 'object' ? value.id : value;\r\n }\r\n\r\n // Wne \r\n clone( value : RecordRefValue ){\r\n return value && typeof value === 'object' ? value.id : value;\r\n }\r\n\r\n // Model refs by id are equal when their ids are equal.\r\n isChanged( a : RecordRefValue, b : RecordRefValue){\r\n var aId = a && ( (a).id == null ? a : (a).id ),\r\n bId = b && ( (b).id == null ? b : (b).id );\r\n\r\n return aId !== bId;\r\n }\r\n\r\n // Refs are always valid.\r\n validate( model, value, name ){}\r\n}\r\n\r\nRecord.from = function from( masterCollection : CollectionReference ) : ChainableAttributeSpec {\r\n const getMasterCollection = parseReference( masterCollection );\r\n\r\n const typeSpec = new ChainableAttributeSpec({\r\n value : null,\r\n _attribute : RecordRefAttribute\r\n });\r\n \r\n typeSpec\r\n .get( function( objOrId : RecordRefValue, name : string ) : Record {\r\n if( typeof objOrId === 'object' ) return objOrId;\r\n\r\n // So, we're dealing with an id reference. Resolve it.\r\n const collection = getMasterCollection( this );\r\n let record : Record = null;\r\n\r\n // If master collection exists and is not empty...\r\n if( collection && collection.length ){\r\n // Silently update attribute with record from this collection.\r\n record = collection.get( objOrId ) || null;\r\n this.attributes[ name ] = record;\r\n\r\n // Subscribe for events manually. delegateEvents won't be invoked.\r\n record && this._attributes[ name ].handleChange( record, null, this );\r\n }\r\n\r\n return record;\r\n });\r\n\r\n return typeSpec;\r\n};\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/relations/from.ts\n **/","import { Collection } from '../collection'\r\nimport { Record } from '../record'\r\nimport { CompiledReference } from '../traversable'\r\n\r\nexport type CollectionReference = ( () => Collection ) | Collection | string; \r\n\r\n/** @private */\r\nexport function parseReference( collectionRef : CollectionReference ) : ( root : Record ) => Collection {\r\n switch( typeof collectionRef ){\r\n case 'function' :\r\n return root => (collectionRef).call( root );\r\n case 'object' :\r\n return () => collectionRef;\r\n case 'string' :\r\n const { resolve } = new CompiledReference( collectionRef );\r\n return resolve;\r\n }\r\n}\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/relations/commons.ts\n **/","import { Collection, CollectionOptions } from '../collection'\r\nimport { tools, define } from '../object-plus'\r\nimport { Record, TransactionalType } from '../record'\r\nimport { parseReference, CollectionReference } from './commons'\r\nimport { ChainableAttributeSpec } from '../record'\r\nimport { Transactional, TransactionOptions } from '../transactions'\r\n\r\nconst { fastDefaults } = tools;\r\n\r\ntype RecordsIds = ( string | number )[];\r\n\r\nCollection.subsetOf = function subsetOf( masterCollection : CollectionReference ) : ChainableAttributeSpec {\r\n const SubsetOf = this._SubsetOf || ( this._SubsetOf = defineSubsetCollection( this ) ),\r\n getMasterCollection = parseReference( masterCollection ),\r\n typeSpec = new ChainableAttributeSpec({\r\n type : SubsetOf\r\n });\r\n\r\n typeSpec.get(\r\n function( refs ){\r\n !refs || refs.resolvedWith || refs.resolve( getMasterCollection( this ) );\r\n return refs;\r\n }\r\n );\r\n\r\n return typeSpec;\r\n};\r\n\r\n/** @private */\r\nfunction subsetOptions( options : CollectionOptions ){\r\n const subsetOptions = { parse : true };\r\n if( options ) fastDefaults( subsetOptions, options );\r\n return subsetOptions;\r\n}\r\n\r\nfunction defineSubsetCollection( CollectionConstructor : typeof Collection ) {\r\n @define({})\r\n class SubsetOfCollection extends CollectionConstructor {\r\n refs : any[];\r\n resolvedWith : Collection = null;\r\n\r\n _attribute : TransactionalType\r\n\r\n get _state(){ return this.refs || this.models; }\r\n\r\n constructor( recordsOrIds?, options? ){\r\n super( recordsOrIds, subsetOptions( options ), 2 );\r\n }\r\n\r\n add( elements, options? ){\r\n return super.add( elements, subsetOptions( options ) );\r\n }\r\n\r\n reset( elements?, options? ){\r\n return super.reset( elements, subsetOptions( options ) );\r\n }\r\n\r\n _createTransaction( elements, options? ){\r\n return super._createTransaction( elements, subsetOptions( options ) );\r\n }\r\n\r\n // Serialized as an array of model ids.\r\n toJSON() : RecordsIds {\r\n return this.refs ?\r\n this.refs.map( objOrId => objOrId.id || objOrId ) :\r\n this.models.map( model => model.id );\r\n }\r\n\r\n // Subset is always valid.\r\n _validateNested(){ return 0; }\r\n\r\n // Must be shallow copied on clone.\r\n clone( owner? ){\r\n var Ctor = (this).constructor,\r\n copy = new Ctor( [], {\r\n model : this.model,\r\n comparator : this.comparator\r\n });\r\n\r\n if( this.resolvedWith ){\r\n copy.resolvedWith = this.resolvedWith;\r\n copy.reset( this.models, { silent : true } );\r\n }\r\n else{\r\n copy.refs = this.refs;\r\n }\r\n\r\n return copy;\r\n }\r\n\r\n // Parse is always invoked. Careful, performance-sensitive.\r\n parse( raw : any ) : Record[] {\r\n const { resolvedWith } = this,\r\n elements = Array.isArray( raw ) ? raw : [ raw ],\r\n records : Record[] = []; \r\n\r\n if( resolvedWith ){\r\n for( let element of elements ){\r\n const record = resolvedWith.get( element );\r\n if( record ) records.push( record );\r\n }\r\n }\r\n else if( elements.length ){\r\n this.refs = elements;\r\n }\r\n\r\n return records;\r\n }\r\n\r\n resolve( collection : Collection ) : this {\r\n if( collection && collection.length ){\r\n this.resolvedWith = collection;\r\n\r\n if( this.refs ){\r\n this.reset( this.refs, { silent : true } );\r\n this.refs = null;\r\n }\r\n }\r\n\r\n return this;\r\n }\r\n\r\n getModelIds() : RecordsIds { return this.toJSON(); }\r\n\r\n toggle( modelOrId : any, val : boolean ) : boolean {\r\n return super.toggle( this.resolvedWith.get( modelOrId ), val );\r\n }\r\n\r\n addAll() : Record[] {\r\n return this.reset( this.resolvedWith.models );\r\n }\r\n\r\n toggleAll() : Record[] {\r\n return this.length ? this.reset() : this.addAll();\r\n }\r\n }\r\n\r\n return SubsetOfCollection;\r\n}\r\n\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/relations/subsetOf.ts\n **/","import { Record } from '../record'\r\nimport { Transactional } from '../transactions'\r\n\r\nlet _store : Store = null;\r\n\r\nexport class Store extends Record {\r\n getStore() : Store { return this; }\r\n \r\n // delegate item lookup to owner, and to the global store if undefined\r\n get( name : string ) : any {\r\n // Lookup for resource in the current store. \r\n let local = this[ name ];\r\n\r\n // If something is found or it's the global store, return result.\r\n if( local || this === this._defaultStore ) return local;\r\n\r\n // Forward failed lookup to owner or global store.\r\n return this._owner ? this._owner.get( name ) : this._defaultStore.get( name ); \r\n }\r\n\r\n static get global(){ return _store; }\r\n static set global( store : Store ){\r\n if( _store ){\r\n _store.dispose();\r\n }\r\n\r\n Transactional.prototype._defaultStore = _store = store;\r\n }\r\n}\r\n\r\nStore.global = new Store();\n\n\n/** WEBPACK FOOTER **\n ** ./type-r/src/relations/store.ts\n **/","/*******\r\n * Backbone Backward compatibility shim for View, Router, and History.\r\n * Based on 1.2.3, converted to browser-only ES6 modules thing. \r\n */\r\n\r\n// Backbone.js 1.2.3\r\n// (c) 2010-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\r\n// Backbone may be freely distributed under the MIT license.\r\nimport * as _ from 'underscore'\r\nimport * as jQuery from 'jquery'\r\n\r\n// Initial Setup\r\n// -------------\r\n\r\n// Save the previous value of the `Backbone` variable, so that it can be\r\n// restored later on, if `noConflict` is used.\r\nconst previousBackbone = window.Backbone;\r\n\r\n// Create a local reference to a common array method we'll want to use later.\r\nconst slice = Array.prototype.slice;\r\n\r\n// Current version of the library. Keep in sync with `package.json`.\r\nexport const VERSION = '1.2.3';\r\n\r\n// For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns\r\n// the `$` variable.\r\nexport let $ = jQuery;\r\n\r\n// Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable\r\n// to its previous owner. Returns a reference to this Backbone object.\r\nexport function noConflict() {\r\n window.Backbone = previousBackbone;\r\n return this;\r\n};\r\n\r\nexport let emulateHTTP = false;\r\nexport let emulateJSON = false;\r\n\r\n// Backbone.View\r\n// -------------\r\n\r\n// Backbone Views are almost more convention than they are actual code. A View\r\n// is simply a JavaScript object that represents a logical chunk of UI in the\r\n// DOM. This might be a single item, an entire list, a sidebar or panel, or\r\n// even the surrounding frame which wraps your whole app. Defining a chunk of\r\n// UI as a **View** allows you to define your DOM events declaratively, without\r\n// having to worry about render order ... and makes it easy for the view to\r\n// react to specific changes in the state of your models.\r\n\r\n// Creating a Backbone.View creates its initial element outside of the DOM,\r\n// if an existing element is not provided...\r\nexport function View(options) {\r\n this.cid = _.uniqueId('view');\r\n options || (options = {});\r\n _.extend(this, _.pick(options, viewOptions));\r\n this._ensureElement();\r\n this.initialize.apply(this, arguments);\r\n this.delegateEvents();\r\n};\r\n\r\n// Cached regex to split keys for `delegate`.\r\nvar delegateEventSplitter = /^(\\S+)\\s*(.*)$/;\r\n\r\n// List of view options to be merged as properties.\r\nvar viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];\r\n\r\n// Set up all inheritable **Backbone.View** properties and methods.\r\n_.extend(View.prototype, {\r\n\r\n // The default `tagName` of a View's element is `\"div\"`.\r\n tagName: 'div',\r\n\r\n // jQuery delegate for element lookup, scoped to DOM elements within the\r\n // current view. This should be preferred to global lookups where possible.\r\n $: function (selector) {\r\n return this.$el.find(selector);\r\n },\r\n\r\n // Initialize is an empty function by default. Override it with your own\r\n // initialization logic.\r\n initialize: function () { },\r\n\r\n // **render** is the core function that your view should override, in order\r\n // to populate its element (`this.el`), with the appropriate HTML. The\r\n // convention is for **render** to always return `this`.\r\n render: function () {\r\n return this;\r\n },\r\n\r\n // Remove this view by taking the element out of the DOM, and removing any\r\n // applicable Backbone.Events listeners.\r\n remove: function () {\r\n this.$el.remove();\r\n this.stopListening();\r\n return this;\r\n },\r\n\r\n // Change the view's element (`this.el` property), including event\r\n // re-delegation.\r\n setElement: function (element, delegate) {\r\n if (this.$el) this.undelegateEvents();\r\n this.$el = element instanceof $ ? element : $(element);\r\n this.el = this.$el[0];\r\n if (delegate !== false) this.delegateEvents();\r\n return this;\r\n },\r\n\r\n // Set callbacks, where `this.events` is a hash of\r\n //\r\n // *{\"event selector\": \"callback\"}*\r\n //\r\n // {\r\n // 'mousedown .title': 'edit',\r\n // 'click .button': 'save',\r\n // 'click .open': function(e) { ... }\r\n // }\r\n //\r\n // pairs. Callbacks will be bound to the view, with `this` set properly.\r\n // Uses event delegation for efficiency.\r\n // Omitting the selector binds the event to `this.el`.\r\n // This only works for delegate-able events: not `focus`, `blur`, and\r\n // not `change`, `submit`, and `reset` in Internet Explorer.\r\n delegateEvents: function (events) {\r\n if (!(events || (events = _.result(this, 'events')))) return this;\r\n this.undelegateEvents();\r\n for (var key in events) {\r\n var method = events[key];\r\n if (!_.isFunction(method)) method = this[events[key]];\r\n if (!method) continue;\r\n\r\n var match = key.match(delegateEventSplitter);\r\n var eventName = match[1], selector = match[2];\r\n method = _.bind(method, this);\r\n eventName += '.delegateEvents' + this.cid;\r\n if (selector === '') {\r\n this.$el.on(eventName, method);\r\n } else {\r\n this.$el.on(eventName, selector, method);\r\n }\r\n }\r\n return this;\r\n },\r\n\r\n // Clears all callbacks previously bound to the view with `delegateEvents`.\r\n // You usually don't need to use this, but may wish to if you have multiple\r\n // Backbone views attached to the same DOM element.\r\n undelegateEvents: function () {\r\n this.$el.off('.delegateEvents' + this.cid);\r\n return this;\r\n },\r\n\r\n // Ensure that the View has a DOM element to render into.\r\n // If `this.el` is a string, pass it through `$()`, take the first\r\n // matching element, and re-assign it to `el`. Otherwise, create\r\n // an element from the `id`, `className` and `tagName` properties.\r\n _ensureElement: function () {\r\n if (!this.el) {\r\n var attrs = _.extend({}, _.result(this, 'attributes'));\r\n if (this.id) attrs.id = _.result(this, 'id');\r\n if (this.className) attrs['class'] = _.result(this, 'className');\r\n var $el = $('<' + _.result(this, 'tagName') + '>').attr(attrs);\r\n this.setElement($el, false);\r\n } else {\r\n this.setElement(_.result(this, 'el'), false);\r\n }\r\n }\r\n\r\n});\r\n\r\n// Backbone.Router\r\n// ---------------\r\n\r\n// Routers map faux-URLs to actions, and fire events when routes are\r\n// matched. Creating a new one sets its `routes` hash, if not set statically.\r\nexport function Router(options) {\r\n options || (options = {});\r\n if (options.routes) this.routes = options.routes;\r\n this._bindRoutes();\r\n this.initialize.apply(this, arguments);\r\n}\r\n\r\n// Cached regular expressions for matching named param parts and splatted\r\n// parts of route strings.\r\nvar optionalParam = /\\((.*?)\\)/g;\r\nvar namedParam = /(\\(\\?)?:\\w+/g;\r\nvar splatParam = /\\*\\w+/g;\r\nvar escapeRegExp = /[\\-{}\\[\\]+?.,\\\\\\^$|#\\s]/g;\r\n\r\n// Set up all inheritable **Backbone.Router** properties and methods.\r\n_.extend(Router.prototype, {\r\n\r\n // Initialize is an empty function by default. Override it with your own\r\n // initialization logic.\r\n initialize: function () { },\r\n\r\n // Manually bind a single named route to a callback. For example:\r\n //\r\n // this.route('search/:query/p:num', 'search', function(query, num) {\r\n // ...\r\n // });\r\n //\r\n route: function (route, name, callback) {\r\n if (!_.isRegExp(route)) route = this._routeToRegExp(route);\r\n if (_.isFunction(name)) {\r\n callback = name;\r\n name = '';\r\n }\r\n if (!callback) callback = this[name];\r\n var router = this;\r\n history.route(route, function (fragment) {\r\n var args = router._extractParameters(route, fragment);\r\n if (router.execute(callback, args, name) !== false) {\r\n router.trigger.apply(router, ['route:' + name].concat(args));\r\n router.trigger('route', name, args);\r\n history.trigger('route', router, name, args);\r\n }\r\n });\r\n return this;\r\n },\r\n\r\n // Execute a route handler with the provided parameters. This is an\r\n // excellent place to do pre-route setup or post-route cleanup.\r\n execute: function (callback, args, name) {\r\n if (callback) callback.apply(this, args);\r\n },\r\n\r\n // Simple proxy to `Backbone.history` to save a fragment into the history.\r\n navigate: function (fragment, options) {\r\n history.navigate(fragment, options);\r\n return this;\r\n },\r\n\r\n // Bind all defined routes to `Backbone.history`. We have to reverse the\r\n // order of the routes here to support behavior where the most general\r\n // routes can be defined at the bottom of the route map.\r\n _bindRoutes: function () {\r\n if (!this.routes) return;\r\n this.routes = _.result(this, 'routes');\r\n var route, routes = _.keys(this.routes);\r\n while ((route = routes.pop()) != null) {\r\n this.route(route, this.routes[route]);\r\n }\r\n },\r\n\r\n // Convert a route string into a regular expression, suitable for matching\r\n // against the current location hash.\r\n _routeToRegExp: function (route) {\r\n route = route.replace(escapeRegExp, '\\\\$&')\r\n .replace(optionalParam, '(?:$1)?')\r\n .replace(namedParam, function (match, optional) {\r\n return optional ? match : '([^/?]+)';\r\n })\r\n .replace(splatParam, '([^?]*?)');\r\n return new RegExp('^' + route + '(?:\\\\?([\\\\s\\\\S]*))?$');\r\n },\r\n\r\n // Given a route, and a URL fragment that it matches, return the array of\r\n // extracted decoded parameters. Empty or unmatched parameters will be\r\n // treated as `null` to normalize cross-browser behavior.\r\n _extractParameters: function (route, fragment) {\r\n var params = route.exec(fragment).slice(1);\r\n return _.map(params, function (param, i) {\r\n // Don't decode the search params.\r\n if (i === params.length - 1) return param || null;\r\n return param ? decodeURIComponent(param) : null;\r\n });\r\n }\r\n\r\n});\r\n\r\n// Backbone.History\r\n// ----------------\r\n\r\n// Handles cross-browser history management, based on either\r\n// [pushState](http://diveintohtml5.info/history.html) and real URLs, or\r\n// [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)\r\n// and URL fragments. If the browser supports neither (old IE, natch),\r\n// falls back to polling.\r\nexport function History() {\r\n this.handlers = [];\r\n this.checkUrl = _.bind(this.checkUrl, this);\r\n\r\n // Ensure that `History` can be used outside of the browser.\r\n if (typeof window !== 'undefined') {\r\n this.location = window.location;\r\n this.history = window.history;\r\n }\r\n};\r\n\r\n// Cached regex for stripping a leading hash/slash and trailing space.\r\nvar routeStripper = /^[#\\/]|\\s+$/g;\r\n\r\n// Cached regex for stripping leading and trailing slashes.\r\nvar rootStripper = /^\\/+|\\/+$/g;\r\n\r\n// Cached regex for stripping urls of hash.\r\nvar pathStripper = /#.*$/;\r\n\r\n// Has the history handling already been started?\r\nHistory.started = false;\r\n\r\n// Set up all inheritable **Backbone.History** properties and methods.\r\n_.extend(History.prototype, {\r\n\r\n // The default interval to poll for hash changes, if necessary, is\r\n // twenty times a second.\r\n interval: 50,\r\n\r\n // Are we at the app root?\r\n atRoot: function () {\r\n var path = this.location.pathname.replace(/[^\\/]$/, '$&/');\r\n return path === this.root && !this.getSearch();\r\n },\r\n\r\n // Does the pathname match the root?\r\n matchRoot: function () {\r\n var path = this.decodeFragment(this.location.pathname);\r\n var root = path.slice(0, this.root.length - 1) + '/';\r\n return root === this.root;\r\n },\r\n // Unicode characters in `location.pathname` are percent encoded so they're\r\n // decoded for comparison. `%25` should not be decoded since it may be part\r\n // of an encoded parameter.\r\n decodeFragment: function (fragment) {\r\n return decodeURI(fragment.replace(/%25/g, '%2525'));\r\n },\r\n // In IE6, the hash fragment and search params are incorrect if the\r\n // fragment contains `?`.\r\n getSearch: function () {\r\n var match = this.location.href.replace(/#.*/, '').match(/\\?.+/);\r\n return match ? match[0] : '';\r\n },\r\n // Gets the true hash value. Cannot use location.hash directly due to bug\r\n // in Firefox where location.hash will always be decoded.\r\n getHash: function (window) {\r\n var match = (window || this).location.href.match(/#(.*)$/);\r\n return match ? match[1] : '';\r\n },\r\n\r\n // Get the pathname and search params, without the root.\r\n getPath: function () {\r\n var path = this.decodeFragment(\r\n this.location.pathname + this.getSearch()\r\n ).slice(this.root.length - 1);\r\n return path.charAt(0) === '/' ? path.slice(1) : path;\r\n },\r\n\r\n // Get the cross-browser normalized URL fragment from the path or hash.\r\n getFragment: function (fragment) {\r\n if (fragment == null) {\r\n if (this._usePushState || !this._wantsHashChange) {\r\n fragment = this.getPath();\r\n } else {\r\n fragment = this.getHash();\r\n }\r\n }\r\n return fragment.replace(routeStripper, '');\r\n },\r\n\r\n // Start the hash change handling, returning `true` if the current URL matches\r\n // an existing route, and `false` otherwise.\r\n start: function (options) {\r\n if (History.started) throw new Error('Backbone.history has already been started');\r\n History.started = true;\r\n\r\n // Figure out the initial configuration. Do we need an iframe?\r\n // Is pushState desired ... is it available?\r\n this.options = _.extend({ root: '/' }, this.options, options);\r\n this.root = this.options.root;\r\n this._wantsHashChange = this.options.hashChange !== false;\r\n this._hasHashChange = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7);\r\n this._useHashChange = this._wantsHashChange && this._hasHashChange;\r\n this._wantsPushState = !!this.options.pushState;\r\n this._hasPushState = !!(this.history && this.history.pushState);\r\n this._usePushState = this._wantsPushState && this._hasPushState;\r\n this.fragment = this.getFragment();\r\n\r\n // Normalize root to always include a leading and trailing slash.\r\n this.root = ('/' + this.root + '/').replace(rootStripper, '/');\r\n\r\n\r\n\r\n\r\n // Transition from hashChange to pushState or vice versa if both are\r\n // requested.\r\n if (this._wantsHashChange && this._wantsPushState) {\r\n\r\n // If we've started off with a route from a `pushState`-enabled\r\n // browser, but we're currently in a browser that doesn't support it...\r\n if (!this._hasPushState && !this.atRoot()) {\r\n var root = this.root.slice(0, -1) || '/';\r\n this.location.replace(root + '#' + this.getPath());\r\n // Return immediately as browser will do redirect to new url\r\n return true;\r\n\r\n // Or if we've started out with a hash-based route, but we're currently\r\n // in a browser where it could be `pushState`-based instead...\r\n } else if (this._hasPushState && this.atRoot()) {\r\n this.navigate(this.getHash(), { replace: true });\r\n }\r\n\r\n }\r\n\r\n // Proxy an iframe to handle location events if the browser doesn't\r\n // support the `hashchange` event, HTML5 history, or the user wants\r\n // `hashChange` but not `pushState`.\r\n if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) {\r\n this.iframe = document.createElement('iframe');\r\n this.iframe.src = 'javascript:0';\r\n this.iframe.style.display = 'none';\r\n this.iframe.tabIndex = -1;\r\n var body = document.body;\r\n // Using `appendChild` will throw on IE < 9 if the document is not ready.\r\n var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow;\r\n iWindow.document.open();\r\n iWindow.document.close();\r\n iWindow.location.hash = '#' + this.fragment;\r\n }\r\n\r\n // Add a cross-platform `addEventListener` shim for older browsers.\r\n var addEventListener = window.addEventListener || function (eventName, listener) {\r\n return attachEvent('on' + eventName, listener);\r\n };\r\n // Depending on whether we're using pushState or hashes, and whether\r\n // 'onhashchange' is supported, determine how we check the URL state.\r\n if (this._usePushState) {\r\n addEventListener('popstate', this.checkUrl, false);\r\n } else if (this._useHashChange && !this.iframe) {\r\n addEventListener('hashchange', this.checkUrl, false);\r\n } else if (this._wantsHashChange) {\r\n this._checkUrlInterval = setInterval(this.checkUrl, this.interval);\r\n }\r\n if (!this.options.silent) return this.loadUrl();\r\n },\r\n\r\n // Disable Backbone.history, perhaps temporarily. Not useful in a real app,\r\n // but possibly useful for unit testing Routers.\r\n stop: function () {\r\n // Add a cross-platform `removeEventListener` shim for older browsers.\r\n var removeEventListener = window.removeEventListener || function (eventName, listener) {\r\n return detachEvent('on' + eventName, listener);\r\n };\r\n // Remove window listeners.\r\n if (this._usePushState) {\r\n removeEventListener('popstate', this.checkUrl, false);\r\n } else if (this._useHashChange && !this.iframe) {\r\n removeEventListener('hashchange', this.checkUrl, false);\r\n }\r\n // Clean up the iframe if necessary.\r\n if (this.iframe) {\r\n document.body.removeChild(this.iframe);\r\n this.iframe = null;\r\n }\r\n // Some environments will throw when clearing an undefined interval.\r\n if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);\r\n History.started = false;\r\n },\r\n\r\n // Add a route to be tested when the fragment changes. Routes added later\r\n // may override previous routes.\r\n route: function (route, callback) {\r\n this.handlers.unshift({ route: route, callback: callback });\r\n },\r\n\r\n // Checks the current URL to see if it has changed, and if it has,\r\n // calls `loadUrl`, normalizing across the hidden iframe.\r\n checkUrl: function (e) {\r\n var current = this.getFragment();\r\n // If the user pressed the back button, the iframe's hash will have\r\n // changed and we should use that for comparison.\r\n if (current === this.fragment && this.iframe) {\r\n current = this.getHash(this.iframe.contentWindow);\r\n }\r\n if (current === this.fragment) return false;\r\n if (this.iframe) this.navigate(current);\r\n this.loadUrl();\r\n },\r\n\r\n // Attempt to load the current URL fragment. If a route succeeds with a\r\n // match, returns `true`. If no defined routes matches the fragment,\r\n // returns `false`.\r\n loadUrl: function (fragment) {\r\n // If the root doesn't match, no routes can match either.\r\n if (!this.matchRoot()) return false;\r\n fragment = this.fragment = this.getFragment(fragment);\r\n return _.some(this.handlers, function (handler) {\r\n if (handler.route.test(fragment)) {\r\n handler.callback(fragment);\r\n return true;\r\n }\r\n });\r\n },\r\n\r\n // Save a fragment into the hash history, or replace the URL state if the\r\n // 'replace' option is passed. You are responsible for properly URL-encoding\r\n // the fragment in advance.\r\n //\r\n // The options object can contain `trigger: true` if you wish to have the\r\n // route callback be fired (not usually desirable), or `replace: true`, if\r\n // you wish to modify the current URL without adding an entry to the history.\r\n navigate: function (fragment, options) {\r\n if (!History.started) return false;\r\n if (!options || options === true) options = { trigger: !!options };\r\n\r\n // Normalize the fragment.\r\n fragment = this.getFragment(fragment || '');\r\n\r\n // Don't include a trailing slash on the root.\r\n var root = this.root;\r\n if (fragment === '' || fragment.charAt(0) === '?') {\r\n root = root.slice(0, -1) || '/';\r\n }\r\n var url = root + fragment;\r\n // Strip the hash and decode for matching.\r\n fragment = this.decodeFragment(fragment.replace(pathStripper, ''));\r\n\r\n if (this.fragment === fragment) return;\r\n this.fragment = fragment;\r\n\r\n\r\n // If pushState is available, we use it to set the fragment as a real URL.\r\n if (this._usePushState) {\r\n this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);\r\n\r\n // If hash changes haven't been explicitly disabled, update the hash\r\n // fragment to store history.\r\n } else if (this._wantsHashChange) {\r\n this._updateHash(this.location, fragment, options.replace);\r\n if (this.iframe && (fragment !== this.getHash(this.iframe.contentWindow))) {\r\n var iWindow = this.iframe.contentWindow;\r\n // Opening and closing the iframe tricks IE7 and earlier to push a\r\n // history entry on hash-tag change. When replace is true, we don't\r\n // want this.\r\n if (!options.replace) {\r\n iWindow.document.open();\r\n iWindow.document.close();\r\n }\r\n\r\n this._updateHash(iWindow.location, fragment, options.replace);\r\n }\r\n\r\n // If you've told us that you explicitly don't want fallback hashchange-\r\n // based history, then `navigate` becomes a page refresh.\r\n } else {\r\n return this.location.assign(url);\r\n }\r\n if (options.trigger) return this.loadUrl(fragment);\r\n },\r\n\r\n // Update the hash location, either replacing the current entry, or adding\r\n // a new one to the browser history.\r\n _updateHash: function (location, fragment, replace) {\r\n if (replace) {\r\n var href = location.href.replace(/(javascript:|#).*$/, '');\r\n location.replace(href + '#' + fragment);\r\n } else {\r\n // Some browsers require that `hash` contains a leading #.\r\n location.hash = '#' + fragment;\r\n }\r\n }\r\n\r\n});\r\n\r\n// Create the default Backbone.history.\r\nexport const history = new History;\r\n\r\n\n\n\n/** WEBPACK FOOTER **\n ** ./~/source-map-loader!./src/backbone.js\n **/","module.exports = __WEBPACK_EXTERNAL_MODULE_31__;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** external {\"commonjs\":\"underscore\",\"commonjs2\":\"underscore\",\"amd\":\"underscore\",\"root\":\"_\"}\n ** module id = 31\n ** module chunks = 0\n **/","module.exports = __WEBPACK_EXTERNAL_MODULE_32__;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** external {\"commonjs\":\"jquery\",\"commonjs2\":\"jquery\",\"amd\":\"jquery\",\"root\":\"$\"}\n ** module id = 32\n ** module chunks = 0\n **/","import { sync, errorPromise, urlError, SyncOptions, LazyValue } from './sync'\r\n\r\nimport * as _ from 'underscore'\r\nimport * as Backbone from './backbone'\r\n\r\nimport { define, Model, Collection, tools } from '../type-r/src'\r\nconst { defaults } = tools;\r\n\r\nconst transactionalProto = tools.getBaseClass( Model ).prototype;\r\n\r\ninterface RestOptions extends SyncOptions {\r\n wait? : boolean\r\n patch? : boolean\r\n reset? : boolean\r\n}\r\n\r\n@define({\r\n itemEvents : {\r\n destroy( model ){ this.remove( model ); }\r\n } \r\n})\r\nexport class RestCollection extends Collection {\r\n model : typeof RestModel\r\n url() : string { return this.model.prototype.urlRoot || ''; }\r\n\r\n _invalidate( options : { validate? : boolean } ) : boolean {\r\n var error;\r\n if( options.validate && ( error = this.validationError ) ){\r\n this.trigger( 'invalid', this, error, _.extend( { validationError : error }, options ) );\r\n return true;\r\n }\r\n }\r\n\r\n // Fetch the default set of models for this collection, resetting the\r\n // collection when they arrive. If `reset: true` is passed, the response\r\n // data will be passed through the `reset` method instead of `set`.\r\n fetch( options : RestOptions ){\r\n options = _.extend( { parse : true }, options );\r\n var success = options.success;\r\n var collection = this;\r\n options.success = function( resp ){\r\n var method = options.reset ? 'reset' : 'set';\r\n collection[ method ]( resp, options );\r\n if( collection._invalidate( options ) ) return false;\r\n\r\n if( success ) success.call( options.context, collection, resp, options );\r\n collection.trigger( 'sync', collection, resp, options );\r\n };\r\n\r\n wrapError( this, options );\r\n return _sync( 'read', this, options );\r\n }\r\n\r\n create( a_model, options : any = {} ){\r\n const model : RestModel = a_model instanceof RestModel ?\r\n a_model :\r\n this.model.create( a_model, options, this );\r\n\r\n // Hack! For the situation when model instance is given, aquire it. \r\n model._owner || ( model._owner = this );\r\n\r\n options.wait || this.add([ model ], options );\r\n\r\n var collection = this;\r\n var success = options.success;\r\n options.success = ( model, resp, callbackOpts ) =>{\r\n if( options.wait ) this.add( [ model ], defaults({ parse : false }, callbackOpts ) );\r\n if( success ) success.call( callbackOpts.context, model, resp, callbackOpts );\r\n };\r\n\r\n model.save( null, options );\r\n return model;\r\n }\r\n\r\n // Proxy `Backbone.sync` by default -- but override this if you need\r\n // custom syncing semantics for *this* particular model.\r\n sync(){\r\n return sync.apply( this, arguments );\r\n }\r\n};\r\n\r\n@define({\r\n collection : RestCollection,\r\n urlRoot : ''\r\n})\r\nexport class RestModel extends Model {\r\n urlRoot : string\r\n\r\n /** @private */\r\n _invalidate( options : { validate? : boolean } ) : boolean {\r\n var error;\r\n if( options.validate && ( error = this.validationError ) ){\r\n triggerAndBubble( this, 'invalid', this, error, _.extend( { validationError : error }, options ) );\r\n return true;\r\n }\r\n }\r\n\r\n // Fetch the model from the server, merging the response with the model's\r\n // local attributes. Any changed attributes will trigger a \"change\" event.\r\n fetch( options : RestOptions ){\r\n options = _.extend( { parse : true }, options );\r\n var model = this;\r\n var success = options.success;\r\n options.success = function( serverAttrs ){\r\n model.set( serverAttrs, options );\r\n if( model._invalidate( options ) ) return false;\r\n\r\n if( success ) success.call( options.context, model, serverAttrs, options );\r\n triggerAndBubble( model, 'sync', model, serverAttrs, options );\r\n };\r\n\r\n wrapError( this, options );\r\n return _sync( 'read', this, options );\r\n }\r\n\r\n // Proxy `Backbone.sync` by default -- but override this if you need\r\n // custom syncing semantics for *this* particular model.\r\n sync(){\r\n return sync.apply( this, arguments );\r\n }\r\n\r\n // Set a hash of model attributes, and sync the model to the server.\r\n // If the server returns an attributes hash that differs, the model's\r\n // state will be `set` again.\r\n save( attrs? : {}, options? : RestOptions )\r\n save( key : string, value : any, options? : RestOptions )\r\n save( key, val, a_options? : RestOptions ){\r\n // Handle both `\"key\", value` and `{key: value}` -style arguments.\r\n let attrs, originalOptions;\r\n\r\n if( key == null || typeof key === 'object' ){\r\n attrs = key;\r\n originalOptions = val || {};\r\n }\r\n else{\r\n (attrs = {})[ key ] = val;\r\n originalOptions = a_options || {};\r\n }\r\n\r\n const options = _.extend( { validate : true, parse : true }, originalOptions ),\r\n wait = options.wait;\r\n\r\n // If we're not waiting and attributes exist, save acts as\r\n // `set(attr).save(null, opts)` with validation. Otherwise, check if\r\n // the model will be valid when the attributes, if any, are set.\r\n if( attrs && !wait ){\r\n this.set( attrs, originalOptions );\r\n }\r\n\r\n if( this._invalidate( originalOptions ) ){\r\n if( attrs && wait ) this.set( attrs, originalOptions );\r\n return errorPromise( this.validationError );\r\n }\r\n\r\n // After a successful server-side save, the client is (optionally)\r\n // updated with the server-side state.\r\n var model = this;\r\n var success = options.success;\r\n var attributes = this.attributes;\r\n options.success = serverAttrs => {\r\n // Ensure attributes are restored during synchronous saves.\r\n model.attributes = attributes;\r\n if( wait ) serverAttrs = _.extend( {}, attrs, serverAttrs );\r\n\r\n if( serverAttrs ){\r\n // When server sends string, polimorphyc Model set screws up.\r\n transactionalProto.set.call( this, serverAttrs, options );\r\n if( model._invalidate( options ) ) return false;\r\n }\r\n\r\n if( success ) success.call( options.context, model, serverAttrs, options );\r\n triggerAndBubble( model, 'sync', model, serverAttrs, options );\r\n };\r\n\r\n wrapError( this, options );\r\n\r\n // Set temporary attributes if `{wait: true}` to properly find new ids.\r\n if( attrs && wait ) this.attributes = _.extend( {}, attributes, attrs );\r\n\r\n var method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');\r\n if( method === 'patch' && !options.attrs ) options.attrs = attrs;\r\n var xhr = _sync( method, this, options );\r\n\r\n // Restore attributes.\r\n this.attributes = attributes;\r\n\r\n return xhr;\r\n }\r\n\r\n // Destroy this model on the server if it was already persisted.\r\n // Optimistically removes the model from its collection, if it has one.\r\n // If `wait: true` is passed, waits for the server to respond before removal.\r\n destroy( options : RestOptions ){\r\n options = options ? _.clone( options ) : {};\r\n var model = this;\r\n var success = options.success;\r\n var wait = options.wait;\r\n\r\n var destroy = function(){\r\n model.stopListening(); // TBD: figure out whenever we need to dispose the model.\r\n model.trigger( 'destroy', model, model.collection, options );\r\n };\r\n\r\n options.success = function( resp ){\r\n if( wait ) destroy();\r\n if( success ) success.call( options.context, model, resp, options );\r\n if( !model.isNew() ) triggerAndBubble( model, 'sync', model, resp, options );\r\n };\r\n\r\n var xhr = false;\r\n if( this.isNew() ){\r\n _.defer( options.success );\r\n }\r\n else{\r\n wrapError( this, options );\r\n xhr = _sync( 'delete', this, options );\r\n }\r\n if( !wait ) destroy();\r\n return xhr;\r\n }\r\n\r\n // Default URL for the model's representation on the server -- if you're\r\n // using Backbone's restful methods, override this to change the endpoint\r\n // that will be called.\r\n url(){\r\n var base =\r\n _.result( this, 'urlRoot' ) ||\r\n _.result( this.collection, 'url' ) ||\r\n urlError();\r\n if( this.isNew() ) return base;\r\n var id = this.get( this.idAttribute );\r\n return base.replace( /[^\\/]$/, '$&/' ) + encodeURIComponent( id );\r\n }\r\n}\r\n\r\nfunction _sync( method, _this, options ){\r\n // Abort and pending IO request. Just one is allowed at the time.\r\n _this._xhr && _this._xhr.abort && _this._xhr.abort();\r\n const xhr = _this._xhr = _this.sync( method, _this, options );\r\n xhr && xhr.always && xhr.always( function(){ _this.xhr = void 0; });\r\n return xhr;\r\n}\r\n\r\n// Wrap an optional error callback with a fallback error event.\r\nfunction wrapError( model, options ){\r\n var error = options.error;\r\n options.error = function( resp ){\r\n if( error ) error.call( options.context, model, resp, options );\r\n triggerAndBubble( model, 'error', model, resp, options );\r\n };\r\n}\r\n\r\nfunction triggerAndBubble( model : RestModel, ...args : any[] ){\r\n model.trigger.apply( model, args );\r\n const { collection } = model;\r\n collection && collection.trigger.apply( collection, args ); \r\n}\n\n\n/** WEBPACK FOOTER **\n ** ./src/rest.ts\n **/","/**\r\n * Backbone.js 1.2.3 REST implementation\r\n * (c) 2010-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\r\n * Backbone may be freely distributed under the MIT license.\r\n *\r\n * With validation patches - NestedTypes validation semantic is applied. (c) Vlad Balin, 2015.\r\n */\r\nimport * as _ from 'underscore'\r\nimport * as Backbone from './backbone'\r\n\r\nimport { tools } from '../type-r/src'\r\nconst { defaults } = tools;\r\n\r\nexport type LazyValue< T > = () => T | T;\r\n\r\n// Map from CRUD to HTTP for our default `Backbone.sync` implementation.\r\nexport type Method = 'create' | 'update' | 'patch' | 'delete' | 'read' \r\n\r\nexport interface Restful {\r\n trigger( event : string, model, xhr, options )\r\n collection? : { trigger( event : string, model, xhr, options ) }\r\n toJSON( options : any ) : {}\r\n}\r\n\r\nexport interface SyncOptions {\r\n url? : LazyValue< string >\r\n data? : any\r\n emulateJSON? : boolean\r\n emulateHTTP? : boolean\r\n attrs? : {}\r\n beforeSend? : ( xhr ) => any\r\n\r\n success? : ( resp : any ) => void\r\n error? : ( xhr?, textStatus?, errorThrown? ) => void\r\n\r\n textStatus? : string\r\n errorThrown? : any\r\n xhr? : any\r\n context? : {}\r\n}\r\n\r\nconst methodMap = {\r\n 'create' : 'POST',\r\n 'update' : 'PUT',\r\n 'patch' : 'PATCH',\r\n 'delete' : 'DELETE',\r\n 'read' : 'GET'\r\n};\r\n\r\n\r\nexport let $ = Backbone.$;\r\n \r\nexport let errorPromise = function( error ){\r\n var x = $.Deferred();\r\n x.reject( error );\r\n return x;\r\n}\r\n\r\n// Set the default implementation of `Backbone.ajax` to proxy through to `$`.\r\n// Override this if you'd like to use a different library.\r\nexport let ajax : ( options : {} ) => any = function(){\r\n return $.ajax.apply( $, arguments );\r\n}\r\n\r\n // Backbone.sync\r\n // -------------\r\n\r\n // Override this function to change the manner in which Backbone persists\r\n // models to the server. You will be passed the type of request, and the\r\n // model in question. By default, makes a RESTful Ajax request\r\n // to the model's `url()`. Some possible customizations could be:\r\n //\r\n // * Use `setTimeout` to batch rapid-fire updates into a single request.\r\n // * Send up the models as XML instead of JSON.\r\n // * Persist models via WebSockets instead of Ajax.\r\n //\r\n // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests\r\n // as `POST`, with a `_method` parameter containing the true HTTP method,\r\n // as well as all requests with the body as `application/x-www-form-urlencoded`\r\n // instead of `application/json` with the model in a param named `model`.\r\n // Useful when interfacing with server-side languages like **PHP** that make\r\n // it difficult to read the body of `PUT` requests.\r\nexport let sync = function( method : Method, model : Restful, options : SyncOptions = {} ){\r\n var type = methodMap[ method ];\r\n // Default options, unless specified.\r\n defaults( options, {\r\n emulateHTTP: Backbone.emulateHTTP,\r\n emulateJSON: Backbone.emulateJSON\r\n });\r\n\r\n // Default JSON-request options.\r\n var params : any = { type : type, dataType : 'json' };\r\n\r\n // Ensure that we have a URL.\r\n if( !options.url ){\r\n params.url = _.result( model, 'url' ) || urlError();\r\n }\r\n\r\n // Ensure that we have the appropriate request data.\r\n if( options.data == null && model && (method === 'create' || method === 'update' || method === 'patch') ){\r\n params.contentType = 'application/json';\r\n params.data = JSON.stringify( options.attrs || model.toJSON( options ) );\r\n }\r\n\r\n // For older servers, emulate JSON by encoding the request into an HTML-form.\r\n if( options.emulateJSON ){\r\n params.contentType = 'application/x-www-form-urlencoded';\r\n params.data = params.data ? { model : params.data } : {};\r\n }\r\n\r\n // For older servers, emulate HTTP by mimicking the HTTP method with `_method`\r\n // And an `X-HTTP-Method-Override` header.\r\n if( options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH') ){\r\n params.type = 'POST';\r\n if( options.emulateJSON ) params.data._method = type;\r\n var beforeSend = options.beforeSend;\r\n options.beforeSend = function( xhr ){\r\n xhr.setRequestHeader( 'X-HTTP-Method-Override', type );\r\n if( beforeSend ) return beforeSend.apply( this, arguments );\r\n };\r\n }\r\n\r\n // Don't process data on a non-GET request.\r\n if( params.type !== 'GET' && !options.emulateJSON ){\r\n params.processData = false;\r\n }\r\n\r\n // Pass along `textStatus` and `errorThrown` from jQuery.\r\n var error = options.error;\r\n options.error = function( xhr, textStatus, errorThrown ){\r\n options.textStatus = textStatus;\r\n options.errorThrown = errorThrown;\r\n if( error ) error.call( options.context, xhr, textStatus, errorThrown );\r\n };\r\n\r\n // Make the request, allowing the user to override any Ajax options.\r\n var xhr = options.xhr = ajax( _.extend( params, options ) );\r\n model.trigger( 'request', model, xhr, options );\r\n model.collection && model.collection.trigger( 'request', model, xhr, options );\r\n return xhr;\r\n}\r\n\r\n\r\n// Throw an error when a URL is needed, and none is supplied.\r\nexport function urlError(){\r\n throw new Error( 'A \"url\" property or function must be specified' );\r\n}\n\n\n/** WEBPACK FOOTER **\n ** ./src/sync.ts\n **/","import * as _ from 'underscore'\r\n\r\nvar slice = Array.prototype.slice;\r\n\r\nexport const UnderscoreModel = {\r\n pick( ...args : any[] ){\r\n return _.pick( this, args );\r\n },\r\n\r\n escape( attr ){\r\n return _.escape( this[ attr ] );\r\n },\r\n\r\n matches( attrs ){\r\n return !!_.iteratee( attrs, this )( this );\r\n },\r\n\r\n omit( ...keys : string[] ) : {} {\r\n return this.mapObject( ( value, key ) => {\r\n if( keys.indexOf( key ) < 0 ){\r\n return value;\r\n }\r\n });\r\n },\r\n\r\n invert(){\r\n const inverted = {};\r\n this.each( ( value, key ) => inverted[ value ] = key );\r\n return inverted;\r\n },\r\n\r\n pairs(){\r\n return this.map( ( value, key ) => [ key, value ] );\r\n },\r\n\r\n isEmpty(){\r\n return !this.values().length;\r\n },\r\n\r\n chain(){\r\n return _.chain( this.mapObject( x => x ) );\r\n }\r\n};\r\n\r\nexport const UnderscoreCollection = {\r\n where(attrs, first) {\r\n return this[first ? 'find' : 'filter'](attrs);\r\n },\r\n\r\n findWhere(attrs) {\r\n return this.where(attrs, true);\r\n }\r\n};\r\n\r\naddUnderscoreMethods( UnderscoreCollection, 'models', {\r\n forEach : 3, each : 3, map : 3, collect : 3, reduce : 4,\r\n foldl : 4, inject : 4, reduceRight : 4, foldr : 4, find : 3, findIndex : 3, findLastIndex : 3, detect : 3, filter : 3,\r\n select : 3, reject : 3, every : 3, all : 3, some : 3, any : 3, include : 3, includes : 3,\r\n contains : 3, invoke : 0, max : 3, min : 3, toArray : 1, size : 1, first : 3,\r\n head : 3, take : 3, initial : 3, rest : 3, tail : 3, drop : 3, last : 3,\r\n without : 0, difference : 0, indexOf : 3, shuffle : 1, lastIndexOf : 3,\r\n isEmpty : 1, chain : 1, sample : 3, partition : 3, groupBy : 3, countBy : 3,\r\n sortBy : 3, indexBy : 3\r\n});\r\n\r\n\r\nfunction addUnderscoreMethods(Mixin, attribute, methods ) {\r\n _.each(methods, function(length, method) {\r\n if (_[method]) Mixin[method] = addMethod(length, method, attribute);\r\n });\r\n}\r\n\r\n// Proxy Backbone class methods to Underscore functions, wrapping the model's\r\n// `attributes` object or collection's `models` array behind the scenes.\r\n//\r\n// collection.filter(function(model) { return model.get('age') > 10 });\r\n// collection.each(this.addView);\r\n//\r\n// `Function#apply` can be slow so we use the method's arg count, if we know it.\r\nfunction addMethod(length, method, attribute) {\r\n switch (length) {\r\n case 1: return function() {\r\n return _[method](this[attribute]);\r\n };\r\n case 2: return function(value) {\r\n return _[method](this[attribute], value);\r\n };\r\n case 3: return function(iteratee, context) {\r\n var value = this[ attribute ],\r\n callback = cb(iteratee, this);\r\n\r\n return arguments.length > 1 ?\r\n _[method]( value, callback, context)\r\n : _[method]( value, callback );\r\n };\r\n case 4: return function(iteratee, defaultVal, context) {\r\n var value = this[ attribute ],\r\n callback = cb(iteratee, this);\r\n\r\n return arguments.length > 1 ?\r\n _[method]( value, callback, defaultVal, context )\r\n : _[method](value, callback );\r\n };\r\n default: return function() {\r\n var args = slice.call(arguments);\r\n args.unshift(this[attribute]);\r\n return _[method].apply(_, args);\r\n };\r\n }\r\n}\r\n\r\n// Support `collection.sortBy('attr')` and `collection.findWhere({id: 1})`.\r\nfunction cb(iteratee, instance) {\r\n switch( typeof iteratee ){\r\n case 'function' : return iteratee;\r\n case 'string' : return model => model.get( iteratee );\r\n case 'object' :\r\n if( !(iteratee instanceof instance.model )) return _.matches( iteratee ); \r\n }\r\n\r\n return iteratee;\r\n}\r\n\n\n\n/** WEBPACK FOOTER **\n ** ./src/underscore-mixin.ts\n **/","import * as Backbone from './backbone'\r\nimport * as _ from 'underscore'\r\nimport { mixins, define, Store } from '../type-r/src'\r\nimport { RestModel, RestCollection } from './rest'\r\n\r\nconst { $ } = Backbone;\r\n\r\n@define({})\r\n@mixins( Store )\r\nexport class RestStore extends RestModel {}\r\n\r\n@define({})\r\nexport class LazyStore extends RestStore {\r\n _resolved : {} = {}\r\n\r\n initialize(){\r\n this.each( ( element, name ) => {\r\n if( !element ) return;\r\n\r\n element.store = this;\r\n\r\n var fetch = element.fetch;\r\n\r\n if( fetch ){\r\n const self = this;\r\n element.fetch = function() {\r\n return self._resolved[ name ] = fetch.apply( this, arguments );\r\n }\r\n }\r\n\r\n if( element instanceof RestCollection && element.length ){\r\n this._resolved[name] = true;\r\n }\r\n });\r\n }\r\n\r\n // fetch specified items, or all items if called without arguments.\r\n // returns jquery promise\r\n fetch( ...args : string[] ) : {} {\r\n var xhr = [],\r\n objsToFetch = args.length ? args : this.keys();\r\n\r\n for( let name of objsToFetch ){\r\n var attr = this.attributes[name];\r\n attr && attr.fetch && xhr.push( attr.fetch() );\r\n }\r\n\r\n return $ && $.when && $.when.apply( Backbone.$, xhr );\r\n }\r\n\r\n // fetch specified items, or all items if called without arguments.\r\n // returns first jquery promise.\r\n fetchOnce( ...args : string[] ) : {} {\r\n var xhr = [],\r\n self = this,\r\n objsToFetch = args.length ? args : this.keys();\r\n\r\n for( let name of objsToFetch ){\r\n var attr = self.attributes[ name ];\r\n xhr.push( self._resolved[ name ] || attr && attr.fetch && attr.fetch());\r\n }\r\n\r\n return $ && $.when && $.when.apply( Backbone.$, xhr );\r\n }\r\n\r\n clear( ...args : string[] ) : this {\r\n var objsToClear = args.length ? args : this.keys();\r\n\r\n for( let name of objsToClear ){\r\n var element = this.attributes[ name ];\r\n\r\n if( element instanceof RestCollection ){\r\n element.reset();\r\n }\r\n else if( element instanceof Store ){\r\n element.clear();\r\n }\r\n else if( element instanceof RestModel ){\r\n element.set( element.defaults() )\r\n }\r\n\r\n this._resolved[ name ] = false;\r\n }\r\n\r\n return this;\r\n }\r\n\r\n static define( props, staticProps ){\r\n var attributes = props.defaults || props.attributes;\r\n\r\n // add automatic fetching on first element's access\r\n _.each( attributes, ( Type : Function, name ) => {\r\n if( Type.has ){\r\n attributes[name] = Type.has\r\n .get( function( value ){\r\n if( !this._resolved[name] ) {\r\n value.fetch && value.fetch();\r\n }\r\n\r\n return value;\r\n })\r\n .set( function( value ){\r\n if( !value.length ){\r\n const resolved = this._resolved || ( this._resolved = {} ); \r\n resolved[name] = false;\r\n }\r\n \r\n return value;\r\n })\r\n } \r\n });\r\n\r\n return RestModel.define.call( this, props, staticProps );\r\n }\r\n} \r\n \n\n\n/** WEBPACK FOOTER **\n ** ./src/rest-store.ts\n **/"],"sourceRoot":""} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..94305df --- /dev/null +++ b/package-lock.json @@ -0,0 +1,611 @@ +{ + "name": "nestedtypes", + "version": "2.1.4", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@babel/code-frame": { + "version": "7.0.0-rc.1", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0-rc.1.tgz", + "integrity": "sha512-qhQo3GqwqMUv03SxxjcEkWtlkEDvFYrBKbJUn4Dtd9amC2cLkJ3me4iYUVSBbVXWbfbVRalEeVBHzX4aQYKnBg==", + "dev": true, + "requires": { + "@babel/highlight": "7.0.0-rc.1" + } + }, + "@babel/highlight": { + "version": "7.0.0-rc.1", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.0.0-rc.1.tgz", + "integrity": "sha512-5PgPDV6F5s69XNznTcP0za3qH7qgBkr9DVQTXfZtpF+3iEyuIZB1Mjxu52F5CFxgzQUQJoBYHVxtH4Itdb5MgA==", + "dev": true, + "requires": { + "chalk": "2.4.1", + "esutils": "2.0.2", + "js-tokens": "3.0.2" + } + }, + "@types/estree": { + "version": "0.0.39", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz", + "integrity": "sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==", + "dev": true + }, + "@types/jquery": { + "version": "2.0.49", + "resolved": "https://registry.npmjs.org/@types/jquery/-/jquery-2.0.49.tgz", + "integrity": "sha512-/9xLnYmohN/vD2gDnLS4cym8TUmrJu7DvZa/LELKzZjdPsvWVJiedsdu2SXNtb/DA7FGimqL2g0IoyhbNKLl8g==", + "dev": true + }, + "@types/node": { + "version": "10.7.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-10.7.0.tgz", + "integrity": "sha512-dmYIvoQEZWnyQfgrwPCoxztv/93NYQGEiOoQhuI56rJahv9de6Q2apZl3bufV46YJ0OAXdaktIuw4RIRl4DTeA==", + "dev": true + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "1.9.2" + } + }, + "arr-diff": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-2.0.0.tgz", + "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=", + "dev": true, + "requires": { + "arr-flatten": "1.1.0" + } + }, + "arr-flatten": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/arr-flatten/-/arr-flatten-1.1.0.tgz", + "integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==", + "dev": true + }, + "array-unique": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz", + "integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=", + "dev": true + }, + "atob": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/atob/-/atob-2.0.3.tgz", + "integrity": "sha1-GcenYEc3dEaPILLS0DNyrX1Mv10=", + "dev": true + }, + "braces": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/braces/-/braces-1.8.5.tgz", + "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=", + "dev": true, + "requires": { + "expand-range": "1.8.2", + "preserve": "0.2.0", + "repeat-element": "1.1.2" + } + }, + "builtin-modules": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-2.0.0.tgz", + "integrity": "sha512-3U5kUA5VPsRUA3nofm/BXX7GVHKfxz0hOBAPxXrIvHzlDRkQVqEn6yi8QJegxl4LzOHLdvb7XF5dVawa/VVYBg==", + "dev": true + }, + "chalk": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", + "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "dev": true, + "requires": { + "ansi-styles": "3.2.1", + "escape-string-regexp": "1.0.5", + "supports-color": "5.4.0" + } + }, + "color-convert": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.2.tgz", + "integrity": "sha512-3NUJZdhMhcdPn8vJ9v2UQJoH0qqoGUkYTgFEPZaPjEtwmmKUfNV46zZmgB2M5M4DCEQHMaCfWHCxiBflLm04Tg==", + "dev": true, + "requires": { + "color-name": "1.1.1" + } + }, + "color-name": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.1.tgz", + "integrity": "sha1-SxQVMEz1ACjqgWQ2Q72C6gWANok=", + "dev": true + }, + "commander": { + "version": "2.16.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.16.0.tgz", + "integrity": "sha512-sVXqklSaotK9at437sFlFpyOcJonxe0yST/AG9DkQKUdIE6IqGIMv4SfAQSKaJbSdVEJYItASCrBiVQHq1HQew==", + "dev": true + }, + "decode-uri-component": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz", + "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=", + "dev": true + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "estree-walker": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-0.3.1.tgz", + "integrity": "sha1-5rGlHPcpJSTnI3wxLl/mZgwc4ao=", + "dev": true + }, + "esutils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", + "dev": true + }, + "expand-brackets": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-0.1.5.tgz", + "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", + "dev": true, + "requires": { + "is-posix-bracket": "0.1.1" + } + }, + "expand-range": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/expand-range/-/expand-range-1.8.2.tgz", + "integrity": "sha1-opnv/TNf4nIeuujiV+x5ZE/IUzc=", + "dev": true, + "requires": { + "fill-range": "2.2.3" + } + }, + "extglob": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-0.3.2.tgz", + "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", + "dev": true, + "requires": { + "is-extglob": "1.0.0" + } + }, + "filename-regex": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/filename-regex/-/filename-regex-2.0.1.tgz", + "integrity": "sha1-wcS5vuPglyXdsQa3XB4wH+LxiyY=", + "dev": true + }, + "fill-range": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-2.2.3.tgz", + "integrity": "sha1-ULd9/X5Gm8dJJHCWNpn+eoSFpyM=", + "dev": true, + "requires": { + "is-number": "2.1.0", + "isobject": "2.1.0", + "randomatic": "1.1.7", + "repeat-element": "1.1.2", + "repeat-string": "1.6.1" + } + }, + "for-in": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", + "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=", + "dev": true + }, + "for-own": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/for-own/-/for-own-0.1.5.tgz", + "integrity": "sha1-UmXGgaTylNq78XyVCbZ2OqhFEM4=", + "dev": true, + "requires": { + "for-in": "1.0.2" + } + }, + "glob-base": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/glob-base/-/glob-base-0.3.0.tgz", + "integrity": "sha1-27Fk9iIbHAscz4Kuoyi0l98Oo8Q=", + "dev": true, + "requires": { + "glob-parent": "2.0.0", + "is-glob": "2.0.1" + } + }, + "glob-parent": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-2.0.0.tgz", + "integrity": "sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg=", + "dev": true, + "requires": { + "is-glob": "2.0.1" + } + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true + }, + "is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", + "dev": true + }, + "is-dotfile": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/is-dotfile/-/is-dotfile-1.0.3.tgz", + "integrity": "sha1-pqLzL/0t+wT1yiXs0Pa4PPeYoeE=", + "dev": true + }, + "is-equal-shallow": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/is-equal-shallow/-/is-equal-shallow-0.1.3.tgz", + "integrity": "sha1-IjgJj8Ih3gvPpdnqxMRdY4qhxTQ=", + "dev": true, + "requires": { + "is-primitive": "2.0.0" + } + }, + "is-extendable": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", + "integrity": "sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=", + "dev": true + }, + "is-extglob": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-1.0.0.tgz", + "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=", + "dev": true + }, + "is-glob": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-2.0.1.tgz", + "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", + "dev": true, + "requires": { + "is-extglob": "1.0.0" + } + }, + "is-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", + "integrity": "sha1-Mlj7afeMFNW4FdZkM2tM/7ZEFZE=", + "dev": true + }, + "is-number": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-2.1.0.tgz", + "integrity": "sha1-Afy7s5NGOlSPL0ZszhbezknbkI8=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + } + }, + "is-posix-bracket": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz", + "integrity": "sha1-MzTceXdDaOkvAW5vvAqI9c1ua8Q=", + "dev": true + }, + "is-primitive": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-primitive/-/is-primitive-2.0.0.tgz", + "integrity": "sha1-IHurkWOEmcB7Kt8kCkGochADRXU=", + "dev": true + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "dev": true + }, + "isobject": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", + "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", + "dev": true, + "requires": { + "isarray": "1.0.0" + } + }, + "jquery": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/jquery/-/jquery-3.3.1.tgz", + "integrity": "sha512-Ubldcmxp5np52/ENotGxlLe6aGMvmF4R8S6tZjsP6Knsaxd/xp3Zrh50cG93lR6nPXyUFwzN3ZSOQI0wRJNdGg==", + "dev": true + }, + "js-tokens": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", + "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=", + "dev": true + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + }, + "micromatch": { + "version": "2.3.11", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-2.3.11.tgz", + "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=", + "dev": true, + "requires": { + "arr-diff": "2.0.0", + "array-unique": "0.2.1", + "braces": "1.8.5", + "expand-brackets": "0.1.5", + "extglob": "0.3.2", + "filename-regex": "2.0.1", + "is-extglob": "1.0.0", + "is-glob": "2.0.1", + "kind-of": "3.2.2", + "normalize-path": "2.1.1", + "object.omit": "2.0.1", + "parse-glob": "3.0.4", + "regex-cache": "0.4.4" + } + }, + "normalize-path": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", + "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", + "dev": true, + "requires": { + "remove-trailing-separator": "1.1.0" + } + }, + "object.omit": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/object.omit/-/object.omit-2.0.1.tgz", + "integrity": "sha1-Gpx0SCnznbuFjHbKNXmuKlTr0fo=", + "dev": true, + "requires": { + "for-own": "0.1.5", + "is-extendable": "0.1.1" + } + }, + "parse-glob": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/parse-glob/-/parse-glob-3.0.4.tgz", + "integrity": "sha1-ssN2z7EfNVE7rdFz7wu246OIORw=", + "dev": true, + "requires": { + "glob-base": "0.3.0", + "is-dotfile": "1.0.3", + "is-extglob": "1.0.0", + "is-glob": "2.0.1" + } + }, + "path-parse": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.5.tgz", + "integrity": "sha1-PBrfhx6pzWyUMbbqK9dKD/BVxME=", + "dev": true + }, + "preserve": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/preserve/-/preserve-0.2.0.tgz", + "integrity": "sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks=", + "dev": true + }, + "randomatic": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/randomatic/-/randomatic-1.1.7.tgz", + "integrity": "sha512-D5JUjPyJbaJDkuAazpVnSfVkLlpeO3wDlPROTMLGKG1zMFNFRgrciKo1ltz/AzNTkqE0HzDx655QOL51N06how==", + "dev": true, + "requires": { + "is-number": "3.0.0", + "kind-of": "4.0.0" + }, + "dependencies": { + "is-number": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", + "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "kind-of": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz", + "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "regex-cache": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/regex-cache/-/regex-cache-0.4.4.tgz", + "integrity": "sha512-nVIZwtCjkC9YgvWkpM55B5rBhBYRZhAaJbgcFYXXsHnbZ9UZI9nnVWYZpBlCqv9ho2eZryPnWrZGsOdPwVWXWQ==", + "dev": true, + "requires": { + "is-equal-shallow": "0.1.3" + } + }, + "remove-trailing-separator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz", + "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=", + "dev": true + }, + "repeat-element": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/repeat-element/-/repeat-element-1.1.2.tgz", + "integrity": "sha1-7wiaF40Ug7quTZPrmLT55OEdmQo=", + "dev": true + }, + "repeat-string": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=", + "dev": true + }, + "resolve": { + "version": "1.7.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.7.1.tgz", + "integrity": "sha512-c7rwLofp8g1U+h1KNyHL/jicrKg1Ek4q+Lr33AL65uZTinUZHe30D5HlyN5V9NW0JX1D5dXQ4jqW5l7Sy/kGfw==", + "dev": true, + "requires": { + "path-parse": "1.0.5" + } + }, + "resolve-url": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz", + "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=", + "dev": true + }, + "rollup": { + "version": "0.64.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-0.64.1.tgz", + "integrity": "sha512-+ThdVXrvonJdOTzyybMBipP0uz605Z8AnzWVY3rf+cSGnLO7uNkJBlN+9jXqWOomkvumXfm/esmBpA5d53qm7g==", + "dev": true, + "requires": { + "@types/estree": "0.0.39", + "@types/node": "10.7.0" + } + }, + "rollup-plugin-node-resolve": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/rollup-plugin-node-resolve/-/rollup-plugin-node-resolve-3.3.0.tgz", + "integrity": "sha512-9zHGr3oUJq6G+X0oRMYlzid9fXicBdiydhwGChdyeNRGPcN/majtegApRKHLR5drboUvEWU+QeUmGTyEZQs3WA==", + "dev": true, + "requires": { + "builtin-modules": "2.0.0", + "is-module": "1.0.0", + "resolve": "1.7.1" + } + }, + "rollup-plugin-sourcemaps": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/rollup-plugin-sourcemaps/-/rollup-plugin-sourcemaps-0.4.2.tgz", + "integrity": "sha1-YhJaqUCHqt97g+9N+vYptHMTXoc=", + "dev": true, + "requires": { + "rollup-pluginutils": "2.0.1", + "source-map-resolve": "0.5.1" + } + }, + "rollup-plugin-uglify": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/rollup-plugin-uglify/-/rollup-plugin-uglify-4.0.0.tgz", + "integrity": "sha512-f6W31EQLzxSEYfN3x6/lyljHqXSoCjXKcTsnwz3evQvHgU1+qTzU2SE0SIG7tbAvaCewp2UaZ5x3k6nYsxOP9A==", + "dev": true, + "requires": { + "@babel/code-frame": "7.0.0-rc.1", + "uglify-js": "3.4.7" + } + }, + "rollup-pluginutils": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/rollup-pluginutils/-/rollup-pluginutils-2.0.1.tgz", + "integrity": "sha1-fslbNXP2VDpGpkYb2afFRFJdD8A=", + "dev": true, + "requires": { + "estree-walker": "0.3.1", + "micromatch": "2.3.11" + } + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + }, + "source-map-resolve": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.1.tgz", + "integrity": "sha512-0KW2wvzfxm8NCTb30z0LMNyPqWCdDGE2viwzUaucqJdkTRXtZiSY3I+2A6nVAjmdOy0I4gU8DwnVVGsk9jvP2A==", + "dev": true, + "requires": { + "atob": "2.0.3", + "decode-uri-component": "0.2.0", + "resolve-url": "0.2.1", + "source-map-url": "0.4.0", + "urix": "0.1.0" + } + }, + "source-map-url": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.4.0.tgz", + "integrity": "sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=", + "dev": true + }, + "supports-color": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.4.0.tgz", + "integrity": "sha512-zjaXglF5nnWpsq470jSv6P9DwPvgLkuapYmfDm3JWOm0vkNTVF2tI4UrN2r6jH1qM/uc/WtxYY1hYoA2dOKj5w==", + "dev": true, + "requires": { + "has-flag": "3.0.0" + } + }, + "tslib": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.9.3.tgz", + "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" + }, + "typescript": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.0.1.tgz", + "integrity": "sha512-zQIMOmC+372pC/CCVLqnQ0zSBiY7HHodU7mpQdjiZddek4GMj31I3dUJ7gAs9o65X7mnRma6OokOkc6f9jjfBg==", + "dev": true + }, + "uglify-js": { + "version": "3.4.7", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.4.7.tgz", + "integrity": "sha512-J0M2i1mQA+ze3EdN9SBi751DNdAXmeFLfJrd/MDIkRc3G3Gbb9OPVSx7GIQvVwfWxQARcYV2DTxIkMyDAk3o9Q==", + "dev": true, + "requires": { + "commander": "2.16.0", + "source-map": "0.6.1" + } + }, + "underscore": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.9.1.tgz", + "integrity": "sha512-5/4etnCkd9c8gwgowi5/om/mYO5ajCaOgdzj/oW+0eQV9WxKBDZw5+ycmKmeaTXjInS/W0BzpGLo2xR2aBwZdg==", + "dev": true + }, + "urix": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/urix/-/urix-0.1.0.tgz", + "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=", + "dev": true + } + } +} diff --git a/package.json b/package.json index b6a96ec..1800194 100644 --- a/package.json +++ b/package.json @@ -1,51 +1,55 @@ { "name": "nestedtypes", - "main": "nestedtypes.js", - "description": "Next generation data framework, which can be used as drop-in backbonejs replacement.", - "homepage": "https://github.com/Volicon/backbone.nestedTypes", + "version": "2.1.4", + "main": "./dist/index.js", + "module": "./lib/index.js", + "types": "./lib/index.d.ts", + "description": "BackboneJS compatibility layer for the Type-R", + "homepage": "https://github.com/Volicon/NestedTypes", "keywords": [ - "backbone", - "relation", + "backbonejs", + "relations", "nested", "model", - "types", + "collection", "properties" ], "repository": { "type": "git", - "url": "https://github.com/Volicon/backbone.nestedTypes.git" + "url": "https://github.com/Volicon/NestedTypes.git" }, "author": "Vlad Balin ", "contributors": [], - "dependencies": { + "peerDependencies": { "jquery": "*", - "underscore": "^1.8.3" + "underscore": "*" }, "devDependencies": { - "chai-as-promised": "^5.3.0", - "chai": "* <3", - "mocha": "*", - "requirejs": "^2.1.20", - "sinon": "*", - "sinon-chai": "*", - "source-map-loader": "^0.1.5", - "ts-loader": "^0.8.2", - "typescript": "^1.8.10", - "uglify-js": "*", - "webpack": "^1.12.2" + "@types/jquery": "^2.0.49", + "jquery": "^3.3.1", + "rollup": "*", + "rollup-plugin-node-resolve": "*", + "rollup-plugin-sourcemaps": "*", + "rollup-plugin-uglify": "*", + "typescript": "^3.0.1", + "underscore": "*" }, "files": [ - "nestedtypes.js", + "dist", + "lib", + "src", "LICENSE" ], "license": "MIT", - "version": "2.0.0-rc6", "scripts": { - "test": "node_modules/.bin/mocha", - "pull" : "git submodule update --remote", - "build": "./node_modules/.bin/webpack", - "deploy": "copy .\\nestedtypes.js ..\\observer-frontend\\htdocs\\node_modules\\nestedtypes", - "all" : "npm run pull && npm run build && npm run deploy", - "watch": "./node_modules/.bin/webpack --watch" + "build": "npm run pull && npm run compile && npm run build:endpoints", + "pull": "git submodule update --remote && cp -R ./submodules/Type-R/src/* ./src/type-r && cp -R ./submodules/Type-R/endpoints/* ./endpoints", + "compile": "node_modules/.bin/tsc && ./node_modules/.bin/rollup --config", + "deploy": "cp ./dist/* ../observer-frontend/htdocs/js/lib/nested", + "build:endpoints": "cd endpoints/attributes && npm run build && cd ../localStorage && npm run build && cd ../memory && npm run build && cd ../restful && npm run build && cd ../proxy && npm run build", + "all": "npm run pull && npm run build && npm run deploy" + }, + "dependencies": { + "tslib": "^1.9.3" } } diff --git a/rollup.config.js b/rollup.config.js new file mode 100644 index 0000000..2393773 --- /dev/null +++ b/rollup.config.js @@ -0,0 +1,29 @@ +import resolve from 'rollup-plugin-node-resolve'; +import { uglify } from 'rollup-plugin-uglify'; +import sourcemaps from 'rollup-plugin-sourcemaps'; + +export default { + input : 'lib/index.js', + + output : { + file : 'dist/index.js', + format : 'umd', + name : 'Nested', + exports: 'named', + globals: { + jquery: '$', + underscore: '_' + }, + sourcemap: true + }, + plugins: [ + resolve(), //for support of `import X from "directory"` rather than verbose `import X from "directory/index"` + sourcemaps(), + uglify() + ], + + external: [ + 'jquery', + 'underscore' + ] +}; \ No newline at end of file diff --git a/src/backbone.js b/src/backbone.ts similarity index 95% rename from src/backbone.js rename to src/backbone.ts index 1912473..c5894a5 100644 --- a/src/backbone.js +++ b/src/backbone.ts @@ -11,6 +11,14 @@ import * as jQuery from 'jquery' // Initial Setup // ------------- +declare global { + interface Window { + Backbone : any + } + + function attachEvent( a, b ); + function detachEvent( a, b ); +} // Save the previous value of the `Backbone` variable, so that it can be // restored later on, if `noConflict` is used. @@ -19,23 +27,24 @@ const previousBackbone = window.Backbone; // Create a local reference to a common array method we'll want to use later. const slice = Array.prototype.slice; -// Current version of the library. Keep in sync with `package.json`. -export const VERSION = '1.2.3'; - // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns // the `$` variable. -export let $ = jQuery; +const exported = { + $ : jQuery, + history : null, + VERSION : '1.2.3', + View, History, Router, noConflict +} + +export default exported; // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable // to its previous owner. Returns a reference to this Backbone object. -export function noConflict() { +function noConflict() { window.Backbone = previousBackbone; return this; }; -export let emulateHTTP = false; -export let emulateJSON = false; - // Backbone.View // ------------- @@ -99,7 +108,7 @@ _.extend(View.prototype, { // re-delegation. setElement: function (element, delegate) { if (this.$el) this.undelegateEvents(); - this.$el = element instanceof $ ? element : $(element); + this.$el = element instanceof exported.$ ? element : exported.$(element); this.el = this.$el[0]; if (delegate !== false) this.delegateEvents(); return this; @@ -158,7 +167,7 @@ _.extend(View.prototype, { var attrs = _.extend({}, _.result(this, 'attributes')); if (this.id) attrs.id = _.result(this, 'id'); if (this.className) attrs['class'] = _.result(this, 'className'); - var $el = $('<' + _.result(this, 'tagName') + '>').attr(attrs); + var $el = exported.$('<' + _.result(this, 'tagName') + '>').attr(attrs); this.setElement($el, false); } else { this.setElement(_.result(this, 'el'), false); @@ -207,12 +216,12 @@ _.extend(Router.prototype, { } if (!callback) callback = this[name]; var router = this; - history.route(route, function (fragment) { + exported.history.route(route, function (fragment) { var args = router._extractParameters(route, fragment); if (router.execute(callback, args, name) !== false) { router.trigger.apply(router, ['route:' + name].concat(args)); router.trigger('route', name, args); - history.trigger('route', router, name, args); + exported.history.trigger('route', router, name, args); } }); return this; @@ -226,7 +235,7 @@ _.extend(Router.prototype, { // Simple proxy to `Backbone.history` to save a fragment into the history. navigate: function (fragment, options) { - history.navigate(fragment, options); + exported.history.navigate(fragment, options); return this; }, @@ -297,7 +306,7 @@ var rootStripper = /^\/+|\/+$/g; var pathStripper = /#.*$/; // Has the history handling already been started? -History.started = false; +(History as any).started = false; // Set up all inheritable **Backbone.History** properties and methods. _.extend(History.prototype, { @@ -360,15 +369,15 @@ _.extend(History.prototype, { // Start the hash change handling, returning `true` if the current URL matches // an existing route, and `false` otherwise. start: function (options) { - if (History.started) throw new Error('Backbone.history has already been started'); - History.started = true; + if ((History as any).started) throw new Error('Backbone.history has already been started'); + (History as any).started = true; // Figure out the initial configuration. Do we need an iframe? // Is pushState desired ... is it available? this.options = _.extend({ root: '/' }, this.options, options); this.root = this.options.root; this._wantsHashChange = this.options.hashChange !== false; - this._hasHashChange = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7); + this._hasHashChange = 'onhashchange' in window && ((document as any).documentMode === void 0 || (document as any).documentMode > 7); this._useHashChange = this._wantsHashChange && this._hasHashChange; this._wantsPushState = !!this.options.pushState; this._hasPushState = !!(this.history && this.history.pushState); @@ -453,7 +462,7 @@ _.extend(History.prototype, { } // Some environments will throw when clearing an undefined interval. if (this._checkUrlInterval) clearInterval(this._checkUrlInterval); - History.started = false; + (History as any).started = false; }, // Add a route to be tested when the fragment changes. Routes added later @@ -499,7 +508,7 @@ _.extend(History.prototype, { // route callback be fired (not usually desirable), or `replace: true`, if // you wish to modify the current URL without adding an entry to the history. navigate: function (fragment, options) { - if (!History.started) return false; + if (!(History as any).started) return false; if (!options || options === true) options = { trigger: !!options }; // Normalize the fragment. @@ -562,5 +571,5 @@ _.extend(History.prototype, { }); // Create the default Backbone.history. -export const history = new History; +exported.history = new History; diff --git a/src/index.ts b/src/index.ts index 596585c..f48125c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,57 +1,66 @@ +/** + * Extend Type-R namespace + */ +import * as TypeR from './type-r' +export * from './type-r' + /** * Prepare backbone View, Router, History, and Events. */ -import * as Nested from '../type-r/src' -export = Nested; -import * as Backbone from './backbone' +import Backbone from './backbone' import { RestCollection, RestModel } from './rest' -import { Store } from '../type-r/src' -import * as Sync from './sync' -import * as _ from 'underscore' -import { RestStore, LazyStore } from './rest-store' - -Nested.Mixable.mixins( Nested.Events ); -Nested.Mixable.mixTo( Backbone.View, Backbone.Router, Backbone.History ); +import { Store as BaseStore, tools, MixinsState } from './type-r' +import Sync from './sync' -Nested.useUnderscore( _ ); - -const { assign } = Nested.tools; +import { ModelMixin, CollectionMixin } from './underscore-mixin' +import { RestStore, LazyStore } from './rest-store' /** * Prepare */ -// allow sync and jQuery override -Object.defineProperties( Nested, { - 'emulateHTTP' : linkProperty( Backbone, 'emulateHTTP' ), - 'emulateJSON' : linkProperty( Backbone, 'emulateJSON' ), - 'sync' : linkProperty( Sync, 'sync' ), - 'errorPromise' : linkProperty( Sync, 'errorPromise' ), - 'ajax' : linkProperty( Sync, 'ajax' ), - 'history' : linkProperty( Backbone, 'history' ), - 'store' : linkProperty( Store, 'global' ), - '$' : { - get(){ return Backbone.$; }, - set( value ){ Backbone.$ = Sync.$ = value; } - } -} ); - -assign( Nested, Backbone, { - Backbone : Backbone, - Class : Nested.Messenger, - Model : RestModel, - Collection : RestCollection, - LazyStore : LazyStore, - Store : RestStore, - - defaults( x ){ - return Nested.Model.defaults( x ); - } -} ); +export const Class : typeof TypeR.Messenger = TypeR.Messenger; + +const Nested : typeof TypeR & typeof Backbone = Object.create( TypeR, tools.defaults({ + 'sync' : linkProperty( Sync, 'sync' ), + 'errorPromise' : linkProperty( Sync, 'errorPromise' ), + 'ajax' : linkProperty( Sync, 'ajax' ), + 'history' : linkProperty( Backbone, 'history' ), + 'store' : linkProperty( BaseStore, 'global' ), + '$' : { + get(){ return Backbone.$; }, + set( value ){ (Backbone).$ = (Sync).$ = value; } + } + }, + toProps( { Backbone, Class, Model : RestModel, Collection : RestCollection, LazyStore, Store : RestStore, defaults } ), + toProps( Backbone ) +)); + +export default Nested; +export { Backbone, RestStore, LazyStore, RestCollection as Collection, RestModel as Model }; + +export function defaults( x ) : typeof Nested.Record { + return Nested.Model.defaults( x ); +} + +export * from './backbone'; + +MixinsState.get( Nested.Mixable ).merge([ Nested.Events ]); +Nested.Messenger.mixins.populate( Backbone.View, Backbone.Router, Backbone.History ); +Nested.Record.mixins.merge([ ModelMixin ]); +Nested.Record.Collection.mixins.merge([ CollectionMixin ]); + +/** + * Local utilities + */ function linkProperty( Namespace, name ){ return { - get : function(){ return Namespace[ name ]; }, - set : function( value ){ Namespace[ name ] = value; } + get(){ return Namespace[ name ]; }, + set( value ){ Namespace[ name ] = value; } }; } + +function toProps( obj ){ + return tools.transform({}, obj, x => ({ value : x }) ); +} \ No newline at end of file diff --git a/src/rest-store.ts b/src/rest-store.ts index e2897cb..ff51aa9 100644 --- a/src/rest-store.ts +++ b/src/rest-store.ts @@ -1,15 +1,15 @@ -import * as Backbone from './backbone' +import Backbone from './backbone' import * as _ from 'underscore' -import { mixins, define, Store } from '../type-r/src' +import { mixins, mixinRules, define, Store } from './type-r' import { RestModel, RestCollection } from './rest' -const { $ } = Backbone; - -@define({}) -@mixins( Store ) +@define({ + getStore : Store.prototype.getStore, + get : Store.prototype.get, +}) export class RestStore extends RestModel {} -@define({}) +@define export class LazyStore extends RestStore { _resolved : {} = {} @@ -36,7 +36,7 @@ export class LazyStore extends RestStore { // fetch specified items, or all items if called without arguments. // returns jquery promise - fetch( ...args : string[] ) : {} { + fetch( ...args : any[] /* hack, inheritance here violates LSP */) : any { var xhr = [], objsToFetch = args.length ? args : this.keys(); @@ -45,12 +45,13 @@ export class LazyStore extends RestStore { attr && attr.fetch && xhr.push( attr.fetch() ); } - return $ && $.when && $.when.apply( Backbone.$, xhr ); + const { $ } = Backbone; + return $ && $.when && $.when.apply( $, xhr ); } // fetch specified items, or all items if called without arguments. // returns first jquery promise. - fetchOnce( ...args : string[] ) : {} { + fetchOnce( ...args : string[] ) : JQueryXHR { var xhr = [], self = this, objsToFetch = args.length ? args : this.keys(); @@ -60,7 +61,8 @@ export class LazyStore extends RestStore { xhr.push( self._resolved[ name ] || attr && attr.fetch && attr.fetch()); } - return $ && $.when && $.when.apply( Backbone.$, xhr ); + const { $ } = Backbone; + return $ && $.when && $.when.apply( $, xhr ); } clear( ...args : string[] ) : this { @@ -85,22 +87,15 @@ export class LazyStore extends RestStore { return this; } - static define( props, staticProps ){ - var attributes = props.defaults || props.attributes; + static onDefine( definitions, BaseClass ){ + var attributes = definitions.defaults || definitions.attributes; // add automatic fetching on first element's access _.each( attributes, ( Type : Function, name ) => { if( Type.has ){ attributes[name] = Type.has - .get( function( value ){ - if( !this._resolved[name] ) { - value.fetch && value.fetch(); - } - - return value; - }) .set( function( value ){ - if( !value.length ){ + if( !value || !value.length ){ const resolved = this._resolved || ( this._resolved = {} ); resolved[name] = false; } @@ -110,7 +105,7 @@ export class LazyStore extends RestStore { } }); - return RestModel.define.call( this, props, staticProps ); + RestModel.onDefine.call( this, definitions, BaseClass ); } } \ No newline at end of file diff --git a/src/rest.ts b/src/rest.ts index 0730eb9..b1dde00 100644 --- a/src/rest.ts +++ b/src/rest.ts @@ -1,17 +1,18 @@ -import { sync, errorPromise, urlError, SyncOptions, LazyValue } from './sync' +import Sync, { SyncOptions, Restful, LazyValue } from './sync' import * as _ from 'underscore' import * as Backbone from './backbone' -import { define, Model, Collection, tools } from '../type-r/src' +import { define, Model, Collection, tools, definitions, mixinRules } from './type-r' const { defaults } = tools; const transactionalProto = tools.getBaseClass( Model ).prototype; -interface RestOptions extends SyncOptions { +export interface RestOptions extends SyncOptions { wait? : boolean patch? : boolean reset? : boolean + validate? : boolean } @define({ @@ -19,7 +20,14 @@ interface RestOptions extends SyncOptions { destroy( model ){ this.remove( model ); } } }) -export class RestCollection extends Collection { +export class RestCollection extends Collection implements Restful { + _xhr : JQueryXHR + + dispose(){ + if( this._xhr && this._xhr.abort ) this._xhr.abort(); + super.dispose(); + } + model : typeof RestModel url() : string { return this.model.prototype.urlRoot || ''; } @@ -34,7 +42,7 @@ export class RestCollection extends Collection { // Fetch the default set of models for this collection, resetting the // collection when they arrive. If `reset: true` is passed, the response // data will be passed through the `reset` method instead of `set`. - fetch( options : RestOptions ){ + fetch( options : RestOptions ) : any { options = _.extend( { parse : true }, options ); var success = options.success; var collection = this; @@ -51,10 +59,10 @@ export class RestCollection extends Collection { return _sync( 'read', this, options ); } - create( a_model, options : any = {} ){ + create( a_model, options : any = {} ) : RestModel { const model : RestModel = a_model instanceof RestModel ? a_model : - this.model.create( a_model, options, this ); + this.model.create( a_model, options ); // Hack! For the situation when model instance is given, aquire it. model._owner || ( model._owner = this ); @@ -75,15 +83,21 @@ export class RestCollection extends Collection { // Proxy `Backbone.sync` by default -- but override this if you need // custom syncing semantics for *this* particular model. sync(){ - return sync.apply( this, arguments ); + return Sync.sync.apply( this, arguments ); } }; @define({ - collection : RestCollection, urlRoot : '' }) -export class RestModel extends Model { +@definitions({ + urlRoot : mixinRules.protoValue +}) +export class RestModel extends Model implements Restful { + static Collection : typeof Collection = RestCollection as any; + + _xhr : JQueryXHR + urlRoot : string /** @private */ @@ -95,9 +109,14 @@ export class RestModel extends Model { } } + dispose(){ + if( this._xhr && this._xhr.abort ) this._xhr.abort(); + super.dispose(); + } + // Fetch the model from the server, merging the response with the model's // local attributes. Any changed attributes will trigger a "change" event. - fetch( options : RestOptions ){ + fetch( options? : RestOptions ) : any { options = _.extend( { parse : true }, options ); var model = this; var success = options.success; @@ -115,16 +134,17 @@ export class RestModel extends Model { // Proxy `Backbone.sync` by default -- but override this if you need // custom syncing semantics for *this* particular model. - sync(){ - return sync.apply( this, arguments ); + sync( method : string, self : this, options : SyncOptions ) : any + sync() : JQueryXHR { + return Sync.sync.apply( this, arguments ); } // Set a hash of model attributes, and sync the model to the server. // If the server returns an attributes hash that differs, the model's // state will be `set` again. - save( attrs? : {}, options? : RestOptions ) - save( key : string, value : any, options? : RestOptions ) - save( key, val, a_options? : RestOptions ){ + save( attrs? : {}, options? : RestOptions ) : any + save( key : string, value : any, options? : RestOptions ) : any + save( key, val, a_options? : RestOptions ) : any { // Handle both `"key", value` and `{key: value}` -style arguments. let attrs, originalOptions; @@ -147,9 +167,9 @@ export class RestModel extends Model { this.set( attrs, originalOptions ); } - if( this._invalidate( originalOptions ) ){ + if( this._invalidate( options ) ){ if( attrs && wait ) this.set( attrs, originalOptions ); - return errorPromise( this.validationError ); + return Sync.errorPromise( this.validationError ); } // After a successful server-side save, the client is (optionally) @@ -190,7 +210,7 @@ export class RestModel extends Model { // Destroy this model on the server if it was already persisted. // Optimistically removes the model from its collection, if it has one. // If `wait: true` is passed, waits for the server to respond before removal. - destroy( options : RestOptions ){ + destroy( options : RestOptions ) : any { options = options ? _.clone( options ) : {}; var model = this; var success = options.success; @@ -207,7 +227,8 @@ export class RestModel extends Model { if( !model.isNew() ) triggerAndBubble( model, 'sync', model, resp, options ); }; - var xhr = false; + var xhr : JQueryXHR; + if( this.isNew() ){ _.defer( options.success ); } @@ -215,34 +236,56 @@ export class RestModel extends Model { wrapError( this, options ); xhr = _sync( 'delete', this, options ); } + if( !wait ) destroy(); - return xhr; + + return xhr || false; } // Default URL for the model's representation on the server -- if you're // using Backbone's restful methods, override this to change the endpoint // that will be called. - url(){ + url() : string { var base = _.result( this, 'urlRoot' ) || _.result( this.collection, 'url' ) || - urlError(); + Sync.urlError(); + if( this.isNew() ) return base; + var id = this.get( this.idAttribute ); + return base.replace( /[^\/]$/, '$&/' ) + encodeURIComponent( id ); } + + set( key : string, value : any, options? : object ) : this + set( attrs : {}, options? : object ) : this + set( a, b?, c? ) : this { + if( typeof a === 'string' ){ + if( c ){ + return super.set({ [ a ] : b }, c ); + } + else{ + this[ a ] = b; + return this; + } + } + else{ + return super.set( a, b ); + } + } } -function _sync( method, _this, options ){ +function _sync( method : string, _this : Restful, options ) : JQueryXHR { // Abort and pending IO request. Just one is allowed at the time. _this._xhr && _this._xhr.abort && _this._xhr.abort(); const xhr = _this._xhr = _this.sync( method, _this, options ); - xhr && xhr.always && xhr.always( function(){ _this.xhr = void 0; }); + xhr && xhr.always && xhr.always( function(){ _this._xhr = void 0; }); return xhr; } // Wrap an optional error callback with a fallback error event. -function wrapError( model, options ){ +function wrapError( model : any, options : RestOptions ){ var error = options.error; options.error = function( resp ){ if( error ) error.call( options.context, model, resp, options ); @@ -250,7 +293,7 @@ function wrapError( model, options ){ }; } -function triggerAndBubble( model : RestModel, ...args : any[] ){ +function triggerAndBubble( model : any, ...args : any[] ){ model.trigger.apply( model, args ); const { collection } = model; collection && collection.trigger.apply( collection, args ); diff --git a/src/sync.ts b/src/sync.ts index b7da11c..879e5f5 100644 --- a/src/sync.ts +++ b/src/sync.ts @@ -6,9 +6,9 @@ * With validation patches - NestedTypes validation semantic is applied. (c) Vlad Balin, 2015. */ import * as _ from 'underscore' -import * as Backbone from './backbone' +import Backbone from './backbone' -import { tools } from '../type-r/src' +import { tools } from './type-r' const { defaults } = tools; export type LazyValue< T > = () => T | T; @@ -20,13 +20,13 @@ export interface Restful { trigger( event : string, model, xhr, options ) collection? : { trigger( event : string, model, xhr, options ) } toJSON( options : any ) : {} + _xhr : JQueryXHR + sync( method : string, object : Restful, options : SyncOptions ) } export interface SyncOptions { url? : LazyValue< string > data? : any - emulateJSON? : boolean - emulateHTTP? : boolean attrs? : {} beforeSend? : ( xhr ) => any @@ -47,20 +47,30 @@ const methodMap = { 'read' : 'GET' }; - -export let $ = Backbone.$; +const exported = { + $ : Backbone.$, -export let errorPromise = function( error ){ - var x = $.Deferred(); - x.reject( error ); - return x; -} + errorPromise : error => { + var x = $.Deferred(); + x.reject( error ); + return x; + }, + + // Set the default implementation of `Backbone.ajax` to proxy through to `$`. + // Override this if you'd like to use a different library. + ajax : function( options : {} ){ + return $.ajax.apply( $, arguments ); + }, + + sync, + + // Throw an error when a URL is needed, and none is supplied. + urlError : function(){ + throw new Error( 'A "url" property or function must be specified' ); + } +}; -// Set the default implementation of `Backbone.ajax` to proxy through to `$`. -// Override this if you'd like to use a different library. -export let ajax : ( options : {} ) => any = function(){ - return $.ajax.apply( $, arguments ); -} +export default exported; // Backbone.sync // ------------- @@ -73,27 +83,16 @@ export let ajax : ( options : {} ) => any = function(){ // * Use `setTimeout` to batch rapid-fire updates into a single request. // * Send up the models as XML instead of JSON. // * Persist models via WebSockets instead of Ajax. - // - // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests - // as `POST`, with a `_method` parameter containing the true HTTP method, - // as well as all requests with the body as `application/x-www-form-urlencoded` - // instead of `application/json` with the model in a param named `model`. - // Useful when interfacing with server-side languages like **PHP** that make - // it difficult to read the body of `PUT` requests. -export let sync = function( method : Method, model : Restful, options : SyncOptions = {} ){ + +function sync( method : Method, model : Restful, options : SyncOptions = {} ) : JQueryXHR{ var type = methodMap[ method ]; - // Default options, unless specified. - defaults( options, { - emulateHTTP: Backbone.emulateHTTP, - emulateJSON: Backbone.emulateJSON - }); // Default JSON-request options. var params : any = { type : type, dataType : 'json' }; // Ensure that we have a URL. if( !options.url ){ - params.url = _.result( model, 'url' ) || urlError(); + params.url = _.result( model, 'url' ) || exported.urlError(); } // Ensure that we have the appropriate request data. @@ -102,26 +101,8 @@ export let sync = function( method : Method, model : Restful, options : SyncOpti params.data = JSON.stringify( options.attrs || model.toJSON( options ) ); } - // For older servers, emulate JSON by encoding the request into an HTML-form. - if( options.emulateJSON ){ - params.contentType = 'application/x-www-form-urlencoded'; - params.data = params.data ? { model : params.data } : {}; - } - - // For older servers, emulate HTTP by mimicking the HTTP method with `_method` - // And an `X-HTTP-Method-Override` header. - if( options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH') ){ - params.type = 'POST'; - if( options.emulateJSON ) params.data._method = type; - var beforeSend = options.beforeSend; - options.beforeSend = function( xhr ){ - xhr.setRequestHeader( 'X-HTTP-Method-Override', type ); - if( beforeSend ) return beforeSend.apply( this, arguments ); - }; - } - // Don't process data on a non-GET request. - if( params.type !== 'GET' && !options.emulateJSON ){ + if( params.type !== 'GET' ){ params.processData = false; } @@ -134,14 +115,8 @@ export let sync = function( method : Method, model : Restful, options : SyncOpti }; // Make the request, allowing the user to override any Ajax options. - var xhr = options.xhr = ajax( _.extend( params, options ) ); + var xhr = options.xhr = exported.ajax( _.extend( params, options ) ); model.trigger( 'request', model, xhr, options ); model.collection && model.collection.trigger( 'request', model, xhr, options ); return xhr; -} - - -// Throw an error when a URL is needed, and none is supplied. -export function urlError(){ - throw new Error( 'A "url" property or function must be specified' ); } \ No newline at end of file diff --git a/src/type-r/collection/README.md b/src/type-r/collection/README.md new file mode 100644 index 0000000..ca5c306 --- /dev/null +++ b/src/type-r/collection/README.md @@ -0,0 +1,16 @@ +# Transactional collections core implementation + +Collection implements two-phase commit transactions, +and core manipulation methods. + +## Folder structure and dependencies + + index.ts + ↗ ↑ ↖ + add.ts remove.ts set.ts + ↖ ↑ ↗ + commons.ts + ↑ + ../record/index.ts + + diff --git a/src/type-r/collection/add.ts b/src/type-r/collection/add.ts new file mode 100644 index 0000000..ab435f8 --- /dev/null +++ b/src/type-r/collection/add.ts @@ -0,0 +1,97 @@ +import { Transaction, transactionApi } from '../transactions' +import { CollectionTransaction, logAggregationError, sortElements, convertAndAquire, free, CollectionOptions, addIndex, updateIndex, CollectionCore } from './commons' +import { Record } from '../record' + +const { begin, commit, markAsDirty } = transactionApi; + +export interface AddOptions extends CollectionOptions { + at? : number +} + +/** @private */ +export function addTransaction( collection : CollectionCore, items : any[], options : AddOptions, merge? : boolean ){ + const isRoot = begin( collection ), + nested : Transaction[]= []; + + var added = appendElements( collection, items, nested, options, merge ); + + if( added.length || nested.length ){ + let needSort = sortOrMoveElements( collection, added, options ); + if( markAsDirty( collection, options ) ){ + return new CollectionTransaction( collection, isRoot, added, [], nested, needSort ); + } + + if( collection._aggregationError ) logAggregationError( collection ); + } + + // No changes... + isRoot && commit( collection ); +}; + +// Handle sort or insert at options for add operation. Reurns true if sort happened. +/** @private */ +function sortOrMoveElements( collection : CollectionCore, added : Record[], options : AddOptions ) : boolean { + let at = options.at; + + // if `at` option is given, it overrides sorting option... + if( at != null ){ + // Take an original collection's length. + const length = collection.models.length - added.length; + + // Crazy Backbone rules about `at` index. I don't know what that guys smoke. + at = Number( at ); + if( at < 0 ) at += length + 1; + if( at < 0 ) at = 0; + if( at > length ) at = length; + + // Move added elements to desired position. In place. + moveElements( collection.models, at, added ); + return false; + } + + return sortElements( collection, options ); +} + +/** @private */ +function moveElements( source : any[], at : number, added : any[] ) : void { + for( var j = source.length - 1, i = j - added.length; i >= at; i--, j-- ){ + source[ j ] = source[ i ]; + } + + for( i = 0, j = at; i < added.length; i++, j++ ){ + source[ j ] = added[ i ]; + } +} + +// append data to model and index +/** @private */ +function appendElements( collection : CollectionCore, a_items : any[], nested : Transaction[], a_options : AddOptions, forceMerge : boolean ){ + var { _byId, models } = collection, + merge = ( forceMerge || a_options.merge ) && !collection._shared, + parse = a_options.parse, + idAttribute = collection.model.prototype.idAttribute, + prevLength = models.length; + + for( const item of a_items ){ + let model = item ? _byId[ item[ idAttribute ] ] || _byId[ item.cid ] : null; + + if( model ){ + if( merge && item !== model ){ + var attrs = item.attributes || item; + const transaction = model._createTransaction( attrs, a_options ); + transaction && nested.push( transaction ); + + if( model.hasChanged( idAttribute ) ){ + updateIndex( _byId, model ); + } + } + } + else{ + model = convertAndAquire( collection, item, a_options ); + models.push( model ); + addIndex( _byId, model ); + } + } + + return models.slice( prevLength ); +} diff --git a/src/type-r/collection/commons.ts b/src/type-r/collection/commons.ts new file mode 100644 index 0000000..b9239d1 --- /dev/null +++ b/src/type-r/collection/commons.ts @@ -0,0 +1,222 @@ +import { Record } from '../record' +import { Owner, Transaction, ItemsBehavior, + TransactionOptions, Transactional, transactionApi } from '../transactions' + +import { eventsApi, tools } from '../object-plus' + +const { EventMap, trigger2, trigger3, on, off } = eventsApi, + { commit, markAsDirty } = transactionApi, + _aquire = transactionApi.aquire, _free = transactionApi.free; + +/** @private */ +export interface CollectionCore extends Transactional, Owner { + _byId : IdIndex + models : Record[] + model : typeof Record + idAttribute : string // TODO: Refactor inconsistent idAttribute usage + _comparator : Comparator + get( objOrId : string | Record | Object ) : Record + _itemEvents? : eventsApi.EventMap + _shared : number + _aggregationError : Record[] + + _log( level : string, text : string, value : any ) : void +} + +// Collection's manipulation methods elements +export type Elements = ( Object | Record )[]; + +export interface CollectionOptions extends TransactionOptions { + sort? : boolean +} + +export type Comparator = ( a : Record, b : Record ) => number; + +/** @private */ +export function dispose( collection : CollectionCore ) : Record[]{ + const { models } = collection; + + collection.models = []; + collection._byId = {}; + + freeAll( collection, models ); + return models; +} + +/** @private */ +export function convertAndAquire( collection : CollectionCore, attrs : {} | Record, options : CollectionOptions ){ + const { model } = collection; + + let record : Record; + + if( collection._shared ){ + record = attrs instanceof model ? attrs : model.create( attrs, options ); + + if( collection._shared & ItemsBehavior.listen ){ + on( record, record._changeEventName, collection._onChildrenChange, collection ); + } + } + else{ + record = attrs instanceof model ? ( options.merge ? attrs.clone() : attrs ) : model.create( attrs, options ); + + if( !_aquire( collection, record ) ){ + const errors = collection._aggregationError || ( collection._aggregationError = [] ); + errors.push( record ); + } + } + + // Subscribe for events... + const { _itemEvents } = collection; + _itemEvents && _itemEvents.subscribe( collection, record ); + + return record; +} + +/** @private */ +export function free( owner : CollectionCore, child : Record, unset? : boolean ) : void { + if( owner._shared ){ + if( owner._shared & ItemsBehavior.listen ){ + off( child, child._changeEventName, owner._onChildrenChange, owner ); + } + } + else{ + _free( owner, child ); + unset || child.dispose(); + } + + const { _itemEvents } = owner; + _itemEvents && _itemEvents.unsubscribe( owner, child ); +} + +/** @private */ +export function freeAll( collection : CollectionCore, children : Record[] ) : Record[] { + for( let child of children ){ + free( collection, child ); + } + + return children; +} + +/** + * Silently sort collection, if its required. Returns true if sort happened. + * @private + */ +export function sortElements( collection : CollectionCore, options : CollectionOptions ) : boolean { + let { _comparator } = collection; + if( _comparator && options.sort !== false ){ + collection.models.sort( _comparator ); + return true; + } + + return false; +} + +/********************************** + * Collection Index + * @private + */ +export interface IdIndex { + [ id : string ] : Record +} + +/** @private Add record */ +export function addIndex( index : IdIndex, model : Record ) : void { + index[ model.cid ] = model; + var id = model.id; + + if( id || id === 0 ){ + index[ id ] = model; + } +} + +/** @private Remove record */ +export function removeIndex( index : IdIndex, model : Record ) : void { + delete index[ model.cid ]; + var id = model.id; + if( id || id === 0 ){ + delete index[ id ]; + } +} + +export function updateIndex( index : IdIndex, model : Record ){ + delete index[ model.previous( model.idAttribute ) ]; + + const { id } = model; + id == null || ( index[ id ] = model ); +} + +/*** + * In Collections, transactions appears only when + * add remove or change events might be emitted. + * reset doesn't require transaction. + * + * Transaction holds information regarding events, and knows how to emit them. + * + * Two major optimization cases. + * 1) Population of an empty collection + * 2) Update of the collection (no or little changes) - it's crucial to reject empty transactions. + */ + + +// Transaction class. Implements two-phase transactions on object's tree. +/** @private */ +export class CollectionTransaction implements Transaction { + // open transaction + constructor( public object : CollectionCore, + public isRoot : boolean, + public added : Record[], + public removed : Record[], + public nested : Transaction[], + public sorted : boolean ){} + + // commit transaction + commit( initiator? : Transactional ){ + const { nested, object } = this, + { _isDirty } = object; + + // Commit all nested transactions... + for( let transaction of nested ){ + transaction.commit( object ); + } + + if( object._aggregationError ){ + logAggregationError( object ); + } + + // Just trigger 'change' on collection, it must be already triggered for models during nested commits. + // ??? TODO: do it in nested transactions loop? This way appears to be more correct. + for( let transaction of nested ){ + trigger2( object, 'change', transaction.object, _isDirty ); + } + + // Notify listeners on attribute changes... + const { added, removed } = this; + + // Trigger `add` events for both model and collection. + for( let record of added ){ + trigger3( record, 'add', record, object, _isDirty ); + trigger3( object, 'add', record, object, _isDirty ); + } + + // Trigger `remove` events for both model and collection. + for( let record of removed ){ + trigger3( record, 'remove', record, object, _isDirty ); + trigger3( object, 'remove', record, object, _isDirty ); + } + + if( this.sorted ){ + trigger2( object, 'sort', object, _isDirty ); + } + + if( added.length || removed.length ){ + trigger2( object, 'update', object, _isDirty ); + } + + this.isRoot && commit( object, initiator ); + } +} + +export function logAggregationError( collection : CollectionCore ){ + collection._log( 'error', 'added records already have an owner', collection._aggregationError ); + collection._aggregationError = void 0; +} \ No newline at end of file diff --git a/src/type-r/collection/index.ts b/src/type-r/collection/index.ts new file mode 100644 index 0000000..55ff533 --- /dev/null +++ b/src/type-r/collection/index.ts @@ -0,0 +1,614 @@ +import { define, tools, eventsApi, EventMap, definitions, mixinRules, EventsDefinition, Mixable } from '../object-plus' +import { ItemsBehavior, transactionApi, Transactional, CloneOptions, Transaction, TransactionOptions, TransactionalDefinition, Owner } from '../transactions' +import { Record, SharedType, AggregatedType, createSharedTypeSpec } from '../record' + +import { IdIndex, free, sortElements, dispose, Elements, CollectionCore, addIndex, removeIndex, updateIndex, Comparator, CollectionTransaction } from './commons' +import { addTransaction, AddOptions } from './add' +import { setTransaction, emptySetTransaction } from './set' +import { removeOne, removeMany } from './remove' +import { IOPromise, startIO } from '../io-tools' + +const { trigger2, on, off } = eventsApi, + { begin, commit, markAsDirty } = transactionApi, + { omit, log, assign, defaults, assignToClassProto } = tools; + +let _count = 0; + +export type GenericComparator = string | ( ( x : Record ) => number ) | ( ( a : Record, b : Record ) => number ); + +export interface CollectionOptions extends TransactionOptions { + comparator? : GenericComparator + model? : typeof Record +} + +export type Predicate = ( val : R, key : number ) => boolean | object; + +export interface CollectionDefinition extends TransactionalDefinition { + model? : typeof Record, + itemEvents? : EventsDefinition + _itemEvents? : EventMap +} + +const slice = Array.prototype.slice; + +class CollectionRefsType extends SharedType { + static defaultValue = []; +} + +@define({ + // Default client id prefix + cidPrefix : 'c', + model : Record, + _changeEventName : 'changes', + _aggregationError : null +}) +@definitions({ + comparator : mixinRules.value, + model : mixinRules.protoValue, + itemEvents : mixinRules.merge +}) +export class Collection< R extends Record = Record> extends Transactional implements CollectionCore { + _shared : number + _aggregationError : R[] + + static Subset : typeof Collection + static Refs : typeof Collection + static _SubsetOf : typeof Collection + + createSubset( models : ElementsArg, options ){ + const SubsetOf = (this.constructor).subsetOf( this ).options.type, + subset = new SubsetOf( models, options ); + + subset.resolve( this ); + return subset; + } + + static onExtend( BaseClass : typeof Transactional ){ + // Cached subset collection must not be inherited. + const Ctor = this; + this._SubsetOf = null; + + function RefsCollection( a, b, listen? ){ + Ctor.call( this, a, b, ItemsBehavior.share | ( listen ? ItemsBehavior.listen : 0 ) ); + } + + Mixable.mixins.populate( RefsCollection ); + + RefsCollection.prototype = this.prototype; + RefsCollection._attribute = CollectionRefsType; + + this.Refs = this.Subset = RefsCollection; + + Transactional.onExtend.call( this, BaseClass ); + createSharedTypeSpec( this, SharedType ); + } + + static onDefine( definition : CollectionDefinition, BaseClass : any ){ + if( definition.itemEvents ){ + const eventsMap = new EventMap( BaseClass.prototype._itemEvents ); + eventsMap.addEventsMap( definition.itemEvents ); + this.prototype._itemEvents = eventsMap; + } + + if( definition.comparator !== void 0 ) this.prototype.comparator = definition.comparator; + + Transactional.onDefine.call( this, definition ); + } + + static subsetOf : ( collectionReference : any ) => any; + + _itemEvents : EventMap + + /*********************************** + * Core Members + */ + // Array of the records + models : R[] + + // Polymorphic accessor for aggregated attribute's canBeUpdated(). + get __inner_state__(){ return this.models; } + + // Index by id and cid + _byId : { [ id : string ] : R } + + set comparator( x : GenericComparator ){ + let compare; + + switch( typeof x ){ + case 'string' : + this._comparator = ( a, b ) => { + const aa = a[ x ], bb = b[ x ]; + if( aa === bb ) return 0; + return aa < bb ? -1 : + 1; + } + break; + case 'function' : + if( x.length === 1 ){ + this._comparator = ( a, b ) => { + const aa = (x).call( this, a ), bb = (x).call( this, b ); + if( aa === bb ) return 0; + return aa < bb ? -1 : + 1; + } + } + else{ + this._comparator = ( a, b ) => (x).call( this, a, b ); + } + break; + + default : + this._comparator = null; + } + } + + // TODO: Improve typing + getStore() : Transactional { + return this._store || ( this._store = this._owner ? this._owner.getStore() : this._defaultStore ); + } + + _store : Transactional + + get comparator(){ return this._comparator; } + _comparator : ( a : R, b : R ) => number + + _onChildrenChange( record : R, options : TransactionOptions = {}, initiator? : Transactional ){ + // Ignore updates from nested transactions. + if( initiator === this ) return; + + const { idAttribute } = this; + + if( record.hasChanged( idAttribute ) ){ + updateIndex( this._byId, record ); + } + + const isRoot = begin( this ); + + if( markAsDirty( this, options ) ){ + // Forward change event from the record. + trigger2( this, 'change', record, options ) + } + + isRoot && commit( this ); + } + + get( objOrId : string | R | Object ) : R { + if( objOrId == null ) return; + + if( typeof objOrId === 'object' ){ + const id = objOrId[ this.idAttribute ]; + return ( id !== void 0 && this._byId[ id ] ) || this._byId[ (objOrId).cid ]; + } + else{ + return this._byId[ objOrId ]; + } + } + + each( iteratee : ( val : R, key : number ) => void, context? : any ){ + const fun = bindContext( iteratee, context ), + { models } = this; + + for( let i = 0; i < models.length; i++ ){ + fun( models[ i ], i ); + } + } + + forEach( iteratee : ( val : R, key? : number ) => void, context? : any ){ + return this.each( iteratee, context ); + } + + every( iteratee : Predicate, context? : any ) : boolean { + const fun = toPredicateFunction( iteratee, context ), + { models } = this; + + for( let i = 0; i < models.length; i++ ){ + if( !fun( models[ i ], i ) ) return false; + } + + return true; + } + + filter( iteratee : Predicate, context? : any ) : R[] { + const fun = toPredicateFunction( iteratee, context ), + { models } = this; + + return this.map( ( x, i ) => fun( x, i ) ? x : void 0 ); + } + + find( iteratee : Predicate, context? : any ) : R { + const fun = toPredicateFunction( iteratee, context ), + { models } = this; + + for( let i = 0; i < models.length; i++ ){ + if( fun( models[ i ], i ) ) return models[ i ]; + } + + return null; + } + + some( iteratee : Predicate, context? : any ) : boolean { + return Boolean( this.find( iteratee, context ) ); + } + + map< T >( iteratee : ( val : R, key : number ) => T, context? : any ) : T[]{ + const fun = bindContext( iteratee, context ), + { models } = this, + mapped = Array( models.length ); + + let j = 0; + + for( let i = 0; i < models.length; i++ ){ + const x = fun( models[ i ], i ); + x === void 0 || ( mapped[ j++ ] = x ); + } + + mapped.length = j; + + return mapped; + } + + _validateNested( errors : {} ) : number { + // Don't validate if not aggregated. + if( this._shared ) return 0; + + let count = 0; + + this.each( record => { + const error = record.validationError; + if( error ){ + errors[ record.cid ] = error; + count++; + } + }); + + return count; + } + + model : typeof Record + + // idAttribute extracted from the model type. + idAttribute : string + + constructor( records? : ( R | {} )[], options : CollectionOptions = {}, shared? : number ){ + super( _count++ ); + this.models = []; + this._byId = {}; + + this.comparator = this.comparator; + + if( options.comparator !== void 0 ){ + this.comparator = options.comparator; + options.comparator = void 0; + } + + this.model = this.model; + + if( options.model ){ + this.model = options.model; + options.model = void 0; + } + + this.idAttribute = this.model.prototype.idAttribute; //TODO: Remove? + + this._shared = shared || 0; + + if( records ){ + const elements = toElements( this, records, options ); + emptySetTransaction( this, elements, options, true ); + } + + this.initialize.apply( this, arguments ); + + if( this._localEvents ) this._localEvents.subscribe( this, this ); + } + + initialize(){} + + get length() : number { return this.models.length; } + first() : R { return this.models[ 0 ]; } + last() : R { return this.models[ this.models.length - 1 ]; } + at( a_index : number ) : R { + const index = a_index < 0 ? a_index + this.models.length : a_index; + return this.models[ index ]; + } + + // Deeply clone collection, optionally setting new owner. + clone( options : CloneOptions = {} ) : this { + const models = this._shared & ItemsBehavior.share ? this.models : this.map( model => model.clone() ), + copy : this = new (this.constructor)( models, { model : this.model, comparator : this.comparator }, this._shared ); + + if( options.pinStore ) copy._defaultStore = this.getStore(); + + return copy; + } + + toJSON( options? : object ) : any { + return this.models.map( model => model.toJSON( options ) ); + } + + // Apply bulk in-place object update in scope of ad-hoc transaction + set( elements : ElementsArg = [], options : TransactionOptions = {} ) : this { + if( (options).add !== void 0 ){ + this._log( 'warn', "Collection.set doesn't support 'add' option, behaving as if options.add === true.", options ); + } + + // Handle reset option here - no way it will be populated from the top as nested transaction. + if( options.reset ){ + this.reset( elements, options ) + } + else{ + const transaction = this._createTransaction( elements, options ); + transaction && transaction.commit(); + } + + return this; + } + + /** + * Enable or disable live updates. + * + * `true` enables full collection synchronization. + * `false` cancel live updates. + * `json => true | false` - filter updates + */ + liveUpdates( enabled : LiveUpdatesOption ) : IOPromise { + if( enabled ){ + this.liveUpdates( false ); + + const filter = typeof enabled === 'function' ? enabled : () => true; + + this._liveUpdates = { + updated : json => { + filter( json ) && this.add( json, { parse : true, merge : true } ); + }, + + removed : id => this.remove( id ) + }; + + return this.getEndpoint().subscribe( this._liveUpdates, this ).then( () => this ); + } + else{ + if( this._liveUpdates ){ + this.getEndpoint().unsubscribe( this._liveUpdates, this ); + this._liveUpdates = null; + } + } + } + + _liveUpdates : object + + fetch( a_options : { liveUpdates? : LiveUpdatesOption } & TransactionOptions = {} ) : IOPromise { + const options = { parse : true, ...a_options }, + endpoint = this.getEndpoint(); + + return startIO( + this, + endpoint.list( options, this ), + options, + + json => { + let result : any = this.set( json, { parse : true, ...options } as TransactionOptions ); + + if( options.liveUpdates ){ + result = this.liveUpdates( options.liveUpdates ); + } + + return result; + } + ); + } + + dispose() : void { + if( this._disposed ) return; + + const aggregated = !this._shared; + + for( let record of this.models ){ + free( this, record ); + + if( aggregated ) record.dispose(); + } + + this.liveUpdates( false ); + + super.dispose(); + } + + reset( a_elements? : ElementsArg, options : TransactionOptions = {} ) : R[] { + const isRoot = begin( this ), + previousModels = this.models; + + // Make all changes required, but be silent. + if( a_elements ){ + emptySetTransaction( this, toElements( this, a_elements, options ), options, true ); + } + else{ + this._byId = {}; + this.models = []; + } + + markAsDirty( this, options ); + + options.silent || trigger2( this, 'reset', this, defaults( { previousModels : previousModels }, options ) ); + + // Dispose models which are not in the updated collection. + const { _byId } = this; + + for( let toDispose of previousModels ){ + _byId[ toDispose.cid ] || free( this, toDispose ); + } + + isRoot && commit( this ); + return this.models; + } + + // Add elements to collection. + add( a_elements : ElementsArg , options : AddOptions = {} ){ + const elements = toElements( this, a_elements, options ), + transaction = this.models.length ? + addTransaction( this, elements, options ) : + emptySetTransaction( this, elements, options ); + + if( transaction ){ + transaction.commit(); + return transaction.added; + } + } + + // Remove elements. + remove( recordsOrIds : any, options : CollectionOptions = {} ) : R[] | R { + if( recordsOrIds ){ + return Array.isArray( recordsOrIds ) ? + removeMany( this, recordsOrIds, options ) as R[]: + removeOne( this, recordsOrIds, options ) as R; + } + + return []; + } + + // Apply bulk object update without any notifications, and return open transaction. + // Used internally to implement two-phase commit. + _createTransaction( a_elements : ElementsArg, options : TransactionOptions = {} ) : CollectionTransaction | void { + const elements = toElements( this, a_elements, options ); + + if( this.models.length ){ + return options.remove === false ? + addTransaction( this, elements, options, true ) : + setTransaction( this, elements, options ); + } + else{ + return emptySetTransaction( this, elements, options ); + } + } + + static _attribute = AggregatedType; + + /*********************************** + * Collection manipulation methods + */ + + pluck( key : keyof R ) : any[] { + return this.models.map( model => model[ key ] ); + } + + sort( options : TransactionOptions = {} ) : this { + if( sortElements( this, options ) ){ + const isRoot = begin( this ); + + if( markAsDirty( this, options ) ){ + trigger2( this, 'sort', this, options ); + } + + isRoot && commit( this ); + } + + return this; + } + + // Add a model to the end of the collection. + push(model : ElementsArg, options : CollectionOptions ) { + return this.add(model, assign({at: this.length}, options)); + } + + // Remove a model from the end of the collection. + pop( options : CollectionOptions ) : R { + var model = this.at(this.length - 1); + this.remove(model, { unset : true, ...options }); + return model; + } + + // Remove and return given model. + // TODO: do not dispose the model for aggregated collection. + unset( modelOrId : R | string, options? ) : R { + const value = this.get( modelOrId ); + this.remove( modelOrId, { unset : true, ...options } ); + return value; + } + + // Add a model to the beginning of the collection. + unshift(model : ElementsArg, options : CollectionOptions ) { + return this.add(model, assign({at: 0}, options)); + } + + // Remove a model from the beginning of the collection. + shift( options? : CollectionOptions ) : R { + var model = this.at(0); + this.remove( model, { unset : true, ...options } ); + return model; + } + + // Slice out a sub-array of models from the collection. + slice() : R[] { + return slice.apply(this.models, arguments); + } + + indexOf( modelOrId : any ) : number { + const record = this.get( modelOrId ); + return this.models.indexOf( record ); + } + + modelId( attrs : {} ) : any { + return attrs[ this.model.prototype.idAttribute ]; + } + + // Toggle model in collection. + toggle( model : R, a_next? : boolean ) : boolean { + var prev = Boolean( this.get( model ) ), + next = a_next === void 0 ? !prev : Boolean( a_next ); + + if( prev !== next ){ + if( prev ){ + this.remove( model ); + } + else{ + this.add( model ); + } + } + + return next; + } + + _log( level : tools.LogLevel, text : string, value ) : void { + tools.log( level, `[Collection Update] ${ this.model.prototype.getClassName() }.${ this.getClassName() }: ` + text, { + Argument : value, + 'Attributes spec' : this.model.prototype._attributes + }); + } + + getClassName() : string { + return super.getClassName() || 'Collection'; + } +} + +export type LiveUpdatesOption = boolean | ( ( x : any ) => boolean ); + +export type ElementsArg = Object | Record | Object[] | Record[]; + +// TODO: make is safe for parse to return null (?) +function toElements( collection : Collection, elements : ElementsArg, options : CollectionOptions ) : Elements { + const parsed = options.parse ? collection.parse( elements, options ) : elements; + return Array.isArray( parsed ) ? parsed : [ parsed ]; +} + +createSharedTypeSpec( Collection, SharedType ); + +Record.Collection = Collection; + +function bindContext( fun : Function, context? : any ){ + return context !== void 0 ? ( v, k ) => fun.call( context, v, k ) : fun; +} + +function toPredicateFunction( iteratee : Predicate, context : any ){ + if( typeof iteratee === 'object' ){ + // Wrap object to the predicate... + return x => { + for( let key in iteratee as any ){ + if( iteratee[ key ] !== x[ key ] ) + return false; + } + + return true; + } + } + + return bindContext( iteratee, context ); + +} \ No newline at end of file diff --git a/src/type-r/collection/remove.ts b/src/type-r/collection/remove.ts new file mode 100644 index 0000000..2ae1b5b --- /dev/null +++ b/src/type-r/collection/remove.ts @@ -0,0 +1,114 @@ +/************* + * Remove items from collections. + * + * Cannot be a part of two-phase transaction on object tree. + * Can be executed in the scope of ad-hoc transaction or from the trigger, though. + * + * Implemented with low-level API. + * Most frequent operation - single element remove. Thus, it have the fast-path. + */ + +import { Record } from '../record' +import { free, CollectionCore, CollectionTransaction, removeIndex } from './commons' +import { eventsApi } from '../object-plus' +import { TransactionOptions, transactionApi } from '../transactions' + +const { trigger2, trigger3 } = eventsApi, + { markAsDirty, begin, commit } = transactionApi; + +/** @private */ +export function removeOne( collection : CollectionCore, el : Record | {} | string, options : TransactionOptions ) : Record { + var model : Record = collection.get( el ); + + if( model ){ + const isRoot = begin( collection ), + models = collection.models; + + // Remove model form the collection. + models.splice( models.indexOf( model ), 1 ); + removeIndex( collection._byId, model ); + + // Mark transaction as dirty. + const notify = markAsDirty( collection, options ); + + // Send out events. + if( notify ){ + trigger3( model, 'remove', model, collection, options ); + trigger3( collection, 'remove', model, collection, options ); + } + + free( collection, model, options.unset ); + + notify && trigger2( collection, 'update', collection, options ); + + // Commit transaction. + isRoot && commit( collection ); + + return model; + } +}; + +/** Optimized for removing many elements + * 1. Remove elements from the index, checking for duplicates + * 2. Create new models array matching index + * 3. Send notifications and remove references + */ + +/** @private */ +export function removeMany( collection : CollectionCore, toRemove : any[], options ){ + const removed = _removeFromIndex( collection, toRemove, options.unset ); + if( removed.length ){ + const isRoot = begin( collection ); + + _reallocate( collection, removed.length ); + + if( markAsDirty( collection, options ) ){ + const transaction = new CollectionTransaction( collection, isRoot, [], removed, [], false ); + transaction.commit(); + } + else{ + // Commit transaction. + isRoot && commit( collection ); + } + } + + return removed; +}; + +// remove models from the index... +/** @private */ +function _removeFromIndex( collection, toRemove, unset : boolean ){ + var removed = Array( toRemove.length ), + _byId = collection._byId; + + for( var i = 0, j = 0; i < toRemove.length; i++ ){ + var model = collection.get( toRemove[ i ] ); + if( model ){ + removed[ j++ ] = model; + removeIndex( _byId, model ); + free( collection, model, unset ); + } + } + + removed.length = j; + + return removed; +} + +// Allocate new models array removing models not present in the index. +/** @private */ +function _reallocate( collection, removed ){ + var prev = collection.models, + models = collection.models = Array( prev.length - removed ), + _byId = collection._byId; + + for( var i = 0, j = 0; i < prev.length; i++ ){ + var model = prev[ i ]; + + if( _byId[ model.cid ] ){ + models[ j++ ] = model; + } + } + + models.length = j; +} \ No newline at end of file diff --git a/src/type-r/collection/set.ts b/src/type-r/collection/set.ts new file mode 100644 index 0000000..3eedce3 --- /dev/null +++ b/src/type-r/collection/set.ts @@ -0,0 +1,154 @@ +import { Transaction, transactionApi } from '../transactions' +import { CollectionTransaction, logAggregationError, IdIndex, convertAndAquire, free, sortElements, CollectionOptions, addIndex, CollectionCore, Elements, freeAll } from './commons' +import { Record } from '../record' + +const { begin, commit, markAsDirty } = transactionApi; + +/** @private */ +const silentOptions = { silent : true }; + +/** @private */ +export function emptySetTransaction( collection : CollectionCore, items : Elements, options : CollectionOptions, silent? : boolean ){ + const isRoot = begin( collection ); + + const added = _reallocateEmpty( collection, items, options ); + + if( added.length ){ + const needSort = sortElements( collection, options ); + + if( markAsDirty( collection, silent ? silentOptions : options ) ){ + // 'added' is the reference to this.models. Need to copy it. + return new CollectionTransaction( collection, isRoot, added.slice(), [], [], needSort ); + } + + if( collection._aggregationError ) logAggregationError( collection ); + } + + // No changes... + isRoot && commit( collection ); +}; + +/** @private */ +export function setTransaction( collection, items, options ){ + const isRoot = begin( collection ), + nested = []; + + var previous = collection.models, + added = _reallocate( collection, items, nested, options ); + + const reusedCount = collection.models.length - added.length, + removed = reusedCount < previous.length ? ( + reusedCount ? _garbageCollect( collection, previous ) : + freeAll( collection, previous ) + ) : []; + + const addedOrChanged = nested.length || added.length, + // As we are reallocating models array, it needs to be sorted even if there are no changes. + sorted = ( sortElements( collection, options ) && addedOrChanged ) || added.length || options.sorted; + + if( addedOrChanged || removed.length || sorted ){ + if( markAsDirty( collection, options ) ){ + return new CollectionTransaction( collection, isRoot, added, removed, nested, sorted ); + } + + if( collection._aggregationError ) logAggregationError( collection ); + } + + isRoot && commit( collection ); +}; + +// Remove references to all previous elements, which are not present in collection. +// Returns an array with removed elements. +/** @private */ +function _garbageCollect( collection : CollectionCore, previous : Record[] ) : Record[]{ + const { _byId } = collection, + removed = []; + + // Filter out removed models and remove them from the index... + for( let record of previous ){ + if( !_byId[ record.cid ] ){ + removed.push( record ); + free( collection, record ); + } + } + + return removed; +} + +// reallocate model and index +/** @private */ +function _reallocate( collection : CollectionCore, source : any[], nested : Transaction[], options ){ + var models = Array( source.length ), + _byId : IdIndex = {}, + merge = ( options.merge == null ? true : options.merge ) && !collection._shared, + _prevById = collection._byId, + prevModels = collection.models, + idAttribute = collection.model.prototype.idAttribute, + toAdd = [], + orderKept = true; + + // for each item in source set... + for( var i = 0, j = 0; i < source.length; i++ ){ + var item = source[ i ], + model : Record = null; + + if( item ){ + var id = item[ idAttribute ], + cid = item.cid; + + if( _byId[ id ] || _byId[ cid ] ) continue; + + model = _prevById[ id ] || _prevById[ cid ]; + } + + if( model ){ + if( merge && item !== model ){ + if( orderKept && prevModels[ j ] !== model ) orderKept = false; + + var attrs = item.attributes || item; + const transaction = model._createTransaction( attrs, options ); + transaction && nested.push( transaction ); + } + } + else{ + model = convertAndAquire( collection, item, options ); + toAdd.push( model ); + } + + models[ j++ ] = model; + addIndex( _byId, model ); + } + + models.length = j; + collection.models = models; + collection._byId = _byId; + + if( !orderKept ) options.sorted = true; + + return toAdd; +} + +/** @private */ +function _reallocateEmpty( self, source, options ){ + var len = source ? source.length : 0, + models = Array( len ), + _byId : IdIndex = {}, + idAttribute = self.model.prototype.idAttribute; + + for( var i = 0, j = 0; i < len; i++ ){ + var src = source[ i ]; + + if( src && ( _byId[ src[ idAttribute ] ] || _byId[ src.cid ] ) ){ + continue; + } + + var model = convertAndAquire( self, src, options ); + models[ j++ ] = model; + addIndex( _byId, model ); + } + + models.length = j; + self._byId = _byId; + + return self.models = models; +} \ No newline at end of file diff --git a/src/type-r/index.ts b/src/type-r/index.ts new file mode 100644 index 0000000..09ecf5c --- /dev/null +++ b/src/type-r/index.ts @@ -0,0 +1,61 @@ +// Polyfill for IE10. Should fix problems with babel and statics inheritance. +import { tools } from './object-plus' + +declare global { + interface ObjectConstructor { + setPrototypeOf( target : Object, proto : Object ); + } +} + +Object.setPrototypeOf || ( Object.setPrototypeOf = tools.defaults ); + +/** + * Export everything + */ + +export * from './object-plus' +export * from './collection' +export * from './relations' +export * from './record' +export * from './transactions' + +export * from './io-tools' + +// Exported module itself is the global event bus. +import { Events } from './object-plus/' +export const { on, off, trigger, once, listenTo, stopListening, listenToOnce } = Events; + +import { Collection } from './collection' + +// Define synonims for NestedTypes backward compatibility. +import { Record as Model } from './record' +import { define, Mixable as Class } from './object-plus/' +export { Model, Class }; + +export function attributes( attrDefs ) : typeof Model { + @define class DefaultRecord extends Model { + static attributes = attrDefs; + } + + return DefaultRecord; +} + +import { ChainableAttributeSpec } from './record' + +/** Typeless attribute declaration with default value. */ +export function value( x : any ) : ChainableAttributeSpec { + return new ChainableAttributeSpec({ value : x }); +} + +/** Wrap model or collection method in transaction. */ +export function transaction< F extends Function >( method : F ) : F { + return function( ...args ){ + let result; + + this.transaction( () => { + result = method.apply( this, args ); + }); + + return result; + } +} \ No newline at end of file diff --git a/src/type-r/io-tools.ts b/src/type-r/io-tools.ts new file mode 100644 index 0000000..2659c2d --- /dev/null +++ b/src/type-r/io-tools.ts @@ -0,0 +1,116 @@ +export interface IONode { + _endpoint : IOEndpoint + _ioPromise : IOPromise< this > +} + +export interface IOPromise extends Promise { + abort? : () => void +} + +export interface IOEndpoint { + list( options : IOOptions, collection? ) : IOPromise + create( json : any, options : IOOptions, record? ) : IOPromise + update( id : string | number, json :any, options : IOOptions, record? ) : IOPromise + read( id : string | number, options : IOOptions, record? ) : IOPromise + destroy( id : string | number, options : IOOptions, record? ) : IOPromise + subscribe( events : IOEvents, collection? ) : IOPromise + unsubscribe( events : IOEvents, collection? ) : void +} + +export interface IOOptions { + ioUpdate? : boolean +} + +export interface IOEvents { + updated? : ( json : any ) => void + removed? : ( json : any ) => void +} + +export function getOwnerEndpoint( self ) : IOEndpoint { + // Check if we are the member of the collection... + const { collection } = self; + if( collection ){ + return getOwnerEndpoint( collection ); + } + + // Now, if we're the member of the model... + if( self._owner ){ + const { _endpoints } = self._owner; + return _endpoints && _endpoints[ self._ownerKey ]; + } +} + +/** + * Create abortable promise. + * Adds `promise.abort()` function which rejects the promise by default + * initialize() function takes third optional argument `abort : ( resolve, reject ) => void`, + * which can be used to add custom abort handling. + */ +declare var Promise: PromiseConstructorLike; + +export function createIOPromise( initialize : InitIOPromise ) : IOPromise{ + let resolve, reject, onAbort; + + function abort( fn ){ + onAbort = fn; + } + + const promise : IOPromise = new Promise( ( a_resolve, a_reject ) =>{ + reject = a_reject; + resolve = a_resolve; + initialize( resolve, reject, abort ); + }) as IOPromise; + + promise.abort = () => { + onAbort ? onAbort( resolve, reject ) : reject( new Error( "I/O Aborted" ) ); + } + + return promise; +} + +export type InitIOPromise = ( resolve : ( x? : any ) => void, reject : ( x? : any ) => void, abort? : ( fn : Function ) => void ) => void; + +export function startIO( self : IONode, promise : IOPromise, options : IOOptions, thenDo : ( json : any ) => any ) : IOPromise { + // Stop pending I/O first... + abortIO( self ); + + // Mark future update transaction as IO transaction. + options.ioUpdate = true; + + self._ioPromise = promise + .then( resp => { + self._ioPromise = null; + + const result = thenDo ? thenDo( resp ) : resp; + + triggerAndBubble( self, 'sync', self, resp, options ); + + return result; + } ) + .catch( err => { + self._ioPromise = null; + + console.error( err ); + + triggerAndBubble( self, 'error', self, err, options ); + + throw err; + } ) as IOPromise; + + self._ioPromise.abort = promise.abort; + + return self._ioPromise; +} + +export function abortIO( self : IONode ){ + if( self._ioPromise && self._ioPromise.abort ){ + self._ioPromise.abort(); + self._ioPromise = null; + } +} + +export function triggerAndBubble( eventSource, ...args ){ + eventSource.trigger.apply( eventSource, args ); + const { collection } = eventSource; + collection && collection.trigger.apply( collection, args ); +} \ No newline at end of file diff --git a/src/type-r/object-plus/README.md b/src/type-r/object-plus/README.md new file mode 100644 index 0000000..6f58144 --- /dev/null +++ b/src/type-r/object-plus/README.md @@ -0,0 +1,121 @@ +# MixtureJS + +Mixins is very powerful abstraction addressing cross-cutting concerns, which can dramatically simplify inheritance graph when used wisely. + +MixtureJS is the toolkit combining React-style mixins, Backbone-style events, and minimal set of Underscore-style object manipulation functions. Just what you need when you're working in modern ES5/ES6 envorinment, packed in API which you already know. + +Written in TypeScript, works with ES5, ES6, and TypeScript. + +## Installation + +`npm install mixturejs` + +Packed as UMD, exports to global `Mixture` variable when included with script tag. + +> MixtureJS is the core part of [Volicon/Verizon](http://www.volicon.com/) technology stack - [Type-R](https://github.com/Volicon/Type-R), [NestedTypes](https://github.com/Volicon/NestedTypes), and [NestedReact](https://github.com/Volicon/NestedReact). + +## Events Performance + +MixtureJS _implements_ [Backbone API for Events](http://backbonejs.org/#Events), but it's entirely different internally. Here's the results of the typical +run of the [performance tests](https://github.com/Volicon/mixturejs/tree/master/tests) enclosed. + +![performance](https://raw.githubusercontent.com/Volicon/mixturejs/master/perf-chart.jpg) + +## Features + +- `Mixable`, React-style mixins implementation. + - Fine-grained control over member merge rules. + - Can mix both classes and plain objects. + - Works with and without ES6 class decorators. +- `Object.extend` to simulate classes in ES5. + - 100% backward compatible with Backbone `.extend()`. + - Complete `Mixable` support. + - Native properties declatations (`properties` specification). +- `Messenger`, synchronous events. + - Can be used as mixin and as a base class. + - 100% backward API compatibility with [Backbone Events](http://backbonejs.org/#Events) (passes Backbone 1.2.x unit test) + - Much faster than Backbone events. +- `tools` + - Object manipulation tools (`assign`, `defaults`, `mapObject`, etc). + - Simple logging API with variable log-level and overridable functions. Defaults to the `console`. + +## Backbone Events Compatibility + +`Mixture.Events` implements the complete semantic and API of [Backbone 1.1.x Events](http://backbonejs.org/#Events), with the following exceptions: + +- `source.trigger( 'ev1 ev2 ev3' )` is not supported. Use `source.trigger( 'ev1' ).trigger( 'ev2' ).trigger( 'ev3' )` instead. +- `source.trigger( 'ev', a, b, ... )` doesn't support more than 5 event parameters. +- `source.on( 'ev', callback )` - callback will _not_ be called in the context of `source` by default. + +## Mixins + +Both plain JS object and class constructor may be used as mixins. In the case of the class constructor, missing static members will copied over as well. + +You need to import `mixins` decorator to use mixins: + +```javascript +import { mixins } from 'mixturejs' + +... + +@mixins( plainObject, MyClass, ... ) +class X { + ... +} +``` + +### Merge Rules and React Compatibility + +MixtureJS implements _configurable_ merge rules, which allows to add standard React mixins functionality to the ES6 React Components. + +```javascript +import React from 'react' +import { Mixable } from 'mixturejs' + +// Make React.Component mixable... +Mixable.mixTo( React.Component ); + +// Define lifecycle methods merge rules... +React.Component.mixinRules({ + componentWillMount : 'reverse', + componentDidMount : 'reverse', + componentWillReceiveProps : 'reverse', + shouldComponentUpdate : 'some', + componentWillUpdate : 'reverse', + componentDidUpdate : 'reverse', + componentWillUnmount : 'sequence', +}); +``` + +Mixin merge rules can be extented in any subclass using the `@mixinRules({ attr : rule })` class decorator. Rule is the string from the following list. + +- *merge* - assume property to be an object, which members taken from mixins must be merged. +- *pipe* - property is the function `( x : T ) => T` transforming the value. Multiple functions joined in pipe. +- *sequence* - property is the function. Multiple functions will be called in sequence. +- *reverse* - same as *sequence*, but functions called in reverse sequence. +- *mergeSequence* - merge the object returned by functions, executing them in sequence. +- *every* - property is the function `( ...args : any[] ) => boolean`. Resulting method will return true if every single function returns true. +- *some* - same as previous, but method will return true when at least one function returns true. + +If merge rule is an object, the corresponding member is expected to be an object and the rule defines the merge rules for its members. + +### Usage Example + +Here we adding [Events](http://backbonejs.org/#Events) support (on, off, trigger, listenTo, etc.): + +```javascript +import React from 'react' +import { mixins, Events } from 'mixturejs' + +const UnsubscribeMixin = { + componentWillUnmount(){ + this.off(); + this.stopListening(); + } +} + +@mixins( Events, UnsubscribeMixin ) +class EventedComponent extends React.Component { + // ... +} +``` \ No newline at end of file diff --git a/src/type-r/object-plus/events.ts b/src/type-r/object-plus/events.ts new file mode 100644 index 0000000..da6e241 --- /dev/null +++ b/src/type-r/object-plus/events.ts @@ -0,0 +1,210 @@ +import { define, mixins, Mixable, Mixin, MixableConstructor, MixinsState, mixinRules, definitions, MixinMergeRules } from './mixins' +import { omit, transform } from './tools' +import { EventMap, EventsDefinition, EventSource, HandlersByEvent } from './eventsource' +import * as _eventsApi from './eventsource' + +const { EventHandler, strings, on, off, once, trigger5, trigger2, trigger3 } = _eventsApi; + +/** @hidden */ +const eventSplitter = /\s+/; + +/** @hidden */ +let _idCount = 0; + +/** @hidden */ +function uniqueId() : string { + return 'l' + _idCount++; +} + +export { EventMap, EventsDefinition } + +export interface MessengerDefinition { + _localEvents? : EventMap + localEvents? : EventsDefinition + properties? : PropertyMap + [ name : string ] : any +} + +export interface PropertyMap { + [ name : string ] : Property +} + +export type Property = PropertyDescriptor | ( () => any ) + +/** @hidden */ +export interface MessengersByCid { + [ cid : string ] : Messenger +} + +/** @hidden */ +export type CallbacksByEvents = { [ events : string ] : Function } + +/************************* + * Messenger is mixable class with capabilities of sending and receiving synchronous events. + * This class itself can serve as both mixin and base class. + */ + +@define +@definitions({ + properties : mixinRules.merge, + localEvents : mixinRules.merge +}) +export abstract class Messenger implements Mixable, EventSource { + // Define extendable mixin static properties. + static __super__ : object; + static mixins : MixinsState; + static onExtend : ( BaseClass : Function ) => void; + static define : ( definition? : MessengerDefinition, statics? : object ) => MixableConstructor; + static extend : ( definition? : MessengerDefinition, statics? : object ) => MixableConstructor; + static onDefine({ localEvents, _localEvents, properties } : MessengerDefinition, BaseClass? : typeof Mixable ){ + // Handle localEvents definition + if( localEvents || _localEvents ){ + const eventsMap = new EventMap( this.prototype._localEvents ); + + localEvents && eventsMap.addEventsMap( localEvents ); + _localEvents && eventsMap.merge( _localEvents ); + + this.prototype._localEvents = eventsMap; + } + + // Handle properties definitions... + if( properties ){ + Object.defineProperties( this.prototype, transform( {}, properties, toPropertyDescriptor ) ); + } + } + + /** @hidden */ + _events : HandlersByEvent = void 0; + + /** @hidden */ + _listeningTo : MessengersByCid = void 0 + + /** Unique client-only id. */ + cid : string + + /** @hidden Prototype-only property to manage automatic local events subscription */ + _localEvents : EventMap + + /** @hidden */ + constructor(){ + this.cid = uniqueId(); + this.initialize.apply( this, arguments ); + + // TODO: local events subscribe? + } + + /** Method is called at the end of the constructor */ + initialize() : void {} + + on( events : string | CallbacksByEvents, callback, context? ) : this { + if( typeof events === 'string' ) strings( on, this, events, callback, context ); + else for( let name in events ) strings( on, this, name, events[ name ], context || callback ); + + return this; + } + + once( events : string | CallbacksByEvents, callback, context? ) : this { + if( typeof events === 'string' ) strings( once, this, events, callback, context ); + else for( let name in events ) strings( once, this, name, events[ name ], context || callback ); + + return this; + } + + off( events? : string | CallbacksByEvents, callback?, context? ) : this { + if( !events ) off( this, void 0, callback, context ); + else if( typeof events === 'string' ) strings( off, this, events, callback, context ); + else for( let name in events ) strings( off, this, name, events[ name ], context || callback ); + + return this; + } + + // Trigger one or many events, firing all bound callbacks. Callbacks are + // passed the same arguments as `trigger` is, apart from the event name + // (unless you're listening on `"all"`, which will cause your callback to + // receive the true name of the event as the first argument). + trigger(name : string, a?, b?, c?, d?, e? ) : this { + if( d !== void 0 || e !== void 0 ) trigger5( this, name, a, b, c, d, e ); + else if( c !== void 0 ) trigger3( this, name, a, b, c ); + else trigger2( this, name, a, b ); + return this; + } + + listenTo( source : Messenger, a : string | CallbacksByEvents, b? : Function ) : this { + if( source ){ + addReference( this, source ); + source.on( a, !b && typeof a === 'object' ? this : b, this ); + } + + return this; + } + + listenToOnce( source : Messenger, a : string | CallbacksByEvents, b? : Function ) : this { + if( source ){ + addReference( this, source ); + source.once( a, !b && typeof a === 'object' ? this : b, this ); + } + + return this; + } + + stopListening( a_source? : Messenger, a? : string | CallbacksByEvents, b? : Function ) : this { + const { _listeningTo } = this; + if( _listeningTo ){ + const removeAll = !( a || b ), + second = !b && typeof a === 'object' ? this : b; + + if( a_source ){ + const source = _listeningTo[ a_source.cid ]; + if( source ){ + if( removeAll ) delete _listeningTo[ a_source.cid ]; + source.off( a, second, this ); + } + } + else if( a_source == null ){ + for( let cid in _listeningTo ) _listeningTo[ cid ].off( a, second, this ); + + if( removeAll ) ( this._listeningTo = void 0 ); + } + } + + return this; + } + + /** + * Destructor. Stops messenger from listening to all objects, + * and stop others from listening to the messenger. + */ + _disposed : boolean + + dispose() : void { + if( this._disposed ) return; + + this.stopListening(); + this.off(); + + this._disposed = true; + } +} + +/** + * Backbone 1.2 API conformant Events mixin. + */ +export const Events : Messenger = omit( Messenger.prototype, 'constructor', 'initialize' ); + +/** + * Messenger Private Helpers + */ + +function toPropertyDescriptor( x : Property ) : PropertyDescriptor { + if( x ){ + return typeof x === 'function' ? { get : < () => any >x } : x; + } +} + +/** @hidden */ +function addReference( listener : Messenger, source : Messenger ){ + const listeningTo = listener._listeningTo || (listener._listeningTo = Object.create( null ) ), + cid = source.cid || ( source.cid = uniqueId() ); + + listeningTo[ cid ] = source; +} \ No newline at end of file diff --git a/src/type-r/object-plus/eventsource.ts b/src/type-r/object-plus/eventsource.ts new file mode 100644 index 0000000..e55c4fd --- /dev/null +++ b/src/type-r/object-plus/eventsource.ts @@ -0,0 +1,273 @@ +import { once as _once } from './tools' + +/******************* + * Prebuilt events map, used for optimized bulk event subscriptions. + * + * const events = new EventMap({ + * 'change' : true, // Resend this event from self as it is. + * 'change:attr' : 'localTargetFunction', + * 'executedInTargetContext' : function(){ ... } + * 'executedInNativeContext' : '^props.handler' + * }) + */ +/** @hidden */ +export interface EventsDefinition { + [ events : string ] : Function | string | boolean +} + +/** @hidden */ +export class EventMap { + handlers : EventDescriptor[] = []; + + constructor( map? : EventsDefinition | EventMap ){ + if( map ){ + if( map instanceof EventMap ){ + this.handlers = map.handlers.slice(); + } + else{ + map && this.addEventsMap( map ); + } + } + } + + merge( map : EventMap ){ + this.handlers = this.handlers.concat( map.handlers ); + } + + addEventsMap( map : EventsDefinition ){ + for( let names in map ){ + this.addEvent( names, map[ names ] ) + } + } + + bubbleEvents( names : string ){ + for( let name of names.split( eventSplitter ) ){ + this.addEvent( name, getBubblingHandler( name ) ); + } + } + + addEvent( names : string, callback : Function | string | boolean ){ + const { handlers } = this; + + for( let name of names.split( eventSplitter ) ){ + handlers.push( new EventDescriptor( name, callback ) ); + } + } + + subscribe( target : {}, source : EventSource ){ + for( let event of this.handlers ){ + on( source, event.name, event.callback, target ); + } + } + + unsubscribe( target : {}, source : EventSource ){ + for( let event of this.handlers ){ + off( source, event.name, event.callback, target ); + } + } +} + +/** @hidden */ +export class EventDescriptor { + callback : Function + + constructor( + public name : string, + callback : Function | string | boolean + ){ + if( callback === true ){ + this.callback = getBubblingHandler( name ); + } + else if( typeof callback === 'string' ){ + this.callback = + function localCallback(){ + const handler = this[ callback ]; + handler && handler.apply( this, arguments ); + }; + } + else{ + this.callback = callback; + } + } +} + +/** @hidden */ +const _bubblingHandlers = {}; + +/** @hidden */ +function getBubblingHandler( event : string ){ + return _bubblingHandlers[ event ] || ( + _bubblingHandlers[ event ] = function( a?, b?, c?, d?, e? ){ + if( d !== void 0 || e !== void 0 ) trigger5( this, event, a, b, c, d, e ); + if( c !== void 0 ) trigger3( this, event, a, b, c ); + else trigger2( this, event, a, b ); + } + ); +} + +/** @hidden */ +export interface HandlersByEvent { + [ name : string ] : EventHandler +} + +/** @hidden */ +export class EventHandler { + constructor( public callback : Callback, public context : any, public next = null ){} +} + +/** @hidden */ +function listOff( _events : HandlersByEvent, name : string, callback : Callback, context : any ){ + const head = _events[ name ]; + + let filteredHead, prev; + + for( let ev = head; ev; ev = ev.next ){ + // Element must be kept + if( ( callback && callback !== ev.callback && callback !== ev.callback._callback ) || + ( context && context !== ev.context ) ){ + + prev = ev; + filteredHead || ( filteredHead = ev ); + } + // Element must be skipped + else{ + if( prev ) prev.next = ev.next; + } + } + + if( head !== filteredHead ) _events[ name ] = filteredHead; +} + +/** @hidden */ +function listSend2( head : EventHandler, a, b ){ + for( let ev = head; ev; ev = ev.next ) ev.callback.call( ev.context, a, b ); +} + +/** @hidden */ +function listSend3( head : EventHandler, a, b, c ){ + for( let ev = head; ev; ev = ev.next ) ev.callback.call( ev.context, a, b, c ); +} + +/** @hidden */ +function listSend4( head : EventHandler, a, b, c, d ){ + for( let ev = head; ev; ev = ev.next ) ev.callback.call( ev.context, a, b, c, d ); +} + +/** @hidden */ +function listSend5( head : EventHandler, a, b, c, d, e ){ + for( let ev = head; ev; ev = ev.next ) ev.callback.call( ev.context, a, b, c, d, e ); +} + +/** @hidden */ +function listSend6( head : EventHandler, a, b, c, d, e, f ){ + for( let ev = head; ev; ev = ev.next ) ev.callback.call( ev.context, a, b, c, d, e, f ); +} + +/** @hidden */ +export interface Callback extends Function { + _callback? : Function +} + +/** @hidden */ +export function on( source : EventSource, name : string, callback : Callback, context? : any ) : void { + if( callback ){ + const _events = source._events || ( source._events = Object.create( null ) ); + _events[ name ] = new EventHandler( callback, context, _events[ name ] ); + } +} + +/** @hidden */ +export function once( source : EventSource, name : string, callback : Callback, context? : any ) : void { + if( callback ){ + const once : Callback = _once( function(){ + off( source, name, once ); + callback.apply(this, arguments); + }); + + once._callback = callback; + on( source, name, once, context ); + } +} + +/** @hidden */ +export function off( source : EventSource, name? : string, callback? : Callback, context? : any ) : void { + const { _events } = source; + if( _events ){ + if( callback || context ) { + if( name ){ + listOff( _events, name, callback, context ); + } + else{ + for( let name in _events ){ + listOff( _events, name, callback, context ); + } + } + } + else if( name ){ + _events[ name ] = void 0; + } + else{ + source._events = void 0; + } + } +} + +/** @hidden */ +export interface EventSource { + _events : HandlersByEvent +} + +/** @hidden */ +const eventSplitter = /\s+/; + +/** @hidden */ +export function strings( api : ApiEntry, source : EventSource, events : string, callback : Callback, context ){ + if( eventSplitter.test( events ) ){ + const names = events.split( eventSplitter ); + for( let name of names ) api( source, name, callback, context ); + } + else api( source, events, callback, context ); +} + +/** @hidden */ +export type ApiEntry = ( source : EventSource, event : string, callback : Callback, context? : any ) => void + +/********************************* + * Event-triggering API + */ + +/** @hidden */ +export function trigger2( self : EventSource, name : string, a, b ) : void { + const { _events } = self; + if( _events ){ + const queue = _events[ name ], + { all } = _events; + + listSend2( queue, a, b ); + listSend3( all, name, a, b ); + } +}; + +/** @hidden */ +export function trigger3( self : EventSource, name : string, a, b, c ) : void{ + const { _events } = self; + if( _events ){ + const queue = _events[ name ], + { all } = _events; + + listSend3( queue, a, b, c ); + listSend4( all, name, a, b, c ); + } +}; + +/** @hidden */ +export function trigger5( self : EventSource, name : string, a, b, c, d, e ) : void{ + const { _events } = self; + if( _events ){ + const queue = _events[ name ], + { all } = _events; + + listSend5( queue, a, b, c, d, e ); + listSend6( all, name, a, b, c, d, e ); + } +}; \ No newline at end of file diff --git a/src/type-r/object-plus/index.ts b/src/type-r/object-plus/index.ts new file mode 100644 index 0000000..d08fb80 --- /dev/null +++ b/src/type-r/object-plus/index.ts @@ -0,0 +1,28 @@ +// (c) 2016 Vlad Balin and Volicon +// MixtureJS may be freely distributed under the MIT license. + +import * as tools from './tools' +export { tools } +export * from './mixins' +export * from './events' +import * as eventsApi from './eventsource' +export { eventsApi } + +import { Mixable, MixableConstructor } from './mixins' + +declare global { + interface ObjectConstructor { + /** Polyfill for Object.assign */ + assign< T >( dest : T, ...sources : Object[] ) : T + + /** Global logging interface, for console debugging. */ + log : tools.Log + + /** ES5 Object.extend */ + extend( protoProps : {}, staticProps : {} ) : MixableConstructor + } +} + +Object.extend = ( protoProps, staticProps ) => Mixable.extend( protoProps, staticProps ); +Object.assign || ( Object.assign = tools.assign ); +Object.log = tools.log; \ No newline at end of file diff --git a/src/type-r/object-plus/mixins.ts b/src/type-r/object-plus/mixins.ts new file mode 100644 index 0000000..086faa0 --- /dev/null +++ b/src/type-r/object-plus/mixins.ts @@ -0,0 +1,407 @@ +/***************************************************************** + * Mixins engine and @define metaprogramming class extensions + * + * Vlad Balin & Volicon, (c) 2016-2017 + */ +import { log, assign, omit, hashMap, getPropertyDescriptor, getBaseClass, defaults, transform } from './tools' +import { __extends } from 'tslib' + +export interface Subclass< T > extends MixableConstructor { + new ( ...args ) : T + prototype : T +} + +export interface MixableConstructor extends Function{ + __super__? : object; + mixins? : MixinsState; + onExtend? : ( BaseClass : Function ) => void; + onDefine? : ( definition : object, BaseClass : Function ) => void; + define? : ( definition? : object, statics? : object ) => MixableConstructor; + extend? : ( definition? : T, statics? : object ) => Subclass; +} + +export interface MixableDefinition { + mixins? : Mixin[] +} + +/** + * Base class, holding metaprogramming class extensions. + * Supports mixins and Class.define metaprogramming method. + */ +export class Mixable { + static onExtend : ( BaseClass : Function ) => void; + static onDefine : ( definition : object, BaseClass : Function ) => object; + static __super__ : object + static mixins : MixinsState; + + /** + * Must be called after inheritance and before 'define'. + */ + static define( protoProps : MixableDefinition = {}, staticProps? : object ) : MixableConstructor { + const BaseClass : MixableConstructor = getBaseClass( this ); + + // Assign statics. + staticProps && assign( this, staticProps ); + + // Extract and apply mixins from the definition. + const { mixins, ...defineMixin } = protoProps; + mixins && this.mixins.merge( mixins ); + + // Unshift definition to the the prototype. + this.mixins.mergeObject( this.prototype, defineMixin, true ); + + // Unshift definition from statics to the prototype. + this.mixins.mergeObject( this.prototype, this.mixins.getStaticDefinitions( BaseClass ), true ); + + // Call onDefine hook, if it's present. + this.onDefine && this.onDefine( this.mixins.definitions, BaseClass ); + + // Apply merge rules to inherited members. No mixins can be added after this point. + this.mixins.mergeInheritedMembers( BaseClass ); + + return this; + } + + /** Backbone-compatible extend method to be used in ES5 and for backward compatibility */ + static extend< T extends object>(spec? : T, statics? : {} ) : Subclass< T > { + let TheSubclass : Subclass< T >; + + // 1. Create the subclass (ES5 compatibility shim). + // If constructor function is given... + if( spec && spec.hasOwnProperty( 'constructor' ) ){ + // ...we need to manually call internal TypeScript __extend function. Hack! Hack! + TheSubclass = spec.constructor as any; + __extends( TheSubclass, this ); + } + // Otherwise, create the subclall in usual way. + else{ + TheSubclass = class Subclass extends this {} as any; + } + + predefine( TheSubclass ); + spec && TheSubclass.define( spec, statics ); + + return TheSubclass; + } +} + +/** @decorator `@predefine` for forward definitions. Can be used with [[Mixable]] classes only. + * Forwards the call to the [[Mixable.predefine]]; + */ +export function predefine( Constructor : MixableConstructor ) : void { + const BaseClass : MixableConstructor = getBaseClass( Constructor ); + + // Legacy systems support + Constructor.__super__ = BaseClass.prototype; + + // Initialize mixins structures... + Constructor.define || MixinsState.get( Mixable ).populate( Constructor ); + + // Make sure Ctor.mixins are ready before the callback... + MixinsState.get( Constructor ); + + // Call extend hook. + Constructor.onExtend && Constructor.onExtend( BaseClass ); +} + +/** @decorator `@define` for metaprogramming magic. Can be used with [[Mixable]] classes only. + * Forwards the call to [[Mixable.define]]. + */ +export function define( ClassOrDefinition : Function ) : void; +export function define( ClassOrDefinition : object ) : ClassDecorator; +export function define( ClassOrDefinition : object | MixableConstructor ){ + // @define class + if( typeof ClassOrDefinition === 'function' ){ + predefine( ClassOrDefinition ); + ClassOrDefinition.define(); + } + // @define({ prop : val, ... }) class + else{ + return function( Ctor : MixableConstructor ){ + predefine( Ctor ); + Ctor.define( ClassOrDefinition ); + } + } +} + +export function definitions( rules : MixinMergeRules ) : ClassDecorator { + return ( Class : Function ) => { + const mixins = MixinsState.get( Class ); + mixins.definitionRules = defaults( hashMap(), rules, mixins.definitionRules ); + } +} + +// Create simple property list decorator +export function propertyListDecorator( listName: string ) : PropertyDecorator { + return function propList(proto, name : string) { + const list = proto.hasOwnProperty( listName ) ? + proto[ listName ] : (proto[ listName ] = (proto[ listName ] || []).slice()); + + list.push(name); + } +} + +export function definitionDecorator( definitionKey, value ){ + return ( proto : object, name : string ) => { + MixinsState + .get( proto.constructor ) + .mergeObject( proto, { + [ definitionKey ] : { + [ name ] : value + } + }); + } +} + +export class MixinsState { + mergeRules : MixinMergeRules; + definitionRules : MixinMergeRules; + definitions : object = {}; + appliedMixins : Mixin[]; + + // Return mixins state for the class. Initialize if it's not exist. + static get( Class ) : MixinsState { + const { mixins } = Class; + + return mixins && Class === mixins.Class ? mixins : + Class.mixins = new MixinsState( Class ); + } + + constructor( public Class : MixableConstructor ){ + const { mixins } = getBaseClass( Class ); + + this.mergeRules = ( mixins && mixins.mergeRules ) || hashMap(); + this.definitionRules = ( mixins && mixins.definitionRules ) || hashMap(); + this.appliedMixins = ( mixins && mixins.appliedMixins ) || []; + } + + getStaticDefinitions( BaseClass : Function ){ + const definitions = hashMap(), + { Class } = this; + + return transform( definitions, this.definitionRules, ( rule, name ) =>{ + if( BaseClass[ name ] !== Class[ name ]){ + return Class[ name ]; + } + }); + } + + merge( mixins : Mixin[] ){ + const proto = this.Class.prototype, + { mergeRules } = this; + + // Copy applied mixins array as it's going to be updated. + const appliedMixins = this.appliedMixins = this.appliedMixins.slice(); + + // Apply mixins in sequence... + for( let mixin of mixins ) { + // Mixins array should be flattened. + if( Array.isArray( mixin ) ) { + this.merge( mixin ); + } + // Don't apply mixins twice. + else if( appliedMixins.indexOf( mixin ) < 0 ){ + appliedMixins.push( mixin ); + + // For constructors, merge _both_ static and prototype members. + if( typeof mixin === 'function' ){ + // Merge static members + this.mergeObject( this.Class, mixin ); + + // merge definitionRules and mergeRules + const sourceMixins = ( mixin as any ).mixins; + if( sourceMixins ){ + this.mergeRules = defaults( hashMap(), this.mergeRules, sourceMixins.mergeRules ); + this.definitionRules = defaults( hashMap(), this.definitionRules, sourceMixins.definitionRules ); + this.appliedMixins = this.appliedMixins.concat( sourceMixins.appliedMixins ); + } + + // Prototypes are merged according with rules. + this.mergeObject( proto, mixin.prototype ); + } + // Handle plain object mixins. + else { + this.mergeObject( proto, mixin ); + } + } + } + } + + populate( ...ctors : Function[] ){ + for( let Ctor of ctors ) { + MixinsState.get( Ctor ).merge([ this.Class ]); + } + } + + mergeObject( dest : object, source : object, unshift? : boolean ) { + forEachOwnProp( source, name => { + const sourceProp = Object.getOwnPropertyDescriptor( source, name ); + let rule : MixinMergeRule; + + if( rule = this.definitionRules[ name ] ){ + assignProperty( this.definitions, name, sourceProp, rule, unshift ); + } + + if( !rule || rule === mixinRules.protoValue ){ + assignProperty( dest, name, sourceProp, this.mergeRules[ name ], unshift ); + } + }); + } + + mergeInheritedMembers( BaseClass : Function ){ + const { mergeRules, Class } = this; + + if( mergeRules ){ + const proto = Class.prototype, + baseProto = BaseClass.prototype; + + for( let name in mergeRules ) { + const rule = mergeRules[ name ]; + + if( proto.hasOwnProperty( name ) && name in baseProto ){ + proto[ name ] = resolveRule( proto[ name ], baseProto[ name ], rule ); + } + } + } + } +} + +const dontMix = { + function : hashMap({ + length : true, + prototype : true, + caller : true, + arguments : true, + name : true, + __super__ : true + }), + + object : hashMap({ + constructor : true + }) +} + +function forEachOwnProp( object : object, fun : ( name : string ) => void ){ + const ignore = dontMix[ typeof object ]; + + for( let name of Object.keys( object ) ) { + ignore[ name ] || fun( name ); + } +} + +export interface MixinMergeRules { + [ name : string ] : MixinMergeRule +} + +export type MixinMergeRule = ( a : any, b : any ) => any +export type Mixin = { [ key : string ] : any } | Function + +// @mixins( A, B, ... ) decorator. +export interface MixinRulesDecorator { + ( rules : MixinMergeRules ) : ClassDecorator + value( a : object, b : object) : object; + protoValue( a : object, b : object) : object; + merge( a : object, b : object ) : object; + pipe( a: Function, b : Function ) : Function; + defaults( a: Function, b : Function ) : Function; + classFirst( a: Function, b : Function ) : Function; + classLast( a: Function, b : Function ) : Function; + every( a: Function, b : Function ) : Function; + some( a: Function, b : Function ) : Function; +} + +export const mixins = ( ...list : Mixin[] ) => ( + ( Class : Function ) => MixinsState.get( Class ).merge( list ) +); + +// @mixinRules({ name : rule, ... }) decorator. +export const mixinRules = ( ( rules : MixinMergeRules ) => ( + ( Class : Function ) => { + const mixins = MixinsState.get( Class ); + mixins.mergeRules = defaults( rules, mixins.mergeRules ); + } +) ) as MixinRulesDecorator; + +// Pre-defined mixin merge rules + +mixinRules.value = ( a, b ) => a; + +mixinRules.protoValue = ( a, b ) => a; + +// Recursively merge members +mixinRules.merge = ( a, b ) => defaults( {}, a, b ); + + // Execute methods in pipe, with the class method executed last. +mixinRules.pipe = ( a, b ) => ( + function( x : any ) : any { + return a.call( this, b.call( this, x ) ); + } +); + + // Assume methods return an object, and merge results with defaults (class method executed first) +mixinRules.defaults = ( a : Function, b : Function ) => ( + function() : object { + return defaults( a.apply( this, arguments ), b.apply( this, arguments ) ); + } +); + +// Execute methods in sequence staring with the class method. +mixinRules.classFirst = ( a : Function, b : Function ) => ( + function() : void { + a.apply( this, arguments ); + b.apply( this, arguments ); + } +); + + // Execute methods in sequence ending with the class method. +mixinRules.classLast = ( a : Function, b : Function ) => ( + function() : void { + b.apply( this, arguments ); + a.apply( this, arguments ); + } +) + + // Execute methods in sequence returning the first falsy result. +mixinRules.every = ( a : Function, b : Function ) =>( + function() : any { + return a.apply( this, arguments ) && b.apply( this, arguments ); + } +); + // Execute methods in sequence returning the first truthy result. +mixinRules.some = ( a : Function, b : Function ) =>( + function() : any { + return a.apply( this, arguments ) || b.apply( this, arguments ); + } +); + +/** + * Helpers + */ + +function assignProperty( dest : object, name : string, sourceProp : PropertyDescriptor, rule : MixinMergeRule, unshift? : boolean ){ +// Destination prop is defined, thus the merge rules must be applied. + if( dest.hasOwnProperty( name ) ){ + const destProp = Object.getOwnPropertyDescriptor( dest, name ); + + if( destProp.configurable && 'value' in destProp ){ + dest[ name ] = unshift ? + resolveRule( sourceProp.value, destProp.value, rule ) : + resolveRule( destProp.value, sourceProp.value, rule ) ; + } + } + // If destination is empty, just copy the prop over. + else{ + Object.defineProperty( dest, name, sourceProp ); + } +} + +function resolveRule( dest, source, rule : MixinMergeRule ){ + // When destination is empty, take the source. + if( dest === void 0 ) return source; + + // In these cases we take non-empty destination: + if( !rule || source === void 0 ) return dest; + + // In other cases we must merge values. + return rule( dest, source ); +} \ No newline at end of file diff --git a/src/type-r/object-plus/tools.ts b/src/type-r/object-plus/tools.ts new file mode 100644 index 0000000..479646d --- /dev/null +++ b/src/type-r/object-plus/tools.ts @@ -0,0 +1,367 @@ +/** + * Simple overridable logging stubs, writing to `console` by default. + * Node.js users might want to redirect logging somewhere. + * + * This is the singleton avaliable globally through `Object.log` or + * exported [[log]] variable. + */ + + /** Similar to underscore `_.defaults` */ +export function defaults< T >( dest : T, ...sources : Object[] ) : T +export function defaults< T >( dest : T, source : Object ) : T { + for( var name in source ) { + if( source.hasOwnProperty( name ) && !dest.hasOwnProperty( name ) ) { + dest[ name ] = source[ name ]; + } + } + + if( arguments.length > 2 ){ + for( let i = 2; i < arguments.length; i++ ){ + const other = arguments[ i ]; + other && defaults( dest, other ); + } + } + + return dest; +} + +// Logger is the function. +export type Logger = ( level : LogLevel, error : string, props? : object ) => void; + +export type LogLevel = 'none' | 'error' | 'warn' | 'info' | 'debug' | 'log'; + +const levelToNumber = { + none : 0, error : 1, warn : 2, info : 3, log : 4, debug : 5 +} + +export interface Log extends Logger { + level : number + throw : number + stop : number + logger : Logger +} + +export const log : Log = function( a_level : LogLevel, a_msg : string, a_props : object ){ + let levelAsNumber = levelToNumber[ a_level ], msg, props, level; + + if( levelAsNumber === void 0 && !a_props ){ + levelAsNumber = 4; + msg = a_level; + props = a_msg; + level = 'log'; + } + else{ + msg = a_msg, level = a_level, props = a_props; + } + + if( levelAsNumber <= log.level ){ + if( levelAsNumber <= log.throw || !log.logger ){ + const error = new Error( msg ); + (error as any).props = props; + throw error; + } + else{ + log.logger( level, msg, props ); + + if( levelAsNumber <= log.stop ){ + debugger; + } + } + } +} + +declare var process: any; + +log.level = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'production' ? 1 : 2; +log.throw = 0; +log.stop = 0; + + +let toString = typeof window === 'undefined' ? + function toString( something ){ + if( something && typeof something === 'object' ){ + const value = something.__inner_state__ || something, + isTransactional = Boolean( something.__inner_state__ ), + isArray = Array.isArray( value ); + + const keys = Object.keys( value ).join( ', ' ), + body = isArray ? `[ length = ${ value.length } ]` : `{ ${ keys } }`; + + return something.constructor.name + ' ' + body; + } + + return something; + } : function toString( x ){ return x; }; + +if( typeof console !== 'undefined' ) { + log.logger = function _console( level : LogLevel, error : string, props : object ){ + const args = [ error ]; + for( let name in props ){ + args.push( `\n\t${name}:`, toString( props[ name ] ) ); + } + + console[ level ].apply( console, args ); + } +} + +/** Check if value is raw JSON */ +export function isValidJSON( value : any ) : boolean { + if( value === null ){ + return true; + } + + switch( typeof value ){ + case 'number' : + case 'string' : + case 'boolean' : + return true; + + case 'object': + var proto = Object.getPrototypeOf( value ); + + if( proto === Object.prototype || proto === Array.prototype ){ + return every( value, isValidJSON ); + } + } + + return false; +} + +/** Get the base class constructor function. + * @param Class Subclass constructor function. + * @returns Base class constructor function. + */ +export function getBaseClass( Class : Function ) { + return Object.getPrototypeOf( Class.prototype ).constructor +} + +export function assignToClassProto( Class, definition : T, ...names : K[] ) : void { + for( let name of names ){ + const value = definition[ name ]; + value === void 0 || ( Class.prototype[ name ] = value ); + } +} + +/** Checks whenever given object is an empty hash `{}` */ +export function isEmpty( obj : {} ) : boolean { + if( obj ){ + for( let key in obj ){ + if( obj.hasOwnProperty( key ) ){ + return false; + } + } + } + + return true; +} + +export type Iteratee = ( value : any, key? : string | number ) => any; + +/** @hidden */ +function someArray( arr : any[], fun : Iteratee ) : any { + let result; + + for( let i = 0; i < arr.length; i++ ){ + if( result = fun( arr[ i ], i ) ){ + return result; + } + } +} + +/** @hidden */ +function someObject( obj : {}, fun : Iteratee ) : any { + let result; + + for( let key in obj ){ + if( obj.hasOwnProperty( key ) ){ + if( result = fun( obj[ key ], key ) ){ + return result; + } + } + } +} + +/** Similar to underscore `_.some` */ +export function some( obj, fun : Iteratee ) : any { + if( Object.getPrototypeOf( obj ) === ArrayProto ){ + return someArray( obj, fun ); + } + else{ + return someObject( obj, fun ); + } +} + +/** Similar to underscore `_.every` */ +export function every( obj : { }, predicate : Iteratee ) : boolean { + return !some( obj, x => !predicate( x ) ); +} + +/** Similar to `getOwnPropertyDescriptor`, but traverse the whole prototype chain. */ +export function getPropertyDescriptor( obj : {}, prop : string ) : PropertyDescriptor { + let desc : PropertyDescriptor; + + for( let proto = obj; !desc && proto; proto = Object.getPrototypeOf( proto ) ) { + desc = Object.getOwnPropertyDescriptor( proto, prop ); + } + + return desc; +} + +/** Similar to underscore `_.omit` */ +export function omit( source : {}, ...rest : string[] ) : {} +export function omit( source ) : {} { + const dest = {}, discard = {}; + + for( let i = 1; i < arguments.length; i ++ ){ + discard[ arguments[ i ] ] = true; + } + + for( var name in source ) { + if( !discard.hasOwnProperty( name ) && source.hasOwnProperty( name ) ) { + dest[ name ] = source[ name ]; + } + } + + return dest; +} + +/** map `source` object properties with a given function, and assign the result to the `dest` object. + * When `fun` returns `undefined`, skip this value. + */ +export function transform< A, B >( dest : { [ key : string ] : A }, source : { [ key : string ] : B }, fun : ( value : B, key : string ) => A | void ) : { [ key : string ] : A } { + for( var name in source ) { + if( source.hasOwnProperty( name ) ) { + var value = fun( source[ name ], name ); + value === void 0 || ( dest[ name ] = < A >value ); + } + } + + return dest; +} + +/** @hidden */ +export function fastAssign< A >( dest : A, source : {} ) : A { + for( var name in source ) { + dest[ name ] = source[ name ]; + } + + return dest; +} + +/** @hidden */ +export function fastDefaults< A >( dest : A, source : {} ) : A { + for( var name in source ) { + if( dest[ name ] === void 0 ){ + dest[ name ] = source[ name ]; + } + } + + return dest; +} + +/** Similar to underscore `_.extend` and `Object.assign` */ +export function assign< T >( dest : T, ...sources : Object[] ) : T +export function assign< T >( dest : T, source : Object ) : T { + for( var name in source ) { + if( source.hasOwnProperty( name ) ) { + dest[ name ] = source[ name ]; + } + } + + if( arguments.length > 2 ){ + for( let i = 2; i < arguments.length; i++ ){ + const other = arguments[ i ]; + other && assign( dest, other ); + } + } + + return dest; +} + +/** Similar to underscore `_.keys` */ +export function keys( o : any ) : string[]{ + return o ? Object.keys( o ) : []; +} + +/** Similar to underscore `_.once` */ +export function once( func : Function ) : Function { + var memo, first = true; + return function() { + if ( first ) { + first = false; + memo = func.apply(this, arguments); + func = null; + } + return memo; + }; +} + +/** @hidden */ +const ArrayProto = Array.prototype, + DateProto = Date.prototype, + ObjectProto = Object.prototype; + +/** + * Determine whenever two values are not equal, deeply traversing + * arrays and plain JS objects (hashes). Dates are compared by enclosed timestamps, all other + * values are compared with strict comparison. + */ +export function notEqual( a : any, b : any) : boolean { + if( a === b ) return false; + + if( a && b && typeof a == 'object' && typeof b == 'object' ) { + const protoA = Object.getPrototypeOf( a ); + + if( protoA !== Object.getPrototypeOf( b ) ) return true; + + switch( protoA ){ + case DateProto : return +a !== +b; + case ArrayProto : return arraysNotEqual( a, b ); + case ObjectProto : + case null: + return objectsNotEqual( a, b ); + } + } + + return true; +} + +/** @hidden */ +function objectsNotEqual( a, b ) { + const keysA = Object.keys( a ); + + if( keysA.length !== Object.keys( b ).length ) return true; + + for( let i = 0; i < keysA.length; i++ ) { + const key = keysA[ i ]; + + if( !b.hasOwnProperty( key ) || notEqual( a[ key ], b[ key ] ) ) { + return true; + } + } + + return false; +} + +/** @hidden */ +function arraysNotEqual( a, b ) { + if( a.length !== b.length ) return true; + + for( let i = 0; i < a.length; i++ ) { + if( notEqual( a[ i ], b[ i ] ) ) return true; + } + + return false; +} + +/** + * Create an object without Object prototype members except hasOwnProperty. + * @param obj - optional parameter to populate the hash map from. + */ +const HashProto = Object.create( null ); +HashProto.hasOwnProperty = ObjectProto.hasOwnProperty; + +export function hashMap( obj? ){ + const hash = Object.create( HashProto ); + return obj ? assign( hash, obj ) : hash; +} \ No newline at end of file diff --git a/src/type-r/record/README.md b/src/type-r/record/README.md new file mode 100644 index 0000000..79c13b4 --- /dev/null +++ b/src/type-r/record/README.md @@ -0,0 +1,14 @@ +# Record transactional core + +## Dependencies + + index.ts + ↑ ↑ + | | + | define.ts + | ↑ basicTypes.ts + | | ↗ + | attribute.ts → nestedTypes.ts + | ↑ / + | | / + transactions.ts diff --git a/src/type-r/record/TODO.md b/src/type-r/record/TODO.md new file mode 100644 index 0000000..9dc3fd4 --- /dev/null +++ b/src/type-r/record/TODO.md @@ -0,0 +1,145 @@ +# Records todo list + +(!) Add merge option to the record.set. +So, set must accept and pass through: add, remove, merge. + + + +Okay. So. + +transaction.ts (needs to be renamed to record.ts) will me the base thingy. +Keep all definitions with relates to Record there. +This includes definition (but not implementation) of the Record.define method. + +attribute.ts - imports transaction.ts, implements Attribute base class and factory. + +basicTypes.ts, nestedTypes.ts -> rename to metatypes.ts? Or rename. +nestedTypes will include Record as well, and register itself. + +define.ts will contain will compile stuff and create mixin. + +index.ts will wire up the things together, adding define method to Record. +Need it to resolve circular dependency. + +Key points: +- no reference to collection stuff from there. Remove getOwner(). +- no monadic type specs, no type inference. It takes raw attribute descriptors. +- Attribute and TransactionalAttr must be exported. + +This core must perform transactions and serialization. Cover with unit tests. +Consider moving class.ts and tools.ts inside. + +It would make the nice core project. Collection is way simpler, it doesn't require code generation. + +The rest of the stuff can be built on this foundation. + +## Minimal flat record +[ ] Primitive types attributes +[ ] Type inference +[ ] constructor +[ ] default record.toJSON() +[ ] set +[ ] transactional updates +[ ] ad-hoc attribute access + +- no parsing +- no nested stuff + +## Advanced flat record +[ ] Date type attribute +[ ] Object and Array types +[ ] JSON attr type +[ ] Constructor type +[ ] Global type inference +[ ] Custom toJSON() +[ ] Custom parse() +[ ] deep and shallow copy + +## Nested record +[ ] deep update +[ ] + +# Remarks + +Ownership stuff. + +There's a pattern with ViewModels - assigning if the globals +to state members just to listen the changes. + +With a current ownership scheme, it won't work. +1) New metatypes are needed: +- Model.ref( optional std ref ) +- Collection.ref( optional std ref ) + +These things are not serializable. Nor they set an owner. +Nor they will trigger the change. + +2) So, we need either to add these watching support to the core +(which we don't want to do), or use some mechanics to listen for events. + +``` +a : Model.Ref.events({ + change(){ this.forceChange( 'a' ); } +}) +``` + +or, more clear syntax: + +``` +a : Model.Ref.changeEvents( 'change' ) +``` + +We need to support both. + + +or, use special type + +``` +a : Model.LinkedRef +``` + +or, reverse semantic: + +``` +a : Model.Ref // listening to changes +a : Model.WeakRef // doesn't listen to changes +``` + +Regarding the text ref stuff. +- in this case attribute should be constant. +- there's an unsolvable issue that master link can be changed. So, its dangerous. +- Therefore, we could use separate .take() thingy for that. + +# Decorators + +For attributes, it's possible to make it way better. + +@define +class M extends Record { + @type( String ) s + @type( Number ) x = 6 + @type( Model ) m + @type( Model ) @has({ toJSON : false }) m5 + @attr x = 5 + @attr y = '' + @attr z = false + @attr({ type : Number }) g + + static attributes = { + s : String, + x : Number.value( 6 ), + m : Model, + m5 : Model.has.toJSON( false ), + x : 5, + y : '', + z : false, + g : Number + } +} + +- so, we can really do crazy shit here. +- for typescript, it's possible to get design-time type (!) in decorator. + +- decorator returns native property immediately. +- it can update _attributes in the prototype immediately. +- @define can just grab the results. \ No newline at end of file diff --git a/src/type-r/record/attributes/README.md b/src/type-r/record/attributes/README.md new file mode 100644 index 0000000..d7b6a54 --- /dev/null +++ b/src/type-r/record/attributes/README.md @@ -0,0 +1,42 @@ +Attributes run-time metadata, record update pipleline, and attribute definitions. + +- `any.ts` - `AnyType` is the base class for the typeless attribute descriptor. +- `updates.ts` - transactional updates. +- `attrDef.ts` - chainable attribute spec definition. + +## Design + +Record's attributes has descriptors stored on `record._attributes`. Attribute descriptor controls all aspects of attribute behavior. + +`AnyType` is the base class for an attribute, and it represents the *typeless attribute*. This attribute might hold value of an type and perform _no type assertions and convertions_. It must implement all the update pipeline methods, though. + +### Streamlined attributes semantic + +Mutable attributes (changes _are_ detected): + +- aggregated (Record, Collection) +- shared (Record.shared, Collection.shared, Collection.Refs) +- shared serializable (Record.from, Collection.subsetOf) + +Typeless attribute: must be anything. + +- No type convertion. +- No complex comparisons and other stuff, just the raw assignments. + +Immutable attributes (changes are _not_ detected): + +- JSON (Object, Array) +- Primitives (Boolean, Number, String) +- Date +- Function +- Class (custom constructor) + +Common for immutable things: + +- dispose is noop. +- clone is noop. +- no update in place. +- no change detection. + +Consider adding value links to perform pure updates. record.linkAt( 'key1' ).at( 'key2' ).set( value ); +Consider making it optional dependency. \ No newline at end of file diff --git a/src/type-r/record/attributes/any.ts b/src/type-r/record/attributes/any.ts new file mode 100644 index 0000000..3a8a163 --- /dev/null +++ b/src/type-r/record/attributes/any.ts @@ -0,0 +1,292 @@ +import { setAttribute, AttributesContainer, AttributeUpdatePipeline, RecordTransaction } from './updates' +import { tools } from '../../object-plus' +import { Owner, Transactional, TransactionOptions } from '../../transactions' +import { IOEndpoint } from '../../io-tools' + +const { notEqual, assign} = tools; + +declare global { + interface Function { + _attribute : typeof AnyType + } +} + +export type Transform = ( this : AnyType, next : any, prev : any, record : AttributesContainer, options : TransactionOptions ) => any; +export type ChangeHandler = ( this : AnyType, next : any, prev : any, record : AttributesContainer, options : TransactionOptions ) => void; + +export interface AttributeOptions { + _attribute? : typeof AnyType + validate? : ( record : AttributesContainer, value : any, key : string ) => any + isRequired? : boolean + changeEvents? : boolean + + endpoint? : IOEndpoint + + type? : Function + value? : any + hasCustomDefault? : boolean + + parse? : Parse + toJSON? : AttributeToJSON + + getHooks? : GetHook[] + transforms? : Transform[] + changeHandlers? : ChangeHandler[] + + _onChange? : ChangeAttrHandler +} + +export type Parse = ( value : any, key : string ) => any; +export type GetHook = ( value : any, key : string ) => any; +export type AttributeToJSON = ( value : any, key : string ) => any +export type AttributeParse = ( value : any, key : string ) => any +export type ChangeAttrHandler = ( ( value : any, attr : string ) => void ) | string; + +// TODO: interface differs from options, do something obout it +const emptyOptions : TransactionOptions = {}; + +/** + * Typeless attribute. Is the base class for all other attributes. + */ +export class AnyType implements AttributeUpdatePipeline { + // Factory method to create attribute from options + static create( options : AttributeOptions, name : string ) : AnyType { + const type = options.type, + AttributeCtor = options._attribute || ( type ? type._attribute : AnyType ); + + return new AttributeCtor( name, options ); + } + /** + * Update pipeline functions + * ========================= + * + * Stage 0. canBeUpdated( value ) + * - presence of this function implies attribute's ability to update in place. + */ + canBeUpdated( prev, next, options : TransactionOptions ) : any {} + + /** + * Stage 1. Transform stage + */ + transform( next : any, prev : any, model : AttributesContainer, options : TransactionOptions ) : any { return next; } + + // convert attribute type to `this.type`. + convert( next : any, prev : any, model : AttributesContainer, options : TransactionOptions ) : any { return next; } + + /** + * Stage 2. Check if attr value is changed + */ + isChanged( a : any, b : any ) : boolean { + return notEqual( a, b ); + } + + /** + * Stage 3. Handle attribute change + */ + handleChange( next : any, prev : any, model : AttributesContainer, options : TransactionOptions ) {} + + /** + * End update pipeline definitions. + */ + + // create empty object passing backbone options to constructor... + create() { return void 0; } + + // generic clone function for typeless attributes + // Must be overriden in sublass + clone( value : any, record : AttributesContainer ) { + return value; + } + + dispose( record : AttributesContainer, value : any ) : void { + this.handleChange( void 0, value, record, emptyOptions ); + } + + validate( record : AttributesContainer, value : any, key : string ){} + + toJSON( value, key, options? : object ) { + return value && value.toJSON ? value.toJSON( options ) : value; + } + + createPropertyDescriptor() : PropertyDescriptor | void { + const { name, getHook } = this; + + if( name !== 'id' ){ + return { + // call to optimized set function for single argument. + set( value ){ + setAttribute( this, name, value ); + }, + + // attach get hook to the getter function, if it present + get : ( + getHook ? + function() { + return getHook.call( this, this.attributes[ name ], name ); + } : + function() { return this.attributes[ name ]; } + ) + } + } + } + + value : any + + // Used as global default value for the given metatype + static defaultValue : any; + + type : Function + + initialize( name : string, options : TransactionOptions ){} + + options : AttributeOptions + + doInit( value, record : AttributesContainer, options : TransactionOptions ){ + const v = value === void 0 ? this.defaultValue() : value, + x = this.transform( v, void 0, record, options ); + + this.handleChange( x, void 0, record, options ); + return x; + } + + doUpdate( value, record : AttributesContainer, options : TransactionOptions, nested? : RecordTransaction[] ){ + const { name } = this, + { attributes } = record, + prev = attributes[ name ]; + + const next = this.transform( value, prev, record, options ); + attributes[ name ] = next; + + if( this.isChanged( next, prev ) ) { + // Do the rest of the job after assignment + this.handleChange( next, prev, record, options ); + return true; + } + + return false; + } + + propagateChanges : boolean + + _log( level : tools.LogLevel, text : string, value, record : AttributesContainer ){ + tools.log( level, `[Attribute Update Error] ${ record.getClassName() }.${ this.name }: ` + text, { + 'Record' : record, + 'Attribute definition' : this, + 'Prev. value' : record.attributes[ this.name ], + 'New value' : value + }); + } + + defaultValue(){ + return this.value; + } + + constructor( public name : string, a_options : AttributeOptions ) { + // Save original options... + this.options = a_options; + + // Clone options. + const options : AttributeOptions = assign( { getHooks : [], transforms : [], changeHandlers : [] }, a_options ); + options.getHooks = options.getHooks.slice(); + options.transforms = options.transforms.slice(); + options.changeHandlers = options.changeHandlers.slice(); + + const { + value, type, parse, toJSON, changeEvents, + validate, getHooks, transforms, changeHandlers + } = options; + + // Initialize default value... + this.value = value; + this.type = type; + + // TODO: An opportunity to optimize for attribute subtype. + if( !options.hasCustomDefault && type ){ + this.defaultValue = this.create; + } + else if( tools.isValidJSON( value ) ){ + // JSON literals must be deep copied. + this.defaultValue = new Function( `return ${ JSON.stringify( value ) };` ) as any; + } + else{ + this.defaultValue = this.defaultValue; + } + + // Changes must be bubbled when they are not disabled for an attribute and transactional object. + this.propagateChanges = changeEvents !== false; + + this.toJSON = toJSON === void 0 ? this.toJSON : toJSON; + + this.validate = validate || this.validate; + + if( options.isRequired ){ + this.validate = wrapIsRequired( this.validate ); + } + + /** + * Assemble pipelines... + */ + + // `convert` is default transform, which is always present... + transforms.unshift( this.convert ); + + // Get hook from the attribute will be used first... + if( this.get ) getHooks.unshift( this.get ); + + // let subclasses configure the pipeline... + this.initialize.call( this, options ); + + // let attribute spec configure the pipeline... + if( getHooks.length ){ + const getHook = this.getHook = getHooks.reduce( chainGetHooks ); + + const { validate } = this; + this.validate = function( record : AttributesContainer, value : any, key : string ){ + return validate.call( this, record, getHook.call( record, value, key ), key ); + } + } + + this.transform = transforms.length ? transforms.reduce( chainTransforms ) : this.transform; + + this.handleChange = changeHandlers.length ? changeHandlers.reduce( chainChangeHandlers ) : this.handleChange; + + // Attribute-level parse transform are attached as update hooks modifiers... + const { doInit, doUpdate } = this; + this.doInit = parse ? function( value, record : AttributesContainer, options : TransactionOptions ){ + return doInit.call( this, options.parse && value !== void 0 ? parse.call( record, value, this.name ) : value, record, options ); + } : doInit; + + this.doUpdate = parse ? function( value, record : AttributesContainer, options : TransactionOptions, nested? : RecordTransaction[] ){ + return doUpdate.call( this, options.parse && value !== void 0 ? parse.call( record, value, this.name ) : value, record, options, nested ); + } : doUpdate; + } + + getHook : ( value, key : string ) => any = null + get : ( value, key : string ) => any +} + + +function chainGetHooks( prevHook : GetHook, nextHook : GetHook ) : GetHook { + return function( value, name ) { + return nextHook.call( this, prevHook.call( this, value, name ), name ); + } +} + +function chainTransforms( prevTransform : Transform, nextTransform : Transform ) : Transform { + return function( next, prev, record, options ) { + return nextTransform.call( this, prevTransform.call( this, next, prev, record, options ), prev, record, options ); + } +} + +function chainChangeHandlers( prevHandler : ChangeHandler, nextHandler : ChangeHandler ) : ChangeHandler { + return function( next, prev, record, options ) { + prevHandler.call( this, next, prev, record, options ); + nextHandler.call( this, next, prev, record, options ); + } +} + +function wrapIsRequired( validate ){ + return function( record : AttributesContainer, value : any, key : string ){ + return value ? validate.call( this, record, value, key ) : 'Required'; + } +} \ No newline at end of file diff --git a/src/type-r/record/attributes/attrDef.ts b/src/type-r/record/attributes/attrDef.ts new file mode 100644 index 0000000..f538d5b --- /dev/null +++ b/src/type-r/record/attributes/attrDef.ts @@ -0,0 +1,213 @@ +/** + * Type spec engine. Declare attributes using chainable syntax, + * and returns object with spec. + */ +import { Transactional } from '../../transactions' +import { ChangeAttrHandler, AttributeOptions, Parse } from './any' +import { AttributesContainer } from './updates' +import { EventMap, EventsDefinition, definitionDecorator, tools } from '../../object-plus' +import { IOEndpoint } from '../../io-tools' + +const { assign } = tools; + +export interface AttributeCheck { + ( value : any, key : string ) : boolean + error? : any +} + +export class ChainableAttributeSpec { + options : AttributeOptions; + + constructor( options : AttributeOptions ) { + // Shallow copy options, fill it with defaults. + this.options = { getHooks : [], transforms : [], changeHandlers : []}; + if( options ) assign( this.options, options ); + } + + check( check : AttributeCheck, error : any ) : ChainableAttributeSpec { + function validate( model, value, name ){ + if( !check.call( model, value, name ) ){ + const msg = error || check.error || name + ' is not valid'; + return typeof msg === 'function' ? msg.call( model, name ) : msg; + } + } + + const prev = this.options.validate; + + return this.metadata({ + validate : prev ? ( + function( model, value, name ){ + return prev( model, value, name ) || validate( model, value, name ); + } + ) : validate + }); + } + + get asProp(){ + return definitionDecorator( 'attributes', this ); + } + + get as(){ return this.asProp; } + + get isRequired() : ChainableAttributeSpec { + return this.metadata({ isRequired : true }); + } + + endpoint( endpoint : IOEndpoint ){ + return this.metadata({ endpoint }); + } + + watcher( ref : string | ( ( value : any, key : string ) => void ) ) : ChainableAttributeSpec { + return this.metadata({ _onChange : ref }); + } + + // Attribute-specific parse transform + parse( fun : Parse ) : ChainableAttributeSpec { + return this.metadata({ parse : fun }); + } + + toJSON( fun ) : ChainableAttributeSpec { + return this.metadata({ + toJSON : typeof fun === 'function' ? fun : ( fun ? ( x, k, o ) => x && x.toJSON( o ) : emptyFunction ) + }); + } + + // Attribute get hook. + get( fun ) : ChainableAttributeSpec { + return this.metadata({ + getHooks : this.options.getHooks.concat( fun ) + }); + } + + // Attribute set hook. + set( fun ) : ChainableAttributeSpec { + function handleSetHook( next, prev, record : AttributesContainer, options ) { + if( this.isChanged( next, prev ) ) { + const changed = fun.call( record, next, this.name ); + return changed === void 0 ? prev : this.convert( changed, prev, record, options ); + } + + return prev; + } + + return this.metadata({ + transforms : this.options.transforms.concat( handleSetHook ) + }); + } + + changeEvents( events : boolean ) : ChainableAttributeSpec { + return this.metadata({ changeEvents : events }); + } + + // Subsribe to events from an attribute. + events( map : EventsDefinition ) : ChainableAttributeSpec { + const eventMap = new EventMap( map ); + + function handleEventsSubscribtion( next, prev, record : AttributesContainer ){ + prev && prev.trigger && eventMap.unsubscribe( record, prev ); + + next && next.trigger && eventMap.subscribe( record, next ); + } + + return this.metadata({ + changeHandlers : this.options.changeHandlers.concat( handleEventsSubscribtion ) + }); + } + + // Creates a copy of the spec. + get has() : ChainableAttributeSpec { + return this; + } + + metadata( options : AttributeOptions ) : ChainableAttributeSpec { + const cloned = new ChainableAttributeSpec( this.options ); + assign( cloned.options, options ); + return cloned; + } + + value( x ) : ChainableAttributeSpec { + return this.metadata({ value : x, hasCustomDefault : true }); + } + + static from( spec : any ) : ChainableAttributeSpec { + let attrSpec : ChainableAttributeSpec; + + if( typeof spec === 'function' ) { + attrSpec = spec.has; + } + else if( spec && spec instanceof ChainableAttributeSpec ) { + attrSpec = spec; + } + else{ + // Infer type from value. + const type = inferType( spec ); + + // Transactional types inferred from values must have shared type. + if( type && type.prototype instanceof Transactional ){ + attrSpec = (type).shared.value( spec ); + } + // All others will be created in regular way. + else{ + attrSpec = new ChainableAttributeSpec({ type : type, value : spec, hasCustomDefault : true }); + } + } + + return attrSpec; + } +} + +function emptyFunction(){} + +export function type( this : void, spec : ChainableAttributeSpec | Function ) : ChainableAttributeSpec { + return spec instanceof ChainableAttributeSpec ? spec : new ChainableAttributeSpec( { + type : spec, + value : spec._attribute.defaultValue, + hasCustomDefault : spec._attribute.defaultValue !== void 0 + } );; +} + +declare global { + interface Function{ + value : ( x : any ) => ChainableAttributeSpec; + isRequired : ChainableAttributeSpec; + asProp : PropertyDecorator + has : ChainableAttributeSpec; + } +} + +Function.prototype.value = function( x ) { + return new ChainableAttributeSpec( { type : this, value : x, hasCustomDefault : true } ); +}; + +Object.defineProperty( Function.prototype, 'isRequired', { + get() { return this._isRequired || this.has.isRequired; }, + set( x ){ this._isRequired = x; } +}); + +Object.defineProperty( Function.prototype, 'asProp', { + get() { return this.has.asProp; }, +}); + +Object.defineProperty( Function.prototype, 'has', { + get() { + // workaround for sinon.js and other libraries overriding 'has' + return this._has || type( this ); + }, + + set( value ) { this._has = value; } +} ); + +function inferType( value : {} ) : Function { + switch( typeof value ) { + case 'number' : + return Number; + case 'string' : + return String; + case 'boolean' : + return Boolean; + case 'undefined' : + return void 0; + case 'object' : + return value ? value.constructor : void 0; + } +} diff --git a/src/type-r/record/attributes/basic.ts b/src/type-r/record/attributes/basic.ts new file mode 100644 index 0000000..f82b029 --- /dev/null +++ b/src/type-r/record/attributes/basic.ts @@ -0,0 +1,194 @@ +/** + * Built-in JSON types attributes: Object, Array, Number, String, Boolean, and immutable class. + * + * Adds type assertions, default validation, and optimized update pipeline. + */ + +import { AnyType } from './any' +import { tools } from '../../object-plus' +import { AttributesContainer } from './updates' +import { TransactionOptions } from '../../transactions' + +/** + * Custom class must be immutable class which implements toJSON() method + * with a constructor taking json. + */ +class ImmutableClassType extends AnyType { + type : new ( value? : any ) => {} + + create(){ + return new this.type(); + } + + convert( next : any ) : any { + return next == null || next instanceof this.type ? next : new this.type( next ); + } + + toJSON( value, key? : string, options? : object ){ + return value && value.toJSON ? value.toJSON( options ) : value; + } + + clone( value ) { + return new this.type( this.toJSON( value ) ); + } + + isChanged( a, b ){ + return a !== b; + } +} + +Function.prototype._attribute = ImmutableClassType; + +/** + * Optimized attribute of primitive type. + * + * Primitives has specialized simplified pipeline. + */ +export class PrimitiveType extends AnyType { + type : NumberConstructor | StringConstructor | BooleanConstructor + + dispose(){} + create() { return this.type(); } + + toJSON( value ) { return value; } + + convert( next ) { return next == null ? next : this.type( next ); } + + isChanged( a, b ) { return a !== b; } + + clone( value ) { return value; } + + doInit( value, record : AttributesContainer, options : TransactionOptions ){ + return this.transform( value === void 0 ? this.value : value, void 0, record, options ); + } + + doUpdate( value, record, options, nested ){ + const { name } = this, + { attributes } = record, + prev = attributes[ name ]; + + return prev !== ( attributes[ name ] = this.transform( value, prev, record, options ) ); + } + + initialize(){ + if( !this.options.hasCustomDefault ){ + this.value = this.type(); + } + } +} + +Boolean._attribute = String._attribute = PrimitiveType; + +// Number type with special validation algothim. +/** @private */ +export class NumericType extends PrimitiveType { + type : NumberConstructor + + create(){ + return 0; + } + + convert( next, prev?, record? ) { + const num = next == null ? next : this.type( next ); + + if( num !== num ){ + this._log( 'warn', 'assigned with Invalid Number', next, record ); + } + + return num; + } + + validate( model, value, name ) { + // Whatever is not symmetrically serializable to JSON, is not valid by default. + if( value != null && !isFinite( value ) ) { + return name + ' is not valid number'; + } + } +} + +Number._attribute = NumericType; + +/** + * Add Number.integer attrubute type + */ +declare global { + interface NumberConstructor { + integer : Function + } + + interface Window { + Integer : Function; + } +} + +function Integer( x ){ + return x ? Math.round( x ) : 0; +} +Integer._attribute = NumericType; +Number.integer = Integer; + + +if( typeof window !== 'undefined' ){ + window.Integer = Number.integer; +} + +/** + * Compatibility wrapper for Array type. + * @private + */ +export class ArrayType extends AnyType { + toJSON( value ) { return value; } + dispose(){} + create(){ return []; } + + convert( next, prev, record ) { + // Fix incompatible constructor behaviour of Array... + if( next == null || Array.isArray( next ) ) return next; + + this._log( 'warn', 'assignment of non-array to Array attribute is ignored', next, record ); + + return []; + } + + clone( value ){ + return value && value.slice(); + } +} + +Array._attribute = ArrayType; + +export class ObjectType extends AnyType { + create(){ return {}; } + + convert( next, prev, record ) { + if( next == null || typeof next === 'object' ) return next; + + this._log( 'warn', 'assignment of non-object to Object attribute is ignored', next, record ); + return {}; + } +} + +Object._attribute = ObjectType; + +export function doNothing(){} + +export class FunctionType extends AnyType { + // Functions are not serialized. + toJSON( value ) { return void 0; } + create(){ return doNothing; } + dispose(){} + + convert( next, prev, record ) { + // Fix incompatible constructor behaviour of Function... + if( next == null || typeof next === 'function' ) return next; + + this._log( 'warn', 'assigned with non-function', next, record ); + + return doNothing; + } + + // Functions are not cloned. + clone( value ){ return value; } +} + +Function._attribute = FunctionType; \ No newline at end of file diff --git a/src/type-r/record/attributes/date.ts b/src/type-r/record/attributes/date.ts new file mode 100644 index 0000000..4930a7a --- /dev/null +++ b/src/type-r/record/attributes/date.ts @@ -0,0 +1,163 @@ +/** + * Date attribute type. + * + * Implements validation, cross-browser compatibility fixes, variety of Date serialization formats, + * and optimized update pipeline. + */ +import { AnyType } from './any' +import { tools } from '../../object-plus' +import { AttributesContainer } from './updates' +import { TransactionOptions } from '../../transactions' +import { ChainableAttributeSpec } from './attrDef' + +const DateProto = Date.prototype; + +// Date Attribute +/** @private */ +export class DateType extends AnyType { + create(){ + return new Date(); + } + + convert( next : any, a, record ){ + if( next == null || next instanceof Date ) return next; + + const date = new Date( next ), + timestamp = date.getTime(); + + if( timestamp !== timestamp ){ + this._log( 'warn', 'assigned with Invalid Date', next, record ); + } + + return date; + } + + validate( model, value, name ) { + if( value != null ){ + const timestamp = value.getTime(); + if( timestamp !== timestamp ) return name + ' is Invalid Date'; + } + } + + toJSON( value ) { return value && value.toISOString(); } + + isChanged( a, b ) { return ( a && a.getTime() ) !== ( b && b.getTime() ); } + + doInit( value, record : AttributesContainer, options : TransactionOptions ){ + // Date don't have handleChanges step. + return this.transform( value === void 0 ? this.defaultValue() : value, void 0, record, options ); + } + + doUpdate( value, record, options, nested ){ + const { name } = this, + { attributes } = record, + prev = attributes[ name ]; + + // Date don't have handleChanges step. + return this.isChanged( prev , attributes[ name ] = this.transform( value, prev, record, options ) ); + } + + clone( value ) { return value && new Date( value.getTime() ); } + dispose(){} +} + +Date._attribute = DateType; + +const msDatePattern = /\/Date\(([0-9]+)\)\//; + +export class MSDateType extends DateType { + convert( next ) { + if( typeof next === 'string' ){ + const msDate = msDatePattern.exec( next ); + if( msDate ){ + return new Date( Number( msDate[ 1 ] ) ); + } + } + + return DateType.prototype.convert.apply( this, arguments ); + } + + toJSON( value ) { return value && `/Date(${ value.getTime() })/`; } +} + +export class TimestampType extends DateType { + toJSON( value ) { return value && value.getTime(); } +} + +declare global { + interface DateConstructor { + microsoft : ChainableAttributeSpec + timestamp : ChainableAttributeSpec + } +} + +Object.defineProperties( Date, { + microsoft : { + get(){ + return new ChainableAttributeSpec({ + type : Date, + _attribute : MSDateType + }) + } + }, + + timestamp : { + get(){ + return new ChainableAttributeSpec({ + type : Date, + _attribute : TimestampType + }) + } + } +}); + +// If ISO date is not supported by date constructor (such as in Safari), polyfill it. +function supportsDate( date ){ + return !isNaN( ( new Date( date ) ).getTime() ); +} + +if( !supportsDate('2011-11-29T15:52:30.5') || + !supportsDate('2011-11-29T15:52:30.52') || + !supportsDate('2011-11-29T15:52:18.867') || + !supportsDate('2011-11-29T15:52:18.867Z') || + !supportsDate('2011-11-29T15:52:18.867-03:30') ){ + + DateType.prototype.convert = function( value ){ + return value == null || value instanceof Date ? value : new Date( safeParseDate( value ) ); + } +} + +const numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ], + isoDatePattern = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/; + +function safeParseDate( date : string ) : number { + var timestamp, struct : any[], minutesOffset = 0; + + if( ( struct = isoDatePattern.exec( date )) ) { + // avoid NaN timestamps caused by undefined values being passed to Date.UTC + for( var i = 0, k; ( k = numericKeys[ i ] ); ++i ) { + struct[ k ] = +struct[ k ] || 0; + } + + // allow undefined days and months + struct[ 2 ] = (+struct[ 2 ] || 1) - 1; + struct[ 3 ] = +struct[ 3 ] || 1; + + if( struct[ 8 ] !== 'Z' && struct[ 9 ] !== undefined ) { + minutesOffset = struct[ 10 ] * 60 + struct[ 11 ]; + + if( struct[ 9 ] === '+' ) { + minutesOffset = 0 - minutesOffset; + } + } + + timestamp = + Date.UTC( struct[ 1 ], struct[ 2 ], struct[ 3 ], struct[ 4 ], struct[ 5 ] + minutesOffset, struct[ 6 ], + struct[ 7 ] ); + } + else { + timestamp = Date.parse( date ); + } + + return timestamp; +} \ No newline at end of file diff --git a/src/type-r/record/attributes/index.ts b/src/type-r/record/attributes/index.ts new file mode 100644 index 0000000..07226c5 --- /dev/null +++ b/src/type-r/record/attributes/index.ts @@ -0,0 +1,110 @@ +import { tools as _, eventsApi } from '../../object-plus' + +export * from './any' +export * from './owned' +export * from './date' +export * from './basic' +export * from './shared' +export * from './updates' +export * from './attrDef' + +import { AnyType } from './any' +import { ConstructorsMixin, constructorsMixin } from './updates' +import { ChainableAttributeSpec } from './attrDef' +import { CompiledReference } from '../../traversable' +import { IOEndpoint } from '../../io-tools' + +export interface RecordAttributesMixin extends ConstructorsMixin { + // Attributes descriptors + _attributes : AttributeDescriptors + _attributesArray : AnyType[] + + // Attribute's property descriptors + properties : PropertyDescriptorMap + + // Event map for record's local events. + _localEvents? : eventsApi.EventMap, + + _endpoints : { [ name : string ] : IOEndpoint } +} + +export interface AttributeDescriptors { + [ name : string ] : AnyType +} + +// Create record mixin from the given record's attributes definition +export default function( attributesDefinition : object, baseClassAttributes : AttributeDescriptors ) : RecordAttributesMixin { + const myAttributes = _.transform( {} as AttributeDescriptors, attributesDefinition, createAttribute ), + allAttributes = _.defaults( {} as AttributeDescriptors, myAttributes, baseClassAttributes ); + + const ConstructorsMixin = constructorsMixin( allAttributes ); + + return { + ...ConstructorsMixin, + _attributes : new ConstructorsMixin.AttributesCopy( allAttributes ), + _attributesArray : Object.keys( allAttributes ).map( key => allAttributes[ key ] ), + properties : _.transform( {}, myAttributes, x => x.createPropertyDescriptor() ), + ...localEventsMixin( myAttributes ), + _endpoints : _.transform( {}, allAttributes, attrDef => attrDef.options.endpoint ) + } +} + +// Create attribute from the type spec. +export function createAttribute( spec : any, name : string ) : AnyType { + return AnyType.create( ChainableAttributeSpec.from( spec ).options, name ); +} + +export function createSharedTypeSpec( Constructor : Function, Attribute : typeof AnyType ){ + if( !Constructor.hasOwnProperty( 'shared' ) ){ + Object.defineProperty( Constructor, 'shared', { + get(){ + return new ChainableAttributeSpec({ + value : null, + type : Constructor, + _attribute : Attribute + }); + } + }); + } +} + +interface LocalEventsMixin { + _localEvents? : eventsApi.EventMap +} + +function localEventsMixin( attrSpecs : AttributeDescriptors ) : LocalEventsMixin { + let _localEvents : eventsApi.EventMap; + + for( var key in attrSpecs ){ + const attribute = attrSpecs[ key ], + { _onChange } = attribute.options; + + if( _onChange ){ + _localEvents || ( _localEvents = new eventsApi.EventMap() ); + + _localEvents.addEvent( 'change:' + key, + typeof _onChange === 'string' ? + createWatcherFromRef( _onChange, key ) : + wrapWatcher( _onChange, key ) ); + } + } + + return _localEvents ? { _localEvents } : {}; +} + +function wrapWatcher( watcher, key ){ + return function( record, value ){ + watcher.call( record, value, key ); + } +} + +function createWatcherFromRef( ref : string, key : string ){ + const { local, resolve, tail } = new CompiledReference( ref, true ); + return local ? + function( record, value ){ + record[ tail ]( value, key ); + } : + function( record, value ){ + resolve( record )[ tail ]( value, key ); + } +} \ No newline at end of file diff --git a/src/type-r/record/attributes/owned.ts b/src/type-r/record/attributes/owned.ts new file mode 100644 index 0000000..ba2bcb9 --- /dev/null +++ b/src/type-r/record/attributes/owned.ts @@ -0,0 +1,122 @@ +import { AnyType } from './any' +import { Owner, transactionApi, Transactional, ItemsBehavior, TransactionOptions } from '../../transactions' +import { tools } from '../../object-plus' +import { AttributesContainer, ConstructorOptions } from './updates' +import { ValidationError } from '../../validation' + +const { free, aquire } = transactionApi; + +export class AggregatedType extends AnyType { + type : typeof Transactional + + clone( value : Transactional ) : Transactional { + return value ? value.clone() : value; + } + + toJSON( x, key : string, options : object ){ return x && x.toJSON( options ); } + + doInit( value, record : AttributesContainer, options : ConstructorOptions ){ + const v = options.clone ? this.clone( value ) : ( + value === void 0 ? this.defaultValue() : value + ); + + const x = this.transform( v, void 0, record, options ); + this.handleChange( x, void 0, record, options ); + return x; + } + + doUpdate( value, record, options, nested : any[] ){ // Last to things can be wrapped to an object, either transaction or ad-hoc + const key = this.name, { attributes } = record; + const prev = attributes[ key ]; + let update; + + // This can be moved to transactional attribute. And chained with the rest. + if( update = this.canBeUpdated( prev, value, options ) ) { // todo - skip empty updates. + const nestedTransaction = prev._createTransaction( update, options ); + if( nestedTransaction ){ + if( nested ){ + nested.push( nestedTransaction ); + } + else{ + nestedTransaction.commit( record ); + } + + if( this.propagateChanges ) return true; + } + + return false; + } + + const next = this.transform( value, prev, record, options ); + attributes[ key ] = next; + + if( this.isChanged( next, prev ) ) { // Primitives and nested comparison can be inlined. + // Do the rest of the job after assignment + this.handleChange( next, prev, record, options ); + + return true; + } + + return false; + } + + canBeUpdated( prev : Transactional, next : any, options : TransactionOptions ) : any { + // If an object already exists, and new value is of incompatible type, let object handle the update. + if( prev && next != null ){ + if( next instanceof this.type ){ + // In case if merge option explicitly specified, force merge. + if( options.merge ) return next.__inner_state__; + } + else{ + return next; + } + } + } + + convert( next : any, prev : any, record : AttributesContainer, options : TransactionOptions ) : Transactional { + // Invoke class factory to handle abstract classes + if( next == null ) return next; + + if( next instanceof this.type ){ + if( next._shared && !( next._shared & ItemsBehavior.persistent ) ) { // TODO: think more about shared types assignment compatibility. + this._log( 'error', 'aggregated collection attribute is assigned with shared collection', next, record ); + } + + // With explicit 'merge' option we need to clone an object if its previous value was 'null'. + // This is an only case we could be here when merge === true. + return options.merge ? next.clone() : next; + } + + return this.type.create( next, options ); + } + + dispose ( record : AttributesContainer, value : Transactional ){ + if( value ){ + this.handleChange( void 0, value, record, {} ); + } + } + + validate( record : AttributesContainer, value : Transactional ) : ValidationError { + var error = value && value.validationError; + if( error ) return error; + } + + create() : Transactional { + return (this.type).create(); // this the subclass of Transactional here. + } + + initialize( options ){ + options.changeHandlers.unshift( this._handleChange ); + } + + _handleChange( next : Transactional, prev : Transactional, record : AttributesContainer, options : TransactionOptions ){ + if( prev ){ + free( record, prev ); + options.unset || prev.dispose(); + } + + if( next && !aquire( record, next, this.name ) ){ + this._log( 'error', 'aggregated attribute assigned with object already having an owner', next, record ); + } + } +} \ No newline at end of file diff --git a/src/type-r/record/attributes/shared.ts b/src/type-r/record/attributes/shared.ts new file mode 100644 index 0000000..b855e59 --- /dev/null +++ b/src/type-r/record/attributes/shared.ts @@ -0,0 +1,148 @@ +import { AnyType } from './any' +import { AttributesContainer, ConstructorOptions } from './updates' +import { ItemsBehavior, Owner, transactionApi, Transactional, TransactionOptions } from '../../transactions' +import { tools, eventsApi } from '../../object-plus' + +const { on, off } = eventsApi, + { free, aquire } = transactionApi; + +/************************ + * Shared attribute definition. + * - Not serialized. + * - Listening to the changes. + * - Doesn't take ownership when assigned with object of proper type. + * - Takes ownership on objects which are converted. + */ + +const shareAndListen = ItemsBehavior.listen | ItemsBehavior.share; + +/** @private */ +export class SharedType extends AnyType { + type : typeof Transactional + + doInit( value, record : AttributesContainer, options : ConstructorOptions ){ + const v = options.clone ? this.clone( value, record ) : ( + value === void 0 ? this.defaultValue() : value + ); + + const x = this.transform( v, void 0, record, options ); + this.handleChange( x, void 0, record, options ); + return x; + } + + doUpdate( value, record, options, nested : any[] ){ // Last to things can be wrapped to an object, either transaction or ad-hoc + const key = this.name, { attributes } = record; + const prev = attributes[ key ]; + let update; + + // This can be moved to transactional attribute. And chained with the rest. + if( update = this.canBeUpdated( prev, value, options ) ) { // todo - skip empty updates. + const nestedTransaction = prev._createTransaction( update, options ); + if( nestedTransaction ){ + if( nested ){ + nested.push( nestedTransaction ); + } + else{ + nestedTransaction.commit( record ); + } + + if( this.propagateChanges ) return true; + } + + return false; + } + + const next = this.transform( value, prev, record, options ); + attributes[ key ] = next; + + if( this.isChanged( next, prev ) ) { // Primitives and nested comparison can be inlined. + // Do the rest of the job after assignment + this.handleChange( next, prev, record, options ); + + return true; + } + + return false; + } + + clone( value : Transactional, record : AttributesContainer ) : Transactional { + // References are not cloned. + if( !value || value._owner !== record ) return value; + + // Implicitly created objects are cloned. + const clone = value.clone(); + aquire( record, clone, this.name ); + return clone; + } + + // Do not serialize by default. + toJSON(){} + + canBeUpdated( prev : Transactional, next : any, options : TransactionOptions ) : any { + // If an object already exists, and new value is of incompatible type, let object handle the update. + if( prev && next != null && !( next instanceof this.type ) ){ + return next; + } + } + + convert( next : any, prev : any, record : AttributesContainer, options : TransactionOptions ) : Transactional { + if( next == null || next instanceof this.type ) return next; + + // Convert type using implicitly created rtransactional object. + const implicitObject = new ( this.type as any )( next, options, shareAndListen ); + + // To prevent a leak, we need to take an ownership on it. + aquire( record, implicitObject, this.name ); + + return implicitObject; + } + + // Refs are always valid. + validate( model, value, name ){} + + // They are always created as null. + create() : Transactional { + return null; + } + + // Listening to the change events + _handleChange( next : Transactional, prev : Transactional, record : AttributesContainer, options ){ + if( prev ){ + // If there was an implicitly created object, remove an ownership. + if( prev._owner === record ){ + free( record, prev ); + options.unset || prev.dispose(); + } + else{ + off( prev, prev._changeEventName, this._onChange, record ); + } + } + + if( next ){ + // No need to take an ownership for an implicit object - already done in convert or clone. + if( next._owner !== record ){ + on( next, next._changeEventName, this._onChange, record ); + } + } + } + + dispose( record : AttributesContainer, value : Transactional ){ + if( value ){ + this.handleChange( void 0, value, record, {} ); + } + } + + _onChange : ( child : Transactional, options : TransactionOptions, initiator : Transactional ) => void + + initialize( options ){ + // Create change event handler which knows current attribute name. + const attribute = this; + this._onChange = this.propagateChanges ? function( child, options, initiator ){ + this === initiator || this.forceAttributeChange( attribute.name, options ); + } : ignore; + + options.changeHandlers.unshift( this._handleChange ); + } +} + +function ignore(){} \ No newline at end of file diff --git a/src/type-r/record/attributes/updates.ts b/src/type-r/record/attributes/updates.ts new file mode 100644 index 0000000..4f17ae7 --- /dev/null +++ b/src/type-r/record/attributes/updates.ts @@ -0,0 +1,226 @@ +import { Transactional, Transaction, TransactionOptions, Owner, transactionApi } from "../../transactions" +const { begin : _begin, markAsDirty : _markAsDirty, commit } = transactionApi; + +import { eventsApi } from '../../object-plus' +const { trigger3 } = eventsApi; + +export interface ConstructorsMixin { + Attributes : AttributesConstructor + AttributesCopy : AttributesCopyConstructor +} + +export interface ConstructorOptions extends TransactionOptions{ + clone? : boolean +} + +export type AttributesConstructor = new ( record : AttributesContainer, values : object, options : TransactionOptions ) => AttributesValues; +export type AttributesCopyConstructor = new ( values : object ) => AttributesValues; + +export interface AttributesContainer extends Transactional, Owner, ConstructorsMixin { + // Attribute descriptors. + _attributes : AttributesDescriptors + + // Attribute values. + attributes : AttributesValues + + // Previous attribute values. + _previousAttributes : AttributesValues + + // Changed attributes cache. + _changedAttributes : AttributesValues +} + +export interface AttributesValues { + [ name : string ] : any +} + +export interface AttributesDescriptors { + [ name : string ] : AttributeUpdatePipeline +} + +export interface AttributeUpdatePipeline{ + doUpdate( value, record : AttributesContainer, options : TransactionOptions, nested? : Transaction[] ) : boolean +} + + // Optimized single attribute transactional update. To be called from attributes setters + // options.silent === false, parse === false. +export function setAttribute( record : AttributesContainer, name : string, value : any ) : void { + // Open the transaction. + const isRoot = begin( record ), + options = {}; + + // Update attribute. + if( record._attributes[ name ].doUpdate( value, record, options ) ){ + // Notify listeners on changes. + markAsDirty( record, options ); + trigger3( record, 'change:' + name, record, record.attributes[ name ], options ); + } + + // Close the transaction. + isRoot && commit( record ); +} + +function begin( record : AttributesContainer ){ + if( _begin( record ) ){ + record._previousAttributes = new record.AttributesCopy( record.attributes ); + record._changedAttributes = null; + return true; + } + + return false; +} + +function markAsDirty( record : AttributesContainer, options : TransactionOptions ){ + // Need to recalculate changed attributes, when we have nested set in change:attr handler + if( record._changedAttributes ){ + record._changedAttributes = null; + } + + return _markAsDirty( record, options ); +} + +/** + * TODO: There's an opportunity to create an optimized pipeline for primitive types and Date, which makes the majority + * of attributes. It might create the major speedup. + * + * Create the dedicated pipeline for owned and shared attributes as well. + * + * Three elements of the pipeline: + * - from constructor + * - from assignment + * - from `set` + */ + +export const UpdateRecordMixin = { +// Need to override it here, since begin/end transaction brackets are overriden. + transaction( this : AttributesContainer, fun : ( self : AttributesContainer ) => void, options : TransactionOptions = {} ) : void{ + const isRoot = begin( this ); + fun.call( this, this ); + isRoot && commit( this ); + }, + + // Handle nested changes. TODO: propagateChanges == false, same in transaction. + _onChildrenChange( child : Transactional, options : TransactionOptions ) : void { + const { _ownerKey } = child, + attribute = this._attributes[ _ownerKey ]; + + if( !attribute /* TODO: Must be an opposite, likely the bug */ || attribute.propagateChanges ) this.forceAttributeChange( _ownerKey, options ); + }, + + // Simulate attribute change + forceAttributeChange( key : string, options : TransactionOptions = {} ){ + // Touch an attribute in bounds of transaction + const isRoot = begin( this ); + + if( markAsDirty( this, options ) ){ + trigger3( this, 'change:' + key, this, this.attributes[ key ], options ); + } + + isRoot && commit( this ); + }, + + _createTransaction( this : AttributesContainer, a_values : {}, options : TransactionOptions = {} ) : Transaction { + const isRoot = begin( this ), + changes : string[] = [], + nested : RecordTransaction[]= [], + { _attributes } = this, + values = options.parse ? this.parse( a_values, options ) : a_values; + + let unknown; + + if( shouldBeAnObject( this, values ) ){ + for( let name in values ){ + const spec = _attributes[ name ]; + + if( spec ){ + if( spec.doUpdate( values[ name ], this, options, nested ) ){ + changes.push( name ); + } + } + else{ + unknown || ( unknown = [] ); + unknown.push( `'${ name }'` ); + } + } + + if( unknown ){ + // this._log( 'warn', `Undefined attributes ${ unknown.join(', ')} are ignored!`, values ); + } + } + + if( changes.length && markAsDirty( this, options ) ){ + return new RecordTransaction( this, isRoot, nested, changes ); + } + + // No changes, but there might be silent attributes with open transactions. + for( let pendingTransaction of nested ){ + pendingTransaction.commit( this ); + } + + isRoot && commit( this ); + } +}; + +// One of the main performance tricks of Type-R. +// Create loop unrolled constructors for internal attribute hash, +// so the hidden class JIT optimization will be engaged and they will become static structs. +// It dramatically improves record performance. +export function constructorsMixin( attrDefs : AttributesDescriptors ) : ConstructorsMixin { + const attrs = Object.keys( attrDefs ); + + const AttributesCopy : AttributesCopyConstructor = new Function( 'values', ` + ${ attrs.map( attr =>` + this.${ attr } = values.${ attr }; + `).join( '' ) } + `) as any; + + AttributesCopy.prototype = Object.prototype; + + const Attributes : AttributesConstructor = new Function( 'record', 'values', 'options', ` + var _attrs = record._attributes; + + ${ attrs.map( attr =>` + this.${ attr } = _attrs.${ attr }.doInit( values.${ attr }, record, options ); + `).join( '' ) } + `) as any; + + Attributes.prototype = Object.prototype; + + return { Attributes, AttributesCopy }; +} + +export function shouldBeAnObject( record : AttributesContainer, values : object ){ + if( values && values.constructor === Object ) return true; + + record._log( 'warn', 'update with non-object is ignored!', { values } ); + return false; +} + +// Transaction class. Implements two-phase transactions on object's tree. +// Transaction must be created if there are actual changes and when markIsDirty returns true. +export class RecordTransaction implements Transaction { + // open transaction + constructor( public object : AttributesContainer, + public isRoot : boolean, + public nested : Transaction[], + public changes : string[] ){} + + // commit transaction + commit( initiator? : AttributesContainer ) : void { + const { nested, object, changes } = this; + + // Commit all pending nested transactions... + for( let transaction of nested ){ + transaction.commit( object ); + } + + // Notify listeners on attribute changes... + // Transaction is never created when silent option is set, so just send events out. + const { attributes, _isDirty } = object; + for( let key of changes ){ + trigger3( object, 'change:' + key, object, attributes[ key ], _isDirty ); + } + + this.isRoot && commit( object, initiator ); + } +} \ No newline at end of file diff --git a/src/type-r/record/index.ts b/src/type-r/record/index.ts new file mode 100644 index 0000000..b47b8e0 --- /dev/null +++ b/src/type-r/record/index.ts @@ -0,0 +1,94 @@ +import { Record, RecordDefinition } from './record' +import { Mixable, tools, predefine, define, MixinsState } from '../object-plus' +import compile, { ChainableAttributeSpec } from './attributes' +import { Transactional } from '../transactions' + +import { createSharedTypeSpec, AggregatedType, MSDateType, TimestampType, NumericType, SharedType } from './attributes' + +export * from './attributes' +export { Record } + +const { assign, defaults, omit, getBaseClass } = tools; + +Record.onExtend = function( this : typeof Record, BaseClass : typeof Record ){ + Transactional.onExtend.call( this, BaseClass ); + + // Create the default collection + const Class = this; + + @predefine class DefaultCollection extends BaseClass.Collection { + static model = Class; + } + + this.DefaultCollection = DefaultCollection; + + // If there are no collection defined in statics, use the default collection. + // It will appear in onDefine's definition, overriding all other settings. + if( Class.Collection === BaseClass.Collection ){ + this.Collection = DefaultCollection; + } + + // Create Class.shared modifier + createSharedTypeSpec( this, SharedType ); +} + +Record.onDefine = function( definition : RecordDefinition, BaseClass : typeof Record ){ + const baseProto : Record = BaseClass.prototype; + + // Compile attributes spec, creating definition mixin. + const { properties, _localEvents, ...dynamicMixin } = compile( this.attributes = getAttributes( definition ), baseProto._attributes ); + assign( this.prototype, dynamicMixin ); + + definition.properties = defaults( definition.properties || {}, properties ); + definition._localEvents = _localEvents; + + Transactional.onDefine.call( this, definition, BaseClass ); + + // Finalize the definition of the default collection. + this.DefaultCollection.define( definition.collection || {} ); + + // assign collection from the definition. + this.Collection = definition.Collection; + this.Collection.prototype.model = this; + + if( definition.endpoint ) this.Collection.prototype._endpoint = definition.endpoint; +} + +Record._attribute = AggregatedType; +createSharedTypeSpec( Record, SharedType ); + +function getAttributes({ defaults, attributes, idAttribute } : RecordDefinition ) { + const definition = attributes || defaults || {}; + + // If there is an undeclared idAttribute, add its definition as untyped generic attribute. + if( idAttribute && !( idAttribute in definition ) ){ + definition[ idAttribute ] = void 0; + } + + return definition; +} + +declare var Reflect; + +export function attr( proto : object, attrName : string ) : void; +export function attr( spec : any ) : PropertyDecorator; +export function attr( proto, attrName? : string ) : any { + if( attrName ){ + // Called without the spec. Extract the type. + if( typeof Reflect !== 'undefined' && Reflect.getMetadata ){ + Reflect + .getMetadata( "design:type", proto, attrName ) + .asProp( proto, attrName ); + } + else{ + proto._log( 'error', 'Add import "reflect-metadata"; as the first line of your app.' ); + } + } + else{ + return ChainableAttributeSpec.from( proto ).asProp; + } +} + +export function prop( spec ) : any { + return spec.asProp; +} \ No newline at end of file diff --git a/src/type-r/record/io-mixin.ts b/src/type-r/record/io-mixin.ts new file mode 100644 index 0000000..29e9b10 --- /dev/null +++ b/src/type-r/record/io-mixin.ts @@ -0,0 +1,61 @@ +import { getOwnerEndpoint, startIO, IOOptions, IOEndpoint, IOPromise, IONode } from '../io-tools' + +export interface IORecord extends IONode { + getEndpoint() : IOEndpoint + save( options? : IOOptions ) : IOPromise + fetch( options? : IOOptions ) : IOPromise + destroy( options? : IOOptions ) : IOPromise + toJSON( options? : object ) : any + isNew() : boolean + id : string | number + set( json : object, options : object ) +} + +export const IORecordMixin = { + save( this : IORecord, options : IOOptions = {} ){ + const endpoint = this.getEndpoint(), + json = this.toJSON( options ); + + return startIO( + this, + this.isNew() ? + endpoint.create( json, options, this ) : + endpoint.update( this.id, json, options, this ), + options, + + update => { + this.set( update, { parse : true, ...options } ); + } + ); + }, + + fetch( options : IOOptions = {} ){ + return startIO( + this, + this.getEndpoint().read( this.id, options, this ), + options, + + json => this.set( json, { parse : true, ...options } ) + ); + }, + + destroy( options : IOOptions = {} ){ + return startIO( + this, + this.getEndpoint().destroy( this.id, options, this ), + options, + + () => { + const { collection } = this; + if( collection ){ + collection.remove( this, options ); + } + else{ + this.dispose(); + } + + return this; + } + ) + } +} \ No newline at end of file diff --git a/src/type-r/record/record.ts b/src/type-r/record/record.ts new file mode 100644 index 0000000..873fb0b --- /dev/null +++ b/src/type-r/record/record.ts @@ -0,0 +1,506 @@ +/** + * Record core implementing transactional updates. + * The root of all definitions. + */ + +import { tools, eventsApi, Mixable, definitions, mixins, mixinRules, define } from '../object-plus' + +import { CloneOptions, Transactional, TransactionalDefinition, Transaction, TransactionOptions, Owner } from '../transactions' +import { ChildrenErrors } from '../validation' + +import { Collection } from '../collection' + +import { AnyType, AggregatedType, setAttribute, UpdateRecordMixin, + AttributesValues, AttributesContainer, + ConstructorsMixin, AttributesConstructor, AttributesCopyConstructor } from './attributes' + +import { IORecord, IORecordMixin } from './io-mixin' +import { IOPromise, IOEndpoint } from '../io-tools' + +const { assign, isEmpty, log } = tools; + +/******************************************************* + * Record core implementation + */ + +export interface ConstructorOptions extends TransactionOptions{ + clone? : boolean +} + +// Client unique id counter +let _cidCounter : number = 0; + +/*************************************************************** + * Record Definition as accepted by Record.define( definition ) + */ +export interface RecordDefinition extends TransactionalDefinition { + idAttribute? : string + attributes? : AttributesValues + collection? : object + Collection? : typeof Transactional +} + +@define({ + // Default client id prefix + cidPrefix : 'm', + + // Name of the change event + _changeEventName : 'change', + + // Default id attribute name + idAttribute : 'id' +}) +@definitions({ + defaults : mixinRules.merge, + attributes : mixinRules.merge, + collection : mixinRules.merge, + Collection : mixinRules.value, + idAttribute : mixinRules.protoValue +}) +export class Record extends Transactional implements IORecord, AttributesContainer { + // Hack + static onDefine( definition, BaseClass ){} + + static Collection : typeof Collection; + static DefaultCollection : typeof Collection; + + static from : ( collectionReference : any ) => any; + + static defaults( attrs : AttributesValues ) : typeof Record { + return this.extend({ attributes : attrs }); + } + + static attributes : AttributesValues + + /******************** + * IO Methods + */ + _endpoints : { [ name : string ] : IOEndpoint } + + // Save record + save( options? : object ) : IOPromise { throw new Error( 'Implemented by mixin' ); } + + // Destroy record + destroy( options? : object ) : IOPromise { throw new Error( 'Implemented by mixin' ); } + + /*********************************** + * Core Members + */ + // Previous attributes + _previousAttributes : {} + + previousAttributes(){ return new this.AttributesCopy( this._previousAttributes ); } + + // Current attributes + attributes : AttributesValues + + // Polymorphic accessor for aggregated attribute's canBeUpdated(). + get __inner_state__(){ return this.attributes; } + + // Lazily evaluated changed attributes hash + _changedAttributes : AttributesValues + + get changed(){ + let changed = this._changedAttributes; + + if( !changed ){ + const prev = this._previousAttributes; + changed = {}; + + const { _attributes, attributes } = this; + + for( let attr of this._attributesArray ){ + const key = attr.name, + value = attributes[ key ]; + + if( attr.isChanged( value, prev[ key ] ) ){ + changed[ key ] = value; + } + } + + this._changedAttributes = changed; + } + + return changed; + } + + changedAttributes( diff? : {} ) : boolean | {} { + if( !diff ) return this.hasChanged() ? assign( {}, this.changed ) : false; + + var val, changed : {} | boolean = false, + old = this._transaction ? this._previousAttributes : this.attributes, + attrSpecs = this._attributes; + + for( var attr in diff ){ + if( !attrSpecs[ attr ].isChanged( old[ attr ], ( val = diff[ attr ] ) ) ) continue; + (changed || (changed = {}))[ attr ] = val; + } + + return changed; + } + + hasChanged( key? : string ) : boolean { + const { _previousAttributes } = this; + if( !_previousAttributes ) return false; + + return key ? + this._attributes[ key ].isChanged( this.attributes[ key ], _previousAttributes[ key ] ) : + !isEmpty( this.changed ); + } + + previous( key : string ) : any { + if( key ){ + const { _previousAttributes } = this; + if( _previousAttributes ) return _previousAttributes[ key ]; + } + + return null; + } + + isNew() : boolean { + return this.id == null; + } + + has( key : string ) : boolean { + return this[ key ] != void 0; + } + + // Return attribute value, setting an attribute to undefined. + // TODO: If attribute was aggregated, don't dispose it. + unset( key : string, options? ) : any { + const value = this[ key ]; + this.set({ [ key ] : void 0 }, { unset : true, ...options }); + return value; + } + + // Undocumented. Move to NestedTypes? + clear( options? ) : this { + const nullify = options && options.nullify; + + this.transaction( () =>{ + this.forEachAttr( this.attributes, ( value, key ) => this[ key ] = nullify ? null : void 0 ); + }, options ); + + return this; + } + + // Returns Record owner skipping collections. TODO: Move out + getOwner() : Owner { + const owner : any = this._owner; + + // If there are no key, owner must be transactional object, and it's the collection. + // We don't expect that collection can be the member of collection, so we're skipping just one level up. An optimization. + return this._ownerKey ? owner : owner && owner._owner; + } + + /*********************************** + * Identity managements + */ + + // Id attribute name ('id' by default) + idAttribute : string; + + // Fixed 'id' property pointing to id attribute + get id() : string | number { return this.attributes[ this.idAttribute ]; } + set id( x : string | number ){ setAttribute( this, this.idAttribute, x ); } + + /*********************************** + * Dynamically compiled stuff + */ + + // Attributes specifications + _attributes : { [ key : string ] : AnyType } + _attributesArray : AnyType[] + + // Attributes object copy constructor + Attributes : AttributesConstructor + AttributesCopy : AttributesCopyConstructor + + // forEach function for traversing through attributes, with protective default implementation + // Overriden by dynamically compiled loop unrolled function in define.ts + forEachAttr( attrs : {}, iteratee : ( value : any, key? : string, spec? : AnyType ) => void ) : void { + const { _attributes } = this; + let unknown : string[]; + + for( let name in attrs ){ + const spec = _attributes[ name ]; + + if( spec ){ + iteratee( attrs[ name ], name, spec ); + } + else{ + unknown || ( unknown = [] ); + unknown.push( `'${ name }'` ); + } + } + + if( unknown ){ + this._log( 'warn', `attributes ${ unknown.join(', ')} are not defined`,{ + attributes : attrs + } ); + } + } + + each( iteratee : ( value? : any, key? : string ) => void, context? : any ){ + const fun = context !== void 0 ? ( v, k ) => iteratee.call( context, v, k ) : iteratee, + { attributes } = this; + + for( const key in this.attributes ){ + const value = attributes[ key ]; + if( value !== void 0 ) fun( value, key ); + } + } + + // Get array of attribute keys (Record) or record ids (Collection) + keys() : string[] { + const keys : string[] = []; + + this.each( ( value, key ) => value === void 0 || keys.push( key ) ); + + return keys; + } + + // Get array of attribute values (Record) or records (Collection) + values() : any[] { + return this.map( value => value ); + } + + // Create record default values, optionally augmenting given values. + defaults( values = {} ){ + const defaults = {}, + { _attributesArray } = this; + + for( let attr of _attributesArray ){ + const key = attr.name, + value = values[ key ]; + + defaults[ key ] = value === void 0 ? attr.defaultValue() : value; + } + + return defaults; + } + + /*************************************************** + * Record construction + */ + // Create record, optionally setting an owner + constructor( a_values? : {}, a_options? : ConstructorOptions ){ + super( _cidCounter++ ); + this.attributes = {}; + + const options = a_options || {}, + values = ( options.parse ? this.parse( a_values, options ) : a_values ) || {}; + + if( log.level > 1 ) typeCheck( this, values ); + + this._previousAttributes = this.attributes = new this.Attributes( this, values, options ); + + this.initialize( a_values, a_options ); + + if( this._localEvents ) this._localEvents.subscribe( this, this ); + } + + // Initialization callback, to be overriden by the subclasses + initialize( values?, options? ){} + + // Deeply clone record, optionally setting new owner. + clone( options : CloneOptions = {} ) : this { + const copy : this = new (this.constructor)( this.attributes, { clone : true } ); + + if( options.pinStore ) copy._defaultStore = this.getStore(); + + return copy; + } + + // Deprecated, every clone is the deep one now. + deepClone() : this { return this.clone() }; + + // Validate attributes. + _validateNested( errors : ChildrenErrors ) : number { + var length = 0; + + this.forEachAttr( this.attributes, ( value, name, attribute ) => { + const error = attribute.validate( this, value, name ); + + if( error ){ + errors[ name ] = error; + length++; + } + } ); + + return length; + } + + // Get attribute by key + get( key : string ) : any { + return this[ key ]; + } + + /** + * Serialization control + */ + + // Default record-level serializer, to be overriden by subclasses + toJSON( options? : object ) : any { + const json = {}; + + this.forEachAttr( this.attributes, ( value, key : string, { toJSON } ) =>{ + // If attribute serialization is not disabled, and its value is not undefined... + if( value !== void 0 ){ + // ...serialize it according to its spec. + const asJson = toJSON.call( this, value, key, options ); + + // ...skipping undefined values. Such an attributes are excluded. + if( asJson !== void 0 ) json[ key ] = asJson; + } + }); + + return json; + } + + // Default record-level parser, to be overriden by the subclasses. + parse( data, options? : TransactionOptions ){ + return data; + } + + // DEPRECATED: Attributes-level parse. Is moved to attribute descriptors. + _parse( data ){ return data; } + + /** + * Transactional control + */ + + deepSet( name : string, value : any, options? ){ + // Operation might involve series of nested object updates, thus it's wrapped in transaction. + this.transaction( () => { + const path = name.split( '.' ), + l = path.length - 1, + attr = path[ l ]; + + let model = this; + + // Locate the model, traversing the path. + for( let i = 0; i < l; i++ ){ + const key = path[ i ]; + + // There might be collections in path, so use `get`. + let next = model.get ? model.get( key ) : model[ key ]; + + // Create models, if they are not exist. + if( !next ){ + const attrSpecs = model._attributes; + if( attrSpecs ){ + // If current object is model, create default attribute + var newModel = attrSpecs[ key ].create(); + + // If created object is model, nullify attributes when requested + if( options && options.nullify && newModel._attributes ){ + newModel.clear( options ); + } + + model[ key ] = next = newModel; + } + // Silently fail in other case. + else return; + } + + model = next; + } + + // Set model attribute. + if( model.set ){ + model.set({ [ attr ] : value }, options ); + } + else{ + model[ attr ] = value; + } + }); + + return this; + } + + // Returns owner without the key (usually it's collection) + get collection() : any { + return this._ownerKey ? null : this._owner; + } + + // Dispose object and all childrens + dispose(){ + if( this._disposed ) return; + + this.forEachAttr( this.attributes, ( value, key, attribute ) => { + attribute.dispose( this, value ); + }); + + super.dispose(); + } + + _log( level : tools.LogLevel, text : string, props : object ) : void { + tools.log( level, '[Record] ' + text, { + 'Record' : this, + 'Attributes definition:' : this._attributes, + ...props + }); + } + + getClassName() : string { + return super.getClassName() || 'Record'; + } + + // Dummies to + _createTransaction( values : object, options : TransactionOptions ) : Transaction { return void 0; } + // Simulate attribute change + forceAttributeChange : ( key : string, options : TransactionOptions ) => void + _onChildrenChange : ( child : Transactional, options : TransactionOptions ) => void +}; + +assign( Record.prototype, UpdateRecordMixin, IORecordMixin ); + +/*********************************************** + * Helper functions + */ + +class BaseRecordAttributes { + id : string | number + + constructor( record : Record, x : AttributesValues, options : TransactionOptions ) { + this.id = x.id; + } +} + +Record.prototype.Attributes = BaseRecordAttributes; + +class BaseRecordAttributesCopy { + id : string | number + + constructor( x : AttributesValues ) { + this.id = x.id; + } +} + +Record.prototype.AttributesCopy = BaseRecordAttributesCopy; + +const IdAttribute = AnyType.create({ value : void 0 }, 'id' ); +Record.prototype._attributes = { id : IdAttribute }; +Record.prototype._attributesArray = [ IdAttribute ]; +Record._attribute = AggregatedType; + +import { shouldBeAnObject } from './attributes' + +function typeCheck( record : Record, values : object ){ + if( shouldBeAnObject( record, values ) ){ + const { _attributes } = record; + let unknown : string[]; + + for( let name in values ){ + if( !_attributes[ name ] ){ + unknown || ( unknown = [] ); + unknown.push( `'${ name }'` ); + } + } + + if( unknown ){ + record._log( 'warn', `undefined attributes ${ unknown.join(', ')} are ignored.`, { values } ); + } + } +} \ No newline at end of file diff --git a/src/type-r/relations/commons.ts b/src/type-r/relations/commons.ts new file mode 100644 index 0000000..6248b68 --- /dev/null +++ b/src/type-r/relations/commons.ts @@ -0,0 +1,18 @@ +import { Collection } from '../collection' +import { Record } from '../record' +import { CompiledReference } from '../traversable' + +export type CollectionReference = ( () => Collection ) | Collection | string; + +/** @private */ +export function parseReference( collectionRef : CollectionReference ) : ( root : Record ) => Collection { + switch( typeof collectionRef ){ + case 'function' : + return root => (collectionRef).call( root ); + case 'object' : + return () => collectionRef; + case 'string' : + const { resolve } = new CompiledReference( collectionRef ); + return resolve; + } +} \ No newline at end of file diff --git a/src/type-r/relations/from.ts b/src/type-r/relations/from.ts new file mode 100644 index 0000000..5ef3f13 --- /dev/null +++ b/src/type-r/relations/from.ts @@ -0,0 +1,72 @@ +import { AnyType, AttributeOptions } from '../record' +import { parseReference, CollectionReference } from './commons' +import { Collection } from '../collection' +import { Record } from '../record' + +import { ChainableAttributeSpec } from '../record' + +/******** + * Reference to model by id. + * + * Untyped attribute. Holds model id, when unresolved. When resolved, is substituted + * with a real model. + * + * No model changes are detected and counted as owner's change. That's intentional. + */ + +/** @private */ +type RecordRefValue = Record | string; + +/** @private */ +class RecordRefType extends AnyType { + // It is always serialized as an id, whenever it's resolved or not. + toJSON( value : RecordRefValue ){ + return value && typeof value === 'object' ? value.id : value; + } + + // Wne + clone( value : RecordRefValue ){ + return value && typeof value === 'object' ? value.id : value; + } + + // Model refs by id are equal when their ids are equal. + isChanged( a : RecordRefValue, b : RecordRefValue){ + var aId = a && ( (a).id == null ? a : (a).id ), + bId = b && ( (b).id == null ? b : (b).id ); + + return aId !== bId; + } + + // Refs are always valid. + validate( model, value, name ){} +} + +Record.from = function from( masterCollection : CollectionReference ) : ChainableAttributeSpec { + const getMasterCollection = parseReference( masterCollection ); + + const typeSpec = new ChainableAttributeSpec({ + value : null, + _attribute : RecordRefType + }); + + return typeSpec + .get( function( objOrId : RecordRefValue, name : string ) : Record { + if( typeof objOrId === 'object' ) return objOrId; + + // So, we're dealing with an id reference. Resolve it. + const collection = getMasterCollection( this ); + let record : Record = null; + + // If master collection exists and is not empty... + if( collection && collection.length ){ + // Silently update attribute with record from this collection. + record = collection.get( objOrId ) || null; + this.attributes[ name ] = record; + + // Subscribe for events manually. delegateEvents won't be invoked. + record && this._attributes[ name ].handleChange( record, null, this, {} ); + } + + return record; + }); +}; \ No newline at end of file diff --git a/src/type-r/relations/index.ts b/src/type-r/relations/index.ts new file mode 100644 index 0000000..3052dd5 --- /dev/null +++ b/src/type-r/relations/index.ts @@ -0,0 +1,4 @@ +import './from' +import './subsetOf' + +export * from './store' \ No newline at end of file diff --git a/src/type-r/relations/store.ts b/src/type-r/relations/store.ts new file mode 100644 index 0000000..6ee3c3b --- /dev/null +++ b/src/type-r/relations/store.ts @@ -0,0 +1,32 @@ +import { Record } from '../record' +import { Transactional } from '../transactions' +import { startIO, IOPromise } from '../io-tools' + +let _store : Store = null; + +export class Store extends Record { + getStore() : Store { return this; } + + // delegate item lookup to owner, and to the global store if undefined + get( name : string ) : any { + // Lookup for resource in the current store. + let local = this[ name ]; + + // If something is found or it's the global store, return result. + if( local || this === this._defaultStore ) return local; + + // Forward failed lookup to owner or global store. + return this._owner ? this._owner.get( name ) : this._defaultStore.get( name ); + } + + static get global(){ return _store; } + static set global( store : Store ){ + if( _store ){ + _store.dispose(); + } + + Transactional.prototype._defaultStore = _store = store; + } +} + +Store.global = new Store(); \ No newline at end of file diff --git a/src/type-r/relations/subsetOf.ts b/src/type-r/relations/subsetOf.ts new file mode 100644 index 0000000..0e21d1e --- /dev/null +++ b/src/type-r/relations/subsetOf.ts @@ -0,0 +1,198 @@ +import { Collection, CollectionOptions } from '../collection' +import { tools, eventsApi, define } from '../object-plus' +import { Record, AggregatedType } from '../record' +import { parseReference, CollectionReference } from './commons' +import { ChainableAttributeSpec } from '../record' +import { Transactional, ItemsBehavior, TransactionOptions, transactionApi } from '../transactions' + +const { fastDefaults } = tools; + +type RecordsIds = ( string | number )[]; + +Collection.subsetOf = function subsetOf( masterCollection : CollectionReference ) : ChainableAttributeSpec { + const SubsetOf = this._SubsetOf || ( this._SubsetOf = defineSubsetCollection( this ) ), + getMasterCollection = parseReference( masterCollection ), + typeSpec = new ChainableAttributeSpec({ + type : SubsetOf + }); + + return typeSpec.get( + function( refs ){ + !refs || refs.resolvedWith || refs.resolve( getMasterCollection( this ) ); + return refs; + } + ); +}; + +const subsetOfBehavior = ItemsBehavior.share | ItemsBehavior.persistent; + +function defineSubsetCollection( CollectionConstructor : typeof Collection ) { + @define class SubsetOfCollection extends CollectionConstructor { + refs : any[]; + resolvedWith : Collection = null; + + _attribute : AggregatedType + + get __inner_state__(){ return this.refs || this.models; } + + constructor( recordsOrIds?, options? ){ + super( [], options, subsetOfBehavior ); + this.refs = toArray( recordsOrIds ); + } + + // Remove should work fine as it already accepts ids. Add won't... + add( a_elements, options = {} ){ + const { resolvedWith } = this, + toAdd = toArray( a_elements ); + + if( resolvedWith ){ + // If the collection is resolved already, everything is simple. + return super.add( resolveRefs( resolvedWith, toAdd ), options ); + } + else{ + // Collection is not resolved yet. So, we prepare the delayed computation. + if( toAdd.length ){ + const isRoot = transactionApi.begin( this ); + + // Save elements to resolve in future... + this.refs = this.refs ? this.refs.concat( toAdd ) : toAdd.slice(); + + transactionApi.markAsDirty( this, options ); + + // And throw the 'changes' event. + isRoot && transactionApi.commit( this ); + } + } + } + + reset( a_elements?, options = {} ){ + const { resolvedWith } = this, + elements = toArray( a_elements ); + + return resolvedWith ? + // Collection is resolved, so parse ids and forward the call to set. + super.reset( resolveRefs( resolvedWith, elements ), options ) : + // Collection is not resolved yet. So, we prepare the delayed computation. + delaySet( this, elements, options ) || []; + } + + _createTransaction( a_elements, options? ){ + const { resolvedWith } = this, + elements = toArray( a_elements ); + + return resolvedWith ? + // Collection is resolved, so parse ids and forward the call to set. + super._createTransaction( resolveRefs( resolvedWith, elements ), options ) : + // Collection is not resolved yet. So, we prepare the delayed computation. + delaySet( this, elements, options ); + } + + // Serialized as an array of model ids. + toJSON() : RecordsIds { + return this.refs ? + this.refs.map( objOrId => objOrId.id || objOrId ) : + this.models.map( model => model.id ); + } + + // Subset is always valid. + _validateNested(){ return 0; } + + get length() : number { + return this.models.length || ( this.refs ? this.refs.length : 0 ); + } + + // Must be shallow copied on clone. + clone( owner? ){ + var Ctor = (this).constructor, + copy = new Ctor( [], { + model : this.model, + comparator : this.comparator + }); + + if( this.resolvedWith ){ + // TODO: bug here. + copy.resolvedWith = this.resolvedWith; + copy.refs = null; + copy.reset( this.models, { silent : true } ); + } + else{ + copy.refs = this.refs.slice(); + } + + return copy; + } + + // Clean up the custom parse method possibly defined in the base class. + parse( raw : any ) : Record[] { + return raw; + } + + resolve( collection : Collection ) : this { + if( collection && collection.length ){ + this.resolvedWith = collection; + + if( this.refs ){ + this.reset( this.refs, { silent : true } ); + this.refs = null; + } + } + + return this; + } + + getModelIds() : RecordsIds { return this.toJSON(); } + + toggle( modelOrId : any, val : boolean ) : boolean { + return super.toggle( this.resolvedWith.get( modelOrId ), val ); + } + + addAll() : Record[] { + if( this.resolvedWith ){ + this.set( this.resolvedWith.models ); + return this.models; + } + + throw new Error( "Cannot add elemens because the subset collection is not resolved yet." ); + } + + toggleAll() : Record[] { + return this.length ? this.reset() : this.addAll(); + } + } + + // Clean up all custom item events to prevent memory leaks. + SubsetOfCollection.prototype._itemEvents = void 0; + + return SubsetOfCollection; +} + +function resolveRefs( master, elements ){ + const records = []; + + for( let el of elements ){ + const record = master.get( el ); + if( record ) records.push( record ); + } + + return records; +} + +function delaySet( collection, elements, options ) : void { + if( tools.notEqual( collection.refs, elements ) ){ + const isRoot = transactionApi.begin( collection ); + + // Save elements to resolve in future... + collection.refs = elements.slice(); + + transactionApi.markAsDirty( collection, options ); + + // And throw the 'changes' event. + isRoot && transactionApi.commit( collection ); + } +} + +function toArray( elements ){ + return elements ? ( + Array.isArray( elements ) ? elements : [ elements ] + ) : []; +} \ No newline at end of file diff --git a/src/type-r/transactions.ts b/src/type-r/transactions.ts new file mode 100644 index 0000000..915af16 --- /dev/null +++ b/src/type-r/transactions.ts @@ -0,0 +1,499 @@ +import { Messenger, CallbacksByEvents, MessengersByCid, MixinsState, MixinMergeRules, MessengerDefinition, tools, mixins, mixinRules, definitions, eventsApi, define, Subclass } from './object-plus' +import { ValidationError, Validatable, ChildrenErrors } from './validation' +import { Traversable, resolveReference } from './traversable' +import { IOEndpoint, IOPromise, IONode, abortIO } from './io-tools' + +const { assign } = tools, + { trigger2, trigger3, on, off } = eventsApi; +/*** + * Abstract class implementing ownership tree, tho-phase transactions, and validation. + * 1. createTransaction() - apply changes to an object tree, and if there are some events to send, transaction object is created. + * 2. transaction.commit() - send and process all change events, and close transaction. + */ + +/** @private */ +export interface TransactionalDefinition extends MessengerDefinition { + endpoint? : IOEndpoint +} + +export enum ItemsBehavior { + share = 0b0001, + listen = 0b0010, + persistent = 0b0100 +} + +// Transactional object interface +@define +@definitions({ + endpoint : mixinRules.value +}) +@mixins( Messenger ) +export abstract class Transactional implements Messenger, IONode, Validatable, Traversable { + // Mixins are hard in TypeScript. We need to copy type signatures over... + // Here goes 'Mixable' mixin. + static endpoint : IOEndpoint; + static __super__ : object; + static mixins : MixinsState; + static define : ( definition? : TransactionalDefinition, statics? : object ) => typeof Transactional; + static extend : ( definition? : T, statics? : object ) => any; + + static onDefine( definitions : TransactionalDefinition, BaseClass : typeof Transactional ){ + if( definitions.endpoint ) this.prototype._endpoint = definitions.endpoint; + Messenger.onDefine.call( this, definitions, BaseClass ); + }; + + static onExtend( BaseClass : typeof Transactional ) : void { + // Make sure we don't inherit class factories. + if( BaseClass.create === this.create ) { + this.create = Transactional.create; + } + } + + // Define extendable mixin static properties. + static create( a : any, b? : any ) : Transactional { + return new (this as any)( a, b ); + } + + /** Generic class factory. May be overridden for abstract classes. Not inherited. */ + on : ( events : string | CallbacksByEvents, callback, context? ) => this + once : ( events : string | CallbacksByEvents, callback, context? ) => this + off : ( events? : string | CallbacksByEvents, callback?, context? ) => this + trigger : (name : string, a?, b?, c?, d?, e? ) => this + + stopListening : ( source? : Messenger, a? : string | CallbacksByEvents, b? : Function ) => this + listenTo : ( source : Messenger, a : string | CallbacksByEvents, b? : Function ) => this + listenToOnce : ( source : Messenger, a : string | CallbacksByEvents, b? : Function ) => this + + _disposed : boolean; + + // State accessor. + readonly __inner_state__ : any; + + // Shared modifier (used by collections of shared models) + _shared? : number; + + dispose() : void { + if( this._disposed ) return; + + abortIO( this ); + this._owner = void 0; + this._ownerKey = void 0; + this.off(); + this.stopListening(); + this._disposed = true; + } + + // Must be called at the end of the constructor in the subclass. + initialize() : void {} + + /** @private */ + _events : eventsApi.HandlersByEvent = void 0; + + /** @private */ + _listeningTo : MessengersByCid + + /** @private */ + _localEvents : eventsApi.EventMap + + cid : string + cidPrefix : string + + static shared : any; + + // Unique version token replaced on change + /** @private */ + _changeToken : {} = {} + + // true while inside of the transaction + /** @private */ + _transaction : boolean = false; + + // Holds current transaction's options, when in the middle of transaction and there're changes but is an unsent change event + /** @private */ + _isDirty : TransactionOptions = null; + + // Backreference set by owner (Record, Collection, or other object) + /** @private */ + _owner : Owner = void 0; + + // Key supplied by owner. Used by record to identify attribute key. + // Only collections doesn't set the key, which is used to distinguish collections. + /** @private */ + _ownerKey : string = void 0; + + // Name of the change event + /** @private */ + _changeEventName : string + + /** + * Subsribe for the changes. + */ + onChanges( handler : Function, target? : Messenger ){ + on( this, this._changeEventName, handler, target ); + } + + /** + * Unsubscribe from changes. + */ + offChanges( handler? : Function, target? : Messenger ){ + off( this, this._changeEventName, handler, target ); + } + + /** + * Listen to changes event. + */ + listenToChanges( target : Transactional, handler ){ + this.listenTo( target, target._changeEventName, handler ); + } + + constructor( cid : string | number ){ + this.cid = this.cidPrefix + cid; + } + + // Deeply clone ownership subtree + abstract clone( options? : CloneOptions ) : this + + // Execute given function in the scope of ad-hoc transaction. + transaction( fun : ( self : this ) => void, options : TransactionOptions = {} ) : void{ + const isRoot = transactionApi.begin( this ); + const update = fun.call( this, this ); + update && this.set( update ); + isRoot && transactionApi.commit( this ); + } + + // Loop through the members in the scope of transaction. + // Transactional version of each() + updateEach( iteratee : ( val : any, key : string | number ) => void, options? : TransactionOptions ){ + const isRoot = transactionApi.begin( this ); + this.each( iteratee ); + isRoot && transactionApi.commit( this ); + } + + // Apply bulk in-place object update in scope of ad-hoc transaction + set( values : any, options? : TransactionOptions ) : this { + if( values ){ + const transaction = this._createTransaction( values, options ); + transaction && transaction.commit(); + } + + return this; + } + + // Assign transactional object "by value", copying aggregated items. + assignFrom( source : Transactional | Object ) : this { + // Need to delay change events until change token willl by synced. + this.transaction( () =>{ + this.set( ( source ).__inner_state__ || source, { merge : true } ); + + // Synchronize change tokens + const { _changeToken } = source as any; + + if( _changeToken ){ + this._changeToken = _changeToken; + } + }); + + return this; + } + + // Apply bulk object update without any notifications, and return open transaction. + // Used internally to implement two-phase commit. + // Returns null if there are no any changes. + /** @private */ + abstract _createTransaction( values : any, options? : TransactionOptions ) : Transaction | void + + // Parse function applied when 'parse' option is set for transaction. + parse( data : any, options? : TransactionOptions ) : any { return data } + + // Convert object to the serializable JSON structure + abstract toJSON( options? : object ) : {} + + /******************* + * Traversals and member access + */ + + // Get object member by its key. + abstract get( key : string ) : any + + // Get object member by symbolic reference. + deepGet( reference : string ) : any { + return resolveReference( this, reference, ( object, key ) => object.get ? object.get( key ) : object[ key ] ); + } + + //_isCollection : boolean + + // Return owner skipping collections. + getOwner() : Owner { + return this._owner; + } + + // Store used when owner chain store lookup failed. Static value in the prototype. + /** @private */ + _defaultStore : Transactional + + // Locate the closest store. Store object stops traversal by overriding this method. + getStore() : Transactional { + const { _owner } = this; + return _owner ? _owner.getStore() : this._defaultStore; + } + + + /*************************************************** + * Iteration API + */ + + // Loop through the members. Must be efficiently implemented in container class. + abstract each( iteratee : ( val : any, key : string | number ) => void, context? : any ) + + // Map members to an array + map( iteratee : ( val : any, key : string | number ) => T, context? : any ) : T[]{ + const arr : T[] = [], + fun = context !== void 0 ? ( v, k ) => iteratee.call( context, v, k ) : iteratee; + + this.each( ( val, key ) => { + const result = fun( val, key ); + if( result !== void 0 ) arr.push( result ); + } ); + + return arr; + } + + _endpoint : IOEndpoint + _ioPromise : IOPromise + + hasPendingIO() : IOPromise { return this._ioPromise; } + + fetch( options? : object ) : IOPromise { throw new Error( "Not implemented" ); } + + getEndpoint() : IOEndpoint { + return getOwnerEndpoint( this ) || this._endpoint; + } + + // Map members to an object + mapObject( iteratee : ( val : any, key : string | number ) => T, context? : any ) : { [ key : string ] : T }{ + const obj : { [ key : string ] : T } = {}, + fun = context !== void 0 ? ( v, k ) => iteratee.call( context, v, k ) : iteratee; + + this.each( ( val, key ) => { + const result = iteratee( val, key ); + if( result !== void 0 ) obj[ key ] = result; + } ); + + return obj; + } + + /********************************* + * Validation API + */ + + // Lazily evaluated validation error + /** @private */ + _validationError : ValidationError = void 0 + + // Validate ownership tree and return valudation error + get validationError() : ValidationError { + const error = this._validationError || ( this._validationError = new ValidationError( this ) ); + return error.length ? error : null; + } + + // Validate nested members. Returns errors count. + /** @private */ + abstract _validateNested( errors : ChildrenErrors ) : number + + // Object-level validator. Returns validation error. + validate( obj? : Transactional ) : any {} + + // Return validation error (or undefined) for nested object with the given key. + getValidationError( key : string ) : any { + var error = this.validationError; + return ( key ? error && error.nested[ key ] : error ) || null; + } + + // Get validation error for the given symbolic reference. + deepValidationError( reference : string ) : any { + return resolveReference( this, reference, ( object, key ) => object.getValidationError( key ) ); + } + + // Iterate through all validation errors across the ownership tree. + eachValidationError( iteratee : ( error : any, key : string, object : Transactional ) => void ) : void { + const { validationError } = this; + validationError && validationError.eachError( iteratee, this ); + } + + // Check whenever member with a given key is valid. + isValid( key : string ) : boolean { + return !this.getValidationError( key ); + } + + valueOf() : Object { return this.cid; } + toString(){ return this.cid; } + + // Get class name for an object instance. Works fine with ES6 classes definitions (not in IE). + getClassName() : string { + const { name } = this.constructor; + if( name !== 'Subclass' ) return name; + } + + // Logging interface for run time errors and warnings. + abstract _log( level : string, text : string, value : any ) : void; +} + +export interface CloneOptions { + // 'Pin store' shall assign this._defaultStore = this.getStore(); + pinStore? : boolean +} + +// Owner must accept children update events. It's an only way children communicates with an owner. +/** @private */ +export interface Owner extends Traversable, Messenger { + _onChildrenChange( child : Transactional, options : TransactionOptions ) : void; + getOwner() : Owner + getStore() : Transactional +} + +// Transaction object used for two-phase commit protocol. +// Must be implemented by subclasses. +// Transaction must be created if there are actual changes and when markIsDirty returns true. +/** @private */ +export interface Transaction { + // Object transaction is being made on. + object : Transactional + + // Send out change events, process update triggers, and close transaction. + // Nested transactions must be marked with isNested flag (it suppress owner notification). + commit( initiator? : Transactional ) +} + +// Options for distributed transaction +export interface TransactionOptions { + // Invoke parsing + parse? : boolean + + // Suppress change notifications and update triggers + silent? : boolean + + // Update existing transactional members in place, or skip the update (ignored by models) + merge? : boolean // =true + + // Should collections remove elements in set (ignored by models) + remove? : boolean // =true + + // Always replace enclosed objects with new instances + reset? : boolean // = false + + // Do not dispose aggregated members + unset? : boolean + + validate? : boolean + + // `true` if the transaction is initiated as a result of IO operation + ioUpdate? : boolean + + // The hint for IOEndpoint + // If `true`, `record.save()` will behave as "upsert" operation for the records having id. + upsert? : boolean +} + +/** + * Low-level transactions API. Must be used like this: + * const isRoot = begin( record ); + * ... + * isRoot && commit( record, options ); + * + * When committing nested transaction, the flag must be set to true. + * commit( object, options, isNested ) + */ + +export const transactionApi = { + // Start transaction. Return true if it's the root one. + /** @private */ + begin( object : Transactional ) : boolean { + return object._transaction ? false : ( object._transaction = true ); + }, + + // Mark object having changes inside of the current transaction. + // Returns true whenever there notifications are required. + /** @private */ + markAsDirty( object : Transactional, options : TransactionOptions ) : boolean { + // If silent option is in effect, don't set isDirty flag. + const dirty = !options.silent; + if( dirty ) object._isDirty = options; + + // Reset version token. + object._changeToken = {}; + + // Object is changed, so validation must happen again. Clear the cache. + object._validationError = void 0; + + return dirty; + }, + + // Commit transaction. Send out change event and notify owner. Returns true if there were changes. + // Must be executed for the root transaction only. + /** @private */ + commit( object : Transactional, initiator? : Transactional ){ + let originalOptions = object._isDirty; + + if( originalOptions ){ + // Send the sequence of change events, handling chained handlers. + while( object._isDirty ){ + const options = object._isDirty; + object._isDirty = null; + trigger3( object, object._changeEventName, object, options, initiator ); + } + + // Mark transaction as closed. + object._transaction = false; + + // Notify owner on changes out of transaction scope. + const { _owner } = object; + if( _owner && _owner !== initiator ){ // If it's the nested transaction, owner is already aware there are some changes. + _owner._onChildrenChange( object, originalOptions ); + } + } + else{ + // No changes. Silently close transaction. + object._isDirty = null; + object._transaction = false; + } + }, + + /************************************ + * Ownership management + */ + + // Add reference to the record. + /** @private */ + aquire( owner : Owner, child : Transactional, key? : string ) : boolean { + if( !child._owner ){ + child._owner = owner; + child._ownerKey = key; + return true; + } + + return child._owner === owner; + }, + + // Remove reference to the record. + /** @private */ + free( owner : Owner, child : Transactional ) : void { + if( owner === child._owner ){ + child._owner = void 0; + child._ownerKey = void 0; + } + } +} + +function getOwnerEndpoint( self : Transactional ) : IOEndpoint { + // Check if we are the member of the collection... + const { collection } = self as any; + if( collection ){ + return getOwnerEndpoint( collection ); + } + + // Now, if we're the member of the model... + if( self._owner ){ + const { _endpoints } = self._owner as any; + return _endpoints && _endpoints[ self._ownerKey ]; + } +} diff --git a/src/type-r/traversable.ts b/src/type-r/traversable.ts new file mode 100644 index 0000000..f0e3974 --- /dev/null +++ b/src/type-r/traversable.ts @@ -0,0 +1,72 @@ +/** + * Some sketches for reference resolution. + * + * + * a : Model.from( '~collection' ) + * + * We need two functions. One for get, and one for compile. + */ +export interface Traversable { + getStore() : Traversable + getOwner() : Traversable + get( key : string ) : any +} + +const referenceMask = /\^|(store\.[^.]+)|([^.]+)/g; + +// Compile reference to function +export type ResolveReference = ( root : Traversable ) => any; + +export class CompiledReference { + resolve : ResolveReference + tail : string + local : boolean + + constructor( reference : string, splitTail : boolean = false ){ + const path = reference + .match( referenceMask ) + .map( key => { + if( key === '^' || key === 'owner' ) return 'getOwner()'; + + if( key[ 0 ] === '~' ) return `getStore().get("${ key.substr( 1 ) }")`; + + if( key.indexOf( 'store.' ) === 0 ) return `getStore().get("${ key.substr( 6 ) }")`; + + return key; + } ); + + this.tail = splitTail && path.pop(); + this.local = !path.length; + + this.resolve = new Function( 'self', ` + var v = self.${ path.shift() }; + + ${ path.map( x => ` + v = v && v.${ x }; + `).join('')} + + return v; + ` ); + } +} + +export function resolveReference( root : Traversable, reference : string, action : ( object, key : string ) => any ) : any { + const path = reference.match( referenceMask ), + skip = path.length - 1; + + let self = root; + + for( var i = 0; i < skip; i++ ){ + const key = path[ i ]; + switch( key ){ + case '~' : self = self.getStore(); break; + case '^' : self = self.getOwner(); break; + default : self = self.get( key ); + } + + // Do nothing if object on the path doesn't exist. + if( !self ) return; + } + + return action( self, path[ skip ] ); +} \ No newline at end of file diff --git a/src/type-r/validation.ts b/src/type-r/validation.ts new file mode 100644 index 0000000..ff023a9 --- /dev/null +++ b/src/type-r/validation.ts @@ -0,0 +1,48 @@ +export interface ChildrenErrors { + [ key : string ] : ValidationError | any +} + +export interface Validatable { + _validateNested( errors : ChildrenErrors ) : number; + validate( self : any ) : any + get( key : string ) : any +} + +// Validation error object. +export class ValidationError { + // Invalid nested object keys + nested : ChildrenErrors + length : number + + // Local error + error : any + + constructor( obj : Validatable ){ + this.length = obj._validateNested( this.nested = {} ); + + if( this.error = obj.validate( obj ) ){ + this.length++; + } + } + + each( iteratee : ( value : any, key : string ) => void ) : void { + const { error, nested } = this; + + if( error ) iteratee( error, null ); + + for( const key in nested ){ + iteratee( nested[ key ], key ); + } + } + + eachError( iteratee : ( error : any, key : string, object : Validatable ) => void, object : Validatable ) : void { + this.each( ( value : any, key : string ) => { + if( value instanceof ValidationError ){ + (value).eachError( iteratee, object.get( key ) ); + } + else{ + iteratee( value, key, object ); + } + }); + } +} \ No newline at end of file diff --git a/src/underscore-mixin.ts b/src/underscore-mixin.ts new file mode 100644 index 0000000..f0a3530 --- /dev/null +++ b/src/underscore-mixin.ts @@ -0,0 +1,118 @@ +import * as _ from 'underscore' + +export const ModelMixin = { + pick( ...args : any[] ){ + return _.pick( this, args ); + }, + + escape( attr ){ + return _.escape( this[ attr ] ); + }, + + matches( attrs ){ + return !!_.iteratee( attrs, this )( this ); + }, + + omit( ...keys : string[] ) : {} { + return this.mapObject( ( value, key ) => { + if( keys.indexOf( key ) < 0 ){ + return value; + } + }); + }, + + invert(){ + const inverted = {}; + this.each( ( value, key ) => inverted[ value ] = key ); + return inverted; + }, + + pairs(){ + return this.map( ( value, key ) => [ key, value ] ); + }, + + isEmpty(){ + return !this.values().length; + }, + + chain(){ + return _.chain( this.mapObject( x => x ) ); + } +}; + +export const CollectionMixin = { + where(attrs, first) { + return this[first ? 'find' : 'filter'](attrs); + }, + + findWhere(attrs) { + return this.where(attrs, true); + } +}; + +addUnderscoreMethods( CollectionMixin, 'models', { + forEach : 3, each : 3, map : 3, collect : 3, reduce : 4, + foldl : 4, inject : 4, reduceRight : 4, foldr : 4, find : 3, findIndex : 3, findLastIndex : 3, detect : 3, filter : 3, + select : 3, reject : 3, every : 3, all : 3, some : 3, any : 3, include : 3, includes : 3, + contains : 3, invoke : 0, max : 3, min : 3, toArray : 1, size : 1, first : 3, + head : 3, take : 3, initial : 3, rest : 3, tail : 3, drop : 3, last : 3, + without : 0, difference : 0, indexOf : 3, shuffle : 1, lastIndexOf : 3, + isEmpty : 1, chain : 1, sample : 3, partition : 3, groupBy : 3, countBy : 3, + sortBy : 3, indexBy : 3 +}); + +function addUnderscoreMethods(Mixin, attribute, methods ) { + _.each(methods, function(length, method) { + if (_[method]) Mixin[method] = addMethod(length, method, attribute); + }); +} + +// Proxy Backbone class methods to Underscore functions, wrapping the model's +// `attributes` object or collection's `models` array behind the scenes. +// +// collection.filter(function(model) { return model.get('age') > 10 }); +// collection.each(this.addView); +// +// `Function#apply` can be slow so we use the method's arg count, if we know it. +function addMethod(length, method, attribute) { + switch (length) { + case 1: return function() { + return _[method](this[attribute]); + }; + case 2: return function(value) { + return _[method](this[attribute], value); + }; + case 3: return function(iteratee, context) { + var value = this[ attribute ], + callback = cb(iteratee, this); + + return arguments.length > 1 ? + _[method]( value, callback, context) + : _[method]( value, callback ); + }; + case 4: return function(iteratee, defaultVal, context) { + var value = this[ attribute ], + callback = cb(iteratee, this); + + return arguments.length > 1 ? + _[method]( value, callback, defaultVal, context ) + : _[method](value, callback ); + }; + default: return function( ...args : any[] ) { + args.unshift(this[attribute]); + return _[method].apply(_, args); + }; + } +} + +// Support `collection.sortBy('attr')` and `collection.findWhere({id: 1})`. +function cb(iteratee, instance) { + switch( typeof iteratee ){ + case 'function' : return iteratee; + case 'string' : return model => model.get( iteratee ); + case 'object' : + if( !(iteratee instanceof instance.model )) return _.matches( iteratee ); + } + + return iteratee; +} \ No newline at end of file diff --git a/submodules/Type-R b/submodules/Type-R new file mode 160000 index 0000000..7edd1e4 --- /dev/null +++ b/submodules/Type-R @@ -0,0 +1 @@ +Subproject commit 7edd1e49cb024ef674a870072943de3ff602ccba diff --git a/tests/backbone/collection.js b/tests/backbone/collection.js index e388068..7c345e7 100644 --- a/tests/backbone/collection.js +++ b/tests/backbone/collection.js @@ -147,7 +147,7 @@ var one = col.get( 0 ); assert.equal( one.get( 'name' ), 'one' ); col.on( 'change:name', function( model ){ - assert.ok( this.get( model ) ); + assert.ok( col.get( model ) ); } ); one.set( { name : 'dalmatians', id : 101 } ); assert.equal( col.get( 0 ), null ); @@ -166,6 +166,8 @@ } ); QUnit.test( "add", function( assert ){ + otherCol = new M.Collection.Refs(); + assert.expect( 13 ); var added, opts, secondAdded; added = opts = secondAdded = null; @@ -189,7 +191,7 @@ var f = new M( { id : 20, label : 'f' } ); var g = new M( { id : 21, label : 'g' } ); var h = new M( { id : 22, label : 'h' } ); - var atCol = new M.Collection( [ f, g, h ] ); + var atCol = new M.Collection.Refs( [ f, g, h ] ); assert.equal( atCol.length, 3 ); atCol.add( e, { at : 1 } ); assert.equal( atCol.length, 4 ); @@ -269,7 +271,7 @@ QUnit.test( "add model to multiple collections", function( assert ){ assert.expect( 10 ); var counter = 0; - var e = new Backbone.Model( { id : 10, label : 'e' } ); + var e = new ( Backbone.Model.defaults( { id : 10, label : 'e' } ) ); e.on( 'add', function( model, collection ){ counter++; assert.equal( e, model ); @@ -285,7 +287,7 @@ assert.equal( e, model ); assert.equal( colE, collection ); } ); - var colF = new Backbone.Collection( [] ); + var colF = new Backbone.Collection.Refs( [] ); colF.on( 'add', function( model, collection ){ assert.equal( e, model ); assert.equal( colF, collection ); @@ -468,14 +470,16 @@ id : 5, title : 'Othello' }; + + var M = Backbone.attributes( modelData ); var passed = false; - var e = new Backbone.Model( modelData ); - var f = new Backbone.Model( modelData ); + var e = new M( modelData ); + var f = new M( modelData ); f.on( 'remove', function(){ passed = true; } ); - var colE = new Backbone.Collection( [ e ] ); - var colF = new Backbone.Collection( [ f ] ); + var colE = new M.Collection( [ e ] ); + var colF = new M.Collection( [ f ] ); assert.ok( e != f ); assert.ok( colE.length === 1 ); assert.ok( colF.length === 1 ); @@ -489,8 +493,11 @@ QUnit.test( "remove same model in multiple collection", function( assert ){ assert.expect( 16 ); + + var M = Backbone.attributes({ id : 5, title : 'Othello' }); + var counter = 0; - var e = new Backbone.Model( { id : 5, title : 'Othello' } ); + var e = new M(); e.on( 'remove', function( model, collection ){ counter++; assert.equal( e, model ); @@ -501,12 +508,12 @@ assert.equal( collection, colF ); } } ); - var colE = new Backbone.Collection( [ e ] ); + var colE = new M.Collection( [ e ] ); colE.on( 'remove', function( model, collection ){ assert.equal( e, model ); assert.equal( colE, collection ); } ); - var colF = new Backbone.Collection( [ e ] ); + var colF = new M.Collection.Refs( [ e ] ); colF.on( 'remove', function( model, collection ){ assert.equal( e, model ); assert.equal( colF, collection ); @@ -519,6 +526,7 @@ assert.equal( colE, e.collection ); colE.remove( e ); assert.equal( null, e.collection ); + assert.ok( colE.length === 0 ); assert.equal( counter, 2 ); } ); @@ -562,7 +570,7 @@ assert.equal( col.length, 0 ); assert.equal( resetCount, 4 ); - var f = new Backbone.Model( { id : 20, label : 'f' } ); + var f = new M( { id : 20, label : 'f' } ); col.reset( [ undefined, f ] ); assert.equal( col.length, 2 ); assert.equal( resetCount, 5 ); @@ -588,6 +596,11 @@ QUnit.test( "reset passes caller options", function( assert ){ assert.expect( 3 ); var Model = Backbone.Model.extend( { + attributes : { + astring : '', + anumber : 0 + }, + initialize : function( attrs, options ){ this.model_parameter = options.model_parameter; } @@ -639,29 +652,6 @@ assert.equal( col.length, 0 ); } ); - QUnit.test( "#861, adding models to a collection which do not pass validation, with validate:true", - function( assert ){ - assert.expect( 2 ); - var Model = Backbone.Model.extend( { - validate : function( attrs ){ - if( attrs.id == 3 ) return "id can't be 3"; - } - } ); - - var Collection = Backbone.Collection.extend( { - model : Model - } ); - - var collection = new Collection; - collection.on( "invalid", function(){ assert.ok( true ); } ); - - collection.add( [ { id : 1 }, { id : 2 }, { id : 3 }, { id : 4 }, { id : 5 }, { id : 6 } ], - { validate : true } ); - assert.deepEqual( collection.pluck( "id" ), [ 1, 2, 3, 4, 5, 6 ] ); - - collection._invalidate( { validate : true } ); - } ); - QUnit.test( "Invalid models are discarded with validate:true.", function( assert ){ assert.expect( 5 ); @@ -1000,6 +990,10 @@ QUnit.test( "`set` data is only parsed once", function( assert ){ var collection = new Backbone.Collection(); collection.model = Backbone.Model.extend( { + attributes : { + parsed : Boolean + }, + parse : function( data ){ assert.equal( data.parsed, void 0 ); data.parsed = true; @@ -1050,13 +1044,13 @@ model : Backbone.Model.extend( { idAttribute : '_id', defaults : { - a : 1 + a : 0 } } ) } ); var collection = new Collection( { _id : 1 } ); - collection.set( [ { _id : 1, a : 1 } ], { add : false } ); - assert.equal( collection.first().get( 'a' ), 1 ); + collection.set( [ { _id : 1, a : 1 } ], { merge : false } ); + assert.equal( collection.first().get( 'a' ), 0 ); } ); QUnit.test( "#1894 - `sort` can optionally be turned off", function( assert ){ @@ -1256,7 +1250,7 @@ calls.add++; assert.equal( model, collection._byId[ model.id ] ); assert.equal( model, collection._byId[ model.cid ] ); - assert.equal( model._events.dummy.length, 1 ); + assert.equal( model._events.dummy.next, null ); }); collection.on( 'remove', function( model ){ @@ -1264,7 +1258,7 @@ assert.equal( collection._byId[ model.id ], void 0 ); assert.equal( collection._byId[ model.cid ], void 0 ); assert.equal( model.collection, void 0 ); - assert.deepEqual( model._events, { dummy : void 0, destroy : void 0 }); + assert.deepEqual( model._events, void 0 ); }); var model = collection.add( { id : 1 } ); @@ -1353,7 +1347,8 @@ QUnit.test( "#3039: index is not sent when at is not specified", function( assert ){ assert.expect( 2 ); - var col = new Backbone.Collection( [ { at : 0 } ] ); + var M = Backbone.attributes({ at : 0 }); + var col = new M.Collection( [ { at : 0 } ] ); col.on( 'add', function( model, col, options ){ assert.equal( undefined, options.index ); } ); @@ -1750,7 +1745,7 @@ QUnit.test( "#1939 - `parse` is passed `options`", function( assert ){ }, initialize : function(){ assert.equal( this.prop, 'value' ); - assert.equal( this.collection, collection ); + assert.equal( this.collection, void 0 ); return this; } } ); @@ -1868,7 +1863,7 @@ QUnit.test( "#1939 - `parse` is passed `options`", function( assert ){ } ); QUnit.test( "Underscore methods with object-style and property-style iteratee", function( assert ){ - assert.expect( 26 ); + assert.expect( 24 ); var M = Backbone.Model.defaults( { a : 1, b : undefined, e: undefined, c: undefined } ); @@ -1881,8 +1876,6 @@ QUnit.test( "#1939 - `parse` is passed `options`", function( assert ){ ] ); assert.equal( coll.find( { a : 0 } ), undefined ); assert.deepEqual( coll.find( { a : 4 } ), model ); - assert.equal( coll.find( 'd' ), undefined ); - assert.deepEqual( coll.find( 'e' ), model ); assert.equal( coll.filter( { a : 0 } ), false ); assert.deepEqual( coll.filter( { a : 4 } ), [ model ] ); assert.equal( coll.some( { a : 0 } ), false ); @@ -1895,8 +1888,8 @@ QUnit.test( "#1939 - `parse` is passed `options`", function( assert ){ assert.deepEqual( coll.partition( { a : 0 } )[ 1 ], coll.models ); assert.deepEqual( coll.partition( { a : 4 } )[ 0 ], [ model ] ); assert.deepEqual( coll.partition( { a : 4 } )[ 1 ], _.without( coll.models, model ) ); - assert.deepEqual( coll.map( { a : 2 } ), [ false, true, false, false ] ); - assert.deepEqual( coll.map( 'a' ), [ 1, 2, 3, 4 ] ); + assert.deepEqual( coll.map( function( x ){ return x.a === 2; }), [ false, true, false, false ] ); + assert.deepEqual( coll.map( function( x ){ return x.a; } ), [ 1, 2, 3, 4 ] ); assert.deepEqual( coll.sortBy( 'a' )[ 3 ], model ); assert.deepEqual( coll.sortBy( 'e' )[ 0 ], model ); assert.deepEqual( coll.countBy( { a : 4 } ), { 'false' : 3, 'true' : 1 } ); diff --git a/tests/backbone/events.js b/tests/backbone/events.js index 06b354f..074c3f6 100644 --- a/tests/backbone/events.js +++ b/tests/backbone/events.js @@ -73,7 +73,7 @@ _.extend(obj, Backbone.Events); var increment = function() { - this.counter += 1; + obj.counter += 1; }; obj.on({ @@ -224,50 +224,50 @@ }); QUnit.test("stopListening cleans up references", function(assert) { - assert.expect(12); + assert.expect(10); var a = _.extend({}, Backbone.Events); var b = _.extend({}, Backbone.Events); var fn = function() {}; b.on('event', fn); a.listenTo(b, 'event', fn).stopListening(); assert.equal(_.size(a._listeningTo), 0); - assert.equal(_.size(b._events.event), 1); + assert.equal( b._events.event.context, void 0 ); assert.equal(_.size(b._listeners), 0); a.listenTo(b, 'event', fn).stopListening(b); assert.equal(_.size(a._listeningTo), 0); - assert.equal(_.size(b._events.event), 1); + assert.equal( b._events.event.context, void 0 ); assert.equal(_.size(b._listeners), 0); a.listenTo(b, 'event', fn).stopListening(b, 'event'); - assert.equal(_.size(a._listeningTo), 0); - assert.equal(_.size(b._events.event), 1); + //assert.equal(_.size(a._listeningTo), 0); + assert.equal( b._events.event.context, void 0 ); assert.equal(_.size(b._listeners), 0); a.listenTo(b, 'event', fn).stopListening(b, 'event', fn); - assert.equal(_.size(a._listeningTo), 0); - assert.equal(_.size(b._events.event), 1); + //assert.equal(_.size(a._listeningTo), 0); + assert.equal( b._events.event.context, void 0 ); assert.equal(_.size(b._listeners), 0); }); QUnit.test("stopListening cleans up references from listenToOnce", function(assert) { - assert.expect(12); + assert.expect(10); var a = _.extend({}, Backbone.Events); var b = _.extend({}, Backbone.Events); var fn = function() {}; b.on('event', fn); a.listenToOnce(b, 'event', fn).stopListening(); assert.equal(_.size(a._listeningTo), 0); - assert.equal(_.size(b._events.event), 1); + assert.equal( b._events.event.context, void 0 ); assert.equal(_.size(b._listeners), 0); a.listenToOnce(b, 'event', fn).stopListening(b); assert.equal(_.size(a._listeningTo), 0); - assert.equal(_.size(b._events.event), 1); + assert.equal( b._events.event.context, void 0 ); assert.equal(_.size(b._listeners), 0); a.listenToOnce(b, 'event', fn).stopListening(b, 'event'); - assert.equal(_.size(a._listeningTo), 0); - assert.equal(_.size(b._events.event), 1); + //assert.equal(_.size(a._listeningTo), 0); We do not count references. + assert.equal( b._events.event.context, void 0 ); assert.equal(_.size(b._listeners), 0); a.listenToOnce(b, 'event', fn).stopListening(b, 'event', fn); - assert.equal(_.size(a._listeningTo), 0); - assert.equal(_.size(b._events.event), 1); + //assert.equal(_.size(a._listeningTo), 0); + assert.equal( b._events.event.context, void 0 ); assert.equal(_.size(b._listeners), 0); }); @@ -277,23 +277,24 @@ var b = _.extend({}, Backbone.Events); var fn = function() {}; a.listenTo(b, 'event', fn); - b.off(); + a.stopListening( b ); assert.equal(_.size(a._listeningTo), 0); assert.equal(_.size(b._listeners), 0); a.listenTo(b, 'event', fn); b.off('event'); - assert.equal(_.size(a._listeningTo), 0); + assert.equal(_.size(a._listeningTo), 1); assert.equal(_.size(b._listeners), 0); a.listenTo(b, 'event', fn); b.off(null, fn); - assert.equal(_.size(a._listeningTo), 0); + assert.equal(_.size(a._listeningTo), 1); assert.equal(_.size(b._listeners), 0); a.listenTo(b, 'event', fn); - b.off(null, null, a); + a.stopListening( b ); assert.equal(_.size(a._listeningTo), 0); assert.equal(_.size(b._listeners), 0); }); +/* Do not support this. QUnit.test("listenTo and stopListening cleaning up references", function(assert) { assert.expect(2); var a = _.extend({}, Backbone.Events); @@ -315,6 +316,8 @@ assert.equal(_.size(a._listeningTo), 0); }); + */ + QUnit.test("listenToOnce with event maps cleans up references", function(assert) { assert.expect(2); var a = _.extend({}, Backbone.Events); @@ -622,7 +625,7 @@ QUnit.test("Off during iteration with once.", function(assert) { assert.expect(2); var obj = _.extend({}, Backbone.Events); - var f = function(){ this.off('event', f); }; + var f = function(){ obj.off('event', f); }; obj.on('event', f); obj.once('event', function(){}); obj.on('event', function(){ assert.ok(true); }); diff --git a/tests/backbone/index.html b/tests/backbone/index.html index 545fab0..f1013ae 100644 --- a/tests/backbone/index.html +++ b/tests/backbone/index.html @@ -10,9 +10,9 @@ - + diff --git a/tests/backbone/model.js b/tests/backbone/model.js index 896481a..a1e288f 100644 --- a/tests/backbone/model.js +++ b/tests/backbone/model.js @@ -33,16 +33,20 @@ }); QUnit.test("initialize", function(assert) { - assert.expect(3); + assert.expect(2); var Model = Backbone.Model.extend({ + attrbutes : { + one : 5 + }, + initialize: function() { this.one = 1; - assert.equal(this.collection, collection); + //assert.equal(this.collection, collection); No access to collection in constructor. } }); - var model = new Model({}, {}, collection ); + var model = new Model({}, {}); assert.equal(model.one, 1); - assert.equal(model.collection, collection); + assert.equal(model.collection, void 0); }); QUnit.test("initialize with attributes and options", function(assert) { @@ -119,16 +123,17 @@ }); QUnit.test("isNew", function(assert) { + var M = Backbone.attributes({ 'foo': 0, 'bar': 0, 'baz': 0}); assert.expect(6); - var a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3}); + var a = new M({ 'foo': 1, 'bar': 2, 'baz': 3}); assert.ok(a.isNew(), "it should be new"); - a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3, 'id': -5 }); + a = new M({ 'foo': 1, 'bar': 2, 'baz': 3, 'id': -5 }); assert.ok(!a.isNew(), "any defined ID is legal, negative or positive"); - a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3, 'id': 0 }); + a = new M({ 'foo': 1, 'bar': 2, 'baz': 3, 'id': 0 }); assert.ok(!a.isNew(), "any defined ID is legal, including zero"); - assert.ok( new Backbone.Model({ }).isNew(), "is true when there is no id"); - assert.ok(!new Backbone.Model({ 'id': 2 }).isNew(), "is false for a positive integer"); - assert.ok(!new Backbone.Model({ 'id': -5 }).isNew(), "is false for a negative integer"); + assert.ok( new M({ }).isNew(), "is true when there is no id"); + assert.ok(!new M({ 'id': 2 }).isNew(), "is false for a positive integer"); + assert.ok(!new M({ 'id': -5 }).isNew(), "is false for a negative integer"); }); QUnit.test("get", function(assert) { @@ -292,7 +297,7 @@ QUnit.test("using a non-default id attribute.", function(assert) { assert.expect(4); - var MongoModel = Backbone.Model.extend({idAttribute : '_id', defaults : { _id : '' }}); + var MongoModel = Backbone.Model.extend({idAttribute : '_id', defaults : { _id : '', title : '' }}); var model = new MongoModel({id: 'eye-dee', _id: 25, title: 'Model'}); //assert.equal(model.get('id'), 'eye-dee'); assert.equal(model.id, 25); @@ -324,7 +329,6 @@ assert.equal(collection.get('c6').cid.charAt(0), 'm'); collection.set([{id: 'c6', value: 'test'}], { merge: true, - add: true, remove: false }); assert.ok(collection.get('c6').has('value')); @@ -368,7 +372,7 @@ }); QUnit.test("defaults", function(assert) { - assert.expect(4); + assert.expect(2); var Defaulted = Backbone.Model.extend({ defaults: { "one": 1, @@ -378,6 +382,8 @@ var model = new Defaulted({two: undefined}); assert.equal(model.get('one'), 1); assert.equal(model.get('two'), 2); + /* defaults as function is deprecated. + Defaulted = Backbone.Model.extend({ defaults: function() { return { @@ -388,7 +394,7 @@ }); model = new Defaulted({two: undefined}); assert.equal(model.get('one'), 3); - assert.equal(model.get('two'), 4); + assert.equal(model.get('two'), 4);*/ }); QUnit.test("change, hasChanged, changedAttributes, previous, previousAttributes", function(assert) { @@ -490,9 +496,6 @@ model.validate = function(attrs) { if (this.admin) return "Can't change admin status."; }; - model.on('invalid', function(model, error) { - boundError = true; - }); var result = model.set({a: 100}, {validate:true}); assert.equal(result, model); assert.equal(model.get('a'), 100); @@ -502,8 +505,8 @@ assert.equal( model.isValid(), false); assert.equal(model.get('a'), 200); assert.equal(model.validationError.error, "Can't change admin status."); - model._invalidate( { validate : true } ); - assert.equal(boundError, true); + + assert.equal(model.isValid(), false); }); QUnit.test("defaults always extend attrs (#459)", function(assert) { @@ -563,7 +566,7 @@ assert.expect(2); var changed = 0, model = new ( Backbone.Model.defaults({a: null}) ); model.on('change', function() { - assert.ok(this.hasChanged('a')); + assert.ok(model.hasChanged('a')); }) .on('change:a', function() { changed++; @@ -699,17 +702,17 @@ model.on('change', function() { switch(count++) { case 0: - assert.deepEqual(this.changedAttributes(), {x: true}); + assert.deepEqual(model.changedAttributes(), {x: true}); assert.equal(model.previous('x'), undefined); model.set({y: true}); break; case 1: - assert.deepEqual(this.changedAttributes(), {x: true, y: true}); + assert.deepEqual(model.changedAttributes(), {x: true, y: true}); assert.equal(model.previous('x'), undefined); model.set({z: true}); break; case 2: - assert.deepEqual(this.changedAttributes(), {x: true, y: true, z: true}); + assert.deepEqual(model.changedAttributes(), {x: true, y: true, z: true}); assert.equal(model.previous('y'), undefined); break; default: @@ -727,15 +730,15 @@ model.on('change', function() { switch(count++) { case 0: - assert.deepEqual(this.changedAttributes(), {x: true}); + assert.deepEqual(model.changedAttributes(), {x: true}); model.set({y: true}, {silent: true}); model.set({z: true}); break; case 1: - assert.deepEqual(this.changedAttributes(), {x: true, y: true, z: true}); + assert.deepEqual(model.changedAttributes(), {x: true, y: true, z: true}); break; case 2: - assert.deepEqual(this.changedAttributes(), {z: false}); + assert.deepEqual(model.changedAttributes(), {z: false}); break; default: assert.ok(false); @@ -936,7 +939,7 @@ QUnit.test('#3778 - id will only be updated if it is set', function(assert) { assert.expect(2); - var model = new Backbone.Model({id: 1}); + var model = new ( Backbone.Model.defaults({id: 1, foo : void 0}) ); model.id = 2; model.set({foo: 'bar'}); assert.equal(model.id, 2); diff --git a/tests/backbone/sync.js b/tests/backbone/sync.js index 87b21f9..252e96d 100644 --- a/tests/backbone/sync.js +++ b/tests/backbone/sync.js @@ -74,50 +74,6 @@ assert.equal(data.length, 123); }); - QUnit.test("update with emulateHTTP and emulateJSON", function(assert) { - assert.expect(7); - library.first().save({id: '2-the-tempest', author: 'Tim Shakespeare'}, { - emulateHTTP: true, - emulateJSON: true - }); - assert.equal(this.ajaxSettings.url, '/library/2-the-tempest'); - assert.equal(this.ajaxSettings.type, 'POST'); - assert.equal(this.ajaxSettings.dataType, 'json'); - assert.equal(this.ajaxSettings.data._method, 'PUT'); - var data = JSON.parse(this.ajaxSettings.data.model); - assert.equal(data.id, '2-the-tempest'); - assert.equal(data.author, 'Tim Shakespeare'); - assert.equal(data.length, 123); - }); - - QUnit.test("update with just emulateHTTP", function(assert) { - assert.expect(6); - library.first().save({id: '2-the-tempest', author: 'Tim Shakespeare'}, { - emulateHTTP: true - }); - assert.equal(this.ajaxSettings.url, '/library/2-the-tempest'); - assert.equal(this.ajaxSettings.type, 'POST'); - assert.equal(this.ajaxSettings.contentType, 'application/json'); - var data = JSON.parse(this.ajaxSettings.data); - assert.equal(data.id, '2-the-tempest'); - assert.equal(data.author, 'Tim Shakespeare'); - assert.equal(data.length, 123); - }); - - QUnit.test("update with just emulateJSON", function(assert) { - assert.expect(6); - library.first().save({id: '2-the-tempest', author: 'Tim Shakespeare'}, { - emulateJSON: true - }); - assert.equal(this.ajaxSettings.url, '/library/2-the-tempest'); - assert.equal(this.ajaxSettings.type, 'PUT'); - assert.equal(this.ajaxSettings.contentType, 'application/x-www-form-urlencoded'); - var data = JSON.parse(this.ajaxSettings.data.model); - assert.equal(data.id, '2-the-tempest'); - assert.equal(data.author, 'Tim Shakespeare'); - assert.equal(data.length, 123); - }); - QUnit.test("read model", function(assert) { assert.expect(3); library.first().save({id: '2-the-tempest', author: 'Tim Shakespeare'}); @@ -136,17 +92,6 @@ assert.equal(this.ajaxSettings.data, null); }); - QUnit.test("destroy with emulateHTTP", function(assert) { - assert.expect(3); - library.first().save({id: '2-the-tempest', author: 'Tim Shakespeare'}); - library.first().destroy({ - emulateHTTP: true, - emulateJSON: true - }); - assert.equal(this.ajaxSettings.url, '/library/2-the-tempest'); - assert.equal(this.ajaxSettings.type, 'POST'); - assert.equal(JSON.stringify(this.ajaxSettings.data), '{"_method":"DELETE"}'); - }); QUnit.test("urlError", function(assert) { assert.expect(2); @@ -185,54 +130,6 @@ this.ajaxSettings.error(); }); - QUnit.test('Use Backbone.emulateHTTP as default.', function(assert) { - assert.expect(2); - var model = new Backbone.Model; - model.url = '/test'; - - Backbone.emulateHTTP = true; - model.sync('create', model); - assert.strictEqual(this.ajaxSettings.emulateHTTP, true); - - Backbone.emulateHTTP = false; - model.sync('create', model); - assert.strictEqual(this.ajaxSettings.emulateHTTP, false); - }); - - QUnit.test('Use Backbone.emulateJSON as default.', function(assert) { - assert.expect(2); - var model = new Backbone.Model; - model.url = '/test'; - - Backbone.emulateJSON = true; - model.sync('create', model); - assert.strictEqual(this.ajaxSettings.emulateJSON, true); - - Backbone.emulateJSON = false; - model.sync('create', model); - assert.strictEqual(this.ajaxSettings.emulateJSON, false); - }); - - QUnit.test("#1756 - Call user provided beforeSend function.", function(assert) { - assert.expect(4); - Backbone.emulateHTTP = true; - var model = new Backbone.Model; - model.url = '/test'; - var xhr = { - setRequestHeader: function(header, value) { - assert.strictEqual(header, 'X-HTTP-Method-Override'); - assert.strictEqual(value, 'DELETE'); - } - }; - model.sync('delete', model, { - beforeSend: function(_xhr) { - assert.ok(_xhr === xhr); - return false; - } - }); - assert.strictEqual(this.ajaxSettings.beforeSend(xhr), false); - }); - QUnit.test('#2928 - Pass along `textStatus` and `errorThrown`.', function(assert) { assert.expect(2); var model = new Backbone.Model; diff --git a/tests/nestedtypes/README.md b/tests/nestedtypes/README.md deleted file mode 100644 index 5b00830..0000000 --- a/tests/nestedtypes/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# NestedTypes 1.3 Regression Tests - -Tests suite taken as is from NestedTypes 1.3.X. Used for basic regression testing. - -As usual, an ultimate regression is an ability to run Volicon Observer product (SPA of ~100 KLOCs) with the recent version of the framework. - -## To run - -- Do `npm install` -- Open `index.html` for functional tests -- Open `performance.html` for performance test vs `backbonejs` \ No newline at end of file diff --git a/tests/nestedtypes/functionality/README.md b/tests/nestedtypes/functionality/README.md deleted file mode 100644 index 2252d4b..0000000 --- a/tests/nestedtypes/functionality/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Deprecated features list - -- .trigger( "a b c ") is deprecated. -- 'replace:attr' event is deprecated. -- Array attribute casts wrong types to an empty array, and prints the warning. \ No newline at end of file diff --git a/tests/nestedtypes/functionality/advanced.js b/tests/nestedtypes/functionality/advanced.js deleted file mode 100644 index ce8b3c9..0000000 --- a/tests/nestedtypes/functionality/advanced.js +++ /dev/null @@ -1,50 +0,0 @@ -var Nested = require( '../nestedtypes' ), - expect = require( 'chai' ).expect, - sinon = require( 'sinon' ); - -var Model = Nested.Model, Collection = Nested.Collection; - -describe( 'Advanced functionality', function(){ - describe( 'Collection.Subset', function(){ - var M = Model.extend({ - attributes : { - name : String - } - }); - - var A = Model.extend({ - attributes : { - subset : M.Collection.Subset, - aggregated : M.Collection - } - }); - - it( 'inherits from collection type', function(){ - expect( Collection.Subset.prototype ).to.be.instanceOf( Collection ); - - var M = Model.extend({}); - - expect( M.Collection ).to.not.equal( Collection ); - expect( M.Collection.prototype ).to.be.instanceOf( Collection ); - expect( M.Collection.Subset.prototype ).to.be.instanceOf( M.Collection ); - } ); - - it( "doesn't take ownership on its elements", function(){ - var a = new A(); - - a.subset.set([ { name : '1'}, { name : '2'} ]); - a.aggregated.set( a.subset.models ); - expect( a.aggregated.first()._owner ).to.equal( a ); - } ); - - it( "doesn't merge records on set", function(){ - var a = new A(); - - a.subset.set([ { id : 1, name : '1'}, { id : 2, name : '2'} ]); - var f = a.subset.get( 1 ); - a.subset.set([ { id : 1, name : '1'}, { id : 2, name : '2'} ]); - - expect( a.subset.get( 1 ) ).to.not.equal( f ); - }); - }); -}); diff --git a/tests/nestedtypes/functionality/backboneTypes.js b/tests/nestedtypes/functionality/backboneTypes.js deleted file mode 100644 index 3ffdd0f..0000000 --- a/tests/nestedtypes/functionality/backboneTypes.js +++ /dev/null @@ -1,280 +0,0 @@ - var Nested = require( '../nestedtypes' ), - expect = require( 'chai' ).expect, - _ = require( 'underscore' ), - sinon = require( 'sinon' ); - - describe( 'Nested Models and Collections', function(){ - function shouldFireChangeOnce( model, attr, todo ){ - var change = sinon.spy(), - attrs = attr.split( ' ' ); - - model.on( 'change', change ); - - var changeAttrs = _.map( attrs, function( name ){ - var changeName = sinon.spy(); - model.on( 'change:' + name, changeName ); - return changeName; - }); - - todo( model ); - - expect( change ).to.be.calledOnce; - model.off( change ); - - _.each( changeAttrs, function( spy ){ - expect( spy ).to.be.calledOnce; - model.off( spy ); - }); - } - - var A = Nested.Model.extend({ - attributes : { - a : 1, - b : 2 - } - }); - - var B = Nested.Model.extend({ - attributes :{ - first : A.has.parse( function( resp ){ - return { a : resp.a + 1, b : resp.b + 1 }; - }), - second : A.has.triggerWhenChanged( false ), - c : A.Collection - } - }); - - function createSpies(){ - var collection = sinon.spy(), - model = sinon.spy(); - - A.Collection.prototype.parse = function( data ){ - collection(); - return data; - }; - - A.prototype.parse = function( data ){ - model(); - return data; - }; - - return { model : model, collection : collection }; - } - - describe( 'Nested parse method', function(){ - describe( 'Nested model', function(){ - it( 'set _owner property', function(){ - var m = new B(); - - expect( m.first._owner ).to.eql( m ); - expect( m.c._owner ).to.eql( m ); - - var a = new A(); - var _first = m.first; - m.first = a; - expect( _first._owner ).to.not.ok; - expect( m.first._owner ).to.eql( m ); - }); - - it( 'invoke "parse" on construction', function(){ - var spies = createSpies(); - - var m = new B({ - first : {id : 1, a : 2, b : 2} - }, { parse : true }); - - expect( spies.model ).to.be.calledOnce; - expect( m.first.a ).to.eql( 3 ); - expect( m.first.b ).to.eql( 3 ); - }); - - it( 'invoke "parse" on set', function(){ - var spies = createSpies(); - - var m = new B(); - m.set( 'first', {id : 1, a : 2, b : 2}, { parse : true }); - - expect( spies.model ).to.be.calledOnce; - }); - - it( 'invoke "parse" on set when value is nul' , function(){ - var spies = createSpies(); - - var m = new B({ first : null }); - m.set( 'first', {id : 1, a : 1, b : 2}, { parse : true } ); - expect( spies.model ).to.be.calledOnce; - }); - }); - - describe( 'Nested collection', function(){ - - it( 'invoke "parse" on construction', function(){ - var spies = createSpies(); - - var m = new B({ - c : [{id : 1, a : 2, b : 2}] - }, { parse : true }); - - expect( spies.collection ).to.be.calledOnce; - expect( spies.model ).to.be.calledOnce; - }); - - it( 'invoke "parse" on set', function(){ - var spies = createSpies(); - - var m = new B(); - m.set( 'c', [{id : 1, a : 1, b : 2}], { parse : true } ); - - expect( spies.collection ).to.be.calledOnce; - expect( spies.model ).to.be.calledOnce; - }); - - it( 'invoke "parse" on set when value is null', function(){ - var spies = createSpies(); - - var m = new B({ c : null }); - m.set( 'c', [{id : 1, a : 1, b : 2}], { parse : true } ); - - expect( spies.collection ).to.be.calledOnce; - expect( spies.model ).to.be.calledOnce; - }); - }) - }); - - describe( 'Nested.Model attribute type cast on assignment', function(){ - describe( 'when current attribute value is not null (deep update)', function(){ - - it( 'delegate update to nested model\'s .set', function(){ - var m = new B(), - id = m.first.cid; - - m.first = {id : 1, a : 1, b : 2}; - - expect( id ).to.eql( m.first.cid ); - expect( m.first.id ).to.eql( 1 ); - }); - - it( 'triggers single "change" and single "change:attr" events if nested model is changed', function(){ - var m = new B(); - shouldFireChangeOnce( m, 'first', function(){ - m.first = {id : 1, a : 1, b : 2}; - }); - } ); - }); - - describe( 'when current attribute value is empty (null)', function(){ - - it( 'creates new model', function(){ - var m = new B({ first : null }); - m.first = { id : 1, a : 1, b : 2 }; - expect( m.first.id ).to.eql( 1 ); - }); - - it( 'triggers "change", "change:attr" events', function(){ - var m = new B({ first : null } ); - - shouldFireChangeOnce( m, 'first', function(){ - m.first = {id : 1, a : 1, b : 2}; - }); - }); - }); - }); - - describe( 'Nested.Collection attribute type cast on assignment', function(){ - describe( 'when current attribute value is not null (deep update)', function(){ - it( 'delegate update to nested collection\'s .set', function(){ - var m = new B(), - id = m.c._listenId; - - m.c = [{id : 1, a : 1, b : 2}]; - - expect( id ).to.eql( m.c._listenId ); - expect( m.c.first().id ).to.eql( 1 ); - }); - - - it( 'triggers single "change" and single "change:attr" events when nested collection is changed', function(){ - var m = new B(); - shouldFireChangeOnce( m, 'c', function(){ - m.c = [{id : 1, a : 1, b : 2}]; - }); - }); - }); - - describe( 'when current attribute value is empty (null)', function(){ - it( 'creates new collection', function(){ - var m = new B({ c : null }); - m.c = [{id : 1, a : 1, b : 2}]; - expect( m.c.first().id ).to.eql( 1 ); - }); - - it( 'triggers "change", "change:attr", events', function(){ - var m = new B({ c : null } ); - - shouldFireChangeOnce( m, 'c', function(){ - m.c = [{id : 1, a : 1, b : 2}]; - }); - }); - }); - }); - - describe( 'nested model and collection event bubbling', function(){ - it( 'bubble "change" event from nested model', function(){ - var m = new B(); - - shouldFireChangeOnce( m, 'first', function(){ - m.first.a = 2; - }); - }); - - it( 'send single "change" event in a transaction', function(){ - var m = new B(); - - shouldFireChangeOnce( m, 'first', function(){ - m.first.transaction( function( first ){ - first.a = 7; - first.b = 7; - }); - }); - }); - - it( 'send single "change" event in a nested transaction', function(){ - var m = new B(); - - shouldFireChangeOnce( m, 'first second', function(){ - m.transaction( function(){ - m.first.a = 7; - m.second.a = 7; - }); - }); - }); - - it( 'generate "change" event on any nested collection modification', function(){ - var m = new B(); - - shouldFireChangeOnce( m, 'c', function(){ - m.c.add({ id: 1, a: 1, b : 2 }); - }); - - shouldFireChangeOnce( m, 'c', function(){ - m.c.first().a = 2; - }); - - shouldFireChangeOnce( m, 'c', function(){ - m.c.remove( m.c.first() ); - }); - }); - - it( 'may be disabled for selected nested attributes', function(){ - var m = new B(), - spyTop = sinon.spy(), - spyBottom = sinon.spy(); - - m.on( 'change', spyTop ); - m.second.on( 'change', spyBottom ); - m.second.a = 5; - expect( spyBottom ).to.be.calledOnce; - expect( spyBottom ).to.be.notCalled; - }); - }) - }); diff --git a/tests/nestedtypes/functionality/basic.js b/tests/nestedtypes/functionality/basic.js deleted file mode 100644 index 4ab995e..0000000 --- a/tests/nestedtypes/functionality/basic.js +++ /dev/null @@ -1,239 +0,0 @@ - var Nested = require( '../nestedtypes' ), - expect = require( 'chai' ).expect, - sinon = require( 'sinon' ); - - describe( 'Basic functionality', function(){ - function canHaveNativeProperties( Type ){ - var C = Type.extend({ - something : false, - - properties : { - readOnly : function(){ return this.something; }, - rw : { - get : function(){ return this.something; }, - set : function( value ){ - return this.something = value; - } - } - } - }); - - var c = new C(); - expect( c.readOnly ).to.be.false; - c.rw = true; - expect( c.rw ).to.be.true; - expect( c.readOnly ).to.be.true; - } - - describe( 'Nested.Model', function(){ - var M = Nested.Model.extend({ - urlRoot : '/root', - - defaults : { - a : 'a' - } - }); - - it( 'may use "Model.attributes" instead of "Model.defaults"', function(){ - var M = Nested.Model.extend({ - attributes : { - a : 'a' - } - }); - - var m = new M(); - expect( m.get( 'a' ) ).to.eql( 'a' ); - }); - - it( 'create native properties for every default attribute', function(){ - var m = new M(); - expect( m.a ).to.eql( 'a' ); - m.a = 'b'; - expect( m.get( 'a' ) ).to.eql( 'b' ); - expect( m.a ).to.eql( 'b' ); - }); - - it( 'can have explicitly defined native properties', function(){ - canHaveNativeProperties( Nested.Model ); - }); - - it( 'may turn off native properties for model\'s attributes', function(){ - var M = Nested.Model.extend({ - attributes : { - a : 'a' - }, - - properties : false - }); - - var m = new M(); - - expect( m.a ).to.be.an( 'undefined' ); - - }); - - it( 'inherit default attributes from the base model', function(){ - var B = M.extend({ - defaults : { - b : 'b' - } - }); - - m = new B(); - expect( m.a ).to.eql( 'a' ); - expect( m.b ).to.eql( 'b' ); - }); - - it( 'deep copy defaults JSON literals on model creation', function(){ - var A = Nested.Model.extend({ - defaults : { - a : { first : [ 1 ], second : [ 2 ] } - } - }); - - var m = new A(), - n = new A(); - - m.a.first.push( 2 ); - expect( m.a.first ).to.eql( [ 1, 2 ] ); - expect( n.a.first ).to.eql( [ 1 ] ); - }); - - it( 'can define a tree', function(){ - var M = Nested.Model.extend(); - - M.define({ - defaults : { - nested : M.value( null ), - elements : M.Collection - } - }) - - var m = new M(); - - m.elements.add({}); - - expect( m.elements.first().elements.length ).to.be.zero; - - }); - - it( 'can handle function in Model.defaults', function(){ - var M = Nested.Model.extend({ - defaults : function(){ - return { - num : 1, - date : new Date() - }; - } - }); - - var m = new M(); - - expect( m.num ).to.equal( 1 ); - expect( m.date ).to.be.instanceOf( Date ); - - m.num = "2"; - expect( m.num ).to.equal( 2 ); - }); - }); - - describe( 'Nested.Collection', function(){ - var M = Nested.Model.extend({ - urlRoot : '/root', - - defaults : { - a : 'a' - }, - - collection : { - initialize : function(){ - this.b = 'b'; - } - } - }); - - it( 'can have explicitly defined native properties', function(){ - canHaveNativeProperties( Nested.Collection ); - }); - - it( 'is automatically defined for every model', function(){ - var c = new M.Collection(); - expect( c.model ).to.eql( M ); - }); - - it( 'can be defined in Model.collection', function(){ - var c = new M.Collection(); - expect( c.b ).to.eql( 'b' ); - }); - - it( 'inherits from the base Model.collection', function(){ - var B = M.extend({ - urlRoot : '/myroot', - collection : { - c : 'c' - } - }); - - var c = new B.Collection(); - expect( c.c ).to.eql( 'c' ); - expect( c.b ).to.eql( 'b' ); - //expect( c.url ).to.eql( '/myroot' ); - }); - - }); - - describe( 'Class type', function(){ - var C = Nested.Class.extend({ - a : 'a', - constructor : function(){ - this.b = 'b'; - } - }); - - it( 'has custom constructor method', function(){ - var c = new C(); - expect( c.a ).to.eql( 'a' ); - expect( c.b ).to.eql( 'b' ); - }); - - it( 'can be extended', function(){ - var D = C.extend({ - d : 'd' - }); - - var d = new D(); - - expect( d.a ).to.eql( 'a' ); - expect( d.b ).to.eql( 'b' ); - expect( d.d ).to.eql( 'd' ); - }); - - it( 'Messenger can trigger/listen to backbone events', function(){ - var C = Nested.Messenger.extend({ - constructor : function(){ - Nested.Messenger.apply( this, arguments ); - - this.listenTo( this, { - 'hello' : function(){ - this.hello = true; - }, - - 'a b c' : function(){ - this.abc = true; - } - }); - } - }); - - var c = new C(); - c.trigger( 'hello' ); - expect( c.hello ).to.be.true; - c.trigger( 'b' ); - expect( c.abc ).to.be.true; - }); - - it( 'can have explicitly defined native properties', function(){ - canHaveNativeProperties( Nested.Class ); - }); - }); - }); diff --git a/tests/nestedtypes/functionality/collections.js b/tests/nestedtypes/functionality/collections.js deleted file mode 100644 index f167ea4..0000000 --- a/tests/nestedtypes/functionality/collections.js +++ /dev/null @@ -1,86 +0,0 @@ -var Nested = require( '../nestedtypes' ), - expect = require( 'chai' ).expect, - sinon = require( 'sinon' ); - -var Model = Nested.Model.extend({ - defaults : { - data : '' - }, - - parse : function( d ){ - return { data : d }; - } -}); - -describe( 'Collections', function(){ - describe( 'Collection#constructor', function(){ - it( 'invoked wo/arguments', function(){ - var c = new Model.Collection(); - expect( c.length ).to.eql( 0 ); - }); - - it( 'takes single model', function(){ - var m = new Model(); - c = new Model.Collection( m ); - - expect( c.length ).to.eql( 1 ); - expect( c.first() ).to.eql( m ); - }); - - it( 'takes attributes', function(){ - var c = new Model.Collection({ data : 'hi' }); - - expect( c.length ).to.eql( 1 ); - expect( c.first().data ).to.eql( 'hi' ); - }); - - it( 'takes an empty array', function(){ - var c = new Model.Collection( [] ); - expect( c.length ).to.eql( 0 ); - }); - - it( 'takes an array of models', function(){ - var m = new Model(); - c = new Model.Collection([ m, new Model() ]); - - expect( c.length ).to.eql( 2 ); - expect( c.first() ).to.eql( m ); - }); - - it( 'takes an array of attributes', function(){ - var c = new Model.Collection([{ data : '1' }, { data : '2' }]); - - expect( c.length ).to.eql( 2 ); - expect( c.first().data ).to.eql( '1' ); - expect( c.last().data ).to.eql( '2' ); - }); - - it( 'parses raw data', function(){ - var c = new Model.Collection([ '1' , '2' ], { parse : true }); - - expect( c.length ).to.eql( 2 ); - expect( c.first().data ).to.eql( '1' ); - expect( c.last().data ).to.eql( '2' ); - } ); - } ); - - describe( 'Collection#set & Collection#reset', function(){ - it( 'sets empty collection' ); - it( 'updates collection with same data with no changes' ); - it( 'reset existing collection' ); - it( 'handles data intersection' ); - it( 'handle sorted collection' ); - } ); - - describe( 'Collection#add & Collection#remove', function(){ - it( 'sets empty collection' ); - it( 'remove single element from collection' ); - it( 'add many items to collection' ); - it( 'remove many items from collection' ); - it( 'add one item to collection' ); - it( 'add one item to sorted collection' ); - it( 'add many items to sorted collection' ); - it( 'insert one item in given position' ); - it( 'insert many items in given position' ) - } ); -} ); \ No newline at end of file diff --git a/tests/nestedtypes/functionality/relations.js b/tests/nestedtypes/functionality/relations.js deleted file mode 100644 index bbd8841..0000000 --- a/tests/nestedtypes/functionality/relations.js +++ /dev/null @@ -1,211 +0,0 @@ - var Nested = require( '../nestedtypes' ), - sinon = require( 'sinon' ), - chai = require( 'chai'), - as_promised = require("chai-as-promised"); - - chai.use( as_promised ); - - expect = chai.expect; - - describe( 'One-to-many and many-to-many relations', function(){ - var Something = Nested.Model.extend({ - attributes : { - name : '' - } - }); - - var collection = new Something.Collection([ - { id: 1, name : 1 }, - { id: 2, name : 2 }, - { id: 3, name : 3 } - ]); - - describe( 'Model.from reference', function(){ - var A = Nested.Model.extend({ - attributes : { - ref : Something.from( collection ) - } - }); - - it( 'is initialized with null', function(){ - var m = new A(); - expect( m.ref ).to.be.null; - }); - - it( 'parse model id', function(){ - var m = new A({ ref : 1 }); - expect( m.ref.name ).to.equal( "1" ); - }); - - it( 'can be assigned with model id', function(){ - var m = new A(); - m.ref = 1; - expect( m.ref.name ).to.equal( "1" ); - - m.set({ ref: 2 }); - expect( m.ref.name ).to.equal( "2" ); - }); - - it( 'can be assigned with model', function(){ - var m = new A(); - m.ref = collection.first(); - expect( m.ref.name ).to.equal( "1" ); - }); - - it( 'is serialized to model id', function(){ - var m = new A(); - m.ref = collection.first(); - var json = m.toJSON(); - expect( json.ref ).to.equal( 1 ); - }); - - it( 'can use lazy reference to collection', function(){ - var A = Nested.Model.extend({ - attributes : { - ref : Something.from( function(){ return collection; } ) - } - }); - - var m = new A(); - m.ref = 1; - expect( m.ref.name ).to.equal( "1" ); - }); - - it( 'must return null when not resolved', function(){ - var A = Nested.Model.extend({ - attributes : { - ref : Something.from( function(){ return this.__collection; } ) - } - }); - - var m = new A(); - m.ref = 1; - expect( m.ref ).to.be.null; - - m.__collection = collection; - expect( m.ref.name ).to.equal( "1" ); - }); - }); - - describe( 'Collection.subsetOf', function(){ - var A = Nested.Model.extend({ - attributes : { - refs : Something.Collection.subsetOf( collection ) - } - }); - - it( 'is initialized with empty collection', function(){ - var m = new A(); - expect( m.refs.length ).to.equal( 0 ); - }); - - it( 'parse array of model ids', function(){ - var m = new A({ refs : [ 1 ] }); - expect( m.refs.first().name ).to.equal( "1" ); - }); - - it( 'can be assigned with array of model ids', function(){ - var m = new A(); - m.refs = [ 1 ]; - expect( m.refs.first().name ).to.equal( "1" ); - }); - - it( 'can be assigned with models array', function(){ - var m = new A(); - m.refs = [ collection.first() ]; - expect( m.refs.first().name ).to.equal( "1" ); - }); - - it( 'is serialized to array of model ids', function(){ - var m = new A(); - m.refs = [ collection.first() ]; - var json = m.toJSON(); - expect( json.refs[ 0 ] ).to.equal( 1 ); - }); - - it( 'can use lazy reference to collection', function(){ - var A = Nested.Model.extend({ - attributes : { - refs : Something.Collection.subsetOf( function(){ return collection; } ) - } - }); - - var m = new A(); - m.refs = [ 1 ]; - expect( m.refs.first().name ).to.equal( "1" ); - }); - }); - }); - - describe( 'Nested relations', function(){ - var User = Nested.Model.extend({ - defaults : { - name : '', - roles : Nested.Collection.subsetOf( '~roles' ) - }, - - collection : { - fetch : function(){ - this.reset([ { - id : 1, - name : 'admin', - roles : [ 1 ] - },{ - id : 2, - name : 'user', - roles : [ 2 ] - }], { parse : true }); - - this.trigger( 'sync', this ); - - return new Promise(function( resolve, reject ) { - resolve('loaded'); - }); - } - } - }); - - var Role = Nested.Model.extend({ - defaults : { - name : '', - users : Nested.Collection.subsetOf( '~users' ) - }, - - collection : { - fetch : function(){ - this.reset([ { - id : 1, - name : 'Administrators', - users : [ 1 ] - },{ - id : 2, - name : 'Users', - users : [ 2 ] - }], { parse : true }); - - this.trigger( 'sync', this ); - return new Promise(function( resolve, reject ) { - resolve('loaded'); - }); - } - } - }); - - it( 'can be initialized with a list of attributes', function(){ - var Store = Nested.Store.defaults({ - users : User.Collection, - roles : Role.Collection - }); - - Nested.Store.global = new Store(); - }); - - it( 'References are properly resolved', function(){ - var store = Nested.Store.global; - store.users.fetch(); - store.roles.fetch(); - - expect( store.users.first().roles.first().name ).to.eql( 'Administrators' ); - }); - - }); diff --git a/tests/nestedtypes/functionality/types.js b/tests/nestedtypes/functionality/types.js deleted file mode 100644 index 347282b..0000000 --- a/tests/nestedtypes/functionality/types.js +++ /dev/null @@ -1,397 +0,0 @@ - var Nested = require( '../nestedtypes' ), - chai = require( 'chai' ), - expect = chai.expect, - sinon = require( 'sinon' ), - sinonChai = require( 'sinon-chai' ); - - chai.use( sinonChai ); - - describe( 'Type specs', function(){ - describe( 'Constructor type spec', function(){ - var Ctor = Nested.Class.extend({ - a : 1, - - constructor : function( a ){ - a === undefined || ( this.a = a ); - }, - - toJSON : function(){ - return this.a; - } - }); - - var A = Nested.Model.extend({ - defaults : { - a : Ctor - } - }); - - describe( 'Model creation', function(){ - it( 'automatically creates new object', function(){ - var m = new A(); - expect( m.a ).to.be.instanceOf( Ctor ); - expect( m.a.a ).to.eql( 1 ); - }); - - it( 'pass value to the constructor on creation ', function(){ - var m = new A({ a : 3 }); - expect( m.a ).to.be.instanceOf( Ctor ); - expect( m.a.a ).to.eql( 3 ); - }); - - it( 'may have default value', function(){ - var A = Nested.Model.extend({ - defaults : { - a : Ctor.value( 3 ) - } - }); - - var m = new A(); - expect( m.a ).to.be.instanceOf( Ctor ); - expect( m.a.a ).to.eql( 3 ); - }); - - it( 'may have default value of null', function(){ - var A = Nested.Model.extend({ - defaults : { - a : Ctor.value( null ) - } - }); - - var m = new A(); - expect( m.a ).to.be.null; - }); - }); - - describe( 'Attribute assignment', function(){ - it( 'replace value if assigned with defined type', function(){ - var m = new A(); - - m.a = new Ctor( 5 ); - - expect( m.a ).to.be.instanceOf( Ctor ); - expect( m.a.a ).to.eql( 5 ); - }); - - it( 'convert value to defined type on assignment', function(){ - var m = new A(); - - m.a = 5; - - expect( m.a ).to.be.instanceOf( Ctor ); - expect( m.a.a ).to.eql( 5 ); - }); - - it( 'may set attribute with null', function(){ - var m = new A(); - - m.a = null; - - expect( m.a ).to.be.null; - }); - }); - - describe( 'Serialization and parsing', function(){ - it( 'serialize attribute to JSON', function(){ - var m = new A(), - json = m.toJSON(); - - expect( json.a ).to.eql( 1 ); - }); - - it( 'set attribute on model set', function(){ - var m = new A(); - - m.set({ a : 5 }); - - expect( m.a ).to.be.instanceOf( Ctor ); - expect( m.a.a ).to.eql( 5 ); - }); - }); - }); - - describe( 'Array type', function(){ - var M = Nested.Model.extend({ - defaults : { - arr : Array - } - }); - - it( 'creates an empty array by default', function(){ - var m = new M(); - expect( m.arr ).to.be.instanceOf( Array ); - expect( m.arr.length ).to.be.equal( 0 ); - }); - - it( 'non-array value in array on assignment is ignored', function(){ - var m = new M(); - m.arr = 1; - - expect( m.arr ).to.be.instanceOf( Array ); - expect( m.arr.length ).to.be.equal( 0 ); - }); - }); - - describe( 'Primitive types (Number, Integer, Boolean, String)', function(){ - var A = Nested.Model.extend({ - defaults : { - num : Number, - str : String, - bool : Boolean, - int : Number.integer - } - }); - - it( 'initialized with primitive types', function(){ - var m = new A(); - - expect( m.num ).to.be.a( 'number' ).and.equal( 0 ); - expect( m.int ).to.be.a( 'number' ).and.equal( 0 ); - expect( m.str ).to.be.a( 'string' ).and.equal( "" ); - expect( m.bool ).to.be.a( 'boolean' ).and.equal( false ); - }); - - it( 'converted to defined types on assignments', function(){ - var m = new A(); - - m.num = "25.5"; - expect( m.num ).to.be.a( 'number' ).and.equal( 25.5 ); - - m.str = 32; - expect( m.str ).to.be.a( 'string' ).and.equal( "32" ); - - m.bool = "5"; - expect( m.bool ).to.be.a( 'boolean' ).and.equal( true ); - - m.int = 25.7; - expect( m.int ).to.be.a( 'number' ).and.equal( 26 ); - - m.int = "25.7"; - expect( m.int ).to.be.a( 'number' ).and.equal( 26 ); - }); - - it( 'can be set with null', function(){ - var m = new A(); - - m.num = null; - expect( m.num ).to.be.null; - - m.str = null; - expect( m.str ).to.be.null; - - m.bool = null; - expect( m.bool ).to.be.null; - - m.int = null; - expect( m.int ).to.be.null; - }); - - it( 'inferred from default values (except Integer)', function(){ - var A = Nested.Model.extend({ - defaults : { - num : 1, - str : 'str', - bool : true - } - }); - - var m = new A(); - expect( m.num ).to.be.a( 'number' ).and.equal( 1 ); - expect( m.str ).to.be.a( 'string' ).and.equal( "str" ); - expect( m.bool ).to.be.a( 'boolean' ).and.equal( true ); - }); - }); - - describe( 'Date type', function(){ - var user, User = Nested.Model.extend({ - attributes:{ - created : Date, - timestamp : Date.timestamp, - microsoft : Date.microsoft, - name: String, - loginCount: Integer - } - }); - - before( function(){ - user = new User(); - }); - - it( 'create new Date object on construction', function(){ - expect( user.created ).to.be.instanceOf( Date ); - expect( user.microsoft ).to.be.instanceOf( Date ); - expect( user.timestamp ).to.be.instanceOf( Date ); - }); - - it( 'parse ISO dates in all browsers on assignment', function(){ - // parse Date from string - user.created = "2012-12-12T10:00"; - expect( user.created ).to.be.instanceof( Date ); - expect( user.created.toISOString() ).to.be.eql( '2012-12-12T10:00:00.000Z' ); - - user.timestamp = "2012-12-12T10:00"; - expect( user.timestamp ).to.be.instanceof( Date ); - expect( user.timestamp.toISOString() ).to.be.eql( '2012-12-12T10:00:00.000Z' ); - - user.microsoft = "2012-12-12T10:00"; - expect( user.microsoft ).to.be.instanceof( Date ); - expect( user.microsoft.toISOString() ).to.be.eql( '2012-12-12T10:00:00.000Z' ); - }); - - it( 'parse integer time stamps on assignment', function(){ - // parse Date from timestamp - user.created = 1234567890123; - expect( user.created ).to.be.instanceof( Date ); - expect( user.created.toISOString() ).to.be.eql( '2009-02-13T23:31:30.123Z' ); - - user.timestamp = 1234567890123; - expect( user.timestamp ).to.be.instanceof( Date ); - expect( user.timestamp.toISOString() ).to.be.eql( '2009-02-13T23:31:30.123Z' ); - - user.microsoft = 1234567890123; - expect( user.microsoft ).to.be.instanceof( Date ); - expect( user.microsoft.toISOString() ).to.be.eql( '2009-02-13T23:31:30.123Z' ); - }); - - it( 'parse MS time stamps on assignment', function(){ - user.microsoft = "/Date(1234567890123)/"; - expect( user.microsoft ).to.be.instanceof( Date ); - expect( user.microsoft.toISOString() ).to.be.eql( '2009-02-13T23:31:30.123Z' ); - }); - - it( 'is serialized to ISO date', function(){ - var json = user.toJSON(); - expect( json.created ).to.be.eql( '2009-02-13T23:31:30.123Z' ); - expect( json.timestamp ).to.be.eql( 1234567890123 ); - expect( json.microsoft ).to.be.eql( '/Date(1234567890123)/' ); - } ); - }); - - describe( 'Attribute options', function(){ - describe( 'get hook', function(){ - var A = Nested.Model.extend({ - defaults : { - a : Number.has - .get( function( value ){ - return value * 2; - }) - } - }); - - var m = new A(); - m.a = 1; - - it( 'may modify returned attribute\'s value', function(){ - expect( m.a ).to.be.equal( 2 ); - }); - - it( 'is called from model.get', function(){ - expect( m.get( 'a' ) ).to.be.equal( 2 ); - }); - }); - - describe( 'set hook', function(){ - var A = Nested.Model.extend({ - defaults : { - a : Number.value( 33 ) - .set( function( value, options ){ - expect( value ).to.be.a( 'number' ); - - if( value !== 0 ){ - return value * 2; - } - }), - b : Number.has.watcher( 'watcher' ) - } - }); - - it( 'may modify value assigned to attribute\'s', function(){ - var m = new A(); - m.a = 1; - - expect( m.a ).to.be.equal( 2 ); - }); - - it( 'is called from model.set', function(){ - var m = new A(); - m.set({ 'a' : 1 }); - - expect( m.a ).to.be.equal( 2 ); - - m.set( { a : 3 } ); - - expect( m.a ).to.be.equal( 6 ); - }); - - it( 'is called after type cast', function(){ - var m = new A(); - m.a = "1"; - - expect( m.a ).to.be.equal( 2 ); - }); - - it( 'may prevent attribute\'s assignment', function(){ - var m = new A(); - m.set({ 'a' : 0 }); - - expect( m.a ).to.be.equal( 66 ); - }); - - it( 'Watcher functions', function(){ - var m = new A(); - m.watcher = sinon.spy(); - - m.b = 77; - expect( m.watcher ).to.be.calledOnce; - expect( m.watcher ).to.be.calledWith( 77 ); - }); - }); - - describe( 'toJSON hook', function(){ - it( 'override attribute\'s toJSON', function(){ - var A = Nested.Model.extend({ - defaults : { - a : Date.has - .toJSON( function( date ){ - return date.getTime(); - }) - } - }); - - var m = new A(), - json = m.toJSON(); - - expect( json.a ).to.be.a( 'number' ); - }); - - it( 'can prevent attribute from serialization', function(){ - var A = Nested.Model.extend({ - defaults : { - a : Date.has.toJSON( false ), - b : true - } - }); - - var m = new A(), - json = m.toJSON(); - - expect( json.a ).to.not.exist; - expect( json.b ).to.be.true; - }); - }); - - it( 'can define untyped attribute', function(){ - var A = Nested.Model.extend({ - defaults : { - a : Nested.value( 1 ) - } - }); - - var m = new A(); - expect( m.a ).to.equal( 1 ); - m.a = "1"; - expect( m.a ).to.equal( "1" ); - }); - }); - - }); diff --git a/tests/nestedtypes/index.html b/tests/nestedtypes/index.html deleted file mode 100644 index 5697d62..0000000 --- a/tests/nestedtypes/index.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - Models Tests - - - -
- - - - diff --git a/tests/nestedtypes/package.json b/tests/nestedtypes/package.json deleted file mode 100644 index 2f721f7..0000000 --- a/tests/nestedtypes/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "nestedtypes-regression", - "version": "1.0.0", - "description": "Regression tests from NestedTypes 1.3", - "main": "index.html", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "Vlad \"Gaperton\" Balin", - "license": "MIT", - "devDependencies": { - "backbone": "^1.3.3", - "chai": "^3.5.0", - "chai-as-promised": "^5.3.0", - "jquery": "^3.1.0", - "mocha": "^2.5.3", - "requirejs": "^2.2.0", - "sinon": "^1.17.4", - "sinon-chai": "^2.8.0", - "underscore": "^1.8.3" - } -} diff --git a/tests/nestedtypes/performance.html b/tests/nestedtypes/performance.html deleted file mode 100644 index a348b20..0000000 --- a/tests/nestedtypes/performance.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - Models Tests - - - -
- - - - diff --git a/tests/nestedtypes/performance/README.md b/tests/nestedtypes/performance/README.md deleted file mode 100644 index f9bf3c1..0000000 --- a/tests/nestedtypes/performance/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# Todo - -We need new perfromance test which would represent the reality we're dealing with. - -Large data structures comes from the server. - -There are two situations - empty set and merge set. Both must be checked. - -From UI standpoint - single field modification deep inside of the tree must be measured, -with validation. Ideally - links performance. - -## Large collections (50K). - -- Large collection, narrow models -- Large collection, wide models. - -## Deep model trees - -- Large tree, narrow models -- Large tree, wide models - -## Mixed tree. - -- Recursive model tree -- 10K collection of recursive model tree. - -## Links performance - -- Boolean deep inside the tree -- Text link with validation deep inside the tree. \ No newline at end of file diff --git a/tests/nestedtypes/performance/complex.js b/tests/nestedtypes/performance/complex.js deleted file mode 100644 index bf02914..0000000 --- a/tests/nestedtypes/performance/complex.js +++ /dev/null @@ -1,452 +0,0 @@ -define( function( require, exports, module ){ - var Nested = require( '../../../index.js' ), - Model = Nested.Model; - - /******************** - * Model definitions - */ - if( Nested.tools ){ - Nested.tools.log.level = 1; - } - - describe( 'Collections of flat models', function(){ - this.timeout( 100000 ); - - var SmallFlatModel = Model.extend({ - attributes : { - a : 0 - } - }); - - var LargeFlatModel = Model.extend({ - attributes : { - a0 : 0, a1 : 1, a2 : 2, a3 : 3, a4: 4, a5 : 5, a6: 6, a7: 7, a8: 8, a9: 9, - b0 : 0, b1 : 1, b2 : 2, b3 : 3, b4: 4, b5 : 5, b6: 6, b7: 7, b8: 8, b9: 9 - } - }); - - var smallData = [], - largeData = []; - - for( var i = 0; i < 50000; i++ ){ - smallData.push({ id : i, a : i }); - largeData.push({ id : i, - a0 : i, a1 : i, a2 : i, a3 : i, a4: i, a5 : i, a6: i, a7: i, a8: i, a9: i, - b0 : i, b1 : i, b2 : i, b3 : i, b4: i, b5 : i, b6: i, b7: i, b8: i, b9: i - }); - } - - smallData = JSON.stringify( smallData ); - largeData = JSON.stringify( largeData ); - - var small, large; - - beforeEach( function(){ - small = JSON.parse( smallData ); - large = JSON.parse( largeData ); - }); - - describe( 'Create 50K collection', function(){ - it( '1 attribute model', function(){ - var smallCollection = new SmallFlatModel.Collection( small ); - }); - - it( '20 attribute model', function(){ - var largeCollection = new LargeFlatModel.Collection( large ); - }); - }); - - describe( 'Fetch 50K collection', function(){ - it( '1 attribute model', function(){ - var smallCollection = new SmallFlatModel.Collection(); - smallCollection.set( small ); - }); - - it( '20 attribute model', function(){ - var largeCollection = new LargeFlatModel.Collection(); - largeCollection.set( large ); - }); - }); - - var _smallCollection = new SmallFlatModel.Collection( JSON.parse( smallData ) ); - var _largeCollection = new LargeFlatModel.Collection( JSON.parse( largeData ) ); - - describe( 'Update 50K collection', function(){ - it( '1 attribute model', function(){ - _smallCollection.set( small ); - }); - - it( '20 attribute model', function(){ - _largeCollection.set( large ); - }); - }); - - describe( 'Reset 50K collection', function(){ - it( '1 attribute model', function(){ - _smallCollection.reset( small ); - }); - - it( '20 attribute model', function(){ - _largeCollection.reset( large ); - }); - }); - }); - - describe( 'Recursive model structures', function(){ - this.timeout( 100000 ); - - var LinkedList = Model.extend(); - LinkedList.define({ - attributes : { - next : LinkedList.value( null ), - value : 0 - } - }); - - var Tree = Model.extend(); - Tree.define({ - attributes : { - a0 : Tree.value( null ), - a1 : Tree.value( null ), - a2 : Tree.value( null ), - a3 : Tree.value( null ), - a4 : Tree.value( null ), - a5 : Tree.value( null ), - a6 : Tree.value( null ), - a7 : Tree.value( null ), - a8 : Tree.value( null ), - a9 : Tree.value( null ), - value : 0 - } - }); - - function createTree( level ){ - if( level ){ - var l = level - 1; - return { - a0 : createTree( l ), - a1 : createTree( l ), - a2 : createTree( l ), - a3 : createTree( l ), - a4 : createTree( l ), - a5 : createTree( l ), - a6 : createTree( l ), - a7 : createTree( l ), - a8 : createTree( l ), - a9 : createTree( l ), - value : l - } - } - - return null; - } - - function createList( n ){ - var list = {}; - - for( var i = 0, l = list; i < 1000; i++, l = l.next ){ - l.next = { next : null, value : i }; - } - - return list; - } - - var treeData, listData; - - treeJSON = JSON.stringify( createTree( 6 ) ); - listJSON = JSON.stringify( createList( 1000 ) ); - - var _tree, _list; - - describe( '1000 elements linked list, 1000 times + parse time', function(){ - var list; - - it( 'Create from JSON', function(){ - for( var i = 0; i < 1000; i++ ){ - list = new LinkedList( JSON.parse( listJSON ) ); - } - }); - - it( 'Fetch empty from JSON', function(){ - for( var i = 0; i < 1000; i++ ){ - list = new LinkedList(); - list.set( JSON.parse( listJSON ) ); - } - }); - - it( 'Update with JSON', function(){ - for( var i = 0; i < 1000; i++ ){ - list.set( JSON.parse( listJSON ) ); - } - }); - }); - - describe( 'Wide model tree with 10 childs, 100K elements', function(){ - var data, tree; - beforeEach( function(){ - data = JSON.parse( treeJSON ); - }); - - it( 'Create from JSON', function(){ - tree = new Tree( data ); - }); - - it( 'Fetch empty from JSON', function(){ - tree = new Tree(); - tree.set( data ); - }); - - it( 'Update with JSON', function(){ - tree.set( data ); - }); - }); - }); - - describe( 'Recursive model/collection tree', function(){ - this.timeout( 100000 ); - - var Comment = Model.extend(); - Comment.define({ - attributes : { - time : Date, - text : String, - author_id : Number, - replies : Comment.Collection, - } - }); - - function createTree( level, id ){ - var l = level - 1; - return { - id : id || 0, - time : new Date(), - author_id : level, - text : 'hjkfshdkhjfksdhkj fhsdjkhfsdjk hjfksdhjk hfjsdkhjk hfjdskhjkhj fdssdffsdn,m nm, nm, nv,xvcvcx', - replies : l ? [ - createTree( l, 0 ), - createTree( l, 1 ), - createTree( l, 2 ), - createTree( l, 3 ), - createTree( l, 4 ), - createTree( l, 5 ), - createTree( l, 6 ), - createTree( l, 7 ), - createTree( l, 8 ), - createTree( l, 9 ) - ] : [] - } - } - - function createList( width, depth ){ - var list = []; - - for( var i = 0; i < width; i++ ){ - list.push( createTree( depth, i ) ); - } - - return list; - } - - var treeData = JSON.stringify( createTree( 6 ) ), - shortList = JSON.stringify( createList( 100, 4 ) ), - midList = JSON.stringify( createList( 1000, 3 ) ), - longList = JSON.stringify( createList( 10000, 2 ) ); - - var _comment, _short, _mid, _long; - - describe( '100K Model/Collection Tree', function(){ - var data, collection; - beforeEach( function(){ - data = JSON.parse( treeData ); - }); - - it( 'Create from JSON', function(){ - collection = new Comment.Collection( data ); - collection = null; - }); - - it( 'Fetch empty from JSON', function(){ - collection = new Comment.Collection(); - collection.set( data ); - }); - - it( 'Update with JSON', function(){ - collection.set( data ); - collection = null; - }); - }); - - describe( '100 elements Collection of 1000 items Model/Collection tree', function(){ - var data, collection; - beforeEach( function(){ - data = JSON.parse( shortList ); - }); - - it( 'Create from JSON', function(){ - collection = new Comment.Collection( data ); - collection = null; - }); - - it( 'Fetch empty from JSON', function(){ - collection = new Comment.Collection(); - collection.set( data ); - }); - - it( 'Update with JSON', function(){ - collection.set( data ); - collection = null; - }); - }); - - describe( '1000 elements Collection of 100 items Model/Collection tree', function(){ - var data, collection; - beforeEach( function(){ - data = JSON.parse( midList ); - }); - - it( 'Create from JSON', function(){ - collection = new Comment.Collection( data ); - collection = null; - }); - - it( 'Fetch empty from JSON', function(){ - collection = new Comment.Collection(); - collection.set( data ); - }); - - it( 'Update with JSON', function(){ - collection.set( data ); - collection = null; - }); - }); - - describe( '10 000 elements Collection of 10 items Model/Collection tree', function(){ - var data, collection; - beforeEach( function(){ - data = JSON.parse( longList ); - }); - - it( 'Create from JSON', function(){ - collection = new Comment.Collection( data ); - collection = null; - }); - - it( 'Fetch empty from JSON', function(){ - collection = new Comment.Collection(); - collection.set( data ); - }); - - it( 'Update with JSON', function(){ - collection.set( data ); - collection = null; - }); - }); - }); - - describe( 'Users directory', function(){ - var User = Model.extend({ - idAttribute: 'user_id', - defaults: { - created_at : Date, - updated_at : Date, - username : String, - password : String, - fname : String, - lname : String, - email : String, - active : Number, - 'default' : Number, - guid : '', - old_7password : String, - created_by : null, - domain_id: 0, - user_type : Number, - user_types : Array, - permissions: {}, - selectedEncoders : Nested.Collection.subsetOf( '~encoders' ), - roles : Nested.Collection.subsetOf( '~roles' ), - settings: Model.defaults({ - TZ: '', - DefaultMetadataState: 'off', - LoudnessMeterState: 'off', - OrderChannels: 'name', - PlayLiveLastChannel: false, - SendExportNotification: true, - DisplayPlayerSpeed: false - }) - } - }); - - var Dummy = Nested.Model.extend({ - attributes : { - name : '' - } - }); - - var Store = Nested.Store.defaults({ - encoders : Dummy.Collection, - roles : Dummy.Collection - }); - - var store; - if( Nested.store ){ - store = Nested.store = new Store(); - } - else{ - store = Nested.Store.global = new Store(); - } - - var dummies = []; - for( var i = 0; i < 100; i++ ){ - dummies.push( { id : i, name : 'name' + i }); - } - - store.encoders = dummies; - store.roles = dummies; - - var _users = []; - - for( var i = 0; i < 10000; i++ ){ - _users.push({ - active : 1, - created_at : "2015-11-18T16:57:10+00:00", - created_by : null, - default : 1, - domain_id : 0, - email : "observer-import-system@volicon.com", - fname : "api_import_user", - lname : "api_import_user", - roles:["5"], - updated_at:"2015-11-18T16:57:10+00:00", - user_id: i, - user_type:3, - user_types:["3"], - username : "api_import_user" - }); - } - - var usersJSONtext = JSON.stringify( _users ); - _users = null; - - var usersJSON; - - beforeEach( function(){ - usersJSON = JSON.parse( usersJSONtext ); - }); - - var collection; - - it( 'Creates users collection from JSON', function(){ - collection = new User.Collection( usersJSON ); - } ); - - it( 'Fetches users collection from JSON', function(){ - collection = new User.Collection(); - collection.set( usersJSON ); - } ); - - it( 'Updates users collection', function(){ - collection.set( usersJSON ); - }); - }); -}); diff --git a/tests/nestedtypes/performance/core.js b/tests/nestedtypes/performance/core.js deleted file mode 100644 index 82fa220..0000000 --- a/tests/nestedtypes/performance/core.js +++ /dev/null @@ -1,158 +0,0 @@ -import { Model } from 'nestedtypes' - -function emptyTest( n, context ){ - for( var i = 0; i < n; i++ ){ - // do nothing - } -} - -function measure( fun, context, iterations ){ - const start = window.performance.now(); - fun( iterations, context ); - return window.performance.now() - start; -} - -export const Test = Model.extend( { - idAttribute : 'name', - - defaults : { - executedAt : Date.value( null ), - name : String, - time : Number.value( null ), - count : Integer, - iterations : Integer, - faster : Number.value( null ), - exception : Error.value( null ), - init : Function.has.toJSON( false ), - test : Function.has.toJSON( false ).value( emptyTest ) - }, - - properties : { - ops(){ - return this.time ? Integer( this.count * 1000 / this.time ) : 0; - } - }, - - _measure( iterations, cumulative = false ){ - if( !cumulative ){ - this.time = this.count = 0; - } - - const context = this.init( iterations ) || {}; - this.time += measure( this.test, iterations, context ); - this.count += iterations; - }, - - _estimate(){ - this._measure( 100 ); - - for( let n = 200; this.time < 200; n *= 2 ){ - this._measure( n, true ); - } - - return this.ops * 3; - }, - - run( a_iterations ){ - this.transaction( () =>{ - this.exception = null; - this.executedAt = new Date(); - - try{ - var iterations = this.iterations || a_iterations || _estimate(); - this._measure( iterations ); - } - catch( e ){ - this.exception = e; - } - }); - }, - - collection : { - whoIsFaster( thanMe ){ - const ops = thanMe && thanMe.ops; - - this.transaction( () =>{ - this.tests.each( test => test.faster = ops && test.ops ? test.ops / ops : null ); - } ); - }, - - properties : { - time(){ - return this.reduce( ( ( sum, test ) => sum + test.time ), 0 ); - }, - - count(){ - return this.reduce( ( ( sum, test ) => sum + test.count ), 0 ); - }, - - ops(){ - return this.time ? Integer( this.count * 1000 / this.time ) : 0; - } - } - } -}); - -export const Group = Model.extend( { - idAttribute : 'name', - - defaults : { - executedAt : Date.value( null ), - name : String, - tests : Test.Collection, - selected : Test.from( 'tests' ), - iterations : Integer - }, - - initialize(){ - this.listenTo( this, 'change:selected change:tests', () =>{ - this.tests.whoIsFaster( this.selected ); - } ); - }, - - run(){ - this.executedAt = new Date(); - this.tests.each( test => test.run( this.iterations ) ); - } -} ); - -var groups = new Group.Collection(); - - -function oneAttrModel(){ - return Model.defaults({ a : 0 }); -} - -function createModel( count, Model ){ - var m; - - for( var i = 0; i < count; i++ ){ - m = new Model(); - } -} - -groups.create({ - name : 'Model creation (50K)', - tests : [ - { - name : 'Backbone 1-attr', - init : oneAttrBBModel, - test : createModel - }, - { - name : 'Nested 1-attr', - init : oneAttrNTModel, - test : createModel - }, - { - name : 'Backbone 20-attr', - init : twentyAttrBBModel, - test : createModel - }, - { - name : 'Nested 20-attr', - init : twentyAttrNTModel, - test : createModel - } - ] -}); \ No newline at end of file diff --git a/tests/nestedtypes/performance/main.js b/tests/nestedtypes/performance/main.js deleted file mode 100644 index 39d49e2..0000000 --- a/tests/nestedtypes/performance/main.js +++ /dev/null @@ -1,497 +0,0 @@ -define( function( require, exports, module ){ - var Nested = require( '../../../index' ), - Backbone = require( 'backbone' ); - - var NLarge = Nested.Model.extend({ - defaults : { - a1 : 1, a2 : 2, a3 : 3, a4: 4, a5 : 5, a6: 6, a7: 7, a8: 8, a9: 9, a10 : 10, - b1 : 1, b2 : 2, b3 : 3, b4: 4, b5 : 5, b6: 6, b7: 7, b8: 8, b9: 9, b10 : 10 - }, - - updateSet : function(){ - this.set({ - a1 : this.a1 + 1, - a2 : this.a2 + 1, - a3 : this.a3 + 1, - a4 : this.a4 + 1, - a5 : this.a5 + 1 - }); - }, - - updateTransaction : Nested.transaction(function(){ - this.a1 = this.a1 + 1; - this.a2 = this.a2 + 1; - this.a3 = this.a3 + 1; - this.a4 = this.a4 + 1; - this.a5 = this.a5 + 1; - }), - - updateAdHocTransaction : function(){ - this.transaction( function(){ - this.a1 = this.a1 + 1; - this.a2 = this.a2 + 1; - this.a3 = this.a3 + 1; - this.a4 = this.a4 + 1; - this.a5 = this.a5 + 1; - }, {} ); - }, - - save : function(){} - }); - - var BLarge = Backbone.Model.extend({ - defaults : { - a1 : 1, a2 : 2, a3 : 3, a4: 4, a5 : 5, a6: 6, a7: 7, a8: 8, a9: 9, a10 : 10, - b1 : 1, b2 : 2, b3 : 3, b4: 4, b5 : 5, b6: 6, b7: 7, b8: 8, b9: 9, b10 : 10 - }, - - updateSet : function(){ - this.set({ - a1 : this.get( 'a1' ) + 1, - a2 : this.get( 'a2' ) + 1, - a3 : this.get( 'a3' ) + 1, - a4 : this.get( 'a4' ) + 1, - a5 : this.get( 'a5' ) + 1 - }); - }, - - save : function(){} - }); - - var BLargeCollection = Backbone.Collection.extend({ - model : BLarge - }); - - - var NSmall = Nested.Model.extend({ - defaults : { - a1 : 1 - }, - - save : function(){} - }); - - var BSmall = Backbone.Model.extend({ - defaults : { - a1 : 1 - }, - - save : function(){} - }); - - var BSmallCollection = Backbone.Collection.extend({ - model : BSmall - }); - - describe( 'Flat models', function(){ - this.timeout( 100000 ); - - describe( 'Create performance', function(){ - var n, b; - - describe( '1-attr model, 50K new', function(){ - it( 'Backbone', function(){ - for( var i = 0; i < 50000; i++ ){ - b = new BSmall(); - } - } ); - - it( 'Nested', function(){ - for( var i = 0; i < 50000; i++ ){ - n = new NSmall(); - } - } ); - } ); - - describe( '20-attrs model, 50K new', function(){ - - it( 'Backbone', function(){ - for( var i = 0; i < 50000; i++ ){ - b = new BLarge(); - } - } ); - - it( 'Nested', function(){ - for( var i = 0; i < 50000; i++ ){ - n = new NLarge(); - } - } ); - } ); - - describe( '1-attr model, 50K collection.create', function(){ - it( 'Backbone', function(){ - var c = new BSmallCollection(); - for( var i = 0; i < 50000; i++ ){ - c.create(); - } - } ); - - it( 'Nested', function(){ - var c = new NSmall.Collection(); - - for( var i = 0; i < 50000; i++ ){ - c.create(); - } - } ); - } ); - - describe( '20-attr model, 50K collection.create', function(){ - it( 'Backbone', function(){ - var c = new BLargeCollection(); - for( var i = 0; i < 50000; i++ ){ - c.create(); - } - } ); - - it( 'Nested', function(){ - var c = new NLarge.Collection(); - - for( var i = 0; i < 50000; i++ ){ - c.create(); - } - } ); - } ); - - describe( '1-attr model, 50K collection reset', function(){ - var arr = []; - for( var i = 0; i < 50000; i++ ){ - arr.push({ a1 : i }); - } - - it( 'Backbone', function(){ - var c = new BSmallCollection(); - c.reset( arr ); - } ); - - it( 'Nested', function(){ - var c = new NSmall.Collection(); - c.reset( arr ); - } ); - } ); - - describe( '20-attr model, 50K collection reset', function(){ - var arr = []; - for( var i = 0; i < 50000; i++ ){ - arr.push({ a1 : i, a2 : i, a3: i, a4 : i, a5 : i, a6 : i, a7 : i, a8: i, a9 : i, a10 : i}); - } - - it( 'Backbone', function(){ - var c = new BLargeCollection(); - c.reset( arr ); - } ); - - it( 'Nested', function(){ - var c = new NLarge.Collection(); - c.reset( arr ); - } ); - } ); - - describe( '1-attr model, 50K collection set/update', function(){ - var arr = [], update = []; - for( var i = 0; i < 50000; i++ ){ - arr.push({ id: i, a1 : i }); - update.push({ id: i, a1 : i + 1 }); - } - - it( 'Backbone', function(){ - var c = new BSmallCollection(); - c.set( arr ); - c.set( update ); - } ); - - it( 'Nested', function(){ - var c = new NSmall.Collection(); - c.set( arr ); - c.set( update ); - } ); - - } ); - - describe( '20-attr model, 50K collection set/update', function(){ - var arr = [], update = []; - for( var i = 0; i < 100000; i++ ){ - arr.push({ id : i, a1 : i, a2 : i, a3: i, a4 : i, a5 : i, a6 : i, a7 : i, a8: i, a9 : i, a10 : i}); - i++; - update.push({ id : i - 1, a1 : i, a2 : i, a3: i, a4 : i, a5 : i, a6 : i, a7 : i, a8: i, a9 : i, a10 : i}); - } - - it( 'Backbone', function(){ - var c = new BLargeCollection(); - c.set( arr ); - c.set( update ); - } ); - - it( 'Nested', function(){ - var c = new NLarge.Collection(); - c.set( arr ); - c.set( update ); - } ); - } ); - }); - - describe( 'Update performance', function(){ - var n, b; - - describe( '1-attr model, 100K collection.create', function(){ - it( 'Backbone', function(){ - var c = new BSmallCollection(); - for( var i = 0; i < 100000; i++ ){ - c.create(); - } - } ); - - it( 'Nested', function(){ - var c = new NSmall.Collection(); - - for( var i = 0; i < 100000; i++ ){ - c.create(); - } - } ); - } ); - - describe( '20-attr model, 100K collection.create', function(){ - it( 'Backbone', function(){ - var c = new BLargeCollection(); - for( var i = 0; i < 100000; i++ ){ - c.create(); - } - } ); - - it( 'Nested', function(){ - var c = new NLarge.Collection(); - - for( var i = 0; i < 100000; i++ ){ - c.create(); - } - } ); - } ); - - describe( '1-attr model, 100K collection reset', function(){ - var arr = []; - for( var i = 0; i < 100000; i++ ){ - arr.push({ a1 : i }); - } - - it( 'Backbone', function(){ - var c = new BSmallCollection(); - c.reset( arr ); - } ); - - it( 'Nested', function(){ - var c = new NSmall.Collection(); - c.reset( arr ); - } ); - } ); - - describe( '20-attr model, 100K collection reset', function(){ - var arr = []; - for( var i = 0; i < 100000; i++ ){ - arr.push({ a1 : i, a2 : i, a3: i, a4 : i, a5 : i, a6 : i, a7 : i, a8: i, a9 : i, a10 : i}); - } - - it( 'Backbone', function(){ - var c = new BLargeCollection(); - c.reset( arr ); - } ); - - it( 'Nested', function(){ - var c = new NLarge.Collection(); - c.reset( arr ); - } ); - } ); - - describe( '1-attr model, 100K collection set/update', function(){ - var arr = [], update = []; - for( var i = 0; i < 100000; i++ ){ - arr.push({ id: i, a1 : i }); - update.push({ id: i, a1 : i + 1 }); - } - - it( 'Backbone', function(){ - var c = new BSmallCollection(); - c.set( arr ); - c.set( update ); - } ); - - it( 'Nested', function(){ - var c = new NSmall.Collection(); - c.set( arr ); - c.set( update ); - } ); - - } ); - - describe( '20-attr model, 100K collection set/update', function(){ - var arr = [], update = []; - for( var i = 0; i < 200000; i++ ){ - arr.push({ id : i, a1 : i, a2 : i, a3: i, a4 : i, a5 : i, a6 : i, a7 : i, a8: i, a9 : i, a10 : i}); - i++; - update.push({ id : i - 1, a1 : i, a2 : i, a3: i, a4 : i, a5 : i, a6 : i, a7 : i, a8: i, a9 : i, a10 : i}); - } - - it( 'Backbone', function(){ - var c = new BLargeCollection(); - c.set( arr ); - c.set( update ); - } ); - - it( 'Nested', function(){ - var c = new NLarge.Collection(); - c.set( arr ); - c.set( update ); - } ); - } ); - }); - - describe( 'Model update performance', function(){ - var n, b; - - describe( '1-attr model, 1M .set( "a1", number )', function(){ - - var b = new BSmall(); - - it( 'Backbone', function(){ - for( var i = 0; i < 1000000; i++ ){ - b.set( 'a1', i ); - } - }); - - var n = new NSmall(); - - it( 'Nested', function(){ - for( var i = 0; i < 1000000; i++ ){ - n.set( 'a1' , i ); - } - }); - - var n = new NSmall(); - - it( 'Nested native property', function(){ - for( var i = 0; i < 1000000; i++ ){ - n.a1 = i; - } - }); - }); - - describe( '20-attrs model, 1M .set( "a1", number )', function(){ - var b = new BLarge(); - - it( 'Backbone', function(){ - for( var i = 0; i < 1000000; i++ ){ - b.set( 'a1', i ); - } - }); - - var n = new NLarge(); - - it( 'Nested', function(){ - for( var i = 0; i < 1000000; i++ ){ - n.set( 'a1', i ); - } - }); - - var n = new NLarge(); - - it( 'Nested native property', function(){ - for( var i = 0; i < 1000000; i++ ){ - n.a1 = i; - } - }); - }); - - describe( '20-attrs model, 10M .get( "a1" )', function(){ - - var b = new BLarge({ a1: 1 }), x; - - it( 'Backbone', function(){ - for( var i = 0; i < 10000000; i++ ){ - x = b.get( 'a1' ); - } - }); - - var n = new NLarge({ a1: 1 }); - - it( 'Nested', function(){ - for( var i = 0; i < 10000000; i++ ){ - x = n.get( 'a1' ); - } - }); - - var n = new NLarge({ a1: 1 }); - - it( 'Nested native property', function(){ - for( var i = 0; i < 10000000; i++ ){ - x = n.a1; - } - }); - }); - - describe( 'both models, 1M read and write', function(){ - - it( 'Backbone', function(){ - var l = new BLarge(), s = new BSmall(); - - for( var i = 0; i < 1000000; i++ ){ - l.set( 'a1', l.get( 'a1' ) + 1 ); - s.set( 'a1', l.get( 'a1' ) + 1 ); - } - }); - - it( 'Nested', function(){ - var l = new NLarge(), s = new NSmall(); - - for( var i = 0; i < 1000000; i++ ){ - l.set( 'a1', l.get( 'a1' ) + 1 ); - s.set( 'a1', l.get( 'a1' ) + 1 ); - } - }); - - it( 'Nested native', function(){ - var l = new NLarge(), s = new NSmall(); - - for( var i = 0; i < 1000000; i++ ){ - l.a1 = l.a1 + 1; - s.a1 = l.a1 + 1; - } - }); - }); - - describe( '1M 5-attr transactional updates', function(){ - - it( 'Backbone', function(){ - var l = new BLarge(); - - for( var i = 0; i < 1000000; i++ ){ - l.updateSet(); - } - }); - - it( 'Nested', function(){ - var l = new NLarge(); - - for( var i = 0; i < 1000000; i++ ){ - l.updateSet(); - } - }); - - it( 'Nested transaction', function(){ - var l = new NLarge(); - - for( var i = 0; i < 1000000; i++ ){ - l.updateTransaction(); - } - }); - - it( 'Nested AdHoc transaction', function(){ - var l = new NLarge(); - - for( var i = 0; i < 1000000; i++ ){ - l.updateAdHocTransaction(); - } - }); - }); - }); - - - }); -}); diff --git a/tests/nestedtypes/performance/models.js b/tests/nestedtypes/performance/models.js deleted file mode 100644 index 3527982..0000000 --- a/tests/nestedtypes/performance/models.js +++ /dev/null @@ -1,403 +0,0 @@ -define( function( require, exports, module ){ - var Nested = require( '../nestedtypes' ), - Backbone = require( 'backbone' ); - - var NLarge = Nested.Model.extend({ - defaults : { - a1 : 1, a2 : 2, a3 : 3, a4: 4, a5 : 5, a6: 6, a7: 7, a8: 8, a9: 9, a10 : 10, - b1 : 1, b2 : 2, b3 : 3, b4: 4, b5 : 5, b6: 6, b7: 7, b8: 8, b9: 9, b10 : 10 - }, - - updateSet : function(){ - this.set({ - a1 : this.a1 + 1, - a2 : this.a2 + 1, - a3 : this.a3 + 1, - a4 : this.a4 + 1, - a5 : this.a5 + 1 - }); - }, - - updateTransaction : Nested.transaction(function(){ - this.a1 = this.a1 + 1; - this.a2 = this.a2 + 1; - this.a3 = this.a3 + 1; - this.a4 = this.a4 + 1; - this.a5 = this.a5 + 1; - }), - - updateAdHocTransaction : function(){ - this.transaction( function(){ - this.a1 = this.a1 + 1; - this.a2 = this.a2 + 1; - this.a3 = this.a3 + 1; - this.a4 = this.a4 + 1; - this.a5 = this.a5 + 1; - }, {} ); - }, - - save(){} - }); - - var BLarge = Backbone.Model.extend({ - defaults : { - a1 : 1, a2 : 2, a3 : 3, a4: 4, a5 : 5, a6: 6, a7: 7, a8: 8, a9: 9, a10 : 10, - b1 : 1, b2 : 2, b3 : 3, b4: 4, b5 : 5, b6: 6, b7: 7, b8: 8, b9: 9, b10 : 10 - }, - - updateSet : function(){ - this.set({ - a1 : this.get( 'a1' ) + 1, - a2 : this.get( 'a2' ) + 1, - a3 : this.get( 'a3' ) + 1, - a4 : this.get( 'a4' ) + 1, - a5 : this.get( 'a5' ) + 1 - }); - }, - - save(){} - }); - - var BLargeCollection = Backbone.Collection.extend({ - model : BLarge - }); - - - var NSmall = Nested.Model.extend({ - defaults : { - a1 : 1 - }, - - save(){} - }); - - var BSmall = Backbone.Model.extend({ - defaults : { - a1 : 1 - }, - - save(){} - }); - - var BSmallCollection = Backbone.Collection.extend({ - model : BSmall - }); - - describe( 'Models performance', function(){ - this.timeout( 100000 ); - - describe( 'Create', function(){ - var n, b; - - describe( '50K new 1attrModel()', function(){ - it( 'Backbone', function(){ - for( var i = 0; i < 50000; i++ ){ - b = new BSmall(); - } - } ); - - it( 'Nested', function(){ - for( var i = 0; i < 50000; i++ ){ - n = new NSmall(); - } - } ); - } ); - - describe( '50K new 20attrModel()', function(){ - it( 'Backbone', function(){ - for( var i = 0; i < 50000; i++ ){ - b = new BLarge(); - } - } ); - - it( 'Nested', function(){ - for( var i = 0; i < 50000; i++ ){ - n = new NLarge(); - } - } ); - } ); - - describe( '50K new 20attrModel({ all attrs }, { parse : true })', function(){ - it( 'Backbone', function(){ - for( var i = 0; i < 50000; i++ ){ - b = new BLarge(); - } - } ); - - it( 'Nested', function(){ - for( var i = 0; i < 50000; i++ ){ - n = new NLarge(); - } - } ); - } ); - }); - - describe( 'Update performance', function(){ - var n, b; - - describe( '1-attr model, 100K collection.create', function(){ - it( 'Backbone', function(){ - var c = new BSmallCollection(); - for( var i = 0; i < 100000; i++ ){ - c.create(); - } - } ); - - it( 'Nested', function(){ - var c = new NSmall.Collection(); - - for( var i = 0; i < 100000; i++ ){ - c.create(); - } - } ); - } ); - - describe( '20-attr model, 100K collection.create', function(){ - it( 'Backbone', function(){ - var c = new BLargeCollection(); - for( var i = 0; i < 100000; i++ ){ - c.create(); - } - } ); - - it( 'Nested', function(){ - var c = new NLarge.Collection(); - - for( var i = 0; i < 100000; i++ ){ - c.create(); - } - } ); - } ); - - describe( '1-attr model, 100K collection reset', function(){ - var arr = []; - for( var i = 0; i < 100000; i++ ){ - arr.push({ a1 : i }); - } - - it( 'Backbone', function(){ - var c = new BSmallCollection(); - c.reset( arr ); - } ); - - it( 'Nested', function(){ - var c = new NSmall.Collection(); - c.reset( arr ); - } ); - } ); - - describe( '20-attr model, 100K collection reset', function(){ - var arr = []; - for( var i = 0; i < 100000; i++ ){ - arr.push({ a1 : i, a2 : i, a3: i, a4 : i, a5 : i, a6 : i, a7 : i, a8: i, a9 : i, a10 : i}); - } - - it( 'Backbone', function(){ - var c = new BLargeCollection(); - c.reset( arr ); - } ); - - it( 'Nested', function(){ - var c = new NLarge.Collection(); - c.reset( arr ); - } ); - } ); - - describe( '1-attr model, 100K collection set/update', function(){ - var arr = [], update = []; - for( var i = 0; i < 100000; i++ ){ - arr.push({ id: i, a1 : i }); - update.push({ id: i, a1 : i + 1 }); - } - - it( 'Backbone', function(){ - var c = new BSmallCollection(); - c.set( arr ); - c.set( update ); - } ); - - it( 'Nested', function(){ - var c = new NSmall.Collection(); - c.set( arr ); - c.set( update ); - } ); - - } ); - - describe( '20-attr model, 100K collection set/update', function(){ - var arr = [], update = []; - for( var i = 0; i < 200000; i++ ){ - arr.push({ id : i, a1 : i, a2 : i, a3: i, a4 : i, a5 : i, a6 : i, a7 : i, a8: i, a9 : i, a10 : i}); - i++; - update.push({ id : i - 1, a1 : i, a2 : i, a3: i, a4 : i, a5 : i, a6 : i, a7 : i, a8: i, a9 : i, a10 : i}); - } - - it( 'Backbone', function(){ - var c = new BLargeCollection(); - c.set( arr ); - c.set( update ); - } ); - - it( 'Nested', function(){ - var c = new NLarge.Collection(); - c.set( arr ); - c.set( update ); - } ); - } ); - }); - - describe( 'Update performance', function(){ - var n, b; - - describe( '1-attr model, 1M .set( "a1", number )', function(){ - - var b = new BSmall(); - - it( 'Backbone', function(){ - for( var i = 0; i < 1000000; i++ ){ - b.set( 'a1', i ); - } - }); - - var n = new NSmall(); - - it( 'Nested', function(){ - for( var i = 0; i < 1000000; i++ ){ - n.set( 'a1', i ); - } - }); - - var n = new NSmall(); - - it( 'Nested native property', function(){ - for( var i = 0; i < 1000000; i++ ){ - n.a1 = i; - } - }); - }); - - describe( '20-attrs model, 1M .set( "a1", number )', function(){ - - - - var b = new BLarge(); - - it( 'Backbone', function(){ - for( var i = 0; i < 1000000; i++ ){ - b.set( 'a1', i ); - } - }); - - var n = new NLarge(); - - it( 'Nested', function(){ - for( var i = 0; i < 1000000; i++ ){ - n.set( 'a1', i ); - } - }); - - var n = new NLarge(); - - it( 'Nested native property', function(){ - for( var i = 0; i < 1000000; i++ ){ - n.a1 = i; - } - }); - }); - - describe( '20-attrs model, 10M .get( "a1" )', function(){ - - var b = new BLarge({ a1: 1 }), x; - - it( 'Backbone', function(){ - for( var i = 0; i < 10000000; i++ ){ - x = b.get( 'a1' ); - } - }); - - var n = new NLarge({ a1: 1 }); - - it( 'Nested', function(){ - for( var i = 0; i < 10000000; i++ ){ - x = n.get( 'a1' ); - } - }); - - var n = new NLarge({ a1: 1 }); - - it( 'Nested native property', function(){ - for( var i = 0; i < 10000000; i++ ){ - x = n.a1; - } - }); - }); - - describe( 'both models, 1M read and write', function(){ - - it( 'Backbone', function(){ - var l = new BLarge(), s = new BSmall(); - - for( var i = 0; i < 1000000; i++ ){ - l.set( 'a1', l.get( 'a1' ) + 1 ); - s.set( 'a1', l.get( 'a1' ) + 1 ); - } - }); - - it( 'Nested', function(){ - var l = new NLarge(), s = new NSmall(); - - for( var i = 0; i < 1000000; i++ ){ - l.set( 'a1', l.get( 'a1' ) + 1 ); - s.set( 'a1', l.get( 'a1' ) + 1 ); - } - }); - - it( 'Nested native', function(){ - var l = new NLarge(), s = new NSmall(); - - for( var i = 0; i < 1000000; i++ ){ - l.a1 = l.a1 + 1; - s.a1 = l.a1 + 1; - } - }); - }); - - describe( '1M 5-attr transactional updates', function(){ - - it( 'Backbone', function(){ - var l = new BLarge(); - - for( var i = 0; i < 1000000; i++ ){ - l.updateSet(); - } - }); - - it( 'Nested', function(){ - var l = new NLarge(); - - for( var i = 0; i < 1000000; i++ ){ - l.updateSet(); - } - }); - - it( 'Nested transaction', function(){ - var l = new NLarge(); - - for( var i = 0; i < 1000000; i++ ){ - l.updateTransaction(); - } - }); - - it( 'Nested AdHoc transaction', function(){ - var l = new NLarge(); - - for( var i = 0; i < 1000000; i++ ){ - l.updateAdHocTransaction(); - } - }); - }); - }); - - - }); -}); diff --git a/tsconfig.json b/tsconfig.json index 6598cca..c56ad6d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,17 +1,17 @@ { "compilerOptions": { "target": "es5", - "module":"commonjs", + "module":"es6", + "declaration": true, "moduleResolution": "node", + "importHelpers": true, "sourceMap": true, - "outDir": "./dist", + "outDir": "./lib", "noImplicitAny": false, "removeComments":true, - "experimentalDecorators": true, - "allowJs" : true + "experimentalDecorators": true }, "files":[ - "./src/index.ts", - "./typings/index.d.ts" + "./src/index.ts" ] } \ No newline at end of file diff --git a/typings.json b/typings.json deleted file mode 100644 index 531f26d..0000000 --- a/typings.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "globalDependencies": { - "jquery": "registry:dt/jquery#1.10.0+20160704162008", - "underscore": "registry:dt/underscore#1.7.0+20160720002543" - } -} diff --git a/typings/globals/jquery/index.d.ts b/typings/globals/jquery/index.d.ts deleted file mode 100644 index 1217be0..0000000 --- a/typings/globals/jquery/index.d.ts +++ /dev/null @@ -1,3218 +0,0 @@ -// Generated by typings -// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/6e54cb627506cf64d6effba1fe49b5a091ac4297/jquery/jquery.d.ts -interface JQueryAjaxSettings { - /** - * The content type sent in the request header that tells the server what kind of response it will accept in return. If the accepts setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. - */ - accepts?: any; - /** - * By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success(). - */ - async?: boolean; - /** - * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request. - */ - beforeSend? (jqXHR: JQueryXHR, settings: JQueryAjaxSettings): any; - /** - * If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET. - */ - cache?: boolean; - /** - * A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. - */ - complete? (jqXHR: JQueryXHR, textStatus: string): any; - /** - * An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. (version added: 1.5) - */ - contents?: { [key: string]: any; }; - //According to jQuery.ajax source code, ajax's option actually allows contentType to set to "false" - // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/742 - /** - * When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. - */ - contentType?: any; - /** - * This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). - */ - context?: any; - /** - * An object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. (version added: 1.5) - */ - converters?: { [key: string]: any; }; - /** - * If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain. (version added: 1.5) - */ - crossDomain?: boolean; - /** - * Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). - */ - data?: any; - /** - * A function to be used to handle the raw response data of XMLHttpRequest.This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter. - */ - dataFilter? (data: any, ty: any): any; - /** - * The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). - */ - dataType?: string; - /** - * A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event. - */ - error? (jqXHR: JQueryXHR, textStatus: string, errorThrown: string): any; - /** - * Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events. - */ - global?: boolean; - /** - * An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, but its default XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from within the beforeSend function. (version added: 1.5) - */ - headers?: { [key: string]: any; }; - /** - * Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data. - */ - ifModified?: boolean; - /** - * Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. (version added: 1.5.1) - */ - isLocal?: boolean; - /** - * Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" } - */ - jsonp?: any; - /** - * Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function. - */ - jsonpCallback?: any; - /** - * The HTTP method to use for the request (e.g. "POST", "GET", "PUT"). (version added: 1.9.0) - */ - method?: string; - /** - * A mime type to override the XHR mime type. (version added: 1.5.1) - */ - mimeType?: string; - /** - * A password to be used with XMLHttpRequest in response to an HTTP access authentication request. - */ - password?: string; - /** - * By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false. - */ - processData?: boolean; - /** - * Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or "script" dataType and "GET" type). Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script. - */ - scriptCharset?: string; - /** - * An object of numeric HTTP codes and functions to be called when the response has the corresponding code. f the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback. (version added: 1.5) - */ - statusCode?: { [key: string]: any; }; - /** - * A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. - */ - success? (data: any, textStatus: string, jqXHR: JQueryXHR): any; - /** - * Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period. - */ - timeout?: number; - /** - * Set this to true if you wish to use the traditional style of param serialization. - */ - traditional?: boolean; - /** - * The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers. - */ - type?: string; - /** - * A string containing the URL to which the request is sent. - */ - url?: string; - /** - * A username to be used with XMLHttpRequest in response to an HTTP access authentication request. - */ - username?: string; - /** - * Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory. - */ - xhr?: any; - /** - * An object of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed. In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it. (version added: 1.5.1) - */ - xhrFields?: { [key: string]: any; }; -} - -/** - * Interface for the jqXHR object - */ -interface JQueryXHR extends XMLHttpRequest, JQueryPromise { - /** - * The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header. As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). - */ - overrideMimeType(mimeType: string): any; - /** - * Cancel the request. - * - * @param statusText A string passed as the textStatus parameter for the done callback. Default value: "canceled" - */ - abort(statusText?: string): void; - /** - * Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details. - */ - then(doneCallback: (data: any, textStatus: string, jqXHR: JQueryXHR) => R, failCallback?: (jqXHR: JQueryXHR, textStatus: string, errorThrown: any) => void): JQueryPromise; - /** - * Property containing the parsed response if the response Content-Type is json - */ - responseJSON?: any; - /** - * A function to be called if the request fails. - */ - error(xhr: JQueryXHR, textStatus: string, errorThrown: string): void; -} - -/** - * Interface for the JQuery callback - */ -interface JQueryCallback { - /** - * Add a callback or a collection of callbacks to a callback list. - * - * @param callbacks A function, or array of functions, that are to be added to the callback list. - */ - add(callbacks: Function): JQueryCallback; - /** - * Add a callback or a collection of callbacks to a callback list. - * - * @param callbacks A function, or array of functions, that are to be added to the callback list. - */ - add(callbacks: Function[]): JQueryCallback; - - /** - * Disable a callback list from doing anything more. - */ - disable(): JQueryCallback; - - /** - * Determine if the callbacks list has been disabled. - */ - disabled(): boolean; - - /** - * Remove all of the callbacks from a list. - */ - empty(): JQueryCallback; - - /** - * Call all of the callbacks with the given arguments - * - * @param arguments The argument or list of arguments to pass back to the callback list. - */ - fire(...arguments: any[]): JQueryCallback; - - /** - * Determine if the callbacks have already been called at least once. - */ - fired(): boolean; - - /** - * Call all callbacks in a list with the given context and arguments. - * - * @param context A reference to the context in which the callbacks in the list should be fired. - * @param arguments An argument, or array of arguments, to pass to the callbacks in the list. - */ - fireWith(context?: any, args?: any[]): JQueryCallback; - - /** - * Determine whether a supplied callback is in a list - * - * @param callback The callback to search for. - */ - has(callback: Function): boolean; - - /** - * Lock a callback list in its current state. - */ - lock(): JQueryCallback; - - /** - * Determine if the callbacks list has been locked. - */ - locked(): boolean; - - /** - * Remove a callback or a collection of callbacks from a callback list. - * - * @param callbacks A function, or array of functions, that are to be removed from the callback list. - */ - remove(callbacks: Function): JQueryCallback; - /** - * Remove a callback or a collection of callbacks from a callback list. - * - * @param callbacks A function, or array of functions, that are to be removed from the callback list. - */ - remove(callbacks: Function[]): JQueryCallback; -} - -/** - * Allows jQuery Promises to interop with non-jQuery promises - */ -interface JQueryGenericPromise { - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter A function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - */ - then(doneFilter: (value?: T, ...values: any[]) => U|JQueryPromise, failFilter?: (...reasons: any[]) => any, progressFilter?: (...progression: any[]) => any): JQueryPromise; - - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter A function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - */ - then(doneFilter: (value?: T, ...values: any[]) => void, failFilter?: (...reasons: any[]) => any, progressFilter?: (...progression: any[]) => any): JQueryPromise; -} - -/** - * Interface for the JQuery promise/deferred callbacks - */ -interface JQueryPromiseCallback { - (value?: T, ...args: any[]): void; -} - -interface JQueryPromiseOperator { - (callback1: JQueryPromiseCallback|JQueryPromiseCallback[], ...callbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; -} - -/** - * Interface for the JQuery promise, part of callbacks - */ -interface JQueryPromise extends JQueryGenericPromise { - /** - * Determine the current state of a Deferred object. - */ - state(): string; - /** - * Add handlers to be called when the Deferred object is either resolved or rejected. - * - * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. - * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. - */ - always(alwaysCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...alwaysCallbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; - /** - * Add handlers to be called when the Deferred object is resolved. - * - * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. - * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. - */ - done(doneCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...doneCallbackN: Array|JQueryPromiseCallback[]>): JQueryPromise; - /** - * Add handlers to be called when the Deferred object is rejected. - * - * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. - * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. - */ - fail(failCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...failCallbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; - /** - * Add handlers to be called when the Deferred object generates progress notifications. - * - * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. - */ - progress(progressCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...progressCallbackN: Array|JQueryPromiseCallback[]>): JQueryPromise; - - // Deprecated - given no typings - pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; -} - -/** - * Interface for the JQuery deferred, part of callbacks - */ -interface JQueryDeferred extends JQueryGenericPromise { - /** - * Determine the current state of a Deferred object. - */ - state(): string; - /** - * Add handlers to be called when the Deferred object is either resolved or rejected. - * - * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. - * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. - */ - always(alwaysCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...alwaysCallbacksN: Array|JQueryPromiseCallback[]>): JQueryDeferred; - /** - * Add handlers to be called when the Deferred object is resolved. - * - * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. - * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. - */ - done(doneCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...doneCallbackN: Array|JQueryPromiseCallback[]>): JQueryDeferred; - /** - * Add handlers to be called when the Deferred object is rejected. - * - * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. - * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. - */ - fail(failCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...failCallbacksN: Array|JQueryPromiseCallback[]>): JQueryDeferred; - /** - * Add handlers to be called when the Deferred object generates progress notifications. - * - * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. - */ - progress(progressCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...progressCallbackN: Array|JQueryPromiseCallback[]>): JQueryDeferred; - - /** - * Call the progressCallbacks on a Deferred object with the given args. - * - * @param args Optional arguments that are passed to the progressCallbacks. - */ - notify(value?: any, ...args: any[]): JQueryDeferred; - - /** - * Call the progressCallbacks on a Deferred object with the given context and args. - * - * @param context Context passed to the progressCallbacks as the this object. - * @param args Optional arguments that are passed to the progressCallbacks. - */ - notifyWith(context: any, value?: any[]): JQueryDeferred; - - /** - * Reject a Deferred object and call any failCallbacks with the given args. - * - * @param args Optional arguments that are passed to the failCallbacks. - */ - reject(value?: any, ...args: any[]): JQueryDeferred; - /** - * Reject a Deferred object and call any failCallbacks with the given context and args. - * - * @param context Context passed to the failCallbacks as the this object. - * @param args An optional array of arguments that are passed to the failCallbacks. - */ - rejectWith(context: any, value?: any[]): JQueryDeferred; - - /** - * Resolve a Deferred object and call any doneCallbacks with the given args. - * - * @param value First argument passed to doneCallbacks. - * @param args Optional subsequent arguments that are passed to the doneCallbacks. - */ - resolve(value?: T, ...args: any[]): JQueryDeferred; - - /** - * Resolve a Deferred object and call any doneCallbacks with the given context and args. - * - * @param context Context passed to the doneCallbacks as the this object. - * @param args An optional array of arguments that are passed to the doneCallbacks. - */ - resolveWith(context: any, value?: T[]): JQueryDeferred; - - /** - * Return a Deferred's Promise object. - * - * @param target Object onto which the promise methods have to be attached - */ - promise(target?: any): JQueryPromise; - - // Deprecated - given no typings - pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; -} - -/** - * Interface of the JQuery extension of the W3C event object - */ -interface BaseJQueryEventObject extends Event { - currentTarget: Element; - data: any; - delegateTarget: Element; - isDefaultPrevented(): boolean; - isImmediatePropagationStopped(): boolean; - isPropagationStopped(): boolean; - namespace: string; - originalEvent: Event; - preventDefault(): any; - relatedTarget: Element; - result: any; - stopImmediatePropagation(): void; - stopPropagation(): void; - target: Element; - pageX: number; - pageY: number; - which: number; - metaKey: boolean; -} - -interface JQueryInputEventObject extends BaseJQueryEventObject { - altKey: boolean; - ctrlKey: boolean; - metaKey: boolean; - shiftKey: boolean; -} - -interface JQueryMouseEventObject extends JQueryInputEventObject { - button: number; - clientX: number; - clientY: number; - offsetX: number; - offsetY: number; - pageX: number; - pageY: number; - screenX: number; - screenY: number; -} - -interface JQueryKeyEventObject extends JQueryInputEventObject { - char: any; - charCode: number; - key: any; - keyCode: number; -} - -interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject{ -} - -/* - Collection of properties of the current browser -*/ - -interface JQuerySupport { - ajax?: boolean; - boxModel?: boolean; - changeBubbles?: boolean; - checkClone?: boolean; - checkOn?: boolean; - cors?: boolean; - cssFloat?: boolean; - hrefNormalized?: boolean; - htmlSerialize?: boolean; - leadingWhitespace?: boolean; - noCloneChecked?: boolean; - noCloneEvent?: boolean; - opacity?: boolean; - optDisabled?: boolean; - optSelected?: boolean; - scriptEval? (): boolean; - style?: boolean; - submitBubbles?: boolean; - tbody?: boolean; -} - -interface JQueryParam { - /** - * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. - * - * @param obj An array or object to serialize. - */ - (obj: any): string; - - /** - * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. - * - * @param obj An array or object to serialize. - * @param traditional A Boolean indicating whether to perform a traditional "shallow" serialization. - */ - (obj: any, traditional: boolean): string; -} - -/** - * The interface used to construct jQuery events (with $.Event). It is - * defined separately instead of inline in JQueryStatic to allow - * overriding the construction function with specific strings - * returning specific event objects. - */ -interface JQueryEventConstructor { - (name: string, eventProperties?: any): JQueryEventObject; - new (name: string, eventProperties?: any): JQueryEventObject; -} - -/** - * The interface used to specify coordinates. - */ -interface JQueryCoordinates { - left: number; - top: number; -} - -/** - * Elements in the array returned by serializeArray() - */ -interface JQuerySerializeArrayElement { - name: string; - value: string; -} - -interface JQueryAnimationOptions { - /** - * A string or number determining how long the animation will run. - */ - duration?: any; - /** - * A string indicating which easing function to use for the transition. - */ - easing?: string; - /** - * A function to call once the animation is complete. - */ - complete?: Function; - /** - * A function to be called for each animated property of each animated element. This function provides an opportunity to modify the Tween object to change the value of the property before it is set. - */ - step?: (now: number, tween: any) => any; - /** - * A function to be called after each step of the animation, only once per animated element regardless of the number of animated properties. (version added: 1.8) - */ - progress?: (animation: JQueryPromise, progress: number, remainingMs: number) => any; - /** - * A function to call when the animation begins. (version added: 1.8) - */ - start?: (animation: JQueryPromise) => any; - /** - * A function to be called when the animation completes (its Promise object is resolved). (version added: 1.8) - */ - done?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; - /** - * A function to be called when the animation fails to complete (its Promise object is rejected). (version added: 1.8) - */ - fail?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; - /** - * A function to be called when the animation completes or stops without completing (its Promise object is either resolved or rejected). (version added: 1.8) - */ - always?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; - /** - * A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string. When a custom queue name is used the animation does not automatically start; you must call .dequeue("queuename") to start it. - */ - queue?: any; - /** - * A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions. (version added: 1.4) - */ - specialEasing?: Object; -} - -interface JQueryEasingFunction { - ( percent: number ): number; -} - -interface JQueryEasingFunctions { - [ name: string ]: JQueryEasingFunction; - linear: JQueryEasingFunction; - swing: JQueryEasingFunction; -} - -/** - * Static members of jQuery (those on $ and jQuery themselves) - */ -interface JQueryStatic { - - /** - * Perform an asynchronous HTTP (Ajax) request. - * - * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). - */ - ajax(settings: JQueryAjaxSettings): JQueryXHR; - /** - * Perform an asynchronous HTTP (Ajax) request. - * - * @param url A string containing the URL to which the request is sent. - * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). - */ - ajax(url: string, settings?: JQueryAjaxSettings): JQueryXHR; - - /** - * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). - * - * @param dataTypes An optional string containing one or more space-separated dataTypes - * @param handler A handler to set default values for future Ajax requests. - */ - ajaxPrefilter(dataTypes: string, handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; - /** - * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). - * - * @param handler A handler to set default values for future Ajax requests. - */ - ajaxPrefilter(handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; - - ajaxSettings: JQueryAjaxSettings; - - /** - * Set default values for future Ajax requests. Its use is not recommended. - * - * @param options A set of key/value pairs that configure the default Ajax request. All options are optional. - */ - ajaxSetup(options: JQueryAjaxSettings): void; - - /** - * Load data from the server using a HTTP GET request. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). - */ - get(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; - /** - * Load data from the server using a HTTP GET request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). - */ - get(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; - /** - * Load data from the server using a HTTP GET request. - * - * @param settings The JQueryAjaxSettings to be used for the request - */ - get(settings : JQueryAjaxSettings): JQueryXHR; - /** - * Load JSON-encoded data from the server using a GET HTTP request. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. - */ - getJSON(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; - /** - * Load JSON-encoded data from the server using a GET HTTP request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. - */ - getJSON(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; - /** - * Load a JavaScript file from the server using a GET HTTP request, then execute it. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. - */ - getScript(url: string, success?: (script: string, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; - - /** - * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. - */ - param: JQueryParam; - - /** - * Load data from the server using a HTTP POST request. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - */ - post(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; - /** - * Load data from the server using a HTTP POST request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - */ - post(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; - /** - * Load data from the server using a HTTP POST request. - * - * @param settings The JQueryAjaxSettings to be used for the request - */ - post(settings : JQueryAjaxSettings): JQueryXHR; - /** - * A multi-purpose callbacks list object that provides a powerful way to manage callback lists. - * - * @param flags An optional list of space-separated flags that change how the callback list behaves. - */ - Callbacks(flags?: string): JQueryCallback; - - /** - * Holds or releases the execution of jQuery's ready event. - * - * @param hold Indicates whether the ready hold is being requested or released - */ - holdReady(hold: boolean): void; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param selector A string containing a selector expression - * @param context A DOM Element, Document, or jQuery to use as context - */ - (selector: string, context?: Element|JQuery): JQuery; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param element A DOM element to wrap in a jQuery object. - */ - (element: Element): JQuery; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param elementArray An array containing a set of DOM elements to wrap in a jQuery object. - */ - (elementArray: Element[]): JQuery; - - /** - * Binds a function to be executed when the DOM has finished loading. - * - * @param callback A function to execute after the DOM is ready. - */ - (callback: (jQueryAlias?: JQueryStatic) => any): JQuery; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param object A plain object to wrap in a jQuery object. - */ - (object: {}): JQuery; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param object An existing jQuery object to clone. - */ - (object: JQuery): JQuery; - - /** - * Specify a function to execute when the DOM is fully loaded. - */ - (): JQuery; - - /** - * Creates DOM elements on the fly from the provided string of raw HTML. - * - * @param html A string of HTML to create on the fly. Note that this parses HTML, not XML. - * @param ownerDocument A document in which the new elements will be created. - */ - (html: string, ownerDocument?: Document): JQuery; - - /** - * Creates DOM elements on the fly from the provided string of raw HTML. - * - * @param html A string defining a single, standalone, HTML element (e.g.
or
). - * @param attributes An object of attributes, events, and methods to call on the newly-created element. - */ - (html: string, attributes: Object): JQuery; - - /** - * Relinquish jQuery's control of the $ variable. - * - * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). - */ - noConflict(removeAll?: boolean): JQueryStatic; - - /** - * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. - * - * @param deferreds One or more Deferred objects, or plain JavaScript objects. - */ - when(...deferreds: Array/* as JQueryDeferred */>): JQueryPromise; - - /** - * Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties. - */ - cssHooks: { [key: string]: any; }; - cssNumber: any; - - /** - * Store arbitrary data associated with the specified element. Returns the value that was set. - * - * @param element The DOM element to associate with the data. - * @param key A string naming the piece of data to set. - * @param value The new data value. - */ - data(element: Element, key: string, value: T): T; - /** - * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. - * - * @param element The DOM element to associate with the data. - * @param key A string naming the piece of data to set. - */ - data(element: Element, key: string): any; - /** - * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. - * - * @param element The DOM element to associate with the data. - */ - data(element: Element): any; - - /** - * Execute the next function on the queue for the matched element. - * - * @param element A DOM element from which to remove and execute a queued function. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - dequeue(element: Element, queueName?: string): void; - - /** - * Determine whether an element has any jQuery data associated with it. - * - * @param element A DOM element to be checked for data. - */ - hasData(element: Element): boolean; - - /** - * Show the queue of functions to be executed on the matched element. - * - * @param element A DOM element to inspect for an attached queue. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - queue(element: Element, queueName?: string): any[]; - /** - * Manipulate the queue of functions to be executed on the matched element. - * - * @param element A DOM element where the array of queued functions is attached. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param newQueue An array of functions to replace the current queue contents. - */ - queue(element: Element, queueName: string, newQueue: Function[]): JQuery; - /** - * Manipulate the queue of functions to be executed on the matched element. - * - * @param element A DOM element on which to add a queued function. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param callback The new function to add to the queue. - */ - queue(element: Element, queueName: string, callback: Function): JQuery; - - /** - * Remove a previously-stored piece of data. - * - * @param element A DOM element from which to remove data. - * @param name A string naming the piece of data to remove. - */ - removeData(element: Element, name?: string): JQuery; - - /** - * A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. - * - * @param beforeStart A function that is called just before the constructor returns. - */ - Deferred(beforeStart?: (deferred: JQueryDeferred) => any): JQueryDeferred; - - /** - * Effects - */ - - easing: JQueryEasingFunctions; - - fx: { - tick: () => void; - /** - * The rate (in milliseconds) at which animations fire. - */ - interval: number; - stop: () => void; - speeds: { slow: number; fast: number; }; - /** - * Globally disable all animations. - */ - off: boolean; - step: any; - }; - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fnction The function whose context will be changed. - * @param context The object to which the context (this) of the function should be set. - * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. - */ - proxy(fnction: (...args: any[]) => any, context: Object, ...additionalArguments: any[]): any; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param context The object to which the context (this) of the function should be set. - * @param name The name of the function whose context will be changed (should be a property of the context object). - * @param additionalArguments Any number of arguments to be passed to the function named in the name argument. - */ - proxy(context: Object, name: string, ...additionalArguments: any[]): any; - - Event: JQueryEventConstructor; - - /** - * Takes a string and throws an exception containing it. - * - * @param message The message to send out. - */ - error(message: any): JQuery; - - expr: any; - fn: any; //TODO: Decide how we want to type this - - isReady: boolean; - - // Properties - support: JQuerySupport; - - /** - * Check to see if a DOM element is a descendant of another DOM element. - * - * @param container The DOM element that may contain the other element. - * @param contained The DOM element that may be contained by (a descendant of) the other element. - */ - contains(container: Element, contained: Element): boolean; - - /** - * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. - * - * @param collection The object or array to iterate over. - * @param callback The function that will be executed on every object. - */ - each( - collection: T[], - callback: (indexInArray: number, valueOfElement: T) => any - ): any; - - /** - * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. - * - * @param collection The object or array to iterate over. - * @param callback The function that will be executed on every object. - */ - each( - collection: any, - callback: (indexInArray: any, valueOfElement: any) => any - ): any; - - /** - * Merge the contents of two or more objects together into the first object. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument. - * @param object1 An object containing additional properties to merge in. - * @param objectN Additional objects containing properties to merge in. - */ - extend(target: any, object1?: any, ...objectN: any[]): any; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param deep If true, the merge becomes recursive (aka. deep copy). - * @param target The object to extend. It will receive the new properties. - * @param object1 An object containing additional properties to merge in. - * @param objectN Additional objects containing properties to merge in. - */ - extend(deep: boolean, target: any, object1?: any, ...objectN: any[]): any; - - /** - * Execute some JavaScript code globally. - * - * @param code The JavaScript code to execute. - */ - globalEval(code: string): any; - - /** - * Finds the elements of an array which satisfy a filter function. The original array is not affected. - * - * @param array The array to search through. - * @param func The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object. - * @param invert If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false. - */ - grep(array: T[], func: (elementOfArray?: T, indexInArray?: number) => boolean, invert?: boolean): T[]; - - /** - * Search for a specified value within an array and return its index (or -1 if not found). - * - * @param value The value to search for. - * @param array An array through which to search. - * @param fromIndex he index of the array at which to begin the search. The default is 0, which will search the whole array. - */ - inArray(value: T, array: T[], fromIndex?: number): number; - - /** - * Determine whether the argument is an array. - * - * @param obj Object to test whether or not it is an array. - */ - isArray(obj: any): boolean; - /** - * Check to see if an object is empty (contains no enumerable properties). - * - * @param obj The object that will be checked to see if it's empty. - */ - isEmptyObject(obj: any): boolean; - /** - * Determine if the argument passed is a Javascript function object. - * - * @param obj Object to test whether or not it is a function. - */ - isFunction(obj: any): boolean; - /** - * Determines whether its argument is a number. - * - * @param obj The value to be tested. - */ - isNumeric(value: any): boolean; - /** - * Check to see if an object is a plain object (created using "{}" or "new Object"). - * - * @param obj The object that will be checked to see if it's a plain object. - */ - isPlainObject(obj: any): boolean; - /** - * Determine whether the argument is a window. - * - * @param obj Object to test whether or not it is a window. - */ - isWindow(obj: any): boolean; - /** - * Check to see if a DOM node is within an XML document (or is an XML document). - * - * @param node he DOM node that will be checked to see if it's in an XML document. - */ - isXMLDoc(node: Node): boolean; - - /** - * Convert an array-like object into a true JavaScript array. - * - * @param obj Any object to turn into a native Array. - */ - makeArray(obj: any): any[]; - - /** - * Translate all items in an array or object to new array of items. - * - * @param array The Array to translate. - * @param callback The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object. - */ - map(array: T[], callback: (elementOfArray?: T, indexInArray?: number) => U): U[]; - /** - * Translate all items in an array or object to new array of items. - * - * @param arrayOrObject The Array or Object to translate. - * @param callback The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object. - */ - map(arrayOrObject: any, callback: (value?: any, indexOrKey?: any) => any): any; - - /** - * Merge the contents of two arrays together into the first array. - * - * @param first The first array to merge, the elements of second added. - * @param second The second array to merge into the first, unaltered. - */ - merge(first: T[], second: T[]): T[]; - - /** - * An empty function. - */ - noop(): any; - - /** - * Return a number representing the current time. - */ - now(): number; - - /** - * Takes a well-formed JSON string and returns the resulting JavaScript object. - * - * @param json The JSON string to parse. - */ - parseJSON(json: string): any; - - /** - * Parses a string into an XML document. - * - * @param data a well-formed XML string to be parsed - */ - parseXML(data: string): XMLDocument; - - /** - * Remove the whitespace from the beginning and end of a string. - * - * @param str Remove the whitespace from the beginning and end of a string. - */ - trim(str: string): string; - - /** - * Determine the internal JavaScript [[Class]] of an object. - * - * @param obj Object to get the internal JavaScript [[Class]] of. - */ - type(obj: any): string; - - /** - * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers. - * - * @param array The Array of DOM elements. - */ - unique(array: Element[]): Element[]; - - /** - * Parses a string into an array of DOM nodes. - * - * @param data HTML string to be parsed - * @param context DOM element to serve as the context in which the HTML fragment will be created - * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string - */ - parseHTML(data: string, context?: HTMLElement, keepScripts?: boolean): any[]; - - /** - * Parses a string into an array of DOM nodes. - * - * @param data HTML string to be parsed - * @param context DOM element to serve as the context in which the HTML fragment will be created - * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string - */ - parseHTML(data: string, context?: Document, keepScripts?: boolean): any[]; -} - -/** - * The jQuery instance members - */ -interface JQuery { - /** - * Register a handler to be called when Ajax requests complete. This is an AjaxEvent. - * - * @param handler The function to be invoked. - */ - ajaxComplete(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: any) => any): JQuery; - /** - * Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxError(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxSettings: JQueryAjaxSettings, thrownError: any) => any): JQuery; - /** - * Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxSend(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxOptions: JQueryAjaxSettings) => any): JQuery; - /** - * Register a handler to be called when the first Ajax request begins. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxStart(handler: () => any): JQuery; - /** - * Register a handler to be called when all Ajax requests have completed. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxStop(handler: () => any): JQuery; - /** - * Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxSuccess(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: JQueryAjaxSettings) => any): JQuery; - - /** - * Load data from the server and place the returned HTML into the matched element. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param complete A callback function that is executed when the request completes. - */ - load(url: string, data?: string|Object, complete?: (responseText: string, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any): JQuery; - - /** - * Encode a set of form elements as a string for submission. - */ - serialize(): string; - /** - * Encode a set of form elements as an array of names and values. - */ - serializeArray(): JQuerySerializeArrayElement[]; - - /** - * Adds the specified class(es) to each of the set of matched elements. - * - * @param className One or more space-separated classes to be added to the class attribute of each matched element. - */ - addClass(className: string): JQuery; - /** - * Adds the specified class(es) to each of the set of matched elements. - * - * @param function A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set. - */ - addClass(func: (index: number, className: string) => string): JQuery; - - /** - * Add the previous set of elements on the stack to the current set, optionally filtered by a selector. - */ - addBack(selector?: string): JQuery; - - /** - * Get the value of an attribute for the first element in the set of matched elements. - * - * @param attributeName The name of the attribute to get. - */ - attr(attributeName: string): string; - /** - * Set one or more attributes for the set of matched elements. - * - * @param attributeName The name of the attribute to set. - * @param value A value to set for the attribute. - */ - attr(attributeName: string, value: string|number): JQuery; - /** - * Set one or more attributes for the set of matched elements. - * - * @param attributeName The name of the attribute to set. - * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments. - */ - attr(attributeName: string, func: (index: number, attr: string) => string|number): JQuery; - /** - * Set one or more attributes for the set of matched elements. - * - * @param attributes An object of attribute-value pairs to set. - */ - attr(attributes: Object): JQuery; - - /** - * Determine whether any of the matched elements are assigned the given class. - * - * @param className The class name to search for. - */ - hasClass(className: string): boolean; - - /** - * Get the HTML contents of the first element in the set of matched elements. - */ - html(): string; - /** - * Set the HTML contents of each element in the set of matched elements. - * - * @param htmlString A string of HTML to set as the content of each matched element. - */ - html(htmlString: string): JQuery; - /** - * Set the HTML contents of each element in the set of matched elements. - * - * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. - */ - html(func: (index: number, oldhtml: string) => string): JQuery; - /** - * Set the HTML contents of each element in the set of matched elements. - * - * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. - */ - - /** - * Get the value of a property for the first element in the set of matched elements. - * - * @param propertyName The name of the property to get. - */ - prop(propertyName: string): any; - /** - * Set one or more properties for the set of matched elements. - * - * @param propertyName The name of the property to set. - * @param value A value to set for the property. - */ - prop(propertyName: string, value: string|number|boolean): JQuery; - /** - * Set one or more properties for the set of matched elements. - * - * @param properties An object of property-value pairs to set. - */ - prop(properties: Object): JQuery; - /** - * Set one or more properties for the set of matched elements. - * - * @param propertyName The name of the property to set. - * @param func A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element. - */ - prop(propertyName: string, func: (index: number, oldPropertyValue: any) => any): JQuery; - - /** - * Remove an attribute from each element in the set of matched elements. - * - * @param attributeName An attribute to remove; as of version 1.7, it can be a space-separated list of attributes. - */ - removeAttr(attributeName: string): JQuery; - - /** - * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. - * - * @param className One or more space-separated classes to be removed from the class attribute of each matched element. - */ - removeClass(className?: string): JQuery; - /** - * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. - * - * @param function A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments. - */ - removeClass(func: (index: number, className: string) => string): JQuery; - - /** - * Remove a property for the set of matched elements. - * - * @param propertyName The name of the property to remove. - */ - removeProp(propertyName: string): JQuery; - - /** - * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. - * - * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set. - * @param swtch A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed. - */ - toggleClass(className: string, swtch?: boolean): JQuery; - /** - * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. - * - * @param swtch A boolean value to determine whether the class should be added or removed. - */ - toggleClass(swtch?: boolean): JQuery; - /** - * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. - * - * @param func A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments. - * @param swtch A boolean value to determine whether the class should be added or removed. - */ - toggleClass(func: (index: number, className: string, swtch: boolean) => string, swtch?: boolean): JQuery; - - /** - * Get the current value of the first element in the set of matched elements. - */ - val(): any; - /** - * Set the value of each element in the set of matched elements. - * - * @param value A string of text, an array of strings or number corresponding to the value of each matched element to set as selected/checked. - */ - val(value: string|string[]|number): JQuery; - /** - * Set the value of each element in the set of matched elements. - * - * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. - */ - val(func: (index: number, value: string) => string): JQuery; - - - /** - * Get the value of style properties for the first element in the set of matched elements. - * - * @param propertyName A CSS property. - */ - css(propertyName: string): string; - /** - * Set one or more CSS properties for the set of matched elements. - * - * @param propertyName A CSS property name. - * @param value A value to set for the property. - */ - css(propertyName: string, value: string|number): JQuery; - /** - * Set one or more CSS properties for the set of matched elements. - * - * @param propertyName A CSS property name. - * @param value A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. - */ - css(propertyName: string, value: (index: number, value: string) => string|number): JQuery; - /** - * Set one or more CSS properties for the set of matched elements. - * - * @param properties An object of property-value pairs to set. - */ - css(properties: Object): JQuery; - - /** - * Get the current computed height for the first element in the set of matched elements. - */ - height(): number; - /** - * Set the CSS height of every matched element. - * - * @param value An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string). - */ - height(value: number|string): JQuery; - /** - * Set the CSS height of every matched element. - * - * @param func A function returning the height to set. Receives the index position of the element in the set and the old height as arguments. Within the function, this refers to the current element in the set. - */ - height(func: (index: number, height: number) => number|string): JQuery; - - /** - * Get the current computed height for the first element in the set of matched elements, including padding but not border. - */ - innerHeight(): number; - - /** - * Sets the inner height on elements in the set of matched elements, including padding but not border. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - innerHeight(height: number|string): JQuery; - - /** - * Get the current computed width for the first element in the set of matched elements, including padding but not border. - */ - innerWidth(): number; - - /** - * Sets the inner width on elements in the set of matched elements, including padding but not border. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - innerWidth(width: number|string): JQuery; - - /** - * Get the current coordinates of the first element in the set of matched elements, relative to the document. - */ - offset(): JQueryCoordinates; - /** - * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. - * - * @param coordinates An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. - */ - offset(coordinates: JQueryCoordinates): JQuery; - /** - * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. - * - * @param func A function to return the coordinates to set. Receives the index of the element in the collection as the first argument and the current coordinates as the second argument. The function should return an object with the new top and left properties. - */ - offset(func: (index: number, coords: JQueryCoordinates) => JQueryCoordinates): JQuery; - - /** - * Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns an integer (without "px") representation of the value or null if called on an empty set of elements. - * - * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. - */ - outerHeight(includeMargin?: boolean): number; - - /** - * Sets the outer height on elements in the set of matched elements, including padding and border. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - outerHeight(height: number|string): JQuery; - - /** - * Get the current computed width for the first element in the set of matched elements, including padding and border. - * - * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. - */ - outerWidth(includeMargin?: boolean): number; - - /** - * Sets the outer width on elements in the set of matched elements, including padding and border. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - outerWidth(width: number|string): JQuery; - - /** - * Get the current coordinates of the first element in the set of matched elements, relative to the offset parent. - */ - position(): JQueryCoordinates; - - /** - * Get the current horizontal position of the scroll bar for the first element in the set of matched elements or set the horizontal position of the scroll bar for every matched element. - */ - scrollLeft(): number; - /** - * Set the current horizontal position of the scroll bar for each of the set of matched elements. - * - * @param value An integer indicating the new position to set the scroll bar to. - */ - scrollLeft(value: number): JQuery; - - /** - * Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element. - */ - scrollTop(): number; - /** - * Set the current vertical position of the scroll bar for each of the set of matched elements. - * - * @param value An integer indicating the new position to set the scroll bar to. - */ - scrollTop(value: number): JQuery; - - /** - * Get the current computed width for the first element in the set of matched elements. - */ - width(): number; - /** - * Set the CSS width of each element in the set of matched elements. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - width(value: number|string): JQuery; - /** - * Set the CSS width of each element in the set of matched elements. - * - * @param func A function returning the width to set. Receives the index position of the element in the set and the old width as arguments. Within the function, this refers to the current element in the set. - */ - width(func: (index: number, width: number) => number|string): JQuery; - - /** - * Remove from the queue all items that have not yet been run. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - clearQueue(queueName?: string): JQuery; - - /** - * Store arbitrary data associated with the matched elements. - * - * @param key A string naming the piece of data to set. - * @param value The new data value; it can be any Javascript type including Array or Object. - */ - data(key: string, value: any): JQuery; - /** - * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. - * - * @param key Name of the data stored. - */ - data(key: string): any; - /** - * Store arbitrary data associated with the matched elements. - * - * @param obj An object of key-value pairs of data to update. - */ - data(obj: { [key: string]: any; }): JQuery; - /** - * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. - */ - data(): any; - - /** - * Execute the next function on the queue for the matched elements. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - dequeue(queueName?: string): JQuery; - - /** - * Remove a previously-stored piece of data. - * - * @param name A string naming the piece of data to delete or space-separated string naming the pieces of data to delete. - */ - removeData(name: string): JQuery; - /** - * Remove a previously-stored piece of data. - * - * @param list An array of strings naming the pieces of data to delete. - */ - removeData(list: string[]): JQuery; - /** - * Remove all previously-stored piece of data. - */ - removeData(): JQuery; - - /** - * Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished. - * - * @param type The type of queue that needs to be observed. (default: fx) - * @param target Object onto which the promise methods have to be attached - */ - promise(type?: string, target?: Object): JQueryPromise; - - /** - * Perform a custom animation of a set of CSS properties. - * - * @param properties An object of CSS properties and values that the animation will move toward. - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - animate(properties: Object, duration?: string|number, complete?: Function): JQuery; - /** - * Perform a custom animation of a set of CSS properties. - * - * @param properties An object of CSS properties and values that the animation will move toward. - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. (default: swing) - * @param complete A function to call once the animation is complete. - */ - animate(properties: Object, duration?: string|number, easing?: string, complete?: Function): JQuery; - /** - * Perform a custom animation of a set of CSS properties. - * - * @param properties An object of CSS properties and values that the animation will move toward. - * @param options A map of additional options to pass to the method. - */ - animate(properties: Object, options: JQueryAnimationOptions): JQuery; - - /** - * Set a timer to delay execution of subsequent items in the queue. - * - * @param duration An integer indicating the number of milliseconds to delay execution of the next item in the queue. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - delay(duration: number, queueName?: string): JQuery; - - /** - * Display the matched elements by fading them to opaque. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - fadeIn(duration?: number|string, complete?: Function): JQuery; - /** - * Display the matched elements by fading them to opaque. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - fadeIn(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Display the matched elements by fading them to opaque. - * - * @param options A map of additional options to pass to the method. - */ - fadeIn(options: JQueryAnimationOptions): JQuery; - - /** - * Hide the matched elements by fading them to transparent. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - fadeOut(duration?: number|string, complete?: Function): JQuery; - /** - * Hide the matched elements by fading them to transparent. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - fadeOut(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Hide the matched elements by fading them to transparent. - * - * @param options A map of additional options to pass to the method. - */ - fadeOut(options: JQueryAnimationOptions): JQuery; - - /** - * Adjust the opacity of the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param opacity A number between 0 and 1 denoting the target opacity. - * @param complete A function to call once the animation is complete. - */ - fadeTo(duration: string|number, opacity: number, complete?: Function): JQuery; - /** - * Adjust the opacity of the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param opacity A number between 0 and 1 denoting the target opacity. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - fadeTo(duration: string|number, opacity: number, easing?: string, complete?: Function): JQuery; - - /** - * Display or hide the matched elements by animating their opacity. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - fadeToggle(duration?: number|string, complete?: Function): JQuery; - /** - * Display or hide the matched elements by animating their opacity. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - fadeToggle(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Display or hide the matched elements by animating their opacity. - * - * @param options A map of additional options to pass to the method. - */ - fadeToggle(options: JQueryAnimationOptions): JQuery; - - /** - * Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements. - * - * @param queue The name of the queue in which to stop animations. - */ - finish(queue?: string): JQuery; - - /** - * Hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - hide(duration?: number|string, complete?: Function): JQuery; - /** - * Hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - hide(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Hide the matched elements. - * - * @param options A map of additional options to pass to the method. - */ - hide(options: JQueryAnimationOptions): JQuery; - - /** - * Display the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - show(duration?: number|string, complete?: Function): JQuery; - /** - * Display the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - show(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Display the matched elements. - * - * @param options A map of additional options to pass to the method. - */ - show(options: JQueryAnimationOptions): JQuery; - - /** - * Display the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - slideDown(duration?: number|string, complete?: Function): JQuery; - /** - * Display the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - slideDown(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Display the matched elements with a sliding motion. - * - * @param options A map of additional options to pass to the method. - */ - slideDown(options: JQueryAnimationOptions): JQuery; - - /** - * Display or hide the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - slideToggle(duration?: number|string, complete?: Function): JQuery; - /** - * Display or hide the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - slideToggle(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Display or hide the matched elements with a sliding motion. - * - * @param options A map of additional options to pass to the method. - */ - slideToggle(options: JQueryAnimationOptions): JQuery; - - /** - * Hide the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - slideUp(duration?: number|string, complete?: Function): JQuery; - /** - * Hide the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - slideUp(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Hide the matched elements with a sliding motion. - * - * @param options A map of additional options to pass to the method. - */ - slideUp(options: JQueryAnimationOptions): JQuery; - - /** - * Stop the currently-running animation on the matched elements. - * - * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. - * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. - */ - stop(clearQueue?: boolean, jumpToEnd?: boolean): JQuery; - /** - * Stop the currently-running animation on the matched elements. - * - * @param queue The name of the queue in which to stop animations. - * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. - * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. - */ - stop(queue?: string, clearQueue?: boolean, jumpToEnd?: boolean): JQuery; - - /** - * Display or hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - toggle(duration?: number|string, complete?: Function): JQuery; - /** - * Display or hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - toggle(duration?: number|string, easing?: string, complete?: Function): JQuery; - /** - * Display or hide the matched elements. - * - * @param options A map of additional options to pass to the method. - */ - toggle(options: JQueryAnimationOptions): JQuery; - /** - * Display or hide the matched elements. - * - * @param showOrHide A Boolean indicating whether to show or hide the elements. - */ - toggle(showOrHide: boolean): JQuery; - - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - bind(eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param handler A function to execute each time the event is triggered. - */ - bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param eventData An object containing data that will be passed to the event handler. - * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. - */ - bind(eventType: string, eventData: any, preventBubble: boolean): JQuery; - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. - */ - bind(eventType: string, preventBubble: boolean): JQuery; - /** - * Attach a handler to an event for the elements. - * - * @param events An object containing one or more DOM event types and functions to execute for them. - */ - bind(events: any): JQuery; - - /** - * Trigger the "blur" event on an element - */ - blur(): JQuery; - /** - * Bind an event handler to the "blur" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - blur(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "blur" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - blur(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "change" event on an element. - */ - change(): JQuery; - /** - * Bind an event handler to the "change" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - change(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "change" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - change(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "click" event on an element. - */ - click(): JQuery; - /** - * Bind an event handler to the "click" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - */ - click(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "click" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "contextmenu" event on an element. - */ - contextmenu(): JQuery; - /** - * Bind an event handler to the "contextmenu" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - contextmenu(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to the "contextmenu" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - contextmenu(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "dblclick" event on an element. - */ - dblclick(): JQuery; - /** - * Bind an event handler to the "dblclick" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - dblclick(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "dblclick" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - dblclick(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - delegate(selector: any, eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - delegate(selector: any, eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "focus" event on an element. - */ - focus(): JQuery; - /** - * Bind an event handler to the "focus" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - focus(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "focus" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - focus(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "focusin" event on an element. - */ - focusin(): JQuery; - /** - * Bind an event handler to the "focusin" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - focusin(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "focusin" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - focusin(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "focusout" event on an element. - */ - focusout(): JQuery; - /** - * Bind an event handler to the "focusout" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - focusout(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "focusout" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - focusout(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. - * - * @param handlerIn A function to execute when the mouse pointer enters the element. - * @param handlerOut A function to execute when the mouse pointer leaves the element. - */ - hover(handlerIn: (eventObject: JQueryEventObject) => any, handlerOut: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. - * - * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. - */ - hover(handlerInOut: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "keydown" event on an element. - */ - keydown(): JQuery; - /** - * Bind an event handler to the "keydown" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - keydown(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; - /** - * Bind an event handler to the "keydown" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - keydown(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; - - /** - * Trigger the "keypress" event on an element. - */ - keypress(): JQuery; - /** - * Bind an event handler to the "keypress" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - keypress(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; - /** - * Bind an event handler to the "keypress" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - keypress(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; - - /** - * Trigger the "keyup" event on an element. - */ - keyup(): JQuery; - /** - * Bind an event handler to the "keyup" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - keyup(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; - /** - * Bind an event handler to the "keyup" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - keyup(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; - - /** - * Bind an event handler to the "load" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - load(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "load" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - load(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "mousedown" event on an element. - */ - mousedown(): JQuery; - /** - * Bind an event handler to the "mousedown" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mousedown(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to the "mousedown" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mousedown(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "mouseenter" event on an element. - */ - mouseenter(): JQuery; - /** - * Bind an event handler to be fired when the mouse enters an element. - * - * @param handler A function to execute when the event is triggered. - */ - mouseenter(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to be fired when the mouse enters an element. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseenter(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "mouseleave" event on an element. - */ - mouseleave(): JQuery; - /** - * Bind an event handler to be fired when the mouse leaves an element. - * - * @param handler A function to execute when the event is triggered. - */ - mouseleave(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to be fired when the mouse leaves an element. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseleave(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "mousemove" event on an element. - */ - mousemove(): JQuery; - /** - * Bind an event handler to the "mousemove" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mousemove(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to the "mousemove" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mousemove(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "mouseout" event on an element. - */ - mouseout(): JQuery; - /** - * Bind an event handler to the "mouseout" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mouseout(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to the "mouseout" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseout(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "mouseover" event on an element. - */ - mouseover(): JQuery; - /** - * Bind an event handler to the "mouseover" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mouseover(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to the "mouseover" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseover(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Trigger the "mouseup" event on an element. - */ - mouseup(): JQuery; - /** - * Bind an event handler to the "mouseup" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mouseup(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - /** - * Bind an event handler to the "mouseup" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseup(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; - - /** - * Remove an event handler. - */ - off(): JQuery; - /** - * Remove an event handler. - * - * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". - * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: string, selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Remove an event handler. - * - * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". - * @param handler A handler function previously attached for the event(s), or the special value false. Takes handler with extra args that can be attached with on(). - */ - off(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - /** - * Remove an event handler. - * - * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Remove an event handler. - * - * @param events An object where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s). - * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. - */ - off(events: { [key: string]: any; }, selector?: string): JQuery; - - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: string, data : any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: string, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). - * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event occurs. - */ - on(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). - * @param data Data to be passed to the handler in event.data when an event occurs. - */ - on(events: { [key: string]: any; }, data?: any): JQuery; - - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. - * @param handler A function to execute at the time the event is triggered. - */ - one(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. - * @param data An object containing data that will be passed to the event handler. - * @param handler A function to execute at the time the event is triggered. - */ - one(events: string, data: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - one(events: string, selector: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - one(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). - * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event occurs. - */ - one(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; - - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). - * @param data Data to be passed to the handler in event.data when an event occurs. - */ - one(events: { [key: string]: any; }, data?: any): JQuery; - - - /** - * Specify a function to execute when the DOM is fully loaded. - * - * @param handler A function to execute after the DOM is ready. - */ - ready(handler: (jQueryAlias?: JQueryStatic) => any): JQuery; - - /** - * Trigger the "resize" event on an element. - */ - resize(): JQuery; - /** - * Bind an event handler to the "resize" JavaScript event. - * - * @param handler A function to execute each time the event is triggered. - */ - resize(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "resize" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - resize(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "scroll" event on an element. - */ - scroll(): JQuery; - /** - * Bind an event handler to the "scroll" JavaScript event. - * - * @param handler A function to execute each time the event is triggered. - */ - scroll(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "scroll" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - scroll(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "select" event on an element. - */ - select(): JQuery; - /** - * Bind an event handler to the "select" JavaScript event. - * - * @param handler A function to execute each time the event is triggered. - */ - select(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "select" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - select(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Trigger the "submit" event on an element. - */ - submit(): JQuery; - /** - * Bind an event handler to the "submit" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - submit(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "submit" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - submit(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Execute all handlers and behaviors attached to the matched elements for the given event type. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param extraParameters Additional parameters to pass along to the event handler. - */ - trigger(eventType: string, extraParameters?: any[]|Object): JQuery; - /** - * Execute all handlers and behaviors attached to the matched elements for the given event type. - * - * @param event A jQuery.Event object. - * @param extraParameters Additional parameters to pass along to the event handler. - */ - trigger(event: JQueryEventObject, extraParameters?: any[]|Object): JQuery; - - /** - * Execute all handlers attached to an element for an event. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param extraParameters An array of additional parameters to pass along to the event handler. - */ - triggerHandler(eventType: string, ...extraParameters: any[]): Object; - - /** - * Execute all handlers attached to an element for an event. - * - * @param event A jQuery.Event object. - * @param extraParameters An array of additional parameters to pass along to the event handler. - */ - triggerHandler(event: JQueryEventObject, ...extraParameters: any[]): Object; - - /** - * Remove a previously-attached event handler from the elements. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param handler The function that is to be no longer executed. - */ - unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Remove a previously-attached event handler from the elements. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ). - */ - unbind(eventType: string, fls: boolean): JQuery; - /** - * Remove a previously-attached event handler from the elements. - * - * @param evt A JavaScript event object as passed to an event handler. - */ - unbind(evt: any): JQuery; - - /** - * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - */ - undelegate(): JQuery; - /** - * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * - * @param selector A selector which will be used to filter the event results. - * @param eventType A string containing a JavaScript event type, such as "click" or "keydown" - * @param handler A function to execute at the time the event is triggered. - */ - undelegate(selector: string, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * - * @param selector A selector which will be used to filter the event results. - * @param events An object of one or more event types and previously bound functions to unbind from them. - */ - undelegate(selector: string, events: Object): JQuery; - /** - * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * - * @param namespace A string containing a namespace to unbind all events from. - */ - undelegate(namespace: string): JQuery; - - /** - * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) - * - * @param handler A function to execute when the event is triggered. - */ - unload(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) - * - * @param eventData A plain object of data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - unload(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document. (DEPRECATED from v1.10) - */ - context: Element; - - jquery: string; - - /** - * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) - * - * @param handler A function to execute when the event is triggered. - */ - error(handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) - * - * @param eventData A plain object of data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - error(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Add a collection of DOM elements onto the jQuery stack. - * - * @param elements An array of elements to push onto the stack and make into a new jQuery object. - */ - pushStack(elements: any[]): JQuery; - /** - * Add a collection of DOM elements onto the jQuery stack. - * - * @param elements An array of elements to push onto the stack and make into a new jQuery object. - * @param name The name of a jQuery method that generated the array of elements. - * @param arguments The arguments that were passed in to the jQuery method (for serialization). - */ - pushStack(elements: any[], name: string, arguments: any[]): JQuery; - - /** - * Insert content, specified by the parameter, after each element in the set of matched elements. - * - * param content1 HTML string, DOM element, DocumentFragment, array of elements, or jQuery object to insert after each element in the set of matched elements. - * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements. - */ - after(content1: JQuery|any[]|Element|DocumentFragment|Text|string, ...content2: any[]): JQuery; - /** - * Insert content, specified by the parameter, after each element in the set of matched elements. - * - * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. - */ - after(func: (index: number, html: string) => string|Element|JQuery): JQuery; - - /** - * Insert content, specified by the parameter, to the end of each element in the set of matched elements. - * - * param content1 DOM element, DocumentFragment, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. - * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. - */ - append(content1: JQuery|any[]|Element|DocumentFragment|Text|string, ...content2: any[]): JQuery; - /** - * Insert content, specified by the parameter, to the end of each element in the set of matched elements. - * - * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. - */ - append(func: (index: number, html: string) => string|Element|JQuery): JQuery; - - /** - * Insert every element in the set of matched elements to the end of the target. - * - * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. - */ - appendTo(target: JQuery|any[]|Element|string): JQuery; - - /** - * Insert content, specified by the parameter, before each element in the set of matched elements. - * - * param content1 HTML string, DOM element, DocumentFragment, array of elements, or jQuery object to insert before each element in the set of matched elements. - * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. - */ - before(content1: JQuery|any[]|Element|DocumentFragment|Text|string, ...content2: any[]): JQuery; - /** - * Insert content, specified by the parameter, before each element in the set of matched elements. - * - * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. - */ - before(func: (index: number, html: string) => string|Element|JQuery): JQuery; - - /** - * Create a deep copy of the set of matched elements. - * - * param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. - * param deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false). - */ - clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): JQuery; - - /** - * Remove the set of matched elements from the DOM. - * - * param selector A selector expression that filters the set of matched elements to be removed. - */ - detach(selector?: string): JQuery; - - /** - * Remove all child nodes of the set of matched elements from the DOM. - */ - empty(): JQuery; - - /** - * Insert every element in the set of matched elements after the target. - * - * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. - */ - insertAfter(target: JQuery|any[]|Element|Text|string): JQuery; - - /** - * Insert every element in the set of matched elements before the target. - * - * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. - */ - insertBefore(target: JQuery|any[]|Element|Text|string): JQuery; - - /** - * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. - * - * param content1 DOM element, DocumentFragment, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements. - * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements. - */ - prepend(content1: JQuery|any[]|Element|DocumentFragment|Text|string, ...content2: any[]): JQuery; - /** - * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. - * - * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. - */ - prepend(func: (index: number, html: string) => string|Element|JQuery): JQuery; - - /** - * Insert every element in the set of matched elements to the beginning of the target. - * - * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter. - */ - prependTo(target: JQuery|any[]|Element|string): JQuery; - - /** - * Remove the set of matched elements from the DOM. - * - * @param selector A selector expression that filters the set of matched elements to be removed. - */ - remove(selector?: string): JQuery; - - /** - * Replace each target element with the set of matched elements. - * - * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. - */ - replaceAll(target: JQuery|any[]|Element|string): JQuery; - - /** - * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. - * - * param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. - */ - replaceWith(newContent: JQuery|any[]|Element|Text|string): JQuery; - /** - * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. - * - * param func A function that returns content with which to replace the set of matched elements. - */ - replaceWith(func: () => Element|JQuery): JQuery; - - /** - * Get the combined text contents of each element in the set of matched elements, including their descendants. - */ - text(): string; - /** - * Set the content of each element in the set of matched elements to the specified text. - * - * @param text The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation. - */ - text(text: string|number|boolean): JQuery; - /** - * Set the content of each element in the set of matched elements to the specified text. - * - * @param func A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments. - */ - text(func: (index: number, text: string) => string): JQuery; - - /** - * Retrieve all the elements contained in the jQuery set, as an array. - */ - toArray(): any[]; - - /** - * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. - */ - unwrap(): JQuery; - - /** - * Wrap an HTML structure around each element in the set of matched elements. - * - * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. - */ - wrap(wrappingElement: JQuery|Element|string): JQuery; - /** - * Wrap an HTML structure around each element in the set of matched elements. - * - * @param func A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. - */ - wrap(func: (index: number) => string|JQuery): JQuery; - - /** - * Wrap an HTML structure around all elements in the set of matched elements. - * - * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. - */ - wrapAll(wrappingElement: JQuery|Element|string): JQuery; - wrapAll(func: (index: number) => string): JQuery; - - /** - * Wrap an HTML structure around the content of each element in the set of matched elements. - * - * @param wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements. - */ - wrapInner(wrappingElement: JQuery|Element|string): JQuery; - /** - * Wrap an HTML structure around the content of each element in the set of matched elements. - * - * @param func A callback function which generates a structure to wrap around the content of the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. - */ - wrapInner(func: (index: number) => string): JQuery; - - /** - * Iterate over a jQuery object, executing a function for each matched element. - * - * @param func A function to execute for each matched element. - */ - each(func: (index: number, elem: Element) => any): JQuery; - - /** - * Retrieve one of the elements matched by the jQuery object. - * - * @param index A zero-based integer indicating which element to retrieve. - */ - get(index: number): HTMLElement; - /** - * Retrieve the elements matched by the jQuery object. - */ - get(): any[]; - - /** - * Search for a given element from among the matched elements. - */ - index(): number; - /** - * Search for a given element from among the matched elements. - * - * @param selector A selector representing a jQuery collection in which to look for an element. - */ - index(selector: string|JQuery|Element): number; - - /** - * The number of elements in the jQuery object. - */ - length: number; - /** - * A selector representing selector passed to jQuery(), if any, when creating the original set. - * version deprecated: 1.7, removed: 1.9 - */ - selector: string; - [index: string]: any; - [index: number]: HTMLElement; - - /** - * Add elements to the set of matched elements. - * - * @param selector A string representing a selector expression to find additional elements to add to the set of matched elements. - * @param context The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method. - */ - add(selector: string, context?: Element): JQuery; - /** - * Add elements to the set of matched elements. - * - * @param elements One or more elements to add to the set of matched elements. - */ - add(...elements: Element[]): JQuery; - /** - * Add elements to the set of matched elements. - * - * @param html An HTML fragment to add to the set of matched elements. - */ - add(html: string): JQuery; - /** - * Add elements to the set of matched elements. - * - * @param obj An existing jQuery object to add to the set of matched elements. - */ - add(obj: JQuery): JQuery; - - /** - * Get the children of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - children(selector?: string): JQuery; - - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * - * @param selector A string containing a selector expression to match elements against. - */ - closest(selector: string): JQuery; - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * - * @param selector A string containing a selector expression to match elements against. - * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. - */ - closest(selector: string, context?: Element): JQuery; - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * - * @param obj A jQuery object to match elements against. - */ - closest(obj: JQuery): JQuery; - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * - * @param element An element to match elements against. - */ - closest(element: Element): JQuery; - - /** - * Get an array of all the elements and selectors matched against the current element up through the DOM tree. - * - * @param selectors An array or string containing a selector expression to match elements against (can also be a jQuery object). - * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. - */ - closest(selectors: any, context?: Element): any[]; - - /** - * Get the children of each element in the set of matched elements, including text and comment nodes. - */ - contents(): JQuery; - - /** - * End the most recent filtering operation in the current chain and return the set of matched elements to its previous state. - */ - end(): JQuery; - - /** - * Reduce the set of matched elements to the one at the specified index. - * - * @param index An integer indicating the 0-based position of the element. OR An integer indicating the position of the element, counting backwards from the last element in the set. - * - */ - eq(index: number): JQuery; - - /** - * Reduce the set of matched elements to those that match the selector or pass the function's test. - * - * @param selector A string containing a selector expression to match the current set of elements against. - */ - filter(selector: string): JQuery; - /** - * Reduce the set of matched elements to those that match the selector or pass the function's test. - * - * @param func A function used as a test for each element in the set. this is the current DOM element. - */ - filter(func: (index: number, element: Element) => any): JQuery; - /** - * Reduce the set of matched elements to those that match the selector or pass the function's test. - * - * @param element An element to match the current set of elements against. - */ - filter(element: Element): JQuery; - /** - * Reduce the set of matched elements to those that match the selector or pass the function's test. - * - * @param obj An existing jQuery object to match the current set of elements against. - */ - filter(obj: JQuery): JQuery; - - /** - * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - * - * @param selector A string containing a selector expression to match elements against. - */ - find(selector: string): JQuery; - /** - * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - * - * @param element An element to match elements against. - */ - find(element: Element): JQuery; - /** - * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - * - * @param obj A jQuery object to match elements against. - */ - find(obj: JQuery): JQuery; - - /** - * Reduce the set of matched elements to the first in the set. - */ - first(): JQuery; - - /** - * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. - * - * @param selector A string containing a selector expression to match elements against. - */ - has(selector: string): JQuery; - /** - * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. - * - * @param contained A DOM element to match elements against. - */ - has(contained: Element): JQuery; - - /** - * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * - * @param selector A string containing a selector expression to match elements against. - */ - is(selector: string): boolean; - /** - * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * - * @param func A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element. - */ - is(func: (index: number, element: Element) => boolean): boolean; - /** - * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * - * @param obj An existing jQuery object to match the current set of elements against. - */ - is(obj: JQuery): boolean; - /** - * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * - * @param elements One or more elements to match the current set of elements against. - */ - is(elements: any): boolean; - - /** - * Reduce the set of matched elements to the final one in the set. - */ - last(): JQuery; - - /** - * Pass each element in the current matched set through a function, producing a new jQuery object containing the return values. - * - * @param callback A function object that will be invoked for each element in the current set. - */ - map(callback: (index: number, domElement: Element) => any): JQuery; - - /** - * Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - next(selector?: string): JQuery; - - /** - * Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - nextAll(selector?: string): JQuery; - - /** - * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - * - * @param selector A string containing a selector expression to indicate where to stop matching following sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - nextUntil(selector?: string, filter?: string): JQuery; - /** - * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - * - * @param element A DOM node or jQuery object indicating where to stop matching following sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - nextUntil(element?: Element, filter?: string): JQuery; - /** - * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - * - * @param obj A DOM node or jQuery object indicating where to stop matching following sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - nextUntil(obj?: JQuery, filter?: string): JQuery; - - /** - * Remove elements from the set of matched elements. - * - * @param selector A string containing a selector expression to match elements against. - */ - not(selector: string): JQuery; - /** - * Remove elements from the set of matched elements. - * - * @param func A function used as a test for each element in the set. this is the current DOM element. - */ - not(func: (index: number, element: Element) => boolean): JQuery; - /** - * Remove elements from the set of matched elements. - * - * @param elements One or more DOM elements to remove from the matched set. - */ - not(elements: Element|Element[]): JQuery; - /** - * Remove elements from the set of matched elements. - * - * @param obj An existing jQuery object to match the current set of elements against. - */ - not(obj: JQuery): JQuery; - - /** - * Get the closest ancestor element that is positioned. - */ - offsetParent(): JQuery; - - /** - * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - parent(selector?: string): JQuery; - - /** - * Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - parents(selector?: string): JQuery; - - /** - * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param selector A string containing a selector expression to indicate where to stop matching ancestor elements. - * @param filter A string containing a selector expression to match elements against. - */ - parentsUntil(selector?: string, filter?: string): JQuery; - /** - * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param element A DOM node or jQuery object indicating where to stop matching ancestor elements. - * @param filter A string containing a selector expression to match elements against. - */ - parentsUntil(element?: Element, filter?: string): JQuery; - /** - * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param obj A DOM node or jQuery object indicating where to stop matching ancestor elements. - * @param filter A string containing a selector expression to match elements against. - */ - parentsUntil(obj?: JQuery, filter?: string): JQuery; - - /** - * Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - prev(selector?: string): JQuery; - - /** - * Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - prevAll(selector?: string): JQuery; - - /** - * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param selector A string containing a selector expression to indicate where to stop matching preceding sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - prevUntil(selector?: string, filter?: string): JQuery; - /** - * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param element A DOM node or jQuery object indicating where to stop matching preceding sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - prevUntil(element?: Element, filter?: string): JQuery; - /** - * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param obj A DOM node or jQuery object indicating where to stop matching preceding sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - prevUntil(obj?: JQuery, filter?: string): JQuery; - - /** - * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - siblings(selector?: string): JQuery; - - /** - * Reduce the set of matched elements to a subset specified by a range of indices. - * - * @param start An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set. - * @param end An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set. - */ - slice(start: number, end?: number): JQuery; - - /** - * Show the queue of functions to be executed on the matched elements. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - queue(queueName?: string): any[]; - /** - * Manipulate the queue of functions to be executed, once for each matched element. - * - * @param newQueue An array of functions to replace the current queue contents. - */ - queue(newQueue: Function[]): JQuery; - /** - * Manipulate the queue of functions to be executed, once for each matched element. - * - * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. - */ - queue(callback: Function): JQuery; - /** - * Manipulate the queue of functions to be executed, once for each matched element. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param newQueue An array of functions to replace the current queue contents. - */ - queue(queueName: string, newQueue: Function[]): JQuery; - /** - * Manipulate the queue of functions to be executed, once for each matched element. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. - */ - queue(queueName: string, callback: Function): JQuery; -} -declare module "jquery" { - export = $; -} -declare var jQuery: JQueryStatic; -declare var $: JQueryStatic; \ No newline at end of file diff --git a/typings/globals/jquery/typings.json b/typings/globals/jquery/typings.json deleted file mode 100644 index d9d4608..0000000 --- a/typings/globals/jquery/typings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "resolution": "main", - "tree": { - "src": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/6e54cb627506cf64d6effba1fe49b5a091ac4297/jquery/jquery.d.ts", - "raw": "registry:dt/jquery#1.10.0+20160704162008", - "typings": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/6e54cb627506cf64d6effba1fe49b5a091ac4297/jquery/jquery.d.ts" - } -} diff --git a/typings/globals/underscore/index.d.ts b/typings/globals/underscore/index.d.ts deleted file mode 100644 index 033c66c..0000000 --- a/typings/globals/underscore/index.d.ts +++ /dev/null @@ -1,5930 +0,0 @@ -// Generated by typings -// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/3c935c7abcfc1f896b1670cd229f71e9c5ad9187/underscore/underscore.d.ts -declare module _ { - /** - * underscore.js _.throttle options. - **/ - interface ThrottleSettings { - - /** - * If you'd like to disable the leading-edge call, pass this as false. - **/ - leading?: boolean; - - /** - * If you'd like to disable the execution on the trailing-edge, pass false. - **/ - trailing?: boolean; - } - - /** - * underscore.js template settings, set templateSettings or pass as an argument - * to 'template()' to override defaults. - **/ - interface TemplateSettings { - /** - * Default value is '/<%([\s\S]+?)%>/g'. - **/ - evaluate?: RegExp; - - /** - * Default value is '/<%=([\s\S]+?)%>/g'. - **/ - interpolate?: RegExp; - - /** - * Default value is '/<%-([\s\S]+?)%>/g'. - **/ - escape?: RegExp; - - /** - * By default, 'template()' places the values from your data in the local scope via the 'with' statement. - * However, you can specify a single variable name with this setting. - **/ - variable?: string; - } - - interface Collection { } - - // Common interface between Arrays and jQuery objects - interface List extends Collection { - [index: number]: T; - length: number; - } - - interface Dictionary extends Collection { - [index: string]: T; - } - - interface ListIterator { - (value: T, index: number, list: List): TResult; - } - - interface ObjectIterator { - (element: T, key: string, list: Dictionary): TResult; - } - - interface MemoIterator { - (prev: TResult, curr: T, index: number, list: List): TResult; - } - - interface MemoObjectIterator { - (prev: TResult, curr: T, key: string, list: Dictionary): TResult; - } -} - -interface UnderscoreStatic { - /** - * Underscore OOP Wrapper, all Underscore functions that take an object - * as the first parameter can be invoked through this function. - * @param key First argument to Underscore object functions. - **/ - (value: _.Dictionary): Underscore; - (value: Array): Underscore; - (value: T): Underscore; - - /* ************* - * Collections * - ************* */ - - /** - * Iterates over a list of elements, yielding each in turn to an iterator function. The iterator is - * bound to the context object, if one is passed. Each invocation of iterator is called with three - * arguments: (element, index, list). If list is a JavaScript object, iterator's arguments will be - * (value, key, object). Delegates to the native forEach function if it exists. - * @param list Iterates over this list of elements. - * @param iterator Iterator function for each element `list`. - * @param context 'this' object in `iterator`, optional. - **/ - each( - list: _.List, - iterator: _.ListIterator, - context?: any): _.List; - - /** - * @see _.each - * @param object Iterates over properties of this object. - * @param iterator Iterator function for each property on `object`. - * @param context 'this' object in `iterator`, optional. - **/ - each( - object: _.Dictionary, - iterator: _.ObjectIterator, - context?: any): _.Dictionary; - - /** - * @see _.each - **/ - forEach( - list: _.List, - iterator: _.ListIterator, - context?: any): _.List; - - /** - * @see _.each - **/ - forEach( - object: _.Dictionary, - iterator: _.ObjectIterator, - context?: any): _.Dictionary; - - /** - * Produces a new array of values by mapping each value in list through a transformation function - * (iterator). If the native map method exists, it will be used instead. If list is a JavaScript - * object, iterator's arguments will be (value, key, object). - * @param list Maps the elements of this array. - * @param iterator Map iterator function for each element in `list`. - * @param context `this` object in `iterator`, optional. - * @return The mapped array result. - **/ - map( - list: _.List, - iterator: _.ListIterator, - context?: any): TResult[]; - - /** - * @see _.map - * @param object Maps the properties of this object. - * @param iterator Map iterator function for each property on `object`. - * @param context `this` object in `iterator`, optional. - * @return The mapped object result. - **/ - map( - object: _.Dictionary, - iterator: _.ObjectIterator, - context?: any): TResult[]; - - /** - * @see _.map - **/ - collect( - list: _.List, - iterator: _.ListIterator, - context?: any): TResult[]; - - /** - * @see _.map - **/ - collect( - object: _.Dictionary, - iterator: _.ObjectIterator, - context?: any): TResult[]; - - /** - * Also known as inject and foldl, reduce boils down a list of values into a single value. - * Memo is the initial state of the reduction, and each successive step of it should be - * returned by iterator. The iterator is passed four arguments: the memo, then the value - * and index (or key) of the iteration, and finally a reference to the entire list. - * @param list Reduces the elements of this array. - * @param iterator Reduce iterator function for each element in `list`. - * @param memo Initial reduce state. - * @param context `this` object in `iterator`, optional. - * @return Reduced object result. - **/ - reduce( - list: _.Collection, - iterator: _.MemoIterator, - memo?: TResult, - context?: any): TResult; - - reduce( - list: _.Dictionary, - iterator: _.MemoObjectIterator, - memo?: TResult, - context?: any): TResult; - - /** - * @see _.reduce - **/ - inject( - list: _.Collection, - iterator: _.MemoIterator, - memo?: TResult, - context?: any): TResult; - - /** - * @see _.reduce - **/ - foldl( - list: _.Collection, - iterator: _.MemoIterator, - memo?: TResult, - context?: any): TResult; - - /** - * The right-associative version of reduce. Delegates to the JavaScript 1.8 version of - * reduceRight, if it exists. `foldr` is not as useful in JavaScript as it would be in a - * language with lazy evaluation. - * @param list Reduces the elements of this array. - * @param iterator Reduce iterator function for each element in `list`. - * @param memo Initial reduce state. - * @param context `this` object in `iterator`, optional. - * @return Reduced object result. - **/ - reduceRight( - list: _.Collection, - iterator: _.MemoIterator, - memo?: TResult, - context?: any): TResult; - - /** - * @see _.reduceRight - **/ - foldr( - list: _.Collection, - iterator: _.MemoIterator, - memo?: TResult, - context?: any): TResult; - - /** - * Looks through each value in the list, returning the first one that passes a truth - * test (iterator). The function returns as soon as it finds an acceptable element, - * and doesn't traverse the entire list. - * @param list Searches for a value in this list. - * @param iterator Search iterator function for each element in `list`. - * @param context `this` object in `iterator`, optional. - * @return The first acceptable found element in `list`, if nothing is found undefined/null is returned. - **/ - find( - list: _.List, - iterator: _.ListIterator, - context?: any): T; - - /** - * @see _.find - **/ - find( - object: _.Dictionary, - iterator: _.ObjectIterator, - context?: any): T; - - /** - * @see _.find - **/ - find( - object: _.List|_.Dictionary, - iterator: U): T; - - /** - * @see _.find - **/ - find( - object: _.List|_.Dictionary, - iterator: string): T; - - /** - * @see _.find - **/ - detect( - list: _.List, - iterator: _.ListIterator, - context?: any): T; - - /** - * @see _.find - **/ - detect( - object: _.Dictionary, - iterator: _.ObjectIterator, - context?: any): T; - - /** - * @see _.find - **/ - detect( - object: _.List|_.Dictionary, - iterator: U): T; - - /** - * @see _.find - **/ - detect( - object: _.List|_.Dictionary, - iterator: string): T; - - /** - * Looks through each value in the list, returning an array of all the values that pass a truth - * test (iterator). Delegates to the native filter method, if it exists. - * @param list Filter elements out of this list. - * @param iterator Filter iterator function for each element in `list`. - * @param context `this` object in `iterator`, optional. - * @return The filtered list of elements. - **/ - filter( - list: _.List, - iterator: _.ListIterator, - context?: any): T[]; - - /** - * @see _.filter - **/ - filter( - object: _.Dictionary, - iterator: _.ObjectIterator, - context?: any): T[]; - - /** - * @see _.filter - **/ - select( - list: _.List, - iterator: _.ListIterator, - context?: any): T[]; - - /** - * @see _.filter - **/ - select( - object: _.Dictionary, - iterator: _.ObjectIterator, - context?: any): T[]; - - /** - * Looks through each value in the list, returning an array of all the values that contain all - * of the key-value pairs listed in properties. - * @param list List to match elements again `properties`. - * @param properties The properties to check for on each element within `list`. - * @return The elements within `list` that contain the required `properties`. - **/ - where( - list: _.List, - properties: U): T[]; - - /** - * Looks through the list and returns the first value that matches all of the key-value pairs listed in properties. - * @param list Search through this list's elements for the first object with all `properties`. - * @param properties Properties to look for on the elements within `list`. - * @return The first element in `list` that has all `properties`. - **/ - findWhere( - list: _.List, - properties: U): T; - - /** - * Returns the values in list without the elements that the truth test (iterator) passes. - * The opposite of filter. - * Return all the elements for which a truth test fails. - * @param list Reject elements within this list. - * @param iterator Reject iterator function for each element in `list`. - * @param context `this` object in `iterator`, optional. - * @return The rejected list of elements. - **/ - reject( - list: _.List, - iterator: _.ListIterator, - context?: any): T[]; - - /** - * @see _.reject - **/ - reject( - object: _.Dictionary, - iterator: _.ObjectIterator, - context?: any): T[]; - - /** - * Returns true if all of the values in the list pass the iterator truth test. Delegates to the - * native method every, if present. - * @param list Truth test against all elements within this list. - * @param iterator Trust test iterator function for each element in `list`. - * @param context `this` object in `iterator`, optional. - * @return True if all elements passed the truth test, otherwise false. - **/ - every( - list: _.List, - iterator?: _.ListIterator, - context?: any): boolean; - - /** - * @see _.every - **/ - every( - list: _.Dictionary, - iterator?: _.ObjectIterator, - context?: any): boolean; - - /** - * @see _.every - **/ - all( - list: _.List, - iterator?: _.ListIterator, - context?: any): boolean; - - /** - * @see _.every - **/ - all( - list: _.Dictionary, - iterator?: _.ObjectIterator, - context?: any): boolean; - - /** - * Returns true if any of the values in the list pass the iterator truth test. Short-circuits and - * stops traversing the list if a true element is found. Delegates to the native method some, if present. - * @param list Truth test against all elements within this list. - * @param iterator Trust test iterator function for each element in `list`. - * @param context `this` object in `iterator`, optional. - * @return True if any elements passed the truth test, otherwise false. - **/ - some( - list: _.List, - iterator?: _.ListIterator, - context?: any): boolean; - - /** - * @see _.some - **/ - some( - object: _.Dictionary, - iterator?: _.ObjectIterator, - context?: any): boolean; - - /** - * @see _.some - **/ - any( - list: _.List, - iterator?: _.ListIterator, - context?: any): boolean; - - /** - * @see _.some - **/ - any( - object: _.Dictionary, - iterator?: _.ObjectIterator, - context?: any): boolean; - - any( - list: _.List, - value: T): boolean; - - /** - * Returns true if the value is present in the list. Uses indexOf internally, - * if list is an Array. - * @param list Checks each element to see if `value` is present. - * @param value The value to check for within `list`. - * @return True if `value` is present in `list`, otherwise false. - **/ - contains( - list: _.List, - value: T): boolean; - - /** - * @see _.contains - **/ - contains( - object: _.Dictionary, - value: T): boolean; - - /** - * @see _.contains - **/ - include( - list: _.Collection, - value: T): boolean; - - /** - * @see _.contains - **/ - include( - object: _.Dictionary, - value: T): boolean; - - /** - * Calls the method named by methodName on each value in the list. Any extra arguments passed to - * invoke will be forwarded on to the method invocation. - * @param list The element's in this list will each have the method `methodName` invoked. - * @param methodName The method's name to call on each element within `list`. - * @param arguments Additional arguments to pass to the method `methodName`. - **/ - invoke( - list: _.List, - methodName: string, - ...arguments: any[]): any; - - /** - * A convenient version of what is perhaps the most common use-case for map: extracting a list of - * property values. - * @param list The list to pluck elements out of that have the property `propertyName`. - * @param propertyName The property to look for on each element within `list`. - * @return The list of elements within `list` that have the property `propertyName`. - **/ - pluck( - list: _.List, - propertyName: string): any[]; - - /** - * Returns the maximum value in list. - * @param list Finds the maximum value in this list. - * @return Maximum value in `list`. - **/ - max(list: _.List): number; - - /** - * @see _.max - */ - max(object: _.Dictionary): number; - - /** - * Returns the maximum value in list. If iterator is passed, it will be used on each value to generate - * the criterion by which the value is ranked. - * @param list Finds the maximum value in this list. - * @param iterator Compares each element in `list` to find the maximum value. - * @param context `this` object in `iterator`, optional. - * @return The maximum element within `list`. - **/ - max( - list: _.List, - iterator?: _.ListIterator, - context?: any): T; - - /** - * @see _.max - */ - max( - list: _.Dictionary, - iterator?: _.ObjectIterator, - context?: any): T; - - /** - * Returns the minimum value in list. - * @param list Finds the minimum value in this list. - * @return Minimum value in `list`. - **/ - min(list: _.List): number; - - /** - * @see _.min - */ - min(o: _.Dictionary): number; - - /** - * Returns the minimum value in list. If iterator is passed, it will be used on each value to generate - * the criterion by which the value is ranked. - * @param list Finds the minimum value in this list. - * @param iterator Compares each element in `list` to find the minimum value. - * @param context `this` object in `iterator`, optional. - * @return The minimum element within `list`. - **/ - min( - list: _.List, - iterator?: _.ListIterator, - context?: any): T; - - /** - * @see _.min - */ - min( - list: _.Dictionary, - iterator?: _.ObjectIterator, - context?: any): T; - - /** - * Returns a sorted copy of list, ranked in ascending order by the results of running each value - * through iterator. Iterator may also be the string name of the property to sort by (eg. length). - * @param list Sorts this list. - * @param iterator Sort iterator for each element within `list`. - * @param context `this` object in `iterator`, optional. - * @return A sorted copy of `list`. - **/ - sortBy( - list: _.List, - iterator?: _.ListIterator, - context?: any): T[]; - - /** - * @see _.sortBy - * @param iterator Sort iterator for each element within `list`. - **/ - sortBy( - list: _.List, - iterator: string, - context?: any): T[]; - - /** - * Splits a collection into sets, grouped by the result of running each value through iterator. - * If iterator is a string instead of a function, groups by the property named by iterator on - * each of the values. - * @param list Groups this list. - * @param iterator Group iterator for each element within `list`, return the key to group the element by. - * @param context `this` object in `iterator`, optional. - * @return An object with the group names as properties where each property contains the grouped elements from `list`. - **/ - groupBy( - list: _.List, - iterator?: _.ListIterator, - context?: any): _.Dictionary; - - /** - * @see _.groupBy - * @param iterator Property on each object to group them by. - **/ - groupBy( - list: _.List, - iterator: string, - context?: any): _.Dictionary; - - /** - * Given a `list`, and an `iterator` function that returns a key for each element in the list (or a property name), - * returns an object with an index of each item. Just like _.groupBy, but for when you know your keys are unique. - **/ - indexBy( - list: _.List, - iterator: _.ListIterator, - context?: any): _.Dictionary; - - /** - * @see _.indexBy - * @param iterator Property on each object to index them by. - **/ - indexBy( - list: _.List, - iterator: string, - context?: any): _.Dictionary; - - /** - * Sorts a list into groups and returns a count for the number of objects in each group. Similar - * to groupBy, but instead of returning a list of values, returns a count for the number of values - * in that group. - * @param list Group elements in this list and then count the number of elements in each group. - * @param iterator Group iterator for each element within `list`, return the key to group the element by. - * @param context `this` object in `iterator`, optional. - * @return An object with the group names as properties where each property contains the number of elements in that group. - **/ - countBy( - list: _.List, - iterator?: _.ListIterator, - context?: any): _.Dictionary; - - /** - * @see _.countBy - * @param iterator Function name - **/ - countBy( - list: _.List, - iterator: string, - context?: any): _.Dictionary; - - /** - * Returns a shuffled copy of the list, using a version of the Fisher-Yates shuffle. - * @param list List to shuffle. - * @return Shuffled copy of `list`. - **/ - shuffle(list: _.Collection): T[]; - - /** - * Produce a random sample from the `list`. Pass a number to return `n` random elements from the list. Otherwise a single random item will be returned. - * @param list List to sample. - * @return Random sample of `n` elements in `list`. - **/ - sample(list: _.Collection, n: number): T[]; - - /** - * @see _.sample - **/ - sample(list: _.Collection): T; - - /** - * Converts the list (anything that can be iterated over), into a real Array. Useful for transmuting - * the arguments object. - * @param list object to transform into an array. - * @return `list` as an array. - **/ - toArray(list: _.Collection): T[]; - - /** - * Return the number of values in the list. - * @param list Count the number of values/elements in this list. - * @return Number of values in `list`. - **/ - size(list: _.Collection): number; - - /** - * Split array into two arrays: - * one whose elements all satisfy predicate and one whose elements all do not satisfy predicate. - * @param array Array to split in two. - * @param iterator Filter iterator function for each element in `array`. - * @param context `this` object in `iterator`, optional. - * @return Array where Array[0] are the elements in `array` that satisfies the predicate, and Array[1] the elements that did not. - **/ - partition( - array: Array, - iterator: _.ListIterator, - context?: any): T[][]; - - /********* - * Arrays * - **********/ - - /** - * Returns the first element of an array. Passing n will return the first n elements of the array. - * @param array Retrieves the first element of this array. - * @return Returns the first element of `array`. - **/ - first(array: _.List): T; - - /** - * @see _.first - * @param n Return more than one element from `array`. - **/ - first( - array: _.List, - n: number): T[]; - - /** - * @see _.first - **/ - head(array: _.List): T; - - /** - * @see _.first - **/ - head( - array: _.List, - n: number): T[]; - - /** - * @see _.first - **/ - take(array: _.List): T; - - /** - * @see _.first - **/ - take( - array: _.List, - n: number): T[]; - - /** - * Returns everything but the last entry of the array. Especially useful on the arguments object. - * Pass n to exclude the last n elements from the result. - * @param array Retrieve all elements except the last `n`. - * @param n Leaves this many elements behind, optional. - * @return Returns everything but the last `n` elements of `array`. - **/ - initial( - array: _.List, - n?: number): T[]; - - /** - * Returns the last element of an array. Passing n will return the last n elements of the array. - * @param array Retrieves the last element of this array. - * @return Returns the last element of `array`. - **/ - last(array: _.List): T; - - /** - * @see _.last - * @param n Return more than one element from `array`. - **/ - last( - array: _.List, - n: number): T[]; - - /** - * Returns the rest of the elements in an array. Pass an index to return the values of the array - * from that index onward. - * @param array The array to retrieve all but the first `index` elements. - * @param n The index to start retrieving elements forward from, optional, default = 1. - * @return Returns the elements of `array` from `index` to the end of `array`. - **/ - rest( - array: _.List, - n?: number): T[]; - - /** - * @see _.rest - **/ - tail( - array: _.List, - n?: number): T[]; - - /** - * @see _.rest - **/ - drop( - array: _.List, - n?: number): T[]; - - /** - * Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", - * undefined and NaN are all falsy. - * @param array Array to compact. - * @return Copy of `array` without false values. - **/ - compact(array: _.List): T[]; - - /** - * Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will - * only be flattened a single level. - * @param array The array to flatten. - * @param shallow If true then only flatten one level, optional, default = false. - * @return `array` flattened. - **/ - flatten( - array: _.List, - shallow?: boolean): any[]; - - /** - * Returns a copy of the array with all instances of the values removed. - * @param array The array to remove `values` from. - * @param values The values to remove from `array`. - * @return Copy of `array` without `values`. - **/ - without( - array: _.List, - ...values: T[]): T[]; - - /** - * Computes the union of the passed-in arrays: the list of unique items, in order, that are - * present in one or more of the arrays. - * @param arrays Array of arrays to compute the union of. - * @return The union of elements within `arrays`. - **/ - union(...arrays: _.List[]): T[]; - - /** - * Computes the list of values that are the intersection of all the arrays. Each value in the result - * is present in each of the arrays. - * @param arrays Array of arrays to compute the intersection of. - * @return The intersection of elements within `arrays`. - **/ - intersection(...arrays: _.List[]): T[]; - - /** - * Similar to without, but returns the values from array that are not present in the other arrays. - * @param array Keeps values that are within `others`. - * @param others The values to keep within `array`. - * @return Copy of `array` with only `others` values. - **/ - difference( - array: _.List, - ...others: _.List[]): T[]; - - /** - * Produces a duplicate-free version of the array, using === to test object equality. If you know in - * advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If - * you want to compute unique items based on a transformation, pass an iterator function. - * @param array Array to remove duplicates from. - * @param isSorted True if `array` is already sorted, optional, default = false. - * @param iterator Transform the elements of `array` before comparisons for uniqueness. - * @param context 'this' object in `iterator`, optional. - * @return Copy of `array` where all elements are unique. - **/ - uniq( - array: _.List, - isSorted?: boolean, - iterator?: _.ListIterator, - context?: any): T[]; - - /** - * @see _.uniq - **/ - uniq( - array: _.List, - iterator?: _.ListIterator, - context?: any): T[]; - - /** - * @see _.uniq - **/ - unique( - array: _.List, - iterator?: _.ListIterator, - context?: any): T[]; - - /** - * @see _.uniq - **/ - unique( - array: _.List, - isSorted?: boolean, - iterator?: _.ListIterator, - context?: any): T[]; - - - /** - * Merges together the values of each of the arrays with the values at the corresponding position. - * Useful when you have separate data sources that are coordinated through matching array indexes. - * If you're working with a matrix of nested arrays, zip.apply can transpose the matrix in a similar fashion. - * @param arrays The arrays to merge/zip. - * @return Zipped version of `arrays`. - **/ - zip(...arrays: any[][]): any[][]; - - /** - * @see _.zip - **/ - zip(...arrays: any[]): any[]; - - /** - * The opposite of zip. Given a number of arrays, returns a series of new arrays, the first - * of which contains all of the first elements in the input arrays, the second of which - * contains all of the second elements, and so on. Use with apply to pass in an array - * of arrays - * @param arrays The arrays to unzip. - * @return Unzipped version of `arrays`. - **/ - unzip(...arrays: any[][]): any[][]; - - /** - * Converts arrays into objects. Pass either a single list of [key, value] pairs, or a - * list of keys, and a list of values. - * @param keys Key array. - * @param values Value array. - * @return An object containing the `keys` as properties and `values` as the property values. - **/ - object( - keys: _.List, - values: _.List): TResult; - - /** - * Converts arrays into objects. Pass either a single list of [key, value] pairs, or a - * list of keys, and a list of values. - * @param keyValuePairs Array of [key, value] pairs. - * @return An object containing the `keys` as properties and `values` as the property values. - **/ - object(...keyValuePairs: any[][]): TResult; - - /** - * @see _.object - **/ - object( - list: _.List, - values?: any): TResult; - - /** - * Returns the index at which value can be found in the array, or -1 if value is not present in the array. - * Uses the native indexOf function unless it's missing. If you're working with a large array, and you know - * that the array is already sorted, pass true for isSorted to use a faster binary search ... or, pass a number - * as the third argument in order to look for the first matching value in the array after the given index. - * @param array The array to search for the index of `value`. - * @param value The value to search for within `array`. - * @param isSorted True if the array is already sorted, optional, default = false. - * @return The index of `value` within `array`. - **/ - indexOf( - array: _.List, - value: T, - isSorted?: boolean): number; - - /** - * @see _indexof - **/ - indexOf( - array: _.List, - value: T, - startFrom: number): number; - - /** - * Returns the index of the last occurrence of value in the array, or -1 if value is not present. Uses the - * native lastIndexOf function if possible. Pass fromIndex to start your search at a given index. - * @param array The array to search for the last index of `value`. - * @param value The value to search for within `array`. - * @param from The starting index for the search, optional. - * @return The index of the last occurrence of `value` within `array`. - **/ - lastIndexOf( - array: _.List, - value: T, - from?: number): number; - - /** - * Returns the first index of an element in `array` where the predicate truth test passes - * @param array The array to search for the index of the first element where the predicate truth test passes. - * @param predicate Predicate function. - * @param context `this` object in `predicate`, optional. - * @return Returns the index of an element in `array` where the predicate truth test passes or -1.` - **/ - findIndex( - array: _.List, - predicate: _.ListIterator | {}, - context?: any): number; - - /** - * Returns the last index of an element in `array` where the predicate truth test passes - * @param array The array to search for the index of the last element where the predicate truth test passes. - * @param predicate Predicate function. - * @param context `this` object in `predicate`, optional. - * @return Returns the index of an element in `array` where the predicate truth test passes or -1.` - **/ - findLastIndex( - array: _.List, - predicate: _.ListIterator | {}, - context?: any): number; - - /** - * Uses a binary search to determine the index at which the value should be inserted into the list in order - * to maintain the list's sorted order. If an iterator is passed, it will be used to compute the sort ranking - * of each value, including the value you pass. - * @param list The sorted list. - * @param value The value to determine its index within `list`. - * @param iterator Iterator to compute the sort ranking of each value, optional. - * @return The index where `value` should be inserted into `list`. - **/ - sortedIndex( - list: _.List, - value: T, - iterator?: (x: T) => TSort, context?: any): number; - - /** - * A function to create flexibly-numbered lists of integers, handy for each and map loops. start, if omitted, - * defaults to 0; step defaults to 1. Returns a list of integers from start to stop, incremented (or decremented) - * by step, exclusive. - * @param start Start here. - * @param stop Stop here. - * @param step The number to count up by each iteration, optional, default = 1. - * @return Array of numbers from `start` to `stop` with increments of `step`. - **/ - - range( - start: number, - stop: number, - step?: number): number[]; - - /** - * @see _.range - * @param stop Stop here. - * @return Array of numbers from 0 to `stop` with increments of 1. - * @note If start is not specified the implementation will never pull the step (step = arguments[2] || 0) - **/ - range(stop: number): number[]; - - /************* - * Functions * - *************/ - - /** - * Bind a function to an object, meaning that whenever the function is called, the value of this will - * be the object. Optionally, bind arguments to the function to pre-fill them, also known as partial application. - * @param func The function to bind `this` to `object`. - * @param context The `this` pointer whenever `fn` is called. - * @param arguments Additional arguments to pass to `fn` when called. - * @return `fn` with `this` bound to `object`. - **/ - bind( - func: Function, - context: any, - ...arguments: any[]): () => any; - - /** - * Binds a number of methods on the object, specified by methodNames, to be run in the context of that object - * whenever they are invoked. Very handy for binding functions that are going to be used as event handlers, - * which would otherwise be invoked with a fairly useless this. If no methodNames are provided, all of the - * object's function properties will be bound to it. - * @param object The object to bind the methods `methodName` to. - * @param methodNames The methods to bind to `object`, optional and if not provided all of `object`'s - * methods are bound. - **/ - bindAll( - object: any, - ...methodNames: string[]): any; - - /** - * Partially apply a function by filling in any number of its arguments, without changing its dynamic this value. - * A close cousin of bind. You may pass _ in your list of arguments to specify an argument that should not be - * pre-filled, but left open to supply at call-time. - * @param fn Function to partially fill in arguments. - * @param arguments The partial arguments. - * @return `fn` with partially filled in arguments. - **/ - - partial( - fn: { (p1: T1):T2 }, - p1: T1 - ): { (): T2 }; - - partial( - fn: { (p1: T1, p2: T2):T3 }, - p1: T1 - ): { (p2: T2): T3 }; - - partial( - fn: { (p1: T1, p2: T2):T3 }, - p1: T1, - p2: T2 - ): { (): T3 }; - - partial( - fn: { (p1: T1, p2: T2):T3 }, - stub1: UnderscoreStatic, - p2: T2 - ): { (p1: T1): T3 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3):T4 }, - p1: T1 - ): { (p2: T2, p3: T3): T4 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3):T4 }, - p1: T1, - p2: T2 - ): { (p3: T3): T4 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3):T4 }, - stub1: UnderscoreStatic, - p2: T2 - ): { (p1: T1, p3: T3): T4 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3):T4 }, - p1: T1, - p2: T2, - p3: T3 - ): { (): T4 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3):T4 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3 - ): { (p1: T1): T4 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3):T4 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3 - ): { (p2: T2): T4 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3):T4 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3 - ): { (p1: T1, p2: T2): T4 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4):T5 }, - p1: T1 - ): { (p2: T2, p3: T3, p4: T4): T5 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4):T5 }, - p1: T1, - p2: T2 - ): { (p3: T3, p4: T4): T5 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4):T5 }, - stub1: UnderscoreStatic, - p2: T2 - ): { (p1: T1, p3: T3, p4: T4): T5 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4):T5 }, - p1: T1, - p2: T2, - p3: T3 - ): { (p4: T4): T5 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4):T5 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3 - ): { (p1: T1, p4: T4): T5 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4):T5 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3 - ): { (p2: T2, p4: T4): T5 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4):T5 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3 - ): { (p1: T1, p2: T2, p4: T4): T5 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4):T5 }, - p1: T1, - p2: T2, - p3: T3, - p4: T4 - ): { (): T5 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4):T5 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - p4: T4 - ): { (p1: T1): T5 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4):T5 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - p4: T4 - ): { (p2: T2): T5 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4):T5 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - p4: T4 - ): { (p1: T1, p2: T2): T5 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4):T5 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - p4: T4 - ): { (p3: T3): T5 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4):T5 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - p4: T4 - ): { (p1: T1, p3: T3): T5 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4):T5 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4 - ): { (p2: T2, p3: T3): T5 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4):T5 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4 - ): { (p1: T1, p2: T2, p3: T3): T5 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - p1: T1 - ): { (p2: T2, p3: T3, p4: T4, p5: T5): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - p1: T1, - p2: T2 - ): { (p3: T3, p4: T4, p5: T5): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - stub1: UnderscoreStatic, - p2: T2 - ): { (p1: T1, p3: T3, p4: T4, p5: T5): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - p1: T1, - p2: T2, - p3: T3 - ): { (p4: T4, p5: T5): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3 - ): { (p1: T1, p4: T4, p5: T5): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3 - ): { (p2: T2, p4: T4, p5: T5): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3 - ): { (p1: T1, p2: T2, p4: T4, p5: T5): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - p1: T1, - p2: T2, - p3: T3, - p4: T4 - ): { (p5: T5): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - p4: T4 - ): { (p1: T1, p5: T5): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - p4: T4 - ): { (p2: T2, p5: T5): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - p4: T4 - ): { (p1: T1, p2: T2, p5: T5): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - p4: T4 - ): { (p3: T3, p5: T5): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - p4: T4 - ): { (p1: T1, p3: T3, p5: T5): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4 - ): { (p2: T2, p3: T3, p5: T5): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4 - ): { (p1: T1, p2: T2, p3: T3, p5: T5): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - p1: T1, - p2: T2, - p3: T3, - p4: T4, - p5: T5 - ): { (): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - p4: T4, - p5: T5 - ): { (p1: T1): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - p5: T5 - ): { (p2: T2): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - p5: T5 - ): { (p1: T1, p2: T2): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - p5: T5 - ): { (p3: T3): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - p5: T5 - ): { (p1: T1, p3: T3): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - p5: T5 - ): { (p2: T2, p3: T3): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - p5: T5 - ): { (p1: T1, p2: T2, p3: T3): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - p1: T1, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - p5: T5 - ): { (p4: T4): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - p5: T5 - ): { (p1: T1, p4: T4): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - p5: T5 - ): { (p2: T2, p4: T4): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - p5: T5 - ): { (p1: T1, p2: T2, p4: T4): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5 - ): { (p3: T3, p4: T4): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5 - ): { (p1: T1, p3: T3, p4: T4): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5 - ): { (p2: T2, p3: T3, p4: T4): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5):T6 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5 - ): { (p1: T1, p2: T2, p3: T3, p4: T4): T6 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1 - ): { (p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - p2: T2 - ): { (p3: T3, p4: T4, p5: T5, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - p2: T2 - ): { (p1: T1, p3: T3, p4: T4, p5: T5, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - p2: T2, - p3: T3 - ): { (p4: T4, p5: T5, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3 - ): { (p1: T1, p4: T4, p5: T5, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3 - ): { (p2: T2, p4: T4, p5: T5, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3 - ): { (p1: T1, p2: T2, p4: T4, p5: T5, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - p2: T2, - p3: T3, - p4: T4 - ): { (p5: T5, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - p4: T4 - ): { (p1: T1, p5: T5, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - p4: T4 - ): { (p2: T2, p5: T5, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - p4: T4 - ): { (p1: T1, p2: T2, p5: T5, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - p4: T4 - ): { (p3: T3, p5: T5, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - p4: T4 - ): { (p1: T1, p3: T3, p5: T5, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4 - ): { (p2: T2, p3: T3, p5: T5, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4 - ): { (p1: T1, p2: T2, p3: T3, p5: T5, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - p2: T2, - p3: T3, - p4: T4, - p5: T5 - ): { (p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - p4: T4, - p5: T5 - ): { (p1: T1, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - p5: T5 - ): { (p2: T2, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - p5: T5 - ): { (p1: T1, p2: T2, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - p5: T5 - ): { (p3: T3, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - p5: T5 - ): { (p1: T1, p3: T3, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - p5: T5 - ): { (p2: T2, p3: T3, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - p5: T5 - ): { (p1: T1, p2: T2, p3: T3, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - p5: T5 - ): { (p4: T4, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - p5: T5 - ): { (p1: T1, p4: T4, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - p5: T5 - ): { (p2: T2, p4: T4, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - p5: T5 - ): { (p1: T1, p2: T2, p4: T4, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5 - ): { (p3: T3, p4: T4, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5 - ): { (p1: T1, p3: T3, p4: T4, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5 - ): { (p2: T2, p3: T3, p4: T4, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5 - ): { (p1: T1, p2: T2, p3: T3, p4: T4, p6: T6): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - p2: T2, - p3: T3, - p4: T4, - p5: T5, - p6: T6 - ): { (): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - p4: T4, - p5: T5, - p6: T6 - ): { (p1: T1): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - p5: T5, - p6: T6 - ): { (p2: T2): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - p5: T5, - p6: T6 - ): { (p1: T1, p2: T2): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - p5: T5, - p6: T6 - ): { (p3: T3): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - p5: T5, - p6: T6 - ): { (p1: T1, p3: T3): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - p5: T5, - p6: T6 - ): { (p2: T2, p3: T3): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - p5: T5, - p6: T6 - ): { (p1: T1, p2: T2, p3: T3): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - p5: T5, - p6: T6 - ): { (p4: T4): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - p5: T5, - p6: T6 - ): { (p1: T1, p4: T4): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - p5: T5, - p6: T6 - ): { (p2: T2, p4: T4): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - p5: T5, - p6: T6 - ): { (p1: T1, p2: T2, p4: T4): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5, - p6: T6 - ): { (p3: T3, p4: T4): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5, - p6: T6 - ): { (p1: T1, p3: T3, p4: T4): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5, - p6: T6 - ): { (p2: T2, p3: T3, p4: T4): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5, - p6: T6 - ): { (p1: T1, p2: T2, p3: T3, p4: T4): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - p2: T2, - p3: T3, - p4: T4, - stub5: UnderscoreStatic, - p6: T6 - ): { (p5: T5): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - p4: T4, - stub5: UnderscoreStatic, - p6: T6 - ): { (p1: T1, p5: T5): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - stub5: UnderscoreStatic, - p6: T6 - ): { (p2: T2, p5: T5): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - stub5: UnderscoreStatic, - p6: T6 - ): { (p1: T1, p2: T2, p5: T5): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - stub5: UnderscoreStatic, - p6: T6 - ): { (p3: T3, p5: T5): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - stub5: UnderscoreStatic, - p6: T6 - ): { (p1: T1, p3: T3, p5: T5): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - stub5: UnderscoreStatic, - p6: T6 - ): { (p2: T2, p3: T3, p5: T5): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - stub5: UnderscoreStatic, - p6: T6 - ): { (p1: T1, p2: T2, p3: T3, p5: T5): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6 - ): { (p4: T4, p5: T5): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6 - ): { (p1: T1, p4: T4, p5: T5): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6 - ): { (p2: T2, p4: T4, p5: T5): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6 - ): { (p1: T1, p2: T2, p4: T4, p5: T5): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6 - ): { (p3: T3, p4: T4, p5: T5): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6 - ): { (p1: T1, p3: T3, p4: T4, p5: T5): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6 - ): { (p2: T2, p3: T3, p4: T4, p5: T5): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6):T7 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6 - ): { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T7 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1 - ): { (p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2 - ): { (p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2 - ): { (p1: T1, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - p3: T3 - ): { (p4: T4, p5: T5, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3 - ): { (p1: T1, p4: T4, p5: T5, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3 - ): { (p2: T2, p4: T4, p5: T5, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3 - ): { (p1: T1, p2: T2, p4: T4, p5: T5, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - p3: T3, - p4: T4 - ): { (p5: T5, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - p4: T4 - ): { (p1: T1, p5: T5, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - p4: T4 - ): { (p2: T2, p5: T5, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - p4: T4 - ): { (p1: T1, p2: T2, p5: T5, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - p4: T4 - ): { (p3: T3, p5: T5, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - p4: T4 - ): { (p1: T1, p3: T3, p5: T5, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4 - ): { (p2: T2, p3: T3, p5: T5, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4 - ): { (p1: T1, p2: T2, p3: T3, p5: T5, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - p3: T3, - p4: T4, - p5: T5 - ): { (p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - p4: T4, - p5: T5 - ): { (p1: T1, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - p5: T5 - ): { (p2: T2, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - p5: T5 - ): { (p1: T1, p2: T2, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - p5: T5 - ): { (p3: T3, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - p5: T5 - ): { (p1: T1, p3: T3, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - p5: T5 - ): { (p2: T2, p3: T3, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - p5: T5 - ): { (p1: T1, p2: T2, p3: T3, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - p5: T5 - ): { (p4: T4, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - p5: T5 - ): { (p1: T1, p4: T4, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - p5: T5 - ): { (p2: T2, p4: T4, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - p5: T5 - ): { (p1: T1, p2: T2, p4: T4, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5 - ): { (p3: T3, p4: T4, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5 - ): { (p1: T1, p3: T3, p4: T4, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5 - ): { (p2: T2, p3: T3, p4: T4, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5 - ): { (p1: T1, p2: T2, p3: T3, p4: T4, p6: T6, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - p3: T3, - p4: T4, - p5: T5, - p6: T6 - ): { (p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - p4: T4, - p5: T5, - p6: T6 - ): { (p1: T1, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - p5: T5, - p6: T6 - ): { (p2: T2, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - p5: T5, - p6: T6 - ): { (p1: T1, p2: T2, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - p5: T5, - p6: T6 - ): { (p3: T3, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - p5: T5, - p6: T6 - ): { (p1: T1, p3: T3, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - p5: T5, - p6: T6 - ): { (p2: T2, p3: T3, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - p5: T5, - p6: T6 - ): { (p1: T1, p2: T2, p3: T3, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - p5: T5, - p6: T6 - ): { (p4: T4, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - p5: T5, - p6: T6 - ): { (p1: T1, p4: T4, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - p5: T5, - p6: T6 - ): { (p2: T2, p4: T4, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - p5: T5, - p6: T6 - ): { (p1: T1, p2: T2, p4: T4, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5, - p6: T6 - ): { (p3: T3, p4: T4, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5, - p6: T6 - ): { (p1: T1, p3: T3, p4: T4, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5, - p6: T6 - ): { (p2: T2, p3: T3, p4: T4, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5, - p6: T6 - ): { (p1: T1, p2: T2, p3: T3, p4: T4, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - p3: T3, - p4: T4, - stub5: UnderscoreStatic, - p6: T6 - ): { (p5: T5, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - p4: T4, - stub5: UnderscoreStatic, - p6: T6 - ): { (p1: T1, p5: T5, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - stub5: UnderscoreStatic, - p6: T6 - ): { (p2: T2, p5: T5, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - stub5: UnderscoreStatic, - p6: T6 - ): { (p1: T1, p2: T2, p5: T5, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - stub5: UnderscoreStatic, - p6: T6 - ): { (p3: T3, p5: T5, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - stub5: UnderscoreStatic, - p6: T6 - ): { (p1: T1, p3: T3, p5: T5, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - stub5: UnderscoreStatic, - p6: T6 - ): { (p2: T2, p3: T3, p5: T5, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - stub5: UnderscoreStatic, - p6: T6 - ): { (p1: T1, p2: T2, p3: T3, p5: T5, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6 - ): { (p4: T4, p5: T5, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6 - ): { (p1: T1, p4: T4, p5: T5, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6 - ): { (p2: T2, p4: T4, p5: T5, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6 - ): { (p1: T1, p2: T2, p4: T4, p5: T5, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6 - ): { (p3: T3, p4: T4, p5: T5, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6 - ): { (p1: T1, p3: T3, p4: T4, p5: T5, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6 - ): { (p2: T2, p3: T3, p4: T4, p5: T5, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6 - ): { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p7: T7): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - p3: T3, - p4: T4, - p5: T5, - p6: T6, - p7: T7 - ): { (): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - p4: T4, - p5: T5, - p6: T6, - p7: T7 - ): { (p1: T1): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - p5: T5, - p6: T6, - p7: T7 - ): { (p2: T2): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - p5: T5, - p6: T6, - p7: T7 - ): { (p1: T1, p2: T2): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - p5: T5, - p6: T6, - p7: T7 - ): { (p3: T3): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - p5: T5, - p6: T6, - p7: T7 - ): { (p1: T1, p3: T3): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - p5: T5, - p6: T6, - p7: T7 - ): { (p2: T2, p3: T3): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - p5: T5, - p6: T6, - p7: T7 - ): { (p1: T1, p2: T2, p3: T3): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - p5: T5, - p6: T6, - p7: T7 - ): { (p4: T4): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - p5: T5, - p6: T6, - p7: T7 - ): { (p1: T1, p4: T4): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - p5: T5, - p6: T6, - p7: T7 - ): { (p2: T2, p4: T4): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - p5: T5, - p6: T6, - p7: T7 - ): { (p1: T1, p2: T2, p4: T4): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5, - p6: T6, - p7: T7 - ): { (p3: T3, p4: T4): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5, - p6: T6, - p7: T7 - ): { (p1: T1, p3: T3, p4: T4): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5, - p6: T6, - p7: T7 - ): { (p2: T2, p3: T3, p4: T4): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5, - p6: T6, - p7: T7 - ): { (p1: T1, p2: T2, p3: T3, p4: T4): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - p3: T3, - p4: T4, - stub5: UnderscoreStatic, - p6: T6, - p7: T7 - ): { (p5: T5): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - p4: T4, - stub5: UnderscoreStatic, - p6: T6, - p7: T7 - ): { (p1: T1, p5: T5): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - stub5: UnderscoreStatic, - p6: T6, - p7: T7 - ): { (p2: T2, p5: T5): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - stub5: UnderscoreStatic, - p6: T6, - p7: T7 - ): { (p1: T1, p2: T2, p5: T5): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - stub5: UnderscoreStatic, - p6: T6, - p7: T7 - ): { (p3: T3, p5: T5): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - stub5: UnderscoreStatic, - p6: T6, - p7: T7 - ): { (p1: T1, p3: T3, p5: T5): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - stub5: UnderscoreStatic, - p6: T6, - p7: T7 - ): { (p2: T2, p3: T3, p5: T5): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - stub5: UnderscoreStatic, - p6: T6, - p7: T7 - ): { (p1: T1, p2: T2, p3: T3, p5: T5): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6, - p7: T7 - ): { (p4: T4, p5: T5): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6, - p7: T7 - ): { (p1: T1, p4: T4, p5: T5): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6, - p7: T7 - ): { (p2: T2, p4: T4, p5: T5): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6, - p7: T7 - ): { (p1: T1, p2: T2, p4: T4, p5: T5): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6, - p7: T7 - ): { (p3: T3, p4: T4, p5: T5): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6, - p7: T7 - ): { (p1: T1, p3: T3, p4: T4, p5: T5): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6, - p7: T7 - ): { (p2: T2, p3: T3, p4: T4, p5: T5): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - p6: T6, - p7: T7 - ): { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - p3: T3, - p4: T4, - p5: T5, - stub6: UnderscoreStatic, - p7: T7 - ): { (p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - p4: T4, - p5: T5, - stub6: UnderscoreStatic, - p7: T7 - ): { (p1: T1, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - p5: T5, - stub6: UnderscoreStatic, - p7: T7 - ): { (p2: T2, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - p5: T5, - stub6: UnderscoreStatic, - p7: T7 - ): { (p1: T1, p2: T2, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - p5: T5, - stub6: UnderscoreStatic, - p7: T7 - ): { (p3: T3, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - p5: T5, - stub6: UnderscoreStatic, - p7: T7 - ): { (p1: T1, p3: T3, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - p5: T5, - stub6: UnderscoreStatic, - p7: T7 - ): { (p2: T2, p3: T3, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - p5: T5, - stub6: UnderscoreStatic, - p7: T7 - ): { (p1: T1, p2: T2, p3: T3, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - p5: T5, - stub6: UnderscoreStatic, - p7: T7 - ): { (p4: T4, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - p5: T5, - stub6: UnderscoreStatic, - p7: T7 - ): { (p1: T1, p4: T4, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - p5: T5, - stub6: UnderscoreStatic, - p7: T7 - ): { (p2: T2, p4: T4, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - p5: T5, - stub6: UnderscoreStatic, - p7: T7 - ): { (p1: T1, p2: T2, p4: T4, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5, - stub6: UnderscoreStatic, - p7: T7 - ): { (p3: T3, p4: T4, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5, - stub6: UnderscoreStatic, - p7: T7 - ): { (p1: T1, p3: T3, p4: T4, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5, - stub6: UnderscoreStatic, - p7: T7 - ): { (p2: T2, p3: T3, p4: T4, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - p5: T5, - stub6: UnderscoreStatic, - p7: T7 - ): { (p1: T1, p2: T2, p3: T3, p4: T4, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - p3: T3, - p4: T4, - stub5: UnderscoreStatic, - stub6: UnderscoreStatic, - p7: T7 - ): { (p5: T5, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - p4: T4, - stub5: UnderscoreStatic, - stub6: UnderscoreStatic, - p7: T7 - ): { (p1: T1, p5: T5, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - stub5: UnderscoreStatic, - stub6: UnderscoreStatic, - p7: T7 - ): { (p2: T2, p5: T5, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - p4: T4, - stub5: UnderscoreStatic, - stub6: UnderscoreStatic, - p7: T7 - ): { (p1: T1, p2: T2, p5: T5, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - stub5: UnderscoreStatic, - stub6: UnderscoreStatic, - p7: T7 - ): { (p3: T3, p5: T5, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - p4: T4, - stub5: UnderscoreStatic, - stub6: UnderscoreStatic, - p7: T7 - ): { (p1: T1, p3: T3, p5: T5, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - stub5: UnderscoreStatic, - stub6: UnderscoreStatic, - p7: T7 - ): { (p2: T2, p3: T3, p5: T5, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - p4: T4, - stub5: UnderscoreStatic, - stub6: UnderscoreStatic, - p7: T7 - ): { (p1: T1, p2: T2, p3: T3, p5: T5, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - stub6: UnderscoreStatic, - p7: T7 - ): { (p4: T4, p5: T5, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - p3: T3, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - stub6: UnderscoreStatic, - p7: T7 - ): { (p1: T1, p4: T4, p5: T5, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - stub6: UnderscoreStatic, - p7: T7 - ): { (p2: T2, p4: T4, p5: T5, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - p3: T3, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - stub6: UnderscoreStatic, - p7: T7 - ): { (p1: T1, p2: T2, p4: T4, p5: T5, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - stub6: UnderscoreStatic, - p7: T7 - ): { (p3: T3, p4: T4, p5: T5, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - p2: T2, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - stub6: UnderscoreStatic, - p7: T7 - ): { (p1: T1, p3: T3, p4: T4, p5: T5, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - p1: T1, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - stub6: UnderscoreStatic, - p7: T7 - ): { (p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T8 }; - - partial( - fn: { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6, p7: T7):T8 }, - stub1: UnderscoreStatic, - stub2: UnderscoreStatic, - stub3: UnderscoreStatic, - stub4: UnderscoreStatic, - stub5: UnderscoreStatic, - stub6: UnderscoreStatic, - p7: T7 - ): { (p1: T1, p2: T2, p3: T3, p4: T4, p5: T5, p6: T6): T8 }; - - /** - * Memoizes a given function by caching the computed result. Useful for speeding up slow-running computations. - * If passed an optional hashFunction, it will be used to compute the hash key for storing the result, based - * on the arguments to the original function. The default hashFunction just uses the first argument to the - * memoized function as the key. - * @param fn Computationally expensive function that will now memoized results. - * @param hashFn Hash function for storing the result of `fn`. - * @return Memoized version of `fn`. - **/ - memoize( - fn: Function, - hashFn?: (...args: any[]) => string): Function; - - /** - * Much like setTimeout, invokes function after wait milliseconds. If you pass the optional arguments, - * they will be forwarded on to the function when it is invoked. - * @param func Function to delay `waitMS` amount of ms. - * @param wait The amount of milliseconds to delay `fn`. - * @arguments Additional arguments to pass to `fn`. - **/ - delay( - func: Function, - wait: number, - ...arguments: any[]): any; - - /** - * @see _delay - **/ - delay( - func: Function, - ...arguments: any[]): any; - - /** - * Defers invoking the function until the current call stack has cleared, similar to using setTimeout - * with a delay of 0. Useful for performing expensive computations or HTML rendering in chunks without - * blocking the UI thread from updating. If you pass the optional arguments, they will be forwarded on - * to the function when it is invoked. - * @param fn The function to defer. - * @param arguments Additional arguments to pass to `fn`. - **/ - defer( - fn: Function, - ...arguments: any[]): void; - - /** - * Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, - * will only actually call the original function at most once per every wait milliseconds. Useful for - * rate-limiting events that occur faster than you can keep up with. - * By default, throttle will execute the function as soon as you call it for the first time, and, - * if you call it again any number of times during the wait period, as soon as that period is over. - * If you'd like to disable the leading-edge call, pass {leading: false}, and if you'd like to disable - * the execution on the trailing-edge, pass {trailing: false}. - * @param func Function to throttle `waitMS` ms. - * @param wait The number of milliseconds to wait before `fn` can be invoked again. - * @param options Allows for disabling execution of the throttled function on either the leading or trailing edge. - * @return `fn` with a throttle of `wait`. - **/ - throttle( - func: T, - wait: number, - options?: _.ThrottleSettings): T; - - /** - * Creates and returns a new debounced version of the passed function that will postpone its execution - * until after wait milliseconds have elapsed since the last time it was invoked. Useful for implementing - * behavior that should only happen after the input has stopped arriving. For example: rendering a preview - * of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on. - * - * Pass true for the immediate parameter to cause debounce to trigger the function on the leading instead - * of the trailing edge of the wait interval. Useful in circumstances like preventing accidental double - *-clicks on a "submit" button from firing a second time. - * @param fn Function to debounce `waitMS` ms. - * @param wait The number of milliseconds to wait before `fn` can be invoked again. - * @param immediate True if `fn` should be invoked on the leading edge of `waitMS` instead of the trailing edge. - * @return Debounced version of `fn` that waits `wait` ms when invoked. - **/ - debounce( - fn: T, - wait: number, - immediate?: boolean): T; - - /** - * Creates a version of the function that can only be called one time. Repeated calls to the modified - * function will have no effect, returning the value from the original call. Useful for initialization - * functions, instead of having to set a boolean flag and then check it later. - * @param fn Function to only execute once. - * @return Copy of `fn` that can only be invoked once. - **/ - once(fn: T): T; - - /** - * Creates a version of the function that will only be run after first being called count times. Useful - * for grouping asynchronous responses, where you want to be sure that all the async calls have finished, - * before proceeding. - * @param number count Number of times to be called before actually executing. - * @param Function fn The function to defer execution `count` times. - * @return Copy of `fn` that will not execute until it is invoked `count` times. - **/ - after( - count: number, - fn: Function): Function; - - /** - * Creates a version of the function that can be called no more than count times. The result of - * the last function call is memoized and returned when count has been reached. - * @param number count The maxmimum number of times the function can be called. - * @param Function fn The function to limit the number of times it can be called. - * @return Copy of `fn` that can only be called `count` times. - **/ - before( - count: number, - fn: Function): Function; - - /** - * Wraps the first function inside of the wrapper function, passing it as the first argument. This allows - * the wrapper to execute code before and after the function runs, adjust the arguments, and execute it - * conditionally. - * @param fn Function to wrap. - * @param wrapper The function that will wrap `fn`. - * @return Wrapped version of `fn. - **/ - wrap( - fn: Function, - wrapper: (fn: Function, ...args: any[]) => any): Function; - - /** - * Returns a negated version of the pass-in predicate. - * @param (...args: any[]) => boolean predicate - * @return (...args: any[]) => boolean - **/ - negate(predicate: (...args: any[]) => boolean): (...args: any[]) => boolean; - - /** - * Returns the composition of a list of functions, where each function consumes the return value of the - * function that follows. In math terms, composing the functions f(), g(), and h() produces f(g(h())). - * @param functions List of functions to compose. - * @return Composition of `functions`. - **/ - compose(...functions: Function[]): Function; - - /********** - * Objects * - ***********/ - - /** - * Retrieve all the names of the object's properties. - * @param object Retrieve the key or property names from this object. - * @return List of all the property names on `object`. - **/ - keys(object: any): string[]; - - /** - * Retrieve all the names of object's own and inherited properties. - * @param object Retrieve the key or property names from this object. - * @return List of all the property names on `object`. - **/ - allKeys(object: any): string[]; - - /** - * Return all of the values of the object's properties. - * @param object Retrieve the values of all the properties on this object. - * @return List of all the values on `object`. - **/ - values(object: _.Dictionary): T[]; - - /** - * Return all of the values of the object's properties. - * @param object Retrieve the values of all the properties on this object. - * @return List of all the values on `object`. - **/ - values(object: any): any[]; - - /** - * Like map, but for objects. Transform the value of each property in turn. - * @param object The object to transform - * @param iteratee The function that transforms property values - * @param context The optional context (value of `this`) to bind to - * @return a new _.Dictionary of property values - */ - mapObject(object: _.Dictionary, iteratee: (val: T, key: string, object: _.Dictionary) => U, context?: any): _.Dictionary; - - /** - * Like map, but for objects. Transform the value of each property in turn. - * @param object The object to transform - * @param iteratee The function that tranforms property values - * @param context The optional context (value of `this`) to bind to - */ - mapObject(object: any, iteratee: (val: any, key: string, object: any) => T, context?: any): _.Dictionary; - - /** - * Like map, but for objects. Retrieves a property from each entry in the object, as if by _.property - * @param object The object to transform - * @param iteratee The property name to retrieve - * @param context The optional context (value of `this`) to bind to - */ - mapObject(object: any, iteratee: string, context?: any): _.Dictionary; - - /** - * Convert an object into a list of [key, value] pairs. - * @param object Convert this object to a list of [key, value] pairs. - * @return List of [key, value] pairs on `object`. - **/ - pairs(object: any): any[][]; - - /** - * Returns a copy of the object where the keys have become the values and the values the keys. - * For this to work, all of your object's values should be unique and string serializable. - * @param object Object to invert key/value pairs. - * @return An inverted key/value paired version of `object`. - **/ - invert(object: any): any; - - /** - * Returns a sorted list of the names of every method in an object - that is to say, - * the name of every function property of the object. - * @param object Object to pluck all function property names from. - * @return List of all the function names on `object`. - **/ - functions(object: any): string[]; - - /** - * @see _functions - **/ - methods(object: any): string[]; - - /** - * Copy all of the properties in the source objects over to the destination object, and return - * the destination object. It's in-order, so the last source will override properties of the - * same name in previous arguments. - * @param destination Object to extend all the properties from `sources`. - * @param sources Extends `destination` with all properties from these source objects. - * @return `destination` extended with all the properties from the `sources` objects. - **/ - extend( - destination: any, - ...sources: any[]): any; - - /** - * Like extend, but only copies own properties over to the destination object. (alias: assign) - */ - extendOwn( - destination: any, - ...source: any[]): any; - - /** - * Like extend, but only copies own properties over to the destination object. (alias: extendOwn) - */ - assign( - destination: any, - ...source: any[]): any; - - /** - * Return a copy of the object, filtered to only have values for the whitelisted keys - * (or array of valid keys). - * @param object Object to strip unwanted key/value pairs. - * @keys The key/value pairs to keep on `object`. - * @return Copy of `object` with only the `keys` properties. - **/ - pick( - object: any, - ...keys: any[]): any; - - /** - * @see _.pick - **/ - pick( - object: any, - fn: (value: any, key: any, object: any) => any): any; - - /** - * Return a copy of the object, filtered to omit the blacklisted keys (or array of keys). - * @param object Object to strip unwanted key/value pairs. - * @param keys The key/value pairs to remove on `object`. - * @return Copy of `object` without the `keys` properties. - **/ - omit( - object: any, - ...keys: string[]): any; - - /** - * @see _.omit - **/ - omit( - object: any, - keys: string[]): any; - - /** - * @see _.omit - **/ - omit( - object: any, - iteratee: Function): any; - - /** - * Fill in null and undefined properties in object with values from the defaults objects, - * and return the object. As soon as the property is filled, further defaults will have no effect. - * @param object Fill this object with default values. - * @param defaults The default values to add to `object`. - * @return `object` with added `defaults` values. - **/ - defaults( - object: any, - ...defaults: any[]): any; - - /** - * Create a shallow-copied clone of the object. - * Any nested objects or arrays will be copied by reference, not duplicated. - * @param object Object to clone. - * @return Copy of `object`. - **/ - clone(object: T): T; - - /** - * Invokes interceptor with the object, and then returns object. The primary purpose of this method - * is to "tap into" a method chain, in order to perform operations on intermediate results within the chain. - * @param object Argument to `interceptor`. - * @param intercepter The function to modify `object` before continuing the method chain. - * @return Modified `object`. - **/ - tap(object: T, intercepter: Function): T; - - /** - * Does the object contain the given key? Identical to object.hasOwnProperty(key), but uses a safe - * reference to the hasOwnProperty function, in case it's been overridden accidentally. - * @param object Object to check for `key`. - * @param key The key to check for on `object`. - * @return True if `key` is a property on `object`, otherwise false. - **/ - has(object: any, key: string): boolean; - - /** - * Returns a predicate function that will tell you if a passed in object contains all of the key/value properties present in attrs. - * @param attrs Object with key values pair - * @return Predicate function - **/ - matches(attrs: T): _.ListIterator; - - /** - * Returns a function that will itself return the key property of any passed-in object. - * @param key Property of the object. - * @return Function which accept an object an returns the value of key in that object. - **/ - property(key: string): (object: Object) => any; - - /** - * Returns a function that will itself return the value of a object key property. - * @param key The object to get the property value from. - * @return Function which accept a key property in `object` and returns its value. - **/ - propertyOf(object: Object): (key: string) => any; - - /** - * Performs an optimized deep comparison between the two objects, - * to determine if they should be considered equal. - * @param object Compare to `other`. - * @param other Compare to `object`. - * @return True if `object` is equal to `other`. - **/ - isEqual(object: any, other: any): boolean; - - /** - * Returns true if object contains no values. - * @param object Check if this object has no properties or values. - * @return True if `object` is empty. - **/ - isEmpty(object: any): boolean; - - /** - * Returns true if the keys and values in `properties` matches with the `object` properties. - * @param object Object to be compared with `properties`. - * @param properties Properties be compared with `object` - * @return True if `object` has matching keys and values, otherwise false. - **/ - isMatch(object:any, properties:any): boolean; - - /** - * Returns true if object is a DOM element. - * @param object Check if this object is a DOM element. - * @return True if `object` is a DOM element, otherwise false. - **/ - isElement(object: any): object is Element; - - /** - * Returns true if object is an Array. - * @param object Check if this object is an Array. - * @return True if `object` is an Array, otherwise false. - **/ - isArray(object: any): object is []; - - /** - * Returns true if object is an Array. - * @param object Check if this object is an Array. - * @return True if `object` is an Array, otherwise false. - **/ - isArray(object: any): object is T[]; - - /** - * Returns true if value is an Object. Note that JavaScript arrays and functions are objects, - * while (normal) strings and numbers are not. - * @param object Check if this object is an Object. - * @return True of `object` is an Object, otherwise false. - **/ - isObject(object: any): boolean; - - /** - * Returns true if object is an Arguments object. - * @param object Check if this object is an Arguments object. - * @return True if `object` is an Arguments object, otherwise false. - **/ - isArguments(object: any): object is IArguments; - - /** - * Returns true if object is a Function. - * @param object Check if this object is a Function. - * @return True if `object` is a Function, otherwise false. - **/ - isFunction(object: any): object is Function; - - /** - * Returns true if object inherits from an Error. - * @param object Check if this object is an Error. - * @return True if `object` is a Error, otherwise false. - **/ - isError(object:any): object is Error; - - /** - * Returns true if object is a String. - * @param object Check if this object is a String. - * @return True if `object` is a String, otherwise false. - **/ - isString(object: any): object is string; - - /** - * Returns true if object is a Number (including NaN). - * @param object Check if this object is a Number. - * @return True if `object` is a Number, otherwise false. - **/ - isNumber(object: any): object is number; - - /** - * Returns true if object is a finite Number. - * @param object Check if this object is a finite Number. - * @return True if `object` is a finite Number. - **/ - isFinite(object: any): boolean; - - /** - * Returns true if object is either true or false. - * @param object Check if this object is a bool. - * @return True if `object` is a bool, otherwise false. - **/ - isBoolean(object: any): object is boolean; - - /** - * Returns true if object is a Date. - * @param object Check if this object is a Date. - * @return True if `object` is a Date, otherwise false. - **/ - isDate(object: any): object is Date; - - /** - * Returns true if object is a RegExp. - * @param object Check if this object is a RegExp. - * @return True if `object` is a RegExp, otherwise false. - **/ - isRegExp(object: any): object is RegExp; - - /** - * Returns true if object is NaN. - * Note: this is not the same as the native isNaN function, - * which will also return true if the variable is undefined. - * @param object Check if this object is NaN. - * @return True if `object` is NaN, otherwise false. - **/ - isNaN(object: any): boolean; - - /** - * Returns true if the value of object is null. - * @param object Check if this object is null. - * @return True if `object` is null, otherwise false. - **/ - isNull(object: any): boolean; - - /** - * Returns true if value is undefined. - * @param object Check if this object is undefined. - * @return True if `object` is undefined, otherwise false. - **/ - isUndefined(value: any): boolean; - - /* ********* - * Utility * - ********** */ - - /** - * Give control of the "_" variable back to its previous owner. - * Returns a reference to the Underscore object. - * @return Underscore object reference. - **/ - noConflict(): any; - - /** - * Returns the same value that is used as the argument. In math: f(x) = x - * This function looks useless, but is used throughout Underscore as a default iterator. - * @param value Identity of this object. - * @return `value`. - **/ - identity(value: T): T; - - /** - * Creates a function that returns the same value that is used as the argument of _.constant - * @param value Identity of this object. - * @return Function that return value. - **/ - constant(value: T): () => T; - - /** - * Returns undefined irrespective of the arguments passed to it. Useful as the default - * for optional callback arguments. - * Note there is no way to indicate a 'undefined' return, so it is currently typed as void. - * @return undefined - **/ - noop(): void; - - /** - * Invokes the given iterator function n times. - * Each invocation of iterator is called with an index argument - * @param n Number of times to invoke `iterator`. - * @param iterator Function iterator to invoke `n` times. - * @param context `this` object in `iterator`, optional. - **/ - times(n: number, iterator: (n: number) => TResult, context?: any): TResult[]; - - /** - * Returns a random integer between min and max, inclusive. If you only pass one argument, - * it will return a number between 0 and that number. - * @param max The maximum random number. - * @return A random number between 0 and `max`. - **/ - random(max: number): number; - - /** - * @see _.random - * @param min The minimum random number. - * @return A random number between `min` and `max`. - **/ - random(min: number, max: number): number; - - /** - * Allows you to extend Underscore with your own utility functions. Pass a hash of - * {name: function} definitions to have your functions added to the Underscore object, - * as well as the OOP wrapper. - * @param object Mixin object containing key/function pairs to add to the Underscore object. - **/ - mixin(object: any): void; - - /** - * A mostly-internal function to generate callbacks that can be applied to each element - * in a collection, returning the desired result -- either identity, an arbitrary callback, - * a property matcher, or a propetery accessor. - * @param string|Function|Object value The value to iterate over, usually the key. - * @param any context - * @param number argCount - * @return Callback that can be applied to each element in a collection. - **/ - iteratee(value: string): Function; - iteratee(value: Function, context?: any, argCount?: number): Function; - iteratee(value: Object): Function; - - /** - * Generate a globally-unique id for client-side models or DOM elements that need one. - * If prefix is passed, the id will be appended to it. Without prefix, returns an integer. - * @param prefix A prefix string to start the unique ID with. - * @return Unique string ID beginning with `prefix`. - **/ - uniqueId(prefix?: string): string; - - /** - * Escapes a string for insertion into HTML, replacing &, <, >, ", ', and / characters. - * @param str Raw string to escape. - * @return `str` HTML escaped. - **/ - escape(str: string): string; - - /** - * The opposite of escape, replaces &, <, >, ", and ' with their unescaped counterparts. - * @param str HTML escaped string. - * @return `str` Raw string. - **/ - unescape(str: string): string; - - /** - * If the value of the named property is a function then invoke it; otherwise, return it. - * @param object Object to maybe invoke function `property` on. - * @param property The function by name to invoke on `object`. - * @param defaultValue The value to be returned in case `property` doesn't exist or is undefined. - * @return The result of invoking the function `property` on `object. - **/ - result(object: any, property: string, defaultValue?:any): any; - - /** - * Compiles JavaScript templates into functions that can be evaluated for rendering. Useful - * for rendering complicated bits of HTML from JSON data sources. Template functions can both - * interpolate variables, using <%= ... %>, as well as execute arbitrary JavaScript code, with - * <% ... %>. If you wish to interpolate a value, and have it be HTML-escaped, use <%- ... %> When - * you evaluate a template function, pass in a data object that has properties corresponding to - * the template's free variables. If you're writing a one-off, you can pass the data object as - * the second parameter to template in order to render immediately instead of returning a template - * function. The settings argument should be a hash containing any _.templateSettings that should - * be overridden. - * @param templateString Underscore HTML template. - * @param data Data to use when compiling `templateString`. - * @param settings Settings to use while compiling. - * @return Returns the compiled Underscore HTML template. - **/ - template(templateString: string, settings?: _.TemplateSettings): (...data: any[]) => string; - - /** - * By default, Underscore uses ERB-style template delimiters, change the - * following template settings to use alternative delimiters. - **/ - templateSettings: _.TemplateSettings; - - /** - * Returns an integer timestamp for the current time, using the fastest method available in the runtime. Useful for implementing timing/animation functions. - **/ - now(): number; - - /* ********** - * Chaining * - *********** */ - - /** - * Returns a wrapped object. Calling methods on this object will continue to return wrapped objects - * until value() is used. - * @param obj Object to chain. - * @return Wrapped `obj`. - **/ - chain(obj: T[]): _Chain; - chain(obj: _.Dictionary): _Chain; - chain(obj: T): _Chain; -} - -interface Underscore { - - /* ************* - * Collections * - ************* */ - - /** - * Wrapped type `any[]`. - * @see _.each - **/ - each(iterator: _.ListIterator, context?: any): T[]; - - /** - * @see _.each - **/ - each(iterator: _.ObjectIterator, context?: any): T[]; - - /** - * @see _.each - **/ - forEach(iterator: _.ListIterator, context?: any): T[]; - - /** - * @see _.each - **/ - forEach(iterator: _.ObjectIterator, context?: any): T[]; - - /** - * Wrapped type `any[]`. - * @see _.map - **/ - map(iterator: _.ListIterator, context?: any): TResult[]; - - /** - * Wrapped type `any[]`. - * @see _.map - **/ - map(iterator: _.ObjectIterator, context?: any): TResult[]; - - /** - * @see _.map - **/ - collect(iterator: _.ListIterator, context?: any): TResult[]; - - /** - * @see _.map - **/ - collect(iterator: _.ObjectIterator, context?: any): TResult[]; - - /** - * Wrapped type `any[]`. - * @see _.reduce - **/ - reduce(iterator: _.MemoIterator, memo?: TResult, context?: any): TResult; - - /** - * @see _.reduce - **/ - inject(iterator: _.MemoIterator, memo?: TResult, context?: any): TResult; - - /** - * @see _.reduce - **/ - foldl(iterator: _.MemoIterator, memo?: TResult, context?: any): TResult; - - /** - * Wrapped type `any[]`. - * @see _.reduceRight - **/ - reduceRight(iterator: _.MemoIterator, memo?: TResult, context?: any): TResult; - - /** - * @see _.reduceRight - **/ - foldr(iterator: _.MemoIterator, memo?: TResult, context?: any): TResult; - - /** - * Wrapped type `any[]`. - * @see _.find - **/ - find(iterator: _.ListIterator|_.ObjectIterator, context?: any): T; - - /** - * @see _.find - **/ - find(interator: U): T; - - /** - * @see _.find - **/ - find(interator: string): T; - - /** - * @see _.find - **/ - detect(iterator: _.ListIterator|_.ObjectIterator, context?: any): T; - - /** - * @see _.find - **/ - detect(interator?: U): T; - - /** - * @see _.find - **/ - detect(interator?: string): T; - - /** - * Wrapped type `any[]`. - * @see _.filter - **/ - filter(iterator: _.ListIterator, context?: any): T[]; - - /** - * @see _.filter - **/ - select(iterator: _.ListIterator, context?: any): T[]; - - /** - * Wrapped type `any[]`. - * @see _.where - **/ - where(properties: U): T[]; - - /** - * Wrapped type `any[]`. - * @see _.findWhere - **/ - findWhere(properties: U): T; - - /** - * Wrapped type `any[]`. - * @see _.reject - **/ - reject(iterator: _.ListIterator, context?: any): T[]; - - /** - * Wrapped type `any[]`. - * @see _.all - **/ - all(iterator?: _.ListIterator, context?: any): boolean; - - /** - * @see _.all - **/ - every(iterator?: _.ListIterator, context?: any): boolean; - - /** - * Wrapped type `any[]`. - * @see _.any - **/ - any(iterator?: _.ListIterator, context?: any): boolean; - - /** - * @see _.any - **/ - some(iterator?: _.ListIterator, context?: any): boolean; - - /** - * Wrapped type `any[]`. - * @see _.contains - **/ - contains(value: T): boolean; - - /** - * Alias for 'contains'. - * @see contains - **/ - include(value: T): boolean; - - /** - * Wrapped type `any[]`. - * @see _.invoke - **/ - invoke(methodName: string, ...arguments: any[]): any; - - /** - * Wrapped type `any[]`. - * @see _.pluck - **/ - pluck(propertyName: string): any[]; - - /** - * Wrapped type `number[]`. - * @see _.max - **/ - max(): number; - - /** - * Wrapped type `any[]`. - * @see _.max - **/ - max(iterator: _.ListIterator, context?: any): T; - - /** - * Wrapped type `any[]`. - * @see _.max - **/ - max(iterator?: _.ListIterator, context?: any): T; - - /** - * Wrapped type `number[]`. - * @see _.min - **/ - min(): number; - - /** - * Wrapped type `any[]`. - * @see _.min - **/ - min(iterator: _.ListIterator, context?: any): T; - - /** - * Wrapped type `any[]`. - * @see _.min - **/ - min(iterator?: _.ListIterator, context?: any): T; - - /** - * Wrapped type `any[]`. - * @see _.sortBy - **/ - sortBy(iterator?: _.ListIterator, context?: any): T[]; - - /** - * Wrapped type `any[]`. - * @see _.sortBy - **/ - sortBy(iterator: string, context?: any): T[]; - - /** - * Wrapped type `any[]`. - * @see _.groupBy - **/ - groupBy(iterator?: _.ListIterator, context?: any): _.Dictionary<_.List>; - - /** - * Wrapped type `any[]`. - * @see _.groupBy - **/ - groupBy(iterator: string, context?: any): _.Dictionary; - - /** - * Wrapped type `any[]`. - * @see _.indexBy - **/ - indexBy(iterator: _.ListIterator, context?: any): _.Dictionary; - - /** - * Wrapped type `any[]`. - * @see _.indexBy - **/ - indexBy(iterator: string, context?: any): _.Dictionary; - - /** - * Wrapped type `any[]`. - * @see _.countBy - **/ - countBy(iterator?: _.ListIterator, context?: any): _.Dictionary; - - /** - * Wrapped type `any[]`. - * @see _.countBy - **/ - countBy(iterator: string, context?: any): _.Dictionary; - - /** - * Wrapped type `any[]`. - * @see _.shuffle - **/ - shuffle(): T[]; - - /** - * Wrapped type `any[]`. - * @see _.sample - **/ - sample(n: number): T[]; - - /** - * @see _.sample - **/ - sample(): T; - - /** - * Wrapped type `any`. - * @see _.toArray - **/ - toArray(): T[]; - - /** - * Wrapped type `any`. - * @see _.size - **/ - size(): number; - - /********* - * Arrays * - **********/ - - /** - * Wrapped type `any[]`. - * @see _.first - **/ - first(): T; - - /** - * Wrapped type `any[]`. - * @see _.first - **/ - first(n: number): T[]; - - /** - * @see _.first - **/ - head(): T; - - /** - * @see _.first - **/ - head(n: number): T[]; - - /** - * @see _.first - **/ - take(): T; - - /** - * @see _.first - **/ - take(n: number): T[]; - - /** - * Wrapped type `any[]`. - * @see _.initial - **/ - initial(n?: number): T[]; - - /** - * Wrapped type `any[]`. - * @see _.last - **/ - last(): T; - - /** - * Wrapped type `any[]`. - * @see _.last - **/ - last(n: number): T[]; - - /** - * Wrapped type `any[]`. - * @see _.rest - **/ - rest(n?: number): T[]; - - /** - * @see _.rest - **/ - tail(n?: number): T[]; - - /** - * @see _.rest - **/ - drop(n?: number): T[]; - - /** - * Wrapped type `any[]`. - * @see _.compact - **/ - compact(): T[]; - - /** - * Wrapped type `any`. - * @see _.flatten - **/ - flatten(shallow?: boolean): any[]; - - /** - * Wrapped type `any[]`. - * @see _.without - **/ - without(...values: T[]): T[]; - - /** - * Wrapped type `any[]`. - * @see _.partition - **/ - partition(iterator: _.ListIterator, context?: any): T[][]; - - /** - * Wrapped type `any[][]`. - * @see _.union - **/ - union(...arrays: _.List[]): T[]; - - /** - * Wrapped type `any[][]`. - * @see _.intersection - **/ - intersection(...arrays: _.List[]): T[]; - - /** - * Wrapped type `any[]`. - * @see _.difference - **/ - difference(...others: _.List[]): T[]; - - /** - * Wrapped type `any[]`. - * @see _.uniq - **/ - uniq(isSorted?: boolean, iterator?: _.ListIterator): T[]; - - /** - * Wrapped type `any[]`. - * @see _.uniq - **/ - uniq(iterator?: _.ListIterator, context?: any): T[]; - - /** - * @see _.uniq - **/ - unique(isSorted?: boolean, iterator?: _.ListIterator): T[]; - - /** - * @see _.uniq - **/ - unique(iterator?: _.ListIterator, context?: any): T[]; - - /** - * Wrapped type `any[][]`. - * @see _.zip - **/ - zip(...arrays: any[][]): any[][]; - - /** - * Wrapped type `any[][]`. - * @see _.unzip - **/ - unzip(...arrays: any[][]): any[][]; - - /** - * Wrapped type `any[][]`. - * @see _.object - **/ - object(...keyValuePairs: any[][]): any; - - /** - * @see _.object - **/ - object(values?: any): any; - - /** - * Wrapped type `any[]`. - * @see _.indexOf - **/ - indexOf(value: T, isSorted?: boolean): number; - - /** - * @see _.indexOf - **/ - indexOf(value: T, startFrom: number): number; - - /** - * Wrapped type `any[]`. - * @see _.lastIndexOf - **/ - lastIndexOf(value: T, from?: number): number; - - /** - * @see _.findIndex - **/ - findIndex(array: _.List, predicate: _.ListIterator | {}, context?: any): number; - - /** - * @see _.findLastIndex - **/ - findLastIndex(array: _.List, predicate: _.ListIterator | {}, context?: any): number; - - /** - * Wrapped type `any[]`. - * @see _.sortedIndex - **/ - sortedIndex(value: T, iterator?: (x: T) => any, context?: any): number; - - /** - * Wrapped type `number`. - * @see _.range - **/ - range(stop: number, step?: number): number[]; - - /** - * Wrapped type `number`. - * @see _.range - **/ - range(): number[]; - - /* *********** - * Functions * - ************ */ - - /** - * Wrapped type `Function`. - * @see _.bind - **/ - bind(object: any, ...arguments: any[]): Function; - - /** - * Wrapped type `object`. - * @see _.bindAll - **/ - bindAll(...methodNames: string[]): any; - - /** - * Wrapped type `Function`. - * @see _.partial - **/ - partial(...arguments: any[]): Function; - - /** - * Wrapped type `Function`. - * @see _.memoize - **/ - memoize(hashFn?: (n: any) => string): Function; - - /** - * Wrapped type `Function`. - * @see _.defer - **/ - defer(...arguments: any[]): void; - - /** - * Wrapped type `Function`. - * @see _.delay - **/ - delay(wait: number, ...arguments: any[]): any; - - /** - * @see _.delay - **/ - delay(...arguments: any[]): any; - - /** - * Wrapped type `Function`. - * @see _.throttle - **/ - throttle(wait: number, options?: _.ThrottleSettings): Function; - - /** - * Wrapped type `Function`. - * @see _.debounce - **/ - debounce(wait: number, immediate?: boolean): Function; - - /** - * Wrapped type `Function`. - * @see _.once - **/ - once(): Function; - - /** - * Wrapped type `number`. - * @see _.after - **/ - after(fn: Function): Function; - - /** - * Wrapped type `number`. - * @see _.before - **/ - before(fn: Function): Function; - - /** - * Wrapped type `Function`. - * @see _.wrap - **/ - wrap(wrapper: Function): () => Function; - - /** - * Wrapped type `Function`. - * @see _.negate - **/ - negate(): boolean; - - /** - * Wrapped type `Function[]`. - * @see _.compose - **/ - compose(...functions: Function[]): Function; - - /********* * - * Objects * - ********** */ - - /** - * Wrapped type `object`. - * @see _.keys - **/ - keys(): string[]; - - /** - * Wrapped type `object`. - * @see _.allKeys - **/ - allKeys(): string[]; - - /** - * Wrapped type `object`. - * @see _.values - **/ - values(): T[]; - - /** - * Wrapped type `object`. - * @see _.pairs - **/ - pairs(): any[][]; - - /** - * Wrapped type `object`. - * @see _.invert - **/ - invert(): any; - - /** - * Wrapped type `object`. - * @see _.functions - **/ - functions(): string[]; - - /** - * @see _.functions - **/ - methods(): string[]; - - /** - * Wrapped type `object`. - * @see _.extend - **/ - extend(...sources: any[]): any; - - /** - * Wrapped type `object`. - * @see _.pick - **/ - pick(...keys: any[]): any; - pick(keys: any[]): any; - pick(fn: (value: any, key: any, object: any) => any): any; - - /** - * Wrapped type `object`. - * @see _.omit - **/ - omit(...keys: string[]): any; - omit(keys: string[]): any; - omit(fn: Function): any; - - /** - * Wrapped type `object`. - * @see _.defaults - **/ - defaults(...defaults: any[]): any; - - /** - * Wrapped type `any[]`. - * @see _.clone - **/ - clone(): T; - - /** - * Wrapped type `object`. - * @see _.tap - **/ - tap(interceptor: (...as: any[]) => any): any; - - /** - * Wrapped type `object`. - * @see _.has - **/ - has(key: string): boolean; - - /** - * Wrapped type `any[]`. - * @see _.matches - **/ - matches(): _.ListIterator; - - /** - * Wrapped type `string`. - * @see _.property - **/ - property(): (object: Object) => any; - - /** - * Wrapped type `object`. - * @see _.propertyOf - **/ - propertyOf(): (key: string) => any; - - /** - * Wrapped type `object`. - * @see _.isEqual - **/ - isEqual(other: any): boolean; - - /** - * Wrapped type `object`. - * @see _.isEmpty - **/ - isEmpty(): boolean; - - /** - * Wrapped type `object`. - * @see _.isMatch - **/ - isMatch(): boolean; - - /** - * Wrapped type `object`. - * @see _.isElement - **/ - isElement(): boolean; - - /** - * Wrapped type `object`. - * @see _.isArray - **/ - isArray(): boolean; - - /** - * Wrapped type `object`. - * @see _.isObject - **/ - isObject(): boolean; - - /** - * Wrapped type `object`. - * @see _.isArguments - **/ - isArguments(): boolean; - - /** - * Wrapped type `object`. - * @see _.isFunction - **/ - isFunction(): boolean; - - /** - * Wrapped type `object`. - * @see _.isError - **/ - isError(): boolean; - - /** - * Wrapped type `object`. - * @see _.isString - **/ - isString(): boolean; - - /** - * Wrapped type `object`. - * @see _.isNumber - **/ - isNumber(): boolean; - - /** - * Wrapped type `object`. - * @see _.isFinite - **/ - isFinite(): boolean; - - /** - * Wrapped type `object`. - * @see _.isBoolean - **/ - isBoolean(): boolean; - - /** - * Wrapped type `object`. - * @see _.isDate - **/ - isDate(): boolean; - - /** - * Wrapped type `object`. - * @see _.isRegExp - **/ - isRegExp(): boolean; - - /** - * Wrapped type `object`. - * @see _.isNaN - **/ - isNaN(): boolean; - - /** - * Wrapped type `object`. - * @see _.isNull - **/ - isNull(): boolean; - - /** - * Wrapped type `object`. - * @see _.isUndefined - **/ - isUndefined(): boolean; - - /********* * - * Utility * - ********** */ - - /** - * Wrapped type `any`. - * @see _.identity - **/ - identity(): any; - - /** - * Wrapped type `any`. - * @see _.constant - **/ - constant(): () => T; - - /** - * Wrapped type `any`. - * @see _.noop - **/ - noop(): void; - - /** - * Wrapped type `number`. - * @see _.times - **/ - times(iterator: (n: number) => TResult, context?: any): TResult[]; - - /** - * Wrapped type `number`. - * @see _.random - **/ - random(): number; - /** - * Wrapped type `number`. - * @see _.random - **/ - random(max: number): number; - - /** - * Wrapped type `object`. - * @see _.mixin - **/ - mixin(): void; - - /** - * Wrapped type `string|Function|Object`. - * @see _.iteratee - **/ - iteratee(context?: any, argCount?: number): Function; - - /** - * Wrapped type `string`. - * @see _.uniqueId - **/ - uniqueId(): string; - - /** - * Wrapped type `string`. - * @see _.escape - **/ - escape(): string; - - /** - * Wrapped type `string`. - * @see _.unescape - **/ - unescape(): string; - - /** - * Wrapped type `object`. - * @see _.result - **/ - result(property: string, defaultValue?:any): any; - - /** - * Wrapped type `string`. - * @see _.template - **/ - template(settings?: _.TemplateSettings): (...data: any[]) => string; - - /********** * - * Chaining * - *********** */ - - /** - * Wrapped type `any`. - * @see _.chain - **/ - chain(): _Chain; - - /** - * Wrapped type `any`. - * Extracts the value of a wrapped object. - * @return Value of the wrapped object. - **/ - value(): TResult; -} - -interface _Chain { - - /* ************* - * Collections * - ************* */ - - /** - * Wrapped type `any[]`. - * @see _.each - **/ - each(iterator: _.ListIterator, context?: any): _Chain; - - /** - * @see _.each - **/ - each(iterator: _.ObjectIterator, context?: any): _Chain; - - /** - * @see _.each - **/ - forEach(iterator: _.ListIterator, context?: any): _Chain; - - /** - * @see _.each - **/ - forEach(iterator: _.ObjectIterator, context?: any): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.map - **/ - map(iterator: _.ListIterator, context?: any): _ChainOfArrays; - - /** - * Wrapped type `any[]`. - * @see _.map - **/ - map(iterator: _.ListIterator, context?: any): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.map - **/ - map(iterator: _.ObjectIterator, context?: any): _ChainOfArrays; - - /** - * Wrapped type `any[]`. - * @see _.map - **/ - map(iterator: _.ObjectIterator, context?: any): _Chain; - - /** - * @see _.map - **/ - collect(iterator: _.ListIterator, context?: any): _Chain; - - /** - * @see _.map - **/ - collect(iterator: _.ObjectIterator, context?: any): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.reduce - **/ - reduce(iterator: _.MemoIterator, memo?: TResult, context?: any): _ChainSingle; - - /** - * @see _.reduce - **/ - inject(iterator: _.MemoIterator, memo?: TResult, context?: any): _ChainSingle; - - /** - * @see _.reduce - **/ - foldl(iterator: _.MemoIterator, memo?: TResult, context?: any): _ChainSingle; - - /** - * Wrapped type `any[]`. - * @see _.reduceRight - **/ - reduceRight(iterator: _.MemoIterator, memo?: TResult, context?: any): _ChainSingle; - - /** - * @see _.reduceRight - **/ - foldr(iterator: _.MemoIterator, memo?: TResult, context?: any): _ChainSingle; - - /** - * Wrapped type `any[]`. - * @see _.find - **/ - find(iterator: _.ListIterator|_.ObjectIterator, context?: any): _ChainSingle; - - /** - * @see _.find - **/ - find(interator: U): _ChainSingle; - - /** - * @see _.find - **/ - find(interator: string): _ChainSingle; - - /** - * @see _.find - **/ - detect(iterator: _.ListIterator|_.ObjectIterator, context?: any): _ChainSingle; - - /** - * @see _.find - **/ - detect(interator: U): _ChainSingle; - - /** - * @see _.find - **/ - detect(interator: string): _ChainSingle; - - /** - * Wrapped type `any[]`. - * @see _.filter - **/ - filter(iterator: _.ListIterator, context?: any): _Chain; - - /** - * @see _.filter - **/ - select(iterator: _.ListIterator, context?: any): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.where - **/ - where(properties: U): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.findWhere - **/ - findWhere(properties: U): _ChainSingle; - - /** - * Wrapped type `any[]`. - * @see _.reject - **/ - reject(iterator: _.ListIterator, context?: any): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.all - **/ - all(iterator?: _.ListIterator, context?: any): _Chain; - - /** - * @see _.all - **/ - every(iterator?: _.ListIterator, context?: any): _ChainSingle; - - /** - * Wrapped type `any[]`. - * @see _.any - **/ - any(iterator?: _.ListIterator, context?: any): _ChainSingle; - - /** - * @see _.any - **/ - some(iterator?: _.ListIterator, context?: any): _ChainSingle; - - /** - * Wrapped type `any[]`. - * @see _.contains - **/ - contains(value: T): _ChainSingle; - - /** - * Alias for 'contains'. - * @see contains - **/ - include(value: T): _ChainSingle; - - /** - * Wrapped type `any[]`. - * @see _.invoke - **/ - invoke(methodName: string, ...arguments: any[]): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.pluck - **/ - pluck(propertyName: string): _Chain; - - /** - * Wrapped type `number[]`. - * @see _.max - **/ - max(): _ChainSingle; - - /** - * Wrapped type `any[]`. - * @see _.max - **/ - max(iterator: _.ListIterator, context?: any): _ChainSingle; - - /** - * Wrapped type `any[]`. - * @see _.max - **/ - max(iterator?: _.ListIterator, context?: any): _ChainSingle; - - /** - * Wrapped type `number[]`. - * @see _.min - **/ - min(): _ChainSingle; - - /** - * Wrapped type `any[]`. - * @see _.min - **/ - min(iterator: _.ListIterator, context?: any): _ChainSingle; - - /** - * Wrapped type `any[]`. - * @see _.min - **/ - min(iterator?: _.ListIterator, context?: any): _ChainSingle; - - /** - * Wrapped type `any[]`. - * @see _.sortBy - **/ - sortBy(iterator?: _.ListIterator, context?: any): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.sortBy - **/ - sortBy(iterator: string, context?: any): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.groupBy - **/ - groupBy(iterator?: _.ListIterator, context?: any): _ChainOfArrays; - - /** - * Wrapped type `any[]`. - * @see _.groupBy - **/ - groupBy(iterator: string, context?: any): _ChainOfArrays; - - /** - * Wrapped type `any[]`. - * @see _.indexBy - **/ - indexBy(iterator: _.ListIterator, context?: any): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.indexBy - **/ - indexBy(iterator: string, context?: any): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.countBy - **/ - countBy(iterator?: _.ListIterator, context?: any): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.countBy - **/ - countBy(iterator: string, context?: any): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.shuffle - **/ - shuffle(): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.sample - **/ - sample(n: number): _Chain; - - /** - * @see _.sample - **/ - sample(): _Chain; - - /** - * Wrapped type `any`. - * @see _.toArray - **/ - toArray(): _Chain; - - /** - * Wrapped type `any`. - * @see _.size - **/ - size(): _ChainSingle; - - /********* - * Arrays * - **********/ - - /** - * Wrapped type `any[]`. - * @see _.first - **/ - first(): _ChainSingle; - - /** - * Wrapped type `any[]`. - * @see _.first - **/ - first(n: number): _Chain; - - /** - * @see _.first - **/ - head(): _Chain; - - /** - * @see _.first - **/ - head(n: number): _Chain; - - /** - * @see _.first - **/ - take(): _Chain; - - /** - * @see _.first - **/ - take(n: number): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.initial - **/ - initial(n?: number): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.last - **/ - last(): _ChainSingle; - - /** - * Wrapped type `any[]`. - * @see _.last - **/ - last(n: number): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.rest - **/ - rest(n?: number): _Chain; - - /** - * @see _.rest - **/ - tail(n?: number): _Chain; - - /** - * @see _.rest - **/ - drop(n?: number): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.compact - **/ - compact(): _Chain; - - /** - * Wrapped type `any`. - * @see _.flatten - **/ - flatten(shallow?: boolean): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.without - **/ - without(...values: T[]): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.partition - **/ - partition(iterator: _.ListIterator, context?: any): _Chain; - - /** - * Wrapped type `any[][]`. - * @see _.union - **/ - union(...arrays: _.List[]): _Chain; - - /** - * Wrapped type `any[][]`. - * @see _.intersection - **/ - intersection(...arrays: _.List[]): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.difference - **/ - difference(...others: _.List[]): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.uniq - **/ - uniq(isSorted?: boolean, iterator?: _.ListIterator): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.uniq - **/ - uniq(iterator?: _.ListIterator, context?: any): _Chain; - - /** - * @see _.uniq - **/ - unique(isSorted?: boolean, iterator?: _.ListIterator): _Chain; - - /** - * @see _.uniq - **/ - unique(iterator?: _.ListIterator, context?: any): _Chain; - - /** - * Wrapped type `any[][]`. - * @see _.zip - **/ - zip(...arrays: any[][]): _Chain; - - /** - * Wrapped type `any[][]`. - * @see _.unzip - **/ - unzip(...arrays: any[][]): _Chain; - - /** - * Wrapped type `any[][]`. - * @see _.object - **/ - object(...keyValuePairs: any[][]): _Chain; - - /** - * @see _.object - **/ - object(values?: any): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.indexOf - **/ - indexOf(value: T, isSorted?: boolean): _ChainSingle; - - /** - * @see _.indexOf - **/ - indexOf(value: T, startFrom: number): _ChainSingle; - - /** - * Wrapped type `any[]`. - * @see _.lastIndexOf - **/ - lastIndexOf(value: T, from?: number): _ChainSingle; - - /** - * @see _.findIndex - **/ - findIndex(predicate: _.ListIterator | {}, context?: any): _ChainSingle; - - /** - * @see _.findLastIndex - **/ - findLastIndex(predicate: _.ListIterator | {}, context?: any): _ChainSingle; - - /** - * Wrapped type `any[]`. - * @see _.sortedIndex - **/ - sortedIndex(value: T, iterator?: (x: T) => any, context?: any): _Chain; - - /** - * Wrapped type `number`. - * @see _.range - **/ - range(stop: number, step?: number): _Chain; - - /** - * Wrapped type `number`. - * @see _.range - **/ - range(): _Chain; - - /* *********** - * Functions * - ************ */ - - /** - * Wrapped type `Function`. - * @see _.bind - **/ - bind(object: any, ...arguments: any[]): _Chain; - - /** - * Wrapped type `object`. - * @see _.bindAll - **/ - bindAll(...methodNames: string[]): _Chain; - - /** - * Wrapped type `Function`. - * @see _.partial - **/ - partial(...arguments: any[]): _Chain; - - /** - * Wrapped type `Function`. - * @see _.memoize - **/ - memoize(hashFn?: (n: any) => string): _Chain; - - /** - * Wrapped type `Function`. - * @see _.defer - **/ - defer(...arguments: any[]): _Chain; - - /** - * Wrapped type `Function`. - * @see _.delay - **/ - delay(wait: number, ...arguments: any[]): _Chain; - - /** - * @see _.delay - **/ - delay(...arguments: any[]): _Chain; - - /** - * Wrapped type `Function`. - * @see _.throttle - **/ - throttle(wait: number, options?: _.ThrottleSettings): _Chain; - - /** - * Wrapped type `Function`. - * @see _.debounce - **/ - debounce(wait: number, immediate?: boolean): _Chain; - - /** - * Wrapped type `Function`. - * @see _.once - **/ - once(): _Chain; - - /** - * Wrapped type `number`. - * @see _.after - **/ - after(func: Function): _Chain; - - /** - * Wrapped type `number`. - * @see _.before - **/ - before(fn: Function): _Chain; - - /** - * Wrapped type `Function`. - * @see _.wrap - **/ - wrap(wrapper: Function): () => _Chain; - - /** - * Wrapped type `Function`. - * @see _.negate - **/ - negate(): _Chain; - - /** - * Wrapped type `Function[]`. - * @see _.compose - **/ - compose(...functions: Function[]): _Chain; - - /********* * - * Objects * - ********** */ - - /** - * Wrapped type `object`. - * @see _.keys - **/ - keys(): _Chain; - - /** - * Wrapped type `object`. - * @see _.allKeys - **/ - allKeys(): _Chain; - - /** - * Wrapped type `object`. - * @see _.values - **/ - values(): _Chain; - - /** - * Wrapped type `object`. - * @see _.pairs - **/ - pairs(): _Chain; - - /** - * Wrapped type `object`. - * @see _.invert - **/ - invert(): _Chain; - - /** - * Wrapped type `object`. - * @see _.functions - **/ - functions(): _Chain; - - /** - * @see _.functions - **/ - methods(): _Chain; - - /** - * Wrapped type `object`. - * @see _.extend - **/ - extend(...sources: any[]): _Chain; - - /** - * Wrapped type `object`. - * @see _.pick - **/ - pick(...keys: any[]): _Chain; - pick(keys: any[]): _Chain; - pick(fn: (value: any, key: any, object: any) => any): _Chain; - - /** - * Wrapped type `object`. - * @see _.omit - **/ - omit(...keys: string[]): _Chain; - omit(keys: string[]): _Chain; - omit(iteratee: Function): _Chain; - - /** - * Wrapped type `object`. - * @see _.defaults - **/ - defaults(...defaults: any[]): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.clone - **/ - clone(): _Chain; - - /** - * Wrapped type `object`. - * @see _.tap - **/ - tap(interceptor: (...as: any[]) => any): _Chain; - - /** - * Wrapped type `object`. - * @see _.has - **/ - has(key: string): _Chain; - - /** - * Wrapped type `any[]`. - * @see _.matches - **/ - matches(): _Chain; - - /** - * Wrapped type `string`. - * @see _.property - **/ - property(): _Chain; - - /** - * Wrapped type `object`. - * @see _.propertyOf - **/ - propertyOf(): _Chain; - - /** - * Wrapped type `object`. - * @see _.isEqual - **/ - isEqual(other: any): _Chain; - - /** - * Wrapped type `object`. - * @see _.isEmpty - **/ - isEmpty(): _Chain; - - /** - * Wrapped type `object`. - * @see _.isMatch - **/ - isMatch(): _Chain; - - /** - * Wrapped type `object`. - * @see _.isElement - **/ - isElement(): _Chain; - - /** - * Wrapped type `object`. - * @see _.isArray - **/ - isArray(): _Chain; - - /** - * Wrapped type `object`. - * @see _.isObject - **/ - isObject(): _Chain; - - /** - * Wrapped type `object`. - * @see _.isArguments - **/ - isArguments(): _Chain; - - /** - * Wrapped type `object`. - * @see _.isFunction - **/ - isFunction(): _Chain; - - /** - * Wrapped type `object`. - * @see _.isError - **/ - isError(): _Chain; - - /** - * Wrapped type `object`. - * @see _.isString - **/ - isString(): _Chain; - - /** - * Wrapped type `object`. - * @see _.isNumber - **/ - isNumber(): _Chain; - - /** - * Wrapped type `object`. - * @see _.isFinite - **/ - isFinite(): _Chain; - - /** - * Wrapped type `object`. - * @see _.isBoolean - **/ - isBoolean(): _Chain; - - /** - * Wrapped type `object`. - * @see _.isDate - **/ - isDate(): _Chain; - - /** - * Wrapped type `object`. - * @see _.isRegExp - **/ - isRegExp(): _Chain; - - /** - * Wrapped type `object`. - * @see _.isNaN - **/ - isNaN(): _Chain; - - /** - * Wrapped type `object`. - * @see _.isNull - **/ - isNull(): _Chain; - - /** - * Wrapped type `object`. - * @see _.isUndefined - **/ - isUndefined(): _Chain; - - /********* * - * Utility * - ********** */ - - /** - * Wrapped type `any`. - * @see _.identity - **/ - identity(): _Chain; - - /** - * Wrapped type `any`. - * @see _.constant - **/ - constant(): _Chain; - - /** - * Wrapped type `any`. - * @see _.noop - **/ - noop(): _Chain; - - /** - * Wrapped type `number`. - * @see _.times - **/ - times(iterator: (n: number) => TResult, context?: any): _Chain; - - /** - * Wrapped type `number`. - * @see _.random - **/ - random(): _Chain; - /** - * Wrapped type `number`. - * @see _.random - **/ - random(max: number): _Chain; - - /** - * Wrapped type `object`. - * @see _.mixin - **/ - mixin(): _Chain; - - /** - * Wrapped type `string|Function|Object`. - * @see _.iteratee - **/ - iteratee(context?: any, argCount?: number): _Chain; - - /** - * Wrapped type `string`. - * @see _.uniqueId - **/ - uniqueId(): _Chain; - - /** - * Wrapped type `string`. - * @see _.escape - **/ - escape(): _Chain; - - /** - * Wrapped type `string`. - * @see _.unescape - **/ - unescape(): _Chain; - - /** - * Wrapped type `object`. - * @see _.result - **/ - result(property: string, defaultValue?:any): _Chain; - - /** - * Wrapped type `string`. - * @see _.template - **/ - template(settings?: _.TemplateSettings): (...data: any[]) => _Chain; - - /************* * - * Array proxy * - ************** */ - - /** - * Returns a new array comprised of the array on which it is called - * joined with the array(s) and/or value(s) provided as arguments. - * @param arr Arrays and/or values to concatenate into a new array. See the discussion below for details. - * @return A new array comprised of the array on which it is called - **/ - concat(...arr: Array): _Chain; - - /** - * Join all elements of an array into a string. - * @param separator Optional. Specifies a string to separate each element of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma. - * @return The string conversions of all array elements joined into one string. - **/ - join(separator?: any): _ChainSingle; - - /** - * Removes the last element from an array and returns that element. - * @return Returns the popped element. - **/ - pop(): _ChainSingle; - - /** - * Adds one or more elements to the end of an array and returns the new length of the array. - * @param item The elements to add to the end of the array. - * @return The array with the element added to the end. - **/ - push(...item: Array): _Chain; - - /** - * Reverses an array in place. The first array element becomes the last and the last becomes the first. - * @return The reversed array. - **/ - reverse(): _Chain; - - /** - * Removes the first element from an array and returns that element. This method changes the length of the array. - * @return The shifted element. - **/ - shift(): _ChainSingle; - - /** - * Returns a shallow copy of a portion of an array into a new array object. - * @param start Zero-based index at which to begin extraction. - * @param end Optional. Zero-based index at which to end extraction. slice extracts up to but not including end. - * @return A shallow copy of a portion of an array into a new array object. - **/ - slice(start: number, end?: number): _Chain; - - /** - * Sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points. - * @param compareFn Optional. Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element. - * @return The sorted array. - **/ - sort(compareFn: (a: T, b: T) => boolean): _Chain; - - /** - * Changes the content of an array by removing existing elements and/or adding new elements. - * @param index Index at which to start changing the array. If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end. - * @param quantity An integer indicating the number of old array elements to remove. If deleteCount is 0, no elements are removed. In this case, you should specify at least one new element. If deleteCount is greater than the number of elements left in the array starting at index, then all of the elements through the end of the array will be deleted. - * @param items The element to add to the array. If you don't specify any elements, splice will only remove elements from the array. - * @return An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. - **/ - splice(index: number, quantity: number, ...items: Array): _Chain; - - /** - * A string representing the specified array and its elements. - * @return A string representing the specified array and its elements. - **/ - toString(): _ChainSingle; - - /** - * Adds one or more elements to the beginning of an array and returns the new length of the array. - * @param items The elements to add to the front of the array. - * @return The array with the element added to the beginning. - **/ - unshift(...items: Array): _Chain; - - /********** * - * Chaining * - *********** */ - - /** - * Wrapped type `any`. - * @see _.chain - **/ - chain(): _Chain; - - /** - * Wrapped type `any`. - * @see _.value - **/ - value(): T[]; -} -interface _ChainSingle { - value(): T; -} -interface _ChainOfArrays extends _Chain { - flatten(shallow?: boolean): _Chain; -} - -declare var _: UnderscoreStatic; - -declare module "underscore" { - export = _; -} \ No newline at end of file diff --git a/typings/globals/underscore/typings.json b/typings/globals/underscore/typings.json deleted file mode 100644 index 150c5a8..0000000 --- a/typings/globals/underscore/typings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "resolution": "main", - "tree": { - "src": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/3c935c7abcfc1f896b1670cd229f71e9c5ad9187/underscore/underscore.d.ts", - "raw": "registry:dt/underscore#1.7.0+20160720002543", - "typings": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/3c935c7abcfc1f896b1670cd229f71e9c5ad9187/underscore/underscore.d.ts" - } -} diff --git a/typings/index.d.ts b/typings/index.d.ts deleted file mode 100644 index 1abab8e..0000000 --- a/typings/index.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -/// -/// diff --git a/webpack.config.js b/webpack.config.js deleted file mode 100644 index 7813b63..0000000 --- a/webpack.config.js +++ /dev/null @@ -1,48 +0,0 @@ -module.exports = { - entry: "./src/index", - - output : { - filename : './nestedtypes.js', - library : "Nested", - libraryTarget : 'umd' - }, - - devtool : 'source-map', - - resolve : { - modulesDirectories : [ 'node_modules', 'src' ], - extensions : [ '.ts', '.js' ] - }, - - externals : [ - { - 'jquery' : { - commonjs : 'jquery', - commonjs2 : 'jquery', - amd : 'jquery', - root : '$' - }, - - 'underscore' : { - commonjs : 'underscore', - commonjs2 : 'underscore', - amd : 'underscore', - root : '_' - } - } - ], - - module: { - loaders: [ - { - test: /\.[tj]sx?$/, - /*exclude: /(node_modules|bower_components)/,*/ - loader: 'ts' - } - ], - - preLoaders : [ - { test: /\.js$/, loader: "source-map-loader" } - ] - } -};