ember-source
Version:
A JavaScript framework for creating ambitious web applications
45,581 lines • 1.83 MB
JavaScript
/*!
* @overview Ember - JavaScript Application Framework
* @copyright Copyright 2011 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 6.1.0
*/
/* eslint-disable no-var */
/* globals global globalThis self */
/* eslint-disable-next-line no-unused-vars */
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);
}
}
var result = callback.apply(this, reified);
if (!deps.includes('exports') || result !== undefined) {
exports = seen[name] = result;
}
return exports;
}
require = function (name) {
return internalRequire(name, null);
};
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;
})();
(function () {
'use strict';
function d(name, mod) {
Object.defineProperty(mod, '__esModule', { value: true });
define(name, [], () => mod);
}
// check if window exists and actually is the global
const 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';
const window$1 = hasDOM ? self : null;
const location$1 = hasDOM ? self.location : null;
const history$1 = hasDOM ? self.history : null;
const userAgent = hasDOM ? self.navigator.userAgent : 'Lynx (textmode)';
const isChrome = hasDOM ? typeof chrome === 'object' && !(typeof opera === 'object') : false;
const isFirefox = hasDOM ? /Firefox|FxiOS/.test(userAgent) : false;
const emberinternalsBrowserEnvironmentIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
hasDOM,
history: history$1,
isChrome,
isFirefox,
location: location$1,
userAgent,
window: window$1
}, Symbol.toStringTag, { value: 'Module' });
/**
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$1(str) {
let obj = Object.create(null);
obj[str] = 1;
for (let 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$1(value) {
return value !== null && (typeof value === 'object' || typeof value === 'function');
}
/**
@module @ember/object
*/
/**
@private
@return {Number} the uuid
*/
let _uuid$1 = 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$1() {
return ++_uuid$1;
}
/**
Prefix used for guids through out Ember.
@private
@property GUID_PREFIX
@for Ember
@type String
@final
*/
const GUID_PREFIX = 'ember';
// Used for guid generation...
const OBJECT_GUIDS = new WeakMap();
const 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
*/
const GUID_KEY = intern$1(`__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
*/
function generateGuid(obj, prefix = GUID_PREFIX) {
let guid = prefix + uuid$1().toString();
if (isObject$1(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) {
let guid;
if (isObject$1(value)) {
guid = OBJECT_GUIDS.get(value);
if (guid === undefined) {
guid = `${GUID_PREFIX}${uuid$1()}`;
OBJECT_GUIDS.set(value, guid);
}
} else {
guid = NON_OBJECT_GUIDS.get(value);
if (guid === undefined) {
let type = typeof value;
if (type === 'string') {
guid = `st${uuid$1()}`;
} else if (type === 'number') {
guid = `nu${uuid$1()}`;
} else if (type === 'symbol') {
guid = `sy${uuid$1()}`;
} else {
guid = `(${value})`;
}
NON_OBJECT_GUIDS.set(value, guid);
}
}
return guid;
}
const 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.
let id = GUID_KEY + Math.floor(Math.random() * Date.now()).toString();
let symbol = intern$1(`__${debugName}${id}__`);
return symbol;
}
const 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.
function makeDictionary(parent) {
let dict = Object.create(parent);
dict['_dict'] = null;
delete dict['_dict'];
return dict;
}
let getDebugName;
const HAS_SUPER_PATTERN = /\.(_super|call\(this|apply\(this)/;
const fnToString = Function.prototype.toString;
const checkHasSuper = (() => {
let 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;
};
})();
const HAS_SUPER_MAP = new WeakMap();
const ROOT = Object.freeze(function () {});
HAS_SUPER_MAP.set(ROOT, false);
function hasSuper(func) {
let hasSuper = HAS_SUPER_MAP.get(func);
if (hasSuper === undefined) {
hasSuper = checkHasSuper(func);
HAS_SUPER_MAP.set(func, hasSuper);
}
return hasSuper;
}
class ObserverListenerMeta {
listeners = undefined;
observers = undefined;
}
const OBSERVERS_LISTENERS_MAP = new WeakMap();
function createObserverListenerMetaFor(fn) {
let 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) {
let meta = createObserverListenerMetaFor(func);
meta.observers = observers;
}
function setListeners(func, listeners) {
let meta = createObserverListenerMetaFor(func);
meta.listeners = listeners;
}
const IS_WRAPPED_FUNCTION_SET = new 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$1(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() {
let orig = this._super;
this._super = superFunc;
let ret = func.apply(this, arguments);
this._super = orig;
return ret;
}
IS_WRAPPED_FUNCTION_SET.add(superWrapper);
let meta = OBSERVERS_LISTENERS_MAP.get(func);
if (meta !== undefined) {
OBSERVERS_LISTENERS_MAP.set(superWrapper, meta);
}
return superWrapper;
}
function lookupDescriptor(obj, keyName) {
let current = obj;
do {
let 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 && typeof obj[methodName] === 'function';
}
/**
@module @ember/utils
*/
const NAMES = new WeakMap();
function setName(obj, name) {
if (isObject$1(obj)) NAMES.set(obj, name);
}
function getName(obj) {
return NAMES.get(obj);
}
const objectToString$1 = Object.prototype.toString;
function isNone$1(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$1(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.
let r = '';
for (let k = 0; k < obj.length; k++) {
if (k > 0) {
r += ',';
}
if (!isNone$1(obj[k])) {
r += toString$1(obj[k]);
}
}
return r;
}
if (typeof obj.toString === 'function') {
return obj.toString();
}
return objectToString$1.call(obj);
}
const PROXIES = new WeakSet();
function isProxy(value) {
if (isObject$1(value)) {
return PROXIES.has(value);
}
return false;
}
function setProxy(object) {
if (isObject$1(object)) {
PROXIES.add(object);
}
}
class Cache {
size = 0;
misses = 0;
hits = 0;
constructor(limit, func, store = new Map()) {
this.limit = limit;
this.func = func;
this.store = store;
}
get(key) {
if (this.store.has(key)) {
this.hits++;
// SAFETY: we know the value is present because `.has(key)` was `true`.
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;
}
}
/* globals window, self */
// 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
const 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
// legacy imports/exports/lookup stuff (should we keep this??)
const context$1 = 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);
function getLookup() {
return context$1.lookup;
}
function setLookup(value) {
context$1.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
*/
const 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.
The behavior from setting this option to `true` was deprecated in Ember 5.10.
@property EXTEND_PROTOTYPES
@type Boolean
@default true
@for EmberENV
@private
@deprecated in v5.10
*/
EXTEND_PROTOTYPES: {
Array: false
},
/**
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 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: false /* DEBUG */,
/**
Whether to force all deprecations to be enabled. This is used internally by
Ember to enable deprecations in tests. It is not intended to be set in
projects.
@property _ALL_DEPRECATIONS_ENABLED
@for EmberENV
@type Boolean
@default false
@private
*/
_ALL_DEPRECATIONS_ENABLED: false,
/**
Override the version of ember-source used to determine when deprecations "break".
This is used internally by Ember to test with deprecated features "removed".
This is never intended to be set by projects.
@property _OVERRIDE_DEPRECATION_VERSION
@for EmberENV
@type string | null
@default null
@private
*/
_OVERRIDE_DEPRECATION_VERSION: null,
/**
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,
/**
Whether the app still has default record-loading behavior in the model
hook from RFC https://rfcs.emberjs.com/id/0774-implicit-record-route-loading
This will also remove the default store property from the route.
This is not intended to be set directly, as the implementation may change in
the future. Use `@ember/optional-features` instead.
@property _NO_IMPLICIT_ROUTE_MODEL
@for EmberENV
@type Boolean
@default false
@private
*/
_NO_IMPLICIT_ROUTE_MODEL: 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: {}
};
(EmberENV => {
if (typeof EmberENV !== 'object' || EmberENV === null) return;
for (let flag in EmberENV) {
if (!Object.prototype.hasOwnProperty.call(EmberENV, flag) || flag === 'EXTEND_PROTOTYPES' || flag === 'EMBER_LOAD_HOOKS') continue;
let defaultValue = ENV[flag];
if (defaultValue === true) {
ENV[flag] = EmberENV[flag] !== false;
} else if (defaultValue === false) {
ENV[flag] = EmberENV[flag] === true;
} else {
ENV[flag] = EmberENV[flag];
}
}
// TODO: Remove in Ember 6.5. This setting code for EXTEND_PROTOTYPES
// should stay for at least an LTS cycle so that users get the explicit
// deprecation exception when it breaks in >= 6.0.0.
let {
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?
let {
EMBER_LOAD_HOOKS
} = EmberENV;
if (typeof EMBER_LOAD_HOOKS === 'object' && EMBER_LOAD_HOOKS !== null) {
for (let hookName in EMBER_LOAD_HOOKS) {
if (!Object.prototype.hasOwnProperty.call(EMBER_LOAD_HOOKS, hookName)) continue;
let hooks = EMBER_LOAD_HOOKS[hookName];
if (Array.isArray(hooks)) {
ENV.EMBER_LOAD_HOOKS[hookName] = hooks.filter(hook => typeof hook === 'function');
}
}
}
let {
FEATURES
} = EmberENV;
if (typeof FEATURES === 'object' && FEATURES !== null) {
for (let feature in FEATURES) {
if (!Object.prototype.hasOwnProperty.call(FEATURES, feature)) continue;
ENV.FEATURES[feature] = FEATURES[feature] === true;
}
}
})(global$1.EmberENV);
function getENV() {
return ENV;
}
const emberinternalsEnvironmentIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
ENV,
context: context$1,
getENV,
getLookup,
global: global$1,
setLookup
}, Symbol.toStringTag, { value: 'Module' });
let assert$1 = () => {};
let HANDLERS = {};
let registerHandler$2 = function registerHandler(_type, _callback) {};
let invoke = () => {};
const emberDebugLibHandlers = /*#__PURE__*/Object.defineProperty({
__proto__: null,
HANDLERS,
invoke,
registerHandler: registerHandler$2
}, Symbol.toStringTag, { value: 'Module' });
// This is a "global", but instead of declaring it as `declare global`, which
// will expose it to all other modules, declare it *locally* (and don't export
// it) so that it has the desired "private global" semantics -- however odd that
// particular notion is.
/**
@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
*/
let registerHandler$1 = () => {};
let missingOptionsDeprecation$1;
let missingOptionsIdDeprecation$1;
let missingOptionDeprecation = () => '';
let deprecate$3 = () => {};
const emberDebugLibDeprecate = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: deprecate$3,
missingOptionDeprecation,
missingOptionsDeprecation: missingOptionsDeprecation$1,
missingOptionsIdDeprecation: missingOptionsIdDeprecation$1,
registerHandler: registerHandler$1
}, Symbol.toStringTag, { value: 'Module' });
let testing = false;
function isTesting() {
return testing;
}
function setTesting(value) {
testing = Boolean(value);
}
const emberDebugLibTesting = /*#__PURE__*/Object.defineProperty({
__proto__: null,
isTesting,
setTesting
}, Symbol.toStringTag, { value: 'Module' });
let registerHandler = () => {};
let warn$1 = () => {};
let missingOptionsDeprecation;
let missingOptionsIdDeprecation;
const emberDebugLibWarn = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: warn$1,
missingOptionsDeprecation,
missingOptionsIdDeprecation,
registerHandler
}, Symbol.toStringTag, { value: 'Module' });
const {
toString: objectToString
} = Object.prototype;
const {
toString: functionToString
} = Function.prototype;
const {
isArray: isArray$4
} = Array;
const {
keys: objectKeys
} = Object;
const {
stringify: stringify$1
} = JSON;
const LIST_LIMIT = 100;
const DEPTH_LIMIT = 4;
const 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) {
let valueIsArray = false;
switch (typeof value) {
case 'undefined':
return 'undefined';
case 'object':
if (value === null) return 'null';
if (isArray$4(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$1(value);
case 'symbol':
case 'boolean':
case 'number':
default:
return value.toString();
}
if (seen === undefined) {
seen = new 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$1(key);
}
function inspectObject(obj, depth, seen) {
if (depth > DEPTH_LIMIT) {
return '[Object]';
}
let s = '{';
let keys = objectKeys(obj);
for (let i = 0; i < keys.length; i++) {
s += i === 0 ? ' ' : ', ';
if (i >= LIST_LIMIT) {
s += `... ${keys.length - LIST_LIMIT} more keys`;
break;
}
let key = keys[i];
s += `${inspectKey(String(key))}: ${inspectValue(obj[key], depth, seen)}`;
}
s += ' }';
return s;
}
function inspectArray(arr, depth, seen) {
if (depth > DEPTH_LIMIT) {
return '[Array]';
}
let s = '[';
for (let 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;
}
const emberDebugLibInspect = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: inspect
}, Symbol.toStringTag, { value: 'Module' });
const EMPTY_ARRAY$4 = Object.freeze([]);
function emptyArray() {
return EMPTY_ARRAY$4;
}
const EMPTY_STRING_ARRAY = emptyArray(),
EMPTY_NUMBER_ARRAY = emptyArray();
/**
* This function returns `true` if the input array is the special empty array sentinel,
* which is sometimes used for optimizations.
*/
function isEmptyArray(input) {
return input === EMPTY_ARRAY$4;
}
function* reverse(input) {
for (let i = input.length - 1; i >= 0; i--) yield input[i];
}
function* enumerate(input) {
let i = 0;
for (const item of input) yield [i++, item];
}
// import Logger from './logger';
// let alreadyWarned = false;
function debugAssert(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$2(desc) {
LOCAL_LOGGER.warn(`DEPRECATION: ${desc}`);
}
function keys(obj) {
return Object.keys(obj);
}
function unwrap$1(val) {
if (null == val) throw new Error("Expected value to be present");
return val;
}
function expect(val, message) {
if (null == val) throw new Error(message);
return val;
}
function unreachable(message = "unreachable") {
return new Error(message);
}
function exhausted(value) {
throw new Error(`Exhausted ${String(value)}`);
}
const tuple = (...args) => args;
function isPresent$2(value) {
return null != value;
}
function assertPresent(value, message) {
if (!isPresent$2(value)) throw new Error(`Expected present, got ${"string" == typeof value ? value : message}`);
}
function isPresentArray(list) {
return list.length > 0;
}
function ifPresent(list, ifPresent, otherwise) {
return isPresentArray(list) ? ifPresent(list) : otherwise();
}
function arrayToOption(list) {
return isPresentArray(list) ? list : null;
}
function assertPresentArray(list, message = "unexpected empty list") {
if (!isPresentArray(list)) throw new Error(message);
}
function asPresentArray(list, message = "unexpected empty list") {
return assertPresentArray(list, message), list;
}
function getLast(list) {
return 0 === list.length ? void 0 : list[list.length - 1];
}
function getFirst(list) {
return 0 === list.length ? void 0 : list[0];
}
function mapPresentArray(list, mapper) {
if (null === list) return null;
let out = [];
for (let item of list) out.push(mapper(item));
return out;
}
function dict() {
return Object.create(null);
}
function isDict(u) {
return null != u;
}
function isObject(u) {
return "function" == typeof u || "object" == typeof u && null !== u;
}
class StackImpl {
stack;
current = null;
constructor(values = []) {
this.stack = values;
}
get size() {
return this.stack.length;
}
push(item) {
this.current = item, this.stack.push(item);
}
pop() {
let item = this.stack.pop();
return this.current = getLast(this.stack) ?? null, void 0 === item ? null : item;
}
nth(from) {
let len = this.stack.length;
return len < from ? null : unwrap$1(this.stack[len - from]);
}
isEmpty() {
return 0 === this.stack.length;
}
toArray() {
return this.stack;
}
}
/// <reference types="qunit" />
let beginTestSteps, endTestSteps, verifySteps, logStep, debugToString;
var debugToString$1 = debugToString;
function clearElement(parent) {
let current = parent.firstChild;
for (; current;) {
let next = current.nextSibling;
parent.removeChild(current), current = next;
}
}
const RAW_NODE = -1,
ELEMENT_NODE = 1,
TEXT_NODE = 3,
COMMENT_NODE = 8,
DOCUMENT_NODE = 9,
DOCUMENT_TYPE_NODE = 10,
DOCUMENT_FRAGMENT_NODE = 11,
NS_HTML = "http://www.w3.org/1999/xhtml",
NS_MATHML = "http://www.w3.org/1998/Math/MathML",
NS_SVG = "http://www.w3.org/2000/svg",
NS_XLINK = "http://www.w3.org/1999/xlink",
NS_XML = "http://www.w3.org/XML/1998/namespace",
NS_XMLNS = "http://www.w3.org/2000/xmlns/",
INSERT_BEFORE_BEGIN = "beforebegin",
INSERT_AFTER_BEGIN = "afterbegin",
INSERT_BEFORE_END = "beforeend",
INSERT_AFTER_END = "afterend";
/*
Encoding notes
We use 30 bit integers for encoding, so that we don't ever encode a non-SMI
integer to push on the stack.
Handles are >= 0
Immediates are < 0
True, False, Undefined and Null are pushed as handles into the symbol table,
with well known handles (0, 1, 2, 3)
The negative space is divided into positives and negatives. Positives are
higher numbers (-1, -2, -3, etc), negatives are lower.
We only encode immediates for two reasons:
1. To transfer over the wire, so they're smaller in general
2. When pushing values onto the stack from the low level/inner VM, which may
be converted into WASM one day.
This allows the low-level VM to always use SMIs, and to minimize using JS
values via handles for things like the stack pointer and frame pointer.
Externally, most code pushes values as JS values, except when being pulled
from the append byte code where it was already encoded.
Logically, this is because the low level VM doesn't really care about these
higher level values. For instance, the result of a userland helper may be a
number, or a boolean, or undefined/null, but it's extra work to figure that
out and push it correctly, vs. just pushing the value as a JS value with a
handle.
Note: The details could change here in the future, this is just the current
strategy.
*/
let ImmediateConstants = function (ImmediateConstants) {
return ImmediateConstants[ImmediateConstants.MAX_SMI = 1073741823] = "MAX_SMI", ImmediateConstants[ImmediateConstants.MIN_SMI = -1073741824] = "MIN_SMI", ImmediateConstants[ImmediateConstants.SIGN_BIT = -536870913] = "SIGN_BIT", ImmediateConstants[ImmediateConstants.MAX_INT = 536870911] = "MAX_INT", ImmediateConstants[ImmediateConstants.MIN_INT = -536870912] = "MIN_INT", ImmediateConstants[ImmediateConstants.FALSE_HANDLE = 0] = "FALSE_HANDLE", ImmediateConstants[ImmediateConstants.TRUE_HANDLE = 1] = "TRUE_HANDLE", ImmediateConstants[ImmediateConstants.NULL_HANDLE = 2] = "NULL_HANDLE", ImmediateConstants[ImmediateConstants.UNDEFINED_HANDLE = 3] = "UNDEFINED_HANDLE", ImmediateConstants[ImmediateConstants.ENCODED_FALSE_HANDLE = 0] = "ENCODED_FALSE_HANDLE", ImmediateConstants[ImmediateConstants.ENCODED_TRUE_HANDLE = 1] = "ENCODED_TRUE_HANDLE", ImmediateConstants[ImmediateConstants.ENCODED_NULL_HANDLE = 2] = "ENCODED_NULL_HANDLE", ImmediateConstants[ImmediateConstants.ENCODED_UNDEFINED_HANDLE = 3] = "ENCODED_UNDEFINED_HANDLE", ImmediateConstants;
}({});
function isHandle(value) {
return value >= 0;
}
function isNonPrimitiveHandle(value) {
return value > ImmediateConstants.ENCODED_UNDEFINED_HANDLE;
}
function constants(...values) {
return [!1, !0, null, void 0, ...values];
}
function isSmallInt(value) {
return value % 1 == 0 && value <= ImmediateConstants.MAX_INT && value >= ImmediateConstants.MIN_INT;
}
function encodeNegative(num) {
return num & ImmediateConstants.SIGN_BIT;
}
function decodeNegative(num) {
return num | ~ImmediateConstants.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) {
return (num |= 0) < 0 ? encodeNegative(num) : encodePositive(num);
}
function decodeImmediate(num) {
return (num |= 0) > ImmediateConstants.SIGN_BIT ? decodePositive(num) : decodeNegative(num);
}
/**
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) {
let obj = {};
obj[str] = 1;
for (let key in obj) if (key === str) return key;
return str;
}
[1, -1].forEach(x => decodeImmediate(encodeImmediate(x)));
const SERIALIZATION_FIRST_NODE_STRING$1 = "%+b:0%";
function isSerializationFirstNode$1(node) {
return "%+b:0%" === node.nodeValue;
}
let assign = Object.assign;
function values(obj) {
return Object.values(obj);
}
function entries(dict) {
return Object.entries(dict);
}
function castToSimple(node) {
return isDocument(node) || isSimpleElement(node), node;
}
// If passed a document, verify we're in the browser and return it as a Document
// If we don't know what this is, but the check requires it to be an element,
// the cast will mandate that it's a browser element
// Finally, if it's a more generic check, the cast will mandate that it's a
// browser node and return a BrowserNodeUtils corresponding to the check
function castToBrowser(node, sugaryCheck) {
if (null == node) return null;
if (void 0 === typeof document) 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 checkBrowserNode(node, sugaryCheck);
}
function isDocument(node) {
return node.nodeType === DOCUMENT_NODE;
}
function isSimpleElement(node) {
return node?.nodeType === ELEMENT_NODE;
}
function isElement$1(node) {
return node?.nodeType === ELEMENT_NODE && node instanceof Element;
}
function checkBrowserNode(node, check) {
let isMatch = !1;
if (null !== node) if ("string" == typeof check) isMatch = stringCheckNode(node, check);else {
if (!Array.isArray(check)) throw unreachable();
isMatch = check.some(c => stringCheckNode(node, c));
}
if (isMatch && node instanceof Node) return node;
throw function (from, check) {
return new Error(`cannot cast a ${from} into ${String(check)}`);
}(`SimpleElement(${node?.constructor?.name ?? "null"})`, check);
}
function stringCheckNode(node, check) {
switch (check) {
case "NODE":
return !0;
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 strip$1(strings, ...args) {
let out = "";
for (const [i, string] of enumerate(strings)) out += `${string}${void 0 !== args[i] ? String(args[i]) : ""}`;
let lines = out.split("\n");
for (; isPresentArray(lines) && /^\s*$/u.test(getFirst(lines));) lines.shift();
for (; isPresentArray(lines) && /^\s*$/u.test(getLast(lines));) lines.pop();
let min = 1 / 0;
for (let line of lines) {
let leading = /^\s*/u.exec(line)[0].length;
min = Math.min(min, leading);
}
let stripped = [];
for (let line of lines) stripped.push(line.slice(min));
return stripped.join("\n");
}
function unwrapHandle(handle) {
if ("number" == typeof handle) return handle;
{
let error = handle.errors[0];
throw new Error(`Compile Error: ${error.problem} @ ${error.span.start}..${error.span.end}`);
}
}
function unwrapTemplate(template) {
if ("error" === template.result) throw new Error(`Compile Error: ${template.problem} @ ${template.span.start}..${template.span.end}`);
return template;
}
function extractHandle(handle) {
return "number" == typeof handle ? handle : handle.handle;
}
function isOkHandle(handle) {
return "number" == typeof handle;
}
function isErrHandle(handle) {
return "number" == typeof handle;
}
function buildUntouchableThis(source) {
let context = null;
return context;
}
/**
* 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.
*/
const LOCAL_LOGGER = console,
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.
*/
function assertNever(value, desc = "unexpected unreachable branch") {
throw LOGGER.log("unreachable", value), LOGGER.log(`${desc} :: ${JSON.stringify(value)} (${value})`), new Error("code reached unreachable");
}
const glimmerUtil = /*#__PURE__*/Object.defineProperty({
__proto__: null,
COMMENT_NODE,
DOCUMENT_FRAGMENT_NODE,
DOCUMENT_NODE,
DOCUMENT_TYPE_NODE,
ELEMENT_NODE,
EMPTY_ARRAY: EMPTY_ARRAY$4,
EMPTY_NUMBER_ARRAY,
EMPTY_STRING_ARRAY,
INSERT_AFTER_BEGIN,
INSERT_AFTER_END,
INSERT_BEFORE_BEGIN,
INSERT_BEFORE_END,
ImmediateConstants,
LOCAL_LOGGER,
LOGGER,
NS_HTML,
NS_MATHML,
NS_SVG,
NS_XLINK,
NS_XML,
NS_XMLNS,
RAW_NODE,
SERIALIZATION_FIRST_NODE_STRING: SERIALIZATION_FIRST_NODE_STRING$1,
Stack: StackImpl,
TEXT_NODE,
arrayToOption,
asPresentArray,
assert: debugAssert,
assertNever,
assertPresent,
assertPresentArray,
assign,
beginTestSteps,
buildUntouchableThis,
castToBrowser,
castToSimple,
checkNode: checkBrowserNode,
clearElement,
constants,
debugToString: debugToString$1,
decodeHandle,
decodeImmediate,
decodeNegative,
decodePositive,
deprecate: deprecate$2,
dict,
emptyArray,
encodeHandle,
encodeImmediate,
encodeNegative,
encodePositive,
endTestSteps,
entries,
enumerate,
exhausted,
expect,
extractHandle,
getFirst,
getLast,
ifPresent,
intern,
isDict,
isElement: isElement$1,
isEmptyArray,
isErrHandle,
isHandle,
isNonPrimitiveHandle,
isObject,
isOkHandle,
isPresent: isPresent$2,
isPresentArray,
isSerializationFirstNode: isSerializationFirstNode$1,
isSimpleElement,
isSmallInt,
keys,
logStep,
mapPresentArray,
reverse,
strip: strip$1,
tuple,
unreachable,
unwrap: unwrap$1,
unwrapHandle,
unwrapTemplate,
values,
verifySteps
}, Symbol.toStringTag, { value: 'Module' });
/**
@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) {
// SAFETY: Ideally we'd assert here but that causes awkward circular requires since this is also in @ember/debug.
// This is only for debug stuff so not very risky.
let renderer = expect(app.lookup('renderer:-dom'), `BUG: owner is missing renderer`);
return renderer.debugRenderTree.capture();
}
const emberDebugLibCaptureRenderTree = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: captureRenderTree
}, Symbol.toStringTag, { value: 'Module' });
// These are the default production build versions:
const noop$3 = () => {};
// SAFETY: these casts are just straight-up lies, but the point is that they do
// not do anything in production builds.
let info = noop$3;
let warn = noop$3;
let debug$2 = noop$3;
let debugSeal = noop$3;
let debugFreeze = noop$3;
let runInDebug = noop$3;
let setDebugFunction = noop$3;
let getDebugFunction = noop$3;
let deprecateFunc = function () {
return arguments[arguments.length - 1];
};
function deprecate$1(...args) {
return (deprecate$3)(...args);
}
let _warnIfUsingStrippedFeatureFlags;
const emberDebugIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
_warnIfUsingStrippedFeatureFlags,
assert: assert$1,
captureRenderTree,
debug: debug$2,
debugFreeze,
debugSeal,
deprecate: deprecate$1,
deprecateFunc,
getDebugFunction,
info,
inspect,
isTesting,
registerDeprecationHandler: registerHandler$1,
registerWarnHandler: registerHandler,
runInDebug,
setDebugFunction,
setTesting,
warn
}, Symbol.toStringTag, { value: 'Module' });
let setupMandatorySetter;
let teardownMandatorySetter;
let setWithMandatorySetter;
/*
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).
*/
const emberinternalsUtilsIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
Cache,
GUID_KEY,
ROOT,
canInvoke,
checkHasSuper,
dictionary: makeDictionary,
enumerableSymbol,
generateGuid,
getDebugName,
getName,
guidFor,
intern: intern$1,
isInternalSymbol,
isObject: isObject$1,
isProxy,
lookupDescriptor,
observerListenerMetaFor,
setListeners,
setName,
setObservers,
setProxy,
setWithMandatorySetter,
setupMandatorySetter,
symbol,
teardownMandatorySetter,
toString: toString$1,
uuid: uuid$1,
wrap: wrap$1
}, Symbol.toStringTag, { value: 'Module' });
const OWNER$1 = 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.
*/
function getOwner$3(object) {
return object[OWNER$1];
}
/**
`setOwner` set's an object's owner
*/
function setOwner$2(object, owner) {
object[OWNER$1] = owner;
}
const glimmerOwner = /*#__PURE__*/Object.defineProperty({
__proto__: null,
OWNER: OWNER$1,
getOwner: getOwner$3,
setOwner: setOwner$2
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/owner
*/
/**
The name for a factory consists of a namespace and the name of a specific type
within that namespace, like `'service:session'`.
**Note:** `FullName` is *not* a class, just a contract for strings used in the
DI system. It is currently documented as a class only due to limits in our
documentation infrastructure.
@for @ember/owner
@class FullName
@public
*/
/**
A type registry for the DI system, which other participants in the DI system
can register themselves into with declaration merging. The contract for this
type is that its keys are the `Type` from a `FullName`, and each value for a
`Type` is another registry whose keys are the `Name` from a `FullName`. The
mechanic for providing a registry is [declaration merging][handbook].
[handbook]: https://www.typescriptlang.org/docs/handbook/declaration-merging.html
For example, Ember's `@ember/service` module includes this set of definitions:
```ts
export default class Service extends EmberObject {}
// For concrete singleton classes to be merged into.
interface Registry extends Record<string, Service> {}
declare module '@ember/owner' {
service: Registry;
}
```
Declarations of services can then include the registry:
```ts
import Service from '@ember/service';
export default class Session extends Service {
login(username: string, password: string) {
// ...
}
}
declare module '@ember/service' {
interface Registry {
session: Session;
}
}
```
Then users of the `Owner` API will be able to do things like this with strong
type safety guarantees:
```ts
getOwner(this)?.lookup('service:session').login("hello", "1234abcd");
```
@for @ember/owner
@private
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
// Convenience utility for pulling a specific factory manager off `DIRegistry`
// if one exists, or falling back to the default definition otherwise.
/**
@private
*/
/**
The common interface for the ability to `register()` an item, shared by the
`Owner` and `RegistryProxy` interfaces.
@for @ember/owner
@class BasicRegistry
@private
*/
/**
The common interface for the ability to `lookup()` or get the `factoryFor` an
item, shared by the `Owner` and `ContainerProxy` interfaces.
@for @ember/owner
@class BasicContainer
@private
*/
/**
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 handles its
instantiation and manages its lifetime.
An `Owner` is not a class you construct; it is one the framework constructs
for you. The normal way to get access to the relevant `Owner` is using the
`getOwner` function.
@for @ember/owner
@uses BasicRegistry
@uses BasicContainer
@class Owner
@since 4.10.0
@public
*/
/**
* Interface representing the options for registering an item as a factory.
*
* @for @ember/owner
* @class RegisterOptions
* @public
*/
/**
Registered factories are instantiated by having create called on them.
Additionally they are singletons by default, so each time they are looked up
they return the same instance.
However, that behavior can be modified with the `instantiate` and `singleton`
options to the `Owner.register()` method.
@for @ember/owner
@class Factory
@since 4.10.0
@public
*/
/**
The interface representing 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.
**Note:** `FactoryManager` is *not* user-constructible; the only legal way
to get a `FactoryManager` is via `Owner.factoryFor`.
@for @ember/owner
@class FactoryManager
@extends Factory
@public
*/
/**
* A record mapping all known items of a given type: if the item is known it
* will be `true`; otherwise it will be `false` or `undefined`.
*/
/**
A `Resolver` is the mechanism responsible for looking up code in your
application and converting its naming conventions into the actual classes,
functions, and templates that Ember needs to resolve its dependencies, for
example, what template to render for a given route. It is a system that helps
the app resolve the lookup of JavaScript modules agnostic of what kind of
module system is used, which can be AMD, CommonJS or just plain globals. It
is used to lookup routes, models, components, templates, or anything that is
used in your Ember app.
This interface is not a concrete class; instead, it represents the contract a
custom resolver must implement. Most apps never need to think about this: in
the default blueprint, this is supplied by the `ember-resolver` package.
@for @ember/owner
@class Resolver
@since 4.10.0
@public
*/
/**
The internal representation of a `Factory`, for the extra detail available for
private use internally than we expose to consumers.
@for @ember/owner
@class InternalFactory
@private
*/
/**
@private
@method isFactory
@param {Object} obj
@return {Boolean}
@static
*/
function isFactory(obj) {
return obj != null && typeof obj.create === 'function';
}
// NOTE: For docs, see the definition at the public API site in `@ember/owner`;
// we document it there for the sake of public API docs and for TS consumption,
// while having the richer `InternalOwner` representation for Ember itself.
function getOwner$2(object) {
return getOwner$3(object);
}
/**
`setOwner` forces a new owner on a given object instance. This is primarily
useful in some testing cases.
@method setOwner
@static
@for @ember/owner
@param {Object} object An object instance.
@param {Owner} object The new owner object of the object instance.
@since 2.3.0
@public
*/
function setOwner$1(object, owner) {
setOwner$2(object, owner);
}
// Defines the type for the ContainerProxyMixin. When we rationalize our Owner
// *not* to work via mixins, we will be able to delete this entirely, in favor
// of just using the Owner class itself.
/**
* The interface for a container proxy, which is itself a private API used
* by the private `ContainerProxyMixin` as part of the base definition of
* `EngineInstance`.
*
* @class ContainerProxy
* @for @ember/owner
* @private
* @extends BasicContainer
*/
/**
* @class RegistryProxy
* @extends BasicRegistry
* @private
* @for @ember/owner
*/
/**
* @internal This is the same basic interface which is implemented (via the
* mixins) by `EngineInstance` and therefore `ApplicationInstance`, which are
* the normal interfaces to an `Owner` for end user applications now. However,
* going forward, we expect to progressively deprecate and remove the "extra"
* APIs which are not exposed on `Owner` itself.
*/
const emberinternalsOwnerIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
getOwner: getOwner$2,
isFactory,
setOwner: setOwner$1
}, Symbol.toStringTag, { value: 'Module' });
/**
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 {
static _leakTracking;
owner;
registry;
cache;
factoryManagerCache;
validationCache;
isDestroyed;
isDestroying;
constructor(registry, options = {}) {
this.registry = registry;
this.owner = options.owner || null;
this.cache = makeDictionary(options.cache || null);
this.factoryManagerCache = makeDictionary(options.factoryManagerCache || null);
this.isDestroyed = false;
this.isDestroying = false;
}
/**
@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 {RegisterOptions} [options]
@return {any}
*/
lookup(fullName, options) {
if (this.isDestroyed) {
throw new Error(`Cannot call \`.lookup('${fullName}')\` after the owner has been destroyed`);
}
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() {
let injection = {};
setOwner$1(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
@return {any}
*/
factoryFor(fullName) {
if (this.isDestroyed) {
throw new Error(`Cannot call \`.factoryFor('${fullName}')\` after the owner has been destroyed`);
}
let normalizedName = this.registry.normalize(fullName);
return factoryFor(this, normalizedName, fullName);
}
}
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 = {}) {
let normalizedName = fullName;
if (options.singleton === true || options.singleton === undefined && isSingleton(container, fullName)) {
let cached = container.cache[normalizedName];
if (cached !== undefined) {
return cached;
}
}
return instantiateFactory(container, normalizedName, fullName, options);
}
function factoryFor(container, normalizedName, fullName) {
let cached = container.factoryManagerCache[normalizedName];
if (cached !== undefined) {
return cached;
}
let factory = container.registry.resolve(normalizedName);
if (factory === undefined) {
return;
}
let manager = new InternalFactoryManager(container, factory, fullName, normalizedName);
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) {
let 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)) {
let 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) {
let cache = container.cache;
let keys = Object.keys(cache);
for (let key of keys) {
let value = cache[key];
if (value.destroy) {
value.destroy();
}
}
}
function resetCache(container) {
container.cache = makeDictionary(null);
container.factoryManagerCache = makeDictionary(null);
}
function resetMember(container, fullName) {
let member = container.cache[fullName];
delete container.factoryManagerCache[fullName];
if (member) {
delete container.cache[fullName];
if (member.destroy) {
member.destroy();
}
}
}
const INIT_FACTORY = Symbol('INIT_FACTORY');
function getFactoryFor(obj) {
// SAFETY: since we know `obj` is an `object`, we also know we can safely ask
// whether a key is set on it.
return obj[INIT_FACTORY];
}
function setFactoryFor(obj, factory) {
// SAFETY: since we know `obj` is an `object`, we also know we can safely set
// a key it safely at this location. (The only way this could be blocked is if
// someone has gone out of their way to use `Object.defineProperty()` with our
// internal-only symbol and made it `writable: false`.)
obj[INIT_FACTORY] = factory;
}
class InternalFactoryManager {
container;
owner;
class;
fullName;
normalizedName;
madeToString;
injections;
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;
}
toString() {
if (this.madeToString === undefined) {
this.madeToString = this.container.registry.makeToString(this.class, this.fullName);
}
return this.madeToString;
}
create(options) {
let {
container
} = this;
if (container.isDestroyed) {
throw new Error(`Cannot create new instances after the owner has been destroyed (you attempted to create ${this.fullName})`);
}
let props = options ? {
...options
} : {};
setOwner$1(props, container.owner);
setFactoryFor(props, this);
return this.class.create(props);
}
}
const 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 {
_failSet;
resolver;
fallback;
registrations;
_normalizeCache;
_options;
_resolveCache;
_typeOptions;
constructor(options = {}) {
this.fallback = options.fallback || null;
this.resolver = options.resolver || null;
this.registrations = makeDictionary(options.registrations || null);
this._normalizeCache = makeDictionary(null);
this._resolveCache = makeDictionary(null);
this._failSet = new Set();
this._options = makeDictionary(null);
this._typeOptions = makeDictionary(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 = {}) {
let normalizedName = this.normalize(fullName);
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) {
let normalizedName = this.normalize(fullName);
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
@return {Function} fullName's factory
*/
resolve(fullName) {
let factory = resolve$5(this, this.normalize(fullName));
if (factory === undefined && this.fallback !== null) {
factory = this.fallback.resolve(fullName);
}
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) {
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 : factory.name ?? '(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$1(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) {
let 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) {
let normalizedName = this.normalize(fullName);
this._options[normalizedName] = options;
}
getOptions(fullName) {
let normalizedName = this.normalize(fullName);
let options = this._options[normalizedName];
if (options === undefined && this.fallback !== null) {
options = this.fallback.getOptions(fullName);
}
return options;
}
getOption(fullName, optionName) {
let options = this._options[fullName];
if (options !== undefined && options[optionName] !== undefined) {
return options[optionName];
}
let 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;
}
/**
@private
@method knownForType
@param {String} type the type to iterate over
*/
knownForType(type) {
let localKnown = makeDictionary(null);
let registeredNames = Object.keys(this.registrations);
for (let fullName of registeredNames) {
let itemType = fullName.split(':')[0];
if (itemType === type) {
localKnown[fullName] = true;
}
}
let 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);
}
}
function resolve$5(registry, _normalizedName) {
let normalizedName = _normalizedName;
let cached = registry._resolveCache[normalizedName];
if (cached !== undefined) {
return cached;
}
if (registry._failSet.has(normalizedName)) {
return;
}
let 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$1(registry, fullName) {
return registry.resolve(fullName) !== undefined;
}
const privateNames = makeDictionary(null);
const privateSuffix = `${Math.random()}${Date.now()}`.replace('.', '');
function privatize([fullName]) {
let name = privateNames[fullName];
if (name) {
return name;
}
let [type, rawName] = fullName.split(':');
return privateNames[fullName] = intern$1(`${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
*/
const emberinternalsContainerIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
Container,
INIT_FACTORY,
Registry,
getFactoryFor,
privatize,
setFactoryFor
}, Symbol.toStringTag, { value: 'Module' });
// this file gets replaced with the real value during the build
const Version = '6.1.0';
const emberVersion = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: Version
}, Symbol.toStringTag, { value: 'Module' });
const emberVersionIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
VERSION: Version
}, Symbol.toStringTag, { value: 'Module' });
/*
This module exists to separate the @ember/string methods used
internally in ember-source, from those public methods that are
now deprecated and to be removed.
*/
const STRING_DASHERIZE_REGEXP = /[ _]/g;
const STRING_DASHERIZE_CACHE = new Cache(1000, key => decamelize(key).replace(STRING_DASHERIZE_REGEXP, '-'));
const STRING_CLASSIFY_REGEXP_1 = /^(-|_)+(.)?/;
const STRING_CLASSIFY_REGEXP_2 = /(.)(-|_|\.|\s)+(.)?/g;
const STRING_CLASSIFY_REGEXP_3 = /(^|\/|\.)([a-z])/g;
const CLASSIFY_CACHE = new Cache(1000, str => {
let replace1 = (_match, _separator, chr) => chr ? `_${chr.toUpperCase()}` : '';
let replace2 = (_match, initialChar, _separator, chr) => initialChar + (chr ? chr.toUpperCase() : '');
let parts = str.split('/');
for (let 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());
});
const STRING_DECAMELIZE_REGEXP = /([a-z\d])([A-Z])/g;
const DECAMELIZE_CACHE = new Cache(1000, str => str.replace(STRING_DECAMELIZE_REGEXP, '$1_$2').toLowerCase());
/**
Defines string helper methods used internally in ember-source.
@class String
@private
*/
/**
Replaces underscores, spaces, or camelCase with dashes.
```javascript
import { dasherize } from '@ember/-internals/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.
@private
*/
function dasherize(str) {
return STRING_DASHERIZE_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
@private
*/
function classify(str) {
return CLASSIFY_CACHE.get(str);
}
/**
Converts a camelized string into all lower case separated by underscores.
```javascript
decamelize('innerHTML'); // 'inner_html'
decamelize('action_name'); // 'action_name'
decamelize('css-class-name'); // 'css-class-name'
decamelize('my favorite items'); // 'my favorite items'
```
*/
function decamelize(str) {
return DECAMELIZE_CACHE.get(str);
}
const emberinternalsStringIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
classify,
dasherize
}, Symbol.toStringTag, { value: 'Module' });
function isEnabled$1(options) {
return Object.hasOwnProperty.call(options.since, 'enabled') || ENV._ALL_DEPRECATIONS_ENABLED;
}
let numEmberVersion = parseFloat(ENV._OVERRIDE_DEPRECATION_VERSION ?? Version);
/* until must only be a minor version or major version */
function emberVersionGte(until, emberVersion = numEmberVersion) {
let significantUntil = until.replace(/(\.0+)/g, '');
return emberVersion >= parseFloat(significantUntil);
}
function isRemoved(options) {
return emberVersionGte(options.until);
}
function deprecation(options) {
return {
options,
test: !isEnabled$1(options),
isEnabled: isEnabled$1(options) || isRemoved(options),
isRemoved: isRemoved(options)
};
}
/*
To add a deprecation, you must add a new entry to the `DEPRECATIONS` object.
The entry should be an object with the following properties:
* `id` (required): A string that uniquely identifies the deprecation. This
should be a short, descriptive name, typically dasherized.
* `for` (required): The string `ember-source` -- every deprecation from this
package is for `ember-source`.
* `since` (required): An object with `available` and `enabled`. `available` is
the first version of Ember that the deprecation is available in. `enabled` is
the version of Ember that the deprecation was first enabled. This is used as
a feature flag deprecations. For public APIs, the `enabled` value is added
only once the deprecation RFC is [Ready for Release](https://github.com/emberjs/rfcs#ready-for-release).
* `until` (required): The version of Ember that the deprecation will be removed
* `url` (required): A URL to the deprecation guide for the deprecation. This
URL can be constructed in advance of the deprecation being added to the
[deprecation app](https://github.com/ember-learn/deprecation-app) by
following this format: `https://deprecations.emberjs.com/deprecations/{{id}}`.
For example:
`deprecate` should then be called using the entry from the `DEPRECATIONS` object.
```ts
import { DEPRECATIONS } from '@ember/-internals/deprecations';
//...
deprecateUntil(message, DEPRECATIONS.MY_DEPRECATION);
```
`expectDeprecation` should also use the DEPRECATIONS object, but it should be noted
that it uses `isEnabled` instead of `test` because the expectations of `expectDeprecation`
are the opposite of `test`.
```ts
expectDeprecation(
() => {
assert.equal(foo, bar(), 'foo is equal to bar'); // something that triggers the deprecation
},
/matchesMessage/,
DEPRECATIONS.MY_DEPRECATION.isEnabled
);
```
Tests can be conditionally run based on whether a deprecation is enabled or not:
```ts
[`${testUnless(DEPRECATIONS.MY_DEPRECATION.isRemoved)} specific deprecated feature tested only in this test`]
```
This test will be skipped when the MY_DEPRECATION is removed.
When adding a deprecation, we need to guard all the code that will eventually be removed, including tests.
For tests that are not specifically testing the deprecated feature, we need to figure out how to
test the behavior without encountering the deprecated feature, just as users would.
*/
const DEPRECATIONS = {
DEPRECATE_IMPORT_EMBER(importName) {
return deprecation({
id: `deprecate-import-${dasherize(importName).toLowerCase()}-from-ember`,
for: 'ember-source',
since: {
available: '5.10.0'
},
until: '7.0.0',
url: `https://deprecations.emberjs.com/id/import-${dasherize(importName).toLowerCase()}-from-ember`
});
},
DEPRECATE_IMPLICIT_ROUTE_MODEL: deprecation({
id: 'deprecate-implicit-route-model',
for: 'ember-source',
since: {
available: '5.3.0',
enabled: '5.3.0'
},
until: '6.0.0',
url: 'https://deprecations.emberjs.com/v5.x/#toc_deprecate-implicit-route-model'
}),
DEPRECATE_TEMPLATE_ACTION: deprecation({
id: 'template-action',
url: 'https://deprecations.emberjs.com/id/template-action',
until: '6.0.0',
for: 'ember-source',
since: {
available: '5.9.0',
enabled: '5.9.0'
}
}),
DEPRECATE_COMPONENT_TEMPLATE_RESOLVING: deprecation({
id: 'component-template-resolving',
url: 'https://deprecations.emberjs.com/id/component-template-resolving',
until: '6.0.0',
for: 'ember-source',
since: {
available: '5.10.0',
enabled: '5.10.0'
}
}),
DEPRECATE_ARRAY_PROTOTYPE_EXTENSIONS: deprecation({
id: 'deprecate-array-prototype-extensions',
url: 'https://deprecations.emberjs.com/id/deprecate-array-prototype-extensions',
until: '6.0.0',
for: 'ember-source',
since: {
available: '5.10.0',
enabled: '5.10.0'
}
})
};
function deprecateUntil(message, deprecation) {
const {
options
} = deprecation;
if (deprecation.isRemoved) {
throw new Error(`The API deprecated by ${options.id} was removed in ember-source ${options.until}. The message was: ${message}. Please see ${options.url} for more details.`);
}
}
const {
EXTEND_PROTOTYPES
} = ENV;
if (EXTEND_PROTOTYPES.Array !== false) {
deprecateUntil('Array prototype extensions are deprecated. Follow the deprecation guide for migration instructions, and set EmberENV.EXTEND_PROTOTYPES to false in your config/environment.js', DEPRECATIONS.DEPRECATE_ARRAY_PROTOTYPE_EXTENSIONS);
}
const emberinternalsDeprecationsIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
DEPRECATIONS,
deprecateUntil,
emberVersionGte,
isRemoved
}, Symbol.toStringTag, { value: 'Module' });
let onerror;
const onErrorTarget = {
get onerror() {
return onerror;
}
};
// Ember.onerror getter
function getOnerror() {
return onerror;
}
// Ember.onerror setter
function setOnerror(handler) {
onerror = handler;
}
let dispatchOverride = null;
// allows testing adapter to override dispatch
function getDispatchOverride() {
return dispatchOverride;
}
function setDispatchOverride(handler) {
dispatchOverride = handler;
}
const emberinternalsErrorHandlingIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
getDispatchOverride,
getOnerror,
onErrorTarget,
setDispatchOverride,
setOnerror
}, Symbol.toStringTag, { value: 'Module' });
const ContentType = {
Component: 0,
Helper: 1,
String: 2,
Empty: 3,
SafeString: 4,
Fragment: 5,
Node: 6,
Other: 8
},
CurriedTypes = {
Component: 0,
Helper: 1,
Modifier: 2
},
InternalComponentCapabilities = {
Empty: 0,
dynamicLayout: 1,
dynamicTag: 2,
prepareArgs: 4,
createArgs: 8,
attributeHook: 16,
elementHook: 32,
dynamicScope: 64,
createCaller: 128,
updateHook: 256,
createInstance: 512,
wrapped: 1024,
willDestroy: 2048,
hasSubOwner: 4096
},
ARG_SHIFT = 8,
MAX_SIZE = 2147483647,
TYPE_SIZE = 255,
TYPE_MASK = 255,
OPERAND_LEN_MASK = 768,
MACHINE_MASK = 1024,
MachineOp = {
PushFrame: 0,
PopFrame: 1,
InvokeVirtual: 2,
InvokeStatic: 3,
Jump: 4,
Return: 5,
ReturnTo: 6,
Size: 7
},
Op = {
Helper: 16,
SetNamedVariables: 17,
SetBlocks: 18,
SetVariable: 19,
SetBlock: 20,
GetVariable: 21,
GetProperty: 22,
GetBlock: 23,
SpreadBlock: 24,
HasBlock: 25,
HasBlockParams: 26,
Concat: 27,
Constant: 28,
ConstantReference: 29,
Primitive: 30,
PrimitiveReference: 31,
ReifyU32: 32,
Dup: 33,
Pop: 34,
Load: 35,
Fetch: 36,
RootScope: 37,
VirtualRootScope: 38,
ChildScope: 39,
PopScope: 40,
Text: 41,
Comment: 42,
AppendHTML: 43,
AppendSafeHTML: 44,
AppendDocumentFragment: 45,
AppendNode: 46,
AppendText: 47,
OpenElement: 48,
OpenDynamicElement: 49,
PushRemoteElement: 50,
StaticAttr: 51,
DynamicAttr: 52,
ComponentAttr: 53,
FlushElement: 54,
CloseElement: 55,
PopRemoteElement: 56,
Modifier: 57,
BindDynamicScope: 58,
PushDynamicScope: 59,
PopDynamicScope: 60,
CompileBlock: 61,
PushBlockScope: 62,
PushSymbolTable: 63,
InvokeYield: 64,
JumpIf: 65,
JumpUnless: 66,
JumpEq: 67,
AssertSame: 68,
Enter: 69,
Exit: 70,
ToBoolean: 71,
EnterList: 72,
ExitList: 73,
Iterate: 74,
Main: 75,
ContentType: 76,
Curry: 77,
PushComponentDefinition: 78,
PushDynamicComponentInstance: 79,
ResolveDynamicComponent: 80,
ResolveCurriedComponent: 81,
PushArgs: 82,
PushEmptyArgs: 83,
PopArgs: 84,
PrepareArgs: 85,
CaptureArgs: 86,
CreateComponent: 87,
RegisterComponentDestructor: 88,
PutComponentOperations: 89,
GetComponentSelf: 90,
GetComponentTagName: 91,
GetComponentLayout: 92,
BindEvalScope: 93,
SetupForEval: 94,
PopulateLayout: 95,
InvokeComponentLayout: 96,
BeginComponentTransaction: 97,
CommitComponentTransaction: 98,
DidCreateElement: 99,
DidRenderLayout: 100,
ResolveMaybeLocal: 102,
Debugger: 103,
Size: 104,
StaticComponentAttr: 105,
DynamicContentType: 106,
DynamicHelper: 107,
DynamicModifier: 108,
IfInline: 109,
Not: 110,
GetDynamicVar: 111,
Log: 112
};
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
const $pc = 0,
$ra = 1,
$fp = 2,
$sp = 3,
$s0 = 4,
$s1 = 5,
$t0 = 6,
$t1 = 7,
$v0 = 8;
// $1 or $ra (return address): pointer into `program` for the return
let MachineRegister = function (MachineRegister) {
return MachineRegister[MachineRegister.pc = 0] = "pc", MachineRegister[MachineRegister.ra = 1] = "ra", MachineRegister[MachineRegister.fp = 2] = "fp", MachineRegister[MachineRegister.sp = 3] = "sp", MachineRegister;
}({});
function isLowLevelRegister(register) {
return register <= 3;
}
let SavedRegister = function (SavedRegister) {
return SavedRegister[SavedRegister.s0 = 4] = "s0", SavedRegister[SavedRegister.s1 = 5] = "s1", SavedRegister;
}({}),
TemporaryRegister = function (TemporaryRegister) {
return TemporaryRegister[TemporaryRegister.t0 = 6] = "t0", TemporaryRegister[TemporaryRegister.t1 = 7] = "t1", TemporaryRegister;
}({});
const glimmerVm = /*#__PURE__*/Object.defineProperty({
__proto__: null,
$fp,
$pc,
$ra,
$s0,
$s1,
$sp,
$t0,
$t1,
$v0,
ARG_SHIFT,
ContentType,
CurriedType: CurriedTypes,
CurriedTypes,
InternalComponentCapabilities,
InternalComponentCapability: InternalComponentCapabilities,
MACHINE_MASK,
MAX_SIZE,
MachineOp,
MachineRegister,
OPERAND_LEN_MASK,
Op,
SavedRegister,
TYPE_MASK,
TYPE_SIZE,
TemporaryRegister,
isLowLevelRegister,
isMachineOp,
isOp
}, Symbol.toStringTag, { value: 'Module' });
class InstructionEncoderImpl {
constructor(buffer) {
this.buffer = buffer;
}
size = 0;
encode(type, machine, ...args) {
if (type > TYPE_SIZE) throw new Error(`Opcode type over 8-bits. Got ${type}.`);
let first = type | machine | arguments.length - 2 << ARG_SHIFT;
this.buffer.push(first);
for (const op of args) {
this.buffer.push(op);
}
this.size = this.buffer.length;
}
patch(position, target) {
if (-1 !== this.buffer[position + 1]) throw new Error("Trying to patch operand in populated slot instead of a reserved slot.");
this.buffer[position + 1] = target;
}
}
const glimmerEncoder = /*#__PURE__*/Object.defineProperty({
__proto__: null,
InstructionEncoderImpl
}, Symbol.toStringTag, { value: 'Module' });
const opcodes = {
Append: 1,
TrustingAppend: 2,
Comment: 3,
Modifier: 4,
StrictModifier: 5,
Block: 6,
StrictBlock: 7,
Component: 8,
OpenElement: 10,
OpenElementWithSplat: 11,
FlushElement: 12,
CloseElement: 13,
StaticAttr: 14,
DynamicAttr: 15,
ComponentAttr: 16,
AttrSplat: 17,
Yield: 18,
DynamicArg: 20,
StaticArg: 21,
TrustingDynamicAttr: 22,
TrustingComponentAttr: 23,
StaticComponentAttr: 24,
Debugger: 26,
Undefined: 27,
Call: 28,
Concat: 29,
GetSymbol: 30,
GetLexicalSymbol: 32,
GetStrictKeyword: 31,
GetFreeAsComponentOrHelperHead: 35,
GetFreeAsHelperHead: 37,
GetFreeAsModifierHead: 38,
GetFreeAsComponentHead: 39,
InElement: 40,
If: 41,
Each: 42,
Let: 44,
WithDynamicVars: 45,
InvokeComponent: 46,
HasBlock: 48,
HasBlockParams: 49,
Curry: 50,
Not: 51,
IfInline: 52,
GetDynamicVar: 53,
Log: 54
},
resolution = {
Strict: 0,
ResolveAsComponentOrHelperHead: 1,
ResolveAsHelperHead: 5,
ResolveAsModifierHead: 6,
ResolveAsComponentHead: 7
},
WellKnownAttrNames = {
class: 0,
id: 1,
value: 2,
name: 3,
type: 4,
style: 5,
href: 6
},
WellKnownTagNames = {
div: 0,
span: 1,
p: 2,
a: 3
};
// eslint-disable-next-line @typescript-eslint/naming-convention
function is(variant) {
return function (value) {
return Array.isArray(value) && value[0] === variant;
};
}
// Statements
const isFlushElement = is(opcodes.FlushElement);
function isAttribute(val) {
return val[0] === opcodes.StaticAttr || val[0] === opcodes.DynamicAttr || val[0] === opcodes.TrustingDynamicAttr || val[0] === opcodes.ComponentAttr || val[0] === opcodes.StaticComponentAttr || val[0] === opcodes.TrustingComponentAttr || val[0] === opcodes.AttrSplat || val[0] === opcodes.Modifier;
}
function isStringLiteral(expr) {
return "string" == typeof expr;
}
function getStringFromValue(expr) {
return expr;
}
function isArgument(val) {
return val[0] === opcodes.StaticArg || val[0] === opcodes.DynamicArg;
}
function isHelper(expr) {
return Array.isArray(expr) && expr[0] === opcodes.Call;
}
// Expressions
const isGet = is(opcodes.GetSymbol);
const glimmerWireFormat = /*#__PURE__*/Object.defineProperty({
__proto__: null,
SexpOpcodes: opcodes,
VariableResolutionContext: resolution,
WellKnownAttrNames,
WellKnownTagNames,
getStringFromValue,
is,
isArgument,
isAttribute,
isFlushElement,
isGet,
isHelper,
isStringLiteral
}, Symbol.toStringTag, { value: 'Module' });
/**
* 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
*
*/
//////////
/**
* Interfaces
*
* TODO: Move these into @glimmer/interfaces, move @glimmer/interfaces to
* @glimmer/internal-interfaces.
*/
//////////
/**
* Schedules a VM revalidation.
*
* Note: this has a default value so that tags can warm themselves when first loaded.
*/
let scheduleDestroy,
scheduleDestroyed,
toIterator$1,
toBool$1,
getProp,
setProp,
getPath$1,
setPath,
warnIfStyleNotTrusted,
assert,
deprecate,
assertGlobalContextWasSet,
testOverrideGlobalContext,
scheduleRevalidate = () => {};
/**
* Schedules a destructor to run
*
* @param destroyable The destroyable being destroyed
* @param destructor The destructor being scheduled
*/
function setGlobalContext(context) {
scheduleRevalidate = context.scheduleRevalidate, scheduleDestroy = context.scheduleDestroy, scheduleDestroyed = context.scheduleDestroyed, toIterator$1 = context.toIterator, toBool$1 = context.toBool, getProp = context.getProp, setProp = context.setProp, getPath$1 = context.getPath, setPath = context.setPath, warnIfStyleNotTrusted = context.warnIfStyleNotTrusted, assert = context.assert, deprecate = context.deprecate;
}
const glimmerGlobalContext = /*#__PURE__*/Object.defineProperty({
__proto__: null,
get assert () { return assert; },
assertGlobalContextWasSet,
default: setGlobalContext,
get deprecate () { return deprecate; },
get getPath () { return getPath$1; },
get getProp () { return getProp; },
get scheduleDestroy () { return scheduleDestroy; },
get scheduleDestroyed () { return scheduleDestroyed; },
get scheduleRevalidate () { return scheduleRevalidate; },
get setPath () { return setPath; },
get setProp () { return setProp; },
testOverrideGlobalContext,
get toBool () { return toBool$1; },
get toIterator () { return toIterator$1; },
get warnIfStyleNotTrusted () { return warnIfStyleNotTrusted; }
}, Symbol.toStringTag, { value: 'Module' });
var DestroyingState = function (DestroyingState) {
return DestroyingState[DestroyingState.Live = 0] = "Live", DestroyingState[DestroyingState.Destroying = 1] = "Destroying", DestroyingState[DestroyingState.Destroyed = 2] = "Destroyed", DestroyingState;
}(DestroyingState || {});
let enableDestroyableTracking,
assertDestroyablesDestroyed,
DESTROYABLE_META = new WeakMap();
function push(collection, newItem) {
return null === collection ? newItem : Array.isArray(collection) ? (collection.push(newItem), collection) : [collection, newItem];
}
function iterate$1(collection, fn) {
Array.isArray(collection) ? collection.forEach(fn) : null !== collection && fn(collection);
}
function remove(collection, item, message) {
if (Array.isArray(collection) && collection.length > 1) {
let index = collection.indexOf(item);
return collection.splice(index, 1), collection;
}
return null;
}
function getDestroyableMeta(destroyable) {
let meta = DESTROYABLE_META.get(destroyable);
return void 0 === meta && (meta = {
parents: null,
children: null,
eagerDestructors: null,
destructors: null,
state: DestroyingState.Live
}, DESTROYABLE_META.set(destroyable, meta)), meta;
}
function associateDestroyableChild(parent, child) {
let parentMeta = getDestroyableMeta(parent),
childMeta = getDestroyableMeta(child);
return parentMeta.children = push(parentMeta.children, child), childMeta.parents = push(childMeta.parents, parent), child;
}
function registerDestructor$1(destroyable, destructor, eager = !1) {
let meta = getDestroyableMeta(destroyable),
destructorsKey = !0 === eager ? "eagerDestructors" : "destructors";
return meta[destructorsKey] = push(meta[destructorsKey], destructor), destructor;
}
function unregisterDestructor$1(destroyable, destructor, eager = !1) {
let meta = getDestroyableMeta(destroyable),
destructorsKey = !0 === eager ? "eagerDestructors" : "destructors";
meta[destructorsKey] = remove(meta[destructorsKey], destructor);
}
////////////
function destroy(destroyable) {
let meta = getDestroyableMeta(destroyable);
if (meta.state >= DestroyingState.Destroying) return;
let {
parents: parents,
children: children,
eagerDestructors: eagerDestructors,
destructors: destructors
} = meta;
meta.state = DestroyingState.Destroying, iterate$1(children, destroy), iterate$1(eagerDestructors, destructor => destructor(destroyable)), iterate$1(destructors, destructor => scheduleDestroy(destroyable, destructor)), scheduleDestroyed(() => {
iterate$1(parents, parent => function (child, parent) {
let parentMeta = getDestroyableMeta(parent);
parentMeta.state === DestroyingState.Live && (parentMeta.children = remove(parentMeta.children, child));
}(destroyable, parent)), meta.state = DestroyingState.Destroyed;
});
}
function destroyChildren(destroyable) {
let {
children: children
} = getDestroyableMeta(destroyable);
iterate$1(children, destroy);
}
function _hasDestroyableChildren(destroyable) {
let meta = DESTROYABLE_META.get(destroyable);
return void 0 !== meta && null !== meta.children;
}
function isDestroying(destroyable) {
let meta = DESTROYABLE_META.get(destroyable);
return void 0 !== meta && meta.state >= DestroyingState.Destroying;
}
function isDestroyed(destroyable) {
let meta = DESTROYABLE_META.get(destroyable);
return void 0 !== meta && meta.state >= DestroyingState.Destroyed;
}
const glimmerDestroyable = /*#__PURE__*/Object.defineProperty({
__proto__: null,
_hasDestroyableChildren,
assertDestroyablesDestroyed,
associateDestroyableChild,
destroy,
destroyChildren,
enableDestroyableTracking,
isDestroyed,
isDestroying,
registerDestructor: registerDestructor$1,
unregisterDestructor: unregisterDestructor$1
}, Symbol.toStringTag, { value: 'Module' });
function unwrap(val) {
if (null == val) throw new Error("Expected value to be present");
return val;
}
const debug$1 = {};
const CONSTANT = 0,
INITIAL = 1,
VOLATILE = NaN;
let $REVISION = 1;
function bump() {
$REVISION++;
}
//////////
const UPDATABLE_TAG_ID = 1,
COMPUTE$1 = 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
*/
function valueForTag(tag) {
return tag[COMPUTE$1]();
}
/**
* `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$1]();
}
//////////
const TYPE$1 = Symbol("TAG_TYPE");
// this is basically a const
let ALLOW_CYCLES;
class MonomorphicTagImpl {
static combine(tags) {
switch (tags.length) {
case 0:
return CONSTANT_TAG;
case 1:
return tags[0];
default:
{
let tag = new MonomorphicTagImpl(2);
return tag.subtag = tags, tag;
}
}
}
revision = 1;
lastChecked = 1;
lastValue = 1;
isUpdating = !1;
subtag = null;
subtagBufferCache = null;
[TYPE$1];
constructor(type) {
this[TYPE$1] = type;
}
[COMPUTE$1]() {
let {
lastChecked: lastChecked
} = this;
if (!0 === this.isUpdating) {
this.lastChecked = ++$REVISION;
} else if (lastChecked !== $REVISION) {
this.isUpdating = !0, this.lastChecked = $REVISION;
try {
let {
subtag: subtag,
revision: revision
} = this;
if (null !== subtag) if (Array.isArray(subtag)) for (const tag of subtag) {
let value = tag[COMPUTE$1]();
revision = Math.max(value, revision);
} else {
let subtagValue = subtag[COMPUTE$1]();
subtagValue === this.subtagBufferCache ? revision = Math.max(revision, this.lastValue) : (
// Clear the temporary buffer cache
this.subtagBufferCache = null, revision = Math.max(revision, subtagValue));
}
this.lastValue = revision;
} finally {
this.isUpdating = !1;
}
}
return this.lastValue;
}
static updateTag(_tag, _subtag) {
// TODO: TS 3.7 should allow us to do this via assertion
let tag = _tag,
subtag = _subtag;
subtag === CONSTANT_TAG ? tag.subtag = null : (
// 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$1](), tag.subtag = subtag);
}
static dirtyTag(tag, disableConsumptionAssertion) {
tag.revision = ++$REVISION, scheduleRevalidate();
}
}
const DIRTY_TAG$1 = MonomorphicTagImpl.dirtyTag,
UPDATE_TAG = MonomorphicTagImpl.updateTag;
//////////
function createTag() {
return new MonomorphicTagImpl(0);
}
function createUpdatableTag() {
return new MonomorphicTagImpl(UPDATABLE_TAG_ID);
}
//////////
const CONSTANT_TAG = new MonomorphicTagImpl(3);
function isConstTag(tag) {
return tag === CONSTANT_TAG;
}
//////////
class VolatileTag {
[TYPE$1] = 100;
[COMPUTE$1]() {
return NaN;
}
}
const VOLATILE_TAG = new VolatileTag();
//////////
class CurrentTag {
[TYPE$1] = 101;
[COMPUTE$1]() {
return $REVISION;
}
}
const CURRENT_TAG = new CurrentTag(),
combine = MonomorphicTagImpl.combine;
//////////
// Warm
let tag1 = createUpdatableTag(),
tag2 = createUpdatableTag(),
tag3 = createUpdatableTag();
valueForTag(tag1), DIRTY_TAG$1(tag1), valueForTag(tag1), UPDATE_TAG(tag1, combine([tag2, tag3])), valueForTag(tag1), DIRTY_TAG$1(tag2), valueForTag(tag1), DIRTY_TAG$1(tag3), valueForTag(tag1), UPDATE_TAG(tag1, tag3), valueForTag(tag1), DIRTY_TAG$1(tag3), valueForTag(tag1);
///////////
const TRACKED_TAGS = new WeakMap();
function dirtyTagFor(obj, key, meta) {
let tags = void 0 === meta ? TRACKED_TAGS.get(obj) : meta;
// No tags have been setup for this object yet, return
if (void 0 === tags) return;
// Dirty the tag for the specific property if it exists
let propertyTag = tags.get(key);
void 0 !== propertyTag && (DIRTY_TAG$1(propertyTag, !0));
}
function tagMetaFor(obj) {
let tags = TRACKED_TAGS.get(obj);
return void 0 === tags && (tags = new Map(), TRACKED_TAGS.set(obj, tags)), tags;
}
function tagFor(obj, key, meta) {
let tags = void 0 === meta ? tagMetaFor(obj) : meta,
tag = tags.get(key);
return void 0 === tag && (tag = createUpdatableTag(), tags.set(key, tag)), tag;
}
/**
* An object that that tracks @tracked properties that were consumed.
*/
class Tracker {
tags = new Set();
last = null;
add(tag) {
tag !== CONSTANT_TAG && (this.tags.add(tag), this.last = tag);
}
combine() {
let {
tags: tags
} = this;
return 0 === tags.size ? CONSTANT_TAG : 1 === tags.size ? this.last : combine(Array.from(this.tags));
}
}
/**
* 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.
*/
let CURRENT_TRACKER = null;
const OPEN_TRACK_FRAMES = [];
function beginTrackFrame(debuggingContext) {
OPEN_TRACK_FRAMES.push(CURRENT_TRACKER), CURRENT_TRACKER = new Tracker();
}
function endTrackFrame() {
let current = CURRENT_TRACKER;
return CURRENT_TRACKER = OPEN_TRACK_FRAMES.pop() || null, unwrap(current).combine();
}
function beginUntrackFrame() {
OPEN_TRACK_FRAMES.push(CURRENT_TRACKER), CURRENT_TRACKER = null;
}
function endUntrackFrame() {
CURRENT_TRACKER = OPEN_TRACK_FRAMES.pop() || null;
}
// This function is only for handling errors and resetting to a valid state
function resetTracking() {
for (; OPEN_TRACK_FRAMES.length > 0;) OPEN_TRACK_FRAMES.pop();
if (CURRENT_TRACKER = null, false /* DEBUG */) ;
}
function isTracking() {
return null !== CURRENT_TRACKER;
}
function consumeTag(tag) {
null !== CURRENT_TRACKER && CURRENT_TRACKER.add(tag);
}
// public interface
const FN = Symbol("FN"),
LAST_VALUE = Symbol("LAST_VALUE"),
TAG = Symbol("TAG"),
SNAPSHOT = Symbol("SNAPSHOT");
function createCache(fn, debuggingLabel) {
let cache = {
[FN]: fn,
[LAST_VALUE]: void 0,
[TAG]: void 0,
[SNAPSHOT]: -1
};
return cache;
}
function getValue(cache) {
let fn = cache[FN],
tag = cache[TAG],
snapshot = cache[SNAPSHOT];
if (void 0 !== tag && validateTag(tag, snapshot)) consumeTag(tag);else {
beginTrackFrame();
try {
cache[LAST_VALUE] = fn();
} finally {
tag = endTrackFrame(), cache[TAG] = tag, cache[SNAPSHOT] = valueForTag(tag), consumeTag(tag);
}
}
return cache[LAST_VALUE];
}
function isConst(cache) {
let tag = cache[TAG];
// replace this with `expect` when we can
return isConstTag(tag);
}
function track(block, debugLabel) {
let tag;
beginTrackFrame();
try {
block();
} 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) {
let values = new WeakMap(),
hasInitializer = "function" == typeof initializer;
return {
getter: function (self) {
let value;
// If the field has never been initialized, we should initialize it
return consumeTag(tagFor(self, key)), hasInitializer && !values.has(self) ? (value = initializer.call(self), values.set(self, value)) : value = values.get(self), value;
},
setter: function (self, value) {
dirtyTagFor(self, key), values.set(self, value);
}
};
}
const GLIMMER_VALIDATOR_REGISTRATION = Symbol("GLIMMER_VALIDATOR_REGISTRATION"),
globalObj = function () {
if ("undefined" != typeof globalThis) return globalThis;
if ("undefined" != typeof self) return self;
if ("undefined" != typeof window) return window;
if ("undefined" != typeof global) return global;
throw new Error("unable to locate global object");
}();
if (!0 === globalObj[GLIMMER_VALIDATOR_REGISTRATION]) 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] = !0;
const glimmerValidator = /*#__PURE__*/Object.defineProperty({
__proto__: null,
ALLOW_CYCLES,
COMPUTE: COMPUTE$1,
CONSTANT,
CONSTANT_TAG,
CURRENT_TAG,
CurrentTag,
INITIAL,
VOLATILE,
VOLATILE_TAG,
VolatileTag,
beginTrackFrame,
beginUntrackFrame,
bump,
combine,
consumeTag,
createCache,
createTag,
createUpdatableTag,
debug: debug$1,
dirtyTag: DIRTY_TAG$1,
dirtyTagFor,
endTrackFrame,
endUntrackFrame,
getValue,
isConst,
isConstTag,
isTracking,
resetTracking,
tagFor,
tagMetaFor,
track,
trackedData,
untrack,
updateTag: UPDATE_TAG,
validateTag,
valueForTag
}, Symbol.toStringTag, { value: 'Module' });
const REFERENCE = Symbol("REFERENCE"),
COMPUTE = 1,
UNBOUND = 2;
//////////
class ReferenceImpl {
[REFERENCE];
tag = null;
lastRevision = INITIAL;
lastValue;
children = null;
compute = null;
update = null;
debugLabel;
constructor(type) {
this[REFERENCE] = type;
}
}
function createPrimitiveRef(value) {
const ref = new ReferenceImpl(UNBOUND);
return ref.tag = CONSTANT_TAG, ref.lastValue = value, ref;
}
const UNDEFINED_REFERENCE = createPrimitiveRef(void 0),
NULL_REFERENCE = createPrimitiveRef(null),
TRUE_REFERENCE = createPrimitiveRef(!0),
FALSE_REFERENCE = createPrimitiveRef(!1);
function createConstRef(value, debugLabel) {
const ref = new ReferenceImpl(0);
return ref.lastValue = value, ref.tag = CONSTANT_TAG, ref;
}
function createUnboundRef(value, debugLabel) {
const ref = new ReferenceImpl(UNBOUND);
return ref.lastValue = value, ref.tag = CONSTANT_TAG, ref;
}
function createComputeRef(compute, update = null, debugLabel = "unknown") {
const ref = new ReferenceImpl(COMPUTE);
return ref.compute = compute, ref.update = update, ref;
}
function createReadOnlyRef(ref) {
return isUpdatableRef(ref) ? createComputeRef(() => valueForRef(ref), null, ref.debugLabel) : ref;
}
function isInvokableRef(ref) {
return 3 === ref[REFERENCE];
}
function createInvokableRef(inner) {
const ref = createComputeRef(() => valueForRef(inner), value => updateRef(inner, value));
return ref.debugLabel = inner.debugLabel, ref[REFERENCE] = 3, ref;
}
function isConstRef(_ref) {
return _ref.tag === CONSTANT_TAG;
}
function isUpdatableRef(_ref) {
return null !== _ref.update;
}
function valueForRef(_ref) {
const ref = _ref;
let {
tag: tag
} = ref;
if (tag === CONSTANT_TAG) return ref.lastValue;
const {
lastRevision: lastRevision
} = ref;
let lastValue;
if (null !== tag && validateTag(tag, lastRevision)) lastValue = ref.lastValue;else {
const {
compute: compute
} = ref,
newTag = track(() => {
lastValue = ref.lastValue = compute();
});
tag = ref.tag = newTag, ref.lastRevision = valueForTag(newTag);
}
return consumeTag(tag), lastValue;
}
function updateRef(_ref, value) {
expect(_ref.update, "called update on a non-updatable reference")(value);
}
function childRefFor(_parentRef, path) {
const parentRef = _parentRef,
type = parentRef[REFERENCE];
let child,
children = parentRef.children;
if (null === children) children = parentRef.children = new Map();else if (child = children.get(path), void 0 !== child) return child;
if (type === UNBOUND) {
const parent = valueForRef(parentRef);
child = isDict(parent) ? createUnboundRef(parent[path]) : UNDEFINED_REFERENCE;
} else child = createComputeRef(() => {
const parent = valueForRef(parentRef);
if (isDict(parent)) return getProp(parent, path);
}, val => {
const parent = valueForRef(parentRef);
if (isDict(parent)) return setProp(parent, path, val);
});
return children.set(path, child), child;
}
function childRefFromParts(root, parts) {
let reference = root;
for (const part of parts) reference = childRefFor(reference, part);
return reference;
}
let createDebugAliasRef;
const NULL_IDENTITY = {},
KEY = (_, index) => index,
INDEX = (_, index) => String(index),
IDENTITY = item => null === item ? NULL_IDENTITY : item;
class WeakMapWithPrimitives {
_weakMap;
_primitiveMap;
get weakMap() {
return void 0 === this._weakMap && (this._weakMap = new WeakMap()), this._weakMap;
}
get primitiveMap() {
return void 0 === this._primitiveMap && (this._primitiveMap = new Map()), this._primitiveMap;
}
set(key, value) {
isObject(key) ? this.weakMap.set(key, value) : this.primitiveMap.set(key, value);
}
get(key) {
return isObject(key) ? this.weakMap.get(key) : this.primitiveMap.get(key);
}
}
const IDENTITIES = new WeakMapWithPrimitives();
/**
* 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) {
let seen = new WeakMapWithPrimitives();
return (value, memo) => {
let key = keyFor(value, memo),
count = seen.get(key) || 0;
return seen.set(key, count + 1), 0 === count ? key : function (value, count) {
let identities = IDENTITIES.get(value);
void 0 === identities && (identities = [], IDENTITIES.set(value, identities));
let identity = identities[count];
return void 0 === identity && (identity = {
value: value,
count: count
}, identities[count] = identity), identity;
}(key, count);
};
}
function createIteratorRef(listRef, key) {
return createComputeRef(() => {
let iterable = valueForRef(listRef),
keyFor = function (key) {
switch (key) {
case "@key":
return uniqueKeyFor(KEY);
case "@index":
return uniqueKeyFor(INDEX);
case "@identity":
return uniqueKeyFor(IDENTITY);
default:
return function (path) {
return uniqueKeyFor(item => getPath$1(item, path));
}(key);
}
}(key);
if (Array.isArray(iterable)) return new ArrayIterator$1(iterable, keyFor);
let maybeIterator = toIterator$1(iterable);
return null === maybeIterator ? new ArrayIterator$1(EMPTY_ARRAY$4, () => null) : new IteratorWrapper(maybeIterator, keyFor);
});
}
function createIteratorItemRef(_value) {
let value = _value,
tag = createTag();
return createComputeRef(() => (consumeTag(tag), value), newValue => {
value !== newValue && (value = newValue, DIRTY_TAG$1(tag));
});
}
class IteratorWrapper {
constructor(inner, keyFor) {
this.inner = inner, this.keyFor = keyFor;
}
isEmpty() {
return this.inner.isEmpty();
}
next() {
let nextValue = this.inner.next();
return null !== nextValue && (nextValue.key = this.keyFor(nextValue.value, nextValue.memo)), nextValue;
}
}
let ArrayIterator$1 = class ArrayIterator {
current;
pos = 0;
constructor(iterator, keyFor) {
this.iterator = iterator, this.keyFor = keyFor, 0 === iterator.length ? this.current = {
kind: "empty"
} : this.current = {
kind: "first",
value: iterator[this.pos]
};
}
isEmpty() {
return "empty" === this.current.kind;
}
next() {
let value,
current = this.current;
if ("first" === current.kind) this.current = {
kind: "progress"
}, value = current.value;else {
if (this.pos >= this.iterator.length - 1) return null;
value = this.iterator[++this.pos];
}
let {
keyFor: keyFor
} = this;
return {
key: keyFor(value, this.pos),
value: value,
memo: this.pos
};
}
};
const glimmerReference = /*#__PURE__*/Object.defineProperty({
__proto__: null,
FALSE_REFERENCE,
NULL_REFERENCE,
REFERENCE,
TRUE_REFERENCE,
UNDEFINED_REFERENCE,
childRefFor,
childRefFromParts,
createComputeRef,
createConstRef,
createDebugAliasRef,
createInvokableRef,
createIteratorItemRef,
createIteratorRef,
createPrimitiveRef,
createReadOnlyRef,
createUnboundRef,
isConstRef,
isInvokableRef,
isUpdatableRef,
updateRef,
valueForRef
}, Symbol.toStringTag, { value: 'Module' });
const 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 ("symbol" == typeof prop) return null;
const num = Number(prop);
return isNaN(num) ? null : num % 1 == 0 ? num : null;
}
class NamedArgsProxy {
constructor(named) {
this.named = named;
}
get(_target, prop) {
const ref = this.named[prop];
if (void 0 !== ref) return valueForRef(ref);
}
has(_target, prop) {
return prop in this.named;
}
ownKeys() {
return Object.keys(this.named);
}
isExtensible() {
return !1;
}
getOwnPropertyDescriptor(_target, prop) {
return {
enumerable: !0,
configurable: !0
};
}
}
class PositionalArgsProxy {
constructor(positional) {
this.positional = positional;
}
get(target, prop) {
let {
positional: positional
} = this;
if ("length" === prop) return positional.length;
const parsed = convertToInt(prop);
return null !== parsed && parsed < positional.length ? valueForRef(positional[parsed]) : target[prop];
}
isExtensible() {
return !1;
}
has(_target, prop) {
const parsed = convertToInt(prop);
return null !== parsed && parsed < this.positional.length;
}
}
const argsProxyFor = (capturedArgs, type) => {
const {
named: named,
positional: positional
} = capturedArgs,
namedHandler = new NamedArgsProxy(named),
positionalHandler = new PositionalArgsProxy(positional),
namedTarget = Object.create(null);
const namedProxy = new Proxy(namedTarget, namedHandler),
positionalProxy = new Proxy([], positionalHandler);
return setCustomTagFor(namedProxy, (_obj, key) => function (namedArgs, key) {
return track(() => {
key in namedArgs && valueForRef(namedArgs[key]);
});
}(named, key)), setCustomTagFor(positionalProxy, (_obj, key) => function (positionalArgs, key) {
return track(() => {
"[]" === key &&
// consume all of the tags in the positional array
positionalArgs.forEach(valueForRef);
const parsed = convertToInt(key);
null !== parsed && parsed < positionalArgs.length &&
// consume the tag of the referenced index
valueForRef(positionalArgs[parsed]);
});
}(positional, key)), {
named: namedProxy,
positional: positionalProxy
};
};
/* This file is generated by build/debug.js */
new Array(Op.Size).fill(null), new Array(Op.Size).fill(null);
function buildCapabilities(capabilities) {
return capabilities;
}
const EMPTY = InternalComponentCapabilities.Empty;
/**
* Converts a ComponentCapabilities object into a 32-bit integer representation.
*/
function capabilityFlagsFrom(capabilities) {
return EMPTY | capability(capabilities, "dynamicLayout") | capability(capabilities, "dynamicTag") | capability(capabilities, "prepareArgs") | capability(capabilities, "createArgs") | capability(capabilities, "attributeHook") | capability(capabilities, "elementHook") | capability(capabilities, "dynamicScope") | capability(capabilities, "createCaller") | capability(capabilities, "updateHook") | capability(capabilities, "createInstance") | capability(capabilities, "wrapped") | capability(capabilities, "willDestroy") | capability(capabilities, "hasSubOwner");
}
function capability(capabilities, capability) {
return capabilities[capability] ? InternalComponentCapabilities[capability] : EMPTY;
}
function managerHasCapability(_manager, capabilities, capability) {
return !!(capabilities & capability);
}
function hasCapability(capabilities, capability) {
return !!(capabilities & capability);
}
function helperCapabilities(managerAPI, options = {}) {
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;
}
helperManagerDelegates = new WeakMap();
undefinedDelegate = null;
getDelegateForOwner(owner) {
let delegate = this.helperManagerDelegates.get(owner);
if (void 0 === delegate) {
let {
factory: factory
} = this;
if (delegate = factory(owner), false /* DEBUG */ )
// TODO: This error message should make sense in both Ember and Glimmer https://github.com/glimmerjs/glimmer-vm/issues/1200
;
this.helperManagerDelegates.set(owner, delegate);
}
return delegate;
}
getDelegateFor(owner) {
if (void 0 === owner) {
let {
undefinedDelegate: undefinedDelegate
} = this;
if (null === undefinedDelegate) {
let {
factory: factory
} = this;
this.undefinedDelegate = undefinedDelegate = factory(void 0);
}
return undefinedDelegate;
}
return this.getDelegateForOwner(owner);
}
getHelper(definition) {
return (capturedArgs, owner) => {
let manager = this.getDelegateFor(owner);
const args = argsProxyFor(capturedArgs),
bucket = manager.createHelper(definition, args);
if (hasValue(manager)) {
let cache = createComputeRef(() => manager.getValue(bucket), null, false /* DEBUG */ );
return hasDestroyable(manager) && associateDestroyableChild(cache, manager.getDestroyable(bucket)), cache;
}
if (hasDestroyable(manager)) {
let ref = createConstRef(void 0);
return associateDestroyableChild(ref, manager.getDestroyable(bucket)), ref;
}
return UNDEFINED_REFERENCE;
};
}
}
class FunctionHelperManager {
capabilities = buildCapabilities({
hasValue: !0,
hasDestroyable: !1,
hasScheduledEffect: !1
});
createHelper(fn, args) {
return {
fn: fn,
args: args
};
}
getValue({
fn: fn,
args: args
}) {
return Object.keys(args.named).length > 0 ? fn(...args.positional, args.named) : fn(...args.positional);
}
getDebugName(fn) {
return fn.name ? `(helper function ${fn.name})` : "(anonymous helper function)";
}
}
const COMPONENT_MANAGERS = new WeakMap(),
MODIFIER_MANAGERS = new WeakMap(),
HELPER_MANAGERS = new WeakMap(),
getPrototypeOf$1 = Object.getPrototypeOf;
function setManager(map, manager, obj) {
return map.set(obj, manager), obj;
}
function getManager(map, obj) {
let pointer = obj;
for (; null != pointer;) {
const manager = map.get(pointer);
if (void 0 !== manager) return manager;
pointer = getPrototypeOf$1(pointer);
}
}
///////////
function setInternalModifierManager(manager, definition) {
return setManager(MODIFIER_MANAGERS, manager, definition);
}
function getInternalModifierManager(definition, isOptional) {
const manager = getManager(MODIFIER_MANAGERS, definition);
if (void 0 === manager) {
if (!0 === isOptional) return null;
}
return manager;
}
function setInternalHelperManager(manager, definition) {
return setManager(HELPER_MANAGERS, manager, definition);
}
const DEFAULT_MANAGER = new CustomHelperManager(() => new FunctionHelperManager());
function getInternalHelperManager(definition, isOptional) {
let manager = getManager(HELPER_MANAGERS, definition);
// Functions are special-cased because functions are defined
// as the "default" helper, per: https://github.com/emberjs/rfcs/pull/756
if (void 0 === manager && "function" == typeof definition && (manager = DEFAULT_MANAGER), manager) return manager;
if (!0 === isOptional) return null;
return null;
}
function setInternalComponentManager(factory, obj) {
return setManager(COMPONENT_MANAGERS, factory, obj);
}
function getInternalComponentManager(definition, isOptional) {
const manager = getManager(COMPONENT_MANAGERS, definition);
if (void 0 === manager) {
if (!0 === isOptional) return null;
}
return manager;
}
///////////
function hasInternalComponentManager(definition) {
return void 0 !== getManager(COMPONENT_MANAGERS, definition);
}
function hasInternalHelperManager(definition) {
return function (definition) {
return "function" == typeof definition;
}(definition) || void 0 !== getManager(HELPER_MANAGERS, definition);
}
function hasInternalModifierManager(definition) {
return void 0 !== getManager(MODIFIER_MANAGERS, definition);
}
const CAPABILITIES$4 = {
dynamicLayout: !1,
dynamicTag: !1,
prepareArgs: !1,
createArgs: !0,
attributeHook: !1,
elementHook: !1,
createCaller: !1,
dynamicScope: !0,
updateHook: !0,
createInstance: !0,
wrapped: !1,
willDestroy: !1,
hasSubOwner: !1
};
function componentCapabilities(managerAPI, options = {}) {
let updateHook = Boolean(options.updateHook);
return buildCapabilities({
asyncLifeCycleCallbacks: Boolean(options.asyncLifecycleCallbacks),
destructor: Boolean(options.destructor),
updateHook: updateHook
});
}
function hasAsyncLifeCycleCallbacks(delegate) {
return delegate.capabilities.asyncLifeCycleCallbacks;
}
function hasUpdateHook(delegate) {
return delegate.capabilities.updateHook;
}
/**
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 {
componentManagerDelegates = new WeakMap();
constructor(factory) {
this.factory = factory;
}
getDelegateFor(owner) {
let {
componentManagerDelegates: componentManagerDelegates
} = this,
delegate = componentManagerDelegates.get(owner);
if (void 0 === delegate) {
let {
factory: factory
} = this;
if (delegate = factory(owner), false /* DEBUG */ )
// TODO: This error message should make sense in both Ember and Glimmer https://github.com/glimmerjs/glimmer-vm/issues/1200
;
componentManagerDelegates.set(owner, delegate);
}
return delegate;
}
create(owner, definition, vmArgs) {
let delegate = this.getDelegateFor(owner),
args = argsProxyFor(vmArgs.capture()),
component = delegate.createComponent(definition, args);
return new CustomComponentState(component, delegate, args);
}
getDebugName(definition) {
return "function" == typeof definition ? definition.name : definition.toString();
}
update(bucket) {
let {
delegate: delegate
} = bucket;
if (hasUpdateHook(delegate)) {
let {
component: component,
args: args
} = bucket;
delegate.updateComponent(component, args);
}
}
didCreate({
component: component,
delegate: delegate
}) {
hasAsyncLifeCycleCallbacks(delegate) && delegate.didCreateComponent(component);
}
didUpdate({
component: component,
delegate: delegate
}) {
(function (delegate) {
return hasAsyncLifeCycleCallbacks(delegate) && hasUpdateHook(delegate);
})(delegate) && delegate.didUpdateComponent(component);
}
didRenderLayout() {}
didUpdateLayout() {}
getSelf({
component: component,
delegate: delegate
}) {
return createConstRef(delegate.getContext(component));
}
getDestroyable(bucket) {
const {
delegate: delegate
} = bucket;
if (function (delegate) {
return delegate.capabilities.destructor;
}(delegate)) {
const {
component: component
} = bucket;
return registerDestructor$1(bucket, () => delegate.destroyComponent(component)), bucket;
}
return null;
}
getCapabilities() {
return CAPABILITIES$4;
}
}
/**
* Stores internal state about a component instance after it's been created.
*/
class CustomComponentState {
constructor(component, delegate, args) {
this.component = component, this.delegate = delegate, this.args = args;
}
}
function modifierCapabilities(managerAPI, optionalFeatures = {}) {
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 {
componentManagerDelegates = new WeakMap();
constructor(factory) {
this.factory = factory;
}
getDelegateFor(owner) {
let {
componentManagerDelegates: componentManagerDelegates
} = this,
delegate = componentManagerDelegates.get(owner);
if (void 0 === delegate) {
let {
factory: factory
} = this;
if (delegate = factory(owner), false /* DEBUG */ )
// TODO: This error message should make sense in both Ember and Glimmer https://github.com/glimmerjs/glimmer-vm/issues/1200
;
componentManagerDelegates.set(owner, delegate);
}
return delegate;
}
create(owner, element, definition, capturedArgs) {
let state,
delegate = this.getDelegateFor(owner),
args = argsProxyFor(capturedArgs),
instance = delegate.createModifier(definition, args);
return state = {
tag: createUpdatableTag(),
element: element,
delegate: delegate,
args: args,
modifier: instance
}, registerDestructor$1(state, () => delegate.destroyModifier(instance, args)), state;
}
getDebugName(definition) {
return "function" == typeof definition ? definition.name || definition.toString() : "<unknown>";
}
getDebugInstance({
modifier: modifier
}) {
return modifier;
}
getTag({
tag: tag
}) {
return tag;
}
install({
element: element,
args: args,
modifier: modifier,
delegate: delegate
}) {
let {
capabilities: capabilities
} = delegate;
!0 === capabilities.disableAutoTracking ? untrack(() => delegate.installModifier(modifier, castToBrowser(element, "ELEMENT"), args)) : delegate.installModifier(modifier, castToBrowser(element, "ELEMENT"), args);
}
update({
args: args,
modifier: modifier,
delegate: delegate
}) {
let {
capabilities: capabilities
} = delegate;
!0 === capabilities.disableAutoTracking ? untrack(() => delegate.updateModifier(modifier, args)) : delegate.updateModifier(modifier, args);
}
getDestroyable(state) {
return state;
}
}
function setComponentManager$1(factory, obj) {
return setInternalComponentManager(new CustomComponentManager(factory), obj);
}
function setModifierManager$1(factory, obj) {
return setInternalModifierManager(new CustomModifierManager(factory), obj);
}
function setHelperManager$1(factory, obj) {
return setInternalHelperManager(new CustomHelperManager(factory), obj);
}
const TEMPLATES$1 = new WeakMap(),
getPrototypeOf$2 = Object.getPrototypeOf;
function setComponentTemplate(factory, obj) {
return TEMPLATES$1.set(obj, factory), obj;
}
function getComponentTemplate(obj) {
let pointer = obj;
for (; null !== pointer;) {
let template = TEMPLATES$1.get(pointer);
if (void 0 !== template) return template;
pointer = getPrototypeOf$2(pointer);
}
}
const glimmerManager = /*#__PURE__*/Object.defineProperty({
__proto__: null,
CustomComponentManager,
CustomHelperManager,
CustomModifierManager,
capabilityFlagsFrom,
componentCapabilities,
getComponentTemplate,
getCustomTagFor,
getInternalComponentManager,
getInternalHelperManager,
getInternalModifierManager,
hasCapability,
hasDestroyable,
hasInternalComponentManager,
hasInternalHelperManager,
hasInternalModifierManager,
hasValue,
helperCapabilities,
managerHasCapability,
modifierCapabilities,
setComponentManager: setComponentManager$1,
setComponentTemplate,
setCustomTagFor,
setHelperManager: setHelperManager$1,
setInternalComponentManager,
setInternalHelperManager,
setInternalModifierManager,
setModifierManager: setModifierManager$1
}, Symbol.toStringTag, { value: 'Module' });
/* This file is generated by build/debug.js */
let debugCompiler;
function makeResolutionTypeVerifier(typeToVerify) {
return opcode => {
if (!function (opcode) {
return Array.isArray(opcode) && 2 === opcode.length;
}(opcode)) return !1;
let type = opcode[0];
return type === opcodes.GetStrictKeyword || type === opcodes.GetLexicalSymbol || type === typeToVerify;
};
}
new Array(Op.Size).fill(null), new Array(Op.Size).fill(null);
const isGetFreeComponent = makeResolutionTypeVerifier(opcodes.GetFreeAsComponentHead),
isGetFreeModifier = makeResolutionTypeVerifier(opcodes.GetFreeAsModifierHead),
isGetFreeHelper = makeResolutionTypeVerifier(opcodes.GetFreeAsHelperHead),
isGetFreeComponentOrHelper = makeResolutionTypeVerifier(opcodes.GetFreeAsComponentOrHelperHead);
function assertResolverInvariants(meta) {
return meta;
}
/**
* <Foo/>
* <Foo></Foo>
* <Foo @arg={{true}} />
*/
function lookupBuiltInHelper(expr, resolver, meta, constants, type) {
let {
upvars: upvars
} = assertResolverInvariants(meta),
name = unwrap$1(upvars[expr[1]]),
helper = resolver.lookupBuiltInHelper(name);
return constants.helper(helper, name);
}
const HighLevelResolutionOpcodes = {
Modifier: 1003,
Component: 1004,
Helper: 1005,
ComponentOrHelper: 1007,
OptionalComponentOrHelper: 1008,
Local: 1010,
TemplateLocal: 1011
},
HighLevelBuilderOpcodes = {
Label: 1e3,
StartLabels: 1001,
StopLabels: 1002,
Start: 1e3,
End: 1002
},
HighLevelOperands = {
Label: 1,
IsStrictMode: 2,
DebugSymbols: 3,
Block: 4,
StdLib: 5,
NonSmallInt: 6,
SymbolTable: 7,
Layout: 8
};
function labelOperand(value) {
return {
type: HighLevelOperands.Label,
value: value
};
}
function isStrictMode() {
return {
type: HighLevelOperands.IsStrictMode,
value: void 0
};
}
function stdlibOperand(value) {
return {
type: HighLevelOperands.StdLib,
value: value
};
}
function symbolTableOperand(value) {
return {
type: HighLevelOperands.SymbolTable,
value: value
};
}
function layoutOperand(value) {
return {
type: HighLevelOperands.Layout,
value: value
};
}
class Labels {
labels = dict();
targets = [];
label(name, index) {
this.labels[name] = index;
}
target(at, target) {
this.targets.push({
at: at,
target: target
});
}
patch(heap) {
let {
targets: targets,
labels: labels
} = this;
for (const {
at: at,
target: target
} of targets) {
let address = labels[target] - at;
debugAssert(-1 === heap.getbyaddr(at), "Expected heap to contain a placeholder, but it did not"), heap.setbyaddr(at, address);
}
}
}
function encodeOp(encoder, constants, resolver, meta, op) {
if (function (op) {
return op < HighLevelBuilderOpcodes.Start;
}(op[0])) {
let [type, ...operands] = op;
encoder.push(constants, type, ...operands);
} else switch (op[0]) {
case HighLevelBuilderOpcodes.Label:
return encoder.label(op[1]);
case HighLevelBuilderOpcodes.StartLabels:
return encoder.startLabels();
case HighLevelBuilderOpcodes.StopLabels:
return encoder.stopLabels();
case HighLevelResolutionOpcodes.Component:
return function (resolver, constants, meta, [, expr, then]) {
debugAssert(isGetFreeComponent(expr), "Attempted to resolve a component with incorrect opcode");
let type = expr[0];
if (type === opcodes.GetLexicalSymbol) {
let {
scopeValues: scopeValues,
owner: owner
} = meta,
definition = expect(scopeValues, "BUG: scopeValues must exist if template symbol is used")[expr[1]];
then(constants.component(definition, expect(owner, "BUG: expected owner when resolving component definition")));
} else {
let {
upvars: upvars,
owner: owner
} = assertResolverInvariants(meta),
name = unwrap$1(upvars[expr[1]]),
definition = resolver.lookupComponent(name, owner);
then(constants.resolvedComponent(definition, name));
}
}
/**
* (helper)
* (helper arg)
*/(resolver, constants, meta, op);
case HighLevelResolutionOpcodes.Modifier:
/**
* <div {{modifier}}/>
* <div {{modifier arg}}/>
* <Foo {{modifier}}/>
*/
return function (resolver, constants, meta, [, expr, then]) {
debugAssert(isGetFreeModifier(expr), "Attempted to resolve a modifier with incorrect opcode");
let type = expr[0];
if (type === opcodes.GetLexicalSymbol) {
let {
scopeValues: scopeValues
} = meta,
definition = expect(scopeValues, "BUG: scopeValues must exist if template symbol is used")[expr[1]];
then(constants.modifier(definition));
} else if (type === opcodes.GetStrictKeyword) {
let {
upvars: upvars
} = assertResolverInvariants(meta),
name = unwrap$1(upvars[expr[1]]),
modifier = resolver.lookupBuiltInModifier(name);
then(constants.modifier(modifier, name));
} else {
let {
upvars: upvars,
owner: owner
} = assertResolverInvariants(meta),
name = unwrap$1(upvars[expr[1]]),
modifier = resolver.lookupModifier(name, owner);
then(constants.modifier(modifier, name));
}
}
/**
* {{component-or-helper arg}}
*/(resolver, constants, meta, op);
case HighLevelResolutionOpcodes.Helper:
return function (resolver, constants, meta, [, expr, then]) {
debugAssert(isGetFreeHelper(expr), "Attempted to resolve a helper with incorrect opcode");
let type = expr[0];
if (type === opcodes.GetLexicalSymbol) {
let {
scopeValues: scopeValues
} = meta,
definition = expect(scopeValues, "BUG: scopeValues must exist if template symbol is used")[expr[1]];
then(constants.helper(definition));
} else if (type === opcodes.GetStrictKeyword) then(lookupBuiltInHelper(expr, resolver, meta, constants));else {
let {
upvars: upvars,
owner: owner
} = assertResolverInvariants(meta),
name = unwrap$1(upvars[expr[1]]),
helper = resolver.lookupHelper(name, owner);
then(constants.helper(helper, name));
}
}(resolver, constants, meta, op);
case HighLevelResolutionOpcodes.ComponentOrHelper:
return function (resolver, constants, meta, [, expr, {
ifComponent: ifComponent,
ifHelper: ifHelper
}]) {
debugAssert(isGetFreeComponentOrHelper(expr), "Attempted to resolve a component or helper with incorrect opcode");
let type = expr[0];
if (type === opcodes.GetLexicalSymbol) {
let {
scopeValues: scopeValues,
owner: owner
} = meta,
definition = expect(scopeValues, "BUG: scopeValues must exist if template symbol is used")[expr[1]],
component = constants.component(definition, expect(owner, "BUG: expected owner when resolving component definition"), !0);
if (null !== component) return void ifComponent(component);
let helper = constants.helper(definition, null, !0);
ifHelper(expect(helper, "BUG: helper must exist"));
} else if (type === opcodes.GetStrictKeyword) ifHelper(lookupBuiltInHelper(expr, resolver, meta, constants));else {
let {
upvars: upvars,
owner: owner
} = assertResolverInvariants(meta),
name = unwrap$1(upvars[expr[1]]),
definition = resolver.lookupComponent(name, owner);
if (null !== definition) ifComponent(constants.resolvedComponent(definition, name));else {
let helper = resolver.lookupHelper(name, owner);
ifHelper(constants.helper(helper, name));
}
}
}
/**
* {{maybeHelperOrComponent}}
*/(resolver, constants, meta, op);
case HighLevelResolutionOpcodes.OptionalComponentOrHelper:
return function (resolver, constants, meta, [, expr, {
ifComponent: ifComponent,
ifHelper: ifHelper,
ifValue: ifValue
}]) {
debugAssert(isGetFreeComponentOrHelper(expr), "Attempted to resolve an optional component or helper with incorrect opcode");
let type = expr[0];
if (type === opcodes.GetLexicalSymbol) {
let {
scopeValues: scopeValues,
owner: owner
} = meta,
definition = expect(scopeValues, "BUG: scopeValues must exist if template symbol is used")[expr[1]];
if ("function" != typeof definition && ("object" != typeof definition || null === definition))
// The value is not an object, so it can't be a component or helper.
return void ifValue(constants.value(definition));
let component = constants.component(definition, expect(owner, "BUG: expected owner when resolving component definition"), !0);
if (null !== component) return void ifComponent(component);
let helper = constants.helper(definition, null, !0);
if (null !== helper) return void ifHelper(helper);
ifValue(constants.value(definition));
} else if (type === opcodes.GetStrictKeyword) ifHelper(lookupBuiltInHelper(expr, resolver, meta, constants));else {
let {
upvars: upvars,
owner: owner
} = assertResolverInvariants(meta),
name = unwrap$1(upvars[expr[1]]),
definition = resolver.lookupComponent(name, owner);
if (null !== definition) return void ifComponent(constants.resolvedComponent(definition, name));
let helper = resolver.lookupHelper(name, owner);
null !== helper && ifHelper(constants.helper(helper, name));
}
}(resolver, constants, meta, op);
case HighLevelResolutionOpcodes.Local:
{
let freeVar = op[1],
name = expect(meta.upvars, "BUG: attempted to resolve value but no upvars found")[freeVar];
(0, op[2])(name, meta.moduleName);
break;
}
case HighLevelResolutionOpcodes.TemplateLocal:
{
let [, valueIndex, then] = op,
value = expect(meta.scopeValues, "BUG: Attempted to get a template local, but template does not have any")[valueIndex];
then(constants.value(value));
break;
}
default:
throw new Error(`Unexpected high level opcode ${op[0]}`);
}
}
class EncoderImpl {
labelsStack = new StackImpl();
encoder = new InstructionEncoderImpl([]);
errors = [];
handle;
constructor(heap, meta, stdlib) {
this.heap = heap, this.meta = meta, this.stdlib = stdlib, this.handle = heap.malloc();
}
error(error) {
this.encoder.encode(Op.Primitive, 0), this.errors.push(error);
}
commit(size) {
let handle = this.handle;
return this.heap.pushMachine(MachineOp.Return), this.heap.finishMalloc(handle, size), isPresentArray(this.errors) ? {
errors: this.errors,
handle: handle
} : handle;
}
push(constants, type, ...args) {
let {
heap: heap
} = this;
let first = type | (isMachineOp(type) ? MACHINE_MASK : 0) | args.length << ARG_SHIFT;
heap.pushRaw(first);
for (let i = 0; i < args.length; i++) {
let op = args[i];
heap.pushRaw(this.operand(constants, op));
}
}
operand(constants, operand) {
if ("number" == typeof operand) return operand;
if ("object" == typeof operand && null !== operand) {
if (Array.isArray(operand)) return encodeHandle(constants.array(operand));
switch (operand.type) {
case HighLevelOperands.Label:
return this.currentLabels.target(this.heap.offset, operand.value), -1;
case HighLevelOperands.IsStrictMode:
return encodeHandle(constants.value(this.meta.isStrictMode));
case HighLevelOperands.DebugSymbols:
return encodeHandle(constants.array(this.meta.evalSymbols || EMPTY_STRING_ARRAY));
case HighLevelOperands.Block:
return encodeHandle(constants.value((block = operand.value, containing = this.meta, new CompilableTemplateImpl(block[0], containing, {
parameters: block[1] || EMPTY_ARRAY$4
}))));
case HighLevelOperands.StdLib:
return expect(this.stdlib, "attempted to encode a stdlib operand, but the encoder did not have a stdlib. Are you currently building the stdlib?")[operand.value];
case HighLevelOperands.NonSmallInt:
case HighLevelOperands.SymbolTable:
case HighLevelOperands.Layout:
return constants.value(operand.value);
}
}
var block, containing;
return encodeHandle(constants.value(operand));
}
get currentLabels() {
return expect(this.labelsStack.current, "bug: not in a label stack");
}
label(name) {
this.currentLabels.label(name, this.heap.offset + 1);
}
startLabels() {
this.labelsStack.push(new Labels());
}
stopLabels() {
expect(this.labelsStack.pop(), "unbalanced push and pop labels").patch(this.heap);
}
}
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;
}
}
class NamedBlocksImpl {
names;
constructor(blocks) {
this.blocks = blocks, this.names = blocks ? Object.keys(blocks) : [];
}
get(name) {
return this.blocks && this.blocks[name] || null;
}
has(name) {
let {
blocks: blocks
} = this;
return null !== blocks && name in blocks;
}
with(name, block) {
let {
blocks: blocks
} = this;
return new NamedBlocksImpl(blocks ? assign({}, blocks, {
[name]: block
}) : {
[name]: block
});
}
get hasAny() {
return null !== this.blocks;
}
}
const EMPTY_BLOCKS = new NamedBlocksImpl(null);
function namedBlocks(blocks) {
if (null === blocks) return EMPTY_BLOCKS;
let out = dict(),
[keys, values] = blocks;
for (const [i, key] of enumerate(keys)) out[key] = unwrap$1(values[i]);
return new NamedBlocksImpl(out);
}
/**
* 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(Op.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) {
let p = primitive;
var value;
"number" == typeof p && (p = isSmallInt(p) ? encodeImmediate(p) : (debugAssert(!isSmallInt(value = p), "Attempted to make a operand for an int that was not a small int, you should encode this as an immediate"), {
type: HighLevelOperands.NonSmallInt,
value: value
})), op(Op.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(MachineOp.PushFrame), SimpleArgs(op, positional, named, !1), op(Op.Helper, handle), op(MachineOp.PopFrame), op(Op.Fetch, $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(MachineOp.PushFrame), SimpleArgs(op, positional, named, !1), op(Op.Dup, $fp, 1), op(Op.DynamicHelper), append ? (op(Op.Fetch, $v0), append(), op(MachineOp.PopFrame), op(Op.Pop, 1)) : (op(MachineOp.PopFrame), op(Op.Pop, 1), op(Op.Fetch, $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 Curry(op, type, definition, positional, named) {
op(MachineOp.PushFrame), SimpleArgs(op, positional, named, !1), op(Op.CaptureArgs), expr(op, definition), op(Op.Curry, type, isStrictMode()), op(MachineOp.PopFrame), op(Op.Fetch, $v0);
}
class Compilers {
names = {};
funcs = [];
add(name, func) {
this.names[name] = this.funcs.push(func) - 1;
}
compile(op, sexp) {
let name = sexp[0],
index = unwrap$1(this.names[name]),
func = this.funcs[index];
debugAssert(!!func, `expected an implementation for ${sexp[0]}`), func(op, sexp);
}
}
const EXPRESSIONS = new Compilers();
function withPath(op, path) {
if (void 0 !== path && 0 !== path.length) for (let i = 0; i < path.length; i++) op(Op.GetProperty, path[i]);
}
function expr(op, expression) {
Array.isArray(expression) ? EXPRESSIONS.compile(op, expression) : (PushPrimitive(op, expression), op(Op.PrimitiveReference));
}
/**
* Compile arguments, pushing an Arguments object onto the stack.
*
* @param args.params
* @param args.hash
* @param args.blocks
* @param args.atNames
*/
function SimpleArgs(op, positional, named, atNames) {
if (null === positional && null === named) return void op(Op.PushEmptyArgs);
let flags = CompilePositional(op, positional) << 4;
atNames && (flags |= 8);
let names = EMPTY_STRING_ARRAY;
if (named) {
names = named[0];
let val = named[1];
for (let i = 0; i < val.length; i++) expr(op, val[i]);
}
op(Op.PushArgs, names, 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 (null === positional) return 0;
for (let i = 0; i < positional.length; i++) expr(op, positional[i]);
return positional.length;
}
function meta$1(layout) {
let [, symbols,, upvars] = layout.block;
return {
evalSymbols: evalSymbols(layout),
upvars: upvars,
scopeValues: layout.scope?.() ?? null,
isStrictMode: layout.isStrictMode,
moduleName: layout.moduleName,
owner: layout.owner,
size: symbols.length
};
}
function evalSymbols(layout) {
let {
block: block
} = layout,
[, symbols, hasEval] = block;
return hasEval ? symbols : null;
}
/**
* 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, !0), op(Op.GetBlock, to), op(Op.SpreadBlock), op(Op.CompileBlock), op(Op.InvokeYield), op(Op.PopScope), op(MachineOp.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) {
!function (op, parameters) {
null !== parameters ? op(Op.PushSymbolTable, symbolTableOperand({
parameters: parameters
})) : PushPrimitive(op, null);
}(op, block && block[1]), op(Op.PushBlockScope), PushCompilable(op, block);
}
/**
* Invoke a block that is known statically at compile time.
*
* @param block a Compilable block
*/
function InvokeStaticBlock(op, block) {
op(MachineOp.PushFrame), PushCompilable(op, block), op(Op.CompileBlock), op(MachineOp.InvokeVirtual), op(MachineOp.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) {
let parameters = block[1],
calleeCount = parameters.length,
count = Math.min(callerCount, calleeCount);
if (0 !== count) {
if (op(MachineOp.PushFrame), count) {
op(Op.ChildScope);
for (let i = 0; i < count; i++) op(Op.Dup, $fp, callerCount - i), op(Op.SetVariable, parameters[i]);
}
PushCompilable(op, block), op(Op.CompileBlock), op(MachineOp.InvokeVirtual), count && op(Op.PopScope), op(MachineOp.PopFrame);
} else InvokeStaticBlock(op, block);
}
function PushCompilable(op, _block) {
var value;
null === _block ? PushPrimitive(op, null) : op(Op.Constant, (value = _block, {
type: HighLevelOperands.Block,
value: value
}));
}
function SwitchCases(op, bootstrap, matcher) {
// Setup the switch DSL
let clauses = [],
count = 0;
// Call the callback
matcher(function (match, callback) {
clauses.push({
match: match,
callback: callback,
label: "CLAUSE" + count++
});
}),
// Emit the opcodes for the switch
op(Op.Enter, 1), bootstrap(), op(HighLevelBuilderOpcodes.StartLabels);
// First, emit the jump opcodes. We don't need a jump for the last
// opcode, since it bleeds directly into its clause.
for (let clause of clauses.slice(0, -1)) op(Op.JumpEq, labelOperand(clause.label), clause.match);
// Enumerate the clauses in reverse order. Earlier matches will
// require fewer checks.
for (let i = clauses.length - 1; i >= 0; i--) {
let clause = unwrap$1(clauses[i]);
op(HighLevelBuilderOpcodes.Label, clause.label), op(Op.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.
0 !== i && op(MachineOp.Jump, labelOperand("END"));
}
op(HighLevelBuilderOpcodes.Label, "END"), op(HighLevelBuilderOpcodes.StopLabels), op(Op.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(HighLevelBuilderOpcodes.StartLabels), op(MachineOp.PushFrame),
// If the body invokes a block, its return will return to
// END. Otherwise, the return in RETURN will return to END.
op(MachineOp.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.
let 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(Op.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(HighLevelBuilderOpcodes.Label, "FINALLY"),
// Finalize the DOM.
op(Op.Exit),
// In initial execution, this is a noop: it returns to the
// immediately following opcode. In updating execution, this
// exits the updating routine.
op(MachineOp.Return),
// Cleanup code for the block. Runs on initial execution
// but not on updating.
op(HighLevelBuilderOpcodes.Label, "ENDINITIAL"), op(MachineOp.PopFrame), op(HighLevelBuilderOpcodes.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(Op.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(MachineOp.Jump, labelOperand("FINALLY")), op(HighLevelBuilderOpcodes.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.
void 0 !== ifFalse && ifFalse();
});
}
// {{component}}
// <Component>
// chokepoint
function InvokeComponent(op, component, _elementBlock, positional, named, _blocks) {
let {
compilable: compilable,
capabilities: capabilities,
handle: handle
} = component,
elementBlock = _elementBlock ? [_elementBlock, []] : null,
blocks = Array.isArray(_blocks) || null === _blocks ? namedBlocks(_blocks) : _blocks;
compilable ? (op(Op.PushComponentDefinition, handle), function (op, {
capabilities: capabilities,
layout: layout,
elementBlock: elementBlock,
positional: positional,
named: named,
blocks: blocks
}) {
let {
symbolTable: symbolTable
} = layout;
if (symbolTable.hasEval || hasCapability(capabilities, InternalComponentCapabilities.prepareArgs)) return void InvokeNonStaticComponent(op, {
capabilities: capabilities,
elementBlock: elementBlock,
positional: positional,
named: named,
atNames: !0,
blocks: blocks,
layout: layout
});
op(Op.Fetch, $s0), op(Op.Dup, $sp, 1), op(Op.Load, $s0), op(MachineOp.PushFrame);
// Setup arguments
let {
symbols: symbols
} = symbolTable,
blockSymbols = [],
argSymbols = [],
argNames = [],
blockNames = blocks.names;
// 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
// Starting with the attrs block, if it exists and is referenced in the component
if (null !== elementBlock) {
let symbol = symbols.indexOf("&attrs");
-1 !== symbol && (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 (const name of blockNames) {
let symbol = symbols.indexOf(`&${name}`);
-1 !== symbol && (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 (hasCapability(capabilities, InternalComponentCapabilities.createArgs)) {
// First we push positional arguments
let flags = CompilePositional(op, positional) << 4;
// setup the flags with the count of positionals, and to indicate that atNames
// are used
flags |= 8;
let names = 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 (null !== named) {
names = named[0];
let val = named[1];
for (let i = 0; i < val.length; i++) {
let symbol = symbols.indexOf(unwrap$1(names[i]));
expr(op, val[i]), argSymbols.push(symbol);
}
}
// 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(Op.PushArgs, names, 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 (null !== named) {
// 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).
let names = named[0],
val = named[1];
for (let i = 0; i < val.length; i++) {
let name = unwrap$1(names[i]),
symbol = symbols.indexOf(name);
-1 !== symbol && (expr(op, val[i]), argSymbols.push(symbol), argNames.push(name));
}
}
op(Op.BeginComponentTransaction, $s0), hasCapability(capabilities, InternalComponentCapabilities.dynamicScope) && op(Op.PushDynamicScope), hasCapability(capabilities, InternalComponentCapabilities.createInstance) && op(Op.CreateComponent, 0 | blocks.has("default"), $s0), op(Op.RegisterComponentDestructor, $s0), hasCapability(capabilities, InternalComponentCapabilities.createArgs) ? op(Op.GetComponentSelf, $s0) : op(Op.GetComponentSelf, $s0, argNames),
// Setup the new root scope for the component
op(Op.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(Op.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 (const symbol of reverse(argSymbols))
// for (let i = argSymbols.length - 1; i >= 0; i--) {
// let symbol = argSymbols[i];
-1 === symbol ?
// The expression was not bound to a local symbol, it was only pushed to be
// used with VM args in the javascript side
op(Op.Pop, 1) : op(Op.SetVariable, symbol + 1);
// if any positional params exist, pop them off the stack as well
null !== positional && op(Op.Pop, positional.length);
// Finish up by popping off and assigning blocks
for (const symbol of reverse(blockSymbols)) op(Op.SetBlock, symbol + 1);
op(Op.Constant, layoutOperand(layout)), op(Op.CompileBlock), op(MachineOp.InvokeVirtual), op(Op.DidRenderLayout, $s0), op(MachineOp.PopFrame), op(Op.PopScope), hasCapability(capabilities, InternalComponentCapabilities.dynamicScope) && op(Op.PopDynamicScope), op(Op.CommitComponentTransaction), op(Op.Load, $s0);
}(op, {
capabilities: capabilities,
layout: compilable,
elementBlock: elementBlock,
positional: positional,
named: named,
blocks: blocks
})) : (op(Op.PushComponentDefinition, handle), InvokeNonStaticComponent(op, {
capabilities: capabilities,
elementBlock: elementBlock,
positional: positional,
named: named,
atNames: !0,
blocks: blocks
}));
}
function InvokeDynamicComponent(op, definition, _elementBlock, positional, named, _blocks, atNames, curried) {
let elementBlock = _elementBlock ? [_elementBlock, []] : null,
blocks = Array.isArray(_blocks) || null === _blocks ? namedBlocks(_blocks) : _blocks;
Replayable(op, () => (expr(op, definition), op(Op.Dup, $sp, 0), 2), () => {
op(Op.JumpUnless, labelOperand("ELSE")), curried ? op(Op.ResolveCurriedComponent) : op(Op.ResolveDynamicComponent, isStrictMode()), op(Op.PushDynamicComponentInstance), InvokeNonStaticComponent(op, {
capabilities: !0,
elementBlock: elementBlock,
positional: positional,
named: named,
atNames: atNames,
blocks: blocks
}), op(HighLevelBuilderOpcodes.Label, "ELSE");
});
}
function InvokeNonStaticComponent(op, {
capabilities: capabilities,
elementBlock: elementBlock,
positional: positional,
named: named,
atNames: atNames,
blocks: namedBlocks,
layout: layout
}) {
let bindableBlocks = !!namedBlocks,
bindableAtNames = !0 === capabilities || hasCapability(capabilities, InternalComponentCapabilities.prepareArgs) || !(!named || 0 === named[0].length),
blocks = namedBlocks.with("attrs", elementBlock);
op(Op.Fetch, $s0), op(Op.Dup, $sp, 1), op(Op.Load, $s0), op(MachineOp.PushFrame), function (op, positional, named, blocks, atNames) {
let blockNames = blocks.names;
for (const name of blockNames) PushYieldableBlock(op, blocks.get(name));
let flags = CompilePositional(op, positional) << 4;
atNames && (flags |= 8), blocks && (flags |= 7);
let names = EMPTY_ARRAY$4;
if (named) {
names = named[0];
let val = named[1];
for (let i = 0; i < val.length; i++) expr(op, val[i]);
}
op(Op.PushArgs, names, blockNames, flags);
}(op, positional, named, blocks, atNames), op(Op.PrepareArgs, $s0), invokePreparedComponent(op, blocks.has("default"), bindableBlocks, bindableAtNames, () => {
layout ? (op(Op.PushSymbolTable, symbolTableOperand(layout.symbolTable)), op(Op.Constant, layoutOperand(layout)), op(Op.CompileBlock)) : op(Op.GetComponentLayout, $s0), op(Op.PopulateLayout, $s0);
}), op(Op.Load, $s0);
}
function invokePreparedComponent(op, hasBlock, bindableBlocks, bindableAtNames, populateLayout = null) {
op(Op.BeginComponentTransaction, $s0), op(Op.PushDynamicScope), op(Op.CreateComponent, 0 | hasBlock, $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.
populateLayout && populateLayout(), op(Op.RegisterComponentDestructor, $s0), op(Op.GetComponentSelf, $s0), op(Op.VirtualRootScope, $s0), op(Op.SetVariable, 0), op(Op.SetupForEval, $s0), bindableAtNames && op(Op.SetNamedVariables, $s0), bindableBlocks && op(Op.SetBlocks, $s0), op(Op.Pop, 1), op(Op.InvokeComponentLayout, $s0), op(Op.DidRenderLayout, $s0), op(MachineOp.PopFrame), op(Op.PopScope), op(Op.PopDynamicScope), op(Op.CommitComponentTransaction);
}
/**
* 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(Op.ContentType), when => {
when(ContentType.String, () => {
trusting ? (op(Op.AssertSame), op(Op.AppendHTML)) : op(Op.AppendText);
}), "number" == typeof nonDynamicAppend ? (when(ContentType.Component, () => {
op(Op.ResolveCurriedComponent), op(Op.PushDynamicComponentInstance), function (op) {
op(Op.Fetch, $s0), op(Op.Dup, $sp, 1), op(Op.Load, $s0), op(MachineOp.PushFrame), op(Op.PushEmptyArgs), op(Op.PrepareArgs, $s0), invokePreparedComponent(op, !1, !1, !0, () => {
op(Op.GetComponentLayout, $s0), op(Op.PopulateLayout, $s0);
}), op(Op.Load, $s0);
}(op);
}), when(ContentType.Helper, () => {
CallDynamic(op, null, null, () => {
op(MachineOp.InvokeStatic, nonDynamicAppend);
});
})) : (
// 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(ContentType.Component, () => {
op(Op.AppendText);
}), when(ContentType.Helper, () => {
op(Op.AppendText);
})), when(ContentType.SafeString, () => {
op(Op.AssertSame), op(Op.AppendSafeHTML);
}), when(ContentType.Fragment, () => {
op(Op.AssertSame), op(Op.AppendDocumentFragment);
}), when(ContentType.Node, () => {
op(Op.AssertSame), op(Op.AppendNode);
});
});
}
function compileStd(context) {
let mainHandle = build(context, op => function (op) {
op(Op.Main, $s0), invokePreparedComponent(op, !1, !1, !0);
}(op)),
trustingGuardedNonDynamicAppend = build(context, op => StdAppend(op, !0, null)),
cautiousGuardedNonDynamicAppend = build(context, op => StdAppend(op, !1, null)),
trustingGuardedDynamicAppend = build(context, op => StdAppend(op, !0, trustingGuardedNonDynamicAppend)),
cautiousGuardedDynamicAppend = build(context, op => StdAppend(op, !1, cautiousGuardedNonDynamicAppend));
return new StdLib(mainHandle, trustingGuardedDynamicAppend, cautiousGuardedDynamicAppend, trustingGuardedNonDynamicAppend, cautiousGuardedNonDynamicAppend);
}
EXPRESSIONS.add(opcodes.Concat, (op, [, parts]) => {
for (let part of parts) expr(op, part);
op(Op.Concat, parts.length);
}), EXPRESSIONS.add(opcodes.Call, (op, [, expression, positional, named]) => {
isGetFreeHelper(expression) ? op(HighLevelResolutionOpcodes.Helper, expression, handle => {
Call(op, handle, positional, named);
}) : (expr(op, expression), CallDynamic(op, positional, named));
}), EXPRESSIONS.add(opcodes.Curry, (op, [, expr, type, positional, named]) => {
Curry(op, type, expr, positional, named);
}), EXPRESSIONS.add(opcodes.GetSymbol, (op, [, sym, path]) => {
op(Op.GetVariable, sym), withPath(op, path);
}), EXPRESSIONS.add(opcodes.GetLexicalSymbol, (op, [, sym, path]) => {
op(HighLevelResolutionOpcodes.TemplateLocal, sym, handle => {
op(Op.ConstantReference, handle), withPath(op, path);
});
}), EXPRESSIONS.add(opcodes.GetStrictKeyword, (op, expr) => {
op(HighLevelResolutionOpcodes.Local, expr[1], _name => {
op(HighLevelResolutionOpcodes.Helper, expr, handle => {
Call(op, handle, null, null);
});
});
}), EXPRESSIONS.add(opcodes.GetFreeAsHelperHead, (op, expr) => {
op(HighLevelResolutionOpcodes.Local, expr[1], _name => {
op(HighLevelResolutionOpcodes.Helper, expr, handle => {
Call(op, handle, null, null);
});
});
}), EXPRESSIONS.add(opcodes.Undefined, op => PushPrimitiveReference(op, void 0)), EXPRESSIONS.add(opcodes.HasBlock, (op, [, block]) => {
expr(op, block), op(Op.HasBlock);
}), EXPRESSIONS.add(opcodes.HasBlockParams, (op, [, block]) => {
expr(op, block), op(Op.SpreadBlock), op(Op.CompileBlock), op(Op.HasBlockParams);
}), EXPRESSIONS.add(opcodes.IfInline, (op, [, condition, truthy, falsy]) => {
// Push in reverse order
expr(op, falsy), expr(op, truthy), expr(op, condition), op(Op.IfInline);
}), EXPRESSIONS.add(opcodes.Not, (op, [, value]) => {
expr(op, value), op(Op.Not);
}), EXPRESSIONS.add(opcodes.GetDynamicVar, (op, [, expression]) => {
expr(op, expression), op(Op.GetDynamicVar);
}), EXPRESSIONS.add(opcodes.Log, (op, [, positional]) => {
op(MachineOp.PushFrame), SimpleArgs(op, positional, null, !1), op(Op.Log), op(MachineOp.PopFrame), op(Op.Fetch, $v0);
});
const STDLIB_META = {
evalSymbols: null,
upvars: null,
moduleName: "stdlib",
// TODO: ??
scopeValues: null,
isStrictMode: !0,
owner: null,
size: 0
};
function build(program, builder) {
let {
constants: constants,
heap: heap,
resolver: resolver
} = program,
encoder = new EncoderImpl(heap, STDLIB_META);
builder(function (...op) {
encodeOp(encoder, constants, resolver, STDLIB_META, op);
});
let result = encoder.commit(0);
if ("number" != typeof result)
// This shouldn't be possible
throw new Error("Unexpected errors compiling std");
return result;
}
class CompileTimeCompilationContextImpl {
constants;
heap;
stdlib;
constructor({
constants: constants,
heap: heap
}, resolver, createOp) {
this.resolver = resolver, this.createOp = createOp, this.constants = constants, this.heap = heap, this.stdlib = compileStd(this);
}
}
function programCompilationContext(artifacts, resolver, createOp) {
return new CompileTimeCompilationContextImpl(artifacts, resolver, createOp);
}
function templateCompilationContext(program, meta) {
return {
program: program,
encoder: new EncoderImpl(program.heap, meta, program.stdlib),
meta: meta
};
}
const STATEMENTS = new Compilers(),
INFLATE_ATTR_TABLE = ["class", "id", "value", "name", "type", "style", "href"],
INFLATE_TAG_TABLE = ["div", "span", "p", "a"];
function inflateTagName(tagName) {
return "string" == typeof tagName ? tagName : INFLATE_TAG_TABLE[tagName];
}
function inflateAttrName(attrName) {
return "string" == typeof attrName ? attrName : INFLATE_ATTR_TABLE[attrName];
}
function hashToArgs(hash) {
return null === hash ? null : [hash[0].map(key => `@${key}`), hash[1]];
}
STATEMENTS.add(opcodes.Comment, (op, sexp) => op(Op.Comment, sexp[1])), STATEMENTS.add(opcodes.CloseElement, op => op(Op.CloseElement)), STATEMENTS.add(opcodes.FlushElement, op => op(Op.FlushElement)), STATEMENTS.add(opcodes.Modifier, (op, [, expression, positional, named]) => {
isGetFreeModifier(expression) ? op(HighLevelResolutionOpcodes.Modifier, expression, handle => {
op(MachineOp.PushFrame), SimpleArgs(op, positional, named, !1), op(Op.Modifier, handle), op(MachineOp.PopFrame);
}) : (expr(op, expression), op(MachineOp.PushFrame), SimpleArgs(op, positional, named, !1), op(Op.Dup, $fp, 1), op(Op.DynamicModifier), op(MachineOp.PopFrame));
}), STATEMENTS.add(opcodes.StaticAttr, (op, [, name, value, namespace]) => {
op(Op.StaticAttr, inflateAttrName(name), value, namespace ?? null);
}), STATEMENTS.add(opcodes.StaticComponentAttr, (op, [, name, value, namespace]) => {
op(Op.StaticComponentAttr, inflateAttrName(name), value, namespace ?? null);
}), STATEMENTS.add(opcodes.DynamicAttr, (op, [, name, value, namespace]) => {
expr(op, value), op(Op.DynamicAttr, inflateAttrName(name), !1, namespace ?? null);
}), STATEMENTS.add(opcodes.TrustingDynamicAttr, (op, [, name, value, namespace]) => {
expr(op, value), op(Op.DynamicAttr, inflateAttrName(name), !0, namespace ?? null);
}), STATEMENTS.add(opcodes.ComponentAttr, (op, [, name, value, namespace]) => {
expr(op, value), op(Op.ComponentAttr, inflateAttrName(name), !1, namespace ?? null);
}), STATEMENTS.add(opcodes.TrustingComponentAttr, (op, [, name, value, namespace]) => {
expr(op, value), op(Op.ComponentAttr, inflateAttrName(name), !0, namespace ?? null);
}), STATEMENTS.add(opcodes.OpenElement, (op, [, tag]) => {
op(Op.OpenElement, inflateTagName(tag));
}), STATEMENTS.add(opcodes.OpenElementWithSplat, (op, [, tag]) => {
op(Op.PutComponentOperations), op(Op.OpenElement, inflateTagName(tag));
}), STATEMENTS.add(opcodes.Component, (op, [, expr, elementBlock, named, blocks]) => {
isGetFreeComponent(expr) ? op(HighLevelResolutionOpcodes.Component, expr, component => {
InvokeComponent(op, component, elementBlock, null, named, blocks);
}) :
// otherwise, the component name was an expression, so resolve the expression
// and invoke it as a dynamic component
InvokeDynamicComponent(op, expr, elementBlock, null, named, blocks, !0, !0);
}), STATEMENTS.add(opcodes.Yield, (op, [, to, params]) => YieldBlock(op, to, params)), STATEMENTS.add(opcodes.AttrSplat, (op, [, to]) => YieldBlock(op, to, null)), STATEMENTS.add(opcodes.Debugger, (op, [, debugInfo]) => op(Op.Debugger, {
type: HighLevelOperands.DebugSymbols,
value: void 0
}, debugInfo)), STATEMENTS.add(opcodes.Append, (op, [, value]) => {
// Special case for static values
if (Array.isArray(value)) {
if (isGetFreeComponentOrHelper(value)) op(HighLevelResolutionOpcodes.OptionalComponentOrHelper, value, {
ifComponent(component) {
InvokeComponent(op, component, null, null, null, null);
},
ifHelper(handle) {
op(MachineOp.PushFrame), Call(op, handle, null, null), op(MachineOp.InvokeStatic, stdlibOperand("cautious-non-dynamic-append")), op(MachineOp.PopFrame);
},
ifValue(handle) {
op(MachineOp.PushFrame), op(Op.ConstantReference, handle), op(MachineOp.InvokeStatic, stdlibOperand("cautious-non-dynamic-append")), op(MachineOp.PopFrame);
}
});else if (value[0] === opcodes.Call) {
let [, expression, positional, named] = value;
isGetFreeComponentOrHelper(expression) ? op(HighLevelResolutionOpcodes.ComponentOrHelper, expression, {
ifComponent(component) {
InvokeComponent(op, component, null, positional, hashToArgs(named), null);
},
ifHelper(handle) {
op(MachineOp.PushFrame), Call(op, handle, positional, named), op(MachineOp.InvokeStatic, stdlibOperand("cautious-non-dynamic-append")), op(MachineOp.PopFrame);
}
}) : SwitchCases(op, () => {
expr(op, expression), op(Op.DynamicContentType);
}, when => {
when(ContentType.Component, () => {
op(Op.ResolveCurriedComponent), op(Op.PushDynamicComponentInstance), InvokeNonStaticComponent(op, {
capabilities: !0,
elementBlock: null,
positional: positional,
named: named,
atNames: !1,
blocks: namedBlocks(null)
});
}), when(ContentType.Helper, () => {
CallDynamic(op, positional, named, () => {
op(MachineOp.InvokeStatic, stdlibOperand("cautious-non-dynamic-append"));
});
});
});
} else op(MachineOp.PushFrame), expr(op, value), op(MachineOp.InvokeStatic, stdlibOperand("cautious-append")), op(MachineOp.PopFrame);
} else op(Op.Text, null == value ? "" : String(value));
}), STATEMENTS.add(opcodes.TrustingAppend, (op, [, value]) => {
Array.isArray(value) ? (op(MachineOp.PushFrame), expr(op, value), op(MachineOp.InvokeStatic, stdlibOperand("trusting-append")), op(MachineOp.PopFrame)) : op(Op.Text, null == value ? "" : String(value));
}), STATEMENTS.add(opcodes.Block, (op, [, expr, positional, named, blocks]) => {
isGetFreeComponent(expr) ? op(HighLevelResolutionOpcodes.Component, expr, component => {
InvokeComponent(op, component, null, positional, hashToArgs(named), blocks);
}) : InvokeDynamicComponent(op, expr, null, positional, named, blocks, !1, !1);
}), STATEMENTS.add(opcodes.InElement, (op, [, block, guid, destination, insertBefore]) => {
ReplayableIf(op, () => (expr(op, guid), void 0 === insertBefore ? PushPrimitiveReference(op, void 0) : expr(op, insertBefore), expr(op, destination), op(Op.Dup, $sp, 0), 4), () => {
op(Op.PushRemoteElement), InvokeStaticBlock(op, block), op(Op.PopRemoteElement);
});
}), STATEMENTS.add(opcodes.If, (op, [, condition, block, inverse]) => ReplayableIf(op, () => (expr(op, condition), op(Op.ToBoolean), 1), () => {
InvokeStaticBlock(op, block);
}, inverse ? () => {
InvokeStaticBlock(op, inverse);
} : void 0)), STATEMENTS.add(opcodes.Each, (op, [, value, key, block, inverse]) => Replayable(op, () => (key ? expr(op, key) : PushPrimitiveReference(op, null), expr(op, value), 2), () => {
op(Op.EnterList, labelOperand("BODY"), labelOperand("ELSE")), op(MachineOp.PushFrame), op(Op.Dup, $fp, 1), op(MachineOp.ReturnTo, labelOperand("ITER")), op(HighLevelBuilderOpcodes.Label, "ITER"), op(Op.Iterate, labelOperand("BREAK")), op(HighLevelBuilderOpcodes.Label, "BODY"), InvokeStaticBlockWithStack(op, block, 2), op(Op.Pop, 2), op(MachineOp.Jump, labelOperand("FINALLY")), op(HighLevelBuilderOpcodes.Label, "BREAK"), op(MachineOp.PopFrame), op(Op.ExitList), op(MachineOp.Jump, labelOperand("FINALLY")), op(HighLevelBuilderOpcodes.Label, "ELSE"), inverse && InvokeStaticBlock(op, inverse);
})), STATEMENTS.add(opcodes.Let, (op, [, positional, block]) => {
InvokeStaticBlockWithStack(op, block, CompilePositional(op, positional));
}), STATEMENTS.add(opcodes.WithDynamicVars, (op, [, named, block]) => {
if (named) {
let [names, expressions] = named;
CompilePositional(op, expressions), function (op, names, block) {
op(Op.PushDynamicScope), op(Op.BindDynamicScope, names), block(), op(Op.PopDynamicScope);
}(op, names, () => {
InvokeStaticBlock(op, block);
});
} else InvokeStaticBlock(op, block);
}), STATEMENTS.add(opcodes.InvokeComponent, (op, [, expr, positional, named, blocks]) => {
isGetFreeComponent(expr) ? op(HighLevelResolutionOpcodes.Component, expr, component => {
InvokeComponent(op, component, null, positional, hashToArgs(named), blocks);
}) : InvokeDynamicComponent(op, expr, null, positional, named, blocks, !1, !1);
});
class CompilableTemplateImpl {
compiled = null;
constructor(statements, meta,
// Part of CompilableTemplate
symbolTable,
// Used for debugging
moduleName = "plain block") {
this.statements = statements, this.meta = meta, this.symbolTable = symbolTable, this.moduleName = moduleName;
}
// Part of CompilableTemplate
compile(context) {
return function (compilable, context) {
if (null !== compilable.compiled) return compilable.compiled;
compilable.compiled = -1;
let {
statements: statements,
meta: meta
} = compilable,
result = compileStatements(statements, meta, context);
return compilable.compiled = result, result;
}(this, context);
}
}
function compilable(layout, moduleName) {
let [statements, symbols, hasEval] = layout.block;
return new CompilableTemplateImpl(statements, meta$1(layout), {
symbols: symbols,
hasEval: hasEval
}, moduleName);
}
function compileStatements(statements, meta, syntaxContext) {
let sCompiler = STATEMENTS,
context = templateCompilationContext(syntaxContext, meta),
{
encoder: encoder,
program: {
constants: constants,
resolver: resolver
}
} = context;
function pushOp(...op) {
encodeOp(encoder, constants, resolver, meta, op);
}
for (const statement of statements) sCompiler.compile(pushOp, statement);
return context.encoder.commit(meta.size);
}
const DEFAULT_CAPABILITIES = {
dynamicLayout: !0,
dynamicTag: !0,
prepareArgs: !0,
createArgs: !0,
attributeHook: !1,
elementHook: !1,
dynamicScope: !0,
createCaller: !1,
updateHook: !0,
createInstance: !0,
wrapped: !1,
willDestroy: !1,
hasSubOwner: !1
},
MINIMAL_CAPABILITIES = {
dynamicLayout: !1,
dynamicTag: !1,
prepareArgs: !1,
createArgs: !1,
attributeHook: !1,
elementHook: !1,
dynamicScope: !1,
createCaller: !1,
updateHook: !1,
createInstance: !1,
wrapped: !1,
willDestroy: !1,
hasSubOwner: !1
};
class WrappedBuilder {
symbolTable;
compiled = null;
attrsBlockNumber;
constructor(layout, moduleName) {
this.layout = layout, this.moduleName = moduleName;
let {
block: block
} = layout,
[, symbols, hasEval] = block;
symbols = symbols.slice();
// ensure ATTRS_BLOCK is always included (only once) in the list of symbols
let attrsBlockIndex = symbols.indexOf("&attrs");
this.attrsBlockNumber = -1 === attrsBlockIndex ? symbols.push("&attrs") : attrsBlockIndex + 1, this.symbolTable = {
hasEval: hasEval,
symbols: symbols
};
}
compile(syntax) {
if (null !== this.compiled) return this.compiled;
let m = meta$1(this.layout),
context = templateCompilationContext(syntax, m),
{
encoder: encoder,
program: {
constants: constants,
resolver: resolver
}
} = context;
var op, layout, attrsBlockNumber;
op = function (...op) {
encodeOp(encoder, constants, resolver, m, op);
}, layout = this.layout, attrsBlockNumber = this.attrsBlockNumber, op(HighLevelBuilderOpcodes.StartLabels), function (op, register, block) {
op(Op.Fetch, register), block(), op(Op.Load, register);
}(op, $s1, () => {
op(Op.GetComponentTagName, $s0), op(Op.PrimitiveReference), op(Op.Dup, $sp, 0);
}), op(Op.JumpUnless, labelOperand("BODY")), op(Op.Fetch, $s1), op(Op.PutComponentOperations), op(Op.OpenDynamicElement), op(Op.DidCreateElement, $s0), YieldBlock(op, attrsBlockNumber, null), op(Op.FlushElement), op(HighLevelBuilderOpcodes.Label, "BODY"), InvokeStaticBlock(op, [layout.block[0], []]), op(Op.Fetch, $s1), op(Op.JumpUnless, labelOperand("END")), op(Op.CloseElement), op(HighLevelBuilderOpcodes.Label, "END"), op(Op.Load, $s1), op(HighLevelBuilderOpcodes.StopLabels);
let handle = context.encoder.commit(m.size);
return "number" != typeof handle || (this.compiled = handle), handle;
}
}
let clientId = 0,
templateCacheCounters = {
cacheHit: 0,
cacheMiss: 0
};
// These interfaces are for backwards compatibility, some addons use these intimate APIs
/**
* 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.
*/
function templateFactory({
id: templateId,
moduleName: moduleName,
block: block,
scope: scope,
isStrictMode: 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.
let parsedBlock,
id = templateId || "client-" + clientId++,
ownerlessTemplate = null,
templateCache = new WeakMap(),
factory = owner => {
if (void 0 === parsedBlock && (parsedBlock = JSON.parse(block)), void 0 === owner) return null === ownerlessTemplate ? (templateCacheCounters.cacheMiss++, ownerlessTemplate = new TemplateImpl({
id: id,
block: parsedBlock,
moduleName: moduleName,
owner: null,
scope: scope,
isStrictMode: isStrictMode
})) : templateCacheCounters.cacheHit++, ownerlessTemplate;
let result = templateCache.get(owner);
return void 0 === result ? (templateCacheCounters.cacheMiss++, result = new TemplateImpl({
id: id,
block: parsedBlock,
moduleName: moduleName,
owner: owner,
scope: scope,
isStrictMode: isStrictMode
}), templateCache.set(owner, result)) : templateCacheCounters.cacheHit++, result;
};
// 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.
return factory.__id = id, factory.__meta = {
moduleName: moduleName
}, factory;
}
class TemplateImpl {
result = "ok";
layout = null;
wrappedLayout = null;
constructor(parsedLayout) {
this.parsedLayout = parsedLayout;
}
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() {
return this.layout ? this.layout : this.layout = compilable(assign({}, this.parsedLayout), this.moduleName);
}
asWrappedLayout() {
return this.wrappedLayout ? this.wrappedLayout : this.wrappedLayout = new WrappedBuilder(assign({}, this.parsedLayout), this.moduleName);
}
}
const glimmerOpcodeCompiler = /*#__PURE__*/Object.defineProperty({
__proto__: null,
CompileTimeCompilationContextImpl,
DEFAULT_CAPABILITIES,
EMPTY_BLOCKS,
MINIMAL_CAPABILITIES,
StdLib,
WrappedBuilder,
compilable,
compileStatements,
compileStd,
debugCompiler,
invokeStaticBlock: InvokeStaticBlock,
invokeStaticBlockWithStack: InvokeStaticBlockWithStack,
meta: meta$1,
programCompilationContext,
templateCacheCounters,
templateCompilationContext,
templateFactory
}, Symbol.toStringTag, { value: 'Module' });
const emberTemplateFactoryIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
createTemplateFactory: templateFactory
}, Symbol.toStringTag, { value: 'Module' });
const RootTemplate = templateFactory(
/*
{{component this}}
*/
{
"id": "tjANIXCV",
"block": "[[[46,[30,0],null,null,null]],[],false,[\"component\"]]",
"moduleName": "packages/@ember/-internals/glimmer/lib/templates/root.hbs",
"isStrictMode": true
});
const objectPrototype = Object.prototype;
let counters;
/**
@module ember
*/
const UNDEFINED = symbol('undefined');
var ListenerKind = /*#__PURE__*/function (ListenerKind) {
ListenerKind[ListenerKind["ADD"] = 0] = "ADD";
ListenerKind[ListenerKind["ONCE"] = 1] = "ONCE";
ListenerKind[ListenerKind["REMOVE"] = 2] = "REMOVE";
return ListenerKind;
}(ListenerKind || {});
let currentListenerVersion = 1;
class Meta {
/** @internal */
_descriptors;
/** @internal */
_mixins;
/** @internal */
_isInit;
/** @internal */
_lazyChains;
/** @internal */
_values;
/** @internal */
_revisions;
/** @internal */
source;
/** @internal */
proto;
/** @internal */
_parent;
/** @internal */
_listeners;
/** @internal */
_listenersVersion = 1;
/** @internal */
_inheritedEnd = -1;
/** @internal */
_flattenedVersion = 0;
// DEBUG
/** @internal */
constructor(obj) {
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;
}
/** @internal */
get parent() {
let parent = this._parent;
if (parent === undefined) {
let proto = getPrototypeOf(this.source);
this._parent = parent = proto === null || proto === objectPrototype ? null : meta(proto);
}
return parent;
}
setInitializing() {
this._isInit = true;
}
/** @internal */
unsetInitializing() {
this._isInit = false;
}
/** @internal */
isInitializing() {
return this._isInit;
}
/** @internal */
isPrototypeMeta(obj) {
return this.proto === this.source && this.source === obj;
}
/** @internal */
_getOrCreateOwnMap(key) {
return this[key] || (this[key] = Object.create(null));
}
/** @internal */
_getOrCreateOwnSet(key) {
return this[key] || (this[key] = new Set());
}
/** @internal */
_findInheritedMap(key, subkey) {
let pointer = this;
while (pointer !== null) {
let map = pointer[key];
if (map !== undefined) {
let value = map.get(subkey);
if (value !== undefined) {
return value;
}
}
pointer = pointer.parent;
}
}
/** @internal */
_hasInInheritedSet(key, value) {
let pointer = this;
while (pointer !== null) {
let set = pointer[key];
if (set !== undefined && set.has(value)) {
return true;
}
pointer = pointer.parent;
}
return false;
}
/** @internal */
valueFor(key) {
let values = this._values;
return values !== undefined ? values[key] : undefined;
}
/** @internal */
setValueFor(key, value) {
let values = this._getOrCreateOwnMap('_values');
values[key] = value;
}
/** @internal */
revisionFor(key) {
let revisions = this._revisions;
return revisions !== undefined ? revisions[key] : undefined;
}
/** @internal */
setRevisionFor(key, revision) {
let revisions = this._getOrCreateOwnMap('_revisions');
revisions[key] = revision;
}
/** @internal */
writableLazyChainsFor(key) {
let lazyChains = this._getOrCreateOwnMap('_lazyChains');
let chains = lazyChains[key];
if (chains === undefined) {
chains = lazyChains[key] = [];
}
return chains;
}
/** @internal */
readableLazyChainsFor(key) {
let lazyChains = this._lazyChains;
if (lazyChains !== undefined) {
return lazyChains[key];
}
return undefined;
}
/** @internal */
addMixin(mixin) {
let set = this._getOrCreateOwnSet('_mixins');
set.add(mixin);
}
/** @internal */
hasMixin(mixin) {
return this._hasInInheritedSet('_mixins', mixin);
}
/** @internal */
forEachMixins(fn) {
let pointer = this;
let seen;
while (pointer !== null) {
let 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;
}
}
/** @internal */
writeDescriptors(subkey, value) {
let map = this._descriptors || (this._descriptors = new Map());
map.set(subkey, value);
}
/** @internal */
peekDescriptors(subkey) {
let possibleDesc = this._findInheritedMap('_descriptors', subkey);
return possibleDesc === UNDEFINED ? undefined : possibleDesc;
}
/** @internal */
removeDescriptors(subkey) {
this.writeDescriptors(subkey, UNDEFINED);
}
/** @internal */
forEachDescriptors(fn) {
let pointer = this;
let seen;
while (pointer !== null) {
let 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;
}
}
/** @internal */
addToListeners(eventName, target, method, once, sync) {
this.pushListener(eventName, target, method, once ? ListenerKind.ONCE : ListenerKind.ADD, sync);
}
/** @internal */
removeFromListeners(eventName, target, method) {
this.pushListener(eventName, target, method, ListenerKind.REMOVE);
}
pushListener(event, target, method, kind, sync = false) {
let listeners = this.writableListeners();
let 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) {
listeners.push({
event,
target,
method,
kind,
sync
});
} else {
let listener = listeners[i];
// want to splice it out entirely so we don't hold onto a reference.
if (kind === ListenerKind.REMOVE && listener.kind !== ListenerKind.REMOVE) {
listeners.splice(i, 1);
} else {
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)) {
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 (this._flattenedVersion < currentListenerVersion) {
let parent = this.parent;
if (parent !== null) {
// compute
let parentListeners = parent.flattenedListeners();
if (parentListeners !== undefined) {
if (this._listeners === undefined) {
this._listeners = parentListeners;
} else {
let listeners = this._listeners;
if (this._inheritedEnd > 0) {
listeners.splice(0, this._inheritedEnd);
this._inheritedEnd = 0;
}
for (let listener of parentListeners) {
let index = indexOfListener(listeners, listener.event, listener.target, listener.method);
if (index === -1) {
listeners.unshift(listener);
this._inheritedEnd++;
}
}
}
}
}
this._flattenedVersion = currentListenerVersion;
}
return this._listeners;
}
/** @internal */
matchingListeners(eventName) {
let listeners = this.flattenedListeners();
let result;
if (listeners !== undefined) {
for (let listener of listeners) {
// 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 === ListenerKind.ADD || listener.kind === ListenerKind.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 === ListenerKind.ONCE);
}
}
}
return result;
}
/** @internal */
observerEvents() {
let listeners = this.flattenedListeners();
let result;
if (listeners !== undefined) {
for (let listener of listeners) {
// REMOVE listeners are placeholders that tell us not to
// inherit, so they never match. Only ADD and ONCE can match.
if ((listener.kind === ListenerKind.ADD || listener.kind === ListenerKind.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;
}
}
const getPrototypeOf = Object.getPrototypeOf;
const metaStore = new WeakMap();
function setMeta(obj, meta) {
metaStore.set(obj, meta);
}
function peekMeta(obj) {
let meta = metaStore.get(obj);
if (meta !== undefined) {
return meta;
}
let pointer = getPrototypeOf(obj);
while (pointer !== null) {
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
*/
const meta = function meta(obj) {
let maybeMeta = peekMeta(obj);
// remove this code, in-favor of explicit parent
if (maybeMeta !== null && maybeMeta.source === obj) {
return maybeMeta;
}
let newMeta = new Meta(obj);
setMeta(obj, newMeta);
return newMeta;
};
function indexOfListener(listeners, event, target, method) {
for (let i = listeners.length - 1; i >= 0; i--) {
let listener = listeners[i];
if (listener.event === event && listener.target === target && listener.method === method) {
return i;
}
}
return -1;
}
const emberinternalsMetaLibMeta = /*#__PURE__*/Object.defineProperty({
__proto__: null,
Meta,
UNDEFINED,
counters,
meta,
peekMeta,
setMeta
}, Symbol.toStringTag, { value: 'Module' });
const emberinternalsMetaIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
Meta,
UNDEFINED,
counters,
meta,
peekMeta,
setMeta
}, Symbol.toStringTag, { value: 'Module' });
function objectAt(array, index) {
if (Array.isArray(array)) {
return array[index];
} else {
return array.objectAt(index);
}
}
/////////
// This is exported for `@tracked`, but should otherwise be avoided. Use `tagForObject`.
const SELF_TAG = symbol('SELF_TAG');
function tagForProperty(obj, propertyKey, addMandatorySetter = false, meta) {
let customTagFor = getCustomTagFor(obj);
if (customTagFor !== undefined) {
return customTagFor(obj, propertyKey, addMandatorySetter);
}
let tag = tagFor(obj, propertyKey, meta);
return tag;
}
function tagForObject(obj) {
if (isObject$1(obj)) {
return tagFor(obj, SELF_TAG);
}
return CONSTANT_TAG;
}
function markObjectAsDirty(obj, propertyKey) {
dirtyTagFor(obj, propertyKey);
dirtyTagFor(obj, SELF_TAG);
}
const CHAIN_PASS_THROUGH = new WeakSet();
function finishLazyChains(meta, key, value) {
let lazyTags = meta.readableLazyChainsFor(key);
if (lazyTags === undefined) {
return;
}
if (isObject$1(value)) {
for (let [tag, deps] of lazyTags) {
UPDATE_TAG(tag, getChainTagsForKey(value, deps, tagMetaFor(value), peekMeta(value)));
}
}
lazyTags.length = 0;
}
function getChainTagsForKeys(obj, keys, tagMeta, meta) {
let tags = [];
for (let key of keys) {
getChainTags(tags, obj, key, tagMeta, meta);
}
return combine(tags);
}
function getChainTagsForKey(obj, key, tagMeta, meta) {
return combine(getChainTags([], obj, key, tagMeta, meta));
}
function getChainTags(chainTags, obj, path, tagMeta, meta$1) {
let current = obj;
let currentTagMeta = tagMeta;
let currentMeta = meta$1;
let pathLength = path.length;
let segmentEnd = -1;
// prevent closures
let segment, descriptor;
// eslint-disable-next-line no-constant-condition
while (true) {
let 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);
let 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 (let i = 0; i < arrLength; i++) {
let item = objectAt(current, i);
if (item) {
chainTags.push(tagForProperty(item, segment, true));
currentMeta = 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') {
item[segment];
}
}
}
// Push the tag for the array length itself
chainTags.push(tagForProperty(current, '[]', true, currentTagMeta));
break;
}
let 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)) {
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.
let instanceMeta = currentMeta.source === current ? currentMeta : meta(current);
let lastRevision = instanceMeta.revisionFor(segment);
if (lastRevision !== undefined && validateTag(propertyTag, lastRevision)) {
current = instanceMeta.valueFor(segment);
} else {
// use metaFor here to ensure we have the meta for the instance
let lazyChains = instanceMeta.writableLazyChainsFor(segment);
let rest = path.substring(segmentEnd + 1);
let placeholderTag = createUpdatableTag();
lazyChains.push([placeholderTag, rest]);
chainTags.push(placeholderTag);
break;
}
}
if (!isObject$1(current)) {
// we've hit the end of the chain for now, break out
break;
}
currentTagMeta = tagMetaFor(current);
currentMeta = peekMeta(current);
}
return chainTags;
}
// Same as built-in MethodDecorator but with more arguments
function isElementDescriptor(args) {
let [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) {
let 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 {
enumerable = true;
configurable = true;
_dependentKeys = undefined;
_meta = undefined;
setup(_obj, keyName, _propertyDesc, meta) {
meta.writeDescriptors(keyName, this);
}
teardown(_obj, keyName, meta) {
meta.removeDescriptors(keyName);
}
}
function DESCRIPTOR_GETTER_FUNCTION(name, descriptor) {
function getter() {
return descriptor.get(this, name);
}
return getter;
}
function DESCRIPTOR_SETTER_FUNCTION(name, descriptor) {
let set = function CPSETTER_FUNCTION(value) {
return descriptor.set(this, name, value);
};
COMPUTED_SETTERS.add(set);
return set;
}
const COMPUTED_SETTERS = new WeakSet();
function makeComputedDecorator(desc, DecoratorClass) {
let decorator = function COMPUTED_DECORATOR(target, key, propertyDesc, maybeMeta, isClassicDecorator) {
let meta$1 = arguments.length === 3 ? meta(target) : maybeMeta;
desc.setup(target, key, propertyDesc, meta$1);
let 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;
}
/////////////
const 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) {
let meta = _meta === undefined ? peekMeta(obj) : _meta;
if (meta !== null) {
return meta.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
*/
const 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) {
let start = pattern.indexOf('{');
if (start < 0) {
callback(pattern.replace(END_WITH_EACH_REGEX, '.[]'));
} else {
dive('', pattern, start, callback);
}
}
function dive(prefix, pattern, start, callback) {
let end = pattern.indexOf('}'),
i = 0,
newStart,
arrayLength;
let tempArr = pattern.substring(start + 1, end).split(',');
let 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);
}
}
}
const AFTER_OBSERVERS = ':change';
function changeEvent(keyName) {
return keyName + AFTER_OBSERVERS;
}
/**
@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) {
if (!method && 'function' === typeof target) {
method = target;
target = null;
}
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) {
let target, method;
if (typeof targetOrFunction === 'object') {
target = targetOrFunction;
method = functionOrName;
} else {
target = null;
method = targetOrFunction;
}
let m = 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) {
let meta = _meta === undefined ? peekMeta(obj) : _meta;
actions = meta !== null ? meta.matchingListeners(eventName) : undefined;
}
if (actions === undefined || actions.length === 0) {
return false;
}
for (let i = actions.length - 3; i >= 0; i -= 3) {
// looping in reverse for once listeners
let target = actions[i];
let method = actions[i + 1];
let once = actions[i + 2];
if (!method) {
continue;
}
if (once) {
removeListener(obj, eventName, target, method);
}
if (!target) {
target = obj;
}
let type = typeof method;
if (type === 'string' || type === 'symbol') {
method = target[method];
}
method.apply(target, params);
}
return true;
}
/**
@public
@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) {
let meta = peekMeta(obj);
if (meta === null) {
return false;
}
let matched = meta.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$3(...args) {
let func = args.pop();
let events = args;
setListeners(func, events);
return func;
}
const SYNC_DEFAULT = !ENV._DEFAULT_ASYNC_OBSERVERS;
const SYNC_OBSERVERS = new Map();
const 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
*/
function addObserver(obj, path, target, method, sync = SYNC_DEFAULT) {
let eventName = changeEvent(path);
addListener(obj, eventName, target, method, false, sync);
let meta = peekMeta(obj);
if (meta === null || !(meta.isPrototypeMeta(obj) || meta.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) {
let eventName = changeEvent(path);
let meta = peekMeta(obj);
if (meta === null || !(meta.isPrototypeMeta(obj) || meta.isInitializing())) {
deactivateObserver(obj, eventName, sync);
}
removeListener(obj, eventName, target, method);
}
function getOrCreateActiveObserversFor(target, sync) {
let observerMap = sync === true ? SYNC_OBSERVERS : ASYNC_OBSERVERS;
if (!observerMap.has(target)) {
observerMap.set(target, new Map());
registerDestructor$1(target, () => destroyObservers(target), true);
}
return observerMap.get(target);
}
function activateObserver(target, eventName, sync = false) {
let activeObservers = getOrCreateActiveObserversFor(target, sync);
if (activeObservers.has(eventName)) {
activeObservers.get(eventName).count++;
} else {
let path = eventName.substring(0, eventName.lastIndexOf(':'));
let tag = getChainTagsForKey(target, path, tagMetaFor(target), peekMeta(target));
activeObservers.set(eventName, {
count: 1,
path,
tag,
lastRevision: valueForTag(tag),
suspended: false
});
}
}
let DEACTIVATE_SUSPENDED = false;
let SCHEDULED_DEACTIVATE = [];
function deactivateObserver(target, eventName, sync = false) {
if (DEACTIVATE_SUSPENDED === true) {
SCHEDULED_DEACTIVATE.push([target, eventName, sync]);
return;
}
let observerMap = sync === true ? SYNC_OBSERVERS : ASYNC_OBSERVERS;
let activeObservers = observerMap.get(target);
if (activeObservers !== undefined) {
let 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 (let [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, tagMetaFor(target), peekMeta(target));
observer.lastRevision = valueForTag(observer.tag);
});
}
if (SYNC_OBSERVERS.has(target)) {
SYNC_OBSERVERS.get(target).forEach(observer => {
observer.tag = getChainTagsForKey(target, observer.path, tagMetaFor(target), peekMeta(target));
observer.lastRevision = valueForTag(observer.tag);
});
}
}
let lastKnownRevision = 0;
function flushAsyncObservers(_schedule) {
let currentRevision = valueForTag(CURRENT_TAG);
if (lastKnownRevision === currentRevision) {
return;
}
lastKnownRevision = currentRevision;
ASYNC_OBSERVERS.forEach((activeObservers, target) => {
let meta = peekMeta(target);
activeObservers.forEach((observer, eventName) => {
if (!validateTag(observer.tag, observer.lastRevision)) {
let sendObserver = () => {
try {
sendEvent(target, eventName, [target, observer.path], undefined, meta);
} finally {
observer.tag = getChainTagsForKey(target, observer.path, tagMetaFor(target), peekMeta(target));
observer.lastRevision = valueForTag(observer.tag);
}
};
if (_schedule) {
_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) => {
let meta = peekMeta(target);
activeObservers.forEach((observer, eventName) => {
if (!observer.suspended && !validateTag(observer.tag, observer.lastRevision)) {
try {
observer.suspended = true;
sendEvent(target, eventName, [target, observer.path], undefined, meta);
} finally {
observer.tag = getChainTagsForKey(target, observer.path, tagMetaFor(target), peekMeta(target));
observer.lastRevision = valueForTag(observer.tag);
observer.suspended = false;
}
}
});
});
}
function setObserverSuspended(target, property, suspended) {
let activeObservers = SYNC_OBSERVERS.get(target);
if (!activeObservers) {
return;
}
let 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);
}
/**
@module ember
@private
*/
const PROPERTY_DID_CHANGE = Symbol('PROPERTY_DID_CHANGE');
let deferred$1 = 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) {
let meta = _meta === undefined ? peekMeta(obj) : _meta;
if (meta !== null && (meta.isInitializing() || meta.isPrototypeMeta(obj))) {
return;
}
markObjectAsDirty(obj, keyName);
if (deferred$1 <= 0) {
flushSyncObservers();
}
if (PROPERTY_DID_CHANGE in obj) {
// 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$1++;
suspendedObserverDeactivation();
}
/**
@method endPropertyChanges
@private
*/
function endPropertyChanges() {
deferred$1--;
if (deferred$1 <= 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 noop$2() {}
/**
`@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 {
_readOnly = false;
_hasConfig = false;
_getter = undefined;
_setter = undefined;
constructor(args) {
super();
let maybeConfig = args[args.length - 1];
if (typeof maybeConfig === 'function' || maybeConfig !== null && typeof maybeConfig === 'object') {
this._hasConfig = true;
let config = args.pop();
if (typeof config === 'function') {
this._getter = config;
} else {
const objectConfig = config;
this._getter = objectConfig.get || noop$2;
this._setter = objectConfig.set;
}
}
if (args.length > 0) {
this._property(...args);
}
}
setup(obj, keyName, propertyDesc, meta) {
super.setup(obj, keyName, propertyDesc, meta);
if (this._hasConfig === false) {
let {
get,
set
} = propertyDesc;
if (get !== undefined) {
this._getter = get;
}
if (set !== undefined) {
this._setter = function setterWrapper(_key, value) {
let ret = set.call(this, value);
if (get !== undefined) {
return typeof ret === 'undefined' ? get.call(this) : ret;
}
return ret;
};
}
}
}
_property(...passedArgs) {
let args = [];
function addArg(property) {
args.push(property);
}
for (let arg of passedArgs) {
expandProperties(arg, addArg);
}
this._dependentKeys = args;
}
get(obj, keyName) {
let meta$1 = meta(obj);
let tagMeta = tagMetaFor(obj);
let propertyTag = tagFor(obj, keyName, tagMeta);
let ret;
let revision = meta$1.revisionFor(keyName);
if (revision !== undefined && validateTag(propertyTag, revision)) {
ret = meta$1.valueFor(keyName);
} else {
let {
_getter,
_dependentKeys
} = this;
// Create a tracker that absorbs any trackable actions inside the CP
untrack(() => {
ret = _getter.call(obj, keyName);
});
if (_dependentKeys !== undefined) {
UPDATE_TAG(propertyTag, getChainTagsForKeys(obj, _dependentKeys, tagMeta, meta$1));
}
meta$1.setValueFor(keyName, ret);
meta$1.setRevisionFor(keyName, valueForTag(propertyTag));
finishLazyChains(meta$1, keyName, ret);
}
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)) {
consumeTag(tagFor(ret, '[]'));
}
return ret;
}
set(obj, keyName, value) {
if (this._readOnly) {
this._throwReadOnlyError(obj, keyName);
}
let meta$1 = 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 && typeof obj[PROPERTY_DID_CHANGE] === 'function' && obj.isComponent) {
addObserver(obj, keyName, () => {
obj[PROPERTY_DID_CHANGE](keyName);
}, undefined, true);
}
let ret;
try {
beginPropertyChanges();
ret = this._set(obj, keyName, value, meta$1);
finishLazyChains(meta$1, keyName, ret);
let tagMeta = tagMetaFor(obj);
let propertyTag = tagFor(obj, keyName, tagMeta);
let {
_dependentKeys
} = this;
if (_dependentKeys !== undefined) {
UPDATE_TAG(propertyTag, getChainTagsForKeys(obj, _dependentKeys, tagMeta, meta$1));
if (false /* DEBUG */) ;
}
meta$1.setRevisionFor(keyName, valueForTag(propertyTag));
} finally {
endPropertyChanges();
}
return ret;
}
_throwReadOnlyError(obj, keyName) {
throw new Error(`Cannot set read-only property "${keyName}" on object: ${inspect(obj)}`);
}
_set(obj, keyName, value, meta) {
let hadCachedValue = meta.revisionFor(keyName) !== undefined;
let cachedValue = meta.valueFor(keyName);
let ret;
let {
_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.setValueFor(keyName, ret);
notifyPropertyChange(obj, keyName, meta, value);
return ret;
}
/* called before property is overridden */
teardown(obj, keyName, meta) {
if (meta.revisionFor(keyName) !== undefined) {
meta.setRevisionFor(keyName, undefined);
meta.setValueFor(keyName, undefined);
}
super.teardown(obj, keyName, meta);
}
}
class AutoComputedProperty extends ComputedProperty {
get(obj, keyName) {
let meta$1 = meta(obj);
let tagMeta = tagMetaFor(obj);
let propertyTag = tagFor(obj, keyName, tagMeta);
let ret;
let revision = meta$1.revisionFor(keyName);
if (revision !== undefined && validateTag(propertyTag, revision)) {
ret = meta$1.valueFor(keyName);
} else {
let {
_getter
} = this;
// Create a tracker that absorbs any trackable actions inside the CP
let tag = track(() => {
ret = _getter.call(obj, keyName);
});
UPDATE_TAG(propertyTag, tag);
meta$1.setValueFor(keyName, ret);
meta$1.setRevisionFor(keyName, valueForTag(propertyTag));
finishLazyChains(meta$1, keyName, ret);
}
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)) {
consumeTag(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() {
let desc = descriptorForDecorator(this);
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) {
let prop = descriptorForDecorator(this);
if (arguments.length === 0) {
return prop._meta || {};
} else {
prop._meta = meta;
return this;
}
}
// TODO: Remove this when we can provide alternatives in the ecosystem to
// addons such as ember-macro-helpers that use it.
/** @internal */
get _getter() {
return descriptorForDecorator(this)._getter;
}
// TODO: Refactor this, this is an internal API only
/** @internal */
set enumerable(value) {
descriptorForDecorator(this).enumerable = value;
}
}
/**
This helper returns a new property descriptor that wraps the passed
computed property function. You can use this helper to define properties with
native decorator syntax, mixins, or via `defineProperty()`.
Example:
```js
import { computed, set } from '@ember/object';
class Person {
constructor() {
this.firstName = 'Betty';
this.lastName = 'Jones';
},
@computed('firstName', 'lastName')
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
let client = new Person();
client.fullName; // 'Betty Jones'
set(client, 'lastName', 'Fuller');
client.fullName; // 'Betty Fuller'
```
Classic Class Example:
```js
import EmberObject, { computed } from '@ember/object';
let Person = EmberObject.extend({
init() {
this._super(...arguments);
this.firstName = 'Betty';
this.lastName = 'Jones';
},
fullName: computed('firstName', 'lastName', function() {
return `${this.get('firstName')} ${this.get('lastName')}`;
})
});
let client = Person.create();
client.get('fullName'); // 'Betty Jones'
client.set('lastName', 'Fuller');
client.get('fullName'); // 'Betty Fuller'
```
You can also provide a setter, either directly on the class using native class
syntax, or by passing a hash with `get` and `set` functions.
Example:
```js
import { computed, set } from '@ember/object';
class Person {
constructor() {
this.firstName = 'Betty';
this.lastName = 'Jones';
},
@computed('firstName', 'lastName')
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
set fullName(value) {
let [firstName, lastName] = value.split(/\s+/);
set(this, 'firstName', firstName);
set(this, 'lastName', lastName);
return value;
}
}
let client = new Person();
client.fullName; // 'Betty Jones'
set(client, 'lastName', 'Fuller');
client.fullName; // 'Betty Fuller'
```
Classic Class Example:
```js
import EmberObject, { computed } from '@ember/object';
let Person = EmberObject.extend({
init() {
this._super(...arguments);
this.firstName = 'Betty';
this.lastName = 'Jones';
},
fullName: computed('firstName', 'lastName', {
get(key) {
return `${this.get('firstName')} ${this.get('lastName')}`;
},
set(key, value) {
let [firstName, lastName] = value.split(/\s+/);
this.setProperties({ firstName, lastName });
return value;
}
})
});
let client = Person.create();
client.get('firstName'); // 'Betty'
client.set('fullName', 'Carroll Fuller');
client.get('firstName'); // 'Carroll'
```
When passed as an argument, the `set` function should accept two parameters,
`key` and `value`. The value returned from `set` will be the new value of the
property.
_Note: This is the preferred way to define computed properties when writing third-party
libraries that depend on or use Ember, since there is no guarantee that the user
will have [prototype Extensions](https://guides.emberjs.com/release/configuring-ember/disabling-prototype-extensions/) enabled._
@method computed
@for @ember/object
@static
@param {String} [dependentKeys*] Optional dependent keys that trigger this computed property.
@param {Function} func The computed property function.
@return {ComputedDecorator} property decorator instance
@public
*/
// @computed without parens or computed with descriptor args
// @computed with keys only
// @computed with keys and config
// @computed with config only
function computed(...args) {
if (isElementDescriptor(args)) {
// SAFETY: We passed in the impl for this class
let decorator = makeComputedDecorator(new ComputedProperty([]), ComputedDecoratorImpl);
return decorator(args[0], args[1], args[2]);
}
// SAFETY: We passed in the impl for this class
return makeComputedDecorator(new ComputedProperty(args), ComputedDecoratorImpl);
}
function autoComputed(...config) {
// SAFETY: We passed in the impl for this class
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) {
let meta = peekMeta(obj);
if (meta) {
return meta.valueFor(key);
} else {
return undefined;
}
}
/**
@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) {
let meta$1 = _meta === undefined ? meta(obj) : _meta;
let previousDesc = descriptorForProperty(obj, keyName, meta$1);
let 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) {
let propertyDesc;
{
propertyDesc = desc(obj, keyName, undefined, meta);
}
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 {
{
obj[keyName] = value;
}
}
return value;
}
const EMBER_ARRAYS = new WeakSet();
function setEmberArray(obj) {
EMBER_ARRAYS.add(obj);
}
function isEmberArray(obj) {
return EMBER_ARRAYS.has(obj);
}
const emberArrayinternals = /*#__PURE__*/Object.defineProperty({
__proto__: null,
isEmberArray,
setEmberArray
}, Symbol.toStringTag, { value: 'Module' });
const firstDotIndexCache = new Cache(1000, key => key.indexOf('.'));
function isPath(path) {
return typeof path === 'string' && firstDotIndexCache.get(path) !== -1;
}
/**
@module @ember/object
*/
const PROXY_CONTENT = symbol('PROXY_CONTENT');
function hasUnknownProperty(val) {
return typeof val === 'object' && val !== null && typeof val.unknownProperty === 'function';
}
// ..........................................................
// 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$2(obj, keyName) {
return isPath(keyName) ? _getPath(obj, keyName) : _getProp(obj, keyName);
}
function _getProp(obj, keyName) {
if (obj == null) {
return;
}
let value;
if (typeof obj === 'object' || typeof obj === 'function') {
{
value = obj[keyName];
}
if (value === undefined && typeof obj === 'object' && !(keyName in obj) && hasUnknownProperty(obj)) {
value = obj.unknownProperty(keyName);
}
if (isTracking()) {
consumeTag(tagFor(obj, keyName));
if (Array.isArray(value) || 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
consumeTag(tagFor(value, '[]'));
}
}
} else {
// SAFETY: It should be ok to access properties on any non-nullish value
value = obj[keyName];
}
return value;
}
function _getPath(obj, path, forSet) {
let parts = typeof path === 'string' ? path.split('.') : path;
for (let part of parts) {
if (obj === undefined || obj === null || obj.isDestroyed) {
return undefined;
}
if (forSet && (part === '__proto__' || part === 'constructor')) {
return;
}
obj = _getProp(obj, part);
}
return obj;
}
// Warm it up
_getProp('foo', 'a');
_getProp('foo', 1);
_getProp({}, 'a');
_getProp({}, 1);
_getProp({
unknownProperty() {}
}, 'a');
_getProp({
unknownProperty() {}
}, 1);
get$2({}, 'foo');
get$2({}, 'foo.bar');
let fakeProxy = {};
setProxy(fakeProxy);
track(() => _getProp({}, 'a'));
track(() => _getProp({}, 1));
track(() => _getProp({
a: []
}, 'a'));
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) {
if (obj.isDestroyed) {
return value;
}
return isPath(keyName) ? _setPath(obj, keyName, value, tolerant) : _setProp(obj, keyName, value);
}
function _setProp(obj, keyName, value) {
let descriptor = lookupDescriptor(obj, keyName);
if (descriptor !== null && COMPUTED_SETTERS.has(descriptor.set)) {
obj[keyName] = value;
return value;
}
let currentValue;
{
currentValue = obj[keyName];
}
if (currentValue === undefined && 'object' === typeof obj && !(keyName in obj) && typeof obj.setUnknownProperty === 'function') {
/* unknown property */
obj.setUnknownProperty(keyName, value);
} else {
{
obj[keyName] = value;
}
if (currentValue !== value) {
notifyPropertyChange(obj, keyName);
}
}
return value;
}
function _setPath(root, path, value, tolerant) {
let parts = path.split('.');
let keyName = parts.pop();
let newRoot = _getPath(root, parts, true);
if (newRoot !== null && newRoot !== undefined) {
return set(newRoot, keyName, value);
} else if (!tolerant) {
throw new Error(`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) {
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) {
let prop = descriptorForDecorator(this);
if (arguments.length === 0) {
return prop._meta || {};
} else {
prop._meta = meta;
}
}
}
class AliasedProperty extends ComputedDescriptor {
altKey;
constructor(altKey) {
super();
this.altKey = altKey;
}
setup(obj, keyName, propertyDesc, meta) {
super.setup(obj, keyName, propertyDesc, meta);
CHAIN_PASS_THROUGH.add(this);
}
get(obj, keyName) {
let ret;
let meta$1 = meta(obj);
let tagMeta = tagMetaFor(obj);
let propertyTag = 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
untrack(() => {
ret = get$2(obj, this.altKey);
});
let lastRevision = meta$1.revisionFor(keyName);
if (lastRevision === undefined || !validateTag(propertyTag, lastRevision)) {
UPDATE_TAG(propertyTag, getChainTagsForKey(obj, this.altKey, tagMeta, meta$1));
meta$1.setRevisionFor(keyName, valueForTag(propertyTag));
finishLazyChains(meta$1, keyName, ret);
}
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) {
throw new Error(`Cannot set read-only property '${keyName}' on object: ${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) {
Object.defineProperty(object, deprecatedKey, {
configurable: true,
enumerable: false,
set(value) {
set(this, newKey, value);
},
get() {
return get$2(this, newKey);
}
});
}
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;
}
}
let meta = peekMeta(array);
if (notify) {
if (addAmt < 0 || removeAmt < 0 || addAmt - removeAmt !== 0) {
notifyPropertyChange(array, 'length', meta);
}
notifyPropertyChange(array, '[]', meta);
}
sendEvent(array, '@array:change', [array, startIdx, removeAmt, addAmt]);
if (meta !== null) {
let length = array.length;
let addedAmount = addAmt === -1 ? 0 : addAmt;
let removedAmount = removeAmt === -1 ? 0 : removeAmt;
let delta = addedAmount - removedAmount;
let previousLength = length - delta;
let normalStartIdx = startIdx < 0 ? previousLength + startIdx : startIdx;
if (meta.revisionFor('firstObject') !== undefined && normalStartIdx === 0) {
notifyPropertyChange(array, 'firstObject', meta);
}
if (meta.revisionFor('lastObject') !== undefined) {
let previousLastIndex = previousLength - 1;
let lastAffectedIndex = normalStartIdx + removedAmount;
if (previousLastIndex < lastAffectedIndex) {
notifyPropertyChange(array, 'lastObject', meta);
}
}
}
return array;
}
const EMPTY_ARRAY$3 = Object.freeze([]);
// Ideally, we'd use MutableArray.detect but for unknown reasons this causes
// the node tests to fail strangely.
function isMutableArray(obj) {
return obj != null && typeof obj.replace === 'function';
}
function replace(array, start, deleteCount, items = EMPTY_ARRAY$3) {
if (isMutableArray(array)) {
array.replace(start, deleteCount, items);
} else {
replaceInNativeArray(array, start, deleteCount, items);
}
}
const 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 (let i = 0; i < items.length; i += CHUNK_SIZE) {
let 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) {
let {
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.
*/
obj._revalidate?.();
return obj;
}
function addArrayObserver(array, target, opts) {
return arrayObserversHelper(array, target, opts, addListener);
}
function removeArrayObserver(array, target, opts) {
return arrayObserversHelper(array, target, opts, removeListener);
}
const EACH_PROXIES = new WeakMap();
function eachProxyArrayWillChange(array, idx, removedCnt, addedCnt) {
let eachProxy = EACH_PROXIES.get(array);
if (eachProxy !== undefined) {
eachProxy.arrayWillChange(array, idx, removedCnt, addedCnt);
}
}
function eachProxyArrayDidChange(array, idx, removedCnt, addedCnt) {
let eachProxy = EACH_PROXIES.get(array);
if (eachProxy !== undefined) {
eachProxy.arrayDidChange(array, idx, removedCnt, addedCnt);
}
}
/**
@module ember
*/
/**
Helper class that allows you to register your library with Ember.
Singleton created at `Ember.libraries`.
@class Libraries
@constructor
@private
*/
class Libraries {
_registry;
_coreLibIndex;
constructor() {
this._registry = [];
this._coreLibIndex = 0;
}
_getLibraryByName(name) {
let libs = this._registry;
for (let lib of libs) {
if (lib.name === name) {
return lib;
}
}
return undefined;
}
register(name, version, isCoreLibrary) {
let index = this._registry.length;
if (!this._getLibraryByName(name)) {
if (isCoreLibrary) {
index = this._coreLibIndex++;
}
this._registry.splice(index, 0, {
name,
version
});
}
}
registerCoreLibrary(name, version) {
this.register(name, version, true);
}
deRegister(name) {
let lib = this._getLibraryByName(name);
let index;
if (lib) {
index = this._registry.indexOf(lib);
this._registry.splice(index, 1);
}
}
isRegistered;
logVersions;
}
const LIBRARIES = new Libraries();
LIBRARIES.registerCoreLibrary('Ember', Version);
/**
@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) {
let ret = {};
let propertyNames;
let i = 1;
if (arguments.length === 2 && Array.isArray(keys)) {
i = 0;
propertyNames = arguments[1];
} else {
propertyNames = Array.from(arguments);
}
for (; i < propertyNames.length; i++) {
// SAFETY: we are just walking the list of property names, so we know the
// index access never produces `undefined`.
let name = propertyNames[i];
ret[name] = get$2(obj, name);
}
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(() => {
let props = Object.keys(properties);
for (let propertyName of props) {
// SAFETY: casting `properties` this way is safe because any object in JS
// can be indexed this way, and the result will be `unknown`, making it
// safe for callers.
set(obj, propertyName, properties[propertyName]);
}
});
return properties;
}
let DEBUG_INJECTION_FUNCTIONS;
/**
@module ember
@private
*/
/**
Read-only property that returns the result of a container lookup.
@class InjectedProperty
@namespace Ember
@constructor
@param {String} type The container type the property will lookup
@param {String} nameOrDesc (optional) The name the property will lookup, defaults
to the property's name
@private
*/
// Decorator factory (with args)
// (Also matches non-decorator form, types may be incorrect for this.)
// Non-decorator
// Decorator (without args)
// Catch-all for service and controller injections
function inject$2(type, ...args) {
let elementDescriptor;
let name;
if (isElementDescriptor(args)) {
elementDescriptor = args;
} else if (typeof args[0] === 'string') {
name = args[0];
}
let getInjection = function (propertyName) {
let owner = getOwner$2(this) || this.container; // fallback to `container` for backwards compat
return owner.lookup(`${type}:${name || propertyName}`);
};
let decorator = computed({
get: getInjection,
set(keyName, value) {
defineProperty(this, keyName, null, value);
}
});
if (elementDescriptor) {
return decorator(elementDescriptor[0], elementDescriptor[1], elementDescriptor[2]);
} else {
return decorator;
}
}
/**
@decorator
@private
Marks a property as tracked.
By default, a component's properties are expected to be static,
meaning you are not able to update them and have the template update accordingly.
Marking a property as tracked means that when that property changes,
a rerender of the component is scheduled so the template is kept up to date.
There are two usages for the `@tracked` decorator, shown below.
@example No dependencies
If you don't pass an argument to `@tracked`, only changes to that property
will be tracked:
```typescript
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
export default class MyComponent extends Component {
@tracked
remainingApples = 10
}
```
When something changes the component's `remainingApples` property, the rerender
will be scheduled.
@example Dependents
In the case that you have a computed property that depends other
properties, you want to track both so that when one of the
dependents change, a rerender is scheduled.
In the following example we have two properties,
`eatenApples`, and `remainingApples`.
```typescript
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
const totalApples = 100;
export default class MyComponent extends Component {
@tracked
eatenApples = 0
get remainingApples() {
return totalApples - this.eatenApples;
}
increment() {
this.eatenApples = this.eatenApples + 1;
}
}
```
@param dependencies Optional dependents to be tracked.
*/
function tracked(...args) {
if (!isElementDescriptor(args)) {
let propertyDesc = args[0];
let initializer = propertyDesc ? propertyDesc.initializer : undefined;
let value = propertyDesc ? propertyDesc.value : undefined;
let decorator = function (target, key, _desc, _meta, isClassicDecorator) {
let fieldDesc = {
initializer: initializer || (() => value)
};
return descriptorForField([target, key, fieldDesc]);
};
setClassicDecorator(decorator);
return decorator;
}
return descriptorForField(args);
}
function descriptorForField([target, key, desc]) {
let {
getter,
setter
} = trackedData(key, desc ? desc.initializer : undefined);
function get() {
let 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) || isEmberArray(value)) {
consumeTag(tagFor(value, '[]'));
}
return value;
}
function set(newValue) {
setter(this, newValue);
dirtyTagFor(this, SELF_TAG);
}
let newDesc = {
enumerable: true,
configurable: true,
isTracked: true,
get,
set
};
COMPUTED_SETTERS.add(set);
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);
}
}
// NOTE: copied from: https://github.com/glimmerjs/glimmer.js/pull/358
// Both glimmerjs/glimmer.js and emberjs/ember.js have the exact same implementation
// of @cached, so any changes made to one should also be made to the other
/**
* @decorator
*
Gives the getter a caching behavior. The return value of the getter
will be cached until any of the properties it is entangled with
are invalidated. This is useful when a getter is expensive and
used very often.
For instance, in this `GuestList` class, we have the `sortedGuests`
getter that sorts the guests alphabetically:
```javascript
import { tracked } from '@glimmer/tracking';
class GuestList {
@tracked guests = ['Zoey', 'Tomster'];
get sortedGuests() {
return this.guests.slice().sort()
}
}
```
Every time `sortedGuests` is accessed, a new array will be created and sorted,
because JavaScript getters do not cache by default. When the guest list
is small, like the one in the example, this is not a problem. However, if
the guest list were to grow very large, it would mean that we would be doing
a large amount of work each time we accessed `sortedGuests`. With `@cached`,
we can cache the value instead:
```javascript
import { tracked, cached } from '@glimmer/tracking';
class GuestList {
@tracked guests = ['Zoey', 'Tomster'];
@cached
get sortedGuests() {
return this.guests.slice().sort()
}
}
```
Now the `sortedGuests` getter will be cached based on autotracking.
It will only rerun and create a new sorted array when the guests tracked
property is updated.
### Tradeoffs
Overuse is discouraged.
In general, you should avoid using `@cached` unless you have confirmed that
the getter you are decorating is computationally expensive, since `@cached`
adds a small amount of overhead to the getter.
While the individual costs are small, a systematic use of the `@cached`
decorator can add up to a large impact overall in your app.
Many getters and tracked properties are only accessed once during rendering,
and then never rerendered, so adding `@cached` when unnecessary can
negatively impact performance.
Also, `@cached` may rerun even if the values themselves have not changed,
since tracked properties will always invalidate.
For example updating an integer value from `5` to an other `5` will trigger
a rerun of the cached properties building from this integer.
Avoiding a cache invalidation in this case is not something that can
be achieved on the `@cached` decorator itself, but rather when updating
the underlying tracked values, by applying some diff checking mechanisms:
```javascript
if (nextValue !== this.trackedProp) {
this.trackedProp = nextValue;
}
```
Here equal values won't update the property, therefore not triggering
the subsequent cache invalidations of the `@cached` properties who were
using this `trackedProp`.
Remember that setting tracked data should only be done during initialization,
or as the result of a user action. Setting tracked data during render
(such as in a getter), is not supported.
@method cached
@static
@for @glimmer/tracking
@public
*/
const cached = (...args) => {
const [target, key, descriptor] = args;
const caches = new WeakMap();
const getter = descriptor.get;
descriptor.get = function () {
if (!caches.has(this)) {
caches.set(this, createCache(getter.bind(this)));
}
return getValue(caches.get(this));
};
};
const hasOwnProperty$2 = Object.prototype.hasOwnProperty;
let searchDisabled = false;
const flags = {
_set: 0,
_unprocessedNamespaces: false,
get unprocessedNamespaces() {
return this._unprocessedNamespaces;
},
set unprocessedNamespaces(v) {
this._set++;
this._unprocessedNamespaces = v;
}
};
let unprocessedMixins = false;
const NAMESPACES = [];
const NAMESPACES_BY_ID = Object.create(null);
function addNamespace(namespace) {
flags.unprocessedNamespaces = true;
NAMESPACES.push(namespace);
}
function removeNamespace(namespace) {
let name = getName(namespace);
delete NAMESPACES_BY_ID[name];
NAMESPACES.splice(NAMESPACES.indexOf(namespace), 1);
if (name in context$1.lookup && namespace === context$1.lookup[name]) {
context$1.lookup[name] = undefined;
}
}
function findNamespaces() {
if (!flags.unprocessedNamespaces) {
return;
}
let lookup = context$1.lookup;
let keys = Object.keys(lookup);
for (let key of keys) {
// Only process entities that start with uppercase A-Z
if (!isUppercase(key.charCodeAt(0))) {
continue;
}
let obj = tryIsNamespace(lookup, key);
if (obj) {
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() {
let unprocessedNamespaces = flags.unprocessedNamespaces;
if (unprocessedNamespaces) {
findNamespaces();
flags.unprocessedNamespaces = false;
}
if (unprocessedNamespaces || unprocessedMixins) {
let namespaces = NAMESPACES;
for (let namespace of namespaces) {
processNamespace(namespace);
}
unprocessedMixins = false;
}
}
function isSearchDisabled() {
return searchDisabled;
}
function setSearchDisabled(flag) {
searchDisabled = Boolean(flag);
}
function setUnprocessedMixins() {
unprocessedMixins = true;
}
function _processNamespace(paths, root, seen) {
let idx = paths.length;
let id = paths.join('.');
NAMESPACES_BY_ID[id] = root;
setName(root, id);
// Loop over all of the keys in the namespace, looking for classes
for (let key in root) {
if (!hasOwnProperty$2.call(root, key)) {
continue;
}
let 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 && getName(obj) === void 0) {
// Replace the class' `toString` with the dot-separated path
setName(obj, paths.join('.'));
// Support nested namespaces
} else if (obj && isNamespace(obj)) {
// 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 isNamespace(obj) {
return obj != null && typeof obj === 'object' && obj.isNamespace;
}
function isUppercase(code) {
return code >= 65 && code <= 90 // A
; // Z
}
function tryIsNamespace(lookup, prop) {
try {
let obj = lookup[prop];
return (obj !== null && typeof obj === 'object' || typeof obj === 'function') && obj.isNamespace && obj;
} catch (_e) {
// continue
}
}
const emberinternalsMetalIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
ASYNC_OBSERVERS,
ComputedDescriptor,
ComputedProperty,
DEBUG_INJECTION_FUNCTIONS,
Libraries,
NAMESPACES,
NAMESPACES_BY_ID,
PROPERTY_DID_CHANGE,
PROXY_CONTENT,
SYNC_OBSERVERS,
TrackedDescriptor,
_getPath,
_getProp,
_setProp,
activateObserver,
addArrayObserver,
addListener,
addNamespace,
addObserver,
alias,
arrayContentDidChange,
arrayContentWillChange,
autoComputed,
beginPropertyChanges,
cached,
changeProperties,
computed,
createCache,
defineDecorator,
defineProperty,
defineValue,
deprecateProperty,
descriptorForDecorator,
descriptorForProperty,
eachProxyArrayDidChange,
eachProxyArrayWillChange,
endPropertyChanges,
expandProperties,
findNamespace,
findNamespaces,
flushAsyncObservers,
get: get$2,
getCachedValueFor,
getProperties,
getValue,
hasListeners,
hasUnknownProperty,
inject: inject$2,
isClassicDecorator,
isComputed,
isConst,
isElementDescriptor,
isNamespaceSearchDisabled: isSearchDisabled,
libraries: LIBRARIES,
makeComputedDecorator,
markObjectAsDirty,
nativeDescDecorator,
notifyPropertyChange,
objectAt,
on: on$3,
processAllNamespaces,
processNamespace,
removeArrayObserver,
removeListener,
removeNamespace,
removeObserver,
replace,
replaceInNativeArray,
revalidateObservers,
sendEvent,
set,
setClassicDecorator,
setNamespaceSearchDisabled: setSearchDisabled,
setProperties,
setUnprocessedMixins,
tagForObject,
tagForProperty,
tracked,
trySet
}, Symbol.toStringTag, { value: 'Module' });
const emberObjectEvents = /*#__PURE__*/Object.defineProperty({
__proto__: null,
addListener,
removeListener,
sendEvent
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/object/mixin
*/
const a_concat = Array.prototype.concat;
function extractAccessors(properties) {
if (properties !== undefined) {
for (let key of Object.keys(properties)) {
let 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
let 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;
}
let originalGetter = property._getter;
if (originalGetter === undefined) {
return decorator;
}
let superDesc = descs[key];
// Check to see if the super property is a decorator first, if so load its descriptor
let superProperty = typeof superDesc === 'function' ? descriptorForDecorator(superDesc) : superDesc;
if (superProperty === undefined || superProperty === true) {
return decorator;
}
let superGetter = superProperty._getter;
if (superGetter === undefined) {
return decorator;
}
let get = wrap$1(originalGetter, superGetter);
let set;
let originalSetter = property._setter;
let superSetter = superProperty._setter;
if (superSetter !== undefined) {
if (originalSetter !== undefined) {
set = wrap$1(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.
let dependentKeys = property._dependentKeys || [];
let newProperty = new ComputedProperty([...dependentKeys, {
get,
set
}]);
newProperty._readOnly = property._readOnly;
newProperty._meta = property._meta;
newProperty.enumerable = property.enumerable;
// SAFETY: We passed in the impl for this class
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
let superMethod = values[key];
// Only wrap the new method if the original method was a function
if (typeof superMethod === 'function') {
return wrap$1(method, superMethod);
}
return method;
}
function simpleMakeArray(value) {
if (!value) {
return [];
} else if (!Array.isArray(value)) {
return [value];
} else {
return value;
}
}
function applyConcatenatedProperties(key, value, values) {
let baseValue = values[key];
let ret = simpleMakeArray(baseValue).concat(simpleMakeArray(value));
return ret;
}
function applyMergedProperties(key, value, values) {
let baseValue = values[key];
if (!baseValue) {
return value;
}
let newBase = Object.assign({}, baseValue);
let hasFunction = false;
let props = Object.keys(value);
for (let prop of props) {
let propValue = value[prop];
if (typeof propValue === 'function') {
hasFunction = true;
newBase[prop] = giveMethodSuper(prop, propValue, baseValue, {});
} else {
newBase[prop] = propValue;
}
}
if (hasFunction) {
newBase._super = ROOT;
}
return newBase;
}
function mergeMixins(mixins, meta, descs, values, base, keys, keysWithSuper) {
let currentMixin;
for (let i = 0; i < mixins.length; i++) {
currentMixin = mixins[i];
if (MIXINS.has(currentMixin)) {
if (meta.hasMixin(currentMixin)) {
continue;
}
meta.addMixin(currentMixin);
let {
properties,
mixins
} = currentMixin;
if (properties !== undefined) {
mergeProps(meta, properties, descs, values, base, keys, keysWithSuper);
} else if (mixins !== undefined) {
mergeMixins(mixins, meta, descs, values, base, keys, keysWithSuper);
if (currentMixin instanceof Mixin && currentMixin._without !== undefined) {
currentMixin._without.forEach(keyName => {
// deleting the key means we won't process the value
let index = keys.indexOf(keyName);
if (index !== -1) {
keys.splice(index, 1);
}
});
}
}
} else {
mergeProps(meta, currentMixin, descs, values, base, keys, keysWithSuper);
}
}
}
function mergeProps(meta, props, descs, values, base, keys, keysWithSuper) {
let concats = concatenatedMixinProperties('concatenatedProperties', props, values, base);
let mergings = concatenatedMixinProperties('mergedProperties', props, values, base);
let propKeys = Object.keys(props);
for (let key of propKeys) {
let value = props[key];
if (value === undefined) continue;
if (keys.indexOf(key) === -1) {
keys.push(key);
let desc = meta.peekDescriptors(key);
if (desc === undefined) {
// If the value is a classic decorator, we don't want to actually
// access it, because that will execute the decorator while we're
// building the class.
if (!isClassicDecorator(value)) {
// The superclass did not have a CP, which means it may have
// observers or listeners on that property.
let 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);
}
}
let isFunction = typeof value === 'function';
if (isFunction) {
let desc = descriptorForDecorator(value);
if (desc !== undefined) {
// Wrap descriptor function to implement _super() if needed
descs[key] = giveDecoratorSuper(key, value, desc, 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) {
let meta = observerListenerMetaFor(fn);
if (meta === undefined) return;
let {
observers,
listeners
} = meta;
if (observers !== undefined) {
let updateObserver = add ? addObserver : removeObserver;
for (let path of observers.paths) {
updateObserver(obj, path, null, key, observers.sync);
}
}
if (listeners !== undefined) {
let updateListener = add ? addListener : removeListener;
for (let listener of listeners) {
updateListener(obj, listener, null, key);
}
}
}
function applyMixin(obj, mixins, _hideKeys = false) {
let descs = Object.create(null);
let values = Object.create(null);
let meta$1 = meta(obj);
let keys = [];
let keysWithSuper = [];
obj._super = 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 (let key of keys) {
let value = values[key];
let 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;
}
const MIXINS = new 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 {
/** @internal */
/** @internal */
mixins;
/** @internal */
properties;
/** @internal */
ownerConstructor;
/** @internal */
_without;
/** @internal */
constructor(mixins, properties) {
MIXINS.add(this);
this.properties = extractAccessors(properties);
this.mixins = buildMixinsArray(mixins);
this.ownerConstructor = undefined;
this._without = undefined;
}
/**
@method create
@for @ember/object/mixin
@static
@param arguments*
@public
*/
static create(...args) {
setUnprocessedMixins();
let M = this;
return new M(args, undefined);
}
// returns the mixins currently applied to the specified object
// TODO: Make `mixin`
/** @internal */
static mixins(obj) {
let meta = peekMeta(obj);
let ret = [];
if (meta === null) {
return ret;
}
meta.forEachMixins(currentMixin => {
// skip primitive mixins since these are always anonymous
if (!currentMixin.properties) {
ret.push(currentMixin);
}
});
return ret;
}
/**
@method reopen
@param arguments*
@private
@internal
*/
reopen(...args) {
if (args.length === 0) {
return this;
}
if (this.properties) {
let 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
@internal
*/
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);
}
/** @internal */
applyPartial(obj) {
return applyMixin(obj, [this]);
}
/**
@method detect
@param obj
@return {Boolean}
@private
@internal
*/
detect(obj) {
if (typeof obj !== 'object' || obj === null) {
return false;
}
if (MIXINS.has(obj)) {
return _detect(obj, this);
}
let meta = peekMeta(obj);
if (meta === null) {
return false;
}
return meta.hasMixin(this);
}
/** @internal */
without(...args) {
let ret = new Mixin([this]);
ret._without = args;
return ret;
}
/** @internal */
keys() {
let keys = _keys(this);
return keys;
}
/** @internal */
toString() {
return '(unknown mixin)';
}
}
function buildMixinsArray(mixins) {
let length = mixins && mixins.length || 0;
let m = undefined;
if (length > 0) {
m = new Array(length);
for (let i = 0; i < length; i++) {
let x = mixins[i];
if (MIXINS.has(x)) {
m[i] = x;
} else {
m[i] = new Mixin(undefined, x);
}
}
}
return m;
}
function _detect(curMixin, targetMixin, seen = new Set()) {
if (seen.has(curMixin)) {
return false;
}
seen.add(curMixin);
if (curMixin === targetMixin) {
return true;
}
let 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) {
let props = Object.keys(mixin.properties);
for (let prop of props) {
ret.add(prop);
}
} else if (mixin.mixins) {
mixin.mixins.forEach(x => _keys(x, ret, seen));
}
return ret;
}
const emberObjectMixin = /*#__PURE__*/Object.defineProperty({
__proto__: null,
applyMixin,
default: Mixin,
mixin
}, Symbol.toStringTag, { value: 'Module' });
/**
@module ember
*/
/**
RegistryProxyMixin is used to provide public access to specific
registry functionality.
@class RegistryProxyMixin
@extends RegistryProxy
@private
*/
const RegistryProxyMixin = Mixin.create({
__registry__: null,
resolveRegistration(fullName) {
return this.__registry__.resolve(fullName);
},
register: registryAlias('register'),
unregister: registryAlias('unregister'),
hasRegistration: registryAlias('has'),
registeredOption: registryAlias('getOption'),
registerOptions: registryAlias('options'),
registeredOptions: registryAlias('getOptions'),
registerOptionsForType: registryAlias('optionsForType'),
registeredOptionsForType: registryAlias('getOptionsForType')
});
function registryAlias(name) {
return function (...args) {
// We need this cast because `Parameters` is deferred so that it is not
// possible for TS to see it will always produce the right type. However,
// since `AnyFn` has a rest type, it is allowed. See discussion on [this
// issue](https://github.com/microsoft/TypeScript/issues/47615).
return this.__registry__[name](...args);
};
}
const emberinternalsRuntimeLibMixinsRegistryProxy = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: RegistryProxyMixin
}, Symbol.toStringTag, { value: 'Module' });
const SET_TIMEOUT = setTimeout;
const NOOP$4 = () => {};
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') {
const autorunPromise = Promise.resolve();
return () => autorunPromise.then(flush);
} else if (typeof MutationObserver === 'function') {
let iterations = 0;
let observer = new MutationObserver(flush);
let 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) {
let clearNext = NOOP$4;
return {
setTimeout(fn, ms) {
return setTimeout(fn, ms);
},
clearTimeout(timerId) {
return clearTimeout(timerId);
},
now() {
return Date.now();
},
next: buildNext(flush),
clearNext
};
}
const NUMBER = /\d+/;
const TIMERS_OFFSET = 6;
function isCoercableNumber(suspect) {
let 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) {
let index = -1;
for (let 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) {
let index = -1;
for (let 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) {
let queueItems = [];
for (let i = 0; i < items.length; i += queueItemLength) {
let maybeError = items[i + 3 /* stack */ + queueItemPositionOffset];
let 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) {
let start = 0;
let end = timers.length - TIMERS_OFFSET;
let middle;
let 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;
}
const 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) {
let entry = this._queue[index * 3 + QUEUE_ITEM_LENGTH];
if (entry) {
return entry.stack;
} else {
return null;
}
}
}
flush(sync) {
let {
before,
after
} = this.options;
let target;
let method;
let args;
let errorRecordedForStack;
this.targetQueues.clear();
if (this._queueBeingFlushed.length === 0) {
this._queueBeingFlushed = this._queue;
this._queue = [];
}
if (before !== undefined) {
before();
}
let invoke;
let queueItems = this._queueBeingFlushed;
if (queueItems.length > 0) {
let onError = getOnError(this.globalOptions);
invoke = onError ? this.invokeWithOnError : this.invoke;
for (let 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
}) {
let queue = this._queue;
let targetQueueMap = this.targetQueues.get(target);
if (targetQueueMap !== undefined) {
targetQueueMap.delete(method);
}
let index = findItem(target, method, queue);
if (index > -1) {
queue[index + 1] = null;
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) {
let localQueueMap = this.targetQueues.get(target);
if (localQueueMap === undefined) {
localQueueMap = new Map();
this.targetQueues.set(target, localQueueMap);
}
let index = localQueueMap.get(method);
if (index === undefined) {
let queueIndex = this._queue.push(target, method, args, stack) - QUEUE_ITEM_LENGTH;
localQueueMap.set(method, queueIndex);
} else {
let queue = this._queue;
queue[index + 2] = args; // replace args
queue[index + 3] = stack; // replace stack
}
return {
queue: this,
target,
method
};
}
_getDebugInfo(debugEnabled) {
if (debugEnabled) {
let 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) {
let queues = this.queues;
let 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) {
let queue;
let queueName;
let 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) {
let debugInfo = {};
let queue;
let queueName;
let numberOfQueues = this.queueNames.length;
let 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) {
let iterator = fn();
let result = iterator.next();
while (result.done === false) {
result.value();
result = iterator.next();
}
}
const noop$1 = function () {};
const DISABLE_SCHEDULE = Object.freeze([]);
function parseArgs() {
let length = arguments.length;
let args;
let method;
let target;
if (length === 0) ;else if (length === 1) {
target = null;
method = arguments[0];
} else {
let argsIndex = 2;
let methodOrTarget = arguments[0];
let methodOrArgs = arguments[1];
let 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) {
let len = length - argsIndex;
args = new Array(len);
for (let i = 0; i < len; i++) {
args[i] = arguments[i + argsIndex];
}
}
}
return [target, method, args];
}
function parseTimerArgs() {
let [target, method, args] = parseArgs(...arguments);
let wait = 0;
let length = args !== undefined ? args.length : 0;
if (length > 0) {
let last = args[length - 1];
if (isCoercableNumber(last)) {
wait = parseInt(args.pop(), 10);
}
}
return [target, method, args, wait];
}
function parseDebounceArgs() {
let target;
let method;
let isImmediate;
let args;
let 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];
}
let UUID = 0;
let beginCount = 0;
let endCount = 0;
let beginEventCount = 0;
let endEventCount = 0;
let runCount = 0;
let joinCount = 0;
let deferCount = 0;
let scheduleCount = 0;
let scheduleIterableCount = 0;
let deferOnceCount = 0;
let scheduleOnceCount = 0;
let setTimeoutCount = 0;
let laterCount = 0;
let throttleCount = 0;
let debounceCount = 0;
let cancelTimersCount = 0;
let cancelCount = 0;
let autorunsCreatedCount = 0;
let autorunsCompletedCount = 0;
let deferredActionQueuesCreatedCount = 0;
let 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$1;
this._onEnd = this.options.onEnd || noop$1;
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 */);
};
let 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++;
let options = this.options;
let previousInstance = this.currentInstance;
let 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`);
}
let 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) {
let callbacks = this._eventCallbacks[eventName];
if (!eventName || callbacks === undefined) {
throw new TypeError(`Cannot off() event ${eventName} because it does not exist`);
}
let callbackFound = false;
if (callback) {
for (let 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++;
let [target, method, args] = parseArgs(...arguments);
return this._run(target, method, args);
}
join() {
joinCount++;
let [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++;
let [target, method, args] = parseArgs(..._args);
let 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++;
let 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++;
let [target, method, args] = parseArgs(..._args);
let stack = this.DEBUG ? new Error() : undefined;
return this._ensureInstance().schedule(queueName, target, method, args, true, stack);
}
setTimeout() {
setTimeoutCount++;
return this.later(...arguments);
}
later() {
laterCount++;
let [target, method, args, wait] = parseTimerArgs(...arguments);
return this._later(target, method, args, wait);
}
throttle() {
throttleCount++;
let [target, method, args, wait, isImmediate = true] = parseDebounceArgs(...arguments);
let index = findTimerItem(target, method, this._timers);
let 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];
let argIndex = index + 4;
if (this._timers[argIndex] !== DISABLE_SCHEDULE) {
this._timers[argIndex] = args;
}
}
return timerId;
}
debounce() {
debounceCount++;
let [target, method, args, wait, isImmediate = false] = parseDebounceArgs(...arguments);
let _timers = this._timers;
let index = findTimerItem(target, method, _timers);
let timerId;
if (index === -1) {
timerId = this._later(target, method, isImmediate ? DISABLE_SCHEDULE : args, wait);
if (isImmediate) {
this._join(target, method, args);
}
} else {
let executeAt = this._platform.now() + wait;
let argIndex = index + 4;
if (_timers[argIndex] === DISABLE_SCHEDULE) {
args = DISABLE_SCHEDULE;
}
timerId = _timers[index + 1];
let i = binarySearch(executeAt, _timers);
if (index + TIMERS_OFFSET === i) {
_timers[index] = executeAt;
_timers[argIndex] = args;
} else {
let 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;
}
let 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) {
let currentInstance = this.currentInstance;
let 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
let finallyAlreadyCalled = false;
let result;
try {
result = currentInstance.flush(fromAutorun);
} finally {
if (!finallyAlreadyCalled) {
finallyAlreadyCalled = true;
if (result === 1 /* Pause */) {
const 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) {
let 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) {
let stack = this.DEBUG ? new Error() : undefined;
let executeAt = this._platform.now() + wait;
let id = UUID++;
if (this._timers.length === 0) {
this._timers.push(executeAt, id, target, method, args, stack);
this._installTimerTimeout();
} else {
// find position to insert
let 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 (let 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) {
let callbacks = this._eventCallbacks[eventName];
if (callbacks !== undefined) {
for (let 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() {
let timers = this._timers;
let i = 0;
let l = timers.length;
let defaultQueue = this._defaultQueue;
let n = this._platform.now();
for (; i < l; i += TIMERS_OFFSET) {
let executeAt = timers[i];
if (executeAt > n) {
break;
}
let args = timers[i + 4];
if (args !== DISABLE_SCHEDULE) {
let target = timers[i + 2];
let method = timers[i + 3];
let 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;
}
let minExpiresAt = this._timers[0];
let n = this._platform.now();
let wait = Math.max(0, minExpiresAt - n);
this._timerTimeoutId = this._platform.setTimeout(this._boundRunExpiredTimers, wait);
}
_ensureInstance() {
let 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++;
const next = this._platform.next;
const flush = this.options.flush;
if (flush) {
flush(plannedNextQueue, next);
} else {
next();
}
this._autorun = true;
}
}
Backburner.Queue = Queue;
Backburner.buildPlatform = buildPlatform;
Backburner.buildNext = buildNext;
const backburnerjs = /*#__PURE__*/Object.defineProperty({
__proto__: null,
buildPlatform,
default: Backburner
}, Symbol.toStringTag, { value: 'Module' });
// Partial types from https://medium.com/codex/currying-in-typescript-ca5226c85b85
let currentRunLoop = null;
function _getCurrentRunLoop() {
return currentRunLoop;
}
function onBegin(current) {
currentRunLoop = current;
}
function onEnd(_current, next) {
currentRunLoop = next;
flushAsyncObservers(schedule);
}
function flush$1(queueName, next) {
if (queueName === 'render' || queueName === _rsvpErrorQueue) {
flushAsyncObservers(schedule);
}
next();
}
const _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
*/
const _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];
/**
* @internal
* @private
*/
const _backburner = new Backburner(_queues, {
defaultQueue: 'actions',
onBegin,
onEnd,
onErrorTarget,
onErrorMethod: 'onerror',
flush: flush$1
});
/**
@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
*/
function run$1(...args) {
// @ts-expect-error TS doesn't like our spread args
return _backburner.run(...args);
}
/**
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(methodOrTarget, methodOrArg, ...additionalArgs) {
return _backburner.join(methodOrTarget, methodOrArg, ...additionalArgs);
}
/**
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
*/
// This final fallback is the equivalent of the (quite unsafe!) type for `bind`
// from TS' defs for `Function.prototype.bind`. In general, it means we have a
// loss of safety if we do not
function bind(...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
*/
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(...args) {
// @ts-expect-error TS doesn't like the rest args here
return _backburner.schedule(...args);
}
// 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(...args) {
return _backburner.later(...args);
}
/**
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) {
// @ts-expect-error TS doesn't like the rest args here
return _backburner.scheduleOnce('actions', ...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(...args) {
// @ts-expect-error TS doesn't like the rest args here
return _backburner.scheduleOnce(...args);
}
/**
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) {
return _backburner.later(...args, 1);
}
/**
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(...args) {
// @ts-expect-error TS doesn't like the rest args here
return _backburner.debounce(...args);
}
/**
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(...args) {
// @ts-expect-error TS doesn't like the rest args here
return _backburner.throttle(...args);
}
const emberRunloopIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
_backburner,
_cancelTimers,
_getCurrentRunLoop,
_hasScheduledTimers,
_queues,
_rsvpErrorQueue,
begin,
bind,
cancel,
debounce,
end,
join,
later,
next,
once,
run: run$1,
schedule,
scheduleOnce,
throttle
}, Symbol.toStringTag, { value: 'Module' });
// This is defined as a separate interface so that it can be used in the definition of
// `Owner` without also including the `__container__` property.
/**
ContainerProxyMixin is used to provide public access to specific
container functionality.
@class ContainerProxyMixin
@extends ContainerProxy
@private
*/
const ContainerProxyMixin = Mixin.create({
/**
The container stores state.
@private
@property {Ember.Container} __container__
*/
__container__: null,
ownerInjection() {
return this.__container__.ownerInjection();
},
lookup(fullName, options) {
return this.__container__.lookup(fullName, options);
},
destroy() {
let container = this.__container__;
if (container) {
join(() => {
container.destroy();
schedule('destroy', container, 'finalizeDestroy');
});
}
this._super();
},
factoryFor(fullName) {
return this.__container__.factoryFor(fullName);
}
});
const emberinternalsRuntimeLibMixinsContainerProxy = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: ContainerProxyMixin
}, Symbol.toStringTag, { value: 'Module' });
/**
@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
*/
const Comparable = 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
});
const emberinternalsRuntimeLibMixinsComparable = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: Comparable
}, Symbol.toStringTag, { value: 'Module' });
/**
@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
*/
const ActionHandler = 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/object/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/object/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) {
if (this.actions && this.actions[actionName]) {
let shouldBubble = this.actions[actionName].apply(this, args) === true;
if (!shouldBubble) {
return;
}
}
let target = get$2(this, 'target');
if (target) {
target.send(...arguments);
}
}
});
const emberinternalsRuntimeLibMixinsActionHandler = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: ActionHandler
}, Symbol.toStringTag, { value: 'Module' });
/**
@module ember
*/
function contentFor(proxy) {
let content = get$2(proxy, 'content');
// SAFETY: Ideally we'd assert instead of casting, but @glimmer/validator doesn't give us
// sufficient public types for this. Previously this code was .js and worked correctly so
// hopefully this is sufficiently reliable.
UPDATE_TAG(tagForObject(proxy), tagForObject(content));
return content;
}
function customTagForProxy(proxy, key, addMandatorySetter) {
let meta = tagMetaFor(proxy);
let tag = tagFor(proxy, key, meta);
if (key in proxy) {
return tag;
} else {
let tags = [tag, tagFor(proxy, 'content', meta)];
let content = contentFor(proxy);
if (isObject$1(content)) {
tags.push(tagForProperty(content, key, addMandatorySetter));
}
return 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
*/
const ProxyMixin = Mixin.create({
/**
The object whose properties will be forwarded.
@property content
@type {unknown}
@default null
@public
*/
content: null,
init() {
this._super(...arguments);
setProxy(this);
tagForObject(this);
setCustomTagFor(this, customTagForProxy);
},
willDestroy() {
this.set('content', null);
this._super(...arguments);
},
isTruthy: computed('content', function () {
return Boolean(get$2(this, 'content'));
}),
unknownProperty(key) {
let content = contentFor(this);
return content ? get$2(content, key) : undefined;
},
setUnknownProperty(key, value) {
let m = meta(this);
if (m.isInitializing() || m.isPrototypeMeta(this)) {
// if marked as prototype or object is initializing then just
// defineProperty rather than delegate
defineProperty(this, key, null, value);
return value;
}
let content = contentFor(this);
return set(content, key, value);
}
});
const emberinternalsRuntimeLibMixinsproxy = /*#__PURE__*/Object.defineProperty({
__proto__: null,
contentFor,
default: ProxyMixin
}, Symbol.toStringTag, { value: 'Module' });
/**
@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
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
const Enumerable = Mixin.create();
const emberEnumerableIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: Enumerable
}, Symbol.toStringTag, { value: 'Module' });
/**
@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
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
const MutableEnumerable = Mixin.create(Enumerable);
const emberEnumerableMutable = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: MutableEnumerable
}, Symbol.toStringTag, { value: 'Module' });
/**
@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
*/
const TargetActionSupport = Mixin.create({
target: null,
action: null,
actionContext: null,
actionContextObject: computed('actionContext', function () {
let actionContext = get$2(this, 'actionContext');
if (typeof actionContext === 'string') {
let value = get$2(this, actionContext);
if (value === undefined) {
value = get$2(context$1.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 = {}) {
let {
action,
target,
actionContext
} = opts;
action = action || get$2(this, 'action');
target = target || getTarget(this);
if (actionContext === undefined) {
actionContext = get$2(this, 'actionContextObject') || this;
}
let context = Array.isArray(actionContext) ? actionContext : [actionContext];
if (target && action) {
let ret;
if (isSendable(target)) {
ret = target.send(action, ...context);
} else {
ret = target[action](...context);
}
if (ret !== false) {
return true;
}
}
return false;
}
});
function isSendable(obj) {
return obj != null && typeof obj === 'object' && typeof obj.send === 'function';
}
function getTarget(instance) {
let target = get$2(instance, 'target');
if (target) {
if (typeof target === 'string') {
let value = get$2(instance, target);
if (value === undefined) {
value = get$2(context$1.lookup, target);
}
return value;
} else {
return target;
}
}
if (instance._target) {
return instance._target;
}
return null;
}
const emberinternalsRuntimeLibMixinsTargetActionSupport = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: TargetActionSupport
}, Symbol.toStringTag, { value: 'Module' });
function callbacksFor(object) {
let callbacks = object._promiseCallbacks;
if (!callbacks) {
callbacks = object._promiseCallbacks = {};
}
return callbacks;
}
/**
@class EventTarget
@for rsvp
@public
*/
const 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');
}
let allCallbacks = callbacksFor(this);
let 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) {
let allCallbacks = callbacksFor(this);
if (!callback) {
allCallbacks[eventName] = [];
return;
}
let callbacks = allCallbacks[eventName];
let 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) {
let allCallbacks = callbacksFor(this);
let callbacks = allCallbacks[eventName];
if (callbacks) {
// Don't cache the callbacks.length since it may grow
let callback;
for (let i = 0; i < callbacks.length; i++) {
callback = callbacks[i];
callback(options, label);
}
}
}
};
const config = {
instrument: false
};
EventTarget['mixin'](config);
function configure(name, value) {
if (arguments.length === 2) {
config[name] = value;
} else {
return config[name];
}
}
const queue$1 = [];
function scheduleFlush$1() {
setTimeout(() => {
for (let i = 0; i < queue$1.length; i++) {
let entry = queue$1[i];
let 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$1.length = 0;
}, 50);
}
function instrument$1(eventName, promise, child) {
if (1 === queue$1.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$1();
}
}
/**
`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$4(object, label) {
/*jshint validthis:true */
let Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
let promise = new Constructor(noop, label);
resolve$3(promise, object);
return promise;
}
function withOwnPromise() {
return new TypeError('A promises callback cannot return that same promise.');
}
function objectOrFunction(x) {
let type = typeof x;
return x !== null && (type === 'object' || type === 'function');
}
function noop() {}
const PENDING = void 0;
const FULFILLED = 1;
const REJECTED = 2;
function tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
} catch (e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then) {
config.async(promise => {
let sealed = false;
let error = tryThen(then, thenable, value => {
if (sealed) {
return;
}
sealed = true;
if (thenable === value) {
fulfill(promise, value);
} else {
resolve$3(promise, value);
}
}, reason => {
if (sealed) {
return;
}
sealed = true;
reject$2(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
reject$2(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
thenable._onError = null;
reject$2(promise, thenable._result);
} else {
subscribe$1(thenable, undefined, value => {
if (thenable === value) {
fulfill(promise, value);
} else {
resolve$3(promise, value);
}
}, reason => reject$2(promise, reason));
}
}
function handleMaybeThenable(promise, maybeThenable, then$1) {
let isOwnThenable = maybeThenable.constructor === promise.constructor && then$1 === then && promise.constructor.resolve === resolve$4;
if (isOwnThenable) {
handleOwnThenable(promise, maybeThenable);
} else if (typeof then$1 === 'function') {
handleForeignThenable(promise, maybeThenable, then$1);
} else {
fulfill(promise, maybeThenable);
}
}
function resolve$3(promise, value) {
if (promise === value) {
fulfill(promise, value);
} else if (objectOrFunction(value)) {
let then;
try {
then = value.then;
} catch (error) {
reject$2(promise, error);
return;
}
handleMaybeThenable(promise, value, then);
} 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$1('fulfilled', promise);
}
} else {
config.async(publish, promise);
}
}
function reject$2(promise, reason) {
if (promise._state !== PENDING) {
return;
}
promise._state = REJECTED;
promise._result = reason;
config.async(publishRejection, promise);
}
function subscribe$1(parent, child, onFulfillment, onRejection) {
let subscribers = parent._subscribers;
let 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) {
let subscribers = promise._subscribers;
let settled = promise._state;
if (config.instrument) {
instrument$1(settled === FULFILLED ? 'fulfilled' : 'rejected', promise);
}
if (subscribers.length === 0) {
return;
}
let child,
callback,
result = promise._result;
for (let 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) {
let hasCallback = typeof callback === 'function';
let value,
succeeded = true,
error;
if (hasCallback) {
try {
value = callback(result);
} catch (e) {
succeeded = false;
error = e;
}
} else {
value = result;
}
if (promise._state !== PENDING) ; else if (value === promise) {
reject$2(promise, withOwnPromise());
} else if (succeeded === false) {
reject$2(promise, error);
} else if (hasCallback) {
resolve$3(promise, value);
} else if (state === FULFILLED) {
fulfill(promise, value);
} else if (state === REJECTED) {
reject$2(promise, value);
}
}
function initializePromise(promise, resolver) {
let resolved = false;
try {
resolver(value => {
if (resolved) {
return;
}
resolved = true;
resolve$3(promise, value);
}, reason => {
if (resolved) {
return;
}
resolved = true;
reject$2(promise, reason);
});
} catch (e) {
reject$2(promise, e);
}
}
function then(onFulfillment, onRejection, label) {
let parent = this;
let state = parent._state;
if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) {
config.instrument && instrument$1('chained', parent, parent);
return parent;
}
parent._onError = null;
let child = new parent.constructor(noop, label);
let result = parent._result;
config.instrument && instrument$1('chained', parent, child);
if (state === PENDING) {
subscribe$1(parent, child, onFulfillment, onRejection);
} else {
let 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$2;
this._isUsingOwnResolve = Constructor.resolve === resolve$4;
this._init(...arguments);
}
_init(Constructor, input) {
let len = input.length || 0;
this.length = len;
this._remaining = len;
this._result = new Array(len);
this._enumerate(input);
}
_enumerate(input) {
let length = this.length;
let promise = this.promise;
for (let i = 0; promise._state === PENDING && i < length; i++) {
this._eachEntry(input[i], i, true);
}
this._checkFullfillment();
}
_checkFullfillment() {
if (this._remaining === 0) {
let result = this._result;
fulfill(this.promise, result);
this._result = null;
}
}
_settleMaybeThenable(entry, i, firstPass) {
let c = this._instanceConstructor;
if (this._isUsingOwnResolve) {
let 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) {
let promise = new c(noop);
if (succeeded === false) {
reject$2(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) {
let promise = this.promise;
if (promise._state === PENDING) {
if (this._abortOnReject && state === REJECTED) {
reject$2(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$1(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$1(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$1(entries, label) {
/*jshint validthis:true */
let Constructor = this;
let promise = new Constructor(noop, label);
if (!Array.isArray(entries)) {
reject$2(promise, new TypeError('Promise.race must be called with an array'));
return promise;
}
for (let i = 0; promise._state === PENDING && i < entries.length; i++) {
subscribe$1(Constructor.resolve(entries[i]), undefined, value => resolve$3(promise, value), reason => reject$2(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 */
let Constructor = this;
let promise = new Constructor(noop, label);
reject$2(promise, reason);
return promise;
}
const guidKey = 'rsvp_' + Date.now() + '-';
let 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 promise’s 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
*/
let Promise$1 = class Promise {
constructor(resolver, label) {
this._id = counter++;
this._label = label;
this._state = undefined;
this._result = undefined;
this._subscribers = [];
config.instrument && instrument$1('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) {
let promise = this;
let 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);
}
};
Promise$1.cast = resolve$4; // deprecated
Promise$1.all = all$1;
Promise$1.race = race$1;
Promise$1.resolve = resolve$4;
Promise$1.reject = reject$1;
Promise$1.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$1.prototype.then = then;
const Promise$2 = Promise$1;
function makeObject(_, argumentNames) {
let obj = {};
let length = _.length;
let args = new Array(length);
for (let x = 0; x < length; x++) {
args[x] = _[x];
}
for (let i = 0; i < argumentNames.length; i++) {
let name = argumentNames[i];
obj[name] = args[i + 1];
}
return obj;
}
function arrayResult(_) {
let length = _.length;
let args = new Array(length - 1);
for (let 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) {
let fn = function () {
let l = arguments.length;
let args = new Array(l + 1);
let promiseInput = false;
for (let i = 0; i < l; ++i) {
let arg = arguments[i];
// TODO: this code really needs to be cleaned up
if (!promiseInput) {
if (arg !== null && typeof arg === 'object') {
if (arg.constructor === Promise$2) {
promiseInput = true;
} else {
try {
promiseInput = arg.then;
} catch (error) {
let p = new Promise$2(noop);
reject$2(p, error);
return p;
}
}
} else {
promiseInput = false;
}
if (promiseInput && promiseInput !== true) {
arg = wrapThenable(promiseInput, arg);
}
}
args[i] = arg;
}
let promise = new Promise$2(noop);
args[l] = function (err, val) {
if (err) {
reject$2(promise, err);
} else if (options === undefined) {
resolve$3(promise, val);
} else if (options === true) {
resolve$3(promise, arrayResult(arguments));
} else if (Array.isArray(options)) {
resolve$3(promise, makeObject(arguments, options));
} else {
resolve$3(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$2(promise, error);
}
return promise;
}
function handlePromiseInput(promise, args, nodeFunc, self) {
return Promise$2.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(array, label) {
return Promise$2.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$2.reject(new TypeError("Promise.allSettled must be called with an array"), label);
}
return new AllSettled(Promise$2, 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(array, label) {
return Promise$2.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) {
let keys = Object.keys(input);
let length = keys.length;
let promise = this.promise;
this._remaining = length;
let key, val;
for (let 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$2(object, label) {
return Promise$2.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$2, 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$2.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$2, 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) {
let deferred = {
resolve: undefined,
reject: undefined
};
deferred.promise = new Promise$2((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) {
let 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$2(promises, mapFn, label) {
if (typeof mapFn !== 'function') {
return Promise$2.reject(new TypeError("map expects a function as a second argument"), label);
}
return Promise$2.resolve(promises, label).then(function (promises) {
if (!Array.isArray(promises)) {
throw new TypeError("map must be called with an array");
}
return new MapEnumerator(Promise$2, 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$2.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(reason, label) {
return Promise$2.reject(reason, label);
}
const EMPTY_OBJECT = {};
class FilterEnumerator extends MapEnumerator {
_checkFullfillment() {
if (this._remaining === 0 && this._result !== null) {
let 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;
let 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$1(promises, filterFn, label) {
if (typeof filterFn !== 'function') {
return Promise$2.reject(new TypeError("filter expects function as a second argument"), label);
}
return Promise$2.resolve(promises, label).then(function (promises) {
if (!Array.isArray(promises)) {
throw new TypeError("filter must be called with an array");
}
return new FilterEnumerator(Promise$2, promises, filterFn, label).promise;
});
}
let len = 0;
let vertxNext;
function asap(callback, arg) {
queue[len] = callback;
queue[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();
}
}
const browserWindow = typeof window !== 'undefined' ? window : undefined;
const browserGlobal = browserWindow || {};
const BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
const isNode$1 = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
// test for web worker but not in IE10
const isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
let nextTick = process.nextTick;
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// setImmediate should be used instead instead
let 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() {
let iterations = 0;
let observer = new BrowserMutationObserver(flush);
let node = document.createTextNode('');
observer.observe(node, {
characterData: true
});
return () => node.data = iterations = ++iterations % 2;
}
// web worker
function useMessageChannel() {
let channel = new MessageChannel();
channel.port1.onmessage = flush;
return () => channel.port2.postMessage(0);
}
function useSetTimeout() {
return () => setTimeout(flush, 1);
}
const queue = new Array(1000);
function flush() {
for (let i = 0; i < len; i += 2) {
let callback = queue[i];
let arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
function attemptVertex() {
try {
const vertx = Function('return this')().require('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
return useSetTimeout();
}
}
let scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode$1) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof require === 'function') {
scheduleFlush = attemptVertex();
} else {
scheduleFlush = useSetTimeout();
}
// defaults
config.async = asap;
config.after = cb => setTimeout(cb, 0);
const cast = resolve$2;
const async = (callback, arg) => config.async(callback, arg);
function on$2() {
config.on(...arguments);
}
function off() {
config.off(...arguments);
}
// Set up instrumentation through `window.__PROMISE_INTRUMENTATION__`
if (typeof window !== 'undefined' && typeof window['__PROMISE_INSTRUMENTATION__'] === 'object') {
let callbacks = window['__PROMISE_INSTRUMENTATION__'];
configure('instrument', true);
for (let eventName in callbacks) {
if (callbacks.hasOwnProperty(eventName)) {
on$2(eventName, callbacks[eventName]);
}
}
}
// the default export here is for backwards compat:
// https://github.com/tildeio/rsvp.js/issues/434
const RSVP = {
asap,
cast,
Promise: Promise$2,
EventTarget,
all,
allSettled,
race,
hash: hash$2,
hashSettled,
rethrow,
defer,
denodeify,
configure,
on: on$2,
off,
resolve: resolve$2,
reject,
map: map$2,
async,
filter: filter$1
};
const rsvp = /*#__PURE__*/Object.defineProperty({
__proto__: null,
EventTarget,
Promise: Promise$2,
all,
allSettled,
asap,
async,
cast,
configure,
default: RSVP,
defer,
denodeify,
filter: filter$1,
hash: hash$2,
hashSettled,
map: map$2,
off,
on: on$2,
race,
reject,
resolve: resolve$2,
rethrow
}, Symbol.toStringTag, { value: 'Module' });
configure('async', (callback, promise) => {
_backburner.schedule('actions', null, callback, promise);
});
configure('after', cb => {
_backburner.schedule(_rsvpErrorQueue, null, cb);
});
on$2('error', onerrorDefault);
function onerrorDefault(reason) {
let error = errorFor(reason);
if (error) {
let overrideDispatch = getDispatchOverride();
if (overrideDispatch) {
overrideDispatch(error);
} else {
throw error;
}
}
}
function errorFor(reason) {
if (!reason) return;
let withErrorThrown = reason;
if (withErrorThrown.errorThrown) {
return unwrapErrorThrown(withErrorThrown);
}
let withName = reason;
if (withName.name === 'UnrecognizedURLError') {
return;
}
if (reason.name === 'TransitionAborted') {
return;
}
return reason;
}
function unwrapErrorThrown(reason) {
let error = reason.errorThrown;
if (typeof error === 'string') {
error = new Error(error);
}
Object.defineProperty(error, '__reason_with_error_thrown__', {
value: reason,
enumerable: false
});
return error;
}
const emberinternalsRuntimeLibExtRsvp = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: rsvp,
onerrorDefault
}, Symbol.toStringTag, { value: 'Module' });
// just for side effect of extending Ember.RSVP
const emberinternalsRuntimeIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
ActionHandler,
Comparable,
ContainerProxyMixin,
MutableEnumerable,
RSVP: rsvp,
RegistryProxyMixin,
TargetActionSupport,
_ProxyMixin: ProxyMixin,
_contentFor: contentFor,
onerrorDefault
}, Symbol.toStringTag, { value: 'Module' });
const {
isArray: isArray$3
} = Array;
/**
@module @ember/array
*/
/**
Forces the passed object to be part of an array. If the object is already
an array, it will return the object. Otherwise, it will add the object to
an array. If object is `null` or `undefined`, it will return an empty array.
```javascript
import { makeArray } from '@ember/array';
import ArrayProxy from '@ember/array/proxy';
makeArray(); // []
makeArray(null); // []
makeArray(undefined); // []
makeArray('lindsay'); // ['lindsay']
makeArray([1, 2, 42]); // [1, 2, 42]
let proxy = ArrayProxy.create({ content: [] });
makeArray(proxy) === proxy; // false
```
@method makeArray
@static
@for @ember/array
@param {Object} obj the object
@return {Array}
@private
*/
function makeArray(obj) {
if (obj === null || obj === undefined) {
return [];
}
return isArray$3(obj) ? obj : [obj];
}
const emberArrayLibMakeArray = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: makeArray
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/object/core
*/
// TODO: Is this correct?
function hasSetUnknownProperty(val) {
return typeof val === 'object' && val !== null && typeof val.setUnknownProperty === 'function';
}
function hasToStringExtension(val) {
return typeof val === 'object' && val !== null && typeof val.toStringExtension === 'function';
}
const reopen = Mixin.prototype.reopen;
const wasApplied = new WeakSet();
const prototypeMixinMap = new WeakMap();
const destroyCalled = new Set();
function ensureDestroyCalled(instance) {
if (!destroyCalled.has(instance)) {
instance.destroy();
}
}
function initialize(obj, properties) {
let m = meta(obj);
if (properties !== undefined) {
let concatenatedProperties = obj.concatenatedProperties;
let mergedProperties = obj.mergedProperties;
let keyNames = Object.keys(properties);
for (let keyName of keyNames) {
// SAFETY: this cast as a Record is safe because all object types can be
// indexed in JS, and we explicitly type it as returning `unknown`, so the
// result *must* be checked below.
let value = properties[keyName];
let possibleDesc = descriptorForProperty(obj, keyName, m);
let isDescriptor = possibleDesc !== undefined;
if (!isDescriptor) {
if (concatenatedProperties !== undefined && concatenatedProperties.length > 0 && concatenatedProperties.includes(keyName)) {
let baseValue = obj[keyName];
if (baseValue) {
value = makeArray(baseValue).concat(value);
} else {
value = makeArray(value);
}
}
if (mergedProperties !== undefined && mergedProperties.length > 0 && mergedProperties.includes(keyName)) {
let baseValue = obj[keyName];
value = Object.assign({}, baseValue, value);
}
}
if (isDescriptor) {
possibleDesc.set(obj, keyName, value);
} else if (hasSetUnknownProperty(obj) && !(keyName in obj)) {
obj.setUnknownProperty(keyName, value);
} else {
{
obj[keyName] = value;
}
}
}
}
obj.init(properties);
m.unsetInitializing();
let observerEvents = m.observerEvents();
if (observerEvents !== undefined) {
for (let i = 0; i < observerEvents.length; i++) {
activateObserver(obj, observerEvents[i].event, observerEvents[i].sync);
}
}
sendEvent(obj, 'init', 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 {
/** @internal */
[OWNER$1];
constructor(owner) {
this[OWNER$1] = owner;
// prepare prototype...
this.constructor.proto();
let self;
{
self = this;
}
const destroyable = self;
registerDestructor$1(self, ensureDestroyCalled, true);
registerDestructor$1(self, () => destroyable.willDestroy());
// disable chains
let m = meta(self);
m.setInitializing();
}
reopen(...args) {
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(_properties) {}
/**
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 isDestroyed(this);
}
set isDestroyed(_value) {
}
/**
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 isDestroying(this);
}
set isDestroying(_value) {
}
/**
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 {
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() {
let extension = hasToStringExtension(this) ? `:${this.toStringExtension()}` : '';
return `<${getFactoryFor(this) || '(unknown)'}:${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(...mixins) {
let Class = class extends this {};
reopen.apply(Class.PrototypeMixin, mixins);
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(...args) {
let props = args[0];
let instance;
if (props !== undefined) {
instance = new this(getOwner$2(props));
// TODO(SAFETY): at present, we cannot actually rely on this being set,
// because a number of acceptance tests are (incorrectly? Unclear!)
// relying on the ability to run through this path with `factory` being
// `undefined`. It's *possible* that actually means that the type for
// `setFactoryFor()` should allow `undefined`, but we typed it the other
// way for good reason! Accordingly, this *casts* `factory`, and the
// commented-out `assert()` is here in the hope that we can enable it
// after addressing tests *or* updating the call signature here.
let factory = getFactoryFor(props);
// assert(`missing factory when creating object ${instance}`, factory !== undefined);
setFactoryFor(instance, factory);
} else {
instance = new this();
}
if (args.length <= 1) {
initialize(instance, props);
} else {
initialize(instance, flattenProps.apply(this, args));
}
// SAFETY: The `initialize` call is responsible to merge the prototype chain
// so that this holds.
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(...args) {
this.willReopen();
reopen.apply(this.PrototypeMixin, args);
return this;
}
static willReopen() {
let 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, 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(...mixins) {
applyMixin(this, mixins);
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) {
let proto = this.proto(); // ensure prototype is initialized
let possibleDesc = descriptorForProperty(proto, key);
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
let empty = {};
meta(this.prototype).forEachDescriptors((name, descriptor) => {
if (descriptor.enumerable) {
let meta = descriptor._meta || empty;
callback.call(binding, name, meta);
}
});
}
static get PrototypeMixin() {
let prototypeMixin = prototypeMixinMap.get(this);
if (prototypeMixin === undefined) {
prototypeMixin = Mixin.create();
prototypeMixin.ownerConstructor = this;
prototypeMixinMap.set(this, prototypeMixin);
}
return prototypeMixin;
}
static get superclass() {
let c = Object.getPrototypeOf(this);
return c !== Function.prototype ? c : undefined;
}
static proto() {
let p = this.prototype;
if (!wasApplied.has(p)) {
wasApplied.add(p);
let 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 `<${getFactoryFor(this) || '(unknown)'}:constructor>`;
}
static isClass = true;
static isMethod = false;
static _onLookup;
static _lazyInjections;
}
function flattenProps(...props) {
let initProperties = {};
for (let properties of props) {
let keyNames = Object.keys(properties);
for (let j = 0, k = keyNames.length; j < k; j++) {
let keyName = keyNames[j];
let value = properties[keyName];
initProperties[keyName] = value;
}
}
return initProperties;
}
const emberObjectCore = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: CoreObject
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/object/observable
*/
/**
## 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
*/
const Observable = Mixin.create({
get(keyName) {
return get$2(this, keyName);
},
getProperties(...args) {
return getProperties(this, ...args);
},
set(keyName, value) {
return set(this, keyName, value);
},
setProperties(hash) {
return 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() {
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() {
endPropertyChanges();
return this;
},
notifyPropertyChange(keyName) {
notifyPropertyChange(this, keyName);
return this;
},
addObserver(key, target, method, sync) {
addObserver(this, key, target, method, sync);
return this;
},
removeObserver(key, target, method, sync) {
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 hasListeners(this, `${key}:change`);
},
incrementProperty(keyName, increment = 1) {
return set(this, keyName, (parseFloat(get$2(this, keyName)) || 0) + increment);
},
decrementProperty(keyName, decrement = 1) {
return set(this, keyName, (get$2(this, keyName) || 0) - decrement);
},
toggleProperty(keyName) {
return set(this, keyName, !get$2(this, keyName));
},
cacheFor(keyName) {
let meta = peekMeta(this);
return meta !== null ? meta.valueFor(keyName) : undefined;
}
});
const emberObjectObservable = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: Observable
}, Symbol.toStringTag, { value: 'Module' });
/**
@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
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
class EmberObject extends CoreObject.extend(Observable) {
get _debugContainerKey() {
let factory = getFactoryFor(this);
return factory !== undefined && factory.fullName;
}
}
/**
Decorator that turns the target function into an Action which can be accessed
directly by reference.
```js
import Component from '@ember/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
export default class Tooltip extends Component {
@tracked isShowing = false;
@action
toggleShowing() {
this.isShowing = !this.isShowing;
}
}
```
```hbs
<!-- template.hbs -->
<button {{on "click" this.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:
```js
import Component from '@ember/component';
import { tracked } from '@glimmer/tracking';
import { action } 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);
}
@tracked isShowing = false;
@action
toggleShowing() {
this.isShowing = !this.isShowing;
}
}
```
@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
*/
const BINDINGS_MAP = new WeakMap();
function hasProto(obj) {
return obj != null && obj.constructor !== undefined && typeof obj.constructor.proto === 'function';
}
function setupAction(target, key, actionFn) {
if (hasProto(target)) {
target.constructor.proto();
}
if (!Object.prototype.hasOwnProperty.call(target, 'actions')) {
let 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() {
let bindings = BINDINGS_MAP.get(this);
if (bindings === undefined) {
bindings = new Map();
BINDINGS_MAP.set(this, bindings);
}
let fn = bindings.get(actionFn);
if (fn === undefined) {
fn = actionFn.bind(this);
bindings.set(actionFn, fn);
}
return fn;
}
};
}
function action$1(...args) {
let actionFn;
if (!isElementDescriptor(args)) {
actionFn = args[0];
let decorator = function (target, key, _desc, _meta, isClassicDecorator) {
return setupAction(target, key, actionFn);
};
setClassicDecorator(decorator);
return decorator;
}
let [target, key, desc] = args;
actionFn = desc?.value;
return setupAction(target, key, actionFn);
}
// SAFETY: TS types are weird with decorators. This should work.
setClassicDecorator(action$1);
// ..........................................................
// OBSERVER HELPER
//
/**
Specify a method that observes property changes.
```javascript
import EmberObject from '@ember/object';
import { observer } from '@ember/object';
export default EmberObject.extend({
valueObserver: observer('value', function() {
// Executes whenever the "value" property changes
})
});
```
Also available as `Function.prototype.observes` if prototype extensions are
enabled.
@method observer
@for @ember/object
@param {String} propertyNames*
@param {Function} func
@return func
@public
@static
*/
function observer(...args) {
let funcOrDef = args.pop();
let func;
let dependentKeys;
let sync;
if (typeof funcOrDef === 'function') {
func = funcOrDef;
dependentKeys = args;
sync = !ENV._DEFAULT_ASYNC_OBSERVERS;
} else {
func = funcOrDef.fn;
dependentKeys = funcOrDef.dependentKeys;
sync = funcOrDef.sync;
}
let paths = [];
for (let dependentKey of dependentKeys) {
expandProperties(dependentKey, path => paths.push(path));
}
setObservers(func, {
paths,
sync
});
return func;
}
const emberObjectIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
action: action$1,
computed,
default: EmberObject,
defineProperty,
get: get$2,
getProperties,
notifyPropertyChange,
observer,
set,
setProperties,
trySet
}, Symbol.toStringTag, { value: 'Module' });
/**
* Default component template, which is a plain yield
*/
const DEFAULT_TEMPLATE_BLOCK = [[[opcodes.Yield, 1, null]], ["&default"], !1, []],
DEFAULT_TEMPLATE = {
// random uuid
id: "1b32f5c2-7623-43d6-a0ad-9672898920a1",
moduleName: "__default__.hbs",
block: JSON.stringify(DEFAULT_TEMPLATE_BLOCK),
scope: null,
isStrictMode: !0
},
WELL_KNOWN_EMPTY_ARRAY = Object.freeze([]),
STARTER_CONSTANTS = constants(WELL_KNOWN_EMPTY_ARRAY),
WELL_KNOWN_EMPTY_ARRAY_POSITION = STARTER_CONSTANTS.indexOf(WELL_KNOWN_EMPTY_ARRAY);
class CompileTimeConstantImpl {
// `0` means NULL
values = STARTER_CONSTANTS.slice();
indexMap = new Map(this.values.map((value, index) => [value, index]));
value(value) {
let indexMap = this.indexMap,
index = indexMap.get(value);
return void 0 === index && (index = this.values.push(value) - 1, indexMap.set(value, index)), index;
}
array(values) {
if (0 === values.length) return WELL_KNOWN_EMPTY_ARRAY_POSITION;
let handles = new Array(values.length);
for (let i = 0; i < values.length; i++) handles[i] = this.value(values[i]);
return this.value(handles);
}
toPool() {
return this.values;
}
}
class RuntimeConstantsImpl {
values;
constructor(pool) {
this.values = pool;
}
getValue(handle) {
return this.values[handle];
}
getArray(value) {
let handles = this.getValue(value),
reified = new Array(handles.length);
for (const [i, n] of enumerate(handles)) reified[i] = this.getValue(n);
return reified;
}
}
class ConstantsImpl extends CompileTimeConstantImpl {
reifiedArrs = {
[WELL_KNOWN_EMPTY_ARRAY_POSITION]: WELL_KNOWN_EMPTY_ARRAY
};
defaultTemplate = 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
helperDefinitionCount = 0;
modifierDefinitionCount = 0;
componentDefinitionCount = 0;
helperDefinitionCache = new WeakMap();
modifierDefinitionCache = new WeakMap();
componentDefinitionCache = new WeakMap();
helper(definitionState,
// TODO: Add a way to expose resolved name for debugging
_resolvedName = null, isOptional) {
let handle = this.helperDefinitionCache.get(definitionState);
if (void 0 === handle) {
let managerOrHelper = getInternalHelperManager(definitionState, isOptional);
if (null === managerOrHelper) return this.helperDefinitionCache.set(definitionState, null), null;
debugAssert(managerOrHelper, "BUG: expected manager or helper");
let helper = "function" == typeof managerOrHelper ? managerOrHelper : managerOrHelper.getHelper(definitionState);
handle = this.value(helper), this.helperDefinitionCache.set(definitionState, handle), this.helperDefinitionCount++;
}
return handle;
}
modifier(definitionState, resolvedName = null, isOptional) {
let handle = this.modifierDefinitionCache.get(definitionState);
if (void 0 === handle) {
let manager = getInternalModifierManager(definitionState, isOptional);
if (null === manager) return this.modifierDefinitionCache.set(definitionState, null), null;
let definition = {
resolvedName: resolvedName,
manager: manager,
state: definitionState
};
handle = this.value(definition), this.modifierDefinitionCache.set(definitionState, handle), this.modifierDefinitionCount++;
}
return handle;
}
component(definitionState, owner, isOptional) {
let definition = this.componentDefinitionCache.get(definitionState);
if (void 0 === definition) {
let manager = getInternalComponentManager(definitionState, isOptional);
if (null === manager) return this.componentDefinitionCache.set(definitionState, null), null;
debugAssert(manager, "BUG: expected manager");
let template,
capabilities = capabilityFlagsFrom(manager.getCapabilities(definitionState)),
templateFactory = getComponentTemplate(definitionState),
compilable = null;
template = managerHasCapability(manager, capabilities, InternalComponentCapabilities.dynamicLayout) ? templateFactory?.(owner) : templateFactory?.(owner) ?? this.defaultTemplate, void 0 !== template && (template = unwrapTemplate(template), compilable = managerHasCapability(manager, capabilities, InternalComponentCapabilities.wrapped) ? template.asWrappedLayout() : template.asLayout()), definition = {
resolvedName: null,
handle: -1,
// replaced momentarily
manager: manager,
capabilities: capabilities,
state: definitionState,
compilable: compilable
}, definition.handle = this.value(definition), this.componentDefinitionCache.set(definitionState, definition), this.componentDefinitionCount++;
}
return definition;
}
resolvedComponent(resolvedDefinition, resolvedName) {
let definition = this.componentDefinitionCache.get(resolvedDefinition);
if (void 0 === definition) {
let {
manager: manager,
state: state,
template: template
} = resolvedDefinition,
capabilities = capabilityFlagsFrom(manager.getCapabilities(resolvedDefinition)),
compilable = null;
managerHasCapability(manager, capabilities, InternalComponentCapabilities.dynamicLayout) || (template = template ?? this.defaultTemplate), null !== template && (template = unwrapTemplate(template), compilable = managerHasCapability(manager, capabilities, InternalComponentCapabilities.wrapped) ? template.asWrappedLayout() : template.asLayout()), definition = {
resolvedName: resolvedName,
handle: -1,
// replaced momentarily
manager: manager,
capabilities: capabilities,
state: state,
compilable: compilable
}, definition.handle = this.value(definition), this.componentDefinitionCache.set(resolvedDefinition, definition), this.componentDefinitionCount++;
}
return expect(definition, "BUG: resolved component definitions cannot be null");
}
getValue(index) {
return debugAssert(index >= 0, `cannot get value for handle: ${index}`), this.values[index];
}
getArray(index) {
let reifiedArrs = this.reifiedArrs,
reified = reifiedArrs[index];
if (void 0 === reified) {
let names = this.getValue(index);
reified = new Array(names.length);
for (const [i, name] of enumerate(names)) reified[i] = this.getValue(name);
reifiedArrs[index] = reified;
}
return reified;
}
}
class RuntimeOpImpl {
offset = 0;
constructor(heap) {
this.heap = heap;
}
get size() {
return 1 + ((this.heap.getbyaddr(this.offset) & OPERAND_LEN_MASK) >> ARG_SHIFT);
}
get isMachine() {
return this.heap.getbyaddr(this.offset) & MACHINE_MASK ? 1 : 0;
}
get type() {
return this.heap.getbyaddr(this.offset) & 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);
}
}
var TableSlotState = function (TableSlotState) {
return TableSlotState[TableSlotState.Allocated = 0] = "Allocated", TableSlotState[TableSlotState.Freed = 1] = "Freed", TableSlotState[TableSlotState.Purged = 2] = "Purged", TableSlotState[TableSlotState.Pointer = 3] = "Pointer", TableSlotState;
}(TableSlotState || {});
class RuntimeHeapImpl {
heap;
table;
constructor(serializedHeap) {
let {
buffer: buffer,
table: 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 unwrap$1(this.table[handle]);
}
getbyaddr(address) {
return expect(this.heap[address], "Access memory out of bounds of the heap");
}
sizeof(handle) {
return this.table, -1;
}
}
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 {
offset = 0;
heap;
handleTable;
handleState;
handle = 0;
constructor() {
this.heap = new Int32Array(1048576), this.handleTable = [], this.handleState = [];
}
pushRaw(value) {
this.sizeCheck(), this.heap[this.offset++] = value;
}
pushOp(item) {
this.pushRaw(item);
}
pushMachine(item) {
this.pushRaw(item | MACHINE_MASK);
}
sizeCheck() {
let {
heap: heap
} = this;
if (this.offset === this.heap.length) {
let newHeap = new Int32Array(heap.length + 1048576);
newHeap.set(heap, 0), this.heap = newHeap;
}
}
getbyaddr(address) {
return unwrap$1(this.heap[address]);
}
setbyaddr(address, value) {
this.heap[address] = value;
}
malloc() {
// push offset, info, size
return this.handleTable.push(this.offset), 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 unwrap$1(this.handleTable[handle]);
}
sizeof(handle) {
return this.handleTable, -1;
}
free(handle) {
this.handleState[handle] = TableSlotState.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() {
let compactedSize = 0,
{
handleTable: handleTable,
handleState: handleState,
heap: heap
} = this;
for (let i = 0; i < length; i++) {
let offset = unwrap$1(handleTable[i]),
size = unwrap$1(handleTable[i + 1]) - unwrap$1(offset),
state = handleState[i];
if (state !== TableSlotState.Purged) if (state === TableSlotState.Freed)
// transition to "already freed" aka "purged"
// a good improvement would be to reuse
// these slots
handleState[i] = TableSlotState.Purged, compactedSize += size;else if (state === TableSlotState.Allocated) {
for (let j = offset; j <= i + size; j++) heap[j - compactedSize] = unwrap$1(heap[j]);
handleTable[i] = offset - compactedSize;
} else state === TableSlotState.Pointer && (handleTable[i] = offset - compactedSize);
}
this.offset = this.offset - compactedSize;
}
capture(offset = this.offset) {
// Only called in eager mode
let buffer = function (arr, start, end) {
if (void 0 !== arr.slice) return arr.slice(start, end);
let ret = new Int32Array(end);
for (; start < end; start++) ret[start] = unwrap$1(arr[start]);
return ret;
}(this.heap, 0, offset).buffer;
return {
handle: this.handle,
table: this.handleTable,
buffer: buffer
};
}
}
class RuntimeProgramImpl {
_opcode;
constructor(constants, heap) {
this.constants = constants, this.heap = heap, this._opcode = new RuntimeOpImpl(this.heap);
}
opcode(offset) {
return this._opcode.offset = offset, this._opcode;
}
}
function artifacts() {
return {
constants: new ConstantsImpl(),
heap: new HeapImpl()
};
}
const glimmerProgram = /*#__PURE__*/Object.defineProperty({
__proto__: null,
CompileTimeConstantImpl,
ConstantsImpl,
HeapImpl,
RuntimeConstantsImpl,
RuntimeHeapImpl,
RuntimeOpImpl,
RuntimeProgramImpl,
artifacts,
hydrateHeap
}, Symbol.toStringTag, { value: 'Module' });
/* This file is generated by build/debug.js */
new Array(Op.Size).fill(null), new Array(Op.Size).fill(null);
class DynamicScopeImpl {
bucket;
constructor(bucket) {
this.bucket = bucket ? assign({}, bucket) : {};
}
get(key) {
return unwrap$1(this.bucket[key]);
}
set(key, reference) {
return this.bucket[key] = reference;
}
child() {
return new DynamicScopeImpl(this.bucket);
}
}
class PartialScopeImpl {
static root(self, size = 0, owner) {
let refs = new Array(size + 1).fill(UNDEFINED_REFERENCE);
return new PartialScopeImpl(refs, owner, null, null, null).init({
self: self
});
}
static sized(size = 0, owner) {
let refs = new Array(size + 1).fill(UNDEFINED_REFERENCE);
return new PartialScopeImpl(refs, owner, null, null, null);
}
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;
}
init({
self: self
}) {
return this.slots[0] = self, this;
}
getSelf() {
return this.get(0);
}
getSymbol(symbol) {
return this.get(symbol);
}
getBlock(symbol) {
let block = this.get(symbol);
return block === UNDEFINED_REFERENCE ? null : block;
}
getEvalScope() {
return this.evalScope;
}
getPartialMap() {
return this.partialMap;
}
bind(symbol, value) {
this.set(symbol, value);
}
bindSelf(self) {
this.set(0, self);
}
bindSymbol(symbol, value) {
this.set(symbol, value);
}
bindBlock(symbol, value) {
this.set(symbol, 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;
}
}
// These symbols represent "friend" properties that are used inside of
// the VM in other classes, but are not intended to be a part of
// Glimmer's API.
const INNER_VM = Symbol("INNER_VM"),
DESTROYABLE_STACK = Symbol("DESTROYABLE_STACK"),
STACKS = Symbol("STACKS"),
REGISTERS = Symbol("REGISTERS"),
HEAP = Symbol("HEAP"),
CONSTANTS = Symbol("CONSTANTS"),
ARGS$1 = Symbol("ARGS");
class CursorImpl {
constructor(element, nextSibling) {
this.element = element, this.nextSibling = nextSibling;
}
}
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;
}
}
function move(bounds, reference) {
let parent = bounds.parentElement(),
first = bounds.firstNode(),
last = bounds.lastNode(),
current = first;
// eslint-disable-next-line no-constant-condition
for (;;) {
let next = current.nextSibling;
if (parent.insertBefore(current, reference), current === last) return next;
current = expect(next, "invalid bounds");
}
}
function clear(bounds) {
let parent = bounds.parentElement(),
first = bounds.firstNode(),
last = bounds.lastNode(),
current = first;
// eslint-disable-next-line no-constant-condition
for (;;) {
let next = current.nextSibling;
if (parent.removeChild(current), current === last) return next;
current = expect(next, "invalid bounds");
}
}
function normalizeStringValue(value) {
return isEmpty$2(value) ? "" : String(value);
}
function isEmpty$2(value) {
return null == value || "function" != typeof value.toString;
}
function isSafeString(value) {
return "object" == typeof value && null !== value && "function" == typeof value.toHTML;
}
function isNode(value) {
return "object" == typeof value && null !== value && "number" == typeof value.nodeType;
}
function isString(value) {
return "string" == typeof value;
}
/*
* @method normalizeProperty
* @param element {HTMLElement}
* @param slotName {String}
* @returns {Object} { name, type }
*/
function normalizeProperty(element, slotName) {
let type, normalized;
if (slotName in element) normalized = slotName, type = "prop";else {
let lower = slotName.toLowerCase();
lower in element ? (type = "prop", normalized = lower) : (type = "attr", normalized = slotName);
}
return "prop" !== type || "style" !== normalized.toLowerCase() && !function (tagName, propName) {
let tag = ATTR_OVERRIDES[tagName.toUpperCase()];
return tag && tag[propName.toLowerCase()] || !1;
}(element.tagName, normalized) || (type = "attr"), {
normalized: normalized,
type: type
};
}
// properties that MUST be set as attributes, due to:
// * browser bug
// * strange spec outlier
const ATTR_OVERRIDES = {
INPUT: {
form: !0,
// 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: !0,
// Chrome 54.0.2840.98: 'list' in document.createElement('input') === true
// Safari 9.1.3: 'list' in document.createElement('input') === false
list: !0
},
// element.form is actually a legitimate readOnly property, that is to be
// mutated, but must be mutated by setAttribute...
SELECT: {
form: !0
},
OPTION: {
form: !0
},
TEXTAREA: {
form: !0
},
LABEL: {
form: !0
},
FIELDSET: {
form: !0
},
LEGEND: {
form: !0
},
OBJECT: {
form: !0
},
OUTPUT: {
form: !0
},
BUTTON: {
form: !0
}
},
badProtocols = ["javascript:", "vbscript:"],
badTags = ["A", "BODY", "LINK", "IMG", "IFRAME", "BASE", "FORM"],
badTagsForDataURI = ["EMBED"],
badAttributes = ["href", "src", "background", "action"],
badAttributesForDataURI = ["src"];
function has(array, item) {
return -1 !== array.indexOf(item);
}
function checkURI(tagName, attribute) {
return (null === tagName || has(badTags, tagName)) && has(badAttributes, attribute);
}
function checkDataURI(tagName, attribute) {
return null !== tagName && has(badTagsForDataURI, tagName) && has(badAttributesForDataURI, attribute);
}
function requiresSanitization(tagName, attribute) {
return checkURI(tagName, attribute) || checkDataURI(tagName, attribute);
}
let _protocolForUrlImplementation;
function sanitizeAttributeValue(element, attribute, value) {
let tagName = null;
if (null == value) return value;
if (isSafeString(value)) return value.toHTML();
tagName = element ? element.tagName.toUpperCase() : null;
let str = normalizeStringValue(value);
if (checkURI(tagName, attribute)) {
let protocol = (url = str, _protocolForUrlImplementation || (_protocolForUrlImplementation = function () {
if ("object" == typeof URL && null !== URL &&
// 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`
"function" == typeof URL.parse) {
// 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')`.
let nodeURL = URL;
return url => {
let protocol = null;
return "string" == typeof url && (protocol = nodeURL.parse(url).protocol), null === protocol ? ":" : protocol;
};
}
if ("function" == typeof URL) return _url => {
try {
return new URL(_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 ":";
}
};
throw new Error('@glimmer/runtime needs a valid "globalThis.URL"');
}()), _protocolForUrlImplementation(url));
if (has(badProtocols, protocol)) return `unsafe:${str}`;
}
var url;
return checkDataURI(tagName, attribute) ? `unsafe:${str}` : str;
}
function dynamicAttribute(element, attr, namespace, isTrusting = !1) {
const {
tagName: tagName,
namespaceURI: namespaceURI
} = element,
attribute = {
element: element,
name: attr,
namespace: namespace
};
if (namespaceURI === NS_SVG) return buildDynamicAttribute(tagName, attr, attribute);
const {
type: type,
normalized: normalized
} = normalizeProperty(element, attr);
return "attr" === type ? buildDynamicAttribute(tagName, normalized, attribute) : function (tagName, name, attribute) {
return requiresSanitization(tagName, name) ? new SafeDynamicProperty(name, attribute) : function (tagName, attribute) {
return ("INPUT" === tagName || "TEXTAREA" === tagName) && "value" === attribute;
}(tagName, name) ? new InputValueDynamicAttribute(name, attribute) : function (tagName, attribute) {
return "OPTION" === tagName && "selected" === attribute;
}(tagName, name) ? new OptionSelectedDynamicAttribute(name, attribute) : new DefaultDynamicProperty(name, attribute);
}(tagName, normalized, attribute);
}
function buildDynamicAttribute(tagName, name, attribute) {
return requiresSanitization(tagName, name) ? new SafeDynamicAttribute(attribute) : new SimpleDynamicAttribute(attribute);
}
class DynamicAttribute {
constructor(attribute) {
this.attribute = attribute;
}
}
class SimpleDynamicAttribute extends DynamicAttribute {
set(dom, value, _env) {
const normalizedValue = normalizeValue(value);
if (null !== normalizedValue) {
const {
name: name,
namespace: namespace
} = this.attribute;
dom.__setAttribute(name, normalizedValue, namespace);
}
}
update(value, _env) {
const normalizedValue = normalizeValue(value),
{
element: element,
name: name
} = this.attribute;
null === normalizedValue ? element.removeAttribute(name) : element.setAttribute(name, normalizedValue);
}
}
class DefaultDynamicProperty extends DynamicAttribute {
constructor(normalizedName, attribute) {
super(attribute), this.normalizedName = normalizedName;
}
value;
set(dom, value, _env) {
null != value && (this.value = value, dom.__setProperty(this.normalizedName, value));
}
update(value, _env) {
const {
element: element
} = this.attribute;
this.value !== value && (element[this.normalizedName] = this.value = value, null == value && this.removeAttribute());
}
removeAttribute() {
// TODO this sucks but to preserve properties first and to meet current
// semantics we must do this.
const {
element: element,
namespace: namespace
} = this.attribute;
namespace ? element.removeAttributeNS(namespace, this.normalizedName) : element.removeAttribute(this.normalizedName);
}
}
class SafeDynamicProperty extends DefaultDynamicProperty {
set(dom, value, env) {
const {
element: element,
name: name
} = this.attribute,
sanitized = sanitizeAttributeValue(element, name, value);
super.set(dom, sanitized, env);
}
update(value, env) {
const {
element: element,
name: name
} = this.attribute,
sanitized = sanitizeAttributeValue(element, name, value);
super.update(sanitized, env);
}
}
class SafeDynamicAttribute extends SimpleDynamicAttribute {
set(dom, value, env) {
const {
element: element,
name: name
} = this.attribute,
sanitized = sanitizeAttributeValue(element, name, value);
super.set(dom, sanitized, env);
}
update(value, env) {
const {
element: element,
name: name
} = this.attribute,
sanitized = sanitizeAttributeValue(element, name, value);
super.update(sanitized, env);
}
}
class InputValueDynamicAttribute extends DefaultDynamicProperty {
set(dom, value) {
dom.__setProperty("value", normalizeStringValue(value));
}
update(value) {
const input = castToBrowser(this.attribute.element, ["input", "textarea"]),
currentValue = input.value,
normalizedValue = normalizeStringValue(value);
currentValue !== normalizedValue && (input.value = normalizedValue);
}
}
class OptionSelectedDynamicAttribute extends DefaultDynamicProperty {
set(dom, value) {
null != value && !1 !== value && dom.__setProperty("selected", !0);
}
update(value) {
castToBrowser(this.attribute.element, "option").selected = !!value;
}
}
function normalizeValue(value) {
return !1 === value || null == value || void 0 === value.toString ? null : !0 === value ? "" :
// onclick function etc in SSR
"function" == typeof value ? null : String(value);
}
class First {
constructor(node) {
this.node = node;
}
firstNode() {
return this.node;
}
}
class Last {
constructor(node) {
this.node = node;
}
lastNode() {
return this.node;
}
}
const CURSOR_STACK = Symbol("CURSOR_STACK");
class NewElementBuilder {
dom;
updateOperations;
constructing = null;
operations = null;
env;
[CURSOR_STACK] = new StackImpl();
modifierStack = new StackImpl();
blockStack = new StackImpl();
static forInitialRender(env, cursor) {
return new this(env, cursor.element, cursor.nextSibling).initialize();
}
static resume(env, block) {
let stack = new this(env, block.parentElement(), block.reset(env)).initialize();
return stack.pushLiveBlock(block), stack;
}
constructor(env, parentNode, nextSibling) {
this.pushElement(parentNode, nextSibling), this.env = env, this.dom = env.getAppendOperations(), this.updateOperations = env.getDOM();
}
initialize() {
return this.pushSimpleBlock(), 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 expect(this.blockStack.current, "Expected a current live block");
}
popElement() {
this[CURSOR_STACK].pop(), expect(this[CURSOR_STACK].current, "can't pop past the last element");
}
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 = !1) {
let current = this.blockStack.current;
return null !== current && (isRemote || current.didAppendBounds(block)), this.__openBlock(), this.blockStack.push(block), block;
}
popBlock() {
return this.block().finalize(this), this.__closeBlock(), expect(this.blockStack.pop(), "Expected popBlock to return a block");
}
__openBlock() {}
__closeBlock() {}
// todo return seems unused
openElement(tag) {
let element = this.__openElement(tag);
return this.constructing = element, element;
}
__openElement(tag) {
return this.dom.createElement(tag, this.element);
}
flushElement(modifiers) {
let parent = this.element,
element = expect(this.constructing, "flushElement should only be called when constructing an element");
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() {
return this.willCloseElement(), this.popElement(), this.popModifiers();
}
pushRemoteElement(element, guid, insertBefore) {
return this.__pushRemoteElement(element, guid, insertBefore);
}
__pushRemoteElement(element, _guid, insertBefore) {
if (this.pushElement(element, insertBefore), void 0 === insertBefore) for (; element.lastChild;) element.removeChild(element.lastChild);
let block = new RemoteLiveBlock(element);
return this.pushLiveBlock(block, !0);
}
popRemoteElement() {
const block = this.popBlock();
return debugAssert(block instanceof RemoteLiveBlock, "[BUG] expecting a RemoteLiveBlock"), this.popElement(), block;
}
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) {
return this.block().didAppendBounds(bounds), bounds;
}
didAppendNode(node) {
return this.block().didAppendNode(node), node;
}
didOpenElement(element) {
return this.block().openElement(element), element;
}
willCloseElement() {
this.block().closeElement();
}
appendText(string) {
return this.didAppendNode(this.__appendText(string));
}
__appendText(text) {
let {
dom: dom,
element: element,
nextSibling: nextSibling
} = this,
node = dom.createTextNode(text);
return dom.insertBefore(element, node, nextSibling), node;
}
__appendNode(node) {
return this.dom.insertBefore(this.element, node, this.nextSibling), node;
}
__appendFragment(fragment) {
let first = fragment.firstChild;
if (first) {
let ret = new ConcreteBounds(this.element, first, fragment.lastChild);
return this.dom.insertBefore(this.element, fragment, this.nextSibling), ret;
}
{
const comment = this.__appendComment("");
return new ConcreteBounds(this.element, comment, comment);
}
}
__appendHTML(html) {
return this.dom.insertHTMLBefore(this.element, this.nextSibling, html);
}
appendDynamicHTML(value) {
let bounds = this.trustedContent(value);
this.didAppendBounds(bounds);
}
appendDynamicText(value) {
let node = this.untrustedContent(value);
return this.didAppendNode(node), node;
}
appendDynamicFragment(value) {
let bounds = this.__appendFragment(value);
this.didAppendBounds(bounds);
}
appendDynamicNode(value) {
let node = this.__appendNode(value),
bounds = new ConcreteBounds(this.element, node, 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) {
let {
dom: dom,
element: element,
nextSibling: nextSibling
} = this,
node = dom.createComment(string);
return dom.insertBefore(element, node, nextSibling), 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) {
let attribute = dynamicAttribute(this.constructing, name, namespace, trusting);
return attribute.set(this, value, this.env), attribute;
}
}
class SimpleLiveBlock {
first = null;
last = null;
nesting = 0;
constructor(parent) {
this.parent = parent;
}
parentElement() {
return this.parent;
}
firstNode() {
return expect(this.first, "cannot call `firstNode()` while `SimpleLiveBlock` is still initializing").firstNode();
}
lastNode() {
return expect(this.last, "cannot call `lastNode()` while `SimpleLiveBlock` is still initializing").lastNode();
}
openElement(element) {
this.didAppendNode(element), this.nesting++;
}
closeElement() {
this.nesting--;
}
didAppendNode(node) {
0 === this.nesting && (this.first || (this.first = new First(node)), this.last = new Last(node));
}
didAppendBounds(bounds) {
0 === this.nesting && (this.first || (this.first = bounds), this.last = bounds);
}
finalize(stack) {
null === this.first && stack.appendComment("");
}
}
class RemoteLiveBlock extends SimpleLiveBlock {
constructor(parent) {
super(parent), registerDestructor$1(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.
this.parentElement() === this.firstNode().parentNode && clear(this);
});
}
}
class UpdatableBlockImpl extends SimpleLiveBlock {
reset() {
destroy(this);
let nextSibling = clear(this);
return this.first = null, this.last = null, this.nesting = 0, nextSibling;
}
}
// FIXME: All the noops in here indicate a modelling problem
class LiveBlockList {
constructor(parent, boundList) {
this.parent = parent, this.boundList = boundList, this.parent = parent, this.boundList = boundList;
}
parentElement() {
return this.parent;
}
firstNode() {
return expect(this.boundList[0], "cannot call `firstNode()` while `LiveBlockList` is still initializing").firstNode();
}
lastNode() {
let boundList = this.boundList;
return expect(boundList[boundList.length - 1], "cannot call `lastNode()` while `LiveBlockList` is still initializing").lastNode();
}
openElement(_element) {
debugAssert(!1, "Cannot openElement directly inside a block list");
}
closeElement() {
debugAssert(!1, "Cannot closeElement directly inside a block list");
}
didAppendNode(_node) {
debugAssert(!1, "Cannot create a new node directly inside a block list");
}
didAppendBounds(_bounds) {}
finalize(_stack) {
debugAssert(this.boundList.length > 0, "boundsList cannot be empty");
}
}
function clientBuilder(env, cursor) {
return NewElementBuilder.forInitialRender(env, cursor);
}
const APPEND_OPCODES = new class {
evaluateOpcode = new Array(Op.Size).fill(null);
add(name, evaluate, kind = "syscall") {
this.evaluateOpcode[name] = {
syscall: "machine" !== kind,
evaluate: evaluate
};
}
debugBefore(vm, opcode) {
return {
sp: void 0,
pc: vm.fetchValue($pc),
name: void 0,
params: void 0,
type: opcode.type,
isMachine: opcode.isMachine,
size: opcode.size,
state: void 0
};
}
debugAfter(vm, pre) {}
evaluate(vm, opcode, type) {
let operation = unwrap$1(this.evaluateOpcode[type]);
operation.syscall ? (debugAssert(!opcode.isMachine, `BUG: Mismatch between operation.syscall (${operation.syscall}) and opcode.isMachine (${opcode.isMachine}) for ${opcode.type}`), operation.evaluate(vm, opcode)) : (debugAssert(opcode.isMachine, `BUG: Mismatch between operation.syscall (${operation.syscall}) and opcode.isMachine (${opcode.isMachine}) for ${opcode.type}`), operation.evaluate(vm[INNER_VM], opcode));
}
}(),
TYPE = Symbol("TYPE"),
INNER = Symbol("INNER"),
OWNER = Symbol("OWNER"),
ARGS$2 = Symbol("ARGS"),
RESOLVED = Symbol("RESOLVED"),
CURRIED_VALUES = new WeakSet();
function isCurriedValue(value) {
return CURRIED_VALUES.has(value);
}
function isCurriedType(value, type) {
return isCurriedValue(value) && value[TYPE] === type;
}
class CurriedValue {
[TYPE];
[INNER];
[OWNER];
[ARGS$2];
[RESOLVED];
/** @internal */
constructor(type, inner, owner, args, resolved = !1) {
CURRIED_VALUES.add(this), this[TYPE] = type, this[INNER] = inner, this[OWNER] = owner, this[ARGS$2] = args, this[RESOLVED] = resolved;
}
}
function resolveCurriedValue(curriedValue) {
let positional,
named,
definition,
owner,
resolved,
currentWrapper = curriedValue;
// eslint-disable-next-line no-constant-condition
for (;;) {
let {
[ARGS$2]: curriedArgs,
[INNER]: inner
} = currentWrapper;
if (null !== curriedArgs) {
let {
named: curriedNamed,
positional: curriedPositional
} = curriedArgs;
curriedPositional.length > 0 && (positional = void 0 === positional ? curriedPositional : curriedPositional.concat(positional)), void 0 === named && (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: definition,
owner: owner,
resolved: resolved,
positional: positional,
named: named
};
}
function curry(type, spec, owner, args, resolved = !1) {
return new CurriedValue(type, spec, owner, args, resolved);
}
/** @internal */
function hasCustomDebugRenderTreeLifecycle(manager) {
return "getDebugCustomRenderTree" in manager;
}
APPEND_OPCODES.add(Op.ChildScope, vm => vm.pushChildScope()), APPEND_OPCODES.add(Op.PopScope, vm => vm.popScope()), APPEND_OPCODES.add(Op.PushDynamicScope, vm => vm.pushDynamicScope()), APPEND_OPCODES.add(Op.PopDynamicScope, vm => vm.popDynamicScope()), APPEND_OPCODES.add(Op.Constant, (vm, {
op1: other
}) => {
vm.stack.push(vm[CONSTANTS].getValue(decodeHandle(other)));
}), APPEND_OPCODES.add(Op.ConstantReference, (vm, {
op1: other
}) => {
vm.stack.push(createConstRef(vm[CONSTANTS].getValue(decodeHandle(other))));
}), APPEND_OPCODES.add(Op.Primitive, (vm, {
op1: primitive
}) => {
let stack = vm.stack;
if (isHandle(primitive)) {
// it is a handle which does not already exist on the stack
let value = vm[CONSTANTS].getValue(decodeHandle(primitive));
stack.push(value);
} else
// is already an encoded immediate or primitive handle
stack.push(decodeImmediate(primitive));
}), APPEND_OPCODES.add(Op.PrimitiveReference, vm => {
let ref,
stack = vm.stack,
value = stack.pop();
ref = void 0 === value ? UNDEFINED_REFERENCE : null === value ? NULL_REFERENCE : !0 === value ? TRUE_REFERENCE : !1 === value ? FALSE_REFERENCE : createPrimitiveRef(value), stack.push(ref);
}), APPEND_OPCODES.add(Op.Dup, (vm, {
op1: register,
op2: offset
}) => {
let position = vm.fetchValue(register) - offset;
vm.stack.dup(position);
}), APPEND_OPCODES.add(Op.Pop, (vm, {
op1: count
}) => {
vm.stack.pop(count);
}), APPEND_OPCODES.add(Op.Load, (vm, {
op1: register
}) => {
vm.load(register);
}), APPEND_OPCODES.add(Op.Fetch, (vm, {
op1: register
}) => {
vm.fetch(register);
}), APPEND_OPCODES.add(Op.BindDynamicScope, (vm, {
op1: _names
}) => {
let names = vm[CONSTANTS].getArray(_names);
vm.bindDynamicScope(names);
}), APPEND_OPCODES.add(Op.Enter, (vm, {
op1: args
}) => {
vm.enter(args);
}), APPEND_OPCODES.add(Op.Exit, vm => {
vm.exit();
}), APPEND_OPCODES.add(Op.PushSymbolTable, (vm, {
op1: _table
}) => {
vm.stack.push(vm[CONSTANTS].getValue(_table));
}), APPEND_OPCODES.add(Op.PushBlockScope, vm => {
vm.stack.push(vm.scope());
}), APPEND_OPCODES.add(Op.CompileBlock, vm => {
let stack = vm.stack,
block = stack.pop();
block ? stack.push(vm.compile(block)) : stack.push(null);
}), APPEND_OPCODES.add(Op.InvokeYield, vm => {
let {
stack: stack
} = vm,
handle = stack.pop(),
scope = stack.pop(),
table = stack.pop();
debugAssert(null === table || table && "object" == typeof table && Array.isArray(table.parameters), `Expected top of stack to be Option<BlockSymbolTable>, was ${String(table)}`);
let args = stack.pop();
if (null === table)
// To balance the pop{Frame,Scope}
return vm.pushFrame(), void vm.pushScope(scope ?? vm.scope());
let invokingScope = expect(scope, "BUG: expected scope");
// If necessary, create a child scope
{
let locals = table.parameters,
localsCount = locals.length;
if (localsCount > 0) {
invokingScope = invokingScope.child();
for (let i = 0; i < localsCount; i++) invokingScope.bindSymbol(unwrap$1(locals[i]), args.at(i));
}
}
vm.pushFrame(), vm.pushScope(invokingScope), vm.call(handle);
}), APPEND_OPCODES.add(Op.JumpIf, (vm, {
op1: target
}) => {
let reference = vm.stack.pop(),
value = Boolean(valueForRef(reference));
isConstRef(reference) ? !0 === value && vm.goto(target) : (!0 === value && vm.goto(target), vm.updateWith(new Assert(reference)));
}), APPEND_OPCODES.add(Op.JumpUnless, (vm, {
op1: target
}) => {
let reference = vm.stack.pop(),
value = Boolean(valueForRef(reference));
isConstRef(reference) ? !1 === value && vm.goto(target) : (!1 === value && vm.goto(target), vm.updateWith(new Assert(reference)));
}), APPEND_OPCODES.add(Op.JumpEq, (vm, {
op1: target,
op2: comparison
}) => {
vm.stack.peek() === comparison && vm.goto(target);
}), APPEND_OPCODES.add(Op.AssertSame, vm => {
let reference = vm.stack.peek();
!1 === isConstRef(reference) && vm.updateWith(new Assert(reference));
}), APPEND_OPCODES.add(Op.ToBoolean, vm => {
let {
stack: stack
} = vm,
valueRef = stack.pop();
stack.push(createComputeRef(() => toBool$1(valueForRef(valueRef))));
});
class Assert {
last;
constructor(ref) {
this.ref = ref, this.last = valueForRef(ref);
}
evaluate(vm) {
let {
last: last,
ref: ref
} = this;
last !== valueForRef(ref) && vm.throw();
}
}
class AssertFilter {
last;
constructor(ref, filter) {
this.ref = ref, this.filter = filter, this.last = filter(valueForRef(ref));
}
evaluate(vm) {
let {
last: last,
ref: ref,
filter: filter
} = this;
last !== filter(valueForRef(ref)) && vm.throw();
}
}
class JumpIfNotModifiedOpcode {
tag = CONSTANT_TAG;
lastRevision = INITIAL;
target;
finalize(tag, target) {
this.target = target, this.didModify(tag);
}
evaluate(vm) {
let {
tag: tag,
target: target,
lastRevision: lastRevision
} = this;
!vm.alwaysRevalidate && validateTag(tag, lastRevision) && (consumeTag(tag), vm.goto(expect(target, "VM BUG: Target must be set before attempting to jump")));
}
didModify(tag) {
this.tag = tag, this.lastRevision = valueForTag(this.tag), consumeTag(tag);
}
}
class BeginTrackFrameOpcode {
constructor(debugLabel) {
this.debugLabel = debugLabel;
}
evaluate() {
beginTrackFrame(this.debugLabel);
}
}
class EndTrackFrameOpcode {
constructor(target) {
this.target = target;
}
evaluate() {
let tag = endTrackFrame();
this.target.didModify(tag);
}
}
APPEND_OPCODES.add(Op.Text, (vm, {
op1: text
}) => {
vm.elements().appendText(vm[CONSTANTS].getValue(text));
}), APPEND_OPCODES.add(Op.Comment, (vm, {
op1: text
}) => {
vm.elements().appendComment(vm[CONSTANTS].getValue(text));
}), APPEND_OPCODES.add(Op.OpenElement, (vm, {
op1: tag
}) => {
vm.elements().openElement(vm[CONSTANTS].getValue(tag));
}), APPEND_OPCODES.add(Op.OpenDynamicElement, vm => {
let tagName = valueForRef(vm.stack.pop());
vm.elements().openElement(tagName);
}), APPEND_OPCODES.add(Op.PushRemoteElement, vm => {
let elementRef = vm.stack.pop(),
insertBeforeRef = vm.stack.pop(),
guidRef = vm.stack.pop(),
element = valueForRef(elementRef),
insertBefore = valueForRef(insertBeforeRef),
guid = valueForRef(guidRef);
isConstRef(elementRef) || vm.updateWith(new Assert(elementRef)), void 0 === insertBefore || isConstRef(insertBeforeRef) || vm.updateWith(new Assert(insertBeforeRef));
let block = vm.elements().pushRemoteElement(element, guid, insertBefore);
if (block && vm.associateDestroyable(block), void 0 !== vm.env.debugRenderTree) {
// Note that there is nothing to update – when the args for an
// {{#in-element}} changes it gets torn down and a new one is
// re-created/rendered in its place (see the `Assert`s above)
let args = createCapturedArgs(void 0 === insertBefore ? {} : {
insertBefore: insertBeforeRef
}, [elementRef]);
vm.env.debugRenderTree.create(block, {
type: "keyword",
name: "in-element",
args: args,
instance: null
}), registerDestructor$1(block, () => {
vm.env.debugRenderTree?.willDestroy(block);
});
}
}), APPEND_OPCODES.add(Op.PopRemoteElement, vm => {
let bounds = vm.elements().popRemoteElement();
void 0 !== vm.env.debugRenderTree &&
// The RemoteLiveBlock is also its bounds
vm.env.debugRenderTree.didRender(bounds, bounds);
}), APPEND_OPCODES.add(Op.FlushElement, vm => {
let operations = vm.fetchValue($t0),
modifiers = null;
operations && (modifiers = operations.flush(vm), vm.loadValue($t0, null)), vm.elements().flushElement(modifiers);
}), APPEND_OPCODES.add(Op.CloseElement, vm => {
let modifiers = vm.elements().closeElement();
null !== modifiers && modifiers.forEach(modifier => {
vm.env.scheduleInstallModifier(modifier);
const d = modifier.manager.getDestroyable(modifier.state);
null !== d && vm.associateDestroyable(d);
});
}), APPEND_OPCODES.add(Op.Modifier, (vm, {
op1: handle
}) => {
if (!1 === vm.env.isInteractive) return;
let owner = vm.getOwner(),
args = vm.stack.pop(),
definition = vm[CONSTANTS].getValue(handle),
{
manager: manager
} = definition,
{
constructing: constructing
} = vm.elements(),
capturedArgs = args.capture(),
state = manager.create(owner, expect(constructing, "BUG: ElementModifier could not find the element it applies to"), definition.state, capturedArgs),
instance = {
manager: manager,
state: state,
definition: definition
};
expect(vm.fetchValue($t0), "BUG: ElementModifier could not find operations to append to").addModifier(vm, instance, capturedArgs);
let tag = manager.getTag(state);
return null !== tag ? (consumeTag(tag), vm.updateWith(new UpdateModifierOpcode(tag, instance))) : void 0;
}), APPEND_OPCODES.add(Op.DynamicModifier, vm => {
if (!1 === vm.env.isInteractive) return;
let {
stack: stack
} = vm,
ref = stack.pop(),
args = stack.pop().capture(),
{
positional: outerPositional,
named: outerNamed
} = args,
{
constructing: constructing
} = vm.elements(),
initialOwner = vm.getOwner(),
instanceRef = createComputeRef(() => {
let owner,
hostDefinition,
value = valueForRef(ref);
if (!isObject(value)) return;
if (isCurriedType(value, CurriedTypes.Modifier)) {
let {
definition: resolvedDefinition,
owner: curriedOwner,
positional: positional,
named: named
} = resolveCurriedValue(value);
hostDefinition = resolvedDefinition, owner = curriedOwner, void 0 !== positional && (args.positional = positional.concat(outerPositional)), void 0 !== named && (args.named = Object.assign({}, ...named, outerNamed));
} else hostDefinition = value, owner = initialOwner;
let manager = getInternalModifierManager(hostDefinition, !0);
if (null === manager) throw new Error("BUG: modifier manager expected");
let definition = {
resolvedName: null,
manager: manager,
state: hostDefinition
},
state = manager.create(owner, expect(constructing, "BUG: ElementModifier could not find the element it applies to"), definition.state, args);
return {
manager: manager,
state: state,
definition: definition
};
}),
instance = valueForRef(instanceRef),
tag = null;
return void 0 !== instance && (expect(vm.fetchValue($t0), "BUG: ElementModifier could not find operations to append to").addModifier(vm, instance, args), tag = instance.manager.getTag(instance.state), null !== tag && consumeTag(tag)), !isConstRef(ref) || tag ? vm.updateWith(new UpdateDynamicModifierOpcode(tag, instance, instanceRef)) : void 0;
});
class UpdateModifierOpcode {
lastUpdated;
constructor(tag, modifier) {
this.tag = tag, this.modifier = modifier, this.lastUpdated = valueForTag(tag);
}
evaluate(vm) {
let {
modifier: modifier,
tag: tag,
lastUpdated: lastUpdated
} = this;
consumeTag(tag), validateTag(tag, lastUpdated) || (vm.env.scheduleUpdateModifier(modifier), this.lastUpdated = valueForTag(tag));
}
}
class UpdateDynamicModifierOpcode {
lastUpdated;
constructor(tag, instance, instanceRef) {
this.tag = tag, this.instance = instance, this.instanceRef = instanceRef, this.lastUpdated = valueForTag(tag ?? CURRENT_TAG);
}
evaluate(vm) {
let {
tag: tag,
lastUpdated: lastUpdated,
instance: instance,
instanceRef: instanceRef
} = this,
newInstance = valueForRef(instanceRef);
if (newInstance !== instance) {
if (void 0 !== instance) {
let destroyable = instance.manager.getDestroyable(instance.state);
null !== destroyable && destroy(destroyable);
}
if (void 0 !== newInstance) {
let {
manager: manager,
state: state
} = newInstance,
destroyable = manager.getDestroyable(state);
null !== destroyable && associateDestroyableChild(this, destroyable), tag = manager.getTag(state), null !== tag && (this.lastUpdated = valueForTag(tag)), this.tag = tag, vm.env.scheduleInstallModifier(newInstance);
}
this.instance = newInstance;
} else null === tag || validateTag(tag, lastUpdated) || (vm.env.scheduleUpdateModifier(instance), this.lastUpdated = valueForTag(tag));
null !== tag && consumeTag(tag);
}
}
APPEND_OPCODES.add(Op.StaticAttr, (vm, {
op1: _name,
op2: _value,
op3: _namespace
}) => {
let name = vm[CONSTANTS].getValue(_name),
value = vm[CONSTANTS].getValue(_value),
namespace = _namespace ? vm[CONSTANTS].getValue(_namespace) : null;
vm.elements().setStaticAttribute(name, value, namespace);
}), APPEND_OPCODES.add(Op.DynamicAttr, (vm, {
op1: _name,
op2: _trusting,
op3: _namespace
}) => {
let name = vm[CONSTANTS].getValue(_name),
trusting = vm[CONSTANTS].getValue(_trusting),
reference = vm.stack.pop(),
value = valueForRef(reference),
namespace = _namespace ? vm[CONSTANTS].getValue(_namespace) : null,
attribute = vm.elements().setDynamicAttribute(name, value, trusting, namespace);
isConstRef(reference) || vm.updateWith(new UpdateDynamicAttributeOpcode(reference, attribute, vm.env));
});
class UpdateDynamicAttributeOpcode {
updateRef;
constructor(reference, attribute, env) {
let initialized = !1;
this.updateRef = createComputeRef(() => {
let value = valueForRef(reference);
!0 === initialized ? attribute.update(value, env) : initialized = !0;
}), valueForRef(this.updateRef);
}
evaluate() {
valueForRef(this.updateRef);
}
}
/**
* The VM creates a new ComponentInstance data structure for every component
* invocation it encounters.
*
* Similar to how a ComponentDefinition contains state about all components of a
* particular type, a ComponentInstance contains state specific to a particular
* instance of a component type. It also contains a pointer back to its
* component type's ComponentDefinition.
*/
APPEND_OPCODES.add(Op.PushComponentDefinition, (vm, {
op1: handle
}) => {
let definition = vm[CONSTANTS].getValue(handle);
debugAssert(!!definition, `Missing component for ${handle}`);
let {
manager: manager,
capabilities: capabilities
} = definition,
instance = {
definition: definition,
manager: manager,
capabilities: capabilities,
state: null,
handle: null,
table: null,
lookup: null
};
vm.stack.push(instance);
}), APPEND_OPCODES.add(Op.ResolveDynamicComponent, (vm, {
op1: _isStrict
}) => {
let definition,
stack = vm.stack,
component = valueForRef(stack.pop()),
constants = vm[CONSTANTS],
owner = vm.getOwner();
constants.getValue(_isStrict);
if (vm.loadValue($t1, null), "string" == typeof component) {
let resolvedDefinition = function (resolver, constants, name, owner) {
let definition = resolver.lookupComponent(name, expect(owner, "BUG: expected owner when looking up component"));
return constants.resolvedComponent(definition, name);
}(vm.runtime.resolver, constants, component, owner);
definition = expect(resolvedDefinition, `Could not find a component named "${component}"`);
} else definition = isCurriedValue(component) ? component : constants.component(component, owner);
stack.push(definition);
}), APPEND_OPCODES.add(Op.ResolveCurriedComponent, vm => {
let definition,
stack = vm.stack,
ref = stack.pop(),
value = valueForRef(ref),
constants = vm[CONSTANTS];
if (isCurriedValue(value)) definition = value;else if (definition = constants.component(value, vm.getOwner(), !0), false /* DEBUG */ ) ;
stack.push(definition);
}), APPEND_OPCODES.add(Op.PushDynamicComponentInstance, vm => {
let capabilities,
manager,
{
stack: stack
} = vm,
definition = stack.pop();
isCurriedValue(definition) ? manager = capabilities = null : (manager = definition.manager, capabilities = definition.capabilities), stack.push({
definition: definition,
capabilities: capabilities,
manager: manager,
state: null,
handle: null,
table: null
});
}), APPEND_OPCODES.add(Op.PushArgs, (vm, {
op1: _names,
op2: _blockNames,
op3: flags
}) => {
let stack = vm.stack,
names = vm[CONSTANTS].getArray(_names),
positionalCount = flags >> 4,
atNames = 8 & flags,
blockNames = 7 & flags ? vm[CONSTANTS].getArray(_blockNames) : EMPTY_STRING_ARRAY;
vm[ARGS$1].setup(stack, names, blockNames, positionalCount, !!atNames), stack.push(vm[ARGS$1]);
}), APPEND_OPCODES.add(Op.PushEmptyArgs, vm => {
let {
stack: stack
} = vm;
stack.push(vm[ARGS$1].empty(stack));
}), APPEND_OPCODES.add(Op.CaptureArgs, vm => {
let stack = vm.stack,
capturedArgs = stack.pop().capture();
stack.push(capturedArgs);
}), APPEND_OPCODES.add(Op.PrepareArgs, (vm, {
op1: _state
}) => {
let stack = vm.stack,
instance = vm.fetchValue(_state),
args = stack.pop(),
{
definition: definition
} = instance;
if (isCurriedType(definition, CurriedTypes.Component)) {
debugAssert(!definition.manager, "If the component definition was curried, we don't yet have a manager");
let constants = vm[CONSTANTS],
{
definition: resolvedDefinition,
owner: owner,
resolved: resolved,
positional: positional,
named: named
} = resolveCurriedValue(definition);
if (!0 === resolved) definition = resolvedDefinition;else if ("string" == typeof resolvedDefinition) {
let resolvedValue = vm.runtime.resolver.lookupComponent(resolvedDefinition, owner);
definition = constants.resolvedComponent(expect(resolvedValue, "BUG: expected resolved component"), resolvedDefinition);
} else definition = constants.component(resolvedDefinition, owner);
void 0 !== named && args.named.merge(assign({}, ...named)), void 0 !== positional && (args.realloc(positional.length), args.positional.prepend(positional));
let {
manager: manager
} = definition;
debugAssert(null === instance.manager, "component instance manager should not be populated yet"), debugAssert(null === instance.capabilities, "component instance manager should not be populated yet"), 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($t1, owner);
}
let {
manager: manager,
state: state
} = definition,
capabilities = instance.capabilities;
if (!managerHasCapability(manager, capabilities, InternalComponentCapabilities.prepareArgs)) return void stack.push(args);
let blocks = args.blocks.values,
blockNames = args.blocks.names,
preparedArgs = manager.prepareArgs(state, args);
if (preparedArgs) {
args.clear();
for (let i = 0; i < blocks.length; i++) stack.push(blocks[i]);
let {
positional: positional,
named: named
} = preparedArgs,
positionalCount = positional.length;
for (let i = 0; i < positionalCount; i++) stack.push(positional[i]);
let names = Object.keys(named);
for (let i = 0; i < names.length; i++) stack.push(named[unwrap$1(names[i])]);
args.setup(stack, names, blockNames, positionalCount, !1);
}
stack.push(args);
}), APPEND_OPCODES.add(Op.CreateComponent, (vm, {
op1: flags,
op2: _state
}) => {
let instance = vm.fetchValue(_state),
{
definition: definition,
manager: manager,
capabilities: capabilities
} = instance;
if (!managerHasCapability(manager, capabilities, InternalComponentCapabilities.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;
let dynamicScope = null;
managerHasCapability(manager, capabilities, InternalComponentCapabilities.dynamicScope) && (dynamicScope = vm.dynamicScope());
let hasDefaultBlock = 1 & flags,
args = null;
managerHasCapability(manager, capabilities, InternalComponentCapabilities.createArgs) && (args = vm.stack.peek());
let self = null;
managerHasCapability(manager, capabilities, InternalComponentCapabilities.createCaller) && (self = vm.getSelf());
let 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, managerHasCapability(manager, capabilities, InternalComponentCapabilities.updateHook) && vm.updateWith(new UpdateComponentOpcode(state, manager, dynamicScope));
}), APPEND_OPCODES.add(Op.RegisterComponentDestructor, (vm, {
op1: _state
}) => {
let {
manager: manager,
state: state,
capabilities: capabilities
} = vm.fetchValue(_state),
d = manager.getDestroyable(state);
d && vm.associateDestroyable(d);
}), APPEND_OPCODES.add(Op.BeginComponentTransaction, (vm, {
op1: _state
}) => {
let name;
vm.beginCacheGroup(name), vm.elements().pushSimpleBlock();
}), APPEND_OPCODES.add(Op.PutComponentOperations, vm => {
vm.loadValue($t0, new ComponentElementOperations());
}), APPEND_OPCODES.add(Op.ComponentAttr, (vm, {
op1: _name,
op2: _trusting,
op3: _namespace
}) => {
let name = vm[CONSTANTS].getValue(_name),
trusting = vm[CONSTANTS].getValue(_trusting),
reference = vm.stack.pop(),
namespace = _namespace ? vm[CONSTANTS].getValue(_namespace) : null;
vm.fetchValue($t0).setAttribute(name, reference, trusting, namespace);
}), APPEND_OPCODES.add(Op.StaticComponentAttr, (vm, {
op1: _name,
op2: _value,
op3: _namespace
}) => {
let name = vm[CONSTANTS].getValue(_name),
value = vm[CONSTANTS].getValue(_value),
namespace = _namespace ? vm[CONSTANTS].getValue(_namespace) : null;
vm.fetchValue($t0).setStaticAttribute(name, value, namespace);
});
class ComponentElementOperations {
attributes = dict();
classes = [];
modifiers = [];
setAttribute(name, value, trusting, namespace) {
let deferred = {
value: value,
namespace: namespace,
trusting: trusting
};
"class" === name && this.classes.push(value), this.attributes[name] = deferred;
}
setStaticAttribute(name, value, namespace) {
let deferred = {
value: value,
namespace: namespace
};
"class" === name && this.classes.push(value), this.attributes[name] = deferred;
}
addModifier(vm, modifier, capturedArgs) {
if (this.modifiers.push(modifier), void 0 !== vm.env.debugRenderTree) {
const {
manager: manager,
definition: definition,
state: state
} = modifier;
// TODO: we need a stable object for the debugRenderTree as the key, add support for
// the case where the state is a primitive, or if in practice we always have/require
// an object, then change the internal types to reflect that
if (null === state || "object" != typeof state && "function" != typeof state) return;
let {
element: element,
constructing: constructing
} = vm.elements(),
name = manager.getDebugName(definition.state),
instance = manager.getDebugInstance(state);
debugAssert(constructing, "Expected a constructing element in addModifier");
let bounds = new ConcreteBounds(element, constructing, constructing);
vm.env.debugRenderTree.create(state, {
type: "modifier",
name: name,
args: capturedArgs,
instance: instance
}), vm.env.debugRenderTree.didRender(state, bounds),
// For tearing down the debugRenderTree
vm.associateDestroyable(state), vm.updateWith(new DebugRenderTreeUpdateOpcode(state)), vm.updateWith(new DebugRenderTreeDidRenderOpcode(state, bounds)), registerDestructor$1(state, () => {
vm.env.debugRenderTree?.willDestroy(state);
});
}
}
flush(vm) {
let type,
attributes = this.attributes;
for (let name in this.attributes) {
if ("type" === name) {
type = attributes[name];
continue;
}
let attr = unwrap$1(this.attributes[name]);
"class" === name ? setDeferredAttr(vm, "class", mergeClasses(this.classes), attr.namespace, attr.trusting) : setDeferredAttr(vm, name, attr.value, attr.namespace, attr.trusting);
}
return void 0 !== type && setDeferredAttr(vm, "type", type.value, type.namespace, type.trusting), this.modifiers;
}
}
function mergeClasses(classes) {
return 0 === classes.length ? "" : 1 === classes.length ? unwrap$1(classes[0]) : function (classes) {
return classes.every(c => "string" == typeof c);
}(classes) ? classes.join(" ") : (list = classes, createComputeRef(() => {
let ret = [];
for (const ref of list) {
let value = normalizeStringValue("string" == typeof ref ? ref : valueForRef(ref));
value && ret.push(value);
}
return 0 === ret.length ? null : ret.join(" ");
}));
var list;
}
function setDeferredAttr(vm, name, value, namespace, trusting = !1) {
if ("string" == typeof value) vm.elements().setStaticAttribute(name, value, namespace);else {
let attribute = vm.elements().setDynamicAttribute(name, valueForRef(value), trusting, namespace);
isConstRef(value) || vm.updateWith(new UpdateDynamicAttributeOpcode(value, attribute, vm.env));
}
}
function bindBlock(symbolName, blockName, state, blocks, vm) {
let symbol = state.table.symbols.indexOf(symbolName),
block = blocks.get(blockName);
-1 !== symbol && vm.scope().bindBlock(symbol + 1, block), state.lookup && (state.lookup[symbolName] = block);
}
APPEND_OPCODES.add(Op.DidCreateElement, (vm, {
op1: _state
}) => {
let {
definition: definition,
state: state
} = vm.fetchValue(_state),
{
manager: manager
} = definition,
operations = vm.fetchValue($t0);
manager.didCreateElement(state, expect(vm.elements().constructing, "Expected a constructing element in DidCreateOpcode"), operations);
}), APPEND_OPCODES.add(Op.GetComponentSelf, (vm, {
op1: _state,
op2: _names
}) => {
let instance = vm.fetchValue(_state),
{
definition: definition,
state: state
} = instance,
{
manager: manager
} = definition,
selfRef = manager.getSelf(state);
if (void 0 !== vm.env.debugRenderTree) {
let args,
moduleName,
instance = vm.fetchValue(_state),
{
definition: definition,
manager: manager
} = instance;
if (vm.stack.peek() === vm[ARGS$1]) args = vm[ARGS$1].capture();else {
let names = vm[CONSTANTS].getArray(_names);
vm[ARGS$1].setup(vm.stack, names, [], 0, !0), args = vm[ARGS$1].capture();
}
let compilable = definition.compilable;
if (null === compilable ? (debugAssert(managerHasCapability(manager, instance.capabilities, InternalComponentCapabilities.dynamicLayout), "BUG: No template was found for this component, and the component did not have the dynamic layout capability"), compilable = manager.getDynamicLayout(state, vm.runtime.resolver), moduleName = null !== compilable ? compilable.moduleName : "__default__.hbs") : moduleName = compilable.moduleName,
// For tearing down the debugRenderTree
vm.associateDestroyable(instance), hasCustomDebugRenderTreeLifecycle(manager)) manager.getDebugCustomRenderTree(instance.definition.state, instance.state, args, moduleName).forEach(node => {
let {
bucket: bucket
} = node;
vm.env.debugRenderTree.create(bucket, node), registerDestructor$1(instance, () => {
vm.env.debugRenderTree?.willDestroy(bucket);
}), vm.updateWith(new DebugRenderTreeUpdateOpcode(bucket));
});else {
let name = definition.resolvedName ?? manager.getDebugName(definition.state);
vm.env.debugRenderTree.create(instance, {
type: "component",
name: name,
args: args,
template: moduleName,
instance: valueForRef(selfRef)
}), registerDestructor$1(instance, () => {
vm.env.debugRenderTree?.willDestroy(instance);
}), vm.updateWith(new DebugRenderTreeUpdateOpcode(instance));
}
}
vm.stack.push(selfRef);
}), APPEND_OPCODES.add(Op.GetComponentTagName, (vm, {
op1: _state
}) => {
let {
definition: definition,
state: state
} = vm.fetchValue(_state),
{
manager: manager
} = definition,
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(Op.GetComponentLayout, (vm, {
op1: _state
}) => {
let instance = vm.fetchValue(_state),
{
manager: manager,
definition: definition
} = instance,
{
stack: stack
} = vm,
{
compilable: compilable
} = definition;
if (null === compilable) {
let {
capabilities: capabilities
} = instance;
debugAssert(managerHasCapability(manager, capabilities, InternalComponentCapabilities.dynamicLayout), "BUG: No template was found for this component, and the component did not have the dynamic layout capability"), compilable = manager.getDynamicLayout(instance.state, vm.runtime.resolver), null === compilable && (compilable = managerHasCapability(manager, capabilities, InternalComponentCapabilities.wrapped) ? unwrapTemplate(vm[CONSTANTS].defaultTemplate).asWrappedLayout() : unwrapTemplate(vm[CONSTANTS].defaultTemplate).asLayout());
}
let handle = compilable.compile(vm.context);
stack.push(compilable.symbolTable), stack.push(handle);
}), APPEND_OPCODES.add(Op.Main, (vm, {
op1: register
}) => {
let definition = vm.stack.pop(),
invocation = vm.stack.pop(),
{
manager: manager,
capabilities: capabilities
} = definition,
state = {
definition: definition,
manager: manager,
capabilities: capabilities,
state: null,
handle: invocation.handle,
table: invocation.symbolTable,
lookup: null
};
vm.loadValue(register, state);
}), APPEND_OPCODES.add(Op.PopulateLayout, (vm, {
op1: _state
}) => {
let {
stack: stack
} = vm,
handle = stack.pop(),
table = stack.pop(),
state = vm.fetchValue(_state);
// In DEBUG handles could be ErrHandle objects
state.handle = handle, state.table = table;
}), APPEND_OPCODES.add(Op.VirtualRootScope, (vm, {
op1: _state
}) => {
let owner,
{
table: table,
manager: manager,
capabilities: capabilities,
state: state
} = vm.fetchValue(_state);
managerHasCapability(manager, capabilities, InternalComponentCapabilities.hasSubOwner) ? (owner = manager.getOwner(state), vm.loadValue($t1, null)) : (
// Check the temp register to see if an owner was resolved from currying
owner = vm.fetchValue($t1), null === owner ?
// 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 the owner was found, so clear the temp register. This will happen
// if we are loading a curried component, e.g. <@someCurriedComponent/>
vm.loadValue($t1, null)), vm.pushRootScope(table.symbols.length + 1, owner);
}), APPEND_OPCODES.add(Op.SetupForEval, (vm, {
op1: _state
}) => {
let state = vm.fetchValue(_state);
if (state.table.hasEval) {
let lookup = state.lookup = dict();
vm.scope().bindEvalScope(lookup);
}
}), APPEND_OPCODES.add(Op.SetNamedVariables, (vm, {
op1: _state
}) => {
let state = vm.fetchValue(_state),
scope = vm.scope(),
args = vm.stack.peek(),
callerNames = args.named.atNames;
for (let i = callerNames.length - 1; i >= 0; i--) {
let atName = unwrap$1(callerNames[i]),
symbol = state.table.symbols.indexOf(atName),
value = args.named.get(atName, !0);
-1 !== symbol && scope.bindSymbol(symbol + 1, value), state.lookup && (state.lookup[atName] = value);
}
}), APPEND_OPCODES.add(Op.SetBlocks, (vm, {
op1: _state
}) => {
let state = vm.fetchValue(_state),
{
blocks: blocks
} = vm.stack.peek();
for (const [i] of enumerate(blocks.names)) bindBlock(unwrap$1(blocks.symbolNames[i]), unwrap$1(blocks.names[i]), state, blocks, vm);
}),
// Dynamic Invocation Only
APPEND_OPCODES.add(Op.InvokeComponentLayout, (vm, {
op1: _state
}) => {
let state = vm.fetchValue(_state);
vm.call(state.handle);
}), APPEND_OPCODES.add(Op.DidRenderLayout, (vm, {
op1: _state
}) => {
let instance = vm.fetchValue(_state),
{
manager: manager,
state: state,
capabilities: capabilities
} = instance,
bounds = vm.elements().popBlock();
void 0 !== vm.env.debugRenderTree && (hasCustomDebugRenderTreeLifecycle(manager) ? manager.getDebugCustomRenderTree(instance.definition.state, state, EMPTY_ARGS).reverse().forEach(node => {
let {
bucket: bucket
} = node;
vm.env.debugRenderTree.didRender(bucket, bounds), vm.updateWith(new DebugRenderTreeDidRenderOpcode(bucket, bounds));
}) : (vm.env.debugRenderTree.didRender(instance, bounds), vm.updateWith(new DebugRenderTreeDidRenderOpcode(instance, bounds)))), managerHasCapability(manager, capabilities, InternalComponentCapabilities.createInstance) && (manager.didRenderLayout(state, bounds), vm.env.didCreate(instance), vm.updateWith(new DidUpdateLayoutOpcode(instance, bounds)));
}), APPEND_OPCODES.add(Op.CommitComponentTransaction, vm => {
vm.commitCacheGroup();
});
class UpdateComponentOpcode {
constructor(component, manager, dynamicScope) {
this.component = component, this.manager = manager, this.dynamicScope = dynamicScope;
}
evaluate(_vm) {
let {
component: component,
manager: manager,
dynamicScope: dynamicScope
} = this;
manager.update(component, dynamicScope);
}
}
class DidUpdateLayoutOpcode {
constructor(component, bounds) {
this.component = component, this.bounds = bounds;
}
evaluate(vm) {
let {
component: component,
bounds: bounds
} = this,
{
manager: manager,
state: state
} = component;
manager.didUpdateLayout(state, bounds), vm.env.didUpdate(component);
}
}
class DebugRenderTreeUpdateOpcode {
constructor(bucket) {
this.bucket = bucket;
}
evaluate(vm) {
vm.env.debugRenderTree?.update(this.bucket);
}
}
class DebugRenderTreeDidRenderOpcode {
constructor(bucket, bounds) {
this.bucket = bucket, this.bounds = bounds;
}
evaluate(vm) {
vm.env.debugRenderTree?.didRender(this.bucket, this.bounds);
}
}
/*
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 {
stack = null;
positional = new PositionalArgumentsImpl();
named = new NamedArgumentsImpl();
blocks = new BlockArgumentsImpl();
empty(stack) {
let base = stack[REGISTERS][$sp] + 1;
return this.named.empty(stack, base), this.positional.empty(stack, base), this.blocks.empty(stack, base), 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
*/
let named = this.named,
namedCount = names.length,
namedBase = stack[REGISTERS][$sp] - namedCount + 1;
named.setup(stack, namedBase, namedCount, names, atNames);
let positionalBase = namedBase - positionalCount;
this.positional.setup(stack, positionalBase, positionalCount);
let blocks = this.blocks,
blocksCount = blockNames.length,
blocksBase = positionalBase - 3 * blocksCount;
blocks.setup(stack, blocksBase, blocksCount, blockNames);
}
get base() {
return this.blocks.base;
}
get length() {
return this.positional.length + this.named.length + 3 * this.blocks.length;
}
at(pos) {
return this.positional.at(pos);
}
realloc(offset) {
let {
stack: stack
} = this;
if (offset > 0 && null !== stack) {
let {
positional: positional,
named: named
} = this,
newBase = positional.base + offset;
for (let i = positional.length + named.length - 1; i >= 0; i--) stack.copy(i + positional.base, i + newBase);
positional.base += offset, named.base += offset, stack[REGISTERS][$sp] += offset;
}
}
capture() {
let positional = 0 === this.positional.length ? EMPTY_POSITIONAL : this.positional.capture();
return {
named: 0 === this.named.length ? EMPTY_NAMED : this.named.capture(),
positional: positional
};
}
clear() {
let {
stack: stack,
length: length
} = this;
length > 0 && null !== stack && stack.pop(length);
}
}
const EMPTY_REFERENCES = emptyArray();
class PositionalArgumentsImpl {
base = 0;
length = 0;
stack = null;
_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, this._references = 0 === length ? EMPTY_REFERENCES : null;
}
at(position) {
let {
base: base,
length: length,
stack: stack
} = this;
return position < 0 || position >= length ? UNDEFINED_REFERENCE : stack.get(position, base);
}
capture() {
return this.references;
}
prepend(other) {
let additions = other.length;
if (additions > 0) {
let {
base: base,
length: length,
stack: stack
} = this;
this.base = base -= additions, this.length = length + additions;
for (let i = 0; i < additions; i++) stack.set(other[i], i, base);
this._references = null;
}
}
get references() {
let references = this._references;
if (!references) {
let {
stack: stack,
base: base,
length: length
} = this;
references = this._references = stack.slice(base, base + length);
}
return references;
}
}
class NamedArgumentsImpl {
base = 0;
length = 0;
_references = null;
_names = EMPTY_STRING_ARRAY;
_atNames = EMPTY_STRING_ARRAY;
empty(stack, base) {
this.stack = stack, this.base = base, this.length = 0, this._references = EMPTY_REFERENCES, this._names = EMPTY_STRING_ARRAY, this._atNames = EMPTY_STRING_ARRAY;
}
setup(stack, base, length, names, atNames) {
this.stack = stack, this.base = base, this.length = length, 0 === length ? (this._references = EMPTY_REFERENCES, this._names = EMPTY_STRING_ARRAY, this._atNames = EMPTY_STRING_ARRAY) : (this._references = null, atNames ? (this._names = null, this._atNames = names) : (this._names = names, this._atNames = null));
}
get names() {
let names = this._names;
return names || (names = this._names = this._atNames.map(this.toSyntheticName)), names;
}
get atNames() {
let atNames = this._atNames;
return atNames || (atNames = this._atNames = this._names.map(this.toAtName)), atNames;
}
has(name) {
return -1 !== this.names.indexOf(name);
}
get(name, atNames = !1) {
let {
base: base,
stack: stack
} = this,
idx = (atNames ? this.atNames : this.names).indexOf(name);
if (-1 === idx) return UNDEFINED_REFERENCE;
let ref = stack.get(idx, base);
return ref;
}
capture() {
let {
names: names,
references: references
} = this,
map = dict();
for (const [i, name] of enumerate(names)) map[name] = unwrap$1(references[i]);
return map;
}
merge(other) {
let keys = Object.keys(other);
if (keys.length > 0) {
let {
names: names,
length: length,
stack: stack
} = this,
newNames = names.slice();
for (const name of keys) -1 === newNames.indexOf(name) && (length = newNames.push(name), stack.push(other[name]));
this.length = length, this._references = null, this._names = newNames, this._atNames = null;
}
}
get references() {
let references = this._references;
if (!references) {
let {
base: base,
length: length,
stack: 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}`;
}
const EMPTY_BLOCK_VALUES = emptyArray();
class BlockArgumentsImpl {
internalValues = null;
_symbolNames = null;
internalTag = null;
names = EMPTY_STRING_ARRAY;
length = 0;
base = 0;
empty(stack, base) {
this.stack = stack, this.names = EMPTY_STRING_ARRAY, this.base = base, this.length = 0, this._symbolNames = null, this.internalTag = 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, 0 === length ? (this.internalTag = CONSTANT_TAG, this.internalValues = EMPTY_BLOCK_VALUES) : (this.internalTag = null, this.internalValues = null);
}
get values() {
let values = this.internalValues;
if (!values) {
let {
base: base,
length: length,
stack: stack
} = this;
values = this.internalValues = stack.slice(base, base + 3 * length);
}
return values;
}
has(name) {
return -1 !== this.names.indexOf(name);
}
get(name) {
let idx = this.names.indexOf(name);
if (-1 === idx) return null;
let {
base: base,
stack: stack
} = this,
table = stack.get(3 * idx, base),
scope = stack.get(3 * idx + 1, base),
handle = stack.get(3 * idx + 2, base);
return null === handle ? null : [handle, scope, table];
}
capture() {
return new CapturedBlockArgumentsImpl(this.names, this.values);
}
get symbolNames() {
let symbolNames = this._symbolNames;
return null === symbolNames && (symbolNames = this._symbolNames = this.names.map(toSymbolName)), symbolNames;
}
}
class CapturedBlockArgumentsImpl {
length;
constructor(names, values) {
this.names = names, this.values = values, this.length = names.length;
}
has(name) {
return -1 !== this.names.indexOf(name);
}
get(name) {
let idx = this.names.indexOf(name);
return -1 === idx ? null : [this.values[3 * idx + 2], this.values[3 * idx + 1], this.values[3 * idx]];
}
}
function createCapturedArgs(named, positional) {
return {
named: named,
positional: positional
};
}
function reifyNamed(named) {
let reified = dict();
for (const [key, value] of Object.entries(named)) reified[key] = valueForRef(value);
return reified;
}
function reifyPositional(positional) {
return positional.map(valueForRef);
}
function reifyArgs(args) {
return {
named: reifyNamed(args.named),
positional: reifyPositional(args.positional)
};
}
const ARGUMENT_ERROR = Symbol("ARGUMENT_ERROR");
function isArgumentError(arg) {
return null !== arg && "object" == typeof arg && arg[ARGUMENT_ERROR];
}
function ArgumentErrorImpl(error) {
return {
[ARGUMENT_ERROR]: !0,
error: error
};
}
function reifyArgsDebug(args) {
return {
named: function (named) {
let reified = dict();
for (const [key, value] of Object.entries(named)) try {
reified[key] = valueForRef(value);
} catch (e) {
reified[key] = ArgumentErrorImpl(e);
}
return reified;
}(args.named),
positional: (positional = args.positional, positional.map(p => {
try {
return valueForRef(p);
} catch (e) {
return ArgumentErrorImpl(e);
}
}))
};
var positional;
}
const EMPTY_NAMED = Object.freeze(Object.create(null)),
EMPTY_POSITIONAL = EMPTY_REFERENCES,
EMPTY_ARGS = createCapturedArgs(EMPTY_NAMED, EMPTY_POSITIONAL);
function castToString(value) {
return "string" == typeof value ? value : "function" != typeof value.toString ? "" : String(value);
}
function resolveHelper(definition, ref) {
let helper,
managerOrHelper = getInternalHelperManager(definition, !0);
if (null === managerOrHelper ? helper = null : (helper = "function" == typeof managerOrHelper ? managerOrHelper : managerOrHelper.getHelper(definition), debugAssert(managerOrHelper, "BUG: expected manager or helper")), false /* DEBUG */ ) ;
return helper;
}
function isUndefinedReference(input) {
return debugAssert(Array.isArray(input) || input === UNDEFINED_REFERENCE, "a reference other than UNDEFINED_REFERENCE is illegal here"), input === UNDEFINED_REFERENCE;
}
APPEND_OPCODES.add(Op.Curry, (vm, {
op1: type,
op2: _isStrict
}) => {
let stack = vm.stack,
definition = stack.pop(),
capturedArgs = stack.pop(),
owner = vm.getOwner();
vm.runtime.resolver;
vm.loadValue($v0, function (type, inner, owner, args, resolver, isStrict) {
let lastValue, curriedDefinition;
return createComputeRef(() => {
let value = valueForRef(inner);
if (value === lastValue) return curriedDefinition;
if (isCurriedType(value, type)) curriedDefinition = args ? curry(type, value, owner, args) : args;else if (type === CurriedTypes.Component && "string" == typeof value && value) {
curriedDefinition = curry(type, value, owner, args);
} else curriedDefinition = isObject(value) ? curry(type, value, owner, args) : null;
return lastValue = value, curriedDefinition;
});
}(type, definition, owner, capturedArgs));
}), APPEND_OPCODES.add(Op.DynamicHelper, vm => {
let helperRef,
stack = vm.stack,
ref = stack.pop(),
args = stack.pop().capture(),
initialOwner = vm.getOwner(),
helperInstanceRef = createComputeRef(() => {
void 0 !== helperRef && destroy(helperRef);
let definition = valueForRef(ref);
if (isCurriedType(definition, CurriedTypes.Helper)) {
let {
definition: resolvedDef,
owner: owner,
positional: positional,
named: named
} = resolveCurriedValue(definition),
helper = resolveHelper(resolvedDef);
void 0 !== named && (args.named = assign({}, ...named, args.named)), void 0 !== positional && (args.positional = positional.concat(args.positional)), helperRef = helper(args, owner), associateDestroyableChild(helperInstanceRef, helperRef);
} else if (isObject(definition)) {
let helper = resolveHelper(definition);
helperRef = helper(args, initialOwner), _hasDestroyableChildren(helperRef) && associateDestroyableChild(helperInstanceRef, helperRef);
} else helperRef = UNDEFINED_REFERENCE;
}),
helperValueRef = createComputeRef(() => (valueForRef(helperInstanceRef), valueForRef(helperRef)));
vm.associateDestroyable(helperInstanceRef), vm.loadValue($v0, helperValueRef);
}), APPEND_OPCODES.add(Op.Helper, (vm, {
op1: handle
}) => {
let stack = vm.stack,
value = vm[CONSTANTS].getValue(handle)(stack.pop().capture(), vm.getOwner(), vm.dynamicScope());
_hasDestroyableChildren(value) && vm.associateDestroyable(value), vm.loadValue($v0, value);
}), APPEND_OPCODES.add(Op.GetVariable, (vm, {
op1: symbol
}) => {
let expr = vm.referenceForSymbol(symbol);
vm.stack.push(expr);
}), APPEND_OPCODES.add(Op.SetVariable, (vm, {
op1: symbol
}) => {
let expr = vm.stack.pop();
vm.scope().bindSymbol(symbol, expr);
}), APPEND_OPCODES.add(Op.SetBlock, (vm, {
op1: symbol
}) => {
let handle = vm.stack.pop(),
scope = vm.stack.pop(),
table = vm.stack.pop();
vm.scope().bindBlock(symbol, [handle, scope, table]);
}), APPEND_OPCODES.add(Op.ResolveMaybeLocal, (vm, {
op1: _name
}) => {
let name = vm[CONSTANTS].getValue(_name),
ref = vm.scope().getPartialMap()[name];
void 0 === ref && (ref = childRefFor(vm.getSelf(), name)), vm.stack.push(ref);
}), APPEND_OPCODES.add(Op.RootScope, (vm, {
op1: symbols
}) => {
vm.pushRootScope(symbols, vm.getOwner());
}), APPEND_OPCODES.add(Op.GetProperty, (vm, {
op1: _key
}) => {
let key = vm[CONSTANTS].getValue(_key),
expr = vm.stack.pop();
vm.stack.push(childRefFor(expr, key));
}), APPEND_OPCODES.add(Op.GetBlock, (vm, {
op1: _block
}) => {
let {
stack: stack
} = vm,
block = vm.scope().getBlock(_block);
stack.push(block);
}), APPEND_OPCODES.add(Op.SpreadBlock, vm => {
let {
stack: stack
} = vm,
block = stack.pop();
if (block && !isUndefinedReference(block)) {
let [handleOrCompilable, scope, table] = block;
stack.push(table), stack.push(scope), stack.push(handleOrCompilable);
} else stack.push(null), stack.push(null), stack.push(null);
}), APPEND_OPCODES.add(Op.HasBlock, vm => {
let {
stack: stack
} = vm,
block = stack.pop();
block && !isUndefinedReference(block) ? stack.push(TRUE_REFERENCE) : stack.push(FALSE_REFERENCE);
}), APPEND_OPCODES.add(Op.HasBlockParams, vm => {
// FIXME(mmun): should only need to push the symbol table
vm.stack.pop(), vm.stack.pop();
let table = vm.stack.pop(),
hasBlockParams = table && table.parameters.length;
vm.stack.push(hasBlockParams ? TRUE_REFERENCE : FALSE_REFERENCE);
}), APPEND_OPCODES.add(Op.Concat, (vm, {
op1: count
}) => {
let out = new Array(count);
for (let i = count; i > 0; i--) out[i - 1] = vm.stack.pop();
var partsRefs;
vm.stack.push((partsRefs = out, createComputeRef(() => {
const parts = [];
for (const ref of partsRefs) {
const value = valueForRef(ref);
null != value && parts.push(castToString(value));
}
return parts.length > 0 ? parts.join("") : null;
})));
}), APPEND_OPCODES.add(Op.IfInline, vm => {
let condition = vm.stack.pop(),
truthy = vm.stack.pop(),
falsy = vm.stack.pop();
vm.stack.push(createComputeRef(() => !0 === toBool$1(valueForRef(condition)) ? valueForRef(truthy) : valueForRef(falsy)));
}), APPEND_OPCODES.add(Op.Not, vm => {
let ref = vm.stack.pop();
vm.stack.push(createComputeRef(() => !toBool$1(valueForRef(ref))));
}), APPEND_OPCODES.add(Op.GetDynamicVar, vm => {
let scope = vm.dynamicScope(),
stack = vm.stack,
nameRef = stack.pop();
stack.push(createComputeRef(() => {
let name = String(valueForRef(nameRef));
return valueForRef(scope.get(name));
}));
}), APPEND_OPCODES.add(Op.Log, vm => {
let {
positional: positional
} = vm.stack.pop().capture();
vm.loadValue($v0, createComputeRef(() => {
// eslint-disable-next-line no-console
console.log(...reifyPositional(positional));
}));
});
class DynamicTextContent {
constructor(node, reference, lastValue) {
this.node = node, this.reference = reference, this.lastValue = lastValue;
}
evaluate() {
let normalized,
value = valueForRef(this.reference),
{
lastValue: lastValue
} = this;
value !== lastValue && (normalized = isEmpty$2(value) ? "" : isString(value) ? value : String(value), normalized !== lastValue) && (this.node.nodeValue = this.lastValue = normalized);
}
}
function toContentType(value) {
return function (value) {
return isString(value) || isEmpty$2(value) || "boolean" == typeof value || "number" == typeof value;
}(value) ? ContentType.String : isCurriedType(value, CurriedTypes.Component) || hasInternalComponentManager(value) ? ContentType.Component : isCurriedType(value, CurriedTypes.Helper) || hasInternalHelperManager(value) ? ContentType.Helper : isSafeString(value) ? ContentType.SafeString : function (value) {
return isNode(value) && 11 === value.nodeType;
}(value) ? ContentType.Fragment : isNode(value) ? ContentType.Node : ContentType.String;
}
function toDynamicContentType(value) {
if (!isObject(value)) return ContentType.String;
if (isCurriedType(value, CurriedTypes.Component) || hasInternalComponentManager(value)) return ContentType.Component;
return ContentType.Helper;
}
function debugCallback(context, get) {
// eslint-disable-next-line no-console
console.info("Use `context`, and `get(<path>)` to debug this template."), get("this");
}
APPEND_OPCODES.add(Op.ContentType, vm => {
let reference = vm.stack.peek();
vm.stack.push(toContentType(valueForRef(reference))), isConstRef(reference) || vm.updateWith(new AssertFilter(reference, toContentType));
}), APPEND_OPCODES.add(Op.DynamicContentType, vm => {
let reference = vm.stack.peek();
vm.stack.push(toDynamicContentType(valueForRef(reference))), isConstRef(reference) || vm.updateWith(new AssertFilter(reference, toDynamicContentType));
}), APPEND_OPCODES.add(Op.AppendHTML, vm => {
let reference = vm.stack.pop(),
rawValue = valueForRef(reference),
value = isEmpty$2(rawValue) ? "" : String(rawValue);
vm.elements().appendDynamicHTML(value);
}), APPEND_OPCODES.add(Op.AppendSafeHTML, vm => {
let reference = vm.stack.pop(),
rawValue = valueForRef(reference).toHTML(),
value = isEmpty$2(rawValue) ? "" : rawValue;
vm.elements().appendDynamicHTML(value);
}), APPEND_OPCODES.add(Op.AppendText, vm => {
let reference = vm.stack.pop(),
rawValue = valueForRef(reference),
value = isEmpty$2(rawValue) ? "" : String(rawValue),
node = vm.elements().appendDynamicText(value);
isConstRef(reference) || vm.updateWith(new DynamicTextContent(node, reference, value));
}), APPEND_OPCODES.add(Op.AppendDocumentFragment, vm => {
let reference = vm.stack.pop(),
value = valueForRef(reference);
vm.elements().appendDynamicFragment(value);
}), APPEND_OPCODES.add(Op.AppendNode, vm => {
let reference = vm.stack.pop(),
value = valueForRef(reference);
vm.elements().appendDynamicNode(value);
});
let callback = debugCallback;
// For testing purposes
function setDebuggerCallback(cb) {
callback = cb;
}
function resetDebuggerCallback() {
callback = debugCallback;
}
class ScopeInspector {
locals = dict();
constructor(scope, symbols, debugInfo) {
this.scope = scope;
for (const slot of debugInfo) {
let name = unwrap$1(symbols[slot - 1]),
ref = scope.getSymbol(slot);
this.locals[name] = ref;
}
}
get(path) {
let ref,
{
scope: scope,
locals: locals
} = this,
parts = path.split("."),
[head, ...tail] = path.split("."),
evalScope = scope.getEvalScope();
return "this" === head ? ref = scope.getSelf() : locals[head] ? ref = unwrap$1(locals[head]) : 0 === head.indexOf("@") && evalScope[head] ? ref = evalScope[head] : (ref = this.scope.getSelf(), tail = parts), tail.reduce((r, part) => childRefFor(r, part), ref);
}
}
APPEND_OPCODES.add(Op.Debugger, (vm, {
op1: _symbols,
op2: _debugInfo
}) => {
let symbols = vm[CONSTANTS].getArray(_symbols),
debugInfo = vm[CONSTANTS].getArray(decodeHandle(_debugInfo)),
inspector = new ScopeInspector(vm.scope(), symbols, debugInfo);
callback(valueForRef(vm.getSelf()), path => valueForRef(inspector.get(path)));
}), APPEND_OPCODES.add(Op.EnterList, (vm, {
op1: relativeStart,
op2: elseTarget
}) => {
let stack = vm.stack,
listRef = stack.pop(),
keyRef = stack.pop(),
keyValue = valueForRef(keyRef),
key = null === keyValue ? "@identity" : String(keyValue),
iteratorRef = createIteratorRef(listRef, key),
iterator = valueForRef(iteratorRef);
vm.updateWith(new AssertFilter(iteratorRef, iterator => iterator.isEmpty())), !0 === iterator.isEmpty() ?
// TODO: Fix this offset, should be accurate
vm.goto(elseTarget + 1) : (vm.enterList(iteratorRef, relativeStart), vm.stack.push(iterator));
}), APPEND_OPCODES.add(Op.ExitList, vm => {
vm.exitList();
}), APPEND_OPCODES.add(Op.Iterate, (vm, {
op1: breaks
}) => {
let item = vm.stack.peek().next();
null !== item ? vm.registerItem(vm.enterItem(item)) : vm.goto(breaks);
});
const CAPABILITIES$3 = {
dynamicLayout: !1,
dynamicTag: !1,
prepareArgs: !1,
createArgs: !1,
attributeHook: !1,
elementHook: !1,
createCaller: !1,
dynamicScope: !1,
updateHook: !1,
createInstance: !1,
wrapped: !1,
willDestroy: !1,
hasSubOwner: !1
};
class TemplateOnlyComponentManager {
getCapabilities() {
return CAPABILITIES$3;
}
getDebugName({
name: name
}) {
return name;
}
getSelf() {
return NULL_REFERENCE;
}
getDestroyable() {
return null;
}
}
const TEMPLATE_ONLY_COMPONENT_MANAGER = new TemplateOnlyComponentManager();
// This is only exported for types, don't use this class directly
class TemplateOnlyComponentDefinition {
constructor(moduleName = "@glimmer/component/template-only", name = "(unknown template-only component)") {
this.moduleName = moduleName, this.name = name;
}
toString() {
return this.moduleName;
}
}
/**
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
setInternalComponentManager(TEMPLATE_ONLY_COMPONENT_MANAGER, TemplateOnlyComponentDefinition.prototype);
const SVG_INTEGRATION_POINTS = {
foreignObject: 1,
desc: 1,
title: 1
},
BLACKLIST_TABLE = Object.create(null);
// 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
class DOMOperations {
// Set by this.setupUselessElement() in constructor
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) {
let isElementInSVGNamespace, isHTMLIntegrationPoint;
if (context ? (isElementInSVGNamespace = context.namespaceURI === NS_SVG || "svg" === tag, isHTMLIntegrationPoint = !!SVG_INTEGRATION_POINTS[context.tagName]) : (isElementInSVGNamespace = "svg" === tag, isHTMLIntegrationPoint = !1), 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(NS_SVG, tag);
}
return this.document.createElement(tag);
}
insertBefore(parent, node, reference) {
parent.insertBefore(node, reference);
}
insertHTMLBefore(parent, nextSibling, html) {
if ("" === html) {
const comment = this.createComment("");
return parent.insertBefore(comment, nextSibling), new ConcreteBounds(parent, comment, comment);
}
const prev = nextSibling ? nextSibling.previousSibling : parent.lastChild;
let last;
if (null === nextSibling) parent.insertAdjacentHTML(INSERT_BEFORE_END, html), last = expect(parent.lastChild, "bug in insertAdjacentHTML?");else if (nextSibling instanceof HTMLElement) nextSibling.insertAdjacentHTML("beforebegin", html), last = expect(nextSibling.previousSibling, "bug in insertAdjacentHTML?");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
const {
uselessElement: uselessElement
} = this;
parent.insertBefore(uselessElement, nextSibling), uselessElement.insertAdjacentHTML(INSERT_BEFORE_BEGIN, html), last = expect(uselessElement.previousSibling, "bug in insertAdjacentHTML?"), parent.removeChild(uselessElement);
}
const first = expect(prev ? prev.nextSibling : parent.firstChild, "bug in insertAdjacentHTML?");
return new ConcreteBounds(parent, first, last);
}
createTextNode(text) {
return this.document.createTextNode(text);
}
createComment(data) {
return this.document.createComment(data);
}
}
// 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 (!function (document, svgNamespace) {
const svg = document.createElementNS(svgNamespace, "svg");
try {
svg.insertAdjacentHTML(INSERT_BEFORE_END, "<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
return 1 !== svg.childNodes.length || castToBrowser(unwrap$1(svg.firstChild), "SVG").namespaceURI !== NS_SVG;
// eslint-disable-next-line no-unsafe-finally
}
}
// 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.
(document, svgNamespace)) return DOMClass;
const div = document.createElement("div");
return class extends DOMClass {
insertHTMLBefore(parent, nextSibling, html) {
return "" === html || parent.namespaceURI !== svgNamespace ? super.insertHTMLBefore(parent, nextSibling, html) : function (parent, div, html, reference) {
let source;
// This is important, because descendants of the <foreignObject> integration
// point are parsed in the HTML namespace
if (debugAssert("" !== html, "html cannot be empty"), "FOREIGNOBJECT" === parent.tagName.toUpperCase()) {
// IE, Edge: also do not correctly support using `innerHTML` on SVG
// namespaced elements. So here a wrapper is used.
const wrappedHtml = "<svg><foreignObject>" + html + "</foreignObject></svg>";
clearElement(div), div.insertAdjacentHTML(INSERT_AFTER_BEGIN, 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.
const wrappedHtml = "<svg>" + html + "</svg>";
clearElement(div), div.insertAdjacentHTML(INSERT_AFTER_BEGIN, wrappedHtml), source = div.firstChild;
}
return function (source, target, nextSibling) {
const first = expect(source.firstChild, "source is empty");
let last = first,
current = first;
for (; current;) {
const next = current.nextSibling;
target.insertBefore(current, nextSibling), last = current, current = next;
}
return new ConcreteBounds(target, first, last);
}(source, parent, reference);
}(parent, div, html, nextSibling);
}
};
}
function applyTextNodeMergingFix(document, DOMClass) {
return document && function (document) {
const mergingTextDiv = document.createElement("div");
return mergingTextDiv.appendChild(document.createTextNode("first")), mergingTextDiv.insertAdjacentHTML(INSERT_BEFORE_END, "second"), 2 !== mergingTextDiv.childNodes.length;
}(document) ? class extends DOMClass {
uselessComment;
constructor(document) {
super(document), this.uselessComment = document.createComment("");
}
insertHTMLBefore(parent, nextSibling, html) {
if ("" === html) return super.insertHTMLBefore(parent, nextSibling, html);
let didSetUselessComment = !1;
const nextPrevious = nextSibling ? nextSibling.previousSibling : parent.lastChild;
nextPrevious && nextPrevious instanceof Text && (didSetUselessComment = !0, parent.insertBefore(this.uselessComment, nextSibling));
const bounds = super.insertHTMLBefore(parent, nextSibling, html);
return didSetUselessComment && parent.removeChild(this.uselessComment), bounds;
}
} : DOMClass;
}
const doc$1 = "undefined" == typeof document ? null : castToSimple(document);
let appliedTreeConstruction = class extends DOMOperations {
createElementNS(namespace, tag) {
return this.document.createElementNS(namespace, tag);
}
setAttribute(element, name, value, namespace = null) {
namespace ? element.setAttributeNS(namespace, name, value) : element.setAttribute(name, value);
}
};
appliedTreeConstruction = applyTextNodeMergingFix(doc$1, appliedTreeConstruction), appliedTreeConstruction = applySVGInnerHTMLFix(doc$1, appliedTreeConstruction, NS_SVG);
const DOMTreeConstruction = appliedTreeConstruction;
["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);
const WHITESPACE = /[\t\n\v\f\r \xA0\u{1680}\u{180e}\u{2000}-\u{200a}\u{2028}\u{2029}\u{202f}\u{205f}\u{3000}\u{feff}]/u,
doc = "undefined" == typeof document ? null : castToSimple(document);
function isWhitespace(string) {
return WHITESPACE.test(string);
}
class DOMChangesImpl extends DOMOperations {
namespace;
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);
}
}
let helper$3 = DOMChangesImpl;
helper$3 = applyTextNodeMergingFix(doc, helper$3), helper$3 = applySVGInnerHTMLFix(doc, helper$3, NS_SVG);
const DOMChanges = helper$3;
let GUID = 0;
class Ref {
id = GUID++;
value;
constructor(value) {
this.value = value;
}
get() {
return this.value;
}
release() {
this.value = null;
}
toString() {
let label = `Ref ${this.id}`;
if (null === this.value) return `${label} (released)`;
try {
return `${label}: ${this.value}`;
} catch {
return label;
}
}
}
class DebugRenderTreeImpl {
stack = new StackImpl();
refs = new WeakMap();
roots = new Set();
nodes = new WeakMap();
begin() {
this.reset();
}
create(state, node) {
let internalNode = 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) {
this.nodeFor(state).bounds = bounds, this.exit();
}
willDestroy(state) {
expect(this.refs.get(state), "BUG: missing ref").release();
}
commit() {
this.reset();
}
capture() {
return this.captureRefs(this.roots);
}
reset() {
if (0 !== this.stack.size) {
// 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)
let root = expect(this.stack.toArray()[0], "expected root state when resetting render tree"),
ref = this.refs.get(root);
for (void 0 !== ref && this.roots.delete(ref); !this.stack.isEmpty();) this.stack.pop();
}
}
enter(state) {
this.stack.push(state);
}
exit() {
this.stack.pop();
}
nodeFor(state) {
return expect(this.nodes.get(state), "BUG: missing node");
}
appendChild(node, state) {
let parent = this.stack.current,
ref = new Ref(state);
if (this.refs.set(state, ref), parent) {
let parentNode = this.nodeFor(parent);
parentNode.refs.add(ref), node.parent = parentNode;
} else this.roots.add(ref);
}
captureRefs(refs) {
let captured = [];
return refs.forEach(ref => {
let state = ref.get();
state ? captured.push(this.captureNode(`render-node:${ref.id}`, state)) : refs.delete(ref);
}), captured;
}
captureNode(id, state) {
let node = this.nodeFor(state),
{
type: type,
name: name,
args: args,
instance: instance,
refs: refs
} = node,
template = this.captureTemplate(node),
bounds = this.captureBounds(node),
children = this.captureRefs(refs);
return {
id: id,
type: type,
name: name,
args: reifyArgsDebug(args),
instance: instance,
template: template,
bounds: bounds,
children: children
};
}
captureTemplate({
template: template
}) {
return template || null;
}
captureBounds(node) {
let bounds = expect(node.bounds, "BUG: missing bounds");
return {
parentElement: bounds.parentElement(),
firstNode: bounds.firstNode(),
lastNode: bounds.lastNode()
};
}
}
const TRANSACTION = Symbol("TRANSACTION");
class TransactionImpl {
scheduledInstallModifiers = [];
scheduledUpdateModifiers = [];
createdComponents = [];
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() {
let {
createdComponents: createdComponents,
updatedComponents: updatedComponents
} = this;
for (const {
manager: manager,
state: state
} of createdComponents) manager.didCreate(state);
for (const {
manager: manager,
state: state
} of updatedComponents) manager.didUpdate(state);
let {
scheduledInstallModifiers: scheduledInstallModifiers,
scheduledUpdateModifiers: scheduledUpdateModifiers
} = this;
for (const {
manager: manager,
state: state,
definition: definition
} of scheduledInstallModifiers) {
let modifierTag = manager.getTag(state);
if (null !== modifierTag) {
let tag = track(() => manager.install(state));
UPDATE_TAG(modifierTag, tag);
} else manager.install(state);
}
for (const {
manager: manager,
state: state,
definition: definition
} of scheduledUpdateModifiers) {
let modifierTag = manager.getTag(state);
if (null !== modifierTag) {
let tag = track(() => manager.update(state));
UPDATE_TAG(modifierTag, tag);
} else manager.update(state);
}
}
}
class EnvironmentImpl {
[TRANSACTION] = null;
updateOperations;
// Delegate methods and values
isInteractive;
isArgumentCaptureError;
debugRenderTree;
constructor(options, delegate) {
if (this.delegate = delegate, this.isInteractive = delegate.isInteractive, this.debugRenderTree = this.delegate.enableDebugTooling ? new DebugRenderTreeImpl() : void 0, this.isArgumentCaptureError = this.delegate.enableDebugTooling ? isArgumentError : void 0, 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 ;
}
getAppendOperations() {
return this.appendOperations;
}
getDOM() {
return expect(this.updateOperations, "Attempted to get DOM updateOperations, but they were not provided by the environment. You may be attempting to rerender in an environment which does not support rerendering, such as SSR.");
}
begin() {
debugAssert(!this[TRANSACTION], "A glimmer transaction was begun, but one already exists. You may have a nested transaction, possibly caused by an earlier runtime exception while rendering. Please check your console for the stack trace of any prior exceptions."), this.debugRenderTree?.begin(), this[TRANSACTION] = new TransactionImpl();
}
get transaction() {
return expect(this[TRANSACTION], "must be in a transaction");
}
didCreate(component) {
this.transaction.didCreate(component);
}
didUpdate(component) {
this.transaction.didUpdate(component);
}
scheduleInstallModifier(modifier) {
this.isInteractive && this.transaction.scheduleInstallModifier(modifier);
}
scheduleUpdateModifier(modifier) {
this.isInteractive && this.transaction.scheduleUpdateModifier(modifier);
}
commit() {
let transaction = this.transaction;
this[TRANSACTION] = null, transaction.commit(), this.debugRenderTree?.commit(), this.delegate.onTransactionCommit();
}
}
function runtimeContext(options, delegate, artifacts, resolver) {
return {
env: new EnvironmentImpl(options, delegate),
program: new RuntimeProgramImpl(artifacts.constants, artifacts.heap),
resolver: resolver
};
}
function inTransaction(env, block) {
if (env[TRANSACTION]) block();else {
env.begin();
try {
block();
} finally {
env.commit();
}
}
}
function internalHelper$1(helper) {
return setInternalHelperManager(helper, {});
}
/**
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
*/
const array$1 = internalHelper$1(({
positional: positional
}) => createComputeRef(() => reifyPositional(positional), null, "array")),
normalizeTextValue = value => (value => null == value || "function" != typeof value.toString)(value) ? "" : String(value),
concat$1 = internalHelper$1(({
positional: positional
}) => createComputeRef(() => reifyPositional(positional).map(normalizeTextValue).join(""), null, "concat")),
context = buildUntouchableThis(),
fn$1 = internalHelper$1(({
positional: positional
}) => {
let callbackRef = positional[0];
return createComputeRef(() => (...invocationArgs) => {
let [fn, ...args] = reifyPositional(positional);
if (isInvokableRef(callbackRef)) {
let value = args.length > 0 ? args[0] : invocationArgs[0];
return updateRef(callbackRef, value);
}
return fn.call(context, ...args, ...invocationArgs);
}, null, "fn");
}),
get$1 = internalHelper$1(({
positional: positional
}) => {
let sourceRef = positional[0] ?? UNDEFINED_REFERENCE,
pathRef = positional[1] ?? UNDEFINED_REFERENCE;
return createComputeRef(() => {
let source = valueForRef(sourceRef);
if (isDict(source)) return getPath$1(source, String(valueForRef(pathRef)));
}, value => {
let source = valueForRef(sourceRef);
if (isDict(source)) return setPath(source, String(valueForRef(pathRef)), value);
}, "get");
}),
hash$1 = internalHelper$1(({
named: named
}) => {
let ref = createComputeRef(() => reifyNamed(named), null, "hash"),
children = new Map();
// Setup the children so that templates can bypass getting the value of
// the reference and treat children lazily
for (let name in named) children.set(name, named[name]);
return ref.children = children, ref;
});
function getArgs(proxy) {
return getValue(proxy.argsCache);
}
class SimpleArgsProxy {
argsCache;
constructor(context, computeArgs = () => EMPTY_ARGS) {
let argsCache = createCache(() => computeArgs(context));
this.argsCache = argsCache;
}
get named() {
return getArgs(this).named || EMPTY_NAMED;
}
get positional() {
return getArgs(this).positional || EMPTY_POSITIONAL;
}
}
////////////
function invokeHelper$1(context, definition, computeArgs) {
const owner = getOwner$3(context),
internalManager = getInternalHelperManager(definition);
const manager = internalManager.getDelegateFor(owner);
let cache,
args = new SimpleArgsProxy(context, computeArgs),
bucket = manager.createHelper(definition, args);
if (!hasValue(manager)) throw new Error("TODO: unreachable, to be implemented with hasScheduledEffect");
if (cache = createCache(() => {
return manager.getValue(bucket);
}), associateDestroyableChild(context, cache), hasDestroyable(manager)) {
let destroyable = manager.getDestroyable(bucket);
associateDestroyableChild(cache, destroyable);
}
return cache;
}
class OnModifierState {
tag = createUpdatableTag();
element;
args;
listener = null;
constructor(element, args) {
this.element = element, this.args = args, registerDestructor$1(this, () => {
let {
element: element,
listener: listener
} = this;
if (listener) {
let {
eventName: eventName,
callback: callback,
options: options
} = listener;
removeEventListener(element, eventName, callback, options);
}
});
}
// Update this.listener if needed
updateListener() {
let {
element: element,
args: args,
listener: listener
} = this;
debugAssert(args.positional[0], "You must pass a valid DOM event name as the first argument to the `on` modifier");
let eventName = valueForRef(args.positional[0]);
debugAssert(args.positional[1], "You must pass a function as the second argument to the `on` modifier");
let once,
passive,
capture,
userProvidedCallback = valueForRef(args.positional[1]);
{
let {
once: _once,
passive: _passive,
capture: _capture
} = args.named;
_once && (once = valueForRef(_once)), _passive && (passive = valueForRef(_passive)), _capture && (capture = valueForRef(_capture));
}
let options,
shouldUpdate = !1;
if (shouldUpdate = null === listener || eventName !== listener.eventName || userProvidedCallback !== listener.userProvidedCallback || once !== listener.once || passive !== listener.passive || capture !== listener.capture,
// we want to handle both `true` and `false` because both have a meaning:
// https://bugs.chromium.org/p/chromium/issues/detail?id=770208
shouldUpdate && (void 0 === once && void 0 === passive && void 0 === capture || (options = {
once: once,
passive: passive,
capture: capture
})), shouldUpdate) {
let callback = userProvidedCallback;
this.listener = {
eventName: eventName,
callback: callback,
userProvidedCallback: userProvidedCallback,
once: once,
passive: passive,
capture: capture,
options: options
}, listener && removeEventListener(element, listener.eventName, listener.callback, listener.options), function (element, eventName, callback, options) {
adds++, element.addEventListener(eventName, callback, options);
}
/**
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
*/(element, eventName, callback, options);
}
}
}
let adds = 0,
removes = 0;
function removeEventListener(element, eventName, callback, options) {
removes++, element.removeEventListener(eventName, callback, options);
}
const on$1 = setInternalModifierManager(new class {
getDebugName() {
return "on";
}
getDebugInstance() {
return null;
}
get counters() {
return {
adds: adds,
removes: removes
};
}
create(_owner, element, _state, args) {
return new OnModifierState(element, args);
}
getTag({
tag: tag
}) {
return tag;
}
install(state) {
state.updateListener();
}
update(state) {
state.updateListener();
}
getDestroyable(state) {
return state;
}
}(), {});
class LowLevelVM {
currentOpSize = 0;
constructor(stack, heap, program, externs, registers) {
this.stack = stack, this.heap = heap, this.program = program, this.externs = externs, this.registers = registers;
}
fetchRegister(register) {
return this.registers[register];
}
loadRegister(register, value) {
this.registers[register] = value;
}
setPc(pc) {
debugAssert("number" == typeof pc && !isNaN(pc), "pc is set to a number"), this.registers[$pc] = pc;
}
// Start a new frame and save $ra and $fp on the stack
pushFrame() {
this.stack.push(this.registers[$ra]), this.stack.push(this.registers[$fp]), this.registers[$fp] = this.registers[$sp] - 1;
}
// Restore $ra, $sp and $fp
popFrame() {
this.registers[$sp] = this.registers[$fp] - 1, this.registers[$ra] = this.stack.get(0), this.registers[$fp] = this.stack.get(1);
}
pushSmallFrame() {
this.stack.push(this.registers[$ra]);
}
popSmallFrame() {
this.registers[$ra] = this.stack.pop();
}
// Jump to an address in `program`
goto(offset) {
this.setPc(this.target(offset));
}
target(offset) {
return this.registers[$pc] + offset - this.currentOpSize;
}
// Save $pc into $ra, then jump to a new address in `program` (jal in MIPS)
call(handle) {
debugAssert(handle < 4294967295, "Jumping to placeholder address"), this.registers[$ra] = this.registers[$pc], this.setPc(this.heap.getaddr(handle));
}
// Put a specific `program` address in $ra
returnTo(offset) {
this.registers[$ra] = this.target(offset);
}
// Return to the `program` address stored in $ra
return() {
this.setPc(this.registers[$ra]);
}
nextStatement() {
let {
registers: registers,
program: program
} = this,
pc = registers[$pc];
if (debugAssert("number" == typeof pc, "pc is a number"), -1 === pc) 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.
let opcode = program.opcode(pc),
operationSize = this.currentOpSize = opcode.size;
return this.registers[$pc] += operationSize, opcode;
}
evaluateOuter(opcode, vm) {
this.evaluateInner(opcode, vm);
}
evaluateInner(opcode, vm) {
opcode.isMachine ? this.evaluateMachine(opcode) : this.evaluateSyscall(opcode, vm);
}
evaluateMachine(opcode) {
switch (opcode.type) {
case MachineOp.PushFrame:
return this.pushFrame();
case MachineOp.PopFrame:
return this.popFrame();
case MachineOp.InvokeStatic:
return this.call(opcode.op1);
case MachineOp.InvokeVirtual:
return this.call(this.stack.pop());
case MachineOp.Jump:
return this.goto(opcode.op1);
case MachineOp.Return:
return this.return();
case MachineOp.ReturnTo:
return this.returnTo(opcode.op1);
}
}
evaluateSyscall(opcode, vm) {
APPEND_OPCODES.evaluate(vm, opcode, opcode.type);
}
}
class UpdatingVM {
env;
dom;
alwaysRevalidate;
frameStack = new StackImpl();
constructor(env, {
alwaysRevalidate = !1
}) {
this.env = env, this.dom = env.getDOM(), this.alwaysRevalidate = alwaysRevalidate;
}
execute(opcodes, handler) {
this._execute(opcodes, handler);
}
_execute(opcodes, handler) {
let {
frameStack: frameStack
} = this;
for (this.try(opcodes, handler); !frameStack.isEmpty();) {
let opcode = this.frame.nextStatement();
void 0 !== opcode ? opcode.evaluate(this) : frameStack.pop();
}
}
get frame() {
return expect(this.frameStack.current, "bug: expected a frame");
}
goto(index) {
this.frame.goto(index);
}
try(ops, handler) {
this.frameStack.push(new UpdatingVMFrame(ops, handler));
}
throw() {
this.frame.handleException(), this.frameStack.pop();
}
}
class ResumableVMStateImpl {
constructor(state, resumeCallback) {
this.state = state, this.resumeCallback = resumeCallback;
}
resume(runtime, builder) {
return this.resumeCallback(runtime, this.state, builder);
}
}
class BlockOpcode {
children;
bounds;
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 {
type = "try";
// Hides property on base class
evaluate(vm) {
vm.try(this.children, this);
}
handleException() {
let {
state: state,
bounds: bounds,
runtime: runtime
} = this;
destroyChildren(this);
let elementStack = NewElementBuilder.resume(runtime.env, bounds),
vm = state.resume(runtime, elementStack),
updating = [],
children = this.children = [],
result = vm.execute(vm => {
vm.pushUpdating(updating), vm.updateWith(this), vm.pushUpdating(children);
});
associateDestroyableChild(this, result.drop);
}
}
class ListItemOpcode extends TryOpcode {
retained = !1;
index = -1;
constructor(state, runtime, bounds, key, memo, value) {
super(state, runtime, bounds, []), this.key = key, this.memo = memo, this.value = value;
}
updateReferences(item) {
this.retained = !0, updateRef(this.value, item.value), updateRef(this.memo, item.memo);
}
shouldRemove() {
return !this.retained;
}
reset() {
this.retained = !1;
}
}
class ListBlockOpcode extends BlockOpcode {
type = "list-block";
opcodeMap = new Map();
marker = null;
lastIterator;
constructor(state, runtime, bounds, children, iterableRef) {
super(state, runtime, bounds, children), this.iterableRef = iterableRef, this.lastIterator = valueForRef(iterableRef);
}
initializeChild(opcode) {
opcode.index = this.children.length - 1, this.opcodeMap.set(opcode.key, opcode);
}
evaluate(vm) {
let iterator = valueForRef(this.iterableRef);
if (this.lastIterator !== iterator) {
let {
bounds: bounds
} = this,
{
dom: dom
} = vm,
marker = this.marker = dom.createComment("");
dom.insertAfter(bounds.parentElement(), marker, expect(bounds.lastNode(), "can't insert after an empty bounds")), this.sync(iterator), this.parentElement().removeChild(marker), this.marker = null, this.lastIterator = iterator;
}
// Run now-updated updating opcodes
super.evaluate(vm);
}
sync(iterator) {
let {
opcodeMap: itemMap,
children: children
} = this,
currentOpcodeIndex = 0,
seenIndex = 0;
// eslint-disable-next-line no-constant-condition
for (this.children = this.bounds.boundList = [];;) {
let item = iterator.next();
if (null === item) break;
let opcode = children[currentOpcodeIndex],
{
key: key
} = item;
// Items that have already been found and moved will already be retained,
// we can continue until we find the next unretained item
for (; void 0 !== opcode && !0 === opcode.retained;) opcode = children[++currentOpcodeIndex];
if (void 0 !== opcode && opcode.key === key) this.retainItem(opcode, item), currentOpcodeIndex++;else if (itemMap.has(key)) {
let 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;
let seenUnretained = !1;
// 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 (let i = currentOpcodeIndex + 1; i < seenIndex; i++) if (!1 === unwrap$1(children[i]).retained) {
seenUnretained = !0;
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.
!1 === seenUnretained ? (this.retainItem(itemOpcode, item), currentOpcodeIndex = seenIndex + 1) : (this.moveItem(itemOpcode, item, opcode), currentOpcodeIndex++);
}
} else this.insertItem(item, opcode);
}
for (const opcode of children) !1 === opcode.retained ? this.deleteItem(opcode) : opcode.reset();
}
retainItem(opcode, item) {
let {
children: children
} = this;
updateRef(opcode.memo, item.memo), updateRef(opcode.value, item.value), opcode.retained = !0, opcode.index = children.length, children.push(opcode);
}
insertItem(item, before) {
let {
opcodeMap: opcodeMap,
bounds: bounds,
state: state,
runtime: runtime,
children: children
} = this,
{
key: key
} = item,
nextSibling = void 0 === before ? this.marker : before.firstNode(),
elementStack = NewElementBuilder.forInitialRender(runtime.env, {
element: bounds.parentElement(),
nextSibling: nextSibling
});
state.resume(runtime, elementStack).execute(vm => {
vm.pushUpdating();
let opcode = vm.enterItem(item);
opcode.index = children.length, children.push(opcode), opcodeMap.set(key, opcode), associateDestroyableChild(this, opcode);
});
}
moveItem(opcode, item, before) {
let currentSibling,
nextSibling,
{
children: children
} = this;
updateRef(opcode.memo, item.memo), updateRef(opcode.value, item.value), opcode.retained = !0, void 0 === before ? move(opcode, this.marker) : (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.
currentSibling !== nextSibling && move(opcode, nextSibling)), opcode.index = children.length, children.push(opcode);
}
deleteItem(opcode) {
destroy(opcode), clear(opcode), this.opcodeMap.delete(opcode.key);
}
}
class UpdatingVMFrame {
current = 0;
constructor(ops, exceptionHandler) {
this.ops = ops, this.exceptionHandler = exceptionHandler;
}
goto(index) {
this.current = index;
}
nextStatement() {
return this.ops[this.current++];
}
handleException() {
this.exceptionHandler && this.exceptionHandler.handleException();
}
}
class RenderResultImpl {
constructor(env, updating, bounds, drop) {
this.env = env, this.updating = updating, this.bounds = bounds, this.drop = drop, associateDestroyableChild(this, drop), registerDestructor$1(this, () => clear(this.bounds));
}
rerender({
alwaysRevalidate = !1
} = {
alwaysRevalidate: !1
}) {
let {
env: env,
updating: updating
} = this;
new UpdatingVM(env, {
alwaysRevalidate: alwaysRevalidate
}).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 {
static restore(snapshot) {
return new this(snapshot.slice(), [0, -1, snapshot.length - 1, 0]);
}
[REGISTERS];
// fp -> sp
constructor(stack = [], registers) {
this.stack = stack, this[REGISTERS] = registers;
}
push(value) {
this.stack[++this[REGISTERS][$sp]] = value;
}
dup(position = this[REGISTERS][$sp]) {
this.stack[++this[REGISTERS][$sp]] = this.stack[position];
}
copy(from, to) {
this.stack[to] = this.stack[from];
}
pop(n = 1) {
let top = this.stack[this[REGISTERS][$sp]];
return this[REGISTERS][$sp] -= n, top;
}
peek(offset = 0) {
return this.stack[this[REGISTERS][$sp] - offset];
}
get(offset, base = this[REGISTERS][$fp]) {
return this.stack[base + offset];
}
set(value, offset, base = this[REGISTERS][$fp]) {
this.stack[base + offset] = value;
}
slice(start, end) {
return this.stack.slice(start, end);
}
capture(items) {
let end = this[REGISTERS][$sp] + 1,
start = end - items;
return this.stack.slice(start, end);
}
reset() {
this.stack.length = 0;
}
toArray() {
return this.stack.slice(this[REGISTERS][$fp], this[REGISTERS][$sp] + 1);
}
}
/**
* This interface is used by internal opcodes, and is more stable than
* the implementation of the Append VM itself.
*/
class Stacks {
scope = new StackImpl();
dynamicScope = new StackImpl();
updating = new StackImpl();
cache = new StackImpl();
list = new StackImpl();
}
class VM {
[STACKS] = new Stacks();
[HEAP];
destructor;
[DESTROYABLE_STACK] = new StackImpl();
[CONSTANTS];
[ARGS$1];
[INNER_VM];
get stack() {
return this[INNER_VM].stack;
}
/* Registers */
get pc() {
return this[INNER_VM].fetchRegister($pc);
}
s0 = null;
s1 = null;
t0 = null;
t1 = null;
v0 = null;
// Fetch a value from a register onto the stack
fetch(register) {
let value = this.fetchValue(register);
this.stack.push(value);
}
// Load a value from the stack into a register
load(register) {
let value = this.stack.pop();
this.loadValue(register, value);
}
// Fetch a value from a register
fetchValue(register) {
if (isLowLevelRegister(register)) return this[INNER_VM].fetchRegister(register);
switch (register) {
case $s0:
return this.s0;
case $s1:
return this.s1;
case $t0:
return this.t0;
case $t1:
return this.t1;
case $v0:
return this.v0;
}
}
// Load a value into a register
loadValue(register, value) {
switch (isLowLevelRegister(register) && this[INNER_VM].loadRegister(register, value), register) {
case $s0:
this.s0 = value;
break;
case $s1:
this.s1 = value;
break;
case $t0:
this.t0 = value;
break;
case $t1:
this.t1 = value;
break;
case $v0:
this.v0 = value;
}
}
/**
* 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();
}
/**
* End of migrated.
*/
constructor(runtime, {
pc: pc,
scope: scope,
dynamicScope: dynamicScope,
stack: stack
}, elementStack, context) {
this.runtime = runtime, this.elementStack = elementStack, this.context = context, this.resume = initVM(context);
let evalStack = EvaluationStackImpl.restore(stack);
debugAssert("number" == typeof pc, "pc is a number"), evalStack[REGISTERS][$pc] = pc, evalStack[REGISTERS][$sp] = stack.length - 1, evalStack[REGISTERS][$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$1] = new VMArgumentsImpl(), this[INNER_VM] = new LowLevelVM(evalStack, this[HEAP], runtime.program, {
debugBefore: opcode => APPEND_OPCODES.debugBefore(this, opcode),
debugAfter: state => {
APPEND_OPCODES.debugAfter(this, state);
}
}, evalStack[REGISTERS]), this.destructor = {}, this[DESTROYABLE_STACK].push(this.destructor);
}
static initial(runtime, context, {
handle: handle,
self: self,
dynamicScope: dynamicScope,
treeBuilder: treeBuilder,
numSymbols: numSymbols,
owner: owner
}) {
let scope = PartialScopeImpl.root(self, numSymbols, owner),
state = vmState(runtime.program.heap.getaddr(handle), scope, dynamicScope),
vm = initVM(context)(runtime, state, treeBuilder);
return vm.pushUpdating(), vm;
}
static empty(runtime, {
handle: handle,
treeBuilder: treeBuilder,
dynamicScope: dynamicScope,
owner: owner
}, context) {
let vm = initVM(context)(runtime, vmState(runtime.program.heap.getaddr(handle), PartialScopeImpl.root(UNDEFINED_REFERENCE, 0, owner), dynamicScope), treeBuilder);
return vm.pushUpdating(), vm;
}
resume;
compile(block) {
return unwrapHandle(block.compile(this.context));
}
get program() {
return this.runtime.program;
}
get env() {
return this.runtime.env;
}
captureState(args, pc = this[INNER_VM].fetchRegister($pc)) {
return {
pc: pc,
scope: this.scope(),
dynamicScope: this.dynamicScope(),
stack: this.stack.capture(args)
};
}
capture(args, pc = this[INNER_VM].fetchRegister($pc)) {
return new ResumableVMStateImpl(this.captureState(args, pc), this.resume);
}
beginCacheGroup(name) {
let opcodes = this.updating(),
guard = new JumpIfNotModifiedOpcode();
opcodes.push(guard), opcodes.push(new BeginTrackFrameOpcode(name)), this[STACKS].cache.push(guard), beginTrackFrame();
}
commitCacheGroup() {
let opcodes = this.updating(),
guard = expect(this[STACKS].cache.pop(), "VM BUG: Expected a cache group"),
tag = endTrackFrame();
opcodes.push(new EndTrackFrameOpcode(guard)), guard.finalize(tag, opcodes.length);
}
enter(args) {
let state = this.capture(args),
block = this.elements().pushUpdatableBlock(),
tryOpcode = new TryOpcode(state, this.runtime, block, []);
this.didEnter(tryOpcode);
}
enterItem({
key: key,
value: value,
memo: memo
}) {
let {
stack: stack
} = this,
valueRef = createIteratorItemRef(value),
memoRef = createIteratorItemRef(memo);
stack.push(valueRef), stack.push(memoRef);
let state = this.capture(2),
block = this.elements().pushUpdatableBlock(),
opcode = new ListItemOpcode(state, this.runtime, block, key, memoRef, valueRef);
return this.didEnter(opcode), opcode;
}
registerItem(opcode) {
this.listBlock().initializeChild(opcode);
}
enterList(iterableRef, offset) {
let updating = [],
addr = this[INNER_VM].target(offset),
state = this.capture(0, addr),
list = this.elements().pushBlockList(updating),
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 expect(this[STACKS].updating.pop(), "can't pop an empty stack");
}
updateWith(opcode) {
this.updating().push(opcode);
}
listBlock() {
return expect(this[STACKS].list.current, "expected a list block");
}
associateDestroyable(child) {
let parent = expect(this[DESTROYABLE_STACK].current, "Expected destructor parent");
associateDestroyableChild(parent, child);
}
tryUpdating() {
return this[STACKS].updating.current;
}
updating() {
return expect(this[STACKS].updating.current, "expected updating opcode on the updating opcode stack");
}
elements() {
return this.elementStack;
}
scope() {
return expect(this[STACKS].scope.current, "expected scope on the scope stack");
}
dynamicScope() {
return expect(this[STACKS].dynamicScope.current, "expected dynamic scope on the dynamic scope stack");
}
pushChildScope() {
this[STACKS].scope.push(this.scope().child());
}
pushDynamicScope() {
let child = this.dynamicScope().child();
return this[STACKS].dynamicScope.push(child), child;
}
pushRootScope(size, owner) {
let scope = PartialScopeImpl.sized(size, owner);
return this[STACKS].scope.push(scope), 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) {
return this.scope().getSymbol(symbol);
}
/// EXECUTION
execute(initialize) {
return this._execute(initialize);
}
_execute(initialize) {
let result;
initialize && initialize(this);
do {
result = this.next();
} while (!result.done);
return result.value;
}
next() {
let result,
{
env: env,
elementStack: elementStack
} = this,
opcode = this[INNER_VM].nextStatement();
return null !== opcode ? (this[INNER_VM].evaluateOuter(opcode, this), result = {
done: !1,
value: null
}) : (
// Unload the stack
this.stack.reset(), result = {
done: !0,
value: new RenderResultImpl(env, this.popUpdating(), elementStack.popBlock(), this.destructor)
}), result;
}
bindDynamicScope(names) {
let scope = this.dynamicScope();
for (const name of reverse(names)) scope.set(name, this.stack.pop());
}
}
function vmState(pc, scope, dynamicScope) {
return {
pc: pc,
scope: scope,
dynamicScope: 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() {
return this.vm.execute();
}
}
function renderSync(env, iterator) {
let result;
return inTransaction(env, () => result = iterator.sync()), result;
}
function renderMain(runtime, context, owner, self, treeBuilder, layout, dynamicScope = new DynamicScopeImpl()) {
let handle = unwrapHandle(layout.compile(context)),
numSymbols = layout.symbolTable.symbols.length,
vm = VM.initial(runtime, context, {
self: self,
dynamicScope: dynamicScope,
treeBuilder: treeBuilder,
handle: handle,
numSymbols: numSymbols,
owner: owner
});
return new TemplateIteratorImpl(vm);
}
function renderComponent(runtime, treeBuilder, context, owner, definition, args = {}, dynamicScope = new DynamicScopeImpl()) {
return function (vm, context, owner, definition, args) {
// Get a list of tuples of argument names and references, like
// [['title', reference], ['name', reference]]
const argList = Object.keys(args).map(key => [key, args[key]]),
blockNames = ["main", "else", "attrs"],
argNames = argList.map(([name]) => `@${name}`);
let reified = vm[CONSTANTS].component(definition, owner);
vm.pushFrame();
// Push blocks on to the stack, three stack values per block
for (let 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$1].setup(vm.stack, argNames, blockNames, 0, !0);
const compilable = expect(reified.compilable, "BUG: Expected the root component rendered with renderComponent to have an associated template, set with setComponentTemplate"),
invocation = {
handle: unwrapHandle(compilable.compile(context)),
symbolTable: compilable.symbolTable
};
// Needed for the Op.Main opcode: arguments, component invocation object, and
// component definition.
return vm.stack.push(vm[ARGS$1]), vm.stack.push(invocation), vm.stack.push(reified), new TemplateIteratorImpl(vm);
}(VM.empty(runtime, {
treeBuilder: treeBuilder,
handle: context.stdlib.main,
dynamicScope: dynamicScope,
owner: owner
}, context), context, owner, definition, function (record) {
const root = createConstRef(record);
return Object.keys(record).reduce((acc, key) => (acc[key] = childRefFor(root, key), acc), {});
}(args));
}
const SERIALIZATION_FIRST_NODE_STRING = "%+b:0%";
function isSerializationFirstNode(node) {
return "%+b:0%" === node.nodeValue;
}
class RehydratingCursor extends CursorImpl {
candidate = null;
openBlockDepth;
injectedOmittedNode = !1;
constructor(element, nextSibling, startingBlockDepth) {
super(element, nextSibling), this.startingBlockDepth = startingBlockDepth, this.openBlockDepth = startingBlockDepth - 1;
}
}
class RehydrateBuilder extends NewElementBuilder {
unmatchedAttributes = null;
// Hides property on base class
blockDepth = 0;
startingBlockOffset;
constructor(env, parentNode, nextSibling) {
if (super(env, parentNode, nextSibling), nextSibling) throw new Error("Rehydration with nextSibling not supported");
let node = this.currentCursor.element.firstChild;
for (; null !== node && !isOpenBlock(node);) node = node.nextSibling;
debugAssert(node, "Must have opening comment for rehydration."), this.candidate = node;
const startingBlockOffset = getBlockDepth(node);
if (0 !== startingBlockOffset) {
// 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
const newBlockDepth = startingBlockOffset - 1,
newCandidate = this.dom.createComment(`%+b:${newBlockDepth}%`);
node.parentNode.insertBefore(newCandidate, this.candidate);
let closingNode = node.nextSibling;
for (; null !== closingNode && (!isCloseBlock(closingNode) || getBlockDepth(closingNode) !== startingBlockOffset);) closingNode = closingNode.nextSibling;
debugAssert(closingNode, "Must have closing comment for starting block comment");
const 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() {
return this.currentCursor ? this.currentCursor.candidate : null;
}
set candidate(node) {
this.currentCursor.candidate = node;
}
disableRehydration(nextSibling) {
const 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) {
const currentCursor = this.currentCursor;
currentCursor.candidate = candidate, currentCursor.nextSibling = null;
}
pushElement(element, nextSibling = null) {
const 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
*/
null !== this.candidate && (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) {
let current = candidate;
const currentCursor = this.currentCursor;
if (null !== currentCursor) {
const openBlockDepth = currentCursor.openBlockDepth;
if (openBlockDepth >= currentCursor.startingBlockDepth) for (; current && !(isCloseBlock(current) && openBlockDepth >= getBlockDepthWithOffset(current, this.startingBlockOffset));) current = this.remove(current);else for (; null !== current;) current = this.remove(current);
// current cursor parentNode should be openCandidate if element
// or openCandidate.parentNode if comment
this.disableRehydration(current);
}
}
__openBlock() {
const {
currentCursor: currentCursor
} = this;
if (null === currentCursor) return;
const blockDepth = this.blockDepth;
this.blockDepth++;
const {
candidate: candidate
} = currentCursor;
if (null === candidate) return;
const {
tagName: tagName
} = currentCursor.element;
isOpenBlock(candidate) && getBlockDepthWithOffset(candidate, this.startingBlockOffset) === blockDepth ? (this.candidate = this.remove(candidate), currentCursor.openBlockDepth = blockDepth) : "TITLE" !== tagName && "SCRIPT" !== tagName && "STYLE" !== tagName && this.clearMismatch(candidate);
}
__closeBlock() {
const {
currentCursor: currentCursor
} = this;
if (null === currentCursor) return;
// openBlock is the last rehydrated open block
const openBlockDepth = currentCursor.openBlockDepth;
// this currently is the expected next open block depth
this.blockDepth--;
const {
candidate: candidate
} = currentCursor;
let isRehydrating = !1;
if (null !== candidate)
//assert(
// openBlockDepth === this.blockDepth,
// 'when rehydrating, openBlockDepth should match this.blockDepth here'
//);
if (isRehydrating = !0, isCloseBlock(candidate) && getBlockDepthWithOffset(candidate, this.startingBlockOffset) === openBlockDepth) {
const 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 = !1;
if (!1 === isRehydrating) {
// check if nextSibling matches our expected close block
// if so, we remove the close block comment and
// restore rehydration after clearMismatch disabled
const nextSibling = currentCursor.nextSibling;
if (null !== nextSibling && isCloseBlock(nextSibling) && getBlockDepthWithOffset(nextSibling, this.startingBlockOffset) === this.blockDepth) {
// restore rehydration state
const candidate = this.remove(nextSibling);
this.enableRehydration(candidate), currentCursor.openBlockDepth--;
}
}
}
__appendNode(node) {
const {
candidate: 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.
return candidate || super.__appendNode(node);
}
__appendHTML(html) {
const candidateBounds = this.markerBounds();
if (candidateBounds) {
const first = candidateBounds.firstNode(),
last = candidateBounds.lastNode(),
newBounds = new ConcreteBounds(this.element, first.nextSibling, last.previousSibling),
possibleEmptyMarker = this.remove(first);
return this.remove(last), null !== possibleEmptyMarker && isEmpty$1(possibleEmptyMarker) && (this.candidate = this.remove(possibleEmptyMarker), null !== this.candidate && this.clearMismatch(this.candidate)), newBounds;
}
return super.__appendHTML(html);
}
remove(node) {
const element = expect(node.parentNode, "cannot remove a detached node"),
next = node.nextSibling;
return element.removeChild(node), next;
}
markerBounds() {
const _candidate = this.candidate;
if (_candidate && isMarker(_candidate)) {
const first = _candidate;
let last = expect(first.nextSibling, "BUG: serialization markers must be paired");
for (; last && !isMarker(last);) last = expect(last.nextSibling, "BUG: serialization markers must be paired");
return new ConcreteBounds(this.element, first, last);
}
return null;
}
__appendText(string) {
const {
candidate: candidate
} = this;
return candidate ? 3 === candidate.nodeType ? (candidate.nodeValue !== string && (candidate.nodeValue = string), this.candidate = candidate.nextSibling, candidate) : 8 === (node = candidate).nodeType && "%|%" === node.nodeValue || isEmpty$1(candidate) && "" === string ? (this.candidate = this.remove(candidate), this.__appendText(string)) : (this.clearMismatch(candidate), super.__appendText(string)) : super.__appendText(string);
var node;
}
__appendComment(string) {
const _candidate = this.candidate;
return _candidate && 8 === _candidate.nodeType ? (_candidate.nodeValue !== string && (_candidate.nodeValue = string), this.candidate = _candidate.nextSibling, _candidate) : (_candidate && this.clearMismatch(_candidate), super.__appendComment(string));
}
__openElement(tag) {
const _candidate = this.candidate;
if (_candidate && isElement(_candidate) && function (candidate, tag) {
return candidate.namespaceURI === NS_SVG ? candidate.tagName === tag : candidate.tagName === tag.toUpperCase();
}(_candidate, tag)) return this.unmatchedAttributes = [].slice.call(_candidate.attributes), _candidate;
if (_candidate) {
if (isElement(_candidate) && "TBODY" === _candidate.tagName) return this.pushElement(_candidate, null), this.currentCursor.injectedOmittedNode = !0, this.__openElement(tag);
this.clearMismatch(_candidate);
}
return super.__openElement(tag);
}
__setAttribute(name, value, namespace) {
const unmatched = this.unmatchedAttributes;
if (unmatched) {
const attr = findByName(unmatched, name);
if (attr) return attr.value !== value && (attr.value = value), void unmatched.splice(unmatched.indexOf(attr), 1);
}
return super.__setAttribute(name, value, namespace);
}
__setProperty(name, value) {
const unmatched = this.unmatchedAttributes;
if (unmatched) {
const attr = findByName(unmatched, name);
if (attr) return attr.value !== value && (attr.value = value), void unmatched.splice(unmatched.indexOf(attr), 1);
}
return super.__setProperty(name, value);
}
__flushElement(parent, constructing) {
const {
unmatchedAttributes: unmatched
} = this;
if (unmatched) {
for (const attr of unmatched) this.constructing.removeAttribute(attr.name);
this.unmatchedAttributes = null;
} else super.__flushElement(parent, constructing);
}
willCloseElement() {
const {
candidate: candidate,
currentCursor: currentCursor
} = this;
null !== candidate && this.clearMismatch(candidate), currentCursor && currentCursor.injectedOmittedNode && this.popElement(), super.willCloseElement();
}
getMarker(element, guid) {
const marker = element.querySelector(`script[glmr="${guid}"]`);
return marker ? castToSimple(marker) : null;
}
__pushRemoteElement(element, cursorId, insertBefore) {
const marker = this.getMarker(castToBrowser(element, "HTML"), cursorId);
// when insertBefore is not present, we clear the element
if (debugAssert(!marker || marker.parentNode === element, "expected remote element marker's parent node to match remote element"), void 0 === insertBefore) {
for (; null !== element.firstChild && element.firstChild !== marker;) this.remove(element.firstChild);
insertBefore = null;
}
const cursor = new RehydratingCursor(element, null, this.blockDepth);
this[CURSOR_STACK].push(cursor), null === marker ? this.disableRehydration(insertBefore) : this.candidate = this.remove(marker);
const block = new RemoteLiveBlock(element);
return this.pushLiveBlock(block, !0);
}
didAppendBounds(bounds) {
if (super.didAppendBounds(bounds), this.candidate) {
const last = bounds.lastNode();
this.candidate = last && last.nextSibling;
}
return bounds;
}
}
function isOpenBlock(node) {
return node.nodeType === COMMENT_NODE && 0 === node.nodeValue.lastIndexOf("%+b:", 0);
}
function isCloseBlock(node) {
return node.nodeType === COMMENT_NODE && 0 === node.nodeValue.lastIndexOf("%-b:", 0);
}
function getBlockDepth(node) {
return parseInt(node.nodeValue.slice(4), 10);
}
function getBlockDepthWithOffset(node, offset) {
return getBlockDepth(node) - offset;
}
function isElement(node) {
return 1 === node.nodeType;
}
function isMarker(node) {
return 8 === node.nodeType && "%glmr%" === node.nodeValue;
}
function isEmpty$1(node) {
return 8 === node.nodeType && "% %" === node.nodeValue;
}
function findByName(array, name) {
for (const attr of array) if (attr.name === name) return attr;
}
function rehydrationBuilder(env, cursor) {
return RehydrateBuilder.forInitialRender(env, cursor);
}
const glimmerRuntime = /*#__PURE__*/Object.defineProperty({
__proto__: null,
ConcreteBounds,
CurriedValue,
CursorImpl,
DOMChanges,
DOMTreeConstruction,
DynamicAttribute,
DynamicScopeImpl,
EMPTY_ARGS,
EMPTY_NAMED,
EMPTY_POSITIONAL,
EnvironmentImpl,
IDOMChanges: DOMChangesImpl,
LowLevelVM: VM,
NewElementBuilder,
PartialScopeImpl,
RehydrateBuilder,
RemoteLiveBlock,
SERIALIZATION_FIRST_NODE_STRING,
SimpleDynamicAttribute,
TEMPLATE_ONLY_COMPONENT_MANAGER,
TemplateOnlyComponent: TemplateOnlyComponentDefinition,
TemplateOnlyComponentManager,
UpdatableBlockImpl,
UpdatingVM,
array: array$1,
clear,
clientBuilder,
concat: concat$1,
createCapturedArgs,
curry,
destroy,
dynamicAttribute,
fn: fn$1,
get: get$1,
hash: hash$1,
inTransaction,
invokeHelper: invokeHelper$1,
isDestroyed,
isDestroying,
isSerializationFirstNode,
isWhitespace,
normalizeProperty,
on: on$1,
registerDestructor: registerDestructor$1,
rehydrationBuilder,
reifyArgs,
reifyNamed,
reifyPositional,
renderComponent,
renderMain,
renderSync,
resetDebuggerCallback,
runtimeContext,
setDebuggerCallback,
templateOnlyComponent
}, Symbol.toStringTag, { value: 'Module' });
// In normal TypeScript, this modifier is essentially an opaque token that just
// needs to be importable. Declaring it with a unique interface like this,
// however, gives tools like Glint (that *do* have a richer notion of what it
// is) a place to install more detailed type information.
// eslint-disable-next-line @typescript-eslint/no-empty-interface
// SAFETY: at the time of writing, the cast here is from `{}` to `OnModifier`,
// which makes it strictly safer to use outside this module because it is not
// usable as "any non-null item", which is what `{}` means, without loss of any
// information from the type itself.
const on = on$1;
const InputTemplate = templateFactory(
/*
<input
{{!-- for compatibility --}}
id={{this.id}}
class={{this.class}}
...attributes
type={{this.type}}
checked={{this.checked}}
value={{this.value}}
{{on "change" this.change}}
{{on "input" this.input}}
{{on "keyup" this.keyUp}}
{{on "paste" this.valueDidChange}}
{{on "cut" this.valueDidChange}}
/>
*/
{
"id": "4z3DuGQ3",
"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,[32,0],[\"change\",[30,0,[\"change\"]]],null],[4,[32,0],[\"input\",[30,0,[\"input\"]]],null],[4,[32,0],[\"keyup\",[30,0,[\"keyUp\"]]],null],[4,[32,0],[\"paste\",[30,0,[\"valueDidChange\"]]],null],[4,[32,0],[\"cut\",[30,0,[\"valueDidChange\"]]],null],[12],[13]],[\"&attrs\"],false,[]]",
"moduleName": "packages/@ember/-internals/glimmer/lib/templates/input.hbs",
"scope": () => [on],
"isStrictMode": true
});
function NOOP$3() {}
class InternalComponent {
// Override this
static toString() {
return 'internal component';
}
constructor(owner, args, caller) {
this.owner = owner;
this.args = args;
this.caller = caller;
setOwner$1(this, owner);
}
/**
* 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 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 (let name of Object.keys(this.args.named)) {
if (!this.isSupportedArgument(name)) {
this.onUnsupportedArgument(name);
}
}
}
named(name) {
let ref = this.args.named[name];
return ref ? valueForRef(ref) : undefined;
}
positional(index) {
let ref = this.args.positional[index];
return ref ? valueForRef(ref) : undefined;
}
listenerFor(name) {
let listener = this.named(name);
if (listener) {
return listener;
} else {
return NOOP$3;
}
}
isSupportedArgument(_name) {
return false;
}
onUnsupportedArgument(_name) {}
toString() {
return `<${this.constructor}:${guidFor(this)}>`;
}
}
const OPAQUE_CONSTRUCTOR_MAP = new WeakMap();
function opaquify(constructor, template) {
let _opaque = {
// Factory interface
create() {
throw assert$1();
},
toString() {
return constructor.toString();
}
};
let opaque = _opaque;
OPAQUE_CONSTRUCTOR_MAP.set(opaque, constructor);
setInternalComponentManager(INTERNAL_COMPONENT_MANAGER, opaque);
setComponentTemplate(template, opaque);
return opaque;
}
function deopaquify(opaque) {
let constructor = OPAQUE_CONSTRUCTOR_MAP.get(opaque);
return constructor;
}
const CAPABILITIES$2 = {
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$2;
}
create(owner, definition, args, _env, _dynamicScope, caller) {
let ComponentClass = deopaquify(definition);
let instance = new ComponentClass(owner, args.capture(), valueForRef(caller));
untrack(instance['validateArguments'].bind(instance));
return instance;
}
didCreate() {}
didUpdate() {}
didRenderLayout() {}
didUpdateLayout() {}
getDebugName(definition) {
return definition.toString();
}
getSelf(instance) {
return createConstRef(instance);
}
getDestroyable(instance) {
return instance;
}
}
const INTERNAL_COMPONENT_MANAGER = new InternalManager();
var __defProp = Object.defineProperty;
var __export = (target, all) => {
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: true
});
};
// src/runtime.ts
var runtime_exports = {};
__export(runtime_exports, {
c: () => decorateClass,
f: () => decorateFieldV1,
g: () => decorateFieldV2,
i: () => initializeDeferredDecorator,
m: () => decorateMethodV1,
n: () => decorateMethodV2,
p: () => decoratePOJO
});
var deferred = /* @__PURE__ */new WeakMap();
function deferDecorator(proto, prop, desc) {
let map = deferred.get(proto);
if (!map) {
map = /* @__PURE__ */new Map();
deferred.set(proto, map);
}
map.set(prop, desc);
}
function findDeferredDecorator(target, prop) {
let cursor = target.prototype;
while (cursor) {
let desc = deferred.get(cursor)?.get(prop);
if (desc) {
return desc;
}
cursor = cursor.prototype;
}
}
function decorateFieldV1(target, prop, decorators, initializer) {
return decorateFieldV2(target.prototype, prop, decorators, initializer);
}
function decorateFieldV2(prototype, prop, decorators, initializer) {
let desc = {
configurable: true,
enumerable: true,
writable: true,
initializer: null
};
if (initializer) {
desc.initializer = initializer;
}
for (let decorator of decorators) {
desc = decorator(prototype, prop, desc) || desc;
}
if (desc.initializer === void 0) {
Object.defineProperty(prototype, prop, desc);
} else {
deferDecorator(prototype, prop, desc);
}
}
function decorateMethodV1({
prototype
}, prop, decorators) {
return decorateMethodV2(prototype, prop, decorators);
}
function decorateMethodV2(prototype, prop, decorators) {
const origDesc = Object.getOwnPropertyDescriptor(prototype, prop);
let desc = {
...origDesc
};
for (let decorator of decorators) {
desc = decorator(prototype, prop, desc) || desc;
}
if (desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(prototype) : void 0;
desc.initializer = void 0;
}
Object.defineProperty(prototype, prop, desc);
}
function initializeDeferredDecorator(target, prop) {
let desc = findDeferredDecorator(target.constructor, prop);
if (desc) {
Object.defineProperty(target, prop, {
enumerable: desc.enumerable,
configurable: desc.configurable,
writable: desc.writable,
value: desc.initializer ? desc.initializer.call(target) : void 0
});
}
}
function decorateClass(target, decorators) {
return decorators.reduce((accum, decorator) => decorator(accum) || accum, target);
}
function decoratePOJO(pojo, decorated) {
for (let [type, prop, decorators] of decorated) {
if (type === "field") {
decoratePojoField(pojo, prop, decorators);
} else {
decorateMethodV2(pojo, prop, decorators);
}
}
return pojo;
}
function decoratePojoField(pojo, prop, decorators) {
let desc = {
configurable: true,
enumerable: true,
writable: true,
initializer: () => Object.getOwnPropertyDescriptor(pojo, prop)?.value
};
for (let decorator of decorators) {
desc = decorator(pojo, prop, desc) || desc;
}
if (desc.initializer) {
desc.value = desc.initializer.call(pojo);
delete desc.initializer;
}
Object.defineProperty(pojo, prop, desc);
}
const UNINITIALIZED = Object.freeze({});
function elementForEvent(event) {
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 (isConstRef(reference)) {
return new LocalValue(valueForRef(reference));
} else if (isUpdatableRef(reference)) {
return new UpstreamValue(reference);
} else {
return new ForkedValue(reference);
}
}
class LocalValue {
static {
decorateFieldV2(this.prototype, "value", [tracked]);
}
#value = (initializeDeferredDecorator(this, "value"), void 0);
constructor(value) {
this.value = value;
}
get() {
return this.value;
}
set(value) {
this.value = value;
}
}
class UpstreamValue {
constructor(reference) {
this.reference = reference;
}
get() {
return valueForRef(this.reference);
}
set(value) {
updateRef(this.reference, value);
}
}
class ForkedValue {
local;
upstream;
lastUpstreamValue = UNINITIALIZED;
constructor(reference) {
this.upstream = new UpstreamValue(reference);
}
get() {
let upstreamValue = this.upstream.get();
if (upstreamValue !== this.lastUpstreamValue) {
this.lastUpstreamValue = upstreamValue;
this.local = new LocalValue(upstreamValue);
}
return this.local.get();
}
set(value) {
this.local.set(value);
}
}
class AbstractInput extends InternalComponent {
validateArguments() {
super.validateArguments();
}
_value = valueFrom(this.args.named['value']);
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 */
static {
decorateMethodV2(this.prototype, "valueDidChange", [action$1]);
}
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;
}
}
static {
decorateMethodV2(this.prototype, "keyUp", [action$1]);
}
listenerFor(name) {
let listener = super.listenerFor(name);
if (this.isVirtualEventListener(name, listener)) {
return devirtualize(listener);
} else {
return listener;
}
}
isVirtualEventListener(name, _listener) {
let virtualEvents = ['enter', 'insert-newline', 'escape-press'];
return virtualEvents.indexOf(name) !== -1;
}
}
/**
@module @ember/component
*/
let isValidInputType;
if (hasDOM) {
const INPUT_TYPES = Object.create(null);
const INPUT_ELEMENT = document.createElement('input');
INPUT_TYPES[''] = false;
INPUT_TYPES['text'] = true;
INPUT_TYPES['checkbox'] = true;
isValidInputType = type => {
let 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.
### 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.
@method Input
@for Ember.Templates.components
@param {Hash} options
@public
*/
class _Input extends AbstractInput {
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() {
let type = this.named('type');
if (type === null || type === undefined) {
return 'text';
}
return isValidInputType(type) ? type : 'text';
}
get isCheckbox() {
return this.named('type') === 'checkbox';
}
_checked = valueFrom(this.args.named['checked']);
get checked() {
if (this.isCheckbox) {
return this._checked.get();
} else {
return undefined;
}
}
set checked(checked) {
this._checked.set(checked);
}
change(event) {
if (this.isCheckbox) {
this.checkedDidChange(event);
} else {
super.change(event);
}
}
static {
decorateMethodV2(this.prototype, "change", [action$1]);
}
input(event) {
if (!this.isCheckbox) {
super.input(event);
}
}
static {
decorateMethodV2(this.prototype, "input", [action$1]);
}
checkedDidChange(event) {
let element = event.target;
this.checked = element.checked;
}
static {
decorateMethodV2(this.prototype, "checkedDidChange", [action$1]);
}
isSupportedArgument(name) {
let supportedArguments = ['type', 'value', 'checked', 'enter', 'insert-newline', 'escape-press'];
return supportedArguments.indexOf(name) !== -1 || super.isSupportedArgument(name);
}
}
const Input = opaquify(_Input, InputTemplate);
/**
@module ember
*/
function isSimpleClick(event) {
if (!(event instanceof MouseEvent)) {
return false;
}
let modifier = event.shiftKey || event.metaKey || event.altKey || event.ctrlKey;
let 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) {
let registry = owner.lookup('-view-registry:main');
let rootViews = [];
Object.keys(registry).forEach(id => {
let 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 guidFor(view);
}
}
const ELEMENT_VIEW = new WeakMap();
const 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);
}
const CHILD_VIEW_IDS = new WeakMap();
/**
@private
@method getChildViews
@param {Ember.View} view
*/
function getChildViews(view) {
let owner = getOwner$2(view);
let registry = owner.lookup('-view-registry:main');
return collectChildViews(view, registry);
}
function initChildViews(view) {
let childViews = new Set();
CHILD_VIEW_IDS.set(view, childViews);
return childViews;
}
function addChildView(parent, child) {
let childViews = CHILD_VIEW_IDS.get(parent);
if (childViews === undefined) {
childViews = initChildViews(parent);
}
childViews.add(getViewId(child));
}
function collectChildViews(view, registry) {
let views = [];
let childViews = CHILD_VIEW_IDS.get(view);
if (childViews !== undefined) {
childViews.forEach(id => {
let 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) {
let bounds = getViewBounds(view);
let 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) {
let 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) {
let range = getViewRange(view);
return range.getBoundingClientRect();
}
/**
Determines if the element matches the specified selector.
@private
@method matches
@param {DOMElement} el
@param {String} selector
*/
const elMatches = typeof Element !== 'undefined' ? Element.prototype.matches : undefined;
function matches(el, selector) {
return elMatches.call(el, selector);
}
function contains(a, b) {
if (a.contains !== undefined) {
return a.contains(b);
}
let current = b.parentNode;
while (current && (current = current.parentNode)) {
if (current === a) {
return true;
}
}
return false;
}
const emberinternalsViewsLibSystemUtils = /*#__PURE__*/Object.defineProperty({
__proto__: null,
addChildView,
clearElementView,
clearViewElement,
collectChildViews,
constructStyleDeprecationMessage,
contains,
elMatches,
getChildViews,
getElementView,
getRootViews,
getViewBoundingClientRect,
getViewBounds,
getViewClientRects,
getViewElement,
getViewId,
getViewRange,
initChildViews,
isSimpleClick,
matches,
setElementView,
setViewElement
}, Symbol.toStringTag, { value: 'Module' });
/**
@module ember
*/
function ActionManager() {}
/**
Global action id hash.
@private
@property registeredActions
@type Object
*/
ActionManager.registeredActions = {};
const emberinternalsViewsLibSystemActionManager = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: ActionManager
}, Symbol.toStringTag, { value: 'Module' });
/**
@module ember
*/
const ROOT_ELEMENT_CLASS = 'ember-application';
/**
`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 EmberObject
*/
class EventDispatcher extends EmberObject {
/**
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';
_eventHandlers = Object.create(null);
_didSetup = false;
finalEventNameMapping = null;
_sanitizedRootElement = null;
lazyEvents = new Map();
_reverseEventNameMapping = null;
/**
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) {
let events = this.finalEventNameMapping = {
...get$2(this, 'events'),
...addedEvents
};
this._reverseEventNameMapping = Object.keys(events).reduce((result, key) => {
let eventName = events[key];
return eventName ? {
...result,
[eventName]: key
} : result;
}, {});
let lazyEvents = this.lazyEvents;
if (_rootElement !== undefined && _rootElement !== null) {
set(this, 'rootElement', _rootElement);
}
let specifiedRootElement = get$2(this, 'rootElement');
let rootElement = typeof specifiedRootElement !== 'string' ? specifiedRootElement : document.querySelector(specifiedRootElement);
rootElement.classList.add(ROOT_ELEMENT_CLASS);
this._sanitizedRootElement = rootElement;
// setup event listeners for the non-lazily setup events
for (let event in events) {
if (Object.prototype.hasOwnProperty.call(events, event)) {
lazyEvents.set(event, events[event] ?? null);
}
}
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] ?? null);
}
/**
Setup event listeners for the given Ember event name (camel case)
@private
@method setupHandlerForEmberEvent
@param eventName
*/
setupHandlerForEmberEvent(eventName) {
let event = this._reverseEventNameMapping?.[eventName];
if (event) {
this.setupHandler(this._sanitizedRootElement, event, 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
}
let viewHandler = (target, event) => {
let view = getElementView(target);
let result = true;
if (view) {
// SAFETY: As currently written, this is not safe. Though it seems to always be true.
result = view.handleEvent(eventName, event);
}
return result;
};
let actionHandler = (target, event) => {
let actionId = target.getAttribute('data-ember-action');
let actions;
// 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 === '') {
actions = [];
for (let attr of target.attributes) {
let attrName = attr.name;
if (attrName.indexOf('data-ember-action-') === 0) {
let action = ActionManager.registeredActions[attr.value];
actions.push(action);
}
}
} else if (actionId) {
// FIXME: This branch is never called in tests. Improve tests or remove
let actionState = ActionManager.registeredActions[actionId];
if (actionState) {
actions = [actionState];
}
}
// 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) {
// FIXME: This branch is never called in tests. Improve tests or remove
return;
}
let result = true;
for (let index = 0; index < actions.length; index++) {
let 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;
};
let handleEvent = this._eventHandlers[event] = event => {
let target = event.target;
do {
if (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 instanceof Element);
};
rootElement.addEventListener(event, handleEvent);
this.lazyEvents.delete(event);
}
destroy() {
if (this._didSetup === false) {
return;
}
let rootElement = this._sanitizedRootElement;
if (!rootElement) {
return;
}
for (let event in this._eventHandlers) {
rootElement.removeEventListener(event, this._eventHandlers[event]);
}
rootElement.classList.remove(ROOT_ELEMENT_CLASS);
return this._super(...arguments);
}
toString() {
return '(EventDispatcher)';
}
}
const emberinternalsViewsLibSystemEventDispatcher = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: EventDispatcher
}, Symbol.toStringTag, { value: 'Module' });
const ComponentLookup = EmberObject.extend({
componentFor(name, owner) {
let fullName = `component:${name}`;
return owner.factoryFor(fullName);
},
layoutFor(name, owner, options) {
let templateFullName = `template:components/${name}`;
return owner.lookup(templateFullName, options);
}
});
const emberinternalsViewsLibComponentLookup = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: ComponentLookup
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/object/evented
*/
/**
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
*/
const Evented = Mixin.create({
on(name, target, method) {
addListener(this, name, target, method);
return this;
},
one(name, target, method) {
addListener(this, name, target, method, true);
return this;
},
trigger(name, ...args) {
sendEvent(this, name, args);
},
off(name, target, method) {
removeListener(this, name, target, method);
return this;
},
has(name) {
return hasListeners(this, name);
}
});
const emberObjectEvented = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: Evented,
on: on$3
}, Symbol.toStringTag, { value: 'Module' });
// Here we have runtime shenanigans to add debug-only errors to the class in dev
// builds. Those runtime shenanigans produce the need for type-level shenanigans
// to match: if we just assign without an explicit type annotation on the `let`
// binding below for `FrameworkObject`, TS gets stuck because this creates
// `FrameworkObject` with a class expression (rather than the usual class
// declaration form). That in turn means TS needs to be able to fully name the
// type produced by the class expression, which includes the `OWNER` symbol from
// `@glimmer/owner`.
//
// By explicitly giving the declaration a type when assigning it the class
// expression, instead of relying on inference, TS no longer needs to name the
// `OWNER` property key from the super class, eliminating the private name
// shenanigans.
// eslint-disable-next-line @typescript-eslint/no-empty-interface
let FrameworkObject = class FrameworkObject extends EmberObject {};
const emberObjectinternals = /*#__PURE__*/Object.defineProperty({
__proto__: null,
FrameworkObject,
cacheFor: getCachedValueFor,
guidFor
}, Symbol.toStringTag, { value: 'Module' });
/* 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
*/
let subscribers = [];
let cache = {};
function populateListeners(name) {
let listeners = [];
for (let subscriber of subscribers) {
if (subscriber.regex.test(name)) {
listeners.push(subscriber.object);
}
}
cache[name] = listeners;
return listeners;
}
const time = (() => {
let perf = 'undefined' !== typeof window ? window.performance || {} : {};
let fn = perf.now || perf.mozNow || perf.webkitNow || perf.msNow || perf.oNow;
return fn ? fn.bind(perf) : Date.now;
})();
function isCallback$1(value) {
return typeof value === 'function';
}
/**
Notifies event's subscribers, calls `before` and `after` hooks.
@method instrument
@for @ember/instrumentation
@static
@param {String} [name] Namespaced event name.
@param {Object} payload
@param {Function} callback Function that you're instrumenting.
@param {Object} binding Context that instrument function is called with.
@private
*/
function instrument(name, p1, p2, p3) {
let _payload;
let callback;
let binding;
if (arguments.length <= 3 && isCallback$1(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
let payload = _payload || {};
let finalizer = _instrumentStart(name, () => payload);
if (finalizer === NOOP$2) {
return callback.call(binding);
} else {
return withFinalizer(callback, finalizer, payload, binding);
}
}
function flaggedInstrument(_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$2() {}
// private for now
function _instrumentStart(name, payloadFunc, payloadArg) {
if (subscribers.length === 0) {
return NOOP$2;
}
let listeners = cache[name];
if (!listeners) {
listeners = populateListeners(name);
}
if (listeners.length === 0) {
return NOOP$2;
}
let payload = payloadFunc(payloadArg);
let STRUCTURED_PROFILE = ENV.STRUCTURED_PROFILE;
let timeName;
if (STRUCTURED_PROFILE) {
timeName = `${name}: ${payload.object}`;
console.time(timeName);
}
let beforeValues = [];
let timestamp = time();
for (let listener of listeners) {
beforeValues.push(listener.before(name, timestamp, payload));
}
const constListeners = listeners;
return function _instrumentEnd() {
let timestamp = time();
for (let i = 0; i < constListeners.length; i++) {
let listener = constListeners[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) {
let paths = pattern.split('.');
let regexes = [];
for (let path of paths) {
if (path === '*') {
regexes.push('[^\\.]*');
} else {
regexes.push(path);
}
}
let regex = regexes.join('\\.');
regex = `${regex}(\\..*)?`;
let 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) {
let index = 0;
for (let 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 = {};
}
const emberInstrumentationIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
_instrumentStart,
flaggedInstrument,
instrument,
reset,
subscribe,
subscribers,
unsubscribe
}, Symbol.toStringTag, { value: 'Module' });
const DEFAULT = Object.freeze({
// appendChild is only legal while rendering the buffer.
appendChild() {
throw new Error("You can't use appendChild outside of the rendering process");
},
// Handle events from `Ember.EventDispatcher`
handleEvent() {
return true; // continue event propagation
},
rerender() {},
destroy() {}
});
const PRE_RENDER = Object.freeze({
...DEFAULT
});
const HAS_ELEMENT = Object.freeze({
...DEFAULT,
rerender(view) {
view.renderer.rerender();
},
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 flaggedInstrument(`interaction.${eventName}`, {
event,
view
}, () => {
return join(view, view.trigger, eventName, event);
});
} else {
return true; // continue event propagation
}
}
});
const IN_DOM = Object.freeze({
...HAS_ELEMENT,
enter(view) {
// Register the view for event handling. This hash is used by
// Ember.EventDispatcher to dispatch incoming events.
view.renderer.register(view);
}
});
const DESTROYING = Object.freeze({
...DEFAULT,
appendChild() {
throw new Error("You can't call appendChild on a view being destroyed");
},
rerender() {
throw new Error("You can't call rerender on a view being destroyed");
}
});
/*
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.
*/
const states = Object.freeze({
preRender: PRE_RENDER,
inDOM: IN_DOM,
hasElement: HAS_ELEMENT,
destroying: DESTROYING
});
const emberinternalsViewsLibViewsStates = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: states
}, Symbol.toStringTag, { value: 'Module' });
class CoreView extends FrameworkObject.extend(Evented, ActionHandler) {
isView = true;
_superTrigger;
_superHas;
/**
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
*/
init(properties) {
super.init(properties);
// Handle methods from Evented
// The native class inheritance will not work for mixins. To work around this,
// we copy the existing trigger and has methods provided by the mixin and swap in the
// new ones from our class.
this._superTrigger = this.trigger;
this.trigger = this._trigger;
this._superHas = this.has;
this.has = this._has;
this.parentView ??= null;
this._state = 'preRender';
this._currentState = this._states.preRender;
}
static {
decorateFieldV2(this.prototype, "renderer", [inject$2('renderer', '-dom')]);
}
#renderer = (initializeDeferredDecorator(this, "renderer"), void 0);
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
*/
// Changed to `trigger` on init
_trigger(name, ...args) {
this._superTrigger(name, ...args);
let method = this[name];
if (typeof method === 'function') {
return method.apply(this, args);
}
}
// Changed to `has` on init
_has(name) {
return typeof this[name] === 'function' || this._superHas(name);
}
static isViewFactory = true;
}
// Declare on the prototype to have a single shared value.
CoreView.prototype._states = states;
const emberinternalsViewsLibViewsCoreView = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: CoreView
}, Symbol.toStringTag, { value: 'Module' });
/**
@module ember
*/
const EMPTY_ARRAY$2 = Object.freeze([]);
/**
@class ClassNamesSupport
@namespace Ember
@private
*/
const ClassNamesSupport = Mixin.create({
concatenatedProperties: ['classNames', 'classNameBindings'],
init() {
this._super(...arguments);
},
/**
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$2,
/**
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$2
});
const emberinternalsViewsLibMixinsClassNamesSupport = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: ClassNamesSupport
}, Symbol.toStringTag, { value: 'Module' });
/**
@module ember
*/
const ChildViewsSupport = Mixin.create({
/**
Array of child views. You should never edit this array directly.
@property childViews
@type Array
@default []
@private
*/
childViews: nativeDescDecorator({
configurable: false,
enumerable: false,
get() {
return getChildViews(this);
}
}),
appendChild(view) {
addChildView(this, view);
}
});
const emberinternalsViewsLibMixinsChildViewsSupport = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: ChildViewsSupport
}, Symbol.toStringTag, { value: 'Module' });
/**
@module ember
*/
const ViewStateSupport = Mixin.create({
_transitionTo(state) {
let priorState = this._currentState;
let currentState = this._currentState = this._states[state];
this._state = state;
if (priorState && priorState.exit) {
priorState.exit(this);
}
if (currentState.enter) {
currentState.enter(this);
}
}
});
const emberinternalsViewsLibMixinsViewStateSupport = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: ViewStateSupport
}, Symbol.toStringTag, { value: 'Module' });
function K$1() {
return this;
}
/**
@class ViewMixin
@namespace Ember
@private
*/
const ViewMixin = Mixin.create({
/**
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) {
let view = this.parentView;
let isOfType = klass instanceof Mixin ? view => klass.detect(view) : view => klass.detect(view.constructor);
while (view) {
if (isOfType(view)) {
return view;
}
view = view.parentView;
}
return;
},
/**
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) {
let 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: 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) {
let target;
if (hasDOM) {
target = typeof selector === 'string' ? document.querySelector(selector) : selector;
} else {
target = selector;
}
// SAFETY: SimpleElement is supposed to be a subset of Element so this _should_ be safe.
// However, the types are more specific in some places which necessitates the `as`.
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$1,
/**
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$1,
/**
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$1,
/**
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$1,
/**
Called after the element of the view is destroyed.
@event willDestroyElement
@public
*/
didDestroyElement: K$1,
/**
Called when the parentView property has changed.
@event parentViewDidChange
@private
*/
parentViewDidChange: K$1,
// ..........................................................
// 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);
if (!this.elementId && this.tagName !== '') {
this.elementId = guidFor(this);
}
},
// .......................................................
// 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);
}
});
const emberinternalsViewsLibMixinsViewSupport = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: ViewMixin
}, Symbol.toStringTag, { value: 'Module' });
/**
@module ember
*/
/**
@class ActionSupport
@namespace Ember
@private
*/
const ActionSupport = Mixin.create({
send(actionName, ...args) {
let action = this.actions && this.actions[actionName];
if (action) {
let shouldBubble = action.apply(this, args) === true;
if (!shouldBubble) {
return;
}
}
let target = get$2(this, 'target');
if (target) {
target.send(...arguments);
}
}
});
const emberinternalsViewsLibMixinsActionSupport = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: ActionSupport
}, Symbol.toStringTag, { value: 'Module' });
const MUTABLE_CELL = Symbol('MUTABLE_CELL');
const emberinternalsViewsLibCompatAttrs = /*#__PURE__*/Object.defineProperty({
__proto__: null,
MUTABLE_CELL
}, Symbol.toStringTag, { value: 'Module' });
const emberinternalsViewsIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
ActionManager,
ActionSupport,
ChildViewsSupport,
ClassNamesSupport,
ComponentLookup,
CoreView,
EventDispatcher,
MUTABLE_CELL,
ViewMixin,
ViewStateSupport,
addChildView,
clearElementView,
clearViewElement,
constructStyleDeprecationMessage,
getChildViews,
getElementView,
getRootViews,
getViewBoundingClientRect,
getViewBounds,
getViewClientRects,
getViewElement,
getViewId,
isSimpleClick,
setElementView,
setViewElement
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/engine
*/
const ENGINE_PARENT = 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;
}
const emberEngineLibEngineParent = /*#__PURE__*/Object.defineProperty({
__proto__: null,
ENGINE_PARENT,
getEngineParent,
setEngineParent
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/service
@public
*/
/**
@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$1(...args) {
return inject$2('service', ...args);
}
/**
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 { 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 { 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 service
@static
@since 4.1.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 service(...args) {
return inject$2('service', ...args);
}
/**
@class Service
@extends EmberObject
@since 1.10.0
@public
*/
class Service extends FrameworkObject {
static isServiceFactory = true;
}
/**
A type registry for Ember `Service`s. Meant to be declaration-merged so string
lookups resolve to the correct type.
Blueprints should include such a declaration merge for TypeScript:
```ts
import Service from '@ember/service';
export default class ExampleService extends Service {
// ...
}
declare module '@ember/service' {
export interface Registry {
example: ExampleService;
}
}
```
Then `@service` can check that the service is registered correctly, and APIs
like `owner.lookup('service:example')` can return `ExampleService`.
*/
// NOTE: this cannot be `Record<string, Service | undefined>`, convenient as
// that would be for end users, because there is no actual contract to that
// effect with Ember -- and in the future this choice would allow us to have
// registered services which have no base class.
// eslint-disable-next-line @typescript-eslint/no-empty-interface
const emberServiceIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: Service,
inject: inject$1,
service
}, Symbol.toStringTag, { value: 'Module' });
const LinkToTemplate = templateFactory(
/*
<a
{{!-- for compatibility --}}
id={{this.id}}
class={{this.class}}
{{!-- deprecated attribute bindings --}}
role={{this.role}}
title={{this.title}}
rel={{this.rel}}
tabindex={{this.tabindex}}
target={{this.target}}
...attributes
href={{this.href}}
{{on 'click' this.click}}
>{{yield}}</a>
*/
{
"id": "Ub0nir+H",
"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,[32,0],[\"click\",[30,0,[\"click\"]]],null],[12],[18,2,null],[13]],[\"&attrs\",\"&default\"],false,[\"yield\"]]",
"moduleName": "packages/@ember/-internals/glimmer/lib/templates/link-to.hbs",
"scope": () => [on],
"isStrictMode": true
});
const EMPTY_ARRAY$1 = [];
const EMPTY_QUERY_PARAMS = {};
function isMissing(value) {
return value === null || value === undefined;
}
function isPresent$1(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 {
static toString() {
return 'LinkTo';
}
static {
decorateFieldV2(this.prototype, "routing", [service('-routing')]);
}
#routing = (initializeDeferredDecorator(this, "routing"), void 0);
validateArguments() {
super.validateArguments();
}
get class() {
let 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 '#';
}
let {
routing,
route,
models,
query
} = this;
// TODO: can we narrow this down to QP changes only?
consumeTag(tagFor(routing, 'currentState'));
{
return routing.generateURL(route, models, query);
}
}
click(event) {
if (!isSimpleClick(event)) {
return;
}
let element = event.currentTarget;
let isSelf = element.target === '' || element.target === '_self';
if (isSelf) {
this.preventDefault(event);
} else {
return;
}
if (this.isDisabled) {
return;
}
if (this.isLoading) {
return;
}
let {
routing,
route,
models,
query,
replace
} = this;
let payload = {
routeName: route,
queryParams: query,
transition: undefined
};
flaggedInstrument('interaction.link-to', payload, () => {
payload.transition = routing.transitionTo(route, models, query, replace);
});
}
static {
decorateMethodV2(this.prototype, "click", [action$1]);
}
get route() {
if ('route' in this.args.named) {
let route = this.named('route');
return route && this.namespaceRoute(route);
} else {
return this.currentRoute;
}
}
// GH #17963
currentRouteCache = createCache(() => {
consumeTag(tagFor(this.routing, 'currentState'));
return untrack(() => this.routing.currentRouteName);
});
get currentRoute() {
return getValue(this.currentRouteCache);
}
// TODO: not sure why generateURL takes {}[] instead of unknown[]
get models() {
if ('models' in this.args.named) {
let models = this.named('models');
return models;
} else if ('model' in this.args.named) {
return [this.named('model')];
} else {
return EMPTY_ARRAY$1;
}
}
get query() {
if ('query' in this.args.named) {
let query = this.named('query');
return {
...query
};
} else {
return EMPTY_QUERY_PARAMS;
}
}
get replace() {
return this.named('replace') === true;
}
get isActive() {
return this.isActiveForState(this.routing.currentState);
}
get willBeActive() {
let current = this.routing.currentState;
let 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() {
let owner = this.owner;
return getEngineParent(owner) !== undefined;
}
get engineMountPoint() {
let owner = this.owner;
return owner.mountPoint;
}
classFor(state) {
let className = this.named(`${state}Class`);
if (className === true || isMissing(className)) {
return ` ${state}`;
} else if (className) {
return ` ${className}`;
} else {
return '';
}
}
namespaceRoute(route) {
let {
engineMountPoint
} = this;
if (engineMountPoint === undefined) {
return route;
} else if (route === 'application') {
return engineMountPoint;
} else {
return `${engineMountPoint}.${route}`;
}
}
isActiveForState(state) {
if (!isPresent$1(state)) {
return false;
}
if (this.isLoading) {
return false;
}
let currentWhen = this.named('current-when');
if (typeof currentWhen === 'boolean') {
return currentWhen;
} else if (typeof currentWhen === 'string') {
let {
models,
routing
} = this;
return currentWhen.split(' ').some(route => routing.isActiveForRoute(models, undefined, this.namespaceRoute(route), state));
} else {
let {
route,
models,
query,
routing
} = this;
return routing.isActiveForRoute(models, query, route, state);
}
}
preventDefault(event) {
event.preventDefault();
}
isSupportedArgument(name) {
let supportedArguments = ['route', 'model', 'models', 'query', 'replace', 'disabled', 'current-when', 'activeClass', 'loadingClass', 'disabledClass'];
return supportedArguments.indexOf(name) !== -1 || super.isSupportedArgument(name);
}
}
let {
prototype
} = _LinkTo;
let descriptorFor = (target, property) => {
if (target) {
return Object.getOwnPropertyDescriptor(target, property) || descriptorFor(Object.getPrototypeOf(target), property);
} else {
return null;
}
};
// @href
{
let superOnUnsupportedArgument = prototype['onUnsupportedArgument'];
Object.defineProperty(prototype, 'onUnsupportedArgument', {
configurable: true,
enumerable: false,
value: function onUnsupportedArgument(name) {
if (name === 'href') ; else {
superOnUnsupportedArgument.call(this, name);
}
}
});
}
// QP
{
let superModelsDescriptor = descriptorFor(prototype, 'models');
let superModelsGetter = superModelsDescriptor.get;
Object.defineProperty(prototype, 'models', {
configurable: true,
enumerable: false,
get: function models() {
let 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;
}
});
let superQueryDescriptor = descriptorFor(prototype, 'query');
let superQueryGetter = superQueryDescriptor.get;
Object.defineProperty(prototype, 'query', {
configurable: true,
enumerable: false,
get: function query() {
if ('query' in this.args.named) {
let qp = superQueryGetter.call(this);
if (isQueryParams(qp)) {
return qp.values ?? EMPTY_QUERY_PARAMS;
} else {
return qp;
}
} else {
let models = superModelsGetter.call(this);
if (models.length > 0) {
let qp = models[models.length - 1];
if (isQueryParams(qp) && qp.values !== null) {
return qp.values;
}
}
return EMPTY_QUERY_PARAMS;
}
}
});
}
// Positional Arguments
{
let superOnUnsupportedArgument = prototype['onUnsupportedArgument'];
Object.defineProperty(prototype, 'onUnsupportedArgument', {
configurable: true,
enumerable: false,
value: function onUnsupportedArgument(name) {
if (name !== 'params') {
superOnUnsupportedArgument.call(this, name);
}
}
});
}
const LinkTo = opaquify(_LinkTo, LinkToTemplate);
const TextareaTemplate = templateFactory(
/*
<textarea
{{!-- for compatibility --}}
id={{this.id}}
class={{this.class}}
...attributes
value={{this.value}}
{{on "change" this.change}}
{{on "input" this.input}}
{{on "keyup" this.keyUp}}
{{on "paste" this.valueDidChange}}
{{on "cut" this.valueDidChange}}
/>
*/
{
"id": "112WKCh2",
"block": "[[[11,\"textarea\"],[16,1,[30,0,[\"id\"]]],[16,0,[30,0,[\"class\"]]],[17,1],[16,2,[30,0,[\"value\"]]],[4,[32,0],[\"change\",[30,0,[\"change\"]]],null],[4,[32,0],[\"input\",[30,0,[\"input\"]]],null],[4,[32,0],[\"keyup\",[30,0,[\"keyUp\"]]],null],[4,[32,0],[\"paste\",[30,0,[\"valueDidChange\"]]],null],[4,[32,0],[\"cut\",[30,0,[\"valueDidChange\"]]],null],[12],[13]],[\"&attrs\"],false,[]]",
"moduleName": "packages/@ember/-internals/glimmer/lib/templates/textarea.hbs",
"scope": () => [on],
"isStrictMode": true
});
/**
@module @ember/component
*/
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);
}
static {
decorateMethodV2(this.prototype, "change", [action$1]);
}
input(event) {
super.input(event);
}
static {
decorateMethodV2(this.prototype, "input", [action$1]);
}
isSupportedArgument(name) {
let supportedArguments = ['type', 'value', 'enter', 'insert-newline', 'escape-press'];
return supportedArguments.indexOf(name) !== -1 || super.isSupportedArgument(name);
}
}
const Textarea = opaquify(_Textarea, TextareaTemplate);
function isTemplateFactory(template) {
return typeof template === 'function';
}
function referenceForParts(rootRef, parts) {
let isAttrs = parts[0] === 'attrs';
// TODO deprecate this
if (isAttrs) {
parts.shift();
if (parts.length === 1) {
return childRefFor(rootRef, parts[0]);
}
}
return childRefFromParts(rootRef, parts);
}
function parseAttributeBinding(microsyntax) {
let colonIndex = microsyntax.indexOf(':');
if (colonIndex === -1) {
return [microsyntax, microsyntax, true];
} else {
let prop = microsyntax.substring(0, colonIndex);
let attribute = microsyntax.substring(colonIndex + 1);
return [prop, attribute, false];
}
}
function installAttributeBinding(component, rootRef, parsed, operations) {
let [prop, attribute, isSimple] = parsed;
if (attribute === 'id') {
// SAFETY: `get` could not infer the type of `prop` and just gave us `unknown`.
// we may want to throw an error in the future if the value isn't string or null/undefined.
let elementId = get$2(component, prop);
if (elementId === undefined || elementId === null) {
elementId = component.elementId;
}
let elementIdRef = createPrimitiveRef(elementId);
operations.setAttribute('id', elementIdRef, true, null);
return;
}
let isPath = prop.indexOf('.') > -1;
let reference = isPath ? referenceForParts(rootRef, prop.split('.')) : childRefFor(rootRef, prop);
operations.setAttribute(attribute, reference, false, null);
}
function createClassNameBindingRef(rootRef, microsyntax, operations) {
let parts = microsyntax.split(':');
let [prop, truthy, falsy] = parts;
let isStatic = prop === '';
if (isStatic) {
operations.setAttribute('class', createPrimitiveRef(truthy), true, null);
} else {
let isPath = prop.indexOf('.') > -1;
let parts = isPath ? prop.split('.') : [];
let value = isPath ? referenceForParts(rootRef, parts) : childRefFor(rootRef, prop);
let 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) {
let dasherizedPath;
return createComputeRef(() => {
let value = valueForRef(inner);
if (value === true) {
return dasherizedPath || (dasherizedPath = dasherize(path));
} else if (value || value === 0) {
return String(value);
} else {
return null;
}
});
}
function createColonClassNameBindingRef(inner, truthy, falsy) {
return createComputeRef(() => {
return valueForRef(inner) ? truthy : falsy;
});
}
function NOOP$1() {}
/**
@module ember
*/
/**
Represents the internal state of the component.
@class ComponentStateBucket
@private
*/
class ComponentStateBucket {
classRef = null;
rootRef;
argsRevision;
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.argsRevision = args === null ? 0 : valueForTag(argsTag);
this.rootRef = createConstRef(component);
registerDestructor$1(this, () => this.willDestroy(), true);
registerDestructor$1(this, () => this.component.destroy());
}
willDestroy() {
let {
component,
isInteractive
} = this;
if (isInteractive) {
beginUntrackFrame();
component.trigger('willDestroyElement');
component.trigger('willClearRender');
endUntrackFrame();
let element = getViewElement(component);
if (element) {
clearElementView(element);
clearViewElement(component);
}
}
component.renderer.unregister(component);
}
finalize() {
let {
finalizer
} = this;
finalizer();
this.finalizer = NOOP$1;
}
}
function internalHelper(helper) {
return setInternalHelperManager(helper, {});
}
/**
@module ember
*/
const ACTIONS = new 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 { service } from '@ember/service';
export default class extends Controller {
@service someService;
}
```
@method action
@deprecated
@for Ember.Templates.helpers
@public
*/
const action = internalHelper(args => {
deprecateUntil(`Usage of the \`(action)\` helper is deprecated. Migrate to native functions and function invocation.`, DEPRECATIONS.DEPRECATE_TEMPLATE_ACTION);
let {
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.
let [context, action, ...restArgs] = positional;
action.debugLabel;
let target = 'target' in named ? named['target'] : context;
let processArgs = makeArgsProcessor('value' in named && named['value'] || false, restArgs);
let fn;
if (isInvokableRef(action)) {
fn = makeClosureAction(action, action, invokeRef, processArgs);
} else {
fn = makeDynamicClosureAction(valueForRef(context),
// SAFETY: glimmer-vm should expose narrowing utilities for references
// as is, `target` is still `Reference<unknown>`.
// however, we never even tried to narrow `target`, so this is potentially risky code.
target,
// SAFETY: glimmer-vm should expose narrowing utilities for references
// as is, `action` is still `Reference<unknown>`
action, processArgs);
}
ACTIONS.add(fn);
return createUnboundRef(fn);
});
function NOOP(args) {
return args;
}
function makeArgsProcessor(valuePathRef, actionArgsRef) {
let mergeArgs;
if (actionArgsRef.length > 0) {
mergeArgs = args => {
return actionArgsRef.map(valueForRef).concat(args);
};
}
let readValue;
if (valuePathRef) {
readValue = args => {
let valuePath = valueForRef(valuePathRef);
if (valuePath && args.length > 0) {
args[0] = get$2(args[0], valuePath);
}
return args;
};
}
if (mergeArgs && readValue) {
return args => {
return readValue(mergeArgs(args));
};
} else {
return mergeArgs || readValue || NOOP;
}
}
function makeDynamicClosureAction(context, targetRef, actionRef, processArgs, debugKey) {
const action = valueForRef(actionRef);
return (...args) => {
return makeClosureAction(context, valueForRef(targetRef), action, processArgs)(...args);
};
}
function makeClosureAction(context, target, action, processArgs, debugKey) {
let self;
let fn;
if (typeof action === 'string') {
self = target;
let value = target.actions?.[action];
fn = value;
} else if (typeof action === 'function') {
self = context;
fn = action;
} else ;
return (...args) => {
let payload = {
target: self,
args,
label: '@glimmer/closure-action'
};
return flaggedInstrument('interaction.ember-action', payload, () => {
return join(self, fn, ...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) {
updateRef(this, value);
}
// ComponentArgs takes EvaluatedNamedArgs and converts them into the
// inputs needed by CurlyComponents (attrs and props, with mutable
// cells, etc).
function processComponentArgs(namedArgs) {
let attrs = Object.create(null);
let props = Object.create(null);
for (let name in namedArgs) {
let ref = namedArgs[name];
let value = valueForRef(ref);
let isAction = typeof value === 'function' && ACTIONS.has(value);
if (isUpdatableRef(ref) && !isAction) {
attrs[name] = new MutableCell(ref, value);
} else {
attrs[name] = value;
}
props[name] = value;
}
props.attrs = attrs;
return props;
}
const REF = Symbol('REF');
class MutableCell {
value;
[MUTABLE_CELL];
[REF];
constructor(ref, value) {
this[MUTABLE_CELL] = true;
this[REF] = ref;
this.value = value;
}
update(val) {
updateRef(this[REF], val);
}
}
const ARGS = enumerableSymbol('ARGS');
const HAS_BLOCK = enumerableSymbol('HAS_BLOCK');
const DIRTY_TAG = Symbol('DIRTY_TAG');
const IS_DISPATCHING_ATTRS = Symbol('IS_DISPATCHING_ATTRS');
const BOUNDS = Symbol('BOUNDS');
const EMBER_VIEW_REF = createPrimitiveRef('ember-view');
function aliasIdToElementId(args, props) {
if (args.named.has('id')) {
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) {
let seen = [];
let i = attributeBindings.length - 1;
while (i !== -1) {
let binding = attributeBindings[i];
let parsed = parseAttributeBinding(binding);
let attribute = parsed[1];
if (seen.indexOf(attribute) === -1) {
seen.push(attribute);
installAttributeBinding(component, rootRef, parsed, operations);
}
i--;
}
if (seen.indexOf('id') === -1) {
let id = component.elementId ? component.elementId : guidFor(component);
operations.setAttribute('id', createPrimitiveRef(id), false, null);
}
}
class CurlyComponentManager {
templateFor(component) {
let {
layout,
layoutName
} = component;
let owner = getOwner$2(component);
let factory;
if (layout === undefined) {
if (layoutName !== undefined) {
let _factory = owner.lookup(`template:${layoutName}`);
factory = _factory;
} else {
return null;
}
} else if (isTemplateFactory(layout)) {
factory = layout;
} else {
// no layout was found, use the default layout
return null;
}
return unwrapTemplate(factory(owner)).asWrappedLayout();
}
getDynamicLayout(bucket) {
return this.templateFor(bucket.component);
}
getTagName(state) {
let {
component,
hasWrappedElement
} = state;
if (!hasWrappedElement) {
return null;
}
return component && component.tagName || 'div';
}
getCapabilities() {
return CURLY_CAPABILITIES;
}
prepareArgs(ComponentClass, args) {
if (args.named.has('__ARGS__')) {
let {
__ARGS__,
...rest
} = args.named.capture();
let __args__ = valueForRef(__ARGS__);
let prepared = {
positional: __args__.positional,
named: {
...rest,
...__args__.named
}
};
return prepared;
}
const {
positionalParams
} = ComponentClass.class ?? ComponentClass;
// early exits
if (positionalParams === undefined || positionalParams === null || args.positional.length === 0) {
return null;
}
let named;
if (typeof positionalParams === 'string') {
let captured = args.positional.capture();
named = {
[positionalParams]: createComputeRef(() => reifyPositional(captured))
};
Object.assign(named, args.named.capture());
} else if (Array.isArray(positionalParams) && positionalParams.length > 0) {
const count = Math.min(positionalParams.length, args.positional.length);
named = {};
Object.assign(named, args.named.capture());
for (let i = 0; i < count; i++) {
let name = positionalParams[i];
named[name] = args.positional.at(i);
}
} else {
return null;
}
return {
positional: EMPTY_ARRAY$4,
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.
let 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.
let capturedArgs = args.named.capture();
beginTrackFrame();
let props = processComponentArgs(capturedArgs);
props[ARGS] = capturedArgs;
let argsTag = 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 = valueForRef(callerSelfRef);
setOwner$1(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.
beginUntrackFrame();
let component = ComponentClass.create(props);
let finalizer = _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) {
addChildView(parentView, component);
}
component.trigger('didReceiveAttrs');
let 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.
let bucket = new ComponentStateBucket(component, capturedArgs, argsTag, finalizer, hasWrappedElement, isInteractive);
if (args.named.has('class')) {
bucket.classRef = args.named.get('class');
}
if (isInteractive && hasWrappedElement) {
component.trigger('willRender');
}
endUntrackFrame();
// consume every argument so we always run again
consumeTag(bucket.argsTag);
consumeTag(component[DIRTY_TAG]);
return bucket;
}
getDebugName(definition) {
return definition.fullName || definition.normalizedName || definition.class?.name || definition.name;
}
getSelf({
rootRef
}) {
return rootRef;
}
didCreateElement({
component,
classRef,
isInteractive,
rootRef
}, element, operations) {
setViewElement(component, element);
setElementView(element, component);
let {
attributeBindings,
classNames,
classNameBindings
} = component;
if (attributeBindings && attributeBindings.length) {
applyAttributeBindings(attributeBindings, component, rootRef, operations);
} else {
let id = component.elementId ? component.elementId : guidFor(component);
operations.setAttribute('id', createPrimitiveRef(id), false, null);
}
if (classRef) {
const ref = createSimpleClassNameBindingRef(classRef);
operations.setAttribute('class', ref, false, null);
}
if (classNames && classNames.length) {
classNames.forEach(name => {
operations.setAttribute('class', 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', childRefFor(rootRef, 'ariaRole'), false, null);
}
component._transitionTo('hasElement');
if (isInteractive) {
beginUntrackFrame();
component.trigger('willInsertElement');
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) {
let {
component,
args,
argsTag,
argsRevision,
isInteractive
} = bucket;
bucket.finalizer = _instrumentStart('render.component', rerenderInstrumentDetails, component);
beginUntrackFrame();
if (args !== null && !validateTag(argsTag, argsRevision)) {
beginTrackFrame();
let props = processComponentArgs(args);
argsTag = bucket.argsTag = endTrackFrame();
bucket.argsRevision = 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');
}
endUntrackFrame();
consumeTag(argsTag);
consumeTag(component[DIRTY_TAG]);
}
didUpdateLayout(bucket) {
bucket.finalize();
}
didUpdate({
component,
isInteractive
}) {
if (isInteractive) {
component.trigger('didUpdate');
component.trigger('didRender');
}
}
getDestroyable(bucket) {
return bucket;
}
}
function initialRenderInstrumentDetails(component) {
return component.instrumentDetails({
initialRender: true
});
}
function rerenderInstrumentDetails(component) {
return component.instrumentDetails({
initialRender: false
});
}
const 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
};
const CURLY_COMPONENT_MANAGER = new CurlyComponentManager();
function isCurlyManager(manager) {
return manager === CURLY_COMPONENT_MANAGER;
}
// Keep track of which component classes have already been processed for lazy event setup.
let lazyEventsProcessed = new WeakMap();
/**
@module @ember/component
*/
// A zero-runtime-overhead private symbol to use in branding the component to
// preserve its type parameter.
/**
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
There are two ways to handle user-initiated events:
### Using the `on` modifier to capture browser events
In a component's template, you can attach an event handler to any element with the `on` modifier:
```handlebars
<button {{on 'click' this.doSomething}} />
```
This will call the function on your component:
```js
import Component from '@ember/component';
export default class ExampleComponent extends Component {
doSomething = (event) => {
// `event` is the native click Event
console.log('clicked on the button');
};
});
```
See the [Guide on Component event
handlers](https://guides.emberjs.com/release/components/component-state-and-actions/#toc_html-modifiers-and-actions)
and the [API docs for `on`](../Ember.Templates.helpers/methods/on?anchor=on)
for more details.
### 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`
@class Component
@extends Ember.CoreView
@uses Ember.TargetActionSupport
@uses Ember.ClassNamesSupport
@uses Ember.ActionSupport
@uses Ember.ViewMixin
@uses Ember.ViewStateSupport
@public
*/
// This type param is used in the class, so must appear here.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
class Component extends CoreView.extend(ChildViewsSupport, ViewStateSupport, ClassNamesSupport, TargetActionSupport, ActionSupport, ViewMixin, {
// These need to be overridable via extend/create but should still
// have a default. Defining them here is the best way to achieve that.
didReceiveAttrs() {},
didRender() {},
didUpdate() {},
didUpdateAttrs() {},
willRender() {},
willUpdate() {}
}) {
isComponent = true;
// SAFETY: this has no runtime existence whatsoever; it is a "phantom type"
// here to preserve the type param.
// SAFTEY: This is set in `init`.
init(properties) {
super.init(properties);
// Handle methods from ViewMixin.
// The native class inheritance will not work for mixins. To work around this,
// we copy the existing rerender method provided by the mixin and swap in the
// new rerender method from our class.
this._superRerender = this.rerender;
this.rerender = this._rerender;
this[IS_DISPATCHING_ATTRS] = false;
this[DIRTY_TAG] = createTag();
this[BOUNDS] = null;
const eventDispatcher = this._dispatcher;
if (eventDispatcher) {
let lazyEventsProcessedForComponentClass = lazyEventsProcessed.get(eventDispatcher);
if (!lazyEventsProcessedForComponentClass) {
lazyEventsProcessedForComponentClass = new WeakSet();
lazyEventsProcessed.set(eventDispatcher, lazyEventsProcessedForComponentClass);
}
let proto = Object.getPrototypeOf(this);
if (!lazyEventsProcessedForComponentClass.has(proto)) {
let lazyEvents = eventDispatcher.lazyEvents;
lazyEvents.forEach((mappedEventName, event) => {
if (mappedEventName !== null && typeof this[mappedEventName] === 'function') {
eventDispatcher.setupHandlerForBrowserEvent(event);
}
});
lazyEventsProcessedForComponentClass.add(proto);
}
}
}
__dispatcher;
get _dispatcher() {
if (this.__dispatcher === undefined) {
let owner = getOwner$2(this);
if (owner.lookup('-environment:main').isInteractive) {
let dispatcher = owner.lookup('event_dispatcher:main');
this.__dispatcher = dispatcher;
} 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(name, target, method) {
this._dispatcher?.setupHandlerForEmberEvent(name);
// The `on` method here comes from the Evented mixin. Since this mixin
// is applied to the parent of this class, however, we are still able
// to use `super`.
return super.on(name, target, method);
}
// Changed to `rerender` on init
_rerender() {
DIRTY_TAG$1(this[DIRTY_TAG]);
this._superRerender();
}
[PROPERTY_DID_CHANGE](key, value) {
if (this[IS_DISPATCHING_ATTRS]) {
return;
}
let args = this[ARGS];
let reference = args !== undefined ? args[key] : undefined;
if (reference !== undefined && isUpdatableRef(reference)) {
updateRef(reference, arguments.length === 2 ? value : get$2(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
let _element = getViewElement(this);
let element = _element;
let isSVG = element.namespaceURI === 'http://www.w3.org/2000/svg';
let {
type,
normalized
} = normalizeProperty(element, name);
if (isSVG || type === 'attr') {
return element.getAttribute(normalized);
}
return element[normalized];
}
// --- Declarations which support mixins ---
// We use `declare` on these properties, even though they are optional, so
// that they do not get created on the class *at all* when emitting the
// transpiled code. Otherwise, since declared class properties are equivalent
// to calling `defineProperty` in the class constructor, they would "stomp"
// the properties supplied by mixins.
/**
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
*/ /**
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
*/
/**
Layout can be used to wrap content in a component.
@property layout
@type Function
@public
*/
/**
The name of the layout to lookup if no layout is provided.
By default `Component` will lookup a template with this name in
`Ember.TEMPLATES` (a shared global object).
@property layoutName
@type String
@default undefined
@private
*/
/**
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 undefined
@public
*/
static isComponentFactory = true;
static toString() {
return '@ember/component';
}
}
// We continue to use reopenClass here so that positionalParams can be overridden with reopenClass in subclasses.
Component.reopenClass({
positionalParams: []
});
setInternalComponentManager(CURLY_COMPONENT_MANAGER, Component);
/**
@module @ember/component
*/
const RECOMPUTE_TAG = Symbol('RECOMPUTE_TAG');
// Signature type utilities
// Implements Ember's `Factory` interface and tags it for narrowing/checking.
const IS_CLASSIC_HELPER = Symbol('IS_CLASSIC_HELPER');
// A zero-runtime-overhead private symbol to use in branding the component to
// preserve its type parameter.
/**
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
*/
// ESLint doesn't understand declaration merging.
/* eslint-disable import/export */
class Helper extends FrameworkObject {
static isHelperFactory = true;
static [IS_CLASSIC_HELPER] = true;
// `packages/ember/index.js` was setting `Helper.helper`. This seems like
// a bad idea and probably not something we want. We've moved that definition
// here, but it should definitely be reviewed and probably removed.
/** @deprecated */
static helper = helper$2;
// SAFETY: this is initialized in `init`, rather than `constructor`. It is
// safe to `declare` like this *if and only if* nothing uses the constructor
// directly in this class, since nothing else can run before `init`.
// SAFETY: this has no runtime existence whatsoever; it is a "phantom type"
// here to preserve the type param.
init(properties) {
super.init(properties);
this[RECOMPUTE_TAG] = 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 { 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() {
join(() => DIRTY_TAG$1(this[RECOMPUTE_TAG]));
}
}
/* eslint-enable import/export */
function isClassicHelper(obj) {
return obj[IS_CLASSIC_HELPER] === true;
}
class ClassicHelperManager {
capabilities = helperCapabilities('3.23', {
hasValue: true,
hasDestroyable: true
});
ownerInjection;
constructor(owner) {
let ownerInjection = {};
setOwner$1(ownerInjection, owner);
this.ownerInjection = ownerInjection;
}
createHelper(definition, args) {
let instance = isFactoryManager(definition) ? definition.create() : definition.create(this.ownerInjection);
return {
instance,
args
};
}
getDestroyable({
instance
}) {
return instance;
}
getValue({
instance,
args
}) {
let {
positional,
named
} = args;
let ret = instance.compute(positional, named);
consumeTag(instance[RECOMPUTE_TAG]);
return ret;
}
getDebugName(definition) {
return getDebugName((definition.class || definition)['prototype']);
}
}
function isFactoryManager(obj) {
return obj != null && 'class' in obj;
}
setHelperManager$1(owner => {
return new ClassicHelperManager(owner);
}, Helper);
const CLASSIC_HELPER_MANAGER = getInternalHelperManager(Helper);
///////////
class Wrapper {
isHelperFactory = true;
constructor(compute) {
this.compute = compute;
}
create() {
// needs new instance or will leak containers
return {
compute: this.compute
};
}
}
class SimpleClassicHelperManager {
capabilities = helperCapabilities('3.23', {
hasValue: true
});
createHelper(definition, args) {
return () => definition.compute.call(null, args.positional, args.named);
}
getValue(fn) {
return fn();
}
getDebugName(definition) {
return getDebugName(definition.compute);
}
}
const SIMPLE_CLASSIC_HELPER_MANAGER = new SimpleClassicHelperManager();
setHelperManager$1(() => SIMPLE_CLASSIC_HELPER_MANAGER, Wrapper.prototype);
/*
Function-based helpers need to present with a constructor signature so that
type parameters can be preserved when `helper()` is passed a generic function
(this is particularly key for checking helper invocations with Glint).
Accordingly, we define an abstract class and declaration merge it with the
interface; this inherently provides an `abstract` constructor. Since it is
`abstract`, it is not callable, which is important since end users should not
be able to do `let myHelper = helper(someFn); new myHelper()`.
*/
/**
* The type of a function-based helper.
*
* @note This is *not* user-constructible: it is exported only so that the type
* returned by the `helper` function can be named (and indeed can be exported
* like `export default helper(...)` safely).
*/
// Making `FunctionBasedHelper` an alias this way allows callers to name it in
// terms meaningful to *them*, while preserving the type behavior described on
// the `abstract class FunctionBasedHelperInstance` below.
// This abstract class -- specifically, its `protected abstract __concrete__`
// member -- prevents subclasses from doing `class X extends helper(..)`, since
// that is an error at runtime. While it is rare that people would type that, it
// is not impossible and we use this to give them early signal via the types for
// a behavior which will break (and in a somewhat inscrutable way!) at runtime.
//
// This is needful because we lie about what this actually is for Glint's sake:
// a function-based helper returns a `Factory<SimpleHelper>`, which is designed
// to be "opaque" from a consumer's POV, i.e. not user-callable or constructible
// but only useable in a template (or via `invokeHelper()` which also treats it
// as a fully opaque `object` from a type POV). But Glint needs a `Helper<S>` to
// make it work the same way as class-based helpers. (Note that this does not
// hold for plain functions as helpers, which it can handle distinctly.) This
// signature thus makes it so that the item is usable *as* a `Helper` in Glint,
// but without letting end users treat it as a helper class instance.
/**
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
*/
// This overload allows users to write types directly on the callback passed to
// the `helper` function and infer the resulting type correctly.
// This overload allows users to provide a `Signature` type explicitly at the
// helper definition site, e.g. `helper<Sig>((pos, named) => {...})`. **Note:**
// this overload must appear second, since TS' inference engine will not
// correctly infer the type of `S` here from the types on the supplied callback.
function helper$2(helperFn) {
// SAFETY: this is completely lies, in two ways:
//
// 1. `Wrapper` is a `Factory<SimpleHelper<S>>`, but from the perspective of
// any external callers (i.e. Ember *users*), it is quite important that
// the `Factory` relationship be hidden, because it is not public API for
// an end user to call `.create()` on a helper created this way. Instead,
// we provide them an `abstract new` signature (which means it cannot be
// directly constructed by calling `new` on it) and which does not have the
// `.create()` signature on it anymore.
//
// 2. The produced type here ends up being a subtype of `Helper`, which is not
// strictly true. This is necessary for the sake of Glint, which provides
// its information by way of a "declaration merge" with `Helper<S>` in the
// case of items produced by `helper()`.
//
// Long-term, this entire construct can go away in favor of deprecating the
// `helper()` invocation in favor of using plain functions.
return new Wrapper(helperFn);
}
/**
@module @ember/template
*/
/**
A wrapper around a string that has been marked as safe ("trusted"). **When
rendered in HTML, Ember will not perform any escaping.**
Note:
1. This does not *make* the string safe; it means that some code in your
application has *marked* it as safe using the `htmlSafe()` function.
2. The only public API for getting a `SafeString` is calling `htmlSafe()`. It
is *not* user-constructible.
If a string contains user inputs or other untrusted data, you must sanitize
the string before using the `htmlSafe` method. Otherwise your code is
vulnerable to [Cross-Site Scripting][xss]. There are many open source
sanitization libraries to choose from, both for front end and server-side
sanitization.
[xss]: https://owasp.org/www-community/attacks/DOM_Based_XSS
```javascript
import { htmlSafe } from '@ember/template';
let someTrustedOrSanitizedString = "<div>Hello!</div>"
htmlSafe(someTrustedorSanitizedString);
```
@for @ember/template
@class SafeString
@since 4.12.0
@public
*/
class SafeString {
__string;
constructor(string) {
this.__string = string;
}
/**
Get the string back to use as a string.
@public
@method toString
@returns {String} The string marked as trusted
*/
toString() {
return `${this.__string}`;
}
/**
Get the wrapped string as HTML to use without escaping.
@public
@method toHTML
@returns {String} the trusted string, without any escaping applied
*/
toHTML() {
return this.toString();
}
}
const escape = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'`': '`',
'=': '='
};
const possible = /[&<>"'`=]/;
const badChars = /[&<>"'`=]/g;
function escapeChar(chr) {
return escape[chr];
}
function escapeExpression(string) {
let s;
if (typeof string !== 'string') {
// don't escape SafeStrings, since they're already safe
if (isHTMLSafe(string)) {
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.
s = String(string);
} else {
s = string;
}
if (!possible.test(s)) {
return s;
}
// SAFETY: this is technically a lie, but it's a true lie as long as the
// invariant it depends on is upheld: `escapeChar` will always return a string
// as long as its input is one of the characters in `escape`, and it will only
// be called if it matches one of the characters in the `badChar` regex, which
// is hand-maintained to match the set escaped. (It would be nice if TS could
// "see" into the regex to see how this works, but that'd be quite a lot of
// extra fanciness.)
return s.replace(badChars, escapeChar);
}
/**
Use this method to indicate that a string should be rendered as HTML
when the string is used in a template. To say this another way,
strings marked with `htmlSafe` will not be HTML escaped.
A word of warning - The `htmlSafe` method does not make the string safe;
it only tells the framework to treat the string as if it is safe to render
as HTML. If a string contains user inputs or other untrusted
data, you must sanitize the string before using the `htmlSafe` method.
Otherwise your code is vulnerable to
[Cross-Site Scripting](https://owasp.org/www-community/attacks/DOM_Based_XSS).
There are many open source sanitization libraries to choose from,
both for front end and server-side sanitization.
```javascript
import { htmlSafe } from '@ember/template';
const someTrustedOrSanitizedString = "<div>Hello!</div>"
htmlSafe(someTrustedorSanitizedString)
```
@method htmlSafe
@for @ember/template
@param str {String} The string to treat as trusted.
@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';
let plainString = 'plain string';
let 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(str) {
return str !== null && typeof str === 'object' && 'toHTML' in str && typeof str.toHTML === 'function';
}
/**
@module @ember/engine
*/
/**
The `EngineInstance` encapsulates all of the stateful aspects of a
running `Engine`.
@public
@class EngineInstance
@extends EmberObject
@uses RegistryProxyMixin
@uses ContainerProxyMixin
*/
// Note on types: since `EngineInstance` uses `RegistryProxyMixin` and
// `ContainerProxyMixin`, which respectively implement the same `RegistryMixin`
// and `ContainerMixin` types used to define `InternalOwner`, this is the same
// type as `InternalOwner` from TS's POV. The point of the explicit `extends`
// clauses for `InternalOwner` and `Owner` is to keep us honest: if this stops
// type checking, we have broken part of our public API contract. Medium-term,
// the goal here is to `EngineInstance` simple be `Owner`.
class EngineInstance extends EmberObject.extend(RegistryProxyMixin, ContainerProxyMixin) {
/**
@private
@method setupRegistry
@param {Registry} registry
@param {BootOptions} options
*/
// This is effectively an "abstract" method: it defines the contract a
// subclass (e.g. `ApplicationInstance`) must follow to implement this
// behavior, but an `EngineInstance` has no behavior of its own here.
static setupRegistry(_registry, _options) {}
/**
The base `Engine` for which this is an instance.
@property {Engine} engine
@private
*/
[ENGINE_PARENT];
_booted = false;
init(properties) {
super.init(properties);
// Ensure the guid gets setup for this instance
guidFor(this);
this.base ??= this.application;
// Create a per-instance registry that will use the application's registry
// as a fallback for resolving registrations.
let registry = this.__registry__ = new Registry({
fallback: this.base.__registry__
});
// Create a per-instance container from the instance's registry
this.__container__ = registry.container({
owner: this
});
this._booted = false;
}
_bootPromise = null;
/**
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 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;
}
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);
// We overwrote this method from RegistryProxyMixin.
this.__registry__.unregister(fullName);
}
/**
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 = {}) {
let ChildEngine = this.lookup(`engine:${name}`);
if (!ChildEngine) {
throw new Error(`You attempted to mount the engine '${name}', but it is not registered with its parent.`);
}
let engineInstance = ChildEngine.buildInstance(options);
setEngineParent(engineInstance, this);
return engineInstance;
}
/**
Clone dependencies shared between an engine instance and its parent.
@private
@method cloneParentDependencies
*/
cloneParentDependencies() {
const parent = getEngineParent(this);
let registrations = ['route:basic', 'service:-routing'];
registrations.forEach(key => {
let registration = parent.resolveRegistration(key);
this.register(key, registration);
});
let env = parent.lookup('-environment:main');
this.register('-environment:main', env, {
instantiate: false
});
// The type annotation forces TS to (a) validate that these match and (b)
// *notice* that they match, e.g. below on the `singletons.push()`.
let singletons = ['router:main', privatize`-bucket-cache:main`, '-view-registry:main', `renderer:-dom`, 'service:-document'];
if (env['isInteractive']) {
singletons.push('event_dispatcher:main');
}
singletons.forEach(key => {
// SAFETY: We already expect this to be a singleton
let singleton = parent.lookup(key);
this.register(key, singleton, {
instantiate: false
});
});
}
}
const emberEngineInstance = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: EngineInstance
}, Symbol.toStringTag, { value: 'Module' });
function instrumentationPayload$1(def) {
// "main" used to be the outlet name, keeping it around for compatibility
return {
object: `${def.name}:main`
};
}
const 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) {
let parentStateRef = dynamicScope.get('outletState');
let currentStateRef = definition.ref;
dynamicScope.set('outletState', currentStateRef);
let state = {
self: createConstRef(definition.controller),
finalize: _instrumentStart('render.outlet', instrumentationPayload$1, definition)
};
if (env.debugRenderTree !== undefined) {
state.outletBucket = {};
let parentState = valueForRef(parentStateRef);
let parentOwner = parentState && parentState.render && parentState.render.owner;
let currentOwner = valueForRef(currentStateRef).render.owner;
if (parentOwner && parentOwner !== currentOwner) {
let mountPoint = currentOwner.mountPoint;
state.engine = currentOwner;
if (mountPoint) {
state.engineBucket = {
mountPoint
};
}
}
}
return state;
}
getDebugName({
name
}) {
return name;
}
getDebugCustomRenderTree(definition, state, args) {
let nodes = [];
nodes.push({
bucket: state.outletBucket,
type: 'outlet',
// "main" used to be the outlet name, keeping it around for compatibility
name: 'main',
args: EMPTY_ARGS,
instance: undefined,
template: undefined
});
if (state.engineBucket) {
nodes.push({
bucket: state.engineBucket,
type: 'engine',
name: state.engineBucket.mountPoint,
args: EMPTY_ARGS,
instance: state.engine,
template: undefined
});
}
nodes.push({
bucket: state,
type: 'route-template',
name: definition.name,
args: args,
instance: definition.controller,
template: unwrapTemplate(definition.template).moduleName
});
return nodes;
}
getCapabilities() {
return CAPABILITIES$1;
}
getSelf({
self
}) {
return self;
}
didCreate() {}
didUpdate() {}
didRenderLayout(state) {
state.finalize();
}
didUpdateLayout() {}
getDestroyable() {
return null;
}
}
const OUTLET_MANAGER = new OutletComponentManager();
class OutletComponentDefinition {
// handle is not used by this custom definition
handle = -1;
resolvedName;
compilable;
capabilities;
constructor(state, manager = OUTLET_MANAGER) {
this.state = state;
this.manager = manager;
let capabilities = manager.getCapabilities();
this.capabilities = capabilityFlagsFrom(capabilities);
this.compilable = capabilities.wrapped ? unwrapTemplate(state.template).asWrappedLayout() : unwrapTemplate(state.template).asLayout();
this.resolvedName = state.name;
}
}
function createRootOutlet(outletView) {
return new OutletComponentDefinition(outletView.state);
}
class RootComponentManager extends CurlyComponentManager {
component;
constructor(component) {
super();
this.component = component;
}
create(_owner, _state, _args, {
isInteractive
}, dynamicScope) {
let component = this.component;
let finalizer = _instrumentStart('render.component', initialRenderInstrumentDetails, component);
dynamicScope.view = component;
let 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');
}
}
let bucket = new ComponentStateBucket(component, null, CONSTANT_TAG, finalizer, hasWrappedElement, isInteractive);
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
const 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 {
// handle is not used by this custom definition
handle = -1;
resolvedName = '-top-level';
state;
manager;
capabilities = capabilityFlagsFrom(ROOT_CAPABILITIES);
compilable = null;
constructor(component) {
this.manager = new RootComponentManager(component);
let factory = getFactoryFor(component);
this.state = factory;
}
}
const EMPTY_ATTRS = [];
function indexOfAttribute(attributes, namespaceURI, localName) {
for (let i = 0; i < attributes.length; i++) {
const 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) {
const index = indexOfAttribute(attributes, namespaceURI, localName);
return index === -1 ? null : attributes[index].value;
}
function removeAttribute(attributes, namespaceURI, localName) {
const 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;
}
let {
attributes
} = element;
if (attributes === EMPTY_ATTRS) {
attributes = element.attributes = [];
} else {
const 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;
let len = 0;
let child = this.node.firstChild;
for (; child !== null; len++) {
this[len] = child;
child = child.nextSibling;
}
const 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) {
const clone = nodeFrom(node);
if (deep) {
let child = node.firstChild;
let nextChild = child;
while (child !== null) {
nextChild = child.nextSibling;
clone.appendChild(child.cloneNode(true));
child = nextChild;
}
}
return clone;
}
function nodeFrom(node) {
let namespaceURI;
if (node.nodeType === 1 /* ELEMENT_NODE */) {
namespaceURI = node.namespaceURI;
}
const 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;
}
const copy = [];
for (let i = 0; i < attrs.length; i++) {
const 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) {
const 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) {
const firstChild = fragment.firstChild;
if (firstChild === null) {
return;
}
fragment.firstChild = null;
fragment.lastChild = null;
let lastChild = firstChild;
let 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) {
let localName = qualifiedName;
let prefix = null;
const 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() {
let 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) {
const raw = new SimpleNodeImpl(this.ownerDocument, -1 /* RAW_NODE */, '#raw', html, void 0);
let parentNode;
let 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) {
const localName = adjustAttrName(this.namespaceURI, name);
return getAttribute(this.attributes, null, localName);
}
getAttributeNS(namespaceURI, localName) {
return getAttribute(this.attributes, namespaceURI, localName);
}
setAttribute(name, value) {
const localName = adjustAttrName(this.namespaceURI, name);
setAttribute(this, null, null, localName, value);
}
setAttributeNS(namespaceURI, qualifiedName, value) {
const [prefix, localName] = parseQualifiedName(qualifiedName);
setAttribute(this, namespaceURI, prefix, localName, value);
}
removeAttribute(name) {
const 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
const 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
const document = new SimpleNodeImpl(null, 9 /* DOCUMENT_NODE */, '#document', null, "http://www.w3.org/1999/xhtml" /* HTML */);
const doctype = new SimpleNodeImpl(document, 10 /* DOCUMENT_TYPE_NODE */, 'html', null, "http://www.w3.org/1999/xhtml" /* HTML */);
const html = new SimpleNodeImpl(document, 1 /* ELEMENT_NODE */, 'HTML', null, "http://www.w3.org/1999/xhtml" /* HTML */);
const head = new SimpleNodeImpl(document, 1 /* ELEMENT_NODE */, 'HEAD', null, "http://www.w3.org/1999/xhtml" /* HTML */);
const 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;
}
const simpleDomDocument = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: createHTMLDocument
}, Symbol.toStringTag, { value: 'Module' });
class NodeDOMTreeConstruction extends DOMTreeConstruction {
// Hides property on base class
constructor(doc) {
super(doc || createHTMLDocument());
}
// override to prevent usage of `this.document` until after the constructor
setupUselessElement() {}
insertHTMLBefore(parent, reference, html) {
let raw = this.document.createRawHTMLSection(html);
return parent.insertBefore(raw, reference), new 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);
}
}
const NEEDS_EXTRA_CLOSE = new WeakMap();
class SerializeBuilder extends NewElementBuilder {
serializeBlockDepth = 0;
__openBlock() {
let {
tagName: tagName
} = this.element;
if ("TITLE" !== tagName && "SCRIPT" !== tagName && "STYLE" !== tagName) {
let depth = this.serializeBlockDepth++;
this.__appendComment(`%+b:${depth}%`);
}
super.__openBlock();
}
__closeBlock() {
let {
tagName: tagName
} = this.element;
if (super.__closeBlock(), "TITLE" !== tagName && "SCRIPT" !== tagName && "STYLE" !== tagName) {
let depth = --this.serializeBlockDepth;
this.__appendComment(`%-b:${depth}%`);
}
}
__appendHTML(html) {
let {
tagName: tagName
} = this.element;
if ("TITLE" === tagName || "SCRIPT" === tagName || "STYLE" === tagName) return super.__appendHTML(html);
// Do we need to run the html tokenizer here?
let first = this.__appendComment("%glmr%");
if ("TABLE" === tagName) {
let openIndex = html.indexOf("<");
openIndex > -1 && "tr" === html.slice(openIndex + 1, openIndex + 3) && (html = `<tbody>${html}</tbody>`);
}
"" === html ? this.__appendComment("% %") : super.__appendHTML(html);
let last = this.__appendComment("%glmr%");
return new ConcreteBounds(this.element, first, last);
}
__appendText(string) {
let {
tagName: tagName
} = this.element,
current = function (cursor) {
let {
element: element,
nextSibling: nextSibling
} = cursor;
return null === nextSibling ? element.lastChild : nextSibling.previousSibling;
}(this);
return "TITLE" === tagName || "SCRIPT" === tagName || "STYLE" === tagName ? super.__appendText(string) : "" === string ? this.__appendComment("% %") : (current && 3 === current.nodeType && this.__appendComment("%|%"), super.__appendText(string));
}
closeElement() {
return NEEDS_EXTRA_CLOSE.has(this.element) && (NEEDS_EXTRA_CLOSE.delete(this.element), super.closeElement()), super.closeElement();
}
openElement(tag) {
return "tr" === tag && "TBODY" !== this.element.tagName && "THEAD" !== this.element.tagName && "TFOOT" !== this.element.tagName && (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, !0), this.flushElement(null)), super.openElement(tag);
}
pushRemoteElement(element, cursorId, insertBefore = null) {
let {
dom: dom
} = this,
script = dom.createElement("script");
return script.setAttribute("glmr", cursorId), dom.insertBefore(element, script, insertBefore), super.pushRemoteElement(element, cursorId, insertBefore);
}
}
function serializeBuilder(env, cursor) {
return SerializeBuilder.forInitialRender(env, cursor);
}
const glimmerNode = /*#__PURE__*/Object.defineProperty({
__proto__: null,
NodeDOMTreeConstruction,
serializeBuilder
}, Symbol.toStringTag, { value: 'Module' });
/**
@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;
}
}
const eachIn = internalHelper(({
positional
}) => {
const inner = positional[0];
return createComputeRef(() => {
let iterable = valueForRef(inner);
consumeTag(tagForObject(iterable));
if (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 = 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) || 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 (!isObject$1(iterable)) {
return null;
}
if (Array.isArray(iterable)) {
return ArrayIterator.from(iterable);
} else if (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 {
position = 0;
constructor(length) {
this.length = length;
}
isEmpty() {
return false;
}
memoFor(position) {
return position;
}
next() {
let {
length,
position
} = this;
if (position >= length) {
return null;
}
let value = this.valueFor(position);
let memo = this.memoFor(position);
this.position++;
return {
value,
memo
};
}
}
class ArrayIterator extends BoundedIterator {
static from(iterable) {
return iterable.length > 0 ? new this(iterable) : null;
}
static fromForEachable(object) {
let array = [];
object.forEach(item => array.push(item));
return this.from(array);
}
constructor(array) {
super(array.length);
this.array = array;
}
valueFor(position) {
return this.array[position];
}
}
class EmberArrayIterator extends BoundedIterator {
static from(iterable) {
return iterable.length > 0 ? new this(iterable) : null;
}
constructor(array) {
super(array.length);
this.array = array;
}
valueFor(position) {
return objectAt(this.array, position);
}
}
class ObjectIterator extends BoundedIterator {
static fromIndexable(obj) {
let keys = Object.keys(obj);
if (keys.length === 0) {
return null;
} else {
let values = [];
for (let key of keys) {
let value;
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 (isTracking()) {
consumeTag(tagFor(obj, key));
if (Array.isArray(value)) {
consumeTag(tagFor(value, '[]'));
}
}
values.push(value);
}
return new this(keys, values);
}
}
static fromForEachable(obj) {
let keys = [];
let values = [];
let length = 0;
let 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);
}
}
constructor(keys, values) {
super(values.length);
this.keys = keys;
this.values = values;
}
valueFor(position) {
return this.values[position];
}
memoFor(position) {
return this.keys[position];
}
}
class NativeIterator {
static from(iterable) {
let iterator = iterable[Symbol.iterator]();
let result = iterator.next();
let {
done
} = result;
if (done) {
return null;
} else {
return new this(iterator, result);
}
}
position = 0;
constructor(iterable, result) {
this.iterable = iterable;
this.result = result;
}
isEmpty() {
return false;
}
next() {
let {
iterable,
result,
position
} = this;
if (result.done) {
return null;
}
let value = this.valueFor(result, position);
let 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 value != null && typeof value['forEach'] === 'function';
}
function isNativeIterable(value) {
return value != null && typeof value[Symbol.iterator] === 'function';
}
function isIndexable(value) {
return value !== null && (typeof value === 'object' || typeof value === 'function');
}
/**
@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(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;
}
const emberUtilsLibIsNone = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: isNone
}, Symbol.toStringTag, { value: 'Module' });
/**
@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(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) {
if (obj === null || obj === undefined) {
return true;
}
if (!hasUnknownProperty(obj) && typeof obj.size === 'number') {
return !obj.size;
}
if (typeof obj === 'object') {
let size = get$2(obj, 'size');
if (typeof size === 'number') {
return !size;
}
let length = get$2(obj, 'length');
if (typeof length === 'number') {
return !length;
}
}
if (typeof obj.length === 'number' && typeof obj !== 'function') {
return !obj.length;
}
return false;
}
const emberUtilsLibIsEmpty = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: isEmpty
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/utils
*/
/**
A value is blank if it is empty or a whitespace string.
```javascript
import { isBlank } from '@ember/utils';
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;
}
const emberUtilsLibIsBlank = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: isBlank
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/utils
*/
/**
A value is present if it not `isBlank`.
```javascript
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);
}
const emberUtilsLibIsPresent = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: isPresent
}, Symbol.toStringTag, { value: 'Module' });
/**
@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;
}
const emberUtilsLibIsEqual = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: isEqual
}, Symbol.toStringTag, { value: 'Module' });
// ........................................
// TYPING & ARRAY MESSAGING
//
const 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'
};
const {
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 item the item to check
@return {String} the type
@public
@static
*/
function typeOf(item) {
if (item === null) {
return 'null';
}
if (item === undefined) {
return 'undefined';
}
let ret = TYPE_MAP[toString.call(item)] || 'object';
if (ret === 'function') {
if (CoreObject.detect(item)) {
ret = 'class';
}
} else if (ret === 'object') {
if (item instanceof Error) {
ret = 'error';
} else if (item instanceof CoreObject) {
ret = 'instance';
} else if (item instanceof Date) {
ret = 'date';
}
}
return ret;
}
const emberUtilsLibTypeOf = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: typeOf
}, Symbol.toStringTag, { value: 'Module' });
const TYPE_ORDER = {
undefined: 0,
null: 1,
boolean: 2,
number: 3,
string: 4,
array: 5,
object: 6,
instance: 7,
function: 8,
class: 9,
date: 10,
regexp: 11,
filelist: 12,
error: 13
};
//
// the spaceship operator
//
// `. ___
// __,' __`. _..----....____
// __...--.'``;. ,. ;``--..__ .' ,-._ _.-'
// _..-''-------' `' `' `' O ``-''._ (,;') _,'
// ,'________________ \`-._`-','
// `._ ```````````------...___ '-.._'-:
// ```--.._ ,. ````--...__\-.
// `.--. `-` "INFINITY IS LESS ____ | |`
// `. `. THAN BEYOND" ,'`````. ; ;`
// `._`. __________ `. \'__/`
// `-:._____/______/___/____`. \ `
// | `._ `. \
// `._________`-. `. `.___
// SSt `------'`
function spaceship(a, b) {
// SAFETY: `Math.sign` always returns `-1` for negative, `0` for zero, and `1`
// for positive numbers. (The extra precision is useful for the way we use
// this in the context of `compare`.)
return Math.sign(a - b);
}
/**
@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;
}
let type1 = typeOf(v);
let type2 = typeOf(w);
if (type1 === 'instance' && isComparable(v) && v.constructor.compare) {
return v.constructor.compare(v, w);
}
if (type2 === 'instance' && isComparable(w) && w.constructor.compare) {
// SAFETY: Multiplying by a negative just changes the sign
return w.constructor.compare(w, v) * -1;
}
let 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':
return spaceship(Number(v), Number(w));
case 'number':
return spaceship(v, w);
case 'string':
return spaceship(v.localeCompare(w), 0);
case 'array':
{
let vLen = v.length;
let wLen = w.length;
let len = Math.min(vLen, wLen);
for (let i = 0; i < len; i++) {
let 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 (isComparable(v) && v.compare) {
return v.compare(v, w);
}
return 0;
case 'date':
return spaceship(v.getTime(), w.getTime());
default:
return 0;
}
}
function isComparable(value) {
return Comparable.detect(value);
}
const emberUtilsLibCompare = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: compare
}, Symbol.toStringTag, { value: 'Module' });
const emberUtilsIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
compare,
isBlank,
isEmpty,
isEqual,
isNone,
isPresent,
typeOf
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/array
*/
const EMPTY_ARRAY = Object.freeze([]);
const identityFunction = item => item;
function uniqBy$1(array, keyOrFunc = identityFunction) {
let ret = A();
let seen = new Set();
let getter = typeof keyOrFunc === 'function' ? keyOrFunc : item => get$2(item, keyOrFunc);
array.forEach(item => {
let val = getter(item);
if (!seen.has(val)) {
seen.add(val);
ret.push(item);
}
});
return ret;
}
function iter(...args) {
let valueProvided = args.length === 2;
let [key, value] = args;
return valueProvided ? item => value === get$2(item, key) : item => Boolean(get$2(item, key));
}
function findIndex(array, predicate, startAt) {
let len = array.length;
for (let index = startAt; index < len; index++) {
// SAFETY: Because we're checking the index this value should always be set.
let item = objectAt(array, index);
if (predicate(item, index, array)) {
return index;
}
}
return -1;
}
function find(array, callback, target = null) {
let predicate = callback.bind(target);
let index = findIndex(array, predicate, 0);
return index === -1 ? undefined : objectAt(array, index);
}
function any(array, callback, target = null) {
let predicate = callback.bind(target);
return findIndex(array, predicate, 0) !== -1;
}
function every(array, callback, target = null) {
let cb = callback.bind(target);
let predicate = (item, index, array) => !cb(item, index, array);
return findIndex(array, predicate, 0) === -1;
}
function indexOf$1(array, val, startAt = 0, withNaNCheck) {
let len = array.length;
if (startAt < 0) {
startAt += len;
}
// SameValueZero comparison (NaN !== NaN)
let predicate = withNaNCheck && val !== val ? item => item !== item : item => item === val;
return findIndex(array, predicate, startAt);
}
function removeAt(array, index, len) {
replace(array, index, len ?? 1, EMPTY_ARRAY);
return array;
}
function insertAt(array, index, item) {
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$2(obj) {
// SAFETY: Property read checks are safe if it's an object
if (!obj || obj.setInterval) {
return false;
}
if (Array.isArray(obj) || EmberArray.detect(obj)) {
return true;
}
let type = typeOf(obj);
if ('array' === type) {
return true;
}
// SAFETY: Property read checks are safe if it's an object
let 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(callback) {
let property = computed(callback);
property.enumerable = false;
return property;
}
function mapBy$1(key) {
return this.map(next => get$2(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
*/
const EmberArray = Mixin.create(Enumerable, {
init() {
this._super(...arguments);
setEmberArray(this);
},
objectsAt(indexes) {
return indexes.map(idx => objectAt(this, idx));
},
'[]': nonEnumerableComputed({
get() {
return this;
},
set(_key, value) {
this.replace(0, this.length, value);
return this;
}
}),
firstObject: nonEnumerableComputed(function () {
return objectAt(this, 0);
}).readOnly(),
lastObject: nonEnumerableComputed(function () {
return objectAt(this, this.length - 1);
}).readOnly(),
// Add any extra methods to EmberArray that are native to the built-in Array.
slice(beginIndex = 0, endIndex) {
let ret = A();
let length = this.length;
if (beginIndex < 0) {
beginIndex = length + beginIndex;
}
let validatedEndIndex;
if (endIndex === undefined || endIndex > length) {
validatedEndIndex = length;
} else if (endIndex < 0) {
validatedEndIndex = length + endIndex;
} else {
validatedEndIndex = endIndex;
}
while (beginIndex < validatedEndIndex) {
ret[ret.length] = objectAt(this, beginIndex++);
}
return ret;
},
indexOf(object, startAt) {
return indexOf$1(this, object, startAt, false);
},
lastIndexOf(object, startAt) {
let len = this.length;
if (startAt === undefined || startAt >= len) {
startAt = len - 1;
}
if (startAt < 0) {
startAt += len;
}
for (let idx = startAt; idx >= 0; idx--) {
if (objectAt(this, idx) === object) {
return idx;
}
}
return -1;
},
forEach(callback, target = null) {
let length = this.length;
for (let index = 0; index < length; index++) {
let item = this.objectAt(index);
callback.call(target, item, index, this);
}
return this;
},
getEach: mapBy$1,
setEach(key, value) {
return this.forEach(item => set(item, key, value));
},
map(callback, target = null) {
let ret = A();
this.forEach((x, idx, i) => ret[idx] = callback.call(target, x, idx, i));
return ret;
},
mapBy: mapBy$1,
filter(callback, target = null) {
let ret = A();
this.forEach((x, idx, i) => {
if (callback.call(target, x, idx, i)) {
ret.push(x);
}
});
return ret;
},
reject(callback, target = null) {
return this.filter(function () {
// @ts-expect-error TS doesn't like us using arguments like this
return !callback.apply(target, arguments);
});
},
filterBy() {
// @ts-expect-error TS doesn't like the ...arguments spread here.
return this.filter(iter(...arguments));
},
rejectBy() {
// @ts-expect-error TS doesn't like the ...arguments spread here.
return this.reject(iter(...arguments));
},
find(callback, target = null) {
return find(this, callback, target);
},
findBy() {
// @ts-expect-error TS doesn't like the ...arguments spread here.
let callback = iter(...arguments);
return find(this, callback);
},
every(callback, target = null) {
return every(this, callback, target);
},
isEvery() {
// @ts-expect-error TS doesn't like the ...arguments spread here.
let callback = iter(...arguments);
return every(this, callback);
},
any(callback, target = null) {
return any(this, callback, target);
},
isAny() {
// @ts-expect-error TS doesn't like us using arguments like this
let callback = iter(...arguments);
return any(this, callback);
},
// FIXME: When called without initialValue, behavior does not match native behavior
reduce(callback, initialValue) {
let ret = initialValue;
this.forEach(function (item, i) {
ret = callback(ret, item, i, this);
}, this);
return ret;
},
invoke(methodName, ...args) {
let ret = A();
// SAFETY: This is not entirely safe and the code will not work with Ember proxies
this.forEach(item => ret.push(item[methodName]?.(...args)));
return ret;
},
toArray() {
return this.map(item => item);
},
compact() {
return this.filter(value => value != null);
},
includes(object, startAt) {
return indexOf$1(this, object, startAt, true) !== -1;
},
sortBy() {
let sortKeys = arguments;
return this.toArray().sort((a, b) => {
for (let i = 0; i < sortKeys.length; i++) {
let key = sortKeys[i];
let propA = get$2(a, key);
let propB = get$2(b, key);
// return 1 or -1 else continue to the next sortKey
let compareValue = compare(propA, propB);
if (compareValue) {
return compareValue;
}
}
return 0;
});
},
uniq() {
return uniqBy$1(this);
},
uniqBy(key) {
return uniqBy$1(this, key);
},
without(value) {
if (!this.includes(value)) {
return this; // nothing to do
}
// SameValueZero comparison (NaN !== NaN)
let 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
*/
const MutableArray = Mixin.create(EmberArray, MutableEnumerable, {
clear() {
let len = this.length;
if (len === 0) {
return this;
}
this.replace(0, len, EMPTY_ARRAY);
return this;
},
insertAt(idx, object) {
insertAt(this, idx, object);
return this;
},
removeAt(start, len) {
return removeAt(this, start, len);
},
pushObject(obj) {
return insertAt(this, this.length, obj);
},
pushObjects(objects) {
this.replace(this.length, 0, objects);
return this;
},
popObject() {
let len = this.length;
if (len === 0) {
return null;
}
let ret = objectAt(this, len - 1);
this.removeAt(len - 1, 1);
return ret;
},
shiftObject() {
if (this.length === 0) {
return null;
}
let ret = objectAt(this, 0);
this.removeAt(0);
return ret;
},
unshiftObject(obj) {
return insertAt(this, 0, obj);
},
unshiftObjects(objects) {
this.replace(0, 0, objects);
return this;
},
reverseObjects() {
let len = this.length;
if (len === 0) {
return this;
}
let objects = this.toArray().reverse();
this.replace(0, len, objects);
return this;
},
setObjects(objects) {
if (objects.length === 0) {
return this.clear();
}
let len = this.length;
this.replace(0, len, objects);
return this;
},
removeObject(obj) {
let loc = this.length || 0;
while (--loc >= 0) {
let curObject = objectAt(this, loc);
if (curObject === obj) {
this.removeAt(loc);
}
}
return this;
},
removeObjects(objects) {
beginPropertyChanges();
for (let i = objects.length - 1; i >= 0; i--) {
// SAFETY: Due to the loop structure we know this will always exist.
this.removeObject(objects[i]);
}
endPropertyChanges();
return this;
},
addObject(obj) {
let included = this.includes(obj);
if (!included) {
this.pushObject(obj);
}
return this;
},
addObjects(objects) {
beginPropertyChanges();
objects.forEach(obj => this.addObject(obj));
endPropertyChanges();
return this;
}
});
/**
Creates an `Ember.NativeArray` from an Array-like object.
Does not modify the original object's contents.
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 final definition of NativeArray removes all native methods. This is the list of removed methods
* when run in Chrome 106.
*/
/**
* These additional items must be redefined since `Omit` causes methods that return `this` to return the
* type at the time of the Omit.
*/
// This is the same as MutableArray, but removes the actual native methods that exist on Array.prototype.
/**
The NativeArray mixin contains the properties needed to make the native
Array support MutableArray and all of its dependent APIs.
@class Ember.NativeArray
@uses MutableArray
@uses Observable
@public
*/
let NativeArray = Mixin.create(MutableArray, Observable, {
objectAt(idx) {
return this[idx];
},
// primitive for array support.
replace(start, deleteCount, items = EMPTY_ARRAY) {
replaceInNativeArray(this, start, deleteCount, items);
return this;
}
});
// Remove any methods implemented natively so we don't override them
const ignore = ['length'];
NativeArray.keys().forEach(methodName => {
// SAFETY: It's safe to read unknown properties from an object
if (Array.prototype[methodName]) {
ignore.push(methodName);
}
});
NativeArray = NativeArray.without(...ignore);
let A;
A = function (arr) {
if (isEmberArray(arr)) {
// SAFETY: If it's a true native array and it is also an EmberArray then it should be an Ember NativeArray
return arr;
} else {
// SAFETY: This will return an NativeArray but TS can't infer that.
return NativeArray.apply(arr ?? []);
}
};
const emberArrayIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
get A () { return A; },
MutableArray,
get NativeArray () { return NativeArray; },
default: EmberArray,
isArray: isArray$2,
makeArray,
removeAt,
uniqBy: uniqBy$1
}, Symbol.toStringTag, { value: 'Module' });
function toBool(predicate) {
if (isProxy(predicate)) {
consumeTag(tagForProperty(predicate, 'content'));
return Boolean(get$2(predicate, 'isTruthy'));
} else if (isArray$2(predicate)) {
consumeTag(tagForProperty(predicate, '[]'));
return predicate.length !== 0;
} else if (isHTMLSafe(predicate)) {
return Boolean(predicate.toString());
} else {
return Boolean(predicate);
}
}
///////////
// Setup global context
setGlobalContext({
FEATURES: {
DEFAULT_HELPER_MANAGER: true
},
scheduleRevalidate() {
_backburner.ensureInstance();
},
toBool,
toIterator,
getProp: _getProp,
setProp: _setProp,
getPath: get$2,
setPath: set,
scheduleDestroy(destroyable, destructor) {
schedule('actions', null, destructor, destroyable);
},
scheduleDestroyed(finalizeDestructor) {
schedule('destroy', null, finalizeDestructor);
},
warnIfStyleNotTrusted(value) {
},
assert(test, msg, options) {
},
deprecate(msg, test, options) {
}
});
///////////
// Define environment delegate
class EmberEnvironmentDelegate {
enableDebugTooling = ENV._DEBUG_RENDER_TREE;
constructor(owner, isInteractive) {
this.owner = owner;
this.isInteractive = isInteractive;
}
onTransactionCommit() {}
}
/**
@module ember
*/
const disallowDynamicResolution = internalHelper(({
positional,
named
}) => {
const nameOrValueRef = positional[0];
let typeRef = named['type'];
let locRef = named['loc'];
let originalRef = named['original'];
// 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));
valueForRef(typeRef);
valueForRef(locRef);
valueForRef(originalRef);
return createComputeRef(() => {
let nameOrValue = valueForRef(nameOrValueRef);
return nameOrValue;
});
});
let helper$1;
{
helper$1 = args => {
let arg = args.positional[0];
return arg;
};
}
const inElementNullCheckHelper = internalHelper(helper$1);
const normalizeClassHelper = internalHelper(({
positional
}) => {
return createComputeRef(() => {
let classNameArg = positional[0];
let valueArg = positional[1];
let classNameParts = valueForRef(classNameArg).split('.');
let className = classNameParts[classNameParts.length - 1];
let value = valueForRef(valueArg);
if (value === true) {
return dasherize(className);
} else if (!value && value !== 0) {
return '';
} else {
return String(value);
}
});
});
/**
@module ember
*/
const resolve$1 = internalHelper(({
positional
}, owner) => {
let fullNameRef = positional[0];
let fullName = valueForRef(fullNameRef);
return createConstRef(owner.factoryFor(fullName)?.class);
});
/**
@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
*/
const trackArray = internalHelper(({
positional
}) => {
const inner = positional[0];
return createComputeRef(() => {
let iterable = valueForRef(inner);
if (isObject$1(iterable)) {
consumeTag(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
*/
const mut = internalHelper(({
positional
}) => {
let ref = positional[0];
return createInvokableRef(ref);
});
/**
@module ember
*/
/**
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
*/
const readonly = internalHelper(({
positional
}) => {
let firstArg = positional[0];
return createReadOnlyRef(firstArg);
});
/**
@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
*/
const unbound = internalHelper(({
positional,
named
}) => {
return createUnboundRef(valueForRef(positional[0]));
});
/**
@module ember
*/
const uniqueId$1 = internalHelper(() => {
// SAFETY: glimmer-vm should change the signature of createUnboundRef to use a generic
// so that the type param to `Reference<?>` can infer from the first argument.
//
// NOTE: constRef is an optimization so we don't let the VM create extra wrappers,
// tracking frames, etc.
return createConstRef(uniqueId$2());
});
// From https://gist.github.com/selfish/fef2c0ba6cdfe07af76e64cecd74888b
//
// This code should be reasonably fast, and provide a unique value every time
// it's called, which is what we need here. It produces a string formatted as a
// standard UUID, which avoids accidentally turning Ember-specific
// implementation details into an intimate API. It also ensures that the UUID
// always starts with a letter, to avoid creating invalid IDs with a numeric
// digit at the start.
function uniqueId$2() {
// @ts-expect-error this one-liner abuses weird JavaScript semantics that
// TypeScript (legitimately) doesn't like, but they're nonetheless valid and
// specced.
return ([3e7] + -1e3 + -4e3 + -2e3 + -1e11).replace(/[0-3]/g, a => (a * 4 ^ Math.random() * 16 >> (a & 2)).toString(16));
}
const MODIFIERS = ['alt', 'shift', 'meta', 'ctrl'];
const 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 isSimpleClick(event);
} else {
allowedKeys = '';
}
}
if (allowedKeys.indexOf('any') >= 0) {
return true;
}
for (let i = 0; i < MODIFIERS.length; i++) {
if (event[MODIFIERS[i] + 'Key'] && allowedKeys.indexOf(MODIFIERS[i]) === -1) {
return false;
}
}
return true;
}
let ActionHelper = {
// registeredActions is re-exported for compatibility with older plugins
// that were using this undocumented API.
registeredActions: ActionManager.registeredActions,
registerAction(actionState) {
let {
actionId
} = actionState;
ActionManager.registeredActions[actionId] = actionState;
return actionId;
},
unregisterAction(actionState) {
let {
actionId
} = actionState;
delete ActionManager.registeredActions[actionId];
}
};
class ActionState {
element;
owner;
actionId;
actionName;
actionArgs;
namedArgs;
positional;
implicitTarget;
eventName;
tag = createUpdatableTag();
constructor(element, owner, actionId, actionArgs, namedArgs, positionalArgs) {
this.element = element;
this.owner = owner;
this.actionId = actionId;
this.actionArgs = actionArgs;
this.namedArgs = namedArgs;
this.positional = positionalArgs;
this.eventName = this.getEventName();
registerDestructor$1(this, () => ActionHelper.unregisterAction(this));
}
getEventName() {
let {
on
} = this.namedArgs;
return on !== undefined ? valueForRef(on) : 'click';
}
getActionArgs() {
let result = new Array(this.actionArgs.length);
for (let i = 0; i < this.actionArgs.length; i++) {
result[i] = valueForRef(this.actionArgs[i]);
}
return result;
}
getTarget() {
let {
implicitTarget,
namedArgs
} = this;
let {
target
} = namedArgs;
return target !== undefined ? valueForRef(target) : valueForRef(implicitTarget);
}
handler(event) {
let {
actionName,
namedArgs
} = this;
let {
bubbles,
preventDefault,
allowedKeys
} = namedArgs;
let bubblesVal = bubbles !== undefined ? valueForRef(bubbles) : undefined;
let preventDefaultVal = preventDefault !== undefined ? valueForRef(preventDefault) : undefined;
let allowedKeysVal = allowedKeys !== undefined ? valueForRef(allowedKeys) : undefined;
let target = this.getTarget();
let shouldBubble = bubblesVal !== false;
if (!isAllowedEvent(event, allowedKeysVal)) {
return true;
}
if (preventDefaultVal !== false) {
event.preventDefault();
}
if (!shouldBubble) {
event.stopPropagation();
}
join(() => {
let args = this.getActionArgs();
let payload = {
args,
target,
name: null
};
if (isInvokableRef(actionName)) {
flaggedInstrument('interaction.ember-action', payload, () => {
updateRef(actionName, args[0]);
});
return;
}
if (typeof actionName === 'function') {
flaggedInstrument('interaction.ember-action', payload, () => {
actionName.apply(target, args);
});
return;
}
payload.name = actionName;
if (target.send) {
flaggedInstrument('interaction.ember-action', payload, () => {
target.send.apply(target, [actionName, ...args]);
});
} else {
flaggedInstrument('interaction.ember-action', payload, () => {
target[actionName].apply(target, args);
});
}
});
return shouldBubble;
}
}
class ActionModifierManager {
create(owner, element, _state, {
named,
positional
}) {
let actionArgs = [];
// The first two arguments are (1) `this` and (2) the action name.
// Everything else is a param.
for (let i = 2; i < positional.length; i++) {
actionArgs.push(positional[i]);
}
let actionId = uuid$1();
return new ActionState(element, owner, actionId, actionArgs, named, positional);
}
getDebugInstance() {
return null;
}
getDebugName() {
return 'action';
}
install(actionState) {
deprecateUntil(`Usage of the \`{{action}}\` modifier is deprecated. Migrate to native functions and function invocation.`, DEPRECATIONS.DEPRECATE_TEMPLATE_ACTION);
let {
element,
actionId,
positional
} = actionState;
let actionName;
let actionNameRef;
let implicitTarget;
if (positional.length > 1) {
implicitTarget = positional[0];
actionNameRef = positional[1];
if (isInvokableRef(actionNameRef)) {
actionName = actionNameRef;
} else {
actionName = valueForRef(actionNameRef);
}
}
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) {
let {
positional
} = actionState;
let actionNameRef = positional[1];
if (!isInvokableRef(actionNameRef)) {
actionState.actionName = valueForRef(actionNameRef);
}
let newEventName = actionState.getEventName();
if (newEventName !== actionState.eventName) {
this.ensureEventSetup(actionState);
actionState.eventName = actionState.getEventName();
}
}
ensureEventSetup(actionState) {
let dispatcher = actionState.owner.lookup('event_dispatcher:main');
dispatcher?.setupHandlerForEmberEvent(actionState.eventName);
}
getTag(actionState) {
return actionState.tag;
}
getDestroyable(actionState) {
return actionState;
}
}
const ACTION_MODIFIER_MANAGER = new ActionModifierManager();
const actionModifier = setInternalModifierManager(ACTION_MODIFIER_MANAGER, {});
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$1 = 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$1 = Array.isArray;
var hasOwnProperty$1 = 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$1.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$1 = this;
var nextStates = this.nextStates;
if (nextStates === null) {
return;
}
if (isArray$1(nextStates)) {
for (var i = 0; i < nextStates.length; i++) {
var child = this$1$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$1(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$1 = this;
var nextStates = this.nextStates;
if (!nextStates) {
return [];
}
var returned = [];
if (isArray$1(nextStates)) {
for (var i = 0; i < nextStates.length; i++) {
var child = this$1$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$1(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$1;
const routeRecognizer = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: RouteRecognizer
}, Symbol.toStringTag, { value: 'Module' });
function buildTransitionAborted() {
let 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();
}
}
const slice$1 = Array.prototype.slice;
const 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 (let 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) {
let len = array && array.length,
head,
queryParams;
if (len && len > 0) {
let obj = array[len - 1];
if (isQueryParamsContainer(obj)) {
queryParams = obj.queryParams;
head = slice$1.call(array, 0, len - 1);
return [head, queryParams];
}
}
// SAFETY: We confirmed that the last item isn't a QP container
return [array, null];
}
// TODO: Actually check that Dict is QueryParams
function isQueryParamsContainer(obj) {
if (obj && typeof obj === 'object') {
let cast = obj;
return 'queryParams' in cast && Object.keys(cast.queryParams).every(k => typeof k === 'string');
}
return false;
}
/**
@private
Coerces query param properties and array elements into strings.
**/
function coerceQueryParamsToString(queryParams) {
for (let key in queryParams) {
let val = queryParams[key];
if (typeof val === 'number') {
queryParams[key] = '' + val;
} else if (Array.isArray(val)) {
for (let 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) {
let [sequence, msg] = args;
router.log('Transition #' + sequence + ': ' + msg);
} else {
let [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 (let i = 0, l = array.length; i < l && callback(array[i]) !== false; i++) {
// empty intentionally
}
}
function getChangelist(oldObject, newObject) {
let key;
let results = {
all: {},
changed: {},
removed: {}
};
merge(results.all, newObject);
let 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)) {
let oldElement = oldObject[key];
let newElement = newObject[key];
if (isArray(oldElement) && isArray(newElement)) {
if (oldElement.length !== newElement.length) {
results.changed[key] = newObject[key];
didChange = true;
} else {
for (let 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;
}
const STATE_SYMBOL = `__STATE__-2619860001345920-3322w3`;
const PARAMS_SYMBOL = `__PARAMS__-261986232992830203-23323`;
const 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
*/
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 (error) {
this.promise = Promise$2.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;
let len = state.routeInfos.length;
if (len) {
this.targetName = state.routeInfos[len - 1].name;
}
for (let i = 0; i < len; ++i) {
let 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 => {
let error = this.router.transitionDidError(result, this);
throw error;
}, promiseLabel('Handle Abort'));
} else {
this.promise = Promise$2.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();
let 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 (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();
let 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() {
let router = this.router;
return this.promise.catch(function (reason) {
if (router.activeTransition) {
return router.activeTransition.followRedirects();
}
return Promise$2.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.
*/
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;
}
let ROUTE_INFOS = new WeakMap();
function toReadOnlyRouteInfo(routeInfos, queryParams = {}, options = {
includeAttributes: false,
localizeMapUpdates: false
}) {
const LOCAL_ROUTE_INFOS = new WeakMap();
return routeInfos.map((info, i) => {
let {
name,
params,
paramNames,
context,
route
} = info;
// SAFETY: This should be safe since it is just for use as a key
let key = info;
if (ROUTE_INFOS.has(key) && options.includeAttributes) {
let routeInfo = ROUTE_INFOS.get(key);
routeInfo = attachMetadata(route, routeInfo);
let routeInfoWithAttribute = createRouteInfoWithAttributes(routeInfo, context);
LOCAL_ROUTE_INFOS.set(key, routeInfo);
if (!options.localizeMapUpdates) {
ROUTE_INFOS.set(key, routeInfoWithAttribute);
}
return routeInfoWithAttribute;
}
const routeInfosRef = options.localizeMapUpdates ? LOCAL_ROUTE_INFOS : ROUTE_INFOS;
let routeInfo = {
find(predicate, thisArg) {
let publicInfo;
let arr = [];
if (predicate.length === 3) {
arr = routeInfos.map(
// SAFETY: This should be safe since it is just for use as a key
info => routeInfosRef.get(info));
}
for (let i = 0; routeInfos.length > i; i++) {
// SAFETY: This should be safe since it is just for use as a key
publicInfo = routeInfosRef.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() {
let parent = routeInfos[i - 1];
if (parent === undefined) {
return null;
}
// SAFETY: This should be safe since it is just for use as a key
return routeInfosRef.get(parent);
},
get child() {
let child = routeInfos[i + 1];
if (child === undefined) {
return null;
}
// SAFETY: This should be safe since it is just for use as a key
return routeInfosRef.get(child);
},
get localName() {
let parts = this.name.split('.');
return parts[parts.length - 1];
},
get params() {
return params;
},
get queryParams() {
return queryParams;
}
};
if (options.includeAttributes) {
routeInfo = createRouteInfoWithAttributes(routeInfo, context);
}
// SAFETY: This should be safe since it is just for use as a key
LOCAL_ROUTE_INFOS.set(info, routeInfo);
if (!options.localizeMapUpdates) {
// SAFETY: This should be safe since it is just for use as a key
ROUTE_INFOS.set(info, routeInfo);
}
return routeInfo;
});
}
function createRouteInfoWithAttributes(routeInfo, context) {
let 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) {
let 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 Promise$2.resolve(this.context);
}
serialize(_context) {
return this.params || {};
}
resolve(transition) {
return Promise$2.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) {
let params = this.serialize(resolvedContext);
if (transition) {
this.stashResolvedModel(transition, resolvedContext);
transition[PARAMS_SYMBOL] = transition[PARAMS_SYMBOL] || {};
transition[PARAMS_SYMBOL][this.name] = params;
}
let context;
let contextsMatch = resolvedContext === this.context;
if ('context' in this || !contextsMatch) {
context = resolvedContext;
}
// SAFETY: Since this is just for lookup, it should be safe
let cached = ROUTE_INFOS.get(this);
let resolved = new ResolvedRouteInfo(this.router, this.name, this.paramNames, params, this.route, context);
if (cached !== undefined) {
// SAFETY: This is potentially a bit risker, but for what we're doing, it should be ok.
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;
}
let 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);
}
let result;
if (this.route) {
if (this.route.beforeModel !== undefined) {
result = this.route.beforeModel(transition);
}
}
if (isTransition(result)) {
result = null;
}
return Promise$2.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.
let name = this.name;
this.stashResolvedModel(transition, resolvedModel);
let result;
if (this.route !== undefined) {
if (this.route.afterModel !== undefined) {
result = this.route.afterModel(resolvedModel, transition);
}
}
result = prepareResult(result);
return Promise$2.resolve(result).then(() => {
// Ignore the fulfilled value returned from afterModel.
// Return the value stashed in resolvedModels, which
// might have been swapped out in afterModel.
// SAFTEY: We expect this to be of type T, though typing it as such is challenging.
return transition.resolvedModels[name];
});
}
stashResolvedModel(transition, resolvedModel) {
transition.resolvedModels = transition.resolvedModels || {};
// SAFETY: It's unfortunate that we have to do this cast. It should be safe though.
transition.resolvedModels[this.name] = resolvedModel;
}
fetchRoute() {
let 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 = Promise$2.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;
}
}
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 Promise$2.resolve(this);
}
}
class UnresolvedRouteInfoByParam extends InternalRouteInfo {
constructor(router, name, paramNames, params, route) {
super(router, name, paramNames, route);
this.params = {};
if (params) {
this.params = params;
}
}
getModel(transition) {
let fullParams = this.params;
if (transition && transition[QUERY_PARAMS_SYMBOL]) {
fullParams = {};
merge(fullParams, this.params);
fullParams.queryParams = transition[QUERY_PARAMS_SYMBOL];
}
let route = this.route;
let result;
// FIXME: Review these casts
if (route.deserialize) {
result = route.deserialize(fullParams, transition);
} else if (route.model) {
result = route.model(fullParams, transition);
}
if (result && isTransition(result)) {
result = undefined;
}
return Promise$2.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) {
let {
paramNames,
context
} = this;
if (!model) {
// SAFETY: By the time we serialize, we expect to be resolved.
// This may not be an entirely safe assumption though no tests fail.
model = context;
}
let 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;
}
let name = paramNames[0];
if (/_id$/.test(name)) {
// SAFETY: Model is supposed to extend IModel already
object[name] = model.id;
} else {
object[name] = model;
}
return object;
}
}
function paramsMatch(a, b) {
if (a === b) {
// Both are identical, may both be undefined
return true;
}
if (!a || !b) {
// Only one is undefined, already checked they aren't identical
return false;
}
// Note: this assumes that both params have the same
// number of keys, but since we're comparing the
// same routes, they should.
for (let 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
let routeInfos = currentState.routeInfos;
let errorHandlerIndex = transition.resolveIndex >= routeInfos.length ? routeInfos.length - 1 : transition.resolveIndex;
let 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;
}
let routeInfo = currentState.routeInfos[transition.resolveIndex];
let callback = proceed.bind(null, currentState, transition);
return routeInfo.resolve(transition).then(callback, null, currentState.promiseLabel('Proceed'));
}
function proceed(currentState, transition, resolvedRouteInfo) {
let 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.
let {
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) {
let 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.
let params = this.params;
forEach(this.routeInfos, routeInfo => {
params[routeInfo.name] = routeInfo.params || {};
return true;
});
transition.resolveIndex = 0;
let callback = resolveOneRouteInfo.bind(null, this, transition);
let errorHandler = handleError.bind(null, this, transition);
// The prelude RSVP.resolve() async moves us into the promise land.
return Promise$2.resolve(null, this.promiseLabel('Start transition')).then(callback, null, this.promiseLabel('Resolve route')).catch(errorHandler, this.promiseLabel('Handle error')).then(() => this);
}
}
class TransitionError {
constructor(error, route, wasAborted, state) {
this.error = error;
this.route = route;
this.wasAborted = wasAborted;
this.state = state;
}
}
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) {
let handlers = this.router.recognizer.handlersFor(this.name);
let targetRouteName = handlers[handlers.length - 1].handler;
return this.applyToHandlers(oldState, handlers, targetRouteName, isIntermediate, false);
}
applyToHandlers(oldState, parsedHandlers, targetRouteName, isIntermediate, checkingIfActive) {
let i, len;
let newState = new TransitionState();
let objects = this.contexts.slice(0);
let 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) {
let result = parsedHandlers[i];
let name = result.handler;
let oldHandlerInfo = oldState.routeInfos[i];
let 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,
// SAFETY: This seems to imply that it would be resolved, but it's unclear if that's actually the case.
newHandlerInfo.context);
let 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;
}
let handlerToUse = oldHandlerInfo;
if (i >= invalidateIndex || newHandlerInfo.shouldSupersede(oldHandlerInfo)) {
invalidateIndex = Math.min(i, invalidateIndex);
handlerToUse = newHandlerInfo;
}
if (isIntermediate && !checkingIfActive) {
handlerToUse = handlerToUse.becomeResolved(null,
// SAFETY: This seems to imply that it would be resolved, but it's unclear if that's actually the case.
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 (let i = invalidateIndex, l = handlerInfos.length; i < l; ++i) {
let handlerInfo = handlerInfos[i];
if (handlerInfo.isResolved) {
let {
name,
params,
route,
paramNames
} = handlerInfos[i];
handlerInfos[i] = new UnresolvedRouteInfoByParam(this.router, name, paramNames, params, route);
}
}
}
getHandlerInfoForDynamicSegment(name, names, objects, oldHandlerInfo, _targetRouteName, i) {
let 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) {
let preTransitionHandlerInfo = this.preTransitionState.routeInfos[i];
objectToUse = preTransitionHandlerInfo === null || preTransitionHandlerInfo === void 0 ? void 0 : 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) {
let params = {};
// Soak up all the provided string/numbers
let numNames = names.length;
let missingParams = [];
while (numNames--) {
// Only use old params if the names match with the new handler
let oldParams = oldHandlerInfo && name === oldHandlerInfo.name && oldHandlerInfo.params || {};
let peek = objects[objects.length - 1];
let 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);
}
}
const UnrecognizedURLError = function () {
UnrecognizedURLError.prototype = Object.create(Error.prototype);
UnrecognizedURLError.prototype.constructor = UnrecognizedURLError;
function UnrecognizedURLError(message) {
let 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) {
let newState = new TransitionState();
let results = this.router.recognizer.recognize(this.url),
i,
len;
if (!results) {
throw new UnrecognizedURLError(this.url);
}
let statesDiffer = false;
let _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) {
let result = results[i];
let name = result.handler;
let paramNames = [];
if (this.router.recognizer.hasRoute(name)) {
paramNames = this.router.recognizer.handlersFor(name)[i].names;
}
let newRouteInfo = new UnresolvedRouteInfoByParam(this.router, name, paramNames, result.params);
let 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);
}
let 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();
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 (let i = routes.length - 1, proceed = true; i >= 0 && proceed; --i) {
let route = routes[i];
let 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).
let 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) {
let intent = new URLTransitionIntent(this, url);
let newState = this.generateNewState(intent);
if (newState === null) {
return newState;
}
let readonlyInfos = toReadOnlyRouteInfo(newState.routeInfos, newState.queryParams, {
includeAttributes: false,
localizeMapUpdates: true
});
return readonlyInfos[readonlyInfos.length - 1];
}
recognizeAndLoad(url) {
let intent = new URLTransitionIntent(this, url);
let newState = this.generateNewState(intent);
if (newState === null) {
return Promise$2.reject(`URL ${url} was not recognized`);
}
let newTransition = new Transition(this, intent, newState, undefined);
return newTransition.then(() => {
let routeInfosWithAttributes = toReadOnlyRouteInfo(newState.routeInfos, newTransition[QUERY_PARAMS_SYMBOL], {
includeAttributes: true,
localizeMapUpdates: false
});
return routeInfosWithAttributes[routeInfosWithAttributes.length - 1];
});
}
generateNewState(intent) {
try {
return intent.applyToState(this.state, false);
} catch (e) {
return null;
}
}
getTransitionByIntent(intent, isIntermediate) {
let wasTransitioning = !!this.activeTransition;
let oldState = wasTransitioning ? this.activeTransition[STATE_SYMBOL] : this.state;
let newTransition;
let newState = intent.applyToState(oldState, isIntermediate);
let 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) {
let newTransition = this.queryParamsTransition(queryParamChangelist, wasTransitioning, oldState, newState);
newTransition.queryParamsOnly = true;
// SAFETY: The returned OpaqueTransition should actually be this.
return newTransition;
}
// No-op. No need to create a new transition.
return this.activeTransition || new Transition(this, undefined, undefined);
}
if (isIntermediate) {
let 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) {
let lastArg = modelsArray[modelsArray.length - 1];
let queryParams = {};
if (lastArg && Object.prototype.hasOwnProperty.call(lastArg, 'queryParams')) {
// We just checked this.
// TODO: Use an assertion?
queryParams = modelsArray.pop().queryParams;
}
let 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.
let {
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,
// SAFETY: We know this to be the case since we removed the last item if it was QPs
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.');
let 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 Promise$2.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)) {
let 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) {
let partition = this.partitionRoutes(this.state, newState);
let 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);
}
}
}
let oldState = this.oldState = this.state;
this.state = newState;
let 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) {
let 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) {
let oldRouteInfos = oldState.routeInfos;
let newRouteInfos = newState.routeInfos;
let routes = {
updatedContext: [],
exited: [],
entered: [],
unchanged: [],
reset: []
};
let routeChanged,
contextChanged = false,
i,
l;
for (i = 0, l = newRouteInfos.length; i < l; i++) {
let 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) {
let urlMethod = transition.urlMethod;
if (!urlMethod) {
return;
}
let {
routeInfos
} = state;
let {
name: routeName
} = routeInfos[routeInfos.length - 1];
let params = {};
for (let i = routeInfos.length - 1; i >= 0; --i) {
let routeInfo = routeInfos[i];
merge(params, routeInfo.params);
if (routeInfo.route.inaccessibleByURL) {
urlMethod = null;
}
}
if (urlMethod) {
params.queryParams = transition._visibleQueryParams || state.queryParams;
let 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
let 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
let 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.
let 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.
let 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 (let k in newQueryParams) {
if (newQueryParams.hasOwnProperty(k) && newQueryParams[k] === null) {
delete newQueryParams[k];
}
}
let finalQueryParamsArray = [];
this.triggerEvent(resolvedHandlers, true, 'finalizeQueryParamChange', [newQueryParams, finalQueryParamsArray, transition]);
if (transition) {
transition._visibleQueryParams = {};
}
let finalQueryParams = {};
for (let i = 0, len = finalQueryParamsArray.length; i < len; ++i) {
let qp = finalQueryParamsArray[i];
finalQueryParams[qp.key] = qp.value;
if (transition && qp.visible !== false) {
transition._visibleQueryParams[qp.key] = qp.value;
}
}
return finalQueryParams;
}
toReadOnlyInfos(newTransition, newState) {
let 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) {
let fromInfos = toReadOnlyRouteInfo(oldRouteInfos, Object.assign({}, this._lastQueryParams), {
includeAttributes: true,
localizeMapUpdates: false
});
newTransition.from = fromInfos[fromInfos.length - 1] || null;
}
}
toInfos(newTransition, newRouteInfos, includeAttributes = false) {
if (newTransition !== undefined && newRouteInfos.length > 0) {
let toInfos = toReadOnlyRouteInfo(newRouteInfos, Object.assign({}, newTransition[QUERY_PARAMS_SYMBOL]), {
includeAttributes,
localizeMapUpdates: false
});
newTransition.to = toInfos[toInfos.length - 1] || null;
}
}
notifyExistingHandlers(newState, newTransition) {
let 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) {
let 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) {
let previousTransition = this.activeTransition;
let state = previousTransition ? previousTransition[STATE_SYMBOL] : this.state;
let routeInfos = state.routeInfos;
if (pivotRoute === undefined) {
pivotRoute = routeInfos[0].route;
}
log(this, 'Starting a refresh transition');
let name = routeInfos[routeInfos.length - 1].name;
let intent = new NamedTransitionIntent(this, name, pivotRoute, [], this._changedQueryParams || state.queryParams);
let 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) {
let 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.
let intent = new NamedTransitionIntent(this, routeName, undefined, suppliedParams);
let state = intent.applyToState(this.state, false);
let params = {};
for (let i = 0, len = state.routeInfos.length; i < len; ++i) {
let routeInfo = state.routeInfos[i];
let routeParams = routeInfo.serialize();
merge(params, routeParams);
}
params.queryParams = queryParams;
return this.recognizer.generate(routeName, params);
}
applyIntent(routeName, contexts) {
let intent = new NamedTransitionIntent(this, routeName, undefined, contexts);
let state = this.activeTransition && this.activeTransition[STATE_SYMBOL] || this.state;
return intent.applyToState(state, false);
}
isActiveIntent(routeName, contexts, queryParams, _state) {
let state = _state || this.state,
targetRouteInfos = state.routeInfos,
routeInfo,
len;
if (!targetRouteInfos.length) {
return false;
}
let targetHandler = targetRouteInfos[targetRouteInfos.length - 1].name;
let recognizerHandlers = this.recognizer.handlersFor(targetHandler);
let 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;
}
let testState = new TransitionState();
testState.routeInfos = targetRouteInfos.slice(0, index + 1);
recognizerHandlers = recognizerHandlers.slice(0, index + 1);
let intent = new NamedTransitionIntent(this, targetHandler, undefined, contexts);
let newState = intent.applyToHandlers(testState, recognizerHandlers, targetHandler, true, true);
let routesEqual = routeInfosEqual(newState.routeInfos, testState.routeInfos);
if (!queryParams || !routesEqual) {
return routesEqual;
}
// Get a hash of QPs that will still be active on new route
let activeQPsOnNewHandler = {};
merge(activeQPsOnNewHandler, queryParams);
let activeQueryParams = state.queryParams;
for (let key in activeQueryParams) {
if (activeQueryParams.hasOwnProperty(key) && activeQPsOnNewHandler.hasOwnProperty(key)) {
activeQPsOnNewHandler[key] = activeQueryParams[key];
}
}
return routesEqual && !getChangelist(activeQPsOnNewHandler, queryParams);
}
isActive(routeName, ...args) {
let [contexts, queryParams] = extractQueryParams(args);
return this.isActiveIntent(routeName, contexts, queryParams);
}
trigger(name, ...args) {
this.triggerEvent(this.currentRouteInfos, false, name, args);
}
}
function routeInfosEqual(routeInfos, otherRouteInfos) {
if (routeInfos.length !== otherRouteInfos.length) {
return false;
}
for (let i = 0, len = routeInfos.length; i < len; ++i) {
// SAFETY: Just casting for comparison
if (routeInfos[i] !== otherRouteInfos[i]) {
return false;
}
}
return true;
}
function routeInfosSameExceptQueryParams(routeInfos, otherRouteInfos) {
if (routeInfos.length !== otherRouteInfos.length) {
return false;
}
for (let 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) {
// Both identical or both undefined
return true;
}
if (!params || !otherParams) {
// One is falsy but other is not
return false;
}
let keys = Object.keys(params);
let otherKeys = Object.keys(otherParams);
if (keys.length !== otherKeys.length) {
return false;
}
for (let i = 0, len = keys.length; i < len; ++i) {
let key = keys[i];
if (params[key] !== otherParams[key]) {
return false;
}
}
return true;
}
const routerJs = /*#__PURE__*/Object.defineProperty({
__proto__: null,
InternalRouteInfo,
InternalTransition: Transition,
PARAMS_SYMBOL,
QUERY_PARAMS_SYMBOL,
STATE_SYMBOL,
TransitionError,
TransitionState,
default: Router,
logAbort
}, Symbol.toStringTag, { value: 'Module' });
const ALL_PERIODS_REGEX = /\./g;
function extractRouteArgs(args) {
// SAFETY: This should just be the same thing
args = args.slice();
let possibleOptions = args[args.length - 1];
let queryParams;
if (isRouteOptions(possibleOptions)) {
args.pop(); // Remove options
queryParams = possibleOptions.queryParams;
} else {
queryParams = {};
}
let routeName;
if (typeof args[0] === 'string') {
routeName = args.shift();
}
// SAFTEY: We removed the name and options if they existed, only models left.
let models = args;
return {
routeName,
models,
queryParams
};
}
function getActiveTargetName(router) {
let routeInfos = router.activeTransition ? router.activeTransition[STATE_SYMBOL].routeInfos : router.state.routeInfos;
let lastRouteInfo = routeInfos[routeInfos.length - 1];
return lastRouteInfo.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.
let routeInfo = routeInfos[routeInfos.length - 1];
let targetRouteName = routeInfo.name;
let recogHandlers = router._routerMicrolib.recognizer.handlersFor(targetRouteName);
let dynamicParent;
for (let i = 0; i < routeInfos.length; ++i) {
let routeInfo = routeInfos[i];
let names = recogHandlers[i].names;
if (names.length) {
dynamicParent = routeInfo;
}
routeInfo['_names'] = names;
let 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)
let prefixParts = prefix.split('.');
let currPrefix = '';
for (let i = 0; i < prefixParts.length; i++) {
let 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) {
let suffixes = '';
for (let part of parts) {
let cacheValuePrefix = _calculateCacheValuePrefix(prefix, part);
let value;
if (values) {
if (cacheValuePrefix && cacheValuePrefix in values) {
let partRemovedPrefix = part.indexOf(cacheValuePrefix) === 0 ? part.substring(cacheValuePrefix.length + 1) : part;
value = get$2(values[cacheValuePrefix], partRemovedPrefix);
} else {
value = get$2(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) {
let qpMap = {};
for (let queryParam of queryParams) {
accumulateQueryParamDescriptors(queryParam, qpMap);
}
return qpMap;
}
function accumulateQueryParamDescriptors(_desc, accum) {
let desc = typeof _desc === 'string' ? {
[_desc]: {
as: null
}
} : _desc;
for (let key in desc) {
if (!Object.prototype.hasOwnProperty.call(desc, key)) {
return;
}
let _singleDesc = desc[key];
let singleDesc = typeof _singleDesc === 'string' ? {
as: _singleDesc
} : _singleDesc;
let partialVal = accum[key] || {
as: null,
scope: 'model'
};
let val = {
...partialVal,
...singleDesc
};
accum[key] = val;
}
}
/*
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) {
let routeName;
let owner = getOwner$2(route);
let prefix = owner.mountPoint;
// only alter the routeName if it's actually referencing a route.
if (owner.routable && typeof args[0] === 'string') {
routeName = args[0];
if (resemblesURL(routeName)) {
throw new Error('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) {
let aCount = 0;
let bCount = 0;
for (let kA in a) {
if (Object.prototype.hasOwnProperty.call(a, kA)) {
if (a[kA] !== b[kA]) {
return false;
}
aCount++;
}
}
for (let kB in b) {
if (Object.prototype.hasOwnProperty.call(b, kB)) {
bCount++;
}
}
return aCount === bCount;
}
function isRouteOptions(value) {
if (value && typeof value === 'object') {
let qps = value.queryParams;
if (qps && typeof qps === 'object') {
return Object.keys(qps).every(k => typeof k === 'string');
}
}
return false;
}
const emberRoutingLibUtils = /*#__PURE__*/Object.defineProperty({
__proto__: null,
calculateCacheKey,
extractRouteArgs,
getActiveTargetName,
normalizeControllerQueryParams,
prefixRouteNameArg,
resemblesURL,
shallowEqual,
stashParamNames
}, Symbol.toStringTag, { value: 'Module' });
class RouterState {
router;
emberRouter;
routerJsState;
constructor(emberRouter, router, routerJsState) {
this.emberRouter = emberRouter;
this.router = router;
this.routerJsState = routerJsState;
}
isActiveIntent(routeName, models, queryParams) {
let state = this.routerJsState;
if (!this.router.isActiveIntent(routeName, models, undefined, state)) {
return false;
}
if (queryParams !== undefined && Object.keys(queryParams).length > 0) {
let visibleQueryParams = Object.assign({}, queryParams);
this.emberRouter._prepareQueryParams(routeName, models, visibleQueryParams);
return shallowEqual(visibleQueryParams, state.queryParams);
}
return true;
}
}
const emberRoutingLibRouterState = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: RouterState
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/object
*/
function expandPropertiesToArray(predicateName, properties) {
let expandedProperties = [];
function extractProperty(entry) {
expandedProperties.push(entry);
}
for (let property of properties) {
expandProperties(property, extractProperty);
}
return expandedProperties;
}
function generateComputedWithPredicate(name, predicate) {
return (dependentKey, ...additionalDependentKeys) => {
let properties = [dependentKey, ...additionalDependentKeys];
let dependentKeys = expandPropertiesToArray(name, properties);
let computedFunc = computed(...dependentKeys, function () {
let lastIdx = dependentKeys.length - 1;
for (let i = 0; i < lastIdx; i++) {
// SAFETY: `i` is derived from the length of `dependentKeys`
let value = get$2(this, dependentKeys[i]);
if (!predicate(value)) {
return value;
}
}
// SAFETY: `lastIdx` is derived from the length of `dependentKeys`
return get$2(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) {
return computed(`${dependentKey}.length`, function () {
return isEmpty(get$2(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) {
return computed(`${dependentKey}.length`, function () {
return !isEmpty(get$2(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) {
return computed(dependentKey, function () {
return isNone(get$2(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) {
return computed(dependentKey, function () {
return !get$2(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) {
return computed(dependentKey, function () {
return Boolean(get$2(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) {
return computed(dependentKey, function () {
let value = get$2(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) {
return computed(dependentKey, function () {
return get$2(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) {
return computed(dependentKey, function () {
return get$2(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) {
return computed(dependentKey, function () {
return get$2(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) {
return computed(dependentKey, function () {
return get$2(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) {
return computed(dependentKey, function () {
return get$2(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
*/
const 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
*/
const 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
*/
function oneWay(dependentKey) {
return 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) {
return 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) {
return computed(dependentKey, {
get(key) {
return get$2(this, dependentKey);
},
set(key, value) {
set(this, dependentKey, value);
return value;
}
});
}
const emberObjectLibComputedComputedMacros = /*#__PURE__*/Object.defineProperty({
__proto__: null,
and,
bool,
deprecatingAlias,
empty,
equal,
gt,
gte,
lt,
lte,
match,
none,
not,
notEmpty,
oneWay,
or,
readOnly
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/object
*/
function isNativeOrEmberArray(obj) {
return Array.isArray(obj) || EmberArray.detect(obj);
}
function reduceMacro(dependentKey, callback, initialValue, name) {
return computed(`${dependentKey}.[]`, function () {
let arr = get$2(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
let propertyName;
if (/@each/.test(dependentKey)) {
propertyName = dependentKey.replace(/\.@each.*$/, '');
} else {
propertyName = dependentKey;
dependentKey += '.[]';
}
return computed(dependentKey, ...additionalDependentKeys, function () {
let value = get$2(this, propertyName);
if (isNativeOrEmberArray(value)) {
return A(callback.call(this, value));
} else {
return A();
}
}).readOnly();
}
function multiArrayMacro(_dependentKeys, callback, name) {
let dependentKeys = _dependentKeys.map(key => `${key}.[]`);
return computed(...dependentKeys, function () {
return 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) {
return reduceMacro(dependentKey, (sum, item) => sum + item, 0);
}
/**
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) {
return reduceMacro(dependentKey, (max, item) => Math.max(max, item), -Infinity);
}
/**
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) {
return reduceMacro(dependentKey, (min, item) => Math.min(min, item), Infinity);
}
/**
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, additionalDependentKeysOrCallback, callback) {
let additionalDependentKeys;
if (typeof additionalDependentKeysOrCallback === 'function') {
callback = additionalDependentKeysOrCallback;
additionalDependentKeys = [];
} else {
additionalDependentKeys = additionalDependentKeysOrCallback;
}
const cCallback = callback;
return arrayMacro(dependentKey, additionalDependentKeys, function (value) {
// This is so dumb...
return Array.isArray(value) ? value.map(cCallback, this) : value.map(cCallback, 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) {
return map(`${dependentKey}.@each.${propertyKey}`, item => get$2(item, propertyKey));
}
/**
Filters the array by the callback, like the `Array.prototype.filter` method.
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);
```
In the callback, return a truthy value that coerces to true to keep the
element, or a falsy to reject it.
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, additionalDependentKeysOrCallback, callback) {
let additionalDependentKeys;
if (typeof additionalDependentKeysOrCallback === 'function') {
callback = additionalDependentKeysOrCallback;
additionalDependentKeys = [];
} else {
additionalDependentKeys = additionalDependentKeysOrCallback;
}
const cCallback = callback;
return arrayMacro(dependentKey, additionalDependentKeys, function (value) {
// This is a really silly way to keep TS happy
return Array.isArray(value) ? value.filter(cCallback, this) : value.filter(cCallback, 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) {
let callback;
if (arguments.length === 2) {
callback = item => get$2(item, propertyKey);
} else {
callback = item => get$2(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(dependentKey, ...additionalDependentKeys) {
let args = [dependentKey, ...additionalDependentKeys];
return multiArrayMacro(args, function (dependentKeys) {
let uniq = A();
let seen = new Set();
dependentKeys.forEach(dependentKey => {
let value = get$2(this, dependentKey);
if (isNativeOrEmberArray(value)) {
value.forEach(item => {
if (!seen.has(item)) {
seen.add(item);
uniq.push(item);
}
});
}
});
return 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) {
return computed(`${dependentKey}.[]`, function () {
let list = get$2(this, dependentKey);
return isNativeOrEmberArray(list) ? uniqBy$1(list, propertyKey) : 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
*/
let 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
*/
function intersect(dependentKey, ...additionalDependentKeys) {
let args = [dependentKey, ...additionalDependentKeys];
return multiArrayMacro(args, function (dependentKeys) {
let arrays = dependentKeys.map(dependentKey => {
let array = get$2(this, dependentKey);
return Array.isArray(array) ? array : [];
});
let firstArray = arrays.pop();
let results = firstArray.filter(candidate => {
for (let array of arrays) {
let found = false;
for (let item of array) {
if (item === candidate) {
found = true;
break;
}
}
if (found === false) {
return false;
}
}
return true;
});
return A(results);
});
}
/**
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) {
return computed(`${setAProperty}.[]`, `${setBProperty}.[]`, function () {
let setA = get$2(this, setAProperty);
let setB = get$2(this, setBProperty);
if (!isNativeOrEmberArray(setA)) {
return A();
}
if (!isNativeOrEmberArray(setB)) {
return 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(dependentKey, ...additionalDependentKeys) {
let dependentKeys = [dependentKey, ...additionalDependentKeys];
return multiArrayMacro(dependentKeys, function () {
let res = dependentKeys.map(key => {
let val = get$2(this, key);
return val === undefined ? null : val;
});
return A(res);
});
}
// (UN)SAFETY: we use `any` here to match how TS defines the sorting for arrays.
// Additionally, since we're using it with *decorators*, we don't have any way
// to plumb through the relationship between the types in a way that would be
// variance-safe.
/**
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, additionalDependentKeysOrDefinition, sortDefinition) {
let additionalDependentKeys;
let sortDefinitionOrString;
if (Array.isArray(additionalDependentKeysOrDefinition)) {
additionalDependentKeys = additionalDependentKeysOrDefinition;
sortDefinitionOrString = sortDefinition;
} else {
additionalDependentKeys = [];
sortDefinitionOrString = additionalDependentKeysOrDefinition;
}
if (typeof sortDefinitionOrString === 'function') {
return customSort(itemsKey, additionalDependentKeys, sortDefinitionOrString);
} else {
return propertySort(itemsKey, sortDefinitionOrString);
}
}
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) {
let cp = autoComputed(function (key) {
let sortProperties = get$2(this, sortPropertiesKey);
let itemsKeyIsAtThis = itemsKey === '@this';
let normalizedSortProperties = normalizeSortProperties(sortProperties);
let items = itemsKeyIsAtThis ? this : get$2(this, itemsKey);
if (!isNativeOrEmberArray(items)) {
return A();
}
if (normalizedSortProperties.length === 0) {
return A(items.slice());
} else {
return sortByNormalizedSortProperties(items, normalizedSortProperties);
}
}).readOnly();
return cp;
}
function normalizeSortProperties(sortProperties) {
let callback = p => {
let [prop, direction] = p.split(':');
direction = direction || 'asc';
// SAFETY: There will always be at least one value returned by split
return [prop, direction];
};
// This nonsense is necessary since technically the two map implementations diverge.
return Array.isArray(sortProperties) ? sortProperties.map(callback) : sortProperties.map(callback);
}
function sortByNormalizedSortProperties(items, normalizedSortProperties) {
return A(items.slice().sort((itemA, itemB) => {
for (let [prop, direction] of normalizedSortProperties) {
let result = compare(get$2(itemA, prop), get$2(itemB, prop));
if (result !== 0) {
return direction === 'desc' ? -1 * result : result;
}
}
return 0;
}));
}
const emberObjectLibComputedReduceComputedMacros = /*#__PURE__*/Object.defineProperty({
__proto__: null,
collect,
filter,
filterBy,
intersect,
map,
mapBy,
max,
min,
setDiff,
sort,
sum,
union,
uniq,
uniqBy
}, Symbol.toStringTag, { value: 'Module' });
const emberObjectComputed = /*#__PURE__*/Object.defineProperty({
__proto__: null,
alias,
and,
bool,
collect,
default: ComputedProperty,
deprecatingAlias,
empty,
equal,
expandProperties,
filter,
filterBy,
gt,
gte,
intersect,
lt,
lte,
map,
mapBy,
match,
max,
min,
none,
not,
notEmpty,
oneWay,
or,
readOnly,
reads: oneWay,
setDiff,
sort,
sum,
union,
uniq,
uniqBy
}, Symbol.toStringTag, { value: 'Module' });
/**
Ember’s dependency injection system is built on the idea of an "owner": an
object responsible for managing items which can be registered and looked up
with the system.
This module does not provide any concrete instances of owners. Instead, it
defines the core type, `Owner`, which specifies the public API contract for an
owner. The primary concrete implementations of `Owner` are `EngineInstance`,
from `@ember/engine/instance`, and its `ApplicationInstance` subclass, from
`@ember/application/instance`.
Along with `Owner` itself, this module provides a number of supporting types
related to Ember's DI system:
- `Factory`, Ember's primary interface for something which can create class
instances registered with the DI system.
- `FactoryManager`, an interface for inspecting a `Factory`'s class.
- `Resolver`, an interface defining the contract for the object responsible
for mapping string names to the corresponding classes. For example, when you
write `@service('session')`, a resolver is responsible to map that back to
the `Session` service class in your codebase. Normally, this is handled for
you automatically with `ember-resolver`, which is the main implementor of
this interface.
For more details on each, see their per-item docs.
@module @ember/owner
@public
*/
// NOTE: this documentation appears here instead of at the definition site so
// it can appear correctly in both API docs and for TS, while providing a richer
// internal representation for Ember's own usage.
/**
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/owner';
// Usage:
//
// <PlayAudio @audioType={{@model.audioType}} @audioFile={{@model.file}}/>
//
export default class extends Component {
get audioService() {
return getOwner(this)?.lookup(`service:${this.args.audioType}`);
}
@action
onPlay() {
this.audioService?.play(this.args.audioFile);
}
}
```
@method getOwner
@static
@for @ember/owner
@param {Object} object An object with an owner.
@return {Object} An owner object.
@since 2.3.0
@public
*/
// SAFETY: the cast here is necessary, instead of using an assignment, because
// TS (not incorrectly! Nothing expressly relates them) does not see that the
// `InternalOwner` and `Owner` do actually have identical constraints on their
// relations to the `DIRegistry`.
const getOwner$1 = getOwner$2;
const emberOwnerIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
getOwner: getOwner$1,
setOwner: setOwner$1
}, Symbol.toStringTag, { value: 'Module' });
/**
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 {
cache;
constructor() {
this.cache = new Map();
}
has(bucketKey) {
return this.cache.has(bucketKey);
}
stash(bucketKey, key, value) {
let 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;
}
let bucket = this.cache.get(bucketKey);
if (bucket.has(prop)) {
return bucket.get(prop);
} else {
return defaultValue;
}
}
}
const emberRoutingLibCache = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: BucketCache
}, Symbol.toStringTag, { value: 'Module' });
let uuid = 0;
function isCallback(value) {
return typeof value === 'function';
}
class DSLImpl {
parent;
matches;
enableLoadingSubstates;
explicitIndex = false;
options;
constructor(name = null, options) {
this.parent = name;
this.enableLoadingSubstates = Boolean(options && options.enableLoadingSubstates);
this.matches = [];
this.options = options;
}
route(name, _options, _callback) {
let options;
let callback = null;
let dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`;
if (isCallback(_options)) {
options = {};
callback = _options;
} else if (isCallback(_callback)) {
options = _options;
callback = _callback;
} else {
options = _options || {};
}
if (this.enableLoadingSubstates) {
createRoute(this, `${name}_loading`, {
resetNamespace: options.resetNamespace
});
createRoute(this, `${name}_error`, {
resetNamespace: options.resetNamespace,
path: dummyErrorRoute
});
}
if (callback) {
let fullName = getFullName(this, name, options.resetNamespace);
let 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) {
let parts = name.split('.');
if (this.options.engineInfo) {
let localFullName = name.slice(this.options.engineInfo.fullName.length + 1);
let 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() {
let dslMatches = this.matches;
if (!this.explicitIndex) {
this.route('index', {
path: '/'
});
}
return match => {
for (let i = 0; i < dslMatches.length; i += 3) {
match(dslMatches[i]).to(dslMatches[i + 1], dslMatches[i + 2]);
}
};
}
mount(_name, options = {}) {
let engineRouteMap = this.options.resolveRouteMap(_name);
let name = _name;
if (options.as) {
name = options.as;
}
let fullName = getFullName(this, name, options.resetNamespace);
let engineInfo = {
name: _name,
instanceId: uuid++,
mountPoint: fullName,
fullName
};
let path = options.path;
if (typeof path !== 'string') {
path = `/${name}`;
}
let callback;
let dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`;
if (engineRouteMap) {
let shouldResetEngineInfo = false;
let oldEngineInfo = this.options.engineInfo;
if (oldEngineInfo) {
shouldResetEngineInfo = true;
this.options.engineInfo = engineInfo;
}
let optionsForChild = Object.assign({
engineInfo
}, this.options);
let 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;
}
}
let localFullName = 'application';
let 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.
let substateName = `${name}_loading`;
let localFullName = `application_loading`;
let routeInfo = Object.assign({
localFullName
}, engineInfo);
createRoute(this, substateName, {
resetNamespace: options.resetNamespace
});
this.options.addRouteForEngine(substateName, routeInfo);
substateName = `${name}_error`;
localFullName = `application_error`;
routeInfo = Object.assign({
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);
}
}
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) {
let fullName = getFullName(dsl, name, options.resetNamespace);
if (typeof options.path !== 'string') {
options.path = `/${name}`;
}
dsl.push(options.path, fullName, callback, options.serialize);
}
const emberRoutingLibDsl = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: DSLImpl
}, Symbol.toStringTag, { value: 'Module' });
const MODEL = symbol('MODEL');
/**
@module @ember/controller
*/
/**
@class ControllerMixin
@namespace Ember
@uses Ember.ActionHandler
@private
*/
const ControllerMixin = Mixin.create(ActionHandler, {
/* ducktype as a controller */
isController: true,
concatenatedProperties: ['queryParams'],
target: null,
store: null,
init() {
this._super(...arguments);
let owner = getOwner$2(this);
if (owner) {
this.namespace = owner.lookup('application:main');
this.target = owner.lookup('router:main');
}
},
model: computed({
get() {
return this[MODEL];
},
set(_key, value) {
return this[MODEL] = value;
}
}),
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,
// set by route
/**
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) {
let dotIndex = _prop.indexOf('.[]');
let prop = dotIndex === -1 ? _prop : _prop.slice(0, dotIndex);
let delegate = controller._qpDelegate;
let value = get$2(controller, prop);
delegate(prop, value);
}
});
// NOTE: This doesn't actually extend EmberObject.
/**
@class Controller
@extends EmberObject
@uses Ember.ControllerMixin
@public
*/
class Controller extends FrameworkObject.extend(ControllerMixin) {}
/**
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(...args) {
return inject$2('controller', ...args);
}
/**
A type registry for Ember `Controller`s. Meant to be declaration-merged so string
lookups resolve to the correct type.
Blueprints should include such a declaration merge for TypeScript:
```ts
import Controller from '@ember/controller';
export default class ExampleController extends Controller {
// ...
}
declare module '@ember/controller' {
export interface Registry {
example: ExampleController;
}
}
```
Then `@inject` can check that the service is registered correctly, and APIs
like `owner.lookup('controller:example')` can return `ExampleController`.
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
const emberControllerIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
ControllerMixin,
default: Controller,
inject
}, Symbol.toStringTag, { value: 'Module' });
let wrapGetterSetter = function (target, key, desc) {
let {
get: originalGet
} = desc;
if (originalGet !== undefined) {
desc.get = function () {
let propertyTag = tagFor(this, key);
let ret;
let tag = track(() => {
ret = originalGet.call(this);
});
UPDATE_TAG(propertyTag, tag);
consumeTag(tag);
return ret;
};
}
return desc;
};
/**
`@dependentKeyCompat` is decorator that can be used on _native getters_ that
use tracked properties. It exposes the getter to Ember's classic computed
property and observer systems, so they can watch it for changes. It can be
used in both native and classic classes.
Native Example:
```js
import { tracked } from '@glimmer/tracking';
import { dependentKeyCompat } from '@ember/object/compat';
import { computed, set } from '@ember/object';
class Person {
@tracked firstName;
@tracked lastName;
@dependentKeyCompat
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
class Profile {
constructor(person) {
set(this, 'person', person);
}
@computed('person.fullName')
get helloMessage() {
return `Hello, ${this.person.fullName}!`;
}
}
```
Classic Example:
```js
import { tracked } from '@glimmer/tracking';
import { dependentKeyCompat } from '@ember/object/compat';
import EmberObject, { computed, observer, set } from '@ember/object';
const Person = EmberObject.extend({
firstName: tracked(),
lastName: tracked(),
fullName: dependentKeyCompat(function() {
return `${this.firstName} ${this.lastName}`;
}),
});
const Profile = EmberObject.extend({
person: null,
helloMessage: computed('person.fullName', function() {
return `Hello, ${this.person.fullName}!`;
}),
onNameUpdated: observer('person.fullName', function() {
console.log('person name updated!');
}),
});
```
`dependentKeyCompat()` can receive a getter function or an object containing
`get`/`set` methods when used in classic classes, like computed properties.
In general, only properties which you _expect_ to be watched by older,
untracked clases should be marked as dependency compatible. The decorator is
meant as an interop layer for parts of Ember's older classic APIs, and should
not be applied to every possible getter/setter in classes. The number of
dependency compatible getters should be _minimized_ wherever possible. New
application code should not need to use `@dependentKeyCompat`, since it is
only for interoperation with older code.
@public
@method dependentKeyCompat
@for @ember/object/compat
@static
@param {PropertyDescriptor|undefined} desc A property descriptor containing
the getter and setter (when used in
classic classes)
@return {PropertyDecorator} property decorator instance
*/
function dependentKeyCompat(...args) {
if (isElementDescriptor(args)) {
let [target, key, desc] = args;
return wrapGetterSetter(target, key, desc);
} else {
const desc = args[0];
let decorator = function (target, key, _desc, _meta, isClassicDecorator) {
return wrapGetterSetter(target, key, desc);
};
setClassicDecorator(decorator);
return decorator;
}
}
setClassicDecorator(dependentKeyCompat);
const emberObjectCompat = /*#__PURE__*/Object.defineProperty({
__proto__: null,
dependentKeyCompat
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/routing
*/
/**
Generates a controller factory
@for Ember
@method generateControllerFactory
@private
*/
function generateControllerFactory(owner, controllerName) {
let factoryManager = owner.factoryFor('controller:basic');
// `assert()` below after altering *tests*. It is left in this state for the
// moment in the interest of keeping type-only changes separate from changes
// to the runtime behavior of the system, even for tests.
let Factory = factoryManager.class;
// assert(
// '[BUG] factory for `controller:main` is unexpectedly not a Controller',
// ((factory): factory is typeof Controller => factory === Controller)(Factory)
// );
Factory = Factory.extend({
toString() {
return `(generated ${controllerName} controller)`;
}
});
let 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);
let fullName = `controller:${controllerName}`;
let instance = owner.lookup(fullName);
return instance;
}
const emberRoutingLibGenerateController = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: generateController,
generateControllerFactory
}, Symbol.toStringTag, { value: 'Module' });
const RENDER = Symbol('render');
const RENDER_STATE = Symbol('render-state');
/**
@module @ember/routing/route
*/
/**
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 EmberObject.extend(ActionHandler, Evented) {
static isRouteFactory = true;
// These properties will end up appearing in the public interface because we
// `implements IRoute` from `router.js`, which has them as part of *its*
// public contract. We mark them as `@internal` so they at least signal to
// people subclassing `Route` that they should not use them.
/** @internal */
context = {};
/** @internal */
/** @internal */
_bucketCache;
/** @internal */
_internalName;
_names;
_router;
constructor(owner) {
super(owner);
if (owner) {
let router = owner.lookup('router:main');
let bucketCache = owner.lookup(privatize`-bucket-cache:main`);
this._router = router;
this._bucketCache = bucketCache;
this._topLevelViewTemplate = owner.lookup('template:-outlet');
this._environment = owner.lookup('-environment:main');
}
}
/**
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
*/
serialize(model, params) {
if (params.length < 1 || !model) {
return;
}
let object = {};
if (params.length === 1) {
let [name] = params;
if (typeof model === 'object' && name in model) {
object[name] = get$2(model, name);
} else if (/_id$/.test(name)) {
object[name] = get$2(model, 'id');
} else if (isProxy(model)) {
object[name] = get$2(model, name);
}
} else {
object = getProperties(model, params);
}
return object;
}
/**
Configuration hash for this route's queryParams. The possible
configuration options and their defaults are as follows
(assuming a query param whose controller property is `page`):
```javascript
queryParams = {
page: {
// By default, controller query param properties don't
// cause a full transition when they are changed, but
// rather only cause the URL to update. Setting
// `refreshModel` to true will cause an "in-place"
// transition to occur, whereby the model hooks for
// this route (and any child routes) will re-fire, allowing
// you to reload models (e.g., from the server) using the
// updated query param values.
refreshModel: false,
// By default, changes to controller query param properties
// cause the URL to update via `pushState`, which means an
// item will be added to the browser's history, allowing
// you to use the back button to restore the app to the
// previous state before the query param property was changed.
// Setting `replace` to true will use `replaceState` (or its
// hash location equivalent), which causes no browser history
// item to be added. This options name and default value are
// the same as the `link-to` helper's `replace` option.
replace: false,
// By default, the query param URL key is the same name as
// the controller property name. Use `as` to specify a
// different URL key.
as: 'page'
}
};
```
@property queryParams
@for Route
@type Object
@since 1.6.0
@public
*/
// Set in reopen so it can be overriden with extend
/**
The name of the template to use by default when rendering this route's
template.
```app/routes/posts/list.js
import Route from '@ember/routing/route';
export default class PostsListRoute extends Route {
templateName = 'posts/list';
}
```
```app/routes/posts/index.js
import PostsListRoute from '../posts/list';
export default class PostsIndexRoute extends PostsListRoute {};
```
```app/routes/posts/archived.js
import PostsListRoute from '../posts/list';
export default class PostsArchivedRoute extends PostsListRoute {};
```
@property templateName
@type String
@default null
@since 1.4.0
@public
*/
// Set in reopen so it can be overriden with extend
/**
The name of the controller to associate with this route.
By default, Ember will lookup a route's controller that matches the name
of the route (i.e. `posts.new`). However,
if you would like to define a specific controller to use, you can do so
using this property.
This is useful in many ways, as the controller specified will be:
* passed to the `setupController` method.
* used as the controller for the template being rendered by the route.
* returned from a call to `controllerFor` for the route.
@property controllerName
@type String
@default null
@since 1.4.0
@public
*/
// Set in reopen so it can be overriden with extend
/**
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
*/
/**
The name of the route, dot-delimited.
For example, a route found at `app/routes/posts/post.js` will have
a `routeName` of `posts.post`.
@property routeName
@for Route
@type String
@since 1.0.0
@public
*/
/**
The name of the route, dot-delimited, including the engine prefix
if applicable.
For example, a route found at `addon/routes/posts/post.js` within an
engine named `admin` will have a `fullRouteName` of `admin.posts.post`.
@property fullRouteName
@for Route
@type String
@since 2.10.0
@public
*/
/**
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;
let owner = getOwner$2(this);
this.fullRouteName = getEngineRouteName(owner, name);
}
/**
@private
@method _stashNames
*/
_stashNames(routeInfo, dynamicParent) {
if (this._names) {
return;
}
let names = this._names = routeInfo['_names'];
if (!names.length) {
routeInfo = dynamicParent;
names = routeInfo && routeInfo['_names'] || [];
}
// SAFETY: Since `_qp` is protected we can't infer the type
let qps = get$2(this, '_qp').qps;
let namePaths = new Array(names.length);
for (let a = 0; a < names.length; ++a) {
namePaths[a] = `${routeInfo.name}.${names[a]}`;
}
for (let qp of qps) {
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) {
let owner = getOwner$2(this);
let route = owner.lookup(`route:${name}`);
if (route === undefined) {
return {};
}
let transition = this._router._routerMicrolib.activeTransition;
let state = transition ? transition[STATE_SYMBOL] : this._router._routerMicrolib.state;
let fullName = route.fullRouteName;
let params = {
...state.params[fullName]
};
let queryParams = getQueryParamsFor(route, state);
return Object.entries(queryParams).reduce((params, [key, value]) => {
params[key] = value;
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) {
const queryParams = get$2(this, 'queryParams');
return get$2(queryParams, qp.urlKey) || get$2(queryParams, qp.prop) || queryParams[qp.urlKey] || 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) {
// We document that subclasses do not have to return *anything* and in fact
// do not even have to call super, so whiel we *do* return `this`, we need
// to be explicit in the types that our return type is *effectively* `void`.
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) {
let controller = this.controller;
// SAFETY: Since `_qp` is protected we can't infer the type
controller['_qpDelegate'] = get$2(this, '_qp').states.inactive;
this.resetController(controller, isExiting, transition);
}
/**
@private
@method enter
*/
enter(transition) {
this[RENDER_STATE] = undefined;
this.activate(transition);
this.trigger('activate', transition);
}
/**
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) {}
/**
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) {
let [name, ...preparedArgs] = 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);
}
/**
This hook is the entry point for router.js
@private
@method setup
*/
setup(context, transition) {
let controllerName = this.controllerName || this.routeName;
let definedController = this.controllerFor(controllerName, true);
let controller = definedController ?? this.generateController(controllerName);
// SAFETY: Since `_qp` is protected we can't infer the type
let queryParams = get$2(this, '_qp');
// Assign the route's controller so that it can more easily be
// referenced in action handlers. Side effects. Side effects everywhere.
if (!this.controller) {
let propNames = queryParams.propertyNames;
addQueryParamsObservers(controller, propNames);
this.controller = controller;
}
let states = queryParams.states;
controller._qpDelegate = states.allowOverrides;
if (transition) {
// Update the model dep values used to calculate cache keys.
stashParamNames(this._router, transition[STATE_SYMBOL].routeInfos);
let cache = this._bucketCache;
let params = transition[PARAMS_SYMBOL];
let allParams = queryParams.propertyNames;
allParams.forEach(prop => {
let aQp = queryParams.map[prop];
aQp.values = params;
let cacheKey = calculateCacheKey(aQp.route.fullRouteName, aQp.parts, aQp.values);
let value = cache.lookup(cacheKey, prop, aQp.undecoratedDefaultValue);
set(controller, prop, value);
});
let qpValues = getQueryParamsFor(this, transition[STATE_SYMBOL]);
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.
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
let cache = this._bucketCache;
let cacheKey = 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
`router.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(_transition) {}
/**
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';
import { service } from '@ember/service';
export default class PostsRoute extends Route {
@service router;
afterModel(posts, transition) {
if (posts.get('length') === 1) {
this.router.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(_resolvedModel, _transition) {}
/**
A hook you can implement to optionally redirect to another route.
Calling `this.router.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.router.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(_model, _transition) {}
/**
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;
```
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.router.transitionTo('posts');
// model passed in, so model hook not called
thePost = store.findRecord('post', 1);
this.router.transitionTo('post', thePost);
// integer passed in, model hook is called
this.router.transitionTo('post', 1);
// model id passed in, model hook is called
// useful for forcing the hook to execute
thePost = store.findRecord('post', 1);
this.router.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`.
Note that the legacy behavior of automatically defining a model
hook when a dynamic segment ending in `_id` is present is
[deprecated](https://deprecations.emberjs.com/v5.x#toc_deprecate-implicit-route-model).
You should explicitly define a model hook whenever any segments are
present.
Example
```app/routes/post.js
import Route from '@ember/routing/route';
import { service } from '@ember/service';
export default class PostRoute extends Route {
@service store;
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) {
let name, sawParams, value;
// SAFETY: Since `_qp` is protected we can't infer the type
let queryParams = get$2(this, '_qp').map;
for (let prop in params) {
if (prop === 'queryParams' || queryParams && prop in queryParams) {
continue;
}
let match = prop.match(/^(.*)_id$/);
if (match !== null) {
name = match[1];
value = params[prop];
}
sawParams = true;
}
if (!name) {
if (sawParams) {
// SAFETY: This should be equivalent
return Object.assign({}, params);
} else {
if (transition.resolveIndex < 1) {
return;
}
// SAFETY: This should be correct, but TS is unable to infer this.
return transition[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(type, value) {
if (ENV._NO_IMPLICIT_ROUTE_MODEL) {
return;
}
deprecateUntil(`The implicit model loading behavior for routes is deprecated. ` + `Please define an explicit model hook for ${this.fullRouteName}.`, DEPRECATIONS.DEPRECATE_IMPLICIT_ROUTE_MODEL);
const store = 'store' in this ? this.store : get$2(this, '_store');
return store.find(type, value);
}
/**
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';
import { service } from '@ember/service';
export default class PhotosRoute extends Route {
@service store;
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) {
if (controller && context !== undefined) {
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 | undefined}
@since 1.0.0
@public
*/
controllerFor(name, _skipAssert = false) {
let owner = getOwner$2(this);
let route = owner.lookup(`route:${name}`);
if (route && route.controllerName) {
name = route.controllerName;
}
let controller = owner.lookup(`controller:${name}`);
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) {
let owner = getOwner$2(this);
return generateController(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) {
let name;
let owner = getOwner$2(this);
let 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;
}
let 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) {
let modelLookupName = route && route.routeName || name;
if (Object.prototype.hasOwnProperty.call(transition.resolvedModels, modelLookupName)) {
return transition.resolvedModels[modelLookupName];
}
}
return route?.currentModel;
}
[RENDER_STATE] = undefined;
/**
`this[RENDER]` is used to set up the rendering option for the outlet state.
@method this[RENDER]
@private
*/
[RENDER]() {
this[RENDER_STATE] = buildRenderState(this);
once(this._router, '_setOutlets');
}
willDestroy() {
this.teardownViews();
}
/**
@private
@method teardownViews
*/
teardownViews() {
if (this[RENDER_STATE]) {
this[RENDER_STATE] = undefined;
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 { 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) {
let transition = this._router._routerMicrolib.activeTransition;
if (transition !== undefined) {
return this.paramsFor(routeName);
}
return params;
}
/** @deprecated Manually define your own store, such as with `@service store` */
get _store() {
const owner = getOwner$2(this);
this.routeName;
return {
find(name, value) {
let modelClass = owner.factoryFor(`model:${name}`);
if (!modelClass) {
return;
}
modelClass = modelClass.class;
return modelClass.find(value);
}
};
}
/**
@private
@property _qp
*/
static {
decorateMethodV2(this.prototype, "_store", [computed]);
}
get _qp() {
let combinedQueryParameterConfiguration = {};
let controllerName = this.controllerName || this.routeName;
let owner = getOwner$2(this);
let controller = owner.lookup(`controller:${controllerName}`);
let queryParameterConfiguraton = get$2(this, 'queryParams');
let hasRouterDefinedQueryParams = Object.keys(queryParameterConfiguraton).length > 0;
if (controller) {
// 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 `{}`
let controllerDefinedQueryParameterConfiguration = get$2(controller, 'queryParams') || [];
let normalizedControllerQueryParameterConfiguration = 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 = generateController(owner, controllerName);
combinedQueryParameterConfiguration = queryParameterConfiguraton;
}
let qps = [];
let map = {};
let propertyNames = [];
for (let 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;
}
let desc = combinedQueryParameterConfiguration[propName];
let scope = desc.scope || 'model';
let parts = undefined;
if (scope === 'controller') {
parts = [];
}
let urlKey = desc.as || this.serializeQueryParamKey(propName);
let defaultValue = get$2(controller, propName);
defaultValue = copyDefaultValue(defaultValue);
let type = desc.type || typeOf(defaultValue);
let defaultValueSerialized = this.serializeQueryParam(defaultValue, urlKey, type);
let scopedPropertyName = `${controllerName}:${propName}`;
let qp = {
undecoratedDefaultValue: get$2(controller, propName),
defaultValue,
serializedDefaultValue: defaultValueSerialized,
serializedValue: defaultValueSerialized,
type,
urlKey,
prop: propName,
scopedPropertyName,
controllerName,
route: this,
parts,
// provided later when stashNames is called if 'model' scope
values: null,
// provided later when setup is called. no idea why.
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) => {
let 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) => {
let 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) => {
let qp = map[prop];
this._qpChanged(prop, value, qp);
return this._updatingQPChanged(qp);
}
}
};
}
// Set in reopen
static {
decorateMethodV2(this.prototype, "_qp", [computed]);
}
/**
Sends an action to the router, which will delegate it to the currently
active route hierarchy per the bubbling rules explained under `actions`.
Example
```app/router.js
// ...
Router.map(function() {
this.route('index');
});
export default Router;
```
```app/routes/application.js
import Route from '@ember/routing/route';
import { action } from '@ember/object';
export default class ApplicationRoute extends Route {
@action
track(arg) {
console.log(arg, 'was clicked');
}
}
```
```app/routes/index.js
import Route from '@ember/routing/route';
import { action } from '@ember/object';
export default class IndexRoute extends Route {
@action
trackIfDebug(arg) {
if (debug) {
this.send('track', arg);
}
}
}
```
@method send
@param {String} name the name of the action to trigger
@param {...*} args
@since 1.0.0
@public
*/
// Set with reopen to override parent behavior
}
function getRenderState(route) {
return route[RENDER_STATE];
}
function buildRenderState(route) {
let owner = getOwner$2(route);
let name = route.routeName;
let controller = owner.lookup(`controller:${route.controllerName || name}`);
let model = route.currentModel;
let template = owner.lookup(`template:${route.templateName || name}`);
let render = {
owner,
into: undefined,
outlet: 'main',
name,
controller,
model,
template: template?.(owner) ?? route._topLevelViewTemplate(owner)
};
return render;
}
function getFullQueryParams(router, state) {
if (state.fullQueryParams) {
return state.fullQueryParams;
}
let haveAllRouteInfosResolved = state.routeInfos.every(routeInfo => routeInfo.route);
let 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 || {};
let name = route.fullRouteName;
let existing = state.queryParamsFor[name];
if (existing) {
return existing;
}
let fullQueryParams = getFullQueryParams(route._router, state);
let params = state.queryParamsFor[name] = {};
// Copy over all the query params for this route/controller into params hash.
// SAFETY: Since `_qp` is protected we can't infer the type
let qps = get$2(route, '_qp').qps;
for (let qp of qps) {
// Put deserialized qp on params hash.
let qpValueWasPassedIn = (qp.prop in fullQueryParams);
params[qp.prop] = qpValueWasPassedIn ? fullQueryParams[qp.prop] : copyDefaultValue(qp.defaultValue);
}
return params;
}
// FIXME: This should probably actually return a `NativeArray` if the passed in value is an Array.
function copyDefaultValue(value) {
if (Array.isArray(value)) {
// SAFETY: We lost the type data about the array if we don't cast.
return 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) {
let qps = {};
let 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 (let cqpName in controllerQP) {
if (!Object.prototype.hasOwnProperty.call(controllerQP, cqpName)) {
continue;
}
qps[cqpName] = {
...controllerQP[cqpName],
...routeQP[cqpName]
};
// 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 (let rqpName in routeQP) {
if (!Object.prototype.hasOwnProperty.call(routeQP, rqpName) || keysAlreadyMergedOrSkippable[rqpName]) {
continue;
}
qps[rqpName] = {
...routeQP[rqpName],
...controllerQP[rqpName]
};
}
return qps;
}
function addQueryParamsObservers(controller, propNames) {
propNames.forEach(prop => {
if (descriptorForProperty(controller, prop) === undefined) {
let desc = lookupDescriptor(controller, prop);
if (desc !== null && (typeof desc.get === 'function' || typeof desc.set === 'function')) {
defineProperty(controller, prop, dependentKeyCompat({
get: desc.get,
set: desc.set
}));
}
}
addObserver(controller, `${prop}.[]`, controller, controller._qpChanged, false);
});
}
function getEngineRouteName(engine, routeName) {
if (engine.routable) {
let prefix = engine.mountPoint;
if (routeName === 'application') {
return prefix;
} else {
return `${prefix}.${routeName}`;
}
}
return routeName;
}
const defaultSerialize = Route.prototype.serialize;
function hasDefaultSerialize(route) {
return route.serialize === defaultSerialize;
}
// Set these here so they can be overridden with extend
Route.reopen({
mergedProperties: ['queryParams'],
queryParams: {},
templateName: null,
controllerName: null,
send(...args) {
if (this._router && this._router._routerMicrolib || !isTesting()) {
this._router.send(...args);
} else {
let name = args.shift();
let 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) {
// SAFETY: Since `_qp` is protected we can't infer the type
let qpMap = get$2(this, '_qp').map;
let totalChanged = Object.keys(changed).concat(Object.keys(removed));
for (let change of totalChanged) {
let qp = qpMap[change];
if (qp) {
let options = this._optionsForQueryParam(qp);
if (get$2(options, '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;
}
let routeInfos = transition[STATE_SYMBOL].routeInfos;
let router = this._router;
let qpMeta = router._queryParamsFor(routeInfos);
let changes = router._qpUpdates;
let qpUpdated = false;
let replaceUrl;
stashParamNames(router, routeInfos);
for (let qp of qpMeta.qps) {
let route = qp.route;
let controller = route.controller;
let 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.
let value;
let svalue;
if (changes.has(qp.urlKey)) {
// Value updated in/before setupController
value = get$2(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);
}
}
// SAFETY: Since `_qp` is protected we can't infer the type
controller._qpDelegate = get$2(route, '_qp').states.inactive;
let thisQueryParamChanged = svalue !== qp.serializedValue;
if (thisQueryParamChanged) {
if (transition.queryParamsOnly && replaceUrl !== false) {
let options = route._optionsForQueryParam(qp);
let replaceConfigValue = get$2(options, 'replace');
if (replaceConfigValue) {
replaceUrl = true;
} else if (replaceConfigValue === false) {
// Explicit pushState wins over any other replaceStates.
replaceUrl = false;
}
}
set(controller, qp.prop, value);
qpUpdated = true;
}
// Stash current serialized value of controller.
qp.serializedValue = svalue;
let thisQueryParamHasDefaultValue = qp.serializedDefaultValue === svalue;
if (!thisQueryParamHasDefaultValue) {
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) {
flushAsyncObservers(false);
}
if (replaceUrl) {
transition.method('replace');
}
qpMeta.qps.forEach(qp => {
// SAFETY: Since `_qp` is protected we can't infer the type
let routeQpMeta = get$2(qp.route, '_qp');
let finalizedController = qp.route.controller;
finalizedController['_qpDelegate'] = get$2(routeQpMeta, 'states.active');
});
router._qpUpdates.clear();
return;
}
}
});
const emberRoutingRoute = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: Route,
defaultSerialize,
getFullQueryParams,
getRenderState,
hasDefaultSerialize
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/routing/router
*/
function defaultDidTransition(infos) {
updatePaths(this);
this._cancelSlowTransitionTimer();
this.notifyPropertyChange('url');
this.set('currentState', this.targetState);
}
function defaultWillTransition(oldInfos, newInfos) {
}
function K() {
return this;
}
const {
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 EmberObject.extend(Evented) {
/**
Represents the URL of the root of the application, often '/'. This prefix is
assumed on all routes defined on this router.
@property rootURL
@default '/'
@public
*/
// Set with reopen to allow overriding via extend
/**
The `location` property determines the type of URL's that your
application will use.
The following location types are currently available:
* `history` - use the browser's history API to make the URLs look just like any standard URL
* `hash` - use `#` to separate the server part of the URL from the Ember part: `/blog/#/posts/new`
* `none` - do not store the Ember URL in the actual browser URL (mainly used for testing)
* `auto` - use the best option based on browser capabilities: `history` if possible, then `hash` if possible, otherwise `none`
This value is defaulted to `history` by the `locationType` setting of `/config/environment.js`
@property location
@default 'hash'
@see {Location}
@public
*/
// Set with reopen to allow overriding via extend
_routerMicrolib;
_didSetupRouter = false;
_initialTransitionStarted = false;
currentURL = null;
currentRouteName = null;
currentPath = null;
currentRoute = null;
_qpCache = Object.create(null);
// Set of QueryParam['urlKey']
_qpUpdates = new Set();
_queuedQPChanges = {};
_bucketCache;
_toplevelView = null;
_handledErrors = new Set();
_engineInstances = Object.create(null);
_engineInfoByRoute = Object.create(null);
_routerService;
_slowTransitionTimer = null;
namespace;
// Begin Evented
// End Evented
// Set with reopenClass
static dslCallbacks;
/**
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) {
let 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 (let i = 0; i < a1.length; ++i) {
if (a1[i] !== a2[i]) {
return false;
}
}
return true;
}
let name, nameParts, oldNameParts;
for (let i = 1; i < routeInfos.length; i++) {
let routeInfo = routeInfos[i];
name = routeInfo.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('.');
}
// Note that owner is actually required in this scenario, but since it is strictly
// optional in other contexts trying to make it required here confuses TS.
constructor(owner) {
super(owner);
this._resetQueuedQueryParameterChanges();
this.namespace = owner.lookup('application:main');
let bucketCache = owner.lookup(privatize`-bucket-cache:main`);
this._bucketCache = bucketCache;
let routerService = owner.lookup('service:router');
this._routerService = routerService;
}
_initRouterJs() {
let location = get$2(this, 'location');
let router = this;
const owner = getOwner$1(this);
let seen = Object.create(null);
class PrivateRouter extends Router {
getRoute(name) {
let routeName = name;
let routeOwner = owner;
let engineInfo = router._engineInfoByRoute[routeName];
if (engineInfo) {
let engineInstance = router._getEngineInstance(engineInfo);
routeOwner = engineInstance;
routeName = engineInfo.localFullName;
}
let fullRouteName = `route:${routeName}`;
let route = routeOwner.lookup(fullRouteName);
if (seen[name]) {
return route;
}
seen[name] = true;
if (!route) {
// SAFETY: this is configured in `commonSetupRegistry` in the
// `@ember/application/lib` package.
let DefaultRoute = routeOwner.factoryFor('route:basic').class;
routeOwner.register(fullRouteName, DefaultRoute.extend());
route = routeOwner.lookup(fullRouteName);
}
route._setRouteName(routeName);
if (engineInfo && !hasDefaultSerialize(route)) {
throw new Error('Defining a custom serialize method on an Engine route is not supported.');
}
return route;
}
getSerializer(name) {
let 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 || defaultSerialize;
}
updateURL(path) {
once(() => {
location.setURL(path);
set(router, 'currentURL', path);
});
}
// TODO: merge into routeDidChange
didTransition(infos) {
router.didTransition(infos);
}
// TODO: merge into routeWillChange
willTransition(oldInfos, newInfos) {
router.willTransition(oldInfos, newInfos);
}
triggerEvent(routeInfos, ignoreFailure, name, args) {
return triggerEvent.bind(router)(routeInfos, ignoreFailure, name, args);
}
routeWillChange(transition) {
router.trigger('routeWillChange', 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);
once(() => {
router.trigger('routeDidChange', 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 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) {
let doReplaceURL = () => {
location.replaceURL(url);
set(router, 'currentURL', url);
};
once(doReplaceURL);
} else {
this.updateURL(url);
}
}
}
let routerMicrolib = this._routerMicrolib = new PrivateRouter();
let dslCallbacks = this.constructor.dslCallbacks || [K];
let dsl = this._buildDSL();
dsl.route('application', {
path: '/',
resetNamespace: true,
overrideNameAssertion: true
}, function () {
for (let i = 0; i < dslCallbacks.length; i++) {
dslCallbacks[i].call(this);
}
});
routerMicrolib.map(dsl.generate());
}
_buildDSL() {
let enableLoadingSubstates = this._hasModuleBasedResolver();
let router = this;
const owner = getOwner$1(this);
let options = {
enableLoadingSubstates,
resolveRouteMap(name) {
return owner.factoryFor(`route-map:${name}`);
},
addRouteForEngine(name, engineInfo) {
if (!router._engineInfoByRoute[name]) {
router._engineInfoByRoute[name] = engineInfo;
}
}
};
return new DSLImpl(null, options);
}
/*
Resets all pending query parameter changes.
Called after transitioning to a new route
based on query parameter changes.
*/
_resetQueuedQueryParameterChanges() {
this._queuedQPChanges = {};
}
_hasModuleBasedResolver() {
let owner = getOwner$1(this);
let resolver = get$2(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()) {
let initialURL = get$2(this, 'initialURL');
if (initialURL === undefined) {
initialURL = get$2(this, 'location').getURL();
}
let initialTransition = this.handleURL(initialURL);
if (initialTransition && initialTransition.error) {
throw initialTransition.error;
}
}
}
setupRouter() {
if (this._didSetupRouter) {
return false;
}
this._didSetupRouter = true;
this._setupLocation();
let location = get$2(this, 'location');
// Allow the Location class to cancel the router setup while it refreshes
// the page
if (get$2(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;
}
let routeInfos = this._routerMicrolib.currentRouteInfos;
if (!routeInfos) {
return;
}
let root = null;
let parent = null;
for (let routeInfo of routeInfos) {
let route = routeInfo.route;
let render = getRenderState(route);
if (render) {
let state = {
render,
outlets: {
main: undefined
}
};
if (parent) {
parent.outlets.main = state;
} else {
root = state;
}
parent = state;
} else {
// It used to be that we would create a stub entry and keep traversing,
// but I don't think that is necessary anymore – if a parent route did
// not render, then the child routes have nowhere to render into these
// days. That wasn't always the case since in the past any route can
// render into any other route's outlets.
break;
}
}
// 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 (root === null) {
return;
}
if (!this._toplevelView) {
let owner = getOwner$1(this);
// this safe, so in each of these cases we assume that nothing *else* is
// registered at this `FullName`, and simply check to make sure that
// *something* is.
let OutletView = owner.factoryFor('view:-outlet');
let application = owner.lookup('application:main');
let environment = owner.lookup('-environment:main');
let template = owner.lookup('template:-outlet');
this._toplevelView = OutletView.create({
environment,
template,
application
});
this._toplevelView.setOutletState(root);
// TODO(SAFETY): At least one test runs without this set correctly. At a
// later time, update the test to configure this correctly. The test ID:
// `Router Service - non application test: RouterService#transitionTo with basic route`
let instance = owner.lookup('-application-instance:main');
// let instance = owner.lookup('-application-instance:main') as ApplicationInstance | undefined;
// assert('[BUG] unexpectedly missing `-application-instance:main`', instance !== undefined);
if (instance) {
// SAFETY: LOL. This is calling a deprecated API with a type that we
// cannot actually confirm at a type level *is* a `ViewMixin`. Seems:
// not great on multiple fronts!
instance.didCreateRootView(this._toplevelView);
}
} else {
this._toplevelView.setOutletState(root);
}
}
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.
let _url = url.split(/#(.+)?/)[0];
return this._doURLTransition('handleURL', _url);
}
_doURLTransition(routerJsMethod, url) {
this._initialTransitionStarted = true;
let 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:
@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 (resemblesURL(args[0])) {
return this._doURLTransition('transitionTo', args[0]);
}
let {
routeName,
models,
queryParams
} = extractRouteArgs(args);
return this._doTransition(routeName, models, queryParams);
}
intermediateTransitionTo(name, ...args) {
this._routerMicrolib.intermediateTransitionTo(name, ...args);
updatePaths(this);
}
/**
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.
@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
@public
*/
replaceWith(...args) {
return this.transitionTo(...args).method('replace');
}
generate(name, ...args) {
let url = this._routerMicrolib.generate(name, ...args);
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();
let instances = this._engineInstances;
for (let name in instances) {
let instanceMap = instances[name];
for (let id in instanceMap) {
let instance = instanceMap[id];
run$1(instance, '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;
once(this, this._fireQueryParamTransition);
}
// The queryParameterName is QueryParam['urlKey']
_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() {
let location = this.location;
let rootURL = this.rootURL;
let owner = getOwner$1(this);
if ('string' === typeof location) {
let resolvedLocation = owner.lookup(`location:${location}`);
location = set(this, 'location', resolvedLocation);
}
if (location !== null && typeof location === 'object') {
if (rootURL) {
set(location, 'rootURL', rootURL);
}
// 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, 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 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) {
let qps = this._queryParamsFor(routeInfos);
for (let key in queryParams) {
let qp = qps.map[key];
if (qp && qp.serializedDefaultValue === queryParams[key]) {
delete queryParams[key];
}
}
}
_doTransition(_targetRouteName, models, _queryParams, _fromRouterService) {
let targetRouteName = _targetRouteName || getActiveTargetName(this._routerMicrolib);
this._initialTransitionStarted = true;
let queryParams = {};
this._processActiveTransitionQueryParams(targetRouteName, models, queryParams, _queryParams);
Object.assign(queryParams, _queryParams);
this._prepareQueryParams(targetRouteName, models, queryParams, Boolean(_fromRouterService));
let 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;
}
let unchangedQPs = {};
let qpUpdates = this._qpUpdates;
let params = getFullQueryParams(this, this._routerMicrolib.activeTransition[STATE_SYMBOL]);
for (let 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) {
let 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) {
let route = routeInfo.route;
return route && get$2(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) {
let routeInfoLength = routeInfos.length;
let leafRouteName = routeInfos[routeInfoLength - 1].name;
let cached = this._qpCache[leafRouteName];
if (cached !== undefined) {
return cached;
}
let shouldCache = true;
let map = {};
let qps = [];
let qpMeta;
for (let routeInfo of routeInfos) {
qpMeta = this._getQPMeta(routeInfo);
if (!qpMeta) {
shouldCache = false;
continue;
}
// Loop over each QP to make sure we don't have any collisions by urlKey
for (let qp of qpMeta.qps) {
qps.push(qp);
}
Object.assign(map, qpMeta.map);
}
let 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) {
let state = calculatePostTransitionState(this, leafRouteName, contexts);
let routeInfos = state.routeInfos;
let qpMeta;
for (let routeInfo of routeInfos) {
qpMeta = this._getQPMeta(routeInfo);
if (!qpMeta) {
continue;
}
for (let qp of qpMeta.qps) {
let 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) {
let routeInfos = state.routeInfos;
let appCache = this._bucketCache;
let qpMeta;
let qp;
let presentProp;
for (let routeInfo of routeInfos) {
qpMeta = this._getQPMeta(routeInfo);
if (!qpMeta) {
continue;
}
// Needs to stay for index loop to avoid throwIfClosureRequired
for (let 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];
}
} else {
let cacheKey = calculateCacheKey(qp.route.fullRouteName, qp.parts, state.params);
queryParams[qp.scopedPropertyName] = appCache.lookup(cacheKey, qp.prop, qp.defaultValue);
}
}
}
}
_scheduleLoadingEvent(transition, originRoute) {
this._cancelSlowTransitionTimer();
this._slowTransitionTimer = scheduleOnce('routerTransitions', this, this._handleSlowTransition, transition, originRoute);
}
currentState = null;
targetState = null;
_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;
}
let targetState = new RouterState(this, this._routerMicrolib, this._routerMicrolib.activeTransition[STATE_SYMBOL]);
this.set('targetState', targetState);
transition.trigger(true, 'loading', transition, originRoute);
}
_cancelSlowTransitionTimer() {
if (this._slowTransitionTimer) {
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
}) {
let engineInstances = this._engineInstances;
let namedInstances = engineInstances[name];
if (!namedInstances) {
namedInstances = Object.create(null);
engineInstances[name] = namedInstances;
}
let engineInstance = namedInstances[instanceId];
if (!engineInstance) {
let owner = getOwner$1(this);
engineInstance = owner.buildChildEngineInstance(name, {
routable: true,
mountPoint
});
engineInstance.boot();
namedInstances[instanceId] = engineInstance;
}
return engineInstance;
}
/**
Handles updating the paths and notifying any listeners of the URL
change.
Triggers the router level `didTransition` hook.
For example, to notify google analytics when the route changes,
you could use this hook. (Note: requires also including GA scripts, etc.)
```javascript
import config from './config/environment';
import EmberRouter from '@ember/routing/router';
import { service } from '@ember/service';
let Router = EmberRouter.extend({
location: config.locationType,
router: service(),
didTransition: function() {
this._super(...arguments);
ga('send', 'pageview', {
page: this.router.currentURL,
title: this.router.currentRouteName,
});
}
});
```
@method didTransition
@private
@since 1.2.0
*/
// Set with reopen to allow overriding via extend
/**
Handles notifying any listeners of an impending URL
change.
Triggers the router level `willTransition` hook.
@method willTransition
@private
@since 1.11.0
*/
// Set with reopen to allow overriding via extend
/**
Represents the current URL.
@property url
@type {String}
@private
*/
// Set with reopen to allow overriding via extend
}
/*
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 (let i = routeInfos.length - 1; i >= 0; --i) {
let routeInfo = routeInfos[i];
let 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.
let defaultActionHandlers = {
willResolveModel(_routeInfos, transition, originRoute) {
this._scheduleLoadingEvent(transition, originRoute);
},
// Attempt to find an appropriate error route or substate to enter.
error(routeInfos, error, transition) {
let router = this;
let 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.
let errorRouteName = findRouteStateName(route, 'error');
if (errorRouteName) {
router._markErrorAsHandled(error);
router.intermediateTransitionTo(errorRouteName, error);
return false;
}
}
// Check for an 'error' substate route
let 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) {
let router = this;
let 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.
let loadingRouteName = findRouteStateName(route, 'loading');
if (loadingRouteName) {
router.intermediateTransitionTo(loadingRouteName);
return false;
}
}
// Check for loading substate
let 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) {
let errorArgs = [];
let 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) {
let owner = getOwner$1(route);
let {
routeName,
fullRouteName,
_router: router
} = route;
let substateName = `${routeName}_${state}`;
let 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) {
let owner = getOwner$1(route);
let {
routeName,
fullRouteName,
_router: router
} = route;
let stateName = routeName === 'application' ? state : `${routeName}.${state}`;
let 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) {
let routerHasRoute = router.hasRoute(fullName);
let ownerHasRoute = owner.factoryFor(`template:${localName}`) || owner.factoryFor(`route:${localName}`);
return routerHasRoute && ownerHasRoute;
}
function triggerEvent(routeInfos, ignoreFailure, name, args) {
if (!routeInfos) {
if (ignoreFailure) {
return;
}
// TODO: update?
throw new Error(`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.`);
}
let eventWasHandled = false;
let routeInfo, handler, actionHandler;
for (let 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;
}
}
}
let defaultHandler = defaultActionHandlers[name];
if (defaultHandler) {
defaultHandler.call(this, routeInfos, ...args);
return;
}
if (!eventWasHandled && !ignoreFailure) {
throw new Error(`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) {
let state = emberRouter._routerMicrolib.applyIntent(leafRouteName, contexts);
let {
routeInfos,
params
} = state;
for (let routeInfo of routeInfos) {
// 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) {
let infos = router._routerMicrolib.currentRouteInfos;
if (infos.length === 0) {
return;
}
let path = EmberRouter._routePath(infos);
let info = infos[infos.length - 1];
let currentRouteName = info.name;
let location = router.location;
let currentURL = location.getURL();
set(router, 'currentPath', path);
set(router, 'currentRouteName', currentRouteName);
set(router, 'currentURL', currentURL);
}
function didBeginTransition(transition, router) {
let routerState = new RouterState(router, router._routerMicrolib, transition[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) {
let qpCache = router._queryParamsFor(routeInfos);
for (let key in queryParams) {
if (!Object.prototype.hasOwnProperty.call(queryParams, key)) {
continue;
}
let value = queryParams[key];
let qp = qpCache.map[key];
callback(key, value, qp);
}
}
EmberRouter.reopen({
didTransition: defaultDidTransition,
willTransition: defaultWillTransition,
rootURL: '/',
location: 'hash',
// FIXME: Does this need to be overrideable via extend?
url: computed(function () {
let location = get$2(this, 'location');
if (typeof location === 'string') {
return undefined;
}
return location.getURL();
})
});
const emberRoutingRouter = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: EmberRouter,
triggerEvent
}, Symbol.toStringTag, { value: 'Module' });
/**
* @module @ember/routing/router-service
*/
const ROUTER = Symbol('ROUTER');
function cleanURL(url, rootURL) {
if (rootURL === '/') {
return url;
}
return url.substring(rootURL.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 { 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.extend(Evented) {
[ROUTER];
get _router() {
let router = this[ROUTER];
if (router !== undefined) {
return router;
}
let owner = getOwner$2(this);
let _router = owner.lookup('router:main');
return this[ROUTER] = _router;
}
willDestroy() {
super.willDestroy();
this[ROUTER] = undefined;
}
/**
Transition the application into another route. The route may
be either a single route or route path:
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 { 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 (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]);
}
let {
routeName,
models,
queryParams
} = extractRouteArgs(args);
let transition = this._router._doTransition(routeName, models, queryParams, 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.
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';
import { service } from '@ember/service';
export default class extends Route {
@service router;
beforeModel() {
if (!authorized()){
this.router.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(...args) {
return this.transitionTo(...args).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 { 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 { 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) for 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 { 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 { 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) {
let {
routeName,
models,
queryParams
} = extractRouteArgs(args);
let 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
consumeTag(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;
}
let hasQueryParams = Object.keys(queryParams).length > 0;
if (hasQueryParams) {
// 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`.
let targetRouteName = routeName;
queryParams = Object.assign({}, queryParams);
this._router._prepareQueryParams(targetRouteName, models, queryParams, true /* fromRouterService */);
let currentQueryParams = Object.assign({}, routerMicrolib.state.queryParams);
this._router._prepareQueryParams(targetRouteName, models, currentQueryParams, true /* fromRouterService */);
return shallowEqual(queryParams, currentQueryParams);
}
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 { 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
@return {RouteInfo | null}
@public
*/
recognize(url) {
this._router.setupRouter();
let 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
@return {RouteInfo}
@public
*/
recognizeAndLoad(url) {
this._router.setupRouter();
let internalURL = cleanURL(url, this.rootURL);
return this._router._routerMicrolib.recognizeAndLoad(internalURL);
}
/**
You can register a listener for events emitted by this service with `.on()`:
```app/routes/contact-form.js
import Route from '@ember/routing';
import { service } from '@ember/service';
export default class extends Route {
@service router;
activate() {
this.router.on('routeWillChange', (transition) => {
if (!transition.to.find(route => route.name === this.routeName)) {
alert("Please save or cancel your changes.");
transition.abort();
}
})
}
}
```
@method on
@param {String} eventName
@param {Function} callback
@public
*/
/**
You can unregister a listener for events emitted by this service with `.off()`:
```app/routes/contact-form.js
import Route from '@ember/routing';
import { service } from '@ember/service';
export default class ContactFormRoute extends Route {
@service router;
callback = (transition) => {
if (!transition.to.find(route => route.name === this.routeName)) {
alert('Please save or cancel your changes.');
transition.abort();
}
};
activate() {
this.router.on('routeWillChange', this.callback);
}
deactivate() {
this.router.off('routeWillChange', this.callback);
}
}
```
@method off
@param {String} eventName
@param {Function} callback
@public
*/
/**
The `routeWillChange` event 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';
import { service } from '@ember/service';
export default class extends Route {
@service router;
activate() {
this.router.on('routeWillChange', (transition) => {
if (!transition.to.find(route => route.name === this.routeName)) {
alert("Please save or cancel your changes.");
transition.abort();
}
})
}
}
```
The `routeWillChange` event fires whenever a new route is chosen as the desired target of a transition. This includes `transitionTo`, `replaceWith`, all redirection for any reason including error handling, and abort. Aborting implies changing the desired target back to where you already were. Once a transition has completed, `routeDidChange` fires.
@event routeWillChange
@param {Transition} transition
@public
*/
/**
The `routeDidChange` event only fires once a transition has settled.
This includes aborts and error substates. Like the `routeWillChange` event
it receives a Transition as the sole argument.
A good example is sending some analytics when the route has transitioned:
```app/routes/contact-form.js
import Route from '@ember/routing';
import { service } from '@ember/service';
export default class extends Route {
@service router;
activate() {
this.router.on('routeDidChange', (transition) => {
ga.send('pageView', {
current: transition.to.name,
from: transition.from.name
});
})
}
}
```
`routeDidChange` will be called after any `Route`'s
[didTransition](/ember/release/classes/Route/events/didTransition?anchor=didTransition)
action has been fired.
The updates of properties
[currentURL](/ember/release/classes/RouterService/properties/currentURL?anchor=currentURL),
[currentRouteName](/ember/release/classes/RouterService/properties/currentURL?anchor=currentRouteName)
and
[currentRoute](/ember/release/classes/RouterService/properties/currentURL?anchor=currentRoute)
are completed at the time `routeDidChange` is called.
@event routeDidChange
@param {Transition} transition
@public
*/
/**
* 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
* @public
*/
refresh(pivotRouteName) {
if (!pivotRouteName) {
return this._router._routerMicrolib.refresh();
}
let owner = getOwner$2(this);
let pivotRoute = owner.lookup(`route:${pivotRouteName}`);
return this._router._routerMicrolib.refresh(pivotRoute);
}
/**
Name of the current route.
This property represents the logical name of the route,
which is dot 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 | null}
@public
*/
static {
decorateFieldV2(this.prototype, "currentRouteName", [readOnly('_router.currentRouteName')]);
}
#currentRouteName = (initializeDeferredDecorator(this, "currentRouteName"), void 0);
static {
decorateFieldV2(this.prototype, "currentURL", [readOnly('_router.currentURL')]);
}
#currentURL = (initializeDeferredDecorator(this, "currentURL"), void 0);
/**
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
*/
static {
decorateFieldV2(this.prototype, "location", [readOnly('_router.location')]);
}
#location = (initializeDeferredDecorator(this, "location"), void 0);
/**
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:
`hash`, `history`, `none`.
See [HashLocation](/ember/release/classes/HashLocation).
See [HistoryLocation](/ember/release/classes/HistoryLocation).
See [NoneLocation](/ember/release/classes/NoneLocation).
@property location
@default 'hash'
@see {Location}
@public
*/
static {
decorateFieldV2(this.prototype, "rootURL", [readOnly('_router.rootURL')]);
}
#rootURL = (initializeDeferredDecorator(this, "rootURL"), void 0);
/**
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
*/
static {
decorateFieldV2(this.prototype, "currentRoute", [readOnly('_router.currentRoute')]);
}
#currentRoute = (initializeDeferredDecorator(this, "currentRoute"), void 0);
/**
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 { 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
*/
}
const emberRoutingRouterService = /*#__PURE__*/Object.defineProperty({
__proto__: null,
ROUTER,
default: RouterService
}, Symbol.toStringTag, { value: 'Module' });
/**
@module ember
*/
/**
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 {
[ROUTER];
get router() {
let router = this[ROUTER];
if (router !== undefined) {
return router;
}
let owner = getOwner$2(this);
let _router = owner.lookup('router:main');
_router.setupRouter();
return this[ROUTER] = _router;
}
hasRoute(routeName) {
return this.router.hasRoute(routeName);
}
transitionTo(routeName, models, queryParams, shouldReplace) {
let 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) {
let 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) {
let handlers = this.router._routerMicrolib.recognizer.handlersFor(routeName);
let leafName = handlers[handlers.length - 1].handler;
let 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);
}
}
RoutingService.reopen({
targetState: readOnly('router.targetState'),
currentState: readOnly('router.currentState'),
currentRouteName: readOnly('router.currentRouteName'),
currentPath: readOnly('router.currentPath')
});
function numberOfContextsAcceptedByHandler(handlerName, handlerInfos) {
let req = 0;
for (let i = 0; i < handlerInfos.length; i++) {
req += handlerInfos[i].names.length;
if (handlerInfos[i].handler === handlerName) {
break;
}
}
return req;
}
const emberRoutingLibRoutingService = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: RoutingService
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/routing
*/
/**
Finds a controller instance.
@for Ember
@method controllerFor
@private
*/
function controllerFor(container, controllerName, lookupOptions) {
return container.lookup(`controller:${controllerName}`, lookupOptions);
}
const emberRoutingLibControllerFor = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: controllerFor
}, Symbol.toStringTag, { value: 'Module' });
const emberRoutinginternals = /*#__PURE__*/Object.defineProperty({
__proto__: null,
BucketCache,
DSL: DSLImpl,
RouterState,
RoutingService,
controllerFor,
generateController,
generateControllerFactory,
prefixRouteNameArg
}, Symbol.toStringTag, { value: 'Module' });
const CAPABILITIES = {
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) {
let templateFactory = state.engine.lookup('template:application');
return unwrapTemplate(templateFactory(state.engine)).asLayout();
}
getCapabilities() {
return CAPABILITIES;
}
getOwner(state) {
return state.engine;
}
create(owner, {
name
}, args, env) {
let engine = owner.buildChildEngineInstance(name);
engine.boot();
let applicationFactory = engine.factoryFor(`controller:application`);
let controllerFactory = applicationFactory || generateControllerFactory(engine, 'application');
let controller;
let self;
let bucket;
let modelRef;
if (args.named.has('model')) {
modelRef = args.named.get('model');
}
if (modelRef === undefined) {
controller = controllerFactory.create();
self = createConstRef(controller);
bucket = {
engine,
controller,
self,
modelRef
};
} else {
let model = valueForRef(modelRef);
controller = controllerFactory.create({
model
});
self = createConstRef(controller);
bucket = {
engine,
controller,
self,
modelRef
};
}
if (env.debugRenderTree) {
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) {
let {
controller,
modelRef
} = bucket;
if (modelRef !== undefined) {
controller.set('model', valueForRef(modelRef));
}
}
}
const MOUNT_MANAGER = new MountManager();
class MountDefinition {
// handle is not used by this custom definition
handle = -1;
state;
manager = MOUNT_MANAGER;
compilable = null;
capabilities = capabilityFlagsFrom(CAPABILITIES);
constructor(resolvedName) {
this.resolvedName = resolvedName;
this.state = {
name: resolvedName
};
}
}
/**
@module ember
*/
/**
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
*/
const mountHelper = internalHelper((args, owner) => {
let nameRef = args.positional[0];
let captured;
captured = createCapturedArgs(args.named, EMPTY_POSITIONAL);
let lastName, lastDef;
return createComputeRef(() => {
let name = valueForRef(nameRef);
if (typeof name === 'string') {
if (lastName === name) {
return lastDef;
}
lastName = name;
lastDef = curry(CurriedTypes.Component, new MountDefinition(name), owner, captured, true);
return lastDef;
} else {
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
@for Ember.Templates.helpers
@public
*/
const outletHelper = internalHelper((_args, owner, scope) => {
let outletRef = createComputeRef(() => {
let state = valueForRef(scope.get('outletState'));
return state?.outlets?.main;
});
let lastState = null;
let definition = null;
return createComputeRef(() => {
let outletState = valueForRef(outletRef);
let state = stateFor(outletRef, outletState);
if (!validate(state, lastState)) {
lastState = state;
if (state !== null) {
let named = dict();
// Create a ref for the model
let modelRef = childRefFromParts(outletRef, ['render', 'model']);
// Store the value of the model
let model = 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'] = createComputeRef(() => {
if (lastState === state) {
model = valueForRef(modelRef);
}
return model;
});
let args = createCapturedArgs(named, EMPTY_POSITIONAL);
definition = curry(CurriedTypes.Component, new OutletComponentDefinition(state), outletState?.render?.owner ?? owner, args, true);
} else {
definition = null;
}
}
return definition;
});
});
function stateFor(ref, outlet) {
if (outlet === undefined) return null;
let render = outlet.render;
if (render === undefined) return null;
let template = render.template;
if (template === undefined) return null;
if (isTemplateFactory(template)) {
template = template(render.owner);
}
return {
ref,
name: render.name,
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(name) {
return {
object: `component:${name}`
};
}
function componentFor(name, owner) {
let fullName = `component:${name}`;
return owner.factoryFor(fullName) || null;
}
function layoutFor(name, owner, options) {
if (DEPRECATIONS.DEPRECATE_COMPONENT_TEMPLATE_RESOLVING.isRemoved) {
return null;
}
let templateFullName = `template:components/${name}`;
let result = owner.lookup(templateFullName, options) || null;
if (result) {
deprecateUntil(`Components with separately resolved templates are deprecated. Migrate to either co-located js/ts + hbs files or to gjs/gts. Tried to lookup '${templateFullName}'.`, DEPRECATIONS.DEPRECATE_COMPONENT_TEMPLATE_RESOLVING);
}
return result;
}
function lookupComponentPair(owner, name, options) {
let component = componentFor(name, owner);
if (isFactory(component) && component.class) {
let layout = getComponentTemplate(component.class);
if (layout !== undefined) {
return {
component,
layout
};
}
}
let layout = layoutFor(name, owner, options);
if (component === null && layout === null) {
return null;
} else {
return {
component,
layout
};
}
}
const BUILTIN_KEYWORD_HELPERS = {
action,
mut,
readonly,
unbound,
'-hash': hash$1,
'-each-in': eachIn,
'-normalize-class': normalizeClassHelper,
'-resolve': resolve$1,
'-track-array': trackArray,
'-mount': mountHelper,
'-outlet': outletHelper,
'-in-el-null': inElementNullCheckHelper
};
const BUILTIN_HELPERS = {
...BUILTIN_KEYWORD_HELPERS,
array: array$1,
concat: concat$1,
fn: fn$1,
get: get$1,
hash: hash$1,
'unique-id': uniqueId$1
};
{
// 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_HELPERS['-disallow-dynamic-resolution'] = disallowDynamicResolution;
}
const BUILTIN_KEYWORD_MODIFIERS = {
action: actionModifier
};
const BUILTIN_MODIFIERS = {
...BUILTIN_KEYWORD_MODIFIERS,
on: on$1
};
class ResolverImpl {
componentDefinitionCache = new Map();
lookupPartial() {
return null;
}
lookupHelper(name, owner) {
let helper = BUILTIN_HELPERS[name];
if (helper !== undefined) {
return helper;
}
let factory = owner.factoryFor(`helper:${name}`);
if (factory === undefined) {
return null;
}
let 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
{
setInternalHelperManager(CLASSIC_HELPER_MANAGER, factory);
}
return factory;
}
return definition;
}
lookupBuiltInHelper(name) {
return BUILTIN_KEYWORD_HELPERS[name] ?? null;
}
lookupModifier(name, owner) {
let builtin = BUILTIN_MODIFIERS[name];
if (builtin !== undefined) {
return builtin;
}
let modifier = owner.factoryFor(`modifier:${name}`);
if (modifier === undefined) {
return null;
}
return modifier.class || null;
}
lookupBuiltInModifier(name) {
return BUILTIN_KEYWORD_MODIFIERS[name] ?? null;
}
lookupComponent(name, owner) {
let pair = lookupComponentPair(owner, name);
if (pair === null) {
return null;
}
let template = null;
let key;
if (pair.component === null) {
key = template = pair.layout(owner);
} else {
key = pair.component;
}
let cachedComponentDefinition = this.componentDefinitionCache.get(key);
if (cachedComponentDefinition !== undefined) {
return cachedComponentDefinition;
}
if (template === null && pair.layout !== null) {
template = pair.layout(owner);
}
let finalizer = _instrumentStart('render.getComponentDefinition', instrumentationPayload, name);
let definition = null;
if (pair.component === null) {
definition = {
state: templateOnlyComponent(undefined, name),
manager: TEMPLATE_ONLY_COMPONENT_MANAGER,
template
};
} else {
let factory = pair.component;
let ComponentClass = factory.class;
let manager = getInternalComponentManager(ComponentClass);
definition = {
state: isCurlyManager(manager) ? factory : ComponentClass,
manager,
template
};
}
finalizer();
this.componentDefinitionCache.set(key, definition);
return definition;
}
}
// We use the `InternalOwner` notion here because we actually need all of its
// API for using with renderers (normally, it will be `EngineInstance`).
// We use `getOwner` from our internal home for it rather than the narrower
// public API for the same reason.
const TOP_LEVEL_NAME = '-top-level';
class OutletView {
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) {
let {
environment: _environment,
application: namespace,
template: templateFactory
} = options;
let owner = getOwner$2(options);
let template = templateFactory(owner);
return new OutletView(_environment, owner, template, namespace);
}
ref;
state;
constructor(_environment, owner, template, namespace) {
this._environment = _environment;
this.owner = owner;
this.template = template;
this.namespace = namespace;
let outletStateTag = createTag();
let outletState = {
outlets: {
main: undefined
},
render: {
owner: owner,
into: undefined,
outlet: 'main',
name: TOP_LEVEL_NAME,
controller: undefined,
model: undefined,
template
}
};
let ref = this.ref = createComputeRef(() => {
consumeTag(outletStateTag);
return outletState;
}, state => {
DIRTY_TAG$1(outletStateTag);
outletState.outlets['main'] = state;
});
this.state = {
ref,
name: TOP_LEVEL_NAME,
template,
controller: undefined,
model: undefined
};
}
appendTo(selector) {
let target;
if (this._environment.hasDOM) {
target = typeof selector === 'string' ? document.querySelector(selector) : selector;
} else {
target = selector;
}
let renderer = this.owner.lookup('renderer:-dom');
// SAFETY: It's not clear that this cast is safe.
// The types for appendOutletView may be incorrect or this is a potential bug.
schedule('render', renderer, 'appendOutletView', this, target);
}
rerender() {
/**/
}
setOutletState(state) {
updateRef(this.ref, state);
}
destroy() {
/**/
}
}
class DynamicScope {
constructor(view, outletState) {
this.view = view;
this.outletState = outletState;
}
child() {
return new DynamicScope(this.view, this.outletState);
}
get(key) {
return this.outletState;
}
set(key, value) {
this.outletState = value;
return value;
}
}
const NO_OP = () => {};
// 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) {
{
return fn;
}
}
class RootState {
id;
result;
destroyed;
render;
constructor(root, runtime, context, owner, template, self, parentElement, dynamicScope, builder) {
this.root = root;
this.runtime = runtime;
this.id = root instanceof OutletView ? guidFor(root) : getViewId(root);
this.result = undefined;
this.destroyed = false;
this.render = errorLoopTransaction(() => {
let layout = unwrapTemplate(template).asLayout();
let iterator = renderMain(runtime, context, owner, self, builder(runtime.env, {
element: parentElement,
nextSibling: null
}), layout, dynamicScope);
let 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() {
let {
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
*/
inTransaction(env, () => destroy(result));
}
}
}
const renderers = [];
function _resetRenderers() {
renderers.length = 0;
}
function register(renderer) {
renderers.push(renderer);
}
function deregister(renderer) {
let index = renderers.indexOf(renderer);
renderers.splice(index, 1);
}
function loopBegin() {
for (let renderer of renderers) {
renderer._scheduleRevalidate();
}
}
let 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.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 (!_getCurrentRunLoop()) {
// ensure a runloop has been kicked off
_backburner.schedule('actions', null, NO_OP);
}
}
return renderSettledDeferred.promise;
}
function resolveRenderPromise() {
if (renderSettledDeferred !== null) {
let resolve = renderSettledDeferred.resolve;
renderSettledDeferred = null;
_backburner.join(null, resolve);
}
}
let loops = 0;
function loopEnd() {
for (let renderer of renderers) {
if (!renderer._isValid()) {
if (loops > ENV._RERENDER_LOOP_LIMIT) {
loops = 0;
// TODO: do something better
renderer.destroy();
throw new Error('infinite rendering invalidation detected');
}
loops++;
return _backburner.join(null, NO_OP);
}
}
loops = 0;
resolveRenderPromise();
}
_backburner.on('begin', loopBegin);
_backburner.on('end', loopEnd);
class Renderer {
_rootTemplate;
_viewRegistry;
_roots;
_removedRoots;
_builder;
_inRenderTransaction = false;
_owner;
_context;
_runtime;
_lastRevision = -1;
_destroyed = false;
/** @internal */
_isInteractive;
_runtimeResolver;
static create(props) {
let {
_viewRegistry
} = props;
let owner = getOwner$2(props);
let document = owner.lookup('service:-document');
let env = owner.lookup('-environment:main');
let rootTemplate = owner.lookup(privatize`template:-root`);
let builder = owner.lookup('service:-dom-builder');
return new this(owner, document, env, rootTemplate, _viewRegistry, builder);
}
constructor(owner, document, env, rootTemplate, viewRegistry, builder = clientBuilder) {
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
let resolver = this._runtimeResolver = new ResolverImpl();
let sharedArtifacts = artifacts();
this._context = programCompilationContext(sharedArtifacts, resolver, heap => new RuntimeOpImpl(heap));
let runtimeEnvironmentDelegate = new EmberEnvironmentDelegate(owner, env.isInteractive);
this._runtime = runtimeContext({
appendOperations: env.hasDOM ? new DOMTreeConstruction(document) : new NodeDOMTreeConstruction(document),
updateOperations: new DOMChanges(document)
}, runtimeEnvironmentDelegate, sharedArtifacts, resolver);
}
get debugRenderTree() {
let {
debugRenderTree
} = this._runtime.env;
return debugRenderTree;
}
// renderer HOOKS
appendOutletView(view, target) {
let definition = createRootOutlet(view);
this._appendDefinition(view, curry(CurriedTypes.Component, definition, view.owner, null, true), target);
}
appendTo(view, target) {
let definition = new RootComponentDefinition(view);
this._appendDefinition(view, curry(CurriedTypes.Component, definition, this._owner, null, true), target);
}
_appendDefinition(root, definition, target) {
let self = createConstRef(definition);
let dynamicScope = new DynamicScope(null, UNDEFINED_REFERENCE);
let 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) {
let id = getViewId(view);
this._viewRegistry[id] = view;
}
unregister(view) {
delete this._viewRegistry[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;
}
let roots = this._roots;
// traverse in reverse so we can remove items
// without mucking up the index
let i = this._roots.length;
while (i--) {
let 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 getViewElement(view);
} else {
throw new Error('Accessing `this.element` is not allowed in non-interactive environments (such as FastBoot).');
}
}
getBounds(view) {
let bounds = view[BOUNDS];
let parentElement = bounds.parentElement();
let firstNode = bounds.firstNode();
let lastNode = bounds.lastNode();
return {
parentElement,
firstNode,
lastNode
};
}
createElement(tagName) {
return this._runtime.env.getAppendOperations().createElement(tagName);
}
_renderRoot(root) {
let {
_roots: roots
} = this;
roots.push(root);
if (roots.length === 1) {
register(this);
}
this._renderRootsTransaction();
}
_renderRoots() {
let {
_roots: roots,
_runtime: runtime,
_removedRoots: removedRoots
} = this;
let initialRootsLength;
do {
initialRootsLength = roots.length;
inTransaction(runtime.env, () => {
// ensure that for the first iteration of the loop
// each root is processed
for (let i = 0; i < roots.length; i++) {
let root = roots[i];
(false && !(root) && assert$1('has root', root));
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 = valueForTag(CURRENT_TAG);
});
} while (roots.length > initialRootsLength);
// remove any roots that were destroyed during this transaction
while (removedRoots.length) {
let root = removedRoots.pop();
let 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;
let completedWithoutError = false;
try {
this._renderRoots();
completedWithoutError = true;
} finally {
if (!completedWithoutError) {
this._lastRevision = valueForTag(CURRENT_TAG);
}
this._inRenderTransaction = false;
}
}
_clearAllRoots() {
let roots = this._roots;
for (let root of roots) {
root.destroy();
}
this._removedRoots.length = 0;
this._roots = [];
// if roots were present before destroying
// deregister this renderer instance
if (roots.length) {
deregister(this);
}
}
_scheduleRevalidate() {
_backburner.scheduleOnce('render', this, this._revalidate);
}
_isValid() {
return this._destroyed || this._roots.length === 0 || validateTag(CURRENT_TAG, this._lastRevision);
}
_revalidate() {
if (this._isValid()) {
return;
}
this._renderRootsTransaction();
}
}
// STATE within a module is frowned upon, this exists
// to support Ember.TEMPLATES but shield ember internals from this legacy
// global API.
let 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;
}
const OutletTemplate = templateFactory(
/*
{{component (outletHelper)}}
*/
{
"id": "2c6+lAmT",
"block": "[[[46,[28,[32,0],null,null],null,null,null]],[],false,[\"component\"]]",
"moduleName": "packages/@ember/-internals/glimmer/lib/templates/outlet.hbs",
"scope": () => [outletHelper],
"isStrictMode": true
});
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', {
// Additionally, we *must* constrain this to require `props` on create, else
// we *know* it cannot have an owner.
create(props) {
let owner = getOwner$2(props);
let env = owner.lookup('-environment:main');
switch (env._renderMode) {
case 'serialize':
return serializeBuilder.bind(null);
case 'rehydrate':
return rehydrationBuilder.bind(null);
default:
return clientBuilder.bind(null);
}
}
});
registry.register(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);
registry.register('component:link-to', LinkTo);
registry.register('component:textarea', Textarea);
}
/**
Associate a class with a component manager (an object that is responsible for
coordinating the lifecycle events that occurs when invoking, rendering and
re-rendering a component).
@method setComponentManager
@param {Function} factory a function to create the owner for an object
@param {Object} obj the object to associate with the componetn manager
@return {Object} the same object passed in
@public
*/
function setComponentManager(manager, obj) {
return setComponentManager$1(manager, obj);
}
/**
[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
*/
const emberinternalsGlimmerIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
Component,
DOMChanges,
DOMTreeConstruction,
Helper,
Input,
LinkTo,
NodeDOMTreeConstruction,
OutletView,
Renderer,
RootTemplate,
SafeString,
Textarea,
_resetRenderers,
componentCapabilities,
escapeExpression,
getTemplate,
getTemplates,
hasTemplate,
helper: helper$2,
htmlSafe,
isHTMLSafe,
isSerializationFirstNode,
modifierCapabilities,
renderSettled,
setComponentManager,
setTemplate,
setTemplates,
setupApplicationRegistry,
setupEngineRegistry,
template: templateFactory,
templateCacheCounters,
uniqueId: uniqueId$2
}, Symbol.toStringTag, { value: 'Module' });
const emberinternalsRoutingIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
RouterDSL: DSLImpl,
controllerFor,
generateController,
generateControllerFactory
}, Symbol.toStringTag, { value: 'Module' });
// The formatting here is designed to help make this type actually be
// comprehensible to mortals, including the mortals who came up with it.
// prettier-ignore
// A way of representing non-user-constructible types. You can conveniently use
// this by doing `interface Type extends Opaque<'some-type-name'> { ... }` for
// simple types, and/or you can type-parameterize it as makes sense for your use
// case (see e.g. `@ember/component/helper`'s use with functional helpers).
class Opaque {}
const emberinternalsUtilityTypesIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
Opaque
}, Symbol.toStringTag, { value: 'Module' });
const fallbackViewRegistry = makeDictionary(null);
const emberinternalsViewsLibCompatFallbackViewRegistry = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: fallbackViewRegistry
}, Symbol.toStringTag, { value: 'Module' });
/*globals CustomEvent */
/**
@module @ember/application
*/
const loadHooks = ENV.EMBER_LOAD_HOOKS || {};
const loaded = {};
let _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
*/
function onLoad(name, callback) {
let object = loaded[name];
let hooks = loadHooks[name] ??= [];
hooks.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 (window$1 && typeof CustomEvent === 'function') {
let event = new CustomEvent(name, {
detail: object
});
window$1.dispatchEvent(event);
}
loadHooks[name]?.forEach(callback => callback(object));
}
const emberApplicationLibLazyLoad = /*#__PURE__*/Object.defineProperty({
__proto__: null,
_loaded,
onLoad,
runLoadHooks
}, Symbol.toStringTag, { value: 'Module' });
/**
@private
Returns the current `location.pathname`, normalized for IE inconsistencies.
*/
function getPath(location) {
let 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.substring(0);
}
return '';
}
function getFullPath(location) {
return getPath(location) + getQuery(location) + getHash(location);
}
function getOrigin(location) {
let 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;
}
/**
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);
}
const emberRoutingLibLocationUtils = /*#__PURE__*/Object.defineProperty({
__proto__: null,
getFullPath,
getHash,
getOrigin,
getPath,
getQuery,
replacePath
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/routing/hash-location
*/
/**
`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 EmberObject {
_hashchangeHandler;
_location;
init() {
this.location = this._location ?? window.location;
this._hashchangeHandler = undefined;
}
/**
@private
Returns normalized location.hash
@since 1.5.1
@method getHash
*/
getHash() {
return 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() {
let originalPath = this.getHash().substring(1);
let 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;
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}`);
this.lastSetURL = path;
}
lastSetURL = null;
/**
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 = bind(this, function (_event) {
let path = this.getURL();
if (this.lastSetURL === path) {
return;
}
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.
@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);
}
}
}
const emberRoutingHashLocation = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: HashLocation
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/routing/history-location
*/
let popstateFired = false;
function _uuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
let 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 EmberObject {
// SAFETY: both of these properties initialized via `init`.
history;
_previousURL;
_popstateHandler;
/**
Will be pre-pended to path upon state change
@property rootURL
@default '/'
@private
*/
rootURL = '/';
/**
@private
Returns normalized location.hash
@method getHash
*/
getHash() {
return getHash(this.location);
}
init() {
this._super(...arguments);
let base = document.querySelector('base');
let baseURL = '';
if (base !== null && base.hasAttribute('href')) {
baseURL = base.getAttribute('href') ?? '';
}
this.baseURL = baseURL;
this.location = this.location ?? window.location;
this._popstateHandler = undefined;
}
/**
Used to set state on first call to setURL
@private
@method initState
*/
initState() {
let history = this.history ?? window.history;
this.history = history;
let {
state
} = history;
let 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() {
let {
location,
rootURL,
baseURL
} = this;
let path = location.pathname;
// remove trailing slashes if they exists
rootURL = rootURL.replace(/\/$/, '');
baseURL = baseURL.replace(/\/$/, '');
// remove baseURL and rootURL from start of path
let url = path.replace(new RegExp(`^${baseURL}(?=/|$)`), '').replace(new RegExp(`^${rootURL}(?=/|$)`), '').replace(/\/\//g, '/'); // remove extra slashes
let 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) {
let {
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) {
let {
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) {
let state = {
path,
uuid: _uuid()
};
this.history.pushState(state, '', path);
// used for webkit workaround
this._previousURL = this.getURL();
}
/**
Replaces the current state.
@private
@method replaceState
@param path {String}
*/
replaceState(path) {
let state = {
path,
uuid: _uuid()
};
this.history.replaceState(state, '', 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);
}
/**
Formats url to be placed into href attribute.
@private
@method formatURL
@param url {String}
@return formatted url {String}
*/
formatURL(url) {
let {
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);
}
}
}
const emberRoutingHistoryLocation = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: HistoryLocation
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/routing/none-location
*/
/**
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 EmberObject {
updateCallback;
// Set in reopen so it can be overwritten with extend
/**
Will be pre-pended to path.
@private
@property rootURL
@default '/'
*/
// Set in reopen so it can be overwritten with extend
initState() {
this._super(...arguments);
}
/**
Returns the current path without `rootURL`.
@private
@method getURL
@return {String} path
*/
getURL() {
let {
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) {
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) {
this.path = url;
if (this.updateCallback) {
this.updateCallback(url);
}
}
/**
Given a URL, formats it to be placed into the page as part
of an element's `href` attribute.
@private
@method formatURL
@param {String} url
@return {String} url
*/
formatURL(url) {
let {
rootURL
} = this;
if (url !== '') {
// remove trailing slashes if they exists
rootURL = rootURL.replace(/\/$/, '');
}
return rootURL + url;
}
}
NoneLocation.reopen({
path: '',
rootURL: '/'
});
const emberRoutingNoneLocation = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: NoneLocation
}, Symbol.toStringTag, { value: 'Module' });
/**
@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
*/
class ApplicationInstance extends EngineInstance {
/**
The `Application` for which this is an instance.
@property {Application} application
@private
*/
/**
The root DOM element of the Application as an element or a
CSS selector.
@private
@property {String|DOMElement} rootElement
*/
rootElement = null;
init(properties) {
super.init(properties);
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) {
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;
get router() {
if (!this._router) {
let router = this.lookup('router:main');
this._router = router;
}
return this._router;
}
/**
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() {
let dispatcher = this.lookup('event_dispatcher:main');
let applicationCustomEvents = get$2(this.application, 'customEvents');
let instanceCustomEvents = get$2(this, 'customEvents');
let 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 transition was aborted due to an error.
@public
@param url {String} the destination URL
@return {Promise<ApplicationInstance>}
*/
visit(url) {
this.setupRouter();
let bootOptions = this.__container__.lookup('-environment:main');
let router = this.router;
let 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 renderSettled().then(() => this);
}
};
let handleTransitionReject = error => {
if (error.error && error.error instanceof 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;
}
};
let location = get$2(router, 'location');
location.setURL(url);
// getURL returns the set url with the rootURL stripped off
return router.handleURL(location.getURL()).then(handleTransitionResolve, handleTransitionReject);
}
willDestroy() {
super.willDestroy();
this.application._unwatchInstance(this);
}
/**
@private
@method setupRegistry
@param {Registry} registry
@param {BootOptions} options
*/
static setupRegistry(registry, options = {}) {
let coptions = options instanceof _BootOptions ? options : new _BootOptions(options);
registry.register('-environment:main', coptions.toEnvironment(), {
instantiate: false
});
registry.register('service:-document', coptions.document, {
instantiate: false
});
super.setupRegistry(registry, coptions);
}
}
/**
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 {
/**
Interactive mode: whether we need to set up event delegation and invoke
lifecycle callbacks on Components.
@property isInteractive
@type boolean
@default auto-detected
@private
*/
isInteractive;
/**
@property _renderMode
@type string
@default undefined
@private
*/
_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
*/
isBrowser;
/**
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
*/
location = null;
/**
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
*/
shouldRender;
/**
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
*/
document;
/**
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
*/
rootElement;
constructor(options = {}) {
this.isInteractive = Boolean(hasDOM); // This default is overridable below
this._renderMode = options._renderMode;
if (options.isBrowser !== undefined) {
this.isBrowser = Boolean(options.isBrowser);
} else {
this.isBrowser = Boolean(hasDOM);
}
if (!this.isBrowser) {
this.isInteractive = false;
this.location = 'none';
}
if (options.shouldRender !== undefined) {
this.shouldRender = Boolean(options.shouldRender);
} else {
this.shouldRender = true;
}
if (!this.shouldRender) {
this.isInteractive = false;
}
if (options.document) {
this.document = options.document;
} else {
this.document = typeof document !== 'undefined' ? document : null;
}
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 (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!?
return {
...emberinternalsBrowserEnvironmentIndex,
// For compatibility with existing code
hasDOM: this.isBrowser,
isInteractive: this.isInteractive,
_renderMode: this._renderMode,
options: this
};
}
}
const emberApplicationInstance = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: ApplicationInstance
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/application/namespace
*/
/**
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
@extends EmberObject
@public
*/
class Namespace extends EmberObject {
static NAMESPACES = NAMESPACES;
static NAMESPACES_BY_ID = NAMESPACES_BY_ID;
static processAll = processAllNamespaces;
static byName = findNamespace;
init(properties) {
super.init(properties);
addNamespace(this);
}
toString() {
let existing_name = get$2(this, 'name') || get$2(this, 'modulePrefix');
if (existing_name) {
return existing_name;
}
findNamespaces();
let name = getName(this);
if (name === undefined) {
name = guidFor(this);
setName(this, name);
}
return name;
}
nameClasses() {
processNamespace(this);
}
destroy() {
removeNamespace(this);
return super.destroy();
}
}
// Declare on the prototype to have a single shared value.
Namespace.prototype.isNamespace = true;
const emberApplicationNamespace = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: Namespace
}, Symbol.toStringTag, { value: 'Module' });
/**
* 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;
}();
/** @private */
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;
}();
const dagMap = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: DAG
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/debug/container-debug-adapter
*/
/**
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
*/
class ContainerDebugAdapter extends EmberObject {
constructor(owner) {
super(owner);
this.resolver = getOwner$2(this).lookup('resolver-for-debugging:main');
}
/**
The resolver instance of the application
being debugged. This property will be injected
on creation.
@property resolver
@public
*/
resolver;
/**
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) {
let namespaces = Namespace.NAMESPACES;
let types = [];
let typeSuffixRegex = new RegExp(`${classify(type)}$`);
namespaces.forEach(namespace => {
for (let key in namespace) {
if (!Object.prototype.hasOwnProperty.call(namespace, key)) {
continue;
}
if (typeSuffixRegex.test(key)) {
let klass = namespace[key];
if (typeOf(klass) === 'class') {
types.push(dasherize(key.replace(typeSuffixRegex, '')));
}
}
}
});
return types;
}
}
const emberDebugContainerDebugAdapter = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: ContainerDebugAdapter
}, Symbol.toStringTag, { value: 'Module' });
function props(obj) {
let properties = [];
for (let 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 RegistryProxyMixin
@public
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
class Engine extends Namespace.extend(RegistryProxyMixin) {
static initializers = Object.create(null);
static 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
*/
static initializer = buildInitializerMethod('initializers');
/**
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
*/
static instanceInitializer = buildInitializerMethod('instanceInitializers');
/**
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
*/
static buildRegistry(namespace) {
let registry = new Registry({
resolver: resolverFor(namespace)
});
registry.set = set;
registry.register('application:main', namespace, {
instantiate: false
});
commonSetupRegistry$1(registry);
setupEngineRegistry(registry);
return registry;
}
/**
Set this to provide an alternate class to `DefaultResolver`
@property resolver
@public
*/
init(properties) {
super.init(properties);
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();
return EngineInstance.create({
...options,
base: this
});
}
/**
Build and configure the registry for the current engine.
@private
@method buildRegistry
@return {Ember.Registry} the configured registry
*/
buildRegistry() {
let registry = this.__registry__ = this.constructor.buildRegistry(this);
return registry;
}
/**
@private
@method initializer
*/
initializer(initializer) {
this.constructor.initializer(initializer);
}
/**
@private
@method instanceInitializer
*/
instanceInitializer(initializer) {
this.constructor.instanceInitializer(initializer);
}
/**
@private
@method runInitializers
*/
runInitializers() {
this._runInitializer('initializers', (name, initializer) => {
initializer.initialize(this);
});
}
/**
@private
@since 1.12.0
@method runInstanceInitializers
*/
runInstanceInitializers(instance) {
this._runInitializer('instanceInitializers', (name, initializer) => {
initializer.initialize(instance);
});
}
_runInitializer(bucketName, cb) {
let initializersByName = get$2(this.constructor, bucketName);
let initializers = props(initializersByName);
let graph = new DAG();
let initializer;
for (let name of initializers) {
initializer = initializersByName[name];
graph.add(initializer.name, initializer, initializer.before, initializer.after);
}
graph.topsort(cb);
}
}
/**
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.Enginer} namespace the namespace to look for classes
@return {*} the resolved value for a given lookup
*/
function resolverFor(namespace) {
let ResolverClass = namespace.Resolver;
let props = {
namespace
};
return ResolverClass.create(props);
}
/** @internal */
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.
// SAFETY: The superclass may be an Engine, we don't call unless we confirmed it was ok.
let superclass = this.superclass;
if (superclass[bucketName] !== undefined && superclass[bucketName] === this[bucketName]) {
let attrs = {
[bucketName]: Object.create(this[bucketName])
};
this.reopenClass(attrs);
}
let initializers = this[bucketName];
initializers[initializer.name] = initializer;
};
}
function commonSetupRegistry$1(registry) {
registry.optionsForType('component', {
singleton: false
});
registry.optionsForType('view', {
singleton: false
});
registry.register('controller:basic', Controller, {
instantiate: false
});
// Register the routing service...
registry.register('service:-routing', RoutingService);
// DEBUGGING
registry.register('resolver-for-debugging:main', registry.resolver, {
instantiate: false
});
registry.register('container-debug-adapter:main', ContainerDebugAdapter);
registry.register('component-lookup:main', ComponentLookup);
}
const emberEngineIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
buildInitializerMethod,
default: Engine,
getEngineParent,
setEngineParent
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/application
*/
/**
* @deprecated Use `import { getOwner } from '@ember/owner';` instead.
*/
const getOwner = getOwner$1;
/**
* @deprecated Use `import { setOwner } from '@ember/owner';` instead.
*/
const setOwner = setOwner$1;
/**
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
export default class App extends Application {
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';
export default class App extends Application {
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';
export default class App extends Application {
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';
export default class App extends Application {
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
@public
*/
class Application extends Engine {
/**
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
*/
static buildRegistry(namespace) {
let registry = super.buildRegistry(namespace);
commonSetupRegistry(registry);
setupApplicationRegistry(registry);
return registry;
}
static initializer = buildInitializerMethod('initializers');
static instanceInitializer = buildInitializerMethod('instanceInitializers');
/**
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
*/
/**
@property _document
@type Document | null
@default 'window.document'
@private
*/
/**
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
*/
/**
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
*/
/**
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
*/
/**
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
*/
/**
An array of application instances created by `buildInstance()`. Used
internally to ensure that all instances get destroyed.
@property _applicationInstances
@type Array
@private
*/
init(properties) {
super.init(properties);
this.rootElement ??= 'body';
this._document ??= null;
this.eventDispatcher ??= null;
this.customEvents ??= null;
this.autoboot ??= true;
this._document ??= hasDOM ? window.document : null;
this._globalsMode ??= true;
// 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 = {}) {
return ApplicationInstance.create({
...options,
base: this,
application: this
});
}
/**
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);
}
Router;
/**
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 || EmberRouter).extend();
this._buildDeprecatedInstance();
}
__deprecatedInstance__;
__container__;
/*
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
let 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() {
const document = this._document;
// SAFETY: Casting as Document should be safe since we're just reading a property.
// If it's not actually a Document then it will evaluate false which is fine for our
// purposes.
if (document === null || document.readyState !== 'loading') {
schedule('actions', this, this.domReady);
} else {
let callback = () => {
document.removeEventListener('DOMContentLoaded', callback);
run$1(this, this.domReady);
};
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() {
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() {
this._readinessDeferrals--;
if (this._readinessDeferrals === 0) {
once(this, this.didBecomeReady);
}
}
_bootPromise = null;
/**
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() {
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;
}
_bootResolver = null;
/**
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.
let defer = this._bootResolver = rsvp.defer();
this._bootPromise = defer.promise;
try {
this.runInitializers();
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() {
let instance = this.__deprecatedInstance__;
this._readinessDeferrals = 1;
this._bootPromise = null;
this._bootResolver = null;
this._booted = false;
function handleReset() {
run$1(instance, 'destroy');
this._buildDeprecatedInstance();
schedule('actions', this, '_bootSync');
}
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) {
let instance;
if (this._globalsMode) {
// If we already have the __deprecatedInstance__ lying around, boot it to
// avoid unnecessary work
instance = this.__deprecatedInstance__;
(false && !(instance) && assert$1('expected instance', instance));
} 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() {
super.willDestroy();
if (_loaded['application'] === this) {
_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 { 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) {
return this.boot().then(() => {
let instance = this.buildInstance();
return instance.boot(options).then(() => instance.visit(url)).catch(error => {
run$1(instance, 'destroy');
throw error;
});
});
}
}
function commonSetupRegistry(registry) {
registry.register('router:main', EmberRouter);
registry.register('-view-registry:main', {
create() {
return makeDictionary(null);
}
});
registry.register('route:basic', Route);
registry.register('event_dispatcher:main', EventDispatcher);
registry.register('location:hash', HashLocation);
registry.register('location:history', HistoryLocation);
registry.register('location:none', NoneLocation);
registry.register(privatize`-bucket-cache:main`, {
create() {
return new BucketCache();
}
});
registry.register('service:router', RouterService);
}
const emberApplicationIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
_loaded,
default: Application,
getOwner,
onLoad,
runLoadHooks,
setOwner
}, Symbol.toStringTag, { value: 'Module' });
const emberArrayMutable = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: MutableArray
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/array/proxy
*/
const 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 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 EmberObject {
/*
`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.
*/
/** @internal */
_objectsDirtyIndex = 0;
/** @internal */
_objects = null;
/** @internal */
_lengthDirty = true;
/** @internal */
_length = 0;
/** @internal */
_arrangedContent = null;
/** @internal */
_arrangedContentIsUpdating = false;
/** @internal */
_arrangedContentTag = null;
/** @internal */
_arrangedContentRevision = null;
/** @internal */
_lengthTag = null;
/** @internal */
_arrTag = null;
init(props) {
super.init(props);
setCustomTagFor(this, customTagForArrayProxy);
}
[PROPERTY_DID_CHANGE]() {
this._revalidate();
}
willDestroy() {
this._removeArrangedContentArrayObserver();
}
objectAtContent(idx) {
let arrangedContent = get$2(this, 'arrangedContent');
return objectAt(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) {
this.replaceContent(idx, amt, objects);
}
replaceContent(idx, amt, objects) {
let content = get$2(this, 'content');
replace(content, 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) {
let arrangedContent = get$2(this, 'arrangedContent');
if (arrangedContent) {
let length = this._objects.length = get$2(arrangedContent, 'length');
for (let i = this._objectsDirtyIndex; i < length; i++) {
// SAFETY: This is expected to only ever return an instance of T. In other words, there should
// be no gaps in the array. Unfortunately, we can't actually assert for it since T could include
// any types, including null or undefined.
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) {
let arrangedContent = get$2(this, 'arrangedContent');
this._length = arrangedContent ? get$2(arrangedContent, 'length') : 0;
this._lengthDirty = false;
}
consumeTag(this._lengthTag);
return this._length;
}
set length(value) {
let length = this.length;
let removedCount = length - value;
let added;
if (removedCount === 0) {
return;
} else if (removedCount < 0) {
added = new Array(-removedCount);
removedCount = 0;
}
let content = get$2(this, 'content');
if (content) {
replace(content, value, removedCount, added);
this._invalidate();
}
}
_updateArrangedContentArray(arrangedContent) {
let oldLength = this._objects === null ? 0 : this._objects.length;
let newLength = arrangedContent ? get$2(arrangedContent, 'length') : 0;
this._removeArrangedContentArrayObserver();
arrayContentWillChange(this, 0, oldLength, newLength);
this._invalidate();
arrayContentDidChange(this, 0, oldLength, newLength, false);
this._addArrangedContentArrayObserver(arrangedContent);
}
_addArrangedContentArrayObserver(arrangedContent) {
if (arrangedContent && !arrangedContent.isDestroyed) {
addArrayObserver(arrangedContent, this, ARRAY_OBSERVER_MAPPING);
this._arrangedContent = arrangedContent;
}
}
_removeArrangedContentArrayObserver() {
if (this._arrangedContent) {
removeArrayObserver(this._arrangedContent, this, ARRAY_OBSERVER_MAPPING);
}
}
_arrangedContentArrayWillChange() {}
_arrangedContentArrayDidChange(_proxy, idx, removedCnt, addedCnt) {
arrayContentWillChange(this, idx, removedCnt, addedCnt);
let dirtyIndex = idx;
if (dirtyIndex < 0) {
let length = get$2(this._arrangedContent, 'length');
dirtyIndex += length + removedCnt - addedCnt;
}
if (this._objectsDirtyIndex === -1 || this._objectsDirtyIndex > dirtyIndex) {
this._objectsDirtyIndex = dirtyIndex;
}
this._lengthDirty = true;
arrayContentDidChange(this, idx, removedCnt, addedCnt, false);
}
_invalidate() {
this._objectsDirtyIndex = 0;
this._lengthDirty = true;
}
_revalidate() {
if (this._arrangedContentIsUpdating === true) return;
if (this._arrangedContentTag === null || !validateTag(this._arrangedContentTag, this._arrangedContentRevision)) {
let 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;
}
let arrangedContentTag = this._arrangedContentTag = tagFor(this, 'arrangedContent');
this._arrangedContentRevision = valueForTag(this._arrangedContentTag);
if (isObject$1(arrangedContent)) {
this._lengthTag = combine([arrangedContentTag, tagForProperty(arrangedContent, 'length')]);
this._arrTag = combine([arrangedContentTag, tagForProperty(arrangedContent, '[]')]);
} else {
this._lengthTag = this._arrTag = arrangedContentTag;
}
}
}
}
ArrayProxy.reopen(MutableArray, {
arrangedContent: alias('content')
});
const emberArrayProxy = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: ArrayProxy
}, Symbol.toStringTag, { value: 'Module' });
/**
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
*/
const DEFAULT_FEATURES = {
// FLAG_NAME: true/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
*/
const FEATURES = Object.assign(DEFAULT_FEATURES, 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
*/
function isEnabled(feature) {
let value = FEATURES[feature];
if (value === true || value === false) {
return value;
} else if (ENV.ENABLE_OPTIONAL_FEATURES) {
return true;
} else {
return false;
}
}
// Uncomment the below when features are present:
// function featureValue(value: null | boolean) {
// if (ENV.ENABLE_OPTIONAL_FEATURES && value === null) {
// return true;
// }
// return value;
// }
//
// export const FLAG_NAME = featureValue(FEATURES.FLAG_NAME);
const emberCanaryFeaturesIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
DEFAULT_FEATURES,
FEATURES,
isEnabled
}, Symbol.toStringTag, { value: 'Module' });
const emberComponentHelper = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: Helper,
helper: helper$2
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/component
@public
*/
/**
* Assigns a TemplateFactory to a component class.
*
* @method setComponentTemplate
* @static
* @for @ember/component
* @public
*
* ```js
* import Component from '@glimmer/component';
* import { hbs } from 'ember-cli-htmlbars';
* import { setComponentTemplate } from '@ember/component';
*
* export default class Demo extends Component {
* // ...
* }
*
* setComponentTemplate(hbs`
* <div>my template</div>
* `, Demo);
* ```
*
* @param {TemplateFactory} templateFactory
* @param {object} componentDefinition
*/
/**
* Returns the TemplateFactory associated with a component
*
* @method getComponentTemplate
* @static
* @for @ember/component
* @public
*
* ```js
* import Component from '@glimmer/component';
* import { hbs } from 'ember-cli-htmlbars';
* import { getComponentTemplate } from '@ember/component';
*
* export default class Demo extends Component {
* // ...
* }
*
* let theTemplateFactory = getTemplateFactory(Demo)
* ```
*
* @param {object} componentDefinition
* @returns {TemplateFactory}
*/
/**
* Tell the VM how manage a type of object / class when encountered
* via component-invocation.
*
* A Component Manager, must implement this interface:
* - static create()
* - createComponent()
* - updateComponent()
* - destroyComponent()
* - getContext()
*
* @method setComponentManager
* @static
* @for @ember/component
* @public
*
*
* After a component manager is registered via `setComponentManager`,
*
* ```js
* import { StateNode } from 'xstate';
* import ComponentManager from './-private/statechart-manager';
*
* setComponentManager((owner) => ComponentManager.create(owner), StateNode.prototype);
* ```
*
* Instances of the class can be used as component.
* No need to extend from `@glimmer/component`.
*
* ```js
* // app/components/my-component.js
* import { createMachine } from 'xstate';
*
* export default createMachine({ ... });
* ```
* ```hbs
* {{!-- app/templates/application.hbs}}
* <MyComponent />
* ```
*
* @param {(owner: Owner) => import('@glimmer/interfaces').ComponentManager} managerFactory
* @param {object} object that will be managed by the return value of `managerFactory`
*
*/
/**
* Tells Glimmer what capabilities a Component Manager will have
*
* ```js
* import { capabilities } from '@ember/component';
*
* export class MyComponentManager {
* capabilities = capabilities('3.13', {
* // capabilities listed here
* })
* }
* ```
*
*
* For a full list of capabilities, their defaults, and how they are used, see [@glimmer/manager](https://github.com/glimmerjs/glimmer-vm/blob/4f1bef0d9a8a3c3ebd934c5b6e09de4c5f6e4468/packages/%40glimmer/manager/lib/public/component.ts#L26)
*
*
* @method capabilities
* @static
* @for @ember/component
* @public
* @param {'3.13'} managerApiVersion
* @param {Parameters<import('@ember/-internals/glimmer').componentCapabilities>[1]} options
*
*/
const emberComponentIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
Input,
Textarea,
capabilities: componentCapabilities,
default: Component,
getComponentTemplate,
setComponentManager,
setComponentTemplate
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/component/template-only
@public
*/
/**
* Template-only components have no backing class instance, so `this` in their
* templates is null. This means that you can only reference passed in arguments
* (e.g. `{{@arg}}`).
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
/**
* A convenience alias for {@link TemplateOnlyComponent}
*/
// NOTES:
//
// 1. The generic here is for a *signature: a way to hang information for tools
// like Glint which can provide typey checking for component templates using
// information supplied via this generic. While it may appear useless on this
// class definition and extension, it is used by external tools and should
// not be removed.
// 2. SAFETY: this cast is *throwing away* information that is not part of the
// public API and replacing it with something which has the same calling
// contract, but much less information (since we do not want to expose the
// internal APIs like `moduleName` etc.).
// prettier-ignore
const templateOnly = templateOnlyComponent;
const emberComponentTemplateOnly = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: templateOnly
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/debug/data-adapter
*/
// Represents the base contract for iterables as understood in the GLimmer VM
// historically. This is *not* the public API for it, because there *is* no
// public API for it. Recent versions of Glimmer simply use `Symbol.iterator`,
// but some older consumers still use this basic shape.
function iterate(arr, fn) {
if (Symbol.iterator in arr) {
for (let item of arr) {
fn(item);
}
} else {
// SAFETY: this cast required to work this way to interop between TS 4.8
// and 4.9. When we drop support for 4.8, it will narrow correctly via the
// use of the `in` operator above. (Preferably we will solve this by just
// switching to require `Symbol.iterator` instead.)
assert$1('', typeof arr.forEach === 'function');
arr.forEach(fn);
}
}
class RecordsWatcher {
recordCaches = new Map();
added = [];
updated = [];
removed = [];
getCacheForItem(record) {
let recordCache = this.recordCaches.get(record);
if (!recordCache) {
let hasBeenAdded = false;
recordCache = 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.wrapRecord = wrapRecord;
this.release = release;
this.recordArrayCache = createCache(() => {
let seen = new Set();
// Track `[]` for legacy support
consumeTag(tagFor(records, '[]'));
iterate(records, record => {
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
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() {
getValue(this.recordArrayCache);
}
}
class TypeWatcher {
constructor(records, onChange, release) {
this.release = release;
let hasBeenAccessed = false;
this.cache = createCache(() => {
// Empty iteration, we're doing this just
// to track changes to the records array
iterate(records, () => {});
// Also track `[]` for legacy support
consumeTag(tagFor(records, '[]'));
if (hasBeenAccessed === true) {
next(onChange);
} else {
hasBeenAccessed = true;
}
});
this.release = release;
}
revalidate() {
getValue(this.cache);
}
}
/**
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
*/
class DataAdapter extends EmberObject {
releaseMethods = A();
recordsWatchers = new Map();
typeWatchers = new Map();
flushWatchers = null;
// TODO: Revisit this
constructor(owner) {
super(owner);
this.containerDebugAdapter = getOwner$2(this).lookup('container-debug-adapter:main');
}
/**
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 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) {
let modelTypes = this.getModelTypes();
let releaseMethods = A();
let typesToSend;
typesToSend = modelTypes.map(type => {
let klass = type.klass;
let wrapped = this.wrapModelType(klass, type.name);
releaseMethods.push(this.observeModelType(type.name, typesUpdated));
return wrapped;
});
typesAdded(typesToSend);
let release = () => {
releaseMethods.forEach(fn => fn());
this.releaseMethods.removeObject(release);
};
this.releaseMethods.pushObject(release);
return release;
}
_nameToClass(type) {
if (typeof type === 'string') {
let owner = getOwner$2(this);
let 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) {
let klass = this._nameToClass(modelName);
let records = this.getRecords(klass, modelName);
let {
recordsWatchers
} = this;
let 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());
};
_backburner.on('end', this.flushWatchers);
}
} else if (this.typeWatchers.size === 0 && this.recordsWatchers.size === 0) {
_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) {
_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(_klass) {
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(_klass) {
return 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) {
let klass = this._nameToClass(modelName);
let records = this.getRecords(klass, modelName);
let onChange = () => {
typesUpdated([this.wrapModelType(klass, modelName)]);
};
let {
typeWatchers
} = this;
let 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} 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.
*/
wrapModelType(klass, name) {
let records = this.getRecords(klass, name);
return {
name,
count: get$2(records, 'length'),
columns: this.columnsForType(klass),
object: klass
};
}
/**
Fetches all models defined in the application.
@private
@method getModelTypes
@return {Array} Array of model types.
*/
getModelTypes() {
let containerDebugAdapter = this.containerDebugAdapter;
let stringTypes = containerDebugAdapter.canCatalogEntriesByType('model') ? containerDebugAdapter.catalogEntriesByType('model') : this._getObjectsOnNamespaces();
// New adapters return strings instead of classes.
let klassTypes = stringTypes.map(name => {
return {
klass: this._nameToClass(name),
name
};
});
return klassTypes.filter(type => this.detect(type.klass));
}
/**
Loops over all namespaces and all objects
attached to them.
@private
@method _getObjectsOnNamespaces
@return {Array} Array of model type strings.
*/
_getObjectsOnNamespaces() {
let namespaces = Namespace.NAMESPACES;
let types = [];
namespaces.forEach(namespace => {
for (let 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;
}
let name = 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(_klass, _name) {
return 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) {
return {
object: record,
columnValues: this.getRecordColumnValues(record),
searchKeywords: this.getRecordKeywords(record),
filterValues: this.getRecordFilterValues(record),
color: this.getRecordColor(record)
};
}
/**
Gets the values for each column.
@public
@method getRecordColumnValues
@return {Object} Keys should match column names defined
by the model type.
*/
getRecordColumnValues(_record) {
return {};
}
/**
Returns keywords to match when searching records.
@public
@method getRecordKeywords
@return {Array} Relevant keywords for search.
*/
getRecordKeywords(_record) {
return A();
}
/**
Returns the values of filters defined by `getFilters`.
@public
@method getRecordFilterValues
@param {Object} record The record instance.
@return {Object} The filter values.
*/
getRecordFilterValues(_record) {
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(_record) {
return null;
}
}
const emberDebugDataAdapter = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: DataAdapter
}, Symbol.toStringTag, { value: 'Module' });
// These versions should be the version that the deprecation was _introduced_,
// not the version that the feature will be removed.
/** Introduced in 4.0.0-beta.1 */
const ASSIGN = true;
const emberDeprecatedFeaturesIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
ASSIGN
}, Symbol.toStringTag, { value: 'Module' });
/**
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 destroyed
* 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(...args) {
super(...args);
// 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 Component from '@glimmer/component';
import { registerDestructor } from '@ember/destroyable';
class Modal extends Component {
@service resize;
constructor(...args) {
super(...args);
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 Component from '@glimmer/component';
import { registerDestructor } from '@ember/destroyable';
function unregisterResize(instance) {
instance.resize.unregister(instance);
}
class Modal extends Component {
@service resize;
constructor(...args) {
super(...args);
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 registerDestructor$1(destroyable, destructor);
}
/**
Receives a destroyable and a destructor function, and de-associates the destructor
from the destroyable.
```js
import Component from '@glimmer/component';
import { registerDestructor, unregisterDestructor } from '@ember/destroyable';
class Modal extends Component {
@service modals;
constructor(...args) {
super(...args);
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 unregisterDestructor$1(destroyable, destructor);
}
const emberDestroyableIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
assertDestroyablesDestroyed,
associateDestroyableChild,
destroy,
enableDestroyableTracking,
isDestroyed,
isDestroying,
registerDestructor,
unregisterDestructor
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/helper
*/
/**
`capabilities` returns a capabilities configuration which can be used to modify
the behavior of the manager. Manager capabilities _must_ be provided using the
`capabilities` function, as the underlying implementation can change over time.
The first argument to capabilities is a version string, which is the version of
Ember that the capabilities were defined in. Ember can add new versions at any
time, and these may have entirely different behaviors, but it will not remove
old versions until the next major version.
```js
capabilities('3.23');
```
The second argument is an object of capabilities and boolean values indicating
whether they are enabled or disabled.
```js
capabilities('3.23', {
hasValue: true,
hasDestructor: true,
});
```
If no value is specified, then the default value will be used.
### `3.23` capabilities
#### `hasDestroyable`
- Default value: false
Determines if the helper has a destroyable to include in the destructor
hierarchy. If enabled, the `getDestroyable` hook will be called, and its result
will be associated with the destroyable parent block.
#### `hasValue`
- Default value: false
Determines if the helper has a value which can be used externally. The helper's
`getValue` hook will be run whenever the value of the helper is accessed if this
capability is enabled.
@method capabilities
@for @ember/helper
@static
@param {String} managerApiVersion The version of capabilities that are being used
@param options The capabilities values
@return {Capabilities} The capabilities object instance
@public
*/
const capabilities = helperCapabilities;
/**
Sets the helper manager for an object or function.
```js
setHelperManager((owner) => new ClassHelperManager(owner), Helper)
```
When a value is used as a helper in a template, the helper manager is looked up
on the object by walking up its prototype chain and finding the first helper
manager. This manager then receives the value and can create and manage an
instance of a helper from it. This provides a layer of indirection that allows
users to design high-level helper APIs, without Ember needing to worry about the
details. High-level APIs can be experimented with and iterated on while the
core of Ember helpers remains stable, and new APIs can be introduced gradually
over time to existing code bases.
`setHelperManager` receives two arguments:
1. A factory function, which receives the `owner` and returns an instance of a
helper manager.
2. A helper definition, which is the object or function to associate the factory function with.
The first time the object is looked up, the factory function will be called to
create the helper manager. It will be cached, and in subsequent lookups the
cached helper manager will be used instead.
Only one helper manager is guaranteed to exist per `owner` and per usage of
`setHelperManager`, so many helpers will end up using the same instance of the
helper manager. As such, you should only store state that is related to the
manager itself. If you want to store state specific to a particular helper
definition, you should assign a unique helper manager to that helper. In
general, most managers should either be stateless, or only have the `owner` they
were created with as state.
Helper managers must fulfill the following interface (This example uses
[TypeScript interfaces](https://www.typescriptlang.org/docs/handbook/interfaces.html)
for precision, you do not need to write helper managers using TypeScript):
```ts
interface HelperManager<HelperStateBucket> {
capabilities: HelperCapabilities;
createHelper(definition: HelperDefinition, args: TemplateArgs): HelperStateBucket;
getValue?(bucket: HelperStateBucket): unknown;
runEffect?(bucket: HelperStateBucket): void;
getDestroyable?(bucket: HelperStateBucket): object;
}
```
The capabilities property _must_ be provided using the `capabilities()` function
imported from the same module as `setHelperManager`:
```js
import { capabilities } from '@ember/helper';
class MyHelperManager {
capabilities = capabilities('3.21.0', { hasValue: true });
// ...snip...
}
```
Below is a description of each of the methods on the interface and their
functions.
#### `createHelper`
`createHelper` is a required hook on the HelperManager interface. The hook is
passed the definition of the helper that is currently being created, and is
expected to return a _state bucket_. This state bucket is what represents the
current state of the helper, and will be passed to the other lifecycle hooks at
appropriate times. It is not necessarily related to the definition of the
helper itself - for instance, you could return an object _containing_ an
instance of the helper:
```js
class MyManager {
createHelper(Definition, args) {
return {
instance: new Definition(args);
};
}
}
```
This allows the manager to store metadata that it doesn't want to expose to the
user.
This hook is _not_ autotracked - changes to tracked values used within this hook
will _not_ result in a call to any of the other lifecycle hooks. This is because
it is unclear what should happen if it invalidates, and rather than make a
decision at this point, the initial API is aiming to allow as much expressivity
as possible. This could change in the future with changes to capabilities and
their behaviors.
If users do want to autotrack some values used during construction, they can
either create the instance of the helper in `runEffect` or `getValue`, or they
can use the `cache` API to autotrack the `createHelper` hook themselves. This
provides maximum flexibility and expressiveness to manager authors.
This hook has the following timing semantics:
**Always**
- called as discovered during DOM construction
- called in definition order in the template
#### `getValue`
`getValue` is an optional hook that should return the value of the helper. This
is the value that is returned from the helper and passed into the template.
This hook is called when the value is requested from the helper (e.g. when the
template is rendering and the helper value is needed). The hook is autotracked,
and will rerun whenever any tracked values used inside of it are updated.
Otherwise it does not rerun.
> Note: This means that arguments which are not _consumed_ within the hook will
> not trigger updates.
This hook is only called for helpers with the `hasValue` capability enabled.
This hook has the following timing semantics:
**Always**
- called the first time the helper value is requested
- called after autotracked state has changed
**Never**
- called if the `hasValue` capability is disabled
#### `runEffect`
`runEffect` is an optional hook that should run the effect that the helper is
applying, setting it up or updating it.
This hook is scheduled to be called some time after render and prior to paint.
There is not a guaranteed, 1-to-1 relationship between a render pass and this
hook firing. For instance, multiple render passes could occur, and the hook may
only trigger once. It may also never trigger if it was dirtied in one render
pass and then destroyed in the next.
The hook is autotracked, and will rerun whenever any tracked values used inside
of it are updated. Otherwise it does not rerun.
The hook is also run during a time period where state mutations are _disabled_
in Ember. Any tracked state mutation will throw an error during this time,
including changes to tracked properties, changes made using `Ember.set`, updates
to computed properties, etc. This is meant to prevent infinite rerenders and
other antipatterns.
This hook is only called for helpers with the `hasScheduledEffect` capability
enabled. This hook is also not called in SSR currently, though this could be
added as a capability in the future. It has the following timing semantics:
**Always**
- called after the helper was first created, if the helper has not been
destroyed since creation
- called after autotracked state has changed, if the helper has not been
destroyed during render
**Never**
- called if the `hasScheduledEffect` capability is disabled
- called in SSR
#### `getDestroyable`
`getDestroyable` is an optional hook that users can use to register a
destroyable object for the helper. This destroyable will be registered to the
containing block or template parent, and will be destroyed when it is destroyed.
See the [Destroyables RFC](https://github.com/emberjs/rfcs/blob/master/text/0580-destroyables.md)
for more details.
`getDestroyable` is only called if the `hasDestroyable` capability is enabled.
This hook has the following timing semantics:
**Always**
- called immediately after the `createHelper` hook is called
**Never**
- called if the `hasDestroyable` capability is disabled
@method setHelperManager
@for @ember/helper
@static
@param {Function} factory A factory function which receives an optional owner, and returns a helper manager
@param {object} definition The definition to associate the manager factory with
@return {object} The definition passed into setHelperManager
@public
*/
const setHelperManager = setHelperManager$1;
/**
The `invokeHelper` function can be used to create a helper instance in
JavaScript.
To access a helper's value you have to use `getValue` from
`@glimmer/tracking/primitives/cache`.
```js
// app/components/data-loader.js
import Component from '@glimmer/component';
import { getValue } from '@glimmer/tracking/primitives/cache';
import Helper from '@ember/component/helper';
import { invokeHelper } from '@ember/helper';
class PlusOne extends Helper {
compute([number]) {
return number + 1;
}
}
export default class PlusOneComponent extends Component {
plusOne = invokeHelper(this, PlusOne, () => {
return {
positional: [this.args.number],
};
});
get value() {
return getValue(this.plusOne);
}
}
```
```js
{{this.value}}
```
It receives three arguments:
* `context`: The parent context of the helper. When the parent is torn down and
removed, the helper will be as well.
* `definition`: The definition of the helper.
* `computeArgs`: An optional function that produces the arguments to the helper.
The function receives the parent context as an argument, and must return an
object with a `positional` property that is an array and/or a `named`
property that is an object.
And it returns a Cache instance that contains the most recent value of the
helper. You can access the helper using `getValue()` like any other cache. The
cache is also destroyable, and using the `destroy()` function on it will cause
the helper to be torn down.
Note that using `getValue()` on helpers that have scheduled effects will not
trigger the effect early. Effects will continue to run at their scheduled time.
@method invokeHelper
@for @ember/helper
@static
@param {object} context The parent context of the helper
@param {object} definition The helper definition
@param {Function} computeArgs An optional function that produces args
@returns
@public
*/
const invokeHelper = invokeHelper$1;
// SAFETY: we need to provide interfaces that Glint can declaration-merge with
// to provide appropriate completions. In each case, the imported item is
// currently typed only as `object`, and we are replacing it with a similarly
// low-information interface type: these are empty objects which are simply able
// to be distinguished so that Glint can provide the relevant extensions.
/* eslint-disable @typescript-eslint/no-empty-interface */
/**
* Using the `{{hash}}` helper, you can pass objects directly from the template
* as an argument to your components.
*
* ```
* import { hash } from '@ember/helper';
*
* <template>
* {{#each-in (hash givenName='Jen' familyName='Weber') as |key value|}}
* <p>{{key}}: {{value}}</p>
* {{/each-in}}
* </template>
* ```
*
* **NOTE:** this example uses the experimental `<template>` feature, which is
* the only place you need to import `hash` to use it (it is a built-in when
* writing standalone `.hbs` files).
*/
const hash = hash$1;
/**
* Using the `{{array}}` helper, you can pass arrays directly from the template
* as an argument to your components.
*
* ```js
* import { array } from '@ember/helper';
*
* <template>
* <ul>
* {{#each (array 'Tom Dale' 'Yehuda Katz' @anotherPerson) as |person|}}
* <li>{{person}}</li>
* {{/each}}
* </ul>
* </template>
*
* **NOTE:** this example uses the experimental `<template>` feature, which is
* the only place you need to import `array` to use it (it is a built-in when
* writing standalone `.hbs` files).
* ```
*/
const array = array$1;
/**
* The `{{concat}}` helper makes it easy to dynamically send a number of
* parameters to a component or helper as a single parameter in the format of a
* concatenated string.
*
* For example:
*
* ```js
* import { concat } from '@ember/helper';
*
* <template>
* {{get @foo (concat "item" @index)}}
* </template>
* ```
*
* This will display the result of `@foo.item1` when `index` is `1`, and
* `this.foo.item2` when `index` is `2`, etc.
*
* **NOTE:** this example uses the experimental `<template>` feature, which is
* the only place you need to import `concat` to use it (it is a built-in when
* writing standalone `.hbs` files).
*/
const concat = concat$1;
/**
* The `{{get}}` helper makes it easy to dynamically look up a property on an
* object or an element in an array. The second argument to `{{get}}` can be a
* string or a number, depending on the object being accessed.
*
* To access a property on an object with a string key:
*
* ```js
* import { get } from '@ember/helper';
*
* <template>
* {{get @someObject "objectKey"}}
* </template>
* ```
*
* To access the first element in an array:
*
* ```js
* import { get } from '@ember/helper';
*
* <template>
* {{get @someArray 0}}
* </template>
* ```
*
* To access a property on an object with a dynamic key:
*
* ```js
* import { get } from '@ember/helper';
*
* <template>
* {{get @address @field}}
* </template>
* ```
*
* This will display the result of `@foo.item1` when `index` is `1`, and
* `this.foo.item2` when `index` is `2`, etc.
*
* **NOTE:** this example uses the experimental `<template>` feature, which is
* the only place you need to import `concat` to use it (it is a built-in when
* writing standalone `.hbs` files).
*/
const get = get$1;
/**
* `{{fn}}` is a helper that receives a function and some arguments, and returns
* a new function that combines. This allows you to pass parameters along to
* functions in your templates:
*
* ```js
* import { fn } from '@ember/helper';
*
* function showAlert(message) {
* alert(`The message is: '${message}'`);
* }
*
* <template>
* <button type="button" {{on "click" (fn showAlert "Hello!")}}>
* Click me!
* </button>
* </template>
* ```
*/
const fn = fn$1;
/**
* Use the {{uniqueId}} helper to generate a unique ID string suitable for use as
* an ID attribute in the DOM.
*
* Each invocation of {{uniqueId}} will return a new, unique ID string.
* You can use the `let` helper to create an ID that can be reused within a template.
*
* ```js
* import { uniqueId } from '@ember/helper';
*
* <template>
* {{#let (uniqueId) as |emailId|}}
* <label for={{emailId}}>Email address</label>
* <input id={{emailId}} type="email" />
* {{/let}}
* </template>
* ```
*/
const uniqueId = uniqueId$2;
/* eslint-enable @typescript-eslint/no-empty-interface */
const emberHelperIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
array,
capabilities,
concat,
fn,
get,
hash,
invokeHelper,
setHelperManager,
uniqueId
}, Symbol.toStringTag, { value: 'Module' });
// NOTE: this uses assignment to *require* that the `glimmerSetModifierManager`
// is legally assignable to this type, i.e. that variance is properly upheld.
const setModifierManager = setModifierManager$1;
const emberModifierIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
capabilities: modifierCapabilities,
on,
setModifierManager
}, Symbol.toStringTag, { value: 'Module' });
// This is a legacy location to keep the reexports test happy.
// Don't add anything new here.
const emberObjectInternals = /*#__PURE__*/Object.defineProperty({
__proto__: null,
cacheFor: getCachedValueFor,
guidFor
}, Symbol.toStringTag, { value: 'Module' });
const emberObjectObservers = /*#__PURE__*/Object.defineProperty({
__proto__: null,
addObserver,
removeObserver
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/object/promise-proxy-mixin
*/
function tap(proxy, promise) {
setProperties(proxy, {
isFulfilled: false,
isRejected: false
});
return promise.then(value => {
if (!proxy.isDestroyed && !proxy.isDestroying) {
setProperties(proxy, {
content: value,
isFulfilled: true
});
}
return value;
}, reason => {
if (!proxy.isDestroyed && !proxy.isDestroying) {
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
*/
const PromiseProxyMixin = Mixin.create({
reason: null,
isPending: computed('isSettled', function () {
return !get$2(this, 'isSettled');
}).readOnly(),
isSettled: computed('isRejected', 'isFulfilled', function () {
return get$2(this, 'isRejected') || get$2(this, 'isFulfilled');
}).readOnly(),
isRejected: false,
isFulfilled: false,
promise: computed({
get() {
throw new Error("PromiseProxy's promise must be set");
},
set(_key, promise) {
return tap(this, promise);
}
}),
then: promiseAlias('then'),
catch: promiseAlias('catch'),
finally: promiseAlias('finally')
});
function promiseAlias(name) {
return function (...args) {
let promise = get$2(this, 'promise');
// We need this cast because `Parameters` is deferred so that it is not
// possible for TS to see it will always produce the right type. However,
// since `AnyFn` has a rest type, it is allowed. See discussion on [this
// issue](https://github.com/microsoft/TypeScript/issues/47615).
return promise[name](...args);
};
}
const emberObjectPromiseProxyMixin = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: PromiseProxyMixin
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/object/proxy
*/
/**
`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
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
class ObjectProxy extends FrameworkObject {}
ObjectProxy.PrototypeMixin.reopen(ProxyMixin);
const emberObjectProxy = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: ObjectProxy
}, Symbol.toStringTag, { value: 'Module' });
/**
@module @ember/renderer
@public
*/
const emberRendererIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
renderSettled
}, Symbol.toStringTag, { value: 'Module' });
const emberRoutingIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
LinkTo
}, Symbol.toStringTag, { value: 'Module' });
const emberRoutingLibEngines = /*#__PURE__*/Object.defineProperty({
__proto__: null
}, Symbol.toStringTag, { value: 'Module' });
class QueryParams {
values;
isQueryParams = true;
constructor(values = null) {
this.values = values;
}
}
const emberRoutingLibQueryParams = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: QueryParams
}, Symbol.toStringTag, { value: 'Module' });
const emberRoutingLibRouteInfo = /*#__PURE__*/Object.defineProperty({
__proto__: null
}, Symbol.toStringTag, { value: 'Module' });
const emberRoutingLocation = /*#__PURE__*/Object.defineProperty({
__proto__: null
}, Symbol.toStringTag, { value: 'Module' });
const emberRoutingRouteInfo = /*#__PURE__*/Object.defineProperty({
__proto__: null
}, Symbol.toStringTag, { value: 'Module' });
const emberRoutingTransition = /*#__PURE__*/Object.defineProperty({
__proto__: null
}, Symbol.toStringTag, { value: 'Module' });
const emberRunloopprivateBackburner = /*#__PURE__*/Object.defineProperty({
__proto__: null
}, Symbol.toStringTag, { value: 'Module' });
// (UN)SAFETY: the public API is that people can import and use this (and indeed
// it is emitted as part of Ember's build!), so we define it as having the type
// which makes that work. However, in practice it is supplied by the build,
// *for* the build, and will *not* be present at runtime, so the actual value
// here is `undefined` in prod; in dev it is a function which throws a somewhat
// nicer error. This is janky, but... here we are.
let __emberTemplateCompiler;
const compileTemplate = (...args) => {
if (!__emberTemplateCompiler) {
throw new Error('Attempted to call `compileTemplate` without first loading the runtime template compiler.');
}
return __emberTemplateCompiler.compile(...args);
};
let precompileTemplate;
function __registerTemplateCompiler(c) {
__emberTemplateCompiler = c;
}
const emberTemplateCompilationIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
get __emberTemplateCompiler () { return __emberTemplateCompiler; },
__registerTemplateCompiler,
compileTemplate,
precompileTemplate
}, Symbol.toStringTag, { value: 'Module' });
// NOTE: this intentionally *only* exports the *type* `SafeString`, not its
// value, since it should not be constructed by users.
const emberTemplateIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
htmlSafe,
isHTMLSafe
}, Symbol.toStringTag, { value: 'Module' });
function run(fn) {
if (!_getCurrentRunLoop()) {
return run$1(fn);
} else {
return fn();
}
}
let lastPromise = null;
class TestPromise extends rsvp.Promise {
constructor(executor, label) {
super(executor, label);
lastPromise = this;
}
then(onFulfilled, onRejected, label) {
let normalizedOnFulfilled = typeof onFulfilled === 'function' ? result => isolate(onFulfilled, result) : undefined;
return super.then(normalizedOnFulfilled, onRejected, label);
}
}
/**
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.
*/
function promise(resolver, label) {
let 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(onFulfilled, result) {
// Reset lastPromise for nested helpers
lastPromise = null;
let value = onFulfilled(result);
let 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 run(() => resolve(promise).then(() => value));
}
}
const 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}
*/
function registerHelper$1(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$1(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$1(name) {
delete helpers[name];
// SAFETY: This isn't necessarily a safe thing to do, but in terms of the immediate types here
// it won't error.
delete TestPromise.prototype[name];
}
const callbacks$1 = [];
/**
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.
*/
function onInjectHelpers(callback) {
callbacks$1.push(callback);
}
function invokeInjectHelpersCallbacks(app) {
for (let callback of callbacks$1) {
callback(app);
}
}
/**
@module @ember/test
*/
const contexts = [];
const 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$1(
// Formatting makes a pretty big difference in how readable this is.
// prettier-ignore
...args) {
let checkedCallback;
let checkedContext;
if (args.length === 1) {
checkedContext = null;
checkedCallback = args[0];
} else {
checkedContext = args[0];
checkedCallback = args[1];
}
if (indexOf(checkedContext, checkedCallback) > -1) {
return;
}
contexts.push(checkedContext);
callbacks.push(checkedCallback);
}
/**
`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$1(context, callback) {
if (!callbacks.length) {
return;
}
if (arguments.length === 1) {
callback = context;
context = null;
}
let 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 (let i = 0; i < callbacks.length; i++) {
let context = contexts[i];
let callback = callbacks[i];
// SAFETY: The loop ensures that this exists
if (!callback.call(context)) {
return true;
}
}
return false;
}
function indexOf(context, callback) {
for (let i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback && contexts[i] === context) {
return i;
}
}
return -1;
}
let adapter;
function getAdapter() {
return adapter;
}
function setAdapter(value) {
adapter = value;
if (value && typeof value.exception === 'function') {
setDispatchOverride(adapterDispatch);
} else {
setDispatchOverride(null);
}
}
function asyncStart() {
if (adapter) {
adapter.asyncStart();
}
}
function asyncEnd() {
if (adapter) {
adapter.asyncEnd();
}
}
function adapterDispatch(error) {
adapter.exception(error);
// @ts-expect-error Normally unreachable
console.error(error.stack); // eslint-disable-line no-console
}
/**
@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
*/
const Test = {
/**
Hash containing all known test helpers.
@property _helpers
@private
@since 1.7.0
*/
_helpers: helpers,
registerHelper: registerHelper$1,
registerAsyncHelper: registerAsyncHelper$1,
unregisterHelper: unregisterHelper$1,
onInjectHelpers,
Promise: TestPromise,
promise,
resolve,
registerWaiter: registerWaiter$1,
unregisterWaiter: unregisterWaiter$1,
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: getAdapter,
set: setAdapter
});
/**
@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
*/
const Adapter = EmberObject.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() {},
/**
This callback will be called whenever an async operation has completed.
@public
@method asyncEnd
*/
asyncEnd() {},
/**
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;
}
});
/* globals QUnit */
function isVeryOldQunit(obj) {
return obj != null && typeof obj.stop === 'function';
}
/**
@module ember
*/
/**
This class implements the methods defined by TestAdapter for the
QUnit testing framework.
@class QUnitAdapter
@namespace Ember.Test
@extends TestAdapter
@public
*/
const QUnitAdapter = Adapter.extend({
init() {
this.doneCallbacks = [];
},
asyncStart() {
if (isVeryOldQunit(QUnit)) {
// very old QUnit version
// eslint-disable-next-line qunit/no-qunit-stop
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 (isVeryOldQunit(QUnit)) {
QUnit.start();
} else {
let 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, inspect(error));
}
});
/* 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() {
setTesting(true);
let adapter = getAdapter();
// if adapter is not manually set default to QUnit
if (!adapter) {
setAdapter(typeof self.QUnit === 'undefined' ? Adapter.create() : QUnitAdapter.create());
}
}
Application.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() {
setupForTesting();
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 (let name in helpers) {
// SAFETY: It is safe to access a property on an object
this.originalMethods[name] = this.helperContainer[name];
// SAFETY: It is not quite as safe to do this, but it _seems_ to be ok.
this.testHelpers[name] = this.helperContainer[name] = helper(this, name);
// SAFETY: We checked that it exists
protoWrap(TestPromise.prototype, name, helper(this, name), helpers[name].meta.wait);
}
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 (let name in helpers) {
this.helperContainer[name] = this.originalMethods[name];
// SAFETY: This is a weird thing, but it's not technically unsafe here.
delete TestPromise.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) {
// SAFETY: This isn't entirely safe, but it _seems_ to be ok.
proto[name] = function (...args) {
if (isAsync) {
return callback.apply(this, args);
} else {
// SAFETY: This is not actually safe.
return this.then(function () {
return callback.apply(this, args);
});
}
};
}
function helper(app, name) {
let helper = helpers[name];
let fn = helper.method;
let meta = helper.meta;
if (!meta.wait) {
return (...args) => fn.apply(app, [app, ...args]);
}
return (...args) => {
let lastPromise = run(() => resolve(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.
asyncStart();
return lastPromise.then(() => fn.apply(app, [app, ...args])).finally(asyncEnd);
};
}
rsvp.configure('async', function (callback, promise) {
// if schedule will cause autorun, we need to inform adapter
_backburner.schedule('actions', () => callback(promise));
});
function andThen(app, callback) {
let wait = app.testHelpers['wait'];
return wait(callback(app));
}
/**
@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) {
let routingService = app.__container__.lookup('service:-routing');
return get$2(routingService, 'currentPath');
}
/**
@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) {
let routingService = app.__container__.lookup('service:-routing');
return get$2(routingService, 'currentRouteName');
}
/**
@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) {
let router = app.__container__.lookup('router:main');
let location = get$2(router, 'location');
return location.getURL();
}
/**
@module ember
*/
let resume;
/**
Resumes a test paused by `pauseTest`.
@method resumeTest
@return {void}
@public
*/
function resumeTest() {
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() {
return new rsvp.Promise(resolve => {
resume = resolve;
}, 'TestAdapter paused promise');
}
/**
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) {
const router = app.__container__.lookup('router:main');
let shouldHandleURL = false;
app.boot().then(() => {
router.location.setURL(url);
if (shouldHandleURL) {
run$1(app.__deprecatedInstance__, 'handleURL', url);
}
});
if (app._readinessDeferrals > 0) {
// SAFETY: This should be safe, though it is odd.
router.initialURL = url;
run$1(app, 'advanceReadiness');
delete router.initialURL;
} else {
shouldHandleURL = true;
}
let wait = app.testHelpers['wait'];
return wait();
}
let requests = [];
function pendingRequests() {
return requests.length;
}
/**
@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 rsvp.Promise(function (resolve) {
const router = app.__container__.lookup('router:main');
let watcher = setInterval(() => {
// 1. If the router is loading, keep polling
let routerIsLoading = router._routerMicrolib && Boolean(router._routerMicrolib.activeTransition);
if (routerIsLoading) {
return;
}
// 2. If there are pending Ajax requests, keep polling
if (pendingRequests()) {
return;
}
// 3. If there are scheduled timers or we are inside of a run loop, keep polling
if (_hasScheduledTimers() || _getCurrentRunLoop()) {
return;
}
if (checkWaiters()) {
return;
}
// Stop polling
clearInterval(watcher);
// Synchronously resolve the promise
run$1(null, resolve, value);
}, 10);
});
}
registerAsyncHelper$1('visit', visit);
registerAsyncHelper$1('wait', wait);
registerAsyncHelper$1('andThen', andThen);
registerAsyncHelper$1('pauseTest', pauseTest);
registerHelper$1('currentRouteName', currentRouteName);
registerHelper$1('currentPath', currentPath);
registerHelper$1('currentURL', currentURL);
registerHelper$1('resumeTest', resumeTest);
let name = 'deferReadiness in `testing` mode';
onLoad('Ember.Application', function (ApplicationClass) {
if (!ApplicationClass.initializers[name]) {
ApplicationClass.initializer({
name: name,
initialize(application) {
if (application.testing) {
application.deferReadiness();
}
}
});
}
});
// to setup initializer
const EmberTesting = /*#__PURE__*/Object.defineProperty({
__proto__: null,
Adapter,
QUnitAdapter,
Test,
setupForTesting
}, Symbol.toStringTag, { value: 'Module' });
let registerAsyncHelper;
let registerHelper;
let registerWaiter;
let unregisterHelper;
let unregisterWaiter;
let _impl;
let testingNotAvailableMessage = () => {
throw new Error('Attempted to use test utilities, but `ember-testing` was not included');
};
registerAsyncHelper = testingNotAvailableMessage;
registerHelper = testingNotAvailableMessage;
registerWaiter = testingNotAvailableMessage;
unregisterHelper = testingNotAvailableMessage;
unregisterWaiter = testingNotAvailableMessage;
function registerTestImplementation(impl) {
let {
Test
} = impl;
registerAsyncHelper = Test.registerAsyncHelper;
registerHelper = Test.registerHelper;
registerWaiter = Test.registerWaiter;
unregisterHelper = Test.unregisterHelper;
unregisterWaiter = Test.unregisterWaiter;
_impl = impl;
}
const emberTestIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
get _impl () { return _impl; },
get registerAsyncHelper () { return registerAsyncHelper; },
get registerHelper () { return registerHelper; },
registerTestImplementation,
get registerWaiter () { return registerWaiter; },
get unregisterHelper () { return unregisterHelper; },
get unregisterWaiter () { return unregisterWaiter; }
}, Symbol.toStringTag, { value: 'Module' });
registerTestImplementation(EmberTesting);
const emberTestAdapter = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: Adapter
}, Symbol.toStringTag, { value: 'Module' });
/* This file is generated by build/debug.js */
function opcodeMetadata(op, isMachine) {
return null;
}
function debugSlice(context, start, end) {}
function logOpcode(type, params) {}
function debug(c, op, isMachine) {}
// TODO: How do these map onto constant and machine types?
new Array(Op.Size).fill(null), new Array(Op.Size).fill(null);
const OPERAND_TYPES = ["u32", "i32", "owner", "handle", "str", "option-str", "array", "str-array", "bool", "primitive", "register", "unknown", "symbol-table", "scope"];
function normalize(key, input) {
let name;
if (void 0 === input.format) throw new Error(`Missing format in ${JSON.stringify(input)}`);
name = Array.isArray(input.format) ? input.format[0] : input.format;
let ops = Array.isArray(input.format) ? function (input) {
if (!Array.isArray(input)) throw new Error(`Expected operands array, got ${JSON.stringify(input)}`);
return input.map(op);
}(input.format.slice(1)) : [];
return {
name: name,
mnemonic: key,
before: null,
stackChange: stackChange(input["operand-stack"]),
ops: ops,
operands: ops.length,
check: !0 !== input.skip
};
}
function stackChange(stack) {
if (void 0 === stack) return 0;
let before = stack[0],
after = stack[1];
return hasRest(before) || hasRest(after) ? null : after.length - before.length;
}
function hasRest(input) {
if (!Array.isArray(input)) throw new Error(`Unexpected stack entry: ${JSON.stringify(input)}`);
return input.some(s => "..." === s.slice(-3));
}
function op(input) {
let [name, type] = input.split(":");
if (s = type, -1 !== OPERAND_TYPES.indexOf(s)) return {
name: name,
type: type
};
throw new Error(`Expected operand, found ${JSON.stringify(input)}`);
var s;
}
function normalizeAll(parsed) {
return {
machine: normalizeParsed(parsed.machine),
syscall: normalizeParsed(parsed.syscall)
};
}
function normalizeParsed(parsed) {
let out = Object.create(null);
for (const [key, value] of Object.entries(parsed)) out[key] = normalize(key, value);
return out;
}
function buildEnum(name, parsed, offset, max) {
let last,
e = [`export enum ${name} {`];
Object.values(parsed).forEach((value, i) => {
e.push(` ${value.name} = ${offset + i},`), last = i;
}), e.push(` Size = ${last + offset + 1},`), e.push("}");
let predicate,
enumString = e.join("\n");
return predicate = max ? strip`
export function is${name}(value: number): value is ${name} {
return value >= ${offset} && value <= ${max};
}
` : strip`
export function is${name}(value: number): value is ${name} {
return value >= ${offset};
}
`, {
enumString: enumString,
predicate: predicate
};
}
function strip(strings, ...args) {
let out = "";
for (let i = 0; i < strings.length; i++) out += `${strings[i]}${void 0 !== args[i] ? String(args[i]) : ""}`;
// eslint-disable-next-line regexp/no-super-linear-backtracking
out = /^\s*?\n?([\s\S]*?)\s*$/u.exec(out)[1];
let min = Number.MAX_SAFE_INTEGER;
for (let line of out.split("\n")) {
let leading = /^\s*/u.exec(line)[0].length;
min = Math.min(min, leading);
}
let stripped = "";
for (let line of out.split("\n")) stripped += line.slice(min) + "\n";
return stripped;
}
const META_KIND = ["METADATA", "MACHINE_METADATA"];
function buildSingleMeta(kind, all, key) {
return `${kind}[${"MACHINE_METADATA" === kind ? "MachineOp" : "Op"}.${all[key].name}] = ${stringify(all[key], 0)};`;
}
function stringify(o, pad) {
if ("object" != typeof o || null === o) return "string" == typeof o ? `'${o}'` : JSON.stringify(o);
if (Array.isArray(o)) return `[${o.map(v => stringify(v, pad)).join(", ")}]`;
let out = ["{"];
for (let key of Object.keys(o)) out.push(`${" ".repeat(pad + 2)}${key}: ${stringify(o[key], pad + 2)},`);
return out.push(`${" ".repeat(pad)}}`), out.join("\n");
}
function buildMetas(kind, all) {
let out = [];
for (let key of Object.keys(all)) out.push(buildSingleMeta(kind, all, key));
return out.join("\n\n");
}
class NoopChecker {
validate(value) {
return !0;
}
expected() {
return "<noop>";
}
}
function wrap(checker) {
return new NoopChecker();
}
function CheckInstanceof(Class) {
return new NoopChecker();
}
function CheckOption(checker) {
return new NoopChecker();
}
function CheckMaybe(checker) {
return new NoopChecker();
}
function CheckInterface(obj) {
return new NoopChecker();
}
function CheckArray(obj) {
return new NoopChecker();
}
function CheckDict(obj) {
return new NoopChecker();
}
function defaultMessage(value, expected) {
return `Got ${value}, expected:\n${expected}`;
}
function check(value, checker, message = defaultMessage) {
return value;
}
function recordStackSize(sp) {}
const CheckPrimitive = new NoopChecker(),
CheckFunction = new NoopChecker(),
CheckNumber = new NoopChecker(),
CheckBoolean = new NoopChecker(),
CheckHandle = new NoopChecker(),
CheckString = new NoopChecker(),
CheckUndefined = new NoopChecker(),
CheckUnknown = new NoopChecker(),
CheckSafeString = new NoopChecker(),
CheckObject = new NoopChecker();
function CheckOr(left, right) {
return new NoopChecker();
}
const CheckBlockSymbolTable = new NoopChecker(),
CheckProgramSymbolTable = new NoopChecker(),
CheckElement = new NoopChecker(),
CheckDocumentFragment = new NoopChecker(),
CheckNode = new NoopChecker();
const glimmerDebug = /*#__PURE__*/Object.defineProperty({
__proto__: null,
CheckArray,
CheckBlockSymbolTable,
CheckBoolean,
CheckDict,
CheckDocumentFragment,
CheckElement,
CheckFunction,
CheckHandle,
CheckInstanceof,
CheckInterface,
CheckMaybe,
CheckNode,
CheckNumber,
CheckObject,
CheckOption,
CheckOr,
CheckPrimitive,
CheckProgramSymbolTable,
CheckSafeString,
CheckString,
CheckUndefined,
CheckUnknown,
META_KIND,
OPERAND_TYPES,
buildEnum,
buildMetas,
buildSingleMeta,
check,
debug,
debugSlice,
logOpcode,
normalize,
normalizeAll,
normalizeParsed,
opcodeMetadata,
recordStackSize,
strip,
wrap
}, Symbol.toStringTag, { value: 'Module' });
const DEBUG = false;
const CI = false;
const glimmerEnv = /*#__PURE__*/Object.defineProperty({
__proto__: null,
CI,
DEBUG
}, Symbol.toStringTag, { value: 'Module' });
/**
In order to tell Ember a value might change, we need to mark it as trackable.
Trackable values are values that:
- Can change over their component’s lifetime and
- Should cause Ember to rerender if and when they change
We can do this by marking the field with the `@tracked` decorator.
@module @glimmer/tracking
@public
*/
/**
Marks a property as tracked. By default, values that are rendered in Ember app
templates are _static_, meaning that updates to them won't cause the
application to rerender. Marking a property as tracked means that when that
property changes, any templates that used that property, directly or
indirectly, will rerender. For instance, consider this component:
```handlebars
<div>Count: {{this.count}}</div>
<div>Times Ten: {{this.timesTen}}</div>
<div>
<button {{on "click" this.plusOne}}>
Plus One
</button>
</div>
```
```javascript
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
export default class CounterComponent extends Component {
@tracked count = 0;
get timesTen() {
return this.count * 10;
}
@action
plusOne() {
this.count += 1;
}
}
```
Both the `{{this.count}}` and the `{{this.timesTen}}` properties in the
template will update whenever the button is clicked. Any tracked properties
that are used in any way to calculate a value that is used in the template
will cause a rerender when updated - this includes through method calls and
other means:
```javascript
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
class Entry {
@tracked name;
@tracked phoneNumber;
constructor(name, phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
}
export default class PhoneBookComponent extends Component {
entries = [
new Entry('Pizza Palace', 5551234),
new Entry('1st Street Cleaners', 5554321),
new Entry('Plants R Us', 5552468),
];
// Any usage of this property will update whenever any of the names in the
// entries arrays are updated
get names() {
return this.entries.map(e => e.name);
}
// Any usage of this property will update whenever any of the numbers in the
// entries arrays are updated
get numbers() {
return this.getFormattedNumbers();
}
getFormattedNumbers() {
return this.entries
.map(e => e.phoneNumber)
.map(number => {
let numberString = '' + number;
return numberString.slice(0, 3) + '-' + numberString.slice(3);
});
}
}
```
It's important to note that setting tracked properties will always trigger an
update, even if the property is set to the same value as it was before.
```js
let entry = new Entry('Pizza Palace', 5551234);
// if entry was used when rendering, this would cause a rerender, even though
// the name is being set to the same value as it was before
entry.name = entry.name;
```
`tracked` can also be used with the classic Ember object model in a similar
manner to classic computed properties:
```javascript
import EmberObject from '@ember/object';
import { tracked } from '@glimmer/tracking';
const Entry = EmberObject.extend({
name: tracked(),
phoneNumber: tracked()
});
```
Often this is unnecessary, but to ensure robust auto-tracking behavior it is
advisable to mark tracked state appropriately wherever possible.
This form of `tracked` also accepts an optional configuration object
containing either an initial `value` or an `initializer` function (but not
both).
```javascript
import EmberObject from '@ember/object';
import { tracked } from '@glimmer/tracking';
const Entry = EmberObject.extend({
name: tracked({ value: 'Zoey' }),
favoriteSongs: tracked({
initializer: () => ['Raspberry Beret', 'Time After Time']
})
});
```
@method tracked
@static
@for @glimmer/tracking
@public
*/
/**
The `@cached` decorator can be used on getters in order to cache the return
value of the getter. This is useful when a getter is expensive and used very
often. For instance, in this guest list class, we have the `sortedGuests`
getter that sorts the guests alphabetically:
```js
import { tracked } from '@glimmer/tracking';
class GuestList {
@tracked guests = ['Zoey', 'Tomster'];
get sortedGuests() {
return this.guests.slice().sort()
}
}
```
Every time `sortedGuests` is accessed, a new array will be created and sorted,
because JavaScript getters do not cache by default. When the guest list is
small, like the one in the example, this is not a problem. However, if the guest
list were to grow very large, it would mean that we would be doing a large
amount of work each time we accessed `sortedGetters`. With `@cached`, we can
cache the value instead:
```js
import { tracked, cached } from '@glimmer/tracking';
class GuestList {
@tracked guests = ['Zoey', 'Tomster'];
@cached
get sortedGuests() {
return this.guests.slice().sort()
}
}
```
Now the `sortedGuests` getter will be cached based on _autotracking_. It will
only rerun and create a new sorted array when the `guests` tracked property is
updated.
In general, you should avoid using `@cached` unless you have confirmed that the
getter you are decorating is computationally expensive. `@cached` adds a small
amount of overhead to the getter, making it more expensive. While this overhead
is small, if `@cached` is overused it can add up to a large impact overall in
your app. Many getters and tracked properties are only accessed once, rendered,
and then never rerendered, so adding `@cached` when it is unnecessary can
negatively impact performance.
@method cached
@static
@for @glimmer/tracking
@public
*/
const glimmerTrackingIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
cached,
tracked
}, Symbol.toStringTag, { value: 'Module' });
const glimmerTrackingPrimitivesCache = /*#__PURE__*/Object.defineProperty({
__proto__: null,
createCache,
getValue,
isConst
}, Symbol.toStringTag, { value: 'Module' });
/**
@module ember
*/
// eslint-disable-next-line @typescript-eslint/no-namespace
let Ember;
(function (_Ember) {
_Ember.isNamespace = true;
function toString() {
return 'Ember';
}
_Ember.toString = toString;
_Ember.Container = Container;
_Ember.Registry = Registry;
// ****@ember/-internals/glimmer****
// Partially re-exported from @glimmer/manager
_Ember._setComponentManager = setComponentManager;
_Ember._componentManagerCapabilities = componentCapabilities;
_Ember._modifierManagerCapabilities = modifierCapabilities;
_Ember.meta = meta;
_Ember._createCache = createCache;
_Ember._cacheGetValue = getValue;
_Ember._cacheIsConst = isConst;
_Ember._descriptor = nativeDescDecorator;
_Ember._getPath = _getPath;
_Ember._setClassicDecorator = setClassicDecorator;
_Ember._tracked = tracked;
_Ember.beginPropertyChanges = beginPropertyChanges;
_Ember.changeProperties = changeProperties;
_Ember.endPropertyChanges = endPropertyChanges;
_Ember.hasListeners = hasListeners;
_Ember.libraries = LIBRARIES;
_Ember._ContainerProxyMixin = ContainerProxyMixin;
_Ember._ProxyMixin = ProxyMixin;
_Ember._RegistryProxyMixin = RegistryProxyMixin;
_Ember.ActionHandler = ActionHandler;
_Ember.Comparable = Comparable;
// ****@ember/-internals/view****
_Ember.ComponentLookup = ComponentLookup;
_Ember.EventDispatcher = EventDispatcher;
_Ember._Cache = Cache;
_Ember.GUID_KEY = GUID_KEY;
_Ember.canInvoke = canInvoke;
_Ember.generateGuid = generateGuid;
_Ember.guidFor = guidFor;
_Ember.uuid = uuid$1;
_Ember.wrap = wrap$1;
_Ember.getOwner = getOwner;
_Ember.onLoad = onLoad;
_Ember.runLoadHooks = runLoadHooks;
_Ember.setOwner = setOwner;
_Ember.Application = Application;
// ****@ember/application/instance****
_Ember.ApplicationInstance = ApplicationInstance;
// // ****@ember/application/namespace****
_Ember.Namespace = Namespace;
// ****@ember/array****
_Ember.A = A;
_Ember.Array = EmberArray;
_Ember.NativeArray = NativeArray;
_Ember.isArray = isArray$2;
_Ember.makeArray = makeArray;
_Ember.MutableArray = MutableArray;
// ****@ember/array/proxy****
_Ember.ArrayProxy = ArrayProxy;
// ****@ember/canary-features****
_Ember.FEATURES = {
isEnabled,
...FEATURES
};
_Ember._Input = Input;
_Ember.Component = Component;
// // ****@ember/component/helper****
_Ember.Helper = Helper;
// ****@ember/controller****
_Ember.Controller = Controller;
_Ember.ControllerMixin = ControllerMixin;
// ****@ember/debug****
_Ember._captureRenderTree = captureRenderTree;
_Ember.assert = assert$1;
_Ember.warn = warn;
_Ember.debug = debug$2;
_Ember.deprecate = deprecate$1;
_Ember.deprecateFunc = deprecateFunc;
_Ember.runInDebug = runInDebug;
_Ember.inspect = inspect;
_Ember.Debug = {
registerDeprecationHandler: registerHandler$1,
registerWarnHandler: registerHandler,
// ****@ember/-internals/metal****
isComputed: isComputed
};
_Ember.ContainerDebugAdapter = ContainerDebugAdapter;
// ****@ember/debug/data-adapter****
_Ember.DataAdapter = DataAdapter;
// ****@ember/destroyable****
_Ember._assertDestroyablesDestroyed = assertDestroyablesDestroyed;
_Ember._associateDestroyableChild = associateDestroyableChild;
_Ember._enableDestroyableTracking = enableDestroyableTracking;
_Ember._isDestroying = isDestroying;
_Ember._isDestroyed = isDestroyed;
_Ember._registerDestructor = registerDestructor;
_Ember._unregisterDestructor = unregisterDestructor;
_Ember.destroy = destroy;
_Ember.Engine = Engine;
// ****@ember/engine/instance****
_Ember.EngineInstance = EngineInstance;
// ****@ember/enumerable****
_Ember.Enumerable = Enumerable;
// ****@ember/enumerable/mutable****
_Ember.MutableEnumerable = MutableEnumerable;
// ****@ember/instrumentation****
/** @private */
_Ember.instrument = instrument;
_Ember.subscribe = subscribe;
_Ember.Instrumentation = {
instrument: instrument,
subscribe: subscribe,
unsubscribe: unsubscribe,
reset: reset
};
_Ember.Object = EmberObject;
_Ember._action = action$1;
_Ember.computed = computed;
_Ember.defineProperty = defineProperty;
_Ember.get = get$2;
_Ember.getProperties = getProperties;
_Ember.notifyPropertyChange = notifyPropertyChange;
_Ember.observer = observer;
_Ember.set = set;
_Ember.trySet = trySet;
_Ember.setProperties = setProperties;
_Ember.cacheFor = getCachedValueFor;
_Ember._dependentKeyCompat = dependentKeyCompat;
_Ember.ComputedProperty = ComputedProperty;
_Ember.expandProperties = expandProperties;
_Ember.CoreObject = CoreObject;
// ****@ember/object/evented****
_Ember.Evented = Evented;
_Ember.on = on$3;
_Ember.addListener = addListener;
_Ember.removeListener = removeListener;
_Ember.sendEvent = sendEvent;
_Ember.Mixin = Mixin;
_Ember.mixin = mixin;
_Ember.Observable = Observable;
// ****@ember/object/observers****
_Ember.addObserver = addObserver;
_Ember.removeObserver = removeObserver;
_Ember.PromiseProxyMixin = PromiseProxyMixin;
// ****@ember/object/proxy****
_Ember.ObjectProxy = ObjectProxy;
// ****@ember/routing/-internals****
_Ember.RouterDSL = DSLImpl;
_Ember.controllerFor = controllerFor;
_Ember.generateController = generateController;
_Ember.generateControllerFactory = generateControllerFactory;
_Ember.HashLocation = HashLocation;
// ****@ember/routing/history-location****
_Ember.HistoryLocation = HistoryLocation;
// ****@ember/routing/none-location****
_Ember.NoneLocation = NoneLocation;
// ****@ember/routing/route****
_Ember.Route = Route;
// ****@ember/routing/router****
_Ember.Router = EmberRouter;
// // ****@ember/runloop****
_Ember.run = run$1;
_Ember.Service = Service;
// ****@ember/utils****
_Ember.compare = compare;
_Ember.isBlank = isBlank;
_Ember.isEmpty = isEmpty;
_Ember.isEqual = isEqual;
_Ember.isNone = isNone;
_Ember.isPresent = isPresent;
_Ember.typeOf = typeOf;
_Ember.VERSION = Version;
_Ember.ViewUtils = {
// ****@ember/-internals/views****
getChildViews: getChildViews,
getElementView: getElementView,
getRootViews: getRootViews,
getViewBounds: getViewBounds,
getViewBoundingClientRect: getViewBoundingClientRect,
getViewClientRects: getViewClientRects,
getViewElement: getViewElement,
isSimpleClick: isSimpleClick,
// ****@ember/-internals/glimmer****
isSerializationFirstNode
};
_Ember._getComponentTemplate = getComponentTemplate;
_Ember._helperManagerCapabilities = helperCapabilities;
_Ember._setComponentTemplate = setComponentTemplate;
_Ember._setHelperManager = setHelperManager$1;
_Ember._setModifierManager = setModifierManager$1;
_Ember._templateOnlyComponent = templateOnlyComponent;
_Ember._invokeHelper = invokeHelper$1;
_Ember._hash = hash$1;
_Ember._array = array$1;
_Ember._concat = concat$1;
_Ember._get = get$1;
_Ember._on = on$1;
_Ember._fn = fn$1;
_Ember._Backburner = Backburner;
// // ****@ember/controller, @ember/service****
/**
Namespace for injection helper methods.
@class inject
@namespace Ember
@static
@public
*/
function inject$1() {
}
_Ember.inject = inject$1;
// ****@ember/controller****
inject$1.controller = inject;
// ****@ember/service****
inject$1.service = service;
_Ember.__loader = {
get require() {
return globalThis.require;
},
get define() {
return globalThis.define;
},
get registry() {
let g = globalThis;
return g.requirejs?.entries ?? g.require.entries;
}
};
// ------------------------------------------------------------------------ //
// These properties are assigned to the namespace with getters (and, in some
// cases setters) with `Object.defineProperty` below.
// ------------------------------------------------------------------------ //
// ****@ember/-internals/environment****
/**
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 {Error} error the error object
@public
*/
// ****@ember/-internals/error-handling****
/**
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
*/
/**
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
*/
})(Ember || (Ember = {})); // This syntax is not reliably implemented by TypeScript transpilers, but
// we need to re-export the`RSVP` *namespace* for type compatibility.
// To achieve this, we use a type-only `declare namespace` block to get the
// types to behave correctly, and separately set the `RSVP` property on the
// `Ember` object dynamically. (The types behave correctly because of
// namespace merging semantics.)
// eslint-disable-next-line @typescript-eslint/no-namespace
Reflect.set(Ember, 'RSVP', rsvp);
Object.defineProperty(Ember, 'ENV', {
get: getENV,
enumerable: false
});
Object.defineProperty(Ember, 'lookup', {
get: getLookup,
set: setLookup,
enumerable: false
});
Object.defineProperty(Ember, 'onerror', {
get: getOnerror,
set: setOnerror,
enumerable: false
});
Object.defineProperty(Ember, 'testing', {
get: isTesting,
set: setTesting,
enumerable: false
});
Object.defineProperty(Ember, 'BOOTED', {
configurable: false,
enumerable: false,
get: isSearchDisabled,
set: setSearchDisabled
});
Object.defineProperty(Ember, 'TEMPLATES', {
get: getTemplates,
set: setTemplates,
configurable: false,
enumerable: false
});
Object.defineProperty(Ember, 'TEMPLATES', {
get: getTemplates,
set: setTemplates,
configurable: false,
enumerable: false
});
// ****@ember/debug****
Object.defineProperty(Ember, 'testing', {
get: isTesting,
set: setTesting,
enumerable: false
});
runLoadHooks('Ember.Application', Application);
let EmberHandlebars = {
template: templateFactory,
Utils: {
escapeExpression
}
};
let EmberHTMLBars = {
template: templateFactory
};
function defineEmberTemplateCompilerLazyLoad(key) {
Object.defineProperty(Ember, key, {
configurable: true,
enumerable: true,
get() {
if (__emberTemplateCompiler) {
EmberHTMLBars.precompile = EmberHandlebars.precompile = __emberTemplateCompiler.precompile;
EmberHTMLBars.compile = EmberHandlebars.compile = compileTemplate;
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 (_impl) {
let {
Test,
Adapter,
QUnitAdapter,
setupForTesting
} = _impl;
// @ts-expect-error We should not do this
Test.Adapter = Adapter;
// @ts-expect-error We should not do this
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');
// @ts-expect-error Per types, runLoadHooks requires a second parameter. Should we loosen types?
runLoadHooks('Ember');
const doNotUseThis = Ember;
const index = new Proxy(doNotUseThis, {
get(target, key, receiver) {
// We don't have symbol exports, so this is probably fine.
if (typeof key === 'string') {
deprecateUntil(`importing ${key} from the 'ember' barrel file is deprecated.`, DEPRECATIONS.DEPRECATE_IMPORT_EMBER(key));
}
return Reflect.get(target, key, receiver);
},
getOwnPropertyDescriptor(target, key) {
if (typeof key === 'string') {
deprecateUntil(`importing ${key} from the 'ember' barrel file is deprecated.`, DEPRECATIONS.DEPRECATE_IMPORT_EMBER(key));
}
return Object.getOwnPropertyDescriptor(target, key);
}
});
const emberIndex = /*#__PURE__*/Object.defineProperty({
__proto__: null,
default: index
}, Symbol.toStringTag, { value: 'Module' });
/* eslint-disable */
d('@ember/-internals/browser-environment/index', emberinternalsBrowserEnvironmentIndex);
d('@ember/-internals/container/index', emberinternalsContainerIndex);
d('@ember/-internals/deprecations/index', emberinternalsDeprecationsIndex);
d('@ember/-internals/environment/index', emberinternalsEnvironmentIndex);
d('@ember/-internals/error-handling/index', emberinternalsErrorHandlingIndex);
d('@ember/-internals/glimmer/index', emberinternalsGlimmerIndex);
d('@ember/-internals/meta/index', emberinternalsMetaIndex);
d('@ember/-internals/meta/lib/meta', emberinternalsMetaLibMeta);
d('@ember/-internals/metal/index', emberinternalsMetalIndex);
d('@ember/-internals/owner/index', emberinternalsOwnerIndex);
d('@ember/-internals/routing/index', emberinternalsRoutingIndex);
d('@ember/-internals/runtime/index', emberinternalsRuntimeIndex);
d('@ember/-internals/runtime/lib/ext/rsvp', emberinternalsRuntimeLibExtRsvp);
d('@ember/-internals/runtime/lib/mixins/-proxy', emberinternalsRuntimeLibMixinsproxy);
d('@ember/-internals/runtime/lib/mixins/action_handler', emberinternalsRuntimeLibMixinsActionHandler);
d('@ember/-internals/runtime/lib/mixins/comparable', emberinternalsRuntimeLibMixinsComparable);
d('@ember/-internals/runtime/lib/mixins/container_proxy', emberinternalsRuntimeLibMixinsContainerProxy);
d('@ember/-internals/runtime/lib/mixins/registry_proxy', emberinternalsRuntimeLibMixinsRegistryProxy);
d('@ember/-internals/runtime/lib/mixins/target_action_support', emberinternalsRuntimeLibMixinsTargetActionSupport);
d('@ember/-internals/string/index', emberinternalsStringIndex);
d('@ember/-internals/utility-types/index', emberinternalsUtilityTypesIndex);
d('@ember/-internals/utils/index', emberinternalsUtilsIndex);
d('@ember/-internals/views/index', emberinternalsViewsIndex);
d('@ember/-internals/views/lib/compat/attrs', emberinternalsViewsLibCompatAttrs);
d('@ember/-internals/views/lib/compat/fallback-view-registry', emberinternalsViewsLibCompatFallbackViewRegistry);
d('@ember/-internals/views/lib/component_lookup', emberinternalsViewsLibComponentLookup);
d('@ember/-internals/views/lib/mixins/action_support', emberinternalsViewsLibMixinsActionSupport);
d('@ember/-internals/views/lib/mixins/child_views_support', emberinternalsViewsLibMixinsChildViewsSupport);
d('@ember/-internals/views/lib/mixins/class_names_support', emberinternalsViewsLibMixinsClassNamesSupport);
d('@ember/-internals/views/lib/mixins/view_state_support', emberinternalsViewsLibMixinsViewStateSupport);
d('@ember/-internals/views/lib/mixins/view_support', emberinternalsViewsLibMixinsViewSupport);
d('@ember/-internals/views/lib/system/action_manager', emberinternalsViewsLibSystemActionManager);
d('@ember/-internals/views/lib/system/event_dispatcher', emberinternalsViewsLibSystemEventDispatcher);
d('@ember/-internals/views/lib/system/utils', emberinternalsViewsLibSystemUtils);
d('@ember/-internals/views/lib/views/core_view', emberinternalsViewsLibViewsCoreView);
d('@ember/-internals/views/lib/views/states', emberinternalsViewsLibViewsStates);
d('@ember/application/index', emberApplicationIndex);
d('@ember/application/instance', emberApplicationInstance);
d('@ember/application/lib/lazy_load', emberApplicationLibLazyLoad);
d('@ember/application/namespace', emberApplicationNamespace);
d('@ember/array/-internals', emberArrayinternals);
d('@ember/array/index', emberArrayIndex);
d('@ember/array/lib/make-array', emberArrayLibMakeArray);
d('@ember/array/mutable', emberArrayMutable);
d('@ember/array/proxy', emberArrayProxy);
d('@ember/canary-features/index', emberCanaryFeaturesIndex);
d('@ember/component/helper', emberComponentHelper);
d('@ember/component/index', emberComponentIndex);
d('@ember/component/template-only', emberComponentTemplateOnly);
d('@ember/controller/index', emberControllerIndex);
d('@ember/debug/index', emberDebugIndex);
d('@ember/debug/lib/capture-render-tree', emberDebugLibCaptureRenderTree);
d('@ember/debug/lib/deprecate', emberDebugLibDeprecate);
d('@ember/debug/lib/handlers', emberDebugLibHandlers);
d('@ember/debug/lib/inspect', emberDebugLibInspect);
d('@ember/debug/lib/testing', emberDebugLibTesting);
d('@ember/debug/lib/warn', emberDebugLibWarn);
d('@ember/debug/container-debug-adapter', emberDebugContainerDebugAdapter);
d('@ember/debug/data-adapter', emberDebugDataAdapter);
d('@ember/deprecated-features/index', emberDeprecatedFeaturesIndex);
d('@ember/destroyable/index', emberDestroyableIndex);
d('@ember/engine/index', emberEngineIndex);
d('@ember/engine/instance', emberEngineInstance);
d('@ember/engine/lib/engine-parent', emberEngineLibEngineParent);
d('@ember/enumerable/index', emberEnumerableIndex);
d('@ember/enumerable/mutable', emberEnumerableMutable);
d('@ember/helper/index', emberHelperIndex);
d('@ember/instrumentation/index', emberInstrumentationIndex);
d('@ember/modifier/index', emberModifierIndex);
d('@ember/object/-internals', emberObjectinternals);
d('@ember/object/compat', emberObjectCompat);
d('@ember/object/computed', emberObjectComputed);
d('@ember/object/core', emberObjectCore);
d('@ember/object/evented', emberObjectEvented);
d('@ember/object/events', emberObjectEvents);
d('@ember/object/index', emberObjectIndex);
d('@ember/object/internals', emberObjectInternals);
d('@ember/object/lib/computed/computed_macros', emberObjectLibComputedComputedMacros);
d('@ember/object/lib/computed/reduce_computed_macros', emberObjectLibComputedReduceComputedMacros);
d('@ember/object/mixin', emberObjectMixin);
d('@ember/object/observable', emberObjectObservable);
d('@ember/object/observers', emberObjectObservers);
d('@ember/object/promise-proxy-mixin', emberObjectPromiseProxyMixin);
d('@ember/object/proxy', emberObjectProxy);
d('@ember/owner/index', emberOwnerIndex);
d('@ember/renderer/index', emberRendererIndex);
d('@ember/routing/-internals', emberRoutinginternals);
d('@ember/routing/hash-location', emberRoutingHashLocation);
d('@ember/routing/history-location', emberRoutingHistoryLocation);
d('@ember/routing/index', emberRoutingIndex);
d('@ember/routing/lib/cache', emberRoutingLibCache);
d('@ember/routing/lib/controller_for', emberRoutingLibControllerFor);
d('@ember/routing/lib/dsl', emberRoutingLibDsl);
d('@ember/routing/lib/engines', emberRoutingLibEngines);
d('@ember/routing/lib/generate_controller', emberRoutingLibGenerateController);
d('@ember/routing/lib/location-utils', emberRoutingLibLocationUtils);
d('@ember/routing/lib/query_params', emberRoutingLibQueryParams);
d('@ember/routing/lib/route-info', emberRoutingLibRouteInfo);
d('@ember/routing/lib/router_state', emberRoutingLibRouterState);
d('@ember/routing/lib/routing-service', emberRoutingLibRoutingService);
d('@ember/routing/lib/utils', emberRoutingLibUtils);
d('@ember/routing/location', emberRoutingLocation);
d('@ember/routing/none-location', emberRoutingNoneLocation);
d('@ember/routing/route-info', emberRoutingRouteInfo);
d('@ember/routing/route', emberRoutingRoute);
d('@ember/routing/router-service', emberRoutingRouterService);
d('@ember/routing/router', emberRoutingRouter);
d('@ember/routing/transition', emberRoutingTransition);
d('@ember/runloop/-private/backburner', emberRunloopprivateBackburner);
d('@ember/runloop/index', emberRunloopIndex);
d('@ember/service/index', emberServiceIndex);
d('@ember/template-compilation/index', emberTemplateCompilationIndex);
d('@ember/template-factory/index', emberTemplateFactoryIndex);
d('@ember/template/index', emberTemplateIndex);
d('@ember/test/adapter', emberTestAdapter);
d('@ember/test/index', emberTestIndex);
d('@ember/utils/index', emberUtilsIndex);
d('@ember/utils/lib/compare', emberUtilsLibCompare);
d('@ember/utils/lib/is-equal', emberUtilsLibIsEqual);
d('@ember/utils/lib/is_blank', emberUtilsLibIsBlank);
d('@ember/utils/lib/is_empty', emberUtilsLibIsEmpty);
d('@ember/utils/lib/is_none', emberUtilsLibIsNone);
d('@ember/utils/lib/is_present', emberUtilsLibIsPresent);
d('@ember/utils/lib/type-of', emberUtilsLibTypeOf);
d('@ember/version/index', emberVersionIndex);
d('@glimmer/debug', glimmerDebug);
d('@glimmer/destroyable', glimmerDestroyable);
d('@glimmer/encoder', glimmerEncoder);
d('@glimmer/env', glimmerEnv);
d('@glimmer/global-context', glimmerGlobalContext);
d('@glimmer/manager', glimmerManager);
d('@glimmer/node', glimmerNode);
d('@glimmer/opcode-compiler', glimmerOpcodeCompiler);
d('@glimmer/owner', glimmerOwner);
d('@glimmer/program', glimmerProgram);
d('@glimmer/reference', glimmerReference);
d('@glimmer/runtime', glimmerRuntime);
d('@glimmer/tracking/index', glimmerTrackingIndex);
d('@glimmer/tracking/primitives/cache', glimmerTrackingPrimitivesCache);
d('@glimmer/util', glimmerUtil);
d('@glimmer/validator', glimmerValidator);
d('@glimmer/vm', glimmerVm);
d('@glimmer/wire-format', glimmerWireFormat);
d('@simple-dom/document', simpleDomDocument);
d('backburner.js', backburnerjs);
d('dag-map', dagMap);
d('ember/index', emberIndex);
d('ember/version', emberVersion);
d('route-recognizer', routeRecognizer);
d('router_js', routerJs);
d('rsvp', rsvp);
if (typeof module === 'object' && typeof module.require === 'function') {
module.exports = index;
}
})();
//# sourceMappingURL=ember.prod.js.map