diff --git a/README.md b/README.md index 0e8aeb0..a3a2065 100644 --- a/README.md +++ b/README.md @@ -3,4 +3,4 @@ To run it, launch dotnet command : `dotnet run` As it connects to [chatle server](https://github.com/aguacongas/chatle/tree/develop/src/chatle), you'll need to run the server [![Travis Build Status](https://travis-ci.org/aguacongas/chatle.aurelia.svg?branch=develop)](https://travis-ci.org/aguacongas/chatle.aurelia) [![AppVeyor Build status](https://ci.appveyor.com/api/projects/status/github/aguacongas/chatle.aurelia?svg=true&retina=true)](https://ci.appveyor.com/project/aguacongas/chatle-aurelia) -[![Coverage Status](https://coveralls.io/repos/github/aguacongas/chatle.aurelia/badge.svg?branch=develop&service=github)](https://coveralls.io/github/aguacongas/chatle.aurelia?branch=develop) \ No newline at end of file +[![Coverage Status](https://coveralls.io/repos/github/aguacongas/chatle.aurelia/badge.svg)](https://coveralls.io/github/aguacongas/chatle.aurelia) diff --git a/docs/favicon.ico b/docs/favicon.ico new file mode 100644 index 0000000..2a4d144 Binary files /dev/null and b/docs/favicon.ico differ diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000..56ad7d4 --- /dev/null +++ b/docs/index.html @@ -0,0 +1,14 @@ + + + + Chatle + + + + + + + + + + diff --git a/docs/scripts/app-bundle.js b/docs/scripts/app-bundle.js new file mode 100644 index 0000000..753a404 --- /dev/null +++ b/docs/scripts/app-bundle.js @@ -0,0 +1,2803 @@ +define('environment',["require", "exports"], function (require, exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = { + debug: true, + testing: true, + apiBaseUrl: 'http://localhost:5000' + }; +}); + +define('config/settings',["require", "exports"], function (require, exports) { + "use strict"; + var Settings = (function () { + function Settings() { + this.apiBaseUrl = 'http://localhost:5000'; + this.userAPI = '/api/users'; + this.convAPI = '/api/chat/conv'; + this.chatAPI = '/api/chat'; + this.accountdAPI = "/account"; + } + return Settings; + }()); + exports.Settings = Settings; +}); + +define('services/state',["require", "exports"], function (require, exports) { + "use strict"; + var State = (function () { + function State() { + } + return State; + }()); + exports.State = State; +}); + +define('model/serviceError',["require", "exports"], function (require, exports) { + "use strict"; + var Key = (function () { + function Key() { + } + return Key; + }()); + var ErrorMessage = (function () { + function ErrorMessage() { + } + return ErrorMessage; + }()); + var ServiceError = (function () { + function ServiceError() { + } + return ServiceError; + }()); + exports.ServiceError = ServiceError; +}); + +define('model/attendee',["require", "exports"], function (require, exports) { + "use strict"; + var Attendee = (function () { + function Attendee(userId) { + this.userId = userId; + } + return Attendee; + }()); + exports.Attendee = Attendee; +}); + +define('model/message',["require", "exports"], function (require, exports) { + "use strict"; + var Message = (function () { + function Message() { + } + return Message; + }()); + exports.Message = Message; +}); + +define('model/user',["require", "exports"], function (require, exports) { + "use strict"; + var User = (function () { + function User() { + } + return User; + }()); + exports.User = User; +}); + +define('model/conversation',["require", "exports", './attendee'], function (require, exports, attendee_1) { + "use strict"; + var Conversation = (function () { + function Conversation(user) { + if (!user) { + return; + } + var attendees = new Array(); + attendees.push(new attendee_1.Attendee(user.id)); + this.attendees = attendees; + this.messages = new Array(); + this.isInitiatedByUser = true; + } + return Conversation; + }()); + exports.Conversation = Conversation; +}); + +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 __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define('services/helpers',["require", "exports", 'aurelia-framework', './state'], function (require, exports, aurelia_framework_1, state_1) { + "use strict"; + var Helpers = (function () { + function Helpers(state) { + this.state = state; + this.location = window.location; + } + Helpers.prototype.getError = function (error) { + var errors = error.content; + var se = errors[0]; + var e = new Error(se.errors[0].errorMessage); + e.name = se.key; + return e; + }; + Helpers.prototype.setConverationTitle = function (conversation) { + var _this = this; + if (conversation.title) { + return; + } + var title = ''; + conversation.attendees.forEach(function (attendee) { + if (attendee && attendee.userId && attendee.userId !== _this.state.userName) { + title += attendee.userId + ' '; + } + }); + conversation.title = title.trim(); + }; + Helpers.prototype.getUrlParameter = function (name) { + name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]'); + var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'); + var results = regex.exec(this.location.search); + return results === null ? undefined : decodeURIComponent(results[1].replace(/\+/g, ' ')); + }; + Helpers = __decorate([ + aurelia_framework_1.autoinject, + __metadata('design:paramtypes', [state_1.State]) + ], Helpers); + return Helpers; + }()); + exports.Helpers = Helpers; +}); + +define('events/connectionStateChanged',["require", "exports"], function (require, exports) { + "use strict"; + var ConnectionStateChanged = (function () { + function ConnectionStateChanged(state) { + this.state = state; + } + return ConnectionStateChanged; + }()); + exports.ConnectionStateChanged = ConnectionStateChanged; +}); + +define('events/conversationJoined',["require", "exports"], function (require, exports) { + "use strict"; + var ConversationJoined = (function () { + function ConversationJoined(conversation) { + this.conversation = conversation; + } + return ConversationJoined; + }()); + exports.ConversationJoined = ConversationJoined; +}); + +define('events/messageReceived',["require", "exports"], function (require, exports) { + "use strict"; + var MessageReceived = (function () { + function MessageReceived(message) { + this.message = message; + } + return MessageReceived; + }()); + exports.MessageReceived = MessageReceived; +}); + +define('events/userConnected',["require", "exports"], function (require, exports) { + "use strict"; + var UserConnected = (function () { + function UserConnected(user) { + this.user = user; + } + return UserConnected; + }()); + exports.UserConnected = UserConnected; +}); + +define('events/userDisconnected',["require", "exports"], function (require, exports) { + "use strict"; + var UserDisconnected = (function () { + function UserDisconnected(user) { + this.user = user; + } + return UserDisconnected; + }()); + exports.UserDisconnected = UserDisconnected; +}); + +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 __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define('services/chat.service',["require", "exports", 'aurelia-event-aggregator', 'aurelia-http-client', 'aurelia-framework', '../environment', '../config/settings', './helpers', './state', '../events/connectionStateChanged', '../events/conversationJoined', '../events/messageReceived', '../events/userConnected', '../events/userDisconnected'], function (require, exports, aurelia_event_aggregator_1, aurelia_http_client_1, aurelia_framework_1, environment_1, settings_1, helpers_1, state_1, connectionStateChanged_1, conversationJoined_1, messageReceived_1, userConnected_1, userDisconnected_1) { + "use strict"; + (function (ConnectionState) { + ConnectionState[ConnectionState["Connected"] = 1] = "Connected"; + ConnectionState[ConnectionState["Disconnected"] = 2] = "Disconnected"; + ConnectionState[ConnectionState["Error"] = 3] = "Error"; + })(exports.ConnectionState || (exports.ConnectionState = {})); + var ConnectionState = exports.ConnectionState; + var ChatService = (function () { + function ChatService(settings, ea, http, state, helpers) { + this.settings = settings; + this.ea = ea; + this.http = http; + this.state = state; + this.helpers = helpers; + this.currentState = ConnectionState.Disconnected; + } + ChatService.prototype.start = function () { + var _this = this; + var debug = environment_1.default.debug; + var hub = jQuery.connection.hub; + hub.logging = debug; + hub.url = this.settings.apiBaseUrl + '/signalr'; + var connection = jQuery.connection; + var chatHub = connection.chat; + chatHub.client.userConnected = function (user) { return _this.onUserConnected(user); }; + chatHub.client.userDisconnected = function (user) { return _this.onUserDisconnected(user); }; + chatHub.client.messageReceived = function (message) { return _this.onMessageReceived(message); }; + chatHub.client.joinConversation = function (conversation) { return _this.onJoinConversation(conversation); }; + if (debug) { + hub.stateChanged(function (change) { + var oldState, newState; + var signalR = jQuery.signalR; + for (var state in signalR.connectionState) { + if (signalR.connectionState[state] === change.oldState) { + oldState = state; + } + if (signalR.connectionState[state] === change.newState) { + newState = state; + } + } + console.log("Chat Hub state changed from " + oldState + " to " + newState); + }); + } + hub.reconnected(function () { return _this.onReconnected(); }); + hub.error(function (error) { return _this.onError(error); }); + hub.disconnected(function () { return _this.onDisconnected(); }); + return new Promise(function (resolve, reject) { + hub.start() + .done(function () { + _this.setConnectionState(ConnectionState.Connected); + resolve(ConnectionState.Connected); + }) + .fail(function (error) { + _this.setConnectionState(ConnectionState.Error); + reject(new Error(error)); + }); + }); + }; + ChatService.prototype.stop = function () { + jQuery.connection.hub.stop(); + }; + ChatService.prototype.setConnectionState = function (connectionState) { + if (this.currentState === connectionState) { + return; + } + console.log('connection state changed to: ' + connectionState); + this.currentState = connectionState; + this.ea.publish(new connectionStateChanged_1.ConnectionStateChanged(connectionState)); + }; + ChatService.prototype.onReconnected = function () { + this.setConnectionState(ConnectionState.Connected); + }; + ChatService.prototype.onDisconnected = function () { + this.setConnectionState(ConnectionState.Disconnected); + }; + ChatService.prototype.onError = function (error) { + this.setConnectionState(ConnectionState.Error); + }; + ChatService.prototype.onUserConnected = function (user) { + console.log("Chat Hub new user connected: " + user.id); + this.ea.publish(new userConnected_1.UserConnected(user)); + }; + ChatService.prototype.onUserDisconnected = function (user) { + console.log("Chat Hub user disconnected: " + user.id); + if (user.id !== this.state.userName) { + this.ea.publish(new userDisconnected_1.UserDisconnected(user)); + } + }; + ChatService.prototype.onMessageReceived = function (message) { + this.ea.publish(new messageReceived_1.MessageReceived(message)); + }; + ChatService.prototype.onJoinConversation = function (conversation) { + this.helpers.setConverationTitle(conversation); + this.ea.publish(new conversationJoined_1.ConversationJoined(conversation)); + }; + ChatService = __decorate([ + aurelia_framework_1.autoinject, + __metadata('design:paramtypes', [settings_1.Settings, aurelia_event_aggregator_1.EventAggregator, aurelia_http_client_1.HttpClient, state_1.State, helpers_1.Helpers]) + ], ChatService); + return ChatService; + }()); + exports.ChatService = ChatService; +}); + +define('model/provider',["require", "exports"], function (require, exports) { + "use strict"; + var Provider = (function () { + function Provider() { + } + return Provider; + }()); + exports.Provider = Provider; +}); + +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 __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define('services/login.service',["require", "exports", 'aurelia-http-client', 'aurelia-framework', '../config/settings', './chat.service', './helpers', './state'], function (require, exports, aurelia_http_client_1, aurelia_framework_1, settings_1, chat_service_1, helpers_1, state_1) { + "use strict"; + var LoginService = (function () { + function LoginService(http, settings, chatService, state, helpers) { + this.http = http; + this.settings = settings; + this.chatService = chatService; + this.state = state; + this.helpers = helpers; + } + LoginService.prototype.getXhrf = function (clearCookies) { + var _this = this; + return new Promise(function (resolve, reject) { + if (clearCookies) { + _this.http.get('cls') + .then(function () { return _this.setXhrf(resolve, reject); }) + .catch(function (e) { return reject(new Error('the service is down')); }); + } + else if (_this.xhrf) { + resolve(_this.xhrf); + } + else { + _this.setXhrf(resolve, reject); + } + }); + }; + LoginService.prototype.login = function (userName) { + var _this = this; + this.state.isGuess = true; + return new Promise(function (resolve, reject) { + _this.getXhrf() + .then(function (r) { + if (_this.state.isGuess) { + _this.loginAsGuess(userName, resolve, reject); + } + }) + .catch(function (error) { return reject(error); }); + }); + }; + LoginService.prototype.logoff = function () { + var _this = this; + if (!this.state.userName) { + return; + } + this.chatService.stop(); + this.getXhrf() + .then(function (r) { + _this.http.post(_this.settings.accountdAPI + '/spalogoff', null); + }); + this.xhrf = undefined; + this.state.userName = undefined; + }; + LoginService.prototype.exists = function (userName) { + var _this = this; + return new Promise(function (resolve, reject) { + if (!userName) { + resolve(false); + return; + } + _this.getXhrf() + .then(function (r) { + _this.http.get(_this.settings.accountdAPI + "/exists?userName=" + encodeURIComponent(userName)) + .then(function (response) { + resolve(response.content); + }) + .catch(function (error) { + _this.manageError(error, reject, new Error('the service is down')); + }); + }) + .catch(function (error) { return reject(new Error('the service is down')); }); + }); + }; + LoginService.prototype.confirm = function (userName) { + var _this = this; + return new Promise(function (resolve, reject) { + _this.getXhrf() + .then(function (r) { + _this.http.put(_this.settings.accountdAPI + "/spaExternalLoginConfirmation", { userName: userName }) + .then(function (response) { + _this.logged(userName, resolve, reject); + sessionStorage.setItem('userName', userName); + }) + .catch(function (error) { return _this.manageError(error, reject, _this.helpers.getError(error)); }); + }) + .catch(function (error) { return reject(new Error('the service is down')); }); + }); + }; + LoginService.prototype.getExternalLoginProviders = function () { + var _this = this; + return new Promise(function (resolve, reject) { + _this.getXhrf() + .then(function (r) { + _this.http.get(_this.settings.accountdAPI + "/getExternalProviders") + .then(function (response) { + resolve(response.content); + }) + .catch(function (error) { return _this.manageError(error, reject, _this.helpers.getError(error)); }); + }) + .catch(function (error) { return reject(new Error('the service is down')); }); + }); + }; + LoginService.prototype.setXhrf = function (resolve, reject) { + var _this = this; + this.http.get('xhrf') + .then(function (r) { + _this.xhrf = r.response; + _this.http.configure(function (builder) { + builder.withHeader('X-XSRF-TOKEN', _this.xhrf); + }); + resolve(_this.xhrf); + }) + .catch(function (error) { return reject(new Error('the service is down')); }); + }; + LoginService.prototype.loginAsGuess = function (userName, resolve, reject) { + var _this = this; + this.http.post(this.settings.accountdAPI + '/spaguess', { userName: userName }) + .then(function (response) { + _this.logged(userName, resolve, reject); + }) + .catch(function (error) { + _this.manageError(error, reject, _this.helpers.getError(error)); + }); + }; + LoginService.prototype.logged = function (userName, resolve, reject) { + this.state.userName = userName; + this.setXhrf(resolve, reject); + }; + LoginService.prototype.manageError = function (error, reject, exception) { + this.xhrf = undefined; + reject(exception); + }; + LoginService = __decorate([ + aurelia_framework_1.autoinject, + __metadata('design:paramtypes', [aurelia_http_client_1.HttpClient, settings_1.Settings, chat_service_1.ChatService, state_1.State, helpers_1.Helpers]) + ], LoginService); + return LoginService; + }()); + exports.LoginService = LoginService; +}); + +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 __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define('app',["require", "exports", 'aurelia-framework', 'aurelia-router', 'aurelia-event-aggregator', 'aurelia-http-client', './environment', './services/login.service', './services/state', './events/connectionStateChanged', './config/settings', './services/helpers'], function (require, exports, aurelia_framework_1, aurelia_router_1, aurelia_event_aggregator_1, aurelia_http_client_1, environment_1, login_service_1, state_1, connectionStateChanged_1, settings_1, helpers_1) { + "use strict"; + var App = (function () { + function App(service, ea, state, helpers, settings, http) { + this.service = service; + this.ea = ea; + this.state = state; + this.helpers = helpers; + settings.apiBaseUrl = environment_1.default.apiBaseUrl; + http.configure(function (builder) { return builder + .withBaseUrl(environment_1.default.apiBaseUrl) + .withCredentials(true); }); + state.userName = sessionStorage.getItem('userName'); + } + App.prototype.configureRouter = function (config, router) { + var _this = this; + config.title = 'Chatle'; + config.addPipelineStep('authorize', AuthorizeStep); + var confirm = { route: 'confirm', name: 'confirm', moduleId: 'pages/confirm', title: 'Confirm', anomymous: true }; + var login = { route: 'login', name: 'login', moduleId: 'pages/login', title: 'Login', anomymous: true }; + var account = { route: 'account', name: 'account', moduleId: 'pages/account', title: 'Account' }; + var home = { route: 'home', name: 'home', moduleId: 'pages/home', title: 'Home' }; + config.map([ + home, + account, + confirm, + login + ]); + var handleUnknownRoutes = function (instruction) { + var provider = _this.helpers.getUrlParameter('p'); + if (provider) { + return confirm; + } + var userName = _this.helpers.getUrlParameter('u'); + var action = _this.helpers.getUrlParameter('a'); + if (userName) { + _this.state.userName = userName; + sessionStorage.setItem('userName', userName); + } + window.history.replaceState(null, null, '/'); + if (!_this.state.userName) { + return login; + } + if (action) { + return account; + } + return home; + }; + config.mapUnknownRoutes(handleUnknownRoutes); + this.router = router; + }; + App.prototype.attached = function () { + var _this = this; + this.ea.subscribe(connectionStateChanged_1.ConnectionStateChanged, function (e) { + _this.setIsConnected(); + }); + this.setIsConnected(); + }; + App.prototype.logoff = function () { + this.service.logoff(); + this.router.navigateToRoute('login'); + }; + App.prototype.manage = function () { + this.router.navigateToRoute('account'); + }; + App.prototype.home = function () { + if (this.isConnected) { + this.router.navigateToRoute('home'); + } + else { + this.router.navigateToRoute('login'); + } + }; + App.prototype.setIsConnected = function () { + this.isConnected = this.state.userName !== undefined + && this.state.userName != null + && this.router.currentInstruction.config.moduleId != 'pages/confirm'; + this.userName = this.state.userName; + }; + App = __decorate([ + aurelia_framework_1.autoinject, + __metadata('design:paramtypes', [login_service_1.LoginService, aurelia_event_aggregator_1.EventAggregator, state_1.State, helpers_1.Helpers, settings_1.Settings, aurelia_http_client_1.HttpClient]) + ], App); + return App; + }()); + exports.App = App; + var AuthorizeStep = (function () { + function AuthorizeStep(state, helpers) { + this.state = state; + this.helpers = helpers; + } + AuthorizeStep.prototype.run = function (navigationInstruction, next) { + if (navigationInstruction.getAllInstructions().some(function (i) { + var route = i.config; + return !route.anomymous; + })) { + var isLoggedIn = this.state.userName; + if (!isLoggedIn) { + return next.cancel(new aurelia_router_1.Redirect('login')); + } + } + return next(); + }; + AuthorizeStep = __decorate([ + aurelia_framework_1.autoinject, + __metadata('design:paramtypes', [state_1.State, helpers_1.Helpers]) + ], AuthorizeStep); + return AuthorizeStep; + }()); +}); + +define('main',["require", "exports", 'aurelia-framework', 'aurelia-logging-console', './environment'], function (require, exports, aurelia_framework_1, aurelia_logging_console_1, environment_1) { + "use strict"; + if (environment_1.default.debug) { + aurelia_framework_1.LogManager.addAppender(new aurelia_logging_console_1.ConsoleAppender()); + aurelia_framework_1.LogManager.setLevel(aurelia_framework_1.LogManager.logLevel.debug); + } + Promise.config({ + warnings: { + wForgottenReturn: false + } + }); + function configure(aurelia) { + aurelia.use + .standardConfiguration() + .feature('resources') + .plugin('aurelia-validation'); + if (environment_1.default.debug) { + aurelia.use.developmentLogging(); + } + if (environment_1.default.testing) { + aurelia.use.plugin('aurelia-testing'); + } + aurelia.start().then(function () { return aurelia.setRoot(); }); + } + exports.configure = configure; +}); + +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 __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define('services/user.service',["require", "exports", 'aurelia-http-client', 'aurelia-framework', '../config/settings', './state'], function (require, exports, aurelia_http_client_1, aurelia_framework_1, settings_1, state_1) { + "use strict"; + var UserService = (function () { + function UserService(http, settings, state) { + this.http = http; + this.settings = settings; + this.state = state; + } + UserService.prototype.getUsers = function () { + var _this = this; + return new Promise(function (resolve, reject) { + _this.http.get(_this.settings.userAPI) + .then(function (response) { + var data = response.content; + if (data && data.users) { + resolve(data.users); + } + }) + .catch(function (error) { return reject(new Error('the service is down')); }); + }); + }; + UserService = __decorate([ + aurelia_framework_1.autoinject, + __metadata('design:paramtypes', [aurelia_http_client_1.HttpClient, settings_1.Settings, state_1.State]) + ], UserService); + return UserService; + }()); + exports.UserService = UserService; +}); + +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 __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define('components/contact-list',["require", "exports", 'aurelia-framework', 'aurelia-event-aggregator', '../services/chat.service', '../services/user.service', '../services/chat.service', '../events/userConnected', '../events/userDisconnected', '../events/connectionStateChanged'], function (require, exports, aurelia_framework_1, aurelia_event_aggregator_1, chat_service_1, user_service_1, chat_service_2, userConnected_1, userDisconnected_1, connectionStateChanged_1) { + "use strict"; + var ContactList = (function () { + function ContactList(userService, chatService, ea) { + this.userService = userService; + this.chatService = chatService; + this.ea = ea; + this.loadingMessage = "loading..."; + } + ContactList.prototype.attached = function () { + var _this = this; + this.connectionStateChangeSubscription = this.ea.subscribe(connectionStateChanged_1.ConnectionStateChanged, function (e) { + if (e.state === chat_service_1.ConnectionState.Connected) { + _this.getUser(); + } + }); + if (this.chatService.currentState === chat_service_1.ConnectionState.Connected) { + this.getUser(); + } + }; + ContactList.prototype.detached = function () { + this.connectionStateChangeSubscription.dispose(); + if (this.userConnectedSubscription) { + this.userConnectedSubscription.dispose(); + } + if (this.userDisconnectedSubscription) { + this.userDisconnectedSubscription.dispose(); + } + }; + ContactList.prototype.getUser = function () { + var _this = this; + this.userService.getUsers() + .then(function (users) { + _this.users = users; + _this.userConnectedSubscription = _this.ea.subscribe(userConnected_1.UserConnected, function (e) { + var userConnected = e; + _this.removeUser(userConnected.user.id); + _this.users.unshift(userConnected.user); + }); + _this.userDisconnectedSubscription = _this.ea.subscribe(userDisconnected_1.UserDisconnected, function (e) { + _this.removeUser(e.user.id); + }); + }) + .catch(function (error) { return _this.loadingMessage = error.message; }); + }; + ContactList.prototype.removeUser = function (id) { + var user; + this.users.forEach(function (u) { + if (u.id === id) { + user = u; + } + }); + if (user) { + var index = this.users.indexOf(user); + this.users.splice(index, 1); + } + }; + ContactList = __decorate([ + aurelia_framework_1.autoinject, + __metadata('design:paramtypes', [user_service_1.UserService, chat_service_2.ChatService, aurelia_event_aggregator_1.EventAggregator]) + ], ContactList); + return ContactList; + }()); + exports.ContactList = ContactList; +}); + +define('events/conversationSelected',["require", "exports"], function (require, exports) { + "use strict"; + var ConversationSelected = (function () { + function ConversationSelected(conversation) { + this.conversation = conversation; + } + return ConversationSelected; + }()); + exports.ConversationSelected = ConversationSelected; +}); + +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 __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define('services/conversation.service',["require", "exports", 'aurelia-event-aggregator', 'aurelia-http-client', 'aurelia-framework', '../config/settings', './state', './helpers', '../model/message', '../events/conversationSelected', '../events/conversationJoined'], function (require, exports, aurelia_event_aggregator_1, aurelia_http_client_1, aurelia_framework_1, settings_1, state_1, helpers_1, message_1, conversationSelected_1, conversationJoined_1) { + "use strict"; + var ConversationService = (function () { + function ConversationService(http, settings, state, helpers, ea) { + this.http = http; + this.settings = settings; + this.state = state; + this.helpers = helpers; + this.ea = ea; + } + ConversationService.prototype.showConversation = function (conversation, router) { + if (router.currentInstruction.fragment !== 'conversation/' + conversation.title) { + this.currentConversation = conversation; + this.helpers.setConverationTitle(conversation); + this.ea.publish(new conversationSelected_1.ConversationSelected(conversation)); + router.navigateToRoute('conversation', { id: conversation.title }); + } + }; + ConversationService.prototype.sendMessage = function (conversation, message) { + var _this = this; + var m = new message_1.Message(); + m.conversationId = conversation.id; + m.from = this.state.userName; + m.text = message; + if (conversation.id) { + return new Promise(function (resolve, reject) { + _this.http.post(_this.settings.chatAPI, { + to: conversation.id, + text: message + }) + .then(function (response) { + conversation.messages.unshift(m); + resolve(m); + }) + .catch(function (error) { return reject(_this.helpers.getError(error)); }); + }); + } + else { + var attendee_1; + conversation.attendees.forEach(function (a) { + if (a.userId !== _this.state.userName) { + attendee_1 = a; + } + }); + return new Promise(function (resolve, reject) { + _this.http.post(_this.settings.convAPI, { + to: attendee_1.userId, + text: message + }) + .then(function (response) { + conversation.id = response.content; + _this.ea.publish(new conversationJoined_1.ConversationJoined(conversation)); + conversation.messages.unshift(m); + resolve(m); + }) + .catch(function (error) { return reject(_this.helpers.getError(error)); }); + }); + } + }; + ConversationService.prototype.getConversations = function () { + var _this = this; + return new Promise(function (resolve, reject) { + _this.http.get(_this.settings.chatAPI) + .then(function (response) { + if (response.response) { + var data = response.content; + if (data) { + var conversations = data; + conversations.forEach(function (c) { return _this.helpers.setConverationTitle(c); }); + resolve(conversations); + return; + } + } + resolve(null); + }) + .catch(function (error) { return reject(new Error('The service is down')); }); + }); + }; + ConversationService = __decorate([ + aurelia_framework_1.autoinject, + __metadata('design:paramtypes', [aurelia_http_client_1.HttpClient, settings_1.Settings, state_1.State, helpers_1.Helpers, aurelia_event_aggregator_1.EventAggregator]) + ], ConversationService); + return ConversationService; + }()); + exports.ConversationService = ConversationService; +}); + +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 __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define('components/contact',["require", "exports", 'aurelia-framework', 'aurelia-event-aggregator', 'aurelia-router', '../services/conversation.service', '../services/state', '../model/user', '../model/conversation', '../events/conversationSelected'], function (require, exports, aurelia_framework_1, aurelia_event_aggregator_1, aurelia_router_1, conversation_service_1, state_1, user_1, conversation_1, conversationSelected_1) { + "use strict"; + var Contact = (function () { + function Contact(service, state, ea, router) { + this.service = service; + this.state = state; + this.ea = ea; + this.router = router; + } + Object.defineProperty(Contact.prototype, "isCurrentUser", { + get: function () { + return this.state.userName === this.user.id; + }, + enumerable: true, + configurable: true + }); + Contact.prototype.select = function () { + if (this.isCurrentUser) { + return; + } + if (!this.user.conversation) { + this.user.conversation = new conversation_1.Conversation(this.user); + } + this.service.showConversation(this.user.conversation, this.router); + }; + Contact.prototype.attached = function () { + var _this = this; + this.conversationSelectedSubscription = this.ea.subscribe(conversationSelected_1.ConversationSelected, function (e) { + var conv = e.conversation; + var attendees = conv.attendees; + _this.isSelected = false; + if (attendees.length < 3) { + attendees.forEach(function (a) { + if (a.userId !== _this.state.userName && a.userId === _this.user.id) { + _this.isSelected = true; + } + }); + } + }); + }; + Contact.prototype.detached = function () { + this.conversationSelectedSubscription.dispose(); + }; + __decorate([ + aurelia_framework_1.bindable, + __metadata('design:type', user_1.User) + ], Contact.prototype, "user", void 0); + Contact = __decorate([ + aurelia_framework_1.autoinject, + __metadata('design:paramtypes', [conversation_service_1.ConversationService, state_1.State, aurelia_event_aggregator_1.EventAggregator, aurelia_router_1.Router]) + ], Contact); + return Contact; + }()); + exports.Contact = Contact; +}); + +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 __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define('components/conversation-component',["require", "exports", 'aurelia-framework', 'aurelia-router', '../services/conversation.service'], function (require, exports, aurelia_framework_1, aurelia_router_1, conversation_service_1) { + "use strict"; + var ConversationComponent = (function () { + function ConversationComponent(service, router) { + this.service = service; + this.router = router; + } + ConversationComponent.prototype.activate = function (params, routeConfig) { + if (!params) { + delete this.service.currentConversation; + } + this.conversation = this.service.currentConversation; + if (!this.conversation) { + this.router.navigateToRoute('home'); + } + else { + routeConfig.navModel.setTitle(this.conversation.title); + } + }; + ConversationComponent.prototype.sendMessage = function () { + this.service.sendMessage(this.conversation, this.message); + this.message = ''; + }; + ConversationComponent = __decorate([ + aurelia_framework_1.autoinject, + __metadata('design:paramtypes', [conversation_service_1.ConversationService, aurelia_router_1.Router]) + ], ConversationComponent); + return ConversationComponent; + }()); + exports.ConversationComponent = ConversationComponent; +}); + +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 __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define('components/conversation-list',["require", "exports", 'aurelia-framework', 'aurelia-event-aggregator', '../services/chat.service', '../services/conversation.service', '../services/state', '../events/conversationJoined', '../events/userDisconnected', '../events/connectionStateChanged'], function (require, exports, aurelia_framework_1, aurelia_event_aggregator_1, chat_service_1, conversation_service_1, state_1, conversationJoined_1, userDisconnected_1, connectionStateChanged_1) { + "use strict"; + var ConversationList = (function () { + function ConversationList(service, state, ea) { + this.service = service; + this.state = state; + this.ea = ea; + } + ConversationList.prototype.attached = function () { + var _this = this; + this.conversations = new Array(); + this.getConversations(); + this.connectionStateSubscription = this.ea.subscribe(connectionStateChanged_1.ConnectionStateChanged, function (e) { + var state = e.state; + if (state === chat_service_1.ConnectionState.Disconnected) { + _this.conversations.splice(_this.conversations.length); + } + else if (state === chat_service_1.ConnectionState.Connected) { + _this.getConversations(); + } + }); + }; + ConversationList.prototype.detached = function () { + this.Unsubscribe(); + this.connectionStateSubscription.dispose(); + }; + ConversationList.prototype.Unsubscribe = function () { + if (this.conversationJoinedSubscription) { + this.conversationJoinedSubscription.dispose(); + } + if (this.userDisconnectedSubscription) { + this.userDisconnectedSubscription.dispose(); + } + }; + ConversationList.prototype.getConversations = function () { + var _this = this; + this.service.getConversations() + .then(function (conversations) { + _this.Unsubscribe(); + if (!conversations) { + return; + } + _this.conversations = conversations; + _this.userDisconnectedSubscription = _this.ea.subscribe(userDisconnected_1.UserDisconnected, function (e) { + _this.conversations.forEach(function (c) { + var attendees = c.attendees; + if (attendees.length === 2) { + attendees.forEach(function (a) { + var user = e.user; + if (user.isRemoved && a.userId === user.id) { + var index = _this.conversations.indexOf(c); + var conversation = _this.conversations[index]; + _this.conversations.splice(index, 1); + if (_this.service.currentConversation === conversation) { + delete _this.service.currentConversation; + } + } + }); + } + }); + }); + _this.conversationJoinedSubscription = _this.ea.subscribe(conversationJoined_1.ConversationJoined, function (e) { + var conversation = e.conversation; + _this.conversations.unshift(e.conversation); + }); + }); + }; + ConversationList = __decorate([ + aurelia_framework_1.autoinject, + __metadata('design:paramtypes', [conversation_service_1.ConversationService, state_1.State, aurelia_event_aggregator_1.EventAggregator]) + ], ConversationList); + return ConversationList; + }()); + exports.ConversationList = ConversationList; +}); + +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 __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define('components/conversation-preview',["require", "exports", 'aurelia-framework', 'aurelia-event-aggregator', 'aurelia-router', '../services/conversation.service', '../model/conversation', '../events/conversationSelected', '../events/messageReceived'], function (require, exports, aurelia_framework_1, aurelia_event_aggregator_1, aurelia_router_1, conversation_service_1, conversation_1, conversationSelected_1, messageReceived_1) { + "use strict"; + var ConversationPreview = (function () { + function ConversationPreview(service, ea, router) { + this.service = service; + this.ea = ea; + this.router = router; + } + ConversationPreview.prototype.select = function () { + this.service.showConversation(this.conversation, this.router); + }; + ConversationPreview.prototype.attached = function () { + var _this = this; + this.lastMessage = this.conversation.messages[0].text; + this.isSelected = this.conversation && this.conversation.isInitiatedByUser; + this.conversationSelectedSubscription = this.ea.subscribe(conversationSelected_1.ConversationSelected, function (e) { + if (e.conversation.id === _this.conversation.id) { + _this.isSelected = true; + } + else { + _this.isSelected = false; + } + }); + this.messageReceivedSubscription = this.ea.subscribe(messageReceived_1.MessageReceived, function (e) { + var message = e.message; + if (message.conversationId === _this.conversation.id) { + _this.conversation.messages.unshift(message); + _this.lastMessage = message.text; + } + }); + }; + ConversationPreview.prototype.detached = function () { + this.conversationSelectedSubscription.dispose(); + this.messageReceivedSubscription.dispose(); + }; + __decorate([ + aurelia_framework_1.bindable, + __metadata('design:type', conversation_1.Conversation) + ], ConversationPreview.prototype, "conversation", void 0); + ConversationPreview = __decorate([ + aurelia_framework_1.autoinject, + __metadata('design:paramtypes', [conversation_service_1.ConversationService, aurelia_event_aggregator_1.EventAggregator, aurelia_router_1.Router]) + ], ConversationPreview); + return ConversationPreview; + }()); + exports.ConversationPreview = ConversationPreview; +}); + +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 __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define('components/user-name',["require", "exports", 'aurelia-framework', 'aurelia-validation', '../services/login.service', '../services/state'], function (require, exports, aurelia_framework_1, aurelia_validation_1, login_service_1, state_1) { + "use strict"; + var UserName = (function () { + function UserName(service, state, controllerFactory) { + this.service = service; + this.state = state; + this.controller = controllerFactory.createForCurrentScope(); + this.controller.validateTrigger = 'change'; + } + UserName.prototype.attached = function () { + this.userName = this.state.userName; + }; + UserName.prototype.userNameAvailable = function (value) { + var _this = this; + return new Promise(function (resolve) { + _this.service.exists(value) + .then(function (r) { + resolve(!r); + _this.state.userName = value; + }); + }); + }; + __decorate([ + aurelia_framework_1.bindable({ defaultBindingMode: aurelia_framework_1.bindingMode.twoWay }), + __metadata('design:type', String) + ], UserName.prototype, "userName", void 0); + UserName = __decorate([ + aurelia_framework_1.autoinject, + aurelia_framework_1.customElement('user-name'), + __metadata('design:paramtypes', [login_service_1.LoginService, state_1.State, aurelia_validation_1.ValidationControllerFactory]) + ], UserName); + return UserName; + }()); + exports.UserName = UserName; + aurelia_validation_1.ValidationRules + .ensure(function (c) { return c.userName; }) + .satisfies(function (value, obj) { return obj.userNameAvailable(value); }) + .withMessage('This user name already exists, please choose another one') + .satisfiesRule('required') + .on(UserName); +}); + +define('model/changePassword',["require", "exports"], function (require, exports) { + "use strict"; + var ChangePassword = (function () { + function ChangePassword() { + } + return ChangePassword; + }()); + exports.ChangePassword = ChangePassword; +}); + +define('model/manage-logins',["require", "exports"], function (require, exports) { + "use strict"; + var UserLoginInfo = (function () { + function UserLoginInfo() { + } + return UserLoginInfo; + }()); + var UserLogiAuthenticationDescriptionnInfo = (function () { + function UserLogiAuthenticationDescriptionnInfo() { + } + return UserLogiAuthenticationDescriptionnInfo; + }()); + exports.UserLogiAuthenticationDescriptionnInfo = UserLogiAuthenticationDescriptionnInfo; + var ManageLogins = (function () { + function ManageLogins() { + } + return ManageLogins; + }()); + exports.ManageLogins = ManageLogins; +}); + +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 __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define('services/account.service',["require", "exports", 'aurelia-http-client', 'aurelia-framework', '../config/settings', './state', './helpers'], function (require, exports, aurelia_http_client_1, aurelia_framework_1, settings_1, state_1, helpers_1) { + "use strict"; + var AccountService = (function () { + function AccountService(http, settings, state, helpers) { + this.http = http; + this.settings = settings; + this.state = state; + this.helpers = helpers; + } + AccountService.prototype.getLogins = function () { + var _this = this; + return new Promise(function (resove, reject) { + _this.http.get(_this.settings.accountdAPI + '/logins') + .then(function (response) { + resove(response.content); + }) + .catch(function (error) { return reject(new Error('The service is down')); }); + }); + }; + AccountService.prototype.removeLogin = function (loginProvider, providerKey) { + var _this = this; + return new Promise(function (resolve, reject) { + _this.http.delete(_this.settings.accountdAPI + '/sparemoveLogin?loginProvider=' + encodeURIComponent(loginProvider) + '&providerKey=' + encodeURIComponent(providerKey)) + .then(function () { + resolve(); + }) + .catch(function (e) { return reject(_this.helpers.getError(e)); }); + }); + }; + AccountService = __decorate([ + aurelia_framework_1.autoinject, + __metadata('design:paramtypes', [aurelia_http_client_1.HttpClient, settings_1.Settings, state_1.State, helpers_1.Helpers]) + ], AccountService); + return AccountService; + }()); + exports.AccountService = AccountService; +}); + +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 __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define('pages/account',["require", "exports", 'aurelia-framework', 'aurelia-router', 'aurelia-event-aggregator', '../services/chat.service', '../services/state', '../services/account.service', '../services/login.service', '../model/manage-logins', '../events/connectionStateChanged', '../config/settings', '../services/helpers'], function (require, exports, aurelia_framework_1, aurelia_router_1, aurelia_event_aggregator_1, chat_service_1, state_1, account_service_1, login_service_1, manage_logins_1, connectionStateChanged_1, settings_1, helpers_1) { + "use strict"; + var Account = (function () { + function Account(accountService, loginService, router, ea, state, settings, helpers) { + this.accountService = accountService; + this.loginService = loginService; + this.router = router; + this.ea = ea; + this.state = state; + this.externalLinkLogin = settings.apiBaseUrl + + settings.accountdAPI + + '/linklogin?returnUrl=' + + encodeURIComponent(location.protocol + '//' + location.host + '?a=account&u=' + encodeURIComponent(this.state.userName)); + } + Account.prototype.remove = function (loginProvider, providerKey) { + var _this = this; + this.accountService.removeLogin(loginProvider, providerKey) + .then(function () { + var currentLogins = _this.logins.currentLogins; + var index = currentLogins.findIndex(function (value) { return value.loginProvider === loginProvider && value.providerKey === providerKey; }); + currentLogins.splice(index, 1); + var provider = new manage_logins_1.UserLogiAuthenticationDescriptionnInfo(); + provider.authenticationScheme = provider.displayName = loginProvider; + _this.logins.otherLogins.push(provider); + }) + .catch(function (e) { return _this.errorMessage = e.message; }); + }; + Account.prototype.attached = function () { + var _this = this; + this.connectionStateSubscription = this.ea.subscribe(connectionStateChanged_1.ConnectionStateChanged, function (e) { + if (e.state === chat_service_1.ConnectionState.Connected) { + _this.getLogins(); + } + }); + this.getLogins(); + }; + Account.prototype.detached = function () { + this.connectionStateSubscription.dispose(); + }; + Account.prototype.getLogins = function () { + var _this = this; + this.loginService.getXhrf() + .then(function (token) { + _this.token = token; + _this.accountService.getLogins() + .then(function (logins) { return _this.logins = logins; }) + .catch(function (e) { return _this.errorMessage = e.message; }); + }) + .catch(function (e) { return _this.errorMessage = e.message; }); + }; + Account = __decorate([ + aurelia_framework_1.autoinject, + __metadata('design:paramtypes', [account_service_1.AccountService, login_service_1.LoginService, aurelia_router_1.Router, aurelia_event_aggregator_1.EventAggregator, state_1.State, settings_1.Settings, helpers_1.Helpers]) + ], Account); + return Account; + }()); + exports.Account = Account; +}); + +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 __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define('pages/confirm',["require", "exports", 'aurelia-framework', 'aurelia-router', 'aurelia-validation', '../services/login.service', '../services/helpers', '../services/state'], function (require, exports, aurelia_framework_1, aurelia_router_1, aurelia_validation_1, login_service_1, helpers_1, state_1) { + "use strict"; + var Confirm = (function () { + function Confirm(service, router, helpers, state, controllerFactory) { + this.service = service; + this.router = router; + this.helpers = helpers; + this.state = state; + this.controller = controllerFactory.createForCurrentScope(); + this.provider = this.helpers.getUrlParameter('p'); + state.userName = this.helpers.getUrlParameter('u'); + window.history.replaceState(null, null, '/'); + } + Confirm.prototype.confirm = function () { + var _this = this; + this.controller.validate() + .then(function () { + _this.service.confirm(_this.state.userName) + .then(function () { + _this.router.navigateToRoute('home'); + }) + .catch(function (e) { + if (e.name === 'NullInfo') { + _this.router.navigateToRoute('login'); + } + else { + _this.error = e; + } + }); + }) + .catch(function (e) { return _this.error = e; }); + }; + Confirm = __decorate([ + aurelia_framework_1.autoinject, + __metadata('design:paramtypes', [login_service_1.LoginService, aurelia_router_1.Router, helpers_1.Helpers, state_1.State, aurelia_validation_1.ValidationControllerFactory]) + ], Confirm); + return Confirm; + }()); + exports.Confirm = Confirm; +}); + +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 __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define('pages/home',["require", "exports", 'aurelia-framework', 'aurelia-event-aggregator', '../services/chat.service', '../events/connectionStateChanged'], function (require, exports, aurelia_framework_1, aurelia_event_aggregator_1, chat_service_1, connectionStateChanged_1) { + "use strict"; + var Home = (function () { + function Home(chatService, ea) { + this.chatService = chatService; + this.ea = ea; + } + Home.prototype.configureRouter = function (config, router) { + config.map([ + { route: ['', 'conversation/:id'], name: 'conversation', moduleId: '../components/conversation-component' } + ]); + this.router = router; + }; + Home.prototype.attached = function () { + var _this = this; + this.connectionStateSubscription = this.ea.subscribe(connectionStateChanged_1.ConnectionStateChanged, function (e) { + _this.setIsDisconnected(e.state); + }); + this.setIsDisconnected(this.chatService.currentState); + if (this.chatService.currentState !== chat_service_1.ConnectionState.Connected) { + this.chatService.start(); + } + }; + Home.prototype.detached = function () { + this.connectionStateSubscription.dispose(); + }; + Home.prototype.setIsDisconnected = function (state) { + if (state === chat_service_1.ConnectionState.Error) { + this.router.navigateToRoute('login'); + } + if (state === chat_service_1.ConnectionState.Disconnected) { + this.isDisconnected = true; + } + else { + this.isDisconnected = false; + } + }; + Home = __decorate([ + aurelia_framework_1.autoinject, + __metadata('design:paramtypes', [chat_service_1.ChatService, aurelia_event_aggregator_1.EventAggregator]) + ], Home); + return Home; + }()); + exports.Home = Home; +}); + +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 __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define('pages/login',["require", "exports", 'aurelia-framework', 'aurelia-router', '../services/login.service', '../config/settings', '../services/state'], function (require, exports, aurelia_framework_1, aurelia_router_1, login_service_1, settings_1, state_1) { + "use strict"; + var Login = (function () { + function Login(service, router, state, settings) { + this.service = service; + this.router = router; + this.state = state; + var location = window.location; + this.externalLogin = settings.apiBaseUrl + + settings.accountdAPI + + '/externalLogin?returnUrl=' + + encodeURIComponent(location.protocol + '//' + location.host); + } + Login.prototype.login = function () { + var _this = this; + this.service.login(this.state.userName) + .then(function () { + _this.router.navigateToRoute('home'); + }) + .catch(function (error) { + _this.error = error; + }); + }; + Login.prototype.activate = function () { + var _this = this; + this.service.logoff(); + this.service.getXhrf(true) + .then(function (t) { + _this.token = t; + _this.service.getExternalLoginProviders() + .then(function (providers) { return _this.providers = providers; }) + .catch(function (e) { return _this.error = e; }); + }) + .catch(function (e) { + return _this.error = e; + }); + }; + Login = __decorate([ + aurelia_framework_1.autoinject, + __metadata('design:paramtypes', [login_service_1.LoginService, aurelia_router_1.Router, state_1.State, settings_1.Settings]) + ], Login); + return Login; + }()); + exports.Login = Login; +}); + +define('resources/index',["require", "exports"], function (require, exports) { + "use strict"; + function configure(config) { + } + exports.configure = configure; +}); + +define('aurelia-validation/validate-binding-behavior',["require", "exports", 'aurelia-dependency-injection', 'aurelia-pal', 'aurelia-task-queue', './validation-controller', './validate-trigger'], function (require, exports, aurelia_dependency_injection_1, aurelia_pal_1, aurelia_task_queue_1, validation_controller_1, validate_trigger_1) { + "use strict"; + /** + * Binding behavior. Indicates the bound property should be validated. + */ + var ValidateBindingBehavior = (function () { + function ValidateBindingBehavior(taskQueue) { + this.taskQueue = taskQueue; + } + /** + * Gets the DOM element associated with the data-binding. Most of the time it's + * the binding.target but sometimes binding.target is an aurelia custom element, + * or custom attribute which is a javascript "class" instance, so we need to use + * the controller's container to retrieve the actual DOM element. + */ + ValidateBindingBehavior.prototype.getTarget = function (binding, view) { + var target = binding.target; + // DOM element + if (target instanceof Element) { + return target; + } + // custom element or custom attribute + for (var i = 0, ii = view.controllers.length; i < ii; i++) { + var controller = view.controllers[i]; + if (controller.viewModel === target) { + var element = controller.container.get(aurelia_pal_1.DOM.Element); + if (element) { + return element; + } + throw new Error("Unable to locate target element for \"" + binding.sourceExpression + "\"."); + } + } + throw new Error("Unable to locate target element for \"" + binding.sourceExpression + "\"."); + }; + ValidateBindingBehavior.prototype.bind = function (binding, source, rulesOrController, rules) { + var _this = this; + // identify the target element. + var target = this.getTarget(binding, source); + // locate the controller. + var controller; + if (rulesOrController instanceof validation_controller_1.ValidationController) { + controller = rulesOrController; + } + else { + controller = source.container.get(aurelia_dependency_injection_1.Optional.of(validation_controller_1.ValidationController)); + rules = rulesOrController; + } + if (controller === null) { + throw new Error("A ValidationController has not been registered."); + } + controller.registerBinding(binding, target, rules); + binding.validationController = controller; + if (controller.validateTrigger === validate_trigger_1.validateTrigger.change) { + binding.standardUpdateSource = binding.updateSource; + binding.updateSource = function (value) { + this.standardUpdateSource(value); + this.validationController.validateBinding(this); + }; + } + else if (controller.validateTrigger === validate_trigger_1.validateTrigger.blur) { + binding.validateBlurHandler = function () { + _this.taskQueue.queueMicroTask(function () { return controller.validateBinding(binding); }); + }; + binding.validateTarget = target; + target.addEventListener('blur', binding.validateBlurHandler); + } + if (controller.validateTrigger !== validate_trigger_1.validateTrigger.manual) { + binding.standardUpdateTarget = binding.updateTarget; + binding.updateTarget = function (value) { + this.standardUpdateTarget(value); + this.validationController.resetBinding(this); + }; + } + }; + ValidateBindingBehavior.prototype.unbind = function (binding) { + // reset the binding to it's original state. + if (binding.standardUpdateSource) { + binding.updateSource = binding.standardUpdateSource; + binding.standardUpdateSource = null; + } + if (binding.standardUpdateTarget) { + binding.updateTarget = binding.standardUpdateTarget; + binding.standardUpdateTarget = null; + } + if (binding.validateBlurHandler) { + binding.validateTarget.removeEventListener('blur', binding.validateBlurHandler); + binding.validateBlurHandler = null; + binding.validateTarget = null; + } + binding.validationController.unregisterBinding(binding); + binding.validationController = null; + }; + ValidateBindingBehavior.inject = [aurelia_task_queue_1.TaskQueue]; + return ValidateBindingBehavior; + }()); + exports.ValidateBindingBehavior = ValidateBindingBehavior; +}); + +define('aurelia-validation/validation-controller',["require", "exports", './validator', './validate-trigger', './property-info', './validation-error'], function (require, exports, validator_1, validate_trigger_1, property_info_1, validation_error_1) { + "use strict"; + /** + * Orchestrates validation. + * Manages a set of bindings, renderers and objects. + * Exposes the current list of validation errors for binding purposes. + */ + var ValidationController = (function () { + function ValidationController(validator) { + this.validator = validator; + // Registered bindings (via the validate binding behavior) + this.bindings = new Map(); + // Renderers that have been added to the controller instance. + this.renderers = []; + /** + * Errors that have been rendered by the controller. + */ + this.errors = []; + /** + * Whether the controller is currently validating. + */ + this.validating = false; + // Elements related to errors that have been rendered. + this.elements = new Map(); + // Objects that have been added to the controller instance (entity-style validation). + this.objects = new Map(); + /** + * The trigger that will invoke automatic validation of a property used in a binding. + */ + this.validateTrigger = validate_trigger_1.validateTrigger.blur; + // Promise that resolves when validation has completed. + this.finishValidating = Promise.resolve(); + } + /** + * Adds an object to the set of objects that should be validated when validate is called. + * @param object The object. + * @param rules Optional. The rules. If rules aren't supplied the Validator implementation will lookup the rules. + */ + ValidationController.prototype.addObject = function (object, rules) { + this.objects.set(object, rules); + }; + /** + * Removes an object from the set of objects that should be validated when validate is called. + * @param object The object. + */ + ValidationController.prototype.removeObject = function (object) { + this.objects.delete(object); + this.processErrorDelta('reset', this.errors.filter(function (error) { return error.object === object; }), []); + }; + /** + * Adds and renders a ValidationError. + */ + ValidationController.prototype.addError = function (message, object, propertyName) { + var error = new validation_error_1.ValidationError({}, message, object, propertyName); + this.processErrorDelta('validate', [], [error]); + return error; + }; + /** + * Removes and unrenders a ValidationError. + */ + ValidationController.prototype.removeError = function (error) { + if (this.errors.indexOf(error) !== -1) { + this.processErrorDelta('reset', [error], []); + } + }; + /** + * Adds a renderer. + * @param renderer The renderer. + */ + ValidationController.prototype.addRenderer = function (renderer) { + var _this = this; + this.renderers.push(renderer); + renderer.render({ + kind: 'validate', + render: this.errors.map(function (error) { return ({ error: error, elements: _this.elements.get(error) }); }), + unrender: [] + }); + }; + /** + * Removes a renderer. + * @param renderer The renderer. + */ + ValidationController.prototype.removeRenderer = function (renderer) { + var _this = this; + this.renderers.splice(this.renderers.indexOf(renderer), 1); + renderer.render({ + kind: 'reset', + render: [], + unrender: this.errors.map(function (error) { return ({ error: error, elements: _this.elements.get(error) }); }) + }); + }; + /** + * Registers a binding with the controller. + * @param binding The binding instance. + * @param target The DOM element. + * @param rules (optional) rules associated with the binding. Validator implementation specific. + */ + ValidationController.prototype.registerBinding = function (binding, target, rules) { + this.bindings.set(binding, { target: target, rules: rules }); + }; + /** + * Unregisters a binding with the controller. + * @param binding The binding instance. + */ + ValidationController.prototype.unregisterBinding = function (binding) { + this.resetBinding(binding); + this.bindings.delete(binding); + }; + /** + * Interprets the instruction and returns a predicate that will identify + * relevant errors in the list of rendered errors. + */ + ValidationController.prototype.getInstructionPredicate = function (instruction) { + if (instruction) { + var object_1 = instruction.object, propertyName_1 = instruction.propertyName, rules_1 = instruction.rules; + var predicate_1; + if (instruction.propertyName) { + predicate_1 = function (x) { return x.object === object_1 && x.propertyName === propertyName_1; }; + } + else { + predicate_1 = function (x) { return x.object === object_1; }; + } + // todo: move to Validator interface: + if (rules_1 && rules_1.indexOf) { + return function (x) { return predicate_1(x) && rules_1.indexOf(x.rule) !== -1; }; + } + return predicate_1; + } + else { + return function () { return true; }; + } + }; + /** + * Validates and renders errors. + * @param instruction Optional. Instructions on what to validate. If undefined, all objects and bindings will be validated. + */ + ValidationController.prototype.validate = function (instruction) { + var _this = this; + // Get a function that will process the validation instruction. + var execute; + if (instruction) { + var object_2 = instruction.object, propertyName_2 = instruction.propertyName, rules_2 = instruction.rules; + // if rules were not specified, check the object map. + rules_2 = rules_2 || this.objects.get(object_2); + // property specified? + if (instruction.propertyName === undefined) { + // validate the specified object. + execute = function () { return _this.validator.validateObject(object_2, rules_2); }; + } + else { + // validate the specified property. + execute = function () { return _this.validator.validateProperty(object_2, propertyName_2, rules_2); }; + } + } + else { + // validate all objects and bindings. + execute = function () { + var promises = []; + for (var _i = 0, _a = Array.from(_this.objects); _i < _a.length; _i++) { + var _b = _a[_i], object = _b[0], rules = _b[1]; + promises.push(_this.validator.validateObject(object, rules)); + } + for (var _c = 0, _d = Array.from(_this.bindings); _c < _d.length; _c++) { + var _e = _d[_c], binding = _e[0], rules = _e[1].rules; + var _f = property_info_1.getPropertyInfo(binding.sourceExpression, binding.source), object = _f.object, propertyName = _f.propertyName; + if (_this.objects.has(object)) { + continue; + } + promises.push(_this.validator.validateProperty(object, propertyName, rules)); + } + return Promise.all(promises).then(function (errorSets) { return errorSets.reduce(function (a, b) { return a.concat(b); }, []); }); + }; + } + // Wait for any existing validation to finish, execute the instruction, render the errors. + this.validating = true; + var result = this.finishValidating + .then(execute) + .then(function (newErrors) { + var predicate = _this.getInstructionPredicate(instruction); + var oldErrors = _this.errors.filter(predicate); + _this.processErrorDelta('validate', oldErrors, newErrors); + if (result === _this.finishValidating) { + _this.validating = false; + } + return newErrors; + }) + .catch(function (error) { + // recover, to enable subsequent calls to validate() + _this.validating = false; + _this.finishValidating = Promise.resolve(); + return Promise.reject(error); + }); + this.finishValidating = result; + return result; + }; + /** + * Resets any rendered errors (unrenders). + * @param instruction Optional. Instructions on what to reset. If unspecified all rendered errors will be unrendered. + */ + ValidationController.prototype.reset = function (instruction) { + var predicate = this.getInstructionPredicate(instruction); + var oldErrors = this.errors.filter(predicate); + this.processErrorDelta('reset', oldErrors, []); + }; + /** + * Gets the elements associated with an object and propertyName (if any). + */ + ValidationController.prototype.getAssociatedElements = function (_a) { + var object = _a.object, propertyName = _a.propertyName; + var elements = []; + for (var _i = 0, _b = Array.from(this.bindings); _i < _b.length; _i++) { + var _c = _b[_i], binding = _c[0], target = _c[1].target; + var _d = property_info_1.getPropertyInfo(binding.sourceExpression, binding.source), o = _d.object, p = _d.propertyName; + if (o === object && p === propertyName) { + elements.push(target); + } + } + return elements; + }; + ValidationController.prototype.processErrorDelta = function (kind, oldErrors, newErrors) { + // prepare the instruction. + var instruction = { + kind: kind, + render: [], + unrender: [] + }; + // create a shallow copy of newErrors so we can mutate it without causing side-effects. + newErrors = newErrors.slice(0); + // create unrender instructions from the old errors. + var _loop_1 = function(oldError) { + // get the elements associated with the old error. + var elements = this_1.elements.get(oldError); + // remove the old error from the element map. + this_1.elements.delete(oldError); + // create the unrender instruction. + instruction.unrender.push({ error: oldError, elements: elements }); + // determine if there's a corresponding new error for the old error we are unrendering. + var newErrorIndex = newErrors.findIndex(function (x) { return x.rule === oldError.rule && x.object === oldError.object && x.propertyName === oldError.propertyName; }); + if (newErrorIndex === -1) { + // no corresponding new error... simple remove. + this_1.errors.splice(this_1.errors.indexOf(oldError), 1); + } + else { + // there is a corresponding new error... + var newError = newErrors.splice(newErrorIndex, 1)[0]; + // get the elements that are associated with the new error. + var elements_1 = this_1.getAssociatedElements(newError); + this_1.elements.set(newError, elements_1); + // create a render instruction for the new error. + instruction.render.push({ error: newError, elements: elements_1 }); + // do an in-place replacement of the old error with the new error. + // this ensures any repeats bound to this.errors will not thrash. + this_1.errors.splice(this_1.errors.indexOf(oldError), 1, newError); + } + }; + var this_1 = this; + for (var _i = 0, oldErrors_1 = oldErrors; _i < oldErrors_1.length; _i++) { + var oldError = oldErrors_1[_i]; + _loop_1(oldError); + } + // create render instructions from the remaining new errors. + for (var _a = 0, newErrors_1 = newErrors; _a < newErrors_1.length; _a++) { + var error = newErrors_1[_a]; + var elements = this.getAssociatedElements(error); + instruction.render.push({ error: error, elements: elements }); + this.elements.set(error, elements); + this.errors.push(error); + } + // render. + for (var _b = 0, _c = this.renderers; _b < _c.length; _b++) { + var renderer = _c[_b]; + renderer.render(instruction); + } + }; + /** + * Validates the property associated with a binding. + */ + ValidationController.prototype.validateBinding = function (binding) { + if (!binding.isBound) { + return; + } + var _a = property_info_1.getPropertyInfo(binding.sourceExpression, binding.source), object = _a.object, propertyName = _a.propertyName; + var registeredBinding = this.bindings.get(binding); + var rules = registeredBinding ? registeredBinding.rules : undefined; + this.validate({ object: object, propertyName: propertyName, rules: rules }); + }; + /** + * Resets the errors for a property associated with a binding. + */ + ValidationController.prototype.resetBinding = function (binding) { + var _a = property_info_1.getPropertyInfo(binding.sourceExpression, binding.source), object = _a.object, propertyName = _a.propertyName; + this.reset({ object: object, propertyName: propertyName }); + }; + ValidationController.inject = [validator_1.Validator]; + return ValidationController; + }()); + exports.ValidationController = ValidationController; +}); + +define('aurelia-validation/validator',["require", "exports"], function (require, exports) { + "use strict"; + /** + * Validates. + * Responsible for validating objects and properties. + */ + var Validator = (function () { + function Validator() { + } + return Validator; + }()); + exports.Validator = Validator; +}); + +define('aurelia-validation/validate-trigger',["require", "exports"], function (require, exports) { + "use strict"; + /** + * Validation triggers. + */ + exports.validateTrigger = { + /** + * Validate the binding when the binding's target element fires a DOM "blur" event. + */ + blur: 'blur', + /** + * Validate the binding when it updates the model due to a change in the view. + * Not specific to DOM "change" events. + */ + change: 'change', + /** + * Manual validation. Use the controller's `validate()` and `reset()` methods + * to validate all bindings. + */ + manual: 'manual' + }; +}); + +define('aurelia-validation/property-info',["require", "exports", 'aurelia-binding'], function (require, exports, aurelia_binding_1) { + "use strict"; + function getObject(expression, objectExpression, source) { + var value = objectExpression.evaluate(source, null); + if (value !== null && (typeof value === 'object' || typeof value === 'function')) { + return value; + } + if (value === null) { + value = 'null'; + } + else if (value === undefined) { + value = 'undefined'; + } + throw new Error("The '" + objectExpression + "' part of '" + expression + "' evaluates to " + value + " instead of an object."); + } + /** + * Retrieves the object and property name for the specified expression. + * @param expression The expression + * @param source The scope + */ + function getPropertyInfo(expression, source) { + var originalExpression = expression; + while (expression instanceof aurelia_binding_1.BindingBehavior || expression instanceof aurelia_binding_1.ValueConverter) { + expression = expression.expression; + } + var object; + var propertyName; + if (expression instanceof aurelia_binding_1.AccessScope) { + object = source.bindingContext; + propertyName = expression.name; + } + else if (expression instanceof aurelia_binding_1.AccessMember) { + object = getObject(originalExpression, expression.object, source); + propertyName = expression.name; + } + else if (expression instanceof aurelia_binding_1.AccessKeyed) { + object = getObject(originalExpression, expression.object, source); + propertyName = expression.key.evaluate(source); + } + else { + throw new Error("Expression '" + originalExpression + "' is not compatible with the validate binding-behavior."); + } + return { object: object, propertyName: propertyName }; + } + exports.getPropertyInfo = getPropertyInfo; +}); + +define('aurelia-validation/validation-error',["require", "exports"], function (require, exports) { + "use strict"; + /** + * A validation error. + */ + var ValidationError = (function () { + /** + * @param rule The rule associated with the error. Validator implementation specific. + * @param message The error message. + * @param object The invalid object + * @param propertyName The name of the invalid property. Optional. + */ + function ValidationError(rule, message, object, propertyName) { + if (propertyName === void 0) { propertyName = null; } + this.rule = rule; + this.message = message; + this.object = object; + this.propertyName = propertyName; + this.id = ValidationError.nextId++; + } + ValidationError.prototype.toString = function () { + return this.message; + }; + ValidationError.nextId = 0; + return ValidationError; + }()); + exports.ValidationError = ValidationError; +}); + +define('aurelia-validation/validation-controller-factory',["require", "exports", './validation-controller'], function (require, exports, validation_controller_1) { + "use strict"; + /** + * Creates ValidationController instances. + */ + var ValidationControllerFactory = (function () { + function ValidationControllerFactory(container) { + this.container = container; + } + ValidationControllerFactory.get = function (container) { + return new ValidationControllerFactory(container); + }; + /** + * Creates a new controller and registers it in the current element's container so that it's + * available to the validate binding behavior and renderers. + */ + ValidationControllerFactory.prototype.create = function () { + return this.container.invoke(validation_controller_1.ValidationController); + }; + /** + * Creates a new controller and registers it in the current element's container so that it's + * available to the validate binding behavior and renderers. + */ + ValidationControllerFactory.prototype.createForCurrentScope = function () { + var controller = this.create(); + this.container.registerInstance(validation_controller_1.ValidationController, controller); + return controller; + }; + return ValidationControllerFactory; + }()); + exports.ValidationControllerFactory = ValidationControllerFactory; + ValidationControllerFactory['protocol:aurelia:resolver'] = true; +}); + +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; +}; +define('aurelia-validation/validation-errors-custom-attribute',["require", "exports", 'aurelia-binding', 'aurelia-dependency-injection', 'aurelia-templating', './validation-controller'], function (require, exports, aurelia_binding_1, aurelia_dependency_injection_1, aurelia_templating_1, validation_controller_1) { + "use strict"; + var ValidationErrorsCustomAttribute = (function () { + function ValidationErrorsCustomAttribute(boundaryElement, controllerAccessor) { + this.boundaryElement = boundaryElement; + this.controllerAccessor = controllerAccessor; + this.errors = []; + } + ValidationErrorsCustomAttribute.prototype.sort = function () { + this.errors.sort(function (a, b) { + if (a.targets[0] === b.targets[0]) { + return 0; + } + return a.targets[0].compareDocumentPosition(b.targets[0]) & 2 ? 1 : -1; + }); + }; + ValidationErrorsCustomAttribute.prototype.interestingElements = function (elements) { + var _this = this; + return elements.filter(function (e) { return _this.boundaryElement.contains(e); }); + }; + ValidationErrorsCustomAttribute.prototype.render = function (instruction) { + var _loop_1 = function(error) { + var index = this_1.errors.findIndex(function (x) { return x.error === error; }); + if (index !== -1) { + this_1.errors.splice(index, 1); + } + }; + var this_1 = this; + for (var _i = 0, _a = instruction.unrender; _i < _a.length; _i++) { + var error = _a[_i].error; + _loop_1(error); + } + for (var _b = 0, _c = instruction.render; _b < _c.length; _b++) { + var _d = _c[_b], error = _d.error, elements = _d.elements; + var targets = this.interestingElements(elements); + if (targets.length) { + this.errors.push({ error: error, targets: targets }); + } + } + this.sort(); + this.value = this.errors; + }; + ValidationErrorsCustomAttribute.prototype.bind = function () { + this.controllerAccessor().addRenderer(this); + this.value = this.errors; + }; + ValidationErrorsCustomAttribute.prototype.unbind = function () { + this.controllerAccessor().removeRenderer(this); + }; + ValidationErrorsCustomAttribute.inject = [Element, aurelia_dependency_injection_1.Lazy.of(validation_controller_1.ValidationController)]; + ValidationErrorsCustomAttribute = __decorate([ + aurelia_templating_1.customAttribute('validation-errors', aurelia_binding_1.bindingMode.twoWay) + ], ValidationErrorsCustomAttribute); + return ValidationErrorsCustomAttribute; + }()); + exports.ValidationErrorsCustomAttribute = ValidationErrorsCustomAttribute; +}); + +define('aurelia-validation/validation-renderer-custom-attribute',["require", "exports", './validation-controller'], function (require, exports, validation_controller_1) { + "use strict"; + var ValidationRendererCustomAttribute = (function () { + function ValidationRendererCustomAttribute() { + } + ValidationRendererCustomAttribute.prototype.created = function (view) { + this.container = view.container; + }; + ValidationRendererCustomAttribute.prototype.bind = function () { + this.controller = this.container.get(validation_controller_1.ValidationController); + this.renderer = this.container.get(this.value); + this.controller.addRenderer(this.renderer); + }; + ValidationRendererCustomAttribute.prototype.unbind = function () { + this.controller.removeRenderer(this.renderer); + this.controller = null; + this.renderer = null; + }; + return ValidationRendererCustomAttribute; + }()); + exports.ValidationRendererCustomAttribute = ValidationRendererCustomAttribute; +}); + +define('aurelia-validation/implementation/rules',["require", "exports"], function (require, exports) { + "use strict"; + /** + * Sets, unsets and retrieves rules on an object or constructor function. + */ + var Rules = (function () { + function Rules() { + } + /** + * Applies the rules to a target. + */ + Rules.set = function (target, rules) { + if (target instanceof Function) { + target = target.prototype; + } + Object.defineProperty(target, Rules.key, { enumerable: false, configurable: false, writable: true, value: rules }); + }; + /** + * Removes rules from a target. + */ + Rules.unset = function (target) { + if (target instanceof Function) { + target = target.prototype; + } + target[Rules.key] = null; + }; + /** + * Retrieves the target's rules. + */ + Rules.get = function (target) { + return target[Rules.key] || null; + }; + /** + * The name of the property that stores the rules. + */ + Rules.key = '__rules__'; + return Rules; + }()); + exports.Rules = Rules; +}); + +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 __()); +}; +define('aurelia-validation/implementation/standard-validator',["require", "exports", 'aurelia-templating', '../validator', '../validation-error', './rules', './validation-messages'], function (require, exports, aurelia_templating_1, validator_1, validation_error_1, rules_1, validation_messages_1) { + "use strict"; + /** + * Validates. + * Responsible for validating objects and properties. + */ + var StandardValidator = (function (_super) { + __extends(StandardValidator, _super); + function StandardValidator(messageProvider, resources) { + _super.call(this); + this.messageProvider = messageProvider; + this.lookupFunctions = resources.lookupFunctions; + this.getDisplayName = messageProvider.getDisplayName.bind(messageProvider); + } + StandardValidator.prototype.getMessage = function (rule, object, value) { + var expression = rule.message || this.messageProvider.getMessage(rule.messageKey); + var _a = rule.property, propertyName = _a.name, displayName = _a.displayName; + if (displayName === null && propertyName !== null) { + displayName = this.messageProvider.getDisplayName(propertyName); + } + var overrideContext = { + $displayName: displayName, + $propertyName: propertyName, + $value: value, + $object: object, + $config: rule.config, + $getDisplayName: this.getDisplayName + }; + return expression.evaluate({ bindingContext: object, overrideContext: overrideContext }, this.lookupFunctions); + }; + StandardValidator.prototype.validate = function (object, propertyName, rules) { + var _this = this; + var errors = []; + // rules specified? + if (!rules) { + // no. locate the rules via metadata. + rules = rules_1.Rules.get(object); + } + // any rules? + if (!rules) { + return Promise.resolve(errors); + } + // are we validating all properties or a single property? + var validateAllProperties = propertyName === null || propertyName === undefined; + var addError = function (rule, value) { + var message = _this.getMessage(rule, object, value); + errors.push(new validation_error_1.ValidationError(rule, message, object, rule.property.name)); + }; + // validate each rule. + var promises = []; + var _loop_1 = function(i) { + var rule = rules[i]; + // is the rule related to the property we're validating. + if (!validateAllProperties && rule.property.name !== propertyName) { + return "continue"; + } + // is this a conditional rule? is the condition met? + if (rule.when && !rule.when(object)) { + return "continue"; + } + // validate. + var value = rule.property.name === null ? object : object[rule.property.name]; + var promiseOrBoolean = rule.condition(value, object); + if (promiseOrBoolean instanceof Promise) { + promises.push(promiseOrBoolean.then(function (isValid) { + if (!isValid) { + addError(rule, value); + } + })); + return "continue"; + } + if (!promiseOrBoolean) { + addError(rule, value); + } + }; + for (var i = 0; i < rules.length; i++) { + _loop_1(i); + } + if (promises.length === 0) { + return Promise.resolve(errors); + } + return Promise.all(promises).then(function () { return errors; }); + }; + /** + * Validates the specified property. + * @param object The object to validate. + * @param propertyName The name of the property to validate. + * @param rules Optional. If unspecified, the rules will be looked up using the metadata + * for the object created by ValidationRules....on(class/object) + */ + StandardValidator.prototype.validateProperty = function (object, propertyName, rules) { + return this.validate(object, propertyName, rules || null); + }; + /** + * Validates all rules for specified object and it's properties. + * @param object The object to validate. + * @param rules Optional. If unspecified, the rules will be looked up using the metadata + * for the object created by ValidationRules....on(class/object) + */ + StandardValidator.prototype.validateObject = function (object, rules) { + return this.validate(object, null, rules || null); + }; + StandardValidator.inject = [validation_messages_1.ValidationMessageProvider, aurelia_templating_1.ViewResources]; + return StandardValidator; + }(validator_1.Validator)); + exports.StandardValidator = StandardValidator; +}); + +define('aurelia-validation/implementation/validation-messages',["require", "exports", './validation-parser'], function (require, exports, validation_parser_1) { + "use strict"; + /** + * Dictionary of validation messages. [messageKey]: messageExpression + */ + exports.validationMessages = { + /** + * The default validation message. Used with rules that have no standard message. + */ + default: "${$displayName} is invalid.", + required: "${$displayName} is required.", + matches: "${$displayName} is not correctly formatted.", + email: "${$displayName} is not a valid email.", + minLength: "${$displayName} must be at least ${$config.length} character${$config.length === 1 ? '' : 's'}.", + maxLength: "${$displayName} cannot be longer than ${$config.length} character${$config.length === 1 ? '' : 's'}.", + minItems: "${$displayName} must contain at least ${$config.count} item${$config.count === 1 ? '' : 's'}.", + maxItems: "${$displayName} cannot contain more than ${$config.count} item${$config.count === 1 ? '' : 's'}.", + equals: "${$displayName} must be ${$config.expectedValue}.", + }; + /** + * Retrieves validation messages and property display names. + */ + var ValidationMessageProvider = (function () { + function ValidationMessageProvider(parser) { + this.parser = parser; + } + /** + * Returns a message binding expression that corresponds to the key. + * @param key The message key. + */ + ValidationMessageProvider.prototype.getMessage = function (key) { + var message; + if (key in exports.validationMessages) { + message = exports.validationMessages[key]; + } + else { + message = exports.validationMessages['default']; + } + return this.parser.parseMessage(message); + }; + /** + * When a display name is not provided, this method is used to formulate + * a display name using the property name. + * Override this with your own custom logic. + * @param propertyName The property name. + */ + ValidationMessageProvider.prototype.getDisplayName = function (propertyName) { + // split on upper-case letters. + var words = propertyName.split(/(?=[A-Z])/).join(' '); + // capitalize first letter. + return words.charAt(0).toUpperCase() + words.slice(1); + }; + ValidationMessageProvider.inject = [validation_parser_1.ValidationParser]; + return ValidationMessageProvider; + }()); + exports.ValidationMessageProvider = ValidationMessageProvider; +}); + +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 __()); +}; +define('aurelia-validation/implementation/validation-parser',["require", "exports", 'aurelia-binding', 'aurelia-templating', './util', 'aurelia-logging'], function (require, exports, aurelia_binding_1, aurelia_templating_1, util_1, LogManager) { + "use strict"; + var ValidationParser = (function () { + function ValidationParser(parser, bindinqLanguage) { + this.parser = parser; + this.bindinqLanguage = bindinqLanguage; + this.emptyStringExpression = new aurelia_binding_1.LiteralString(''); + this.nullExpression = new aurelia_binding_1.LiteralPrimitive(null); + this.undefinedExpression = new aurelia_binding_1.LiteralPrimitive(undefined); + this.cache = {}; + } + ValidationParser.prototype.coalesce = function (part) { + // part === null || part === undefined ? '' : part + return new aurelia_binding_1.Conditional(new aurelia_binding_1.Binary('||', new aurelia_binding_1.Binary('===', part, this.nullExpression), new aurelia_binding_1.Binary('===', part, this.undefinedExpression)), this.emptyStringExpression, new aurelia_binding_1.CallMember(part, 'toString', [])); + }; + ValidationParser.prototype.parseMessage = function (message) { + if (this.cache[message] !== undefined) { + return this.cache[message]; + } + var parts = this.bindinqLanguage.parseInterpolation(null, message); + if (parts === null) { + return new aurelia_binding_1.LiteralString(message); + } + var expression = new aurelia_binding_1.LiteralString(parts[0]); + for (var i = 1; i < parts.length; i += 2) { + expression = new aurelia_binding_1.Binary('+', expression, new aurelia_binding_1.Binary('+', this.coalesce(parts[i]), new aurelia_binding_1.LiteralString(parts[i + 1]))); + } + MessageExpressionValidator.validate(expression, message); + this.cache[message] = expression; + return expression; + }; + ValidationParser.prototype.getAccessorExpression = function (fn) { + var classic = /^function\s*\([$_\w\d]+\)\s*\{\s*(?:"use strict";)?\s*return\s+[$_\w\d]+\.([$_\w\d]+)\s*;?\s*\}$/; + var arrow = /^[$_\w\d]+\s*=>\s*[$_\w\d]+\.([$_\w\d]+)$/; + var match = classic.exec(fn) || arrow.exec(fn); + if (match === null) { + throw new Error("Unable to parse accessor function:\n" + fn); + } + return this.parser.parse(match[1]); + }; + ValidationParser.prototype.parseProperty = function (property) { + var accessor; + if (util_1.isString(property)) { + accessor = this.parser.parse(property); + } + else { + accessor = this.getAccessorExpression(property.toString()); + } + if (accessor instanceof aurelia_binding_1.AccessScope + || accessor instanceof aurelia_binding_1.AccessMember && accessor.object instanceof aurelia_binding_1.AccessScope) { + return { + name: accessor.name, + displayName: null + }; + } + throw new Error("Invalid subject: \"" + accessor + "\""); + }; + ValidationParser.inject = [aurelia_binding_1.Parser, aurelia_templating_1.BindingLanguage]; + return ValidationParser; + }()); + exports.ValidationParser = ValidationParser; + var MessageExpressionValidator = (function (_super) { + __extends(MessageExpressionValidator, _super); + function MessageExpressionValidator(originalMessage) { + _super.call(this, []); + this.originalMessage = originalMessage; + } + MessageExpressionValidator.validate = function (expression, originalMessage) { + var visitor = new MessageExpressionValidator(originalMessage); + expression.accept(visitor); + }; + MessageExpressionValidator.prototype.visitAccessScope = function (access) { + if (access.ancestor !== 0) { + throw new Error('$parent is not permitted in validation message expressions.'); + } + if (['displayName', 'propertyName', 'value', 'object', 'config', 'getDisplayName'].indexOf(access.name) !== -1) { + LogManager.getLogger('aurelia-validation') + .warn("Did you mean to use \"$" + access.name + "\" instead of \"" + access.name + "\" in this validation message template: \"" + this.originalMessage + "\"?"); + } + }; + return MessageExpressionValidator; + }(aurelia_binding_1.Unparser)); + exports.MessageExpressionValidator = MessageExpressionValidator; +}); + +define('aurelia-validation/implementation/util',["require", "exports"], function (require, exports) { + "use strict"; + function isString(value) { + return Object.prototype.toString.call(value) === '[object String]'; + } + exports.isString = isString; +}); + +define('aurelia-validation/implementation/validation-rules',["require", "exports", './util', './rules', './validation-messages'], function (require, exports, util_1, rules_1, validation_messages_1) { + "use strict"; + /** + * Part of the fluent rule API. Enables customizing property rules. + */ + var FluentRuleCustomizer = (function () { + function FluentRuleCustomizer(property, condition, config, fluentEnsure, fluentRules, parser) { + if (config === void 0) { config = {}; } + this.fluentEnsure = fluentEnsure; + this.fluentRules = fluentRules; + this.parser = parser; + this.rule = { + property: property, + condition: condition, + config: config, + when: null, + messageKey: 'default', + message: null + }; + this.fluentEnsure.rules.push(this.rule); + } + /** + * Specifies the key to use when looking up the rule's validation message. + */ + FluentRuleCustomizer.prototype.withMessageKey = function (key) { + this.rule.messageKey = key; + this.rule.message = null; + return this; + }; + /** + * Specifies rule's validation message. + */ + FluentRuleCustomizer.prototype.withMessage = function (message) { + this.rule.messageKey = 'custom'; + this.rule.message = this.parser.parseMessage(message); + return this; + }; + /** + * Specifies a condition that must be met before attempting to validate the rule. + * @param condition A function that accepts the object as a parameter and returns true + * or false whether the rule should be evaluated. + */ + FluentRuleCustomizer.prototype.when = function (condition) { + this.rule.when = condition; + return this; + }; + /** + * Tags the rule instance, enabling the rule to be found easily + * using ValidationRules.taggedRules(rules, tag) + */ + FluentRuleCustomizer.prototype.tag = function (tag) { + this.rule.tag = tag; + return this; + }; + ///// FluentEnsure APIs ///// + /** + * Target a property with validation rules. + * @param property The property to target. Can be the property name or a property accessor function. + */ + FluentRuleCustomizer.prototype.ensure = function (subject) { + return this.fluentEnsure.ensure(subject); + }; + /** + * Targets an object with validation rules. + */ + FluentRuleCustomizer.prototype.ensureObject = function () { + return this.fluentEnsure.ensureObject(); + }; + Object.defineProperty(FluentRuleCustomizer.prototype, "rules", { + /** + * Rules that have been defined using the fluent API. + */ + get: function () { + return this.fluentEnsure.rules; + }, + enumerable: true, + configurable: true + }); + /** + * Applies the rules to a class or object, making them discoverable by the StandardValidator. + * @param target A class or object. + */ + FluentRuleCustomizer.prototype.on = function (target) { + return this.fluentEnsure.on(target); + }; + ///////// FluentRules APIs ///////// + /** + * Applies an ad-hoc rule function to the ensured property or object. + * @param condition The function to validate the rule. + * Will be called with two arguments, the property value and the object. + * Should return a boolean or a Promise that resolves to a boolean. + */ + FluentRuleCustomizer.prototype.satisfies = function (condition, config) { + return this.fluentRules.satisfies(condition, config); + }; + /** + * Applies a rule by name. + * @param name The name of the custom or standard rule. + * @param args The rule's arguments. + */ + FluentRuleCustomizer.prototype.satisfiesRule = function (name) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + return (_a = this.fluentRules).satisfiesRule.apply(_a, [name].concat(args)); + var _a; + }; + /** + * Applies the "required" rule to the property. + * The value cannot be null, undefined or whitespace. + */ + FluentRuleCustomizer.prototype.required = function () { + return this.fluentRules.required(); + }; + /** + * Applies the "matches" rule to the property. + * Value must match the specified regular expression. + * null, undefined and empty-string values are considered valid. + */ + FluentRuleCustomizer.prototype.matches = function (regex) { + return this.fluentRules.matches(regex); + }; + /** + * Applies the "email" rule to the property. + * null, undefined and empty-string values are considered valid. + */ + FluentRuleCustomizer.prototype.email = function () { + return this.fluentRules.email(); + }; + /** + * Applies the "minLength" STRING validation rule to the property. + * null, undefined and empty-string values are considered valid. + */ + FluentRuleCustomizer.prototype.minLength = function (length) { + return this.fluentRules.minLength(length); + }; + /** + * Applies the "maxLength" STRING validation rule to the property. + * null, undefined and empty-string values are considered valid. + */ + FluentRuleCustomizer.prototype.maxLength = function (length) { + return this.fluentRules.maxLength(length); + }; + /** + * Applies the "minItems" ARRAY validation rule to the property. + * null and undefined values are considered valid. + */ + FluentRuleCustomizer.prototype.minItems = function (count) { + return this.fluentRules.minItems(count); + }; + /** + * Applies the "maxItems" ARRAY validation rule to the property. + * null and undefined values are considered valid. + */ + FluentRuleCustomizer.prototype.maxItems = function (count) { + return this.fluentRules.maxItems(count); + }; + /** + * Applies the "equals" validation rule to the property. + * null, undefined and empty-string values are considered valid. + */ + FluentRuleCustomizer.prototype.equals = function (expectedValue) { + return this.fluentRules.equals(expectedValue); + }; + return FluentRuleCustomizer; + }()); + exports.FluentRuleCustomizer = FluentRuleCustomizer; + /** + * Part of the fluent rule API. Enables applying rules to properties and objects. + */ + var FluentRules = (function () { + function FluentRules(fluentEnsure, parser, property) { + this.fluentEnsure = fluentEnsure; + this.parser = parser; + this.property = property; + } + /** + * Sets the display name of the ensured property. + */ + FluentRules.prototype.displayName = function (name) { + this.property.displayName = name; + return this; + }; + /** + * Applies an ad-hoc rule function to the ensured property or object. + * @param condition The function to validate the rule. + * Will be called with two arguments, the property value and the object. + * Should return a boolean or a Promise that resolves to a boolean. + */ + FluentRules.prototype.satisfies = function (condition, config) { + return new FluentRuleCustomizer(this.property, condition, config, this.fluentEnsure, this, this.parser); + }; + /** + * Applies a rule by name. + * @param name The name of the custom or standard rule. + * @param args The rule's arguments. + */ + FluentRules.prototype.satisfiesRule = function (name) { + var _this = this; + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + var rule = FluentRules.customRules[name]; + if (!rule) { + // standard rule? + rule = this[name]; + if (rule instanceof Function) { + return rule.call.apply(rule, [this].concat(args)); + } + throw new Error("Rule with name \"" + name + "\" does not exist."); + } + var config = rule.argsToConfig ? rule.argsToConfig.apply(rule, args) : undefined; + return this.satisfies(function (value, obj) { return (_a = rule.condition).call.apply(_a, [_this, value, obj].concat(args)); var _a; }, config) + .withMessageKey(name); + }; + /** + * Applies the "required" rule to the property. + * The value cannot be null, undefined or whitespace. + */ + FluentRules.prototype.required = function () { + return this.satisfies(function (value) { + return value !== null + && value !== undefined + && !(util_1.isString(value) && !/\S/.test(value)); + }).withMessageKey('required'); + }; + /** + * Applies the "matches" rule to the property. + * Value must match the specified regular expression. + * null, undefined and empty-string values are considered valid. + */ + FluentRules.prototype.matches = function (regex) { + return this.satisfies(function (value) { return value === null || value === undefined || value.length === 0 || regex.test(value); }) + .withMessageKey('matches'); + }; + /** + * Applies the "email" rule to the property. + * null, undefined and empty-string values are considered valid. + */ + FluentRules.prototype.email = function () { + return this.matches(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/) + .withMessageKey('email'); + }; + /** + * Applies the "minLength" STRING validation rule to the property. + * null, undefined and empty-string values are considered valid. + */ + FluentRules.prototype.minLength = function (length) { + return this.satisfies(function (value) { return value === null || value === undefined || value.length === 0 || value.length >= length; }, { length: length }) + .withMessageKey('minLength'); + }; + /** + * Applies the "maxLength" STRING validation rule to the property. + * null, undefined and empty-string values are considered valid. + */ + FluentRules.prototype.maxLength = function (length) { + return this.satisfies(function (value) { return value === null || value === undefined || value.length === 0 || value.length <= length; }, { length: length }) + .withMessageKey('maxLength'); + }; + /** + * Applies the "minItems" ARRAY validation rule to the property. + * null and undefined values are considered valid. + */ + FluentRules.prototype.minItems = function (count) { + return this.satisfies(function (value) { return value === null || value === undefined || value.length >= count; }, { count: count }) + .withMessageKey('minItems'); + }; + /** + * Applies the "maxItems" ARRAY validation rule to the property. + * null and undefined values are considered valid. + */ + FluentRules.prototype.maxItems = function (count) { + return this.satisfies(function (value) { return value === null || value === undefined || value.length <= count; }, { count: count }) + .withMessageKey('maxItems'); + }; + /** + * Applies the "equals" validation rule to the property. + * null and undefined values are considered valid. + */ + FluentRules.prototype.equals = function (expectedValue) { + return this.satisfies(function (value) { return value === null || value === undefined || value === '' || value === expectedValue; }, { expectedValue: expectedValue }) + .withMessageKey('equals'); + }; + FluentRules.customRules = {}; + return FluentRules; + }()); + exports.FluentRules = FluentRules; + /** + * Part of the fluent rule API. Enables targeting properties and objects with rules. + */ + var FluentEnsure = (function () { + function FluentEnsure(parser) { + this.parser = parser; + /** + * Rules that have been defined using the fluent API. + */ + this.rules = []; + } + /** + * Target a property with validation rules. + * @param property The property to target. Can be the property name or a property accessor function. + */ + FluentEnsure.prototype.ensure = function (property) { + this.assertInitialized(); + return new FluentRules(this, this.parser, this.parser.parseProperty(property)); + }; + /** + * Targets an object with validation rules. + */ + FluentEnsure.prototype.ensureObject = function () { + this.assertInitialized(); + return new FluentRules(this, this.parser, { name: null, displayName: null }); + }; + /** + * Applies the rules to a class or object, making them discoverable by the StandardValidator. + * @param target A class or object. + */ + FluentEnsure.prototype.on = function (target) { + rules_1.Rules.set(target, this.rules); + return this; + }; + FluentEnsure.prototype.assertInitialized = function () { + if (this.parser) { + return; + } + throw new Error("Did you forget to add \".plugin('aurelia-validation)\" to your main.js?"); + }; + return FluentEnsure; + }()); + exports.FluentEnsure = FluentEnsure; + /** + * Fluent rule definition API. + */ + var ValidationRules = (function () { + function ValidationRules() { + } + ValidationRules.initialize = function (parser) { + ValidationRules.parser = parser; + }; + /** + * Target a property with validation rules. + * @param property The property to target. Can be the property name or a property accessor function. + */ + ValidationRules.ensure = function (property) { + return new FluentEnsure(ValidationRules.parser).ensure(property); + }; + /** + * Targets an object with validation rules. + */ + ValidationRules.ensureObject = function () { + return new FluentEnsure(ValidationRules.parser).ensureObject(); + }; + /** + * Defines a custom rule. + * @param name The name of the custom rule. Also serves as the message key. + * @param condition The rule function. + * @param message The message expression + * @param argsToConfig A function that maps the rule's arguments to a "config" object that can be used when evaluating the message expression. + */ + ValidationRules.customRule = function (name, condition, message, argsToConfig) { + validation_messages_1.validationMessages[name] = message; + FluentRules.customRules[name] = { condition: condition, argsToConfig: argsToConfig }; + }; + /** + * Returns rules with the matching tag. + * @param rules The rules to search. + * @param tag The tag to search for. + */ + ValidationRules.taggedRules = function (rules, tag) { + return rules.filter(function (r) { return r.tag === tag; }); + }; + /** + * Removes the rules from a class or object. + * @param target A class or object. + */ + ValidationRules.off = function (target) { + rules_1.Rules.unset(target); + }; + return ValidationRules; + }()); + exports.ValidationRules = ValidationRules; +}); + +define('text!app.html', ['module'], function(module) { module.exports = "\n"; }); +define('text!css/site.css', ['module'], function(module) { module.exports = "html {\n font-family: cursive\n}\n/* Move down content because we have a fixed navbar that is 50px tall */\nbody.chatle {\n padding-top: 50px;\n padding-bottom: 20px;\n}\n\n/* Wrapping element */\n/* Set some basic padding to keep content from hitting the edges */\n.body-content {\n padding-left: 15px;\n padding-right: 15px;\n}\n\n.navbar.navbar-default {\n background-color: #000;\n}\n\n.title.navbar-brand:focus,\n.title.navbar-brand:hover,\n.nav.navbar-nav > li > a:hover {\n color: #fff; \n}\n\nli:hover {\n cursor: pointer;\n}\n\n/* Set widths on the form inputs since otherwise they're 100% wide */\ninput,\nselect,\ntextarea {\n max-width: 280px;\n}\n\nul\n{\n padding-left: 0;\n list-style-type: none;\n}\n\nsmall {\n color: #666666;\n}\n\n/* Responsive: Portrait tablets and up */\n@media screen and (min-width: 768px) {\n .jumbotron {\n margin-top: 20px;\n }\n\n .body-content {\n padding: 0;\n }\n}\n\n.list-group-item,\n.list-group-item:first-child,\n.list-group-item:last-child {\n border: 0;\n padding: 0;\n border-radius: 0;\n}\n\n.list-group-item:hover {\n padding-right: 4px;\n padding-left: 4px;\n}\n\n.list-group-item.active {\n background-color: #fff;\n border-top: 1px solid #ccc;\n border-bottom: 1px solid #ccc;\n}\n\n.list-group-item.active:hover {\n background-color: #fff; \n border-color: #333;\n}\n\n.list-group-item.active span {\n color: #333;\n}"; }); +define('text!components/contact-list.html', ['module'], function(module) { module.exports = ""; }); +define('text!css/site.min.css', ['module'], function(module) { module.exports = "html{font-family:cursive}body{padding-top:50px;padding-bottom:20px}.console{font-family:'Lucida Console',Monaco,monospace}.body-content{padding-left:15px;padding-right:15px}.navbar.navbar-default{background-color:#fff}.nav.navbar-nav>li>a:hover,.title.navbar-brand:focus,.title.navbar-brand:hover{color:#222}input,select,textarea{max-width:280px}ul{padding-left:0;list-style-type:none}small{color:#666}@media screen and (min-width:768px){.jumbotron{margin-top:20px}.body-content{padding:0}}"; }); +define('text!components/contact.html', ['module'], function(module) { module.exports = ""; }); +define('text!components/conversation-component.html', ['module'], function(module) { module.exports = ""; }); +define('text!components/conversation-list.html', ['module'], function(module) { module.exports = ""; }); +define('text!components/conversation-preview.html', ['module'], function(module) { module.exports = ""; }); +define('text!components/user-name.html', ['module'], function(module) { module.exports = ">"; }); +define('text!pages/account.html', ['module'], function(module) { module.exports = ""; }); +define('text!pages/confirm.html', ['module'], function(module) { module.exports = ""; }); +define('text!pages/home.html', ['module'], function(module) { module.exports = ""; }); +define('text!pages/login.html', ['module'], function(module) { module.exports = ""; }); +//# sourceMappingURL=app-bundle.js.map \ No newline at end of file diff --git a/docs/scripts/chatle.signalR.js b/docs/scripts/chatle.signalR.js new file mode 100644 index 0000000..003e0f9 --- /dev/null +++ b/docs/scripts/chatle.signalR.js @@ -0,0 +1,89 @@ +/*! + * ASP.NET SignalR JavaScript Library v2.2.0-pre + * http://signalr.net/ + * + * Copyright Microsoft Open Technologies, Inc. All rights reserved. + * Licensed under the Apache 2.0 + * https://github.com/SignalR/SignalR/blob/master/LICENSE.md + * + */ +(function ($, window, undefined) { + /// + "use strict"; + + if (typeof ($.signalR) !== "function") { + throw new Error("SignalR: SignalR is not loaded. Please ensure jquery.signalR-x.js is referenced before ~/signalr/js."); + } + + var signalR = $.signalR; + + function makeProxyCallback(hub, callback) { + return function () { + // Call the client hub method + callback.apply(hub, $.makeArray(arguments)); + }; + } + + function registerHubProxies(instance, shouldSubscribe) { + var key, hub, memberKey, memberValue, subscriptionMethod; + + for (key in instance) { + if (instance.hasOwnProperty(key)) { + hub = instance[key]; + + if (!(hub.hubName)) { + // Not a client hub + continue; + } + + if (shouldSubscribe) { + // We want to subscribe to the hub events + subscriptionMethod = hub.on; + } else { + // We want to unsubscribe from the hub events + subscriptionMethod = hub.off; + } + + // Loop through all members on the hub and find client hub functions to subscribe/unsubscribe + for (memberKey in hub.client) { + if (hub.client.hasOwnProperty(memberKey)) { + memberValue = hub.client[memberKey]; + + if (!$.isFunction(memberValue)) { + // Not a client hub function + continue; + } + + subscriptionMethod.call(hub, memberKey, makeProxyCallback(hub, memberValue)); + } + } + } + } + } + + $.hubConnection.prototype.createHubProxies = function () { + var proxies = {}; + this.starting(function () { + // Register the hub proxies as subscribed + // (instance, shouldSubscribe) + registerHubProxies(proxies, true); + + this._registerSubscribedHubs(); + }).disconnected(function () { + // Unsubscribe all hub proxies when we "disconnect". This is to ensure that we do not re-add functional call backs. + // (instance, shouldSubscribe) + registerHubProxies(proxies, false); + }); + + proxies['chat'] = this.createHubProxy('chat'); + proxies['chat'].client = { }; + proxies['chat'].server = { + }; + + return proxies; + }; + + signalR.hub = $.hubConnection("http://localhost:5000/signalr", { useDefaultPath: false }); + $.extend(signalR, signalR.hub.createHubProxies()); + +}(window.jQuery, window)); \ No newline at end of file diff --git a/docs/scripts/jquery.signalR.min.js b/docs/scripts/jquery.signalR.min.js new file mode 100644 index 0000000..020a4f0 --- /dev/null +++ b/docs/scripts/jquery.signalR.min.js @@ -0,0 +1,9 @@ +/*! + * ASP.NET SignalR JavaScript Library v2.2.1 + * http://signalr.net/ + * + * Copyright (c) .NET Foundation. All rights reserved. + * Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + * + */ +(function(n,t,i){function w(t,i){var u,f;if(n.isArray(t)){for(u=t.length-1;u>=0;u--)f=t[u],n.type(f)==="string"&&r.transports[f]||(i.log("Invalid transport: "+f+", removing it from the transports list."),t.splice(u,1));t.length===0&&(i.log("No transports remain within the specified transport array."),t=null)}else if(r.transports[t]||t==="auto"){if(t==="auto"&&r._.ieVersion<=8)return["longPolling"]}else i.log("Invalid transport: "+t.toString()+"."),t=null;return t}function b(n){return n==="http:"?80:n==="https:"?443:void 0}function a(n,t){return t.match(/:\d+$/)?t:t+":"+b(n)}function k(t,i){var u=this,r=[];u.tryBuffer=function(i){return t.state===n.signalR.connectionState.connecting?(r.push(i),!0):!1};u.drain=function(){if(t.state===n.signalR.connectionState.connected)while(r.length>0)i(r.shift())};u.clear=function(){r=[]}}var f={nojQuery:"jQuery was not found. Please ensure jQuery is referenced before the SignalR client JavaScript file.",noTransportOnInit:"No transport could be initialized successfully. Try specifying a different transport or none at all for auto initialization.",errorOnNegotiate:"Error during negotiation request.",stoppedWhileLoading:"The connection was stopped during page load.",stoppedWhileNegotiating:"The connection was stopped during the negotiate request.",errorParsingNegotiateResponse:"Error parsing negotiate response.",errorDuringStartRequest:"Error during start request. Stopping the connection.",stoppedDuringStartRequest:"The connection was stopped during the start request.",errorParsingStartResponse:"Error parsing start response: '{0}'. Stopping the connection.",invalidStartResponse:"Invalid start response: '{0}'. Stopping the connection.",protocolIncompatible:"You are using a version of the client that isn't compatible with the server. Client version {0}, server version {1}.",sendFailed:"Send failed.",parseFailed:"Failed at parsing response: {0}",longPollFailed:"Long polling request failed.",eventSourceFailedToConnect:"EventSource failed to connect.",eventSourceError:"Error raised by EventSource",webSocketClosed:"WebSocket closed.",pingServerFailedInvalidResponse:"Invalid ping response when pinging server: '{0}'.",pingServerFailed:"Failed to ping server.",pingServerFailedStatusCode:"Failed to ping server. Server responded with status code {0}, stopping the connection.",pingServerFailedParse:"Failed to parse ping server response, stopping the connection.",noConnectionTransport:"Connection is in an invalid state, there is no transport active.",webSocketsInvalidState:"The Web Socket transport is in an invalid state, transitioning into reconnecting.",reconnectTimeout:"Couldn't reconnect within the configured timeout of {0} ms, disconnecting.",reconnectWindowTimeout:"The client has been inactive since {0} and it has exceeded the inactivity timeout of {1} ms. Stopping the connection."};if(typeof n!="function")throw new Error(f.nojQuery);var r,h,o=t.document.readyState==="complete",e=n(t),c="__Negotiate Aborted__",u={onStart:"onStart",onStarting:"onStarting",onReceived:"onReceived",onError:"onError",onConnectionSlow:"onConnectionSlow",onReconnecting:"onReconnecting",onReconnect:"onReconnect",onStateChanged:"onStateChanged",onDisconnect:"onDisconnect"},v=function(n,i){if(i!==!1){var r;typeof t.console!="undefined"&&(r="["+(new Date).toTimeString()+"] SignalR: "+n,t.console.debug?t.console.debug(r):t.console.log&&t.console.log(r))}},s=function(t,i,r){return i===t.state?(t.state=r,n(t).triggerHandler(u.onStateChanged,[{oldState:i,newState:r}]),!0):!1},y=function(n){return n.state===r.connectionState.disconnected},l=function(n){return n._.keepAliveData.activated&&n.transport.supportsKeepAlive(n)},p=function(i){var f,e;i._.configuredStopReconnectingTimeout||(e=function(t){var i=r._.format(r.resources.reconnectTimeout,t.disconnectTimeout);t.log(i);n(t).triggerHandler(u.onError,[r._.error(i,"TimeoutException")]);t.stop(!1,!1)},i.reconnecting(function(){var n=this;n.state===r.connectionState.reconnecting&&(f=t.setTimeout(function(){e(n)},n.disconnectTimeout))}),i.stateChanged(function(n){n.oldState===r.connectionState.reconnecting&&t.clearTimeout(f)}),i._.configuredStopReconnectingTimeout=!0)};if(r=function(n,t,i){return new r.fn.init(n,t,i)},r._={defaultContentType:"application/x-www-form-urlencoded; charset=UTF-8",ieVersion:function(){var i,n;return t.navigator.appName==="Microsoft Internet Explorer"&&(n=/MSIE ([0-9]+\.[0-9]+)/.exec(t.navigator.userAgent),n&&(i=t.parseFloat(n[1]))),i}(),error:function(n,t,i){var r=new Error(n);return r.source=t,typeof i!="undefined"&&(r.context=i),r},transportError:function(n,t,r,u){var f=this.error(n,r,u);return f.transport=t?t.name:i,f},format:function(){for(var t=arguments[0],n=0;n<\/script>.");}},typeof e.on=="function")e.on("load",function(){o=!0});else e.load(function(){o=!0});r.fn=r.prototype={init:function(t,i,r){var f=n(this);this.url=t;this.qs=i;this.lastError=null;this._={keepAliveData:{},connectingMessageBuffer:new k(this,function(n){f.triggerHandler(u.onReceived,[n])}),lastMessageAt:(new Date).getTime(),lastActiveAt:(new Date).getTime(),beatInterval:5e3,beatHandle:null,totalTransportConnectTimeout:0};typeof r=="boolean"&&(this.logging=r)},_parseResponse:function(n){var t=this;return n?typeof n=="string"?t.json.parse(n):n:n},_originalJson:t.JSON,json:t.JSON,isCrossDomain:function(i,r){var u;return(i=n.trim(i),r=r||t.location,i.indexOf("http")!==0)?!1:(u=t.document.createElement("a"),u.href=i,u.protocol+a(u.protocol,u.host)!==r.protocol+a(r.protocol,r.host))},ajaxDataType:"text",contentType:"application/json; charset=UTF-8",logging:!1,state:r.connectionState.disconnected,clientProtocol:"1.5",reconnectDelay:2e3,transportConnectTimeout:0,disconnectTimeout:3e4,reconnectWindow:3e4,keepAliveWarnAt:2/3,start:function(i,h){var a=this,v={pingInterval:3e5,waitForPageLoad:!0,transport:"auto",jsonp:!1},d,y=a._deferral||n.Deferred(),b=t.document.createElement("a"),k,g;if(a.lastError=null,a._deferral=y,!a.json)throw new Error("SignalR: No JSON parser found. Please ensure json2.js is referenced before the SignalR.js file if you need to support clients without native JSON parsing support, e.g. IE<8.");if(n.type(i)==="function"?h=i:n.type(i)==="object"&&(n.extend(v,i),n.type(v.callback)==="function"&&(h=v.callback)),v.transport=w(v.transport,a),!v.transport)throw new Error("SignalR: Invalid transport(s) specified, aborting start.");return(a._.config=v,!o&&v.waitForPageLoad===!0)?(a._.deferredStartHandler=function(){a.start(i,h)},e.bind("load",a._.deferredStartHandler),y.promise()):a.state===r.connectionState.connecting?y.promise():s(a,r.connectionState.disconnected,r.connectionState.connecting)===!1?(y.resolve(a),y.promise()):(p(a),b.href=a.url,b.protocol&&b.protocol!==":"?(a.protocol=b.protocol,a.host=b.host):(a.protocol=t.document.location.protocol,a.host=b.host||t.document.location.host),a.baseUrl=a.protocol+"//"+a.host,a.wsProtocol=a.protocol==="https:"?"wss://":"ws://",v.transport==="auto"&&v.jsonp===!0&&(v.transport="longPolling"),a.url.indexOf("//")===0&&(a.url=t.location.protocol+a.url,a.log("Protocol relative URL detected, normalizing it to '"+a.url+"'.")),this.isCrossDomain(a.url)&&(a.log("Auto detected cross domain url."),v.transport==="auto"&&(v.transport=["webSockets","serverSentEvents","longPolling"]),typeof v.withCredentials=="undefined"&&(v.withCredentials=!0),v.jsonp||(v.jsonp=!n.support.cors,v.jsonp&&a.log("Using jsonp because this browser doesn't support CORS.")),a.contentType=r._.defaultContentType),a.withCredentials=v.withCredentials,a.ajaxDataType=v.jsonp?"jsonp":"text",n(a).bind(u.onStart,function(){n.type(h)==="function"&&h.call(a);y.resolve(a)}),a._.initHandler=r.transports._logic.initHandler(a),d=function(i,o){var c=r._.error(f.noTransportOnInit);if(o=o||0,o>=i.length){o===0?a.log("No transports supported by the server were selected."):o===1?a.log("No fallback transports were selected."):a.log("Fallback transports exhausted.");n(a).triggerHandler(u.onError,[c]);y.reject(c);a.stop();return}if(a.state!==r.connectionState.disconnected){var p=i[o],h=r.transports[p],v=function(){d(i,o+1)};a.transport=h;try{a._.initHandler.start(h,function(){var i=r._.firefoxMajorVersion(t.navigator.userAgent)>=11,f=!!a.withCredentials&&i;a.log("The start request succeeded. Transitioning to the connected state.");l(a)&&r.transports._logic.monitorKeepAlive(a);r.transports._logic.startHeartbeat(a);r._.configurePingInterval(a);s(a,r.connectionState.connecting,r.connectionState.connected)||a.log("WARNING! The connection was not in the connecting state.");a._.connectingMessageBuffer.drain();n(a).triggerHandler(u.onStart);e.bind("unload",function(){a.log("Window unloading, stopping the connection.");a.stop(f)});i&&e.bind("beforeunload",function(){t.setTimeout(function(){a.stop(f)},0)})},v)}catch(w){a.log(h.name+" transport threw '"+w.message+"' when attempting to start.");v()}}},k=a.url+"/negotiate",g=function(t,i){var e=r._.error(f.errorOnNegotiate,t,i._.negotiateRequest);n(i).triggerHandler(u.onError,e);y.reject(e);i.stop()},n(a).triggerHandler(u.onStarting),k=r.transports._logic.prepareQueryString(a,k),a.log("Negotiating with '"+k+"'."),a._.negotiateRequest=r.transports._logic.ajax(a,{url:k,error:function(n,t){t!==c?g(n,a):y.reject(r._.error(f.stoppedWhileNegotiating,null,a._.negotiateRequest))},success:function(t){var i,e,h,o=[],s=[];try{i=a._parseResponse(t)}catch(c){g(r._.error(f.errorParsingNegotiateResponse,c),a);return}if(e=a._.keepAliveData,a.appRelativeUrl=i.Url,a.id=i.ConnectionId,a.token=i.ConnectionToken,a.webSocketServerUrl=i.WebSocketServerUrl,a._.pollTimeout=i.ConnectionTimeout*1e3+1e4,a.disconnectTimeout=i.DisconnectTimeout*1e3,a._.totalTransportConnectTimeout=a.transportConnectTimeout+i.TransportConnectTimeout*1e3,i.KeepAliveTimeout?(e.activated=!0,e.timeout=i.KeepAliveTimeout*1e3,e.timeoutWarning=e.timeout*a.keepAliveWarnAt,a._.beatInterval=(e.timeout-e.timeoutWarning)/3):e.activated=!1,a.reconnectWindow=a.disconnectTimeout+(e.timeout||0),!i.ProtocolVersion||i.ProtocolVersion!==a.clientProtocol){h=r._.error(r._.format(f.protocolIncompatible,a.clientProtocol,i.ProtocolVersion));n(a).triggerHandler(u.onError,[h]);y.reject(h);return}n.each(r.transports,function(n){if(n.indexOf("_")===0||n==="webSockets"&&!i.TryWebSockets)return!0;s.push(n)});n.isArray(v.transport)?n.each(v.transport,function(t,i){n.inArray(i,s)>=0&&o.push(i)}):v.transport==="auto"?o=s:n.inArray(v.transport,s)>=0&&o.push(v.transport);d(o)}}),y.promise())},starting:function(t){var i=this;return n(i).bind(u.onStarting,function(){t.call(i)}),i},send:function(n){var t=this;if(t.state===r.connectionState.disconnected)throw new Error("SignalR: Connection must be started before data can be sent. Call .start() before .send()");if(t.state===r.connectionState.connecting)throw new Error("SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started.");return t.transport.send(t,n),t},received:function(t){var i=this;return n(i).bind(u.onReceived,function(n,r){t.call(i,r)}),i},stateChanged:function(t){var i=this;return n(i).bind(u.onStateChanged,function(n,r){t.call(i,r)}),i},error:function(t){var i=this;return n(i).bind(u.onError,function(n,r,u){i.lastError=r;t.call(i,r,u)}),i},disconnected:function(t){var i=this;return n(i).bind(u.onDisconnect,function(){t.call(i)}),i},connectionSlow:function(t){var i=this;return n(i).bind(u.onConnectionSlow,function(){t.call(i)}),i},reconnecting:function(t){var i=this;return n(i).bind(u.onReconnecting,function(){t.call(i)}),i},reconnected:function(t){var i=this;return n(i).bind(u.onReconnect,function(){t.call(i)}),i},stop:function(i,h){var a=this,v=a._deferral;if(a._.deferredStartHandler&&e.unbind("load",a._.deferredStartHandler),delete a._.config,delete a._.deferredStartHandler,!o&&(!a._.config||a._.config.waitForPageLoad===!0)){a.log("Stopping connection prior to negotiate.");v&&v.reject(r._.error(f.stoppedWhileLoading));return}if(a.state!==r.connectionState.disconnected)return a.log("Stopping connection."),t.clearTimeout(a._.beatHandle),t.clearInterval(a._.pingIntervalId),a.transport&&(a.transport.stop(a),h!==!1&&a.transport.abort(a,i),l(a)&&r.transports._logic.stopMonitoringKeepAlive(a),a.transport=null),a._.negotiateRequest&&(a._.negotiateRequest.abort(c),delete a._.negotiateRequest),a._.initHandler&&a._.initHandler.stop(),delete a._deferral,delete a.messageId,delete a.groupsToken,delete a.id,delete a._.pingIntervalId,delete a._.lastMessageAt,delete a._.lastActiveAt,a._.connectingMessageBuffer.clear(),s(a,a.state,r.connectionState.disconnected),n(a).triggerHandler(u.onDisconnect),a},log:function(n){v(n,this.logging)}};r.fn.init.prototype=r.fn;r.noConflict=function(){return n.connection===r&&(n.connection=h),r};n.connection&&(h=n.connection);n.connection=n.signalR=r})(window.jQuery,window),function(n,t,i){function s(n){n._.keepAliveData.monitoring&&l(n);u.markActive(n)&&(n._.beatHandle=t.setTimeout(function(){s(n)},n._.beatInterval))}function l(t){var i=t._.keepAliveData,u;t.state===r.connectionState.connected&&(u=(new Date).getTime()-t._.lastMessageAt,u>=i.timeout?(t.log("Keep alive timed out. Notifying transport that connection has been lost."),t.transport.lostConnection(t)):u>=i.timeoutWarning?i.userNotified||(t.log("Keep alive has been missed, connection may be dead/slow."),n(t).triggerHandler(f.onConnectionSlow),i.userNotified=!0):i.userNotified=!1)}function e(n,t){var i=n.url+t;return n.transport&&(i+="?transport="+n.transport.name),u.prepareQueryString(n,i)}function h(n){this.connection=n;this.startRequested=!1;this.startCompleted=!1;this.connectionStopped=!1}var r=n.signalR,f=n.signalR.events,c=n.signalR.changeState,o="__Start Aborted__",u;r.transports={};h.prototype={start:function(n,r,u){var f=this,e=f.connection,o=!1;if(f.startRequested||f.connectionStopped){e.log("WARNING! "+n.name+" transport cannot be started. Initialization ongoing or completed.");return}e.log(n.name+" transport starting.");n.start(e,function(){o||f.initReceived(n,r)},function(t){return o||(o=!0,f.transportFailed(n,t,u)),!f.startCompleted||f.connectionStopped});f.transportTimeoutHandle=t.setTimeout(function(){o||(o=!0,e.log(n.name+" transport timed out when trying to connect."),f.transportFailed(n,i,u))},e._.totalTransportConnectTimeout)},stop:function(){this.connectionStopped=!0;t.clearTimeout(this.transportTimeoutHandle);r.transports._logic.tryAbortStartRequest(this.connection)},initReceived:function(n,i){var u=this,f=u.connection;if(u.startRequested){f.log("WARNING! The client received multiple init messages.");return}u.connectionStopped||(u.startRequested=!0,t.clearTimeout(u.transportTimeoutHandle),f.log(n.name+" transport connected. Initiating start request."),r.transports._logic.ajaxStart(f,function(){u.startCompleted=!0;i()}))},transportFailed:function(i,u,e){var o=this.connection,h=o._deferral,s;this.connectionStopped||(t.clearTimeout(this.transportTimeoutHandle),this.startRequested?this.startCompleted||(s=r._.error(r.resources.errorDuringStartRequest,u),o.log(i.name+" transport failed during the start request. Stopping the connection."),n(o).triggerHandler(f.onError,[s]),h&&h.reject(s),o.stop()):(i.stop(o),o.log(i.name+" transport failed to connect. Attempting to fall back."),e()))}};u=r.transports._logic={ajax:function(t,i){return n.ajax(n.extend(!0,{},n.signalR.ajaxDefaults,{type:"GET",data:{},xhrFields:{withCredentials:t.withCredentials},contentType:t.contentType,dataType:t.ajaxDataType},i))},pingServer:function(t){var e,f,i=n.Deferred();return t.transport?(e=t.url+"/ping",e=u.addQs(e,t.qs),f=u.ajax(t,{url:e,success:function(n){var u;try{u=t._parseResponse(n)}catch(e){i.reject(r._.transportError(r.resources.pingServerFailedParse,t.transport,e,f));t.stop();return}u.Response==="pong"?i.resolve():i.reject(r._.transportError(r._.format(r.resources.pingServerFailedInvalidResponse,n),t.transport,null,f))},error:function(n){n.status===401||n.status===403?(i.reject(r._.transportError(r._.format(r.resources.pingServerFailedStatusCode,n.status),t.transport,n,f)),t.stop()):i.reject(r._.transportError(r.resources.pingServerFailed,t.transport,n,f))}})):i.reject(r._.transportError(r.resources.noConnectionTransport,t.transport)),i.promise()},prepareQueryString:function(n,i){var r;return r=u.addQs(i,"clientProtocol="+n.clientProtocol),r=u.addQs(r,n.qs),n.token&&(r+="&connectionToken="+t.encodeURIComponent(n.token)),n.data&&(r+="&connectionData="+t.encodeURIComponent(n.data)),r},addQs:function(t,i){var r=t.indexOf("?")!==-1?"&":"?",u;if(!i)return t;if(typeof i=="object")return t+r+n.param(i);if(typeof i=="string")return u=i.charAt(0),(u==="?"||u==="&")&&(r=""),t+r+i;throw new Error("Query string property must be either a string or object.");},getUrl:function(n,i,r,f,e){var h=i==="webSockets"?"":n.baseUrl,o=h+n.appRelativeUrl,s="transport="+i;return!e&&n.groupsToken&&(s+="&groupsToken="+t.encodeURIComponent(n.groupsToken)),r?(o+=f?"/poll":"/reconnect",!e&&n.messageId&&(s+="&messageId="+t.encodeURIComponent(n.messageId))):o+="/connect",o+="?"+s,o=u.prepareQueryString(n,o),e||(o+="&tid="+Math.floor(Math.random()*11)),o},maximizePersistentResponse:function(n){return{MessageId:n.C,Messages:n.M,Initialized:typeof n.S!="undefined"?!0:!1,ShouldReconnect:typeof n.T!="undefined"?!0:!1,LongPollDelay:n.L,GroupsToken:n.G}},updateGroups:function(n,t){t&&(n.groupsToken=t)},stringifySend:function(n,t){return typeof t=="string"||typeof t=="undefined"||t===null?t:n.json.stringify(t)},ajaxSend:function(t,i){var h=u.stringifySend(t,i),c=e(t,"/send"),o,s=function(t,u){n(u).triggerHandler(f.onError,[r._.transportError(r.resources.sendFailed,u.transport,t,o),i])};return o=u.ajax(t,{url:c,type:t.ajaxDataType==="jsonp"?"GET":"POST",contentType:r._.defaultContentType,data:{data:h},success:function(n){var i;if(n){try{i=t._parseResponse(n)}catch(r){s(r,t);t.stop();return}u.triggerReceived(t,i)}},error:function(n,i){i!=="abort"&&i!=="parsererror"&&s(n,t)}})},ajaxAbort:function(n,t){if(typeof n.transport!="undefined"){t=typeof t=="undefined"?!0:t;var i=e(n,"/abort");u.ajax(n,{url:i,async:t,timeout:1e3,type:"POST"});n.log("Fired ajax abort async = "+t+".")}},ajaxStart:function(t,i){var h=function(n){var i=t._deferral;i&&i.reject(n)},s=function(i){t.log("The start request failed. Stopping the connection.");n(t).triggerHandler(f.onError,[i]);h(i);t.stop()};t._.startRequest=u.ajax(t,{url:e(t,"/start"),success:function(n,u,f){var e;try{e=t._parseResponse(n)}catch(o){s(r._.error(r._.format(r.resources.errorParsingStartResponse,n),o,f));return}e.Response==="started"?i():s(r._.error(r._.format(r.resources.invalidStartResponse,n),null,f))},error:function(n,i,u){i!==o?s(r._.error(r.resources.errorDuringStartRequest,u,n)):(t.log("The start request aborted because connection.stop() was called."),h(r._.error(r.resources.stoppedDuringStartRequest,null,n)))}})},tryAbortStartRequest:function(n){n._.startRequest&&(n._.startRequest.abort(o),delete n._.startRequest)},tryInitialize:function(n,t,i){t.Initialized&&i?i():t.Initialized&&n.log("WARNING! The client received an init message after reconnecting.")},triggerReceived:function(t,i){t._.connectingMessageBuffer.tryBuffer(i)||n(t).triggerHandler(f.onReceived,[i])},processMessages:function(t,i,r){var f;u.markLastMessage(t);i&&(f=u.maximizePersistentResponse(i),u.updateGroups(t,f.GroupsToken),f.MessageId&&(t.messageId=f.MessageId),f.Messages&&(n.each(f.Messages,function(n,i){u.triggerReceived(t,i)}),u.tryInitialize(t,f,r)))},monitorKeepAlive:function(t){var i=t._.keepAliveData;i.monitoring?t.log("Tried to monitor keep alive but it's already being monitored."):(i.monitoring=!0,u.markLastMessage(t),t._.keepAliveData.reconnectKeepAliveUpdate=function(){u.markLastMessage(t)},n(t).bind(f.onReconnect,t._.keepAliveData.reconnectKeepAliveUpdate),t.log("Now monitoring keep alive with a warning timeout of "+i.timeoutWarning+", keep alive timeout of "+i.timeout+" and disconnecting timeout of "+t.disconnectTimeout))},stopMonitoringKeepAlive:function(t){var i=t._.keepAliveData;i.monitoring&&(i.monitoring=!1,n(t).unbind(f.onReconnect,t._.keepAliveData.reconnectKeepAliveUpdate),t._.keepAliveData={},t.log("Stopping the monitoring of the keep alive."))},startHeartbeat:function(n){n._.lastActiveAt=(new Date).getTime();s(n)},markLastMessage:function(n){n._.lastMessageAt=(new Date).getTime()},markActive:function(n){return u.verifyLastActive(n)?(n._.lastActiveAt=(new Date).getTime(),!0):!1},isConnectedOrReconnecting:function(n){return n.state===r.connectionState.connected||n.state===r.connectionState.reconnecting},ensureReconnectingState:function(t){return c(t,r.connectionState.connected,r.connectionState.reconnecting)===!0&&n(t).triggerHandler(f.onReconnecting),t.state===r.connectionState.reconnecting},clearReconnectTimeout:function(n){n&&n._.reconnectTimeout&&(t.clearTimeout(n._.reconnectTimeout),delete n._.reconnectTimeout)},verifyLastActive:function(t){if((new Date).getTime()-t._.lastActiveAt>=t.reconnectWindow){var i=r._.format(r.resources.reconnectWindowTimeout,new Date(t._.lastActiveAt),t.reconnectWindow);return t.log(i),n(t).triggerHandler(f.onError,[r._.error(i,"TimeoutException")]),t.stop(!1,!1),!1}return!0},reconnect:function(n,i){var f=r.transports[i];if(u.isConnectedOrReconnecting(n)&&!n._.reconnectTimeout){if(!u.verifyLastActive(n))return;n._.reconnectTimeout=t.setTimeout(function(){u.verifyLastActive(n)&&(f.stop(n),u.ensureReconnectingState(n)&&(n.log(i+" reconnecting."),f.start(n)))},n.reconnectDelay)}},handleParseFailure:function(t,i,u,e,o){var s=r._.transportError(r._.format(r.resources.parseFailed,i),t.transport,u,o);e&&e(s)?t.log("Failed to parse server response while attempting to connect."):(n(t).triggerHandler(f.onError,[s]),t.stop())},initHandler:function(n){return new h(n)},foreverFrame:{count:0,connections:{}}}}(window.jQuery,window),function(n,t){var r=n.signalR,u=n.signalR.events,f=n.signalR.changeState,i=r.transports._logic;r.transports.webSockets={name:"webSockets",supportsKeepAlive:function(){return!0},send:function(t,f){var e=i.stringifySend(t,f);try{t.socket.send(e)}catch(o){n(t).triggerHandler(u.onError,[r._.transportError(r.resources.webSocketsInvalidState,t.transport,o,t.socket),f])}},start:function(e,o,s){var h,c=!1,l=this,a=!o,v=n(e);if(!t.WebSocket){s();return}e.socket||(h=e.webSocketServerUrl?e.webSocketServerUrl:e.wsProtocol+e.host,h+=i.getUrl(e,this.name,a),e.log("Connecting to websocket endpoint '"+h+"'."),e.socket=new t.WebSocket(h),e.socket.onopen=function(){c=!0;e.log("Websocket opened.");i.clearReconnectTimeout(e);f(e,r.connectionState.reconnecting,r.connectionState.connected)===!0&&v.triggerHandler(u.onReconnect)},e.socket.onclose=function(t){var i;this===e.socket&&(c&&typeof t.wasClean!="undefined"&&t.wasClean===!1?(i=r._.transportError(r.resources.webSocketClosed,e.transport,t),e.log("Unclean disconnect from websocket: "+(t.reason||"[no reason given]."))):e.log("Websocket closed."),s&&s(i)||(i&&n(e).triggerHandler(u.onError,[i]),l.reconnect(e)))},e.socket.onmessage=function(t){var r;try{r=e._parseResponse(t.data)}catch(u){i.handleParseFailure(e,t.data,u,s,t);return}r&&(n.isEmptyObject(r)||r.M?i.processMessages(e,r,o):i.triggerReceived(e,r))})},reconnect:function(n){i.reconnect(n,this.name)},lostConnection:function(n){this.reconnect(n)},stop:function(n){i.clearReconnectTimeout(n);n.socket&&(n.log("Closing the Websocket."),n.socket.close(),n.socket=null)},abort:function(n,t){i.ajaxAbort(n,t)}}}(window.jQuery,window),function(n,t){var i=n.signalR,u=n.signalR.events,e=n.signalR.changeState,r=i.transports._logic,f=function(n){t.clearTimeout(n._.reconnectAttemptTimeoutHandle);delete n._.reconnectAttemptTimeoutHandle};i.transports.serverSentEvents={name:"serverSentEvents",supportsKeepAlive:function(){return!0},timeOut:3e3,start:function(o,s,h){var c=this,l=!1,a=n(o),v=!s,y;if(o.eventSource&&(o.log("The connection already has an event source. Stopping it."),o.stop()),!t.EventSource){h&&(o.log("This browser doesn't support SSE."),h());return}y=r.getUrl(o,this.name,v);try{o.log("Attempting to connect to SSE endpoint '"+y+"'.");o.eventSource=new t.EventSource(y,{withCredentials:o.withCredentials})}catch(p){o.log("EventSource failed trying to connect with error "+p.Message+".");h?h():(a.triggerHandler(u.onError,[i._.transportError(i.resources.eventSourceFailedToConnect,o.transport,p)]),v&&c.reconnect(o));return}v&&(o._.reconnectAttemptTimeoutHandle=t.setTimeout(function(){l===!1&&o.eventSource.readyState!==t.EventSource.OPEN&&c.reconnect(o)},c.timeOut));o.eventSource.addEventListener("open",function(){o.log("EventSource connected.");f(o);r.clearReconnectTimeout(o);l===!1&&(l=!0,e(o,i.connectionState.reconnecting,i.connectionState.connected)===!0&&a.triggerHandler(u.onReconnect))},!1);o.eventSource.addEventListener("message",function(n){var t;if(n.data!=="initialized"){try{t=o._parseResponse(n.data)}catch(i){r.handleParseFailure(o,n.data,i,h,n);return}r.processMessages(o,t,s)}},!1);o.eventSource.addEventListener("error",function(n){var r=i._.transportError(i.resources.eventSourceError,o.transport,n);this===o.eventSource&&(h&&h(r)||(o.log("EventSource readyState: "+o.eventSource.readyState+"."),n.eventPhase===t.EventSource.CLOSED?(o.log("EventSource reconnecting due to the server connection ending."),c.reconnect(o)):(o.log("EventSource error."),a.triggerHandler(u.onError,[r]))))},!1)},reconnect:function(n){r.reconnect(n,this.name)},lostConnection:function(n){this.reconnect(n)},send:function(n,t){r.ajaxSend(n,t)},stop:function(n){f(n);r.clearReconnectTimeout(n);n&&n.eventSource&&(n.log("EventSource calling close()."),n.eventSource.close(),n.eventSource=null,delete n.eventSource)},abort:function(n,t){r.ajaxAbort(n,t)}}}(window.jQuery,window),function(n,t){var r=n.signalR,e=n.signalR.events,o=n.signalR.changeState,i=r.transports._logic,u=function(){var n=t.document.createElement("iframe");return n.setAttribute("style","position:absolute;top:0;left:0;width:0;height:0;visibility:hidden;"),n},f=function(){var i=null,f=1e3,n=0;return{prevent:function(){r._.ieVersion<=8&&(n===0&&(i=t.setInterval(function(){var n=u();t.document.body.appendChild(n);t.document.body.removeChild(n);n=null},f)),n++)},cancel:function(){n===1&&t.clearInterval(i);n>0&&n--}}}();r.transports.foreverFrame={name:"foreverFrame",supportsKeepAlive:function(){return!0},iframeClearThreshold:50,start:function(n,r,e){var l=this,s=i.foreverFrame.count+=1,h,o=u(),c=function(){n.log("Forever frame iframe finished loading and is no longer receiving messages.");e&&e()||l.reconnect(n)};if(t.EventSource){e&&(n.log("Forever Frame is not supported by SignalR on browsers with SSE support."),e());return}o.setAttribute("data-signalr-connection-id",n.id);f.prevent();h=i.getUrl(n,this.name);h+="&frameId="+s;t.document.documentElement.appendChild(o);n.log("Binding to iframe's load event.");o.addEventListener?o.addEventListener("load",c,!1):o.attachEvent&&o.attachEvent("onload",c);o.src=h;i.foreverFrame.connections[s]=n;n.frame=o;n.frameId=s;r&&(n.onSuccess=function(){n.log("Iframe transport started.");r()})},reconnect:function(n){var r=this;i.isConnectedOrReconnecting(n)&&i.verifyLastActive(n)&&t.setTimeout(function(){if(i.verifyLastActive(n)&&n.frame&&i.ensureReconnectingState(n)){var u=n.frame,t=i.getUrl(n,r.name,!0)+"&frameId="+n.frameId;n.log("Updating iframe src to '"+t+"'.");u.src=t}},n.reconnectDelay)},lostConnection:function(n){this.reconnect(n)},send:function(n,t){i.ajaxSend(n,t)},receive:function(t,u){var f,e,o;if(t.json!==t._originalJson&&(u=t._originalJson.stringify(u)),o=t._parseResponse(u),i.processMessages(t,o,t.onSuccess),t.state===n.signalR.connectionState.connected&&(t.frameMessageCount=(t.frameMessageCount||0)+1,t.frameMessageCount>r.transports.foreverFrame.iframeClearThreshold&&(t.frameMessageCount=0,f=t.frame.contentWindow||t.frame.contentDocument,f&&f.document&&f.document.body)))for(e=f.document.body;e.firstChild;)e.removeChild(e.firstChild)},stop:function(n){var r=null;if(f.cancel(),n.frame){if(n.frame.stop)n.frame.stop();else try{r=n.frame.contentWindow||n.frame.contentDocument;r.document&&r.document.execCommand&&r.document.execCommand("Stop")}catch(u){n.log("Error occurred when stopping foreverFrame transport. Message = "+u.message+".")}n.frame.parentNode===t.document.body&&t.document.body.removeChild(n.frame);delete i.foreverFrame.connections[n.frameId];n.frame=null;n.frameId=null;delete n.frame;delete n.frameId;delete n.onSuccess;delete n.frameMessageCount;n.log("Stopping forever frame.")}},abort:function(n,t){i.ajaxAbort(n,t)},getConnection:function(n){return i.foreverFrame.connections[n]},started:function(t){o(t,r.connectionState.reconnecting,r.connectionState.connected)===!0&&n(t).triggerHandler(e.onReconnect)}}}(window.jQuery,window),function(n,t){var r=n.signalR,u=n.signalR.events,e=n.signalR.changeState,f=n.signalR.isDisconnecting,i=r.transports._logic;r.transports.longPolling={name:"longPolling",supportsKeepAlive:function(){return!1},reconnectDelay:3e3,start:function(o,s,h){var a=this,v=function(){v=n.noop;o.log("LongPolling connected.");s?s():o.log("WARNING! The client received an init message after reconnecting.")},y=function(n){return h(n)?(o.log("LongPolling failed to connect."),!0):!1},c=o._,l=0,p=function(i){t.clearTimeout(c.reconnectTimeoutId);c.reconnectTimeoutId=null;e(i,r.connectionState.reconnecting,r.connectionState.connected)===!0&&(i.log("Raising the reconnect event"),n(i).triggerHandler(u.onReconnect))},w=36e5;o.pollXhr&&(o.log("Polling xhr requests already exists, aborting."),o.stop());o.messageId=null;c.reconnectTimeoutId=null;c.pollTimeoutId=t.setTimeout(function(){(function e(s,h){var g=s.messageId,nt=g===null,k=!nt,tt=!h,d=i.getUrl(s,a.name,k,tt,!0),b={};(s.messageId&&(b.messageId=s.messageId),s.groupsToken&&(b.groupsToken=s.groupsToken),f(s)!==!0)&&(o.log("Opening long polling request to '"+d+"'."),s.pollXhr=i.ajax(o,{xhrFields:{onprogress:function(){i.markLastMessage(o)}},url:d,type:"POST",contentType:r._.defaultContentType,data:b,timeout:o._.pollTimeout,success:function(r){var h,w=0,u,a;o.log("Long poll complete.");l=0;try{h=o._parseResponse(r)}catch(b){i.handleParseFailure(s,r,b,y,s.pollXhr);return}(c.reconnectTimeoutId!==null&&p(s),h&&(u=i.maximizePersistentResponse(h)),i.processMessages(s,h,v),u&&n.type(u.LongPollDelay)==="number"&&(w=u.LongPollDelay),f(s)!==!0)&&(a=u&&u.ShouldReconnect,!a||i.ensureReconnectingState(s))&&(w>0?c.pollTimeoutId=t.setTimeout(function(){e(s,a)},w):e(s,a))},error:function(f,h){var v=r._.transportError(r.resources.longPollFailed,o.transport,f,s.pollXhr);if(t.clearTimeout(c.reconnectTimeoutId),c.reconnectTimeoutId=null,h==="abort"){o.log("Aborted xhr request.");return}if(!y(v)){if(l++,o.state!==r.connectionState.reconnecting&&(o.log("An error occurred using longPolling. Status = "+h+". Response = "+f.responseText+"."),n(s).triggerHandler(u.onError,[v])),(o.state===r.connectionState.connected||o.state===r.connectionState.reconnecting)&&!i.verifyLastActive(o))return;if(!i.ensureReconnectingState(s))return;c.pollTimeoutId=t.setTimeout(function(){e(s,!0)},a.reconnectDelay)}}}),k&&h===!0&&(c.reconnectTimeoutId=t.setTimeout(function(){p(s)},Math.min(1e3*(Math.pow(2,l)-1),w))))})(o)},250)},lostConnection:function(n){n.pollXhr&&n.pollXhr.abort("lostConnection")},send:function(n,t){i.ajaxSend(n,t)},stop:function(n){t.clearTimeout(n._.pollTimeoutId);t.clearTimeout(n._.reconnectTimeoutId);delete n._.pollTimeoutId;delete n._.reconnectTimeoutId;n.pollXhr&&(n.pollXhr.abort(),n.pollXhr=null,delete n.pollXhr)},abort:function(n,t){i.ajaxAbort(n,t)}}}(window.jQuery,window),function(n){function r(n){return n+e}function s(n,t,i){for(var f=n.length,u=[],r=0;rthis.depCount&&!this.defined){if(K(k)){if(this.events.error&&this.map.isDefine||g.onError!== +ha)try{h=l.execCb(c,k,b,h)}catch(d){a=d}else h=l.execCb(c,k,b,h);this.map.isDefine&&void 0===h&&((b=this.module)?h=b.exports:this.usingExports&&(h=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",A(this.error=a)}else h=k;this.exports=h;if(this.map.isDefine&&!this.ignore&&(v[c]=h,g.onResourceLoad)){var f=[];y(this.depMaps,function(a){f.push(a.normalizedMap||a)});g.onResourceLoad(l,this.map,f)}C(c); +this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0)}}},callPlugin:function(){var a=this.map,b=a.id,d=q(a.prefix);this.depMaps.push(d);w(d,"defined",z(this,function(h){var k,f,d=e(fa,this.map.id),M=this.map.name,r=this.map.parentMap?this.map.parentMap.name:null,m=l.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(h.normalize&&(M=h.normalize(M,function(a){return c(a,r,!0)})|| +""),f=q(a.prefix+"!"+M,this.map.parentMap),w(f,"defined",z(this,function(a){this.map.normalizedMap=f;this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),h=e(t,f.id)){this.depMaps.push(f);if(this.events.error)h.on("error",z(this,function(a){this.emit("error",a)}));h.enable()}}else d?(this.map.url=l.nameToUrl(d),this.load()):(k=z(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),k.error=z(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];D(t,function(a){0=== +a.map.id.indexOf(b+"_unnormalized")&&C(a.map.id)});A(a)}),k.fromText=z(this,function(h,c){var d=a.name,f=q(d),M=S;c&&(h=c);M&&(S=!1);u(f);x(p.config,b)&&(p.config[d]=p.config[b]);try{g.exec(h)}catch(e){return A(F("fromtexteval","fromText eval for "+b+" failed: "+e,e,[b]))}M&&(S=!0);this.depMaps.push(f);l.completeLoad(d);m([d],k)}),h.load(a.name,m,k,p))}));l.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){Z[this.map.id]=this;this.enabling=this.enabled=!0;y(this.depMaps,z(this,function(a, +b){var c,h;if("string"===typeof a){a=q(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=e(R,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;w(a,"defined",z(this,function(a){this.undefed||(this.defineDep(b,a),this.check())}));this.errback?w(a,"error",z(this,this.errback)):this.events.error&&w(a,"error",z(this,function(a){this.emit("error",a)}))}c=a.id;h=t[c];x(R,c)||!h||h.enabled||l.enable(a,this)}));D(this.pluginMaps,z(this,function(a){var b=e(t,a.id); +b&&!b.enabled&&l.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){y(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};l={config:p,contextName:b,registry:t,defined:v,urlFetched:W,defQueue:G,defQueueMap:{},Module:da,makeModuleMap:q,nextTick:g.nextTick,onError:A,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");if("string"===typeof a.urlArgs){var b= +a.urlArgs;a.urlArgs=function(a,c){return(-1===c.indexOf("?")?"?":"&")+b}}var c=p.shim,h={paths:!0,bundles:!0,config:!0,map:!0};D(a,function(a,b){h[b]?(p[b]||(p[b]={}),Y(p[b],a,!0,!0)):p[b]=a});a.bundles&&D(a.bundles,function(a,b){y(a,function(a){a!==b&&(fa[a]=b)})});a.shim&&(D(a.shim,function(a,b){L(a)&&(a={deps:a});!a.exports&&!a.init||a.exportsFn||(a.exportsFn=l.makeShimExports(a));c[b]=a}),p.shim=c);a.packages&&y(a.packages,function(a){var b;a="string"===typeof a?{name:a}:a;b=a.name;a.location&& +(p.paths[b]=a.location);p.pkgs[b]=a.name+"/"+(a.main||"main").replace(na,"").replace(U,"")});D(t,function(a,b){a.inited||a.map.unnormalized||(a.map=q(b,null,!0))});(a.deps||a.callback)&&l.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(ga,arguments));return b||a.exports&&ia(a.exports)}},makeRequire:function(a,n){function m(c,d,f){var e,r;n.enableBuildCallback&&d&&K(d)&&(d.__requireJsBuild=!0);if("string"===typeof c){if(K(d))return A(F("requireargs", +"Invalid require call"),f);if(a&&x(R,c))return R[c](t[a.id]);if(g.get)return g.get(l,c,a,m);e=q(c,a,!1,!0);e=e.id;return x(v,e)?v[e]:A(F("notloaded",'Module name "'+e+'" has not been loaded yet for context: '+b+(a?"":". Use require([])")))}P();l.nextTick(function(){P();r=u(q(null,a));r.skipMap=n.skipMap;r.init(c,d,f,{enabled:!0});H()});return m}n=n||{};Y(m,{isBrowser:E,toUrl:function(b){var d,f=b.lastIndexOf("."),g=b.split("/")[0];-1!==f&&("."!==g&&".."!==g||1e.attachEvent.toString().indexOf("[native code")||ca?(e.addEventListener("load",b.onScriptLoad,!1),e.addEventListener("error",b.onScriptError,!1)):(S=!0,e.attachEvent("onreadystatechange",b.onScriptLoad));e.src=d;if(m.onNodeCreated)m.onNodeCreated(e,m,c,d);P=e;H?C.insertBefore(e,H):C.appendChild(e);P=null;return e}if(ja)try{setTimeout(function(){}, +0),importScripts(d),b.completeLoad(c)}catch(q){b.onError(F("importscripts","importScripts failed for "+c+" at "+d,q,[c]))}};E&&!w.skipDataMain&&X(document.getElementsByTagName("script"),function(b){C||(C=b.parentNode);if(O=b.getAttribute("data-main"))return u=O,w.baseUrl||-1!==u.indexOf("!")||(I=u.split("/"),u=I.pop(),T=I.length?I.join("/")+"/":"./",w.baseUrl=T),u=u.replace(U,""),g.jsExtRegExp.test(u)&&(u=O),w.deps=w.deps?w.deps.concat(u):[u],!0});define=function(b,c,d){var e,g;"string"!==typeof b&& +(d=c,c=b,b=null);L(c)||(d=c,c=null);!c&&K(d)&&(c=[],d.length&&(d.toString().replace(qa,ka).replace(ra,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));S&&(e=P||pa())&&(b||(b=e.getAttribute("data-requiremodule")),g=J[e.getAttribute("data-requirecontext")]);g?(g.defQueue.push([b,c,d]),g.defQueueMap[b]=!0):V.push([b,c,d])};define.amd={jQuery:!0};g.exec=function(b){return eval(b)};g(w)}})(this); diff --git a/docs/scripts/text.js b/docs/scripts/text.js new file mode 100644 index 0000000..4c311ed --- /dev/null +++ b/docs/scripts/text.js @@ -0,0 +1,391 @@ +/** + * @license RequireJS text 2.0.14 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved. + * Available via the MIT or new BSD license. + * see: http://github.com/requirejs/text for details + */ +/*jslint regexp: true */ +/*global require, XMLHttpRequest, ActiveXObject, + define, window, process, Packages, + java, location, Components, FileUtils */ + +define(['module'], function (module) { + 'use strict'; + + var text, fs, Cc, Ci, xpcIsWindows, + progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'], + xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im, + bodyRegExp = /]*>\s*([\s\S]+)\s*<\/body>/im, + hasLocation = typeof location !== 'undefined' && location.href, + defaultProtocol = hasLocation && location.protocol && location.protocol.replace(/\:/, ''), + defaultHostName = hasLocation && location.hostname, + defaultPort = hasLocation && (location.port || undefined), + buildMap = {}, + masterConfig = (module.config && module.config()) || {}; + + text = { + version: '2.0.14', + + strip: function (content) { + //Strips declarations so that external SVG and XML + //documents can be added to a document without worry. Also, if the string + //is an HTML document, only the part inside the body tag is returned. + if (content) { + content = content.replace(xmlRegExp, ""); + var matches = content.match(bodyRegExp); + if (matches) { + content = matches[1]; + } + } else { + content = ""; + } + return content; + }, + + jsEscape: function (content) { + return content.replace(/(['\\])/g, '\\$1') + .replace(/[\f]/g, "\\f") + .replace(/[\b]/g, "\\b") + .replace(/[\n]/g, "\\n") + .replace(/[\t]/g, "\\t") + .replace(/[\r]/g, "\\r") + .replace(/[\u2028]/g, "\\u2028") + .replace(/[\u2029]/g, "\\u2029"); + }, + + createXhr: masterConfig.createXhr || function () { + //Would love to dump the ActiveX crap in here. Need IE 6 to die first. + var xhr, i, progId; + if (typeof XMLHttpRequest !== "undefined") { + return new XMLHttpRequest(); + } else if (typeof ActiveXObject !== "undefined") { + for (i = 0; i < 3; i += 1) { + progId = progIds[i]; + try { + xhr = new ActiveXObject(progId); + } catch (e) {} + + if (xhr) { + progIds = [progId]; // so faster next time + break; + } + } + } + + return xhr; + }, + + /** + * Parses a resource name into its component parts. Resource names + * look like: module/name.ext!strip, where the !strip part is + * optional. + * @param {String} name the resource name + * @returns {Object} with properties "moduleName", "ext" and "strip" + * where strip is a boolean. + */ + parseName: function (name) { + var modName, ext, temp, + strip = false, + index = name.lastIndexOf("."), + isRelative = name.indexOf('./') === 0 || + name.indexOf('../') === 0; + + if (index !== -1 && (!isRelative || index > 1)) { + modName = name.substring(0, index); + ext = name.substring(index + 1); + } else { + modName = name; + } + + temp = ext || modName; + index = temp.indexOf("!"); + if (index !== -1) { + //Pull off the strip arg. + strip = temp.substring(index + 1) === "strip"; + temp = temp.substring(0, index); + if (ext) { + ext = temp; + } else { + modName = temp; + } + } + + return { + moduleName: modName, + ext: ext, + strip: strip + }; + }, + + xdRegExp: /^((\w+)\:)?\/\/([^\/\\]+)/, + + /** + * Is an URL on another domain. Only works for browser use, returns + * false in non-browser environments. Only used to know if an + * optimized .js version of a text resource should be loaded + * instead. + * @param {String} url + * @returns Boolean + */ + useXhr: function (url, protocol, hostname, port) { + var uProtocol, uHostName, uPort, + match = text.xdRegExp.exec(url); + if (!match) { + return true; + } + uProtocol = match[2]; + uHostName = match[3]; + + uHostName = uHostName.split(':'); + uPort = uHostName[1]; + uHostName = uHostName[0]; + + return (!uProtocol || uProtocol === protocol) && + (!uHostName || uHostName.toLowerCase() === hostname.toLowerCase()) && + ((!uPort && !uHostName) || uPort === port); + }, + + finishLoad: function (name, strip, content, onLoad) { + content = strip ? text.strip(content) : content; + if (masterConfig.isBuild) { + buildMap[name] = content; + } + onLoad(content); + }, + + load: function (name, req, onLoad, config) { + //Name has format: some.module.filext!strip + //The strip part is optional. + //if strip is present, then that means only get the string contents + //inside a body tag in an HTML string. For XML/SVG content it means + //removing the declarations so the content can be inserted + //into the current doc without problems. + + // Do not bother with the work if a build and text will + // not be inlined. + if (config && config.isBuild && !config.inlineText) { + onLoad(); + return; + } + + masterConfig.isBuild = config && config.isBuild; + + var parsed = text.parseName(name), + nonStripName = parsed.moduleName + + (parsed.ext ? '.' + parsed.ext : ''), + url = req.toUrl(nonStripName), + useXhr = (masterConfig.useXhr) || + text.useXhr; + + // Do not load if it is an empty: url + if (url.indexOf('empty:') === 0) { + onLoad(); + return; + } + + //Load the text. Use XHR if possible and in a browser. + if (!hasLocation || useXhr(url, defaultProtocol, defaultHostName, defaultPort)) { + text.get(url, function (content) { + text.finishLoad(name, parsed.strip, content, onLoad); + }, function (err) { + if (onLoad.error) { + onLoad.error(err); + } + }); + } else { + //Need to fetch the resource across domains. Assume + //the resource has been optimized into a JS module. Fetch + //by the module name + extension, but do not include the + //!strip part to avoid file system issues. + req([nonStripName], function (content) { + text.finishLoad(parsed.moduleName + '.' + parsed.ext, + parsed.strip, content, onLoad); + }); + } + }, + + write: function (pluginName, moduleName, write, config) { + if (buildMap.hasOwnProperty(moduleName)) { + var content = text.jsEscape(buildMap[moduleName]); + write.asModule(pluginName + "!" + moduleName, + "define(function () { return '" + + content + + "';});\n"); + } + }, + + writeFile: function (pluginName, moduleName, req, write, config) { + var parsed = text.parseName(moduleName), + extPart = parsed.ext ? '.' + parsed.ext : '', + nonStripName = parsed.moduleName + extPart, + //Use a '.js' file name so that it indicates it is a + //script that can be loaded across domains. + fileName = req.toUrl(parsed.moduleName + extPart) + '.js'; + + //Leverage own load() method to load plugin value, but only + //write out values that do not have the strip argument, + //to avoid any potential issues with ! in file names. + text.load(nonStripName, req, function (value) { + //Use own write() method to construct full module value. + //But need to create shell that translates writeFile's + //write() to the right interface. + var textWrite = function (contents) { + return write(fileName, contents); + }; + textWrite.asModule = function (moduleName, contents) { + return write.asModule(moduleName, fileName, contents); + }; + + text.write(pluginName, nonStripName, textWrite, config); + }, config); + } + }; + + if (masterConfig.env === 'node' || (!masterConfig.env && + typeof process !== "undefined" && + process.versions && + !!process.versions.node && + !process.versions['node-webkit'] && + !process.versions['atom-shell'])) { + //Using special require.nodeRequire, something added by r.js. + fs = require.nodeRequire('fs'); + + text.get = function (url, callback, errback) { + try { + var file = fs.readFileSync(url, 'utf8'); + //Remove BOM (Byte Mark Order) from utf8 files if it is there. + if (file[0] === '\uFEFF') { + file = file.substring(1); + } + callback(file); + } catch (e) { + if (errback) { + errback(e); + } + } + }; + } else if (masterConfig.env === 'xhr' || (!masterConfig.env && + text.createXhr())) { + text.get = function (url, callback, errback, headers) { + var xhr = text.createXhr(), header; + xhr.open('GET', url, true); + + //Allow plugins direct access to xhr headers + if (headers) { + for (header in headers) { + if (headers.hasOwnProperty(header)) { + xhr.setRequestHeader(header.toLowerCase(), headers[header]); + } + } + } + + //Allow overrides specified in config + if (masterConfig.onXhr) { + masterConfig.onXhr(xhr, url); + } + + xhr.onreadystatechange = function (evt) { + var status, err; + //Do not explicitly handle errors, those should be + //visible via console output in the browser. + if (xhr.readyState === 4) { + status = xhr.status || 0; + if (status > 399 && status < 600) { + //An http 4xx or 5xx error. Signal an error. + err = new Error(url + ' HTTP status: ' + status); + err.xhr = xhr; + if (errback) { + errback(err); + } + } else { + callback(xhr.responseText); + } + + if (masterConfig.onXhrComplete) { + masterConfig.onXhrComplete(xhr, url); + } + } + }; + xhr.send(null); + }; + } else if (masterConfig.env === 'rhino' || (!masterConfig.env && + typeof Packages !== 'undefined' && typeof java !== 'undefined')) { + //Why Java, why is this so awkward? + text.get = function (url, callback) { + var stringBuffer, line, + encoding = "utf-8", + file = new java.io.File(url), + lineSeparator = java.lang.System.getProperty("line.separator"), + input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)), + content = ''; + try { + stringBuffer = new java.lang.StringBuffer(); + line = input.readLine(); + + // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324 + // http://www.unicode.org/faq/utf_bom.html + + // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK: + // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058 + if (line && line.length() && line.charAt(0) === 0xfeff) { + // Eat the BOM, since we've already found the encoding on this file, + // and we plan to concatenating this buffer with others; the BOM should + // only appear at the top of a file. + line = line.substring(1); + } + + if (line !== null) { + stringBuffer.append(line); + } + + while ((line = input.readLine()) !== null) { + stringBuffer.append(lineSeparator); + stringBuffer.append(line); + } + //Make sure we return a JavaScript string and not a Java string. + content = String(stringBuffer.toString()); //String + } finally { + input.close(); + } + callback(content); + }; + } else if (masterConfig.env === 'xpconnect' || (!masterConfig.env && + typeof Components !== 'undefined' && Components.classes && + Components.interfaces)) { + //Avert your gaze! + Cc = Components.classes; + Ci = Components.interfaces; + Components.utils['import']('resource://gre/modules/FileUtils.jsm'); + xpcIsWindows = ('@mozilla.org/windows-registry-key;1' in Cc); + + text.get = function (url, callback) { + var inStream, convertStream, fileObj, + readData = {}; + + if (xpcIsWindows) { + url = url.replace(/\//g, '\\'); + } + + fileObj = new FileUtils.File(url); + + //XPCOM, you so crazy + try { + inStream = Cc['@mozilla.org/network/file-input-stream;1'] + .createInstance(Ci.nsIFileInputStream); + inStream.init(fileObj, 1, 0, false); + + convertStream = Cc['@mozilla.org/intl/converter-input-stream;1'] + .createInstance(Ci.nsIConverterInputStream); + convertStream.init(inStream, "utf-8", inStream.available(), + Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER); + + convertStream.readString(inStream.available(), readData); + convertStream.close(); + inStream.close(); + callback(readData.value); + } catch (e) { + throw new Error((fileObj && fileObj.path || '') + ': ' + e); + } + }; + } + return text; +}); diff --git a/docs/scripts/vendor-bundle.js b/docs/scripts/vendor-bundle.js new file mode 100644 index 0000000..6dc292a --- /dev/null +++ b/docs/scripts/vendor-bundle.js @@ -0,0 +1,25806 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2015 Petka Antonov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ +/** + * bluebird build version 3.4.6 + * Features enabled: core + * Features disabled: race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each +*/ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + continue; + } + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +}; + +Async.prototype._drainQueues = function () { + this._drainQueue(this._normalQueue); + this._reset(); + this._haveDrainedQueues = true; + this._drainQueue(this._lateQueue); +}; + +Async.prototype._queueTick = function () { + if (!this._isTickUsed) { + this._isTickUsed = true; + this._schedule(this.drainQueues); + } +}; + +Async.prototype._reset = function () { + this._isTickUsed = false; +}; + +module.exports = Async; +module.exports.firstLineError = firstLineError; + +},{"./queue":17,"./schedule":18,"./util":21}],2:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { +var calledBind = false; +var rejectThis = function(_, e) { + this._reject(e); +}; + +var targetRejected = function(e, context) { + context.promiseRejectionQueued = true; + context.bindingPromise._then(rejectThis, rejectThis, null, this, e); +}; + +var bindingResolved = function(thisArg, context) { + if (((this._bitField & 50397184) === 0)) { + this._resolveCallback(context.target); + } +}; + +var bindingRejected = function(e, context) { + if (!context.promiseRejectionQueued) this._reject(e); +}; + +Promise.prototype.bind = function (thisArg) { + if (!calledBind) { + calledBind = true; + Promise.prototype._propagateFrom = debug.propagateFromFunction(); + Promise.prototype._boundValue = debug.boundValueFunction(); + } + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + ret._propagateFrom(this, 1); + var target = this._target(); + ret._setBoundTo(maybePromise); + if (maybePromise instanceof Promise) { + var context = { + promiseRejectionQueued: false, + promise: ret, + target: target, + bindingPromise: maybePromise + }; + target._then(INTERNAL, targetRejected, undefined, ret, context); + maybePromise._then( + bindingResolved, bindingRejected, undefined, ret, context); + ret._setOnCancel(maybePromise); + } else { + ret._resolveCallback(target); + } + return ret; +}; + +Promise.prototype._setBoundTo = function (obj) { + if (obj !== undefined) { + this._bitField = this._bitField | 2097152; + this._boundTo = obj; + } else { + this._bitField = this._bitField & (~2097152); + } +}; + +Promise.prototype._isBound = function () { + return (this._bitField & 2097152) === 2097152; +}; + +Promise.bind = function (thisArg, value) { + return Promise.resolve(value).bind(thisArg); +}; +}; + +},{}],3:[function(_dereq_,module,exports){ +"use strict"; +var old; +if (typeof Promise !== "undefined") old = Promise; +function noConflict() { + try { if (Promise === bluebird) Promise = old; } + catch (e) {} + return bluebird; +} +var bluebird = _dereq_("./promise")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; + +},{"./promise":15}],4:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, PromiseArray, apiRejection, debug) { +var util = _dereq_("./util"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var async = Promise._async; + +Promise.prototype["break"] = Promise.prototype.cancel = function() { + if (!debug.cancellation()) return this._warn("cancellation is disabled"); + + var promise = this; + var child = promise; + while (promise._isCancellable()) { + if (!promise._cancelBy(child)) { + if (child._isFollowing()) { + child._followee().cancel(); + } else { + child._cancelBranched(); + } + break; + } + + var parent = promise._cancellationParent; + if (parent == null || !parent._isCancellable()) { + if (promise._isFollowing()) { + promise._followee().cancel(); + } else { + promise._cancelBranched(); + } + break; + } else { + if (promise._isFollowing()) promise._followee().cancel(); + promise._setWillBeCancelled(); + child = promise; + promise = parent; + } + } +}; + +Promise.prototype._branchHasCancelled = function() { + this._branchesRemainingToCancel--; +}; + +Promise.prototype._enoughBranchesHaveCancelled = function() { + return this._branchesRemainingToCancel === undefined || + this._branchesRemainingToCancel <= 0; +}; + +Promise.prototype._cancelBy = function(canceller) { + if (canceller === this) { + this._branchesRemainingToCancel = 0; + this._invokeOnCancel(); + return true; + } else { + this._branchHasCancelled(); + if (this._enoughBranchesHaveCancelled()) { + this._invokeOnCancel(); + return true; + } + } + return false; +}; + +Promise.prototype._cancelBranched = function() { + if (this._enoughBranchesHaveCancelled()) { + this._cancel(); + } +}; + +Promise.prototype._cancel = function() { + if (!this._isCancellable()) return; + this._setCancelled(); + async.invoke(this._cancelPromises, this, undefined); +}; + +Promise.prototype._cancelPromises = function() { + if (this._length() > 0) this._settlePromises(); +}; + +Promise.prototype._unsetOnCancel = function() { + this._onCancelField = undefined; +}; + +Promise.prototype._isCancellable = function() { + return this.isPending() && !this._isCancelled(); +}; + +Promise.prototype.isCancellable = function() { + return this.isPending() && !this.isCancelled(); +}; + +Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { + if (util.isArray(onCancelCallback)) { + for (var i = 0; i < onCancelCallback.length; ++i) { + this._doInvokeOnCancel(onCancelCallback[i], internalOnly); + } + } else if (onCancelCallback !== undefined) { + if (typeof onCancelCallback === "function") { + if (!internalOnly) { + var e = tryCatch(onCancelCallback).call(this._boundValue()); + if (e === errorObj) { + this._attachExtraTrace(e.e); + async.throwLater(e.e); + } + } + } else { + onCancelCallback._resultCancelled(this); + } + } +}; + +Promise.prototype._invokeOnCancel = function() { + var onCancelCallback = this._onCancel(); + this._unsetOnCancel(); + async.invoke(this._doInvokeOnCancel, this, onCancelCallback); +}; + +Promise.prototype._invokeInternalOnCancel = function() { + if (this._isCancellable()) { + this._doInvokeOnCancel(this._onCancel(), true); + this._unsetOnCancel(); + } +}; + +Promise.prototype._resultCancelled = function() { + this.cancel(); +}; + +}; + +},{"./util":21}],5:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = _dereq_("./util"); +var getKeys = _dereq_("./es5").keys; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function catchFilter(instances, cb, promise) { + return function(e) { + var boundTo = promise._boundValue(); + predicateLoop: for (var i = 0; i < instances.length; ++i) { + var item = instances[i]; + + if (item === Error || + (item != null && item.prototype instanceof Error)) { + if (e instanceof item) { + return tryCatch(cb).call(boundTo, e); + } + } else if (typeof item === "function") { + var matchesPredicate = tryCatch(item).call(boundTo, e); + if (matchesPredicate === errorObj) { + return matchesPredicate; + } else if (matchesPredicate) { + return tryCatch(cb).call(boundTo, e); + } + } else if (util.isObject(e)) { + var keys = getKeys(item); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + if (item[key] != e[key]) { + continue predicateLoop; + } + } + return tryCatch(cb).call(boundTo, e); + } + } + return NEXT_FILTER; + }; +} + +return catchFilter; +}; + +},{"./es5":10,"./util":21}],6:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var longStackTraces = false; +var contextStack = []; + +Promise.prototype._promiseCreated = function() {}; +Promise.prototype._pushContext = function() {}; +Promise.prototype._popContext = function() {return null;}; +Promise._peekContext = Promise.prototype._peekContext = function() {}; + +function Context() { + this._trace = new Context.CapturedTrace(peekContext()); +} +Context.prototype._pushContext = function () { + if (this._trace !== undefined) { + this._trace._promiseCreated = null; + contextStack.push(this._trace); + } +}; + +Context.prototype._popContext = function () { + if (this._trace !== undefined) { + var trace = contextStack.pop(); + var ret = trace._promiseCreated; + trace._promiseCreated = null; + return ret; + } + return null; +}; + +function createContext() { + if (longStackTraces) return new Context(); +} + +function peekContext() { + var lastIndex = contextStack.length - 1; + if (lastIndex >= 0) { + return contextStack[lastIndex]; + } + return undefined; +} +Context.CapturedTrace = null; +Context.create = createContext; +Context.deactivateLongStackTraces = function() {}; +Context.activateLongStackTraces = function() { + var Promise_pushContext = Promise.prototype._pushContext; + var Promise_popContext = Promise.prototype._popContext; + var Promise_PeekContext = Promise._peekContext; + var Promise_peekContext = Promise.prototype._peekContext; + var Promise_promiseCreated = Promise.prototype._promiseCreated; + Context.deactivateLongStackTraces = function() { + Promise.prototype._pushContext = Promise_pushContext; + Promise.prototype._popContext = Promise_popContext; + Promise._peekContext = Promise_PeekContext; + Promise.prototype._peekContext = Promise_peekContext; + Promise.prototype._promiseCreated = Promise_promiseCreated; + longStackTraces = false; + }; + longStackTraces = true; + Promise.prototype._pushContext = Context.prototype._pushContext; + Promise.prototype._popContext = Context.prototype._popContext; + Promise._peekContext = Promise.prototype._peekContext = peekContext; + Promise.prototype._promiseCreated = function() { + var ctx = this._peekContext(); + if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; + }; +}; +return Context; +}; + +},{}],7:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, Context) { +var getDomain = Promise._getDomain; +var async = Promise._async; +var Warning = _dereq_("./errors").Warning; +var util = _dereq_("./util"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var bluebirdFramePattern = + /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; +var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; +var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; +var stackFramePattern = null; +var formatStack = null; +var indentStackFrames = false; +var printWarning; +var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && + (true || + util.env("BLUEBIRD_DEBUG") || + util.env("NODE_ENV") === "development")); + +var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && + (debugging || util.env("BLUEBIRD_WARNINGS"))); + +var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && + (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); + +var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && + (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); + +Promise.prototype.suppressUnhandledRejections = function() { + var target = this._target(); + target._bitField = ((target._bitField & (~1048576)) | + 524288); +}; + +Promise.prototype._ensurePossibleRejectionHandled = function () { + if ((this._bitField & 524288) !== 0) return; + this._setRejectionIsUnhandled(); + async.invokeLater(this._notifyUnhandledRejection, this, undefined); +}; + +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; + +Promise.prototype._setReturnedNonUndefined = function() { + this._bitField = this._bitField | 268435456; +}; + +Promise.prototype._returnedNonUndefined = function() { + return (this._bitField & 268435456) !== 0; +}; + +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._settledValue(); + this._setUnhandledRejectionIsNotified(); + fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); + } +}; + +Promise.prototype._setUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField | 262144; +}; + +Promise.prototype._unsetUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField & (~262144); +}; + +Promise.prototype._isUnhandledRejectionNotified = function () { + return (this._bitField & 262144) > 0; +}; + +Promise.prototype._setRejectionIsUnhandled = function () { + this._bitField = this._bitField | 1048576; +}; + +Promise.prototype._unsetRejectionIsUnhandled = function () { + this._bitField = this._bitField & (~1048576); + if (this._isUnhandledRejectionNotified()) { + this._unsetUnhandledRejectionIsNotified(); + this._notifyUnhandledRejectionIsHandled(); + } +}; + +Promise.prototype._isRejectionUnhandled = function () { + return (this._bitField & 1048576) > 0; +}; + +Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { + return warn(message, shouldUseOwnTrace, promise || this); +}; + +Promise.onPossiblyUnhandledRejection = function (fn) { + var domain = getDomain(); + possiblyUnhandledRejection = + typeof fn === "function" ? (domain === null ? + fn : util.domainBind(domain, fn)) + : undefined; +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + var domain = getDomain(); + unhandledRejectionHandled = + typeof fn === "function" ? (domain === null ? + fn : util.domainBind(domain, fn)) + : undefined; +}; + +var disableLongStackTraces = function() {}; +Promise.longStackTraces = function () { + if (async.haveItemsQueued() && !config.longStackTraces) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + if (!config.longStackTraces && longStackTracesIsSupported()) { + var Promise_captureStackTrace = Promise.prototype._captureStackTrace; + var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; + config.longStackTraces = true; + disableLongStackTraces = function() { + if (async.haveItemsQueued() && !config.longStackTraces) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + Promise.prototype._captureStackTrace = Promise_captureStackTrace; + Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; + Context.deactivateLongStackTraces(); + async.enableTrampoline(); + config.longStackTraces = false; + }; + Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; + Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; + Context.activateLongStackTraces(); + async.disableTrampolineIfNecessary(); + } +}; + +Promise.hasLongStackTraces = function () { + return config.longStackTraces && longStackTracesIsSupported(); +}; + +var fireDomEvent = (function() { + try { + if (typeof CustomEvent === "function") { + var event = new CustomEvent("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + var domEvent = new CustomEvent(name.toLowerCase(), { + detail: event, + cancelable: true + }); + return !util.global.dispatchEvent(domEvent); + }; + } else if (typeof Event === "function") { + var event = new Event("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + var domEvent = new Event(name.toLowerCase(), { + cancelable: true + }); + domEvent.detail = event; + return !util.global.dispatchEvent(domEvent); + }; + } else { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + util.global.dispatchEvent(event); + return function(name, event) { + var domEvent = document.createEvent("CustomEvent"); + domEvent.initCustomEvent(name.toLowerCase(), false, true, + event); + return !util.global.dispatchEvent(domEvent); + }; + } + } catch (e) {} + return function() { + return false; + }; +})(); + +var fireGlobalEvent = (function() { + if (util.isNode) { + return function() { + return process.emit.apply(process, arguments); + }; + } else { + if (!util.global) { + return function() { + return false; + }; + } + return function(name) { + var methodName = "on" + name.toLowerCase(); + var method = util.global[methodName]; + if (!method) return false; + method.apply(util.global, [].slice.call(arguments, 1)); + return true; + }; + } +})(); + +function generatePromiseLifecycleEventObject(name, promise) { + return {promise: promise}; +} + +var eventToObjectGenerator = { + promiseCreated: generatePromiseLifecycleEventObject, + promiseFulfilled: generatePromiseLifecycleEventObject, + promiseRejected: generatePromiseLifecycleEventObject, + promiseResolved: generatePromiseLifecycleEventObject, + promiseCancelled: generatePromiseLifecycleEventObject, + promiseChained: function(name, promise, child) { + return {promise: promise, child: child}; + }, + warning: function(name, warning) { + return {warning: warning}; + }, + unhandledRejection: function (name, reason, promise) { + return {reason: reason, promise: promise}; + }, + rejectionHandled: generatePromiseLifecycleEventObject +}; + +var activeFireEvent = function (name) { + var globalEventFired = false; + try { + globalEventFired = fireGlobalEvent.apply(null, arguments); + } catch (e) { + async.throwLater(e); + globalEventFired = true; + } + + var domEventFired = false; + try { + domEventFired = fireDomEvent(name, + eventToObjectGenerator[name].apply(null, arguments)); + } catch (e) { + async.throwLater(e); + domEventFired = true; + } + + return domEventFired || globalEventFired; +}; + +Promise.config = function(opts) { + opts = Object(opts); + if ("longStackTraces" in opts) { + if (opts.longStackTraces) { + Promise.longStackTraces(); + } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { + disableLongStackTraces(); + } + } + if ("warnings" in opts) { + var warningsOption = opts.warnings; + config.warnings = !!warningsOption; + wForgottenReturn = config.warnings; + + if (util.isObject(warningsOption)) { + if ("wForgottenReturn" in warningsOption) { + wForgottenReturn = !!warningsOption.wForgottenReturn; + } + } + } + if ("cancellation" in opts && opts.cancellation && !config.cancellation) { + if (async.haveItemsQueued()) { + throw new Error( + "cannot enable cancellation after promises are in use"); + } + Promise.prototype._clearCancellationData = + cancellationClearCancellationData; + Promise.prototype._propagateFrom = cancellationPropagateFrom; + Promise.prototype._onCancel = cancellationOnCancel; + Promise.prototype._setOnCancel = cancellationSetOnCancel; + Promise.prototype._attachCancellationCallback = + cancellationAttachCancellationCallback; + Promise.prototype._execute = cancellationExecute; + propagateFromFunction = cancellationPropagateFrom; + config.cancellation = true; + } + if ("monitoring" in opts) { + if (opts.monitoring && !config.monitoring) { + config.monitoring = true; + Promise.prototype._fireEvent = activeFireEvent; + } else if (!opts.monitoring && config.monitoring) { + config.monitoring = false; + Promise.prototype._fireEvent = defaultFireEvent; + } + } +}; + +function defaultFireEvent() { return false; } + +Promise.prototype._fireEvent = defaultFireEvent; +Promise.prototype._execute = function(executor, resolve, reject) { + try { + executor(resolve, reject); + } catch (e) { + return e; + } +}; +Promise.prototype._onCancel = function () {}; +Promise.prototype._setOnCancel = function (handler) { ; }; +Promise.prototype._attachCancellationCallback = function(onCancel) { + ; +}; +Promise.prototype._captureStackTrace = function () {}; +Promise.prototype._attachExtraTrace = function () {}; +Promise.prototype._clearCancellationData = function() {}; +Promise.prototype._propagateFrom = function (parent, flags) { + ; + ; +}; + +function cancellationExecute(executor, resolve, reject) { + var promise = this; + try { + executor(resolve, reject, function(onCancel) { + if (typeof onCancel !== "function") { + throw new TypeError("onCancel must be a function, got: " + + util.toString(onCancel)); + } + promise._attachCancellationCallback(onCancel); + }); + } catch (e) { + return e; + } +} + +function cancellationAttachCancellationCallback(onCancel) { + if (!this._isCancellable()) return this; + + var previousOnCancel = this._onCancel(); + if (previousOnCancel !== undefined) { + if (util.isArray(previousOnCancel)) { + previousOnCancel.push(onCancel); + } else { + this._setOnCancel([previousOnCancel, onCancel]); + } + } else { + this._setOnCancel(onCancel); + } +} + +function cancellationOnCancel() { + return this._onCancelField; +} + +function cancellationSetOnCancel(onCancel) { + this._onCancelField = onCancel; +} + +function cancellationClearCancellationData() { + this._cancellationParent = undefined; + this._onCancelField = undefined; +} + +function cancellationPropagateFrom(parent, flags) { + if ((flags & 1) !== 0) { + this._cancellationParent = parent; + var branchesRemainingToCancel = parent._branchesRemainingToCancel; + if (branchesRemainingToCancel === undefined) { + branchesRemainingToCancel = 0; + } + parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; + } + if ((flags & 2) !== 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +} + +function bindingPropagateFrom(parent, flags) { + if ((flags & 2) !== 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +} +var propagateFromFunction = bindingPropagateFrom; + +function boundValueFunction() { + var ret = this._boundTo; + if (ret !== undefined) { + if (ret instanceof Promise) { + if (ret.isFulfilled()) { + return ret.value(); + } else { + return undefined; + } + } + } + return ret; +} + +function longStackTracesCaptureStackTrace() { + this._trace = new CapturedTrace(this._peekContext()); +} + +function longStackTracesAttachExtraTrace(error, ignoreSelf) { + if (canAttachTrace(error)) { + var trace = this._trace; + if (trace !== undefined) { + if (ignoreSelf) trace = trace._parent; + } + if (trace !== undefined) { + trace.attachExtraTrace(error); + } else if (!error.__stackCleaned__) { + var parsed = parseStackAndMessage(error); + util.notEnumerableProp(error, "stack", + parsed.message + "\n" + parsed.stack.join("\n")); + util.notEnumerableProp(error, "__stackCleaned__", true); + } + } +} + +function checkForgottenReturns(returnValue, promiseCreated, name, promise, + parent) { + if (returnValue === undefined && promiseCreated !== null && + wForgottenReturn) { + if (parent !== undefined && parent._returnedNonUndefined()) return; + if ((promise._bitField & 65535) === 0) return; + + if (name) name = name + " "; + var handlerLine = ""; + var creatorLine = ""; + if (promiseCreated._trace) { + var traceLines = promiseCreated._trace.stack.split("\n"); + var stack = cleanStack(traceLines); + for (var i = stack.length - 1; i >= 0; --i) { + var line = stack[i]; + if (!nodeFramePattern.test(line)) { + var lineMatches = line.match(parseLinePattern); + if (lineMatches) { + handlerLine = "at " + lineMatches[1] + + ":" + lineMatches[2] + ":" + lineMatches[3] + " "; + } + break; + } + } + + if (stack.length > 0) { + var firstUserLine = stack[0]; + for (var i = 0; i < traceLines.length; ++i) { + + if (traceLines[i] === firstUserLine) { + if (i > 0) { + creatorLine = "\n" + traceLines[i - 1]; + } + break; + } + } + + } + } + var msg = "a promise was created in a " + name + + "handler " + handlerLine + "but was not returned from it, " + + "see http://goo.gl/rRqMUw" + + creatorLine; + promise._warn(msg, true, promiseCreated); + } +} + +function deprecated(name, replacement) { + var message = name + + " is deprecated and will be removed in a future version."; + if (replacement) message += " Use " + replacement + " instead."; + return warn(message); +} + +function warn(message, shouldUseOwnTrace, promise) { + if (!config.warnings) return; + var warning = new Warning(message); + var ctx; + if (shouldUseOwnTrace) { + promise._attachExtraTrace(warning); + } else if (config.longStackTraces && (ctx = Promise._peekContext())) { + ctx.attachExtraTrace(warning); + } else { + var parsed = parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } + + if (!activeFireEvent("warning", warning)) { + formatAndLogError(warning, "", true); + } +} + +function reconstructStack(message, stacks) { + for (var i = 0; i < stacks.length - 1; ++i) { + stacks[i].push("From previous event:"); + stacks[i] = stacks[i].join("\n"); + } + if (i < stacks.length) { + stacks[i] = stacks[i].join("\n"); + } + return message + "\n" + stacks.join("\n"); +} + +function removeDuplicateOrEmptyJumps(stacks) { + for (var i = 0; i < stacks.length; ++i) { + if (stacks[i].length === 0 || + ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { + stacks.splice(i, 1); + i--; + } + } +} + +function removeCommonRoots(stacks) { + var current = stacks[0]; + for (var i = 1; i < stacks.length; ++i) { + var prev = stacks[i]; + var currentLastIndex = current.length - 1; + var currentLastLine = current[currentLastIndex]; + var commonRootMeetPoint = -1; + + for (var j = prev.length - 1; j >= 0; --j) { + if (prev[j] === currentLastLine) { + commonRootMeetPoint = j; + break; + } + } + + for (var j = commonRootMeetPoint; j >= 0; --j) { + var line = prev[j]; + if (current[currentLastIndex] === line) { + current.pop(); + currentLastIndex--; + } else { + break; + } + } + current = prev; + } +} + +function cleanStack(stack) { + var ret = []; + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + var isTraceLine = " (No stack trace)" === line || + stackFramePattern.test(line); + var isInternalFrame = isTraceLine && shouldIgnore(line); + if (isTraceLine && !isInternalFrame) { + if (indentStackFrames && line.charAt(0) !== " ") { + line = " " + line; + } + ret.push(line); + } + } + return ret; +} + +function stackFramesAsArray(error) { + var stack = error.stack.replace(/\s+$/g, "").split("\n"); + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + if (" (No stack trace)" === line || stackFramePattern.test(line)) { + break; + } + } + if (i > 0) { + stack = stack.slice(i); + } + return stack; +} + +function parseStackAndMessage(error) { + var stack = error.stack; + var message = error.toString(); + stack = typeof stack === "string" && stack.length > 0 + ? stackFramesAsArray(error) : [" (No stack trace)"]; + return { + message: message, + stack: cleanStack(stack) + }; +} + +function formatAndLogError(error, title, isSoft) { + if (typeof console !== "undefined") { + var message; + if (util.isObject(error)) { + var stack = error.stack; + message = title + formatStack(stack, error); + } else { + message = title + String(error); + } + if (typeof printWarning === "function") { + printWarning(message, isSoft); + } else if (typeof console.log === "function" || + typeof console.log === "object") { + console.log(message); + } + } +} + +function fireRejectionEvent(name, localHandler, reason, promise) { + var localEventFired = false; + try { + if (typeof localHandler === "function") { + localEventFired = true; + if (name === "rejectionHandled") { + localHandler(promise); + } else { + localHandler(reason, promise); + } + } + } catch (e) { + async.throwLater(e); + } + + if (name === "unhandledRejection") { + if (!activeFireEvent(name, reason, promise) && !localEventFired) { + formatAndLogError(reason, "Unhandled rejection "); + } + } else { + activeFireEvent(name, promise); + } +} + +function formatNonError(obj) { + var str; + if (typeof obj === "function") { + str = "[function " + + (obj.name || "anonymous") + + "]"; + } else { + str = obj && typeof obj.toString === "function" + ? obj.toString() : util.toString(obj); + var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; + if (ruselessToString.test(str)) { + try { + var newStr = JSON.stringify(obj); + str = newStr; + } + catch(e) { + + } + } + if (str.length === 0) { + str = "(empty array)"; + } + } + return ("(<" + snip(str) + ">, no stack trace)"); +} + +function snip(str) { + var maxChars = 41; + if (str.length < maxChars) { + return str; + } + return str.substr(0, maxChars - 3) + "..."; +} + +function longStackTracesIsSupported() { + return typeof captureStackTrace === "function"; +} + +var shouldIgnore = function() { return false; }; +var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; +function parseLineInfo(line) { + var matches = line.match(parseLineInfoRegex); + if (matches) { + return { + fileName: matches[1], + line: parseInt(matches[2], 10) + }; + } +} + +function setBounds(firstLineError, lastLineError) { + if (!longStackTracesIsSupported()) return; + var firstStackLines = firstLineError.stack.split("\n"); + var lastStackLines = lastLineError.stack.split("\n"); + var firstIndex = -1; + var lastIndex = -1; + var firstFileName; + var lastFileName; + for (var i = 0; i < firstStackLines.length; ++i) { + var result = parseLineInfo(firstStackLines[i]); + if (result) { + firstFileName = result.fileName; + firstIndex = result.line; + break; + } + } + for (var i = 0; i < lastStackLines.length; ++i) { + var result = parseLineInfo(lastStackLines[i]); + if (result) { + lastFileName = result.fileName; + lastIndex = result.line; + break; + } + } + if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || + firstFileName !== lastFileName || firstIndex >= lastIndex) { + return; + } + + shouldIgnore = function(line) { + if (bluebirdFramePattern.test(line)) return true; + var info = parseLineInfo(line); + if (info) { + if (info.fileName === firstFileName && + (firstIndex <= info.line && info.line <= lastIndex)) { + return true; + } + } + return false; + }; +} + +function CapturedTrace(parent) { + this._parent = parent; + this._promisesCreated = 0; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); +Context.CapturedTrace = CapturedTrace; + +CapturedTrace.prototype.uncycle = function() { + var length = this._length; + if (length < 2) return; + var nodes = []; + var stackToIndex = {}; + + for (var i = 0, node = this; node !== undefined; ++i) { + nodes.push(node); + node = node._parent; + } + length = this._length = i; + for (var i = length - 1; i >= 0; --i) { + var stack = nodes[i].stack; + if (stackToIndex[stack] === undefined) { + stackToIndex[stack] = i; + } + } + for (var i = 0; i < length; ++i) { + var currentStack = nodes[i].stack; + var index = stackToIndex[currentStack]; + if (index !== undefined && index !== i) { + if (index > 0) { + nodes[index - 1]._parent = undefined; + nodes[index - 1]._length = 1; + } + nodes[i]._parent = undefined; + nodes[i]._length = 1; + var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; + + if (index < length - 1) { + cycleEdgeNode._parent = nodes[index + 1]; + cycleEdgeNode._parent.uncycle(); + cycleEdgeNode._length = + cycleEdgeNode._parent._length + 1; + } else { + cycleEdgeNode._parent = undefined; + cycleEdgeNode._length = 1; + } + var currentChildLength = cycleEdgeNode._length + 1; + for (var j = i - 2; j >= 0; --j) { + nodes[j]._length = currentChildLength; + currentChildLength++; + } + return; + } + } +}; + +CapturedTrace.prototype.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = parseStackAndMessage(error); + var message = parsed.message; + var stacks = [parsed.stack]; + + var trace = this; + while (trace !== undefined) { + stacks.push(cleanStack(trace.stack.split("\n"))); + trace = trace._parent; + } + removeCommonRoots(stacks); + removeDuplicateOrEmptyJumps(stacks); + util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); + util.notEnumerableProp(error, "__stackCleaned__", true); +}; + +var captureStackTrace = (function stackDetection() { + var v8stackFramePattern = /^\s*at\s*/; + var v8stackFormatter = function(stack, error) { + if (typeof stack === "string") return stack; + + if (error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + if (typeof Error.stackTraceLimit === "number" && + typeof Error.captureStackTrace === "function") { + Error.stackTraceLimit += 6; + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + var captureStackTrace = Error.captureStackTrace; + + shouldIgnore = function(line) { + return bluebirdFramePattern.test(line); + }; + return function(receiver, ignoreUntil) { + Error.stackTraceLimit += 6; + captureStackTrace(receiver, ignoreUntil); + Error.stackTraceLimit -= 6; + }; + } + var err = new Error(); + + if (typeof err.stack === "string" && + err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { + stackFramePattern = /@/; + formatStack = v8stackFormatter; + indentStackFrames = true; + return function captureStackTrace(o) { + o.stack = new Error().stack; + }; + } + + var hasStackAfterThrow; + try { throw new Error(); } + catch(e) { + hasStackAfterThrow = ("stack" in e); + } + if (!("stack" in err) && hasStackAfterThrow && + typeof Error.stackTraceLimit === "number") { + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + return function captureStackTrace(o) { + Error.stackTraceLimit += 6; + try { throw new Error(); } + catch(e) { o.stack = e.stack; } + Error.stackTraceLimit -= 6; + }; + } + + formatStack = function(stack, error) { + if (typeof stack === "string") return stack; + + if ((typeof error === "object" || + typeof error === "function") && + error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + return null; + +})([]); + +if (typeof console !== "undefined" && typeof console.warn !== "undefined") { + printWarning = function (message) { + console.warn(message); + }; + if (util.isNode && process.stderr.isTTY) { + printWarning = function(message, isSoft) { + var color = isSoft ? "\u001b[33m" : "\u001b[31m"; + console.warn(color + message + "\u001b[0m\n"); + }; + } else if (!util.isNode && typeof (new Error().stack) === "string") { + printWarning = function(message, isSoft) { + console.warn("%c" + message, + isSoft ? "color: darkorange" : "color: red"); + }; + } +} + +var config = { + warnings: warnings, + longStackTraces: false, + cancellation: false, + monitoring: false +}; + +if (longStackTraces) Promise.longStackTraces(); + +return { + longStackTraces: function() { + return config.longStackTraces; + }, + warnings: function() { + return config.warnings; + }, + cancellation: function() { + return config.cancellation; + }, + monitoring: function() { + return config.monitoring; + }, + propagateFromFunction: function() { + return propagateFromFunction; + }, + boundValueFunction: function() { + return boundValueFunction; + }, + checkForgottenReturns: checkForgottenReturns, + setBounds: setBounds, + warn: warn, + deprecated: deprecated, + CapturedTrace: CapturedTrace, + fireDomEvent: fireDomEvent, + fireGlobalEvent: fireGlobalEvent +}; +}; + +},{"./errors":9,"./util":21}],8:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +function returner() { + return this.value; +} +function thrower() { + throw this.reason; +} + +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (value instanceof Promise) value.suppressUnhandledRejections(); + return this._then( + returner, undefined, undefined, {value: value}, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + return this._then( + thrower, undefined, undefined, {reason: reason}, undefined); +}; + +Promise.prototype.catchThrow = function (reason) { + if (arguments.length <= 1) { + return this._then( + undefined, thrower, undefined, {reason: reason}, undefined); + } else { + var _reason = arguments[1]; + var handler = function() {throw _reason;}; + return this.caught(reason, handler); + } +}; + +Promise.prototype.catchReturn = function (value) { + if (arguments.length <= 1) { + if (value instanceof Promise) value.suppressUnhandledRejections(); + return this._then( + undefined, returner, undefined, {value: value}, undefined); + } else { + var _value = arguments[1]; + if (_value instanceof Promise) _value.suppressUnhandledRejections(); + var handler = function() {return _value;}; + return this.caught(value, handler); + } +}; +}; + +},{}],9:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5"); +var Objectfreeze = es5.freeze; +var util = _dereq_("./util"); +var inherits = util.inherits; +var notEnumerableProp = util.notEnumerableProp; + +function subError(nameProperty, defaultMessage) { + function SubError(message) { + if (!(this instanceof SubError)) return new SubError(message); + notEnumerableProp(this, "message", + typeof message === "string" ? message : defaultMessage); + notEnumerableProp(this, "name", nameProperty); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + Error.call(this); + } + } + inherits(SubError, Error); + return SubError; +} + +var _TypeError, _RangeError; +var Warning = subError("Warning", "warning"); +var CancellationError = subError("CancellationError", "cancellation error"); +var TimeoutError = subError("TimeoutError", "timeout error"); +var AggregateError = subError("AggregateError", "aggregate error"); +try { + _TypeError = TypeError; + _RangeError = RangeError; +} catch(e) { + _TypeError = subError("TypeError", "type error"); + _RangeError = subError("RangeError", "range error"); +} + +var methods = ("join pop push shift unshift slice filter forEach some " + + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); + +for (var i = 0; i < methods.length; ++i) { + if (typeof Array.prototype[methods[i]] === "function") { + AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; + } +} + +es5.defineProperty(AggregateError.prototype, "length", { + value: 0, + configurable: false, + writable: true, + enumerable: true +}); +AggregateError.prototype["isOperational"] = true; +var level = 0; +AggregateError.prototype.toString = function() { + var indent = Array(level * 4 + 1).join(" "); + var ret = "\n" + indent + "AggregateError of:" + "\n"; + level++; + indent = Array(level * 4 + 1).join(" "); + for (var i = 0; i < this.length; ++i) { + var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; + var lines = str.split("\n"); + for (var j = 0; j < lines.length; ++j) { + lines[j] = indent + lines[j]; + } + str = lines.join("\n"); + ret += str + "\n"; + } + level--; + return ret; +}; + +function OperationalError(message) { + if (!(this instanceof OperationalError)) + return new OperationalError(message); + notEnumerableProp(this, "name", "OperationalError"); + notEnumerableProp(this, "message", message); + this.cause = message; + this["isOperational"] = true; + + if (message instanceof Error) { + notEnumerableProp(this, "message", message.message); + notEnumerableProp(this, "stack", message.stack); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + +} +inherits(OperationalError, Error); + +var errorTypes = Error["__BluebirdErrorTypes__"]; +if (!errorTypes) { + errorTypes = Objectfreeze({ + CancellationError: CancellationError, + TimeoutError: TimeoutError, + OperationalError: OperationalError, + RejectionError: OperationalError, + AggregateError: AggregateError + }); + es5.defineProperty(Error, "__BluebirdErrorTypes__", { + value: errorTypes, + writable: false, + enumerable: false, + configurable: false + }); +} + +module.exports = { + Error: Error, + TypeError: _TypeError, + RangeError: _RangeError, + CancellationError: errorTypes.CancellationError, + OperationalError: errorTypes.OperationalError, + TimeoutError: errorTypes.TimeoutError, + AggregateError: errorTypes.AggregateError, + Warning: Warning +}; + +},{"./es5":10,"./util":21}],10:[function(_dereq_,module,exports){ +var isES5 = (function(){ + "use strict"; + return this === undefined; +})(); + +if (isES5) { + module.exports = { + freeze: Object.freeze, + defineProperty: Object.defineProperty, + getDescriptor: Object.getOwnPropertyDescriptor, + keys: Object.keys, + names: Object.getOwnPropertyNames, + getPrototypeOf: Object.getPrototypeOf, + isArray: Array.isArray, + isES5: isES5, + propertyIsWritable: function(obj, prop) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop); + return !!(!descriptor || descriptor.writable || descriptor.set); + } + }; +} else { + var has = {}.hasOwnProperty; + var str = {}.toString; + var proto = {}.constructor.prototype; + + var ObjectKeys = function (o) { + var ret = []; + for (var key in o) { + if (has.call(o, key)) { + ret.push(key); + } + } + return ret; + }; + + var ObjectGetDescriptor = function(o, key) { + return {value: o[key]}; + }; + + var ObjectDefineProperty = function (o, key, desc) { + o[key] = desc.value; + return o; + }; + + var ObjectFreeze = function (obj) { + return obj; + }; + + var ObjectGetPrototypeOf = function (obj) { + try { + return Object(obj).constructor.prototype; + } + catch (e) { + return proto; + } + }; + + var ArrayIsArray = function (obj) { + try { + return str.call(obj) === "[object Array]"; + } + catch(e) { + return false; + } + }; + + module.exports = { + isArray: ArrayIsArray, + keys: ObjectKeys, + names: ObjectKeys, + defineProperty: ObjectDefineProperty, + getDescriptor: ObjectGetDescriptor, + freeze: ObjectFreeze, + getPrototypeOf: ObjectGetPrototypeOf, + isES5: isES5, + propertyIsWritable: function() { + return true; + } + }; +} + +},{}],11:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, tryConvertToPromise) { +var util = _dereq_("./util"); +var CancellationError = Promise.CancellationError; +var errorObj = util.errorObj; + +function PassThroughHandlerContext(promise, type, handler) { + this.promise = promise; + this.type = type; + this.handler = handler; + this.called = false; + this.cancelPromise = null; +} + +PassThroughHandlerContext.prototype.isFinallyHandler = function() { + return this.type === 0; +}; + +function FinallyHandlerCancelReaction(finallyHandler) { + this.finallyHandler = finallyHandler; +} + +FinallyHandlerCancelReaction.prototype._resultCancelled = function() { + checkCancel(this.finallyHandler); +}; + +function checkCancel(ctx, reason) { + if (ctx.cancelPromise != null) { + if (arguments.length > 1) { + ctx.cancelPromise._reject(reason); + } else { + ctx.cancelPromise._cancel(); + } + ctx.cancelPromise = null; + return true; + } + return false; +} + +function succeed() { + return finallyHandler.call(this, this.promise._target()._settledValue()); +} +function fail(reason) { + if (checkCancel(this, reason)) return; + errorObj.e = reason; + return errorObj; +} +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + if (!this.called) { + this.called = true; + var ret = this.isFinallyHandler() + ? handler.call(promise._boundValue()) + : handler.call(promise._boundValue(), reasonOrValue); + if (ret !== undefined) { + promise._setReturnedNonUndefined(); + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + if (this.cancelPromise != null) { + if (maybePromise._isCancelled()) { + var reason = + new CancellationError("late cancellation observer"); + promise._attachExtraTrace(reason); + errorObj.e = reason; + return errorObj; + } else if (maybePromise.isPending()) { + maybePromise._attachCancellationCallback( + new FinallyHandlerCancelReaction(this)); + } + } + return maybePromise._then( + succeed, fail, undefined, this, undefined); + } + } + } + + if (promise.isRejected()) { + checkCancel(this); + errorObj.e = reasonOrValue; + return errorObj; + } else { + checkCancel(this); + return reasonOrValue; + } +} + +Promise.prototype._passThrough = function(handler, type, success, fail) { + if (typeof handler !== "function") return this.then(); + return this._then(success, + fail, + undefined, + new PassThroughHandlerContext(this, type, handler), + undefined); +}; + +Promise.prototype.lastly = +Promise.prototype["finally"] = function (handler) { + return this._passThrough(handler, + 0, + finallyHandler, + finallyHandler); +}; + +Promise.prototype.tap = function (handler) { + return this._passThrough(handler, 1, finallyHandler); +}; + +return PassThroughHandlerContext; +}; + +},{"./util":21}],12:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, + getDomain) { +var util = _dereq_("./util"); +var canEvaluate = util.canEvaluate; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var reject; + +if (!true) { +if (canEvaluate) { + var thenCallback = function(i) { + return new Function("value", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = value; \n\ + holder.checkFulfillment(this); \n\ + ".replace(/Index/g, i)); + }; + + var promiseSetter = function(i) { + return new Function("promise", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = promise; \n\ + ".replace(/Index/g, i)); + }; + + var generateHolderClass = function(total) { + var props = new Array(total); + for (var i = 0; i < props.length; ++i) { + props[i] = "this.p" + (i+1); + } + var assignment = props.join(" = ") + " = null;"; + var cancellationCode= "var promise;\n" + props.map(function(prop) { + return " \n\ + promise = " + prop + "; \n\ + if (promise instanceof Promise) { \n\ + promise.cancel(); \n\ + } \n\ + "; + }).join("\n"); + var passedArguments = props.join(", "); + var name = "Holder$" + total; + + + var code = "return function(tryCatch, errorObj, Promise, async) { \n\ + 'use strict'; \n\ + function [TheName](fn) { \n\ + [TheProperties] \n\ + this.fn = fn; \n\ + this.asyncNeeded = true; \n\ + this.now = 0; \n\ + } \n\ + \n\ + [TheName].prototype._callFunction = function(promise) { \n\ + promise._pushContext(); \n\ + var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ + promise._popContext(); \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(ret.e, false); \n\ + } else { \n\ + promise._resolveCallback(ret); \n\ + } \n\ + }; \n\ + \n\ + [TheName].prototype.checkFulfillment = function(promise) { \n\ + var now = ++this.now; \n\ + if (now === [TheTotal]) { \n\ + if (this.asyncNeeded) { \n\ + async.invoke(this._callFunction, this, promise); \n\ + } else { \n\ + this._callFunction(promise); \n\ + } \n\ + \n\ + } \n\ + }; \n\ + \n\ + [TheName].prototype._resultCancelled = function() { \n\ + [CancellationCode] \n\ + }; \n\ + \n\ + return [TheName]; \n\ + }(tryCatch, errorObj, Promise, async); \n\ + "; + + code = code.replace(/\[TheName\]/g, name) + .replace(/\[TheTotal\]/g, total) + .replace(/\[ThePassedArguments\]/g, passedArguments) + .replace(/\[TheProperties\]/g, assignment) + .replace(/\[CancellationCode\]/g, cancellationCode); + + return new Function("tryCatch", "errorObj", "Promise", "async", code) + (tryCatch, errorObj, Promise, async); + }; + + var holderClasses = []; + var thenCallbacks = []; + var promiseSetters = []; + + for (var i = 0; i < 8; ++i) { + holderClasses.push(generateHolderClass(i + 1)); + thenCallbacks.push(thenCallback(i + 1)); + promiseSetters.push(promiseSetter(i + 1)); + } + + reject = function (reason) { + this._reject(reason); + }; +}} + +Promise.join = function () { + var last = arguments.length - 1; + var fn; + if (last > 0 && typeof arguments[last] === "function") { + fn = arguments[last]; + if (!true) { + if (last <= 8 && canEvaluate) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var HolderClass = holderClasses[last - 1]; + var holder = new HolderClass(fn); + var callbacks = thenCallbacks; + + for (var i = 0; i < last; ++i) { + var maybePromise = tryConvertToPromise(arguments[i], ret); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + var bitField = maybePromise._bitField; + ; + if (((bitField & 50397184) === 0)) { + maybePromise._then(callbacks[i], reject, + undefined, ret, holder); + promiseSetters[i](maybePromise, holder); + holder.asyncNeeded = false; + } else if (((bitField & 33554432) !== 0)) { + callbacks[i].call(ret, + maybePromise._value(), holder); + } else if (((bitField & 16777216) !== 0)) { + ret._reject(maybePromise._reason()); + } else { + ret._cancel(); + } + } else { + callbacks[i].call(ret, maybePromise, holder); + } + } + + if (!ret._isFateSealed()) { + if (holder.asyncNeeded) { + var domain = getDomain(); + if (domain !== null) { + holder.fn = util.domainBind(domain, holder.fn); + } + } + ret._setAsyncGuaranteed(); + ret._setOnCancel(holder); + } + return ret; + } + } + } + var args = [].slice.call(arguments);; + if (fn) args.pop(); + var ret = new PromiseArray(args).promise(); + return fn !== undefined ? ret.spread(fn) : ret; +}; + +}; + +},{"./util":21}],13:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { +var util = _dereq_("./util"); +var tryCatch = util.tryCatch; + +Promise.method = function (fn) { + if (typeof fn !== "function") { + throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); + } + return function () { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = tryCatch(fn).apply(this, arguments); + var promiseCreated = ret._popContext(); + debug.checkForgottenReturns( + value, promiseCreated, "Promise.method", ret); + ret._resolveFromSyncValue(value); + return ret; + }; +}; + +Promise.attempt = Promise["try"] = function (fn) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value; + if (arguments.length > 1) { + debug.deprecated("calling Promise.try with more than 1 argument"); + var arg = arguments[1]; + var ctx = arguments[2]; + value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) + : tryCatch(fn).call(ctx, arg); + } else { + value = tryCatch(fn)(); + } + var promiseCreated = ret._popContext(); + debug.checkForgottenReturns( + value, promiseCreated, "Promise.try", ret); + ret._resolveFromSyncValue(value); + return ret; +}; + +Promise.prototype._resolveFromSyncValue = function (value) { + if (value === util.errorObj) { + this._rejectCallback(value.e, false); + } else { + this._resolveCallback(value, true); + } +}; +}; + +},{"./util":21}],14:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = _dereq_("./errors"); +var OperationalError = errors.OperationalError; +var es5 = _dereq_("./es5"); + +function isUntypedError(obj) { + return obj instanceof Error && + es5.getPrototypeOf(obj) === Error.prototype; +} + +var rErrorKey = /^(?:name|message|stack|cause)$/; +function wrapAsOperationalError(obj) { + var ret; + if (isUntypedError(obj)) { + ret = new OperationalError(obj); + ret.name = obj.name; + ret.message = obj.message; + ret.stack = obj.stack; + var keys = es5.keys(obj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (!rErrorKey.test(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + util.markAsOriginatingFromRejection(obj); + return obj; +} + +function nodebackForPromise(promise, multiArgs) { + return function(err, value) { + if (promise === null) return; + if (err) { + var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); + promise._attachExtraTrace(wrapped); + promise._reject(wrapped); + } else if (!multiArgs) { + promise._fulfill(value); + } else { + var args = [].slice.call(arguments, 1);; + promise._fulfill(args); + } + promise = null; + }; +} + +module.exports = nodebackForPromise; + +},{"./errors":9,"./es5":10,"./util":21}],15:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function() { +var makeSelfResolutionError = function () { + return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); +}; +var reflectHandler = function() { + return new Promise.PromiseInspection(this._target()); +}; +var apiRejection = function(msg) { + return Promise.reject(new TypeError(msg)); +}; +function Proxyable() {} +var UNDEFINED_BINDING = {}; +var util = _dereq_("./util"); + +var getDomain; +if (util.isNode) { + getDomain = function() { + var ret = process.domain; + if (ret === undefined) ret = null; + return ret; + }; +} else { + getDomain = function() { + return null; + }; +} +util.notEnumerableProp(Promise, "_getDomain", getDomain); + +var es5 = _dereq_("./es5"); +var Async = _dereq_("./async"); +var async = new Async(); +es5.defineProperty(Promise, "_async", {value: async}); +var errors = _dereq_("./errors"); +var TypeError = Promise.TypeError = errors.TypeError; +Promise.RangeError = errors.RangeError; +var CancellationError = Promise.CancellationError = errors.CancellationError; +Promise.TimeoutError = errors.TimeoutError; +Promise.OperationalError = errors.OperationalError; +Promise.RejectionError = errors.OperationalError; +Promise.AggregateError = errors.AggregateError; +var INTERNAL = function(){}; +var APPLY = {}; +var NEXT_FILTER = {}; +var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); +var PromiseArray = + _dereq_("./promise_array")(Promise, INTERNAL, + tryConvertToPromise, apiRejection, Proxyable); +var Context = _dereq_("./context")(Promise); + /*jshint unused:false*/ +var createContext = Context.create; +var debug = _dereq_("./debuggability")(Promise, Context); +var CapturedTrace = debug.CapturedTrace; +var PassThroughHandlerContext = + _dereq_("./finally")(Promise, tryConvertToPromise); +var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); +var nodebackForPromise = _dereq_("./nodeback"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function check(self, executor) { + if (typeof executor !== "function") { + throw new TypeError("expecting a function but got " + util.classString(executor)); + } + if (self.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } +} + +function Promise(executor) { + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + if (executor !== INTERNAL) { + check(this, executor); + this._resolveFromExecutor(executor); + } + this._promiseCreated(); + this._fireEvent("promiseCreated", this); +} + +Promise.prototype.toString = function () { + return "[object Promise]"; +}; + +Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { + var len = arguments.length; + if (len > 1) { + var catchInstances = new Array(len - 1), + j = 0, i; + for (i = 0; i < len - 1; ++i) { + var item = arguments[i]; + if (util.isObject(item)) { + catchInstances[j++] = item; + } else { + return apiRejection("expecting an object but got " + + "A catch statement predicate " + util.classString(item)); + } + } + catchInstances.length = j; + fn = arguments[i]; + return this.then(undefined, catchFilter(catchInstances, fn, this)); + } + return this.then(undefined, fn); +}; + +Promise.prototype.reflect = function () { + return this._then(reflectHandler, + reflectHandler, undefined, this, undefined); +}; + +Promise.prototype.then = function (didFulfill, didReject) { + if (debug.warnings() && arguments.length > 0 && + typeof didFulfill !== "function" && + typeof didReject !== "function") { + var msg = ".then() only accepts functions but was passed: " + + util.classString(didFulfill); + if (arguments.length > 1) { + msg += ", " + util.classString(didReject); + } + this._warn(msg); + } + return this._then(didFulfill, didReject, undefined, undefined, undefined); +}; + +Promise.prototype.done = function (didFulfill, didReject) { + var promise = + this._then(didFulfill, didReject, undefined, undefined, undefined); + promise._setIsFinal(); +}; + +Promise.prototype.spread = function (fn) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + return this.all()._then(fn, undefined, undefined, APPLY, undefined); +}; + +Promise.prototype.toJSON = function () { + var ret = { + isFulfilled: false, + isRejected: false, + fulfillmentValue: undefined, + rejectionReason: undefined + }; + if (this.isFulfilled()) { + ret.fulfillmentValue = this.value(); + ret.isFulfilled = true; + } else if (this.isRejected()) { + ret.rejectionReason = this.reason(); + ret.isRejected = true; + } + return ret; +}; + +Promise.prototype.all = function () { + if (arguments.length > 0) { + this._warn(".all() was passed arguments but it does not take any"); + } + return new PromiseArray(this).promise(); +}; + +Promise.prototype.error = function (fn) { + return this.caught(util.originatesFromRejection, fn); +}; + +Promise.getNewLibraryCopy = module.exports; + +Promise.is = function (val) { + return val instanceof Promise; +}; + +Promise.fromNode = Promise.fromCallback = function(fn) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs + : false; + var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); + if (result === errorObj) { + ret._rejectCallback(result.e, true); + } + if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); + return ret; +}; + +Promise.all = function (promises) { + return new PromiseArray(promises).promise(); +}; + +Promise.cast = function (obj) { + var ret = tryConvertToPromise(obj); + if (!(ret instanceof Promise)) { + ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._setFulfilled(); + ret._rejectionHandler0 = obj; + } + return ret; +}; + +Promise.resolve = Promise.fulfilled = Promise.cast; + +Promise.reject = Promise.rejected = function (reason) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._rejectCallback(reason, true); + return ret; +}; + +Promise.setScheduler = function(fn) { + if (typeof fn !== "function") { + throw new TypeError("expecting a function but got " + util.classString(fn)); + } + return async.setScheduler(fn); +}; + +Promise.prototype._then = function ( + didFulfill, + didReject, + _, receiver, + internalData +) { + var haveInternalData = internalData !== undefined; + var promise = haveInternalData ? internalData : new Promise(INTERNAL); + var target = this._target(); + var bitField = target._bitField; + + if (!haveInternalData) { + promise._propagateFrom(this, 3); + promise._captureStackTrace(); + if (receiver === undefined && + ((this._bitField & 2097152) !== 0)) { + if (!((bitField & 50397184) === 0)) { + receiver = this._boundValue(); + } else { + receiver = target === this ? undefined : this._boundTo; + } + } + this._fireEvent("promiseChained", this, promise); + } + + var domain = getDomain(); + if (!((bitField & 50397184) === 0)) { + var handler, value, settler = target._settlePromiseCtx; + if (((bitField & 33554432) !== 0)) { + value = target._rejectionHandler0; + handler = didFulfill; + } else if (((bitField & 16777216) !== 0)) { + value = target._fulfillmentHandler0; + handler = didReject; + target._unsetRejectionIsUnhandled(); + } else { + settler = target._settlePromiseLateCancellationObserver; + value = new CancellationError("late cancellation observer"); + target._attachExtraTrace(value); + handler = didReject; + } + + async.invoke(settler, target, { + handler: domain === null ? handler + : (typeof handler === "function" && + util.domainBind(domain, handler)), + promise: promise, + receiver: receiver, + value: value + }); + } else { + target._addCallbacks(didFulfill, didReject, promise, receiver, domain); + } + + return promise; +}; + +Promise.prototype._length = function () { + return this._bitField & 65535; +}; + +Promise.prototype._isFateSealed = function () { + return (this._bitField & 117506048) !== 0; +}; + +Promise.prototype._isFollowing = function () { + return (this._bitField & 67108864) === 67108864; +}; + +Promise.prototype._setLength = function (len) { + this._bitField = (this._bitField & -65536) | + (len & 65535); +}; + +Promise.prototype._setFulfilled = function () { + this._bitField = this._bitField | 33554432; + this._fireEvent("promiseFulfilled", this); +}; + +Promise.prototype._setRejected = function () { + this._bitField = this._bitField | 16777216; + this._fireEvent("promiseRejected", this); +}; + +Promise.prototype._setFollowing = function () { + this._bitField = this._bitField | 67108864; + this._fireEvent("promiseResolved", this); +}; + +Promise.prototype._setIsFinal = function () { + this._bitField = this._bitField | 4194304; +}; + +Promise.prototype._isFinal = function () { + return (this._bitField & 4194304) > 0; +}; + +Promise.prototype._unsetCancelled = function() { + this._bitField = this._bitField & (~65536); +}; + +Promise.prototype._setCancelled = function() { + this._bitField = this._bitField | 65536; + this._fireEvent("promiseCancelled", this); +}; + +Promise.prototype._setWillBeCancelled = function() { + this._bitField = this._bitField | 8388608; +}; + +Promise.prototype._setAsyncGuaranteed = function() { + if (async.hasCustomScheduler()) return; + this._bitField = this._bitField | 134217728; +}; + +Promise.prototype._receiverAt = function (index) { + var ret = index === 0 ? this._receiver0 : this[ + index * 4 - 4 + 3]; + if (ret === UNDEFINED_BINDING) { + return undefined; + } else if (ret === undefined && this._isBound()) { + return this._boundValue(); + } + return ret; +}; + +Promise.prototype._promiseAt = function (index) { + return this[ + index * 4 - 4 + 2]; +}; + +Promise.prototype._fulfillmentHandlerAt = function (index) { + return this[ + index * 4 - 4 + 0]; +}; + +Promise.prototype._rejectionHandlerAt = function (index) { + return this[ + index * 4 - 4 + 1]; +}; + +Promise.prototype._boundValue = function() {}; + +Promise.prototype._migrateCallback0 = function (follower) { + var bitField = follower._bitField; + var fulfill = follower._fulfillmentHandler0; + var reject = follower._rejectionHandler0; + var promise = follower._promise0; + var receiver = follower._receiverAt(0); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, promise, receiver, null); +}; + +Promise.prototype._migrateCallbackAt = function (follower, index) { + var fulfill = follower._fulfillmentHandlerAt(index); + var reject = follower._rejectionHandlerAt(index); + var promise = follower._promiseAt(index); + var receiver = follower._receiverAt(index); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, promise, receiver, null); +}; + +Promise.prototype._addCallbacks = function ( + fulfill, + reject, + promise, + receiver, + domain +) { + var index = this._length(); + + if (index >= 65535 - 4) { + index = 0; + this._setLength(0); + } + + if (index === 0) { + this._promise0 = promise; + this._receiver0 = receiver; + if (typeof fulfill === "function") { + this._fulfillmentHandler0 = + domain === null ? fulfill : util.domainBind(domain, fulfill); + } + if (typeof reject === "function") { + this._rejectionHandler0 = + domain === null ? reject : util.domainBind(domain, reject); + } + } else { + var base = index * 4 - 4; + this[base + 2] = promise; + this[base + 3] = receiver; + if (typeof fulfill === "function") { + this[base + 0] = + domain === null ? fulfill : util.domainBind(domain, fulfill); + } + if (typeof reject === "function") { + this[base + 1] = + domain === null ? reject : util.domainBind(domain, reject); + } + } + this._setLength(index + 1); + return index; +}; + +Promise.prototype._proxy = function (proxyable, arg) { + this._addCallbacks(undefined, undefined, arg, proxyable, null); +}; + +Promise.prototype._resolveCallback = function(value, shouldBind) { + if (((this._bitField & 117506048) !== 0)) return; + if (value === this) + return this._rejectCallback(makeSelfResolutionError(), false); + var maybePromise = tryConvertToPromise(value, this); + if (!(maybePromise instanceof Promise)) return this._fulfill(value); + + if (shouldBind) this._propagateFrom(maybePromise, 2); + + var promise = maybePromise._target(); + + if (promise === this) { + this._reject(makeSelfResolutionError()); + return; + } + + var bitField = promise._bitField; + if (((bitField & 50397184) === 0)) { + var len = this._length(); + if (len > 0) promise._migrateCallback0(this); + for (var i = 1; i < len; ++i) { + promise._migrateCallbackAt(this, i); + } + this._setFollowing(); + this._setLength(0); + this._setFollowee(promise); + } else if (((bitField & 33554432) !== 0)) { + this._fulfill(promise._value()); + } else if (((bitField & 16777216) !== 0)) { + this._reject(promise._reason()); + } else { + var reason = new CancellationError("late cancellation observer"); + promise._attachExtraTrace(reason); + this._reject(reason); + } +}; + +Promise.prototype._rejectCallback = +function(reason, synchronous, ignoreNonErrorWarnings) { + var trace = util.ensureErrorObject(reason); + var hasStack = trace === reason; + if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { + var message = "a promise was rejected with a non-error: " + + util.classString(reason); + this._warn(message, true); + } + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason); +}; + +Promise.prototype._resolveFromExecutor = function (executor) { + var promise = this; + this._captureStackTrace(); + this._pushContext(); + var synchronous = true; + var r = this._execute(executor, function(value) { + promise._resolveCallback(value); + }, function (reason) { + promise._rejectCallback(reason, synchronous); + }); + synchronous = false; + this._popContext(); + + if (r !== undefined) { + promise._rejectCallback(r, true); + } +}; + +Promise.prototype._settlePromiseFromHandler = function ( + handler, receiver, value, promise +) { + var bitField = promise._bitField; + if (((bitField & 65536) !== 0)) return; + promise._pushContext(); + var x; + if (receiver === APPLY) { + if (!value || typeof value.length !== "number") { + x = errorObj; + x.e = new TypeError("cannot .spread() a non-array: " + + util.classString(value)); + } else { + x = tryCatch(handler).apply(this._boundValue(), value); + } + } else { + x = tryCatch(handler).call(receiver, value); + } + var promiseCreated = promise._popContext(); + bitField = promise._bitField; + if (((bitField & 65536) !== 0)) return; + + if (x === NEXT_FILTER) { + promise._reject(value); + } else if (x === errorObj) { + promise._rejectCallback(x.e, false); + } else { + debug.checkForgottenReturns(x, promiseCreated, "", promise, this); + promise._resolveCallback(x); + } +}; + +Promise.prototype._target = function() { + var ret = this; + while (ret._isFollowing()) ret = ret._followee(); + return ret; +}; + +Promise.prototype._followee = function() { + return this._rejectionHandler0; +}; + +Promise.prototype._setFollowee = function(promise) { + this._rejectionHandler0 = promise; +}; + +Promise.prototype._settlePromise = function(promise, handler, receiver, value) { + var isPromise = promise instanceof Promise; + var bitField = this._bitField; + var asyncGuaranteed = ((bitField & 134217728) !== 0); + if (((bitField & 65536) !== 0)) { + if (isPromise) promise._invokeInternalOnCancel(); + + if (receiver instanceof PassThroughHandlerContext && + receiver.isFinallyHandler()) { + receiver.cancelPromise = promise; + if (tryCatch(handler).call(receiver, value) === errorObj) { + promise._reject(errorObj.e); + } + } else if (handler === reflectHandler) { + promise._fulfill(reflectHandler.call(receiver)); + } else if (receiver instanceof Proxyable) { + receiver._promiseCancelled(promise); + } else if (isPromise || promise instanceof PromiseArray) { + promise._cancel(); + } else { + receiver.cancel(); + } + } else if (typeof handler === "function") { + if (!isPromise) { + handler.call(receiver, value, promise); + } else { + if (asyncGuaranteed) promise._setAsyncGuaranteed(); + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (receiver instanceof Proxyable) { + if (!receiver._isResolved()) { + if (((bitField & 33554432) !== 0)) { + receiver._promiseFulfilled(value, promise); + } else { + receiver._promiseRejected(value, promise); + } + } + } else if (isPromise) { + if (asyncGuaranteed) promise._setAsyncGuaranteed(); + if (((bitField & 33554432) !== 0)) { + promise._fulfill(value); + } else { + promise._reject(value); + } + } +}; + +Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { + var handler = ctx.handler; + var promise = ctx.promise; + var receiver = ctx.receiver; + var value = ctx.value; + if (typeof handler === "function") { + if (!(promise instanceof Promise)) { + handler.call(receiver, value, promise); + } else { + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (promise instanceof Promise) { + promise._reject(value); + } +}; + +Promise.prototype._settlePromiseCtx = function(ctx) { + this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); +}; + +Promise.prototype._settlePromise0 = function(handler, value, bitField) { + var promise = this._promise0; + var receiver = this._receiverAt(0); + this._promise0 = undefined; + this._receiver0 = undefined; + this._settlePromise(promise, handler, receiver, value); +}; + +Promise.prototype._clearCallbackDataAtIndex = function(index) { + var base = index * 4 - 4; + this[base + 2] = + this[base + 3] = + this[base + 0] = + this[base + 1] = undefined; +}; + +Promise.prototype._fulfill = function (value) { + var bitField = this._bitField; + if (((bitField & 117506048) >>> 16)) return; + if (value === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._reject(err); + } + this._setFulfilled(); + this._rejectionHandler0 = value; + + if ((bitField & 65535) > 0) { + if (((bitField & 134217728) !== 0)) { + this._settlePromises(); + } else { + async.settlePromises(this); + } + } +}; + +Promise.prototype._reject = function (reason) { + var bitField = this._bitField; + if (((bitField & 117506048) >>> 16)) return; + this._setRejected(); + this._fulfillmentHandler0 = reason; + + if (this._isFinal()) { + return async.fatalError(reason, util.isNode); + } + + if ((bitField & 65535) > 0) { + async.settlePromises(this); + } else { + this._ensurePossibleRejectionHandled(); + } +}; + +Promise.prototype._fulfillPromises = function (len, value) { + for (var i = 1; i < len; i++) { + var handler = this._fulfillmentHandlerAt(i); + var promise = this._promiseAt(i); + var receiver = this._receiverAt(i); + this._clearCallbackDataAtIndex(i); + this._settlePromise(promise, handler, receiver, value); + } +}; + +Promise.prototype._rejectPromises = function (len, reason) { + for (var i = 1; i < len; i++) { + var handler = this._rejectionHandlerAt(i); + var promise = this._promiseAt(i); + var receiver = this._receiverAt(i); + this._clearCallbackDataAtIndex(i); + this._settlePromise(promise, handler, receiver, reason); + } +}; + +Promise.prototype._settlePromises = function () { + var bitField = this._bitField; + var len = (bitField & 65535); + + if (len > 0) { + if (((bitField & 16842752) !== 0)) { + var reason = this._fulfillmentHandler0; + this._settlePromise0(this._rejectionHandler0, reason, bitField); + this._rejectPromises(len, reason); + } else { + var value = this._rejectionHandler0; + this._settlePromise0(this._fulfillmentHandler0, value, bitField); + this._fulfillPromises(len, value); + } + this._setLength(0); + } + this._clearCancellationData(); +}; + +Promise.prototype._settledValue = function() { + var bitField = this._bitField; + if (((bitField & 33554432) !== 0)) { + return this._rejectionHandler0; + } else if (((bitField & 16777216) !== 0)) { + return this._fulfillmentHandler0; + } +}; + +function deferResolve(v) {this.promise._resolveCallback(v);} +function deferReject(v) {this.promise._rejectCallback(v, false);} + +Promise.defer = Promise.pending = function() { + debug.deprecated("Promise.defer", "new Promise"); + var promise = new Promise(INTERNAL); + return { + promise: promise, + resolve: deferResolve, + reject: deferReject + }; +}; + +util.notEnumerableProp(Promise, + "_makeSelfResolutionError", + makeSelfResolutionError); + +_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, + debug); +_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); +_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); +_dereq_("./direct_resolve")(Promise); +_dereq_("./synchronous_inspection")(Promise); +_dereq_("./join")( + Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); +Promise.Promise = Promise; +Promise.version = "3.4.6"; + + util.toFastProperties(Promise); + util.toFastProperties(Promise.prototype); + function fillTypes(value) { + var p = new Promise(INTERNAL); + p._fulfillmentHandler0 = value; + p._rejectionHandler0 = value; + p._promise0 = value; + p._receiver0 = value; + } + // Complete slack tracking, opt out of field-type tracking and + // stabilize map + fillTypes({a: 1}); + fillTypes({b: 2}); + fillTypes({c: 3}); + fillTypes(1); + fillTypes(function(){}); + fillTypes(undefined); + fillTypes(false); + fillTypes(new Promise(INTERNAL)); + debug.setBounds(Async.firstLineError, util.lastLineError); + return Promise; + +}; + +},{"./async":1,"./bind":2,"./cancel":4,"./catch_filter":5,"./context":6,"./debuggability":7,"./direct_resolve":8,"./errors":9,"./es5":10,"./finally":11,"./join":12,"./method":13,"./nodeback":14,"./promise_array":16,"./synchronous_inspection":19,"./thenables":20,"./util":21}],16:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection, Proxyable) { +var util = _dereq_("./util"); +var isArray = util.isArray; + +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + } +} + +function PromiseArray(values) { + var promise = this._promise = new Promise(INTERNAL); + if (values instanceof Promise) { + promise._propagateFrom(values, 3); + } + promise._setOnCancel(this); + this._values = values; + this._length = 0; + this._totalResolved = 0; + this._init(undefined, -2); +} +util.inherits(PromiseArray, Proxyable); + +PromiseArray.prototype.length = function () { + return this._length; +}; + +PromiseArray.prototype.promise = function () { + return this._promise; +}; + +PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { + var values = tryConvertToPromise(this._values, this._promise); + if (values instanceof Promise) { + values = values._target(); + var bitField = values._bitField; + ; + this._values = values; + + if (((bitField & 50397184) === 0)) { + this._promise._setAsyncGuaranteed(); + return values._then( + init, + this._reject, + undefined, + this, + resolveValueIfEmpty + ); + } else if (((bitField & 33554432) !== 0)) { + values = values._value(); + } else if (((bitField & 16777216) !== 0)) { + return this._reject(values._reason()); + } else { + return this._cancel(); + } + } + values = util.asArray(values); + if (values === null) { + var err = apiRejection( + "expecting an array or an iterable object but got " + util.classString(values)).reason(); + this._promise._rejectCallback(err, false); + return; + } + + if (values.length === 0) { + if (resolveValueIfEmpty === -5) { + this._resolveEmptyArray(); + } + else { + this._resolve(toResolutionValue(resolveValueIfEmpty)); + } + return; + } + this._iterate(values); +}; + +PromiseArray.prototype._iterate = function(values) { + var len = this.getActualLength(values.length); + this._length = len; + this._values = this.shouldCopyValues() ? new Array(len) : this._values; + var result = this._promise; + var isResolved = false; + var bitField = null; + for (var i = 0; i < len; ++i) { + var maybePromise = tryConvertToPromise(values[i], result); + + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + bitField = maybePromise._bitField; + } else { + bitField = null; + } + + if (isResolved) { + if (bitField !== null) { + maybePromise.suppressUnhandledRejections(); + } + } else if (bitField !== null) { + if (((bitField & 50397184) === 0)) { + maybePromise._proxy(this, i); + this._values[i] = maybePromise; + } else if (((bitField & 33554432) !== 0)) { + isResolved = this._promiseFulfilled(maybePromise._value(), i); + } else if (((bitField & 16777216) !== 0)) { + isResolved = this._promiseRejected(maybePromise._reason(), i); + } else { + isResolved = this._promiseCancelled(i); + } + } else { + isResolved = this._promiseFulfilled(maybePromise, i); + } + } + if (!isResolved) result._setAsyncGuaranteed(); +}; + +PromiseArray.prototype._isResolved = function () { + return this._values === null; +}; + +PromiseArray.prototype._resolve = function (value) { + this._values = null; + this._promise._fulfill(value); +}; + +PromiseArray.prototype._cancel = function() { + if (this._isResolved() || !this._promise._isCancellable()) return; + this._values = null; + this._promise._cancel(); +}; + +PromiseArray.prototype._reject = function (reason) { + this._values = null; + this._promise._rejectCallback(reason, false); +}; + +PromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + return true; + } + return false; +}; + +PromiseArray.prototype._promiseCancelled = function() { + this._cancel(); + return true; +}; + +PromiseArray.prototype._promiseRejected = function (reason) { + this._totalResolved++; + this._reject(reason); + return true; +}; + +PromiseArray.prototype._resultCancelled = function() { + if (this._isResolved()) return; + var values = this._values; + this._cancel(); + if (values instanceof Promise) { + values.cancel(); + } else { + for (var i = 0; i < values.length; ++i) { + if (values[i] instanceof Promise) { + values[i].cancel(); + } + } + } +}; + +PromiseArray.prototype.shouldCopyValues = function () { + return true; +}; + +PromiseArray.prototype.getActualLength = function (len) { + return len; +}; + +return PromiseArray; +}; + +},{"./util":21}],17:[function(_dereq_,module,exports){ +"use strict"; +function arrayMove(src, srcIndex, dst, dstIndex, len) { + for (var j = 0; j < len; ++j) { + dst[j + dstIndex] = src[j + srcIndex]; + src[j + srcIndex] = void 0; + } +} + +function Queue(capacity) { + this._capacity = capacity; + this._length = 0; + this._front = 0; +} + +Queue.prototype._willBeOverCapacity = function (size) { + return this._capacity < size; +}; + +Queue.prototype._pushOne = function (arg) { + var length = this.length(); + this._checkCapacity(length + 1); + var i = (this._front + length) & (this._capacity - 1); + this[i] = arg; + this._length = length + 1; +}; + +Queue.prototype._unshiftOne = function(value) { + var capacity = this._capacity; + this._checkCapacity(this.length() + 1); + var front = this._front; + var i = (((( front - 1 ) & + ( capacity - 1) ) ^ capacity ) - capacity ); + this[i] = value; + this._front = i; + this._length = this.length() + 1; +}; + +Queue.prototype.unshift = function(fn, receiver, arg) { + this._unshiftOne(arg); + this._unshiftOne(receiver); + this._unshiftOne(fn); +}; + +Queue.prototype.push = function (fn, receiver, arg) { + var length = this.length() + 3; + if (this._willBeOverCapacity(length)) { + this._pushOne(fn); + this._pushOne(receiver); + this._pushOne(arg); + return; + } + var j = this._front + length - 3; + this._checkCapacity(length); + var wrapMask = this._capacity - 1; + this[(j + 0) & wrapMask] = fn; + this[(j + 1) & wrapMask] = receiver; + this[(j + 2) & wrapMask] = arg; + this._length = length; +}; + +Queue.prototype.shift = function () { + var front = this._front, + ret = this[front]; + + this[front] = undefined; + this._front = (front + 1) & (this._capacity - 1); + this._length--; + return ret; +}; + +Queue.prototype.length = function () { + return this._length; +}; + +Queue.prototype._checkCapacity = function (size) { + if (this._capacity < size) { + this._resizeTo(this._capacity << 1); + } +}; + +Queue.prototype._resizeTo = function (capacity) { + var oldCapacity = this._capacity; + this._capacity = capacity; + var front = this._front; + var length = this._length; + var moveItemsCount = (front + length) & (oldCapacity - 1); + arrayMove(this, 0, this, oldCapacity, moveItemsCount); +}; + +module.exports = Queue; + +},{}],18:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util"); +var schedule; +var noAsyncScheduler = function() { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); +}; +var NativePromise = util.getNativePromise(); +if (util.isNode && typeof MutationObserver === "undefined") { + var GlobalSetImmediate = global.setImmediate; + var ProcessNextTick = process.nextTick; + schedule = util.isRecentNode + ? function(fn) { GlobalSetImmediate.call(global, fn); } + : function(fn) { ProcessNextTick.call(process, fn); }; +} else if (typeof NativePromise === "function" && + typeof NativePromise.resolve === "function") { + var nativePromise = NativePromise.resolve(); + schedule = function(fn) { + nativePromise.then(fn); + }; +} else if ((typeof MutationObserver !== "undefined") && + !(typeof window !== "undefined" && + window.navigator && + (window.navigator.standalone || window.cordova))) { + schedule = (function() { + var div = document.createElement("div"); + var opts = {attributes: true}; + var toggleScheduled = false; + var div2 = document.createElement("div"); + var o2 = new MutationObserver(function() { + div.classList.toggle("foo"); + toggleScheduled = false; + }); + o2.observe(div2, opts); + + var scheduleToggle = function() { + if (toggleScheduled) return; + toggleScheduled = true; + div2.classList.toggle("foo"); + }; + + return function schedule(fn) { + var o = new MutationObserver(function() { + o.disconnect(); + fn(); + }); + o.observe(div, opts); + scheduleToggle(); + }; + })(); +} else if (typeof setImmediate !== "undefined") { + schedule = function (fn) { + setImmediate(fn); + }; +} else if (typeof setTimeout !== "undefined") { + schedule = function (fn) { + setTimeout(fn, 0); + }; +} else { + schedule = noAsyncScheduler; +} +module.exports = schedule; + +},{"./util":21}],19:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +function PromiseInspection(promise) { + if (promise !== undefined) { + promise = promise._target(); + this._bitField = promise._bitField; + this._settledValueField = promise._isFateSealed() + ? promise._settledValue() : undefined; + } + else { + this._bitField = 0; + this._settledValueField = undefined; + } +} + +PromiseInspection.prototype._settledValue = function() { + return this._settledValueField; +}; + +var value = PromiseInspection.prototype.value = function () { + if (!this.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + return this._settledValue(); +}; + +var reason = PromiseInspection.prototype.error = +PromiseInspection.prototype.reason = function () { + if (!this.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + return this._settledValue(); +}; + +var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { + return (this._bitField & 33554432) !== 0; +}; + +var isRejected = PromiseInspection.prototype.isRejected = function () { + return (this._bitField & 16777216) !== 0; +}; + +var isPending = PromiseInspection.prototype.isPending = function () { + return (this._bitField & 50397184) === 0; +}; + +var isResolved = PromiseInspection.prototype.isResolved = function () { + return (this._bitField & 50331648) !== 0; +}; + +PromiseInspection.prototype.isCancelled = function() { + return (this._bitField & 8454144) !== 0; +}; + +Promise.prototype.__isCancelled = function() { + return (this._bitField & 65536) === 65536; +}; + +Promise.prototype._isCancelled = function() { + return this._target().__isCancelled(); +}; + +Promise.prototype.isCancelled = function() { + return (this._target()._bitField & 8454144) !== 0; +}; + +Promise.prototype.isPending = function() { + return isPending.call(this._target()); +}; + +Promise.prototype.isRejected = function() { + return isRejected.call(this._target()); +}; + +Promise.prototype.isFulfilled = function() { + return isFulfilled.call(this._target()); +}; + +Promise.prototype.isResolved = function() { + return isResolved.call(this._target()); +}; + +Promise.prototype.value = function() { + return value.call(this._target()); +}; + +Promise.prototype.reason = function() { + var target = this._target(); + target._unsetRejectionIsUnhandled(); + return reason.call(target); +}; + +Promise.prototype._value = function() { + return this._settledValue(); +}; + +Promise.prototype._reason = function() { + this._unsetRejectionIsUnhandled(); + return this._settledValue(); +}; + +Promise.PromiseInspection = PromiseInspection; +}; + +},{}],20:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = _dereq_("./util"); +var errorObj = util.errorObj; +var isObject = util.isObject; + +function tryConvertToPromise(obj, context) { + if (isObject(obj)) { + if (obj instanceof Promise) return obj; + var then = getThen(obj); + if (then === errorObj) { + if (context) context._pushContext(); + var ret = Promise.reject(then.e); + if (context) context._popContext(); + return ret; + } else if (typeof then === "function") { + if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfill, + ret._reject, + undefined, + ret, + null + ); + return ret; + } + return doThenable(obj, then, context); + } + } + return obj; +} + +function doGetThen(obj) { + return obj.then; +} + +function getThen(obj) { + try { + return doGetThen(obj); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} + +var hasProp = {}.hasOwnProperty; +function isAnyBluebirdPromise(obj) { + try { + return hasProp.call(obj, "_promise0"); + } catch (e) { + return false; + } +} + +function doThenable(x, then, context) { + var promise = new Promise(INTERNAL); + var ret = promise; + if (context) context._pushContext(); + promise._captureStackTrace(); + if (context) context._popContext(); + var synchronous = true; + var result = util.tryCatch(then).call(x, resolve, reject); + synchronous = false; + + if (promise && result === errorObj) { + promise._rejectCallback(result.e, true, true); + promise = null; + } + + function resolve(value) { + if (!promise) return; + promise._resolveCallback(value); + promise = null; + } + + function reject(reason) { + if (!promise) return; + promise._rejectCallback(reason, synchronous, true); + promise = null; + } + return ret; +} + +return tryConvertToPromise; +}; + +},{"./util":21}],21:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5"); +var canEvaluate = typeof navigator == "undefined"; + +var errorObj = {e: {}}; +var tryCatchTarget; +var globalObject = typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : + typeof global !== "undefined" ? global : + this !== undefined ? this : null; + +function tryCatcher() { + try { + var target = tryCatchTarget; + tryCatchTarget = null; + return target.apply(this, arguments); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} +function tryCatch(fn) { + tryCatchTarget = fn; + return tryCatcher; +} + +var inherits = function(Child, Parent) { + var hasProp = {}.hasOwnProperty; + + function T() { + this.constructor = Child; + this.constructor$ = Parent; + for (var propertyName in Parent.prototype) { + if (hasProp.call(Parent.prototype, propertyName) && + propertyName.charAt(propertyName.length-1) !== "$" + ) { + this[propertyName + "$"] = Parent.prototype[propertyName]; + } + } + } + T.prototype = Parent.prototype; + Child.prototype = new T(); + return Child.prototype; +}; + + +function isPrimitive(val) { + return val == null || val === true || val === false || + typeof val === "string" || typeof val === "number"; + +} + +function isObject(value) { + return typeof value === "function" || + typeof value === "object" && value !== null; +} + +function maybeWrapAsError(maybeError) { + if (!isPrimitive(maybeError)) return maybeError; + + return new Error(safeToString(maybeError)); +} + +function withAppended(target, appendee) { + var len = target.length; + var ret = new Array(len + 1); + var i; + for (i = 0; i < len; ++i) { + ret[i] = target[i]; + } + ret[i] = appendee; + return ret; +} + +function getDataPropertyOrDefault(obj, key, defaultValue) { + if (es5.isES5) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + + if (desc != null) { + return desc.get == null && desc.set == null + ? desc.value + : defaultValue; + } + } else { + return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; + } +} + +function notEnumerableProp(obj, name, value) { + if (isPrimitive(obj)) return obj; + var descriptor = { + value: value, + configurable: true, + enumerable: false, + writable: true + }; + es5.defineProperty(obj, name, descriptor); + return obj; +} + +function thrower(r) { + throw r; +} + +var inheritedDataKeys = (function() { + var excludedPrototypes = [ + Array.prototype, + Object.prototype, + Function.prototype + ]; + + var isExcludedProto = function(val) { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (excludedPrototypes[i] === val) { + return true; + } + } + return false; + }; + + if (es5.isES5) { + var getKeys = Object.getOwnPropertyNames; + return function(obj) { + var ret = []; + var visitedKeys = Object.create(null); + while (obj != null && !isExcludedProto(obj)) { + var keys; + try { + keys = getKeys(obj); + } catch (e) { + return ret; + } + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (visitedKeys[key]) continue; + visitedKeys[key] = true; + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null && desc.get == null && desc.set == null) { + ret.push(key); + } + } + obj = es5.getPrototypeOf(obj); + } + return ret; + }; + } else { + var hasProp = {}.hasOwnProperty; + return function(obj) { + if (isExcludedProto(obj)) return []; + var ret = []; + + /*jshint forin:false */ + enumeration: for (var key in obj) { + if (hasProp.call(obj, key)) { + ret.push(key); + } else { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (hasProp.call(excludedPrototypes[i], key)) { + continue enumeration; + } + } + ret.push(key); + } + } + return ret; + }; + } + +})(); + +var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + + var hasMethods = es5.isES5 && keys.length > 1; + var hasMethodsOtherThanConstructor = keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + var hasThisAssignmentAndStaticMethods = + thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; + + if (hasMethods || hasMethodsOtherThanConstructor || + hasThisAssignmentAndStaticMethods) { + return true; + } + } + return false; + } catch (e) { + return false; + } +} + +function toFastProperties(obj) { + /*jshint -W027,-W055,-W031*/ + function FakeConstructor() {} + FakeConstructor.prototype = obj; + var l = 8; + while (l--) new FakeConstructor(); + return obj; + eval(obj); +} + +var rident = /^[a-z$_][a-z$_0-9]*$/i; +function isIdentifier(str) { + return rident.test(str); +} + +function filledRange(count, prefix, suffix) { + var ret = new Array(count); + for(var i = 0; i < count; ++i) { + ret[i] = prefix + i + suffix; + } + return ret; +} + +function safeToString(obj) { + try { + return obj + ""; + } catch (e) { + return "[no string representation]"; + } +} + +function isError(obj) { + return obj !== null && + typeof obj === "object" && + typeof obj.message === "string" && + typeof obj.name === "string"; +} + +function markAsOriginatingFromRejection(e) { + try { + notEnumerableProp(e, "isOperational", true); + } + catch(ignore) {} +} + +function originatesFromRejection(e) { + if (e == null) return false; + return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || + e["isOperational"] === true); +} + +function canAttachTrace(obj) { + return isError(obj) && es5.propertyIsWritable(obj, "stack"); +} + +var ensureErrorObject = (function() { + if (!("stack" in new Error())) { + return function(value) { + if (canAttachTrace(value)) return value; + try {throw new Error(safeToString(value));} + catch(err) {return err;} + }; + } else { + return function(value) { + if (canAttachTrace(value)) return value; + return new Error(safeToString(value)); + }; + } +})(); + +function classString(obj) { + return {}.toString.call(obj); +} + +function copyDescriptors(from, to, filter) { + var keys = es5.names(from); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (filter(key)) { + try { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } catch (ignore) {} + } + } +} + +var asArray = function(v) { + if (es5.isArray(v)) { + return v; + } + return null; +}; + +if (typeof Symbol !== "undefined" && Symbol.iterator) { + var ArrayFrom = typeof Array.from === "function" ? function(v) { + return Array.from(v); + } : function(v) { + var ret = []; + var it = v[Symbol.iterator](); + var itResult; + while (!((itResult = it.next()).done)) { + ret.push(itResult.value); + } + return ret; + }; + + asArray = function(v) { + if (es5.isArray(v)) { + return v; + } else if (v != null && typeof v[Symbol.iterator] === "function") { + return ArrayFrom(v); + } + return null; + }; +} + +var isNode = typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]"; + +function env(key, def) { + return isNode ? process.env[key] : def; +} + +function getNativePromise() { + if (typeof Promise === "function") { + try { + var promise = new Promise(function(){}); + if ({}.toString.call(promise) === "[object Promise]") { + return Promise; + } + } catch (e) {} + } +} + +function domainBind(self, cb) { + return self.bind(cb); +} + +var ret = { + isClass: isClass, + isIdentifier: isIdentifier, + inheritedDataKeys: inheritedDataKeys, + getDataPropertyOrDefault: getDataPropertyOrDefault, + thrower: thrower, + isArray: es5.isArray, + asArray: asArray, + notEnumerableProp: notEnumerableProp, + isPrimitive: isPrimitive, + isObject: isObject, + isError: isError, + canEvaluate: canEvaluate, + errorObj: errorObj, + tryCatch: tryCatch, + inherits: inherits, + withAppended: withAppended, + maybeWrapAsError: maybeWrapAsError, + toFastProperties: toFastProperties, + filledRange: filledRange, + toString: safeToString, + canAttachTrace: canAttachTrace, + ensureErrorObject: ensureErrorObject, + originatesFromRejection: originatesFromRejection, + markAsOriginatingFromRejection: markAsOriginatingFromRejection, + classString: classString, + copyDescriptors: copyDescriptors, + hasDevTools: typeof chrome !== "undefined" && chrome && + typeof chrome.loadTimes === "function", + isNode: isNode, + env: env, + global: globalObject, + getNativePromise: getNativePromise, + domainBind: domainBind +}; +ret.isRecentNode = ret.isNode && (function() { + var version = process.versions.node.split(".").map(Number); + return (version[0] === 0 && version[1] > 10) || (version[0] > 0); +})(); + +if (ret.isNode) ret.toFastProperties(process); + +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; + +},{"./es5":10}]},{},[3])(3) +}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } +/* + RequireJS 2.2.0 Copyright jQuery Foundation and other contributors. + Released under MIT license, http://github.com/requirejs/requirejs/LICENSE +*/ +var requirejs,require,define; +(function(ga){function ka(b,c,d,g){return g||""}function K(b){return"[object Function]"===Q.call(b)}function L(b){return"[object Array]"===Q.call(b)}function y(b,c){if(b){var d;for(d=0;dthis.depCount&&!this.defined){if(K(k)){if(this.events.error&&this.map.isDefine||g.onError!== +ha)try{h=l.execCb(c,k,b,h)}catch(d){a=d}else h=l.execCb(c,k,b,h);this.map.isDefine&&void 0===h&&((b=this.module)?h=b.exports:this.usingExports&&(h=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",A(this.error=a)}else h=k;this.exports=h;if(this.map.isDefine&&!this.ignore&&(v[c]=h,g.onResourceLoad)){var f=[];y(this.depMaps,function(a){f.push(a.normalizedMap||a)});g.onResourceLoad(l,this.map,f)}C(c); +this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0)}}},callPlugin:function(){var a=this.map,b=a.id,d=q(a.prefix);this.depMaps.push(d);w(d,"defined",z(this,function(h){var k,f,d=e(fa,this.map.id),M=this.map.name,r=this.map.parentMap?this.map.parentMap.name:null,m=l.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(h.normalize&&(M=h.normalize(M,function(a){return c(a,r,!0)})|| +""),f=q(a.prefix+"!"+M,this.map.parentMap),w(f,"defined",z(this,function(a){this.map.normalizedMap=f;this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),h=e(t,f.id)){this.depMaps.push(f);if(this.events.error)h.on("error",z(this,function(a){this.emit("error",a)}));h.enable()}}else d?(this.map.url=l.nameToUrl(d),this.load()):(k=z(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),k.error=z(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];D(t,function(a){0=== +a.map.id.indexOf(b+"_unnormalized")&&C(a.map.id)});A(a)}),k.fromText=z(this,function(h,c){var d=a.name,f=q(d),M=S;c&&(h=c);M&&(S=!1);u(f);x(p.config,b)&&(p.config[d]=p.config[b]);try{g.exec(h)}catch(e){return A(F("fromtexteval","fromText eval for "+b+" failed: "+e,e,[b]))}M&&(S=!0);this.depMaps.push(f);l.completeLoad(d);m([d],k)}),h.load(a.name,m,k,p))}));l.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){Z[this.map.id]=this;this.enabling=this.enabled=!0;y(this.depMaps,z(this,function(a, +b){var c,h;if("string"===typeof a){a=q(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=e(R,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;w(a,"defined",z(this,function(a){this.undefed||(this.defineDep(b,a),this.check())}));this.errback?w(a,"error",z(this,this.errback)):this.events.error&&w(a,"error",z(this,function(a){this.emit("error",a)}))}c=a.id;h=t[c];x(R,c)||!h||h.enabled||l.enable(a,this)}));D(this.pluginMaps,z(this,function(a){var b=e(t,a.id); +b&&!b.enabled&&l.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){y(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};l={config:p,contextName:b,registry:t,defined:v,urlFetched:W,defQueue:G,defQueueMap:{},Module:da,makeModuleMap:q,nextTick:g.nextTick,onError:A,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");if("string"===typeof a.urlArgs){var b= +a.urlArgs;a.urlArgs=function(a,c){return(-1===c.indexOf("?")?"?":"&")+b}}var c=p.shim,h={paths:!0,bundles:!0,config:!0,map:!0};D(a,function(a,b){h[b]?(p[b]||(p[b]={}),Y(p[b],a,!0,!0)):p[b]=a});a.bundles&&D(a.bundles,function(a,b){y(a,function(a){a!==b&&(fa[a]=b)})});a.shim&&(D(a.shim,function(a,b){L(a)&&(a={deps:a});!a.exports&&!a.init||a.exportsFn||(a.exportsFn=l.makeShimExports(a));c[b]=a}),p.shim=c);a.packages&&y(a.packages,function(a){var b;a="string"===typeof a?{name:a}:a;b=a.name;a.location&& +(p.paths[b]=a.location);p.pkgs[b]=a.name+"/"+(a.main||"main").replace(na,"").replace(U,"")});D(t,function(a,b){a.inited||a.map.unnormalized||(a.map=q(b,null,!0))});(a.deps||a.callback)&&l.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(ga,arguments));return b||a.exports&&ia(a.exports)}},makeRequire:function(a,n){function m(c,d,f){var e,r;n.enableBuildCallback&&d&&K(d)&&(d.__requireJsBuild=!0);if("string"===typeof c){if(K(d))return A(F("requireargs", +"Invalid require call"),f);if(a&&x(R,c))return R[c](t[a.id]);if(g.get)return g.get(l,c,a,m);e=q(c,a,!1,!0);e=e.id;return x(v,e)?v[e]:A(F("notloaded",'Module name "'+e+'" has not been loaded yet for context: '+b+(a?"":". Use require([])")))}P();l.nextTick(function(){P();r=u(q(null,a));r.skipMap=n.skipMap;r.init(c,d,f,{enabled:!0});H()});return m}n=n||{};Y(m,{isBrowser:E,toUrl:function(b){var d,f=b.lastIndexOf("."),g=b.split("/")[0];-1!==f&&("."!==g&&".."!==g||1e.attachEvent.toString().indexOf("[native code")||ca?(e.addEventListener("load",b.onScriptLoad,!1),e.addEventListener("error",b.onScriptError,!1)):(S=!0,e.attachEvent("onreadystatechange",b.onScriptLoad));e.src=d;if(m.onNodeCreated)m.onNodeCreated(e,m,c,d);P=e;H?C.insertBefore(e,H):C.appendChild(e);P=null;return e}if(ja)try{setTimeout(function(){}, +0),importScripts(d),b.completeLoad(c)}catch(q){b.onError(F("importscripts","importScripts failed for "+c+" at "+d,q,[c]))}};E&&!w.skipDataMain&&X(document.getElementsByTagName("script"),function(b){C||(C=b.parentNode);if(O=b.getAttribute("data-main"))return u=O,w.baseUrl||-1!==u.indexOf("!")||(I=u.split("/"),u=I.pop(),T=I.length?I.join("/")+"/":"./",w.baseUrl=T),u=u.replace(U,""),g.jsExtRegExp.test(u)&&(u=O),w.deps=w.deps?w.deps.concat(u):[u],!0});define=function(b,c,d){var e,g;"string"!==typeof b&& +(d=c,c=b,b=null);L(c)||(d=c,c=null);!c&&K(d)&&(c=[],d.length&&(d.toString().replace(qa,ka).replace(ra,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));S&&(e=P||pa())&&(b||(b=e.getAttribute("data-requiremodule")),g=J[e.getAttribute("data-requirecontext")]);g?(g.defQueue.push([b,c,d]),g.defQueueMap[b]=!0):V.push([b,c,d])};define.amd={jQuery:!0};g.exec=function(b){return eval(b)};g(w)}})(this); + +_aureliaConfigureModuleLoader(); +define('text',{}); +define('aurelia-dependency-injection',['exports', 'aurelia-metadata', 'aurelia-pal'], function (exports, _aureliaMetadata, _aureliaPal) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.Container = exports.InvocationHandler = exports._emptyParameters = exports.SingletonRegistration = exports.TransientRegistration = exports.FactoryInvoker = exports.NewInstance = exports.Factory = exports.StrategyResolver = exports.Parent = exports.Optional = exports.All = exports.Lazy = exports.resolver = undefined; + exports.getDecoratorDependencies = getDecoratorDependencies; + exports.lazy = lazy; + exports.all = all; + exports.optional = optional; + exports.parent = parent; + exports.factory = factory; + exports.newInstance = newInstance; + exports.invoker = invoker; + exports.invokeAsFactory = invokeAsFactory; + exports.registration = registration; + exports.transient = transient; + exports.singleton = singleton; + exports.autoinject = autoinject; + exports.inject = inject; + + + + var _dec, _class, _dec2, _class3, _dec3, _class5, _dec4, _class7, _dec5, _class9, _dec6, _class11, _dec7, _class13, _classInvokers; + + var resolver = exports.resolver = _aureliaMetadata.protocol.create('aurelia:resolver', function (target) { + if (!(typeof target.get === 'function')) { + return 'Resolvers must implement: get(container: Container, key: any): any'; + } + + return true; + }); + + var Lazy = exports.Lazy = (_dec = resolver(), _dec(_class = function () { + function Lazy(key) { + + + this._key = key; + } + + Lazy.prototype.get = function get(container) { + var _this = this; + + return function () { + return container.get(_this._key); + }; + }; + + Lazy.of = function of(key) { + return new Lazy(key); + }; + + return Lazy; + }()) || _class); + var All = exports.All = (_dec2 = resolver(), _dec2(_class3 = function () { + function All(key) { + + + this._key = key; + } + + All.prototype.get = function get(container) { + return container.getAll(this._key); + }; + + All.of = function of(key) { + return new All(key); + }; + + return All; + }()) || _class3); + var Optional = exports.Optional = (_dec3 = resolver(), _dec3(_class5 = function () { + function Optional(key) { + var checkParent = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1]; + + + + this._key = key; + this._checkParent = checkParent; + } + + Optional.prototype.get = function get(container) { + if (container.hasResolver(this._key, this._checkParent)) { + return container.get(this._key); + } + + return null; + }; + + Optional.of = function of(key) { + var checkParent = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1]; + + return new Optional(key, checkParent); + }; + + return Optional; + }()) || _class5); + var Parent = exports.Parent = (_dec4 = resolver(), _dec4(_class7 = function () { + function Parent(key) { + + + this._key = key; + } + + Parent.prototype.get = function get(container) { + return container.parent ? container.parent.get(this._key) : null; + }; + + Parent.of = function of(key) { + return new Parent(key); + }; + + return Parent; + }()) || _class7); + var StrategyResolver = exports.StrategyResolver = (_dec5 = resolver(), _dec5(_class9 = function () { + function StrategyResolver(strategy, state) { + + + this.strategy = strategy; + this.state = state; + } + + StrategyResolver.prototype.get = function get(container, key) { + switch (this.strategy) { + case 0: + return this.state; + case 1: + var singleton = container.invoke(this.state); + this.state = singleton; + this.strategy = 0; + return singleton; + case 2: + return container.invoke(this.state); + case 3: + return this.state(container, key, this); + case 4: + return this.state[0].get(container, key); + case 5: + return container.get(this.state); + default: + throw new Error('Invalid strategy: ' + this.strategy); + } + }; + + return StrategyResolver; + }()) || _class9); + var Factory = exports.Factory = (_dec6 = resolver(), _dec6(_class11 = function () { + function Factory(key) { + + + this._key = key; + } + + Factory.prototype.get = function get(container) { + var _this2 = this; + + return function () { + for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) { + rest[_key] = arguments[_key]; + } + + return container.invoke(_this2._key, rest); + }; + }; + + Factory.of = function of(key) { + return new Factory(key); + }; + + return Factory; + }()) || _class11); + var NewInstance = exports.NewInstance = (_dec7 = resolver(), _dec7(_class13 = function () { + function NewInstance(key) { + + + this.key = key; + this.asKey = key; + + for (var _len2 = arguments.length, dynamicDependencies = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + dynamicDependencies[_key2 - 1] = arguments[_key2]; + } + + this.dynamicDependencies = dynamicDependencies; + } + + NewInstance.prototype.get = function get(container) { + var dynamicDependencies = this.dynamicDependencies.length > 0 ? this.dynamicDependencies.map(function (dependency) { + return dependency['protocol:aurelia:resolver'] ? dependency.get(container) : container.get(dependency); + }) : undefined; + var instance = container.invoke(this.key, dynamicDependencies); + container.registerInstance(this.asKey, instance); + return instance; + }; + + NewInstance.prototype.as = function as(key) { + this.asKey = key; + return this; + }; + + NewInstance.of = function of(key) { + for (var _len3 = arguments.length, dynamicDependencies = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + dynamicDependencies[_key3 - 1] = arguments[_key3]; + } + + return new (Function.prototype.bind.apply(NewInstance, [null].concat([key], dynamicDependencies)))(); + }; + + return NewInstance; + }()) || _class13); + function getDecoratorDependencies(target, name) { + var dependencies = target.inject; + if (typeof dependencies === 'function') { + throw new Error('Decorator ' + name + ' cannot be used with "inject()". Please use an array instead.'); + } + if (!dependencies) { + dependencies = _aureliaMetadata.metadata.getOwn(_aureliaMetadata.metadata.paramTypes, target).slice(); + target.inject = dependencies; + } + + return dependencies; + } + + function lazy(keyValue) { + return function (target, key, index) { + var params = getDecoratorDependencies(target, 'lazy'); + params[index] = Lazy.of(keyValue); + }; + } + + function all(keyValue) { + return function (target, key, index) { + var params = getDecoratorDependencies(target, 'all'); + params[index] = All.of(keyValue); + }; + } + + function optional() { + var checkParentOrTarget = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; + + var deco = function deco(checkParent) { + return function (target, key, index) { + var params = getDecoratorDependencies(target, 'optional'); + params[index] = Optional.of(params[index], checkParent); + }; + }; + if (typeof checkParentOrTarget === 'boolean') { + return deco(checkParentOrTarget); + } + return deco(true); + } + + function parent(target, key, index) { + var params = getDecoratorDependencies(target, 'parent'); + params[index] = Parent.of(params[index]); + } + + function factory(keyValue, asValue) { + return function (target, key, index) { + var params = getDecoratorDependencies(target, 'factory'); + var factory = Factory.of(keyValue); + params[index] = asValue ? factory.as(asValue) : factory; + }; + } + + function newInstance(asKeyOrTarget) { + for (var _len4 = arguments.length, dynamicDependencies = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + dynamicDependencies[_key4 - 1] = arguments[_key4]; + } + + var deco = function deco(asKey) { + return function (target, key, index) { + var params = getDecoratorDependencies(target, 'newInstance'); + params[index] = NewInstance.of.apply(NewInstance, [params[index]].concat(dynamicDependencies)); + if (!!asKey) { + params[index].as(asKey); + } + }; + }; + if (arguments.length >= 1) { + return deco(asKeyOrTarget); + } + return deco(); + } + + function invoker(value) { + return function (target) { + _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.invoker, value, target); + }; + } + + function invokeAsFactory(potentialTarget) { + var deco = function deco(target) { + _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.invoker, FactoryInvoker.instance, target); + }; + + return potentialTarget ? deco(potentialTarget) : deco; + } + + var FactoryInvoker = exports.FactoryInvoker = function () { + function FactoryInvoker() { + + } + + FactoryInvoker.prototype.invoke = function invoke(container, fn, dependencies) { + var i = dependencies.length; + var args = new Array(i); + + while (i--) { + args[i] = container.get(dependencies[i]); + } + + return fn.apply(undefined, args); + }; + + FactoryInvoker.prototype.invokeWithDynamicDependencies = function invokeWithDynamicDependencies(container, fn, staticDependencies, dynamicDependencies) { + var i = staticDependencies.length; + var args = new Array(i); + + while (i--) { + args[i] = container.get(staticDependencies[i]); + } + + if (dynamicDependencies !== undefined) { + args = args.concat(dynamicDependencies); + } + + return fn.apply(undefined, args); + }; + + return FactoryInvoker; + }(); + + FactoryInvoker.instance = new FactoryInvoker(); + + function registration(value) { + return function (target) { + _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.registration, value, target); + }; + } + + function transient(key) { + return registration(new TransientRegistration(key)); + } + + function singleton(keyOrRegisterInChild) { + var registerInChild = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + + return registration(new SingletonRegistration(keyOrRegisterInChild, registerInChild)); + } + + var TransientRegistration = exports.TransientRegistration = function () { + function TransientRegistration(key) { + + + this._key = key; + } + + TransientRegistration.prototype.registerResolver = function registerResolver(container, key, fn) { + return container.registerTransient(this._key || key, fn); + }; + + return TransientRegistration; + }(); + + var SingletonRegistration = exports.SingletonRegistration = function () { + function SingletonRegistration(keyOrRegisterInChild) { + var registerInChild = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + + + + if (typeof keyOrRegisterInChild === 'boolean') { + this._registerInChild = keyOrRegisterInChild; + } else { + this._key = keyOrRegisterInChild; + this._registerInChild = registerInChild; + } + } + + SingletonRegistration.prototype.registerResolver = function registerResolver(container, key, fn) { + return this._registerInChild ? container.registerSingleton(this._key || key, fn) : container.root.registerSingleton(this._key || key, fn); + }; + + return SingletonRegistration; + }(); + + function validateKey(key) { + if (key === null || key === undefined) { + throw new Error('key/value cannot be null or undefined. Are you trying to inject/register something that doesn\'t exist with DI?'); + } + } + var _emptyParameters = exports._emptyParameters = Object.freeze([]); + + _aureliaMetadata.metadata.registration = 'aurelia:registration'; + _aureliaMetadata.metadata.invoker = 'aurelia:invoker'; + + var resolverDecorates = resolver.decorates; + + var InvocationHandler = exports.InvocationHandler = function () { + function InvocationHandler(fn, invoker, dependencies) { + + + this.fn = fn; + this.invoker = invoker; + this.dependencies = dependencies; + } + + InvocationHandler.prototype.invoke = function invoke(container, dynamicDependencies) { + return dynamicDependencies !== undefined ? this.invoker.invokeWithDynamicDependencies(container, this.fn, this.dependencies, dynamicDependencies) : this.invoker.invoke(container, this.fn, this.dependencies); + }; + + return InvocationHandler; + }(); + + function invokeWithDynamicDependencies(container, fn, staticDependencies, dynamicDependencies) { + var i = staticDependencies.length; + var args = new Array(i); + + while (i--) { + args[i] = container.get(staticDependencies[i]); + } + + if (dynamicDependencies !== undefined) { + args = args.concat(dynamicDependencies); + } + + return Reflect.construct(fn, args); + } + + var classInvokers = (_classInvokers = {}, _classInvokers[0] = { + invoke: function invoke(container, Type) { + return new Type(); + }, + + invokeWithDynamicDependencies: invokeWithDynamicDependencies + }, _classInvokers[1] = { + invoke: function invoke(container, Type, deps) { + return new Type(container.get(deps[0])); + }, + + invokeWithDynamicDependencies: invokeWithDynamicDependencies + }, _classInvokers[2] = { + invoke: function invoke(container, Type, deps) { + return new Type(container.get(deps[0]), container.get(deps[1])); + }, + + invokeWithDynamicDependencies: invokeWithDynamicDependencies + }, _classInvokers[3] = { + invoke: function invoke(container, Type, deps) { + return new Type(container.get(deps[0]), container.get(deps[1]), container.get(deps[2])); + }, + + invokeWithDynamicDependencies: invokeWithDynamicDependencies + }, _classInvokers[4] = { + invoke: function invoke(container, Type, deps) { + return new Type(container.get(deps[0]), container.get(deps[1]), container.get(deps[2]), container.get(deps[3])); + }, + + invokeWithDynamicDependencies: invokeWithDynamicDependencies + }, _classInvokers[5] = { + invoke: function invoke(container, Type, deps) { + return new Type(container.get(deps[0]), container.get(deps[1]), container.get(deps[2]), container.get(deps[3]), container.get(deps[4])); + }, + + invokeWithDynamicDependencies: invokeWithDynamicDependencies + }, _classInvokers.fallback = { + invoke: invokeWithDynamicDependencies, + invokeWithDynamicDependencies: invokeWithDynamicDependencies + }, _classInvokers); + + function getDependencies(f) { + if (!f.hasOwnProperty('inject')) { + return []; + } + + if (typeof f.inject === 'function') { + return f.inject(); + } + + return f.inject; + } + + var Container = exports.Container = function () { + function Container(configuration) { + + + if (configuration === undefined) { + configuration = {}; + } + + this._configuration = configuration; + this._onHandlerCreated = configuration.onHandlerCreated; + this._handlers = configuration.handlers || (configuration.handlers = new Map()); + this._resolvers = new Map(); + this.root = this; + this.parent = null; + } + + Container.prototype.makeGlobal = function makeGlobal() { + Container.instance = this; + return this; + }; + + Container.prototype.setHandlerCreatedCallback = function setHandlerCreatedCallback(onHandlerCreated) { + this._onHandlerCreated = onHandlerCreated; + this._configuration.onHandlerCreated = onHandlerCreated; + }; + + Container.prototype.registerInstance = function registerInstance(key, instance) { + return this.registerResolver(key, new StrategyResolver(0, instance === undefined ? key : instance)); + }; + + Container.prototype.registerSingleton = function registerSingleton(key, fn) { + return this.registerResolver(key, new StrategyResolver(1, fn === undefined ? key : fn)); + }; + + Container.prototype.registerTransient = function registerTransient(key, fn) { + return this.registerResolver(key, new StrategyResolver(2, fn === undefined ? key : fn)); + }; + + Container.prototype.registerHandler = function registerHandler(key, handler) { + return this.registerResolver(key, new StrategyResolver(3, handler)); + }; + + Container.prototype.registerAlias = function registerAlias(originalKey, aliasKey) { + return this.registerResolver(aliasKey, new StrategyResolver(5, originalKey)); + }; + + Container.prototype.registerResolver = function registerResolver(key, resolver) { + validateKey(key); + + var allResolvers = this._resolvers; + var result = allResolvers.get(key); + + if (result === undefined) { + allResolvers.set(key, resolver); + } else if (result.strategy === 4) { + result.state.push(resolver); + } else { + allResolvers.set(key, new StrategyResolver(4, [result, resolver])); + } + + return resolver; + }; + + Container.prototype.autoRegister = function autoRegister(key, fn) { + fn = fn === undefined ? key : fn; + + if (typeof fn === 'function') { + var _registration = _aureliaMetadata.metadata.get(_aureliaMetadata.metadata.registration, fn); + + if (_registration === undefined) { + return this.registerResolver(key, new StrategyResolver(1, fn)); + } + + return _registration.registerResolver(this, key, fn); + } + + return this.registerResolver(key, new StrategyResolver(0, fn)); + }; + + Container.prototype.autoRegisterAll = function autoRegisterAll(fns) { + var i = fns.length; + while (i--) { + this.autoRegister(fns[i]); + } + }; + + Container.prototype.unregister = function unregister(key) { + this._resolvers.delete(key); + }; + + Container.prototype.hasResolver = function hasResolver(key) { + var checkParent = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + + validateKey(key); + + return this._resolvers.has(key) || checkParent && this.parent !== null && this.parent.hasResolver(key, checkParent); + }; + + Container.prototype.get = function get(key) { + validateKey(key); + + if (key === Container) { + return this; + } + + if (resolverDecorates(key)) { + return key.get(this, key); + } + + var resolver = this._resolvers.get(key); + + if (resolver === undefined) { + if (this.parent === null) { + return this.autoRegister(key).get(this, key); + } + + return this.parent._get(key); + } + + return resolver.get(this, key); + }; + + Container.prototype._get = function _get(key) { + var resolver = this._resolvers.get(key); + + if (resolver === undefined) { + if (this.parent === null) { + return this.autoRegister(key).get(this, key); + } + + return this.parent._get(key); + } + + return resolver.get(this, key); + }; + + Container.prototype.getAll = function getAll(key) { + validateKey(key); + + var resolver = this._resolvers.get(key); + + if (resolver === undefined) { + if (this.parent === null) { + return _emptyParameters; + } + + return this.parent.getAll(key); + } + + if (resolver.strategy === 4) { + var state = resolver.state; + var i = state.length; + var results = new Array(i); + + while (i--) { + results[i] = state[i].get(this, key); + } + + return results; + } + + return [resolver.get(this, key)]; + }; + + Container.prototype.createChild = function createChild() { + var child = new Container(this._configuration); + child.root = this.root; + child.parent = this; + return child; + }; + + Container.prototype.invoke = function invoke(fn, dynamicDependencies) { + try { + var _handler = this._handlers.get(fn); + + if (_handler === undefined) { + _handler = this._createInvocationHandler(fn); + this._handlers.set(fn, _handler); + } + + return _handler.invoke(this, dynamicDependencies); + } catch (e) { + throw new _aureliaPal.AggregateError('Error invoking ' + fn.name + '. Check the inner error for details.', e, true); + } + }; + + Container.prototype._createInvocationHandler = function _createInvocationHandler(fn) { + var dependencies = void 0; + + if (fn.inject === undefined) { + dependencies = _aureliaMetadata.metadata.getOwn(_aureliaMetadata.metadata.paramTypes, fn) || _emptyParameters; + } else { + dependencies = []; + var ctor = fn; + while (typeof ctor === 'function') { + var _dependencies; + + (_dependencies = dependencies).push.apply(_dependencies, getDependencies(ctor)); + ctor = Object.getPrototypeOf(ctor); + } + } + + var invoker = _aureliaMetadata.metadata.getOwn(_aureliaMetadata.metadata.invoker, fn) || classInvokers[dependencies.length] || classInvokers.fallback; + + var handler = new InvocationHandler(fn, invoker, dependencies); + return this._onHandlerCreated !== undefined ? this._onHandlerCreated(handler) : handler; + }; + + return Container; + }(); + + function autoinject(potentialTarget) { + var deco = function deco(target) { + var previousInject = target.inject; + var autoInject = _aureliaMetadata.metadata.getOwn(_aureliaMetadata.metadata.paramTypes, target) || _emptyParameters; + if (!previousInject) { + target.inject = autoInject; + } else { + for (var i = 0; i < autoInject.length; i++) { + if (previousInject[i] && previousInject[i] !== autoInject[i]) { + var prevIndex = previousInject.indexOf(autoInject[i]); + if (prevIndex > -1) { + previousInject.splice(prevIndex, 1); + } + previousInject.splice(prevIndex > -1 && prevIndex < i ? i - 1 : i, 0, autoInject[i]); + } else if (!previousInject[i]) { + previousInject[i] = autoInject[i]; + } + } + } + }; + + return potentialTarget ? deco(potentialTarget) : deco; + } + + function inject() { + for (var _len5 = arguments.length, rest = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + rest[_key5] = arguments[_key5]; + } + + return function (target, key, descriptor) { + if (typeof descriptor === 'number' && rest.length === 1) { + var params = target.inject; + if (typeof params === 'function') { + throw new Error('Decorator inject cannot be used with "inject()". Please use an array instead.'); + } + if (!params) { + params = _aureliaMetadata.metadata.getOwn(_aureliaMetadata.metadata.paramTypes, target).slice(); + target.inject = params; + } + params[descriptor] = rest[0]; + return; + } + + if (descriptor) { + var _fn = descriptor.value; + _fn.inject = rest; + } else { + target.inject = rest; + } + }; + } +}); +define('aurelia-binding',['exports', 'aurelia-logging', 'aurelia-pal', 'aurelia-task-queue', 'aurelia-metadata'], function (exports, _aureliaLogging, _aureliaPal, _aureliaTaskQueue, _aureliaMetadata) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.getSetObserver = exports.BindingEngine = exports.NameExpression = exports.Listener = exports.ListenerExpression = exports.BindingBehaviorResource = exports.ValueConverterResource = exports.Call = exports.CallExpression = exports.Binding = exports.BindingExpression = exports.ObjectObservationAdapter = exports.ObserverLocator = exports.SVGAnalyzer = exports.presentationAttributes = exports.presentationElements = exports.elements = exports.ComputedExpression = exports.ClassObserver = exports.SelectValueObserver = exports.CheckedObserver = exports.ValueAttributeObserver = exports.StyleObserver = exports.DataAttributeObserver = exports.dataAttributeAccessor = exports.XLinkAttributeObserver = exports.SetterObserver = exports.PrimitiveObserver = exports.propertyAccessor = exports.DirtyCheckProperty = exports.DirtyChecker = exports.EventManager = exports.getMapObserver = exports.ParserImplementation = exports.Parser = exports.Scanner = exports.Lexer = exports.Token = exports.bindingMode = exports.ExpressionCloner = exports.Unparser = exports.LiteralObject = exports.LiteralArray = exports.LiteralString = exports.LiteralPrimitive = exports.PrefixNot = exports.Binary = exports.CallFunction = exports.CallMember = exports.CallScope = exports.AccessKeyed = exports.AccessMember = exports.AccessScope = exports.AccessThis = exports.Conditional = exports.Assign = exports.ValueConverter = exports.BindingBehavior = exports.Chain = exports.Expression = exports.getArrayObserver = exports.CollectionLengthObserver = exports.ModifyCollectionObserver = exports.ExpressionObserver = exports.sourceContext = undefined; + exports.camelCase = camelCase; + exports.createOverrideContext = createOverrideContext; + exports.getContextFor = getContextFor; + exports.createScopeForTest = createScopeForTest; + exports.connectable = connectable; + exports.enqueueBindingConnect = enqueueBindingConnect; + exports.subscriberCollection = subscriberCollection; + exports.calcSplices = calcSplices; + exports.mergeSplice = mergeSplice; + exports.projectArraySplices = projectArraySplices; + exports.getChangeRecords = getChangeRecords; + exports.cloneExpression = cloneExpression; + exports.hasDeclaredDependencies = hasDeclaredDependencies; + exports.declarePropertyDependencies = declarePropertyDependencies; + exports.computedFrom = computedFrom; + exports.createComputedObserver = createComputedObserver; + exports.valueConverter = valueConverter; + exports.bindingBehavior = bindingBehavior; + exports.observable = observable; + + var LogManager = _interopRequireWildcard(_aureliaLogging); + + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + + newObj.default = obj; + return newObj; + } + } + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; + }; + + var _createClass = function () { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + return function (Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps); + if (staticProps) defineProperties(Constructor, staticProps); + return Constructor; + }; + }(); + + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + + + + var _dec, _dec2, _class, _dec3, _class2, _dec4, _class3, _dec5, _class5, _dec6, _class7, _dec7, _class8, _dec8, _class9, _dec9, _class10, _class11, _temp, _dec10, _class12, _class13, _temp2; + + var map = Object.create(null); + + function camelCase(name) { + if (name in map) { + return map[name]; + } + var result = name.charAt(0).toLowerCase() + name.slice(1).replace(/[_.-](\w|$)/g, function (_, x) { + return x.toUpperCase(); + }); + map[name] = result; + return result; + } + + function createOverrideContext(bindingContext, parentOverrideContext) { + return { + bindingContext: bindingContext, + parentOverrideContext: parentOverrideContext || null + }; + } + + function getContextFor(name, scope, ancestor) { + var oc = scope.overrideContext; + + if (ancestor) { + while (ancestor && oc) { + ancestor--; + oc = oc.parentOverrideContext; + } + if (ancestor || !oc) { + return undefined; + } + return name in oc ? oc : oc.bindingContext; + } + + while (oc && !(name in oc) && !(oc.bindingContext && name in oc.bindingContext)) { + oc = oc.parentOverrideContext; + } + if (oc) { + return name in oc ? oc : oc.bindingContext; + } + + return scope.bindingContext || scope.overrideContext; + } + + function createScopeForTest(bindingContext, parentBindingContext) { + if (parentBindingContext) { + return { + bindingContext: bindingContext, + overrideContext: createOverrideContext(bindingContext, createOverrideContext(parentBindingContext)) + }; + } + return { + bindingContext: bindingContext, + overrideContext: createOverrideContext(bindingContext) + }; + } + + var sourceContext = exports.sourceContext = 'Binding:source'; + var slotNames = []; + var versionSlotNames = []; + + for (var i = 0; i < 100; i++) { + slotNames.push('_observer' + i); + versionSlotNames.push('_observerVersion' + i); + } + + function addObserver(observer) { + var observerSlots = this._observerSlots === undefined ? 0 : this._observerSlots; + var i = observerSlots; + while (i-- && this[slotNames[i]] !== observer) {} + + if (i === -1) { + i = 0; + while (this[slotNames[i]]) { + i++; + } + this[slotNames[i]] = observer; + observer.subscribe(sourceContext, this); + + if (i === observerSlots) { + this._observerSlots = i + 1; + } + } + + if (this._version === undefined) { + this._version = 0; + } + this[versionSlotNames[i]] = this._version; + } + + function observeProperty(obj, propertyName) { + var observer = this.observerLocator.getObserver(obj, propertyName); + addObserver.call(this, observer); + } + + function observeArray(array) { + var observer = this.observerLocator.getArrayObserver(array); + addObserver.call(this, observer); + } + + function unobserve(all) { + var i = this._observerSlots; + while (i--) { + if (all || this[versionSlotNames[i]] !== this._version) { + var observer = this[slotNames[i]]; + this[slotNames[i]] = null; + if (observer) { + observer.unsubscribe(sourceContext, this); + } + } + } + } + + function connectable() { + return function (target) { + target.prototype.observeProperty = observeProperty; + target.prototype.observeArray = observeArray; + target.prototype.unobserve = unobserve; + target.prototype.addObserver = addObserver; + }; + } + + var bindings = new Map(); + var minimumImmediate = 100; + var frameBudget = 15; + + var isFlushRequested = false; + var immediate = 0; + + function flush(animationFrameStart) { + var i = 0; + var keys = bindings.keys(); + var item = void 0; + + while (item = keys.next()) { + if (item.done) { + break; + } + + var binding = item.value; + bindings.delete(binding); + binding.connect(true); + i++; + + if (i % 100 === 0 && _aureliaPal.PLATFORM.performance.now() - animationFrameStart > frameBudget) { + break; + } + } + + if (bindings.size) { + _aureliaPal.PLATFORM.requestAnimationFrame(flush); + } else { + isFlushRequested = false; + immediate = 0; + } + } + + function enqueueBindingConnect(binding) { + if (immediate < minimumImmediate) { + immediate++; + binding.connect(false); + } else { + bindings.set(binding); + } + if (!isFlushRequested) { + isFlushRequested = true; + _aureliaPal.PLATFORM.requestAnimationFrame(flush); + } + } + + function addSubscriber(context, callable) { + if (this.hasSubscriber(context, callable)) { + return false; + } + if (!this._context0) { + this._context0 = context; + this._callable0 = callable; + return true; + } + if (!this._context1) { + this._context1 = context; + this._callable1 = callable; + return true; + } + if (!this._context2) { + this._context2 = context; + this._callable2 = callable; + return true; + } + if (!this._contextsRest) { + this._contextsRest = [context]; + this._callablesRest = [callable]; + return true; + } + this._contextsRest.push(context); + this._callablesRest.push(callable); + return true; + } + + function removeSubscriber(context, callable) { + if (this._context0 === context && this._callable0 === callable) { + this._context0 = null; + this._callable0 = null; + return true; + } + if (this._context1 === context && this._callable1 === callable) { + this._context1 = null; + this._callable1 = null; + return true; + } + if (this._context2 === context && this._callable2 === callable) { + this._context2 = null; + this._callable2 = null; + return true; + } + var rest = this._contextsRest; + var index = void 0; + if (!rest || !rest.length || (index = rest.indexOf(context)) === -1 || this._callablesRest[index] !== callable) { + return false; + } + rest.splice(index, 1); + this._callablesRest.splice(index, 1); + return true; + } + + var arrayPool1 = []; + var arrayPool2 = []; + var poolUtilization = []; + + function callSubscribers(newValue, oldValue) { + var context0 = this._context0; + var callable0 = this._callable0; + var context1 = this._context1; + var callable1 = this._callable1; + var context2 = this._context2; + var callable2 = this._callable2; + var length = this._contextsRest ? this._contextsRest.length : 0; + var contextsRest = void 0; + var callablesRest = void 0; + var poolIndex = void 0; + var i = void 0; + if (length) { + poolIndex = poolUtilization.length; + while (poolIndex-- && poolUtilization[poolIndex]) {} + if (poolIndex < 0) { + poolIndex = poolUtilization.length; + contextsRest = []; + callablesRest = []; + poolUtilization.push(true); + arrayPool1.push(contextsRest); + arrayPool2.push(callablesRest); + } else { + poolUtilization[poolIndex] = true; + contextsRest = arrayPool1[poolIndex]; + callablesRest = arrayPool2[poolIndex]; + } + + i = length; + while (i--) { + contextsRest[i] = this._contextsRest[i]; + callablesRest[i] = this._callablesRest[i]; + } + } + + if (context0) { + if (callable0) { + callable0.call(context0, newValue, oldValue); + } else { + context0(newValue, oldValue); + } + } + if (context1) { + if (callable1) { + callable1.call(context1, newValue, oldValue); + } else { + context1(newValue, oldValue); + } + } + if (context2) { + if (callable2) { + callable2.call(context2, newValue, oldValue); + } else { + context2(newValue, oldValue); + } + } + if (length) { + for (i = 0; i < length; i++) { + var callable = callablesRest[i]; + var context = contextsRest[i]; + if (callable) { + callable.call(context, newValue, oldValue); + } else { + context(newValue, oldValue); + } + contextsRest[i] = null; + callablesRest[i] = null; + } + poolUtilization[poolIndex] = false; + } + } + + function hasSubscribers() { + return !!(this._context0 || this._context1 || this._context2 || this._contextsRest && this._contextsRest.length); + } + + function hasSubscriber(context, callable) { + var has = this._context0 === context && this._callable0 === callable || this._context1 === context && this._callable1 === callable || this._context2 === context && this._callable2 === callable; + if (has) { + return true; + } + var index = void 0; + var contexts = this._contextsRest; + if (!contexts || (index = contexts.length) === 0) { + return false; + } + var callables = this._callablesRest; + while (index--) { + if (contexts[index] === context && callables[index] === callable) { + return true; + } + } + return false; + } + + function subscriberCollection() { + return function (target) { + target.prototype.addSubscriber = addSubscriber; + target.prototype.removeSubscriber = removeSubscriber; + target.prototype.callSubscribers = callSubscribers; + target.prototype.hasSubscribers = hasSubscribers; + target.prototype.hasSubscriber = hasSubscriber; + }; + } + + var ExpressionObserver = exports.ExpressionObserver = (_dec = connectable(), _dec2 = subscriberCollection(), _dec(_class = _dec2(_class = function () { + function ExpressionObserver(scope, expression, observerLocator, lookupFunctions) { + + + this.scope = scope; + this.expression = expression; + this.observerLocator = observerLocator; + this.lookupFunctions = lookupFunctions; + } + + ExpressionObserver.prototype.getValue = function getValue() { + return this.expression.evaluate(this.scope, this.lookupFunctions); + }; + + ExpressionObserver.prototype.setValue = function setValue(newValue) { + this.expression.assign(this.scope, newValue); + }; + + ExpressionObserver.prototype.subscribe = function subscribe(context, callable) { + var _this = this; + + if (!this.hasSubscribers()) { + this.oldValue = this.expression.evaluate(this.scope, this.lookupFunctions); + this.expression.connect(this, this.scope); + } + this.addSubscriber(context, callable); + if (arguments.length === 1 && context instanceof Function) { + return { + dispose: function dispose() { + _this.unsubscribe(context, callable); + } + }; + } + }; + + ExpressionObserver.prototype.unsubscribe = function unsubscribe(context, callable) { + if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) { + this.unobserve(true); + this.oldValue = undefined; + } + }; + + ExpressionObserver.prototype.call = function call() { + var newValue = this.expression.evaluate(this.scope, this.lookupFunctions); + var oldValue = this.oldValue; + if (newValue !== oldValue) { + this.oldValue = newValue; + this.callSubscribers(newValue, oldValue); + } + this._version++; + this.expression.connect(this, this.scope); + this.unobserve(false); + }; + + return ExpressionObserver; + }()) || _class) || _class); + + + function isIndex(s) { + return +s === s >>> 0; + } + + function toNumber(s) { + return +s; + } + + function newSplice(index, removed, addedCount) { + return { + index: index, + removed: removed, + addedCount: addedCount + }; + } + + var EDIT_LEAVE = 0; + var EDIT_UPDATE = 1; + var EDIT_ADD = 2; + var EDIT_DELETE = 3; + + function ArraySplice() {} + + ArraySplice.prototype = { + calcEditDistances: function calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd) { + var rowCount = oldEnd - oldStart + 1; + var columnCount = currentEnd - currentStart + 1; + var distances = new Array(rowCount); + var north = void 0; + var west = void 0; + + for (var _i = 0; _i < rowCount; ++_i) { + distances[_i] = new Array(columnCount); + distances[_i][0] = _i; + } + + for (var j = 0; j < columnCount; ++j) { + distances[0][j] = j; + } + + for (var _i2 = 1; _i2 < rowCount; ++_i2) { + for (var _j = 1; _j < columnCount; ++_j) { + if (this.equals(current[currentStart + _j - 1], old[oldStart + _i2 - 1])) { + distances[_i2][_j] = distances[_i2 - 1][_j - 1]; + } else { + north = distances[_i2 - 1][_j] + 1; + west = distances[_i2][_j - 1] + 1; + distances[_i2][_j] = north < west ? north : west; + } + } + } + + return distances; + }, + + spliceOperationsFromEditDistances: function spliceOperationsFromEditDistances(distances) { + var i = distances.length - 1; + var j = distances[0].length - 1; + var current = distances[i][j]; + var edits = []; + while (i > 0 || j > 0) { + if (i === 0) { + edits.push(EDIT_ADD); + j--; + continue; + } + if (j === 0) { + edits.push(EDIT_DELETE); + i--; + continue; + } + var northWest = distances[i - 1][j - 1]; + var west = distances[i - 1][j]; + var north = distances[i][j - 1]; + + var min = void 0; + if (west < north) { + min = west < northWest ? west : northWest; + } else { + min = north < northWest ? north : northWest; + } + + if (min === northWest) { + if (northWest === current) { + edits.push(EDIT_LEAVE); + } else { + edits.push(EDIT_UPDATE); + current = northWest; + } + i--; + j--; + } else if (min === west) { + edits.push(EDIT_DELETE); + i--; + current = west; + } else { + edits.push(EDIT_ADD); + j--; + current = north; + } + } + + edits.reverse(); + return edits; + }, + + calcSplices: function calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd) { + var prefixCount = 0; + var suffixCount = 0; + + var minLength = Math.min(currentEnd - currentStart, oldEnd - oldStart); + if (currentStart === 0 && oldStart === 0) { + prefixCount = this.sharedPrefix(current, old, minLength); + } + + if (currentEnd === current.length && oldEnd === old.length) { + suffixCount = this.sharedSuffix(current, old, minLength - prefixCount); + } + + currentStart += prefixCount; + oldStart += prefixCount; + currentEnd -= suffixCount; + oldEnd -= suffixCount; + + if (currentEnd - currentStart === 0 && oldEnd - oldStart === 0) { + return []; + } + + if (currentStart === currentEnd) { + var _splice = newSplice(currentStart, [], 0); + while (oldStart < oldEnd) { + _splice.removed.push(old[oldStart++]); + } + + return [_splice]; + } else if (oldStart === oldEnd) { + return [newSplice(currentStart, [], currentEnd - currentStart)]; + } + + var ops = this.spliceOperationsFromEditDistances(this.calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd)); + + var splice = undefined; + var splices = []; + var index = currentStart; + var oldIndex = oldStart; + for (var _i3 = 0; _i3 < ops.length; ++_i3) { + switch (ops[_i3]) { + case EDIT_LEAVE: + if (splice) { + splices.push(splice); + splice = undefined; + } + + index++; + oldIndex++; + break; + case EDIT_UPDATE: + if (!splice) { + splice = newSplice(index, [], 0); + } + + splice.addedCount++; + index++; + + splice.removed.push(old[oldIndex]); + oldIndex++; + break; + case EDIT_ADD: + if (!splice) { + splice = newSplice(index, [], 0); + } + + splice.addedCount++; + index++; + break; + case EDIT_DELETE: + if (!splice) { + splice = newSplice(index, [], 0); + } + + splice.removed.push(old[oldIndex]); + oldIndex++; + break; + } + } + + if (splice) { + splices.push(splice); + } + return splices; + }, + + sharedPrefix: function sharedPrefix(current, old, searchLength) { + for (var _i4 = 0; _i4 < searchLength; ++_i4) { + if (!this.equals(current[_i4], old[_i4])) { + return _i4; + } + } + + return searchLength; + }, + + sharedSuffix: function sharedSuffix(current, old, searchLength) { + var index1 = current.length; + var index2 = old.length; + var count = 0; + while (count < searchLength && this.equals(current[--index1], old[--index2])) { + count++; + } + + return count; + }, + + calculateSplices: function calculateSplices(current, previous) { + return this.calcSplices(current, 0, current.length, previous, 0, previous.length); + }, + + equals: function equals(currentValue, previousValue) { + return currentValue === previousValue; + } + }; + + var arraySplice = new ArraySplice(); + + function calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd) { + return arraySplice.calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd); + } + + function intersect(start1, end1, start2, end2) { + if (end1 < start2 || end2 < start1) { + return -1; + } + + if (end1 === start2 || end2 === start1) { + return 0; + } + + if (start1 < start2) { + if (end1 < end2) { + return end1 - start2; + } + + return end2 - start2; + } + + if (end2 < end1) { + return end2 - start1; + } + + return end1 - start1; + } + + function mergeSplice(splices, index, removed, addedCount) { + var splice = newSplice(index, removed, addedCount); + + var inserted = false; + var insertionOffset = 0; + + for (var _i5 = 0; _i5 < splices.length; _i5++) { + var current = splices[_i5]; + current.index += insertionOffset; + + if (inserted) { + continue; + } + + var intersectCount = intersect(splice.index, splice.index + splice.removed.length, current.index, current.index + current.addedCount); + + if (intersectCount >= 0) { + + splices.splice(_i5, 1); + _i5--; + + insertionOffset -= current.addedCount - current.removed.length; + + splice.addedCount += current.addedCount - intersectCount; + var deleteCount = splice.removed.length + current.removed.length - intersectCount; + + if (!splice.addedCount && !deleteCount) { + inserted = true; + } else { + var currentRemoved = current.removed; + + if (splice.index < current.index) { + var prepend = splice.removed.slice(0, current.index - splice.index); + Array.prototype.push.apply(prepend, currentRemoved); + currentRemoved = prepend; + } + + if (splice.index + splice.removed.length > current.index + current.addedCount) { + var append = splice.removed.slice(current.index + current.addedCount - splice.index); + Array.prototype.push.apply(currentRemoved, append); + } + + splice.removed = currentRemoved; + if (current.index < splice.index) { + splice.index = current.index; + } + } + } else if (splice.index < current.index) { + + inserted = true; + + splices.splice(_i5, 0, splice); + _i5++; + + var offset = splice.addedCount - splice.removed.length; + current.index += offset; + insertionOffset += offset; + } + } + + if (!inserted) { + splices.push(splice); + } + } + + function createInitialSplices(array, changeRecords) { + var splices = []; + + for (var _i6 = 0; _i6 < changeRecords.length; _i6++) { + var record = changeRecords[_i6]; + switch (record.type) { + case 'splice': + mergeSplice(splices, record.index, record.removed.slice(), record.addedCount); + break; + case 'add': + case 'update': + case 'delete': + if (!isIndex(record.name)) { + continue; + } + + var index = toNumber(record.name); + if (index < 0) { + continue; + } + + mergeSplice(splices, index, [record.oldValue], record.type === 'delete' ? 0 : 1); + break; + default: + console.error('Unexpected record type: ' + JSON.stringify(record)); + break; + } + } + + return splices; + } + + function projectArraySplices(array, changeRecords) { + var splices = []; + + createInitialSplices(array, changeRecords).forEach(function (splice) { + if (splice.addedCount === 1 && splice.removed.length === 1) { + if (splice.removed[0] !== array[splice.index]) { + splices.push(splice); + } + + return; + } + + splices = splices.concat(calcSplices(array, splice.index, splice.index + splice.addedCount, splice.removed, 0, splice.removed.length)); + }); + + return splices; + } + + function newRecord(type, object, key, oldValue) { + return { + type: type, + object: object, + key: key, + oldValue: oldValue + }; + } + + function getChangeRecords(map) { + var entries = new Array(map.size); + var keys = map.keys(); + var i = 0; + var item = void 0; + + while (item = keys.next()) { + if (item.done) { + break; + } + + entries[i] = newRecord('added', map, item.value); + i++; + } + + return entries; + } + + var ModifyCollectionObserver = exports.ModifyCollectionObserver = (_dec3 = subscriberCollection(), _dec3(_class2 = function () { + function ModifyCollectionObserver(taskQueue, collection) { + + + this.taskQueue = taskQueue; + this.queued = false; + this.changeRecords = null; + this.oldCollection = null; + this.collection = collection; + this.lengthPropertyName = collection instanceof Map || collection instanceof Set ? 'size' : 'length'; + } + + ModifyCollectionObserver.prototype.subscribe = function subscribe(context, callable) { + this.addSubscriber(context, callable); + }; + + ModifyCollectionObserver.prototype.unsubscribe = function unsubscribe(context, callable) { + this.removeSubscriber(context, callable); + }; + + ModifyCollectionObserver.prototype.addChangeRecord = function addChangeRecord(changeRecord) { + if (!this.hasSubscribers() && !this.lengthObserver) { + return; + } + + if (changeRecord.type === 'splice') { + var index = changeRecord.index; + var arrayLength = changeRecord.object.length; + if (index > arrayLength) { + index = arrayLength - changeRecord.addedCount; + } else if (index < 0) { + index = arrayLength + changeRecord.removed.length + index - changeRecord.addedCount; + } + if (index < 0) { + index = 0; + } + changeRecord.index = index; + } + + if (this.changeRecords === null) { + this.changeRecords = [changeRecord]; + } else { + this.changeRecords.push(changeRecord); + } + + if (!this.queued) { + this.queued = true; + this.taskQueue.queueMicroTask(this); + } + }; + + ModifyCollectionObserver.prototype.flushChangeRecords = function flushChangeRecords() { + if (this.changeRecords && this.changeRecords.length || this.oldCollection) { + this.call(); + } + }; + + ModifyCollectionObserver.prototype.reset = function reset(oldCollection) { + this.oldCollection = oldCollection; + + if (this.hasSubscribers() && !this.queued) { + this.queued = true; + this.taskQueue.queueMicroTask(this); + } + }; + + ModifyCollectionObserver.prototype.getLengthObserver = function getLengthObserver() { + return this.lengthObserver || (this.lengthObserver = new CollectionLengthObserver(this.collection)); + }; + + ModifyCollectionObserver.prototype.call = function call() { + var changeRecords = this.changeRecords; + var oldCollection = this.oldCollection; + var records = void 0; + + this.queued = false; + this.changeRecords = []; + this.oldCollection = null; + + if (this.hasSubscribers()) { + if (oldCollection) { + if (this.collection instanceof Map || this.collection instanceof Set) { + records = getChangeRecords(oldCollection); + } else { + records = calcSplices(this.collection, 0, this.collection.length, oldCollection, 0, oldCollection.length); + } + } else { + if (this.collection instanceof Map || this.collection instanceof Set) { + records = changeRecords; + } else { + records = projectArraySplices(this.collection, changeRecords); + } + } + + this.callSubscribers(records); + } + + if (this.lengthObserver) { + this.lengthObserver.call(this.collection[this.lengthPropertyName]); + } + }; + + return ModifyCollectionObserver; + }()) || _class2); + var CollectionLengthObserver = exports.CollectionLengthObserver = (_dec4 = subscriberCollection(), _dec4(_class3 = function () { + function CollectionLengthObserver(collection) { + + + this.collection = collection; + this.lengthPropertyName = collection instanceof Map || collection instanceof Set ? 'size' : 'length'; + this.currentValue = collection[this.lengthPropertyName]; + } + + CollectionLengthObserver.prototype.getValue = function getValue() { + return this.collection[this.lengthPropertyName]; + }; + + CollectionLengthObserver.prototype.setValue = function setValue(newValue) { + this.collection[this.lengthPropertyName] = newValue; + }; + + CollectionLengthObserver.prototype.subscribe = function subscribe(context, callable) { + this.addSubscriber(context, callable); + }; + + CollectionLengthObserver.prototype.unsubscribe = function unsubscribe(context, callable) { + this.removeSubscriber(context, callable); + }; + + CollectionLengthObserver.prototype.call = function call(newValue) { + var oldValue = this.currentValue; + this.callSubscribers(newValue, oldValue); + this.currentValue = newValue; + }; + + return CollectionLengthObserver; + }()) || _class3); + + var pop = Array.prototype.pop; + var push = Array.prototype.push; + var reverse = Array.prototype.reverse; + var shift = Array.prototype.shift; + var sort = Array.prototype.sort; + var splice = Array.prototype.splice; + var unshift = Array.prototype.unshift; + + Array.prototype.pop = function () { + var notEmpty = this.length > 0; + var methodCallResult = pop.apply(this, arguments); + if (notEmpty && this.__array_observer__ !== undefined) { + this.__array_observer__.addChangeRecord({ + type: 'delete', + object: this, + name: this.length, + oldValue: methodCallResult + }); + } + return methodCallResult; + }; + + Array.prototype.push = function () { + var methodCallResult = push.apply(this, arguments); + if (this.__array_observer__ !== undefined) { + this.__array_observer__.addChangeRecord({ + type: 'splice', + object: this, + index: this.length - arguments.length, + removed: [], + addedCount: arguments.length + }); + } + return methodCallResult; + }; + + Array.prototype.reverse = function () { + var oldArray = void 0; + if (this.__array_observer__ !== undefined) { + this.__array_observer__.flushChangeRecords(); + oldArray = this.slice(); + } + var methodCallResult = reverse.apply(this, arguments); + if (this.__array_observer__ !== undefined) { + this.__array_observer__.reset(oldArray); + } + return methodCallResult; + }; + + Array.prototype.shift = function () { + var notEmpty = this.length > 0; + var methodCallResult = shift.apply(this, arguments); + if (notEmpty && this.__array_observer__ !== undefined) { + this.__array_observer__.addChangeRecord({ + type: 'delete', + object: this, + name: 0, + oldValue: methodCallResult + }); + } + return methodCallResult; + }; + + Array.prototype.sort = function () { + var oldArray = void 0; + if (this.__array_observer__ !== undefined) { + this.__array_observer__.flushChangeRecords(); + oldArray = this.slice(); + } + var methodCallResult = sort.apply(this, arguments); + if (this.__array_observer__ !== undefined) { + this.__array_observer__.reset(oldArray); + } + return methodCallResult; + }; + + Array.prototype.splice = function () { + var methodCallResult = splice.apply(this, arguments); + if (this.__array_observer__ !== undefined) { + this.__array_observer__.addChangeRecord({ + type: 'splice', + object: this, + index: arguments[0], + removed: methodCallResult, + addedCount: arguments.length > 2 ? arguments.length - 2 : 0 + }); + } + return methodCallResult; + }; + + Array.prototype.unshift = function () { + var methodCallResult = unshift.apply(this, arguments); + if (this.__array_observer__ !== undefined) { + this.__array_observer__.addChangeRecord({ + type: 'splice', + object: this, + index: 0, + removed: [], + addedCount: arguments.length + }); + } + return methodCallResult; + }; + + function _getArrayObserver(taskQueue, array) { + return ModifyArrayObserver.for(taskQueue, array); + } + + exports.getArrayObserver = _getArrayObserver; + + var ModifyArrayObserver = function (_ModifyCollectionObse) { + _inherits(ModifyArrayObserver, _ModifyCollectionObse); + + function ModifyArrayObserver(taskQueue, array) { + + + return _possibleConstructorReturn(this, _ModifyCollectionObse.call(this, taskQueue, array)); + } + + ModifyArrayObserver.for = function _for(taskQueue, array) { + if (!('__array_observer__' in array)) { + Reflect.defineProperty(array, '__array_observer__', { + value: ModifyArrayObserver.create(taskQueue, array), + enumerable: false, configurable: false + }); + } + return array.__array_observer__; + }; + + ModifyArrayObserver.create = function create(taskQueue, array) { + return new ModifyArrayObserver(taskQueue, array); + }; + + return ModifyArrayObserver; + }(ModifyCollectionObserver); + + var Expression = exports.Expression = function () { + function Expression() { + + + this.isChain = false; + this.isAssignable = false; + } + + Expression.prototype.evaluate = function evaluate(scope, lookupFunctions, args) { + throw new Error('Binding expression "' + this + '" cannot be evaluated.'); + }; + + Expression.prototype.assign = function assign(scope, value, lookupFunctions) { + throw new Error('Binding expression "' + this + '" cannot be assigned to.'); + }; + + Expression.prototype.toString = function toString() { + return Unparser.unparse(this); + }; + + return Expression; + }(); + + var Chain = exports.Chain = function (_Expression) { + _inherits(Chain, _Expression); + + function Chain(expressions) { + + + var _this3 = _possibleConstructorReturn(this, _Expression.call(this)); + + _this3.expressions = expressions; + _this3.isChain = true; + return _this3; + } + + Chain.prototype.evaluate = function evaluate(scope, lookupFunctions) { + var result = void 0; + var expressions = this.expressions; + var last = void 0; + + for (var _i7 = 0, length = expressions.length; _i7 < length; ++_i7) { + last = expressions[_i7].evaluate(scope, lookupFunctions); + + if (last !== null) { + result = last; + } + } + + return result; + }; + + Chain.prototype.accept = function accept(visitor) { + return visitor.visitChain(this); + }; + + return Chain; + }(Expression); + + var BindingBehavior = exports.BindingBehavior = function (_Expression2) { + _inherits(BindingBehavior, _Expression2); + + function BindingBehavior(expression, name, args) { + + + var _this4 = _possibleConstructorReturn(this, _Expression2.call(this)); + + _this4.expression = expression; + _this4.name = name; + _this4.args = args; + return _this4; + } + + BindingBehavior.prototype.evaluate = function evaluate(scope, lookupFunctions) { + return this.expression.evaluate(scope, lookupFunctions); + }; + + BindingBehavior.prototype.assign = function assign(scope, value, lookupFunctions) { + return this.expression.assign(scope, value, lookupFunctions); + }; + + BindingBehavior.prototype.accept = function accept(visitor) { + return visitor.visitBindingBehavior(this); + }; + + BindingBehavior.prototype.connect = function connect(binding, scope) { + this.expression.connect(binding, scope); + }; + + BindingBehavior.prototype.bind = function bind(binding, scope, lookupFunctions) { + if (this.expression.expression && this.expression.bind) { + this.expression.bind(binding, scope, lookupFunctions); + } + var behavior = lookupFunctions.bindingBehaviors(this.name); + if (!behavior) { + throw new Error('No BindingBehavior named "' + this.name + '" was found!'); + } + var behaviorKey = 'behavior-' + this.name; + if (binding[behaviorKey]) { + throw new Error('A binding behavior named "' + this.name + '" has already been applied to "' + this.expression + '"'); + } + binding[behaviorKey] = behavior; + behavior.bind.apply(behavior, [binding, scope].concat(evalList(scope, this.args, binding.lookupFunctions))); + }; + + BindingBehavior.prototype.unbind = function unbind(binding, scope) { + var behaviorKey = 'behavior-' + this.name; + binding[behaviorKey].unbind(binding, scope); + binding[behaviorKey] = null; + if (this.expression.expression && this.expression.unbind) { + this.expression.unbind(binding, scope); + } + }; + + return BindingBehavior; + }(Expression); + + var ValueConverter = exports.ValueConverter = function (_Expression3) { + _inherits(ValueConverter, _Expression3); + + function ValueConverter(expression, name, args, allArgs) { + + + var _this5 = _possibleConstructorReturn(this, _Expression3.call(this)); + + _this5.expression = expression; + _this5.name = name; + _this5.args = args; + _this5.allArgs = allArgs; + return _this5; + } + + ValueConverter.prototype.evaluate = function evaluate(scope, lookupFunctions) { + var converter = lookupFunctions.valueConverters(this.name); + if (!converter) { + throw new Error('No ValueConverter named "' + this.name + '" was found!'); + } + + if ('toView' in converter) { + return converter.toView.apply(converter, evalList(scope, this.allArgs, lookupFunctions)); + } + + return this.allArgs[0].evaluate(scope, lookupFunctions); + }; + + ValueConverter.prototype.assign = function assign(scope, value, lookupFunctions) { + var converter = lookupFunctions.valueConverters(this.name); + if (!converter) { + throw new Error('No ValueConverter named "' + this.name + '" was found!'); + } + + if ('fromView' in converter) { + value = converter.fromView.apply(converter, [value].concat(evalList(scope, this.args, lookupFunctions))); + } + + return this.allArgs[0].assign(scope, value, lookupFunctions); + }; + + ValueConverter.prototype.accept = function accept(visitor) { + return visitor.visitValueConverter(this); + }; + + ValueConverter.prototype.connect = function connect(binding, scope) { + var expressions = this.allArgs; + var i = expressions.length; + while (i--) { + expressions[i].connect(binding, scope); + } + }; + + return ValueConverter; + }(Expression); + + var Assign = exports.Assign = function (_Expression4) { + _inherits(Assign, _Expression4); + + function Assign(target, value) { + + + var _this6 = _possibleConstructorReturn(this, _Expression4.call(this)); + + _this6.target = target; + _this6.value = value; + return _this6; + } + + Assign.prototype.evaluate = function evaluate(scope, lookupFunctions) { + return this.target.assign(scope, this.value.evaluate(scope, lookupFunctions)); + }; + + Assign.prototype.accept = function accept(vistor) { + vistor.visitAssign(this); + }; + + Assign.prototype.connect = function connect(binding, scope) {}; + + return Assign; + }(Expression); + + var Conditional = exports.Conditional = function (_Expression5) { + _inherits(Conditional, _Expression5); + + function Conditional(condition, yes, no) { + + + var _this7 = _possibleConstructorReturn(this, _Expression5.call(this)); + + _this7.condition = condition; + _this7.yes = yes; + _this7.no = no; + return _this7; + } + + Conditional.prototype.evaluate = function evaluate(scope, lookupFunctions) { + return !!this.condition.evaluate(scope) ? this.yes.evaluate(scope) : this.no.evaluate(scope); + }; + + Conditional.prototype.accept = function accept(visitor) { + return visitor.visitConditional(this); + }; + + Conditional.prototype.connect = function connect(binding, scope) { + this.condition.connect(binding, scope); + if (this.condition.evaluate(scope)) { + this.yes.connect(binding, scope); + } else { + this.no.connect(binding, scope); + } + }; + + return Conditional; + }(Expression); + + var AccessThis = exports.AccessThis = function (_Expression6) { + _inherits(AccessThis, _Expression6); + + function AccessThis(ancestor) { + + + var _this8 = _possibleConstructorReturn(this, _Expression6.call(this)); + + _this8.ancestor = ancestor; + return _this8; + } + + AccessThis.prototype.evaluate = function evaluate(scope, lookupFunctions) { + var oc = scope.overrideContext; + var i = this.ancestor; + while (i-- && oc) { + oc = oc.parentOverrideContext; + } + return i < 1 && oc ? oc.bindingContext : undefined; + }; + + AccessThis.prototype.accept = function accept(visitor) { + return visitor.visitAccessThis(this); + }; + + AccessThis.prototype.connect = function connect(binding, scope) {}; + + return AccessThis; + }(Expression); + + var AccessScope = exports.AccessScope = function (_Expression7) { + _inherits(AccessScope, _Expression7); + + function AccessScope(name, ancestor) { + + + var _this9 = _possibleConstructorReturn(this, _Expression7.call(this)); + + _this9.name = name; + _this9.ancestor = ancestor; + _this9.isAssignable = true; + return _this9; + } + + AccessScope.prototype.evaluate = function evaluate(scope, lookupFunctions) { + var context = getContextFor(this.name, scope, this.ancestor); + return context[this.name]; + }; + + AccessScope.prototype.assign = function assign(scope, value) { + var context = getContextFor(this.name, scope, this.ancestor); + return context ? context[this.name] = value : undefined; + }; + + AccessScope.prototype.accept = function accept(visitor) { + return visitor.visitAccessScope(this); + }; + + AccessScope.prototype.connect = function connect(binding, scope) { + var context = getContextFor(this.name, scope, this.ancestor); + binding.observeProperty(context, this.name); + }; + + return AccessScope; + }(Expression); + + var AccessMember = exports.AccessMember = function (_Expression8) { + _inherits(AccessMember, _Expression8); + + function AccessMember(object, name) { + + + var _this10 = _possibleConstructorReturn(this, _Expression8.call(this)); + + _this10.object = object; + _this10.name = name; + _this10.isAssignable = true; + return _this10; + } + + AccessMember.prototype.evaluate = function evaluate(scope, lookupFunctions) { + var instance = this.object.evaluate(scope, lookupFunctions); + return instance === null || instance === undefined ? instance : instance[this.name]; + }; + + AccessMember.prototype.assign = function assign(scope, value) { + var instance = this.object.evaluate(scope); + + if (instance === null || instance === undefined) { + instance = {}; + this.object.assign(scope, instance); + } + + instance[this.name] = value; + return value; + }; + + AccessMember.prototype.accept = function accept(visitor) { + return visitor.visitAccessMember(this); + }; + + AccessMember.prototype.connect = function connect(binding, scope) { + this.object.connect(binding, scope); + var obj = this.object.evaluate(scope); + if (obj) { + binding.observeProperty(obj, this.name); + } + }; + + return AccessMember; + }(Expression); + + var AccessKeyed = exports.AccessKeyed = function (_Expression9) { + _inherits(AccessKeyed, _Expression9); + + function AccessKeyed(object, key) { + + + var _this11 = _possibleConstructorReturn(this, _Expression9.call(this)); + + _this11.object = object; + _this11.key = key; + _this11.isAssignable = true; + return _this11; + } + + AccessKeyed.prototype.evaluate = function evaluate(scope, lookupFunctions) { + var instance = this.object.evaluate(scope, lookupFunctions); + var lookup = this.key.evaluate(scope, lookupFunctions); + return getKeyed(instance, lookup); + }; + + AccessKeyed.prototype.assign = function assign(scope, value) { + var instance = this.object.evaluate(scope); + var lookup = this.key.evaluate(scope); + return setKeyed(instance, lookup, value); + }; + + AccessKeyed.prototype.accept = function accept(visitor) { + return visitor.visitAccessKeyed(this); + }; + + AccessKeyed.prototype.connect = function connect(binding, scope) { + this.object.connect(binding, scope); + var obj = this.object.evaluate(scope); + if (obj instanceof Object) { + this.key.connect(binding, scope); + var key = this.key.evaluate(scope); + + if (key !== null && key !== undefined && !(Array.isArray(obj) && typeof key === 'number')) { + binding.observeProperty(obj, key); + } + } + }; + + return AccessKeyed; + }(Expression); + + var CallScope = exports.CallScope = function (_Expression10) { + _inherits(CallScope, _Expression10); + + function CallScope(name, args, ancestor) { + + + var _this12 = _possibleConstructorReturn(this, _Expression10.call(this)); + + _this12.name = name; + _this12.args = args; + _this12.ancestor = ancestor; + return _this12; + } + + CallScope.prototype.evaluate = function evaluate(scope, lookupFunctions, mustEvaluate) { + var args = evalList(scope, this.args, lookupFunctions); + var context = getContextFor(this.name, scope, this.ancestor); + var func = getFunction(context, this.name, mustEvaluate); + if (func) { + return func.apply(context, args); + } + return undefined; + }; + + CallScope.prototype.accept = function accept(visitor) { + return visitor.visitCallScope(this); + }; + + CallScope.prototype.connect = function connect(binding, scope) { + var args = this.args; + var i = args.length; + while (i--) { + args[i].connect(binding, scope); + } + }; + + return CallScope; + }(Expression); + + var CallMember = exports.CallMember = function (_Expression11) { + _inherits(CallMember, _Expression11); + + function CallMember(object, name, args) { + + + var _this13 = _possibleConstructorReturn(this, _Expression11.call(this)); + + _this13.object = object; + _this13.name = name; + _this13.args = args; + return _this13; + } + + CallMember.prototype.evaluate = function evaluate(scope, lookupFunctions, mustEvaluate) { + var instance = this.object.evaluate(scope, lookupFunctions); + var args = evalList(scope, this.args, lookupFunctions); + var func = getFunction(instance, this.name, mustEvaluate); + if (func) { + return func.apply(instance, args); + } + return undefined; + }; + + CallMember.prototype.accept = function accept(visitor) { + return visitor.visitCallMember(this); + }; + + CallMember.prototype.connect = function connect(binding, scope) { + this.object.connect(binding, scope); + var obj = this.object.evaluate(scope); + if (getFunction(obj, this.name, false)) { + var args = this.args; + var _i8 = args.length; + while (_i8--) { + args[_i8].connect(binding, scope); + } + } + }; + + return CallMember; + }(Expression); + + var CallFunction = exports.CallFunction = function (_Expression12) { + _inherits(CallFunction, _Expression12); + + function CallFunction(func, args) { + + + var _this14 = _possibleConstructorReturn(this, _Expression12.call(this)); + + _this14.func = func; + _this14.args = args; + return _this14; + } + + CallFunction.prototype.evaluate = function evaluate(scope, lookupFunctions, mustEvaluate) { + var func = this.func.evaluate(scope, lookupFunctions); + if (typeof func === 'function') { + return func.apply(null, evalList(scope, this.args, lookupFunctions)); + } + if (!mustEvaluate && (func === null || func === undefined)) { + return undefined; + } + throw new Error(this.func + ' is not a function'); + }; + + CallFunction.prototype.accept = function accept(visitor) { + return visitor.visitCallFunction(this); + }; + + CallFunction.prototype.connect = function connect(binding, scope) { + this.func.connect(binding, scope); + var func = this.func.evaluate(scope); + if (typeof func === 'function') { + var args = this.args; + var _i9 = args.length; + while (_i9--) { + args[_i9].connect(binding, scope); + } + } + }; + + return CallFunction; + }(Expression); + + var Binary = exports.Binary = function (_Expression13) { + _inherits(Binary, _Expression13); + + function Binary(operation, left, right) { + + + var _this15 = _possibleConstructorReturn(this, _Expression13.call(this)); + + _this15.operation = operation; + _this15.left = left; + _this15.right = right; + return _this15; + } + + Binary.prototype.evaluate = function evaluate(scope, lookupFunctions) { + var left = this.left.evaluate(scope); + + switch (this.operation) { + case '&&': + return left && this.right.evaluate(scope); + case '||': + return left || this.right.evaluate(scope); + } + + var right = this.right.evaluate(scope); + + switch (this.operation) { + case '==': + return left == right; + case '===': + return left === right; + case '!=': + return left != right; + case '!==': + return left !== right; + } + + if (left === null || right === null || left === undefined || right === undefined) { + switch (this.operation) { + case '+': + if (left !== null && left !== undefined) return left; + if (right !== null && right !== undefined) return right; + return 0; + case '-': + if (left !== null && left !== undefined) return left; + if (right !== null && right !== undefined) return 0 - right; + return 0; + } + + return null; + } + + switch (this.operation) { + case '+': + return autoConvertAdd(left, right); + case '-': + return left - right; + case '*': + return left * right; + case '/': + return left / right; + case '%': + return left % right; + case '<': + return left < right; + case '>': + return left > right; + case '<=': + return left <= right; + case '>=': + return left >= right; + case '^': + return left ^ right; + } + + throw new Error('Internal error [' + this.operation + '] not handled'); + }; + + Binary.prototype.accept = function accept(visitor) { + return visitor.visitBinary(this); + }; + + Binary.prototype.connect = function connect(binding, scope) { + this.left.connect(binding, scope); + var left = this.left.evaluate(scope); + if (this.operation === '&&' && !left || this.operation === '||' && left) { + return; + } + this.right.connect(binding, scope); + }; + + return Binary; + }(Expression); + + var PrefixNot = exports.PrefixNot = function (_Expression14) { + _inherits(PrefixNot, _Expression14); + + function PrefixNot(operation, expression) { + + + var _this16 = _possibleConstructorReturn(this, _Expression14.call(this)); + + _this16.operation = operation; + _this16.expression = expression; + return _this16; + } + + PrefixNot.prototype.evaluate = function evaluate(scope, lookupFunctions) { + return !this.expression.evaluate(scope); + }; + + PrefixNot.prototype.accept = function accept(visitor) { + return visitor.visitPrefix(this); + }; + + PrefixNot.prototype.connect = function connect(binding, scope) { + this.expression.connect(binding, scope); + }; + + return PrefixNot; + }(Expression); + + var LiteralPrimitive = exports.LiteralPrimitive = function (_Expression15) { + _inherits(LiteralPrimitive, _Expression15); + + function LiteralPrimitive(value) { + + + var _this17 = _possibleConstructorReturn(this, _Expression15.call(this)); + + _this17.value = value; + return _this17; + } + + LiteralPrimitive.prototype.evaluate = function evaluate(scope, lookupFunctions) { + return this.value; + }; + + LiteralPrimitive.prototype.accept = function accept(visitor) { + return visitor.visitLiteralPrimitive(this); + }; + + LiteralPrimitive.prototype.connect = function connect(binding, scope) {}; + + return LiteralPrimitive; + }(Expression); + + var LiteralString = exports.LiteralString = function (_Expression16) { + _inherits(LiteralString, _Expression16); + + function LiteralString(value) { + + + var _this18 = _possibleConstructorReturn(this, _Expression16.call(this)); + + _this18.value = value; + return _this18; + } + + LiteralString.prototype.evaluate = function evaluate(scope, lookupFunctions) { + return this.value; + }; + + LiteralString.prototype.accept = function accept(visitor) { + return visitor.visitLiteralString(this); + }; + + LiteralString.prototype.connect = function connect(binding, scope) {}; + + return LiteralString; + }(Expression); + + var LiteralArray = exports.LiteralArray = function (_Expression17) { + _inherits(LiteralArray, _Expression17); + + function LiteralArray(elements) { + + + var _this19 = _possibleConstructorReturn(this, _Expression17.call(this)); + + _this19.elements = elements; + return _this19; + } + + LiteralArray.prototype.evaluate = function evaluate(scope, lookupFunctions) { + var elements = this.elements; + var result = []; + + for (var _i10 = 0, length = elements.length; _i10 < length; ++_i10) { + result[_i10] = elements[_i10].evaluate(scope, lookupFunctions); + } + + return result; + }; + + LiteralArray.prototype.accept = function accept(visitor) { + return visitor.visitLiteralArray(this); + }; + + LiteralArray.prototype.connect = function connect(binding, scope) { + var length = this.elements.length; + for (var _i11 = 0; _i11 < length; _i11++) { + this.elements[_i11].connect(binding, scope); + } + }; + + return LiteralArray; + }(Expression); + + var LiteralObject = exports.LiteralObject = function (_Expression18) { + _inherits(LiteralObject, _Expression18); + + function LiteralObject(keys, values) { + + + var _this20 = _possibleConstructorReturn(this, _Expression18.call(this)); + + _this20.keys = keys; + _this20.values = values; + return _this20; + } + + LiteralObject.prototype.evaluate = function evaluate(scope, lookupFunctions) { + var instance = {}; + var keys = this.keys; + var values = this.values; + + for (var _i12 = 0, length = keys.length; _i12 < length; ++_i12) { + instance[keys[_i12]] = values[_i12].evaluate(scope, lookupFunctions); + } + + return instance; + }; + + LiteralObject.prototype.accept = function accept(visitor) { + return visitor.visitLiteralObject(this); + }; + + LiteralObject.prototype.connect = function connect(binding, scope) { + var length = this.keys.length; + for (var _i13 = 0; _i13 < length; _i13++) { + this.values[_i13].connect(binding, scope); + } + }; + + return LiteralObject; + }(Expression); + + function evalList(scope, list, lookupFunctions) { + var length = list.length; + var result = []; + for (var _i14 = 0; _i14 < length; _i14++) { + result[_i14] = list[_i14].evaluate(scope, lookupFunctions); + } + return result; + } + + function autoConvertAdd(a, b) { + if (a !== null && b !== null) { + if (typeof a === 'string' && typeof b !== 'string') { + return a + b.toString(); + } + + if (typeof a !== 'string' && typeof b === 'string') { + return a.toString() + b; + } + + return a + b; + } + + if (a !== null) { + return a; + } + + if (b !== null) { + return b; + } + + return 0; + } + + function getFunction(obj, name, mustExist) { + var func = obj === null || obj === undefined ? null : obj[name]; + if (typeof func === 'function') { + return func; + } + if (!mustExist && (func === null || func === undefined)) { + return null; + } + throw new Error(name + ' is not a function'); + } + + function getKeyed(obj, key) { + if (Array.isArray(obj)) { + return obj[parseInt(key, 10)]; + } else if (obj) { + return obj[key]; + } else if (obj === null || obj === undefined) { + return undefined; + } + + return obj[key]; + } + + function setKeyed(obj, key, value) { + if (Array.isArray(obj)) { + var index = parseInt(key, 10); + + if (obj.length <= index) { + obj.length = index + 1; + } + + obj[index] = value; + } else { + obj[key] = value; + } + + return value; + } + + var Unparser = exports.Unparser = function () { + function Unparser(buffer) { + + + this.buffer = buffer; + } + + Unparser.unparse = function unparse(expression) { + var buffer = []; + var visitor = new Unparser(buffer); + + expression.accept(visitor); + + return buffer.join(''); + }; + + Unparser.prototype.write = function write(text) { + this.buffer.push(text); + }; + + Unparser.prototype.writeArgs = function writeArgs(args) { + this.write('('); + + for (var _i15 = 0, length = args.length; _i15 < length; ++_i15) { + if (_i15 !== 0) { + this.write(','); + } + + args[_i15].accept(this); + } + + this.write(')'); + }; + + Unparser.prototype.visitChain = function visitChain(chain) { + var expressions = chain.expressions; + + for (var _i16 = 0, length = expression.length; _i16 < length; ++_i16) { + if (_i16 !== 0) { + this.write(';'); + } + + expressions[_i16].accept(this); + } + }; + + Unparser.prototype.visitBindingBehavior = function visitBindingBehavior(behavior) { + var args = behavior.args; + + behavior.expression.accept(this); + this.write('&' + behavior.name); + + for (var _i17 = 0, length = args.length; _i17 < length; ++_i17) { + this.write(':'); + args[_i17].accept(this); + } + }; + + Unparser.prototype.visitValueConverter = function visitValueConverter(converter) { + var args = converter.args; + + converter.expression.accept(this); + this.write('|' + converter.name); + + for (var _i18 = 0, length = args.length; _i18 < length; ++_i18) { + this.write(':'); + args[_i18].accept(this); + } + }; + + Unparser.prototype.visitAssign = function visitAssign(assign) { + assign.target.accept(this); + this.write('='); + assign.value.accept(this); + }; + + Unparser.prototype.visitConditional = function visitConditional(conditional) { + conditional.condition.accept(this); + this.write('?'); + conditional.yes.accept(this); + this.write(':'); + conditional.no.accept(this); + }; + + Unparser.prototype.visitAccessThis = function visitAccessThis(access) { + if (access.ancestor === 0) { + this.write('$this'); + return; + } + this.write('$parent'); + var i = access.ancestor - 1; + while (i--) { + this.write('.$parent'); + } + }; + + Unparser.prototype.visitAccessScope = function visitAccessScope(access) { + var i = access.ancestor; + while (i--) { + this.write('$parent.'); + } + this.write(access.name); + }; + + Unparser.prototype.visitAccessMember = function visitAccessMember(access) { + access.object.accept(this); + this.write('.' + access.name); + }; + + Unparser.prototype.visitAccessKeyed = function visitAccessKeyed(access) { + access.object.accept(this); + this.write('['); + access.key.accept(this); + this.write(']'); + }; + + Unparser.prototype.visitCallScope = function visitCallScope(call) { + var i = call.ancestor; + while (i--) { + this.write('$parent.'); + } + this.write(call.name); + this.writeArgs(call.args); + }; + + Unparser.prototype.visitCallFunction = function visitCallFunction(call) { + call.func.accept(this); + this.writeArgs(call.args); + }; + + Unparser.prototype.visitCallMember = function visitCallMember(call) { + call.object.accept(this); + this.write('.' + call.name); + this.writeArgs(call.args); + }; + + Unparser.prototype.visitPrefix = function visitPrefix(prefix) { + this.write('(' + prefix.operation); + prefix.expression.accept(this); + this.write(')'); + }; + + Unparser.prototype.visitBinary = function visitBinary(binary) { + binary.left.accept(this); + this.write(binary.operation); + binary.right.accept(this); + }; + + Unparser.prototype.visitLiteralPrimitive = function visitLiteralPrimitive(literal) { + this.write('' + literal.value); + }; + + Unparser.prototype.visitLiteralArray = function visitLiteralArray(literal) { + var elements = literal.elements; + + this.write('['); + + for (var _i19 = 0, length = elements.length; _i19 < length; ++_i19) { + if (_i19 !== 0) { + this.write(','); + } + + elements[_i19].accept(this); + } + + this.write(']'); + }; + + Unparser.prototype.visitLiteralObject = function visitLiteralObject(literal) { + var keys = literal.keys; + var values = literal.values; + + this.write('{'); + + for (var _i20 = 0, length = keys.length; _i20 < length; ++_i20) { + if (_i20 !== 0) { + this.write(','); + } + + this.write('\'' + keys[_i20] + '\':'); + values[_i20].accept(this); + } + + this.write('}'); + }; + + Unparser.prototype.visitLiteralString = function visitLiteralString(literal) { + var escaped = literal.value.replace(/'/g, "\'"); + this.write('\'' + escaped + '\''); + }; + + return Unparser; + }(); + + var ExpressionCloner = exports.ExpressionCloner = function () { + function ExpressionCloner() { + + } + + ExpressionCloner.prototype.cloneExpressionArray = function cloneExpressionArray(array) { + var clonedArray = []; + var i = array.length; + while (i--) { + clonedArray[i] = array[i].accept(this); + } + return clonedArray; + }; + + ExpressionCloner.prototype.visitChain = function visitChain(chain) { + return new Chain(this.cloneExpressionArray(chain.expressions)); + }; + + ExpressionCloner.prototype.visitBindingBehavior = function visitBindingBehavior(behavior) { + return new BindingBehavior(behavior.expression.accept(this), behavior.name, this.cloneExpressionArray(behavior.args)); + }; + + ExpressionCloner.prototype.visitValueConverter = function visitValueConverter(converter) { + return new ValueConverter(converter.expression.accept(this), converter.name, this.cloneExpressionArray(converter.args)); + }; + + ExpressionCloner.prototype.visitAssign = function visitAssign(assign) { + return new Assign(assign.target.accept(this), assign.value.accept(this)); + }; + + ExpressionCloner.prototype.visitConditional = function visitConditional(conditional) { + return new Conditional(conditional.condition.accept(this), conditional.yes.accept(this), conditional.no.accept(this)); + }; + + ExpressionCloner.prototype.visitAccessThis = function visitAccessThis(access) { + return new AccessThis(access.ancestor); + }; + + ExpressionCloner.prototype.visitAccessScope = function visitAccessScope(access) { + return new AccessScope(access.name, access.ancestor); + }; + + ExpressionCloner.prototype.visitAccessMember = function visitAccessMember(access) { + return new AccessMember(access.object.accept(this), access.name); + }; + + ExpressionCloner.prototype.visitAccessKeyed = function visitAccessKeyed(access) { + return new AccessKeyed(access.object.accept(this), access.key.accept(this)); + }; + + ExpressionCloner.prototype.visitCallScope = function visitCallScope(call) { + return new CallScope(call.name, this.cloneExpressionArray(call.args), call.ancestor); + }; + + ExpressionCloner.prototype.visitCallFunction = function visitCallFunction(call) { + return new CallFunction(call.func.accept(this), this.cloneExpressionArray(call.args)); + }; + + ExpressionCloner.prototype.visitCallMember = function visitCallMember(call) { + return new CallMember(call.object.accept(this), call.name, this.cloneExpressionArray(call.args)); + }; + + ExpressionCloner.prototype.visitPrefix = function visitPrefix(prefix) { + return new PrefixNot(prefix.operation, prefix.expression.accept(this)); + }; + + ExpressionCloner.prototype.visitBinary = function visitBinary(binary) { + return new Binary(binary.operation, binary.left.accept(this), binary.right.accept(this)); + }; + + ExpressionCloner.prototype.visitLiteralPrimitive = function visitLiteralPrimitive(literal) { + return new LiteralPrimitive(literal); + }; + + ExpressionCloner.prototype.visitLiteralArray = function visitLiteralArray(literal) { + return new LiteralArray(this.cloneExpressionArray(literal.elements)); + }; + + ExpressionCloner.prototype.visitLiteralObject = function visitLiteralObject(literal) { + return new LiteralObject(literal.keys, this.cloneExpressionArray(literal.values)); + }; + + ExpressionCloner.prototype.visitLiteralString = function visitLiteralString(literal) { + return new LiteralString(literal.value); + }; + + return ExpressionCloner; + }(); + + function cloneExpression(expression) { + var visitor = new ExpressionCloner(); + return expression.accept(visitor); + } + + var bindingMode = exports.bindingMode = { + oneTime: 0, + oneWay: 1, + twoWay: 2 + }; + + var Token = exports.Token = function () { + function Token(index, text) { + + + this.index = index; + this.text = text; + } + + Token.prototype.withOp = function withOp(op) { + this.opKey = op; + return this; + }; + + Token.prototype.withGetterSetter = function withGetterSetter(key) { + this.key = key; + return this; + }; + + Token.prototype.withValue = function withValue(value) { + this.value = value; + return this; + }; + + Token.prototype.toString = function toString() { + return 'Token(' + this.text + ')'; + }; + + return Token; + }(); + + var Lexer = exports.Lexer = function () { + function Lexer() { + + } + + Lexer.prototype.lex = function lex(text) { + var scanner = new Scanner(text); + var tokens = []; + var token = scanner.scanToken(); + + while (token) { + tokens.push(token); + token = scanner.scanToken(); + } + + return tokens; + }; + + return Lexer; + }(); + + var Scanner = exports.Scanner = function () { + function Scanner(input) { + + + this.input = input; + this.length = input.length; + this.peek = 0; + this.index = -1; + + this.advance(); + } + + Scanner.prototype.scanToken = function scanToken() { + while (this.peek <= $SPACE) { + if (++this.index >= this.length) { + this.peek = $EOF; + return null; + } + + this.peek = this.input.charCodeAt(this.index); + } + + if (isIdentifierStart(this.peek)) { + return this.scanIdentifier(); + } + + if (isDigit(this.peek)) { + return this.scanNumber(this.index); + } + + var start = this.index; + + switch (this.peek) { + case $PERIOD: + this.advance(); + return isDigit(this.peek) ? this.scanNumber(start) : new Token(start, '.'); + case $LPAREN: + case $RPAREN: + case $LBRACE: + case $RBRACE: + case $LBRACKET: + case $RBRACKET: + case $COMMA: + case $COLON: + case $SEMICOLON: + return this.scanCharacter(start, String.fromCharCode(this.peek)); + case $SQ: + case $DQ: + return this.scanString(); + case $PLUS: + case $MINUS: + case $STAR: + case $SLASH: + case $PERCENT: + case $CARET: + case $QUESTION: + return this.scanOperator(start, String.fromCharCode(this.peek)); + case $LT: + case $GT: + case $BANG: + case $EQ: + return this.scanComplexOperator(start, $EQ, String.fromCharCode(this.peek), '='); + case $AMPERSAND: + return this.scanComplexOperator(start, $AMPERSAND, '&', '&'); + case $BAR: + return this.scanComplexOperator(start, $BAR, '|', '|'); + case $NBSP: + while (isWhitespace(this.peek)) { + this.advance(); + } + + return this.scanToken(); + } + + var character = String.fromCharCode(this.peek); + this.error('Unexpected character [' + character + ']'); + return null; + }; + + Scanner.prototype.scanCharacter = function scanCharacter(start, text) { + assert(this.peek === text.charCodeAt(0)); + this.advance(); + return new Token(start, text); + }; + + Scanner.prototype.scanOperator = function scanOperator(start, text) { + assert(this.peek === text.charCodeAt(0)); + assert(OPERATORS.indexOf(text) !== -1); + this.advance(); + return new Token(start, text).withOp(text); + }; + + Scanner.prototype.scanComplexOperator = function scanComplexOperator(start, code, one, two) { + assert(this.peek === one.charCodeAt(0)); + this.advance(); + + var text = one; + + if (this.peek === code) { + this.advance(); + text += two; + } + + if (this.peek === code) { + this.advance(); + text += two; + } + + assert(OPERATORS.indexOf(text) !== -1); + + return new Token(start, text).withOp(text); + }; + + Scanner.prototype.scanIdentifier = function scanIdentifier() { + assert(isIdentifierStart(this.peek)); + var start = this.index; + + this.advance(); + + while (isIdentifierPart(this.peek)) { + this.advance(); + } + + var text = this.input.substring(start, this.index); + var result = new Token(start, text); + + if (OPERATORS.indexOf(text) !== -1) { + result.withOp(text); + } else { + result.withGetterSetter(text); + } + + return result; + }; + + Scanner.prototype.scanNumber = function scanNumber(start) { + assert(isDigit(this.peek)); + var simple = this.index === start; + this.advance(); + + while (true) { + if (!isDigit(this.peek)) { + if (this.peek === $PERIOD) { + simple = false; + } else if (isExponentStart(this.peek)) { + this.advance(); + + if (isExponentSign(this.peek)) { + this.advance(); + } + + if (!isDigit(this.peek)) { + this.error('Invalid exponent', -1); + } + + simple = false; + } else { + break; + } + } + + this.advance(); + } + + var text = this.input.substring(start, this.index); + var value = simple ? parseInt(text, 10) : parseFloat(text); + return new Token(start, text).withValue(value); + }; + + Scanner.prototype.scanString = function scanString() { + assert(this.peek === $SQ || this.peek === $DQ); + + var start = this.index; + var quote = this.peek; + + this.advance(); + + var buffer = void 0; + var marker = this.index; + + while (this.peek !== quote) { + if (this.peek === $BACKSLASH) { + if (!buffer) { + buffer = []; + } + + buffer.push(this.input.substring(marker, this.index)); + this.advance(); + + var _unescaped = void 0; + + if (this.peek === $u) { + var hex = this.input.substring(this.index + 1, this.index + 5); + + if (!/[A-Z0-9]{4}/.test(hex)) { + this.error('Invalid unicode escape [\\u' + hex + ']'); + } + + _unescaped = parseInt(hex, 16); + + for (var _i21 = 0; _i21 < 5; ++_i21) { + this.advance(); + } + } else { + _unescaped = unescape(this.peek); + this.advance(); + } + + buffer.push(String.fromCharCode(_unescaped)); + marker = this.index; + } else if (this.peek === $EOF) { + this.error('Unterminated quote'); + } else { + this.advance(); + } + } + + var last = this.input.substring(marker, this.index); + this.advance(); + var text = this.input.substring(start, this.index); + + var unescaped = last; + + if (buffer !== null && buffer !== undefined) { + buffer.push(last); + unescaped = buffer.join(''); + } + + return new Token(start, text).withValue(unescaped); + }; + + Scanner.prototype.advance = function advance() { + if (++this.index >= this.length) { + this.peek = $EOF; + } else { + this.peek = this.input.charCodeAt(this.index); + } + }; + + Scanner.prototype.error = function error(message) { + var offset = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; + + var position = this.index + offset; + throw new Error('Lexer Error: ' + message + ' at column ' + position + ' in expression [' + this.input + ']'); + }; + + return Scanner; + }(); + + var OPERATORS = ['undefined', 'null', 'true', 'false', '+', '-', '*', '/', '%', '^', '=', '==', '===', '!=', '!==', '<', '>', '<=', '>=', '&&', '||', '&', '|', '!', '?']; + + var $EOF = 0; + var $TAB = 9; + var $LF = 10; + var $VTAB = 11; + var $FF = 12; + var $CR = 13; + var $SPACE = 32; + var $BANG = 33; + var $DQ = 34; + var $$ = 36; + var $PERCENT = 37; + var $AMPERSAND = 38; + var $SQ = 39; + var $LPAREN = 40; + var $RPAREN = 41; + var $STAR = 42; + var $PLUS = 43; + var $COMMA = 44; + var $MINUS = 45; + var $PERIOD = 46; + var $SLASH = 47; + var $COLON = 58; + var $SEMICOLON = 59; + var $LT = 60; + var $EQ = 61; + var $GT = 62; + var $QUESTION = 63; + + var $0 = 48; + var $9 = 57; + + var $A = 65; + var $E = 69; + var $Z = 90; + + var $LBRACKET = 91; + var $BACKSLASH = 92; + var $RBRACKET = 93; + var $CARET = 94; + var $_ = 95; + + var $a = 97; + var $e = 101; + var $f = 102; + var $n = 110; + var $r = 114; + var $t = 116; + var $u = 117; + var $v = 118; + var $z = 122; + + var $LBRACE = 123; + var $BAR = 124; + var $RBRACE = 125; + var $NBSP = 160; + + function isWhitespace(code) { + return code >= $TAB && code <= $SPACE || code === $NBSP; + } + + function isIdentifierStart(code) { + return $a <= code && code <= $z || $A <= code && code <= $Z || code === $_ || code === $$; + } + + function isIdentifierPart(code) { + return $a <= code && code <= $z || $A <= code && code <= $Z || $0 <= code && code <= $9 || code === $_ || code === $$; + } + + function isDigit(code) { + return $0 <= code && code <= $9; + } + + function isExponentStart(code) { + return code === $e || code === $E; + } + + function isExponentSign(code) { + return code === $MINUS || code === $PLUS; + } + + function unescape(code) { + switch (code) { + case $n: + return $LF; + case $f: + return $FF; + case $r: + return $CR; + case $t: + return $TAB; + case $v: + return $VTAB; + default: + return code; + } + } + + function assert(condition, message) { + if (!condition) { + throw message || 'Assertion failed'; + } + } + + var EOF = new Token(-1, null); + + var Parser = exports.Parser = function () { + function Parser() { + + + this.cache = {}; + this.lexer = new Lexer(); + } + + Parser.prototype.parse = function parse(input) { + input = input || ''; + + return this.cache[input] || (this.cache[input] = new ParserImplementation(this.lexer, input).parseChain()); + }; + + return Parser; + }(); + + var ParserImplementation = exports.ParserImplementation = function () { + function ParserImplementation(lexer, input) { + + + this.index = 0; + this.input = input; + this.tokens = lexer.lex(input); + } + + ParserImplementation.prototype.parseChain = function parseChain() { + var isChain = false; + var expressions = []; + + while (this.optional(';')) { + isChain = true; + } + + while (this.index < this.tokens.length) { + if (this.peek.text === ')' || this.peek.text === '}' || this.peek.text === ']') { + this.error('Unconsumed token ' + this.peek.text); + } + + var expr = this.parseBindingBehavior(); + expressions.push(expr); + + while (this.optional(';')) { + isChain = true; + } + + if (isChain) { + this.error('Multiple expressions are not allowed.'); + } + } + + return expressions.length === 1 ? expressions[0] : new Chain(expressions); + }; + + ParserImplementation.prototype.parseBindingBehavior = function parseBindingBehavior() { + var result = this.parseValueConverter(); + + while (this.optional('&')) { + var name = this.peek.text; + var args = []; + + this.advance(); + + while (this.optional(':')) { + args.push(this.parseExpression()); + } + + result = new BindingBehavior(result, name, args); + } + + return result; + }; + + ParserImplementation.prototype.parseValueConverter = function parseValueConverter() { + var result = this.parseExpression(); + + while (this.optional('|')) { + var name = this.peek.text; + var args = []; + + this.advance(); + + while (this.optional(':')) { + args.push(this.parseExpression()); + } + + result = new ValueConverter(result, name, args, [result].concat(args)); + } + + return result; + }; + + ParserImplementation.prototype.parseExpression = function parseExpression() { + var start = this.peek.index; + var result = this.parseConditional(); + + while (this.peek.text === '=') { + if (!result.isAssignable) { + var end = this.index < this.tokens.length ? this.peek.index : this.input.length; + var _expression = this.input.substring(start, end); + + this.error('Expression ' + _expression + ' is not assignable'); + } + + this.expect('='); + result = new Assign(result, this.parseConditional()); + } + + return result; + }; + + ParserImplementation.prototype.parseConditional = function parseConditional() { + var start = this.peek.index; + var result = this.parseLogicalOr(); + + if (this.optional('?')) { + var yes = this.parseExpression(); + + if (!this.optional(':')) { + var end = this.index < this.tokens.length ? this.peek.index : this.input.length; + var _expression2 = this.input.substring(start, end); + + this.error('Conditional expression ' + _expression2 + ' requires all 3 expressions'); + } + + var no = this.parseExpression(); + result = new Conditional(result, yes, no); + } + + return result; + }; + + ParserImplementation.prototype.parseLogicalOr = function parseLogicalOr() { + var result = this.parseLogicalAnd(); + + while (this.optional('||')) { + result = new Binary('||', result, this.parseLogicalAnd()); + } + + return result; + }; + + ParserImplementation.prototype.parseLogicalAnd = function parseLogicalAnd() { + var result = this.parseEquality(); + + while (this.optional('&&')) { + result = new Binary('&&', result, this.parseEquality()); + } + + return result; + }; + + ParserImplementation.prototype.parseEquality = function parseEquality() { + var result = this.parseRelational(); + + while (true) { + if (this.optional('==')) { + result = new Binary('==', result, this.parseRelational()); + } else if (this.optional('!=')) { + result = new Binary('!=', result, this.parseRelational()); + } else if (this.optional('===')) { + result = new Binary('===', result, this.parseRelational()); + } else if (this.optional('!==')) { + result = new Binary('!==', result, this.parseRelational()); + } else { + return result; + } + } + }; + + ParserImplementation.prototype.parseRelational = function parseRelational() { + var result = this.parseAdditive(); + + while (true) { + if (this.optional('<')) { + result = new Binary('<', result, this.parseAdditive()); + } else if (this.optional('>')) { + result = new Binary('>', result, this.parseAdditive()); + } else if (this.optional('<=')) { + result = new Binary('<=', result, this.parseAdditive()); + } else if (this.optional('>=')) { + result = new Binary('>=', result, this.parseAdditive()); + } else { + return result; + } + } + }; + + ParserImplementation.prototype.parseAdditive = function parseAdditive() { + var result = this.parseMultiplicative(); + + while (true) { + if (this.optional('+')) { + result = new Binary('+', result, this.parseMultiplicative()); + } else if (this.optional('-')) { + result = new Binary('-', result, this.parseMultiplicative()); + } else { + return result; + } + } + }; + + ParserImplementation.prototype.parseMultiplicative = function parseMultiplicative() { + var result = this.parsePrefix(); + + while (true) { + if (this.optional('*')) { + result = new Binary('*', result, this.parsePrefix()); + } else if (this.optional('%')) { + result = new Binary('%', result, this.parsePrefix()); + } else if (this.optional('/')) { + result = new Binary('/', result, this.parsePrefix()); + } else { + return result; + } + } + }; + + ParserImplementation.prototype.parsePrefix = function parsePrefix() { + if (this.optional('+')) { + return this.parsePrefix(); + } else if (this.optional('-')) { + return new Binary('-', new LiteralPrimitive(0), this.parsePrefix()); + } else if (this.optional('!')) { + return new PrefixNot('!', this.parsePrefix()); + } + + return this.parseAccessOrCallMember(); + }; + + ParserImplementation.prototype.parseAccessOrCallMember = function parseAccessOrCallMember() { + var result = this.parsePrimary(); + + while (true) { + if (this.optional('.')) { + var name = this.peek.text; + + this.advance(); + + if (this.optional('(')) { + var args = this.parseExpressionList(')'); + this.expect(')'); + if (result instanceof AccessThis) { + result = new CallScope(name, args, result.ancestor); + } else { + result = new CallMember(result, name, args); + } + } else { + if (result instanceof AccessThis) { + result = new AccessScope(name, result.ancestor); + } else { + result = new AccessMember(result, name); + } + } + } else if (this.optional('[')) { + var key = this.parseExpression(); + this.expect(']'); + result = new AccessKeyed(result, key); + } else if (this.optional('(')) { + var _args = this.parseExpressionList(')'); + this.expect(')'); + result = new CallFunction(result, _args); + } else { + return result; + } + } + }; + + ParserImplementation.prototype.parsePrimary = function parsePrimary() { + if (this.optional('(')) { + var result = this.parseExpression(); + this.expect(')'); + return result; + } else if (this.optional('null')) { + return new LiteralPrimitive(null); + } else if (this.optional('undefined')) { + return new LiteralPrimitive(undefined); + } else if (this.optional('true')) { + return new LiteralPrimitive(true); + } else if (this.optional('false')) { + return new LiteralPrimitive(false); + } else if (this.optional('[')) { + var elements = this.parseExpressionList(']'); + this.expect(']'); + return new LiteralArray(elements); + } else if (this.peek.text === '{') { + return this.parseObject(); + } else if (this.peek.key !== null && this.peek.key !== undefined) { + return this.parseAccessOrCallScope(); + } else if (this.peek.value !== null && this.peek.value !== undefined) { + var value = this.peek.value; + this.advance(); + return value instanceof String || typeof value === 'string' ? new LiteralString(value) : new LiteralPrimitive(value); + } else if (this.index >= this.tokens.length) { + throw new Error('Unexpected end of expression: ' + this.input); + } else { + this.error('Unexpected token ' + this.peek.text); + } + }; + + ParserImplementation.prototype.parseAccessOrCallScope = function parseAccessOrCallScope() { + var name = this.peek.key; + + this.advance(); + + if (name === '$this') { + return new AccessThis(0); + } + + var ancestor = 0; + while (name === '$parent') { + ancestor++; + if (this.optional('.')) { + name = this.peek.key; + this.advance(); + } else if (this.peek === EOF || this.peek.text === '(' || this.peek.text === '[' || this.peek.text === '}' || this.peek.text === ',') { + return new AccessThis(ancestor); + } else { + this.error('Unexpected token ' + this.peek.text); + } + } + + if (this.optional('(')) { + var args = this.parseExpressionList(')'); + this.expect(')'); + return new CallScope(name, args, ancestor); + } + + return new AccessScope(name, ancestor); + }; + + ParserImplementation.prototype.parseObject = function parseObject() { + var keys = []; + var values = []; + + this.expect('{'); + + if (this.peek.text !== '}') { + do { + var peek = this.peek; + var value = peek.value; + keys.push(typeof value === 'string' ? value : peek.text); + + this.advance(); + if (peek.key && (this.peek.text === ',' || this.peek.text === '}')) { + --this.index; + values.push(this.parseAccessOrCallScope()); + } else { + this.expect(':'); + values.push(this.parseExpression()); + } + } while (this.optional(',')); + } + + this.expect('}'); + + return new LiteralObject(keys, values); + }; + + ParserImplementation.prototype.parseExpressionList = function parseExpressionList(terminator) { + var result = []; + + if (this.peek.text !== terminator) { + do { + result.push(this.parseExpression()); + } while (this.optional(',')); + } + + return result; + }; + + ParserImplementation.prototype.optional = function optional(text) { + if (this.peek.text === text) { + this.advance(); + return true; + } + + return false; + }; + + ParserImplementation.prototype.expect = function expect(text) { + if (this.peek.text === text) { + this.advance(); + } else { + this.error('Missing expected ' + text); + } + }; + + ParserImplementation.prototype.advance = function advance() { + this.index++; + }; + + ParserImplementation.prototype.error = function error(message) { + var location = this.index < this.tokens.length ? 'at column ' + (this.tokens[this.index].index + 1) + ' in' : 'at the end of the expression'; + + throw new Error('Parser Error: ' + message + ' ' + location + ' [' + this.input + ']'); + }; + + _createClass(ParserImplementation, [{ + key: 'peek', + get: function get() { + return this.index < this.tokens.length ? this.tokens[this.index] : EOF; + } + }]); + + return ParserImplementation; + }(); + + var mapProto = Map.prototype; + + function _getMapObserver(taskQueue, map) { + return ModifyMapObserver.for(taskQueue, map); + } + + exports.getMapObserver = _getMapObserver; + + var ModifyMapObserver = function (_ModifyCollectionObse2) { + _inherits(ModifyMapObserver, _ModifyCollectionObse2); + + function ModifyMapObserver(taskQueue, map) { + + + return _possibleConstructorReturn(this, _ModifyCollectionObse2.call(this, taskQueue, map)); + } + + ModifyMapObserver.for = function _for(taskQueue, map) { + if (!('__map_observer__' in map)) { + Reflect.defineProperty(map, '__map_observer__', { + value: ModifyMapObserver.create(taskQueue, map), + enumerable: false, configurable: false + }); + } + return map.__map_observer__; + }; + + ModifyMapObserver.create = function create(taskQueue, map) { + var observer = new ModifyMapObserver(taskQueue, map); + + var proto = mapProto; + if (proto.add !== map.add || proto.delete !== map.delete || proto.clear !== map.clear) { + proto = { + add: map.add, + delete: map.delete, + clear: map.clear + }; + } + + map.set = function () { + var hasValue = map.has(arguments[0]); + var type = hasValue ? 'update' : 'add'; + var oldValue = map.get(arguments[0]); + var methodCallResult = proto.set.apply(map, arguments); + if (!hasValue || oldValue !== map.get(arguments[0])) { + observer.addChangeRecord({ + type: type, + object: map, + key: arguments[0], + oldValue: oldValue + }); + } + return methodCallResult; + }; + + map.delete = function () { + var hasValue = map.has(arguments[0]); + var oldValue = map.get(arguments[0]); + var methodCallResult = proto.delete.apply(map, arguments); + if (hasValue) { + observer.addChangeRecord({ + type: 'delete', + object: map, + key: arguments[0], + oldValue: oldValue + }); + } + return methodCallResult; + }; + + map.clear = function () { + var methodCallResult = proto.clear.apply(map, arguments); + observer.addChangeRecord({ + type: 'clear', + object: map + }); + return methodCallResult; + }; + + return observer; + }; + + return ModifyMapObserver; + }(ModifyCollectionObserver); + + function findOriginalEventTarget(event) { + return event.path && event.path[0] || event.deepPath && event.deepPath[0] || event.target; + } + + function interceptStopPropagation(event) { + event.standardStopPropagation = event.stopPropagation; + event.stopPropagation = function () { + this.propagationStopped = true; + this.standardStopPropagation(); + }; + } + + function handleDelegatedEvent(event) { + var interceptInstalled = false; + event.propagationStopped = false; + var target = findOriginalEventTarget(event); + + while (target && !event.propagationStopped) { + if (target.delegatedCallbacks) { + var callback = target.delegatedCallbacks[event.type]; + if (callback) { + if (!interceptInstalled) { + interceptStopPropagation(event); + interceptInstalled = true; + } + callback(event); + } + } + + target = target.parentNode; + } + } + + var DelegateHandlerEntry = function () { + function DelegateHandlerEntry(eventName) { + + + this.eventName = eventName; + this.count = 0; + } + + DelegateHandlerEntry.prototype.increment = function increment() { + this.count++; + + if (this.count === 1) { + _aureliaPal.DOM.addEventListener(this.eventName, handleDelegatedEvent, false); + } + }; + + DelegateHandlerEntry.prototype.decrement = function decrement() { + this.count--; + + if (this.count === 0) { + _aureliaPal.DOM.removeEventListener(this.eventName, handleDelegatedEvent); + } + }; + + return DelegateHandlerEntry; + }(); + + var DefaultEventStrategy = function () { + function DefaultEventStrategy() { + + + this.delegatedHandlers = {}; + } + + DefaultEventStrategy.prototype.subscribe = function subscribe(target, targetEvent, callback, delegate) { + var _this22 = this; + + if (delegate) { + var _ret = function () { + var delegatedHandlers = _this22.delegatedHandlers; + var handlerEntry = delegatedHandlers[targetEvent] || (delegatedHandlers[targetEvent] = new DelegateHandlerEntry(targetEvent)); + var delegatedCallbacks = target.delegatedCallbacks || (target.delegatedCallbacks = {}); + + handlerEntry.increment(); + delegatedCallbacks[targetEvent] = callback; + + return { + v: function v() { + handlerEntry.decrement(); + delegatedCallbacks[targetEvent] = null; + } + }; + }(); + + if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + + target.addEventListener(targetEvent, callback, false); + + return function () { + target.removeEventListener(targetEvent, callback); + }; + }; + + return DefaultEventStrategy; + }(); + + var EventManager = exports.EventManager = function () { + function EventManager() { + + + this.elementHandlerLookup = {}; + this.eventStrategyLookup = {}; + + this.registerElementConfig({ + tagName: 'input', + properties: { + value: ['change', 'input'], + checked: ['change', 'input'], + files: ['change', 'input'] + } + }); + + this.registerElementConfig({ + tagName: 'textarea', + properties: { + value: ['change', 'input'] + } + }); + + this.registerElementConfig({ + tagName: 'select', + properties: { + value: ['change'] + } + }); + + this.registerElementConfig({ + tagName: 'content editable', + properties: { + value: ['change', 'input', 'blur', 'keyup', 'paste'] + } + }); + + this.registerElementConfig({ + tagName: 'scrollable element', + properties: { + scrollTop: ['scroll'], + scrollLeft: ['scroll'] + } + }); + + this.defaultEventStrategy = new DefaultEventStrategy(); + } + + EventManager.prototype.registerElementConfig = function registerElementConfig(config) { + var tagName = config.tagName.toLowerCase(); + var properties = config.properties; + var propertyName = void 0; + + this.elementHandlerLookup[tagName] = {}; + + for (propertyName in properties) { + if (properties.hasOwnProperty(propertyName)) { + this.registerElementPropertyConfig(tagName, propertyName, properties[propertyName]); + } + } + }; + + EventManager.prototype.registerElementPropertyConfig = function registerElementPropertyConfig(tagName, propertyName, events) { + this.elementHandlerLookup[tagName][propertyName] = this.createElementHandler(events); + }; + + EventManager.prototype.createElementHandler = function createElementHandler(events) { + return { + subscribe: function subscribe(target, callback) { + events.forEach(function (changeEvent) { + target.addEventListener(changeEvent, callback, false); + }); + + return function () { + events.forEach(function (changeEvent) { + target.removeEventListener(changeEvent, callback); + }); + }; + } + }; + }; + + EventManager.prototype.registerElementHandler = function registerElementHandler(tagName, handler) { + this.elementHandlerLookup[tagName.toLowerCase()] = handler; + }; + + EventManager.prototype.registerEventStrategy = function registerEventStrategy(eventName, strategy) { + this.eventStrategyLookup[eventName] = strategy; + }; + + EventManager.prototype.getElementHandler = function getElementHandler(target, propertyName) { + var tagName = void 0; + var lookup = this.elementHandlerLookup; + + if (target.tagName) { + tagName = target.tagName.toLowerCase(); + + if (lookup[tagName] && lookup[tagName][propertyName]) { + return lookup[tagName][propertyName]; + } + + if (propertyName === 'textContent' || propertyName === 'innerHTML') { + return lookup['content editable'].value; + } + + if (propertyName === 'scrollTop' || propertyName === 'scrollLeft') { + return lookup['scrollable element'][propertyName]; + } + } + + return null; + }; + + EventManager.prototype.addEventListener = function addEventListener(target, targetEvent, callback, delegate) { + return (this.eventStrategyLookup[targetEvent] || this.defaultEventStrategy).subscribe(target, targetEvent, callback, delegate); + }; + + return EventManager; + }(); + + var DirtyChecker = exports.DirtyChecker = function () { + function DirtyChecker() { + + + this.tracked = []; + this.checkDelay = 120; + } + + DirtyChecker.prototype.addProperty = function addProperty(property) { + var tracked = this.tracked; + + tracked.push(property); + + if (tracked.length === 1) { + this.scheduleDirtyCheck(); + } + }; + + DirtyChecker.prototype.removeProperty = function removeProperty(property) { + var tracked = this.tracked; + tracked.splice(tracked.indexOf(property), 1); + }; + + DirtyChecker.prototype.scheduleDirtyCheck = function scheduleDirtyCheck() { + var _this23 = this; + + setTimeout(function () { + return _this23.check(); + }, this.checkDelay); + }; + + DirtyChecker.prototype.check = function check() { + var tracked = this.tracked; + var i = tracked.length; + + while (i--) { + var current = tracked[i]; + + if (current.isDirty()) { + current.call(); + } + } + + if (tracked.length) { + this.scheduleDirtyCheck(); + } + }; + + return DirtyChecker; + }(); + + var DirtyCheckProperty = exports.DirtyCheckProperty = (_dec5 = subscriberCollection(), _dec5(_class5 = function () { + function DirtyCheckProperty(dirtyChecker, obj, propertyName) { + + + this.dirtyChecker = dirtyChecker; + this.obj = obj; + this.propertyName = propertyName; + } + + DirtyCheckProperty.prototype.getValue = function getValue() { + return this.obj[this.propertyName]; + }; + + DirtyCheckProperty.prototype.setValue = function setValue(newValue) { + this.obj[this.propertyName] = newValue; + }; + + DirtyCheckProperty.prototype.call = function call() { + var oldValue = this.oldValue; + var newValue = this.getValue(); + + this.callSubscribers(newValue, oldValue); + + this.oldValue = newValue; + }; + + DirtyCheckProperty.prototype.isDirty = function isDirty() { + return this.oldValue !== this.obj[this.propertyName]; + }; + + DirtyCheckProperty.prototype.subscribe = function subscribe(context, callable) { + if (!this.hasSubscribers()) { + this.oldValue = this.getValue(); + this.dirtyChecker.addProperty(this); + } + this.addSubscriber(context, callable); + }; + + DirtyCheckProperty.prototype.unsubscribe = function unsubscribe(context, callable) { + if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) { + this.dirtyChecker.removeProperty(this); + } + }; + + return DirtyCheckProperty; + }()) || _class5); + + + var logger = LogManager.getLogger('property-observation'); + + var propertyAccessor = exports.propertyAccessor = { + getValue: function getValue(obj, propertyName) { + return obj[propertyName]; + }, + setValue: function setValue(value, obj, propertyName) { + obj[propertyName] = value; + } + }; + + var PrimitiveObserver = exports.PrimitiveObserver = function () { + function PrimitiveObserver(primitive, propertyName) { + + + this.doNotCache = true; + + this.primitive = primitive; + this.propertyName = propertyName; + } + + PrimitiveObserver.prototype.getValue = function getValue() { + return this.primitive[this.propertyName]; + }; + + PrimitiveObserver.prototype.setValue = function setValue() { + var type = _typeof(this.primitive); + throw new Error('The ' + this.propertyName + ' property of a ' + type + ' (' + this.primitive + ') cannot be assigned.'); + }; + + PrimitiveObserver.prototype.subscribe = function subscribe() {}; + + PrimitiveObserver.prototype.unsubscribe = function unsubscribe() {}; + + return PrimitiveObserver; + }(); + + var SetterObserver = exports.SetterObserver = (_dec6 = subscriberCollection(), _dec6(_class7 = function () { + function SetterObserver(taskQueue, obj, propertyName) { + + + this.taskQueue = taskQueue; + this.obj = obj; + this.propertyName = propertyName; + this.queued = false; + this.observing = false; + } + + SetterObserver.prototype.getValue = function getValue() { + return this.obj[this.propertyName]; + }; + + SetterObserver.prototype.setValue = function setValue(newValue) { + this.obj[this.propertyName] = newValue; + }; + + SetterObserver.prototype.getterValue = function getterValue() { + return this.currentValue; + }; + + SetterObserver.prototype.setterValue = function setterValue(newValue) { + var oldValue = this.currentValue; + + if (oldValue !== newValue) { + if (!this.queued) { + this.oldValue = oldValue; + this.queued = true; + this.taskQueue.queueMicroTask(this); + } + + this.currentValue = newValue; + } + }; + + SetterObserver.prototype.call = function call() { + var oldValue = this.oldValue; + var newValue = this.currentValue; + + this.queued = false; + + this.callSubscribers(newValue, oldValue); + }; + + SetterObserver.prototype.subscribe = function subscribe(context, callable) { + if (!this.observing) { + this.convertProperty(); + } + this.addSubscriber(context, callable); + }; + + SetterObserver.prototype.unsubscribe = function unsubscribe(context, callable) { + this.removeSubscriber(context, callable); + }; + + SetterObserver.prototype.convertProperty = function convertProperty() { + this.observing = true; + this.currentValue = this.obj[this.propertyName]; + this.setValue = this.setterValue; + this.getValue = this.getterValue; + + if (!Reflect.defineProperty(this.obj, this.propertyName, { + configurable: true, + enumerable: this.propertyName in this.obj ? this.obj.propertyIsEnumerable(this.propertyName) : true, + get: this.getValue.bind(this), + set: this.setValue.bind(this) + })) { + logger.warn('Cannot observe property \'' + this.propertyName + '\' of object', this.obj); + } + }; + + return SetterObserver; + }()) || _class7); + + var XLinkAttributeObserver = exports.XLinkAttributeObserver = function () { + function XLinkAttributeObserver(element, propertyName, attributeName) { + + + this.element = element; + this.propertyName = propertyName; + this.attributeName = attributeName; + } + + XLinkAttributeObserver.prototype.getValue = function getValue() { + return this.element.getAttributeNS('http://www.w3.org/1999/xlink', this.attributeName); + }; + + XLinkAttributeObserver.prototype.setValue = function setValue(newValue) { + return this.element.setAttributeNS('http://www.w3.org/1999/xlink', this.attributeName, newValue); + }; + + XLinkAttributeObserver.prototype.subscribe = function subscribe() { + throw new Error('Observation of a "' + this.element.nodeName + '" element\'s "' + this.propertyName + '" property is not supported.'); + }; + + return XLinkAttributeObserver; + }(); + + var dataAttributeAccessor = exports.dataAttributeAccessor = { + getValue: function getValue(obj, propertyName) { + return obj.getAttribute(propertyName); + }, + setValue: function setValue(value, obj, propertyName) { + return obj.setAttribute(propertyName, value); + } + }; + + var DataAttributeObserver = exports.DataAttributeObserver = function () { + function DataAttributeObserver(element, propertyName) { + + + this.element = element; + this.propertyName = propertyName; + } + + DataAttributeObserver.prototype.getValue = function getValue() { + return this.element.getAttribute(this.propertyName); + }; + + DataAttributeObserver.prototype.setValue = function setValue(newValue) { + return this.element.setAttribute(this.propertyName, newValue); + }; + + DataAttributeObserver.prototype.subscribe = function subscribe() { + throw new Error('Observation of a "' + this.element.nodeName + '" element\'s "' + this.propertyName + '" property is not supported.'); + }; + + return DataAttributeObserver; + }(); + + var StyleObserver = exports.StyleObserver = function () { + function StyleObserver(element, propertyName) { + + + this.element = element; + this.propertyName = propertyName; + + this.styles = null; + this.version = 0; + } + + StyleObserver.prototype.getValue = function getValue() { + return this.element.style.cssText; + }; + + StyleObserver.prototype._setProperty = function _setProperty(style, value) { + var priority = ''; + + if (value !== null && value !== undefined && typeof value.indexOf === 'function' && value.indexOf('!important') !== -1) { + priority = 'important'; + value = value.replace('!important', ''); + } + this.element.style.setProperty(style, value, priority); + }; + + StyleObserver.prototype.setValue = function setValue(newValue) { + var styles = this.styles || {}; + var style = void 0; + var version = this.version; + + if (newValue !== null && newValue !== undefined) { + if (newValue instanceof Object) { + for (style in newValue) { + if (newValue.hasOwnProperty(style)) { + styles[style] = version; + this._setProperty(style, newValue[style]); + } + } + } else if (newValue.length) { + var rx = /\s*([\w\-]+)\s*:\s*((?:(?:[\w\-]+\(\s*(?:"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|[\w\-]+\(\s*(?:^"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|[^\)]*)\),?|[^\)]*)\),?|"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|[^;]*),?\s*)+);?/g; + var pair = void 0; + while ((pair = rx.exec(newValue)) !== null) { + style = pair[1]; + if (!style) { + continue; + } + + styles[style] = version; + this._setProperty(style, pair[2]); + } + } + } + + this.styles = styles; + this.version += 1; + + if (version === 0) { + return; + } + + version -= 1; + for (style in styles) { + if (!styles.hasOwnProperty(style) || styles[style] !== version) { + continue; + } + + this.element.style.removeProperty(style); + } + }; + + StyleObserver.prototype.subscribe = function subscribe() { + throw new Error('Observation of a "' + this.element.nodeName + '" element\'s "' + this.propertyName + '" property is not supported.'); + }; + + return StyleObserver; + }(); + + var ValueAttributeObserver = exports.ValueAttributeObserver = (_dec7 = subscriberCollection(), _dec7(_class8 = function () { + function ValueAttributeObserver(element, propertyName, handler) { + + + this.element = element; + this.propertyName = propertyName; + this.handler = handler; + if (propertyName === 'files') { + this.setValue = function () {}; + } + } + + ValueAttributeObserver.prototype.getValue = function getValue() { + return this.element[this.propertyName]; + }; + + ValueAttributeObserver.prototype.setValue = function setValue(newValue) { + newValue = newValue === undefined || newValue === null ? '' : newValue; + if (this.element[this.propertyName] !== newValue) { + this.element[this.propertyName] = newValue; + this.notify(); + } + }; + + ValueAttributeObserver.prototype.notify = function notify() { + var oldValue = this.oldValue; + var newValue = this.getValue(); + + this.callSubscribers(newValue, oldValue); + + this.oldValue = newValue; + }; + + ValueAttributeObserver.prototype.subscribe = function subscribe(context, callable) { + if (!this.hasSubscribers()) { + this.oldValue = this.getValue(); + this.disposeHandler = this.handler.subscribe(this.element, this.notify.bind(this)); + } + + this.addSubscriber(context, callable); + }; + + ValueAttributeObserver.prototype.unsubscribe = function unsubscribe(context, callable) { + if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) { + this.disposeHandler(); + this.disposeHandler = null; + } + }; + + return ValueAttributeObserver; + }()) || _class8); + + + var checkedArrayContext = 'CheckedObserver:array'; + var checkedValueContext = 'CheckedObserver:value'; + + var CheckedObserver = exports.CheckedObserver = (_dec8 = subscriberCollection(), _dec8(_class9 = function () { + function CheckedObserver(element, handler, observerLocator) { + + + this.element = element; + this.handler = handler; + this.observerLocator = observerLocator; + } + + CheckedObserver.prototype.getValue = function getValue() { + return this.value; + }; + + CheckedObserver.prototype.setValue = function setValue(newValue) { + if (this.value === newValue) { + return; + } + + if (this.arrayObserver) { + this.arrayObserver.unsubscribe(checkedArrayContext, this); + this.arrayObserver = null; + } + + if (this.element.type === 'checkbox' && Array.isArray(newValue)) { + this.arrayObserver = this.observerLocator.getArrayObserver(newValue); + this.arrayObserver.subscribe(checkedArrayContext, this); + } + + this.oldValue = this.value; + this.value = newValue; + this.synchronizeElement(); + this.notify(); + + if (!this.initialSync) { + this.initialSync = true; + this.observerLocator.taskQueue.queueMicroTask(this); + } + }; + + CheckedObserver.prototype.call = function call(context, splices) { + this.synchronizeElement(); + + if (!this.valueObserver) { + this.valueObserver = this.element.__observers__.model || this.element.__observers__.value; + if (this.valueObserver) { + this.valueObserver.subscribe(checkedValueContext, this); + } + } + }; + + CheckedObserver.prototype.synchronizeElement = function synchronizeElement() { + var value = this.value; + var element = this.element; + var elementValue = element.hasOwnProperty('model') ? element.model : element.value; + var isRadio = element.type === 'radio'; + var matcher = element.matcher || function (a, b) { + return a === b; + }; + + element.checked = isRadio && !!matcher(value, elementValue) || !isRadio && value === true || !isRadio && Array.isArray(value) && value.findIndex(function (item) { + return !!matcher(item, elementValue); + }) !== -1; + }; + + CheckedObserver.prototype.synchronizeValue = function synchronizeValue() { + var value = this.value; + var element = this.element; + var elementValue = element.hasOwnProperty('model') ? element.model : element.value; + var index = void 0; + var matcher = element.matcher || function (a, b) { + return a === b; + }; + + if (element.type === 'checkbox') { + if (Array.isArray(value)) { + index = value.findIndex(function (item) { + return !!matcher(item, elementValue); + }); + if (element.checked && index === -1) { + value.push(elementValue); + } else if (!element.checked && index !== -1) { + value.splice(index, 1); + } + + return; + } + + value = element.checked; + } else if (element.checked) { + value = elementValue; + } else { + return; + } + + this.oldValue = this.value; + this.value = value; + this.notify(); + }; + + CheckedObserver.prototype.notify = function notify() { + var oldValue = this.oldValue; + var newValue = this.value; + + this.callSubscribers(newValue, oldValue); + }; + + CheckedObserver.prototype.subscribe = function subscribe(context, callable) { + if (!this.hasSubscribers()) { + this.disposeHandler = this.handler.subscribe(this.element, this.synchronizeValue.bind(this, false)); + } + this.addSubscriber(context, callable); + }; + + CheckedObserver.prototype.unsubscribe = function unsubscribe(context, callable) { + if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) { + this.disposeHandler(); + this.disposeHandler = null; + } + }; + + CheckedObserver.prototype.unbind = function unbind() { + if (this.arrayObserver) { + this.arrayObserver.unsubscribe(checkedArrayContext, this); + this.arrayObserver = null; + } + if (this.valueObserver) { + this.valueObserver.unsubscribe(checkedValueContext, this); + } + }; + + return CheckedObserver; + }()) || _class9); + + + var selectArrayContext = 'SelectValueObserver:array'; + + var SelectValueObserver = exports.SelectValueObserver = (_dec9 = subscriberCollection(), _dec9(_class10 = function () { + function SelectValueObserver(element, handler, observerLocator) { + + + this.element = element; + this.handler = handler; + this.observerLocator = observerLocator; + } + + SelectValueObserver.prototype.getValue = function getValue() { + return this.value; + }; + + SelectValueObserver.prototype.setValue = function setValue(newValue) { + if (newValue !== null && newValue !== undefined && this.element.multiple && !Array.isArray(newValue)) { + throw new Error('Only null or Array instances can be bound to a multi-select.'); + } + if (this.value === newValue) { + return; + } + + if (this.arrayObserver) { + this.arrayObserver.unsubscribe(selectArrayContext, this); + this.arrayObserver = null; + } + + if (Array.isArray(newValue)) { + this.arrayObserver = this.observerLocator.getArrayObserver(newValue); + this.arrayObserver.subscribe(selectArrayContext, this); + } + + this.oldValue = this.value; + this.value = newValue; + this.synchronizeOptions(); + this.notify(); + + if (!this.initialSync) { + this.initialSync = true; + this.observerLocator.taskQueue.queueMicroTask(this); + } + }; + + SelectValueObserver.prototype.call = function call(context, splices) { + this.synchronizeOptions(); + }; + + SelectValueObserver.prototype.synchronizeOptions = function synchronizeOptions() { + var value = this.value; + var clear = void 0; + var isArray = void 0; + + if (value === null || value === undefined) { + clear = true; + } else if (Array.isArray(value)) { + isArray = true; + } + + var options = this.element.options; + var i = options.length; + var matcher = this.element.matcher || function (a, b) { + return a === b; + }; + + var _loop = function _loop() { + var option = options.item(i); + if (clear) { + option.selected = false; + return 'continue'; + } + var optionValue = option.hasOwnProperty('model') ? option.model : option.value; + if (isArray) { + option.selected = value.findIndex(function (item) { + return !!matcher(optionValue, item); + }) !== -1; + return 'continue'; + } + option.selected = !!matcher(optionValue, value); + }; + + while (i--) { + var _ret2 = _loop(); + + if (_ret2 === 'continue') continue; + } + }; + + SelectValueObserver.prototype.synchronizeValue = function synchronizeValue() { + var _this24 = this; + + var options = this.element.options; + var count = 0; + var value = []; + + for (var _i22 = 0, ii = options.length; _i22 < ii; _i22++) { + var _option = options.item(_i22); + if (!_option.selected) { + continue; + } + value.push(_option.hasOwnProperty('model') ? _option.model : _option.value); + count++; + } + + if (this.element.multiple) { + if (Array.isArray(this.value)) { + var _ret3 = function () { + var matcher = _this24.element.matcher || function (a, b) { + return a === b; + }; + + var i = 0; + + var _loop2 = function _loop2() { + var a = _this24.value[i]; + if (value.findIndex(function (b) { + return matcher(a, b); + }) === -1) { + _this24.value.splice(i, 1); + } else { + i++; + } + }; + + while (i < _this24.value.length) { + _loop2(); + } + + i = 0; + + var _loop3 = function _loop3() { + var a = value[i]; + if (_this24.value.findIndex(function (b) { + return matcher(a, b); + }) === -1) { + _this24.value.push(a); + } + i++; + }; + + while (i < value.length) { + _loop3(); + } + return { + v: void 0 + }; + }(); + + if ((typeof _ret3 === 'undefined' ? 'undefined' : _typeof(_ret3)) === "object") return _ret3.v; + } + } else { + if (count === 0) { + value = null; + } else { + value = value[0]; + } + } + + if (value !== this.value) { + this.oldValue = this.value; + this.value = value; + this.notify(); + } + }; + + SelectValueObserver.prototype.notify = function notify() { + var oldValue = this.oldValue; + var newValue = this.value; + + this.callSubscribers(newValue, oldValue); + }; + + SelectValueObserver.prototype.subscribe = function subscribe(context, callable) { + if (!this.hasSubscribers()) { + this.disposeHandler = this.handler.subscribe(this.element, this.synchronizeValue.bind(this, false)); + } + this.addSubscriber(context, callable); + }; + + SelectValueObserver.prototype.unsubscribe = function unsubscribe(context, callable) { + if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) { + this.disposeHandler(); + this.disposeHandler = null; + } + }; + + SelectValueObserver.prototype.bind = function bind() { + var _this25 = this; + + this.domObserver = _aureliaPal.DOM.createMutationObserver(function () { + _this25.synchronizeOptions(); + _this25.synchronizeValue(); + }); + this.domObserver.observe(this.element, { childList: true, subtree: true }); + }; + + SelectValueObserver.prototype.unbind = function unbind() { + this.domObserver.disconnect(); + this.domObserver = null; + + if (this.arrayObserver) { + this.arrayObserver.unsubscribe(selectArrayContext, this); + this.arrayObserver = null; + } + }; + + return SelectValueObserver; + }()) || _class10); + + var ClassObserver = exports.ClassObserver = function () { + function ClassObserver(element) { + + + this.element = element; + this.doNotCache = true; + this.value = ''; + this.version = 0; + } + + ClassObserver.prototype.getValue = function getValue() { + return this.value; + }; + + ClassObserver.prototype.setValue = function setValue(newValue) { + var nameIndex = this.nameIndex || {}; + var version = this.version; + var names = void 0; + var name = void 0; + + if (newValue !== null && newValue !== undefined && newValue.length) { + names = newValue.split(/\s+/); + for (var _i23 = 0, length = names.length; _i23 < length; _i23++) { + name = names[_i23]; + if (name === '') { + continue; + } + nameIndex[name] = version; + this.element.classList.add(name); + } + } + + this.value = newValue; + this.nameIndex = nameIndex; + this.version += 1; + + if (version === 0) { + return; + } + + version -= 1; + for (name in nameIndex) { + if (!nameIndex.hasOwnProperty(name) || nameIndex[name] !== version) { + continue; + } + this.element.classList.remove(name); + } + }; + + ClassObserver.prototype.subscribe = function subscribe() { + throw new Error('Observation of a "' + this.element.nodeName + '" element\'s "class" property is not supported.'); + }; + + return ClassObserver; + }(); + + function hasDeclaredDependencies(descriptor) { + return !!(descriptor && descriptor.get && descriptor.get.dependencies); + } + + function declarePropertyDependencies(ctor, propertyName, dependencies) { + var descriptor = Object.getOwnPropertyDescriptor(ctor.prototype, propertyName); + descriptor.get.dependencies = dependencies; + } + + function computedFrom() { + for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) { + rest[_key] = arguments[_key]; + } + + return function (target, key, descriptor) { + descriptor.get.dependencies = rest; + return descriptor; + }; + } + + var ComputedExpression = exports.ComputedExpression = function (_Expression19) { + _inherits(ComputedExpression, _Expression19); + + function ComputedExpression(name, dependencies) { + + + var _this26 = _possibleConstructorReturn(this, _Expression19.call(this)); + + _this26.name = name; + _this26.dependencies = dependencies; + _this26.isAssignable = true; + return _this26; + } + + ComputedExpression.prototype.evaluate = function evaluate(scope, lookupFunctions) { + return scope.bindingContext[this.name]; + }; + + ComputedExpression.prototype.assign = function assign(scope, value) { + scope.bindingContext[this.name] = value; + }; + + ComputedExpression.prototype.accept = function accept(visitor) { + throw new Error('not implemented'); + }; + + ComputedExpression.prototype.connect = function connect(binding, scope) { + var dependencies = this.dependencies; + var i = dependencies.length; + while (i--) { + dependencies[i].connect(binding, scope); + } + }; + + return ComputedExpression; + }(Expression); + + function createComputedObserver(obj, propertyName, descriptor, observerLocator) { + var dependencies = descriptor.get.dependencies; + if (!(dependencies instanceof ComputedExpression)) { + var _i24 = dependencies.length; + while (_i24--) { + dependencies[_i24] = observerLocator.parser.parse(dependencies[_i24]); + } + dependencies = descriptor.get.dependencies = new ComputedExpression(propertyName, dependencies); + } + + var scope = { bindingContext: obj, overrideContext: createOverrideContext(obj) }; + return new ExpressionObserver(scope, dependencies, observerLocator); + } + + var elements = exports.elements = { + a: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'target', 'transform', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], + altGlyph: ['class', 'dx', 'dy', 'externalResourcesRequired', 'format', 'glyphRef', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], + altGlyphDef: ['id', 'xml:base', 'xml:lang', 'xml:space'], + altGlyphItem: ['id', 'xml:base', 'xml:lang', 'xml:space'], + animate: ['accumulate', 'additive', 'attributeName', 'attributeType', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], + animateColor: ['accumulate', 'additive', 'attributeName', 'attributeType', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], + animateMotion: ['accumulate', 'additive', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keyPoints', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'origin', 'path', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'rotate', 'systemLanguage', 'to', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], + animateTransform: ['accumulate', 'additive', 'attributeName', 'attributeType', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'type', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], + circle: ['class', 'cx', 'cy', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'r', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], + clipPath: ['class', 'clipPathUnits', 'externalResourcesRequired', 'id', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], + 'color-profile': ['id', 'local', 'name', 'rendering-intent', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], + cursor: ['externalResourcesRequired', 'id', 'requiredExtensions', 'requiredFeatures', 'systemLanguage', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], + defs: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], + desc: ['class', 'id', 'style', 'xml:base', 'xml:lang', 'xml:space'], + ellipse: ['class', 'cx', 'cy', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rx', 'ry', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], + feBlend: ['class', 'height', 'id', 'in', 'in2', 'mode', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + feColorMatrix: ['class', 'height', 'id', 'in', 'result', 'style', 'type', 'values', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + feComponentTransfer: ['class', 'height', 'id', 'in', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + feComposite: ['class', 'height', 'id', 'in', 'in2', 'k1', 'k2', 'k3', 'k4', 'operator', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + feConvolveMatrix: ['bias', 'class', 'divisor', 'edgeMode', 'height', 'id', 'in', 'kernelMatrix', 'kernelUnitLength', 'order', 'preserveAlpha', 'result', 'style', 'targetX', 'targetY', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + feDiffuseLighting: ['class', 'diffuseConstant', 'height', 'id', 'in', 'kernelUnitLength', 'result', 'style', 'surfaceScale', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + feDisplacementMap: ['class', 'height', 'id', 'in', 'in2', 'result', 'scale', 'style', 'width', 'x', 'xChannelSelector', 'xml:base', 'xml:lang', 'xml:space', 'y', 'yChannelSelector'], + feDistantLight: ['azimuth', 'elevation', 'id', 'xml:base', 'xml:lang', 'xml:space'], + feFlood: ['class', 'height', 'id', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + feFuncA: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'], + feFuncB: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'], + feFuncG: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'], + feFuncR: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'], + feGaussianBlur: ['class', 'height', 'id', 'in', 'result', 'stdDeviation', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + feImage: ['class', 'externalResourcesRequired', 'height', 'id', 'preserveAspectRatio', 'result', 'style', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], + feMerge: ['class', 'height', 'id', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + feMergeNode: ['id', 'xml:base', 'xml:lang', 'xml:space'], + feMorphology: ['class', 'height', 'id', 'in', 'operator', 'radius', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + feOffset: ['class', 'dx', 'dy', 'height', 'id', 'in', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + fePointLight: ['id', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y', 'z'], + feSpecularLighting: ['class', 'height', 'id', 'in', 'kernelUnitLength', 'result', 'specularConstant', 'specularExponent', 'style', 'surfaceScale', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + feSpotLight: ['id', 'limitingConeAngle', 'pointsAtX', 'pointsAtY', 'pointsAtZ', 'specularExponent', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y', 'z'], + feTile: ['class', 'height', 'id', 'in', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + feTurbulence: ['baseFrequency', 'class', 'height', 'id', 'numOctaves', 'result', 'seed', 'stitchTiles', 'style', 'type', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + filter: ['class', 'externalResourcesRequired', 'filterRes', 'filterUnits', 'height', 'id', 'primitiveUnits', 'style', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], + font: ['class', 'externalResourcesRequired', 'horiz-adv-x', 'horiz-origin-x', 'horiz-origin-y', 'id', 'style', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'xml:base', 'xml:lang', 'xml:space'], + 'font-face': ['accent-height', 'alphabetic', 'ascent', 'bbox', 'cap-height', 'descent', 'font-family', 'font-size', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'hanging', 'id', 'ideographic', 'mathematical', 'overline-position', 'overline-thickness', 'panose-1', 'slope', 'stemh', 'stemv', 'strikethrough-position', 'strikethrough-thickness', 'underline-position', 'underline-thickness', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'widths', 'x-height', 'xml:base', 'xml:lang', 'xml:space'], + 'font-face-format': ['id', 'string', 'xml:base', 'xml:lang', 'xml:space'], + 'font-face-name': ['id', 'name', 'xml:base', 'xml:lang', 'xml:space'], + 'font-face-src': ['id', 'xml:base', 'xml:lang', 'xml:space'], + 'font-face-uri': ['id', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], + foreignObject: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + g: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], + glyph: ['arabic-form', 'class', 'd', 'glyph-name', 'horiz-adv-x', 'id', 'lang', 'orientation', 'style', 'unicode', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'xml:base', 'xml:lang', 'xml:space'], + glyphRef: ['class', 'dx', 'dy', 'format', 'glyphRef', 'id', 'style', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], + hkern: ['g1', 'g2', 'id', 'k', 'u1', 'u2', 'xml:base', 'xml:lang', 'xml:space'], + image: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'preserveAspectRatio', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], + line: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'x1', 'x2', 'xml:base', 'xml:lang', 'xml:space', 'y1', 'y2'], + linearGradient: ['class', 'externalResourcesRequired', 'gradientTransform', 'gradientUnits', 'id', 'spreadMethod', 'style', 'x1', 'x2', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y1', 'y2'], + marker: ['class', 'externalResourcesRequired', 'id', 'markerHeight', 'markerUnits', 'markerWidth', 'orient', 'preserveAspectRatio', 'refX', 'refY', 'style', 'viewBox', 'xml:base', 'xml:lang', 'xml:space'], + mask: ['class', 'externalResourcesRequired', 'height', 'id', 'maskContentUnits', 'maskUnits', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + metadata: ['id', 'xml:base', 'xml:lang', 'xml:space'], + 'missing-glyph': ['class', 'd', 'horiz-adv-x', 'id', 'style', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'xml:base', 'xml:lang', 'xml:space'], + mpath: ['externalResourcesRequired', 'id', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], + path: ['class', 'd', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'pathLength', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], + pattern: ['class', 'externalResourcesRequired', 'height', 'id', 'patternContentUnits', 'patternTransform', 'patternUnits', 'preserveAspectRatio', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'viewBox', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], + polygon: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'points', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], + polyline: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'points', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], + radialGradient: ['class', 'cx', 'cy', 'externalResourcesRequired', 'fx', 'fy', 'gradientTransform', 'gradientUnits', 'id', 'r', 'spreadMethod', 'style', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], + rect: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rx', 'ry', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + script: ['externalResourcesRequired', 'id', 'type', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], + set: ['attributeName', 'attributeType', 'begin', 'dur', 'end', 'externalResourcesRequired', 'fill', 'id', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], + stop: ['class', 'id', 'offset', 'style', 'xml:base', 'xml:lang', 'xml:space'], + style: ['id', 'media', 'title', 'type', 'xml:base', 'xml:lang', 'xml:space'], + svg: ['baseProfile', 'class', 'contentScriptType', 'contentStyleType', 'externalResourcesRequired', 'height', 'id', 'onabort', 'onactivate', 'onclick', 'onerror', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onresize', 'onscroll', 'onunload', 'onzoom', 'preserveAspectRatio', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'version', 'viewBox', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y', 'zoomAndPan'], + switch: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], + symbol: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'preserveAspectRatio', 'style', 'viewBox', 'xml:base', 'xml:lang', 'xml:space'], + text: ['class', 'dx', 'dy', 'externalResourcesRequired', 'id', 'lengthAdjust', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'textLength', 'transform', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + textPath: ['class', 'externalResourcesRequired', 'id', 'lengthAdjust', 'method', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'spacing', 'startOffset', 'style', 'systemLanguage', 'textLength', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], + title: ['class', 'id', 'style', 'xml:base', 'xml:lang', 'xml:space'], + tref: ['class', 'dx', 'dy', 'externalResourcesRequired', 'id', 'lengthAdjust', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'textLength', 'x', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], + tspan: ['class', 'dx', 'dy', 'externalResourcesRequired', 'id', 'lengthAdjust', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'textLength', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], + use: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], + view: ['externalResourcesRequired', 'id', 'preserveAspectRatio', 'viewBox', 'viewTarget', 'xml:base', 'xml:lang', 'xml:space', 'zoomAndPan'], + vkern: ['g1', 'g2', 'id', 'k', 'u1', 'u2', 'xml:base', 'xml:lang', 'xml:space'] + }; + var presentationElements = exports.presentationElements = { + 'a': true, + 'altGlyph': true, + 'animate': true, + 'animateColor': true, + 'circle': true, + 'clipPath': true, + 'defs': true, + 'ellipse': true, + 'feBlend': true, + 'feColorMatrix': true, + 'feComponentTransfer': true, + 'feComposite': true, + 'feConvolveMatrix': true, + 'feDiffuseLighting': true, + 'feDisplacementMap': true, + 'feFlood': true, + 'feGaussianBlur': true, + 'feImage': true, + 'feMerge': true, + 'feMorphology': true, + 'feOffset': true, + 'feSpecularLighting': true, + 'feTile': true, + 'feTurbulence': true, + 'filter': true, + 'font': true, + 'foreignObject': true, + 'g': true, + 'glyph': true, + 'glyphRef': true, + 'image': true, + 'line': true, + 'linearGradient': true, + 'marker': true, + 'mask': true, + 'missing-glyph': true, + 'path': true, + 'pattern': true, + 'polygon': true, + 'polyline': true, + 'radialGradient': true, + 'rect': true, + 'stop': true, + 'svg': true, + 'switch': true, + 'symbol': true, + 'text': true, + 'textPath': true, + 'tref': true, + 'tspan': true, + 'use': true + }; + + var presentationAttributes = exports.presentationAttributes = { + 'alignment-baseline': true, + 'baseline-shift': true, + 'clip-path': true, + 'clip-rule': true, + 'clip': true, + 'color-interpolation-filters': true, + 'color-interpolation': true, + 'color-profile': true, + 'color-rendering': true, + 'color': true, + 'cursor': true, + 'direction': true, + 'display': true, + 'dominant-baseline': true, + 'enable-background': true, + 'fill-opacity': true, + 'fill-rule': true, + 'fill': true, + 'filter': true, + 'flood-color': true, + 'flood-opacity': true, + 'font-family': true, + 'font-size-adjust': true, + 'font-size': true, + 'font-stretch': true, + 'font-style': true, + 'font-variant': true, + 'font-weight': true, + 'glyph-orientation-horizontal': true, + 'glyph-orientation-vertical': true, + 'image-rendering': true, + 'kerning': true, + 'letter-spacing': true, + 'lighting-color': true, + 'marker-end': true, + 'marker-mid': true, + 'marker-start': true, + 'mask': true, + 'opacity': true, + 'overflow': true, + 'pointer-events': true, + 'shape-rendering': true, + 'stop-color': true, + 'stop-opacity': true, + 'stroke-dasharray': true, + 'stroke-dashoffset': true, + 'stroke-linecap': true, + 'stroke-linejoin': true, + 'stroke-miterlimit': true, + 'stroke-opacity': true, + 'stroke-width': true, + 'stroke': true, + 'text-anchor': true, + 'text-decoration': true, + 'text-rendering': true, + 'unicode-bidi': true, + 'visibility': true, + 'word-spacing': true, + 'writing-mode': true + }; + + function createElement(html) { + var div = _aureliaPal.DOM.createElement('div'); + div.innerHTML = html; + return div.firstChild; + } + + var SVGAnalyzer = exports.SVGAnalyzer = function () { + function SVGAnalyzer() { + + + if (createElement('').firstElementChild.nodeName === 'altglyph' && elements.altGlyph) { + elements.altglyph = elements.altGlyph; + delete elements.altGlyph; + elements.altglyphdef = elements.altGlyphDef; + delete elements.altGlyphDef; + elements.altglyphitem = elements.altGlyphItem; + delete elements.altGlyphItem; + elements.glyphref = elements.glyphRef; + delete elements.glyphRef; + } + } + + SVGAnalyzer.prototype.isStandardSvgAttribute = function isStandardSvgAttribute(nodeName, attributeName) { + return presentationElements[nodeName] && presentationAttributes[attributeName] || elements[nodeName] && elements[nodeName].indexOf(attributeName) !== -1; + }; + + return SVGAnalyzer; + }(); + + var ObserverLocator = exports.ObserverLocator = (_temp = _class11 = function () { + function ObserverLocator(taskQueue, eventManager, dirtyChecker, svgAnalyzer, parser) { + + + this.taskQueue = taskQueue; + this.eventManager = eventManager; + this.dirtyChecker = dirtyChecker; + this.svgAnalyzer = svgAnalyzer; + this.parser = parser; + this.adapters = []; + this.logger = LogManager.getLogger('observer-locator'); + } + + ObserverLocator.prototype.getObserver = function getObserver(obj, propertyName) { + var observersLookup = obj.__observers__; + var observer = void 0; + + if (observersLookup && propertyName in observersLookup) { + return observersLookup[propertyName]; + } + + observer = this.createPropertyObserver(obj, propertyName); + + if (!observer.doNotCache) { + if (observersLookup === undefined) { + observersLookup = this.getOrCreateObserversLookup(obj); + } + + observersLookup[propertyName] = observer; + } + + return observer; + }; + + ObserverLocator.prototype.getOrCreateObserversLookup = function getOrCreateObserversLookup(obj) { + return obj.__observers__ || this.createObserversLookup(obj); + }; + + ObserverLocator.prototype.createObserversLookup = function createObserversLookup(obj) { + var value = {}; + + if (!Reflect.defineProperty(obj, '__observers__', { + enumerable: false, + configurable: false, + writable: false, + value: value + })) { + this.logger.warn('Cannot add observers to object', obj); + } + + return value; + }; + + ObserverLocator.prototype.addAdapter = function addAdapter(adapter) { + this.adapters.push(adapter); + }; + + ObserverLocator.prototype.getAdapterObserver = function getAdapterObserver(obj, propertyName, descriptor) { + for (var _i25 = 0, ii = this.adapters.length; _i25 < ii; _i25++) { + var adapter = this.adapters[_i25]; + var observer = adapter.getObserver(obj, propertyName, descriptor); + if (observer) { + return observer; + } + } + return null; + }; + + ObserverLocator.prototype.createPropertyObserver = function createPropertyObserver(obj, propertyName) { + var descriptor = void 0; + var handler = void 0; + var xlinkResult = void 0; + + if (!(obj instanceof Object)) { + return new PrimitiveObserver(obj, propertyName); + } + + if (obj instanceof _aureliaPal.DOM.Element) { + if (propertyName === 'class') { + return new ClassObserver(obj); + } + if (propertyName === 'style' || propertyName === 'css') { + return new StyleObserver(obj, propertyName); + } + handler = this.eventManager.getElementHandler(obj, propertyName); + if (propertyName === 'value' && obj.tagName.toLowerCase() === 'select') { + return new SelectValueObserver(obj, handler, this); + } + if (propertyName === 'checked' && obj.tagName.toLowerCase() === 'input') { + return new CheckedObserver(obj, handler, this); + } + if (handler) { + return new ValueAttributeObserver(obj, propertyName, handler); + } + xlinkResult = /^xlink:(.+)$/.exec(propertyName); + if (xlinkResult) { + return new XLinkAttributeObserver(obj, propertyName, xlinkResult[1]); + } + if (propertyName === 'role' && (obj instanceof _aureliaPal.DOM.Element || obj instanceof _aureliaPal.DOM.SVGElement) || /^\w+:|^data-|^aria-/.test(propertyName) || obj instanceof _aureliaPal.DOM.SVGElement && this.svgAnalyzer.isStandardSvgAttribute(obj.nodeName, propertyName)) { + return new DataAttributeObserver(obj, propertyName); + } + } + + descriptor = Object.getPropertyDescriptor(obj, propertyName); + + if (hasDeclaredDependencies(descriptor)) { + return createComputedObserver(obj, propertyName, descriptor, this); + } + + if (descriptor) { + var existingGetterOrSetter = descriptor.get || descriptor.set; + if (existingGetterOrSetter) { + if (existingGetterOrSetter.getObserver) { + return existingGetterOrSetter.getObserver(obj); + } + + var adapterObserver = this.getAdapterObserver(obj, propertyName, descriptor); + if (adapterObserver) { + return adapterObserver; + } + return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName); + } + } + + if (obj instanceof Array) { + if (propertyName === 'length') { + return this.getArrayObserver(obj).getLengthObserver(); + } + + return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName); + } else if (obj instanceof Map) { + if (propertyName === 'size') { + return this.getMapObserver(obj).getLengthObserver(); + } + + return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName); + } else if (obj instanceof Set) { + if (propertyName === 'size') { + return this.getSetObserver(obj).getLengthObserver(); + } + + return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName); + } + + return new SetterObserver(this.taskQueue, obj, propertyName); + }; + + ObserverLocator.prototype.getAccessor = function getAccessor(obj, propertyName) { + if (obj instanceof _aureliaPal.DOM.Element) { + if (propertyName === 'class' || propertyName === 'style' || propertyName === 'css' || propertyName === 'value' && (obj.tagName.toLowerCase() === 'input' || obj.tagName.toLowerCase() === 'select') || propertyName === 'checked' && obj.tagName.toLowerCase() === 'input' || propertyName === 'model' && obj.tagName.toLowerCase() === 'input' || /^xlink:.+$/.exec(propertyName)) { + return this.getObserver(obj, propertyName); + } + if (/^\w+:|^data-|^aria-/.test(propertyName) || obj instanceof _aureliaPal.DOM.SVGElement && this.svgAnalyzer.isStandardSvgAttribute(obj.nodeName, propertyName)) { + return dataAttributeAccessor; + } + } + return propertyAccessor; + }; + + ObserverLocator.prototype.getArrayObserver = function getArrayObserver(array) { + return _getArrayObserver(this.taskQueue, array); + }; + + ObserverLocator.prototype.getMapObserver = function getMapObserver(map) { + return _getMapObserver(this.taskQueue, map); + }; + + ObserverLocator.prototype.getSetObserver = function getSetObserver(set) { + return _getSetObserver(this.taskQueue, set); + }; + + return ObserverLocator; + }(), _class11.inject = [_aureliaTaskQueue.TaskQueue, EventManager, DirtyChecker, SVGAnalyzer, Parser], _temp); + + var ObjectObservationAdapter = exports.ObjectObservationAdapter = function () { + function ObjectObservationAdapter() { + + } + + ObjectObservationAdapter.prototype.getObserver = function getObserver(object, propertyName, descriptor) { + throw new Error('BindingAdapters must implement getObserver(object, propertyName).'); + }; + + return ObjectObservationAdapter; + }(); + + var BindingExpression = exports.BindingExpression = function () { + function BindingExpression(observerLocator, targetProperty, sourceExpression, mode, lookupFunctions, attribute) { + + + this.observerLocator = observerLocator; + this.targetProperty = targetProperty; + this.sourceExpression = sourceExpression; + this.mode = mode; + this.lookupFunctions = lookupFunctions; + this.attribute = attribute; + this.discrete = false; + } + + BindingExpression.prototype.createBinding = function createBinding(target) { + return new Binding(this.observerLocator, this.sourceExpression, target, this.targetProperty, this.mode, this.lookupFunctions); + }; + + return BindingExpression; + }(); + + var targetContext = 'Binding:target'; + + var Binding = exports.Binding = (_dec10 = connectable(), _dec10(_class12 = function () { + function Binding(observerLocator, sourceExpression, target, targetProperty, mode, lookupFunctions) { + + + this.observerLocator = observerLocator; + this.sourceExpression = sourceExpression; + this.target = target; + this.targetProperty = targetProperty; + this.mode = mode; + this.lookupFunctions = lookupFunctions; + } + + Binding.prototype.updateTarget = function updateTarget(value) { + this.targetObserver.setValue(value, this.target, this.targetProperty); + }; + + Binding.prototype.updateSource = function updateSource(value) { + this.sourceExpression.assign(this.source, value, this.lookupFunctions); + }; + + Binding.prototype.call = function call(context, newValue, oldValue) { + if (!this.isBound) { + return; + } + if (context === sourceContext) { + oldValue = this.targetObserver.getValue(this.target, this.targetProperty); + newValue = this.sourceExpression.evaluate(this.source, this.lookupFunctions); + if (newValue !== oldValue) { + this.updateTarget(newValue); + } + if (this.mode !== bindingMode.oneTime) { + this._version++; + this.sourceExpression.connect(this, this.source); + this.unobserve(false); + } + return; + } + if (context === targetContext) { + if (newValue !== this.sourceExpression.evaluate(this.source, this.lookupFunctions)) { + this.updateSource(newValue); + } + return; + } + throw new Error('Unexpected call context ' + context); + }; + + Binding.prototype.bind = function bind(source) { + if (this.isBound) { + if (this.source === source) { + return; + } + this.unbind(); + } + this.isBound = true; + this.source = source; + + if (this.sourceExpression.bind) { + this.sourceExpression.bind(this, source, this.lookupFunctions); + } + + var mode = this.mode; + if (!this.targetObserver) { + var method = mode === bindingMode.twoWay ? 'getObserver' : 'getAccessor'; + this.targetObserver = this.observerLocator[method](this.target, this.targetProperty); + } + + if ('bind' in this.targetObserver) { + this.targetObserver.bind(); + } + var value = this.sourceExpression.evaluate(source, this.lookupFunctions); + this.updateTarget(value); + + if (mode === bindingMode.oneWay) { + enqueueBindingConnect(this); + } else if (mode === bindingMode.twoWay) { + this.sourceExpression.connect(this, source); + this.targetObserver.subscribe(targetContext, this); + } + }; + + Binding.prototype.unbind = function unbind() { + if (!this.isBound) { + return; + } + this.isBound = false; + if (this.sourceExpression.unbind) { + this.sourceExpression.unbind(this, this.source); + } + this.source = null; + if ('unbind' in this.targetObserver) { + this.targetObserver.unbind(); + } + if (this.targetObserver.unsubscribe) { + this.targetObserver.unsubscribe(targetContext, this); + } + this.unobserve(true); + }; + + Binding.prototype.connect = function connect(evaluate) { + if (!this.isBound) { + return; + } + if (evaluate) { + var value = this.sourceExpression.evaluate(this.source, this.lookupFunctions); + this.updateTarget(value); + } + this.sourceExpression.connect(this, this.source); + }; + + return Binding; + }()) || _class12); + + var CallExpression = exports.CallExpression = function () { + function CallExpression(observerLocator, targetProperty, sourceExpression, lookupFunctions) { + + + this.observerLocator = observerLocator; + this.targetProperty = targetProperty; + this.sourceExpression = sourceExpression; + this.lookupFunctions = lookupFunctions; + } + + CallExpression.prototype.createBinding = function createBinding(target) { + return new Call(this.observerLocator, this.sourceExpression, target, this.targetProperty, this.lookupFunctions); + }; + + return CallExpression; + }(); + + var Call = exports.Call = function () { + function Call(observerLocator, sourceExpression, target, targetProperty, lookupFunctions) { + + + this.sourceExpression = sourceExpression; + this.target = target; + this.targetProperty = observerLocator.getObserver(target, targetProperty); + this.lookupFunctions = lookupFunctions; + } + + Call.prototype.callSource = function callSource($event) { + var overrideContext = this.source.overrideContext; + Object.assign(overrideContext, $event); + overrideContext.$event = $event; + var mustEvaluate = true; + var result = this.sourceExpression.evaluate(this.source, this.lookupFunctions, mustEvaluate); + delete overrideContext.$event; + for (var prop in $event) { + delete overrideContext[prop]; + } + return result; + }; + + Call.prototype.bind = function bind(source) { + var _this27 = this; + + if (this.isBound) { + if (this.source === source) { + return; + } + this.unbind(); + } + this.isBound = true; + this.source = source; + + if (this.sourceExpression.bind) { + this.sourceExpression.bind(this, source, this.lookupFunctions); + } + this.targetProperty.setValue(function ($event) { + return _this27.callSource($event); + }); + }; + + Call.prototype.unbind = function unbind() { + if (!this.isBound) { + return; + } + this.isBound = false; + if (this.sourceExpression.unbind) { + this.sourceExpression.unbind(this, this.source); + } + this.source = null; + this.targetProperty.setValue(null); + }; + + return Call; + }(); + + var ValueConverterResource = exports.ValueConverterResource = function () { + function ValueConverterResource(name) { + + + this.name = name; + } + + ValueConverterResource.convention = function convention(name) { + if (name.endsWith('ValueConverter')) { + return new ValueConverterResource(camelCase(name.substring(0, name.length - 14))); + } + }; + + ValueConverterResource.prototype.initialize = function initialize(container, target) { + this.instance = container.get(target); + }; + + ValueConverterResource.prototype.register = function register(registry, name) { + registry.registerValueConverter(name || this.name, this.instance); + }; + + ValueConverterResource.prototype.load = function load(container, target) {}; + + return ValueConverterResource; + }(); + + function valueConverter(nameOrTarget) { + if (nameOrTarget === undefined || typeof nameOrTarget === 'string') { + return function (target) { + _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new ValueConverterResource(nameOrTarget), target); + }; + } + + _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new ValueConverterResource(), nameOrTarget); + } + + var BindingBehaviorResource = exports.BindingBehaviorResource = function () { + function BindingBehaviorResource(name) { + + + this.name = name; + } + + BindingBehaviorResource.convention = function convention(name) { + if (name.endsWith('BindingBehavior')) { + return new BindingBehaviorResource(camelCase(name.substring(0, name.length - 15))); + } + }; + + BindingBehaviorResource.prototype.initialize = function initialize(container, target) { + this.instance = container.get(target); + }; + + BindingBehaviorResource.prototype.register = function register(registry, name) { + registry.registerBindingBehavior(name || this.name, this.instance); + }; + + BindingBehaviorResource.prototype.load = function load(container, target) {}; + + return BindingBehaviorResource; + }(); + + function bindingBehavior(nameOrTarget) { + if (nameOrTarget === undefined || typeof nameOrTarget === 'string') { + return function (target) { + _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new BindingBehaviorResource(nameOrTarget), target); + }; + } + + _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new BindingBehaviorResource(), nameOrTarget); + } + + var ListenerExpression = exports.ListenerExpression = function () { + function ListenerExpression(eventManager, targetEvent, sourceExpression, delegate, preventDefault, lookupFunctions) { + + + this.eventManager = eventManager; + this.targetEvent = targetEvent; + this.sourceExpression = sourceExpression; + this.delegate = delegate; + this.discrete = true; + this.preventDefault = preventDefault; + this.lookupFunctions = lookupFunctions; + } + + ListenerExpression.prototype.createBinding = function createBinding(target) { + return new Listener(this.eventManager, this.targetEvent, this.delegate, this.sourceExpression, target, this.preventDefault, this.lookupFunctions); + }; + + return ListenerExpression; + }(); + + var Listener = exports.Listener = function () { + function Listener(eventManager, targetEvent, delegate, sourceExpression, target, preventDefault, lookupFunctions) { + + + this.eventManager = eventManager; + this.targetEvent = targetEvent; + this.delegate = delegate; + this.sourceExpression = sourceExpression; + this.target = target; + this.preventDefault = preventDefault; + this.lookupFunctions = lookupFunctions; + } + + Listener.prototype.callSource = function callSource(event) { + var overrideContext = this.source.overrideContext; + overrideContext.$event = event; + var mustEvaluate = true; + var result = this.sourceExpression.evaluate(this.source, this.lookupFunctions, mustEvaluate); + delete overrideContext.$event; + if (result !== true && this.preventDefault) { + event.preventDefault(); + } + return result; + }; + + Listener.prototype.bind = function bind(source) { + var _this28 = this; + + if (this.isBound) { + if (this.source === source) { + return; + } + this.unbind(); + } + this.isBound = true; + this.source = source; + + if (this.sourceExpression.bind) { + this.sourceExpression.bind(this, source, this.lookupFunctions); + } + this._disposeListener = this.eventManager.addEventListener(this.target, this.targetEvent, function (event) { + return _this28.callSource(event); + }, this.delegate); + }; + + Listener.prototype.unbind = function unbind() { + if (!this.isBound) { + return; + } + this.isBound = false; + if (this.sourceExpression.unbind) { + this.sourceExpression.unbind(this, this.source); + } + this.source = null; + this._disposeListener(); + this._disposeListener = null; + }; + + return Listener; + }(); + + function getAU(element) { + var au = element.au; + + if (au === undefined) { + throw new Error('No Aurelia APIs are defined for the element: "' + element.tagName + '".'); + } + + return au; + } + + var NameExpression = exports.NameExpression = function () { + function NameExpression(sourceExpression, apiName, lookupFunctions) { + + + this.sourceExpression = sourceExpression; + this.apiName = apiName; + this.lookupFunctions = lookupFunctions; + this.discrete = true; + } + + NameExpression.prototype.createBinding = function createBinding(target) { + return new NameBinder(this.sourceExpression, NameExpression.locateAPI(target, this.apiName), this.lookupFunctions); + }; + + NameExpression.locateAPI = function locateAPI(element, apiName) { + switch (apiName) { + case 'element': + return element; + case 'controller': + return getAU(element).controller; + case 'view-model': + return getAU(element).controller.viewModel; + case 'view': + return getAU(element).controller.view; + default: + var target = getAU(element)[apiName]; + + if (target === undefined) { + throw new Error('Attempted to reference "' + apiName + '", but it was not found amongst the target\'s API.'); + } + + return target.viewModel; + } + }; + + return NameExpression; + }(); + + var NameBinder = function () { + function NameBinder(sourceExpression, target, lookupFunctions) { + + + this.sourceExpression = sourceExpression; + this.target = target; + this.lookupFunctions = lookupFunctions; + } + + NameBinder.prototype.bind = function bind(source) { + if (this.isBound) { + if (this.source === source) { + return; + } + this.unbind(); + } + this.isBound = true; + this.source = source; + if (this.sourceExpression.bind) { + this.sourceExpression.bind(this, source, this.lookupFunctions); + } + this.sourceExpression.assign(this.source, this.target, this.lookupFunctions); + }; + + NameBinder.prototype.unbind = function unbind() { + if (!this.isBound) { + return; + } + this.isBound = false; + if (this.sourceExpression.evaluate(this.source, this.lookupFunctions) === this.target) { + this.sourceExpression.assign(this.source, null, this.lookupFunctions); + } + if (this.sourceExpression.unbind) { + this.sourceExpression.unbind(this, this.source); + } + this.source = null; + }; + + return NameBinder; + }(); + + var LookupFunctions = { + bindingBehaviors: function bindingBehaviors(name) { + return null; + }, + valueConverters: function valueConverters(name) { + return null; + } + }; + + var BindingEngine = exports.BindingEngine = (_temp2 = _class13 = function () { + function BindingEngine(observerLocator, parser) { + + + this.observerLocator = observerLocator; + this.parser = parser; + } + + BindingEngine.prototype.createBindingExpression = function createBindingExpression(targetProperty, sourceExpression) { + var mode = arguments.length <= 2 || arguments[2] === undefined ? bindingMode.oneWay : arguments[2]; + var lookupFunctions = arguments.length <= 3 || arguments[3] === undefined ? LookupFunctions : arguments[3]; + + return new BindingExpression(this.observerLocator, targetProperty, this.parser.parse(sourceExpression), mode, lookupFunctions); + }; + + BindingEngine.prototype.propertyObserver = function propertyObserver(obj, propertyName) { + var _this29 = this; + + return { + subscribe: function subscribe(callback) { + var observer = _this29.observerLocator.getObserver(obj, propertyName); + observer.subscribe(callback); + return { + dispose: function dispose() { + return observer.unsubscribe(callback); + } + }; + } + }; + }; + + BindingEngine.prototype.collectionObserver = function collectionObserver(collection) { + var _this30 = this; + + return { + subscribe: function subscribe(callback) { + var observer = void 0; + if (collection instanceof Array) { + observer = _this30.observerLocator.getArrayObserver(collection); + } else if (collection instanceof Map) { + observer = _this30.observerLocator.getMapObserver(collection); + } else if (collection instanceof Set) { + observer = _this30.observerLocator.getSetObserver(collection); + } else { + throw new Error('collection must be an instance of Array, Map or Set.'); + } + observer.subscribe(callback); + return { + dispose: function dispose() { + return observer.unsubscribe(callback); + } + }; + } + }; + }; + + BindingEngine.prototype.expressionObserver = function expressionObserver(bindingContext, expression) { + var scope = { bindingContext: bindingContext, overrideContext: createOverrideContext(bindingContext) }; + return new ExpressionObserver(scope, this.parser.parse(expression), this.observerLocator, LookupFunctions); + }; + + BindingEngine.prototype.parseExpression = function parseExpression(expression) { + return this.parser.parse(expression); + }; + + BindingEngine.prototype.registerAdapter = function registerAdapter(adapter) { + this.observerLocator.addAdapter(adapter); + }; + + return BindingEngine; + }(), _class13.inject = [ObserverLocator, Parser], _temp2); + + + var setProto = Set.prototype; + + function _getSetObserver(taskQueue, set) { + return ModifySetObserver.for(taskQueue, set); + } + + exports.getSetObserver = _getSetObserver; + + var ModifySetObserver = function (_ModifyCollectionObse3) { + _inherits(ModifySetObserver, _ModifyCollectionObse3); + + function ModifySetObserver(taskQueue, set) { + + + return _possibleConstructorReturn(this, _ModifyCollectionObse3.call(this, taskQueue, set)); + } + + ModifySetObserver.for = function _for(taskQueue, set) { + if (!('__set_observer__' in set)) { + Reflect.defineProperty(set, '__set_observer__', { + value: ModifySetObserver.create(taskQueue, set), + enumerable: false, configurable: false + }); + } + return set.__set_observer__; + }; + + ModifySetObserver.create = function create(taskQueue, set) { + var observer = new ModifySetObserver(taskQueue, set); + + var proto = setProto; + if (proto.add !== set.add || proto.delete !== set.delete || proto.clear !== set.clear) { + proto = { + add: set.add, + delete: set.delete, + clear: set.clear + }; + } + + set.add = function () { + var type = 'add'; + var oldSize = set.size; + var methodCallResult = proto.add.apply(set, arguments); + var hasValue = set.size === oldSize; + if (!hasValue) { + observer.addChangeRecord({ + type: type, + object: set, + value: Array.from(set).pop() + }); + } + return methodCallResult; + }; + + set.delete = function () { + var hasValue = set.has(arguments[0]); + var methodCallResult = proto.delete.apply(set, arguments); + if (hasValue) { + observer.addChangeRecord({ + type: 'delete', + object: set, + value: arguments[0] + }); + } + return methodCallResult; + }; + + set.clear = function () { + var methodCallResult = proto.clear.apply(set, arguments); + observer.addChangeRecord({ + type: 'clear', + object: set + }); + return methodCallResult; + }; + + return observer; + }; + + return ModifySetObserver; + }(ModifyCollectionObserver); + + function observable(targetOrConfig, key, descriptor) { + function deco(target, key, descriptor, config) { + var isClassDecorator = key === undefined; + if (isClassDecorator) { + target = target.prototype; + key = typeof config === 'string' ? config : config.name; + } + + var innerPropertyName = '_' + key; + var innerPropertyDescriptor = { + configurable: true, + enumerable: false, + writable: true + }; + + var callbackName = config && config.changeHandler || key + 'Changed'; + + if (descriptor) { + if (typeof descriptor.initializer === 'function') { + innerPropertyDescriptor.value = descriptor.initializer(); + } + } else { + descriptor = {}; + } + + if (!('enumerable' in descriptor)) { + descriptor.enumerable = true; + } + + delete descriptor.value; + delete descriptor.writable; + delete descriptor.initializer; + + Reflect.defineProperty(target, innerPropertyName, innerPropertyDescriptor); + + descriptor.get = function () { + return this[innerPropertyName]; + }; + descriptor.set = function (newValue) { + var oldValue = this[innerPropertyName]; + + this[innerPropertyName] = newValue; + Reflect.defineProperty(this, innerPropertyName, { enumerable: false }); + + if (this[callbackName]) { + this[callbackName](newValue, oldValue, key); + } + }; + + descriptor.get.dependencies = [innerPropertyName]; + + if (isClassDecorator) { + Reflect.defineProperty(target, key, descriptor); + } else { + return descriptor; + } + } + + if (key === undefined) { + return function (t, k, d) { + return deco(t, k, d, targetOrConfig); + }; + } + return deco(targetOrConfig, key, descriptor); + } +}); +define('aurelia-bootstrapper',['exports', 'aurelia-pal', 'aurelia-pal-browser', 'aurelia-polyfills'], function (exports, _aureliaPal, _aureliaPalBrowser) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.bootstrap = bootstrap; + + + var bootstrapQueue = []; + var sharedLoader = null; + var Aurelia = null; + + function onBootstrap(callback) { + return new Promise(function (resolve, reject) { + if (sharedLoader) { + resolve(callback(sharedLoader)); + } else { + bootstrapQueue.push(function () { + try { + resolve(callback(sharedLoader)); + } catch (e) { + reject(e); + } + }); + } + }); + } + + function ready(global) { + return new Promise(function (resolve, reject) { + if (global.document.readyState === 'complete') { + resolve(global.document); + } else { + global.document.addEventListener('DOMContentLoaded', completed); + global.addEventListener('load', completed); + } + + function completed() { + global.document.removeEventListener('DOMContentLoaded', completed); + global.removeEventListener('load', completed); + resolve(global.document); + } + }); + } + + function createLoader() { + if (_aureliaPal.PLATFORM.Loader) { + return Promise.resolve(new _aureliaPal.PLATFORM.Loader()); + } + + if (window.System && typeof window.System.import === 'function') { + return System.normalize('aurelia-bootstrapper').then(function (bootstrapperName) { + return System.normalize('aurelia-loader-default', bootstrapperName); + }).then(function (loaderName) { + return System.import(loaderName).then(function (m) { + return new m.DefaultLoader(); + }); + }); + } + + if (typeof window.require === 'function') { + return new Promise(function (resolve, reject) { + return require(['aurelia-loader-default'], function (m) { + return resolve(new m.DefaultLoader()); + }, reject); + }); + } + + return Promise.reject('No PLATFORM.Loader is defined and there is neither a System API (ES6) or a Require API (AMD) globally available to load your app.'); + } + + function preparePlatform(loader) { + return loader.normalize('aurelia-bootstrapper').then(function (bootstrapperName) { + return loader.normalize('aurelia-framework', bootstrapperName).then(function (frameworkName) { + loader.map('aurelia-framework', frameworkName); + + return Promise.all([loader.normalize('aurelia-dependency-injection', frameworkName).then(function (diName) { + return loader.map('aurelia-dependency-injection', diName); + }), loader.normalize('aurelia-router', bootstrapperName).then(function (routerName) { + return loader.map('aurelia-router', routerName); + }), loader.normalize('aurelia-logging-console', bootstrapperName).then(function (loggingConsoleName) { + return loader.map('aurelia-logging-console', loggingConsoleName); + })]).then(function () { + return loader.loadModule(frameworkName).then(function (m) { + return Aurelia = m.Aurelia; + }); + }); + }); + }); + } + + function handleApp(loader, appHost) { + var moduleId = appHost.getAttribute('aurelia-app') || appHost.getAttribute('data-aurelia-app'); + return config(loader, appHost, moduleId); + } + + function config(loader, appHost, configModuleId) { + var aurelia = new Aurelia(loader); + aurelia.host = appHost; + aurelia.configModuleId = configModuleId || null; + + if (configModuleId) { + return loader.loadModule(configModuleId).then(function (customConfig) { + return customConfig.configure(aurelia); + }); + } + + aurelia.use.standardConfiguration().developmentLogging(); + + return aurelia.start().then(function () { + return aurelia.setRoot(); + }); + } + + function run() { + return ready(window).then(function (doc) { + (0, _aureliaPalBrowser.initialize)(); + + var appHost = doc.querySelectorAll('[aurelia-app],[data-aurelia-app]'); + return createLoader().then(function (loader) { + return preparePlatform(loader).then(function () { + for (var i = 0, ii = appHost.length; i < ii; ++i) { + handleApp(loader, appHost[i]).catch(console.error.bind(console)); + } + + sharedLoader = loader; + for (var _i = 0, _ii = bootstrapQueue.length; _i < _ii; ++_i) { + bootstrapQueue[_i](); + } + bootstrapQueue = null; + }); + }); + }); + } + + function bootstrap(configure) { + return onBootstrap(function (loader) { + var aurelia = new Aurelia(loader); + return configure(aurelia); + }); + } + + run(); +}); +define('aurelia-framework',['exports', 'aurelia-dependency-injection', 'aurelia-binding', 'aurelia-metadata', 'aurelia-templating', 'aurelia-loader', 'aurelia-task-queue', 'aurelia-path', 'aurelia-pal', 'aurelia-logging'], function (exports, _aureliaDependencyInjection, _aureliaBinding, _aureliaMetadata, _aureliaTemplating, _aureliaLoader, _aureliaTaskQueue, _aureliaPath, _aureliaPal, _aureliaLogging) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.LogManager = exports.FrameworkConfiguration = exports.Aurelia = undefined; + Object.keys(_aureliaDependencyInjection).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _aureliaDependencyInjection[key]; + } + }); + }); + Object.keys(_aureliaBinding).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _aureliaBinding[key]; + } + }); + }); + Object.keys(_aureliaMetadata).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _aureliaMetadata[key]; + } + }); + }); + Object.keys(_aureliaTemplating).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _aureliaTemplating[key]; + } + }); + }); + Object.keys(_aureliaLoader).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _aureliaLoader[key]; + } + }); + }); + Object.keys(_aureliaTaskQueue).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _aureliaTaskQueue[key]; + } + }); + }); + Object.keys(_aureliaPath).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _aureliaPath[key]; + } + }); + }); + Object.keys(_aureliaPal).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _aureliaPal[key]; + } + }); + }); + + var TheLogManager = _interopRequireWildcard(_aureliaLogging); + + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + + newObj.default = obj; + return newObj; + } + } + + + + function preventActionlessFormSubmit() { + _aureliaPal.DOM.addEventListener('submit', function (evt) { + var target = evt.target; + var action = target.action; + + if (target.tagName.toLowerCase() === 'form' && !action) { + evt.preventDefault(); + } + }); + } + + var Aurelia = exports.Aurelia = function () { + function Aurelia(loader, container, resources) { + + + this.loader = loader || new _aureliaPal.PLATFORM.Loader(); + this.container = container || new _aureliaDependencyInjection.Container().makeGlobal(); + this.resources = resources || new _aureliaTemplating.ViewResources(); + this.use = new FrameworkConfiguration(this); + this.logger = TheLogManager.getLogger('aurelia'); + this.hostConfigured = false; + this.host = null; + + this.use.instance(Aurelia, this); + this.use.instance(_aureliaLoader.Loader, this.loader); + this.use.instance(_aureliaTemplating.ViewResources, this.resources); + } + + Aurelia.prototype.start = function start() { + var _this = this; + + if (this.started) { + return Promise.resolve(this); + } + + this.started = true; + this.logger.info('Aurelia Starting'); + + return this.use.apply().then(function () { + preventActionlessFormSubmit(); + + if (!_this.container.hasResolver(_aureliaTemplating.BindingLanguage)) { + var message = 'You must configure Aurelia with a BindingLanguage implementation.'; + _this.logger.error(message); + throw new Error(message); + } + + _this.logger.info('Aurelia Started'); + var evt = _aureliaPal.DOM.createCustomEvent('aurelia-started', { bubbles: true, cancelable: true }); + _aureliaPal.DOM.dispatchEvent(evt); + return _this; + }); + }; + + Aurelia.prototype.enhance = function enhance() { + var _this2 = this; + + var bindingContext = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; + var applicationHost = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + this._configureHost(applicationHost || _aureliaPal.DOM.querySelectorAll('body')[0]); + + return new Promise(function (resolve) { + var engine = _this2.container.get(_aureliaTemplating.TemplatingEngine); + _this2.root = engine.enhance({ container: _this2.container, element: _this2.host, resources: _this2.resources, bindingContext: bindingContext }); + _this2.root.attached(); + _this2._onAureliaComposed(); + resolve(_this2); + }); + }; + + Aurelia.prototype.setRoot = function setRoot() { + var _this3 = this; + + var root = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0]; + var applicationHost = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + var instruction = {}; + + if (this.root && this.root.viewModel && this.root.viewModel.router) { + this.root.viewModel.router.deactivate(); + this.root.viewModel.router.reset(); + } + + this._configureHost(applicationHost); + + var engine = this.container.get(_aureliaTemplating.TemplatingEngine); + var transaction = this.container.get(_aureliaTemplating.CompositionTransaction); + delete transaction.initialComposition; + + if (!root) { + if (this.configModuleId) { + root = (0, _aureliaPath.relativeToFile)('./app', this.configModuleId); + } else { + root = 'app'; + } + } + + instruction.viewModel = root; + instruction.container = instruction.childContainer = this.container; + instruction.viewSlot = this.hostSlot; + instruction.host = this.host; + + return engine.compose(instruction).then(function (r) { + _this3.root = r; + instruction.viewSlot.attached(); + _this3._onAureliaComposed(); + return _this3; + }); + }; + + Aurelia.prototype._configureHost = function _configureHost(applicationHost) { + if (this.hostConfigured) { + return; + } + applicationHost = applicationHost || this.host; + + if (!applicationHost || typeof applicationHost === 'string') { + this.host = _aureliaPal.DOM.getElementById(applicationHost || 'applicationHost'); + } else { + this.host = applicationHost; + } + + if (!this.host) { + throw new Error('No applicationHost was specified.'); + } + + this.hostConfigured = true; + this.host.aurelia = this; + this.hostSlot = new _aureliaTemplating.ViewSlot(this.host, true); + this.hostSlot.transformChildNodesIntoView(); + this.container.registerInstance(_aureliaPal.DOM.boundary, this.host); + }; + + Aurelia.prototype._onAureliaComposed = function _onAureliaComposed() { + var evt = _aureliaPal.DOM.createCustomEvent('aurelia-composed', { bubbles: true, cancelable: true }); + setTimeout(function () { + return _aureliaPal.DOM.dispatchEvent(evt); + }, 1); + }; + + return Aurelia; + }(); + + var logger = TheLogManager.getLogger('aurelia'); + var extPattern = /\.[^/.]+$/; + + function runTasks(config, tasks) { + var current = void 0; + var next = function next() { + current = tasks.shift(); + if (current) { + return Promise.resolve(current(config)).then(next); + } + + return Promise.resolve(); + }; + + return next(); + } + + function loadPlugin(config, loader, info) { + logger.debug('Loading plugin ' + info.moduleId + '.'); + config.resourcesRelativeTo = info.resourcesRelativeTo; + + var id = info.moduleId; + + if (info.resourcesRelativeTo.length > 1) { + return loader.normalize(info.moduleId, info.resourcesRelativeTo[1]).then(function (normalizedId) { + return _loadPlugin(normalizedId); + }); + } + + return _loadPlugin(id); + + function _loadPlugin(moduleId) { + return loader.loadModule(moduleId).then(function (m) { + if ('configure' in m) { + return Promise.resolve(m.configure(config, info.config || {})).then(function () { + config.resourcesRelativeTo = null; + logger.debug('Configured plugin ' + info.moduleId + '.'); + }); + } + + config.resourcesRelativeTo = null; + logger.debug('Loaded plugin ' + info.moduleId + '.'); + }); + } + } + + function loadResources(aurelia, resourcesToLoad, appResources) { + var viewEngine = aurelia.container.get(_aureliaTemplating.ViewEngine); + + return Promise.all(Object.keys(resourcesToLoad).map(function (n) { + return _normalize(resourcesToLoad[n]); + })).then(function (loads) { + var names = []; + var importIds = []; + + loads.forEach(function (l) { + names.push(undefined); + importIds.push(l.importId); + }); + + return viewEngine.importViewResources(importIds, names, appResources); + }); + + function _normalize(load) { + var moduleId = load.moduleId; + var ext = getExt(moduleId); + + if (isOtherResource(moduleId)) { + moduleId = removeExt(moduleId); + } + + return aurelia.loader.normalize(moduleId, load.relativeTo).then(function (normalized) { + return { + name: load.moduleId, + importId: isOtherResource(load.moduleId) ? addOriginalExt(normalized, ext) : normalized + }; + }); + } + + function isOtherResource(name) { + var ext = getExt(name); + if (!ext) return false; + if (ext === '') return false; + if (ext === '.js' || ext === '.ts') return false; + return true; + } + + function removeExt(name) { + return name.replace(extPattern, ''); + } + + function addOriginalExt(normalized, ext) { + return removeExt(normalized) + '.' + ext; + } + } + + function getExt(name) { + var match = name.match(extPattern); + if (match && match.length > 0) { + return match[0].split('.')[1]; + } + } + + function assertProcessed(plugins) { + if (plugins.processed) { + throw new Error('This config instance has already been applied. To load more plugins or global resources, create a new FrameworkConfiguration instance.'); + } + } + + var FrameworkConfiguration = function () { + function FrameworkConfiguration(aurelia) { + var _this4 = this; + + + + this.aurelia = aurelia; + this.container = aurelia.container; + this.info = []; + this.processed = false; + this.preTasks = []; + this.postTasks = []; + this.resourcesToLoad = {}; + this.preTask(function () { + return aurelia.loader.normalize('aurelia-bootstrapper').then(function (name) { + return _this4.bootstrapperName = name; + }); + }); + this.postTask(function () { + return loadResources(aurelia, _this4.resourcesToLoad, aurelia.resources); + }); + } + + FrameworkConfiguration.prototype.instance = function instance(type, _instance) { + this.container.registerInstance(type, _instance); + return this; + }; + + FrameworkConfiguration.prototype.singleton = function singleton(type, implementation) { + this.container.registerSingleton(type, implementation); + return this; + }; + + FrameworkConfiguration.prototype.transient = function transient(type, implementation) { + this.container.registerTransient(type, implementation); + return this; + }; + + FrameworkConfiguration.prototype.preTask = function preTask(task) { + assertProcessed(this); + this.preTasks.push(task); + return this; + }; + + FrameworkConfiguration.prototype.postTask = function postTask(task) { + assertProcessed(this); + this.postTasks.push(task); + return this; + }; + + FrameworkConfiguration.prototype.feature = function feature(plugin, config) { + if (getExt(plugin)) { + return this.plugin({ moduleId: plugin, resourcesRelativeTo: [plugin, ''], config: config || {} }); + } + + return this.plugin({ moduleId: plugin + '/index', resourcesRelativeTo: [plugin, ''], config: config || {} }); + }; + + FrameworkConfiguration.prototype.globalResources = function globalResources(resources) { + assertProcessed(this); + + var toAdd = Array.isArray(resources) ? resources : arguments; + var resource = void 0; + var resourcesRelativeTo = this.resourcesRelativeTo || ['', '']; + + for (var i = 0, ii = toAdd.length; i < ii; ++i) { + resource = toAdd[i]; + if (typeof resource !== 'string') { + throw new Error('Invalid resource path [' + resource + ']. Resources must be specified as relative module IDs.'); + } + + var parent = resourcesRelativeTo[0]; + var grandParent = resourcesRelativeTo[1]; + var name = resource; + + if ((resource.startsWith('./') || resource.startsWith('../')) && parent !== '') { + name = (0, _aureliaPath.join)(parent, resource); + } + + this.resourcesToLoad[name] = { moduleId: name, relativeTo: grandParent }; + } + + return this; + }; + + FrameworkConfiguration.prototype.globalName = function globalName(resourcePath, newName) { + assertProcessed(this); + this.resourcesToLoad[resourcePath] = { moduleId: newName, relativeTo: '' }; + return this; + }; + + FrameworkConfiguration.prototype.plugin = function plugin(_plugin, config) { + assertProcessed(this); + + if (typeof _plugin === 'string') { + return this.plugin({ moduleId: _plugin, resourcesRelativeTo: [_plugin, ''], config: config || {} }); + } + + this.info.push(_plugin); + return this; + }; + + FrameworkConfiguration.prototype._addNormalizedPlugin = function _addNormalizedPlugin(name, config) { + var _this5 = this; + + var plugin = { moduleId: name, resourcesRelativeTo: [name, ''], config: config || {} }; + this.plugin(plugin); + + this.preTask(function () { + var relativeTo = [name, _this5.bootstrapperName]; + plugin.moduleId = name; + plugin.resourcesRelativeTo = relativeTo; + return Promise.resolve(); + }); + + return this; + }; + + FrameworkConfiguration.prototype.defaultBindingLanguage = function defaultBindingLanguage() { + return this._addNormalizedPlugin('aurelia-templating-binding'); + }; + + FrameworkConfiguration.prototype.router = function router() { + return this._addNormalizedPlugin('aurelia-templating-router'); + }; + + FrameworkConfiguration.prototype.history = function history() { + return this._addNormalizedPlugin('aurelia-history-browser'); + }; + + FrameworkConfiguration.prototype.defaultResources = function defaultResources() { + return this._addNormalizedPlugin('aurelia-templating-resources'); + }; + + FrameworkConfiguration.prototype.eventAggregator = function eventAggregator() { + return this._addNormalizedPlugin('aurelia-event-aggregator'); + }; + + FrameworkConfiguration.prototype.basicConfiguration = function basicConfiguration() { + return this.defaultBindingLanguage().defaultResources().eventAggregator(); + }; + + FrameworkConfiguration.prototype.standardConfiguration = function standardConfiguration() { + return this.basicConfiguration().history().router(); + }; + + FrameworkConfiguration.prototype.developmentLogging = function developmentLogging() { + var _this6 = this; + + this.preTask(function () { + return _this6.aurelia.loader.normalize('aurelia-logging-console', _this6.bootstrapperName).then(function (name) { + return _this6.aurelia.loader.loadModule(name).then(function (m) { + TheLogManager.addAppender(new m.ConsoleAppender()); + TheLogManager.setLevel(TheLogManager.logLevel.debug); + }); + }); + }); + + return this; + }; + + FrameworkConfiguration.prototype.apply = function apply() { + var _this7 = this; + + if (this.processed) { + return Promise.resolve(); + } + + return runTasks(this, this.preTasks).then(function () { + var loader = _this7.aurelia.loader; + var info = _this7.info; + var current = void 0; + + var next = function next() { + current = info.shift(); + if (current) { + return loadPlugin(_this7, loader, current).then(next); + } + + _this7.processed = true; + return Promise.resolve(); + }; + + return next().then(function () { + return runTasks(_this7, _this7.postTasks); + }); + }); + }; + + return FrameworkConfiguration; + }(); + + exports.FrameworkConfiguration = FrameworkConfiguration; + var LogManager = exports.LogManager = TheLogManager; +}); +define('aurelia-event-aggregator',['exports', 'aurelia-logging'], function (exports, _aureliaLogging) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.EventAggregator = undefined; + exports.includeEventsIn = includeEventsIn; + exports.configure = configure; + + var LogManager = _interopRequireWildcard(_aureliaLogging); + + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + + newObj.default = obj; + return newObj; + } + } + + + + var logger = LogManager.getLogger('event-aggregator'); + + var Handler = function () { + function Handler(messageType, callback) { + + + this.messageType = messageType; + this.callback = callback; + } + + Handler.prototype.handle = function handle(message) { + if (message instanceof this.messageType) { + this.callback.call(null, message); + } + }; + + return Handler; + }(); + + var EventAggregator = exports.EventAggregator = function () { + function EventAggregator() { + + + this.eventLookup = {}; + this.messageHandlers = []; + } + + EventAggregator.prototype.publish = function publish(event, data) { + var subscribers = void 0; + var i = void 0; + + if (!event) { + throw new Error('Event was invalid.'); + } + + if (typeof event === 'string') { + subscribers = this.eventLookup[event]; + if (subscribers) { + subscribers = subscribers.slice(); + i = subscribers.length; + + try { + while (i--) { + subscribers[i](data, event); + } + } catch (e) { + logger.error(e); + } + } + } else { + subscribers = this.messageHandlers.slice(); + i = subscribers.length; + + try { + while (i--) { + subscribers[i].handle(event); + } + } catch (e) { + logger.error(e); + } + } + }; + + EventAggregator.prototype.subscribe = function subscribe(event, callback) { + var handler = void 0; + var subscribers = void 0; + + if (!event) { + throw new Error('Event channel/type was invalid.'); + } + + if (typeof event === 'string') { + handler = callback; + subscribers = this.eventLookup[event] || (this.eventLookup[event] = []); + } else { + handler = new Handler(event, callback); + subscribers = this.messageHandlers; + } + + subscribers.push(handler); + + return { + dispose: function dispose() { + var idx = subscribers.indexOf(handler); + if (idx !== -1) { + subscribers.splice(idx, 1); + } + } + }; + }; + + EventAggregator.prototype.subscribeOnce = function subscribeOnce(event, callback) { + var sub = this.subscribe(event, function (a, b) { + sub.dispose(); + return callback(a, b); + }); + + return sub; + }; + + return EventAggregator; + }(); + + function includeEventsIn(obj) { + var ea = new EventAggregator(); + + obj.subscribeOnce = function (event, callback) { + return ea.subscribeOnce(event, callback); + }; + + obj.subscribe = function (event, callback) { + return ea.subscribe(event, callback); + }; + + obj.publish = function (event, data) { + ea.publish(event, data); + }; + + return ea; + } + + function configure(config) { + config.instance(EventAggregator, includeEventsIn(config.aurelia)); + } +}); +define('aurelia-history-browser',['exports', 'aurelia-pal', 'aurelia-history'], function (exports, _aureliaPal, _aureliaHistory) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.BrowserHistory = exports.DefaultLinkHandler = exports.LinkHandler = undefined; + exports.configure = configure; + + var _class, _temp; + + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + + + + var LinkHandler = exports.LinkHandler = function () { + function LinkHandler() { + + } + + LinkHandler.prototype.activate = function activate(history) {}; + + LinkHandler.prototype.deactivate = function deactivate() {}; + + return LinkHandler; + }(); + + var DefaultLinkHandler = exports.DefaultLinkHandler = function (_LinkHandler) { + _inherits(DefaultLinkHandler, _LinkHandler); + + function DefaultLinkHandler() { + + + var _this = _possibleConstructorReturn(this, _LinkHandler.call(this)); + + _this.handler = function (e) { + var _DefaultLinkHandler$g = DefaultLinkHandler.getEventInfo(e); + + var shouldHandleEvent = _DefaultLinkHandler$g.shouldHandleEvent; + var href = _DefaultLinkHandler$g.href; + + + if (shouldHandleEvent) { + e.preventDefault(); + _this.history.navigate(href); + } + }; + return _this; + } + + DefaultLinkHandler.prototype.activate = function activate(history) { + if (history._hasPushState) { + this.history = history; + _aureliaPal.DOM.addEventListener('click', this.handler, true); + } + }; + + DefaultLinkHandler.prototype.deactivate = function deactivate() { + _aureliaPal.DOM.removeEventListener('click', this.handler); + }; + + DefaultLinkHandler.getEventInfo = function getEventInfo(event) { + var info = { + shouldHandleEvent: false, + href: null, + anchor: null + }; + + var target = DefaultLinkHandler.findClosestAnchor(event.target); + if (!target || !DefaultLinkHandler.targetIsThisWindow(target)) { + return info; + } + + if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) { + return info; + } + + var href = target.getAttribute('href'); + info.anchor = target; + info.href = href; + + var leftButtonClicked = event.which === 1; + var isRelative = href && !(href.charAt(0) === '#' || /^[a-z]+:/i.test(href)); + + info.shouldHandleEvent = leftButtonClicked && isRelative; + return info; + }; + + DefaultLinkHandler.findClosestAnchor = function findClosestAnchor(el) { + while (el) { + if (el.tagName === 'A') { + return el; + } + + el = el.parentNode; + } + }; + + DefaultLinkHandler.targetIsThisWindow = function targetIsThisWindow(target) { + var targetWindow = target.getAttribute('target'); + var win = _aureliaPal.PLATFORM.global; + + return !targetWindow || targetWindow === win.name || targetWindow === '_self' || targetWindow === 'top' && win === win.top; + }; + + return DefaultLinkHandler; + }(LinkHandler); + + function configure(config) { + config.singleton(_aureliaHistory.History, BrowserHistory); + config.transient(LinkHandler, DefaultLinkHandler); + } + + var BrowserHistory = exports.BrowserHistory = (_temp = _class = function (_History) { + _inherits(BrowserHistory, _History); + + function BrowserHistory(linkHandler) { + + + var _this2 = _possibleConstructorReturn(this, _History.call(this)); + + _this2._isActive = false; + _this2._checkUrlCallback = _this2._checkUrl.bind(_this2); + + _this2.location = _aureliaPal.PLATFORM.location; + _this2.history = _aureliaPal.PLATFORM.history; + _this2.linkHandler = linkHandler; + return _this2; + } + + BrowserHistory.prototype.activate = function activate(options) { + if (this._isActive) { + throw new Error('History has already been activated.'); + } + + var wantsPushState = !!options.pushState; + + this._isActive = true; + this.options = Object.assign({}, { root: '/' }, this.options, options); + + this.root = ('/' + this.options.root + '/').replace(rootStripper, '/'); + + this._wantsHashChange = this.options.hashChange !== false; + this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); + + var eventName = void 0; + if (this._hasPushState) { + eventName = 'popstate'; + } else if (this._wantsHashChange) { + eventName = 'hashchange'; + } + + _aureliaPal.PLATFORM.addEventListener(eventName, this._checkUrlCallback); + + if (this._wantsHashChange && wantsPushState) { + var loc = this.location; + var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root; + + if (!this._hasPushState && !atRoot) { + this.fragment = this._getFragment(null, true); + this.location.replace(this.root + this.location.search + '#' + this.fragment); + + return true; + } else if (this._hasPushState && atRoot && loc.hash) { + this.fragment = this._getHash().replace(routeStripper, ''); + this.history.replaceState({}, _aureliaPal.DOM.title, this.root + this.fragment + loc.search); + } + } + + if (!this.fragment) { + this.fragment = this._getFragment(); + } + + this.linkHandler.activate(this); + + if (!this.options.silent) { + return this._loadUrl(); + } + }; + + BrowserHistory.prototype.deactivate = function deactivate() { + _aureliaPal.PLATFORM.removeEventListener('popstate', this._checkUrlCallback); + _aureliaPal.PLATFORM.removeEventListener('hashchange', this._checkUrlCallback); + this._isActive = false; + this.linkHandler.deactivate(); + }; + + BrowserHistory.prototype.getAbsoluteRoot = function getAbsoluteRoot() { + var origin = createOrigin(this.location.protocol, this.location.hostname, this.location.port); + return '' + origin + this.root; + }; + + BrowserHistory.prototype.navigate = function navigate(fragment) { + var _ref = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + + var _ref$trigger = _ref.trigger; + var trigger = _ref$trigger === undefined ? true : _ref$trigger; + var _ref$replace = _ref.replace; + var replace = _ref$replace === undefined ? false : _ref$replace; + + if (fragment && absoluteUrl.test(fragment)) { + this.location.href = fragment; + return true; + } + + if (!this._isActive) { + return false; + } + + fragment = this._getFragment(fragment || ''); + + if (this.fragment === fragment && !replace) { + return false; + } + + this.fragment = fragment; + + var url = this.root + fragment; + + if (fragment === '' && url !== '/') { + url = url.slice(0, -1); + } + + if (this._hasPushState) { + url = url.replace('//', '/'); + this.history[replace ? 'replaceState' : 'pushState']({}, _aureliaPal.DOM.title, url); + } else if (this._wantsHashChange) { + updateHash(this.location, fragment, replace); + } else { + return this.location.assign(url); + } + + if (trigger) { + return this._loadUrl(fragment); + } + }; + + BrowserHistory.prototype.navigateBack = function navigateBack() { + this.history.back(); + }; + + BrowserHistory.prototype.setTitle = function setTitle(title) { + _aureliaPal.DOM.title = title; + }; + + BrowserHistory.prototype._getHash = function _getHash() { + return this.location.hash.substr(1); + }; + + BrowserHistory.prototype._getFragment = function _getFragment(fragment, forcePushState) { + var root = void 0; + + if (!fragment) { + if (this._hasPushState || !this._wantsHashChange || forcePushState) { + fragment = this.location.pathname + this.location.search; + root = this.root.replace(trailingSlash, ''); + if (!fragment.indexOf(root)) { + fragment = fragment.substr(root.length); + } + } else { + fragment = this._getHash(); + } + } + + return '/' + fragment.replace(routeStripper, ''); + }; + + BrowserHistory.prototype._checkUrl = function _checkUrl() { + var current = this._getFragment(); + if (current !== this.fragment) { + this._loadUrl(); + } + }; + + BrowserHistory.prototype._loadUrl = function _loadUrl(fragmentOverride) { + var fragment = this.fragment = this._getFragment(fragmentOverride); + + return this.options.routeHandler ? this.options.routeHandler(fragment) : false; + }; + + return BrowserHistory; + }(_aureliaHistory.History), _class.inject = [LinkHandler], _temp); + + var routeStripper = /^#?\/*|\s+$/g; + + var rootStripper = /^\/+|\/+$/g; + + var trailingSlash = /\/$/; + + var absoluteUrl = /^([a-z][a-z0-9+\-.]*:)?\/\//i; + + function updateHash(location, fragment, replace) { + if (replace) { + var _href = location.href.replace(/(javascript:|#).*$/, ''); + location.replace(_href + '#' + fragment); + } else { + location.hash = '#' + fragment; + } + } + + function createOrigin(protocol, hostname, port) { + return protocol + '//' + hostname + (port ? ':' + port : ''); + } +}); +define('aurelia-loader',['exports', 'aurelia-path', 'aurelia-metadata'], function (exports, _aureliaPath, _aureliaMetadata) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.Loader = exports.TemplateRegistryEntry = exports.TemplateDependency = undefined; + + var _createClass = function () { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + return function (Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps); + if (staticProps) defineProperties(Constructor, staticProps); + return Constructor; + }; + }(); + + + + var TemplateDependency = exports.TemplateDependency = function TemplateDependency(src, name) { + + + this.src = src; + this.name = name; + }; + + var TemplateRegistryEntry = exports.TemplateRegistryEntry = function () { + function TemplateRegistryEntry(address) { + + + this.templateIsLoaded = false; + this.factoryIsReady = false; + this.resources = null; + this.dependencies = null; + + this.address = address; + this.onReady = null; + this._template = null; + this._factory = null; + } + + TemplateRegistryEntry.prototype.addDependency = function addDependency(src, name) { + var finalSrc = typeof src === 'string' ? (0, _aureliaPath.relativeToFile)(src, this.address) : _aureliaMetadata.Origin.get(src).moduleId; + + this.dependencies.push(new TemplateDependency(finalSrc, name)); + }; + + _createClass(TemplateRegistryEntry, [{ + key: 'template', + get: function get() { + return this._template; + }, + set: function set(value) { + var address = this.address; + var requires = void 0; + var current = void 0; + var src = void 0; + var dependencies = void 0; + + this._template = value; + this.templateIsLoaded = true; + + requires = value.content.querySelectorAll('require'); + dependencies = this.dependencies = new Array(requires.length); + + for (var i = 0, ii = requires.length; i < ii; ++i) { + current = requires[i]; + src = current.getAttribute('from'); + + if (!src) { + throw new Error(' element in ' + address + ' has no "from" attribute.'); + } + + dependencies[i] = new TemplateDependency((0, _aureliaPath.relativeToFile)(src, address), current.getAttribute('as')); + + if (current.parentNode) { + current.parentNode.removeChild(current); + } + } + } + }, { + key: 'factory', + get: function get() { + return this._factory; + }, + set: function set(value) { + this._factory = value; + this.factoryIsReady = true; + } + }]); + + return TemplateRegistryEntry; + }(); + + var Loader = exports.Loader = function () { + function Loader() { + + + this.templateRegistry = {}; + } + + Loader.prototype.map = function map(id, source) { + throw new Error('Loaders must implement map(id, source).'); + }; + + Loader.prototype.normalizeSync = function normalizeSync(moduleId, relativeTo) { + throw new Error('Loaders must implement normalizeSync(moduleId, relativeTo).'); + }; + + Loader.prototype.normalize = function normalize(moduleId, relativeTo) { + throw new Error('Loaders must implement normalize(moduleId: string, relativeTo: string): Promise.'); + }; + + Loader.prototype.loadModule = function loadModule(id) { + throw new Error('Loaders must implement loadModule(id).'); + }; + + Loader.prototype.loadAllModules = function loadAllModules(ids) { + throw new Error('Loader must implement loadAllModules(ids).'); + }; + + Loader.prototype.loadTemplate = function loadTemplate(url) { + throw new Error('Loader must implement loadTemplate(url).'); + }; + + Loader.prototype.loadText = function loadText(url) { + throw new Error('Loader must implement loadText(url).'); + }; + + Loader.prototype.applyPluginToUrl = function applyPluginToUrl(url, pluginName) { + throw new Error('Loader must implement applyPluginToUrl(url, pluginName).'); + }; + + Loader.prototype.addPlugin = function addPlugin(pluginName, implementation) { + throw new Error('Loader must implement addPlugin(pluginName, implementation).'); + }; + + Loader.prototype.getOrCreateTemplateRegistryEntry = function getOrCreateTemplateRegistryEntry(address) { + return this.templateRegistry[address] || (this.templateRegistry[address] = new TemplateRegistryEntry(address)); + }; + + return Loader; + }(); +}); +define('aurelia-metadata',['exports', 'aurelia-pal'], function (exports, _aureliaPal) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.Origin = exports.metadata = undefined; + exports.decorators = decorators; + exports.deprecated = deprecated; + exports.mixin = mixin; + exports.protocol = protocol; + + var _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target; + }; + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; + }; + + + + var metadata = exports.metadata = { + resource: 'aurelia:resource', + paramTypes: 'design:paramtypes', + propertyType: 'design:type', + properties: 'design:properties', + get: function get(metadataKey, target, targetKey) { + if (!target) { + return undefined; + } + var result = metadata.getOwn(metadataKey, target, targetKey); + return result === undefined ? metadata.get(metadataKey, Object.getPrototypeOf(target), targetKey) : result; + }, + getOwn: function getOwn(metadataKey, target, targetKey) { + if (!target) { + return undefined; + } + return Reflect.getOwnMetadata(metadataKey, target, targetKey); + }, + define: function define(metadataKey, metadataValue, target, targetKey) { + Reflect.defineMetadata(metadataKey, metadataValue, target, targetKey); + }, + getOrCreateOwn: function getOrCreateOwn(metadataKey, Type, target, targetKey) { + var result = metadata.getOwn(metadataKey, target, targetKey); + + if (result === undefined) { + result = new Type(); + Reflect.defineMetadata(metadataKey, result, target, targetKey); + } + + return result; + } + }; + + var originStorage = new Map(); + var unknownOrigin = Object.freeze({ moduleId: undefined, moduleMember: undefined }); + + var Origin = exports.Origin = function () { + function Origin(moduleId, moduleMember) { + + + this.moduleId = moduleId; + this.moduleMember = moduleMember; + } + + Origin.get = function get(fn) { + var origin = originStorage.get(fn); + + if (origin === undefined) { + _aureliaPal.PLATFORM.eachModule(function (key, value) { + if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') { + for (var name in value) { + var exp = value[name]; + if (exp === fn) { + originStorage.set(fn, origin = new Origin(key, name)); + return true; + } + } + } + + if (value === fn) { + originStorage.set(fn, origin = new Origin(key, 'default')); + return true; + } + + return false; + }); + } + + return origin || unknownOrigin; + }; + + Origin.set = function set(fn, origin) { + originStorage.set(fn, origin); + }; + + return Origin; + }(); + + function decorators() { + for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) { + rest[_key] = arguments[_key]; + } + + var applicator = function applicator(target, key, descriptor) { + var i = rest.length; + + if (key) { + descriptor = descriptor || { + value: target[key], + writable: true, + configurable: true, + enumerable: true + }; + + while (i--) { + descriptor = rest[i](target, key, descriptor) || descriptor; + } + + Object.defineProperty(target, key, descriptor); + } else { + while (i--) { + target = rest[i](target) || target; + } + } + + return target; + }; + + applicator.on = applicator; + return applicator; + } + + function deprecated(optionsOrTarget, maybeKey, maybeDescriptor) { + function decorator(target, key, descriptor) { + var methodSignature = target.constructor.name + '#' + key; + var options = maybeKey ? {} : optionsOrTarget || {}; + var message = 'DEPRECATION - ' + methodSignature; + + if (typeof descriptor.value !== 'function') { + throw new SyntaxError('Only methods can be marked as deprecated.'); + } + + if (options.message) { + message += ' - ' + options.message; + } + + return _extends({}, descriptor, { + value: function deprecationWrapper() { + if (options.error) { + throw new Error(message); + } else { + console.warn(message); + } + + return descriptor.value.apply(this, arguments); + } + }); + } + + return maybeKey ? decorator(optionsOrTarget, maybeKey, maybeDescriptor) : decorator; + } + + function mixin(behavior) { + var instanceKeys = Object.keys(behavior); + + function _mixin(possible) { + var decorator = function decorator(target) { + var resolvedTarget = typeof target === 'function' ? target.prototype : target; + + var i = instanceKeys.length; + while (i--) { + var property = instanceKeys[i]; + Object.defineProperty(resolvedTarget, property, { + value: behavior[property], + writable: true + }); + } + }; + + return possible ? decorator(possible) : decorator; + } + + return _mixin; + } + + function alwaysValid() { + return true; + } + function noCompose() {} + + function ensureProtocolOptions(options) { + if (options === undefined) { + options = {}; + } else if (typeof options === 'function') { + options = { + validate: options + }; + } + + if (!options.validate) { + options.validate = alwaysValid; + } + + if (!options.compose) { + options.compose = noCompose; + } + + return options; + } + + function createProtocolValidator(validate) { + return function (target) { + var result = validate(target); + return result === true; + }; + } + + function createProtocolAsserter(name, validate) { + return function (target) { + var result = validate(target); + if (result !== true) { + throw new Error(result || name + ' was not correctly implemented.'); + } + }; + } + + function protocol(name, options) { + options = ensureProtocolOptions(options); + + var result = function result(target) { + var resolvedTarget = typeof target === 'function' ? target.prototype : target; + + options.compose(resolvedTarget); + result.assert(resolvedTarget); + + Object.defineProperty(resolvedTarget, 'protocol:' + name, { + enumerable: false, + configurable: false, + writable: false, + value: true + }); + }; + + result.validate = createProtocolValidator(options.validate); + result.assert = createProtocolAsserter(name, options.validate); + + return result; + } + + protocol.create = function (name, options) { + options = ensureProtocolOptions(options); + var hidden = 'protocol:' + name; + var result = function result(target) { + var decorator = protocol(name, options); + return target ? decorator(target) : decorator; + }; + + result.decorates = function (obj) { + return obj[hidden] === true; + }; + result.validate = createProtocolValidator(options.validate); + result.assert = createProtocolAsserter(name, options.validate); + + return result; + }; +}); +define('aurelia-pal',['exports'], function (exports) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.AggregateError = AggregateError; + exports.initializePAL = initializePAL; + function AggregateError(message, innerError, skipIfAlreadyAggregate) { + if (innerError) { + if (innerError.innerError && skipIfAlreadyAggregate) { + return innerError; + } + + var separator = '\n------------------------------------------------\n'; + + message += separator + 'Inner Error:\n'; + + if (typeof innerError === 'string') { + message += 'Message: ' + innerError; + } else { + if (innerError.message) { + message += 'Message: ' + innerError.message; + } else { + message += 'Unknown Inner Error Type. Displaying Inner Error as JSON:\n ' + JSON.stringify(innerError, null, ' '); + } + + if (innerError.stack) { + message += '\nInner Error Stack:\n' + innerError.stack; + message += '\nEnd Inner Error Stack'; + } + } + + message += separator; + } + + var e = new Error(message); + if (innerError) { + e.innerError = innerError; + } + + return e; + } + + var FEATURE = exports.FEATURE = {}; + + var PLATFORM = exports.PLATFORM = { + noop: function noop() {}, + eachModule: function eachModule() {} + }; + + PLATFORM.global = function () { + if (typeof self !== 'undefined') { + return self; + } + + if (typeof global !== 'undefined') { + return global; + } + + return new Function('return this')(); + }(); + + var DOM = exports.DOM = {}; + + function initializePAL(callback) { + if (typeof Object.getPropertyDescriptor !== 'function') { + Object.getPropertyDescriptor = function (subject, name) { + var pd = Object.getOwnPropertyDescriptor(subject, name); + var proto = Object.getPrototypeOf(subject); + while (typeof pd === 'undefined' && proto !== null) { + pd = Object.getOwnPropertyDescriptor(proto, name); + proto = Object.getPrototypeOf(proto); + } + return pd; + }; + } + + callback(PLATFORM, FEATURE, DOM); + } +}); +define('aurelia-loader-default',['exports', 'aurelia-loader', 'aurelia-pal', 'aurelia-metadata'], function (exports, _aureliaLoader, _aureliaPal, _aureliaMetadata) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.DefaultLoader = exports.TextTemplateLoader = undefined; + + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + + + + var TextTemplateLoader = exports.TextTemplateLoader = function () { + function TextTemplateLoader() { + + } + + TextTemplateLoader.prototype.loadTemplate = function loadTemplate(loader, entry) { + return loader.loadText(entry.address).then(function (text) { + entry.template = _aureliaPal.DOM.createTemplateFromMarkup(text); + }); + }; + + return TextTemplateLoader; + }(); + + function ensureOriginOnExports(executed, name) { + var target = executed; + var key = void 0; + var exportedValue = void 0; + + if (target.__useDefault) { + target = target['default']; + } + + _aureliaMetadata.Origin.set(target, new _aureliaMetadata.Origin(name, 'default')); + + for (key in target) { + exportedValue = target[key]; + + if (typeof exportedValue === 'function') { + _aureliaMetadata.Origin.set(exportedValue, new _aureliaMetadata.Origin(name, key)); + } + } + + return executed; + } + + var DefaultLoader = exports.DefaultLoader = function (_Loader) { + _inherits(DefaultLoader, _Loader); + + function DefaultLoader() { + + + var _this = _possibleConstructorReturn(this, _Loader.call(this)); + + _this.textPluginName = 'text'; + + + _this.moduleRegistry = Object.create(null); + _this.useTemplateLoader(new TextTemplateLoader()); + + var that = _this; + + _this.addPlugin('template-registry-entry', { + 'fetch': function fetch(address) { + var entry = that.getOrCreateTemplateRegistryEntry(address); + return entry.templateIsLoaded ? entry : that.templateLoader.loadTemplate(that, entry).then(function (x) { + return entry; + }); + } + }); + return _this; + } + + DefaultLoader.prototype.useTemplateLoader = function useTemplateLoader(templateLoader) { + this.templateLoader = templateLoader; + }; + + DefaultLoader.prototype.loadAllModules = function loadAllModules(ids) { + var loads = []; + + for (var i = 0, ii = ids.length; i < ii; ++i) { + loads.push(this.loadModule(ids[i])); + } + + return Promise.all(loads); + }; + + DefaultLoader.prototype.loadTemplate = function loadTemplate(url) { + return this._import(this.applyPluginToUrl(url, 'template-registry-entry')); + }; + + DefaultLoader.prototype.loadText = function loadText(url) { + return this._import(this.applyPluginToUrl(url, this.textPluginName)).then(function (textOrModule) { + if (typeof textOrModule === 'string') { + return textOrModule; + } + + return textOrModule['default']; + }); + }; + + return DefaultLoader; + }(_aureliaLoader.Loader); + + _aureliaPal.PLATFORM.Loader = DefaultLoader; + + if (!_aureliaPal.PLATFORM.global.System || !_aureliaPal.PLATFORM.global.System.import) { + if (_aureliaPal.PLATFORM.global.requirejs && requirejs.s && requirejs.s.contexts && requirejs.s.contexts._ && requirejs.s.contexts._.defined) { + _aureliaPal.PLATFORM.eachModule = function (callback) { + var defined = requirejs.s.contexts._.defined; + for (var key in defined) { + try { + if (callback(key, defined[key])) return; + } catch (e) {} + } + }; + } else { + _aureliaPal.PLATFORM.eachModule = function (callback) {}; + } + + DefaultLoader.prototype._import = function (moduleId) { + return new Promise(function (resolve, reject) { + require([moduleId], resolve, reject); + }); + }; + + DefaultLoader.prototype.loadModule = function (id) { + var _this2 = this; + + var existing = this.moduleRegistry[id]; + if (existing !== undefined) { + return Promise.resolve(existing); + } + + return new Promise(function (resolve, reject) { + require([id], function (m) { + _this2.moduleRegistry[id] = m; + resolve(ensureOriginOnExports(m, id)); + }, reject); + }); + }; + + DefaultLoader.prototype.map = function (id, source) {}; + + DefaultLoader.prototype.normalize = function (moduleId, relativeTo) { + return Promise.resolve(moduleId); + }; + + DefaultLoader.prototype.normalizeSync = function (moduleId, relativeTo) { + return moduleId; + }; + + DefaultLoader.prototype.applyPluginToUrl = function (url, pluginName) { + return pluginName + '!' + url; + }; + + DefaultLoader.prototype.addPlugin = function (pluginName, implementation) { + var nonAnonDefine = define; + nonAnonDefine(pluginName, [], { + 'load': function load(name, req, onload) { + var result = implementation.fetch(name); + Promise.resolve(result).then(onload); + } + }); + }; + } else { + _aureliaPal.PLATFORM.eachModule = function (callback) { + var modules = System._loader.modules; + + for (var key in modules) { + try { + if (callback(key, modules[key].module)) return; + } catch (e) {} + } + }; + + System.set('text', System.newModule({ + 'translate': function translate(load) { + return 'module.exports = "' + load.source.replace(/(["\\])/g, '\\$1').replace(/[\f]/g, '\\f').replace(/[\b]/g, '\\b').replace(/[\n]/g, '\\n').replace(/[\t]/g, '\\t').replace(/[\r]/g, '\\r').replace(/[\u2028]/g, '\\u2028').replace(/[\u2029]/g, '\\u2029') + '";'; + } + })); + + DefaultLoader.prototype._import = function (moduleId) { + return System.import(moduleId); + }; + + DefaultLoader.prototype.loadModule = function (id) { + var _this3 = this; + + return System.normalize(id).then(function (newId) { + var existing = _this3.moduleRegistry[newId]; + if (existing !== undefined) { + return Promise.resolve(existing); + } + + return System.import(newId).then(function (m) { + _this3.moduleRegistry[newId] = m; + return ensureOriginOnExports(m, newId); + }); + }); + }; + + DefaultLoader.prototype.map = function (id, source) { + System.map[id] = source; + }; + + DefaultLoader.prototype.normalizeSync = function (moduleId, relativeTo) { + return System.normalizeSync(moduleId, relativeTo); + }; + + DefaultLoader.prototype.normalize = function (moduleId, relativeTo) { + return System.normalize(moduleId, relativeTo); + }; + + DefaultLoader.prototype.applyPluginToUrl = function (url, pluginName) { + return url + '!' + pluginName; + }; + + DefaultLoader.prototype.addPlugin = function (pluginName, implementation) { + System.set(pluginName, System.newModule({ + 'fetch': function fetch(load, _fetch) { + var result = implementation.fetch(load.address); + return Promise.resolve(result).then(function (x) { + load.metadata.result = x; + return ''; + }); + }, + 'instantiate': function instantiate(load) { + return load.metadata.result; + } + })); + }; + } +}); +define('aurelia-polyfills',['aurelia-pal'], function (_aureliaPal) { + 'use strict'; + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; + }; + + (function (Object, GOPS) { + 'use strict'; + + if (GOPS in Object) return; + + var setDescriptor, + G = _aureliaPal.PLATFORM.global, + id = 0, + random = '' + Math.random(), + prefix = '__\x01symbol:', + prefixLength = prefix.length, + internalSymbol = '__\x01symbol@@' + random, + DP = 'defineProperty', + DPies = 'defineProperties', + GOPN = 'getOwnPropertyNames', + GOPD = 'getOwnPropertyDescriptor', + PIE = 'propertyIsEnumerable', + gOPN = Object[GOPN], + gOPD = Object[GOPD], + create = Object.create, + keys = Object.keys, + defineProperty = Object[DP], + $defineProperties = Object[DPies], + descriptor = gOPD(Object, GOPN), + ObjectProto = Object.prototype, + hOP = ObjectProto.hasOwnProperty, + pIE = ObjectProto[PIE], + toString = ObjectProto.toString, + indexOf = Array.prototype.indexOf || function (v) { + for (var i = this.length; i-- && this[i] !== v;) {} + return i; + }, + addInternalIfNeeded = function addInternalIfNeeded(o, uid, enumerable) { + if (!hOP.call(o, internalSymbol)) { + defineProperty(o, internalSymbol, { + enumerable: false, + configurable: false, + writable: false, + value: {} + }); + } + o[internalSymbol]['@@' + uid] = enumerable; + }, + createWithSymbols = function createWithSymbols(proto, descriptors) { + var self = create(proto); + gOPN(descriptors).forEach(function (key) { + if (propertyIsEnumerable.call(descriptors, key)) { + $defineProperty(self, key, descriptors[key]); + } + }); + return self; + }, + copyAsNonEnumerable = function copyAsNonEnumerable(descriptor) { + var newDescriptor = create(descriptor); + newDescriptor.enumerable = false; + return newDescriptor; + }, + get = function get() {}, + onlyNonSymbols = function onlyNonSymbols(name) { + return name != internalSymbol && !hOP.call(source, name); + }, + onlySymbols = function onlySymbols(name) { + return name != internalSymbol && hOP.call(source, name); + }, + propertyIsEnumerable = function propertyIsEnumerable(key) { + var uid = '' + key; + return onlySymbols(uid) ? hOP.call(this, uid) && this[internalSymbol]['@@' + uid] : pIE.call(this, key); + }, + setAndGetSymbol = function setAndGetSymbol(uid) { + var descriptor = { + enumerable: false, + configurable: true, + get: get, + set: function set(value) { + setDescriptor(this, uid, { + enumerable: false, + configurable: true, + writable: true, + value: value + }); + addInternalIfNeeded(this, uid, true); + } + }; + defineProperty(ObjectProto, uid, descriptor); + return source[uid] = defineProperty(Object(uid), 'constructor', sourceConstructor); + }, + _Symbol = function _Symbol2(description) { + if (this && this !== G) { + throw new TypeError('Symbol is not a constructor'); + } + return setAndGetSymbol(prefix.concat(description || '', random, ++id)); + }, + source = create(null), + sourceConstructor = { value: _Symbol }, + sourceMap = function sourceMap(uid) { + return source[uid]; + }, + $defineProperty = function defineProp(o, key, descriptor) { + var uid = '' + key; + if (onlySymbols(uid)) { + setDescriptor(o, uid, descriptor.enumerable ? copyAsNonEnumerable(descriptor) : descriptor); + addInternalIfNeeded(o, uid, !!descriptor.enumerable); + } else { + defineProperty(o, key, descriptor); + } + return o; + }, + $getOwnPropertySymbols = function getOwnPropertySymbols(o) { + var cof = toString.call(o); + o = cof === '[object String]' ? o.split('') : Object(o); + return gOPN(o).filter(onlySymbols).map(sourceMap); + }; + + descriptor.value = $defineProperty; + defineProperty(Object, DP, descriptor); + + descriptor.value = $getOwnPropertySymbols; + defineProperty(Object, GOPS, descriptor); + + descriptor.value = function getOwnPropertyNames(o) { + return gOPN(o).filter(onlyNonSymbols); + }; + defineProperty(Object, GOPN, descriptor); + + descriptor.value = function defineProperties(o, descriptors) { + var symbols = $getOwnPropertySymbols(descriptors); + if (symbols.length) { + keys(descriptors).concat(symbols).forEach(function (uid) { + if (propertyIsEnumerable.call(descriptors, uid)) { + $defineProperty(o, uid, descriptors[uid]); + } + }); + } else { + $defineProperties(o, descriptors); + } + return o; + }; + defineProperty(Object, DPies, descriptor); + + descriptor.value = propertyIsEnumerable; + defineProperty(ObjectProto, PIE, descriptor); + + descriptor.value = _Symbol; + defineProperty(G, 'Symbol', descriptor); + + descriptor.value = function (key) { + var uid = prefix.concat(prefix, key, random); + return uid in ObjectProto ? source[uid] : setAndGetSymbol(uid); + }; + defineProperty(_Symbol, 'for', descriptor); + + descriptor.value = function (symbol) { + return hOP.call(source, symbol) ? symbol.slice(prefixLength * 2, -random.length) : void 0; + }; + defineProperty(_Symbol, 'keyFor', descriptor); + + descriptor.value = function getOwnPropertyDescriptor(o, key) { + var descriptor = gOPD(o, key); + if (descriptor && onlySymbols(key)) { + descriptor.enumerable = propertyIsEnumerable.call(o, key); + } + return descriptor; + }; + defineProperty(Object, GOPD, descriptor); + + descriptor.value = function (proto, descriptors) { + return arguments.length === 1 ? create(proto) : createWithSymbols(proto, descriptors); + }; + defineProperty(Object, 'create', descriptor); + + descriptor.value = function () { + var str = toString.call(this); + return str === '[object String]' && onlySymbols(this) ? '[object Symbol]' : str; + }; + defineProperty(ObjectProto, 'toString', descriptor); + + try { + setDescriptor = create(defineProperty({}, prefix, { + get: function get() { + return defineProperty(this, prefix, { value: false })[prefix]; + } + }))[prefix] || defineProperty; + } catch (o_O) { + setDescriptor = function setDescriptor(o, key, descriptor) { + var protoDescriptor = gOPD(ObjectProto, key); + delete ObjectProto[key]; + defineProperty(o, key, descriptor); + defineProperty(ObjectProto, key, protoDescriptor); + }; + } + })(Object, 'getOwnPropertySymbols'); + + (function (O, S) { + var dP = O.defineProperty, + ObjectProto = O.prototype, + toString = ObjectProto.toString, + toStringTag = 'toStringTag', + descriptor; + ['iterator', 'match', 'replace', 'search', 'split', 'hasInstance', 'isConcatSpreadable', 'unscopables', 'species', 'toPrimitive', toStringTag].forEach(function (name) { + if (!(name in Symbol)) { + dP(Symbol, name, { value: Symbol(name) }); + switch (name) { + case toStringTag: + descriptor = O.getOwnPropertyDescriptor(ObjectProto, 'toString'); + descriptor.value = function () { + var str = toString.call(this), + tst = typeof this === 'undefined' || this === null ? undefined : this[Symbol.toStringTag]; + return typeof tst === 'undefined' ? str : '[object ' + tst + ']'; + }; + dP(ObjectProto, 'toString', descriptor); + break; + } + } + }); + })(Object, Symbol); + + (function (Si, AP, SP) { + + function returnThis() { + return this; + } + + if (!AP[Si]) AP[Si] = function () { + var i = 0, + self = this, + iterator = { + next: function next() { + var done = self.length <= i; + return done ? { done: done } : { done: done, value: self[i++] }; + } + }; + iterator[Si] = returnThis; + return iterator; + }; + + if (!SP[Si]) SP[Si] = function () { + var fromCodePoint = String.fromCodePoint, + self = this, + i = 0, + length = self.length, + iterator = { + next: function next() { + var done = length <= i, + c = done ? '' : fromCodePoint(self.codePointAt(i)); + i += c.length; + return done ? { done: done } : { done: done, value: c }; + } + }; + iterator[Si] = returnThis; + return iterator; + }; + })(Symbol.iterator, Array.prototype, String.prototype); + + Number.isNaN = Number.isNaN || function (value) { + return value !== value; + }; + + Number.isFinite = Number.isFinite || function (value) { + return typeof value === "number" && isFinite(value); + }; + if (!String.prototype.endsWith || function () { + try { + return !"ab".endsWith("a", 1); + } catch (e) { + return true; + } + }()) { + String.prototype.endsWith = function (searchString, position) { + var subjectString = this.toString(); + if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { + position = subjectString.length; + } + position -= searchString.length; + var lastIndex = subjectString.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; + }; + } + + if (!String.prototype.startsWith || function () { + try { + return !"ab".startsWith("b", 1); + } catch (e) { + return true; + } + }()) { + String.prototype.startsWith = function (searchString, position) { + position = position || 0; + return this.substr(position, searchString.length) === searchString; + }; + } + + if (!Array.from) { + Array.from = function () { + var toInteger = function toInteger(it) { + return isNaN(it = +it) ? 0 : (it > 0 ? Math.floor : Math.ceil)(it); + }; + var toLength = function toLength(it) { + return it > 0 ? Math.min(toInteger(it), 0x1fffffffffffff) : 0; + }; + var iterCall = function iterCall(iter, fn, val, index) { + try { + return fn(val, index); + } catch (E) { + if (typeof iter.return == 'function') iter.return(); + throw E; + } + }; + + return function from(arrayLike) { + var O = Object(arrayLike), + C = typeof this == 'function' ? this : Array, + aLen = arguments.length, + mapfn = aLen > 1 ? arguments[1] : undefined, + mapping = mapfn !== undefined, + index = 0, + iterFn = O[Symbol.iterator], + length, + result, + step, + iterator; + if (mapping) mapfn = mapfn.bind(aLen > 2 ? arguments[2] : undefined); + if (iterFn != undefined && !Array.isArray(arrayLike)) { + for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { + result[index] = mapping ? iterCall(iterator, mapfn, step.value, index) : step.value; + } + } else { + length = toLength(O.length); + for (result = new C(length); length > index; index++) { + result[index] = mapping ? mapfn(O[index], index) : O[index]; + } + } + result.length = index; + return result; + }; + }(); + } + + if (!Array.prototype.find) { + Object.defineProperty(Array.prototype, 'find', { + configurable: true, + writable: true, + enumerable: false, + value: function value(predicate) { + if (this === null) { + throw new TypeError('Array.prototype.find called on null or undefined'); + } + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + var list = Object(this); + var length = list.length >>> 0; + var thisArg = arguments[1]; + var value; + + for (var i = 0; i < length; i++) { + value = list[i]; + if (predicate.call(thisArg, value, i, list)) { + return value; + } + } + return undefined; + } + }); + } + + if (!Array.prototype.findIndex) { + Object.defineProperty(Array.prototype, 'findIndex', { + configurable: true, + writable: true, + enumerable: false, + value: function value(predicate) { + if (this === null) { + throw new TypeError('Array.prototype.findIndex called on null or undefined'); + } + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + var list = Object(this); + var length = list.length >>> 0; + var thisArg = arguments[1]; + var value; + + for (var i = 0; i < length; i++) { + value = list[i]; + if (predicate.call(thisArg, value, i, list)) { + return i; + } + } + return -1; + } + }); + } + + if (!Array.prototype.includes) { + Object.defineProperty(Array.prototype, 'includes', { + configurable: true, + writable: true, + enumerable: false, + value: function value(searchElement) { + var O = Object(this); + var len = parseInt(O.length) || 0; + if (len === 0) { + return false; + } + var n = parseInt(arguments[1]) || 0; + var k; + if (n >= 0) { + k = n; + } else { + k = len + n; + if (k < 0) { + k = 0; + } + } + var currentElement; + while (k < len) { + currentElement = O[k]; + if (searchElement === currentElement || searchElement !== searchElement && currentElement !== currentElement) { + return true; + } + k++; + } + return false; + } + }); + } + + (function () { + var needsFix = false; + + try { + var s = Object.keys('a'); + needsFix = s.length !== 1 || s[0] !== '0'; + } catch (e) { + needsFix = true; + } + + if (needsFix) { + Object.keys = function () { + var hasOwnProperty = Object.prototype.hasOwnProperty, + hasDontEnumBug = !{ toString: null }.propertyIsEnumerable('toString'), + dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'], + dontEnumsLength = dontEnums.length; + + return function (obj) { + if (obj === undefined || obj === null) { + throw TypeError('Cannot convert undefined or null to object'); + } + + obj = Object(obj); + + var result = [], + prop, + i; + + for (prop in obj) { + if (hasOwnProperty.call(obj, prop)) { + result.push(prop); + } + } + + if (hasDontEnumBug) { + for (i = 0; i < dontEnumsLength; i++) { + if (hasOwnProperty.call(obj, dontEnums[i])) { + result.push(dontEnums[i]); + } + } + } + + return result; + }; + }(); + } + })(); + + (function (O) { + if ('assign' in O) { + return; + } + + O.defineProperty(O, 'assign', { + configurable: true, + writable: true, + value: function () { + var gOPS = O.getOwnPropertySymbols, + pIE = O.propertyIsEnumerable, + filterOS = gOPS ? function (self) { + return gOPS(self).filter(pIE, self); + } : function () { + return Array.prototype; + }; + + return function assign(where) { + if (gOPS && !(where instanceof O)) { + console.warn('problematic Symbols', where); + } + + function set(keyOrSymbol) { + where[keyOrSymbol] = arg[keyOrSymbol]; + } + + for (var i = 1, ii = arguments.length; i < ii; ++i) { + var arg = arguments[i]; + + if (arg === null || arg === undefined) { + continue; + } + + O.keys(arg).concat(filterOS(arg)).forEach(set); + } + + return where; + }; + }() + }); + })(Object); + + (function (global) { + var i; + + var defineProperty = Object.defineProperty, + is = function is(a, b) { + return a === b || a !== a && b !== b; + }; + + if (typeof WeakMap == 'undefined') { + global.WeakMap = createCollection({ + 'delete': sharedDelete, + + clear: sharedClear, + + get: sharedGet, + + has: mapHas, + + set: sharedSet + }, true); + } + + if (typeof Map == 'undefined' || typeof new Map().values !== 'function' || !new Map().values().next) { + var _createCollection; + + global.Map = createCollection((_createCollection = { + 'delete': sharedDelete, + + has: mapHas, + + get: sharedGet, + + set: sharedSet, + + keys: sharedKeys, + + values: sharedValues, + + entries: mapEntries, + + forEach: sharedForEach, + + clear: sharedClear + }, _createCollection[Symbol.iterator] = mapEntries, _createCollection)); + } + + if (typeof Set == 'undefined' || typeof new Set().values !== 'function' || !new Set().values().next) { + var _createCollection2; + + global.Set = createCollection((_createCollection2 = { + has: setHas, + + add: sharedAdd, + + 'delete': sharedDelete, + + clear: sharedClear, + + keys: sharedValues, + values: sharedValues, + + entries: setEntries, + + forEach: sharedForEach + }, _createCollection2[Symbol.iterator] = sharedValues, _createCollection2)); + } + + if (typeof WeakSet == 'undefined') { + global.WeakSet = createCollection({ + 'delete': sharedDelete, + + add: sharedAdd, + + clear: sharedClear, + + has: setHas + }, true); + } + + function createCollection(proto, objectOnly) { + function Collection(a) { + if (!this || this.constructor !== Collection) return new Collection(a); + this._keys = []; + this._values = []; + this._itp = []; + this.objectOnly = objectOnly; + + if (a) init.call(this, a); + } + + if (!objectOnly) { + defineProperty(proto, 'size', { + get: sharedSize + }); + } + + proto.constructor = Collection; + Collection.prototype = proto; + + return Collection; + } + + function init(a) { + var i; + + if (this.add) a.forEach(this.add, this);else a.forEach(function (a) { + this.set(a[0], a[1]); + }, this); + } + + function sharedDelete(key) { + if (this.has(key)) { + this._keys.splice(i, 1); + this._values.splice(i, 1); + + this._itp.forEach(function (p) { + if (i < p[0]) p[0]--; + }); + } + + return -1 < i; + }; + + function sharedGet(key) { + return this.has(key) ? this._values[i] : undefined; + } + + function has(list, key) { + if (this.objectOnly && key !== Object(key)) throw new TypeError("Invalid value used as weak collection key"); + + if (key != key || key === 0) for (i = list.length; i-- && !is(list[i], key);) {} else i = list.indexOf(key); + return -1 < i; + } + + function setHas(value) { + return has.call(this, this._values, value); + } + + function mapHas(value) { + return has.call(this, this._keys, value); + } + + function sharedSet(key, value) { + this.has(key) ? this._values[i] = value : this._values[this._keys.push(key) - 1] = value; + return this; + } + + function sharedAdd(value) { + if (!this.has(value)) this._values.push(value); + return this; + } + + function sharedClear() { + (this._keys || 0).length = this._values.length = 0; + } + + function sharedKeys() { + return sharedIterator(this._itp, this._keys); + } + + function sharedValues() { + return sharedIterator(this._itp, this._values); + } + + function mapEntries() { + return sharedIterator(this._itp, this._keys, this._values); + } + + function setEntries() { + return sharedIterator(this._itp, this._values, this._values); + } + + function sharedIterator(itp, array, array2) { + var _ref; + + var p = [0], + done = false; + itp.push(p); + return _ref = {}, _ref[Symbol.iterator] = function () { + return this; + }, _ref.next = function next() { + var v, + k = p[0]; + if (!done && k < array.length) { + v = array2 ? [array[k], array2[k]] : array[k]; + p[0]++; + } else { + done = true; + itp.splice(itp.indexOf(p), 1); + } + return { done: done, value: v }; + }, _ref; + } + + function sharedSize() { + return this._values.length; + } + + function sharedForEach(callback, context) { + var it = this.entries(); + for (;;) { + var r = it.next(); + if (r.done) break; + callback.call(context, r.value[1], r.value[0], this); + } + } + })(_aureliaPal.PLATFORM.global); + + var emptyMetadata = Object.freeze({}); + var metadataContainerKey = '__metadata__'; + var bind = Function.prototype.bind; + + if (typeof _aureliaPal.PLATFORM.global.Reflect === 'undefined') { + _aureliaPal.PLATFORM.global.Reflect = {}; + } + + if (typeof Reflect.getOwnMetadata !== 'function') { + Reflect.getOwnMetadata = function (metadataKey, target, targetKey) { + if (target.hasOwnProperty(metadataContainerKey)) { + return (target[metadataContainerKey][targetKey] || emptyMetadata)[metadataKey]; + } + }; + } + + if (typeof Reflect.defineMetadata !== 'function') { + Reflect.defineMetadata = function (metadataKey, metadataValue, target, targetKey) { + var metadataContainer = target.hasOwnProperty(metadataContainerKey) ? target[metadataContainerKey] : target[metadataContainerKey] = {}; + var targetContainer = metadataContainer[targetKey] || (metadataContainer[targetKey] = {}); + targetContainer[metadataKey] = metadataValue; + }; + } + + if (typeof Reflect.metadata !== 'function') { + Reflect.metadata = function (metadataKey, metadataValue) { + return function (target, targetKey) { + Reflect.defineMetadata(metadataKey, metadataValue, target, targetKey); + }; + }; + } + + if (typeof Reflect.defineProperty !== 'function') { + Reflect.defineProperty = function (target, propertyKey, descriptor) { + if ((typeof target === 'undefined' ? 'undefined' : _typeof(target)) === 'object' ? target === null : typeof target !== 'function') { + throw new TypeError('Reflect.defineProperty called on non-object'); + } + try { + Object.defineProperty(target, propertyKey, descriptor); + return true; + } catch (e) { + return false; + } + }; + } + + if (typeof Reflect.construct !== 'function') { + Reflect.construct = function (Target, args) { + if (args) { + switch (args.length) { + case 0: + return new Target(); + case 1: + return new Target(args[0]); + case 2: + return new Target(args[0], args[1]); + case 3: + return new Target(args[0], args[1], args[2]); + case 4: + return new Target(args[0], args[1], args[2], args[3]); + } + } + + var a = [null]; + a.push.apply(a, args); + return new (bind.apply(Target, a))(); + }; + } + + if (typeof Reflect.ownKeys !== 'function') { + Reflect.ownKeys = function (o) { + return Object.getOwnPropertyNames(o).concat(Object.getOwnPropertySymbols(o)); + }; + } +}); +define('aurelia-logging',['exports'], function (exports) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.getLogger = getLogger; + exports.addAppender = addAppender; + exports.setLevel = setLevel; + + + + var logLevel = exports.logLevel = { + none: 0, + error: 1, + warn: 2, + info: 3, + debug: 4 + }; + + var loggers = {}; + var currentLevel = logLevel.none; + var appenders = []; + var slice = Array.prototype.slice; + var loggerConstructionKey = {}; + + function log(logger, level, args) { + var i = appenders.length; + var current = void 0; + + args = slice.call(args); + args.unshift(logger); + + while (i--) { + current = appenders[i]; + current[level].apply(current, args); + } + } + + function debug() { + if (currentLevel < 4) { + return; + } + + log(this, 'debug', arguments); + } + + function info() { + if (currentLevel < 3) { + return; + } + + log(this, 'info', arguments); + } + + function warn() { + if (currentLevel < 2) { + return; + } + + log(this, 'warn', arguments); + } + + function error() { + if (currentLevel < 1) { + return; + } + + log(this, 'error', arguments); + } + + function connectLogger(logger) { + logger.debug = debug; + logger.info = info; + logger.warn = warn; + logger.error = error; + } + + function createLogger(id) { + var logger = new Logger(id, loggerConstructionKey); + + if (appenders.length) { + connectLogger(logger); + } + + return logger; + } + + function getLogger(id) { + return loggers[id] || (loggers[id] = createLogger(id)); + } + + function addAppender(appender) { + appenders.push(appender); + + if (appenders.length === 1) { + for (var key in loggers) { + connectLogger(loggers[key]); + } + } + } + + function setLevel(level) { + currentLevel = level; + } + + var Logger = exports.Logger = function () { + function Logger(id, key) { + + + if (key !== loggerConstructionKey) { + throw new Error('Cannot instantiate "Logger". Use "getLogger" instead.'); + } + + this.id = id; + } + + Logger.prototype.debug = function debug(message) {}; + + Logger.prototype.info = function info(message) {}; + + Logger.prototype.warn = function warn(message) {}; + + Logger.prototype.error = function error(message) {}; + + return Logger; + }(); +}); +define('aurelia-logging-console',['exports', 'aurelia-logging'], function (exports, _aureliaLogging) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.ConsoleAppender = undefined; + + + + var ConsoleAppender = exports.ConsoleAppender = function () { + function ConsoleAppender() { + + } + + ConsoleAppender.prototype.debug = function debug(logger) { + var _console; + + for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + rest[_key - 1] = arguments[_key]; + } + + (_console = console).debug.apply(_console, ['DEBUG [' + logger.id + ']'].concat(rest)); + }; + + ConsoleAppender.prototype.info = function info(logger) { + var _console2; + + for (var _len2 = arguments.length, rest = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + rest[_key2 - 1] = arguments[_key2]; + } + + (_console2 = console).info.apply(_console2, ['INFO [' + logger.id + ']'].concat(rest)); + }; + + ConsoleAppender.prototype.warn = function warn(logger) { + var _console3; + + for (var _len3 = arguments.length, rest = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + rest[_key3 - 1] = arguments[_key3]; + } + + (_console3 = console).warn.apply(_console3, ['WARN [' + logger.id + ']'].concat(rest)); + }; + + ConsoleAppender.prototype.error = function error(logger) { + var _console4; + + for (var _len4 = arguments.length, rest = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + rest[_key4 - 1] = arguments[_key4]; + } + + (_console4 = console).error.apply(_console4, ['ERROR [' + logger.id + ']'].concat(rest)); + }; + + return ConsoleAppender; + }(); +}); +define('aurelia-path',['exports'], function (exports) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.relativeToFile = relativeToFile; + exports.join = join; + exports.buildQueryString = buildQueryString; + exports.parseQueryString = parseQueryString; + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; + }; + + function trimDots(ary) { + for (var i = 0; i < ary.length; ++i) { + var part = ary[i]; + if (part === '.') { + ary.splice(i, 1); + i -= 1; + } else if (part === '..') { + if (i === 0 || i === 1 && ary[2] === '..' || ary[i - 1] === '..') { + continue; + } else if (i > 0) { + ary.splice(i - 1, 2); + i -= 2; + } + } + } + } + + function relativeToFile(name, file) { + var fileParts = file && file.split('/'); + var nameParts = name.trim().split('/'); + + if (nameParts[0].charAt(0) === '.' && fileParts) { + var normalizedBaseParts = fileParts.slice(0, fileParts.length - 1); + nameParts.unshift.apply(nameParts, normalizedBaseParts); + } + + trimDots(nameParts); + + return nameParts.join('/'); + } + + function join(path1, path2) { + if (!path1) { + return path2; + } + + if (!path2) { + return path1; + } + + var schemeMatch = path1.match(/^([^/]*?:)\//); + var scheme = schemeMatch && schemeMatch.length > 0 ? schemeMatch[1] : ''; + path1 = path1.substr(scheme.length); + + var urlPrefix = void 0; + if (path1.indexOf('///') === 0 && scheme === 'file:') { + urlPrefix = '///'; + } else if (path1.indexOf('//') === 0) { + urlPrefix = '//'; + } else if (path1.indexOf('/') === 0) { + urlPrefix = '/'; + } else { + urlPrefix = ''; + } + + var trailingSlash = path2.slice(-1) === '/' ? '/' : ''; + + var url1 = path1.split('/'); + var url2 = path2.split('/'); + var url3 = []; + + for (var i = 0, ii = url1.length; i < ii; ++i) { + if (url1[i] === '..') { + url3.pop(); + } else if (url1[i] === '.' || url1[i] === '') { + continue; + } else { + url3.push(url1[i]); + } + } + + for (var _i = 0, _ii = url2.length; _i < _ii; ++_i) { + if (url2[_i] === '..') { + url3.pop(); + } else if (url2[_i] === '.' || url2[_i] === '') { + continue; + } else { + url3.push(url2[_i]); + } + } + + return scheme + urlPrefix + url3.join('/') + trailingSlash; + } + + var encode = encodeURIComponent; + var encodeKey = function encodeKey(k) { + return encode(k).replace('%24', '$'); + }; + + function buildParam(key, value, traditional) { + var result = []; + if (value === null || value === undefined) { + return result; + } + if (Array.isArray(value)) { + for (var i = 0, l = value.length; i < l; i++) { + if (traditional) { + result.push(encodeKey(key) + '=' + encode(value[i])); + } else { + var arrayKey = key + '[' + (_typeof(value[i]) === 'object' && value[i] !== null ? i : '') + ']'; + result = result.concat(buildParam(arrayKey, value[i])); + } + } + } else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && !traditional) { + for (var propertyName in value) { + result = result.concat(buildParam(key + '[' + propertyName + ']', value[propertyName])); + } + } else { + result.push(encodeKey(key) + '=' + encode(value)); + } + return result; + } + + function buildQueryString(params, traditional) { + var pairs = []; + var keys = Object.keys(params || {}).sort(); + for (var i = 0, len = keys.length; i < len; i++) { + var key = keys[i]; + pairs = pairs.concat(buildParam(key, params[key], traditional)); + } + + if (pairs.length === 0) { + return ''; + } + + return pairs.join('&'); + } + + function processScalarParam(existedParam, value) { + if (Array.isArray(existedParam)) { + existedParam.push(value); + return existedParam; + } + if (existedParam !== undefined) { + return [existedParam, value]; + } + + return value; + } + + function parseComplexParam(queryParams, keys, value) { + var currentParams = queryParams; + var keysLastIndex = keys.length - 1; + for (var j = 0; j <= keysLastIndex; j++) { + var key = keys[j] === '' ? currentParams.length : keys[j]; + if (j < keysLastIndex) { + var prevValue = !currentParams[key] || _typeof(currentParams[key]) === 'object' ? currentParams[key] : [currentParams[key]]; + currentParams = currentParams[key] = prevValue || (isNaN(keys[j + 1]) ? {} : []); + } else { + currentParams = currentParams[key] = value; + } + } + } + + function parseQueryString(queryString) { + var queryParams = {}; + if (!queryString || typeof queryString !== 'string') { + return queryParams; + } + + var query = queryString; + if (query.charAt(0) === '?') { + query = query.substr(1); + } + + var pairs = query.replace(/\+/g, ' ').split('&'); + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i].split('='); + var key = decodeURIComponent(pair[0]); + if (!key) { + continue; + } + + var keys = key.split(']['); + var keysLastIndex = keys.length - 1; + + if (/\[/.test(keys[0]) && /\]$/.test(keys[keysLastIndex])) { + keys[keysLastIndex] = keys[keysLastIndex].replace(/\]$/, ''); + keys = keys.shift().split('[').concat(keys); + keysLastIndex = keys.length - 1; + } else { + keysLastIndex = 0; + } + + if (pair.length >= 2) { + var value = pair[1] ? decodeURIComponent(pair[1]) : ''; + if (keysLastIndex) { + parseComplexParam(queryParams, keys, value); + } else { + queryParams[key] = processScalarParam(queryParams[key], value); + } + } else { + queryParams[key] = true; + } + } + return queryParams; + } +}); +define('aurelia-route-recognizer',['exports', 'aurelia-path'], function (exports, _aureliaPath) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.RouteRecognizer = exports.EpsilonSegment = exports.StarSegment = exports.DynamicSegment = exports.StaticSegment = exports.State = undefined; + + + + var State = exports.State = function () { + function State(charSpec) { + + + this.charSpec = charSpec; + this.nextStates = []; + } + + State.prototype.get = function get(charSpec) { + for (var _iterator = this.nextStates, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var child = _ref; + + var isEqual = child.charSpec.validChars === charSpec.validChars && child.charSpec.invalidChars === charSpec.invalidChars; + + if (isEqual) { + return child; + } + } + + return undefined; + }; + + State.prototype.put = function put(charSpec) { + var state = this.get(charSpec); + + if (state) { + return state; + } + + state = new State(charSpec); + + this.nextStates.push(state); + + if (charSpec.repeat) { + state.nextStates.push(state); + } + + return state; + }; + + State.prototype.match = function match(ch) { + var nextStates = this.nextStates; + var results = []; + + for (var i = 0, l = nextStates.length; i < l; i++) { + var child = nextStates[i]; + var charSpec = child.charSpec; + + if (charSpec.validChars !== undefined) { + if (charSpec.validChars.indexOf(ch) !== -1) { + results.push(child); + } + } else if (charSpec.invalidChars !== undefined) { + if (charSpec.invalidChars.indexOf(ch) === -1) { + results.push(child); + } + } + } + + return results; + }; + + return State; + }(); + + var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\']; + + var escapeRegex = new RegExp('(\\' + specials.join('|\\') + ')', 'g'); + + var StaticSegment = exports.StaticSegment = function () { + function StaticSegment(string, caseSensitive) { + + + this.string = string; + this.caseSensitive = caseSensitive; + } + + StaticSegment.prototype.eachChar = function eachChar(callback) { + var s = this.string; + for (var i = 0, ii = s.length; i < ii; ++i) { + var ch = s[i]; + callback({ validChars: this.caseSensitive ? ch : ch.toUpperCase() + ch.toLowerCase() }); + } + }; + + StaticSegment.prototype.regex = function regex() { + return this.string.replace(escapeRegex, '\\$1'); + }; + + StaticSegment.prototype.generate = function generate() { + return this.string; + }; + + return StaticSegment; + }(); + + var DynamicSegment = exports.DynamicSegment = function () { + function DynamicSegment(name, optional) { + + + this.name = name; + this.optional = optional; + } + + DynamicSegment.prototype.eachChar = function eachChar(callback) { + callback({ invalidChars: '/', repeat: true }); + }; + + DynamicSegment.prototype.regex = function regex() { + return this.optional ? '([^/]+)?' : '([^/]+)'; + }; + + DynamicSegment.prototype.generate = function generate(params, consumed) { + consumed[this.name] = true; + return params[this.name]; + }; + + return DynamicSegment; + }(); + + var StarSegment = exports.StarSegment = function () { + function StarSegment(name) { + + + this.name = name; + } + + StarSegment.prototype.eachChar = function eachChar(callback) { + callback({ invalidChars: '', repeat: true }); + }; + + StarSegment.prototype.regex = function regex() { + return '(.+)'; + }; + + StarSegment.prototype.generate = function generate(params, consumed) { + consumed[this.name] = true; + return params[this.name]; + }; + + return StarSegment; + }(); + + var EpsilonSegment = exports.EpsilonSegment = function () { + function EpsilonSegment() { + + } + + EpsilonSegment.prototype.eachChar = function eachChar() {}; + + EpsilonSegment.prototype.regex = function regex() { + return ''; + }; + + EpsilonSegment.prototype.generate = function generate() { + return ''; + }; + + return EpsilonSegment; + }(); + + var RouteRecognizer = exports.RouteRecognizer = function () { + function RouteRecognizer() { + + + this.rootState = new State(); + this.names = {}; + } + + RouteRecognizer.prototype.add = function add(route) { + var _this = this; + + if (Array.isArray(route)) { + route.forEach(function (r) { + return _this.add(r); + }); + return undefined; + } + + var currentState = this.rootState; + var regex = '^'; + var types = { statics: 0, dynamics: 0, stars: 0 }; + var names = []; + var routeName = route.handler.name; + var isEmpty = true; + var isAllOptional = true; + var segments = parse(route.path, names, types, route.caseSensitive); + + for (var i = 0, ii = segments.length; i < ii; i++) { + var segment = segments[i]; + if (segment instanceof EpsilonSegment) { + continue; + } + + isEmpty = false; + isAllOptional = isAllOptional && segment.optional; + + currentState = addSegment(currentState, segment); + regex += segment.optional ? '/?' : '/'; + regex += segment.regex(); + } + + if (isAllOptional) { + if (isEmpty) { + currentState = currentState.put({ validChars: '/' }); + regex += '/'; + } else { + var finalState = this.rootState.put({ validChars: '/' }); + currentState.epsilon = [finalState]; + currentState = finalState; + } + } + + var handlers = [{ handler: route.handler, names: names }]; + + if (routeName) { + var routeNames = Array.isArray(routeName) ? routeName : [routeName]; + for (var _i2 = 0; _i2 < routeNames.length; _i2++) { + this.names[routeNames[_i2]] = { + segments: segments, + handlers: handlers + }; + } + } + + currentState.handlers = handlers; + currentState.regex = new RegExp(regex + '$', route.caseSensitive ? '' : 'i'); + currentState.types = types; + + return currentState; + }; + + RouteRecognizer.prototype.handlersFor = function handlersFor(name) { + var route = this.names[name]; + if (!route) { + throw new Error('There is no route named ' + name); + } + + return [].concat(route.handlers); + }; + + RouteRecognizer.prototype.hasRoute = function hasRoute(name) { + return !!this.names[name]; + }; + + RouteRecognizer.prototype.generate = function generate(name, params) { + var route = this.names[name]; + if (!route) { + throw new Error('There is no route named ' + name); + } + + var handler = route.handlers[0].handler; + if (handler.generationUsesHref) { + return handler.href; + } + + var routeParams = Object.assign({}, params); + var segments = route.segments; + var consumed = {}; + var output = ''; + + for (var i = 0, l = segments.length; i < l; i++) { + var segment = segments[i]; + + if (segment instanceof EpsilonSegment) { + continue; + } + + var segmentValue = segment.generate(routeParams, consumed); + if (segmentValue === null || segmentValue === undefined) { + if (!segment.optional) { + throw new Error('A value is required for route parameter \'' + segment.name + '\' in route \'' + name + '\'.'); + } + } else { + output += '/'; + output += segmentValue; + } + } + + if (output.charAt(0) !== '/') { + output = '/' + output; + } + + for (var param in consumed) { + delete routeParams[param]; + } + + var queryString = (0, _aureliaPath.buildQueryString)(routeParams); + output += queryString ? '?' + queryString : ''; + + return output; + }; + + RouteRecognizer.prototype.recognize = function recognize(path) { + var states = [this.rootState]; + var queryParams = {}; + var isSlashDropped = false; + var normalizedPath = path; + + var queryStart = normalizedPath.indexOf('?'); + if (queryStart !== -1) { + var queryString = normalizedPath.substr(queryStart + 1, normalizedPath.length); + normalizedPath = normalizedPath.substr(0, queryStart); + queryParams = (0, _aureliaPath.parseQueryString)(queryString); + } + + normalizedPath = decodeURI(normalizedPath); + + if (normalizedPath.charAt(0) !== '/') { + normalizedPath = '/' + normalizedPath; + } + + var pathLen = normalizedPath.length; + if (pathLen > 1 && normalizedPath.charAt(pathLen - 1) === '/') { + normalizedPath = normalizedPath.substr(0, pathLen - 1); + isSlashDropped = true; + } + + for (var i = 0, l = normalizedPath.length; i < l; i++) { + states = recognizeChar(states, normalizedPath.charAt(i)); + if (!states.length) { + break; + } + } + + var solutions = []; + for (var _i3 = 0, _l = states.length; _i3 < _l; _i3++) { + if (states[_i3].handlers) { + solutions.push(states[_i3]); + } + } + + states = sortSolutions(solutions); + + var state = solutions[0]; + if (state && state.handlers) { + if (isSlashDropped && state.regex.source.slice(-5) === '(.+)$') { + normalizedPath = normalizedPath + '/'; + } + + return findHandler(state, normalizedPath, queryParams); + } + + return undefined; + }; + + return RouteRecognizer; + }(); + + var RecognizeResults = function RecognizeResults(queryParams) { + + + this.splice = Array.prototype.splice; + this.slice = Array.prototype.slice; + this.push = Array.prototype.push; + this.length = 0; + this.queryParams = queryParams || {}; + }; + + function parse(route, names, types, caseSensitive) { + var normalizedRoute = route; + if (route.charAt(0) === '/') { + normalizedRoute = route.substr(1); + } + + var results = []; + + var splitRoute = normalizedRoute.split('/'); + for (var i = 0, ii = splitRoute.length; i < ii; ++i) { + var segment = splitRoute[i]; + + var match = segment.match(/^:([^?]+)(\?)?$/); + if (match) { + var _match = match; + var _name = _match[1]; + var optional = _match[2]; + + if (_name.indexOf('=') !== -1) { + throw new Error('Parameter ' + _name + ' in route ' + route + ' has a default value, which is not supported.'); + } + results.push(new DynamicSegment(_name, !!optional)); + names.push(_name); + types.dynamics++; + continue; + } + + match = segment.match(/^\*(.+)$/); + if (match) { + results.push(new StarSegment(match[1])); + names.push(match[1]); + types.stars++; + } else if (segment === '') { + results.push(new EpsilonSegment()); + } else { + results.push(new StaticSegment(segment, caseSensitive)); + types.statics++; + } + } + + return results; + } + + function sortSolutions(states) { + return states.sort(function (a, b) { + if (a.types.stars !== b.types.stars) { + return a.types.stars - b.types.stars; + } + + if (a.types.stars) { + if (a.types.statics !== b.types.statics) { + return b.types.statics - a.types.statics; + } + if (a.types.dynamics !== b.types.dynamics) { + return b.types.dynamics - a.types.dynamics; + } + } + + if (a.types.dynamics !== b.types.dynamics) { + return a.types.dynamics - b.types.dynamics; + } + + if (a.types.statics !== b.types.statics) { + return b.types.statics - a.types.statics; + } + + return 0; + }); + } + + function recognizeChar(states, ch) { + var nextStates = []; + + for (var i = 0, l = states.length; i < l; i++) { + var state = states[i]; + nextStates.push.apply(nextStates, state.match(ch)); + } + + var skippableStates = nextStates.filter(function (s) { + return s.epsilon; + }); + + var _loop = function _loop() { + var newStates = []; + skippableStates.forEach(function (s) { + nextStates.push.apply(nextStates, s.epsilon); + newStates.push.apply(newStates, s.epsilon); + }); + skippableStates = newStates.filter(function (s) { + return s.epsilon; + }); + }; + + while (skippableStates.length > 0) { + _loop(); + } + + return nextStates; + } + + function findHandler(state, path, queryParams) { + var handlers = state.handlers; + var regex = state.regex; + var captures = path.match(regex); + var currentCapture = 1; + var result = new RecognizeResults(queryParams); + + for (var i = 0, l = handlers.length; i < l; i++) { + var _handler = handlers[i]; + var _names = _handler.names; + var _params = {}; + + for (var j = 0, m = _names.length; j < m; j++) { + _params[_names[j]] = captures[currentCapture++]; + } + + result.push({ handler: _handler.handler, params: _params, isDynamic: !!_names.length }); + } + + return result; + } + + function addSegment(currentState, segment) { + var state = currentState.put({ validChars: '/' }); + segment.eachChar(function (ch) { + state = state.put(ch); + }); + + if (segment.optional) { + currentState.epsilon = currentState.epsilon || []; + currentState.epsilon.push(state); + } + + return state; + } +}); +define('aurelia-router',['exports', 'aurelia-logging', 'aurelia-route-recognizer', 'aurelia-dependency-injection', 'aurelia-history', 'aurelia-event-aggregator'], function (exports, _aureliaLogging, _aureliaRouteRecognizer, _aureliaDependencyInjection, _aureliaHistory, _aureliaEventAggregator) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.AppRouter = exports.PipelineProvider = exports.LoadRouteStep = exports.RouteLoader = exports.ActivateNextStep = exports.DeactivatePreviousStep = exports.CanActivateNextStep = exports.CanDeactivatePreviousStep = exports.Router = exports.BuildNavigationPlanStep = exports.activationStrategy = exports.RouterConfiguration = exports.RedirectToRoute = exports.Redirect = exports.NavModel = exports.NavigationInstruction = exports.CommitChangesStep = exports.Pipeline = exports.pipelineStatus = undefined; + exports._normalizeAbsolutePath = _normalizeAbsolutePath; + exports._createRootedPath = _createRootedPath; + exports._resolveUrl = _resolveUrl; + exports.isNavigationCommand = isNavigationCommand; + exports._buildNavigationPlan = _buildNavigationPlan; + + var LogManager = _interopRequireWildcard(_aureliaLogging); + + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + + newObj.default = obj; + return newObj; + } + } + + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; + }; + + var _createClass = function () { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + return function (Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps); + if (staticProps) defineProperties(Constructor, staticProps); + return Constructor; + }; + }(); + + + + function _normalizeAbsolutePath(path, hasPushState) { + var absolute = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; + + if (!hasPushState && path[0] !== '#') { + path = '#' + path; + } + + if (hasPushState && absolute) { + path = path.substring(1, path.length); + } + + return path; + } + + function _createRootedPath(fragment, baseUrl, hasPushState, absolute) { + if (isAbsoluteUrl.test(fragment)) { + return fragment; + } + + var path = ''; + + if (baseUrl.length && baseUrl[0] !== '/') { + path += '/'; + } + + path += baseUrl; + + if ((!path.length || path[path.length - 1] !== '/') && fragment[0] !== '/') { + path += '/'; + } + + if (path.length && path[path.length - 1] === '/' && fragment[0] === '/') { + path = path.substring(0, path.length - 1); + } + + return _normalizeAbsolutePath(path + fragment, hasPushState, absolute); + } + + function _resolveUrl(fragment, baseUrl, hasPushState) { + if (isRootedPath.test(fragment)) { + return _normalizeAbsolutePath(fragment, hasPushState); + } + + return _createRootedPath(fragment, baseUrl, hasPushState); + } + + var isRootedPath = /^#?\//; + var isAbsoluteUrl = /^([a-z][a-z0-9+\-.]*:)?\/\//i; + + var pipelineStatus = exports.pipelineStatus = { + completed: 'completed', + canceled: 'canceled', + rejected: 'rejected', + running: 'running' + }; + + var Pipeline = exports.Pipeline = function () { + function Pipeline() { + + + this.steps = []; + } + + Pipeline.prototype.addStep = function addStep(step) { + var run = void 0; + + if (typeof step === 'function') { + run = step; + } else if (typeof step.getSteps === 'function') { + var steps = step.getSteps(); + for (var i = 0, l = steps.length; i < l; i++) { + this.addStep(steps[i]); + } + + return this; + } else { + run = step.run.bind(step); + } + + this.steps.push(run); + + return this; + }; + + Pipeline.prototype.run = function run(instruction) { + var index = -1; + var steps = this.steps; + + function next() { + index++; + + if (index < steps.length) { + var currentStep = steps[index]; + + try { + return currentStep(instruction, next); + } catch (e) { + return next.reject(e); + } + } else { + return next.complete(); + } + } + + next.complete = createCompletionHandler(next, pipelineStatus.completed); + next.cancel = createCompletionHandler(next, pipelineStatus.canceled); + next.reject = createCompletionHandler(next, pipelineStatus.rejected); + + return next(); + }; + + return Pipeline; + }(); + + function createCompletionHandler(next, status) { + return function (output) { + return Promise.resolve({ status: status, output: output, completed: status === pipelineStatus.completed }); + }; + } + + var CommitChangesStep = exports.CommitChangesStep = function () { + function CommitChangesStep() { + + } + + CommitChangesStep.prototype.run = function run(navigationInstruction, next) { + return navigationInstruction._commitChanges(true).then(function () { + navigationInstruction._updateTitle(); + return next(); + }); + }; + + return CommitChangesStep; + }(); + + var NavigationInstruction = exports.NavigationInstruction = function () { + function NavigationInstruction(init) { + + + this.plan = null; + this.options = {}; + + Object.assign(this, init); + + this.params = this.params || {}; + this.viewPortInstructions = {}; + + var ancestorParams = []; + var current = this; + do { + var currentParams = Object.assign({}, current.params); + if (current.config && current.config.hasChildRouter) { + delete currentParams[current.getWildCardName()]; + } + + ancestorParams.unshift(currentParams); + current = current.parentInstruction; + } while (current); + + var allParams = Object.assign.apply(Object, [{}, this.queryParams].concat(ancestorParams)); + this.lifecycleArgs = [allParams, this.config, this]; + } + + NavigationInstruction.prototype.getAllInstructions = function getAllInstructions() { + var instructions = [this]; + for (var key in this.viewPortInstructions) { + var childInstruction = this.viewPortInstructions[key].childNavigationInstruction; + if (childInstruction) { + instructions.push.apply(instructions, childInstruction.getAllInstructions()); + } + } + + return instructions; + }; + + NavigationInstruction.prototype.getAllPreviousInstructions = function getAllPreviousInstructions() { + return this.getAllInstructions().map(function (c) { + return c.previousInstruction; + }).filter(function (c) { + return c; + }); + }; + + NavigationInstruction.prototype.addViewPortInstruction = function addViewPortInstruction(viewPortName, strategy, moduleId, component) { + var viewportInstruction = this.viewPortInstructions[viewPortName] = { + name: viewPortName, + strategy: strategy, + moduleId: moduleId, + component: component, + childRouter: component.childRouter, + lifecycleArgs: this.lifecycleArgs.slice() + }; + + return viewportInstruction; + }; + + NavigationInstruction.prototype.getWildCardName = function getWildCardName() { + var wildcardIndex = this.config.route.lastIndexOf('*'); + return this.config.route.substr(wildcardIndex + 1); + }; + + NavigationInstruction.prototype.getWildcardPath = function getWildcardPath() { + var wildcardName = this.getWildCardName(); + var path = this.params[wildcardName] || ''; + + if (this.queryString) { + path += '?' + this.queryString; + } + + return path; + }; + + NavigationInstruction.prototype.getBaseUrl = function getBaseUrl() { + if (!this.params) { + return this.fragment; + } + + var wildcardName = this.getWildCardName(); + var path = this.params[wildcardName] || ''; + + if (!path) { + return this.fragment; + } + + path = encodeURI(path); + return this.fragment.substr(0, this.fragment.lastIndexOf(path)); + }; + + NavigationInstruction.prototype._commitChanges = function _commitChanges(waitToSwap) { + var _this = this; + + var router = this.router; + router.currentInstruction = this; + + if (this.previousInstruction) { + this.previousInstruction.config.navModel.isActive = false; + } + + this.config.navModel.isActive = true; + + router._refreshBaseUrl(); + router.refreshNavigation(); + + var loads = []; + var delaySwaps = []; + + var _loop = function _loop(viewPortName) { + var viewPortInstruction = _this.viewPortInstructions[viewPortName]; + var viewPort = router.viewPorts[viewPortName]; + + if (!viewPort) { + throw new Error('There was no router-view found in the view for ' + viewPortInstruction.moduleId + '.'); + } + + if (viewPortInstruction.strategy === activationStrategy.replace) { + if (waitToSwap) { + delaySwaps.push({ viewPort: viewPort, viewPortInstruction: viewPortInstruction }); + } + + loads.push(viewPort.process(viewPortInstruction, waitToSwap).then(function (x) { + if (viewPortInstruction.childNavigationInstruction) { + return viewPortInstruction.childNavigationInstruction._commitChanges(); + } + + return undefined; + })); + } else { + if (viewPortInstruction.childNavigationInstruction) { + loads.push(viewPortInstruction.childNavigationInstruction._commitChanges(waitToSwap)); + } + } + }; + + for (var viewPortName in this.viewPortInstructions) { + _loop(viewPortName); + } + + return Promise.all(loads).then(function () { + delaySwaps.forEach(function (x) { + return x.viewPort.swap(x.viewPortInstruction); + }); + return null; + }).then(function () { + return prune(_this); + }); + }; + + NavigationInstruction.prototype._updateTitle = function _updateTitle() { + var title = this._buildTitle(); + if (title) { + this.router.history.setTitle(title); + } + }; + + NavigationInstruction.prototype._buildTitle = function _buildTitle() { + var separator = arguments.length <= 0 || arguments[0] === undefined ? ' | ' : arguments[0]; + + var title = this.config.navModel.title || ''; + var childTitles = []; + + for (var viewPortName in this.viewPortInstructions) { + var _viewPortInstruction = this.viewPortInstructions[viewPortName]; + + if (_viewPortInstruction.childNavigationInstruction) { + var childTitle = _viewPortInstruction.childNavigationInstruction._buildTitle(separator); + if (childTitle) { + childTitles.push(childTitle); + } + } + } + + if (childTitles.length) { + title = childTitles.join(separator) + (title ? separator : '') + title; + } + + if (this.router.title) { + title += (title ? separator : '') + this.router.title; + } + + return title; + }; + + return NavigationInstruction; + }(); + + function prune(instruction) { + instruction.previousInstruction = null; + instruction.plan = null; + } + + var NavModel = exports.NavModel = function () { + function NavModel(router, relativeHref) { + + + this.isActive = false; + this.title = null; + this.href = null; + this.relativeHref = null; + this.settings = {}; + this.config = null; + + this.router = router; + this.relativeHref = relativeHref; + } + + NavModel.prototype.setTitle = function setTitle(title) { + this.title = title; + + if (this.isActive) { + this.router.updateTitle(); + } + }; + + return NavModel; + }(); + + function isNavigationCommand(obj) { + return obj && typeof obj.navigate === 'function'; + } + + var Redirect = exports.Redirect = function () { + function Redirect(url) { + var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + + + + this.url = url; + this.options = Object.assign({ trigger: true, replace: true }, options); + this.shouldContinueProcessing = false; + } + + Redirect.prototype.setRouter = function setRouter(router) { + this.router = router; + }; + + Redirect.prototype.navigate = function navigate(appRouter) { + var navigatingRouter = this.options.useAppRouter ? appRouter : this.router || appRouter; + navigatingRouter.navigate(this.url, this.options); + }; + + return Redirect; + }(); + + var RedirectToRoute = exports.RedirectToRoute = function () { + function RedirectToRoute(route) { + var params = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + + + + this.route = route; + this.params = params; + this.options = Object.assign({ trigger: true, replace: true }, options); + this.shouldContinueProcessing = false; + } + + RedirectToRoute.prototype.setRouter = function setRouter(router) { + this.router = router; + }; + + RedirectToRoute.prototype.navigate = function navigate(appRouter) { + var navigatingRouter = this.options.useAppRouter ? appRouter : this.router || appRouter; + navigatingRouter.navigateToRoute(this.route, this.params, this.options); + }; + + return RedirectToRoute; + }(); + + var RouterConfiguration = exports.RouterConfiguration = function () { + function RouterConfiguration() { + + + this.instructions = []; + this.options = {}; + this.pipelineSteps = []; + } + + RouterConfiguration.prototype.addPipelineStep = function addPipelineStep(name, step) { + this.pipelineSteps.push({ name: name, step: step }); + return this; + }; + + RouterConfiguration.prototype.addAuthorizeStep = function addAuthorizeStep(step) { + return this.addPipelineStep('authorize', step); + }; + + RouterConfiguration.prototype.addPreActivateStep = function addPreActivateStep(step) { + return this.addPipelineStep('preActivate', step); + }; + + RouterConfiguration.prototype.addPreRenderStep = function addPreRenderStep(step) { + return this.addPipelineStep('preRender', step); + }; + + RouterConfiguration.prototype.addPostRenderStep = function addPostRenderStep(step) { + return this.addPipelineStep('postRender', step); + }; + + RouterConfiguration.prototype.map = function map(route) { + if (Array.isArray(route)) { + route.forEach(this.map.bind(this)); + return this; + } + + return this.mapRoute(route); + }; + + RouterConfiguration.prototype.mapRoute = function mapRoute(config) { + this.instructions.push(function (router) { + var routeConfigs = []; + + if (Array.isArray(config.route)) { + for (var i = 0, ii = config.route.length; i < ii; ++i) { + var current = Object.assign({}, config); + current.route = config.route[i]; + routeConfigs.push(current); + } + } else { + routeConfigs.push(Object.assign({}, config)); + } + + var navModel = void 0; + for (var _i = 0, _ii = routeConfigs.length; _i < _ii; ++_i) { + var _routeConfig = routeConfigs[_i]; + _routeConfig.settings = _routeConfig.settings || {}; + if (!navModel) { + navModel = router.createNavModel(_routeConfig); + } + + router.addRoute(_routeConfig, navModel); + } + }); + + return this; + }; + + RouterConfiguration.prototype.mapUnknownRoutes = function mapUnknownRoutes(config) { + this.unknownRouteConfig = config; + return this; + }; + + RouterConfiguration.prototype.exportToRouter = function exportToRouter(router) { + var instructions = this.instructions; + for (var i = 0, ii = instructions.length; i < ii; ++i) { + instructions[i](router); + } + + if (this.title) { + router.title = this.title; + } + + if (this.unknownRouteConfig) { + router.handleUnknownRoutes(this.unknownRouteConfig); + } + + router.options = this.options; + + var pipelineSteps = this.pipelineSteps; + if (pipelineSteps.length) { + if (!router.isRoot) { + throw new Error('Pipeline steps can only be added to the root router'); + } + + var pipelineProvider = router.pipelineProvider; + for (var _i2 = 0, _ii2 = pipelineSteps.length; _i2 < _ii2; ++_i2) { + var _pipelineSteps$_i = pipelineSteps[_i2]; + var _name = _pipelineSteps$_i.name; + var step = _pipelineSteps$_i.step; + + pipelineProvider.addStep(_name, step); + } + } + }; + + return RouterConfiguration; + }(); + + var activationStrategy = exports.activationStrategy = { + noChange: 'no-change', + invokeLifecycle: 'invoke-lifecycle', + replace: 'replace' + }; + + var BuildNavigationPlanStep = exports.BuildNavigationPlanStep = function () { + function BuildNavigationPlanStep() { + + } + + BuildNavigationPlanStep.prototype.run = function run(navigationInstruction, next) { + return _buildNavigationPlan(navigationInstruction).then(function (plan) { + navigationInstruction.plan = plan; + return next(); + }).catch(next.cancel); + }; + + return BuildNavigationPlanStep; + }(); + + function _buildNavigationPlan(instruction, forceLifecycleMinimum) { + var prev = instruction.previousInstruction; + var config = instruction.config; + var plan = {}; + + if ('redirect' in config) { + var redirectLocation = _resolveUrl(config.redirect, getInstructionBaseUrl(instruction)); + if (instruction.queryString) { + redirectLocation += '?' + instruction.queryString; + } + + return Promise.reject(new Redirect(redirectLocation)); + } + + if (prev) { + var newParams = hasDifferentParameterValues(prev, instruction); + var pending = []; + + var _loop2 = function _loop2(viewPortName) { + var prevViewPortInstruction = prev.viewPortInstructions[viewPortName]; + var nextViewPortConfig = config.viewPorts[viewPortName]; + + if (!nextViewPortConfig) throw new Error('Invalid Route Config: Configuration for viewPort "' + viewPortName + '" was not found for route: "' + instruction.config.route + '."'); + + var viewPortPlan = plan[viewPortName] = { + name: viewPortName, + config: nextViewPortConfig, + prevComponent: prevViewPortInstruction.component, + prevModuleId: prevViewPortInstruction.moduleId + }; + + if (prevViewPortInstruction.moduleId !== nextViewPortConfig.moduleId) { + viewPortPlan.strategy = activationStrategy.replace; + } else if ('determineActivationStrategy' in prevViewPortInstruction.component.viewModel) { + var _prevViewPortInstruct; + + viewPortPlan.strategy = (_prevViewPortInstruct = prevViewPortInstruction.component.viewModel).determineActivationStrategy.apply(_prevViewPortInstruct, instruction.lifecycleArgs); + } else if (config.activationStrategy) { + viewPortPlan.strategy = config.activationStrategy; + } else if (newParams || forceLifecycleMinimum) { + viewPortPlan.strategy = activationStrategy.invokeLifecycle; + } else { + viewPortPlan.strategy = activationStrategy.noChange; + } + + if (viewPortPlan.strategy !== activationStrategy.replace && prevViewPortInstruction.childRouter) { + var path = instruction.getWildcardPath(); + var task = prevViewPortInstruction.childRouter._createNavigationInstruction(path, instruction).then(function (childInstruction) { + viewPortPlan.childNavigationInstruction = childInstruction; + + return _buildNavigationPlan(childInstruction, viewPortPlan.strategy === activationStrategy.invokeLifecycle).then(function (childPlan) { + childInstruction.plan = childPlan; + }); + }); + + pending.push(task); + } + }; + + for (var viewPortName in prev.viewPortInstructions) { + _loop2(viewPortName); + } + + return Promise.all(pending).then(function () { + return plan; + }); + } + + for (var _viewPortName in config.viewPorts) { + plan[_viewPortName] = { + name: _viewPortName, + strategy: activationStrategy.replace, + config: instruction.config.viewPorts[_viewPortName] + }; + } + + return Promise.resolve(plan); + } + + function hasDifferentParameterValues(prev, next) { + var prevParams = prev.params; + var nextParams = next.params; + var nextWildCardName = next.config.hasChildRouter ? next.getWildCardName() : null; + + for (var key in nextParams) { + if (key === nextWildCardName) { + continue; + } + + if (prevParams[key] !== nextParams[key]) { + return true; + } + } + + for (var _key in prevParams) { + if (_key === nextWildCardName) { + continue; + } + + if (prevParams[_key] !== nextParams[_key]) { + return true; + } + } + + if (!next.options.compareQueryParams) { + return false; + } + + var prevQueryParams = prev.queryParams; + var nextQueryParams = next.queryParams; + for (var _key2 in nextQueryParams) { + if (prevQueryParams[_key2] !== nextQueryParams[_key2]) { + return true; + } + } + + for (var _key3 in prevQueryParams) { + if (prevQueryParams[_key3] !== nextQueryParams[_key3]) { + return true; + } + } + + return false; + } + + function getInstructionBaseUrl(instruction) { + var instructionBaseUrlParts = []; + instruction = instruction.parentInstruction; + + while (instruction) { + instructionBaseUrlParts.unshift(instruction.getBaseUrl()); + instruction = instruction.parentInstruction; + } + + instructionBaseUrlParts.unshift('/'); + return instructionBaseUrlParts.join(''); + } + + var Router = exports.Router = function () { + function Router(container, history) { + + + this.parent = null; + this.options = {}; + + this.container = container; + this.history = history; + this.reset(); + } + + Router.prototype.reset = function reset() { + var _this2 = this; + + this.viewPorts = {}; + this.routes = []; + this.baseUrl = ''; + this.isConfigured = false; + this.isNavigating = false; + this.navigation = []; + this.currentInstruction = null; + this._fallbackOrder = 100; + this._recognizer = new _aureliaRouteRecognizer.RouteRecognizer(); + this._childRecognizer = new _aureliaRouteRecognizer.RouteRecognizer(); + this._configuredPromise = new Promise(function (resolve) { + _this2._resolveConfiguredPromise = resolve; + }); + }; + + Router.prototype.registerViewPort = function registerViewPort(viewPort, name) { + name = name || 'default'; + this.viewPorts[name] = viewPort; + }; + + Router.prototype.ensureConfigured = function ensureConfigured() { + return this._configuredPromise; + }; + + Router.prototype.configure = function configure(callbackOrConfig) { + var _this3 = this; + + this.isConfigured = true; + + var result = callbackOrConfig; + var config = void 0; + if (typeof callbackOrConfig === 'function') { + config = new RouterConfiguration(); + result = callbackOrConfig(config); + } + + return Promise.resolve(result).then(function (c) { + if (c && c.exportToRouter) { + config = c; + } + + config.exportToRouter(_this3); + _this3.isConfigured = true; + _this3._resolveConfiguredPromise(); + }); + }; + + Router.prototype.navigate = function navigate(fragment, options) { + if (!this.isConfigured && this.parent) { + return this.parent.navigate(fragment, options); + } + + return this.history.navigate(_resolveUrl(fragment, this.baseUrl, this.history._hasPushState), options); + }; + + Router.prototype.navigateToRoute = function navigateToRoute(route, params, options) { + var path = this.generate(route, params); + return this.navigate(path, options); + }; + + Router.prototype.navigateBack = function navigateBack() { + this.history.navigateBack(); + }; + + Router.prototype.createChild = function createChild(container) { + var childRouter = new Router(container || this.container.createChild(), this.history); + childRouter.parent = this; + return childRouter; + }; + + Router.prototype.generate = function generate(name, params) { + var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + + var hasRoute = this._recognizer.hasRoute(name); + if ((!this.isConfigured || !hasRoute) && this.parent) { + return this.parent.generate(name, params); + } + + if (!hasRoute) { + throw new Error('A route with name \'' + name + '\' could not be found. Check that `name: \'' + name + '\'` was specified in the route\'s config.'); + } + + var path = this._recognizer.generate(name, params); + var rootedPath = _createRootedPath(path, this.baseUrl, this.history._hasPushState, options.absolute); + return options.absolute ? '' + this.history.getAbsoluteRoot() + rootedPath : rootedPath; + }; + + Router.prototype.createNavModel = function createNavModel(config) { + var navModel = new NavModel(this, 'href' in config ? config.href : config.route); + navModel.title = config.title; + navModel.order = config.nav; + navModel.href = config.href; + navModel.settings = config.settings; + navModel.config = config; + + return navModel; + }; + + Router.prototype.addRoute = function addRoute(config, navModel) { + validateRouteConfig(config, this.routes); + + if (!('viewPorts' in config) && !config.navigationStrategy) { + config.viewPorts = { + 'default': { + moduleId: config.moduleId, + view: config.view + } + }; + } + + if (!navModel) { + navModel = this.createNavModel(config); + } + + this.routes.push(config); + + var path = config.route; + if (path.charAt(0) === '/') { + path = path.substr(1); + } + var caseSensitive = config.caseSensitive === true; + var state = this._recognizer.add({ path: path, handler: config, caseSensitive: caseSensitive }); + + if (path) { + var _settings = config.settings; + delete config.settings; + var withChild = JSON.parse(JSON.stringify(config)); + config.settings = _settings; + withChild.route = path + '/*childRoute'; + withChild.hasChildRouter = true; + this._childRecognizer.add({ + path: withChild.route, + handler: withChild, + caseSensitive: caseSensitive + }); + + withChild.navModel = navModel; + withChild.settings = config.settings; + withChild.navigationStrategy = config.navigationStrategy; + } + + config.navModel = navModel; + + if ((navModel.order || navModel.order === 0) && this.navigation.indexOf(navModel) === -1) { + if (!navModel.href && navModel.href !== '' && (state.types.dynamics || state.types.stars)) { + throw new Error('Invalid route config for "' + config.route + '" : dynamic routes must specify an "href:" to be included in the navigation model.'); + } + + if (typeof navModel.order !== 'number') { + navModel.order = ++this._fallbackOrder; + } + + this.navigation.push(navModel); + this.navigation = this.navigation.sort(function (a, b) { + return a.order - b.order; + }); + } + }; + + Router.prototype.hasRoute = function hasRoute(name) { + return !!(this._recognizer.hasRoute(name) || this.parent && this.parent.hasRoute(name)); + }; + + Router.prototype.hasOwnRoute = function hasOwnRoute(name) { + return this._recognizer.hasRoute(name); + }; + + Router.prototype.handleUnknownRoutes = function handleUnknownRoutes(config) { + var _this4 = this; + + if (!config) { + throw new Error('Invalid unknown route handler'); + } + + this.catchAllHandler = function (instruction) { + return _this4._createRouteConfig(config, instruction).then(function (c) { + instruction.config = c; + return instruction; + }); + }; + }; + + Router.prototype.updateTitle = function updateTitle() { + if (this.parent) { + return this.parent.updateTitle(); + } + + this.currentInstruction._updateTitle(); + return undefined; + }; + + Router.prototype.refreshNavigation = function refreshNavigation() { + var nav = this.navigation; + + for (var i = 0, length = nav.length; i < length; i++) { + var current = nav[i]; + if (!current.config.href) { + current.href = _createRootedPath(current.relativeHref, this.baseUrl, this.history._hasPushState); + } else { + current.href = _normalizeAbsolutePath(current.config.href, this.history._hasPushState); + } + } + }; + + Router.prototype._refreshBaseUrl = function _refreshBaseUrl() { + if (this.parent) { + var baseUrl = this.parent.currentInstruction.getBaseUrl(); + this.baseUrl = this.parent.baseUrl + baseUrl; + } + }; + + Router.prototype._createNavigationInstruction = function _createNavigationInstruction() { + var url = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0]; + var parentInstruction = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + var fragment = url; + var queryString = ''; + + var queryIndex = url.indexOf('?'); + if (queryIndex !== -1) { + fragment = url.substr(0, queryIndex); + queryString = url.substr(queryIndex + 1); + } + + var results = this._recognizer.recognize(url); + if (!results || !results.length) { + results = this._childRecognizer.recognize(url); + } + + var instructionInit = { + fragment: fragment, + queryString: queryString, + config: null, + parentInstruction: parentInstruction, + previousInstruction: this.currentInstruction, + router: this, + options: { + compareQueryParams: this.options.compareQueryParams + } + }; + + if (results && results.length) { + var first = results[0]; + var _instruction = new NavigationInstruction(Object.assign({}, instructionInit, { + params: first.params, + queryParams: first.queryParams || results.queryParams, + config: first.config || first.handler + })); + + if (typeof first.handler === 'function') { + return evaluateNavigationStrategy(_instruction, first.handler, first); + } else if (first.handler && typeof first.handler.navigationStrategy === 'function') { + return evaluateNavigationStrategy(_instruction, first.handler.navigationStrategy, first.handler); + } + + return Promise.resolve(_instruction); + } else if (this.catchAllHandler) { + var _instruction2 = new NavigationInstruction(Object.assign({}, instructionInit, { + params: { path: fragment }, + queryParams: results && results.queryParams, + config: null })); + + return evaluateNavigationStrategy(_instruction2, this.catchAllHandler); + } + + return Promise.reject(new Error('Route not found: ' + url)); + }; + + Router.prototype._createRouteConfig = function _createRouteConfig(config, instruction) { + var _this5 = this; + + return Promise.resolve(config).then(function (c) { + if (typeof c === 'string') { + return { moduleId: c }; + } else if (typeof c === 'function') { + return c(instruction); + } + + return c; + }).then(function (c) { + return typeof c === 'string' ? { moduleId: c } : c; + }).then(function (c) { + c.route = instruction.params.path; + validateRouteConfig(c, _this5.routes); + + if (!c.navModel) { + c.navModel = _this5.createNavModel(c); + } + + return c; + }); + }; + + _createClass(Router, [{ + key: 'isRoot', + get: function get() { + return !this.parent; + } + }]); + + return Router; + }(); + + function validateRouteConfig(config, routes) { + if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) !== 'object') { + throw new Error('Invalid Route Config'); + } + + if (typeof config.route !== 'string') { + var _name2 = config.name || '(no name)'; + throw new Error('Invalid Route Config for "' + _name2 + '": You must specify a "route:" pattern.'); + } + + if (!('redirect' in config || config.moduleId || config.navigationStrategy || config.viewPorts)) { + throw new Error('Invalid Route Config for "' + config.route + '": You must specify a "moduleId:", "redirect:", "navigationStrategy:", or "viewPorts:".'); + } + } + + function evaluateNavigationStrategy(instruction, evaluator, context) { + return Promise.resolve(evaluator.call(context, instruction)).then(function () { + if (!('viewPorts' in instruction.config)) { + instruction.config.viewPorts = { + 'default': { + moduleId: instruction.config.moduleId + } + }; + } + + return instruction; + }); + } + + var CanDeactivatePreviousStep = exports.CanDeactivatePreviousStep = function () { + function CanDeactivatePreviousStep() { + + } + + CanDeactivatePreviousStep.prototype.run = function run(navigationInstruction, next) { + return processDeactivatable(navigationInstruction.plan, 'canDeactivate', next); + }; + + return CanDeactivatePreviousStep; + }(); + + var CanActivateNextStep = exports.CanActivateNextStep = function () { + function CanActivateNextStep() { + + } + + CanActivateNextStep.prototype.run = function run(navigationInstruction, next) { + return processActivatable(navigationInstruction, 'canActivate', next); + }; + + return CanActivateNextStep; + }(); + + var DeactivatePreviousStep = exports.DeactivatePreviousStep = function () { + function DeactivatePreviousStep() { + + } + + DeactivatePreviousStep.prototype.run = function run(navigationInstruction, next) { + return processDeactivatable(navigationInstruction.plan, 'deactivate', next, true); + }; + + return DeactivatePreviousStep; + }(); + + var ActivateNextStep = exports.ActivateNextStep = function () { + function ActivateNextStep() { + + } + + ActivateNextStep.prototype.run = function run(navigationInstruction, next) { + return processActivatable(navigationInstruction, 'activate', next, true); + }; + + return ActivateNextStep; + }(); + + function processDeactivatable(plan, callbackName, next, ignoreResult) { + var infos = findDeactivatable(plan, callbackName); + var i = infos.length; + + function inspect(val) { + if (ignoreResult || shouldContinue(val)) { + return iterate(); + } + + return next.cancel(val); + } + + function iterate() { + if (i--) { + try { + var viewModel = infos[i]; + var _result = viewModel[callbackName](); + return processPotential(_result, inspect, next.cancel); + } catch (error) { + return next.cancel(error); + } + } + + return next(); + } + + return iterate(); + } + + function findDeactivatable(plan, callbackName) { + var list = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2]; + + for (var viewPortName in plan) { + var _viewPortPlan = plan[viewPortName]; + var prevComponent = _viewPortPlan.prevComponent; + + if ((_viewPortPlan.strategy === activationStrategy.invokeLifecycle || _viewPortPlan.strategy === activationStrategy.replace) && prevComponent) { + var viewModel = prevComponent.viewModel; + + if (callbackName in viewModel) { + list.push(viewModel); + } + } + + if (_viewPortPlan.childNavigationInstruction) { + findDeactivatable(_viewPortPlan.childNavigationInstruction.plan, callbackName, list); + } else if (prevComponent) { + addPreviousDeactivatable(prevComponent, callbackName, list); + } + } + + return list; + } + + function addPreviousDeactivatable(component, callbackName, list) { + var childRouter = component.childRouter; + + if (childRouter && childRouter.currentInstruction) { + var viewPortInstructions = childRouter.currentInstruction.viewPortInstructions; + + for (var viewPortName in viewPortInstructions) { + var _viewPortInstruction2 = viewPortInstructions[viewPortName]; + var prevComponent = _viewPortInstruction2.component; + var prevViewModel = prevComponent.viewModel; + + if (callbackName in prevViewModel) { + list.push(prevViewModel); + } + + addPreviousDeactivatable(prevComponent, callbackName, list); + } + } + } + + function processActivatable(navigationInstruction, callbackName, next, ignoreResult) { + var infos = findActivatable(navigationInstruction, callbackName); + var length = infos.length; + var i = -1; + + function inspect(val, router) { + if (ignoreResult || shouldContinue(val, router)) { + return iterate(); + } + + return next.cancel(val); + } + + function iterate() { + i++; + + if (i < length) { + try { + var _ret3 = function () { + var _current$viewModel; + + var current = infos[i]; + var result = (_current$viewModel = current.viewModel)[callbackName].apply(_current$viewModel, current.lifecycleArgs); + return { + v: processPotential(result, function (val) { + return inspect(val, current.router); + }, next.cancel) + }; + }(); + + if ((typeof _ret3 === 'undefined' ? 'undefined' : _typeof(_ret3)) === "object") return _ret3.v; + } catch (error) { + return next.cancel(error); + } + } + + return next(); + } + + return iterate(); + } + + function findActivatable(navigationInstruction, callbackName) { + var list = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2]; + var router = arguments[3]; + + var plan = navigationInstruction.plan; + + Object.keys(plan).filter(function (viewPortName) { + var viewPortPlan = plan[viewPortName]; + var viewPortInstruction = navigationInstruction.viewPortInstructions[viewPortName]; + var viewModel = viewPortInstruction.component.viewModel; + + if ((viewPortPlan.strategy === activationStrategy.invokeLifecycle || viewPortPlan.strategy === activationStrategy.replace) && callbackName in viewModel) { + list.push({ + viewModel: viewModel, + lifecycleArgs: viewPortInstruction.lifecycleArgs, + router: router + }); + } + + if (viewPortPlan.childNavigationInstruction) { + findActivatable(viewPortPlan.childNavigationInstruction, callbackName, list, viewPortInstruction.component.childRouter || router); + } + }); + + return list; + } + + function shouldContinue(output, router) { + if (output instanceof Error) { + return false; + } + + if (isNavigationCommand(output)) { + if (typeof output.setRouter === 'function') { + output.setRouter(router); + } + + return !!output.shouldContinueProcessing; + } + + if (output === undefined) { + return true; + } + + return output; + } + + var SafeSubscription = function () { + function SafeSubscription(subscriptionFunc) { + + + this._subscribed = true; + this._subscription = subscriptionFunc(this); + + if (!this._subscribed) this.unsubscribe(); + } + + SafeSubscription.prototype.unsubscribe = function unsubscribe() { + if (this._subscribed && this._subscription) this._subscription.unsubscribe(); + + this._subscribed = false; + }; + + _createClass(SafeSubscription, [{ + key: 'subscribed', + get: function get() { + return this._subscribed; + } + }]); + + return SafeSubscription; + }(); + + function processPotential(obj, resolve, reject) { + if (obj && typeof obj.then === 'function') { + return Promise.resolve(obj).then(resolve).catch(reject); + } + + if (obj && typeof obj.subscribe === 'function') { + var _ret4 = function () { + var obs = obj; + return { + v: new SafeSubscription(function (sub) { + return obs.subscribe({ + next: function next() { + if (sub.subscribed) { + sub.unsubscribe(); + resolve(obj); + } + }, + error: function error(_error) { + if (sub.subscribed) { + sub.unsubscribe(); + reject(_error); + } + }, + complete: function complete() { + if (sub.subscribed) { + sub.unsubscribe(); + resolve(obj); + } + } + }); + }) + }; + }(); + + if ((typeof _ret4 === 'undefined' ? 'undefined' : _typeof(_ret4)) === "object") return _ret4.v; + } + + try { + return resolve(obj); + } catch (error) { + return reject(error); + } + } + + var RouteLoader = exports.RouteLoader = function () { + function RouteLoader() { + + } + + RouteLoader.prototype.loadRoute = function loadRoute(router, config, navigationInstruction) { + throw Error('Route loaders must implement "loadRoute(router, config, navigationInstruction)".'); + }; + + return RouteLoader; + }(); + + var LoadRouteStep = exports.LoadRouteStep = function () { + LoadRouteStep.inject = function inject() { + return [RouteLoader]; + }; + + function LoadRouteStep(routeLoader) { + + + this.routeLoader = routeLoader; + } + + LoadRouteStep.prototype.run = function run(navigationInstruction, next) { + return loadNewRoute(this.routeLoader, navigationInstruction).then(next).catch(next.cancel); + }; + + return LoadRouteStep; + }(); + + function loadNewRoute(routeLoader, navigationInstruction) { + var toLoad = determineWhatToLoad(navigationInstruction); + var loadPromises = toLoad.map(function (current) { + return loadRoute(routeLoader, current.navigationInstruction, current.viewPortPlan); + }); + + return Promise.all(loadPromises); + } + + function determineWhatToLoad(navigationInstruction) { + var toLoad = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1]; + + var plan = navigationInstruction.plan; + + for (var viewPortName in plan) { + var _viewPortPlan2 = plan[viewPortName]; + + if (_viewPortPlan2.strategy === activationStrategy.replace) { + toLoad.push({ viewPortPlan: _viewPortPlan2, navigationInstruction: navigationInstruction }); + + if (_viewPortPlan2.childNavigationInstruction) { + determineWhatToLoad(_viewPortPlan2.childNavigationInstruction, toLoad); + } + } else { + var _viewPortInstruction3 = navigationInstruction.addViewPortInstruction(viewPortName, _viewPortPlan2.strategy, _viewPortPlan2.prevModuleId, _viewPortPlan2.prevComponent); + + if (_viewPortPlan2.childNavigationInstruction) { + _viewPortInstruction3.childNavigationInstruction = _viewPortPlan2.childNavigationInstruction; + determineWhatToLoad(_viewPortPlan2.childNavigationInstruction, toLoad); + } + } + } + + return toLoad; + } + + function loadRoute(routeLoader, navigationInstruction, viewPortPlan) { + var moduleId = viewPortPlan.config.moduleId; + + return loadComponent(routeLoader, navigationInstruction, viewPortPlan.config).then(function (component) { + var viewPortInstruction = navigationInstruction.addViewPortInstruction(viewPortPlan.name, viewPortPlan.strategy, moduleId, component); + + var childRouter = component.childRouter; + if (childRouter) { + var path = navigationInstruction.getWildcardPath(); + + return childRouter._createNavigationInstruction(path, navigationInstruction).then(function (childInstruction) { + viewPortPlan.childNavigationInstruction = childInstruction; + + return _buildNavigationPlan(childInstruction).then(function (childPlan) { + childInstruction.plan = childPlan; + viewPortInstruction.childNavigationInstruction = childInstruction; + + return loadNewRoute(routeLoader, childInstruction); + }); + }); + } + + return undefined; + }); + } + + function loadComponent(routeLoader, navigationInstruction, config) { + var router = navigationInstruction.router; + var lifecycleArgs = navigationInstruction.lifecycleArgs; + + return routeLoader.loadRoute(router, config, navigationInstruction).then(function (component) { + var viewModel = component.viewModel; + var childContainer = component.childContainer; + + component.router = router; + component.config = config; + + if ('configureRouter' in viewModel) { + var _ret5 = function () { + var childRouter = childContainer.getChildRouter(); + component.childRouter = childRouter; + + return { + v: childRouter.configure(function (c) { + return viewModel.configureRouter.apply(viewModel, [c, childRouter].concat(lifecycleArgs)); + }).then(function () { + return component; + }) + }; + }(); + + if ((typeof _ret5 === 'undefined' ? 'undefined' : _typeof(_ret5)) === "object") return _ret5.v; + } + + return component; + }); + } + + var PipelineSlot = function () { + function PipelineSlot(container, name, alias) { + + + this.steps = []; + + this.container = container; + this.slotName = name; + this.slotAlias = alias; + } + + PipelineSlot.prototype.getSteps = function getSteps() { + var _this6 = this; + + return this.steps.map(function (x) { + return _this6.container.get(x); + }); + }; + + return PipelineSlot; + }(); + + var PipelineProvider = exports.PipelineProvider = function () { + PipelineProvider.inject = function inject() { + return [_aureliaDependencyInjection.Container]; + }; + + function PipelineProvider(container) { + + + this.container = container; + this.steps = [BuildNavigationPlanStep, CanDeactivatePreviousStep, LoadRouteStep, this._createPipelineSlot('authorize'), CanActivateNextStep, this._createPipelineSlot('preActivate', 'modelbind'), DeactivatePreviousStep, ActivateNextStep, this._createPipelineSlot('preRender', 'precommit'), CommitChangesStep, this._createPipelineSlot('postRender', 'postcomplete')]; + } + + PipelineProvider.prototype.createPipeline = function createPipeline() { + var _this7 = this; + + var pipeline = new Pipeline(); + this.steps.forEach(function (step) { + return pipeline.addStep(_this7.container.get(step)); + }); + return pipeline; + }; + + PipelineProvider.prototype._findStep = function _findStep(name) { + return this.steps.find(function (x) { + return x.slotName === name || x.slotAlias === name; + }); + }; + + PipelineProvider.prototype.addStep = function addStep(name, step) { + var found = this._findStep(name); + if (found) { + if (!found.steps.includes(step)) { + found.steps.push(step); + } + } else { + throw new Error('Invalid pipeline slot name: ' + name + '.'); + } + }; + + PipelineProvider.prototype.removeStep = function removeStep(name, step) { + var slot = this._findStep(name); + if (slot) { + slot.steps.splice(slot.steps.indexOf(step), 1); + } + }; + + PipelineProvider.prototype._clearSteps = function _clearSteps() { + var name = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0]; + + var slot = this._findStep(name); + if (slot) { + slot.steps = []; + } + }; + + PipelineProvider.prototype.reset = function reset() { + this._clearSteps('authorize'); + this._clearSteps('preActivate'); + this._clearSteps('preRender'); + this._clearSteps('postRender'); + }; + + PipelineProvider.prototype._createPipelineSlot = function _createPipelineSlot(name, alias) { + return new PipelineSlot(this.container, name, alias); + }; + + return PipelineProvider; + }(); + + var logger = LogManager.getLogger('app-router'); + + var AppRouter = exports.AppRouter = function (_Router) { + _inherits(AppRouter, _Router); + + AppRouter.inject = function inject() { + return [_aureliaDependencyInjection.Container, _aureliaHistory.History, PipelineProvider, _aureliaEventAggregator.EventAggregator]; + }; + + function AppRouter(container, history, pipelineProvider, events) { + + + var _this8 = _possibleConstructorReturn(this, _Router.call(this, container, history)); + + _this8.pipelineProvider = pipelineProvider; + _this8.events = events; + return _this8; + } + + AppRouter.prototype.reset = function reset() { + _Router.prototype.reset.call(this); + this.maxInstructionCount = 10; + if (!this._queue) { + this._queue = []; + } else { + this._queue.length = 0; + } + }; + + AppRouter.prototype.loadUrl = function loadUrl(url) { + var _this9 = this; + + return this._createNavigationInstruction(url).then(function (instruction) { + return _this9._queueInstruction(instruction); + }).catch(function (error) { + logger.error(error); + restorePreviousLocation(_this9); + }); + }; + + AppRouter.prototype.registerViewPort = function registerViewPort(viewPort, name) { + var _this10 = this; + + _Router.prototype.registerViewPort.call(this, viewPort, name); + + if (!this.isActive) { + var _ret6 = function () { + var viewModel = _this10._findViewModel(viewPort); + if ('configureRouter' in viewModel) { + if (!_this10.isConfigured) { + var _ret7 = function () { + var resolveConfiguredPromise = _this10._resolveConfiguredPromise; + _this10._resolveConfiguredPromise = function () {}; + return { + v: { + v: _this10.configure(function (config) { + return viewModel.configureRouter(config, _this10); + }).then(function () { + _this10.activate(); + resolveConfiguredPromise(); + }) + } + }; + }(); + + if ((typeof _ret7 === 'undefined' ? 'undefined' : _typeof(_ret7)) === "object") return _ret7.v; + } + } else { + _this10.activate(); + } + }(); + + if ((typeof _ret6 === 'undefined' ? 'undefined' : _typeof(_ret6)) === "object") return _ret6.v; + } else { + this._dequeueInstruction(); + } + + return Promise.resolve(); + }; + + AppRouter.prototype.activate = function activate(options) { + if (this.isActive) { + return; + } + + this.isActive = true; + this.options = Object.assign({ routeHandler: this.loadUrl.bind(this) }, this.options, options); + this.history.activate(this.options); + this._dequeueInstruction(); + }; + + AppRouter.prototype.deactivate = function deactivate() { + this.isActive = false; + this.history.deactivate(); + }; + + AppRouter.prototype._queueInstruction = function _queueInstruction(instruction) { + var _this11 = this; + + return new Promise(function (resolve) { + instruction.resolve = resolve; + _this11._queue.unshift(instruction); + _this11._dequeueInstruction(); + }); + }; + + AppRouter.prototype._dequeueInstruction = function _dequeueInstruction() { + var _this12 = this; + + var instructionCount = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + + return Promise.resolve().then(function () { + if (_this12.isNavigating && !instructionCount) { + return undefined; + } + + var instruction = _this12._queue.shift(); + _this12._queue.length = 0; + + if (!instruction) { + return undefined; + } + + _this12.isNavigating = true; + instruction.previousInstruction = _this12.currentInstruction; + + if (!instructionCount) { + _this12.events.publish('router:navigation:processing', { instruction: instruction }); + } else if (instructionCount === _this12.maxInstructionCount - 1) { + logger.error(instructionCount + 1 + ' navigation instructions have been attempted without success. Restoring last known good location.'); + restorePreviousLocation(_this12); + return _this12._dequeueInstruction(instructionCount + 1); + } else if (instructionCount > _this12.maxInstructionCount) { + throw new Error('Maximum navigation attempts exceeded. Giving up.'); + } + + var pipeline = _this12.pipelineProvider.createPipeline(); + + return pipeline.run(instruction).then(function (result) { + return processResult(instruction, result, instructionCount, _this12); + }).catch(function (error) { + return { output: error instanceof Error ? error : new Error(error) }; + }).then(function (result) { + return resolveInstruction(instruction, result, !!instructionCount, _this12); + }); + }); + }; + + AppRouter.prototype._findViewModel = function _findViewModel(viewPort) { + if (this.container.viewModel) { + return this.container.viewModel; + } + + if (viewPort.container) { + var container = viewPort.container; + + while (container) { + if (container.viewModel) { + this.container.viewModel = container.viewModel; + return container.viewModel; + } + + container = container.parent; + } + } + + return undefined; + }; + + return AppRouter; + }(Router); + + function processResult(instruction, result, instructionCount, router) { + if (!(result && 'completed' in result && 'output' in result)) { + result = result || {}; + result.output = new Error('Expected router pipeline to return a navigation result, but got [' + JSON.stringify(result) + '] instead.'); + } + + var finalResult = null; + if (isNavigationCommand(result.output)) { + result.output.navigate(router); + } else { + finalResult = result; + + if (!result.completed) { + if (result.output instanceof Error) { + logger.error(result.output); + } + + restorePreviousLocation(router); + } + } + + return router._dequeueInstruction(instructionCount + 1).then(function (innerResult) { + return finalResult || innerResult || result; + }); + } + + function resolveInstruction(instruction, result, isInnerInstruction, router) { + instruction.resolve(result); + + if (!isInnerInstruction) { + router.isNavigating = false; + var eventArgs = { instruction: instruction, result: result }; + var eventName = void 0; + + if (result.output instanceof Error) { + eventName = 'error'; + } else if (!result.completed) { + eventName = 'canceled'; + } else { + var _queryString = instruction.queryString ? '?' + instruction.queryString : ''; + router.history.previousLocation = instruction.fragment + _queryString; + eventName = 'success'; + } + + router.events.publish('router:navigation:' + eventName, eventArgs); + router.events.publish('router:navigation:complete', eventArgs); + } + + return result; + } + + function restorePreviousLocation(router) { + var previousLocation = router.history.previousLocation; + if (previousLocation) { + router.navigate(router.history.previousLocation, { trigger: false, replace: true }); + } else { + logger.error('Router navigation failed, and no previous location could be restored.'); + } + } +}); +define('aurelia-history',['exports'], function (exports) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + + + function mi(name) { + throw new Error('History must implement ' + name + '().'); + } + + var History = exports.History = function () { + function History() { + + } + + History.prototype.activate = function activate(options) { + mi('activate'); + }; + + History.prototype.deactivate = function deactivate() { + mi('deactivate'); + }; + + History.prototype.getAbsoluteRoot = function getAbsoluteRoot() { + mi('getAbsoluteRoot'); + }; + + History.prototype.navigate = function navigate(fragment, options) { + mi('navigate'); + }; + + History.prototype.navigateBack = function navigateBack() { + mi('navigateBack'); + }; + + History.prototype.setTitle = function setTitle(title) { + mi('setTitle'); + }; + + return History; + }(); +}); +define('aurelia-task-queue',['exports', 'aurelia-pal'], function (exports, _aureliaPal) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.TaskQueue = undefined; + + + + var hasSetImmediate = typeof setImmediate === 'function'; + + function makeRequestFlushFromMutationObserver(flush) { + var toggle = 1; + var observer = _aureliaPal.DOM.createMutationObserver(flush); + var node = _aureliaPal.DOM.createTextNode(''); + observer.observe(node, { characterData: true }); + return function requestFlush() { + toggle = -toggle; + node.data = toggle; + }; + } + + function makeRequestFlushFromTimer(flush) { + return function requestFlush() { + var timeoutHandle = setTimeout(handleFlushTimer, 0); + + var intervalHandle = setInterval(handleFlushTimer, 50); + function handleFlushTimer() { + clearTimeout(timeoutHandle); + clearInterval(intervalHandle); + flush(); + } + }; + } + + function onError(error, task) { + if ('onError' in task) { + task.onError(error); + } else if (hasSetImmediate) { + setImmediate(function () { + throw error; + }); + } else { + setTimeout(function () { + throw error; + }, 0); + } + } + + var TaskQueue = exports.TaskQueue = function () { + function TaskQueue() { + var _this = this; + + + + this.flushing = false; + + this.microTaskQueue = []; + this.microTaskQueueCapacity = 1024; + this.taskQueue = []; + + if (_aureliaPal.FEATURE.mutationObserver) { + this.requestFlushMicroTaskQueue = makeRequestFlushFromMutationObserver(function () { + return _this.flushMicroTaskQueue(); + }); + } else { + this.requestFlushMicroTaskQueue = makeRequestFlushFromTimer(function () { + return _this.flushMicroTaskQueue(); + }); + } + + this.requestFlushTaskQueue = makeRequestFlushFromTimer(function () { + return _this.flushTaskQueue(); + }); + } + + TaskQueue.prototype.queueMicroTask = function queueMicroTask(task) { + if (this.microTaskQueue.length < 1) { + this.requestFlushMicroTaskQueue(); + } + + this.microTaskQueue.push(task); + }; + + TaskQueue.prototype.queueTask = function queueTask(task) { + if (this.taskQueue.length < 1) { + this.requestFlushTaskQueue(); + } + + this.taskQueue.push(task); + }; + + TaskQueue.prototype.flushTaskQueue = function flushTaskQueue() { + var queue = this.taskQueue; + var index = 0; + var task = void 0; + + this.taskQueue = []; + + try { + this.flushing = true; + while (index < queue.length) { + task = queue[index]; + task.call(); + index++; + } + } catch (error) { + onError(error, task); + } finally { + this.flushing = false; + } + }; + + TaskQueue.prototype.flushMicroTaskQueue = function flushMicroTaskQueue() { + var queue = this.microTaskQueue; + var capacity = this.microTaskQueueCapacity; + var index = 0; + var task = void 0; + + try { + this.flushing = true; + while (index < queue.length) { + task = queue[index]; + task.call(); + index++; + + if (index > capacity) { + for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { + queue[scan] = queue[scan + index]; + } + + queue.length -= index; + index = 0; + } + } + } catch (error) { + onError(error, task); + } finally { + this.flushing = false; + } + + queue.length = 0; + }; + + return TaskQueue; + }(); +}); +define('aurelia-templating-binding',['exports', 'aurelia-logging', 'aurelia-binding', 'aurelia-templating'], function (exports, _aureliaLogging, _aureliaBinding, _aureliaTemplating) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.TemplatingBindingLanguage = exports.SyntaxInterpreter = exports.ChildInterpolationBinding = exports.InterpolationBinding = exports.InterpolationBindingExpression = exports.AttributeMap = undefined; + exports.configure = configure; + + var LogManager = _interopRequireWildcard(_aureliaLogging); + + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + + newObj.default = obj; + return newObj; + } + } + + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + + + + var _class, _temp, _dec, _class2, _class3, _temp2, _class4, _temp3; + + var AttributeMap = exports.AttributeMap = (_temp = _class = function () { + function AttributeMap(svg) { + + + this.elements = Object.create(null); + this.allElements = Object.create(null); + + this.svg = svg; + + this.registerUniversal('accesskey', 'accessKey'); + this.registerUniversal('contenteditable', 'contentEditable'); + this.registerUniversal('tabindex', 'tabIndex'); + this.registerUniversal('textcontent', 'textContent'); + this.registerUniversal('innerhtml', 'innerHTML'); + this.registerUniversal('scrolltop', 'scrollTop'); + this.registerUniversal('scrollleft', 'scrollLeft'); + this.registerUniversal('readonly', 'readOnly'); + + this.register('label', 'for', 'htmlFor'); + + this.register('input', 'maxlength', 'maxLength'); + this.register('input', 'minlength', 'minLength'); + this.register('input', 'formaction', 'formAction'); + this.register('input', 'formenctype', 'formEncType'); + this.register('input', 'formmethod', 'formMethod'); + this.register('input', 'formnovalidate', 'formNoValidate'); + this.register('input', 'formtarget', 'formTarget'); + + this.register('textarea', 'maxlength', 'maxLength'); + + this.register('td', 'rowspan', 'rowSpan'); + this.register('td', 'colspan', 'colSpan'); + this.register('th', 'rowspan', 'rowSpan'); + this.register('th', 'colspan', 'colSpan'); + } + + AttributeMap.prototype.register = function register(elementName, attributeName, propertyName) { + elementName = elementName.toLowerCase(); + attributeName = attributeName.toLowerCase(); + var element = this.elements[elementName] = this.elements[elementName] || Object.create(null); + element[attributeName] = propertyName; + }; + + AttributeMap.prototype.registerUniversal = function registerUniversal(attributeName, propertyName) { + attributeName = attributeName.toLowerCase(); + this.allElements[attributeName] = propertyName; + }; + + AttributeMap.prototype.map = function map(elementName, attributeName) { + if (this.svg.isStandardSvgAttribute(elementName, attributeName)) { + return attributeName; + } + elementName = elementName.toLowerCase(); + attributeName = attributeName.toLowerCase(); + var element = this.elements[elementName]; + if (element !== undefined && attributeName in element) { + return element[attributeName]; + } + if (attributeName in this.allElements) { + return this.allElements[attributeName]; + } + + if (/(^data-)|(^aria-)|:/.test(attributeName)) { + return attributeName; + } + return (0, _aureliaBinding.camelCase)(attributeName); + }; + + return AttributeMap; + }(), _class.inject = [_aureliaBinding.SVGAnalyzer], _temp); + + var InterpolationBindingExpression = exports.InterpolationBindingExpression = function () { + function InterpolationBindingExpression(observerLocator, targetProperty, parts, mode, lookupFunctions, attribute) { + + + this.observerLocator = observerLocator; + this.targetProperty = targetProperty; + this.parts = parts; + this.mode = mode; + this.lookupFunctions = lookupFunctions; + this.attribute = this.attrToRemove = attribute; + this.discrete = false; + } + + InterpolationBindingExpression.prototype.createBinding = function createBinding(target) { + if (this.parts.length === 3) { + return new ChildInterpolationBinding(target, this.observerLocator, this.parts[1], this.mode, this.lookupFunctions, this.targetProperty, this.parts[0], this.parts[2]); + } + return new InterpolationBinding(this.observerLocator, this.parts, target, this.targetProperty, this.mode, this.lookupFunctions); + }; + + return InterpolationBindingExpression; + }(); + + function validateTarget(target, propertyName) { + if (propertyName === 'style') { + LogManager.getLogger('templating-binding').info('Internet Explorer does not support interpolation in "style" attributes. Use the style attribute\'s alias, "css" instead.'); + } else if (target.parentElement && target.parentElement.nodeName === 'TEXTAREA' && propertyName === 'textContent') { + throw new Error('Interpolation binding cannot be used in the content of a textarea element. Use instead.'); + } + } + + var InterpolationBinding = exports.InterpolationBinding = function () { + function InterpolationBinding(observerLocator, parts, target, targetProperty, mode, lookupFunctions) { + + + validateTarget(target, targetProperty); + this.observerLocator = observerLocator; + this.parts = parts; + this.target = target; + this.targetProperty = targetProperty; + this.targetAccessor = observerLocator.getAccessor(target, targetProperty); + this.mode = mode; + this.lookupFunctions = lookupFunctions; + } + + InterpolationBinding.prototype.interpolate = function interpolate() { + if (this.isBound) { + var value = ''; + var parts = this.parts; + for (var i = 0, ii = parts.length; i < ii; i++) { + value += i % 2 === 0 ? parts[i] : this['childBinding' + i].value; + } + this.targetAccessor.setValue(value, this.target, this.targetProperty); + } + }; + + InterpolationBinding.prototype.updateOneTimeBindings = function updateOneTimeBindings() { + for (var i = 1, ii = this.parts.length; i < ii; i += 2) { + var child = this['childBinding' + i]; + if (child.mode === _aureliaBinding.bindingMode.oneTime) { + child.call(); + } + } + }; + + InterpolationBinding.prototype.bind = function bind(source) { + if (this.isBound) { + if (this.source === source) { + return; + } + this.unbind(); + } + this.source = source; + + var parts = this.parts; + for (var i = 1, ii = parts.length; i < ii; i += 2) { + var binding = new ChildInterpolationBinding(this, this.observerLocator, parts[i], this.mode, this.lookupFunctions); + binding.bind(source); + this['childBinding' + i] = binding; + } + + this.isBound = true; + this.interpolate(); + }; + + InterpolationBinding.prototype.unbind = function unbind() { + if (!this.isBound) { + return; + } + this.isBound = false; + this.source = null; + var parts = this.parts; + for (var i = 1, ii = parts.length; i < ii; i += 2) { + var name = 'childBinding' + i; + this[name].unbind(); + } + }; + + return InterpolationBinding; + }(); + + var ChildInterpolationBinding = exports.ChildInterpolationBinding = (_dec = (0, _aureliaBinding.connectable)(), _dec(_class2 = function () { + function ChildInterpolationBinding(target, observerLocator, sourceExpression, mode, lookupFunctions, targetProperty, left, right) { + + + if (target instanceof InterpolationBinding) { + this.parent = target; + } else { + validateTarget(target, targetProperty); + this.target = target; + this.targetProperty = targetProperty; + this.targetAccessor = observerLocator.getAccessor(target, targetProperty); + } + this.observerLocator = observerLocator; + this.sourceExpression = sourceExpression; + this.mode = mode; + this.lookupFunctions = lookupFunctions; + this.left = left; + this.right = right; + } + + ChildInterpolationBinding.prototype.updateTarget = function updateTarget(value) { + value = value === null || value === undefined ? '' : value.toString(); + if (value !== this.value) { + this.value = value; + if (this.parent) { + this.parent.interpolate(); + } else { + this.targetAccessor.setValue(this.left + value + this.right, this.target, this.targetProperty); + } + } + }; + + ChildInterpolationBinding.prototype.call = function call() { + if (!this.isBound) { + return; + } + + this.rawValue = this.sourceExpression.evaluate(this.source, this.lookupFunctions); + this.updateTarget(this.rawValue); + + if (this.mode !== _aureliaBinding.bindingMode.oneTime) { + this._version++; + this.sourceExpression.connect(this, this.source); + if (this.rawValue instanceof Array) { + this.observeArray(this.rawValue); + } + this.unobserve(false); + } + }; + + ChildInterpolationBinding.prototype.bind = function bind(source) { + if (this.isBound) { + if (this.source === source) { + return; + } + this.unbind(); + } + this.isBound = true; + this.source = source; + + var sourceExpression = this.sourceExpression; + if (sourceExpression.bind) { + sourceExpression.bind(this, source, this.lookupFunctions); + } + + this.rawValue = sourceExpression.evaluate(source, this.lookupFunctions); + this.updateTarget(this.rawValue); + + if (this.mode === _aureliaBinding.bindingMode.oneWay) { + (0, _aureliaBinding.enqueueBindingConnect)(this); + } + }; + + ChildInterpolationBinding.prototype.unbind = function unbind() { + if (!this.isBound) { + return; + } + this.isBound = false; + var sourceExpression = this.sourceExpression; + if (sourceExpression.unbind) { + sourceExpression.unbind(this, this.source); + } + this.source = null; + this.value = null; + this.rawValue = null; + this.unobserve(true); + }; + + ChildInterpolationBinding.prototype.connect = function connect(evaluate) { + if (!this.isBound) { + return; + } + if (evaluate) { + this.rawValue = this.sourceExpression.evaluate(this.source, this.lookupFunctions); + this.updateTarget(this.rawValue); + } + this.sourceExpression.connect(this, this.source); + if (this.rawValue instanceof Array) { + this.observeArray(this.rawValue); + } + }; + + return ChildInterpolationBinding; + }()) || _class2); + var SyntaxInterpreter = exports.SyntaxInterpreter = (_temp2 = _class3 = function () { + function SyntaxInterpreter(parser, observerLocator, eventManager, attributeMap) { + + + this.parser = parser; + this.observerLocator = observerLocator; + this.eventManager = eventManager; + this.attributeMap = attributeMap; + } + + SyntaxInterpreter.prototype.interpret = function interpret(resources, element, info, existingInstruction, context) { + if (info.command in this) { + return this[info.command](resources, element, info, existingInstruction, context); + } + + return this.handleUnknownCommand(resources, element, info, existingInstruction, context); + }; + + SyntaxInterpreter.prototype.handleUnknownCommand = function handleUnknownCommand(resources, element, info, existingInstruction, context) { + LogManager.getLogger('templating-binding').warn('Unknown binding command.', info); + return existingInstruction; + }; + + SyntaxInterpreter.prototype.determineDefaultBindingMode = function determineDefaultBindingMode(element, attrName, context) { + var tagName = element.tagName.toLowerCase(); + + if (tagName === 'input' && (attrName === 'value' || attrName === 'files') && element.type !== 'checkbox' && element.type !== 'radio' || tagName === 'input' && attrName === 'checked' && (element.type === 'checkbox' || element.type === 'radio') || (tagName === 'textarea' || tagName === 'select') && attrName === 'value' || (attrName === 'textcontent' || attrName === 'innerhtml') && element.contentEditable === 'true' || attrName === 'scrolltop' || attrName === 'scrollleft') { + return _aureliaBinding.bindingMode.twoWay; + } + + if (context && attrName in context.attributes && context.attributes[attrName] && context.attributes[attrName].defaultBindingMode >= _aureliaBinding.bindingMode.oneTime) { + return context.attributes[attrName].defaultBindingMode; + } + + return _aureliaBinding.bindingMode.oneWay; + }; + + SyntaxInterpreter.prototype.bind = function bind(resources, element, info, existingInstruction, context) { + var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); + + instruction.attributes[info.attrName] = new _aureliaBinding.BindingExpression(this.observerLocator, this.attributeMap.map(element.tagName, info.attrName), this.parser.parse(info.attrValue), info.defaultBindingMode || this.determineDefaultBindingMode(element, info.attrName, context), resources.lookupFunctions); + + return instruction; + }; + + SyntaxInterpreter.prototype.trigger = function trigger(resources, element, info) { + return new _aureliaBinding.ListenerExpression(this.eventManager, info.attrName, this.parser.parse(info.attrValue), false, true, resources.lookupFunctions); + }; + + SyntaxInterpreter.prototype.delegate = function delegate(resources, element, info) { + return new _aureliaBinding.ListenerExpression(this.eventManager, info.attrName, this.parser.parse(info.attrValue), true, true, resources.lookupFunctions); + }; + + SyntaxInterpreter.prototype.call = function call(resources, element, info, existingInstruction) { + var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); + + instruction.attributes[info.attrName] = new _aureliaBinding.CallExpression(this.observerLocator, info.attrName, this.parser.parse(info.attrValue), resources.lookupFunctions); + + return instruction; + }; + + SyntaxInterpreter.prototype.options = function options(resources, element, info, existingInstruction, context) { + var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); + var attrValue = info.attrValue; + var language = this.language; + var name = null; + var target = ''; + var current = void 0; + var i = void 0; + var ii = void 0; + var inString = false; + var inEscape = false; + + for (i = 0, ii = attrValue.length; i < ii; ++i) { + current = attrValue[i]; + + if (current === ';' && !inString) { + info = language.inspectAttribute(resources, '?', name, target.trim()); + language.createAttributeInstruction(resources, element, info, instruction, context); + + if (!instruction.attributes[info.attrName]) { + instruction.attributes[info.attrName] = info.attrValue; + } + + target = ''; + name = null; + } else if (current === ':' && name === null) { + name = target.trim(); + target = ''; + } else if (current === '\\') { + target += current; + inEscape = true; + continue; + } else { + target += current; + + if (name !== null && inEscape === false && current === '\'') { + inString = !inString; + } + } + + inEscape = false; + } + + if (name !== null) { + info = language.inspectAttribute(resources, '?', name, target.trim()); + language.createAttributeInstruction(resources, element, info, instruction, context); + + if (!instruction.attributes[info.attrName]) { + instruction.attributes[info.attrName] = info.attrValue; + } + } + + return instruction; + }; + + SyntaxInterpreter.prototype['for'] = function _for(resources, element, info, existingInstruction) { + var parts = void 0; + var keyValue = void 0; + var instruction = void 0; + var attrValue = void 0; + var isDestructuring = void 0; + + attrValue = info.attrValue; + isDestructuring = attrValue.match(/^ *[[].+[\]]/); + parts = isDestructuring ? attrValue.split('of ') : attrValue.split(' of '); + + if (parts.length !== 2) { + throw new Error('Incorrect syntax for "for". The form is: "$local of $items" or "[$key, $value] of $items".'); + } + + instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); + + if (isDestructuring) { + keyValue = parts[0].replace(/[[\]]/g, '').replace(/,/g, ' ').replace(/\s+/g, ' ').trim().split(' '); + instruction.attributes.key = keyValue[0]; + instruction.attributes.value = keyValue[1]; + } else { + instruction.attributes.local = parts[0]; + } + + instruction.attributes.items = new _aureliaBinding.BindingExpression(this.observerLocator, 'items', this.parser.parse(parts[1]), _aureliaBinding.bindingMode.oneWay, resources.lookupFunctions); + + return instruction; + }; + + SyntaxInterpreter.prototype['two-way'] = function twoWay(resources, element, info, existingInstruction) { + var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); + + instruction.attributes[info.attrName] = new _aureliaBinding.BindingExpression(this.observerLocator, this.attributeMap.map(element.tagName, info.attrName), this.parser.parse(info.attrValue), _aureliaBinding.bindingMode.twoWay, resources.lookupFunctions); + + return instruction; + }; + + SyntaxInterpreter.prototype['one-way'] = function oneWay(resources, element, info, existingInstruction) { + var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); + + instruction.attributes[info.attrName] = new _aureliaBinding.BindingExpression(this.observerLocator, this.attributeMap.map(element.tagName, info.attrName), this.parser.parse(info.attrValue), _aureliaBinding.bindingMode.oneWay, resources.lookupFunctions); + + return instruction; + }; + + SyntaxInterpreter.prototype['one-time'] = function oneTime(resources, element, info, existingInstruction) { + var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); + + instruction.attributes[info.attrName] = new _aureliaBinding.BindingExpression(this.observerLocator, this.attributeMap.map(element.tagName, info.attrName), this.parser.parse(info.attrValue), _aureliaBinding.bindingMode.oneTime, resources.lookupFunctions); + + return instruction; + }; + + return SyntaxInterpreter; + }(), _class3.inject = [_aureliaBinding.Parser, _aureliaBinding.ObserverLocator, _aureliaBinding.EventManager, AttributeMap], _temp2); + + var info = {}; + + var TemplatingBindingLanguage = exports.TemplatingBindingLanguage = (_temp3 = _class4 = function (_BindingLanguage) { + _inherits(TemplatingBindingLanguage, _BindingLanguage); + + function TemplatingBindingLanguage(parser, observerLocator, syntaxInterpreter, attributeMap) { + + + var _this = _possibleConstructorReturn(this, _BindingLanguage.call(this)); + + _this.parser = parser; + _this.observerLocator = observerLocator; + _this.syntaxInterpreter = syntaxInterpreter; + _this.emptyStringExpression = _this.parser.parse('\'\''); + syntaxInterpreter.language = _this; + _this.attributeMap = attributeMap; + return _this; + } + + TemplatingBindingLanguage.prototype.inspectAttribute = function inspectAttribute(resources, elementName, attrName, attrValue) { + var parts = attrName.split('.'); + + info.defaultBindingMode = null; + + if (parts.length === 2) { + info.attrName = parts[0].trim(); + info.attrValue = attrValue; + info.command = parts[1].trim(); + + if (info.command === 'ref') { + info.expression = new _aureliaBinding.NameExpression(this.parser.parse(attrValue), info.attrName, resources.lookupFunctions); + info.command = null; + info.attrName = 'ref'; + } else { + info.expression = null; + } + } else if (attrName === 'ref') { + info.attrName = attrName; + info.attrValue = attrValue; + info.command = null; + info.expression = new _aureliaBinding.NameExpression(this.parser.parse(attrValue), 'element', resources.lookupFunctions); + } else { + info.attrName = attrName; + info.attrValue = attrValue; + info.command = null; + var interpolationParts = this.parseInterpolation(resources, attrValue); + if (interpolationParts === null) { + info.expression = null; + } else { + info.expression = new InterpolationBindingExpression(this.observerLocator, this.attributeMap.map(elementName, attrName), interpolationParts, _aureliaBinding.bindingMode.oneWay, resources.lookupFunctions, attrName); + } + } + + return info; + }; + + TemplatingBindingLanguage.prototype.createAttributeInstruction = function createAttributeInstruction(resources, element, theInfo, existingInstruction, context) { + var instruction = void 0; + + if (theInfo.expression) { + if (theInfo.attrName === 'ref') { + return theInfo.expression; + } + + instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(theInfo.attrName); + instruction.attributes[theInfo.attrName] = theInfo.expression; + } else if (theInfo.command) { + instruction = this.syntaxInterpreter.interpret(resources, element, theInfo, existingInstruction, context); + } + + return instruction; + }; + + TemplatingBindingLanguage.prototype.inspectTextContent = function inspectTextContent(resources, value) { + var parts = this.parseInterpolation(resources, value); + if (parts === null) { + return null; + } + return new InterpolationBindingExpression(this.observerLocator, 'textContent', parts, _aureliaBinding.bindingMode.oneWay, resources.lookupFunctions, 'textContent'); + }; + + TemplatingBindingLanguage.prototype.parseInterpolation = function parseInterpolation(resources, value) { + var i = value.indexOf('${', 0); + var ii = value.length; + var char = void 0; + var pos = 0; + var open = 0; + var quote = null; + var interpolationStart = void 0; + var parts = void 0; + var partIndex = 0; + + while (i >= 0 && i < ii - 2) { + open = 1; + interpolationStart = i; + i += 2; + + do { + char = value[i]; + i++; + + if (char === "'" || char === '"') { + if (quote === null) { + quote = char; + } else if (quote === char) { + quote = null; + } + continue; + } + + if (char === '\\') { + i++; + continue; + } + + if (quote !== null) { + continue; + } + + if (char === '{') { + open++; + } else if (char === '}') { + open--; + } + } while (open > 0 && i < ii); + + if (open === 0) { + parts = parts || []; + if (value[interpolationStart - 1] === '\\' && value[interpolationStart - 2] !== '\\') { + parts[partIndex] = value.substring(pos, interpolationStart - 1) + value.substring(interpolationStart, i); + partIndex++; + parts[partIndex] = this.emptyStringExpression; + partIndex++; + } else { + parts[partIndex] = value.substring(pos, interpolationStart); + partIndex++; + parts[partIndex] = this.parser.parse(value.substring(interpolationStart + 2, i - 1)); + partIndex++; + } + pos = i; + i = value.indexOf('${', i); + } else { + break; + } + } + + if (partIndex === 0) { + return null; + } + + parts[partIndex] = value.substr(pos); + return parts; + }; + + return TemplatingBindingLanguage; + }(_aureliaTemplating.BindingLanguage), _class4.inject = [_aureliaBinding.Parser, _aureliaBinding.ObserverLocator, SyntaxInterpreter, AttributeMap], _temp3); + function configure(config) { + config.container.registerSingleton(_aureliaTemplating.BindingLanguage, TemplatingBindingLanguage); + config.container.registerAlias(_aureliaTemplating.BindingLanguage, TemplatingBindingLanguage); + } +}); +define('aurelia-http-client',['exports', 'aurelia-path', 'aurelia-pal'], function (exports, _aureliaPath, _aureliaPal) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.HttpClient = exports.RequestBuilder = exports.HttpRequestMessage = exports.JSONPRequestMessage = exports.RequestMessageProcessor = exports.mimeTypes = exports.HttpResponseMessage = exports.RequestMessage = exports.Headers = undefined; + exports.timeoutTransformer = timeoutTransformer; + exports.callbackParameterNameTransformer = callbackParameterNameTransformer; + exports.credentialsTransformer = credentialsTransformer; + exports.progressTransformer = progressTransformer; + exports.responseTypeTransformer = responseTypeTransformer; + exports.headerTransformer = headerTransformer; + exports.contentTransformer = contentTransformer; + exports.createJSONPRequestMessageProcessor = createJSONPRequestMessageProcessor; + exports.createHttpRequestMessageProcessor = createHttpRequestMessageProcessor; + + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + + var _createClass = function () { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + return function (Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps); + if (staticProps) defineProperties(Constructor, staticProps); + return Constructor; + }; + }(); + + + + var Headers = exports.Headers = function () { + function Headers() { + var headers = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; + + + + this.headers = headers; + } + + Headers.prototype.add = function add(key, value) { + this.headers[key] = value; + }; + + Headers.prototype.get = function get(key) { + return this.headers[key]; + }; + + Headers.prototype.clear = function clear() { + this.headers = {}; + }; + + Headers.prototype.has = function has(header) { + var lowered = header.toLowerCase(); + var headers = this.headers; + + for (var _key in headers) { + if (_key.toLowerCase() === lowered) { + return true; + } + } + + return false; + }; + + Headers.prototype.configureXHR = function configureXHR(xhr) { + var headers = this.headers; + + for (var _key2 in headers) { + xhr.setRequestHeader(_key2, headers[_key2]); + } + }; + + Headers.parse = function parse(headerStr) { + var headers = new Headers(); + if (!headerStr) { + return headers; + } + + var headerPairs = headerStr.split('\r\n'); + for (var i = 0; i < headerPairs.length; i++) { + var headerPair = headerPairs[i]; + + var index = headerPair.indexOf(': '); + if (index > 0) { + var _key3 = headerPair.substring(0, index); + var val = headerPair.substring(index + 2); + headers.add(_key3, val); + } + } + + return headers; + }; + + return Headers; + }(); + + var RequestMessage = exports.RequestMessage = function () { + function RequestMessage(method, url, content, headers) { + + + this.method = method; + this.url = url; + this.content = content; + this.headers = headers || new Headers(); + this.baseUrl = ''; + } + + RequestMessage.prototype.buildFullUrl = function buildFullUrl() { + var absoluteUrl = /^([a-z][a-z0-9+\-.]*:)?\/\//i; + var url = absoluteUrl.test(this.url) ? this.url : (0, _aureliaPath.join)(this.baseUrl, this.url); + + if (this.params) { + var qs = (0, _aureliaPath.buildQueryString)(this.params); + url = qs ? url + (this.url.indexOf('?') < 0 ? '?' : '&') + qs : url; + } + + return url; + }; + + return RequestMessage; + }(); + + var HttpResponseMessage = exports.HttpResponseMessage = function () { + function HttpResponseMessage(requestMessage, xhr, responseType, reviver) { + + + this.requestMessage = requestMessage; + this.statusCode = xhr.status; + this.response = xhr.response || xhr.responseText; + this.isSuccess = xhr.status >= 200 && xhr.status < 400; + this.statusText = xhr.statusText; + this.reviver = reviver; + this.mimeType = null; + + if (xhr.getAllResponseHeaders) { + try { + this.headers = Headers.parse(xhr.getAllResponseHeaders()); + } catch (err) { + if (xhr.requestHeaders) this.headers = { headers: xhr.requestHeaders }; + } + } else { + this.headers = new Headers(); + } + + var contentType = void 0; + if (this.headers && this.headers.headers) contentType = this.headers.headers['Content-Type']; + if (contentType) { + this.mimeType = responseType = contentType.split(';')[0].trim(); + if (mimeTypes.hasOwnProperty(this.mimeType)) responseType = mimeTypes[this.mimeType]; + } + + this.responseType = responseType; + } + + _createClass(HttpResponseMessage, [{ + key: 'content', + get: function get() { + try { + if (this._content !== undefined) { + return this._content; + } + + if (this.response === undefined || this.response === null) { + this._content = this.response; + return this._content; + } + + if (this.responseType === 'json') { + this._content = JSON.parse(this.response, this.reviver); + return this._content; + } + + if (this.reviver) { + this._content = this.reviver(this.response); + return this._content; + } + + this._content = this.response; + return this._content; + } catch (e) { + if (this.isSuccess) { + throw e; + } + + this._content = null; + return this._content; + } + } + }]); + + return HttpResponseMessage; + }(); + + var mimeTypes = exports.mimeTypes = { + 'text/html': 'html', + 'text/javascript': 'js', + 'application/javascript': 'js', + 'text/json': 'json', + 'application/json': 'json', + 'application/rss+xml': 'rss', + 'application/atom+xml': 'atom', + 'application/xhtml+xml': 'xhtml', + 'text/markdown': 'md', + 'text/xml': 'xml', + 'text/mathml': 'mml', + 'application/xml': 'xml', + 'text/yml': 'yml', + 'text/csv': 'csv', + 'text/css': 'css', + 'text/less': 'less', + 'text/stylus': 'styl', + 'text/scss': 'scss', + 'text/sass': 'sass', + 'text/plain': 'txt' + }; + + function applyXhrTransformers(xhrTransformers, client, processor, message, xhr) { + var i = void 0; + var ii = void 0; + + for (i = 0, ii = xhrTransformers.length; i < ii; ++i) { + xhrTransformers[i](client, processor, message, xhr); + } + } + + var RequestMessageProcessor = exports.RequestMessageProcessor = function () { + function RequestMessageProcessor(xhrType, xhrTransformers) { + + + this.XHRType = xhrType; + this.xhrTransformers = xhrTransformers; + this.isAborted = false; + } + + RequestMessageProcessor.prototype.abort = function abort() { + if (this.xhr && this.xhr.readyState !== _aureliaPal.PLATFORM.XMLHttpRequest.UNSENT) { + this.xhr.abort(); + } + + this.isAborted = true; + }; + + RequestMessageProcessor.prototype.process = function process(client, requestMessage) { + var _this = this; + + var promise = new Promise(function (resolve, reject) { + var xhr = _this.xhr = new _this.XHRType(); + + xhr.onload = function (e) { + var response = new HttpResponseMessage(requestMessage, xhr, requestMessage.responseType, requestMessage.reviver); + if (response.isSuccess) { + resolve(response); + } else { + reject(response); + } + }; + + xhr.ontimeout = function (e) { + reject(new HttpResponseMessage(requestMessage, { + response: e, + status: xhr.status, + statusText: xhr.statusText + }, 'timeout')); + }; + + xhr.onerror = function (e) { + reject(new HttpResponseMessage(requestMessage, { + response: e, + status: xhr.status, + statusText: xhr.statusText + }, 'error')); + }; + + xhr.onabort = function (e) { + reject(new HttpResponseMessage(requestMessage, { + response: e, + status: xhr.status, + statusText: xhr.statusText + }, 'abort')); + }; + }); + + return Promise.resolve(requestMessage).then(function (message) { + var processRequest = function processRequest() { + if (_this.isAborted) { + _this.xhr.abort(); + } else { + _this.xhr.open(message.method, message.buildFullUrl(), true, message.user, message.password); + applyXhrTransformers(_this.xhrTransformers, client, _this, message, _this.xhr); + if (typeof message.content === 'undefined') { + _this.xhr.send(); + } else { + _this.xhr.send(message.content); + } + } + + return promise; + }; + + var chain = [[processRequest, undefined]]; + + var interceptors = message.interceptors || []; + interceptors.forEach(function (interceptor) { + if (interceptor.request || interceptor.requestError) { + chain.unshift([interceptor.request ? interceptor.request.bind(interceptor) : undefined, interceptor.requestError ? interceptor.requestError.bind(interceptor) : undefined]); + } + + if (interceptor.response || interceptor.responseError) { + chain.push([interceptor.response ? interceptor.response.bind(interceptor) : undefined, interceptor.responseError ? interceptor.responseError.bind(interceptor) : undefined]); + } + }); + + var interceptorsPromise = Promise.resolve(message); + + while (chain.length) { + var _interceptorsPromise; + + interceptorsPromise = (_interceptorsPromise = interceptorsPromise).then.apply(_interceptorsPromise, chain.shift()); + } + + return interceptorsPromise; + }); + }; + + return RequestMessageProcessor; + }(); + + function timeoutTransformer(client, processor, message, xhr) { + if (message.timeout !== undefined) { + xhr.timeout = message.timeout; + } + } + + function callbackParameterNameTransformer(client, processor, message, xhr) { + if (message.callbackParameterName !== undefined) { + xhr.callbackParameterName = message.callbackParameterName; + } + } + + function credentialsTransformer(client, processor, message, xhr) { + if (message.withCredentials !== undefined) { + xhr.withCredentials = message.withCredentials; + } + } + + function progressTransformer(client, processor, message, xhr) { + if (message.progressCallback) { + xhr.upload.onprogress = message.progressCallback; + } + } + + function responseTypeTransformer(client, processor, message, xhr) { + var responseType = message.responseType; + + if (responseType === 'json') { + responseType = 'text'; + } + + xhr.responseType = responseType; + } + + function headerTransformer(client, processor, message, xhr) { + message.headers.configureXHR(xhr); + } + + function contentTransformer(client, processor, message, xhr) { + if (message.skipContentProcessing) { + return; + } + + if (_aureliaPal.PLATFORM.global.FormData && message.content instanceof FormData) { + return; + } + + if (_aureliaPal.PLATFORM.global.Blob && message.content instanceof Blob) { + return; + } + + if (_aureliaPal.PLATFORM.global.ArrayBufferView && message.content instanceof ArrayBufferView) { + return; + } + + if (message.content instanceof Document) { + return; + } + + if (typeof message.content === 'string') { + return; + } + + if (message.content === null || message.content === undefined) { + return; + } + + message.content = JSON.stringify(message.content, message.replacer); + + if (!message.headers.has('Content-Type')) { + message.headers.add('Content-Type', 'application/json'); + } + } + + var JSONPRequestMessage = exports.JSONPRequestMessage = function (_RequestMessage) { + _inherits(JSONPRequestMessage, _RequestMessage); + + function JSONPRequestMessage(url, callbackParameterName) { + + + var _this2 = _possibleConstructorReturn(this, _RequestMessage.call(this, 'JSONP', url)); + + _this2.responseType = 'jsonp'; + _this2.callbackParameterName = callbackParameterName; + return _this2; + } + + return JSONPRequestMessage; + }(RequestMessage); + + var JSONPXHR = function () { + function JSONPXHR() { + + } + + JSONPXHR.prototype.open = function open(method, url) { + this.method = method; + this.url = url; + this.callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random()); + }; + + JSONPXHR.prototype.send = function send() { + var _this3 = this; + + var url = this.url + (this.url.indexOf('?') >= 0 ? '&' : '?') + encodeURIComponent(this.callbackParameterName) + '=' + this.callbackName; + var script = _aureliaPal.DOM.createElement('script'); + + script.src = url; + script.onerror = function (e) { + cleanUp(); + + _this3.status = 0; + _this3.onerror(new Error('error')); + }; + + var cleanUp = function cleanUp() { + delete _aureliaPal.PLATFORM.global[_this3.callbackName]; + _aureliaPal.DOM.removeNode(script); + }; + + _aureliaPal.PLATFORM.global[this.callbackName] = function (data) { + cleanUp(); + + if (_this3.status === undefined) { + _this3.status = 200; + _this3.statusText = 'OK'; + _this3.response = data; + _this3.onload(_this3); + } + }; + + _aureliaPal.DOM.appendNode(script); + + if (this.timeout !== undefined) { + setTimeout(function () { + if (_this3.status === undefined) { + _this3.status = 0; + _this3.ontimeout(new Error('timeout')); + } + }, this.timeout); + } + }; + + JSONPXHR.prototype.abort = function abort() { + if (this.status === undefined) { + this.status = 0; + this.onabort(new Error('abort')); + } + }; + + JSONPXHR.prototype.setRequestHeader = function setRequestHeader() {}; + + return JSONPXHR; + }(); + + function createJSONPRequestMessageProcessor() { + return new RequestMessageProcessor(JSONPXHR, [timeoutTransformer, callbackParameterNameTransformer]); + } + + var HttpRequestMessage = exports.HttpRequestMessage = function (_RequestMessage2) { + _inherits(HttpRequestMessage, _RequestMessage2); + + function HttpRequestMessage(method, url, content, headers) { + + + var _this4 = _possibleConstructorReturn(this, _RequestMessage2.call(this, method, url, content, headers)); + + _this4.responseType = 'json';return _this4; + } + + return HttpRequestMessage; + }(RequestMessage); + + function createHttpRequestMessageProcessor() { + return new RequestMessageProcessor(_aureliaPal.PLATFORM.XMLHttpRequest, [timeoutTransformer, credentialsTransformer, progressTransformer, responseTypeTransformer, contentTransformer, headerTransformer]); + } + + var RequestBuilder = exports.RequestBuilder = function () { + function RequestBuilder(client) { + + + this.client = client; + this.transformers = client.requestTransformers.slice(0); + this.useJsonp = false; + } + + RequestBuilder.prototype.asDelete = function asDelete() { + return this._addTransformer(function (client, processor, message) { + message.method = 'DELETE'; + }); + }; + + RequestBuilder.prototype.asGet = function asGet() { + return this._addTransformer(function (client, processor, message) { + message.method = 'GET'; + }); + }; + + RequestBuilder.prototype.asHead = function asHead() { + return this._addTransformer(function (client, processor, message) { + message.method = 'HEAD'; + }); + }; + + RequestBuilder.prototype.asOptions = function asOptions() { + return this._addTransformer(function (client, processor, message) { + message.method = 'OPTIONS'; + }); + }; + + RequestBuilder.prototype.asPatch = function asPatch() { + return this._addTransformer(function (client, processor, message) { + message.method = 'PATCH'; + }); + }; + + RequestBuilder.prototype.asPost = function asPost() { + return this._addTransformer(function (client, processor, message) { + message.method = 'POST'; + }); + }; + + RequestBuilder.prototype.asPut = function asPut() { + return this._addTransformer(function (client, processor, message) { + message.method = 'PUT'; + }); + }; + + RequestBuilder.prototype.asJsonp = function asJsonp(callbackParameterName) { + this.useJsonp = true; + return this._addTransformer(function (client, processor, message) { + message.callbackParameterName = callbackParameterName; + }); + }; + + RequestBuilder.prototype.withUrl = function withUrl(url) { + return this._addTransformer(function (client, processor, message) { + message.url = url; + }); + }; + + RequestBuilder.prototype.withContent = function withContent(content) { + return this._addTransformer(function (client, processor, message) { + message.content = content; + }); + }; + + RequestBuilder.prototype.withBaseUrl = function withBaseUrl(baseUrl) { + return this._addTransformer(function (client, processor, message) { + message.baseUrl = baseUrl; + }); + }; + + RequestBuilder.prototype.withParams = function withParams(params) { + return this._addTransformer(function (client, processor, message) { + message.params = params; + }); + }; + + RequestBuilder.prototype.withResponseType = function withResponseType(responseType) { + return this._addTransformer(function (client, processor, message) { + message.responseType = responseType; + }); + }; + + RequestBuilder.prototype.withTimeout = function withTimeout(timeout) { + return this._addTransformer(function (client, processor, message) { + message.timeout = timeout; + }); + }; + + RequestBuilder.prototype.withHeader = function withHeader(key, value) { + return this._addTransformer(function (client, processor, message) { + message.headers.add(key, value); + }); + }; + + RequestBuilder.prototype.withCredentials = function withCredentials(value) { + return this._addTransformer(function (client, processor, message) { + message.withCredentials = value; + }); + }; + + RequestBuilder.prototype.withLogin = function withLogin(user, password) { + return this._addTransformer(function (client, processor, message) { + message.user = user;message.password = password; + }); + }; + + RequestBuilder.prototype.withReviver = function withReviver(reviver) { + return this._addTransformer(function (client, processor, message) { + message.reviver = reviver; + }); + }; + + RequestBuilder.prototype.withReplacer = function withReplacer(replacer) { + return this._addTransformer(function (client, processor, message) { + message.replacer = replacer; + }); + }; + + RequestBuilder.prototype.withProgressCallback = function withProgressCallback(progressCallback) { + return this._addTransformer(function (client, processor, message) { + message.progressCallback = progressCallback; + }); + }; + + RequestBuilder.prototype.withCallbackParameterName = function withCallbackParameterName(callbackParameterName) { + return this._addTransformer(function (client, processor, message) { + message.callbackParameterName = callbackParameterName; + }); + }; + + RequestBuilder.prototype.withInterceptor = function withInterceptor(interceptor) { + return this._addTransformer(function (client, processor, message) { + message.interceptors = message.interceptors || []; + message.interceptors.unshift(interceptor); + }); + }; + + RequestBuilder.prototype.skipContentProcessing = function skipContentProcessing() { + return this._addTransformer(function (client, processor, message) { + message.skipContentProcessing = true; + }); + }; + + RequestBuilder.prototype._addTransformer = function _addTransformer(fn) { + this.transformers.push(fn); + return this; + }; + + RequestBuilder.addHelper = function addHelper(name, fn) { + RequestBuilder.prototype[name] = function () { + return this._addTransformer(fn.apply(this, arguments)); + }; + }; + + RequestBuilder.prototype.send = function send() { + var message = this.useJsonp ? new JSONPRequestMessage() : new HttpRequestMessage(); + return this.client.send(message, this.transformers); + }; + + return RequestBuilder; + }(); + + function trackRequestStart(client, processor) { + client.pendingRequests.push(processor); + client.isRequesting = true; + } + + function trackRequestEnd(client, processor) { + var index = client.pendingRequests.indexOf(processor); + + client.pendingRequests.splice(index, 1); + client.isRequesting = client.pendingRequests.length > 0; + + if (!client.isRequesting) { + (function () { + var evt = _aureliaPal.DOM.createCustomEvent('aurelia-http-client-requests-drained', { bubbles: true, cancelable: true }); + setTimeout(function () { + return _aureliaPal.DOM.dispatchEvent(evt); + }, 1); + })(); + } + } + + var HttpClient = exports.HttpClient = function () { + function HttpClient() { + + + this.isRequesting = false; + + this.requestTransformers = []; + this.requestProcessorFactories = new Map(); + this.requestProcessorFactories.set(HttpRequestMessage, createHttpRequestMessageProcessor); + this.requestProcessorFactories.set(JSONPRequestMessage, createJSONPRequestMessageProcessor); + this.pendingRequests = []; + } + + HttpClient.prototype.configure = function configure(fn) { + var builder = new RequestBuilder(this); + fn(builder); + this.requestTransformers = builder.transformers; + return this; + }; + + HttpClient.prototype.createRequest = function createRequest(url) { + var builder = new RequestBuilder(this); + + if (url) { + builder.withUrl(url); + } + + return builder; + }; + + HttpClient.prototype.send = function send(requestMessage, transformers) { + var _this5 = this; + + var createProcessor = this.requestProcessorFactories.get(requestMessage.constructor); + var processor = void 0; + var promise = void 0; + var i = void 0; + var ii = void 0; + + if (!createProcessor) { + throw new Error('No request message processor factory for ' + requestMessage.constructor + '.'); + } + + processor = createProcessor(); + trackRequestStart(this, processor); + + transformers = transformers || this.requestTransformers; + + promise = Promise.resolve(requestMessage).then(function (message) { + for (i = 0, ii = transformers.length; i < ii; ++i) { + transformers[i](_this5, processor, message); + } + + return processor.process(_this5, message).then(function (response) { + trackRequestEnd(_this5, processor); + return response; + }).catch(function (response) { + trackRequestEnd(_this5, processor); + throw response; + }); + }); + + promise.abort = promise.cancel = function () { + processor.abort(); + }; + + return promise; + }; + + HttpClient.prototype.delete = function _delete(url) { + return this.createRequest(url).asDelete().send(); + }; + + HttpClient.prototype.get = function get(url) { + return this.createRequest(url).asGet().send(); + }; + + HttpClient.prototype.head = function head(url) { + return this.createRequest(url).asHead().send(); + }; + + HttpClient.prototype.jsonp = function jsonp(url) { + var callbackParameterName = arguments.length <= 1 || arguments[1] === undefined ? 'jsoncallback' : arguments[1]; + + return this.createRequest(url).asJsonp(callbackParameterName).send(); + }; + + HttpClient.prototype.options = function options(url) { + return this.createRequest(url).asOptions().send(); + }; + + HttpClient.prototype.put = function put(url, content) { + return this.createRequest(url).asPut().withContent(content).send(); + }; + + HttpClient.prototype.patch = function patch(url, content) { + return this.createRequest(url).asPatch().withContent(content).send(); + }; + + HttpClient.prototype.post = function post(url, content) { + return this.createRequest(url).asPost().withContent(content).send(); + }; + + return HttpClient; + }(); +}); +define('aurelia-fetch-client',['exports'], function (exports) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.json = json; + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; + }; + + + + function json(body) { + return new Blob([JSON.stringify(body)], { type: 'application/json' }); + } + + var HttpClientConfiguration = exports.HttpClientConfiguration = function () { + function HttpClientConfiguration() { + + + this.baseUrl = ''; + this.defaults = {}; + this.interceptors = []; + } + + HttpClientConfiguration.prototype.withBaseUrl = function withBaseUrl(baseUrl) { + this.baseUrl = baseUrl; + return this; + }; + + HttpClientConfiguration.prototype.withDefaults = function withDefaults(defaults) { + this.defaults = defaults; + return this; + }; + + HttpClientConfiguration.prototype.withInterceptor = function withInterceptor(interceptor) { + this.interceptors.push(interceptor); + return this; + }; + + HttpClientConfiguration.prototype.useStandardConfiguration = function useStandardConfiguration() { + var standardConfig = { credentials: 'same-origin' }; + Object.assign(this.defaults, standardConfig, this.defaults); + return this.rejectErrorResponses(); + }; + + HttpClientConfiguration.prototype.rejectErrorResponses = function rejectErrorResponses() { + return this.withInterceptor({ response: rejectOnError }); + }; + + return HttpClientConfiguration; + }(); + + function rejectOnError(response) { + if (!response.ok) { + throw response; + } + + return response; + } + + var HttpClient = exports.HttpClient = function () { + function HttpClient() { + + + this.activeRequestCount = 0; + this.isRequesting = false; + this.isConfigured = false; + this.baseUrl = ''; + this.defaults = null; + this.interceptors = []; + + if (typeof fetch === 'undefined') { + throw new Error('HttpClient requires a Fetch API implementation, but the current environment doesn\'t support it. You may need to load a polyfill such as https://github.com/github/fetch.'); + } + } + + HttpClient.prototype.configure = function configure(config) { + var _interceptors; + + var normalizedConfig = void 0; + + if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object') { + normalizedConfig = { defaults: config }; + } else if (typeof config === 'function') { + normalizedConfig = new HttpClientConfiguration(); + var c = config(normalizedConfig); + if (HttpClientConfiguration.prototype.isPrototypeOf(c)) { + normalizedConfig = c; + } + } else { + throw new Error('invalid config'); + } + + var defaults = normalizedConfig.defaults; + if (defaults && Headers.prototype.isPrototypeOf(defaults.headers)) { + throw new Error('Default headers must be a plain object.'); + } + + this.baseUrl = normalizedConfig.baseUrl; + this.defaults = defaults; + (_interceptors = this.interceptors).push.apply(_interceptors, normalizedConfig.interceptors || []); + this.isConfigured = true; + + return this; + }; + + HttpClient.prototype.fetch = function (_fetch) { + function fetch(_x, _x2) { + return _fetch.apply(this, arguments); + } + + fetch.toString = function () { + return _fetch.toString(); + }; + + return fetch; + }(function (input, init) { + var _this = this; + + trackRequestStart.call(this); + + var request = Promise.resolve().then(function () { + return buildRequest.call(_this, input, init, _this.defaults); + }); + var promise = processRequest(request, this.interceptors).then(function (result) { + var response = null; + + if (Response.prototype.isPrototypeOf(result)) { + response = result; + } else if (Request.prototype.isPrototypeOf(result)) { + request = Promise.resolve(result); + response = fetch(result); + } else { + throw new Error('An invalid result was returned by the interceptor chain. Expected a Request or Response instance, but got [' + result + ']'); + } + + return request.then(function (_request) { + return processResponse(response, _this.interceptors, _request); + }); + }); + + return trackRequestEndWith.call(this, promise); + }); + + return HttpClient; + }(); + + var absoluteUrlRegexp = /^([a-z][a-z0-9+\-.]*:)?\/\//i; + + function trackRequestStart() { + this.isRequesting = !! ++this.activeRequestCount; + } + + function trackRequestEnd() { + this.isRequesting = !! --this.activeRequestCount; + } + + function trackRequestEndWith(promise) { + var handle = trackRequestEnd.bind(this); + promise.then(handle, handle); + return promise; + } + + function parseHeaderValues(headers) { + var parsedHeaders = {}; + for (var name in headers || {}) { + if (headers.hasOwnProperty(name)) { + parsedHeaders[name] = typeof headers[name] === 'function' ? headers[name]() : headers[name]; + } + } + return parsedHeaders; + } + + function buildRequest(input, init) { + var defaults = this.defaults || {}; + var request = void 0; + var body = void 0; + var requestContentType = void 0; + + var parsedDefaultHeaders = parseHeaderValues(defaults.headers); + if (Request.prototype.isPrototypeOf(input)) { + request = input; + requestContentType = new Headers(request.headers).get('Content-Type'); + } else { + init || (init = {}); + body = init.body; + var bodyObj = body ? { body: body } : null; + var requestInit = Object.assign({}, defaults, { headers: {} }, init, bodyObj); + requestContentType = new Headers(requestInit.headers).get('Content-Type'); + request = new Request(getRequestUrl(this.baseUrl, input), requestInit); + } + if (!requestContentType && new Headers(parsedDefaultHeaders).has('content-type')) { + request.headers.set('Content-Type', new Headers(parsedDefaultHeaders).get('content-type')); + } + setDefaultHeaders(request.headers, parsedDefaultHeaders); + if (body && Blob.prototype.isPrototypeOf(body) && body.type) { + request.headers.set('Content-Type', body.type); + } + return request; + } + + function getRequestUrl(baseUrl, url) { + if (absoluteUrlRegexp.test(url)) { + return url; + } + + return (baseUrl || '') + url; + } + + function setDefaultHeaders(headers, defaultHeaders) { + for (var name in defaultHeaders || {}) { + if (defaultHeaders.hasOwnProperty(name) && !headers.has(name)) { + headers.set(name, defaultHeaders[name]); + } + } + } + + function processRequest(request, interceptors) { + return applyInterceptors(request, interceptors, 'request', 'requestError'); + } + + function processResponse(response, interceptors, request) { + return applyInterceptors(response, interceptors, 'response', 'responseError', request); + } + + function applyInterceptors(input, interceptors, successName, errorName) { + for (var _len = arguments.length, interceptorArgs = Array(_len > 4 ? _len - 4 : 0), _key = 4; _key < _len; _key++) { + interceptorArgs[_key - 4] = arguments[_key]; + } + + return (interceptors || []).reduce(function (chain, interceptor) { + var successHandler = interceptor[successName]; + var errorHandler = interceptor[errorName]; + + return chain.then(successHandler && function (value) { + return successHandler.call.apply(successHandler, [interceptor, value].concat(interceptorArgs)); + } || identity, errorHandler && function (reason) { + return errorHandler.call.apply(errorHandler, [interceptor, reason].concat(interceptorArgs)); + } || thrower); + }, Promise.resolve(input)); + } + + function identity(x) { + return x; + } + + function thrower(x) { + throw x; + } +}); +define('aurelia-pal-browser',['exports', 'aurelia-pal'], function (exports, _aureliaPal) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports._DOM = exports._FEATURE = exports._PLATFORM = undefined; + exports._ensureFunctionName = _ensureFunctionName; + exports._ensureClassList = _ensureClassList; + exports._ensurePerformance = _ensurePerformance; + exports._ensureCustomEvent = _ensureCustomEvent; + exports._ensureElementMatches = _ensureElementMatches; + exports._ensureHTMLTemplateElement = _ensureHTMLTemplateElement; + exports.initialize = initialize; + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; + }; + + var _PLATFORM = exports._PLATFORM = { + location: window.location, + history: window.history, + addEventListener: function addEventListener(eventName, callback, capture) { + this.global.addEventListener(eventName, callback, capture); + }, + removeEventListener: function removeEventListener(eventName, callback, capture) { + this.global.removeEventListener(eventName, callback, capture); + }, + + performance: window.performance, + requestAnimationFrame: function requestAnimationFrame(callback) { + return this.global.requestAnimationFrame(callback); + } + }; + + function _ensureFunctionName() { + function test() {} + + if (!test.name) { + Object.defineProperty(Function.prototype, 'name', { + get: function get() { + var name = this.toString().match(/^\s*function\s*(\S*)\s*\(/)[1]; + + Object.defineProperty(this, 'name', { value: name }); + return name; + } + }); + } + } + + function _ensureClassList() { + if (!('classList' in document.createElement('_')) || document.createElementNS && !('classList' in document.createElementNS('http://www.w3.org/2000/svg', 'g'))) { + (function () { + var protoProp = 'prototype'; + var strTrim = String.prototype.trim; + var arrIndexOf = Array.prototype.indexOf; + var emptyArray = []; + + var DOMEx = function DOMEx(type, message) { + this.name = type; + this.code = DOMException[type]; + this.message = message; + }; + + var checkTokenAndGetIndex = function checkTokenAndGetIndex(classList, token) { + if (token === '') { + throw new DOMEx('SYNTAX_ERR', 'An invalid or illegal string was specified'); + } + + if (/\s/.test(token)) { + throw new DOMEx('INVALID_CHARACTER_ERR', 'String contains an invalid character'); + } + + return arrIndexOf.call(classList, token); + }; + + var ClassList = function ClassList(elem) { + var trimmedClasses = strTrim.call(elem.getAttribute('class') || ''); + var classes = trimmedClasses ? trimmedClasses.split(/\s+/) : emptyArray; + + for (var i = 0, ii = classes.length; i < ii; ++i) { + this.push(classes[i]); + } + + this._updateClassName = function () { + elem.setAttribute('class', this.toString()); + }; + }; + + var classListProto = ClassList[protoProp] = []; + + DOMEx[protoProp] = Error[protoProp]; + + classListProto.item = function (i) { + return this[i] || null; + }; + + classListProto.contains = function (token) { + token += ''; + return checkTokenAndGetIndex(this, token) !== -1; + }; + + classListProto.add = function () { + var tokens = arguments; + var i = 0; + var ii = tokens.length; + var token = void 0; + var updated = false; + + do { + token = tokens[i] + ''; + if (checkTokenAndGetIndex(this, token) === -1) { + this.push(token); + updated = true; + } + } while (++i < ii); + + if (updated) { + this._updateClassName(); + } + }; + + classListProto.remove = function () { + var tokens = arguments; + var i = 0; + var ii = tokens.length; + var token = void 0; + var updated = false; + var index = void 0; + + do { + token = tokens[i] + ''; + index = checkTokenAndGetIndex(this, token); + while (index !== -1) { + this.splice(index, 1); + updated = true; + index = checkTokenAndGetIndex(this, token); + } + } while (++i < ii); + + if (updated) { + this._updateClassName(); + } + }; + + classListProto.toggle = function (token, force) { + token += ''; + + var result = this.contains(token); + var method = result ? force !== true && 'remove' : force !== false && 'add'; + + if (method) { + this[method](token); + } + + if (force === true || force === false) { + return force; + } + + return !result; + }; + + classListProto.toString = function () { + return this.join(' '); + }; + + Object.defineProperty(Element.prototype, 'classList', { + get: function get() { + return new ClassList(this); + }, + enumerable: true, + configurable: true + }); + })(); + } else { + var testElement = document.createElement('_'); + testElement.classList.add('c1', 'c2'); + + if (!testElement.classList.contains('c2')) { + var createMethod = function createMethod(method) { + var original = DOMTokenList.prototype[method]; + + DOMTokenList.prototype[method] = function (token) { + for (var i = 0, ii = arguments.length; i < ii; ++i) { + token = arguments[i]; + original.call(this, token); + } + }; + }; + + createMethod('add'); + createMethod('remove'); + } + + testElement.classList.toggle('c3', false); + + if (testElement.classList.contains('c3')) { + (function () { + var _toggle = DOMTokenList.prototype.toggle; + + DOMTokenList.prototype.toggle = function (token, force) { + if (1 in arguments && !this.contains(token) === !force) { + return force; + } + + return _toggle.call(this, token); + }; + })(); + } + + testElement = null; + } + } + + function _ensurePerformance() { + // @license http://opensource.org/licenses/MIT + + + if ('performance' in window === false) { + window.performance = {}; + } + + if ('now' in window.performance === false) { + (function () { + var nowOffset = Date.now(); + + if (performance.timing && performance.timing.navigationStart) { + nowOffset = performance.timing.navigationStart; + } + + window.performance.now = function now() { + return Date.now() - nowOffset; + }; + })(); + } + + _PLATFORM.performance = window.performance; + } + + function _ensureCustomEvent() { + if (!window.CustomEvent || typeof window.CustomEvent !== 'function') { + var _CustomEvent = function _CustomEvent(event, params) { + params = params || { + bubbles: false, + cancelable: false, + detail: undefined + }; + + var evt = document.createEvent('CustomEvent'); + evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); + return evt; + }; + + _CustomEvent.prototype = window.Event.prototype; + window.CustomEvent = _CustomEvent; + } + } + + function _ensureElementMatches() { + if (Element && !Element.prototype.matches) { + var proto = Element.prototype; + proto.matches = proto.matchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector || proto.webkitMatchesSelector; + } + } + + var _FEATURE = exports._FEATURE = {}; + + _FEATURE.shadowDOM = function () { + return !!HTMLElement.prototype.attachShadow; + }(); + + _FEATURE.scopedCSS = function () { + return 'scoped' in document.createElement('style'); + }(); + + _FEATURE.htmlTemplateElement = function () { + return 'content' in document.createElement('template'); + }(); + + _FEATURE.mutationObserver = function () { + return !!(window.MutationObserver || window.WebKitMutationObserver); + }(); + + function _ensureHTMLTemplateElement() { + function isSVGTemplate(el) { + return el.tagName === 'template' && el.namespaceURI === 'http://www.w3.org/2000/svg'; + } + + function fixSVGTemplateElement(el) { + var template = el.ownerDocument.createElement('template'); + var attrs = el.attributes; + var length = attrs.length; + var attr = void 0; + + el.parentNode.insertBefore(template, el); + + while (length-- > 0) { + attr = attrs[length]; + template.setAttribute(attr.name, attr.value); + el.removeAttribute(attr.name); + } + + el.parentNode.removeChild(el); + + return fixHTMLTemplateElement(template); + } + + function fixHTMLTemplateElement(template) { + var content = template.content = document.createDocumentFragment(); + var child = void 0; + + while (child = template.firstChild) { + content.appendChild(child); + } + + return template; + } + + function fixHTMLTemplateElementRoot(template) { + var content = fixHTMLTemplateElement(template).content; + var childTemplates = content.querySelectorAll('template'); + + for (var i = 0, ii = childTemplates.length; i < ii; ++i) { + var child = childTemplates[i]; + + if (isSVGTemplate(child)) { + fixSVGTemplateElement(child); + } else { + fixHTMLTemplateElement(child); + } + } + + return template; + } + + if (_FEATURE.htmlTemplateElement) { + _FEATURE.ensureHTMLTemplateElement = function (template) { + return template; + }; + } else { + _FEATURE.ensureHTMLTemplateElement = fixHTMLTemplateElementRoot; + } + } + + var shadowPoly = window.ShadowDOMPolyfill || null; + + var _DOM = exports._DOM = { + Element: Element, + SVGElement: SVGElement, + boundary: 'aurelia-dom-boundary', + addEventListener: function addEventListener(eventName, callback, capture) { + document.addEventListener(eventName, callback, capture); + }, + removeEventListener: function removeEventListener(eventName, callback, capture) { + document.removeEventListener(eventName, callback, capture); + }, + adoptNode: function adoptNode(node) { + return document.adoptNode(node, true); + }, + createElement: function createElement(tagName) { + return document.createElement(tagName); + }, + createTextNode: function createTextNode(text) { + return document.createTextNode(text); + }, + createComment: function createComment(text) { + return document.createComment(text); + }, + createDocumentFragment: function createDocumentFragment() { + return document.createDocumentFragment(); + }, + createMutationObserver: function createMutationObserver(callback) { + return new (window.MutationObserver || window.WebKitMutationObserver)(callback); + }, + createCustomEvent: function createCustomEvent(eventType, options) { + return new window.CustomEvent(eventType, options); + }, + dispatchEvent: function dispatchEvent(evt) { + document.dispatchEvent(evt); + }, + getComputedStyle: function getComputedStyle(element) { + return window.getComputedStyle(element); + }, + getElementById: function getElementById(id) { + return document.getElementById(id); + }, + querySelectorAll: function querySelectorAll(query) { + return document.querySelectorAll(query); + }, + nextElementSibling: function nextElementSibling(element) { + if (element.nextElementSibling) { + return element.nextElementSibling; + } + do { + element = element.nextSibling; + } while (element && element.nodeType !== 1); + return element; + }, + createTemplateFromMarkup: function createTemplateFromMarkup(markup) { + var parser = document.createElement('div'); + parser.innerHTML = markup; + + var temp = parser.firstElementChild; + if (!temp || temp.nodeName !== 'TEMPLATE') { + throw new Error('Template markup must be wrapped in a