LocalCDN-Firefox-Chrome-Brave/resources/ember.js/4.0.0/ember.min.jsm

60766 lines
1.7 MiB
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

(function() {
/*!
* @overview Ember - JavaScript Application Framework
* @copyright Copyright 2011-2021 Tilde Inc. and contributors
* Portions Copyright 2006-2011 Strobe Inc.
* Portions Copyright 2008-2011 Apple Inc. All rights reserved.
* @license Licensed under MIT license
* See https://raw.github.com/emberjs/ember.js/master/LICENSE
* @version 4.0.0
*/
/* eslint-disable no-var */
/* globals global globalThis self */
var define, require;
(function () {
var globalObj = typeof globalThis !== 'undefined' ? globalThis : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : null;
if (globalObj === null) {
throw new Error('unable to locate global object');
}
if (typeof globalObj.define === 'function' && typeof globalObj.require === 'function') {
define = globalObj.define;
require = globalObj.require;
return;
}
var registry = Object.create(null);
var seen = Object.create(null);
function missingModule(name, referrerName) {
if (referrerName) {
throw new Error('Could not find module ' + name + ' required by: ' + referrerName);
} else {
throw new Error('Could not find module ' + name);
}
}
function internalRequire(_name, referrerName) {
var name = _name;
var mod = registry[name];
if (!mod) {
name = name + '/index';
mod = registry[name];
}
var exports = seen[name];
if (exports !== undefined) {
return exports;
}
exports = seen[name] = {};
if (!mod) {
missingModule(_name, referrerName);
}
var deps = mod.deps;
var callback = mod.callback;
var reified = new Array(deps.length);
for (var i = 0; i < deps.length; i++) {
if (deps[i] === 'exports') {
reified[i] = exports;
} else if (deps[i] === 'require') {
reified[i] = require;
} else {
reified[i] = require(deps[i], name);
}
}
callback.apply(this, reified);
return exports;
}
require = function (name) {
return internalRequire(name, null);
}; // eslint-disable-next-line no-unused-vars
define = function (name, deps, callback) {
registry[name] = {
deps: deps,
callback: callback
};
}; // setup `require` module
require['default'] = require;
require.has = function registryHas(moduleName) {
return Boolean(registry[moduleName]) || Boolean(registry[moduleName + '/index']);
};
require._eak_seen = require.entries = registry;
})();
define("@ember/-internals/bootstrap/index", ["require"], function (_require) {
"use strict";
(function bootstrap() {
// Bootstrap Node module
// eslint-disable-next-line no-undef
if (typeof module === 'object' && typeof module.require === 'function') {
// tslint:disable-next-line: no-require-imports
module.exports = (0, _require.default)("ember").default;
}
})();
});
define("@ember/-internals/browser-environment/index", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.hasDOM = _exports.isIE = _exports.isFirefox = _exports.isChrome = _exports.userAgent = _exports.history = _exports.location = _exports.window = void 0;
// check if window exists and actually is the global
var hasDom = typeof self === 'object' && self !== null && self.Object === Object && typeof Window !== 'undefined' && self.constructor === Window && typeof document === 'object' && document !== null && self.document === document && typeof location === 'object' && location !== null && self.location === location && typeof history === 'object' && history !== null && self.history === history && typeof navigator === 'object' && navigator !== null && self.navigator === navigator && typeof navigator.userAgent === 'string';
_exports.hasDOM = hasDom;
var window = hasDom ? self : null;
_exports.window = window;
var location$1 = hasDom ? self.location : null;
_exports.location = location$1;
var history$1 = hasDom ? self.history : null;
_exports.history = history$1;
var userAgent = hasDom ? self.navigator.userAgent : 'Lynx (textmode)';
_exports.userAgent = userAgent;
var isChrome = hasDom ? typeof chrome === 'object' && !(typeof opera === 'object') : false;
_exports.isChrome = isChrome;
var isFirefox = hasDom ? typeof InstallTrigger !== 'undefined' : false;
_exports.isFirefox = isFirefox;
var isIE = hasDom ? typeof MSInputMethodContext !== 'undefined' && typeof documentMode !== 'undefined' : false;
_exports.isIE = isIE;
});
define("@ember/-internals/container/index", ["exports", "@ember/-internals/owner", "@ember/-internals/utils", "@ember/debug"], function (_exports, _owner, _utils, _debug) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.privatize = privatize;
_exports.getFactoryFor = getFactoryFor;
_exports.setFactoryFor = setFactoryFor;
_exports.INIT_FACTORY = _exports.Container = _exports.Registry = void 0;
var leakTracking;
var containers;
if (true
/* DEBUG */
) {
// requires v8
// chrome --js-flags="--allow-natives-syntax --expose-gc"
// node --allow-natives-syntax --expose-gc
try {
if (typeof gc === 'function') {
leakTracking = (() => {
// avoid syntax errors when --allow-natives-syntax not present
var GetWeakSetValues = new Function('weakSet', 'return %GetWeakSetValues(weakSet, 0)');
containers = new WeakSet();
return {
hasContainers() {
gc();
return GetWeakSetValues(containers).length > 0;
},
reset() {
var values = GetWeakSetValues(containers);
for (var i = 0; i < values.length; i++) {
containers.delete(values[i]);
}
}
};
})();
}
} catch (e) {// ignore
}
}
/**
A container used to instantiate and cache objects.
Every `Container` must be associated with a `Registry`, which is referenced
to determine the factory and options that should be used to instantiate
objects.
The public API for `Container` is still in flux and should not be considered
stable.
@private
@class Container
*/
class Container {
constructor(registry, options = {}) {
this.registry = registry;
this.owner = options.owner || null;
this.cache = (0, _utils.dictionary)(options.cache || null);
this.factoryManagerCache = (0, _utils.dictionary)(options.factoryManagerCache || null);
this.isDestroyed = false;
this.isDestroying = false;
if (true
/* DEBUG */
) {
this.validationCache = (0, _utils.dictionary)(options.validationCache || null);
if (containers !== undefined) {
containers.add(this);
}
}
}
/**
@private
@property registry
@type Registry
@since 1.11.0
*/
/**
@private
@property cache
@type InheritingDict
*/
/**
@private
@property validationCache
@type InheritingDict
*/
/**
Given a fullName return a corresponding instance.
The default behavior is for lookup to return a singleton instance.
The singleton is scoped to the container, allowing multiple containers
to all have their own locally scoped singletons.
```javascript
let registry = new Registry();
let container = registry.container();
registry.register('api:twitter', Twitter);
let twitter = container.lookup('api:twitter');
twitter instanceof Twitter; // => true
// by default the container will return singletons
let twitter2 = container.lookup('api:twitter');
twitter2 instanceof Twitter; // => true
twitter === twitter2; //=> true
```
If singletons are not wanted, an optional flag can be provided at lookup.
```javascript
let registry = new Registry();
let container = registry.container();
registry.register('api:twitter', Twitter);
let twitter = container.lookup('api:twitter', { singleton: false });
let twitter2 = container.lookup('api:twitter', { singleton: false });
twitter === twitter2; //=> false
```
@private
@method lookup
@param {String} fullName
@param {Object} [options]
@param {String} [options.source] The fullname of the request source (used for local lookup)
@return {any}
*/
lookup(fullName, options) {
if (this.isDestroyed) {
throw new Error(`Can not call \`.lookup\` after the owner has been destroyed`);
}
(true && !(this.registry.isValidFullName(fullName)) && (0, _debug.assert)('fullName must be a proper full name', this.registry.isValidFullName(fullName)));
return lookup(this, this.registry.normalize(fullName), options);
}
/**
A depth first traversal, destroying the container, its descendant containers and all
their managed objects.
@private
@method destroy
*/
destroy() {
this.isDestroying = true;
destroyDestroyables(this);
}
finalizeDestroy() {
resetCache(this);
this.isDestroyed = true;
}
/**
Clear either the entire cache or just the cache for a particular key.
@private
@method reset
@param {String} fullName optional key to reset; if missing, resets everything
*/
reset(fullName) {
if (this.isDestroyed) return;
if (fullName === undefined) {
destroyDestroyables(this);
resetCache(this);
} else {
resetMember(this, this.registry.normalize(fullName));
}
}
/**
Returns an object that can be used to provide an owner to a
manually created instance.
@private
@method ownerInjection
@returns { Object }
*/
ownerInjection() {
var injection = {};
(0, _owner.setOwner)(injection, this.owner);
return injection;
}
/**
Given a fullName, return the corresponding factory. The consumer of the factory
is responsible for the destruction of any factory instances, as there is no
way for the container to ensure instances are destroyed when it itself is
destroyed.
@public
@method factoryFor
@param {String} fullName
@param {Object} [options]
@param {String} [options.source] The fullname of the request source (used for local lookup)
@return {any}
*/
factoryFor(fullName) {
if (this.isDestroyed) {
throw new Error(`Can not call \`.factoryFor\` after the owner has been destroyed`);
}
var normalizedName = this.registry.normalize(fullName);
(true && !(this.registry.isValidFullName(normalizedName)) && (0, _debug.assert)('fullName must be a proper full name', this.registry.isValidFullName(normalizedName)));
return factoryFor(this, normalizedName, fullName);
}
}
_exports.Container = Container;
if (true
/* DEBUG */
) {
Container._leakTracking = leakTracking;
}
/*
* Wrap a factory manager in a proxy which will not permit properties to be
* set on the manager.
*/
function wrapManagerInDeprecationProxy(manager) {
var validator = {
set(_obj, prop) {
throw new Error(`You attempted to set "${prop}" on a factory manager created by container#factoryFor. A factory manager is a read-only construct.`);
}
}; // Note:
// We have to proxy access to the manager here so that private property
// access doesn't cause the above errors to occur.
var m = manager;
var proxiedManager = {
class: m.class,
create(props) {
return m.create(props);
}
};
return new Proxy(proxiedManager, validator);
}
function isSingleton(container, fullName) {
return container.registry.getOption(fullName, 'singleton') !== false;
}
function isInstantiatable(container, fullName) {
return container.registry.getOption(fullName, 'instantiate') !== false;
}
function lookup(container, fullName, options = {}) {
var normalizedName = fullName;
if (options.singleton === true || options.singleton === undefined && isSingleton(container, fullName)) {
var cached = container.cache[normalizedName];
if (cached !== undefined) {
return cached;
}
}
return instantiateFactory(container, normalizedName, fullName, options);
}
function factoryFor(container, normalizedName, fullName) {
var cached = container.factoryManagerCache[normalizedName];
if (cached !== undefined) {
return cached;
}
var factory = container.registry.resolve(normalizedName);
if (factory === undefined) {
return;
}
if (true
/* DEBUG */
&& factory && typeof factory._onLookup === 'function') {
factory._onLookup(fullName);
}
var manager = new FactoryManager(container, factory, fullName, normalizedName);
if (true
/* DEBUG */
) {
manager = wrapManagerInDeprecationProxy(manager);
}
container.factoryManagerCache[normalizedName] = manager;
return manager;
}
function isSingletonClass(container, fullName, {
instantiate,
singleton
}) {
return singleton !== false && !instantiate && isSingleton(container, fullName) && !isInstantiatable(container, fullName);
}
function isSingletonInstance(container, fullName, {
instantiate,
singleton
}) {
return singleton !== false && instantiate !== false && (singleton === true || isSingleton(container, fullName)) && isInstantiatable(container, fullName);
}
function isFactoryClass(container, fullname, {
instantiate,
singleton
}) {
return instantiate === false && (singleton === false || !isSingleton(container, fullname)) && !isInstantiatable(container, fullname);
}
function isFactoryInstance(container, fullName, {
instantiate,
singleton
}) {
return instantiate !== false && (singleton === false || !isSingleton(container, fullName)) && isInstantiatable(container, fullName);
}
function instantiateFactory(container, normalizedName, fullName, options) {
var factoryManager = factoryFor(container, normalizedName, fullName);
if (factoryManager === undefined) {
return;
} // SomeClass { singleton: true, instantiate: true } | { singleton: true } | { instantiate: true } | {}
// By default majority of objects fall into this case
if (isSingletonInstance(container, fullName, options)) {
var instance = container.cache[normalizedName] = factoryManager.create(); // if this lookup happened _during_ destruction (emits a deprecation, but
// is still possible) ensure that it gets destroyed
if (container.isDestroying) {
if (typeof instance.destroy === 'function') {
instance.destroy();
}
}
return instance;
} // SomeClass { singleton: false, instantiate: true }
if (isFactoryInstance(container, fullName, options)) {
return factoryManager.create();
} // SomeClass { singleton: true, instantiate: false } | { instantiate: false } | { singleton: false, instantiation: false }
if (isSingletonClass(container, fullName, options) || isFactoryClass(container, fullName, options)) {
return factoryManager.class;
}
throw new Error('Could not create factory');
}
function destroyDestroyables(container) {
var cache = container.cache;
var keys = Object.keys(cache);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = cache[key];
if (value.destroy) {
value.destroy();
}
}
}
function resetCache(container) {
container.cache = (0, _utils.dictionary)(null);
container.factoryManagerCache = (0, _utils.dictionary)(null);
}
function resetMember(container, fullName) {
var member = container.cache[fullName];
delete container.factoryManagerCache[fullName];
if (member) {
delete container.cache[fullName];
if (member.destroy) {
member.destroy();
}
}
}
var INIT_FACTORY = (0, _utils.symbol)('INIT_FACTORY');
_exports.INIT_FACTORY = INIT_FACTORY;
function getFactoryFor(obj) {
return obj[INIT_FACTORY];
}
function setFactoryFor(obj, factory) {
obj[INIT_FACTORY] = factory;
}
class FactoryManager {
constructor(container, factory, fullName, normalizedName) {
this.container = container;
this.owner = container.owner;
this.class = factory;
this.fullName = fullName;
this.normalizedName = normalizedName;
this.madeToString = undefined;
this.injections = undefined;
setFactoryFor(this, this);
if (isInstantiatable(container, fullName)) {
setFactoryFor(factory, this);
}
}
toString() {
if (this.madeToString === undefined) {
this.madeToString = this.container.registry.makeToString(this.class, this.fullName);
}
return this.madeToString;
}
create(options) {
var {
container
} = this;
if (container.isDestroyed) {
throw new Error(`Can not create new instances after the owner has been destroyed (you attempted to create ${this.fullName})`);
}
var props = {};
(0, _owner.setOwner)(props, container.owner);
setFactoryFor(props, this);
if (options !== undefined) {
props = Object.assign({}, props, options);
}
if (true
/* DEBUG */
) {
var lazyInjections;
var validationCache = this.container.validationCache; // Ensure that all lazy injections are valid at instantiation time
if (!validationCache[this.fullName] && this.class && typeof this.class._lazyInjections === 'function') {
lazyInjections = this.class._lazyInjections();
lazyInjections = this.container.registry.normalizeInjectionsHash(lazyInjections);
this.container.registry.validateInjections(lazyInjections);
}
validationCache[this.fullName] = true;
(true && !(typeof this.class.create === 'function') && (0, _debug.assert)(`Failed to create an instance of '${this.normalizedName}'. Most likely an improperly defined class or an invalid module export.`, typeof this.class.create === 'function'));
}
return this.class.create(props);
}
}
var VALID_FULL_NAME_REGEXP = /^[^:]+:[^:]+$/;
/**
A registry used to store factory and option information keyed
by type.
A `Registry` stores the factory and option information needed by a
`Container` to instantiate and cache objects.
The API for `Registry` is still in flux and should not be considered stable.
@private
@class Registry
@since 1.11.0
*/
class Registry {
constructor(options = {}) {
this.fallback = options.fallback || null;
this.resolver = options.resolver || null;
this.registrations = (0, _utils.dictionary)(options.registrations || null);
this._localLookupCache = Object.create(null);
this._normalizeCache = (0, _utils.dictionary)(null);
this._resolveCache = (0, _utils.dictionary)(null);
this._failSet = new Set();
this._options = (0, _utils.dictionary)(null);
this._typeOptions = (0, _utils.dictionary)(null);
}
/**
A backup registry for resolving registrations when no matches can be found.
@private
@property fallback
@type Registry
*/
/**
An object that has a `resolve` method that resolves a name.
@private
@property resolver
@type Resolver
*/
/**
@private
@property registrations
@type InheritingDict
*/
/**
@private
@property _normalizeCache
@type InheritingDict
*/
/**
@private
@property _resolveCache
@type InheritingDict
*/
/**
@private
@property _options
@type InheritingDict
*/
/**
@private
@property _typeOptions
@type InheritingDict
*/
/**
Creates a container based on this registry.
@private
@method container
@param {Object} options
@return {Container} created container
*/
container(options) {
return new Container(this, options);
}
/**
Registers a factory for later injection.
Example:
```javascript
let registry = new Registry();
registry.register('model:user', Person, {singleton: false });
registry.register('fruit:favorite', Orange);
registry.register('communication:main', Email, {singleton: false});
```
@private
@method register
@param {String} fullName
@param {Function} factory
@param {Object} options
*/
register(fullName, factory, options = {}) {
(true && !(this.isValidFullName(fullName)) && (0, _debug.assert)('fullName must be a proper full name', this.isValidFullName(fullName)));
(true && !(factory !== undefined) && (0, _debug.assert)(`Attempting to register an unknown factory: '${fullName}'`, factory !== undefined));
var normalizedName = this.normalize(fullName);
(true && !(!this._resolveCache[normalizedName]) && (0, _debug.assert)(`Cannot re-register: '${fullName}', as it has already been resolved.`, !this._resolveCache[normalizedName]));
this._failSet.delete(normalizedName);
this.registrations[normalizedName] = factory;
this._options[normalizedName] = options;
}
/**
Unregister a fullName
```javascript
let registry = new Registry();
registry.register('model:user', User);
registry.resolve('model:user').create() instanceof User //=> true
registry.unregister('model:user')
registry.resolve('model:user') === undefined //=> true
```
@private
@method unregister
@param {String} fullName
*/
unregister(fullName) {
(true && !(this.isValidFullName(fullName)) && (0, _debug.assert)('fullName must be a proper full name', this.isValidFullName(fullName)));
var normalizedName = this.normalize(fullName);
this._localLookupCache = Object.create(null);
delete this.registrations[normalizedName];
delete this._resolveCache[normalizedName];
delete this._options[normalizedName];
this._failSet.delete(normalizedName);
}
/**
Given a fullName return the corresponding factory.
By default `resolve` will retrieve the factory from
the registry.
```javascript
let registry = new Registry();
registry.register('api:twitter', Twitter);
registry.resolve('api:twitter') // => Twitter
```
Optionally the registry can be provided with a custom resolver.
If provided, `resolve` will first provide the custom resolver
the opportunity to resolve the fullName, otherwise it will fallback
to the registry.
```javascript
let registry = new Registry();
registry.resolver = function(fullName) {
// lookup via the module system of choice
};
// the twitter factory is added to the module system
registry.resolve('api:twitter') // => Twitter
```
@private
@method resolve
@param {String} fullName
@param {Object} [options]
@param {String} [options.source] the fullname of the request source (used for local lookups)
@return {Function} fullName's factory
*/
resolve(fullName) {
var factory = resolve(this, this.normalize(fullName));
if (factory === undefined && this.fallback !== null) {
factory = this.fallback.resolve(...arguments);
}
return factory;
}
/**
A hook that can be used to describe how the resolver will
attempt to find the factory.
For example, the default Ember `.describe` returns the full
class name (including namespace) where Ember's resolver expects
to find the `fullName`.
@private
@method describe
@param {String} fullName
@return {string} described fullName
*/
describe(fullName) {
if (this.resolver !== null && this.resolver.lookupDescription) {
return this.resolver.lookupDescription(fullName);
} else if (this.fallback !== null) {
return this.fallback.describe(fullName);
} else {
return fullName;
}
}
/**
A hook to enable custom fullName normalization behavior
@private
@method normalizeFullName
@param {String} fullName
@return {string} normalized fullName
*/
normalizeFullName(fullName) {
if (this.resolver !== null && this.resolver.normalize) {
return this.resolver.normalize(fullName);
} else if (this.fallback !== null) {
return this.fallback.normalizeFullName(fullName);
} else {
return fullName;
}
}
/**
Normalize a fullName based on the application's conventions
@private
@method normalize
@param {String} fullName
@return {string} normalized fullName
*/
normalize(fullName) {
return this._normalizeCache[fullName] || (this._normalizeCache[fullName] = this.normalizeFullName(fullName));
}
/**
@method makeToString
@private
@param {any} factory
@param {string} fullName
@return {function} toString function
*/
makeToString(factory, fullName) {
var _a;
if (this.resolver !== null && this.resolver.makeToString) {
return this.resolver.makeToString(factory, fullName);
} else if (this.fallback !== null) {
return this.fallback.makeToString(factory, fullName);
} else {
return typeof factory === 'string' ? factory : (_a = factory.name) !== null && _a !== void 0 ? _a : '(unknown class)';
}
}
/**
Given a fullName check if the container is aware of its factory
or singleton instance.
@private
@method has
@param {String} fullName
@param {Object} [options]
@param {String} [options.source] the fullname of the request source (used for local lookups)
@return {Boolean}
*/
has(fullName) {
if (!this.isValidFullName(fullName)) {
return false;
}
return has(this, this.normalize(fullName));
}
/**
Allow registering options for all factories of a type.
```javascript
let registry = new Registry();
let container = registry.container();
// if all of type `connection` must not be singletons
registry.optionsForType('connection', { singleton: false });
registry.register('connection:twitter', TwitterConnection);
registry.register('connection:facebook', FacebookConnection);
let twitter = container.lookup('connection:twitter');
let twitter2 = container.lookup('connection:twitter');
twitter === twitter2; // => false
let facebook = container.lookup('connection:facebook');
let facebook2 = container.lookup('connection:facebook');
facebook === facebook2; // => false
```
@private
@method optionsForType
@param {String} type
@param {Object} options
*/
optionsForType(type, options) {
this._typeOptions[type] = options;
}
getOptionsForType(type) {
var optionsForType = this._typeOptions[type];
if (optionsForType === undefined && this.fallback !== null) {
optionsForType = this.fallback.getOptionsForType(type);
}
return optionsForType;
}
/**
@private
@method options
@param {String} fullName
@param {Object} options
*/
options(fullName, options) {
var normalizedName = this.normalize(fullName);
this._options[normalizedName] = options;
}
getOptions(fullName) {
var normalizedName = this.normalize(fullName);
var options = this._options[normalizedName];
if (options === undefined && this.fallback !== null) {
options = this.fallback.getOptions(fullName);
}
return options;
}
getOption(fullName, optionName) {
var options = this._options[fullName];
if (options !== undefined && options[optionName] !== undefined) {
return options[optionName];
}
var type = fullName.split(':')[0];
options = this._typeOptions[type];
if (options && options[optionName] !== undefined) {
return options[optionName];
} else if (this.fallback !== null) {
return this.fallback.getOption(fullName, optionName);
}
return undefined;
}
/**
This is deprecated in favor of explicit injection of dependencies.
Reference: https://deprecations.emberjs.com/v3.x#toc_implicit-injections
```
@private
@method injection
@param {String} factoryName
@param {String} property
@param {String} injectionName
@deprecated
*/
injection(fullName, property) {
(true && !(false) && (0, _debug.deprecate)(`As of Ember 4.0.0, owner.inject no longer injects values into resolved instances, and calling the method has been deprecated. Since this method no longer does anything, it is fully safe to remove this injection. As an alternative to this API, you can refactor to explicitly inject \`${property}\` on \`${fullName}\`, or look it up directly using the \`getOwner\` API.`, false, {
id: 'remove-owner-inject',
until: '5.0.0',
url: 'https://deprecations.emberjs.com/v4.x#toc_implicit-injections',
for: 'ember-source',
since: {
enabled: '4.0.0'
}
}));
}
/**
@private
@method knownForType
@param {String} type the type to iterate over
*/
knownForType(type) {
var localKnown = (0, _utils.dictionary)(null);
var registeredNames = Object.keys(this.registrations);
for (var index = 0; index < registeredNames.length; index++) {
var fullName = registeredNames[index];
var itemType = fullName.split(':')[0];
if (itemType === type) {
localKnown[fullName] = true;
}
}
var fallbackKnown, resolverKnown;
if (this.fallback !== null) {
fallbackKnown = this.fallback.knownForType(type);
}
if (this.resolver !== null && this.resolver.knownForType) {
resolverKnown = this.resolver.knownForType(type);
}
return Object.assign({}, fallbackKnown, localKnown, resolverKnown);
}
isValidFullName(fullName) {
return VALID_FULL_NAME_REGEXP.test(fullName);
}
}
_exports.Registry = Registry;
if (true
/* DEBUG */
) {
var proto = Registry.prototype;
proto.normalizeInjectionsHash = function (hash) {
var injections = [];
for (var key in hash) {
if (Object.prototype.hasOwnProperty.call(hash, key)) {
var {
specifier
} = hash[key];
(true && !(this.isValidFullName(specifier)) && (0, _debug.assert)(`Expected a proper full name, given '${specifier}'`, this.isValidFullName(specifier)));
injections.push({
property: key,
specifier
});
}
}
return injections;
};
proto.validateInjections = function (injections) {
if (!injections) {
return;
}
for (var i = 0; i < injections.length; i++) {
var {
specifier
} = injections[i];
(true && !(this.has(specifier)) && (0, _debug.assert)(`Attempting to inject an unknown injection: '${specifier}'`, this.has(specifier)));
}
};
}
function resolve(registry, _normalizedName) {
var normalizedName = _normalizedName;
var cached = registry._resolveCache[normalizedName];
if (cached !== undefined) {
return cached;
}
if (registry._failSet.has(normalizedName)) {
return;
}
var resolved;
if (registry.resolver) {
resolved = registry.resolver.resolve(normalizedName);
}
if (resolved === undefined) {
resolved = registry.registrations[normalizedName];
}
if (resolved === undefined) {
registry._failSet.add(normalizedName);
} else {
registry._resolveCache[normalizedName] = resolved;
}
return resolved;
}
function has(registry, fullName) {
return registry.resolve(fullName) !== undefined;
}
var privateNames = (0, _utils.dictionary)(null);
var privateSuffix = `${Math.random()}${Date.now()}`.replace('.', '');
function privatize([fullName]) {
var name = privateNames[fullName];
if (name) {
return name;
}
var [type, rawName] = fullName.split(':');
return privateNames[fullName] = (0, _utils.intern)(`${type}:${rawName}-${privateSuffix}`);
}
/*
Public API for the container is still in flux.
The public API, specified on the application namespace should be considered the stable API.
// @module container
@private
*/
});
define("@ember/-internals/environment/index", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.getLookup = getLookup;
_exports.setLookup = setLookup;
_exports.getENV = getENV;
_exports.ENV = _exports.context = _exports.global = void 0;
// from lodash to catch fake globals
function checkGlobal(value) {
return value && value.Object === Object ? value : undefined;
} // element ids can ruin global miss checks
function checkElementIdShadowing(value) {
return value && value.nodeType === undefined ? value : undefined;
} // export real global
var global$1 = checkGlobal(checkElementIdShadowing(typeof global === 'object' && global)) || checkGlobal(typeof self === 'object' && self) || checkGlobal(typeof window === 'object' && window) || typeof mainContext !== 'undefined' && mainContext || // set before strict mode in Ember loader/wrapper
new Function('return this')(); // eval outside of strict mode
_exports.global = global$1;
var context = function (global, Ember) {
return Ember === undefined ? {
imports: global,
exports: global,
lookup: global
} : {
// import jQuery
imports: Ember.imports || global,
// export Ember
exports: Ember.exports || global,
// search for Namespaces
lookup: Ember.lookup || global
};
}(global$1, global$1.Ember);
_exports.context = context;
function getLookup() {
return context.lookup;
}
function setLookup(value) {
context.lookup = value;
}
/**
The hash of environment variables used to control various configuration
settings. To specify your own or override default settings, add the
desired properties to a global hash named `EmberENV` (or `ENV` for
backwards compatibility with earlier versions of Ember). The `EmberENV`
hash must be created before loading Ember.
@class EmberENV
@type Object
@public
*/
var ENV = {
ENABLE_OPTIONAL_FEATURES: false,
/**
Determines whether Ember should add to `Array`
native object prototypes, a few extra methods in order to provide a more
friendly API.
We generally recommend leaving this option set to true however, if you need
to turn it off, you can add the configuration property
`EXTEND_PROTOTYPES` to `EmberENV` and set it to `false`.
Note, when disabled (the default configuration for Ember Addons), you will
instead have to access all methods and functions from the Ember
namespace.
@property EXTEND_PROTOTYPES
@type Boolean
@default true
@for EmberENV
@public
*/
EXTEND_PROTOTYPES: {
Array: true
},
/**
The `LOG_STACKTRACE_ON_DEPRECATION` property, when true, tells Ember to log
a full stack trace during deprecation warnings.
@property LOG_STACKTRACE_ON_DEPRECATION
@type Boolean
@default true
@for EmberENV
@public
*/
LOG_STACKTRACE_ON_DEPRECATION: true,
/**
The `LOG_VERSION` property, when true, tells Ember to log versions of all
dependent libraries in use.
@property LOG_VERSION
@type Boolean
@default true
@for EmberENV
@public
*/
LOG_VERSION: true,
RAISE_ON_DEPRECATION: false,
STRUCTURED_PROFILE: false,
/**
Whether to insert a `<div class="ember-view" />` wrapper around the
application template. See RFC #280.
This is not intended to be set directly, as the implementation may change in
the future. Use `@ember/optional-features` instead.
@property _APPLICATION_TEMPLATE_WRAPPER
@for EmberENV
@type Boolean
@default true
@private
*/
_APPLICATION_TEMPLATE_WRAPPER: true,
/**
Whether to use Glimmer Component semantics (as opposed to the classic "Curly"
components semantics) for template-only components. See RFC #278.
This is not intended to be set directly, as the implementation may change in
the future. Use `@ember/optional-features` instead.
@property _TEMPLATE_ONLY_GLIMMER_COMPONENTS
@for EmberENV
@type Boolean
@default false
@private
*/
_TEMPLATE_ONLY_GLIMMER_COMPONENTS: false,
/**
Whether to perform extra bookkeeping needed to make the `captureRenderTree`
API work.
This has to be set before the ember JavaScript code is evaluated. This is
usually done by setting `window.EmberENV = { _DEBUG_RENDER_TREE: true };`
before the "vendor" `<script>` tag in `index.html`.
Setting the flag after Ember is already loaded will not work correctly. It
may appear to work somewhat, but fundamentally broken.
This is not intended to be set directly. Ember Inspector will enable the
flag on behalf of the user as needed.
This flag is always on in development mode.
The flag is off by default in production mode, due to the cost associated
with the the bookkeeping work.
The expected flow is that Ember Inspector will ask the user to refresh the
page after enabling the feature. It could also offer a feature where the
user add some domains to the "always on" list. In either case, Ember
Inspector will inject the code on the page to set the flag if needed.
@property _DEBUG_RENDER_TREE
@for EmberENV
@type Boolean
@default false
@private
*/
_DEBUG_RENDER_TREE: true
/* DEBUG */
,
/**
Whether the app defaults to using async observers.
This is not intended to be set directly, as the implementation may change in
the future. Use `@ember/optional-features` instead.
@property _DEFAULT_ASYNC_OBSERVERS
@for EmberENV
@type Boolean
@default false
@private
*/
_DEFAULT_ASYNC_OBSERVERS: false,
/**
Controls the maximum number of scheduled rerenders without "settling". In general,
applications should not need to modify this environment variable, but please
open an issue so that we can determine if a better default value is needed.
@property _RERENDER_LOOP_LIMIT
@for EmberENV
@type number
@default 1000
@private
*/
_RERENDER_LOOP_LIMIT: 1000,
EMBER_LOAD_HOOKS: {},
FEATURES: {}
};
_exports.ENV = ENV;
(EmberENV => {
if (typeof EmberENV !== 'object' || EmberENV === null) return;
for (var flag in EmberENV) {
if (!Object.prototype.hasOwnProperty.call(EmberENV, flag) || flag === 'EXTEND_PROTOTYPES' || flag === 'EMBER_LOAD_HOOKS') continue;
var defaultValue = ENV[flag];
if (defaultValue === true) {
ENV[flag] = EmberENV[flag] !== false;
} else if (defaultValue === false) {
ENV[flag] = EmberENV[flag] === true;
}
}
var {
EXTEND_PROTOTYPES
} = EmberENV;
if (EXTEND_PROTOTYPES !== undefined) {
if (typeof EXTEND_PROTOTYPES === 'object' && EXTEND_PROTOTYPES !== null) {
ENV.EXTEND_PROTOTYPES.Array = EXTEND_PROTOTYPES.Array !== false;
} else {
ENV.EXTEND_PROTOTYPES.Array = EXTEND_PROTOTYPES !== false;
}
} // TODO this does not seem to be used by anything,
// can we remove it? do we need to deprecate it?
var {
EMBER_LOAD_HOOKS
} = EmberENV;
if (typeof EMBER_LOAD_HOOKS === 'object' && EMBER_LOAD_HOOKS !== null) {
for (var hookName in EMBER_LOAD_HOOKS) {
if (!Object.prototype.hasOwnProperty.call(EMBER_LOAD_HOOKS, hookName)) continue;
var hooks = EMBER_LOAD_HOOKS[hookName];
if (Array.isArray(hooks)) {
ENV.EMBER_LOAD_HOOKS[hookName] = hooks.filter(hook => typeof hook === 'function');
}
}
}
var {
FEATURES
} = EmberENV;
if (typeof FEATURES === 'object' && FEATURES !== null) {
for (var feature in FEATURES) {
if (!Object.prototype.hasOwnProperty.call(FEATURES, feature)) continue;
ENV.FEATURES[feature] = FEATURES[feature] === true;
}
}
if (true
/* DEBUG */
) {
ENV._DEBUG_RENDER_TREE = true;
}
})(global$1.EmberENV);
function getENV() {
return ENV;
}
});
define("@ember/-internals/error-handling/index", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.getOnerror = getOnerror;
_exports.setOnerror = setOnerror;
_exports.getDispatchOverride = getDispatchOverride;
_exports.setDispatchOverride = setDispatchOverride;
_exports.onErrorTarget = void 0;
var onerror;
var onErrorTarget = {
get onerror() {
return onerror;
}
}; // Ember.onerror getter
_exports.onErrorTarget = onErrorTarget;
function getOnerror() {
return onerror;
} // Ember.onerror setter
function setOnerror(handler) {
onerror = handler;
}
var dispatchOverride; // allows testing adapter to override dispatch
function getDispatchOverride() {
return dispatchOverride;
}
function setDispatchOverride(handler) {
dispatchOverride = handler;
}
});
define("@ember/-internals/extension-support/index", ["exports", "@ember/-internals/extension-support/lib/data_adapter", "@ember/-internals/extension-support/lib/container_debug_adapter"], function (_exports, _data_adapter, _container_debug_adapter) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "DataAdapter", {
enumerable: true,
get: function () {
return _data_adapter.default;
}
});
Object.defineProperty(_exports, "ContainerDebugAdapter", {
enumerable: true,
get: function () {
return _container_debug_adapter.default;
}
});
});
define("@ember/-internals/extension-support/lib/container_debug_adapter", ["exports", "@ember/string", "@ember/-internals/runtime", "@ember/-internals/owner"], function (_exports, _string, _runtime, _owner) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module @ember/debug
*/
/**
The `ContainerDebugAdapter` helps the container and resolver interface
with tools that debug Ember such as the
[Ember Inspector](https://github.com/emberjs/ember-inspector)
for Chrome and Firefox.
This class can be extended by a custom resolver implementer
to override some of the methods with library-specific code.
The methods likely to be overridden are:
* `canCatalogEntriesByType`
* `catalogEntriesByType`
The adapter will need to be registered
in the application's container as `container-debug-adapter:main`.
Example:
```javascript
Application.initializer({
name: "containerDebugAdapter",
initialize(application) {
application.register('container-debug-adapter:main', require('app/container-debug-adapter'));
}
});
```
@class ContainerDebugAdapter
@extends EmberObject
@since 1.5.0
@public
*/
var _default = _runtime.Object.extend({
init() {
this._super(...arguments);
this.resolver = (0, _owner.getOwner)(this).lookup('resolver-for-debugging:main');
},
/**
The resolver instance of the application
being debugged. This property will be injected
on creation.
@property resolver
@default null
@public
*/
resolver: null,
/**
Returns true if it is possible to catalog a list of available
classes in the resolver for a given type.
@method canCatalogEntriesByType
@param {String} type The type. e.g. "model", "controller", "route".
@return {boolean} whether a list is available for this type.
@public
*/
canCatalogEntriesByType(type) {
if (type === 'model' || type === 'template') {
return false;
}
return true;
},
/**
Returns the available classes a given type.
@method catalogEntriesByType
@param {String} type The type. e.g. "model", "controller", "route".
@return {Array} An array of strings.
@public
*/
catalogEntriesByType(type) {
var namespaces = (0, _runtime.A)(_runtime.Namespace.NAMESPACES);
var types = (0, _runtime.A)();
var typeSuffixRegex = new RegExp(`${(0, _string.classify)(type)}$`);
namespaces.forEach(namespace => {
for (var key in namespace) {
if (!Object.prototype.hasOwnProperty.call(namespace, key)) {
continue;
}
if (typeSuffixRegex.test(key)) {
var klass = namespace[key];
if ((0, _runtime.typeOf)(klass) === 'class') {
types.push((0, _string.dasherize)(key.replace(typeSuffixRegex, '')));
}
}
}
});
return types;
}
});
_exports.default = _default;
});
define("@ember/-internals/extension-support/lib/data_adapter", ["exports", "@ember/-internals/owner", "@ember/runloop", "@ember/-internals/metal", "@ember/string", "@ember/-internals/runtime", "@glimmer/validator"], function (_exports, _owner, _runloop, _metal, _string, _runtime, _validator) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
function iterate(arr, fn) {
if (Symbol.iterator in arr) {
for (var item of arr) {
fn(item);
}
} else {
arr.forEach(fn);
}
}
class RecordsWatcher {
getCacheForItem(record) {
var recordCache = this.recordCaches.get(record);
if (!recordCache) {
var hasBeenAdded = false;
recordCache = (0, _validator.createCache)(() => {
if (!hasBeenAdded) {
this.added.push(this.wrapRecord(record));
hasBeenAdded = true;
} else {
this.updated.push(this.wrapRecord(record));
}
});
this.recordCaches.set(record, recordCache);
}
return recordCache;
}
constructor(records, recordsAdded, recordsUpdated, recordsRemoved, wrapRecord, release) {
this.recordCaches = new Map();
this.added = [];
this.updated = [];
this.removed = [];
this.release = release;
this.wrapRecord = wrapRecord;
this.recordArrayCache = (0, _validator.createCache)(() => {
var seen = new Set(); // Track `[]` for legacy support
(0, _validator.consumeTag)((0, _validator.tagFor)(records, '[]'));
iterate(records, record => {
(0, _validator.getValue)(this.getCacheForItem(record));
seen.add(record);
}); // Untrack this operation because these records are being removed, they
// should not be polled again in the future
(0, _validator.untrack)(() => {
this.recordCaches.forEach((cache, record) => {
if (!seen.has(record)) {
this.removed.push(wrapRecord(record));
this.recordCaches.delete(record);
}
});
});
if (this.added.length > 0) {
recordsAdded(this.added);
this.added = [];
}
if (this.updated.length > 0) {
recordsUpdated(this.updated);
this.updated = [];
}
if (this.removed.length > 0) {
recordsRemoved(this.removed);
this.removed = [];
}
});
}
revalidate() {
(0, _validator.getValue)(this.recordArrayCache);
}
}
class TypeWatcher {
constructor(records, onChange, release) {
var hasBeenAccessed = false;
this.cache = (0, _validator.createCache)(() => {
// Empty iteration, we're doing this just
// to track changes to the records array
iterate(records, () => {}); // Also track `[]` for legacy support
(0, _validator.consumeTag)((0, _validator.tagFor)(records, '[]'));
if (hasBeenAccessed === true) {
onChange();
} else {
hasBeenAccessed = true;
}
});
this.release = release;
}
revalidate() {
(0, _validator.getValue)(this.cache);
}
}
/**
@module @ember/debug
*/
/**
The `DataAdapter` helps a data persistence library
interface with tools that debug Ember such
as the [Ember Inspector](https://github.com/emberjs/ember-inspector)
for Chrome and Firefox.
This class will be extended by a persistence library
which will override some of the methods with
library-specific code.
The methods likely to be overridden are:
* `getFilters`
* `detect`
* `columnsForType`
* `getRecords`
* `getRecordColumnValues`
* `getRecordKeywords`
* `getRecordFilterValues`
* `getRecordColor`
The adapter will need to be registered
in the application's container as `dataAdapter:main`.
Example:
```javascript
Application.initializer({
name: "data-adapter",
initialize: function(application) {
application.register('data-adapter:main', DS.DataAdapter);
}
});
```
@class DataAdapter
@extends EmberObject
@public
*/
var _default = _runtime.Object.extend({
init() {
this._super(...arguments);
this.containerDebugAdapter = (0, _owner.getOwner)(this).lookup('container-debug-adapter:main');
this.releaseMethods = (0, _runtime.A)();
this.recordsWatchers = new Map();
this.typeWatchers = new Map();
this.flushWatchers = null;
},
/**
The container-debug-adapter which is used
to list all models.
@property containerDebugAdapter
@default undefined
@since 1.5.0
@public
**/
/**
The number of attributes to send
as columns. (Enough to make the record
identifiable).
@private
@property attributeLimit
@default 3
@since 1.3.0
*/
attributeLimit: 3,
/**
Ember Data > v1.0.0-beta.18
requires string model names to be passed
around instead of the actual factories.
This is a stamp for the Ember Inspector
to differentiate between the versions
to be able to support older versions too.
@public
@property acceptsModelName
*/
acceptsModelName: true,
/**
Map from records arrays to RecordsWatcher instances
@private
@property recordsWatchers
@since 3.26.0
*/
/**
Map from records arrays to TypeWatcher instances
@private
@property typeWatchers
@since 3.26.0
*/
/**
Callback that is currently scheduled on backburner end to flush and check
all active watchers.
@private
@property flushWatchers
@since 3.26.0
*/
/**
Stores all methods that clear observers.
These methods will be called on destruction.
@private
@property releaseMethods
@since 1.3.0
*/
/**
Specifies how records can be filtered.
Records returned will need to have a `filterValues`
property with a key for every name in the returned array.
@public
@method getFilters
@return {Array} List of objects defining filters.
The object should have a `name` and `desc` property.
*/
getFilters() {
return (0, _runtime.A)();
},
/**
Fetch the model types and observe them for changes.
@public
@method watchModelTypes
@param {Function} typesAdded Callback to call to add types.
Takes an array of objects containing wrapped types (returned from `wrapModelType`).
@param {Function} typesUpdated Callback to call when a type has changed.
Takes an array of objects containing wrapped types.
@return {Function} Method to call to remove all observers
*/
watchModelTypes(typesAdded, typesUpdated) {
var modelTypes = this.getModelTypes();
var releaseMethods = (0, _runtime.A)();
var typesToSend;
typesToSend = modelTypes.map(type => {
var klass = type.klass;
var wrapped = this.wrapModelType(klass, type.name);
releaseMethods.push(this.observeModelType(type.name, typesUpdated));
return wrapped;
});
typesAdded(typesToSend);
var release = () => {
releaseMethods.forEach(fn => fn());
this.releaseMethods.removeObject(release);
};
this.releaseMethods.pushObject(release);
return release;
},
_nameToClass(type) {
if (typeof type === 'string') {
var owner = (0, _owner.getOwner)(this);
var Factory = owner.factoryFor(`model:${type}`);
type = Factory && Factory.class;
}
return type;
},
/**
Fetch the records of a given type and observe them for changes.
@public
@method watchRecords
@param {String} modelName The model name.
@param {Function} recordsAdded Callback to call to add records.
Takes an array of objects containing wrapped records.
The object should have the following properties:
columnValues: {Object} The key and value of a table cell.
object: {Object} The actual record object.
@param {Function} recordsUpdated Callback to call when a record has changed.
Takes an array of objects containing wrapped records.
@param {Function} recordsRemoved Callback to call when a record has removed.
Takes an array of objects containing wrapped records.
@return {Function} Method to call to remove all observers.
*/
watchRecords(modelName, recordsAdded, recordsUpdated, recordsRemoved) {
var klass = this._nameToClass(modelName);
var records = this.getRecords(klass, modelName);
var {
recordsWatchers
} = this;
var recordsWatcher = recordsWatchers.get(records);
if (!recordsWatcher) {
recordsWatcher = new RecordsWatcher(records, recordsAdded, recordsUpdated, recordsRemoved, record => this.wrapRecord(record), () => {
recordsWatchers.delete(records);
this.updateFlushWatchers();
});
recordsWatchers.set(records, recordsWatcher);
this.updateFlushWatchers();
recordsWatcher.revalidate();
}
return recordsWatcher.release;
},
updateFlushWatchers() {
if (this.flushWatchers === null) {
if (this.typeWatchers.size > 0 || this.recordsWatchers.size > 0) {
this.flushWatchers = () => {
this.typeWatchers.forEach(watcher => watcher.revalidate());
this.recordsWatchers.forEach(watcher => watcher.revalidate());
};
_runloop._backburner.on('end', this.flushWatchers);
}
} else if (this.typeWatchers.size === 0 && this.recordsWatchers.size === 0) {
_runloop._backburner.off('end', this.flushWatchers);
this.flushWatchers = null;
}
},
/**
Clear all observers before destruction
@private
@method willDestroy
*/
willDestroy() {
this._super(...arguments);
this.typeWatchers.forEach(watcher => watcher.release());
this.recordsWatchers.forEach(watcher => watcher.release());
this.releaseMethods.forEach(fn => fn());
if (this.flushWatchers) {
_runloop._backburner.off('end', this.flushWatchers);
}
},
/**
Detect whether a class is a model.
Test that against the model class
of your persistence library.
@public
@method detect
@return boolean Whether the class is a model class or not.
*/
detect() {
return false;
},
/**
Get the columns for a given model type.
@public
@method columnsForType
@return {Array} An array of columns of the following format:
name: {String} The name of the column.
desc: {String} Humanized description (what would show in a table column name).
*/
columnsForType() {
return (0, _runtime.A)();
},
/**
Adds observers to a model type class.
@private
@method observeModelType
@param {String} modelName The model type name.
@param {Function} typesUpdated Called when a type is modified.
@return {Function} The function to call to remove observers.
*/
observeModelType(modelName, typesUpdated) {
var klass = this._nameToClass(modelName);
var records = this.getRecords(klass, modelName);
var onChange = () => {
typesUpdated([this.wrapModelType(klass, modelName)]);
};
var {
typeWatchers
} = this;
var typeWatcher = typeWatchers.get(records);
if (!typeWatcher) {
typeWatcher = new TypeWatcher(records, onChange, () => {
typeWatchers.delete(records);
this.updateFlushWatchers();
});
typeWatchers.set(records, typeWatcher);
this.updateFlushWatchers();
typeWatcher.revalidate();
}
return typeWatcher.release;
},
/**
Wraps a given model type and observes changes to it.
@private
@method wrapModelType
@param {Class} klass A model class.
@param {String} modelName Name of the class.
@return {Object} Contains the wrapped type and the function to remove observers
Format:
type: {Object} The wrapped type.
The wrapped type has the following format:
name: {String} The name of the type.
count: {Integer} The number of records available.
columns: {Columns} An array of columns to describe the record.
object: {Class} The actual Model type class.
release: {Function} The function to remove observers.
*/
wrapModelType(klass, name) {
var records = this.getRecords(klass, name);
var typeToSend;
typeToSend = {
name,
count: (0, _metal.get)(records, 'length'),
columns: this.columnsForType(klass),
object: klass
};
return typeToSend;
},
/**
Fetches all models defined in the application.
@private
@method getModelTypes
@return {Array} Array of model types.
*/
getModelTypes() {
var containerDebugAdapter = this.get('containerDebugAdapter');
var types;
if (containerDebugAdapter.canCatalogEntriesByType('model')) {
types = containerDebugAdapter.catalogEntriesByType('model');
} else {
types = this._getObjectsOnNamespaces();
} // New adapters return strings instead of classes.
types = (0, _runtime.A)(types).map(name => {
return {
klass: this._nameToClass(name),
name
};
});
types = (0, _runtime.A)(types).filter(type => this.detect(type.klass));
return (0, _runtime.A)(types);
},
/**
Loops over all namespaces and all objects
attached to them.
@private
@method _getObjectsOnNamespaces
@return {Array} Array of model type strings.
*/
_getObjectsOnNamespaces() {
var namespaces = (0, _runtime.A)(_runtime.Namespace.NAMESPACES);
var types = (0, _runtime.A)();
namespaces.forEach(namespace => {
for (var key in namespace) {
if (!Object.prototype.hasOwnProperty.call(namespace, key)) {
continue;
} // Even though we will filter again in `getModelTypes`,
// we should not call `lookupFactory` on non-models
if (!this.detect(namespace[key])) {
continue;
}
var name = (0, _string.dasherize)(key);
types.push(name);
}
});
return types;
},
/**
Fetches all loaded records for a given type.
@public
@method getRecords
@return {Array} An array of records.
This array will be observed for changes,
so it should update when new records are added/removed.
*/
getRecords() {
return (0, _runtime.A)();
},
/**
Wraps a record and observers changes to it.
@private
@method wrapRecord
@param {Object} record The record instance.
@return {Object} The wrapped record. Format:
columnValues: {Array}
searchKeywords: {Array}
*/
wrapRecord(record) {
var recordToSend = {
object: record
};
recordToSend.columnValues = this.getRecordColumnValues(record);
recordToSend.searchKeywords = this.getRecordKeywords(record);
recordToSend.filterValues = this.getRecordFilterValues(record);
recordToSend.color = this.getRecordColor(record);
return recordToSend;
},
/**
Gets the values for each column.
@public
@method getRecordColumnValues
@return {Object} Keys should match column names defined
by the model type.
*/
getRecordColumnValues() {
return {};
},
/**
Returns keywords to match when searching records.
@public
@method getRecordKeywords
@return {Array} Relevant keywords for search.
*/
getRecordKeywords() {
return (0, _runtime.A)();
},
/**
Returns the values of filters defined by `getFilters`.
@public
@method getRecordFilterValues
@param {Object} record The record instance.
@return {Object} The filter values.
*/
getRecordFilterValues() {
return {};
},
/**
Each record can have a color that represents its state.
@public
@method getRecordColor
@param {Object} record The record instance
@return {String} The records color.
Possible options: black, red, blue, green.
*/
getRecordColor() {
return null;
}
});
_exports.default = _default;
});
define("@ember/-internals/glimmer/index", ["exports", "@glimmer/opcode-compiler", "@ember/-internals/owner", "@ember/-internals/utils", "@ember/debug", "@glimmer/manager", "@glimmer/reference", "@glimmer/validator", "@ember/-internals/metal", "@ember/object", "@ember/-internals/browser-environment", "@ember/-internals/views", "@ember/engine", "@ember/instrumentation", "@ember/service", "@ember/string", "@glimmer/destroyable", "@ember/runloop", "@glimmer/util", "@glimmer/runtime", "@ember/-internals/runtime", "@ember/-internals/environment", "@ember/-internals/container", "@glimmer/node", "@ember/-internals/glimmer", "@glimmer/global-context", "@ember/-internals/routing", "@glimmer/program", "rsvp"], function (_exports, _opcodeCompiler, _owner2, _utils, _debug, _manager2, _reference, _validator, _metal, _object, _browserEnvironment, _views, _engine, _instrumentation, _service, _string, _destroyable, _runloop, _util, _runtime, _runtime2, _environment2, _container, _node, _glimmer, _globalContext, _routing2, _program, _rsvp) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.helper = helper;
_exports.escapeExpression = escapeExpression;
_exports.htmlSafe = htmlSafe;
_exports.isHTMLSafe = isHTMLSafe$1;
_exports._resetRenderers = _resetRenderers;
_exports.renderSettled = renderSettled;
_exports.getTemplate = getTemplate;
_exports.setTemplate = setTemplate;
_exports.hasTemplate = hasTemplate;
_exports.getTemplates = getTemplates;
_exports.setTemplates = setTemplates;
_exports.setupEngineRegistry = setupEngineRegistry;
_exports.setupApplicationRegistry = setupApplicationRegistry;
_exports.setComponentManager = setComponentManager$1;
Object.defineProperty(_exports, "template", {
enumerable: true,
get: function () {
return _opcodeCompiler.templateFactory;
}
});
Object.defineProperty(_exports, "templateCacheCounters", {
enumerable: true,
get: function () {
return _opcodeCompiler.templateCacheCounters;
}
});
Object.defineProperty(_exports, "DOMChanges", {
enumerable: true,
get: function () {
return _runtime.DOMChanges;
}
});
Object.defineProperty(_exports, "DOMTreeConstruction", {
enumerable: true,
get: function () {
return _runtime.DOMTreeConstruction;
}
});
Object.defineProperty(_exports, "isSerializationFirstNode", {
enumerable: true,
get: function () {
return _runtime.isSerializationFirstNode;
}
});
Object.defineProperty(_exports, "NodeDOMTreeConstruction", {
enumerable: true,
get: function () {
return _node.NodeDOMTreeConstruction;
}
});
_exports.modifierCapabilities = _exports.componentCapabilities = _exports.OutletView = _exports.Renderer = _exports.SafeString = _exports.Helper = _exports.Component = _exports.Textarea = _exports.LinkTo = _exports.Input = _exports.RootTemplate = void 0;
var RootTemplate = (0, _opcodeCompiler.templateFactory)({
"id": "9BtKrod8",
"block": "[[[46,[30,0],null,null,null]],[],false,[\"component\"]]",
"moduleName": "packages/@ember/-internals/glimmer/lib/templates/root.hbs",
"isStrictMode": false
});
_exports.RootTemplate = RootTemplate;
var InputTemplate = (0, _opcodeCompiler.templateFactory)({
"id": "OGSIkgXP",
"block": "[[[11,\"input\"],[16,1,[30,0,[\"id\"]]],[16,0,[30,0,[\"class\"]]],[17,1],[16,4,[30,0,[\"type\"]]],[16,\"checked\",[30,0,[\"checked\"]]],[16,2,[30,0,[\"value\"]]],[4,[38,0],[\"change\",[30,0,[\"change\"]]],null],[4,[38,0],[\"input\",[30,0,[\"input\"]]],null],[4,[38,0],[\"keyup\",[30,0,[\"keyUp\"]]],null],[4,[38,0],[\"paste\",[30,0,[\"valueDidChange\"]]],null],[4,[38,0],[\"cut\",[30,0,[\"valueDidChange\"]]],null],[12],[13]],[\"&attrs\"],false,[\"on\"]]",
"moduleName": "packages/@ember/-internals/glimmer/lib/templates/input.hbs",
"isStrictMode": false
});
function NOOP() {}
class InternalComponent {
constructor(owner, args, caller) {
this.owner = owner;
this.args = args;
this.caller = caller;
(0, _owner2.setOwner)(this, owner);
} // Override this
static toString() {
return 'internal component';
}
/**
* The default HTML id attribute. We don't really _need_ one, this is just
* added for compatibility as it's hard to tell if people rely on it being
* present, and it doens't really hurt.
*
* However, don't rely on this internally, like passing it to `getElementId`.
* This can be (and often is) overriden by passing an `id` attribute on the
* invocation, which shadows this default id via `...attributes`.
*/
get id() {
return (0, _utils.guidFor)(this);
}
/**
* The default HTML class attribute. Similar to the above, we don't _need_
* them, they are just added for compatibility as it's similarly hard to tell
* if people rely on it in their CSS etc, and it doens't really hurt.
*/
get class() {
return 'ember-view';
}
validateArguments() {
for (var name of Object.keys(this.args.named)) {
if (!this.isSupportedArgument(name)) {
this.onUnsupportedArgument(name);
}
}
}
named(name) {
var ref = this.args.named[name];
return ref ? (0, _reference.valueForRef)(ref) : undefined;
}
positional(index) {
var ref = this.args.positional[index];
return ref ? (0, _reference.valueForRef)(ref) : undefined;
}
listenerFor(name) {
var listener = this.named(name);
if (listener) {
(true && !(typeof listener === 'function') && (0, _debug.assert)(`The \`@${name}\` argument to the <${this.constructor}> component must be a function`, typeof listener === 'function'));
return listener;
} else {
return NOOP;
}
} // eslint-disable-next-line @typescript-eslint/no-unused-vars
isSupportedArgument(_name) {
return false;
} // eslint-disable-next-line @typescript-eslint/no-unused-vars
onUnsupportedArgument(_name) {}
toString() {
return `<${this.constructor}:${(0, _utils.guidFor)(this)}>`;
}
}
var OPAQUE_CONSTRUCTOR_MAP = new WeakMap();
function opaquify(constructor, template) {
var _opaque = {
// Factory interface
create() {
throw (0, _debug.assert)('Use constructor instead of create');
},
toString() {
return constructor.toString();
}
};
var opaque = _opaque;
OPAQUE_CONSTRUCTOR_MAP.set(opaque, constructor);
(0, _manager2.setInternalComponentManager)(INTERNAL_COMPONENT_MANAGER, opaque);
(0, _manager2.setComponentTemplate)(template, opaque);
return opaque;
}
function deopaquify(opaque) {
var constructor = OPAQUE_CONSTRUCTOR_MAP.get(opaque);
(true && !(constructor) && (0, _debug.assert)(`[BUG] Invalid internal component constructor: ${opaque}`, constructor));
return constructor;
}
var CAPABILITIES = {
dynamicLayout: false,
dynamicTag: false,
prepareArgs: false,
createArgs: true,
attributeHook: false,
elementHook: false,
createCaller: true,
dynamicScope: false,
updateHook: false,
createInstance: true,
wrapped: false,
willDestroy: false,
hasSubOwner: false
};
class InternalManager {
getCapabilities() {
return CAPABILITIES;
}
create(owner, definition, args, _env, _dynamicScope, caller) {
(true && !((0, _reference.isConstRef)(caller)) && (0, _debug.assert)('caller must be const', (0, _reference.isConstRef)(caller)));
var ComponentClass = deopaquify(definition);
var instance = new ComponentClass(owner, args.capture(), (0, _reference.valueForRef)(caller));
(0, _validator.untrack)(instance['validateArguments'].bind(instance));
return instance;
}
didCreate() {}
didUpdate() {}
didRenderLayout() {}
didUpdateLayout() {}
getDebugName(definition) {
return definition.toString();
}
getSelf(instance) {
return (0, _reference.createConstRef)(instance, 'this');
}
getDestroyable(instance) {
return instance;
}
}
var INTERNAL_COMPONENT_MANAGER = new InternalManager();
var __decorate = undefined && undefined.__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 UNINITIALIZED = Object.freeze({});
function elementForEvent(event) {
(true && !(event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) && (0, _debug.assert)('[BUG] event target must be an <input> or <textarea> element', event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement));
return event.target;
}
function valueForEvent(event) {
return elementForEvent(event).value;
}
function devirtualize(callback) {
return event => callback(valueForEvent(event), event);
}
function valueFrom(reference) {
if (reference === undefined) {
return new LocalValue(undefined);
} else if ((0, _reference.isConstRef)(reference)) {
return new LocalValue((0, _reference.valueForRef)(reference));
} else if ((0, _reference.isUpdatableRef)(reference)) {
return new UpstreamValue(reference);
} else {
return new ForkedValue(reference);
}
}
class LocalValue {
constructor(value) {
this.value = value;
}
get() {
return this.value;
}
set(value) {
this.value = value;
}
}
__decorate([_metal.tracked], LocalValue.prototype, "value", void 0);
class UpstreamValue {
constructor(reference) {
this.reference = reference;
}
get() {
return (0, _reference.valueForRef)(this.reference);
}
set(value) {
(0, _reference.updateRef)(this.reference, value);
}
}
class ForkedValue {
constructor(reference) {
this.lastUpstreamValue = UNINITIALIZED;
this.upstream = new UpstreamValue(reference);
}
get() {
var upstreamValue = this.upstream.get();
if (upstreamValue !== this.lastUpstreamValue) {
this.lastUpstreamValue = upstreamValue;
this.local = new LocalValue(upstreamValue);
}
(true && !(this.local) && (0, _debug.assert)('[BUG] this.local must have been initialized at this point', this.local));
return this.local.get();
}
set(value) {
(true && !(this.local) && (0, _debug.assert)('[BUG] this.local must have been initialized at this point', this.local));
this.local.set(value);
}
}
class AbstractInput extends InternalComponent {
constructor() {
super(...arguments);
this._value = valueFrom(this.args.named.value);
}
validateArguments() {
(true && !(this.args.positional.length === 0) && (0, _debug.assert)(`The ${this.constructor} component does not take any positional arguments`, this.args.positional.length === 0));
super.validateArguments();
}
get value() {
return this._value.get();
}
set value(value) {
this._value.set(value);
}
valueDidChange(event) {
this.value = valueForEvent(event);
}
/**
* The `change` and `input` actions need to be overridden in the `Input`
* subclass. Unfortunately, some ember-source builds currently uses babel
* loose mode to transpile its classes. Having the `@action` decorator on the
* super class creates a getter on the prototype, and when the subclass
* overrides the method, the loose mode transpilation would emit something
* like `Subclass.prototype['change'] = function change() { ... }`, which
* fails because `prototype['change']` is getter-only/readonly. The correct
* solution is to use `Object.defineProperty(prototype, 'change', ...)` but
* that requires disabling loose mode. For now, the workaround is to add the
* decorator only on the subclass. This is more of a configuration issue on
* our own builds and doesn't really affect apps.
*/
/* @action */
change(event) {
this.valueDidChange(event);
}
/* @action */
input(event) {
this.valueDidChange(event);
}
keyUp(event) {
switch (event.key) {
case 'Enter':
this.listenerFor('enter')(event);
this.listenerFor('insert-newline')(event);
break;
case 'Escape':
this.listenerFor('escape-press')(event);
break;
}
}
listenerFor(name) {
var listener = super.listenerFor(name);
if (this.isVirtualEventListener(name, listener)) {
return devirtualize(listener);
} else {
return listener;
}
}
isVirtualEventListener(name, _listener) {
var virtualEvents = ['enter', 'insert-newline', 'escape-press'];
return virtualEvents.indexOf(name) !== -1;
}
}
__decorate([_object.action], AbstractInput.prototype, "valueDidChange", null);
__decorate([_object.action], AbstractInput.prototype, "keyUp", null);
var __decorate$1 = undefined && undefined.__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 isValidInputType;
if (_browserEnvironment.hasDOM) {
var INPUT_TYPES = Object.create(null);
var INPUT_ELEMENT = document.createElement('input');
INPUT_TYPES[''] = false;
INPUT_TYPES['text'] = true;
INPUT_TYPES['checkbox'] = true;
isValidInputType = type => {
var isValid = INPUT_TYPES[type];
if (isValid === undefined) {
try {
INPUT_ELEMENT.type = type;
isValid = INPUT_ELEMENT.type === type;
} catch (e) {
isValid = false;
} finally {
INPUT_ELEMENT.type = 'text';
}
INPUT_TYPES[type] = isValid;
}
return isValid;
};
} else {
isValidInputType = type => type !== '';
}
/**
See [Ember.Templates.components.Input](/ember/release/classes/Ember.Templates.components/methods/Input?anchor=Input).
@method input
@for Ember.Templates.helpers
@param {Hash} options
@public
*/
/**
An opaque interface which can be imported and used in strict-mode
templates to call <Input>.
See [Ember.Templates.components.Input](/ember/release/classes/Ember.Templates.components/methods/Input?anchor=Input).
@for @ember/component
@method Input
@see {Ember.Templates.components.Input}
@public
**/
/**
The `Input` component lets you create an HTML `<input>` element.
```handlebars
<Input @value="987" />
```
creates an `<input>` element with `type="text"` and value set to 987.
### Text field
If no `type` argument is specified, a default of type 'text' is used.
```handlebars
Search:
<Input @value={{this.searchWord}} />
```
In this example, the initial value in the `<input>` will be set to the value of
`this.searchWord`. If the user changes the text, the value of `this.searchWord` will also be
updated.
### Actions
The `Input` component takes a number of arguments with callbacks that are invoked in response to
user events.
* `enter`
* `insert-newline`
* `escape-press`
* `focus-in`
* `focus-out`
* `key-down`
* `key-press`
* `key-up`
These callbacks are passed to `Input` like this:
```handlebars
<Input @value={{this.searchWord}} @enter={{this.query}} />
```
Starting with Ember Octane, we recommend using the `{{on}}` modifier to call actions
on specific events, such as the input event.
```handlebars
<label for="input-name">Name:</label>
<Input
@id="input-name"
@value={{this.name}}
{{on "input" this.validateName}}
/>
```
The event name (e.g. `focusout`, `input`, `keydown`) always follows the casing
that the HTML standard uses.
### `<input>` HTML Attributes to Avoid
In most cases, if you want to pass an attribute to the underlying HTML `<input>` element, you
can pass the attribute directly, just like any other Ember component.
```handlebars
<Input @type="text" size="10" />
```
In this example, the `size` attribute will be applied to the underlying `<input>` element in the
outputted HTML.
However, there are a few attributes where you **must** use the `@` version.
* `@type`: This argument is used to control which Ember component is used under the hood
* `@value`: The `@value` argument installs a two-way binding onto the element. If you wanted a
one-way binding, use `<input>` with the `value` property and the `input` event instead.
* `@checked` (for checkboxes): like `@value`, the `@checked` argument installs a two-way binding
onto the element. If you wanted a one-way binding, use `<input type="checkbox">` with
`checked` and the `input` event instead.
### Extending `TextField`
Internally, `<Input @type="text" />` creates an instance of `TextField`, passing arguments from
the helper to `TextField`'s `create` method. Subclassing `TextField` is supported but not
recommended.
See [TextField](/ember/release/classes/TextField)
### Checkbox
To create an `<input type="checkbox">`:
```handlebars
Emberize Everything:
<Input @type="checkbox" @checked={{this.isEmberized}} name="isEmberized" />
```
This will bind the checked state of this checkbox to the value of `isEmberized` -- if either one
changes, it will be reflected in the other.
### Extending `Checkbox`
Internally, `<Input @type="checkbox" />` creates an instance of `Checkbox`. Subclassing
`TextField` is supported but not recommended.
See [Checkbox](/ember/release/classes/Checkbox)
@method Input
@for Ember.Templates.components
@see {TextField}
@see {Checkbox}
@param {Hash} options
@public
*/
class Input extends AbstractInput {
constructor() {
super(...arguments);
this._checked = valueFrom(this.args.named.checked);
}
static toString() {
return 'Input';
}
/**
* The HTML class attribute.
*/
get class() {
if (this.isCheckbox) {
return 'ember-checkbox ember-view';
} else {
return 'ember-text-field ember-view';
}
}
/**
* The HTML type attribute.
*/
get type() {
var type = this.named('type');
if (type === null || type === undefined) {
return 'text';
}
(true && !(typeof type === 'string') && (0, _debug.assert)('The `@type` argument to the <Input> component must be a string', typeof type === 'string'));
return isValidInputType(type) ? type : 'text';
}
get isCheckbox() {
return this.named('type') === 'checkbox';
}
get checked() {
if (this.isCheckbox) {
(true && (0, _debug.warn)('`<Input @type="checkbox" />` reflects its checked state via the `@checked` argument. ' + 'You wrote `<Input @type="checkbox" @value={{...}} />` which is likely not what you intended. ' + 'Did you mean `<Input @type="checkbox" @checked={{...}} />`?', (0, _validator.untrack)(() => this.args.named.checked !== undefined || this.args.named.value === undefined || typeof (0, _reference.valueForRef)(this.args.named.value) === 'string'), {
id: 'ember.built-in-components.input-checkbox-value'
}));
return this._checked.get();
} else {
return undefined;
}
}
set checked(checked) {
(true && (0, _debug.warn)('`<Input @type="checkbox" />` reflects its checked state via the `@checked` argument. ' + 'You wrote `<Input @type="checkbox" @value={{...}} />` which is likely not what you intended. ' + 'Did you mean `<Input @type="checkbox" @checked={{...}} />`?', (0, _validator.untrack)(() => this.args.named.checked !== undefined || this.args.named.value === undefined || typeof (0, _reference.valueForRef)(this.args.named.value) === 'string'), {
id: 'ember.built-in-components.input-checkbox-value'
}));
this._checked.set(checked);
}
change(event) {
if (this.isCheckbox) {
this.checkedDidChange(event);
} else {
super.change(event);
}
}
input(event) {
if (!this.isCheckbox) {
super.input(event);
}
}
checkedDidChange(event) {
var element = event.target;
(true && !(element instanceof HTMLInputElement) && (0, _debug.assert)('[BUG] element must be an <input>', element instanceof HTMLInputElement));
this.checked = element.checked;
}
isSupportedArgument(name) {
var supportedArguments = ['type', 'value', 'checked', 'enter', 'insert-newline', 'escape-press'];
return supportedArguments.indexOf(name) !== -1 || super.isSupportedArgument(name);
}
}
__decorate$1([_object.action], Input.prototype, "change", null);
__decorate$1([_object.action], Input.prototype, "input", null);
__decorate$1([_object.action], Input.prototype, "checkedDidChange", null);
var Input$1 = opaquify(Input, InputTemplate);
_exports.Input = Input$1;
var LinkToTemplate = (0, _opcodeCompiler.templateFactory)({
"id": "CVwkBtGh",
"block": "[[[11,3],[16,1,[30,0,[\"id\"]]],[16,0,[30,0,[\"class\"]]],[16,\"role\",[30,0,[\"role\"]]],[16,\"title\",[30,0,[\"title\"]]],[16,\"rel\",[30,0,[\"rel\"]]],[16,\"tabindex\",[30,0,[\"tabindex\"]]],[16,\"target\",[30,0,[\"target\"]]],[17,1],[16,6,[30,0,[\"href\"]]],[4,[38,0],[\"click\",[30,0,[\"click\"]]],null],[12],[18,2,null],[13]],[\"&attrs\",\"&default\"],false,[\"on\",\"yield\"]]",
"moduleName": "packages/@ember/-internals/glimmer/lib/templates/link-to.hbs",
"isStrictMode": false
});
var __decorate$2 = undefined && undefined.__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 EMPTY_ARRAY$1 = [];
var EMPTY_QUERY_PARAMS = {};
(0, _debug.debugFreeze)(EMPTY_ARRAY$1);
(0, _debug.debugFreeze)(EMPTY_QUERY_PARAMS);
function isMissing(value) {
return value === null || value === undefined;
}
function isPresent(value) {
return !isMissing(value);
}
function isQueryParams(value) {
return typeof value === 'object' && value !== null && value['isQueryParams'] === true;
}
/**
The `LinkTo` component renders a link to the supplied `routeName` passing an optionally
supplied model to the route as its `model` context of the route. The block for `LinkTo`
becomes the contents of the rendered element:
```handlebars
<LinkTo @route='photoGallery'>
Great Hamster Photos
</LinkTo>
```
This will result in:
```html
<a href="/hamster-photos">
Great Hamster Photos
</a>
```
### Disabling the `LinkTo` component
The `LinkTo` component can be disabled by using the `disabled` argument. A disabled link
doesn't result in a transition when activated, and adds the `disabled` class to the `<a>`
element.
(The class name to apply to the element can be overridden by using the `disabledClass`
argument)
```handlebars
<LinkTo @route='photoGallery' @disabled={{true}}>
Great Hamster Photos
</LinkTo>
```
### Handling `href`
`<LinkTo>` will use your application's Router to fill the element's `href` property with a URL
that matches the path to the supplied `routeName`.
### Handling current route
The `LinkTo` component will apply a CSS class name of 'active' when the application's current
route matches the supplied routeName. For example, if the application's current route is
'photoGallery.recent', then the following invocation of `LinkTo`:
```handlebars
<LinkTo @route='photoGallery.recent'>
Great Hamster Photos
</LinkTo>
```
will result in
```html
<a href="/hamster-photos/this-week" class="active">
Great Hamster Photos
</a>
```
The CSS class used for active classes can be customized by passing an `activeClass` argument:
```handlebars
<LinkTo @route='photoGallery.recent' @activeClass="current-url">
Great Hamster Photos
</LinkTo>
```
```html
<a href="/hamster-photos/this-week" class="current-url">
Great Hamster Photos
</a>
```
### Keeping a link active for other routes
If you need a link to be 'active' even when it doesn't match the current route, you can use the
`current-when` argument.
```handlebars
<LinkTo @route='photoGallery' @current-when='photos'>
Photo Gallery
</LinkTo>
```
This may be helpful for keeping links active for:
* non-nested routes that are logically related
* some secondary menu approaches
* 'top navigation' with 'sub navigation' scenarios
A link will be active if `current-when` is `true` or the current
route is the route this link would transition to.
To match multiple routes 'space-separate' the routes:
```handlebars
<LinkTo @route='gallery' @current-when='photos drawings paintings'>
Art Gallery
</LinkTo>
```
### Supplying a model
An optional `model` argument can be used for routes whose
paths contain dynamic segments. This argument will become
the model context of the linked route:
```javascript
Router.map(function() {
this.route("photoGallery", {path: "hamster-photos/:photo_id"});
});
```
```handlebars
<LinkTo @route='photoGallery' @model={{this.aPhoto}}>
{{aPhoto.title}}
</LinkTo>
```
```html
<a href="/hamster-photos/42">
Tomster
</a>
```
### Supplying multiple models
For deep-linking to route paths that contain multiple
dynamic segments, the `models` argument can be used.
As the router transitions through the route path, each
supplied model argument will become the context for the
route with the dynamic segments:
```javascript
Router.map(function() {
this.route("photoGallery", { path: "hamster-photos/:photo_id" }, function() {
this.route("comment", {path: "comments/:comment_id"});
});
});
```
This argument will become the model context of the linked route:
```handlebars
<LinkTo @route='photoGallery.comment' @models={{array this.aPhoto this.comment}}>
{{comment.body}}
</LinkTo>
```
```html
<a href="/hamster-photos/42/comments/718">
A+++ would snuggle again.
</a>
```
### Supplying an explicit dynamic segment value
If you don't have a model object available to pass to `LinkTo`,
an optional string or integer argument can be passed for routes whose
paths contain dynamic segments. This argument will become the value
of the dynamic segment:
```javascript
Router.map(function() {
this.route("photoGallery", { path: "hamster-photos/:photo_id" });
});
```
```handlebars
<LinkTo @route='photoGallery' @model={{aPhotoId}}>
{{this.aPhoto.title}}
</LinkTo>
```
```html
<a href="/hamster-photos/42">
Tomster
</a>
```
When transitioning into the linked route, the `model` hook will
be triggered with parameters including this passed identifier.
### Supplying query parameters
If you need to add optional key-value pairs that appear to the right of the ? in a URL,
you can use the `query` argument.
```handlebars
<LinkTo @route='photoGallery' @query={{hash page=1 per_page=20}}>
Great Hamster Photos
</LinkTo>
```
This will result in:
```html
<a href="/hamster-photos?page=1&per_page=20">
Great Hamster Photos
</a>
```
@for Ember.Templates.components
@method LinkTo
@public
*/
/**
@module @ember/routing
*/
/**
See [Ember.Templates.components.LinkTo](/ember/release/classes/Ember.Templates.components/methods/input?anchor=LinkTo).
@for Ember.Templates.helpers
@method link-to
@see {Ember.Templates.components.LinkTo}
@public
**/
/**
An opaque interface which can be imported and used in strict-mode
templates to call <LinkTo>.
See [Ember.Templates.components.LinkTo](/ember/release/classes/Ember.Templates.components/methods/input?anchor=LinkTo).
@for @ember/routing
@method LinkTo
@see {Ember.Templates.components.LinkTo}
@public
**/
class LinkTo extends InternalComponent {
constructor() {
super(...arguments); // GH #17963
this.currentRouteCache = (0, _validator.createCache)(() => {
(0, _validator.consumeTag)((0, _validator.tagFor)(this.routing, 'currentState'));
return (0, _validator.untrack)(() => this.routing.currentRouteName);
});
}
static toString() {
return 'LinkTo';
}
validateArguments() {
(true && !(!this.isEngine || this.engineMountPoint !== undefined) && (0, _debug.assert)('You attempted to use the <LinkTo> component within a routeless engine, this is not supported. ' + 'If you are using the ember-engines addon, use the <LinkToExternal> component instead. ' + 'See https://ember-engines.com/docs/links for more info.', !this.isEngine || this.engineMountPoint !== undefined));
(true && !('route' in this.args.named || 'model' in this.args.named || 'models' in this.args.named || 'query' in this.args.named) && (0, _debug.assert)('You must provide at least one of the `@route`, `@model`, `@models` or `@query` arguments to `<LinkTo>`.', 'route' in this.args.named || 'model' in this.args.named || 'models' in this.args.named || 'query' in this.args.named));
(true && !(!('model' in this.args.named && 'models' in this.args.named)) && (0, _debug.assert)('You cannot provide both the `@model` and `@models` arguments to the <LinkTo> component.', !('model' in this.args.named && 'models' in this.args.named)));
super.validateArguments();
}
get class() {
var classes = 'ember-view';
if (this.isActive) {
classes += this.classFor('active');
if (this.willBeActive === false) {
classes += ' ember-transitioning-out';
}
} else if (this.willBeActive) {
classes += ' ember-transitioning-in';
}
if (this.isLoading) {
classes += this.classFor('loading');
}
if (this.isDisabled) {
classes += this.classFor('disabled');
}
return classes;
}
get href() {
if (this.isLoading) {
return '#';
}
var {
routing,
route,
models,
query
} = this;
(true && !(isPresent(route)) && (0, _debug.assert)('[BUG] route can only be missing if isLoading is true', isPresent(route))); // consume the current router state so we invalidate when QP changes
// TODO: can we narrow this down to QP changes only?
(0, _validator.consumeTag)((0, _validator.tagFor)(routing, 'currentState'));
if (true
/* DEBUG */
) {
try {
return routing.generateURL(route, models, query);
} catch (e) {
// tslint:disable-next-line:max-line-length
e.message = `While generating link to route "${route}": ${e.message}`;
throw e;
}
} else {
return routing.generateURL(route, models, query);
}
}
click(event) {
if (!(0, _views.isSimpleClick)(event)) {
return;
}
var element = event.currentTarget;
(true && !(element instanceof HTMLAnchorElement) && (0, _debug.assert)('[BUG] must be an <a> element', element instanceof HTMLAnchorElement));
var isSelf = element.target === '' || element.target === '_self';
if (isSelf) {
this.preventDefault(event);
} else {
return;
}
if (this.isDisabled) {
return;
}
if (this.isLoading) {
(true && (0, _debug.warn)('This link is in an inactive loading state because at least one of its models ' + 'currently has a null/undefined value, or the provided route name is invalid.', false, {
id: 'ember-glimmer.link-to.inactive-loading-state'
}));
return;
}
var {
routing,
route,
models,
query,
replace
} = this;
var payload = {
routeName: route,
queryParams: query,
transition: undefined
};
(0, _instrumentation.flaggedInstrument)('interaction.link-to', payload, () => {
(true && !(isPresent(route)) && (0, _debug.assert)('[BUG] route can only be missing if isLoading is true', isPresent(route))); // TODO: is the signature wrong? this.query is definitely NOT a QueryParam!
payload.transition = routing.transitionTo(route, models, query, replace);
});
}
get route() {
if ('route' in this.args.named) {
var route = this.named('route');
(true && !(isMissing(route) || typeof route === 'string') && (0, _debug.assert)('The `@route` argument to the <LinkTo> component must be a string', isMissing(route) || typeof route === 'string'));
return route && this.namespaceRoute(route);
} else {
return this.currentRoute;
}
}
get currentRoute() {
return (0, _validator.getValue)(this.currentRouteCache);
} // TODO: not sure why generateURL takes {}[] instead of unknown[]
get models() {
if ('models' in this.args.named) {
var models = this.named('models');
(true && !(Array.isArray(models)) && (0, _debug.assert)('The `@models` argument to the <LinkTo> component must be an array.', Array.isArray(models)));
return models;
} else if ('model' in this.args.named) {
return [this.named('model')];
} else {
return EMPTY_ARRAY$1;
}
} // TODO: this should probably be Record<string, unknown> or something
get query() {
if ('query' in this.args.named) {
var query = this.named('query');
(true && !(query !== null && typeof query === 'object') && (0, _debug.assert)('The `@query` argument to the <LinkTo> component must be an object.', query !== null && typeof query === 'object'));
return Object.assign({}, query);
} else {
return EMPTY_QUERY_PARAMS;
}
}
get replace() {
return this.named('replace') === true;
}
get isActive() {
return this.isActiveForState(this.routing.currentState);
}
get willBeActive() {
var current = this.routing.currentState;
var target = this.routing.targetState;
if (current === target) {
return null;
} else {
return this.isActiveForState(target);
}
}
get isLoading() {
return isMissing(this.route) || this.models.some(model => isMissing(model));
}
get isDisabled() {
return Boolean(this.named('disabled'));
}
get isEngine() {
return (0, _engine.getEngineParent)(this.owner) !== undefined;
}
get engineMountPoint() {
return this.owner.mountPoint;
}
classFor(state) {
var className = this.named(`${state}Class`);
(true && !(isMissing(className) || typeof className === 'string' || typeof className === 'boolean') && (0, _debug.assert)(`The \`@${state}Class\` argument to the <LinkTo> component must be a string or boolean`, isMissing(className) || typeof className === 'string' || typeof className === 'boolean'));
if (className === true || isMissing(className)) {
return ` ${state}`;
} else if (className) {
return ` ${className}`;
} else {
return '';
}
}
namespaceRoute(route) {
var {
engineMountPoint
} = this;
if (engineMountPoint === undefined) {
return route;
} else if (route === 'application') {
return engineMountPoint;
} else {
return `${engineMountPoint}.${route}`;
}
}
isActiveForState(state) {
if (!isPresent(state)) {
return false;
}
if (this.isLoading) {
return false;
}
var currentWhen = this.named('current-when');
if (typeof currentWhen === 'boolean') {
return currentWhen;
} else if (typeof currentWhen === 'string') {
var {
models,
routing
} = this;
return currentWhen.split(' ').some(route => routing.isActiveForRoute(models, undefined, this.namespaceRoute(route), state));
} else {
var {
route,
models: _models,
query,
routing: _routing
} = this;
(true && !(isPresent(route)) && (0, _debug.assert)('[BUG] route can only be missing if isLoading is true', isPresent(route))); // TODO: is the signature wrong? this.query is definitely NOT a QueryParam!
return _routing.isActiveForRoute(_models, query, route, state);
}
}
preventDefault(event) {
event.preventDefault();
}
isSupportedArgument(name) {
var supportedArguments = ['route', 'model', 'models', 'query', 'replace', 'disabled', 'current-when', 'activeClass', 'loadingClass', 'disabledClass'];
return supportedArguments.indexOf(name) !== -1 || super.isSupportedArgument(name);
}
}
__decorate$2([(0, _service.inject)('-routing')], LinkTo.prototype, "routing", void 0);
__decorate$2([_object.action], LinkTo.prototype, "click", null);
var {
prototype
} = LinkTo;
var descriptorFor = (target, property) => {
if (target) {
return Object.getOwnPropertyDescriptor(target, property) || descriptorFor(Object.getPrototypeOf(target), property);
} else {
return null;
}
}; // @href
{
var superOnUnsupportedArgument = prototype['onUnsupportedArgument'];
Object.defineProperty(prototype, 'onUnsupportedArgument', {
configurable: true,
enumerable: false,
value: function onUnsupportedArgument(name) {
if (name === 'href') {
(true && !(false) && (0, _debug.assert)(`Passing the \`@href\` argument to <LinkTo> is not supported.`));
} else {
superOnUnsupportedArgument.call(this, name);
}
}
});
} // QP
{
var superModelsDescriptor = descriptorFor(prototype, 'models');
(true && !(superModelsDescriptor && typeof superModelsDescriptor.get === 'function') && (0, _debug.assert)(`[BUG] expecting models to be a getter on <LinkTo>`, superModelsDescriptor && typeof superModelsDescriptor.get === 'function'));
var superModelsGetter = superModelsDescriptor.get;
Object.defineProperty(prototype, 'models', {
configurable: true,
enumerable: false,
get: function models() {
var models = superModelsGetter.call(this);
if (models.length > 0 && !('query' in this.args.named)) {
if (isQueryParams(models[models.length - 1])) {
models = models.slice(0, -1);
}
}
return models;
}
});
var superQueryDescriptor = descriptorFor(prototype, 'query');
(true && !(superQueryDescriptor && typeof superQueryDescriptor.get === 'function') && (0, _debug.assert)(`[BUG] expecting query to be a getter on <LinkTo>`, superQueryDescriptor && typeof superQueryDescriptor.get === 'function'));
var superQueryGetter = superQueryDescriptor.get;
Object.defineProperty(prototype, 'query', {
configurable: true,
enumerable: false,
get: function query() {
var _a;
if ('query' in this.args.named) {
var qp = superQueryGetter.call(this);
if (isQueryParams(qp)) {
return (_a = qp.values) !== null && _a !== void 0 ? _a : EMPTY_QUERY_PARAMS;
} else {
return qp;
}
} else {
var models = superModelsGetter.call(this);
if (models.length > 0) {
var _qp = models[models.length - 1];
if (isQueryParams(_qp) && _qp.values !== null) {
return _qp.values;
}
}
return EMPTY_QUERY_PARAMS;
}
}
});
} // Positional Arguments
{
var _superOnUnsupportedArgument = prototype['onUnsupportedArgument'];
Object.defineProperty(prototype, 'onUnsupportedArgument', {
configurable: true,
enumerable: false,
value: function onUnsupportedArgument(name) {
if (name !== 'params') {
_superOnUnsupportedArgument.call(this, name);
}
}
});
}
var LinkTo$1 = opaquify(LinkTo, LinkToTemplate);
_exports.LinkTo = LinkTo$1;
var TextareaTemplate = (0, _opcodeCompiler.templateFactory)({
"id": "OpzctQXz",
"block": "[[[11,\"textarea\"],[16,1,[30,0,[\"id\"]]],[16,0,[30,0,[\"class\"]]],[17,1],[16,2,[30,0,[\"value\"]]],[4,[38,0],[\"change\",[30,0,[\"change\"]]],null],[4,[38,0],[\"input\",[30,0,[\"input\"]]],null],[4,[38,0],[\"keyup\",[30,0,[\"keyUp\"]]],null],[4,[38,0],[\"paste\",[30,0,[\"valueDidChange\"]]],null],[4,[38,0],[\"cut\",[30,0,[\"valueDidChange\"]]],null],[12],[13]],[\"&attrs\"],false,[\"on\"]]",
"moduleName": "packages/@ember/-internals/glimmer/lib/templates/textarea.hbs",
"isStrictMode": false
});
var __decorate$3 = undefined && undefined.__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;
};
/**
The `Textarea` component inserts a new instance of `<textarea>` tag into the template.
The `@value` argument provides the content of the `<textarea>`.
This template:
```handlebars
<Textarea @value="A bunch of text" />
```
Would result in the following HTML:
```html
<textarea class="ember-text-area">
A bunch of text
</textarea>
```
The `@value` argument is two-way bound. If the user types text into the textarea, the `@value`
argument is updated. If the `@value` argument is updated, the text in the textarea is updated.
In the following example, the `writtenWords` property on the component will be updated as the user
types 'Lots of text' into the text area of their browser's window.
```app/components/word-editor.js
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
export default class WordEditorComponent extends Component {
@tracked writtenWords = "Lots of text that IS bound";
}
```
```handlebars
<Textarea @value={{writtenWords}} />
```
Would result in the following HTML:
```html
<textarea class="ember-text-area">
Lots of text that IS bound
</textarea>
```
If you wanted a one way binding, you could use the `<textarea>` element directly, and use the
`value` DOM property and the `input` event.
### Actions
The `Textarea` component takes a number of arguments with callbacks that are invoked in
response to user events.
* `enter`
* `insert-newline`
* `escape-press`
* `focus-in`
* `focus-out`
* `key-press`
These callbacks are passed to `Textarea` like this:
```handlebars
<Textarea @value={{this.searchWord}} @enter={{this.query}} />
```
## Classic Invocation Syntax
The `Textarea` component can also be invoked using curly braces, just like any other Ember
component.
For example, this is an invocation using angle-bracket notation:
```handlebars
<Textarea @value={{this.searchWord}} @enter={{this.query}} />
```
You could accomplish the same thing using classic invocation:
```handlebars
{{textarea value=this.searchWord enter=this.query}}
```
The main difference is that angle-bracket invocation supports any HTML attribute using HTML
attribute syntax, because attributes and arguments have different syntax when using angle-bracket
invocation. Curly brace invocation, on the other hand, only has a single syntax for arguments,
and components must manually map attributes onto component arguments.
When using classic invocation with `{{textarea}}`, only the following attributes are mapped onto
arguments:
* rows
* cols
* name
* selectionEnd
* selectionStart
* autocomplete
* wrap
* lang
* dir
* value
## Classic `layout` and `layoutName` properties
Because HTML `textarea` elements do not contain inner HTML the `layout` and
`layoutName` properties will not be applied.
@method Textarea
@for Ember.Templates.components
@public
*/
/**
See Ember.Templates.components.Textarea.
@method textarea
@for Ember.Templates.helpers
@see {Ember.Templates.components.Textarea}
@public
*/
/**
An opaque interface which can be imported and used in strict-mode
templates to call <Textarea>.
See [Ember.Templates.components.Textarea](/ember/release/classes/Ember.Templates.components/methods/Textarea?anchor=Input).
@for @ember/component
@method Textarea
@see {Ember.Templates.components.Textarea}
@public
**/
class Textarea extends AbstractInput {
static toString() {
return 'Textarea';
}
get class() {
return 'ember-text-area ember-view';
} // See abstract-input.ts for why these are needed
change(event) {
super.change(event);
}
input(event) {
super.input(event);
}
isSupportedArgument(name) {
var supportedArguments = ['type', 'value', 'enter', 'insert-newline', 'escape-press'];
return supportedArguments.indexOf(name) !== -1 || super.isSupportedArgument(name);
}
}
__decorate$3([_object.action], Textarea.prototype, "change", null);
__decorate$3([_object.action], Textarea.prototype, "input", null);
var Textarea$1 = opaquify(Textarea, TextareaTemplate);
_exports.Textarea = Textarea$1;
function isTemplateFactory(template) {
return typeof template === 'function';
}
function referenceForParts(rootRef, parts) {
var isAttrs = parts[0] === 'attrs'; // TODO deprecate this
if (isAttrs) {
parts.shift();
if (parts.length === 1) {
return (0, _reference.childRefFor)(rootRef, parts[0]);
}
}
return (0, _reference.childRefFromParts)(rootRef, parts);
}
function parseAttributeBinding(microsyntax) {
var colonIndex = microsyntax.indexOf(':');
if (colonIndex === -1) {
(true && !(microsyntax !== 'class') && (0, _debug.assert)('You cannot use class as an attributeBinding, use classNameBindings instead.', microsyntax !== 'class'));
return [microsyntax, microsyntax, true];
} else {
var prop = microsyntax.substring(0, colonIndex);
var attribute = microsyntax.substring(colonIndex + 1);
(true && !(attribute !== 'class') && (0, _debug.assert)('You cannot use class as an attributeBinding, use classNameBindings instead.', attribute !== 'class'));
return [prop, attribute, false];
}
}
function installAttributeBinding(component, rootRef, parsed, operations) {
var [prop, attribute, isSimple] = parsed;
if (attribute === 'id') {
var elementId = (0, _metal.get)(component, prop);
if (elementId === undefined || elementId === null) {
elementId = component.elementId;
}
elementId = (0, _reference.createPrimitiveRef)(elementId);
operations.setAttribute('id', elementId, true, null);
return;
}
var isPath = prop.indexOf('.') > -1;
var reference = isPath ? referenceForParts(rootRef, prop.split('.')) : (0, _reference.childRefFor)(rootRef, prop);
(true && !(!(isSimple && isPath)) && (0, _debug.assert)(`Illegal attributeBinding: '${prop}' is not a valid attribute name.`, !(isSimple && isPath)));
operations.setAttribute(attribute, reference, false, null);
}
function createClassNameBindingRef(rootRef, microsyntax, operations) {
var [prop, truthy, falsy] = microsyntax.split(':');
var isStatic = prop === '';
if (isStatic) {
operations.setAttribute('class', (0, _reference.createPrimitiveRef)(truthy), true, null);
} else {
var isPath = prop.indexOf('.') > -1;
var parts = isPath ? prop.split('.') : [];
var value = isPath ? referenceForParts(rootRef, parts) : (0, _reference.childRefFor)(rootRef, prop);
var ref;
if (truthy === undefined) {
ref = createSimpleClassNameBindingRef(value, isPath ? parts[parts.length - 1] : prop);
} else {
ref = createColonClassNameBindingRef(value, truthy, falsy);
}
operations.setAttribute('class', ref, false, null);
}
}
function createSimpleClassNameBindingRef(inner, path) {
var dasherizedPath;
return (0, _reference.createComputeRef)(() => {
var value = (0, _reference.valueForRef)(inner);
if (value === true) {
(true && !(path !== undefined) && (0, _debug.assert)('You must pass a path when binding a to a class name using classNameBindings', path !== undefined));
return dasherizedPath || (dasherizedPath = (0, _string.dasherize)(path));
} else if (value || value === 0) {
return String(value);
} else {
return null;
}
});
}
function createColonClassNameBindingRef(inner, truthy, falsy) {
return (0, _reference.createComputeRef)(() => {
return (0, _reference.valueForRef)(inner) ? truthy : falsy;
});
}
function NOOP$1() {}
/**
@module ember
*/
/**
Represents the internal state of the component.
@class ComponentStateBucket
@private
*/
class ComponentStateBucket {
constructor(component, args, argsTag, finalizer, hasWrappedElement, isInteractive) {
this.component = component;
this.args = args;
this.argsTag = argsTag;
this.finalizer = finalizer;
this.hasWrappedElement = hasWrappedElement;
this.isInteractive = isInteractive;
this.classRef = null;
this.classRef = null;
this.argsRevision = args === null ? 0 : (0, _validator.valueForTag)(argsTag);
this.rootRef = (0, _reference.createConstRef)(component, 'this');
(0, _destroyable.registerDestructor)(this, () => this.willDestroy(), true);
(0, _destroyable.registerDestructor)(this, () => this.component.destroy());
}
willDestroy() {
var {
component,
isInteractive
} = this;
if (isInteractive) {
(0, _validator.beginUntrackFrame)();
component.trigger('willDestroyElement');
component.trigger('willClearRender');
(0, _validator.endUntrackFrame)();
var element = (0, _views.getViewElement)(component);
if (element) {
(0, _views.clearElementView)(element);
(0, _views.clearViewElement)(component);
}
}
component.renderer.unregister(component);
}
finalize() {
var {
finalizer
} = this;
finalizer();
this.finalizer = NOOP$1;
}
}
function internalHelper(helper) {
return (0, _manager2.setInternalHelperManager)(helper, {});
}
/**
@module ember
*/
var ACTIONS = new _util._WeakSet();
/**
The `{{action}}` helper provides a way to pass triggers for behavior (usually
just a function) between components, and into components from controllers.
### Passing functions with the action helper
There are three contexts an action helper can be used in. The first two
contexts to discuss are attribute context, and Handlebars value context.
```handlebars
{{! An example of attribute context }}
<div onclick={{action "save"}}></div>
{{! Examples of Handlebars value context }}
{{input on-input=(action "save")}}
{{yield (action "refreshData") andAnotherParam}}
```
In these contexts,
the helper is called a "closure action" helper. Its behavior is simple:
If passed a function name, read that function off the `actions` property
of the current context. Once that function is read, or immediately if a function was
passed, create a closure over that function and any arguments.
The resulting value of an action helper used this way is simply a function.
For example, in the attribute context:
```handlebars
{{! An example of attribute context }}
<div onclick={{action "save"}}></div>
```
The resulting template render logic would be:
```js
var div = document.createElement('div');
var actionFunction = (function(context){
return function() {
return context.actions.save.apply(context, arguments);
};
})(context);
div.onclick = actionFunction;
```
Thus when the div is clicked, the action on that context is called.
Because the `actionFunction` is just a function, closure actions can be
passed between components and still execute in the correct context.
Here is an example action handler on a component:
```app/components/my-component.js
import Component from '@glimmer/component';
import { action } from '@ember/object';
export default class extends Component {
@action
save() {
this.model.save();
}
}
```
Actions are always looked up on the `actions` property of the current context.
This avoids collisions in the naming of common actions, such as `destroy`.
Two options can be passed to the `action` helper when it is used in this way.
* `target=someProperty` will look to `someProperty` instead of the current
context for the `actions` hash. This can be useful when targeting a
service for actions.
* `value="target.value"` will read the path `target.value` off the first
argument to the action when it is called and rewrite the first argument
to be that value. This is useful when attaching actions to event listeners.
### Invoking an action
Closure actions curry both their scope and any arguments. When invoked, any
additional arguments are added to the already curried list.
Actions are presented in JavaScript as callbacks, and are
invoked like any other JavaScript function.
For example
```app/components/update-name.js
import Component from '@glimmer/component';
import { action } from '@ember/object';
export default class extends Component {
@action
setName(model, name) {
model.set('name', name);
}
}
```
```app/components/update-name.hbs
{{input on-input=(action (action 'setName' @model) value="target.value")}}
```
The first argument (`@model`) was curried over, and the run-time argument (`event`)
becomes a second argument. Action calls can be nested this way because each simply
returns a function. Any function can be passed to the `{{action}}` helper, including
other actions.
Actions invoked with `sendAction` have the same currying behavior as demonstrated
with `on-input` above. For example:
```app/components/my-input.js
import Component from '@glimmer/component';
import { action } from '@ember/object';
export default class extends Component {
@action
setName(model, name) {
model.set('name', name);
}
}
```
```handlebars
<MyInput @submit={{action 'setName' @model}} />
```
or
```handlebars
{{my-input submit=(action 'setName' @model)}}
```
```app/components/my-component.js
import Component from '@ember/component';
export default Component.extend({
click() {
// Note that model is not passed, it was curried in the template
this.submit('bob');
}
});
```
### Attaching actions to DOM elements
The third context of the `{{action}}` helper can be called "element space".
For example:
```handlebars
{{! An example of element space }}
<div {{action "save"}}></div>
```
Used this way, the `{{action}}` helper provides a useful shortcut for
registering an HTML element in a template for a single DOM event and
forwarding that interaction to the template's context (controller or component).
If the context of a template is a controller, actions used this way will
bubble to routes when the controller does not implement the specified action.
Once an action hits a route, it will bubble through the route hierarchy.
### Event Propagation
`{{action}}` helpers called in element space can control event bubbling. Note
that the closure style actions cannot.
Events triggered through the action helper will automatically have
`.preventDefault()` called on them. You do not need to do so in your event
handlers. If you need to allow event propagation (to handle file inputs for
example) you can supply the `preventDefault=false` option to the `{{action}}` helper:
```handlebars
<div {{action "sayHello" preventDefault=false}}>
<input type="file" />
<input type="checkbox" />
</div>
```
To disable bubbling, pass `bubbles=false` to the helper:
```handlebars
<button {{action 'edit' post bubbles=false}}>Edit</button>
```
To disable bubbling with closure style actions you must create your own
wrapper helper that makes use of `event.stopPropagation()`:
```handlebars
<div onclick={{disable-bubbling (action "sayHello")}}>Hello</div>
```
```app/helpers/disable-bubbling.js
import { helper } from '@ember/component/helper';
export function disableBubbling([action]) {
return function(event) {
event.stopPropagation();
return action(event);
};
}
export default helper(disableBubbling);
```
If you need the default handler to trigger you should either register your
own event handler, or use event methods on your view class. See
["Responding to Browser Events"](/ember/release/classes/Component)
in the documentation for `Component` for more information.
### Specifying DOM event type
`{{action}}` helpers called in element space can specify an event type.
By default the `{{action}}` helper registers for DOM `click` events. You can
supply an `on` option to the helper to specify a different DOM event name:
```handlebars
<div {{action "anActionName" on="doubleClick"}}>
click me
</div>
```
See ["Event Names"](/ember/release/classes/Component) for a list of
acceptable DOM event names.
### Specifying whitelisted modifier keys
`{{action}}` helpers called in element space can specify modifier keys.
By default the `{{action}}` helper will ignore click events with pressed modifier
keys. You can supply an `allowedKeys` option to specify which keys should not be ignored.
```handlebars
<div {{action "anActionName" allowedKeys="alt"}}>
click me
</div>
```
This way the action will fire when clicking with the alt key pressed down.
Alternatively, supply "any" to the `allowedKeys` option to accept any combination of modifier keys.
```handlebars
<div {{action "anActionName" allowedKeys="any"}}>
click me with any key pressed
</div>
```
### Specifying a Target
A `target` option can be provided to the helper to change
which object will receive the method call. This option must be a path
to an object, accessible in the current context:
```app/templates/application.hbs
<div {{action "anActionName" target=someService}}>
click me
</div>
```
```app/controllers/application.js
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
export default class extends Controller {
@service someService;
}
```
@method action
@for Ember.Templates.helpers
@public
*/
var action$1 = internalHelper(args => {
var {
named,
positional
} = args; // The first two argument slots are reserved.
// pos[0] is the context (or `this`)
// pos[1] is the action name or function
// Anything else is an action argument.
var [context, action$$1, ...restArgs] = positional;
var debugKey = action$$1.debugLabel;
var target = 'target' in named ? named.target : context;
var processArgs = makeArgsProcessor('value' in named && named.value, restArgs);
var fn$$1;
if ((0, _reference.isInvokableRef)(action$$1)) {
fn$$1 = makeClosureAction(action$$1, action$$1, invokeRef, processArgs, debugKey);
} else {
fn$$1 = makeDynamicClosureAction((0, _reference.valueForRef)(context), target, action$$1, processArgs, debugKey);
}
ACTIONS.add(fn$$1);
return (0, _reference.createUnboundRef)(fn$$1, '(result of an `action` helper)');
});
function NOOP$2(args) {
return args;
}
function makeArgsProcessor(valuePathRef, actionArgsRef) {
var mergeArgs;
if (actionArgsRef.length > 0) {
mergeArgs = args => {
return actionArgsRef.map(_reference.valueForRef).concat(args);
};
}
var readValue;
if (valuePathRef) {
readValue = args => {
var valuePath = (0, _reference.valueForRef)(valuePathRef);
if (valuePath && args.length > 0) {
args[0] = (0, _metal.get)(args[0], valuePath);
}
return args;
};
}
if (mergeArgs && readValue) {
return args => {
return readValue(mergeArgs(args));
};
} else {
return mergeArgs || readValue || NOOP$2;
}
}
function makeDynamicClosureAction(context, targetRef, actionRef, processArgs, debugKey) {
// We don't allow undefined/null values, so this creates a throw-away action to trigger the assertions
if (true
/* DEBUG */
) {
makeClosureAction(context, (0, _reference.valueForRef)(targetRef), (0, _reference.valueForRef)(actionRef), processArgs, debugKey);
}
return (...args) => {
return makeClosureAction(context, (0, _reference.valueForRef)(targetRef), (0, _reference.valueForRef)(actionRef), processArgs, debugKey)(...args);
};
}
function makeClosureAction(context, target, action$$1, processArgs, debugKey) {
var self;
var fn$$1;
(true && !(action$$1 !== undefined && action$$1 !== null) && (0, _debug.assert)(`Action passed is null or undefined in (action) from ${target}.`, action$$1 !== undefined && action$$1 !== null));
var typeofAction = typeof action$$1;
if (typeofAction === 'string') {
self = target;
fn$$1 = target.actions && target.actions[action$$1];
(true && !(Boolean(fn$$1)) && (0, _debug.assert)(`An action named '${action$$1}' was not found in ${target}`, Boolean(fn$$1)));
} else if (typeofAction === 'function') {
self = context;
fn$$1 = action$$1;
} else {
// tslint:disable-next-line:max-line-length
(true && !(false) && (0, _debug.assert)(`An action could not be made for \`${debugKey || action$$1}\` in ${target}. Please confirm that you are using either a quoted action name (i.e. \`(action '${debugKey || 'myAction'}')\`) or a function available in ${target}.`, false));
}
return (...args) => {
var payload = {
target: self,
args,
label: '@glimmer/closure-action'
};
return (0, _instrumentation.flaggedInstrument)('interaction.ember-action', payload, () => {
return (0, _runloop.join)(self, fn$$1, ...processArgs(args));
});
};
} // The code above:
// 1. Finds an action function, usually on the `actions` hash
// 2. Calls it with the target as the correct `this` context
// Previously, `UPDATE_REFERENCED_VALUE` was a method on the reference itself,
// so this made a bit more sense. Now, it isn't, and so we need to create a
// function that can have `this` bound to it when called. This allows us to use
// the same codepath to call `updateRef` on the reference.
function invokeRef(value) {
(0, _reference.updateRef)(this, value);
} // inputs needed by CurlyComponents (attrs and props, with mutable
// cells, etc).
function processComponentArgs(namedArgs) {
var attrs = Object.create(null);
var props = Object.create(null);
props[ARGS] = namedArgs;
for (var name in namedArgs) {
var ref = namedArgs[name];
var value = (0, _reference.valueForRef)(ref);
var isAction = typeof value === 'function' && ACTIONS.has(value);
if ((0, _reference.isUpdatableRef)(ref) && !isAction) {
attrs[name] = new MutableCell(ref, value);
} else {
attrs[name] = value;
}
props[name] = value;
}
props.attrs = attrs;
return props;
}
var REF = (0, _utils.symbol)('REF');
class MutableCell {
constructor(ref, value) {
this[_views.MUTABLE_CELL] = true;
this[REF] = ref;
this.value = value;
}
update(val) {
(0, _reference.updateRef)(this[REF], val);
}
}
var __rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var ARGS = (0, _utils.enumerableSymbol)('ARGS');
var HAS_BLOCK = (0, _utils.enumerableSymbol)('HAS_BLOCK');
var DIRTY_TAG = (0, _utils.symbol)('DIRTY_TAG');
var IS_DISPATCHING_ATTRS = (0, _utils.symbol)('IS_DISPATCHING_ATTRS');
var BOUNDS = (0, _utils.symbol)('BOUNDS');
var EMBER_VIEW_REF = (0, _reference.createPrimitiveRef)('ember-view');
function aliasIdToElementId(args, props) {
if (args.named.has('id')) {
// tslint:disable-next-line:max-line-length
(true && !(!args.named.has('elementId')) && (0, _debug.assert)(`You cannot invoke a component with both 'id' and 'elementId' at the same time.`, !args.named.has('elementId')));
props.elementId = props.id;
}
} // We must traverse the attributeBindings in reverse keeping track of
// what has already been applied. This is essentially refining the concatenated
// properties applying right to left.
function applyAttributeBindings(attributeBindings, component, rootRef, operations) {
var seen = [];
var i = attributeBindings.length - 1;
while (i !== -1) {
var binding = attributeBindings[i];
var parsed = parseAttributeBinding(binding);
var attribute = parsed[1];
if (seen.indexOf(attribute) === -1) {
seen.push(attribute);
installAttributeBinding(component, rootRef, parsed, operations);
}
i--;
}
if (seen.indexOf('id') === -1) {
var id = component.elementId ? component.elementId : (0, _utils.guidFor)(component);
operations.setAttribute('id', (0, _reference.createPrimitiveRef)(id), false, null);
}
}
var EMPTY_POSITIONAL_ARGS = [];
(0, _debug.debugFreeze)(EMPTY_POSITIONAL_ARGS);
class CurlyComponentManager {
templateFor(component) {
var {
layout,
layoutName
} = component;
var owner = (0, _owner2.getOwner)(component);
var factory;
if (layout === undefined) {
if (layoutName !== undefined) {
var _factory = owner.lookup(`template:${layoutName}`);
(true && !(_factory !== undefined) && (0, _debug.assert)(`Layout \`${layoutName}\` not found!`, _factory !== undefined));
factory = _factory;
} else {
return null;
}
} else if (isTemplateFactory(layout)) {
factory = layout;
} else {
// no layout was found, use the default layout
return null;
}
return (0, _util.unwrapTemplate)(factory(owner)).asWrappedLayout();
}
getDynamicLayout(bucket) {
return this.templateFor(bucket.component);
}
getTagName(state) {
var {
component,
hasWrappedElement
} = state;
if (!hasWrappedElement) {
return null;
}
return component && component.tagName || 'div';
}
getCapabilities() {
return CURLY_CAPABILITIES;
}
prepareArgs(ComponentClass, args) {
var _a;
if (args.named.has('__ARGS__')) {
(true && !(args.positional.length === 0) && (0, _debug.assert)('[BUG] cannot pass both __ARGS__ and positional arguments', args.positional.length === 0));
var _b = args.named.capture(),
{
__ARGS__
} = _b,
rest = __rest(_b, ["__ARGS__"]); // does this need to be untracked?
var __args__ = (0, _reference.valueForRef)(__ARGS__);
var prepared = {
positional: __args__.positional,
named: Object.assign(Object.assign({}, rest), __args__.named)
};
return prepared;
}
var {
positionalParams
} = (_a = ComponentClass.class) !== null && _a !== void 0 ? _a : ComponentClass; // early exits
if (positionalParams === undefined || positionalParams === null || args.positional.length === 0) {
return null;
}
var named;
if (typeof positionalParams === 'string') {
(true && !(!args.named.has(positionalParams)) && (0, _debug.assert)(`You cannot specify positional parameters and the hash argument \`${positionalParams}\`.`, !args.named.has(positionalParams)));
var captured = args.positional.capture();
named = {
[positionalParams]: (0, _reference.createComputeRef)(() => (0, _runtime.reifyPositional)(captured))
};
Object.assign(named, args.named.capture());
} else if (Array.isArray(positionalParams) && positionalParams.length > 0) {
var count = Math.min(positionalParams.length, args.positional.length);
named = {};
Object.assign(named, args.named.capture());
for (var i = 0; i < count; i++) {
// As of TS 3.7, tsc is giving us the following error on this line without the type annotation
//
// TS7022: 'name' implicitly has type 'any' because it does not have a type annotation and is
// referenced directly or indirectly in its own initializer.
//
// This is almost certainly a TypeScript bug, feel free to try and remove the annotation after
// upgrading if it is not needed anymore.
var name = positionalParams[i];
(true && !(!args.named.has(name)) && (0, _debug.assert)(`You cannot specify both a positional param (at position ${i}) and the hash argument \`${name}\`.`, !args.named.has(name)));
named[name] = args.positional.at(i);
}
} else {
return null;
}
return {
positional: _util.EMPTY_ARRAY,
named
};
}
/*
* This hook is responsible for actually instantiating the component instance.
* It also is where we perform additional bookkeeping to support legacy
* features like exposed by view mixins like ChildViewSupport, ActionSupport,
* etc.
*/
create(owner, ComponentClass, args, {
isInteractive
}, dynamicScope, callerSelfRef, hasBlock) {
// Get the nearest concrete component instance from the scope. "Virtual"
// components will be skipped.
var parentView = dynamicScope.view; // Capture the arguments, which tells Glimmer to give us our own, stable
// copy of the Arguments object that is safe to hold on to between renders.
var capturedArgs = args.named.capture();
(0, _validator.beginTrackFrame)();
var props = processComponentArgs(capturedArgs);
var argsTag = (0, _validator.endTrackFrame)(); // Alias `id` argument to `elementId` property on the component instance.
aliasIdToElementId(args, props); // Set component instance's parentView property to point to nearest concrete
// component.
props.parentView = parentView; // Set whether this component was invoked with a block
// (`{{#my-component}}{{/my-component}}`) or without one
// (`{{my-component}}`).
props[HAS_BLOCK] = hasBlock; // Save the current `this` context of the template as the component's
// `_target`, so bubbled actions are routed to the right place.
props._target = (0, _reference.valueForRef)(callerSelfRef);
(0, _owner2.setOwner)(props, owner); // caller:
// <FaIcon @name="bug" />
//
// callee:
// <i class="fa-{{@name}}"></i>
// Now that we've built up all of the properties to set on the component instance,
// actually create it.
(0, _validator.beginUntrackFrame)();
var component = ComponentClass.create(props);
var finalizer = (0, _instrumentation._instrumentStart)('render.component', initialRenderInstrumentDetails, component); // We become the new parentView for downstream components, so save our
// component off on the dynamic scope.
dynamicScope.view = component; // Unless we're the root component, we need to add ourselves to our parent
// component's childViews array.
if (parentView !== null && parentView !== undefined) {
(0, _views.addChildView)(parentView, component);
}
component.trigger('didReceiveAttrs');
var hasWrappedElement = component.tagName !== ''; // We usually do this in the `didCreateElement`, but that hook doesn't fire for tagless components
if (!hasWrappedElement) {
if (isInteractive) {
component.trigger('willRender');
}
component._transitionTo('hasElement');
if (isInteractive) {
component.trigger('willInsertElement');
}
} // Track additional lifecycle metadata about this component in a state bucket.
// Essentially we're saving off all the state we'll need in the future.
var bucket = new ComponentStateBucket(component, capturedArgs, argsTag, finalizer, hasWrappedElement, isInteractive);
if (args.named.has('class')) {
bucket.classRef = args.named.get('class');
}
if (true
/* DEBUG */
) {
processComponentInitializationAssertions(component, props);
}
if (isInteractive && hasWrappedElement) {
component.trigger('willRender');
}
(0, _validator.endUntrackFrame)(); // consume every argument so we always run again
(0, _validator.consumeTag)(bucket.argsTag);
(0, _validator.consumeTag)(component[DIRTY_TAG]);
return bucket;
}
getDebugName(definition) {
var _a;
return definition.fullName || definition.normalizedName || ((_a = definition.class) === null || _a === void 0 ? void 0 : _a.name) || definition.name;
}
getSelf({
rootRef
}) {
return rootRef;
}
didCreateElement({
component,
classRef,
isInteractive,
rootRef
}, element, operations) {
(0, _views.setViewElement)(component, element);
(0, _views.setElementView)(element, component);
var {
attributeBindings,
classNames,
classNameBindings
} = component;
if (attributeBindings && attributeBindings.length) {
applyAttributeBindings(attributeBindings, component, rootRef, operations);
} else {
var id = component.elementId ? component.elementId : (0, _utils.guidFor)(component);
operations.setAttribute('id', (0, _reference.createPrimitiveRef)(id), false, null);
}
if (classRef) {
var ref = createSimpleClassNameBindingRef(classRef);
operations.setAttribute('class', ref, false, null);
}
if (classNames && classNames.length) {
classNames.forEach(name => {
operations.setAttribute('class', (0, _reference.createPrimitiveRef)(name), false, null);
});
}
if (classNameBindings && classNameBindings.length) {
classNameBindings.forEach(binding => {
createClassNameBindingRef(rootRef, binding, operations);
});
}
operations.setAttribute('class', EMBER_VIEW_REF, false, null);
if ('ariaRole' in component) {
operations.setAttribute('role', (0, _reference.childRefFor)(rootRef, 'ariaRole'), false, null);
}
component._transitionTo('hasElement');
if (isInteractive) {
(0, _validator.beginUntrackFrame)();
component.trigger('willInsertElement');
(0, _validator.endUntrackFrame)();
}
}
didRenderLayout(bucket, bounds) {
bucket.component[BOUNDS] = bounds;
bucket.finalize();
}
didCreate({
component,
isInteractive
}) {
if (isInteractive) {
component._transitionTo('inDOM');
component.trigger('didInsertElement');
component.trigger('didRender');
}
}
update(bucket) {
var {
component,
args,
argsTag,
argsRevision,
isInteractive
} = bucket;
bucket.finalizer = (0, _instrumentation._instrumentStart)('render.component', rerenderInstrumentDetails, component);
(0, _validator.beginUntrackFrame)();
if (args !== null && !(0, _validator.validateTag)(argsTag, argsRevision)) {
(0, _validator.beginTrackFrame)();
var props = processComponentArgs(args);
argsTag = bucket.argsTag = (0, _validator.endTrackFrame)();
bucket.argsRevision = (0, _validator.valueForTag)(argsTag);
component[IS_DISPATCHING_ATTRS] = true;
component.setProperties(props);
component[IS_DISPATCHING_ATTRS] = false;
component.trigger('didUpdateAttrs');
component.trigger('didReceiveAttrs');
}
if (isInteractive) {
component.trigger('willUpdate');
component.trigger('willRender');
}
(0, _validator.endUntrackFrame)();
(0, _validator.consumeTag)(argsTag);
(0, _validator.consumeTag)(component[DIRTY_TAG]);
}
didUpdateLayout(bucket) {
bucket.finalize();
}
didUpdate({
component,
isInteractive
}) {
if (isInteractive) {
component.trigger('didUpdate');
component.trigger('didRender');
}
}
getDestroyable(bucket) {
return bucket;
}
}
function processComponentInitializationAssertions(component, props) {
(true && !((() => {
var {
classNameBindings
} = component;
for (var i = 0; i < classNameBindings.length; i++) {
var binding = classNameBindings[i];
if (typeof binding !== 'string' || binding.length === 0) {
return false;
}
}
return true;
})()) && (0, _debug.assert)(`classNameBindings must be non-empty strings: ${component}`, (() => {
var {
classNameBindings
} = component;
for (var i = 0; i < classNameBindings.length; i++) {
var binding = classNameBindings[i];
if (typeof binding !== 'string' || binding.length === 0) {
return false;
}
}
return true;
})()));
(true && !((() => {
var {
classNameBindings
} = component;
for (var i = 0; i < classNameBindings.length; i++) {
var binding = classNameBindings[i];
if (binding.split(' ').length > 1) {
return false;
}
}
return true;
})()) && (0, _debug.assert)(`classNameBindings must not have spaces in them: ${component}`, (() => {
var {
classNameBindings
} = component;
for (var i = 0; i < classNameBindings.length; i++) {
var binding = classNameBindings[i];
if (binding.split(' ').length > 1) {
return false;
}
}
return true;
})()));
(true && !(component.tagName !== '' || !component.classNameBindings || component.classNameBindings.length === 0) && (0, _debug.assert)(`You cannot use \`classNameBindings\` on a tag-less component: ${component}`, component.tagName !== '' || !component.classNameBindings || component.classNameBindings.length === 0));
(true && !(component.tagName !== '' || props.id === component.elementId || !component.elementId && component.elementId !== '') && (0, _debug.assert)(`You cannot use \`elementId\` on a tag-less component: ${component}`, component.tagName !== '' || props.id === component.elementId || !component.elementId && component.elementId !== ''));
(true && !(component.tagName !== '' || !component.attributeBindings || component.attributeBindings.length === 0) && (0, _debug.assert)(`You cannot use \`attributeBindings\` on a tag-less component: ${component}`, component.tagName !== '' || !component.attributeBindings || component.attributeBindings.length === 0));
}
function initialRenderInstrumentDetails(component) {
return component.instrumentDetails({
initialRender: true
});
}
function rerenderInstrumentDetails(component) {
return component.instrumentDetails({
initialRender: false
});
}
var CURLY_CAPABILITIES = {
dynamicLayout: true,
dynamicTag: true,
prepareArgs: true,
createArgs: true,
attributeHook: true,
elementHook: true,
createCaller: true,
dynamicScope: true,
updateHook: true,
createInstance: true,
wrapped: true,
willDestroy: true,
hasSubOwner: false
};
var CURLY_COMPONENT_MANAGER = new CurlyComponentManager();
function isCurlyManager(manager) {
return manager === CURLY_COMPONENT_MANAGER;
}
var lazyEventsProcessed = new WeakMap();
/**
@module @ember/component
*/
/**
A component is a reusable UI element that consists of a `.hbs` template and an
optional JavaScript class that defines its behavior. For example, someone
might make a `button` in the template and handle the click behavior in the
JavaScript file that shares the same name as the template.
Components are broken down into two categories:
- Components _without_ JavaScript, that are based only on a template. These
are called Template-only or TO components.
- Components _with_ JavaScript, which consist of a template and a backing
class.
Ember ships with two types of JavaScript classes for components:
1. Glimmer components, imported from `@glimmer/component`, which are the
default component's for Ember Octane (3.15) and more recent editions.
2. Classic components, imported from `@ember/component`, which were the
default for older editions of Ember (pre 3.15).
Below is the documentation for Classic components. If you are looking for the
API documentation for Template-only or Glimmer components, it is
[available here](/ember/release/modules/@glimmer%2Fcomponent).
## Defining a Classic Component
If you want to customize the component in order to handle events, transform
arguments or maintain internal state, you implement a subclass of `Component`.
One example is to add computed properties to your component:
```app/components/person-profile.js
import Component from '@ember/component';
export default Component.extend({
displayName: computed('person.title', 'person.firstName', 'person.lastName', function() {
let { title, firstName, lastName } = this.person;
if (title) {
return `${title} ${lastName}`;
} else {
return `${firstName} ${lastName}`;
}
})
});
```
And then use it in the component's template:
```app/templates/components/person-profile.hbs
<h1>{{this.displayName}}</h1>
{{yield}}
```
## Customizing a Classic Component's HTML Element in JavaScript
### HTML Tag
The default HTML tag name used for a component's HTML representation is `div`.
This can be customized by setting the `tagName` property.
Consider the following component class:
```app/components/emphasized-paragraph.js
import Component from '@ember/component';
export default Component.extend({
tagName: 'em'
});
```
When invoked, this component would produce output that looks something like
this:
```html
<em id="ember1" class="ember-view"></em>
```
### HTML `class` Attribute
The HTML `class` attribute of a component's tag can be set by providing a
`classNames` property that is set to an array of strings:
```app/components/my-widget.js
import Component from '@ember/component';
export default Component.extend({
classNames: ['my-class', 'my-other-class']
});
```
Invoking this component will produce output that looks like this:
```html
<div id="ember1" class="ember-view my-class my-other-class"></div>
```
`class` attribute values can also be set by providing a `classNameBindings`
property set to an array of properties names for the component. The return
value of these properties will be added as part of the value for the
components's `class` attribute. These properties can be computed properties:
```app/components/my-widget.js
import Component from '@ember/component';
import { computed } from '@ember/object';
export default Component.extend({
classNames: ['my-class', 'my-other-class'],
classNameBindings: ['propertyA', 'propertyB'],
propertyA: 'from-a',
propertyB: computed(function() {
if (someLogic) { return 'from-b'; }
})
});
```
Invoking this component will produce HTML that looks like:
```html
<div id="ember1" class="ember-view my-class my-other-class from-a from-b"></div>
```
Note that `classNames` and `classNameBindings` is in addition to the `class`
attribute passed with the angle bracket invocation syntax. Therefore, if this
component was invoked like so:
```handlebars
<MyWidget class="from-invocation" />
```
The resulting HTML will look similar to this:
```html
<div id="ember1" class="from-invocation ember-view my-class my-other-class from-a from-b"></div>
```
If the value of a class name binding returns a boolean the property name
itself will be used as the class name if the property is true. The class name
will not be added if the value is `false` or `undefined`.
```app/components/my-widget.js
import Component from '@ember/component';
export default Component.extend({
classNameBindings: ['hovered'],
hovered: true
});
```
Invoking this component will produce HTML that looks like:
```html
<div id="ember1" class="ember-view hovered"></div>
```
### Custom Class Names for Boolean Values
When using boolean class name bindings you can supply a string value other
than the property name for use as the `class` HTML attribute by appending the
preferred value after a ":" character when defining the binding:
```app/components/my-widget.js
import Component from '@ember/component';
export default Component.extend({
classNameBindings: ['awesome:so-very-cool'],
awesome: true
});
```
Invoking this component will produce HTML that looks like:
```html
<div id="ember1" class="ember-view so-very-cool"></div>
```
Boolean value class name bindings whose property names are in a
camelCase-style format will be converted to a dasherized format:
```app/components/my-widget.js
import Component from '@ember/component';
export default Component.extend({
classNameBindings: ['isUrgent'],
isUrgent: true
});
```
Invoking this component will produce HTML that looks like:
```html
<div id="ember1" class="ember-view is-urgent"></div>
```
Class name bindings can also refer to object values that are found by
traversing a path relative to the component itself:
```app/components/my-widget.js
import Component from '@ember/component';
import EmberObject from '@ember/object';
export default Component.extend({
classNameBindings: ['messages.empty'],
messages: EmberObject.create({
empty: true
})
});
```
Invoking this component will produce HTML that looks like:
```html
<div id="ember1" class="ember-view empty"></div>
```
If you want to add a class name for a property which evaluates to true and
and a different class name if it evaluates to false, you can pass a binding
like this:
```app/components/my-widget.js
import Component from '@ember/component';
export default Component.extend({
classNameBindings: ['isEnabled:enabled:disabled'],
isEnabled: true
});
```
Invoking this component will produce HTML that looks like:
```html
<div id="ember1" class="ember-view enabled"></div>
```
When isEnabled is `false`, the resulting HTML representation looks like this:
```html
<div id="ember1" class="ember-view disabled"></div>
```
This syntax offers the convenience to add a class if a property is `false`:
```app/components/my-widget.js
import Component from '@ember/component';
// Applies no class when isEnabled is true and class 'disabled' when isEnabled is false
export default Component.extend({
classNameBindings: ['isEnabled::disabled'],
isEnabled: true
});
```
Invoking this component when the `isEnabled` property is true will produce
HTML that looks like:
```html
<div id="ember1" class="ember-view"></div>
```
Invoking it when the `isEnabled` property on the component is `false` will
produce HTML that looks like:
```html
<div id="ember1" class="ember-view disabled"></div>
```
Updates to the value of a class name binding will result in automatic update
of the HTML `class` attribute in the component's rendered HTML
representation. If the value becomes `false` or `undefined` the class name
will be removed.
Both `classNames` and `classNameBindings` are concatenated properties. See
[EmberObject](/ember/release/classes/EmberObject) documentation for more
information about concatenated properties.
### Other HTML Attributes
The HTML attribute section of a component's tag can be set by providing an
`attributeBindings` property set to an array of property names on the component.
The return value of these properties will be used as the value of the component's
HTML associated attribute:
```app/components/my-anchor.js
import Component from '@ember/component';
export default Component.extend({
tagName: 'a',
attributeBindings: ['href'],
href: 'http://google.com'
});
```
Invoking this component will produce HTML that looks like:
```html
<a id="ember1" class="ember-view" href="http://google.com"></a>
```
One property can be mapped on to another by placing a ":" between
the source property and the destination property:
```app/components/my-anchor.js
import Component from '@ember/component';
export default Component.extend({
tagName: 'a',
attributeBindings: ['url:href'],
url: 'http://google.com'
});
```
Invoking this component will produce HTML that looks like:
```html
<a id="ember1" class="ember-view" href="http://google.com"></a>
```
HTML attributes passed with angle bracket invocations will take precedence
over those specified in `attributeBindings`. Therefore, if this component was
invoked like so:
```handlebars
<MyAnchor href="http://bing.com" @url="http://google.com" />
```
The resulting HTML will looks like this:
```html
<a id="ember1" class="ember-view" href="http://bing.com"></a>
```
Note that the `href` attribute is ultimately set to `http://bing.com`,
despite it having attribute binidng to the `url` property, which was
set to `http://google.com`.
Namespaced attributes (e.g. `xlink:href`) are supported, but have to be
mapped, since `:` is not a valid character for properties in Javascript:
```app/components/my-use.js
import Component from '@ember/component';
export default Component.extend({
tagName: 'use',
attributeBindings: ['xlinkHref:xlink:href'],
xlinkHref: '#triangle'
});
```
Invoking this component will produce HTML that looks like:
```html
<use xlink:href="#triangle"></use>
```
If the value of a property monitored by `attributeBindings` is a boolean, the
attribute will be present or absent depending on the value:
```app/components/my-text-input.js
import Component from '@ember/component';
export default Component.extend({
tagName: 'input',
attributeBindings: ['disabled'],
disabled: false
});
```
Invoking this component will produce HTML that looks like:
```html
<input id="ember1" class="ember-view" />
```
`attributeBindings` can refer to computed properties:
```app/components/my-text-input.js
import Component from '@ember/component';
import { computed } from '@ember/object';
export default Component.extend({
tagName: 'input',
attributeBindings: ['disabled'],
disabled: computed(function() {
if (someLogic) {
return true;
} else {
return false;
}
})
});
```
To prevent setting an attribute altogether, use `null` or `undefined` as the
value of the property used in `attributeBindings`:
```app/components/my-text-input.js
import Component from '@ember/component';
export default Component.extend({
tagName: 'form',
attributeBindings: ['novalidate'],
novalidate: null
});
```
Updates to the property of an attribute binding will result in automatic
update of the HTML attribute in the component's HTML output.
`attributeBindings` is a concatenated property. See
[EmberObject](/ember/release/classes/EmberObject) documentation for more
information about concatenated properties.
## Layouts
The `layout` property can be used to dynamically specify a template associated
with a component class, instead of relying on Ember to link together a
component class and a template based on file names.
In general, applications should not use this feature, but it's commonly used
in addons for historical reasons.
The `layout` property should be set to the default export of a template
module, which is the name of a template file without the `.hbs` extension.
```app/templates/components/person-profile.hbs
<h1>Person's Title</h1>
<div class='details'>{{yield}}</div>
```
```app/components/person-profile.js
import Component from '@ember/component';
import layout from '../templates/components/person-profile';
export default Component.extend({
layout
});
```
If you invoke the component:
```handlebars
<PersonProfile>
<h2>Chief Basket Weaver</h2>
<h3>Fisherman Industries</h3>
</PersonProfile>
```
or
```handlebars
{{#person-profile}}
<h2>Chief Basket Weaver</h2>
<h3>Fisherman Industries</h3>
{{/person-profile}}
```
It will result in the following HTML output:
```html
<h1>Person's Title</h1>
<div class="details">
<h2>Chief Basket Weaver</h2>
<h3>Fisherman Industries</h3>
</div>
```
## Handling Browser Events
Components can respond to user-initiated events in one of three ways: passing
actions with angle bracket invocation, adding event handler methods to the
component's class, or adding actions to the component's template.
### Passing Actions With Angle Bracket Invocation
For one-off events specific to particular instance of a component, it is possible
to pass actions to the component's element using angle bracket invocation syntax.
```handlebars
<MyWidget {{action 'firstWidgetClicked'}} />
<MyWidget {{action 'secondWidgetClicked'}} />
```
In this case, when the first component is clicked on, Ember will invoke the
`firstWidgetClicked` action. When the second component is clicked on, Ember
will invoke the `secondWidgetClicked` action instead.
Besides `{{action}}`, it is also possible to pass any arbitrary element modifiers
using the angle bracket invocation syntax.
### Event Handler Methods
Components can also respond to user-initiated events by implementing a method
that matches the event name. This approach is appropriate when the same event
should be handled by all instances of the same component.
An event object will be passed as the argument to the event handler method.
```app/components/my-widget.js
import Component from '@ember/component';
export default Component.extend({
click(event) {
// `event.target` is either the component's element or one of its children
let tag = event.target.tagName.toLowerCase();
console.log('clicked on a `<${tag}>` HTML element!');
}
});
```
In this example, whenever the user clicked anywhere inside the component, it
will log a message to the console.
It is possible to handle event types other than `click` by implementing the
following event handler methods. In addition, custom events can be registered
by using `Application.customEvents`.
Touch events:
* `touchStart`
* `touchMove`
* `touchEnd`
* `touchCancel`
Keyboard events:
* `keyDown`
* `keyUp`
* `keyPress`
Mouse events:
* `mouseDown`
* `mouseUp`
* `contextMenu`
* `click`
* `doubleClick`
* `focusIn`
* `focusOut`
Form events:
* `submit`
* `change`
* `focusIn`
* `focusOut`
* `input`
Drag and drop events:
* `dragStart`
* `drag`
* `dragEnter`
* `dragLeave`
* `dragOver`
* `dragEnd`
* `drop`
### `{{action}}` Helper
Instead of handling all events of a particular type anywhere inside the
component's element, you may instead want to limit it to a particular
element in the component's template. In this case, it would be more
convenient to implement an action instead.
For example, you could implement the action `hello` for the `person-profile`
component:
```app/components/person-profile.js
import Component from '@ember/component';
export default Component.extend({
actions: {
hello(name) {
console.log("Hello", name);
}
}
});
```
And then use it in the component's template:
```app/templates/components/person-profile.hbs
<h1>{{@person.name}}</h1>
<button {{action 'hello' @person.name}}>
Say Hello to {{@person.name}}
</button>
```
When the user clicks the button, Ember will invoke the `hello` action,
passing in the current value of `@person.name` as an argument.
See [Ember.Templates.helpers.action](/ember/release/classes/Ember.Templates.helpers/methods/action?anchor=action).
@class Component
@extends Ember.CoreView
@uses Ember.TargetActionSupport
@uses Ember.ClassNamesSupport
@uses Ember.ActionSupport
@uses Ember.ViewMixin
@uses Ember.ViewStateSupport
@public
*/
var Component = _views.CoreView.extend(_views.ChildViewsSupport, _views.ViewStateSupport, _views.ClassNamesSupport, _runtime2.TargetActionSupport, _views.ActionSupport, _views.ViewMixin, {
isComponent: true,
init() {
this._super(...arguments);
this[IS_DISPATCHING_ATTRS] = false;
this[DIRTY_TAG] = (0, _validator.createTag)();
this[BOUNDS] = null;
var eventDispatcher = this._dispatcher;
if (eventDispatcher) {
var lazyEventsProcessedForComponentClass = lazyEventsProcessed.get(eventDispatcher);
if (!lazyEventsProcessedForComponentClass) {
lazyEventsProcessedForComponentClass = new WeakSet();
lazyEventsProcessed.set(eventDispatcher, lazyEventsProcessedForComponentClass);
}
var proto = Object.getPrototypeOf(this);
if (!lazyEventsProcessedForComponentClass.has(proto)) {
var lazyEvents = eventDispatcher.lazyEvents;
lazyEvents.forEach((mappedEventName, event) => {
if (mappedEventName !== null && typeof this[mappedEventName] === 'function') {
eventDispatcher.setupHandlerForBrowserEvent(event);
}
});
lazyEventsProcessedForComponentClass.add(proto);
}
}
if (true
/* DEBUG */
&& eventDispatcher && this.renderer._isInteractive && this.tagName === '') {
var eventNames = [];
var events = eventDispatcher.finalEventNameMapping; // tslint:disable-next-line:forin
for (var key in events) {
var methodName = events[key];
if (typeof this[methodName] === 'function') {
eventNames.push(methodName);
}
} // If in a tagless component, assert that no event handlers are defined
(true && !(!eventNames.length) && (0, _debug.assert)( // tslint:disable-next-line:max-line-length
`You can not define \`${eventNames}\` function(s) to handle DOM event in the \`${this}\` tagless component since it doesn't have any DOM element.`, !eventNames.length));
}
},
get _dispatcher() {
if (this.__dispatcher === undefined) {
var owner = (0, _owner2.getOwner)(this);
if (owner.lookup('-environment:main').isInteractive) {
this.__dispatcher = owner.lookup('event_dispatcher:main');
} else {
// In FastBoot we have no EventDispatcher. Set to null to not try again to look it up.
this.__dispatcher = null;
}
}
return this.__dispatcher;
},
on(eventName) {
var _a;
(_a = this._dispatcher) === null || _a === void 0 ? void 0 : _a.setupHandlerForEmberEvent(eventName);
return this._super(...arguments);
},
rerender() {
(0, _validator.dirtyTag)(this[DIRTY_TAG]);
this._super();
},
[_metal.PROPERTY_DID_CHANGE](key, value) {
if (this[IS_DISPATCHING_ATTRS]) {
return;
}
var args = this[ARGS];
var reference = args !== undefined ? args[key] : undefined;
if (reference !== undefined && (0, _reference.isUpdatableRef)(reference)) {
(0, _reference.updateRef)(reference, arguments.length === 2 ? value : (0, _metal.get)(this, key));
}
},
getAttr(key) {
// TODO Intimate API should be deprecated
return this.get(key);
},
/**
Normally, Ember's component model is "write-only". The component takes a
bunch of attributes that it got passed in, and uses them to render its
template.
One nice thing about this model is that if you try to set a value to the
same thing as last time, Ember (through HTMLBars) will avoid doing any
work on the DOM.
This is not just a performance optimization. If an attribute has not
changed, it is important not to clobber the element's "hidden state".
For example, if you set an input's `value` to the same value as before,
it will clobber selection state and cursor position. In other words,
setting an attribute is not **always** idempotent.
This method provides a way to read an element's attribute and also
update the last value Ember knows about at the same time. This makes
setting an attribute idempotent.
In particular, what this means is that if you get an `<input>` element's
`value` attribute and then re-render the template with the same value,
it will avoid clobbering the cursor and selection position.
Since most attribute sets are idempotent in the browser, you typically
can get away with reading attributes using jQuery, but the most reliable
way to do so is through this method.
@method readDOMAttr
@param {String} name the name of the attribute
@return String
@public
*/
readDOMAttr(name) {
// TODO revisit this
var _element = (0, _views.getViewElement)(this);
(true && !(_element !== null) && (0, _debug.assert)(`Cannot call \`readDOMAttr\` on ${this} which does not have an element`, _element !== null));
var element = _element;
var isSVG = element.namespaceURI === "http://www.w3.org/2000/svg"
/* SVG */
;
var {
type,
normalized
} = (0, _runtime.normalizeProperty)(element, name);
if (isSVG || type === 'attr') {
return element.getAttribute(normalized);
}
return element[normalized];
},
/**
The WAI-ARIA role of the control represented by this view. For example, a
button may have a role of type 'button', or a pane may have a role of
type 'alertdialog'. This property is used by assistive software to help
visually challenged users navigate rich web applications.
The full list of valid WAI-ARIA roles is available at:
[https://www.w3.org/TR/wai-aria/#roles_categorization](https://www.w3.org/TR/wai-aria/#roles_categorization)
@property ariaRole
@type String
@default null
@public
*/
/**
Enables components to take a list of parameters as arguments.
For example, a component that takes two parameters with the names
`name` and `age`:
```app/components/my-component.js
import Component from '@ember/component';
let MyComponent = Component.extend();
MyComponent.reopenClass({
positionalParams: ['name', 'age']
});
export default MyComponent;
```
It can then be invoked like this:
```hbs
{{my-component "John" 38}}
```
The parameters can be referred to just like named parameters:
```hbs
Name: {{name}}, Age: {{age}}.
```
Using a string instead of an array allows for an arbitrary number of
parameters:
```app/components/my-component.js
import Component from '@ember/component';
let MyComponent = Component.extend();
MyComponent.reopenClass({
positionalParams: 'names'
});
export default MyComponent;
```
It can then be invoked like this:
```hbs
{{my-component "John" "Michael" "Scott"}}
```
The parameters can then be referred to by enumerating over the list:
```hbs
{{#each names as |name|}}{{name}}{{/each}}
```
@static
@public
@property positionalParams
@since 1.13.0
*/
/**
Called when the attributes passed into the component have been updated.
Called both during the initial render of a container and during a rerender.
Can be used in place of an observer; code placed here will be executed
every time any attribute updates.
@method didReceiveAttrs
@public
@since 1.13.0
*/
didReceiveAttrs() {},
/**
Called when the attributes passed into the component have been updated.
Called both during the initial render of a container and during a rerender.
Can be used in place of an observer; code placed here will be executed
every time any attribute updates.
@event didReceiveAttrs
@public
@since 1.13.0
*/
/**
Called after a component has been rendered, both on initial render and
in subsequent rerenders.
@method didRender
@public
@since 1.13.0
*/
didRender() {},
/**
Called after a component has been rendered, both on initial render and
in subsequent rerenders.
@event didRender
@public
@since 1.13.0
*/
/**
Called before a component has been rendered, both on initial render and
in subsequent rerenders.
@method willRender
@public
@since 1.13.0
*/
willRender() {},
/**
Called before a component has been rendered, both on initial render and
in subsequent rerenders.
@event willRender
@public
@since 1.13.0
*/
/**
Called when the attributes passed into the component have been changed.
Called only during a rerender, not during an initial render.
@method didUpdateAttrs
@public
@since 1.13.0
*/
didUpdateAttrs() {},
/**
Called when the attributes passed into the component have been changed.
Called only during a rerender, not during an initial render.
@event didUpdateAttrs
@public
@since 1.13.0
*/
/**
Called when the component is about to update and rerender itself.
Called only during a rerender, not during an initial render.
@method willUpdate
@public
@since 1.13.0
*/
willUpdate() {},
/**
Called when the component is about to update and rerender itself.
Called only during a rerender, not during an initial render.
@event willUpdate
@public
@since 1.13.0
*/
/**
Called when the component has updated and rerendered itself.
Called only during a rerender, not during an initial render.
@method didUpdate
@public
@since 1.13.0
*/
didUpdate() {}
});
_exports.Component = Component;
Component.toString = () => '@ember/component';
Component.reopenClass({
isComponentFactory: true,
positionalParams: []
});
(0, _manager2.setInternalComponentManager)(CURLY_COMPONENT_MANAGER, Component);
/**
@module @ember/component
*/
var RECOMPUTE_TAG = (0, _utils.symbol)('RECOMPUTE_TAG');
/**
Ember Helpers are functions that can compute values, and are used in templates.
For example, this code calls a helper named `format-currency`:
```app/templates/application.hbs
<Cost @cents={{230}} />
```
```app/components/cost.hbs
<div>{{format-currency @cents currency="$"}}</div>
```
Additionally a helper can be called as a nested helper.
In this example, we show the formatted currency value if the `showMoney`
named argument is truthy.
```handlebars
{{if @showMoney (format-currency @cents currency="$")}}
```
Helpers defined using a class must provide a `compute` function. For example:
```app/helpers/format-currency.js
import Helper from '@ember/component/helper';
export default class extends Helper {
compute([cents], { currency }) {
return `${currency}${cents * 0.01}`;
}
}
```
Each time the input to a helper changes, the `compute` function will be
called again.
As instances, these helpers also have access to the container and will accept
injected dependencies.
Additionally, class helpers can call `recompute` to force a new computation.
@class Helper
@extends CoreObject
@public
@since 1.13.0
*/
var Helper = _runtime2.FrameworkObject.extend({
init() {
this._super(...arguments);
this[RECOMPUTE_TAG] = (0, _validator.createTag)();
},
/**
On a class-based helper, it may be useful to force a recomputation of that
helpers value. This is akin to `rerender` on a component.
For example, this component will rerender when the `currentUser` on a
session service changes:
```app/helpers/current-user-email.js
import Helper from '@ember/component/helper'
import { inject as service } from '@ember/service'
import { observer } from '@ember/object'
export default Helper.extend({
session: service(),
onNewUser: observer('session.currentUser', function() {
this.recompute();
}),
compute() {
return this.get('session.currentUser.email');
}
});
```
@method recompute
@public
@since 1.13.0
*/
recompute() {
(0, _runloop.join)(() => (0, _validator.dirtyTag)(this[RECOMPUTE_TAG]));
}
});
_exports.Helper = Helper;
var IS_CLASSIC_HELPER = (0, _utils.symbol)('IS_CLASSIC_HELPER');
Helper.isHelperFactory = true;
Helper[IS_CLASSIC_HELPER] = true;
function isClassicHelper(obj) {
return obj[IS_CLASSIC_HELPER] === true;
}
class ClassicHelperManager {
constructor(owner) {
this.capabilities = (0, _manager2.helperCapabilities)('3.23', {
hasValue: true,
hasDestroyable: true
});
var ownerInjection = {};
(0, _owner2.setOwner)(ownerInjection, owner);
this.ownerInjection = ownerInjection;
}
createHelper(definition, args) {
var instance = definition.class === undefined ? definition.create(this.ownerInjection) : definition.create();
return {
instance,
args
};
}
getDestroyable({
instance
}) {
return instance;
}
getValue({
instance,
args
}) {
var {
positional,
named
} = args;
var ret = instance.compute(positional, named);
(0, _validator.consumeTag)(instance[RECOMPUTE_TAG]);
return ret;
}
getDebugName(definition) {
return (0, _utils.getDebugName)(definition.class['prototype']);
}
}
(0, _manager2.setHelperManager)(owner => {
return new ClassicHelperManager(owner);
}, Helper);
var CLASSIC_HELPER_MANAGER = (0, _manager2.getInternalHelperManager)(Helper); ///////////
class Wrapper {
constructor(compute) {
this.compute = compute;
this.isHelperFactory = true;
}
create() {
// needs new instance or will leak containers
return {
compute: this.compute
};
}
}
class SimpleClassicHelperManager {
constructor() {
this.capabilities = (0, _manager2.helperCapabilities)('3.23', {
hasValue: true
});
}
createHelper(definition, args) {
var {
compute
} = definition;
return () => compute.call(null, args.positional, args.named);
}
getValue(fn$$1) {
return fn$$1();
}
getDebugName(definition) {
return (0, _utils.getDebugName)(definition.compute);
}
}
var SIMPLE_CLASSIC_HELPER_MANAGER = new SimpleClassicHelperManager();
(0, _manager2.setHelperManager)(() => SIMPLE_CLASSIC_HELPER_MANAGER, Wrapper.prototype);
/**
In many cases it is not necessary to use the full `Helper` class.
The `helper` method create pure-function helpers without instances.
For example:
```app/helpers/format-currency.js
import { helper } from '@ember/component/helper';
export default helper(function([cents], {currency}) {
return `${currency}${cents * 0.01}`;
});
```
@static
@param {Function} helper The helper function
@method helper
@for @ember/component/helper
@public
@since 1.13.0
*/
function helper(helperFn) {
return new Wrapper(helperFn);
}
/**
@module @ember/template
*/
class SafeString {
constructor(string) {
this.string = string;
}
toString() {
return `${this.string}`;
}
toHTML() {
return this.toString();
}
}
_exports.SafeString = SafeString;
var escape = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#x27;',
'`': '&#x60;',
'=': '&#x3D;'
};
var possible = /[&<>"'`=]/;
var badChars = /[&<>"'`=]/g;
function escapeChar(chr) {
return escape[chr];
}
function escapeExpression(string) {
if (typeof string !== 'string') {
// don't escape SafeStrings, since they're already safe
if (string && string.toHTML) {
return string.toHTML();
} else if (string === null || string === undefined) {
return '';
} else if (!string) {
return String(string);
} // Force a string conversion as this will be done by the append regardless and
// the regex test will do this transparently behind the scenes, causing issues if
// an object's to string has escaped characters in it.
string = String(string);
}
if (!possible.test(string)) {
return string;
}
return string.replace(badChars, escapeChar);
}
/**
Mark a string as safe for unescaped output with Ember templates. If you
return HTML from a helper, use this function to
ensure Ember's rendering layer does not escape the HTML.
```javascript
import { htmlSafe } from '@ember/template';
htmlSafe('<div>someString</div>')
```
@method htmlSafe
@for @ember/template
@static
@return {SafeString} A string that will not be HTML escaped by Handlebars.
@public
*/
function htmlSafe(str) {
if (str === null || str === undefined) {
str = '';
} else if (typeof str !== 'string') {
str = String(str);
}
return new SafeString(str);
}
/**
Detects if a string was decorated using `htmlSafe`.
```javascript
import { htmlSafe, isHTMLSafe } from '@ember/template';
var plainString = 'plain string',
safeString = htmlSafe('<div>someValue</div>');
isHTMLSafe(plainString); // false
isHTMLSafe(safeString); // true
```
@method isHTMLSafe
@for @ember/template
@static
@return {Boolean} `true` if the string was decorated with `htmlSafe`, `false` otherwise.
@public
*/
function isHTMLSafe$1(str) {
return str !== null && typeof str === 'object' && typeof str.toHTML === 'function';
}
function instrumentationPayload(def) {
return {
object: `${def.name}:${def.outlet}`
};
}
var CAPABILITIES$1 = {
dynamicLayout: false,
dynamicTag: false,
prepareArgs: false,
createArgs: false,
attributeHook: false,
elementHook: false,
createCaller: false,
dynamicScope: true,
updateHook: false,
createInstance: true,
wrapped: false,
willDestroy: false,
hasSubOwner: false
};
class OutletComponentManager {
create(_owner, definition, _args, env, dynamicScope) {
var parentStateRef = dynamicScope.get('outletState');
var currentStateRef = definition.ref;
dynamicScope.set('outletState', currentStateRef);
var state = {
self: (0, _reference.createConstRef)(definition.controller, 'this'),
finalize: (0, _instrumentation._instrumentStart)('render.outlet', instrumentationPayload, definition)
};
if (env.debugRenderTree !== undefined) {
state.outlet = {
name: definition.outlet
};
var parentState = (0, _reference.valueForRef)(parentStateRef);
var parentOwner = parentState && parentState.render && parentState.render.owner;
var currentOwner = (0, _reference.valueForRef)(currentStateRef).render.owner;
if (parentOwner && parentOwner !== currentOwner) {
var engine = currentOwner;
(true && !(typeof currentOwner.mountPoint === 'string') && (0, _debug.assert)('invalid engine: missing mountPoint', typeof currentOwner.mountPoint === 'string'));
(true && !(currentOwner.routable === true) && (0, _debug.assert)('invalid engine: missing routable', currentOwner.routable === true));
var mountPoint = engine.mountPoint;
state.engine = engine;
state.engineBucket = {
mountPoint
};
}
}
return state;
}
getDebugName({
name
}) {
return name;
}
getDebugCustomRenderTree(definition, state, args) {
var nodes = [];
if (state.outlet) {
nodes.push({
bucket: state.outlet,
type: 'outlet',
name: state.outlet.name,
args: _runtime.EMPTY_ARGS,
instance: undefined,
template: undefined
});
}
if (state.engineBucket) {
nodes.push({
bucket: state.engineBucket,
type: 'engine',
name: state.engineBucket.mountPoint,
args: _runtime.EMPTY_ARGS,
instance: state.engine,
template: undefined
});
}
nodes.push({
bucket: state,
type: 'route-template',
name: definition.name,
args: args,
instance: definition.controller,
template: (0, _util.unwrapTemplate)(definition.template).moduleName
});
return nodes;
}
getCapabilities() {
return CAPABILITIES$1;
}
getSelf({
self
}) {
return self;
}
didCreate() {}
didUpdate() {}
didRenderLayout(state) {
state.finalize();
}
didUpdateLayout() {}
getDestroyable() {
return null;
}
}
var OUTLET_MANAGER = new OutletComponentManager();
class OutletComponentDefinition {
constructor(state, manager = OUTLET_MANAGER) {
this.state = state;
this.manager = manager; // handle is not used by this custom definition
this.handle = -1;
var capabilities = manager.getCapabilities();
this.capabilities = (0, _manager2.capabilityFlagsFrom)(capabilities);
this.compilable = capabilities.wrapped ? (0, _util.unwrapTemplate)(state.template).asWrappedLayout() : (0, _util.unwrapTemplate)(state.template).asLayout();
this.resolvedName = state.name;
}
}
function createRootOutlet(outletView) {
if (_environment2.ENV._APPLICATION_TEMPLATE_WRAPPER) {
var WRAPPED_CAPABILITIES = Object.assign({}, CAPABILITIES$1, {
dynamicTag: true,
elementHook: true,
wrapped: true
});
var WrappedOutletComponentManager = class extends OutletComponentManager {
getTagName() {
return 'div';
}
getCapabilities() {
return WRAPPED_CAPABILITIES;
}
didCreateElement(component, element) {
// to add GUID id and class
element.setAttribute('class', 'ember-view');
element.setAttribute('id', (0, _utils.guidFor)(component));
}
};
var WRAPPED_OUTLET_MANAGER = new WrappedOutletComponentManager();
return new OutletComponentDefinition(outletView.state, WRAPPED_OUTLET_MANAGER);
} else {
return new OutletComponentDefinition(outletView.state);
}
}
class RootComponentManager extends CurlyComponentManager {
constructor(component) {
super();
this.component = component;
}
create(_owner, _state, _args, {
isInteractive
}, dynamicScope) {
var component = this.component;
var finalizer = (0, _instrumentation._instrumentStart)('render.component', initialRenderInstrumentDetails, component);
dynamicScope.view = component;
var hasWrappedElement = component.tagName !== ''; // We usually do this in the `didCreateElement`, but that hook doesn't fire for tagless components
if (!hasWrappedElement) {
if (isInteractive) {
component.trigger('willRender');
}
component._transitionTo('hasElement');
if (isInteractive) {
component.trigger('willInsertElement');
}
}
if (true
/* DEBUG */
) {
processComponentInitializationAssertions(component, {});
}
var bucket = new ComponentStateBucket(component, null, _validator.CONSTANT_TAG, finalizer, hasWrappedElement, isInteractive);
(0, _validator.consumeTag)(component[DIRTY_TAG]);
return bucket;
}
} // ROOT is the top-level template it has nothing but one yield.
// it is supposed to have a dummy element
var ROOT_CAPABILITIES = {
dynamicLayout: true,
dynamicTag: true,
prepareArgs: false,
createArgs: false,
attributeHook: true,
elementHook: true,
createCaller: true,
dynamicScope: true,
updateHook: true,
createInstance: true,
wrapped: true,
willDestroy: false,
hasSubOwner: false
};
class RootComponentDefinition {
constructor(component) {
// handle is not used by this custom definition
this.handle = -1;
this.resolvedName = '-top-level';
this.capabilities = (0, _manager2.capabilityFlagsFrom)(ROOT_CAPABILITIES);
this.compilable = null;
this.manager = new RootComponentManager(component);
this.state = (0, _container.getFactoryFor)(component);
}
}
/**
@module ember
*/
/**
The `{{#each}}` helper loops over elements in a collection. It is an extension
of the base Handlebars `{{#each}}` helper.
The default behavior of `{{#each}}` is to yield its inner block once for every
item in an array passing the item as the first block parameter.
Assuming the `@developers` argument contains this array:
```javascript
[{ name: 'Yehuda' },{ name: 'Tom' }, { name: 'Paul' }];
```
```handlebars
<ul>
{{#each @developers as |person|}}
<li>Hello, {{person.name}}!</li>
{{/each}}
</ul>
```
The same rules apply to arrays of primitives.
```javascript
['Yehuda', 'Tom', 'Paul']
```
```handlebars
<ul>
{{#each @developerNames as |name|}}
<li>Hello, {{name}}!</li>
{{/each}}
</ul>
```
During iteration, the index of each item in the array is provided as a second block
parameter.
```handlebars
<ul>
{{#each @developers as |person index|}}
<li>Hello, {{person.name}}! You're number {{index}} in line</li>
{{/each}}
</ul>
```
### Specifying Keys
In order to improve rendering speed, Ember will try to reuse the DOM elements
where possible. Specifically, if the same item is present in the array both
before and after the change, its DOM output will be reused.
The `key` option is used to tell Ember how to determine if the items in the
array being iterated over with `{{#each}}` has changed between renders. By
default the item's object identity is used.
This is usually sufficient, so in most cases, the `key` option is simply not
needed. However, in some rare cases, the objects' identities may change even
though they represent the same underlying data.
For example:
```javascript
people.map(person => {
return { ...person, type: 'developer' };
});
```
In this case, each time the `people` array is `map`-ed over, it will produce
an new array with completely different objects between renders. In these cases,
you can help Ember determine how these objects related to each other with the
`key` option:
```handlebars
<ul>
{{#each @developers key="name" as |person|}}
<li>Hello, {{person.name}}!</li>
{{/each}}
</ul>
```
By doing so, Ember will use the value of the property specified (`person.name`
in the example) to find a "match" from the previous render. That is, if Ember
has previously seen an object from the `@developers` array with a matching
name, its DOM elements will be re-used.
There are two special values for `key`:
* `@index` - The index of the item in the array.
* `@identity` - The item in the array itself.
### {{else}} condition
`{{#each}}` can have a matching `{{else}}`. The contents of this block will render
if the collection is empty.
```handlebars
<ul>
{{#each @developers as |person|}}
<li>{{person.name}} is available!</li>
{{else}}
<li>Sorry, nobody is available for this task.</li>
{{/each}}
</ul>
```
@method each
@for Ember.Templates.helpers
@public
*/
/**
The `{{each-in}}` helper loops over properties on an object.
For example, given this component definition:
```app/components/developer-details.js
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
export default class extends Component {
@tracked developer = {
"name": "Shelly Sails",
"age": 42
};
}
```
This template would display all properties on the `developer`
object in a list:
```app/components/developer-details.hbs
<ul>
{{#each-in this.developer as |key value|}}
<li>{{key}}: {{value}}</li>
{{/each-in}}
</ul>
```
Outputting their name and age:
```html
<ul>
<li>name: Shelly Sails</li>
<li>age: 42</li>
</ul>
```
@method each-in
@for Ember.Templates.helpers
@public
@since 2.1.0
*/
class EachInWrapper {
constructor(inner) {
this.inner = inner;
}
}
var eachIn = internalHelper(({
positional
}) => {
var inner = positional[0];
return (0, _reference.createComputeRef)(() => {
var iterable = (0, _reference.valueForRef)(inner);
(0, _validator.consumeTag)((0, _metal.tagForObject)(iterable));
if ((0, _utils.isProxy)(iterable)) {
// this is because the each-in doesn't actually get(proxy, 'key') but bypasses it
// and the proxy's tag is lazy updated on access
iterable = (0, _runtime2._contentFor)(iterable);
}
return new EachInWrapper(iterable);
});
});
function toIterator(iterable) {
if (iterable instanceof EachInWrapper) {
return toEachInIterator(iterable.inner);
} else {
return toEachIterator(iterable);
}
}
function toEachInIterator(iterable) {
if (!isIndexable(iterable)) {
return null;
}
if (Array.isArray(iterable) || (0, _utils.isEmberArray)(iterable)) {
return ObjectIterator.fromIndexable(iterable);
} else if (isNativeIterable(iterable)) {
return MapLikeNativeIterator.from(iterable);
} else if (hasForEach(iterable)) {
return ObjectIterator.fromForEachable(iterable);
} else {
return ObjectIterator.fromIndexable(iterable);
}
}
function toEachIterator(iterable) {
if (!(0, _utils.isObject)(iterable)) {
return null;
}
if (Array.isArray(iterable)) {
return ArrayIterator.from(iterable);
} else if ((0, _utils.isEmberArray)(iterable)) {
return EmberArrayIterator.from(iterable);
} else if (isNativeIterable(iterable)) {
return ArrayLikeNativeIterator.from(iterable);
} else if (hasForEach(iterable)) {
return ArrayIterator.fromForEachable(iterable);
} else {
return null;
}
}
class BoundedIterator {
constructor(length) {
this.length = length;
this.position = 0;
}
isEmpty() {
return false;
}
memoFor(position) {
return position;
}
next() {
var {
length,
position
} = this;
if (position >= length) {
return null;
}
var value = this.valueFor(position);
var memo = this.memoFor(position);
this.position++;
return {
value,
memo
};
}
}
class ArrayIterator extends BoundedIterator {
constructor(array$$1) {
super(array$$1.length);
this.array = array$$1;
}
static from(iterable) {
return iterable.length > 0 ? new this(iterable) : null;
}
static fromForEachable(object) {
var array$$1 = [];
object.forEach(item => array$$1.push(item));
return this.from(array$$1);
}
valueFor(position) {
return this.array[position];
}
}
class EmberArrayIterator extends BoundedIterator {
constructor(array$$1) {
super(array$$1.length);
this.array = array$$1;
}
static from(iterable) {
return iterable.length > 0 ? new this(iterable) : null;
}
valueFor(position) {
return (0, _metal.objectAt)(this.array, position);
}
}
class ObjectIterator extends BoundedIterator {
constructor(keys, values) {
super(values.length);
this.keys = keys;
this.values = values;
}
static fromIndexable(obj) {
var keys = Object.keys(obj);
var {
length
} = keys;
if (length === 0) {
return null;
} else {
var values = [];
for (var i = 0; i < length; i++) {
var value = void 0;
var key = keys[i];
value = obj[key]; // Add the tag of the returned value if it is an array, since arrays
// should always cause updates if they are consumed and then changed
if ((0, _validator.isTracking)()) {
(0, _validator.consumeTag)((0, _validator.tagFor)(obj, key));
if (Array.isArray(value)) {
(0, _validator.consumeTag)((0, _validator.tagFor)(value, '[]'));
}
}
values.push(value);
}
return new this(keys, values);
}
}
static fromForEachable(obj) {
var keys = [];
var values = [];
var length = 0;
var isMapLike = false; // Not using an arrow function here so we can get an accurate `arguments`
obj.forEach(function (value, key) {
isMapLike = isMapLike || arguments.length >= 2;
if (isMapLike) {
keys.push(key);
}
values.push(value);
length++;
});
if (length === 0) {
return null;
} else if (isMapLike) {
return new this(keys, values);
} else {
return new ArrayIterator(values);
}
}
valueFor(position) {
return this.values[position];
}
memoFor(position) {
return this.keys[position];
}
}
class NativeIterator {
constructor(iterable, result) {
this.iterable = iterable;
this.result = result;
this.position = 0;
}
static from(iterable) {
var iterator = iterable[Symbol.iterator]();
var result = iterator.next();
var {
done
} = result;
if (done) {
return null;
} else {
return new this(iterator, result);
}
}
isEmpty() {
return false;
}
next() {
var {
iterable,
result,
position
} = this;
if (result.done) {
return null;
}
var value = this.valueFor(result, position);
var memo = this.memoFor(result, position);
this.position++;
this.result = iterable.next();
return {
value,
memo
};
}
}
class ArrayLikeNativeIterator extends NativeIterator {
valueFor(result) {
return result.value;
}
memoFor(_result, position) {
return position;
}
}
class MapLikeNativeIterator extends NativeIterator {
valueFor(result) {
return result.value[1];
}
memoFor(result) {
return result.value[0];
}
}
function hasForEach(value) {
return typeof value['forEach'] === 'function';
}
function isNativeIterable(value) {
return typeof value[Symbol.iterator] === 'function';
}
function isIndexable(value) {
return value !== null && (typeof value === 'object' || typeof value === 'function');
}
function toBool(predicate) {
if ((0, _utils.isProxy)(predicate)) {
(0, _validator.consumeTag)((0, _metal.tagForProperty)(predicate, 'content'));
return Boolean((0, _metal.get)(predicate, 'isTruthy'));
} else if ((0, _runtime2.isArray)(predicate)) {
(0, _validator.consumeTag)((0, _metal.tagForProperty)(predicate, '[]'));
return predicate.length !== 0;
} else if ((0, _glimmer.isHTMLSafe)(predicate)) {
return Boolean(predicate.toString());
} else {
return Boolean(predicate);
}
} // Setup global context
(0, _globalContext.default)({
scheduleRevalidate() {
_runloop._backburner.ensureInstance();
},
toBool,
toIterator,
getProp: _metal._getProp,
setProp: _metal._setProp,
getPath: _metal.get,
setPath: _metal.set,
scheduleDestroy(destroyable, destructor) {
(0, _runloop.schedule)('actions', null, destructor, destroyable);
},
scheduleDestroyed(finalizeDestructor) {
(0, _runloop.schedule)('destroy', null, finalizeDestructor);
},
warnIfStyleNotTrusted(value) {
(true && (0, _debug.warn)((0, _views.constructStyleDeprecationMessage)(value), (() => {
if (value === null || value === undefined || isHTMLSafe$1(value)) {
return true;
}
return false;
})(), {
id: 'ember-htmlbars.style-xss-warning'
}));
},
assert(test, msg, options) {
var _a;
if (true
/* DEBUG */
) {
var id = options === null || options === void 0 ? void 0 : options.id;
var override = VM_ASSERTION_OVERRIDES.filter(o => o.id === id)[0];
(true && !(test) && (0, _debug.assert)((_a = override === null || override === void 0 ? void 0 : override.message) !== null && _a !== void 0 ? _a : msg, test));
}
},
deprecate(msg, test, options) {
var _a;
if (true
/* DEBUG */
) {
var {
id
} = options;
if (id === 'argument-less-helper-paren-less-invocation') {
throw new Error(`A resolved helper cannot be passed as a named argument as the syntax is ` + `ambiguously a pass-by-reference or invocation. Use the ` + `\`{{helper 'foo-helper}}\` helper to pass by reference or explicitly ` + `invoke the helper with parens: \`{{(fooHelper)}}\`.`);
}
var override = VM_DEPRECATION_OVERRIDES.filter(o => o.id === id)[0];
if (!override) throw new Error(`deprecation override for ${id} not found`); // allow deprecations to be disabled in the VM_DEPRECATION_OVERRIDES array below
if (!override.disabled) {
(true && !(Boolean(test)) && (0, _debug.deprecate)((_a = override.message) !== null && _a !== void 0 ? _a : msg, Boolean(test), override));
}
}
}
});
if (true
/* DEBUG */
) {
_validator.setTrackingTransactionEnv === null || _validator.setTrackingTransactionEnv === void 0 ? void 0 : (0, _validator.setTrackingTransactionEnv)({
debugMessage(obj, keyName) {
var dirtyString = keyName ? `\`${keyName}\` on \`${_utils.getDebugName === null || _utils.getDebugName === void 0 ? void 0 : (0, _utils.getDebugName)(obj)}\`` : `\`${_utils.getDebugName === null || _utils.getDebugName === void 0 ? void 0 : (0, _utils.getDebugName)(obj)}\``;
return `You attempted to update ${dirtyString}, but it had already been used previously in the same computation. Attempting to update a value after using it in a computation can cause logical errors, infinite revalidation bugs, and performance issues, and is not supported.`;
}
});
} ///////////
// VM Assertion/Deprecation overrides
var VM_DEPRECATION_OVERRIDES = [{
id: 'setting-on-hash',
until: '4.4.0',
for: 'ember-source',
since: {
enabled: '3.28.0'
}
}];
var VM_ASSERTION_OVERRIDES = []; ///////////
// Define environment delegate
class EmberEnvironmentDelegate {
constructor(owner, isInteractive) {
this.owner = owner;
this.isInteractive = isInteractive;
this.enableDebugTooling = _environment2.ENV._DEBUG_RENDER_TREE;
}
onTransactionCommit() {}
}
/**
@module ember
*/
var disallowDynamicResolution = internalHelper(({
positional,
named
}) => {
(true && !(positional.length === 1) && (0, _debug.assert)(`[BUG] wrong number of positional arguments, expecting 1, got ${positional.length}`, positional.length === 1));
var nameOrValueRef = positional[0];
(true && !('type' in named) && (0, _debug.assert)(`[BUG] expecting \`type\` named argument`, 'type' in named));
(true && !('loc' in named) && (0, _debug.assert)(`[BUG] expecting \`loc\` named argument`, 'loc' in named));
(true && !('original' in named) && (0, _debug.assert)(`[BUG] expecting \`original\` named argument`, 'original' in named));
var typeRef = named.type;
var locRef = named.loc;
var originalRef = named.original; // Bug: why do these fail?
// assert('[BUG] expecting a string literal for the `type` argument', isConstRef(typeRef));
// assert('[BUG] expecting a string literal for the `loc` argument', isConstRef(locRef));
// assert('[BUG] expecting a string literal for the `original` argument', isConstRef(originalRef));
var type = (0, _reference.valueForRef)(typeRef);
var loc = (0, _reference.valueForRef)(locRef);
var original = (0, _reference.valueForRef)(originalRef);
(true && !(typeof type === 'string') && (0, _debug.assert)('[BUG] expecting a string literal for the `type` argument', typeof type === 'string'));
(true && !(typeof loc === 'string') && (0, _debug.assert)('[BUG] expecting a string literal for the `loc` argument', typeof loc === 'string'));
(true && !(typeof original === 'string') && (0, _debug.assert)('[BUG] expecting a string literal for the `original` argument', typeof original === 'string'));
return (0, _reference.createComputeRef)(() => {
var nameOrValue = (0, _reference.valueForRef)(nameOrValueRef);
(true && !(typeof nameOrValue !== 'string') && (0, _debug.assert)(`Passing a dynamic string to the \`(${type})\` keyword is disallowed. ` + `(You specified \`(${type} ${original})\` and \`${original}\` evaluated into "${nameOrValue}".) ` + `This ensures we can statically analyze the template and determine which ${type}s are used. ` + `If the ${type} name is always the same, use a string literal instead, i.e. \`(${type} "${nameOrValue}")\`. ` + `Otherwise, import the ${type}s into JavaScript and pass them to the ${type} keyword. ` + 'See https://github.com/emberjs/rfcs/blob/master/text/0496-handlebars-strict-mode.md#4-no-dynamic-resolution for details. ' + loc, typeof nameOrValue !== 'string'));
return nameOrValue;
});
});
var helper$1;
if (true
/* DEBUG */
) {
helper$1 = args => {
var inner = args.positional[0];
return (0, _reference.createComputeRef)(() => {
var value = (0, _reference.valueForRef)(inner);
(true && !(value !== null && value !== undefined) && (0, _debug.assert)('You cannot pass a null or undefined destination element to in-element', value !== null && value !== undefined));
return value;
});
};
} else {
helper$1 = args => args.positional[0];
}
var inElementNullCheckHelper = internalHelper(helper$1);
var normalizeClassHelper = internalHelper(({
positional
}) => {
return (0, _reference.createComputeRef)(() => {
var classNameParts = (0, _reference.valueForRef)(positional[0]).split('.');
var className = classNameParts[classNameParts.length - 1];
var value = (0, _reference.valueForRef)(positional[1]);
if (value === true) {
return (0, _string.dasherize)(className);
} else if (!value && value !== 0) {
return '';
} else {
return String(value);
}
});
});
var resolve = internalHelper(({
positional
}, owner) => {
var _a; // why is this allowed to be undefined in the first place?
(true && !(owner) && (0, _debug.assert)('[BUG] missing owner', owner));
(true && !(positional.length === 1) && (0, _debug.assert)(`[BUG] wrong number of positional arguments, expecting 1, got ${positional.length}`, positional.length === 1));
var fullNameRef = positional[0];
(true && !((0, _reference.isConstRef)(fullNameRef)) && (0, _debug.assert)('[BUG] expecting a string literal as argument', (0, _reference.isConstRef)(fullNameRef)));
var fullName = (0, _reference.valueForRef)(fullNameRef);
(true && !(typeof fullName === 'string') && (0, _debug.assert)('[BUG] expecting a string literal as argument', typeof fullName === 'string'));
(true && !(fullName.split(':').length === 2) && (0, _debug.assert)('[BUG] expecting a valid full name', fullName.split(':').length === 2));
if (true
/* DEBUG */
) {
var [type, name] = fullName.split(':');
(true && !(owner.hasRegistration(fullName)) && (0, _debug.assert)(`Attempted to invoke \`(-resolve "${fullName}")\`, but ${name} was not a valid ${type} name.`, owner.hasRegistration(fullName)));
}
return (0, _reference.createConstRef)((_a = owner.factoryFor(fullName)) === null || _a === void 0 ? void 0 : _a.class, `(-resolve "${fullName}")`);
});
/**
@module ember
*/
/**
This reference is used to get the `[]` tag of iterables, so we can trigger
updates to `{{each}}` when it changes. It is put into place by a template
transform at build time, similar to the (-each-in) helper
*/
var trackArray = internalHelper(({
positional
}) => {
var inner = positional[0];
return (0, _reference.createComputeRef)(() => {
var iterable = (0, _reference.valueForRef)(inner);
if ((0, _utils.isObject)(iterable)) {
(0, _validator.consumeTag)((0, _metal.tagForProperty)(iterable, '[]'));
}
return iterable;
});
});
/**
@module ember
*/
/**
The `mut` helper lets you __clearly specify__ that a child `Component` can update the
(mutable) value passed to it, which will __change the value of the parent component__.
To specify that a parameter is mutable, when invoking the child `Component`:
```handlebars
<MyChild @childClickCount={{fn (mut totalClicks)}} />
```
or
```handlebars
{{my-child childClickCount=(mut totalClicks)}}
```
The child `Component` can then modify the parent's value just by modifying its own
property:
```javascript
// my-child.js
export default Component.extend({
click() {
this.incrementProperty('childClickCount');
}
});
```
Note that for curly components (`{{my-component}}`) the bindings are already mutable,
making the `mut` unnecessary.
Additionally, the `mut` helper can be combined with the `fn` helper to
mutate a value. For example:
```handlebars
<MyChild @childClickCount={{this.totalClicks}} @click-count-change={{fn (mut totalClicks))}} />
```
or
```handlebars
{{my-child childClickCount=totalClicks click-count-change=(fn (mut totalClicks))}}
```
The child `Component` would invoke the function with the new click value:
```javascript
// my-child.js
export default Component.extend({
click() {
this.get('click-count-change')(this.get('childClickCount') + 1);
}
});
```
The `mut` helper changes the `totalClicks` value to what was provided as the `fn` argument.
The `mut` helper, when used with `fn`, will return a function that
sets the value passed to `mut` to its first argument. As an example, we can create a
button that increments a value passing the value directly to the `fn`:
```handlebars
{{! inc helper is not provided by Ember }}
<button onclick={{fn (mut count) (inc count)}}>
Increment count
</button>
```
@method mut
@param {Object} [attr] the "two-way" attribute that can be modified.
@for Ember.Templates.helpers
@public
*/
var mut = internalHelper(({
positional
}) => {
var ref = positional[0]; // TODO: Improve this error message. This covers at least two distinct
// cases:
//
// 1. (mut "not a path") passing a literal, result from a helper
// invocation, etc
//
// 2. (mut receivedValue) passing a value received from the caller
// that was originally derived from a literal, result from a helper
// invocation, etc
//
// This message is alright for the first case, but could be quite
// confusing for the second case.
(true && !((0, _reference.isUpdatableRef)(ref)) && (0, _debug.assert)('You can only pass a path to mut', (0, _reference.isUpdatableRef)(ref)));
return (0, _reference.createInvokableRef)(ref);
});
/**
The `readonly` helper let's you specify that a binding is one-way only,
instead of two-way.
When you pass a `readonly` binding from an outer context (e.g. parent component),
to to an inner context (e.g. child component), you are saying that changing that
property in the inner context does not change the value in the outer context.
To specify that a binding is read-only, when invoking the child `Component`:
```app/components/my-parent.js
export default Component.extend({
totalClicks: 3
});
```
```app/templates/components/my-parent.hbs
{{log totalClicks}} // -> 3
<MyChild @childClickCount={{readonly totalClicks}} />
```
```
{{my-child childClickCount=(readonly totalClicks)}}
```
Now, when you update `childClickCount`:
```app/components/my-child.js
export default Component.extend({
click() {
this.incrementProperty('childClickCount');
}
});
```
The value updates in the child component, but not the parent component:
```app/templates/components/my-child.hbs
{{log childClickCount}} //-> 4
```
```app/templates/components/my-parent.hbs
{{log totalClicks}} //-> 3
<MyChild @childClickCount={{readonly totalClicks}} />
```
or
```app/templates/components/my-parent.hbs
{{log totalClicks}} //-> 3
{{my-child childClickCount=(readonly totalClicks)}}
```
### Objects and Arrays
When passing a property that is a complex object (e.g. object, array) instead of a primitive object (e.g. number, string),
only the reference to the object is protected using the readonly helper.
This means that you can change properties of the object both on the parent component, as well as the child component.
The `readonly` binding behaves similar to the `const` keyword in JavaScript.
Let's look at an example:
First let's set up the parent component:
```app/components/my-parent.js
import Component from '@ember/component';
export default Component.extend({
clicks: null,
init() {
this._super(...arguments);
this.set('clicks', { total: 3 });
}
});
```
```app/templates/components/my-parent.hbs
{{log clicks.total}} //-> 3
<MyChild @childClicks={{readonly clicks}} />
```
```app/templates/components/my-parent.hbs
{{log clicks.total}} //-> 3
{{my-child childClicks=(readonly clicks)}}
```
Now, if you update the `total` property of `childClicks`:
```app/components/my-child.js
import Component from '@ember/component';
export default Component.extend({
click() {
this.get('clicks').incrementProperty('total');
}
});
```
You will see the following happen:
```app/templates/components/my-parent.hbs
{{log clicks.total}} //-> 4
<MyChild @childClicks={{readonly clicks}} />
```
or
```app/templates/components/my-parent.hbs
{{log clicks.total}} //-> 4
{{my-child childClicks=(readonly clicks)}}
```
```app/templates/components/my-child.hbs
{{log childClicks.total}} //-> 4
```
@method readonly
@param {Object} [attr] the read-only attribute.
@for Ember.Templates.helpers
@private
*/
var readonly = internalHelper(({
positional
}) => {
return (0, _reference.createReadOnlyRef)(positional[0]);
});
/**
@module ember
*/
/**
The `{{unbound}}` helper disconnects the one-way binding of a property,
essentially freezing its value at the moment of rendering. For example,
in this example the display of the variable `name` will not change even
if it is set with a new value:
```handlebars
{{unbound this.name}}
```
Like any helper, the `unbound` helper can accept a nested helper expression.
This allows for custom helpers to be rendered unbound:
```handlebars
{{unbound (some-custom-helper)}}
{{unbound (capitalize this.name)}}
{{! You can use any helper, including unbound, in a nested expression }}
{{capitalize (unbound this.name)}}
```
The `unbound` helper only accepts a single argument, and it return an
unbound value.
@method unbound
@for Ember.Templates.helpers
@public
*/
var unbound = internalHelper(({
positional,
named
}) => {
(true && !(positional.length === 1 && Object.keys(named).length === 0) && (0, _debug.assert)('unbound helper cannot be called with multiple params or hash params', positional.length === 1 && Object.keys(named).length === 0));
return (0, _reference.createUnboundRef)((0, _reference.valueForRef)(positional[0]), '(resurt of an `unbound` helper)');
});
var MODIFIERS = ['alt', 'shift', 'meta', 'ctrl'];
var POINTER_EVENT_TYPE_REGEX = /^click|mouse|touch/;
function isAllowedEvent(event, allowedKeys) {
if (allowedKeys === null || allowedKeys === undefined) {
if (POINTER_EVENT_TYPE_REGEX.test(event.type)) {
return (0, _views.isSimpleClick)(event);
} else {
allowedKeys = '';
}
}
if (allowedKeys.indexOf('any') >= 0) {
return true;
}
for (var i = 0; i < MODIFIERS.length; i++) {
if (event[MODIFIERS[i] + 'Key'] && allowedKeys.indexOf(MODIFIERS[i]) === -1) {
return false;
}
}
return true;
}
var ActionHelper = {
// registeredActions is re-exported for compatibility with older plugins
// that were using this undocumented API.
registeredActions: _views.ActionManager.registeredActions,
registerAction(actionState) {
var {
actionId
} = actionState;
_views.ActionManager.registeredActions[actionId] = actionState;
return actionId;
},
unregisterAction(actionState) {
var {
actionId
} = actionState;
delete _views.ActionManager.registeredActions[actionId];
}
};
class ActionState {
constructor(element, owner, actionId, actionArgs, namedArgs, positionalArgs) {
this.tag = (0, _validator.createUpdatableTag)();
this.element = element;
this.owner = owner;
this.actionId = actionId;
this.actionArgs = actionArgs;
this.namedArgs = namedArgs;
this.positional = positionalArgs;
this.eventName = this.getEventName();
(0, _destroyable.registerDestructor)(this, () => ActionHelper.unregisterAction(this));
}
getEventName() {
var {
on: on$$1
} = this.namedArgs;
return on$$1 !== undefined ? (0, _reference.valueForRef)(on$$1) : 'click';
}
getActionArgs() {
var result = new Array(this.actionArgs.length);
for (var i = 0; i < this.actionArgs.length; i++) {
result[i] = (0, _reference.valueForRef)(this.actionArgs[i]);
}
return result;
}
getTarget() {
var {
implicitTarget,
namedArgs
} = this;
var {
target
} = namedArgs;
return target !== undefined ? (0, _reference.valueForRef)(target) : (0, _reference.valueForRef)(implicitTarget);
}
handler(event) {
var {
actionName,
namedArgs
} = this;
var {
bubbles,
preventDefault,
allowedKeys
} = namedArgs;
var bubblesVal = bubbles !== undefined ? (0, _reference.valueForRef)(bubbles) : undefined;
var preventDefaultVal = preventDefault !== undefined ? (0, _reference.valueForRef)(preventDefault) : undefined;
var allowedKeysVal = allowedKeys !== undefined ? (0, _reference.valueForRef)(allowedKeys) : undefined;
var target = this.getTarget();
var shouldBubble = bubblesVal !== false;
if (!isAllowedEvent(event, allowedKeysVal)) {
return true;
}
if (preventDefaultVal !== false) {
event.preventDefault();
}
if (!shouldBubble) {
event.stopPropagation();
}
(0, _runloop.join)(() => {
var args = this.getActionArgs();
var payload = {
args,
target,
name: null
};
if ((0, _reference.isInvokableRef)(actionName)) {
(0, _instrumentation.flaggedInstrument)('interaction.ember-action', payload, () => {
(0, _reference.updateRef)(actionName, args[0]);
});
return;
}
if (typeof actionName === 'function') {
(0, _instrumentation.flaggedInstrument)('interaction.ember-action', payload, () => {
actionName.apply(target, args);
});
return;
}
payload.name = actionName;
if (target.send) {
(0, _instrumentation.flaggedInstrument)('interaction.ember-action', payload, () => {
target.send.apply(target, [actionName, ...args]);
});
} else {
(true && !(typeof target[actionName] === 'function') && (0, _debug.assert)(`The action '${actionName}' did not exist on ${target}`, typeof target[actionName] === 'function'));
(0, _instrumentation.flaggedInstrument)('interaction.ember-action', payload, () => {
target[actionName].apply(target, args);
});
}
});
return shouldBubble;
}
}
class ActionModifierManager {
create(owner, element, _state, {
named,
positional
}) {
var actionArgs = []; // The first two arguments are (1) `this` and (2) the action name.
// Everything else is a param.
for (var i = 2; i < positional.length; i++) {
actionArgs.push(positional[i]);
}
var actionId = (0, _utils.uuid)();
return new ActionState(element, owner, actionId, actionArgs, named, positional);
}
getDebugName() {
return 'action';
}
install(actionState) {
var {
element,
actionId,
positional
} = actionState;
var actionName;
var actionNameRef;
var implicitTarget;
if (positional.length > 1) {
implicitTarget = positional[0];
actionNameRef = positional[1];
if ((0, _reference.isInvokableRef)(actionNameRef)) {
actionName = actionNameRef;
} else {
actionName = (0, _reference.valueForRef)(actionNameRef);
if (true
/* DEBUG */
) {
var actionPath = actionNameRef.debugLabel;
var actionPathParts = actionPath.split('.');
var actionLabel = actionPathParts[actionPathParts.length - 1];
(true && !(typeof actionName === 'string' || typeof actionName === 'function') && (0, _debug.assert)('You specified a quoteless path, `' + actionPath + '`, to the ' + '{{action}} helper which did not resolve to an action name (a ' + 'string). Perhaps you meant to use a quoted actionName? (e.g. ' + '{{action "' + actionLabel + '"}}).', typeof actionName === 'string' || typeof actionName === 'function'));
}
}
}
actionState.actionName = actionName;
actionState.implicitTarget = implicitTarget;
this.ensureEventSetup(actionState);
ActionHelper.registerAction(actionState);
element.setAttribute('data-ember-action', '');
element.setAttribute(`data-ember-action-${actionId}`, String(actionId));
}
update(actionState) {
var {
positional
} = actionState;
var actionNameRef = positional[1];
if (!(0, _reference.isInvokableRef)(actionNameRef)) {
actionState.actionName = (0, _reference.valueForRef)(actionNameRef);
}
var newEventName = actionState.getEventName();
if (newEventName !== actionState.eventName) {
this.ensureEventSetup(actionState);
actionState.eventName = actionState.getEventName();
}
}
ensureEventSetup(actionState) {
var dispatcher = actionState.owner.lookup('event_dispatcher:main');
dispatcher === null || dispatcher === void 0 ? void 0 : dispatcher.setupHandlerForEmberEvent(actionState.eventName);
}
getTag(actionState) {
return actionState.tag;
}
getDestroyable(actionState) {
return actionState;
}
}
var ACTION_MODIFIER_MANAGER = new ActionModifierManager();
var actionModifier = (0, _manager2.setInternalModifierManager)(ACTION_MODIFIER_MANAGER, {});
var CAPABILITIES$2 = {
dynamicLayout: true,
dynamicTag: false,
prepareArgs: false,
createArgs: true,
attributeHook: false,
elementHook: false,
createCaller: true,
dynamicScope: true,
updateHook: true,
createInstance: true,
wrapped: false,
willDestroy: false,
hasSubOwner: true
};
class MountManager {
getDynamicLayout(state) {
var templateFactory$$1 = state.engine.lookup('template:application');
return (0, _util.unwrapTemplate)(templateFactory$$1(state.engine)).asLayout();
}
getCapabilities() {
return CAPABILITIES$2;
}
getOwner(state) {
return state.engine;
}
create(owner, {
name
}, args, env) {
// TODO
// mount is a runtime helper, this shouldn't use dynamic layout
// we should resolve the engine app template in the helper
// it also should use the owner that looked up the mount helper.
var engine = owner.buildChildEngineInstance(name);
engine.boot();
var applicationFactory = engine.factoryFor(`controller:application`);
var controllerFactory = applicationFactory || (0, _routing2.generateControllerFactory)(engine, 'application');
var controller;
var self;
var bucket;
var modelRef;
if (args.named.has('model')) {
modelRef = args.named.get('model');
}
if (modelRef === undefined) {
controller = controllerFactory.create();
self = (0, _reference.createConstRef)(controller, 'this');
bucket = {
engine,
controller,
self,
modelRef
};
} else {
var model = (0, _reference.valueForRef)(modelRef);
controller = controllerFactory.create({
model
});
self = (0, _reference.createConstRef)(controller, 'this');
bucket = {
engine,
controller,
self,
modelRef
};
}
if (env.debugRenderTree) {
(0, _destroyable.associateDestroyableChild)(engine, controller);
}
return bucket;
}
getDebugName({
name
}) {
return name;
}
getDebugCustomRenderTree(definition, state, args, templateModuleName) {
return [{
bucket: state.engine,
instance: state.engine,
type: 'engine',
name: definition.name,
args
}, {
bucket: state.controller,
instance: state.controller,
type: 'route-template',
name: 'application',
args,
template: templateModuleName
}];
}
getSelf({
self
}) {
return self;
}
getDestroyable(bucket) {
return bucket.engine;
}
didCreate() {}
didUpdate() {}
didRenderLayout() {}
didUpdateLayout() {}
update(bucket) {
var {
controller,
modelRef
} = bucket;
if (modelRef !== undefined) {
controller.set('model', (0, _reference.valueForRef)(modelRef));
}
}
}
var MOUNT_MANAGER = new MountManager();
class MountDefinition {
constructor(resolvedName) {
this.resolvedName = resolvedName; // handle is not used by this custom definition
this.handle = -1;
this.manager = MOUNT_MANAGER;
this.compilable = null;
this.capabilities = (0, _manager2.capabilityFlagsFrom)(CAPABILITIES$2);
this.state = {
name: resolvedName
};
}
}
/**
The `{{mount}}` helper lets you embed a routeless engine in a template.
Mounting an engine will cause an instance to be booted and its `application`
template to be rendered.
For example, the following template mounts the `ember-chat` engine:
```handlebars
{{! application.hbs }}
{{mount "ember-chat"}}
```
Additionally, you can also pass in a `model` argument that will be
set as the engines model. This can be an existing object:
```
<div>
{{mount 'admin' model=userSettings}}
</div>
```
Or an inline `hash`, and you can even pass components:
```
<div>
<h1>Application template!</h1>
{{mount 'admin' model=(hash
title='Secret Admin'
signInButton=(component 'sign-in-button')
)}}
</div>
```
@method mount
@param {String} name Name of the engine to mount.
@param {Object} [model] Object that will be set as
the model of the engine.
@for Ember.Templates.helpers
@public
*/
var mountHelper = internalHelper((args, owner) => {
(true && !(owner) && (0, _debug.assert)('{{mount}} must be used within a component that has an owner', owner));
var nameRef = args.positional[0];
var captured;
(true && !(args.positional.length === 1) && (0, _debug.assert)('You can only pass a single positional argument to the {{mount}} helper, e.g. {{mount "chat-engine"}}.', args.positional.length === 1));
if (true
/* DEBUG */
&& args.named) {
var keys = Object.keys(args.named);
var extra = keys.filter(k => k !== 'model');
(true && !(extra.length === 0) && (0, _debug.assert)('You can only pass a `model` argument to the {{mount}} helper, ' + 'e.g. {{mount "profile-engine" model=this.profile}}. ' + `You passed ${extra.join(',')}.`, extra.length === 0));
}
captured = (0, _runtime.createCapturedArgs)(args.named, _runtime.EMPTY_POSITIONAL);
var lastName, lastDef;
return (0, _reference.createComputeRef)(() => {
var name = (0, _reference.valueForRef)(nameRef);
if (typeof name === 'string') {
if (lastName === name) {
return lastDef;
}
(true && !(owner.hasRegistration(`engine:${name}`)) && (0, _debug.assert)(`You used \`{{mount '${name}'}}\`, but the engine '${name}' can not be found.`, owner.hasRegistration(`engine:${name}`)));
lastName = name;
lastDef = (0, _runtime.curry)(0
/* Component */
, new MountDefinition(name), owner, captured, true);
return lastDef;
} else {
(true && !(name === null || name === undefined) && (0, _debug.assert)(`Invalid engine name '${name}' specified, engine name must be either a string, null or undefined.`, name === null || name === undefined));
lastDef = null;
lastName = null;
return null;
}
});
});
/**
The `{{outlet}}` helper lets you specify where a child route will render in
your template. An important use of the `{{outlet}}` helper is in your
application's `application.hbs` file:
```app/templates/application.hbs
<MyHeader />
<div class="my-dynamic-content">
<!-- this content will change based on the current route, which depends on the current URL -->
{{outlet}}
</div>
<MyFooter />
```
See the [routing guide](https://guides.emberjs.com/release/routing/rendering-a-template/) for more
information on how your `route` interacts with the `{{outlet}}` helper.
Note: Your content __will not render__ if there isn't an `{{outlet}}` for it.
@method outlet
@param {String} [name]
@for Ember.Templates.helpers
@public
*/
var outletHelper = internalHelper((args, owner, scope) => {
(true && !(owner) && (0, _debug.assert)('Expected owner to be present, {{outlet}} requires an owner', owner));
(true && !(scope) && (0, _debug.assert)('Expected dynamic scope to be present. You may have attempted to use the {{outlet}} keyword dynamically. This keyword cannot be used dynamically.', scope));
var nameRef;
if (args.positional.length === 0) {
nameRef = (0, _reference.createPrimitiveRef)('main');
} else {
nameRef = args.positional[0];
}
var outletRef = (0, _reference.createComputeRef)(() => {
var state = (0, _reference.valueForRef)(scope.get('outletState'));
var outlets = state !== undefined ? state.outlets : undefined;
return outlets !== undefined ? outlets[(0, _reference.valueForRef)(nameRef)] : undefined;
});
var lastState = null;
var definition = null;
return (0, _reference.createComputeRef)(() => {
var _a, _b;
var outletState = (0, _reference.valueForRef)(outletRef);
var state = stateFor(outletRef, outletState);
if (!validate(state, lastState)) {
lastState = state;
if (state !== null) {
var named = (0, _util.dict)(); // Create a ref for the model
var modelRef = (0, _reference.childRefFromParts)(outletRef, ['render', 'model']); // Store the value of the model
var model = (0, _reference.valueForRef)(modelRef); // Create a compute ref which we pass in as the `{{@model}}` reference
// for the outlet. This ref will update and return the value of the
// model _until_ the outlet itself changes. Once the outlet changes,
// dynamic scope also changes, and so the original model ref would not
// provide the correct updated value. So we stop updating and return
// the _last_ model value for that outlet.
named.model = (0, _reference.createComputeRef)(() => {
if (lastState === state) {
model = (0, _reference.valueForRef)(modelRef);
}
return model;
});
if (true
/* DEBUG */
) {
named.model = (0, _reference.createDebugAliasRef)('@model', named.model);
}
var _args2 = (0, _runtime.createCapturedArgs)(named, _runtime.EMPTY_POSITIONAL);
definition = (0, _runtime.curry)(0
/* Component */
, new OutletComponentDefinition(state), (_b = (_a = outletState === null || outletState === void 0 ? void 0 : outletState.render) === null || _a === void 0 ? void 0 : _a.owner) !== null && _b !== void 0 ? _b : owner, _args2, true);
} else {
definition = null;
}
}
return definition;
});
});
function stateFor(ref, outlet) {
if (outlet === undefined) return null;
var render = outlet.render;
if (render === undefined) return null;
var template = render.template;
if (template === undefined) return null; // this guard can be removed once @ember/test-helpers@1.6.0 has "aged out"
// and is no longer considered supported
if (isTemplateFactory(template)) {
template = template(render.owner);
}
return {
ref,
name: render.name,
outlet: render.outlet,
template,
controller: render.controller,
model: render.model
};
}
function validate(state, lastState) {
if (state === null) {
return lastState === null;
}
if (lastState === null) {
return false;
}
return state.template === lastState.template && state.controller === lastState.controller;
}
function instrumentationPayload$1(name) {
return {
object: `component:${name}`
};
}
function componentFor(name, owner, options) {
var fullName = `component:${name}`;
return owner.factoryFor(fullName, options) || null;
}
function layoutFor(name, owner, options) {
var templateFullName = `template:components/${name}`;
return owner.lookup(templateFullName, options) || null;
}
function lookupComponentPair(owner, name, options) {
var component = componentFor(name, owner, options);
if (component !== null && component.class !== undefined) {
var _layout = (0, _manager2.getComponentTemplate)(component.class);
if (_layout !== undefined) {
return {
component,
layout: _layout
};
}
}
var layout = layoutFor(name, owner, options);
if (component === null && layout === null) {
return null;
} else {
return {
component,
layout
};
}
}
var BUILTIN_KEYWORD_HELPERS = {
action: action$1,
mut,
readonly,
unbound,
'-hash': _runtime.hash,
'-each-in': eachIn,
'-normalize-class': normalizeClassHelper,
'-resolve': resolve,
'-track-array': trackArray,
'-mount': mountHelper,
'-outlet': outletHelper,
'-in-el-null': inElementNullCheckHelper
};
if (true
/* DEBUG */
) {
BUILTIN_KEYWORD_HELPERS['-disallow-dynamic-resolution'] = disallowDynamicResolution;
} else {
// Bug: this may be a quirk of our test setup?
// In prod builds, this is a no-op helper and is unused in practice. We shouldn't need
// to add it at all, but the current test build doesn't produce a "prod compiler", so
// we ended up running the debug-build for the template compliler in prod tests. Once
// that is fixed, this can be removed. For now, this allows the test to work and does
// not really harm anything, since it's just a no-op pass-through helper and the bytes
// has to be included anyway. In the future, perhaps we can avoid the latter by using
// `import(...)`?
BUILTIN_KEYWORD_HELPERS['-disallow-dynamic-resolution'] = disallowDynamicResolution;
}
var BUILTIN_HELPERS = Object.assign(Object.assign({}, BUILTIN_KEYWORD_HELPERS), {
array: _runtime.array,
concat: _runtime.concat,
fn: _runtime.fn,
get: _runtime.get,
hash: _runtime.hash
});
var BUILTIN_KEYWORD_MODIFIERS = {
action: actionModifier
};
var BUILTIN_MODIFIERS = Object.assign(Object.assign({}, BUILTIN_KEYWORD_MODIFIERS), {
on: _runtime.on
});
var CLASSIC_HELPER_MANAGER_ASSOCIATED = new _util._WeakSet();
class ResolverImpl {
constructor() {
this.componentDefinitionCache = new Map();
}
lookupPartial() {
return null;
}
lookupHelper(name, owner) {
(true && !(!(BUILTIN_HELPERS[name] && owner.hasRegistration(`helper:${name}`))) && (0, _debug.assert)(`You attempted to overwrite the built-in helper "${name}" which is not allowed. Please rename the helper.`, !(BUILTIN_HELPERS[name] && owner.hasRegistration(`helper:${name}`))));
var helper$$1 = BUILTIN_HELPERS[name];
if (helper$$1 !== undefined) {
return helper$$1;
}
var factory = owner.factoryFor(`helper:${name}`);
if (factory === undefined) {
return null;
}
var definition = factory.class;
if (definition === undefined) {
return null;
}
if (typeof definition === 'function' && isClassicHelper(definition)) {
// For classic class based helpers, we need to pass the factoryFor result itself rather
// than the raw value (`factoryFor(...).class`). This is because injections are already
// bound in the factoryFor result, including type-based injections
if (true
/* DEBUG */
) {
// In DEBUG we need to only set the associated value once, otherwise
// we'll trigger an assertion
if (!CLASSIC_HELPER_MANAGER_ASSOCIATED.has(factory)) {
CLASSIC_HELPER_MANAGER_ASSOCIATED.add(factory);
(0, _manager2.setInternalHelperManager)(CLASSIC_HELPER_MANAGER, factory);
}
} else {
(0, _manager2.setInternalHelperManager)(CLASSIC_HELPER_MANAGER, factory);
}
return factory;
}
return definition;
}
lookupBuiltInHelper(name) {
var _a;
return (_a = BUILTIN_KEYWORD_HELPERS[name]) !== null && _a !== void 0 ? _a : null;
}
lookupModifier(name, owner) {
var builtin = BUILTIN_MODIFIERS[name];
if (builtin !== undefined) {
return builtin;
}
var modifier = owner.factoryFor(`modifier:${name}`);
if (modifier === undefined) {
return null;
}
return modifier.class || null;
}
lookupBuiltInModifier(name) {
var _a;
return (_a = BUILTIN_KEYWORD_MODIFIERS[name]) !== null && _a !== void 0 ? _a : null;
}
lookupComponent(name, owner) {
var pair = lookupComponentPair(owner, name);
if (pair === null) {
(true && !(name !== 'text-area') && (0, _debug.assert)('Could not find component `<TextArea />` (did you mean `<Textarea />`?)', name !== 'text-area'));
return null;
}
var template = null;
var key;
if (pair.component === null) {
key = template = pair.layout(owner);
} else {
key = pair.component;
}
var cachedComponentDefinition = this.componentDefinitionCache.get(key);
if (cachedComponentDefinition !== undefined) {
return cachedComponentDefinition;
}
if (template === null && pair.layout !== null) {
template = pair.layout(owner);
}
var finalizer = (0, _instrumentation._instrumentStart)('render.getComponentDefinition', instrumentationPayload$1, name);
var definition = null;
if (pair.component === null) {
if (_environment2.ENV._TEMPLATE_ONLY_GLIMMER_COMPONENTS) {
definition = {
state: (0, _runtime.templateOnlyComponent)(undefined, name),
manager: _runtime.TEMPLATE_ONLY_COMPONENT_MANAGER,
template
};
} else {
var factory = owner.factoryFor((0, _container.privatize)`component:-default`);
var manager = (0, _manager2.getInternalComponentManager)(factory.class);
definition = {
state: factory,
manager,
template
};
}
} else {
(true && !(pair.component.class !== undefined) && (0, _debug.assert)(`missing component class ${name}`, pair.component.class !== undefined));
var _factory2 = pair.component;
var ComponentClass = _factory2.class;
var _manager = (0, _manager2.getInternalComponentManager)(ComponentClass);
definition = {
state: isCurlyManager(_manager) ? _factory2 : ComponentClass,
manager: _manager,
template
};
}
finalizer();
this.componentDefinitionCache.set(key, definition);
(true && !(!(definition === null && name === 'text-area')) && (0, _debug.assert)('Could not find component `<TextArea />` (did you mean `<Textarea />`?)', !(definition === null && name === 'text-area')));
return definition;
}
}
class DynamicScope {
constructor(view, outletState) {
this.view = view;
this.outletState = outletState;
}
child() {
return new DynamicScope(this.view, this.outletState);
}
get(key) {
// tslint:disable-next-line:max-line-length
(true && !(key === 'outletState') && (0, _debug.assert)(`Using \`-get-dynamic-scope\` is only supported for \`outletState\` (you used \`${key}\`).`, key === 'outletState'));
return this.outletState;
}
set(key, value) {
// tslint:disable-next-line:max-line-length
(true && !(key === 'outletState') && (0, _debug.assert)(`Using \`-with-dynamic-scope\` is only supported for \`outletState\` (you used \`${key}\`).`, key === 'outletState'));
this.outletState = value;
return value;
}
} // This wrapper logic prevents us from rerendering in case of a hard failure
// during render. This prevents infinite revalidation type loops from occuring,
// and ensures that errors are not swallowed by subsequent follow on failures.
function errorLoopTransaction(fn$$1) {
if (true
/* DEBUG */
) {
return () => {
var didError = true;
try {
fn$$1();
didError = false;
} finally {
if (didError) {
// Noop the function so that we won't keep calling it and causing
// infinite looping failures;
fn$$1 = () => {
console.warn('Attempted to rerender, but the Ember application has had an unrecoverable error occur during render. You should reload the application after fixing the cause of the error.');
};
}
}
};
} else {
return fn$$1;
}
}
class RootState {
constructor(root, runtime, context, owner, template, self, parentElement, dynamicScope, builder) {
this.root = root;
this.runtime = runtime;
(true && !(template !== undefined) && (0, _debug.assert)(`You cannot render \`${(0, _reference.valueForRef)(self)}\` without a template.`, template !== undefined));
this.id = (0, _views.getViewId)(root);
this.result = undefined;
this.destroyed = false;
this.render = errorLoopTransaction(() => {
var layout = (0, _util.unwrapTemplate)(template).asLayout();
var iterator = (0, _runtime.renderMain)(runtime, context, owner, self, builder(runtime.env, {
element: parentElement,
nextSibling: null
}), layout, dynamicScope);
var result = this.result = iterator.sync(); // override .render function after initial render
this.render = errorLoopTransaction(() => result.rerender({
alwaysRevalidate: false
}));
});
}
isFor(possibleRoot) {
return this.root === possibleRoot;
}
destroy() {
var {
result,
runtime: {
env
}
} = this;
this.destroyed = true;
this.runtime = undefined;
this.root = null;
this.result = undefined;
this.render = undefined;
if (result !== undefined) {
/*
Handles these scenarios:
* When roots are removed during standard rendering process, a transaction exists already
`.begin()` / `.commit()` are not needed.
* When roots are being destroyed manually (`component.append(); component.destroy() case), no
transaction exists already.
* When roots are being destroyed during `Renderer#destroy`, no transaction exists
*/
(0, _runtime.inTransaction)(env, () => (0, _destroyable.destroy)(result));
}
}
}
var renderers = [];
function _resetRenderers() {
renderers.length = 0;
}
function register(renderer) {
(true && !(renderers.indexOf(renderer) === -1) && (0, _debug.assert)('Cannot register the same renderer twice', renderers.indexOf(renderer) === -1));
renderers.push(renderer);
}
function deregister(renderer) {
var index = renderers.indexOf(renderer);
(true && !(index !== -1) && (0, _debug.assert)('Cannot deregister unknown unregistered renderer', index !== -1));
renderers.splice(index, 1);
}
function loopBegin() {
for (var i = 0; i < renderers.length; i++) {
renderers[i]._scheduleRevalidate();
}
}
function K() {
/* noop */
}
var renderSettledDeferred = null;
/*
Returns a promise which will resolve when rendering has settled. Settled in
this context is defined as when all of the tags in use are "current" (e.g.
`renderers.every(r => r._isValid())`). When this is checked at the _end_ of
the run loop, this essentially guarantees that all rendering is completed.
@method renderSettled
@returns {Promise<void>} a promise which fulfills when rendering has settled
*/
function renderSettled() {
if (renderSettledDeferred === null) {
renderSettledDeferred = _rsvp.default.defer(); // if there is no current runloop, the promise created above will not have
// a chance to resolve (because its resolved in backburner's "end" event)
if (!(0, _runloop._getCurrentRunLoop)()) {
// ensure a runloop has been kicked off
_runloop._backburner.schedule('actions', null, K);
}
}
return renderSettledDeferred.promise;
}
function resolveRenderPromise() {
if (renderSettledDeferred !== null) {
var _resolve = renderSettledDeferred.resolve;
renderSettledDeferred = null;
_runloop._backburner.join(null, _resolve);
}
}
var loops = 0;
function loopEnd() {
for (var i = 0; i < renderers.length; i++) {
if (!renderers[i]._isValid()) {
if (loops > _environment2.ENV._RERENDER_LOOP_LIMIT) {
loops = 0; // TODO: do something better
renderers[i].destroy();
throw new Error('infinite rendering invalidation detected');
}
loops++;
return _runloop._backburner.join(null, K);
}
}
loops = 0;
resolveRenderPromise();
}
_runloop._backburner.on('begin', loopBegin);
_runloop._backburner.on('end', loopEnd);
class Renderer {
constructor(owner, document, env, rootTemplate, viewRegistry, builder = _runtime.clientBuilder) {
this._inRenderTransaction = false;
this._lastRevision = -1;
this._destroyed = false;
this._owner = owner;
this._rootTemplate = rootTemplate(owner);
this._viewRegistry = viewRegistry || owner.lookup('-view-registry:main');
this._roots = [];
this._removedRoots = [];
this._builder = builder;
this._isInteractive = env.isInteractive; // resolver is exposed for tests
var resolver = this._runtimeResolver = new ResolverImpl();
var sharedArtifacts = (0, _program.artifacts)();
this._context = (0, _opcodeCompiler.programCompilationContext)(sharedArtifacts, resolver);
var runtimeEnvironmentDelegate = new EmberEnvironmentDelegate(owner, env.isInteractive);
this._runtime = (0, _runtime.runtimeContext)({
appendOperations: env.hasDOM ? new _runtime.DOMTreeConstruction(document) : new _node.NodeDOMTreeConstruction(document),
updateOperations: new _runtime.DOMChanges(document)
}, runtimeEnvironmentDelegate, sharedArtifacts, resolver);
}
static create(props) {
var {
_viewRegistry
} = props;
var document = (0, _owner2.getOwner)(props).lookup('service:-document');
var env = (0, _owner2.getOwner)(props).lookup('-environment:main');
var owner = (0, _owner2.getOwner)(props);
var rootTemplate = owner.lookup((0, _container.privatize)`template:-root`);
var builder = owner.lookup('service:-dom-builder');
return new this((0, _owner2.getOwner)(props), document, env, rootTemplate, _viewRegistry, builder);
}
get debugRenderTree() {
var {
debugRenderTree
} = this._runtime.env;
(true && !(debugRenderTree) && (0, _debug.assert)('Attempted to access the DebugRenderTree, but it did not exist. Is the Ember Inspector open?', debugRenderTree));
return debugRenderTree;
} // renderer HOOKS
appendOutletView(view, target) {
var definition = createRootOutlet(view);
this._appendDefinition(view, (0, _runtime.curry)(0
/* Component */
, definition, view.owner, null, true), target);
}
appendTo(view, target) {
var definition = new RootComponentDefinition(view);
this._appendDefinition(view, (0, _runtime.curry)(0
/* Component */
, definition, this._owner, null, true), target);
}
_appendDefinition(root, definition, target) {
var self = (0, _reference.createConstRef)(definition, 'this');
var dynamicScope = new DynamicScope(null, _reference.UNDEFINED_REFERENCE);
var rootState = new RootState(root, this._runtime, this._context, this._owner, this._rootTemplate, self, target, dynamicScope, this._builder);
this._renderRoot(rootState);
}
rerender() {
this._scheduleRevalidate();
}
register(view) {
var id = (0, _views.getViewId)(view);
(true && !(!this._viewRegistry[id]) && (0, _debug.assert)('Attempted to register a view with an id already in use: ' + id, !this._viewRegistry[id]));
this._viewRegistry[id] = view;
}
unregister(view) {
delete this._viewRegistry[(0, _views.getViewId)(view)];
}
remove(view) {
view._transitionTo('destroying');
this.cleanupRootFor(view);
if (this._isInteractive) {
view.trigger('didDestroyElement');
}
}
cleanupRootFor(view) {
// no need to cleanup roots if we have already been destroyed
if (this._destroyed) {
return;
}
var roots = this._roots; // traverse in reverse so we can remove items
// without mucking up the index
var i = this._roots.length;
while (i--) {
var root = roots[i];
if (root.isFor(view)) {
root.destroy();
roots.splice(i, 1);
}
}
}
destroy() {
if (this._destroyed) {
return;
}
this._destroyed = true;
this._clearAllRoots();
}
getElement(view) {
if (this._isInteractive) {
return (0, _views.getViewElement)(view);
} else {
throw new Error('Accessing `this.element` is not allowed in non-interactive environments (such as FastBoot).');
}
}
getBounds(view) {
var bounds = view[BOUNDS];
(true && !(Boolean(bounds)) && (0, _debug.assert)('object passed to getBounds must have the BOUNDS symbol as a property', Boolean(bounds)));
var parentElement = bounds.parentElement();
var firstNode = bounds.firstNode();
var lastNode = bounds.lastNode();
return {
parentElement,
firstNode,
lastNode
};
}
createElement(tagName) {
return this._runtime.env.getAppendOperations().createElement(tagName);
}
_renderRoot(root) {
var {
_roots: roots
} = this;
roots.push(root);
if (roots.length === 1) {
register(this);
}
this._renderRootsTransaction();
}
_renderRoots() {
var {
_roots: roots,
_runtime: runtime,
_removedRoots: removedRoots
} = this;
var initialRootsLength;
do {
initialRootsLength = roots.length;
(0, _runtime.inTransaction)(runtime.env, () => {
// ensure that for the first iteration of the loop
// each root is processed
for (var i = 0; i < roots.length; i++) {
var root = roots[i];
if (root.destroyed) {
// add to the list of roots to be removed
// they will be removed from `this._roots` later
removedRoots.push(root); // skip over roots that have been marked as destroyed
continue;
} // when processing non-initial reflush loops,
// do not process more roots than needed
if (i >= initialRootsLength) {
continue;
}
root.render();
}
this._lastRevision = (0, _validator.valueForTag)(_validator.CURRENT_TAG);
});
} while (roots.length > initialRootsLength); // remove any roots that were destroyed during this transaction
while (removedRoots.length) {
var root = removedRoots.pop();
var rootIndex = roots.indexOf(root);
roots.splice(rootIndex, 1);
}
if (this._roots.length === 0) {
deregister(this);
}
}
_renderRootsTransaction() {
if (this._inRenderTransaction) {
// currently rendering roots, a new root was added and will
// be processed by the existing _renderRoots invocation
return;
} // used to prevent calling _renderRoots again (see above)
// while we are actively rendering roots
this._inRenderTransaction = true;
var completedWithoutError = false;
try {
this._renderRoots();
completedWithoutError = true;
} finally {
if (!completedWithoutError) {
this._lastRevision = (0, _validator.valueForTag)(_validator.CURRENT_TAG);
}
this._inRenderTransaction = false;
}
}
_clearAllRoots() {
var roots = this._roots;
for (var i = 0; i < roots.length; i++) {
var root = roots[i];
root.destroy();
}
this._removedRoots.length = 0;
this._roots = []; // if roots were present before destroying
// deregister this renderer instance
if (roots.length) {
deregister(this);
}
}
_scheduleRevalidate() {
_runloop._backburner.scheduleOnce('render', this, this._revalidate);
}
_isValid() {
return this._destroyed || this._roots.length === 0 || (0, _validator.validateTag)(_validator.CURRENT_TAG, this._lastRevision);
}
_revalidate() {
if (this._isValid()) {
return;
}
this._renderRootsTransaction();
}
}
_exports.Renderer = Renderer;
var TEMPLATES = {};
function setTemplates(templates) {
TEMPLATES = templates;
}
function getTemplates() {
return TEMPLATES;
}
function getTemplate(name) {
if (Object.prototype.hasOwnProperty.call(TEMPLATES, name)) {
return TEMPLATES[name];
}
}
function hasTemplate(name) {
return Object.prototype.hasOwnProperty.call(TEMPLATES, name);
}
function setTemplate(name, template) {
return TEMPLATES[name] = template;
}
var OutletTemplate = (0, _opcodeCompiler.templateFactory)({
"id": "3jT+eJpe",
"block": "[[[46,[28,[37,1],null,null],null,null,null]],[],false,[\"component\",\"-outlet\"]]",
"moduleName": "packages/@ember/-internals/glimmer/lib/templates/outlet.hbs",
"isStrictMode": false
});
var TOP_LEVEL_NAME = '-top-level';
var TOP_LEVEL_OUTLET = 'main';
class OutletView {
constructor(_environment, owner, template, namespace) {
this._environment = _environment;
this.owner = owner;
this.template = template;
this.namespace = namespace;
var outletStateTag = (0, _validator.createTag)();
var outletState = {
outlets: {
main: undefined
},
render: {
owner: owner,
into: undefined,
outlet: TOP_LEVEL_OUTLET,
name: TOP_LEVEL_NAME,
controller: undefined,
model: undefined,
template
}
};
var ref = this.ref = (0, _reference.createComputeRef)(() => {
(0, _validator.consumeTag)(outletStateTag);
return outletState;
}, state => {
(0, _validator.dirtyTag)(outletStateTag);
outletState.outlets.main = state;
});
this.state = {
ref,
name: TOP_LEVEL_NAME,
outlet: TOP_LEVEL_OUTLET,
template,
controller: undefined,
model: undefined
};
}
static extend(injections) {
return class extends OutletView {
static create(options) {
if (options) {
return super.create(Object.assign({}, injections, options));
} else {
return super.create(injections);
}
}
};
}
static reopenClass(injections) {
Object.assign(this, injections);
}
static create(options) {
var {
environment: _environment,
application: namespace,
template: templateFactory$$1
} = options;
var owner = (0, _owner2.getOwner)(options);
var template = templateFactory$$1(owner);
return new OutletView(_environment, owner, template, namespace);
}
appendTo(selector) {
var target;
if (this._environment.hasDOM) {
target = typeof selector === 'string' ? document.querySelector(selector) : selector;
} else {
target = selector;
}
var renderer = this.owner.lookup('renderer:-dom');
(0, _runloop.schedule)('render', renderer, 'appendOutletView', this, target);
}
rerender() {
/**/
}
setOutletState(state) {
(0, _reference.updateRef)(this.ref, state);
}
destroy() {
/**/
}
}
_exports.OutletView = OutletView;
function setupApplicationRegistry(registry) {
// because we are using injections we can't use instantiate false
// we need to use bind() to copy the function so factory for
// association won't leak
registry.register('service:-dom-builder', {
create(props) {
var env = (0, _owner2.getOwner)(props).lookup('-environment:main');
switch (env._renderMode) {
case 'serialize':
return _node.serializeBuilder.bind(null);
case 'rehydrate':
return _runtime.rehydrationBuilder.bind(null);
default:
return _runtime.clientBuilder.bind(null);
}
}
});
registry.register((0, _container.privatize)`template:-root`, RootTemplate);
registry.register('renderer:-dom', Renderer);
}
function setupEngineRegistry(registry) {
registry.optionsForType('template', {
instantiate: false
});
registry.register('view:-outlet', OutletView);
registry.register('template:-outlet', OutletTemplate);
registry.optionsForType('helper', {
instantiate: false
});
registry.register('component:input', Input$1);
registry.register('component:link-to', LinkTo$1);
registry.register('component:textarea', Textarea$1);
if (!_environment2.ENV._TEMPLATE_ONLY_GLIMMER_COMPONENTS) {
registry.register((0, _container.privatize)`component:-default`, Component);
}
}
function setComponentManager$1(manager, obj) {
return (0, _manager2.setComponentManager)(manager, obj);
}
var componentCapabilities$1 = _manager2.componentCapabilities;
_exports.componentCapabilities = componentCapabilities$1;
var modifierCapabilities$1 = _manager2.modifierCapabilities;
/**
[Glimmer](https://github.com/tildeio/glimmer) is a templating engine used by Ember.js that is compatible with a subset of the [Handlebars](http://handlebarsjs.com/) syntax.
### Showing a property
Templates manage the flow of an application's UI, and display state (through
the DOM) to a user. For example, given a component with the property "name",
that component's template can use the name in several ways:
```app/components/person-profile.js
import Component from '@ember/component';
export default Component.extend({
name: 'Jill'
});
```
```app/components/person-profile.hbs
{{this.name}}
<div>{{this.name}}</div>
<span data-name={{this.name}}></span>
```
Any time the "name" property on the component changes, the DOM will be
updated.
Properties can be chained as well:
```handlebars
{{@aUserModel.name}}
<div>{{@listOfUsers.firstObject.name}}</div>
```
### Using Ember helpers
When content is passed in mustaches `{{}}`, Ember will first try to find a helper
or component with that name. For example, the `if` helper:
```app/components/person-profile.hbs
{{if this.name "I have a name" "I have no name"}}
<span data-has-name={{if this.name true}}></span>
```
The returned value is placed where the `{{}}` is called. The above style is
called "inline". A second style of helper usage is called "block". For example:
```handlebars
{{#if this.name}}
I have a name
{{else}}
I have no name
{{/if}}
```
The block form of helpers allows you to control how the UI is created based
on the values of properties.
A third form of helper is called "nested". For example here the concat
helper will add " Doe" to a displayed name if the person has no last name:
```handlebars
<span data-name={{concat this.firstName (
if this.lastName (concat " " this.lastName) "Doe"
)}}></span>
```
Ember's built-in helpers are described under the [Ember.Templates.helpers](/ember/release/classes/Ember.Templates.helpers)
namespace. Documentation on creating custom helpers can be found under
[helper](/ember/release/functions/@ember%2Fcomponent%2Fhelper/helper) (or
under [Helper](/ember/release/classes/Helper) if a helper requires access to
dependency injection).
### Invoking a Component
Ember components represent state to the UI of an application. Further
reading on components can be found under [Component](/ember/release/classes/Component).
@module @ember/component
@main @ember/component
@public
*/
_exports.modifierCapabilities = modifierCapabilities$1;
});
define("@ember/-internals/meta/index", ["exports", "@ember/-internals/meta/lib/meta"], function (_exports, _meta) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "counters", {
enumerable: true,
get: function () {
return _meta.counters;
}
});
Object.defineProperty(_exports, "Meta", {
enumerable: true,
get: function () {
return _meta.Meta;
}
});
Object.defineProperty(_exports, "meta", {
enumerable: true,
get: function () {
return _meta.meta;
}
});
Object.defineProperty(_exports, "peekMeta", {
enumerable: true,
get: function () {
return _meta.peekMeta;
}
});
Object.defineProperty(_exports, "setMeta", {
enumerable: true,
get: function () {
return _meta.setMeta;
}
});
Object.defineProperty(_exports, "UNDEFINED", {
enumerable: true,
get: function () {
return _meta.UNDEFINED;
}
});
});
define("@ember/-internals/meta/lib/meta", ["exports", "@ember/-internals/utils", "@ember/debug", "@glimmer/destroyable"], function (_exports, _utils, _debug, _destroyable) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.setMeta = setMeta;
_exports.peekMeta = peekMeta;
_exports.counters = _exports.meta = _exports.Meta = _exports.UNDEFINED = void 0;
var objectPrototype = Object.prototype;
var counters;
_exports.counters = counters;
if (true
/* DEBUG */
) {
_exports.counters = counters = {
peekCalls: 0,
peekPrototypeWalks: 0,
setCalls: 0,
deleteCalls: 0,
metaCalls: 0,
metaInstantiated: 0,
matchingListenersCalls: 0,
observerEventsCalls: 0,
addToListenersCalls: 0,
removeFromListenersCalls: 0,
removeAllListenersCalls: 0,
listenersInherited: 0,
listenersFlattened: 0,
parentListenersUsed: 0,
flattenedListenersCalls: 0,
reopensAfterFlatten: 0,
readableLazyChainsCalls: 0,
writableLazyChainsCalls: 0
};
}
/**
@module ember
*/
var UNDEFINED = (0, _utils.symbol)('undefined');
_exports.UNDEFINED = UNDEFINED;
var currentListenerVersion = 1;
class Meta {
// DEBUG
constructor(obj) {
this._listenersVersion = 1;
this._inheritedEnd = -1;
this._flattenedVersion = 0;
if (true
/* DEBUG */
) {
counters.metaInstantiated++;
}
this._parent = undefined;
this._descriptors = undefined;
this._mixins = undefined;
this._lazyChains = undefined;
this._values = undefined;
this._revisions = undefined; // initial value for all flags right now is false
// see FLAGS const for detailed list of flags used
this._isInit = false; // used only internally
this.source = obj;
this.proto = obj.constructor === undefined ? undefined : obj.constructor.prototype;
this._listeners = undefined;
}
get parent() {
var parent = this._parent;
if (parent === undefined) {
var proto = getPrototypeOf(this.source);
this._parent = parent = proto === null || proto === objectPrototype ? null : meta(proto);
}
return parent;
}
setInitializing() {
this._isInit = true;
}
unsetInitializing() {
this._isInit = false;
}
isInitializing() {
return this._isInit;
}
isPrototypeMeta(obj) {
return this.proto === this.source && this.source === obj;
}
_getOrCreateOwnMap(key) {
return this[key] || (this[key] = Object.create(null));
}
_getOrCreateOwnSet(key) {
return this[key] || (this[key] = new Set());
}
_findInheritedMap(key, subkey) {
var pointer = this;
while (pointer !== null) {
var map = pointer[key];
if (map !== undefined) {
var value = map.get(subkey);
if (value !== undefined) {
return value;
}
}
pointer = pointer.parent;
}
}
_hasInInheritedSet(key, value) {
var pointer = this;
while (pointer !== null) {
var set = pointer[key];
if (set !== undefined && set.has(value)) {
return true;
}
pointer = pointer.parent;
}
return false;
}
valueFor(key) {
var values = this._values;
return values !== undefined ? values[key] : undefined;
}
setValueFor(key, value) {
var values = this._getOrCreateOwnMap('_values');
values[key] = value;
}
revisionFor(key) {
var revisions = this._revisions;
return revisions !== undefined ? revisions[key] : undefined;
}
setRevisionFor(key, revision) {
var revisions = this._getOrCreateOwnMap('_revisions');
revisions[key] = revision;
}
writableLazyChainsFor(key) {
if (true
/* DEBUG */
) {
counters.writableLazyChainsCalls++;
}
var lazyChains = this._getOrCreateOwnMap('_lazyChains');
var chains = lazyChains[key];
if (chains === undefined) {
chains = lazyChains[key] = [];
}
return chains;
}
readableLazyChainsFor(key) {
if (true
/* DEBUG */
) {
counters.readableLazyChainsCalls++;
}
var lazyChains = this._lazyChains;
if (lazyChains !== undefined) {
return lazyChains[key];
}
return undefined;
}
addMixin(mixin) {
(true && !(!(0, _destroyable.isDestroyed)(this.source)) && (0, _debug.assert)((0, _destroyable.isDestroyed)(this.source) ? `Cannot add mixins of \`${(0, _utils.toString)(mixin)}\` on \`${(0, _utils.toString)(this.source)}\` call addMixin after it has been destroyed.` : '', !(0, _destroyable.isDestroyed)(this.source)));
var set = this._getOrCreateOwnSet('_mixins');
set.add(mixin);
}
hasMixin(mixin) {
return this._hasInInheritedSet('_mixins', mixin);
}
forEachMixins(fn) {
var pointer = this;
var seen;
while (pointer !== null) {
var set = pointer._mixins;
if (set !== undefined) {
seen = seen === undefined ? new Set() : seen; // TODO cleanup typing here
set.forEach(mixin => {
if (!seen.has(mixin)) {
seen.add(mixin);
fn(mixin);
}
});
}
pointer = pointer.parent;
}
}
writeDescriptors(subkey, value) {
(true && !(!(0, _destroyable.isDestroyed)(this.source)) && (0, _debug.assert)((0, _destroyable.isDestroyed)(this.source) ? `Cannot update descriptors for \`${subkey}\` on \`${(0, _utils.toString)(this.source)}\` after it has been destroyed.` : '', !(0, _destroyable.isDestroyed)(this.source)));
var map = this._descriptors || (this._descriptors = new Map());
map.set(subkey, value);
}
peekDescriptors(subkey) {
var possibleDesc = this._findInheritedMap('_descriptors', subkey);
return possibleDesc === UNDEFINED ? undefined : possibleDesc;
}
removeDescriptors(subkey) {
this.writeDescriptors(subkey, UNDEFINED);
}
forEachDescriptors(fn) {
var pointer = this;
var seen;
while (pointer !== null) {
var map = pointer._descriptors;
if (map !== undefined) {
seen = seen === undefined ? new Set() : seen;
map.forEach((value, key) => {
if (!seen.has(key)) {
seen.add(key);
if (value !== UNDEFINED) {
fn(key, value);
}
}
});
}
pointer = pointer.parent;
}
}
addToListeners(eventName, target, method, once, sync) {
if (true
/* DEBUG */
) {
counters.addToListenersCalls++;
}
this.pushListener(eventName, target, method, once ? 1
/* ONCE */
: 0
/* ADD */
, sync);
}
removeFromListeners(eventName, target, method) {
if (true
/* DEBUG */
) {
counters.removeFromListenersCalls++;
}
this.pushListener(eventName, target, method, 2
/* REMOVE */
);
}
pushListener(event, target, method, kind, sync = false) {
var listeners = this.writableListeners();
var i = indexOfListener(listeners, event, target, method); // remove if found listener was inherited
if (i !== -1 && i < this._inheritedEnd) {
listeners.splice(i, 1);
this._inheritedEnd--;
i = -1;
} // if not found, push. Note that we must always push if a listener is not
// found, even in the case of a function listener remove, because we may be
// attempting to add or remove listeners _before_ flattening has occurred.
if (i === -1) {
(true && !(!(this.isPrototypeMeta(this.source) && typeof method === 'function')) && (0, _debug.assert)('You cannot add function listeners to prototypes. Convert the listener to a string listener, or add it to the instance instead.', !(this.isPrototypeMeta(this.source) && typeof method === 'function')));
(true && !(!(!this.isPrototypeMeta(this.source) && typeof method === 'function' && kind === 2
/* REMOVE */
)) && (0, _debug.assert)('You attempted to remove a function listener which did not exist on the instance, which means you may have attempted to remove it before it was added.', !(!this.isPrototypeMeta(this.source) && typeof method === 'function' && kind === 2)));
listeners.push({
event,
target,
method,
kind,
sync
});
} else {
var listener = listeners[i]; // If the listener is our own listener and we are trying to remove it, we
// want to splice it out entirely so we don't hold onto a reference.
if (kind === 2
/* REMOVE */
&& listener.kind !== 2
/* REMOVE */
) {
listeners.splice(i, 1);
} else {
(true && !(!(listener.kind === 0
/* ADD */
&& kind === 0
/* ADD */
&& listener.sync !== sync)) && (0, _debug.assert)(`You attempted to add an observer for the same method on '${event.split(':')[0]}' twice to ${target} as both sync and async. Observers must be either sync or async, they cannot be both. This is likely a mistake, you should either remove the code that added the observer a second time, or update it to always be sync or async. The method was ${method}.`, !(listener.kind === 0 && kind === 0 && listener.sync !== sync))); // update own listener
listener.kind = kind;
listener.sync = sync;
}
}
}
writableListeners() {
// Check if we need to invalidate and reflatten. We need to do this if we
// have already flattened (flattened version is the current version) and
// we are either writing to a prototype meta OR we have never inherited, and
// may have cached the parent's listeners.
if (this._flattenedVersion === currentListenerVersion && (this.source === this.proto || this._inheritedEnd === -1)) {
if (true
/* DEBUG */
) {
counters.reopensAfterFlatten++;
}
currentListenerVersion++;
} // Inherited end has not been set, then we have never created our own
// listeners, but may have cached the parent's
if (this._inheritedEnd === -1) {
this._inheritedEnd = 0;
this._listeners = [];
}
return this._listeners;
}
/**
Flattening is based on a global revision counter. If the revision has
bumped it means that somewhere in a class inheritance chain something has
changed, so we need to reflatten everything. This can only happen if:
1. A meta has been flattened (listener has been called)
2. The meta is a prototype meta with children who have inherited its
listeners
3. A new listener is subsequently added to the meta (e.g. via `.reopen()`)
This is a very rare occurrence, so while the counter is global it shouldn't
be updated very often in practice.
*/
flattenedListeners() {
if (true
/* DEBUG */
) {
counters.flattenedListenersCalls++;
}
if (this._flattenedVersion < currentListenerVersion) {
if (true
/* DEBUG */
) {
counters.listenersFlattened++;
}
var parent = this.parent;
if (parent !== null) {
// compute
var parentListeners = parent.flattenedListeners();
if (parentListeners !== undefined) {
if (this._listeners === undefined) {
// If this instance doesn't have any of its own listeners (writableListeners
// has never been called) then we don't need to do any flattening, return
// the parent's listeners instead.
if (true
/* DEBUG */
) {
counters.parentListenersUsed++;
}
this._listeners = parentListeners;
} else {
var listeners = this._listeners;
if (this._inheritedEnd > 0) {
listeners.splice(0, this._inheritedEnd);
this._inheritedEnd = 0;
}
for (var i = 0; i < parentListeners.length; i++) {
var listener = parentListeners[i];
var index = indexOfListener(listeners, listener.event, listener.target, listener.method);
if (index === -1) {
if (true
/* DEBUG */
) {
counters.listenersInherited++;
}
listeners.unshift(listener);
this._inheritedEnd++;
}
}
}
}
}
this._flattenedVersion = currentListenerVersion;
}
return this._listeners;
}
matchingListeners(eventName) {
var listeners = this.flattenedListeners();
var result;
if (true
/* DEBUG */
) {
counters.matchingListenersCalls++;
}
if (listeners !== undefined) {
for (var index = 0; index < listeners.length; index++) {
var listener = listeners[index]; // REMOVE listeners are placeholders that tell us not to
// inherit, so they never match. Only ADD and ONCE can match.
if (listener.event === eventName && (listener.kind === 0
/* ADD */
|| listener.kind === 1
/* ONCE */
)) {
if (result === undefined) {
// we create this array only after we've found a listener that
// matches to avoid allocations when no matches are found.
result = [];
}
result.push(listener.target, listener.method, listener.kind === 1
/* ONCE */
);
}
}
}
return result;
}
observerEvents() {
var listeners = this.flattenedListeners();
var result;
if (true
/* DEBUG */
) {
counters.observerEventsCalls++;
}
if (listeners !== undefined) {
for (var index = 0; index < listeners.length; index++) {
var listener = listeners[index]; // REMOVE listeners are placeholders that tell us not to
// inherit, so they never match. Only ADD and ONCE can match.
if ((listener.kind === 0
/* ADD */
|| listener.kind === 1
/* ONCE */
) && listener.event.indexOf(':change') !== -1) {
if (result === undefined) {
// we create this array only after we've found a listener that
// matches to avoid allocations when no matches are found.
result = [];
}
result.push(listener);
}
}
}
return result;
}
}
_exports.Meta = Meta;
var getPrototypeOf = Object.getPrototypeOf;
var metaStore = new WeakMap();
function setMeta(obj, meta) {
(true && !(obj !== null) && (0, _debug.assert)('Cannot call `setMeta` on null', obj !== null));
(true && !(obj !== undefined) && (0, _debug.assert)('Cannot call `setMeta` on undefined', obj !== undefined));
(true && !(typeof obj === 'object' || typeof obj === 'function') && (0, _debug.assert)(`Cannot call \`setMeta\` on ${typeof obj}`, typeof obj === 'object' || typeof obj === 'function'));
if (true
/* DEBUG */
) {
counters.setCalls++;
}
metaStore.set(obj, meta);
}
function peekMeta(obj) {
(true && !(obj !== null) && (0, _debug.assert)('Cannot call `peekMeta` on null', obj !== null));
(true && !(obj !== undefined) && (0, _debug.assert)('Cannot call `peekMeta` on undefined', obj !== undefined));
(true && !(typeof obj === 'object' || typeof obj === 'function') && (0, _debug.assert)(`Cannot call \`peekMeta\` on ${typeof obj}`, typeof obj === 'object' || typeof obj === 'function'));
if (true
/* DEBUG */
) {
counters.peekCalls++;
}
var meta = metaStore.get(obj);
if (meta !== undefined) {
return meta;
}
var pointer = getPrototypeOf(obj);
while (pointer !== null) {
if (true
/* DEBUG */
) {
counters.peekPrototypeWalks++;
}
meta = metaStore.get(pointer);
if (meta !== undefined) {
if (meta.proto !== pointer) {
// The meta was a prototype meta which was not marked as initializing.
// This can happen when a prototype chain was created manually via
// Object.create() and the source object does not have a constructor.
meta.proto = pointer;
}
return meta;
}
pointer = getPrototypeOf(pointer);
}
return null;
}
/**
Retrieves the meta hash for an object. If `writable` is true ensures the
hash is writable for this object as well.
The meta object contains information about computed property descriptors as
well as any watched properties and other information. You generally will
not access this information directly but instead work with higher level
methods that manipulate this hash indirectly.
@method meta
@for Ember
@private
@param {Object} obj The object to retrieve meta for
@param {Boolean} [writable=true] Pass `false` if you do not intend to modify
the meta hash, allowing the method to avoid making an unnecessary copy.
@return {Object} the meta hash for an object
*/
var meta = function meta(obj) {
(true && !(obj !== null) && (0, _debug.assert)('Cannot call `meta` on null', obj !== null));
(true && !(obj !== undefined) && (0, _debug.assert)('Cannot call `meta` on undefined', obj !== undefined));
(true && !(typeof obj === 'object' || typeof obj === 'function') && (0, _debug.assert)(`Cannot call \`meta\` on ${typeof obj}`, typeof obj === 'object' || typeof obj === 'function'));
if (true
/* DEBUG */
) {
counters.metaCalls++;
}
var maybeMeta = peekMeta(obj); // remove this code, in-favor of explicit parent
if (maybeMeta !== null && maybeMeta.source === obj) {
return maybeMeta;
}
var newMeta = new Meta(obj);
setMeta(obj, newMeta);
return newMeta;
};
_exports.meta = meta;
if (true
/* DEBUG */
) {
meta._counters = counters;
}
function indexOfListener(listeners, event, target, method) {
for (var i = listeners.length - 1; i >= 0; i--) {
var listener = listeners[i];
if (listener.event === event && listener.target === target && listener.method === method) {
return i;
}
}
return -1;
}
});
define("@ember/-internals/metal/index", ["exports", "@ember/-internals/meta", "@ember/-internals/utils", "@ember/debug", "@ember/-internals/environment", "@ember/runloop", "@glimmer/destroyable", "@glimmer/validator", "@glimmer/manager", "@glimmer/util", "@ember/error", "ember/version", "@ember/-internals/container", "@ember/-internals/owner"], function (_exports, _meta2, _utils, _debug, _environment, _runloop, _destroyable, _validator, _manager, _util, _error, _version, _container, _owner) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.computed = computed;
_exports.autoComputed = autoComputed;
_exports.isComputed = isComputed;
_exports.getCachedValueFor = getCachedValueFor;
_exports.alias = alias;
_exports.deprecateProperty = deprecateProperty;
_exports._getPath = _getPath;
_exports.get = get;
_exports._getProp = _getProp;
_exports.set = set;
_exports._setProp = _setProp;
_exports.trySet = trySet;
_exports.objectAt = objectAt;
_exports.replace = replace;
_exports.replaceInNativeArray = replaceInNativeArray;
_exports.addArrayObserver = addArrayObserver;
_exports.removeArrayObserver = removeArrayObserver;
_exports.arrayContentWillChange = arrayContentWillChange;
_exports.arrayContentDidChange = arrayContentDidChange;
_exports.eachProxyArrayWillChange = eachProxyArrayWillChange;
_exports.eachProxyArrayDidChange = eachProxyArrayDidChange;
_exports.addListener = addListener;
_exports.hasListeners = hasListeners;
_exports.on = on;
_exports.removeListener = removeListener;
_exports.sendEvent = sendEvent;
_exports.isNone = isNone;
_exports.isEmpty = isEmpty;
_exports.isBlank = isBlank;
_exports.isPresent = isPresent;
_exports.beginPropertyChanges = beginPropertyChanges;
_exports.changeProperties = changeProperties;
_exports.endPropertyChanges = endPropertyChanges;
_exports.notifyPropertyChange = notifyPropertyChange;
_exports.defineProperty = defineProperty;
_exports.isElementDescriptor = isElementDescriptor;
_exports.nativeDescDecorator = nativeDescDecorator;
_exports.descriptorForDecorator = descriptorForDecorator;
_exports.descriptorForProperty = descriptorForProperty;
_exports.isClassicDecorator = isClassicDecorator;
_exports.setClassicDecorator = setClassicDecorator;
_exports.getProperties = getProperties;
_exports.setProperties = setProperties;
_exports.expandProperties = expandProperties;
_exports.addObserver = addObserver;
_exports.activateObserver = activateObserver;
_exports.removeObserver = removeObserver;
_exports.flushAsyncObservers = flushAsyncObservers;
_exports.mixin = mixin;
_exports.observer = observer;
_exports.applyMixin = applyMixin;
_exports.inject = inject;
_exports.tagForProperty = tagForProperty;
_exports.tagForObject = tagForObject;
_exports.markObjectAsDirty = markObjectAsDirty;
_exports.tracked = tracked;
_exports.addNamespace = addNamespace;
_exports.findNamespace = findNamespace;
_exports.findNamespaces = findNamespaces;
_exports.processNamespace = processNamespace;
_exports.processAllNamespaces = processAllNamespaces;
_exports.removeNamespace = removeNamespace;
_exports.isNamespaceSearchDisabled = isSearchDisabled;
_exports.setNamespaceSearchDisabled = setSearchDisabled;
Object.defineProperty(_exports, "createCache", {
enumerable: true,
get: function () {
return _validator.createCache;
}
});
Object.defineProperty(_exports, "getValue", {
enumerable: true,
get: function () {
return _validator.getValue;
}
});
Object.defineProperty(_exports, "isConst", {
enumerable: true,
get: function () {
return _validator.isConst;
}
});
_exports.NAMESPACES_BY_ID = _exports.NAMESPACES = _exports.TrackedDescriptor = _exports.DEBUG_INJECTION_FUNCTIONS = _exports.Mixin = _exports.SYNC_OBSERVERS = _exports.ASYNC_OBSERVERS = _exports.Libraries = _exports.libraries = _exports.PROPERTY_DID_CHANGE = _exports.PROXY_CONTENT = _exports.ComputedProperty = void 0;
/**
@module @ember/object
*/
/*
The event system uses a series of nested hashes to store listeners on an
object. When a listener is registered, or when an event arrives, these
hashes are consulted to determine which target and action pair to invoke.
The hashes are stored in the object's meta hash, and look like this:
// Object's meta hash
{
listeners: { // variable name: `listenerSet`
"foo:change": [ // variable name: `actions`
target, method, once
]
}
}
*/
/**
Add an event listener
@method addListener
@static
@for @ember/object/events
@param obj
@param {String} eventName
@param {Object|Function} target A target object or a function
@param {Function|String} method A function or the name of a function to be called on `target`
@param {Boolean} once A flag whether a function should only be called once
@public
*/
function addListener(obj, eventName, target, method, once, sync = true) {
(true && !(Boolean(obj) && Boolean(eventName)) && (0, _debug.assert)('You must pass at least an object and event name to addListener', Boolean(obj) && Boolean(eventName)));
if (!method && 'function' === typeof target) {
method = target;
target = null;
}
(0, _meta2.meta)(obj).addToListeners(eventName, target, method, once === true, sync);
}
/**
Remove an event listener
Arguments should match those passed to `addListener`.
@method removeListener
@static
@for @ember/object/events
@param obj
@param {String} eventName
@param {Object|Function} target A target object or a function
@param {Function|String} method A function or the name of a function to be called on `target`
@public
*/
function removeListener(obj, eventName, targetOrFunction, functionOrName) {
(true && !(Boolean(obj) && Boolean(eventName) && (typeof targetOrFunction === 'function' || typeof targetOrFunction === 'object' && Boolean(functionOrName))) && (0, _debug.assert)('You must pass at least an object, event name, and method or target and method/method name to removeListener', Boolean(obj) && Boolean(eventName) && (typeof targetOrFunction === 'function' || typeof targetOrFunction === 'object' && Boolean(functionOrName))));
var target, method;
if (typeof targetOrFunction === 'object') {
target = targetOrFunction;
method = functionOrName;
} else {
target = null;
method = targetOrFunction;
}
var m = (0, _meta2.meta)(obj);
m.removeFromListeners(eventName, target, method);
}
/**
Send an event. The execution of suspended listeners
is skipped, and once listeners are removed. A listener without
a target is executed on the passed object. If an array of actions
is not passed, the actions stored on the passed object are invoked.
@method sendEvent
@static
@for @ember/object/events
@param obj
@param {String} eventName
@param {Array} params Optional parameters for each listener.
@return {Boolean} if the event was delivered to one or more actions
@public
*/
function sendEvent(obj, eventName, params, actions, _meta) {
if (actions === undefined) {
var meta$$1 = _meta === undefined ? (0, _meta2.peekMeta)(obj) : _meta;
actions = meta$$1 !== null ? meta$$1.matchingListeners(eventName) : undefined;
}
if (actions === undefined || actions.length === 0) {
return false;
}
for (var i = actions.length - 3; i >= 0; i -= 3) {
// looping in reverse for once listeners
var target = actions[i];
var method = actions[i + 1];
var once = actions[i + 2];
if (!method) {
continue;
}
if (once) {
removeListener(obj, eventName, target, method);
}
if (!target) {
target = obj;
}
var type = typeof method;
if (type === 'string' || type === 'symbol') {
method = target[method];
}
method.apply(target, params);
}
return true;
}
/**
@private
@method hasListeners
@static
@for @ember/object/events
@param obj
@param {String} eventName
@return {Boolean} if `obj` has listeners for event `eventName`
*/
function hasListeners(obj, eventName) {
var meta$$1 = (0, _meta2.peekMeta)(obj);
if (meta$$1 === null) {
return false;
}
var matched = meta$$1.matchingListeners(eventName);
return matched !== undefined && matched.length > 0;
}
/**
Define a property as a function that should be executed when
a specified event or events are triggered.
``` javascript
import EmberObject from '@ember/object';
import { on } from '@ember/object/evented';
import { sendEvent } from '@ember/object/events';
let Job = EmberObject.extend({
logCompleted: on('completed', function() {
console.log('Job completed!');
})
});
let job = Job.create();
sendEvent(job, 'completed'); // Logs 'Job completed!'
```
@method on
@static
@for @ember/object/evented
@param {String} eventNames*
@param {Function} func
@return {Function} the listener function, passed as last argument to on(...)
@public
*/
function on(...args) {
var func = args.pop();
var events = args;
(true && !(typeof func === 'function') && (0, _debug.assert)('on expects function as last argument', typeof func === 'function'));
(true && !(events.length > 0 && events.every(p => typeof p === 'string' && p.length > 0)) && (0, _debug.assert)('on called without valid event names', events.length > 0 && events.every(p => typeof p === 'string' && p.length > 0)));
(0, _utils.setListeners)(func, events);
return func;
}
var AFTER_OBSERVERS = ':change';
function changeEvent(keyName) {
return keyName + AFTER_OBSERVERS;
}
var SYNC_DEFAULT = !_environment.ENV._DEFAULT_ASYNC_OBSERVERS;
var SYNC_OBSERVERS = new Map();
_exports.SYNC_OBSERVERS = SYNC_OBSERVERS;
var ASYNC_OBSERVERS = new Map();
/**
@module @ember/object
*/
/**
@method addObserver
@static
@for @ember/object/observers
@param obj
@param {String} path
@param {Object|Function} target
@param {Function|String} [method]
@public
*/
_exports.ASYNC_OBSERVERS = ASYNC_OBSERVERS;
function addObserver(obj, path, target, method, sync = SYNC_DEFAULT) {
var eventName = changeEvent(path);
addListener(obj, eventName, target, method, false, sync);
var meta$$1 = (0, _meta2.peekMeta)(obj);
if (meta$$1 === null || !(meta$$1.isPrototypeMeta(obj) || meta$$1.isInitializing())) {
activateObserver(obj, eventName, sync);
}
}
/**
@method removeObserver
@static
@for @ember/object/observers
@param obj
@param {String} path
@param {Object|Function} target
@param {Function|String} [method]
@public
*/
function removeObserver(obj, path, target, method, sync = SYNC_DEFAULT) {
var eventName = changeEvent(path);
var meta$$1 = (0, _meta2.peekMeta)(obj);
if (meta$$1 === null || !(meta$$1.isPrototypeMeta(obj) || meta$$1.isInitializing())) {
deactivateObserver(obj, eventName, sync);
}
removeListener(obj, eventName, target, method);
}
function getOrCreateActiveObserversFor(target, sync) {
var observerMap = sync === true ? SYNC_OBSERVERS : ASYNC_OBSERVERS;
if (!observerMap.has(target)) {
observerMap.set(target, new Map());
(0, _destroyable.registerDestructor)(target, () => destroyObservers(target), true);
}
return observerMap.get(target);
}
function activateObserver(target, eventName, sync = false) {
var activeObservers = getOrCreateActiveObserversFor(target, sync);
if (activeObservers.has(eventName)) {
activeObservers.get(eventName).count++;
} else {
var path = eventName.substring(0, eventName.lastIndexOf(':'));
var tag = getChainTagsForKey(target, path, (0, _validator.tagMetaFor)(target), (0, _meta2.peekMeta)(target));
activeObservers.set(eventName, {
count: 1,
path,
tag,
lastRevision: (0, _validator.valueForTag)(tag),
suspended: false
});
}
}
var DEACTIVATE_SUSPENDED = false;
var SCHEDULED_DEACTIVATE = [];
function deactivateObserver(target, eventName, sync = false) {
if (DEACTIVATE_SUSPENDED === true) {
SCHEDULED_DEACTIVATE.push([target, eventName, sync]);
return;
}
var observerMap = sync === true ? SYNC_OBSERVERS : ASYNC_OBSERVERS;
var activeObservers = observerMap.get(target);
if (activeObservers !== undefined) {
var _observer = activeObservers.get(eventName);
_observer.count--;
if (_observer.count === 0) {
activeObservers.delete(eventName);
if (activeObservers.size === 0) {
observerMap.delete(target);
}
}
}
}
function suspendedObserverDeactivation() {
DEACTIVATE_SUSPENDED = true;
}
function resumeObserverDeactivation() {
DEACTIVATE_SUSPENDED = false;
for (var [target, eventName, sync] of SCHEDULED_DEACTIVATE) {
deactivateObserver(target, eventName, sync);
}
SCHEDULED_DEACTIVATE = [];
}
/**
* Primarily used for cases where we are redefining a class, e.g. mixins/reopen
* being applied later. Revalidates all the observers, resetting their tags.
*
* @private
* @param target
*/
function revalidateObservers(target) {
if (ASYNC_OBSERVERS.has(target)) {
ASYNC_OBSERVERS.get(target).forEach(observer => {
observer.tag = getChainTagsForKey(target, observer.path, (0, _validator.tagMetaFor)(target), (0, _meta2.peekMeta)(target));
observer.lastRevision = (0, _validator.valueForTag)(observer.tag);
});
}
if (SYNC_OBSERVERS.has(target)) {
SYNC_OBSERVERS.get(target).forEach(observer => {
observer.tag = getChainTagsForKey(target, observer.path, (0, _validator.tagMetaFor)(target), (0, _meta2.peekMeta)(target));
observer.lastRevision = (0, _validator.valueForTag)(observer.tag);
});
}
}
var lastKnownRevision = 0;
function flushAsyncObservers(shouldSchedule = true) {
var currentRevision = (0, _validator.valueForTag)(_validator.CURRENT_TAG);
if (lastKnownRevision === currentRevision) {
return;
}
lastKnownRevision = currentRevision;
ASYNC_OBSERVERS.forEach((activeObservers, target) => {
var meta$$1 = (0, _meta2.peekMeta)(target);
activeObservers.forEach((observer, eventName) => {
if (!(0, _validator.validateTag)(observer.tag, observer.lastRevision)) {
var sendObserver = () => {
try {
sendEvent(target, eventName, [target, observer.path], undefined, meta$$1);
} finally {
observer.tag = getChainTagsForKey(target, observer.path, (0, _validator.tagMetaFor)(target), (0, _meta2.peekMeta)(target));
observer.lastRevision = (0, _validator.valueForTag)(observer.tag);
}
};
if (shouldSchedule) {
(0, _runloop.schedule)('actions', sendObserver);
} else {
sendObserver();
}
}
});
});
}
function flushSyncObservers() {
// When flushing synchronous observers, we know that something has changed (we
// only do this during a notifyPropertyChange), so there's no reason to check
// a global revision.
SYNC_OBSERVERS.forEach((activeObservers, target) => {
var meta$$1 = (0, _meta2.peekMeta)(target);
activeObservers.forEach((observer, eventName) => {
if (!observer.suspended && !(0, _validator.validateTag)(observer.tag, observer.lastRevision)) {
try {
observer.suspended = true;
sendEvent(target, eventName, [target, observer.path], undefined, meta$$1);
} finally {
observer.tag = getChainTagsForKey(target, observer.path, (0, _validator.tagMetaFor)(target), (0, _meta2.peekMeta)(target));
observer.lastRevision = (0, _validator.valueForTag)(observer.tag);
observer.suspended = false;
}
}
});
});
}
function setObserverSuspended(target, property, suspended) {
var activeObservers = SYNC_OBSERVERS.get(target);
if (!activeObservers) {
return;
}
var observer = activeObservers.get(changeEvent(property));
if (observer) {
observer.suspended = suspended;
}
}
function destroyObservers(target) {
if (SYNC_OBSERVERS.size > 0) SYNC_OBSERVERS.delete(target);
if (ASYNC_OBSERVERS.size > 0) ASYNC_OBSERVERS.delete(target);
}
var SELF_TAG = (0, _utils.symbol)('SELF_TAG');
function tagForProperty(obj, propertyKey, addMandatorySetter = false, meta$$1) {
var customTagFor = (0, _manager.getCustomTagFor)(obj);
if (customTagFor !== undefined) {
return customTagFor(obj, propertyKey, addMandatorySetter);
}
var tag = (0, _validator.tagFor)(obj, propertyKey, meta$$1);
if (true
/* DEBUG */
&& addMandatorySetter) {
(0, _utils.setupMandatorySetter)(tag, obj, propertyKey);
}
return tag;
}
function tagForObject(obj) {
if ((0, _utils.isObject)(obj)) {
if (true
/* DEBUG */
) {
(true && !(!(0, _destroyable.isDestroyed)(obj)) && (0, _debug.assert)((0, _destroyable.isDestroyed)(obj) ? `Cannot create a new tag for \`${(0, _utils.toString)(obj)}\` after it has been destroyed.` : '', !(0, _destroyable.isDestroyed)(obj)));
}
return (0, _validator.tagFor)(obj, SELF_TAG);
}
return _validator.CONSTANT_TAG;
}
function markObjectAsDirty(obj, propertyKey) {
(0, _validator.dirtyTagFor)(obj, propertyKey);
(0, _validator.dirtyTagFor)(obj, SELF_TAG);
}
/**
@module ember
@private
*/
var PROPERTY_DID_CHANGE = (0, _utils.enumerableSymbol)('PROPERTY_DID_CHANGE');
_exports.PROPERTY_DID_CHANGE = PROPERTY_DID_CHANGE;
var deferred = 0;
/**
This function is called just after an object property has changed.
It will notify any observers and clear caches among other things.
Normally you will not need to call this method directly but if for some
reason you can't directly watch a property you can invoke this method
manually.
@method notifyPropertyChange
@for @ember/object
@param {Object} obj The object with the property that will change
@param {String} keyName The property key (or path) that will change.
@param {Meta} [_meta] The objects meta.
@param {unknown} [value] The new value to set for the property
@return {void}
@since 3.1.0
@public
*/
function notifyPropertyChange(obj, keyName, _meta, value) {
var meta$$1 = _meta === undefined ? (0, _meta2.peekMeta)(obj) : _meta;
if (meta$$1 !== null && (meta$$1.isInitializing() || meta$$1.isPrototypeMeta(obj))) {
return;
}
markObjectAsDirty(obj, keyName);
if (deferred <= 0) {
flushSyncObservers();
}
if (PROPERTY_DID_CHANGE in obj) {
// we need to check the arguments length here; there's a check in `PROPERTY_DID_CHANGE`
// that checks its arguments length, so we have to explicitly not call this with `value`
// if it is not passed to `notifyPropertyChange`
if (arguments.length === 4) {
obj[PROPERTY_DID_CHANGE](keyName, value);
} else {
obj[PROPERTY_DID_CHANGE](keyName);
}
}
}
/**
@method beginPropertyChanges
@chainable
@private
*/
function beginPropertyChanges() {
deferred++;
suspendedObserverDeactivation();
}
/**
@method endPropertyChanges
@private
*/
function endPropertyChanges() {
deferred--;
if (deferred <= 0) {
flushSyncObservers();
resumeObserverDeactivation();
}
}
/**
Make a series of property changes together in an
exception-safe way.
```javascript
Ember.changeProperties(function() {
obj1.set('foo', mayBlowUpWhenSet);
obj2.set('bar', baz);
});
```
@method changeProperties
@param {Function} callback
@private
*/
function changeProperties(callback) {
beginPropertyChanges();
try {
callback();
} finally {
endPropertyChanges();
}
}
function arrayContentWillChange(array, startIdx, removeAmt, addAmt) {
// if no args are passed assume everything changes
if (startIdx === undefined) {
startIdx = 0;
removeAmt = addAmt = -1;
} else {
if (removeAmt === undefined) {
removeAmt = -1;
}
if (addAmt === undefined) {
addAmt = -1;
}
}
sendEvent(array, '@array:before', [array, startIdx, removeAmt, addAmt]);
return array;
}
function arrayContentDidChange(array, startIdx, removeAmt, addAmt, notify = true) {
// if no args are passed assume everything changes
if (startIdx === undefined) {
startIdx = 0;
removeAmt = addAmt = -1;
} else {
if (removeAmt === undefined) {
removeAmt = -1;
}
if (addAmt === undefined) {
addAmt = -1;
}
}
var meta$$1 = (0, _meta2.peekMeta)(array);
if (notify) {
if (addAmt < 0 || removeAmt < 0 || addAmt - removeAmt !== 0) {
notifyPropertyChange(array, 'length', meta$$1);
}
notifyPropertyChange(array, '[]', meta$$1);
}
sendEvent(array, '@array:change', [array, startIdx, removeAmt, addAmt]);
if (meta$$1 !== null) {
var length = array.length;
var addedAmount = addAmt === -1 ? 0 : addAmt;
var removedAmount = removeAmt === -1 ? 0 : removeAmt;
var delta = addedAmount - removedAmount;
var previousLength = length - delta;
var normalStartIdx = startIdx < 0 ? previousLength + startIdx : startIdx;
if (meta$$1.revisionFor('firstObject') !== undefined && normalStartIdx === 0) {
notifyPropertyChange(array, 'firstObject', meta$$1);
}
if (meta$$1.revisionFor('lastObject') !== undefined) {
var previousLastIndex = previousLength - 1;
var lastAffectedIndex = normalStartIdx + removedAmount;
if (previousLastIndex < lastAffectedIndex) {
notifyPropertyChange(array, 'lastObject', meta$$1);
}
}
}
return array;
}
var EMPTY_ARRAY = Object.freeze([]);
function objectAt(array, index) {
if (Array.isArray(array)) {
return array[index];
} else {
return array.objectAt(index);
}
}
function replace(array, start, deleteCount, items = EMPTY_ARRAY) {
if (Array.isArray(array)) {
replaceInNativeArray(array, start, deleteCount, items);
} else {
array.replace(start, deleteCount, items);
}
}
var CHUNK_SIZE = 60000; // To avoid overflowing the stack, we splice up to CHUNK_SIZE items at a time.
// See https://code.google.com/p/chromium/issues/detail?id=56588 for more details.
function replaceInNativeArray(array, start, deleteCount, items) {
arrayContentWillChange(array, start, deleteCount, items.length);
if (items.length <= CHUNK_SIZE) {
array.splice(start, deleteCount, ...items);
} else {
array.splice(start, deleteCount);
for (var i = 0; i < items.length; i += CHUNK_SIZE) {
var chunk = items.slice(i, i + CHUNK_SIZE);
array.splice(start + i, 0, ...chunk);
}
}
arrayContentDidChange(array, start, deleteCount, items.length);
}
function arrayObserversHelper(obj, target, opts, operation) {
var _a;
var {
willChange,
didChange
} = opts;
operation(obj, '@array:before', target, willChange);
operation(obj, '@array:change', target, didChange);
/*
* Array proxies have a `_revalidate` method which must be called to set
* up their internal array observation systems.
*/
(_a = obj._revalidate) === null || _a === void 0 ? void 0 : _a.call(obj);
return obj;
}
function addArrayObserver(array, target, opts) {
return arrayObserversHelper(array, target, opts, addListener);
}
function removeArrayObserver(array, target, opts) {
return arrayObserversHelper(array, target, opts, removeListener);
}
var CHAIN_PASS_THROUGH = new _util._WeakSet();
function finishLazyChains(meta$$1, key, value) {
var lazyTags = meta$$1.readableLazyChainsFor(key);
if (lazyTags === undefined) {
return;
}
if ((0, _utils.isObject)(value)) {
for (var i = 0; i < lazyTags.length; i++) {
var [tag, deps] = lazyTags[i];
(0, _validator.updateTag)(tag, getChainTagsForKey(value, deps, (0, _validator.tagMetaFor)(value), (0, _meta2.peekMeta)(value)));
}
}
lazyTags.length = 0;
}
function getChainTagsForKeys(obj, keys, tagMeta, meta$$1) {
var tags = [];
for (var i = 0; i < keys.length; i++) {
getChainTags(tags, obj, keys[i], tagMeta, meta$$1);
}
return (0, _validator.combine)(tags);
}
function getChainTagsForKey(obj, key, tagMeta, meta$$1) {
return (0, _validator.combine)(getChainTags([], obj, key, tagMeta, meta$$1));
}
function getChainTags(chainTags, obj, path, tagMeta, meta$$1) {
var current = obj;
var currentTagMeta = tagMeta;
var currentMeta = meta$$1;
var pathLength = path.length;
var segmentEnd = -1; // prevent closures
var segment, descriptor; // eslint-disable-next-line no-constant-condition
while (true) {
var lastSegmentEnd = segmentEnd + 1;
segmentEnd = path.indexOf('.', lastSegmentEnd);
if (segmentEnd === -1) {
segmentEnd = pathLength;
}
segment = path.slice(lastSegmentEnd, segmentEnd); // If the segment is an @each, we can process it and then break
if (segment === '@each' && segmentEnd !== pathLength) {
lastSegmentEnd = segmentEnd + 1;
segmentEnd = path.indexOf('.', lastSegmentEnd);
var arrLength = current.length;
if (typeof arrLength !== 'number' || // TODO: should the second test be `isEmberArray` instead?
!(Array.isArray(current) || 'objectAt' in current)) {
// If the current object isn't an array, there's nothing else to do,
// we don't watch individual properties. Break out of the loop.
break;
} else if (arrLength === 0) {
// Fast path for empty arrays
chainTags.push(tagForProperty(current, '[]'));
break;
}
if (segmentEnd === -1) {
segment = path.slice(lastSegmentEnd);
} else {
// Deprecated, remove once we turn the deprecation into an assertion
segment = path.slice(lastSegmentEnd, segmentEnd);
} // Push the tags for each item's property
for (var i = 0; i < arrLength; i++) {
var item = objectAt(current, i);
if (item) {
(true && !(typeof item === 'object') && (0, _debug.assert)(`When using @each to observe the array \`${current.toString()}\`, the items in the array must be objects`, typeof item === 'object'));
chainTags.push(tagForProperty(item, segment, true));
currentMeta = (0, _meta2.peekMeta)(item);
descriptor = currentMeta !== null ? currentMeta.peekDescriptors(segment) : undefined; // If the key is an alias, we need to bootstrap it
if (descriptor !== undefined && typeof descriptor.altKey === 'string') {
// tslint:disable-next-line: no-unused-expression
item[segment];
}
}
} // Push the tag for the array length itself
chainTags.push(tagForProperty(current, '[]', true, currentTagMeta));
break;
}
var propertyTag = tagForProperty(current, segment, true, currentTagMeta);
descriptor = currentMeta !== null ? currentMeta.peekDescriptors(segment) : undefined;
chainTags.push(propertyTag); // If we're at the end of the path, processing the last segment, and it's
// not an alias, we should _not_ get the last value, since we already have
// its tag. There's no reason to access it and do more work.
if (segmentEnd === pathLength) {
// If the key was an alias, we should always get the next value in order to
// bootstrap the alias. This is because aliases, unlike other CPs, should
// always be in sync with the aliased value.
if (CHAIN_PASS_THROUGH.has(descriptor)) {
// tslint:disable-next-line: no-unused-expression
current[segment];
}
break;
}
if (descriptor === undefined) {
// If the descriptor is undefined, then its a normal property, so we should
// lookup the value to chain off of like normal.
if (!(segment in current) && typeof current.unknownProperty === 'function') {
current = current.unknownProperty(segment);
} else {
current = current[segment];
}
} else if (CHAIN_PASS_THROUGH.has(descriptor)) {
current = current[segment];
} else {
// If the descriptor is defined, then its a normal CP (not an alias, which
// would have been handled earlier). We get the last revision to check if
// the CP is still valid, and if so we use the cached value. If not, then
// we create a lazy chain lookup, and the next time the CP is calculated,
// it will update that lazy chain.
var instanceMeta = currentMeta.source === current ? currentMeta : (0, _meta2.meta)(current);
var lastRevision = instanceMeta.revisionFor(segment);
if (lastRevision !== undefined && (0, _validator.validateTag)(propertyTag, lastRevision)) {
current = instanceMeta.valueFor(segment);
} else {
// use metaFor here to ensure we have the meta for the instance
var lazyChains = instanceMeta.writableLazyChainsFor(segment);
var rest = path.substr(segmentEnd + 1);
var placeholderTag = (0, _validator.createUpdatableTag)();
lazyChains.push([placeholderTag, rest]);
chainTags.push(placeholderTag);
break;
}
}
if (!(0, _utils.isObject)(current)) {
// we've hit the end of the chain for now, break out
break;
}
currentTagMeta = (0, _validator.tagMetaFor)(current);
currentMeta = (0, _meta2.peekMeta)(current);
}
return chainTags;
}
function isElementDescriptor(args) {
var [maybeTarget, maybeKey, maybeDesc] = args;
return (// Ensure we have the right number of args
args.length === 3 && ( // Make sure the target is a class or object (prototype)
typeof maybeTarget === 'function' || typeof maybeTarget === 'object' && maybeTarget !== null) && // Make sure the key is a string
typeof maybeKey === 'string' && ( // Make sure the descriptor is the right shape
typeof maybeDesc === 'object' && maybeDesc !== null || maybeDesc === undefined)
);
}
function nativeDescDecorator(propertyDesc) {
var decorator = function () {
return propertyDesc;
};
setClassicDecorator(decorator);
return decorator;
}
/**
Objects of this type can implement an interface to respond to requests to
get and set. The default implementation handles simple properties.
@class Descriptor
@private
*/
class ComputedDescriptor {
constructor() {
this.enumerable = true;
this.configurable = true;
this._dependentKeys = undefined;
this._meta = undefined;
}
setup(_obj, keyName, _propertyDesc, meta$$1) {
meta$$1.writeDescriptors(keyName, this);
}
teardown(_obj, keyName, meta$$1) {
meta$$1.removeDescriptors(keyName);
}
}
var COMPUTED_GETTERS;
if (true
/* DEBUG */
) {
COMPUTED_GETTERS = new _util._WeakSet();
}
function DESCRIPTOR_GETTER_FUNCTION(name, descriptor) {
function getter() {
return descriptor.get(this, name);
}
if (true
/* DEBUG */
) {
COMPUTED_GETTERS.add(getter);
}
return getter;
}
function DESCRIPTOR_SETTER_FUNCTION(name, descriptor) {
var set = function CPSETTER_FUNCTION(value) {
return descriptor.set(this, name, value);
};
COMPUTED_SETTERS.add(set);
return set;
}
var COMPUTED_SETTERS = new _util._WeakSet();
function makeComputedDecorator(desc, DecoratorClass) {
var decorator = function COMPUTED_DECORATOR(target, key, propertyDesc, maybeMeta, isClassicDecorator) {
(true && !(isClassicDecorator || !propertyDesc || !propertyDesc.get || !COMPUTED_GETTERS.has(propertyDesc.get)) && (0, _debug.assert)(`Only one computed property decorator can be applied to a class field or accessor, but '${key}' was decorated twice. You may have added the decorator to both a getter and setter, which is unnecessary.`, isClassicDecorator || !propertyDesc || !propertyDesc.get || !COMPUTED_GETTERS.has(propertyDesc.get)));
var meta$$1 = arguments.length === 3 ? (0, _meta2.meta)(target) : maybeMeta;
desc.setup(target, key, propertyDesc, meta$$1);
var computedDesc = {
enumerable: desc.enumerable,
configurable: desc.configurable,
get: DESCRIPTOR_GETTER_FUNCTION(key, desc),
set: DESCRIPTOR_SETTER_FUNCTION(key, desc)
};
return computedDesc;
};
setClassicDecorator(decorator, desc);
Object.setPrototypeOf(decorator, DecoratorClass.prototype);
return decorator;
} /////////////
var DECORATOR_DESCRIPTOR_MAP = new WeakMap();
/**
Returns the CP descriptor associated with `obj` and `keyName`, if any.
@method descriptorForProperty
@param {Object} obj the object to check
@param {String} keyName the key to check
@return {Descriptor}
@private
*/
function descriptorForProperty(obj, keyName, _meta) {
(true && !(obj !== null) && (0, _debug.assert)('Cannot call `descriptorForProperty` on null', obj !== null));
(true && !(obj !== undefined) && (0, _debug.assert)('Cannot call `descriptorForProperty` on undefined', obj !== undefined));
(true && !(typeof obj === 'object' || typeof obj === 'function') && (0, _debug.assert)(`Cannot call \`descriptorForProperty\` on ${typeof obj}`, typeof obj === 'object' || typeof obj === 'function'));
var meta$$1 = _meta === undefined ? (0, _meta2.peekMeta)(obj) : _meta;
if (meta$$1 !== null) {
return meta$$1.peekDescriptors(keyName);
}
}
function descriptorForDecorator(dec) {
return DECORATOR_DESCRIPTOR_MAP.get(dec);
}
/**
Check whether a value is a decorator
@method isClassicDecorator
@param {any} possibleDesc the value to check
@return {boolean}
@private
*/
function isClassicDecorator(dec) {
return typeof dec === 'function' && DECORATOR_DESCRIPTOR_MAP.has(dec);
}
/**
Set a value as a decorator
@method setClassicDecorator
@param {function} decorator the value to mark as a decorator
@private
*/
function setClassicDecorator(dec, value = true) {
DECORATOR_DESCRIPTOR_MAP.set(dec, value);
}
/**
@module @ember/object
*/
var END_WITH_EACH_REGEX = /\.@each$/;
/**
Expands `pattern`, invoking `callback` for each expansion.
The only pattern supported is brace-expansion, anything else will be passed
once to `callback` directly.
Example
```js
import { expandProperties } from '@ember/object/computed';
function echo(arg){ console.log(arg); }
expandProperties('foo.bar', echo); //=> 'foo.bar'
expandProperties('{foo,bar}', echo); //=> 'foo', 'bar'
expandProperties('foo.{bar,baz}', echo); //=> 'foo.bar', 'foo.baz'
expandProperties('{foo,bar}.baz', echo); //=> 'foo.baz', 'bar.baz'
expandProperties('foo.{bar,baz}.[]', echo) //=> 'foo.bar.[]', 'foo.baz.[]'
expandProperties('{foo,bar}.{spam,eggs}', echo) //=> 'foo.spam', 'foo.eggs', 'bar.spam', 'bar.eggs'
expandProperties('{foo}.bar.{baz}') //=> 'foo.bar.baz'
```
@method expandProperties
@static
@for @ember/object/computed
@public
@param {String} pattern The property pattern to expand.
@param {Function} callback The callback to invoke. It is invoked once per
expansion, and is passed the expansion.
*/
function expandProperties(pattern, callback) {
(true && !(typeof pattern === 'string') && (0, _debug.assert)(`A computed property key must be a string, you passed ${typeof pattern} ${pattern}`, typeof pattern === 'string'));
(true && !(pattern.indexOf(' ') === -1) && (0, _debug.assert)('Brace expanded properties cannot contain spaces, e.g. "user.{firstName, lastName}" should be "user.{firstName,lastName}"', pattern.indexOf(' ') === -1)); // regex to look for double open, double close, or unclosed braces
(true && !(pattern.match(/\{[^}{]*\{|\}[^}{]*\}|\{[^}]*$/g) === null) && (0, _debug.assert)(`Brace expanded properties have to be balanced and cannot be nested, pattern: ${pattern}`, pattern.match(/\{[^}{]*\{|\}[^}{]*\}|\{[^}]*$/g) === null));
var start = pattern.indexOf('{');
if (start < 0) {
callback(pattern.replace(END_WITH_EACH_REGEX, '.[]'));
} else {
dive('', pattern, start, callback);
}
}
function dive(prefix, pattern, start, callback) {
var end = pattern.indexOf('}'),
i = 0,
newStart,
arrayLength;
var tempArr = pattern.substring(start + 1, end).split(',');
var after = pattern.substring(end + 1);
prefix = prefix + pattern.substring(0, start);
arrayLength = tempArr.length;
while (i < arrayLength) {
newStart = after.indexOf('{');
if (newStart < 0) {
callback((prefix + tempArr[i++] + after).replace(END_WITH_EACH_REGEX, '.[]'));
} else {
dive(prefix + tempArr[i++], after, newStart, callback);
}
}
}
/**
@module @ember/object
*/
var DEEP_EACH_REGEX = /\.@each\.[^.]+\./;
function noop() {}
/**
`@computed` is a decorator that turns a JavaScript getter and setter into a
computed property, which is a _cached, trackable value_. By default the getter
will only be called once and the result will be cached. You can specify
various properties that your computed property depends on. This will force the
cached result to be cleared if the dependencies are modified, and lazily recomputed the next time something asks for it.
In the following example we decorate a getter - `fullName` - by calling
`computed` with the property dependencies (`firstName` and `lastName`) as
arguments. The `fullName` getter will be called once (regardless of how many
times it is accessed) as long as its dependencies do not change. Once
`firstName` or `lastName` are updated any future calls to `fullName` will
incorporate the new values, and any watchers of the value such as templates
will be updated:
```javascript
import { computed, set } from '@ember/object';
class Person {
constructor(firstName, lastName) {
set(this, 'firstName', firstName);
set(this, 'lastName', lastName);
}
@computed('firstName', 'lastName')
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
});
let tom = new Person('Tom', 'Dale');
tom.fullName; // 'Tom Dale'
```
You can also provide a setter, which will be used when updating the computed
property. Ember's `set` function must be used to update the property
since it will also notify observers of the property:
```javascript
import { computed, set } from '@ember/object';
class Person {
constructor(firstName, lastName) {
set(this, 'firstName', firstName);
set(this, 'lastName', lastName);
}
@computed('firstName', 'lastName')
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
set fullName(value) {
let [firstName, lastName] = value.split(' ');
set(this, 'firstName', firstName);
set(this, 'lastName', lastName);
}
});
let person = new Person();
set(person, 'fullName', 'Peter Wagenet');
person.firstName; // 'Peter'
person.lastName; // 'Wagenet'
```
You can also pass a getter function or object with `get` and `set` functions
as the last argument to the computed decorator. This allows you to define
computed property _macros_:
```js
import { computed } from '@ember/object';
function join(...keys) {
return computed(...keys, function() {
return keys.map(key => this[key]).join(' ');
});
}
class Person {
@join('firstName', 'lastName')
fullName;
}
```
Note that when defined this way, getters and setters receive the _key_ of the
property they are decorating as the first argument. Setters receive the value
they are setting to as the second argument instead. Additionally, setters must
_return_ the value that should be cached:
```javascript
import { computed, set } from '@ember/object';
function fullNameMacro(firstNameKey, lastNameKey) {
return computed(firstNameKey, lastNameKey, {
get() {
return `${this[firstNameKey]} ${this[lastNameKey]}`;
}
set(key, value) {
let [firstName, lastName] = value.split(' ');
set(this, firstNameKey, firstName);
set(this, lastNameKey, lastName);
return value;
}
});
}
class Person {
constructor(firstName, lastName) {
set(this, 'firstName', firstName);
set(this, 'lastName', lastName);
}
@fullNameMacro('firstName', 'lastName') fullName;
});
let person = new Person();
set(person, 'fullName', 'Peter Wagenet');
person.firstName; // 'Peter'
person.lastName; // 'Wagenet'
```
Computed properties can also be used in classic classes. To do this, we
provide the getter and setter as the last argument like we would for a macro,
and we assign it to a property on the class definition. This is an _anonymous_
computed macro:
```javascript
import EmberObject, { computed, set } from '@ember/object';
let Person = EmberObject.extend({
// these will be supplied by `create`
firstName: null,
lastName: null,
fullName: computed('firstName', 'lastName', {
get() {
return `${this.firstName} ${this.lastName}`;
}
set(key, value) {
let [firstName, lastName] = value.split(' ');
set(this, 'firstName', firstName);
set(this, 'lastName', lastName);
return value;
}
})
});
let tom = Person.create({
firstName: 'Tom',
lastName: 'Dale'
});
tom.get('fullName') // 'Tom Dale'
```
You can overwrite computed property without setters with a normal property (no
longer computed) that won't change if dependencies change. You can also mark
computed property as `.readOnly()` and block all attempts to set it.
```javascript
import { computed, set } from '@ember/object';
class Person {
constructor(firstName, lastName) {
set(this, 'firstName', firstName);
set(this, 'lastName', lastName);
}
@computed('firstName', 'lastName').readOnly()
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
});
let person = new Person();
person.set('fullName', 'Peter Wagenet'); // Uncaught Error: Cannot set read-only property "fullName" on object: <(...):emberXXX>
```
Additional resources:
- [Decorators RFC](https://github.com/emberjs/rfcs/blob/master/text/0408-decorators.md)
- [New CP syntax RFC](https://github.com/emberjs/rfcs/blob/master/text/0011-improved-cp-syntax.md)
- [New computed syntax explained in "Ember 1.12 released" ](https://emberjs.com/blog/2015/05/13/ember-1-12-released.html#toc_new-computed-syntax)
@class ComputedProperty
@public
*/
class ComputedProperty extends ComputedDescriptor {
constructor(args) {
super();
this._readOnly = false;
this._hasConfig = false;
this._getter = undefined;
this._setter = undefined;
var maybeConfig = args[args.length - 1];
if (typeof maybeConfig === 'function' || maybeConfig !== null && typeof maybeConfig === 'object') {
this._hasConfig = true;
var config = args.pop();
if (typeof config === 'function') {
(true && !(!isClassicDecorator(config)) && (0, _debug.assert)(`You attempted to pass a computed property instance to computed(). Computed property instances are decorator functions, and cannot be passed to computed() because they cannot be turned into decorators twice`, !isClassicDecorator(config)));
this._getter = config;
} else {
var objectConfig = config;
(true && !(typeof objectConfig === 'object' && !Array.isArray(objectConfig)) && (0, _debug.assert)('computed expects a function or an object as last argument.', typeof objectConfig === 'object' && !Array.isArray(objectConfig)));
(true && !(Object.keys(objectConfig).every(key => key === 'get' || key === 'set')) && (0, _debug.assert)('Config object passed to computed can only contain `get` and `set` keys.', Object.keys(objectConfig).every(key => key === 'get' || key === 'set')));
(true && !(Boolean(objectConfig.get) || Boolean(objectConfig.set)) && (0, _debug.assert)('Computed properties must receive a getter or a setter, you passed none.', Boolean(objectConfig.get) || Boolean(objectConfig.set)));
this._getter = objectConfig.get || noop;
this._setter = objectConfig.set;
}
}
if (args.length > 0) {
this._property(...args);
}
}
setup(obj, keyName, propertyDesc, meta$$1) {
super.setup(obj, keyName, propertyDesc, meta$$1);
(true && !(!(propertyDesc && typeof propertyDesc.value === 'function')) && (0, _debug.assert)(`@computed can only be used on accessors or fields, attempted to use it with ${keyName} but that was a method. Try converting it to a getter (e.g. \`get ${keyName}() {}\`)`, !(propertyDesc && typeof propertyDesc.value === 'function')));
(true && !(!propertyDesc || !propertyDesc.initializer) && (0, _debug.assert)(`@computed can only be used on empty fields. ${keyName} has an initial value (e.g. \`${keyName} = someValue\`)`, !propertyDesc || !propertyDesc.initializer));
(true && !(!(this._hasConfig && propertyDesc && (typeof propertyDesc.get === 'function' || typeof propertyDesc.set === 'function'))) && (0, _debug.assert)(`Attempted to apply a computed property that already has a getter/setter to a ${keyName}, but it is a method or an accessor. If you passed @computed a function or getter/setter (e.g. \`@computed({ get() { ... } })\`), then it must be applied to a field`, !(this._hasConfig && propertyDesc && (typeof propertyDesc.get === 'function' || typeof propertyDesc.set === 'function'))));
if (this._hasConfig === false) {
(true && !(propertyDesc && (typeof propertyDesc.get === 'function' || typeof propertyDesc.set === 'function')) && (0, _debug.assert)(`Attempted to use @computed on ${keyName}, but it did not have a getter or a setter. You must either pass a get a function or getter/setter to @computed directly (e.g. \`@computed({ get() { ... } })\`) or apply @computed directly to a getter/setter`, propertyDesc && (typeof propertyDesc.get === 'function' || typeof propertyDesc.set === 'function')));
var {
get: _get2,
set: _set2
} = propertyDesc;
if (_get2 !== undefined) {
this._getter = _get2;
}
if (_set2 !== undefined) {
this._setter = function setterWrapper(_key, value) {
var ret = _set2.call(this, value);
if (_get2 !== undefined) {
return typeof ret === 'undefined' ? _get2.call(this) : ret;
}
return ret;
};
}
}
}
_property(...passedArgs) {
var args = [];
function addArg(property) {
(true && !(DEEP_EACH_REGEX.test(property) === false) && (0, _debug.assert)(`Dependent keys containing @each only work one level deep. ` + `You used the key "${property}" which is invalid. ` + `Please create an intermediary computed property or ` + `switch to using tracked properties.`, DEEP_EACH_REGEX.test(property) === false));
args.push(property);
}
for (var i = 0; i < passedArgs.length; i++) {
expandProperties(passedArgs[i], addArg);
}
this._dependentKeys = args;
}
get(obj, keyName) {
var meta$$1 = (0, _meta2.meta)(obj);
var tagMeta = (0, _validator.tagMetaFor)(obj);
var propertyTag = (0, _validator.tagFor)(obj, keyName, tagMeta);
var ret;
var revision = meta$$1.revisionFor(keyName);
if (revision !== undefined && (0, _validator.validateTag)(propertyTag, revision)) {
ret = meta$$1.valueFor(keyName);
} else {
// For backwards compatibility, we only throw if the CP has any dependencies. CPs without dependencies
// should be allowed, even after the object has been destroyed, which is why we check _dependentKeys.
(true && !(this._dependentKeys === undefined || !(0, _destroyable.isDestroyed)(obj)) && (0, _debug.assert)(`Attempted to access the computed ${obj}.${keyName} on a destroyed object, which is not allowed`, this._dependentKeys === undefined || !(0, _destroyable.isDestroyed)(obj)));
var {
_getter,
_dependentKeys
} = this; // Create a tracker that absorbs any trackable actions inside the CP
(0, _validator.untrack)(() => {
ret = _getter.call(obj, keyName);
});
if (_dependentKeys !== undefined) {
(0, _validator.updateTag)(propertyTag, getChainTagsForKeys(obj, _dependentKeys, tagMeta, meta$$1));
if (true
/* DEBUG */
) {
_validator.ALLOW_CYCLES.set(propertyTag, true);
}
}
meta$$1.setValueFor(keyName, ret);
meta$$1.setRevisionFor(keyName, (0, _validator.valueForTag)(propertyTag));
finishLazyChains(meta$$1, keyName, ret);
}
(0, _validator.consumeTag)(propertyTag); // Add the tag of the returned value if it is an array, since arrays
// should always cause updates if they are consumed and then changed
if (Array.isArray(ret)) {
(0, _validator.consumeTag)((0, _validator.tagFor)(ret, '[]'));
}
return ret;
}
set(obj, keyName, value) {
if (this._readOnly) {
this._throwReadOnlyError(obj, keyName);
}
(true && !(this._setter !== undefined) && (0, _debug.assert)(`Cannot override the computed property \`${keyName}\` on ${(0, _utils.toString)(obj)}.`, this._setter !== undefined));
var meta$$1 = (0, _meta2.meta)(obj); // ensure two way binding works when the component has defined a computed
// property with both a setter and dependent keys, in that scenario without
// the sync observer added below the caller's value will never be updated
//
// See GH#18147 / GH#19028 for details.
if ( // ensure that we only run this once, while the component is being instantiated
meta$$1.isInitializing() && this._dependentKeys !== undefined && this._dependentKeys.length > 0 && // These two properties are set on Ember.Component
typeof obj[PROPERTY_DID_CHANGE] === 'function' && obj.isComponent) {
addObserver(obj, keyName, () => {
obj[PROPERTY_DID_CHANGE](keyName);
}, undefined, true);
}
var ret;
try {
beginPropertyChanges();
ret = this._set(obj, keyName, value, meta$$1);
finishLazyChains(meta$$1, keyName, ret);
var tagMeta = (0, _validator.tagMetaFor)(obj);
var propertyTag = (0, _validator.tagFor)(obj, keyName, tagMeta);
var {
_dependentKeys
} = this;
if (_dependentKeys !== undefined) {
(0, _validator.updateTag)(propertyTag, getChainTagsForKeys(obj, _dependentKeys, tagMeta, meta$$1));
if (true
/* DEBUG */
) {
_validator.ALLOW_CYCLES.set(propertyTag, true);
}
}
meta$$1.setRevisionFor(keyName, (0, _validator.valueForTag)(propertyTag));
} finally {
endPropertyChanges();
}
return ret;
}
_throwReadOnlyError(obj, keyName) {
throw new _error.default(`Cannot set read-only property "${keyName}" on object: ${(0, _utils.inspect)(obj)}`);
}
_set(obj, keyName, value, meta$$1) {
var hadCachedValue = meta$$1.revisionFor(keyName) !== undefined;
var cachedValue = meta$$1.valueFor(keyName);
var ret;
var {
_setter
} = this;
setObserverSuspended(obj, keyName, true);
try {
ret = _setter.call(obj, keyName, value, cachedValue);
} finally {
setObserverSuspended(obj, keyName, false);
} // allows setter to return the same value that is cached already
if (hadCachedValue && cachedValue === ret) {
return ret;
}
meta$$1.setValueFor(keyName, ret);
notifyPropertyChange(obj, keyName, meta$$1, value);
return ret;
}
/* called before property is overridden */
teardown(obj, keyName, meta$$1) {
if (meta$$1.revisionFor(keyName) !== undefined) {
meta$$1.setRevisionFor(keyName, undefined);
meta$$1.setValueFor(keyName, undefined);
}
super.teardown(obj, keyName, meta$$1);
}
}
_exports.ComputedProperty = ComputedProperty;
class AutoComputedProperty extends ComputedProperty {
get(obj, keyName) {
var meta$$1 = (0, _meta2.meta)(obj);
var tagMeta = (0, _validator.tagMetaFor)(obj);
var propertyTag = (0, _validator.tagFor)(obj, keyName, tagMeta);
var ret;
var revision = meta$$1.revisionFor(keyName);
if (revision !== undefined && (0, _validator.validateTag)(propertyTag, revision)) {
ret = meta$$1.valueFor(keyName);
} else {
(true && !(!(0, _destroyable.isDestroyed)(obj)) && (0, _debug.assert)(`Attempted to access the computed ${obj}.${keyName} on a destroyed object, which is not allowed`, !(0, _destroyable.isDestroyed)(obj)));
var {
_getter
} = this; // Create a tracker that absorbs any trackable actions inside the CP
var tag = (0, _validator.track)(() => {
ret = _getter.call(obj, keyName);
});
(0, _validator.updateTag)(propertyTag, tag);
meta$$1.setValueFor(keyName, ret);
meta$$1.setRevisionFor(keyName, (0, _validator.valueForTag)(propertyTag));
finishLazyChains(meta$$1, keyName, ret);
}
(0, _validator.consumeTag)(propertyTag); // Add the tag of the returned value if it is an array, since arrays
// should always cause updates if they are consumed and then changed
if (Array.isArray(ret)) {
(0, _validator.consumeTag)((0, _validator.tagFor)(ret, '[]', tagMeta));
}
return ret;
}
} // TODO: This class can be svelted once `meta` has been deprecated
class ComputedDecoratorImpl extends Function {
/**
Call on a computed property to set it into read-only mode. When in this
mode the computed property will throw an error when set.
Example:
```javascript
import { computed, set } from '@ember/object';
class Person {
@computed().readOnly()
get guid() {
return 'guid-guid-guid';
}
}
let person = new Person();
set(person, 'guid', 'new-guid'); // will throw an exception
```
Classic Class Example:
```javascript
import EmberObject, { computed } from '@ember/object';
let Person = EmberObject.extend({
guid: computed(function() {
return 'guid-guid-guid';
}).readOnly()
});
let person = Person.create();
person.set('guid', 'new-guid'); // will throw an exception
```
@method readOnly
@return {ComputedProperty} this
@chainable
@public
*/
readOnly() {
var desc = descriptorForDecorator(this);
(true && !(!(desc._setter && desc._setter !== desc._getter)) && (0, _debug.assert)('Computed properties that define a setter using the new syntax cannot be read-only', !(desc._setter && desc._setter !== desc._getter)));
desc._readOnly = true;
return this;
}
/**
In some cases, you may want to annotate computed properties with additional
metadata about how they function or what values they operate on. For example,
computed property functions may close over variables that are then no longer
available for introspection. You can pass a hash of these values to a
computed property.
Example:
```javascript
import { computed } from '@ember/object';
import Person from 'my-app/utils/person';
class Store {
@computed().meta({ type: Person })
get person() {
let personId = this.personId;
return Person.create({ id: personId });
}
}
```
Classic Class Example:
```javascript
import { computed } from '@ember/object';
import Person from 'my-app/utils/person';
const Store = EmberObject.extend({
person: computed(function() {
let personId = this.get('personId');
return Person.create({ id: personId });
}).meta({ type: Person })
});
```
The hash that you pass to the `meta()` function will be saved on the
computed property descriptor under the `_meta` key. Ember runtime
exposes a public API for retrieving these values from classes,
via the `metaForProperty()` function.
@method meta
@param {Object} meta
@chainable
@public
*/
meta(meta$$1) {
var prop = descriptorForDecorator(this);
if (arguments.length === 0) {
return prop._meta || {};
} else {
prop._meta = meta$$1;
return this;
}
} // TODO: Remove this when we can provide alternatives in the ecosystem to
// addons such as ember-macro-helpers that use it.
get _getter() {
return descriptorForDecorator(this)._getter;
} // TODO: Refactor this, this is an internal API only
set enumerable(value) {
descriptorForDecorator(this).enumerable = value;
}
}
function computed(...args) {
(true && !(!(isElementDescriptor(args.slice(0, 3)) && args.length === 5 && args[4] === true)) && (0, _debug.assert)(`@computed can only be used directly as a native decorator. If you're using tracked in classic classes, add parenthesis to call it like a function: computed()`, !(isElementDescriptor(args.slice(0, 3)) && args.length === 5 && args[4] === true)));
if (isElementDescriptor(args)) {
var decorator = makeComputedDecorator(new ComputedProperty([]), ComputedDecoratorImpl);
return decorator(args[0], args[1], args[2]);
}
return makeComputedDecorator(new ComputedProperty(args), ComputedDecoratorImpl);
}
function autoComputed(...config) {
return makeComputedDecorator(new AutoComputedProperty(config), ComputedDecoratorImpl);
}
/**
Allows checking if a given property on an object is a computed property. For the most part,
this doesn't matter (you would normally just access the property directly and use its value),
but for some tooling specific scenarios (e.g. the ember-inspector) it is important to
differentiate if a property is a computed property or a "normal" property.
This will work on either a class's prototype or an instance itself.
@static
@method isComputed
@for @ember/debug
@private
*/
function isComputed(obj, key) {
return Boolean(descriptorForProperty(obj, key));
}
function getCachedValueFor(obj, key) {
var meta$$1 = (0, _meta2.peekMeta)(obj);
if (meta$$1) {
return meta$$1.valueFor(key);
}
}
/**
@module @ember/object
*/
/**
NOTE: This is a low-level method used by other parts of the API. You almost
never want to call this method directly. Instead you should use
`mixin()` to define new properties.
Defines a property on an object. This method works much like the ES5
`Object.defineProperty()` method except that it can also accept computed
properties and other special descriptors.
Normally this method takes only three parameters. However if you pass an
instance of `Descriptor` as the third param then you can pass an
optional value as the fourth parameter. This is often more efficient than
creating new descriptor hashes for each property.
## Examples
```javascript
import { defineProperty, computed } from '@ember/object';
// ES5 compatible mode
defineProperty(contact, 'firstName', {
writable: true,
configurable: false,
enumerable: true,
value: 'Charles'
});
// define a simple property
defineProperty(contact, 'lastName', undefined, 'Jolley');
// define a computed property
defineProperty(contact, 'fullName', computed('firstName', 'lastName', function() {
return this.firstName+' '+this.lastName;
}));
```
@public
@method defineProperty
@static
@for @ember/object
@param {Object} obj the object to define this property on. This may be a prototype.
@param {String} keyName the name of the property
@param {Descriptor} [desc] an instance of `Descriptor` (typically a
computed property) or an ES5 descriptor.
You must provide this or `data` but not both.
@param {*} [data] something other than a descriptor, that will
become the explicit value of this property.
*/
function defineProperty(obj, keyName, desc, data, _meta) {
var meta$$1 = _meta === undefined ? (0, _meta2.meta)(obj) : _meta;
var previousDesc = descriptorForProperty(obj, keyName, meta$$1);
var wasDescriptor = previousDesc !== undefined;
if (wasDescriptor) {
previousDesc.teardown(obj, keyName, meta$$1);
}
if (isClassicDecorator(desc)) {
defineDecorator(obj, keyName, desc, meta$$1);
} else if (desc === null || desc === undefined) {
defineValue(obj, keyName, data, wasDescriptor, true);
} else {
// fallback to ES5
Object.defineProperty(obj, keyName, desc);
} // if key is being watched, override chains that
// were initialized with the prototype
if (!meta$$1.isPrototypeMeta(obj)) {
revalidateObservers(obj);
}
}
function defineDecorator(obj, keyName, desc, meta$$1) {
var propertyDesc;
if (true
/* DEBUG */
) {
propertyDesc = desc(obj, keyName, undefined, meta$$1, true);
} else {
propertyDesc = desc(obj, keyName, undefined, meta$$1);
}
Object.defineProperty(obj, keyName, propertyDesc); // pass the decorator function forward for backwards compat
return desc;
}
function defineValue(obj, keyName, value, wasDescriptor, enumerable = true) {
if (wasDescriptor === true || enumerable === false) {
Object.defineProperty(obj, keyName, {
configurable: true,
enumerable,
writable: true,
value
});
} else {
if (true
/* DEBUG */
) {
(0, _utils.setWithMandatorySetter)(obj, keyName, value);
} else {
obj[keyName] = value;
}
}
return value;
}
var firstDotIndexCache = new _utils.Cache(1000, key => key.indexOf('.'));
function isPath(path) {
return typeof path === 'string' && firstDotIndexCache.get(path) !== -1;
}
/**
@module @ember/object
*/
var PROXY_CONTENT = (0, _utils.symbol)('PROXY_CONTENT');
_exports.PROXY_CONTENT = PROXY_CONTENT;
var getPossibleMandatoryProxyValue;
if (true
/* DEBUG */
) {
getPossibleMandatoryProxyValue = function getPossibleMandatoryProxyValue(obj, keyName) {
var content = obj[PROXY_CONTENT];
if (content === undefined) {
return obj[keyName];
} else {
/* global Reflect */
return Reflect.get(content, keyName, obj);
}
};
} // ..........................................................
// GET AND SET
//
// If we are on a platform that supports accessors we can use those.
// Otherwise simulate accessors by looking up the property directly on the
// object.
/**
Gets the value of a property on an object. If the property is computed,
the function will be invoked. If the property is not defined but the
object implements the `unknownProperty` method then that will be invoked.
```javascript
import { get } from '@ember/object';
get(obj, "name");
```
If you plan to run on IE8 and older browsers then you should use this
method anytime you want to retrieve a property on an object that you don't
know for sure is private. (Properties beginning with an underscore '_'
are considered private.)
On all newer browsers, you only need to use this method to retrieve
properties if the property might not be defined on the object and you want
to respect the `unknownProperty` handler. Otherwise you can ignore this
method.
Note that if the object itself is `undefined`, this method will throw
an error.
@method get
@for @ember/object
@static
@param {Object} obj The object to retrieve from.
@param {String} keyName The property key to retrieve
@return {Object} the property value or `null`.
@public
*/
function get(obj, keyName) {
(true && !(arguments.length === 2) && (0, _debug.assert)(`Get must be called with two arguments; an object and a property key`, arguments.length === 2));
(true && !(obj !== undefined && obj !== null) && (0, _debug.assert)(`Cannot call get with '${keyName}' on an undefined object.`, obj !== undefined && obj !== null));
(true && !(typeof keyName === 'string' || typeof keyName === 'number' && !isNaN(keyName)) && (0, _debug.assert)(`The key provided to get must be a string or number, you passed ${keyName}`, typeof keyName === 'string' || typeof keyName === 'number' && !isNaN(keyName)));
(true && !(typeof keyName !== 'string' || keyName.lastIndexOf('this.', 0) !== 0) && (0, _debug.assert)(`'this' in paths is not supported`, typeof keyName !== 'string' || keyName.lastIndexOf('this.', 0) !== 0));
return isPath(keyName) ? _getPath(obj, keyName) : _getProp(obj, keyName);
}
function _getProp(obj, keyName) {
var type = typeof obj;
var isObject$$1 = type === 'object';
var isFunction = type === 'function';
var isObjectLike = isObject$$1 || isFunction;
var value;
if (isObjectLike) {
if (true
/* DEBUG */
) {
value = getPossibleMandatoryProxyValue(obj, keyName);
} else {
value = obj[keyName];
}
if (value === undefined && isObject$$1 && !(keyName in obj) && typeof obj.unknownProperty === 'function') {
value = obj.unknownProperty(keyName);
}
if ((0, _validator.isTracking)()) {
(0, _validator.consumeTag)((0, _validator.tagFor)(obj, keyName));
if (Array.isArray(value) || (0, _utils.isEmberArray)(value)) {
// Add the tag of the returned value if it is an array, since arrays
// should always cause updates if they are consumed and then changed
(0, _validator.consumeTag)((0, _validator.tagFor)(value, '[]'));
}
}
} else {
value = obj[keyName];
}
return value;
}
function _getPath(root, path) {
var obj = root;
var parts = typeof path === 'string' ? path.split('.') : path;
for (var i = 0; i < parts.length; i++) {
if (obj === undefined || obj === null || obj.isDestroyed) {
return undefined;
}
obj = _getProp(obj, parts[i]);
}
return obj;
}
_getProp('foo', 'a');
_getProp('foo', 1);
_getProp({}, 'a');
_getProp({}, 1);
_getProp({
unkonwnProperty() {}
}, 'a');
_getProp({
unkonwnProperty() {}
}, 1);
get({}, 'foo');
get({}, 'foo.bar');
var fakeProxy = {};
(0, _utils.setProxy)(fakeProxy);
(0, _validator.track)(() => _getProp({}, 'a'));
(0, _validator.track)(() => _getProp({}, 1));
(0, _validator.track)(() => _getProp({
a: []
}, 'a'));
(0, _validator.track)(() => _getProp({
a: fakeProxy
}, 'a'));
/**
@module @ember/object
*/
/**
Sets the value of a property on an object, respecting computed properties
and notifying observers and other listeners of the change.
If the specified property is not defined on the object and the object
implements the `setUnknownProperty` method, then instead of setting the
value of the property on the object, its `setUnknownProperty` handler
will be invoked with the two parameters `keyName` and `value`.
```javascript
import { set } from '@ember/object';
set(obj, "name", value);
```
@method set
@static
@for @ember/object
@param {Object} obj The object to modify.
@param {String} keyName The property key to set
@param {Object} value The value to set
@return {Object} the passed value.
@public
*/
function set(obj, keyName, value, tolerant) {
(true && !(arguments.length === 3 || arguments.length === 4) && (0, _debug.assert)(`Set must be called with three or four arguments; an object, a property key, a value and tolerant true/false`, arguments.length === 3 || arguments.length === 4));
(true && !(obj && typeof obj === 'object' || typeof obj === 'function') && (0, _debug.assert)(`Cannot call set with '${keyName}' on an undefined object.`, obj && typeof obj === 'object' || typeof obj === 'function'));
(true && !(typeof keyName === 'string' || typeof keyName === 'number' && !isNaN(keyName)) && (0, _debug.assert)(`The key provided to set must be a string or number, you passed ${keyName}`, typeof keyName === 'string' || typeof keyName === 'number' && !isNaN(keyName)));
(true && !(typeof keyName !== 'string' || keyName.lastIndexOf('this.', 0) !== 0) && (0, _debug.assert)(`'this' in paths is not supported`, typeof keyName !== 'string' || keyName.lastIndexOf('this.', 0) !== 0));
if (obj.isDestroyed) {
(true && !(tolerant) && (0, _debug.assert)(`calling set on destroyed object: ${(0, _utils.toString)(obj)}.${keyName} = ${(0, _utils.toString)(value)}`, tolerant));
return value;
}
return isPath(keyName) ? _setPath(obj, keyName, value, tolerant) : _setProp(obj, keyName, value);
}
function _setProp(obj, keyName, value) {
var descriptor = (0, _utils.lookupDescriptor)(obj, keyName);
if (descriptor !== null && COMPUTED_SETTERS.has(descriptor.set)) {
obj[keyName] = value;
return value;
}
var currentValue;
if (true
/* DEBUG */
) {
currentValue = getPossibleMandatoryProxyValue(obj, keyName);
} else {
currentValue = obj[keyName];
}
if (currentValue === undefined && 'object' === typeof obj && !(keyName in obj) && typeof obj.setUnknownProperty === 'function') {
/* unknown property */
obj.setUnknownProperty(keyName, value);
} else {
if (true
/* DEBUG */
) {
(0, _utils.setWithMandatorySetter)(obj, keyName, value);
} else {
obj[keyName] = value;
}
if (currentValue !== value) {
notifyPropertyChange(obj, keyName);
}
}
return value;
}
function _setPath(root, path, value, tolerant) {
var parts = path.split('.');
var keyName = parts.pop();
(true && !(keyName.trim().length > 0) && (0, _debug.assert)('Property set failed: You passed an empty path', keyName.trim().length > 0));
var newRoot = _getPath(root, parts);
if (newRoot !== null && newRoot !== undefined) {
return set(newRoot, keyName, value);
} else if (!tolerant) {
throw new _error.default(`Property set failed: object in path "${parts.join('.')}" could not be found.`);
}
}
/**
Error-tolerant form of `set`. Will not blow up if any part of the
chain is `undefined`, `null`, or destroyed.
This is primarily used when syncing bindings, which may try to update after
an object has been destroyed.
```javascript
import { trySet } from '@ember/object';
let obj = { name: "Zoey" };
trySet(obj, "contacts.twitter", "@emberjs");
```
@method trySet
@static
@for @ember/object
@param {Object} root The object to modify.
@param {String} path The property path to set
@param {Object} value The value to set
@public
*/
function trySet(root, path, value) {
return set(root, path, value, true);
}
function alias(altKey) {
(true && !(!isElementDescriptor(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @alias as a decorator directly, but it requires a `altKey` parameter', !isElementDescriptor(Array.prototype.slice.call(arguments))));
return makeComputedDecorator(new AliasedProperty(altKey), AliasDecoratorImpl);
} // TODO: This class can be svelted once `meta` has been deprecated
class AliasDecoratorImpl extends Function {
readOnly() {
descriptorForDecorator(this).readOnly();
return this;
}
oneWay() {
descriptorForDecorator(this).oneWay();
return this;
}
meta(meta$$1) {
var prop = descriptorForDecorator(this);
if (arguments.length === 0) {
return prop._meta || {};
} else {
prop._meta = meta$$1;
}
}
}
class AliasedProperty extends ComputedDescriptor {
constructor(altKey) {
super();
this.altKey = altKey;
}
setup(obj, keyName, propertyDesc, meta$$1) {
(true && !(this.altKey !== keyName) && (0, _debug.assert)(`Setting alias '${keyName}' on self`, this.altKey !== keyName));
super.setup(obj, keyName, propertyDesc, meta$$1);
CHAIN_PASS_THROUGH.add(this);
}
get(obj, keyName) {
var ret;
var meta$$1 = (0, _meta2.meta)(obj);
var tagMeta = (0, _validator.tagMetaFor)(obj);
var propertyTag = (0, _validator.tagFor)(obj, keyName, tagMeta); // We don't use the tag since CPs are not automatic, we just want to avoid
// anything tracking while we get the altKey
(0, _validator.untrack)(() => {
ret = get(obj, this.altKey);
});
var lastRevision = meta$$1.revisionFor(keyName);
if (lastRevision === undefined || !(0, _validator.validateTag)(propertyTag, lastRevision)) {
(0, _validator.updateTag)(propertyTag, getChainTagsForKey(obj, this.altKey, tagMeta, meta$$1));
meta$$1.setRevisionFor(keyName, (0, _validator.valueForTag)(propertyTag));
finishLazyChains(meta$$1, keyName, ret);
}
(0, _validator.consumeTag)(propertyTag);
return ret;
}
set(obj, _keyName, value) {
return set(obj, this.altKey, value);
}
readOnly() {
this.set = AliasedProperty_readOnlySet;
}
oneWay() {
this.set = AliasedProperty_oneWaySet;
}
}
function AliasedProperty_readOnlySet(obj, keyName) {
// eslint-disable-line no-unused-vars
throw new _error.default(`Cannot set read-only property '${keyName}' on object: ${(0, _utils.inspect)(obj)}`);
}
function AliasedProperty_oneWaySet(obj, keyName, value) {
defineProperty(obj, keyName, null);
return set(obj, keyName, value);
}
/**
@module ember
*/
/**
Used internally to allow changing properties in a backwards compatible way, and print a helpful
deprecation warning.
@method deprecateProperty
@param {Object} object The object to add the deprecated property to.
@param {String} deprecatedKey The property to add (and print deprecation warnings upon accessing).
@param {String} newKey The property that will be aliased.
@private
@since 1.7.0
*/
function deprecateProperty(object, deprecatedKey, newKey, options) {
function _deprecate() {
(true && !(false) && (0, _debug.deprecate)(`Usage of \`${deprecatedKey}\` is deprecated, use \`${newKey}\` instead.`, false, options));
}
Object.defineProperty(object, deprecatedKey, {
configurable: true,
enumerable: false,
set(value) {
_deprecate();
set(this, newKey, value);
},
get() {
_deprecate();
return get(this, newKey);
}
});
}
var EACH_PROXIES = new WeakMap();
function eachProxyArrayWillChange(array, idx, removedCnt, addedCnt) {
var eachProxy = EACH_PROXIES.get(array);
if (eachProxy !== undefined) {
eachProxy.arrayWillChange(array, idx, removedCnt, addedCnt);
}
}
function eachProxyArrayDidChange(array, idx, removedCnt, addedCnt) {
var eachProxy = EACH_PROXIES.get(array);
if (eachProxy !== undefined) {
eachProxy.arrayDidChange(array, idx, removedCnt, addedCnt);
}
}
/**
@module @ember/utils
*/
/**
Returns true if the passed value is null or undefined. This avoids errors
from JSLint complaining about use of ==, which can be technically
confusing.
```javascript
isNone(); // true
isNone(null); // true
isNone(undefined); // true
isNone(''); // false
isNone([]); // false
isNone(function() {}); // false
```
@method isNone
@static
@for @ember/utils
@param {Object} obj Value to test
@return {Boolean}
@public
*/
function isNone(obj) {
return obj === null || obj === undefined;
}
/**
@module @ember/utils
*/
/**
Verifies that a value is `null` or `undefined`, an empty string, or an empty
array.
Constrains the rules on `isNone` by returning true for empty strings and
empty arrays.
If the value is an object with a `size` property of type number, it is used
to check emptiness.
```javascript
isEmpty(); // true
isEmpty(null); // true
isEmpty(undefined); // true
isEmpty(''); // true
isEmpty([]); // true
isEmpty({ size: 0}); // true
isEmpty({}); // false
isEmpty('Adam Hawkins'); // false
isEmpty([0,1,2]); // false
isEmpty('\n\t'); // false
isEmpty(' '); // false
isEmpty({ size: 1 }) // false
isEmpty({ size: () => 0 }) // false
```
@method isEmpty
@static
@for @ember/utils
@param {Object} obj Value to test
@return {Boolean}
@public
*/
function isEmpty(obj) {
var none = obj === null || obj === undefined;
if (none) {
return none;
}
if (typeof obj.size === 'number') {
return !obj.size;
}
var objectType = typeof obj;
if (objectType === 'object') {
var size = get(obj, 'size');
if (typeof size === 'number') {
return !size;
}
}
if (typeof obj.length === 'number' && objectType !== 'function') {
return !obj.length;
}
if (objectType === 'object') {
var length = get(obj, 'length');
if (typeof length === 'number') {
return !length;
}
}
return false;
}
/**
@module @ember/utils
*/
/**
A value is blank if it is empty or a whitespace string.
```javascript
import { isBlank } from '@ember/utils';
isBlank(); // true
isBlank(null); // true
isBlank(undefined); // true
isBlank(''); // true
isBlank([]); // true
isBlank('\n\t'); // true
isBlank(' '); // true
isBlank({}); // false
isBlank('\n\t Hello'); // false
isBlank('Hello world'); // false
isBlank([1,2,3]); // false
```
@method isBlank
@static
@for @ember/utils
@param {Object} obj Value to test
@return {Boolean}
@since 1.5.0
@public
*/
function isBlank(obj) {
return isEmpty(obj) || typeof obj === 'string' && /\S/.test(obj) === false;
}
/**
@module @ember/utils
*/
/**
A value is present if it not `isBlank`.
```javascript
isPresent(); // false
isPresent(null); // false
isPresent(undefined); // false
isPresent(''); // false
isPresent(' '); // false
isPresent('\n\t'); // false
isPresent([]); // false
isPresent({ length: 0 }); // false
isPresent(false); // true
isPresent(true); // true
isPresent('string'); // true
isPresent(0); // true
isPresent(function() {}); // true
isPresent({}); // true
isPresent('\n\t Hello'); // true
isPresent([1, 2, 3]); // true
```
@method isPresent
@static
@for @ember/utils
@param {Object} obj Value to test
@return {Boolean}
@since 1.8.0
@public
*/
function isPresent(obj) {
return !isBlank(obj);
}
/**
@module ember
*/
/**
Helper class that allows you to register your library with Ember.
Singleton created at `Ember.libraries`.
@class Libraries
@constructor
@private
*/
class Libraries {
constructor() {
this._registry = [];
this._coreLibIndex = 0;
}
_getLibraryByName(name) {
var libs = this._registry;
var count = libs.length;
for (var i = 0; i < count; i++) {
if (libs[i].name === name) {
return libs[i];
}
}
return undefined;
}
register(name, version, isCoreLibrary) {
var index = this._registry.length;
if (!this._getLibraryByName(name)) {
if (isCoreLibrary) {
index = this._coreLibIndex++;
}
this._registry.splice(index, 0, {
name,
version
});
} else {
(true && (0, _debug.warn)(`Library "${name}" is already registered with Ember.`, false, {
id: 'ember-metal.libraries-register'
}));
}
}
registerCoreLibrary(name, version) {
this.register(name, version, true);
}
deRegister(name) {
var lib = this._getLibraryByName(name);
var index;
if (lib) {
index = this._registry.indexOf(lib);
this._registry.splice(index, 1);
}
}
}
_exports.Libraries = Libraries;
if (true
/* DEBUG */
) {
Libraries.prototype.logVersions = function () {
var libs = this._registry;
var nameLengths = libs.map(item => get(item, 'name.length'));
var maxNameLength = Math.max.apply(null, nameLengths);
(0, _debug.debug)('-------------------------------');
for (var i = 0; i < libs.length; i++) {
var lib = libs[i];
var spaces = new Array(maxNameLength - lib.name.length + 1).join(' ');
(0, _debug.debug)([lib.name, spaces, ' : ', lib.version].join(''));
}
(0, _debug.debug)('-------------------------------');
};
}
var LIBRARIES = new Libraries();
_exports.libraries = LIBRARIES;
LIBRARIES.registerCoreLibrary('Ember', _version.default);
/**
@module @ember/object
*/
/**
To get multiple properties at once, call `getProperties`
with an object followed by a list of strings or an array:
```javascript
import { getProperties } from '@ember/object';
getProperties(record, 'firstName', 'lastName', 'zipCode');
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
```
is equivalent to:
```javascript
import { getProperties } from '@ember/object';
getProperties(record, ['firstName', 'lastName', 'zipCode']);
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
```
@method getProperties
@static
@for @ember/object
@param {Object} obj
@param {String...|Array} list of keys to get
@return {Object}
@public
*/
function getProperties(obj, keys) {
var ret = {};
var propertyNames = arguments;
var i = 1;
if (arguments.length === 2 && Array.isArray(keys)) {
i = 0;
propertyNames = arguments[1];
}
for (; i < propertyNames.length; i++) {
ret[propertyNames[i]] = get(obj, propertyNames[i]);
}
return ret;
}
/**
@module @ember/object
*/
/**
Set a list of properties on an object. These properties are set inside
a single `beginPropertyChanges` and `endPropertyChanges` batch, so
observers will be buffered.
```javascript
import EmberObject from '@ember/object';
let anObject = EmberObject.create();
anObject.setProperties({
firstName: 'Stanley',
lastName: 'Stuart',
age: 21
});
```
@method setProperties
@static
@for @ember/object
@param obj
@param {Object} properties
@return properties
@public
*/
function setProperties(obj, properties) {
if (properties === null || typeof properties !== 'object') {
return properties;
}
changeProperties(() => {
var props = Object.keys(properties);
var propertyName;
for (var i = 0; i < props.length; i++) {
propertyName = props[i];
set(obj, propertyName, properties[propertyName]);
}
});
return properties;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
var searchDisabled = false;
var flags = {
_set: 0,
_unprocessedNamespaces: false,
get unprocessedNamespaces() {
return this._unprocessedNamespaces;
},
set unprocessedNamespaces(v) {
this._set++;
this._unprocessedNamespaces = v;
}
};
var unprocessedMixins = false;
var NAMESPACES = [];
_exports.NAMESPACES = NAMESPACES;
var NAMESPACES_BY_ID = Object.create(null);
_exports.NAMESPACES_BY_ID = NAMESPACES_BY_ID;
function addNamespace(namespace) {
flags.unprocessedNamespaces = true;
NAMESPACES.push(namespace);
}
function removeNamespace(namespace) {
var name = (0, _utils.getName)(namespace);
delete NAMESPACES_BY_ID[name];
NAMESPACES.splice(NAMESPACES.indexOf(namespace), 1);
if (name in _environment.context.lookup && namespace === _environment.context.lookup[name]) {
_environment.context.lookup[name] = undefined;
}
}
function findNamespaces() {
if (!flags.unprocessedNamespaces) {
return;
}
var lookup = _environment.context.lookup;
var keys = Object.keys(lookup);
for (var i = 0; i < keys.length; i++) {
var key = keys[i]; // Only process entities that start with uppercase A-Z
if (!isUppercase(key.charCodeAt(0))) {
continue;
}
var obj = tryIsNamespace(lookup, key);
if (obj) {
(0, _utils.setName)(obj, key);
}
}
}
function findNamespace(name) {
if (!searchDisabled) {
processAllNamespaces();
}
return NAMESPACES_BY_ID[name];
}
function processNamespace(namespace) {
_processNamespace([namespace.toString()], namespace, new Set());
}
function processAllNamespaces() {
var unprocessedNamespaces = flags.unprocessedNamespaces;
if (unprocessedNamespaces) {
findNamespaces();
flags.unprocessedNamespaces = false;
}
if (unprocessedNamespaces || unprocessedMixins) {
var namespaces = NAMESPACES;
for (var i = 0; i < namespaces.length; i++) {
processNamespace(namespaces[i]);
}
unprocessedMixins = false;
}
}
function isSearchDisabled() {
return searchDisabled;
}
function setSearchDisabled(flag) {
searchDisabled = Boolean(flag);
}
function setUnprocessedMixins() {
unprocessedMixins = true;
}
function _processNamespace(paths, root, seen) {
var idx = paths.length;
var id = paths.join('.');
NAMESPACES_BY_ID[id] = root;
(0, _utils.setName)(root, id); // Loop over all of the keys in the namespace, looking for classes
for (var key in root) {
if (!hasOwnProperty.call(root, key)) {
continue;
}
var obj = root[key]; // If we are processing the `Ember` namespace, for example, the
// `paths` will start with `["Ember"]`. Every iteration through
// the loop will update the **second** element of this list with
// the key, so processing `Ember.View` will make the Array
// `['Ember', 'View']`.
paths[idx] = key; // If we have found an unprocessed class
if (obj && (0, _utils.getName)(obj) === void 0) {
// Replace the class' `toString` with the dot-separated path
(0, _utils.setName)(obj, paths.join('.')); // Support nested namespaces
} else if (obj && obj.isNamespace) {
// Skip aliased namespaces
if (seen.has(obj)) {
continue;
}
seen.add(obj); // Process the child namespace
_processNamespace(paths, obj, seen);
}
}
paths.length = idx; // cut out last item
}
function isUppercase(code) {
return code >= 65 && code <= 90 // A
; // Z
}
function tryIsNamespace(lookup, prop) {
try {
var obj = lookup[prop];
return (obj !== null && typeof obj === 'object' || typeof obj === 'function') && obj.isNamespace && obj;
} catch (e) {// continue
}
}
/**
@module @ember/object
*/
var a_concat = Array.prototype.concat;
var {
isArray
} = Array;
function extractAccessors(properties) {
if (properties !== undefined) {
var keys = Object.keys(properties);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var desc = Object.getOwnPropertyDescriptor(properties, key);
if (desc.get !== undefined || desc.set !== undefined) {
Object.defineProperty(properties, key, {
value: nativeDescDecorator(desc)
});
}
}
}
return properties;
}
function concatenatedMixinProperties(concatProp, props, values, base) {
// reset before adding each new mixin to pickup concats from previous
var concats = values[concatProp] || base[concatProp];
if (props[concatProp]) {
concats = concats ? a_concat.call(concats, props[concatProp]) : props[concatProp];
}
return concats;
}
function giveDecoratorSuper(key, decorator, property, descs) {
if (property === true) {
return decorator;
}
var originalGetter = property._getter;
if (originalGetter === undefined) {
return decorator;
}
var superDesc = descs[key]; // Check to see if the super property is a decorator first, if so load its descriptor
var superProperty = typeof superDesc === 'function' ? descriptorForDecorator(superDesc) : superDesc;
if (superProperty === undefined || superProperty === true) {
return decorator;
}
var superGetter = superProperty._getter;
if (superGetter === undefined) {
return decorator;
}
var get = (0, _utils.wrap)(originalGetter, superGetter);
var set;
var originalSetter = property._setter;
var superSetter = superProperty._setter;
if (superSetter !== undefined) {
if (originalSetter !== undefined) {
set = (0, _utils.wrap)(originalSetter, superSetter);
} else {
// If the super property has a setter, we default to using it no matter what.
// This is clearly very broken and weird, but it's what was here so we have
// to keep it until the next major at least.
//
// TODO: Add a deprecation here.
set = superSetter;
}
} else {
set = originalSetter;
} // only create a new CP if we must
if (get !== originalGetter || set !== originalSetter) {
// Since multiple mixins may inherit from the same parent, we need
// to clone the computed property so that other mixins do not receive
// the wrapped version.
var dependentKeys = property._dependentKeys || [];
var newProperty = new ComputedProperty([...dependentKeys, {
get,
set
}]);
newProperty._readOnly = property._readOnly;
newProperty._meta = property._meta;
newProperty.enumerable = property.enumerable;
return makeComputedDecorator(newProperty, ComputedProperty);
}
return decorator;
}
function giveMethodSuper(key, method, values, descs) {
// Methods overwrite computed properties, and do not call super to them.
if (descs[key] !== undefined) {
return method;
} // Find the original method in a parent mixin
var superMethod = values[key]; // Only wrap the new method if the original method was a function
if (typeof superMethod === 'function') {
return (0, _utils.wrap)(method, superMethod);
}
return method;
}
function applyConcatenatedProperties(key, value, values) {
var baseValue = values[key];
var ret = (0, _utils.makeArray)(baseValue).concat((0, _utils.makeArray)(value));
if (true
/* DEBUG */
) {
// it is possible to use concatenatedProperties with strings (which cannot be frozen)
// only freeze objects...
if (typeof ret === 'object' && ret !== null) {
// prevent mutating `concatenatedProperties` array after it is applied
Object.freeze(ret);
}
}
return ret;
}
function applyMergedProperties(key, value, values) {
var baseValue = values[key];
(true && !(!isArray(value)) && (0, _debug.assert)(`You passed in \`${JSON.stringify(value)}\` as the value for \`${key}\` but \`${key}\` cannot be an Array`, !isArray(value)));
if (!baseValue) {
return value;
}
var newBase = Object.assign({}, baseValue);
var hasFunction = false;
var props = Object.keys(value);
for (var i = 0; i < props.length; i++) {
var prop = props[i];
var propValue = value[prop];
if (typeof propValue === 'function') {
hasFunction = true;
newBase[prop] = giveMethodSuper(prop, propValue, baseValue, {});
} else {
newBase[prop] = propValue;
}
}
if (hasFunction) {
newBase._super = _utils.ROOT;
}
return newBase;
}
function mergeMixins(mixins, meta$$1, descs, values, base, keys, keysWithSuper) {
var currentMixin;
for (var i = 0; i < mixins.length; i++) {
currentMixin = mixins[i];
(true && !(typeof currentMixin === 'object' && currentMixin !== null && Object.prototype.toString.call(currentMixin) !== '[object Array]') && (0, _debug.assert)(`Expected hash or Mixin instance, got ${Object.prototype.toString.call(currentMixin)}`, typeof currentMixin === 'object' && currentMixin !== null && Object.prototype.toString.call(currentMixin) !== '[object Array]'));
if (MIXINS.has(currentMixin)) {
if (meta$$1.hasMixin(currentMixin)) {
continue;
}
meta$$1.addMixin(currentMixin);
var {
properties,
mixins: _mixins
} = currentMixin;
if (properties !== undefined) {
mergeProps(meta$$1, properties, descs, values, base, keys, keysWithSuper);
} else if (_mixins !== undefined) {
mergeMixins(_mixins, meta$$1, descs, values, base, keys, keysWithSuper);
if (currentMixin._without !== undefined) {
currentMixin._without.forEach(keyName => {
// deleting the key means we won't process the value
var index = keys.indexOf(keyName);
if (index !== -1) {
keys.splice(index, 1);
}
});
}
}
} else {
mergeProps(meta$$1, currentMixin, descs, values, base, keys, keysWithSuper);
}
}
}
function mergeProps(meta$$1, props, descs, values, base, keys, keysWithSuper) {
var concats = concatenatedMixinProperties('concatenatedProperties', props, values, base);
var mergings = concatenatedMixinProperties('mergedProperties', props, values, base);
var propKeys = Object.keys(props);
for (var i = 0; i < propKeys.length; i++) {
var key = propKeys[i];
var value = props[key];
if (value === undefined) continue;
if (keys.indexOf(key) === -1) {
keys.push(key);
var desc = meta$$1.peekDescriptors(key);
if (desc === undefined) {
// The superclass did not have a CP, which means it may have
// observers or listeners on that property.
var prev = values[key] = base[key];
if (typeof prev === 'function') {
updateObserversAndListeners(base, key, prev, false);
}
} else {
descs[key] = desc; // The super desc will be overwritten on descs, so save off the fact that
// there was a super so we know to Object.defineProperty when writing
// the value
keysWithSuper.push(key);
desc.teardown(base, key, meta$$1);
}
}
var isFunction = typeof value === 'function';
if (isFunction) {
var _desc2 = descriptorForDecorator(value);
if (_desc2 !== undefined) {
// Wrap descriptor function to implement _super() if needed
descs[key] = giveDecoratorSuper(key, value, _desc2, descs);
values[key] = undefined;
continue;
}
}
if (concats && concats.indexOf(key) >= 0 || key === 'concatenatedProperties' || key === 'mergedProperties') {
value = applyConcatenatedProperties(key, value, values);
} else if (mergings && mergings.indexOf(key) > -1) {
value = applyMergedProperties(key, value, values);
} else if (isFunction) {
value = giveMethodSuper(key, value, values, descs);
}
values[key] = value;
descs[key] = undefined;
}
}
function updateObserversAndListeners(obj, key, fn, add) {
var meta$$1 = (0, _utils.observerListenerMetaFor)(fn);
if (meta$$1 === undefined) return;
var {
observers,
listeners
} = meta$$1;
if (observers !== undefined) {
var updateObserver = add ? addObserver : removeObserver;
for (var i = 0; i < observers.paths.length; i++) {
updateObserver(obj, observers.paths[i], null, key, observers.sync);
}
}
if (listeners !== undefined) {
var updateListener = add ? addListener : removeListener;
for (var _i = 0; _i < listeners.length; _i++) {
updateListener(obj, listeners[_i], null, key);
}
}
}
function applyMixin(obj, mixins, _hideKeys = false) {
var descs = Object.create(null);
var values = Object.create(null);
var meta$$1 = (0, _meta2.meta)(obj);
var keys = [];
var keysWithSuper = [];
obj._super = _utils.ROOT; // Go through all mixins and hashes passed in, and:
//
// * Handle concatenated properties
// * Handle merged properties
// * Set up _super wrapping if necessary
// * Set up computed property descriptors
// * Copying `toString` in broken browsers
mergeMixins(mixins, meta$$1, descs, values, obj, keys, keysWithSuper);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = values[key];
var desc = descs[key];
if (value !== undefined) {
if (typeof value === 'function') {
updateObserversAndListeners(obj, key, value, true);
}
defineValue(obj, key, value, keysWithSuper.indexOf(key) !== -1, !_hideKeys);
} else if (desc !== undefined) {
defineDecorator(obj, key, desc, meta$$1);
}
}
if (!meta$$1.isPrototypeMeta(obj)) {
revalidateObservers(obj);
}
return obj;
}
/**
@method mixin
@param obj
@param mixins*
@return obj
@private
*/
function mixin(obj, ...args) {
applyMixin(obj, args);
return obj;
}
var MIXINS = new _util._WeakSet();
/**
The `Mixin` class allows you to create mixins, whose properties can be
added to other classes. For instance,
```javascript
import Mixin from '@ember/object/mixin';
const EditableMixin = Mixin.create({
edit() {
console.log('starting to edit');
this.set('isEditing', true);
},
isEditing: false
});
```
```javascript
import EmberObject from '@ember/object';
import EditableMixin from '../mixins/editable';
// Mix mixins into classes by passing them as the first arguments to
// `.extend.`
const Comment = EmberObject.extend(EditableMixin, {
post: null
});
let comment = Comment.create({
post: somePost
});
comment.edit(); // outputs 'starting to edit'
```
Note that Mixins are created with `Mixin.create`, not
`Mixin.extend`.
Note that mixins extend a constructor's prototype so arrays and object literals
defined as properties will be shared amongst objects that implement the mixin.
If you want to define a property in a mixin that is not shared, you can define
it either as a computed property or have it be created on initialization of the object.
```javascript
// filters array will be shared amongst any object implementing mixin
import Mixin from '@ember/object/mixin';
import { A } from '@ember/array';
const FilterableMixin = Mixin.create({
filters: A()
});
```
```javascript
import Mixin from '@ember/object/mixin';
import { A } from '@ember/array';
import { computed } from '@ember/object';
// filters will be a separate array for every object implementing the mixin
const FilterableMixin = Mixin.create({
filters: computed(function() {
return A();
})
});
```
```javascript
import Mixin from '@ember/object/mixin';
import { A } from '@ember/array';
// filters will be created as a separate array during the object's initialization
const Filterable = Mixin.create({
filters: null,
init() {
this._super(...arguments);
this.set("filters", A());
}
});
```
@class Mixin
@public
*/
class Mixin {
constructor(mixins, properties) {
MIXINS.add(this);
this.properties = extractAccessors(properties);
this.mixins = buildMixinsArray(mixins);
this.ownerConstructor = undefined;
this._without = undefined;
if (true
/* DEBUG */
) {
// Eagerly add INIT_FACTORY to avoid issues in DEBUG as a result of Object.seal(mixin)
this[_container.INIT_FACTORY] = null;
/*
In debug builds, we seal mixins to help avoid performance pitfalls.
In IE11 there is a quirk that prevents sealed objects from being added
to a WeakMap. Unfortunately, the mixin system currently relies on
weak maps in `guidFor`, so we need to prime the guid cache weak map.
*/
(0, _utils.guidFor)(this);
if (Mixin._disableDebugSeal !== true) {
Object.seal(this);
}
}
}
/**
@method create
@for @ember/object/mixin
@static
@param arguments*
@public
*/
static create(...args) {
setUnprocessedMixins();
var M = this;
return new M(args, undefined);
} // returns the mixins currently applied to the specified object
// TODO: Make `mixin`
static mixins(obj) {
var meta$$1 = (0, _meta2.peekMeta)(obj);
var ret = [];
if (meta$$1 === null) {
return ret;
}
meta$$1.forEachMixins(currentMixin => {
// skip primitive mixins since these are always anonymous
if (!currentMixin.properties) {
ret.push(currentMixin);
}
});
return ret;
}
/**
@method reopen
@param arguments*
@private
*/
reopen(...args) {
if (args.length === 0) {
return;
}
if (this.properties) {
var currentMixin = new Mixin(undefined, this.properties);
this.properties = undefined;
this.mixins = [currentMixin];
} else if (!this.mixins) {
this.mixins = [];
}
this.mixins = this.mixins.concat(buildMixinsArray(args));
return this;
}
/**
@method apply
@param obj
@return applied object
@private
*/
apply(obj, _hideKeys = false) {
// Ember.NativeArray is a normal Ember.Mixin that we mix into `Array.prototype` when prototype extensions are enabled
// mutating a native object prototype like this should _not_ result in enumerable properties being added (or we have significant
// issues with things like deep equality checks from test frameworks, or things like jQuery.extend(true, [], [])).
//
// _hideKeys disables enumerablity when applying the mixin. This is a hack, and we should stop mutating the array prototype by default 😫
return applyMixin(obj, [this], _hideKeys);
}
applyPartial(obj) {
return applyMixin(obj, [this]);
}
/**
@method detect
@param obj
@return {Boolean}
@private
*/
detect(obj) {
if (typeof obj !== 'object' || obj === null) {
return false;
}
if (MIXINS.has(obj)) {
return _detect(obj, this);
}
var meta$$1 = (0, _meta2.peekMeta)(obj);
if (meta$$1 === null) {
return false;
}
return meta$$1.hasMixin(this);
}
without(...args) {
var ret = new Mixin([this]);
ret._without = args;
return ret;
}
keys() {
return _keys(this);
}
toString() {
return '(unknown mixin)';
}
}
_exports.Mixin = Mixin;
if (true
/* DEBUG */
) {
Object.defineProperty(Mixin, '_disableDebugSeal', {
configurable: true,
enumerable: false,
writable: true,
value: false
});
}
function buildMixinsArray(mixins) {
var length = mixins && mixins.length || 0;
var m = undefined;
if (length > 0) {
m = new Array(length);
for (var i = 0; i < length; i++) {
var x = mixins[i];
(true && !(typeof x === 'object' && x !== null && Object.prototype.toString.call(x) !== '[object Array]') && (0, _debug.assert)(`Expected hash or Mixin instance, got ${Object.prototype.toString.call(x)}`, typeof x === 'object' && x !== null && Object.prototype.toString.call(x) !== '[object Array]'));
if (MIXINS.has(x)) {
m[i] = x;
} else {
m[i] = new Mixin(undefined, x);
}
}
}
return m;
}
if (true
/* DEBUG */
) {
Object.seal(Mixin.prototype);
}
function _detect(curMixin, targetMixin, seen = new Set()) {
if (seen.has(curMixin)) {
return false;
}
seen.add(curMixin);
if (curMixin === targetMixin) {
return true;
}
var mixins = curMixin.mixins;
if (mixins) {
return mixins.some(mixin => _detect(mixin, targetMixin, seen));
}
return false;
}
function _keys(mixin, ret = new Set(), seen = new Set()) {
if (seen.has(mixin)) {
return;
}
seen.add(mixin);
if (mixin.properties) {
var props = Object.keys(mixin.properties);
for (var i = 0; i < props.length; i++) {
ret.add(props[i]);
}
} else if (mixin.mixins) {
mixin.mixins.forEach(x => _keys(x, ret, seen));
}
return ret;
}
function observer(...args) {
var funcOrDef = args.pop();
(true && !(typeof funcOrDef === 'function' || typeof funcOrDef === 'object' && funcOrDef !== null) && (0, _debug.assert)('observer must be provided a function or an observer definition', typeof funcOrDef === 'function' || typeof funcOrDef === 'object' && funcOrDef !== null));
var func, dependentKeys, sync;
if (typeof funcOrDef === 'function') {
func = funcOrDef;
dependentKeys = args;
sync = !_environment.ENV._DEFAULT_ASYNC_OBSERVERS;
} else {
func = funcOrDef.fn;
dependentKeys = funcOrDef.dependentKeys;
sync = funcOrDef.sync;
}
(true && !(typeof func === 'function') && (0, _debug.assert)('observer called without a function', typeof func === 'function'));
(true && !(Array.isArray(dependentKeys) && dependentKeys.length > 0 && dependentKeys.every(p => typeof p === 'string' && Boolean(p.length))) && (0, _debug.assert)('observer called without valid path', Array.isArray(dependentKeys) && dependentKeys.length > 0 && dependentKeys.every(p => typeof p === 'string' && Boolean(p.length))));
(true && !(typeof sync === 'boolean') && (0, _debug.assert)('observer called without sync', typeof sync === 'boolean'));
var paths = [];
for (var i = 0; i < dependentKeys.length; ++i) {
expandProperties(dependentKeys[i], path => paths.push(path));
}
(0, _utils.setObservers)(func, {
paths,
sync
});
return func;
}
var DEBUG_INJECTION_FUNCTIONS;
_exports.DEBUG_INJECTION_FUNCTIONS = DEBUG_INJECTION_FUNCTIONS;
if (true
/* DEBUG */
) {
_exports.DEBUG_INJECTION_FUNCTIONS = DEBUG_INJECTION_FUNCTIONS = new WeakMap();
}
function inject(type, ...args) {
(true && !(typeof type === 'string') && (0, _debug.assert)('a string type must be provided to inject', typeof type === 'string'));
var calledAsDecorator = isElementDescriptor(args);
var name = calledAsDecorator ? undefined : args[0];
var getInjection = function (propertyName) {
var owner = (0, _owner.getOwner)(this) || this.container; // fallback to `container` for backwards compat
(true && !(Boolean(owner)) && (0, _debug.assert)(`Attempting to lookup an injected property on an object without a container, ensure that the object was instantiated via a container.`, Boolean(owner)));
return owner.lookup(`${type}:${name || propertyName}`);
};
if (true
/* DEBUG */
) {
DEBUG_INJECTION_FUNCTIONS.set(getInjection, {
type,
name
});
}
var decorator = computed({
get: getInjection,
set(keyName, value) {
defineProperty(this, keyName, null, value);
}
});
if (calledAsDecorator) {
return decorator(args[0], args[1], args[2]);
} else {
return decorator;
}
}
function tracked(...args) {
(true && !(!(isElementDescriptor(args.slice(0, 3)) && args.length === 5 && args[4] === true)) && (0, _debug.assert)(`@tracked can only be used directly as a native decorator. If you're using tracked in classic classes, add parenthesis to call it like a function: tracked()`, !(isElementDescriptor(args.slice(0, 3)) && args.length === 5 && args[4] === true)));
if (!isElementDescriptor(args)) {
var propertyDesc = args[0];
(true && !(args.length === 0 || typeof propertyDesc === 'object' && propertyDesc !== null) && (0, _debug.assert)(`tracked() may only receive an options object containing 'value' or 'initializer', received ${propertyDesc}`, args.length === 0 || typeof propertyDesc === 'object' && propertyDesc !== null));
if (true
/* DEBUG */
&& propertyDesc) {
var keys = Object.keys(propertyDesc);
(true && !(keys.length <= 1 && (keys[0] === undefined || keys[0] === 'value' || keys[0] === 'initializer')) && (0, _debug.assert)(`The options object passed to tracked() may only contain a 'value' or 'initializer' property, not both. Received: [${keys}]`, keys.length <= 1 && (keys[0] === undefined || keys[0] === 'value' || keys[0] === 'initializer')));
(true && !(!('initializer' in propertyDesc) || typeof propertyDesc.initializer === 'function') && (0, _debug.assert)(`The initializer passed to tracked must be a function. Received ${propertyDesc.initializer}`, !('initializer' in propertyDesc) || typeof propertyDesc.initializer === 'function'));
}
var initializer = propertyDesc ? propertyDesc.initializer : undefined;
var value = propertyDesc ? propertyDesc.value : undefined;
var decorator = function (target, key, _desc, _meta, isClassicDecorator$$1) {
(true && !(isClassicDecorator$$1) && (0, _debug.assert)(`You attempted to set a default value for ${key} with the @tracked({ value: 'default' }) syntax. You can only use this syntax with classic classes. For native classes, you can use class initializers: @tracked field = 'default';`, isClassicDecorator$$1));
var fieldDesc = {
initializer: initializer || (() => value)
};
return descriptorForField([target, key, fieldDesc]);
};
setClassicDecorator(decorator);
return decorator;
}
return descriptorForField(args);
}
if (true
/* DEBUG */
) {
// Normally this isn't a classic decorator, but we want to throw a helpful
// error in development so we need it to treat it like one
setClassicDecorator(tracked);
}
function descriptorForField([target, key, desc]) {
(true && !(!desc || !desc.value && !desc.get && !desc.set) && (0, _debug.assert)(`You attempted to use @tracked on ${key}, but that element is not a class field. @tracked is only usable on class fields. Native getters and setters will autotrack add any tracked fields they encounter, so there is no need mark getters and setters with @tracked.`, !desc || !desc.value && !desc.get && !desc.set));
var {
getter,
setter
} = (0, _validator.trackedData)(key, desc ? desc.initializer : undefined);
function get() {
var value = getter(this); // Add the tag of the returned value if it is an array, since arrays
// should always cause updates if they are consumed and then changed
if (Array.isArray(value) || (0, _utils.isEmberArray)(value)) {
(0, _validator.consumeTag)((0, _validator.tagFor)(value, '[]'));
}
return value;
}
function set(newValue) {
setter(this, newValue);
(0, _validator.dirtyTagFor)(this, SELF_TAG);
}
var newDesc = {
enumerable: true,
configurable: true,
isTracked: true,
get,
set
};
COMPUTED_SETTERS.add(set);
(0, _meta2.meta)(target).writeDescriptors(key, new TrackedDescriptor(get, set));
return newDesc;
}
class TrackedDescriptor {
constructor(_get, _set) {
this._get = _get;
this._set = _set;
CHAIN_PASS_THROUGH.add(this);
}
get(obj) {
return this._get.call(obj);
}
set(obj, _key, value) {
this._set.call(obj, value);
}
}
/**
Ember uses caching based on trackable values to avoid updating large portions
of the application. This caching is exposed via a cache primitive that can be
used to cache a specific computation, so that it will not update and will
return the cached value until a tracked value used in its computation has
updated.
@module @glimmer/tracking/primitives/cache
@public
*/
/**
Receives a function, and returns a wrapped version of it that memoizes based on
_autotracking_. The function will only rerun whenever any tracked values used
within it have changed. Otherwise, it will return the previous value.
```js
import { tracked } from '@glimmer/tracking';
import { createCache, getValue } from '@glimmer/tracking/primitives/cache';
class State {
@tracked value;
}
let state = new State();
let computeCount = 0;
let counter = createCache(() => {
// consume the state. Now, `counter` will
// only rerun if `state.value` changes.
state.value;
return ++computeCount;
});
getValue(counter); // 1
// returns the same value because no tracked state has changed
getValue(counter); // 1
state.value = 'foo';
// reruns because a tracked value used in the function has changed,
// incermenting the counter
getValue(counter); // 2
```
@method createCache
@static
@for @glimmer/tracking/primitives/cache
@public
*/
/**
Gets the value of a cache created with `createCache`.
```js
import { tracked } from '@glimmer/tracking';
import { createCache, getValue } from '@glimmer/tracking/primitives/cache';
let computeCount = 0;
let counter = createCache(() => {
return ++computeCount;
});
getValue(counter); // 1
```
@method getValue
@static
@for @glimmer/tracking/primitives/cache
@public
*/
/**
Can be used to check if a memoized function is _constant_. If no tracked state
was used while running a memoized function, it will never rerun, because nothing
can invalidate its result. `isConst` can be used to determine if a memoized
function is constant or not, in order to optimize code surrounding that
function.
```js
import { tracked } from '@glimmer/tracking';
import { createCache, getValue, isConst } from '@glimmer/tracking/primitives/cache';
class State {
@tracked value;
}
let state = new State();
let computeCount = 0;
let counter = createCache(() => {
// consume the state
state.value;
return computeCount++;
});
let constCounter = createCache(() => {
return computeCount++;
});
getValue(counter);
getValue(constCounter);
isConst(counter); // false
isConst(constCounter); // true
```
If called on a cache that hasn't been accessed yet, it will throw an
error. This is because there's no way to know if the function will be constant
or not yet, and so this helps prevent missing an optimization opportunity on
accident.
@method isConst
@static
@for @glimmer/tracking/primitives/cache
@public
*/
_exports.TrackedDescriptor = TrackedDescriptor;
});
define("@ember/-internals/overrides/index", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.onEmberGlobalAccess = void 0;
var onEmberGlobalAccess;
_exports.onEmberGlobalAccess = onEmberGlobalAccess;
});
define("@ember/-internals/owner/index", ["exports", "@glimmer/owner"], function (_exports, _owner) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.getOwner = getOwner;
_exports.setOwner = setOwner;
/**
Framework objects in an Ember application (components, services, routes, etc.)
are created via a factory and dependency injection system. Each of these
objects is the responsibility of an "owner", which handled its
instantiation and manages its lifetime.
`getOwner` fetches the owner object responsible for an instance. This can
be used to lookup or resolve other class instances, or register new factories
into the owner.
For example, this component dynamically looks up a service based on the
`audioType` passed as an argument:
```app/components/play-audio.js
import Component from '@glimmer/component';
import { action } from '@ember/object';
import { getOwner } from '@ember/application';
// Usage:
//
// <PlayAudio @audioType={{@model.audioType}} @audioFile={{@model.file}}/>
//
export default class extends Component {
get audioService() {
let owner = getOwner(this);
return owner.lookup(`service:${this.args.audioType}`);
}
@action
onPlay() {
let player = this.audioService;
player.play(this.args.audioFile);
}
}
```
@method getOwner
@static
@for @ember/application
@param {Object} object An object with an owner.
@return {Object} An owner object.
@since 2.3.0
@public
*/
function getOwner(object) {
return (0, _owner.getOwner)(object);
}
/**
`setOwner` forces a new owner on a given object instance. This is primarily
useful in some testing cases.
@method setOwner
@static
@for @ember/application
@param {Object} object An object instance.
@param {Object} object The new owner object of the object instance.
@since 2.3.0
@public
*/
function setOwner(object, owner) {
(0, _owner.setOwner)(object, owner);
}
});
define("@ember/-internals/routing/index", ["exports", "@ember/-internals/routing/lib/ext/controller", "@ember/-internals/routing/lib/location/api", "@ember/-internals/routing/lib/location/none_location", "@ember/-internals/routing/lib/location/hash_location", "@ember/-internals/routing/lib/location/history_location", "@ember/-internals/routing/lib/location/auto_location", "@ember/-internals/routing/lib/system/generate_controller", "@ember/-internals/routing/lib/system/controller_for", "@ember/-internals/routing/lib/system/dsl", "@ember/-internals/routing/lib/system/router", "@ember/-internals/routing/lib/system/route", "@ember/-internals/routing/lib/system/query_params", "@ember/-internals/routing/lib/services/routing", "@ember/-internals/routing/lib/services/router", "@ember/-internals/routing/lib/system/router_state", "@ember/-internals/routing/lib/system/cache"], function (_exports, _controller, _api, _none_location, _hash_location, _history_location, _auto_location, _generate_controller, _controller_for, _dsl, _router, _route, _query_params, _routing, _router2, _router_state, _cache) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "Location", {
enumerable: true,
get: function () {
return _api.default;
}
});
Object.defineProperty(_exports, "NoneLocation", {
enumerable: true,
get: function () {
return _none_location.default;
}
});
Object.defineProperty(_exports, "HashLocation", {
enumerable: true,
get: function () {
return _hash_location.default;
}
});
Object.defineProperty(_exports, "HistoryLocation", {
enumerable: true,
get: function () {
return _history_location.default;
}
});
Object.defineProperty(_exports, "AutoLocation", {
enumerable: true,
get: function () {
return _auto_location.default;
}
});
Object.defineProperty(_exports, "generateController", {
enumerable: true,
get: function () {
return _generate_controller.default;
}
});
Object.defineProperty(_exports, "generateControllerFactory", {
enumerable: true,
get: function () {
return _generate_controller.generateControllerFactory;
}
});
Object.defineProperty(_exports, "controllerFor", {
enumerable: true,
get: function () {
return _controller_for.default;
}
});
Object.defineProperty(_exports, "RouterDSL", {
enumerable: true,
get: function () {
return _dsl.default;
}
});
Object.defineProperty(_exports, "Router", {
enumerable: true,
get: function () {
return _router.default;
}
});
Object.defineProperty(_exports, "Route", {
enumerable: true,
get: function () {
return _route.default;
}
});
Object.defineProperty(_exports, "QueryParams", {
enumerable: true,
get: function () {
return _query_params.default;
}
});
Object.defineProperty(_exports, "RoutingService", {
enumerable: true,
get: function () {
return _routing.default;
}
});
Object.defineProperty(_exports, "RouterService", {
enumerable: true,
get: function () {
return _router2.default;
}
});
Object.defineProperty(_exports, "RouterState", {
enumerable: true,
get: function () {
return _router_state.default;
}
});
Object.defineProperty(_exports, "BucketCache", {
enumerable: true,
get: function () {
return _cache.default;
}
});
});
define("@ember/-internals/routing/lib/ext/controller", ["exports", "@ember/-internals/metal", "@ember/-internals/owner", "@ember/controller/lib/controller_mixin", "@ember/-internals/routing/lib/utils"], function (_exports, _metal, _owner, _controller_mixin, _utils) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module ember
*/
_controller_mixin.default.reopen({
concatenatedProperties: ['queryParams'],
init() {
this._super(...arguments);
var owner = (0, _owner.getOwner)(this);
if (owner) {
this.namespace = owner.lookup('application:main');
this.target = owner.lookup('router:main');
}
},
/**
Defines which query parameters the controller accepts.
If you give the names `['category','page']` it will bind
the values of these query parameters to the variables
`this.category` and `this.page`.
By default, query parameters are parsed as strings. This
may cause unexpected behavior if a query parameter is used with `toggleProperty`,
because the initial value set for `param=false` will be the string `"false"`, which is truthy.
To avoid this, you may specify that the query parameter should be parsed as a boolean
by using the following verbose form with a `type` property:
```javascript
queryParams: [{
category: {
type: 'boolean'
}
}]
```
Available values for the `type` parameter are `'boolean'`, `'number'`, `'array'`, and `'string'`.
If query param type is not specified, it will default to `'string'`.
@for Ember.ControllerMixin
@property queryParams
@public
*/
queryParams: null,
/**
This property is updated to various different callback functions depending on
the current "state" of the backing route. It is used by
`Controller.prototype._qpChanged`.
The methods backing each state can be found in the `Route.prototype._qp` computed
property return value (the `.states` property). The current values are listed here for
the sanity of future travelers:
* `inactive` - This state is used when this controller instance is not part of the active
route hierarchy. Set in `Route.prototype._reset` (a `router.js` microlib hook) and
`Route.prototype.actions.finalizeQueryParamChange`.
* `active` - This state is used when this controller instance is part of the active
route hierarchy. Set in `Route.prototype.actions.finalizeQueryParamChange`.
* `allowOverrides` - This state is used in `Route.prototype.setup` (`route.js` microlib hook).
@method _qpDelegate
@private
*/
_qpDelegate: null,
/**
During `Route#setup` observers are created to invoke this method
when any of the query params declared in `Controller#queryParams` property
are changed.
When invoked this method uses the currently active query param update delegate
(see `Controller.prototype._qpDelegate` for details) and invokes it with
the QP key/value being changed.
@method _qpChanged
@private
*/
_qpChanged(controller, _prop) {
var dotIndex = _prop.indexOf('.[]');
var prop = dotIndex === -1 ? _prop : _prop.slice(0, dotIndex);
var delegate = controller._qpDelegate;
var value = (0, _metal.get)(controller, prop);
delegate(prop, value);
},
/**
Transition the application into another route. The route may
be either a single route or route path:
```javascript
aController.transitionToRoute('blogPosts');
aController.transitionToRoute('blogPosts.recentEntries');
```
Optionally supply a model for the route in question. The model
will be serialized into the URL using the `serialize` hook of
the route:
```javascript
aController.transitionToRoute('blogPost', aPost);
```
If a literal is passed (such as a number or a string), it will
be treated as an identifier instead. In this case, the `model`
hook of the route will be triggered:
```javascript
aController.transitionToRoute('blogPost', 1);
```
Multiple models will be applied last to first recursively up the
route tree.
```app/router.js
Router.map(function() {
this.route('blogPost', { path: ':blogPostId' }, function() {
this.route('blogComment', { path: ':blogCommentId', resetNamespace: true });
});
});
```
```javascript
aController.transitionToRoute('blogComment', aPost, aComment);
aController.transitionToRoute('blogComment', 1, 13);
```
It is also possible to pass a URL (a string that starts with a
`/`).
```javascript
aController.transitionToRoute('/');
aController.transitionToRoute('/blog/post/1/comment/13');
aController.transitionToRoute('/blog/posts?sort=title');
```
An options hash with a `queryParams` property may be provided as
the final argument to add query parameters to the destination URL.
```javascript
aController.transitionToRoute('blogPost', 1, {
queryParams: { showComments: 'true' }
});
// if you just want to transition the query parameters without changing the route
aController.transitionToRoute({ queryParams: { sort: 'date' } });
```
See also [replaceRoute](/ember/release/classes/Ember.ControllerMixin/methods/replaceRoute?anchor=replaceRoute).
@param {String} name the name of the route or a URL
@param {...Object} models the model(s) or identifier(s) to be used
while transitioning to the route.
@param {Object} [options] optional hash with a queryParams property
containing a mapping of query parameters
@for Ember.ControllerMixin
@method transitionToRoute
@return {Transition} the transition object associated with this
attempted transition
@deprecated Use transitionTo from the Router service instead.
@public
*/
transitionToRoute(...args) {
(0, _utils.deprecateTransitionMethods)('controller', 'transitionToRoute'); // target may be either another controller or a router
var target = (0, _metal.get)(this, 'target');
var method = target.transitionToRoute || target.transitionTo;
return method.apply(target, (0, _utils.prefixRouteNameArg)(this, args));
},
/**
Transition into another route while replacing the current URL, if possible.
This will replace the current history entry instead of adding a new one.
Beside that, it is identical to `transitionToRoute` in all other respects.
```javascript
aController.replaceRoute('blogPosts');
aController.replaceRoute('blogPosts.recentEntries');
```
Optionally supply a model for the route in question. The model
will be serialized into the URL using the `serialize` hook of
the route:
```javascript
aController.replaceRoute('blogPost', aPost);
```
If a literal is passed (such as a number or a string), it will
be treated as an identifier instead. In this case, the `model`
hook of the route will be triggered:
```javascript
aController.replaceRoute('blogPost', 1);
```
Multiple models will be applied last to first recursively up the
route tree.
```app/router.js
Router.map(function() {
this.route('blogPost', { path: ':blogPostId' }, function() {
this.route('blogComment', { path: ':blogCommentId', resetNamespace: true });
});
});
```
```
aController.replaceRoute('blogComment', aPost, aComment);
aController.replaceRoute('blogComment', 1, 13);
```
It is also possible to pass a URL (a string that starts with a
`/`).
```javascript
aController.replaceRoute('/');
aController.replaceRoute('/blog/post/1/comment/13');
```
@param {String} name the name of the route or a URL
@param {...Object} models the model(s) or identifier(s) to be used
while transitioning to the route.
@for Ember.ControllerMixin
@method replaceRoute
@return {Transition} the transition object associated with this
attempted transition
@public
*/
replaceRoute(...args) {
(0, _utils.deprecateTransitionMethods)('controller', 'replaceRoute'); // target may be either another controller or a router
var target = (0, _metal.get)(this, 'target');
var method = target.replaceRoute || target.replaceWith;
return method.apply(target, (0, _utils.prefixRouteNameArg)(this, args));
}
});
var _default = _controller_mixin.default;
_exports.default = _default;
});
define("@ember/-internals/routing/lib/location/api", ["exports", "@ember/debug"], function (_exports, _debug) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module @ember/routing
*/
/**
Location returns an instance of the correct implementation of
the `location` API.
## Implementations
You can pass an implementation name (`hash`, `history`, `none`, `auto`) to force a
particular implementation to be used in your application.
See [HashLocation](/ember/release/classes/HashLocation).
See [HistoryLocation](/ember/release/classes/HistoryLocation).
See [NoneLocation](/ember/release/classes/NoneLocation).
See [AutoLocation](/ember/release/classes/AutoLocation).
## Location API
Each location implementation must provide the following methods:
* implementation: returns the string name used to reference the implementation.
* getURL: returns the current URL.
* setURL(path): sets the current URL.
* replaceURL(path): replace the current URL (optional).
* onUpdateURL(callback): triggers the callback when the URL changes.
* formatURL(url): formats `url` to be placed into `href` attribute.
* detect() (optional): instructs the location to do any feature detection
necessary. If the location needs to redirect to a different URL, it
can cancel routing by setting the `cancelRouterSetup` property on itself
to `false`.
Calling setURL or replaceURL will not trigger onUpdateURL callbacks.
## Custom implementation
Ember scans `app/locations/*` for extending the Location API.
Example:
```javascript
import HistoryLocation from '@ember/routing/history-location';
export default class MyHistory {
implementation = 'my-custom-history';
constructor() {
this._history = HistoryLocation.create(...arguments);
}
create() {
return new this(...arguments);
}
pushState(path) {
this._history.pushState(path);
}
}
```
@class Location
@private
*/
var _default = {
/**
This is deprecated in favor of using the container to lookup the location
implementation as desired.
For example:
```javascript
// Given a location registered as follows:
container.register('location:history-test', HistoryTestLocation);
// You could create a new instance via:
container.lookup('location:history-test');
```
@method create
@param {Object} options
@return {Object} an instance of an implementation of the `location` API
@deprecated Use the container to lookup the location implementation that you
need.
@private
*/
create(options) {
var implementation = options && options.implementation;
(true && !(Boolean(implementation)) && (0, _debug.assert)("Location.create: you must specify a 'implementation' option", Boolean(implementation)));
var implementationClass = this.implementations[implementation];
(true && !(Boolean(implementationClass)) && (0, _debug.assert)(`Location.create: ${implementation} is not a valid implementation`, Boolean(implementationClass)));
return implementationClass.create(...arguments);
},
implementations: {}
};
_exports.default = _default;
});
define("@ember/-internals/routing/lib/location/auto_location", ["exports", "@ember/-internals/browser-environment", "@ember/-internals/metal", "@ember/-internals/owner", "@ember/-internals/runtime", "@ember/debug", "@ember/-internals/routing/lib/location/util"], function (_exports, _browserEnvironment, _metal, _owner, _runtime, _debug, _util) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.getHistoryPath = getHistoryPath;
_exports.getHashPath = getHashPath;
_exports.default = void 0;
/**
@module @ember/routing
*/
/**
AutoLocation will select the best location option based off browser
support with the priority order: history, hash, none.
Clean pushState paths accessed by hashchange-only browsers will be redirected
to the hash-equivalent and vice versa so future transitions are consistent.
Keep in mind that since some of your users will use `HistoryLocation`, your
server must serve the Ember app at all the routes you define.
Browsers that support the `history` API will use `HistoryLocation`, those that
do not, but still support the `hashchange` event will use `HashLocation`, and
in the rare case neither is supported will use `NoneLocation`.
Example:
```app/router.js
Router.map(function() {
this.route('posts', function() {
this.route('new');
});
});
Router.reopen({
location: 'auto'
});
```
This will result in a posts.new url of `/posts/new` for modern browsers that
support the `history` api or `/#/posts/new` for older ones, like Internet
Explorer 9 and below.
When a user visits a link to your application, they will be automatically
upgraded or downgraded to the appropriate `Location` class, with the URL
transformed accordingly, if needed.
Keep in mind that since some of your users will use `HistoryLocation`, your
server must serve the Ember app at all the routes you define.
@class AutoLocation
@static
@protected
*/
class AutoLocation extends _runtime.Object {
constructor() {
super(...arguments);
this.implementation = 'auto';
}
/**
Called by the router to instruct the location to do any feature detection
necessary. In the case of AutoLocation, we detect whether to use history
or hash concrete implementations.
@private
*/
detect() {
var rootURL = this.rootURL;
(true && !(rootURL.charAt(rootURL.length - 1) === '/') && (0, _debug.assert)('rootURL must end with a trailing forward slash e.g. "/app/"', rootURL.charAt(rootURL.length - 1) === '/'));
var implementation = detectImplementation({
location: this.location,
history: this.history,
userAgent: this.userAgent,
rootURL,
documentMode: this.documentMode,
global: this.global
});
if (implementation === false) {
(0, _metal.set)(this, 'cancelRouterSetup', true);
implementation = 'none';
}
var concrete = (0, _owner.getOwner)(this).lookup(`location:${implementation}`);
(true && !(concrete !== undefined) && (0, _debug.assert)(`Could not find location '${implementation}'.`, concrete !== undefined));
(0, _metal.set)(concrete, 'rootURL', rootURL);
(0, _metal.set)(this, 'concreteImplementation', concrete);
}
willDestroy() {
var {
concreteImplementation
} = this;
if (concreteImplementation) {
concreteImplementation.destroy();
}
}
}
_exports.default = AutoLocation;
AutoLocation.reopen({
rootURL: '/',
initState: delegateToConcreteImplementation('initState'),
getURL: delegateToConcreteImplementation('getURL'),
setURL: delegateToConcreteImplementation('setURL'),
replaceURL: delegateToConcreteImplementation('replaceURL'),
onUpdateURL: delegateToConcreteImplementation('onUpdateURL'),
formatURL: delegateToConcreteImplementation('formatURL'),
location: _browserEnvironment.location,
history: _browserEnvironment.history,
global: _browserEnvironment.window,
userAgent: _browserEnvironment.userAgent,
cancelRouterSetup: false
});
function delegateToConcreteImplementation(methodName) {
return function (...args) {
var _a;
var {
concreteImplementation
} = this;
(true && !(concreteImplementation) && (0, _debug.assert)("AutoLocation's detect() method should be called before calling any other hooks.", concreteImplementation));
return (_a = concreteImplementation[methodName]) === null || _a === void 0 ? void 0 : _a.call(concreteImplementation, ...args);
};
}
function detectImplementation(options) {
var {
location,
userAgent,
history,
documentMode,
global,
rootURL
} = options;
var implementation = 'none';
var cancelRouterSetup = false;
var currentPath = (0, _util.getFullPath)(location);
if ((0, _util.supportsHistory)(userAgent, history)) {
var historyPath = getHistoryPath(rootURL, location); // If the browser supports history and we have a history path, we can use
// the history location with no redirects.
if (currentPath === historyPath) {
implementation = 'history';
} else if (currentPath.substr(0, 2) === '/#') {
history.replaceState({
path: historyPath
}, '', historyPath);
implementation = 'history';
} else {
cancelRouterSetup = true;
(0, _util.replacePath)(location, historyPath);
}
} else if ((0, _util.supportsHashChange)(documentMode, global)) {
var hashPath = getHashPath(rootURL, location); // Be sure we're using a hashed path, otherwise let's switch over it to so
// we start off clean and consistent. We'll count an index path with no
// hash as "good enough" as well.
if (currentPath === hashPath || currentPath === '/' && hashPath === '/#/') {
implementation = 'hash';
} else {
// Our URL isn't in the expected hash-supported format, so we want to
// cancel the router setup and replace the URL to start off clean
cancelRouterSetup = true;
(0, _util.replacePath)(location, hashPath);
}
}
if (cancelRouterSetup) {
return false;
}
return implementation;
}
/**
@private
Returns the current path as it should appear for HistoryLocation supported
browsers. This may very well differ from the real current path (e.g. if it
starts off as a hashed URL)
*/
function getHistoryPath(rootURL, location) {
var path = (0, _util.getPath)(location);
var hash = (0, _util.getHash)(location);
var query = (0, _util.getQuery)(location);
var rootURLIndex = path.indexOf(rootURL);
var routeHash;
var hashParts;
(true && !(rootURLIndex === 0) && (0, _debug.assert)(`Path ${path} does not start with the provided rootURL ${rootURL}`, rootURLIndex === 0)); // By convention, Ember.js routes using HashLocation are required to start
// with `#/`. Anything else should NOT be considered a route and should
// be passed straight through, without transformation.
if (hash.substr(0, 2) === '#/') {
// There could be extra hash segments after the route
hashParts = hash.substr(1).split('#'); // The first one is always the route url
routeHash = hashParts.shift(); // If the path already has a trailing slash, remove the one
// from the hashed route so we don't double up.
if (path.charAt(path.length - 1) === '/') {
routeHash = routeHash.substr(1);
} // This is the "expected" final order
path += routeHash + query;
if (hashParts.length) {
path += `#${hashParts.join('#')}`;
}
} else {
path += query + hash;
}
return path;
}
/**
@private
Returns the current path as it should appear for HashLocation supported
browsers. This may very well differ from the real current path.
@method _getHashPath
*/
function getHashPath(rootURL, location) {
var path = rootURL;
var historyPath = getHistoryPath(rootURL, location);
var routePath = historyPath.substr(rootURL.length);
if (routePath !== '') {
if (routePath[0] !== '/') {
routePath = `/${routePath}`;
}
path += `#${routePath}`;
}
return path;
}
});
define("@ember/-internals/routing/lib/location/hash_location", ["exports", "@ember/-internals/metal", "@ember/-internals/runtime", "@ember/runloop", "@ember/-internals/routing/lib/location/util"], function (_exports, _metal, _runtime, _runloop, _util) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module @ember/routing
*/
/**
`HashLocation` implements the location API using the browser's
hash. At present, it relies on a `hashchange` event existing in the
browser.
Using `HashLocation` results in URLs with a `#` (hash sign) separating the
server side URL portion of the URL from the portion that is used by Ember.
Example:
```app/router.js
Router.map(function() {
this.route('posts', function() {
this.route('new');
});
});
Router.reopen({
location: 'hash'
});
```
This will result in a posts.new url of `/#/posts/new`.
@class HashLocation
@extends EmberObject
@protected
*/
class HashLocation extends _runtime.Object {
constructor() {
super(...arguments);
this.implementation = 'hash';
this.lastSetURL = null;
}
init() {
(0, _metal.set)(this, 'location', this._location || window.location);
this._hashchangeHandler = undefined;
}
/**
@private
Returns normalized location.hash
@since 1.5.1
@method getHash
*/
getHash() {
return (0, _util.getHash)(this.location);
}
/**
Returns the normalized URL, constructed from `location.hash`.
e.g. `#/foo` => `/foo` as well as `#/foo#bar` => `/foo#bar`.
By convention, hashed paths must begin with a forward slash, otherwise they
are not treated as a path so we can distinguish intent.
@private
@method getURL
*/
getURL() {
var originalPath = this.getHash().substr(1);
var outPath = originalPath;
if (outPath[0] !== '/') {
outPath = '/'; // Only add the # if the path isn't empty.
// We do NOT want `/#` since the ampersand
// is only included (conventionally) when
// the location.hash has a value
if (originalPath) {
outPath += `#${originalPath}`;
}
}
return outPath;
}
/**
Set the `location.hash` and remembers what was set. This prevents
`onUpdateURL` callbacks from triggering when the hash was set by
`HashLocation`.
@private
@method setURL
@param path {String}
*/
setURL(path) {
this.location.hash = path;
(0, _metal.set)(this, 'lastSetURL', path);
}
/**
Uses location.replace to update the url without a page reload
or history modification.
@private
@method replaceURL
@param path {String}
*/
replaceURL(path) {
this.location.replace(`#${path}`);
(0, _metal.set)(this, 'lastSetURL', path);
}
/**
Register a callback to be invoked when the hash changes. These
callbacks will execute when the user presses the back or forward
button, but not after `setURL` is invoked.
@private
@method onUpdateURL
@param callback {Function}
*/
onUpdateURL(callback) {
this._removeEventListener();
this._hashchangeHandler = (0, _runloop.bind)(this, function () {
var path = this.getURL();
if (this.lastSetURL === path) {
return;
}
(0, _metal.set)(this, 'lastSetURL', null);
callback(path);
});
window.addEventListener('hashchange', this._hashchangeHandler);
}
/**
Given a URL, formats it to be placed into the page as part
of an element's `href` attribute.
This is used, for example, when using the {{action}} helper
to generate a URL based on an event.
@private
@method formatURL
@param url {String}
*/
formatURL(url) {
return `#${url}`;
}
/**
Cleans up the HashLocation event listener.
@private
@method willDestroy
*/
willDestroy() {
this._removeEventListener();
}
_removeEventListener() {
if (this._hashchangeHandler) {
window.removeEventListener('hashchange', this._hashchangeHandler);
}
}
}
_exports.default = HashLocation;
});
define("@ember/-internals/routing/lib/location/history_location", ["exports", "@ember/-internals/metal", "@ember/-internals/runtime", "@ember/-internals/routing/lib/location/util"], function (_exports, _metal, _runtime, _util) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module @ember/routing
*/
var popstateFired = false;
function _uuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r, v;
r = Math.random() * 16 | 0;
v = c === 'x' ? r : r & 3 | 8;
return v.toString(16);
});
}
/**
HistoryLocation implements the location API using the browser's
history.pushState API.
Using `HistoryLocation` results in URLs that are indistinguishable from a
standard URL. This relies upon the browser's `history` API.
Example:
```app/router.js
Router.map(function() {
this.route('posts', function() {
this.route('new');
});
});
Router.reopen({
location: 'history'
});
```
This will result in a posts.new url of `/posts/new`.
Keep in mind that your server must serve the Ember app at all the routes you
define.
Using `HistoryLocation` will also result in location states being recorded by
the browser `history` API with the following schema:
```
window.history.state -> { path: '/', uuid: '3552e730-b4a6-46bd-b8bf-d8c3c1a97e0a' }
```
This allows each in-app location state to be tracked uniquely across history
state changes via the `uuid` field.
@class HistoryLocation
@extends EmberObject
@protected
*/
class HistoryLocation extends _runtime.Object {
constructor() {
super(...arguments);
this.implementation = 'history';
/**
Will be pre-pended to path upon state change
@property rootURL
@default '/'
@private
*/
this.rootURL = '/';
}
/**
@private
Returns normalized location.hash
@method getHash
*/
getHash() {
return (0, _util.getHash)(this.location);
}
init() {
var _a;
this._super(...arguments);
var base = document.querySelector('base');
var baseURL = '';
if (base !== null && base.hasAttribute('href')) {
baseURL = (_a = base.getAttribute('href')) !== null && _a !== void 0 ? _a : '';
}
(0, _metal.set)(this, 'baseURL', baseURL);
(0, _metal.set)(this, 'location', this.location || window.location);
this._popstateHandler = undefined;
}
/**
Used to set state on first call to setURL
@private
@method initState
*/
initState() {
var history = this.history || window.history;
(0, _metal.set)(this, 'history', history);
var {
state
} = history;
var path = this.formatURL(this.getURL());
if (state && state.path === path) {
// preserve existing state
// used for webkit workaround, since there will be no initial popstate event
this._previousURL = this.getURL();
} else {
this.replaceState(path);
}
}
/**
Returns the current `location.pathname` without `rootURL` or `baseURL`
@private
@method getURL
@return url {String}
*/
getURL() {
var {
location,
rootURL,
baseURL
} = this;
var path = location.pathname; // remove trailing slashes if they exists
rootURL = rootURL.replace(/\/$/, '');
baseURL = baseURL.replace(/\/$/, ''); // remove baseURL and rootURL from start of path
var url = path.replace(new RegExp(`^${baseURL}(?=/|$)`), '').replace(new RegExp(`^${rootURL}(?=/|$)`), '').replace(/\/\//g, '/'); // remove extra slashes
var search = location.search || '';
url += search + this.getHash();
return url;
}
/**
Uses `history.pushState` to update the url without a page reload.
@private
@method setURL
@param path {String}
*/
setURL(path) {
var {
state
} = this.history;
path = this.formatURL(path);
if (!state || state.path !== path) {
this.pushState(path);
}
}
/**
Uses `history.replaceState` to update the url without a page reload
or history modification.
@private
@method replaceURL
@param path {String}
*/
replaceURL(path) {
var {
state
} = this.history;
path = this.formatURL(path);
if (!state || state.path !== path) {
this.replaceState(path);
}
}
/**
Pushes a new state.
@private
@method pushState
@param path {String}
*/
pushState(path) {
var state = {
path,
uuid: _uuid()
};
this.history.pushState(state, null, path); // used for webkit workaround
this._previousURL = this.getURL();
}
/**
Replaces the current state.
@private
@method replaceState
@param path {String}
*/
replaceState(path) {
var state = {
path,
uuid: _uuid()
};
this.history.replaceState(state, null, path); // used for webkit workaround
this._previousURL = this.getURL();
}
/**
Register a callback to be invoked whenever the browser
history changes, including using forward and back buttons.
@private
@method onUpdateURL
@param callback {Function}
*/
onUpdateURL(callback) {
this._removeEventListener();
this._popstateHandler = () => {
// Ignore initial page load popstate event in Chrome
if (!popstateFired) {
popstateFired = true;
if (this.getURL() === this._previousURL) {
return;
}
}
callback(this.getURL());
};
window.addEventListener('popstate', this._popstateHandler);
}
/**
Used when using `{{action}}` helper. The url is always appended to the rootURL.
@private
@method formatURL
@param url {String}
@return formatted url {String}
*/
formatURL(url) {
var {
rootURL,
baseURL
} = this;
if (url !== '') {
// remove trailing slashes if they exists
rootURL = rootURL.replace(/\/$/, '');
baseURL = baseURL.replace(/\/$/, '');
} else if (baseURL[0] === '/' && rootURL[0] === '/') {
// if baseURL and rootURL both start with a slash
// ... remove trailing slash from baseURL if it exists
baseURL = baseURL.replace(/\/$/, '');
}
return baseURL + rootURL + url;
}
/**
Cleans up the HistoryLocation event listener.
@private
@method willDestroy
*/
willDestroy() {
this._removeEventListener();
}
_removeEventListener() {
if (this._popstateHandler) {
window.removeEventListener('popstate', this._popstateHandler);
}
}
}
_exports.default = HistoryLocation;
});
define("@ember/-internals/routing/lib/location/none_location", ["exports", "@ember/-internals/metal", "@ember/-internals/runtime", "@ember/debug"], function (_exports, _metal, _runtime, _debug) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module @ember/routing
*/
/**
NoneLocation does not interact with the browser. It is useful for
testing, or when you need to manage state with your Router, but temporarily
don't want it to muck with the URL (for example when you embed your
application in a larger page).
Using `NoneLocation` causes Ember to not store the applications URL state
in the actual URL. This is generally used for testing purposes, and is one
of the changes made when calling `App.setupForTesting()`.
@class NoneLocation
@extends EmberObject
@protected
*/
class NoneLocation extends _runtime.Object {
constructor() {
super(...arguments);
this.implementation = 'none';
}
detect() {
var {
rootURL
} = this;
(true && !(rootURL.charAt(rootURL.length - 1) === '/') && (0, _debug.assert)('rootURL must end with a trailing forward slash e.g. "/app/"', rootURL.charAt(rootURL.length - 1) === '/'));
}
/**
Returns the current path without `rootURL`.
@private
@method getURL
@return {String} path
*/
getURL() {
var {
path,
rootURL
} = this; // remove trailing slashes if they exists
rootURL = rootURL.replace(/\/$/, ''); // remove rootURL from url
return path.replace(new RegExp(`^${rootURL}(?=/|$)`), '');
}
/**
Set the path and remembers what was set. Using this method
to change the path will not invoke the `updateURL` callback.
@private
@method setURL
@param path {String}
*/
setURL(path) {
(0, _metal.set)(this, 'path', path);
}
/**
Register a callback to be invoked when the path changes. These
callbacks will execute when the user presses the back or forward
button, but not after `setURL` is invoked.
@private
@method onUpdateURL
@param callback {Function}
*/
onUpdateURL(callback) {
this.updateCallback = callback;
}
/**
Sets the path and calls the `updateURL` callback.
@private
@method handleURL
@param url {String}
*/
handleURL(url) {
(0, _metal.set)(this, 'path', url);
this.updateCallback(url);
}
/**
Given a URL, formats it to be placed into the page as part
of an element's `href` attribute.
This is used, for example, when using the {{action}} helper
to generate a URL based on an event.
@private
@method formatURL
@param url {String}
@return {String} url
*/
formatURL(url) {
var {
rootURL
} = this;
if (url !== '') {
// remove trailing slashes if they exists
rootURL = rootURL.replace(/\/$/, '');
}
return rootURL + url;
}
}
_exports.default = NoneLocation;
NoneLocation.reopen({
path: '',
rootURL: '/'
});
});
define("@ember/-internals/routing/lib/location/util", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.getPath = getPath;
_exports.getQuery = getQuery;
_exports.getHash = getHash;
_exports.getFullPath = getFullPath;
_exports.getOrigin = getOrigin;
_exports.supportsHashChange = supportsHashChange;
_exports.supportsHistory = supportsHistory;
_exports.replacePath = replacePath;
/**
@private
Returns the current `location.pathname`, normalized for IE inconsistencies.
*/
function getPath(location) {
var pathname = location.pathname; // Various versions of IE/Opera don't always return a leading slash
if (pathname[0] !== '/') {
pathname = `/${pathname}`;
}
return pathname;
}
/**
@private
Returns the current `location.search`.
*/
function getQuery(location) {
return location.search;
}
/**
@private
Returns the hash or empty string
*/
function getHash(location) {
if (location.hash !== undefined) {
return location.hash.substr(0);
}
return '';
}
function getFullPath(location) {
return getPath(location) + getQuery(location) + getHash(location);
}
function getOrigin(location) {
var origin = location.origin; // Older browsers, especially IE, don't have origin
if (!origin) {
origin = `${location.protocol}//${location.hostname}`;
if (location.port) {
origin += `:${location.port}`;
}
}
return origin;
}
/*
`documentMode` only exist in Internet Explorer, and it's tested because IE8 running in
IE7 compatibility mode claims to support `onhashchange` but actually does not.
`global` is an object that may have an `onhashchange` property.
@private
@function supportsHashChange
*/
function supportsHashChange(documentMode, global) {
return Boolean(global && 'onhashchange' in global && (documentMode === undefined || documentMode > 7));
}
/*
`userAgent` is a user agent string. We use user agent testing here, because
the stock Android browser is known to have buggy versions of the History API,
in some Android versions.
@private
@function supportsHistory
*/
function supportsHistory(userAgent, history) {
// Boosted from Modernizr: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js
// The stock browser on Android 2.2 & 2.3, and 4.0.x returns positive on history support
// Unfortunately support is really buggy and there is no clean way to detect
// these bugs, so we fall back to a user agent sniff :(
// We only want Android 2 and 4.0, stock browser, and not Chrome which identifies
// itself as 'Mobile Safari' as well, nor Windows Phone.
if ((userAgent.indexOf('Android 2.') !== -1 || userAgent.indexOf('Android 4.0') !== -1) && userAgent.indexOf('Mobile Safari') !== -1 && userAgent.indexOf('Chrome') === -1 && userAgent.indexOf('Windows Phone') === -1) {
return false;
}
return Boolean(history && 'pushState' in history);
}
/**
Replaces the current location, making sure we explicitly include the origin
to prevent redirecting to a different origin.
@private
*/
function replacePath(location, path) {
location.replace(getOrigin(location) + path);
}
});
define("@ember/-internals/routing/lib/services/router", ["exports", "@ember/-internals/owner", "@ember/-internals/runtime", "@ember/-internals/utils", "@ember/debug", "@ember/object/computed", "@ember/service", "@glimmer/validator", "@ember/-internals/routing/lib/utils"], function (_exports, _owner, _runtime, _utils, _debug, _computed, _service, _validator, _utils2) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
var ROUTER = (0, _utils.symbol)('ROUTER');
function cleanURL(url, rootURL) {
if (rootURL === '/') {
return url;
}
return url.substr(rootURL.length, url.length);
}
/**
The Router service is the public API that provides access to the router.
The immediate benefit of the Router service is that you can inject it into components,
giving them a friendly way to initiate transitions and ask questions about the current
global router state.
In this example, the Router service is injected into a component to initiate a transition
to a dedicated route:
```app/components/example.js
import Component from '@glimmer/component';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';
export default class ExampleComponent extends Component {
@service router;
@action
next() {
this.router.transitionTo('other.route');
}
}
```
Like any service, it can also be injected into helpers, routes, etc.
@public
@extends Service
@class RouterService
*/
class RouterService extends _service.default {
get _router() {
var router = this[ROUTER];
if (router !== undefined) {
return router;
}
var owner = (0, _owner.getOwner)(this);
router = owner.lookup('router:main');
return this[ROUTER] = router;
}
willDestroy() {
super.willDestroy(...arguments);
this[ROUTER] = null;
}
/**
Transition the application into another route. The route may
be either a single route or route path:
See [transitionTo](/ember/release/classes/Route/methods/transitionTo?anchor=transitionTo) for more info.
Calling `transitionTo` from the Router service will cause default query parameter values to be included in the URL.
This behavior is different from calling `transitionTo` on a route or `transitionToRoute` on a controller.
See the [Router Service RFC](https://github.com/emberjs/rfcs/blob/master/text/0095-router-service.md#query-parameter-semantics) for more info.
In the following example we use the Router service to navigate to a route with a
specific model from a Component in the first action, and in the second we trigger
a query-params only transition.
```app/components/example.js
import Component from '@glimmer/component';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';
export default class extends Component {
@service router;
@action
goToComments(post) {
this.router.transitionTo('comments', post);
}
@action
fetchMoreComments(latestComment) {
this.router.transitionTo({
queryParams: { commentsAfter: latestComment }
});
}
}
```
@method transitionTo
@param {String} [routeNameOrUrl] the name of the route or a URL
@param {...Object} [models] the model(s) or identifier(s) to be used while
transitioning to the route.
@param {Object} [options] optional hash with a queryParams property
containing a mapping of query parameters. May be supplied as the only
parameter to trigger a query-parameter-only transition.
@return {Transition} the transition object associated with this
attempted transition
@public
*/
transitionTo(...args) {
if ((0, _utils2.resemblesURL)(args[0])) {
// NOTE: this `args[0] as string` cast is safe and TS correctly infers it
// in 3.6+, so it can be removed when TS is upgraded.
return this._router._doURLTransition('transitionTo', args[0]);
}
var {
routeName,
models,
queryParams
} = (0, _utils2.extractRouteArgs)(args);
var transition = this._router._doTransition(routeName, models, queryParams, true);
transition['_keepDefaultQueryParamValues'] = true;
return transition;
}
/**
Similar to `transitionTo`, but instead of adding the destination to the browser's URL history,
it replaces the entry for the current route.
When the user clicks the "back" button in the browser, there will be fewer steps.
This is most commonly used to manage redirects in a way that does not cause confusing additions
to the user's browsing history.
See [replaceWith](/ember/release/classes/Route/methods/replaceWith?anchor=replaceWith) for more info.
Calling `replaceWith` from the Router service will cause default query parameter values to be included in the URL.
This behavior is different from calling `replaceWith` on a route.
See the [Router Service RFC](https://github.com/emberjs/rfcs/blob/master/text/0095-router-service.md#query-parameter-semantics) for more info.
Usage example:
```app/routes/application.js
import Route from '@ember/routing/route';
export default class extends Route {
beforeModel() {
if (!authorized()){
this.replaceWith('unauthorized');
}
}
});
```
@method replaceWith
@param {String} routeNameOrUrl the name of the route or a URL of the desired destination
@param {...Object} models the model(s) or identifier(s) to be used while
transitioning to the route i.e. an object of params to pass to the destination route
@param {Object} [options] optional hash with a queryParams property
containing a mapping of query parameters
@return {Transition} the transition object associated with this
attempted transition
@public
*/
replaceWith()
/* routeNameOrUrl, ...models, options */
{
return this.transitionTo(...arguments).method('replace');
}
/**
Generate a URL based on the supplied route name and optionally a model. The
URL is returned as a string that can be used for any purpose.
In this example, the URL for the `author.books` route for a given author
is copied to the clipboard.
```app/templates/application.hbs
<CopyLink @author={{hash id="tomster" name="Tomster"}} />
```
```app/components/copy-link.js
import Component from '@glimmer/component';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
export default class CopyLinkComponent extends Component {
@service router;
@service clipboard;
@action
copyBooksURL() {
if (this.author) {
const url = this.router.urlFor('author.books', this.args.author);
this.clipboard.set(url);
// Clipboard now has /author/tomster/books
}
}
}
```
Just like with `transitionTo` and `replaceWith`, `urlFor` can also handle
query parameters.
```app/templates/application.hbs
<CopyLink @author={{hash id="tomster" name="Tomster"}} />
```
```app/components/copy-link.js
import Component from '@glimmer/component';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
export default class CopyLinkComponent extends Component {
@service router;
@service clipboard;
@action
copyOnlyEmberBooksURL() {
if (this.author) {
const url = this.router.urlFor('author.books', this.author, {
queryParams: { filter: 'emberjs' }
});
this.clipboard.set(url);
// Clipboard now has /author/tomster/books?filter=emberjs
}
}
}
```
@method urlFor
@param {String} routeName the name of the route
@param {...Object} models the model(s) or identifier(s) to be used while
transitioning to the route.
@param {Object} [options] optional hash with a queryParams property
containing a mapping of query parameters
@return {String} the string representing the generated URL
@public
*/
urlFor(routeName, ...args) {
this._router.setupRouter();
return this._router.generate(routeName, ...args);
}
/**
Returns `true` if `routeName/models/queryParams` is the active route, where `models` and `queryParams` are optional.
See [model](api/ember/release/classes/Route/methods/model?anchor=model) and
[queryParams](/api/ember/3.7/classes/Route/properties/queryParams?anchor=queryParams) for more information about these arguments.
In the following example, `isActive` will return `true` if the current route is `/posts`.
```app/components/posts.js
import Component from '@glimmer/component';
import { inject as service } from '@ember/service';
export default class extends Component {
@service router;
displayComments() {
return this.router.isActive('posts');
}
});
```
The next example includes a dynamic segment, and will return `true` if the current route is `/posts/1`,
assuming the post has an id of 1:
```app/components/posts.js
import Component from '@glimmer/component';
import { inject as service } from '@ember/service';
export default class extends Component {
@service router;
displayComments(post) {
return this.router.isActive('posts', post.id);
}
});
```
Where `post.id` is the id of a specific post, which is represented in the route as /posts/[post.id].
If `post.id` is equal to 1, then isActive will return true if the current route is /posts/1, and false if the route is anything else.
@method isActive
@param {String} routeName the name of the route
@param {...Object} models the model(s) or identifier(s) to be used when determining the active route.
@param {Object} [options] optional hash with a queryParams property
containing a mapping of query parameters
@return {boolean} true if the provided routeName/models/queryParams are active
@public
*/
isActive(...args) {
var {
routeName,
models,
queryParams
} = (0, _utils2.extractRouteArgs)(args);
var routerMicrolib = this._router._routerMicrolib; // When using isActive() in a getter, we want to entagle with the auto-tracking system
// for example,
// in
// get isBarActive() {
// return isActive('foo.bar');
// }
//
// you'd expect isBarActive to be dirtied when the route changes.
//
// https://github.com/emberjs/ember.js/issues/19004
(0, _validator.consumeTag)((0, _validator.tagFor)(this._router, 'currentURL')); // UNSAFE: casting `routeName as string` here encodes the existing
// assumption but may be wrong: `extractRouteArgs` correctly returns it as
// `string | undefined`. There may be bugs if `isActiveIntent` does
// not correctly account for `undefined` values for `routeName`. Spoilers:
// it *does not* account for this being `undefined`.
if (!routerMicrolib.isActiveIntent(routeName, models)) {
return false;
}
var hasQueryParams = Object.keys(queryParams).length > 0;
if (hasQueryParams) {
queryParams = Object.assign({}, queryParams);
this._router._prepareQueryParams( // UNSAFE: casting `routeName as string` here encodes the existing
// assumption but may be wrong: `extractRouteArgs` correctly returns it
// as `string | undefined`. There may be bugs if `_prepareQueryParams`
// does not correctly account for `undefined` values for `routeName`.
// Spoilers: under the hood this currently uses router.js APIs which
// *do not* account for this being `undefined`.
routeName, models, // UNSAFE: downstream consumers treat this as `QueryParam`, which the
// type system here *correctly* reports as incorrect, because it may be
// just an empty object.
queryParams, true
/* fromRouterService */
);
return (0, _utils2.shallowEqual)(queryParams, routerMicrolib.state.queryParams);
}
return true;
}
/**
Takes a string URL and returns a `RouteInfo` for the leafmost route represented
by the URL. Returns `null` if the URL is not recognized. This method expects to
receive the actual URL as seen by the browser including the app's `rootURL`.
See [RouteInfo](/ember/release/classes/RouteInfo) for more info.
In the following example `recognize` is used to verify if a path belongs to our
application before transitioning to it.
```
import Component from '@ember/component';
import { inject as service } from '@ember/service';
export default class extends Component {
@service router;
path = '/';
click() {
if (this.router.recognize(this.path)) {
this.router.transitionTo(this.path);
}
}
}
```
@method recognize
@param {String} url
@public
*/
recognize(url) {
(true && !(url.indexOf(this.rootURL) === 0) && (0, _debug.assert)(`You must pass a url that begins with the application's rootURL "${this.rootURL}"`, url.indexOf(this.rootURL) === 0));
this._router.setupRouter();
var internalURL = cleanURL(url, this.rootURL);
return this._router._routerMicrolib.recognize(internalURL);
}
/**
Takes a string URL and returns a promise that resolves to a
`RouteInfoWithAttributes` for the leafmost route represented by the URL.
The promise rejects if the URL is not recognized or an unhandled exception
is encountered. This method expects to receive the actual URL as seen by
the browser including the app's `rootURL`.
@method recognizeAndLoad
@param {String} url
@public
*/
recognizeAndLoad(url) {
(true && !(url.indexOf(this.rootURL) === 0) && (0, _debug.assert)(`You must pass a url that begins with the application's rootURL "${this.rootURL}"`, url.indexOf(this.rootURL) === 0));
this._router.setupRouter();
var internalURL = cleanURL(url, this.rootURL);
return this._router._routerMicrolib.recognizeAndLoad(internalURL);
}
}
_exports.default = RouterService;
if (false
/* EMBER_ROUTING_ROUTER_SERVICE_REFRESH */
) {
RouterService.reopen({
/**
* Refreshes all currently active routes, doing a full transition.
* If a route name is provided and refers to a currently active route,
* it will refresh only that route and its descendents.
* Returns a promise that will be resolved once the refresh is complete.
* All resetController, beforeModel, model, afterModel, redirect, and setupController
* hooks will be called again. You will get new data from the model hook.
*
* @method refresh
* @param {String} [routeName] the route to refresh (along with all child routes)
* @return Transition
* @category EMBER_ROUTING_ROUTER_SERVICE_REFRESH
* @public
*/
refresh(pivotRouteName) {
if (!pivotRouteName) {
return this._router._routerMicrolib.refresh();
}
(true && !(this._router.hasRoute(pivotRouteName)) && (0, _debug.assert)(`The route "${pivotRouteName}" was not found`, this._router.hasRoute(pivotRouteName)));
(true && !(this.isActive(pivotRouteName)) && (0, _debug.assert)(`The route "${pivotRouteName}" is currently not active`, this.isActive(pivotRouteName)));
var pivotRoute = (0, _owner.getOwner)(this).lookup(`route:${pivotRouteName}`);
return this._router._routerMicrolib.refresh(pivotRoute);
}
});
}
RouterService.reopen(_runtime.Evented, {
/**
Name of the current route.
This property represents the logical name of the route,
which is comma separated.
For the following router:
```app/router.js
Router.map(function() {
this.route('about');
this.route('blog', function () {
this.route('post', { path: ':post_id' });
});
});
```
It will return:
* `index` when you visit `/`
* `about` when you visit `/about`
* `blog.index` when you visit `/blog`
* `blog.post` when you visit `/blog/some-post-id`
@property currentRouteName
@type String
@public
*/
currentRouteName: (0, _computed.readOnly)('_router.currentRouteName'),
/**
Current URL for the application.
This property represents the URL path for this route.
For the following router:
```app/router.js
Router.map(function() {
this.route('about');
this.route('blog', function () {
this.route('post', { path: ':post_id' });
});
});
```
It will return:
* `/` when you visit `/`
* `/about` when you visit `/about`
* `/blog` when you visit `/blog`
* `/blog/some-post-id` when you visit `/blog/some-post-id`
@property currentURL
@type String
@public
*/
currentURL: (0, _computed.readOnly)('_router.currentURL'),
/**
The `location` property returns what implementation of the `location` API
your application is using, which determines what type of URL is being used.
See [Location](/ember/release/classes/Location) for more information.
To force a particular `location` API implementation to be used in your
application you can set a location type on your `config/environment`.
For example, to set the `history` type:
```config/environment.js
'use strict';
module.exports = function(environment) {
let ENV = {
modulePrefix: 'router-service',
environment,
rootURL: '/',
locationType: 'history',
...
}
}
```
The following location types are available by default:
`auto`, `hash`, `history`, `none`.
See [HashLocation](/ember/release/classes/HashLocation).
See [HistoryLocation](/ember/release/classes/HistoryLocation).
See [NoneLocation](/ember/release/classes/NoneLocation).
See [AutoLocation](/ember/release/classes/AutoLocation).
@property location
@default 'hash'
@see {Location}
@public
*/
location: (0, _computed.readOnly)('_router.location'),
/**
The `rootURL` property represents the URL of the root of
the application, '/' by default.
This prefix is assumed on all routes defined on this app.
If you change the `rootURL` in your environment configuration
like so:
```config/environment.js
'use strict';
module.exports = function(environment) {
let ENV = {
modulePrefix: 'router-service',
environment,
rootURL: '/my-root',
}
]
```
This property will return `/my-root`.
@property rootURL
@default '/'
@public
*/
rootURL: (0, _computed.readOnly)('_router.rootURL'),
/**
The `currentRoute` property contains metadata about the current leaf route.
It returns a `RouteInfo` object that has information like the route name,
params, query params and more.
See [RouteInfo](/ember/release/classes/RouteInfo) for more info.
This property is guaranteed to change whenever a route transition
happens (even when that transition only changes parameters
and doesn't change the active route).
Usage example:
```app/components/header.js
import Component from '@glimmer/component';
import { inject as service } from '@ember/service';
import { notEmpty } from '@ember/object/computed';
export default class extends Component {
@service router;
@notEmpty('router.currentRoute.child') isChildRoute;
});
```
@property currentRoute
@type RouteInfo
@public
*/
currentRoute: (0, _computed.readOnly)('_router.currentRoute')
});
});
define("@ember/-internals/routing/lib/services/routing", ["exports", "@ember/-internals/owner", "@ember/-internals/utils", "@ember/object/computed", "@ember/service"], function (_exports, _owner, _utils, _computed, _service) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module ember
*/
var ROUTER = (0, _utils.symbol)('ROUTER');
/**
The Routing service is used by LinkTo, and provides facilities for
the component/view layer to interact with the router.
This is a private service for internal usage only. For public usage,
refer to the `Router` service.
@private
@class RoutingService
*/
class RoutingService extends _service.default {
get router() {
var router = this[ROUTER];
if (router !== undefined) {
return router;
}
var owner = (0, _owner.getOwner)(this);
router = owner.lookup('router:main');
router.setupRouter();
return this[ROUTER] = router;
}
hasRoute(routeName) {
return this.router.hasRoute(routeName);
}
transitionTo(routeName, models, queryParams, shouldReplace) {
var transition = this.router._doTransition(routeName, models, queryParams);
if (shouldReplace) {
transition.method('replace');
}
return transition;
}
normalizeQueryParams(routeName, models, queryParams) {
this.router._prepareQueryParams(routeName, models, queryParams);
}
_generateURL(routeName, models, queryParams) {
var visibleQueryParams = {};
if (queryParams) {
Object.assign(visibleQueryParams, queryParams);
this.normalizeQueryParams(routeName, models, visibleQueryParams);
}
return this.router.generate(routeName, ...models, {
queryParams: visibleQueryParams
});
}
generateURL(routeName, models, queryParams) {
if (this.router._initialTransitionStarted) {
return this._generateURL(routeName, models, queryParams);
} else {
// Swallow error when transition has not started.
// When rendering in tests without visit(), we cannot infer the route context which <LinkTo/> needs be aware of
try {
return this._generateURL(routeName, models, queryParams);
} catch (_e) {
return;
}
}
}
isActiveForRoute(contexts, queryParams, routeName, routerState) {
var handlers = this.router._routerMicrolib.recognizer.handlersFor(routeName);
var leafName = handlers[handlers.length - 1].handler;
var maximumContexts = numberOfContextsAcceptedByHandler(routeName, handlers); // NOTE: any ugliness in the calculation of activeness is largely
// due to the fact that we support automatic normalizing of
// `resource` -> `resource.index`, even though there might be
// dynamic segments / query params defined on `resource.index`
// which complicates (and makes somewhat ambiguous) the calculation
// of activeness for links that link to `resource` instead of
// directly to `resource.index`.
// if we don't have enough contexts revert back to full route name
// this is because the leaf route will use one of the contexts
if (contexts.length > maximumContexts) {
routeName = leafName;
}
return routerState.isActiveIntent(routeName, contexts, queryParams);
}
}
_exports.default = RoutingService;
RoutingService.reopen({
targetState: (0, _computed.readOnly)('router.targetState'),
currentState: (0, _computed.readOnly)('router.currentState'),
currentRouteName: (0, _computed.readOnly)('router.currentRouteName'),
currentPath: (0, _computed.readOnly)('router.currentPath')
});
function numberOfContextsAcceptedByHandler(handlerName, handlerInfos) {
var req = 0;
for (var i = 0; i < handlerInfos.length; i++) {
req += handlerInfos[i].names.length;
if (handlerInfos[i].handler === handlerName) {
break;
}
}
return req;
}
});
define("@ember/-internals/routing/lib/system/cache", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
A two-tiered cache with support for fallback values when doing lookups.
Uses "buckets" and then "keys" to cache values.
@private
@class BucketCache
*/
class BucketCache {
constructor() {
this.cache = new Map();
}
has(bucketKey) {
return this.cache.has(bucketKey);
}
stash(bucketKey, key, value) {
var bucket = this.cache.get(bucketKey);
if (bucket === undefined) {
bucket = new Map();
this.cache.set(bucketKey, bucket);
}
bucket.set(key, value);
}
lookup(bucketKey, prop, defaultValue) {
if (!this.has(bucketKey)) {
return defaultValue;
}
var bucket = this.cache.get(bucketKey);
if (bucket.has(prop)) {
return bucket.get(prop);
} else {
return defaultValue;
}
}
}
_exports.default = BucketCache;
});
define("@ember/-internals/routing/lib/system/controller_for", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = controllerFor;
/**
@module ember
*/
/**
Finds a controller instance.
@for Ember
@method controllerFor
@private
*/
function controllerFor(container, controllerName, lookupOptions) {
return container.lookup(`controller:${controllerName}`, lookupOptions);
}
});
define("@ember/-internals/routing/lib/system/dsl", ["exports", "@ember/debug"], function (_exports, _debug) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
var uuid = 0;
function isCallback(value) {
return typeof value === 'function';
}
function isOptions(value) {
return value !== null && typeof value === 'object';
}
class DSLImpl {
constructor(name = null, options) {
this.explicitIndex = false;
this.parent = name;
this.enableLoadingSubstates = Boolean(options && options.enableLoadingSubstates);
this.matches = [];
this.options = options;
}
route(name, _options, _callback) {
var options;
var callback = null;
var dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`;
if (isCallback(_options)) {
(true && !(arguments.length === 2) && (0, _debug.assert)('Unexpected arguments', arguments.length === 2));
options = {};
callback = _options;
} else if (isCallback(_callback)) {
(true && !(arguments.length === 3) && (0, _debug.assert)('Unexpected arguments', arguments.length === 3));
(true && !(isOptions(_options)) && (0, _debug.assert)('Unexpected arguments', isOptions(_options)));
options = _options;
callback = _callback;
} else {
options = _options || {};
}
(true && !((() => {
if (options.overrideNameAssertion === true) {
return true;
}
return ['basic', 'application'].indexOf(name) === -1;
})()) && (0, _debug.assert)(`'${name}' cannot be used as a route name.`, (() => {
if (options.overrideNameAssertion === true) {
return true;
}
return ['basic', 'application'].indexOf(name) === -1;
})()));
(true && !(name.indexOf(':') === -1) && (0, _debug.assert)(`'${name}' is not a valid route name. It cannot contain a ':'. You may want to use the 'path' option instead.`, name.indexOf(':') === -1));
if (this.enableLoadingSubstates) {
createRoute(this, `${name}_loading`, {
resetNamespace: options.resetNamespace
});
createRoute(this, `${name}_error`, {
resetNamespace: options.resetNamespace,
path: dummyErrorRoute
});
}
if (callback) {
var fullName = getFullName(this, name, options.resetNamespace);
var dsl = new DSLImpl(fullName, this.options);
createRoute(dsl, 'loading');
createRoute(dsl, 'error', {
path: dummyErrorRoute
});
callback.call(dsl);
createRoute(this, name, options, dsl.generate());
} else {
createRoute(this, name, options);
}
}
push(url, name, callback, serialize) {
var parts = name.split('.');
if (this.options.engineInfo) {
var localFullName = name.slice(this.options.engineInfo.fullName.length + 1);
var routeInfo = Object.assign({
localFullName
}, this.options.engineInfo);
if (serialize) {
routeInfo.serializeMethod = serialize;
}
this.options.addRouteForEngine(name, routeInfo);
} else if (serialize) {
throw new Error(`Defining a route serializer on route '${name}' outside an Engine is not allowed.`);
}
if (url === '' || url === '/' || parts[parts.length - 1] === 'index') {
this.explicitIndex = true;
}
this.matches.push(url, name, callback);
}
generate() {
var dslMatches = this.matches;
if (!this.explicitIndex) {
this.route('index', {
path: '/'
});
}
return match => {
for (var i = 0; i < dslMatches.length; i += 3) {
match(dslMatches[i]).to(dslMatches[i + 1], dslMatches[i + 2]);
}
};
}
mount(_name, options = {}) {
var engineRouteMap = this.options.resolveRouteMap(_name);
var name = _name;
if (options.as) {
name = options.as;
}
var fullName = getFullName(this, name, options.resetNamespace);
var engineInfo = {
name: _name,
instanceId: uuid++,
mountPoint: fullName,
fullName
};
var path = options.path;
if (typeof path !== 'string') {
path = `/${name}`;
}
var callback;
var dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`;
if (engineRouteMap) {
var shouldResetEngineInfo = false;
var oldEngineInfo = this.options.engineInfo;
if (oldEngineInfo) {
shouldResetEngineInfo = true;
this.options.engineInfo = engineInfo;
}
var optionsForChild = Object.assign({
engineInfo
}, this.options);
var childDSL = new DSLImpl(fullName, optionsForChild);
createRoute(childDSL, 'loading');
createRoute(childDSL, 'error', {
path: dummyErrorRoute
});
engineRouteMap.class.call(childDSL);
callback = childDSL.generate();
if (shouldResetEngineInfo) {
this.options.engineInfo = oldEngineInfo;
}
}
var localFullName = 'application';
var routeInfo = Object.assign({
localFullName
}, engineInfo);
if (this.enableLoadingSubstates) {
// These values are important to register the loading routes under their
// proper names for the Router and within the Engine's registry.
var substateName = `${name}_loading`;
var _localFullName = `application_loading`;
var _routeInfo = Object.assign({
localFullName: _localFullName
}, engineInfo);
createRoute(this, substateName, {
resetNamespace: options.resetNamespace
});
this.options.addRouteForEngine(substateName, _routeInfo);
substateName = `${name}_error`;
_localFullName = `application_error`;
_routeInfo = Object.assign({
localFullName: _localFullName
}, engineInfo);
createRoute(this, substateName, {
resetNamespace: options.resetNamespace,
path: dummyErrorRoute
});
this.options.addRouteForEngine(substateName, _routeInfo);
}
this.options.addRouteForEngine(fullName, routeInfo);
this.push(path, fullName, callback);
}
}
_exports.default = DSLImpl;
function canNest(dsl) {
return dsl.parent !== 'application';
}
function getFullName(dsl, name, resetNamespace) {
if (canNest(dsl) && resetNamespace !== true) {
return `${dsl.parent}.${name}`;
} else {
return name;
}
}
function createRoute(dsl, name, options = {}, callback) {
var fullName = getFullName(dsl, name, options.resetNamespace);
if (typeof options.path !== 'string') {
options.path = `/${name}`;
}
dsl.push(options.path, fullName, callback, options.serialize);
}
});
define("@ember/-internals/routing/lib/system/engines", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
});
define("@ember/-internals/routing/lib/system/generate_controller", ["exports", "@ember/-internals/metal", "@ember/debug"], function (_exports, _metal, _debug) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.generateControllerFactory = generateControllerFactory;
_exports.default = generateController;
/**
@module ember
*/
/**
Generates a controller factory
@for Ember
@method generateControllerFactory
@private
*/
function generateControllerFactory(owner, controllerName) {
var Factory = owner.factoryFor('controller:basic').class;
Factory = Factory.extend({
toString() {
return `(generated ${controllerName} controller)`;
}
});
var fullName = `controller:${controllerName}`;
owner.register(fullName, Factory);
return owner.factoryFor(fullName);
}
/**
Generates and instantiates a controller extending from `controller:basic`
if present, or `Controller` if not.
@for Ember
@method generateController
@private
@since 1.3.0
*/
function generateController(owner, controllerName) {
generateControllerFactory(owner, controllerName);
var fullName = `controller:${controllerName}`;
var instance = owner.lookup(fullName);
if (true
/* DEBUG */
) {
if ((0, _metal.get)(instance, 'namespace.LOG_ACTIVE_GENERATION')) {
(0, _debug.info)(`generated -> ${fullName}`, {
fullName
});
}
}
return instance;
}
});
define("@ember/-internals/routing/lib/system/query_params", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
class QueryParams {
constructor(values = null) {
this.isQueryParams = true;
this.values = values;
}
}
_exports.default = QueryParams;
});
define("@ember/-internals/routing/lib/system/route-info", [], function () {
"use strict";
/**
A `RouteInfoWithAttributes` is an object that contains
metadata, including the resolved value from the routes
`model` hook. Like `RouteInfo`, a `RouteInfoWithAttributes`
represents a specific route within a Transition.
It is read-only and internally immutable. It is also not
observable, because a Transition instance is never
changed after creation.
@class RouteInfoWithAttributes
@public
*/
/**
The dot-separated, fully-qualified name of the
route, like "people.index".
@property {String} name
@public
*/
/**
The final segment of the fully-qualified name of
the route, like "index"
@property {String} localName
@public
*/
/**
The values of the route's parameters. These are the
same params that are received as arguments to the
route's model hook. Contains only the parameters
valid for this route, if any (params for parent or
child routes are not merged).
@property {Object} params
@public
*/
/**
The ordered list of the names of the params
required for this route. It will contain the same
strings as `Object.keys(params)`, but here the order
is significant. This allows users to correctly pass
params into routes programmatically.
@property {Array} paramNames
@public
*/
/**
The values of any queryParams on this route.
@property {Object} queryParams
@public
*/
/**
This is the resolved return value from the
route's model hook.
@property {Object|Array|String} attributes
@public
*/
/**
Will contain the result `Route#buildRouteInfoMetadata`
for the corresponding Route.
@property {Any} metadata
@public
*/
/**
A reference to the parent route's RouteInfo.
This can be used to traverse upward to the topmost
`RouteInfo`.
@property {RouteInfo|null} parent
@public
*/
/**
A reference to the child route's RouteInfo.
This can be used to traverse downward to the
leafmost `RouteInfo`.
@property {RouteInfo|null} child
@public
*/
/**
Allows you to traverse through the linked list
of `RouteInfo`s from the topmost to leafmost.
Returns the first `RouteInfo` in the linked list
for which the callback returns true.
This method is similar to the `find()` method
defined in ECMAScript 2015.
The callback method you provide should have the
following signature (all parameters are optional):
```javascript
function(item, index, array);
```
- `item` is the current item in the iteration.
- `index` is the current index in the iteration.
- `array` is the array itself.
It should return the `true` to include the item in
the results, `false` otherwise.
Note that in addition to a callback, you can also
pass an optional target object that will be set as
`this` on the context.
@method find
@param {Function} callback the callback to execute
@param {Object} [target*] optional target to use
@returns {Object} Found item or undefined
@public
*/
/**
A RouteInfo is an object that contains metadata
about a specific route within a Transition. It is
read-only and internally immutable. It is also not
observable, because a Transition instance is never
changed after creation.
@class RouteInfo
@public
*/
/**
The dot-separated, fully-qualified name of the
route, like "people.index".
@property {String} name
@public
*/
/**
The final segment of the fully-qualified name of
the route, like "index"
@property {String} localName
@public
*/
/**
The values of the route's parameters. These are the
same params that are received as arguments to the
route's `model` hook. Contains only the parameters
valid for this route, if any (params for parent or
child routes are not merged).
@property {Object} params
@public
*/
/**
The ordered list of the names of the params
required for this route. It will contain the same
strings as Object.keys(params), but here the order
is significant. This allows users to correctly pass
params into routes programmatically.
@property {Array} paramNames
@public
*/
/**
The values of any queryParams on this route.
@property {Object} queryParams
@public
*/
/**
Will contain the result `Route#buildRouteInfoMetadata`
for the corresponding Route.
@property {Any} metadata
@public
*/
/**
A reference to the parent route's `RouteInfo`.
This can be used to traverse upward to the topmost
`RouteInfo`.
@property {RouteInfo|null} parent
@public
*/
/**
A reference to the child route's `RouteInfo`.
This can be used to traverse downward to the
leafmost `RouteInfo`.
@property {RouteInfo|null} child
@public
*/
/**
Allows you to traverse through the linked list
of `RouteInfo`s from the topmost to leafmost.
Returns the first `RouteInfo` in the linked list
for which the callback returns true.
This method is similar to the `find()` method
defined in ECMAScript 2015.
The callback method you provide should have the
following signature (all parameters are optional):
```javascript
function(item, index, array);
```
- `item` is the current item in the iteration.
- `index` is the current index in the iteration.
- `array` is the array itself.
It should return the `true` to include the item in
the results, `false` otherwise.
Note that in addition to a callback, you can also
pass an optional target object that will be set as
`this` on the context.
@method find
@param {Function} callback the callback to execute
@param {Object} [target*] optional target to use
@returns {Object} Found item or undefined
@public
*/
});
define("@ember/-internals/routing/lib/system/route", ["exports", "@ember/-internals/container", "@ember/-internals/metal", "@ember/-internals/owner", "@ember/-internals/runtime", "@ember/-internals/utils", "@ember/debug", "@ember/object/compat", "@ember/runloop", "@ember/string", "router_js", "@ember/-internals/routing/lib/utils", "@ember/-internals/routing/lib/system/generate_controller"], function (_exports, _container, _metal, _owner, _runtime, _utils, _debug, _compat, _runloop, _string, _router_js, _utils2, _generate_controller) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.defaultSerialize = defaultSerialize;
_exports.hasDefaultSerialize = hasDefaultSerialize;
_exports.getFullQueryParams = getFullQueryParams;
_exports.default = _exports.ROUTE_CONNECTIONS = void 0;
var __decorate = void 0 && (void 0).__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 ROUTE_CONNECTIONS = new WeakMap();
_exports.ROUTE_CONNECTIONS = ROUTE_CONNECTIONS;
var RENDER = (0, _utils.symbol)('render');
function defaultSerialize(model, params) {
if (params.length < 1 || !model) {
return;
}
var object = {};
if (params.length === 1) {
var [name] = params;
if (name in model) {
object[name] = (0, _metal.get)(model, name);
} else if (/_id$/.test(name)) {
object[name] = (0, _metal.get)(model, 'id');
} else if ((0, _utils.isProxy)(model)) {
object[name] = (0, _metal.get)(model, name);
}
} else {
object = (0, _metal.getProperties)(model, params);
}
return object;
}
function hasDefaultSerialize(route) {
return route.serialize === defaultSerialize;
}
/**
@module @ember/routing
*/
/**
The `Route` class is used to define individual routes. Refer to
the [routing guide](https://guides.emberjs.com/release/routing/) for documentation.
@class Route
@extends EmberObject
@uses ActionHandler
@uses Evented
@since 1.0.0
@public
*/
class Route extends _runtime.Object.extend(_runtime.ActionHandler, _runtime.Evented) {
constructor(owner) {
super(...arguments);
this.context = {};
if (owner) {
var router = owner.lookup('router:main');
var bucketCache = owner.lookup((0, _container.privatize)`-bucket-cache:main`);
(true && !(router && bucketCache) && (0, _debug.assert)('ROUTER BUG: Expected route injections to be defined on the route. This is an internal bug, please open an issue on Github if you see this message!', router && bucketCache));
this._router = router;
this._bucketCache = bucketCache;
this._topLevelViewTemplate = owner.lookup('template:-outlet');
this._environment = owner.lookup('-environment:main');
}
}
/**
Sets the name for this route, including a fully resolved name for routes
inside engines.
@private
@method _setRouteName
@param {String} name
*/
_setRouteName(name) {
this.routeName = name;
this.fullRouteName = getEngineRouteName((0, _owner.getOwner)(this), name);
}
/**
@private
@method _stashNames
*/
_stashNames(routeInfo, dynamicParent) {
if (this._names) {
return;
}
var names = this._names = routeInfo['_names'];
if (!names.length) {
routeInfo = dynamicParent;
names = routeInfo && routeInfo['_names'] || [];
}
var qps = (0, _metal.get)(this, '_qp.qps');
var namePaths = new Array(names.length);
for (var a = 0; a < names.length; ++a) {
namePaths[a] = `${routeInfo.name}.${names[a]}`;
}
for (var i = 0; i < qps.length; ++i) {
var qp = qps[i];
if (qp.scope === 'model') {
qp.parts = namePaths;
}
}
}
/**
@private
@property _activeQPChanged
*/
_activeQPChanged(qp, value) {
this._router._activeQPChanged(qp.scopedPropertyName, value);
}
/**
@private
@method _updatingQPChanged
*/
_updatingQPChanged(qp) {
this._router._updatingQPChanged(qp.urlKey);
}
/**
Returns a hash containing the parameters of an ancestor route.
You may notice that `this.paramsFor` sometimes works when referring to a
child route, but this behavior should not be relied upon as only ancestor
routes are certain to be loaded in time.
Example
```app/router.js
// ...
Router.map(function() {
this.route('member', { path: ':name' }, function() {
this.route('interest', { path: ':interest' });
});
});
```
```app/routes/member.js
import Route from '@ember/routing/route';
export default class MemberRoute extends Route {
queryParams = {
memberQp: { refreshModel: true }
}
}
```
```app/routes/member/interest.js
import Route from '@ember/routing/route';
export default class MemberInterestRoute extends Route {
queryParams = {
interestQp: { refreshModel: true }
}
model() {
return this.paramsFor('member');
}
}
```
If we visit `/turing/maths?memberQp=member&interestQp=interest` the model for
the `member.interest` route is a hash with:
* `name`: `turing`
* `memberQp`: `member`
@method paramsFor
@param {String} name
@return {Object} hash containing the parameters of the route `name`
@since 1.4.0
@public
*/
paramsFor(name) {
var route = (0, _owner.getOwner)(this).lookup(`route:${name}`);
if (route === undefined) {
return {};
}
var transition = this._router._routerMicrolib.activeTransition;
var state = transition ? transition[_router_js.STATE_SYMBOL] : this._router._routerMicrolib.state;
var fullName = route.fullRouteName;
var params = Object.assign({}, state.params[fullName]);
var queryParams = getQueryParamsFor(route, state);
return Object.keys(queryParams).reduce((params, key) => {
(true && !(!params[key]) && (0, _debug.assert)(`The route '${this.routeName}' has both a dynamic segment and query param with name '${key}'. Please rename one to avoid collisions.`, !params[key]));
params[key] = queryParams[key];
return params;
}, params);
}
/**
Serializes the query parameter key
@method serializeQueryParamKey
@param {String} controllerPropertyName
@private
*/
serializeQueryParamKey(controllerPropertyName) {
return controllerPropertyName;
}
/**
Serializes value of the query parameter based on defaultValueType
@method serializeQueryParam
@param {Object} value
@param {String} urlKey
@param {String} defaultValueType
@private
*/
serializeQueryParam(value, _urlKey, defaultValueType) {
// urlKey isn't used here, but anyone overriding
// can use it to provide serialization specific
// to a certain query param.
return this._router._serializeQueryParam(value, defaultValueType);
}
/**
Deserializes value of the query parameter based on defaultValueType
@method deserializeQueryParam
@param {Object} value
@param {String} urlKey
@param {String} defaultValueType
@private
*/
deserializeQueryParam(value, _urlKey, defaultValueType) {
// urlKey isn't used here, but anyone overriding
// can use it to provide deserialization specific
// to a certain query param.
return this._router._deserializeQueryParam(value, defaultValueType);
}
/**
@private
@property _optionsForQueryParam
*/
_optionsForQueryParam(qp) {
return (0, _metal.get)(this, `queryParams.${qp.urlKey}`) || (0, _metal.get)(this, `queryParams.${qp.prop}`) || {};
}
/**
A hook you can use to reset controller values either when the model
changes or the route is exiting.
```app/routes/articles.js
import Route from '@ember/routing/route';
export default class ArticlesRoute extends Route {
resetController(controller, isExiting, transition) {
if (isExiting && transition.targetName !== 'error') {
controller.set('page', 1);
}
}
}
```
@method resetController
@param {Controller} controller instance
@param {Boolean} isExiting
@param {Object} transition
@since 1.7.0
@public
*/
resetController(_controller, _isExiting, _transition) {
return this;
}
/**
@private
@method exit
*/
exit(transition) {
this.deactivate(transition);
this.trigger('deactivate', transition);
this.teardownViews();
}
/**
@private
@method _internalReset
@since 3.6.0
*/
_internalReset(isExiting, transition) {
var controller = this.controller;
controller['_qpDelegate'] = (0, _metal.get)(this, '_qp.states.inactive');
this.resetController(controller, isExiting, transition);
}
/**
@private
@method enter
*/
enter(transition) {
ROUTE_CONNECTIONS.set(this, []);
this.activate(transition);
this.trigger('activate', transition);
}
/**
The `willTransition` action is fired at the beginning of any
attempted transition with a `Transition` object as the sole
argument. This action can be used for aborting, redirecting,
or decorating the transition from the currently active routes.
A good example is preventing navigation when a form is
half-filled out:
```app/routes/contact-form.js
import Route from '@ember/routing/route';
import { action } from '@ember/object';
export default class ContactFormRoute extends Route {
@action
willTransition(transition) {
if (this.controller.get('userHasEnteredData')) {
this.controller.displayNavigationConfirm();
transition.abort();
}
}
}
```
You can also redirect elsewhere by calling
`this.transitionTo('elsewhere')` from within `willTransition`.
Note that `willTransition` will not be fired for the
redirecting `transitionTo`, since `willTransition` doesn't
fire when there is already a transition underway. If you want
subsequent `willTransition` actions to fire for the redirecting
transition, you must first explicitly call
`transition.abort()`.
To allow the `willTransition` event to continue bubbling to the parent
route, use `return true;`. When the `willTransition` method has a
return value of `true` then the parent route's `willTransition` method
will be fired, enabling "bubbling" behavior for the event.
@event willTransition
@param {Transition} transition
@since 1.0.0
@public
*/
/**
The `didTransition` action is fired after a transition has
successfully been completed. This occurs after the normal model
hooks (`beforeModel`, `model`, `afterModel`, `setupController`)
have resolved. The `didTransition` action has no arguments,
however, it can be useful for tracking page views or resetting
state on the controller.
```app/routes/login.js
import Route from '@ember/routing/route';
import { action } from '@ember/object';
export default class LoginRoute extends Route {
@action
didTransition() {
this.controller.get('errors.base').clear();
return true; // Bubble the didTransition event
}
}
```
@event didTransition
@since 1.2.0
@public
*/
/**
The `loading` action is fired on the route when a route's `model`
hook returns a promise that is not already resolved. The current
`Transition` object is the first parameter and the route that
triggered the loading event is the second parameter.
```app/routes/application.js
import Route from '@ember/routing/route';
import { action } from '@ember/object';
export default class ApplicationRoute extends Route {
@action
loading(transition, route) {
let controller = this.controllerFor('foo');
// The controller may not be instantiated when initially loading
if (controller) {
controller.currentlyLoading = true;
transition.finally(function() {
controller.currentlyLoading = false;
});
}
}
}
```
@event loading
@param {Transition} transition
@param {Route} route The route that triggered the loading event
@since 1.2.0
@public
*/
/**
When attempting to transition into a route, any of the hooks
may return a promise that rejects, at which point an `error`
action will be fired on the partially-entered routes, allowing
for per-route error handling logic, or shared error handling
logic defined on a parent route.
Here is an example of an error handler that will be invoked
for rejected promises from the various hooks on the route,
as well as any unhandled errors from child routes:
```app/routes/admin.js
import { reject } from 'rsvp';
import Route from '@ember/routing/route';
import { action } from '@ember/object';
export default class AdminRoute extends Route {
beforeModel() {
return reject('bad things!');
}
@action
error(error, transition) {
// Assuming we got here due to the error in `beforeModel`,
// we can expect that error === "bad things!",
// but a promise model rejecting would also
// call this hook, as would any errors encountered
// in `afterModel`.
// The `error` hook is also provided the failed
// `transition`, which can be stored and later
// `.retry()`d if desired.
this.transitionTo('login');
}
}
```
`error` actions that bubble up all the way to `ApplicationRoute`
will fire a default error handler that logs the error. You can
specify your own global default error handler by overriding the
`error` handler on `ApplicationRoute`:
```app/routes/application.js
import Route from '@ember/routing/route';
import { action } from '@ember/object';
export default class ApplicationRoute extends Route {
@action
error(error, transition) {
this.controllerFor('banner').displayError(error.message);
}
}
```
@event error
@param {Error} error
@param {Transition} transition
@since 1.0.0
@public
*/
/**
This event is triggered when the router enters the route. It is
not executed when the model for the route changes.
```app/routes/application.js
import { on } from '@ember/object/evented';
import Route from '@ember/routing/route';
export default Route.extend({
collectAnalytics: on('activate', function(){
collectAnalytics();
})
});
```
@event activate
@since 1.9.0
@public
*/
/**
This event is triggered when the router completely exits this
route. It is not executed when the model for the route changes.
```app/routes/index.js
import { on } from '@ember/object/evented';
import Route from '@ember/routing/route';
export default Route.extend({
trackPageLeaveAnalytics: on('deactivate', function(){
trackPageLeaveAnalytics();
})
});
```
@event deactivate
@since 1.9.0
@public
*/
/**
This hook is executed when the router completely exits this route. It is
not executed when the model for the route changes.
@method deactivate
@param {Transition} transition
@since 1.0.0
@public
*/
deactivate(_transition) {}
/**
This hook is executed when the router enters the route. It is not executed
when the model for the route changes.
@method activate
@param {Transition} transition
@since 1.0.0
@public
*/
activate(_transition) {}
/**
Transition the application into another route. The route may
be either a single route or route path:
```javascript
this.transitionTo('blogPosts');
this.transitionTo('blogPosts.recentEntries');
```
Optionally supply a model for the route in question. The model
will be serialized into the URL using the `serialize` hook of
the route:
```javascript
this.transitionTo('blogPost', aPost);
```
If a literal is passed (such as a number or a string), it will
be treated as an identifier instead. In this case, the `model`
hook of the route will be triggered:
```javascript
this.transitionTo('blogPost', 1);
```
Multiple models will be applied last to first recursively up the
route tree.
```app/routes.js
// ...
Router.map(function() {
this.route('blogPost', { path:':blogPostId' }, function() {
this.route('blogComment', { path: ':blogCommentId' });
});
});
export default Router;
```
```javascript
this.transitionTo('blogComment', aPost, aComment);
this.transitionTo('blogComment', 1, 13);
```
It is also possible to pass a URL (a string that starts with a
`/`).
```javascript
this.transitionTo('/');
this.transitionTo('/blog/post/1/comment/13');
this.transitionTo('/blog/posts?sort=title');
```
An options hash with a `queryParams` property may be provided as
the final argument to add query parameters to the destination URL.
```javascript
this.transitionTo('blogPost', 1, {
queryParams: { showComments: 'true' }
});
// if you just want to transition the query parameters without changing the route
this.transitionTo({ queryParams: { sort: 'date' } });
```
See also [replaceWith](#method_replaceWith).
Simple Transition Example
```app/routes.js
// ...
Router.map(function() {
this.route('index');
this.route('secret');
this.route('fourOhFour', { path: '*:' });
});
export default Router;
```
```app/routes/index.js
import Route from '@ember/routing/route';
import { action } from '@ember/object';
export default class IndexRoute extends Route {
@action
moveToSecret(context) {
if (authorized()) {
this.transitionTo('secret', context);
} else {
this.transitionTo('fourOhFour');
}
}
}
```
Transition to a nested route
```app/router.js
// ...
Router.map(function() {
this.route('articles', { path: '/articles' }, function() {
this.route('new');
});
});
export default Router;
```
```app/routes/index.js
import Route from '@ember/routing/route';
import { action } from '@ember/object';
export default class IndexRoute extends Route {
@action
transitionToNewArticle() {
this.transitionTo('articles.new');
}
}
```
Multiple Models Example
```app/router.js
// ...
Router.map(function() {
this.route('index');
this.route('breakfast', { path: ':breakfastId' }, function() {
this.route('cereal', { path: ':cerealId' });
});
});
export default Router;
```
```app/routes/index.js
import Route from '@ember/routing/route';
import { action } from '@ember/object';
export default class IndexRoute extends Route {
@action
moveToChocolateCereal() {
let cereal = { cerealId: 'ChocolateYumminess' };
let breakfast = { breakfastId: 'CerealAndMilk' };
this.transitionTo('breakfast.cereal', breakfast, cereal);
}
}
```
Nested Route with Query String Example
```app/routes.js
// ...
Router.map(function() {
this.route('fruits', function() {
this.route('apples');
});
});
export default Router;
```
```app/routes/index.js
import Route from '@ember/routing/route';
export default class IndexRoute extends Route {
@action
transitionToApples() {
this.transitionTo('fruits.apples', { queryParams: { color: 'red' } });
}
}
```
@method transitionTo
@param {String} [name] the name of the route or a URL.
@param {...Object} [models] the model(s) or identifier(s) to be used while
transitioning to the route.
@param {Object} [options] optional hash with a queryParams property
containing a mapping of query parameters. May be supplied as the only
parameter to trigger a query-parameter-only transition.
@return {Transition} the transition object associated with this
attempted transition
@since 1.0.0
@deprecated Use transitionTo from the Router service instead.
@public
*/
transitionTo(...args) {
(0, _utils2.deprecateTransitionMethods)('route', 'transitionTo');
return this._router.transitionTo(...(0, _utils2.prefixRouteNameArg)(this, args));
}
/**
Perform a synchronous transition into another route without attempting
to resolve promises, update the URL, or abort any currently active
asynchronous transitions (i.e. regular transitions caused by
`transitionTo` or URL changes).
This method is handy for performing intermediate transitions on the
way to a final destination route, and is called internally by the
default implementations of the `error` and `loading` handlers.
@method intermediateTransitionTo
@param {String} name the name of the route
@param {...Object} models the model(s) to be used while transitioning
to the route.
@since 1.2.0
@public
*/
intermediateTransitionTo(...args) {
var [name, ...preparedArgs] = (0, _utils2.prefixRouteNameArg)(this, args);
this._router.intermediateTransitionTo(name, ...preparedArgs);
}
/**
Refresh the model on this route and any child routes, firing the
`beforeModel`, `model`, and `afterModel` hooks in a similar fashion
to how routes are entered when transitioning in from other route.
The current route params (e.g. `article_id`) will be passed in
to the respective model hooks, and if a different model is returned,
`setupController` and associated route hooks will re-fire as well.
An example usage of this method is re-querying the server for the
latest information using the same parameters as when the route
was first entered.
Note that this will cause `model` hooks to fire even on routes
that were provided a model object when the route was initially
entered.
@method refresh
@return {Transition} the transition object associated with this
attempted transition
@since 1.4.0
@public
*/
refresh() {
return this._router._routerMicrolib.refresh(this);
}
/**
Transition into another route while replacing the current URL, if possible.
This will replace the current history entry instead of adding a new one.
Beside that, it is identical to `transitionTo` in all other respects. See
'transitionTo' for additional information regarding multiple models.
Example
```app/router.js
// ...
Router.map(function() {
this.route('index');
this.route('secret');
});
export default Router;
```
```app/routes/secret.js
import Route from '@ember/routing/route';
export default class SecretRoute Route {
afterModel() {
if (!authorized()){
this.replaceWith('index');
}
}
}
```
@method replaceWith
@param {String} name the name of the route or a URL
@param {...Object} models the model(s) or identifier(s) to be used while
transitioning to the route.
@param {Object} [options] optional hash with a queryParams property
containing a mapping of query parameters
@return {Transition} the transition object associated with this
attempted transition
@since 1.0.0
@public
*/
replaceWith(...args) {
(0, _utils2.deprecateTransitionMethods)('route', 'replaceWith');
return this._router.replaceWith(...(0, _utils2.prefixRouteNameArg)(this, args));
}
/**
This hook is the entry point for router.js
@private
@method setup
*/
setup(context, transition) {
var controllerName = this.controllerName || this.routeName;
var definedController = this.controllerFor(controllerName, true);
var controller;
if (definedController) {
controller = definedController;
} else {
controller = this.generateController(controllerName);
} // Assign the route's controller so that it can more easily be
// referenced in action handlers. Side effects. Side effects everywhere.
if (!this.controller) {
var qp = (0, _metal.get)(this, '_qp');
var propNames = qp !== undefined ? (0, _metal.get)(qp, 'propertyNames') : [];
addQueryParamsObservers(controller, propNames);
this.controller = controller;
}
var queryParams = (0, _metal.get)(this, '_qp');
var states = queryParams.states;
controller._qpDelegate = states.allowOverrides;
if (transition) {
// Update the model dep values used to calculate cache keys.
(0, _utils2.stashParamNames)(this._router, transition[_router_js.STATE_SYMBOL].routeInfos);
var cache = this._bucketCache;
var params = transition[_router_js.PARAMS_SYMBOL];
var allParams = queryParams.propertyNames;
allParams.forEach(prop => {
var aQp = queryParams.map[prop];
aQp.values = params;
var cacheKey = (0, _utils2.calculateCacheKey)(aQp.route.fullRouteName, aQp.parts, aQp.values);
var value = cache.lookup(cacheKey, prop, aQp.undecoratedDefaultValue);
(0, _metal.set)(controller, prop, value);
});
var qpValues = getQueryParamsFor(this, transition[_router_js.STATE_SYMBOL]);
(0, _metal.setProperties)(controller, qpValues);
}
this.setupController(controller, context, transition);
if (this._environment.options.shouldRender) {
this[RENDER]();
} // Setup can cause changes to QPs which need to be propogated immediately in
// some situations. Eventually, we should work on making these async somehow.
(0, _metal.flushAsyncObservers)(false);
}
/*
Called when a query parameter for this route changes, regardless of whether the route
is currently part of the active route hierarchy. This will update the query parameter's
value in the cache so if this route becomes active, the cache value has been updated.
*/
_qpChanged(prop, value, qp) {
if (!qp) {
return;
} // Update model-dep cache
var cache = this._bucketCache;
var cacheKey = (0, _utils2.calculateCacheKey)(qp.route.fullRouteName, qp.parts, qp.values);
cache.stash(cacheKey, prop, value);
}
/**
This hook is the first of the route entry validation hooks
called when an attempt is made to transition into a route
or one of its children. It is called before `model` and
`afterModel`, and is appropriate for cases when:
1) A decision can be made to redirect elsewhere without
needing to resolve the model first.
2) Any async operations need to occur first before the
model is attempted to be resolved.
This hook is provided the current `transition` attempt
as a parameter, which can be used to `.abort()` the transition,
save it for a later `.retry()`, or retrieve values set
on it from a previous hook. You can also just call
`this.transitionTo` to another route to implicitly
abort the `transition`.
You can return a promise from this hook to pause the
transition until the promise resolves (or rejects). This could
be useful, for instance, for retrieving async code from
the server that is required to enter a route.
@method beforeModel
@param {Transition} transition
@return {any | Promise<any>} if the value returned from this hook is
a promise, the transition will pause until the transition
resolves. Otherwise, non-promise return values are not
utilized in any way.
@since 1.0.0
@public
*/
beforeModel() {}
/**
This hook is called after this route's model has resolved.
It follows identical async/promise semantics to `beforeModel`
but is provided the route's resolved model in addition to
the `transition`, and is therefore suited to performing
logic that can only take place after the model has already
resolved.
```app/routes/posts.js
import Route from '@ember/routing/route';
export default class PostsRoute extends Route {
afterModel(posts, transition) {
if (posts.get('length') === 1) {
this.transitionTo('post.show', posts.get('firstObject'));
}
}
}
```
Refer to documentation for `beforeModel` for a description
of transition-pausing semantics when a promise is returned
from this hook.
@method afterModel
@param {Object} resolvedModel the value returned from `model`,
or its resolved value if it was a promise
@param {Transition} transition
@return {any | Promise<any>} if the value returned from this hook is
a promise, the transition will pause until the transition
resolves. Otherwise, non-promise return values are not
utilized in any way.
@since 1.0.0
@public
*/
afterModel() {}
/**
A hook you can implement to optionally redirect to another route.
Calling `this.transitionTo` from inside of the `redirect` hook will
abort the current transition (into the route that has implemented `redirect`).
`redirect` and `afterModel` behave very similarly and are
called almost at the same time, but they have an important
distinction when calling `this.transitionTo` to a child route
of the current route. From `afterModel`, this new transition
invalidates the current transition, causing `beforeModel`,
`model`, and `afterModel` hooks to be called again. But the
same transition started from `redirect` does _not_ invalidate
the current transition. In other words, by the time the `redirect`
hook has been called, both the resolved model and the attempted
entry into this route are considered fully validated.
@method redirect
@param {Object} model the model for this route
@param {Transition} transition the transition object associated with the current transition
@since 1.0.0
@public
*/
redirect() {}
/**
Called when the context is changed by router.js.
@private
@method contextDidChange
*/
contextDidChange() {
this.currentModel = this.context;
}
/**
A hook you can implement to convert the URL into the model for
this route.
```app/router.js
// ...
Router.map(function() {
this.route('post', { path: '/posts/:post_id' });
});
export default Router;
```
The model for the `post` route is `store.findRecord('post', params.post_id)`.
By default, if your route has a dynamic segment ending in `_id`:
* The model class is determined from the segment (`post_id`'s
class is `App.Post`)
* The find method is called on the model class with the value of
the dynamic segment.
Note that for routes with dynamic segments, this hook is not always
executed. If the route is entered through a transition (e.g. when
using the `link-to` Handlebars helper or the `transitionTo` method
of routes), and a model context is already provided this hook
is not called.
A model context does not include a primitive string or number,
which does cause the model hook to be called.
Routes without dynamic segments will always execute the model hook.
```javascript
// no dynamic segment, model hook always called
this.transitionTo('posts');
// model passed in, so model hook not called
thePost = store.findRecord('post', 1);
this.transitionTo('post', thePost);
// integer passed in, model hook is called
this.transitionTo('post', 1);
// model id passed in, model hook is called
// useful for forcing the hook to execute
thePost = store.findRecord('post', 1);
this.transitionTo('post', thePost.id);
```
This hook follows the asynchronous/promise semantics
described in the documentation for `beforeModel`. In particular,
if a promise returned from `model` fails, the error will be
handled by the `error` hook on `Route`.
Example
```app/routes/post.js
import Route from '@ember/routing/route';
export default class PostRoute extends Route {
model(params) {
return this.store.findRecord('post', params.post_id);
}
}
```
@method model
@param {Object} params the parameters extracted from the URL
@param {Transition} transition
@return {any | Promise<any>} the model for this route. If
a promise is returned, the transition will pause until
the promise resolves, and the resolved value of the promise
will be used as the model for this route.
@since 1.0.0
@public
*/
model(params, transition) {
var name, sawParams, value;
var queryParams = (0, _metal.get)(this, '_qp.map');
for (var prop in params) {
if (prop === 'queryParams' || queryParams && prop in queryParams) {
continue;
}
var match = prop.match(/^(.*)_id$/);
if (match !== null) {
name = match[1];
value = params[prop];
}
sawParams = true;
}
if (!name) {
if (sawParams) {
return Object.assign({}, params);
} else {
if (transition.resolveIndex < 1) {
return;
}
return transition[_router_js.STATE_SYMBOL].routeInfos[transition.resolveIndex - 1].context;
}
}
return this.findModel(name, value);
}
/**
@private
@method deserialize
@param {Object} params the parameters extracted from the URL
@param {Transition} transition
@return {any | Promise<any>} the model for this route.
Router.js hook.
*/
deserialize(_params, transition) {
return this.model(this._paramsFor(this.routeName, _params), transition);
}
/**
@method findModel
@param {String} type the model type
@param {Object} value the value passed to find
@private
*/
findModel(...args) {
return (0, _metal.get)(this, 'store').find(...args);
}
/**
A hook you can use to setup the controller for the current route.
This method is called with the controller for the current route and the
model supplied by the `model` hook.
By default, the `setupController` hook sets the `model` property of
the controller to the specified `model` when it is not `undefined`.
If you implement the `setupController` hook in your Route, it will
prevent this default behavior. If you want to preserve that behavior
when implementing your `setupController` function, make sure to call
`super`:
```app/routes/photos.js
import Route from '@ember/routing/route';
export default class PhotosRoute extends Route {
model() {
return this.store.findAll('photo');
}
setupController(controller, model) {
super.setupController(controller, model);
this.controllerFor('application').set('showingPhotos', true);
}
}
```
The provided controller will be one resolved based on the name
of this route.
If no explicit controller is defined, Ember will automatically create one.
As an example, consider the router:
```app/router.js
// ...
Router.map(function() {
this.route('post', { path: '/posts/:post_id' });
});
export default Router;
```
If you have defined a file for the post controller,
the framework will use it.
If it is not defined, a basic `Controller` instance would be used.
@example Behavior of a basic Controller
```app/routes/post.js
import Route from '@ember/routing/route';
export default class PostRoute extends Route {
setupController(controller, model) {
controller.set('model', model);
}
});
```
@method setupController
@param {Controller} controller instance
@param {Object} model
@param {Transition} [transition]
@since 1.0.0
@public
*/
setupController(controller, context, _transition) {
// eslint-disable-line no-unused-vars
if (controller && context !== undefined) {
(0, _metal.set)(controller, 'model', context);
}
}
/**
Returns the controller of the current route, or a parent (or any ancestor)
route in a route hierarchy.
The controller instance must already have been created, either through entering the
associated route or using `generateController`.
```app/routes/post.js
import Route from '@ember/routing/route';
export default class PostRoute extends Route {
setupController(controller, post) {
super.setupController(controller, post);
this.controllerFor('posts').set('currentPost', post);
}
}
```
@method controllerFor
@param {String} name the name of the route or controller
@return {Controller}
@since 1.0.0
@public
*/
controllerFor(name, _skipAssert) {
var owner = (0, _owner.getOwner)(this);
var route = owner.lookup(`route:${name}`);
if (route && route.controllerName) {
name = route.controllerName;
}
var controller = owner.lookup(`controller:${name}`); // NOTE: We're specifically checking that skipAssert is true, because according
// to the old API the second parameter was model. We do not want people who
// passed a model to skip the assertion.
(true && !(controller !== undefined || _skipAssert === true) && (0, _debug.assert)(`The controller named '${name}' could not be found. Make sure that this route exists and has already been entered at least once. If you are accessing a controller not associated with a route, make sure the controller class is explicitly defined.`, controller !== undefined || _skipAssert === true));
return controller;
}
/**
Generates a controller for a route.
Example
```app/routes/post.js
import Route from '@ember/routing/route';
export default class Post extends Route {
setupController(controller, post) {
super.setupController(controller, post);
this.generateController('posts');
}
}
```
@method generateController
@param {String} name the name of the controller
@private
*/
generateController(name) {
var owner = (0, _owner.getOwner)(this);
return (0, _generate_controller.default)(owner, name);
}
/**
Returns the resolved model of a parent (or any ancestor) route
in a route hierarchy. During a transition, all routes
must resolve a model object, and if a route
needs access to a parent route's model in order to
resolve a model (or just reuse the model from a parent),
it can call `this.modelFor(theNameOfParentRoute)` to
retrieve it. If the ancestor route's model was a promise,
its resolved result is returned.
Example
```app/router.js
// ...
Router.map(function() {
this.route('post', { path: '/posts/:post_id' }, function() {
this.route('comments');
});
});
export default Router;
```
```app/routes/post/comments.js
import Route from '@ember/routing/route';
export default class PostCommentsRoute extends Route {
model() {
let post = this.modelFor('post');
return post.comments;
}
}
```
@method modelFor
@param {String} name the name of the route
@return {Object} the model object
@since 1.0.0
@public
*/
modelFor(_name) {
var name;
var owner = (0, _owner.getOwner)(this);
var transition = this._router && this._router._routerMicrolib ? this._router._routerMicrolib.activeTransition : undefined; // Only change the route name when there is an active transition.
// Otherwise, use the passed in route name.
if (owner.routable && transition !== undefined) {
name = getEngineRouteName(owner, _name);
} else {
name = _name;
}
var route = owner.lookup(`route:${name}`); // If we are mid-transition, we want to try and look up
// resolved parent contexts on the current transitionEvent.
if (transition !== undefined && transition !== null) {
var modelLookupName = route && route.routeName || name;
if (Object.prototype.hasOwnProperty.call(transition.resolvedModels, modelLookupName)) {
return transition.resolvedModels[modelLookupName];
}
}
return route && route.currentModel;
}
/**
`this[RENDER]` is used to render a template into a region of another template
(indicated by an `{{outlet}}`).
@method this[RENDER]
@param {String} name the name of the template to render
@param {Object} [options] the options
@param {String} [options.into] the template to render into,
referenced by name. Defaults to the parent template
@param {String} [options.outlet] the outlet inside `options.into` to render into.
Defaults to 'main'
@param {String|Object} [options.controller] the controller to use for this template,
referenced by name or as a controller instance. Defaults to the Route's paired controller
@param {Object} [options.model] the model object to set on `options.controller`.
Defaults to the return value of the Route's model hook
@private
*/
[RENDER](name, options) {
var renderOptions = buildRenderOptions(this, name, options);
ROUTE_CONNECTIONS.get(this).push(renderOptions);
(0, _runloop.once)(this._router, '_setOutlets');
}
willDestroy() {
this.teardownViews();
}
/**
@private
@method teardownViews
*/
teardownViews() {
var connections = ROUTE_CONNECTIONS.get(this);
if (connections !== undefined && connections.length > 0) {
ROUTE_CONNECTIONS.set(this, []);
(0, _runloop.once)(this._router, '_setOutlets');
}
}
/**
Allows you to produce custom metadata for the route.
The return value of this method will be attached to
its corresponding RouteInfoWithAttributes object.
Example
```app/routes/posts/index.js
import Route from '@ember/routing/route';
export default class PostsIndexRoute extends Route {
buildRouteInfoMetadata() {
return { title: 'Posts Page' }
}
}
```
```app/routes/application.js
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default class ApplicationRoute extends Route {
@service router
constructor() {
super(...arguments);
this.router.on('routeDidChange', transition => {
document.title = transition.to.metadata.title;
// would update document's title to "Posts Page"
});
}
}
```
@method buildRouteInfoMetadata
@return any
@since 3.10.0
@public
*/
buildRouteInfoMetadata() {}
_paramsFor(routeName, params) {
var transition = this._router._routerMicrolib.activeTransition;
if (transition !== undefined) {
return this.paramsFor(routeName);
}
return params;
}
/**
Store property provides a hook for data persistence libraries to inject themselves.
By default, this store property provides the exact same functionality previously
in the model hook.
Currently, the required interface is:
`store.find(modelName, findArguments)`
@property store
@type {Object}
@private
*/
get store() {
var owner = (0, _owner.getOwner)(this);
var routeName = this.routeName;
var namespace = (0, _metal.get)(this, '_router.namespace');
return {
find(name, value) {
var modelClass = owner.factoryFor(`model:${name}`);
(true && !(Boolean(modelClass)) && (0, _debug.assert)(`You used the dynamic segment ${name}_id in your route ${routeName}, but ${namespace}.${(0, _string.classify)(name)} did not exist and you did not override your route's \`model\` hook.`, Boolean(modelClass)));
if (!modelClass) {
return;
}
modelClass = modelClass.class;
(true && !(typeof modelClass.find === 'function') && (0, _debug.assert)(`${(0, _string.classify)(name)} has no method \`find\`.`, typeof modelClass.find === 'function'));
return modelClass.find(value);
}
};
}
set store(value) {
(0, _metal.defineProperty)(this, 'store', null, value);
}
/**
@private
@property _qp
*/
get _qp() {
var combinedQueryParameterConfiguration;
var controllerName = this.controllerName || this.routeName;
var owner = (0, _owner.getOwner)(this);
var controller = owner.lookup(`controller:${controllerName}`);
var queryParameterConfiguraton = (0, _metal.get)(this, 'queryParams');
var hasRouterDefinedQueryParams = Object.keys(queryParameterConfiguraton).length > 0;
if (controller) {
// the developer has authored a controller class in their application for
// this route find its query params and normalize their object shape them
// merge in the query params for the route. As a mergedProperty,
// Route#queryParams is always at least `{}`
var controllerDefinedQueryParameterConfiguration = (0, _metal.get)(controller, 'queryParams') || {};
var normalizedControllerQueryParameterConfiguration = (0, _utils2.normalizeControllerQueryParams)(controllerDefinedQueryParameterConfiguration);
combinedQueryParameterConfiguration = mergeEachQueryParams(normalizedControllerQueryParameterConfiguration, queryParameterConfiguraton);
} else if (hasRouterDefinedQueryParams) {
// the developer has not defined a controller but *has* supplied route query params.
// Generate a class for them so we can later insert default values
controller = (0, _generate_controller.default)(owner, controllerName);
combinedQueryParameterConfiguration = queryParameterConfiguraton;
}
var qps = [];
var map = {};
var propertyNames = [];
for (var propName in combinedQueryParameterConfiguration) {
if (!Object.prototype.hasOwnProperty.call(combinedQueryParameterConfiguration, propName)) {
continue;
} // to support the dubious feature of using unknownProperty
// on queryParams configuration
if (propName === 'unknownProperty' || propName === '_super') {
// possible todo: issue deprecation warning?
continue;
}
var desc = combinedQueryParameterConfiguration[propName];
var scope = desc.scope || 'model';
var parts = void 0;
if (scope === 'controller') {
parts = [];
}
var urlKey = desc.as || this.serializeQueryParamKey(propName);
var defaultValue = (0, _metal.get)(controller, propName);
defaultValue = copyDefaultValue(defaultValue);
var type = desc.type || (0, _runtime.typeOf)(defaultValue);
var defaultValueSerialized = this.serializeQueryParam(defaultValue, urlKey, type);
var scopedPropertyName = `${controllerName}:${propName}`;
var qp = {
undecoratedDefaultValue: (0, _metal.get)(controller, propName),
defaultValue,
serializedDefaultValue: defaultValueSerialized,
serializedValue: defaultValueSerialized,
type,
urlKey,
prop: propName,
scopedPropertyName,
controllerName,
route: this,
parts,
values: null,
scope
};
map[propName] = map[urlKey] = map[scopedPropertyName] = qp;
qps.push(qp);
propertyNames.push(propName);
}
return {
qps,
map,
propertyNames,
states: {
/*
Called when a query parameter changes in the URL, this route cares
about that query parameter, but the route is not currently
in the active route hierarchy.
*/
inactive: (prop, value) => {
var qp = map[prop];
this._qpChanged(prop, value, qp);
},
/*
Called when a query parameter changes in the URL, this route cares
about that query parameter, and the route is currently
in the active route hierarchy.
*/
active: (prop, value) => {
var qp = map[prop];
this._qpChanged(prop, value, qp);
return this._activeQPChanged(qp, value);
},
/*
Called when a value of a query parameter this route handles changes in a controller
and the route is currently in the active route hierarchy.
*/
allowOverrides: (prop, value) => {
var qp = map[prop];
this._qpChanged(prop, value, qp);
return this._updatingQPChanged(qp);
}
}
};
}
}
Route.isRouteFactory = true;
__decorate([_metal.computed], Route.prototype, "store", null);
__decorate([_metal.computed], Route.prototype, "_qp", null);
function parentRoute(route) {
var routeInfo = routeInfoFor(route, route._router._routerMicrolib.state.routeInfos, -1);
return routeInfo && routeInfo.route;
}
function routeInfoFor(route, routeInfos, offset = 0) {
if (!routeInfos) {
return;
}
var current;
for (var i = 0; i < routeInfos.length; i++) {
current = routeInfos[i].route;
if (current === route) {
return routeInfos[i + offset];
}
}
return;
}
function buildRenderOptions(route, nameOrOptions, options) {
var isDefaultRender = !nameOrOptions && !options;
var _name;
if (!isDefaultRender) {
if (typeof nameOrOptions === 'object' && !options) {
_name = route.templateName || route.routeName;
options = nameOrOptions;
} else {
(true && !(!(0, _metal.isEmpty)(nameOrOptions)) && (0, _debug.assert)('The name in the given arguments is undefined or empty string', !(0, _metal.isEmpty)(nameOrOptions)));
_name = nameOrOptions;
}
}
(true && !(isDefaultRender || !(options && 'outlet' in options && options.outlet === undefined)) && (0, _debug.assert)('You passed undefined as the outlet name.', isDefaultRender || !(options && 'outlet' in options && options.outlet === undefined)));
var owner = (0, _owner.getOwner)(route);
var name, templateName, into, outlet, model;
var controller = undefined;
if (options) {
into = options.into && options.into.replace(/\//g, '.');
outlet = options.outlet;
controller = options.controller;
model = options.model;
}
outlet = outlet || 'main';
if (isDefaultRender) {
name = route.routeName;
templateName = route.templateName || name;
} else {
name = _name.replace(/\//g, '.');
templateName = name;
}
if (controller === undefined) {
if (isDefaultRender) {
controller = route.controllerName || owner.lookup(`controller:${name}`);
} else {
controller = owner.lookup(`controller:${name}`) || route.controllerName || route.routeName;
}
}
if (typeof controller === 'string') {
var controllerName = controller;
controller = owner.lookup(`controller:${controllerName}`);
(true && !(isDefaultRender || controller !== undefined) && (0, _debug.assert)(`You passed \`controller: '${controllerName}'\` into the \`render\` method, but no such controller could be found.`, isDefaultRender || controller !== undefined));
}
if (model === undefined) {
model = route.currentModel;
} else {
controller.set('model', model);
}
var template = owner.lookup(`template:${templateName}`);
(true && !(isDefaultRender || template !== undefined) && (0, _debug.assert)(`Could not find "${templateName}" template, view, or component.`, isDefaultRender || template !== undefined));
var parent;
if (into && (parent = parentRoute(route)) && into === parent.routeName) {
into = undefined;
}
var renderOptions = {
owner,
into,
outlet,
name,
controller,
model,
template: template !== undefined ? template(owner) : route._topLevelViewTemplate(owner)
};
if (true
/* DEBUG */
) {
var LOG_VIEW_LOOKUPS = (0, _metal.get)(route._router, 'namespace.LOG_VIEW_LOOKUPS');
if (LOG_VIEW_LOOKUPS && !template) {
(0, _debug.info)(`Could not find "${name}" template. Nothing will be rendered`, {
fullName: `template:${name}`
});
}
}
return renderOptions;
}
function getFullQueryParams(router, state) {
if (state['fullQueryParams']) {
return state['fullQueryParams'];
}
var fullQueryParamsState = {};
var haveAllRouteInfosResolved = state.routeInfos.every(routeInfo => routeInfo.route);
Object.assign(fullQueryParamsState, state.queryParams);
router._deserializeQueryParams(state.routeInfos, fullQueryParamsState); // only cache query params state if all routeinfos have resolved; it's possible
// for lazy routes to not have resolved when `getFullQueryParams` is called, so
// we wait until all routes have resolved prior to caching query params state
if (haveAllRouteInfosResolved) {
state['fullQueryParams'] = fullQueryParamsState;
}
return fullQueryParamsState;
}
function getQueryParamsFor(route, state) {
state['queryParamsFor'] = state['queryParamsFor'] || {};
var name = route.fullRouteName;
if (state['queryParamsFor'][name]) {
return state['queryParamsFor'][name];
}
var fullQueryParams = getFullQueryParams(route._router, state);
var params = state['queryParamsFor'][name] = {}; // Copy over all the query params for this route/controller into params hash.
var qps = (0, _metal.get)(route, '_qp.qps');
for (var i = 0; i < qps.length; ++i) {
// Put deserialized qp on params hash.
var qp = qps[i];
var qpValueWasPassedIn = (qp.prop in fullQueryParams);
params[qp.prop] = qpValueWasPassedIn ? fullQueryParams[qp.prop] : copyDefaultValue(qp.defaultValue);
}
return params;
}
function copyDefaultValue(value) {
if (Array.isArray(value)) {
return (0, _runtime.A)(value.slice());
}
return value;
}
/*
Merges all query parameters from a controller with those from
a route, returning a new object and avoiding any mutations to
the existing objects.
*/
function mergeEachQueryParams(controllerQP, routeQP) {
var qps = {};
var keysAlreadyMergedOrSkippable = {
defaultValue: true,
type: true,
scope: true,
as: true
}; // first loop over all controller qps, merging them with any matching route qps
// into a new empty object to avoid mutating.
for (var cqpName in controllerQP) {
if (!Object.prototype.hasOwnProperty.call(controllerQP, cqpName)) {
continue;
}
var newControllerParameterConfiguration = {};
Object.assign(newControllerParameterConfiguration, controllerQP[cqpName], routeQP[cqpName]);
qps[cqpName] = newControllerParameterConfiguration; // allows us to skip this QP when we check route QPs.
keysAlreadyMergedOrSkippable[cqpName] = true;
} // loop over all route qps, skipping those that were merged in the first pass
// because they also appear in controller qps
for (var rqpName in routeQP) {
if (!Object.prototype.hasOwnProperty.call(routeQP, rqpName) || keysAlreadyMergedOrSkippable[rqpName]) {
continue;
}
var newRouteParameterConfiguration = {};
Object.assign(newRouteParameterConfiguration, routeQP[rqpName], controllerQP[rqpName]);
qps[rqpName] = newRouteParameterConfiguration;
}
return qps;
}
function addQueryParamsObservers(controller, propNames) {
propNames.forEach(prop => {
if ((0, _metal.descriptorForProperty)(controller, prop) === undefined) {
var desc = (0, _utils.lookupDescriptor)(controller, prop);
if (desc !== null && (typeof desc.get === 'function' || typeof desc.set === 'function')) {
(0, _metal.defineProperty)(controller, prop, (0, _compat.dependentKeyCompat)({
get: desc.get,
set: desc.set
}));
}
}
(0, _metal.addObserver)(controller, `${prop}.[]`, controller, controller._qpChanged, false);
});
}
function getEngineRouteName(engine, routeName) {
if (engine.routable) {
var prefix = engine.mountPoint;
if (routeName === 'application') {
return prefix;
} else {
return `${prefix}.${routeName}`;
}
}
return routeName;
}
/**
A hook you can implement to convert the route's model into parameters
for the URL.
```app/router.js
// ...
Router.map(function() {
this.route('post', { path: '/posts/:post_id' });
});
```
```app/routes/post.js
import Route from '@ember/routing/route';
export default class PostRoute extends Route {
model({ post_id }) {
// the server returns `{ id: 12 }`
return fetch(`/posts/${post_id}`;
}
serialize(model) {
// this will make the URL `/posts/12`
return { post_id: model.id };
}
}
```
The default `serialize` method will insert the model's `id` into the
route's dynamic segment (in this case, `:post_id`) if the segment contains '_id'.
If the route has multiple dynamic segments or does not contain '_id', `serialize`
will return `getProperties(model, params)`
This method is called when `transitionTo` is called with a context
in order to populate the URL.
@method serialize
@param {Object} model the routes model
@param {Array} params an Array of parameter names for the current
route (in the example, `['post_id']`.
@return {Object} the serialized parameters
@since 1.0.0
@public
*/
Route.prototype.serialize = defaultSerialize; // Set these here so they can be overridden with extend
Route.reopen({
mergedProperties: ['queryParams'],
queryParams: {},
templateName: null,
controllerName: null,
send(...args) {
(true && !(!this.isDestroying && !this.isDestroyed) && (0, _debug.assert)(`Attempted to call .send() with the action '${args[0]}' on the destroyed route '${this.routeName}'.`, !this.isDestroying && !this.isDestroyed));
if (this._router && this._router._routerMicrolib || !(0, _debug.isTesting)()) {
this._router.send(...args);
} else {
var name = args.shift();
var action = this.actions[name];
if (action) {
return action.apply(this, args);
}
}
},
/**
The controller associated with this route.
Example
```app/routes/form.js
import Route from '@ember/routing/route';
import { action } from '@ember/object';
export default class FormRoute extends Route {
@action
willTransition(transition) {
if (this.controller.get('userHasEnteredData') &&
!confirm('Are you sure you want to abandon progress?')) {
transition.abort();
} else {
// Bubble the `willTransition` action so that
// parent routes can decide whether or not to abort.
return true;
}
}
}
```
@property controller
@type Controller
@since 1.6.0
@public
*/
actions: {
/**
This action is called when one or more query params have changed. Bubbles.
@method queryParamsDidChange
@param changed {Object} Keys are names of query params that have changed.
@param totalPresent {Object} Keys are names of query params that are currently set.
@param removed {Object} Keys are names of query params that have been removed.
@returns {boolean}
@private
*/
queryParamsDidChange(changed, _totalPresent, removed) {
var qpMap = (0, _metal.get)(this, '_qp').map;
var totalChanged = Object.keys(changed).concat(Object.keys(removed));
for (var i = 0; i < totalChanged.length; ++i) {
var qp = qpMap[totalChanged[i]];
if (qp && (0, _metal.get)(this._optionsForQueryParam(qp), 'refreshModel') && this._router.currentState) {
this.refresh();
break;
}
}
return true;
},
finalizeQueryParamChange(params, finalParams, transition) {
if (this.fullRouteName !== 'application') {
return true;
} // Transition object is absent for intermediate transitions.
if (!transition) {
return;
}
var routeInfos = transition[_router_js.STATE_SYMBOL].routeInfos;
var router = this._router;
var qpMeta = router._queryParamsFor(routeInfos);
var changes = router._qpUpdates;
var qpUpdated = false;
var replaceUrl;
(0, _utils2.stashParamNames)(router, routeInfos);
for (var i = 0; i < qpMeta.qps.length; ++i) {
var qp = qpMeta.qps[i];
var route = qp.route;
var controller = route.controller;
var presentKey = qp.urlKey in params && qp.urlKey; // Do a reverse lookup to see if the changed query
// param URL key corresponds to a QP property on
// this controller.
var value = void 0,
svalue = void 0;
if (changes.has(qp.urlKey)) {
// Value updated in/before setupController
value = (0, _metal.get)(controller, qp.prop);
svalue = route.serializeQueryParam(value, qp.urlKey, qp.type);
} else {
if (presentKey) {
svalue = params[presentKey];
if (svalue !== undefined) {
value = route.deserializeQueryParam(svalue, qp.urlKey, qp.type);
}
} else {
// No QP provided; use default value.
svalue = qp.serializedDefaultValue;
value = copyDefaultValue(qp.defaultValue);
}
}
controller._qpDelegate = (0, _metal.get)(route, '_qp.states.inactive');
var thisQueryParamChanged = svalue !== qp.serializedValue;
if (thisQueryParamChanged) {
if (transition.queryParamsOnly && replaceUrl !== false) {
var options = route._optionsForQueryParam(qp);
var replaceConfigValue = (0, _metal.get)(options, 'replace');
if (replaceConfigValue) {
replaceUrl = true;
} else if (replaceConfigValue === false) {
// Explicit pushState wins over any other replaceStates.
replaceUrl = false;
}
}
(0, _metal.set)(controller, qp.prop, value);
qpUpdated = true;
} // Stash current serialized value of controller.
qp.serializedValue = svalue;
var thisQueryParamHasDefaultValue = qp.serializedDefaultValue === svalue;
if (!thisQueryParamHasDefaultValue || transition._keepDefaultQueryParamValues) {
finalParams.push({
value: svalue,
visible: true,
key: presentKey || qp.urlKey
});
}
} // Some QPs have been updated, and those changes need to be propogated
// immediately. Eventually, we should work on making this async somehow.
if (qpUpdated === true) {
(0, _metal.flushAsyncObservers)(false);
}
if (replaceUrl) {
transition.method('replace');
}
qpMeta.qps.forEach(qp => {
var routeQpMeta = (0, _metal.get)(qp.route, '_qp');
var finalizedController = qp.route.controller;
finalizedController['_qpDelegate'] = (0, _metal.get)(routeQpMeta, 'states.active');
});
router._qpUpdates.clear();
return;
}
}
});
var _default = Route;
_exports.default = _default;
});
define("@ember/-internals/routing/lib/system/router", ["exports", "@ember/-internals/container", "@ember/-internals/metal", "@ember/-internals/owner", "@ember/-internals/runtime", "@ember/debug", "@ember/error", "@ember/runloop", "@ember/-internals/routing/lib/location/api", "@ember/-internals/routing/lib/utils", "@ember/-internals/routing/lib/system/dsl", "@ember/-internals/routing/lib/system/route", "@ember/-internals/routing/lib/system/router_state", "router_js"], function (_exports, _container, _metal, _owner, _runtime, _debug, _error2, _runloop, _api, _utils, _dsl, _route, _router_state, _router_js) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.triggerEvent = triggerEvent;
_exports.default = void 0;
function defaultDidTransition(infos) {
updatePaths(this);
this._cancelSlowTransitionTimer();
this.notifyPropertyChange('url');
this.set('currentState', this.targetState);
if (true
/* DEBUG */
) {
// @ts-expect-error namespace isn't public
if (this.namespace.LOG_TRANSITIONS) {
// eslint-disable-next-line no-console
console.log(`Transitioned into '${EmberRouter._routePath(infos)}'`);
}
}
}
function defaultWillTransition(oldInfos, newInfos) {
if (true
/* DEBUG */
) {
// @ts-expect-error namespace isn't public
if (this.namespace.LOG_TRANSITIONS) {
// eslint-disable-next-line no-console
console.log(`Preparing to transition from '${EmberRouter._routePath(oldInfos)}' to '${EmberRouter._routePath(newInfos)}'`);
}
}
}
var freezeRouteInfo;
if (true
/* DEBUG */
) {
freezeRouteInfo = transition => {
if (transition.from !== null && !Object.isFrozen(transition.from)) {
Object.freeze(transition.from);
}
if (transition.to !== null && !Object.isFrozen(transition.to)) {
Object.freeze(transition.to);
}
};
}
function K() {
return this;
}
var {
slice
} = Array.prototype;
/**
The `EmberRouter` class manages the application state and URLs. Refer to
the [routing guide](https://guides.emberjs.com/release/routing/) for documentation.
@class EmberRouter
@extends EmberObject
@uses Evented
@public
*/
class EmberRouter extends _runtime.Object.extend(_runtime.Evented) {
constructor(owner) {
super(...arguments);
this._didSetupRouter = false;
this._initialTransitionStarted = false;
this.currentURL = null;
this.currentRouteName = null;
this.currentPath = null;
this.currentRoute = null;
this._qpCache = Object.create(null);
this._qpUpdates = new Set();
this._queuedQPChanges = {};
this._toplevelView = null;
this._handledErrors = new Set();
this._engineInstances = Object.create(null);
this._engineInfoByRoute = Object.create(null);
this.currentState = null;
this.targetState = null;
this._resetQueuedQueryParameterChanges();
this.namespace = owner.lookup('application:main');
var bucketCache = owner.lookup((0, _container.privatize)`-bucket-cache:main`);
(true && !(bucketCache !== undefined) && (0, _debug.assert)('BUG: BucketCache should always be present', bucketCache !== undefined));
this._bucketCache = bucketCache;
var routerService = owner.lookup('service:router');
(true && !(routerService !== undefined) && (0, _debug.assert)('BUG: RouterService should always be present', routerService !== undefined));
this._routerService = routerService;
}
/**
The `Router.map` function allows you to define mappings from URLs to routes
in your application. These mappings are defined within the
supplied callback function using `this.route`.
The first parameter is the name of the route which is used by default as the
path name as well.
The second parameter is the optional options hash. Available options are:
* `path`: allows you to provide your own path as well as mark dynamic
segments.
* `resetNamespace`: false by default; when nesting routes, ember will
combine the route names to form the fully-qualified route name, which is
used with `{{link-to}}` or manually transitioning to routes. Setting
`resetNamespace: true` will cause the route not to inherit from its
parent route's names. This is handy for preventing extremely long route names.
Keep in mind that the actual URL path behavior is still retained.
The third parameter is a function, which can be used to nest routes.
Nested routes, by default, will have the parent route tree's route name and
path prepended to it's own.
```app/router.js
Router.map(function(){
this.route('post', { path: '/post/:post_id' }, function() {
this.route('edit');
this.route('comments', { resetNamespace: true }, function() {
this.route('new');
});
});
});
```
@method map
@param callback
@public
*/
static map(callback) {
if (!this.dslCallbacks) {
this.dslCallbacks = []; // FIXME: Can we remove this?
this.reopenClass({
dslCallbacks: this.dslCallbacks
});
}
this.dslCallbacks.push(callback);
return this;
}
static _routePath(routeInfos) {
var path = []; // We have to handle coalescing resource names that
// are prefixed with their parent's names, e.g.
// ['foo', 'foo.bar.baz'] => 'foo.bar.baz', not 'foo.foo.bar.baz'
function intersectionMatches(a1, a2) {
for (var i = 0; i < a1.length; ++i) {
if (a1[i] !== a2[i]) {
return false;
}
}
return true;
}
var name, nameParts, oldNameParts;
for (var i = 1; i < routeInfos.length; i++) {
name = routeInfos[i].name;
nameParts = name.split('.');
oldNameParts = slice.call(path);
while (oldNameParts.length) {
if (intersectionMatches(oldNameParts, nameParts)) {
break;
}
oldNameParts.shift();
}
path.push(...nameParts.slice(oldNameParts.length));
}
return path.join('.');
}
_initRouterJs() {
var location = (0, _metal.get)(this, 'location');
var router = this;
var owner = (0, _owner.getOwner)(this);
var seen = Object.create(null);
class PrivateRouter extends _router_js.default {
getRoute(name) {
var routeName = name;
var routeOwner = owner;
var engineInfo = router._engineInfoByRoute[routeName];
if (engineInfo) {
var engineInstance = router._getEngineInstance(engineInfo);
routeOwner = engineInstance;
routeName = engineInfo.localFullName;
}
var fullRouteName = `route:${routeName}`;
var route = routeOwner.lookup(fullRouteName);
if (seen[name]) {
(true && !(route) && (0, _debug.assert)('seen routes should exist', route));
return route;
}
seen[name] = true;
if (!route) {
var DefaultRoute = routeOwner.factoryFor('route:basic').class;
routeOwner.register(fullRouteName, DefaultRoute.extend());
route = routeOwner.lookup(fullRouteName);
if (true
/* DEBUG */
) {
if (router.namespace.LOG_ACTIVE_GENERATION) {
(0, _debug.info)(`generated -> ${fullRouteName}`, {
fullName: fullRouteName
});
}
}
}
route._setRouteName(routeName);
if (engineInfo && !(0, _route.hasDefaultSerialize)(route)) {
throw new Error('Defining a custom serialize method on an Engine route is not supported.');
}
return route;
}
getSerializer(name) {
var engineInfo = router._engineInfoByRoute[name]; // If this is not an Engine route, we fall back to the handler for serialization
if (!engineInfo) {
return;
}
return engineInfo.serializeMethod || _route.defaultSerialize;
}
updateURL(path) {
(0, _runloop.once)(() => {
location.setURL(path);
(0, _metal.set)(router, 'currentURL', path);
});
} // TODO: merge into routeDidChange
didTransition(infos) {
(true && !(router.didTransition === defaultDidTransition) && (0, _debug.assert)('You attempted to override the "didTransition" method which has been deprecated. Please inject the router service and listen to the "routeDidChange" event.', router.didTransition === defaultDidTransition));
router.didTransition(infos);
} // TODO: merge into routeWillChange
willTransition(oldInfos, newInfos) {
(true && !(router.willTransition === defaultWillTransition) && (0, _debug.assert)('You attempted to override the "willTransition" method which has been deprecated. Please inject the router service and listen to the "routeWillChange" event.', router.willTransition === defaultWillTransition));
router.willTransition(oldInfos, newInfos);
}
triggerEvent(routeInfos, ignoreFailure, name, args) {
return triggerEvent.bind(router)(routeInfos, ignoreFailure, name, args);
}
routeWillChange(transition) {
router.trigger('routeWillChange', transition);
if (true
/* DEBUG */
) {
freezeRouteInfo(transition);
}
router._routerService.trigger('routeWillChange', transition); // in case of intermediate transition we update the current route
// to make router.currentRoute.name consistent with router.currentRouteName
// see https://github.com/emberjs/ember.js/issues/19449
if (transition.isIntermediate) {
router.set('currentRoute', transition.to);
}
}
routeDidChange(transition) {
router.set('currentRoute', transition.to);
(0, _runloop.once)(() => {
router.trigger('routeDidChange', transition);
if (true
/* DEBUG */
) {
freezeRouteInfo(transition);
}
router._routerService.trigger('routeDidChange', transition);
});
}
transitionDidError(error, transition) {
if (error.wasAborted || transition.isAborted) {
// If the error was a transition erorr or the transition aborted
// log the abort.
return (0, _router_js.logAbort)(transition);
} else {
// Otherwise trigger the "error" event to attempt an intermediate
// transition into an error substate
transition.trigger(false, 'error', error.error, transition, error.route);
if (router._isErrorHandled(error.error)) {
// If we handled the error with a substate just roll the state back on
// the transition and send the "routeDidChange" event for landing on
// the error substate and return the error.
transition.rollback();
this.routeDidChange(transition);
return error.error;
} else {
// If it was not handled, abort the transition completely and return
// the error.
transition.abort();
return error.error;
}
}
}
replaceURL(url) {
if (location.replaceURL) {
var doReplaceURL = () => {
location.replaceURL(url);
(0, _metal.set)(router, 'currentURL', url);
};
(0, _runloop.once)(doReplaceURL);
} else {
this.updateURL(url);
}
}
}
var routerMicrolib = this._routerMicrolib = new PrivateRouter();
var dslCallbacks = this.constructor.dslCallbacks || [K];
var dsl = this._buildDSL();
dsl.route('application', {
path: '/',
resetNamespace: true,
overrideNameAssertion: true
}, function () {
for (var i = 0; i < dslCallbacks.length; i++) {
dslCallbacks[i].call(this);
}
});
if (true
/* DEBUG */
) {
if (this.namespace.LOG_TRANSITIONS_INTERNAL) {
routerMicrolib.log = console.log.bind(console); // eslint-disable-line no-console
}
}
routerMicrolib.map(dsl.generate());
}
_buildDSL() {
var enableLoadingSubstates = this._hasModuleBasedResolver();
var router = this;
var owner = (0, _owner.getOwner)(this);
var options = {
enableLoadingSubstates,
resolveRouteMap(name) {
return owner.factoryFor(`route-map:${name}`);
},
addRouteForEngine(name, engineInfo) {
if (!router._engineInfoByRoute[name]) {
router._engineInfoByRoute[name] = engineInfo;
}
}
};
return new _dsl.default(null, options);
}
/*
Resets all pending query parameter changes.
Called after transitioning to a new route
based on query parameter changes.
*/
_resetQueuedQueryParameterChanges() {
this._queuedQPChanges = {};
}
_hasModuleBasedResolver() {
var owner = (0, _owner.getOwner)(this);
var resolver = (0, _metal.get)(owner, 'application.__registry__.resolver.moduleBasedResolver');
return Boolean(resolver);
}
/**
Initializes the current router instance and sets up the change handling
event listeners used by the instances `location` implementation.
A property named `initialURL` will be used to determine the initial URL.
If no value is found `/` will be used.
@method startRouting
@private
*/
startRouting() {
if (this.setupRouter()) {
var initialURL = (0, _metal.get)(this, 'initialURL');
if (initialURL === undefined) {
initialURL = (0, _metal.get)(this, 'location').getURL();
}
var initialTransition = this.handleURL(initialURL);
if (initialTransition && initialTransition.error) {
throw initialTransition.error;
}
}
}
setupRouter() {
if (this._didSetupRouter) {
return false;
}
this._didSetupRouter = true;
this._setupLocation();
var location = (0, _metal.get)(this, 'location'); // Allow the Location class to cancel the router setup while it refreshes
// the page
if ((0, _metal.get)(location, 'cancelRouterSetup')) {
return false;
}
this._initRouterJs();
location.onUpdateURL(url => {
this.handleURL(url);
});
return true;
}
_setOutlets() {
// This is triggered async during Route#willDestroy.
// If the router is also being destroyed we do not want to
// to create another this._toplevelView (and leak the renderer)
if (this.isDestroying || this.isDestroyed) {
return;
}
var routeInfos = this._routerMicrolib.currentRouteInfos;
if (!routeInfos) {
return;
}
var defaultParentState;
var liveRoutes = null;
for (var i = 0; i < routeInfos.length; i++) {
var route = routeInfos[i].route;
var connections = _route.ROUTE_CONNECTIONS.get(route);
var ownState = void 0;
if (connections.length === 0) {
ownState = representEmptyRoute(liveRoutes, defaultParentState, route);
} else {
for (var j = 0; j < connections.length; j++) {
var appended = appendLiveRoute(liveRoutes, defaultParentState, connections[j]);
liveRoutes = appended.liveRoutes;
var {
name,
outlet
} = appended.ownState.render;
if (name === route.routeName || outlet === 'main') {
ownState = appended.ownState;
}
}
}
defaultParentState = ownState;
} // when a transitionTo happens after the validation phase
// during the initial transition _setOutlets is called
// when no routes are active. However, it will get called
// again with the correct values during the next turn of
// the runloop
if (!liveRoutes) {
return;
}
if (!this._toplevelView) {
var owner = (0, _owner.getOwner)(this);
var OutletView = owner.factoryFor('view:-outlet');
var application = owner.lookup('application:main');
var environment = owner.lookup('-environment:main');
var template = owner.lookup('template:-outlet');
this._toplevelView = OutletView.create({
environment,
template,
application
});
this._toplevelView.setOutletState(liveRoutes);
var instance = owner.lookup('-application-instance:main');
if (instance) {
instance.didCreateRootView(this._toplevelView);
}
} else {
this._toplevelView.setOutletState(liveRoutes);
}
}
handleURL(url) {
// Until we have an ember-idiomatic way of accessing #hashes, we need to
// remove it because router.js doesn't know how to handle it.
var _url = url.split(/#(.+)?/)[0];
return this._doURLTransition('handleURL', _url);
}
_doURLTransition(routerJsMethod, url) {
this._initialTransitionStarted = true;
var transition = this._routerMicrolib[routerJsMethod](url || '/');
didBeginTransition(transition, this);
return transition;
}
/**
Transition the application into another route. The route may
be either a single route or route path:
See [transitionTo](/ember/release/classes/Route/methods/transitionTo?anchor=transitionTo) for more info.
@method transitionTo
@param {String} name the name of the route or a URL
@param {...Object} models the model(s) or identifier(s) to be used while
transitioning to the route.
@param {Object} [options] optional hash with a queryParams property
containing a mapping of query parameters
@return {Transition} the transition object associated with this
attempted transition
@public
*/
transitionTo(...args) {
if ((0, _utils.resemblesURL)(args[0])) {
(true && !(!this.isDestroying && !this.isDestroyed) && (0, _debug.assert)(`A transition was attempted from '${this.currentRouteName}' to '${args[0]}' but the application instance has already been destroyed.`, !this.isDestroying && !this.isDestroyed));
return this._doURLTransition('transitionTo', args[0]);
}
var {
routeName,
models,
queryParams
} = (0, _utils.extractRouteArgs)(args);
(true && !(!this.isDestroying && !this.isDestroyed) && (0, _debug.assert)(`A transition was attempted from '${this.currentRouteName}' to '${routeName}' but the application instance has already been destroyed.`, !this.isDestroying && !this.isDestroyed));
return this._doTransition(routeName, models, queryParams);
}
intermediateTransitionTo(name, ...args) {
this._routerMicrolib.intermediateTransitionTo(name, ...args);
updatePaths(this);
if (true
/* DEBUG */
) {
var infos = this._routerMicrolib.currentRouteInfos;
if (this.namespace.LOG_TRANSITIONS) {
// eslint-disable-next-line no-console
(true && !(infos) && (0, _debug.assert)('expected infos to be set', infos));
console.log(`Intermediate-transitioned into '${EmberRouter._routePath(infos)}'`);
}
}
}
replaceWith(...args) {
return this.transitionTo(...args).method('replace');
}
generate(name, ...args) {
var url = this._routerMicrolib.generate(name, ...args);
(true && !(typeof this.location !== 'string') && (0, _debug.assert)('expected non-string location', typeof this.location !== 'string'));
return this.location.formatURL(url);
}
/**
Determines if the supplied route is currently active.
@method isActive
@param routeName
@return {Boolean}
@private
*/
isActive(routeName) {
return this._routerMicrolib.isActive(routeName);
}
/**
An alternative form of `isActive` that doesn't require
manual concatenation of the arguments into a single
array.
@method isActiveIntent
@param routeName
@param models
@param queryParams
@return {Boolean}
@private
@since 1.7.0
*/
isActiveIntent(routeName, models, queryParams) {
return this.currentState.isActiveIntent(routeName, models, queryParams);
}
send(name, ...args) {
/*name, context*/
this._routerMicrolib.trigger(name, ...args);
}
/**
Does this router instance have the given route.
@method hasRoute
@return {Boolean}
@private
*/
hasRoute(route) {
return this._routerMicrolib.hasRoute(route);
}
/**
Resets the state of the router by clearing the current route
handlers and deactivating them.
@private
@method reset
*/
reset() {
this._didSetupRouter = false;
this._initialTransitionStarted = false;
if (this._routerMicrolib) {
this._routerMicrolib.reset();
}
}
willDestroy() {
if (this._toplevelView) {
this._toplevelView.destroy();
this._toplevelView = null;
}
super.willDestroy();
this.reset();
var instances = this._engineInstances;
for (var name in instances) {
for (var id in instances[name]) {
(0, _runloop.run)(instances[name][id], 'destroy');
}
}
}
/*
Called when an active route's query parameter has changed.
These changes are batched into a runloop run and trigger
a single transition.
*/
_activeQPChanged(queryParameterName, newValue) {
this._queuedQPChanges[queryParameterName] = newValue;
(0, _runloop.once)(this, this._fireQueryParamTransition);
}
_updatingQPChanged(queryParameterName) {
this._qpUpdates.add(queryParameterName);
}
/*
Triggers a transition to a route based on query parameter changes.
This is called once per runloop, to batch changes.
e.g.
if these methods are called in succession:
this._activeQPChanged('foo', '10');
// results in _queuedQPChanges = { foo: '10' }
this._activeQPChanged('bar', false);
// results in _queuedQPChanges = { foo: '10', bar: false }
_queuedQPChanges will represent both of these changes
and the transition using `transitionTo` will be triggered
once.
*/
_fireQueryParamTransition() {
this.transitionTo({
queryParams: this._queuedQPChanges
});
this._resetQueuedQueryParameterChanges();
}
_setupLocation() {
var location = this.location;
var rootURL = this.rootURL;
var owner = (0, _owner.getOwner)(this);
if ('string' === typeof location) {
var resolvedLocation = owner.lookup(`location:${location}`);
if (resolvedLocation !== undefined) {
location = (0, _metal.set)(this, 'location', resolvedLocation);
} else {
// Allow for deprecated registration of custom location API's
var options = {
implementation: location
};
location = (0, _metal.set)(this, 'location', _api.default.create(options));
}
}
if (location !== null && typeof location === 'object') {
if (rootURL) {
(0, _metal.set)(location, 'rootURL', rootURL);
} // Allow the location to do any feature detection, such as AutoLocation
// detecting history support. This gives it a chance to set its
// `cancelRouterSetup` property which aborts routing.
if (typeof location.detect === 'function') {
location.detect();
} // ensure that initState is called AFTER the rootURL is set on
// the location instance
if (typeof location.initState === 'function') {
location.initState();
}
}
}
/**
Serializes the given query params according to their QP meta information.
@private
@method _serializeQueryParams
@param {Arrray<RouteInfo>} routeInfos
@param {Object} queryParams
@return {Void}
*/
_serializeQueryParams(routeInfos, queryParams) {
forEachQueryParam(this, routeInfos, queryParams, (key, value, qp) => {
if (qp) {
delete queryParams[key];
queryParams[qp.urlKey] = qp.route.serializeQueryParam(value, qp.urlKey, qp.type);
} else if (value === undefined) {
return; // We don't serialize undefined values
} else {
queryParams[key] = this._serializeQueryParam(value, (0, _runtime.typeOf)(value));
}
});
}
/**
Serializes the value of a query parameter based on a type
@private
@method _serializeQueryParam
@param {Object} value
@param {String} type
*/
_serializeQueryParam(value, type) {
if (value === null || value === undefined) {
return value;
} else if (type === 'array') {
return JSON.stringify(value);
}
return `${value}`;
}
/**
Deserializes the given query params according to their QP meta information.
@private
@method _deserializeQueryParams
@param {Array<RouteInfo>} routeInfos
@param {Object} queryParams
@return {Void}
*/
_deserializeQueryParams(routeInfos, queryParams) {
forEachQueryParam(this, routeInfos, queryParams, (key, value, qp) => {
// If we don't have QP meta info for a given key, then we do nothing
// because all values will be treated as strings
if (qp) {
delete queryParams[key];
queryParams[qp.prop] = qp.route.deserializeQueryParam(value, qp.urlKey, qp.type);
}
});
}
/**
Deserializes the value of a query parameter based on a default type
@private
@method _deserializeQueryParam
@param {Object} value
@param {String} defaultType
*/
_deserializeQueryParam(value, defaultType) {
if (value === null || value === undefined) {
return value;
} else if (defaultType === 'boolean') {
return value === 'true';
} else if (defaultType === 'number') {
return Number(value).valueOf();
} else if (defaultType === 'array') {
return (0, _runtime.A)(JSON.parse(value));
}
return value;
}
/**
Removes (prunes) any query params with default values from the given QP
object. Default values are determined from the QP meta information per key.
@private
@method _pruneDefaultQueryParamValues
@param {Array<RouteInfo>} routeInfos
@param {Object} queryParams
@return {Void}
*/
_pruneDefaultQueryParamValues(routeInfos, queryParams) {
var qps = this._queryParamsFor(routeInfos);
for (var key in queryParams) {
var qp = qps.map[key];
if (qp && qp.serializedDefaultValue === queryParams[key]) {
delete queryParams[key];
}
}
}
_doTransition(_targetRouteName, models, _queryParams, _keepDefaultQueryParamValues) {
var targetRouteName = _targetRouteName || (0, _utils.getActiveTargetName)(this._routerMicrolib);
(true && !(Boolean(targetRouteName) && this._routerMicrolib.hasRoute(targetRouteName)) && (0, _debug.assert)(`The route ${targetRouteName} was not found`, Boolean(targetRouteName) && this._routerMicrolib.hasRoute(targetRouteName)));
this._initialTransitionStarted = true;
var queryParams = {};
this._processActiveTransitionQueryParams(targetRouteName, models, queryParams, _queryParams);
Object.assign(queryParams, _queryParams);
this._prepareQueryParams(targetRouteName, models, queryParams, Boolean(_keepDefaultQueryParamValues));
var transition = this._routerMicrolib.transitionTo(targetRouteName, ...models, {
queryParams
});
didBeginTransition(transition, this);
return transition;
}
_processActiveTransitionQueryParams(targetRouteName, models, queryParams, _queryParams) {
// merge in any queryParams from the active transition which could include
// queryParams from the url on initial load.
if (!this._routerMicrolib.activeTransition) {
return;
}
var unchangedQPs = {};
var qpUpdates = this._qpUpdates;
var params = (0, _route.getFullQueryParams)(this, this._routerMicrolib.activeTransition[_router_js.STATE_SYMBOL]);
for (var key in params) {
if (!qpUpdates.has(key)) {
unchangedQPs[key] = params[key];
}
} // We need to fully scope queryParams so that we can create one object
// that represents both passed-in queryParams and ones that aren't changed
// from the active transition.
this._fullyScopeQueryParams(targetRouteName, models, _queryParams);
this._fullyScopeQueryParams(targetRouteName, models, unchangedQPs);
Object.assign(queryParams, unchangedQPs);
}
/**
Prepares the query params for a URL or Transition. Restores any undefined QP
keys/values, serializes all values, and then prunes any default values.
@private
@method _prepareQueryParams
@param {String} targetRouteName
@param {Array<Object>} models
@param {Object} queryParams
@param {boolean} keepDefaultQueryParamValues
@return {Void}
*/
_prepareQueryParams(targetRouteName, models, queryParams, _fromRouterService) {
var state = calculatePostTransitionState(this, targetRouteName, models);
this._hydrateUnsuppliedQueryParams(state, queryParams, Boolean(_fromRouterService));
this._serializeQueryParams(state.routeInfos, queryParams);
if (!_fromRouterService) {
this._pruneDefaultQueryParamValues(state.routeInfos, queryParams);
}
}
/**
Returns the meta information for the query params of a given route. This
will be overridden to allow support for lazy routes.
@private
@method _getQPMeta
@param {RouteInfo} routeInfo
@return {Object}
*/
_getQPMeta(routeInfo) {
var route = routeInfo.route;
return route && (0, _metal.get)(route, '_qp');
}
/**
Returns a merged query params meta object for a given set of routeInfos.
Useful for knowing what query params are available for a given route hierarchy.
@private
@method _queryParamsFor
@param {Array<RouteInfo>} routeInfos
@return {Object}
*/
_queryParamsFor(routeInfos) {
var routeInfoLength = routeInfos.length;
var leafRouteName = routeInfos[routeInfoLength - 1].name;
var cached = this._qpCache[leafRouteName];
if (cached !== undefined) {
return cached;
}
var shouldCache = true;
var map = {};
var qps = [];
var qpsByUrlKey = true
/* DEBUG */
? {} : null;
var qpMeta;
var qp;
var urlKey;
var qpOther;
for (var i = 0; i < routeInfoLength; ++i) {
qpMeta = this._getQPMeta(routeInfos[i]);
if (!qpMeta) {
shouldCache = false;
continue;
} // Loop over each QP to make sure we don't have any collisions by urlKey
for (var _i = 0; _i < qpMeta.qps.length; _i++) {
qp = qpMeta.qps[_i];
if (true
/* DEBUG */
) {
urlKey = qp.urlKey;
qpOther = qpsByUrlKey[urlKey];
if (qpOther && qpOther.controllerName !== qp.controllerName) {
(true && !(false) && (0, _debug.assert)(`You're not allowed to have more than one controller property map to the same query param key, but both \`${qpOther.scopedPropertyName}\` and \`${qp.scopedPropertyName}\` map to \`${urlKey}\`. You can fix this by mapping one of the controller properties to a different query param key via the \`as\` config option, e.g. \`${qpOther.prop}: { as: 'other-${qpOther.prop}' }\``, false));
}
qpsByUrlKey[urlKey] = qp;
}
qps.push(qp);
}
Object.assign(map, qpMeta.map);
}
var finalQPMeta = {
qps,
map
};
if (shouldCache) {
this._qpCache[leafRouteName] = finalQPMeta;
}
return finalQPMeta;
}
/**
Maps all query param keys to their fully scoped property name of the form
`controllerName:propName`.
@private
@method _fullyScopeQueryParams
@param {String} leafRouteName
@param {Array<Object>} contexts
@param {Object} queryParams
@return {Void}
*/
_fullyScopeQueryParams(leafRouteName, contexts, queryParams) {
var state = calculatePostTransitionState(this, leafRouteName, contexts);
var routeInfos = state.routeInfos;
var qpMeta;
for (var i = 0, len = routeInfos.length; i < len; ++i) {
qpMeta = this._getQPMeta(routeInfos[i]);
if (!qpMeta) {
continue;
}
var qp = void 0;
var presentProp = void 0;
for (var j = 0, qpLen = qpMeta.qps.length; j < qpLen; ++j) {
qp = qpMeta.qps[j];
presentProp = qp.prop in queryParams && qp.prop || qp.scopedPropertyName in queryParams && qp.scopedPropertyName || qp.urlKey in queryParams && qp.urlKey;
if (presentProp) {
if (presentProp !== qp.scopedPropertyName) {
queryParams[qp.scopedPropertyName] = queryParams[presentProp];
delete queryParams[presentProp];
}
}
}
}
}
/**
Hydrates (adds/restores) any query params that have pre-existing values into
the given queryParams hash. This is what allows query params to be "sticky"
and restore their last known values for their scope.
@private
@method _hydrateUnsuppliedQueryParams
@param {TransitionState} state
@param {Object} queryParams
@return {Void}
*/
_hydrateUnsuppliedQueryParams(state, queryParams, _fromRouterService) {
var routeInfos = state.routeInfos;
var appCache = this._bucketCache;
var qpMeta;
var qp;
var presentProp;
for (var i = 0; i < routeInfos.length; ++i) {
qpMeta = this._getQPMeta(routeInfos[i]);
if (!qpMeta) {
continue;
}
for (var j = 0, qpLen = qpMeta.qps.length; j < qpLen; ++j) {
qp = qpMeta.qps[j];
presentProp = qp.prop in queryParams && qp.prop || qp.scopedPropertyName in queryParams && qp.scopedPropertyName || qp.urlKey in queryParams && qp.urlKey;
(true && !(function () {
if (qp.urlKey === presentProp || qp.scopedPropertyName === presentProp) {
return true;
}
if (_fromRouterService && presentProp !== false && qp.urlKey !== qp.prop) {
// assumptions (mainly from current transitionTo_test):
// - this is only supposed to be run when there is an alias to a query param and the alias is used to set the param
// - when there is no alias: qp.urlKey == qp.prop
return false;
}
return true;
}()) && (0, _debug.assert)(`You passed the \`${presentProp}\` query parameter during a transition into ${qp.route.routeName}, please update to ${qp.urlKey}`, function () {
if (qp.urlKey === presentProp || qp.scopedPropertyName === presentProp) {
return true;
}
if (_fromRouterService && presentProp !== false && qp.urlKey !== qp.prop) {
return false;
}
return true;
}()));
if (presentProp) {
if (presentProp !== qp.scopedPropertyName) {
queryParams[qp.scopedPropertyName] = queryParams[presentProp];
delete queryParams[presentProp];
}
} else {
var cacheKey = (0, _utils.calculateCacheKey)(qp.route.fullRouteName, qp.parts, state.params);
(true && !(appCache) && (0, _debug.assert)('ROUTER BUG: expected appCache to be defined. This is an internal bug, please open an issue on Github if you see this message!', appCache));
queryParams[qp.scopedPropertyName] = appCache.lookup(cacheKey, qp.prop, qp.defaultValue);
}
}
}
}
_scheduleLoadingEvent(transition, originRoute) {
this._cancelSlowTransitionTimer();
this._slowTransitionTimer = (0, _runloop.scheduleOnce)('routerTransitions', this, '_handleSlowTransition', transition, originRoute);
}
_handleSlowTransition(transition, originRoute) {
if (!this._routerMicrolib.activeTransition) {
// Don't fire an event if we've since moved on from
// the transition that put us in a loading state.
return;
}
var targetState = new _router_state.default(this, this._routerMicrolib, this._routerMicrolib.activeTransition[_router_js.STATE_SYMBOL]);
this.set('targetState', targetState);
transition.trigger(true, 'loading', transition, originRoute);
}
_cancelSlowTransitionTimer() {
if (this._slowTransitionTimer) {
(0, _runloop.cancel)(this._slowTransitionTimer);
}
this._slowTransitionTimer = null;
} // These three helper functions are used to ensure errors aren't
// re-raised if they're handled in a route's error action.
_markErrorAsHandled(error) {
this._handledErrors.add(error);
}
_isErrorHandled(error) {
return this._handledErrors.has(error);
}
_clearHandledError(error) {
this._handledErrors.delete(error);
}
_getEngineInstance({
name,
instanceId,
mountPoint
}) {
var engineInstances = this._engineInstances;
if (!engineInstances[name]) {
engineInstances[name] = Object.create(null);
}
var engineInstance = engineInstances[name][instanceId];
if (!engineInstance) {
var owner = (0, _owner.getOwner)(this);
(true && !(owner.hasRegistration(`engine:${name}`)) && (0, _debug.assert)(`You attempted to mount the engine '${name}' in your router map, but the engine can not be found.`, owner.hasRegistration(`engine:${name}`)));
engineInstance = owner.buildChildEngineInstance(name, {
routable: true,
mountPoint
});
engineInstance.boot();
engineInstances[name][instanceId] = engineInstance;
}
return engineInstance;
}
}
/*
Helper function for iterating over routes in a set of routeInfos that are
at or above the given origin route. Example: if `originRoute` === 'foo.bar'
and the routeInfos given were for 'foo.bar.baz', then the given callback
will be invoked with the routes for 'foo.bar', 'foo', and 'application'
individually.
If the callback returns anything other than `true`, then iteration will stop.
@private
@param {Route} originRoute
@param {Array<RouteInfo>} routeInfos
@param {Function} callback
@return {Void}
*/
function forEachRouteAbove(routeInfos, callback) {
for (var i = routeInfos.length - 1; i >= 0; --i) {
var routeInfo = routeInfos[i];
var route = routeInfo.route; // routeInfo.handler being `undefined` generally means either:
//
// 1. an error occurred during creation of the route in question
// 2. the route is across an async boundary (e.g. within an engine)
//
// In both of these cases, we cannot invoke the callback on that specific
// route, because it just doesn't exist...
if (route === undefined) {
continue;
}
if (callback(route, routeInfo) !== true) {
return;
}
}
} // These get invoked when an action bubbles above ApplicationRoute
// and are not meant to be overridable.
var defaultActionHandlers = {
willResolveModel(_routeInfos, transition, originRoute) {
this._scheduleLoadingEvent(transition, originRoute);
},
// Attempt to find an appropriate error route or substate to enter.
error(routeInfos, error, transition) {
var router = this;
var routeInfoWithError = routeInfos[routeInfos.length - 1];
forEachRouteAbove(routeInfos, (route, routeInfo) => {
// We don't check the leaf most routeInfo since that would
// technically be below where we're at in the route hierarchy.
if (routeInfo !== routeInfoWithError) {
// Check for the existence of an 'error' route.
var errorRouteName = findRouteStateName(route, 'error');
if (errorRouteName) {
router._markErrorAsHandled(error);
router.intermediateTransitionTo(errorRouteName, error);
return false;
}
} // Check for an 'error' substate route
var errorSubstateName = findRouteSubstateName(route, 'error');
if (errorSubstateName) {
router._markErrorAsHandled(error);
router.intermediateTransitionTo(errorSubstateName, error);
return false;
}
return true;
});
logError(error, `Error while processing route: ${transition.targetName}`);
},
// Attempt to find an appropriate loading route or substate to enter.
loading(routeInfos, transition) {
var router = this;
var routeInfoWithSlowLoading = routeInfos[routeInfos.length - 1];
forEachRouteAbove(routeInfos, (route, routeInfo) => {
// We don't check the leaf most routeInfos since that would
// technically be below where we're at in the route hierarchy.
if (routeInfo !== routeInfoWithSlowLoading) {
// Check for the existence of a 'loading' route.
var loadingRouteName = findRouteStateName(route, 'loading');
if (loadingRouteName) {
router.intermediateTransitionTo(loadingRouteName);
return false;
}
} // Check for loading substate
var loadingSubstateName = findRouteSubstateName(route, 'loading');
if (loadingSubstateName) {
router.intermediateTransitionTo(loadingSubstateName);
return false;
} // Don't bubble above pivot route.
return transition.pivotHandler !== route;
});
}
};
function logError(_error, initialMessage) {
var errorArgs = [];
var error;
if (_error && typeof _error === 'object' && typeof _error.errorThrown === 'object') {
error = _error.errorThrown;
} else {
error = _error;
}
if (initialMessage) {
errorArgs.push(initialMessage);
}
if (error) {
if (error.message) {
errorArgs.push(error.message);
}
if (error.stack) {
errorArgs.push(error.stack);
}
if (typeof error === 'string') {
errorArgs.push(error);
}
}
console.error(...errorArgs); //eslint-disable-line no-console
}
/**
Finds the name of the substate route if it exists for the given route. A
substate route is of the form `route_state`, such as `foo_loading`.
@private
@param {Route} route
@param {String} state
@return {String}
*/
function findRouteSubstateName(route, state) {
var owner = (0, _owner.getOwner)(route);
var {
routeName,
fullRouteName,
_router: router
} = route;
var substateName = `${routeName}_${state}`;
var substateNameFull = `${fullRouteName}_${state}`;
return routeHasBeenDefined(owner, router, substateName, substateNameFull) ? substateNameFull : '';
}
/**
Finds the name of the state route if it exists for the given route. A state
route is of the form `route.state`, such as `foo.loading`. Properly Handles
`application` named routes.
@private
@param {Route} route
@param {String} state
@return {String}
*/
function findRouteStateName(route, state) {
var owner = (0, _owner.getOwner)(route);
var {
routeName,
fullRouteName,
_router: router
} = route;
var stateName = routeName === 'application' ? state : `${routeName}.${state}`;
var stateNameFull = fullRouteName === 'application' ? state : `${fullRouteName}.${state}`;
return routeHasBeenDefined(owner, router, stateName, stateNameFull) ? stateNameFull : '';
}
/**
Determines whether or not a route has been defined by checking that the route
is in the Router's map and the owner has a registration for that route.
@private
@param {Owner} owner
@param {Router} router
@param {String} localName
@param {String} fullName
@return {Boolean}
*/
function routeHasBeenDefined(owner, router, localName, fullName) {
var routerHasRoute = router.hasRoute(fullName);
var ownerHasRoute = owner.hasRegistration(`template:${localName}`) || owner.hasRegistration(`route:${localName}`);
return routerHasRoute && ownerHasRoute;
}
function triggerEvent(routeInfos, ignoreFailure, name, args) {
if (!routeInfos) {
if (ignoreFailure) {
return;
} // TODO: update?
throw new _error2.default(`Can't trigger action '${name}' because your app hasn't finished transitioning into its first route. To trigger an action on destination routes during a transition, you can call \`.send()\` on the \`Transition\` object passed to the \`model/beforeModel/afterModel\` hooks.`);
}
var eventWasHandled = false;
var routeInfo, handler, actionHandler;
for (var i = routeInfos.length - 1; i >= 0; i--) {
routeInfo = routeInfos[i];
handler = routeInfo.route;
actionHandler = handler && handler.actions && handler.actions[name];
if (actionHandler) {
if (actionHandler.apply(handler, args) === true) {
eventWasHandled = true;
} else {
// Should only hit here if a non-bubbling error action is triggered on a route.
if (name === 'error') {
handler._router._markErrorAsHandled(args[0]);
}
return;
}
}
}
var defaultHandler = defaultActionHandlers[name];
if (defaultHandler) {
defaultHandler.apply(this, [routeInfos, ...args]);
return;
}
if (!eventWasHandled && !ignoreFailure) {
throw new _error2.default(`Nothing handled the action '${name}'. If you did handle the action, this error can be caused by returning true from an action handler in a controller, causing the action to bubble.`);
}
}
function calculatePostTransitionState(emberRouter, leafRouteName, contexts) {
var state = emberRouter._routerMicrolib.applyIntent(leafRouteName, contexts);
var {
routeInfos,
params
} = state;
for (var i = 0; i < routeInfos.length; ++i) {
var routeInfo = routeInfos[i]; // If the routeInfo is not resolved, we serialize the context into params
if (!routeInfo.isResolved) {
params[routeInfo.name] = routeInfo.serialize(routeInfo.context);
} else {
params[routeInfo.name] = routeInfo.params;
}
}
return state;
}
function updatePaths(router) {
var infos = router._routerMicrolib.currentRouteInfos;
if (infos.length === 0) {
return;
}
var path = EmberRouter._routePath(infos);
var currentRouteName = infos[infos.length - 1].name;
var location = router.location;
(true && !(typeof location !== 'string') && (0, _debug.assert)('expected location to not be a string', typeof location !== 'string'));
var currentURL = location.getURL();
(0, _metal.set)(router, 'currentPath', path);
(0, _metal.set)(router, 'currentRouteName', currentRouteName);
(0, _metal.set)(router, 'currentURL', currentURL);
var appController = (0, _owner.getOwner)(router).lookup('controller:application');
if (!appController) {
// appController might not exist when top-level loading/error
// substates have been entered since ApplicationRoute hasn't
// actually been entered at that point.
return;
}
}
function didBeginTransition(transition, router) {
var routerState = new _router_state.default(router, router._routerMicrolib, transition[_router_js.STATE_SYMBOL]);
if (!router.currentState) {
router.set('currentState', routerState);
}
router.set('targetState', routerState);
transition.promise = transition.catch(error => {
if (router._isErrorHandled(error)) {
router._clearHandledError(error);
} else {
throw error;
}
}, 'Transition Error');
}
function forEachQueryParam(router, routeInfos, queryParams, callback) {
var qpCache = router._queryParamsFor(routeInfos);
for (var key in queryParams) {
if (!Object.prototype.hasOwnProperty.call(queryParams, key)) {
continue;
}
var value = queryParams[key];
var qp = qpCache.map[key];
callback(key, value, qp);
}
}
function findLiveRoute(liveRoutes, name) {
if (!liveRoutes) {
return;
}
var stack = [liveRoutes];
while (stack.length > 0) {
var test = stack.shift();
if (test.render.name === name) {
return test;
}
var outlets = test.outlets;
for (var outletName in outlets) {
stack.push(outlets[outletName]);
}
}
return;
}
function appendLiveRoute(liveRoutes, defaultParentState, renderOptions) {
var ownState = {
render: renderOptions,
outlets: Object.create(null),
wasUsed: false
};
var target;
if (renderOptions.into) {
target = findLiveRoute(liveRoutes, renderOptions.into);
} else {
target = defaultParentState;
}
if (target) {
(0, _metal.set)(target.outlets, renderOptions.outlet, ownState);
} else {
liveRoutes = ownState;
}
return {
liveRoutes,
ownState
};
}
function representEmptyRoute(liveRoutes, defaultParentState, {
routeName
}) {
// the route didn't render anything
var alreadyAppended = findLiveRoute(liveRoutes, routeName);
if (alreadyAppended) {
// But some other route has already rendered our default
// template, so that becomes the default target for any
// children we may have.
return alreadyAppended;
} else {
// Create an entry to represent our default template name,
// just so other routes can target it and inherit its place
// in the outlet hierarchy.
defaultParentState.outlets.main = {
render: {
name: routeName,
outlet: 'main'
},
outlets: {}
};
return defaultParentState;
}
}
EmberRouter.reopen({
didTransition: defaultDidTransition,
willTransition: defaultWillTransition,
rootURL: '/',
location: 'hash',
// FIXME: Does this need to be overrideable via extend?
url: (0, _metal.computed)(function () {
var location = (0, _metal.get)(this, 'location');
if (typeof location === 'string') {
return undefined;
}
return location.getURL();
})
});
var _default = EmberRouter;
_exports.default = _default;
});
define("@ember/-internals/routing/lib/system/router_state", ["exports", "@ember/-internals/routing/lib/utils"], function (_exports, _utils) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
class RouterState {
constructor(emberRouter, router, routerJsState) {
this.emberRouter = emberRouter;
this.router = router;
this.routerJsState = routerJsState;
}
isActiveIntent(routeName, models, queryParams) {
var state = this.routerJsState;
if (!this.router.isActiveIntent(routeName, models, undefined, state)) {
return false;
}
if (queryParams !== undefined && Object.keys(queryParams).length > 0) {
var visibleQueryParams = Object.assign({}, queryParams);
this.emberRouter._prepareQueryParams(routeName, models, visibleQueryParams);
return (0, _utils.shallowEqual)(visibleQueryParams, state.queryParams);
}
return true;
}
}
_exports.default = RouterState;
});
define("@ember/-internals/routing/lib/system/transition", [], function () {
"use strict";
/**
A Transition is a thennable (a promise-like object) that represents
an attempt to transition to another route. It can be aborted, either
explicitly via `abort` or by attempting another transition while a
previous one is still underway. An aborted transition can also
be `retry()`d later.
@class Transition
@public
*/
/**
The Transition's internal promise. Calling `.then` on this property
is that same as calling `.then` on the Transition object itself, but
this property is exposed for when you want to pass around a
Transition's promise, but not the Transition object itself, since
Transition object can be externally `abort`ed, while the promise
cannot.
@property promise
@type {Object}
@public
*/
/**
Custom state can be stored on a Transition's `data` object.
This can be useful for decorating a Transition within an earlier
hook and shared with a later hook. Properties set on `data` will
be copied to new transitions generated by calling `retry` on this
transition.
@property data
@type {Object}
@public
*/
/**
A standard promise hook that resolves if the transition
succeeds and rejects if it fails/redirects/aborts.
Forwards to the internal `promise` property which you can
use in situations where you want to pass around a thennable,
but not the Transition itself.
@method then
@param {Function} onFulfilled
@param {Function} onRejected
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise}
@public
*/
/**
Forwards to the internal `promise` property which you can
use in situations where you want to pass around a thennable,
but not the Transition itself.
@method catch
@param {Function} onRejection
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise}
@public
*/
/**
Forwards to the internal `promise` property which you can
use in situations where you want to pass around a thennable,
but not the Transition itself.
@method finally
@param {Function} callback
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise}
@public
*/
/**
Aborts the Transition. Note you can also implicitly abort a transition
by initiating another transition while a previous one is underway.
@method abort
@return {Transition} this transition
@public
*/
/**
Retries a previously-aborted transition (making sure to abort the
transition if it's still active). Returns a new transition that
represents the new attempt to transition.
@method retry
@return {Transition} new transition
@public
*/
/**
Sets the URL-changing method to be employed at the end of a
successful transition. By default, a new Transition will just
use `updateURL`, but passing 'replace' to this method will
cause the URL to update using 'replaceWith' instead. Omitting
a parameter will disable the URL change, allowing for transitions
that don't update the URL at completion (this is also used for
handleURL, since the URL has already changed before the
transition took place).
@method method
@param {String} method the type of URL-changing method to use
at the end of a transition. Accepted values are 'replace',
falsy values, or any other non-falsy value (which is
interpreted as an updateURL transition).
@return {Transition} this transition
@public
*/
/**
Fires an event on the current list of resolved/resolving
handlers within this transition. Useful for firing events
on route hierarchies that haven't fully been entered yet.
Note: This method is also aliased as `send`
@method trigger
@param {Boolean} [ignoreFailure=false] a boolean specifying whether unhandled events throw an error
@param {String} name the name of the event to fire
@public
*/
/**
* This property is a `RouteInfo` object that represents
* where the router is transitioning to. It's important
* to note that a `RouteInfo` is a linked list and this
* property represents the leafmost route.
* @property {null|RouteInfo|RouteInfoWithAttributes} to
* @public
*/
/**
* This property is a `RouteInfo` object that represents
* where transition originated from. It's important
* to note that a `RouteInfo` is a linked list and this
* property represents the head node of the list.
* In the case of an initial render, `from` will be set to
* `null`.
* @property {null|RouteInfoWithAttributes} from
* @public
*/
/**
Transitions are aborted and their promises rejected
when redirects occur; this method returns a promise
that will follow any redirects that occur and fulfill
with the value fulfilled by any redirecting transitions
that occur.
@method followRedirects
@return {Promise} a promise that fulfills with the same
value that the final redirecting transition fulfills with
@public
*/
/**
In non-production builds, this function will return the stack that this Transition was
created within. In production builds, this function will not be present.
@method debugCreationStack
@return string
*/
/**
In non-production builds, this function will return the stack that this Transition was
aborted within (or `undefined` if the Transition has not been aborted yet). In production
builds, this function will not be present.
@method debugAbortStack
@return string
*/
/**
In non-production builds, this property references the Transition that _this_ Transition
was derived from or `undefined` if this transition did not derive from another. In
production builds, this property will not be present.
@property debugPreviousTransition
@type {Transition | undefined}
*/
});
define("@ember/-internals/routing/lib/utils", ["exports", "@ember/-internals/metal", "@ember/-internals/owner", "@ember/debug", "@ember/error", "router_js"], function (_exports, _metal, _owner, _debug, _error, _router_js) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.extractRouteArgs = extractRouteArgs;
_exports.getActiveTargetName = getActiveTargetName;
_exports.stashParamNames = stashParamNames;
_exports.calculateCacheKey = calculateCacheKey;
_exports.normalizeControllerQueryParams = normalizeControllerQueryParams;
_exports.resemblesURL = resemblesURL;
_exports.prefixRouteNameArg = prefixRouteNameArg;
_exports.shallowEqual = shallowEqual;
_exports.deprecateTransitionMethods = deprecateTransitionMethods;
var ALL_PERIODS_REGEX = /\./g;
function extractRouteArgs(args) {
args = args.slice();
var possibleQueryParams = args[args.length - 1];
var queryParams;
if (possibleQueryParams && Object.prototype.hasOwnProperty.call(possibleQueryParams, 'queryParams')) {
// SAFETY: this cast is safe because we have just checked whether
// `possibleQueryParams` -- defined as the last item in args -- both exists
// and has the property `queryParams`. If either of these invariants change,
// ***this is unsafe and should be changed***.
queryParams = args.pop().queryParams;
} else {
queryParams = {};
} // UNSAFE: these are simply assumed as the existing behavior of the system.
// However, this could break if upstream refactors change it, and the types
// here would not be able to tell us; we would lie to everything downstream.
var routeName = args.shift();
var models = args;
return {
routeName,
models,
queryParams
};
}
function getActiveTargetName(router) {
var routeInfos = router.activeTransition ? router.activeTransition[_router_js.STATE_SYMBOL].routeInfos : router.state.routeInfos;
return routeInfos[routeInfos.length - 1].name;
}
function stashParamNames(router, routeInfos) {
if (routeInfos['_namesStashed']) {
return;
} // This helper exists because router.js/route-recognizer.js awkwardly
// keeps separate a routeInfo's list of parameter names depending
// on whether a URL transition or named transition is happening.
// Hopefully we can remove this in the future.
var targetRouteName = routeInfos[routeInfos.length - 1].name;
var recogHandlers = router._routerMicrolib.recognizer.handlersFor(targetRouteName);
var dynamicParent;
for (var i = 0; i < routeInfos.length; ++i) {
var routeInfo = routeInfos[i];
var names = recogHandlers[i].names;
if (names.length) {
dynamicParent = routeInfo;
}
routeInfo['_names'] = names;
var route = routeInfo.route;
route._stashNames(routeInfo, dynamicParent);
}
routeInfos['_namesStashed'] = true;
}
function _calculateCacheValuePrefix(prefix, part) {
// calculates the dot separated sections from prefix that are also
// at the start of part - which gives us the route name
// given : prefix = site.article.comments, part = site.article.id
// - returns: site.article (use get(values[site.article], 'id') to get the dynamic part - used below)
// given : prefix = site.article, part = site.article.id
// - returns: site.article. (use get(values[site.article], 'id') to get the dynamic part - used below)
var prefixParts = prefix.split('.');
var currPrefix = '';
for (var i = 0; i < prefixParts.length; i++) {
var currPart = prefixParts.slice(0, i + 1).join('.');
if (part.indexOf(currPart) !== 0) {
break;
}
currPrefix = currPart;
}
return currPrefix;
}
/*
Stolen from Controller
*/
function calculateCacheKey(prefix, parts = [], values) {
var suffixes = '';
for (var i = 0; i < parts.length; ++i) {
var part = parts[i];
var cacheValuePrefix = _calculateCacheValuePrefix(prefix, part);
var value = void 0;
if (values) {
if (cacheValuePrefix && cacheValuePrefix in values) {
var partRemovedPrefix = part.indexOf(cacheValuePrefix) === 0 ? part.substr(cacheValuePrefix.length + 1) : part;
value = (0, _metal.get)(values[cacheValuePrefix], partRemovedPrefix);
} else {
value = (0, _metal.get)(values, part);
}
}
suffixes += `::${part}:${value}`;
}
return prefix + suffixes.replace(ALL_PERIODS_REGEX, '-');
}
/*
Controller-defined query parameters can come in three shapes:
Array
queryParams: ['foo', 'bar']
Array of simple objects where value is an alias
queryParams: [
{
'foo': 'rename_foo_to_this'
},
{
'bar': 'call_bar_this_instead'
}
]
Array of fully defined objects
queryParams: [
{
'foo': {
as: 'rename_foo_to_this'
},
}
{
'bar': {
as: 'call_bar_this_instead',
scope: 'controller'
}
}
]
This helper normalizes all three possible styles into the
'Array of fully defined objects' style.
*/
function normalizeControllerQueryParams(queryParams) {
var qpMap = {};
for (var i = 0; i < queryParams.length; ++i) {
accumulateQueryParamDescriptors(queryParams[i], qpMap);
}
return qpMap;
}
function accumulateQueryParamDescriptors(_desc, accum) {
var desc = _desc;
var tmp;
if (typeof desc === 'string') {
tmp = {};
tmp[desc] = {
as: null
};
desc = tmp;
}
for (var key in desc) {
if (!Object.prototype.hasOwnProperty.call(desc, key)) {
return;
}
var singleDesc = desc[key];
if (typeof singleDesc === 'string') {
singleDesc = {
as: singleDesc
};
}
tmp = accum[key] || {
as: null,
scope: 'model'
};
Object.assign(tmp, singleDesc);
accum[key] = tmp;
}
}
/*
Check if a routeName resembles a url instead
@private
*/
function resemblesURL(str) {
return typeof str === 'string' && (str === '' || str[0] === '/');
}
/*
Returns an arguments array where the route name arg is prefixed based on the mount point
@private
*/
function prefixRouteNameArg(route, args) {
var routeName = args[0];
var owner = (0, _owner.getOwner)(route);
var prefix = owner.mountPoint; // only alter the routeName if it's actually referencing a route.
if (owner.routable && typeof routeName === 'string') {
if (resemblesURL(routeName)) {
throw new _error.default('Programmatic transitions by URL cannot be used within an Engine. Please use the route name instead.');
} else {
routeName = `${prefix}.${routeName}`;
args[0] = routeName;
}
}
return args;
}
function shallowEqual(a, b) {
var k;
var aCount = 0;
var bCount = 0;
for (k in a) {
if (Object.prototype.hasOwnProperty.call(a, k)) {
if (a[k] !== b[k]) {
return false;
}
aCount++;
}
}
for (k in b) {
if (Object.prototype.hasOwnProperty.call(b, k)) {
bCount++;
}
}
return aCount === bCount;
}
function deprecateTransitionMethods(frameworkClass, methodName) {
(true && !(false) && (0, _debug.deprecate)(`Calling ${methodName} on a ${frameworkClass} is deprecated. Use the RouterService instead.`, false, {
id: 'routing.transition-methods',
for: 'ember-source',
since: {
enabled: '3.26.0'
},
until: '5.0.0',
url: 'https://deprecations.emberjs.com/v3.x/#toc_routing-transition-methods'
}));
}
});
define("@ember/-internals/runtime/index", ["exports", "@ember/-internals/runtime/lib/system/object", "@ember/-internals/runtime/lib/mixins/registry_proxy", "@ember/-internals/runtime/lib/mixins/container_proxy", "@ember/-internals/runtime/lib/compare", "@ember/-internals/runtime/lib/is-equal", "@ember/-internals/runtime/lib/mixins/array", "@ember/-internals/runtime/lib/mixins/comparable", "@ember/-internals/runtime/lib/system/namespace", "@ember/-internals/runtime/lib/system/array_proxy", "@ember/-internals/runtime/lib/system/object_proxy", "@ember/-internals/runtime/lib/system/core_object", "@ember/-internals/runtime/lib/mixins/action_handler", "@ember/-internals/runtime/lib/mixins/enumerable", "@ember/-internals/runtime/lib/mixins/-proxy", "@ember/-internals/runtime/lib/mixins/observable", "@ember/-internals/runtime/lib/mixins/mutable_enumerable", "@ember/-internals/runtime/lib/mixins/target_action_support", "@ember/-internals/runtime/lib/mixins/evented", "@ember/-internals/runtime/lib/mixins/promise_proxy", "@ember/-internals/runtime/lib/ext/rsvp", "@ember/-internals/runtime/lib/type-of"], function (_exports, _object, _registry_proxy, _container_proxy, _compare, _isEqual, _array, _comparable, _namespace, _array_proxy, _object_proxy, _core_object, _action_handler, _enumerable, _proxy, _observable, _mutable_enumerable, _target_action_support, _evented, _promise_proxy, _rsvp, _typeOf) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "Object", {
enumerable: true,
get: function () {
return _object.default;
}
});
Object.defineProperty(_exports, "FrameworkObject", {
enumerable: true,
get: function () {
return _object.FrameworkObject;
}
});
Object.defineProperty(_exports, "RegistryProxyMixin", {
enumerable: true,
get: function () {
return _registry_proxy.default;
}
});
Object.defineProperty(_exports, "ContainerProxyMixin", {
enumerable: true,
get: function () {
return _container_proxy.default;
}
});
Object.defineProperty(_exports, "compare", {
enumerable: true,
get: function () {
return _compare.default;
}
});
Object.defineProperty(_exports, "isEqual", {
enumerable: true,
get: function () {
return _isEqual.default;
}
});
Object.defineProperty(_exports, "Array", {
enumerable: true,
get: function () {
return _array.default;
}
});
Object.defineProperty(_exports, "NativeArray", {
enumerable: true,
get: function () {
return _array.NativeArray;
}
});
Object.defineProperty(_exports, "A", {
enumerable: true,
get: function () {
return _array.A;
}
});
Object.defineProperty(_exports, "MutableArray", {
enumerable: true,
get: function () {
return _array.MutableArray;
}
});
Object.defineProperty(_exports, "removeAt", {
enumerable: true,
get: function () {
return _array.removeAt;
}
});
Object.defineProperty(_exports, "uniqBy", {
enumerable: true,
get: function () {
return _array.uniqBy;
}
});
Object.defineProperty(_exports, "isArray", {
enumerable: true,
get: function () {
return _array.isArray;
}
});
Object.defineProperty(_exports, "Comparable", {
enumerable: true,
get: function () {
return _comparable.default;
}
});
Object.defineProperty(_exports, "Namespace", {
enumerable: true,
get: function () {
return _namespace.default;
}
});
Object.defineProperty(_exports, "ArrayProxy", {
enumerable: true,
get: function () {
return _array_proxy.default;
}
});
Object.defineProperty(_exports, "ObjectProxy", {
enumerable: true,
get: function () {
return _object_proxy.default;
}
});
Object.defineProperty(_exports, "CoreObject", {
enumerable: true,
get: function () {
return _core_object.default;
}
});
Object.defineProperty(_exports, "ActionHandler", {
enumerable: true,
get: function () {
return _action_handler.default;
}
});
Object.defineProperty(_exports, "Enumerable", {
enumerable: true,
get: function () {
return _enumerable.default;
}
});
Object.defineProperty(_exports, "_ProxyMixin", {
enumerable: true,
get: function () {
return _proxy.default;
}
});
Object.defineProperty(_exports, "_contentFor", {
enumerable: true,
get: function () {
return _proxy.contentFor;
}
});
Object.defineProperty(_exports, "Observable", {
enumerable: true,
get: function () {
return _observable.default;
}
});
Object.defineProperty(_exports, "MutableEnumerable", {
enumerable: true,
get: function () {
return _mutable_enumerable.default;
}
});
Object.defineProperty(_exports, "TargetActionSupport", {
enumerable: true,
get: function () {
return _target_action_support.default;
}
});
Object.defineProperty(_exports, "Evented", {
enumerable: true,
get: function () {
return _evented.default;
}
});
Object.defineProperty(_exports, "PromiseProxyMixin", {
enumerable: true,
get: function () {
return _promise_proxy.default;
}
});
Object.defineProperty(_exports, "RSVP", {
enumerable: true,
get: function () {
return _rsvp.default;
}
});
Object.defineProperty(_exports, "onerrorDefault", {
enumerable: true,
get: function () {
return _rsvp.onerrorDefault;
}
});
Object.defineProperty(_exports, "typeOf", {
enumerable: true,
get: function () {
return _typeOf.typeOf;
}
});
});
define("@ember/-internals/runtime/lib/compare", ["exports", "@ember/-internals/runtime/lib/type-of", "@ember/-internals/runtime/lib/mixins/comparable"], function (_exports, _typeOf, _comparable) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = compare;
var TYPE_ORDER = {
undefined: 0,
null: 1,
boolean: 2,
number: 3,
string: 4,
array: 5,
object: 6,
instance: 7,
function: 8,
class: 9,
date: 10
}; //
// the spaceship operator
//
// `. ___
// __,' __`. _..----....____
// __...--.'``;. ,. ;``--..__ .' ,-._ _.-'
// _..-''-------' `' `' `' O ``-''._ (,;') _,'
// ,'________________ \`-._`-','
// `._ ```````````------...___ '-.._'-:
// ```--.._ ,. ````--...__\-.
// `.--. `-` "INFINITY IS LESS ____ | |`
// `. `. THAN BEYOND" ,'`````. ; ;`
// `._`. __________ `. \'__/`
// `-:._____/______/___/____`. \ `
// | `._ `. \
// `._________`-. `. `.___
// SSt `------'`
function spaceship(a, b) {
var diff = a - b;
return (diff > 0) - (diff < 0);
}
/**
@module @ember/utils
*/
/**
Compares two javascript values and returns:
- -1 if the first is smaller than the second,
- 0 if both are equal,
- 1 if the first is greater than the second.
```javascript
import { compare } from '@ember/utils';
compare('hello', 'hello'); // 0
compare('abc', 'dfg'); // -1
compare(2, 1); // 1
```
If the types of the two objects are different precedence occurs in the
following order, with types earlier in the list considered `<` types
later in the list:
- undefined
- null
- boolean
- number
- string
- array
- object
- instance
- function
- class
- date
```javascript
import { compare } from '@ember/utils';
compare('hello', 50); // 1
compare(50, 'hello'); // -1
```
@method compare
@for @ember/utils
@static
@param {Object} v First value to compare
@param {Object} w Second value to compare
@return {Number} -1 if v < w, 0 if v = w and 1 if v > w.
@public
*/
function compare(v, w) {
if (v === w) {
return 0;
}
var type1 = (0, _typeOf.typeOf)(v);
var type2 = (0, _typeOf.typeOf)(w);
if (type1 === 'instance' && _comparable.default.detect(v) && v.constructor.compare) {
return v.constructor.compare(v, w);
}
if (type2 === 'instance' && _comparable.default.detect(w) && w.constructor.compare) {
return w.constructor.compare(w, v) * -1;
}
var res = spaceship(TYPE_ORDER[type1], TYPE_ORDER[type2]);
if (res !== 0) {
return res;
} // types are equal - so we have to check values now
switch (type1) {
case 'boolean':
case 'number':
return spaceship(v, w);
case 'string':
return spaceship(v.localeCompare(w), 0);
case 'array':
{
var vLen = v.length;
var wLen = w.length;
var len = Math.min(vLen, wLen);
for (var i = 0; i < len; i++) {
var r = compare(v[i], w[i]);
if (r !== 0) {
return r;
}
} // all elements are equal now
// shorter array should be ordered first
return spaceship(vLen, wLen);
}
case 'instance':
if (_comparable.default.detect(v)) {
return v.compare(v, w);
}
return 0;
case 'date':
return spaceship(v.getTime(), w.getTime());
default:
return 0;
}
}
});
define("@ember/-internals/runtime/lib/ext/rsvp", ["exports", "rsvp", "@ember/runloop", "@ember/-internals/error-handling", "@ember/debug"], function (_exports, RSVP, _runloop, _errorHandling, _debug) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.onerrorDefault = onerrorDefault;
_exports.default = void 0;
RSVP.configure('async', (callback, promise) => {
_runloop._backburner.schedule('actions', null, callback, promise);
});
RSVP.configure('after', cb => {
_runloop._backburner.schedule(_runloop._rsvpErrorQueue, null, cb);
});
RSVP.on('error', onerrorDefault);
function onerrorDefault(reason) {
var error = errorFor(reason);
if (error) {
var overrideDispatch = (0, _errorHandling.getDispatchOverride)();
if (overrideDispatch) {
overrideDispatch(error);
} else {
throw error;
}
}
}
function errorFor(reason) {
if (!reason) return;
if (reason.errorThrown) {
return unwrapErrorThrown(reason);
}
if (reason.name === 'UnrecognizedURLError') {
(true && !(false) && (0, _debug.assert)(`The URL '${reason.message}' did not match any routes in your application`, false));
return;
}
if (reason.name === 'TransitionAborted') {
return;
}
return reason;
}
function unwrapErrorThrown(reason) {
var error = reason.errorThrown;
if (typeof error === 'string') {
error = new Error(error);
}
Object.defineProperty(error, '__reason_with_error_thrown__', {
value: reason,
enumerable: false
});
return error;
}
var _default = RSVP;
_exports.default = _default;
});
define("@ember/-internals/runtime/lib/is-equal", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = isEqual;
/**
@module @ember/utils
*/
/**
Compares two objects, returning true if they are equal.
```javascript
import { isEqual } from '@ember/utils';
isEqual('hello', 'hello'); // true
isEqual(1, 2); // false
```
`isEqual` is a more specific comparison than a triple equal comparison.
It will call the `isEqual` instance method on the objects being
compared, allowing finer control over when objects should be considered
equal to each other.
```javascript
import { isEqual } from '@ember/utils';
import EmberObject from '@ember/object';
let Person = EmberObject.extend({
isEqual(other) { return this.ssn == other.ssn; }
});
let personA = Person.create({name: 'Muhammad Ali', ssn: '123-45-6789'});
let personB = Person.create({name: 'Cassius Clay', ssn: '123-45-6789'});
isEqual(personA, personB); // true
```
Due to the expense of array comparisons, collections will never be equal to
each other even if each of their items are equal to each other.
```javascript
import { isEqual } from '@ember/utils';
isEqual([4, 2], [4, 2]); // false
```
@method isEqual
@for @ember/utils
@static
@param {Object} a first object to compare
@param {Object} b second object to compare
@return {Boolean}
@public
*/
function isEqual(a, b) {
if (a && typeof a.isEqual === 'function') {
return a.isEqual(b);
}
if (a instanceof Date && b instanceof Date) {
return a.getTime() === b.getTime();
}
return a === b;
}
});
define("@ember/-internals/runtime/lib/mixins/-proxy", ["exports", "@ember/-internals/meta", "@ember/-internals/metal", "@ember/-internals/utils", "@ember/debug", "@glimmer/manager", "@glimmer/validator"], function (_exports, _meta, _metal, _utils, _debug, _manager, _validator) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.contentFor = contentFor;
_exports.default = void 0;
/**
@module ember
*/
function contentFor(proxy) {
var content = (0, _metal.get)(proxy, 'content');
(0, _validator.updateTag)((0, _metal.tagForObject)(proxy), (0, _metal.tagForObject)(content));
return content;
}
function customTagForProxy(proxy, key, addMandatorySetter) {
var meta = (0, _validator.tagMetaFor)(proxy);
var tag = (0, _validator.tagFor)(proxy, key, meta);
if (true
/* DEBUG */
) {
// TODO: Replace this with something more first class for tracking tags in DEBUG
tag._propertyKey = key;
}
if (key in proxy) {
if (true
/* DEBUG */
&& addMandatorySetter) {
(0, _utils.setupMandatorySetter)(tag, proxy, key);
}
return tag;
} else {
var tags = [tag, (0, _validator.tagFor)(proxy, 'content', meta)];
var content = contentFor(proxy);
if ((0, _utils.isObject)(content)) {
tags.push((0, _metal.tagForProperty)(content, key, addMandatorySetter));
}
return (0, _validator.combine)(tags);
}
}
/**
`Ember.ProxyMixin` forwards all properties not defined by the proxy itself
to a proxied `content` object. See ObjectProxy for more details.
@class ProxyMixin
@namespace Ember
@private
*/
var _default = _metal.Mixin.create({
/**
The object whose properties will be forwarded.
@property content
@type {unknown}
@default null
@public
*/
content: null,
init() {
this._super(...arguments);
(0, _utils.setProxy)(this);
(0, _metal.tagForObject)(this);
(0, _manager.setCustomTagFor)(this, customTagForProxy);
},
willDestroy() {
this.set('content', null);
this._super(...arguments);
},
isTruthy: (0, _metal.computed)('content', function () {
return Boolean((0, _metal.get)(this, 'content'));
}),
unknownProperty(key) {
var content = contentFor(this);
if (content) {
return (0, _metal.get)(content, key);
}
},
setUnknownProperty(key, value) {
var m = (0, _meta.meta)(this);
if (m.isInitializing() || m.isPrototypeMeta(this)) {
// if marked as prototype or object is initializing then just
// defineProperty rather than delegate
(0, _metal.defineProperty)(this, key, null, value);
return value;
}
var content = contentFor(this);
(true && !(content) && (0, _debug.assert)(`Cannot delegate set('${key}', ${value}) to the 'content' property of object proxy ${this}: its 'content' is undefined.`, content));
return (0, _metal.set)(content, key, value);
}
});
_exports.default = _default;
});
define("@ember/-internals/runtime/lib/mixins/action_handler", ["exports", "@ember/-internals/metal", "@ember/debug"], function (_exports, _metal, _debug) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module ember
*/
/**
`Ember.ActionHandler` is available on some familiar classes including
`Route`, `Component`, and `Controller`.
(Internally the mixin is used by `Ember.CoreView`, `Ember.ControllerMixin`,
and `Route` and available to the above classes through
inheritance.)
@class ActionHandler
@namespace Ember
@private
*/
var ActionHandler = _metal.Mixin.create({
mergedProperties: ['actions'],
/**
The collection of functions, keyed by name, available on this
`ActionHandler` as action targets.
These functions will be invoked when a matching `{{action}}` is triggered
from within a template and the application's current route is this route.
Actions can also be invoked from other parts of your application
via `ActionHandler#send`.
The `actions` hash will inherit action handlers from
the `actions` hash defined on extended parent classes
or mixins rather than just replace the entire hash, e.g.:
```app/mixins/can-display-banner.js
import Mixin from '@ember/mixin';
export default Mixin.create({
actions: {
displayBanner(msg) {
// ...
}
}
});
```
```app/routes/welcome.js
import Route from '@ember/routing/route';
import CanDisplayBanner from '../mixins/can-display-banner';
export default Route.extend(CanDisplayBanner, {
actions: {
playMusic() {
// ...
}
}
});
// `WelcomeRoute`, when active, will be able to respond
// to both actions, since the actions hash is merged rather
// then replaced when extending mixins / parent classes.
this.send('displayBanner');
this.send('playMusic');
```
Within a Controller, Route or Component's action handler,
the value of the `this` context is the Controller, Route or
Component object:
```app/routes/song.js
import Route from '@ember/routing/route';
export default Route.extend({
actions: {
myAction() {
this.controllerFor("song");
this.transitionTo("other.route");
...
}
}
});
```
It is also possible to call `this._super(...arguments)` from within an
action handler if it overrides a handler defined on a parent
class or mixin:
Take for example the following routes:
```app/mixins/debug-route.js
import Mixin from '@ember/mixin';
export default Mixin.create({
actions: {
debugRouteInformation() {
console.debug("It's a-me, console.debug!");
}
}
});
```
```app/routes/annoying-debug.js
import Route from '@ember/routing/route';
import DebugRoute from '../mixins/debug-route';
export default Route.extend(DebugRoute, {
actions: {
debugRouteInformation() {
// also call the debugRouteInformation of mixed in DebugRoute
this._super(...arguments);
// show additional annoyance
window.alert(...);
}
}
});
```
## Bubbling
By default, an action will stop bubbling once a handler defined
on the `actions` hash handles it. To continue bubbling the action,
you must return `true` from the handler:
```app/router.js
Router.map(function() {
this.route("album", function() {
this.route("song");
});
});
```
```app/routes/album.js
import Route from '@ember/routing/route';
export default Route.extend({
actions: {
startPlaying: function() {
}
}
});
```
```app/routes/album-song.js
import Route from '@ember/routing/route';
export default Route.extend({
actions: {
startPlaying() {
// ...
if (actionShouldAlsoBeTriggeredOnParentRoute) {
return true;
}
}
}
});
```
@property actions
@type Object
@default null
@public
*/
/**
Triggers a named action on the `ActionHandler`. Any parameters
supplied after the `actionName` string will be passed as arguments
to the action target function.
If the `ActionHandler` has its `target` property set, actions may
bubble to the `target`. Bubbling happens when an `actionName` can
not be found in the `ActionHandler`'s `actions` hash or if the
action target function returns `true`.
Example
```app/routes/welcome.js
import Route from '@ember/routing/route';
export default Route.extend({
actions: {
playTheme() {
this.send('playMusic', 'theme.mp3');
},
playMusic(track) {
// ...
}
}
});
```
@method send
@param {String} actionName The action to trigger
@param {*} context a context to send with the action
@public
*/
send(actionName, ...args) {
(true && !(!this.isDestroying && !this.isDestroyed) && (0, _debug.assert)(`Attempted to call .send() with the action '${actionName}' on the destroyed object '${this}'.`, !this.isDestroying && !this.isDestroyed));
if (this.actions && this.actions[actionName]) {
var shouldBubble = this.actions[actionName].apply(this, args) === true;
if (!shouldBubble) {
return;
}
}
var target = (0, _metal.get)(this, 'target');
if (target) {
(true && !(typeof target.send === 'function') && (0, _debug.assert)(`The \`target\` for ${this} (${target}) does not have a \`send\` method`, typeof target.send === 'function'));
target.send(...arguments);
}
}
});
var _default = ActionHandler;
_exports.default = _default;
});
define("@ember/-internals/runtime/lib/mixins/array", ["exports", "@ember/-internals/metal", "@ember/-internals/utils", "@ember/debug", "@ember/-internals/runtime/lib/mixins/enumerable", "@ember/-internals/runtime/lib/compare", "@ember/-internals/environment", "@ember/-internals/runtime/lib/mixins/observable", "@ember/-internals/runtime/lib/mixins/mutable_enumerable", "@ember/-internals/runtime/lib/type-of"], function (_exports, _metal, _utils, _debug, _enumerable, _compare, _environment, _observable, _mutable_enumerable, _typeOf) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.uniqBy = uniqBy;
_exports.removeAt = removeAt;
_exports.isArray = isArray;
_exports.default = _exports.MutableArray = _exports.NativeArray = _exports.A = void 0;
/**
@module @ember/array
*/
var EMPTY_ARRAY = Object.freeze([]);
var identityFunction = item => item;
function uniqBy(array, key = identityFunction) {
(true && !(isArray(array)) && (0, _debug.assert)(`first argument passed to \`uniqBy\` should be array`, isArray(array)));
var ret = A();
var seen = new Set();
var getter = typeof key === 'function' ? key : item => (0, _metal.get)(item, key);
array.forEach(item => {
var val = getter(item);
if (!seen.has(val)) {
seen.add(val);
ret.push(item);
}
});
return ret;
}
function iter(key, value) {
var valueProvided = arguments.length === 2;
return valueProvided ? item => value === (0, _metal.get)(item, key) : item => Boolean((0, _metal.get)(item, key));
}
function findIndex(array, predicate, startAt) {
var len = array.length;
for (var index = startAt; index < len; index++) {
var item = (0, _metal.objectAt)(array, index);
if (predicate(item, index, array)) {
return index;
}
}
return -1;
}
function find(array, callback, target) {
var predicate = callback.bind(target);
var index = findIndex(array, predicate, 0);
return index === -1 ? undefined : (0, _metal.objectAt)(array, index);
}
function any(array, callback, target) {
var predicate = callback.bind(target);
return findIndex(array, predicate, 0) !== -1;
}
function every(array, callback, target) {
var cb = callback.bind(target);
var predicate = (item, index, array) => !cb(item, index, array);
return findIndex(array, predicate, 0) === -1;
}
function indexOf(array, val, startAt = 0, withNaNCheck) {
var len = array.length;
if (startAt < 0) {
startAt += len;
} // SameValueZero comparison (NaN !== NaN)
var predicate = withNaNCheck && val !== val ? item => item !== item : item => item === val;
return findIndex(array, predicate, startAt);
}
function removeAt(array, index, len = 1) {
(true && !(index > -1 && index < array.length) && (0, _debug.assert)(`\`removeAt\` index provided is out of range`, index > -1 && index < array.length));
(0, _metal.replace)(array, index, len, EMPTY_ARRAY);
return array;
}
function insertAt(array, index, item) {
(true && !(index > -1 && index <= array.length) && (0, _debug.assert)(`\`insertAt\` index provided is out of range`, index > -1 && index <= array.length));
(0, _metal.replace)(array, index, 0, [item]);
return item;
}
/**
Returns true if the passed object is an array or Array-like.
Objects are considered Array-like if any of the following are true:
- the object is a native Array
- the object has an objectAt property
- the object is an Object, and has a length property
Unlike `typeOf` this method returns true even if the passed object is
not formally an array but appears to be array-like (i.e. implements `Array`)
```javascript
import { isArray } from '@ember/array';
import ArrayProxy from '@ember/array/proxy';
isArray(); // false
isArray([]); // true
isArray(ArrayProxy.create({ content: [] })); // true
```
@method isArray
@static
@for @ember/array
@param {Object} obj The object to test
@return {Boolean} true if the passed object is an array or Array-like
@public
*/
function isArray(_obj) {
var obj = _obj;
if (true
/* DEBUG */
&& typeof _obj === 'object' && _obj !== null) {
var possibleProxyContent = _obj[_metal.PROXY_CONTENT];
if (possibleProxyContent !== undefined) {
obj = possibleProxyContent;
}
}
if (!obj || obj.setInterval) {
return false;
}
if (Array.isArray(obj) || ArrayMixin.detect(obj)) {
return true;
}
var type = (0, _typeOf.typeOf)(obj);
if ('array' === type) {
return true;
}
var length = obj.length;
if (typeof length === 'number' && length === length && 'object' === type) {
return true;
}
return false;
}
/*
This allows us to define computed properties that are not enumerable.
The primary reason this is important is that when `NativeArray` is
applied to `Array.prototype` we need to ensure that we do not add _any_
new enumerable properties.
*/
function nonEnumerableComputed() {
var property = (0, _metal.computed)(...arguments);
property.enumerable = false;
return property;
}
function mapBy(key) {
return this.map(next => (0, _metal.get)(next, key));
} // ..........................................................
// ARRAY
//
/**
This mixin implements Observer-friendly Array-like behavior. It is not a
concrete implementation, but it can be used up by other classes that want
to appear like arrays.
For example, ArrayProxy is a concrete class that can be instantiated to
implement array-like behavior. This class uses the Array Mixin by way of
the MutableArray mixin, which allows observable changes to be made to the
underlying array.
This mixin defines methods specifically for collections that provide
index-ordered access to their contents. When you are designing code that
needs to accept any kind of Array-like object, you should use these methods
instead of Array primitives because these will properly notify observers of
changes to the array.
Although these methods are efficient, they do add a layer of indirection to
your application so it is a good idea to use them only when you need the
flexibility of using both true JavaScript arrays and "virtual" arrays such
as controllers and collections.
You can use the methods defined in this module to access and modify array
contents in an observable-friendly way. You can also be notified whenever
the membership of an array changes by using `.observes('myArray.[]')`.
To support `EmberArray` in your own class, you must override two
primitives to use it: `length()` and `objectAt()`.
@class EmberArray
@uses Enumerable
@since Ember 0.9.0
@public
*/
var ArrayMixin = _metal.Mixin.create(_enumerable.default, {
init() {
this._super(...arguments);
(0, _utils.setEmberArray)(this);
},
/**
__Required.__ You must implement this method to apply this mixin.
Your array must support the `length` property. Your replace methods should
set this property whenever it changes.
@property {Number} length
@public
*/
/**
Returns the object at the given `index`. If the given `index` is negative
or is greater or equal than the array length, returns `undefined`.
This is one of the primitives you must implement to support `EmberArray`.
If your object supports retrieving the value of an array item using `get()`
(i.e. `myArray.get(0)`), then you do not need to implement this method
yourself.
```javascript
let arr = ['a', 'b', 'c', 'd'];
arr.objectAt(0); // 'a'
arr.objectAt(3); // 'd'
arr.objectAt(-1); // undefined
arr.objectAt(4); // undefined
arr.objectAt(5); // undefined
```
@method objectAt
@param {Number} idx The index of the item to return.
@return {*} item at index or undefined
@public
*/
/**
This returns the objects at the specified indexes, using `objectAt`.
```javascript
let arr = ['a', 'b', 'c', 'd'];
arr.objectsAt([0, 1, 2]); // ['a', 'b', 'c']
arr.objectsAt([2, 3, 4]); // ['c', 'd', undefined]
```
@method objectsAt
@param {Array} indexes An array of indexes of items to return.
@return {Array}
@public
*/
objectsAt(indexes) {
return indexes.map(idx => (0, _metal.objectAt)(this, idx));
},
/**
This is the handler for the special array content property. If you get
this property, it will return this. If you set this property to a new
array, it will replace the current content.
```javascript
let peopleToMoon = ['Armstrong', 'Aldrin'];
peopleToMoon.get('[]'); // ['Armstrong', 'Aldrin']
peopleToMoon.set('[]', ['Collins']); // ['Collins']
peopleToMoon.get('[]'); // ['Collins']
```
@property []
@return this
@public
*/
'[]': nonEnumerableComputed({
get() {
return this;
},
set(key, value) {
this.replace(0, this.length, value);
return this;
}
}),
/**
The first object in the array, or `undefined` if the array is empty.
```javascript
let vowels = ['a', 'e', 'i', 'o', 'u'];
vowels.firstObject; // 'a'
vowels.shiftObject();
vowels.firstObject; // 'e'
vowels.reverseObjects();
vowels.firstObject; // 'u'
vowels.clear();
vowels.firstObject; // undefined
```
@property firstObject
@return {Object | undefined} The first object in the array
@public
*/
firstObject: nonEnumerableComputed(function () {
return (0, _metal.objectAt)(this, 0);
}).readOnly(),
/**
The last object in the array, or `undefined` if the array is empty.
@property lastObject
@return {Object | undefined} The last object in the array
@public
*/
lastObject: nonEnumerableComputed(function () {
return (0, _metal.objectAt)(this, this.length - 1);
}).readOnly(),
// Add any extra methods to EmberArray that are native to the built-in Array.
/**
Returns a new array that is a slice of the receiver. This implementation
uses the observable array methods to retrieve the objects for the new
slice.
```javascript
let arr = ['red', 'green', 'blue'];
arr.slice(0); // ['red', 'green', 'blue']
arr.slice(0, 2); // ['red', 'green']
arr.slice(1, 100); // ['green', 'blue']
```
@method slice
@param {Number} beginIndex (Optional) index to begin slicing from.
@param {Number} endIndex (Optional) index to end the slice at (but not included).
@return {Array} New array with specified slice
@public
*/
slice(beginIndex = 0, endIndex) {
var ret = A();
var length = this.length;
if (beginIndex < 0) {
beginIndex = length + beginIndex;
}
if (endIndex === undefined || endIndex > length) {
endIndex = length;
} else if (endIndex < 0) {
endIndex = length + endIndex;
}
while (beginIndex < endIndex) {
ret[ret.length] = (0, _metal.objectAt)(this, beginIndex++);
}
return ret;
},
/**
Used to determine the passed object's first occurrence in the array.
Returns the index if found, -1 if no match is found.
The optional `startAt` argument can be used to pass a starting
index to search from, effectively slicing the searchable portion
of the array. If it's negative it will add the array length to
the startAt value passed in as the index to search from. If less
than or equal to `-1 * array.length` the entire array is searched.
```javascript
let arr = ['a', 'b', 'c', 'd', 'a'];
arr.indexOf('a'); // 0
arr.indexOf('z'); // -1
arr.indexOf('a', 2); // 4
arr.indexOf('a', -1); // 4, equivalent to indexOf('a', 4)
arr.indexOf('a', -100); // 0, searches entire array
arr.indexOf('b', 3); // -1
arr.indexOf('a', 100); // -1
let people = [{ name: 'Zoey' }, { name: 'Bob' }]
let newPerson = { name: 'Tom' };
people = [newPerson, ...people, newPerson];
people.indexOf(newPerson); // 0
people.indexOf(newPerson, 1); // 3
people.indexOf(newPerson, -4); // 0
people.indexOf(newPerson, 10); // -1
```
@method indexOf
@param {Object} object the item to search for
@param {Number} startAt optional starting location to search, default 0
@return {Number} index or -1 if not found
@public
*/
indexOf(object, startAt) {
return indexOf(this, object, startAt, false);
},
/**
Returns the index of the given `object`'s last occurrence.
- If no `startAt` argument is given, the search starts from
the last position.
- If it's greater than or equal to the length of the array,
the search starts from the last position.
- If it's negative, it is taken as the offset from the end
of the array i.e. `startAt + array.length`.
- If it's any other positive number, will search backwards
from that index of the array.
Returns -1 if no match is found.
```javascript
let arr = ['a', 'b', 'c', 'd', 'a'];
arr.lastIndexOf('a'); // 4
arr.lastIndexOf('z'); // -1
arr.lastIndexOf('a', 2); // 0
arr.lastIndexOf('a', -1); // 4
arr.lastIndexOf('a', -3); // 0
arr.lastIndexOf('b', 3); // 1
arr.lastIndexOf('a', 100); // 4
```
@method lastIndexOf
@param {Object} object the item to search for
@param {Number} startAt optional starting location to search from
backwards, defaults to `(array.length - 1)`
@return {Number} The last index of the `object` in the array or -1
if not found
@public
*/
lastIndexOf(object, startAt) {
var len = this.length;
if (startAt === undefined || startAt >= len) {
startAt = len - 1;
}
if (startAt < 0) {
startAt += len;
}
for (var idx = startAt; idx >= 0; idx--) {
if ((0, _metal.objectAt)(this, idx) === object) {
return idx;
}
}
return -1;
},
/**
Iterates through the array, calling the passed function on each
item. This method corresponds to the `forEach()` method defined in
JavaScript 1.6.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(item, index, array);
```
- `item` is the current item in the iteration.
- `index` is the current index in the iteration.
- `array` is the array itself.
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context. This is a good way
to give your iterator function access to the current object.
Example Usage:
```javascript
let foods = [
{ name: 'apple', eaten: false },
{ name: 'banana', eaten: false },
{ name: 'carrot', eaten: false }
];
foods.forEach((food) => food.eaten = true);
let output = '';
foods.forEach((item, index, array) =>
output += `${index + 1}/${array.length} ${item.name}\n`;
);
console.log(output);
// 1/3 apple
// 2/3 banana
// 3/3 carrot
```
@method forEach
@param {Function} callback The callback to execute
@param {Object} [target] The target object to use
@return {Object} receiver
@public
*/
forEach(callback, target = null) {
(true && !(typeof callback === 'function') && (0, _debug.assert)('`forEach` expects a function as first argument.', typeof callback === 'function'));
var length = this.length;
for (var index = 0; index < length; index++) {
var item = this.objectAt(index);
callback.call(target, item, index, this);
}
return this;
},
/**
Alias for `mapBy`.
Returns the value of the named
property on all items in the enumeration.
```javascript
let people = [{name: 'Joe'}, {name: 'Matt'}];
people.getEach('name');
// ['Joe', 'Matt'];
people.getEach('nonexistentProperty');
// [undefined, undefined];
```
@method getEach
@param {String} key name of the property
@return {Array} The mapped array.
@public
*/
getEach: mapBy,
/**
Sets the value on the named property for each member. This is more
ergonomic than using other methods defined on this helper. If the object
implements Observable, the value will be changed to `set(),` otherwise
it will be set directly. `null` objects are skipped.
```javascript
let people = [{name: 'Joe'}, {name: 'Matt'}];
people.setEach('zipCode', '10011');
// [{name: 'Joe', zipCode: '10011'}, {name: 'Matt', zipCode: '10011'}];
```
@method setEach
@param {String} key The key to set
@param {Object} value The object to set
@return {Object} receiver
@public
*/
setEach(key, value) {
return this.forEach(item => (0, _metal.set)(item, key, value));
},
/**
Maps all of the items in the enumeration to another value, returning
a new array. This method corresponds to `map()` defined in JavaScript 1.6.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(item, index, array);
let arr = [1, 2, 3, 4, 5, 6];
arr.map(element => element * element);
// [1, 4, 9, 16, 25, 36];
arr.map((element, index) => element + index);
// [1, 3, 5, 7, 9, 11];
```
- `item` is the current item in the iteration.
- `index` is the current index in the iteration.
- `array` is the array itself.
It should return the mapped value.
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context. This is a good way
to give your iterator function access to the current object.
@method map
@param {Function} callback The callback to execute
@param {Object} [target] The target object to use
@return {Array} The mapped array.
@public
*/
map(callback, target = null) {
(true && !(typeof callback === 'function') && (0, _debug.assert)('`map` expects a function as first argument.', typeof callback === 'function'));
var ret = A();
this.forEach((x, idx, i) => ret[idx] = callback.call(target, x, idx, i));
return ret;
},
/**
Similar to map, this specialized function returns the value of the named
property on all items in the enumeration.
```javascript
let people = [{name: 'Joe'}, {name: 'Matt'}];
people.mapBy('name');
// ['Joe', 'Matt'];
people.mapBy('unknownProperty');
// [undefined, undefined];
```
@method mapBy
@param {String} key name of the property
@return {Array} The mapped array.
@public
*/
mapBy,
/**
Returns a new array with all of the items in the enumeration that the provided
callback function returns true for. This method corresponds to [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter).
The callback method should have the following signature:
```javascript
function(item, index, array);
```
- `item` is the current item in the iteration.
- `index` is the current index in the iteration.
- `array` is the array itself.
All parameters are optional. The function should return `true` to include the item
in the results, and `false` otherwise.
Example:
```javascript
function isAdult(person) {
return person.age > 18;
};
let people = Ember.A([{ name: 'John', age: 14 }, { name: 'Joan', age: 45 }]);
people.filter(isAdult); // returns [{ name: 'Joan', age: 45 }];
```
Note that in addition to a callback, you can pass an optional target object
that will be set as `this` on the context. This is a good way to give your
iterator function access to the current object. For example:
```javascript
function isAdultAndEngineer(person) {
return person.age > 18 && this.engineering;
}
class AdultsCollection {
engineering = false;
constructor(opts = {}) {
super(...arguments);
this.engineering = opts.engineering;
this.people = Ember.A([{ name: 'John', age: 14 }, { name: 'Joan', age: 45 }]);
}
}
let collection = new AdultsCollection({ engineering: true });
collection.people.filter(isAdultAndEngineer, { target: collection });
```
@method filter
@param {Function} callback The callback to execute
@param {Object} [target] The target object to use
@return {Array} A filtered array.
@public
*/
filter(callback, target = null) {
(true && !(typeof callback === 'function') && (0, _debug.assert)('`filter` expects a function as first argument.', typeof callback === 'function'));
var ret = A();
this.forEach((x, idx, i) => {
if (callback.call(target, x, idx, i)) {
ret.push(x);
}
});
return ret;
},
/**
Returns an array with all of the items in the enumeration where the passed
function returns false. This method is the inverse of filter().
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(item, index, array);
```
- *item* is the current item in the iteration.
- *index* is the current index in the iteration
- *array* is the array itself.
It should return a falsey value to include the item in the results.
Note that in addition to a callback, you can also pass an optional target
object that will be set as "this" on the context. This is a good way
to give your iterator function access to the current object.
Example Usage:
```javascript
const food = [
{ food: 'apple', isFruit: true },
{ food: 'bread', isFruit: false },
{ food: 'banana', isFruit: true }
];
const nonFruits = food.reject(function(thing) {
return thing.isFruit;
}); // [{food: 'bread', isFruit: false}]
```
@method reject
@param {Function} callback The callback to execute
@param {Object} [target] The target object to use
@return {Array} A rejected array.
@public
*/
reject(callback, target = null) {
(true && !(typeof callback === 'function') && (0, _debug.assert)('`reject` expects a function as first argument.', typeof callback === 'function'));
return this.filter(function () {
return !callback.apply(target, arguments);
});
},
/**
Filters the array by the property and an optional value. If a value is given, it returns
the items that have said value for the property. If not, it returns all the items that
have a truthy value for the property.
Example Usage:
```javascript
let things = Ember.A([{ food: 'apple', isFruit: true }, { food: 'beans', isFruit: false }]);
things.filterBy('food', 'beans'); // [{ food: 'beans', isFruit: false }]
things.filterBy('isFruit'); // [{ food: 'apple', isFruit: true }]
```
@method filterBy
@param {String} key the property to test
@param {*} [value] optional value to test against.
@return {Array} filtered array
@public
*/
filterBy() {
return this.filter(iter(...arguments));
},
/**
Returns an array with the items that do not have truthy values for the provided key.
You can pass an optional second argument with a target value to reject for the key.
Otherwise this will reject objects where the provided property evaluates to false.
Example Usage:
```javascript
let food = [
{ name: "apple", isFruit: true },
{ name: "carrot", isFruit: false },
{ name: "bread", isFruit: false },
];
food.rejectBy('isFruit'); // [{ name: "carrot", isFruit: false }, { name: "bread", isFruit: false }]
food.rejectBy('name', 'carrot'); // [{ name: "apple", isFruit: true }}, { name: "bread", isFruit: false }]
```
@method rejectBy
@param {String} key the property to test
@param {*} [value] optional value to test against.
@return {Array} rejected array
@public
*/
rejectBy() {
return this.reject(iter(...arguments));
},
/**
Returns the first item in the array for which the callback returns true.
This method is similar to the `find()` method defined in ECMAScript 2015.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(item, index, array);
```
- `item` is the current item in the iteration.
- `index` is the current index in the iteration.
- `array` is the array itself.
It should return the `true` to include the item in the results, `false`
otherwise.
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context. This is a good way
to give your iterator function access to the current object.
Example Usage:
```javascript
let users = [
{ id: 1, name: 'Yehuda' },
{ id: 2, name: 'Tom' },
{ id: 3, name: 'Melanie' },
{ id: 4, name: 'Leah' }
];
users.find((user) => user.name == 'Tom'); // [{ id: 2, name: 'Tom' }]
users.find(({ id }) => id == 3); // [{ id: 3, name: 'Melanie' }]
```
@method find
@param {Function} callback The callback to execute
@param {Object} [target] The target object to use
@return {Object} Found item or `undefined`.
@public
*/
find(callback, target = null) {
(true && !(typeof callback === 'function') && (0, _debug.assert)('`find` expects a function as first argument.', typeof callback === 'function'));
return find(this, callback, target);
},
/**
Returns the first item with a property matching the passed value. You
can pass an optional second argument with the target value. Otherwise
this will match any property that evaluates to `true`.
This method works much like the more generic `find()` method.
Usage Example:
```javascript
let users = [
{ id: 1, name: 'Yehuda', isTom: false },
{ id: 2, name: 'Tom', isTom: true },
{ id: 3, name: 'Melanie', isTom: false },
{ id: 4, name: 'Leah', isTom: false }
];
users.findBy('id', 4); // { id: 4, name: 'Leah', isTom: false }
users.findBy('name', 'Melanie'); // { id: 3, name: 'Melanie', isTom: false }
users.findBy('isTom'); // { id: 2, name: 'Tom', isTom: true }
```
@method findBy
@param {String} key the property to test
@param {String} [value] optional value to test against.
@return {Object} found item or `undefined`
@public
*/
findBy() {
return find(this, iter(...arguments));
},
/**
Returns `true` if the passed function returns true for every item in the
enumeration. This corresponds with the `Array.prototype.every()` method defined in ES5.
The callback method should have the following signature:
```javascript
function(item, index, array);
```
- `item` is the current item in the iteration.
- `index` is the current index in the iteration.
- `array` is the array itself.
All params are optional. The method should return `true` or `false`.
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context. This is a good way
to give your iterator function access to the current object.
Usage example:
```javascript
function isAdult(person) {
return person.age > 18;
};
const people = Ember.A([{ name: 'John', age: 24 }, { name: 'Joan', age: 45 }]);
const areAllAdults = people.every(isAdult);
```
@method every
@param {Function} callback The callback to execute
@param {Object} [target] The target object to use
@return {Boolean}
@public
*/
every(callback, target = null) {
(true && !(typeof callback === 'function') && (0, _debug.assert)('`every` expects a function as first argument.', typeof callback === 'function'));
return every(this, callback, target);
},
/**
Returns `true` if the passed property resolves to the value of the second
argument for all items in the array. This method is often simpler/faster
than using a callback.
Note that like the native `Array.every`, `isEvery` will return true when called
on any empty array.
```javascript
class Language {
constructor(name, isProgrammingLanguage) {
this.name = name;
this.programmingLanguage = isProgrammingLanguage;
}
}
const compiledLanguages = [
new Language('Java', true),
new Language('Go', true),
new Language('Rust', true)
]
const languagesKnownByMe = [
new Language('Javascript', true),
new Language('English', false),
new Language('Ruby', true)
]
compiledLanguages.isEvery('programmingLanguage'); // true
languagesKnownByMe.isEvery('programmingLanguage'); // false
```
@method isEvery
@param {String} key the property to test
@param {String} [value] optional value to test against. Defaults to `true`
@return {Boolean}
@since 1.3.0
@public
*/
isEvery() {
return every(this, iter(...arguments));
},
/**
The any() method executes the callback function once for each element
present in the array until it finds the one where callback returns a truthy
value (i.e. `true`). If such an element is found, any() immediately returns
true. Otherwise, any() returns false.
```javascript
function(item, index, array);
```
- `item` is the current item in the iteration.
- `index` is the current index in the iteration.
- `array` is the array object itself.
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context. It can be a good way
to give your iterator function access to an object in cases where an ES6
arrow function would not be appropriate.
Usage Example:
```javascript
let includesManager = people.any(this.findPersonInManagersList, this);
let includesStockHolder = people.any(person => {
return this.findPersonInStockHoldersList(person)
});
if (includesManager || includesStockHolder) {
Paychecks.addBiggerBonus();
}
```
@method any
@param {Function} callback The callback to execute
@param {Object} [target] The target object to use
@return {Boolean} `true` if the passed function returns `true` for any item
@public
*/
any(callback, target = null) {
(true && !(typeof callback === 'function') && (0, _debug.assert)('`any` expects a function as first argument.', typeof callback === 'function'));
return any(this, callback, target);
},
/**
Returns `true` if the passed property resolves to the value of the second
argument for any item in the array. This method is often simpler/faster
than using a callback.
Example usage:
```javascript
const food = [
{ food: 'apple', isFruit: true },
{ food: 'bread', isFruit: false },
{ food: 'banana', isFruit: true }
];
food.isAny('isFruit'); // true
```
@method isAny
@param {String} key the property to test
@param {String} [value] optional value to test against. Defaults to `true`
@return {Boolean}
@since 1.3.0
@public
*/
isAny() {
return any(this, iter(...arguments));
},
/**
This will combine the values of the array into a single value. It
is a useful way to collect a summary value from an array. This
corresponds to the `reduce()` method defined in JavaScript 1.8.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(previousValue, item, index, array);
```
- `previousValue` is the value returned by the last call to the iterator.
- `item` is the current item in the iteration.
- `index` is the current index in the iteration.
- `array` is the array itself.
Return the new cumulative value.
In addition to the callback you can also pass an `initialValue`. An error
will be raised if you do not pass an initial value and the enumerator is
empty.
Note that unlike the other methods, this method does not allow you to
pass a target object to set as this for the callback. It's part of the
spec. Sorry.
Example Usage:
```javascript
let numbers = [1, 2, 3, 4, 5];
numbers.reduce(function(summation, current) {
return summation + current;
}); // 15 (1 + 2 + 3 + 4 + 5)
numbers.reduce(function(summation, current) {
return summation + current;
}, -15); // 0 (-15 + 1 + 2 + 3 + 4 + 5)
let binaryValues = [true, false, false];
binaryValues.reduce(function(truthValue, current) {
return truthValue && current;
}); // false (true && false && false)
```
@method reduce
@param {Function} callback The callback to execute
@param {Object} initialValue Initial value for the reduce
@return {Object} The reduced value.
@public
*/
reduce(callback, initialValue) {
(true && !(typeof callback === 'function') && (0, _debug.assert)('`reduce` expects a function as first argument.', typeof callback === 'function'));
var ret = initialValue;
this.forEach(function (item, i) {
ret = callback(ret, item, i, this);
}, this);
return ret;
},
/**
Invokes the named method on every object in the receiver that
implements it. This method corresponds to the implementation in
Prototype 1.6.
```javascript
class Person {
name = null;
constructor(name) {
this.name = name;
}
greet(prefix='Hello') {
return `${prefix} ${this.name}`;
}
}
let people = [new Person('Joe'), new Person('Matt')];
people.invoke('greet'); // ['Hello Joe', 'Hello Matt']
people.invoke('greet', 'Bonjour'); // ['Bonjour Joe', 'Bonjour Matt']
```
@method invoke
@param {String} methodName the name of the method
@param {Object...} args optional arguments to pass as well.
@return {Array} return values from calling invoke.
@public
*/
invoke(methodName, ...args) {
var ret = A();
this.forEach(item => ret.push(item[methodName]?.(...args)));
return ret;
},
/**
Simply converts the object into a genuine array. The order is not
guaranteed. Corresponds to the method implemented by Prototype.
@method toArray
@return {Array} the object as an array.
@public
*/
toArray() {
return this.map(item => item);
},
/**
Returns a copy of the array with all `null` and `undefined` elements removed.
```javascript
let arr = ['a', null, 'c', undefined];
arr.compact(); // ['a', 'c']
```
@method compact
@return {Array} the array without null and undefined elements.
@public
*/
compact() {
return this.filter(value => value != null);
},
/**
Used to determine if the array contains the passed object.
Returns `true` if found, `false` otherwise.
The optional `startAt` argument can be used to pass a starting
index to search from, effectively slicing the searchable portion
of the array. If it's negative it will add the array length to
the startAt value passed in as the index to search from. If less
than or equal to `-1 * array.length` the entire array is searched.
This method has the same behavior of JavaScript's [Array.includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes).
```javascript
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(3, 2); // true
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
[1, 2, 3].includes(1, -1); // false
[1, 2, 3].includes(1, -4); // true
[1, 2, NaN].includes(NaN); // true
```
@method includes
@param {Object} object The object to search for.
@param {Number} startAt optional starting location to search, default 0
@return {Boolean} `true` if object is found in the array.
@public
*/
includes(object, startAt) {
return indexOf(this, object, startAt, true) !== -1;
},
/**
Sorts the array by the keys specified in the argument.
You may provide multiple arguments to sort by multiple properties.
```javascript
let colors = [
{ name: 'red', weight: 500 },
{ name: 'green', weight: 600 },
{ name: 'blue', weight: 500 }
];
colors.sortBy('name');
// [{name: 'blue', weight: 500}, {name: 'green', weight: 600}, {name: 'red', weight: 500}]
colors.sortBy('weight', 'name');
// [{name: 'blue', weight: 500}, {name: 'red', weight: 500}, {name: 'green', weight: 600}]
```
@method sortBy
@param {String} property name(s) to sort on
@return {Array} The sorted array.
@since 1.2.0
@public
*/
sortBy() {
var sortKeys = arguments;
return this.toArray().sort((a, b) => {
for (var i = 0; i < sortKeys.length; i++) {
var key = sortKeys[i];
var propA = (0, _metal.get)(a, key);
var propB = (0, _metal.get)(b, key); // return 1 or -1 else continue to the next sortKey
var compareValue = (0, _compare.default)(propA, propB);
if (compareValue) {
return compareValue;
}
}
return 0;
});
},
/**
Returns a new array that contains only unique values. The default
implementation returns an array regardless of the receiver type.
```javascript
let arr = ['a', 'a', 'b', 'b'];
arr.uniq(); // ['a', 'b']
```
This only works on primitive data types, e.g. Strings, Numbers, etc.
@method uniq
@return {EmberArray}
@public
*/
uniq() {
return uniqBy(this);
},
/**
Returns a new array that contains only items containing a unique property value.
The default implementation returns an array regardless of the receiver type.
```javascript
let arr = [{ value: 'a' }, { value: 'a' }, { value: 'b' }, { value: 'b' }];
arr.uniqBy('value'); // [{ value: 'a' }, { value: 'b' }]
let arr = [2.2, 2.1, 3.2, 3.3];
arr.uniqBy(Math.floor); // [2.2, 3.2];
```
@method uniqBy
@param {String,Function} key
@return {EmberArray}
@public
*/
uniqBy(key) {
return uniqBy(this, key);
},
/**
Returns a new array that excludes the passed value. The default
implementation returns an array regardless of the receiver type.
If the receiver does not contain the value it returns the original array.
```javascript
let arr = ['a', 'b', 'a', 'c'];
arr.without('a'); // ['b', 'c']
```
@method without
@param {Object} value
@return {EmberArray}
@public
*/
without(value) {
if (!this.includes(value)) {
return this; // nothing to do
} // SameValueZero comparison (NaN !== NaN)
var predicate = value === value ? item => item !== value : item => item === item;
return this.filter(predicate);
}
});
/**
This mixin defines the API for modifying array-like objects. These methods
can be applied only to a collection that keeps its items in an ordered set.
It builds upon the Array mixin and adds methods to modify the array.
One concrete implementations of this class include ArrayProxy.
It is important to use the methods in this class to modify arrays so that
changes are observable. This allows the binding system in Ember to function
correctly.
Note that an Array can change even if it does not implement this mixin.
For example, one might implement a SparseArray that cannot be directly
modified, but if its underlying enumerable changes, it will change also.
@class MutableArray
@uses EmberArray
@uses MutableEnumerable
@public
*/
var MutableArray = _metal.Mixin.create(ArrayMixin, _mutable_enumerable.default, {
/**
__Required.__ You must implement this method to apply this mixin.
This is one of the primitives you must implement to support `Array`.
You should replace amt objects started at idx with the objects in the
passed array.
Note that this method is expected to validate the type(s) of objects that it expects.
@method replace
@param {Number} idx Starting index in the array to replace. If
idx >= length, then append to the end of the array.
@param {Number} amt Number of elements that should be removed from
the array, starting at *idx*.
@param {EmberArray} objects An array of zero or more objects that should be
inserted into the array at *idx*
@public
*/
/**
Remove all elements from the array. This is useful if you
want to reuse an existing array without having to recreate it.
```javascript
let colors = ['red', 'green', 'blue'];
colors.length; // 3
colors.clear(); // []
colors.length; // 0
```
@method clear
@return {Array} An empty Array.
@public
*/
clear() {
var len = this.length;
if (len === 0) {
return this;
}
this.replace(0, len, EMPTY_ARRAY);
return this;
},
/**
This will use the primitive `replace()` method to insert an object at the
specified index.
```javascript
let colors = ['red', 'green', 'blue'];
colors.insertAt(2, 'yellow'); // ['red', 'green', 'yellow', 'blue']
colors.insertAt(5, 'orange'); // Error: Index out of range
```
@method insertAt
@param {Number} idx index of insert the object at.
@param {Object} object object to insert
@return {EmberArray} receiver
@public
*/
insertAt(idx, object) {
insertAt(this, idx, object);
return this;
},
/**
Remove an object at the specified index using the `replace()` primitive
method. You can pass either a single index, or a start and a length.
If you pass a start and length that is beyond the
length this method will throw an assertion.
```javascript
let colors = ['red', 'green', 'blue', 'yellow', 'orange'];
colors.removeAt(0); // ['green', 'blue', 'yellow', 'orange']
colors.removeAt(2, 2); // ['green', 'blue']
colors.removeAt(4, 2); // Error: Index out of range
```
@method removeAt
@param {Number} start index, start of range
@param {Number} len length of passing range
@return {EmberArray} receiver
@public
*/
removeAt(start, len) {
return removeAt(this, start, len);
},
/**
Push the object onto the end of the array. Works just like `push()` but it
is KVO-compliant.
```javascript
let colors = ['red', 'green'];
colors.pushObject('black'); // ['red', 'green', 'black']
colors.pushObject(['yellow']); // ['red', 'green', ['yellow']]
```
@method pushObject
@param {*} obj object to push
@return object same object passed as a param
@public
*/
pushObject(obj) {
return insertAt(this, this.length, obj);
},
/**
Add the objects in the passed array to the end of the array. Defers
notifying observers of the change until all objects are added.
```javascript
let colors = ['red'];
colors.pushObjects(['yellow', 'orange']); // ['red', 'yellow', 'orange']
```
@method pushObjects
@param {EmberArray} objects the objects to add
@return {EmberArray} receiver
@public
*/
pushObjects(objects) {
this.replace(this.length, 0, objects);
return this;
},
/**
Pop object from array or nil if none are left. Works just like `pop()` but
it is KVO-compliant.
```javascript
let colors = ['red', 'green', 'blue'];
colors.popObject(); // 'blue'
console.log(colors); // ['red', 'green']
```
@method popObject
@return object
@public
*/
popObject() {
var len = this.length;
if (len === 0) {
return null;
}
var ret = (0, _metal.objectAt)(this, len - 1);
this.removeAt(len - 1, 1);
return ret;
},
/**
Shift an object from start of array or nil if none are left. Works just
like `shift()` but it is KVO-compliant.
```javascript
let colors = ['red', 'green', 'blue'];
colors.shiftObject(); // 'red'
console.log(colors); // ['green', 'blue']
```
@method shiftObject
@return object
@public
*/
shiftObject() {
if (this.length === 0) {
return null;
}
var ret = (0, _metal.objectAt)(this, 0);
this.removeAt(0);
return ret;
},
/**
Unshift an object to start of array. Works just like `unshift()` but it is
KVO-compliant.
```javascript
let colors = ['red'];
colors.unshiftObject('yellow'); // ['yellow', 'red']
colors.unshiftObject(['black']); // [['black'], 'yellow', 'red']
```
@method unshiftObject
@param {*} obj object to unshift
@return object same object passed as a param
@public
*/
unshiftObject(obj) {
return insertAt(this, 0, obj);
},
/**
Adds the named objects to the beginning of the array. Defers notifying
observers until all objects have been added.
```javascript
let colors = ['red'];
colors.unshiftObjects(['black', 'white']); // ['black', 'white', 'red']
colors.unshiftObjects('yellow'); // Type Error: 'undefined' is not a function
```
@method unshiftObjects
@param {Enumberable} objects the objects to add
@return {EmberArray} receiver
@public
*/
unshiftObjects(objects) {
this.replace(0, 0, objects);
return this;
},
/**
Reverse objects in the array. Works just like `reverse()` but it is
KVO-compliant.
@method reverseObjects
@return {EmberArray} receiver
@public
*/
reverseObjects() {
var len = this.length;
if (len === 0) {
return this;
}
var objects = this.toArray().reverse();
this.replace(0, len, objects);
return this;
},
/**
Replace all the receiver's content with content of the argument.
If argument is an empty array receiver will be cleared.
```javascript
let colors = ['red', 'green', 'blue'];
colors.setObjects(['black', 'white']); // ['black', 'white']
colors.setObjects([]); // []
```
@method setObjects
@param {EmberArray} objects array whose content will be used for replacing
the content of the receiver
@return {EmberArray} receiver with the new content
@public
*/
setObjects(objects) {
if (objects.length === 0) {
return this.clear();
}
var len = this.length;
this.replace(0, len, objects);
return this;
},
/**
Remove all occurrences of an object in the array.
```javascript
let cities = ['Chicago', 'Berlin', 'Lima', 'Chicago'];
cities.removeObject('Chicago'); // ['Berlin', 'Lima']
cities.removeObject('Lima'); // ['Berlin']
cities.removeObject('Tokyo') // ['Berlin']
```
@method removeObject
@param {*} obj object to remove
@return {EmberArray} receiver
@public
*/
removeObject(obj) {
var loc = this.length || 0;
while (--loc >= 0) {
var curObject = (0, _metal.objectAt)(this, loc);
if (curObject === obj) {
this.removeAt(loc);
}
}
return this;
},
/**
Removes each object in the passed array from the receiver.
@method removeObjects
@param {EmberArray} objects the objects to remove
@return {EmberArray} receiver
@public
*/
removeObjects(objects) {
(0, _metal.beginPropertyChanges)();
for (var i = objects.length - 1; i >= 0; i--) {
this.removeObject(objects[i]);
}
(0, _metal.endPropertyChanges)();
return this;
},
/**
Push the object onto the end of the array if it is not already
present in the array.
```javascript
let cities = ['Chicago', 'Berlin'];
cities.addObject('Lima'); // ['Chicago', 'Berlin', 'Lima']
cities.addObject('Berlin'); // ['Chicago', 'Berlin', 'Lima']
```
@method addObject
@param {*} obj object to add, if not already present
@return {EmberArray} receiver
@public
*/
addObject(obj) {
var included = this.includes(obj);
if (!included) {
this.pushObject(obj);
}
return this;
},
/**
Adds each object in the passed array to the receiver.
@method addObjects
@param {EmberArray} objects the objects to add.
@return {EmberArray} receiver
@public
*/
addObjects(objects) {
(0, _metal.beginPropertyChanges)();
objects.forEach(obj => this.addObject(obj));
(0, _metal.endPropertyChanges)();
return this;
}
});
/**
Creates an `Ember.NativeArray` from an Array-like object.
Does not modify the original object's contents. `A()` is not needed if
`EmberENV.EXTEND_PROTOTYPES` is `true` (the default value). However,
it is recommended that you use `A()` when creating addons for
ember or when you can not guarantee that `EmberENV.EXTEND_PROTOTYPES`
will be `true`.
Example
```app/components/my-component.js
import Component from '@ember/component';
import { A } from '@ember/array';
export default Component.extend({
tagName: 'ul',
classNames: ['pagination'],
init() {
this._super(...arguments);
if (!this.get('content')) {
this.set('content', A());
this.set('otherContent', A([1,2,3]));
}
}
});
```
@method A
@static
@for @ember/array
@return {Ember.NativeArray}
@public
*/
// Add Ember.Array to Array.prototype. Remove methods with native
// implementations and supply some more optimized versions of generic methods
// because they are so common.
/**
@module ember
*/
/**
The NativeArray mixin contains the properties needed to make the native
Array support MutableArray and all of its dependent APIs. Unless you
have `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Array` set to
false, this will be applied automatically. Otherwise you can apply the mixin
at anytime by calling `Ember.NativeArray.apply(Array.prototype)`.
@class Ember.NativeArray
@uses MutableArray
@uses Observable
@public
*/
_exports.MutableArray = MutableArray;
var NativeArray = _metal.Mixin.create(MutableArray, _observable.default, {
objectAt(idx) {
return this[idx];
},
// primitive for array support.
replace(start, deleteCount, items = EMPTY_ARRAY) {
(true && !(Array.isArray(items)) && (0, _debug.assert)('The third argument to replace needs to be an array.', Array.isArray(items)));
(0, _metal.replaceInNativeArray)(this, start, deleteCount, items);
return this;
}
}); // Remove any methods implemented natively so we don't override them
_exports.NativeArray = NativeArray;
var ignore = ['length'];
NativeArray.keys().forEach(methodName => {
if (Array.prototype[methodName]) {
ignore.push(methodName);
}
});
_exports.NativeArray = NativeArray = NativeArray.without(...ignore);
var A;
_exports.A = A;
if (_environment.ENV.EXTEND_PROTOTYPES.Array) {
NativeArray.apply(Array.prototype, true);
_exports.A = A = function (arr) {
(true && !(!(this instanceof A)) && (0, _debug.assert)('You cannot create an Ember Array with `new A()`, please update to calling A as a function: `A()`', !(this instanceof A)));
return arr || [];
};
} else {
_exports.A = A = function (arr) {
(true && !(!(this instanceof A)) && (0, _debug.assert)('You cannot create an Ember Array with `new A()`, please update to calling A as a function: `A()`', !(this instanceof A)));
if (!arr) {
arr = [];
}
return ArrayMixin.detect(arr) ? arr : NativeArray.apply(arr);
};
}
var _default = ArrayMixin;
_exports.default = _default;
});
define("@ember/-internals/runtime/lib/mixins/comparable", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module ember
*/
/**
Implements some standard methods for comparing objects. Add this mixin to
any class you create that can compare its instances.
You should implement the `compare()` method.
@class Comparable
@namespace Ember
@since Ember 0.9
@private
*/
var _default = _metal.Mixin.create({
/**
__Required.__ You must implement this method to apply this mixin.
Override to return the result of the comparison of the two parameters. The
compare method should return:
- `-1` if `a < b`
- `0` if `a == b`
- `1` if `a > b`
Default implementation raises an exception.
@method compare
@param a {Object} the first object to compare
@param b {Object} the second object to compare
@return {Number} the result of the comparison
@private
*/
compare: null
});
_exports.default = _default;
});
define("@ember/-internals/runtime/lib/mixins/container_proxy", ["exports", "@ember/runloop", "@ember/-internals/metal"], function (_exports, _runloop, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module ember
*/
/**
ContainerProxyMixin is used to provide public access to specific
container functionality.
@class ContainerProxyMixin
@private
*/
var containerProxyMixin = {
/**
The container stores state.
@private
@property {Ember.Container} __container__
*/
__container__: null,
/**
Returns an object that can be used to provide an owner to a
manually created instance.
Example:
```
import { getOwner } from '@ember/application';
let owner = getOwner(this);
User.create(
owner.ownerInjection(),
{ username: 'rwjblue' }
)
```
@public
@method ownerInjection
@since 2.3.0
@return {Object}
*/
ownerInjection() {
return this.__container__.ownerInjection();
},
/**
Given a fullName return a corresponding instance.
The default behavior is for lookup to return a singleton instance.
The singleton is scoped to the container, allowing multiple containers
to all have their own locally scoped singletons.
```javascript
let registry = new Registry();
let container = registry.container();
registry.register('api:twitter', Twitter);
let twitter = container.lookup('api:twitter');
twitter instanceof Twitter; // => true
// by default the container will return singletons
let twitter2 = container.lookup('api:twitter');
twitter2 instanceof Twitter; // => true
twitter === twitter2; //=> true
```
If singletons are not wanted an optional flag can be provided at lookup.
```javascript
let registry = new Registry();
let container = registry.container();
registry.register('api:twitter', Twitter);
let twitter = container.lookup('api:twitter', { singleton: false });
let twitter2 = container.lookup('api:twitter', { singleton: false });
twitter === twitter2; //=> false
```
@public
@method lookup
@param {String} fullName
@param {Object} options
@return {any}
*/
lookup(fullName, options) {
return this.__container__.lookup(fullName, options);
},
destroy() {
var container = this.__container__;
if (container) {
(0, _runloop.join)(() => {
container.destroy();
(0, _runloop.schedule)('destroy', container, 'finalizeDestroy');
});
}
this._super();
},
/**
Given a fullName return a factory manager.
This method returns a manager which can be used for introspection of the
factory's class or for the creation of factory instances with initial
properties. The manager is an object with the following properties:
* `class` - The registered or resolved class.
* `create` - A function that will create an instance of the class with
any dependencies injected.
For example:
```javascript
import { getOwner } from '@ember/application';
let owner = getOwner(otherInstance);
// the owner is commonly the `applicationInstance`, and can be accessed via
// an instance initializer.
let factory = owner.factoryFor('service:bespoke');
factory.class;
// The registered or resolved class. For example when used with an Ember-CLI
// app, this would be the default export from `app/services/bespoke.js`.
let instance = factory.create({
someProperty: 'an initial property value'
});
// Create an instance with any injections and the passed options as
// initial properties.
```
Any instances created via the factory's `.create()` method *must* be destroyed
manually by the caller of `.create()`. Typically, this is done during the creating
objects own `destroy` or `willDestroy` methods.
@public
@method factoryFor
@param {String} fullName
@param {Object} options
@return {FactoryManager}
*/
factoryFor(fullName, options = {}) {
return this.__container__.factoryFor(fullName, options);
}
};
var _default = _metal.Mixin.create(containerProxyMixin);
_exports.default = _default;
});
define("@ember/-internals/runtime/lib/mixins/enumerable", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module @ember/enumerable
@private
*/
/**
The methods in this mixin have been moved to [MutableArray](/ember/release/classes/MutableArray). This mixin has
been intentionally preserved to avoid breaking Enumerable.detect checks
until the community migrates away from them.
@class Enumerable
@private
*/
var _default = _metal.Mixin.create();
_exports.default = _default;
});
define("@ember/-internals/runtime/lib/mixins/evented", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module @ember/object
*/
/**
This mixin allows for Ember objects to subscribe to and emit events.
```app/utils/person.js
import EmberObject from '@ember/object';
import Evented from '@ember/object/evented';
export default EmberObject.extend(Evented, {
greet() {
// ...
this.trigger('greet');
}
});
```
```javascript
var person = Person.create();
person.on('greet', function() {
console.log('Our person has greeted');
});
person.greet();
// outputs: 'Our person has greeted'
```
You can also chain multiple event subscriptions:
```javascript
person.on('greet', function() {
console.log('Our person has greeted');
}).one('greet', function() {
console.log('Offer one-time special');
}).off('event', this, forgetThis);
```
@class Evented
@public
*/
var _default = _metal.Mixin.create({
/**
Subscribes to a named event with given function.
```javascript
person.on('didLoad', function() {
// fired once the person has loaded
});
```
An optional target can be passed in as the 2nd argument that will
be set as the "this" for the callback. This is a good way to give your
function access to the object triggering the event. When the target
parameter is used the callback method becomes the third argument.
@method on
@param {String} name The name of the event
@param {Object} [target] The "this" binding for the callback
@param {Function|String} method A function or the name of a function to be called on `target`
@return this
@public
*/
on(name, target, method) {
(0, _metal.addListener)(this, name, target, method);
return this;
},
/**
Subscribes a function to a named event and then cancels the subscription
after the first time the event is triggered. It is good to use ``one`` when
you only care about the first time an event has taken place.
This function takes an optional 2nd argument that will become the "this"
value for the callback. When the target parameter is used the callback method
becomes the third argument.
@method one
@param {String} name The name of the event
@param {Object} [target] The "this" binding for the callback
@param {Function|String} method A function or the name of a function to be called on `target`
@return this
@public
*/
one(name, target, method) {
(0, _metal.addListener)(this, name, target, method, true);
return this;
},
/**
Triggers a named event for the object. Any additional arguments
will be passed as parameters to the functions that are subscribed to the
event.
```javascript
person.on('didEat', function(food) {
console.log('person ate some ' + food);
});
person.trigger('didEat', 'broccoli');
// outputs: person ate some broccoli
```
@method trigger
@param {String} name The name of the event
@param {Object...} args Optional arguments to pass on
@public
*/
trigger(name, ...args) {
(0, _metal.sendEvent)(this, name, args);
},
/**
Cancels subscription for given name, target, and method.
@method off
@param {String} name The name of the event
@param {Object} target The target of the subscription
@param {Function|String} method The function or the name of a function of the subscription
@return this
@public
*/
off(name, target, method) {
(0, _metal.removeListener)(this, name, target, method);
return this;
},
/**
Checks to see if object has any subscriptions for named event.
@method has
@param {String} name The name of the event
@return {Boolean} does the object have a subscription for event
@public
*/
has(name) {
return (0, _metal.hasListeners)(this, name);
}
});
_exports.default = _default;
});
define("@ember/-internals/runtime/lib/mixins/mutable_enumerable", ["exports", "@ember/-internals/runtime/lib/mixins/enumerable", "@ember/-internals/metal"], function (_exports, _enumerable, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module ember
*/
/**
The methods in this mixin have been moved to MutableArray. This mixin has
been intentionally preserved to avoid breaking MutableEnumerable.detect
checks until the community migrates away from them.
@class MutableEnumerable
@namespace Ember
@uses Enumerable
@private
*/
var _default = _metal.Mixin.create(_enumerable.default);
_exports.default = _default;
});
define("@ember/-internals/runtime/lib/mixins/observable", ["exports", "@ember/-internals/meta", "@ember/-internals/metal", "@ember/debug"], function (_exports, _meta, _metal, _debug) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module @ember/object
*/
/**
## Overview
This mixin provides properties and property observing functionality, core
features of the Ember object model.
Properties and observers allow one object to observe changes to a
property on another object. This is one of the fundamental ways that
models, controllers and views communicate with each other in an Ember
application.
Any object that has this mixin applied can be used in observer
operations. That includes `EmberObject` and most objects you will
interact with as you write your Ember application.
Note that you will not generally apply this mixin to classes yourself,
but you will use the features provided by this module frequently, so it
is important to understand how to use it.
## Using `get()` and `set()`
Because of Ember's support for bindings and observers, you will always
access properties using the get method, and set properties using the
set method. This allows the observing objects to be notified and
computed properties to be handled properly.
More documentation about `get` and `set` are below.
## Observing Property Changes
You typically observe property changes simply by using the `observer`
function in classes that you write.
For example:
```javascript
import { observer } from '@ember/object';
import EmberObject from '@ember/object';
EmberObject.extend({
valueObserver: observer('value', function(sender, key, value, rev) {
// Executes whenever the "value" property changes
// See the addObserver method for more information about the callback arguments
})
});
```
Although this is the most common way to add an observer, this capability
is actually built into the `EmberObject` class on top of two methods
defined in this mixin: `addObserver` and `removeObserver`. You can use
these two methods to add and remove observers yourself if you need to
do so at runtime.
To add an observer for a property, call:
```javascript
object.addObserver('propertyKey', targetObject, targetAction)
```
This will call the `targetAction` method on the `targetObject` whenever
the value of the `propertyKey` changes.
Note that if `propertyKey` is a computed property, the observer will be
called when any of the property dependencies are changed, even if the
resulting value of the computed property is unchanged. This is necessary
because computed properties are not computed until `get` is called.
@class Observable
@public
*/
var _default = _metal.Mixin.create({
/**
Retrieves the value of a property from the object.
This method is usually similar to using `object[keyName]` or `object.keyName`,
however it supports both computed properties and the unknownProperty
handler.
Because `get` unifies the syntax for accessing all these kinds
of properties, it can make many refactorings easier, such as replacing a
simple property with a computed property, or vice versa.
### Computed Properties
Computed properties are methods defined with the `property` modifier
declared at the end, such as:
```javascript
import { computed } from '@ember/object';
fullName: computed('firstName', 'lastName', function() {
return this.get('firstName') + ' ' + this.get('lastName');
})
```
When you call `get` on a computed property, the function will be
called and the return value will be returned instead of the function
itself.
### Unknown Properties
Likewise, if you try to call `get` on a property whose value is
`undefined`, the `unknownProperty()` method will be called on the object.
If this method returns any value other than `undefined`, it will be returned
instead. This allows you to implement "virtual" properties that are
not defined upfront.
@method get
@param {String} keyName The property to retrieve
@return {Object} The property value or undefined.
@public
*/
get(keyName) {
return (0, _metal.get)(this, keyName);
},
/**
To get the values of multiple properties at once, call `getProperties`
with a list of strings or an array:
```javascript
record.getProperties('firstName', 'lastName', 'zipCode');
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
```
is equivalent to:
```javascript
record.getProperties(['firstName', 'lastName', 'zipCode']);
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
```
@method getProperties
@param {String...|Array} list of keys to get
@return {Object}
@public
*/
getProperties(...args) {
return (0, _metal.getProperties)(...[this].concat(args));
},
/**
Sets the provided key or path to the value.
```javascript
record.set("key", value);
```
This method is generally very similar to calling `object["key"] = value` or
`object.key = value`, except that it provides support for computed
properties, the `setUnknownProperty()` method and property observers.
### Computed Properties
If you try to set a value on a key that has a computed property handler
defined (see the `get()` method for an example), then `set()` will call
that method, passing both the value and key instead of simply changing
the value itself. This is useful for those times when you need to
implement a property that is composed of one or more member
properties.
### Unknown Properties
If you try to set a value on a key that is undefined in the target
object, then the `setUnknownProperty()` handler will be called instead. This
gives you an opportunity to implement complex "virtual" properties that
are not predefined on the object. If `setUnknownProperty()` returns
undefined, then `set()` will simply set the value on the object.
### Property Observers
In addition to changing the property, `set()` will also register a property
change with the object. Unless you have placed this call inside of a
`beginPropertyChanges()` and `endPropertyChanges(),` any "local" observers
(i.e. observer methods declared on the same object), will be called
immediately. Any "remote" observers (i.e. observer methods declared on
another object) will be placed in a queue and called at a later time in a
coalesced manner.
@method set
@param {String} keyName The property to set
@param {Object} value The value to set or `null`.
@return {Object} The passed value
@public
*/
set(keyName, value) {
return (0, _metal.set)(this, keyName, value);
},
/**
Sets a list of properties at once. These properties are set inside
a single `beginPropertyChanges` and `endPropertyChanges` batch, so
observers will be buffered.
```javascript
record.setProperties({ firstName: 'Charles', lastName: 'Jolley' });
```
@method setProperties
@param {Object} hash the hash of keys and values to set
@return {Object} The passed in hash
@public
*/
setProperties(hash) {
return (0, _metal.setProperties)(this, hash);
},
/**
Begins a grouping of property changes.
You can use this method to group property changes so that notifications
will not be sent until the changes are finished. If you plan to make a
large number of changes to an object at one time, you should call this
method at the beginning of the changes to begin deferring change
notifications. When you are done making changes, call
`endPropertyChanges()` to deliver the deferred change notifications and end
deferring.
@method beginPropertyChanges
@return {Observable}
@private
*/
beginPropertyChanges() {
(0, _metal.beginPropertyChanges)();
return this;
},
/**
Ends a grouping of property changes.
You can use this method to group property changes so that notifications
will not be sent until the changes are finished. If you plan to make a
large number of changes to an object at one time, you should call
`beginPropertyChanges()` at the beginning of the changes to defer change
notifications. When you are done making changes, call this method to
deliver the deferred change notifications and end deferring.
@method endPropertyChanges
@return {Observable}
@private
*/
endPropertyChanges() {
(0, _metal.endPropertyChanges)();
return this;
},
/**
Notify the observer system that a property has just changed.
Sometimes you need to change a value directly or indirectly without
actually calling `get()` or `set()` on it. In this case, you can use this
method instead. Calling this method will notify all observers that the
property has potentially changed value.
@method notifyPropertyChange
@param {String} keyName The property key to be notified about.
@return {Observable}
@public
*/
notifyPropertyChange(keyName) {
(0, _metal.notifyPropertyChange)(this, keyName);
return this;
},
/**
Adds an observer on a property.
This is the core method used to register an observer for a property.
Once you call this method, any time the key's value is set, your observer
will be notified. Note that the observers are triggered any time the
value is set, regardless of whether it has actually changed. Your
observer should be prepared to handle that.
There are two common invocation patterns for `.addObserver()`:
- Passing two arguments:
- the name of the property to observe (as a string)
- the function to invoke (an actual function)
- Passing three arguments:
- the name of the property to observe (as a string)
- the target object (will be used to look up and invoke a
function on)
- the name of the function to invoke on the target object
(as a string).
```app/components/my-component.js
import Component from '@ember/component';
export default Component.extend({
init() {
this._super(...arguments);
// the following are equivalent:
// using three arguments
this.addObserver('foo', this, 'fooDidChange');
// using two arguments
this.addObserver('foo', (...args) => {
this.fooDidChange(...args);
});
},
fooDidChange() {
// your custom logic code
}
});
```
### Observer Methods
Observer methods have the following signature:
```app/components/my-component.js
import Component from '@ember/component';
export default Component.extend({
init() {
this._super(...arguments);
this.addObserver('foo', this, 'fooDidChange');
},
fooDidChange(sender, key, value, rev) {
// your code
}
});
```
The `sender` is the object that changed. The `key` is the property that
changes. The `value` property is currently reserved and unused. The `rev`
is the last property revision of the object when it changed, which you can
use to detect if the key value has really changed or not.
Usually you will not need the value or revision parameters at
the end. In this case, it is common to write observer methods that take
only a sender and key value as parameters or, if you aren't interested in
any of these values, to write an observer that has no parameters at all.
@method addObserver
@param {String} key The key to observe
@param {Object} target The target object to invoke
@param {String|Function} method The method to invoke
@param {Boolean} sync Whether the observer is sync or not
@return {Observable}
@public
*/
addObserver(key, target, method, sync) {
(0, _metal.addObserver)(this, key, target, method, sync);
return this;
},
/**
Remove an observer you have previously registered on this object. Pass
the same key, target, and method you passed to `addObserver()` and your
target will no longer receive notifications.
@method removeObserver
@param {String} key The key to observe
@param {Object} target The target object to invoke
@param {String|Function} method The method to invoke
@param {Boolean} sync Whether the observer is async or not
@return {Observable}
@public
*/
removeObserver(key, target, method, sync) {
(0, _metal.removeObserver)(this, key, target, method, sync);
return this;
},
/**
Returns `true` if the object currently has observers registered for a
particular key. You can use this method to potentially defer performing
an expensive action until someone begins observing a particular property
on the object.
@method hasObserverFor
@param {String} key Key to check
@return {Boolean}
@private
*/
hasObserverFor(key) {
return (0, _metal.hasListeners)(this, `${key}:change`);
},
/**
Set the value of a property to the current value plus some amount.
```javascript
person.incrementProperty('age');
team.incrementProperty('score', 2);
```
@method incrementProperty
@param {String} keyName The name of the property to increment
@param {Number} increment The amount to increment by. Defaults to 1
@return {Number} The new property value
@public
*/
incrementProperty(keyName, increment = 1) {
(true && !(!isNaN(parseFloat(increment)) && isFinite(increment)) && (0, _debug.assert)('Must pass a numeric value to incrementProperty', !isNaN(parseFloat(increment)) && isFinite(increment)));
return (0, _metal.set)(this, keyName, (parseFloat((0, _metal.get)(this, keyName)) || 0) + increment);
},
/**
Set the value of a property to the current value minus some amount.
```javascript
player.decrementProperty('lives');
orc.decrementProperty('health', 5);
```
@method decrementProperty
@param {String} keyName The name of the property to decrement
@param {Number} decrement The amount to decrement by. Defaults to 1
@return {Number} The new property value
@public
*/
decrementProperty(keyName, decrement = 1) {
(true && !(!isNaN(parseFloat(decrement)) && isFinite(decrement)) && (0, _debug.assert)('Must pass a numeric value to decrementProperty', !isNaN(parseFloat(decrement)) && isFinite(decrement)));
return (0, _metal.set)(this, keyName, ((0, _metal.get)(this, keyName) || 0) - decrement);
},
/**
Set the value of a boolean property to the opposite of its
current value.
```javascript
starship.toggleProperty('warpDriveEngaged');
```
@method toggleProperty
@param {String} keyName The name of the property to toggle
@return {Boolean} The new property value
@public
*/
toggleProperty(keyName) {
return (0, _metal.set)(this, keyName, !(0, _metal.get)(this, keyName));
},
/**
Returns the cached value of a computed property, if it exists.
This allows you to inspect the value of a computed property
without accidentally invoking it if it is intended to be
generated lazily.
@method cacheFor
@param {String} keyName
@return {Object} The cached value of the computed property, if any
@public
*/
cacheFor(keyName) {
var meta = (0, _meta.peekMeta)(this);
if (meta !== null) {
return meta.valueFor(keyName);
}
}
});
_exports.default = _default;
});
define("@ember/-internals/runtime/lib/mixins/promise_proxy", ["exports", "@ember/-internals/metal", "@ember/error"], function (_exports, _metal, _error) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module @ember/object
*/
function tap(proxy, promise) {
(0, _metal.setProperties)(proxy, {
isFulfilled: false,
isRejected: false
});
return promise.then(value => {
if (!proxy.isDestroyed && !proxy.isDestroying) {
(0, _metal.setProperties)(proxy, {
content: value,
isFulfilled: true
});
}
return value;
}, reason => {
if (!proxy.isDestroyed && !proxy.isDestroying) {
(0, _metal.setProperties)(proxy, {
reason,
isRejected: true
});
}
throw reason;
}, 'Ember: PromiseProxy');
}
/**
A low level mixin making ObjectProxy promise-aware.
```javascript
import { resolve } from 'rsvp';
import $ from 'jquery';
import ObjectProxy from '@ember/object/proxy';
import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';
let ObjectPromiseProxy = ObjectProxy.extend(PromiseProxyMixin);
let proxy = ObjectPromiseProxy.create({
promise: resolve($.getJSON('/some/remote/data.json'))
});
proxy.then(function(json){
// the json
}, function(reason) {
// the reason why you have no json
});
```
the proxy has bindable attributes which
track the promises life cycle
```javascript
proxy.get('isPending') //=> true
proxy.get('isSettled') //=> false
proxy.get('isRejected') //=> false
proxy.get('isFulfilled') //=> false
```
When the $.getJSON completes, and the promise is fulfilled
with json, the life cycle attributes will update accordingly.
Note that $.getJSON doesn't return an ECMA specified promise,
it is useful to wrap this with an `RSVP.resolve` so that it behaves
as a spec compliant promise.
```javascript
proxy.get('isPending') //=> false
proxy.get('isSettled') //=> true
proxy.get('isRejected') //=> false
proxy.get('isFulfilled') //=> true
```
As the proxy is an ObjectProxy, and the json now its content,
all the json properties will be available directly from the proxy.
```javascript
// Assuming the following json:
{
firstName: 'Stefan',
lastName: 'Penner'
}
// both properties will accessible on the proxy
proxy.get('firstName') //=> 'Stefan'
proxy.get('lastName') //=> 'Penner'
```
@class PromiseProxyMixin
@public
*/
var _default = _metal.Mixin.create({
/**
If the proxied promise is rejected this will contain the reason
provided.
@property reason
@default null
@public
*/
reason: null,
/**
Once the proxied promise has settled this will become `false`.
@property isPending
@default true
@public
*/
isPending: (0, _metal.computed)('isSettled', function () {
return !(0, _metal.get)(this, 'isSettled');
}).readOnly(),
/**
Once the proxied promise has settled this will become `true`.
@property isSettled
@default false
@public
*/
isSettled: (0, _metal.computed)('isRejected', 'isFulfilled', function () {
return (0, _metal.get)(this, 'isRejected') || (0, _metal.get)(this, 'isFulfilled');
}).readOnly(),
/**
Will become `true` if the proxied promise is rejected.
@property isRejected
@default false
@public
*/
isRejected: false,
/**
Will become `true` if the proxied promise is fulfilled.
@property isFulfilled
@default false
@public
*/
isFulfilled: false,
/**
The promise whose fulfillment value is being proxied by this object.
This property must be specified upon creation, and should not be
changed once created.
Example:
```javascript
import ObjectProxy from '@ember/object/proxy';
import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';
ObjectProxy.extend(PromiseProxyMixin).create({
promise: <thenable>
});
```
@property promise
@public
*/
promise: (0, _metal.computed)({
get() {
throw new _error.default("PromiseProxy's promise must be set");
},
set(key, promise) {
return tap(this, promise);
}
}),
/**
An alias to the proxied promise's `then`.
See RSVP.Promise.then.
@method then
@param {Function} callback
@return {RSVP.Promise}
@public
*/
then: promiseAlias('then'),
/**
An alias to the proxied promise's `catch`.
See RSVP.Promise.catch.
@method catch
@param {Function} callback
@return {RSVP.Promise}
@since 1.3.0
@public
*/
catch: promiseAlias('catch'),
/**
An alias to the proxied promise's `finally`.
See RSVP.Promise.finally.
@method finally
@param {Function} callback
@return {RSVP.Promise}
@since 1.3.0
@public
*/
finally: promiseAlias('finally')
});
_exports.default = _default;
function promiseAlias(name) {
return function () {
var promise = (0, _metal.get)(this, 'promise');
return promise[name](...arguments);
};
}
});
define("@ember/-internals/runtime/lib/mixins/registry_proxy", ["exports", "@ember/debug", "@ember/-internals/metal"], function (_exports, _debug, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module ember
*/
/**
RegistryProxyMixin is used to provide public access to specific
registry functionality.
@class RegistryProxyMixin
@private
*/
var _default = _metal.Mixin.create({
__registry__: null,
/**
Given a fullName return the corresponding factory.
@public
@method resolveRegistration
@param {String} fullName
@return {Function} fullName's factory
*/
resolveRegistration(fullName, options) {
(true && !(this.__registry__.isValidFullName(fullName)) && (0, _debug.assert)('fullName must be a proper full name', this.__registry__.isValidFullName(fullName)));
return this.__registry__.resolve(fullName, options);
},
/**
Registers a factory that can be used for dependency injection (with
`inject`) or for service lookup. Each factory is registered with
a full name including two parts: `type:name`.
A simple example:
```javascript
import Application from '@ember/application';
import EmberObject from '@ember/object';
let App = Application.create();
App.Orange = EmberObject.extend();
App.register('fruit:favorite', App.Orange);
```
Ember will resolve factories from the `App` namespace automatically.
For example `App.CarsController` will be discovered and returned if
an application requests `controller:cars`.
An example of registering a controller with a non-standard name:
```javascript
import Application from '@ember/application';
import Controller from '@ember/controller';
let App = Application.create();
let Session = Controller.extend();
App.register('controller:session', Session);
// The Session controller can now be treated like a normal controller,
// despite its non-standard name.
App.ApplicationController = Controller.extend({
needs: ['session']
});
```
Registered factories are **instantiated** by having `create`
called on them. Additionally they are **singletons**, each time
they are looked up they return the same instance.
Some examples modifying that default behavior:
```javascript
import Application from '@ember/application';
import EmberObject from '@ember/object';
let App = Application.create();
App.Person = EmberObject.extend();
App.Orange = EmberObject.extend();
App.Email = EmberObject.extend();
App.session = EmberObject.create();
App.register('model:user', App.Person, { singleton: false });
App.register('fruit:favorite', App.Orange);
App.register('communication:main', App.Email, { singleton: false });
App.register('session', App.session, { instantiate: false });
```
@method register
@param fullName {String} type:name (e.g., 'model:user')
@param factory {any} (e.g., App.Person)
@param options {Object} (optional) disable instantiation or singleton usage
@public
*/
register: registryAlias('register'),
/**
Unregister a factory.
```javascript
import Application from '@ember/application';
import EmberObject from '@ember/object';
let App = Application.create();
let User = EmberObject.extend();
App.register('model:user', User);
App.resolveRegistration('model:user').create() instanceof User //=> true
App.unregister('model:user')
App.resolveRegistration('model:user') === undefined //=> true
```
@public
@method unregister
@param {String} fullName
*/
unregister: registryAlias('unregister'),
/**
Check if a factory is registered.
@public
@method hasRegistration
@param {String} fullName
@return {Boolean}
*/
hasRegistration: registryAlias('has'),
/**
Return a specific registered option for a particular factory.
@public
@method registeredOption
@param {String} fullName
@param {String} optionName
@return {Object} options
*/
registeredOption: registryAlias('getOption'),
/**
Register options for a particular factory.
@public
@method registerOptions
@param {String} fullName
@param {Object} options
*/
registerOptions: registryAlias('options'),
/**
Return registered options for a particular factory.
@public
@method registeredOptions
@param {String} fullName
@return {Object} options
*/
registeredOptions: registryAlias('getOptions'),
/**
Allow registering options for all factories of a type.
```javascript
import Application from '@ember/application';
let App = Application.create();
let appInstance = App.buildInstance();
// if all of type `connection` must not be singletons
appInstance.registerOptionsForType('connection', { singleton: false });
appInstance.register('connection:twitter', TwitterConnection);
appInstance.register('connection:facebook', FacebookConnection);
let twitter = appInstance.lookup('connection:twitter');
let twitter2 = appInstance.lookup('connection:twitter');
twitter === twitter2; // => false
let facebook = appInstance.lookup('connection:facebook');
let facebook2 = appInstance.lookup('connection:facebook');
facebook === facebook2; // => false
```
@public
@method registerOptionsForType
@param {String} type
@param {Object} options
*/
registerOptionsForType: registryAlias('optionsForType'),
/**
Return the registered options for all factories of a type.
@public
@method registeredOptionsForType
@param {String} type
@return {Object} options
*/
registeredOptionsForType: registryAlias('getOptionsForType'),
/**
Define a dependency injection onto a specific factory or all factories
of a type.
When Ember instantiates a controller, view, or other framework component
it can attach a dependency to that component. This is often used to
provide services to a set of framework components.
An example of providing a session object to all controllers:
```javascript
import { alias } from '@ember/object/computed';
import Application from '@ember/application';
import Controller from '@ember/controller';
import EmberObject from '@ember/object';
let App = Application.create();
let Session = EmberObject.extend({ isAuthenticated: false });
// A factory must be registered before it can be injected
App.register('session:main', Session);
// Inject 'session:main' onto all factories of the type 'controller'
// with the name 'session'
App.inject('controller', 'session', 'session:main');
App.IndexController = Controller.extend({
isLoggedIn: alias('session.isAuthenticated')
});
```
Injections can also be performed on specific factories.
```javascript
App.inject(<full_name or type>, <property name>, <full_name>)
App.inject('route', 'source', 'source:main')
App.inject('route:application', 'email', 'model:email')
```
It is important to note that injections can only be performed on
classes that are instantiated by Ember itself. Instantiating a class
directly (via `create` or `new`) bypasses the dependency injection
system.
@public
@method inject
@param factoryNameOrType {String}
@param property {String}
@param injectionName {String}
**/
inject: registryAlias('injection')
});
_exports.default = _default;
function registryAlias(name) {
return function () {
return this.__registry__[name](...arguments);
};
}
});
define("@ember/-internals/runtime/lib/mixins/target_action_support", ["exports", "@ember/-internals/environment", "@ember/-internals/metal", "@ember/debug"], function (_exports, _environment, _metal, _debug) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module ember
*/
/**
`Ember.TargetActionSupport` is a mixin that can be included in a class
to add a `triggerAction` method with semantics similar to the Handlebars
`{{action}}` helper. In normal Ember usage, the `{{action}}` helper is
usually the best choice. This mixin is most often useful when you are
doing more complex event handling in Components.
@class TargetActionSupport
@namespace Ember
@extends Mixin
@private
*/
var TargetActionSupport = _metal.Mixin.create({
target: null,
action: null,
actionContext: null,
actionContextObject: (0, _metal.computed)('actionContext', function () {
var actionContext = (0, _metal.get)(this, 'actionContext');
if (typeof actionContext === 'string') {
var value = (0, _metal.get)(this, actionContext);
if (value === undefined) {
value = (0, _metal.get)(_environment.context.lookup, actionContext);
}
return value;
} else {
return actionContext;
}
}),
/**
Send an `action` with an `actionContext` to a `target`. The action, actionContext
and target will be retrieved from properties of the object. For example:
```javascript
import { alias } from '@ember/object/computed';
App.SaveButtonView = Ember.View.extend(Ember.TargetActionSupport, {
target: alias('controller'),
action: 'save',
actionContext: alias('context'),
click() {
this.triggerAction(); // Sends the `save` action, along with the current context
// to the current controller
}
});
```
The `target`, `action`, and `actionContext` can be provided as properties of
an optional object argument to `triggerAction` as well.
```javascript
App.SaveButtonView = Ember.View.extend(Ember.TargetActionSupport, {
click() {
this.triggerAction({
action: 'save',
target: this.get('controller'),
actionContext: this.get('context')
}); // Sends the `save` action, along with the current context
// to the current controller
}
});
```
The `actionContext` defaults to the object you are mixing `TargetActionSupport` into.
But `target` and `action` must be specified either as properties or with the argument
to `triggerAction`, or a combination:
```javascript
import { alias } from '@ember/object/computed';
App.SaveButtonView = Ember.View.extend(Ember.TargetActionSupport, {
target: alias('controller'),
click() {
this.triggerAction({
action: 'save'
}); // Sends the `save` action, along with a reference to `this`,
// to the current controller
}
});
```
@method triggerAction
@param opts {Object} (optional, with the optional keys action, target and/or actionContext)
@return {Boolean} true if the action was sent successfully and did not return false
@private
*/
triggerAction(opts = {}) {
var {
action,
target,
actionContext
} = opts;
action = action || (0, _metal.get)(this, 'action');
target = target || getTarget(this);
if (actionContext === undefined) {
actionContext = (0, _metal.get)(this, 'actionContextObject') || this;
}
if (target && action) {
var ret;
if (target.send) {
ret = target.send(...[action].concat(actionContext));
} else {
(true && !(typeof target[action] === 'function') && (0, _debug.assert)(`The action '${action}' did not exist on ${target}`, typeof target[action] === 'function'));
ret = target[action](...[].concat(actionContext));
}
if (ret !== false) {
return true;
}
}
return false;
}
});
function getTarget(instance) {
var target = (0, _metal.get)(instance, 'target');
if (target) {
if (typeof target === 'string') {
var value = (0, _metal.get)(instance, target);
if (value === undefined) {
value = (0, _metal.get)(_environment.context.lookup, target);
}
return value;
} else {
return target;
}
}
if (instance._target) {
return instance._target;
}
return null;
}
if (true
/* DEBUG */
) {
Object.seal(TargetActionSupport);
}
var _default = TargetActionSupport;
_exports.default = _default;
});
define("@ember/-internals/runtime/lib/system/array_proxy", ["exports", "@ember/-internals/metal", "@ember/-internals/utils", "@ember/-internals/runtime/lib/system/object", "@ember/-internals/runtime/lib/mixins/array", "@ember/debug", "@glimmer/manager", "@glimmer/validator"], function (_exports, _metal, _utils, _object, _array, _debug, _manager, _validator) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module @ember/array
*/
var ARRAY_OBSERVER_MAPPING = {
willChange: '_arrangedContentArrayWillChange',
didChange: '_arrangedContentArrayDidChange'
};
function customTagForArrayProxy(proxy, key) {
if (key === '[]') {
proxy._revalidate();
return proxy._arrTag;
} else if (key === 'length') {
proxy._revalidate();
return proxy._lengthTag;
}
return (0, _validator.tagFor)(proxy, key);
}
/**
An ArrayProxy wraps any other object that implements `Array` and/or
`MutableArray,` forwarding all requests. This makes it very useful for
a number of binding use cases or other cases where being able to swap
out the underlying array is useful.
A simple example of usage:
```javascript
import { A } from '@ember/array';
import ArrayProxy from '@ember/array/proxy';
let pets = ['dog', 'cat', 'fish'];
let ap = ArrayProxy.create({ content: A(pets) });
ap.get('firstObject'); // 'dog'
ap.set('content', ['amoeba', 'paramecium']);
ap.get('firstObject'); // 'amoeba'
```
This class can also be useful as a layer to transform the contents of
an array, as they are accessed. This can be done by overriding
`objectAtContent`:
```javascript
import { A } from '@ember/array';
import ArrayProxy from '@ember/array/proxy';
let pets = ['dog', 'cat', 'fish'];
let ap = ArrayProxy.create({
content: A(pets),
objectAtContent: function(idx) {
return this.get('content').objectAt(idx).toUpperCase();
}
});
ap.get('firstObject'); // . 'DOG'
```
When overriding this class, it is important to place the call to
`_super` *after* setting `content` so the internal observers have
a chance to fire properly:
```javascript
import { A } from '@ember/array';
import ArrayProxy from '@ember/array/proxy';
export default ArrayProxy.extend({
init() {
this.set('content', A(['dog', 'cat', 'fish']));
this._super(...arguments);
}
});
```
@class ArrayProxy
@extends EmberObject
@uses MutableArray
@public
*/
class ArrayProxy extends _object.default {
init() {
super.init(...arguments);
/*
`this._objectsDirtyIndex` determines which indexes in the `this._objects`
cache are dirty.
If `this._objectsDirtyIndex === -1` then no indexes are dirty.
Otherwise, an index `i` is dirty if `i >= this._objectsDirtyIndex`.
Calling `objectAt` with a dirty index will cause the `this._objects`
cache to be recomputed.
*/
this._objectsDirtyIndex = 0;
this._objects = null;
this._lengthDirty = true;
this._length = 0;
this._arrangedContent = null;
this._arrangedContentIsUpdating = false;
this._arrangedContentTag = null;
this._arrangedContentRevision = null;
this._lengthTag = null;
this._arrTag = null;
(0, _manager.setCustomTagFor)(this, customTagForArrayProxy);
}
[_metal.PROPERTY_DID_CHANGE]() {
this._revalidate();
}
willDestroy() {
this._removeArrangedContentArrayObserver();
}
/**
The content array. Must be an object that implements `Array` and/or
`MutableArray.`
@property content
@type EmberArray
@public
*/
/**
Should actually retrieve the object at the specified index from the
content. You can override this method in subclasses to transform the
content item to something new.
This method will only be called if content is non-`null`.
@method objectAtContent
@param {Number} idx The index to retrieve.
@return {Object} the value or undefined if none found
@public
*/
objectAtContent(idx) {
return (0, _metal.objectAt)((0, _metal.get)(this, 'arrangedContent'), idx);
} // See additional docs for `replace` from `MutableArray`:
// https://api.emberjs.com/ember/release/classes/MutableArray/methods/replace?anchor=replace
replace(idx, amt, objects) {
(true && !((0, _metal.get)(this, 'arrangedContent') === (0, _metal.get)(this, 'content')) && (0, _debug.assert)('Mutating an arranged ArrayProxy is not allowed', (0, _metal.get)(this, 'arrangedContent') === (0, _metal.get)(this, 'content')));
this.replaceContent(idx, amt, objects);
}
/**
Should actually replace the specified objects on the content array.
You can override this method in subclasses to transform the content item
into something new.
This method will only be called if content is non-`null`.
@method replaceContent
@param {Number} idx The starting index
@param {Number} amt The number of items to remove from the content.
@param {EmberArray} objects Optional array of objects to insert or null if no
objects.
@return {void}
@public
*/
replaceContent(idx, amt, objects) {
(0, _metal.get)(this, 'content').replace(idx, amt, objects);
} // Overriding objectAt is not supported.
objectAt(idx) {
this._revalidate();
if (this._objects === null) {
this._objects = [];
}
if (this._objectsDirtyIndex !== -1 && idx >= this._objectsDirtyIndex) {
var arrangedContent = (0, _metal.get)(this, 'arrangedContent');
if (arrangedContent) {
var length = this._objects.length = (0, _metal.get)(arrangedContent, 'length');
for (var i = this._objectsDirtyIndex; i < length; i++) {
this._objects[i] = this.objectAtContent(i);
}
} else {
this._objects.length = 0;
}
this._objectsDirtyIndex = -1;
}
return this._objects[idx];
} // Overriding length is not supported.
get length() {
this._revalidate();
if (this._lengthDirty) {
var arrangedContent = (0, _metal.get)(this, 'arrangedContent');
this._length = arrangedContent ? (0, _metal.get)(arrangedContent, 'length') : 0;
this._lengthDirty = false;
}
(0, _validator.consumeTag)(this._lengthTag);
return this._length;
}
set length(value) {
var length = this.length;
var removedCount = length - value;
var added;
if (removedCount === 0) {
return;
} else if (removedCount < 0) {
added = new Array(-removedCount);
removedCount = 0;
}
var content = (0, _metal.get)(this, 'content');
if (content) {
(0, _metal.replace)(content, value, removedCount, added);
this._invalidate();
}
}
_updateArrangedContentArray(arrangedContent) {
var oldLength = this._objects === null ? 0 : this._objects.length;
var newLength = arrangedContent ? (0, _metal.get)(arrangedContent, 'length') : 0;
this._removeArrangedContentArrayObserver();
(0, _metal.arrayContentWillChange)(this, 0, oldLength, newLength);
this._invalidate();
(0, _metal.arrayContentDidChange)(this, 0, oldLength, newLength, false);
this._addArrangedContentArrayObserver(arrangedContent);
}
_addArrangedContentArrayObserver(arrangedContent) {
if (arrangedContent && !arrangedContent.isDestroyed) {
(true && !(arrangedContent !== this) && (0, _debug.assert)("Can't set ArrayProxy's content to itself", arrangedContent !== this));
(true && !((0, _array.isArray)(arrangedContent) || arrangedContent.isDestroyed) && (0, _debug.assert)(`ArrayProxy expects an Array or ArrayProxy, but you passed ${typeof arrangedContent}`, (0, _array.isArray)(arrangedContent) || arrangedContent.isDestroyed));
(0, _metal.addArrayObserver)(arrangedContent, this, ARRAY_OBSERVER_MAPPING);
this._arrangedContent = arrangedContent;
}
}
_removeArrangedContentArrayObserver() {
if (this._arrangedContent) {
(0, _metal.removeArrayObserver)(this._arrangedContent, this, ARRAY_OBSERVER_MAPPING);
}
}
_arrangedContentArrayWillChange() {}
_arrangedContentArrayDidChange(proxy, idx, removedCnt, addedCnt) {
(0, _metal.arrayContentWillChange)(this, idx, removedCnt, addedCnt);
var dirtyIndex = idx;
if (dirtyIndex < 0) {
var length = (0, _metal.get)(this._arrangedContent, 'length');
dirtyIndex += length + removedCnt - addedCnt;
}
if (this._objectsDirtyIndex === -1 || this._objectsDirtyIndex > dirtyIndex) {
this._objectsDirtyIndex = dirtyIndex;
}
this._lengthDirty = true;
(0, _metal.arrayContentDidChange)(this, idx, removedCnt, addedCnt, false);
}
_invalidate() {
this._objectsDirtyIndex = 0;
this._lengthDirty = true;
}
_revalidate() {
if (this._arrangedContentIsUpdating === true) return;
if (this._arrangedContentTag === null || !(0, _validator.validateTag)(this._arrangedContentTag, this._arrangedContentRevision)) {
var arrangedContent = this.get('arrangedContent');
if (this._arrangedContentTag === null) {
// This is the first time the proxy has been setup, only add the observer
// don't trigger any events
this._addArrangedContentArrayObserver(arrangedContent);
} else {
this._arrangedContentIsUpdating = true;
this._updateArrangedContentArray(arrangedContent);
this._arrangedContentIsUpdating = false;
}
var arrangedContentTag = this._arrangedContentTag = (0, _validator.tagFor)(this, 'arrangedContent');
this._arrangedContentRevision = (0, _validator.valueForTag)(this._arrangedContentTag);
if ((0, _utils.isObject)(arrangedContent)) {
this._lengthTag = (0, _validator.combine)([arrangedContentTag, (0, _metal.tagForProperty)(arrangedContent, 'length')]);
this._arrTag = (0, _validator.combine)([arrangedContentTag, (0, _metal.tagForProperty)(arrangedContent, '[]')]);
} else {
this._lengthTag = this._arrTag = arrangedContentTag;
}
}
}
}
_exports.default = ArrayProxy;
ArrayProxy.reopen(_array.MutableArray, {
/**
The array that the proxy pretends to be. In the default `ArrayProxy`
implementation, this and `content` are the same. Subclasses of `ArrayProxy`
can override this property to provide things like sorting and filtering.
@property arrangedContent
@public
*/
arrangedContent: (0, _metal.alias)('content')
});
});
define("@ember/-internals/runtime/lib/system/core_object", ["exports", "@ember/-internals/container", "@ember/-internals/owner", "@ember/-internals/utils", "@ember/-internals/meta", "@ember/-internals/metal", "@ember/-internals/runtime/lib/mixins/action_handler", "@ember/debug", "@glimmer/util", "@glimmer/destroyable", "@glimmer/owner"], function (_exports, _container, _owner, _utils, _meta2, _metal, _action_handler, _debug, _util, _destroyable, _owner2) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module @ember/object
*/
var reopen = _metal.Mixin.prototype.reopen;
var wasApplied = new _util._WeakSet();
var prototypeMixinMap = new WeakMap();
var initCalled = true
/* DEBUG */
? new _util._WeakSet() : undefined; // only used in debug builds to enable the proxy trap
var destroyCalled = new Set();
function ensureDestroyCalled(instance) {
if (!destroyCalled.has(instance)) {
instance.destroy();
}
}
function initialize(obj, properties) {
var m = (0, _meta2.meta)(obj);
if (properties !== undefined) {
(true && !(typeof properties === 'object' && properties !== null) && (0, _debug.assert)('EmberObject.create only accepts objects.', typeof properties === 'object' && properties !== null));
(true && !(!(properties instanceof _metal.Mixin)) && (0, _debug.assert)('EmberObject.create no longer supports mixing in other ' + 'definitions, use .extend & .create separately instead.', !(properties instanceof _metal.Mixin)));
var concatenatedProperties = obj.concatenatedProperties;
var mergedProperties = obj.mergedProperties;
var hasConcatenatedProps = concatenatedProperties !== undefined && concatenatedProperties.length > 0;
var hasMergedProps = mergedProperties !== undefined && mergedProperties.length > 0;
var keyNames = Object.keys(properties);
for (var i = 0; i < keyNames.length; i++) {
var keyName = keyNames[i];
var value = properties[keyName];
(true && !(!(0, _metal.isClassicDecorator)(value)) && (0, _debug.assert)('EmberObject.create no longer supports defining computed ' + 'properties. Define computed properties using extend() or reopen() ' + 'before calling create().', !(0, _metal.isClassicDecorator)(value)));
(true && !(!(typeof value === 'function' && value.toString().indexOf('._super') !== -1)) && (0, _debug.assert)('EmberObject.create no longer supports defining methods that call _super.', !(typeof value === 'function' && value.toString().indexOf('._super') !== -1)));
(true && !(!(keyName === 'actions' && _action_handler.default.detect(obj))) && (0, _debug.assert)('`actions` must be provided at extend time, not at create time, ' + 'when Ember.ActionHandler is used (i.e. views, controllers & routes).', !(keyName === 'actions' && _action_handler.default.detect(obj))));
var possibleDesc = (0, _metal.descriptorForProperty)(obj, keyName, m);
var isDescriptor = possibleDesc !== undefined;
if (!isDescriptor) {
if (hasConcatenatedProps && concatenatedProperties.indexOf(keyName) > -1) {
var baseValue = obj[keyName];
if (baseValue) {
value = (0, _utils.makeArray)(baseValue).concat(value);
} else {
value = (0, _utils.makeArray)(value);
}
}
if (hasMergedProps && mergedProperties.indexOf(keyName) > -1) {
var _baseValue = obj[keyName];
value = Object.assign({}, _baseValue, value);
}
}
if (isDescriptor) {
possibleDesc.set(obj, keyName, value);
} else if (typeof obj.setUnknownProperty === 'function' && !(keyName in obj)) {
obj.setUnknownProperty(keyName, value);
} else {
if (true
/* DEBUG */
) {
(0, _metal.defineProperty)(obj, keyName, null, value, m); // setup mandatory setter
} else {
obj[keyName] = value;
}
}
}
} // using DEBUG here to avoid the extraneous variable when not needed
if (true
/* DEBUG */
) {
initCalled.add(obj);
}
obj.init(properties);
m.unsetInitializing();
var observerEvents = m.observerEvents();
if (observerEvents !== undefined) {
for (var _i = 0; _i < observerEvents.length; _i++) {
(0, _metal.activateObserver)(obj, observerEvents[_i].event, observerEvents[_i].sync);
}
}
(0, _metal.sendEvent)(obj, 'init', undefined, undefined, undefined, m);
}
/**
`CoreObject` is the base class for all Ember constructs. It establishes a
class system based on Ember's Mixin system, and provides the basis for the
Ember Object Model. `CoreObject` should generally not be used directly,
instead you should use `EmberObject`.
## Usage
You can define a class by extending from `CoreObject` using the `extend`
method:
```js
const Person = CoreObject.extend({
name: 'Tomster',
});
```
For detailed usage, see the [Object Model](https://guides.emberjs.com/release/object-model/)
section of the guides.
## Usage with Native Classes
Native JavaScript `class` syntax can be used to extend from any `CoreObject`
based class:
```js
class Person extends CoreObject {
init() {
super.init(...arguments);
this.name = 'Tomster';
}
}
```
Some notes about `class` usage:
* `new` syntax is not currently supported with classes that extend from
`EmberObject` or `CoreObject`. You must continue to use the `create` method
when making new instances of classes, even if they are defined using native
class syntax. If you want to use `new` syntax, consider creating classes
which do _not_ extend from `EmberObject` or `CoreObject`. Ember features,
such as computed properties and decorators, will still work with base-less
classes.
* Instead of using `this._super()`, you must use standard `super` syntax in
native classes. See the [MDN docs on classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Super_class_calls_with_super)
for more details.
* Native classes support using [constructors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Constructor)
to set up newly-created instances. Ember uses these to, among other things,
support features that need to retrieve other entities by name, like Service
injection and `getOwner`. To ensure your custom instance setup logic takes
place after this important work is done, avoid using the `constructor` in
favor of `init`.
* Properties passed to `create` will be available on the instance by the time
`init` runs, so any code that requires these values should work at that
time.
* Using native classes, and switching back to the old Ember Object model is
fully supported.
@class CoreObject
@public
*/
class CoreObject {
constructor(owner) {
this[_owner2.OWNER] = owner; // prepare prototype...
this.constructor.proto();
var self = this;
if (true
/* DEBUG */
&& typeof self.unknownProperty === 'function') {
var messageFor = (obj, property) => {
return `You attempted to access the \`${String(property)}\` property (of ${obj}).\n` + `Since Ember 3.1, this is usually fine as you no longer need to use \`.get()\`\n` + `to access computed properties. However, in this case, the object in question\n` + `is a special kind of Ember object (a proxy). Therefore, it is still necessary\n` + `to use \`.get('${String(property)}')\` in this case.\n\n` + `If you encountered this error because of third-party code that you don't control,\n` + `there is more information at https://github.com/emberjs/ember.js/issues/16148, and\n` + `you can help us improve this error message by telling us more about what happened in\n` + `this situation.`;
};
/* globals Proxy Reflect */
self = new Proxy(this, {
get(target, property, receiver) {
if (property === _metal.PROXY_CONTENT) {
return target;
} else if ( // init called will be set on the proxy, not the target, so get with the receiver
!initCalled.has(receiver) || typeof property === 'symbol' || (0, _utils.isInternalSymbol)(property) || property === 'toJSON' || property === 'toString' || property === 'toStringExtension' || property === 'didDefineProperty' || property === 'willWatchProperty' || property === 'didUnwatchProperty' || property === 'didAddListener' || property === 'didRemoveListener' || property === 'isDescriptor' || property === '_onLookup' || property in target) {
return Reflect.get(target, property, receiver);
}
var value = target.unknownProperty.call(receiver, property);
if (typeof value !== 'function') {
(true && !(value === undefined || value === null) && (0, _debug.assert)(messageFor(receiver, property), value === undefined || value === null));
}
}
});
}
(0, _destroyable.registerDestructor)(self, ensureDestroyCalled, true);
(0, _destroyable.registerDestructor)(self, () => self.willDestroy()); // disable chains
var m = (0, _meta2.meta)(self);
m.setInitializing(); // only return when in debug builds and `self` is the proxy created above
if (true
/* DEBUG */
&& self !== this) {
return self;
}
}
reopen(...args) {
(0, _metal.applyMixin)(this, args);
return this;
}
/**
An overridable method called when objects are instantiated. By default,
does nothing unless it is overridden during class definition.
Example:
```javascript
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
init() {
alert(`Name is ${this.get('name')}`);
}
});
let steve = Person.create({
name: 'Steve'
});
// alerts 'Name is Steve'.
```
NOTE: If you do override `init` for a framework class like `Component`
from `@ember/component`, be sure to call `this._super(...arguments)`
in your `init` declaration!
If you don't, Ember may not have an opportunity to
do important setup work, and you'll see strange behavior in your
application.
@method init
@public
*/
init() {}
/**
Defines the properties that will be concatenated from the superclass
(instead of overridden).
By default, when you extend an Ember class a property defined in
the subclass overrides a property with the same name that is defined
in the superclass. However, there are some cases where it is preferable
to build up a property's value by combining the superclass' property
value with the subclass' value. An example of this in use within Ember
is the `classNames` property of `Component` from `@ember/component`.
Here is some sample code showing the difference between a concatenated
property and a normal one:
```javascript
import EmberObject from '@ember/object';
const Bar = EmberObject.extend({
// Configure which properties to concatenate
concatenatedProperties: ['concatenatedProperty'],
someNonConcatenatedProperty: ['bar'],
concatenatedProperty: ['bar']
});
const FooBar = Bar.extend({
someNonConcatenatedProperty: ['foo'],
concatenatedProperty: ['foo']
});
let fooBar = FooBar.create();
fooBar.get('someNonConcatenatedProperty'); // ['foo']
fooBar.get('concatenatedProperty'); // ['bar', 'foo']
```
This behavior extends to object creation as well. Continuing the
above example:
```javascript
let fooBar = FooBar.create({
someNonConcatenatedProperty: ['baz'],
concatenatedProperty: ['baz']
})
fooBar.get('someNonConcatenatedProperty'); // ['baz']
fooBar.get('concatenatedProperty'); // ['bar', 'foo', 'baz']
```
Adding a single property that is not an array will just add it in the array:
```javascript
let fooBar = FooBar.create({
concatenatedProperty: 'baz'
})
view.get('concatenatedProperty'); // ['bar', 'foo', 'baz']
```
Using the `concatenatedProperties` property, we can tell Ember to mix the
content of the properties.
In `Component` the `classNames`, `classNameBindings` and
`attributeBindings` properties are concatenated.
This feature is available for you to use throughout the Ember object model,
although typical app developers are likely to use it infrequently. Since
it changes expectations about behavior of properties, you should properly
document its usage in each individual concatenated property (to not
mislead your users to think they can override the property in a subclass).
@property concatenatedProperties
@type Array
@default null
@public
*/
/**
Defines the properties that will be merged from the superclass
(instead of overridden).
By default, when you extend an Ember class a property defined in
the subclass overrides a property with the same name that is defined
in the superclass. However, there are some cases where it is preferable
to build up a property's value by merging the superclass property value
with the subclass property's value. An example of this in use within Ember
is the `queryParams` property of routes.
Here is some sample code showing the difference between a merged
property and a normal one:
```javascript
import EmberObject from '@ember/object';
const Bar = EmberObject.extend({
// Configure which properties are to be merged
mergedProperties: ['mergedProperty'],
someNonMergedProperty: {
nonMerged: 'superclass value of nonMerged'
},
mergedProperty: {
page: { replace: false },
limit: { replace: true }
}
});
const FooBar = Bar.extend({
someNonMergedProperty: {
completelyNonMerged: 'subclass value of nonMerged'
},
mergedProperty: {
limit: { replace: false }
}
});
let fooBar = FooBar.create();
fooBar.get('someNonMergedProperty');
// => { completelyNonMerged: 'subclass value of nonMerged' }
//
// Note the entire object, including the nonMerged property of
// the superclass object, has been replaced
fooBar.get('mergedProperty');
// => {
// page: {replace: false},
// limit: {replace: false}
// }
//
// Note the page remains from the superclass, and the
// `limit` property's value of `false` has been merged from
// the subclass.
```
This behavior is not available during object `create` calls. It is only
available at `extend` time.
In `Route` the `queryParams` property is merged.
This feature is available for you to use throughout the Ember object model,
although typical app developers are likely to use it infrequently. Since
it changes expectations about behavior of properties, you should properly
document its usage in each individual merged property (to not
mislead your users to think they can override the property in a subclass).
@property mergedProperties
@type Array
@default null
@public
*/
/**
Destroyed object property flag.
if this property is `true` the observers and bindings were already
removed by the effect of calling the `destroy()` method.
@property isDestroyed
@default false
@public
*/
get isDestroyed() {
return (0, _destroyable.isDestroyed)(this);
}
set isDestroyed(value) {
(true && !(false) && (0, _debug.assert)(`You cannot set \`${this}.isDestroyed\` directly, please use \`.destroy()\`.`, false));
}
/**
Destruction scheduled flag. The `destroy()` method has been called.
The object stays intact until the end of the run loop at which point
the `isDestroyed` flag is set.
@property isDestroying
@default false
@public
*/
get isDestroying() {
return (0, _destroyable.isDestroying)(this);
}
set isDestroying(value) {
(true && !(false) && (0, _debug.assert)(`You cannot set \`${this}.isDestroying\` directly, please use \`.destroy()\`.`, false));
}
/**
Destroys an object by setting the `isDestroyed` flag and removing its
metadata, which effectively destroys observers and bindings.
If you try to set a property on a destroyed object, an exception will be
raised.
Note that destruction is scheduled for the end of the run loop and does not
happen immediately. It will set an isDestroying flag immediately.
@method destroy
@return {EmberObject} receiver
@public
*/
destroy() {
// Used to ensure that manually calling `.destroy()` does not immediately call destroy again
destroyCalled.add(this);
try {
(0, _destroyable.destroy)(this);
} finally {
destroyCalled.delete(this);
}
return this;
}
/**
Override to implement teardown.
@method willDestroy
@public
*/
willDestroy() {}
/**
Returns a string representation which attempts to provide more information
than Javascript's `toString` typically does, in a generic way for all Ember
objects.
```javascript
import EmberObject from '@ember/object';
const Person = EmberObject.extend();
person = Person.create();
person.toString(); //=> "<Person:ember1024>"
```
If the object's class is not defined on an Ember namespace, it will
indicate it is a subclass of the registered superclass:
```javascript
const Student = Person.extend();
let student = Student.create();
student.toString(); //=> "<(subclass of Person):ember1025>"
```
If the method `toStringExtension` is defined, its return value will be
included in the output.
```javascript
const Teacher = Person.extend({
toStringExtension() {
return this.get('fullName');
}
});
teacher = Teacher.create();
teacher.toString(); //=> "<Teacher:ember1026:Tom Dale>"
```
@method toString
@return {String} string representation
@public
*/
toString() {
var hasToStringExtension = typeof this.toStringExtension === 'function';
var extension = hasToStringExtension ? `:${this.toStringExtension()}` : '';
return `<${(0, _container.getFactoryFor)(this) || '(unknown)'}:${(0, _utils.guidFor)(this)}${extension}>`;
}
/**
Creates a new subclass.
```javascript
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
say(thing) {
alert(thing);
}
});
```
This defines a new subclass of EmberObject: `Person`. It contains one method: `say()`.
You can also create a subclass from any existing class by calling its `extend()` method.
For example, you might want to create a subclass of Ember's built-in `Component` class:
```javascript
import Component from '@ember/component';
const PersonComponent = Component.extend({
tagName: 'li',
classNameBindings: ['isAdministrator']
});
```
When defining a subclass, you can override methods but still access the
implementation of your parent class by calling the special `_super()` method:
```javascript
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
say(thing) {
let name = this.get('name');
alert(`${name} says: ${thing}`);
}
});
const Soldier = Person.extend({
say(thing) {
this._super(`${thing}, sir!`);
},
march(numberOfHours) {
alert(`${this.get('name')} marches for ${numberOfHours} hours.`);
}
});
let yehuda = Soldier.create({
name: 'Yehuda Katz'
});
yehuda.say('Yes'); // alerts "Yehuda Katz says: Yes, sir!"
```
The `create()` on line #17 creates an *instance* of the `Soldier` class.
The `extend()` on line #8 creates a *subclass* of `Person`. Any instance
of the `Person` class will *not* have the `march()` method.
You can also pass `Mixin` classes to add additional properties to the subclass.
```javascript
import EmberObject from '@ember/object';
import Mixin from '@ember/object/mixin';
const Person = EmberObject.extend({
say(thing) {
alert(`${this.get('name')} says: ${thing}`);
}
});
const SingingMixin = Mixin.create({
sing(thing) {
alert(`${this.get('name')} sings: la la la ${thing}`);
}
});
const BroadwayStar = Person.extend(SingingMixin, {
dance() {
alert(`${this.get('name')} dances: tap tap tap tap `);
}
});
```
The `BroadwayStar` class contains three methods: `say()`, `sing()`, and `dance()`.
@method extend
@static
@for @ember/object
@param {Mixin} [mixins]* One or more Mixin classes
@param {Object} [arguments]* Object containing values to use within the new class
@public
*/
static extend() {
var Class = class extends this {};
reopen.apply(Class.PrototypeMixin, arguments);
return Class;
}
/**
Creates an instance of a class. Accepts either no arguments, or an object
containing values to initialize the newly instantiated object with.
```javascript
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
helloWorld() {
alert(`Hi, my name is ${this.get('name')}`);
}
});
let tom = Person.create({
name: 'Tom Dale'
});
tom.helloWorld(); // alerts "Hi, my name is Tom Dale".
```
`create` will call the `init` function if defined during
`AnyObject.extend`
If no arguments are passed to `create`, it will not set values to the new
instance during initialization:
```javascript
let noName = Person.create();
noName.helloWorld(); // alerts undefined
```
NOTE: For performance reasons, you cannot declare methods or computed
properties during `create`. You should instead declare methods and computed
properties when using `extend`.
@method create
@for @ember/object
@static
@param [arguments]*
@public
*/
static create(props, extra) {
var instance;
if (props !== undefined) {
instance = new this((0, _owner.getOwner)(props));
(0, _container.setFactoryFor)(instance, (0, _container.getFactoryFor)(props));
} else {
instance = new this();
}
if (extra === undefined) {
initialize(instance, props);
} else {
initialize(instance, flattenProps.apply(this, arguments));
}
return instance;
}
/**
Augments a constructor's prototype with additional
properties and functions:
```javascript
import EmberObject from '@ember/object';
const MyObject = EmberObject.extend({
name: 'an object'
});
o = MyObject.create();
o.get('name'); // 'an object'
MyObject.reopen({
say(msg) {
console.log(msg);
}
});
o2 = MyObject.create();
o2.say('hello'); // logs "hello"
o.say('goodbye'); // logs "goodbye"
```
To add functions and properties to the constructor itself,
see `reopenClass`
@method reopen
@for @ember/object
@static
@public
*/
static reopen() {
this.willReopen();
reopen.apply(this.PrototypeMixin, arguments);
return this;
}
static willReopen() {
var p = this.prototype;
if (wasApplied.has(p)) {
wasApplied.delete(p); // If the base mixin already exists and was applied, create a new mixin to
// make sure that it gets properly applied. Reusing the same mixin after
// the first `proto` call will cause it to get skipped.
if (prototypeMixinMap.has(this)) {
prototypeMixinMap.set(this, _metal.Mixin.create(this.PrototypeMixin));
}
}
}
/**
Augments a constructor's own properties and functions:
```javascript
import EmberObject from '@ember/object';
const MyObject = EmberObject.extend({
name: 'an object'
});
MyObject.reopenClass({
canBuild: false
});
MyObject.canBuild; // false
o = MyObject.create();
```
In other words, this creates static properties and functions for the class.
These are only available on the class and not on any instance of that class.
```javascript
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
name: '',
sayHello() {
alert(`Hello. My name is ${this.get('name')}`);
}
});
Person.reopenClass({
species: 'Homo sapiens',
createPerson(name) {
return Person.create({ name });
}
});
let tom = Person.create({
name: 'Tom Dale'
});
let yehuda = Person.createPerson('Yehuda Katz');
tom.sayHello(); // "Hello. My name is Tom Dale"
yehuda.sayHello(); // "Hello. My name is Yehuda Katz"
alert(Person.species); // "Homo sapiens"
```
Note that `species` and `createPerson` are *not* valid on the `tom` and `yehuda`
variables. They are only valid on `Person`.
To add functions and properties to instances of
a constructor by extending the constructor's prototype
see `reopen`
@method reopenClass
@for @ember/object
@static
@public
*/
static reopenClass() {
(0, _metal.applyMixin)(this, arguments);
return this;
}
static detect(obj) {
if ('function' !== typeof obj) {
return false;
}
while (obj) {
if (obj === this) {
return true;
}
obj = obj.superclass;
}
return false;
}
static detectInstance(obj) {
return obj instanceof this;
}
/**
In some cases, you may want to annotate computed properties with additional
metadata about how they function or what values they operate on. For
example, computed property functions may close over variables that are then
no longer available for introspection.
You can pass a hash of these values to a computed property like this:
```javascript
import { computed } from '@ember/object';
person: computed(function() {
let personId = this.get('personId');
return Person.create({ id: personId });
}).meta({ type: Person })
```
Once you've done this, you can retrieve the values saved to the computed
property from your class like this:
```javascript
MyClass.metaForProperty('person');
```
This will return the original hash that was passed to `meta()`.
@static
@method metaForProperty
@param key {String} property name
@private
*/
static metaForProperty(key) {
var proto = this.proto(); // ensure prototype is initialized
var possibleDesc = (0, _metal.descriptorForProperty)(proto, key);
(true && !(possibleDesc !== undefined) && (0, _debug.assert)(`metaForProperty() could not find a computed property with key '${key}'.`, possibleDesc !== undefined));
return possibleDesc._meta || {};
}
/**
Iterate over each computed property for the class, passing its name
and any associated metadata (see `metaForProperty`) to the callback.
@static
@method eachComputedProperty
@param {Function} callback
@param {Object} binding
@private
*/
static eachComputedProperty(callback, binding = this) {
this.proto(); // ensure prototype is initialized
var empty = {};
(0, _meta2.meta)(this.prototype).forEachDescriptors((name, descriptor) => {
if (descriptor.enumerable) {
var _meta = descriptor._meta || empty;
callback.call(binding, name, _meta);
}
});
}
static get PrototypeMixin() {
var prototypeMixin = prototypeMixinMap.get(this);
if (prototypeMixin === undefined) {
prototypeMixin = _metal.Mixin.create();
prototypeMixin.ownerConstructor = this;
prototypeMixinMap.set(this, prototypeMixin);
}
return prototypeMixin;
}
static get superclass() {
var c = Object.getPrototypeOf(this);
return c !== Function.prototype ? c : undefined;
}
static proto() {
var p = this.prototype;
if (!wasApplied.has(p)) {
wasApplied.add(p);
var parent = this.superclass;
if (parent) {
parent.proto();
} // If the prototype mixin exists, apply it. In the case of native classes,
// it will not exist (unless the class has been reopened).
if (prototypeMixinMap.has(this)) {
this.PrototypeMixin.apply(p);
}
}
return p;
}
static toString() {
return `<${(0, _container.getFactoryFor)(this) || '(unknown)'}:constructor>`;
}
}
CoreObject.isClass = true;
CoreObject.isMethod = false;
function flattenProps(...props) {
var {
concatenatedProperties,
mergedProperties
} = this;
var hasConcatenatedProps = concatenatedProperties !== undefined && concatenatedProperties.length > 0;
var hasMergedProps = mergedProperties !== undefined && mergedProperties.length > 0;
var initProperties = {};
for (var i = 0; i < props.length; i++) {
var properties = props[i];
(true && !(!(properties instanceof _metal.Mixin)) && (0, _debug.assert)('EmberObject.create no longer supports mixing in other ' + 'definitions, use .extend & .create separately instead.', !(properties instanceof _metal.Mixin)));
var keyNames = Object.keys(properties);
for (var j = 0, k = keyNames.length; j < k; j++) {
var keyName = keyNames[j];
var value = properties[keyName];
if (hasConcatenatedProps && concatenatedProperties.indexOf(keyName) > -1) {
var baseValue = initProperties[keyName];
if (baseValue) {
value = (0, _utils.makeArray)(baseValue).concat(value);
} else {
value = (0, _utils.makeArray)(value);
}
}
if (hasMergedProps && mergedProperties.indexOf(keyName) > -1) {
var _baseValue2 = initProperties[keyName];
value = Object.assign({}, _baseValue2, value);
}
initProperties[keyName] = value;
}
}
return initProperties;
}
if (true
/* DEBUG */
) {
/**
Provides lookup-time type validation for injected properties.
@private
@method _onLookup
*/
CoreObject._onLookup = function injectedPropertyAssertion(debugContainerKey) {
var [type] = debugContainerKey.split(':');
var proto = this.proto();
for (var key in proto) {
var desc = (0, _metal.descriptorForProperty)(proto, key);
if (desc && _metal.DEBUG_INJECTION_FUNCTIONS.has(desc._getter)) {
(true && !(type === 'controller' || _metal.DEBUG_INJECTION_FUNCTIONS.get(desc._getter).type !== 'controller') && (0, _debug.assert)(`Defining \`${key}\` as an injected controller property on a non-controller (\`${debugContainerKey}\`) is not allowed.`, type === 'controller' || _metal.DEBUG_INJECTION_FUNCTIONS.get(desc._getter).type !== 'controller'));
}
}
};
/**
Returns a hash of property names and container names that injected
properties will lookup on the container lazily.
@method _lazyInjections
@return {Object} Hash of all lazy injected property keys to container names
@private
*/
CoreObject._lazyInjections = function () {
var injections = {};
var proto = this.proto();
var key;
var desc;
for (key in proto) {
desc = (0, _metal.descriptorForProperty)(proto, key);
if (desc && _metal.DEBUG_INJECTION_FUNCTIONS.has(desc._getter)) {
var {
namespace,
source,
type,
name
} = _metal.DEBUG_INJECTION_FUNCTIONS.get(desc._getter);
injections[key] = {
namespace,
source,
specifier: `${type}:${name || key}`
};
}
}
return injections;
};
}
var _default = CoreObject;
_exports.default = _default;
});
define("@ember/-internals/runtime/lib/system/namespace", ["exports", "@ember/-internals/metal", "@ember/-internals/utils", "@ember/-internals/runtime/lib/system/object"], function (_exports, _metal, _utils, _object) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module ember
*/
// Preloaded into namespaces
/**
A Namespace is an object usually used to contain other objects or methods
such as an application or framework. Create a namespace anytime you want
to define one of these new containers.
# Example Usage
```javascript
MyFramework = Ember.Namespace.create({
VERSION: '1.0.0'
});
```
@class Namespace
@namespace Ember
@extends EmberObject
@public
*/
class Namespace extends _object.default {
init() {
(0, _metal.addNamespace)(this);
}
toString() {
var name = (0, _metal.get)(this, 'name') || (0, _metal.get)(this, 'modulePrefix');
if (name) {
return name;
}
(0, _metal.findNamespaces)();
name = (0, _utils.getName)(this);
if (name === undefined) {
name = (0, _utils.guidFor)(this);
(0, _utils.setName)(this, name);
}
return name;
}
nameClasses() {
(0, _metal.processNamespace)(this);
}
destroy() {
(0, _metal.removeNamespace)(this);
super.destroy();
}
}
_exports.default = Namespace;
Namespace.prototype.isNamespace = true;
Namespace.NAMESPACES = _metal.NAMESPACES;
Namespace.NAMESPACES_BY_ID = _metal.NAMESPACES_BY_ID;
Namespace.processAll = _metal.processAllNamespaces;
Namespace.byName = _metal.findNamespace;
});
define("@ember/-internals/runtime/lib/system/object", ["exports", "@ember/-internals/container", "@ember/-internals/utils", "@ember/-internals/metal", "@ember/-internals/runtime/lib/system/core_object", "@ember/-internals/runtime/lib/mixins/observable", "@ember/debug"], function (_exports, _container, _utils, _metal, _core_object, _observable, _debug) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.FrameworkObject = _exports.default = void 0;
/**
@module @ember/object
*/
/**
`EmberObject` is the main base class for all Ember objects. It is a subclass
of `CoreObject` with the `Observable` mixin applied. For details,
see the documentation for each of these.
@class EmberObject
@extends CoreObject
@uses Observable
@public
*/
class EmberObject extends _core_object.default {
get _debugContainerKey() {
var factory = (0, _container.getFactoryFor)(this);
return factory !== undefined && factory.fullName;
}
}
_exports.default = EmberObject;
_observable.default.apply(EmberObject.prototype);
var FrameworkObject;
_exports.FrameworkObject = FrameworkObject;
_exports.FrameworkObject = FrameworkObject = class FrameworkObject extends _core_object.default {
get _debugContainerKey() {
var factory = (0, _container.getFactoryFor)(this);
return factory !== undefined && factory.fullName;
}
};
_observable.default.apply(FrameworkObject.prototype);
if (true
/* DEBUG */
) {
var INIT_WAS_CALLED = (0, _utils.symbol)('INIT_WAS_CALLED');
var ASSERT_INIT_WAS_CALLED = (0, _utils.symbol)('ASSERT_INIT_WAS_CALLED');
_exports.FrameworkObject = FrameworkObject = class DebugFrameworkObject extends EmberObject {
init() {
super.init(...arguments);
this[INIT_WAS_CALLED] = true;
}
[ASSERT_INIT_WAS_CALLED]() {
(true && !(this[INIT_WAS_CALLED]) && (0, _debug.assert)(`You must call \`super.init(...arguments);\` or \`this._super(...arguments)\` when overriding \`init\` on a framework object. Please update ${this} to call \`super.init(...arguments);\` from \`init\` when using native classes or \`this._super(...arguments)\` when using \`EmberObject.extend()\`.`, this[INIT_WAS_CALLED]));
}
};
(0, _metal.addListener)(FrameworkObject.prototype, 'init', null, ASSERT_INIT_WAS_CALLED);
}
});
define("@ember/-internals/runtime/lib/system/object_proxy", ["exports", "@ember/-internals/runtime/lib/system/object", "@ember/-internals/runtime/lib/mixins/-proxy"], function (_exports, _object, _proxy) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
`ObjectProxy` forwards all properties not defined by the proxy itself
to a proxied `content` object.
```javascript
import EmberObject from '@ember/object';
import ObjectProxy from '@ember/object/proxy';
let exampleObject = EmberObject.create({
name: 'Foo'
});
let exampleProxy = ObjectProxy.create({
content: exampleObject
});
// Access and change existing properties
exampleProxy.get('name'); // 'Foo'
exampleProxy.set('name', 'Bar');
exampleObject.get('name'); // 'Bar'
// Create new 'description' property on `exampleObject`
exampleProxy.set('description', 'Foo is a whizboo baz');
exampleObject.get('description'); // 'Foo is a whizboo baz'
```
While `content` is unset, setting a property to be delegated will throw an
Error.
```javascript
import ObjectProxy from '@ember/object/proxy';
let exampleProxy = ObjectProxy.create({
content: null,
flag: null
});
exampleProxy.set('flag', true);
exampleProxy.get('flag'); // true
exampleProxy.get('foo'); // undefined
exampleProxy.set('foo', 'data'); // throws Error
```
Delegated properties can be bound to and will change when content is updated.
Computed properties on the proxy itself can depend on delegated properties.
```javascript
import { computed } from '@ember/object';
import ObjectProxy from '@ember/object/proxy';
ProxyWithComputedProperty = ObjectProxy.extend({
fullName: computed('firstName', 'lastName', function() {
var firstName = this.get('firstName'),
lastName = this.get('lastName');
if (firstName && lastName) {
return firstName + ' ' + lastName;
}
return firstName || lastName;
})
});
let exampleProxy = ProxyWithComputedProperty.create();
exampleProxy.get('fullName'); // undefined
exampleProxy.set('content', {
firstName: 'Tom', lastName: 'Dale'
}); // triggers property change for fullName on proxy
exampleProxy.get('fullName'); // 'Tom Dale'
```
@class ObjectProxy
@extends EmberObject
@uses Ember.ProxyMixin
@public
*/
class ObjectProxy extends _object.default {}
_exports.default = ObjectProxy;
ObjectProxy.PrototypeMixin.reopen(_proxy.default);
});
define("@ember/-internals/runtime/lib/type-of", ["exports", "@ember/-internals/runtime/lib/system/core_object"], function (_exports, _core_object) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.typeOf = typeOf;
// ........................................
// TYPING & ARRAY MESSAGING
//
var TYPE_MAP = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object AsyncFunction]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regexp',
'[object Object]': 'object',
'[object FileList]': 'filelist'
};
var {
toString
} = Object.prototype;
/**
@module @ember/utils
*/
/**
Returns a consistent type for the passed object.
Use this instead of the built-in `typeof` to get the type of an item.
It will return the same result across all browsers and includes a bit
more detail. Here is what will be returned:
| Return Value | Meaning |
|---------------|------------------------------------------------------|
| 'string' | String primitive or String object. |
| 'number' | Number primitive or Number object. |
| 'boolean' | Boolean primitive or Boolean object. |
| 'null' | Null value |
| 'undefined' | Undefined value |
| 'function' | A function |
| 'array' | An instance of Array |
| 'regexp' | An instance of RegExp |
| 'date' | An instance of Date |
| 'filelist' | An instance of FileList |
| 'class' | An Ember class (created using EmberObject.extend()) |
| 'instance' | An Ember object instance |
| 'error' | An instance of the Error object |
| 'object' | A JavaScript object not inheriting from EmberObject |
Examples:
```javascript
import { A } from '@ember/array';
import { typeOf } from '@ember/utils';
import EmberObject from '@ember/object';
typeOf(); // 'undefined'
typeOf(null); // 'null'
typeOf(undefined); // 'undefined'
typeOf('michael'); // 'string'
typeOf(new String('michael')); // 'string'
typeOf(101); // 'number'
typeOf(new Number(101)); // 'number'
typeOf(true); // 'boolean'
typeOf(new Boolean(true)); // 'boolean'
typeOf(A); // 'function'
typeOf(A()); // 'array'
typeOf([1, 2, 90]); // 'array'
typeOf(/abc/); // 'regexp'
typeOf(new Date()); // 'date'
typeOf(event.target.files); // 'filelist'
typeOf(EmberObject.extend()); // 'class'
typeOf(EmberObject.create()); // 'instance'
typeOf(new Error('teamocil')); // 'error'
// 'normal' JavaScript object
typeOf({ a: 'b' }); // 'object'
```
@method typeOf
@for @ember/utils
@param {Object} item the item to check
@return {String} the type
@public
@static
*/
function typeOf(item) {
if (item === null) {
return 'null';
}
if (item === undefined) {
return 'undefined';
}
var ret = TYPE_MAP[toString.call(item)] || 'object';
if (ret === 'function') {
if (_core_object.default.detect(item)) {
ret = 'class';
}
} else if (ret === 'object') {
if (item instanceof Error) {
ret = 'error';
} else if (item instanceof _core_object.default) {
ret = 'instance';
} else if (item instanceof Date) {
ret = 'date';
}
}
return ret;
}
});
define("@ember/-internals/utils/index", ["exports", "@glimmer/util", "@ember/debug"], function (_exports, _util, _debug) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.enumerableSymbol = enumerableSymbol;
_exports.isInternalSymbol = isInternalSymbol;
_exports.dictionary = makeDictionary;
_exports.uuid = uuid;
_exports.generateGuid = generateGuid;
_exports.guidFor = guidFor;
_exports.intern = intern;
_exports.wrap = wrap;
_exports.observerListenerMetaFor = observerListenerMetaFor;
_exports.setObservers = setObservers;
_exports.setListeners = setListeners;
_exports.inspect = inspect;
_exports.lookupDescriptor = lookupDescriptor;
_exports.canInvoke = canInvoke;
_exports.makeArray = makeArray;
_exports.getName = getName;
_exports.setName = setName;
_exports.toString = toString;
_exports.isObject = isObject;
_exports.isProxy = isProxy;
_exports.setProxy = setProxy;
_exports.setEmberArray = setEmberArray;
_exports.isEmberArray = isEmberArray;
_exports.setWithMandatorySetter = _exports.teardownMandatorySetter = _exports.setupMandatorySetter = _exports.Cache = _exports.ROOT = _exports.checkHasSuper = _exports.GUID_KEY = _exports.getDebugName = _exports.symbol = void 0;
/**
Strongly hint runtimes to intern the provided string.
When do I need to use this function?
For the most part, never. Pre-mature optimization is bad, and often the
runtime does exactly what you need it to, and more often the trade-off isn't
worth it.
Why?
Runtimes store strings in at least 2 different representations:
Ropes and Symbols (interned strings). The Rope provides a memory efficient
data-structure for strings created from concatenation or some other string
manipulation like splitting.
Unfortunately checking equality of different ropes can be quite costly as
runtimes must resort to clever string comparison algorithms. These
algorithms typically cost in proportion to the length of the string.
Luckily, this is where the Symbols (interned strings) shine. As Symbols are
unique by their string content, equality checks can be done by pointer
comparison.
How do I know if my string is a rope or symbol?
Typically (warning general sweeping statement, but truthy in runtimes at
present) static strings created as part of the JS source are interned.
Strings often used for comparisons can be interned at runtime if some
criteria are met. One of these criteria can be the size of the entire rope.
For example, in chrome 38 a rope longer then 12 characters will not
intern, nor will segments of that rope.
Some numbers: http://jsperf.com/eval-vs-keys/8
Known Trick™
@private
@return {String} interned version of the provided string
*/
function intern(str) {
var obj = {};
obj[str] = 1;
for (var key in obj) {
if (key === str) {
return key;
}
}
return str;
}
/**
Returns whether Type(value) is Object.
Useful for checking whether a value is a valid WeakMap key.
Refs: https://tc39.github.io/ecma262/#sec-typeof-operator-runtime-semantics-evaluation
https://tc39.github.io/ecma262/#sec-weakmap.prototype.set
@private
@function isObject
*/
function isObject(value) {
return value !== null && (typeof value === 'object' || typeof value === 'function');
}
/**
@module @ember/object
*/
/**
@private
@return {Number} the uuid
*/
var _uuid = 0;
/**
Generates a universally unique identifier. This method
is used internally by Ember for assisting with
the generation of GUID's and other unique identifiers.
@public
@return {Number} [description]
*/
function uuid() {
return ++_uuid;
}
/**
Prefix used for guids through out Ember.
@private
@property GUID_PREFIX
@for Ember
@type String
@final
*/
var GUID_PREFIX = 'ember'; // Used for guid generation...
var OBJECT_GUIDS = new WeakMap();
var NON_OBJECT_GUIDS = new Map();
/**
A unique key used to assign guids and other private metadata to objects.
If you inspect an object in your browser debugger you will often see these.
They can be safely ignored.
On browsers that support it, these properties are added with enumeration
disabled so they won't show up when you iterate over your properties.
@private
@property GUID_KEY
@for Ember
@type String
@final
*/
var GUID_KEY = intern(`__ember${Date.now()}`);
/**
Generates a new guid, optionally saving the guid to the object that you
pass in. You will rarely need to use this method. Instead you should
call `guidFor(obj)`, which return an existing guid if available.
@private
@method generateGuid
@static
@for @ember/object/internals
@param {Object} [obj] Object the guid will be used for. If passed in, the guid will
be saved on the object and reused whenever you pass the same object
again.
If no object is passed, just generate a new guid.
@param {String} [prefix] Prefix to place in front of the guid. Useful when you want to
separate the guid into separate namespaces.
@return {String} the guid
*/
_exports.GUID_KEY = GUID_KEY;
function generateGuid(obj, prefix = GUID_PREFIX) {
var guid = prefix + uuid();
if (isObject(obj)) {
OBJECT_GUIDS.set(obj, guid);
}
return guid;
}
/**
Returns a unique id for the object. If the object does not yet have a guid,
one will be assigned to it. You can call this on any object,
`EmberObject`-based or not.
You can also use this method on DOM Element objects.
@public
@static
@method guidFor
@for @ember/object/internals
@param {Object} obj any object, string, number, Element, or primitive
@return {String} the unique guid for this instance.
*/
function guidFor(value) {
var guid;
if (isObject(value)) {
guid = OBJECT_GUIDS.get(value);
if (guid === undefined) {
guid = GUID_PREFIX + uuid();
OBJECT_GUIDS.set(value, guid);
}
} else {
guid = NON_OBJECT_GUIDS.get(value);
if (guid === undefined) {
var type = typeof value;
if (type === 'string') {
guid = 'st' + uuid();
} else if (type === 'number') {
guid = 'nu' + uuid();
} else if (type === 'symbol') {
guid = 'sy' + uuid();
} else {
guid = '(' + value + ')';
}
NON_OBJECT_GUIDS.set(value, guid);
}
}
return guid;
}
var GENERATED_SYMBOLS = [];
function isInternalSymbol(possibleSymbol) {
return GENERATED_SYMBOLS.indexOf(possibleSymbol) !== -1;
} // Some legacy symbols still need to be enumerable for a variety of reasons.
// This code exists for that, and as a fallback in IE11. In general, prefer
// `symbol` below when creating a new symbol.
function enumerableSymbol(debugName) {
// TODO: Investigate using platform symbols, but we do not
// want to require non-enumerability for this API, which
// would introduce a large cost.
var id = GUID_KEY + Math.floor(Math.random() * Date.now());
var symbol = intern(`__${debugName}${id}__`);
if (true
/* DEBUG */
) {
GENERATED_SYMBOLS.push(symbol);
}
return symbol;
}
var symbol = Symbol; // the delete is meant to hint at runtimes that this object should remain in
// dictionary mode. This is clearly a runtime specific hack, but currently it
// appears worthwhile in some usecases. Please note, these deletes do increase
// the cost of creation dramatically over a plain Object.create. And as this
// only makes sense for long-lived dictionaries that aren't instantiated often.
_exports.symbol = symbol;
function makeDictionary(parent) {
var dict = Object.create(parent);
dict['_dict'] = null;
delete dict['_dict'];
return dict;
}
var getDebugName;
if (true
/* DEBUG */
) {
var getFunctionName = fn => {
var functionName = fn.name;
if (functionName === undefined) {
var match = Function.prototype.toString.call(fn).match(/function (\w+)\s*\(/);
functionName = match && match[1] || '';
}
return functionName.replace(/^bound /, '');
};
var getObjectName = obj => {
var name;
var className;
if (obj.constructor && obj.constructor !== Object) {
className = getFunctionName(obj.constructor);
}
if ('toString' in obj && obj.toString !== Object.prototype.toString && obj.toString !== Function.prototype.toString) {
name = obj.toString();
} // If the class has a decent looking name, and the `toString` is one of the
// default Ember toStrings, replace the constructor portion of the toString
// with the class name. We check the length of the class name to prevent doing
// this when the value is minified.
if (name && name.match(/<.*:ember\d+>/) && className && className[0] !== '_' && className.length > 2 && className !== 'Class') {
return name.replace(/<.*:/, `<${className}:`);
}
return name || className;
};
var getPrimitiveName = value => {
return String(value);
};
getDebugName = value => {
if (typeof value === 'function') {
return getFunctionName(value) || `(unknown function)`;
} else if (typeof value === 'object' && value !== null) {
return getObjectName(value) || `(unknown object)`;
} else {
return getPrimitiveName(value);
}
};
}
var getDebugName$1 = getDebugName;
_exports.getDebugName = getDebugName$1;
var HAS_SUPER_PATTERN = /\.(_super|call\(this|apply\(this)/;
var fnToString = Function.prototype.toString;
var checkHasSuper = (() => {
var sourceAvailable = fnToString.call(function () {
return this;
}).indexOf('return this') > -1;
if (sourceAvailable) {
return function checkHasSuper(func) {
return HAS_SUPER_PATTERN.test(fnToString.call(func));
};
}
return function checkHasSuper() {
return true;
};
})();
_exports.checkHasSuper = checkHasSuper;
var HAS_SUPER_MAP = new WeakMap();
var ROOT = Object.freeze(function () {});
_exports.ROOT = ROOT;
HAS_SUPER_MAP.set(ROOT, false);
function hasSuper(func) {
var hasSuper = HAS_SUPER_MAP.get(func);
if (hasSuper === undefined) {
hasSuper = checkHasSuper(func);
HAS_SUPER_MAP.set(func, hasSuper);
}
return hasSuper;
}
class ObserverListenerMeta {
constructor() {
this.listeners = undefined;
this.observers = undefined;
}
}
var OBSERVERS_LISTENERS_MAP = new WeakMap();
function createObserverListenerMetaFor(fn) {
var meta = OBSERVERS_LISTENERS_MAP.get(fn);
if (meta === undefined) {
meta = new ObserverListenerMeta();
OBSERVERS_LISTENERS_MAP.set(fn, meta);
}
return meta;
}
function observerListenerMetaFor(fn) {
return OBSERVERS_LISTENERS_MAP.get(fn);
}
function setObservers(func, observers) {
var meta = createObserverListenerMetaFor(func);
meta.observers = observers;
}
function setListeners(func, listeners) {
var meta = createObserverListenerMetaFor(func);
meta.listeners = listeners;
}
var IS_WRAPPED_FUNCTION_SET = new _util._WeakSet();
/**
Wraps the passed function so that `this._super` will point to the superFunc
when the function is invoked. This is the primitive we use to implement
calls to super.
@private
@method wrap
@for Ember
@param {Function} func The function to call
@param {Function} superFunc The super function.
@return {Function} wrapped function.
*/
function wrap(func, superFunc) {
if (!hasSuper(func)) {
return func;
} // ensure an unwrapped super that calls _super is wrapped with a terminal _super
if (!IS_WRAPPED_FUNCTION_SET.has(superFunc) && hasSuper(superFunc)) {
return _wrap(func, _wrap(superFunc, ROOT));
}
return _wrap(func, superFunc);
}
function _wrap(func, superFunc) {
function superWrapper() {
var orig = this._super;
this._super = superFunc;
var ret = func.apply(this, arguments);
this._super = orig;
return ret;
}
IS_WRAPPED_FUNCTION_SET.add(superWrapper);
var meta = OBSERVERS_LISTENERS_MAP.get(func);
if (meta !== undefined) {
OBSERVERS_LISTENERS_MAP.set(superWrapper, meta);
}
return superWrapper;
}
var {
toString: objectToString
} = Object.prototype;
var {
toString: functionToString
} = Function.prototype;
var {
isArray
} = Array;
var {
keys: objectKeys
} = Object;
var {
stringify
} = JSON;
var LIST_LIMIT = 100;
var DEPTH_LIMIT = 4;
var SAFE_KEY = /^[\w$]+$/;
/**
@module @ember/debug
*/
/**
Convenience method to inspect an object. This method will attempt to
convert the object into a useful string description.
It is a pretty simple implementation. If you want something more robust,
use something like JSDump: https://github.com/NV/jsDump
@method inspect
@static
@param {Object} obj The object you want to inspect.
@return {String} A description of the object
@since 1.4.0
@private
*/
function inspect(obj) {
// detect Node util.inspect call inspect(depth: number, opts: object)
if (typeof obj === 'number' && arguments.length === 2) {
return this;
}
return inspectValue(obj, 0);
}
function inspectValue(value, depth, seen) {
var valueIsArray = false;
switch (typeof value) {
case 'undefined':
return 'undefined';
case 'object':
if (value === null) return 'null';
if (isArray(value)) {
valueIsArray = true;
break;
} // is toString Object.prototype.toString or undefined then traverse
if (value.toString === objectToString || value.toString === undefined) {
break;
} // custom toString
return value.toString();
case 'function':
return value.toString === functionToString ? value.name ? `[Function:${value.name}]` : `[Function]` : value.toString();
case 'string':
return stringify(value);
case 'symbol':
case 'boolean':
case 'number':
default:
return value.toString();
}
if (seen === undefined) {
seen = new _util._WeakSet();
} else {
if (seen.has(value)) return `[Circular]`;
}
seen.add(value);
return valueIsArray ? inspectArray(value, depth + 1, seen) : inspectObject(value, depth + 1, seen);
}
function inspectKey(key) {
return SAFE_KEY.test(key) ? key : stringify(key);
}
function inspectObject(obj, depth, seen) {
if (depth > DEPTH_LIMIT) {
return '[Object]';
}
var s = '{';
var keys = objectKeys(obj);
for (var i = 0; i < keys.length; i++) {
s += i === 0 ? ' ' : ', ';
if (i >= LIST_LIMIT) {
s += `... ${keys.length - LIST_LIMIT} more keys`;
break;
}
var key = keys[i];
s += inspectKey(key) + ': ' + inspectValue(obj[key], depth, seen);
}
s += ' }';
return s;
}
function inspectArray(arr, depth, seen) {
if (depth > DEPTH_LIMIT) {
return '[Array]';
}
var s = '[';
for (var i = 0; i < arr.length; i++) {
s += i === 0 ? ' ' : ', ';
if (i >= LIST_LIMIT) {
s += `... ${arr.length - LIST_LIMIT} more items`;
break;
}
s += inspectValue(arr[i], depth, seen);
}
s += ' ]';
return s;
}
function lookupDescriptor(obj, keyName) {
var current = obj;
do {
var descriptor = Object.getOwnPropertyDescriptor(current, keyName);
if (descriptor !== undefined) {
return descriptor;
}
current = Object.getPrototypeOf(current);
} while (current !== null);
return null;
}
/**
Checks to see if the `methodName` exists on the `obj`.
```javascript
let foo = { bar: function() { return 'bar'; }, baz: null };
Ember.canInvoke(foo, 'bar'); // true
Ember.canInvoke(foo, 'baz'); // false
Ember.canInvoke(foo, 'bat'); // false
```
@method canInvoke
@for Ember
@param {Object} obj The object to check for the method
@param {String} methodName The method name to check for
@return {Boolean}
@private
*/
function canInvoke(obj, methodName) {
return obj !== null && obj !== undefined && typeof obj[methodName] === 'function';
}
/**
@module @ember/utils
*/
var {
isArray: isArray$1
} = Array;
function makeArray(obj) {
if (obj === null || obj === undefined) {
return [];
}
return isArray$1(obj) ? obj : [obj];
}
var NAMES = new WeakMap();
function setName(obj, name) {
if (isObject(obj)) NAMES.set(obj, name);
}
function getName(obj) {
return NAMES.get(obj);
}
var objectToString$1 = Object.prototype.toString;
function isNone(obj) {
return obj === null || obj === undefined;
}
/*
A `toString` util function that supports objects without a `toString`
method, e.g. an object created with `Object.create(null)`.
*/
function toString(obj) {
if (typeof obj === 'string') {
return obj;
}
if (null === obj) return 'null';
if (undefined === obj) return 'undefined';
if (Array.isArray(obj)) {
// Reimplement Array.prototype.join according to spec (22.1.3.13)
// Changing ToString(element) with this safe version of ToString.
var r = '';
for (var k = 0; k < obj.length; k++) {
if (k > 0) {
r += ',';
}
if (!isNone(obj[k])) {
r += toString(obj[k]);
}
}
return r;
}
if (typeof obj.toString === 'function') {
return obj.toString();
}
return objectToString$1.call(obj);
}
var PROXIES = new _util._WeakSet();
function isProxy(value) {
if (isObject(value)) {
return PROXIES.has(value);
}
return false;
}
function setProxy(object) {
if (isObject(object)) {
PROXIES.add(object);
}
}
class Cache {
constructor(limit, func, store) {
this.limit = limit;
this.func = func;
this.store = store;
this.size = 0;
this.misses = 0;
this.hits = 0;
this.store = store || new Map();
}
get(key) {
if (this.store.has(key)) {
this.hits++;
return this.store.get(key);
} else {
this.misses++;
return this.set(key, this.func(key));
}
}
set(key, value) {
if (this.limit > this.size) {
this.size++;
this.store.set(key, value);
}
return value;
}
purge() {
this.store.clear();
this.size = 0;
this.hits = 0;
this.misses = 0;
}
}
_exports.Cache = Cache;
var EMBER_ARRAYS = new _util._WeakSet();
function setEmberArray(obj) {
EMBER_ARRAYS.add(obj);
}
function isEmberArray(obj) {
return EMBER_ARRAYS.has(obj);
}
var setupMandatorySetter;
_exports.setupMandatorySetter = setupMandatorySetter;
var teardownMandatorySetter;
_exports.teardownMandatorySetter = teardownMandatorySetter;
var setWithMandatorySetter;
_exports.setWithMandatorySetter = setWithMandatorySetter;
function isElementKey(key) {
return typeof key === 'number' ? isPositiveInt(key) : isStringInt(key);
}
function isStringInt(str) {
var num = parseInt(str, 10);
return isPositiveInt(num) && str === String(num);
}
function isPositiveInt(num) {
return num >= 0 && num % 1 === 0;
}
if (true
/* DEBUG */
) {
var SEEN_TAGS = new _util._WeakSet();
var MANDATORY_SETTERS = new WeakMap();
var _propertyIsEnumerable = function (obj, key) {
return Object.prototype.propertyIsEnumerable.call(obj, key);
};
_exports.setupMandatorySetter = setupMandatorySetter = function (tag, obj, keyName) {
if (SEEN_TAGS.has(tag)) {
return;
}
SEEN_TAGS.add(tag);
if (Array.isArray(obj) && isElementKey(keyName)) {
return;
}
var desc = lookupDescriptor(obj, keyName) || {};
if (desc.get || desc.set) {
// if it has a getter or setter, we can't install the mandatory setter.
// native setters are allowed, we have to assume that they will resolve
// to tracked properties.
return;
}
if (desc && (!desc.configurable || !desc.writable)) {
// if it isn't writable anyways, so we shouldn't provide the setter.
// if it isn't configurable, we can't overwrite it anyways.
return;
}
var setters = MANDATORY_SETTERS.get(obj);
if (setters === undefined) {
setters = {};
MANDATORY_SETTERS.set(obj, setters);
}
desc.hadOwnProperty = Object.hasOwnProperty.call(obj, keyName);
setters[keyName] = desc;
Object.defineProperty(obj, keyName, {
configurable: true,
enumerable: _propertyIsEnumerable(obj, keyName),
get() {
if (desc.get) {
return desc.get.call(this);
} else {
return desc.value;
}
},
set(value) {
(true && !(false) && (0, _debug.assert)(`You attempted to update ${this}.${String(keyName)} to "${String(value)}", but it is being tracked by a tracking context, such as a template, computed property, or observer. In order to make sure the context updates properly, you must invalidate the property when updating it. You can mark the property as \`@tracked\`, or use \`@ember/object#set\` to do this.`));
}
});
};
_exports.teardownMandatorySetter = teardownMandatorySetter = function (obj, keyName) {
var setters = MANDATORY_SETTERS.get(obj);
if (setters !== undefined && setters[keyName] !== undefined) {
Object.defineProperty(obj, keyName, setters[keyName]);
setters[keyName] = undefined;
}
};
_exports.setWithMandatorySetter = setWithMandatorySetter = function (obj, keyName, value) {
var setters = MANDATORY_SETTERS.get(obj);
if (setters !== undefined && setters[keyName] !== undefined) {
var setter = setters[keyName];
if (setter.set) {
setter.set.call(obj, value);
} else {
setter.value = value; // If the object didn't have own property before, it would have changed
// the enumerability after setting the value the first time.
if (!setter.hadOwnProperty) {
var desc = lookupDescriptor(obj, keyName);
desc.enumerable = true;
Object.defineProperty(obj, keyName, desc);
}
}
} else {
obj[keyName] = value;
}
};
}
/*
This package will be eagerly parsed and should have no dependencies on external
packages.
It is intended to be used to share utility methods that will be needed
by every Ember application (and is **not** a dumping ground of useful utilities).
Utility methods that are needed in < 80% of cases should be placed
elsewhere (so they can be lazily evaluated / parsed).
*/
});
define("@ember/-internals/views/index", ["exports", "@ember/-internals/views/lib/system/utils", "@ember/-internals/views/lib/system/event_dispatcher", "@ember/-internals/views/lib/component_lookup", "@ember/-internals/views/lib/views/core_view", "@ember/-internals/views/lib/mixins/class_names_support", "@ember/-internals/views/lib/mixins/child_views_support", "@ember/-internals/views/lib/mixins/view_state_support", "@ember/-internals/views/lib/mixins/view_support", "@ember/-internals/views/lib/mixins/action_support", "@ember/-internals/views/lib/compat/attrs", "@ember/-internals/views/lib/system/action_manager"], function (_exports, _utils, _event_dispatcher, _component_lookup, _core_view, _class_names_support, _child_views_support, _view_state_support, _view_support, _action_support, _attrs, _action_manager) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "addChildView", {
enumerable: true,
get: function () {
return _utils.addChildView;
}
});
Object.defineProperty(_exports, "isSimpleClick", {
enumerable: true,
get: function () {
return _utils.isSimpleClick;
}
});
Object.defineProperty(_exports, "getViewBounds", {
enumerable: true,
get: function () {
return _utils.getViewBounds;
}
});
Object.defineProperty(_exports, "getViewClientRects", {
enumerable: true,
get: function () {
return _utils.getViewClientRects;
}
});
Object.defineProperty(_exports, "getViewBoundingClientRect", {
enumerable: true,
get: function () {
return _utils.getViewBoundingClientRect;
}
});
Object.defineProperty(_exports, "getRootViews", {
enumerable: true,
get: function () {
return _utils.getRootViews;
}
});
Object.defineProperty(_exports, "getChildViews", {
enumerable: true,
get: function () {
return _utils.getChildViews;
}
});
Object.defineProperty(_exports, "getViewId", {
enumerable: true,
get: function () {
return _utils.getViewId;
}
});
Object.defineProperty(_exports, "getElementView", {
enumerable: true,
get: function () {
return _utils.getElementView;
}
});
Object.defineProperty(_exports, "getViewElement", {
enumerable: true,
get: function () {
return _utils.getViewElement;
}
});
Object.defineProperty(_exports, "setElementView", {
enumerable: true,
get: function () {
return _utils.setElementView;
}
});
Object.defineProperty(_exports, "setViewElement", {
enumerable: true,
get: function () {
return _utils.setViewElement;
}
});
Object.defineProperty(_exports, "clearElementView", {
enumerable: true,
get: function () {
return _utils.clearElementView;
}
});
Object.defineProperty(_exports, "clearViewElement", {
enumerable: true,
get: function () {
return _utils.clearViewElement;
}
});
Object.defineProperty(_exports, "constructStyleDeprecationMessage", {
enumerable: true,
get: function () {
return _utils.constructStyleDeprecationMessage;
}
});
Object.defineProperty(_exports, "EventDispatcher", {
enumerable: true,
get: function () {
return _event_dispatcher.default;
}
});
Object.defineProperty(_exports, "ComponentLookup", {
enumerable: true,
get: function () {
return _component_lookup.default;
}
});
Object.defineProperty(_exports, "CoreView", {
enumerable: true,
get: function () {
return _core_view.default;
}
});
Object.defineProperty(_exports, "ClassNamesSupport", {
enumerable: true,
get: function () {
return _class_names_support.default;
}
});
Object.defineProperty(_exports, "ChildViewsSupport", {
enumerable: true,
get: function () {
return _child_views_support.default;
}
});
Object.defineProperty(_exports, "ViewStateSupport", {
enumerable: true,
get: function () {
return _view_state_support.default;
}
});
Object.defineProperty(_exports, "ViewMixin", {
enumerable: true,
get: function () {
return _view_support.default;
}
});
Object.defineProperty(_exports, "ActionSupport", {
enumerable: true,
get: function () {
return _action_support.default;
}
});
Object.defineProperty(_exports, "MUTABLE_CELL", {
enumerable: true,
get: function () {
return _attrs.MUTABLE_CELL;
}
});
Object.defineProperty(_exports, "ActionManager", {
enumerable: true,
get: function () {
return _action_manager.default;
}
});
});
define("@ember/-internals/views/lib/compat/attrs", ["exports", "@ember/-internals/utils"], function (_exports, _utils) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.MUTABLE_CELL = void 0;
var MUTABLE_CELL = (0, _utils.symbol)('MUTABLE_CELL');
_exports.MUTABLE_CELL = MUTABLE_CELL;
});
define("@ember/-internals/views/lib/compat/fallback-view-registry", ["exports", "@ember/-internals/utils"], function (_exports, _utils) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
var _default = (0, _utils.dictionary)(null);
_exports.default = _default;
});
define("@ember/-internals/views/lib/component_lookup", ["exports", "@ember/-internals/runtime"], function (_exports, _runtime) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
var _default = _runtime.Object.extend({
componentFor(name, owner, options) {
var fullName = `component:${name}`;
return owner.factoryFor(fullName, options);
},
layoutFor(name, owner, options) {
var templateFullName = `template:components/${name}`;
return owner.lookup(templateFullName, options);
}
});
_exports.default = _default;
});
define("@ember/-internals/views/lib/mixins/action_support", ["exports", "@ember/-internals/utils", "@ember/-internals/metal", "@ember/debug"], function (_exports, _utils, _metal, _debug) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module ember
*/
var mixinObj = {
send(actionName, ...args) {
(true && !(!this.isDestroying && !this.isDestroyed) && (0, _debug.assert)(`Attempted to call .send() with the action '${actionName}' on the destroyed object '${this}'.`, !this.isDestroying && !this.isDestroyed));
var action = this.actions && this.actions[actionName];
if (action) {
var shouldBubble = action.apply(this, args) === true;
if (!shouldBubble) {
return;
}
}
var target = (0, _metal.get)(this, 'target');
if (target) {
(true && !(typeof target.send === 'function') && (0, _debug.assert)(`The \`target\` for ${this} (${target}) does not have a \`send\` method`, typeof target.send === 'function'));
target.send(...arguments);
} else {
(true && !(action) && (0, _debug.assert)(`${(0, _utils.inspect)(this)} had no action handler for: ${actionName}`, action));
}
}
};
/**
@class ActionSupport
@namespace Ember
@private
*/
var _default = _metal.Mixin.create(mixinObj);
_exports.default = _default;
});
define("@ember/-internals/views/lib/mixins/child_views_support", ["exports", "@ember/-internals/metal", "@ember/-internals/views/lib/system/utils"], function (_exports, _metal, _utils) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module ember
*/
var _default = _metal.Mixin.create({
/**
Array of child views. You should never edit this array directly.
@property childViews
@type Array
@default []
@private
*/
childViews: (0, _metal.nativeDescDecorator)({
configurable: false,
enumerable: false,
get() {
return (0, _utils.getChildViews)(this);
}
}),
appendChild(view) {
(0, _utils.addChildView)(this, view);
}
});
_exports.default = _default;
});
define("@ember/-internals/views/lib/mixins/class_names_support", ["exports", "@ember/-internals/metal", "@ember/debug"], function (_exports, _metal, _debug) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module ember
*/
var EMPTY_ARRAY = Object.freeze([]);
/**
@class ClassNamesSupport
@namespace Ember
@private
*/
var _default = _metal.Mixin.create({
concatenatedProperties: ['classNames', 'classNameBindings'],
init() {
this._super(...arguments);
(true && !((0, _metal.descriptorForProperty)(this, 'classNameBindings') === undefined && Array.isArray(this.classNameBindings)) && (0, _debug.assert)(`Only arrays are allowed for 'classNameBindings'`, (0, _metal.descriptorForProperty)(this, 'classNameBindings') === undefined && Array.isArray(this.classNameBindings)));
(true && !((0, _metal.descriptorForProperty)(this, 'classNames') === undefined && Array.isArray(this.classNames)) && (0, _debug.assert)(`Only arrays of static class strings are allowed for 'classNames'. For dynamic classes, use 'classNameBindings'.`, (0, _metal.descriptorForProperty)(this, 'classNames') === undefined && Array.isArray(this.classNames)));
},
/**
Standard CSS class names to apply to the view's outer element. This
property automatically inherits any class names defined by the view's
superclasses as well.
@property classNames
@type Array
@default ['ember-view']
@public
*/
classNames: EMPTY_ARRAY,
/**
A list of properties of the view to apply as class names. If the property
is a string value, the value of that string will be applied as a class
name.
```javascript
// Applies the 'high' class to the view element
import Component from '@ember/component';
Component.extend({
classNameBindings: ['priority'],
priority: 'high'
});
```
If the value of the property is a Boolean, the name of that property is
added as a dasherized class name.
```javascript
// Applies the 'is-urgent' class to the view element
import Component from '@ember/component';
Component.extend({
classNameBindings: ['isUrgent'],
isUrgent: true
});
```
If you would prefer to use a custom value instead of the dasherized
property name, you can pass a binding like this:
```javascript
// Applies the 'urgent' class to the view element
import Component from '@ember/component';
Component.extend({
classNameBindings: ['isUrgent:urgent'],
isUrgent: true
});
```
If you would like to specify a class that should only be added when the
property is false, you can declare a binding like this:
```javascript
// Applies the 'disabled' class to the view element
import Component from '@ember/component';
Component.extend({
classNameBindings: ['isEnabled::disabled'],
isEnabled: false
});
```
This list of properties is inherited from the component's superclasses as well.
@property classNameBindings
@type Array
@default []
@public
*/
classNameBindings: EMPTY_ARRAY
});
_exports.default = _default;
});
define("@ember/-internals/views/lib/mixins/view_state_support", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module ember
*/
var _default = _metal.Mixin.create({
_transitionTo(state) {
var priorState = this._currentState;
var currentState = this._currentState = this._states[state];
this._state = state;
if (priorState && priorState.exit) {
priorState.exit(this);
}
if (currentState.enter) {
currentState.enter(this);
}
}
});
_exports.default = _default;
});
define("@ember/-internals/views/lib/mixins/view_support", ["exports", "@ember/-internals/utils", "@ember/-internals/metal", "@ember/debug", "@ember/-internals/browser-environment", "@ember/-internals/views/lib/system/utils"], function (_exports, _utils, _metal, _debug, _browserEnvironment, _utils2) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
function K() {
return this;
}
var mixin = {
/**
A list of properties of the view to apply as attributes. If the property
is a string value, the value of that string will be applied as the value
for an attribute of the property's name.
The following example creates a tag like `<div priority="high" />`.
```app/components/my-component.js
import Component from '@ember/component';
export default Component.extend({
attributeBindings: ['priority'],
priority: 'high'
});
```
If the value of the property is a Boolean, the attribute is treated as
an HTML Boolean attribute. It will be present if the property is `true`
and omitted if the property is `false`.
The following example creates markup like `<div visible />`.
```app/components/my-component.js
import Component from '@ember/component';
export default Component.extend({
attributeBindings: ['visible'],
visible: true
});
```
If you would prefer to use a custom value instead of the property name,
you can create the same markup as the last example with a binding like
this:
```app/components/my-component.js
import Component from '@ember/component';
export default Component.extend({
attributeBindings: ['isVisible:visible'],
isVisible: true
});
```
This list of attributes is inherited from the component's superclasses,
as well.
@property attributeBindings
@type Array
@default []
@public
*/
concatenatedProperties: ['attributeBindings'],
// ..........................................................
// TEMPLATE SUPPORT
//
/**
Return the nearest ancestor that is an instance of the provided
class or mixin.
@method nearestOfType
@param {Class,Mixin} klass Subclass of Ember.View (or Ember.View itself),
or an instance of Mixin.
@return Ember.View
@deprecated use `yield` and contextual components for composition instead.
@private
*/
nearestOfType(klass) {
var view = this.parentView;
var isOfType = klass instanceof _metal.Mixin ? view => klass.detect(view) : view => klass.detect(view.constructor);
while (view) {
if (isOfType(view)) {
return view;
}
view = view.parentView;
}
},
/**
Return the nearest ancestor that has a given property.
@method nearestWithProperty
@param {String} property A property name
@return Ember.View
@deprecated use `yield` and contextual components for composition instead.
@private
*/
nearestWithProperty(property) {
var view = this.parentView;
while (view) {
if (property in view) {
return view;
}
view = view.parentView;
}
},
/**
Renders the view again. This will work regardless of whether the
view is already in the DOM or not. If the view is in the DOM, the
rendering process will be deferred to give bindings a chance
to synchronize.
If children were added during the rendering process using `appendChild`,
`rerender` will remove them, because they will be added again
if needed by the next `render`.
In general, if the display of your view changes, you should modify
the DOM element directly instead of manually calling `rerender`, which can
be slow.
@method rerender
@public
*/
rerender() {
return this._currentState.rerender(this);
},
// ..........................................................
// ELEMENT SUPPORT
//
/**
Returns the current DOM element for the view.
@property element
@type DOMElement
@public
*/
element: (0, _metal.nativeDescDecorator)({
configurable: false,
enumerable: false,
get() {
return this.renderer.getElement(this);
}
}),
/**
Appends the view's element to the specified parent element.
Note that this method just schedules the view to be appended; the DOM
element will not be appended to the given element until all bindings have
finished synchronizing.
This is not typically a function that you will need to call directly when
building your application. If you do need to use `appendTo`, be sure that
the target element you are providing is associated with an `Application`
and does not have an ancestor element that is associated with an Ember view.
@method appendTo
@param {String|DOMElement} A selector, element, HTML string
@return {Ember.View} receiver
@private
*/
appendTo(selector) {
var target;
if (_browserEnvironment.hasDOM) {
target = typeof selector === 'string' ? document.querySelector(selector) : selector;
(true && !(target) && (0, _debug.assert)(`You tried to append to (${selector}) but that isn't in the DOM`, target));
(true && !(!(0, _utils2.matches)(target, '.ember-view')) && (0, _debug.assert)('You cannot append to an existing Ember.View.', !(0, _utils2.matches)(target, '.ember-view')));
(true && !((() => {
var node = target.parentNode;
while (node) {
if (node.nodeType !== 9 && (0, _utils2.matches)(node, '.ember-view')) {
return false;
}
node = node.parentNode;
}
return true;
})()) && (0, _debug.assert)('You cannot append to an existing Ember.View.', (() => {
var node = target.parentNode;
while (node) {
if (node.nodeType !== 9 && (0, _utils2.matches)(node, '.ember-view')) {
return false;
}
node = node.parentNode;
}
return true;
})()));
} else {
target = selector;
(true && !(typeof target !== 'string') && (0, _debug.assert)(`You tried to append to a selector string (${selector}) in an environment without a DOM`, typeof target !== 'string'));
(true && !(typeof selector.appendChild === 'function') && (0, _debug.assert)(`You tried to append to a non-Element (${selector}) in an environment without a DOM`, typeof selector.appendChild === 'function'));
}
this.renderer.appendTo(this, target);
return this;
},
/**
Appends the view's element to the document body. If the view does
not have an HTML representation yet
the element will be generated automatically.
If your application uses the `rootElement` property, you must append
the view within that element. Rendering views outside of the `rootElement`
is not supported.
Note that this method just schedules the view to be appended; the DOM
element will not be appended to the document body until all bindings have
finished synchronizing.
@method append
@return {Ember.View} receiver
@private
*/
append() {
return this.appendTo(document.body);
},
/**
The HTML `id` of the view's element in the DOM. You can provide this
value yourself but it must be unique (just as in HTML):
```handlebars
{{my-component elementId="a-really-cool-id"}}
```
If not manually set a default value will be provided by the framework.
Once rendered an element's `elementId` is considered immutable and you
should never change it. If you need to compute a dynamic value for the
`elementId`, you should do this when the component or element is being
instantiated:
```app/components/my-component.js
import Component from '@ember/component';
export default Component.extend({
init() {
this._super(...arguments);
let index = this.get('index');
this.set('elementId', 'component-id' + index);
}
});
```
@property elementId
@type String
@public
*/
elementId: null,
/**
Called when a view is going to insert an element into the DOM.
@event willInsertElement
@public
*/
willInsertElement: K,
/**
Called when the element of the view has been inserted into the DOM.
Override this function to do any set up that requires an element
in the document body.
When a view has children, didInsertElement will be called on the
child view(s) first and on itself afterwards.
@event didInsertElement
@public
*/
didInsertElement: K,
/**
Called when the view is about to rerender, but before anything has
been torn down. This is a good opportunity to tear down any manual
observers you have installed based on the DOM state
@event willClearRender
@public
*/
willClearRender: K,
/**
You must call `destroy` on a view to destroy the view (and all of its
child views). This will remove the view from any parent node, then make
sure that the DOM element managed by the view can be released by the
memory manager.
@method destroy
@private
*/
destroy() {
this._super(...arguments);
this._currentState.destroy(this);
},
/**
Called when the element of the view is going to be destroyed. Override
this function to do any teardown that requires an element, like removing
event listeners.
Please note: any property changes made during this event will have no
effect on object observers.
@event willDestroyElement
@public
*/
willDestroyElement: K,
/**
Called after the element of the view is destroyed.
@event willDestroyElement
@public
*/
didDestroyElement: K,
/**
Called when the parentView property has changed.
@event parentViewDidChange
@private
*/
parentViewDidChange: K,
// ..........................................................
// STANDARD RENDER PROPERTIES
//
/**
Tag name for the view's outer element. The tag name is only used when an
element is first created. If you change the `tagName` for an element, you
must destroy and recreate the view element.
By default, the render buffer will use a `<div>` tag for views.
If the tagName is `''`, the view will be tagless, with no outer element.
Component properties that depend on the presence of an outer element, such
as `classNameBindings` and `attributeBindings`, do not work with tagless
components. Tagless components cannot implement methods to handle events,
and their `element` property has a `null` value.
@property tagName
@type String
@default null
@public
*/
// We leave this null by default so we can tell the difference between
// the default case and a user-specified tag.
tagName: null,
// .......................................................
// CORE DISPLAY METHODS
//
/**
Setup a view, but do not finish waking it up.
* configure `childViews`
* register the view with the global views hash, which is used for event
dispatch
@method init
@private
*/
init() {
this._super(...arguments); // tslint:disable-next-line:max-line-length
(true && !((0, _metal.descriptorForProperty)(this, 'elementId') === undefined) && (0, _debug.assert)(`You cannot use a computed property for the component's \`elementId\` (${this}).`, (0, _metal.descriptorForProperty)(this, 'elementId') === undefined)); // tslint:disable-next-line:max-line-length
(true && !((0, _metal.descriptorForProperty)(this, 'tagName') === undefined) && (0, _debug.assert)(`You cannot use a computed property for the component's \`tagName\` (${this}).`, (0, _metal.descriptorForProperty)(this, 'tagName') === undefined));
if (!this.elementId && this.tagName !== '') {
this.elementId = (0, _utils.guidFor)(this);
}
(true && !(!this.render) && (0, _debug.assert)('Using a custom `.render` function is no longer supported.', !this.render));
},
// .......................................................
// EVENT HANDLING
//
/**
Handle events from `EventDispatcher`
@method handleEvent
@param eventName {String}
@param evt {Event}
@private
*/
handleEvent(eventName, evt) {
return this._currentState.handleEvent(this, eventName, evt);
}
};
/**
@class ViewMixin
@namespace Ember
@private
*/
var _default = _metal.Mixin.create(mixin);
_exports.default = _default;
});
define("@ember/-internals/views/lib/system/action_manager", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = ActionManager;
/**
@module ember
*/
function ActionManager() {}
/**
Global action id hash.
@private
@property registeredActions
@type Object
*/
ActionManager.registeredActions = {};
});
define("@ember/-internals/views/lib/system/event_dispatcher", ["exports", "@ember/-internals/owner", "@ember/debug", "@ember/-internals/metal", "@ember/-internals/runtime", "@ember/-internals/views", "@ember/-internals/views/lib/system/action_manager"], function (_exports, _owner, _debug, _metal, _runtime, _views, _action_manager) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module ember
*/
var ROOT_ELEMENT_CLASS = 'ember-application';
var ROOT_ELEMENT_SELECTOR = `.${ROOT_ELEMENT_CLASS}`;
/**
`Ember.EventDispatcher` handles delegating browser events to their
corresponding `Ember.Views.` For example, when you click on a view,
`Ember.EventDispatcher` ensures that that view's `mouseDown` method gets
called.
@class EventDispatcher
@namespace Ember
@private
@extends Ember.Object
*/
var _default = _runtime.Object.extend({
/**
The set of events names (and associated handler function names) to be setup
and dispatched by the `EventDispatcher`. Modifications to this list can be done
at setup time, generally via the `Application.customEvents` hash.
To add new events to be listened to:
```javascript
import Application from '@ember/application';
let App = Application.create({
customEvents: {
paste: 'paste'
}
});
```
To prevent default events from being listened to:
```javascript
import Application from '@ember/application';
let App = Application.create({
customEvents: {
mouseenter: null,
mouseleave: null
}
});
```
@property events
@type Object
@private
*/
events: {
touchstart: 'touchStart',
touchmove: 'touchMove',
touchend: 'touchEnd',
touchcancel: 'touchCancel',
keydown: 'keyDown',
keyup: 'keyUp',
keypress: 'keyPress',
mousedown: 'mouseDown',
mouseup: 'mouseUp',
contextmenu: 'contextMenu',
click: 'click',
dblclick: 'doubleClick',
focusin: 'focusIn',
focusout: 'focusOut',
submit: 'submit',
input: 'input',
change: 'change',
dragstart: 'dragStart',
drag: 'drag',
dragenter: 'dragEnter',
dragleave: 'dragLeave',
dragover: 'dragOver',
drop: 'drop',
dragend: 'dragEnd'
},
/**
The root DOM element to which event listeners should be attached. Event
listeners will be attached to the document unless this is overridden.
Can be specified as a DOMElement or a selector string.
The default body is a string since this may be evaluated before document.body
exists in the DOM.
@private
@property rootElement
@type DOMElement
@default 'body'
*/
rootElement: 'body',
init() {
this._super();
this._eventHandlers = Object.create(null);
this._didSetup = false;
this.finalEventNameMapping = null;
this._sanitizedRootElement = null;
this.lazyEvents = new Map();
},
/**
Sets up event listeners for standard browser events.
This will be called after the browser sends a `DOMContentReady` event. By
default, it will set up all of the listeners on the document body. If you
would like to register the listeners on a different element, set the event
dispatcher's `root` property.
@private
@method setup
@param addedEvents {Object}
*/
setup(addedEvents, _rootElement) {
(true && !((() => {
var owner = (0, _owner.getOwner)(this);
var environment = owner.lookup('-environment:main');
return environment.isInteractive;
})()) && (0, _debug.assert)('EventDispatcher should never be setup in fastboot mode. Please report this as an Ember bug.', (() => {
var owner = (0, _owner.getOwner)(this);
var environment = owner.lookup('-environment:main');
return environment.isInteractive;
})()));
var events = this.finalEventNameMapping = Object.assign({}, (0, _metal.get)(this, 'events'), addedEvents);
this._reverseEventNameMapping = Object.keys(events).reduce((result, key) => Object.assign(result, {
[events[key]]: key
}), {});
var lazyEvents = this.lazyEvents;
if (_rootElement !== undefined && _rootElement !== null) {
(0, _metal.set)(this, 'rootElement', _rootElement);
}
var rootElementSelector = (0, _metal.get)(this, 'rootElement');
var rootElement;
if (typeof rootElementSelector !== 'string') {
rootElement = rootElementSelector;
} else {
rootElement = document.querySelector(rootElementSelector);
}
(true && !(!rootElement.classList.contains(ROOT_ELEMENT_CLASS)) && (0, _debug.assert)(`You cannot use the same root element (${(0, _metal.get)(this, 'rootElement') || rootElement.tagName}) multiple times in an Ember.Application`, !rootElement.classList.contains(ROOT_ELEMENT_CLASS)));
(true && !((() => {
var target = rootElement.parentNode;
do {
if (target.classList.contains(ROOT_ELEMENT_CLASS)) {
return false;
}
target = target.parentNode;
} while (target && target.nodeType === 1);
return true;
})()) && (0, _debug.assert)('You cannot make a new Ember.Application using a root element that is a descendent of an existing Ember.Application', (() => {
var target = rootElement.parentNode;
do {
if (target.classList.contains(ROOT_ELEMENT_CLASS)) {
return false;
}
target = target.parentNode;
} while (target && target.nodeType === 1);
return true;
})()));
(true && !(!rootElement.querySelector(ROOT_ELEMENT_SELECTOR)) && (0, _debug.assert)('You cannot make a new Ember.Application using a root element that is an ancestor of an existing Ember.Application', !rootElement.querySelector(ROOT_ELEMENT_SELECTOR)));
rootElement.classList.add(ROOT_ELEMENT_CLASS);
(true && !(rootElement.classList.contains(ROOT_ELEMENT_CLASS)) && (0, _debug.assert)(`Unable to add '${ROOT_ELEMENT_CLASS}' class to root element (${(0, _metal.get)(this, 'rootElement') || rootElement.tagName}). Make sure you set rootElement to the body or an element in the body.`, rootElement.classList.contains(ROOT_ELEMENT_CLASS))); // save off the final sanitized root element (for usage in setupHandler)
this._sanitizedRootElement = rootElement; // setup event listeners for the non-lazily setup events
for (var event in events) {
if (Object.prototype.hasOwnProperty.call(events, event)) {
lazyEvents.set(event, events[event]);
}
}
this._didSetup = true;
},
/**
Setup event listeners for the given browser event name
@private
@method setupHandlerForBrowserEvent
@param event the name of the event in the browser
*/
setupHandlerForBrowserEvent(event) {
this.setupHandler(this._sanitizedRootElement, event, this.finalEventNameMapping[event]);
},
/**
Setup event listeners for the given Ember event name (camel case)
@private
@method setupHandlerForEmberEvent
@param eventName
*/
setupHandlerForEmberEvent(eventName) {
this.setupHandler(this._sanitizedRootElement, this._reverseEventNameMapping[eventName], eventName);
},
/**
Registers an event listener on the rootElement. If the given event is
triggered, the provided event handler will be triggered on the target view.
If the target view does not implement the event handler, or if the handler
returns `false`, the parent view will be called. The event will continue to
bubble to each successive parent view until it reaches the top.
@private
@method setupHandler
@param {Element} rootElement
@param {String} event the name of the event in the browser
@param {String} eventName the name of the method to call on the view
*/
setupHandler(rootElement, event, eventName) {
if (eventName === null || !this.lazyEvents.has(event)) {
return; // nothing to do
}
var viewHandler = (target, event) => {
var view = (0, _views.getElementView)(target);
var result = true;
if (view) {
result = view.handleEvent(eventName, event);
}
return result;
};
var actionHandler = (target, event) => {
var actionId = target.getAttribute('data-ember-action');
var actions = _action_manager.default.registeredActions[actionId]; // In Glimmer2 this attribute is set to an empty string and an additional
// attribute it set for each action on a given element. In this case, the
// attributes need to be read so that a proper set of action handlers can
// be coalesced.
if (actionId === '') {
var attributes = target.attributes;
var attributeCount = attributes.length;
actions = [];
for (var i = 0; i < attributeCount; i++) {
var attr = attributes.item(i);
var attrName = attr.name;
if (attrName.indexOf('data-ember-action-') === 0) {
actions = actions.concat(_action_manager.default.registeredActions[attr.value]);
}
}
} // We have to check for actions here since in some cases, jQuery will trigger
// an event on `removeChild` (i.e. focusout) after we've already torn down the
// action handlers for the view.
if (!actions) {
return;
}
var result = true;
for (var index = 0; index < actions.length; index++) {
var action = actions[index];
if (action && action.eventName === eventName) {
// return false if any of the action handlers returns false
result = action.handler(event) && result;
}
}
return result;
};
var handleEvent = this._eventHandlers[event] = event => {
var target = event.target;
do {
if ((0, _views.getElementView)(target)) {
if (viewHandler(target, event) === false) {
event.preventDefault();
event.stopPropagation();
break;
} else if (event.cancelBubble === true) {
break;
}
} else if (typeof target.hasAttribute === 'function' && target.hasAttribute('data-ember-action')) {
if (actionHandler(target, event) === false) {
break;
}
}
target = target.parentNode;
} while (target && target.nodeType === 1);
};
rootElement.addEventListener(event, handleEvent);
this.lazyEvents.delete(event);
},
destroy() {
if (this._didSetup === false) {
return;
}
var rootElementSelector = (0, _metal.get)(this, 'rootElement');
var rootElement;
if (rootElementSelector.nodeType) {
rootElement = rootElementSelector;
} else {
rootElement = document.querySelector(rootElementSelector);
}
if (!rootElement) {
return;
}
for (var event in this._eventHandlers) {
rootElement.removeEventListener(event, this._eventHandlers[event]);
}
rootElement.classList.remove(ROOT_ELEMENT_CLASS);
return this._super(...arguments);
},
toString() {
return '(EventDispatcher)';
}
});
_exports.default = _default;
});
define("@ember/-internals/views/lib/system/utils", ["exports", "@ember/-internals/owner", "@ember/-internals/utils", "@ember/debug"], function (_exports, _owner, _utils, _debug) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.isSimpleClick = isSimpleClick;
_exports.constructStyleDeprecationMessage = constructStyleDeprecationMessage;
_exports.getRootViews = getRootViews;
_exports.getViewId = getViewId;
_exports.getElementView = getElementView;
_exports.getViewElement = getViewElement;
_exports.setElementView = setElementView;
_exports.setViewElement = setViewElement;
_exports.clearElementView = clearElementView;
_exports.clearViewElement = clearViewElement;
_exports.getChildViews = getChildViews;
_exports.initChildViews = initChildViews;
_exports.addChildView = addChildView;
_exports.collectChildViews = collectChildViews;
_exports.getViewBounds = getViewBounds;
_exports.getViewRange = getViewRange;
_exports.getViewClientRects = getViewClientRects;
_exports.getViewBoundingClientRect = getViewBoundingClientRect;
_exports.matches = matches;
_exports.contains = contains;
_exports.elMatches = void 0;
/* globals Element */
/**
@module ember
*/
function isSimpleClick(event) {
var modifier = event.shiftKey || event.metaKey || event.altKey || event.ctrlKey;
var secondaryClick = event.which > 1; // IE9 may return undefined
return !modifier && !secondaryClick;
}
function constructStyleDeprecationMessage(affectedStyle) {
return '' + 'Binding style attributes may introduce cross-site scripting vulnerabilities; ' + 'please ensure that values being bound are properly escaped. For more information, ' + 'including how to disable this warning, see ' + 'https://deprecations.emberjs.com/v1.x/#toc_binding-style-attributes. ' + 'Style affected: "' + affectedStyle + '"';
}
/**
@private
@method getRootViews
@param {Object} owner
*/
function getRootViews(owner) {
var registry = owner.lookup('-view-registry:main');
var rootViews = [];
Object.keys(registry).forEach(id => {
var view = registry[id];
if (view.parentView === null) {
rootViews.push(view);
}
});
return rootViews;
}
/**
@private
@method getViewId
@param {Ember.View} view
*/
function getViewId(view) {
if (view.tagName !== '' && view.elementId) {
return view.elementId;
} else {
return (0, _utils.guidFor)(view);
}
}
var ELEMENT_VIEW = new WeakMap();
var VIEW_ELEMENT = new WeakMap();
function getElementView(element) {
return ELEMENT_VIEW.get(element) || null;
}
/**
@private
@method getViewElement
@param {Ember.View} view
*/
function getViewElement(view) {
return VIEW_ELEMENT.get(view) || null;
}
function setElementView(element, view) {
ELEMENT_VIEW.set(element, view);
}
function setViewElement(view, element) {
VIEW_ELEMENT.set(view, element);
} // These are not needed for GC, but for correctness. We want to be able to
// null-out these links while the objects are still live. Specifically, in
// this case, we want to prevent access to the element (and vice verse) during
// destruction.
function clearElementView(element) {
ELEMENT_VIEW.delete(element);
}
function clearViewElement(view) {
VIEW_ELEMENT.delete(view);
}
var CHILD_VIEW_IDS = new WeakMap();
/**
@private
@method getChildViews
@param {Ember.View} view
*/
function getChildViews(view) {
var owner = (0, _owner.getOwner)(view);
var registry = owner.lookup('-view-registry:main');
return collectChildViews(view, registry);
}
function initChildViews(view) {
var childViews = new Set();
CHILD_VIEW_IDS.set(view, childViews);
return childViews;
}
function addChildView(parent, child) {
var childViews = CHILD_VIEW_IDS.get(parent);
if (childViews === undefined) {
childViews = initChildViews(parent);
}
childViews.add(getViewId(child));
}
function collectChildViews(view, registry) {
var views = [];
var childViews = CHILD_VIEW_IDS.get(view);
if (childViews !== undefined) {
childViews.forEach(id => {
var view = registry[id];
if (view && !view.isDestroying && !view.isDestroyed) {
views.push(view);
}
});
}
return views;
}
/**
@private
@method getViewBounds
@param {Ember.View} view
*/
function getViewBounds(view) {
return view.renderer.getBounds(view);
}
/**
@private
@method getViewRange
@param {Ember.View} view
*/
function getViewRange(view) {
var bounds = getViewBounds(view);
var range = document.createRange();
range.setStartBefore(bounds.firstNode);
range.setEndAfter(bounds.lastNode);
return range;
}
/**
`getViewClientRects` provides information about the position of the border
box edges of a view relative to the viewport.
It is only intended to be used by development tools like the Ember Inspector
and may not work on older browsers.
@private
@method getViewClientRects
@param {Ember.View} view
*/
function getViewClientRects(view) {
var range = getViewRange(view);
return range.getClientRects();
}
/**
`getViewBoundingClientRect` provides information about the position of the
bounding border box edges of a view relative to the viewport.
It is only intended to be used by development tools like the Ember Inspector
and may not work on older browsers.
@private
@method getViewBoundingClientRect
@param {Ember.View} view
*/
function getViewBoundingClientRect(view) {
var range = getViewRange(view);
return range.getBoundingClientRect();
}
/**
Determines if the element matches the specified selector.
@private
@method matches
@param {DOMElement} el
@param {String} selector
*/
var elMatches = typeof Element !== 'undefined' ? Element.prototype.matches || Element.prototype['matchesSelector'] || Element.prototype['mozMatchesSelector'] || Element.prototype['msMatchesSelector'] || Element.prototype['oMatchesSelector'] || Element.prototype['webkitMatchesSelector'] : undefined;
_exports.elMatches = elMatches;
function matches(el, selector) {
(true && !(elMatches !== undefined) && (0, _debug.assert)('cannot call `matches` in fastboot mode', elMatches !== undefined));
return elMatches.call(el, selector);
}
function contains(a, b) {
if (a.contains !== undefined) {
return a.contains(b);
}
var current = b.parentNode;
while (current && (current = current.parentNode)) {
if (current === a) {
return true;
}
}
return false;
}
});
define("@ember/-internals/views/lib/views/core_view", ["exports", "@ember/-internals/metal", "@ember/-internals/runtime", "@ember/-internals/views/lib/views/states"], function (_exports, _metal, _runtime, _states) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
`Ember.CoreView` is an abstract class that exists to give view-like behavior
to both Ember's main view class `Component` and other classes that don't need
the full functionality of `Component`.
Unless you have specific needs for `CoreView`, you will use `Component`
in your applications.
@class CoreView
@namespace Ember
@extends EmberObject
@deprecated Use `Component` instead.
@uses Evented
@uses Ember.ActionHandler
@private
*/
var CoreView = _runtime.FrameworkObject.extend(_runtime.Evented, _runtime.ActionHandler, {
isView: true,
_states: _states.default,
init() {
this._super(...arguments);
this._state = 'preRender';
this._currentState = this._states.preRender;
},
renderer: (0, _metal.inject)('renderer', '-dom'),
/**
If the view is currently inserted into the DOM of a parent view, this
property will point to the parent of the view.
@property parentView
@type Ember.View
@default null
@private
*/
parentView: null,
instrumentDetails(hash) {
hash.object = this.toString();
hash.containerKey = this._debugContainerKey;
hash.view = this;
return hash;
},
/**
Override the default event firing from `Evented` to
also call methods with the given name.
@method trigger
@param name {String}
@private
*/
trigger(name, ...args) {
this._super(...arguments);
var method = this[name];
if (typeof method === 'function') {
return method.apply(this, args);
}
},
has(name) {
return typeof this[name] === 'function' || this._super(name);
}
});
CoreView.reopenClass({
isViewFactory: true
});
var _default = CoreView;
_exports.default = _default;
});
define("@ember/-internals/views/lib/views/states", ["exports", "@ember/-internals/views/lib/views/states/pre_render", "@ember/-internals/views/lib/views/states/has_element", "@ember/-internals/views/lib/views/states/in_dom", "@ember/-internals/views/lib/views/states/destroying"], function (_exports, _pre_render, _has_element, _in_dom, _destroying) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/*
Describe how the specified actions should behave in the various
states that a view can exist in. Possible states:
* preRender: when a view is first instantiated, and after its
element was destroyed, it is in the preRender state
* hasElement: the DOM representation of the view is created,
and is ready to be inserted
* inDOM: once a view has been inserted into the DOM it is in
the inDOM state. A view spends the vast majority of its
existence in this state.
* destroyed: once a view has been destroyed (using the destroy
method), it is in this state. No further actions can be invoked
on a destroyed view.
*/
var states = Object.freeze({
preRender: _pre_render.default,
inDOM: _in_dom.default,
hasElement: _has_element.default,
destroying: _destroying.default
});
var _default = states;
_exports.default = _default;
});
define("@ember/-internals/views/lib/views/states/default", ["exports", "@ember/error"], function (_exports, _error) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
var _default = {
// appendChild is only legal while rendering the buffer.
appendChild() {
throw new _error.default("You can't use appendChild outside of the rendering process");
},
// Handle events from `Ember.EventDispatcher`
handleEvent() {
return true; // continue event propagation
},
rerender() {},
destroy() {}
};
var _default2 = Object.freeze(_default);
_exports.default = _default2;
});
define("@ember/-internals/views/lib/views/states/destroying", ["exports", "@ember/error", "@ember/-internals/views/lib/views/states/default"], function (_exports, _error, _default3) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
var destroying = Object.assign({}, _default3.default, {
appendChild() {
throw new _error.default("You can't call appendChild on a view being destroyed");
},
rerender() {
throw new _error.default("You can't call rerender on a view being destroyed");
}
});
var _default2 = Object.freeze(destroying);
_exports.default = _default2;
});
define("@ember/-internals/views/lib/views/states/has_element", ["exports", "@ember/-internals/views/lib/views/states/default", "@ember/runloop", "@ember/instrumentation"], function (_exports, _default3, _runloop, _instrumentation) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
var hasElement = Object.assign({}, _default3.default, {
rerender(view) {
view.renderer.rerender(view);
},
destroy(view) {
view.renderer.remove(view);
},
// Handle events from `Ember.EventDispatcher`
handleEvent(view, eventName, event) {
if (view.has(eventName)) {
// Handler should be able to re-dispatch events, so we don't
// preventDefault or stopPropagation.
return (0, _instrumentation.flaggedInstrument)(`interaction.${eventName}`, {
event,
view
}, () => {
return (0, _runloop.join)(view, view.trigger, eventName, event);
});
} else {
return true; // continue event propagation
}
}
});
var _default2 = Object.freeze(hasElement);
_exports.default = _default2;
});
define("@ember/-internals/views/lib/views/states/in_dom", ["exports", "@ember/-internals/utils", "@ember/error", "@ember/-internals/views/lib/views/states/has_element"], function (_exports, _utils, _error, _has_element) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
var inDOM = Object.assign({}, _has_element.default, {
enter(view) {
// Register the view for event handling. This hash is used by
// Ember.EventDispatcher to dispatch incoming events.
view.renderer.register(view);
if (true
/* DEBUG */
) {
var elementId = view.elementId;
(0, _utils.teardownMandatorySetter)(view, 'elementId');
Object.defineProperty(view, 'elementId', {
configurable: true,
enumerable: true,
get() {
return elementId;
},
set(value) {
if (value !== elementId) {
throw new _error.default("Changing a view's elementId after creation is not allowed");
}
}
});
}
}
});
var _default = Object.freeze(inDOM);
_exports.default = _default;
});
define("@ember/-internals/views/lib/views/states/pre_render", ["exports", "@ember/-internals/views/lib/views/states/default"], function (_exports, _default3) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
var preRender = Object.assign({}, _default3.default);
var _default2 = Object.freeze(preRender);
_exports.default = _default2;
});
define("@ember/application/index", ["exports", "@ember/-internals/owner", "@ember/application/lib/lazy_load", "@ember/application/lib/application"], function (_exports, _owner, _lazy_load, _application) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "getOwner", {
enumerable: true,
get: function () {
return _owner.getOwner;
}
});
Object.defineProperty(_exports, "setOwner", {
enumerable: true,
get: function () {
return _owner.setOwner;
}
});
Object.defineProperty(_exports, "onLoad", {
enumerable: true,
get: function () {
return _lazy_load.onLoad;
}
});
Object.defineProperty(_exports, "runLoadHooks", {
enumerable: true,
get: function () {
return _lazy_load.runLoadHooks;
}
});
Object.defineProperty(_exports, "_loaded", {
enumerable: true,
get: function () {
return _lazy_load._loaded;
}
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _application.default;
}
});
});
define("@ember/application/instance", ["exports", "@ember/-internals/metal", "@ember/-internals/browser-environment", "@ember/engine/instance", "@ember/-internals/glimmer"], function (_exports, _metal, environment, _instance, _glimmer) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module @ember/application
*/
/**
The `ApplicationInstance` encapsulates all of the stateful aspects of a
running `Application`.
At a high-level, we break application boot into two distinct phases:
* Definition time, where all of the classes, templates, and other
dependencies are loaded (typically in the browser).
* Run time, where we begin executing the application once everything
has loaded.
Definition time can be expensive and only needs to happen once since it is
an idempotent operation. For example, between test runs and FastBoot
requests, the application stays the same. It is only the state that we want
to reset.
That state is what the `ApplicationInstance` manages: it is responsible for
creating the container that contains all application state, and disposing of
it once the particular test run or FastBoot request has finished.
@public
@class ApplicationInstance
@extends EngineInstance
*/
var ApplicationInstance = _instance.default.extend({
/**
The `Application` for which this is an instance.
@property {Application} application
@private
*/
application: null,
/**
The DOM events for which the event dispatcher should listen.
By default, the application's `Ember.EventDispatcher` listens
for a set of standard DOM events, such as `mousedown` and
`keyup`, and delegates them to your application's `Ember.View`
instances.
@private
@property {Object} customEvents
*/
customEvents: null,
/**
The root DOM element of the Application as an element or a
CSS selector.
@private
@property {String|DOMElement} rootElement
*/
rootElement: null,
init() {
this._super(...arguments);
this.application._watchInstance(this); // Register this instance in the per-instance registry.
//
// Why do we need to register the instance in the first place?
// Because we need a good way for the root route (a.k.a ApplicationRoute)
// to notify us when it has created the root-most view. That view is then
// appended to the rootElement, in the case of apps, to the fixture harness
// in tests, or rendered to a string in the case of FastBoot.
this.register('-application-instance:main', this, {
instantiate: false
});
},
/**
Overrides the base `EngineInstance._bootSync` method with concerns relevant
to booting application (instead of engine) instances.
This method should only contain synchronous boot concerns. Asynchronous
boot concerns should eventually be moved to the `boot` method, which
returns a promise.
Until all boot code has been made asynchronous, we need to continue to
expose this method for use *internally* in places where we need to boot an
instance synchronously.
@private
*/
_bootSync(options) {
if (this._booted) {
return this;
}
options = new BootOptions(options);
this.setupRegistry(options);
if (options.rootElement) {
this.rootElement = options.rootElement;
} else {
this.rootElement = this.application.rootElement;
}
if (options.location) {
(0, _metal.set)(this.router, 'location', options.location);
}
this.application.runInstanceInitializers(this);
if (options.isInteractive) {
this.setupEventDispatcher();
}
this._booted = true;
return this;
},
setupRegistry(options) {
this.constructor.setupRegistry(this.__registry__, options);
},
router: (0, _metal.computed)(function () {
return this.lookup('router:main');
}).readOnly(),
/**
This hook is called by the root-most Route (a.k.a. the ApplicationRoute)
when it has finished creating the root View. By default, we simply take the
view and append it to the `rootElement` specified on the Application.
In cases like FastBoot and testing, we can override this hook and implement
custom behavior, such as serializing to a string and sending over an HTTP
socket rather than appending to DOM.
@param view {Ember.View} the root-most view
@deprecated
@private
*/
didCreateRootView(view) {
view.appendTo(this.rootElement);
},
/**
Tells the router to start routing. The router will ask the location for the
current URL of the page to determine the initial URL to start routing to.
To start the app at a specific URL, call `handleURL` instead.
@private
*/
startRouting() {
this.router.startRouting();
},
/**
Sets up the router, initializing the child router and configuring the
location before routing begins.
Because setup should only occur once, multiple calls to `setupRouter`
beyond the first call have no effect.
This is commonly used in order to confirm things that rely on the router
are functioning properly from tests that are primarily rendering related.
For example, from within [ember-qunit](https://github.com/emberjs/ember-qunit)'s
`setupRenderingTest` calling `this.owner.setupRouter()` would allow that
rendering test to confirm that any `<LinkTo></LinkTo>`'s that are rendered
have the correct URL.
@public
*/
setupRouter() {
this.router.setupRouter();
},
/**
Directs the router to route to a particular URL. This is useful in tests,
for example, to tell the app to start at a particular URL.
@param url {String} the URL the router should route to
@private
*/
handleURL(url) {
this.setupRouter();
return this.router.handleURL(url);
},
/**
@private
*/
setupEventDispatcher() {
var dispatcher = this.lookup('event_dispatcher:main');
var applicationCustomEvents = (0, _metal.get)(this.application, 'customEvents');
var instanceCustomEvents = (0, _metal.get)(this, 'customEvents');
var customEvents = Object.assign({}, applicationCustomEvents, instanceCustomEvents);
dispatcher.setup(customEvents, this.rootElement);
return dispatcher;
},
/**
Returns the current URL of the app instance. This is useful when your
app does not update the browsers URL bar (i.e. it uses the `'none'`
location adapter).
@public
@return {String} the current URL
*/
getURL() {
return this.router.url;
},
// `instance.visit(url)` should eventually replace `instance.handleURL()`;
// the test helpers can probably be switched to use this implementation too
/**
Navigate the instance to a particular URL. This is useful in tests, for
example, or to tell the app to start at a particular URL. This method
returns a promise that resolves with the app instance when the transition
is complete, or rejects if the transion was aborted due to an error.
@public
@param url {String} the destination URL
@return {Promise<ApplicationInstance>}
*/
visit(url) {
this.setupRouter();
var bootOptions = this.__container__.lookup('-environment:main');
var router = this.router;
var handleTransitionResolve = () => {
if (!bootOptions.options.shouldRender) {
// No rendering is needed, and routing has completed, simply return.
return this;
} else {
// Ensure that the visit promise resolves when all rendering has completed
return (0, _glimmer.renderSettled)().then(() => this);
}
};
var handleTransitionReject = error => {
if (error.error) {
throw error.error;
} else if (error.name === 'TransitionAborted' && router._routerMicrolib.activeTransition) {
return router._routerMicrolib.activeTransition.then(handleTransitionResolve, handleTransitionReject);
} else if (error.name === 'TransitionAborted') {
throw new Error(error.message);
} else {
throw error;
}
};
var location = (0, _metal.get)(router, 'location'); // Keeps the location adapter's internal URL in-sync
location.setURL(url); // getURL returns the set url with the rootURL stripped off
return router.handleURL(location.getURL()).then(handleTransitionResolve, handleTransitionReject);
},
willDestroy() {
this._super(...arguments);
this.application._unwatchInstance(this);
}
});
ApplicationInstance.reopenClass({
/**
@private
@method setupRegistry
@param {Registry} registry
@param {BootOptions} options
*/
setupRegistry(registry, options = {}) {
if (!options.toEnvironment) {
options = new BootOptions(options);
}
registry.register('-environment:main', options.toEnvironment(), {
instantiate: false
});
registry.register('service:-document', options.document, {
instantiate: false
});
this._super(registry, options);
}
});
/**
A list of boot-time configuration options for customizing the behavior of
an `ApplicationInstance`.
This is an interface class that exists purely to document the available
options; you do not need to construct it manually. Simply pass a regular
JavaScript object containing the desired options into methods that require
one of these options object:
```javascript
MyApp.visit("/", { location: "none", rootElement: "#container" });
```
Not all combinations of the supported options are valid. See the documentation
on `Application#visit` for the supported configurations.
Internal, experimental or otherwise unstable flags are marked as private.
@class BootOptions
@namespace ApplicationInstance
@public
*/
class BootOptions {
constructor(options = {}) {
/**
Interactive mode: whether we need to set up event delegation and invoke
lifecycle callbacks on Components.
@property isInteractive
@type boolean
@default auto-detected
@private
*/
this.isInteractive = environment.hasDOM; // This default is overridable below
/**
@property _renderMode
@type string
@default false
@private
*/
this._renderMode = options._renderMode;
/**
Run in a full browser environment.
When this flag is set to `false`, it will disable most browser-specific
and interactive features. Specifically:
* It does not use `jQuery` to append the root view; the `rootElement`
(either specified as a subsequent option or on the application itself)
must already be an `Element` in the given `document` (as opposed to a
string selector).
* It does not set up an `EventDispatcher`.
* It does not run any `Component` lifecycle hooks (such as `didInsertElement`).
* It sets the `location` option to `"none"`. (If you would like to use
the location adapter specified in the app's router instead, you can also
specify `{ location: null }` to specifically opt-out.)
@property isBrowser
@type boolean
@default auto-detected
@public
*/
if (options.isBrowser !== undefined) {
this.isBrowser = Boolean(options.isBrowser);
} else {
this.isBrowser = environment.hasDOM;
}
if (!this.isBrowser) {
this.isInteractive = false;
this.location = 'none';
}
/**
Disable rendering completely.
When this flag is set to `false`, it will disable the entire rendering
pipeline. Essentially, this puts the app into "routing-only" mode. No
templates will be rendered, and no Components will be created.
@property shouldRender
@type boolean
@default true
@public
*/
if (options.shouldRender !== undefined) {
this.shouldRender = Boolean(options.shouldRender);
} else {
this.shouldRender = true;
}
if (!this.shouldRender) {
this.isInteractive = false;
}
/**
If present, render into the given `Document` object instead of the
global `window.document` object.
In practice, this is only useful in non-browser environment or in
non-interactive mode, because Ember's `jQuery` dependency is
implicitly bound to the current document, causing event delegation
to not work properly when the app is rendered into a foreign
document object (such as an iframe's `contentDocument`).
In non-browser mode, this could be a "`Document`-like" object as
Ember only interact with a small subset of the DOM API in non-
interactive mode. While the exact requirements have not yet been
formalized, the `SimpleDOM` library's implementation is known to
work.
@property document
@type Document
@default the global `document` object
@public
*/
if (options.document) {
this.document = options.document;
} else {
this.document = typeof document !== 'undefined' ? document : null;
}
/**
If present, overrides the application's `rootElement` property on
the instance. This is useful for testing environment, where you
might want to append the root view to a fixture area.
In non-browser mode, because Ember does not have access to jQuery,
this options must be specified as a DOM `Element` object instead of
a selector string.
See the documentation on `Application`'s `rootElement` for
details.
@property rootElement
@type String|Element
@default null
@public
*/
if (options.rootElement) {
this.rootElement = options.rootElement;
} // Set these options last to give the user a chance to override the
// defaults from the "combo" options like `isBrowser` (although in
// practice, the resulting combination is probably invalid)
/**
If present, overrides the router's `location` property with this
value. This is useful for environments where trying to modify the
URL would be inappropriate.
@property location
@type string
@default null
@public
*/
if (options.location !== undefined) {
this.location = options.location;
}
if (options.isInteractive !== undefined) {
this.isInteractive = Boolean(options.isInteractive);
}
}
toEnvironment() {
// Do we really want to assign all of this!?
var env = Object.assign({}, environment); // For compatibility with existing code
env.hasDOM = this.isBrowser;
env.isInteractive = this.isInteractive;
env._renderMode = this._renderMode;
env.options = this;
return env;
}
}
var _default = ApplicationInstance;
_exports.default = _default;
});
define("@ember/application/lib/application", ["exports", "@ember/-internals/utils", "@ember/-internals/environment", "@ember/-internals/browser-environment", "@ember/debug", "@ember/runloop", "@ember/-internals/metal", "@ember/application/lib/lazy_load", "@ember/-internals/runtime", "@ember/-internals/views", "@ember/-internals/routing", "@ember/application/instance", "@ember/engine", "@ember/-internals/container", "@ember/-internals/glimmer"], function (_exports, _utils, _environment, _browserEnvironment, _debug, _runloop, _metal, _lazy_load, _runtime, _views, _routing, _instance, _engine, _container, _glimmer) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module @ember/application
*/
/**
An instance of `Application` is the starting point for every Ember
application. It instantiates, initializes and coordinates the
objects that make up your app.
Each Ember app has one and only one `Application` object. Although
Ember CLI creates this object implicitly, the `Application` class
is defined in the `app/app.js`. You can define a `ready` method on the
`Application` class, which will be run by Ember when the application is
initialized.
```app/app.js
const App = Application.extend({
ready() {
// your code here
}
})
```
Because `Application` ultimately inherits from `Ember.Namespace`, any classes
you create will have useful string representations when calling `toString()`.
See the `Ember.Namespace` documentation for more information.
While you can think of your `Application` as a container that holds the
other classes in your application, there are several other responsibilities
going on under-the-hood that you may want to understand. It is also important
to understand that an `Application` is different from an `ApplicationInstance`.
Refer to the Guides to understand the difference between these.
### Event Delegation
Ember uses a technique called _event delegation_. This allows the framework
to set up a global, shared event listener instead of requiring each view to
do it manually. For example, instead of each view registering its own
`mousedown` listener on its associated element, Ember sets up a `mousedown`
listener on the `body`.
If a `mousedown` event occurs, Ember will look at the target of the event and
start walking up the DOM node tree, finding corresponding views and invoking
their `mouseDown` method as it goes.
`Application` has a number of default events that it listens for, as
well as a mapping from lowercase events to camel-cased view method names. For
example, the `keypress` event causes the `keyPress` method on the view to be
called, the `dblclick` event causes `doubleClick` to be called, and so on.
If there is a bubbling browser event that Ember does not listen for by
default, you can specify custom events and their corresponding view method
names by setting the application's `customEvents` property:
```app/app.js
import Application from '@ember/application';
let App = Application.extend({
customEvents: {
// add support for the paste event
paste: 'paste'
}
});
```
To prevent Ember from setting up a listener for a default event,
specify the event name with a `null` value in the `customEvents`
property:
```app/app.js
import Application from '@ember/application';
let App = Application.extend({
customEvents: {
// prevent listeners for mouseenter/mouseleave events
mouseenter: null,
mouseleave: null
}
});
```
By default, the application sets up these event listeners on the document
body. However, in cases where you are embedding an Ember application inside
an existing page, you may want it to set up the listeners on an element
inside the body.
For example, if only events inside a DOM element with the ID of `ember-app`
should be delegated, set your application's `rootElement` property:
```app/app.js
import Application from '@ember/application';
let App = Application.extend({
rootElement: '#ember-app'
});
```
The `rootElement` can be either a DOM element or a CSS selector
string. Note that *views appended to the DOM outside the root element will
not receive events.* If you specify a custom root element, make sure you only
append views inside it!
To learn more about the events Ember components use, see
[components/handling-events](https://guides.emberjs.com/release/components/handling-events/#toc_event-names).
### Initializers
To add behavior to the Application's boot process, you can define initializers in
the `app/initializers` directory, or with `ember generate initializer` using Ember CLI.
These files should export a named `initialize` function which will receive the created `application`
object as its first argument.
```javascript
export function initialize(application) {
// application.inject('route', 'foo', 'service:foo');
}
```
Application initializers can be used for a variety of reasons including:
- setting up external libraries
- injecting dependencies
- setting up event listeners in embedded apps
- deferring the boot process using the `deferReadiness` and `advanceReadiness` APIs.
### Routing
In addition to creating your application's router, `Application` is
also responsible for telling the router when to start routing. Transitions
between routes can be logged with the `LOG_TRANSITIONS` flag, and more
detailed intra-transition logging can be logged with
the `LOG_TRANSITIONS_INTERNAL` flag:
```javascript
import Application from '@ember/application';
let App = Application.create({
LOG_TRANSITIONS: true, // basic logging of successful transitions
LOG_TRANSITIONS_INTERNAL: true // detailed logging of all routing steps
});
```
By default, the router will begin trying to translate the current URL into
application state once the browser emits the `DOMContentReady` event. If you
need to defer routing, you can call the application's `deferReadiness()`
method. Once routing can begin, call the `advanceReadiness()` method.
If there is any setup required before routing begins, you can implement a
`ready()` method on your app that will be invoked immediately before routing
begins.
@class Application
@extends Engine
@uses RegistryProxyMixin
@public
*/
var Application = _engine.default.extend({
/**
The root DOM element of the Application. This can be specified as an
element or a [selector string](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors#reference_table_of_selectors).
This is the element that will be passed to the Application's,
`eventDispatcher`, which sets up the listeners for event delegation. Every
view in your application should be a child of the element you specify here.
@property rootElement
@type DOMElement
@default 'body'
@public
*/
rootElement: 'body',
/**
@property _document
@type Document | null
@default 'window.document'
@private
*/
_document: _browserEnvironment.hasDOM ? window.document : null,
/**
The `Ember.EventDispatcher` responsible for delegating events to this
application's views.
The event dispatcher is created by the application at initialization time
and sets up event listeners on the DOM element described by the
application's `rootElement` property.
See the documentation for `Ember.EventDispatcher` for more information.
@property eventDispatcher
@type Ember.EventDispatcher
@default null
@public
*/
eventDispatcher: null,
/**
The DOM events for which the event dispatcher should listen.
By default, the application's `Ember.EventDispatcher` listens
for a set of standard DOM events, such as `mousedown` and
`keyup`, and delegates them to your application's `Ember.View`
instances.
If you would like additional bubbling events to be delegated to your
views, set your `Application`'s `customEvents` property
to a hash containing the DOM event name as the key and the
corresponding view method name as the value. Setting an event to
a value of `null` will prevent a default event listener from being
added for that event.
To add new events to be listened to:
```app/app.js
import Application from '@ember/application';
let App = Application.extend({
customEvents: {
// add support for the paste event
paste: 'paste'
}
});
```
To prevent default events from being listened to:
```app/app.js
import Application from '@ember/application';
let App = Application.extend({
customEvents: {
// remove support for mouseenter / mouseleave events
mouseenter: null,
mouseleave: null
}
});
```
@property customEvents
@type Object
@default null
@public
*/
customEvents: null,
/**
Whether the application should automatically start routing and render
templates to the `rootElement` on DOM ready. While default by true,
other environments such as FastBoot or a testing harness can set this
property to `false` and control the precise timing and behavior of the boot
process.
@property autoboot
@type Boolean
@default true
@private
*/
autoboot: true,
/**
Whether the application should be configured for the legacy "globals mode".
Under this mode, the Application object serves as a global namespace for all
classes.
```javascript
import Application from '@ember/application';
import Component from '@ember/component';
let App = Application.create({
...
});
App.Router.reopen({
location: 'none'
});
App.Router.map({
...
});
App.MyComponent = Component.extend({
...
});
```
This flag also exposes other internal APIs that assumes the existence of
a special "default instance", like `App.__container__.lookup(...)`.
This option is currently not configurable, its value is derived from
the `autoboot` flag disabling `autoboot` also implies opting-out of
globals mode support, although they are ultimately orthogonal concerns.
Some of the global modes features are already deprecated in 1.x. The
existence of this flag is to untangle the globals mode code paths from
the autoboot code paths, so that these legacy features can be reviewed
for deprecation/removal separately.
Forcing the (autoboot=true, _globalsMode=false) here and running the tests
would reveal all the places where we are still relying on these legacy
behavior internally (mostly just tests).
@property _globalsMode
@type Boolean
@default true
@private
*/
_globalsMode: true,
/**
An array of application instances created by `buildInstance()`. Used
internally to ensure that all instances get destroyed.
@property _applicationInstances
@type Array
@default null
@private
*/
_applicationInstances: null,
init() {
// eslint-disable-line no-unused-vars
this._super(...arguments);
if (true
/* DEBUG */
) {
if (_environment.ENV.LOG_VERSION) {
// we only need to see this once per Application#init
_environment.ENV.LOG_VERSION = false;
_metal.libraries.logVersions();
}
} // Start off the number of deferrals at 1. This will be decremented by
// the Application's own `boot` method.
this._readinessDeferrals = 1;
this._booted = false;
this._applicationInstances = new Set();
this.autoboot = this._globalsMode = Boolean(this.autoboot);
if (this._globalsMode) {
this._prepareForGlobalsMode();
}
if (this.autoboot) {
this.waitForDOMReady();
}
},
/**
Create an ApplicationInstance for this application.
@public
@method buildInstance
@return {ApplicationInstance} the application instance
*/
buildInstance(options = {}) {
(true && !(!this.isDestroyed) && (0, _debug.assert)('You cannot build new instances of this application since it has already been destroyed', !this.isDestroyed));
(true && !(!this.isDestroying) && (0, _debug.assert)('You cannot build new instances of this application since it is being destroyed', !this.isDestroying));
options.base = this;
options.application = this;
return _instance.default.create(options);
},
/**
Start tracking an ApplicationInstance for this application.
Used when the ApplicationInstance is created.
@private
@method _watchInstance
*/
_watchInstance(instance) {
this._applicationInstances.add(instance);
},
/**
Stop tracking an ApplicationInstance for this application.
Used when the ApplicationInstance is about to be destroyed.
@private
@method _unwatchInstance
*/
_unwatchInstance(instance) {
return this._applicationInstances.delete(instance);
},
/**
Enable the legacy globals mode by allowing this application to act
as a global namespace. See the docs on the `_globalsMode` property
for details.
Most of these features are already deprecated in 1.x, so we can
stop using them internally and try to remove them.
@private
@method _prepareForGlobalsMode
*/
_prepareForGlobalsMode() {
// Create subclass of Router for this Application instance.
// This is to ensure that someone reopening `App.Router` does not
// tamper with the default `Router`.
this.Router = (this.Router || _routing.Router).extend();
this._buildDeprecatedInstance();
},
/*
Build the deprecated instance for legacy globals mode support.
Called when creating and resetting the application.
This is orthogonal to autoboot: the deprecated instance needs to
be created at Application construction (not boot) time to expose
App.__container__. If autoboot sees that this instance exists,
it will continue booting it to avoid doing unncessary work (as
opposed to building a new instance at boot time), but they are
otherwise unrelated.
@private
@method _buildDeprecatedInstance
*/
_buildDeprecatedInstance() {
// Build a default instance
var instance = this.buildInstance(); // Legacy support for App.__container__ and other global methods
// on App that rely on a single, default instance.
this.__deprecatedInstance__ = instance;
this.__container__ = instance.__container__;
},
/**
Automatically kick-off the boot process for the application once the
DOM has become ready.
The initialization itself is scheduled on the actions queue which
ensures that code-loading finishes before booting.
If you are asynchronously loading code, you should call `deferReadiness()`
to defer booting, and then call `advanceReadiness()` once all of your code
has finished loading.
@private
@method waitForDOMReady
*/
waitForDOMReady() {
if (this._document === null || this._document.readyState !== 'loading') {
(0, _runloop.schedule)('actions', this, 'domReady');
} else {
var callback = () => {
this._document.removeEventListener('DOMContentLoaded', callback);
(0, _runloop.run)(this, 'domReady');
};
this._document.addEventListener('DOMContentLoaded', callback);
}
},
/**
This is the autoboot flow:
1. Boot the app by calling `this.boot()`
2. Create an instance (or use the `__deprecatedInstance__` in globals mode)
3. Boot the instance by calling `instance.boot()`
4. Invoke the `App.ready()` callback
5. Kick-off routing on the instance
Ideally, this is all we would need to do:
```javascript
_autoBoot() {
this.boot().then(() => {
let instance = (this._globalsMode) ? this.__deprecatedInstance__ : this.buildInstance();
return instance.boot();
}).then((instance) => {
App.ready();
instance.startRouting();
});
}
```
Unfortunately, we cannot actually write this because we need to participate
in the "synchronous" boot process. While the code above would work fine on
the initial boot (i.e. DOM ready), when `App.reset()` is called, we need to
boot a new instance synchronously (see the documentation on `_bootSync()`
for details).
Because of this restriction, the actual logic of this method is located
inside `didBecomeReady()`.
@private
@method domReady
*/
domReady() {
if (this.isDestroying || this.isDestroyed) {
return;
}
this._bootSync(); // Continues to `didBecomeReady`
},
/**
Use this to defer readiness until some condition is true.
Example:
```javascript
import Application from '@ember/application';
let App = Application.create();
App.deferReadiness();
fetch('/auth-token')
.then(response => response.json())
.then(data => {
App.token = data.token;
App.advanceReadiness();
});
```
This allows you to perform asynchronous setup logic and defer
booting your application until the setup has finished.
However, if the setup requires a loading UI, it might be better
to use the router for this purpose.
@method deferReadiness
@public
*/
deferReadiness() {
(true && !(this instanceof Application) && (0, _debug.assert)('You must call deferReadiness on an instance of Application', this instanceof Application));
(true && !(!this.isDestroyed) && (0, _debug.assert)('You cannot defer readiness since application has already destroyed', !this.isDestroyed));
(true && !(!this.isDestroying) && (0, _debug.assert)('You cannot defer readiness since the application is being destroyed', !this.isDestroying));
(true && !(this._readinessDeferrals > 0) && (0, _debug.assert)('You cannot defer readiness since the `ready()` hook has already been called', this._readinessDeferrals > 0));
this._readinessDeferrals++;
},
/**
Call `advanceReadiness` after any asynchronous setup logic has completed.
Each call to `deferReadiness` must be matched by a call to `advanceReadiness`
or the application will never become ready and routing will not begin.
@method advanceReadiness
@see {Application#deferReadiness}
@public
*/
advanceReadiness() {
(true && !(this instanceof Application) && (0, _debug.assert)('You must call advanceReadiness on an instance of Application', this instanceof Application));
(true && !(!this.isDestroyed) && (0, _debug.assert)('You cannot advance readiness since application has already destroyed', !this.isDestroyed));
(true && !(!this.isDestroying) && (0, _debug.assert)('You cannot advance readiness since the application is being destroyed', !this.isDestroying));
(true && !(this._readinessDeferrals > 0) && (0, _debug.assert)('You cannot advance readiness since the `ready()` hook has already been called', this._readinessDeferrals > 0));
this._readinessDeferrals--;
if (this._readinessDeferrals === 0) {
(0, _runloop.once)(this, this.didBecomeReady);
}
},
/**
Initialize the application and return a promise that resolves with the `Application`
object when the boot process is complete.
Run any application initializers and run the application load hook. These hooks may
choose to defer readiness. For example, an authentication hook might want to defer
readiness until the auth token has been retrieved.
By default, this method is called automatically on "DOM ready"; however, if autoboot
is disabled, this is automatically called when the first application instance is
created via `visit`.
@public
@method boot
@return {Promise<Application,Error>}
*/
boot() {
(true && !(!this.isDestroyed) && (0, _debug.assert)('You cannot boot this application since it has already been destroyed', !this.isDestroyed));
(true && !(!this.isDestroying) && (0, _debug.assert)('You cannot boot this application since it is being destroyed', !this.isDestroying));
if (this._bootPromise) {
return this._bootPromise;
}
try {
this._bootSync();
} catch (_) {// Ignore the error: in the asynchronous boot path, the error is already reflected
// in the promise rejection
}
return this._bootPromise;
},
/**
Unfortunately, a lot of existing code assumes the booting process is
"synchronous". Specifically, a lot of tests assumes the last call to
`app.advanceReadiness()` or `app.reset()` will result in the app being
fully-booted when the current runloop completes.
We would like new code (like the `visit` API) to stop making this assumption,
so we created the asynchronous version above that returns a promise. But until
we have migrated all the code, we would have to expose this method for use
*internally* in places where we need to boot an app "synchronously".
@private
*/
_bootSync() {
if (this._booted || this.isDestroying || this.isDestroyed) {
return;
} // Even though this returns synchronously, we still need to make sure the
// boot promise exists for book-keeping purposes: if anything went wrong in
// the boot process, we need to store the error as a rejection on the boot
// promise so that a future caller of `boot()` can tell what failed.
var defer = this._bootResolver = _runtime.RSVP.defer();
this._bootPromise = defer.promise;
try {
this.runInitializers();
(0, _lazy_load.runLoadHooks)('application', this);
this.advanceReadiness(); // Continues to `didBecomeReady`
} catch (error) {
// For the asynchronous boot path
defer.reject(error); // For the synchronous boot path
throw error;
}
},
/**
Reset the application. This is typically used only in tests. It cleans up
the application in the following order:
1. Deactivate existing routes
2. Destroy all objects in the container
3. Create a new application container
4. Re-route to the existing url
Typical Example:
```javascript
import Application from '@ember/application';
let App;
run(function() {
App = Application.create();
});
module('acceptance test', {
setup: function() {
App.reset();
}
});
test('first test', function() {
// App is freshly reset
});
test('second test', function() {
// App is again freshly reset
});
```
Advanced Example:
Occasionally you may want to prevent the app from initializing during
setup. This could enable extra configuration, or enable asserting prior
to the app becoming ready.
```javascript
import Application from '@ember/application';
let App;
run(function() {
App = Application.create();
});
module('acceptance test', {
setup: function() {
run(function() {
App.reset();
App.deferReadiness();
});
}
});
test('first test', function() {
ok(true, 'something before app is initialized');
run(function() {
App.advanceReadiness();
});
ok(true, 'something after app is initialized');
});
```
@method reset
@public
*/
reset() {
(true && !(!this.isDestroyed) && (0, _debug.assert)('You cannot reset this application since it has already been destroyed', !this.isDestroyed));
(true && !(!this.isDestroying) && (0, _debug.assert)('You cannot reset this application since it is being destroyed', !this.isDestroying));
(true && !(this._globalsMode && this.autoboot) && (0, _debug.assert)(`Calling reset() on instances of \`Application\` is not
supported when globals mode is disabled; call \`visit()\` to
create new \`ApplicationInstance\`s and dispose them
via their \`destroy()\` method instead.`, this._globalsMode && this.autoboot));
var instance = this.__deprecatedInstance__;
this._readinessDeferrals = 1;
this._bootPromise = null;
this._bootResolver = null;
this._booted = false;
function handleReset() {
(0, _runloop.run)(instance, 'destroy');
this._buildDeprecatedInstance();
(0, _runloop.schedule)('actions', this, '_bootSync');
}
(0, _runloop.join)(this, handleReset);
},
/**
@private
@method didBecomeReady
*/
didBecomeReady() {
if (this.isDestroying || this.isDestroyed) {
return;
}
try {
// TODO: Is this still needed for _globalsMode = false?
// See documentation on `_autoboot()` for details
if (this.autoboot) {
var instance;
if (this._globalsMode) {
// If we already have the __deprecatedInstance__ lying around, boot it to
// avoid unnecessary work
instance = this.__deprecatedInstance__;
} else {
// Otherwise, build an instance and boot it. This is currently unreachable,
// because we forced _globalsMode to === autoboot; but having this branch
// allows us to locally toggle that flag for weeding out legacy globals mode
// dependencies independently
instance = this.buildInstance();
}
instance._bootSync(); // TODO: App.ready() is not called when autoboot is disabled, is this correct?
this.ready();
instance.startRouting();
} // For the asynchronous boot path
this._bootResolver.resolve(this); // For the synchronous boot path
this._booted = true;
} catch (error) {
// For the asynchronous boot path
this._bootResolver.reject(error); // For the synchronous boot path
throw error;
}
},
/**
Called when the Application has become ready, immediately before routing
begins. The call will be delayed until the DOM has become ready.
@event ready
@public
*/
ready() {
return this;
},
// This method must be moved to the application instance object
willDestroy() {
this._super(...arguments);
if (_lazy_load._loaded.application === this) {
_lazy_load._loaded.application = undefined;
}
if (this._applicationInstances.size) {
this._applicationInstances.forEach(i => i.destroy());
this._applicationInstances.clear();
}
},
/**
Boot a new instance of `ApplicationInstance` for the current
application and navigate it to the given `url`. Returns a `Promise` that
resolves with the instance when the initial routing and rendering is
complete, or rejects with any error that occurred during the boot process.
When `autoboot` is disabled, calling `visit` would first cause the
application to boot, which runs the application initializers.
This method also takes a hash of boot-time configuration options for
customizing the instance's behavior. See the documentation on
`ApplicationInstance.BootOptions` for details.
`ApplicationInstance.BootOptions` is an interface class that exists
purely to document the available options; you do not need to construct it
manually. Simply pass a regular JavaScript object containing of the
desired options:
```javascript
MyApp.visit("/", { location: "none", rootElement: "#container" });
```
### Supported Scenarios
While the `BootOptions` class exposes a large number of knobs, not all
combinations of them are valid; certain incompatible combinations might
result in unexpected behavior.
For example, booting the instance in the full browser environment
while specifying a foreign `document` object (e.g. `{ isBrowser: true,
document: iframe.contentDocument }`) does not work correctly today,
largely due to Ember's jQuery dependency.
Currently, there are three officially supported scenarios/configurations.
Usages outside of these scenarios are not guaranteed to work, but please
feel free to file bug reports documenting your experience and any issues
you encountered to help expand support.
#### Browser Applications (Manual Boot)
The setup is largely similar to how Ember works out-of-the-box. Normally,
Ember will boot a default instance for your Application on "DOM ready".
However, you can customize this behavior by disabling `autoboot`.
For example, this allows you to render a miniture demo of your application
into a specific area on your marketing website:
```javascript
import MyApp from 'my-app';
$(function() {
let App = MyApp.create({ autoboot: false });
let options = {
// Override the router's location adapter to prevent it from updating
// the URL in the address bar
location: 'none',
// Override the default `rootElement` on the app to render into a
// specific `div` on the page
rootElement: '#demo'
};
// Start the app at the special demo URL
App.visit('/demo', options);
});
```
Or perhaps you might want to boot two instances of your app on the same
page for a split-screen multiplayer experience:
```javascript
import MyApp from 'my-app';
$(function() {
let App = MyApp.create({ autoboot: false });
let sessionId = MyApp.generateSessionID();
let player1 = App.visit(`/matches/join?name=Player+1&session=${sessionId}`, { rootElement: '#left', location: 'none' });
let player2 = App.visit(`/matches/join?name=Player+2&session=${sessionId}`, { rootElement: '#right', location: 'none' });
Promise.all([player1, player2]).then(() => {
// Both apps have completed the initial render
$('#loading').fadeOut();
});
});
```
Do note that each app instance maintains their own registry/container, so
they will run in complete isolation by default.
#### Server-Side Rendering (also known as FastBoot)
This setup allows you to run your Ember app in a server environment using
Node.js and render its content into static HTML for SEO purposes.
```javascript
const HTMLSerializer = new SimpleDOM.HTMLSerializer(SimpleDOM.voidMap);
function renderURL(url) {
let dom = new SimpleDOM.Document();
let rootElement = dom.body;
let options = { isBrowser: false, document: dom, rootElement: rootElement };
return MyApp.visit(options).then(instance => {
try {
return HTMLSerializer.serialize(rootElement.firstChild);
} finally {
instance.destroy();
}
});
}
```
In this scenario, because Ember does not have access to a global `document`
object in the Node.js environment, you must provide one explicitly. In practice,
in the non-browser environment, the stand-in `document` object only needs to
implement a limited subset of the full DOM API. The `SimpleDOM` library is known
to work.
Since there is no DOM access in the non-browser environment, you must also
specify a DOM `Element` object in the same `document` for the `rootElement` option
(as opposed to a selector string like `"body"`).
See the documentation on the `isBrowser`, `document` and `rootElement` properties
on `ApplicationInstance.BootOptions` for details.
#### Server-Side Resource Discovery
This setup allows you to run the routing layer of your Ember app in a server
environment using Node.js and completely disable rendering. This allows you
to simulate and discover the resources (i.e. AJAX requests) needed to fulfill
a given request and eagerly "push" these resources to the client.
```app/initializers/network-service.js
import BrowserNetworkService from 'app/services/network/browser';
import NodeNetworkService from 'app/services/network/node';
// Inject a (hypothetical) service for abstracting all AJAX calls and use
// the appropriate implementation on the client/server. This also allows the
// server to log all the AJAX calls made during a particular request and use
// that for resource-discovery purpose.
export function initialize(application) {
if (window) { // browser
application.register('service:network', BrowserNetworkService);
} else { // node
application.register('service:network', NodeNetworkService);
}
};
export default {
name: 'network-service',
initialize: initialize
};
```
```app/routes/post.js
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
// An example of how the (hypothetical) service is used in routes.
export default class IndexRoute extends Route {
@service network;
model(params) {
return this.network.fetch(`/api/posts/${params.post_id}.json`);
}
afterModel(post) {
if (post.isExternalContent) {
return this.network.fetch(`/api/external/?url=${post.externalURL}`);
} else {
return post;
}
}
}
```
```javascript
// Finally, put all the pieces together
function discoverResourcesFor(url) {
return MyApp.visit(url, { isBrowser: false, shouldRender: false }).then(instance => {
let networkService = instance.lookup('service:network');
return networkService.requests; // => { "/api/posts/123.json": "..." }
});
}
```
@public
@method visit
@param url {String} The initial URL to navigate to
@param options {ApplicationInstance.BootOptions}
@return {Promise<ApplicationInstance, Error>}
*/
visit(url, options) {
(true && !(!this.isDestroyed) && (0, _debug.assert)('You cannot visit this application since it has already been destroyed', !this.isDestroyed));
(true && !(!this.isDestroying) && (0, _debug.assert)('You cannot visit this application since it is being destroyed', !this.isDestroying));
return this.boot().then(() => {
var instance = this.buildInstance();
return instance.boot(options).then(() => instance.visit(url)).catch(error => {
(0, _runloop.run)(instance, 'destroy');
throw error;
});
});
}
});
Application.reopenClass({
/**
This creates a registry with the default Ember naming conventions.
It also configures the registry:
* registered views are created every time they are looked up (they are
not singletons)
* registered templates are not factories; the registered value is
returned directly.
* the router receives the application as its `namespace` property
* all controllers receive the router as their `target` and `controllers`
properties
* all controllers receive the application as their `namespace` property
* the application view receives the application controller as its
`controller` property
* the application view receives the application template as its
`defaultTemplate` property
@method buildRegistry
@static
@param {Application} namespace the application for which to
build the registry
@return {Ember.Registry} the built registry
@private
*/
buildRegistry() {
// eslint-disable-line no-unused-vars
var registry = this._super(...arguments);
commonSetupRegistry(registry);
(0, _glimmer.setupApplicationRegistry)(registry);
return registry;
}
});
function commonSetupRegistry(registry) {
registry.register('router:main', _routing.Router);
registry.register('-view-registry:main', {
create() {
return (0, _utils.dictionary)(null);
}
});
registry.register('route:basic', _routing.Route);
registry.register('event_dispatcher:main', _views.EventDispatcher);
registry.register('location:auto', _routing.AutoLocation);
registry.register('location:hash', _routing.HashLocation);
registry.register('location:history', _routing.HistoryLocation);
registry.register('location:none', _routing.NoneLocation);
registry.register((0, _container.privatize)`-bucket-cache:main`, {
create() {
return new _routing.BucketCache();
}
});
registry.register('service:router', _routing.RouterService);
}
var _default = Application;
_exports.default = _default;
});
define("@ember/application/lib/lazy_load", ["exports", "@ember/-internals/environment", "@ember/-internals/browser-environment"], function (_exports, _environment, _browserEnvironment) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.onLoad = onLoad;
_exports.runLoadHooks = runLoadHooks;
_exports._loaded = void 0;
/*globals CustomEvent */
/**
@module @ember/application
*/
var loadHooks = _environment.ENV.EMBER_LOAD_HOOKS || {};
var loaded = {};
var _loaded = loaded;
/**
Detects when a specific package of Ember (e.g. 'Application')
has fully loaded and is available for extension.
The provided `callback` will be called with the `name` passed
resolved from a string into the object:
``` javascript
import { onLoad } from '@ember/application';
onLoad('Ember.Application' function(hbars) {
hbars.registerHelper(...);
});
```
@method onLoad
@static
@for @ember/application
@param name {String} name of hook
@param callback {Function} callback to be called
@private
*/
_exports._loaded = _loaded;
function onLoad(name, callback) {
var object = loaded[name];
loadHooks[name] = loadHooks[name] || [];
loadHooks[name].push(callback);
if (object) {
callback(object);
}
}
/**
Called when an Ember.js package (e.g Application) has finished
loading. Triggers any callbacks registered for this event.
@method runLoadHooks
@static
@for @ember/application
@param name {String} name of hook
@param object {Object} object to pass to callbacks
@private
*/
function runLoadHooks(name, object) {
loaded[name] = object;
if (_browserEnvironment.window && typeof CustomEvent === 'function') {
var event = new CustomEvent(name, {
detail: object,
name
});
_browserEnvironment.window.dispatchEvent(event);
}
if (loadHooks[name]) {
loadHooks[name].forEach(callback => callback(object));
}
}
});
define("@ember/application/namespace", ["exports", "@ember/-internals/runtime"], function (_exports, _runtime) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _runtime.Namespace;
}
});
});
define("@ember/array/index", ["exports", "@ember/-internals/runtime", "@ember/-internals/utils"], function (_exports, _runtime, _utils) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _runtime.Array;
}
});
Object.defineProperty(_exports, "isArray", {
enumerable: true,
get: function () {
return _runtime.isArray;
}
});
Object.defineProperty(_exports, "A", {
enumerable: true,
get: function () {
return _runtime.A;
}
});
Object.defineProperty(_exports, "makeArray", {
enumerable: true,
get: function () {
return _utils.makeArray;
}
});
});
define("@ember/array/mutable", ["exports", "@ember/-internals/runtime"], function (_exports, _runtime) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _runtime.MutableArray;
}
});
});
define("@ember/array/proxy", ["exports", "@ember/-internals/runtime"], function (_exports, _runtime) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _runtime.ArrayProxy;
}
});
});
define("@ember/canary-features/index", ["exports", "@ember/-internals/environment"], function (_exports, _environment) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.isEnabled = isEnabled;
_exports.EMBER_ROUTING_ROUTER_SERVICE_REFRESH = _exports.EMBER_DYNAMIC_HELPERS_AND_MODIFIERS = _exports.EMBER_STRICT_MODE = _exports.EMBER_GLIMMER_INVOKE_HELPER = _exports.EMBER_GLIMMER_HELPER_MANAGER = _exports.EMBER_NAMED_BLOCKS = _exports.EMBER_IMPROVED_INSTRUMENTATION = _exports.EMBER_LIBRARIES_ISREGISTERED = _exports.FEATURES = _exports.DEFAULT_FEATURES = void 0;
/**
Set `EmberENV.FEATURES` in your application's `config/environment.js` file
to enable canary features in your application.
See the [feature flag guide](https://guides.emberjs.com/release/configuring-ember/feature-flags/)
for more details.
@module @ember/canary-features
@public
*/
var DEFAULT_FEATURES = {
EMBER_LIBRARIES_ISREGISTERED: false,
EMBER_IMPROVED_INSTRUMENTATION: false,
EMBER_NAMED_BLOCKS: true,
EMBER_GLIMMER_HELPER_MANAGER: true,
EMBER_GLIMMER_INVOKE_HELPER: true,
EMBER_STRICT_MODE: true,
EMBER_DYNAMIC_HELPERS_AND_MODIFIERS: true,
EMBER_ROUTING_ROUTER_SERVICE_REFRESH: false
};
/**
The hash of enabled Canary features. Add to this, any canary features
before creating your application.
@class FEATURES
@static
@since 1.1.0
@public
*/
_exports.DEFAULT_FEATURES = DEFAULT_FEATURES;
var FEATURES = Object.assign(DEFAULT_FEATURES, _environment.ENV.FEATURES);
/**
Determine whether the specified `feature` is enabled. Used by Ember's
build tools to exclude experimental features from beta/stable builds.
You can define the following configuration options:
* `EmberENV.ENABLE_OPTIONAL_FEATURES` - enable any features that have not been explicitly
enabled/disabled.
@method isEnabled
@param {String} feature The feature to check
@return {Boolean}
@since 1.1.0
@public
*/
_exports.FEATURES = FEATURES;
function isEnabled(feature) {
var value = FEATURES[feature];
if (value === true || value === false) {
return value;
} else if (_environment.ENV.ENABLE_OPTIONAL_FEATURES) {
return true;
} else {
return false;
}
}
function featureValue(value) {
if (_environment.ENV.ENABLE_OPTIONAL_FEATURES && value === null) {
return true;
}
return value;
}
var EMBER_LIBRARIES_ISREGISTERED = featureValue(FEATURES.EMBER_LIBRARIES_ISREGISTERED);
_exports.EMBER_LIBRARIES_ISREGISTERED = EMBER_LIBRARIES_ISREGISTERED;
var EMBER_IMPROVED_INSTRUMENTATION = featureValue(FEATURES.EMBER_IMPROVED_INSTRUMENTATION);
_exports.EMBER_IMPROVED_INSTRUMENTATION = EMBER_IMPROVED_INSTRUMENTATION;
var EMBER_NAMED_BLOCKS = featureValue(FEATURES.EMBER_NAMED_BLOCKS);
_exports.EMBER_NAMED_BLOCKS = EMBER_NAMED_BLOCKS;
var EMBER_GLIMMER_HELPER_MANAGER = featureValue(FEATURES.EMBER_GLIMMER_HELPER_MANAGER);
_exports.EMBER_GLIMMER_HELPER_MANAGER = EMBER_GLIMMER_HELPER_MANAGER;
var EMBER_GLIMMER_INVOKE_HELPER = featureValue(FEATURES.EMBER_GLIMMER_INVOKE_HELPER);
_exports.EMBER_GLIMMER_INVOKE_HELPER = EMBER_GLIMMER_INVOKE_HELPER;
var EMBER_STRICT_MODE = featureValue(FEATURES.EMBER_STRICT_MODE);
_exports.EMBER_STRICT_MODE = EMBER_STRICT_MODE;
var EMBER_DYNAMIC_HELPERS_AND_MODIFIERS = featureValue(FEATURES.EMBER_DYNAMIC_HELPERS_AND_MODIFIERS);
_exports.EMBER_DYNAMIC_HELPERS_AND_MODIFIERS = EMBER_DYNAMIC_HELPERS_AND_MODIFIERS;
var EMBER_ROUTING_ROUTER_SERVICE_REFRESH = featureValue(FEATURES.EMBER_ROUTING_ROUTER_SERVICE_REFRESH);
_exports.EMBER_ROUTING_ROUTER_SERVICE_REFRESH = EMBER_ROUTING_ROUTER_SERVICE_REFRESH;
});
define("@ember/component/helper", ["exports", "@ember/-internals/glimmer"], function (_exports, _glimmer) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _glimmer.Helper;
}
});
Object.defineProperty(_exports, "helper", {
enumerable: true,
get: function () {
return _glimmer.helper;
}
});
});
define("@ember/component/index", ["exports", "@glimmer/manager", "@ember/-internals/glimmer"], function (_exports, _manager, _glimmer) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "setComponentTemplate", {
enumerable: true,
get: function () {
return _manager.setComponentTemplate;
}
});
Object.defineProperty(_exports, "getComponentTemplate", {
enumerable: true,
get: function () {
return _manager.getComponentTemplate;
}
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _glimmer.Component;
}
});
Object.defineProperty(_exports, "Input", {
enumerable: true,
get: function () {
return _glimmer.Input;
}
});
Object.defineProperty(_exports, "Textarea", {
enumerable: true,
get: function () {
return _glimmer.Textarea;
}
});
Object.defineProperty(_exports, "capabilities", {
enumerable: true,
get: function () {
return _glimmer.componentCapabilities;
}
});
Object.defineProperty(_exports, "setComponentManager", {
enumerable: true,
get: function () {
return _glimmer.setComponentManager;
}
});
});
define("@ember/component/template-only", ["exports", "@glimmer/runtime"], function (_exports, _runtime) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _runtime.templateOnlyComponent;
}
});
});
define("@ember/controller/index", ["exports", "@ember/-internals/runtime", "@ember/-internals/metal", "@ember/controller/lib/controller_mixin"], function (_exports, _runtime, _metal, _controller_mixin) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.inject = inject;
_exports.default = void 0;
/**
@module @ember/controller
*/
/**
@class Controller
@extends EmberObject
@uses Ember.ControllerMixin
@public
*/
var Controller = _runtime.FrameworkObject.extend(_controller_mixin.default);
/**
Creates a property that lazily looks up another controller in the container.
Can only be used when defining another controller.
Example:
```app/controllers/post.js
import Controller, {
inject as controller
} from '@ember/controller';
export default class PostController extends Controller {
@controller posts;
}
```
Classic Class Example:
```app/controllers/post.js
import Controller, {
inject as controller
} from '@ember/controller';
export default Controller.extend({
posts: controller()
});
```
This example will create a `posts` property on the `post` controller that
looks up the `posts` controller in the container, making it easy to reference
other controllers.
@method inject
@static
@for @ember/controller
@since 1.10.0
@param {String} name (optional) name of the controller to inject, defaults to
the property's name
@return {ComputedDecorator} injection decorator instance
@public
*/
function inject() {
return (0, _metal.inject)('controller', ...arguments);
}
var _default = Controller;
_exports.default = _default;
});
define("@ember/controller/lib/controller_mixin", ["exports", "@ember/-internals/metal", "@ember/-internals/runtime", "@ember/-internals/utils"], function (_exports, _metal, _runtime, _utils) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
var MODEL = (0, _utils.symbol)('MODEL');
/**
@module ember
*/
/**
@class ControllerMixin
@namespace Ember
@uses Ember.ActionHandler
@private
*/
var _default = _metal.Mixin.create(_runtime.ActionHandler, {
/* ducktype as a controller */
isController: true,
/**
The object to which actions from the view should be sent.
For example, when a Handlebars template uses the `{{action}}` helper,
it will attempt to send the action to the view's controller's `target`.
By default, the value of the target property is set to the router, and
is injected when a controller is instantiated. This injection is applied
as part of the application's initialization process. In most cases the
`target` property will automatically be set to the logical consumer of
actions for the controller.
@property target
@default null
@public
*/
target: null,
store: null,
/**
The controller's current model. When retrieving or modifying a controller's
model, this property should be used instead of the `content` property.
@property model
@public
*/
model: (0, _metal.computed)({
get() {
return this[MODEL];
},
set(key, value) {
return this[MODEL] = value;
}
})
});
_exports.default = _default;
});
define("@ember/debug/container-debug-adapter", ["exports", "@ember/-internals/extension-support"], function (_exports, _extensionSupport) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _extensionSupport.ContainerDebugAdapter;
}
});
});
define("@ember/debug/data-adapter", ["exports", "@ember/-internals/extension-support"], function (_exports, _extensionSupport) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _extensionSupport.DataAdapter;
}
});
});
define("@ember/debug/index", ["exports", "@ember/-internals/browser-environment", "@ember/error", "@ember/debug/lib/deprecate", "@ember/debug/lib/testing", "@ember/debug/lib/warn", "@ember/-internals/utils", "@ember/debug/lib/capture-render-tree"], function (_exports, _browserEnvironment, _error, _deprecate2, _testing, _warn2, _utils, _captureRenderTree) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "registerDeprecationHandler", {
enumerable: true,
get: function () {
return _deprecate2.registerHandler;
}
});
Object.defineProperty(_exports, "isTesting", {
enumerable: true,
get: function () {
return _testing.isTesting;
}
});
Object.defineProperty(_exports, "setTesting", {
enumerable: true,
get: function () {
return _testing.setTesting;
}
});
Object.defineProperty(_exports, "registerWarnHandler", {
enumerable: true,
get: function () {
return _warn2.registerHandler;
}
});
Object.defineProperty(_exports, "inspect", {
enumerable: true,
get: function () {
return _utils.inspect;
}
});
Object.defineProperty(_exports, "captureRenderTree", {
enumerable: true,
get: function () {
return _captureRenderTree.default;
}
});
_exports._warnIfUsingStrippedFeatureFlags = _exports.getDebugFunction = _exports.setDebugFunction = _exports.deprecateFunc = _exports.runInDebug = _exports.debugFreeze = _exports.debugSeal = _exports.deprecate = _exports.debug = _exports.warn = _exports.info = _exports.assert = void 0;
// These are the default production build versions:
var noop = () => {};
var assert = noop;
_exports.assert = assert;
var info = noop;
_exports.info = info;
var warn = noop;
_exports.warn = warn;
var debug = noop;
_exports.debug = debug;
var deprecate = noop;
_exports.deprecate = deprecate;
var debugSeal = noop;
_exports.debugSeal = debugSeal;
var debugFreeze = noop;
_exports.debugFreeze = debugFreeze;
var runInDebug = noop;
_exports.runInDebug = runInDebug;
var setDebugFunction = noop;
_exports.setDebugFunction = setDebugFunction;
var getDebugFunction = noop;
_exports.getDebugFunction = getDebugFunction;
var deprecateFunc = function () {
return arguments[arguments.length - 1];
};
_exports.deprecateFunc = deprecateFunc;
if (true
/* DEBUG */
) {
_exports.setDebugFunction = setDebugFunction = function (type, callback) {
switch (type) {
case 'assert':
return _exports.assert = assert = callback;
case 'info':
return _exports.info = info = callback;
case 'warn':
return _exports.warn = warn = callback;
case 'debug':
return _exports.debug = debug = callback;
case 'deprecate':
return _exports.deprecate = deprecate = callback;
case 'debugSeal':
return _exports.debugSeal = debugSeal = callback;
case 'debugFreeze':
return _exports.debugFreeze = debugFreeze = callback;
case 'runInDebug':
return _exports.runInDebug = runInDebug = callback;
case 'deprecateFunc':
return _exports.deprecateFunc = deprecateFunc = callback;
}
};
_exports.getDebugFunction = getDebugFunction = function (type) {
switch (type) {
case 'assert':
return assert;
case 'info':
return info;
case 'warn':
return warn;
case 'debug':
return debug;
case 'deprecate':
return deprecate;
case 'debugSeal':
return debugSeal;
case 'debugFreeze':
return debugFreeze;
case 'runInDebug':
return runInDebug;
case 'deprecateFunc':
return deprecateFunc;
}
};
}
/**
@module @ember/debug
*/
if (true
/* DEBUG */
) {
/**
Verify that a certain expectation is met, or throw a exception otherwise.
This is useful for communicating assumptions in the code to other human
readers as well as catching bugs that accidentally violates these
expectations.
Assertions are removed from production builds, so they can be freely added
for documentation and debugging purposes without worries of incuring any
performance penalty. However, because of that, they should not be used for
checks that could reasonably fail during normal usage. Furthermore, care
should be taken to avoid accidentally relying on side-effects produced from
evaluating the condition itself, since the code will not run in production.
```javascript
import { assert } from '@ember/debug';
// Test for truthiness
assert('Must pass a string', typeof str === 'string');
// Fail unconditionally
assert('This code path should never be run');
```
@method assert
@static
@for @ember/debug
@param {String} description Describes the expectation. This will become the
text of the Error thrown if the assertion fails.
@param {any} condition Must be truthy for the assertion to pass. If
falsy, an exception will be thrown.
@public
@since 1.0.0
*/
setDebugFunction('assert', function assert(desc, test) {
if (!test) {
throw new _error.default(`Assertion Failed: ${desc}`);
}
});
/**
Display a debug notice.
Calls to this function are not invoked in production builds.
```javascript
import { debug } from '@ember/debug';
debug('I\'m a debug notice!');
```
@method debug
@for @ember/debug
@static
@param {String} message A debug message to display.
@public
*/
setDebugFunction('debug', function debug(message) {
/* eslint-disable no-console */
if (console.debug) {
console.debug(`DEBUG: ${message}`);
} else {
console.log(`DEBUG: ${message}`);
}
/* eslint-ensable no-console */
});
/**
Display an info notice.
Calls to this function are removed from production builds, so they can be
freely added for documentation and debugging purposes without worries of
incuring any performance penalty.
@method info
@private
*/
setDebugFunction('info', function info() {
console.info(...arguments);
/* eslint-disable-line no-console */
});
/**
@module @ember/debug
@public
*/
/**
Alias an old, deprecated method with its new counterpart.
Display a deprecation warning with the provided message and a stack trace
(Chrome and Firefox only) when the assigned method is called.
Calls to this function are removed from production builds, so they can be
freely added for documentation and debugging purposes without worries of
incuring any performance penalty.
```javascript
import { deprecateFunc } from '@ember/debug';
Ember.oldMethod = deprecateFunc('Please use the new, updated method', options, Ember.newMethod);
```
@method deprecateFunc
@static
@for @ember/debug
@param {String} message A description of the deprecation.
@param {Object} [options] The options object for `deprecate`.
@param {Function} func The new function called to replace its deprecated counterpart.
@return {Function} A new function that wraps the original function with a deprecation warning
@private
*/
setDebugFunction('deprecateFunc', function deprecateFunc(...args) {
if (args.length === 3) {
var [message, options, func] = args;
return function (...args) {
deprecate(message, false, options);
return func.apply(this, args);
};
} else {
var [_message, _func] = args;
return function () {
deprecate(_message);
return _func.apply(this, arguments);
};
}
});
/**
@module @ember/debug
@public
*/
/**
Run a function meant for debugging.
Calls to this function are removed from production builds, so they can be
freely added for documentation and debugging purposes without worries of
incuring any performance penalty.
```javascript
import Component from '@ember/component';
import { runInDebug } from '@ember/debug';
runInDebug(() => {
Component.reopen({
didInsertElement() {
console.log("I'm happy");
}
});
});
```
@method runInDebug
@for @ember/debug
@static
@param {Function} func The function to be executed.
@since 1.5.0
@public
*/
setDebugFunction('runInDebug', function runInDebug(func) {
func();
});
setDebugFunction('debugSeal', function debugSeal(obj) {
Object.seal(obj);
});
setDebugFunction('debugFreeze', function debugFreeze(obj) {
// re-freezing an already frozen object introduces a significant
// performance penalty on Chrome (tested through 59).
//
// See: https://bugs.chromium.org/p/v8/issues/detail?id=6450
if (!Object.isFrozen(obj)) {
Object.freeze(obj);
}
});
setDebugFunction('deprecate', _deprecate2.default);
setDebugFunction('warn', _warn2.default);
}
var _warnIfUsingStrippedFeatureFlags;
_exports._warnIfUsingStrippedFeatureFlags = _warnIfUsingStrippedFeatureFlags;
if (true
/* DEBUG */
&& !(0, _testing.isTesting)()) {
if (typeof window !== 'undefined' && (_browserEnvironment.isFirefox || _browserEnvironment.isChrome) && window.addEventListener) {
window.addEventListener('load', () => {
if (document.documentElement && document.documentElement.dataset && !document.documentElement.dataset.emberExtension) {
var downloadURL;
if (_browserEnvironment.isChrome) {
downloadURL = 'https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi';
} else if (_browserEnvironment.isFirefox) {
downloadURL = 'https://addons.mozilla.org/en-US/firefox/addon/ember-inspector/';
}
debug(`For more advanced debugging, install the Ember Inspector from ${downloadURL}`);
}
}, false);
}
}
});
define("@ember/debug/lib/capture-render-tree", ["exports", "@glimmer/util"], function (_exports, _util) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = captureRenderTree;
/**
@module @ember/debug
*/
/**
Ember Inspector calls this function to capture the current render tree.
In production mode, this requires turning on `ENV._DEBUG_RENDER_TREE`
before loading Ember.
@private
@static
@method captureRenderTree
@for @ember/debug
@param app {ApplicationInstance} An `ApplicationInstance`.
@since 3.14.0
*/
function captureRenderTree(app) {
var renderer = (0, _util.expect)(app.lookup('renderer:-dom'), `BUG: owner is missing renderer`);
return renderer.debugRenderTree.capture();
}
});
define("@ember/debug/lib/deprecate", ["exports", "@ember/-internals/environment", "@ember/debug/index", "@ember/debug/lib/handlers"], function (_exports, _environment, _index, _handlers) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.missingOptionDeprecation = _exports.missingOptionsIdDeprecation = _exports.missingOptionsDeprecation = _exports.registerHandler = _exports.default = void 0;
/**
@module @ember/debug
@public
*/
/**
Allows for runtime registration of handler functions that override the default deprecation behavior.
Deprecations are invoked by calls to [@ember/debug/deprecate](/ember/release/classes/@ember%2Fdebug/methods/deprecate?anchor=deprecate).
The following example demonstrates its usage by registering a handler that throws an error if the
message contains the word "should", otherwise defers to the default handler.
```javascript
import { registerDeprecationHandler } from '@ember/debug';
registerDeprecationHandler((message, options, next) => {
if (message.indexOf('should') !== -1) {
throw new Error(`Deprecation message with should: ${message}`);
} else {
// defer to whatever handler was registered before this one
next(message, options);
}
});
```
The handler function takes the following arguments:
<ul>
<li> <code>message</code> - The message received from the deprecation call.</li>
<li> <code>options</code> - An object passed in with the deprecation call containing additional information including:</li>
<ul>
<li> <code>id</code> - An id of the deprecation in the form of <code>package-name.specific-deprecation</code>.</li>
<li> <code>until</code> - The Ember version number the feature and deprecation will be removed in.</li>
</ul>
<li> <code>next</code> - A function that calls into the previously registered handler.</li>
</ul>
@public
@static
@method registerDeprecationHandler
@for @ember/debug
@param handler {Function} A function to handle deprecation calls.
@since 2.1.0
*/
var registerHandler = () => {};
_exports.registerHandler = registerHandler;
var missingOptionsDeprecation;
_exports.missingOptionsDeprecation = missingOptionsDeprecation;
var missingOptionsIdDeprecation;
_exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation;
var missingOptionDeprecation = () => '';
_exports.missingOptionDeprecation = missingOptionDeprecation;
var deprecate = () => {};
if (true
/* DEBUG */
) {
_exports.registerHandler = registerHandler = function registerHandler(handler) {
(0, _handlers.registerHandler)('deprecate', handler);
};
var formatMessage = function formatMessage(_message, options) {
var message = _message;
if (options && options.id) {
message = message + ` [deprecation id: ${options.id}]`;
}
if (options && options.url) {
message += ` See ${options.url} for more details.`;
}
return message;
};
registerHandler(function logDeprecationToConsole(message, options) {
var updatedMessage = formatMessage(message, options);
console.warn(`DEPRECATION: ${updatedMessage}`); // eslint-disable-line no-console
});
var captureErrorForStack;
if (new Error().stack) {
captureErrorForStack = () => new Error();
} else {
captureErrorForStack = () => {
try {
__fail__.fail();
} catch (e) {
return e;
}
};
}
registerHandler(function logDeprecationStackTrace(message, options, next) {
if (_environment.ENV.LOG_STACKTRACE_ON_DEPRECATION) {
var stackStr = '';
var error = captureErrorForStack();
var stack;
if (error.stack) {
if (error['arguments']) {
// Chrome
stack = error.stack.replace(/^\s+at\s+/gm, '').replace(/^([^(]+?)([\n$])/gm, '{anonymous}($1)$2').replace(/^Object.<anonymous>\s*\(([^)]+)\)/gm, '{anonymous}($1)').split('\n');
stack.shift();
} else {
// Firefox
stack = error.stack.replace(/(?:\n@:0)?\s+$/m, '').replace(/^\(/gm, '{anonymous}(').split('\n');
}
stackStr = `\n ${stack.slice(2).join('\n ')}`;
}
var updatedMessage = formatMessage(message, options);
console.warn(`DEPRECATION: ${updatedMessage}${stackStr}`); // eslint-disable-line no-console
} else {
next(message, options);
}
});
registerHandler(function raiseOnDeprecation(message, options, next) {
if (_environment.ENV.RAISE_ON_DEPRECATION) {
var updatedMessage = formatMessage(message);
throw new Error(updatedMessage);
} else {
next(message, options);
}
});
_exports.missingOptionsDeprecation = missingOptionsDeprecation = 'When calling `deprecate` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include `id` and `until` properties.';
_exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation = 'When calling `deprecate` you must provide `id` in options.';
_exports.missingOptionDeprecation = missingOptionDeprecation = (id, missingOption) => {
return `When calling \`deprecate\` you must provide \`${missingOption}\` in options. Missing options.${missingOption} in "${id}" deprecation`;
};
/**
@module @ember/debug
@public
*/
/**
Display a deprecation warning with the provided message and a stack trace
(Chrome and Firefox only).
* In a production build, this method is defined as an empty function (NOP).
Uses of this method in Ember itself are stripped from the ember.prod.js build.
@method deprecate
@for @ember/debug
@param {String} message A description of the deprecation.
@param {Boolean} test A boolean. If falsy, the deprecation will be displayed.
@param {Object} options
@param {String} options.id A unique id for this deprecation. The id can be
used by Ember debugging tools to change the behavior (raise, log or silence)
for that specific deprecation. The id should be namespaced by dots, e.g.
"view.helper.select".
@param {string} options.until The version of Ember when this deprecation
warning will be removed.
@param {String} options.for A namespace for the deprecation, usually the package name
@param {Object} options.since Describes when the deprecation became available and enabled.
@param {String} [options.url] An optional url to the transition guide on the
emberjs.com website.
@static
@public
@since 1.0.0
*/
deprecate = function deprecate(message, test, options) {
(0, _index.assert)(missingOptionsDeprecation, Boolean(options && (options.id || options.until)));
(0, _index.assert)(missingOptionsIdDeprecation, Boolean(options.id));
(0, _index.assert)(missingOptionDeprecation(options.id, 'until'), Boolean(options.until));
(0, _index.assert)(missingOptionDeprecation(options.id, 'for'), Boolean(options.for));
(0, _index.assert)(missingOptionDeprecation(options.id, 'since'), Boolean(options.since));
(0, _handlers.invoke)('deprecate', message, test, options);
};
}
var _default = deprecate;
_exports.default = _default;
});
define("@ember/debug/lib/handlers", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.invoke = _exports.registerHandler = _exports.HANDLERS = void 0;
var HANDLERS = {};
_exports.HANDLERS = HANDLERS;
var registerHandler = () => {};
_exports.registerHandler = registerHandler;
var invoke = () => {};
_exports.invoke = invoke;
if (true
/* DEBUG */
) {
_exports.registerHandler = registerHandler = function registerHandler(type, callback) {
var nextHandler = HANDLERS[type] || (() => {});
HANDLERS[type] = (message, options) => {
callback(message, options, nextHandler);
};
};
_exports.invoke = invoke = function invoke(type, message, test, options) {
if (test) {
return;
}
var handlerForType = HANDLERS[type];
if (handlerForType) {
handlerForType(message, options);
}
};
}
});
define("@ember/debug/lib/testing", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.isTesting = isTesting;
_exports.setTesting = setTesting;
var testing = false;
function isTesting() {
return testing;
}
function setTesting(value) {
testing = Boolean(value);
}
});
define("@ember/debug/lib/warn", ["exports", "@ember/debug/index", "@ember/debug/lib/handlers"], function (_exports, _index, _handlers) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.missingOptionsDeprecation = _exports.missingOptionsIdDeprecation = _exports.registerHandler = _exports.default = void 0;
var registerHandler = () => {};
_exports.registerHandler = registerHandler;
var warn = () => {};
var missingOptionsDeprecation;
_exports.missingOptionsDeprecation = missingOptionsDeprecation;
var missingOptionsIdDeprecation;
/**
@module @ember/debug
*/
_exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation;
if (true
/* DEBUG */
) {
/**
Allows for runtime registration of handler functions that override the default warning behavior.
Warnings are invoked by calls made to [@ember/debug/warn](/ember/release/classes/@ember%2Fdebug/methods/warn?anchor=warn).
The following example demonstrates its usage by registering a handler that does nothing overriding Ember's
default warning behavior.
```javascript
import { registerWarnHandler } from '@ember/debug';
// next is not called, so no warnings get the default behavior
registerWarnHandler(() => {});
```
The handler function takes the following arguments:
<ul>
<li> <code>message</code> - The message received from the warn call. </li>
<li> <code>options</code> - An object passed in with the warn call containing additional information including:</li>
<ul>
<li> <code>id</code> - An id of the warning in the form of <code>package-name.specific-warning</code>.</li>
</ul>
<li> <code>next</code> - A function that calls into the previously registered handler.</li>
</ul>
@public
@static
@method registerWarnHandler
@for @ember/debug
@param handler {Function} A function to handle warnings.
@since 2.1.0
*/
_exports.registerHandler = registerHandler = function registerHandler(handler) {
(0, _handlers.registerHandler)('warn', handler);
};
registerHandler(function logWarning(message) {
/* eslint-disable no-console */
console.warn(`WARNING: ${message}`);
/* eslint-enable no-console */
});
_exports.missingOptionsDeprecation = missingOptionsDeprecation = 'When calling `warn` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include an `id` property.';
_exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation = 'When calling `warn` you must provide `id` in options.';
/**
Display a warning with the provided message.
* In a production build, this method is defined as an empty function (NOP).
Uses of this method in Ember itself are stripped from the ember.prod.js build.
```javascript
import { warn } from '@ember/debug';
import tomsterCount from './tomster-counter'; // a module in my project
// Log a warning if we have more than 3 tomsters
warn('Too many tomsters!', tomsterCount <= 3, {
id: 'ember-debug.too-many-tomsters'
});
```
@method warn
@for @ember/debug
@static
@param {String} message A warning to display.
@param {Boolean} test An optional boolean. If falsy, the warning
will be displayed.
@param {Object} options An object that can be used to pass a unique
`id` for this warning. The `id` can be used by Ember debugging tools
to change the behavior (raise, log, or silence) for that specific warning.
The `id` should be namespaced by dots, e.g. "ember-debug.feature-flag-with-features-stripped"
@public
@since 1.0.0
*/
warn = function warn(message, test, options) {
if (arguments.length === 2 && typeof test === 'object') {
options = test;
test = false;
}
(0, _index.assert)(missingOptionsDeprecation, Boolean(options));
(0, _index.assert)(missingOptionsIdDeprecation, Boolean(options && options.id));
(0, _handlers.invoke)('warn', message, test, options);
};
}
var _default = warn;
_exports.default = _default;
});
define("@ember/deprecated-features/index", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.ASSIGN = void 0;
/* eslint-disable no-implicit-coercion */
// These versions should be the version that the deprecation was _introduced_,
// not the version that the feature will be removed.
var ASSIGN = !!'4.0.0-beta.1';
_exports.ASSIGN = ASSIGN;
});
define("@ember/destroyable/index", ["exports", "@glimmer/destroyable"], function (_exports, _destroyable) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.registerDestructor = registerDestructor;
_exports.unregisterDestructor = unregisterDestructor;
Object.defineProperty(_exports, "assertDestroyablesDestroyed", {
enumerable: true,
get: function () {
return _destroyable.assertDestroyablesDestroyed;
}
});
Object.defineProperty(_exports, "associateDestroyableChild", {
enumerable: true,
get: function () {
return _destroyable.associateDestroyableChild;
}
});
Object.defineProperty(_exports, "destroy", {
enumerable: true,
get: function () {
return _destroyable.destroy;
}
});
Object.defineProperty(_exports, "enableDestroyableTracking", {
enumerable: true,
get: function () {
return _destroyable.enableDestroyableTracking;
}
});
Object.defineProperty(_exports, "isDestroying", {
enumerable: true,
get: function () {
return _destroyable.isDestroying;
}
});
Object.defineProperty(_exports, "isDestroyed", {
enumerable: true,
get: function () {
return _destroyable.isDestroyed;
}
});
/**
Ember manages the lifecycles and lifetimes of many built in constructs, such
as components, and does so in a hierarchical way - when a parent component is
destroyed, all of its children are destroyed as well.
This destroyables API exposes the basic building blocks for destruction:
* registering a function to be ran when an object is destroyyed
* checking if an object is in a destroying state
* associate an object as a child of another so that the child object will be destroyed
when the associated parent object is destroyed.
@module @ember/destroyable
@public
*/
/**
This function is used to associate a destroyable object with a parent. When the parent
is destroyed, all registered children will also be destroyed.
```js
class CustomSelect extends Component {
constructor() {
// obj is now a child of the component. When the component is destroyed,
// obj will also be destroyed, and have all of its destructors triggered.
this.obj = associateDestroyableChild(this, {});
}
}
```
Returns the associated child for convenience.
@method associateDestroyableChild
@for @ember/destroyable
@param {Object|Function} parent the destroyable to entangle the child destroyables lifetime with
@param {Object|Function} child the destroyable to be entangled with the parents lifetime
@returns {Object|Function} the child argument
@static
@public
*/
/**
Receives a destroyable, and returns true if the destroyable has begun destroying. Otherwise returns
false.
```js
let obj = {};
isDestroying(obj); // false
destroy(obj);
isDestroying(obj); // true
// ...sometime later, after scheduled destruction
isDestroyed(obj); // true
isDestroying(obj); // true
```
@method isDestroying
@for @ember/destroyable
@param {Object|Function} destroyable the object to check
@returns {Boolean}
@static
@public
*/
/**
Receives a destroyable, and returns true if the destroyable has finished destroying. Otherwise
returns false.
```js
let obj = {};
isDestroyed(obj); // false
destroy(obj);
// ...sometime later, after scheduled destruction
isDestroyed(obj); // true
```
@method isDestroyed
@for @ember/destroyable
@param {Object|Function} destroyable the object to check
@returns {Boolean}
@static
@public
*/
/**
Initiates the destruction of a destroyable object. It runs all associated destructors, and then
destroys all children recursively.
```js
let obj = {};
registerDestructor(obj, () => console.log('destroyed!'));
destroy(obj); // this will schedule the destructor to be called
// ...some time later, during scheduled destruction
// destroyed!
```
Destruction via `destroy()` follows these steps:
1, Mark the destroyable such that `isDestroying(destroyable)` returns `true`
2, Call `destroy()` on each of the destroyable's associated children
3, Schedule calling the destroyable's destructors
4, Schedule setting destroyable such that `isDestroyed(destroyable)` returns `true`
This results in the entire tree of destroyables being first marked as destroying,
then having all of their destructors called, and finally all being marked as isDestroyed.
There won't be any in between states where some items are marked as `isDestroying` while
destroying, while others are not.
@method destroy
@for @ember/destroyable
@param {Object|Function} destroyable the object to destroy
@static
@public
*/
/**
This function asserts that all objects which have associated destructors or associated children
have been destroyed at the time it is called. It is meant to be a low level hook that testing
frameworks can use to hook into and validate that all destroyables have in fact been destroyed.
This function requires that `enableDestroyableTracking` was called previously, and is only
available in non-production builds.
@method assertDestroyablesDestroyed
@for @ember/destroyable
@static
@public
*/
/**
This function instructs the destroyable system to keep track of all destroyables (their
children, destructors, etc). This enables a future usage of `assertDestroyablesDestroyed`
to be used to ensure that all destroyable tasks (registered destructors and associated children)
have completed when `assertDestroyablesDestroyed` is called.
@method enableDestroyableTracking
@for @ember/destroyable
@static
@public
*/
/**
Receives a destroyable object and a destructor function, and associates the
function with it. When the destroyable is destroyed with destroy, or when its
parent is destroyed, the destructor function will be called.
```js
import { registerDestructor } from '@ember/destroyable';
class Modal extends Component {
@service resize;
constructor() {
this.resize.register(this, this.layout);
registerDestructor(this, () => this.resize.unregister(this));
}
}
```
Multiple destructors can be associated with a given destroyable, and they can be
associated over time, allowing libraries to dynamically add destructors as needed.
`registerDestructor` also returns the associated destructor function, for convenience.
The destructor function is passed a single argument, which is the destroyable itself.
This allows the function to be reused multiple times for many destroyables, rather
than creating a closure function per destroyable.
```js
import { registerDestructor } from '@ember/destroyable';
function unregisterResize(instance) {
instance.resize.unregister(instance);
}
class Modal extends Component {
@service resize;
constructor() {
this.resize.register(this, this.layout);
registerDestructor(this, unregisterResize);
}
}
```
@method registerDestructor
@for @ember/destroyable
@param {Object|Function} destroyable the destroyable to register the destructor function with
@param {Function} destructor the destructor to run when the destroyable object is destroyed
@static
@public
*/
function registerDestructor(destroyable, destructor) {
return (0, _destroyable.registerDestructor)(destroyable, destructor);
}
/**
Receives a destroyable and a destructor function, and de-associates the destructor
from the destroyable.
```js
import { registerDestructor, unregisterDestructor } from '@ember/destroyable';
class Modal extends Component {
@service modals;
constructor() {
this.modals.add(this);
this.modalDestructor = registerDestructor(this, () => this.modals.remove(this));
}
@action pinModal() {
unregisterDestructor(this, this.modalDestructor);
}
}
```
@method unregisterDestructor
@for @ember/destroyable
@param {Object|Function} destroyable the destroyable to unregister the destructor function from
@param {Function} destructor the destructor to remove from the destroyable
@static
@public
*/
function unregisterDestructor(destroyable, destructor) {
return (0, _destroyable.unregisterDestructor)(destroyable, destructor);
}
});
define("@ember/engine/index", ["exports", "@ember/engine/lib/engine-parent", "@ember/-internals/utils", "@ember/controller", "@ember/-internals/runtime", "@ember/-internals/container", "dag-map", "@ember/debug", "@ember/-internals/metal", "@ember/engine/instance", "@ember/-internals/routing", "@ember/-internals/extension-support", "@ember/-internals/views", "@ember/-internals/glimmer"], function (_exports, _engineParent, _utils, _controller, _runtime, _container, _dagMap, _debug, _metal, _instance, _routing, _extensionSupport, _views, _glimmer) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "getEngineParent", {
enumerable: true,
get: function () {
return _engineParent.getEngineParent;
}
});
Object.defineProperty(_exports, "setEngineParent", {
enumerable: true,
get: function () {
return _engineParent.setEngineParent;
}
});
_exports.default = void 0;
function props(obj) {
var properties = [];
for (var key in obj) {
properties.push(key);
}
return properties;
}
/**
@module @ember/engine
*/
/**
The `Engine` class contains core functionality for both applications and
engines.
Each engine manages a registry that's used for dependency injection and
exposed through `RegistryProxy`.
Engines also manage initializers and instance initializers.
Engines can spawn `EngineInstance` instances via `buildInstance()`.
@class Engine
@extends Ember.Namespace
@uses RegistryProxy
@public
*/
var Engine = _runtime.Namespace.extend(_runtime.RegistryProxyMixin, {
init() {
this._super(...arguments);
this.buildRegistry();
},
/**
A private flag indicating whether an engine's initializers have run yet.
@private
@property _initializersRan
*/
_initializersRan: false,
/**
Ensure that initializers are run once, and only once, per engine.
@private
@method ensureInitializers
*/
ensureInitializers() {
if (!this._initializersRan) {
this.runInitializers();
this._initializersRan = true;
}
},
/**
Create an EngineInstance for this engine.
@public
@method buildInstance
@return {EngineInstance} the engine instance
*/
buildInstance(options = {}) {
this.ensureInitializers();
options.base = this;
return _instance.default.create(options);
},
/**
Build and configure the registry for the current engine.
@private
@method buildRegistry
@return {Ember.Registry} the configured registry
*/
buildRegistry() {
var registry = this.__registry__ = this.constructor.buildRegistry(this);
return registry;
},
/**
@private
@method initializer
*/
initializer(options) {
this.constructor.initializer(options);
},
/**
@private
@method instanceInitializer
*/
instanceInitializer(options) {
this.constructor.instanceInitializer(options);
},
/**
@private
@method runInitializers
*/
runInitializers() {
this._runInitializer('initializers', (name, initializer) => {
(true && !(Boolean(initializer)) && (0, _debug.assert)(`No application initializer named '${name}'`, Boolean(initializer)));
initializer.initialize(this);
});
},
/**
@private
@since 1.12.0
@method runInstanceInitializers
*/
runInstanceInitializers(instance) {
this._runInitializer('instanceInitializers', (name, initializer) => {
(true && !(Boolean(initializer)) && (0, _debug.assert)(`No instance initializer named '${name}'`, Boolean(initializer)));
initializer.initialize(instance);
});
},
_runInitializer(bucketName, cb) {
var initializersByName = (0, _metal.get)(this.constructor, bucketName);
var initializers = props(initializersByName);
var graph = new _dagMap.default();
var initializer;
for (var i = 0; i < initializers.length; i++) {
initializer = initializersByName[initializers[i]];
graph.add(initializer.name, initializer, initializer.before, initializer.after);
}
graph.topsort(cb);
}
});
Engine.reopenClass({
initializers: Object.create(null),
instanceInitializers: Object.create(null),
/**
The goal of initializers should be to register dependencies and injections.
This phase runs once. Because these initializers may load code, they are
allowed to defer application readiness and advance it. If you need to access
the container or store you should use an InstanceInitializer that will be run
after all initializers and therefore after all code is loaded and the app is
ready.
Initializer receives an object which has the following attributes:
`name`, `before`, `after`, `initialize`. The only required attribute is
`initialize`, all others are optional.
* `name` allows you to specify under which name the initializer is registered.
This must be a unique name, as trying to register two initializers with the
same name will result in an error.
```app/initializer/named-initializer.js
import { debug } from '@ember/debug';
export function initialize() {
debug('Running namedInitializer!');
}
export default {
name: 'named-initializer',
initialize
};
```
* `before` and `after` are used to ensure that this initializer is ran prior
or after the one identified by the value. This value can be a single string
or an array of strings, referencing the `name` of other initializers.
An example of ordering initializers, we create an initializer named `first`:
```app/initializer/first.js
import { debug } from '@ember/debug';
export function initialize() {
debug('First initializer!');
}
export default {
name: 'first',
initialize
};
```
```bash
// DEBUG: First initializer!
```
We add another initializer named `second`, specifying that it should run
after the initializer named `first`:
```app/initializer/second.js
import { debug } from '@ember/debug';
export function initialize() {
debug('Second initializer!');
}
export default {
name: 'second',
after: 'first',
initialize
};
```
```
// DEBUG: First initializer!
// DEBUG: Second initializer!
```
Afterwards we add a further initializer named `pre`, this time specifying
that it should run before the initializer named `first`:
```app/initializer/pre.js
import { debug } from '@ember/debug';
export function initialize() {
debug('Pre initializer!');
}
export default {
name: 'pre',
before: 'first',
initialize
};
```
```bash
// DEBUG: Pre initializer!
// DEBUG: First initializer!
// DEBUG: Second initializer!
```
Finally we add an initializer named `post`, specifying it should run after
both the `first` and the `second` initializers:
```app/initializer/post.js
import { debug } from '@ember/debug';
export function initialize() {
debug('Post initializer!');
}
export default {
name: 'post',
after: ['first', 'second'],
initialize
};
```
```bash
// DEBUG: Pre initializer!
// DEBUG: First initializer!
// DEBUG: Second initializer!
// DEBUG: Post initializer!
```
* `initialize` is a callback function that receives one argument,
`application`, on which you can operate.
Example of using `application` to register an adapter:
```app/initializer/api-adapter.js
import ApiAdapter from '../utils/api-adapter';
export function initialize(application) {
application.register('api-adapter:main', ApiAdapter);
}
export default {
name: 'post',
after: ['first', 'second'],
initialize
};
```
@method initializer
@param initializer {Object}
@public
*/
initializer: buildInitializerMethod('initializers', 'initializer'),
/**
Instance initializers run after all initializers have run. Because
instance initializers run after the app is fully set up. We have access
to the store, container, and other items. However, these initializers run
after code has loaded and are not allowed to defer readiness.
Instance initializer receives an object which has the following attributes:
`name`, `before`, `after`, `initialize`. The only required attribute is
`initialize`, all others are optional.
* `name` allows you to specify under which name the instanceInitializer is
registered. This must be a unique name, as trying to register two
instanceInitializer with the same name will result in an error.
```app/initializer/named-instance-initializer.js
import { debug } from '@ember/debug';
export function initialize() {
debug('Running named-instance-initializer!');
}
export default {
name: 'named-instance-initializer',
initialize
};
```
* `before` and `after` are used to ensure that this initializer is ran prior
or after the one identified by the value. This value can be a single string
or an array of strings, referencing the `name` of other initializers.
* See Application.initializer for discussion on the usage of before
and after.
Example instanceInitializer to preload data into the store.
```app/initializer/preload-data.js
export function initialize(application) {
var userConfig, userConfigEncoded, store;
// We have a HTML escaped JSON representation of the user's basic
// configuration generated server side and stored in the DOM of the main
// index.html file. This allows the app to have access to a set of data
// without making any additional remote calls. Good for basic data that is
// needed for immediate rendering of the page. Keep in mind, this data,
// like all local models and data can be manipulated by the user, so it
// should not be relied upon for security or authorization.
// Grab the encoded data from the meta tag
userConfigEncoded = document.querySelector('head meta[name=app-user-config]').attr('content');
// Unescape the text, then parse the resulting JSON into a real object
userConfig = JSON.parse(unescape(userConfigEncoded));
// Lookup the store
store = application.lookup('service:store');
// Push the encoded JSON into the store
store.pushPayload(userConfig);
}
export default {
name: 'named-instance-initializer',
initialize
};
```
@method instanceInitializer
@param instanceInitializer
@public
*/
instanceInitializer: buildInitializerMethod('instanceInitializers', 'instance initializer'),
/**
This creates a registry with the default Ember naming conventions.
It also configures the registry:
* registered views are created every time they are looked up (they are
not singletons)
* registered templates are not factories; the registered value is
returned directly.
* the router receives the application as its `namespace` property
* all controllers receive the router as their `target` and `controllers`
properties
* all controllers receive the application as their `namespace` property
* the application view receives the application controller as its
`controller` property
* the application view receives the application template as its
`defaultTemplate` property
@method buildRegistry
@static
@param {Application} namespace the application for which to
build the registry
@return {Ember.Registry} the built registry
@private
*/
buildRegistry(namespace) {
var registry = new _container.Registry({
resolver: resolverFor(namespace)
});
registry.set = _metal.set;
registry.register('application:main', namespace, {
instantiate: false
});
commonSetupRegistry(registry);
(0, _glimmer.setupEngineRegistry)(registry);
return registry;
},
/**
Set this to provide an alternate class to `DefaultResolver`
@property resolver
@public
*/
Resolver: null
});
/**
This function defines the default lookup rules for container lookups:
* templates are looked up on `Ember.TEMPLATES`
* other names are looked up on the application after classifying the name.
For example, `controller:post` looks up `App.PostController` by default.
* if the default lookup fails, look for registered classes on the container
This allows the application to register default injections in the container
that could be overridden by the normal naming convention.
@private
@method resolverFor
@param {Ember.Namespace} namespace the namespace to look for classes
@return {*} the resolved value for a given lookup
*/
function resolverFor(namespace) {
var ResolverClass = (0, _metal.get)(namespace, 'Resolver');
var props = {
namespace
};
return ResolverClass.create(props);
}
function buildInitializerMethod(bucketName, humanName) {
return function (initializer) {
// If this is the first initializer being added to a subclass, we are going to reopen the class
// to make sure we have a new `initializers` object, which extends from the parent class' using
// prototypal inheritance. Without this, attempting to add initializers to the subclass would
// pollute the parent class as well as other subclasses.
if (this.superclass[bucketName] !== undefined && this.superclass[bucketName] === this[bucketName]) {
var attrs = {};
attrs[bucketName] = Object.create(this[bucketName]);
this.reopenClass(attrs);
}
(true && !(!this[bucketName][initializer.name]) && (0, _debug.assert)(`The ${humanName} '${initializer.name}' has already been registered`, !this[bucketName][initializer.name]));
(true && !((0, _utils.canInvoke)(initializer, 'initialize')) && (0, _debug.assert)(`An ${humanName} cannot be registered without an initialize function`, (0, _utils.canInvoke)(initializer, 'initialize')));
(true && !(initializer.name !== undefined) && (0, _debug.assert)(`An ${humanName} cannot be registered without a name property`, initializer.name !== undefined));
this[bucketName][initializer.name] = initializer;
};
}
function commonSetupRegistry(registry) {
registry.optionsForType('component', {
singleton: false
});
registry.optionsForType('view', {
singleton: false
});
registry.register('controller:basic', _controller.default, {
instantiate: false
}); // Register the routing service...
registry.register('service:-routing', _routing.RoutingService); // DEBUGGING
registry.register('resolver-for-debugging:main', registry.resolver, {
instantiate: false
});
registry.register('container-debug-adapter:main', _extensionSupport.ContainerDebugAdapter);
registry.register('component-lookup:main', _views.ComponentLookup);
}
var _default = Engine;
_exports.default = _default;
});
define("@ember/engine/instance", ["exports", "@ember/-internals/runtime", "@ember/debug", "@ember/error", "@ember/-internals/container", "@ember/-internals/utils", "@ember/engine/lib/engine-parent"], function (_exports, _runtime, _debug, _error, _container, _utils, _engineParent) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module @ember/engine
*/
/**
The `EngineInstance` encapsulates all of the stateful aspects of a
running `Engine`.
@public
@class EngineInstance
@extends EmberObject
@uses RegistryProxyMixin
@uses ContainerProxyMixin
*/
var EngineInstance = _runtime.Object.extend(_runtime.RegistryProxyMixin, _runtime.ContainerProxyMixin, {
/**
The base `Engine` for which this is an instance.
@property {Engine} engine
@private
*/
base: null,
init() {
this._super(...arguments); // Ensure the guid gets setup for this instance
(0, _utils.guidFor)(this);
var base = this.base;
if (!base) {
base = this.application;
this.base = base;
} // Create a per-instance registry that will use the application's registry
// as a fallback for resolving registrations.
var registry = this.__registry__ = new _container.Registry({
fallback: base.__registry__
}); // Create a per-instance container from the instance's registry
this.__container__ = registry.container({
owner: this
});
this._booted = false;
},
/**
Initialize the `EngineInstance` and return a promise that resolves
with the instance itself when the boot process is complete.
The primary task here is to run any registered instance initializers.
See the documentation on `BootOptions` for the options it takes.
@public
@method boot
@param options {Object}
@return {Promise<EngineInstance,Error>}
*/
boot(options) {
if (this._bootPromise) {
return this._bootPromise;
}
this._bootPromise = new _runtime.RSVP.Promise(resolve => resolve(this._bootSync(options)));
return this._bootPromise;
},
/**
Unfortunately, a lot of existing code assumes booting an instance is
synchronous specifically, a lot of tests assume the last call to
`app.advanceReadiness()` or `app.reset()` will result in a new instance
being fully-booted when the current runloop completes.
We would like new code (like the `visit` API) to stop making this
assumption, so we created the asynchronous version above that returns a
promise. But until we have migrated all the code, we would have to expose
this method for use *internally* in places where we need to boot an instance
synchronously.
@private
*/
_bootSync(options) {
if (this._booted) {
return this;
}
(true && !((0, _engineParent.getEngineParent)(this)) && (0, _debug.assert)("An engine instance's parent must be set via `setEngineParent(engine, parent)` prior to calling `engine.boot()`.", (0, _engineParent.getEngineParent)(this)));
this.cloneParentDependencies();
this.setupRegistry(options);
this.base.runInstanceInitializers(this);
this._booted = true;
return this;
},
setupRegistry(options = this.__container__.lookup('-environment:main')) {
this.constructor.setupRegistry(this.__registry__, options);
},
/**
Unregister a factory.
Overrides `RegistryProxy#unregister` in order to clear any cached instances
of the unregistered factory.
@public
@method unregister
@param {String} fullName
*/
unregister(fullName) {
this.__container__.reset(fullName);
this._super(...arguments);
},
/**
Build a new `EngineInstance` that's a child of this instance.
Engines must be registered by name with their parent engine
(or application).
@private
@method buildChildEngineInstance
@param name {String} the registered name of the engine.
@param options {Object} options provided to the engine instance.
@return {EngineInstance,Error}
*/
buildChildEngineInstance(name, options = {}) {
var Engine = this.lookup(`engine:${name}`);
if (!Engine) {
throw new _error.default(`You attempted to mount the engine '${name}', but it is not registered with its parent.`);
}
var engineInstance = Engine.buildInstance(options);
(0, _engineParent.setEngineParent)(engineInstance, this);
return engineInstance;
},
/**
Clone dependencies shared between an engine instance and its parent.
@private
@method cloneParentDependencies
*/
cloneParentDependencies() {
var parent = (0, _engineParent.getEngineParent)(this);
var registrations = ['route:basic', 'service:-routing'];
registrations.forEach(key => this.register(key, parent.resolveRegistration(key)));
var env = parent.lookup('-environment:main');
this.register('-environment:main', env, {
instantiate: false
});
var singletons = ['router:main', (0, _container.privatize)`-bucket-cache:main`, '-view-registry:main', `renderer:-dom`, 'service:-document'];
if (env.isInteractive) {
singletons.push('event_dispatcher:main');
}
singletons.forEach(key => this.register(key, parent.lookup(key), {
instantiate: false
}));
}
});
EngineInstance.reopenClass({
/**
@private
@method setupRegistry
@param {Registry} registry
@param {BootOptions} options
*/
setupRegistry(registry, options) {
// when no options/environment is present, do nothing
if (!options) {
return;
}
}
});
var _default = EngineInstance;
_exports.default = _default;
});
define("@ember/engine/lib/engine-parent", ["exports", "@ember/-internals/utils"], function (_exports, _utils) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.getEngineParent = getEngineParent;
_exports.setEngineParent = setEngineParent;
/**
@module @ember/engine
*/
var ENGINE_PARENT = (0, _utils.symbol)('ENGINE_PARENT');
/**
`getEngineParent` retrieves an engine instance's parent instance.
@method getEngineParent
@param {EngineInstance} engine An engine instance.
@return {EngineInstance} The parent engine instance.
@for @ember/engine
@static
@private
*/
function getEngineParent(engine) {
return engine[ENGINE_PARENT];
}
/**
`setEngineParent` sets an engine instance's parent instance.
@method setEngineParent
@param {EngineInstance} engine An engine instance.
@param {EngineInstance} parent The parent engine instance.
@private
*/
function setEngineParent(engine, parent) {
engine[ENGINE_PARENT] = parent;
}
});
define("@ember/enumerable/index", ["exports", "@ember/-internals/runtime"], function (_exports, _runtime) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _runtime.Enumerable;
}
});
});
define("@ember/error/index", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module @ember/error
*/
/**
The JavaScript Error object used by Ember.assert.
@class Error
@namespace Ember
@extends Error
@constructor
@public
*/
var _default = Error;
_exports.default = _default;
});
define("@ember/helper/index", ["exports", "@glimmer/manager", "@glimmer/runtime"], function (_exports, _manager, _runtime) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "setHelperManager", {
enumerable: true,
get: function () {
return _manager.setHelperManager;
}
});
Object.defineProperty(_exports, "capabilities", {
enumerable: true,
get: function () {
return _manager.helperCapabilities;
}
});
Object.defineProperty(_exports, "invokeHelper", {
enumerable: true,
get: function () {
return _runtime.invokeHelper;
}
});
Object.defineProperty(_exports, "hash", {
enumerable: true,
get: function () {
return _runtime.hash;
}
});
Object.defineProperty(_exports, "array", {
enumerable: true,
get: function () {
return _runtime.array;
}
});
Object.defineProperty(_exports, "concat", {
enumerable: true,
get: function () {
return _runtime.concat;
}
});
Object.defineProperty(_exports, "get", {
enumerable: true,
get: function () {
return _runtime.get;
}
});
Object.defineProperty(_exports, "fn", {
enumerable: true,
get: function () {
return _runtime.fn;
}
});
});
define("@ember/instrumentation/index", ["exports", "@ember/-internals/environment"], function (_exports, _environment) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.instrument = instrument;
_exports._instrumentStart = _instrumentStart;
_exports.subscribe = subscribe;
_exports.unsubscribe = unsubscribe;
_exports.reset = reset;
_exports.flaggedInstrument = _exports.subscribers = void 0;
/* eslint no-console:off */
/* global console */
/**
@module @ember/instrumentation
@private
*/
/**
The purpose of the Ember Instrumentation module is
to provide efficient, general-purpose instrumentation
for Ember.
Subscribe to a listener by using `subscribe`:
```javascript
import { subscribe } from '@ember/instrumentation';
subscribe("render", {
before(name, timestamp, payload) {
},
after(name, timestamp, payload) {
}
});
```
If you return a value from the `before` callback, that same
value will be passed as a fourth parameter to the `after`
callback.
Instrument a block of code by using `instrument`:
```javascript
import { instrument } from '@ember/instrumentation';
instrument("render.handlebars", payload, function() {
// rendering logic
}, binding);
```
Event names passed to `instrument` are namespaced
by periods, from more general to more specific. Subscribers
can listen for events by whatever level of granularity they
are interested in.
In the above example, the event is `render.handlebars`,
and the subscriber listened for all events beginning with
`render`. It would receive callbacks for events named
`render`, `render.handlebars`, `render.container`, or
even `render.handlebars.layout`.
@class Instrumentation
@static
@private
*/
var subscribers = [];
_exports.subscribers = subscribers;
var cache = {};
function populateListeners(name) {
var listeners = [];
var subscriber;
for (var i = 0; i < subscribers.length; i++) {
subscriber = subscribers[i];
if (subscriber.regex.test(name)) {
listeners.push(subscriber.object);
}
}
cache[name] = listeners;
return listeners;
}
var time = (() => {
var perf = 'undefined' !== typeof window ? window.performance || {} : {};
var fn = perf.now || perf.mozNow || perf.webkitNow || perf.msNow || perf.oNow;
return fn ? fn.bind(perf) : Date.now;
})();
function isCallback(value) {
return typeof value === 'function';
}
function instrument(name, p1, p2, p3) {
var _payload;
var callback;
var binding;
if (arguments.length <= 3 && isCallback(p1)) {
callback = p1;
binding = p2;
} else {
_payload = p1;
callback = p2;
binding = p3;
} // fast path
if (subscribers.length === 0) {
return callback.call(binding);
} // avoid allocating the payload in fast path
var payload = _payload || {};
var finalizer = _instrumentStart(name, () => payload);
if (finalizer === NOOP) {
return callback.call(binding);
} else {
return withFinalizer(callback, finalizer, payload, binding);
}
}
var flaggedInstrument;
_exports.flaggedInstrument = flaggedInstrument;
if (false
/* EMBER_IMPROVED_INSTRUMENTATION */
) {
_exports.flaggedInstrument = flaggedInstrument = instrument;
} else {
_exports.flaggedInstrument = flaggedInstrument = function instrument(_name, _payload, callback) {
return callback();
};
}
function withFinalizer(callback, finalizer, payload, binding) {
try {
return callback.call(binding);
} catch (e) {
payload.exception = e;
throw e;
} finally {
finalizer();
}
}
function NOOP() {}
function _instrumentStart(name, payloadFunc, payloadArg) {
if (subscribers.length === 0) {
return NOOP;
}
var listeners = cache[name];
if (!listeners) {
listeners = populateListeners(name);
}
if (listeners.length === 0) {
return NOOP;
}
var payload = payloadFunc(payloadArg);
var STRUCTURED_PROFILE = _environment.ENV.STRUCTURED_PROFILE;
var timeName;
if (STRUCTURED_PROFILE) {
timeName = `${name}: ${payload.object}`;
console.time(timeName);
}
var beforeValues = [];
var timestamp = time();
for (var i = 0; i < listeners.length; i++) {
var listener = listeners[i];
beforeValues.push(listener.before(name, timestamp, payload));
}
return function _instrumentEnd() {
var timestamp = time();
for (var _i = 0; _i < listeners.length; _i++) {
var _listener = listeners[_i];
if (typeof _listener.after === 'function') {
_listener.after(name, timestamp, payload, beforeValues[_i]);
}
}
if (STRUCTURED_PROFILE) {
console.timeEnd(timeName);
}
};
}
/**
Subscribes to a particular event or instrumented block of code.
@method subscribe
@for @ember/instrumentation
@static
@param {String} [pattern] Namespaced event name.
@param {Object} [object] Before and After hooks.
@return {Subscriber}
@private
*/
function subscribe(pattern, object) {
var paths = pattern.split('.');
var path;
var regexes = [];
for (var i = 0; i < paths.length; i++) {
path = paths[i];
if (path === '*') {
regexes.push('[^\\.]*');
} else {
regexes.push(path);
}
}
var regex = regexes.join('\\.');
regex = `${regex}(\\..*)?`;
var subscriber = {
pattern,
regex: new RegExp(`^${regex}$`),
object
};
subscribers.push(subscriber);
cache = {};
return subscriber;
}
/**
Unsubscribes from a particular event or instrumented block of code.
@method unsubscribe
@for @ember/instrumentation
@static
@param {Object} [subscriber]
@private
*/
function unsubscribe(subscriber) {
var index = 0;
for (var i = 0; i < subscribers.length; i++) {
if (subscribers[i] === subscriber) {
index = i;
}
}
subscribers.splice(index, 1);
cache = {};
}
/**
Resets `Instrumentation` by flushing list of subscribers.
@method reset
@for @ember/instrumentation
@static
@private
*/
function reset() {
subscribers.length = 0;
cache = {};
}
});
define("@ember/modifier/index", ["exports", "@glimmer/manager", "@ember/-internals/glimmer", "@glimmer/runtime"], function (_exports, _manager, _glimmer, _runtime) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "setModifierManager", {
enumerable: true,
get: function () {
return _manager.setModifierManager;
}
});
Object.defineProperty(_exports, "capabilities", {
enumerable: true,
get: function () {
return _glimmer.modifierCapabilities;
}
});
Object.defineProperty(_exports, "on", {
enumerable: true,
get: function () {
return _runtime.on;
}
});
});
define("@ember/object/compat", ["exports", "@ember/-internals/metal", "@ember/debug", "@glimmer/validator"], function (_exports, _metal, _debug, _validator) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.dependentKeyCompat = dependentKeyCompat;
var wrapGetterSetter = function (target, key, desc) {
var {
get: originalGet
} = desc;
(true && !((0, _metal.descriptorForProperty)(target, key) === undefined) && (0, _debug.assert)('You attempted to use @dependentKeyCompat on a property that already has been decorated with either @computed or @tracked. @dependentKeyCompat is only necessary for native getters that are not decorated with @computed.', (0, _metal.descriptorForProperty)(target, key) === undefined));
if (originalGet !== undefined) {
desc.get = function () {
var propertyTag = (0, _validator.tagFor)(this, key);
var ret;
var tag = (0, _validator.track)(() => {
ret = originalGet.call(this);
});
(0, _validator.updateTag)(propertyTag, tag);
(0, _validator.consumeTag)(tag);
return ret;
};
}
return desc;
};
function dependentKeyCompat(target, key, desc) {
if (!(0, _metal.isElementDescriptor)([target, key, desc])) {
desc = target;
var decorator = function (target, key, _desc, _meta, isClassicDecorator) {
(true && !(isClassicDecorator) && (0, _debug.assert)('The @dependentKeyCompat decorator may only be passed a method when used in classic classes. You should decorate getters/setters directly in native classes', isClassicDecorator));
(true && !(desc !== null && typeof desc === 'object' && (typeof desc.get === 'function' || typeof desc.set === 'function')) && (0, _debug.assert)('The dependentKeyCompat() decorator must be passed a getter or setter when used in classic classes', desc !== null && typeof desc === 'object' && (typeof desc.get === 'function' || typeof desc.set === 'function')));
return wrapGetterSetter(target, key, desc);
};
(0, _metal.setClassicDecorator)(decorator);
return decorator;
}
(true && !(desc !== null && typeof desc.get === 'function' || typeof desc.set === 'function') && (0, _debug.assert)('The @dependentKeyCompat decorator must be applied to getters/setters when used in native classes', desc !== null && typeof desc.get === 'function' || typeof desc.set === 'function'));
return wrapGetterSetter(target, key, desc);
}
(0, _metal.setClassicDecorator)(dependentKeyCompat);
});
define("@ember/object/computed", ["exports", "@ember/-internals/metal", "@ember/object/lib/computed/computed_macros", "@ember/object/lib/computed/reduce_computed_macros"], function (_exports, _metal, _computed_macros, _reduce_computed_macros) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _metal.ComputedProperty;
}
});
Object.defineProperty(_exports, "expandProperties", {
enumerable: true,
get: function () {
return _metal.expandProperties;
}
});
Object.defineProperty(_exports, "alias", {
enumerable: true,
get: function () {
return _metal.alias;
}
});
Object.defineProperty(_exports, "empty", {
enumerable: true,
get: function () {
return _computed_macros.empty;
}
});
Object.defineProperty(_exports, "notEmpty", {
enumerable: true,
get: function () {
return _computed_macros.notEmpty;
}
});
Object.defineProperty(_exports, "none", {
enumerable: true,
get: function () {
return _computed_macros.none;
}
});
Object.defineProperty(_exports, "not", {
enumerable: true,
get: function () {
return _computed_macros.not;
}
});
Object.defineProperty(_exports, "bool", {
enumerable: true,
get: function () {
return _computed_macros.bool;
}
});
Object.defineProperty(_exports, "match", {
enumerable: true,
get: function () {
return _computed_macros.match;
}
});
Object.defineProperty(_exports, "equal", {
enumerable: true,
get: function () {
return _computed_macros.equal;
}
});
Object.defineProperty(_exports, "gt", {
enumerable: true,
get: function () {
return _computed_macros.gt;
}
});
Object.defineProperty(_exports, "gte", {
enumerable: true,
get: function () {
return _computed_macros.gte;
}
});
Object.defineProperty(_exports, "lt", {
enumerable: true,
get: function () {
return _computed_macros.lt;
}
});
Object.defineProperty(_exports, "lte", {
enumerable: true,
get: function () {
return _computed_macros.lte;
}
});
Object.defineProperty(_exports, "oneWay", {
enumerable: true,
get: function () {
return _computed_macros.oneWay;
}
});
Object.defineProperty(_exports, "reads", {
enumerable: true,
get: function () {
return _computed_macros.oneWay;
}
});
Object.defineProperty(_exports, "readOnly", {
enumerable: true,
get: function () {
return _computed_macros.readOnly;
}
});
Object.defineProperty(_exports, "deprecatingAlias", {
enumerable: true,
get: function () {
return _computed_macros.deprecatingAlias;
}
});
Object.defineProperty(_exports, "and", {
enumerable: true,
get: function () {
return _computed_macros.and;
}
});
Object.defineProperty(_exports, "or", {
enumerable: true,
get: function () {
return _computed_macros.or;
}
});
Object.defineProperty(_exports, "sum", {
enumerable: true,
get: function () {
return _reduce_computed_macros.sum;
}
});
Object.defineProperty(_exports, "min", {
enumerable: true,
get: function () {
return _reduce_computed_macros.min;
}
});
Object.defineProperty(_exports, "max", {
enumerable: true,
get: function () {
return _reduce_computed_macros.max;
}
});
Object.defineProperty(_exports, "map", {
enumerable: true,
get: function () {
return _reduce_computed_macros.map;
}
});
Object.defineProperty(_exports, "sort", {
enumerable: true,
get: function () {
return _reduce_computed_macros.sort;
}
});
Object.defineProperty(_exports, "setDiff", {
enumerable: true,
get: function () {
return _reduce_computed_macros.setDiff;
}
});
Object.defineProperty(_exports, "mapBy", {
enumerable: true,
get: function () {
return _reduce_computed_macros.mapBy;
}
});
Object.defineProperty(_exports, "filter", {
enumerable: true,
get: function () {
return _reduce_computed_macros.filter;
}
});
Object.defineProperty(_exports, "filterBy", {
enumerable: true,
get: function () {
return _reduce_computed_macros.filterBy;
}
});
Object.defineProperty(_exports, "uniq", {
enumerable: true,
get: function () {
return _reduce_computed_macros.uniq;
}
});
Object.defineProperty(_exports, "uniqBy", {
enumerable: true,
get: function () {
return _reduce_computed_macros.uniqBy;
}
});
Object.defineProperty(_exports, "union", {
enumerable: true,
get: function () {
return _reduce_computed_macros.union;
}
});
Object.defineProperty(_exports, "intersect", {
enumerable: true,
get: function () {
return _reduce_computed_macros.intersect;
}
});
Object.defineProperty(_exports, "collect", {
enumerable: true,
get: function () {
return _reduce_computed_macros.collect;
}
});
});
define("@ember/object/core", ["exports", "@ember/-internals/runtime"], function (_exports, _runtime) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _runtime.CoreObject;
}
});
});
define("@ember/object/evented", ["exports", "@ember/-internals/runtime", "@ember/-internals/metal"], function (_exports, _runtime, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _runtime.Evented;
}
});
Object.defineProperty(_exports, "on", {
enumerable: true,
get: function () {
return _metal.on;
}
});
});
define("@ember/object/events", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "addListener", {
enumerable: true,
get: function () {
return _metal.addListener;
}
});
Object.defineProperty(_exports, "removeListener", {
enumerable: true,
get: function () {
return _metal.removeListener;
}
});
Object.defineProperty(_exports, "sendEvent", {
enumerable: true,
get: function () {
return _metal.sendEvent;
}
});
});
define("@ember/object/index", ["exports", "@ember/debug", "@ember/-internals/metal", "@ember/-internals/runtime"], function (_exports, _debug, _metal, _runtime) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.action = action;
Object.defineProperty(_exports, "notifyPropertyChange", {
enumerable: true,
get: function () {
return _metal.notifyPropertyChange;
}
});
Object.defineProperty(_exports, "defineProperty", {
enumerable: true,
get: function () {
return _metal.defineProperty;
}
});
Object.defineProperty(_exports, "get", {
enumerable: true,
get: function () {
return _metal.get;
}
});
Object.defineProperty(_exports, "set", {
enumerable: true,
get: function () {
return _metal.set;
}
});
Object.defineProperty(_exports, "getProperties", {
enumerable: true,
get: function () {
return _metal.getProperties;
}
});
Object.defineProperty(_exports, "setProperties", {
enumerable: true,
get: function () {
return _metal.setProperties;
}
});
Object.defineProperty(_exports, "observer", {
enumerable: true,
get: function () {
return _metal.observer;
}
});
Object.defineProperty(_exports, "computed", {
enumerable: true,
get: function () {
return _metal.computed;
}
});
Object.defineProperty(_exports, "trySet", {
enumerable: true,
get: function () {
return _metal.trySet;
}
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _runtime.Object;
}
});
/**
Decorator that turns the target function into an Action which can be accessed
directly by reference.
```js
import Component from '@ember/component';
import { action, set } from '@ember/object';
export default class Tooltip extends Component {
@action
toggleShowing() {
set(this, 'isShowing', !this.isShowing);
}
}
```
```hbs
<!-- template.hbs -->
<button {{action this.toggleShowing}}>Show tooltip</button>
{{#if isShowing}}
<div class="tooltip">
I'm a tooltip!
</div>
{{/if}}
```
Decorated actions also interop with the string style template actions:
```hbs
<!-- template.hbs -->
<button {{action "toggleShowing"}}>Show tooltip</button>
{{#if isShowing}}
<div class="tooltip">
I'm a tooltip!
</div>
{{/if}}
```
It also binds the function directly to the instance, so it can be used in any
context and will correctly refer to the class it came from:
```hbs
<!-- template.hbs -->
<button
{{did-insert this.toggleShowing}}
{{on "click" this.toggleShowing}}
>
Show tooltip
</button>
{{#if isShowing}}
<div class="tooltip">
I'm a tooltip!
</div>
{{/if}}
```
This can also be used in JavaScript code directly:
```js
import Component from '@ember/component';
import { action, set } from '@ember/object';
export default class Tooltip extends Component {
constructor() {
super(...arguments);
// this.toggleShowing is still bound correctly when added to
// the event listener
document.addEventListener('click', this.toggleShowing);
}
@action
toggleShowing() {
set(this, 'isShowing', !this.isShowing);
}
}
```
This is considered best practice, since it means that methods will be bound
correctly no matter where they are used. By contrast, the `{{action}}` helper
and modifier can also be used to bind context, but it will be required for
every usage of the method:
```hbs
<!-- template.hbs -->
<button
{{did-insert (action this.toggleShowing)}}
{{on "click" (action this.toggleShowing)}}
>
Show tooltip
</button>
{{#if isShowing}}
<div class="tooltip">
I'm a tooltip!
</div>
{{/if}}
```
They also do not have equivalents in JavaScript directly, so they cannot be
used for other situations where binding would be useful.
@public
@method action
@for @ember/object
@static
@param {Function|undefined} callback The function to turn into an action,
when used in classic classes
@return {PropertyDecorator} property decorator instance
*/
var BINDINGS_MAP = new WeakMap();
function setupAction(target, key, actionFn) {
if (target.constructor !== undefined && typeof target.constructor.proto === 'function') {
target.constructor.proto();
}
if (!Object.prototype.hasOwnProperty.call(target, 'actions')) {
var parentActions = target.actions; // we need to assign because of the way mixins copy actions down when inheriting
target.actions = parentActions ? Object.assign({}, parentActions) : {};
}
target.actions[key] = actionFn;
return {
get() {
var bindings = BINDINGS_MAP.get(this);
if (bindings === undefined) {
bindings = new Map();
BINDINGS_MAP.set(this, bindings);
}
var fn = bindings.get(actionFn);
if (fn === undefined) {
fn = actionFn.bind(this);
bindings.set(actionFn, fn);
}
return fn;
}
};
}
function action(target, key, desc) {
var actionFn;
if (!(0, _metal.isElementDescriptor)([target, key, desc])) {
actionFn = target;
var decorator = function (target, key, desc, meta, isClassicDecorator) {
(true && !(isClassicDecorator) && (0, _debug.assert)('The @action decorator may only be passed a method when used in classic classes. You should decorate methods directly in native classes', isClassicDecorator));
(true && !(typeof actionFn === 'function') && (0, _debug.assert)('The action() decorator must be passed a method when used in classic classes', typeof actionFn === 'function'));
return setupAction(target, key, actionFn);
};
(0, _metal.setClassicDecorator)(decorator);
return decorator;
}
actionFn = desc.value;
(true && !(typeof actionFn === 'function') && (0, _debug.assert)('The @action decorator must be applied to methods when used in native classes', typeof actionFn === 'function'));
return setupAction(target, key, actionFn);
}
(0, _metal.setClassicDecorator)(action);
});
define("@ember/object/internals", ["exports", "@ember/-internals/metal", "@ember/-internals/utils"], function (_exports, _metal, _utils) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "cacheFor", {
enumerable: true,
get: function () {
return _metal.getCachedValueFor;
}
});
Object.defineProperty(_exports, "guidFor", {
enumerable: true,
get: function () {
return _utils.guidFor;
}
});
});
define("@ember/object/lib/computed/computed_macros", ["exports", "@ember/-internals/metal", "@ember/debug"], function (_exports, _metal, _debug) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.empty = empty;
_exports.notEmpty = notEmpty;
_exports.none = none;
_exports.not = not;
_exports.bool = bool;
_exports.match = match;
_exports.equal = equal;
_exports.gt = gt;
_exports.gte = gte;
_exports.lt = lt;
_exports.lte = lte;
_exports.oneWay = oneWay;
_exports.readOnly = readOnly;
_exports.deprecatingAlias = deprecatingAlias;
_exports.or = _exports.and = void 0;
/**
@module @ember/object
*/
function expandPropertiesToArray(predicateName, properties) {
var expandedProperties = [];
function extractProperty(entry) {
expandedProperties.push(entry);
}
for (var i = 0; i < properties.length; i++) {
var property = properties[i];
(true && !(property.indexOf(' ') < 0) && (0, _debug.assert)(`Dependent keys passed to \`${predicateName}\` computed macro can't have spaces.`, property.indexOf(' ') < 0));
(0, _metal.expandProperties)(property, extractProperty);
}
return expandedProperties;
}
function generateComputedWithPredicate(name, predicate) {
return (...properties) => {
(true && !(!(0, _metal.isElementDescriptor)(properties)) && (0, _debug.assert)(`You attempted to use @${name} as a decorator directly, but it requires at least one dependent key parameter`, !(0, _metal.isElementDescriptor)(properties)));
var dependentKeys = expandPropertiesToArray(name, properties);
var computedFunc = (0, _metal.computed)(...dependentKeys, function () {
var lastIdx = dependentKeys.length - 1;
for (var i = 0; i < lastIdx; i++) {
var value = (0, _metal.get)(this, dependentKeys[i]);
if (!predicate(value)) {
return value;
}
}
return (0, _metal.get)(this, dependentKeys[lastIdx]);
});
return computedFunc;
};
}
/**
A computed property macro that returns true if the value of the dependent
property is null, an empty string, empty array, or empty function.
Example:
```javascript
import { set } from '@ember/object';
import { empty } from '@ember/object/computed';
class ToDoList {
constructor(todos) {
set(this, 'todos', todos);
}
@empty('todos') isDone;
}
let todoList = new ToDoList(
['Unit Test', 'Documentation', 'Release']
);
todoList.isDone; // false
set(todoList, 'todos', []);
todoList.isDone; // true
```
@since 1.6.0
@method empty
@static
@for @ember/object/computed
@param {String} dependentKey
@return {ComputedProperty} computed property which returns true if the value
of the dependent property is null, an empty string, empty array, or empty
function and false if the underlying value is not empty.
@public
*/
function empty(dependentKey) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @empty as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return (0, _metal.computed)(`${dependentKey}.length`, function () {
return (0, _metal.isEmpty)((0, _metal.get)(this, dependentKey));
});
}
/**
A computed property that returns true if the value of the dependent property
is NOT null, an empty string, empty array, or empty function.
Example:
```javascript
import { set } from '@ember/object';
import { notEmpty } from '@ember/object/computed';
class Hamster {
constructor(backpack) {
set(this, 'backpack', backpack);
}
@notEmpty('backpack') hasStuff
}
let hamster = new Hamster(
['Food', 'Sleeping Bag', 'Tent']
);
hamster.hasStuff; // true
set(hamster, 'backpack', []);
hamster.hasStuff; // false
```
@method notEmpty
@static
@for @ember/object/computed
@param {String} dependentKey
@return {ComputedProperty} computed property which returns true if original
value for property is not empty.
@public
*/
function notEmpty(dependentKey) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @notEmpty as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return (0, _metal.computed)(`${dependentKey}.length`, function () {
return !(0, _metal.isEmpty)((0, _metal.get)(this, dependentKey));
});
}
/**
A computed property that returns true if the value of the dependent property
is null or undefined. This avoids errors from JSLint complaining about use of
==, which can be technically confusing.
```javascript
import { set } from '@ember/object';
import { none } from '@ember/object/computed';
class Hamster {
@none('food') isHungry;
}
let hamster = new Hamster();
hamster.isHungry; // true
set(hamster, 'food', 'Banana');
hamster.isHungry; // false
set(hamster, 'food', null);
hamster.isHungry; // true
```
@method none
@static
@for @ember/object/computed
@param {String} dependentKey
@return {ComputedProperty} computed property which returns true if original
value for property is null or undefined.
@public
*/
function none(dependentKey) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @none as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return (0, _metal.computed)(dependentKey, function () {
return (0, _metal.isNone)((0, _metal.get)(this, dependentKey));
});
}
/**
A computed property that returns the inverse boolean value of the original
value for the dependent property.
Example:
```javascript
import { set } from '@ember/object';
import { not } from '@ember/object/computed';
class User {
loggedIn = false;
@not('loggedIn') isAnonymous;
}
let user = new User();
user.isAnonymous; // true
set(user, 'loggedIn', true);
user.isAnonymous; // false
```
@method not
@static
@for @ember/object/computed
@param {String} dependentKey
@return {ComputedProperty} computed property which returns inverse of the
original value for property
@public
*/
function not(dependentKey) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @not as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return (0, _metal.computed)(dependentKey, function () {
return !(0, _metal.get)(this, dependentKey);
});
}
/**
A computed property that converts the provided dependent property into a
boolean value.
Example:
```javascript
import { set } from '@ember/object';
import { bool } from '@ember/object/computed';
class Hamster {
@bool('numBananas') hasBananas
}
let hamster = new Hamster();
hamster.hasBananas; // false
set(hamster, 'numBananas', 0);
hamster.hasBananas; // false
set(hamster, 'numBananas', 1);
hamster.hasBananas; // true
set(hamster, 'numBananas', null);
hamster.hasBananas; // false
```
@method bool
@static
@for @ember/object/computed
@param {String} dependentKey
@return {ComputedProperty} computed property which converts to boolean the
original value for property
@public
*/
function bool(dependentKey) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @bool as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return (0, _metal.computed)(dependentKey, function () {
return Boolean((0, _metal.get)(this, dependentKey));
});
}
/**
A computed property which matches the original value for the dependent
property against a given RegExp, returning `true` if the value matches the
RegExp and `false` if it does not.
Example:
```javascript
import { set } from '@ember/object';
import { match } from '@ember/object/computed';
class User {
@match('email', /^.+@.+\..+$/) hasValidEmail;
}
let user = new User();
user.hasValidEmail; // false
set(user, 'email', '');
user.hasValidEmail; // false
set(user, 'email', 'ember_hamster@example.com');
user.hasValidEmail; // true
```
@method match
@static
@for @ember/object/computed
@param {String} dependentKey
@param {RegExp} regexp
@return {ComputedProperty} computed property which match the original value
for property against a given RegExp
@public
*/
function match(dependentKey, regexp) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @match as a decorator directly, but it requires `dependentKey` and `regexp` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return (0, _metal.computed)(dependentKey, function () {
var value = (0, _metal.get)(this, dependentKey);
return regexp.test(value);
});
}
/**
A computed property that returns true if the provided dependent property is
equal to the given value.
Example:
```javascript
import { set } from '@ember/object';
import { equal } from '@ember/object/computed';
class Hamster {
@equal('percentCarrotsEaten', 100) satisfied;
}
let hamster = new Hamster();
hamster.satisfied; // false
set(hamster, 'percentCarrotsEaten', 100);
hamster.satisfied; // true
set(hamster, 'percentCarrotsEaten', 50);
hamster.satisfied; // false
```
@method equal
@static
@for @ember/object/computed
@param {String} dependentKey
@param {String|Number|Object} value
@return {ComputedProperty} computed property which returns true if the
original value for property is equal to the given value.
@public
*/
function equal(dependentKey, value) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @equal as a decorator directly, but it requires `dependentKey` and `value` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return (0, _metal.computed)(dependentKey, function () {
return (0, _metal.get)(this, dependentKey) === value;
});
}
/**
A computed property that returns true if the provided dependent property is
greater than the provided value.
Example:
```javascript
import { set } from '@ember/object';
import { gt } from '@ember/object/computed';
class Hamster {
@gt('numBananas', 10) hasTooManyBananas;
}
let hamster = new Hamster();
hamster.hasTooManyBananas; // false
set(hamster, 'numBananas', 3);
hamster.hasTooManyBananas; // false
set(hamster, 'numBananas', 11);
hamster.hasTooManyBananas; // true
```
@method gt
@static
@for @ember/object/computed
@param {String} dependentKey
@param {Number} value
@return {ComputedProperty} computed property which returns true if the
original value for property is greater than given value.
@public
*/
function gt(dependentKey, value) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @gt as a decorator directly, but it requires `dependentKey` and `value` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return (0, _metal.computed)(dependentKey, function () {
return (0, _metal.get)(this, dependentKey) > value;
});
}
/**
A computed property that returns true if the provided dependent property is
greater than or equal to the provided value.
Example:
```javascript
import { set } from '@ember/object';
import { gte } from '@ember/object/computed';
class Hamster {
@gte('numBananas', 10) hasTooManyBananas;
}
let hamster = new Hamster();
hamster.hasTooManyBananas; // false
set(hamster, 'numBananas', 3);
hamster.hasTooManyBananas; // false
set(hamster, 'numBananas', 10);
hamster.hasTooManyBananas; // true
```
@method gte
@static
@for @ember/object/computed
@param {String} dependentKey
@param {Number} value
@return {ComputedProperty} computed property which returns true if the
original value for property is greater or equal then given value.
@public
*/
function gte(dependentKey, value) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @gte as a decorator directly, but it requires `dependentKey` and `value` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return (0, _metal.computed)(dependentKey, function () {
return (0, _metal.get)(this, dependentKey) >= value;
});
}
/**
A computed property that returns true if the provided dependent property is
less than the provided value.
Example:
```javascript
import { set } from '@ember/object';
import { lt } from '@ember/object/computed';
class Hamster {
@lt('numBananas', 3) needsMoreBananas;
}
let hamster = new Hamster();
hamster.needsMoreBananas; // true
set(hamster, 'numBananas', 3);
hamster.needsMoreBananas; // false
set(hamster, 'numBananas', 2);
hamster.needsMoreBananas; // true
```
@method lt
@static
@for @ember/object/computed
@param {String} dependentKey
@param {Number} value
@return {ComputedProperty} computed property which returns true if the
original value for property is less then given value.
@public
*/
function lt(dependentKey, value) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @lt as a decorator directly, but it requires `dependentKey` and `value` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return (0, _metal.computed)(dependentKey, function () {
return (0, _metal.get)(this, dependentKey) < value;
});
}
/**
A computed property that returns true if the provided dependent property is
less than or equal to the provided value.
Example:
```javascript
import { set } from '@ember/object';
import { lte } from '@ember/object/computed';
class Hamster {
@lte('numBananas', 3) needsMoreBananas;
}
let hamster = new Hamster();
hamster.needsMoreBananas; // true
set(hamster, 'numBananas', 5);
hamster.needsMoreBananas; // false
set(hamster, 'numBananas', 3);
hamster.needsMoreBananas; // true
```
@method lte
@static
@for @ember/object/computed
@param {String} dependentKey
@param {Number} value
@return {ComputedProperty} computed property which returns true if the
original value for property is less or equal than given value.
@public
*/
function lte(dependentKey, value) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @lte as a decorator directly, but it requires `dependentKey` and `value` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return (0, _metal.computed)(dependentKey, function () {
return (0, _metal.get)(this, dependentKey) <= value;
});
}
/**
A computed property that performs a logical `and` on the original values for
the provided dependent properties.
You may pass in more than two properties and even use property brace
expansion. The computed property will return the first falsy value or last
truthy value just like JavaScript's `&&` operator.
Example:
```javascript
import { set } from '@ember/object';
import { and } from '@ember/object/computed';
class Hamster {
@and('hasTent', 'hasBackpack') readyForCamp;
@and('hasWalkingStick', 'hasBackpack') readyForHike;
}
let tomster = new Hamster();
tomster.readyForCamp; // false
set(tomster, 'hasTent', true);
tomster.readyForCamp; // false
set(tomster, 'hasBackpack', true);
tomster.readyForCamp; // true
set(tomster, 'hasBackpack', 'Yes');
tomster.readyForCamp; // 'Yes'
set(tomster, 'hasWalkingStick', null);
tomster.readyForHike; // null
```
@method and
@static
@for @ember/object/computed
@param {String} dependentKey*
@return {ComputedProperty} computed property which performs a logical `and` on
the values of all the original values for properties.
@public
*/
var and = generateComputedWithPredicate('and', value => value);
/**
A computed property which performs a logical `or` on the original values for
the provided dependent properties.
You may pass in more than two properties and even use property brace
expansion. The computed property will return the first truthy value or last
falsy value just like JavaScript's `||` operator.
Example:
```javascript
import { set } from '@ember/object';
import { or } from '@ember/object/computed';
class Hamster {
@or('hasJacket', 'hasUmbrella') readyForRain;
@or('hasSunscreen', 'hasUmbrella') readyForBeach;
}
let tomster = new Hamster();
tomster.readyForRain; // undefined
set(tomster, 'hasUmbrella', true);
tomster.readyForRain; // true
set(tomster, 'hasJacket', 'Yes');
tomster.readyForRain; // 'Yes'
set(tomster, 'hasSunscreen', 'Check');
tomster.readyForBeach; // 'Check'
```
@method or
@static
@for @ember/object/computed
@param {String} dependentKey*
@return {ComputedProperty} computed property which performs a logical `or` on
the values of all the original values for properties.
@public
*/
_exports.and = and;
var or = generateComputedWithPredicate('or', value => !value);
/**
Creates a new property that is an alias for another property on an object.
Calls to `get` or `set` this property behave as though they were called on the
original property.
Example:
```javascript
import { set } from '@ember/object';
import { alias } from '@ember/object/computed';
class Person {
name = 'Alex Matchneer';
@alias('name') nomen;
}
let alex = new Person();
alex.nomen; // 'Alex Matchneer'
alex.name; // 'Alex Matchneer'
set(alex, 'nomen', '@machty');
alex.name; // '@machty'
```
@method alias
@static
@for @ember/object/computed
@param {String} dependentKey
@return {ComputedProperty} computed property which creates an alias to the
original value for property.
@public
*/
/**
Where the `alias` computed macro aliases `get` and `set`, and allows for
bidirectional data flow, the `oneWay` computed macro only provides an aliased
`get`. The `set` will not mutate the upstream property, rather causes the
current property to become the value set. This causes the downstream property
to permanently diverge from the upstream property.
Example:
```javascript
import { set } from '@ember/object';
import { oneWay }from '@ember/object/computed';
class User {
constructor(firstName, lastName) {
set(this, 'firstName', firstName);
set(this, 'lastName', lastName);
}
@oneWay('firstName') nickName;
}
let teddy = new User('Teddy', 'Zeenny');
teddy.nickName; // 'Teddy'
set(teddy, 'nickName', 'TeddyBear');
teddy.firstName; // 'Teddy'
teddy.nickName; // 'TeddyBear'
```
@method oneWay
@static
@for @ember/object/computed
@param {String} dependentKey
@return {ComputedProperty} computed property which creates a one way computed
property to the original value for property.
@public
*/
_exports.or = or;
function oneWay(dependentKey) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @oneWay as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return (0, _metal.alias)(dependentKey).oneWay();
}
/**
This is a more semantically meaningful alias of the `oneWay` computed macro,
whose name is somewhat ambiguous as to which direction the data flows.
@method reads
@static
@for @ember/object/computed
@param {String} dependentKey
@return {ComputedProperty} computed property which creates a one way computed
property to the original value for property.
@public
*/
/**
Where `oneWay` computed macro provides oneWay bindings, the `readOnly`
computed macro provides a readOnly one way binding. Very often when using
the `oneWay` macro one does not also want changes to propagate back up, as
they will replace the value.
This prevents the reverse flow, and also throws an exception when it occurs.
Example:
```javascript
import { set } from '@ember/object';
import { readOnly } from '@ember/object/computed';
class User {
constructor(firstName, lastName) {
set(this, 'firstName', firstName);
set(this, 'lastName', lastName);
}
@readOnly('firstName') nickName;
});
let teddy = new User('Teddy', 'Zeenny');
teddy.nickName; // 'Teddy'
set(teddy, 'nickName', 'TeddyBear'); // throws Exception
// throw new EmberError('Cannot Set: nickName on: <User:ember27288>' );`
teddy.firstName; // 'Teddy'
```
@method readOnly
@static
@for @ember/object/computed
@param {String} dependentKey
@return {ComputedProperty} computed property which creates a one way computed
property to the original value for property.
@since 1.5.0
@public
*/
function readOnly(dependentKey) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @readOnly as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return (0, _metal.alias)(dependentKey).readOnly();
}
/**
Creates a new property that is an alias for another property on an object.
Calls to `get` or `set` this property behave as though they were called on the
original property, but also print a deprecation warning.
Example:
```javascript
import { set } from '@ember/object';
import { deprecatingAlias } from '@ember/object/computed';
class Hamster {
@deprecatingAlias('cavendishCount', {
id: 'hamster.deprecate-banana',
until: '3.0.0'
})
bananaCount;
}
let hamster = new Hamster();
set(hamster, 'bananaCount', 5); // Prints a deprecation warning.
hamster.cavendishCount; // 5
```
@method deprecatingAlias
@static
@for @ember/object/computed
@param {String} dependentKey
@param {Object} options Options for `deprecate`.
@return {ComputedProperty} computed property which creates an alias with a
deprecation to the original value for property.
@since 1.7.0
@public
*/
function deprecatingAlias(dependentKey, options) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @deprecatingAlias as a decorator directly, but it requires `dependentKey` and `options` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return (0, _metal.computed)(dependentKey, {
get(key) {
(true && !(false) && (0, _debug.deprecate)(`Usage of \`${key}\` is deprecated, use \`${dependentKey}\` instead.`, false, options));
return (0, _metal.get)(this, dependentKey);
},
set(key, value) {
(true && !(false) && (0, _debug.deprecate)(`Usage of \`${key}\` is deprecated, use \`${dependentKey}\` instead.`, false, options));
(0, _metal.set)(this, dependentKey, value);
return value;
}
});
}
});
define("@ember/object/lib/computed/reduce_computed_macros", ["exports", "@ember/debug", "@ember/-internals/metal", "@ember/-internals/runtime"], function (_exports, _debug, _metal, _runtime) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.sum = sum;
_exports.max = max;
_exports.min = min;
_exports.map = map;
_exports.mapBy = mapBy;
_exports.filter = filter;
_exports.filterBy = filterBy;
_exports.uniq = uniq;
_exports.uniqBy = uniqBy;
_exports.intersect = intersect;
_exports.setDiff = setDiff;
_exports.collect = collect;
_exports.sort = sort;
_exports.union = void 0;
/**
@module @ember/object
*/
function reduceMacro(dependentKey, callback, initialValue, name) {
(true && !(!/[[\]{}]/g.test(dependentKey)) && (0, _debug.assert)(`Dependent key passed to \`${name}\` computed macro shouldn't contain brace expanding pattern.`, !/[[\]{}]/g.test(dependentKey)));
return (0, _metal.computed)(`${dependentKey}.[]`, function () {
var arr = (0, _metal.get)(this, dependentKey);
if (arr === null || typeof arr !== 'object') {
return initialValue;
}
return arr.reduce(callback, initialValue, this);
}).readOnly();
}
function arrayMacro(dependentKey, additionalDependentKeys, callback) {
// This is a bit ugly
var propertyName;
if (/@each/.test(dependentKey)) {
propertyName = dependentKey.replace(/\.@each.*$/, '');
} else {
propertyName = dependentKey;
dependentKey += '.[]';
}
return (0, _metal.computed)(dependentKey, ...additionalDependentKeys, function () {
var value = (0, _metal.get)(this, propertyName);
if ((0, _runtime.isArray)(value)) {
return (0, _runtime.A)(callback.call(this, value));
} else {
return (0, _runtime.A)();
}
}).readOnly();
}
function multiArrayMacro(_dependentKeys, callback, name) {
(true && !(_dependentKeys.every(dependentKey => !/[[\]{}]/g.test(dependentKey))) && (0, _debug.assert)(`Dependent keys passed to \`${name}\` computed macro shouldn't contain brace expanding pattern.`, _dependentKeys.every(dependentKey => !/[[\]{}]/g.test(dependentKey))));
var dependentKeys = _dependentKeys.map(key => `${key}.[]`);
return (0, _metal.computed)(...dependentKeys, function () {
return (0, _runtime.A)(callback.call(this, _dependentKeys));
}).readOnly();
}
/**
A computed property that returns the sum of the values in the dependent array.
Example:
```javascript
import { sum } from '@ember/object/computed';
class Invoice {
lineItems = [1.00, 2.50, 9.99];
@sum('lineItems') total;
}
let invoice = new Invoice();
invoice.total; // 13.49
```
@method sum
@for @ember/object/computed
@static
@param {String} dependentKey
@return {ComputedProperty} computes the sum of all values in the
dependentKey's array
@since 1.4.0
@public
*/
function sum(dependentKey) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @sum as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return reduceMacro(dependentKey, (sum, item) => sum + item, 0, 'sum');
}
/**
A computed property that calculates the maximum value in the dependent array.
This will return `-Infinity` when the dependent array is empty.
Example:
```javascript
import { set } from '@ember/object';
import { mapBy, max } from '@ember/object/computed';
class Person {
children = [];
@mapBy('children', 'age') childAges;
@max('childAges') maxChildAge;
}
let lordByron = new Person();
lordByron.maxChildAge; // -Infinity
set(lordByron, 'children', [
{
name: 'Augusta Ada Byron',
age: 7
}
]);
lordByron.maxChildAge; // 7
set(lordByron, 'children', [
...lordByron.children,
{
name: 'Allegra Byron',
age: 5
}, {
name: 'Elizabeth Medora Leigh',
age: 8
}
]);
lordByron.maxChildAge; // 8
```
If the types of the arguments are not numbers, they will be converted to
numbers and the type of the return value will always be `Number`. For example,
the max of a list of Date objects will be the highest timestamp as a `Number`.
This behavior is consistent with `Math.max`.
@method max
@for @ember/object/computed
@static
@param {String} dependentKey
@return {ComputedProperty} computes the largest value in the dependentKey's
array
@public
*/
function max(dependentKey) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @max as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return reduceMacro(dependentKey, (max, item) => Math.max(max, item), -Infinity, 'max');
}
/**
A computed property that calculates the minimum value in the dependent array.
This will return `Infinity` when the dependent array is empty.
Example:
```javascript
import { set } from '@ember/object';
import { mapBy, min } from '@ember/object/computed';
class Person {
children = [];
@mapBy('children', 'age') childAges;
@min('childAges') minChildAge;
}
let lordByron = Person.create({ children: [] });
lordByron.minChildAge; // Infinity
set(lordByron, 'children', [
{
name: 'Augusta Ada Byron',
age: 7
}
]);
lordByron.minChildAge; // 7
set(lordByron, 'children', [
...lordByron.children,
{
name: 'Allegra Byron',
age: 5
}, {
name: 'Elizabeth Medora Leigh',
age: 8
}
]);
lordByron.minChildAge; // 5
```
If the types of the arguments are not numbers, they will be converted to
numbers and the type of the return value will always be `Number`. For example,
the min of a list of Date objects will be the lowest timestamp as a `Number`.
This behavior is consistent with `Math.min`.
@method min
@for @ember/object/computed
@static
@param {String} dependentKey
@return {ComputedProperty} computes the smallest value in the dependentKey's array
@public
*/
function min(dependentKey) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @min as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return reduceMacro(dependentKey, (min, item) => Math.min(min, item), Infinity, 'min');
}
/**
Returns an array mapped via the callback
The callback method you provide should have the following signature:
- `item` is the current item in the iteration.
- `index` is the integer index of the current item in the iteration.
```javascript
function mapCallback(item, index);
```
Example:
```javascript
import { set } from '@ember/object';
import { map } from '@ember/object/computed';
class Hamster {
constructor(chores) {
set(this, 'chores', chores);
}
@map('chores', function(chore, index) {
return `${chore.toUpperCase()}!`;
})
excitingChores;
});
let hamster = new Hamster(['clean', 'write more unit tests']);
hamster.excitingChores; // ['CLEAN!', 'WRITE MORE UNIT TESTS!']
```
You can optionally pass an array of additional dependent keys as the second
parameter to the macro, if your map function relies on any external values:
```javascript
import { set } from '@ember/object';
import { map } from '@ember/object/computed';
class Hamster {
shouldUpperCase = false;
constructor(chores) {
set(this, 'chores', chores);
}
@map('chores', ['shouldUpperCase'], function(chore, index) {
if (this.shouldUpperCase) {
return `${chore.toUpperCase()}!`;
} else {
return `${chore}!`;
}
})
excitingChores;
}
let hamster = new Hamster(['clean', 'write more unit tests']);
hamster.excitingChores; // ['clean!', 'write more unit tests!']
set(hamster, 'shouldUpperCase', true);
hamster.excitingChores; // ['CLEAN!', 'WRITE MORE UNIT TESTS!']
```
@method map
@for @ember/object/computed
@static
@param {String} dependentKey
@param {Array} [additionalDependentKeys] optional array of additional
dependent keys
@param {Function} callback
@return {ComputedProperty} an array mapped via the callback
@public
*/
function map(dependentKey, additionalDependentKeys, callback) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @map as a decorator directly, but it requires atleast `dependentKey` and `callback` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
if (callback === undefined && typeof additionalDependentKeys === 'function') {
callback = additionalDependentKeys;
additionalDependentKeys = [];
}
(true && !(typeof callback === 'function') && (0, _debug.assert)('The final parameter provided to map must be a callback function', typeof callback === 'function'));
(true && !(Array.isArray(additionalDependentKeys)) && (0, _debug.assert)('The second parameter provided to map must either be the callback or an array of additional dependent keys', Array.isArray(additionalDependentKeys)));
return arrayMacro(dependentKey, additionalDependentKeys, function (value) {
return value.map(callback, this);
});
}
/**
Returns an array mapped to the specified key.
Example:
```javascript
import { set } from '@ember/object';
import { mapBy } from '@ember/object/computed';
class Person {
children = [];
@mapBy('children', 'age') childAges;
}
let lordByron = new Person();
lordByron.childAges; // []
set(lordByron, 'children', [
{
name: 'Augusta Ada Byron',
age: 7
}
]);
lordByron.childAges; // [7]
set(lordByron, 'children', [
...lordByron.children,
{
name: 'Allegra Byron',
age: 5
}, {
name: 'Elizabeth Medora Leigh',
age: 8
}
]);
lordByron.childAges; // [7, 5, 8]
```
@method mapBy
@for @ember/object/computed
@static
@param {String} dependentKey
@param {String} propertyKey
@return {ComputedProperty} an array mapped to the specified key
@public
*/
function mapBy(dependentKey, propertyKey) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @mapBy as a decorator directly, but it requires `dependentKey` and `propertyKey` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
(true && !(typeof propertyKey === 'string') && (0, _debug.assert)('`mapBy` computed macro expects a property string for its second argument, ' + 'perhaps you meant to use "map"', typeof propertyKey === 'string'));
(true && !(!/[[\]{}]/g.test(dependentKey)) && (0, _debug.assert)(`Dependent key passed to \`mapBy\` computed macro shouldn't contain brace expanding pattern.`, !/[[\]{}]/g.test(dependentKey)));
return map(`${dependentKey}.@each.${propertyKey}`, item => (0, _metal.get)(item, propertyKey));
}
/**
Filters the array by the callback.
The callback method you provide should have the following signature:
- `item` is the current item in the iteration.
- `index` is the integer index of the current item in the iteration.
- `array` is the dependant array itself.
```javascript
function filterCallback(item, index, array);
```
Example:
```javascript
import { set } from '@ember/object';
import { filter } from '@ember/object/computed';
class Hamster {
constructor(chores) {
set(this, 'chores', chores);
}
@filter('chores', function(chore, index, array) {
return !chore.done;
})
remainingChores;
}
let hamster = Hamster.create([
{ name: 'cook', done: true },
{ name: 'clean', done: true },
{ name: 'write more unit tests', done: false }
]);
hamster.remainingChores; // [{name: 'write more unit tests', done: false}]
```
You can also use `@each.property` in your dependent key, the callback will
still use the underlying array:
```javascript
import { set } from '@ember/object';
import { filter } from '@ember/object/computed';
class Hamster {
constructor(chores) {
set(this, 'chores', chores);
}
@filter('chores.@each.done', function(chore, index, array) {
return !chore.done;
})
remainingChores;
}
let hamster = new Hamster([
{ name: 'cook', done: true },
{ name: 'clean', done: true },
{ name: 'write more unit tests', done: false }
]);
hamster.remainingChores; // [{name: 'write more unit tests', done: false}]
set(hamster.chores[2], 'done', true);
hamster.remainingChores; // []
```
Finally, you can optionally pass an array of additional dependent keys as the
second parameter to the macro, if your filter function relies on any external
values:
```javascript
import { filter } from '@ember/object/computed';
class Hamster {
constructor(chores) {
set(this, 'chores', chores);
}
doneKey = 'finished';
@filter('chores', ['doneKey'], function(chore, index, array) {
return !chore[this.doneKey];
})
remainingChores;
}
let hamster = new Hamster([
{ name: 'cook', finished: true },
{ name: 'clean', finished: true },
{ name: 'write more unit tests', finished: false }
]);
hamster.remainingChores; // [{name: 'write more unit tests', finished: false}]
```
@method filter
@for @ember/object/computed
@static
@param {String} dependentKey
@param {Array} [additionalDependentKeys] optional array of additional dependent keys
@param {Function} callback
@return {ComputedProperty} the filtered array
@public
*/
function filter(dependentKey, additionalDependentKeys, callback) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @filter as a decorator directly, but it requires atleast `dependentKey` and `callback` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
if (callback === undefined && typeof additionalDependentKeys === 'function') {
callback = additionalDependentKeys;
additionalDependentKeys = [];
}
(true && !(typeof callback === 'function') && (0, _debug.assert)('The final parameter provided to filter must be a callback function', typeof callback === 'function'));
(true && !(Array.isArray(additionalDependentKeys)) && (0, _debug.assert)('The second parameter provided to filter must either be the callback or an array of additional dependent keys', Array.isArray(additionalDependentKeys)));
return arrayMacro(dependentKey, additionalDependentKeys, function (value) {
return value.filter(callback, this);
});
}
/**
Filters the array by the property and value.
Example:
```javascript
import { set } from '@ember/object';
import { filterBy } from '@ember/object/computed';
class Hamster {
constructor(chores) {
set(this, 'chores', chores);
}
@filterBy('chores', 'done', false) remainingChores;
}
let hamster = new Hamster([
{ name: 'cook', done: true },
{ name: 'clean', done: true },
{ name: 'write more unit tests', done: false }
]);
hamster.remainingChores; // [{ name: 'write more unit tests', done: false }]
```
@method filterBy
@for @ember/object/computed
@static
@param {String} dependentKey
@param {String} propertyKey
@param {*} value
@return {ComputedProperty} the filtered array
@public
*/
function filterBy(dependentKey, propertyKey, value) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @filterBy as a decorator directly, but it requires atleast `dependentKey` and `propertyKey` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
(true && !(!/[[\]{}]/g.test(dependentKey)) && (0, _debug.assert)(`Dependent key passed to \`filterBy\` computed macro shouldn't contain brace expanding pattern.`, !/[[\]{}]/g.test(dependentKey)));
var callback;
if (arguments.length === 2) {
callback = item => (0, _metal.get)(item, propertyKey);
} else {
callback = item => (0, _metal.get)(item, propertyKey) === value;
}
return filter(`${dependentKey}.@each.${propertyKey}`, callback);
}
/**
A computed property which returns a new array with all the unique elements
from one or more dependent arrays.
Example:
```javascript
import { set } from '@ember/object';
import { uniq } from '@ember/object/computed';
class Hamster {
constructor(fruits) {
set(this, 'fruits', fruits);
}
@uniq('fruits') uniqueFruits;
}
let hamster = new Hamster([
'banana',
'grape',
'kale',
'banana'
]);
hamster.uniqueFruits; // ['banana', 'grape', 'kale']
```
@method uniq
@for @ember/object/computed
@static
@param {String} propertyKey*
@return {ComputedProperty} computes a new array with all the
unique elements from the dependent array
@public
*/
function uniq(...args) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @uniq/@union as a decorator directly, but it requires atleast one dependent key parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return multiArrayMacro(args, function (dependentKeys) {
var uniq = (0, _runtime.A)();
var seen = new Set();
dependentKeys.forEach(dependentKey => {
var value = (0, _metal.get)(this, dependentKey);
if ((0, _runtime.isArray)(value)) {
value.forEach(item => {
if (!seen.has(item)) {
seen.add(item);
uniq.push(item);
}
});
}
});
return uniq;
}, 'uniq');
}
/**
A computed property which returns a new array with all the unique elements
from an array, with uniqueness determined by specific key.
Example:
```javascript
import { set } from '@ember/object';
import { uniqBy } from '@ember/object/computed';
class Hamster {
constructor(fruits) {
set(this, 'fruits', fruits);
}
@uniqBy('fruits', 'id') uniqueFruits;
}
let hamster = new Hamster([
{ id: 1, 'banana' },
{ id: 2, 'grape' },
{ id: 3, 'peach' },
{ id: 1, 'banana' }
]);
hamster.uniqueFruits; // [ { id: 1, 'banana' }, { id: 2, 'grape' }, { id: 3, 'peach' }]
```
@method uniqBy
@for @ember/object/computed
@static
@param {String} dependentKey
@param {String} propertyKey
@return {ComputedProperty} computes a new array with all the
unique elements from the dependent array
@public
*/
function uniqBy(dependentKey, propertyKey) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @uniqBy as a decorator directly, but it requires `dependentKey` and `propertyKey` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
(true && !(!/[[\]{}]/g.test(dependentKey)) && (0, _debug.assert)(`Dependent key passed to \`uniqBy\` computed macro shouldn't contain brace expanding pattern.`, !/[[\]{}]/g.test(dependentKey)));
return (0, _metal.computed)(`${dependentKey}.[]`, function () {
var list = (0, _metal.get)(this, dependentKey);
return (0, _runtime.isArray)(list) ? (0, _runtime.uniqBy)(list, propertyKey) : (0, _runtime.A)();
}).readOnly();
}
/**
A computed property which returns a new array with all the unique elements
from one or more dependent arrays.
Example:
```javascript
import { set } from '@ember/object';
import { union } from '@ember/object/computed';
class Hamster {
constructor(fruits, vegetables) {
set(this, 'fruits', fruits);
set(this, 'vegetables', vegetables);
}
@union('fruits', 'vegetables') uniqueFruits;
});
let hamster = new, Hamster(
[
'banana',
'grape',
'kale',
'banana',
'tomato'
],
[
'tomato',
'carrot',
'lettuce'
]
);
hamster.uniqueFruits; // ['banana', 'grape', 'kale', 'tomato', 'carrot', 'lettuce']
```
@method union
@for @ember/object/computed
@static
@param {String} propertyKey*
@return {ComputedProperty} computes a new array with all the unique elements
from one or more dependent arrays.
@public
*/
var union = uniq;
/**
A computed property which returns a new array with all the elements
two or more dependent arrays have in common.
Example:
```javascript
import { set } from '@ember/object';
import { intersect } from '@ember/object/computed';
class FriendGroups {
constructor(adaFriends, charlesFriends) {
set(this, 'adaFriends', adaFriends);
set(this, 'charlesFriends', charlesFriends);
}
@intersect('adaFriends', 'charlesFriends') friendsInCommon;
}
let groups = new FriendGroups(
['Charles Babbage', 'John Hobhouse', 'William King', 'Mary Somerville'],
['William King', 'Mary Somerville', 'Ada Lovelace', 'George Peacock']
);
groups.friendsInCommon; // ['William King', 'Mary Somerville']
```
@method intersect
@for @ember/object/computed
@static
@param {String} propertyKey*
@return {ComputedProperty} computes a new array with all the duplicated
elements from the dependent arrays
@public
*/
_exports.union = union;
function intersect(...args) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @intersect as a decorator directly, but it requires atleast one dependent key parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return multiArrayMacro(args, function (dependentKeys) {
var arrays = dependentKeys.map(dependentKey => {
var array = (0, _metal.get)(this, dependentKey);
return (0, _runtime.isArray)(array) ? array : [];
});
var results = arrays.pop().filter(candidate => {
for (var i = 0; i < arrays.length; i++) {
var found = false;
var array = arrays[i];
for (var j = 0; j < array.length; j++) {
if (array[j] === candidate) {
found = true;
break;
}
}
if (found === false) {
return false;
}
}
return true;
});
return (0, _runtime.A)(results);
}, 'intersect');
}
/**
A computed property which returns a new array with all the properties from the
first dependent array that are not in the second dependent array.
Example:
```javascript
import { set } from '@ember/object';
import { setDiff } from '@ember/object/computed';
class Hamster {
constructor(likes, fruits) {
set(this, 'likes', likes);
set(this, 'fruits', fruits);
}
@setDiff('likes', 'fruits') wants;
}
let hamster = new Hamster(
[
'banana',
'grape',
'kale'
],
[
'grape',
'kale',
]
);
hamster.wants; // ['banana']
```
@method setDiff
@for @ember/object/computed
@static
@param {String} setAProperty
@param {String} setBProperty
@return {ComputedProperty} computes a new array with all the items from the
first dependent array that are not in the second dependent array
@public
*/
function setDiff(setAProperty, setBProperty) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @setDiff as a decorator directly, but it requires atleast one dependent key parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
(true && !(arguments.length === 2) && (0, _debug.assert)('`setDiff` computed macro requires exactly two dependent arrays.', arguments.length === 2));
(true && !(!/[[\]{}]/g.test(setAProperty) && !/[[\]{}]/g.test(setBProperty)) && (0, _debug.assert)(`Dependent keys passed to \`setDiff\` computed macro shouldn't contain brace expanding pattern.`, !/[[\]{}]/g.test(setAProperty) && !/[[\]{}]/g.test(setBProperty)));
return (0, _metal.computed)(`${setAProperty}.[]`, `${setBProperty}.[]`, function () {
var setA = (0, _metal.get)(this, setAProperty);
var setB = (0, _metal.get)(this, setBProperty);
if (!(0, _runtime.isArray)(setA)) {
return (0, _runtime.A)();
}
if (!(0, _runtime.isArray)(setB)) {
return (0, _runtime.A)(setA);
}
return setA.filter(x => setB.indexOf(x) === -1);
}).readOnly();
}
/**
A computed property that returns the array of values for the provided
dependent properties.
Example:
```javascript
import { set } from '@ember/object';
import { collect } from '@ember/object/computed';
class Hamster {
@collect('hat', 'shirt') clothes;
}
let hamster = new Hamster();
hamster.clothes; // [null, null]
set(hamster, 'hat', 'Camp Hat');
set(hamster, 'shirt', 'Camp Shirt');
hamster.clothes; // ['Camp Hat', 'Camp Shirt']
```
@method collect
@for @ember/object/computed
@static
@param {String} dependentKey*
@return {ComputedProperty} computed property which maps values of all passed
in properties to an array.
@public
*/
function collect(...dependentKeys) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @collect as a decorator directly, but it requires atleast one dependent key parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
return multiArrayMacro(dependentKeys, function () {
var res = dependentKeys.map(key => {
var val = (0, _metal.get)(this, key);
return val === undefined ? null : val;
});
return (0, _runtime.A)(res);
}, 'collect');
}
/**
A computed property which returns a new array with all the properties from the
first dependent array sorted based on a property or sort function. The sort
macro can be used in two different ways:
1. By providing a sort callback function
2. By providing an array of keys to sort the array
In the first form, the callback method you provide should have the following
signature:
```javascript
function sortCallback(itemA, itemB);
```
- `itemA` the first item to compare.
- `itemB` the second item to compare.
This function should return negative number (e.g. `-1`) when `itemA` should
come before `itemB`. It should return positive number (e.g. `1`) when `itemA`
should come after `itemB`. If the `itemA` and `itemB` are equal this function
should return `0`.
Therefore, if this function is comparing some numeric values, simple `itemA -
itemB` or `itemA.get( 'foo' ) - itemB.get( 'foo' )` can be used instead of
series of `if`.
Example:
```javascript
import { set } from '@ember/object';
import { sort } from '@ember/object/computed';
class ToDoList {
constructor(todos) {
set(this, 'todos', todos);
}
// using a custom sort function
@sort('todos', function(a, b){
if (a.priority > b.priority) {
return 1;
} else if (a.priority < b.priority) {
return -1;
}
return 0;
})
priorityTodos;
}
let todoList = new ToDoList([
{ name: 'Unit Test', priority: 2 },
{ name: 'Documentation', priority: 3 },
{ name: 'Release', priority: 1 }
]);
todoList.priorityTodos; // [{ name:'Release', priority:1 }, { name:'Unit Test', priority:2 }, { name:'Documentation', priority:3 }]
```
You can also optionally pass an array of additional dependent keys as the
second parameter, if your sort function is dependent on additional values that
could changes:
```js
import EmberObject, { set } from '@ember/object';
import { sort } from '@ember/object/computed';
class ToDoList {
sortKey = 'priority';
constructor(todos) {
set(this, 'todos', todos);
}
// using a custom sort function
@sort('todos', ['sortKey'], function(a, b){
if (a[this.sortKey] > b[this.sortKey]) {
return 1;
} else if (a[this.sortKey] < b[this.sortKey]) {
return -1;
}
return 0;
})
sortedTodos;
});
let todoList = new ToDoList([
{ name: 'Unit Test', priority: 2 },
{ name: 'Documentation', priority: 3 },
{ name: 'Release', priority: 1 }
]);
todoList.priorityTodos; // [{ name:'Release', priority:1 }, { name:'Unit Test', priority:2 }, { name:'Documentation', priority:3 }]
```
In the second form, you should provide the key of the array of sort values as
the second parameter:
```javascript
import { set } from '@ember/object';
import { sort } from '@ember/object/computed';
class ToDoList {
constructor(todos) {
set(this, 'todos', todos);
}
// using standard ascending sort
todosSorting = ['name'];
@sort('todos', 'todosSorting') sortedTodos;
// using descending sort
todosSortingDesc = ['name:desc'];
@sort('todos', 'todosSortingDesc') sortedTodosDesc;
}
let todoList = new ToDoList([
{ name: 'Unit Test', priority: 2 },
{ name: 'Documentation', priority: 3 },
{ name: 'Release', priority: 1 }
]);
todoList.sortedTodos; // [{ name:'Documentation', priority:3 }, { name:'Release', priority:1 }, { name:'Unit Test', priority:2 }]
todoList.sortedTodosDesc; // [{ name:'Unit Test', priority:2 }, { name:'Release', priority:1 }, { name:'Documentation', priority:3 }]
```
@method sort
@for @ember/object/computed
@static
@param {String} itemsKey
@param {String|Function|Array} sortDefinitionOrDependentKeys The key of the sort definition (an array of sort properties),
the sort function, or an array of additional dependent keys
@param {Function?} sortDefinition the sort function (when used with additional dependent keys)
@return {ComputedProperty} computes a new sorted array based on the sort
property array or callback function
@public
*/
function sort(itemsKey, additionalDependentKeys, sortDefinition) {
(true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @sort as a decorator directly, but it requires atleast an `itemsKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
if (true
/* DEBUG */
) {
var argumentsValid = false;
if (arguments.length === 2) {
argumentsValid = typeof itemsKey === 'string' && (typeof additionalDependentKeys === 'string' || typeof additionalDependentKeys === 'function');
}
if (arguments.length === 3) {
argumentsValid = typeof itemsKey === 'string' && Array.isArray(additionalDependentKeys) && typeof sortDefinition === 'function';
}
(true && !(argumentsValid) && (0, _debug.assert)('The `sort` computed macro can either be used with an array of sort properties or with a sort function. If used with an array of sort properties, it must receive exactly two arguments: the key of the array to sort, and the key of the array of sort properties. If used with a sort function, it may receive up to three arguments: the key of the array to sort, an optional additional array of dependent keys for the computed property, and the sort function.', argumentsValid));
}
if (sortDefinition === undefined && !Array.isArray(additionalDependentKeys)) {
sortDefinition = additionalDependentKeys;
additionalDependentKeys = [];
}
if (typeof sortDefinition === 'function') {
return customSort(itemsKey, additionalDependentKeys, sortDefinition);
} else {
return propertySort(itemsKey, sortDefinition);
}
}
function customSort(itemsKey, additionalDependentKeys, comparator) {
return arrayMacro(itemsKey, additionalDependentKeys, function (value) {
return value.slice().sort((x, y) => comparator.call(this, x, y));
});
} // This one needs to dynamically set up and tear down observers on the itemsKey
// depending on the sortProperties
function propertySort(itemsKey, sortPropertiesKey) {
var cp = (0, _metal.autoComputed)(function (key) {
var sortProperties = (0, _metal.get)(this, sortPropertiesKey);
(true && !((0, _runtime.isArray)(sortProperties) && sortProperties.every(s => typeof s === 'string')) && (0, _debug.assert)(`The sort definition for '${key}' on ${this} must be a function or an array of strings`, (0, _runtime.isArray)(sortProperties) && sortProperties.every(s => typeof s === 'string')));
var itemsKeyIsAtThis = itemsKey === '@this';
var normalizedSortProperties = normalizeSortProperties(sortProperties);
var items = itemsKeyIsAtThis ? this : (0, _metal.get)(this, itemsKey);
if (!(0, _runtime.isArray)(items)) {
return (0, _runtime.A)();
}
if (normalizedSortProperties.length === 0) {
return (0, _runtime.A)(items.slice());
} else {
return sortByNormalizedSortProperties(items, normalizedSortProperties);
}
}).readOnly();
return cp;
}
function normalizeSortProperties(sortProperties) {
return sortProperties.map(p => {
var [prop, direction] = p.split(':');
direction = direction || 'asc';
return [prop, direction];
});
}
function sortByNormalizedSortProperties(items, normalizedSortProperties) {
return (0, _runtime.A)(items.slice().sort((itemA, itemB) => {
for (var i = 0; i < normalizedSortProperties.length; i++) {
var [prop, direction] = normalizedSortProperties[i];
var result = (0, _runtime.compare)((0, _metal.get)(itemA, prop), (0, _metal.get)(itemB, prop));
if (result !== 0) {
return direction === 'desc' ? -1 * result : result;
}
}
return 0;
}));
}
});
define("@ember/object/mixin", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _metal.Mixin;
}
});
});
define("@ember/object/observable", ["exports", "@ember/-internals/runtime"], function (_exports, _runtime) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _runtime.Observable;
}
});
});
define("@ember/object/observers", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "addObserver", {
enumerable: true,
get: function () {
return _metal.addObserver;
}
});
Object.defineProperty(_exports, "removeObserver", {
enumerable: true,
get: function () {
return _metal.removeObserver;
}
});
});
define("@ember/object/promise-proxy-mixin", ["exports", "@ember/-internals/runtime"], function (_exports, _runtime) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _runtime.PromiseProxyMixin;
}
});
});
define("@ember/object/proxy", ["exports", "@ember/-internals/runtime"], function (_exports, _runtime) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _runtime.ObjectProxy;
}
});
});
define("@ember/polyfills/index", ["exports", "@ember/polyfills/lib/assign"], function (_exports, _assign) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "assign", {
enumerable: true,
get: function () {
return _assign.assign;
}
});
_exports.hasPropertyAccessors = void 0;
var hasPropertyAccessors = true;
_exports.hasPropertyAccessors = hasPropertyAccessors;
});
define("@ember/polyfills/lib/assign", ["exports", "@ember/debug"], function (_exports, _debug) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.assign = assign;
/**
Copy properties from a source object to a target object. Source arguments remain unchanged.
```javascript
import { assign } from '@ember/polyfills';
var a = { first: 'Yehuda' };
var b = { last: 'Katz' };
var c = { company: 'Other Company' };
var d = { company: 'Tilde Inc.' };
assign(a, b, c, d); // a === { first: 'Yehuda', last: 'Katz', company: 'Tilde Inc.' };
```
@method assign
@for @ember/polyfills
@param {Object} target The object to assign into
@param {Object} ...args The objects to copy properties from
@return {Object}
@public
@static
*/
function assign(target, ...rest) {
(true && !(false) && (0, _debug.deprecate)('Use of `assign` has been deprecated. Please use `Object.assign` or the spread operator instead.', false, {
id: 'ember-polyfills.deprecate-assign',
until: '5.0.0',
url: 'https://deprecations.emberjs.com/v4.x/#toc_ember-polyfills-deprecate-assign',
for: 'ember-source',
since: {
enabled: '4.0.0'
}
}));
return Object.assign(target, ...rest);
}
});
define("@ember/routing/auto-location", ["exports", "@ember/-internals/routing"], function (_exports, _routing) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _routing.AutoLocation;
}
});
});
define("@ember/routing/hash-location", ["exports", "@ember/-internals/routing"], function (_exports, _routing) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _routing.HashLocation;
}
});
});
define("@ember/routing/history-location", ["exports", "@ember/-internals/routing"], function (_exports, _routing) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _routing.HistoryLocation;
}
});
});
define("@ember/routing/index", ["exports", "@ember/-internals/glimmer"], function (_exports, _glimmer) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "LinkTo", {
enumerable: true,
get: function () {
return _glimmer.LinkTo;
}
});
});
define("@ember/routing/location", ["exports", "@ember/-internals/routing"], function (_exports, _routing) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _routing.Location;
}
});
});
define("@ember/routing/none-location", ["exports", "@ember/-internals/routing"], function (_exports, _routing) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _routing.NoneLocation;
}
});
});
define("@ember/routing/route", ["exports", "@ember/-internals/routing"], function (_exports, _routing) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _routing.Route;
}
});
});
define("@ember/routing/router", ["exports", "@ember/-internals/routing"], function (_exports, _routing) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "default", {
enumerable: true,
get: function () {
return _routing.Router;
}
});
});
define("@ember/runloop/index", ["exports", "@ember/debug", "@ember/-internals/error-handling", "@ember/-internals/metal", "backburner"], function (_exports, _debug, _errorHandling, _metal, _backburner2) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports._getCurrentRunLoop = _getCurrentRunLoop;
_exports.run = run;
_exports.join = join;
_exports.begin = begin;
_exports.end = end;
_exports.schedule = schedule;
_exports._hasScheduledTimers = _hasScheduledTimers;
_exports._cancelTimers = _cancelTimers;
_exports.later = later;
_exports.once = once;
_exports.scheduleOnce = scheduleOnce;
_exports.next = next;
_exports.cancel = cancel;
_exports.debounce = debounce;
_exports.throttle = throttle;
_exports.bind = _exports._backburner = _exports._queues = _exports._rsvpErrorQueue = void 0;
var currentRunLoop = null;
function _getCurrentRunLoop() {
return currentRunLoop;
}
function onBegin(current) {
currentRunLoop = current;
}
function onEnd(current, next) {
currentRunLoop = next;
(0, _metal.flushAsyncObservers)();
}
function flush(queueName, next) {
if (queueName === 'render' || queueName === _rsvpErrorQueue) {
(0, _metal.flushAsyncObservers)();
}
next();
}
var _rsvpErrorQueue = `${Math.random()}${Date.now()}`.replace('.', '');
/**
Array of named queues. This array determines the order in which queues
are flushed at the end of the RunLoop. You can define your own queues by
simply adding the queue name to this array. Normally you should not need
to inspect or modify this property.
@property queues
@type Array
@default ['actions', 'destroy']
@private
*/
_exports._rsvpErrorQueue = _rsvpErrorQueue;
var _queues = ['actions', // used in router transitions to prevent unnecessary loading state entry
// if all context promises resolve on the 'actions' queue first
'routerTransitions', 'render', 'afterRender', 'destroy', // used to re-throw unhandled RSVP rejection errors specifically in this
// position to avoid breaking anything rendered in the other sections
_rsvpErrorQueue];
_exports._queues = _queues;
var _backburner = new _backburner2.default(_queues, {
defaultQueue: 'actions',
onBegin,
onEnd,
onErrorTarget: _errorHandling.onErrorTarget,
onErrorMethod: 'onerror',
flush
});
/**
@module @ember/runloop
*/
// ..........................................................
// run - this is ideally the only public API the dev sees
//
/**
Runs the passed target and method inside of a RunLoop, ensuring any
deferred actions including bindings and views updates are flushed at the
end.
Normally you should not need to invoke this method yourself. However if
you are implementing raw event handlers when interfacing with other
libraries or plugins, you should probably wrap all of your code inside this
call.
```javascript
import { run } from '@ember/runloop';
run(function() {
// code to be executed within a RunLoop
});
```
@method run
@for @ember/runloop
@static
@param {Object} [target] target of method to call
@param {Function|String} method Method to invoke.
May be a function or a string. If you pass a string
then it will be looked up on the passed target.
@param {Object} [args*] Any additional arguments you wish to pass to the method.
@return {Object} return value from invoking the passed function.
@public
*/
_exports._backburner = _backburner;
function run() {
return _backburner.run(...arguments);
}
/**
If no run-loop is present, it creates a new one. If a run loop is
present it will queue itself to run on the existing run-loops action
queue.
Please note: This is not for normal usage, and should be used sparingly.
If invoked when not within a run loop:
```javascript
import { join } from '@ember/runloop';
join(function() {
// creates a new run-loop
});
```
Alternatively, if called within an existing run loop:
```javascript
import { run, join } from '@ember/runloop';
run(function() {
// creates a new run-loop
join(function() {
// joins with the existing run-loop, and queues for invocation on
// the existing run-loops action queue.
});
});
```
@method join
@static
@for @ember/runloop
@param {Object} [target] target of method to call
@param {Function|String} method Method to invoke.
May be a function or a string. If you pass a string
then it will be looked up on the passed target.
@param {Object} [args*] Any additional arguments you wish to pass to the method.
@return {Object} Return value from invoking the passed function. Please note,
when called within an existing loop, no return value is possible.
@public
*/
function join() {
return _backburner.join(...arguments);
}
/**
Allows you to specify which context to call the specified function in while
adding the execution of that function to the Ember run loop. This ability
makes this method a great way to asynchronously integrate third-party libraries
into your Ember application.
`bind` takes two main arguments, the desired context and the function to
invoke in that context. Any additional arguments will be supplied as arguments
to the function that is passed in.
Let's use the creation of a TinyMCE component as an example. Currently,
TinyMCE provides a setup configuration option we can use to do some processing
after the TinyMCE instance is initialized but before it is actually rendered.
We can use that setup option to do some additional setup for our component.
The component itself could look something like the following:
```app/components/rich-text-editor.js
import Component from '@ember/component';
import { on } from '@ember/object/evented';
import { bind } from '@ember/runloop';
export default Component.extend({
initializeTinyMCE: on('didInsertElement', function() {
tinymce.init({
selector: '#' + this.$().prop('id'),
setup: bind(this, this.setupEditor)
});
}),
didInsertElement() {
tinymce.init({
selector: '#' + this.$().prop('id'),
setup: bind(this, this.setupEditor)
});
}
setupEditor(editor) {
this.set('editor', editor);
editor.on('change', function() {
console.log('content changed!');
});
}
});
```
In this example, we use `bind` to bind the setupEditor method to the
context of the RichTextEditor component and to have the invocation of that
method be safely handled and executed by the Ember run loop.
@method bind
@static
@for @ember/runloop
@param {Object} [target] target of method to call
@param {Function|String} method Method to invoke.
May be a function or a string. If you pass a string
then it will be looked up on the passed target.
@param {Object} [args*] Any additional arguments you wish to pass to the method.
@return {Function} returns a new function that will always have a particular context
@since 1.4.0
@public
*/
var bind = (...curried) => {
(true && !(function (methodOrTarget, methodOrArg) {
// Applies the same logic as backburner parseArgs for detecting if a method
// is actually being passed.
var length = arguments.length;
if (length === 0) {
return false;
} else if (length === 1) {
return typeof methodOrTarget === 'function';
} else {
var type = typeof methodOrArg;
return type === 'function' || // second argument is a function
methodOrTarget !== null && type === 'string' && methodOrArg in methodOrTarget || // second argument is the name of a method in first argument
typeof methodOrTarget === 'function' //first argument is a function
;
}
}(...curried)) && (0, _debug.assert)('could not find a suitable method to bind', function (methodOrTarget, methodOrArg) {
var length = arguments.length;
if (length === 0) {
return false;
} else if (length === 1) {
return typeof methodOrTarget === 'function';
} else {
var type = typeof methodOrArg;
return type === 'function' || methodOrTarget !== null && type === 'string' && methodOrArg in methodOrTarget || typeof methodOrTarget === 'function';
}
}(...curried)));
return (...args) => join(...curried.concat(args));
};
/**
Begins a new RunLoop. Any deferred actions invoked after the begin will
be buffered until you invoke a matching call to `end()`. This is
a lower-level way to use a RunLoop instead of using `run()`.
```javascript
import { begin, end } from '@ember/runloop';
begin();
// code to be executed within a RunLoop
end();
```
@method begin
@static
@for @ember/runloop
@return {void}
@public
*/
_exports.bind = bind;
function begin() {
_backburner.begin();
}
/**
Ends a RunLoop. This must be called sometime after you call
`begin()` to flush any deferred actions. This is a lower-level way
to use a RunLoop instead of using `run()`.
```javascript
import { begin, end } from '@ember/runloop';
begin();
// code to be executed within a RunLoop
end();
```
@method end
@static
@for @ember/runloop
@return {void}
@public
*/
function end() {
_backburner.end();
}
/**
Adds the passed target/method and any optional arguments to the named
queue to be executed at the end of the RunLoop. If you have not already
started a RunLoop when calling this method one will be started for you
automatically.
At the end of a RunLoop, any methods scheduled in this way will be invoked.
Methods will be invoked in an order matching the named queues defined in
the `queues` property.
```javascript
import { schedule } from '@ember/runloop';
schedule('afterRender', this, function() {
// this will be executed in the 'afterRender' queue
console.log('scheduled on afterRender queue');
});
schedule('actions', this, function() {
// this will be executed in the 'actions' queue
console.log('scheduled on actions queue');
});
// Note the functions will be run in order based on the run queues order.
// Output would be:
// scheduled on actions queue
// scheduled on afterRender queue
```
@method schedule
@static
@for @ember/runloop
@param {String} queue The name of the queue to schedule against. Default queues is 'actions'
@param {Object} [target] target object to use as the context when invoking a method.
@param {String|Function} method The method to invoke. If you pass a string it
will be resolved on the target object at the time the scheduled item is
invoked allowing you to change the target function.
@param {Object} [arguments*] Optional arguments to be passed to the queued method.
@return {*} Timer information for use in canceling, see `cancel`.
@public
*/
function schedule()
/* queue, target, method */
{
return _backburner.schedule(...arguments);
} // Used by global test teardown
function _hasScheduledTimers() {
return _backburner.hasTimers();
} // Used by global test teardown
function _cancelTimers() {
_backburner.cancelTimers();
}
/**
Invokes the passed target/method and optional arguments after a specified
period of time. The last parameter of this method must always be a number
of milliseconds.
You should use this method whenever you need to run some action after a
period of time instead of using `setTimeout()`. This method will ensure that
items that expire during the same script execution cycle all execute
together, which is often more efficient than using a real setTimeout.
```javascript
import { later } from '@ember/runloop';
later(myContext, function() {
// code here will execute within a RunLoop in about 500ms with this == myContext
}, 500);
```
@method later
@static
@for @ember/runloop
@param {Object} [target] target of method to invoke
@param {Function|String} method The method to invoke.
If you pass a string it will be resolved on the
target at the time the method is invoked.
@param {Object} [args*] Optional arguments to pass to the timeout.
@param {Number} wait Number of milliseconds to wait.
@return {*} Timer information for use in canceling, see `cancel`.
@public
*/
function later()
/*target, method*/
{
return _backburner.later(...arguments);
}
/**
Schedule a function to run one time during the current RunLoop. This is equivalent
to calling `scheduleOnce` with the "actions" queue.
@method once
@static
@for @ember/runloop
@param {Object} [target] The target of the method to invoke.
@param {Function|String} method The method to invoke.
If you pass a string it will be resolved on the
target at the time the method is invoked.
@param {Object} [args*] Optional arguments to pass to the timeout.
@return {Object} Timer information for use in canceling, see `cancel`.
@public
*/
function once(...args) {
args.unshift('actions');
return _backburner.scheduleOnce(...args);
}
/**
Schedules a function to run one time in a given queue of the current RunLoop.
Calling this method with the same queue/target/method combination will have
no effect (past the initial call).
Note that although you can pass optional arguments these will not be
considered when looking for duplicates. New arguments will replace previous
calls.
```javascript
import { run, scheduleOnce } from '@ember/runloop';
function sayHi() {
console.log('hi');
}
run(function() {
scheduleOnce('afterRender', myContext, sayHi);
scheduleOnce('afterRender', myContext, sayHi);
// sayHi will only be executed once, in the afterRender queue of the RunLoop
});
```
Also note that for `scheduleOnce` to prevent additional calls, you need to
pass the same function instance. The following case works as expected:
```javascript
function log() {
console.log('Logging only once');
}
function scheduleIt() {
scheduleOnce('actions', myContext, log);
}
scheduleIt();
scheduleIt();
```
But this other case will schedule the function multiple times:
```javascript
import { scheduleOnce } from '@ember/runloop';
function scheduleIt() {
scheduleOnce('actions', myContext, function() {
console.log('Closure');
});
}
scheduleIt();
scheduleIt();
// "Closure" will print twice, even though we're using `scheduleOnce`,
// because the function we pass to it won't match the
// previously scheduled operation.
```
Available queues, and their order, can be found at `queues`
@method scheduleOnce
@static
@for @ember/runloop
@param {String} [queue] The name of the queue to schedule against. Default queues is 'actions'.
@param {Object} [target] The target of the method to invoke.
@param {Function|String} method The method to invoke.
If you pass a string it will be resolved on the
target at the time the method is invoked.
@param {Object} [args*] Optional arguments to pass to the timeout.
@return {Object} Timer information for use in canceling, see `cancel`.
@public
*/
function scheduleOnce()
/* queue, target, method*/
{
return _backburner.scheduleOnce(...arguments);
}
/**
Schedules an item to run from within a separate run loop, after
control has been returned to the system. This is equivalent to calling
`later` with a wait time of 1ms.
```javascript
import { next } from '@ember/runloop';
next(myContext, function() {
// code to be executed in the next run loop,
// which will be scheduled after the current one
});
```
Multiple operations scheduled with `next` will coalesce
into the same later run loop, along with any other operations
scheduled by `later` that expire right around the same
time that `next` operations will fire.
Note that there are often alternatives to using `next`.
For instance, if you'd like to schedule an operation to happen
after all DOM element operations have completed within the current
run loop, you can make use of the `afterRender` run loop queue (added
by the `ember-views` package, along with the preceding `render` queue
where all the DOM element operations happen).
Example:
```app/components/my-component.js
import Component from '@ember/component';
import { scheduleOnce } from '@ember/runloop';
export Component.extend({
didInsertElement() {
this._super(...arguments);
scheduleOnce('afterRender', this, 'processChildElements');
},
processChildElements() {
// ... do something with component's child component
// elements after they've finished rendering, which
// can't be done within this component's
// `didInsertElement` hook because that gets run
// before the child elements have been added to the DOM.
}
});
```
One benefit of the above approach compared to using `next` is
that you will be able to perform DOM/CSS operations before unprocessed
elements are rendered to the screen, which may prevent flickering or
other artifacts caused by delaying processing until after rendering.
The other major benefit to the above approach is that `next`
introduces an element of non-determinism, which can make things much
harder to test, due to its reliance on `setTimeout`; it's much harder
to guarantee the order of scheduled operations when they are scheduled
outside of the current run loop, i.e. with `next`.
@method next
@static
@for @ember/runloop
@param {Object} [target] target of method to invoke
@param {Function|String} method The method to invoke.
If you pass a string it will be resolved on the
target at the time the method is invoked.
@param {Object} [args*] Optional arguments to pass to the timeout.
@return {Object} Timer information for use in canceling, see `cancel`.
@public
*/
function next(...args) {
args.push(1);
return _backburner.later(...args);
}
/**
Cancels a scheduled item. Must be a value returned by `later()`,
`once()`, `scheduleOnce()`, `next()`, `debounce()`, or
`throttle()`.
```javascript
import {
next,
cancel,
later,
scheduleOnce,
once,
throttle,
debounce
} from '@ember/runloop';
let runNext = next(myContext, function() {
// will not be executed
});
cancel(runNext);
let runLater = later(myContext, function() {
// will not be executed
}, 500);
cancel(runLater);
let runScheduleOnce = scheduleOnce('afterRender', myContext, function() {
// will not be executed
});
cancel(runScheduleOnce);
let runOnce = once(myContext, function() {
// will not be executed
});
cancel(runOnce);
let throttle = throttle(myContext, function() {
// will not be executed
}, 1, false);
cancel(throttle);
let debounce = debounce(myContext, function() {
// will not be executed
}, 1);
cancel(debounce);
let debounceImmediate = debounce(myContext, function() {
// will be executed since we passed in true (immediate)
}, 100, true);
// the 100ms delay until this method can be called again will be canceled
cancel(debounceImmediate);
```
@method cancel
@static
@for @ember/runloop
@param {Object} timer Timer object to cancel
@return {Boolean} true if canceled or false/undefined if it wasn't found
@public
*/
function cancel(timer) {
return _backburner.cancel(timer);
}
/**
Delay calling the target method until the debounce period has elapsed
with no additional debounce calls. If `debounce` is called again before
the specified time has elapsed, the timer is reset and the entire period
must pass again before the target method is called.
This method should be used when an event may be called multiple times
but the action should only be called once when the event is done firing.
A common example is for scroll events where you only want updates to
happen once scrolling has ceased.
```javascript
import { debounce } from '@ember/runloop';
function whoRan() {
console.log(this.name + ' ran.');
}
let myContext = { name: 'debounce' };
debounce(myContext, whoRan, 150);
// less than 150ms passes
debounce(myContext, whoRan, 150);
// 150ms passes
// whoRan is invoked with context myContext
// console logs 'debounce ran.' one time.
```
Immediate allows you to run the function immediately, but debounce
other calls for this function until the wait time has elapsed. If
`debounce` is called again before the specified time has elapsed,
the timer is reset and the entire period must pass again before
the method can be called again.
```javascript
import { debounce } from '@ember/runloop';
function whoRan() {
console.log(this.name + ' ran.');
}
let myContext = { name: 'debounce' };
debounce(myContext, whoRan, 150, true);
// console logs 'debounce ran.' one time immediately.
// 100ms passes
debounce(myContext, whoRan, 150, true);
// 150ms passes and nothing else is logged to the console and
// the debouncee is no longer being watched
debounce(myContext, whoRan, 150, true);
// console logs 'debounce ran.' one time immediately.
// 150ms passes and nothing else is logged to the console and
// the debouncee is no longer being watched
```
@method debounce
@static
@for @ember/runloop
@param {Object} [target] target of method to invoke
@param {Function|String} method The method to invoke.
May be a function or a string. If you pass a string
then it will be looked up on the passed target.
@param {Object} [args*] Optional arguments to pass to the timeout.
@param {Number} wait Number of milliseconds to wait.
@param {Boolean} immediate Trigger the function on the leading instead
of the trailing edge of the wait interval. Defaults to false.
@return {Array} Timer information for use in canceling, see `cancel`.
@public
*/
function debounce() {
return _backburner.debounce(...arguments);
}
/**
Ensure that the target method is never called more frequently than
the specified spacing period. The target method is called immediately.
```javascript
import { throttle } from '@ember/runloop';
function whoRan() {
console.log(this.name + ' ran.');
}
let myContext = { name: 'throttle' };
throttle(myContext, whoRan, 150);
// whoRan is invoked with context myContext
// console logs 'throttle ran.'
// 50ms passes
throttle(myContext, whoRan, 150);
// 50ms passes
throttle(myContext, whoRan, 150);
// 150ms passes
throttle(myContext, whoRan, 150);
// whoRan is invoked with context myContext
// console logs 'throttle ran.'
```
@method throttle
@static
@for @ember/runloop
@param {Object} [target] target of method to invoke
@param {Function|String} method The method to invoke.
May be a function or a string. If you pass a string
then it will be looked up on the passed target.
@param {Object} [args*] Optional arguments to pass to the timeout.
@param {Number} spacing Number of milliseconds to space out requests.
@param {Boolean} immediate Trigger the function on the leading instead
of the trailing edge of the wait interval. Defaults to true.
@return {Array} Timer information for use in canceling, see `cancel`.
@public
*/
function throttle() {
return _backburner.throttle(...arguments);
}
});
define("@ember/service/index", ["exports", "@ember/-internals/runtime", "@ember/-internals/metal"], function (_exports, _runtime, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.inject = inject;
_exports.default = void 0;
/**
@module @ember/service
@public
*/
/**
Creates a property that lazily looks up a service in the container. There are
no restrictions as to what objects a service can be injected into.
Example:
```app/routes/application.js
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default class ApplicationRoute extends Route {
@service('auth') authManager;
model() {
return this.authManager.findCurrentUser();
}
}
```
Classic Class Example:
```app/routes/application.js
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default Route.extend({
authManager: service('auth'),
model() {
return this.get('authManager').findCurrentUser();
}
});
```
This example will create an `authManager` property on the application route
that looks up the `auth` service in the container, making it easily accessible
in the `model` hook.
@method inject
@static
@since 1.10.0
@for @ember/service
@param {String} name (optional) name of the service to inject, defaults to
the property's name
@return {ComputedDecorator} injection decorator instance
@public
*/
function inject() {
return (0, _metal.inject)('service', ...arguments);
}
/**
@class Service
@extends EmberObject
@since 1.10.0
@public
*/
var Service = _runtime.FrameworkObject.extend();
Service.reopenClass({
isServiceFactory: true
});
var _default = Service;
_exports.default = _default;
});
define("@ember/string/index", ["exports", "@ember/string/lib/string_registry", "@ember/-internals/utils", "@ember/debug", "@ember/-internals/glimmer"], function (_exports, _string_registry, _utils, _debug, _glimmer) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.w = w;
_exports.decamelize = decamelize;
_exports.dasherize = dasherize;
_exports.camelize = camelize;
_exports.classify = classify;
_exports.underscore = underscore;
_exports.capitalize = capitalize;
_exports.htmlSafe = htmlSafe;
_exports.isHTMLSafe = isHTMLSafe;
Object.defineProperty(_exports, "_getStrings", {
enumerable: true,
get: function () {
return _string_registry.getStrings;
}
});
Object.defineProperty(_exports, "_setStrings", {
enumerable: true,
get: function () {
return _string_registry.setStrings;
}
});
/**
@module @ember/string
*/
var STRING_DASHERIZE_REGEXP = /[ _]/g;
var STRING_DASHERIZE_CACHE = new _utils.Cache(1000, key => decamelize(key).replace(STRING_DASHERIZE_REGEXP, '-'));
var STRING_CAMELIZE_REGEXP_1 = /(-|_|\.|\s)+(.)?/g;
var STRING_CAMELIZE_REGEXP_2 = /(^|\/)([A-Z])/g;
var CAMELIZE_CACHE = new _utils.Cache(1000, key => key.replace(STRING_CAMELIZE_REGEXP_1, (_match, _separator, chr) => chr ? chr.toUpperCase() : '').replace(STRING_CAMELIZE_REGEXP_2, (match
/*, separator, chr */
) => match.toLowerCase()));
var STRING_CLASSIFY_REGEXP_1 = /^(-|_)+(.)?/;
var STRING_CLASSIFY_REGEXP_2 = /(.)(-|_|\.|\s)+(.)?/g;
var STRING_CLASSIFY_REGEXP_3 = /(^|\/|\.)([a-z])/g;
var CLASSIFY_CACHE = new _utils.Cache(1000, str => {
var replace1 = (_match, _separator, chr) => chr ? `_${chr.toUpperCase()}` : '';
var replace2 = (_match, initialChar, _separator, chr) => initialChar + (chr ? chr.toUpperCase() : '');
var parts = str.split('/');
for (var i = 0; i < parts.length; i++) {
parts[i] = parts[i].replace(STRING_CLASSIFY_REGEXP_1, replace1).replace(STRING_CLASSIFY_REGEXP_2, replace2);
}
return parts.join('/').replace(STRING_CLASSIFY_REGEXP_3, (match
/*, separator, chr */
) => match.toUpperCase());
});
var STRING_UNDERSCORE_REGEXP_1 = /([a-z\d])([A-Z]+)/g;
var STRING_UNDERSCORE_REGEXP_2 = /-|\s+/g;
var UNDERSCORE_CACHE = new _utils.Cache(1000, str => str.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2').replace(STRING_UNDERSCORE_REGEXP_2, '_').toLowerCase());
var STRING_CAPITALIZE_REGEXP = /(^|\/)([a-z\u00C0-\u024F])/g;
var CAPITALIZE_CACHE = new _utils.Cache(1000, str => str.replace(STRING_CAPITALIZE_REGEXP, (match
/*, separator, chr */
) => match.toUpperCase()));
var STRING_DECAMELIZE_REGEXP = /([a-z\d])([A-Z])/g;
var DECAMELIZE_CACHE = new _utils.Cache(1000, str => str.replace(STRING_DECAMELIZE_REGEXP, '$1_$2').toLowerCase());
/**
Defines string helper methods including string formatting and localization.
@class String
@public
*/
/**
Splits a string into separate units separated by spaces, eliminating any
empty strings in the process.
```javascript
import { w } from '@ember/string';
w("alpha beta gamma").forEach(function(key) {
console.log(key);
});
// > alpha
// > beta
// > gamma
```
@method w
@param {String} str The string to split
@return {Array} array containing the split strings
@public
*/
function w(str) {
return str.split(/\s+/);
}
/**
Converts a camelized string into all lower case separated by underscores.
```javascript
import { decamelize } from '@ember/string';
decamelize('innerHTML'); // 'inner_html'
decamelize('action_name'); // 'action_name'
decamelize('css-class-name'); // 'css-class-name'
decamelize('my favorite items'); // 'my favorite items'
```
@method decamelize
@param {String} str The string to decamelize.
@return {String} the decamelized string.
@public
*/
function decamelize(str) {
return DECAMELIZE_CACHE.get(str);
}
/**
Replaces underscores, spaces, or camelCase with dashes.
```javascript
import { dasherize } from '@ember/string';
dasherize('innerHTML'); // 'inner-html'
dasherize('action_name'); // 'action-name'
dasherize('css-class-name'); // 'css-class-name'
dasherize('my favorite items'); // 'my-favorite-items'
dasherize('privateDocs/ownerInvoice'; // 'private-docs/owner-invoice'
```
@method dasherize
@param {String} str The string to dasherize.
@return {String} the dasherized string.
@public
*/
function dasherize(str) {
return STRING_DASHERIZE_CACHE.get(str);
}
/**
Returns the lowerCamelCase form of a string.
```javascript
import { camelize } from '@ember/string';
camelize('innerHTML'); // 'innerHTML'
camelize('action_name'); // 'actionName'
camelize('css-class-name'); // 'cssClassName'
camelize('my favorite items'); // 'myFavoriteItems'
camelize('My Favorite Items'); // 'myFavoriteItems'
camelize('private-docs/owner-invoice'); // 'privateDocs/ownerInvoice'
```
@method camelize
@param {String} str The string to camelize.
@return {String} the camelized string.
@public
*/
function camelize(str) {
return CAMELIZE_CACHE.get(str);
}
/**
Returns the UpperCamelCase form of a string.
```javascript
import { classify } from '@ember/string';
classify('innerHTML'); // 'InnerHTML'
classify('action_name'); // 'ActionName'
classify('css-class-name'); // 'CssClassName'
classify('my favorite items'); // 'MyFavoriteItems'
classify('private-docs/owner-invoice'); // 'PrivateDocs/OwnerInvoice'
```
@method classify
@param {String} str the string to classify
@return {String} the classified string
@public
*/
function classify(str) {
return CLASSIFY_CACHE.get(str);
}
/**
More general than decamelize. Returns the lower\_case\_and\_underscored
form of a string.
```javascript
import { underscore } from '@ember/string';
underscore('innerHTML'); // 'inner_html'
underscore('action_name'); // 'action_name'
underscore('css-class-name'); // 'css_class_name'
underscore('my favorite items'); // 'my_favorite_items'
underscore('privateDocs/ownerInvoice'); // 'private_docs/owner_invoice'
```
@method underscore
@param {String} str The string to underscore.
@return {String} the underscored string.
@public
*/
function underscore(str) {
return UNDERSCORE_CACHE.get(str);
}
/**
Returns the Capitalized form of a string
```javascript
import { capitalize } from '@ember/string';
capitalize('innerHTML') // 'InnerHTML'
capitalize('action_name') // 'Action_name'
capitalize('css-class-name') // 'Css-class-name'
capitalize('my favorite items') // 'My favorite items'
capitalize('privateDocs/ownerInvoice'); // 'PrivateDocs/ownerInvoice'
```
@method capitalize
@param {String} str The string to capitalize.
@return {String} The capitalized string.
@public
*/
function capitalize(str) {
return CAPITALIZE_CACHE.get(str);
}
function deprecateImportFromString(name, message = `Importing ${name} from '@ember/string' is deprecated. Please import ${name} from '@ember/template' instead.`) {
// Disabling this deprecation due to unintended errors in 3.25
// See https://github.com/emberjs/ember.js/issues/19393 fo more information.
(true && !(true) && (0, _debug.deprecate)(message, true, {
id: 'ember-string.htmlsafe-ishtmlsafe',
for: 'ember-source',
since: {
enabled: '3.25'
},
until: '4.0.0',
url: 'https://deprecations.emberjs.com/v3.x/#toc_ember-string-htmlsafe-ishtmlsafe'
}));
}
function htmlSafe(str) {
deprecateImportFromString('htmlSafe');
return (0, _glimmer.htmlSafe)(str);
}
function isHTMLSafe(str) {
deprecateImportFromString('isHTMLSafe');
return (0, _glimmer.isHTMLSafe)(str);
}
});
define("@ember/string/lib/string_registry", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.setStrings = setStrings;
_exports.getStrings = getStrings;
_exports.getString = getString;
// STATE within a module is frowned upon, this exists
// to support Ember.STRINGS but shield ember internals from this legacy global
// API.
var STRINGS = {};
function setStrings(strings) {
STRINGS = strings;
}
function getStrings() {
return STRINGS;
}
function getString(name) {
return STRINGS[name];
}
});
define("@ember/template-compilation/index", ["exports", "ember-template-compiler"], function (_exports, _emberTemplateCompiler) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "compileTemplate", {
enumerable: true,
get: function () {
return _emberTemplateCompiler.compile;
}
});
_exports.precompileTemplate = void 0;
var precompileTemplate;
_exports.precompileTemplate = precompileTemplate;
if (true
/* DEBUG */
) {
_exports.precompileTemplate = precompileTemplate = () => {
throw new Error('Attempted to call `precompileTemplate` at runtime, but this API is meant to be used at compile time. You should use `compileTemplate` instead.');
};
}
});
define("@ember/template-factory/index", ["exports", "@glimmer/opcode-compiler"], function (_exports, _opcodeCompiler) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "createTemplateFactory", {
enumerable: true,
get: function () {
return _opcodeCompiler.templateFactory;
}
});
});
define("@ember/template/index", ["exports", "@ember/-internals/glimmer"], function (_exports, _glimmer) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "htmlSafe", {
enumerable: true,
get: function () {
return _glimmer.htmlSafe;
}
});
Object.defineProperty(_exports, "isHTMLSafe", {
enumerable: true,
get: function () {
return _glimmer.isHTMLSafe;
}
});
});
define("@ember/test/adapter", ["exports", "ember-testing"], function (_exports, _emberTesting) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
var _default = _emberTesting.Test.Adapter;
_exports.default = _default;
});
define("@ember/test/index", ["exports", "require"], function (_exports, _require) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.unregisterWaiter = _exports.unregisterHelper = _exports.registerWaiter = _exports.registerHelper = _exports.registerAsyncHelper = void 0;
var registerAsyncHelper;
_exports.registerAsyncHelper = registerAsyncHelper;
var registerHelper;
_exports.registerHelper = registerHelper;
var registerWaiter;
_exports.registerWaiter = registerWaiter;
var unregisterHelper;
_exports.unregisterHelper = unregisterHelper;
var unregisterWaiter;
_exports.unregisterWaiter = unregisterWaiter;
if ((0, _require.has)('ember-testing')) {
var {
Test
} = (0, _require.default)("ember-testing");
_exports.registerAsyncHelper = registerAsyncHelper = Test.registerAsyncHelper;
_exports.registerHelper = registerHelper = Test.registerHelper;
_exports.registerWaiter = registerWaiter = Test.registerWaiter;
_exports.unregisterHelper = unregisterHelper = Test.unregisterHelper;
_exports.unregisterWaiter = unregisterWaiter = Test.unregisterWaiter;
} else {
var testingNotAvailableMessage = () => {
throw new Error('Attempted to use test utilities, but `ember-testing` was not included');
};
_exports.registerAsyncHelper = registerAsyncHelper = testingNotAvailableMessage;
_exports.registerHelper = registerHelper = testingNotAvailableMessage;
_exports.registerWaiter = registerWaiter = testingNotAvailableMessage;
_exports.unregisterHelper = unregisterHelper = testingNotAvailableMessage;
_exports.unregisterWaiter = unregisterWaiter = testingNotAvailableMessage;
}
});
define("@ember/utils/index", ["exports", "@ember/-internals/metal", "@ember/-internals/runtime"], function (_exports, _metal, _runtime) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "isNone", {
enumerable: true,
get: function () {
return _metal.isNone;
}
});
Object.defineProperty(_exports, "isBlank", {
enumerable: true,
get: function () {
return _metal.isBlank;
}
});
Object.defineProperty(_exports, "isEmpty", {
enumerable: true,
get: function () {
return _metal.isEmpty;
}
});
Object.defineProperty(_exports, "isPresent", {
enumerable: true,
get: function () {
return _metal.isPresent;
}
});
Object.defineProperty(_exports, "compare", {
enumerable: true,
get: function () {
return _runtime.compare;
}
});
Object.defineProperty(_exports, "isEqual", {
enumerable: true,
get: function () {
return _runtime.isEqual;
}
});
Object.defineProperty(_exports, "typeOf", {
enumerable: true,
get: function () {
return _runtime.typeOf;
}
});
});
define("@ember/version/index", ["exports", "ember/version"], function (_exports, _version) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "VERSION", {
enumerable: true,
get: function () {
return _version.default;
}
});
});
define("@glimmer/destroyable", ["exports", "@glimmer/util", "@glimmer/global-context"], function (_exports, _util, _globalContext) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.associateDestroyableChild = associateDestroyableChild;
_exports.registerDestructor = registerDestructor;
_exports.unregisterDestructor = unregisterDestructor;
_exports.destroy = destroy;
_exports.destroyChildren = destroyChildren;
_exports._hasDestroyableChildren = _hasDestroyableChildren;
_exports.isDestroying = isDestroying;
_exports.isDestroyed = isDestroyed;
_exports.assertDestroyablesDestroyed = _exports.enableDestroyableTracking = void 0;
var DESTROYABLE_META = new WeakMap();
function push(collection, newItem) {
if (collection === null) {
return newItem;
} else if (Array.isArray(collection)) {
collection.push(newItem);
return collection;
} else {
return [collection, newItem];
}
}
function iterate(collection, fn) {
if (Array.isArray(collection)) {
for (var i = 0; i < collection.length; i++) {
fn(collection[i]);
}
} else if (collection !== null) {
fn(collection);
}
}
function remove(collection, item, message) {
if (true
/* DEBUG */
) {
var collectionIsItem = collection === item;
var collectionContainsItem = Array.isArray(collection) && collection.indexOf(item) !== -1;
if (!collectionIsItem && !collectionContainsItem) {
throw new Error(String(message));
}
}
if (Array.isArray(collection) && collection.length > 1) {
var index = collection.indexOf(item);
collection.splice(index, 1);
return collection;
} else {
return null;
}
}
function getDestroyableMeta(destroyable) {
var meta = DESTROYABLE_META.get(destroyable);
if (meta === undefined) {
meta = {
parents: null,
children: null,
eagerDestructors: null,
destructors: null,
state: 0
/* Live */
};
if (true
/* DEBUG */
) {
meta.source = destroyable;
}
DESTROYABLE_META.set(destroyable, meta);
}
return meta;
}
function associateDestroyableChild(parent, child) {
if (true
/* DEBUG */
&& isDestroying(parent)) {
throw new Error('Attempted to associate a destroyable child with an object that is already destroying or destroyed');
}
var parentMeta = getDestroyableMeta(parent);
var childMeta = getDestroyableMeta(child);
parentMeta.children = push(parentMeta.children, child);
childMeta.parents = push(childMeta.parents, parent);
return child;
}
function registerDestructor(destroyable, destructor, eager = false) {
if (true
/* DEBUG */
&& isDestroying(destroyable)) {
throw new Error('Attempted to register a destructor with an object that is already destroying or destroyed');
}
var meta = getDestroyableMeta(destroyable);
var destructorsKey = eager === true ? 'eagerDestructors' : 'destructors';
meta[destructorsKey] = push(meta[destructorsKey], destructor);
return destructor;
}
function unregisterDestructor(destroyable, destructor, eager = false) {
if (true
/* DEBUG */
&& isDestroying(destroyable)) {
throw new Error('Attempted to unregister a destructor with an object that is already destroying or destroyed');
}
var meta = getDestroyableMeta(destroyable);
var destructorsKey = eager === true ? 'eagerDestructors' : 'destructors';
meta[destructorsKey] = remove(meta[destructorsKey], destructor, true
/* DEBUG */
&& 'attempted to remove a destructor that was not registered with the destroyable');
} ////////////
function destroy(destroyable) {
var meta = getDestroyableMeta(destroyable);
if (meta.state >= 1
/* Destroying */
) return;
var {
parents,
children,
eagerDestructors,
destructors
} = meta;
meta.state = 1
/* Destroying */
;
iterate(children, destroy);
iterate(eagerDestructors, destructor => destructor(destroyable));
iterate(destructors, destructor => (0, _globalContext.scheduleDestroy)(destroyable, destructor));
(0, _globalContext.scheduleDestroyed)(() => {
iterate(parents, parent => removeChildFromParent(destroyable, parent));
meta.state = 2
/* Destroyed */
;
});
}
function removeChildFromParent(child, parent) {
var parentMeta = getDestroyableMeta(parent);
if (parentMeta.state === 0
/* Live */
) {
parentMeta.children = remove(parentMeta.children, child, true
/* DEBUG */
&& "attempted to remove child from parent, but the parent's children did not contain the child. This is likely a bug with destructors.");
}
}
function destroyChildren(destroyable) {
var {
children
} = getDestroyableMeta(destroyable);
iterate(children, destroy);
}
function _hasDestroyableChildren(destroyable) {
var meta = DESTROYABLE_META.get(destroyable);
return meta === undefined ? false : meta.children !== null;
}
function isDestroying(destroyable) {
var meta = DESTROYABLE_META.get(destroyable);
return meta === undefined ? false : meta.state >= 1
/* Destroying */
;
}
function isDestroyed(destroyable) {
var meta = DESTROYABLE_META.get(destroyable);
return meta === undefined ? false : meta.state >= 2
/* Destroyed */
;
} ////////////
var enableDestroyableTracking;
_exports.enableDestroyableTracking = enableDestroyableTracking;
var assertDestroyablesDestroyed;
_exports.assertDestroyablesDestroyed = assertDestroyablesDestroyed;
if (true
/* DEBUG */
) {
var isTesting = false;
_exports.enableDestroyableTracking = enableDestroyableTracking = () => {
if (isTesting) {
// Reset destroyable meta just in case, before throwing the error
DESTROYABLE_META = new WeakMap();
throw new Error('Attempted to start destroyable testing, but you did not end the previous destroyable test. Did you forget to call `assertDestroyablesDestroyed()`');
}
isTesting = true;
DESTROYABLE_META = new Map();
};
_exports.assertDestroyablesDestroyed = assertDestroyablesDestroyed = () => {
if (!isTesting) {
throw new Error('Attempted to assert destroyables destroyed, but you did not start a destroyable test. Did you forget to call `enableDestroyableTracking()`');
}
isTesting = false;
var map = DESTROYABLE_META;
DESTROYABLE_META = new WeakMap();
var undestroyed = [];
map.forEach(meta => {
if (meta.state !== 2
/* Destroyed */
) {
undestroyed.push(meta.source);
}
});
if (undestroyed.length > 0) {
var objectsToString = undestroyed.map(_util.debugToString).join('\n ');
var error = new Error(`Some destroyables were not destroyed during this test:\n ${objectsToString}`);
error.destroyables = undestroyed;
throw error;
}
};
}
});
define("@glimmer/encoder", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.InstructionEncoderImpl = void 0;
class InstructionEncoderImpl {
constructor(buffer) {
this.buffer = buffer;
this.size = 0;
}
encode(type, machine) {
if (type > 255
/* TYPE_SIZE */
) {
throw new Error(`Opcode type over 8-bits. Got ${type}.`);
}
var first = type | machine | arguments.length - 2 << 8
/* ARG_SHIFT */
;
this.buffer.push(first);
for (var i = 2; i < arguments.length; i++) {
var op = arguments[i];
if (true
/* DEBUG */
&& typeof op === 'number' && op > 2147483647
/* MAX_SIZE */
) {
throw new Error(`Operand over 32-bits. Got ${op}.`);
}
this.buffer.push(op);
}
this.size = this.buffer.length;
}
patch(position, target) {
if (this.buffer[position + 1] === -1) {
this.buffer[position + 1] = target;
} else {
throw new Error('Trying to patch operand in populated slot instead of a reserved slot.');
}
}
}
_exports.InstructionEncoderImpl = InstructionEncoderImpl;
});
define("@glimmer/env", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.CI = _exports.DEBUG = void 0;
var DEBUG = false;
_exports.DEBUG = DEBUG;
var CI = false;
_exports.CI = CI;
});
define("@glimmer/global-context", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.testOverrideGlobalContext = _exports.assertGlobalContextWasSet = _exports.deprecate = _exports.assert = _exports.warnIfStyleNotTrusted = _exports.setPath = _exports.getPath = _exports.setProp = _exports.getProp = _exports.toBool = _exports.toIterator = _exports.scheduleDestroyed = _exports.scheduleDestroy = _exports.scheduleRevalidate = _exports.default = void 0;
/**
* This package contains global context functions for Glimmer. These functions
* are set by the embedding environment and must be set before initial render.
*
* These functions should meet the following criteria:
*
* - Must be provided by the embedder, due to having framework specific
* behaviors (e.g. interop with classic Ember behaviors that should not be
* upstreamed) or to being out of scope for the VM (e.g. scheduling a
* revalidation)
* - Never differ between render roots
* - Never change over time
*
*/
/**
* Schedules a VM revalidation.
*
* Note: this has a default value so that tags can warm themselves when first loaded.
*/
var scheduleRevalidate = () => {};
/**
* Schedules a destructor to run
*
* @param destroyable The destroyable being destroyed
* @param destructor The destructor being scheduled
*/
_exports.scheduleRevalidate = scheduleRevalidate;
var scheduleDestroy;
/**
* Finalizes destruction
*
* @param finalizer finalizer function
*/
_exports.scheduleDestroy = scheduleDestroy;
var scheduleDestroyed;
/**
* Hook to provide iterators for `{{each}}` loops
*
* @param value The value to create an iterator for
*/
_exports.scheduleDestroyed = scheduleDestroyed;
var toIterator;
/**
* Hook to specify truthiness within Glimmer templates
*
* @param value The value to convert to a boolean
*/
_exports.toIterator = toIterator;
var toBool;
/**
* Hook for specifying how Glimmer should access properties in cases where it
* needs to. For instance, accessing an object's values in templates.
*
* @param obj The object provided to get a value from
* @param path The path to get the value from
*/
_exports.toBool = toBool;
var getProp;
/**
* Hook for specifying how Glimmer should update props in cases where it needs
* to. For instance, when updating a template reference (e.g. 2-way-binding)
*
* @param obj The object provided to get a value from
* @param prop The prop to set the value at
* @param value The value to set the value to
*/
_exports.getProp = getProp;
var setProp;
/**
* Hook for specifying how Glimmer should access paths in cases where it needs
* to. For instance, the `key` value of `{{each}}` loops.
*
* @param obj The object provided to get a value from
* @param path The path to get the value from
*/
_exports.setProp = setProp;
var getPath;
/**
* Hook for specifying how Glimmer should update paths in cases where it needs
* to. For instance, when updating a template reference (e.g. 2-way-binding)
*
* @param obj The object provided to get a value from
* @param path The path to get the value from
*/
_exports.getPath = getPath;
var setPath;
/**
* Hook to warn if a style binding string or value was not marked as trusted
* (e.g. HTMLSafe)
*/
_exports.setPath = setPath;
var warnIfStyleNotTrusted;
/**
* Hook to customize assertion messages in the VM. Usages can be stripped out
* by using the @glimmer/vm-babel-plugins package.
*/
_exports.warnIfStyleNotTrusted = warnIfStyleNotTrusted;
var assert;
/**
* Hook to customize deprecation messages in the VM. Usages can be stripped out
* by using the @glimmer/vm-babel-plugins package.
*/
_exports.assert = assert;
var deprecate;
_exports.deprecate = deprecate;
var globalContextWasSet = false;
function setGlobalContext(context) {
if (true
/* DEBUG */
) {
if (globalContextWasSet) {
throw new Error('Attempted to set the global context twice. This should only be set once.');
}
globalContextWasSet = true;
}
_exports.scheduleRevalidate = scheduleRevalidate = context.scheduleRevalidate;
_exports.scheduleDestroy = scheduleDestroy = context.scheduleDestroy;
_exports.scheduleDestroyed = scheduleDestroyed = context.scheduleDestroyed;
_exports.toIterator = toIterator = context.toIterator;
_exports.toBool = toBool = context.toBool;
_exports.getProp = getProp = context.getProp;
_exports.setProp = setProp = context.setProp;
_exports.getPath = getPath = context.getPath;
_exports.setPath = setPath = context.setPath;
_exports.warnIfStyleNotTrusted = warnIfStyleNotTrusted = context.warnIfStyleNotTrusted;
_exports.assert = assert = context.assert;
_exports.deprecate = deprecate = context.deprecate;
}
var assertGlobalContextWasSet;
_exports.assertGlobalContextWasSet = assertGlobalContextWasSet;
var testOverrideGlobalContext;
_exports.testOverrideGlobalContext = testOverrideGlobalContext;
if (true
/* DEBUG */
) {
_exports.assertGlobalContextWasSet = assertGlobalContextWasSet = () => {
if (globalContextWasSet === false) {
throw new Error('The global context for Glimmer VM was not set. You must set these global context functions to let Glimmer VM know how to accomplish certain operations. You can do this by importing `setGlobalContext` from `@glimmer/global-context`');
}
};
_exports.testOverrideGlobalContext = testOverrideGlobalContext = context => {
var originalGlobalContext = globalContextWasSet ? {
scheduleRevalidate,
scheduleDestroy,
scheduleDestroyed,
toIterator,
toBool,
getProp,
setProp,
getPath,
setPath,
warnIfStyleNotTrusted,
assert,
deprecate
} : null;
if (context === null) {
globalContextWasSet = false;
} else {
globalContextWasSet = true;
} // We use `undefined as any` here to unset the values when resetting the
// context at the end of a test.
_exports.scheduleRevalidate = scheduleRevalidate = (context === null || context === void 0 ? void 0 : context.scheduleRevalidate) || undefined;
_exports.scheduleDestroy = scheduleDestroy = (context === null || context === void 0 ? void 0 : context.scheduleDestroy) || undefined;
_exports.scheduleDestroyed = scheduleDestroyed = (context === null || context === void 0 ? void 0 : context.scheduleDestroyed) || undefined;
_exports.toIterator = toIterator = (context === null || context === void 0 ? void 0 : context.toIterator) || undefined;
_exports.toBool = toBool = (context === null || context === void 0 ? void 0 : context.toBool) || undefined;
_exports.getProp = getProp = (context === null || context === void 0 ? void 0 : context.getProp) || undefined;
_exports.setProp = setProp = (context === null || context === void 0 ? void 0 : context.setProp) || undefined;
_exports.getPath = getPath = (context === null || context === void 0 ? void 0 : context.getPath) || undefined;
_exports.setPath = setPath = (context === null || context === void 0 ? void 0 : context.setPath) || undefined;
_exports.warnIfStyleNotTrusted = warnIfStyleNotTrusted = (context === null || context === void 0 ? void 0 : context.warnIfStyleNotTrusted) || undefined;
_exports.assert = assert = (context === null || context === void 0 ? void 0 : context.assert) || undefined;
_exports.deprecate = deprecate = (context === null || context === void 0 ? void 0 : context.deprecate) || undefined;
return originalGlobalContext;
};
}
var _default = setGlobalContext;
_exports.default = _default;
});
define("@glimmer/low-level", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.Stack = _exports.Storage = void 0;
class Storage {
constructor() {
this.array = [];
this.next = 0;
}
add(element) {
var {
next: slot,
array
} = this;
if (slot === array.length) {
this.next++;
} else {
var prev = array[slot];
this.next = prev;
}
this.array[slot] = element;
return slot;
}
deref(pointer) {
return this.array[pointer];
}
drop(pointer) {
this.array[pointer] = this.next;
this.next = pointer;
}
}
_exports.Storage = Storage;
class Stack {
constructor(vec = []) {
this.vec = vec;
}
clone() {
return new Stack(this.vec.slice());
}
sliceFrom(start) {
return new Stack(this.vec.slice(start));
}
slice(start, end) {
return new Stack(this.vec.slice(start, end));
}
copy(from, to) {
this.vec[to] = this.vec[from];
} // TODO: how to model u64 argument?
writeRaw(pos, value) {
// TODO: Grow?
this.vec[pos] = value;
} // TODO: partially decoded enum?
getRaw(pos) {
return this.vec[pos];
}
reset() {
this.vec.length = 0;
}
len() {
return this.vec.length;
}
}
_exports.Stack = Stack;
});
define("@glimmer/manager", ["exports", "@glimmer/util", "@glimmer/reference", "@glimmer/validator", "@glimmer/destroyable"], function (_exports, _util, _reference, _validator, _destroyable) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.setInternalHelperManager = setInternalHelperManager;
_exports.setInternalModifierManager = setInternalModifierManager;
_exports.setInternalComponentManager = setInternalComponentManager;
_exports.getInternalHelperManager = getInternalHelperManager;
_exports.getInternalModifierManager = getInternalModifierManager;
_exports.getInternalComponentManager = getInternalComponentManager;
_exports.hasInternalHelperManager = hasInternalHelperManager;
_exports.hasInternalModifierManager = hasInternalModifierManager;
_exports.hasInternalComponentManager = hasInternalComponentManager;
_exports.setHelperManager = setHelperManager;
_exports.setModifierManager = setModifierManager;
_exports.setComponentManager = setComponentManager;
_exports.componentCapabilities = componentCapabilities;
_exports.modifierCapabilities = modifierCapabilities;
_exports.helperCapabilities = helperCapabilities;
_exports.hasDestroyable = hasDestroyable;
_exports.hasValue = hasValue;
_exports.getComponentTemplate = getComponentTemplate;
_exports.setComponentTemplate = setComponentTemplate;
_exports.capabilityFlagsFrom = capabilityFlagsFrom;
_exports.hasCapability = hasCapability;
_exports.managerHasCapability = managerHasCapability;
_exports.getCustomTagFor = getCustomTagFor;
_exports.setCustomTagFor = setCustomTagFor;
_exports.CustomHelperManager = _exports.CustomModifierManager = _exports.CustomComponentManager = void 0;
var COMPONENT_MANAGERS = new WeakMap();
var MODIFIER_MANAGERS = new WeakMap();
var HELPER_MANAGERS = new WeakMap(); ///////////
var getPrototypeOf = Object.getPrototypeOf;
function setManager(map, manager, obj) {
if (true
/* DEBUG */
&& (typeof obj !== 'object' || obj === null) && typeof obj !== 'function') {
throw new Error(`Attempted to set a manager on a non-object value. Managers can only be associated with objects or functions. Value was ${(0, _util.debugToString)(obj)}`);
}
if (true
/* DEBUG */
&& map.has(obj)) {
throw new Error(`Attempted to set the same type of manager multiple times on a value. You can only associate one manager of each type with a given value. Value was ${(0, _util.debugToString)(obj)}`);
}
map.set(obj, manager);
return obj;
}
function getManager(map, obj) {
var pointer = obj;
while (pointer !== undefined && pointer !== null) {
var manager = map.get(pointer);
if (manager !== undefined) {
return manager;
}
pointer = getPrototypeOf(pointer);
}
return undefined;
} ///////////
function setInternalModifierManager(manager, definition) {
return setManager(MODIFIER_MANAGERS, manager, definition);
}
function getInternalModifierManager(definition, isOptional) {
if (true
/* DEBUG */
&& typeof definition !== 'function' && (typeof definition !== 'object' || definition === null)) {
throw new Error(`Attempted to use a value as a modifier, but it was not an object or function. Modifier definitions must be objects or functions with an associated modifier manager. The value was: ${definition}`);
}
var manager = getManager(MODIFIER_MANAGERS, definition);
if (manager === undefined) {
if (isOptional === true) {
return null;
} else if (true
/* DEBUG */
) {
throw new Error(`Attempted to load a modifier, but there wasn't a modifier manager associated with the definition. The definition was: ${(0, _util.debugToString)(definition)}`);
}
}
return manager;
}
function setInternalHelperManager(manager, definition) {
return setManager(HELPER_MANAGERS, manager, definition);
}
function getInternalHelperManager(definition, isOptional) {
if (true
/* DEBUG */
&& typeof definition !== 'function' && (typeof definition !== 'object' || definition === null)) {
throw new Error(`Attempted to use a value as a helper, but it was not an object or function. Helper definitions must be objects or functions with an associated helper manager. The value was: ${definition}`);
}
var manager = getManager(HELPER_MANAGERS, definition);
if (manager === undefined) {
if (isOptional === true) {
return null;
} else if (true
/* DEBUG */
) {
throw new Error(`Attempted to load a helper, but there wasn't a helper manager associated with the definition. The definition was: ${(0, _util.debugToString)(definition)}`);
}
}
return manager;
}
function setInternalComponentManager(factory, obj) {
return setManager(COMPONENT_MANAGERS, factory, obj);
}
function getInternalComponentManager(definition, isOptional) {
if (true
/* DEBUG */
&& typeof definition !== 'function' && (typeof definition !== 'object' || definition === null)) {
throw new Error(`Attempted to use a value as a component, but it was not an object or function. Component definitions must be objects or functions with an associated component manager. The value was: ${definition}`);
}
var manager = getManager(COMPONENT_MANAGERS, definition);
if (manager === undefined) {
if (isOptional === true) {
return null;
} else if (true
/* DEBUG */
) {
throw new Error(`Attempted to load a component, but there wasn't a component manager associated with the definition. The definition was: ${(0, _util.debugToString)(definition)}`);
}
}
return manager;
} ///////////
function hasInternalComponentManager(definition) {
return getManager(COMPONENT_MANAGERS, definition) !== undefined;
}
function hasInternalHelperManager(definition) {
return getManager(HELPER_MANAGERS, definition) !== undefined;
}
function hasInternalModifierManager(definition) {
return getManager(MODIFIER_MANAGERS, definition) !== undefined;
}
var FROM_CAPABILITIES = true
/* DEBUG */
? new _util._WeakSet() : undefined;
function buildCapabilities(capabilities) {
if (true
/* DEBUG */
) {
FROM_CAPABILITIES.add(capabilities);
Object.freeze(capabilities);
}
return capabilities;
}
/**
* Converts a ComponentCapabilities object into a 32-bit integer representation.
*/
function capabilityFlagsFrom(capabilities) {
return 0 | (capabilities.dynamicLayout ? 1
/* DynamicLayout */
: 0) | (capabilities.dynamicTag ? 2
/* DynamicTag */
: 0) | (capabilities.prepareArgs ? 4
/* PrepareArgs */
: 0) | (capabilities.createArgs ? 8
/* CreateArgs */
: 0) | (capabilities.attributeHook ? 16
/* AttributeHook */
: 0) | (capabilities.elementHook ? 32
/* ElementHook */
: 0) | (capabilities.dynamicScope ? 64
/* DynamicScope */
: 0) | (capabilities.createCaller ? 128
/* CreateCaller */
: 0) | (capabilities.updateHook ? 256
/* UpdateHook */
: 0) | (capabilities.createInstance ? 512
/* CreateInstance */
: 0) | (capabilities.wrapped ? 1024
/* Wrapped */
: 0) | (capabilities.willDestroy ? 2048
/* WillDestroy */
: 0) | (capabilities.hasSubOwner ? 4096
/* HasSubOwner */
: 0);
}
function managerHasCapability(_manager, capabilities, capability) {
return !!(capabilities & capability);
}
function hasCapability(capabilities, capability) {
return !!(capabilities & capability);
}
var CUSTOM_TAG_FOR = new WeakMap();
function getCustomTagFor(obj) {
return CUSTOM_TAG_FOR.get(obj);
}
function setCustomTagFor(obj, customTagFn) {
CUSTOM_TAG_FOR.set(obj, customTagFn);
}
function convertToInt(prop) {
if (typeof prop === 'symbol') return null;
var num = Number(prop);
if (isNaN(num)) return null;
return num % 1 === 0 ? num : null;
}
function tagForNamedArg(namedArgs, key) {
return (0, _validator.track)(() => {
if (key in namedArgs) {
(0, _reference.valueForRef)(namedArgs[key]);
}
});
}
function tagForPositionalArg(positionalArgs, key) {
return (0, _validator.track)(() => {
if (key === '[]') {
// consume all of the tags in the positional array
positionalArgs.forEach(_reference.valueForRef);
}
var parsed = convertToInt(key);
if (parsed !== null && parsed < positionalArgs.length) {
// consume the tag of the referenced index
(0, _reference.valueForRef)(positionalArgs[parsed]);
}
});
}
var argsProxyFor;
class NamedArgsProxy {
constructor(named) {
this.named = named;
}
get(_target, prop) {
var ref = this.named[prop];
if (ref !== undefined) {
return (0, _reference.valueForRef)(ref);
}
}
has(_target, prop) {
return prop in this.named;
}
ownKeys() {
return Object.keys(this.named);
}
isExtensible() {
return false;
}
getOwnPropertyDescriptor(_target, prop) {
if (true
/* DEBUG */
&& !(prop in this.named)) {
throw new Error(`args proxies do not have real property descriptors, so you should never need to call getOwnPropertyDescriptor yourself. This code exists for enumerability, such as in for-in loops and Object.keys(). Attempted to get the descriptor for \`${String(prop)}\``);
}
return {
enumerable: true,
configurable: true
};
}
}
class PositionalArgsProxy {
constructor(positional) {
this.positional = positional;
}
get(target, prop) {
var {
positional
} = this;
if (prop === 'length') {
return positional.length;
}
var parsed = convertToInt(prop);
if (parsed !== null && parsed < positional.length) {
return (0, _reference.valueForRef)(positional[parsed]);
}
return target[prop];
}
isExtensible() {
return false;
}
has(_target, prop) {
var parsed = convertToInt(prop);
return parsed !== null && parsed < this.positional.length;
}
}
if (_util.HAS_NATIVE_PROXY) {
argsProxyFor = (capturedArgs, type) => {
var {
named,
positional
} = capturedArgs;
var getNamedTag = (_obj, key) => tagForNamedArg(named, key);
var getPositionalTag = (_obj, key) => tagForPositionalArg(positional, key);
var namedHandler = new NamedArgsProxy(named);
var positionalHandler = new PositionalArgsProxy(positional);
var namedTarget = Object.create(null);
var positionalTarget = [];
if (true
/* DEBUG */
) {
var setHandler = function (_target, prop) {
throw new Error(`You attempted to set ${String(prop)} on the arguments of a component, helper, or modifier. Arguments are immutable and cannot be updated directly, they always represent the values that is passed down. If you want to set default values, you should use a getter and local tracked state instead.`);
};
var forInDebugHandler = () => {
throw new Error(`Object.keys() was called on the positional arguments array for a ${type}, which is not supported. This function is a low-level function that should not need to be called for positional argument arrays. You may be attempting to iterate over the array using for...in instead of for...of.`);
};
namedHandler.set = setHandler;
positionalHandler.set = setHandler;
positionalHandler.ownKeys = forInDebugHandler;
}
var namedProxy = new Proxy(namedTarget, namedHandler);
var positionalProxy = new Proxy(positionalTarget, positionalHandler);
setCustomTagFor(namedProxy, getNamedTag);
setCustomTagFor(positionalProxy, getPositionalTag);
return {
named: namedProxy,
positional: positionalProxy
};
};
} else {
argsProxyFor = (capturedArgs, _type) => {
var {
named,
positional
} = capturedArgs;
var getNamedTag = (_obj, key) => tagForNamedArg(named, key);
var getPositionalTag = (_obj, key) => tagForPositionalArg(positional, key);
var namedProxy = {};
var positionalProxy = [];
setCustomTagFor(namedProxy, getNamedTag);
setCustomTagFor(positionalProxy, getPositionalTag);
Object.keys(named).forEach(name => {
Object.defineProperty(namedProxy, name, {
enumerable: true,
configurable: true,
get() {
return (0, _reference.valueForRef)(named[name]);
}
});
});
positional.forEach((ref, index) => {
Object.defineProperty(positionalProxy, index, {
enumerable: true,
configurable: true,
get() {
return (0, _reference.valueForRef)(ref);
}
});
});
if (true
/* DEBUG */
) {
// Prevent mutations in development mode. This will not prevent the
// proxy from updating, but will prevent assigning new values or pushing
// for instance.
Object.freeze(namedProxy);
Object.freeze(positionalProxy);
}
return {
named: namedProxy,
positional: positionalProxy
};
};
}
var CAPABILITIES = {
dynamicLayout: false,
dynamicTag: false,
prepareArgs: false,
createArgs: true,
attributeHook: false,
elementHook: false,
createCaller: false,
dynamicScope: true,
updateHook: true,
createInstance: true,
wrapped: false,
willDestroy: false,
hasSubOwner: false
};
function componentCapabilities(managerAPI, options = {}) {
if (true
/* DEBUG */
&& managerAPI !== '3.13') {
throw new Error('Invalid component manager compatibility specified');
}
var updateHook = Boolean(options.updateHook);
return buildCapabilities({
asyncLifeCycleCallbacks: Boolean(options.asyncLifecycleCallbacks),
destructor: Boolean(options.destructor),
updateHook
});
}
function hasAsyncLifeCycleCallbacks(delegate) {
return delegate.capabilities.asyncLifeCycleCallbacks;
}
function hasUpdateHook(delegate) {
return delegate.capabilities.updateHook;
}
function hasAsyncUpdateHook(delegate) {
return hasAsyncLifeCycleCallbacks(delegate) && hasUpdateHook(delegate);
}
function hasDestructors(delegate) {
return delegate.capabilities.destructor;
}
/**
The CustomComponentManager allows addons to provide custom component
implementations that integrate seamlessly into Ember. This is accomplished
through a delegate, registered with the custom component manager, which
implements a set of hooks that determine component behavior.
To create a custom component manager, instantiate a new CustomComponentManager
class and pass the delegate as the first argument:
```js
let manager = new CustomComponentManager({
// ...delegate implementation...
});
```
## Delegate Hooks
Throughout the lifecycle of a component, the component manager will invoke
delegate hooks that are responsible for surfacing those lifecycle changes to
the end developer.
* `create()` - invoked when a new instance of a component should be created
* `update()` - invoked when the arguments passed to a component change
* `getContext()` - returns the object that should be
*/
class CustomComponentManager {
constructor(factory) {
this.factory = factory;
this.componentManagerDelegates = new WeakMap();
}
getDelegateFor(owner) {
var {
componentManagerDelegates
} = this;
var delegate = componentManagerDelegates.get(owner);
if (delegate === undefined) {
var {
factory
} = this;
delegate = factory(owner);
if (true
/* DEBUG */
&& !FROM_CAPABILITIES.has(delegate.capabilities)) {
// TODO: This error message should make sense in both Ember and Glimmer https://github.com/glimmerjs/glimmer-vm/issues/1200
throw new Error(`Custom component managers must have a \`capabilities\` property that is the result of calling the \`capabilities('3.13')\` (imported via \`import { capabilities } from '@ember/component';\`). Received: \`${JSON.stringify(delegate.capabilities)}\` for: \`${delegate}\``);
}
componentManagerDelegates.set(owner, delegate);
}
return delegate;
}
create(owner, definition, vmArgs) {
var delegate = this.getDelegateFor(owner);
var args = argsProxyFor(vmArgs.capture(), 'component');
var component = delegate.createComponent(definition, args);
return new CustomComponentState(component, delegate, args);
}
getDebugName(definition) {
return typeof definition === 'function' ? definition.name : definition.toString();
}
update(bucket) {
var {
delegate
} = bucket;
if (hasUpdateHook(delegate)) {
var {
component,
args
} = bucket;
delegate.updateComponent(component, args);
}
}
didCreate({
component,
delegate
}) {
if (hasAsyncLifeCycleCallbacks(delegate)) {
delegate.didCreateComponent(component);
}
}
didUpdate({
component,
delegate
}) {
if (hasAsyncUpdateHook(delegate)) {
delegate.didUpdateComponent(component);
}
}
didRenderLayout() {}
didUpdateLayout() {}
getSelf({
component,
delegate
}) {
return (0, _reference.createConstRef)(delegate.getContext(component), 'this');
}
getDestroyable(bucket) {
var {
delegate
} = bucket;
if (hasDestructors(delegate)) {
var {
component
} = bucket;
(0, _destroyable.registerDestructor)(bucket, () => delegate.destroyComponent(component));
return bucket;
}
return null;
}
getCapabilities() {
return CAPABILITIES;
}
}
/**
* Stores internal state about a component instance after it's been created.
*/
_exports.CustomComponentManager = CustomComponentManager;
class CustomComponentState {
constructor(component, delegate, args) {
this.component = component;
this.delegate = delegate;
this.args = args;
}
}
function modifierCapabilities(managerAPI, optionalFeatures = {}) {
if (true
/* DEBUG */
&& managerAPI !== '3.22') {
throw new Error('Invalid modifier manager compatibility specified');
}
return buildCapabilities({
disableAutoTracking: Boolean(optionalFeatures.disableAutoTracking)
});
}
/**
The CustomModifierManager allows addons to provide custom modifier
implementations that integrate seamlessly into Ember. This is accomplished
through a delegate, registered with the custom modifier manager, which
implements a set of hooks that determine modifier behavior.
To create a custom modifier manager, instantiate a new CustomModifierManager
class and pass the delegate as the first argument:
```js
let manager = new CustomModifierManager({
// ...delegate implementation...
});
```
## Delegate Hooks
Throughout the lifecycle of a modifier, the modifier manager will invoke
delegate hooks that are responsible for surfacing those lifecycle changes to
the end developer.
* `createModifier()` - invoked when a new instance of a modifier should be created
* `installModifier()` - invoked when the modifier is installed on the element
* `updateModifier()` - invoked when the arguments passed to a modifier change
* `destroyModifier()` - invoked when the modifier is about to be destroyed
*/
class CustomModifierManager {
constructor(factory) {
this.factory = factory;
this.componentManagerDelegates = new WeakMap();
}
getDelegateFor(owner) {
var {
componentManagerDelegates
} = this;
var delegate = componentManagerDelegates.get(owner);
if (delegate === undefined) {
var {
factory
} = this;
delegate = factory(owner);
if (true
/* DEBUG */
&& !FROM_CAPABILITIES.has(delegate.capabilities)) {
// TODO: This error message should make sense in both Ember and Glimmer https://github.com/glimmerjs/glimmer-vm/issues/1200
throw new Error(`Custom modifier managers must have a \`capabilities\` property that is the result of calling the \`capabilities('3.22')\` (imported via \`import { capabilities } from '@ember/modifier';\`). Received: \`${JSON.stringify(delegate.capabilities)}\` for: \`${delegate}\``);
}
componentManagerDelegates.set(owner, delegate);
}
return delegate;
}
create(owner, element, definition, capturedArgs) {
var delegate = this.getDelegateFor(owner);
var args = argsProxyFor(capturedArgs, 'modifier');
var instance = delegate.createModifier(definition, args);
var tag = (0, _validator.createUpdatableTag)();
var state;
state = {
tag,
element,
delegate,
args,
modifier: instance
};
if (true
/* DEBUG */
) {
state.debugName = typeof definition === 'function' ? definition.name : definition.toString();
}
(0, _destroyable.registerDestructor)(state, () => delegate.destroyModifier(instance, args));
return state;
}
getDebugName({
debugName
}) {
return debugName;
}
getTag({
tag
}) {
return tag;
}
install({
element,
args,
modifier,
delegate
}) {
var {
capabilities
} = delegate;
if (capabilities.disableAutoTracking === true) {
(0, _validator.untrack)(() => delegate.installModifier(modifier, element, args));
} else {
delegate.installModifier(modifier, element, args);
}
}
update({
args,
modifier,
delegate
}) {
var {
capabilities
} = delegate;
if (capabilities.disableAutoTracking === true) {
(0, _validator.untrack)(() => delegate.updateModifier(modifier, args));
} else {
delegate.updateModifier(modifier, args);
}
}
getDestroyable(state) {
return state;
}
}
_exports.CustomModifierManager = CustomModifierManager;
function helperCapabilities(managerAPI, options = {}) {
if (true
/* DEBUG */
&& managerAPI !== '3.23') {
throw new Error('Invalid helper manager compatibility specified');
}
if (true
/* DEBUG */
&& (!(options.hasValue || options.hasScheduledEffect) || options.hasValue && options.hasScheduledEffect)) {
throw new Error('You must pass either the `hasValue` OR the `hasScheduledEffect` capability when defining a helper manager. Passing neither, or both, is not permitted.');
}
if (true
/* DEBUG */
&& options.hasScheduledEffect) {
throw new Error('The `hasScheduledEffect` capability has not yet been implemented for helper managers. Please pass `hasValue` instead');
}
return buildCapabilities({
hasValue: Boolean(options.hasValue),
hasDestroyable: Boolean(options.hasDestroyable),
hasScheduledEffect: Boolean(options.hasScheduledEffect)
});
} ////////////
function hasValue(manager) {
return manager.capabilities.hasValue;
}
function hasDestroyable(manager) {
return manager.capabilities.hasDestroyable;
} ////////////
class CustomHelperManager {
constructor(factory) {
this.factory = factory;
this.helperManagerDelegates = new WeakMap();
this.undefinedDelegate = null;
}
getDelegateForOwner(owner) {
var delegate = this.helperManagerDelegates.get(owner);
if (delegate === undefined) {
var {
factory
} = this;
delegate = factory(owner);
if (true
/* DEBUG */
&& !FROM_CAPABILITIES.has(delegate.capabilities)) {
// TODO: This error message should make sense in both Ember and Glimmer https://github.com/glimmerjs/glimmer-vm/issues/1200
throw new Error(`Custom helper managers must have a \`capabilities\` property that is the result of calling the \`capabilities('3.23')\` (imported via \`import { capabilities } from '@ember/helper';\`). Received: \`${JSON.stringify(delegate.capabilities)}\` for: \`${delegate}\``);
}
this.helperManagerDelegates.set(owner, delegate);
}
return delegate;
}
getDelegateFor(owner) {
if (owner === undefined) {
var {
undefinedDelegate
} = this;
if (undefinedDelegate === null) {
var {
factory
} = this;
this.undefinedDelegate = undefinedDelegate = factory(undefined);
}
return undefinedDelegate;
} else {
return this.getDelegateForOwner(owner);
}
}
getHelper(definition) {
return (capturedArgs, owner) => {
var _a, _b;
var manager = this.getDelegateFor(owner);
var args = argsProxyFor(capturedArgs, 'helper');
var bucket = manager.createHelper(definition, args);
if (hasValue(manager)) {
var cache = (0, _reference.createComputeRef)(() => manager.getValue(bucket), null, true
/* DEBUG */
&& manager.getDebugName && manager.getDebugName(definition));
if (hasDestroyable(manager)) {
(0, _destroyable.associateDestroyableChild)(cache, manager.getDestroyable(bucket));
}
return cache;
} else if (hasDestroyable(manager)) {
var ref = (0, _reference.createConstRef)(undefined, true
/* DEBUG */
&& ((_b = (_a = manager.getDebugName) === null || _a === void 0 ? void 0 : _a.call(manager, definition)) !== null && _b !== void 0 ? _b : 'unknown helper'));
(0, _destroyable.associateDestroyableChild)(ref, manager.getDestroyable(bucket));
return ref;
} else {
return _reference.UNDEFINED_REFERENCE;
}
};
}
}
_exports.CustomHelperManager = CustomHelperManager;
function setComponentManager(factory, obj) {
return setInternalComponentManager(new CustomComponentManager(factory), obj);
}
function setModifierManager(factory, obj) {
return setInternalModifierManager(new CustomModifierManager(factory), obj);
}
function setHelperManager(factory, obj) {
return setInternalHelperManager(new CustomHelperManager(factory), obj);
}
var TEMPLATES = new WeakMap();
var getPrototypeOf$1 = Object.getPrototypeOf;
function setComponentTemplate(factory, obj) {
if (true
/* DEBUG */
&& !(obj !== null && (typeof obj === 'object' || typeof obj === 'function'))) {
throw new Error(`Cannot call \`setComponentTemplate\` on \`${(0, _util.debugToString)(obj)}\``);
}
if (true
/* DEBUG */
&& TEMPLATES.has(obj)) {
throw new Error(`Cannot call \`setComponentTemplate\` multiple times on the same class (\`${(0, _util.debugToString)(obj)}\`)`);
}
TEMPLATES.set(obj, factory);
return obj;
}
function getComponentTemplate(obj) {
var pointer = obj;
while (pointer !== null) {
var template = TEMPLATES.get(pointer);
if (template !== undefined) {
return template;
}
pointer = getPrototypeOf$1(pointer);
}
return undefined;
}
});
define("@glimmer/node", ["exports", "@glimmer/runtime", "@simple-dom/document"], function (_exports, _runtime, _document) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.serializeBuilder = serializeBuilder;
_exports.NodeDOMTreeConstruction = void 0;
class NodeDOMTreeConstruction extends _runtime.DOMTreeConstruction {
constructor(doc) {
super(doc || (0, _document.default)());
} // override to prevent usage of `this.document` until after the constructor
setupUselessElement() {}
insertHTMLBefore(parent, reference, html) {
var raw = this.document.createRawHTMLSection(html);
parent.insertBefore(raw, reference);
return new _runtime.ConcreteBounds(parent, raw, raw);
} // override to avoid SVG detection/work when in node (this is not needed in SSR)
createElement(tag) {
return this.document.createElement(tag);
} // override to avoid namespace shenanigans when in node (this is not needed in SSR)
setAttribute(element, name, value) {
element.setAttribute(name, value);
}
}
_exports.NodeDOMTreeConstruction = NodeDOMTreeConstruction;
var TEXT_NODE = 3;
var NEEDS_EXTRA_CLOSE = new WeakMap();
function currentNode(cursor) {
var {
element,
nextSibling
} = cursor;
if (nextSibling === null) {
return element.lastChild;
} else {
return nextSibling.previousSibling;
}
}
class SerializeBuilder extends _runtime.NewElementBuilder {
constructor() {
super(...arguments);
this.serializeBlockDepth = 0;
}
__openBlock() {
var {
tagName
} = this.element;
if (tagName !== 'TITLE' && tagName !== 'SCRIPT' && tagName !== 'STYLE') {
var depth = this.serializeBlockDepth++;
this.__appendComment(`%+b:${depth}%`);
}
super.__openBlock();
}
__closeBlock() {
var {
tagName
} = this.element;
super.__closeBlock();
if (tagName !== 'TITLE' && tagName !== 'SCRIPT' && tagName !== 'STYLE') {
var depth = --this.serializeBlockDepth;
this.__appendComment(`%-b:${depth}%`);
}
}
__appendHTML(html) {
var {
tagName
} = this.element;
if (tagName === 'TITLE' || tagName === 'SCRIPT' || tagName === 'STYLE') {
return super.__appendHTML(html);
} // Do we need to run the html tokenizer here?
var first = this.__appendComment('%glmr%');
if (tagName === 'TABLE') {
var openIndex = html.indexOf('<');
if (openIndex > -1) {
var tr = html.slice(openIndex + 1, openIndex + 3);
if (tr === 'tr') {
html = `<tbody>${html}</tbody>`;
}
}
}
if (html === '') {
this.__appendComment('% %');
} else {
super.__appendHTML(html);
}
var last = this.__appendComment('%glmr%');
return new _runtime.ConcreteBounds(this.element, first, last);
}
__appendText(string) {
var {
tagName
} = this.element;
var current = currentNode(this);
if (tagName === 'TITLE' || tagName === 'SCRIPT' || tagName === 'STYLE') {
return super.__appendText(string);
} else if (string === '') {
return this.__appendComment('% %');
} else if (current && current.nodeType === TEXT_NODE) {
this.__appendComment('%|%');
}
return super.__appendText(string);
}
closeElement() {
if (NEEDS_EXTRA_CLOSE.has(this.element)) {
NEEDS_EXTRA_CLOSE.delete(this.element);
super.closeElement();
}
return super.closeElement();
}
openElement(tag) {
if (tag === 'tr') {
if (this.element.tagName !== 'TBODY' && this.element.tagName !== 'THEAD' && this.element.tagName !== 'TFOOT') {
this.openElement('tbody'); // This prevents the closeBlock comment from being re-parented
// under the auto inserted tbody. Rehydration builder needs to
// account for the insertion since it is injected here and not
// really in the template.
NEEDS_EXTRA_CLOSE.set(this.constructing, true);
this.flushElement(null);
}
}
return super.openElement(tag);
}
pushRemoteElement(element, cursorId, insertBefore = null) {
var {
dom
} = this;
var script = dom.createElement('script');
script.setAttribute('glmr', cursorId);
dom.insertBefore(element, script, insertBefore);
return super.pushRemoteElement(element, cursorId, insertBefore);
}
}
function serializeBuilder(env, cursor) {
return SerializeBuilder.forInitialRender(env, cursor);
}
});
define("@glimmer/opcode-compiler", ["exports", "@glimmer/util", "@glimmer/vm", "@glimmer/global-context", "@glimmer/manager", "@glimmer/encoder"], function (_exports, _util, _vm, _globalContext, _manager, _encoder) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.compileStatements = compileStatements;
_exports.compilable = compilable;
_exports.invokeStaticBlockWithStack = InvokeStaticBlockWithStack;
_exports.invokeStaticBlock = InvokeStaticBlock;
_exports.compileStd = compileStd;
_exports.meta = meta;
_exports.templateFactory = templateFactory;
_exports.programCompilationContext = programCompilationContext;
_exports.templateCompilationContext = templateCompilationContext;
_exports.MINIMAL_CAPABILITIES = _exports.DEFAULT_CAPABILITIES = _exports.CompileTimeCompilationContextImpl = _exports.EMPTY_BLOCKS = _exports.WrappedBuilder = _exports.templateCacheCounters = _exports.StdLib = _exports.debugCompiler = void 0;
class NamedBlocksImpl {
constructor(blocks) {
this.blocks = blocks;
this.names = blocks ? Object.keys(blocks) : [];
}
get(name) {
if (!this.blocks) return null;
return this.blocks[name] || null;
}
has(name) {
var {
blocks
} = this;
return blocks !== null && name in blocks;
}
with(name, block) {
var {
blocks
} = this;
if (blocks) {
return new NamedBlocksImpl((0, _util.assign)({}, blocks, {
[name]: block
}));
} else {
return new NamedBlocksImpl({
[name]: block
});
}
}
get hasAny() {
return this.blocks !== null;
}
}
var EMPTY_BLOCKS = new NamedBlocksImpl(null);
_exports.EMPTY_BLOCKS = EMPTY_BLOCKS;
function namedBlocks(blocks) {
if (blocks === null) {
return EMPTY_BLOCKS;
}
var out = (0, _util.dict)();
var [keys, values] = blocks;
for (var i = 0; i < keys.length; i++) {
out[keys[i]] = values[i];
}
return new NamedBlocksImpl(out);
}
function labelOperand(value) {
return {
type: 1
/* Label */
,
value
};
}
function evalSymbolsOperand() {
return {
type: 3
/* EvalSymbols */
,
value: undefined
};
}
function isStrictMode() {
return {
type: 2
/* IsStrictMode */
,
value: undefined
};
}
function blockOperand(value) {
return {
type: 4
/* Block */
,
value
};
}
function stdlibOperand(value) {
return {
type: 5
/* StdLib */
,
value
};
}
function nonSmallIntOperand(value) {
return {
type: 6
/* NonSmallInt */
,
value
};
}
function symbolTableOperand(value) {
return {
type: 7
/* SymbolTable */
,
value
};
}
function layoutOperand(value) {
return {
type: 8
/* Layout */
,
value
};
}
function isGetLikeTuple(opcode) {
return Array.isArray(opcode) && opcode.length === 2;
}
function makeResolutionTypeVerifier(typeToVerify) {
return opcode => {
if (!isGetLikeTuple(opcode)) return false;
var type = opcode[0];
return type === 31
/* GetStrictFree */
|| type === 32
/* GetTemplateSymbol */
|| type === typeToVerify;
};
}
var isGetFreeComponent = makeResolutionTypeVerifier(39
/* GetFreeAsComponentHead */
);
var isGetFreeModifier = makeResolutionTypeVerifier(38
/* GetFreeAsModifierHead */
);
var isGetFreeHelper = makeResolutionTypeVerifier(37
/* GetFreeAsHelperHead */
);
var isGetFreeComponentOrHelper = makeResolutionTypeVerifier(35
/* GetFreeAsComponentOrHelperHead */
);
var isGetFreeOptionalComponentOrHelper = makeResolutionTypeVerifier(34
/* GetFreeAsComponentOrHelperHeadOrThisFallback */
);
function assertResolverInvariants(meta) {
if (true
/* DEBUG */
) {
if (!meta.upvars) {
throw new Error('Attempted to resolve a component, helper, or modifier, but no free vars were found');
}
if (!meta.owner) {
throw new Error('Attempted to resolve a component, helper, or modifier, but no owner was associated with the template it was being resolved from');
}
}
return meta;
}
/**
* <Foo/>
* <Foo></Foo>
* <Foo @arg={{true}} />
*/
function resolveComponent(resolver, constants, meta, [, expr, then]) {
var type = expr[0];
if (true
/* DEBUG */
&& expr[0] === 31
/* GetStrictFree */
) {
throw new Error(`Attempted to resolve a component in a strict mode template, but that value was not in scope: ${meta.upvars[expr[1]]}`);
}
if (type === 32
/* GetTemplateSymbol */
) {
var {
scopeValues,
owner
} = meta;
var definition = scopeValues[expr[1]];
then(constants.component(definition, owner));
} else {
var {
upvars,
owner: _owner
} = assertResolverInvariants(meta);
var name = upvars[expr[1]];
var _definition = resolver.lookupComponent(name, _owner);
if (true
/* DEBUG */
&& (typeof _definition !== 'object' || _definition === null)) {
throw new Error(`Attempted to resolve \`${name}\`, which was expected to be a component, but nothing was found.`);
}
then(constants.resolvedComponent(_definition, name));
}
}
/**
* (helper)
* (helper arg)
*/
function resolveHelper(resolver, constants, meta, [, expr, then]) {
var type = expr[0];
if (type === 32
/* GetTemplateSymbol */
) {
var {
scopeValues
} = meta;
var definition = scopeValues[expr[1]];
then(constants.helper(definition));
} else if (type === 31
/* GetStrictFree */
) {
then(lookupBuiltInHelper(expr, resolver, meta, constants, 'helper'));
} else {
var {
upvars,
owner
} = assertResolverInvariants(meta);
var name = upvars[expr[1]];
var helper = resolver.lookupHelper(name, owner);
if (true
/* DEBUG */
&& helper === null) {
throw new Error(`Attempted to resolve \`${name}\`, which was expected to be a helper, but nothing was found.`);
}
then(constants.helper(helper, name));
}
}
/**
* <div {{modifier}}/>
* <div {{modifier arg}}/>
* <Foo {{modifier}}/>
*/
function resolveModifier(resolver, constants, meta, [, expr, then]) {
var type = expr[0];
if (type === 32
/* GetTemplateSymbol */
) {
var {
scopeValues
} = meta;
var definition = scopeValues[expr[1]];
then(constants.modifier(definition));
} else if (type === 31
/* GetStrictFree */
) {
var {
upvars
} = assertResolverInvariants(meta);
var name = upvars[expr[1]];
var modifier = resolver.lookupBuiltInModifier(name);
if (true
/* DEBUG */
&& modifier === null) {
throw new Error(`Attempted to resolve a modifier in a strict mode template, but it was not in scope: ${name}`);
}
then(constants.modifier(modifier, name));
} else {
var {
upvars: _upvars,
owner
} = assertResolverInvariants(meta);
var _name2 = _upvars[expr[1]];
var _modifier = resolver.lookupModifier(_name2, owner);
if (true
/* DEBUG */
&& _modifier === null) {
throw new Error(`Attempted to resolve \`${_name2}\`, which was expected to be a modifier, but nothing was found.`);
}
then(constants.modifier(_modifier, _name2));
}
}
/**
* {{component-or-helper arg}}
*/
function resolveComponentOrHelper(resolver, constants, meta, [, expr, {
ifComponent,
ifHelper
}]) {
var type = expr[0];
if (type === 32
/* GetTemplateSymbol */
) {
var {
scopeValues,
owner
} = meta;
var definition = scopeValues[expr[1]];
var component = constants.component(definition, owner, true);
if (component !== null) {
ifComponent(component);
return;
}
var helper = constants.helper(definition, null, true);
if (true
/* DEBUG */
&& helper === null) {
throw new Error(`Attempted to use a value as either a component or helper, but it did not have a component manager or helper manager associated with it. The value was: ${(0, _util.debugToString)(definition)}`);
}
ifHelper(helper);
} else if (type === 31
/* GetStrictFree */
) {
ifHelper(lookupBuiltInHelper(expr, resolver, meta, constants, 'component or helper'));
} else {
var {
upvars,
owner: _owner2
} = assertResolverInvariants(meta);
var name = upvars[expr[1]];
var _definition2 = resolver.lookupComponent(name, _owner2);
if (_definition2 !== null) {
ifComponent(constants.resolvedComponent(_definition2, name));
} else {
var _helper = resolver.lookupHelper(name, _owner2);
if (true
/* DEBUG */
&& _helper === null) {
throw new Error(`Attempted to resolve \`${name}\`, which was expected to be a component or helper, but nothing was found.`);
}
ifHelper(constants.helper(_helper, name));
}
}
}
/**
* <Foo @arg={{helper}}>
*/
function resolveOptionalHelper(resolver, constants, meta, [, expr, {
ifHelper
}]) {
var {
upvars,
owner
} = assertResolverInvariants(meta);
var name = upvars[expr[1]];
var helper = resolver.lookupHelper(name, owner);
if (helper) {
ifHelper(constants.helper(helper, name), name, meta.moduleName);
}
}
/**
* {{maybeHelperOrComponent}}
*/
function resolveOptionalComponentOrHelper(resolver, constants, meta, [, expr, {
ifComponent,
ifHelper,
ifValue
}]) {
var type = expr[0];
if (type === 32
/* GetTemplateSymbol */
) {
var {
scopeValues,
owner
} = meta;
var definition = scopeValues[expr[1]];
if (typeof definition !== 'function' && (typeof definition !== 'object' || definition === null)) {
// The value is not an object, so it can't be a component or helper.
ifValue(constants.value(definition));
return;
}
var component = constants.component(definition, owner, true);
if (component !== null) {
ifComponent(component);
return;
}
var helper = constants.helper(definition, null, true);
if (helper !== null) {
ifHelper(helper);
return;
}
ifValue(constants.value(definition));
} else if (type === 31
/* GetStrictFree */
) {
ifHelper(lookupBuiltInHelper(expr, resolver, meta, constants, 'value'));
} else {
var {
upvars,
owner: _owner3
} = assertResolverInvariants(meta);
var name = upvars[expr[1]];
var _definition3 = resolver.lookupComponent(name, _owner3);
if (_definition3 !== null) {
ifComponent(constants.resolvedComponent(_definition3, name));
return;
}
var _helper2 = resolver.lookupHelper(name, _owner3);
if (_helper2 !== null) {
ifHelper(constants.helper(_helper2, name));
}
}
}
function lookupBuiltInHelper(expr, resolver, meta, constants, type) {
var {
upvars
} = assertResolverInvariants(meta);
var name = upvars[expr[1]];
var helper = resolver.lookupBuiltInHelper(name);
if (true
/* DEBUG */
&& helper === null) {
// Keyword helper did not exist, which means that we're attempting to use a
// value of some kind that is not in scope
throw new Error(`Attempted to resolve a ${type} in a strict mode template, but that value was not in scope: ${meta.upvars[expr[1]]}`);
}
return constants.helper(helper, name);
}
class Compilers {
constructor() {
this.names = {};
this.funcs = [];
}
add(name, func) {
this.names[name] = this.funcs.push(func) - 1;
}
compile(op, sexp) {
var name = sexp[0];
var index = this.names[name];
var func = this.funcs[index];
func(op, sexp);
}
}
var EXPRESSIONS = new Compilers();
EXPRESSIONS.add(29
/* Concat */
, (op, [, parts]) => {
for (var part of parts) {
expr(op, part);
}
op(27
/* Concat */
, parts.length);
});
EXPRESSIONS.add(28
/* Call */
, (op, [, expression, positional, named]) => {
if (isGetFreeHelper(expression)) {
op(1005
/* ResolveHelper */
, expression, handle => {
Call(op, handle, positional, named);
});
} else {
expr(op, expression);
CallDynamic(op, positional, named);
}
});
EXPRESSIONS.add(50
/* Curry */
, (op, [, expr$$1, type, positional, named]) => {
Curry(op, type, expr$$1, positional, named);
});
EXPRESSIONS.add(30
/* GetSymbol */
, (op, [, sym, path]) => {
op(21
/* GetVariable */
, sym);
withPath(op, path);
});
EXPRESSIONS.add(32
/* GetTemplateSymbol */
, (op, [, sym, path]) => {
op(1011
/* ResolveTemplateLocal */
, sym, handle => {
op(29
/* ConstantReference */
, handle);
withPath(op, path);
});
});
EXPRESSIONS.add(31
/* GetStrictFree */
, (op, [, sym, _path]) => {
op(1009
/* ResolveFree */
, sym, _handle => {// TODO: Implement in strict mode
});
});
EXPRESSIONS.add(34
/* GetFreeAsComponentOrHelperHeadOrThisFallback */
, () => {
// TODO: The logic for this opcode currently exists in STATEMENTS.Append, since
// we want different wrapping logic depending on if we are invoking a component,
// helper, or {{this}} fallback. Eventually we fix the opcodes so that we can
// traverse the subexpression tree like normal in this location.
throw new Error('unimplemented opcode');
});
EXPRESSIONS.add(36
/* GetFreeAsHelperHeadOrThisFallback */
, (op, expr$$1) => {
// <div id={{baz}}>
op(1010
/* ResolveLocal */
, expr$$1[1], _name => {
op(1006
/* ResolveOptionalHelper */
, expr$$1, {
ifHelper: handle => {
Call(op, handle, null, null);
}
});
});
});
EXPRESSIONS.add(99
/* GetFreeAsDeprecatedHelperHeadOrThisFallback */
, (op, expr$$1) => {
// <Foo @bar={{baz}}>
op(1010
/* ResolveLocal */
, expr$$1[1], _name => {
op(1006
/* ResolveOptionalHelper */
, expr$$1, {
ifHelper: (handle, name, moduleName) => {
(true && (0, _globalContext.assert)(expr$$1[2] && expr$$1[2].length === 1, '[BUG] Missing argument name'));
var arg = expr$$1[2][0];
(true && !(false) && (0, _globalContext.deprecate)(`The \`${name}\` helper was used in the \`${moduleName}\` template as \`${arg}={{${name}}}\`. ` + `This is ambigious between wanting the \`${arg}\` argument to be the \`${name}\` helper itself, ` + `or the result of invoking the \`${name}\` helper (current behavior). ` + `This implicit invocation behavior has been deprecated.\n\n` + `Instead, please explicitly invoke the helper with parenthesis, i.e. \`${arg}={{(${name})}}\`.\n\n` + `Note: the parenthesis are only required in this exact scenario where an ambiguity is present where ` + `\`${name}\` referes to a global helper (as opposed to a local variable), AND ` + `the \`${name}\` helper invocation does not take any arguments, AND ` + `this occurs in a named argument position of a component invocation.\n\n` + `We expect this combination to be quite rare, as most helpers require at least one argument. ` + `There is no need to refactor helper invocations in cases where this deprecation was not triggered.`, false, {
id: 'argument-less-helper-paren-less-invocation'
}));
Call(op, handle, null, null);
}
});
});
});
function withPath(op, path) {
if (path === undefined || path.length === 0) return;
for (var i = 0; i < path.length; i++) {
op(22
/* GetProperty */
, path[i]);
}
}
EXPRESSIONS.add(27
/* Undefined */
, op => PushPrimitiveReference(op, undefined));
EXPRESSIONS.add(48
/* HasBlock */
, (op, [, block]) => {
expr(op, block);
op(25
/* HasBlock */
);
});
EXPRESSIONS.add(49
/* HasBlockParams */
, (op, [, block]) => {
expr(op, block);
op(24
/* SpreadBlock */
);
op(61
/* CompileBlock */
);
op(26
/* HasBlockParams */
);
});
EXPRESSIONS.add(52
/* IfInline */
, (op, [, condition, truthy, falsy]) => {
// Push in reverse order
expr(op, falsy);
expr(op, truthy);
expr(op, condition);
op(109
/* IfInline */
);
});
EXPRESSIONS.add(51
/* Not */
, (op, [, value]) => {
expr(op, value);
op(110
/* Not */
);
});
EXPRESSIONS.add(53
/* GetDynamicVar */
, (op, [, expression]) => {
expr(op, expression);
op(111
/* GetDynamicVar */
);
});
EXPRESSIONS.add(54
/* Log */
, (op, [, positional]) => {
op(0
/* PushFrame */
);
SimpleArgs(op, positional, null, false);
op(112
/* Log */
);
op(1
/* PopFrame */
);
op(36
/* Fetch */
, _vm.$v0);
});
function expr(op, expression) {
if (Array.isArray(expression)) {
EXPRESSIONS.compile(op, expression);
} else {
PushPrimitive(op, expression);
op(31
/* PrimitiveReference */
);
}
}
/**
* Compile arguments, pushing an Arguments object onto the stack.
*
* @param args.params
* @param args.hash
* @param args.blocks
* @param args.atNames
*/
function CompileArgs(op, positional, named, blocks, atNames) {
var blockNames = blocks.names;
for (var i = 0; i < blockNames.length; i++) {
PushYieldableBlock(op, blocks.get(blockNames[i]));
}
var count = CompilePositional(op, positional);
var flags = count << 4;
if (atNames) flags |= 0b1000;
if (blocks) {
flags |= 0b111;
}
var names = _util.EMPTY_ARRAY;
if (named) {
names = named[0];
var val = named[1];
for (var _i = 0; _i < val.length; _i++) {
expr(op, val[_i]);
}
}
op(82
/* PushArgs */
, names, blockNames, flags);
}
function SimpleArgs(op, positional, named, atNames) {
if (positional === null && named === null) {
op(83
/* PushEmptyArgs */
);
return;
}
var count = CompilePositional(op, positional);
var flags = count << 4;
if (atNames) flags |= 0b1000;
var names = _util.EMPTY_STRING_ARRAY;
if (named) {
names = named[0];
var val = named[1];
for (var i = 0; i < val.length; i++) {
expr(op, val[i]);
}
}
op(82
/* PushArgs */
, names, _util.EMPTY_STRING_ARRAY, flags);
}
/**
* Compile an optional list of positional arguments, which pushes each argument
* onto the stack and returns the number of parameters compiled
*
* @param positional an optional list of positional arguments
*/
function CompilePositional(op, positional) {
if (positional === null) return 0;
for (var i = 0; i < positional.length; i++) {
expr(op, positional[i]);
}
return positional.length;
}
function meta(layout) {
var _a, _b;
var [, symbols,, upvars] = layout.block;
return {
evalSymbols: evalSymbols(layout),
upvars: upvars,
scopeValues: (_b = (_a = layout.scope) === null || _a === void 0 ? void 0 : _a.call(layout)) !== null && _b !== void 0 ? _b : null,
isStrictMode: layout.isStrictMode,
moduleName: layout.moduleName,
owner: layout.owner,
size: symbols.length
};
}
function evalSymbols(layout) {
var {
block
} = layout;
var [, symbols, hasEval] = block;
return hasEval ? symbols : null;
}
/**
* Push a reference onto the stack corresponding to a statically known primitive
* @param value A JavaScript primitive (undefined, null, boolean, number or string)
*/
function PushPrimitiveReference(op, value) {
PushPrimitive(op, value);
op(31
/* PrimitiveReference */
);
}
/**
* Push an encoded representation of a JavaScript primitive on the stack
*
* @param value A JavaScript primitive (undefined, null, boolean, number or string)
*/
function PushPrimitive(op, primitive) {
var p = primitive;
if (typeof p === 'number') {
p = (0, _util.isSmallInt)(p) ? (0, _util.encodeImmediate)(p) : nonSmallIntOperand(p);
}
op(30
/* Primitive */
, p);
}
/**
* Invoke a foreign function (a "helper") based on a statically known handle
*
* @param op The op creation function
* @param handle A handle
* @param positional An optional list of expressions to compile
* @param named An optional list of named arguments (name + expression) to compile
*/
function Call(op, handle, positional, named) {
op(0
/* PushFrame */
);
SimpleArgs(op, positional, named, false);
op(16
/* Helper */
, handle);
op(1
/* PopFrame */
);
op(36
/* Fetch */
, _vm.$v0);
}
/**
* Invoke a foreign function (a "helper") based on a dynamically loaded definition
*
* @param op The op creation function
* @param positional An optional list of expressions to compile
* @param named An optional list of named arguments (name + expression) to compile
*/
function CallDynamic(op, positional, named, append) {
op(0
/* PushFrame */
);
SimpleArgs(op, positional, named, false);
op(33
/* Dup */
, _vm.$fp, 1);
op(107
/* DynamicHelper */
);
if (append) {
op(36
/* Fetch */
, _vm.$v0);
append();
op(1
/* PopFrame */
);
op(34
/* Pop */
, 1);
} else {
op(1
/* PopFrame */
);
op(34
/* Pop */
, 1);
op(36
/* Fetch */
, _vm.$v0);
}
}
/**
* Evaluate statements in the context of new dynamic scope entries. Move entries from the
* stack into named entries in the dynamic scope, then evaluate the statements, then pop
* the dynamic scope
*
* @param names a list of dynamic scope names
* @param block a function that returns a list of statements to evaluate
*/
function DynamicScope(op, names, block) {
op(59
/* PushDynamicScope */
);
op(58
/* BindDynamicScope */
, names);
block();
op(60
/* PopDynamicScope */
);
}
function Curry(op, type, definition, positional, named) {
op(0
/* PushFrame */
);
SimpleArgs(op, positional, named, false);
op(86
/* CaptureArgs */
);
expr(op, definition);
op(77
/* Curry */
, type, isStrictMode());
op(1
/* PopFrame */
);
op(36
/* Fetch */
, _vm.$v0);
}
/**
* Yield to a block located at a particular symbol location.
*
* @param to the symbol containing the block to yield to
* @param params optional block parameters to yield to the block
*/
function YieldBlock(op, to, positional) {
SimpleArgs(op, positional, null, true);
op(23
/* GetBlock */
, to);
op(24
/* SpreadBlock */
);
op(61
/* CompileBlock */
);
op(64
/* InvokeYield */
);
op(40
/* PopScope */
);
op(1
/* PopFrame */
);
}
/**
* Push an (optional) yieldable block onto the stack. The yieldable block must be known
* statically at compile time.
*
* @param block An optional Compilable block
*/
function PushYieldableBlock(op, block) {
PushSymbolTable(op, block && block[1]);
op(62
/* PushBlockScope */
);
PushCompilable(op, block);
}
/**
* Invoke a block that is known statically at compile time.
*
* @param block a Compilable block
*/
function InvokeStaticBlock(op, block) {
op(0
/* PushFrame */
);
PushCompilable(op, block);
op(61
/* CompileBlock */
);
op(2
/* InvokeVirtual */
);
op(1
/* PopFrame */
);
}
/**
* Invoke a static block, preserving some number of stack entries for use in
* updating.
*
* @param block A compilable block
* @param callerCount A number of stack entries to preserve
*/
function InvokeStaticBlockWithStack(op, block, callerCount) {
var parameters = block[1];
var calleeCount = parameters.length;
var count = Math.min(callerCount, calleeCount);
if (count === 0) {
InvokeStaticBlock(op, block);
return;
}
op(0
/* PushFrame */
);
if (count) {
op(39
/* ChildScope */
);
for (var i = 0; i < count; i++) {
op(33
/* Dup */
, _vm.$fp, callerCount - i);
op(19
/* SetVariable */
, parameters[i]);
}
}
PushCompilable(op, block);
op(61
/* CompileBlock */
);
op(2
/* InvokeVirtual */
);
if (count) {
op(40
/* PopScope */
);
}
op(1
/* PopFrame */
);
}
function PushSymbolTable(op, parameters) {
if (parameters !== null) {
op(63
/* PushSymbolTable */
, symbolTableOperand({
parameters
}));
} else {
PushPrimitive(op, null);
}
}
function PushCompilable(op, _block) {
if (_block === null) {
PushPrimitive(op, null);
} else {
op(28
/* Constant */
, blockOperand(_block));
}
}
function SwitchCases(op, bootstrap, callback) {
// Setup the switch DSL
var clauses = [];
var count = 0;
function when(match, callback) {
clauses.push({
match,
callback,
label: `CLAUSE${count++}`
});
} // Call the callback
callback(when); // Emit the opcodes for the switch
op(69
/* Enter */
, 1);
bootstrap();
op(1001
/* StartLabels */
); // First, emit the jump opcodes. We don't need a jump for the last
// opcode, since it bleeds directly into its clause.
for (var clause of clauses.slice(0, -1)) {
op(67
/* JumpEq */
, labelOperand(clause.label), clause.match);
} // Enumerate the clauses in reverse order. Earlier matches will
// require fewer checks.
for (var i = clauses.length - 1; i >= 0; i--) {
var _clause = clauses[i];
op(1000
/* Label */
, _clause.label);
op(34
/* Pop */
, 1);
_clause.callback(); // The first match is special: it is placed directly before the END
// label, so no additional jump is needed at the end of it.
if (i !== 0) {
op(4
/* Jump */
, labelOperand('END'));
}
}
op(1000
/* Label */
, 'END');
op(1002
/* StopLabels */
);
op(70
/* Exit */
);
}
/**
* A convenience for pushing some arguments on the stack and
* running some code if the code needs to be re-executed during
* updating execution if some of the arguments have changed.
*
* # Initial Execution
*
* The `args` function should push zero or more arguments onto
* the stack and return the number of arguments pushed.
*
* The `body` function provides the instructions to execute both
* during initial execution and during updating execution.
*
* Internally, this function starts by pushing a new frame, so
* that the body can return and sets the return point ($ra) to
* the ENDINITIAL label.
*
* It then executes the `args` function, which adds instructions
* responsible for pushing the arguments for the block to the
* stack. These arguments will be restored to the stack before
* updating execution.
*
* Next, it adds the Enter opcode, which marks the current position
* in the DOM, and remembers the current $pc (the next instruction)
* as the first instruction to execute during updating execution.
*
* Next, it runs `body`, which adds the opcodes that should
* execute both during initial execution and during updating execution.
* If the `body` wishes to finish early, it should Jump to the
* `FINALLY` label.
*
* Next, it adds the FINALLY label, followed by:
*
* - the Exit opcode, which finalizes the marked DOM started by the
* Enter opcode.
* - the Return opcode, which returns to the current return point
* ($ra).
*
* Finally, it adds the ENDINITIAL label followed by the PopFrame
* instruction, which restores $fp, $sp and $ra.
*
* # Updating Execution
*
* Updating execution for this `replayable` occurs if the `body` added an
* assertion, via one of the `JumpIf`, `JumpUnless` or `AssertSame` opcodes.
*
* If, during updating executon, the assertion fails, the initial VM is
* restored, and the stored arguments are pushed onto the stack. The DOM
* between the starting and ending markers is cleared, and the VM's cursor
* is set to the area just cleared.
*
* The return point ($ra) is set to -1, the exit instruction.
*
* Finally, the $pc is set to to the instruction saved off by the
* Enter opcode during initial execution, and execution proceeds as
* usual.
*
* The only difference is that when a `Return` instruction is
* encountered, the program jumps to -1 rather than the END label,
* and the PopFrame opcode is not needed.
*/
function Replayable(op, args, body) {
// Start a new label frame, to give END and RETURN
// a unique meaning.
op(1001
/* StartLabels */
);
op(0
/* PushFrame */
); // If the body invokes a block, its return will return to
// END. Otherwise, the return in RETURN will return to END.
op(6
/* ReturnTo */
, labelOperand('ENDINITIAL')); // Push the arguments onto the stack. The args() function
// tells us how many stack elements to retain for re-execution
// when updating.
var count = args(); // Start a new updating closure, remembering `count` elements
// from the stack. Everything after this point, and before END,
// will execute both initially and to update the block.
//
// The enter and exit opcodes also track the area of the DOM
// associated with this block. If an assertion inside the block
// fails (for example, the test value changes from true to false
// in an #if), the DOM is cleared and the program is re-executed,
// restoring `count` elements to the stack and executing the
// instructions between the enter and exit.
op(69
/* Enter */
, count); // Evaluate the body of the block. The body of the block may
// return, which will jump execution to END during initial
// execution, and exit the updating routine.
body(); // All execution paths in the body should run the FINALLY once
// they are done. It is executed both during initial execution
// and during updating execution.
op(1000
/* Label */
, 'FINALLY'); // Finalize the DOM.
op(70
/* Exit */
); // In initial execution, this is a noop: it returns to the
// immediately following opcode. In updating execution, this
// exits the updating routine.
op(5
/* Return */
); // Cleanup code for the block. Runs on initial execution
// but not on updating.
op(1000
/* Label */
, 'ENDINITIAL');
op(1
/* PopFrame */
);
op(1002
/* StopLabels */
);
}
/**
* A specialized version of the `replayable` convenience that allows the
* caller to provide different code based upon whether the item at
* the top of the stack is true or false.
*
* As in `replayable`, the `ifTrue` and `ifFalse` code can invoke `return`.
*
* During the initial execution, a `return` will continue execution
* in the cleanup code, which finalizes the current DOM block and pops
* the current frame.
*
* During the updating execution, a `return` will exit the updating
* routine, as it can reuse the DOM block and is always only a single
* frame deep.
*/
function ReplayableIf(op, args, ifTrue, ifFalse) {
return Replayable(op, args, () => {
// If the conditional is false, jump to the ELSE label.
op(66
/* JumpUnless */
, labelOperand('ELSE')); // Otherwise, execute the code associated with the true branch.
ifTrue(); // We're done, so return. In the initial execution, this runs
// the cleanup code. In the updating VM, it exits the updating
// routine.
op(4
/* Jump */
, labelOperand('FINALLY'));
op(1000
/* Label */
, 'ELSE'); // If the conditional is false, and code associatied ith the
// false branch was provided, execute it. If there was no code
// associated with the false branch, jumping to the else statement
// has no other behavior.
if (ifFalse !== undefined) {
ifFalse();
}
});
}
var ATTRS_BLOCK = '&attrs';
function InvokeComponent(op, component, _elementBlock, positional, named, _blocks) {
var {
compilable,
capabilities,
handle
} = component;
var elementBlock = _elementBlock ? [_elementBlock, []] : null;
var blocks = Array.isArray(_blocks) || _blocks === null ? namedBlocks(_blocks) : _blocks;
if (compilable) {
op(78
/* PushComponentDefinition */
, handle);
InvokeStaticComponent(op, {
capabilities: capabilities,
layout: compilable,
elementBlock,
positional,
named,
blocks
});
} else {
op(78
/* PushComponentDefinition */
, handle);
InvokeNonStaticComponent(op, {
capabilities: capabilities,
elementBlock,
positional,
named,
atNames: true,
blocks
});
}
}
function InvokeDynamicComponent(op, definition, _elementBlock, positional, named, _blocks, atNames, curried) {
var elementBlock = _elementBlock ? [_elementBlock, []] : null;
var blocks = Array.isArray(_blocks) || _blocks === null ? namedBlocks(_blocks) : _blocks;
Replayable(op, () => {
expr(op, definition);
op(33
/* Dup */
, _vm.$sp, 0);
return 2;
}, () => {
op(66
/* JumpUnless */
, labelOperand('ELSE'));
if (curried) {
op(81
/* ResolveCurriedComponent */
);
} else {
op(80
/* ResolveDynamicComponent */
, isStrictMode());
}
op(79
/* PushDynamicComponentInstance */
);
InvokeNonStaticComponent(op, {
capabilities: true,
elementBlock,
positional,
named,
atNames,
blocks
});
op(1000
/* Label */
, 'ELSE');
});
}
function InvokeStaticComponent(op, {
capabilities,
layout,
elementBlock,
positional,
named,
blocks
}) {
var {
symbolTable
} = layout;
var bailOut = symbolTable.hasEval || (0, _manager.hasCapability)(capabilities, 4
/* PrepareArgs */
);
if (bailOut) {
InvokeNonStaticComponent(op, {
capabilities,
elementBlock,
positional,
named,
atNames: true,
blocks,
layout
});
return;
}
op(36
/* Fetch */
, _vm.$s0);
op(33
/* Dup */
, _vm.$sp, 1);
op(35
/* Load */
, _vm.$s0);
op(0
/* PushFrame */
); // Setup arguments
var {
symbols
} = symbolTable; // As we push values onto the stack, we store the symbols associated with them
// so that we can set them on the scope later on with SetVariable and SetBlock
var blockSymbols = [];
var argSymbols = [];
var argNames = []; // First we push the blocks onto the stack
var blockNames = blocks.names; // Starting with the attrs block, if it exists and is referenced in the component
if (elementBlock !== null) {
var symbol = symbols.indexOf(ATTRS_BLOCK);
if (symbol !== -1) {
PushYieldableBlock(op, elementBlock);
blockSymbols.push(symbol);
}
} // Followed by the other blocks, if they exist and are referenced in the component.
// Also store the index of the associated symbol.
for (var i = 0; i < blockNames.length; i++) {
var name = blockNames[i];
var _symbol = symbols.indexOf(`&${name}`);
if (_symbol !== -1) {
PushYieldableBlock(op, blocks.get(name));
blockSymbols.push(_symbol);
}
} // Next up we have arguments. If the component has the `createArgs` capability,
// then it wants access to the arguments in JavaScript. We can't know whether
// or not an argument is used, so we have to give access to all of them.
if ((0, _manager.hasCapability)(capabilities, 8
/* CreateArgs */
)) {
// First we push positional arguments
var count = CompilePositional(op, positional); // setup the flags with the count of positionals, and to indicate that atNames
// are used
var flags = count << 4;
flags |= 0b1000;
var names = _util.EMPTY_STRING_ARRAY; // Next, if named args exist, push them all. If they have an associated symbol
// in the invoked component (e.g. they are used within its template), we push
// that symbol. If not, we still push the expression as it may be used, and
// we store the symbol as -1 (this is used later).
if (named !== null) {
names = named[0];
var val = named[1];
for (var _i2 = 0; _i2 < val.length; _i2++) {
var _symbol2 = symbols.indexOf(names[_i2]);
expr(op, val[_i2]);
argSymbols.push(_symbol2);
}
} // Finally, push the VM arguments themselves. These args won't need access
// to blocks (they aren't accessible from userland anyways), so we push an
// empty array instead of the actual block names.
op(82
/* PushArgs */
, names, _util.EMPTY_STRING_ARRAY, flags); // And push an extra pop operation to remove the args before we begin setting
// variables on the local context
argSymbols.push(-1);
} else if (named !== null) {
// If the component does not have the `createArgs` capability, then the only
// expressions we need to push onto the stack are those that are actually
// referenced in the template of the invoked component (e.g. have symbols).
var _names = named[0];
var _val = named[1];
for (var _i3 = 0; _i3 < _val.length; _i3++) {
var _name3 = _names[_i3];
var _symbol3 = symbols.indexOf(_name3);
if (_symbol3 !== -1) {
expr(op, _val[_i3]);
argSymbols.push(_symbol3);
argNames.push(_name3);
}
}
}
op(97
/* BeginComponentTransaction */
, _vm.$s0);
if ((0, _manager.hasCapability)(capabilities, 64
/* DynamicScope */
)) {
op(59
/* PushDynamicScope */
);
}
if ((0, _manager.hasCapability)(capabilities, 512
/* CreateInstance */
)) {
op(87
/* CreateComponent */
, blocks.has('default') | 0, _vm.$s0);
}
op(88
/* RegisterComponentDestructor */
, _vm.$s0);
if ((0, _manager.hasCapability)(capabilities, 8
/* CreateArgs */
)) {
op(90
/* GetComponentSelf */
, _vm.$s0);
} else {
op(90
/* GetComponentSelf */
, _vm.$s0, argNames);
} // Setup the new root scope for the component
op(37
/* RootScope */
, symbols.length + 1, Object.keys(blocks).length > 0 ? 1 : 0); // Pop the self reference off the stack and set it to the symbol for `this`
// in the new scope. This is why all subsequent symbols are increased by one.
op(19
/* SetVariable */
, 0); // Going in reverse, now we pop the args/blocks off the stack, starting with
// arguments, and assign them to their symbols in the new scope.
for (var _i4 = argSymbols.length - 1; _i4 >= 0; _i4--) {
var _symbol4 = argSymbols[_i4];
if (_symbol4 === -1) {
// The expression was not bound to a local symbol, it was only pushed to be
// used with VM args in the javascript side
op(34
/* Pop */
, 1);
} else {
op(19
/* SetVariable */
, _symbol4 + 1);
}
} // if any positional params exist, pop them off the stack as well
if (positional !== null) {
op(34
/* Pop */
, positional.length);
} // Finish up by popping off and assigning blocks
for (var _i5 = blockSymbols.length - 1; _i5 >= 0; _i5--) {
var _symbol5 = blockSymbols[_i5];
op(20
/* SetBlock */
, _symbol5 + 1);
}
op(28
/* Constant */
, layoutOperand(layout));
op(61
/* CompileBlock */
);
op(2
/* InvokeVirtual */
);
op(100
/* DidRenderLayout */
, _vm.$s0);
op(1
/* PopFrame */
);
op(40
/* PopScope */
);
if ((0, _manager.hasCapability)(capabilities, 64
/* DynamicScope */
)) {
op(60
/* PopDynamicScope */
);
}
op(98
/* CommitComponentTransaction */
);
op(35
/* Load */
, _vm.$s0);
}
function InvokeNonStaticComponent(op, {
capabilities,
elementBlock,
positional,
named,
atNames,
blocks: namedBlocks$$1,
layout
}) {
var bindableBlocks = !!namedBlocks$$1;
var bindableAtNames = capabilities === true || (0, _manager.hasCapability)(capabilities, 4
/* PrepareArgs */
) || !!(named && named[0].length !== 0);
var blocks = namedBlocks$$1.with('attrs', elementBlock);
op(36
/* Fetch */
, _vm.$s0);
op(33
/* Dup */
, _vm.$sp, 1);
op(35
/* Load */
, _vm.$s0);
op(0
/* PushFrame */
);
CompileArgs(op, positional, named, blocks, atNames);
op(85
/* PrepareArgs */
, _vm.$s0);
invokePreparedComponent(op, blocks.has('default'), bindableBlocks, bindableAtNames, () => {
if (layout) {
op(63
/* PushSymbolTable */
, symbolTableOperand(layout.symbolTable));
op(28
/* Constant */
, layoutOperand(layout));
op(61
/* CompileBlock */
);
} else {
op(92
/* GetComponentLayout */
, _vm.$s0);
}
op(95
/* PopulateLayout */
, _vm.$s0);
});
op(35
/* Load */
, _vm.$s0);
}
function WrappedComponent(op, layout, attrsBlockNumber) {
op(1001
/* StartLabels */
);
WithSavedRegister(op, _vm.$s1, () => {
op(91
/* GetComponentTagName */
, _vm.$s0);
op(31
/* PrimitiveReference */
);
op(33
/* Dup */
, _vm.$sp, 0);
});
op(66
/* JumpUnless */
, labelOperand('BODY'));
op(36
/* Fetch */
, _vm.$s1);
op(89
/* PutComponentOperations */
);
op(49
/* OpenDynamicElement */
);
op(99
/* DidCreateElement */
, _vm.$s0);
YieldBlock(op, attrsBlockNumber, null);
op(54
/* FlushElement */
);
op(1000
/* Label */
, 'BODY');
InvokeStaticBlock(op, [layout.block[0], []]);
op(36
/* Fetch */
, _vm.$s1);
op(66
/* JumpUnless */
, labelOperand('END'));
op(55
/* CloseElement */
);
op(1000
/* Label */
, 'END');
op(35
/* Load */
, _vm.$s1);
op(1002
/* StopLabels */
);
}
function invokePreparedComponent(op, hasBlock, bindableBlocks, bindableAtNames, populateLayout = null) {
op(97
/* BeginComponentTransaction */
, _vm.$s0);
op(59
/* PushDynamicScope */
);
op(87
/* CreateComponent */
, hasBlock | 0, _vm.$s0); // this has to run after createComponent to allow
// for late-bound layouts, but a caller is free
// to populate the layout earlier if it wants to
// and do nothing here.
if (populateLayout) {
populateLayout();
}
op(88
/* RegisterComponentDestructor */
, _vm.$s0);
op(90
/* GetComponentSelf */
, _vm.$s0);
op(38
/* VirtualRootScope */
, _vm.$s0);
op(19
/* SetVariable */
, 0);
op(94
/* SetupForEval */
, _vm.$s0);
if (bindableAtNames) op(17
/* SetNamedVariables */
, _vm.$s0);
if (bindableBlocks) op(18
/* SetBlocks */
, _vm.$s0);
op(34
/* Pop */
, 1);
op(96
/* InvokeComponentLayout */
, _vm.$s0);
op(100
/* DidRenderLayout */
, _vm.$s0);
op(1
/* PopFrame */
);
op(40
/* PopScope */
);
op(60
/* PopDynamicScope */
);
op(98
/* CommitComponentTransaction */
);
}
function InvokeBareComponent(op) {
op(36
/* Fetch */
, _vm.$s0);
op(33
/* Dup */
, _vm.$sp, 1);
op(35
/* Load */
, _vm.$s0);
op(0
/* PushFrame */
);
op(83
/* PushEmptyArgs */
);
op(85
/* PrepareArgs */
, _vm.$s0);
invokePreparedComponent(op, false, false, true, () => {
op(92
/* GetComponentLayout */
, _vm.$s0);
op(95
/* PopulateLayout */
, _vm.$s0);
});
op(35
/* Load */
, _vm.$s0);
}
function WithSavedRegister(op, register, block) {
op(36
/* Fetch */
, register);
block();
op(35
/* Load */
, register);
}
class StdLib {
constructor(main, trustingGuardedAppend, cautiousGuardedAppend, trustingNonDynamicAppend, cautiousNonDynamicAppend) {
this.main = main;
this.trustingGuardedAppend = trustingGuardedAppend;
this.cautiousGuardedAppend = cautiousGuardedAppend;
this.trustingNonDynamicAppend = trustingNonDynamicAppend;
this.cautiousNonDynamicAppend = cautiousNonDynamicAppend;
}
get 'trusting-append'() {
return this.trustingGuardedAppend;
}
get 'cautious-append'() {
return this.cautiousGuardedAppend;
}
get 'trusting-non-dynamic-append'() {
return this.trustingNonDynamicAppend;
}
get 'cautious-non-dynamic-append'() {
return this.cautiousNonDynamicAppend;
}
getAppend(trusting) {
return trusting ? this.trustingGuardedAppend : this.cautiousGuardedAppend;
}
}
_exports.StdLib = StdLib;
function programCompilationContext(artifacts, resolver) {
return new CompileTimeCompilationContextImpl(artifacts, resolver);
}
function templateCompilationContext(program, meta) {
var encoder = new EncoderImpl(program.heap, meta, program.stdlib);
return {
program,
encoder,
meta
};
}
var debugCompiler;
_exports.debugCompiler = debugCompiler;
var STATEMENTS = new Compilers();
var INFLATE_ATTR_TABLE = ['class', 'id', 'value', 'name', 'type', 'style', 'href'];
var INFLATE_TAG_TABLE = ['div', 'span', 'p', 'a'];
function inflateTagName(tagName) {
return typeof tagName === 'string' ? tagName : INFLATE_TAG_TABLE[tagName];
}
function inflateAttrName(attrName) {
return typeof attrName === 'string' ? attrName : INFLATE_ATTR_TABLE[attrName];
}
STATEMENTS.add(3
/* Comment */
, (op, sexp) => op(42
/* Comment */
, sexp[1]));
STATEMENTS.add(13
/* CloseElement */
, op => op(55
/* CloseElement */
));
STATEMENTS.add(12
/* FlushElement */
, op => op(54
/* FlushElement */
));
STATEMENTS.add(4
/* Modifier */
, (op, [, expression, positional, named]) => {
if (isGetFreeModifier(expression)) {
op(1003
/* ResolveModifier */
, expression, handle => {
op(0
/* PushFrame */
);
SimpleArgs(op, positional, named, false);
op(57
/* Modifier */
, handle);
op(1
/* PopFrame */
);
});
} else {
expr(op, expression);
op(0
/* PushFrame */
);
SimpleArgs(op, positional, named, false);
op(33
/* Dup */
, _vm.$fp, 1);
op(108
/* DynamicModifier */
);
op(1
/* PopFrame */
);
}
});
STATEMENTS.add(14
/* StaticAttr */
, (op, [, name, value, namespace]) => {
op(51
/* StaticAttr */
, inflateAttrName(name), value, namespace !== null && namespace !== void 0 ? namespace : null);
});
STATEMENTS.add(24
/* StaticComponentAttr */
, (op, [, name, value, namespace]) => {
op(105
/* StaticComponentAttr */
, inflateAttrName(name), value, namespace !== null && namespace !== void 0 ? namespace : null);
});
STATEMENTS.add(15
/* DynamicAttr */
, (op, [, name, value, namespace]) => {
expr(op, value);
op(52
/* DynamicAttr */
, inflateAttrName(name), false, namespace !== null && namespace !== void 0 ? namespace : null);
});
STATEMENTS.add(22
/* TrustingDynamicAttr */
, (op, [, name, value, namespace]) => {
expr(op, value);
op(52
/* DynamicAttr */
, inflateAttrName(name), true, namespace !== null && namespace !== void 0 ? namespace : null);
});
STATEMENTS.add(16
/* ComponentAttr */
, (op, [, name, value, namespace]) => {
expr(op, value);
op(53
/* ComponentAttr */
, inflateAttrName(name), false, namespace !== null && namespace !== void 0 ? namespace : null);
});
STATEMENTS.add(23
/* TrustingComponentAttr */
, (op, [, name, value, namespace]) => {
expr(op, value);
op(53
/* ComponentAttr */
, inflateAttrName(name), true, namespace !== null && namespace !== void 0 ? namespace : null);
});
STATEMENTS.add(10
/* OpenElement */
, (op, [, tag]) => {
op(48
/* OpenElement */
, inflateTagName(tag));
});
STATEMENTS.add(11
/* OpenElementWithSplat */
, (op, [, tag]) => {
op(89
/* PutComponentOperations */
);
op(48
/* OpenElement */
, inflateTagName(tag));
});
STATEMENTS.add(8
/* Component */
, (op, [, expr$$1, elementBlock, named, blocks]) => {
if (isGetFreeComponent(expr$$1)) {
op(1004
/* ResolveComponent */
, expr$$1, component => {
InvokeComponent(op, component, elementBlock, null, named, blocks);
});
} else {
// otherwise, the component name was an expression, so resolve the expression
// and invoke it as a dynamic component
InvokeDynamicComponent(op, expr$$1, elementBlock, null, named, blocks, true, true);
}
});
STATEMENTS.add(18
/* Yield */
, (op, [, to, params]) => YieldBlock(op, to, params));
STATEMENTS.add(17
/* AttrSplat */
, (op, [, to]) => YieldBlock(op, to, null));
STATEMENTS.add(26
/* Debugger */
, (op, [, evalInfo]) => op(103
/* Debugger */
, evalSymbolsOperand(), evalInfo));
STATEMENTS.add(1
/* Append */
, (op, [, value]) => {
// Special case for static values
if (!Array.isArray(value)) {
op(41
/* Text */
, value === null || value === undefined ? '' : String(value));
} else if (isGetFreeOptionalComponentOrHelper(value)) {
op(1008
/* ResolveOptionalComponentOrHelper */
, value, {
ifComponent(component) {
InvokeComponent(op, component, null, null, null, null);
},
ifHelper(handle) {
op(0
/* PushFrame */
);
Call(op, handle, null, null);
op(3
/* InvokeStatic */
, stdlibOperand('cautious-non-dynamic-append'));
op(1
/* PopFrame */
);
},
ifValue(handle) {
op(0
/* PushFrame */
);
op(29
/* ConstantReference */
, handle);
op(3
/* InvokeStatic */
, stdlibOperand('cautious-non-dynamic-append'));
op(1
/* PopFrame */
);
}
});
} else if (value[0] === 28
/* Call */
) {
var [, expression, positional, named] = value;
if (isGetFreeComponentOrHelper(expression)) {
op(1007
/* ResolveComponentOrHelper */
, expression, {
ifComponent(component) {
InvokeComponent(op, component, null, positional, hashToArgs(named), null);
},
ifHelper(handle) {
op(0
/* PushFrame */
);
Call(op, handle, positional, named);
op(3
/* InvokeStatic */
, stdlibOperand('cautious-non-dynamic-append'));
op(1
/* PopFrame */
);
}
});
} else {
SwitchCases(op, () => {
expr(op, expression);
op(106
/* DynamicContentType */
);
}, when => {
when(0
/* Component */
, () => {
op(81
/* ResolveCurriedComponent */
);
op(79
/* PushDynamicComponentInstance */
);
InvokeNonStaticComponent(op, {
capabilities: true,
elementBlock: null,
positional,
named,
atNames: false,
blocks: namedBlocks(null)
});
});
when(1
/* Helper */
, () => {
CallDynamic(op, positional, named, () => {
op(3
/* InvokeStatic */
, stdlibOperand('cautious-non-dynamic-append'));
});
});
});
}
} else {
op(0
/* PushFrame */
);
expr(op, value);
op(3
/* InvokeStatic */
, stdlibOperand('cautious-append'));
op(1
/* PopFrame */
);
}
});
STATEMENTS.add(2
/* TrustingAppend */
, (op, [, value]) => {
if (!Array.isArray(value)) {
op(41
/* Text */
, value === null || value === undefined ? '' : String(value));
} else {
op(0
/* PushFrame */
);
expr(op, value);
op(3
/* InvokeStatic */
, stdlibOperand('trusting-append'));
op(1
/* PopFrame */
);
}
});
STATEMENTS.add(6
/* Block */
, (op, [, expr$$1, positional, named, blocks]) => {
if (isGetFreeComponent(expr$$1)) {
op(1004
/* ResolveComponent */
, expr$$1, component => {
InvokeComponent(op, component, null, positional, hashToArgs(named), blocks);
});
} else {
InvokeDynamicComponent(op, expr$$1, null, positional, named, blocks, false, false);
}
});
STATEMENTS.add(40
/* InElement */
, (op, [, block, guid, destination, insertBefore]) => {
ReplayableIf(op, () => {
expr(op, guid);
if (insertBefore === undefined) {
PushPrimitiveReference(op, undefined);
} else {
expr(op, insertBefore);
}
expr(op, destination);
op(33
/* Dup */
, _vm.$sp, 0);
return 4;
}, () => {
op(50
/* PushRemoteElement */
);
InvokeStaticBlock(op, block);
op(56
/* PopRemoteElement */
);
});
});
STATEMENTS.add(41
/* If */
, (op, [, condition, block, inverse]) => ReplayableIf(op, () => {
expr(op, condition);
op(71
/* ToBoolean */
);
return 1;
}, () => {
InvokeStaticBlock(op, block);
}, inverse ? () => {
InvokeStaticBlock(op, inverse);
} : undefined));
STATEMENTS.add(42
/* Each */
, (op, [, value, key, block, inverse]) => Replayable(op, () => {
if (key) {
expr(op, key);
} else {
PushPrimitiveReference(op, null);
}
expr(op, value);
return 2;
}, () => {
op(72
/* EnterList */
, labelOperand('BODY'), labelOperand('ELSE'));
op(0
/* PushFrame */
);
op(33
/* Dup */
, _vm.$fp, 1);
op(6
/* ReturnTo */
, labelOperand('ITER'));
op(1000
/* Label */
, 'ITER');
op(74
/* Iterate */
, labelOperand('BREAK'));
op(1000
/* Label */
, 'BODY');
InvokeStaticBlockWithStack(op, block, 2);
op(34
/* Pop */
, 2);
op(4
/* Jump */
, labelOperand('FINALLY'));
op(1000
/* Label */
, 'BREAK');
op(1
/* PopFrame */
);
op(73
/* ExitList */
);
op(4
/* Jump */
, labelOperand('FINALLY'));
op(1000
/* Label */
, 'ELSE');
if (inverse) {
InvokeStaticBlock(op, inverse);
}
}));
STATEMENTS.add(43
/* With */
, (op, [, value, block, inverse]) => {
ReplayableIf(op, () => {
expr(op, value);
op(33
/* Dup */
, _vm.$sp, 0);
op(71
/* ToBoolean */
);
return 2;
}, () => {
InvokeStaticBlockWithStack(op, block, 1);
}, () => {
if (inverse) {
InvokeStaticBlock(op, inverse);
}
});
});
STATEMENTS.add(44
/* Let */
, (op, [, positional, block]) => {
var count = CompilePositional(op, positional);
InvokeStaticBlockWithStack(op, block, count);
});
STATEMENTS.add(45
/* WithDynamicVars */
, (op, [, named, block]) => {
if (named) {
var [names, expressions] = named;
CompilePositional(op, expressions);
DynamicScope(op, names, () => {
InvokeStaticBlock(op, block);
});
} else {
InvokeStaticBlock(op, block);
}
});
STATEMENTS.add(46
/* InvokeComponent */
, (op, [, expr$$1, positional, named, blocks]) => {
if (isGetFreeComponent(expr$$1)) {
op(1004
/* ResolveComponent */
, expr$$1, component => {
InvokeComponent(op, component, null, positional, hashToArgs(named), blocks);
});
} else {
InvokeDynamicComponent(op, expr$$1, null, positional, named, blocks, false, false);
}
});
function hashToArgs(hash) {
if (hash === null) return null;
var names = hash[0].map(key => `@${key}`);
return [names, hash[1]];
}
var PLACEHOLDER_HANDLE = -1;
class CompilableTemplateImpl {
constructor(statements, meta$$1, // Part of CompilableTemplate
symbolTable, // Used for debugging
moduleName = 'plain block') {
this.statements = statements;
this.meta = meta$$1;
this.symbolTable = symbolTable;
this.moduleName = moduleName;
this.compiled = null;
} // Part of CompilableTemplate
compile(context) {
return maybeCompile(this, context);
}
}
function compilable(layout, moduleName) {
var [statements, symbols, hasEval] = layout.block;
return new CompilableTemplateImpl(statements, meta(layout), {
symbols,
hasEval
}, moduleName);
}
function maybeCompile(compilable, context) {
if (compilable.compiled !== null) return compilable.compiled;
compilable.compiled = PLACEHOLDER_HANDLE;
var {
statements,
meta: meta$$1
} = compilable;
var result = compileStatements(statements, meta$$1, context);
compilable.compiled = result;
return result;
}
function compileStatements(statements, meta$$1, syntaxContext) {
var sCompiler = STATEMENTS;
var context = templateCompilationContext(syntaxContext, meta$$1);
var {
encoder,
program: {
constants,
resolver
}
} = context;
function pushOp(...op) {
encodeOp(encoder, constants, resolver, meta$$1, op);
}
for (var i = 0; i < statements.length; i++) {
sCompiler.compile(pushOp, statements[i]);
}
var handle = context.encoder.commit(meta$$1.size);
return handle;
}
function compilableBlock(block, containing) {
return new CompilableTemplateImpl(block[0], containing, {
parameters: block[1] || _util.EMPTY_ARRAY
});
}
class Labels {
constructor() {
this.labels = (0, _util.dict)();
this.targets = [];
}
label(name, index) {
this.labels[name] = index;
}
target(at, target) {
this.targets.push({
at,
target
});
}
patch(heap) {
var {
targets,
labels
} = this;
for (var i = 0; i < targets.length; i++) {
var {
at,
target
} = targets[i];
var address = labels[target] - at;
heap.setbyaddr(at, address);
}
}
}
function encodeOp(encoder, constants, resolver, meta, op) {
if (isBuilderOpcode(op[0])) {
var [type, ...operands] = op;
encoder.push(constants, type, ...operands);
} else {
switch (op[0]) {
case 1000
/* Label */
:
return encoder.label(op[1]);
case 1001
/* StartLabels */
:
return encoder.startLabels();
case 1002
/* StopLabels */
:
return encoder.stopLabels();
case 1004
/* ResolveComponent */
:
return resolveComponent(resolver, constants, meta, op);
case 1003
/* ResolveModifier */
:
return resolveModifier(resolver, constants, meta, op);
case 1005
/* ResolveHelper */
:
return resolveHelper(resolver, constants, meta, op);
case 1007
/* ResolveComponentOrHelper */
:
return resolveComponentOrHelper(resolver, constants, meta, op);
case 1006
/* ResolveOptionalHelper */
:
return resolveOptionalHelper(resolver, constants, meta, op);
case 1008
/* ResolveOptionalComponentOrHelper */
:
return resolveOptionalComponentOrHelper(resolver, constants, meta, op);
case 1010
/* ResolveLocal */
:
var freeVar = op[1];
var name = meta.upvars[freeVar];
var andThen = op[2];
andThen(name, meta.moduleName);
break;
case 1011
/* ResolveTemplateLocal */
:
var [, valueIndex, then] = op;
var value = meta.scopeValues[valueIndex];
then(constants.value(value));
break;
case 1009
/* ResolveFree */
:
if (true
/* DEBUG */
) {
var [, upvarIndex] = op;
var freeName = meta.upvars[upvarIndex];
throw new Error(`Attempted to resolve a value in a strict mode template, but that value was not in scope: ${freeName}`);
}
break;
default:
throw new Error(`Unexpected high level opcode ${op[0]}`);
}
}
}
class EncoderImpl {
constructor(heap, meta, stdlib) {
this.heap = heap;
this.meta = meta;
this.stdlib = stdlib;
this.labelsStack = new _util.Stack();
this.encoder = new _encoder.InstructionEncoderImpl([]);
this.errors = [];
this.handle = heap.malloc();
}
error(error) {
this.encoder.encode(30
/* Primitive */
, 0);
this.errors.push(error);
}
commit(size) {
var handle = this.handle;
this.heap.push(5
/* Return */
| 1024
/* MACHINE_MASK */
);
this.heap.finishMalloc(handle, size);
if (this.errors.length) {
return {
errors: this.errors,
handle
};
} else {
return handle;
}
}
push(constants, type, ...args) {
var {
heap
} = this;
if (true
/* DEBUG */
&& type > 255
/* TYPE_SIZE */
) {
throw new Error(`Opcode type over 8-bits. Got ${type}.`);
}
var machine = (0, _vm.isMachineOp)(type) ? 1024
/* MACHINE_MASK */
: 0;
var first = type | machine | args.length << 8
/* ARG_SHIFT */
;
heap.push(first);
for (var i = 0; i < args.length; i++) {
var op = args[i];
heap.push(this.operand(constants, op));
}
}
operand(constants, operand) {
if (typeof operand === 'number') {
return operand;
}
if (typeof operand === 'object' && operand !== null) {
if (Array.isArray(operand)) {
return (0, _util.encodeHandle)(constants.array(operand));
} else {
switch (operand.type) {
case 1
/* Label */
:
this.currentLabels.target(this.heap.offset, operand.value);
return -1;
case 2
/* IsStrictMode */
:
return (0, _util.encodeHandle)(constants.value(this.meta.isStrictMode));
case 3
/* EvalSymbols */
:
return (0, _util.encodeHandle)(constants.array(this.meta.evalSymbols || _util.EMPTY_STRING_ARRAY));
case 4
/* Block */
:
return (0, _util.encodeHandle)(constants.value(compilableBlock(operand.value, this.meta)));
case 5
/* StdLib */
:
return this.stdlib[operand.value];
case 6
/* NonSmallInt */
:
case 7
/* SymbolTable */
:
case 8
/* Layout */
:
return constants.value(operand.value);
}
}
}
return (0, _util.encodeHandle)(constants.value(operand));
}
get currentLabels() {
return this.labelsStack.current;
}
label(name) {
this.currentLabels.label(name, this.heap.offset + 1);
}
startLabels() {
this.labelsStack.push(new Labels());
}
stopLabels() {
var label = this.labelsStack.pop();
label.patch(this.heap);
}
}
function isBuilderOpcode(op) {
return op < 1000
/* Start */
;
}
function main(op) {
op(75
/* Main */
, _vm.$s0);
invokePreparedComponent(op, false, false, true);
}
/**
* Append content to the DOM. This standard function triages content and does the
* right thing based upon whether it's a string, safe string, component, fragment
* or node.
*
* @param trusting whether to interpolate a string as raw HTML (corresponds to
* triple curlies)
*/
function StdAppend(op, trusting, nonDynamicAppend) {
SwitchCases(op, () => op(76
/* ContentType */
), when => {
when(2
/* String */
, () => {
if (trusting) {
op(68
/* AssertSame */
);
op(43
/* AppendHTML */
);
} else {
op(47
/* AppendText */
);
}
});
if (typeof nonDynamicAppend === 'number') {
when(0
/* Component */
, () => {
op(81
/* ResolveCurriedComponent */
);
op(79
/* PushDynamicComponentInstance */
);
InvokeBareComponent(op);
});
when(1
/* Helper */
, () => {
CallDynamic(op, null, null, () => {
op(3
/* InvokeStatic */
, nonDynamicAppend);
});
});
} else {
// when non-dynamic, we can no longer call the value (potentially because we've already called it)
// this prevents infinite loops. We instead coerce the value, whatever it is, into the DOM.
when(0
/* Component */
, () => {
op(47
/* AppendText */
);
});
when(1
/* Helper */
, () => {
op(47
/* AppendText */
);
});
}
when(4
/* SafeString */
, () => {
op(68
/* AssertSame */
);
op(44
/* AppendSafeHTML */
);
});
when(5
/* Fragment */
, () => {
op(68
/* AssertSame */
);
op(45
/* AppendDocumentFragment */
);
});
when(6
/* Node */
, () => {
op(68
/* AssertSame */
);
op(46
/* AppendNode */
);
});
});
}
function compileStd(context) {
var mainHandle = build(context, op => main(op));
var trustingGuardedNonDynamicAppend = build(context, op => StdAppend(op, true, null));
var cautiousGuardedNonDynamicAppend = build(context, op => StdAppend(op, false, null));
var trustingGuardedDynamicAppend = build(context, op => StdAppend(op, true, trustingGuardedNonDynamicAppend));
var cautiousGuardedDynamicAppend = build(context, op => StdAppend(op, false, cautiousGuardedNonDynamicAppend));
return new StdLib(mainHandle, trustingGuardedDynamicAppend, cautiousGuardedDynamicAppend, trustingGuardedNonDynamicAppend, cautiousGuardedNonDynamicAppend);
}
var STDLIB_META = {
evalSymbols: null,
upvars: null,
moduleName: 'stdlib',
// TODO: ??
scopeValues: null,
isStrictMode: true,
owner: null,
size: 0
};
function build(program, callback) {
var {
constants,
heap,
resolver
} = program;
var encoder = new EncoderImpl(heap, STDLIB_META);
function pushOp(...op) {
encodeOp(encoder, constants, resolver, STDLIB_META, op);
}
callback(pushOp);
var result = encoder.commit(0);
if (typeof result !== 'number') {
// This shouldn't be possible
throw new Error(`Unexpected errors compiling std`);
} else {
return result;
}
}
class CompileTimeCompilationContextImpl {
constructor({
constants,
heap
}, resolver) {
this.resolver = resolver;
this.constants = constants;
this.heap = heap;
this.stdlib = compileStd(this);
}
}
_exports.CompileTimeCompilationContextImpl = CompileTimeCompilationContextImpl;
var DEFAULT_CAPABILITIES = {
dynamicLayout: true,
dynamicTag: true,
prepareArgs: true,
createArgs: true,
attributeHook: false,
elementHook: false,
dynamicScope: true,
createCaller: false,
updateHook: true,
createInstance: true,
wrapped: false,
willDestroy: false,
hasSubOwner: false
};
_exports.DEFAULT_CAPABILITIES = DEFAULT_CAPABILITIES;
var MINIMAL_CAPABILITIES = {
dynamicLayout: false,
dynamicTag: false,
prepareArgs: false,
createArgs: false,
attributeHook: false,
elementHook: false,
dynamicScope: false,
createCaller: false,
updateHook: false,
createInstance: false,
wrapped: false,
willDestroy: false,
hasSubOwner: false
};
_exports.MINIMAL_CAPABILITIES = MINIMAL_CAPABILITIES;
class WrappedBuilder {
constructor(layout, moduleName) {
this.layout = layout;
this.moduleName = moduleName;
this.compiled = null;
var {
block
} = layout;
var [, symbols, hasEval] = block;
symbols = symbols.slice(); // ensure ATTRS_BLOCK is always included (only once) in the list of symbols
var attrsBlockIndex = symbols.indexOf(ATTRS_BLOCK);
if (attrsBlockIndex === -1) {
this.attrsBlockNumber = symbols.push(ATTRS_BLOCK);
} else {
this.attrsBlockNumber = attrsBlockIndex + 1;
}
this.symbolTable = {
hasEval,
symbols
};
}
compile(syntax) {
if (this.compiled !== null) return this.compiled;
var m = meta(this.layout);
var context = templateCompilationContext(syntax, m);
var {
encoder,
program: {
constants,
resolver
}
} = context;
function pushOp(...op) {
encodeOp(encoder, constants, resolver, m, op);
}
WrappedComponent(pushOp, this.layout, this.attrsBlockNumber);
var handle = context.encoder.commit(m.size);
if (typeof handle !== 'number') {
return handle;
}
this.compiled = handle;
return handle;
}
}
_exports.WrappedBuilder = WrappedBuilder;
var clientId = 0;
var templateCacheCounters = {
cacheHit: 0,
cacheMiss: 0
};
/**
* Wraps a template js in a template module to change it into a factory
* that handles lazy parsing the template and to create per env singletons
* of the template.
*/
_exports.templateCacheCounters = templateCacheCounters;
function templateFactory({
id: templateId,
moduleName,
block,
scope,
isStrictMode
}) {
// TODO(template-refactors): This should be removed in the near future, as it
// appears that id is unused. It is currently kept for backwards compat reasons.
var id = templateId || `client-${clientId++}`; // TODO: This caches JSON serialized output once in case a template is
// compiled by multiple owners, but we haven't verified if this is actually
// helpful. We should benchmark this in the future.
var parsedBlock;
var ownerlessTemplate = null;
var templateCache = new WeakMap();
var factory = owner => {
if (parsedBlock === undefined) {
parsedBlock = JSON.parse(block);
}
if (owner === undefined) {
if (ownerlessTemplate === null) {
templateCacheCounters.cacheMiss++;
ownerlessTemplate = new TemplateImpl({
id,
block: parsedBlock,
moduleName,
owner: null,
scope,
isStrictMode
});
} else {
templateCacheCounters.cacheHit++;
}
return ownerlessTemplate;
}
var result = templateCache.get(owner);
if (result === undefined) {
templateCacheCounters.cacheMiss++;
result = new TemplateImpl({
id,
block: parsedBlock,
moduleName,
owner,
scope,
isStrictMode
});
templateCache.set(owner, result);
} else {
templateCacheCounters.cacheHit++;
}
return result;
};
factory.__id = id;
factory.__meta = {
moduleName
};
return factory;
}
class TemplateImpl {
constructor(parsedLayout) {
this.parsedLayout = parsedLayout;
this.result = 'ok';
this.layout = null;
this.wrappedLayout = null;
}
get moduleName() {
return this.parsedLayout.moduleName;
}
get id() {
return this.parsedLayout.id;
} // TODO(template-refactors): This should be removed in the near future, it is
// only being exposed for backwards compatibility
get referrer() {
return {
moduleName: this.parsedLayout.moduleName,
owner: this.parsedLayout.owner
};
}
asLayout() {
if (this.layout) return this.layout;
return this.layout = compilable((0, _util.assign)({}, this.parsedLayout), this.moduleName);
}
asWrappedLayout() {
if (this.wrappedLayout) return this.wrappedLayout;
return this.wrappedLayout = new WrappedBuilder((0, _util.assign)({}, this.parsedLayout), this.moduleName);
}
}
});
define("@glimmer/owner", ["exports", "@glimmer/util"], function (_exports, _util) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.getOwner = getOwner;
_exports.setOwner = setOwner;
_exports.OWNER = void 0;
var OWNER = (0, _util.symbol)('OWNER');
/**
Framework objects in a Glimmer application may receive an owner object.
Glimmer is unopinionated about this owner, but will forward it through its
internal resolution system, and through its managers if it is provided.
*/
_exports.OWNER = OWNER;
function getOwner(object) {
return object[OWNER];
}
/**
`setOwner` set's an object's owner
*/
function setOwner(object, owner) {
object[OWNER] = owner;
}
});
define("@glimmer/program", ["exports", "@glimmer/util", "@glimmer/manager", "@glimmer/opcode-compiler"], function (_exports, _util, _manager, _opcodeCompiler) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.hydrateHeap = hydrateHeap;
_exports.artifacts = artifacts;
_exports.RuntimeOpImpl = _exports.RuntimeProgramImpl = _exports.HeapImpl = _exports.RuntimeHeapImpl = _exports.ConstantsImpl = _exports.RuntimeConstantsImpl = _exports.CompileTimeConstantImpl = void 0;
/**
* Default component template, which is a plain yield
*/
var DEFAULT_TEMPLATE_BLOCK = [[[18
/* Yield */
, 1, null]], ['&default'], false, []];
var DEFAULT_TEMPLATE = {
// random uuid
id: '1b32f5c2-7623-43d6-a0ad-9672898920a1',
moduleName: '__default__.hbs',
block: JSON.stringify(DEFAULT_TEMPLATE_BLOCK),
scope: null,
isStrictMode: true
};
var WELL_KNOWN_EMPTY_ARRAY = Object.freeze([]);
var STARTER_CONSTANTS = (0, _util.constants)(WELL_KNOWN_EMPTY_ARRAY);
var WELL_KNOWN_EMPTY_ARRAY_POSITION = STARTER_CONSTANTS.indexOf(WELL_KNOWN_EMPTY_ARRAY);
class CompileTimeConstantImpl {
constructor() {
// `0` means NULL
this.values = STARTER_CONSTANTS.slice();
this.indexMap = new Map(this.values.map((value, index) => [value, index]));
}
value(value) {
var indexMap = this.indexMap;
var index = indexMap.get(value);
if (index === undefined) {
index = this.values.push(value) - 1;
indexMap.set(value, index);
}
return index;
}
array(values) {
if (values.length === 0) {
return WELL_KNOWN_EMPTY_ARRAY_POSITION;
}
var handles = new Array(values.length);
for (var i = 0; i < values.length; i++) {
handles[i] = this.value(values[i]);
}
return this.value(handles);
}
toPool() {
return this.values;
}
}
_exports.CompileTimeConstantImpl = CompileTimeConstantImpl;
class RuntimeConstantsImpl {
constructor(pool) {
this.values = pool;
}
getValue(handle) {
return this.values[handle];
}
getArray(value) {
var handles = this.getValue(value);
var reified = new Array(handles.length);
for (var i = 0; i < handles.length; i++) {
var n = handles[i];
reified[i] = this.getValue(n);
}
return reified;
}
}
_exports.RuntimeConstantsImpl = RuntimeConstantsImpl;
class ConstantsImpl extends CompileTimeConstantImpl {
constructor() {
super(...arguments);
this.reifiedArrs = {
[WELL_KNOWN_EMPTY_ARRAY_POSITION]: WELL_KNOWN_EMPTY_ARRAY
};
this.defaultTemplate = (0, _opcodeCompiler.templateFactory)(DEFAULT_TEMPLATE)(); // Used for tests and debugging purposes, and to be able to analyze large apps
// This is why it's enabled even in production
this.helperDefinitionCount = 0;
this.modifierDefinitionCount = 0;
this.componentDefinitionCount = 0;
this.helperDefinitionCache = new WeakMap();
this.modifierDefinitionCache = new WeakMap();
this.componentDefinitionCache = new WeakMap();
}
helper(definitionState, // TODO: Add a way to expose resolved name for debugging
_resolvedName = null, isOptional) {
var handle = this.helperDefinitionCache.get(definitionState);
if (handle === undefined) {
var managerOrHelper = (0, _manager.getInternalHelperManager)(definitionState, isOptional);
if (managerOrHelper === null) {
this.helperDefinitionCache.set(definitionState, null);
return null;
}
var helper = typeof managerOrHelper === 'function' ? managerOrHelper : managerOrHelper.getHelper(definitionState);
handle = this.value(helper);
this.helperDefinitionCache.set(definitionState, handle);
this.helperDefinitionCount++;
}
return handle;
}
modifier(definitionState, resolvedName = null, isOptional) {
var handle = this.modifierDefinitionCache.get(definitionState);
if (handle === undefined) {
var manager = (0, _manager.getInternalModifierManager)(definitionState, isOptional);
if (manager === null) {
this.modifierDefinitionCache.set(definitionState, null);
return null;
}
var definition = {
resolvedName,
manager,
state: definitionState
};
handle = this.value(definition);
this.modifierDefinitionCache.set(definitionState, handle);
this.modifierDefinitionCount++;
}
return handle;
}
component(definitionState, owner, isOptional) {
var _a;
var definition = this.componentDefinitionCache.get(definitionState);
if (definition === undefined) {
var manager = (0, _manager.getInternalComponentManager)(definitionState, isOptional);
if (manager === null) {
this.componentDefinitionCache.set(definitionState, null);
return null;
}
var capabilities = (0, _manager.capabilityFlagsFrom)(manager.getCapabilities(definitionState));
var templateFactory$$1 = (0, _manager.getComponentTemplate)(definitionState);
var compilable = null;
var template;
if (!(0, _manager.managerHasCapability)(manager, capabilities, 1
/* DynamicLayout */
)) {
template = (_a = templateFactory$$1 === null || templateFactory$$1 === void 0 ? void 0 : templateFactory$$1(owner)) !== null && _a !== void 0 ? _a : this.defaultTemplate;
} else {
template = templateFactory$$1 === null || templateFactory$$1 === void 0 ? void 0 : templateFactory$$1(owner);
}
if (template !== undefined) {
template = (0, _util.unwrapTemplate)(template);
compilable = (0, _manager.managerHasCapability)(manager, capabilities, 1024
/* Wrapped */
) ? template.asWrappedLayout() : template.asLayout();
}
definition = {
resolvedName: null,
handle: -1,
manager,
capabilities,
state: definitionState,
compilable
};
definition.handle = this.value(definition);
this.componentDefinitionCache.set(definitionState, definition);
this.componentDefinitionCount++;
}
return definition;
}
resolvedComponent(resolvedDefinition, resolvedName) {
var definition = this.componentDefinitionCache.get(resolvedDefinition);
if (definition === undefined) {
var {
manager,
state,
template
} = resolvedDefinition;
var capabilities = (0, _manager.capabilityFlagsFrom)(manager.getCapabilities(resolvedDefinition));
var compilable = null;
if (!(0, _manager.managerHasCapability)(manager, capabilities, 1
/* DynamicLayout */
)) {
template = template !== null && template !== void 0 ? template : this.defaultTemplate;
}
if (template !== null) {
template = (0, _util.unwrapTemplate)(template);
compilable = (0, _manager.managerHasCapability)(manager, capabilities, 1024
/* Wrapped */
) ? template.asWrappedLayout() : template.asLayout();
}
definition = {
resolvedName,
handle: -1,
manager,
capabilities,
state,
compilable
};
definition.handle = this.value(definition);
this.componentDefinitionCache.set(resolvedDefinition, definition);
this.componentDefinitionCount++;
}
return definition;
}
getValue(index) {
return this.values[index];
}
getArray(index) {
var reifiedArrs = this.reifiedArrs;
var reified = reifiedArrs[index];
if (reified === undefined) {
var names = this.getValue(index);
reified = new Array(names.length);
for (var i = 0; i < names.length; i++) {
reified[i] = this.getValue(names[i]);
}
reifiedArrs[index] = reified;
}
return reified;
}
}
_exports.ConstantsImpl = ConstantsImpl;
class RuntimeOpImpl {
constructor(heap) {
this.heap = heap;
this.offset = 0;
}
get size() {
var rawType = this.heap.getbyaddr(this.offset);
return ((rawType & 768
/* OPERAND_LEN_MASK */
) >> 8
/* ARG_SHIFT */
) + 1;
}
get isMachine() {
var rawType = this.heap.getbyaddr(this.offset);
return rawType & 1024
/* MACHINE_MASK */
? 1 : 0;
}
get type() {
return this.heap.getbyaddr(this.offset) & 255
/* TYPE_MASK */
;
}
get op1() {
return this.heap.getbyaddr(this.offset + 1);
}
get op2() {
return this.heap.getbyaddr(this.offset + 2);
}
get op3() {
return this.heap.getbyaddr(this.offset + 3);
}
}
_exports.RuntimeOpImpl = RuntimeOpImpl;
var PAGE_SIZE = 0x100000;
class RuntimeHeapImpl {
constructor(serializedHeap) {
var {
buffer,
table
} = serializedHeap;
this.heap = new Int32Array(buffer);
this.table = table;
} // It is illegal to close over this address, as compaction
// may move it. However, it is legal to use this address
// multiple times between compactions.
getaddr(handle) {
return this.table[handle];
}
getbyaddr(address) {
return this.heap[address];
}
sizeof(handle) {
return sizeof(this.table, handle);
}
}
_exports.RuntimeHeapImpl = RuntimeHeapImpl;
function hydrateHeap(serializedHeap) {
return new RuntimeHeapImpl(serializedHeap);
}
/**
* The Heap is responsible for dynamically allocating
* memory in which we read/write the VM's instructions
* from/to. When we malloc we pass out a VMHandle, which
* is used as an indirect way of accessing the memory during
* execution of the VM. Internally we track the different
* regions of the memory in an int array known as the table.
*
* The table 32-bit aligned and has the following layout:
*
* | ... | hp (u32) | info (u32) | size (u32) |
* | ... | Handle | Scope Size | State | Size |
* | ... | 32bits | 30bits | 2bits | 32bit |
*
* With this information we effectively have the ability to
* control when we want to free memory. That being said you
* can not free during execution as raw address are only
* valid during the execution. This means you cannot close
* over them as you will have a bad memory access exception.
*/
class HeapImpl {
constructor() {
this.offset = 0;
this.handle = 0;
this.heap = new Int32Array(PAGE_SIZE);
this.handleTable = [];
this.handleState = [];
}
push(item) {
this.sizeCheck();
this.heap[this.offset++] = item;
}
sizeCheck() {
var {
heap
} = this;
if (this.offset === this.heap.length) {
var newHeap = new Int32Array(heap.length + PAGE_SIZE);
newHeap.set(heap, 0);
this.heap = newHeap;
}
}
getbyaddr(address) {
return this.heap[address];
}
setbyaddr(address, value) {
this.heap[address] = value;
}
malloc() {
// push offset, info, size
this.handleTable.push(this.offset);
return this.handleTable.length - 1;
}
finishMalloc(handle) {}
size() {
return this.offset;
} // It is illegal to close over this address, as compaction
// may move it. However, it is legal to use this address
// multiple times between compactions.
getaddr(handle) {
return this.handleTable[handle];
}
sizeof(handle) {
return sizeof(this.handleTable, handle);
}
free(handle) {
this.handleState[handle] = 1
/* Freed */
;
}
/**
* The heap uses the [Mark-Compact Algorithm](https://en.wikipedia.org/wiki/Mark-compact_algorithm) to shift
* reachable memory to the bottom of the heap and freeable
* memory to the top of the heap. When we have shifted all
* the reachable memory to the top of the heap, we move the
* offset to the next free position.
*/
compact() {
var compactedSize = 0;
var {
handleTable,
handleState,
heap
} = this;
for (var i = 0; i < length; i++) {
var offset = handleTable[i];
var size = handleTable[i + 1] - offset;
var state = handleState[i];
if (state === 2
/* Purged */
) {
continue;
} else if (state === 1
/* Freed */
) {
// transition to "already freed" aka "purged"
// a good improvement would be to reuse
// these slots
handleState[i] = 2
/* Purged */
;
compactedSize += size;
} else if (state === 0
/* Allocated */
) {
for (var j = offset; j <= i + size; j++) {
heap[j - compactedSize] = heap[j];
}
handleTable[i] = offset - compactedSize;
} else if (state === 3
/* Pointer */
) {
handleTable[i] = offset - compactedSize;
}
}
this.offset = this.offset - compactedSize;
}
capture(offset = this.offset) {
// Only called in eager mode
var buffer = slice(this.heap, 0, offset).buffer;
return {
handle: this.handle,
table: this.handleTable,
buffer: buffer
};
}
}
_exports.HeapImpl = HeapImpl;
class RuntimeProgramImpl {
constructor(constants$$1, heap) {
this.constants = constants$$1;
this.heap = heap;
this._opcode = new RuntimeOpImpl(this.heap);
}
opcode(offset) {
this._opcode.offset = offset;
return this._opcode;
}
}
_exports.RuntimeProgramImpl = RuntimeProgramImpl;
function slice(arr, start, end) {
if (arr.slice !== undefined) {
return arr.slice(start, end);
}
var ret = new Int32Array(end);
for (; start < end; start++) {
ret[start] = arr[start];
}
return ret;
}
function sizeof(table, handle) {
{
return -1;
}
}
function artifacts() {
return {
constants: new ConstantsImpl(),
heap: new HeapImpl()
};
}
});
define("@glimmer/reference", ["exports", "@glimmer/global-context", "@glimmer/util", "@glimmer/validator"], function (_exports, _globalContext, _util, _validator) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.createPrimitiveRef = createPrimitiveRef;
_exports.createConstRef = createConstRef;
_exports.createUnboundRef = createUnboundRef;
_exports.createComputeRef = createComputeRef;
_exports.createReadOnlyRef = createReadOnlyRef;
_exports.createInvokableRef = createInvokableRef;
_exports.isInvokableRef = isInvokableRef;
_exports.isConstRef = isConstRef;
_exports.isUpdatableRef = isUpdatableRef;
_exports.valueForRef = valueForRef;
_exports.updateRef = updateRef;
_exports.childRefFor = childRefFor;
_exports.childRefFromParts = childRefFromParts;
_exports.createIteratorRef = createIteratorRef;
_exports.createIteratorItemRef = createIteratorItemRef;
_exports.FALSE_REFERENCE = _exports.TRUE_REFERENCE = _exports.NULL_REFERENCE = _exports.UNDEFINED_REFERENCE = _exports.createDebugAliasRef = _exports.REFERENCE = void 0;
var REFERENCE = (0, _util.symbol)('REFERENCE');
_exports.REFERENCE = REFERENCE;
class ReferenceImpl {
constructor(type) {
this.tag = null;
this.lastRevision = _validator.INITIAL;
this.children = null;
this.compute = null;
this.update = null;
this[REFERENCE] = type;
}
}
function createPrimitiveRef(value) {
var ref = new ReferenceImpl(2
/* Unbound */
);
ref.tag = _validator.CONSTANT_TAG;
ref.lastValue = value;
if (true
/* DEBUG */
) {
ref.debugLabel = String(value);
}
return ref;
}
var UNDEFINED_REFERENCE = createPrimitiveRef(undefined);
_exports.UNDEFINED_REFERENCE = UNDEFINED_REFERENCE;
var NULL_REFERENCE = createPrimitiveRef(null);
_exports.NULL_REFERENCE = NULL_REFERENCE;
var TRUE_REFERENCE = createPrimitiveRef(true);
_exports.TRUE_REFERENCE = TRUE_REFERENCE;
var FALSE_REFERENCE = createPrimitiveRef(false);
_exports.FALSE_REFERENCE = FALSE_REFERENCE;
function createConstRef(value, debugLabel) {
var ref = new ReferenceImpl(0
/* Constant */
);
ref.lastValue = value;
ref.tag = _validator.CONSTANT_TAG;
if (true
/* DEBUG */
) {
ref.debugLabel = debugLabel;
}
return ref;
}
function createUnboundRef(value, debugLabel) {
var ref = new ReferenceImpl(2
/* Unbound */
);
ref.lastValue = value;
ref.tag = _validator.CONSTANT_TAG;
if (true
/* DEBUG */
) {
ref.debugLabel = debugLabel;
}
return ref;
}
function createComputeRef(compute, update = null, debugLabel = 'unknown') {
var ref = new ReferenceImpl(1
/* Compute */
);
ref.compute = compute;
ref.update = update;
if (true
/* DEBUG */
) {
ref.debugLabel = `(result of a \`${debugLabel}\` helper)`;
}
return ref;
}
function createReadOnlyRef(ref) {
if (!isUpdatableRef(ref)) return ref;
return createComputeRef(() => valueForRef(ref), null, ref.debugLabel);
}
function isInvokableRef(ref) {
return ref[REFERENCE] === 3
/* Invokable */
;
}
function createInvokableRef(inner) {
var ref = createComputeRef(() => valueForRef(inner), value => updateRef(inner, value));
ref.debugLabel = inner.debugLabel;
ref[REFERENCE] = 3
/* Invokable */
;
return ref;
}
function isConstRef(_ref) {
var ref = _ref;
return ref.tag === _validator.CONSTANT_TAG;
}
function isUpdatableRef(_ref) {
var ref = _ref;
return ref.update !== null;
}
function valueForRef(_ref) {
var ref = _ref;
var {
tag
} = ref;
if (tag === _validator.CONSTANT_TAG) {
return ref.lastValue;
}
var {
lastRevision
} = ref;
var lastValue;
if (tag === null || !(0, _validator.validateTag)(tag, lastRevision)) {
var {
compute
} = ref;
tag = ref.tag = (0, _validator.track)(() => {
lastValue = ref.lastValue = compute();
}, true
/* DEBUG */
&& ref.debugLabel);
ref.lastRevision = (0, _validator.valueForTag)(tag);
} else {
lastValue = ref.lastValue;
}
(0, _validator.consumeTag)(tag);
return lastValue;
}
function updateRef(_ref, value) {
var ref = _ref;
var update = ref.update;
update(value);
}
function childRefFor(_parentRef, path) {
var parentRef = _parentRef;
var type = parentRef[REFERENCE];
var children = parentRef.children;
var child;
if (children === null) {
children = parentRef.children = new Map();
} else {
child = children.get(path);
if (child !== undefined) {
return child;
}
}
if (type === 2
/* Unbound */
) {
var parent = valueForRef(parentRef);
if ((0, _util.isDict)(parent)) {
child = createUnboundRef(parent[path], true
/* DEBUG */
&& `${parentRef.debugLabel}.${path}`);
} else {
child = UNDEFINED_REFERENCE;
}
} else {
child = createComputeRef(() => {
var parent = valueForRef(parentRef);
if ((0, _util.isDict)(parent)) {
return (0, _globalContext.getProp)(parent, path);
}
}, val => {
var parent = valueForRef(parentRef);
if ((0, _util.isDict)(parent)) {
return (0, _globalContext.setProp)(parent, path, val);
}
});
if (true
/* DEBUG */
) {
child.debugLabel = `${parentRef.debugLabel}.${path}`;
}
}
children.set(path, child);
return child;
}
function childRefFromParts(root, parts) {
var reference = root;
for (var i = 0; i < parts.length; i++) {
reference = childRefFor(reference, parts[i]);
}
return reference;
}
var createDebugAliasRef;
_exports.createDebugAliasRef = createDebugAliasRef;
if (true
/* DEBUG */
) {
_exports.createDebugAliasRef = createDebugAliasRef = (debugLabel, inner) => {
var update = isUpdatableRef(inner) ? value => updateRef(inner, value) : null;
var ref = createComputeRef(() => valueForRef(inner), update);
ref[REFERENCE] = inner[REFERENCE];
ref.debugLabel = debugLabel;
return ref;
};
}
var NULL_IDENTITY = {};
var KEY = (_, index) => index;
var INDEX = (_, index) => String(index);
var IDENTITY = item => {
if (item === null) {
// Returning null as an identity will cause failures since the iterator
// can't tell that it's actually supposed to be null
return NULL_IDENTITY;
}
return item;
};
function keyForPath(path) {
if (true
/* DEBUG */
&& path[0] === '@') {
throw new Error(`invalid keypath: '${path}', valid keys: @index, @identity, or a path`);
}
return uniqueKeyFor(item => (0, _globalContext.getPath)(item, path));
}
function makeKeyFor(key) {
switch (key) {
case '@key':
return uniqueKeyFor(KEY);
case '@index':
return uniqueKeyFor(INDEX);
case '@identity':
return uniqueKeyFor(IDENTITY);
default:
return keyForPath(key);
}
}
class WeakMapWithPrimitives {
get weakMap() {
if (this._weakMap === undefined) {
this._weakMap = new WeakMap();
}
return this._weakMap;
}
get primitiveMap() {
if (this._primitiveMap === undefined) {
this._primitiveMap = new Map();
}
return this._primitiveMap;
}
set(key, value) {
if ((0, _util.isObject)(key)) {
this.weakMap.set(key, value);
} else {
this.primitiveMap.set(key, value);
}
}
get(key) {
if ((0, _util.isObject)(key)) {
return this.weakMap.get(key);
} else {
return this.primitiveMap.get(key);
}
}
}
var IDENTITIES = new WeakMapWithPrimitives();
function identityForNthOccurence(value, count) {
var identities = IDENTITIES.get(value);
if (identities === undefined) {
identities = [];
IDENTITIES.set(value, identities);
}
var identity = identities[count];
if (identity === undefined) {
identity = {
value,
count
};
identities[count] = identity;
}
return identity;
}
/**
* When iterating over a list, it's possible that an item with the same unique
* key could be encountered twice:
*
* ```js
* let arr = ['same', 'different', 'same', 'same'];
* ```
*
* In general, we want to treat these items as _unique within the list_. To do
* this, we track the occurences of every item as we iterate the list, and when
* an item occurs more than once, we generate a new unique key just for that
* item, and that occurence within the list. The next time we iterate the list,
* and encounter an item for the nth time, we can get the _same_ key, and let
* Glimmer know that it should reuse the DOM for the previous nth occurence.
*/
function uniqueKeyFor(keyFor) {
var seen = new WeakMapWithPrimitives();
return (value, memo) => {
var key = keyFor(value, memo);
var count = seen.get(key) || 0;
seen.set(key, count + 1);
if (count === 0) {
return key;
}
return identityForNthOccurence(key, count);
};
}
function createIteratorRef(listRef, key) {
return createComputeRef(() => {
var iterable = valueForRef(listRef);
var keyFor = makeKeyFor(key);
if (Array.isArray(iterable)) {
return new ArrayIterator(iterable, keyFor);
}
var maybeIterator = (0, _globalContext.toIterator)(iterable);
if (maybeIterator === null) {
return new ArrayIterator(_util.EMPTY_ARRAY, () => null);
}
return new IteratorWrapper(maybeIterator, keyFor);
});
}
function createIteratorItemRef(_value) {
var value = _value;
var tag = (0, _validator.createTag)();
return createComputeRef(() => {
(0, _validator.consumeTag)(tag);
return value;
}, newValue => {
if (value !== newValue) {
value = newValue;
(0, _validator.dirtyTag)(tag);
}
});
}
class IteratorWrapper {
constructor(inner, keyFor) {
this.inner = inner;
this.keyFor = keyFor;
}
isEmpty() {
return this.inner.isEmpty();
}
next() {
var nextValue = this.inner.next();
if (nextValue !== null) {
nextValue.key = this.keyFor(nextValue.value, nextValue.memo);
}
return nextValue;
}
}
class ArrayIterator {
constructor(iterator, keyFor) {
this.iterator = iterator;
this.keyFor = keyFor;
this.pos = 0;
if (iterator.length === 0) {
this.current = {
kind: 'empty'
};
} else {
this.current = {
kind: 'first',
value: iterator[this.pos]
};
}
}
isEmpty() {
return this.current.kind === 'empty';
}
next() {
var value;
var current = this.current;
if (current.kind === 'first') {
this.current = {
kind: 'progress'
};
value = current.value;
} else if (this.pos >= this.iterator.length - 1) {
return null;
} else {
value = this.iterator[++this.pos];
}
var {
keyFor
} = this;
var key = keyFor(value, this.pos);
var memo = this.pos;
return {
key,
value,
memo
};
}
}
});
define("@glimmer/runtime", ["exports", "@glimmer/util", "@glimmer/reference", "@glimmer/global-context", "@glimmer/destroyable", "@glimmer/vm", "@glimmer/validator", "@glimmer/manager", "@glimmer/program", "@glimmer/owner", "@glimmer/runtime"], function (_exports, _util, _reference, _globalContext, _destroyable2, _vm2, _validator, _manager5, _program, _owner2, _runtime) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.clear = clear;
_exports.resetDebuggerCallback = resetDebuggerCallback;
_exports.setDebuggerCallback = setDebuggerCallback;
_exports.curry = curry;
_exports.templateOnlyComponent = templateOnlyComponent;
_exports.isWhitespace = isWhitespace;
_exports.normalizeProperty = normalizeProperty;
_exports.runtimeContext = runtimeContext;
_exports.inTransaction = inTransaction;
_exports.renderComponent = renderComponent;
_exports.renderMain = renderMain;
_exports.renderSync = renderSync;
_exports.createCapturedArgs = createCapturedArgs;
_exports.reifyArgs = reifyArgs;
_exports.reifyNamed = reifyNamed$1;
_exports.reifyPositional = reifyPositional$1;
_exports.dynamicAttribute = dynamicAttribute;
_exports.clientBuilder = clientBuilder;
_exports.isSerializationFirstNode = isSerializationFirstNode;
_exports.rehydrationBuilder = rehydrationBuilder;
_exports.invokeHelper = invokeHelper;
Object.defineProperty(_exports, "destroy", {
enumerable: true,
get: function () {
return _destroyable2.destroy;
}
});
Object.defineProperty(_exports, "registerDestructor", {
enumerable: true,
get: function () {
return _destroyable2.registerDestructor;
}
});
Object.defineProperty(_exports, "isDestroying", {
enumerable: true,
get: function () {
return _destroyable2.isDestroying;
}
});
Object.defineProperty(_exports, "isDestroyed", {
enumerable: true,
get: function () {
return _destroyable2.isDestroyed;
}
});
_exports.on = _exports.concat = _exports.get = _exports.array = _exports.hash = _exports.fn = _exports.SERIALIZATION_FIRST_NODE_STRING = _exports.RehydrateBuilder = _exports.RemoteLiveBlock = _exports.UpdatableBlockImpl = _exports.NewElementBuilder = _exports.SimpleDynamicAttribute = _exports.DynamicAttribute = _exports.EMPTY_POSITIONAL = _exports.EMPTY_NAMED = _exports.EMPTY_ARGS = _exports.LowLevelVM = _exports.UpdatingVM = _exports.EnvironmentImpl = _exports.PartialScopeImpl = _exports.DynamicScopeImpl = _exports.DOMTreeConstruction = _exports.IDOMChanges = _exports.DOMChanges = _exports.TemplateOnlyComponent = _exports.TEMPLATE_ONLY_COMPONENT_MANAGER = _exports.TemplateOnlyComponentManager = _exports.CurriedValue = _exports.CursorImpl = _exports.ConcreteBounds = void 0;
class DynamicScopeImpl {
constructor(bucket) {
if (bucket) {
this.bucket = (0, _util.assign)({}, bucket);
} else {
this.bucket = {};
}
}
get(key) {
return this.bucket[key];
}
set(key, reference) {
return this.bucket[key] = reference;
}
child() {
return new DynamicScopeImpl(this.bucket);
}
}
_exports.DynamicScopeImpl = DynamicScopeImpl;
class PartialScopeImpl {
constructor( // the 0th slot is `self`
slots, owner, callerScope, // named arguments and blocks passed to a layout that uses eval
evalScope, // locals in scope when the partial was invoked
partialMap) {
this.slots = slots;
this.owner = owner;
this.callerScope = callerScope;
this.evalScope = evalScope;
this.partialMap = partialMap;
}
static root(self, size = 0, owner) {
var refs = new Array(size + 1);
for (var i = 0; i <= size; i++) {
refs[i] = _reference.UNDEFINED_REFERENCE;
}
return new PartialScopeImpl(refs, owner, null, null, null).init({
self
});
}
static sized(size = 0, owner) {
var refs = new Array(size + 1);
for (var i = 0; i <= size; i++) {
refs[i] = _reference.UNDEFINED_REFERENCE;
}
return new PartialScopeImpl(refs, owner, null, null, null);
}
init({
self
}) {
this.slots[0] = self;
return this;
}
getSelf() {
return this.get(0);
}
getSymbol(symbol$$1) {
return this.get(symbol$$1);
}
getBlock(symbol$$1) {
var block = this.get(symbol$$1);
return block === _reference.UNDEFINED_REFERENCE ? null : block;
}
getEvalScope() {
return this.evalScope;
}
getPartialMap() {
return this.partialMap;
}
bind(symbol$$1, value) {
this.set(symbol$$1, value);
}
bindSelf(self) {
this.set(0, self);
}
bindSymbol(symbol$$1, value) {
this.set(symbol$$1, value);
}
bindBlock(symbol$$1, value) {
this.set(symbol$$1, value);
}
bindEvalScope(map) {
this.evalScope = map;
}
bindPartialMap(map) {
this.partialMap = map;
}
bindCallerScope(scope) {
this.callerScope = scope;
}
getCallerScope() {
return this.callerScope;
}
child() {
return new PartialScopeImpl(this.slots.slice(), this.owner, this.callerScope, this.evalScope, this.partialMap);
}
get(index) {
if (index >= this.slots.length) {
throw new RangeError(`BUG: cannot get $${index} from scope; length=${this.slots.length}`);
}
return this.slots[index];
}
set(index, value) {
if (index >= this.slots.length) {
throw new RangeError(`BUG: cannot get $${index} from scope; length=${this.slots.length}`);
}
this.slots[index] = value;
}
} // the VM in other classes, but are not intended to be a part of
// Glimmer's API.
_exports.PartialScopeImpl = PartialScopeImpl;
var INNER_VM = (0, _util.symbol)('INNER_VM');
var DESTROYABLE_STACK = (0, _util.symbol)('DESTROYABLE_STACK');
var STACKS = (0, _util.symbol)('STACKS');
var REGISTERS = (0, _util.symbol)('REGISTERS');
var HEAP = (0, _util.symbol)('HEAP');
var CONSTANTS = (0, _util.symbol)('CONSTANTS');
var ARGS = (0, _util.symbol)('ARGS');
var PC = (0, _util.symbol)('PC');
class CursorImpl {
constructor(element, nextSibling) {
this.element = element;
this.nextSibling = nextSibling;
}
}
_exports.CursorImpl = CursorImpl;
class ConcreteBounds {
constructor(parentNode, first, last) {
this.parentNode = parentNode;
this.first = first;
this.last = last;
}
parentElement() {
return this.parentNode;
}
firstNode() {
return this.first;
}
lastNode() {
return this.last;
}
}
_exports.ConcreteBounds = ConcreteBounds;
class SingleNodeBounds {
constructor(parentNode, node) {
this.parentNode = parentNode;
this.node = node;
}
parentElement() {
return this.parentNode;
}
firstNode() {
return this.node;
}
lastNode() {
return this.node;
}
}
function move(bounds, reference) {
var parent = bounds.parentElement();
var first = bounds.firstNode();
var last = bounds.lastNode();
var current = first;
while (true) {
var next = current.nextSibling;
parent.insertBefore(current, reference);
if (current === last) {
return next;
}
current = next;
}
}
function clear(bounds) {
var parent = bounds.parentElement();
var first = bounds.firstNode();
var last = bounds.lastNode();
var current = first;
while (true) {
var next = current.nextSibling;
parent.removeChild(current);
if (current === last) {
return next;
}
current = next;
}
}
function normalizeStringValue(value) {
if (isEmpty(value)) {
return '';
}
return String(value);
}
function shouldCoerce(value) {
return isString(value) || isEmpty(value) || typeof value === 'boolean' || typeof value === 'number';
}
function isEmpty(value) {
return value === null || value === undefined || typeof value.toString !== 'function';
}
function isSafeString(value) {
return typeof value === 'object' && value !== null && typeof value.toHTML === 'function';
}
function isNode(value) {
return typeof value === 'object' && value !== null && typeof value.nodeType === 'number';
}
function isFragment(value) {
return isNode(value) && value.nodeType === 11;
}
function isString(value) {
return typeof value === 'string';
}
/*
* @method normalizeProperty
* @param element {HTMLElement}
* @param slotName {String}
* @returns {Object} { name, type }
*/
function normalizeProperty(element, slotName) {
var type, normalized;
if (slotName in element) {
normalized = slotName;
type = 'prop';
} else {
var lower = slotName.toLowerCase();
if (lower in element) {
type = 'prop';
normalized = lower;
} else {
type = 'attr';
normalized = slotName;
}
}
if (type === 'prop' && (normalized.toLowerCase() === 'style' || preferAttr(element.tagName, normalized))) {
type = 'attr';
}
return {
normalized,
type
};
} // * browser bug
// * strange spec outlier
var ATTR_OVERRIDES = {
INPUT: {
form: true,
// Chrome 46.0.2464.0: 'autocorrect' in document.createElement('input') === false
// Safari 8.0.7: 'autocorrect' in document.createElement('input') === false
// Mobile Safari (iOS 8.4 simulator): 'autocorrect' in document.createElement('input') === true
autocorrect: true,
// Chrome 54.0.2840.98: 'list' in document.createElement('input') === true
// Safari 9.1.3: 'list' in document.createElement('input') === false
list: true
},
// element.form is actually a legitimate readOnly property, that is to be
// mutated, but must be mutated by setAttribute...
SELECT: {
form: true
},
OPTION: {
form: true
},
TEXTAREA: {
form: true
},
LABEL: {
form: true
},
FIELDSET: {
form: true
},
LEGEND: {
form: true
},
OBJECT: {
form: true
},
OUTPUT: {
form: true
},
BUTTON: {
form: true
}
};
function preferAttr(tagName, propName) {
var tag = ATTR_OVERRIDES[tagName.toUpperCase()];
return tag && tag[propName.toLowerCase()] || false;
}
var badProtocols = ['javascript:', 'vbscript:'];
var badTags = ['A', 'BODY', 'LINK', 'IMG', 'IFRAME', 'BASE', 'FORM'];
var badTagsForDataURI = ['EMBED'];
var badAttributes = ['href', 'src', 'background', 'action'];
var badAttributesForDataURI = ['src'];
function has(array, item) {
return array.indexOf(item) !== -1;
}
function checkURI(tagName, attribute) {
return (tagName === null || has(badTags, tagName)) && has(badAttributes, attribute);
}
function checkDataURI(tagName, attribute) {
if (tagName === null) return false;
return has(badTagsForDataURI, tagName) && has(badAttributesForDataURI, attribute);
}
function requiresSanitization(tagName, attribute) {
return checkURI(tagName, attribute) || checkDataURI(tagName, attribute);
}
var protocolForUrl;
if (typeof URL === 'object' && URL !== null && // this is super annoying, TS thinks that URL **must** be a function so `URL.parse` check
// thinks it is `never` without this `as unknown as any`
typeof URL.parse === 'function') {
// In Ember-land the `fastboot` package sets the `URL` global to `require('url')`
// ultimately, this should be changed (so that we can either rely on the natural `URL` global
// that exists) but for now we have to detect the specific `FastBoot` case first
//
// a future version of `fastboot` will detect if this legacy URL setup is required (by
// inspecting Ember version) and if new enough, it will avoid shadowing the `URL` global
// constructor with `require('url')`.
var nodeURL = URL;
protocolForUrl = url => {
var protocol = null;
if (typeof url === 'string') {
protocol = nodeURL.parse(url).protocol;
}
return protocol === null ? ':' : protocol;
};
} else if (typeof URL === 'function') {
protocolForUrl = _url => {
try {
var url = new URL(_url);
return url.protocol;
} catch (error) {
// any non-fully qualified url string will trigger an error (because there is no
// baseURI that we can provide; in that case we **know** that the protocol is
// "safe" because it isn't specifically one of the `badProtocols` listed above
// (and those protocols can never be the default baseURI)
return ':';
}
};
} else {
// fallback for IE11 support
var parsingNode = document.createElement('a');
protocolForUrl = url => {
parsingNode.href = url;
return parsingNode.protocol;
};
}
function sanitizeAttributeValue(element, attribute, value) {
var tagName = null;
if (value === null || value === undefined) {
return value;
}
if (isSafeString(value)) {
return value.toHTML();
}
if (!element) {
tagName = null;
} else {
tagName = element.tagName.toUpperCase();
}
var str = normalizeStringValue(value);
if (checkURI(tagName, attribute)) {
var protocol = protocolForUrl(str);
if (has(badProtocols, protocol)) {
return `unsafe:${str}`;
}
}
if (checkDataURI(tagName, attribute)) {
return `unsafe:${str}`;
}
return str;
}
function dynamicAttribute(element, attr, namespace, isTrusting = false) {
var {
tagName,
namespaceURI
} = element;
var attribute = {
element,
name: attr,
namespace
};
if (true
/* DEBUG */
&& attr === 'style' && !isTrusting) {
return new DebugStyleAttributeManager(attribute);
}
if (namespaceURI === "http://www.w3.org/2000/svg"
/* SVG */
) {
return buildDynamicAttribute(tagName, attr, attribute);
}
var {
type,
normalized
} = normalizeProperty(element, attr);
if (type === 'attr') {
return buildDynamicAttribute(tagName, normalized, attribute);
} else {
return buildDynamicProperty(tagName, normalized, attribute);
}
}
function buildDynamicAttribute(tagName, name, attribute) {
if (requiresSanitization(tagName, name)) {
return new SafeDynamicAttribute(attribute);
} else {
return new SimpleDynamicAttribute(attribute);
}
}
function buildDynamicProperty(tagName, name, attribute) {
if (requiresSanitization(tagName, name)) {
return new SafeDynamicProperty(name, attribute);
}
if (isUserInputValue(tagName, name)) {
return new InputValueDynamicAttribute(name, attribute);
}
if (isOptionSelected(tagName, name)) {
return new OptionSelectedDynamicAttribute(name, attribute);
}
return new DefaultDynamicProperty(name, attribute);
}
class DynamicAttribute {
constructor(attribute) {
this.attribute = attribute;
}
}
_exports.DynamicAttribute = DynamicAttribute;
class SimpleDynamicAttribute extends DynamicAttribute {
set(dom, value, _env) {
var normalizedValue = normalizeValue(value);
if (normalizedValue !== null) {
var {
name,
namespace
} = this.attribute;
dom.__setAttribute(name, normalizedValue, namespace);
}
}
update(value, _env) {
var normalizedValue = normalizeValue(value);
var {
element,
name
} = this.attribute;
if (normalizedValue === null) {
element.removeAttribute(name);
} else {
element.setAttribute(name, normalizedValue);
}
}
}
_exports.SimpleDynamicAttribute = SimpleDynamicAttribute;
class DefaultDynamicProperty extends DynamicAttribute {
constructor(normalizedName, attribute) {
super(attribute);
this.normalizedName = normalizedName;
}
set(dom, value, _env) {
if (value !== null && value !== undefined) {
this.value = value;
dom.__setProperty(this.normalizedName, value);
}
}
update(value, _env) {
var {
element
} = this.attribute;
if (this.value !== value) {
element[this.normalizedName] = this.value = value;
if (value === null || value === undefined) {
this.removeAttribute();
}
}
}
removeAttribute() {
// TODO this sucks but to preserve properties first and to meet current
// semantics we must do this.
var {
element,
namespace
} = this.attribute;
if (namespace) {
element.removeAttributeNS(namespace, this.normalizedName);
} else {
element.removeAttribute(this.normalizedName);
}
}
}
class SafeDynamicProperty extends DefaultDynamicProperty {
set(dom, value, env) {
var {
element,
name
} = this.attribute;
var sanitized = sanitizeAttributeValue(element, name, value);
super.set(dom, sanitized, env);
}
update(value, env) {
var {
element,
name
} = this.attribute;
var sanitized = sanitizeAttributeValue(element, name, value);
super.update(sanitized, env);
}
}
class SafeDynamicAttribute extends SimpleDynamicAttribute {
set(dom, value, env) {
var {
element,
name
} = this.attribute;
var sanitized = sanitizeAttributeValue(element, name, value);
super.set(dom, sanitized, env);
}
update(value, env) {
var {
element,
name
} = this.attribute;
var sanitized = sanitizeAttributeValue(element, name, value);
super.update(sanitized, env);
}
}
class InputValueDynamicAttribute extends DefaultDynamicProperty {
set(dom, value) {
dom.__setProperty('value', normalizeStringValue(value));
}
update(value) {
var input = this.attribute.element;
var currentValue = input.value;
var normalizedValue = normalizeStringValue(value);
if (currentValue !== normalizedValue) {
input.value = normalizedValue;
}
}
}
class OptionSelectedDynamicAttribute extends DefaultDynamicProperty {
set(dom, value) {
if (value !== null && value !== undefined && value !== false) {
dom.__setProperty('selected', true);
}
}
update(value) {
var option = this.attribute.element;
if (value) {
option.selected = true;
} else {
option.selected = false;
}
}
}
function isOptionSelected(tagName, attribute) {
return tagName === 'OPTION' && attribute === 'selected';
}
function isUserInputValue(tagName, attribute) {
return (tagName === 'INPUT' || tagName === 'TEXTAREA') && attribute === 'value';
}
function normalizeValue(value) {
if (value === false || value === undefined || value === null || typeof value.toString === 'undefined') {
return null;
}
if (value === true) {
return '';
} // onclick function etc in SSR
if (typeof value === 'function') {
return null;
}
return String(value);
}
var DebugStyleAttributeManager;
if (true
/* DEBUG */
) {
DebugStyleAttributeManager = class extends SimpleDynamicAttribute {
set(dom, value, env) {
(0, _globalContext.warnIfStyleNotTrusted)(value);
super.set(dom, value, env);
}
update(value, env) {
(0, _globalContext.warnIfStyleNotTrusted)(value);
super.update(value, env);
}
};
}
var _a;
class First {
constructor(node) {
this.node = node;
}
firstNode() {
return this.node;
}
}
class Last {
constructor(node) {
this.node = node;
}
lastNode() {
return this.node;
}
}
var CURSOR_STACK = (0, _util.symbol)('CURSOR_STACK');
class NewElementBuilder {
constructor(env, parentNode, nextSibling) {
this.constructing = null;
this.operations = null;
this[_a] = new _util.Stack();
this.modifierStack = new _util.Stack();
this.blockStack = new _util.Stack();
this.pushElement(parentNode, nextSibling);
this.env = env;
this.dom = env.getAppendOperations();
this.updateOperations = env.getDOM();
}
static forInitialRender(env, cursor) {
return new this(env, cursor.element, cursor.nextSibling).initialize();
}
static resume(env, block) {
var parentNode = block.parentElement();
var nextSibling = block.reset(env);
var stack = new this(env, parentNode, nextSibling).initialize();
stack.pushLiveBlock(block);
return stack;
}
initialize() {
this.pushSimpleBlock();
return this;
}
debugBlocks() {
return this.blockStack.toArray();
}
get element() {
return this[CURSOR_STACK].current.element;
}
get nextSibling() {
return this[CURSOR_STACK].current.nextSibling;
}
get hasBlocks() {
return this.blockStack.size > 0;
}
block() {
return this.blockStack.current;
}
popElement() {
this[CURSOR_STACK].pop();
this[CURSOR_STACK].current;
}
pushSimpleBlock() {
return this.pushLiveBlock(new SimpleLiveBlock(this.element));
}
pushUpdatableBlock() {
return this.pushLiveBlock(new UpdatableBlockImpl(this.element));
}
pushBlockList(list) {
return this.pushLiveBlock(new LiveBlockList(this.element, list));
}
pushLiveBlock(block, isRemote = false) {
var current = this.blockStack.current;
if (current !== null) {
if (!isRemote) {
current.didAppendBounds(block);
}
}
this.__openBlock();
this.blockStack.push(block);
return block;
}
popBlock() {
this.block().finalize(this);
this.__closeBlock();
return this.blockStack.pop();
}
__openBlock() {}
__closeBlock() {} // todo return seems unused
openElement(tag) {
var element = this.__openElement(tag);
this.constructing = element;
return element;
}
__openElement(tag) {
return this.dom.createElement(tag, this.element);
}
flushElement(modifiers) {
var parent = this.element;
var element = this.constructing;
this.__flushElement(parent, element);
this.constructing = null;
this.operations = null;
this.pushModifiers(modifiers);
this.pushElement(element, null);
this.didOpenElement(element);
}
__flushElement(parent, constructing) {
this.dom.insertBefore(parent, constructing, this.nextSibling);
}
closeElement() {
this.willCloseElement();
this.popElement();
return this.popModifiers();
}
pushRemoteElement(element, guid, insertBefore) {
return this.__pushRemoteElement(element, guid, insertBefore);
}
__pushRemoteElement(element, _guid, insertBefore) {
this.pushElement(element, insertBefore);
if (insertBefore === undefined) {
while (element.lastChild) {
element.removeChild(element.lastChild);
}
}
var block = new RemoteLiveBlock(element);
return this.pushLiveBlock(block, true);
}
popRemoteElement() {
this.popBlock();
this.popElement();
}
pushElement(element, nextSibling = null) {
this[CURSOR_STACK].push(new CursorImpl(element, nextSibling));
}
pushModifiers(modifiers) {
this.modifierStack.push(modifiers);
}
popModifiers() {
return this.modifierStack.pop();
}
didAppendBounds(bounds) {
this.block().didAppendBounds(bounds);
return bounds;
}
didAppendNode(node) {
this.block().didAppendNode(node);
return node;
}
didOpenElement(element) {
this.block().openElement(element);
return element;
}
willCloseElement() {
this.block().closeElement();
}
appendText(string) {
return this.didAppendNode(this.__appendText(string));
}
__appendText(text) {
var {
dom,
element,
nextSibling
} = this;
var node = dom.createTextNode(text);
dom.insertBefore(element, node, nextSibling);
return node;
}
__appendNode(node) {
this.dom.insertBefore(this.element, node, this.nextSibling);
return node;
}
__appendFragment(fragment) {
var first = fragment.firstChild;
if (first) {
var ret = new ConcreteBounds(this.element, first, fragment.lastChild);
this.dom.insertBefore(this.element, fragment, this.nextSibling);
return ret;
} else {
return new SingleNodeBounds(this.element, this.__appendComment(''));
}
}
__appendHTML(html) {
return this.dom.insertHTMLBefore(this.element, this.nextSibling, html);
}
appendDynamicHTML(value) {
var bounds = this.trustedContent(value);
this.didAppendBounds(bounds);
}
appendDynamicText(value) {
var node = this.untrustedContent(value);
this.didAppendNode(node);
return node;
}
appendDynamicFragment(value) {
var bounds = this.__appendFragment(value);
this.didAppendBounds(bounds);
}
appendDynamicNode(value) {
var node = this.__appendNode(value);
var bounds = new SingleNodeBounds(this.element, node);
this.didAppendBounds(bounds);
}
trustedContent(value) {
return this.__appendHTML(value);
}
untrustedContent(value) {
return this.__appendText(value);
}
appendComment(string) {
return this.didAppendNode(this.__appendComment(string));
}
__appendComment(string) {
var {
dom,
element,
nextSibling
} = this;
var node = dom.createComment(string);
dom.insertBefore(element, node, nextSibling);
return node;
}
__setAttribute(name, value, namespace) {
this.dom.setAttribute(this.constructing, name, value, namespace);
}
__setProperty(name, value) {
this.constructing[name] = value;
}
setStaticAttribute(name, value, namespace) {
this.__setAttribute(name, value, namespace);
}
setDynamicAttribute(name, value, trusting, namespace) {
var element = this.constructing;
var attribute = dynamicAttribute(element, name, namespace, trusting);
attribute.set(this, value, this.env);
return attribute;
}
}
_exports.NewElementBuilder = NewElementBuilder;
_a = CURSOR_STACK;
class SimpleLiveBlock {
constructor(parent) {
this.parent = parent;
this.first = null;
this.last = null;
this.nesting = 0;
}
parentElement() {
return this.parent;
}
firstNode() {
var first = this.first;
return first.firstNode();
}
lastNode() {
var last = this.last;
return last.lastNode();
}
openElement(element) {
this.didAppendNode(element);
this.nesting++;
}
closeElement() {
this.nesting--;
}
didAppendNode(node) {
if (this.nesting !== 0) return;
if (!this.first) {
this.first = new First(node);
}
this.last = new Last(node);
}
didAppendBounds(bounds) {
if (this.nesting !== 0) return;
if (!this.first) {
this.first = bounds;
}
this.last = bounds;
}
finalize(stack) {
if (this.first === null) {
stack.appendComment('');
}
}
}
class RemoteLiveBlock extends SimpleLiveBlock {
constructor(parent) {
super(parent);
(0, _destroyable2.registerDestructor)(this, () => {
// In general, you only need to clear the root of a hierarchy, and should never
// need to clear any child nodes. This is an important constraint that gives us
// a strong guarantee that clearing a subtree is a single DOM operation.
//
// Because remote blocks are not normally physically nested inside of the tree
// that they are logically nested inside, we manually clear remote blocks when
// a logical parent is cleared.
//
// HOWEVER, it is currently possible for a remote block to be physically nested
// inside of the block it is logically contained inside of. This happens when
// the remote block is appended to the end of the application's entire element.
//
// The problem with that scenario is that Glimmer believes that it owns more of
// the DOM than it actually does. The code is attempting to write past the end
// of the Glimmer-managed root, but Glimmer isn't aware of that.
//
// The correct solution to that problem is for Glimmer to be aware of the end
// of the bounds that it owns, and once we make that change, this check could
// be removed.
//
// For now, a more targeted fix is to check whether the node was already removed
// and avoid clearing the node if it was. In most cases this shouldn't happen,
// so this might hide bugs where the code clears nested nodes unnecessarily,
// so we should eventually try to do the correct fix.
if (this.parentElement() === this.firstNode().parentNode) {
clear(this);
}
});
}
}
_exports.RemoteLiveBlock = RemoteLiveBlock;
class UpdatableBlockImpl extends SimpleLiveBlock {
reset() {
(0, _destroyable2.destroy)(this);
var nextSibling = clear(this);
this.first = null;
this.last = null;
this.nesting = 0;
return nextSibling;
}
} // FIXME: All the noops in here indicate a modelling problem
_exports.UpdatableBlockImpl = UpdatableBlockImpl;
class LiveBlockList {
constructor(parent, boundList) {
this.parent = parent;
this.boundList = boundList;
this.parent = parent;
this.boundList = boundList;
}
parentElement() {
return this.parent;
}
firstNode() {
var head = this.boundList[0];
return head.firstNode();
}
lastNode() {
var boundList = this.boundList;
var tail = boundList[boundList.length - 1];
return tail.lastNode();
}
openElement(_element) {}
closeElement() {}
didAppendNode(_node) {}
didAppendBounds(_bounds) {}
finalize(_stack) {}
}
function clientBuilder(env, cursor) {
return NewElementBuilder.forInitialRender(env, cursor);
}
class AppendOpcodes {
constructor() {
this.evaluateOpcode = (0, _util.fillNulls)(104
/* Size */
).slice();
}
add(name, evaluate, kind = 'syscall') {
this.evaluateOpcode[name] = {
syscall: kind !== 'machine',
evaluate
};
}
debugBefore(vm, opcode) {
var params = undefined;
var opName = undefined;
var sp;
return {
sp: sp,
pc: vm.fetchValue(_vm2.$pc),
name: opName,
params,
type: opcode.type,
isMachine: opcode.isMachine,
size: opcode.size,
state: undefined
};
}
debugAfter(vm, pre) {}
evaluate(vm, opcode, type) {
var operation = this.evaluateOpcode[type];
if (operation.syscall) {
operation.evaluate(vm, opcode);
} else {
operation.evaluate(vm[INNER_VM], opcode);
}
}
}
var APPEND_OPCODES = new AppendOpcodes();
function createConcatRef(partsRefs) {
return (0, _reference.createComputeRef)(() => {
var parts = new Array();
for (var i = 0; i < partsRefs.length; i++) {
var value = (0, _reference.valueForRef)(partsRefs[i]);
if (value !== null && value !== undefined) {
parts[i] = castToString(value);
}
}
if (parts.length > 0) {
return parts.join('');
}
return null;
});
}
function castToString(value) {
if (typeof value.toString !== 'function') {
return '';
}
return String(value);
}
var TYPE = (0, _util.symbol)('TYPE');
var INNER = (0, _util.symbol)('INNER');
var OWNER = (0, _util.symbol)('OWNER');
var ARGS$1 = (0, _util.symbol)('ARGS');
var RESOLVED = (0, _util.symbol)('RESOLVED');
var CURRIED_VALUES = new _util._WeakSet();
function isCurriedValue(value) {
return CURRIED_VALUES.has(value);
}
function isCurriedType(value, type) {
return isCurriedValue(value) && value[TYPE] === type;
}
class CurriedValue {
/** @internal */
constructor(type, inner, owner, args, resolved = false) {
CURRIED_VALUES.add(this);
this[TYPE] = type;
this[INNER] = inner;
this[OWNER] = owner;
this[ARGS$1] = args;
this[RESOLVED] = resolved;
}
}
_exports.CurriedValue = CurriedValue;
function resolveCurriedValue(curriedValue) {
var currentWrapper = curriedValue;
var positional;
var named;
var definition, owner, resolved;
while (true) {
var {
[ARGS$1]: curriedArgs,
[INNER]: inner
} = currentWrapper;
if (curriedArgs !== null) {
var {
named: curriedNamed,
positional: curriedPositional
} = curriedArgs;
if (curriedPositional.length > 0) {
positional = positional === undefined ? curriedPositional : curriedPositional.concat(positional);
}
if (named === undefined) {
named = [];
}
named.unshift(curriedNamed);
}
if (!isCurriedValue(inner)) {
// Save off the owner that this helper was curried with. Later on,
// we'll fetch the value of this register and set it as the owner on the
// new root scope.
definition = inner;
owner = currentWrapper[OWNER];
resolved = currentWrapper[RESOLVED];
break;
}
currentWrapper = inner;
}
return {
definition,
owner,
resolved,
positional,
named
};
}
function curry(type, spec, owner, args, resolved = false) {
return new CurriedValue(type, spec, owner, args, resolved);
}
function createCurryRef(type, inner, owner, args, resolver, isStrict) {
var lastValue, curriedDefinition;
return (0, _reference.createComputeRef)(() => {
var value = (0, _reference.valueForRef)(inner);
if (value === lastValue) {
return curriedDefinition;
}
if (isCurriedType(value, type)) {
curriedDefinition = args ? curry(type, value, owner, args) : args;
} else if (type === 0
/* Component */
&& typeof value === 'string' && value) {
// Only components should enter this path, as helpers and modifiers do not
// support string based resolution
if (true
/* DEBUG */
) {
if (isStrict) {
throw new Error(`Attempted to resolve a dynamic component with a string definition, \`${value}\` in a strict mode template. In strict mode, using strings to resolve component definitions is prohibited. You can instead import the component definition and use it directly.`);
}
var resolvedDefinition = resolver.lookupComponent(value, owner);
if (!resolvedDefinition) {
throw new Error(`Attempted to resolve \`${value}\`, which was expected to be a component, but nothing was found.`);
}
}
curriedDefinition = curry(type, value, owner, args);
} else if ((0, _util.isObject)(value)) {
curriedDefinition = curry(type, value, owner, args);
} else {
curriedDefinition = null;
}
lastValue = value;
return curriedDefinition;
});
}
/*
The calling convention is:
* 0-N block arguments at the bottom
* 0-N positional arguments next (left-to-right)
* 0-N named arguments next
*/
class VMArgumentsImpl {
constructor() {
this.stack = null;
this.positional = new PositionalArgumentsImpl();
this.named = new NamedArgumentsImpl();
this.blocks = new BlockArgumentsImpl();
}
empty(stack) {
var base = stack[REGISTERS][_vm2.$sp] + 1;
this.named.empty(stack, base);
this.positional.empty(stack, base);
this.blocks.empty(stack, base);
return this;
}
setup(stack, names, blockNames, positionalCount, atNames) {
this.stack = stack;
/*
| ... | blocks | positional | named |
| ... | b0 b1 | p0 p1 p2 p3 | n0 n1 |
index | ... | 4/5/6 7/8/9 | 10 11 12 13 | 14 15 |
^ ^ ^ ^
bbase pbase nbase sp
*/
var named = this.named;
var namedCount = names.length;
var namedBase = stack[REGISTERS][_vm2.$sp] - namedCount + 1;
named.setup(stack, namedBase, namedCount, names, atNames);
var positional = this.positional;
var positionalBase = namedBase - positionalCount;
positional.setup(stack, positionalBase, positionalCount);
var blocks = this.blocks;
var blocksCount = blockNames.length;
var blocksBase = positionalBase - blocksCount * 3;
blocks.setup(stack, blocksBase, blocksCount, blockNames);
}
get base() {
return this.blocks.base;
}
get length() {
return this.positional.length + this.named.length + this.blocks.length * 3;
}
at(pos) {
return this.positional.at(pos);
}
realloc(offset) {
var {
stack
} = this;
if (offset > 0 && stack !== null) {
var {
positional,
named
} = this;
var newBase = positional.base + offset;
var length = positional.length + named.length;
for (var i = length - 1; i >= 0; i--) {
stack.copy(i + positional.base, i + newBase);
}
positional.base += offset;
named.base += offset;
stack[REGISTERS][_vm2.$sp] += offset;
}
}
capture() {
var positional = this.positional.length === 0 ? EMPTY_POSITIONAL : this.positional.capture();
var named = this.named.length === 0 ? EMPTY_NAMED : this.named.capture();
return {
named,
positional
};
}
clear() {
var {
stack,
length
} = this;
if (length > 0 && stack !== null) stack.pop(length);
}
}
var EMPTY_REFERENCES = (0, _util.emptyArray)();
class PositionalArgumentsImpl {
constructor() {
this.base = 0;
this.length = 0;
this.stack = null;
this._references = null;
}
empty(stack, base) {
this.stack = stack;
this.base = base;
this.length = 0;
this._references = EMPTY_REFERENCES;
}
setup(stack, base, length) {
this.stack = stack;
this.base = base;
this.length = length;
if (length === 0) {
this._references = EMPTY_REFERENCES;
} else {
this._references = null;
}
}
at(position) {
var {
base,
length,
stack
} = this;
if (position < 0 || position >= length) {
return _reference.UNDEFINED_REFERENCE;
}
return stack.get(position, base);
}
capture() {
return this.references;
}
prepend(other) {
var additions = other.length;
if (additions > 0) {
var {
base,
length,
stack
} = this;
this.base = base = base - additions;
this.length = length + additions;
for (var i = 0; i < additions; i++) {
stack.set(other[i], i, base);
}
this._references = null;
}
}
get references() {
var references = this._references;
if (!references) {
var {
stack,
base,
length
} = this;
references = this._references = stack.slice(base, base + length);
}
return references;
}
}
class NamedArgumentsImpl {
constructor() {
this.base = 0;
this.length = 0;
this._references = null;
this._names = _util.EMPTY_STRING_ARRAY;
this._atNames = _util.EMPTY_STRING_ARRAY;
}
empty(stack, base) {
this.stack = stack;
this.base = base;
this.length = 0;
this._references = EMPTY_REFERENCES;
this._names = _util.EMPTY_STRING_ARRAY;
this._atNames = _util.EMPTY_STRING_ARRAY;
}
setup(stack, base, length, names, atNames) {
this.stack = stack;
this.base = base;
this.length = length;
if (length === 0) {
this._references = EMPTY_REFERENCES;
this._names = _util.EMPTY_STRING_ARRAY;
this._atNames = _util.EMPTY_STRING_ARRAY;
} else {
this._references = null;
if (atNames) {
this._names = null;
this._atNames = names;
} else {
this._names = names;
this._atNames = null;
}
}
}
get names() {
var names = this._names;
if (!names) {
names = this._names = this._atNames.map(this.toSyntheticName);
}
return names;
}
get atNames() {
var atNames = this._atNames;
if (!atNames) {
atNames = this._atNames = this._names.map(this.toAtName);
}
return atNames;
}
has(name) {
return this.names.indexOf(name) !== -1;
}
get(name, atNames = false) {
var {
base,
stack
} = this;
var names = atNames ? this.atNames : this.names;
var idx = names.indexOf(name);
if (idx === -1) {
return _reference.UNDEFINED_REFERENCE;
}
var ref = stack.get(idx, base);
if (true
/* DEBUG */
) {
return (0, _reference.createDebugAliasRef)(atNames ? name : `@${name}`, ref);
} else {
return ref;
}
}
capture() {
var {
names,
references
} = this;
var map = (0, _util.dict)();
for (var i = 0; i < names.length; i++) {
var name = names[i];
if (true
/* DEBUG */
) {
map[name] = (0, _reference.createDebugAliasRef)(`@${name}`, references[i]);
} else {
map[name] = references[i];
}
}
return map;
}
merge(other) {
var keys = Object.keys(other);
if (keys.length > 0) {
var {
names,
length,
stack
} = this;
var newNames = names.slice();
for (var i = 0; i < keys.length; i++) {
var name = keys[i];
var idx = newNames.indexOf(name);
if (idx === -1) {
length = newNames.push(name);
stack.push(other[name]);
}
}
this.length = length;
this._references = null;
this._names = newNames;
this._atNames = null;
}
}
get references() {
var references = this._references;
if (!references) {
var {
base,
length,
stack
} = this;
references = this._references = stack.slice(base, base + length);
}
return references;
}
toSyntheticName(name) {
return name.slice(1);
}
toAtName(name) {
return `@${name}`;
}
}
function toSymbolName(name) {
return `&${name}`;
}
var EMPTY_BLOCK_VALUES = (0, _util.emptyArray)();
class BlockArgumentsImpl {
constructor() {
this.internalValues = null;
this._symbolNames = null;
this.internalTag = null;
this.names = _util.EMPTY_STRING_ARRAY;
this.length = 0;
this.base = 0;
}
empty(stack, base) {
this.stack = stack;
this.names = _util.EMPTY_STRING_ARRAY;
this.base = base;
this.length = 0;
this._symbolNames = null;
this.internalTag = _validator.CONSTANT_TAG;
this.internalValues = EMPTY_BLOCK_VALUES;
}
setup(stack, base, length, names) {
this.stack = stack;
this.names = names;
this.base = base;
this.length = length;
this._symbolNames = null;
if (length === 0) {
this.internalTag = _validator.CONSTANT_TAG;
this.internalValues = EMPTY_BLOCK_VALUES;
} else {
this.internalTag = null;
this.internalValues = null;
}
}
get values() {
var values = this.internalValues;
if (!values) {
var {
base,
length,
stack
} = this;
values = this.internalValues = stack.slice(base, base + length * 3);
}
return values;
}
has(name) {
return this.names.indexOf(name) !== -1;
}
get(name) {
var idx = this.names.indexOf(name);
if (idx === -1) {
return null;
}
var {
base,
stack
} = this;
var table = stack.get(idx * 3, base);
var scope = stack.get(idx * 3 + 1, base);
var handle = stack.get(idx * 3 + 2, base);
return handle === null ? null : [handle, scope, table];
}
capture() {
return new CapturedBlockArgumentsImpl(this.names, this.values);
}
get symbolNames() {
var symbolNames = this._symbolNames;
if (symbolNames === null) {
symbolNames = this._symbolNames = this.names.map(toSymbolName);
}
return symbolNames;
}
}
class CapturedBlockArgumentsImpl {
constructor(names, values) {
this.names = names;
this.values = values;
this.length = names.length;
}
has(name) {
return this.names.indexOf(name) !== -1;
}
get(name) {
var idx = this.names.indexOf(name);
if (idx === -1) return null;
return [this.values[idx * 3 + 2], this.values[idx * 3 + 1], this.values[idx * 3]];
}
}
function createCapturedArgs(named, positional) {
return {
named,
positional
};
}
function reifyNamed$1(named) {
var reified = (0, _util.dict)();
for (var key in named) {
reified[key] = (0, _reference.valueForRef)(named[key]);
}
return reified;
}
function reifyPositional$1(positional) {
return positional.map(_reference.valueForRef);
}
function reifyArgs(args) {
return {
named: reifyNamed$1(args.named),
positional: reifyPositional$1(args.positional)
};
}
var EMPTY_NAMED = Object.freeze(Object.create(null));
_exports.EMPTY_NAMED = EMPTY_NAMED;
var EMPTY_POSITIONAL = EMPTY_REFERENCES;
_exports.EMPTY_POSITIONAL = EMPTY_POSITIONAL;
var EMPTY_ARGS = createCapturedArgs(EMPTY_NAMED, EMPTY_POSITIONAL);
_exports.EMPTY_ARGS = EMPTY_ARGS;
APPEND_OPCODES.add(77
/* Curry */
, (vm, {
op1: type,
op2: _isStrict
}) => {
var stack = vm.stack;
var definition = stack.pop();
var capturedArgs = stack.pop();
var owner = vm.getOwner();
var resolver = vm.runtime.resolver;
var isStrict = false;
if (true
/* DEBUG */
) {
// strict check only happens in DEBUG builds, no reason to load it otherwise
isStrict = vm[CONSTANTS].getValue((0, _util.decodeHandle)(_isStrict));
}
vm.loadValue(_vm2.$v0, createCurryRef(type, definition, owner, capturedArgs, resolver, isStrict));
});
APPEND_OPCODES.add(107
/* DynamicHelper */
, vm => {
var stack = vm.stack;
var ref = stack.pop();
var args = stack.pop().capture();
var helperRef;
var initialOwner = vm.getOwner();
var helperInstanceRef = (0, _reference.createComputeRef)(() => {
if (helperRef !== undefined) {
(0, _destroyable2.destroy)(helperRef);
}
var definition = (0, _reference.valueForRef)(ref);
if (isCurriedType(definition, 1
/* Helper */
)) {
var {
definition: resolvedDef,
owner,
positional,
named
} = resolveCurriedValue(definition);
var _helper = resolveHelper(vm[CONSTANTS], resolvedDef, ref);
if (named !== undefined) {
args.named = (0, _util.assign)({}, ...named, args.named);
}
if (positional !== undefined) {
args.positional = positional.concat(args.positional);
}
helperRef = _helper(args, owner);
(0, _destroyable2.associateDestroyableChild)(helperInstanceRef, helperRef);
} else if ((0, _util.isObject)(definition)) {
var _helper2 = resolveHelper(vm[CONSTANTS], definition, ref);
helperRef = _helper2(args, initialOwner);
if ((0, _destroyable2._hasDestroyableChildren)(helperRef)) {
(0, _destroyable2.associateDestroyableChild)(helperInstanceRef, helperRef);
}
} else {
helperRef = _reference.UNDEFINED_REFERENCE;
}
});
var helperValueRef = (0, _reference.createComputeRef)(() => {
(0, _reference.valueForRef)(helperInstanceRef);
return (0, _reference.valueForRef)(helperRef);
});
vm.associateDestroyable(helperInstanceRef);
vm.loadValue(_vm2.$v0, helperValueRef);
});
function resolveHelper(constants, definition, ref) {
var handle = constants.helper(definition, null, true);
if (true
/* DEBUG */
&& handle === null) {
throw new Error(`Expected a dynamic helper definition, but received an object or function that did not have a helper manager associated with it. The dynamic invocation was \`{{${ref.debugLabel}}}\` or \`(${ref.debugLabel})\`, and the incorrect definition is the value at the path \`${ref.debugLabel}\`, which was: ${(0, _util.debugToString)(definition)}`);
}
return constants.getValue(handle);
}
APPEND_OPCODES.add(16
/* Helper */
, (vm, {
op1: handle
}) => {
var stack = vm.stack;
var helper = vm[CONSTANTS].getValue(handle);
var args = stack.pop();
var value = helper(args.capture(), vm.getOwner(), vm.dynamicScope());
if ((0, _destroyable2._hasDestroyableChildren)(value)) {
vm.associateDestroyable(value);
}
vm.loadValue(_vm2.$v0, value);
});
APPEND_OPCODES.add(21
/* GetVariable */
, (vm, {
op1: symbol$$1
}) => {
var expr = vm.referenceForSymbol(symbol$$1);
vm.stack.push(expr);
});
APPEND_OPCODES.add(19
/* SetVariable */
, (vm, {
op1: symbol$$1
}) => {
var expr = vm.stack.pop();
vm.scope().bindSymbol(symbol$$1, expr);
});
APPEND_OPCODES.add(20
/* SetBlock */
, (vm, {
op1: symbol$$1
}) => {
var handle = vm.stack.pop();
var scope = vm.stack.pop();
var table = vm.stack.pop();
vm.scope().bindBlock(symbol$$1, [handle, scope, table]);
});
APPEND_OPCODES.add(102
/* ResolveMaybeLocal */
, (vm, {
op1: _name
}) => {
var name = vm[CONSTANTS].getValue(_name);
var locals = vm.scope().getPartialMap();
var ref = locals[name];
if (ref === undefined) {
ref = (0, _reference.childRefFor)(vm.getSelf(), name);
}
vm.stack.push(ref);
});
APPEND_OPCODES.add(37
/* RootScope */
, (vm, {
op1: symbols
}) => {
vm.pushRootScope(symbols, vm.getOwner());
});
APPEND_OPCODES.add(22
/* GetProperty */
, (vm, {
op1: _key
}) => {
var key = vm[CONSTANTS].getValue(_key);
var expr = vm.stack.pop();
vm.stack.push((0, _reference.childRefFor)(expr, key));
});
APPEND_OPCODES.add(23
/* GetBlock */
, (vm, {
op1: _block
}) => {
var {
stack
} = vm;
var block = vm.scope().getBlock(_block);
stack.push(block);
});
APPEND_OPCODES.add(24
/* SpreadBlock */
, vm => {
var {
stack
} = vm;
var block = stack.pop();
if (block && !isUndefinedReference(block)) {
var [handleOrCompilable, scope, table] = block;
stack.push(table);
stack.push(scope);
stack.push(handleOrCompilable);
} else {
stack.push(null);
stack.push(null);
stack.push(null);
}
});
function isUndefinedReference(input) {
return input === _reference.UNDEFINED_REFERENCE;
}
APPEND_OPCODES.add(25
/* HasBlock */
, vm => {
var {
stack
} = vm;
var block = stack.pop();
if (block && !isUndefinedReference(block)) {
stack.push(_reference.TRUE_REFERENCE);
} else {
stack.push(_reference.FALSE_REFERENCE);
}
});
APPEND_OPCODES.add(26
/* HasBlockParams */
, vm => {
// FIXME(mmun): should only need to push the symbol table
var block = vm.stack.pop();
var scope = vm.stack.pop();
var table = vm.stack.pop();
var hasBlockParams = table && table.parameters.length;
vm.stack.push(hasBlockParams ? _reference.TRUE_REFERENCE : _reference.FALSE_REFERENCE);
});
APPEND_OPCODES.add(27
/* Concat */
, (vm, {
op1: count
}) => {
var out = new Array(count);
for (var i = count; i > 0; i--) {
var offset = i - 1;
out[offset] = vm.stack.pop();
}
vm.stack.push(createConcatRef(out));
});
APPEND_OPCODES.add(109
/* IfInline */
, vm => {
var condition = vm.stack.pop();
var truthy = vm.stack.pop();
var falsy = vm.stack.pop();
vm.stack.push((0, _reference.createComputeRef)(() => {
if ((0, _globalContext.toBool)((0, _reference.valueForRef)(condition)) === true) {
return (0, _reference.valueForRef)(truthy);
} else {
return (0, _reference.valueForRef)(falsy);
}
}));
});
APPEND_OPCODES.add(110
/* Not */
, vm => {
var ref = vm.stack.pop();
vm.stack.push((0, _reference.createComputeRef)(() => {
return !(0, _globalContext.toBool)((0, _reference.valueForRef)(ref));
}));
});
APPEND_OPCODES.add(111
/* GetDynamicVar */
, vm => {
var scope = vm.dynamicScope();
var stack = vm.stack;
var nameRef = stack.pop();
stack.push((0, _reference.createComputeRef)(() => {
var name = String((0, _reference.valueForRef)(nameRef));
return (0, _reference.valueForRef)(scope.get(name));
}));
});
APPEND_OPCODES.add(112
/* Log */
, vm => {
var {
positional
} = vm.stack.pop().capture();
vm.loadValue(_vm2.$v0, (0, _reference.createComputeRef)(() => {
// eslint-disable-next-line no-console
console.log(...reifyPositional$1(positional));
}));
});
function resolveComponent(resolver, constants, name, owner) {
var definition = resolver.lookupComponent(name, owner);
if (true
/* DEBUG */
&& !definition) {
throw new Error(`Attempted to resolve \`${name}\`, which was expected to be a component, but nothing was found.`);
}
return constants.resolvedComponent(definition, name);
}
/** @internal */
function hasCustomDebugRenderTreeLifecycle(manager) {
return 'getDebugCustomRenderTree' in manager;
}
function createClassListRef(list) {
return (0, _reference.createComputeRef)(() => {
var ret = [];
for (var i = 0; i < list.length; i++) {
var ref = list[i];
var value = normalizeStringValue(typeof ref === 'string' ? ref : (0, _reference.valueForRef)(list[i]));
if (value) ret.push(value);
}
return ret.length === 0 ? null : ret.join(' ');
});
}
APPEND_OPCODES.add(39
/* ChildScope */
, vm => vm.pushChildScope());
APPEND_OPCODES.add(40
/* PopScope */
, vm => vm.popScope());
APPEND_OPCODES.add(59
/* PushDynamicScope */
, vm => vm.pushDynamicScope());
APPEND_OPCODES.add(60
/* PopDynamicScope */
, vm => vm.popDynamicScope());
APPEND_OPCODES.add(28
/* Constant */
, (vm, {
op1: other
}) => {
vm.stack.push(vm[CONSTANTS].getValue((0, _util.decodeHandle)(other)));
});
APPEND_OPCODES.add(29
/* ConstantReference */
, (vm, {
op1: other
}) => {
vm.stack.push((0, _reference.createConstRef)(vm[CONSTANTS].getValue((0, _util.decodeHandle)(other)), false));
});
APPEND_OPCODES.add(30
/* Primitive */
, (vm, {
op1: primitive
}) => {
var stack = vm.stack;
if ((0, _util.isHandle)(primitive)) {
// it is a handle which does not already exist on the stack
var value = vm[CONSTANTS].getValue((0, _util.decodeHandle)(primitive));
stack.push(value);
} else {
// is already an encoded immediate or primitive handle
stack.push((0, _util.decodeImmediate)(primitive));
}
});
APPEND_OPCODES.add(31
/* PrimitiveReference */
, vm => {
var stack = vm.stack;
var value = stack.pop();
var ref;
if (value === undefined) {
ref = _reference.UNDEFINED_REFERENCE;
} else if (value === null) {
ref = _reference.NULL_REFERENCE;
} else if (value === true) {
ref = _reference.TRUE_REFERENCE;
} else if (value === false) {
ref = _reference.FALSE_REFERENCE;
} else {
ref = (0, _reference.createPrimitiveRef)(value);
}
stack.push(ref);
});
APPEND_OPCODES.add(33
/* Dup */
, (vm, {
op1: register,
op2: offset
}) => {
var position = vm.fetchValue(register) - offset;
vm.stack.dup(position);
});
APPEND_OPCODES.add(34
/* Pop */
, (vm, {
op1: count
}) => {
vm.stack.pop(count);
});
APPEND_OPCODES.add(35
/* Load */
, (vm, {
op1: register
}) => {
vm.load(register);
});
APPEND_OPCODES.add(36
/* Fetch */
, (vm, {
op1: register
}) => {
vm.fetch(register);
});
APPEND_OPCODES.add(58
/* BindDynamicScope */
, (vm, {
op1: _names
}) => {
var names = vm[CONSTANTS].getArray(_names);
vm.bindDynamicScope(names);
});
APPEND_OPCODES.add(69
/* Enter */
, (vm, {
op1: args
}) => {
vm.enter(args);
});
APPEND_OPCODES.add(70
/* Exit */
, vm => {
vm.exit();
});
APPEND_OPCODES.add(63
/* PushSymbolTable */
, (vm, {
op1: _table
}) => {
var stack = vm.stack;
stack.push(vm[CONSTANTS].getValue(_table));
});
APPEND_OPCODES.add(62
/* PushBlockScope */
, vm => {
var stack = vm.stack;
stack.push(vm.scope());
});
APPEND_OPCODES.add(61
/* CompileBlock */
, vm => {
var stack = vm.stack;
var block = stack.pop();
if (block) {
stack.push(vm.compile(block));
} else {
stack.push(null);
}
});
APPEND_OPCODES.add(64
/* InvokeYield */
, vm => {
var {
stack
} = vm;
var handle = stack.pop();
var scope = stack.pop();
var table = stack.pop();
var args = stack.pop();
if (table === null) {
// To balance the pop{Frame,Scope}
vm.pushFrame();
vm.pushScope(scope !== null && scope !== void 0 ? scope : vm.scope());
return;
}
var invokingScope = scope; // If necessary, create a child scope
{
var locals = table.parameters;
var localsCount = locals.length;
if (localsCount > 0) {
invokingScope = invokingScope.child();
for (var i = 0; i < localsCount; i++) {
invokingScope.bindSymbol(locals[i], args.at(i));
}
}
}
vm.pushFrame();
vm.pushScope(invokingScope);
vm.call(handle);
});
APPEND_OPCODES.add(65
/* JumpIf */
, (vm, {
op1: target
}) => {
var reference = vm.stack.pop();
var value = Boolean((0, _reference.valueForRef)(reference));
if ((0, _reference.isConstRef)(reference)) {
if (value === true) {
vm.goto(target);
}
} else {
if (value === true) {
vm.goto(target);
}
vm.updateWith(new Assert(reference));
}
});
APPEND_OPCODES.add(66
/* JumpUnless */
, (vm, {
op1: target
}) => {
var reference = vm.stack.pop();
var value = Boolean((0, _reference.valueForRef)(reference));
if ((0, _reference.isConstRef)(reference)) {
if (value === false) {
vm.goto(target);
}
} else {
if (value === false) {
vm.goto(target);
}
vm.updateWith(new Assert(reference));
}
});
APPEND_OPCODES.add(67
/* JumpEq */
, (vm, {
op1: target,
op2: comparison
}) => {
var other = vm.stack.peek();
if (other === comparison) {
vm.goto(target);
}
});
APPEND_OPCODES.add(68
/* AssertSame */
, vm => {
var reference = vm.stack.peek();
if ((0, _reference.isConstRef)(reference) === false) {
vm.updateWith(new Assert(reference));
}
});
APPEND_OPCODES.add(71
/* ToBoolean */
, vm => {
var {
stack
} = vm;
var valueRef = stack.pop();
stack.push((0, _reference.createComputeRef)(() => (0, _globalContext.toBool)((0, _reference.valueForRef)(valueRef))));
});
class Assert {
constructor(ref) {
this.ref = ref;
this.last = (0, _reference.valueForRef)(ref);
}
evaluate(vm) {
var {
last,
ref
} = this;
var current = (0, _reference.valueForRef)(ref);
if (last !== current) {
vm.throw();
}
}
}
class AssertFilter {
constructor(ref, filter) {
this.ref = ref;
this.filter = filter;
this.last = filter((0, _reference.valueForRef)(ref));
}
evaluate(vm) {
var {
last,
ref,
filter
} = this;
var current = filter((0, _reference.valueForRef)(ref));
if (last !== current) {
vm.throw();
}
}
}
class JumpIfNotModifiedOpcode {
constructor() {
this.tag = _validator.CONSTANT_TAG;
this.lastRevision = _validator.INITIAL;
}
finalize(tag, target) {
this.target = target;
this.didModify(tag);
}
evaluate(vm) {
var {
tag,
target,
lastRevision
} = this;
if (!vm.alwaysRevalidate && (0, _validator.validateTag)(tag, lastRevision)) {
(0, _validator.consumeTag)(tag);
vm.goto(target);
}
}
didModify(tag) {
this.tag = tag;
this.lastRevision = (0, _validator.valueForTag)(this.tag);
(0, _validator.consumeTag)(tag);
}
}
class BeginTrackFrameOpcode {
constructor(debugLabel) {
this.debugLabel = debugLabel;
}
evaluate() {
(0, _validator.beginTrackFrame)(this.debugLabel);
}
}
class EndTrackFrameOpcode {
constructor(target) {
this.target = target;
}
evaluate() {
var tag = (0, _validator.endTrackFrame)();
this.target.didModify(tag);
}
}
APPEND_OPCODES.add(41
/* Text */
, (vm, {
op1: text
}) => {
vm.elements().appendText(vm[CONSTANTS].getValue(text));
});
APPEND_OPCODES.add(42
/* Comment */
, (vm, {
op1: text
}) => {
vm.elements().appendComment(vm[CONSTANTS].getValue(text));
});
APPEND_OPCODES.add(48
/* OpenElement */
, (vm, {
op1: tag
}) => {
vm.elements().openElement(vm[CONSTANTS].getValue(tag));
});
APPEND_OPCODES.add(49
/* OpenDynamicElement */
, vm => {
var tagName = (0, _reference.valueForRef)(vm.stack.pop());
vm.elements().openElement(tagName);
});
APPEND_OPCODES.add(50
/* PushRemoteElement */
, vm => {
var elementRef = vm.stack.pop();
var insertBeforeRef = vm.stack.pop();
var guidRef = vm.stack.pop();
var element = (0, _reference.valueForRef)(elementRef);
var insertBefore = (0, _reference.valueForRef)(insertBeforeRef);
var guid = (0, _reference.valueForRef)(guidRef);
if (!(0, _reference.isConstRef)(elementRef)) {
vm.updateWith(new Assert(elementRef));
}
if (insertBefore !== undefined && !(0, _reference.isConstRef)(insertBeforeRef)) {
vm.updateWith(new Assert(insertBeforeRef));
}
var block = vm.elements().pushRemoteElement(element, guid, insertBefore);
if (block) vm.associateDestroyable(block);
});
APPEND_OPCODES.add(56
/* PopRemoteElement */
, vm => {
vm.elements().popRemoteElement();
});
APPEND_OPCODES.add(54
/* FlushElement */
, vm => {
var operations = vm.fetchValue(_vm2.$t0);
var modifiers = null;
if (operations) {
modifiers = operations.flush(vm);
vm.loadValue(_vm2.$t0, null);
}
vm.elements().flushElement(modifiers);
});
APPEND_OPCODES.add(55
/* CloseElement */
, vm => {
var modifiers = vm.elements().closeElement();
if (modifiers) {
modifiers.forEach(modifier => {
vm.env.scheduleInstallModifier(modifier);
var {
manager,
state
} = modifier;
var d = manager.getDestroyable(state);
if (d) {
vm.associateDestroyable(d);
}
});
}
});
APPEND_OPCODES.add(57
/* Modifier */
, (vm, {
op1: handle
}) => {
if (vm.env.isInteractive === false) {
return;
}
var owner = vm.getOwner();
var args = vm.stack.pop();
var definition = vm[CONSTANTS].getValue(handle);
var {
manager
} = definition;
var {
constructing
} = vm.elements();
var state = manager.create(owner, constructing, definition.state, args.capture());
var instance = {
manager,
state,
definition
};
var operations = vm.fetchValue(_vm2.$t0);
operations.addModifier(instance);
var tag = manager.getTag(state);
if (tag !== null) {
(0, _validator.consumeTag)(tag);
return vm.updateWith(new UpdateModifierOpcode(tag, instance));
}
});
APPEND_OPCODES.add(108
/* DynamicModifier */
, vm => {
if (vm.env.isInteractive === false) {
return;
}
var {
stack,
[CONSTANTS]: constants
} = vm;
var ref = stack.pop();
var args = stack.pop().capture();
var {
constructing
} = vm.elements();
var initialOwner = vm.getOwner();
var instanceRef = (0, _reference.createComputeRef)(() => {
var value = (0, _reference.valueForRef)(ref);
var owner;
if (!(0, _util.isObject)(value)) {
return;
}
var hostDefinition;
if (isCurriedType(value, 2
/* Modifier */
)) {
var {
definition: resolvedDefinition,
owner: curriedOwner,
positional,
named
} = resolveCurriedValue(value);
hostDefinition = resolvedDefinition;
owner = curriedOwner;
if (positional !== undefined) {
args.positional = positional.concat(args.positional);
}
if (named !== undefined) {
args.named = (0, _util.assign)({}, ...named, args.named);
}
} else {
hostDefinition = value;
owner = initialOwner;
}
var handle = constants.modifier(hostDefinition, null, true);
if (true
/* DEBUG */
&& handle === null) {
throw new Error(`Expected a dynamic modifier definition, but received an object or function that did not have a modifier manager associated with it. The dynamic invocation was \`{{${ref.debugLabel}}}\`, and the incorrect definition is the value at the path \`${ref.debugLabel}\`, which was: ${(0, _util.debugToString)(hostDefinition)}`);
}
var definition = constants.getValue(handle);
var {
manager
} = definition;
var state = manager.create(owner, constructing, definition.state, args);
return {
manager,
state,
definition
};
});
var instance = (0, _reference.valueForRef)(instanceRef);
var tag = null;
if (instance !== undefined) {
var operations = vm.fetchValue(_vm2.$t0);
operations.addModifier(instance);
tag = instance.manager.getTag(instance.state);
if (tag !== null) {
(0, _validator.consumeTag)(tag);
}
}
if (!(0, _reference.isConstRef)(ref) || tag) {
return vm.updateWith(new UpdateDynamicModifierOpcode(tag, instance, instanceRef));
}
});
class UpdateModifierOpcode {
constructor(tag, modifier) {
this.tag = tag;
this.modifier = modifier;
this.lastUpdated = (0, _validator.valueForTag)(tag);
}
evaluate(vm) {
var {
modifier,
tag,
lastUpdated
} = this;
(0, _validator.consumeTag)(tag);
if (!(0, _validator.validateTag)(tag, lastUpdated)) {
vm.env.scheduleUpdateModifier(modifier);
this.lastUpdated = (0, _validator.valueForTag)(tag);
}
}
}
class UpdateDynamicModifierOpcode {
constructor(tag, instance, instanceRef) {
this.tag = tag;
this.instance = instance;
this.instanceRef = instanceRef;
this.lastUpdated = (0, _validator.valueForTag)(tag !== null && tag !== void 0 ? tag : _validator.CURRENT_TAG);
}
evaluate(vm) {
var {
tag,
lastUpdated,
instance,
instanceRef
} = this;
var newInstance = (0, _reference.valueForRef)(instanceRef);
if (newInstance !== instance) {
if (instance !== undefined) {
var destroyable = instance.manager.getDestroyable(instance.state);
if (destroyable !== null) {
(0, _destroyable2.destroy)(destroyable);
}
}
if (newInstance !== undefined) {
var {
manager,
state
} = newInstance;
var _destroyable = manager.getDestroyable(state);
if (_destroyable !== null) {
(0, _destroyable2.associateDestroyableChild)(this, _destroyable);
}
tag = manager.getTag(state);
if (tag !== null) {
this.lastUpdated = (0, _validator.valueForTag)(tag);
}
this.tag = tag;
vm.env.scheduleInstallModifier(newInstance);
}
this.instance = newInstance;
} else if (tag !== null && !(0, _validator.validateTag)(tag, lastUpdated)) {
vm.env.scheduleUpdateModifier(instance);
this.lastUpdated = (0, _validator.valueForTag)(tag);
}
if (tag !== null) {
(0, _validator.consumeTag)(tag);
}
}
}
APPEND_OPCODES.add(51
/* StaticAttr */
, (vm, {
op1: _name,
op2: _value,
op3: _namespace
}) => {
var name = vm[CONSTANTS].getValue(_name);
var value = vm[CONSTANTS].getValue(_value);
var namespace = _namespace ? vm[CONSTANTS].getValue(_namespace) : null;
vm.elements().setStaticAttribute(name, value, namespace);
});
APPEND_OPCODES.add(52
/* DynamicAttr */
, (vm, {
op1: _name,
op2: _trusting,
op3: _namespace
}) => {
var name = vm[CONSTANTS].getValue(_name);
var trusting = vm[CONSTANTS].getValue(_trusting);
var reference = vm.stack.pop();
var value = (0, _reference.valueForRef)(reference);
var namespace = _namespace ? vm[CONSTANTS].getValue(_namespace) : null;
var attribute = vm.elements().setDynamicAttribute(name, value, trusting, namespace);
if (!(0, _reference.isConstRef)(reference)) {
vm.updateWith(new UpdateDynamicAttributeOpcode(reference, attribute, vm.env));
}
});
class UpdateDynamicAttributeOpcode {
constructor(reference, attribute, env) {
var initialized = false;
this.updateRef = (0, _reference.createComputeRef)(() => {
var value = (0, _reference.valueForRef)(reference);
if (initialized === true) {
attribute.update(value, env);
} else {
initialized = true;
}
});
(0, _reference.valueForRef)(this.updateRef);
}
evaluate() {
(0, _reference.valueForRef)(this.updateRef);
}
}
APPEND_OPCODES.add(78
/* PushComponentDefinition */
, (vm, {
op1: handle
}) => {
var definition = vm[CONSTANTS].getValue(handle);
var {
manager,
capabilities
} = definition;
var instance = {
definition,
manager,
capabilities,
state: null,
handle: null,
table: null,
lookup: null
};
vm.stack.push(instance);
});
APPEND_OPCODES.add(80
/* ResolveDynamicComponent */
, (vm, {
op1: _isStrict
}) => {
var stack = vm.stack;
var component = (0, _reference.valueForRef)(stack.pop());
var constants = vm[CONSTANTS];
var owner = vm.getOwner();
var isStrict = constants.getValue(_isStrict);
vm.loadValue(_vm2.$t1, null); // Clear the temp register
var definition;
if (typeof component === 'string') {
if (true
/* DEBUG */
&& isStrict) {
throw new Error(`Attempted to resolve a dynamic component with a string definition, \`${component}\` in a strict mode template. In strict mode, using strings to resolve component definitions is prohibited. You can instead import the component definition and use it directly.`);
}
var resolvedDefinition = resolveComponent(vm.runtime.resolver, constants, component, owner);
definition = resolvedDefinition;
} else if (isCurriedValue(component)) {
definition = component;
} else {
definition = constants.component(component, owner);
}
stack.push(definition);
});
APPEND_OPCODES.add(81
/* ResolveCurriedComponent */
, vm => {
var stack = vm.stack;
var ref = stack.pop();
var value = (0, _reference.valueForRef)(ref);
var constants = vm[CONSTANTS];
var definition;
if (true
/* DEBUG */
&& !(typeof value === 'function' || typeof value === 'object' && value !== null)) {
throw new Error(`Expected a component definition, but received ${value}. You may have accidentally done <${ref.debugLabel}>, where "${ref.debugLabel}" was a string instead of a curried component definition. You must either use the component definition directly, or use the {{component}} helper to create a curried component definition when invoking dynamically.`);
}
if (isCurriedValue(value)) {
definition = value;
} else {
definition = constants.component(value, vm.getOwner(), true);
if (true
/* DEBUG */
&& definition === null) {
throw new Error(`Expected a dynamic component definition, but received an object or function that did not have a component manager associated with it. The dynamic invocation was \`<${ref.debugLabel}>\` or \`{{${ref.debugLabel}}}\`, and the incorrect definition is the value at the path \`${ref.debugLabel}\`, which was: ${(0, _util.debugToString)(value)}`);
}
}
stack.push(definition);
});
APPEND_OPCODES.add(79
/* PushDynamicComponentInstance */
, vm => {
var {
stack
} = vm;
var definition = stack.pop();
var capabilities, manager;
if (isCurriedValue(definition)) {
manager = capabilities = null;
} else {
manager = definition.manager;
capabilities = definition.capabilities;
}
stack.push({
definition,
capabilities,
manager,
state: null,
handle: null,
table: null
});
});
APPEND_OPCODES.add(82
/* PushArgs */
, (vm, {
op1: _names,
op2: _blockNames,
op3: flags
}) => {
var stack = vm.stack;
var names = vm[CONSTANTS].getArray(_names);
var positionalCount = flags >> 4;
var atNames = flags & 0b1000;
var blockNames = flags & 0b0111 ? vm[CONSTANTS].getArray(_blockNames) : _util.EMPTY_STRING_ARRAY;
vm[ARGS].setup(stack, names, blockNames, positionalCount, !!atNames);
stack.push(vm[ARGS]);
});
APPEND_OPCODES.add(83
/* PushEmptyArgs */
, vm => {
var {
stack
} = vm;
stack.push(vm[ARGS].empty(stack));
});
APPEND_OPCODES.add(86
/* CaptureArgs */
, vm => {
var stack = vm.stack;
var args = stack.pop();
var capturedArgs = args.capture();
stack.push(capturedArgs);
});
APPEND_OPCODES.add(85
/* PrepareArgs */
, (vm, {
op1: _state
}) => {
var stack = vm.stack;
var instance = vm.fetchValue(_state);
var args = stack.pop();
var {
definition
} = instance;
if (isCurriedType(definition, 0
/* Component */
)) {
var constants = vm[CONSTANTS];
var {
definition: resolvedDefinition,
owner,
resolved,
positional,
named
} = resolveCurriedValue(definition);
if (resolved === true) {
definition = resolvedDefinition;
} else if (typeof resolvedDefinition === 'string') {
var resolvedValue = vm.runtime.resolver.lookupComponent(resolvedDefinition, owner);
definition = constants.resolvedComponent(resolvedValue, resolvedDefinition);
} else {
definition = constants.component(resolvedDefinition, owner);
}
if (named !== undefined) {
args.named.merge((0, _util.assign)({}, ...named));
}
if (positional !== undefined) {
args.realloc(positional.length);
args.positional.prepend(positional);
}
var {
manager: _manager
} = definition;
instance.definition = definition;
instance.manager = _manager;
instance.capabilities = definition.capabilities; // Save off the owner that this component was curried with. Later on,
// we'll fetch the value of this register and set it as the owner on the
// new root scope.
vm.loadValue(_vm2.$t1, owner);
}
var {
manager,
state
} = definition;
var capabilities = instance.capabilities;
if (!(0, _manager5.managerHasCapability)(manager, capabilities, 4
/* PrepareArgs */
)) {
stack.push(args);
return;
}
var blocks = args.blocks.values;
var blockNames = args.blocks.names;
var preparedArgs = manager.prepareArgs(state, args);
if (preparedArgs) {
args.clear();
for (var i = 0; i < blocks.length; i++) {
stack.push(blocks[i]);
}
var {
positional: _positional,
named: _named
} = preparedArgs;
var positionalCount = _positional.length;
for (var _i = 0; _i < positionalCount; _i++) {
stack.push(_positional[_i]);
}
var names = Object.keys(_named);
for (var _i2 = 0; _i2 < names.length; _i2++) {
stack.push(_named[names[_i2]]);
}
args.setup(stack, names, blockNames, positionalCount, false);
}
stack.push(args);
});
APPEND_OPCODES.add(87
/* CreateComponent */
, (vm, {
op1: flags,
op2: _state
}) => {
var instance = vm.fetchValue(_state);
var {
definition,
manager,
capabilities
} = instance;
if (!(0, _manager5.managerHasCapability)(manager, capabilities, 512
/* CreateInstance */
)) {
// TODO: Closure and Main components are always invoked dynamically, so this
// opcode may run even if this capability is not enabled. In the future we
// should handle this in a better way.
return;
}
var dynamicScope = null;
if ((0, _manager5.managerHasCapability)(manager, capabilities, 64
/* DynamicScope */
)) {
dynamicScope = vm.dynamicScope();
}
var hasDefaultBlock = flags & 1;
var args = null;
if ((0, _manager5.managerHasCapability)(manager, capabilities, 8
/* CreateArgs */
)) {
args = vm.stack.peek();
}
var self = null;
if ((0, _manager5.managerHasCapability)(manager, capabilities, 128
/* CreateCaller */
)) {
self = vm.getSelf();
}
var state = manager.create(vm.getOwner(), definition.state, args, vm.env, dynamicScope, self, !!hasDefaultBlock); // We want to reuse the `state` POJO here, because we know that the opcodes
// only transition at exactly one place.
instance.state = state;
if ((0, _manager5.managerHasCapability)(manager, capabilities, 256
/* UpdateHook */
)) {
vm.updateWith(new UpdateComponentOpcode(state, manager, dynamicScope));
}
});
APPEND_OPCODES.add(88
/* RegisterComponentDestructor */
, (vm, {
op1: _state
}) => {
var {
manager,
state,
capabilities
} = vm.fetchValue(_state);
var d = manager.getDestroyable(state);
if (true
/* DEBUG */
&& !(0, _manager5.managerHasCapability)(manager, capabilities, 2048
/* WillDestroy */
) && d !== null && typeof 'willDestroy' in d) {
throw new Error('BUG: Destructor has willDestroy, but the willDestroy capability was not enabled for this component. Pre-destruction hooks must be explicitly opted into');
}
if (d) vm.associateDestroyable(d);
});
APPEND_OPCODES.add(97
/* BeginComponentTransaction */
, (vm, {
op1: _state
}) => {
var _a;
var name;
if (true
/* DEBUG */
) {
var {
definition,
manager
} = vm.fetchValue(_state);
name = (_a = definition.resolvedName) !== null && _a !== void 0 ? _a : manager.getDebugName(definition.state);
}
vm.beginCacheGroup(name);
vm.elements().pushSimpleBlock();
});
APPEND_OPCODES.add(89
/* PutComponentOperations */
, vm => {
vm.loadValue(_vm2.$t0, new ComponentElementOperations());
});
APPEND_OPCODES.add(53
/* ComponentAttr */
, (vm, {
op1: _name,
op2: _trusting,
op3: _namespace
}) => {
var name = vm[CONSTANTS].getValue(_name);
var trusting = vm[CONSTANTS].getValue(_trusting);
var reference = vm.stack.pop();
var namespace = _namespace ? vm[CONSTANTS].getValue(_namespace) : null;
vm.fetchValue(_vm2.$t0).setAttribute(name, reference, trusting, namespace);
});
APPEND_OPCODES.add(105
/* StaticComponentAttr */
, (vm, {
op1: _name,
op2: _value,
op3: _namespace
}) => {
var name = vm[CONSTANTS].getValue(_name);
var value = vm[CONSTANTS].getValue(_value);
var namespace = _namespace ? vm[CONSTANTS].getValue(_namespace) : null;
vm.fetchValue(_vm2.$t0).setStaticAttribute(name, value, namespace);
});
class ComponentElementOperations {
constructor() {
this.attributes = (0, _util.dict)();
this.classes = [];
this.modifiers = [];
}
setAttribute(name, value, trusting, namespace) {
var deferred = {
value,
namespace,
trusting
};
if (name === 'class') {
this.classes.push(value);
}
this.attributes[name] = deferred;
}
setStaticAttribute(name, value, namespace) {
var deferred = {
value,
namespace
};
if (name === 'class') {
this.classes.push(value);
}
this.attributes[name] = deferred;
}
addModifier(modifier) {
this.modifiers.push(modifier);
}
flush(vm) {
var type;
var attributes = this.attributes;
for (var name in this.attributes) {
if (name === 'type') {
type = attributes[name];
continue;
}
var attr = this.attributes[name];
if (name === 'class') {
setDeferredAttr(vm, 'class', mergeClasses(this.classes), attr.namespace, attr.trusting);
} else {
setDeferredAttr(vm, name, attr.value, attr.namespace, attr.trusting);
}
}
if (type !== undefined) {
setDeferredAttr(vm, 'type', type.value, type.namespace, type.trusting);
}
return this.modifiers;
}
}
function mergeClasses(classes) {
if (classes.length === 0) {
return '';
}
if (classes.length === 1) {
return classes[0];
}
if (allStringClasses(classes)) {
return classes.join(' ');
}
return createClassListRef(classes);
}
function allStringClasses(classes) {
for (var i = 0; i < classes.length; i++) {
if (typeof classes[i] !== 'string') {
return false;
}
}
return true;
}
function setDeferredAttr(vm, name, value, namespace, trusting = false) {
if (typeof value === 'string') {
vm.elements().setStaticAttribute(name, value, namespace);
} else {
var attribute = vm.elements().setDynamicAttribute(name, (0, _reference.valueForRef)(value), trusting, namespace);
if (!(0, _reference.isConstRef)(value)) {
vm.updateWith(new UpdateDynamicAttributeOpcode(value, attribute, vm.env));
}
}
}
APPEND_OPCODES.add(99
/* DidCreateElement */
, (vm, {
op1: _state
}) => {
var {
definition,
state
} = vm.fetchValue(_state);
var {
manager
} = definition;
var operations = vm.fetchValue(_vm2.$t0);
manager.didCreateElement(state, vm.elements().constructing, operations);
});
APPEND_OPCODES.add(90
/* GetComponentSelf */
, (vm, {
op1: _state,
op2: _names
}) => {
var _a;
var instance = vm.fetchValue(_state);
var {
definition,
state
} = instance;
var {
manager
} = definition;
var selfRef = manager.getSelf(state);
if (vm.env.debugRenderTree !== undefined) {
var _instance = vm.fetchValue(_state);
var {
definition: _definition,
manager: _manager2
} = _instance;
var args;
if (vm.stack.peek() === vm[ARGS]) {
args = vm[ARGS].capture();
} else {
var names = vm[CONSTANTS].getArray(_names);
vm[ARGS].setup(vm.stack, names, [], 0, true);
args = vm[ARGS].capture();
}
var moduleName;
var compilable = _definition.compilable;
if (compilable === null) {
compilable = _manager2.getDynamicLayout(state, vm.runtime.resolver);
if (compilable !== null) {
moduleName = compilable.moduleName;
} else {
moduleName = '__default__.hbs';
}
} else {
moduleName = compilable.moduleName;
} // For tearing down the debugRenderTree
vm.associateDestroyable(_instance);
if (hasCustomDebugRenderTreeLifecycle(_manager2)) {
var nodes = _manager2.getDebugCustomRenderTree(_instance.definition.state, _instance.state, args, moduleName);
nodes.forEach(node => {
var {
bucket
} = node;
vm.env.debugRenderTree.create(bucket, node);
(0, _destroyable2.registerDestructor)(_instance, () => {
var _a;
(_a = vm.env.debugRenderTree) === null || _a === void 0 ? void 0 : _a.willDestroy(bucket);
});
vm.updateWith(new DebugRenderTreeUpdateOpcode(bucket));
});
} else {
var name = (_a = _definition.resolvedName) !== null && _a !== void 0 ? _a : _manager2.getDebugName(_definition.state);
vm.env.debugRenderTree.create(_instance, {
type: 'component',
name,
args,
template: moduleName,
instance: (0, _reference.valueForRef)(selfRef)
});
vm.associateDestroyable(_instance);
(0, _destroyable2.registerDestructor)(_instance, () => {
var _a;
(_a = vm.env.debugRenderTree) === null || _a === void 0 ? void 0 : _a.willDestroy(_instance);
});
vm.updateWith(new DebugRenderTreeUpdateOpcode(_instance));
}
}
vm.stack.push(selfRef);
});
APPEND_OPCODES.add(91
/* GetComponentTagName */
, (vm, {
op1: _state
}) => {
var {
definition,
state
} = vm.fetchValue(_state);
var {
manager
} = definition;
var tagName = manager.getTagName(state); // User provided value from JS, so we don't bother to encode
vm.stack.push(tagName);
}); // Dynamic Invocation Only
APPEND_OPCODES.add(92
/* GetComponentLayout */
, (vm, {
op1: _state
}) => {
var instance = vm.fetchValue(_state);
var {
manager,
definition
} = instance;
var {
stack
} = vm;
var {
compilable
} = definition;
if (compilable === null) {
var {
capabilities
} = instance;
compilable = manager.getDynamicLayout(instance.state, vm.runtime.resolver);
if (compilable === null) {
if ((0, _manager5.managerHasCapability)(manager, capabilities, 1024
/* Wrapped */
)) {
compilable = (0, _util.unwrapTemplate)(vm[CONSTANTS].defaultTemplate).asWrappedLayout();
} else {
compilable = (0, _util.unwrapTemplate)(vm[CONSTANTS].defaultTemplate).asLayout();
}
}
}
var handle = compilable.compile(vm.context);
stack.push(compilable.symbolTable);
stack.push(handle);
});
APPEND_OPCODES.add(75
/* Main */
, (vm, {
op1: register
}) => {
var definition = vm.stack.pop();
var invocation = vm.stack.pop();
var {
manager,
capabilities
} = definition;
var state = {
definition,
manager,
capabilities,
state: null,
handle: invocation.handle,
table: invocation.symbolTable,
lookup: null
};
vm.loadValue(register, state);
});
APPEND_OPCODES.add(95
/* PopulateLayout */
, (vm, {
op1: _state
}) => {
var {
stack
} = vm; // In DEBUG handles could be ErrHandle objects
var handle = stack.pop();
var table = stack.pop();
var state = vm.fetchValue(_state);
state.handle = handle;
state.table = table;
});
APPEND_OPCODES.add(38
/* VirtualRootScope */
, (vm, {
op1: _state
}) => {
var {
table,
manager,
capabilities,
state
} = vm.fetchValue(_state);
var owner;
if ((0, _manager5.managerHasCapability)(manager, capabilities, 4096
/* HasSubOwner */
)) {
owner = manager.getOwner(state);
vm.loadValue(_vm2.$t1, null); // Clear the temp register
} else {
// Check the temp register to see if an owner was resolved from currying
owner = vm.fetchValue(_vm2.$t1);
if (owner === null) {
// If an owner wasn't found, default to using the current owner. This
// will happen for normal dynamic component invocation,
// e.g. <SomeClassicEmberComponent/>
owner = vm.getOwner();
} else {
// Else the owner was found, so clear the temp register. This will happen
// if we are loading a curried component, e.g. <@someCurriedComponent/>
vm.loadValue(_vm2.$t1, null);
}
}
vm.pushRootScope(table.symbols.length + 1, owner);
});
APPEND_OPCODES.add(94
/* SetupForEval */
, (vm, {
op1: _state
}) => {
var state = vm.fetchValue(_state);
if (state.table.hasEval) {
var lookup = state.lookup = (0, _util.dict)();
vm.scope().bindEvalScope(lookup);
}
});
APPEND_OPCODES.add(17
/* SetNamedVariables */
, (vm, {
op1: _state
}) => {
var state = vm.fetchValue(_state);
var scope = vm.scope();
var args = vm.stack.peek();
var callerNames = args.named.atNames;
for (var i = callerNames.length - 1; i >= 0; i--) {
var atName = callerNames[i];
var symbol$$1 = state.table.symbols.indexOf(callerNames[i]);
var value = args.named.get(atName, true);
if (symbol$$1 !== -1) scope.bindSymbol(symbol$$1 + 1, value);
if (state.lookup) state.lookup[atName] = value;
}
});
function bindBlock(symbolName, blockName, state, blocks, vm) {
var symbol$$1 = state.table.symbols.indexOf(symbolName);
var block = blocks.get(blockName);
if (symbol$$1 !== -1) vm.scope().bindBlock(symbol$$1 + 1, block);
if (state.lookup) state.lookup[symbolName] = block;
}
APPEND_OPCODES.add(18
/* SetBlocks */
, (vm, {
op1: _state
}) => {
var state = vm.fetchValue(_state);
var {
blocks
} = vm.stack.peek();
for (var i = 0; i < blocks.names.length; i++) {
bindBlock(blocks.symbolNames[i], blocks.names[i], state, blocks, vm);
}
}); // Dynamic Invocation Only
APPEND_OPCODES.add(96
/* InvokeComponentLayout */
, (vm, {
op1: _state
}) => {
var state = vm.fetchValue(_state);
vm.call(state.handle);
});
APPEND_OPCODES.add(100
/* DidRenderLayout */
, (vm, {
op1: _state
}) => {
var instance = vm.fetchValue(_state);
var {
manager,
state,
capabilities
} = instance;
var bounds = vm.elements().popBlock();
if (vm.env.debugRenderTree !== undefined) {
if (hasCustomDebugRenderTreeLifecycle(manager)) {
var nodes = manager.getDebugCustomRenderTree(instance.definition.state, state, EMPTY_ARGS);
nodes.reverse().forEach(node => {
var {
bucket
} = node;
vm.env.debugRenderTree.didRender(bucket, bounds);
vm.updateWith(new DebugRenderTreeDidRenderOpcode(bucket, bounds));
});
} else {
vm.env.debugRenderTree.didRender(instance, bounds);
vm.updateWith(new DebugRenderTreeDidRenderOpcode(instance, bounds));
}
}
if ((0, _manager5.managerHasCapability)(manager, capabilities, 512
/* CreateInstance */
)) {
var mgr = manager;
mgr.didRenderLayout(state, bounds);
vm.env.didCreate(instance);
vm.updateWith(new DidUpdateLayoutOpcode(instance, bounds));
}
});
APPEND_OPCODES.add(98
/* CommitComponentTransaction */
, vm => {
vm.commitCacheGroup();
});
class UpdateComponentOpcode {
constructor(component, manager, dynamicScope) {
this.component = component;
this.manager = manager;
this.dynamicScope = dynamicScope;
}
evaluate(_vm) {
var {
component,
manager,
dynamicScope
} = this;
manager.update(component, dynamicScope);
}
}
class DidUpdateLayoutOpcode {
constructor(component, bounds) {
this.component = component;
this.bounds = bounds;
}
evaluate(vm) {
var {
component,
bounds
} = this;
var {
manager,
state
} = component;
manager.didUpdateLayout(state, bounds);
vm.env.didUpdate(component);
}
}
class DebugRenderTreeUpdateOpcode {
constructor(bucket) {
this.bucket = bucket;
}
evaluate(vm) {
var _a;
(_a = vm.env.debugRenderTree) === null || _a === void 0 ? void 0 : _a.update(this.bucket);
}
}
class DebugRenderTreeDidRenderOpcode {
constructor(bucket, bounds) {
this.bucket = bucket;
this.bounds = bounds;
}
evaluate(vm) {
var _a;
(_a = vm.env.debugRenderTree) === null || _a === void 0 ? void 0 : _a.didRender(this.bucket, this.bounds);
}
}
class DynamicTextContent {
constructor(node, reference, lastValue) {
this.node = node;
this.reference = reference;
this.lastValue = lastValue;
}
evaluate() {
var value = (0, _reference.valueForRef)(this.reference);
var {
lastValue
} = this;
if (value === lastValue) return;
var normalized;
if (isEmpty(value)) {
normalized = '';
} else if (isString(value)) {
normalized = value;
} else {
normalized = String(value);
}
if (normalized !== lastValue) {
var textNode = this.node;
textNode.nodeValue = this.lastValue = normalized;
}
}
}
function toContentType(value) {
if (shouldCoerce(value)) {
return 2
/* String */
;
} else if (isCurriedType(value, 0
/* Component */
) || (0, _manager5.hasInternalComponentManager)(value)) {
return 0
/* Component */
;
} else if (isCurriedType(value, 1
/* Helper */
) || (0, _manager5.hasInternalHelperManager)(value)) {
return 1
/* Helper */
;
} else if (isSafeString(value)) {
return 4
/* SafeString */
;
} else if (isFragment(value)) {
return 5
/* Fragment */
;
} else if (isNode(value)) {
return 6
/* Node */
;
} else {
return 2
/* String */
;
}
}
function toDynamicContentType(value) {
if (!(0, _util.isObject)(value)) {
return 2
/* String */
;
}
if (isCurriedType(value, 0
/* Component */
) || (0, _manager5.hasInternalComponentManager)(value)) {
return 0
/* Component */
;
} else {
if (true
/* DEBUG */
&& !isCurriedType(value, 1
/* Helper */
) && !(0, _manager5.hasInternalHelperManager)(value)) {
throw new Error(`Attempted use a dynamic value as a component or helper, but that value did not have an associated component or helper manager. The value was: ${value}`);
}
return 1
/* Helper */
;
}
}
APPEND_OPCODES.add(76
/* ContentType */
, vm => {
var reference = vm.stack.peek();
vm.stack.push(toContentType((0, _reference.valueForRef)(reference)));
if (!(0, _reference.isConstRef)(reference)) {
vm.updateWith(new AssertFilter(reference, toContentType));
}
});
APPEND_OPCODES.add(106
/* DynamicContentType */
, vm => {
var reference = vm.stack.peek();
vm.stack.push(toDynamicContentType((0, _reference.valueForRef)(reference)));
if (!(0, _reference.isConstRef)(reference)) {
vm.updateWith(new AssertFilter(reference, toDynamicContentType));
}
});
APPEND_OPCODES.add(43
/* AppendHTML */
, vm => {
var reference = vm.stack.pop();
var rawValue = (0, _reference.valueForRef)(reference);
var value = isEmpty(rawValue) ? '' : String(rawValue);
vm.elements().appendDynamicHTML(value);
});
APPEND_OPCODES.add(44
/* AppendSafeHTML */
, vm => {
var reference = vm.stack.pop();
var rawValue = (0, _reference.valueForRef)(reference).toHTML();
var value = isEmpty(rawValue) ? '' : rawValue;
vm.elements().appendDynamicHTML(value);
});
APPEND_OPCODES.add(47
/* AppendText */
, vm => {
var reference = vm.stack.pop();
var rawValue = (0, _reference.valueForRef)(reference);
var value = isEmpty(rawValue) ? '' : String(rawValue);
var node = vm.elements().appendDynamicText(value);
if (!(0, _reference.isConstRef)(reference)) {
vm.updateWith(new DynamicTextContent(node, reference, value));
}
});
APPEND_OPCODES.add(45
/* AppendDocumentFragment */
, vm => {
var reference = vm.stack.pop();
var value = (0, _reference.valueForRef)(reference);
vm.elements().appendDynamicFragment(value);
});
APPEND_OPCODES.add(46
/* AppendNode */
, vm => {
var reference = vm.stack.pop();
var value = (0, _reference.valueForRef)(reference);
vm.elements().appendDynamicNode(value);
});
function debugCallback(context, get) {
// eslint-disable-next-line no-console
console.info('Use `context`, and `get(<path>)` to debug this template.'); // for example...
// eslint-disable-next-line no-unused-expressions
context === get('this'); // eslint-disable-next-line no-debugger
debugger;
}
var callback = debugCallback; // For testing purposes
function setDebuggerCallback(cb) {
callback = cb;
}
function resetDebuggerCallback() {
callback = debugCallback;
}
class ScopeInspector {
constructor(scope, symbols, evalInfo) {
this.scope = scope;
this.locals = (0, _util.dict)();
for (var i = 0; i < evalInfo.length; i++) {
var slot = evalInfo[i];
var name = symbols[slot - 1];
var ref = scope.getSymbol(slot);
this.locals[name] = ref;
}
}
get(path) {
var {
scope,
locals
} = this;
var parts = path.split('.');
var [head, ...tail] = path.split('.');
var evalScope = scope.getEvalScope();
var ref;
if (head === 'this') {
ref = scope.getSelf();
} else if (locals[head]) {
ref = locals[head];
} else if (head.indexOf('@') === 0 && evalScope[head]) {
ref = evalScope[head];
} else {
ref = this.scope.getSelf();
tail = parts;
}
return tail.reduce((r, part) => (0, _reference.childRefFor)(r, part), ref);
}
}
APPEND_OPCODES.add(103
/* Debugger */
, (vm, {
op1: _symbols,
op2: _evalInfo
}) => {
var symbols = vm[CONSTANTS].getArray(_symbols);
var evalInfo = vm[CONSTANTS].getArray((0, _util.decodeHandle)(_evalInfo));
var inspector = new ScopeInspector(vm.scope(), symbols, evalInfo);
callback((0, _reference.valueForRef)(vm.getSelf()), path => (0, _reference.valueForRef)(inspector.get(path)));
});
APPEND_OPCODES.add(72
/* EnterList */
, (vm, {
op1: relativeStart,
op2: elseTarget
}) => {
var stack = vm.stack;
var listRef = stack.pop();
var keyRef = stack.pop();
var keyValue = (0, _reference.valueForRef)(keyRef);
var key = keyValue === null ? '@identity' : String(keyValue);
var iteratorRef = (0, _reference.createIteratorRef)(listRef, key);
var iterator = (0, _reference.valueForRef)(iteratorRef);
vm.updateWith(new AssertFilter(iteratorRef, iterator => iterator.isEmpty()));
if (iterator.isEmpty() === true) {
// TODO: Fix this offset, should be accurate
vm.goto(elseTarget + 1);
} else {
vm.enterList(iteratorRef, relativeStart);
vm.stack.push(iterator);
}
});
APPEND_OPCODES.add(73
/* ExitList */
, vm => {
vm.exitList();
});
APPEND_OPCODES.add(74
/* Iterate */
, (vm, {
op1: breaks
}) => {
var stack = vm.stack;
var iterator = stack.peek();
var item = iterator.next();
if (item !== null) {
vm.registerItem(vm.enterItem(item));
} else {
vm.goto(breaks);
}
});
var CAPABILITIES = {
dynamicLayout: false,
dynamicTag: false,
prepareArgs: false,
createArgs: false,
attributeHook: false,
elementHook: false,
createCaller: false,
dynamicScope: false,
updateHook: false,
createInstance: false,
wrapped: false,
willDestroy: false,
hasSubOwner: false
};
class TemplateOnlyComponentManager {
getCapabilities() {
return CAPABILITIES;
}
getDebugName({
name
}) {
return name;
}
getSelf() {
return _reference.NULL_REFERENCE;
}
getDestroyable() {
return null;
}
}
_exports.TemplateOnlyComponentManager = TemplateOnlyComponentManager;
var TEMPLATE_ONLY_COMPONENT_MANAGER = new TemplateOnlyComponentManager(); // This is only exported for types, don't use this class directly
_exports.TEMPLATE_ONLY_COMPONENT_MANAGER = TEMPLATE_ONLY_COMPONENT_MANAGER;
class TemplateOnlyComponentDefinition {
constructor(moduleName = '@glimmer/component/template-only', name = '(unknown template-only component)') {
this.moduleName = moduleName;
this.name = name;
}
toString() {
return this.moduleName;
}
}
_exports.TemplateOnlyComponent = TemplateOnlyComponentDefinition;
(0, _manager5.setInternalComponentManager)(TEMPLATE_ONLY_COMPONENT_MANAGER, TemplateOnlyComponentDefinition.prototype);
/**
This utility function is used to declare a given component has no backing class. When the rendering engine detects this it
is able to perform a number of optimizations. Templates that are associated with `templateOnly()` will be rendered _as is_
without adding a wrapping `<div>` (or any of the other element customization behaviors of [@ember/component](/ember/release/classes/Component)).
Specifically, this means that the template will be rendered as "outer HTML".
In general, this method will be used by build time tooling and would not be directly written in an application. However,
at times it may be useful to use directly to leverage the "outer HTML" semantics mentioned above. For example, if an addon would like
to use these semantics for its templates but cannot be certain it will only be consumed by applications that have enabled the
`template-only-glimmer-components` optional feature.
@example
```js
import { templateOnlyComponent } from '@glimmer/runtime';
export default templateOnlyComponent();
```
@public
@method templateOnly
@param {String} moduleName the module name that the template only component represents, this will be used for debugging purposes
@category EMBER_GLIMMER_SET_COMPONENT_TEMPLATE
*/
function templateOnlyComponent(moduleName, name) {
return new TemplateOnlyComponentDefinition(moduleName, name);
} // http://www.w3.org/TR/html/syntax.html#html-integration-point
var SVG_INTEGRATION_POINTS = {
foreignObject: 1,
desc: 1,
title: 1
}; // http://www.w3.org/TR/html/syntax.html#adjust-svg-attributes
// TODO: Adjust SVG attributes
// http://www.w3.org/TR/html/syntax.html#parsing-main-inforeign
// TODO: Adjust SVG elements
// http://www.w3.org/TR/html/syntax.html#parsing-main-inforeign
var BLACKLIST_TABLE = Object.create(null);
class DOMOperations {
constructor(document) {
this.document = document;
this.setupUselessElement();
} // split into separate method so that NodeDOMTreeConstruction
// can override it.
setupUselessElement() {
this.uselessElement = this.document.createElement('div');
}
createElement(tag, context) {
var isElementInSVGNamespace, isHTMLIntegrationPoint;
if (context) {
isElementInSVGNamespace = context.namespaceURI === "http://www.w3.org/2000/svg"
/* SVG */
|| tag === 'svg';
isHTMLIntegrationPoint = !!SVG_INTEGRATION_POINTS[context.tagName];
} else {
isElementInSVGNamespace = tag === 'svg';
isHTMLIntegrationPoint = false;
}
if (isElementInSVGNamespace && !isHTMLIntegrationPoint) {
// FIXME: This does not properly handle <font> with color, face, or
// size attributes, which is also disallowed by the spec. We should fix
// this.
if (BLACKLIST_TABLE[tag]) {
throw new Error(`Cannot create a ${tag} inside an SVG context`);
}
return this.document.createElementNS("http://www.w3.org/2000/svg"
/* SVG */
, tag);
} else {
return this.document.createElement(tag);
}
}
insertBefore(parent, node, reference) {
parent.insertBefore(node, reference);
}
insertHTMLBefore(parent, nextSibling, html) {
if (html === '') {
var comment = this.createComment('');
parent.insertBefore(comment, nextSibling);
return new ConcreteBounds(parent, comment, comment);
}
var prev = nextSibling ? nextSibling.previousSibling : parent.lastChild;
var last;
if (nextSibling === null) {
parent.insertAdjacentHTML("beforeend"
/* beforeend */
, html);
last = parent.lastChild;
} else if (nextSibling instanceof HTMLElement) {
nextSibling.insertAdjacentHTML('beforebegin', html);
last = nextSibling.previousSibling;
} else {
// Non-element nodes do not support insertAdjacentHTML, so add an
// element and call it on that element. Then remove the element.
//
// This also protects Edge, IE and Firefox w/o the inspector open
// from merging adjacent text nodes. See ./compat/text-node-merging-fix.ts
var {
uselessElement
} = this;
parent.insertBefore(uselessElement, nextSibling);
uselessElement.insertAdjacentHTML("beforebegin"
/* beforebegin */
, html);
last = uselessElement.previousSibling;
parent.removeChild(uselessElement);
}
var first = prev ? prev.nextSibling : parent.firstChild;
return new ConcreteBounds(parent, first, last);
}
createTextNode(text) {
return this.document.createTextNode(text);
}
createComment(data) {
return this.document.createComment(data);
}
}
function moveNodesBefore(source, target, nextSibling) {
var first = source.firstChild;
var last = first;
var current = first;
while (current) {
var next = current.nextSibling;
target.insertBefore(current, nextSibling);
last = current;
current = next;
}
return new ConcreteBounds(target, first, last);
}
var SVG_NAMESPACE = "http://www.w3.org/2000/svg"
/* SVG */
; // Patch: insertAdjacentHTML on SVG Fix
// Browsers: Safari, IE, Edge, Firefox ~33-34
// Reason: insertAdjacentHTML does not exist on SVG elements in Safari. It is
// present but throws an exception on IE and Edge. Old versions of
// Firefox create nodes in the incorrect namespace.
// Fix: Since IE and Edge silently fail to create SVG nodes using
// innerHTML, and because Firefox may create nodes in the incorrect
// namespace using innerHTML on SVG elements, an HTML-string wrapping
// approach is used. A pre/post SVG tag is added to the string, then
// that whole string is added to a div. The created nodes are plucked
// out and applied to the target location on DOM.
function applySVGInnerHTMLFix(document, DOMClass, svgNamespace) {
if (!document) return DOMClass;
if (!shouldApplyFix(document, svgNamespace)) {
return DOMClass;
}
var div = document.createElement('div');
return class DOMChangesWithSVGInnerHTMLFix extends DOMClass {
insertHTMLBefore(parent, nextSibling, html) {
if (html === '') {
return super.insertHTMLBefore(parent, nextSibling, html);
}
if (parent.namespaceURI !== svgNamespace) {
return super.insertHTMLBefore(parent, nextSibling, html);
}
return fixSVG(parent, div, html, nextSibling);
}
};
}
function fixSVG(parent, div, html, reference) {
var source; // This is important, because descendants of the <foreignObject> integration
// point are parsed in the HTML namespace
if (parent.tagName.toUpperCase() === 'FOREIGNOBJECT') {
// IE, Edge: also do not correctly support using `innerHTML` on SVG
// namespaced elements. So here a wrapper is used.
var wrappedHtml = '<svg><foreignObject>' + html + '</foreignObject></svg>';
(0, _util.clearElement)(div);
div.insertAdjacentHTML("afterbegin"
/* afterbegin */
, wrappedHtml);
source = div.firstChild.firstChild;
} else {
// IE, Edge: also do not correctly support using `innerHTML` on SVG
// namespaced elements. So here a wrapper is used.
var _wrappedHtml = '<svg>' + html + '</svg>';
(0, _util.clearElement)(div);
div.insertAdjacentHTML("afterbegin"
/* afterbegin */
, _wrappedHtml);
source = div.firstChild;
}
return moveNodesBefore(source, parent, reference);
}
function shouldApplyFix(document, svgNamespace) {
var svg = document.createElementNS(svgNamespace, 'svg');
try {
svg.insertAdjacentHTML("beforeend"
/* beforeend */
, '<circle></circle>');
} catch (e) {// IE, Edge: Will throw, insertAdjacentHTML is unsupported on SVG
// Safari: Will throw, insertAdjacentHTML is not present on SVG
} finally {
// FF: Old versions will create a node in the wrong namespace
if (svg.childNodes.length === 1 && svg.firstChild.namespaceURI === SVG_NAMESPACE) {
// The test worked as expected, no fix required
return false;
}
return true;
}
} // Patch: Adjacent text node merging fix
// Browsers: IE, Edge, Firefox w/o inspector open
// Reason: These browsers will merge adjacent text nodes. For example given
// <div>Hello</div> with div.insertAdjacentHTML(' world') browsers
// with proper behavior will populate div.childNodes with two items.
// These browsers will populate it with one merged node instead.
// Fix: Add these nodes to a wrapper element, then iterate the childNodes
// of that wrapper and move the nodes to their target location. Note
// that potential SVG bugs will have been handled before this fix.
// Note that this fix must only apply to the previous text node, as
// the base implementation of `insertHTMLBefore` already handles
// following text nodes correctly.
function applyTextNodeMergingFix(document, DOMClass) {
if (!document) return DOMClass;
if (!shouldApplyFix$1(document)) {
return DOMClass;
}
return class DOMChangesWithTextNodeMergingFix extends DOMClass {
constructor(document) {
super(document);
this.uselessComment = document.createComment('');
}
insertHTMLBefore(parent, nextSibling, html) {
if (html === '') {
return super.insertHTMLBefore(parent, nextSibling, html);
}
var didSetUselessComment = false;
var nextPrevious = nextSibling ? nextSibling.previousSibling : parent.lastChild;
if (nextPrevious && nextPrevious instanceof Text) {
didSetUselessComment = true;
parent.insertBefore(this.uselessComment, nextSibling);
}
var bounds = super.insertHTMLBefore(parent, nextSibling, html);
if (didSetUselessComment) {
parent.removeChild(this.uselessComment);
}
return bounds;
}
};
}
function shouldApplyFix$1(document) {
var mergingTextDiv = document.createElement('div');
mergingTextDiv.appendChild(document.createTextNode('first'));
mergingTextDiv.insertAdjacentHTML("beforeend"
/* beforeend */
, 'second');
if (mergingTextDiv.childNodes.length === 2) {
// It worked as expected, no fix required
return false;
}
return true;
}
['b', 'big', 'blockquote', 'body', 'br', 'center', 'code', 'dd', 'div', 'dl', 'dt', 'em', 'embed', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'hr', 'i', 'img', 'li', 'listing', 'main', 'meta', 'nobr', 'ol', 'p', 'pre', 'ruby', 's', 'small', 'span', 'strong', 'strike', 'sub', 'sup', 'table', 'tt', 'u', 'ul', 'var'].forEach(tag => BLACKLIST_TABLE[tag] = 1);
var WHITESPACE = /[\t-\r \xA0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]/;
var doc = typeof document === 'undefined' ? null : document;
function isWhitespace(string) {
return WHITESPACE.test(string);
}
var DOM;
(function (DOM) {
class TreeConstruction extends DOMOperations {
createElementNS(namespace, tag) {
return this.document.createElementNS(namespace, tag);
}
setAttribute(element, name, value, namespace = null) {
if (namespace) {
element.setAttributeNS(namespace, name, value);
} else {
element.setAttribute(name, value);
}
}
}
DOM.TreeConstruction = TreeConstruction;
var appliedTreeConstruction = TreeConstruction;
appliedTreeConstruction = applyTextNodeMergingFix(doc, appliedTreeConstruction);
appliedTreeConstruction = applySVGInnerHTMLFix(doc, appliedTreeConstruction, "http://www.w3.org/2000/svg"
/* SVG */
);
DOM.DOMTreeConstruction = appliedTreeConstruction;
})(DOM || (DOM = {}));
class DOMChangesImpl extends DOMOperations {
constructor(document) {
super(document);
this.document = document;
this.namespace = null;
}
setAttribute(element, name, value) {
element.setAttribute(name, value);
}
removeAttribute(element, name) {
element.removeAttribute(name);
}
insertAfter(element, node, reference) {
this.insertBefore(element, node, reference.nextSibling);
}
}
_exports.IDOMChanges = DOMChangesImpl;
var helper = DOMChangesImpl;
helper = applyTextNodeMergingFix(doc, helper);
helper = applySVGInnerHTMLFix(doc, helper, "http://www.w3.org/2000/svg"
/* SVG */
);
var helper$1 = helper;
_exports.DOMChanges = helper$1;
var DOMTreeConstruction = DOM.DOMTreeConstruction;
_exports.DOMTreeConstruction = DOMTreeConstruction;
var GUID = 0;
class Ref {
constructor(value) {
this.id = GUID++;
this.value = value;
}
get() {
return this.value;
}
release() {
if (true
/* DEBUG */
&& this.value === null) {
throw new Error('BUG: double release?');
}
this.value = null;
}
toString() {
var label = `Ref ${this.id}`;
if (this.value === null) {
return `${label} (released)`;
} else {
try {
return `${label}: ${this.value}`;
} catch (_a) {
return label;
}
}
}
}
class DebugRenderTreeImpl {
constructor() {
this.stack = new _util.Stack();
this.refs = new WeakMap();
this.roots = new Set();
this.nodes = new WeakMap();
}
begin() {
this.reset();
}
create(state, node) {
var internalNode = (0, _util.assign)({}, node, {
bounds: null,
refs: new Set()
});
this.nodes.set(state, internalNode);
this.appendChild(internalNode, state);
this.enter(state);
}
update(state) {
this.enter(state);
}
didRender(state, bounds) {
if (true
/* DEBUG */
&& this.stack.current !== state) {
throw new Error(`BUG: expecting ${this.stack.current}, got ${state}`);
}
this.nodeFor(state).bounds = bounds;
this.exit();
}
willDestroy(state) {
this.refs.get(state).release();
}
commit() {
this.reset();
}
capture() {
return this.captureRefs(this.roots);
}
reset() {
if (this.stack.size !== 0) {
// We probably encountered an error during the rendering loop. This will
// likely trigger undefined behavior and memory leaks as the error left
// things in an inconsistent state. It is recommended that the user
// refresh the page.
// TODO: We could warn here? But this happens all the time in our tests?
// Clean up the root reference to prevent errors from happening if we
// attempt to capture the render tree (Ember Inspector may do this)
var root = this.stack.toArray()[0];
var ref = this.refs.get(root);
if (ref !== undefined) {
this.roots.delete(ref);
}
while (!this.stack.isEmpty()) {
this.stack.pop();
}
}
}
enter(state) {
this.stack.push(state);
}
exit() {
if (true
/* DEBUG */
&& this.stack.size === 0) {
throw new Error('BUG: unbalanced pop');
}
this.stack.pop();
}
nodeFor(state) {
return this.nodes.get(state);
}
appendChild(node, state) {
if (true
/* DEBUG */
&& this.refs.has(state)) {
throw new Error('BUG: child already appended');
}
var parent = this.stack.current;
var ref = new Ref(state);
this.refs.set(state, ref);
if (parent) {
var parentNode = this.nodeFor(parent);
parentNode.refs.add(ref);
node.parent = parentNode;
} else {
this.roots.add(ref);
}
}
captureRefs(refs) {
var captured = [];
refs.forEach(ref => {
var state = ref.get();
if (state) {
captured.push(this.captureNode(`render-node:${ref.id}`, state));
} else {
refs.delete(ref);
}
});
return captured;
}
captureNode(id, state) {
var node = this.nodeFor(state);
var {
type,
name,
args,
instance,
refs
} = node;
var template = this.captureTemplate(node);
var bounds = this.captureBounds(node);
var children = this.captureRefs(refs);
return {
id,
type,
name,
args: reifyArgs(args),
instance,
template,
bounds,
children
};
}
captureTemplate({
template
}) {
return template || null;
}
captureBounds(node) {
var bounds = node.bounds;
var parentElement = bounds.parentElement();
var firstNode = bounds.firstNode();
var lastNode = bounds.lastNode();
return {
parentElement,
firstNode,
lastNode
};
}
}
var _a$1;
var TRANSACTION = (0, _util.symbol)('TRANSACTION');
class TransactionImpl {
constructor() {
this.scheduledInstallModifiers = [];
this.scheduledUpdateModifiers = [];
this.createdComponents = [];
this.updatedComponents = [];
}
didCreate(component) {
this.createdComponents.push(component);
}
didUpdate(component) {
this.updatedComponents.push(component);
}
scheduleInstallModifier(modifier) {
this.scheduledInstallModifiers.push(modifier);
}
scheduleUpdateModifier(modifier) {
this.scheduledUpdateModifiers.push(modifier);
}
commit() {
var {
createdComponents,
updatedComponents
} = this;
for (var i = 0; i < createdComponents.length; i++) {
var {
manager: _manager3,
state: _state2
} = createdComponents[i];
_manager3.didCreate(_state2);
}
for (var _i3 = 0; _i3 < updatedComponents.length; _i3++) {
var {
manager: _manager4,
state: _state3
} = updatedComponents[_i3];
_manager4.didUpdate(_state3);
}
var {
scheduledInstallModifiers,
scheduledUpdateModifiers
} = this; // Prevent a transpilation issue we guard against in Ember, the
// throw-if-closure-required issue
var manager, state;
for (var _i4 = 0; _i4 < scheduledInstallModifiers.length; _i4++) {
var modifier = scheduledInstallModifiers[_i4];
manager = modifier.manager;
state = modifier.state;
var modifierTag = manager.getTag(state);
if (modifierTag !== null) {
var tag = (0, _validator.track)( // eslint-disable-next-line no-loop-func
() => manager.install(state), true
/* DEBUG */
&& `- While rendering:\n (instance of a \`${modifier.definition.resolvedName || manager.getDebugName(modifier.definition.state)}\` modifier)`);
(0, _validator.updateTag)(modifierTag, tag);
} else {
manager.install(state);
}
}
for (var _i5 = 0; _i5 < scheduledUpdateModifiers.length; _i5++) {
var _modifier = scheduledUpdateModifiers[_i5];
manager = _modifier.manager;
state = _modifier.state;
var _modifierTag = manager.getTag(state);
if (_modifierTag !== null) {
var _tag = (0, _validator.track)( // eslint-disable-next-line no-loop-func
() => manager.update(state), true
/* DEBUG */
&& `- While rendering:\n (instance of a \`${_modifier.definition.resolvedName || manager.getDebugName(_modifier.definition.state)}\` modifier)`);
(0, _validator.updateTag)(_modifierTag, _tag);
} else {
manager.update(state);
}
}
}
}
class EnvironmentImpl {
constructor(options, delegate) {
this.delegate = delegate;
this[_a$1] = null; // Delegate methods and values
this.isInteractive = this.delegate.isInteractive;
this.debugRenderTree = this.delegate.enableDebugTooling ? new DebugRenderTreeImpl() : undefined;
if (options.appendOperations) {
this.appendOperations = options.appendOperations;
this.updateOperations = options.updateOperations;
} else if (options.document) {
this.appendOperations = new DOMTreeConstruction(options.document);
this.updateOperations = new DOMChangesImpl(options.document);
} else if (true
/* DEBUG */
) {
throw new Error('you must pass document or appendOperations to a new runtime');
}
}
getAppendOperations() {
return this.appendOperations;
}
getDOM() {
return this.updateOperations;
}
begin() {
var _b;
(_b = this.debugRenderTree) === null || _b === void 0 ? void 0 : _b.begin();
this[TRANSACTION] = new TransactionImpl();
}
get transaction() {
return this[TRANSACTION];
}
didCreate(component) {
this.transaction.didCreate(component);
}
didUpdate(component) {
this.transaction.didUpdate(component);
}
scheduleInstallModifier(modifier) {
if (this.isInteractive) {
this.transaction.scheduleInstallModifier(modifier);
}
}
scheduleUpdateModifier(modifier) {
if (this.isInteractive) {
this.transaction.scheduleUpdateModifier(modifier);
}
}
commit() {
var _b;
var transaction = this.transaction;
this[TRANSACTION] = null;
transaction.commit();
(_b = this.debugRenderTree) === null || _b === void 0 ? void 0 : _b.commit();
this.delegate.onTransactionCommit();
}
}
_exports.EnvironmentImpl = EnvironmentImpl;
_a$1 = TRANSACTION;
function runtimeContext(options, delegate, artifacts, resolver) {
return {
env: new EnvironmentImpl(options, delegate),
program: new _program.RuntimeProgramImpl(artifacts.constants, artifacts.heap),
resolver: resolver
};
}
function inTransaction(env, cb) {
if (!env[TRANSACTION]) {
env.begin();
try {
cb();
} finally {
env.commit();
}
} else {
cb();
}
}
function initializeRegistersWithSP(sp) {
return [0, -1, sp, 0];
}
class LowLevelVM {
constructor(stack, heap, program, externs, registers) {
this.stack = stack;
this.heap = heap;
this.program = program;
this.externs = externs;
this.registers = registers;
this.currentOpSize = 0;
}
fetchRegister(register) {
return this.registers[register];
}
loadRegister(register, value) {
this.registers[register] = value;
}
setPc(pc) {
this.registers[_vm2.$pc] = pc;
} // Start a new frame and save $ra and $fp on the stack
pushFrame() {
this.stack.push(this.registers[_vm2.$ra]);
this.stack.push(this.registers[_vm2.$fp]);
this.registers[_vm2.$fp] = this.registers[_vm2.$sp] - 1;
} // Restore $ra, $sp and $fp
popFrame() {
this.registers[_vm2.$sp] = this.registers[_vm2.$fp] - 1;
this.registers[_vm2.$ra] = this.stack.get(0);
this.registers[_vm2.$fp] = this.stack.get(1);
}
pushSmallFrame() {
this.stack.push(this.registers[_vm2.$ra]);
}
popSmallFrame() {
this.registers[_vm2.$ra] = this.stack.pop();
} // Jump to an address in `program`
goto(offset) {
this.setPc(this.target(offset));
}
target(offset) {
return this.registers[_vm2.$pc] + offset - this.currentOpSize;
} // Save $pc into $ra, then jump to a new address in `program` (jal in MIPS)
call(handle) {
this.registers[_vm2.$ra] = this.registers[_vm2.$pc];
this.setPc(this.heap.getaddr(handle));
} // Put a specific `program` address in $ra
returnTo(offset) {
this.registers[_vm2.$ra] = this.target(offset);
} // Return to the `program` address stored in $ra
return() {
this.setPc(this.registers[_vm2.$ra]);
}
nextStatement() {
var {
registers,
program
} = this;
var pc = registers[_vm2.$pc];
if (pc === -1) {
return null;
} // We have to save off the current operations size so that
// when we do a jump we can calculate the correct offset
// to where we are going. We can't simply ask for the size
// in a jump because we have have already incremented the
// program counter to the next instruction prior to executing.
var opcode = program.opcode(pc);
var operationSize = this.currentOpSize = opcode.size;
this.registers[_vm2.$pc] += operationSize;
return opcode;
}
evaluateOuter(opcode, vm) {
{
this.evaluateInner(opcode, vm);
}
}
evaluateInner(opcode, vm) {
if (opcode.isMachine) {
this.evaluateMachine(opcode);
} else {
this.evaluateSyscall(opcode, vm);
}
}
evaluateMachine(opcode) {
switch (opcode.type) {
case 0
/* PushFrame */
:
return this.pushFrame();
case 1
/* PopFrame */
:
return this.popFrame();
case 3
/* InvokeStatic */
:
return this.call(opcode.op1);
case 2
/* InvokeVirtual */
:
return this.call(this.stack.pop());
case 4
/* Jump */
:
return this.goto(opcode.op1);
case 5
/* Return */
:
return this.return();
case 6
/* ReturnTo */
:
return this.returnTo(opcode.op1);
}
}
evaluateSyscall(opcode, vm) {
APPEND_OPCODES.evaluate(vm, opcode, opcode.type);
}
}
class UpdatingVMImpl {
constructor(env, {
alwaysRevalidate = false
}) {
this.frameStack = new _util.Stack();
this.env = env;
this.dom = env.getDOM();
this.alwaysRevalidate = alwaysRevalidate;
}
execute(opcodes, handler) {
if (true
/* DEBUG */
) {
var hasErrored = true;
try {
(0, _validator.runInTrackingTransaction)(() => this._execute(opcodes, handler), '- While rendering:'); // using a boolean here to avoid breaking ergonomics of "pause on uncaught exceptions"
// which would happen with a `catch` + `throw`
hasErrored = false;
} finally {
if (hasErrored) {
// eslint-disable-next-line no-console
console.error(`\n\nError occurred:\n\n${(0, _validator.resetTracking)()}\n\n`);
}
}
} else {
this._execute(opcodes, handler);
}
}
_execute(opcodes, handler) {
var {
frameStack
} = this;
this.try(opcodes, handler);
while (true) {
if (frameStack.isEmpty()) break;
var opcode = this.frame.nextStatement();
if (opcode === undefined) {
frameStack.pop();
continue;
}
opcode.evaluate(this);
}
}
get frame() {
return this.frameStack.current;
}
goto(index) {
this.frame.goto(index);
}
try(ops, handler) {
this.frameStack.push(new UpdatingVMFrame(ops, handler));
}
throw() {
this.frame.handleException();
this.frameStack.pop();
}
}
_exports.UpdatingVM = UpdatingVMImpl;
class ResumableVMStateImpl {
constructor(state, resumeCallback) {
this.state = state;
this.resumeCallback = resumeCallback;
}
resume(runtime, builder) {
return this.resumeCallback(runtime, this.state, builder);
}
}
class BlockOpcode {
constructor(state, runtime, bounds, children) {
this.state = state;
this.runtime = runtime;
this.children = children;
this.bounds = bounds;
}
parentElement() {
return this.bounds.parentElement();
}
firstNode() {
return this.bounds.firstNode();
}
lastNode() {
return this.bounds.lastNode();
}
evaluate(vm) {
vm.try(this.children, null);
}
}
class TryOpcode extends BlockOpcode {
constructor() {
super(...arguments);
this.type = 'try';
}
evaluate(vm) {
vm.try(this.children, this);
}
handleException() {
var {
state,
bounds,
runtime
} = this;
(0, _destroyable2.destroyChildren)(this);
var elementStack = NewElementBuilder.resume(runtime.env, bounds);
var vm = state.resume(runtime, elementStack);
var updating = [];
var children = this.children = [];
var result = vm.execute(vm => {
vm.pushUpdating(updating);
vm.updateWith(this);
vm.pushUpdating(children);
});
(0, _destroyable2.associateDestroyableChild)(this, result.drop);
}
}
class ListItemOpcode extends TryOpcode {
constructor(state, runtime, bounds, key, memo, value) {
super(state, runtime, bounds, []);
this.key = key;
this.memo = memo;
this.value = value;
this.retained = false;
this.index = -1;
}
updateReferences(item) {
this.retained = true;
(0, _reference.updateRef)(this.value, item.value);
(0, _reference.updateRef)(this.memo, item.memo);
}
shouldRemove() {
return !this.retained;
}
reset() {
this.retained = false;
}
}
class ListBlockOpcode extends BlockOpcode {
constructor(state, runtime, bounds, children, iterableRef) {
super(state, runtime, bounds, children);
this.iterableRef = iterableRef;
this.type = 'list-block';
this.opcodeMap = new Map();
this.marker = null;
this.lastIterator = (0, _reference.valueForRef)(iterableRef);
}
initializeChild(opcode) {
opcode.index = this.children.length - 1;
this.opcodeMap.set(opcode.key, opcode);
}
evaluate(vm) {
var iterator = (0, _reference.valueForRef)(this.iterableRef);
if (this.lastIterator !== iterator) {
var {
bounds
} = this;
var {
dom
} = vm;
var marker = this.marker = dom.createComment('');
dom.insertAfter(bounds.parentElement(), marker, bounds.lastNode());
this.sync(iterator);
this.parentElement().removeChild(marker);
this.marker = null;
this.lastIterator = iterator;
} // Run now-updated updating opcodes
super.evaluate(vm);
}
sync(iterator) {
var {
opcodeMap: itemMap,
children
} = this;
var currentOpcodeIndex = 0;
var seenIndex = 0;
this.children = this.bounds.boundList = [];
while (true) {
var item = iterator.next();
if (item === null) break;
var opcode = children[currentOpcodeIndex];
var {
key
} = item; // Items that have already been found and moved will already be retained,
// we can continue until we find the next unretained item
while (opcode !== undefined && opcode.retained === true) {
opcode = children[++currentOpcodeIndex];
}
if (opcode !== undefined && opcode.key === key) {
this.retainItem(opcode, item);
currentOpcodeIndex++;
} else if (itemMap.has(key)) {
var itemOpcode = itemMap.get(key); // The item opcode was seen already, so we should move it.
if (itemOpcode.index < seenIndex) {
this.moveItem(itemOpcode, item, opcode);
} else {
// Update the seen index, we are going to be moving this item around
// so any other items that come before it will likely need to move as
// well.
seenIndex = itemOpcode.index;
var seenUnretained = false; // iterate through all of the opcodes between the current position and
// the position of the item's opcode, and determine if they are all
// retained.
for (var i = currentOpcodeIndex + 1; i < seenIndex; i++) {
if (children[i].retained === false) {
seenUnretained = true;
break;
}
} // If we have seen only retained opcodes between this and the matching
// opcode, it means that all the opcodes in between have been moved
// already, and we can safely retain this item's opcode.
if (seenUnretained === false) {
this.retainItem(itemOpcode, item);
currentOpcodeIndex = seenIndex + 1;
} else {
this.moveItem(itemOpcode, item, opcode);
currentOpcodeIndex++;
}
}
} else {
this.insertItem(item, opcode);
}
}
for (var _i6 = 0; _i6 < children.length; _i6++) {
var _opcode = children[_i6];
if (_opcode.retained === false) {
this.deleteItem(_opcode);
} else {
_opcode.reset();
}
}
}
retainItem(opcode, item) {
var {
children
} = this;
(0, _reference.updateRef)(opcode.memo, item.memo);
(0, _reference.updateRef)(opcode.value, item.value);
opcode.retained = true;
opcode.index = children.length;
children.push(opcode);
}
insertItem(item, before) {
var {
opcodeMap,
bounds,
state,
runtime,
children
} = this;
var {
key
} = item;
var nextSibling = before === undefined ? this.marker : before.firstNode();
var elementStack = NewElementBuilder.forInitialRender(runtime.env, {
element: bounds.parentElement(),
nextSibling
});
var vm = state.resume(runtime, elementStack);
vm.execute(vm => {
vm.pushUpdating();
var opcode = vm.enterItem(item);
opcode.index = children.length;
children.push(opcode);
opcodeMap.set(key, opcode);
(0, _destroyable2.associateDestroyableChild)(this, opcode);
});
}
moveItem(opcode, item, before) {
var {
children
} = this;
(0, _reference.updateRef)(opcode.memo, item.memo);
(0, _reference.updateRef)(opcode.value, item.value);
opcode.retained = true;
var currentSibling, nextSibling;
if (before === undefined) {
move(opcode, this.marker);
} else {
currentSibling = opcode.lastNode().nextSibling;
nextSibling = before.firstNode(); // Items are moved throughout the algorithm, so there are cases where the
// the items already happen to be siblings (e.g. an item in between was
// moved before this move happened). Check to see if they are siblings
// first before doing the move.
if (currentSibling !== nextSibling) {
move(opcode, nextSibling);
}
}
opcode.index = children.length;
children.push(opcode);
}
deleteItem(opcode) {
(0, _destroyable2.destroy)(opcode);
clear(opcode);
this.opcodeMap.delete(opcode.key);
}
}
class UpdatingVMFrame {
constructor(ops, exceptionHandler) {
this.ops = ops;
this.exceptionHandler = exceptionHandler;
this.current = 0;
}
goto(index) {
this.current = index;
}
nextStatement() {
return this.ops[this.current++];
}
handleException() {
if (this.exceptionHandler) {
this.exceptionHandler.handleException();
}
}
}
class RenderResultImpl {
constructor(env, updating, bounds, drop) {
this.env = env;
this.updating = updating;
this.bounds = bounds;
this.drop = drop;
(0, _destroyable2.associateDestroyableChild)(this, drop);
(0, _destroyable2.registerDestructor)(this, () => clear(this.bounds));
}
rerender({
alwaysRevalidate = false
} = {
alwaysRevalidate: false
}) {
var {
env,
updating
} = this;
var vm = new UpdatingVMImpl(env, {
alwaysRevalidate
});
vm.execute(updating, this);
}
parentElement() {
return this.bounds.parentElement();
}
firstNode() {
return this.bounds.firstNode();
}
lastNode() {
return this.bounds.lastNode();
}
handleException() {
throw 'this should never happen';
}
}
class EvaluationStackImpl {
// fp -> sp
constructor(stack = [], registers) {
this.stack = stack;
this[REGISTERS] = registers;
}
static restore(snapshot) {
return new this(snapshot.slice(), initializeRegistersWithSP(snapshot.length - 1));
}
push(value) {
this.stack[++this[REGISTERS][_vm2.$sp]] = value;
}
dup(position = this[REGISTERS][_vm2.$sp]) {
this.stack[++this[REGISTERS][_vm2.$sp]] = this.stack[position];
}
copy(from, to) {
this.stack[to] = this.stack[from];
}
pop(n = 1) {
var top = this.stack[this[REGISTERS][_vm2.$sp]];
this[REGISTERS][_vm2.$sp] -= n;
return top;
}
peek(offset = 0) {
return this.stack[this[REGISTERS][_vm2.$sp] - offset];
}
get(offset, base = this[REGISTERS][_vm2.$fp]) {
return this.stack[base + offset];
}
set(value, offset, base = this[REGISTERS][_vm2.$fp]) {
this.stack[base + offset] = value;
}
slice(start, end) {
return this.stack.slice(start, end);
}
capture(items) {
var end = this[REGISTERS][_vm2.$sp] + 1;
var start = end - items;
return this.stack.slice(start, end);
}
reset() {
this.stack.length = 0;
}
toArray() {
return this.stack.slice(this[REGISTERS][_vm2.$fp], this[REGISTERS][_vm2.$sp] + 1);
}
}
var _a$2, _b;
class Stacks {
constructor() {
this.scope = new _util.Stack();
this.dynamicScope = new _util.Stack();
this.updating = new _util.Stack();
this.cache = new _util.Stack();
this.list = new _util.Stack();
}
}
class VM {
/**
* End of migrated.
*/
constructor(runtime, {
pc,
scope,
dynamicScope,
stack
}, elementStack, context) {
this.runtime = runtime;
this.elementStack = elementStack;
this.context = context;
this[_a$2] = new Stacks();
this[_b] = new _util.Stack();
this.s0 = null;
this.s1 = null;
this.t0 = null;
this.t1 = null;
this.v0 = null;
this.resume = initVM(this.context);
if (true
/* DEBUG */
) {
(0, _globalContext.assertGlobalContextWasSet)();
}
var evalStack = EvaluationStackImpl.restore(stack);
evalStack[REGISTERS][_vm2.$pc] = pc;
evalStack[REGISTERS][_vm2.$sp] = stack.length - 1;
evalStack[REGISTERS][_vm2.$fp] = -1;
this[HEAP] = this.program.heap;
this[CONSTANTS] = this.program.constants;
this.elementStack = elementStack;
this[STACKS].scope.push(scope);
this[STACKS].dynamicScope.push(dynamicScope);
this[ARGS] = new VMArgumentsImpl();
this[INNER_VM] = new LowLevelVM(evalStack, this[HEAP], runtime.program, {
debugBefore: opcode => {
return APPEND_OPCODES.debugBefore(this, opcode);
},
debugAfter: state => {
APPEND_OPCODES.debugAfter(this, state);
}
}, evalStack[REGISTERS]);
this.destructor = {};
this[DESTROYABLE_STACK].push(this.destructor);
}
get stack() {
return this[INNER_VM].stack;
}
/* Registers */
get pc() {
return this[INNER_VM].fetchRegister(_vm2.$pc);
} // Fetch a value from a register onto the stack
fetch(register) {
var value = this.fetchValue(register);
this.stack.push(value);
} // Load a value from the stack into a register
load(register) {
var value = this.stack.pop();
this.loadValue(register, value);
}
fetchValue(register) {
if ((0, _vm2.isLowLevelRegister)(register)) {
return this[INNER_VM].fetchRegister(register);
}
switch (register) {
case _vm2.$s0:
return this.s0;
case _vm2.$s1:
return this.s1;
case _vm2.$t0:
return this.t0;
case _vm2.$t1:
return this.t1;
case _vm2.$v0:
return this.v0;
}
} // Load a value into a register
loadValue(register, value) {
if ((0, _vm2.isLowLevelRegister)(register)) {
this[INNER_VM].loadRegister(register, value);
}
switch (register) {
case _vm2.$s0:
this.s0 = value;
break;
case _vm2.$s1:
this.s1 = value;
break;
case _vm2.$t0:
this.t0 = value;
break;
case _vm2.$t1:
this.t1 = value;
break;
case _vm2.$v0:
this.v0 = value;
break;
}
}
/**
* Migrated to Inner
*/
// Start a new frame and save $ra and $fp on the stack
pushFrame() {
this[INNER_VM].pushFrame();
} // Restore $ra, $sp and $fp
popFrame() {
this[INNER_VM].popFrame();
} // Jump to an address in `program`
goto(offset) {
this[INNER_VM].goto(offset);
} // Save $pc into $ra, then jump to a new address in `program` (jal in MIPS)
call(handle) {
this[INNER_VM].call(handle);
} // Put a specific `program` address in $ra
returnTo(offset) {
this[INNER_VM].returnTo(offset);
} // Return to the `program` address stored in $ra
return() {
this[INNER_VM].return();
}
static initial(runtime, context, {
handle,
self,
dynamicScope,
treeBuilder,
numSymbols,
owner
}) {
var scope = PartialScopeImpl.root(self, numSymbols, owner);
var state = vmState(runtime.program.heap.getaddr(handle), scope, dynamicScope);
var vm = initVM(context)(runtime, state, treeBuilder);
vm.pushUpdating();
return vm;
}
static empty(runtime, {
handle,
treeBuilder,
dynamicScope,
owner
}, context) {
var vm = initVM(context)(runtime, vmState(runtime.program.heap.getaddr(handle), PartialScopeImpl.root(_reference.UNDEFINED_REFERENCE, 0, owner), dynamicScope), treeBuilder);
vm.pushUpdating();
return vm;
}
compile(block) {
var handle = (0, _util.unwrapHandle)(block.compile(this.context));
return handle;
}
get program() {
return this.runtime.program;
}
get env() {
return this.runtime.env;
}
captureState(args, pc = this[INNER_VM].fetchRegister(_vm2.$pc)) {
return {
pc,
scope: this.scope(),
dynamicScope: this.dynamicScope(),
stack: this.stack.capture(args)
};
}
capture(args, pc = this[INNER_VM].fetchRegister(_vm2.$pc)) {
return new ResumableVMStateImpl(this.captureState(args, pc), this.resume);
}
beginCacheGroup(name) {
var opcodes = this.updating();
var guard = new JumpIfNotModifiedOpcode();
opcodes.push(guard);
opcodes.push(new BeginTrackFrameOpcode(name));
this[STACKS].cache.push(guard);
(0, _validator.beginTrackFrame)(name);
}
commitCacheGroup() {
var opcodes = this.updating();
var guard = this[STACKS].cache.pop();
var tag = (0, _validator.endTrackFrame)();
opcodes.push(new EndTrackFrameOpcode(guard));
guard.finalize(tag, opcodes.length);
}
enter(args) {
var updating = [];
var state = this.capture(args);
var block = this.elements().pushUpdatableBlock();
var tryOpcode = new TryOpcode(state, this.runtime, block, updating);
this.didEnter(tryOpcode);
}
enterItem({
key,
value,
memo
}) {
var {
stack
} = this;
var valueRef = (0, _reference.createIteratorItemRef)(value);
var memoRef = (0, _reference.createIteratorItemRef)(memo);
stack.push(valueRef);
stack.push(memoRef);
var state = this.capture(2);
var block = this.elements().pushUpdatableBlock();
var opcode = new ListItemOpcode(state, this.runtime, block, key, memoRef, valueRef);
this.didEnter(opcode);
return opcode;
}
registerItem(opcode) {
this.listBlock().initializeChild(opcode);
}
enterList(iterableRef, offset) {
var updating = [];
var addr = this[INNER_VM].target(offset);
var state = this.capture(0, addr);
var list = this.elements().pushBlockList(updating);
var opcode = new ListBlockOpcode(state, this.runtime, list, updating, iterableRef);
this[STACKS].list.push(opcode);
this.didEnter(opcode);
}
didEnter(opcode) {
this.associateDestroyable(opcode);
this[DESTROYABLE_STACK].push(opcode);
this.updateWith(opcode);
this.pushUpdating(opcode.children);
}
exit() {
this[DESTROYABLE_STACK].pop();
this.elements().popBlock();
this.popUpdating();
}
exitList() {
this.exit();
this[STACKS].list.pop();
}
pushUpdating(list = []) {
this[STACKS].updating.push(list);
}
popUpdating() {
return this[STACKS].updating.pop();
}
updateWith(opcode) {
this.updating().push(opcode);
}
listBlock() {
return this[STACKS].list.current;
}
associateDestroyable(child) {
var parent = this[DESTROYABLE_STACK].current;
(0, _destroyable2.associateDestroyableChild)(parent, child);
}
tryUpdating() {
return this[STACKS].updating.current;
}
updating() {
return this[STACKS].updating.current;
}
elements() {
return this.elementStack;
}
scope() {
return this[STACKS].scope.current;
}
dynamicScope() {
return this[STACKS].dynamicScope.current;
}
pushChildScope() {
this[STACKS].scope.push(this.scope().child());
}
pushDynamicScope() {
var child = this.dynamicScope().child();
this[STACKS].dynamicScope.push(child);
return child;
}
pushRootScope(size, owner) {
var scope = PartialScopeImpl.sized(size, owner);
this[STACKS].scope.push(scope);
return scope;
}
pushScope(scope) {
this[STACKS].scope.push(scope);
}
popScope() {
this[STACKS].scope.pop();
}
popDynamicScope() {
this[STACKS].dynamicScope.pop();
} /// SCOPE HELPERS
getOwner() {
return this.scope().owner;
}
getSelf() {
return this.scope().getSelf();
}
referenceForSymbol(symbol$$1) {
return this.scope().getSymbol(symbol$$1);
} /// EXECUTION
execute(initialize) {
if (true
/* DEBUG */
) {
var hasErrored = true;
try {
var value = this._execute(initialize); // using a boolean here to avoid breaking ergonomics of "pause on uncaught exceptions"
// which would happen with a `catch` + `throw`
hasErrored = false;
return value;
} finally {
if (hasErrored) {
// If any existing blocks are open, due to an error or something like
// that, we need to close them all and clean things up properly.
var elements = this.elements();
while (elements.hasBlocks) {
elements.popBlock();
} // eslint-disable-next-line no-console
console.error(`\n\nError occurred:\n\n${(0, _validator.resetTracking)()}\n\n`);
}
}
} else {
return this._execute(initialize);
}
}
_execute(initialize) {
if (initialize) initialize(this);
var result;
while (true) {
result = this.next();
if (result.done) break;
}
return result.value;
}
next() {
var {
env,
elementStack
} = this;
var opcode = this[INNER_VM].nextStatement();
var result;
if (opcode !== null) {
this[INNER_VM].evaluateOuter(opcode, this);
result = {
done: false,
value: null
};
} else {
// Unload the stack
this.stack.reset();
result = {
done: true,
value: new RenderResultImpl(env, this.popUpdating(), elementStack.popBlock(), this.destructor)
};
}
return result;
}
bindDynamicScope(names) {
var scope = this.dynamicScope();
for (var i = names.length - 1; i >= 0; i--) {
var name = names[i];
scope.set(name, this.stack.pop());
}
}
}
_exports.LowLevelVM = VM;
_a$2 = STACKS, _b = DESTROYABLE_STACK;
function vmState(pc, scope, dynamicScope) {
return {
pc,
scope,
dynamicScope,
stack: []
};
}
function initVM(context) {
return (runtime, state, builder) => new VM(runtime, state, builder, context);
}
class TemplateIteratorImpl {
constructor(vm) {
this.vm = vm;
}
next() {
return this.vm.next();
}
sync() {
if (true
/* DEBUG */
) {
return (0, _validator.runInTrackingTransaction)(() => this.vm.execute(), '- While rendering:');
} else {
return this.vm.execute();
}
}
}
function renderSync(env, iterator) {
var result;
inTransaction(env, () => result = iterator.sync());
return result;
}
function renderMain(runtime, context, owner, self, treeBuilder, layout, dynamicScope = new DynamicScopeImpl()) {
var handle = (0, _util.unwrapHandle)(layout.compile(context));
var numSymbols = layout.symbolTable.symbols.length;
var vm = VM.initial(runtime, context, {
self,
dynamicScope,
treeBuilder,
handle,
numSymbols,
owner
});
return new TemplateIteratorImpl(vm);
}
function renderInvocation(vm, context, owner, definition, args) {
// Get a list of tuples of argument names and references, like
// [['title', reference], ['name', reference]]
var argList = Object.keys(args).map(key => [key, args[key]]);
var blockNames = ['main', 'else', 'attrs']; // Prefix argument names with `@` symbol
var argNames = argList.map(([name]) => `@${name}`);
var reified = vm[CONSTANTS].component(definition, owner);
vm.pushFrame(); // Push blocks on to the stack, three stack values per block
for (var i = 0; i < 3 * blockNames.length; i++) {
vm.stack.push(null);
}
vm.stack.push(null); // For each argument, push its backing reference on to the stack
argList.forEach(([, reference]) => {
vm.stack.push(reference);
}); // Configure VM based on blocks and args just pushed on to the stack.
vm[ARGS].setup(vm.stack, argNames, blockNames, 0, true);
var compilable = reified.compilable;
var layoutHandle = (0, _util.unwrapHandle)(compilable.compile(context));
var invocation = {
handle: layoutHandle,
symbolTable: compilable.symbolTable
}; // Needed for the Op.Main opcode: arguments, component invocation object, and
// component definition.
vm.stack.push(vm[ARGS]);
vm.stack.push(invocation);
vm.stack.push(reified);
return new TemplateIteratorImpl(vm);
}
function renderComponent(runtime, treeBuilder, context, owner, definition, args = {}, dynamicScope = new DynamicScopeImpl()) {
var vm = VM.empty(runtime, {
treeBuilder,
handle: context.stdlib.main,
dynamicScope,
owner
}, context);
return renderInvocation(vm, context, owner, definition, recordToReference(args));
}
function recordToReference(record) {
var root = (0, _reference.createConstRef)(record, 'args');
return Object.keys(record).reduce((acc, key) => {
acc[key] = (0, _reference.childRefFor)(root, key);
return acc;
}, {});
}
var SERIALIZATION_FIRST_NODE_STRING = '%+b:0%';
_exports.SERIALIZATION_FIRST_NODE_STRING = SERIALIZATION_FIRST_NODE_STRING;
function isSerializationFirstNode(node) {
return node.nodeValue === SERIALIZATION_FIRST_NODE_STRING;
}
class RehydratingCursor extends CursorImpl {
constructor(element, nextSibling, startingBlockDepth) {
super(element, nextSibling);
this.startingBlockDepth = startingBlockDepth;
this.candidate = null;
this.injectedOmittedNode = false;
this.openBlockDepth = startingBlockDepth - 1;
}
}
class RehydrateBuilder extends NewElementBuilder {
constructor(env, parentNode, nextSibling) {
super(env, parentNode, nextSibling);
this.unmatchedAttributes = null;
this.blockDepth = 0;
if (nextSibling) throw new Error('Rehydration with nextSibling not supported');
var node = this.currentCursor.element.firstChild;
while (node !== null) {
if (isOpenBlock(node)) {
break;
}
node = node.nextSibling;
}
this.candidate = node;
var startingBlockOffset = getBlockDepth(node);
if (startingBlockOffset !== 0) {
// We are rehydrating from a partial tree and not the root component
// We need to add an extra block before the first block to rehydrate correctly
// The extra block is needed since the renderComponent API creates a synthetic component invocation which generates the extra block
var newBlockDepth = startingBlockOffset - 1;
var newCandidate = this.dom.createComment(`%+b:${newBlockDepth}%`);
node.parentNode.insertBefore(newCandidate, this.candidate);
var closingNode = node.nextSibling;
while (closingNode !== null) {
if (isCloseBlock(closingNode) && getBlockDepth(closingNode) === startingBlockOffset) {
break;
}
closingNode = closingNode.nextSibling;
}
var newClosingBlock = this.dom.createComment(`%-b:${newBlockDepth}%`);
node.parentNode.insertBefore(newClosingBlock, closingNode.nextSibling);
this.candidate = newCandidate;
this.startingBlockOffset = newBlockDepth;
} else {
this.startingBlockOffset = 0;
}
}
get currentCursor() {
return this[CURSOR_STACK].current;
}
get candidate() {
if (this.currentCursor) {
return this.currentCursor.candidate;
}
return null;
}
set candidate(node) {
var currentCursor = this.currentCursor;
currentCursor.candidate = node;
}
disableRehydration(nextSibling) {
var currentCursor = this.currentCursor; // rehydration will be disabled until we either:
// * hit popElement (and return to using the parent elements cursor)
// * hit closeBlock and the next sibling is a close block comment
// matching the expected openBlockDepth
currentCursor.candidate = null;
currentCursor.nextSibling = nextSibling;
}
enableRehydration(candidate) {
var currentCursor = this.currentCursor;
currentCursor.candidate = candidate;
currentCursor.nextSibling = null;
}
pushElement(element, nextSibling = null) {
var cursor = new RehydratingCursor(element, nextSibling, this.blockDepth || 0);
/**
* <div> <--------------- currentCursor.element
* <!--%+b:1%--> <------- would have been removed during openBlock
* <div> <--------------- currentCursor.candidate -> cursor.element
* <!--%+b:2%--> <----- currentCursor.candidate.firstChild -> cursor.candidate
* Foo
* <!--%-b:2%-->
* </div>
* <!--%-b:1%--> <------ becomes currentCursor.candidate
*/
if (this.candidate !== null) {
cursor.candidate = element.firstChild;
this.candidate = element.nextSibling;
}
this[CURSOR_STACK].push(cursor);
} // clears until the end of the current container
// either the current open block or higher
clearMismatch(candidate) {
var current = candidate;
var currentCursor = this.currentCursor;
if (currentCursor !== null) {
var openBlockDepth = currentCursor.openBlockDepth;
if (openBlockDepth >= currentCursor.startingBlockDepth) {
while (current) {
if (isCloseBlock(current)) {
var closeBlockDepth = getBlockDepthWithOffset(current, this.startingBlockOffset);
if (openBlockDepth >= closeBlockDepth) {
break;
}
}
current = this.remove(current);
}
} else {
while (current !== null) {
current = this.remove(current);
}
} // current cursor parentNode should be openCandidate if element
// or openCandidate.parentNode if comment
this.disableRehydration(current);
}
}
__openBlock() {
var {
currentCursor
} = this;
if (currentCursor === null) return;
var blockDepth = this.blockDepth;
this.blockDepth++;
var {
candidate
} = currentCursor;
if (candidate === null) return;
var {
tagName
} = currentCursor.element;
if (isOpenBlock(candidate) && getBlockDepthWithOffset(candidate, this.startingBlockOffset) === blockDepth) {
this.candidate = this.remove(candidate);
currentCursor.openBlockDepth = blockDepth;
} else if (tagName !== 'TITLE' && tagName !== 'SCRIPT' && tagName !== 'STYLE') {
this.clearMismatch(candidate);
}
}
__closeBlock() {
var {
currentCursor
} = this;
if (currentCursor === null) return; // openBlock is the last rehydrated open block
var openBlockDepth = currentCursor.openBlockDepth; // this currently is the expected next open block depth
this.blockDepth--;
var {
candidate
} = currentCursor;
var isRehydrating = false;
if (candidate !== null) {
isRehydrating = true; //assert(
// openBlockDepth === this.blockDepth,
// 'when rehydrating, openBlockDepth should match this.blockDepth here'
//);
if (isCloseBlock(candidate) && getBlockDepthWithOffset(candidate, this.startingBlockOffset) === openBlockDepth) {
var nextSibling = this.remove(candidate);
this.candidate = nextSibling;
currentCursor.openBlockDepth--;
} else {
// close the block and clear mismatch in parent container
// we will be either at the end of the element
// or at the end of our containing block
this.clearMismatch(candidate);
isRehydrating = false;
}
}
if (isRehydrating === false) {
// check if nextSibling matches our expected close block
// if so, we remove the close block comment and
// restore rehydration after clearMismatch disabled
var _nextSibling = currentCursor.nextSibling;
if (_nextSibling !== null && isCloseBlock(_nextSibling) && getBlockDepthWithOffset(_nextSibling, this.startingBlockOffset) === this.blockDepth) {
// restore rehydration state
var _candidate2 = this.remove(_nextSibling);
this.enableRehydration(_candidate2);
currentCursor.openBlockDepth--;
}
}
}
__appendNode(node) {
var {
candidate
} = this; // This code path is only used when inserting precisely one node. It needs more
// comparison logic, but we can probably lean on the cases where this code path
// is actually used.
if (candidate) {
return candidate;
} else {
return super.__appendNode(node);
}
}
__appendHTML(html) {
var candidateBounds = this.markerBounds();
if (candidateBounds) {
var first = candidateBounds.firstNode();
var last = candidateBounds.lastNode();
var newBounds = new ConcreteBounds(this.element, first.nextSibling, last.previousSibling);
var possibleEmptyMarker = this.remove(first);
this.remove(last);
if (possibleEmptyMarker !== null && isEmpty$1(possibleEmptyMarker)) {
this.candidate = this.remove(possibleEmptyMarker);
if (this.candidate !== null) {
this.clearMismatch(this.candidate);
}
}
return newBounds;
} else {
return super.__appendHTML(html);
}
}
remove(node) {
var element = node.parentNode;
var next = node.nextSibling;
element.removeChild(node);
return next;
}
markerBounds() {
var _candidate = this.candidate;
if (_candidate && isMarker(_candidate)) {
var first = _candidate;
var last = first.nextSibling;
while (last && !isMarker(last)) {
last = last.nextSibling;
}
return new ConcreteBounds(this.element, first, last);
} else {
return null;
}
}
__appendText(string) {
var {
candidate
} = this;
if (candidate) {
if (isTextNode(candidate)) {
if (candidate.nodeValue !== string) {
candidate.nodeValue = string;
}
this.candidate = candidate.nextSibling;
return candidate;
} else if (isSeparator(candidate)) {
this.candidate = this.remove(candidate);
return this.__appendText(string);
} else if (isEmpty$1(candidate) && string === '') {
this.candidate = this.remove(candidate);
return this.__appendText(string);
} else {
this.clearMismatch(candidate);
return super.__appendText(string);
}
} else {
return super.__appendText(string);
}
}
__appendComment(string) {
var _candidate = this.candidate;
if (_candidate && isComment(_candidate)) {
if (_candidate.nodeValue !== string) {
_candidate.nodeValue = string;
}
this.candidate = _candidate.nextSibling;
return _candidate;
} else if (_candidate) {
this.clearMismatch(_candidate);
}
return super.__appendComment(string);
}
__openElement(tag) {
var _candidate = this.candidate;
if (_candidate && isElement(_candidate) && isSameNodeType(_candidate, tag)) {
this.unmatchedAttributes = [].slice.call(_candidate.attributes);
return _candidate;
} else if (_candidate) {
if (isElement(_candidate) && _candidate.tagName === 'TBODY') {
this.pushElement(_candidate, null);
this.currentCursor.injectedOmittedNode = true;
return this.__openElement(tag);
}
this.clearMismatch(_candidate);
}
return super.__openElement(tag);
}
__setAttribute(name, value, namespace) {
var unmatched = this.unmatchedAttributes;
if (unmatched) {
var attr = findByName(unmatched, name);
if (attr) {
if (attr.value !== value) {
attr.value = value;
}
unmatched.splice(unmatched.indexOf(attr), 1);
return;
}
}
return super.__setAttribute(name, value, namespace);
}
__setProperty(name, value) {
var unmatched = this.unmatchedAttributes;
if (unmatched) {
var attr = findByName(unmatched, name);
if (attr) {
if (attr.value !== value) {
attr.value = value;
}
unmatched.splice(unmatched.indexOf(attr), 1);
return;
}
}
return super.__setProperty(name, value);
}
__flushElement(parent, constructing) {
var {
unmatchedAttributes: unmatched
} = this;
if (unmatched) {
for (var i = 0; i < unmatched.length; i++) {
this.constructing.removeAttribute(unmatched[i].name);
}
this.unmatchedAttributes = null;
} else {
super.__flushElement(parent, constructing);
}
}
willCloseElement() {
var {
candidate,
currentCursor
} = this;
if (candidate !== null) {
this.clearMismatch(candidate);
}
if (currentCursor && currentCursor.injectedOmittedNode) {
this.popElement();
}
super.willCloseElement();
}
getMarker(element, guid) {
var marker = element.querySelector(`script[glmr="${guid}"]`);
if (marker) {
return marker;
}
return null;
}
__pushRemoteElement(element, cursorId, insertBefore) {
var marker = this.getMarker(element, cursorId);
if (insertBefore === undefined) {
while (element.firstChild !== null && element.firstChild !== marker) {
this.remove(element.firstChild);
}
insertBefore = null;
}
var cursor = new RehydratingCursor(element, null, this.blockDepth);
this[CURSOR_STACK].push(cursor);
if (marker === null) {
this.disableRehydration(insertBefore);
} else {
this.candidate = this.remove(marker);
}
var block = new RemoteLiveBlock(element);
return this.pushLiveBlock(block, true);
}
didAppendBounds(bounds) {
super.didAppendBounds(bounds);
if (this.candidate) {
var last = bounds.lastNode();
this.candidate = last && last.nextSibling;
}
return bounds;
}
}
_exports.RehydrateBuilder = RehydrateBuilder;
function isTextNode(node) {
return node.nodeType === 3;
}
function isComment(node) {
return node.nodeType === 8;
}
function isOpenBlock(node) {
return node.nodeType === 8
/* COMMENT_NODE */
&& node.nodeValue.lastIndexOf('%+b:', 0) === 0;
}
function isCloseBlock(node) {
return node.nodeType === 8
/* COMMENT_NODE */
&& node.nodeValue.lastIndexOf('%-b:', 0) === 0;
}
function getBlockDepth(node) {
return parseInt(node.nodeValue.slice(4), 10);
}
function getBlockDepthWithOffset(node, offset) {
return getBlockDepth(node) - offset;
}
function isElement(node) {
return node.nodeType === 1;
}
function isMarker(node) {
return node.nodeType === 8 && node.nodeValue === '%glmr%';
}
function isSeparator(node) {
return node.nodeType === 8 && node.nodeValue === '%|%';
}
function isEmpty$1(node) {
return node.nodeType === 8 && node.nodeValue === '% %';
}
function isSameNodeType(candidate, tag) {
if (candidate.namespaceURI === "http://www.w3.org/2000/svg"
/* SVG */
) {
return candidate.tagName === tag;
}
return candidate.tagName === tag.toUpperCase();
}
function findByName(array, name) {
for (var i = 0; i < array.length; i++) {
var attr = array[i];
if (attr.name === name) return attr;
}
return undefined;
}
function rehydrationBuilder(env, cursor) {
return RehydrateBuilder.forInitialRender(env, cursor);
}
var ARGS_CACHES = true
/* DEBUG */
? new WeakMap() : undefined;
function getArgs(proxy) {
return (0, _validator.getValue)(true
/* DEBUG */
? ARGS_CACHES.get(proxy) : proxy.argsCache);
}
class SimpleArgsProxy {
constructor(context, computeArgs = () => EMPTY_ARGS) {
var argsCache = (0, _validator.createCache)(() => computeArgs(context));
if (true
/* DEBUG */
) {
ARGS_CACHES.set(this, argsCache);
Object.freeze(this);
} else {
this.argsCache = argsCache;
}
}
get named() {
return getArgs(this).named || EMPTY_NAMED;
}
get positional() {
return getArgs(this).positional || EMPTY_POSITIONAL;
}
} ////////////
function invokeHelper(context, definition, computeArgs) {
if (true
/* DEBUG */
&& (typeof context !== 'object' || context === null)) {
throw new Error(`Expected a context object to be passed as the first parameter to invokeHelper, got ${context}`);
}
var owner = (0, _owner2.getOwner)(context);
var internalManager = (0, _manager5.getInternalHelperManager)(definition); // TODO: figure out why assert isn't using the TS assert thing
if (true
/* DEBUG */
&& !internalManager) {
throw new Error(`Expected a helper definition to be passed as the second parameter to invokeHelper, but no helper manager was found. The definition value that was passed was \`${(0, _util.debugToString)(definition)}\`. Did you use setHelperManager to associate a helper manager with this value?`);
}
if (true
/* DEBUG */
&& typeof internalManager === 'function') {
throw new Error('Found a helper manager, but it was an internal built-in helper manager. `invokeHelper` does not support internal helpers yet.');
}
var manager = internalManager.getDelegateFor(owner);
var args = new SimpleArgsProxy(context, computeArgs);
var bucket = manager.createHelper(definition, args);
var cache;
if ((0, _manager5.hasValue)(manager)) {
cache = (0, _validator.createCache)(() => {
if (true
/* DEBUG */
&& ((0, _destroyable2.isDestroying)(cache) || (0, _destroyable2.isDestroyed)(cache))) {
throw new Error(`You attempted to get the value of a helper after the helper was destroyed, which is not allowed`);
}
return manager.getValue(bucket);
});
(0, _destroyable2.associateDestroyableChild)(context, cache);
} else {
throw new Error('TODO: unreachable, to be implemented with hasScheduledEffect');
}
if ((0, _manager5.hasDestroyable)(manager)) {
var destroyable = manager.getDestroyable(bucket);
(0, _destroyable2.associateDestroyableChild)(cache, destroyable);
}
return cache;
}
function internalHelper(helper) {
return (0, _manager5.setInternalHelperManager)(helper, {});
}
var context = (0, _util.buildUntouchableThis)('`fn` helper');
/**
The `fn` helper allows you to ensure a function that you are passing off
to another component, helper, or modifier has access to arguments that are
available in the template.
For example, if you have an `each` helper looping over a number of items, you
may need to pass a function that expects to receive the item as an argument
to a component invoked within the loop. Here's how you could use the `fn`
helper to pass both the function and its arguments together:
```app/templates/components/items-listing.hbs
{{#each @items as |item|}}
<DisplayItem @item=item @select={{fn this.handleSelected item}} />
{{/each}}
```
```app/components/items-list.js
import Component from '@glimmer/component';
import { action } from '@ember/object';
export default class ItemsList extends Component {
handleSelected = (item) => {
// ...snip...
}
}
```
In this case the `display-item` component will receive a normal function
that it can invoke. When it invokes the function, the `handleSelected`
function will receive the `item` and any arguments passed, thanks to the
`fn` helper.
Let's take look at what that means in a couple circumstances:
- When invoked as `this.args.select()` the `handleSelected` function will
receive the `item` from the loop as its first and only argument.
- When invoked as `this.args.select('foo')` the `handleSelected` function
will receive the `item` from the loop as its first argument and the
string `'foo'` as its second argument.
In the example above, we used an arrow function to ensure that
`handleSelected` is properly bound to the `items-list`, but let's explore what
happens if we left out the arrow function:
```app/components/items-list.js
import Component from '@glimmer/component';
export default class ItemsList extends Component {
handleSelected(item) {
// ...snip...
}
}
```
In this example, when `handleSelected` is invoked inside the `display-item`
component, it will **not** have access to the component instance. In other
words, it will have no `this` context, so please make sure your functions
are bound (via an arrow function or other means) before passing into `fn`!
See also [partial application](https://en.wikipedia.org/wiki/Partial_application).
@method fn
@public
*/
var fn = internalHelper(({
positional
}) => {
var callbackRef = positional[0];
if (true
/* DEBUG */
) assertCallbackIsFn(callbackRef);
return (0, _reference.createComputeRef)(() => {
return (...invocationArgs) => {
var [fn, ...args] = (0, _runtime.reifyPositional)(positional);
if (true
/* DEBUG */
) assertCallbackIsFn(callbackRef);
if ((0, _reference.isInvokableRef)(callbackRef)) {
var value = args.length > 0 ? args[0] : invocationArgs[0];
return (0, _reference.updateRef)(callbackRef, value);
} else {
return fn.call(context, ...args, ...invocationArgs);
}
};
}, null, 'fn');
});
_exports.fn = fn;
function assertCallbackIsFn(callbackRef) {
if (!(callbackRef && ((0, _reference.isInvokableRef)(callbackRef) || typeof (0, _reference.valueForRef)(callbackRef) === 'function'))) {
throw new Error(`You must pass a function as the \`fn\` helpers first argument, you passed ${callbackRef ? (0, _reference.valueForRef)(callbackRef) : callbackRef}. While rendering:\n\n${callbackRef === null || callbackRef === void 0 ? void 0 : callbackRef.debugLabel}`);
}
}
var wrapHashProxy;
if (true
/* DEBUG */
) {
wrapHashProxy = hash => {
return new Proxy(hash, {
set(target, key, value) {
(true && !(false) && (0, _globalContext.deprecate)(`You set the '${String(key)}' property on a {{hash}} object. Setting properties on objects generated by {{hash}} is deprecated. Please update to use an object created with a tracked property or getter, or with a custom helper.`, false, {
id: 'setting-on-hash'
}));
target[key] = value;
return true;
}
});
};
}
/**
Use the `{{hash}}` helper to create a hash to pass as an option to your
components. This is specially useful for contextual components where you can
just yield a hash:
```handlebars
{{yield (hash
name='Sarah'
title=office
)}}
```
Would result in an object such as:
```js
{ name: 'Sarah', title: this.get('office') }
```
Where the `title` is bound to updates of the `office` property.
Note that the hash is an empty object with no prototype chain, therefore
common methods like `toString` are not available in the resulting hash.
If you need to use such a method, you can use the `call` or `apply`
approach:
```js
function toString(obj) {
return Object.prototype.toString.apply(obj);
}
```
@method hash
@param {Object} options
@return {Object} Hash
@public
*/
var hash = internalHelper(({
named
}) => {
var ref = (0, _reference.createComputeRef)(() => {
var hash = (0, _runtime.reifyNamed)(named);
if (true
/* DEBUG */
&& _util.HAS_NATIVE_PROXY) {
hash = wrapHashProxy(hash);
}
return hash;
}, null, 'hash'); // Setup the children so that templates can bypass getting the value of
// the reference and treat children lazily
var children = new Map();
for (var name in named) {
children.set(name, named[name]);
}
ref.children = children;
return ref;
});
/**
Use the `{{array}}` helper to create an array to pass as an option to your
components.
```handlebars
<MyComponent @people={{array
'Tom Dale'
'Yehuda Katz'
this.myOtherPerson}}
/>
```
or
```handlebars
{{my-component people=(array
'Tom Dale'
'Yehuda Katz'
this.myOtherPerson)
}}
```
Would result in an object such as:
```js
['Tom Dale', 'Yehuda Katz', this.get('myOtherPerson')]
```
Where the 3rd item in the array is bound to updates of the `myOtherPerson` property.
@method array
@param {Array} options
@return {Array} Array
@public
*/
_exports.hash = hash;
var array = internalHelper(({
positional
}) => {
return (0, _reference.createComputeRef)(() => (0, _runtime.reifyPositional)(positional), null, 'array');
});
/**
Dynamically look up a property on an object. The second argument to `{{get}}`
should have a string value, although it can be bound.
For example, these two usages are equivalent:
```app/components/developer-detail.js
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
export default class extends Component {
@tracked developer = {
name: "Sandi Metz",
language: "Ruby"
}
}
```
```handlebars
{{this.developer.name}}
{{get this.developer "name"}}
```
If there were several facts about a person, the `{{get}}` helper can dynamically
pick one:
```app/templates/application.hbs
<DeveloperDetail @factName="language" />
```
```handlebars
{{get this.developer @factName}}
```
For a more complex example, this template would allow the user to switch
between showing the user's height and weight with a click:
```app/components/developer-detail.js
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
export default class extends Component {
@tracked developer = {
name: "Sandi Metz",
language: "Ruby"
}
@tracked currentFact = 'name'
showFact = (fact) => {
this.currentFact = fact;
}
}
```
```app/components/developer-detail.js
{{get this.developer this.currentFact}}
<button {{on 'click' (fn this.showFact "name")}}>Show name</button>
<button {{on 'click' (fn this.showFact "language")}}>Show language</button>
```
The `{{get}}` helper can also respect mutable values itself. For example:
```app/components/developer-detail.js
<Input @value={{mut (get this.person this.currentFact)}} />
<button {{on 'click' (fn this.showFact "name")}}>Show name</button>
<button {{on 'click' (fn this.showFact "language")}}>Show language</button>
```
Would allow the user to swap what fact is being displayed, and also edit
that fact via a two-way mutable binding.
@public
@method get
*/
_exports.array = array;
var get = internalHelper(({
positional
}) => {
var _a, _b;
var sourceRef = (_a = positional[0]) !== null && _a !== void 0 ? _a : _reference.UNDEFINED_REFERENCE;
var pathRef = (_b = positional[1]) !== null && _b !== void 0 ? _b : _reference.UNDEFINED_REFERENCE;
return (0, _reference.createComputeRef)(() => {
var source = (0, _reference.valueForRef)(sourceRef);
if ((0, _util.isDict)(source)) {
return (0, _globalContext.getPath)(source, String((0, _reference.valueForRef)(pathRef)));
}
}, value => {
var source = (0, _reference.valueForRef)(sourceRef);
if ((0, _util.isDict)(source)) {
return (0, _globalContext.setPath)(source, String((0, _reference.valueForRef)(pathRef)), value);
}
}, 'get');
});
_exports.get = get;
var isEmpty$2 = value => {
return value === null || value === undefined || typeof value.toString !== 'function';
};
var normalizeTextValue = value => {
if (isEmpty$2(value)) {
return '';
}
return String(value);
};
/**
Concatenates the given arguments into a string.
Example:
```handlebars
{{some-component name=(concat firstName " " lastName)}}
{{! would pass name="<first name value> <last name value>" to the component}}
```
or for angle bracket invocation, you actually don't need concat at all.
```handlebars
<SomeComponent @name="{{firstName}} {{lastName}}" />
```
@public
@method concat
*/
var concat = internalHelper(({
positional
}) => {
return (0, _reference.createComputeRef)(() => (0, _runtime.reifyPositional)(positional).map(normalizeTextValue).join(''), null, 'concat');
});
_exports.concat = concat;
var untouchableContext = (0, _util.buildUntouchableThis)('`on` modifier');
/*
Internet Explorer 11 does not support `once` and also does not support
passing `eventOptions`. In some situations it then throws a weird script
error, like:
```
Could not complete the operation due to error 80020101
```
This flag determines, whether `{ once: true }` and thus also event options in
general are supported.
*/
var SUPPORTS_EVENT_OPTIONS = (() => {
try {
var div = document.createElement('div');
var counter = 0;
div.addEventListener('click', () => counter++, {
once: true
});
var event;
if (typeof Event === 'function') {
event = new Event('click');
} else {
event = document.createEvent('Event');
event.initEvent('click', true, true);
}
div.dispatchEvent(event);
div.dispatchEvent(event);
return counter === 1;
} catch (error) {
return false;
}
})();
class OnModifierState {
constructor(element, args) {
this.tag = (0, _validator.createUpdatableTag)();
this.shouldUpdate = true;
this.element = element;
this.args = args;
}
updateFromArgs() {
var {
args
} = this;
var {
once,
passive,
capture
} = (0, _runtime.reifyNamed)(args.named);
if (once !== this.once) {
this.once = once;
this.shouldUpdate = true;
}
if (passive !== this.passive) {
this.passive = passive;
this.shouldUpdate = true;
}
if (capture !== this.capture) {
this.capture = capture;
this.shouldUpdate = true;
}
var options;
if (once || passive || capture) {
options = this.options = {
once,
passive,
capture
};
} else {
this.options = undefined;
}
if (true
/* DEBUG */
&& (args.positional[0] === undefined || typeof (0, _reference.valueForRef)(args.positional[0]) !== 'string')) {
throw new Error('You must pass a valid DOM event name as the first argument to the `on` modifier');
}
var eventName = (0, _reference.valueForRef)(args.positional[0]);
if (eventName !== this.eventName) {
this.eventName = eventName;
this.shouldUpdate = true;
}
var userProvidedCallbackReference = args.positional[1];
if (true
/* DEBUG */
) {
if (args.positional[1] === undefined) {
throw new Error(`You must pass a function as the second argument to the \`on\` modifier.`);
}
var value = (0, _reference.valueForRef)(userProvidedCallbackReference);
if (typeof value !== 'function') {
throw new Error(`You must pass a function as the second argument to the \`on\` modifier, you passed ${value === null ? 'null' : typeof value}. While rendering:\n\n${userProvidedCallbackReference.debugLabel}`);
}
}
var userProvidedCallback = (0, _reference.valueForRef)(userProvidedCallbackReference);
if (userProvidedCallback !== this.userProvidedCallback) {
this.userProvidedCallback = userProvidedCallback;
this.shouldUpdate = true;
}
if (true
/* DEBUG */
&& args.positional.length !== 2) {
throw new Error(`You can only pass two positional arguments (event name and callback) to the \`on\` modifier, but you provided ${args.positional.length}. Consider using the \`fn\` helper to provide additional arguments to the \`on\` callback.`);
}
var needsCustomCallback = SUPPORTS_EVENT_OPTIONS === false && once ||
/* needs manual once implementation */
true
/* DEBUG */
&& passive;
/* needs passive enforcement */
if (this.shouldUpdate) {
if (needsCustomCallback) {
var _callback = this.callback = function (event) {
if (true
/* DEBUG */
&& passive) {
event.preventDefault = () => {
throw new Error(`You marked this listener as 'passive', meaning that you must not call 'event.preventDefault()': \n\n${userProvidedCallback}`);
};
}
if (!SUPPORTS_EVENT_OPTIONS && once) {
removeEventListener(this, eventName, _callback, options);
}
return userProvidedCallback.call(untouchableContext, event);
};
} else if (true
/* DEBUG */
) {
// prevent the callback from being bound to the element
this.callback = userProvidedCallback.bind(untouchableContext);
} else {
this.callback = userProvidedCallback;
}
}
}
}
var adds = 0;
var removes = 0;
function removeEventListener(element, eventName, callback, options) {
removes++;
if (SUPPORTS_EVENT_OPTIONS) {
// when options are supported, use them across the board
element.removeEventListener(eventName, callback, options);
} else if (options !== undefined && options.capture) {
// used only in the following case:
//
// `{ once: true | false, passive: true | false, capture: true }
//
// `once` is handled via a custom callback that removes after first
// invocation so we only care about capture here as a boolean
element.removeEventListener(eventName, callback, true);
} else {
// used only in the following cases:
//
// * where there is no options
// * `{ once: true | false, passive: true | false, capture: false }
element.removeEventListener(eventName, callback);
}
}
function addEventListener(element, eventName, callback, options) {
adds++;
if (SUPPORTS_EVENT_OPTIONS) {
// when options are supported, use them across the board
element.addEventListener(eventName, callback, options);
} else if (options !== undefined && options.capture) {
// used only in the following case:
//
// `{ once: true | false, passive: true | false, capture: true }
//
// `once` is handled via a custom callback that removes after first
// invocation so we only care about capture here as a boolean
element.addEventListener(eventName, callback, true);
} else {
// used only in the following cases:
//
// * where there is no options
// * `{ once: true | false, passive: true | false, capture: false }
element.addEventListener(eventName, callback);
}
}
/**
The `{{on}}` modifier lets you easily add event listeners (it uses
[EventTarget.addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)
internally).
For example, if you'd like to run a function on your component when a `<button>`
in the components template is clicked you might do something like:
```app/components/like-post.hbs
<button {{on 'click' this.saveLike}}>Like this post!</button>
```
```app/components/like-post.js
import Component from '@glimmer/component';
import { action } from '@ember/object';
export default class LikePostComponent extends Component {
saveLike = () => {
// someone likes your post!
// better send a request off to your server...
}
}
```
### Arguments
`{{on}}` accepts two positional arguments, and a few named arguments.
The positional arguments are:
- `event` -- the name to use when calling `addEventListener`
- `callback` -- the function to be passed to `addEventListener`
The named arguments are:
- capture -- a `true` value indicates that events of this type will be dispatched
to the registered listener before being dispatched to any EventTarget beneath it
in the DOM tree.
- once -- indicates that the listener should be invoked at most once after being
added. If true, the listener would be automatically removed when invoked.
- passive -- if `true`, indicates that the function specified by listener will never
call preventDefault(). If a passive listener does call preventDefault(), the user
agent will do nothing other than generate a console warning. See
[Improving scrolling performance with passive listeners](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Improving_scrolling_performance_with_passive_listeners)
to learn more.
The callback function passed to `{{on}}` will receive any arguments that are passed
to the event handler. Most commonly this would be the `event` itself.
If you would like to pass additional arguments to the function you should use
the `{{fn}}` helper.
For example, in our example case above if you'd like to pass in the post that
was being liked when the button is clicked you could do something like:
```app/components/like-post.hbs
<button {{on 'click' (fn this.saveLike @post)}}>Like this post!</button>
```
In this case, the `saveLike` function will receive two arguments: the click event
and the value of `@post`.
### Function Context
In the example above, we used an arrow function to ensure that `likePost` is
properly bound to the `items-list`, but let's explore what happens if we
left out the arrow function:
```app/components/like-post.js
import Component from '@glimmer/component';
export default class LikePostComponent extends Component {
saveLike() {
// ...snip...
}
}
```
In this example, when the button is clicked `saveLike` will be invoked,
it will **not** have access to the component instance. In other
words, it will have no `this` context, so please make sure your functions
are bound (via an arrow function or other means) before passing into `on`!
@method on
@public
*/
class OnModifierManager {
constructor() {
this.SUPPORTS_EVENT_OPTIONS = SUPPORTS_EVENT_OPTIONS;
}
getDebugName() {
return 'on';
}
get counters() {
return {
adds,
removes
};
}
create(_owner, element, _state, args) {
return new OnModifierState(element, args);
}
getTag(state) {
if (state === null) {
return null;
}
return state.tag;
}
install(state) {
if (state === null) {
return;
}
state.updateFromArgs();
var {
element,
eventName,
callback,
options
} = state;
addEventListener(element, eventName, callback, options);
(0, _destroyable2.registerDestructor)(state, () => removeEventListener(element, eventName, callback, options));
state.shouldUpdate = false;
}
update(state) {
if (state === null) {
return;
} // stash prior state for el.removeEventListener
var {
element,
eventName,
callback,
options
} = state;
state.updateFromArgs();
if (!state.shouldUpdate) {
return;
} // use prior state values for removal
removeEventListener(element, eventName, callback, options); // read updated values from the state object
addEventListener(state.element, state.eventName, state.callback, state.options);
state.shouldUpdate = false;
}
getDestroyable(state) {
return state;
}
}
var on = (0, _manager5.setInternalModifierManager)(new OnModifierManager(), {});
_exports.on = on;
});
define("@glimmer/tracking/index", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "tracked", {
enumerable: true,
get: function () {
return _metal.tracked;
}
});
});
define("@glimmer/tracking/primitives/cache", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "createCache", {
enumerable: true,
get: function () {
return _metal.createCache;
}
});
Object.defineProperty(_exports, "getValue", {
enumerable: true,
get: function () {
return _metal.getValue;
}
});
Object.defineProperty(_exports, "isConst", {
enumerable: true,
get: function () {
return _metal.isConst;
}
});
});
define("@glimmer/util", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.assertNever = assertNever;
_exports.assert = debugAssert$$1;
_exports.deprecate = deprecate$$1;
_exports.dict = dict;
_exports.isDict = isDict;
_exports.isObject = isObject;
_exports.isSerializationFirstNode = isSerializationFirstNode;
_exports.fillNulls = fillNulls;
_exports.values = values;
_exports.castToSimple = castToSimple;
_exports.castToBrowser = castToBrowser;
_exports.checkNode = checkNode;
_exports.intern = intern;
_exports.buildUntouchableThis = buildUntouchableThis;
_exports.emptyArray = emptyArray;
_exports.isEmptyArray = isEmptyArray;
_exports.clearElement = clearElement;
_exports.keys = keys;
_exports.unwrap = unwrap;
_exports.expect = expect;
_exports.unreachable = unreachable;
_exports.exhausted = exhausted;
_exports.enumerableSymbol = enumerableSymbol;
_exports.strip = strip;
_exports.isHandle = isHandle;
_exports.isNonPrimitiveHandle = isNonPrimitiveHandle;
_exports.constants = constants;
_exports.isSmallInt = isSmallInt;
_exports.encodeNegative = encodeNegative;
_exports.decodeNegative = decodeNegative;
_exports.encodePositive = encodePositive;
_exports.decodePositive = decodePositive;
_exports.encodeHandle = encodeHandle;
_exports.decodeHandle = decodeHandle;
_exports.encodeImmediate = encodeImmediate;
_exports.decodeImmediate = decodeImmediate;
_exports.unwrapHandle = unwrapHandle;
_exports.unwrapTemplate = unwrapTemplate;
_exports.extractHandle = extractHandle;
_exports.isOkHandle = isOkHandle;
_exports.isErrHandle = isErrHandle;
_exports.isPresent = isPresent;
_exports.ifPresent = ifPresent;
_exports.toPresentOption = toPresentOption;
_exports.assertPresent = assertPresent;
_exports.mapPresent = mapPresent;
_exports.symbol = _exports.tuple = _exports.HAS_NATIVE_SYMBOL = _exports.HAS_NATIVE_PROXY = _exports.EMPTY_NUMBER_ARRAY = _exports.EMPTY_STRING_ARRAY = _exports.EMPTY_ARRAY = _exports.verifySteps = _exports.logStep = _exports.endTestSteps = _exports.beginTestSteps = _exports.debugToString = _exports._WeakSet = _exports.assign = _exports.SERIALIZATION_FIRST_NODE_STRING = _exports.Stack = _exports.LOGGER = _exports.LOCAL_LOGGER = void 0;
var EMPTY_ARRAY = Object.freeze([]);
_exports.EMPTY_ARRAY = EMPTY_ARRAY;
function emptyArray() {
return EMPTY_ARRAY;
}
var EMPTY_STRING_ARRAY = emptyArray();
_exports.EMPTY_STRING_ARRAY = EMPTY_STRING_ARRAY;
var EMPTY_NUMBER_ARRAY = emptyArray();
/**
* This function returns `true` if the input array is the special empty array sentinel,
* which is sometimes used for optimizations.
*/
_exports.EMPTY_NUMBER_ARRAY = EMPTY_NUMBER_ARRAY;
function isEmptyArray(input) {
return input === EMPTY_ARRAY;
} // import Logger from './logger';
function debugAssert$$1(test, msg) {
// if (!alreadyWarned) {
// alreadyWarned = true;
// Logger.warn("Don't leave debug assertions on in public builds");
// }
if (!test) {
throw new Error(msg || 'assertion failure');
}
}
function deprecate$$1(desc) {
LOCAL_LOGGER.warn(`DEPRECATION: ${desc}`);
}
function dict() {
return Object.create(null);
}
function isDict(u) {
return u !== null && u !== undefined;
}
function isObject(u) {
return typeof u === 'function' || typeof u === 'object' && u !== null;
}
class StackImpl {
constructor(values = []) {
this.current = null;
this.stack = values;
}
get size() {
return this.stack.length;
}
push(item) {
this.current = item;
this.stack.push(item);
}
pop() {
var item = this.stack.pop();
var len = this.stack.length;
this.current = len === 0 ? null : this.stack[len - 1];
return item === undefined ? null : item;
}
nth(from) {
var len = this.stack.length;
return len < from ? null : this.stack[len - from];
}
isEmpty() {
return this.stack.length === 0;
}
toArray() {
return this.stack;
}
}
_exports.Stack = StackImpl;
function clearElement(parent) {
var current = parent.firstChild;
while (current) {
var next = current.nextSibling;
parent.removeChild(current);
current = next;
}
}
var SERIALIZATION_FIRST_NODE_STRING = '%+b:0%';
_exports.SERIALIZATION_FIRST_NODE_STRING = SERIALIZATION_FIRST_NODE_STRING;
function isSerializationFirstNode(node) {
return node.nodeValue === SERIALIZATION_FIRST_NODE_STRING;
}
var _a;
var {
keys: objKeys
} = Object;
function assignFn(obj) {
for (var i = 1; i < arguments.length; i++) {
var assignment = arguments[i];
if (assignment === null || typeof assignment !== 'object') continue;
var _keys = objKeys(assignment);
for (var j = 0; j < _keys.length; j++) {
var key = _keys[j];
obj[key] = assignment[key];
}
}
return obj;
}
var assign = (_a = Object.assign) !== null && _a !== void 0 ? _a : assignFn;
_exports.assign = assign;
function fillNulls(count) {
var arr = new Array(count);
for (var i = 0; i < count; i++) {
arr[i] = null;
}
return arr;
}
function values(obj) {
var vals = [];
for (var key in obj) {
vals.push(obj[key]);
}
return vals;
}
/**
Strongly hint runtimes to intern the provided string.
When do I need to use this function?
For the most part, never. Pre-mature optimization is bad, and often the
runtime does exactly what you need it to, and more often the trade-off isn't
worth it.
Why?
Runtimes store strings in at least 2 different representations:
Ropes and Symbols (interned strings). The Rope provides a memory efficient
data-structure for strings created from concatenation or some other string
manipulation like splitting.
Unfortunately checking equality of different ropes can be quite costly as
runtimes must resort to clever string comparison algorithms. These
algorithms typically cost in proportion to the length of the string.
Luckily, this is where the Symbols (interned strings) shine. As Symbols are
unique by their string content, equality checks can be done by pointer
comparison.
How do I know if my string is a rope or symbol?
Typically (warning general sweeping statement, but truthy in runtimes at
present) static strings created as part of the JS source are interned.
Strings often used for comparisons can be interned at runtime if some
criteria are met. One of these criteria can be the size of the entire rope.
For example, in chrome 38 a rope longer then 12 characters will not
intern, nor will segments of that rope.
Some numbers: http://jsperf.com/eval-vs-keys/8
Known Trick™
@private
@return {String} interned version of the provided string
*/
function intern(str) {
var obj = {};
obj[str] = 1;
for (var key in obj) {
if (key === str) {
return key;
}
}
return str;
}
var HAS_NATIVE_PROXY = typeof Proxy === 'function';
_exports.HAS_NATIVE_PROXY = HAS_NATIVE_PROXY;
var HAS_NATIVE_SYMBOL = function () {
if (typeof Symbol !== 'function') {
return false;
} // eslint-disable-next-line symbol-description
return typeof Symbol() === 'symbol';
}();
_exports.HAS_NATIVE_SYMBOL = HAS_NATIVE_SYMBOL;
function keys(obj) {
return Object.keys(obj);
}
function unwrap(val) {
if (val === null || val === undefined) throw new Error(`Expected value to be present`);
return val;
}
function expect(val, message) {
if (val === null || val === undefined) throw new Error(message);
return val;
}
function unreachable(message = 'unreachable') {
return new Error(message);
}
function exhausted(value) {
throw new Error(`Exhausted ${value}`);
}
var tuple = (...args) => args;
_exports.tuple = tuple;
function enumerableSymbol(key) {
return intern(`__${key}${Math.floor(Math.random() * Date.now())}__`);
}
var symbol = HAS_NATIVE_SYMBOL ? Symbol : enumerableSymbol;
_exports.symbol = symbol;
function strip(strings, ...args) {
var out = '';
for (var i = 0; i < strings.length; i++) {
var string = strings[i];
var dynamic = args[i] !== undefined ? String(args[i]) : '';
out += `${string}${dynamic}`;
}
var lines = out.split('\n');
while (lines.length && lines[0].match(/^\s*$/)) {
lines.shift();
}
while (lines.length && lines[lines.length - 1].match(/^\s*$/)) {
lines.pop();
}
var min = Infinity;
for (var line of lines) {
var leading = line.match(/^\s*/)[0].length;
min = Math.min(min, leading);
}
var stripped = [];
for (var _line of lines) {
stripped.push(_line.slice(min));
}
return stripped.join('\n');
}
function isHandle(value) {
return value >= 0;
}
function isNonPrimitiveHandle(value) {
return value > 3
/* ENCODED_UNDEFINED_HANDLE */
;
}
function constants(...values) {
return [false, true, null, undefined, ...values];
}
function isSmallInt(value) {
return value % 1 === 0 && value <= 536870911
/* MAX_INT */
&& value >= -536870912
/* MIN_INT */
;
}
function encodeNegative(num) {
return num & -536870913
/* SIGN_BIT */
;
}
function decodeNegative(num) {
return num | ~-536870913
/* SIGN_BIT */
;
}
function encodePositive(num) {
return ~num;
}
function decodePositive(num) {
return ~num;
}
function encodeHandle(num) {
return num;
}
function decodeHandle(num) {
return num;
}
function encodeImmediate(num) {
num |= 0;
return num < 0 ? encodeNegative(num) : encodePositive(num);
}
function decodeImmediate(num) {
num |= 0;
return num > -536870913
/* SIGN_BIT */
? decodePositive(num) : decodeNegative(num);
} // Warm
[1, -1].forEach(x => decodeImmediate(encodeImmediate(x)));
function unwrapHandle(handle) {
if (typeof handle === 'number') {
return handle;
} else {
var error = handle.errors[0];
throw new Error(`Compile Error: ${error.problem} @ ${error.span.start}..${error.span.end}`);
}
}
function unwrapTemplate(template) {
if (template.result === 'error') {
throw new Error(`Compile Error: ${template.problem} @ ${template.span.start}..${template.span.end}`);
}
return template;
}
function extractHandle(handle) {
if (typeof handle === 'number') {
return handle;
} else {
return handle.handle;
}
}
function isOkHandle(handle) {
return typeof handle === 'number';
}
function isErrHandle(handle) {
return typeof handle === 'number';
}
var weakSet = typeof WeakSet === 'function' ? WeakSet : class WeakSetPolyFill {
constructor() {
this._map = new WeakMap();
}
add(val) {
this._map.set(val, true);
return this;
}
delete(val) {
return this._map.delete(val);
}
has(val) {
return this._map.has(val);
}
};
_exports._WeakSet = weakSet;
function castToSimple(node) {
if (isDocument(node)) {
return node;
} else if (isElement(node)) {
return node;
} else {
return node;
}
}
function castToBrowser(node, sugaryCheck) {
if (node === null || node === undefined) {
return null;
}
if (typeof document === undefined) {
throw new Error('Attempted to cast to a browser node in a non-browser context');
}
if (isDocument(node)) {
return node;
}
if (node.ownerDocument !== document) {
throw new Error('Attempted to cast to a browser node with a node that was not created from this document');
}
return checkNode(node, sugaryCheck);
}
function checkError(from, check) {
return new Error(`cannot cast a ${from} into ${check}`);
}
function isDocument(node) {
return node.nodeType === 9
/* DOCUMENT_NODE */
;
}
function isElement(node) {
return node.nodeType === 1
/* ELEMENT_NODE */
;
}
function checkNode(node, check) {
var isMatch = false;
if (node !== null) {
if (typeof check === 'string') {
isMatch = stringCheckNode(node, check);
} else if (Array.isArray(check)) {
isMatch = check.some(c => stringCheckNode(node, c));
} else {
throw unreachable();
}
}
if (isMatch) {
return node;
} else {
throw checkError(`SimpleElement(${node})`, check);
}
}
function stringCheckNode(node, check) {
switch (check) {
case 'NODE':
return true;
case 'HTML':
return node instanceof HTMLElement;
case 'SVG':
return node instanceof SVGElement;
case 'ELEMENT':
return node instanceof Element;
default:
if (check.toUpperCase() === check) {
throw new Error(`BUG: this code is missing handling for a generic node type`);
}
return node instanceof Element && node.tagName.toLowerCase() === check;
}
}
function isPresent(list) {
return list.length > 0;
}
function ifPresent(list, ifPresent, otherwise) {
if (isPresent(list)) {
return ifPresent(list);
} else {
return otherwise();
}
}
function toPresentOption(list) {
if (isPresent(list)) {
return list;
} else {
return null;
}
}
function assertPresent(list, message = `unexpected empty list`) {
if (!isPresent(list)) {
throw new Error(message);
}
}
function mapPresent(list, callback) {
if (list === null) {
return null;
}
var out = [];
for (var item of list) {
out.push(callback(item));
}
return out;
}
function buildUntouchableThis(source) {
var context = null;
if (true
/* DEBUG */
&& HAS_NATIVE_PROXY) {
var assertOnProperty = property => {
throw new Error(`You accessed \`this.${String(property)}\` from a function passed to the ${source}, but the function itself was not bound to a valid \`this\` context. Consider updating to use a bound function (for instance, use an arrow function, \`() => {}\`).`);
};
context = new Proxy({}, {
get(_target, property) {
assertOnProperty(property);
},
set(_target, property) {
assertOnProperty(property);
return false;
},
has(_target, property) {
assertOnProperty(property);
return false;
}
});
}
return context;
}
var debugToString;
if (true
/* DEBUG */
) {
var getFunctionName = fn => {
var functionName = fn.name;
if (functionName === undefined) {
var match = Function.prototype.toString.call(fn).match(/function (\w+)\s*\(/);
functionName = match && match[1] || '';
}
return functionName.replace(/^bound /, '');
};
var getObjectName = obj => {
var name;
var className;
if (obj.constructor && typeof obj.constructor === 'function') {
className = getFunctionName(obj.constructor);
}
if ('toString' in obj && obj.toString !== Object.prototype.toString && obj.toString !== Function.prototype.toString) {
name = obj.toString();
} // If the class has a decent looking name, and the `toString` is one of the
// default Ember toStrings, replace the constructor portion of the toString
// with the class name. We check the length of the class name to prevent doing
// this when the value is minified.
if (name && name.match(/<.*:ember\d+>/) && className && className[0] !== '_' && className.length > 2 && className !== 'Class') {
return name.replace(/<.*:/, `<${className}:`);
}
return name || className;
};
var getPrimitiveName = value => {
return String(value);
};
debugToString = value => {
if (typeof value === 'function') {
return getFunctionName(value) || `(unknown function)`;
} else if (typeof value === 'object' && value !== null) {
return getObjectName(value) || `(unknown object)`;
} else {
return getPrimitiveName(value);
}
};
}
var debugToString$1 = debugToString;
_exports.debugToString = debugToString$1;
var beginTestSteps;
_exports.beginTestSteps = beginTestSteps;
var endTestSteps;
_exports.endTestSteps = endTestSteps;
var verifySteps;
_exports.verifySteps = verifySteps;
var logStep;
/**
* This constant exists to make it easier to differentiate normal logs from
* errant console.logs. LOCAL_LOGGER should only be used inside a
* LOCAL_SHOULD_LOG check.
*
* It does not alleviate the need to check LOCAL_SHOULD_LOG, which is used
* for stripping.
*/
_exports.logStep = logStep;
var LOCAL_LOGGER = console;
/**
* This constant exists to make it easier to differentiate normal logs from
* errant console.logs. LOGGER can be used outside of LOCAL_SHOULD_LOG checks,
* and is meant to be used in the rare situation where a console.* call is
* actually appropriate.
*/
_exports.LOCAL_LOGGER = LOCAL_LOGGER;
var LOGGER = console;
_exports.LOGGER = LOGGER;
function assertNever(value, desc = 'unexpected unreachable branch') {
LOGGER.log('unreachable', value);
LOGGER.log(`${desc} :: ${JSON.stringify(value)} (${value})`);
throw new Error(`code reached unreachable`);
}
});
define("@glimmer/validator", ["exports", "@glimmer/global-context"], function (_exports, _globalContext) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.bump = bump;
_exports.createTag = createTag;
_exports.createUpdatableTag = createUpdatableTag;
_exports.isConstTag = isConstTag;
_exports.validateTag = validateTag;
_exports.valueForTag = valueForTag;
_exports.dirtyTagFor = dirtyTagFor;
_exports.tagFor = tagFor;
_exports.tagMetaFor = tagMetaFor;
_exports.beginTrackFrame = beginTrackFrame;
_exports.endTrackFrame = endTrackFrame;
_exports.beginUntrackFrame = beginUntrackFrame;
_exports.endUntrackFrame = endUntrackFrame;
_exports.resetTracking = resetTracking;
_exports.consumeTag = consumeTag;
_exports.isTracking = isTracking;
_exports.track = track;
_exports.untrack = untrack;
_exports.createCache = createCache;
_exports.isConst = isConst;
_exports.getValue = getValue;
_exports.trackedData = trackedData;
_exports.endTrackingTransaction = _exports.beginTrackingTransaction = _exports.runInTrackingTransaction = _exports.setTrackingTransactionEnv = _exports.logTrackingStack = _exports.VOLATILE = _exports.VOLATILE_TAG = _exports.VolatileTag = _exports.updateTag = _exports.INITIAL = _exports.dirtyTag = _exports.CURRENT_TAG = _exports.CurrentTag = _exports.CONSTANT = _exports.CONSTANT_TAG = _exports.COMPUTE = _exports.combine = _exports.ALLOW_CYCLES = void 0;
// eslint-disable-next-line @typescript-eslint/ban-types
function indexable(input) {
return input;
} // This is a duplicate utility from @glimmer/util because `@glimmer/validator`
// should not depend on any other @glimmer packages, in order to avoid pulling
// in types and prevent regressions in `@glimmer/tracking` (which has public types).
var symbol = typeof Symbol !== 'undefined' ? Symbol : // eslint-disable-next-line @typescript-eslint/no-explicit-any
key => `__${key}${Math.floor(Math.random() * Date.now())}__`; // eslint-disable-next-line @typescript-eslint/no-explicit-any
var symbolFor = typeof Symbol !== 'undefined' ? Symbol.for : key => `__GLIMMER_VALIDATOR_SYMBOL_FOR_${key}`;
function getGlobal() {
// eslint-disable-next-line node/no-unsupported-features/es-builtins
if (typeof globalThis !== 'undefined') return indexable(globalThis);
if (typeof self !== 'undefined') return indexable(self);
if (typeof window !== 'undefined') return indexable(window);
if (typeof global !== 'undefined') return indexable(global);
throw new Error('unable to locate global object');
}
function unwrap(val) {
if (val === null || val === undefined) throw new Error(`Expected value to be present`);
return val;
}
var beginTrackingTransaction;
_exports.beginTrackingTransaction = beginTrackingTransaction;
var endTrackingTransaction;
_exports.endTrackingTransaction = endTrackingTransaction;
var runInTrackingTransaction;
_exports.runInTrackingTransaction = runInTrackingTransaction;
var resetTrackingTransaction;
var setTrackingTransactionEnv;
_exports.setTrackingTransactionEnv = setTrackingTransactionEnv;
var assertTagNotConsumed;
var markTagAsConsumed;
var logTrackingStack;
_exports.logTrackingStack = logTrackingStack;
if (true
/* DEBUG */
) {
var CONSUMED_TAGS = null;
var TRANSACTION_STACK = []; /////////
var TRANSACTION_ENV = {
debugMessage(obj, keyName) {
var objName;
if (typeof obj === 'function') {
objName = obj.name;
} else if (typeof obj === 'object' && obj !== null) {
var className = obj.constructor && obj.constructor.name || '(unknown class)';
objName = `(an instance of ${className})`;
} else if (obj === undefined) {
objName = '(an unknown tag)';
} else {
objName = String(obj);
}
var dirtyString = keyName ? `\`${keyName}\` on \`${objName}\`` : `\`${objName}\``;
return `You attempted to update ${dirtyString}, but it had already been used previously in the same computation. Attempting to update a value after using it in a computation can cause logical errors, infinite revalidation bugs, and performance issues, and is not supported.`;
}
};
_exports.setTrackingTransactionEnv = setTrackingTransactionEnv = env => Object.assign(TRANSACTION_ENV, env);
_exports.beginTrackingTransaction = beginTrackingTransaction = _debugLabel => {
CONSUMED_TAGS = CONSUMED_TAGS || new WeakMap();
var debugLabel = _debugLabel || undefined;
var parent = TRANSACTION_STACK[TRANSACTION_STACK.length - 1] || null;
TRANSACTION_STACK.push({
parent,
debugLabel
});
};
_exports.endTrackingTransaction = endTrackingTransaction = () => {
if (TRANSACTION_STACK.length === 0) {
throw new Error('attempted to close a tracking transaction, but one was not open');
}
TRANSACTION_STACK.pop();
if (TRANSACTION_STACK.length === 0) {
CONSUMED_TAGS = null;
}
};
resetTrackingTransaction = () => {
var stack = '';
if (TRANSACTION_STACK.length > 0) {
stack = logTrackingStack(TRANSACTION_STACK[TRANSACTION_STACK.length - 1]);
}
TRANSACTION_STACK = [];
CONSUMED_TAGS = null;
return stack;
};
/**
* Creates a global autotracking transaction. This will prevent any backflow
* in any `track` calls within the transaction, even if they are not
* externally consumed.
*
* `runInAutotrackingTransaction` can be called within itself, and it will add
* onto the existing transaction if one exists.
*
* TODO: Only throw an error if the `track` is consumed.
*/
_exports.runInTrackingTransaction = runInTrackingTransaction = (fn, debugLabel) => {
beginTrackingTransaction(debugLabel);
var didError = true;
try {
var value = fn();
didError = false;
return value;
} finally {
if (didError !== true) {
endTrackingTransaction();
}
}
};
var nthIndex = (str, pattern, n, startingPos = -1) => {
var i = startingPos;
while (n-- > 0 && i++ < str.length) {
i = str.indexOf(pattern, i);
if (i < 0) break;
}
return i;
};
var makeTrackingErrorMessage = (transaction, obj, keyName) => {
var message = [TRANSACTION_ENV.debugMessage(obj, keyName && String(keyName))];
message.push(`\`${String(keyName)}\` was first used:`);
message.push(logTrackingStack(transaction));
message.push(`Stack trace for the update:`);
return message.join('\n\n');
};
_exports.logTrackingStack = logTrackingStack = transaction => {
var trackingStack = [];
var current = transaction || TRANSACTION_STACK[TRANSACTION_STACK.length - 1];
if (current === undefined) return '';
while (current) {
if (current.debugLabel) {
trackingStack.unshift(current.debugLabel);
}
current = current.parent;
} // TODO: Use String.prototype.repeat here once we can drop support for IE11
return trackingStack.map((label, index) => Array(2 * index + 1).join(' ') + label).join('\n');
};
markTagAsConsumed = _tag => {
if (!CONSUMED_TAGS || CONSUMED_TAGS.has(_tag)) return;
CONSUMED_TAGS.set(_tag, TRANSACTION_STACK[TRANSACTION_STACK.length - 1]); // We need to mark the tag and all of its subtags as consumed, so we need to
// cast it and access its internals. In the future this shouldn't be necessary,
// this is only for computed properties.
var tag = _tag;
if (tag.subtag) {
markTagAsConsumed(tag.subtag);
}
if (tag.subtags) {
tag.subtags.forEach(tag => markTagAsConsumed(tag));
}
};
assertTagNotConsumed = (tag, obj, keyName) => {
if (CONSUMED_TAGS === null) return;
var transaction = CONSUMED_TAGS.get(tag);
if (!transaction) return; // This hack makes the assertion message nicer, we can cut off the first
// few lines of the stack trace and let users know where the actual error
// occurred.
try {
(true && (0, _globalContext.assert)(false, makeTrackingErrorMessage(transaction, obj, keyName)));
} catch (e) {
if (e.stack) {
var updateStackBegin = e.stack.indexOf('Stack trace for the update:');
if (updateStackBegin !== -1) {
var start = nthIndex(e.stack, '\n', 1, updateStackBegin);
var end = nthIndex(e.stack, '\n', 4, updateStackBegin);
e.stack = e.stack.substr(0, start) + e.stack.substr(end);
}
}
throw e;
}
};
}
var CONSTANT = 0;
_exports.CONSTANT = CONSTANT;
var INITIAL = 1;
_exports.INITIAL = INITIAL;
var VOLATILE = NaN;
_exports.VOLATILE = VOLATILE;
var $REVISION = INITIAL;
function bump() {
$REVISION++;
} //////////
var COMPUTE = symbol('TAG_COMPUTE'); //////////
/**
* `value` receives a tag and returns an opaque Revision based on that tag. This
* snapshot can then later be passed to `validate` with the same tag to
* determine if the tag has changed at all since the time that `value` was
* called.
*
* @param tag
*/
_exports.COMPUTE = COMPUTE;
function valueForTag(tag) {
return tag[COMPUTE]();
}
/**
* `validate` receives a tag and a snapshot from a previous call to `value` with
* the same tag, and determines if the tag is still valid compared to the
* snapshot. If the tag's state has changed at all since then, `validate` will
* return false, otherwise it will return true. This is used to determine if a
* calculation related to the tags should be rerun.
*
* @param tag
* @param snapshot
*/
function validateTag(tag, snapshot) {
return snapshot >= tag[COMPUTE]();
}
var TYPE = symbol('TAG_TYPE'); // this is basically a const
// eslint-disable-next-line @typescript-eslint/naming-convention
var ALLOW_CYCLES;
_exports.ALLOW_CYCLES = ALLOW_CYCLES;
if (true
/* DEBUG */
) {
_exports.ALLOW_CYCLES = ALLOW_CYCLES = new WeakMap();
}
function allowsCycles(tag) {
if (ALLOW_CYCLES === undefined) {
return true;
} else {
return ALLOW_CYCLES.has(tag);
}
}
class MonomorphicTagImpl {
constructor(type) {
this.revision = INITIAL;
this.lastChecked = INITIAL;
this.lastValue = INITIAL;
this.isUpdating = false;
this.subtag = null;
this.subtagBufferCache = null;
this[TYPE] = type;
}
static combine(tags) {
switch (tags.length) {
case 0:
return CONSTANT_TAG;
case 1:
return tags[0];
default:
var tag = new MonomorphicTagImpl(2
/* Combinator */
);
tag.subtag = tags;
return tag;
}
}
[COMPUTE]() {
var {
lastChecked
} = this;
if (this.isUpdating === true) {
if (true
/* DEBUG */
&& !allowsCycles(this)) {
throw new Error('Cycles in tags are not allowed');
}
this.lastChecked = ++$REVISION;
} else if (lastChecked !== $REVISION) {
this.isUpdating = true;
this.lastChecked = $REVISION;
try {
var {
subtag,
revision
} = this;
if (subtag !== null) {
if (Array.isArray(subtag)) {
for (var i = 0; i < subtag.length; i++) {
var value = subtag[i][COMPUTE]();
revision = Math.max(value, revision);
}
} else {
var subtagValue = subtag[COMPUTE]();
if (subtagValue === this.subtagBufferCache) {
revision = Math.max(revision, this.lastValue);
} else {
// Clear the temporary buffer cache
this.subtagBufferCache = null;
revision = Math.max(revision, subtagValue);
}
}
}
this.lastValue = revision;
} finally {
this.isUpdating = false;
}
}
return this.lastValue;
}
static updateTag(_tag, _subtag) {
if (true
/* DEBUG */
&& _tag[TYPE] !== 1
/* Updatable */
) {
throw new Error('Attempted to update a tag that was not updatable');
} // TODO: TS 3.7 should allow us to do this via assertion
var tag = _tag;
var subtag = _subtag;
if (subtag === CONSTANT_TAG) {
tag.subtag = null;
} else {
// There are two different possibilities when updating a subtag:
//
// 1. subtag[COMPUTE]() <= tag[COMPUTE]();
// 2. subtag[COMPUTE]() > tag[COMPUTE]();
//
// The first possibility is completely fine within our caching model, but
// the second possibility presents a problem. If the parent tag has
// already been read, then it's value is cached and will not update to
// reflect the subtag's greater value. Next time the cache is busted, the
// subtag's value _will_ be read, and it's value will be _greater_ than
// the saved snapshot of the parent, causing the resulting calculation to
// be rerun erroneously.
//
// In order to prevent this, when we first update to a new subtag we store
// its computed value, and then check against that computed value on
// subsequent updates. If its value hasn't changed, then we return the
// parent's previous value. Once the subtag changes for the first time,
// we clear the cache and everything is finally in sync with the parent.
tag.subtagBufferCache = subtag[COMPUTE]();
tag.subtag = subtag;
}
}
static dirtyTag(tag, disableConsumptionAssertion) {
if (true
/* DEBUG */
&& !(tag[TYPE] === 1
/* Updatable */
|| tag[TYPE] === 0
/* Dirtyable */
)) {
throw new Error('Attempted to dirty a tag that was not dirtyable');
}
if (true
/* DEBUG */
&& disableConsumptionAssertion !== true) {
// Usually by this point, we've already asserted with better error information,
// but this is our last line of defense.
unwrap(assertTagNotConsumed)(tag);
}
tag.revision = ++$REVISION;
(0, _globalContext.scheduleRevalidate)();
}
}
var DIRTY_TAG = MonomorphicTagImpl.dirtyTag;
_exports.dirtyTag = DIRTY_TAG;
var UPDATE_TAG = MonomorphicTagImpl.updateTag; //////////
_exports.updateTag = UPDATE_TAG;
function createTag() {
return new MonomorphicTagImpl(0
/* Dirtyable */
);
}
function createUpdatableTag() {
return new MonomorphicTagImpl(1
/* Updatable */
);
} //////////
var CONSTANT_TAG = new MonomorphicTagImpl(3
/* Constant */
);
_exports.CONSTANT_TAG = CONSTANT_TAG;
function isConstTag(tag) {
return tag === CONSTANT_TAG;
} //////////
class VolatileTag {
[COMPUTE]() {
return VOLATILE;
}
}
_exports.VolatileTag = VolatileTag;
var VOLATILE_TAG = new VolatileTag(); //////////
_exports.VOLATILE_TAG = VOLATILE_TAG;
class CurrentTag {
[COMPUTE]() {
return $REVISION;
}
}
_exports.CurrentTag = CurrentTag;
var CURRENT_TAG = new CurrentTag(); //////////
_exports.CURRENT_TAG = CURRENT_TAG;
var combine = MonomorphicTagImpl.combine; // Warm
_exports.combine = combine;
var tag1 = createUpdatableTag();
var tag2 = createUpdatableTag();
var tag3 = createUpdatableTag();
valueForTag(tag1);
DIRTY_TAG(tag1);
valueForTag(tag1);
UPDATE_TAG(tag1, combine([tag2, tag3]));
valueForTag(tag1);
DIRTY_TAG(tag2);
valueForTag(tag1);
DIRTY_TAG(tag3);
valueForTag(tag1);
UPDATE_TAG(tag1, tag3);
valueForTag(tag1);
DIRTY_TAG(tag3);
valueForTag(tag1);
function isObjectLike(u) {
return typeof u === 'object' && u !== null || typeof u === 'function';
}
var TRACKED_TAGS = new WeakMap();
function dirtyTagFor(obj, key, meta) {
if (true
/* DEBUG */
&& !isObjectLike(obj)) {
throw new Error(`BUG: Can't update a tag for a primitive`);
}
var tags = meta === undefined ? TRACKED_TAGS.get(obj) : meta; // No tags have been setup for this object yet, return
if (tags === undefined) return; // Dirty the tag for the specific property if it exists
var propertyTag = tags.get(key);
if (propertyTag !== undefined) {
if (true
/* DEBUG */
) {
unwrap(assertTagNotConsumed)(propertyTag, obj, key);
}
DIRTY_TAG(propertyTag, true);
}
}
function tagMetaFor(obj) {
var tags = TRACKED_TAGS.get(obj);
if (tags === undefined) {
tags = new Map();
TRACKED_TAGS.set(obj, tags);
}
return tags;
}
function tagFor(obj, key, meta) {
var tags = meta === undefined ? tagMetaFor(obj) : meta;
var tag = tags.get(key);
if (tag === undefined) {
tag = createUpdatableTag();
tags.set(key, tag);
}
return tag;
}
/**
* An object that that tracks @tracked properties that were consumed.
*/
class Tracker {
constructor() {
this.tags = new Set();
this.last = null;
}
add(tag) {
if (tag === CONSTANT_TAG) return;
this.tags.add(tag);
if (true
/* DEBUG */
) {
unwrap(markTagAsConsumed)(tag);
}
this.last = tag;
}
combine() {
var {
tags
} = this;
if (tags.size === 0) {
return CONSTANT_TAG;
} else if (tags.size === 1) {
return this.last;
} else {
var tagsArr = [];
tags.forEach(tag => tagsArr.push(tag));
return combine(tagsArr);
}
}
}
/**
* Whenever a tracked computed property is entered, the current tracker is
* saved off and a new tracker is replaced.
*
* Any tracked properties consumed are added to the current tracker.
*
* When a tracked computed property is exited, the tracker's tags are
* combined and added to the parent tracker.
*
* The consequence is that each tracked computed property has a tag
* that corresponds to the tracked properties consumed inside of
* itself, including child tracked computed properties.
*/
var CURRENT_TRACKER = null;
var OPEN_TRACK_FRAMES = [];
function beginTrackFrame(debuggingContext) {
OPEN_TRACK_FRAMES.push(CURRENT_TRACKER);
CURRENT_TRACKER = new Tracker();
if (true
/* DEBUG */
) {
unwrap(beginTrackingTransaction)(debuggingContext);
}
}
function endTrackFrame() {
var current = CURRENT_TRACKER;
if (true
/* DEBUG */
) {
if (OPEN_TRACK_FRAMES.length === 0) {
throw new Error('attempted to close a tracking frame, but one was not open');
}
unwrap(endTrackingTransaction)();
}
CURRENT_TRACKER = OPEN_TRACK_FRAMES.pop() || null;
return unwrap(current).combine();
}
function beginUntrackFrame() {
OPEN_TRACK_FRAMES.push(CURRENT_TRACKER);
CURRENT_TRACKER = null;
}
function endUntrackFrame() {
if (true
/* DEBUG */
&& OPEN_TRACK_FRAMES.length === 0) {
throw new Error('attempted to close a tracking frame, but one was not open');
}
CURRENT_TRACKER = OPEN_TRACK_FRAMES.pop() || null;
} // This function is only for handling errors and resetting to a valid state
function resetTracking() {
while (OPEN_TRACK_FRAMES.length > 0) {
OPEN_TRACK_FRAMES.pop();
}
CURRENT_TRACKER = null;
if (true
/* DEBUG */
) {
return unwrap(resetTrackingTransaction)();
}
}
function isTracking() {
return CURRENT_TRACKER !== null;
}
function consumeTag(tag) {
if (CURRENT_TRACKER !== null) {
CURRENT_TRACKER.add(tag);
}
} //////////
var FN = symbol('FN');
var LAST_VALUE = symbol('LAST_VALUE');
var TAG = symbol('TAG');
var SNAPSHOT = symbol('SNAPSHOT');
var DEBUG_LABEL = symbol('DEBUG_LABEL');
function createCache(fn, debuggingLabel) {
if (true
/* DEBUG */
&& !(typeof fn === 'function')) {
throw new Error(`createCache() must be passed a function as its first parameter. Called with: ${String(fn)}`);
}
var cache = {
[FN]: fn,
[LAST_VALUE]: undefined,
[TAG]: undefined,
[SNAPSHOT]: -1
};
if (true
/* DEBUG */
) {
cache[DEBUG_LABEL] = debuggingLabel;
}
return cache;
}
function getValue(cache) {
assertCache(cache, 'getValue');
var fn = cache[FN];
var tag = cache[TAG];
var snapshot = cache[SNAPSHOT];
if (tag === undefined || !validateTag(tag, snapshot)) {
beginTrackFrame();
try {
cache[LAST_VALUE] = fn();
} finally {
tag = endTrackFrame();
cache[TAG] = tag;
cache[SNAPSHOT] = valueForTag(tag);
consumeTag(tag);
}
} else {
consumeTag(tag);
}
return cache[LAST_VALUE];
}
function isConst(cache) {
assertCache(cache, 'isConst');
var tag = cache[TAG];
assertTag(tag, cache);
return isConstTag(tag);
}
function assertCache(value, fnName) {
if (true
/* DEBUG */
&& !(typeof value === 'object' && value !== null && FN in value)) {
throw new Error(`${fnName}() can only be used on an instance of a cache created with createCache(). Called with: ${String(value)}`);
}
} // replace this with `expect` when we can
function assertTag(tag, cache) {
if (true
/* DEBUG */
&& tag === undefined) {
throw new Error(`isConst() can only be used on a cache once getValue() has been called at least once. Called with cache function:\n\n${String(cache[FN])}`);
}
} //////////
// Legacy tracking APIs
// track() shouldn't be necessary at all in the VM once the autotracking
// refactors are merged, and we should generally be moving away from it. It may
// be necessary in Ember for a while longer, but I think we'll be able to drop
// it in favor of cache sooner rather than later.
function track(callback, debugLabel) {
beginTrackFrame(debugLabel);
var tag;
try {
callback();
} finally {
tag = endTrackFrame();
}
return tag;
} // untrack() is currently mainly used to handle places that were previously not
// tracked, and that tracking now would cause backtracking rerender assertions.
// I think once we move everyone forward onto modern APIs, we'll probably be
// able to remove it, but I'm not sure yet.
function untrack(callback) {
beginUntrackFrame();
try {
return callback();
} finally {
endUntrackFrame();
}
}
function trackedData(key, initializer) {
var values = new WeakMap();
var hasInitializer = typeof initializer === 'function';
function getter(self) {
consumeTag(tagFor(self, key));
var value; // If the field has never been initialized, we should initialize it
if (hasInitializer && !values.has(self)) {
value = initializer.call(self);
values.set(self, value);
} else {
value = values.get(self);
}
return value;
}
function setter(self, value) {
dirtyTagFor(self, key);
values.set(self, value);
}
return {
getter,
setter
};
}
var GLIMMER_VALIDATOR_REGISTRATION = symbolFor('GLIMMER_VALIDATOR_REGISTRATION');
var globalObj = getGlobal();
if (globalObj[GLIMMER_VALIDATOR_REGISTRATION] === true) {
throw new Error('The `@glimmer/validator` library has been included twice in this application. It could be different versions of the package, or the same version included twice by mistake. `@glimmer/validator` depends on having a single copy of the package in use at any time in an application, even if they are the same version. You must dedupe your build to remove the duplicate packages in order to prevent this error.');
}
globalObj[GLIMMER_VALIDATOR_REGISTRATION] = true;
});
define("@glimmer/vm", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.isMachineOp = isMachineOp;
_exports.isOp = isOp;
_exports.isLowLevelRegister = isLowLevelRegister;
_exports.$v0 = _exports.$t1 = _exports.$t0 = _exports.$s1 = _exports.$s0 = _exports.$sp = _exports.$ra = _exports.$fp = _exports.$pc = _exports.TemporaryRegister = _exports.SavedRegister = void 0;
/* This file is generated by build/debug.js */
function isMachineOp(value) {
return value >= 0 && value <= 15;
}
function isOp(value) {
return value >= 16;
}
/**
* Registers
*
* For the most part, these follows MIPS naming conventions, however the
* register numbers are different.
*/
// $0 or $pc (program counter): pointer into `program` for the next insturction; -1 means exit
var $pc = 0; // $1 or $ra (return address): pointer into `program` for the return
_exports.$pc = $pc;
var $ra = 1; // $2 or $fp (frame pointer): pointer into the `evalStack` for the base of the stack
_exports.$ra = $ra;
var $fp = 2; // $3 or $sp (stack pointer): pointer into the `evalStack` for the top of the stack
_exports.$fp = $fp;
var $sp = 3; // $4-$5 or $s0-$s1 (saved): callee saved general-purpose registers
_exports.$sp = $sp;
var $s0 = 4;
_exports.$s0 = $s0;
var $s1 = 5; // $6-$7 or $t0-$t1 (temporaries): caller saved general-purpose registers
_exports.$s1 = $s1;
var $t0 = 6;
_exports.$t0 = $t0;
var $t1 = 7; // $8 or $v0 (return value)
_exports.$t1 = $t1;
var $v0 = 8;
_exports.$v0 = $v0;
function isLowLevelRegister(register) {
return register <= $sp;
}
var SavedRegister;
_exports.SavedRegister = SavedRegister;
(function (SavedRegister) {
SavedRegister[SavedRegister["s0"] = 4] = "s0";
SavedRegister[SavedRegister["s1"] = 5] = "s1";
})(SavedRegister || (_exports.SavedRegister = SavedRegister = {}));
var TemporaryRegister;
_exports.TemporaryRegister = TemporaryRegister;
(function (TemporaryRegister) {
TemporaryRegister[TemporaryRegister["t0"] = 6] = "t0";
TemporaryRegister[TemporaryRegister["t1"] = 7] = "t1";
})(TemporaryRegister || (_exports.TemporaryRegister = TemporaryRegister = {}));
});
define("@glimmer/wire-format", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.is = is;
_exports.isAttribute = isAttribute;
_exports.isStringLiteral = isStringLiteral;
_exports.getStringFromValue = getStringFromValue;
_exports.isArgument = isArgument;
_exports.isHelper = isHelper;
_exports.isGet = _exports.isFlushElement = void 0;
function is(variant) {
return function (value) {
return Array.isArray(value) && value[0] === variant;
};
} // Statements
var isFlushElement = is(12
/* FlushElement */
);
_exports.isFlushElement = isFlushElement;
function isAttribute(val) {
return val[0] === 14
/* StaticAttr */
|| val[0] === 15
/* DynamicAttr */
|| val[0] === 22
/* TrustingDynamicAttr */
|| val[0] === 16
/* ComponentAttr */
|| val[0] === 24
/* StaticComponentAttr */
|| val[0] === 23
/* TrustingComponentAttr */
|| val[0] === 17
/* AttrSplat */
|| val[0] === 4
/* Modifier */
;
}
function isStringLiteral(expr) {
return typeof expr === 'string';
}
function getStringFromValue(expr) {
return expr;
}
function isArgument(val) {
return val[0] === 21
/* StaticArg */
|| val[0] === 20
/* DynamicArg */
;
}
function isHelper(expr) {
return Array.isArray(expr) && expr[0] === 28
/* Call */
;
} // Expressions
var isGet = is(30
/* GetSymbol */
);
_exports.isGet = isGet;
});
define("@simple-dom/document", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
var EMPTY_ATTRS = [];
function indexOfAttribute(attributes, namespaceURI, localName) {
for (var i = 0; i < attributes.length; i++) {
var attr = attributes[i];
if (attr.namespaceURI === namespaceURI && attr.localName === localName) {
return i;
}
}
return -1;
}
function adjustAttrName(namespaceURI, localName) {
return namespaceURI === "http://www.w3.org/1999/xhtml"
/* HTML */
? localName.toLowerCase() : localName;
}
function getAttribute(attributes, namespaceURI, localName) {
var index = indexOfAttribute(attributes, namespaceURI, localName);
return index === -1 ? null : attributes[index].value;
}
function removeAttribute(attributes, namespaceURI, localName) {
var index = indexOfAttribute(attributes, namespaceURI, localName);
if (index !== -1) {
attributes.splice(index, 1);
}
} // https://dom.spec.whatwg.org/#dom-element-setattributens
function setAttribute(element, namespaceURI, prefix, localName, value) {
if (typeof value !== 'string') {
value = '' + value;
}
var {
attributes
} = element;
if (attributes === EMPTY_ATTRS) {
attributes = element.attributes = [];
} else {
var index = indexOfAttribute(attributes, namespaceURI, localName);
if (index !== -1) {
attributes[index].value = value;
return;
}
}
attributes.push({
localName,
name: prefix === null ? localName : prefix + ':' + localName,
namespaceURI,
prefix,
specified: true,
value
});
}
class ChildNodes {
constructor(node) {
this.node = node;
this.stale = true;
this._length = 0;
}
get length() {
if (this.stale) {
this.stale = false;
var len = 0;
var child = this.node.firstChild;
for (; child !== null; len++) {
this[len] = child;
child = child.nextSibling;
}
var oldLen = this._length;
this._length = len;
for (; len < oldLen; len++) {
delete this[len];
}
}
return this._length;
}
item(index) {
return index < this.length ? this[index] : null;
}
}
function cloneNode(node, deep) {
var clone = nodeFrom(node);
if (deep) {
var child = node.firstChild;
var nextChild = child;
while (child !== null) {
nextChild = child.nextSibling;
clone.appendChild(child.cloneNode(true));
child = nextChild;
}
}
return clone;
}
function nodeFrom(node) {
var namespaceURI;
if (node.nodeType === 1
/* ELEMENT_NODE */
) {
namespaceURI = node.namespaceURI;
}
var clone = new SimpleNodeImpl(node.ownerDocument, node.nodeType, node.nodeName, node.nodeValue, namespaceURI);
if (node.nodeType === 1
/* ELEMENT_NODE */
) {
clone.attributes = copyAttrs(node.attributes);
}
return clone;
}
function copyAttrs(attrs) {
if (attrs === EMPTY_ATTRS) {
return EMPTY_ATTRS;
}
var copy = [];
for (var i = 0; i < attrs.length; i++) {
var attr = attrs[i];
copy.push({
localName: attr.localName,
name: attr.name,
namespaceURI: attr.namespaceURI,
prefix: attr.prefix,
specified: true,
value: attr.value
});
}
return copy;
}
function insertBefore(parentNode, newChild, refChild) {
invalidate(parentNode);
insertBetween(parentNode, newChild, refChild === null ? parentNode.lastChild : refChild.previousSibling, refChild);
}
function removeChild(parentNode, oldChild) {
invalidate(parentNode);
removeBetween(parentNode, oldChild, oldChild.previousSibling, oldChild.nextSibling);
}
function invalidate(parentNode) {
var childNodes = parentNode._childNodes;
if (childNodes !== undefined) {
childNodes.stale = true;
}
}
function insertBetween(parentNode, newChild, previousSibling, nextSibling) {
if (newChild.nodeType === 11
/* DOCUMENT_FRAGMENT_NODE */
) {
insertFragment(newChild, parentNode, previousSibling, nextSibling);
return;
}
if (newChild.parentNode !== null) {
removeChild(newChild.parentNode, newChild);
}
newChild.parentNode = parentNode;
newChild.previousSibling = previousSibling;
newChild.nextSibling = nextSibling;
if (previousSibling === null) {
parentNode.firstChild = newChild;
} else {
previousSibling.nextSibling = newChild;
}
if (nextSibling === null) {
parentNode.lastChild = newChild;
} else {
nextSibling.previousSibling = newChild;
}
}
function removeBetween(parentNode, oldChild, previousSibling, nextSibling) {
oldChild.parentNode = null;
oldChild.previousSibling = null;
oldChild.nextSibling = null;
if (previousSibling === null) {
parentNode.firstChild = nextSibling;
} else {
previousSibling.nextSibling = nextSibling;
}
if (nextSibling === null) {
parentNode.lastChild = previousSibling;
} else {
nextSibling.previousSibling = previousSibling;
}
}
function insertFragment(fragment, parentNode, previousSibling, nextSibling) {
var firstChild = fragment.firstChild;
if (firstChild === null) {
return;
}
fragment.firstChild = null;
fragment.lastChild = null;
var lastChild = firstChild;
var newChild = firstChild;
firstChild.previousSibling = previousSibling;
if (previousSibling === null) {
parentNode.firstChild = firstChild;
} else {
previousSibling.nextSibling = firstChild;
}
while (newChild !== null) {
newChild.parentNode = parentNode;
lastChild = newChild;
newChild = newChild.nextSibling;
}
lastChild.nextSibling = nextSibling;
if (nextSibling === null) {
parentNode.lastChild = lastChild;
} else {
nextSibling.previousSibling = lastChild;
}
}
function parseQualifiedName(qualifiedName) {
var localName = qualifiedName;
var prefix = null;
var i = qualifiedName.indexOf(':');
if (i !== -1) {
prefix = qualifiedName.slice(0, i);
localName = qualifiedName.slice(i + 1);
}
return [prefix, localName];
}
class SimpleNodeImpl {
constructor(ownerDocument, nodeType, nodeName, nodeValue, namespaceURI) {
this.ownerDocument = ownerDocument;
this.nodeType = nodeType;
this.nodeName = nodeName;
this.nodeValue = nodeValue;
this.namespaceURI = namespaceURI;
this.parentNode = null;
this.previousSibling = null;
this.nextSibling = null;
this.firstChild = null;
this.lastChild = null;
this.attributes = EMPTY_ATTRS;
/**
* @internal
*/
this._childNodes = undefined;
}
get tagName() {
return this.nodeName;
}
get childNodes() {
var children = this._childNodes;
if (children === undefined) {
children = this._childNodes = new ChildNodes(this);
}
return children;
}
cloneNode(deep) {
return cloneNode(this, deep === true);
}
appendChild(newChild) {
insertBefore(this, newChild, null);
return newChild;
}
insertBefore(newChild, refChild) {
insertBefore(this, newChild, refChild);
return newChild;
}
removeChild(oldChild) {
removeChild(this, oldChild);
return oldChild;
}
insertAdjacentHTML(position, html) {
var raw = new SimpleNodeImpl(this.ownerDocument, -1
/* RAW_NODE */
, '#raw', html, void 0);
var parentNode;
var nextSibling;
switch (position) {
case 'beforebegin':
parentNode = this.parentNode;
nextSibling = this;
break;
case 'afterbegin':
parentNode = this;
nextSibling = this.firstChild;
break;
case 'beforeend':
parentNode = this;
nextSibling = null;
break;
case 'afterend':
parentNode = this.parentNode;
nextSibling = this.nextSibling;
break;
default:
throw new Error('invalid position');
}
if (parentNode === null) {
throw new Error(`${position} requires a parentNode`);
}
insertBefore(parentNode, raw, nextSibling);
}
getAttribute(name) {
var localName = adjustAttrName(this.namespaceURI, name);
return getAttribute(this.attributes, null, localName);
}
getAttributeNS(namespaceURI, localName) {
return getAttribute(this.attributes, namespaceURI, localName);
}
setAttribute(name, value) {
var localName = adjustAttrName(this.namespaceURI, name);
setAttribute(this, null, null, localName, value);
}
setAttributeNS(namespaceURI, qualifiedName, value) {
var [prefix, localName] = parseQualifiedName(qualifiedName);
setAttribute(this, namespaceURI, prefix, localName, value);
}
removeAttribute(name) {
var localName = adjustAttrName(this.namespaceURI, name);
removeAttribute(this.attributes, null, localName);
}
removeAttributeNS(namespaceURI, localName) {
removeAttribute(this.attributes, namespaceURI, localName);
}
get doctype() {
return this.firstChild;
}
get documentElement() {
return this.lastChild;
}
get head() {
return this.documentElement.firstChild;
}
get body() {
return this.documentElement.lastChild;
}
createElement(name) {
return new SimpleNodeImpl(this, 1
/* ELEMENT_NODE */
, name.toUpperCase(), null, "http://www.w3.org/1999/xhtml"
/* HTML */
);
}
createElementNS(namespace, qualifiedName) {
// Node name is case-preserving in XML contexts, but returns canonical uppercase form in HTML contexts
// https://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-104682815
var nodeName = namespace === "http://www.w3.org/1999/xhtml"
/* HTML */
? qualifiedName.toUpperCase() : qualifiedName; // we don't care to parse the qualified name because we only support HTML documents
// which don't support prefixed elements
return new SimpleNodeImpl(this, 1
/* ELEMENT_NODE */
, nodeName, null, namespace);
}
createTextNode(text) {
return new SimpleNodeImpl(this, 3
/* TEXT_NODE */
, '#text', text, void 0);
}
createComment(text) {
return new SimpleNodeImpl(this, 8
/* COMMENT_NODE */
, '#comment', text, void 0);
}
/**
* Backwards compat
* @deprecated
*/
createRawHTMLSection(text) {
return new SimpleNodeImpl(this, -1
/* RAW_NODE */
, '#raw', text, void 0);
}
createDocumentFragment() {
return new SimpleNodeImpl(this, 11
/* DOCUMENT_FRAGMENT_NODE */
, '#document-fragment', null, void 0);
}
}
function createHTMLDocument() {
// dom.d.ts types ownerDocument as Document but for a document ownerDocument is null
var document = new SimpleNodeImpl(null, 9
/* DOCUMENT_NODE */
, '#document', null, "http://www.w3.org/1999/xhtml"
/* HTML */
);
var doctype = new SimpleNodeImpl(document, 10
/* DOCUMENT_TYPE_NODE */
, 'html', null, "http://www.w3.org/1999/xhtml"
/* HTML */
);
var html = new SimpleNodeImpl(document, 1
/* ELEMENT_NODE */
, 'HTML', null, "http://www.w3.org/1999/xhtml"
/* HTML */
);
var head = new SimpleNodeImpl(document, 1
/* ELEMENT_NODE */
, 'HEAD', null, "http://www.w3.org/1999/xhtml"
/* HTML */
);
var body = new SimpleNodeImpl(document, 1
/* ELEMENT_NODE */
, 'BODY', null, "http://www.w3.org/1999/xhtml"
/* HTML */
);
html.appendChild(head);
html.appendChild(body);
document.appendChild(doctype);
document.appendChild(html);
return document;
}
var _default = createHTMLDocument;
_exports.default = _default;
});
define("backburner", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.buildPlatform = buildPlatform;
_exports.default = void 0;
var SET_TIMEOUT = setTimeout;
var NOOP = () => {};
function buildNext(flush) {
// Using "promises first" here to:
//
// 1) Ensure more consistent experience on browsers that
// have differently queued microtasks (separate queues for
// MutationObserver vs Promises).
// 2) Ensure better debugging experiences (it shows up in Chrome
// call stack as "Promise.then (async)") which is more consistent
// with user expectations
//
// When Promise is unavailable use MutationObserver (mostly so that we
// still get microtasks on IE11), and when neither MutationObserver and
// Promise are present use a plain old setTimeout.
if (typeof Promise === 'function') {
var autorunPromise = Promise.resolve();
return () => autorunPromise.then(flush);
} else if (typeof MutationObserver === 'function') {
var iterations = 0;
var observer = new MutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, {
characterData: true
});
return () => {
iterations = ++iterations % 2;
node.data = '' + iterations;
return iterations;
};
} else {
return () => SET_TIMEOUT(flush, 0);
}
}
function buildPlatform(flush) {
var clearNext = NOOP;
return {
setTimeout(fn, ms) {
return setTimeout(fn, ms);
},
clearTimeout(timerId) {
return clearTimeout(timerId);
},
now() {
return Date.now();
},
next: buildNext(flush),
clearNext
};
}
var NUMBER = /\d+/;
var TIMERS_OFFSET = 6;
function isCoercableNumber(suspect) {
var type = typeof suspect;
return type === 'number' && suspect === suspect || type === 'string' && NUMBER.test(suspect);
}
function getOnError(options) {
return options.onError || options.onErrorTarget && options.onErrorTarget[options.onErrorMethod];
}
function findItem(target, method, collection) {
var index = -1;
for (var i = 0, l = collection.length; i < l; i += 4) {
if (collection[i] === target && collection[i + 1] === method) {
index = i;
break;
}
}
return index;
}
function findTimerItem(target, method, collection) {
var index = -1;
for (var i = 2, l = collection.length; i < l; i += 6) {
if (collection[i] === target && collection[i + 1] === method) {
index = i - 2;
break;
}
}
return index;
}
function getQueueItems(items, queueItemLength, queueItemPositionOffset = 0) {
var queueItems = [];
for (var i = 0; i < items.length; i += queueItemLength) {
var maybeError = items[i + 3
/* stack */
+ queueItemPositionOffset];
var queueItem = {
target: items[i + 0
/* target */
+ queueItemPositionOffset],
method: items[i + 1
/* method */
+ queueItemPositionOffset],
args: items[i + 2
/* args */
+ queueItemPositionOffset],
stack: maybeError !== undefined && 'stack' in maybeError ? maybeError.stack : ''
};
queueItems.push(queueItem);
}
return queueItems;
}
function binarySearch(time, timers) {
var start = 0;
var end = timers.length - TIMERS_OFFSET;
var middle;
var l;
while (start < end) {
// since timers is an array of pairs 'l' will always
// be an integer
l = (end - start) / TIMERS_OFFSET; // compensate for the index in case even number
// of pairs inside timers
middle = start + l - l % TIMERS_OFFSET;
if (time >= timers[middle]) {
start = middle + TIMERS_OFFSET;
} else {
end = middle;
}
}
return time >= timers[start] ? start + TIMERS_OFFSET : start;
}
var QUEUE_ITEM_LENGTH = 4;
class Queue {
constructor(name, options = {}, globalOptions = {}) {
this._queueBeingFlushed = [];
this.targetQueues = new Map();
this.index = 0;
this._queue = [];
this.name = name;
this.options = options;
this.globalOptions = globalOptions;
}
stackFor(index) {
if (index < this._queue.length) {
var entry = this._queue[index * 3 + QUEUE_ITEM_LENGTH];
if (entry) {
return entry.stack;
} else {
return null;
}
}
}
flush(sync) {
var {
before,
after
} = this.options;
var target;
var method;
var args;
var errorRecordedForStack;
this.targetQueues.clear();
if (this._queueBeingFlushed.length === 0) {
this._queueBeingFlushed = this._queue;
this._queue = [];
}
if (before !== undefined) {
before();
}
var invoke;
var queueItems = this._queueBeingFlushed;
if (queueItems.length > 0) {
var onError = getOnError(this.globalOptions);
invoke = onError ? this.invokeWithOnError : this.invoke;
for (var i = this.index; i < queueItems.length; i += QUEUE_ITEM_LENGTH) {
this.index += QUEUE_ITEM_LENGTH;
method = queueItems[i + 1]; // method could have been nullified / canceled during flush
if (method !== null) {
//
// ** Attention intrepid developer **
//
// To find out the stack of this task when it was scheduled onto
// the run loop, add the following to your app.js:
//
// Ember.run.backburner.DEBUG = true; // NOTE: This slows your app, don't leave it on in production.
//
// Once that is in place, when you are at a breakpoint and navigate
// here in the stack explorer, you can look at `errorRecordedForStack.stack`,
// which will be the captured stack when this job was scheduled.
//
// One possible long-term solution is the following Chrome issue:
// https://bugs.chromium.org/p/chromium/issues/detail?id=332624
//
target = queueItems[i];
args = queueItems[i + 2];
errorRecordedForStack = queueItems[i + 3]; // Debugging assistance
invoke(target, method, args, onError, errorRecordedForStack);
}
if (this.index !== this._queueBeingFlushed.length && this.globalOptions.mustYield && this.globalOptions.mustYield()) {
return 1
/* Pause */
;
}
}
}
if (after !== undefined) {
after();
}
this._queueBeingFlushed.length = 0;
this.index = 0;
if (sync !== false && this._queue.length > 0) {
// check if new items have been added
this.flush(true);
}
}
hasWork() {
return this._queueBeingFlushed.length > 0 || this._queue.length > 0;
}
cancel({
target,
method
}) {
var queue = this._queue;
var targetQueueMap = this.targetQueues.get(target);
if (targetQueueMap !== undefined) {
targetQueueMap.delete(method);
}
var index = findItem(target, method, queue);
if (index > -1) {
queue.splice(index, QUEUE_ITEM_LENGTH);
return true;
} // if not found in current queue
// could be in the queue that is being flushed
queue = this._queueBeingFlushed;
index = findItem(target, method, queue);
if (index > -1) {
queue[index + 1] = null;
return true;
}
return false;
}
push(target, method, args, stack) {
this._queue.push(target, method, args, stack);
return {
queue: this,
target,
method
};
}
pushUnique(target, method, args, stack) {
var localQueueMap = this.targetQueues.get(target);
if (localQueueMap === undefined) {
localQueueMap = new Map();
this.targetQueues.set(target, localQueueMap);
}
var index = localQueueMap.get(method);
if (index === undefined) {
var queueIndex = this._queue.push(target, method, args, stack) - QUEUE_ITEM_LENGTH;
localQueueMap.set(method, queueIndex);
} else {
var queue = this._queue;
queue[index + 2] = args; // replace args
queue[index + 3] = stack; // replace stack
}
return {
queue: this,
target,
method
};
}
_getDebugInfo(debugEnabled) {
if (debugEnabled) {
var debugInfo = getQueueItems(this._queue, QUEUE_ITEM_LENGTH);
return debugInfo;
}
return undefined;
}
invoke(target, method, args
/*, onError, errorRecordedForStack */
) {
if (args === undefined) {
method.call(target);
} else {
method.apply(target, args);
}
}
invokeWithOnError(target, method, args, onError, errorRecordedForStack) {
try {
if (args === undefined) {
method.call(target);
} else {
method.apply(target, args);
}
} catch (error) {
onError(error, errorRecordedForStack);
}
}
}
class DeferredActionQueues {
constructor(queueNames = [], options) {
this.queues = {};
this.queueNameIndex = 0;
this.queueNames = queueNames;
queueNames.reduce(function (queues, queueName) {
queues[queueName] = new Queue(queueName, options[queueName], options);
return queues;
}, this.queues);
}
/**
* @method schedule
* @param {String} queueName
* @param {Any} target
* @param {Any} method
* @param {Any} args
* @param {Boolean} onceFlag
* @param {Any} stack
* @return queue
*/
schedule(queueName, target, method, args, onceFlag, stack) {
var queues = this.queues;
var queue = queues[queueName];
if (queue === undefined) {
throw new Error(`You attempted to schedule an action in a queue (${queueName}) that doesn\'t exist`);
}
if (method === undefined || method === null) {
throw new Error(`You attempted to schedule an action in a queue (${queueName}) for a method that doesn\'t exist`);
}
this.queueNameIndex = 0;
if (onceFlag) {
return queue.pushUnique(target, method, args, stack);
} else {
return queue.push(target, method, args, stack);
}
}
/**
* DeferredActionQueues.flush() calls Queue.flush()
*
* @method flush
* @param {Boolean} fromAutorun
*/
flush(fromAutorun = false) {
var queue;
var queueName;
var numberOfQueues = this.queueNames.length;
while (this.queueNameIndex < numberOfQueues) {
queueName = this.queueNames[this.queueNameIndex];
queue = this.queues[queueName];
if (queue.hasWork() === false) {
this.queueNameIndex++;
if (fromAutorun && this.queueNameIndex < numberOfQueues) {
return 1
/* Pause */
;
}
} else {
if (queue.flush(false
/* async */
) === 1
/* Pause */
) {
return 1
/* Pause */
;
}
}
}
}
/**
* Returns debug information for the current queues.
*
* @method _getDebugInfo
* @param {Boolean} debugEnabled
* @returns {IDebugInfo | undefined}
*/
_getDebugInfo(debugEnabled) {
if (debugEnabled) {
var debugInfo = {};
var queue;
var queueName;
var numberOfQueues = this.queueNames.length;
var i = 0;
while (i < numberOfQueues) {
queueName = this.queueNames[i];
queue = this.queues[queueName];
debugInfo[queueName] = queue._getDebugInfo(debugEnabled);
i++;
}
return debugInfo;
}
return;
}
}
function iteratorDrain(fn) {
var iterator = fn();
var result = iterator.next();
while (result.done === false) {
result.value();
result = iterator.next();
}
}
var noop = function () {};
var DISABLE_SCHEDULE = Object.freeze([]);
function parseArgs() {
var length = arguments.length;
var args;
var method;
var target;
if (length === 0) ;else if (length === 1) {
target = null;
method = arguments[0];
} else {
var argsIndex = 2;
var methodOrTarget = arguments[0];
var methodOrArgs = arguments[1];
var type = typeof methodOrArgs;
if (type === 'function') {
target = methodOrTarget;
method = methodOrArgs;
} else if (methodOrTarget !== null && type === 'string' && methodOrArgs in methodOrTarget) {
target = methodOrTarget;
method = target[methodOrArgs];
} else if (typeof methodOrTarget === 'function') {
argsIndex = 1;
target = null;
method = methodOrTarget;
}
if (length > argsIndex) {
var len = length - argsIndex;
args = new Array(len);
for (var i = 0; i < len; i++) {
args[i] = arguments[i + argsIndex];
}
}
}
return [target, method, args];
}
function parseTimerArgs() {
var [target, method, args] = parseArgs(...arguments);
var wait = 0;
var length = args !== undefined ? args.length : 0;
if (length > 0) {
var last = args[length - 1];
if (isCoercableNumber(last)) {
wait = parseInt(args.pop(), 10);
}
}
return [target, method, args, wait];
}
function parseDebounceArgs() {
var target;
var method;
var isImmediate;
var args;
var wait;
if (arguments.length === 2) {
method = arguments[0];
wait = arguments[1];
target = null;
} else {
[target, method, args] = parseArgs(...arguments);
if (args === undefined) {
wait = 0;
} else {
wait = args.pop();
if (!isCoercableNumber(wait)) {
isImmediate = wait === true;
wait = args.pop();
}
}
}
wait = parseInt(wait, 10);
return [target, method, args, wait, isImmediate];
}
var UUID = 0;
var beginCount = 0;
var endCount = 0;
var beginEventCount = 0;
var endEventCount = 0;
var runCount = 0;
var joinCount = 0;
var deferCount = 0;
var scheduleCount = 0;
var scheduleIterableCount = 0;
var deferOnceCount = 0;
var scheduleOnceCount = 0;
var setTimeoutCount = 0;
var laterCount = 0;
var throttleCount = 0;
var debounceCount = 0;
var cancelTimersCount = 0;
var cancelCount = 0;
var autorunsCreatedCount = 0;
var autorunsCompletedCount = 0;
var deferredActionQueuesCreatedCount = 0;
var nestedDeferredActionQueuesCreated = 0;
class Backburner {
constructor(queueNames, options) {
this.DEBUG = false;
this.currentInstance = null;
this.instanceStack = [];
this._eventCallbacks = {
end: [],
begin: []
};
this._timerTimeoutId = null;
this._timers = [];
this._autorun = false;
this._autorunStack = null;
this.queueNames = queueNames;
this.options = options || {};
if (typeof this.options.defaultQueue === 'string') {
this._defaultQueue = this.options.defaultQueue;
} else {
this._defaultQueue = this.queueNames[0];
}
this._onBegin = this.options.onBegin || noop;
this._onEnd = this.options.onEnd || noop;
this._boundRunExpiredTimers = this._runExpiredTimers.bind(this);
this._boundAutorunEnd = () => {
autorunsCompletedCount++; // if the autorun was already flushed, do nothing
if (this._autorun === false) {
return;
}
this._autorun = false;
this._autorunStack = null;
this._end(true
/* fromAutorun */
);
};
var builder = this.options._buildPlatform || buildPlatform;
this._platform = builder(this._boundAutorunEnd);
}
get counters() {
return {
begin: beginCount,
end: endCount,
events: {
begin: beginEventCount,
end: endEventCount
},
autoruns: {
created: autorunsCreatedCount,
completed: autorunsCompletedCount
},
run: runCount,
join: joinCount,
defer: deferCount,
schedule: scheduleCount,
scheduleIterable: scheduleIterableCount,
deferOnce: deferOnceCount,
scheduleOnce: scheduleOnceCount,
setTimeout: setTimeoutCount,
later: laterCount,
throttle: throttleCount,
debounce: debounceCount,
cancelTimers: cancelTimersCount,
cancel: cancelCount,
loops: {
total: deferredActionQueuesCreatedCount,
nested: nestedDeferredActionQueuesCreated
}
};
}
get defaultQueue() {
return this._defaultQueue;
}
/*
@method begin
@return instantiated class DeferredActionQueues
*/
begin() {
beginCount++;
var options = this.options;
var previousInstance = this.currentInstance;
var current;
if (this._autorun !== false) {
current = previousInstance;
this._cancelAutorun();
} else {
if (previousInstance !== null) {
nestedDeferredActionQueuesCreated++;
this.instanceStack.push(previousInstance);
}
deferredActionQueuesCreatedCount++;
current = this.currentInstance = new DeferredActionQueues(this.queueNames, options);
beginEventCount++;
this._trigger('begin', current, previousInstance);
}
this._onBegin(current, previousInstance);
return current;
}
end() {
endCount++;
this._end(false);
}
on(eventName, callback) {
if (typeof callback !== 'function') {
throw new TypeError(`Callback must be a function`);
}
var callbacks = this._eventCallbacks[eventName];
if (callbacks !== undefined) {
callbacks.push(callback);
} else {
throw new TypeError(`Cannot on() event ${eventName} because it does not exist`);
}
}
off(eventName, callback) {
var callbacks = this._eventCallbacks[eventName];
if (!eventName || callbacks === undefined) {
throw new TypeError(`Cannot off() event ${eventName} because it does not exist`);
}
var callbackFound = false;
if (callback) {
for (var i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
callbackFound = true;
callbacks.splice(i, 1);
i--;
}
}
}
if (!callbackFound) {
throw new TypeError(`Cannot off() callback that does not exist`);
}
}
run() {
runCount++;
var [target, method, args] = parseArgs(...arguments);
return this._run(target, method, args);
}
join() {
joinCount++;
var [target, method, args] = parseArgs(...arguments);
return this._join(target, method, args);
}
/**
* @deprecated please use schedule instead.
*/
defer(queueName, target, method, ...args) {
deferCount++;
return this.schedule(queueName, target, method, ...args);
}
schedule(queueName, ..._args) {
scheduleCount++;
var [target, method, args] = parseArgs(..._args);
var stack = this.DEBUG ? new Error() : undefined;
return this._ensureInstance().schedule(queueName, target, method, args, false, stack);
}
/*
Defer the passed iterable of functions to run inside the specified queue.
@method scheduleIterable
@param {String} queueName
@param {Iterable} an iterable of functions to execute
@return method result
*/
scheduleIterable(queueName, iterable) {
scheduleIterableCount++;
var stack = this.DEBUG ? new Error() : undefined;
return this._ensureInstance().schedule(queueName, null, iteratorDrain, [iterable], false, stack);
}
/**
* @deprecated please use scheduleOnce instead.
*/
deferOnce(queueName, target, method, ...args) {
deferOnceCount++;
return this.scheduleOnce(queueName, target, method, ...args);
}
scheduleOnce(queueName, ..._args) {
scheduleOnceCount++;
var [target, method, args] = parseArgs(..._args);
var stack = this.DEBUG ? new Error() : undefined;
return this._ensureInstance().schedule(queueName, target, method, args, true, stack);
}
setTimeout() {
setTimeoutCount++;
return this.later(...arguments);
}
later() {
laterCount++;
var [target, method, args, wait] = parseTimerArgs(...arguments);
return this._later(target, method, args, wait);
}
throttle() {
throttleCount++;
var [target, method, args, wait, isImmediate = true] = parseDebounceArgs(...arguments);
var index = findTimerItem(target, method, this._timers);
var timerId;
if (index === -1) {
timerId = this._later(target, method, isImmediate ? DISABLE_SCHEDULE : args, wait);
if (isImmediate) {
this._join(target, method, args);
}
} else {
timerId = this._timers[index + 1];
var argIndex = index + 4;
if (this._timers[argIndex] !== DISABLE_SCHEDULE) {
this._timers[argIndex] = args;
}
}
return timerId;
}
debounce() {
debounceCount++;
var [target, method, args, wait, isImmediate = false] = parseDebounceArgs(...arguments);
var _timers = this._timers;
var index = findTimerItem(target, method, _timers);
var timerId;
if (index === -1) {
timerId = this._later(target, method, isImmediate ? DISABLE_SCHEDULE : args, wait);
if (isImmediate) {
this._join(target, method, args);
}
} else {
var executeAt = this._platform.now() + wait;
var argIndex = index + 4;
if (_timers[argIndex] === DISABLE_SCHEDULE) {
args = DISABLE_SCHEDULE;
}
timerId = _timers[index + 1];
var i = binarySearch(executeAt, _timers);
if (index + TIMERS_OFFSET === i) {
_timers[index] = executeAt;
_timers[argIndex] = args;
} else {
var stack = this._timers[index + 5];
this._timers.splice(i, 0, executeAt, timerId, target, method, args, stack);
this._timers.splice(index, TIMERS_OFFSET);
}
if (index === 0) {
this._reinstallTimerTimeout();
}
}
return timerId;
}
cancelTimers() {
cancelTimersCount++;
this._clearTimerTimeout();
this._timers = [];
this._cancelAutorun();
}
hasTimers() {
return this._timers.length > 0 || this._autorun;
}
cancel(timer) {
cancelCount++;
if (timer === null || timer === undefined) {
return false;
}
var timerType = typeof timer;
if (timerType === 'number') {
// we're cancelling a setTimeout or throttle or debounce
return this._cancelLaterTimer(timer);
} else if (timerType === 'object' && timer.queue && timer.method) {
// we're cancelling a deferOnce
return timer.queue.cancel(timer);
}
return false;
}
ensureInstance() {
this._ensureInstance();
}
/**
* Returns debug information related to the current instance of Backburner
*
* @method getDebugInfo
* @returns {Object | undefined} Will return and Object containing debug information if
* the DEBUG flag is set to true on the current instance of Backburner, else undefined.
*/
getDebugInfo() {
if (this.DEBUG) {
return {
autorun: this._autorunStack,
counters: this.counters,
timers: getQueueItems(this._timers, TIMERS_OFFSET, 2),
instanceStack: [this.currentInstance, ...this.instanceStack].map(deferredActionQueue => deferredActionQueue && deferredActionQueue._getDebugInfo(this.DEBUG))
};
}
return undefined;
}
_end(fromAutorun) {
var currentInstance = this.currentInstance;
var nextInstance = null;
if (currentInstance === null) {
throw new Error(`end called without begin`);
} // Prevent double-finally bug in Safari 6.0.2 and iOS 6
// This bug appears to be resolved in Safari 6.0.5 and iOS 7
var finallyAlreadyCalled = false;
var result;
try {
result = currentInstance.flush(fromAutorun);
} finally {
if (!finallyAlreadyCalled) {
finallyAlreadyCalled = true;
if (result === 1
/* Pause */
) {
var plannedNextQueue = this.queueNames[currentInstance.queueNameIndex];
this._scheduleAutorun(plannedNextQueue);
} else {
this.currentInstance = null;
if (this.instanceStack.length > 0) {
nextInstance = this.instanceStack.pop();
this.currentInstance = nextInstance;
}
this._trigger('end', currentInstance, nextInstance);
this._onEnd(currentInstance, nextInstance);
}
}
}
}
_join(target, method, args) {
if (this.currentInstance === null) {
return this._run(target, method, args);
}
if (target === undefined && args === undefined) {
return method();
} else {
return method.apply(target, args);
}
}
_run(target, method, args) {
var onError = getOnError(this.options);
this.begin();
if (onError) {
try {
return method.apply(target, args);
} catch (error) {
onError(error);
} finally {
this.end();
}
} else {
try {
return method.apply(target, args);
} finally {
this.end();
}
}
}
_cancelAutorun() {
if (this._autorun) {
this._platform.clearNext();
this._autorun = false;
this._autorunStack = null;
}
}
_later(target, method, args, wait) {
var stack = this.DEBUG ? new Error() : undefined;
var executeAt = this._platform.now() + wait;
var id = UUID++;
if (this._timers.length === 0) {
this._timers.push(executeAt, id, target, method, args, stack);
this._installTimerTimeout();
} else {
// find position to insert
var i = binarySearch(executeAt, this._timers);
this._timers.splice(i, 0, executeAt, id, target, method, args, stack); // always reinstall since it could be out of sync
this._reinstallTimerTimeout();
}
return id;
}
_cancelLaterTimer(timer) {
for (var i = 1; i < this._timers.length; i += TIMERS_OFFSET) {
if (this._timers[i] === timer) {
this._timers.splice(i - 1, TIMERS_OFFSET);
if (i === 1) {
this._reinstallTimerTimeout();
}
return true;
}
}
return false;
}
/**
Trigger an event. Supports up to two arguments. Designed around
triggering transition events from one run loop instance to the
next, which requires an argument for the instance and then
an argument for the next instance.
@private
@method _trigger
@param {String} eventName
@param {any} arg1
@param {any} arg2
*/
_trigger(eventName, arg1, arg2) {
var callbacks = this._eventCallbacks[eventName];
if (callbacks !== undefined) {
for (var i = 0; i < callbacks.length; i++) {
callbacks[i](arg1, arg2);
}
}
}
_runExpiredTimers() {
this._timerTimeoutId = null;
if (this._timers.length > 0) {
this.begin();
this._scheduleExpiredTimers();
this.end();
}
}
_scheduleExpiredTimers() {
var timers = this._timers;
var i = 0;
var l = timers.length;
var defaultQueue = this._defaultQueue;
var n = this._platform.now();
for (; i < l; i += TIMERS_OFFSET) {
var executeAt = timers[i];
if (executeAt > n) {
break;
}
var args = timers[i + 4];
if (args !== DISABLE_SCHEDULE) {
var target = timers[i + 2];
var method = timers[i + 3];
var stack = timers[i + 5];
this.currentInstance.schedule(defaultQueue, target, method, args, false, stack);
}
}
timers.splice(0, i);
this._installTimerTimeout();
}
_reinstallTimerTimeout() {
this._clearTimerTimeout();
this._installTimerTimeout();
}
_clearTimerTimeout() {
if (this._timerTimeoutId === null) {
return;
}
this._platform.clearTimeout(this._timerTimeoutId);
this._timerTimeoutId = null;
}
_installTimerTimeout() {
if (this._timers.length === 0) {
return;
}
var minExpiresAt = this._timers[0];
var n = this._platform.now();
var wait = Math.max(0, minExpiresAt - n);
this._timerTimeoutId = this._platform.setTimeout(this._boundRunExpiredTimers, wait);
}
_ensureInstance() {
var currentInstance = this.currentInstance;
if (currentInstance === null) {
this._autorunStack = this.DEBUG ? new Error() : undefined;
currentInstance = this.begin();
this._scheduleAutorun(this.queueNames[0]);
}
return currentInstance;
}
_scheduleAutorun(plannedNextQueue) {
autorunsCreatedCount++;
var next = this._platform.next;
var flush = this.options.flush;
if (flush) {
flush(plannedNextQueue, next);
} else {
next();
}
this._autorun = true;
}
}
Backburner.Queue = Queue;
Backburner.buildPlatform = buildPlatform;
Backburner.buildNext = buildNext;
var _default = Backburner;
_exports.default = _default;
});
define("dag-map", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
* A topologically ordered map of key/value pairs with a simple API for adding constraints.
*
* Edges can forward reference keys that have not been added yet (the forward reference will
* map the key to undefined).
*/
var DAG = function () {
function DAG() {
this._vertices = new Vertices();
}
/**
* Adds a key/value pair with dependencies on other key/value pairs.
*
* @public
* @param key The key of the vertex to be added.
* @param value The value of that vertex.
* @param before A key or array of keys of the vertices that must
* be visited before this vertex.
* @param after An string or array of strings with the keys of the
* vertices that must be after this vertex is visited.
*/
DAG.prototype.add = function (key, value, before, after) {
if (!key) throw new Error('argument `key` is required');
var vertices = this._vertices;
var v = vertices.add(key);
v.val = value;
if (before) {
if (typeof before === "string") {
vertices.addEdge(v, vertices.add(before));
} else {
for (var i = 0; i < before.length; i++) {
vertices.addEdge(v, vertices.add(before[i]));
}
}
}
if (after) {
if (typeof after === "string") {
vertices.addEdge(vertices.add(after), v);
} else {
for (var i = 0; i < after.length; i++) {
vertices.addEdge(vertices.add(after[i]), v);
}
}
}
};
/**
* @deprecated please use add.
*/
DAG.prototype.addEdges = function (key, value, before, after) {
this.add(key, value, before, after);
};
/**
* Visits key/value pairs in topological order.
*
* @public
* @param callback The function to be invoked with each key/value.
*/
DAG.prototype.each = function (callback) {
this._vertices.walk(callback);
};
/**
* @deprecated please use each.
*/
DAG.prototype.topsort = function (callback) {
this.each(callback);
};
return DAG;
}();
var _default = DAG;
/** @private */
_exports.default = _default;
var Vertices = function () {
function Vertices() {
this.length = 0;
this.stack = new IntStack();
this.path = new IntStack();
this.result = new IntStack();
}
Vertices.prototype.add = function (key) {
if (!key) throw new Error("missing key");
var l = this.length | 0;
var vertex;
for (var i = 0; i < l; i++) {
vertex = this[i];
if (vertex.key === key) return vertex;
}
this.length = l + 1;
return this[l] = {
idx: l,
key: key,
val: undefined,
out: false,
flag: false,
length: 0
};
};
Vertices.prototype.addEdge = function (v, w) {
this.check(v, w.key);
var l = w.length | 0;
for (var i = 0; i < l; i++) {
if (w[i] === v.idx) return;
}
w.length = l + 1;
w[l] = v.idx;
v.out = true;
};
Vertices.prototype.walk = function (cb) {
this.reset();
for (var i = 0; i < this.length; i++) {
var vertex = this[i];
if (vertex.out) continue;
this.visit(vertex, "");
}
this.each(this.result, cb);
};
Vertices.prototype.check = function (v, w) {
if (v.key === w) {
throw new Error("cycle detected: " + w + " <- " + w);
} // quick check
if (v.length === 0) return; // shallow check
for (var i = 0; i < v.length; i++) {
var key = this[v[i]].key;
if (key === w) {
throw new Error("cycle detected: " + w + " <- " + v.key + " <- " + w);
}
} // deep check
this.reset();
this.visit(v, w);
if (this.path.length > 0) {
var msg_1 = "cycle detected: " + w;
this.each(this.path, function (key) {
msg_1 += " <- " + key;
});
throw new Error(msg_1);
}
};
Vertices.prototype.reset = function () {
this.stack.length = 0;
this.path.length = 0;
this.result.length = 0;
for (var i = 0, l = this.length; i < l; i++) {
this[i].flag = false;
}
};
Vertices.prototype.visit = function (start, search) {
var _a = this,
stack = _a.stack,
path = _a.path,
result = _a.result;
stack.push(start.idx);
while (stack.length) {
var index = stack.pop() | 0;
if (index >= 0) {
// enter
var vertex = this[index];
if (vertex.flag) continue;
vertex.flag = true;
path.push(index);
if (search === vertex.key) break; // push exit
stack.push(~index);
this.pushIncoming(vertex);
} else {
// exit
path.pop();
result.push(~index);
}
}
};
Vertices.prototype.pushIncoming = function (incomming) {
var stack = this.stack;
for (var i = incomming.length - 1; i >= 0; i--) {
var index = incomming[i];
if (!this[index].flag) {
stack.push(index);
}
}
};
Vertices.prototype.each = function (indices, cb) {
for (var i = 0, l = indices.length; i < l; i++) {
var vertex = this[indices[i]];
cb(vertex.key, vertex.val);
}
};
return Vertices;
}();
/** @private */
var IntStack = function () {
function IntStack() {
this.length = 0;
}
IntStack.prototype.push = function (n) {
this[this.length++] = n | 0;
};
IntStack.prototype.pop = function () {
return this[--this.length] | 0;
};
return IntStack;
}();
});
define("ember-babel", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.wrapNativeSuper = wrapNativeSuper;
_exports.classCallCheck = classCallCheck;
_exports.inheritsLoose = inheritsLoose;
_exports.taggedTemplateLiteralLoose = taggedTemplateLiteralLoose;
_exports.createClass = createClass;
_exports.assertThisInitialized = assertThisInitialized;
_exports.possibleConstructorReturn = possibleConstructorReturn;
_exports.objectDestructuringEmpty = objectDestructuringEmpty;
_exports.createSuper = createSuper;
_exports.createForOfIteratorHelperLoose = createForOfIteratorHelperLoose;
/* globals Reflect */
var setPrototypeOf = Object.setPrototypeOf;
var getPrototypeOf = Object.getPrototypeOf;
var hasReflectConstruct = typeof Reflect === 'object' && typeof Reflect.construct === 'function';
var nativeWrapperCache = new Map(); // Super minimal version of Babel's wrapNativeSuper. We only use this for
// extending Function, for ComputedDecoratorImpl and AliasDecoratorImpl. We know
// we will never directly create an instance of these classes so no need to
// include `construct` code or other helpers.
function wrapNativeSuper(Class) {
if (nativeWrapperCache.has(Class)) {
return nativeWrapperCache.get(Class);
}
function Wrapper() {}
Wrapper.prototype = Object.create(Class.prototype, {
constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true
}
});
nativeWrapperCache.set(Class, Wrapper);
return setPrototypeOf(Wrapper, Class);
}
function classCallCheck(instance, Constructor) {
if (true
/* DEBUG */
) {
if (!(instance instanceof Constructor)) {
throw new TypeError('Cannot call a class as a function');
}
}
}
/*
Overrides default `inheritsLoose` to _also_ call `Object.setPrototypeOf`.
This is needed so that we can use `loose` option with the
`@babel/plugin-transform-classes` (because we want simple assignment to the
prototype wherever possible) but also keep our constructor based prototypal
inheritance working properly
*/
function inheritsLoose(subClass, superClass) {
if (true
/* DEBUG */
) {
if (typeof superClass !== 'function' && superClass !== null) {
throw new TypeError('Super expression must either be null or a function');
}
}
subClass.prototype = Object.create(superClass === null ? null : superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass !== null) {
setPrototypeOf(subClass, superClass);
}
}
function taggedTemplateLiteralLoose(strings, raw) {
if (!raw) {
raw = strings.slice(0);
}
strings.raw = raw;
return strings;
}
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);
}
}
/*
Differs from default implementation by avoiding boolean coercion of
`protoProps` and `staticProps`.
*/
function createClass(Constructor, protoProps, staticProps) {
if (protoProps !== null && protoProps !== undefined) {
_defineProperties(Constructor.prototype, protoProps);
}
if (staticProps !== null && staticProps !== undefined) {
_defineProperties(Constructor, staticProps);
}
return Constructor;
}
function assertThisInitialized(self) {
if (true
/* DEBUG */
&& self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
/*
Adds `DEBUG` guard to error being thrown, and avoids boolean coercion of `call`.
*/
function possibleConstructorReturn(self, call) {
if (typeof call === 'object' && call !== null || typeof call === 'function') {
return call;
}
return assertThisInitialized(self);
}
function objectDestructuringEmpty(obj) {
if (true
/* DEBUG */
&& (obj === null || obj === undefined)) {
throw new TypeError('Cannot destructure undefined');
}
}
/*
Differs from default implementation by checking for _any_ `Reflect.construct`
(the default implementation tries to ensure that `Reflect.construct` is truly
the native one).
Original source: https://github.com/babel/babel/blob/v7.9.2/packages/babel-helpers/src/helpers.js#L738-L757
*/
function createSuper(Derived) {
return function () {
var Super = getPrototypeOf(Derived);
var result;
if (hasReflectConstruct) {
// NOTE: This doesn't work if this.__proto__.constructor has been modified.
var NewTarget = getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return possibleConstructorReturn(this, result);
};
}
/*
Does not differ from default implementation.
*/
function arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
var arr2 = new Array(len);
for (var i = 0; i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
/*
Does not differ from default implementation.
*/
function unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === 'string') return arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === 'Object' && o.constructor) n = o.constructor.name;
if (n === 'Map' || n === 'Set') return Array.from(n);
if (n === 'Arguments' || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);
}
/*
Does not differ from default implementation.
*/
function createForOfIteratorHelperLoose(o) {
var i = 0;
if (typeof Symbol === 'undefined' || o[Symbol.iterator] == null) {
// Fallback for engines without symbol support
if (Array.isArray(o) || (o = unsupportedIterableToArray(o))) return function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
};
throw new TypeError('Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.');
}
i = o[Symbol.iterator]();
return i.next.bind(i);
}
});
define("ember-testing/index", ["exports", "ember-testing/lib/test", "ember-testing/lib/adapters/adapter", "ember-testing/lib/setup_for_testing", "ember-testing/lib/adapters/qunit", "ember-testing/lib/ext/application", "ember-testing/lib/ext/rsvp", "ember-testing/lib/helpers", "ember-testing/lib/initializers"], function (_exports, _test, _adapter, _setup_for_testing, _qunit, _application, _rsvp, _helpers, _initializers) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "Test", {
enumerable: true,
get: function () {
return _test.default;
}
});
Object.defineProperty(_exports, "Adapter", {
enumerable: true,
get: function () {
return _adapter.default;
}
});
Object.defineProperty(_exports, "setupForTesting", {
enumerable: true,
get: function () {
return _setup_for_testing.default;
}
});
Object.defineProperty(_exports, "QUnitAdapter", {
enumerable: true,
get: function () {
return _qunit.default;
}
});
});
define("ember-testing/lib/adapters/adapter", ["exports", "@ember/-internals/runtime"], function (_exports, _runtime) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
function K() {
return this;
}
/**
@module @ember/test
*/
/**
The primary purpose of this class is to create hooks that can be implemented
by an adapter for various test frameworks.
@class TestAdapter
@public
*/
var _default = _runtime.Object.extend({
/**
This callback will be called whenever an async operation is about to start.
Override this to call your framework's methods that handle async
operations.
@public
@method asyncStart
*/
asyncStart: K,
/**
This callback will be called whenever an async operation has completed.
@public
@method asyncEnd
*/
asyncEnd: K,
/**
Override this method with your testing framework's false assertion.
This function is called whenever an exception occurs causing the testing
promise to fail.
QUnit example:
```javascript
exception: function(error) {
ok(false, error);
};
```
@public
@method exception
@param {String} error The exception to be raised.
*/
exception(error) {
throw error;
}
});
_exports.default = _default;
});
define("ember-testing/lib/adapters/qunit", ["exports", "@ember/-internals/utils", "ember-testing/lib/adapters/adapter"], function (_exports, _utils, _adapter) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/* globals QUnit */
/**
@module ember
*/
/**
This class implements the methods defined by TestAdapter for the
QUnit testing framework.
@class QUnitAdapter
@namespace Ember.Test
@extends TestAdapter
@public
*/
var _default = _adapter.default.extend({
init() {
this.doneCallbacks = [];
},
asyncStart() {
if (typeof QUnit.stop === 'function') {
// very old QUnit version
QUnit.stop();
} else {
this.doneCallbacks.push(QUnit.config.current ? QUnit.config.current.assert.async() : null);
}
},
asyncEnd() {
// checking for QUnit.stop here (even though we _need_ QUnit.start) because
// QUnit.start() still exists in QUnit 2.x (it just throws an error when calling
// inside a test context)
if (typeof QUnit.stop === 'function') {
QUnit.start();
} else {
var done = this.doneCallbacks.pop(); // This can be null if asyncStart() was called outside of a test
if (done) {
done();
}
}
},
exception(error) {
QUnit.config.current.assert.ok(false, (0, _utils.inspect)(error));
}
});
_exports.default = _default;
});
define("ember-testing/lib/ext/application", ["@ember/application", "ember-testing/lib/setup_for_testing", "ember-testing/lib/test/helpers", "ember-testing/lib/test/promise", "ember-testing/lib/test/run", "ember-testing/lib/test/on_inject_helpers", "ember-testing/lib/test/adapter"], function (_application, _setup_for_testing, _helpers, _promise, _run, _on_inject_helpers, _adapter) {
"use strict";
_application.default.reopen({
/**
This property contains the testing helpers for the current application. These
are created once you call `injectTestHelpers` on your `Application`
instance. The included helpers are also available on the `window` object by
default, but can be used from this object on the individual application also.
@property testHelpers
@type {Object}
@default {}
@public
*/
testHelpers: {},
/**
This property will contain the original methods that were registered
on the `helperContainer` before `injectTestHelpers` is called.
When `removeTestHelpers` is called, these methods are restored to the
`helperContainer`.
@property originalMethods
@type {Object}
@default {}
@private
@since 1.3.0
*/
originalMethods: {},
/**
This property indicates whether or not this application is currently in
testing mode. This is set when `setupForTesting` is called on the current
application.
@property testing
@type {Boolean}
@default false
@since 1.3.0
@public
*/
testing: false,
/**
This hook defers the readiness of the application, so that you can start
the app when your tests are ready to run. It also sets the router's
location to 'none', so that the window's location will not be modified
(preventing both accidental leaking of state between tests and interference
with your testing framework). `setupForTesting` should only be called after
setting a custom `router` class (for example `App.Router = Router.extend(`).
Example:
```
App.setupForTesting();
```
@method setupForTesting
@public
*/
setupForTesting() {
(0, _setup_for_testing.default)();
this.testing = true;
this.resolveRegistration('router:main').reopen({
location: 'none'
});
},
/**
This will be used as the container to inject the test helpers into. By
default the helpers are injected into `window`.
@property helperContainer
@type {Object} The object to be used for test helpers.
@default window
@since 1.2.0
@private
*/
helperContainer: null,
/**
This injects the test helpers into the `helperContainer` object. If an object is provided
it will be used as the helperContainer. If `helperContainer` is not set it will default
to `window`. If a function of the same name has already been defined it will be cached
(so that it can be reset if the helper is removed with `unregisterHelper` or
`removeTestHelpers`).
Any callbacks registered with `onInjectHelpers` will be called once the
helpers have been injected.
Example:
```
App.injectTestHelpers();
```
@method injectTestHelpers
@public
*/
injectTestHelpers(helperContainer) {
if (helperContainer) {
this.helperContainer = helperContainer;
} else {
this.helperContainer = window;
}
this.reopen({
willDestroy() {
this._super(...arguments);
this.removeTestHelpers();
}
});
this.testHelpers = {};
for (var name in _helpers.helpers) {
this.originalMethods[name] = this.helperContainer[name];
this.testHelpers[name] = this.helperContainer[name] = helper(this, name);
protoWrap(_promise.default.prototype, name, helper(this, name), _helpers.helpers[name].meta.wait);
}
(0, _on_inject_helpers.invokeInjectHelpersCallbacks)(this);
},
/**
This removes all helpers that have been registered, and resets and functions
that were overridden by the helpers.
Example:
```javascript
App.removeTestHelpers();
```
@public
@method removeTestHelpers
*/
removeTestHelpers() {
if (!this.helperContainer) {
return;
}
for (var name in _helpers.helpers) {
this.helperContainer[name] = this.originalMethods[name];
delete _promise.default.prototype[name];
delete this.testHelpers[name];
delete this.originalMethods[name];
}
}
}); // This method is no longer needed
// But still here for backwards compatibility
// of helper chaining
function protoWrap(proto, name, callback, isAsync) {
proto[name] = function (...args) {
if (isAsync) {
return callback.apply(this, args);
} else {
return this.then(function () {
return callback.apply(this, args);
});
}
};
}
function helper(app, name) {
var fn = _helpers.helpers[name].method;
var meta = _helpers.helpers[name].meta;
if (!meta.wait) {
return (...args) => fn.apply(app, [app, ...args]);
}
return (...args) => {
var lastPromise = (0, _run.default)(() => (0, _promise.resolve)((0, _promise.getLastPromise)())); // wait for last helper's promise to resolve and then
// execute. To be safe, we need to tell the adapter we're going
// asynchronous here, because fn may not be invoked before we
// return.
(0, _adapter.asyncStart)();
return lastPromise.then(() => fn.apply(app, [app, ...args])).finally(_adapter.asyncEnd);
};
}
});
define("ember-testing/lib/ext/rsvp", ["exports", "@ember/-internals/runtime", "@ember/runloop", "@ember/debug", "ember-testing/lib/test/adapter"], function (_exports, _runtime, _runloop, _debug, _adapter) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
_runtime.RSVP.configure('async', function (callback, promise) {
// if schedule will cause autorun, we need to inform adapter
if ((0, _debug.isTesting)() && !_runloop._backburner.currentInstance) {
(0, _adapter.asyncStart)();
_runloop._backburner.schedule('actions', () => {
(0, _adapter.asyncEnd)();
callback(promise);
});
} else {
_runloop._backburner.schedule('actions', () => callback(promise));
}
});
var _default = _runtime.RSVP;
_exports.default = _default;
});
define("ember-testing/lib/helpers", ["ember-testing/lib/test/helpers", "ember-testing/lib/helpers/and_then", "ember-testing/lib/helpers/current_path", "ember-testing/lib/helpers/current_route_name", "ember-testing/lib/helpers/current_url", "ember-testing/lib/helpers/pause_test", "ember-testing/lib/helpers/visit", "ember-testing/lib/helpers/wait"], function (_helpers, _and_then, _current_path, _current_route_name, _current_url, _pause_test, _visit, _wait) {
"use strict";
(0, _helpers.registerAsyncHelper)('visit', _visit.default);
(0, _helpers.registerAsyncHelper)('wait', _wait.default);
(0, _helpers.registerAsyncHelper)('andThen', _and_then.default);
(0, _helpers.registerAsyncHelper)('pauseTest', _pause_test.pauseTest);
(0, _helpers.registerHelper)('currentRouteName', _current_route_name.default);
(0, _helpers.registerHelper)('currentPath', _current_path.default);
(0, _helpers.registerHelper)('currentURL', _current_url.default);
(0, _helpers.registerHelper)('resumeTest', _pause_test.resumeTest);
});
define("ember-testing/lib/helpers/and_then", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = andThen;
function andThen(app, callback) {
return app.testHelpers.wait(callback(app));
}
});
define("ember-testing/lib/helpers/current_path", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = currentPath;
/**
@module ember
*/
/**
Returns the current path.
Example:
```javascript
function validateURL() {
equal(currentPath(), 'some.path.index', "correct path was transitioned into.");
}
click('#some-link-id').then(validateURL);
```
@method currentPath
@return {Object} The currently active path.
@since 1.5.0
@public
*/
function currentPath(app) {
var routingService = app.__container__.lookup('service:-routing');
return (0, _metal.get)(routingService, 'currentPath');
}
});
define("ember-testing/lib/helpers/current_route_name", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = currentRouteName;
/**
@module ember
*/
/**
Returns the currently active route name.
Example:
```javascript
function validateRouteName() {
equal(currentRouteName(), 'some.path', "correct route was transitioned into.");
}
visit('/some/path').then(validateRouteName)
```
@method currentRouteName
@return {Object} The name of the currently active route.
@since 1.5.0
@public
*/
function currentRouteName(app) {
var routingService = app.__container__.lookup('service:-routing');
return (0, _metal.get)(routingService, 'currentRouteName');
}
});
define("ember-testing/lib/helpers/current_url", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = currentURL;
/**
@module ember
*/
/**
Returns the current URL.
Example:
```javascript
function validateURL() {
equal(currentURL(), '/some/path', "correct URL was transitioned into.");
}
click('#some-link-id').then(validateURL);
```
@method currentURL
@return {Object} The currently active URL.
@since 1.5.0
@public
*/
function currentURL(app) {
var router = app.__container__.lookup('router:main');
return (0, _metal.get)(router, 'location').getURL();
}
});
define("ember-testing/lib/helpers/pause_test", ["exports", "@ember/-internals/runtime", "@ember/debug"], function (_exports, _runtime, _debug) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.resumeTest = resumeTest;
_exports.pauseTest = pauseTest;
/**
@module ember
*/
var resume;
/**
Resumes a test paused by `pauseTest`.
@method resumeTest
@return {void}
@public
*/
function resumeTest() {
(true && !(resume) && (0, _debug.assert)('Testing has not been paused. There is nothing to resume.', resume));
resume();
resume = undefined;
}
/**
Pauses the current test - this is useful for debugging while testing or for test-driving.
It allows you to inspect the state of your application at any point.
Example (The test will pause before clicking the button):
```javascript
visit('/')
return pauseTest();
click('.btn');
```
You may want to turn off the timeout before pausing.
qunit (timeout available to use as of 2.4.0):
```
visit('/');
assert.timeout(0);
return pauseTest();
click('.btn');
```
mocha (timeout happens automatically as of ember-mocha v0.14.0):
```
visit('/');
this.timeout(0);
return pauseTest();
click('.btn');
```
@since 1.9.0
@method pauseTest
@return {Object} A promise that will never resolve
@public
*/
function pauseTest() {
(0, _debug.info)('Testing paused. Use `resumeTest()` to continue.');
return new _runtime.RSVP.Promise(resolve => {
resume = resolve;
}, 'TestAdapter paused promise');
}
});
define("ember-testing/lib/helpers/visit", ["exports", "@ember/runloop"], function (_exports, _runloop) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = visit;
/**
Loads a route, sets up any controllers, and renders any templates associated
with the route as though a real user had triggered the route change while
using your app.
Example:
```javascript
visit('posts/index').then(function() {
// assert something
});
```
@method visit
@param {String} url the name of the route
@return {RSVP.Promise<undefined>}
@public
*/
function visit(app, url) {
var router = app.__container__.lookup('router:main');
var shouldHandleURL = false;
app.boot().then(() => {
router.location.setURL(url);
if (shouldHandleURL) {
(0, _runloop.run)(app.__deprecatedInstance__, 'handleURL', url);
}
});
if (app._readinessDeferrals > 0) {
router.initialURL = url;
(0, _runloop.run)(app, 'advanceReadiness');
delete router.initialURL;
} else {
shouldHandleURL = true;
}
return app.testHelpers.wait();
}
});
define("ember-testing/lib/helpers/wait", ["exports", "ember-testing/lib/test/waiters", "@ember/-internals/runtime", "@ember/runloop", "ember-testing/lib/test/pending_requests"], function (_exports, _waiters, _runtime, _runloop, _pending_requests) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = wait;
/**
@module ember
*/
/**
Causes the run loop to process any pending events. This is used to ensure that
any async operations from other helpers (or your assertions) have been processed.
This is most often used as the return value for the helper functions (see 'click',
'fillIn','visit',etc). However, there is a method to register a test helper which
utilizes this method without the need to actually call `wait()` in your helpers.
The `wait` helper is built into `registerAsyncHelper` by default. You will not need
to `return app.testHelpers.wait();` - the wait behavior is provided for you.
Example:
```javascript
import { registerAsyncHelper } from '@ember/test';
registerAsyncHelper('loginUser', function(app, username, password) {
visit('secured/path/here')
.fillIn('#username', username)
.fillIn('#password', password)
.click('.submit');
});
```
@method wait
@param {Object} value The value to be returned.
@return {RSVP.Promise<any>} Promise that resolves to the passed value.
@public
@since 1.0.0
*/
function wait(app, value) {
return new _runtime.RSVP.Promise(function (resolve) {
var router = app.__container__.lookup('router:main'); // Every 10ms, poll for the async thing to have finished
var watcher = setInterval(() => {
// 1. If the router is loading, keep polling
var routerIsLoading = router._routerMicrolib && Boolean(router._routerMicrolib.activeTransition);
if (routerIsLoading) {
return;
} // 2. If there are pending Ajax requests, keep polling
if ((0, _pending_requests.pendingRequests)()) {
return;
} // 3. If there are scheduled timers or we are inside of a run loop, keep polling
if ((0, _runloop._hasScheduledTimers)() || (0, _runloop._getCurrentRunLoop)()) {
return;
}
if ((0, _waiters.checkWaiters)()) {
return;
} // Stop polling
clearInterval(watcher); // Synchronously resolve the promise
(0, _runloop.run)(null, resolve, value);
}, 10);
});
}
});
define("ember-testing/lib/initializers", ["@ember/application"], function (_application) {
"use strict";
var name = 'deferReadiness in `testing` mode';
(0, _application.onLoad)('Ember.Application', function (Application) {
if (!Application.initializers[name]) {
Application.initializer({
name: name,
initialize(application) {
if (application.testing) {
application.deferReadiness();
}
}
});
}
});
});
define("ember-testing/lib/setup_for_testing", ["exports", "@ember/debug", "ember-testing/lib/test/adapter", "ember-testing/lib/adapters/adapter", "ember-testing/lib/adapters/qunit"], function (_exports, _debug, _adapter, _adapter2, _qunit) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = setupForTesting;
/* global self */
/**
Sets Ember up for testing. This is useful to perform
basic setup steps in order to unit test.
Use `App.setupForTesting` to perform integration tests (full
application testing).
@method setupForTesting
@namespace Ember
@since 1.5.0
@private
*/
function setupForTesting() {
(0, _debug.setTesting)(true);
var adapter = (0, _adapter.getAdapter)(); // if adapter is not manually set default to QUnit
if (!adapter) {
(0, _adapter.setAdapter)(typeof self.QUnit === 'undefined' ? _adapter2.default.create() : _qunit.default.create());
}
}
});
define("ember-testing/lib/test", ["exports", "ember-testing/lib/test/helpers", "ember-testing/lib/test/on_inject_helpers", "ember-testing/lib/test/promise", "ember-testing/lib/test/waiters", "ember-testing/lib/test/adapter"], function (_exports, _helpers, _on_inject_helpers, _promise, _waiters, _adapter) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
/**
@module ember
*/
/**
This is a container for an assortment of testing related functionality:
* Choose your default test adapter (for your framework of choice).
* Register/Unregister additional test helpers.
* Setup callbacks to be fired when the test helpers are injected into
your application.
@class Test
@namespace Ember
@public
*/
var Test = {
/**
Hash containing all known test helpers.
@property _helpers
@private
@since 1.7.0
*/
_helpers: _helpers.helpers,
registerHelper: _helpers.registerHelper,
registerAsyncHelper: _helpers.registerAsyncHelper,
unregisterHelper: _helpers.unregisterHelper,
onInjectHelpers: _on_inject_helpers.onInjectHelpers,
Promise: _promise.default,
promise: _promise.promise,
resolve: _promise.resolve,
registerWaiter: _waiters.registerWaiter,
unregisterWaiter: _waiters.unregisterWaiter,
checkWaiters: _waiters.checkWaiters
};
/**
Used to allow ember-testing to communicate with a specific testing
framework.
You can manually set it before calling `App.setupForTesting()`.
Example:
```javascript
Ember.Test.adapter = MyCustomAdapter.create()
```
If you do not set it, ember-testing will default to `Ember.Test.QUnitAdapter`.
@public
@for Ember.Test
@property adapter
@type {Class} The adapter to be used.
@default Ember.Test.QUnitAdapter
*/
Object.defineProperty(Test, 'adapter', {
get: _adapter.getAdapter,
set: _adapter.setAdapter
});
var _default = Test;
_exports.default = _default;
});
define("ember-testing/lib/test/adapter", ["exports", "@ember/-internals/error-handling"], function (_exports, _errorHandling) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.getAdapter = getAdapter;
_exports.setAdapter = setAdapter;
_exports.asyncStart = asyncStart;
_exports.asyncEnd = asyncEnd;
var adapter;
function getAdapter() {
return adapter;
}
function setAdapter(value) {
adapter = value;
if (value && typeof value.exception === 'function') {
(0, _errorHandling.setDispatchOverride)(adapterDispatch);
} else {
(0, _errorHandling.setDispatchOverride)(null);
}
}
function asyncStart() {
if (adapter) {
adapter.asyncStart();
}
}
function asyncEnd() {
if (adapter) {
adapter.asyncEnd();
}
}
function adapterDispatch(error) {
adapter.exception(error);
console.error(error.stack); // eslint-disable-line no-console
}
});
define("ember-testing/lib/test/helpers", ["exports", "ember-testing/lib/test/promise"], function (_exports, _promise) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.registerHelper = registerHelper;
_exports.registerAsyncHelper = registerAsyncHelper;
_exports.unregisterHelper = unregisterHelper;
_exports.helpers = void 0;
var helpers = {};
/**
@module @ember/test
*/
/**
`registerHelper` is used to register a test helper that will be injected
when `App.injectTestHelpers` is called.
The helper method will always be called with the current Application as
the first parameter.
For example:
```javascript
import { registerHelper } from '@ember/test';
import { run } from '@ember/runloop';
registerHelper('boot', function(app) {
run(app, app.advanceReadiness);
});
```
This helper can later be called without arguments because it will be
called with `app` as the first parameter.
```javascript
import Application from '@ember/application';
App = Application.create();
App.injectTestHelpers();
boot();
```
@public
@for @ember/test
@static
@method registerHelper
@param {String} name The name of the helper method to add.
@param {Function} helperMethod
@param options {Object}
*/
_exports.helpers = helpers;
function registerHelper(name, helperMethod) {
helpers[name] = {
method: helperMethod,
meta: {
wait: false
}
};
}
/**
`registerAsyncHelper` is used to register an async test helper that will be injected
when `App.injectTestHelpers` is called.
The helper method will always be called with the current Application as
the first parameter.
For example:
```javascript
import { registerAsyncHelper } from '@ember/test';
import { run } from '@ember/runloop';
registerAsyncHelper('boot', function(app) {
run(app, app.advanceReadiness);
});
```
The advantage of an async helper is that it will not run
until the last async helper has completed. All async helpers
after it will wait for it complete before running.
For example:
```javascript
import { registerAsyncHelper } from '@ember/test';
registerAsyncHelper('deletePost', function(app, postId) {
click('.delete-' + postId);
});
// ... in your test
visit('/post/2');
deletePost(2);
visit('/post/3');
deletePost(3);
```
@public
@for @ember/test
@method registerAsyncHelper
@param {String} name The name of the helper method to add.
@param {Function} helperMethod
@since 1.2.0
*/
function registerAsyncHelper(name, helperMethod) {
helpers[name] = {
method: helperMethod,
meta: {
wait: true
}
};
}
/**
Remove a previously added helper method.
Example:
```javascript
import { unregisterHelper } from '@ember/test';
unregisterHelper('wait');
```
@public
@method unregisterHelper
@static
@for @ember/test
@param {String} name The helper to remove.
*/
function unregisterHelper(name) {
delete helpers[name];
delete _promise.default.prototype[name];
}
});
define("ember-testing/lib/test/on_inject_helpers", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.onInjectHelpers = onInjectHelpers;
_exports.invokeInjectHelpersCallbacks = invokeInjectHelpersCallbacks;
_exports.callbacks = void 0;
var callbacks = [];
/**
Used to register callbacks to be fired whenever `App.injectTestHelpers`
is called.
The callback will receive the current application as an argument.
Example:
```javascript
import $ from 'jquery';
Ember.Test.onInjectHelpers(function() {
$(document).ajaxSend(function() {
Test.pendingRequests++;
});
$(document).ajaxComplete(function() {
Test.pendingRequests--;
});
});
```
@public
@for Ember.Test
@method onInjectHelpers
@param {Function} callback The function to be called.
*/
_exports.callbacks = callbacks;
function onInjectHelpers(callback) {
callbacks.push(callback);
}
function invokeInjectHelpersCallbacks(app) {
for (var i = 0; i < callbacks.length; i++) {
callbacks[i](app);
}
}
});
define("ember-testing/lib/test/pending_requests", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.pendingRequests = pendingRequests;
_exports.clearPendingRequests = clearPendingRequests;
_exports.incrementPendingRequests = incrementPendingRequests;
_exports.decrementPendingRequests = decrementPendingRequests;
var requests = [];
function pendingRequests() {
return requests.length;
}
function clearPendingRequests() {
requests.length = 0;
}
function incrementPendingRequests(_, xhr) {
requests.push(xhr);
}
function decrementPendingRequests(_, xhr) {
setTimeout(function () {
for (var i = 0; i < requests.length; i++) {
if (xhr === requests[i]) {
requests.splice(i, 1);
break;
}
}
}, 0);
}
});
define("ember-testing/lib/test/promise", ["exports", "@ember/-internals/runtime", "ember-testing/lib/test/run"], function (_exports, _runtime, _run) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.promise = promise;
_exports.resolve = resolve;
_exports.getLastPromise = getLastPromise;
_exports.default = void 0;
var lastPromise;
class TestPromise extends _runtime.RSVP.Promise {
constructor() {
super(...arguments);
lastPromise = this;
}
then(_onFulfillment, ...args) {
var onFulfillment = typeof _onFulfillment === 'function' ? result => isolate(_onFulfillment, result) : undefined;
return super.then(onFulfillment, ...args);
}
}
/**
This returns a thenable tailored for testing. It catches failed
`onSuccess` callbacks and invokes the `Ember.Test.adapter.exception`
callback in the last chained then.
This method should be returned by async helpers such as `wait`.
@public
@for Ember.Test
@method promise
@param {Function} resolver The function used to resolve the promise.
@param {String} label An optional string for identifying the promise.
*/
_exports.default = TestPromise;
function promise(resolver, label) {
var fullLabel = `Ember.Test.promise: ${label || '<Unknown Promise>'}`;
return new TestPromise(resolver, fullLabel);
}
/**
Replacement for `Ember.RSVP.resolve`
The only difference is this uses
an instance of `Ember.Test.Promise`
@public
@for Ember.Test
@method resolve
@param {Mixed} The value to resolve
@since 1.2.0
*/
function resolve(result, label) {
return TestPromise.resolve(result, label);
}
function getLastPromise() {
return lastPromise;
} // This method isolates nested async methods
// so that they don't conflict with other last promises.
//
// 1. Set `Ember.Test.lastPromise` to null
// 2. Invoke method
// 3. Return the last promise created during method
function isolate(onFulfillment, result) {
// Reset lastPromise for nested helpers
lastPromise = null;
var value = onFulfillment(result);
var promise = lastPromise;
lastPromise = null; // If the method returned a promise
// return that promise. If not,
// return the last async helper's promise
if (value && value instanceof TestPromise || !promise) {
return value;
} else {
return (0, _run.default)(() => resolve(promise).then(() => value));
}
}
});
define("ember-testing/lib/test/run", ["exports", "@ember/runloop"], function (_exports, _runloop) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = run;
function run(fn) {
if (!(0, _runloop._getCurrentRunLoop)()) {
return (0, _runloop.run)(fn);
} else {
return fn();
}
}
});
define("ember-testing/lib/test/waiters", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.registerWaiter = registerWaiter;
_exports.unregisterWaiter = unregisterWaiter;
_exports.checkWaiters = checkWaiters;
/**
@module @ember/test
*/
var contexts = [];
var callbacks = [];
/**
This allows ember-testing to play nicely with other asynchronous
events, such as an application that is waiting for a CSS3
transition or an IndexDB transaction. The waiter runs periodically
after each async helper (i.e. `click`, `andThen`, `visit`, etc) has executed,
until the returning result is truthy. After the waiters finish, the next async helper
is executed and the process repeats.
For example:
```javascript
import { registerWaiter } from '@ember/test';
registerWaiter(function() {
return myPendingTransactions() === 0;
});
```
The `context` argument allows you to optionally specify the `this`
with which your callback will be invoked.
For example:
```javascript
import { registerWaiter } from '@ember/test';
registerWaiter(MyDB, MyDB.hasPendingTransactions);
```
@public
@for @ember/test
@static
@method registerWaiter
@param {Object} context (optional)
@param {Function} callback
@since 1.2.0
*/
function registerWaiter(context, callback) {
if (arguments.length === 1) {
callback = context;
context = null;
}
if (indexOf(context, callback) > -1) {
return;
}
contexts.push(context);
callbacks.push(callback);
}
/**
`unregisterWaiter` is used to unregister a callback that was
registered with `registerWaiter`.
@public
@for @ember/test
@static
@method unregisterWaiter
@param {Object} context (optional)
@param {Function} callback
@since 1.2.0
*/
function unregisterWaiter(context, callback) {
if (!callbacks.length) {
return;
}
if (arguments.length === 1) {
callback = context;
context = null;
}
var i = indexOf(context, callback);
if (i === -1) {
return;
}
contexts.splice(i, 1);
callbacks.splice(i, 1);
}
/**
Iterates through each registered test waiter, and invokes
its callback. If any waiter returns false, this method will return
true indicating that the waiters have not settled yet.
This is generally used internally from the acceptance/integration test
infrastructure.
@public
@for @ember/test
@static
@method checkWaiters
*/
function checkWaiters() {
if (!callbacks.length) {
return false;
}
for (var i = 0; i < callbacks.length; i++) {
var context = contexts[i];
var callback = callbacks[i];
if (!callback.call(context)) {
return true;
}
}
return false;
}
function indexOf(context, callback) {
for (var i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback && contexts[i] === context) {
return i;
}
}
return -1;
}
});
define("ember/index", ["exports", "require", "@ember/-internals/environment", "@ember/-internals/utils", "@ember/-internals/container", "@ember/instrumentation", "@ember/-internals/meta", "@ember/-internals/metal", "@ember/canary-features", "@ember/debug", "backburner", "@ember/controller", "@ember/controller/lib/controller_mixin", "@ember/string", "@ember/service", "@ember/object", "@ember/object/compat", "@ember/-internals/runtime", "@ember/-internals/glimmer", "ember/version", "@ember/-internals/views", "@ember/-internals/routing", "@ember/-internals/extension-support", "@ember/error", "@ember/runloop", "@ember/-internals/error-handling", "@ember/-internals/owner", "@ember/application", "@ember/application/instance", "@ember/engine", "@ember/engine/instance", "@ember/polyfills", "@glimmer/runtime", "@glimmer/manager", "@ember/destroyable"], function (_exports, _require, _environment, utils, _container, instrumentation, _meta, metal, _canaryFeatures, EmberDebug, _backburner, _controller, _controller_mixin, _string, _service, _object, _compat, _runtime, _glimmer, _version, views, routing, extensionSupport, _error, _runloop, _errorHandling, _owner, _application, _instance, _engine, _instance2, _polyfills, _runtime2, _manager, _destroyable) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
// eslint-disable-next-line import/no-unresolved
// ****@ember/-internals/environment****
var Ember = {};
Ember.isNamespace = true;
Ember.toString = function () {
return 'Ember';
};
Object.defineProperty(Ember, 'ENV', {
get: _environment.getENV,
enumerable: false
});
Object.defineProperty(Ember, 'lookup', {
get: _environment.getLookup,
set: _environment.setLookup,
enumerable: false
}); // ****@ember/application****
Ember.getOwner = _owner.getOwner;
Ember.setOwner = _owner.setOwner;
Ember.Application = _application.default;
Ember.ApplicationInstance = _instance.default; // ****@ember/engine****
Ember.Engine = _engine.default;
Ember.EngineInstance = _instance2.default; // ****@ember/polyfills****
Ember.assign = _polyfills.assign; // ****@ember/-internals/utils****
Ember.generateGuid = utils.generateGuid;
Ember.GUID_KEY = utils.GUID_KEY;
Ember.guidFor = utils.guidFor;
Ember.inspect = utils.inspect;
Ember.makeArray = utils.makeArray;
Ember.canInvoke = utils.canInvoke;
Ember.wrap = utils.wrap;
Ember.uuid = utils.uuid; // ****@ember/-internals/container****
Ember.Container = _container.Container;
Ember.Registry = _container.Registry; // ****@ember/debug****
Ember.assert = EmberDebug.assert;
Ember.warn = EmberDebug.warn;
Ember.debug = EmberDebug.debug;
Ember.deprecate = EmberDebug.deprecate;
Ember.deprecateFunc = EmberDebug.deprecateFunc;
Ember.runInDebug = EmberDebug.runInDebug; // ****@ember/error****
Ember.Error = _error.default;
/**
@public
@class Ember.Debug
*/
Ember.Debug = {
registerDeprecationHandler: EmberDebug.registerDeprecationHandler,
registerWarnHandler: EmberDebug.registerWarnHandler,
isComputed: metal.isComputed
}; // ****@ember/instrumentation****
Ember.instrument = instrumentation.instrument;
Ember.subscribe = instrumentation.subscribe;
Ember.Instrumentation = {
instrument: instrumentation.instrument,
subscribe: instrumentation.subscribe,
unsubscribe: instrumentation.unsubscribe,
reset: instrumentation.reset
}; // ****@ember/runloop****
Ember.run = _runloop.run; // ****@ember/-internals/metal****
// in globals builds
Ember.computed = _object.computed;
Ember._descriptor = metal.nativeDescDecorator;
Ember._tracked = metal.tracked;
Ember.cacheFor = metal.getCachedValueFor;
Ember.ComputedProperty = metal.ComputedProperty;
Ember._setClassicDecorator = metal.setClassicDecorator;
Ember.meta = _meta.meta;
Ember.get = metal.get;
Ember._getPath = metal._getPath;
Ember.set = metal.set;
Ember.trySet = metal.trySet;
Ember.FEATURES = Object.assign({
isEnabled: _canaryFeatures.isEnabled
}, _canaryFeatures.FEATURES);
Ember._Cache = utils.Cache;
Ember.on = metal.on;
Ember.addListener = metal.addListener;
Ember.removeListener = metal.removeListener;
Ember.sendEvent = metal.sendEvent;
Ember.hasListeners = metal.hasListeners;
Ember.isNone = metal.isNone;
Ember.isEmpty = metal.isEmpty;
Ember.isBlank = metal.isBlank;
Ember.isPresent = metal.isPresent;
Ember.notifyPropertyChange = metal.notifyPropertyChange;
Ember.beginPropertyChanges = metal.beginPropertyChanges;
Ember.endPropertyChanges = metal.endPropertyChanges;
Ember.changeProperties = metal.changeProperties;
Ember.platform = {
defineProperty: true,
hasPropertyAccessors: true
};
Ember.defineProperty = metal.defineProperty;
Ember.destroy = _destroyable.destroy;
Ember.libraries = metal.libraries;
Ember.getProperties = metal.getProperties;
Ember.setProperties = metal.setProperties;
Ember.expandProperties = metal.expandProperties;
Ember.addObserver = metal.addObserver;
Ember.removeObserver = metal.removeObserver;
Ember.observer = metal.observer;
Ember.mixin = metal.mixin;
Ember.Mixin = metal.Mixin;
Ember._createCache = metal.createCache;
Ember._cacheGetValue = metal.getValue;
Ember._cacheIsConst = metal.isConst;
Ember._registerDestructor = _destroyable.registerDestructor;
Ember._unregisterDestructor = _destroyable.unregisterDestructor;
Ember._associateDestroyableChild = _destroyable.associateDestroyableChild;
Ember._assertDestroyablesDestroyed = _destroyable.assertDestroyablesDestroyed;
Ember._enableDestroyableTracking = _destroyable.enableDestroyableTracking;
Ember._isDestroying = _destroyable.isDestroying;
Ember._isDestroyed = _destroyable.isDestroyed;
/**
A function may be assigned to `Ember.onerror` to be called when Ember
internals encounter an error. This is useful for specialized error handling
and reporting code.
```javascript
Ember.onerror = function(error) {
const payload = {
stack: error.stack,
otherInformation: 'whatever app state you want to provide'
};
fetch('/report-error', {
method: 'POST',
body: JSON.stringify(payload)
});
};
```
Internally, `Ember.onerror` is used as Backburner's error handler.
@event onerror
@for Ember
@param {Exception} error the error object
@public
*/
Object.defineProperty(Ember, 'onerror', {
get: _errorHandling.getOnerror,
set: _errorHandling.setOnerror,
enumerable: false
});
Object.defineProperty(Ember, 'testing', {
get: EmberDebug.isTesting,
set: EmberDebug.setTesting,
enumerable: false
});
Ember._Backburner = _backburner.default; // ****@ember/-internals/runtime****
Ember.A = _runtime.A;
Ember.String = {
loc: _string.loc,
w: _string.w,
dasherize: _string.dasherize,
decamelize: _string.decamelize,
camelize: _string.camelize,
classify: _string.classify,
underscore: _string.underscore,
capitalize: _string.capitalize
};
Ember.Object = _runtime.Object;
Ember._RegistryProxyMixin = _runtime.RegistryProxyMixin;
Ember._ContainerProxyMixin = _runtime.ContainerProxyMixin;
Ember.compare = _runtime.compare;
Ember.isEqual = _runtime.isEqual;
/**
@module ember
*/
/**
Namespace for injection helper methods.
@class inject
@namespace Ember
@static
@public
*/
Ember.inject = function inject() {
(true && !(false) && (0, EmberDebug.assert)(`Injected properties must be created through helpers, see '${Object.keys(inject).map(k => `'inject.${k}'`).join(' or ')}'`));
};
Ember.inject.service = _service.inject;
Ember.inject.controller = _controller.inject;
Ember.Array = _runtime.Array;
Ember.Comparable = _runtime.Comparable;
Ember.Enumerable = _runtime.Enumerable;
Ember.ArrayProxy = _runtime.ArrayProxy;
Ember.ObjectProxy = _runtime.ObjectProxy;
Ember.ActionHandler = _runtime.ActionHandler;
Ember.CoreObject = _runtime.CoreObject;
Ember.NativeArray = _runtime.NativeArray;
Ember.MutableEnumerable = _runtime.MutableEnumerable;
Ember.MutableArray = _runtime.MutableArray;
Ember.Evented = _runtime.Evented;
Ember.PromiseProxyMixin = _runtime.PromiseProxyMixin;
Ember.Observable = _runtime.Observable;
Ember.typeOf = _runtime.typeOf;
Ember.isArray = _runtime.isArray;
Ember.Object = _runtime.Object;
Ember.onLoad = _application.onLoad;
Ember.runLoadHooks = _application.runLoadHooks;
Ember.Controller = _controller.default;
Ember.ControllerMixin = _controller_mixin.default;
Ember.Service = _service.default;
Ember._ProxyMixin = _runtime._ProxyMixin;
Ember.RSVP = _runtime.RSVP;
Ember.Namespace = _runtime.Namespace;
Ember._action = _object.action;
Ember._dependentKeyCompat = _compat.dependentKeyCompat;
/**
Defines the hash of localized strings for the current language. Used by
the `String.loc` helper. To localize, add string values to this
hash.
@property STRINGS
@for Ember
@type Object
@private
*/
Object.defineProperty(Ember, 'STRINGS', {
configurable: false,
get: _string._getStrings,
set: _string._setStrings
});
/**
Whether searching on the global for new Namespace instances is enabled.
This is only exported here as to not break any addons. Given the new
visit API, you will have issues if you treat this as a indicator of
booted.
Internally this is only exposing a flag in Namespace.
@property BOOTED
@for Ember
@type Boolean
@private
*/
Object.defineProperty(Ember, 'BOOTED', {
configurable: false,
enumerable: false,
get: metal.isNamespaceSearchDisabled,
set: metal.setNamespaceSearchDisabled
}); // ****@ember/-internals/glimmer****
Ember.Component = _glimmer.Component;
_glimmer.Helper.helper = _glimmer.helper;
Ember.Helper = _glimmer.Helper;
Ember._setComponentManager = _glimmer.setComponentManager;
Ember._componentManagerCapabilities = _glimmer.componentCapabilities;
Ember._setModifierManager = _manager.setModifierManager;
Ember._modifierManagerCapabilities = _glimmer.modifierCapabilities;
Ember._getComponentTemplate = _manager.getComponentTemplate;
Ember._setComponentTemplate = _manager.setComponentTemplate;
Ember._templateOnlyComponent = _runtime2.templateOnlyComponent;
Ember._Input = _glimmer.Input;
Ember._hash = _runtime2.hash;
Ember._array = _runtime2.array;
Ember._concat = _runtime2.concat;
Ember._get = _runtime2.get;
Ember._on = _runtime2.on;
Ember._fn = _runtime2.fn;
if (true
/* EMBER_GLIMMER_HELPER_MANAGER */
) {
Ember._helperManagerCapabilities = _manager.helperCapabilities;
Ember._setHelperManager = _manager.setHelperManager;
}
if (true
/* EMBER_GLIMMER_INVOKE_HELPER */
) {
Ember._invokeHelper = _runtime2.invokeHelper;
}
Ember._captureRenderTree = EmberDebug.captureRenderTree;
var deprecateImportFromString = function (name, message = `Importing ${name} from '@ember/string' is deprecated. Please import ${name} from '@ember/template' instead.`) {
// Disabling this deprecation due to unintended errors in 3.25
// See https://github.com/emberjs/ember.js/issues/19393 fo more information.
(true && !(true) && (0, EmberDebug.deprecate)(message, true, {
id: 'ember-string.htmlsafe-ishtmlsafe',
for: 'ember-source',
since: {
enabled: '3.25'
},
until: '4.0.0',
url: 'https://deprecations.emberjs.com/v3.x/#toc_ember-string-htmlsafe-ishtmlsafe'
}));
};
Object.defineProperty(Ember.String, 'htmlSafe', {
enumerable: true,
configurable: true,
get() {
deprecateImportFromString('htmlSafe');
return _glimmer.htmlSafe;
}
});
Object.defineProperty(Ember.String, 'isHTMLSafe', {
enumerable: true,
configurable: true,
get() {
deprecateImportFromString('isHTMLSafe');
return _glimmer.isHTMLSafe;
}
});
/**
Global hash of shared templates. This will automatically be populated
by the build tools so that you can store your Handlebars templates in
separate files that get loaded into JavaScript at buildtime.
@property TEMPLATES
@for Ember
@type Object
@private
*/
Object.defineProperty(Ember, 'TEMPLATES', {
get: _glimmer.getTemplates,
set: _glimmer.setTemplates,
configurable: false,
enumerable: false
});
/**
The semantic version
@property VERSION
@type String
@public
*/
Ember.VERSION = _version.default;
Ember.ViewUtils = {
isSimpleClick: views.isSimpleClick,
getElementView: views.getElementView,
getViewElement: views.getViewElement,
getViewBounds: views.getViewBounds,
getViewClientRects: views.getViewClientRects,
getViewBoundingClientRect: views.getViewBoundingClientRect,
getRootViews: views.getRootViews,
getChildViews: views.getChildViews,
isSerializationFirstNode: _glimmer.isSerializationFirstNode
};
Ember.ComponentLookup = views.ComponentLookup;
Ember.EventDispatcher = views.EventDispatcher; // ****@ember/-internals/routing****
Ember.Location = routing.Location;
Ember.AutoLocation = routing.AutoLocation;
Ember.HashLocation = routing.HashLocation;
Ember.HistoryLocation = routing.HistoryLocation;
Ember.NoneLocation = routing.NoneLocation;
Ember.controllerFor = routing.controllerFor;
Ember.generateControllerFactory = routing.generateControllerFactory;
Ember.generateController = routing.generateController;
Ember.RouterDSL = routing.RouterDSL;
Ember.Router = routing.Router;
Ember.Route = routing.Route;
(0, _application.runLoadHooks)('Ember.Application', _application.default);
Ember.DataAdapter = extensionSupport.DataAdapter;
Ember.ContainerDebugAdapter = extensionSupport.ContainerDebugAdapter;
var EmberHandlebars = {
template: _glimmer.template,
Utils: {
escapeExpression: _glimmer.escapeExpression
}
};
var EmberHTMLBars = {
template: _glimmer.template
};
function defineEmberTemplateCompilerLazyLoad(key) {
Object.defineProperty(Ember, key, {
configurable: true,
enumerable: true,
get() {
if ((0, _require.has)('ember-template-compiler')) {
var templateCompiler = (0, _require.default)("ember-template-compiler");
EmberHTMLBars.precompile = EmberHandlebars.precompile = templateCompiler.precompile;
EmberHTMLBars.compile = EmberHandlebars.compile = templateCompiler.compile;
Object.defineProperty(Ember, 'HTMLBars', {
configurable: true,
writable: true,
enumerable: true,
value: EmberHTMLBars
});
Object.defineProperty(Ember, 'Handlebars', {
configurable: true,
writable: true,
enumerable: true,
value: EmberHandlebars
});
}
return key === 'Handlebars' ? EmberHandlebars : EmberHTMLBars;
}
});
}
defineEmberTemplateCompilerLazyLoad('HTMLBars');
defineEmberTemplateCompilerLazyLoad('Handlebars'); // do this to ensure that Ember.Test is defined properly on the global
// if it is present.
function defineEmberTestingLazyLoad(key) {
Object.defineProperty(Ember, key, {
configurable: true,
enumerable: true,
get() {
if ((0, _require.has)('ember-testing')) {
var testing = (0, _require.default)("ember-testing");
var {
Test,
Adapter,
QUnitAdapter,
setupForTesting
} = testing;
Test.Adapter = Adapter;
Test.QUnitAdapter = QUnitAdapter;
Object.defineProperty(Ember, 'Test', {
configurable: true,
writable: true,
enumerable: true,
value: Test
});
Object.defineProperty(Ember, 'setupForTesting', {
configurable: true,
writable: true,
enumerable: true,
value: setupForTesting
});
return key === 'Test' ? Test : setupForTesting;
}
return undefined;
}
});
}
defineEmberTestingLazyLoad('Test');
defineEmberTestingLazyLoad('setupForTesting');
(0, _application.runLoadHooks)('Ember');
Ember.__loader = {
require: _require.default,
// eslint-disable-next-line no-undef
define,
// eslint-disable-next-line no-undef
registry: typeof requirejs !== 'undefined' ? requirejs.entries : _require.default.entries
};
var _default = Ember;
_exports.default = _default;
});
define("ember/version", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
var _default = "4.0.0";
_exports.default = _default;
});
define("route-recognizer", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
var createObject = Object.create;
function createMap() {
var map = createObject(null);
map["__"] = undefined;
delete map["__"];
return map;
}
var Target = function Target(path, matcher, delegate) {
this.path = path;
this.matcher = matcher;
this.delegate = delegate;
};
Target.prototype.to = function to(target, callback) {
var delegate = this.delegate;
if (delegate && delegate.willAddRoute) {
target = delegate.willAddRoute(this.matcher.target, target);
}
this.matcher.add(this.path, target);
if (callback) {
if (callback.length === 0) {
throw new Error("You must have an argument in the function passed to `to`");
}
this.matcher.addChild(this.path, target, callback, this.delegate);
}
};
var Matcher = function Matcher(target) {
this.routes = createMap();
this.children = createMap();
this.target = target;
};
Matcher.prototype.add = function add(path, target) {
this.routes[path] = target;
};
Matcher.prototype.addChild = function addChild(path, target, callback, delegate) {
var matcher = new Matcher(target);
this.children[path] = matcher;
var match = generateMatch(path, matcher, delegate);
if (delegate && delegate.contextEntered) {
delegate.contextEntered(target, match);
}
callback(match);
};
function generateMatch(startingPath, matcher, delegate) {
function match(path, callback) {
var fullPath = startingPath + path;
if (callback) {
callback(generateMatch(fullPath, matcher, delegate));
} else {
return new Target(fullPath, matcher, delegate);
}
}
return match;
}
function addRoute(routeArray, path, handler) {
var len = 0;
for (var i = 0; i < routeArray.length; i++) {
len += routeArray[i].path.length;
}
path = path.substr(len);
var route = {
path: path,
handler: handler
};
routeArray.push(route);
}
function eachRoute(baseRoute, matcher, callback, binding) {
var routes = matcher.routes;
var paths = Object.keys(routes);
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
var routeArray = baseRoute.slice();
addRoute(routeArray, path, routes[path]);
var nested = matcher.children[path];
if (nested) {
eachRoute(routeArray, nested, callback, binding);
} else {
callback.call(binding, routeArray);
}
}
}
var map = function (callback, addRouteCallback) {
var matcher = new Matcher();
callback(generateMatch("", matcher, this.delegate));
eachRoute([], matcher, function (routes) {
if (addRouteCallback) {
addRouteCallback(this, routes);
} else {
this.add(routes);
}
}, this);
}; // Normalizes percent-encoded values in `path` to upper-case and decodes percent-encoded
// values that are not reserved (i.e., unicode characters, emoji, etc). The reserved
// chars are "/" and "%".
// Safe to call multiple times on the same path.
// Normalizes percent-encoded values in `path` to upper-case and decodes percent-encoded
function normalizePath(path) {
return path.split("/").map(normalizeSegment).join("/");
} // We want to ensure the characters "%" and "/" remain in percent-encoded
// form when normalizing paths, so replace them with their encoded form after
// decoding the rest of the path
var SEGMENT_RESERVED_CHARS = /%|\//g;
function normalizeSegment(segment) {
if (segment.length < 3 || segment.indexOf("%") === -1) {
return segment;
}
return decodeURIComponent(segment).replace(SEGMENT_RESERVED_CHARS, encodeURIComponent);
} // We do not want to encode these characters when generating dynamic path segments
// See https://tools.ietf.org/html/rfc3986#section-3.3
// sub-delims: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
// others allowed by RFC 3986: ":", "@"
//
// First encode the entire path segment, then decode any of the encoded special chars.
//
// The chars "!", "'", "(", ")", "*" do not get changed by `encodeURIComponent`,
// so the possible encoded chars are:
// ['%24', '%26', '%2B', '%2C', '%3B', '%3D', '%3A', '%40'].
var PATH_SEGMENT_ENCODINGS = /%(?:2(?:4|6|B|C)|3(?:B|D|A)|40)/g;
function encodePathSegment(str) {
return encodeURIComponent(str).replace(PATH_SEGMENT_ENCODINGS, decodeURIComponent);
}
var escapeRegex = /(\/|\.|\*|\+|\?|\||\(|\)|\[|\]|\{|\}|\\)/g;
var isArray = Array.isArray;
var hasOwnProperty = Object.prototype.hasOwnProperty;
function getParam(params, key) {
if (typeof params !== "object" || params === null) {
throw new Error("You must pass an object as the second argument to `generate`.");
}
if (!hasOwnProperty.call(params, key)) {
throw new Error("You must provide param `" + key + "` to `generate`.");
}
var value = params[key];
var str = typeof value === "string" ? value : "" + value;
if (str.length === 0) {
throw new Error("You must provide a param `" + key + "`.");
}
return str;
}
var eachChar = [];
eachChar[0
/* Static */
] = function (segment, currentState) {
var state = currentState;
var value = segment.value;
for (var i = 0; i < value.length; i++) {
var ch = value.charCodeAt(i);
state = state.put(ch, false, false);
}
return state;
};
eachChar[1
/* Dynamic */
] = function (_, currentState) {
return currentState.put(47
/* SLASH */
, true, true);
};
eachChar[2
/* Star */
] = function (_, currentState) {
return currentState.put(-1
/* ANY */
, false, true);
};
eachChar[4
/* Epsilon */
] = function (_, currentState) {
return currentState;
};
var regex = [];
regex[0
/* Static */
] = function (segment) {
return segment.value.replace(escapeRegex, "\\$1");
};
regex[1
/* Dynamic */
] = function () {
return "([^/]+)";
};
regex[2
/* Star */
] = function () {
return "(.+)";
};
regex[4
/* Epsilon */
] = function () {
return "";
};
var generate = [];
generate[0
/* Static */
] = function (segment) {
return segment.value;
};
generate[1
/* Dynamic */
] = function (segment, params) {
var value = getParam(params, segment.value);
if (RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS) {
return encodePathSegment(value);
} else {
return value;
}
};
generate[2
/* Star */
] = function (segment, params) {
return getParam(params, segment.value);
};
generate[4
/* Epsilon */
] = function () {
return "";
};
var EmptyObject = Object.freeze({});
var EmptyArray = Object.freeze([]); // The `names` will be populated with the paramter name for each dynamic/star
// segment. `shouldDecodes` will be populated with a boolean for each dyanamic/star
// segment, indicating whether it should be decoded during recognition.
function parse(segments, route, types) {
// normalize route as not starting with a "/". Recognition will
// also normalize.
if (route.length > 0 && route.charCodeAt(0) === 47
/* SLASH */
) {
route = route.substr(1);
}
var parts = route.split("/");
var names = undefined;
var shouldDecodes = undefined;
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
var flags = 0;
var type = 0;
if (part === "") {
type = 4
/* Epsilon */
;
} else if (part.charCodeAt(0) === 58
/* COLON */
) {
type = 1
/* Dynamic */
;
} else if (part.charCodeAt(0) === 42
/* STAR */
) {
type = 2
/* Star */
;
} else {
type = 0
/* Static */
;
}
flags = 2 << type;
if (flags & 12
/* Named */
) {
part = part.slice(1);
names = names || [];
names.push(part);
shouldDecodes = shouldDecodes || [];
shouldDecodes.push((flags & 4
/* Decoded */
) !== 0);
}
if (flags & 14
/* Counted */
) {
types[type]++;
}
segments.push({
type: type,
value: normalizeSegment(part)
});
}
return {
names: names || EmptyArray,
shouldDecodes: shouldDecodes || EmptyArray
};
}
function isEqualCharSpec(spec, char, negate) {
return spec.char === char && spec.negate === negate;
} // A State has a character specification and (`charSpec`) and a list of possible
// subsequent states (`nextStates`).
//
// If a State is an accepting state, it will also have several additional
// properties:
//
// * `regex`: A regular expression that is used to extract parameters from paths
// that reached this accepting state.
// * `handlers`: Information on how to convert the list of captures into calls
// to registered handlers with the specified parameters
// * `types`: How many static, dynamic or star segments in this route. Used to
// decide which route to use if multiple registered routes match a path.
//
// Currently, State is implemented naively by looping over `nextStates` and
// comparing a character specification against a character. A more efficient
// implementation would use a hash of keys pointing at one or more next states.
var State = function State(states, id, char, negate, repeat) {
this.states = states;
this.id = id;
this.char = char;
this.negate = negate;
this.nextStates = repeat ? id : null;
this.pattern = "";
this._regex = undefined;
this.handlers = undefined;
this.types = undefined;
};
State.prototype.regex = function regex$1() {
if (!this._regex) {
this._regex = new RegExp(this.pattern);
}
return this._regex;
};
State.prototype.get = function get(char, negate) {
var this$1 = this;
var nextStates = this.nextStates;
if (nextStates === null) {
return;
}
if (isArray(nextStates)) {
for (var i = 0; i < nextStates.length; i++) {
var child = this$1.states[nextStates[i]];
if (isEqualCharSpec(child, char, negate)) {
return child;
}
}
} else {
var child$1 = this.states[nextStates];
if (isEqualCharSpec(child$1, char, negate)) {
return child$1;
}
}
};
State.prototype.put = function put(char, negate, repeat) {
var state; // If the character specification already exists in a child of the current
// state, just return that state.
if (state = this.get(char, negate)) {
return state;
} // Make a new state for the character spec
var states = this.states;
state = new State(states, states.length, char, negate, repeat);
states[states.length] = state; // Insert the new state as a child of the current state
if (this.nextStates == null) {
this.nextStates = state.id;
} else if (isArray(this.nextStates)) {
this.nextStates.push(state.id);
} else {
this.nextStates = [this.nextStates, state.id];
} // Return the new state
return state;
}; // Find a list of child states matching the next character
State.prototype.match = function match(ch) {
var this$1 = this;
var nextStates = this.nextStates;
if (!nextStates) {
return [];
}
var returned = [];
if (isArray(nextStates)) {
for (var i = 0; i < nextStates.length; i++) {
var child = this$1.states[nextStates[i]];
if (isMatch(child, ch)) {
returned.push(child);
}
}
} else {
var child$1 = this.states[nextStates];
if (isMatch(child$1, ch)) {
returned.push(child$1);
}
}
return returned;
};
function isMatch(spec, char) {
return spec.negate ? spec.char !== char && spec.char !== -1
/* ANY */
: spec.char === char || spec.char === -1
/* ANY */
;
} // This is a somewhat naive strategy, but should work in a lot of cases
// A better strategy would properly resolve /posts/:id/new and /posts/edit/:id.
//
// This strategy generally prefers more static and less dynamic matching.
// Specifically, it
//
// * prefers fewer stars to more, then
// * prefers using stars for less of the match to more, then
// * prefers fewer dynamic segments to more, then
// * prefers more static segments to more
function sortSolutions(states) {
return states.sort(function (a, b) {
var ref = a.types || [0, 0, 0];
var astatics = ref[0];
var adynamics = ref[1];
var astars = ref[2];
var ref$1 = b.types || [0, 0, 0];
var bstatics = ref$1[0];
var bdynamics = ref$1[1];
var bstars = ref$1[2];
if (astars !== bstars) {
return astars - bstars;
}
if (astars) {
if (astatics !== bstatics) {
return bstatics - astatics;
}
if (adynamics !== bdynamics) {
return bdynamics - adynamics;
}
}
if (adynamics !== bdynamics) {
return adynamics - bdynamics;
}
if (astatics !== bstatics) {
return bstatics - astatics;
}
return 0;
});
}
function recognizeChar(states, ch) {
var nextStates = [];
for (var i = 0, l = states.length; i < l; i++) {
var state = states[i];
nextStates = nextStates.concat(state.match(ch));
}
return nextStates;
}
var RecognizeResults = function RecognizeResults(queryParams) {
this.length = 0;
this.queryParams = queryParams || {};
};
RecognizeResults.prototype.splice = Array.prototype.splice;
RecognizeResults.prototype.slice = Array.prototype.slice;
RecognizeResults.prototype.push = Array.prototype.push;
function findHandler(state, originalPath, queryParams) {
var handlers = state.handlers;
var regex = state.regex();
if (!regex || !handlers) {
throw new Error("state not initialized");
}
var captures = originalPath.match(regex);
var currentCapture = 1;
var result = new RecognizeResults(queryParams);
result.length = handlers.length;
for (var i = 0; i < handlers.length; i++) {
var handler = handlers[i];
var names = handler.names;
var shouldDecodes = handler.shouldDecodes;
var params = EmptyObject;
var isDynamic = false;
if (names !== EmptyArray && shouldDecodes !== EmptyArray) {
for (var j = 0; j < names.length; j++) {
isDynamic = true;
var name = names[j];
var capture = captures && captures[currentCapture++];
if (params === EmptyObject) {
params = {};
}
if (RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS && shouldDecodes[j]) {
params[name] = capture && decodeURIComponent(capture);
} else {
params[name] = capture;
}
}
}
result[i] = {
handler: handler.handler,
params: params,
isDynamic: isDynamic
};
}
return result;
}
function decodeQueryParamPart(part) {
// http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1
part = part.replace(/\+/gm, "%20");
var result;
try {
result = decodeURIComponent(part);
} catch (error) {
result = "";
}
return result;
}
var RouteRecognizer = function RouteRecognizer() {
this.names = createMap();
var states = [];
var state = new State(states, 0, -1
/* ANY */
, true, false);
states[0] = state;
this.states = states;
this.rootState = state;
};
RouteRecognizer.prototype.add = function add(routes, options) {
var currentState = this.rootState;
var pattern = "^";
var types = [0, 0, 0];
var handlers = new Array(routes.length);
var allSegments = [];
var isEmpty = true;
var j = 0;
for (var i = 0; i < routes.length; i++) {
var route = routes[i];
var ref = parse(allSegments, route.path, types);
var names = ref.names;
var shouldDecodes = ref.shouldDecodes; // preserve j so it points to the start of newly added segments
for (; j < allSegments.length; j++) {
var segment = allSegments[j];
if (segment.type === 4
/* Epsilon */
) {
continue;
}
isEmpty = false; // Add a "/" for the new segment
currentState = currentState.put(47
/* SLASH */
, false, false);
pattern += "/"; // Add a representation of the segment to the NFA and regex
currentState = eachChar[segment.type](segment, currentState);
pattern += regex[segment.type](segment);
}
handlers[i] = {
handler: route.handler,
names: names,
shouldDecodes: shouldDecodes
};
}
if (isEmpty) {
currentState = currentState.put(47
/* SLASH */
, false, false);
pattern += "/";
}
currentState.handlers = handlers;
currentState.pattern = pattern + "$";
currentState.types = types;
var name;
if (typeof options === "object" && options !== null && options.as) {
name = options.as;
}
if (name) {
// if (this.names[name]) {
// throw new Error("You may not add a duplicate route named `" + name + "`.");
// }
this.names[name] = {
segments: allSegments,
handlers: handlers
};
}
};
RouteRecognizer.prototype.handlersFor = function handlersFor(name) {
var route = this.names[name];
if (!route) {
throw new Error("There is no route named " + name);
}
var result = new Array(route.handlers.length);
for (var i = 0; i < route.handlers.length; i++) {
var handler = route.handlers[i];
result[i] = handler;
}
return result;
};
RouteRecognizer.prototype.hasRoute = function hasRoute(name) {
return !!this.names[name];
};
RouteRecognizer.prototype.generate = function generate$1(name, params) {
var route = this.names[name];
var output = "";
if (!route) {
throw new Error("There is no route named " + name);
}
var segments = route.segments;
for (var i = 0; i < segments.length; i++) {
var segment = segments[i];
if (segment.type === 4
/* Epsilon */
) {
continue;
}
output += "/";
output += generate[segment.type](segment, params);
}
if (output.charAt(0) !== "/") {
output = "/" + output;
}
if (params && params.queryParams) {
output += this.generateQueryString(params.queryParams);
}
return output;
};
RouteRecognizer.prototype.generateQueryString = function generateQueryString(params) {
var pairs = [];
var keys = Object.keys(params);
keys.sort();
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = params[key];
if (value == null) {
continue;
}
var pair = encodeURIComponent(key);
if (isArray(value)) {
for (var j = 0; j < value.length; j++) {
var arrayPair = key + "[]" + "=" + encodeURIComponent(value[j]);
pairs.push(arrayPair);
}
} else {
pair += "=" + encodeURIComponent(value);
pairs.push(pair);
}
}
if (pairs.length === 0) {
return "";
}
return "?" + pairs.join("&");
};
RouteRecognizer.prototype.parseQueryString = function parseQueryString(queryString) {
var pairs = queryString.split("&");
var queryParams = {};
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split("="),
key = decodeQueryParamPart(pair[0]),
keyLength = key.length,
isArray = false,
value = void 0;
if (pair.length === 1) {
value = "true";
} else {
// Handle arrays
if (keyLength > 2 && key.slice(keyLength - 2) === "[]") {
isArray = true;
key = key.slice(0, keyLength - 2);
if (!queryParams[key]) {
queryParams[key] = [];
}
}
value = pair[1] ? decodeQueryParamPart(pair[1]) : "";
}
if (isArray) {
queryParams[key].push(value);
} else {
queryParams[key] = value;
}
}
return queryParams;
};
RouteRecognizer.prototype.recognize = function recognize(path) {
var results;
var states = [this.rootState];
var queryParams = {};
var isSlashDropped = false;
var hashStart = path.indexOf("#");
if (hashStart !== -1) {
path = path.substr(0, hashStart);
}
var queryStart = path.indexOf("?");
if (queryStart !== -1) {
var queryString = path.substr(queryStart + 1, path.length);
path = path.substr(0, queryStart);
queryParams = this.parseQueryString(queryString);
}
if (path.charAt(0) !== "/") {
path = "/" + path;
}
var originalPath = path;
if (RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS) {
path = normalizePath(path);
} else {
path = decodeURI(path);
originalPath = decodeURI(originalPath);
}
var pathLen = path.length;
if (pathLen > 1 && path.charAt(pathLen - 1) === "/") {
path = path.substr(0, pathLen - 1);
originalPath = originalPath.substr(0, originalPath.length - 1);
isSlashDropped = true;
}
for (var i = 0; i < path.length; i++) {
states = recognizeChar(states, path.charCodeAt(i));
if (!states.length) {
break;
}
}
var solutions = [];
for (var i$1 = 0; i$1 < states.length; i$1++) {
if (states[i$1].handlers) {
solutions.push(states[i$1]);
}
}
states = sortSolutions(solutions);
var state = solutions[0];
if (state && state.handlers) {
// if a trailing slash was dropped and a star segment is the last segment
// specified, put the trailing slash back
if (isSlashDropped && state.pattern && state.pattern.slice(-5) === "(.+)$") {
originalPath = originalPath + "/";
}
results = findHandler(state, originalPath, queryParams);
}
return results;
};
RouteRecognizer.VERSION = "0.3.4"; // Set to false to opt-out of encoding and decoding path segments.
// See https://github.com/tildeio/route-recognizer/pull/55
RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS = true;
RouteRecognizer.Normalizer = {
normalizeSegment: normalizeSegment,
normalizePath: normalizePath,
encodePathSegment: encodePathSegment
};
RouteRecognizer.prototype.map = map;
var _default = RouteRecognizer;
_exports.default = _default;
});
define("router_js", ["exports", "rsvp", "route-recognizer"], function (_exports, _rsvp, _routeRecognizer) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.logAbort = logAbort;
_exports.InternalRouteInfo = _exports.TransitionError = _exports.TransitionState = _exports.QUERY_PARAMS_SYMBOL = _exports.PARAMS_SYMBOL = _exports.STATE_SYMBOL = _exports.InternalTransition = _exports.default = void 0;
function buildTransitionAborted() {
var error = new Error('TransitionAborted');
error.name = 'TransitionAborted';
error.code = 'TRANSITION_ABORTED';
return error;
}
function isTransitionAborted(maybeError) {
return typeof maybeError === 'object' && maybeError !== null && maybeError.code === 'TRANSITION_ABORTED';
}
function isAbortable(maybeAbortable) {
return typeof maybeAbortable === 'object' && maybeAbortable !== null && typeof maybeAbortable.isAborted === 'boolean';
}
function throwIfAborted(maybe) {
if (isAbortable(maybe) && maybe.isAborted) {
throw buildTransitionAborted();
}
}
var slice = Array.prototype.slice;
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
Determines if an object is Promise by checking if it is "thenable".
**/
function isPromise(p) {
return p !== null && typeof p === 'object' && typeof p.then === 'function';
}
function merge(hash, other) {
for (var prop in other) {
if (hasOwnProperty.call(other, prop)) {
hash[prop] = other[prop];
}
}
}
/**
@private
Extracts query params from the end of an array
**/
function extractQueryParams(array) {
var len = array && array.length,
head,
queryParams;
if (len && len > 0) {
var obj = array[len - 1];
if (isQueryParams(obj)) {
queryParams = obj.queryParams;
head = slice.call(array, 0, len - 1);
return [head, queryParams];
}
}
return [array, null];
}
function isQueryParams(obj) {
return obj && hasOwnProperty.call(obj, 'queryParams');
}
/**
@private
Coerces query param properties and array elements into strings.
**/
function coerceQueryParamsToString(queryParams) {
for (var key in queryParams) {
var val = queryParams[key];
if (typeof val === 'number') {
queryParams[key] = '' + val;
} else if (Array.isArray(val)) {
for (var i = 0, l = val.length; i < l; i++) {
val[i] = '' + val[i];
}
}
}
}
/**
@private
*/
function log(router, ...args) {
if (!router.log) {
return;
}
if (args.length === 2) {
var [sequence, msg] = args;
router.log('Transition #' + sequence + ': ' + msg);
} else {
var [_msg] = args;
router.log(_msg);
}
}
function isParam(object) {
return typeof object === 'string' || object instanceof String || typeof object === 'number' || object instanceof Number;
}
function forEach(array, callback) {
for (var i = 0, l = array.length; i < l && callback(array[i]) !== false; i++) {// empty intentionally
}
}
function getChangelist(oldObject, newObject) {
var key;
var results = {
all: {},
changed: {},
removed: {}
};
merge(results.all, newObject);
var didChange = false;
coerceQueryParamsToString(oldObject);
coerceQueryParamsToString(newObject); // Calculate removals
for (key in oldObject) {
if (hasOwnProperty.call(oldObject, key)) {
if (!hasOwnProperty.call(newObject, key)) {
didChange = true;
results.removed[key] = oldObject[key];
}
}
} // Calculate changes
for (key in newObject) {
if (hasOwnProperty.call(newObject, key)) {
var oldElement = oldObject[key];
var newElement = newObject[key];
if (isArray(oldElement) && isArray(newElement)) {
if (oldElement.length !== newElement.length) {
results.changed[key] = newObject[key];
didChange = true;
} else {
for (var i = 0, l = oldElement.length; i < l; i++) {
if (oldElement[i] !== newElement[i]) {
results.changed[key] = newObject[key];
didChange = true;
}
}
}
} else if (oldObject[key] !== newObject[key]) {
results.changed[key] = newObject[key];
didChange = true;
}
}
}
return didChange ? results : undefined;
}
function isArray(obj) {
return Array.isArray(obj);
}
function promiseLabel(label) {
return 'Router: ' + label;
}
var STATE_SYMBOL = `__STATE__-2619860001345920-3322w3`;
_exports.STATE_SYMBOL = STATE_SYMBOL;
var PARAMS_SYMBOL = `__PARAMS__-261986232992830203-23323`;
_exports.PARAMS_SYMBOL = PARAMS_SYMBOL;
var QUERY_PARAMS_SYMBOL = `__QPS__-2619863929824844-32323`;
/**
A Transition is a thenable (a promise-like object) that represents
an attempt to transition to another route. It can be aborted, either
explicitly via `abort` or by attempting another transition while a
previous one is still underway. An aborted transition can also
be `retry()`d later.
@class Transition
@constructor
@param {Object} router
@param {Object} intent
@param {Object} state
@param {Object} error
@private
*/
_exports.QUERY_PARAMS_SYMBOL = QUERY_PARAMS_SYMBOL;
class Transition {
constructor(router, intent, state, error = undefined, previousTransition = undefined) {
this.from = null;
this.to = undefined;
this.isAborted = false;
this.isActive = true;
this.urlMethod = 'update';
this.resolveIndex = 0;
this.queryParamsOnly = false;
this.isTransition = true;
this.isCausedByAbortingTransition = false;
this.isCausedByInitialTransition = false;
this.isCausedByAbortingReplaceTransition = false;
this._visibleQueryParams = {};
this.isIntermediate = false;
this[STATE_SYMBOL] = state || router.state;
this.intent = intent;
this.router = router;
this.data = intent && intent.data || {};
this.resolvedModels = {};
this[QUERY_PARAMS_SYMBOL] = {};
this.promise = undefined;
this.error = undefined;
this[PARAMS_SYMBOL] = {};
this.routeInfos = [];
this.targetName = undefined;
this.pivotHandler = undefined;
this.sequence = -1;
if (true
/* DEBUG */
) {
var _error = new Error(`Transition creation stack`);
this.debugCreationStack = () => _error.stack; // not aborted yet, will be replaced when `this.isAborted` is set
this.debugAbortStack = () => undefined;
this.debugPreviousTransition = previousTransition;
}
if (error) {
this.promise = _rsvp.Promise.reject(error);
this.error = error;
return;
} // if you're doing multiple redirects, need the new transition to know if it
// is actually part of the first transition or not. Any further redirects
// in the initial transition also need to know if they are part of the
// initial transition
this.isCausedByAbortingTransition = !!previousTransition;
this.isCausedByInitialTransition = !!previousTransition && (previousTransition.isCausedByInitialTransition || previousTransition.sequence === 0); // Every transition in the chain is a replace
this.isCausedByAbortingReplaceTransition = !!previousTransition && previousTransition.urlMethod === 'replace' && (!previousTransition.isCausedByAbortingTransition || previousTransition.isCausedByAbortingReplaceTransition);
if (state) {
this[PARAMS_SYMBOL] = state.params;
this[QUERY_PARAMS_SYMBOL] = state.queryParams;
this.routeInfos = state.routeInfos;
var len = state.routeInfos.length;
if (len) {
this.targetName = state.routeInfos[len - 1].name;
}
for (var i = 0; i < len; ++i) {
var handlerInfo = state.routeInfos[i]; // TODO: this all seems hacky
if (!handlerInfo.isResolved) {
break;
}
this.pivotHandler = handlerInfo.route;
}
this.sequence = router.currentSequence++;
this.promise = state.resolve(this).catch(result => {
var error = this.router.transitionDidError(result, this);
throw error;
}, promiseLabel('Handle Abort'));
} else {
this.promise = _rsvp.Promise.resolve(this[STATE_SYMBOL]);
this[PARAMS_SYMBOL] = {};
}
}
/**
The Transition's internal promise. Calling `.then` on this property
is that same as calling `.then` on the Transition object itself, but
this property is exposed for when you want to pass around a
Transition's promise, but not the Transition object itself, since
Transition object can be externally `abort`ed, while the promise
cannot.
@property promise
@type {Object}
@public
*/
/**
Custom state can be stored on a Transition's `data` object.
This can be useful for decorating a Transition within an earlier
hook and shared with a later hook. Properties set on `data` will
be copied to new transitions generated by calling `retry` on this
transition.
@property data
@type {Object}
@public
*/
/**
A standard promise hook that resolves if the transition
succeeds and rejects if it fails/redirects/aborts.
Forwards to the internal `promise` property which you can
use in situations where you want to pass around a thenable,
but not the Transition itself.
@method then
@param {Function} onFulfilled
@param {Function} onRejected
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise}
@public
*/
then(onFulfilled, onRejected, label) {
return this.promise.then(onFulfilled, onRejected, label);
}
/**
Forwards to the internal `promise` property which you can
use in situations where you want to pass around a thennable,
but not the Transition itself.
@method catch
@param {Function} onRejection
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise}
@public
*/
catch(onRejection, label) {
return this.promise.catch(onRejection, label);
}
/**
Forwards to the internal `promise` property which you can
use in situations where you want to pass around a thenable,
but not the Transition itself.
@method finally
@param {Function} callback
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise}
@public
*/
finally(callback, label) {
return this.promise.finally(callback, label);
}
/**
Aborts the Transition. Note you can also implicitly abort a transition
by initiating another transition while a previous one is underway.
@method abort
@return {Transition} this transition
@public
*/
abort() {
this.rollback();
var transition = new Transition(this.router, undefined, undefined, undefined);
transition.to = this.from;
transition.from = this.from;
transition.isAborted = true;
this.router.routeWillChange(transition);
this.router.routeDidChange(transition);
return this;
}
rollback() {
if (!this.isAborted) {
log(this.router, this.sequence, this.targetName + ': transition was aborted');
if (true
/* DEBUG */
) {
var error = new Error(`Transition aborted stack`);
this.debugAbortStack = () => error.stack;
}
if (this.intent !== undefined && this.intent !== null) {
this.intent.preTransitionState = this.router.state;
}
this.isAborted = true;
this.isActive = false;
this.router.activeTransition = undefined;
}
}
redirect(newTransition) {
this.rollback();
this.router.routeWillChange(newTransition);
}
/**
Retries a previously-aborted transition (making sure to abort the
transition if it's still active). Returns a new transition that
represents the new attempt to transition.
@method retry
@return {Transition} new transition
@public
*/
retry() {
// TODO: add tests for merged state retry()s
this.abort();
var newTransition = this.router.transitionByIntent(this.intent, false); // inheriting a `null` urlMethod is not valid
// the urlMethod is only set to `null` when
// the transition is initiated *after* the url
// has been updated (i.e. `router.handleURL`)
//
// in that scenario, the url method cannot be
// inherited for a new transition because then
// the url would not update even though it should
if (this.urlMethod !== null) {
newTransition.method(this.urlMethod);
}
return newTransition;
}
/**
Sets the URL-changing method to be employed at the end of a
successful transition. By default, a new Transition will just
use `updateURL`, but passing 'replace' to this method will
cause the URL to update using 'replaceWith' instead. Omitting
a parameter will disable the URL change, allowing for transitions
that don't update the URL at completion (this is also used for
handleURL, since the URL has already changed before the
transition took place).
@method method
@param {String} method the type of URL-changing method to use
at the end of a transition. Accepted values are 'replace',
falsy values, or any other non-falsy value (which is
interpreted as an updateURL transition).
@return {Transition} this transition
@public
*/
method(method) {
this.urlMethod = method;
return this;
} // Alias 'trigger' as 'send'
send(ignoreFailure = false, _name, err, transition, handler) {
this.trigger(ignoreFailure, _name, err, transition, handler);
}
/**
Fires an event on the current list of resolved/resolving
handlers within this transition. Useful for firing events
on route hierarchies that haven't fully been entered yet.
Note: This method is also aliased as `send`
@method trigger
@param {Boolean} [ignoreFailure=false] a boolean specifying whether unhandled events throw an error
@param {String} name the name of the event to fire
@public
*/
trigger(ignoreFailure = false, name, ...args) {
// TODO: Deprecate the current signature
if (typeof ignoreFailure === 'string') {
name = ignoreFailure;
ignoreFailure = false;
}
this.router.triggerEvent(this[STATE_SYMBOL].routeInfos.slice(0, this.resolveIndex + 1), ignoreFailure, name, args);
}
/**
Transitions are aborted and their promises rejected
when redirects occur; this method returns a promise
that will follow any redirects that occur and fulfill
with the value fulfilled by any redirecting transitions
that occur.
@method followRedirects
@return {Promise} a promise that fulfills with the same
value that the final redirecting transition fulfills with
@public
*/
followRedirects() {
var router = this.router;
return this.promise.catch(function (reason) {
if (router.activeTransition) {
return router.activeTransition.followRedirects();
}
return _rsvp.Promise.reject(reason);
});
}
toString() {
return 'Transition (sequence ' + this.sequence + ')';
}
/**
@private
*/
log(message) {
log(this.router, this.sequence, message);
}
}
/**
@private
Logs and returns an instance of TransitionAborted.
*/
_exports.InternalTransition = Transition;
function logAbort(transition) {
log(transition.router, transition.sequence, 'detected abort.');
return buildTransitionAborted();
}
function isTransition(obj) {
return typeof obj === 'object' && obj instanceof Transition && obj.isTransition;
}
function prepareResult(obj) {
if (isTransition(obj)) {
return null;
}
return obj;
}
var ROUTE_INFOS = new WeakMap();
function toReadOnlyRouteInfo(routeInfos, queryParams = {}, includeAttributes = false) {
return routeInfos.map((info, i) => {
var {
name,
params,
paramNames,
context,
route
} = info;
if (ROUTE_INFOS.has(info) && includeAttributes) {
var _routeInfo = ROUTE_INFOS.get(info);
_routeInfo = attachMetadata(route, _routeInfo);
var routeInfoWithAttribute = createRouteInfoWithAttributes(_routeInfo, context);
ROUTE_INFOS.set(info, routeInfoWithAttribute);
return routeInfoWithAttribute;
}
var routeInfo = {
find(predicate, thisArg) {
var publicInfo;
var arr = [];
if (predicate.length === 3) {
arr = routeInfos.map(info => ROUTE_INFOS.get(info));
}
for (var _i = 0; routeInfos.length > _i; _i++) {
publicInfo = ROUTE_INFOS.get(routeInfos[_i]);
if (predicate.call(thisArg, publicInfo, _i, arr)) {
return publicInfo;
}
}
return undefined;
},
get name() {
return name;
},
get paramNames() {
return paramNames;
},
get metadata() {
return buildRouteInfoMetadata(info.route);
},
get parent() {
var parent = routeInfos[i - 1];
if (parent === undefined) {
return null;
}
return ROUTE_INFOS.get(parent);
},
get child() {
var child = routeInfos[i + 1];
if (child === undefined) {
return null;
}
return ROUTE_INFOS.get(child);
},
get localName() {
var parts = this.name.split('.');
return parts[parts.length - 1];
},
get params() {
return params;
},
get queryParams() {
return queryParams;
}
};
if (includeAttributes) {
routeInfo = createRouteInfoWithAttributes(routeInfo, context);
}
ROUTE_INFOS.set(info, routeInfo);
return routeInfo;
});
}
function createRouteInfoWithAttributes(routeInfo, context) {
var attributes = {
get attributes() {
return context;
}
};
if (!Object.isExtensible(routeInfo) || routeInfo.hasOwnProperty('attributes')) {
return Object.freeze(Object.assign({}, routeInfo, attributes));
}
return Object.assign(routeInfo, attributes);
}
function buildRouteInfoMetadata(route) {
if (route !== undefined && route !== null && route.buildRouteInfoMetadata !== undefined) {
return route.buildRouteInfoMetadata();
}
return null;
}
function attachMetadata(route, routeInfo) {
var metadata = {
get metadata() {
return buildRouteInfoMetadata(route);
}
};
if (!Object.isExtensible(routeInfo) || routeInfo.hasOwnProperty('metadata')) {
return Object.freeze(Object.assign({}, routeInfo, metadata));
}
return Object.assign(routeInfo, metadata);
}
class InternalRouteInfo {
constructor(router, name, paramNames, route) {
this._routePromise = undefined;
this._route = null;
this.params = {};
this.isResolved = false;
this.name = name;
this.paramNames = paramNames;
this.router = router;
if (route) {
this._processRoute(route);
}
}
getModel(_transition) {
return _rsvp.Promise.resolve(this.context);
}
serialize(_context) {
return this.params || {};
}
resolve(transition) {
return _rsvp.Promise.resolve(this.routePromise).then(route => {
throwIfAborted(transition);
return route;
}).then(() => this.runBeforeModelHook(transition)).then(() => throwIfAborted(transition)).then(() => this.getModel(transition)).then(resolvedModel => {
throwIfAborted(transition);
return resolvedModel;
}).then(resolvedModel => this.runAfterModelHook(transition, resolvedModel)).then(resolvedModel => this.becomeResolved(transition, resolvedModel));
}
becomeResolved(transition, resolvedContext) {
var params = this.serialize(resolvedContext);
if (transition) {
this.stashResolvedModel(transition, resolvedContext);
transition[PARAMS_SYMBOL] = transition[PARAMS_SYMBOL] || {};
transition[PARAMS_SYMBOL][this.name] = params;
}
var context;
var contextsMatch = resolvedContext === this.context;
if ('context' in this || !contextsMatch) {
context = resolvedContext;
}
var cached = ROUTE_INFOS.get(this);
var resolved = new ResolvedRouteInfo(this.router, this.name, this.paramNames, params, this.route, context);
if (cached !== undefined) {
ROUTE_INFOS.set(resolved, cached);
}
return resolved;
}
shouldSupersede(routeInfo) {
// Prefer this newer routeInfo over `other` if:
// 1) The other one doesn't exist
// 2) The names don't match
// 3) This route has a context that doesn't match
// the other one (or the other one doesn't have one).
// 4) This route has parameters that don't match the other.
if (!routeInfo) {
return true;
}
var contextsMatch = routeInfo.context === this.context;
return routeInfo.name !== this.name || 'context' in this && !contextsMatch || this.hasOwnProperty('params') && !paramsMatch(this.params, routeInfo.params);
}
get route() {
// _route could be set to either a route object or undefined, so we
// compare against null to know when it's been set
if (this._route !== null) {
return this._route;
}
return this.fetchRoute();
}
set route(route) {
this._route = route;
}
get routePromise() {
if (this._routePromise) {
return this._routePromise;
}
this.fetchRoute();
return this._routePromise;
}
set routePromise(routePromise) {
this._routePromise = routePromise;
}
log(transition, message) {
if (transition.log) {
transition.log(this.name + ': ' + message);
}
}
updateRoute(route) {
route._internalName = this.name;
return this.route = route;
}
runBeforeModelHook(transition) {
if (transition.trigger) {
transition.trigger(true, 'willResolveModel', transition, this.route);
}
var result;
if (this.route) {
if (this.route.beforeModel !== undefined) {
result = this.route.beforeModel(transition);
}
}
if (isTransition(result)) {
result = null;
}
return _rsvp.Promise.resolve(result);
}
runAfterModelHook(transition, resolvedModel) {
// Stash the resolved model on the payload.
// This makes it possible for users to swap out
// the resolved model in afterModel.
var name = this.name;
this.stashResolvedModel(transition, resolvedModel);
var result;
if (this.route !== undefined) {
if (this.route.afterModel !== undefined) {
result = this.route.afterModel(resolvedModel, transition);
}
}
result = prepareResult(result);
return _rsvp.Promise.resolve(result).then(() => {
// Ignore the fulfilled value returned from afterModel.
// Return the value stashed in resolvedModels, which
// might have been swapped out in afterModel.
return transition.resolvedModels[name];
});
}
stashResolvedModel(transition, resolvedModel) {
transition.resolvedModels = transition.resolvedModels || {};
transition.resolvedModels[this.name] = resolvedModel;
}
fetchRoute() {
var route = this.router.getRoute(this.name);
return this._processRoute(route);
}
_processRoute(route) {
// Setup a routePromise so that we can wait for asynchronously loaded routes
this.routePromise = _rsvp.Promise.resolve(route); // Wait until the 'route' property has been updated when chaining to a route
// that is a promise
if (isPromise(route)) {
this.routePromise = this.routePromise.then(r => {
return this.updateRoute(r);
}); // set to undefined to avoid recursive loop in the route getter
return this.route = undefined;
} else if (route) {
return this.updateRoute(route);
}
return undefined;
}
}
_exports.InternalRouteInfo = InternalRouteInfo;
class ResolvedRouteInfo extends InternalRouteInfo {
constructor(router, name, paramNames, params, route, context) {
super(router, name, paramNames, route);
this.params = params;
this.isResolved = true;
this.context = context;
}
resolve(transition) {
// A ResolvedRouteInfo just resolved with itself.
if (transition && transition.resolvedModels) {
transition.resolvedModels[this.name] = this.context;
}
return _rsvp.Promise.resolve(this);
}
}
class UnresolvedRouteInfoByParam extends InternalRouteInfo {
constructor(router, name, paramNames, params, route) {
super(router, name, paramNames, route);
this.params = {};
this.params = params;
}
getModel(transition) {
var fullParams = this.params;
if (transition && transition[QUERY_PARAMS_SYMBOL]) {
fullParams = {};
merge(fullParams, this.params);
fullParams.queryParams = transition[QUERY_PARAMS_SYMBOL];
}
var route = this.route;
var result;
if (route.deserialize) {
result = route.deserialize(fullParams, transition);
} else if (route.model) {
result = route.model(fullParams, transition);
}
if (result && isTransition(result)) {
result = undefined;
}
return _rsvp.Promise.resolve(result);
}
}
class UnresolvedRouteInfoByObject extends InternalRouteInfo {
constructor(router, name, paramNames, context) {
super(router, name, paramNames);
this.context = context;
this.serializer = this.router.getSerializer(name);
}
getModel(transition) {
if (this.router.log !== undefined) {
this.router.log(this.name + ': resolving provided model');
}
return super.getModel(transition);
}
/**
@private
Serializes a route using its custom `serialize` method or
by a default that looks up the expected property name from
the dynamic segment.
@param {Object} model the model to be serialized for this route
*/
serialize(model) {
var {
paramNames,
context
} = this;
if (!model) {
model = context;
}
var object = {};
if (isParam(model)) {
object[paramNames[0]] = model;
return object;
} // Use custom serialize if it exists.
if (this.serializer) {
// invoke this.serializer unbound (getSerializer returns a stateless function)
return this.serializer.call(null, model, paramNames);
} else if (this.route !== undefined) {
if (this.route.serialize) {
return this.route.serialize(model, paramNames);
}
}
if (paramNames.length !== 1) {
return;
}
var name = paramNames[0];
if (/_id$/.test(name)) {
object[name] = model.id;
} else {
object[name] = model;
}
return object;
}
}
function paramsMatch(a, b) {
if (!a !== !b) {
// Only one is null.
return false;
}
if (!a) {
// Both must be null.
return true;
} // Note: this assumes that both params have the same
// number of keys, but since we're comparing the
// same routes, they should.
for (var k in a) {
if (a.hasOwnProperty(k) && a[k] !== b[k]) {
return false;
}
}
return true;
}
class TransitionIntent {
constructor(router, data = {}) {
this.router = router;
this.data = data;
}
}
function handleError(currentState, transition, error) {
// This is the only possible
// reject value of TransitionState#resolve
var routeInfos = currentState.routeInfos;
var errorHandlerIndex = transition.resolveIndex >= routeInfos.length ? routeInfos.length - 1 : transition.resolveIndex;
var wasAborted = transition.isAborted;
throw new TransitionError(error, currentState.routeInfos[errorHandlerIndex].route, wasAborted, currentState);
}
function resolveOneRouteInfo(currentState, transition) {
if (transition.resolveIndex === currentState.routeInfos.length) {
// This is is the only possible
// fulfill value of TransitionState#resolve
return;
}
var routeInfo = currentState.routeInfos[transition.resolveIndex];
return routeInfo.resolve(transition).then(proceed.bind(null, currentState, transition), null, currentState.promiseLabel('Proceed'));
}
function proceed(currentState, transition, resolvedRouteInfo) {
var wasAlreadyResolved = currentState.routeInfos[transition.resolveIndex].isResolved; // Swap the previously unresolved routeInfo with
// the resolved routeInfo
currentState.routeInfos[transition.resolveIndex++] = resolvedRouteInfo;
if (!wasAlreadyResolved) {
// Call the redirect hook. The reason we call it here
// vs. afterModel is so that redirects into child
// routes don't re-run the model hooks for this
// already-resolved route.
var {
route
} = resolvedRouteInfo;
if (route !== undefined) {
if (route.redirect) {
route.redirect(resolvedRouteInfo.context, transition);
}
}
} // Proceed after ensuring that the redirect hook
// didn't abort this transition by transitioning elsewhere.
throwIfAborted(transition);
return resolveOneRouteInfo(currentState, transition);
}
class TransitionState {
constructor() {
this.routeInfos = [];
this.queryParams = {};
this.params = {};
}
promiseLabel(label) {
var targetName = '';
forEach(this.routeInfos, function (routeInfo) {
if (targetName !== '') {
targetName += '.';
}
targetName += routeInfo.name;
return true;
});
return promiseLabel("'" + targetName + "': " + label);
}
resolve(transition) {
// First, calculate params for this state. This is useful
// information to provide to the various route hooks.
var params = this.params;
forEach(this.routeInfos, routeInfo => {
params[routeInfo.name] = routeInfo.params || {};
return true;
});
transition.resolveIndex = 0; // The prelude RSVP.resolve() async moves us into the promise land.
return _rsvp.Promise.resolve(null, this.promiseLabel('Start transition')).then(resolveOneRouteInfo.bind(null, this, transition), null, this.promiseLabel('Resolve route')).catch(handleError.bind(null, this, transition), this.promiseLabel('Handle error')).then(() => this);
}
}
_exports.TransitionState = TransitionState;
class TransitionError {
constructor(error, route, wasAborted, state) {
this.error = error;
this.route = route;
this.wasAborted = wasAborted;
this.state = state;
}
}
_exports.TransitionError = TransitionError;
class NamedTransitionIntent extends TransitionIntent {
constructor(router, name, pivotHandler, contexts = [], queryParams = {}, data) {
super(router, data);
this.preTransitionState = undefined;
this.name = name;
this.pivotHandler = pivotHandler;
this.contexts = contexts;
this.queryParams = queryParams;
}
applyToState(oldState, isIntermediate) {
// TODO: WTF fix me
var partitionedArgs = extractQueryParams([this.name].concat(this.contexts)),
pureArgs = partitionedArgs[0],
handlers = this.router.recognizer.handlersFor(pureArgs[0]);
var targetRouteName = handlers[handlers.length - 1].handler;
return this.applyToHandlers(oldState, handlers, targetRouteName, isIntermediate, false);
}
applyToHandlers(oldState, parsedHandlers, targetRouteName, isIntermediate, checkingIfActive) {
var i, len;
var newState = new TransitionState();
var objects = this.contexts.slice(0);
var invalidateIndex = parsedHandlers.length; // Pivot handlers are provided for refresh transitions
if (this.pivotHandler) {
for (i = 0, len = parsedHandlers.length; i < len; ++i) {
if (parsedHandlers[i].handler === this.pivotHandler._internalName) {
invalidateIndex = i;
break;
}
}
}
for (i = parsedHandlers.length - 1; i >= 0; --i) {
var result = parsedHandlers[i];
var name = result.handler;
var oldHandlerInfo = oldState.routeInfos[i];
var newHandlerInfo = null;
if (result.names.length > 0) {
if (i >= invalidateIndex) {
newHandlerInfo = this.createParamHandlerInfo(name, result.names, objects, oldHandlerInfo);
} else {
newHandlerInfo = this.getHandlerInfoForDynamicSegment(name, result.names, objects, oldHandlerInfo, targetRouteName, i);
}
} else {
// This route has no dynamic segment.
// Therefore treat as a param-based handlerInfo
// with empty params. This will cause the `model`
// hook to be called with empty params, which is desirable.
newHandlerInfo = this.createParamHandlerInfo(name, result.names, objects, oldHandlerInfo);
}
if (checkingIfActive) {
// If we're performing an isActive check, we want to
// serialize URL params with the provided context, but
// ignore mismatches between old and new context.
newHandlerInfo = newHandlerInfo.becomeResolved(null, newHandlerInfo.context);
var oldContext = oldHandlerInfo && oldHandlerInfo.context;
if (result.names.length > 0 && oldHandlerInfo.context !== undefined && newHandlerInfo.context === oldContext) {
// If contexts match in isActive test, assume params also match.
// This allows for flexibility in not requiring that every last
// handler provide a `serialize` method
newHandlerInfo.params = oldHandlerInfo && oldHandlerInfo.params;
}
newHandlerInfo.context = oldContext;
}
var handlerToUse = oldHandlerInfo;
if (i >= invalidateIndex || newHandlerInfo.shouldSupersede(oldHandlerInfo)) {
invalidateIndex = Math.min(i, invalidateIndex);
handlerToUse = newHandlerInfo;
}
if (isIntermediate && !checkingIfActive) {
handlerToUse = handlerToUse.becomeResolved(null, handlerToUse.context);
}
newState.routeInfos.unshift(handlerToUse);
}
if (objects.length > 0) {
throw new Error('More context objects were passed than there are dynamic segments for the route: ' + targetRouteName);
}
if (!isIntermediate) {
this.invalidateChildren(newState.routeInfos, invalidateIndex);
}
merge(newState.queryParams, this.queryParams || {});
if (isIntermediate && oldState.queryParams) {
merge(newState.queryParams, oldState.queryParams);
}
return newState;
}
invalidateChildren(handlerInfos, invalidateIndex) {
for (var i = invalidateIndex, l = handlerInfos.length; i < l; ++i) {
var handlerInfo = handlerInfos[i];
if (handlerInfo.isResolved) {
var {
name,
params,
route,
paramNames
} = handlerInfos[i];
handlerInfos[i] = new UnresolvedRouteInfoByParam(this.router, name, paramNames, params, route);
}
}
}
getHandlerInfoForDynamicSegment(name, names, objects, oldHandlerInfo, _targetRouteName, i) {
var objectToUse;
if (objects.length > 0) {
// Use the objects provided for this transition.
objectToUse = objects[objects.length - 1];
if (isParam(objectToUse)) {
return this.createParamHandlerInfo(name, names, objects, oldHandlerInfo);
} else {
objects.pop();
}
} else if (oldHandlerInfo && oldHandlerInfo.name === name) {
// Reuse the matching oldHandlerInfo
return oldHandlerInfo;
} else {
if (this.preTransitionState) {
var preTransitionHandlerInfo = this.preTransitionState.routeInfos[i];
objectToUse = preTransitionHandlerInfo && preTransitionHandlerInfo.context;
} else {
// Ideally we should throw this error to provide maximal
// information to the user that not enough context objects
// were provided, but this proves too cumbersome in Ember
// in cases where inner template helpers are evaluated
// before parent helpers un-render, in which cases this
// error somewhat prematurely fires.
//throw new Error("Not enough context objects were provided to complete a transition to " + targetRouteName + ". Specifically, the " + name + " route needs an object that can be serialized into its dynamic URL segments [" + names.join(', ') + "]");
return oldHandlerInfo;
}
}
return new UnresolvedRouteInfoByObject(this.router, name, names, objectToUse);
}
createParamHandlerInfo(name, names, objects, oldHandlerInfo) {
var params = {}; // Soak up all the provided string/numbers
var numNames = names.length;
var missingParams = [];
while (numNames--) {
// Only use old params if the names match with the new handler
var oldParams = oldHandlerInfo && name === oldHandlerInfo.name && oldHandlerInfo.params || {};
var peek = objects[objects.length - 1];
var paramName = names[numNames];
if (isParam(peek)) {
params[paramName] = '' + objects.pop();
} else {
// If we're here, this means only some of the params
// were string/number params, so try and use a param
// value from a previous handler.
if (oldParams.hasOwnProperty(paramName)) {
params[paramName] = oldParams[paramName];
} else {
missingParams.push(paramName);
}
}
}
if (missingParams.length > 0) {
throw new Error(`You didn't provide enough string/numeric parameters to satisfy all of the dynamic segments for route ${name}.` + ` Missing params: ${missingParams}`);
}
return new UnresolvedRouteInfoByParam(this.router, name, names, params);
}
}
var UnrecognizedURLError = function () {
UnrecognizedURLError.prototype = Object.create(Error.prototype);
UnrecognizedURLError.prototype.constructor = UnrecognizedURLError;
function UnrecognizedURLError(message) {
var error = Error.call(this, message);
this.name = 'UnrecognizedURLError';
this.message = message || 'UnrecognizedURL';
if (Error.captureStackTrace) {
Error.captureStackTrace(this, UnrecognizedURLError);
} else {
this.stack = error.stack;
}
}
return UnrecognizedURLError;
}();
class URLTransitionIntent extends TransitionIntent {
constructor(router, url, data) {
super(router, data);
this.url = url;
this.preTransitionState = undefined;
}
applyToState(oldState) {
var newState = new TransitionState();
var results = this.router.recognizer.recognize(this.url),
i,
len;
if (!results) {
throw new UnrecognizedURLError(this.url);
}
var statesDiffer = false;
var _url = this.url; // Checks if a handler is accessible by URL. If it is not, an error is thrown.
// For the case where the handler is loaded asynchronously, the error will be
// thrown once it is loaded.
function checkHandlerAccessibility(handler) {
if (handler && handler.inaccessibleByURL) {
throw new UnrecognizedURLError(_url);
}
return handler;
}
for (i = 0, len = results.length; i < len; ++i) {
var result = results[i];
var name = result.handler;
var paramNames = [];
if (this.router.recognizer.hasRoute(name)) {
paramNames = this.router.recognizer.handlersFor(name)[i].names;
}
var newRouteInfo = new UnresolvedRouteInfoByParam(this.router, name, paramNames, result.params);
var route = newRouteInfo.route;
if (route) {
checkHandlerAccessibility(route);
} else {
// If the handler is being loaded asynchronously, check if we can
// access it after it has resolved
newRouteInfo.routePromise = newRouteInfo.routePromise.then(checkHandlerAccessibility);
}
var oldRouteInfo = oldState.routeInfos[i];
if (statesDiffer || newRouteInfo.shouldSupersede(oldRouteInfo)) {
statesDiffer = true;
newState.routeInfos[i] = newRouteInfo;
} else {
newState.routeInfos[i] = oldRouteInfo;
}
}
merge(newState.queryParams, results.queryParams);
return newState;
}
}
class Router {
constructor(logger) {
this._lastQueryParams = {};
this.state = undefined;
this.oldState = undefined;
this.activeTransition = undefined;
this.currentRouteInfos = undefined;
this._changedQueryParams = undefined;
this.currentSequence = 0;
this.log = logger;
this.recognizer = new _routeRecognizer.default();
this.reset();
}
/**
The main entry point into the router. The API is essentially
the same as the `map` method in `route-recognizer`.
This method extracts the String handler at the last `.to()`
call and uses it as the name of the whole route.
@param {Function} callback
*/
map(callback) {
this.recognizer.map(callback, function (recognizer, routes) {
for (var i = routes.length - 1, _proceed = true; i >= 0 && _proceed; --i) {
var route = routes[i];
var handler = route.handler;
recognizer.add(routes, {
as: handler
});
_proceed = route.path === '/' || route.path === '' || handler.slice(-6) === '.index';
}
});
}
hasRoute(route) {
return this.recognizer.hasRoute(route);
}
queryParamsTransition(changelist, wasTransitioning, oldState, newState) {
this.fireQueryParamDidChange(newState, changelist);
if (!wasTransitioning && this.activeTransition) {
// One of the routes in queryParamsDidChange
// caused a transition. Just return that transition.
return this.activeTransition;
} else {
// Running queryParamsDidChange didn't change anything.
// Just update query params and be on our way.
// We have to return a noop transition that will
// perform a URL update at the end. This gives
// the user the ability to set the url update
// method (default is replaceState).
var newTransition = new Transition(this, undefined, undefined);
newTransition.queryParamsOnly = true;
oldState.queryParams = this.finalizeQueryParamChange(newState.routeInfos, newState.queryParams, newTransition);
newTransition[QUERY_PARAMS_SYMBOL] = newState.queryParams;
this.toReadOnlyInfos(newTransition, newState);
this.routeWillChange(newTransition);
newTransition.promise = newTransition.promise.then(result => {
if (!newTransition.isAborted) {
this._updateURL(newTransition, oldState);
this.didTransition(this.currentRouteInfos);
this.toInfos(newTransition, newState.routeInfos, true);
this.routeDidChange(newTransition);
}
return result;
}, null, promiseLabel('Transition complete'));
return newTransition;
}
}
transitionByIntent(intent, isIntermediate) {
try {
return this.getTransitionByIntent(intent, isIntermediate);
} catch (e) {
return new Transition(this, intent, undefined, e, undefined);
}
}
recognize(url) {
var intent = new URLTransitionIntent(this, url);
var newState = this.generateNewState(intent);
if (newState === null) {
return newState;
}
var readonlyInfos = toReadOnlyRouteInfo(newState.routeInfos, newState.queryParams);
return readonlyInfos[readonlyInfos.length - 1];
}
recognizeAndLoad(url) {
var intent = new URLTransitionIntent(this, url);
var newState = this.generateNewState(intent);
if (newState === null) {
return _rsvp.Promise.reject(`URL ${url} was not recognized`);
}
var newTransition = new Transition(this, intent, newState, undefined);
return newTransition.then(() => {
var routeInfosWithAttributes = toReadOnlyRouteInfo(newState.routeInfos, newTransition[QUERY_PARAMS_SYMBOL], true);
return routeInfosWithAttributes[routeInfosWithAttributes.length - 1];
});
}
generateNewState(intent) {
try {
return intent.applyToState(this.state, false);
} catch (e) {
return null;
}
}
getTransitionByIntent(intent, isIntermediate) {
var wasTransitioning = !!this.activeTransition;
var oldState = wasTransitioning ? this.activeTransition[STATE_SYMBOL] : this.state;
var newTransition;
var newState = intent.applyToState(oldState, isIntermediate);
var queryParamChangelist = getChangelist(oldState.queryParams, newState.queryParams);
if (routeInfosEqual(newState.routeInfos, oldState.routeInfos)) {
// This is a no-op transition. See if query params changed.
if (queryParamChangelist) {
var _newTransition = this.queryParamsTransition(queryParamChangelist, wasTransitioning, oldState, newState);
_newTransition.queryParamsOnly = true;
return _newTransition;
} // No-op. No need to create a new transition.
return this.activeTransition || new Transition(this, undefined, undefined);
}
if (isIntermediate) {
var transition = new Transition(this, undefined, newState);
transition.isIntermediate = true;
this.toReadOnlyInfos(transition, newState);
this.setupContexts(newState, transition);
this.routeWillChange(transition);
return this.activeTransition;
} // Create a new transition to the destination route.
newTransition = new Transition(this, intent, newState, undefined, this.activeTransition); // transition is to same route with same params, only query params differ.
// not caught above probably because refresh() has been used
if (routeInfosSameExceptQueryParams(newState.routeInfos, oldState.routeInfos)) {
newTransition.queryParamsOnly = true;
}
this.toReadOnlyInfos(newTransition, newState); // Abort and usurp any previously active transition.
if (this.activeTransition) {
this.activeTransition.redirect(newTransition);
}
this.activeTransition = newTransition; // Transition promises by default resolve with resolved state.
// For our purposes, swap out the promise to resolve
// after the transition has been finalized.
newTransition.promise = newTransition.promise.then(result => {
return this.finalizeTransition(newTransition, result);
}, null, promiseLabel('Settle transition promise when transition is finalized'));
if (!wasTransitioning) {
this.notifyExistingHandlers(newState, newTransition);
}
this.fireQueryParamDidChange(newState, queryParamChangelist);
return newTransition;
}
/**
@private
Begins and returns a Transition based on the provided
arguments. Accepts arguments in the form of both URL
transitions and named transitions.
@param {Router} router
@param {Array[Object]} args arguments passed to transitionTo,
replaceWith, or handleURL
*/
doTransition(name, modelsArray = [], isIntermediate = false) {
var lastArg = modelsArray[modelsArray.length - 1];
var queryParams = {};
if (lastArg !== undefined && lastArg.hasOwnProperty('queryParams')) {
queryParams = modelsArray.pop().queryParams;
}
var intent;
if (name === undefined) {
log(this, 'Updating query params'); // A query param update is really just a transition
// into the route you're already on.
var {
routeInfos
} = this.state;
intent = new NamedTransitionIntent(this, routeInfos[routeInfos.length - 1].name, undefined, [], queryParams);
} else if (name.charAt(0) === '/') {
log(this, 'Attempting URL transition to ' + name);
intent = new URLTransitionIntent(this, name);
} else {
log(this, 'Attempting transition to ' + name);
intent = new NamedTransitionIntent(this, name, undefined, modelsArray, queryParams);
}
return this.transitionByIntent(intent, isIntermediate);
}
/**
@private
Updates the URL (if necessary) and calls `setupContexts`
to update the router's array of `currentRouteInfos`.
*/
finalizeTransition(transition, newState) {
try {
log(transition.router, transition.sequence, 'Resolved all models on destination route; finalizing transition.');
var routeInfos = newState.routeInfos; // Run all the necessary enter/setup/exit hooks
this.setupContexts(newState, transition); // Check if a redirect occurred in enter/setup
if (transition.isAborted) {
// TODO: cleaner way? distinguish b/w targetRouteInfos?
this.state.routeInfos = this.currentRouteInfos;
return _rsvp.Promise.reject(logAbort(transition));
}
this._updateURL(transition, newState);
transition.isActive = false;
this.activeTransition = undefined;
this.triggerEvent(this.currentRouteInfos, true, 'didTransition', []);
this.didTransition(this.currentRouteInfos);
this.toInfos(transition, newState.routeInfos, true);
this.routeDidChange(transition);
log(this, transition.sequence, 'TRANSITION COMPLETE.'); // Resolve with the final route.
return routeInfos[routeInfos.length - 1].route;
} catch (e) {
if (!isTransitionAborted(e)) {
var infos = transition[STATE_SYMBOL].routeInfos;
transition.trigger(true, 'error', e, transition, infos[infos.length - 1].route);
transition.abort();
}
throw e;
}
}
/**
@private
Takes an Array of `RouteInfo`s, figures out which ones are
exiting, entering, or changing contexts, and calls the
proper route hooks.
For example, consider the following tree of routes. Each route is
followed by the URL segment it handles.
```
|~index ("/")
| |~posts ("/posts")
| | |-showPost ("/:id")
| | |-newPost ("/new")
| | |-editPost ("/edit")
| |~about ("/about/:id")
```
Consider the following transitions:
1. A URL transition to `/posts/1`.
1. Triggers the `*model` callbacks on the
`index`, `posts`, and `showPost` routes
2. Triggers the `enter` callback on the same
3. Triggers the `setup` callback on the same
2. A direct transition to `newPost`
1. Triggers the `exit` callback on `showPost`
2. Triggers the `enter` callback on `newPost`
3. Triggers the `setup` callback on `newPost`
3. A direct transition to `about` with a specified
context object
1. Triggers the `exit` callback on `newPost`
and `posts`
2. Triggers the `serialize` callback on `about`
3. Triggers the `enter` callback on `about`
4. Triggers the `setup` callback on `about`
@param {Router} transition
@param {TransitionState} newState
*/
setupContexts(newState, transition) {
var partition = this.partitionRoutes(this.state, newState);
var i, l, route;
for (i = 0, l = partition.exited.length; i < l; i++) {
route = partition.exited[i].route;
delete route.context;
if (route !== undefined) {
if (route._internalReset !== undefined) {
route._internalReset(true, transition);
}
if (route.exit !== undefined) {
route.exit(transition);
}
}
}
var oldState = this.oldState = this.state;
this.state = newState;
var currentRouteInfos = this.currentRouteInfos = partition.unchanged.slice();
try {
for (i = 0, l = partition.reset.length; i < l; i++) {
route = partition.reset[i].route;
if (route !== undefined) {
if (route._internalReset !== undefined) {
route._internalReset(false, transition);
}
}
}
for (i = 0, l = partition.updatedContext.length; i < l; i++) {
this.routeEnteredOrUpdated(currentRouteInfos, partition.updatedContext[i], false, transition);
}
for (i = 0, l = partition.entered.length; i < l; i++) {
this.routeEnteredOrUpdated(currentRouteInfos, partition.entered[i], true, transition);
}
} catch (e) {
this.state = oldState;
this.currentRouteInfos = oldState.routeInfos;
throw e;
}
this.state.queryParams = this.finalizeQueryParamChange(currentRouteInfos, newState.queryParams, transition);
}
/**
@private
Fires queryParamsDidChange event
*/
fireQueryParamDidChange(newState, queryParamChangelist) {
// If queryParams changed trigger event
if (queryParamChangelist) {
// This is a little hacky but we need some way of storing
// changed query params given that no activeTransition
// is guaranteed to have occurred.
this._changedQueryParams = queryParamChangelist.all;
this.triggerEvent(newState.routeInfos, true, 'queryParamsDidChange', [queryParamChangelist.changed, queryParamChangelist.all, queryParamChangelist.removed]);
this._changedQueryParams = undefined;
}
}
/**
@private
Helper method used by setupContexts. Handles errors or redirects
that may happen in enter/setup.
*/
routeEnteredOrUpdated(currentRouteInfos, routeInfo, enter, transition) {
var route = routeInfo.route,
context = routeInfo.context;
function _routeEnteredOrUpdated(route) {
if (enter) {
if (route.enter !== undefined) {
route.enter(transition);
}
}
throwIfAborted(transition);
route.context = context;
if (route.contextDidChange !== undefined) {
route.contextDidChange();
}
if (route.setup !== undefined) {
route.setup(context, transition);
}
throwIfAborted(transition);
currentRouteInfos.push(routeInfo);
return route;
} // If the route doesn't exist, it means we haven't resolved the route promise yet
if (route === undefined) {
routeInfo.routePromise = routeInfo.routePromise.then(_routeEnteredOrUpdated);
} else {
_routeEnteredOrUpdated(route);
}
return true;
}
/**
@private
This function is called when transitioning from one URL to
another to determine which routes are no longer active,
which routes are newly active, and which routes remain
active but have their context changed.
Take a list of old routes and new routes and partition
them into four buckets:
* unchanged: the route was active in both the old and
new URL, and its context remains the same
* updated context: the route was active in both the
old and new URL, but its context changed. The route's
`setup` method, if any, will be called with the new
context.
* exited: the route was active in the old URL, but is
no longer active.
* entered: the route was not active in the old URL, but
is now active.
The PartitionedRoutes structure has four fields:
* `updatedContext`: a list of `RouteInfo` objects that
represent routes that remain active but have a changed
context
* `entered`: a list of `RouteInfo` objects that represent
routes that are newly active
* `exited`: a list of `RouteInfo` objects that are no
longer active.
* `unchanged`: a list of `RouteInfo` objects that remain active.
@param {Array[InternalRouteInfo]} oldRoutes a list of the route
information for the previous URL (or `[]` if this is the
first handled transition)
@param {Array[InternalRouteInfo]} newRoutes a list of the route
information for the new URL
@return {Partition}
*/
partitionRoutes(oldState, newState) {
var oldRouteInfos = oldState.routeInfos;
var newRouteInfos = newState.routeInfos;
var routes = {
updatedContext: [],
exited: [],
entered: [],
unchanged: [],
reset: []
};
var routeChanged,
contextChanged = false,
i,
l;
for (i = 0, l = newRouteInfos.length; i < l; i++) {
var oldRouteInfo = oldRouteInfos[i],
newRouteInfo = newRouteInfos[i];
if (!oldRouteInfo || oldRouteInfo.route !== newRouteInfo.route) {
routeChanged = true;
}
if (routeChanged) {
routes.entered.push(newRouteInfo);
if (oldRouteInfo) {
routes.exited.unshift(oldRouteInfo);
}
} else if (contextChanged || oldRouteInfo.context !== newRouteInfo.context) {
contextChanged = true;
routes.updatedContext.push(newRouteInfo);
} else {
routes.unchanged.push(oldRouteInfo);
}
}
for (i = newRouteInfos.length, l = oldRouteInfos.length; i < l; i++) {
routes.exited.unshift(oldRouteInfos[i]);
}
routes.reset = routes.updatedContext.slice();
routes.reset.reverse();
return routes;
}
_updateURL(transition, state) {
var urlMethod = transition.urlMethod;
if (!urlMethod) {
return;
}
var {
routeInfos
} = state;
var {
name: routeName
} = routeInfos[routeInfos.length - 1];
var params = {};
for (var i = routeInfos.length - 1; i >= 0; --i) {
var routeInfo = routeInfos[i];
merge(params, routeInfo.params);
if (routeInfo.route.inaccessibleByURL) {
urlMethod = null;
}
}
if (urlMethod) {
params.queryParams = transition._visibleQueryParams || state.queryParams;
var url = this.recognizer.generate(routeName, params); // transitions during the initial transition must always use replaceURL.
// When the app boots, you are at a url, e.g. /foo. If some route
// redirects to bar as part of the initial transition, you don't want to
// add a history entry for /foo. If you do, pressing back will immediately
// hit the redirect again and take you back to /bar, thus killing the back
// button
var initial = transition.isCausedByInitialTransition; // say you are at / and you click a link to route /foo. In /foo's
// route, the transition is aborted using replaceWith('/bar').
// Because the current url is still /, the history entry for / is
// removed from the history. Clicking back will take you to the page
// you were on before /, which is often not even the app, thus killing
// the back button. That's why updateURL is always correct for an
// aborting transition that's not the initial transition
var replaceAndNotAborting = urlMethod === 'replace' && !transition.isCausedByAbortingTransition; // because calling refresh causes an aborted transition, this needs to be
// special cased - if the initial transition is a replace transition, the
// urlMethod should be honored here.
var isQueryParamsRefreshTransition = transition.queryParamsOnly && urlMethod === 'replace'; // say you are at / and you a `replaceWith(/foo)` is called. Then, that
// transition is aborted with `replaceWith(/bar)`. At the end, we should
// end up with /bar replacing /. We are replacing the replace. We only
// will replace the initial route if all subsequent aborts are also
// replaces. However, there is some ambiguity around the correct behavior
// here.
var replacingReplace = urlMethod === 'replace' && transition.isCausedByAbortingReplaceTransition;
if (initial || replaceAndNotAborting || isQueryParamsRefreshTransition || replacingReplace) {
this.replaceURL(url);
} else {
this.updateURL(url);
}
}
}
finalizeQueryParamChange(resolvedHandlers, newQueryParams, transition) {
// We fire a finalizeQueryParamChange event which
// gives the new route hierarchy a chance to tell
// us which query params it's consuming and what
// their final values are. If a query param is
// no longer consumed in the final route hierarchy,
// its serialized segment will be removed
// from the URL.
for (var k in newQueryParams) {
if (newQueryParams.hasOwnProperty(k) && newQueryParams[k] === null) {
delete newQueryParams[k];
}
}
var finalQueryParamsArray = [];
this.triggerEvent(resolvedHandlers, true, 'finalizeQueryParamChange', [newQueryParams, finalQueryParamsArray, transition]);
if (transition) {
transition._visibleQueryParams = {};
}
var finalQueryParams = {};
for (var i = 0, len = finalQueryParamsArray.length; i < len; ++i) {
var qp = finalQueryParamsArray[i];
finalQueryParams[qp.key] = qp.value;
if (transition && qp.visible !== false) {
transition._visibleQueryParams[qp.key] = qp.value;
}
}
return finalQueryParams;
}
toReadOnlyInfos(newTransition, newState) {
var oldRouteInfos = this.state.routeInfos;
this.fromInfos(newTransition, oldRouteInfos);
this.toInfos(newTransition, newState.routeInfos);
this._lastQueryParams = newState.queryParams;
}
fromInfos(newTransition, oldRouteInfos) {
if (newTransition !== undefined && oldRouteInfos.length > 0) {
var fromInfos = toReadOnlyRouteInfo(oldRouteInfos, Object.assign({}, this._lastQueryParams), true);
newTransition.from = fromInfos[fromInfos.length - 1] || null;
}
}
toInfos(newTransition, newRouteInfos, includeAttributes = false) {
if (newTransition !== undefined && newRouteInfos.length > 0) {
var toInfos = toReadOnlyRouteInfo(newRouteInfos, Object.assign({}, newTransition[QUERY_PARAMS_SYMBOL]), includeAttributes);
newTransition.to = toInfos[toInfos.length - 1] || null;
}
}
notifyExistingHandlers(newState, newTransition) {
var oldRouteInfos = this.state.routeInfos,
i,
oldRouteInfoLen,
oldHandler,
newRouteInfo;
oldRouteInfoLen = oldRouteInfos.length;
for (i = 0; i < oldRouteInfoLen; i++) {
oldHandler = oldRouteInfos[i];
newRouteInfo = newState.routeInfos[i];
if (!newRouteInfo || oldHandler.name !== newRouteInfo.name) {
break;
}
if (!newRouteInfo.isResolved) {}
}
this.triggerEvent(oldRouteInfos, true, 'willTransition', [newTransition]);
this.routeWillChange(newTransition);
this.willTransition(oldRouteInfos, newState.routeInfos, newTransition);
}
/**
Clears the current and target route routes and triggers exit
on each of them starting at the leaf and traversing up through
its ancestors.
*/
reset() {
if (this.state) {
forEach(this.state.routeInfos.slice().reverse(), function (routeInfo) {
var route = routeInfo.route;
if (route !== undefined) {
if (route.exit !== undefined) {
route.exit();
}
}
return true;
});
}
this.oldState = undefined;
this.state = new TransitionState();
this.currentRouteInfos = undefined;
}
/**
let handler = routeInfo.handler;
The entry point for handling a change to the URL (usually
via the back and forward button).
Returns an Array of handlers and the parameters associated
with those parameters.
@param {String} url a URL to process
@return {Array} an Array of `[handler, parameter]` tuples
*/
handleURL(url) {
// Perform a URL-based transition, but don't change
// the URL afterward, since it already happened.
if (url.charAt(0) !== '/') {
url = '/' + url;
}
return this.doTransition(url).method(null);
}
/**
Transition into the specified named route.
If necessary, trigger the exit callback on any routes
that are no longer represented by the target route.
@param {String} name the name of the route
*/
transitionTo(name, ...contexts) {
if (typeof name === 'object') {
contexts.push(name);
return this.doTransition(undefined, contexts, false);
}
return this.doTransition(name, contexts);
}
intermediateTransitionTo(name, ...args) {
return this.doTransition(name, args, true);
}
refresh(pivotRoute) {
var previousTransition = this.activeTransition;
var state = previousTransition ? previousTransition[STATE_SYMBOL] : this.state;
var routeInfos = state.routeInfos;
if (pivotRoute === undefined) {
pivotRoute = routeInfos[0].route;
}
log(this, 'Starting a refresh transition');
var name = routeInfos[routeInfos.length - 1].name;
var intent = new NamedTransitionIntent(this, name, pivotRoute, [], this._changedQueryParams || state.queryParams);
var newTransition = this.transitionByIntent(intent, false); // if the previous transition is a replace transition, that needs to be preserved
if (previousTransition && previousTransition.urlMethod === 'replace') {
newTransition.method(previousTransition.urlMethod);
}
return newTransition;
}
/**
Identical to `transitionTo` except that the current URL will be replaced
if possible.
This method is intended primarily for use with `replaceState`.
@param {String} name the name of the route
*/
replaceWith(name) {
return this.doTransition(name).method('replace');
}
/**
Take a named route and context objects and generate a
URL.
@param {String} name the name of the route to generate
a URL for
@param {...Object} objects a list of objects to serialize
@return {String} a URL
*/
generate(routeName, ...args) {
var partitionedArgs = extractQueryParams(args),
suppliedParams = partitionedArgs[0],
queryParams = partitionedArgs[1]; // Construct a TransitionIntent with the provided params
// and apply it to the present state of the router.
var intent = new NamedTransitionIntent(this, routeName, undefined, suppliedParams);
var state = intent.applyToState(this.state, false);
var params = {};
for (var i = 0, len = state.routeInfos.length; i < len; ++i) {
var routeInfo = state.routeInfos[i];
var routeParams = routeInfo.serialize();
merge(params, routeParams);
}
params.queryParams = queryParams;
return this.recognizer.generate(routeName, params);
}
applyIntent(routeName, contexts) {
var intent = new NamedTransitionIntent(this, routeName, undefined, contexts);
var state = this.activeTransition && this.activeTransition[STATE_SYMBOL] || this.state;
return intent.applyToState(state, false);
}
isActiveIntent(routeName, contexts, queryParams, _state) {
var state = _state || this.state,
targetRouteInfos = state.routeInfos,
routeInfo,
len;
if (!targetRouteInfos.length) {
return false;
}
var targetHandler = targetRouteInfos[targetRouteInfos.length - 1].name;
var recognizerHandlers = this.recognizer.handlersFor(targetHandler);
var index = 0;
for (len = recognizerHandlers.length; index < len; ++index) {
routeInfo = targetRouteInfos[index];
if (routeInfo.name === routeName) {
break;
}
}
if (index === recognizerHandlers.length) {
// The provided route name isn't even in the route hierarchy.
return false;
}
var testState = new TransitionState();
testState.routeInfos = targetRouteInfos.slice(0, index + 1);
recognizerHandlers = recognizerHandlers.slice(0, index + 1);
var intent = new NamedTransitionIntent(this, targetHandler, undefined, contexts);
var newState = intent.applyToHandlers(testState, recognizerHandlers, targetHandler, true, true);
var routesEqual = routeInfosEqual(newState.routeInfos, testState.routeInfos);
if (!queryParams || !routesEqual) {
return routesEqual;
} // Get a hash of QPs that will still be active on new route
var activeQPsOnNewHandler = {};
merge(activeQPsOnNewHandler, queryParams);
var activeQueryParams = state.queryParams;
for (var key in activeQueryParams) {
if (activeQueryParams.hasOwnProperty(key) && activeQPsOnNewHandler.hasOwnProperty(key)) {
activeQPsOnNewHandler[key] = activeQueryParams[key];
}
}
return routesEqual && !getChangelist(activeQPsOnNewHandler, queryParams);
}
isActive(routeName, ...args) {
var partitionedArgs = extractQueryParams(args);
return this.isActiveIntent(routeName, partitionedArgs[0], partitionedArgs[1]);
}
trigger(name, ...args) {
this.triggerEvent(this.currentRouteInfos, false, name, args);
}
}
function routeInfosEqual(routeInfos, otherRouteInfos) {
if (routeInfos.length !== otherRouteInfos.length) {
return false;
}
for (var i = 0, len = routeInfos.length; i < len; ++i) {
if (routeInfos[i] !== otherRouteInfos[i]) {
return false;
}
}
return true;
}
function routeInfosSameExceptQueryParams(routeInfos, otherRouteInfos) {
if (routeInfos.length !== otherRouteInfos.length) {
return false;
}
for (var i = 0, len = routeInfos.length; i < len; ++i) {
if (routeInfos[i].name !== otherRouteInfos[i].name) {
return false;
}
if (!paramsEqual(routeInfos[i].params, otherRouteInfos[i].params)) {
return false;
}
}
return true;
}
function paramsEqual(params, otherParams) {
if (!params && !otherParams) {
return true;
} else if (!params && !!otherParams || !!params && !otherParams) {
// one is falsy but other is not;
return false;
}
var keys = Object.keys(params);
var otherKeys = Object.keys(otherParams);
if (keys.length !== otherKeys.length) {
return false;
}
for (var i = 0, len = keys.length; i < len; ++i) {
var key = keys[i];
if (params[key] !== otherParams[key]) {
return false;
}
}
return true;
}
var _default = Router;
_exports.default = _default;
});
define("rsvp", ["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.asap = asap;
_exports.all = all$1;
_exports.allSettled = allSettled;
_exports.race = race$1;
_exports.hash = hash;
_exports.hashSettled = hashSettled;
_exports.rethrow = rethrow;
_exports.defer = defer;
_exports.denodeify = denodeify;
_exports.configure = configure;
_exports.on = on;
_exports.off = off;
_exports.resolve = resolve$2;
_exports.reject = reject$2;
_exports.map = map;
_exports.filter = filter;
_exports.async = _exports.EventTarget = _exports.Promise = _exports.cast = _exports.default = void 0;
function callbacksFor(object) {
var callbacks = object._promiseCallbacks;
if (!callbacks) {
callbacks = object._promiseCallbacks = {};
}
return callbacks;
}
/**
@class EventTarget
@for rsvp
@public
*/
var EventTarget = {
/**
`EventTarget.mixin` extends an object with EventTarget methods. For
Example:
```javascript
import EventTarget from 'rsvp';
let object = {};
EventTarget.mixin(object);
object.on('finished', function(event) {
// handle event
});
object.trigger('finished', { detail: value });
```
`EventTarget.mixin` also works with prototypes:
```javascript
import EventTarget from 'rsvp';
let Person = function() {};
EventTarget.mixin(Person.prototype);
let yehuda = new Person();
let tom = new Person();
yehuda.on('poke', function(event) {
console.log('Yehuda says OW');
});
tom.on('poke', function(event) {
console.log('Tom says OW');
});
yehuda.trigger('poke');
tom.trigger('poke');
```
@method mixin
@for rsvp
@private
@param {Object} object object to extend with EventTarget methods
*/
mixin(object) {
object.on = this.on;
object.off = this.off;
object.trigger = this.trigger;
object._promiseCallbacks = undefined;
return object;
},
/**
Registers a callback to be executed when `eventName` is triggered
```javascript
object.on('event', function(eventInfo){
// handle the event
});
object.trigger('event');
```
@method on
@for EventTarget
@private
@param {String} eventName name of the event to listen for
@param {Function} callback function to be called when the event is triggered.
*/
on(eventName, callback) {
if (typeof callback !== 'function') {
throw new TypeError('Callback must be a function');
}
var allCallbacks = callbacksFor(this);
var callbacks = allCallbacks[eventName];
if (!callbacks) {
callbacks = allCallbacks[eventName] = [];
}
if (callbacks.indexOf(callback) === -1) {
callbacks.push(callback);
}
},
/**
You can use `off` to stop firing a particular callback for an event:
```javascript
function doStuff() { // do stuff! }
object.on('stuff', doStuff);
object.trigger('stuff'); // doStuff will be called
// Unregister ONLY the doStuff callback
object.off('stuff', doStuff);
object.trigger('stuff'); // doStuff will NOT be called
```
If you don't pass a `callback` argument to `off`, ALL callbacks for the
event will not be executed when the event fires. For example:
```javascript
let callback1 = function(){};
let callback2 = function(){};
object.on('stuff', callback1);
object.on('stuff', callback2);
object.trigger('stuff'); // callback1 and callback2 will be executed.
object.off('stuff');
object.trigger('stuff'); // callback1 and callback2 will not be executed!
```
@method off
@for rsvp
@private
@param {String} eventName event to stop listening to
@param {Function} [callback] optional argument. If given, only the function
given will be removed from the event's callback queue. If no `callback`
argument is given, all callbacks will be removed from the event's callback
queue.
*/
off(eventName, callback) {
var allCallbacks = callbacksFor(this);
if (!callback) {
allCallbacks[eventName] = [];
return;
}
var callbacks = allCallbacks[eventName];
var index = callbacks.indexOf(callback);
if (index !== -1) {
callbacks.splice(index, 1);
}
},
/**
Use `trigger` to fire custom events. For example:
```javascript
object.on('foo', function(){
console.log('foo event happened!');
});
object.trigger('foo');
// 'foo event happened!' logged to the console
```
You can also pass a value as a second argument to `trigger` that will be
passed as an argument to all event listeners for the event:
```javascript
object.on('foo', function(value){
console.log(value.name);
});
object.trigger('foo', { name: 'bar' });
// 'bar' logged to the console
```
@method trigger
@for rsvp
@private
@param {String} eventName name of the event to be triggered
@param {*} [options] optional value to be passed to any event handlers for
the given `eventName`
*/
trigger(eventName, options, label) {
var allCallbacks = callbacksFor(this);
var callbacks = allCallbacks[eventName];
if (callbacks) {
// Don't cache the callbacks.length since it may grow
var callback;
for (var i = 0; i < callbacks.length; i++) {
callback = callbacks[i];
callback(options, label);
}
}
}
};
_exports.EventTarget = EventTarget;
var config = {
instrument: false
};
EventTarget['mixin'](config);
function configure(name, value) {
if (arguments.length === 2) {
config[name] = value;
} else {
return config[name];
}
}
var queue = [];
function scheduleFlush() {
setTimeout(() => {
for (var i = 0; i < queue.length; i++) {
var entry = queue[i];
var payload = entry.payload;
payload.guid = payload.key + payload.id;
payload.childGuid = payload.key + payload.childId;
if (payload.error) {
payload.stack = payload.error.stack;
}
config['trigger'](entry.name, entry.payload);
}
queue.length = 0;
}, 50);
}
function instrument(eventName, promise, child) {
if (1 === queue.push({
name: eventName,
payload: {
key: promise._guidKey,
id: promise._id,
eventName: eventName,
detail: promise._result,
childId: child && child._id,
label: promise._label,
timeStamp: Date.now(),
error: config["instrument-with-stack"] ? new Error(promise._label) : null
}
})) {
scheduleFlush();
}
}
/**
`Promise.resolve` returns a promise that will become resolved with the
passed `value`. It is shorthand for the following:
```javascript
import Promise from 'rsvp';
let promise = new Promise(function(resolve, reject){
resolve(1);
});
promise.then(function(value){
// value === 1
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
import Promise from 'rsvp';
let promise = RSVP.Promise.resolve(1);
promise.then(function(value){
// value === 1
});
```
@method resolve
@for Promise
@static
@param {*} object value that the returned promise will be resolved with
@param {String} [label] optional string for identifying the returned promise.
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
function resolve$$1(object, label) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(noop, label);
resolve$1(promise, object);
return promise;
}
function withOwnPromise() {
return new TypeError('A promises callback cannot return that same promise.');
}
function objectOrFunction(x) {
var type = typeof x;
return x !== null && (type === 'object' || type === 'function');
}
function noop() {}
var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;
function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
try {
then$$1.call(value, fulfillmentHandler, rejectionHandler);
} catch (e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then$$1) {
config.async(promise => {
var sealed = false;
var error = tryThen(then$$1, thenable, value => {
if (sealed) {
return;
}
sealed = true;
if (thenable === value) {
fulfill(promise, value);
} else {
resolve$1(promise, value);
}
}, reason => {
if (sealed) {
return;
}
sealed = true;
reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
thenable._onError = null;
reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, value => {
if (thenable === value) {
fulfill(promise, value);
} else {
resolve$1(promise, value);
}
}, reason => reject(promise, reason));
}
}
function handleMaybeThenable(promise, maybeThenable, then$$1) {
var isOwnThenable = maybeThenable.constructor === promise.constructor && then$$1 === then && promise.constructor.resolve === resolve$$1;
if (isOwnThenable) {
handleOwnThenable(promise, maybeThenable);
} else if (typeof then$$1 === 'function') {
handleForeignThenable(promise, maybeThenable, then$$1);
} else {
fulfill(promise, maybeThenable);
}
}
function resolve$1(promise, value) {
if (promise === value) {
fulfill(promise, value);
} else if (objectOrFunction(value)) {
var then$$1;
try {
then$$1 = value.then;
} catch (error) {
reject(promise, error);
return;
}
handleMaybeThenable(promise, value, then$$1);
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onError) {
promise._onError(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) {
return;
}
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length === 0) {
if (config.instrument) {
instrument('fulfilled', promise);
}
} else {
config.async(publish, promise);
}
}
function reject(promise, reason) {
if (promise._state !== PENDING) {
return;
}
promise._state = REJECTED;
promise._result = reason;
config.async(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length;
parent._onError = null;
subscribers[length] = child;
subscribers[length + FULFILLED] = onFulfillment;
subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
config.async(publish, parent);
}
}
function publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (config.instrument) {
instrument(settled === FULFILLED ? 'fulfilled' : 'rejected', promise);
}
if (subscribers.length === 0) {
return;
}
var child,
callback,
result = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, result);
} else {
callback(result);
}
}
promise._subscribers.length = 0;
}
function invokeCallback(state, promise, callback, result) {
var hasCallback = typeof callback === 'function';
var value,
succeeded = true,
error;
if (hasCallback) {
try {
value = callback(result);
} catch (e) {
succeeded = false;
error = e;
}
} else {
value = result;
}
if (promise._state !== PENDING) {// noop
} else if (value === promise) {
reject(promise, withOwnPromise());
} else if (succeeded === false) {
reject(promise, error);
} else if (hasCallback) {
resolve$1(promise, value);
} else if (state === FULFILLED) {
fulfill(promise, value);
} else if (state === REJECTED) {
reject(promise, value);
}
}
function initializePromise(promise, resolver) {
var resolved = false;
try {
resolver(value => {
if (resolved) {
return;
}
resolved = true;
resolve$1(promise, value);
}, reason => {
if (resolved) {
return;
}
resolved = true;
reject(promise, reason);
});
} catch (e) {
reject(promise, e);
}
}
function then(onFulfillment, onRejection, label) {
var parent = this;
var state = parent._state;
if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) {
config.instrument && instrument('chained', parent, parent);
return parent;
}
parent._onError = null;
var child = new parent.constructor(noop, label);
var result = parent._result;
config.instrument && instrument('chained', parent, child);
if (state === PENDING) {
subscribe(parent, child, onFulfillment, onRejection);
} else {
var callback = state === FULFILLED ? onFulfillment : onRejection;
config.async(() => invokeCallback(state, child, callback, result));
}
return child;
}
class Enumerator {
constructor(Constructor, input, abortOnReject, label) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop, label);
this._abortOnReject = abortOnReject;
this._isUsingOwnPromise = Constructor === Promise;
this._isUsingOwnResolve = Constructor.resolve === resolve$$1;
this._init(...arguments);
}
_init(Constructor, input) {
var len = input.length || 0;
this.length = len;
this._remaining = len;
this._result = new Array(len);
this._enumerate(input);
}
_enumerate(input) {
var length = this.length;
var promise = this.promise;
for (var i = 0; promise._state === PENDING && i < length; i++) {
this._eachEntry(input[i], i, true);
}
this._checkFullfillment();
}
_checkFullfillment() {
if (this._remaining === 0) {
var result = this._result;
fulfill(this.promise, result);
this._result = null;
}
}
_settleMaybeThenable(entry, i, firstPass) {
var c = this._instanceConstructor;
if (this._isUsingOwnResolve) {
var then$$1,
error,
succeeded = true;
try {
then$$1 = entry.then;
} catch (e) {
succeeded = false;
error = e;
}
if (then$$1 === then && entry._state !== PENDING) {
entry._onError = null;
this._settledAt(entry._state, i, entry._result, firstPass);
} else if (typeof then$$1 !== 'function') {
this._settledAt(FULFILLED, i, entry, firstPass);
} else if (this._isUsingOwnPromise) {
var promise = new c(noop);
if (succeeded === false) {
reject(promise, error);
} else {
handleMaybeThenable(promise, entry, then$$1);
this._willSettleAt(promise, i, firstPass);
}
} else {
this._willSettleAt(new c(resolve => resolve(entry)), i, firstPass);
}
} else {
this._willSettleAt(c.resolve(entry), i, firstPass);
}
}
_eachEntry(entry, i, firstPass) {
if (entry !== null && typeof entry === 'object') {
this._settleMaybeThenable(entry, i, firstPass);
} else {
this._setResultAt(FULFILLED, i, entry, firstPass);
}
}
_settledAt(state, i, value, firstPass) {
var promise = this.promise;
if (promise._state === PENDING) {
if (this._abortOnReject && state === REJECTED) {
reject(promise, value);
} else {
this._setResultAt(state, i, value, firstPass);
this._checkFullfillment();
}
}
}
_setResultAt(state, i, value, firstPass) {
this._remaining--;
this._result[i] = value;
}
_willSettleAt(promise, i, firstPass) {
subscribe(promise, undefined, value => this._settledAt(FULFILLED, i, value, firstPass), reason => this._settledAt(REJECTED, i, reason, firstPass));
}
}
function setSettledResult(state, i, value) {
this._remaining--;
if (state === FULFILLED) {
this._result[i] = {
state: 'fulfilled',
value: value
};
} else {
this._result[i] = {
state: 'rejected',
reason: value
};
}
}
/**
`Promise.all` accepts an array of promises, and returns a new promise which
is fulfilled with an array of fulfillment values for the passed promises, or
rejected with the reason of the first passed promise to be rejected. It casts all
elements of the passed iterable to promises as it runs this algorithm.
Example:
```javascript
import Promise, { resolve } from 'rsvp';
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `RSVP.all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
import Promise, { resolve, reject } from 'rsvp';
let promise1 = resolve(1);
let promise2 = reject(new Error("2"));
let promise3 = reject(new Error("3"));
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@for Promise
@param {Array} entries array of promises
@param {String} [label] optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
@static
*/
function all(entries, label) {
if (!Array.isArray(entries)) {
return this.reject(new TypeError("Promise.all must be called with an array"), label);
}
return new Enumerator(this, entries, true
/* abort on reject */
, label).promise;
}
/**
`Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
import Promise from 'rsvp';
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 2');
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// result === 'promise 2' because it was resolved before promise1
// was resolved.
});
```
`Promise.race` is deterministic in that only the state of the first
settled promise matters. For example, even if other promises given to the
`promises` array argument are resolved, but the first settled promise has
become rejected before the other promises became fulfilled, the returned
promise will become rejected:
```javascript
import Promise from 'rsvp';
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error('promise 2'));
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// Code here never runs
}, function(reason){
// reason.message === 'promise 2' because promise 2 became rejected before
// promise 1 became fulfilled
});
```
An example real-world use case is implementing timeouts:
```javascript
import Promise from 'rsvp';
Promise.race([ajax('foo.json'), timeout(5000)])
```
@method race
@for Promise
@static
@param {Array} entries array of promises to observe
@param {String} [label] optional string for describing the promise returned.
Useful for tooling.
@return {Promise} a promise which settles in the same way as the first passed
promise to settle.
*/
function race(entries, label) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(noop, label);
if (!Array.isArray(entries)) {
reject(promise, new TypeError('Promise.race must be called with an array'));
return promise;
}
for (var i = 0; promise._state === PENDING && i < entries.length; i++) {
subscribe(Constructor.resolve(entries[i]), undefined, value => resolve$1(promise, value), reason => reject(promise, reason));
}
return promise;
}
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
import Promise from 'rsvp';
let promise = new Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
import Promise from 'rsvp';
let promise = Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@for Promise
@static
@param {*} reason value that the returned promise will be rejected with.
@param {String} [label] optional string for identifying the returned promise.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
function reject$1(reason, label) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(noop, label);
reject(promise, reason);
return promise;
}
var guidKey = 'rsvp_' + Date.now() + '-';
var counter = 0;
function needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promises eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
let promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@public
@param {function} resolver
@param {String} [label] optional string for labeling the promise.
Useful for tooling.
@constructor
*/
class Promise {
constructor(resolver, label) {
this._id = counter++;
this._label = label;
this._state = undefined;
this._result = undefined;
this._subscribers = [];
config.instrument && instrument('created', this);
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise ? initializePromise(this, resolver) : needsNew();
}
}
_onError(reason) {
config.after(() => {
if (this._onError) {
config.trigger('error', reason, this._label);
}
});
}
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn\'t find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
@param {String} [label] optional string for labeling the promise.
Useful for tooling.
@return {Promise}
*/
catch(onRejection, label) {
return this.then(undefined, onRejection, label);
}
/**
`finally` will be invoked regardless of the promise's fate just as native
try/catch/finally behaves
Synchronous example:
```js
findAuthor() {
if (Math.random() > 0.5) {
throw new Error();
}
return new Author();
}
try {
return findAuthor(); // succeed or fail
} catch(error) {
return findOtherAuthor();
} finally {
// always runs
// doesn't affect the return value
}
```
Asynchronous example:
```js
findAuthor().catch(function(reason){
return findOtherAuthor();
}).finally(function(){
// author was either found, or not
});
```
@method finally
@param {Function} callback
@param {String} [label] optional string for labeling the promise.
Useful for tooling.
@return {Promise}
*/
finally(callback, label) {
var promise = this;
var constructor = promise.constructor;
if (typeof callback === 'function') {
return promise.then(value => constructor.resolve(callback()).then(() => value), reason => constructor.resolve(callback()).then(() => {
throw reason;
}));
}
return promise.then(callback, callback);
}
}
_exports.Promise = Promise;
Promise.cast = resolve$$1; // deprecated
Promise.all = all;
Promise.race = race;
Promise.resolve = resolve$$1;
Promise.reject = reject$1;
Promise.prototype._guidKey = guidKey;
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we\'re unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we\'re unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
let result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
let author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfillment
@param {Function} onRejection
@param {String} [label] optional string for labeling the promise.
Useful for tooling.
@return {Promise}
*/
Promise.prototype.then = then;
function makeObject(_, argumentNames) {
var obj = {};
var length = _.length;
var args = new Array(length);
for (var x = 0; x < length; x++) {
args[x] = _[x];
}
for (var i = 0; i < argumentNames.length; i++) {
var name = argumentNames[i];
obj[name] = args[i + 1];
}
return obj;
}
function arrayResult(_) {
var length = _.length;
var args = new Array(length - 1);
for (var i = 1; i < length; i++) {
args[i - 1] = _[i];
}
return args;
}
function wrapThenable(then, promise) {
return {
then(onFulFillment, onRejection) {
return then.call(promise, onFulFillment, onRejection);
}
};
}
/**
`denodeify` takes a 'node-style' function and returns a function that
will return an `Promise`. You can use `denodeify` in Node.js or the
browser when you'd prefer to use promises over using callbacks. For example,
`denodeify` transforms the following:
```javascript
let fs = require('fs');
fs.readFile('myfile.txt', function(err, data){
if (err) return handleError(err);
handleData(data);
});
```
into:
```javascript
let fs = require('fs');
let readFile = denodeify(fs.readFile);
readFile('myfile.txt').then(handleData, handleError);
```
If the node function has multiple success parameters, then `denodeify`
just returns the first one:
```javascript
let request = denodeify(require('request'));
request('http://example.com').then(function(res) {
// ...
});
```
However, if you need all success parameters, setting `denodeify`'s
second parameter to `true` causes it to return all success parameters
as an array:
```javascript
let request = denodeify(require('request'), true);
request('http://example.com').then(function(result) {
// result[0] -> res
// result[1] -> body
});
```
Or if you pass it an array with names it returns the parameters as a hash:
```javascript
let request = denodeify(require('request'), ['res', 'body']);
request('http://example.com').then(function(result) {
// result.res
// result.body
});
```
Sometimes you need to retain the `this`:
```javascript
let app = require('express')();
let render = denodeify(app.render.bind(app));
```
The denodified function inherits from the original function. It works in all
environments, except IE 10 and below. Consequently all properties of the original
function are available to you. However, any properties you change on the
denodeified function won't be changed on the original function. Example:
```javascript
let request = denodeify(require('request')),
cookieJar = request.jar(); // <- Inheritance is used here
request('http://example.com', {jar: cookieJar}).then(function(res) {
// cookieJar.cookies holds now the cookies returned by example.com
});
```
Using `denodeify` makes it easier to compose asynchronous operations instead
of using callbacks. For example, instead of:
```javascript
let fs = require('fs');
fs.readFile('myfile.txt', function(err, data){
if (err) { ... } // Handle error
fs.writeFile('myfile2.txt', data, function(err){
if (err) { ... } // Handle error
console.log('done')
});
});
```
you can chain the operations together using `then` from the returned promise:
```javascript
let fs = require('fs');
let readFile = denodeify(fs.readFile);
let writeFile = denodeify(fs.writeFile);
readFile('myfile.txt').then(function(data){
return writeFile('myfile2.txt', data);
}).then(function(){
console.log('done')
}).catch(function(error){
// Handle error
});
```
@method denodeify
@public
@static
@for rsvp
@param {Function} nodeFunc a 'node-style' function that takes a callback as
its last argument. The callback expects an error to be passed as its first
argument (if an error occurred, otherwise null), and the value from the
operation as its second argument ('function(err, value){ }').
@param {Boolean|Array} [options] An optional paramter that if set
to `true` causes the promise to fulfill with the callback's success arguments
as an array. This is useful if the node function has multiple success
paramters. If you set this paramter to an array with names, the promise will
fulfill with a hash with these names as keys and the success parameters as
values.
@return {Function} a function that wraps `nodeFunc` to return a `Promise`
*/
function denodeify(nodeFunc, options) {
var fn = function () {
var l = arguments.length;
var args = new Array(l + 1);
var promiseInput = false;
for (var i = 0; i < l; ++i) {
var arg = arguments[i]; // TODO: this code really needs to be cleaned up
if (!promiseInput) {
if (arg !== null && typeof arg === 'object') {
if (arg.constructor === Promise) {
promiseInput = true;
} else {
try {
promiseInput = arg.then;
} catch (error) {
var p = new Promise(noop);
reject(p, error);
return p;
}
}
} else {
promiseInput = false;
}
if (promiseInput && promiseInput !== true) {
arg = wrapThenable(promiseInput, arg);
}
}
args[i] = arg;
}
var promise = new Promise(noop);
args[l] = function (err, val) {
if (err) {
reject(promise, err);
} else if (options === undefined) {
resolve$1(promise, val);
} else if (options === true) {
resolve$1(promise, arrayResult(arguments));
} else if (Array.isArray(options)) {
resolve$1(promise, makeObject(arguments, options));
} else {
resolve$1(promise, val);
}
};
if (promiseInput) {
return handlePromiseInput(promise, args, nodeFunc, this);
} else {
return handleValueInput(promise, args, nodeFunc, this);
}
};
fn.__proto__ = nodeFunc;
return fn;
}
function handleValueInput(promise, args, nodeFunc, self) {
try {
nodeFunc.apply(self, args);
} catch (error) {
reject(promise, error);
}
return promise;
}
function handlePromiseInput(promise, args, nodeFunc, self) {
return Promise.all(args).then(args => handleValueInput(promise, args, nodeFunc, self));
}
/**
This is a convenient alias for `Promise.all`.
@method all
@public
@static
@for rsvp
@param {Array} array Array of promises.
@param {String} [label] An optional label. This is useful
for tooling.
*/
function all$1(array, label) {
return Promise.all(array, label);
}
/**
@module rsvp
@public
**/
class AllSettled extends Enumerator {
constructor(Constructor, entries, label) {
super(Constructor, entries, false
/* don't abort on reject */
, label);
}
}
AllSettled.prototype._setResultAt = setSettledResult;
/**
`RSVP.allSettled` is similar to `RSVP.all`, but instead of implementing
a fail-fast method, it waits until all the promises have returned and
shows you all the results. This is useful if you want to handle multiple
promises' failure states together as a set.
Returns a promise that is fulfilled when all the given promises have been
settled. The return promise is fulfilled with an array of the states of
the promises passed into the `promises` array argument.
Each state object will either indicate fulfillment or rejection, and
provide the corresponding value or reason. The states will take one of
the following formats:
```javascript
{ state: 'fulfilled', value: value }
or
{ state: 'rejected', reason: reason }
```
Example:
```javascript
let promise1 = RSVP.Promise.resolve(1);
let promise2 = RSVP.Promise.reject(new Error('2'));
let promise3 = RSVP.Promise.reject(new Error('3'));
let promises = [ promise1, promise2, promise3 ];
RSVP.allSettled(promises).then(function(array){
// array == [
// { state: 'fulfilled', value: 1 },
// { state: 'rejected', reason: Error },
// { state: 'rejected', reason: Error }
// ]
// Note that for the second item, reason.message will be '2', and for the
// third item, reason.message will be '3'.
}, function(error) {
// Not run. (This block would only be called if allSettled had failed,
// for instance if passed an incorrect argument type.)
});
```
@method allSettled
@public
@static
@for rsvp
@param {Array} entries
@param {String} [label] - optional string that describes the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled with an array of the settled
states of the constituent promises.
*/
function allSettled(entries, label) {
if (!Array.isArray(entries)) {
return Promise.reject(new TypeError("Promise.allSettled must be called with an array"), label);
}
return new AllSettled(Promise, entries, label).promise;
}
/**
This is a convenient alias for `Promise.race`.
@method race
@public
@static
@for rsvp
@param {Array} array Array of promises.
@param {String} [label] An optional label. This is useful
for tooling.
*/
function race$1(array, label) {
return Promise.race(array, label);
}
class PromiseHash extends Enumerator {
constructor(Constructor, object, abortOnReject = true, label) {
super(Constructor, object, abortOnReject, label);
}
_init(Constructor, object) {
this._result = {};
this._enumerate(object);
}
_enumerate(input) {
var keys = Object.keys(input);
var length = keys.length;
var promise = this.promise;
this._remaining = length;
var key, val;
for (var i = 0; promise._state === PENDING && i < length; i++) {
key = keys[i];
val = input[key];
this._eachEntry(val, key, true);
}
this._checkFullfillment();
}
}
/**
`hash` is similar to `all`, but takes an object instead of an array
for its `promises` argument.
Returns a promise that is fulfilled when all the given promises have been
fulfilled, or rejected if any of them become rejected. The returned promise
is fulfilled with a hash that has the same key names as the `promises` object
argument. If any of the values in the object are not promises, they will
simply be copied over to the fulfilled object.
Example:
```javascript
let promises = {
myPromise: resolve(1),
yourPromise: resolve(2),
theirPromise: resolve(3),
notAPromise: 4
};
hash(promises).then(function(hash){
// hash here is an object that looks like:
// {
// myPromise: 1,
// yourPromise: 2,
// theirPromise: 3,
// notAPromise: 4
// }
});
```
If any of the `promises` given to `hash` are rejected, the first promise
that is rejected will be given as the reason to the rejection handler.
Example:
```javascript
let promises = {
myPromise: resolve(1),
rejectedPromise: reject(new Error('rejectedPromise')),
anotherRejectedPromise: reject(new Error('anotherRejectedPromise')),
};
hash(promises).then(function(hash){
// Code here never runs because there are rejected promises!
}, function(reason) {
// reason.message === 'rejectedPromise'
});
```
An important note: `hash` is intended for plain JavaScript objects that
are just a set of keys and values. `hash` will NOT preserve prototype
chains.
Example:
```javascript
import { hash, resolve } from 'rsvp';
function MyConstructor(){
this.example = resolve('Example');
}
MyConstructor.prototype = {
protoProperty: resolve('Proto Property')
};
let myObject = new MyConstructor();
hash(myObject).then(function(hash){
// protoProperty will not be present, instead you will just have an
// object that looks like:
// {
// example: 'Example'
// }
//
// hash.hasOwnProperty('protoProperty'); // false
// 'undefined' === typeof hash.protoProperty
});
```
@method hash
@public
@static
@for rsvp
@param {Object} object
@param {String} [label] optional string that describes the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all properties of `promises`
have been fulfilled, or rejected if any of them become rejected.
*/
function hash(object, label) {
return Promise.resolve(object, label).then(function (object) {
if (object === null || typeof object !== 'object') {
throw new TypeError("Promise.hash must be called with an object");
}
return new PromiseHash(Promise, object, label).promise;
});
}
class HashSettled extends PromiseHash {
constructor(Constructor, object, label) {
super(Constructor, object, false, label);
}
}
HashSettled.prototype._setResultAt = setSettledResult;
/**
`hashSettled` is similar to `allSettled`, but takes an object
instead of an array for its `promises` argument.
Unlike `all` or `hash`, which implement a fail-fast method,
but like `allSettled`, `hashSettled` waits until all the
constituent promises have returned and then shows you all the results
with their states and values/reasons. This is useful if you want to
handle multiple promises' failure states together as a set.
Returns a promise that is fulfilled when all the given promises have been
settled, or rejected if the passed parameters are invalid.
The returned promise is fulfilled with a hash that has the same key names as
the `promises` object argument. If any of the values in the object are not
promises, they will be copied over to the fulfilled object and marked with state
'fulfilled'.
Example:
```javascript
import { hashSettled, resolve } from 'rsvp';
let promises = {
myPromise: resolve(1),
yourPromise: resolve(2),
theirPromise: resolve(3),
notAPromise: 4
};
hashSettled(promises).then(function(hash){
// hash here is an object that looks like:
// {
// myPromise: { state: 'fulfilled', value: 1 },
// yourPromise: { state: 'fulfilled', value: 2 },
// theirPromise: { state: 'fulfilled', value: 3 },
// notAPromise: { state: 'fulfilled', value: 4 }
// }
});
```
If any of the `promises` given to `hash` are rejected, the state will
be set to 'rejected' and the reason for rejection provided.
Example:
```javascript
import { hashSettled, reject, resolve } from 'rsvp';
let promises = {
myPromise: resolve(1),
rejectedPromise: reject(new Error('rejection')),
anotherRejectedPromise: reject(new Error('more rejection')),
};
hashSettled(promises).then(function(hash){
// hash here is an object that looks like:
// {
// myPromise: { state: 'fulfilled', value: 1 },
// rejectedPromise: { state: 'rejected', reason: Error },
// anotherRejectedPromise: { state: 'rejected', reason: Error },
// }
// Note that for rejectedPromise, reason.message == 'rejection',
// and for anotherRejectedPromise, reason.message == 'more rejection'.
});
```
An important note: `hashSettled` is intended for plain JavaScript objects that
are just a set of keys and values. `hashSettled` will NOT preserve prototype
chains.
Example:
```javascript
import Promise, { hashSettled, resolve } from 'rsvp';
function MyConstructor(){
this.example = resolve('Example');
}
MyConstructor.prototype = {
protoProperty: Promise.resolve('Proto Property')
};
let myObject = new MyConstructor();
hashSettled(myObject).then(function(hash){
// protoProperty will not be present, instead you will just have an
// object that looks like:
// {
// example: { state: 'fulfilled', value: 'Example' }
// }
//
// hash.hasOwnProperty('protoProperty'); // false
// 'undefined' === typeof hash.protoProperty
});
```
@method hashSettled
@public
@for rsvp
@param {Object} object
@param {String} [label] optional string that describes the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when when all properties of `promises`
have been settled.
@static
*/
function hashSettled(object, label) {
return Promise.resolve(object, label).then(function (object) {
if (object === null || typeof object !== 'object') {
throw new TypeError("hashSettled must be called with an object");
}
return new HashSettled(Promise, object, false, label).promise;
});
}
/**
`rethrow` will rethrow an error on the next turn of the JavaScript event
loop in order to aid debugging.
Promises A+ specifies that any exceptions that occur with a promise must be
caught by the promises implementation and bubbled to the last handler. For
this reason, it is recommended that you always specify a second rejection
handler function to `then`. However, `rethrow` will throw the exception
outside of the promise, so it bubbles up to your console if in the browser,
or domain/cause uncaught exception in Node. `rethrow` will also throw the
error again so the error can be handled by the promise per the spec.
```javascript
import { rethrow } from 'rsvp';
function throws(){
throw new Error('Whoops!');
}
let promise = new Promise(function(resolve, reject){
throws();
});
promise.catch(rethrow).then(function(){
// Code here doesn't run because the promise became rejected due to an
// error!
}, function (err){
// handle the error here
});
```
The 'Whoops' error will be thrown on the next turn of the event loop
and you can watch for it in your console. You can also handle it using a
rejection handler given to `.then` or `.catch` on the returned promise.
@method rethrow
@public
@static
@for rsvp
@param {Error} reason reason the promise became rejected.
@throws Error
@static
*/
function rethrow(reason) {
setTimeout(() => {
throw reason;
});
throw reason;
}
/**
`defer` returns an object similar to jQuery's `$.Deferred`.
`defer` should be used when porting over code reliant on `$.Deferred`'s
interface. New code should use the `Promise` constructor instead.
The object returned from `defer` is a plain object with three properties:
* promise - an `Promise`.
* reject - a function that causes the `promise` property on this object to
become rejected
* resolve - a function that causes the `promise` property on this object to
become fulfilled.
Example:
```javascript
let deferred = defer();
deferred.resolve("Success!");
deferred.promise.then(function(value){
// value here is "Success!"
});
```
@method defer
@public
@static
@for rsvp
@param {String} [label] optional string for labeling the promise.
Useful for tooling.
@return {Object}
*/
function defer(label) {
var deferred = {
resolve: undefined,
reject: undefined
};
deferred.promise = new Promise((resolve, reject) => {
deferred.resolve = resolve;
deferred.reject = reject;
}, label);
return deferred;
}
class MapEnumerator extends Enumerator {
constructor(Constructor, entries, mapFn, label) {
super(Constructor, entries, true, label, mapFn);
}
_init(Constructor, input, bool, label, mapFn) {
var len = input.length || 0;
this.length = len;
this._remaining = len;
this._result = new Array(len);
this._mapFn = mapFn;
this._enumerate(input);
}
_setResultAt(state, i, value, firstPass) {
if (firstPass) {
try {
this._eachEntry(this._mapFn(value, i), i, false);
} catch (error) {
this._settledAt(REJECTED, i, error, false);
}
} else {
this._remaining--;
this._result[i] = value;
}
}
}
/**
`map` is similar to JavaScript's native `map` method. `mapFn` is eagerly called
meaning that as soon as any promise resolves its value will be passed to `mapFn`.
`map` returns a promise that will become fulfilled with the result of running
`mapFn` on the values the promises become fulfilled with.
For example:
```javascript
import { map, resolve } from 'rsvp';
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [ promise1, promise2, promise3 ];
let mapFn = function(item){
return item + 1;
};
map(promises, mapFn).then(function(result){
// result is [ 2, 3, 4 ]
});
```
If any of the `promises` given to `map` are rejected, the first promise
that is rejected will be given as an argument to the returned promise's
rejection handler. For example:
```javascript
import { map, reject, resolve } from 'rsvp';
let promise1 = resolve(1);
let promise2 = reject(new Error('2'));
let promise3 = reject(new Error('3'));
let promises = [ promise1, promise2, promise3 ];
let mapFn = function(item){
return item + 1;
};
map(promises, mapFn).then(function(array){
// Code here never runs because there are rejected promises!
}, function(reason) {
// reason.message === '2'
});
```
`map` will also wait if a promise is returned from `mapFn`. For example,
say you want to get all comments from a set of blog posts, but you need
the blog posts first because they contain a url to those comments.
```javscript
import { map } from 'rsvp';
let mapFn = function(blogPost){
// getComments does some ajax and returns an Promise that is fulfilled
// with some comments data
return getComments(blogPost.comments_url);
};
// getBlogPosts does some ajax and returns an Promise that is fulfilled
// with some blog post data
map(getBlogPosts(), mapFn).then(function(comments){
// comments is the result of asking the server for the comments
// of all blog posts returned from getBlogPosts()
});
```
@method map
@public
@static
@for rsvp
@param {Array} promises
@param {Function} mapFn function to be called on each fulfilled promise.
@param {String} [label] optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled with the result of calling
`mapFn` on each fulfilled promise or value when they become fulfilled.
The promise will be rejected if any of the given `promises` become rejected.
*/
function map(promises, mapFn, label) {
if (typeof mapFn !== 'function') {
return Promise.reject(new TypeError("map expects a function as a second argument"), label);
}
return Promise.resolve(promises, label).then(function (promises) {
if (!Array.isArray(promises)) {
throw new TypeError("map must be called with an array");
}
return new MapEnumerator(Promise, promises, mapFn, label).promise;
});
}
/**
This is a convenient alias for `Promise.resolve`.
@method resolve
@public
@static
@for rsvp
@param {*} value value that the returned promise will be resolved with
@param {String} [label] optional string for identifying the returned promise.
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
function resolve$2(value, label) {
return Promise.resolve(value, label);
}
/**
This is a convenient alias for `Promise.reject`.
@method reject
@public
@static
@for rsvp
@param {*} reason value that the returned promise will be rejected with.
@param {String} [label] optional string for identifying the returned promise.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
function reject$2(reason, label) {
return Promise.reject(reason, label);
}
var EMPTY_OBJECT = {};
class FilterEnumerator extends MapEnumerator {
_checkFullfillment() {
if (this._remaining === 0 && this._result !== null) {
var result = this._result.filter(val => val !== EMPTY_OBJECT);
fulfill(this.promise, result);
this._result = null;
}
}
_setResultAt(state, i, value, firstPass) {
if (firstPass) {
this._result[i] = value;
var val,
succeeded = true;
try {
val = this._mapFn(value, i);
} catch (error) {
succeeded = false;
this._settledAt(REJECTED, i, error, false);
}
if (succeeded) {
this._eachEntry(val, i, false);
}
} else {
this._remaining--;
if (!value) {
this._result[i] = EMPTY_OBJECT;
}
}
}
}
/**
`filter` is similar to JavaScript's native `filter` method.
`filterFn` is eagerly called meaning that as soon as any promise
resolves its value will be passed to `filterFn`. `filter` returns
a promise that will become fulfilled with the result of running
`filterFn` on the values the promises become fulfilled with.
For example:
```javascript
import { filter, resolve } from 'rsvp';
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [promise1, promise2, promise3];
let filterFn = function(item){
return item > 1;
};
filter(promises, filterFn).then(function(result){
// result is [ 2, 3 ]
});
```
If any of the `promises` given to `filter` are rejected, the first promise
that is rejected will be given as an argument to the returned promise's
rejection handler. For example:
```javascript
import { filter, reject, resolve } from 'rsvp';
let promise1 = resolve(1);
let promise2 = reject(new Error('2'));
let promise3 = reject(new Error('3'));
let promises = [ promise1, promise2, promise3 ];
let filterFn = function(item){
return item > 1;
};
filter(promises, filterFn).then(function(array){
// Code here never runs because there are rejected promises!
}, function(reason) {
// reason.message === '2'
});
```
`filter` will also wait for any promises returned from `filterFn`.
For instance, you may want to fetch a list of users then return a subset
of those users based on some asynchronous operation:
```javascript
import { filter, resolve } from 'rsvp';
let alice = { name: 'alice' };
let bob = { name: 'bob' };
let users = [ alice, bob ];
let promises = users.map(function(user){
return resolve(user);
});
let filterFn = function(user){
// Here, Alice has permissions to create a blog post, but Bob does not.
return getPrivilegesForUser(user).then(function(privs){
return privs.can_create_blog_post === true;
});
};
filter(promises, filterFn).then(function(users){
// true, because the server told us only Alice can create a blog post.
users.length === 1;
// false, because Alice is the only user present in `users`
users[0] === bob;
});
```
@method filter
@public
@static
@for rsvp
@param {Array} promises
@param {Function} filterFn - function to be called on each resolved value to
filter the final results.
@param {String} [label] optional string describing the promise. Useful for
tooling.
@return {Promise}
*/
function filter(promises, filterFn, label) {
if (typeof filterFn !== 'function') {
return Promise.reject(new TypeError("filter expects function as a second argument"), label);
}
return Promise.resolve(promises, label).then(function (promises) {
if (!Array.isArray(promises)) {
throw new TypeError("filter must be called with an array");
}
return new FilterEnumerator(Promise, promises, filterFn, label).promise;
});
}
var len = 0;
var vertxNext;
function asap(callback, arg) {
queue$1[len] = callback;
queue$1[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 1, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
scheduleFlush$1();
}
}
var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; // test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node
function useNextTick() {
var nextTick = process.nextTick; // node version 0.10.x displays a deprecation warning when nextTick is used recursively
// setImmediate should be used instead instead
var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);
if (Array.isArray(version) && version[1] === '0' && version[2] === '10') {
nextTick = setImmediate;
}
return () => nextTick(flush);
} // vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function () {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, {
characterData: true
});
return () => node.data = iterations = ++iterations % 2;
} // web worker
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return () => channel.port2.postMessage(0);
}
function useSetTimeout() {
return () => setTimeout(flush, 1);
}
var queue$1 = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue$1[i];
var arg = queue$1[i + 1];
callback(arg);
queue$1[i] = undefined;
queue$1[i + 1] = undefined;
}
len = 0;
}
function attemptVertex() {
try {
var vertx = Function('return this')().require('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
return useSetTimeout();
}
}
var scheduleFlush$1; // Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush$1 = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush$1 = useMutationObserver();
} else if (isWorker) {
scheduleFlush$1 = useMessageChannel();
} else if (browserWindow === undefined && typeof require === 'function') {
scheduleFlush$1 = attemptVertex();
} else {
scheduleFlush$1 = useSetTimeout();
} // defaults
config.async = asap;
config.after = cb => setTimeout(cb, 0);
var cast = resolve$2;
_exports.cast = cast;
var async = (callback, arg) => config.async(callback, arg);
_exports.async = async;
function on() {
config.on(...arguments);
}
function off() {
config.off(...arguments);
} // Set up instrumentation through `window.__PROMISE_INTRUMENTATION__`
if (typeof window !== 'undefined' && typeof window['__PROMISE_INSTRUMENTATION__'] === 'object') {
var callbacks = window['__PROMISE_INSTRUMENTATION__'];
configure('instrument', true);
for (var eventName in callbacks) {
if (callbacks.hasOwnProperty(eventName)) {
on(eventName, callbacks[eventName]);
}
}
} // the default export here is for backwards compat:
// https://github.com/tildeio/rsvp.js/issues/434
var rsvp = {
asap,
cast,
Promise,
EventTarget,
all: all$1,
allSettled,
race: race$1,
hash,
hashSettled,
rethrow,
defer,
denodeify,
configure,
on,
off,
resolve: resolve$2,
reject: reject$2,
map,
async,
filter
};
var _default = rsvp;
_exports.default = _default;
});
require('@ember/-internals/bootstrap')
}());
//# sourceMappingURL=ember.map