(function() {
/*!
* @overview Ember - JavaScript Application Framework
* @copyright Copyright 2011-2017 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 2.14.0-beta.3
*/
var enifed, requireModule, Ember;
var mainContext = this; // Used in ember-environment/lib/global.js
(function() {
var isNode = typeof window === 'undefined' &&
typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
if (!isNode) {
Ember = this.Ember = this.Ember || {};
}
if (typeof Ember === 'undefined') { Ember = {}; }
if (typeof Ember.__loader === 'undefined') {
var registry = {};
var seen = {};
enifed = function(name, deps, callback) {
var value = { };
if (!callback) {
value.deps = [];
value.callback = deps;
} else {
value.deps = deps;
value.callback = callback;
}
registry[name] = value;
};
requireModule = function(name) {
return internalRequire(name, null);
};
// setup `require` module
requireModule['default'] = requireModule;
requireModule.has = function registryHas(moduleName) {
return !!registry[moduleName] || !!registry[moduleName + '/index'];
};
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] = requireModule;
} else {
reified[i] = internalRequire(deps[i], name);
}
}
callback.apply(this, reified);
return exports;
}
requireModule._eak_seen = registry;
Ember.__loader = {
define: enifed,
require: requireModule,
registry: registry
};
} else {
enifed = Ember.__loader.define;
requireModule = Ember.__loader.require;
}
})();
enifed('@glimmer/compiler', ['exports', 'ember-babel', 'node-module', '@glimmer/syntax', '@glimmer/util', '@glimmer/wire-format'], function (exports, _emberBabel, _nodeModule, _syntax, _util, _wireFormat) {
'use strict';
exports.TemplateVisitor = exports.precompile = undefined;
var push = Array.prototype.push;
var Frame = function () {
this.parentNode = null;
this.children = null;
this.childIndex = null;
this.childCount = null;
this.childTemplateCount = 0;
this.mustacheCount = 0;
this.actions = [];
this.blankChildTextNodes = null;
this.symbols = null;
};
var SymbolTable = function () {
function SymbolTable(symbols) {
var parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
this.symbols = symbols;
this.parent = parent;
}
SymbolTable.prototype.hasLocalVariable = function (name) {
var symbols = this.symbols,
parent = this.parent;
return symbols.indexOf(name) >= 0 || parent && parent.hasLocalVariable(name);
};
return SymbolTable;
}();
/**
* Takes in an AST and outputs a list of actions to be consumed
* by a compiler. For example, the template
*
* foo{{bar}}
baz
*
* produces the actions
*
* [['startProgram', [programNode, 0]],
* ['text', [textNode, 0, 3]],
* ['mustache', [mustacheNode, 1, 3]],
* ['openElement', [elementNode, 2, 3, 0]],
* ['text', [textNode, 0, 1]],
* ['closeElement', [elementNode, 2, 3],
* ['endProgram', [programNode]]]
*
* This visitor walks the AST depth first and backwards. As
* a result the bottom-most child template will appear at the
* top of the actions list whereas the root template will appear
* at the bottom of the list. For example,
*
*
{{#if}}foo{{else}}bar{{/if}}
*
* produces the actions
*
* [['startProgram', [programNode, 0]],
* ['text', [textNode, 0, 2, 0]],
* ['openElement', [elementNode, 1, 2, 0]],
* ['closeElement', [elementNode, 1, 2]],
* ['endProgram', [programNode]],
* ['startProgram', [programNode, 0]],
* ['text', [textNode, 0, 1]],
* ['endProgram', [programNode]],
* ['startProgram', [programNode, 2]],
* ['openElement', [elementNode, 0, 1, 1]],
* ['block', [blockNode, 0, 1]],
* ['closeElement', [elementNode, 0, 1]],
* ['endProgram', [programNode]]]
*
* The state of the traversal is maintained by a stack of frames.
* Whenever a node with children is entered (either a ProgramNode
* or an ElementNode) a frame is pushed onto the stack. The frame
* contains information about the state of the traversal of that
* node. For example,
*
* - index of the current child node being visited
* - the number of mustaches contained within its child nodes
* - the list of actions generated by its child nodes
*/
function TemplateVisitor() {
this.frameStack = [];
this.actions = [];
this.programDepth = -1;
}
// Traversal methods
TemplateVisitor.prototype.visit = function (node) {
this[node.type](node);
};
TemplateVisitor.prototype.Program = function (program) {
this.programDepth++;
var parentFrame = this.getCurrentFrame(),
i;
var programFrame = this.pushFrame();
if (parentFrame) {
program.symbols = new SymbolTable(program.blockParams, parentFrame.symbols);
} else {
program.symbols = new SymbolTable(program.blockParams);
}
var startType = void 0,
endType = void 0;
if (this.programDepth === 0) {
startType = 'startProgram';
endType = 'endProgram';
} else {
startType = 'startBlock';
endType = 'endBlock';
}
programFrame.parentNode = program;
programFrame.children = program.body;
programFrame.childCount = program.body.length;
programFrame.blankChildTextNodes = [];
programFrame.actions.push([endType, [program, this.programDepth]]);
programFrame.symbols = program.symbols;
for (i = program.body.length - 1; i >= 0; i--) {
programFrame.childIndex = i;
this.visit(program.body[i]);
}
programFrame.actions.push([startType, [program, programFrame.childTemplateCount, programFrame.blankChildTextNodes.reverse()]]);
this.popFrame();
this.programDepth--;
// Push the completed template into the global actions list
if (parentFrame) {
parentFrame.childTemplateCount++;
}
push.apply(this.actions, programFrame.actions.reverse());
};
TemplateVisitor.prototype.ElementNode = function (element) {
var parentFrame = this.getCurrentFrame(),
i,
_i;
var elementFrame = this.pushFrame();
elementFrame.parentNode = element;
elementFrame.children = element.children;
elementFrame.childCount = element.children.length;
elementFrame.mustacheCount += element.modifiers.length;
elementFrame.blankChildTextNodes = [];
elementFrame.symbols = parentFrame.symbols;
var actionArgs = [element, parentFrame.childIndex, parentFrame.childCount];
elementFrame.actions.push(['closeElement', actionArgs]);
for (i = element.attributes.length - 1; i >= 0; i--) {
this.visit(element.attributes[i]);
}
for (_i = element.children.length - 1; _i >= 0; _i--) {
elementFrame.childIndex = _i;
this.visit(element.children[_i]);
}
elementFrame.actions.push(['openElement', actionArgs.concat([elementFrame.mustacheCount, elementFrame.blankChildTextNodes.reverse()])]);
this.popFrame();
// Propagate the element's frame state to the parent frame
if (elementFrame.mustacheCount > 0) {
parentFrame.mustacheCount++;
}
parentFrame.childTemplateCount += elementFrame.childTemplateCount;
push.apply(parentFrame.actions, elementFrame.actions);
};
TemplateVisitor.prototype.AttrNode = function (attr) {
if (attr.value.type !== 'TextNode') {
this.getCurrentFrame().mustacheCount++;
}
};
TemplateVisitor.prototype.TextNode = function (text) {
var frame = this.getCurrentFrame();
if (text.chars === '') {
frame.blankChildTextNodes.push(domIndexOf(frame.children, text));
}
frame.actions.push(['text', [text, frame.childIndex, frame.childCount]]);
};
TemplateVisitor.prototype.BlockStatement = function (node) {
var frame = this.getCurrentFrame();
frame.mustacheCount++;
frame.actions.push(['block', [node, frame.childIndex, frame.childCount]]);
if (node.inverse) {
this.visit(node.inverse);
}
if (node.program) {
this.visit(node.program);
}
};
TemplateVisitor.prototype.PartialStatement = function (node) {
var frame = this.getCurrentFrame();
frame.mustacheCount++;
frame.actions.push(['mustache', [node, frame.childIndex, frame.childCount]]);
};
TemplateVisitor.prototype.CommentStatement = function (text) {
var frame = this.getCurrentFrame();
frame.actions.push(['comment', [text, frame.childIndex, frame.childCount]]);
};
TemplateVisitor.prototype.MustacheCommentStatement = function () {
// Intentional empty: Handlebars comments should not affect output.
};
TemplateVisitor.prototype.MustacheStatement = function (mustache) {
var frame = this.getCurrentFrame();
frame.mustacheCount++;
frame.actions.push(['mustache', [mustache, frame.childIndex, frame.childCount]]);
};
// Frame helpers
TemplateVisitor.prototype.getCurrentFrame = function () {
return this.frameStack[this.frameStack.length - 1];
};
TemplateVisitor.prototype.pushFrame = function () {
var frame = new Frame();
this.frameStack.push(frame);
return frame;
};
TemplateVisitor.prototype.popFrame = function () {
return this.frameStack.pop();
};
// Returns the index of `domNode` in the `nodes` array, skipping
// over any nodes which do not represent DOM nodes.
function domIndexOf(nodes, domNode) {
var index = -1,
i,
node;
for (i = 0; i < nodes.length; i++) {
node = nodes[i];
if (node.type !== 'TextNode' && node.type !== 'ElementNode') {
continue;
} else {
index++;
}
if (node === domNode) {
return index;
}
}
return -1;
}
var Block = function () {
function Block() {
this.type = "block";
this.statements = [];
this.positionals = [];
}
Block.prototype.toJSON = function () {
return {
statements: this.statements,
locals: this.positionals
};
};
Block.prototype.push = function (statement) {
this.statements.push(statement);
};
return Block;
}();
var TemplateBlock = function (_Block) {
(0, _emberBabel.inherits)(TemplateBlock, _Block);
function TemplateBlock() {
var _this = (0, _emberBabel.possibleConstructorReturn)(this, _Block.apply(this, arguments));
_this.type = "template";
_this.yields = new _util.DictSet();
_this.named = new _util.DictSet();
_this.blocks = [];
_this.hasPartials = false;
return _this;
}
TemplateBlock.prototype.toJSON = function () {
return {
statements: this.statements,
locals: this.positionals,
named: this.named.toArray(),
yields: this.yields.toArray(),
hasPartials: this.hasPartials
};
};
return TemplateBlock;
}(Block);
var ComponentBlock = function (_Block2) {
(0, _emberBabel.inherits)(ComponentBlock, _Block2);
function ComponentBlock() {
var _this2 = (0, _emberBabel.possibleConstructorReturn)(this, _Block2.apply(this, arguments));
_this2.type = "component";
_this2.attributes = [];
_this2.arguments = [];
_this2.inParams = true;
return _this2;
}
ComponentBlock.prototype.push = function (statement) {
if (this.inParams) {
if (_wireFormat.Statements.isFlushElement(statement)) {
this.inParams = false;
} else if (_wireFormat.Statements.isArgument(statement)) {
this.arguments.push(statement);
} else if (_wireFormat.Statements.isAttribute(statement)) {
this.attributes.push(statement);
} else if (_wireFormat.Statements.isModifier(statement)) {
throw new Error('Compile Error: Element modifiers are not allowed in components');
} else {
throw new Error('Compile Error: only parameters allowed before flush-element');
}
} else {
this.statements.push(statement);
}
};
ComponentBlock.prototype.toJSON = function () {
var args = this.arguments;
var keys = args.map(function (arg) {
return arg[1];
});
var values = args.map(function (arg) {
return arg[2];
});
return {
attrs: this.attributes,
args: [keys, values],
locals: this.positionals,
statements: this.statements
};
};
return ComponentBlock;
}(Block);
var Template = function () {
function Template(meta) {
this.meta = meta;
this.block = new TemplateBlock();
}
Template.prototype.toJSON = function () {
return {
block: this.block.toJSON(),
meta: this.meta
};
};
return Template;
}();
var JavaScriptCompiler = function () {
function JavaScriptCompiler(opcodes, meta) {
this.blocks = new _util.Stack();
this.values = [];
this.opcodes = opcodes;
this.template = new Template(meta);
}
JavaScriptCompiler.process = function (opcodes, meta) {
var compiler = new JavaScriptCompiler(opcodes, meta);
return compiler.process();
};
JavaScriptCompiler.prototype.process = function () {
var _this3 = this;
this.opcodes.forEach(function (_ref) {
var opcode = _ref[0],
args = _ref.slice(1);
if (!_this3[opcode]) {
throw new Error('unimplemented ' + opcode + ' on JavaScriptCompiler');
}
_this3[opcode].apply(_this3, args);
});
return this.template;
};
JavaScriptCompiler.prototype.startBlock = function (_ref2) {
var program = _ref2[0];
var block = new Block();
block.positionals = program.blockParams;
this.blocks.push(block);
};
JavaScriptCompiler.prototype.endBlock = function () {
var template = this.template,
blocks = this.blocks;
template.block.blocks.push(blocks.pop().toJSON());
};
JavaScriptCompiler.prototype.startProgram = function () {
this.blocks.push(this.template.block);
};
JavaScriptCompiler.prototype.endProgram = function () {};
JavaScriptCompiler.prototype.text = function (content) {
this.push([_wireFormat.Ops.Text, content]);
};
JavaScriptCompiler.prototype.append = function (trusted) {
this.push([_wireFormat.Ops.Append, this.popValue(), trusted]);
};
JavaScriptCompiler.prototype.comment = function (value) {
this.push([_wireFormat.Ops.Comment, value]);
};
JavaScriptCompiler.prototype.modifier = function (path) {
var params = this.popValue();
var hash = this.popValue();
this.push([_wireFormat.Ops.Modifier, path, params, hash]);
};
JavaScriptCompiler.prototype.block = function (path, template, inverse) {
var params = this.popValue();
var hash = this.popValue();
var blocks = this.template.block.blocks;
(0, _util.assert)(typeof template !== 'number' || blocks[template] !== null, 'missing block in the compiler');
(0, _util.assert)(typeof inverse !== 'number' || blocks[inverse] !== null, 'missing block in the compiler');
this.push([_wireFormat.Ops.Block, path, params, hash, blocks[template], blocks[inverse]]);
};
JavaScriptCompiler.prototype.openElement = function (tag, blockParams) {
if (tag.indexOf('-') !== -1) {
this.startComponent(blockParams);
} else {
this.push([_wireFormat.Ops.OpenElement, tag, blockParams]);
}
};
JavaScriptCompiler.prototype.flushElement = function () {
this.push([_wireFormat.Ops.FlushElement]);
};
JavaScriptCompiler.prototype.closeElement = function (tag) {
var component;
if (tag.indexOf('-') !== -1) {
component = this.endComponent();
this.push([_wireFormat.Ops.Component, tag, component]);
} else {
this.push([_wireFormat.Ops.CloseElement]);
}
};
JavaScriptCompiler.prototype.staticAttr = function (name, namespace) {
var value = this.popValue();
this.push([_wireFormat.Ops.StaticAttr, name, value, namespace]);
};
JavaScriptCompiler.prototype.dynamicAttr = function (name, namespace) {
var value = this.popValue();
this.push([_wireFormat.Ops.DynamicAttr, name, value, namespace]);
};
JavaScriptCompiler.prototype.trustingAttr = function (name, namespace) {
var value = this.popValue();
this.push([_wireFormat.Ops.TrustingAttr, name, value, namespace]);
};
JavaScriptCompiler.prototype.staticArg = function (name) {
var value = this.popValue();
this.push([_wireFormat.Ops.StaticArg, name.slice(1), value]);
};
JavaScriptCompiler.prototype.dynamicArg = function (name) {
var value = this.popValue();
this.push([_wireFormat.Ops.DynamicArg, name.slice(1), value]);
};
JavaScriptCompiler.prototype.yield = function (to) {
var params = this.popValue();
this.push([_wireFormat.Ops.Yield, to, params]);
this.template.block.yields.add(to);
};
JavaScriptCompiler.prototype.debugger = function () {
this.push([_wireFormat.Ops.Debugger, null, null]);
};
JavaScriptCompiler.prototype.hasBlock = function (name) {
this.pushValue([_wireFormat.Ops.HasBlock, name]);
this.template.block.yields.add(name);
};
JavaScriptCompiler.prototype.hasBlockParams = function (name) {
this.pushValue([_wireFormat.Ops.HasBlockParams, name]);
this.template.block.yields.add(name);
};
JavaScriptCompiler.prototype.partial = function () {
var params = this.popValue();
this.push([_wireFormat.Ops.Partial, params[0]]);
this.template.block.hasPartials = true;
};
JavaScriptCompiler.prototype.literal = function (value) {
if (value === undefined) {
this.pushValue([_wireFormat.Ops.Undefined]);
} else {
this.pushValue(value);
}
};
JavaScriptCompiler.prototype.unknown = function (path) {
this.pushValue([_wireFormat.Ops.Unknown, path]);
};
JavaScriptCompiler.prototype.arg = function (path) {
this.template.block.named.add(path[0]);
this.pushValue([_wireFormat.Ops.Arg, path]);
};
JavaScriptCompiler.prototype.get = function (path) {
this.pushValue([_wireFormat.Ops.Get, path]);
};
JavaScriptCompiler.prototype.concat = function () {
this.pushValue([_wireFormat.Ops.Concat, this.popValue()]);
};
JavaScriptCompiler.prototype.helper = function (path) {
var params = this.popValue();
var hash = this.popValue();
this.pushValue([_wireFormat.Ops.Helper, path, params, hash]);
};
JavaScriptCompiler.prototype.startComponent = function (blockParams) {
var component = new ComponentBlock();
component.positionals = blockParams;
this.blocks.push(component);
};
JavaScriptCompiler.prototype.endComponent = function () {
var component = this.blocks.pop();
(0, _util.assert)(component.type === 'component', "Compiler bug: endComponent() should end a component");
return component.toJSON();
};
JavaScriptCompiler.prototype.prepareArray = function (size) {
var values = [],
i;
for (i = 0; i < size; i++) {
values.push(this.popValue());
}
this.pushValue(values);
};
JavaScriptCompiler.prototype.prepareObject = function (size) {
(0, _util.assert)(this.values.length >= size, 'Expected ' + size + ' values on the stack, found ' + this.values.length);
var keys = new Array(size),
i;
var values = new Array(size);
for (i = 0; i < size; i++) {
keys[i] = this.popValue();
values[i] = this.popValue();
}
this.pushValue([keys, values]);
};
JavaScriptCompiler.prototype.push = function (args) {
while (args[args.length - 1] === null) {
args.pop();
}
this.blocks.current.push(args);
};
JavaScriptCompiler.prototype.pushValue = function (val) {
this.values.push(val);
};
JavaScriptCompiler.prototype.popValue = function () {
(0, _util.assert)(this.values.length, "No expression found on stack");
return this.values.pop();
};
return JavaScriptCompiler;
}();
function isTrustedValue(value) {
return value.escaped !== undefined && !value.escaped;
}
var TemplateCompiler = function () {
function TemplateCompiler(options) {
this.templateId = 0;
this.templateIds = [];
this.symbols = null;
this.opcodes = [];
this.includeMeta = false;
this.options = options || {};
}
TemplateCompiler.compile = function (options, ast) {
var templateVisitor = new TemplateVisitor();
templateVisitor.visit(ast);
var compiler = new TemplateCompiler(options);
var opcodes = compiler.process(templateVisitor.actions);
return JavaScriptCompiler.process(opcodes, options.meta);
};
TemplateCompiler.prototype.process = function (actions) {
var _this4 = this;
actions.forEach(function (_ref3) {
var name = _ref3[0],
args = _ref3.slice(1);
if (!_this4[name]) {
throw new Error('Unimplemented ' + name + ' on TemplateCompiler');
}
_this4[name].apply(_this4, args);
});
return this.opcodes;
};
TemplateCompiler.prototype.startProgram = function (program) {
this.opcode('startProgram', program, program);
};
TemplateCompiler.prototype.endProgram = function () {
this.opcode('endProgram', null);
};
TemplateCompiler.prototype.startBlock = function (program) {
this.symbols = program[0].symbols;
this.templateId++;
this.opcode('startBlock', program, program);
};
TemplateCompiler.prototype.endBlock = function () {
this.symbols = null;
this.templateIds.push(this.templateId - 1);
this.opcode('endBlock', null);
};
TemplateCompiler.prototype.text = function (_ref4) {
var action = _ref4[0];
this.opcode('text', action, action.chars);
};
TemplateCompiler.prototype.comment = function (_ref5) {
var action = _ref5[0];
this.opcode('comment', action, action.value);
};
TemplateCompiler.prototype.openElement = function (_ref6) {
var action = _ref6[0],
i,
_i2;
this.opcode('openElement', action, action.tag, action.blockParams);
for (i = 0; i < action.attributes.length; i++) {
this.attribute([action.attributes[i]]);
}
for (_i2 = 0; _i2 < action.modifiers.length; _i2++) {
this.modifier([action.modifiers[_i2]]);
}
this.opcode('flushElement', null);
};
TemplateCompiler.prototype.closeElement = function (_ref7) {
var action = _ref7[0];
this.opcode('closeElement', null, action.tag);
};
TemplateCompiler.prototype.attribute = function (_ref8) {
var action = _ref8[0],
isTrusting;
var name = action.name,
value = action.value;
var namespace = (0, _util.getAttrNamespace)(name);
var isStatic = this.prepareAttributeValue(value);
if (name.charAt(0) === '@') {
// Arguments
if (isStatic) {
this.opcode('staticArg', action, name);
} else if (action.value.type === 'MustacheStatement') {
this.opcode('dynamicArg', action, name);
} else {
this.opcode('dynamicArg', action, name);
}
} else {
isTrusting = isTrustedValue(value);
if (isStatic) {
this.opcode('staticAttr', action, name, namespace);
} else if (isTrusting) {
this.opcode('trustingAttr', action, name, namespace);
} else if (action.value.type === 'MustacheStatement') {
this.opcode('dynamicAttr', action, name);
} else {
this.opcode('dynamicAttr', action, name, namespace);
}
}
};
TemplateCompiler.prototype.modifier = function (_ref9) {
var action = _ref9[0];
assertIsSimplePath(action, 'modifier');
var parts = action.path.parts;
this.prepareHelper(action);
this.opcode('modifier', action, parts);
};
TemplateCompiler.prototype.mustache = function (_ref10) {
var action = _ref10[0],
to,
params;
if (isYield(action)) {
to = assertValidYield(action);
this.yield(to, action);
} else if (isPartial(action)) {
params = assertValidPartial(action);
this.partial(params, action);
} else if (isDebugger(action)) {
assertValidDebuggerUsage(action);
this.debugger('debugger', action);
} else {
this.mustacheExpression(action);
this.opcode('append', action, !action.escaped);
}
};
TemplateCompiler.prototype.block = function (_ref11) {
var action /*, index, count*/ = _ref11[0];
this.prepareHelper(action);
var templateId = this.templateIds.pop();
var inverseId = action.inverse === null ? null : this.templateIds.pop();
this.opcode('block', action, action.path.parts, templateId, inverseId);
};
TemplateCompiler.prototype.arg = function (_ref12) {
var path = _ref12[0];
var parts = path.parts;
this.opcode('arg', path, parts);
};
TemplateCompiler.prototype.mustacheExpression = function (expr) {
if (isBuiltInHelper(expr)) {
this.builtInHelper(expr);
} else if (isLiteral(expr)) {
this.opcode('literal', expr, expr.path.value);
} else if (isArg(expr)) {
this.arg([expr.path]);
} else if (isHelperInvocation(expr)) {
this.prepareHelper(expr);
this.opcode('helper', expr, expr.path.parts);
} else if (!isSimplePath(expr) || isSelfGet(expr) || isLocalVariable(expr, this.symbols)) {
this.opcode('get', expr, expr.path.parts);
} else {
this.opcode('unknown', expr, expr.path.parts);
}
};
TemplateCompiler.prototype.yield = function (to, action) {
this.prepareParams(action.params);
this.opcode('yield', action, to);
};
TemplateCompiler.prototype.debugger = function () {
this.opcode('debugger', null);
};
TemplateCompiler.prototype.hasBlock = function (name, action) {
this.opcode('hasBlock', action, name);
};
TemplateCompiler.prototype.hasBlockParams = function (name, action) {
this.opcode('hasBlockParams', action, name);
};
TemplateCompiler.prototype.partial = function (params, action) {
this.prepareParams(action.params);
this.opcode('partial', action);
};
TemplateCompiler.prototype.builtInHelper = function (expr) {
var name, _name;
if (isHasBlock(expr)) {
name = assertValidHasBlockUsage(expr.path.original, expr);
this.hasBlock(name, expr);
} else if (isHasBlockParams(expr)) {
_name = assertValidHasBlockUsage(expr.path.original, expr);
this.hasBlockParams(_name, expr);
}
};
TemplateCompiler.prototype.SubExpression = function (expr) {
if (isBuiltInHelper(expr)) {
this.builtInHelper(expr);
} else {
this.prepareHelper(expr);
this.opcode('helper', expr, expr.path.parts);
}
};
TemplateCompiler.prototype.PathExpression = function (expr) {
if (expr.data) {
this.arg([expr]);
} else {
this.opcode('get', expr, expr.parts);
}
};
TemplateCompiler.prototype.StringLiteral = function (action) {
this.opcode('literal', null, action.value);
};
TemplateCompiler.prototype.BooleanLiteral = function (action) {
this.opcode('literal', null, action.value);
};
TemplateCompiler.prototype.NumberLiteral = function (action) {
this.opcode('literal', null, action.value);
};
TemplateCompiler.prototype.NullLiteral = function (action) {
this.opcode('literal', null, action.value);
};
TemplateCompiler.prototype.UndefinedLiteral = function (action) {
this.opcode('literal', null, action.value);
};
TemplateCompiler.prototype.opcode = function (name, action) {
for (_len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
var opcode = [name].concat(args),
_len,
args,
_key;
if (this.includeMeta && action) {
opcode.push(this.meta(action));
}
this.opcodes.push(opcode);
};
TemplateCompiler.prototype.prepareHelper = function (expr) {
assertIsSimplePath(expr, 'helper');
var params = expr.params,
hash = expr.hash;
this.prepareHash(hash);
this.prepareParams(params);
};
TemplateCompiler.prototype.preparePath = function (path) {
this.opcode('literal', path, path.parts);
};
TemplateCompiler.prototype.prepareParams = function (params) {
var i, param;
if (!params.length) {
this.opcode('literal', null, null);
return;
}
for (i = params.length - 1; i >= 0; i--) {
param = params[i];
(0, _util.assert)(this[param.type], 'Unimplemented ' + param.type + ' on TemplateCompiler');
this[param.type](param);
}
this.opcode('prepareArray', null, params.length);
};
TemplateCompiler.prototype.prepareHash = function (hash) {
var pairs = hash.pairs,
i,
_pairs$i,
key,
value;
if (!pairs.length) {
this.opcode('literal', null, null);
return;
}
for (i = pairs.length - 1; i >= 0; i--) {
_pairs$i = pairs[i], key = _pairs$i.key, value = _pairs$i.value;
(0, _util.assert)(this[value.type], 'Unimplemented ' + value.type + ' on TemplateCompiler');
this[value.type](value);
this.opcode('literal', null, key);
}
this.opcode('prepareObject', null, pairs.length);
};
TemplateCompiler.prototype.prepareAttributeValue = function (value) {
// returns the static value if the value is static
switch (value.type) {
case 'TextNode':
this.opcode('literal', value, value.chars);
return true;
case 'MustacheStatement':
this.attributeMustache([value]);
return false;
case 'ConcatStatement':
this.prepareConcatParts(value.parts);
this.opcode('concat', value);
return false;
}
};
TemplateCompiler.prototype.prepareConcatParts = function (parts) {
var i, part;
for (i = parts.length - 1; i >= 0; i--) {
part = parts[i];
if (part.type === 'MustacheStatement') {
this.attributeMustache([part]);
} else if (part.type === 'TextNode') {
this.opcode('literal', null, part.chars);
}
}
this.opcode('prepareArray', null, parts.length);
};
TemplateCompiler.prototype.attributeMustache = function (_ref13) {
var action = _ref13[0];
this.mustacheExpression(action);
};
TemplateCompiler.prototype.meta = function (node) {
var loc = node.loc;
if (!loc) {
return [];
}
var source = loc.source,
start = loc.start,
end = loc.end;
return ['loc', [source || null, [start.line, start.column], [end.line, end.column]]];
};
return TemplateCompiler;
}();
function isHelperInvocation(mustache) {
return mustache.params && mustache.params.length > 0 || mustache.hash && mustache.hash.pairs.length > 0;
}
function isSimplePath(mustache) {
var parts = mustache.path.parts;
return parts.length === 1;
}
function isSelfGet(mustache) {
var parts = mustache.path.parts;
return parts[0] === null;
}
function isLocalVariable(mustache, symbols) {
var parts = mustache.path.parts;
return parts.length === 1 && symbols && symbols.hasLocalVariable(parts[0]);
}
function isYield(_ref14) {
var path = _ref14.path;
return path.original === 'yield';
}
function isPartial(_ref15) {
var path = _ref15.path;
return path.original === 'partial';
}
function isDebugger(_ref16) {
var path = _ref16.path;
return path.original === 'debugger';
}
function isArg(_ref17) {
var path = _ref17.path;
return path.data;
}
function isLiteral(_ref18) {
var path = _ref18.path;
return path.type === 'StringLiteral' || path.type === 'BooleanLiteral' || path.type === 'NumberLiteral' || path.type === 'NullLiteral' || path.type === 'UndefinedLiteral';
}
function isHasBlock(_ref19) {
var path = _ref19.path;
return path.original === 'has-block';
}
function assertIsSimplePath(expr, context) {
var original, line;
if (!isSimplePath(expr)) {
original = expr.path.original, line = expr.loc.start.line;
throw new Error('`' + original + '` is not a valid name for a ' + context + ' on line ' + line + '.');
}
}
function isHasBlockParams(_ref20) {
var path = _ref20.path;
return path.original === 'has-block-params';
}
function isBuiltInHelper(expr) {
return isHasBlock(expr) || isHasBlockParams(expr);
}
function assertValidYield(_ref21) {
var hash = _ref21.hash;
var pairs = hash.pairs;
if (pairs.length === 1 && pairs[0].key !== 'to' || pairs.length > 1) {
throw new Error('yield only takes a single named argument: \'to\'');
} else if (pairs.length === 1 && pairs[0].value.type !== 'StringLiteral') {
throw new Error('you can only yield to a literal value');
} else if (pairs.length === 0) {
return 'default';
} else {
return pairs[0].value.value;
}
}
function assertValidPartial(_ref22) {
var params = _ref22.params,
hash = _ref22.hash,
escaped = _ref22.escaped,
loc = _ref22.loc;
if (params && params.length !== 1) {
throw new Error('Partial found with no arguments. You must specify a template name. (on line ' + loc.start.line + ')');
} else if (hash && hash.pairs.length > 0) {
throw new Error('partial does not take any named arguments (on line ' + loc.start.line + ')');
} else if (!escaped) {
throw new Error('{{{partial ...}}} is not supported, please use {{partial ...}} instead (on line ' + loc.start.line + ')');
}
return params;
}
function assertValidHasBlockUsage(type, _ref23) {
var params = _ref23.params,
hash = _ref23.hash,
loc = _ref23.loc;
if (hash && hash.pairs.length > 0) {
throw new Error(type + ' does not take any named arguments');
}
if (params.length === 0) {
return 'default';
} else if (params.length === 1) {
if (params[0].type === 'StringLiteral') {
return params[0].value;
} else {
throw new Error('you can only yield to a literal value (on line ' + loc.start.line + ')');
}
} else {
throw new Error(type + ' only takes a single positional argument (on line ' + loc.start.line + ')');
}
}
function assertValidDebuggerUsage(_ref24) {
var params = _ref24.params,
hash = _ref24.hash;
if (hash && hash.pairs.length > 0) {
throw new Error('debugger does not take any named arguments');
}
if (params.length === 0) {
return 'default';
} else {
throw new Error('debugger does not take any positional arguments');
}
}
var defaultId = function () {
var idFn = void 0;
return function () {
var crypto;
if (!idFn) {
if (typeof _nodeModule.require === 'function') {
try {
/* tslint:disable:no-require-imports */
crypto = (0, _nodeModule.require)('crypto');
/* tslint:enable:no-require-imports */
idFn = function (src) {
var hash = crypto.createHash('sha1');
hash.update(src, 'utf8');
// trim to 6 bytes of data (2^48 - 1)
return hash.digest('base64').substring(0, 8);
};
idFn("test");
} catch (e) {
idFn = null;
}
}
if (!idFn) {
idFn = function () {
return null;
};
}
}
return idFn;
};
}();
exports.precompile = function (string, options) {
var opts = options || {
id: defaultId(),
meta: {}
};
var ast = (0, _syntax.preprocess)(string, opts);
var _TemplateCompiler$com = TemplateCompiler.compile(opts, ast),
block = _TemplateCompiler$com.block,
meta = _TemplateCompiler$com.meta;
var idFn = opts.id || defaultId();
var blockJSON = JSON.stringify(block.toJSON());
var templateJSONObject = {
id: idFn(JSON.stringify(meta) + blockJSON),
block: blockJSON,
meta: meta
};
// JSON is javascript
return JSON.stringify(templateJSONObject);
};
exports.TemplateVisitor = TemplateVisitor;
});
enifed("@glimmer/reference", ["exports", "ember-babel", "@glimmer/util"], function (exports, _emberBabel, _util) {
"use strict";
exports.isModified = exports.ReferenceCache = exports.map = exports.CachedReference = exports.CURRENT_TAG = exports.VOLATILE_TAG = exports.CONSTANT_TAG = exports.UpdatableTag = exports.CachedTag = exports.combine = exports.combineSlice = exports.combineTagged = exports.DirtyableTag = exports.RevisionTag = exports.VOLATILE = exports.INITIAL = exports.CONSTANT = exports.IteratorSynchronizer = exports.ReferenceIterator = exports.IterationArtifacts = exports.referenceFromParts = exports.ListItem = exports.isConst = exports.ConstReference = undefined;
var CONSTANT = 0;
var INITIAL = 1;
var VOLATILE = NaN;
var RevisionTag = function () {
function RevisionTag() {}
RevisionTag.prototype.validate = function (snapshot) {
return this.value() === snapshot;
};
return RevisionTag;
}();
var $REVISION = INITIAL;
var DirtyableTag = function (_RevisionTag) {
(0, _emberBabel.inherits)(DirtyableTag, _RevisionTag);
function DirtyableTag() {
var revision = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : $REVISION;
var _this = (0, _emberBabel.possibleConstructorReturn)(this, _RevisionTag.call(this));
_this.revision = revision;
return _this;
}
DirtyableTag.prototype.value = function () {
return this.revision;
};
DirtyableTag.prototype.dirty = function () {
this.revision = ++$REVISION;
};
return DirtyableTag;
}(RevisionTag);
function _combine(tags) {
switch (tags.length) {
case 0:
return CONSTANT_TAG;
case 1:
return tags[0];
case 2:
return new TagsPair(tags[0], tags[1]);
default:
return new TagsCombinator(tags);
}
}
var CachedTag = function (_RevisionTag2) {
(0, _emberBabel.inherits)(CachedTag, _RevisionTag2);
function CachedTag() {
var _this2 = (0, _emberBabel.possibleConstructorReturn)(this, _RevisionTag2.apply(this, arguments));
_this2.lastChecked = null;
_this2.lastValue = null;
return _this2;
}
CachedTag.prototype.value = function () {
var lastChecked = this.lastChecked,
lastValue = this.lastValue;
if (lastChecked !== $REVISION) {
this.lastChecked = $REVISION;
this.lastValue = lastValue = this.compute();
}
return this.lastValue;
};
CachedTag.prototype.invalidate = function () {
this.lastChecked = null;
};
return CachedTag;
}(RevisionTag);
var TagsPair = function (_CachedTag) {
(0, _emberBabel.inherits)(TagsPair, _CachedTag);
function TagsPair(first, second) {
var _this3 = (0, _emberBabel.possibleConstructorReturn)(this, _CachedTag.call(this));
_this3.first = first;
_this3.second = second;
return _this3;
}
TagsPair.prototype.compute = function () {
return Math.max(this.first.value(), this.second.value());
};
return TagsPair;
}(CachedTag);
var TagsCombinator = function (_CachedTag2) {
(0, _emberBabel.inherits)(TagsCombinator, _CachedTag2);
function TagsCombinator(tags) {
var _this4 = (0, _emberBabel.possibleConstructorReturn)(this, _CachedTag2.call(this));
_this4.tags = tags;
return _this4;
}
TagsCombinator.prototype.compute = function () {
var tags = this.tags,
i,
value;
var max = -1;
for (i = 0; i < tags.length; i++) {
value = tags[i].value();
max = Math.max(value, max);
}
return max;
};
return TagsCombinator;
}(CachedTag);
var UpdatableTag = function (_CachedTag3) {
(0, _emberBabel.inherits)(UpdatableTag, _CachedTag3);
function UpdatableTag(tag) {
var _this5 = (0, _emberBabel.possibleConstructorReturn)(this, _CachedTag3.call(this));
_this5.tag = tag;
_this5.lastUpdated = INITIAL;
return _this5;
}
UpdatableTag.prototype.compute = function () {
return Math.max(this.lastUpdated, this.tag.value());
};
UpdatableTag.prototype.update = function (tag) {
if (tag !== this.tag) {
this.tag = tag;
this.lastUpdated = $REVISION;
this.invalidate();
}
};
return UpdatableTag;
}(CachedTag);
//////////
var CONSTANT_TAG = new (function (_RevisionTag3) {
(0, _emberBabel.inherits)(ConstantTag, _RevisionTag3);
function ConstantTag() {
return (0, _emberBabel.possibleConstructorReturn)(this, _RevisionTag3.apply(this, arguments));
}
ConstantTag.prototype.value = function () {
return CONSTANT;
};
return ConstantTag;
}(RevisionTag))();
var VOLATILE_TAG = new (function (_RevisionTag4) {
(0, _emberBabel.inherits)(VolatileTag, _RevisionTag4);
function VolatileTag() {
return (0, _emberBabel.possibleConstructorReturn)(this, _RevisionTag4.apply(this, arguments));
}
VolatileTag.prototype.value = function () {
return VOLATILE;
};
return VolatileTag;
}(RevisionTag))();
var CURRENT_TAG = new (function (_DirtyableTag) {
(0, _emberBabel.inherits)(CurrentTag, _DirtyableTag);
function CurrentTag() {
return (0, _emberBabel.possibleConstructorReturn)(this, _DirtyableTag.apply(this, arguments));
}
CurrentTag.prototype.value = function () {
return $REVISION;
};
return CurrentTag;
}(DirtyableTag))();
var CachedReference = function () {
function CachedReference() {
this.lastRevision = null;
this.lastValue = null;
}
CachedReference.prototype.value = function () {
var tag = this.tag,
lastRevision = this.lastRevision,
lastValue = this.lastValue;
if (!lastRevision || !tag.validate(lastRevision)) {
lastValue = this.lastValue = this.compute();
this.lastRevision = tag.value();
}
return lastValue;
};
CachedReference.prototype.invalidate = function () {
this.lastRevision = null;
};
return CachedReference;
}();
var MapperReference = function (_CachedReference) {
(0, _emberBabel.inherits)(MapperReference, _CachedReference);
function MapperReference(reference, mapper) {
var _this9 = (0, _emberBabel.possibleConstructorReturn)(this, _CachedReference.call(this));
_this9.tag = reference.tag;
_this9.reference = reference;
_this9.mapper = mapper;
return _this9;
}
MapperReference.prototype.compute = function () {
var reference = this.reference,
mapper = this.mapper;
return mapper(reference.value());
};
return MapperReference;
}(CachedReference);
//////////
var ReferenceCache = function () {
function ReferenceCache(reference) {
this.lastValue = null;
this.lastRevision = null;
this.initialized = false;
this.tag = reference.tag;
this.reference = reference;
}
ReferenceCache.prototype.peek = function () {
if (!this.initialized) {
return this.initialize();
}
return this.lastValue;
};
ReferenceCache.prototype.revalidate = function () {
if (!this.initialized) {
return this.initialize();
}
var reference = this.reference,
lastRevision = this.lastRevision;
var tag = reference.tag;
if (tag.validate(lastRevision)) return NOT_MODIFIED;
this.lastRevision = tag.value();
var lastValue = this.lastValue;
var value = reference.value();
if (value === lastValue) return NOT_MODIFIED;
this.lastValue = value;
return value;
};
ReferenceCache.prototype.initialize = function () {
var reference = this.reference;
var value = this.lastValue = reference.value();
this.lastRevision = reference.tag.value();
this.initialized = true;
return value;
};
return ReferenceCache;
}();
var NOT_MODIFIED = "adb3b78e-3d22-4e4b-877a-6317c2c5c145";
var ConstReference = function () {
function ConstReference(inner) {
this.inner = inner;
this.tag = CONSTANT_TAG;
}
ConstReference.prototype.value = function () {
return this.inner;
};
return ConstReference;
}();
var ListItem = function (_ListNode) {
(0, _emberBabel.inherits)(ListItem, _ListNode);
function ListItem(iterable, result) {
var _this10 = (0, _emberBabel.possibleConstructorReturn)(this, _ListNode.call(this, iterable.valueReferenceFor(result)));
_this10.retained = false;
_this10.seen = false;
_this10.key = result.key;
_this10.iterable = iterable;
_this10.memo = iterable.memoReferenceFor(result);
return _this10;
}
ListItem.prototype.update = function (item) {
this.retained = true;
this.iterable.updateValueReference(this.value, item);
this.iterable.updateMemoReference(this.memo, item);
};
ListItem.prototype.shouldRemove = function () {
return !this.retained;
};
ListItem.prototype.reset = function () {
this.retained = false;
this.seen = false;
};
return ListItem;
}(_util.ListNode);
var IterationArtifacts = function () {
function IterationArtifacts(iterable) {
this.map = (0, _util.dict)();
this.list = new _util.LinkedList();
this.tag = iterable.tag;
this.iterable = iterable;
}
IterationArtifacts.prototype.isEmpty = function () {
var iterator = this.iterator = this.iterable.iterate();
return iterator.isEmpty();
};
IterationArtifacts.prototype.iterate = function () {
var iterator = this.iterator || this.iterable.iterate();
this.iterator = null;
return iterator;
};
IterationArtifacts.prototype.has = function (key) {
return !!this.map[key];
};
IterationArtifacts.prototype.get = function (key) {
return this.map[key];
};
IterationArtifacts.prototype.wasSeen = function (key) {
var node = this.map[key];
return node && node.seen;
};
IterationArtifacts.prototype.append = function (item) {
var map = this.map,
list = this.list,
iterable = this.iterable;
var node = map[item.key] = new ListItem(iterable, item);
list.append(node);
return node;
};
IterationArtifacts.prototype.insertBefore = function (item, reference) {
var map = this.map,
list = this.list,
iterable = this.iterable;
var node = map[item.key] = new ListItem(iterable, item);
node.retained = true;
list.insertBefore(node, reference);
return node;
};
IterationArtifacts.prototype.move = function (item, reference) {
var list = this.list;
item.retained = true;
list.remove(item);
list.insertBefore(item, reference);
};
IterationArtifacts.prototype.remove = function (item) {
var list = this.list;
list.remove(item);
delete this.map[item.key];
};
IterationArtifacts.prototype.nextNode = function (item) {
return this.list.nextNode(item);
};
IterationArtifacts.prototype.head = function () {
return this.list.head();
};
return IterationArtifacts;
}();
var ReferenceIterator = function () {
// if anyone needs to construct this object with something other than
// an iterable, let @wycats know.
function ReferenceIterator(iterable) {
this.iterator = null;
var artifacts = new IterationArtifacts(iterable);
this.artifacts = artifacts;
}
ReferenceIterator.prototype.next = function () {
var artifacts = this.artifacts;
var iterator = this.iterator = this.iterator || artifacts.iterate();
var item = iterator.next();
if (!item) return null;
return artifacts.append(item);
};
return ReferenceIterator;
}();
var Phase;
(function (Phase) {
Phase[Phase["Append"] = 0] = "Append";
Phase[Phase["Prune"] = 1] = "Prune";
Phase[Phase["Done"] = 2] = "Done";
})(Phase || (Phase = {}));
var IteratorSynchronizer = function () {
function IteratorSynchronizer(_ref) {
var target = _ref.target,
artifacts = _ref.artifacts;
this.target = target;
this.artifacts = artifacts;
this.iterator = artifacts.iterate();
this.current = artifacts.head();
}
IteratorSynchronizer.prototype.sync = function () {
var phase = Phase.Append;
while (true) {
switch (phase) {
case Phase.Append:
phase = this.nextAppend();
break;
case Phase.Prune:
phase = this.nextPrune();
break;
case Phase.Done:
this.nextDone();
return;
}
}
};
IteratorSynchronizer.prototype.advanceToKey = function (key) {
var current = this.current,
artifacts = this.artifacts;
var seek = current;
while (seek && seek.key !== key) {
seek.seen = true;
seek = artifacts.nextNode(seek);
}
this.current = seek && artifacts.nextNode(seek);
};
IteratorSynchronizer.prototype.nextAppend = function () {
var iterator = this.iterator,
current = this.current,
artifacts = this.artifacts;
var item = iterator.next();
if (item === null) {
return this.startPrune();
}
var key = item.key;
if (current && current.key === key) {
this.nextRetain(item);
} else if (artifacts.has(key)) {
this.nextMove(item);
} else {
this.nextInsert(item);
}
return Phase.Append;
};
IteratorSynchronizer.prototype.nextRetain = function (item) {
var artifacts = this.artifacts,
current = this.current;
current = (0, _util.expect)(current, 'BUG: current is empty');
current.update(item);
this.current = artifacts.nextNode(current);
this.target.retain(item.key, current.value, current.memo);
};
IteratorSynchronizer.prototype.nextMove = function (item) {
var current = this.current,
artifacts = this.artifacts,
target = this.target;
var key = item.key;
var found = artifacts.get(item.key);
found.update(item);
if (artifacts.wasSeen(item.key)) {
artifacts.move(found, current);
target.move(found.key, found.value, found.memo, current ? current.key : null);
} else {
this.advanceToKey(key);
}
};
IteratorSynchronizer.prototype.nextInsert = function (item) {
var artifacts = this.artifacts,
target = this.target,
current = this.current;
var node = artifacts.insertBefore(item, current);
target.insert(node.key, node.value, node.memo, current ? current.key : null);
};
IteratorSynchronizer.prototype.startPrune = function () {
this.current = this.artifacts.head();
return Phase.Prune;
};
IteratorSynchronizer.prototype.nextPrune = function () {
var artifacts = this.artifacts,
target = this.target,
current = this.current;
if (current === null) {
return Phase.Done;
}
var node = current;
this.current = artifacts.nextNode(node);
if (node.shouldRemove()) {
artifacts.remove(node);
target.delete(node.key);
} else {
node.reset();
}
return Phase.Prune;
};
IteratorSynchronizer.prototype.nextDone = function () {
this.target.done();
};
return IteratorSynchronizer;
}();
exports.ConstReference = ConstReference;
exports.isConst = function (reference) {
return reference.tag === CONSTANT_TAG;
};
exports.ListItem = ListItem;
exports.referenceFromParts = function (root, parts) {
var reference = root,
i;
for (i = 0; i < parts.length; i++) {
reference = reference.get(parts[i]);
}
return reference;
};
exports.IterationArtifacts = IterationArtifacts;
exports.ReferenceIterator = ReferenceIterator;
exports.IteratorSynchronizer = IteratorSynchronizer;
exports.CONSTANT = CONSTANT;
exports.INITIAL = INITIAL;
exports.VOLATILE = VOLATILE;
exports.RevisionTag = RevisionTag;
exports.DirtyableTag = DirtyableTag;
exports.combineTagged = function (tagged) {
var optimized = [],
i,
l,
tag;
for (i = 0, l = tagged.length; i < l; i++) {
tag = tagged[i].tag;
if (tag === VOLATILE_TAG) return VOLATILE_TAG;
if (tag === CONSTANT_TAG) continue;
optimized.push(tag);
}
return _combine(optimized);
};
exports.combineSlice = function (slice) {
var optimized = [],
tag;
var node = slice.head();
while (node !== null) {
tag = node.tag;
if (tag === VOLATILE_TAG) return VOLATILE_TAG;
if (tag !== CONSTANT_TAG) optimized.push(tag);
node = slice.nextNode(node);
}
return _combine(optimized);
};
exports.combine = function (tags) {
var optimized = [],
i,
l,
tag;
for (i = 0, l = tags.length; i < l; i++) {
tag = tags[i];
if (tag === VOLATILE_TAG) return VOLATILE_TAG;
if (tag === CONSTANT_TAG) continue;
optimized.push(tag);
}
return _combine(optimized);
};
exports.CachedTag = CachedTag;
exports.UpdatableTag = UpdatableTag;
exports.CONSTANT_TAG = CONSTANT_TAG;
exports.VOLATILE_TAG = VOLATILE_TAG;
exports.CURRENT_TAG = CURRENT_TAG;
exports.CachedReference = CachedReference;
exports.map = function (reference, mapper) {
return new MapperReference(reference, mapper);
};
exports.ReferenceCache = ReferenceCache;
exports.isModified = function (value) {
return value !== NOT_MODIFIED;
};
});
enifed('@glimmer/syntax', ['exports', 'handlebars', 'simple-html-tokenizer'], function (exports, _handlebars, _simpleHtmlTokenizer) {
'use strict';
exports.print = exports.Walker = exports.traverse = exports.builders = exports.preprocess = undefined;
// Statements
// Nodes
// Expressions
function buildPath(original, loc) {
if (typeof original !== 'string') return original;
var parts = original.split('.');
if (parts[0] === 'this') {
parts[0] = null;
}
return {
type: "PathExpression",
original: original,
parts: parts,
data: false,
loc: buildLoc(loc)
};
}
// Miscellaneous
function buildHash(pairs) {
return {
type: "Hash",
pairs: pairs || []
};
}
function buildSource(source) {
return source || null;
}
function buildPosition(line, column) {
return {
line: typeof line === 'number' ? line : null,
column: typeof column === 'number' ? column : null
};
}
function buildLoc() {
var _len, args, _key, loc, startLine, startColumn, endLine, endColumn, source;
for (_len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (args.length === 1) {
loc = args[0];
if (typeof loc === 'object') {
return {
source: buildSource(loc.source),
start: buildPosition(loc.start.line, loc.start.column),
end: buildPosition(loc.end.line, loc.end.column)
};
} else {
return null;
}
} else {
startLine = args[0], startColumn = args[1], endLine = args[2], endColumn = args[3], source = args[4];
return {
source: buildSource(source),
start: buildPosition(startLine, startColumn),
end: buildPosition(endLine, endColumn)
};
}
}
var b = {
mustache: function (path, params, hash, raw, loc) {
return {
type: "MustacheStatement",
path: buildPath(path),
params: params || [],
hash: hash || buildHash([]),
escaped: !raw,
loc: buildLoc(loc)
};
},
block: function (path, params, hash, program, inverse, loc) {
return {
type: "BlockStatement",
path: buildPath(path),
params: params ? params.map(buildPath) : [],
hash: hash || buildHash([]),
program: program || null,
inverse: inverse || null,
loc: buildLoc(loc)
};
},
partial: function (name, params, hash, indent) {
return {
type: "PartialStatement",
name: name,
params: params || [],
hash: hash || buildHash([]),
indent: indent
};
},
comment: function (value, loc) {
return {
type: "CommentStatement",
value: value,
loc: buildLoc(loc)
};
},
mustacheComment: function (value, loc) {
return {
type: "MustacheCommentStatement",
value: value,
loc: buildLoc(loc)
};
},
element: function (tag, attributes, modifiers, children, comments, loc) {
// this is used for backwards compat prior to `comments` being added to the AST
if (!Array.isArray(comments)) {
loc = comments;
comments = [];
}
return {
type: "ElementNode",
tag: tag || "",
attributes: attributes || [],
blockParams: [],
modifiers: modifiers || [],
comments: comments || [],
children: children || [],
loc: buildLoc(loc)
};
},
elementModifier: function (path, params, hash, loc) {
return {
type: "ElementModifierStatement",
path: buildPath(path),
params: params || [],
hash: hash || buildHash([]),
loc: buildLoc(loc)
};
},
attr: function (name, value, loc) {
return {
type: "AttrNode",
name: name,
value: value,
loc: buildLoc(loc)
};
},
text: function (chars, loc) {
return {
type: "TextNode",
chars: chars || "",
loc: buildLoc(loc)
};
},
sexpr: function (path, params, hash, loc) {
return {
type: "SubExpression",
path: buildPath(path),
params: params || [],
hash: hash || buildHash([]),
loc: buildLoc(loc)
};
},
path: buildPath,
string: function (value) {
return {
type: "StringLiteral",
value: value,
original: value
};
},
boolean: function (value) {
return {
type: "BooleanLiteral",
value: value,
original: value
};
},
number: function (value) {
return {
type: "NumberLiteral",
value: value,
original: value
};
},
undefined: function () {
return {
type: "UndefinedLiteral",
value: undefined,
original: undefined
};
},
null: function () {
return {
type: "NullLiteral",
value: null,
original: null
};
},
concat: function (parts) {
return {
type: "ConcatStatement",
parts: parts || []
};
},
hash: buildHash,
pair: function (key, value) {
return {
type: "HashPair",
key: key,
value: value
};
},
program: function (body, blockParams, loc) {
return {
type: "Program",
body: body || [],
blockParams: blockParams || [],
loc: buildLoc(loc)
};
},
loc: buildLoc,
pos: buildPosition
};
function build(ast) {
if (!ast) {
return '';
}
var output = [],
chainBlock,
body,
value,
lines;
switch (ast.type) {
case 'Program':
{
chainBlock = ast.chained && ast.body[0];
if (chainBlock) {
chainBlock.chained = true;
}
body = buildEach(ast.body).join('');
output.push(body);
}
break;
case 'ElementNode':
output.push('<', ast.tag);
if (ast.attributes.length) {
output.push(' ', buildEach(ast.attributes).join(' '));
}
if (ast.modifiers.length) {
output.push(' ', buildEach(ast.modifiers).join(' '));
}
if (ast.comments.length) {
output.push(' ', buildEach(ast.comments).join(' '));
}
output.push('>');
output.push.apply(output, buildEach(ast.children));
output.push('', ast.tag, '>');
break;
case 'AttrNode':
output.push(ast.name, '=');
value = build(ast.value);
if (ast.value.type === 'TextNode') {
output.push('"', value, '"');
} else {
output.push(value);
}
break;
case 'ConcatStatement':
output.push('"');
ast.parts.forEach(function (node) {
if (node.type === 'StringLiteral') {
output.push(node.original);
} else {
output.push(build(node));
}
});
output.push('"');
break;
case 'TextNode':
output.push(ast.chars);
break;
case 'MustacheStatement':
{
output.push(compactJoin(['{{', pathParams(ast), '}}']));
}
break;
case 'MustacheCommentStatement':
{
output.push(compactJoin(['{{!--', ast.value, '--}}']));
}
break;
case 'ElementModifierStatement':
{
output.push(compactJoin(['{{', pathParams(ast), '}}']));
}
break;
case 'PathExpression':
output.push(ast.original);
break;
case 'SubExpression':
{
output.push('(', pathParams(ast), ')');
}
break;
case 'BooleanLiteral':
output.push(ast.value ? 'true' : false);
break;
case 'BlockStatement':
{
lines = [];
if (ast.chained) {
lines.push(['{{else ', pathParams(ast), '}}'].join(''));
} else {
lines.push(openBlock(ast));
}
lines.push(build(ast.program));
if (ast.inverse) {
if (!ast.inverse.chained) {
lines.push('{{else}}');
}
lines.push(build(ast.inverse));
}
if (!ast.chained) {
lines.push(closeBlock(ast));
}
output.push(lines.join(''));
}
break;
case 'PartialStatement':
{
output.push(compactJoin(['{{>', pathParams(ast), '}}']));
}
break;
case 'CommentStatement':
{
output.push(compactJoin(['']));
}
break;
case 'StringLiteral':
{
output.push('"' + ast.value + '"');
}
break;
case 'NumberLiteral':
{
output.push(ast.value);
}
break;
case 'UndefinedLiteral':
{
output.push('undefined');
}
break;
case 'NullLiteral':
{
output.push('null');
}
break;
case 'Hash':
{
output.push(ast.pairs.map(function (pair) {
return build(pair);
}).join(' '));
}
break;
case 'HashPair':
{
output.push(ast.key + '=' + build(ast.value));
}
break;
}
return output.join('');
}
function compact(array) {
var newArray = [];
array.forEach(function (a) {
if (typeof a !== 'undefined' && a !== null && a !== '') {
newArray.push(a);
}
});
return newArray;
}
function buildEach(asts) {
var output = [];
asts.forEach(function (node) {
output.push(build(node));
});
return output;
}
function pathParams(ast) {
var name = build(ast.name);
var path = build(ast.path);
var params = buildEach(ast.params).join(' ');
var hash = build(ast.hash);
return compactJoin([name, path, params, hash], ' ');
}
function compactJoin(array, delimiter) {
return compact(array).join(delimiter || '');
}
function blockParams(block) {
var params = block.program.blockParams;
if (params.length) {
return ' as |' + params.join(' ') + '|';
}
}
function openBlock(block) {
return ['{{#', pathParams(block), blockParams(block), '}}'].join('');
}
function closeBlock(block) {
return ['{{/', build(block.path), '}}'].join('');
}
var visitorKeys = {
Program: ['body'],
MustacheStatement: ['path', 'params', 'hash'],
BlockStatement: ['path', 'params', 'hash', 'program', 'inverse'],
ElementModifierStatement: ['path', 'params', 'hash'],
PartialStatement: ['name', 'params', 'hash'],
CommentStatement: [],
MustacheCommentStatement: [],
ElementNode: ['attributes', 'modifiers', 'children', 'comments'],
AttrNode: ['value'],
TextNode: [],
ConcatStatement: ['parts'],
SubExpression: ['path', 'params', 'hash'],
PathExpression: [],
StringLiteral: [],
BooleanLiteral: [],
NumberLiteral: [],
NullLiteral: [],
UndefinedLiteral: [],
Hash: ['pairs'],
HashPair: ['value']
};
function TraversalError(message, node, parent, key) {
this.name = "TraversalError";
this.message = message;
this.node = node;
this.parent = parent;
this.key = key;
}
TraversalError.prototype = Object.create(Error.prototype);
TraversalError.prototype.constructor = TraversalError;
function cannotRemoveNode(node, parent, key) {
return new TraversalError("Cannot remove a node unless it is part of an array", node, parent, key);
}
function cannotReplaceNode(node, parent, key) {
return new TraversalError("Cannot replace a node with multiple nodes unless it is part of an array", node, parent, key);
}
function cannotReplaceOrRemoveInKeyHandlerYet(node, key) {
return new TraversalError("Replacing and removing in key handlers is not yet supported.", node, null, key);
}
function visitNode(visitor, node) {
var handler = visitor[node.type] || visitor.All,
keys,
i;
var result = void 0;
if (handler && handler.enter) {
result = handler.enter.call(null, node);
}
if (result !== undefined && result !== null) {
if (JSON.stringify(node) === JSON.stringify(result)) {
result = undefined;
} else if (Array.isArray(result)) {
return visitArray(visitor, result) || result;
} else {
return visitNode(visitor, result) || result;
}
}
if (result === undefined) {
keys = visitorKeys[node.type];
for (i = 0; i < keys.length; i++) {
visitKey(visitor, handler, node, keys[i]);
}
if (handler && handler.exit) {
result = handler.exit.call(null, node);
}
}
return result;
}
function visitKey(visitor, handler, node, key) {
var value = node[key],
_result;
if (!value) {
return;
}
var keyHandler = handler && (handler.keys[key] || handler.keys.All);
var result = void 0;
if (keyHandler && keyHandler.enter) {
result = keyHandler.enter.call(null, node, key);
if (result !== undefined) {
throw cannotReplaceOrRemoveInKeyHandlerYet(node, key);
}
}
if (Array.isArray(value)) {
visitArray(visitor, value);
} else {
_result = visitNode(visitor, value);
if (_result !== undefined) {
assignKey(node, key, _result);
}
}
if (keyHandler && keyHandler.exit) {
result = keyHandler.exit.call(null, node, key);
if (result !== undefined) {
throw cannotReplaceOrRemoveInKeyHandlerYet(node, key);
}
}
}
function visitArray(visitor, array) {
var i, result;
for (i = 0; i < array.length; i++) {
result = visitNode(visitor, array[i]);
if (result !== undefined) {
i += spliceArray(array, i, result) - 1;
}
}
}
function assignKey(node, key, result) {
if (result === null) {
throw cannotRemoveNode(node[key], node, key);
} else if (Array.isArray(result)) {
if (result.length === 1) {
node[key] = result[0];
} else {
if (result.length === 0) {
throw cannotRemoveNode(node[key], node, key);
} else {
throw cannotReplaceNode(node[key], node, key);
}
}
} else {
node[key] = result;
}
}
function spliceArray(array, index, result) {
if (result === null) {
array.splice(index, 1);
return 0;
} else if (Array.isArray(result)) {
array.splice.apply(array, [index, 1].concat(result));
return result.length;
} else {
array.splice(index, 1, result);
return 1;
}
}
function traverse(node, visitor) {
visitNode(normalizeVisitor(visitor), node);
}
function normalizeVisitor(visitor) {
var normalizedVisitor = {},
handler,
normalizedKeys,
keys,
keyHandler;
for (var type in visitor) {
handler = visitor[type] || visitor.All;
normalizedKeys = {};
if (typeof handler === 'object') {
keys = handler.keys;
if (keys) {
for (var key in keys) {
keyHandler = keys[key];
if (typeof keyHandler === 'object') {
normalizedKeys[key] = {
enter: typeof keyHandler.enter === 'function' ? keyHandler.enter : null,
exit: typeof keyHandler.exit === 'function' ? keyHandler.exit : null
};
} else if (typeof keyHandler === 'function') {
normalizedKeys[key] = {
enter: keyHandler,
exit: null
};
}
}
}
normalizedVisitor[type] = {
enter: typeof handler.enter === 'function' ? handler.enter : null,
exit: typeof handler.exit === 'function' ? handler.exit : null,
keys: normalizedKeys
};
} else if (typeof handler === 'function') {
normalizedVisitor[type] = {
enter: handler,
exit: null,
keys: normalizedKeys
};
}
}
return normalizedVisitor;
}
function Walker() {
var order = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
this.order = order;
this.stack = [];
}
Walker.prototype.visit = function (node, callback) {
if (!node) {
return;
}
this.stack.push(node);
if (this.order === 'post') {
this.children(node, callback);
callback(node, this);
} else {
callback(node, this);
this.children(node, callback);
}
this.stack.pop();
};
var visitors = {
Program: function (walker, node, callback) {
var i;
for (i = 0; i < node.body.length; i++) {
walker.visit(node.body[i], callback);
}
},
ElementNode: function (walker, node, callback) {
var i;
for (i = 0; i < node.children.length; i++) {
walker.visit(node.children[i], callback);
}
},
BlockStatement: function (walker, node, callback) {
walker.visit(node.program, callback);
walker.visit(node.inverse, callback);
}
};
Walker.prototype.children = function (node, callback) {
var visitor = visitors[node.type];
if (visitor) {
visitor(this, node, callback);
}
};
// Regex to validate the identifier for block parameters.
// Based on the ID validation regex in Handlebars.
var ID_INVERSE_PATTERN = /[!"#%-,\.\/;->@\[-\^`\{-~]/;
// Checks the element's attributes to see if it uses block params.
// If it does, registers the block params with the program and
// removes the corresponding attributes from the element.
function parseElementBlockParams(element) {
var params = parseBlockParams(element);
if (params) element.blockParams = params;
}
function parseBlockParams(element) {
var l = element.attributes.length,
i,
paramsString,
params,
_i,
param;
var attrNames = [];
for (i = 0; i < l; i++) {
attrNames.push(element.attributes[i].name);
}
var asIndex = attrNames.indexOf('as');
if (asIndex !== -1 && l > asIndex && attrNames[asIndex + 1].charAt(0) === '|') {
// Some basic validation, since we're doing the parsing ourselves
paramsString = attrNames.slice(asIndex).join(' ');
if (paramsString.charAt(paramsString.length - 1) !== '|' || paramsString.match(/\|/g).length !== 2) {
throw new Error('Invalid block parameters syntax: \'' + paramsString + '\'');
}
params = [];
for (_i = asIndex + 1; _i < l; _i++) {
param = attrNames[_i].replace(/\|/g, '');
if (param !== '') {
if (ID_INVERSE_PATTERN.test(param)) {
throw new Error('Invalid identifier for block parameters: \'' + param + '\' in \'' + paramsString + '\'');
}
params.push(param);
}
}
if (params.length === 0) {
throw new Error('Cannot use zero block parameters: \'' + paramsString + '\'');
}
element.attributes = element.attributes.slice(0, asIndex);
return params;
}
}
function childrenFor(node) {
if (node.type === 'Program') {
return node.body;
}
if (node.type === 'ElementNode') {
return node.children;
}
}
function appendChild(parent, node) {
childrenFor(parent).push(node);
}
var handlebarsNodeVisitors = {
Program: function (program) {
var node = b.program([], program.blockParams, program.loc);
var i = void 0,
l = program.body.length;
this.elementStack.push(node);
if (l === 0) {
return this.elementStack.pop();
}
for (i = 0; i < l; i++) {
this.acceptNode(program.body[i]);
}
// Ensure that that the element stack is balanced properly.
var poppedNode = this.elementStack.pop();
if (poppedNode !== node) {
throw new Error("Unclosed element `" + poppedNode.tag + "` (on line " + poppedNode.loc.start.line + ").");
}
return node;
},
BlockStatement: function (block) {
delete block.inverseStrip;
delete block.openString;
delete block.closeStrip;
if (this.tokenizer.state === 'comment') {
this.appendToCommentData('{{' + this.sourceForMustache(block) + '}}');
return;
}
if (this.tokenizer.state !== 'comment' && this.tokenizer.state !== 'data' && this.tokenizer.state !== 'beforeData') {
throw new Error("A block may only be used inside an HTML element or another block.");
}
block = acceptCommonNodes(this, block);
var program = block.program ? this.acceptNode(block.program) : null;
var inverse = block.inverse ? this.acceptNode(block.inverse) : null;
var node = b.block(block.path, block.params, block.hash, program, inverse, block.loc);
var parentProgram = this.currentElement();
appendChild(parentProgram, node);
},
MustacheStatement: function (rawMustache) {
var tokenizer = this.tokenizer;
var path = rawMustache.path,
params = rawMustache.params,
hash = rawMustache.hash,
escaped = rawMustache.escaped,
loc = rawMustache.loc;
var mustache = b.mustache(path, params, hash, !escaped, loc);
if (tokenizer.state === 'comment') {
this.appendToCommentData('{{' + this.sourceForMustache(mustache) + '}}');
return;
}
acceptCommonNodes(this, mustache);
switch (tokenizer.state) {
// Tag helpers
case "tagName":
addElementModifier(this.currentNode, mustache);
tokenizer.state = "beforeAttributeName";
break;
case "beforeAttributeName":
addElementModifier(this.currentNode, mustache);
break;
case "attributeName":
case "afterAttributeName":
this.beginAttributeValue(false);
this.finishAttributeValue();
addElementModifier(this.currentNode, mustache);
tokenizer.state = "beforeAttributeName";
break;
case "afterAttributeValueQuoted":
addElementModifier(this.currentNode, mustache);
tokenizer.state = "beforeAttributeName";
break;
// Attribute values
case "beforeAttributeValue":
appendDynamicAttributeValuePart(this.currentAttribute, mustache);
tokenizer.state = 'attributeValueUnquoted';
break;
case "attributeValueDoubleQuoted":
case "attributeValueSingleQuoted":
case "attributeValueUnquoted":
appendDynamicAttributeValuePart(this.currentAttribute, mustache);
break;
// TODO: Only append child when the tokenizer state makes
// sense to do so, otherwise throw an error.
default:
appendChild(this.currentElement(), mustache);
}
return mustache;
},
ContentStatement: function (content) {
updateTokenizerLocation(this.tokenizer, content);
this.tokenizer.tokenizePart(content.value);
this.tokenizer.flushData();
},
CommentStatement: function (rawComment) {
var tokenizer = this.tokenizer;
var value = rawComment.value,
loc = rawComment.loc;
var comment = b.mustacheComment(value, loc);
if (tokenizer.state === 'comment') {
this.appendToCommentData('{{' + this.sourceForMustache(comment) + '}}');
return;
}
switch (tokenizer.state) {
case "beforeAttributeName":
this.currentNode.comments.push(comment);
break;
case 'beforeData':
case 'data':
appendChild(this.currentElement(), comment);
break;
default:
throw new Error('Using a Handlebars comment when in the `' + tokenizer.state + '` state is not supported: "' + comment.value + '" on line ' + loc.start.line + ':' + loc.start.column);
}
return comment;
},
PartialStatement: function (partial) {
var name = partial.name,
loc = partial.loc;
throw new Error('Handlebars partials are not supported: "{{> ' + name.original + '" at L' + loc.start.line + ':C' + loc.start.column);
},
PartialBlockStatement: function (partialBlock) {
var name = partialBlock.name,
loc = partialBlock.loc;
throw new Error('Handlebars partial blocks are not supported: "{{#> ' + name.original + '" at L' + loc.start.line + ':C' + loc.start.column);
},
Decorator: function (decorator) {
var loc = decorator.loc,
path = decorator.path;
this.sourceForMustache(decorator);
throw new Error('Handlebars decorators are not supported: "{{* ' + path.original + '" at L' + loc.start.line + ':C' + loc.start.column);
},
DecoratorBlock: function (decoratorBlock) {
var loc = decoratorBlock.loc,
path = decoratorBlock.path;
this.sourceForMustache(decoratorBlock);
throw new Error('Handlebars decorator blocks are not supported: "{{#* ' + path.original + '" at L' + loc.start.line + ':C' + loc.start.column);
},
SubExpression: function (sexpr) {
return acceptCommonNodes(this, sexpr);
},
PathExpression: function (path) {
var original = path.original,
loc = path.loc;
if (original.indexOf('/') !== -1) {
// TODO add a SyntaxError with loc info
if (original.slice(0, 2) === './') {
throw new Error('Using "./" is not supported in Glimmer and unnecessary: "' + path.original + '" on line ' + loc.start.line + '.');
}
if (original.slice(0, 3) === '../') {
throw new Error('Changing context using "../" is not supported in Glimmer: "' + path.original + '" on line ' + loc.start.line + '.');
}
if (original.indexOf('.') !== -1) {
throw new Error('Mixing \'.\' and \'/\' in paths is not supported in Glimmer; use only \'.\' to separate property paths: "' + path.original + '" on line ' + loc.start.line + '.');
}
path.parts = [path.parts.join('/')];
}
delete path.depth;
// This is to fix a bug in the Handlebars AST where the path expressions in
// `{{this.foo}}` (and similarly `{{foo-bar this.foo named=this.foo}}` etc)
// are simply turned into `{{foo}}`. The fix is to push it back onto the
// parts array and let the runtime see the difference. However, we cannot
// simply use the string `this` as it means literally the property called
// "this" in the current context (it can be expressed in the syntax as
// `{{[this]}}`, where the square bracket are generally for this kind of
// escaping – such as `{{foo.["bar.baz"]}}` would mean lookup a property
// named literally "bar.baz" on `this.foo`). By convention, we use `null`
// for this purpose.
if (original.match(/^this(\..+)?$/)) {
path.parts.unshift(null);
}
return path;
},
Hash: function (hash) {
var i;
for (i = 0; i < hash.pairs.length; i++) {
this.acceptNode(hash.pairs[i].value);
}
return hash;
},
StringLiteral: function () {},
BooleanLiteral: function () {},
NumberLiteral: function () {},
UndefinedLiteral: function () {},
NullLiteral: function () {}
};
function calculateRightStrippedOffsets(original, value) {
if (value === '') {
// if it is empty, just return the count of newlines
// in original
return {
lines: original.split("\n").length - 1,
columns: 0
};
}
// otherwise, return the number of newlines prior to
// `value`
var difference = original.split(value)[0];
var lines = difference.split(/\n/);
var lineCount = lines.length - 1;
return {
lines: lineCount,
columns: lines[lineCount].length
};
}
function updateTokenizerLocation(tokenizer, content) {
var line = content.loc.start.line;
var column = content.loc.start.column;
var offsets = calculateRightStrippedOffsets(content.original, content.value);
line = line + offsets.lines;
if (offsets.lines) {
column = offsets.columns;
} else {
column = column + offsets.columns;
}
tokenizer.line = line;
tokenizer.column = column;
}
function acceptCommonNodes(compiler, node) {
var i;
compiler.acceptNode(node.path);
if (node.params) {
for (i = 0; i < node.params.length; i++) {
compiler.acceptNode(node.params[i]);
}
} else {
node.params = [];
}
if (node.hash) {
compiler.acceptNode(node.hash);
} else {
node.hash = b.hash();
}
return node;
}
function addElementModifier(element, mustache) {
var path = mustache.path,
params = mustache.params,
hash = mustache.hash,
loc = mustache.loc;
var modifier = b.elementModifier(path, params, hash, loc);
element.modifiers.push(modifier);
}
function appendDynamicAttributeValuePart(attribute, part) {
attribute.isDynamic = true;
attribute.parts.push(part);
}
var voidMap = Object.create(null);
"area base br col command embed hr img input keygen link meta param source track wbr".split(" ").forEach(function (tagName) {
voidMap[tagName] = true;
});
var tokenizerEventHandlers = {
reset: function () {
this.currentNode = null;
},
// Comment
beginComment: function () {
this.currentNode = b.comment("");
this.currentNode.loc = {
source: null,
start: b.pos(this.tagOpenLine, this.tagOpenColumn),
end: null
};
},
appendToCommentData: function (char) {
this.currentNode.value += char;
},
finishComment: function () {
this.currentNode.loc.end = b.pos(this.tokenizer.line, this.tokenizer.column);
appendChild(this.currentElement(), this.currentNode);
},
// Data
beginData: function () {
this.currentNode = b.text();
this.currentNode.loc = {
source: null,
start: b.pos(this.tokenizer.line, this.tokenizer.column),
end: null
};
},
appendToData: function (char) {
this.currentNode.chars += char;
},
finishData: function () {
this.currentNode.loc.end = b.pos(this.tokenizer.line, this.tokenizer.column);
appendChild(this.currentElement(), this.currentNode);
},
// Tags - basic
tagOpen: function () {
this.tagOpenLine = this.tokenizer.line;
this.tagOpenColumn = this.tokenizer.column;
},
beginStartTag: function () {
this.currentNode = {
type: 'StartTag',
name: "",
attributes: [],
modifiers: [],
comments: [],
selfClosing: false,
loc: null
};
},
beginEndTag: function () {
this.currentNode = {
type: 'EndTag',
name: "",
attributes: [],
modifiers: [],
comments: [],
selfClosing: false,
loc: null
};
},
finishTag: function () {
var _tokenizer = this.tokenizer,
line = _tokenizer.line,
column = _tokenizer.column;
var tag = this.currentNode;
tag.loc = b.loc(this.tagOpenLine, this.tagOpenColumn, line, column);
if (tag.type === 'StartTag') {
this.finishStartTag();
if (voidMap[tag.name] || tag.selfClosing) {
this.finishEndTag(true);
}
} else if (tag.type === 'EndTag') {
this.finishEndTag(false);
}
},
finishStartTag: function () {
var _currentNode = this.currentNode,
name = _currentNode.name,
attributes = _currentNode.attributes,
modifiers = _currentNode.modifiers,
comments = _currentNode.comments;
var loc = b.loc(this.tagOpenLine, this.tagOpenColumn);
var element = b.element(name, attributes, modifiers, [], comments, loc);
this.elementStack.push(element);
},
finishEndTag: function (isVoid) {
var tag = this.currentNode;
var element = this.elementStack.pop();
var parent = this.currentElement();
validateEndTag(tag, element, isVoid);
element.loc.end.line = this.tokenizer.line;
element.loc.end.column = this.tokenizer.column;
parseElementBlockParams(element);
appendChild(parent, element);
},
markTagAsSelfClosing: function () {
this.currentNode.selfClosing = true;
},
// Tags - name
appendToTagName: function (char) {
this.currentNode.name += char;
},
// Tags - attributes
beginAttribute: function () {
var tag = this.currentNode;
if (tag.type === 'EndTag') {
throw new Error('Invalid end tag: closing tag must not have attributes, ' + ('in `' + tag.name + '` (on line ' + this.tokenizer.line + ').'));
}
this.currentAttribute = {
name: "",
parts: [],
isQuoted: false,
isDynamic: false,
start: b.pos(this.tokenizer.line, this.tokenizer.column),
valueStartLine: null,
valueStartColumn: null
};
},
appendToAttributeName: function (char) {
this.currentAttribute.name += char;
},
beginAttributeValue: function (isQuoted) {
this.currentAttribute.isQuoted = isQuoted;
this.currentAttribute.valueStartLine = this.tokenizer.line;
this.currentAttribute.valueStartColumn = this.tokenizer.column;
},
appendToAttributeValue: function (char) {
var parts = this.currentAttribute.parts,
loc,
text;
var lastPart = parts[parts.length - 1];
if (lastPart && lastPart.type === 'TextNode') {
lastPart.chars += char;
// update end location for each added char
lastPart.loc.end.line = this.tokenizer.line;
lastPart.loc.end.column = this.tokenizer.column;
} else {
// initially assume the text node is a single char
loc = b.loc(this.tokenizer.line, this.tokenizer.column, this.tokenizer.line, this.tokenizer.column);
// correct for `\n` as first char
if (char === '\n') {
loc.start.line -= 1;
loc.start.column = lastPart ? lastPart.loc.end.column : this.currentAttribute.valueStartColumn;
}
text = b.text(char, loc);
parts.push(text);
}
},
finishAttributeValue: function () {
var _currentAttribute = this.currentAttribute,
name = _currentAttribute.name,
parts = _currentAttribute.parts,
isQuoted = _currentAttribute.isQuoted,
isDynamic = _currentAttribute.isDynamic,
valueStartLine = _currentAttribute.valueStartLine,
valueStartColumn = _currentAttribute.valueStartColumn;
var value = assembleAttributeValue(parts, isQuoted, isDynamic, this.tokenizer.line);
value.loc = b.loc(valueStartLine, valueStartColumn, this.tokenizer.line, this.tokenizer.column);
var loc = b.loc(this.currentAttribute.start.line, this.currentAttribute.start.column, this.tokenizer.line, this.tokenizer.column);
var attribute = b.attr(name, value, loc);
this.currentNode.attributes.push(attribute);
},
reportSyntaxError: function (message) {
throw new Error('Syntax error at line ' + this.tokenizer.line + ' col ' + this.tokenizer.column + ': ' + message);
}
};
function assembleAttributeValue(parts, isQuoted, isDynamic, line) {
if (isDynamic) {
if (isQuoted) {
return assembleConcatenatedValue(parts);
} else {
if (parts.length === 1 || parts.length === 2 && parts[1].chars === '/') {
return parts[0];
} else {
throw new Error('An unquoted attribute value must be a string or a mustache, ' + 'preceeded by whitespace or a \'=\' character, and ' + ('followed by whitespace, a \'>\' character, or \'/>\' (on line ' + line + ')'));
}
}
} else {
return parts.length > 0 ? parts[0] : b.text("");
}
}
function assembleConcatenatedValue(parts) {
var i, part;
for (i = 0; i < parts.length; i++) {
part = parts[i];
if (part.type !== 'MustacheStatement' && part.type !== 'TextNode') {
throw new Error("Unsupported node in quoted attribute value: " + part.type);
}
}
return b.concat(parts);
}
function validateEndTag(tag, element, selfClosing) {
var error = void 0;
if (voidMap[tag.name] && !selfClosing) {
// EngTag is also called by StartTag for void and self-closing tags (i.e.
// or , so we need to check for that here. Otherwise, we would
// throw an error for those cases.
error = "Invalid end tag " + formatEndTagInfo(tag) + " (void elements cannot have end tags).";
} else if (element.tag === undefined) {
error = "Closing tag " + formatEndTagInfo(tag) + " without an open tag.";
} else if (element.tag !== tag.name) {
error = "Closing tag " + formatEndTagInfo(tag) + " did not match last open tag `" + element.tag + "` (on line " + element.loc.start.line + ").";
}
if (error) {
throw new Error(error);
}
}
function formatEndTagInfo(tag) {
return "`" + tag.name + "` (on line " + tag.loc.end.line + ")";
}
var syntax = {
parse: preprocess,
builders: b,
print: build,
traverse: traverse,
Walker: Walker
};
function preprocess(html, options) {
var ast = typeof html === 'object' ? html : (0, _handlebars.parse)(html),
i,
l,
plugin;
var combined = new Parser(html, options).acceptNode(ast);
if (options && options.plugins && options.plugins.ast) {
for (i = 0, l = options.plugins.ast.length; i < l; i++) {
plugin = new options.plugins.ast[i](options);
plugin.syntax = syntax;
combined = plugin.transform(combined);
}
}
return combined;
}
var entityParser = new _simpleHtmlTokenizer.EntityParser(_simpleHtmlTokenizer.HTML5NamedCharRefs);
var Parser = function () {
function Parser(source) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
this.elementStack = [];
this.currentAttribute = null;
this.currentNode = null;
this.tokenizer = new _simpleHtmlTokenizer.EventedTokenizer(this, entityParser);
this.options = options;
if (typeof source === 'string') {
this.source = source.split(/(?:\r\n?|\n)/g);
}
}
Parser.prototype.acceptNode = function (node) {
return this[node.type](node);
};
Parser.prototype.currentElement = function () {
return this.elementStack[this.elementStack.length - 1];
};
Parser.prototype.sourceForMustache = function (mustache) {
var firstLine = mustache.loc.start.line - 1;
var lastLine = mustache.loc.end.line - 1;
var currentLine = firstLine - 1;
var firstColumn = mustache.loc.start.column + 2;
var lastColumn = mustache.loc.end.column - 2;
var string = [];
var line = void 0;
if (!this.source) {
return '{{' + mustache.path.id.original + '}}';
}
while (currentLine < lastLine) {
currentLine++;
line = this.source[currentLine];
if (currentLine === firstLine) {
if (firstLine === lastLine) {
string.push(line.slice(firstColumn, lastColumn));
} else {
string.push(line.slice(firstColumn));
}
} else if (currentLine === lastLine) {
string.push(line.slice(0, lastColumn));
} else {
string.push(line);
}
}
return string.join('\n');
};
return Parser;
}();
for (var key in handlebarsNodeVisitors) {
Parser.prototype[key] = handlebarsNodeVisitors[key];
}
for (var _key2 in tokenizerEventHandlers) {
Parser.prototype[_key2] = tokenizerEventHandlers[_key2];
}
// used by ember-compiler
exports.preprocess = preprocess;
exports.builders = b;
exports.traverse = traverse;
exports.Walker = Walker;
exports.print = build;
});
enifed('@glimmer/util', ['exports'], function (exports) {
'use strict';
exports.unreachable = exports.expect = exports.unwrap = exports.HAS_NATIVE_WEAKMAP = exports.A = exports.ListSlice = exports.ListNode = exports.LinkedList = exports.EMPTY_SLICE = exports.dict = exports.DictSet = exports.Stack = exports.initializeGuid = exports.ensureGuid = exports.fillNulls = exports.assign = exports.LogLevel = exports.Logger = exports.LOGGER = exports.assert = exports.getAttrNamespace = undefined;
// There is a small whitelist of namespaced attributes specially
// enumerated in
// https://www.w3.org/TR/html/syntax.html#attributes-0
//
// > When a foreign element has one of the namespaced attributes given by
// > the local name and namespace of the first and second cells of a row
// > from the following table, it must be written using the name given by
// > the third cell from the same row.
//
// In all other cases, colons are interpreted as a regular character
// with no special meaning:
//
// > No other namespaced attribute can be expressed in the HTML syntax.
var XLINK = 'http://www.w3.org/1999/xlink';
var XML = 'http://www.w3.org/XML/1998/namespace';
var XMLNS = 'http://www.w3.org/2000/xmlns/';
var WHITELIST = {
'xlink:actuate': XLINK,
'xlink:arcrole': XLINK,
'xlink:href': XLINK,
'xlink:role': XLINK,
'xlink:show': XLINK,
'xlink:title': XLINK,
'xlink:type': XLINK,
'xml:base': XML,
'xml:lang': XML,
'xml:space': XML,
'xmlns': XMLNS,
'xmlns:xlink': XMLNS
};
// tslint:disable-line
// import Logger from './logger';
// let alreadyWarned = false;
// import Logger from './logger';
var LogLevel;
(function (LogLevel) {
LogLevel[LogLevel["Trace"] = 0] = "Trace";
LogLevel[LogLevel["Debug"] = 1] = "Debug";
LogLevel[LogLevel["Warn"] = 2] = "Warn";
LogLevel[LogLevel["Error"] = 3] = "Error";
})(LogLevel || (exports.LogLevel = LogLevel = {}));
var NullConsole = function () {
function NullConsole() {}
NullConsole.prototype.log = function () {};
NullConsole.prototype.warn = function () {};
NullConsole.prototype.error = function () {};
NullConsole.prototype.trace = function () {};
return NullConsole;
}();
var ALWAYS = void 0;
var Logger = function () {
function Logger(_ref) {
var console = _ref.console,
level = _ref.level;
this.f = ALWAYS;
this.force = ALWAYS;
this.console = console;
this.level = level;
}
Logger.prototype.skipped = function (level) {
return level < this.level;
};
Logger.prototype.trace = function (message) {
var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref2$stackTrace = _ref2.stackTrace,
stackTrace = _ref2$stackTrace === undefined ? false : _ref2$stackTrace;
if (this.skipped(LogLevel.Trace)) return;
this.console.log(message);
if (stackTrace) this.console.trace();
};
Logger.prototype.debug = function (message) {
var _ref3 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref3$stackTrace = _ref3.stackTrace,
stackTrace = _ref3$stackTrace === undefined ? false : _ref3$stackTrace;
if (this.skipped(LogLevel.Debug)) return;
this.console.log(message);
if (stackTrace) this.console.trace();
};
Logger.prototype.warn = function (message) {
var _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref4$stackTrace = _ref4.stackTrace,
stackTrace = _ref4$stackTrace === undefined ? false : _ref4$stackTrace;
if (this.skipped(LogLevel.Warn)) return;
this.console.warn(message);
if (stackTrace) this.console.trace();
};
Logger.prototype.error = function (message) {
if (this.skipped(LogLevel.Error)) return;
this.console.error(message);
};
return Logger;
}();
var _console = typeof console === 'undefined' ? new NullConsole() : console;
ALWAYS = new Logger({ console: _console, level: LogLevel.Trace });
var LOG_LEVEL = LogLevel.Warn;
var logger = new Logger({ console: _console, level: LOG_LEVEL });
var objKeys = Object.keys;
var GUID = 0;
function initializeGuid(object) {
return object._guid = ++GUID;
}
function ensureGuid(object) {
return object._guid || initializeGuid(object);
}
var proto = Object.create(null, {
// without this, we will always still end up with (new
// EmptyObject()).constructor === Object
constructor: {
value: undefined,
enumerable: false,
writable: true
}
});
function EmptyObject() {}
EmptyObject.prototype = proto;
function dict() {
// let d = Object.create(null);
// d.x = 1;
// delete d.x;
// return d;
return new EmptyObject();
}
var DictSet = function () {
function DictSet() {
this.dict = dict();
}
DictSet.prototype.add = function (obj) {
if (typeof obj === 'string') this.dict[obj] = obj;else this.dict[ensureGuid(obj)] = obj;
return this;
};
DictSet.prototype.delete = function (obj) {
if (typeof obj === 'string') delete this.dict[obj];else if (obj._guid) delete this.dict[obj._guid];
};
DictSet.prototype.forEach = function (callback) {
var dict = this.dict;
Object.keys(dict).forEach(function (key) {
return callback(dict[key]);
});
};
DictSet.prototype.toArray = function () {
return Object.keys(this.dict);
};
return DictSet;
}();
var Stack = function () {
function Stack() {
this.stack = [];
this.current = null;
}
Stack.prototype.toArray = function () {
return this.stack;
};
Stack.prototype.push = function (item) {
this.current = item;
this.stack.push(item);
};
Stack.prototype.pop = function () {
var item = this.stack.pop();
var len = this.stack.length;
this.current = len === 0 ? null : this.stack[len - 1];
return item === undefined ? null : item;
};
Stack.prototype.isEmpty = function () {
return this.stack.length === 0;
};
return Stack;
}();
var LinkedList = function () {
function LinkedList() {
this.clear();
}
LinkedList.fromSlice = function (slice) {
var list = new LinkedList();
slice.forEachNode(function (n) {
return list.append(n.clone());
});
return list;
};
LinkedList.prototype.head = function () {
return this._head;
};
LinkedList.prototype.tail = function () {
return this._tail;
};
LinkedList.prototype.clear = function () {
this._head = this._tail = null;
};
LinkedList.prototype.isEmpty = function () {
return this._head === null;
};
LinkedList.prototype.toArray = function () {
var out = [];
this.forEachNode(function (n) {
return out.push(n);
});
return out;
};
LinkedList.prototype.splice = function (start, end, reference) {
var before = void 0;
if (reference === null) {
before = this._tail;
this._tail = end;
} else {
before = reference.prev;
end.next = reference;
reference.prev = end;
}
if (before) {
before.next = start;
start.prev = before;
}
};
LinkedList.prototype.nextNode = function (node) {
return node.next;
};
LinkedList.prototype.prevNode = function (node) {
return node.prev;
};
LinkedList.prototype.forEachNode = function (callback) {
var node = this._head;
while (node !== null) {
callback(node);
node = node.next;
}
};
LinkedList.prototype.contains = function (needle) {
var node = this._head;
while (node !== null) {
if (node === needle) return true;
node = node.next;
}
return false;
};
LinkedList.prototype.insertBefore = function (node) {
var reference = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
if (reference === null) return this.append(node);
if (reference.prev) reference.prev.next = node;else this._head = node;
node.prev = reference.prev;
node.next = reference;
reference.prev = node;
return node;
};
LinkedList.prototype.append = function (node) {
var tail = this._tail;
if (tail) {
tail.next = node;
node.prev = tail;
node.next = null;
} else {
this._head = node;
}
return this._tail = node;
};
LinkedList.prototype.pop = function () {
if (this._tail) return this.remove(this._tail);
return null;
};
LinkedList.prototype.prepend = function (node) {
if (this._head) return this.insertBefore(node, this._head);
return this._head = this._tail = node;
};
LinkedList.prototype.remove = function (node) {
if (node.prev) node.prev.next = node.next;else this._head = node.next;
if (node.next) node.next.prev = node.prev;else this._tail = node.prev;
return node;
};
return LinkedList;
}();
var ListSlice = function () {
function ListSlice(head, tail) {
this._head = head;
this._tail = tail;
}
ListSlice.toList = function (slice) {
var list = new LinkedList();
slice.forEachNode(function (n) {
return list.append(n.clone());
});
return list;
};
ListSlice.prototype.forEachNode = function (callback) {
var node = this._head;
while (node !== null) {
callback(node);
node = this.nextNode(node);
}
};
ListSlice.prototype.contains = function (needle) {
var node = this._head;
while (node !== null) {
if (node === needle) return true;
node = node.next;
}
return false;
};
ListSlice.prototype.head = function () {
return this._head;
};
ListSlice.prototype.tail = function () {
return this._tail;
};
ListSlice.prototype.toArray = function () {
var out = [];
this.forEachNode(function (n) {
return out.push(n);
});
return out;
};
ListSlice.prototype.nextNode = function (node) {
if (node === this._tail) return null;
return node.next;
};
ListSlice.prototype.prevNode = function (node) {
if (node === this._head) return null;
return node.prev;
};
ListSlice.prototype.isEmpty = function () {
return false;
};
return ListSlice;
}();
var EMPTY_SLICE = new ListSlice(null, null);
var HAS_TYPED_ARRAYS = typeof Uint32Array !== 'undefined';
var A = void 0;
if (HAS_TYPED_ARRAYS) {
A = Uint32Array;
} else {
A = Array;
}
var A$1 = A;
var HAS_NATIVE_WEAKMAP = function () {
// detect if `WeakMap` is even present
var hasWeakMap = typeof WeakMap === 'function';
if (!hasWeakMap) {
return false;
}
var instance = new WeakMap();
// use `Object`'s `.toString` directly to prevent us from detecting
// polyfills as native weakmaps
return Object.prototype.toString.call(instance) === '[object WeakMap]';
}();
exports.getAttrNamespace = function (attrName) {
return WHITELIST[attrName] || null;
};
exports.assert = function (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");
}
};
exports.LOGGER = logger;
exports.Logger = Logger;
exports.LogLevel = LogLevel;
exports.assign = function (obj) {
var i, assignment, keys, j, key;
for (i = 1; i < arguments.length; i++) {
assignment = arguments[i];
if (assignment === null || typeof assignment !== 'object') continue;
keys = objKeys(assignment);
for (j = 0; j < keys.length; j++) {
key = keys[j];
obj[key] = assignment[key];
}
}
return obj;
};
exports.fillNulls = function (count) {
var arr = new Array(count),
i;
for (i = 0; i < count; i++) {
arr[i] = null;
}
return arr;
};
exports.ensureGuid = ensureGuid;
exports.initializeGuid = initializeGuid;
exports.Stack = Stack;
exports.DictSet = DictSet;
exports.dict = dict;
exports.EMPTY_SLICE = EMPTY_SLICE;
exports.LinkedList = LinkedList;
exports.ListNode = function (value) {
this.next = null;
this.prev = null;
this.value = value;
};
exports.ListSlice = ListSlice;
exports.A = A$1;
exports.HAS_NATIVE_WEAKMAP = HAS_NATIVE_WEAKMAP;
exports.unwrap = function (val) {
if (val === null || val === undefined) throw new Error('Expected value to be present');
return val;
};
exports.expect = function (val, message) {
if (val === null || val === undefined) throw new Error(message);
return val;
};
exports.unreachable = function () {
return new Error('unreachable');
};
});
enifed("@glimmer/wire-format", ["exports"], function (exports) {
"use strict";
var Opcodes;
(function (Opcodes) {
// Statements
Opcodes[Opcodes["Text"] = 0] = "Text";
Opcodes[Opcodes["Append"] = 1] = "Append";
Opcodes[Opcodes["UnoptimizedAppend"] = 2] = "UnoptimizedAppend";
Opcodes[Opcodes["OptimizedAppend"] = 3] = "OptimizedAppend";
Opcodes[Opcodes["Comment"] = 4] = "Comment";
Opcodes[Opcodes["Modifier"] = 5] = "Modifier";
Opcodes[Opcodes["Block"] = 6] = "Block";
Opcodes[Opcodes["ScannedBlock"] = 7] = "ScannedBlock";
Opcodes[Opcodes["NestedBlock"] = 8] = "NestedBlock";
Opcodes[Opcodes["Component"] = 9] = "Component";
Opcodes[Opcodes["ScannedComponent"] = 10] = "ScannedComponent";
Opcodes[Opcodes["OpenElement"] = 11] = "OpenElement";
Opcodes[Opcodes["OpenPrimitiveElement"] = 12] = "OpenPrimitiveElement";
Opcodes[Opcodes["FlushElement"] = 13] = "FlushElement";
Opcodes[Opcodes["CloseElement"] = 14] = "CloseElement";
Opcodes[Opcodes["StaticAttr"] = 15] = "StaticAttr";
Opcodes[Opcodes["DynamicAttr"] = 16] = "DynamicAttr";
Opcodes[Opcodes["AnyDynamicAttr"] = 17] = "AnyDynamicAttr";
Opcodes[Opcodes["Yield"] = 18] = "Yield";
Opcodes[Opcodes["Partial"] = 19] = "Partial";
Opcodes[Opcodes["StaticPartial"] = 20] = "StaticPartial";
Opcodes[Opcodes["DynamicPartial"] = 21] = "DynamicPartial";
Opcodes[Opcodes["DynamicArg"] = 22] = "DynamicArg";
Opcodes[Opcodes["StaticArg"] = 23] = "StaticArg";
Opcodes[Opcodes["TrustingAttr"] = 24] = "TrustingAttr";
Opcodes[Opcodes["Debugger"] = 25] = "Debugger";
// Expressions
Opcodes[Opcodes["Unknown"] = 26] = "Unknown";
Opcodes[Opcodes["Arg"] = 27] = "Arg";
Opcodes[Opcodes["Get"] = 28] = "Get";
Opcodes[Opcodes["HasBlock"] = 29] = "HasBlock";
Opcodes[Opcodes["HasBlockParams"] = 30] = "HasBlockParams";
Opcodes[Opcodes["Undefined"] = 31] = "Undefined";
Opcodes[Opcodes["Function"] = 32] = "Function";
Opcodes[Opcodes["Helper"] = 33] = "Helper";
Opcodes[Opcodes["Concat"] = 34] = "Concat";
})(Opcodes || (exports.Ops = Opcodes = {}));
function is(variant) {
return function (value) {
return value[0] === variant;
};
}
var Expressions;
(function (Expressions) {
Expressions.isUnknown = is(Opcodes.Unknown);
Expressions.isArg = is(Opcodes.Arg);
Expressions.isGet = is(Opcodes.Get);
Expressions.isConcat = is(Opcodes.Concat);
Expressions.isHelper = is(Opcodes.Helper);
Expressions.isHasBlock = is(Opcodes.HasBlock);
Expressions.isHasBlockParams = is(Opcodes.HasBlockParams);
Expressions.isUndefined = is(Opcodes.Undefined);
Expressions.isPrimitiveValue = function (value) {
if (value === null) {
return true;
}
return typeof value !== 'object';
};
})(Expressions || (exports.Expressions = Expressions = {}));
var Statements;
(function (Statements) {
Statements.isText = is(Opcodes.Text);
Statements.isAppend = is(Opcodes.Append);
Statements.isComment = is(Opcodes.Comment);
Statements.isModifier = is(Opcodes.Modifier);
Statements.isBlock = is(Opcodes.Block);
Statements.isComponent = is(Opcodes.Component);
Statements.isOpenElement = is(Opcodes.OpenElement);
Statements.isFlushElement = is(Opcodes.FlushElement);
Statements.isCloseElement = is(Opcodes.CloseElement);
Statements.isStaticAttr = is(Opcodes.StaticAttr);
Statements.isDynamicAttr = is(Opcodes.DynamicAttr);
Statements.isYield = is(Opcodes.Yield);
Statements.isPartial = is(Opcodes.Partial);
Statements.isDynamicArg = is(Opcodes.DynamicArg);
Statements.isStaticArg = is(Opcodes.StaticArg);
Statements.isTrustingAttr = is(Opcodes.TrustingAttr);
Statements.isDebugger = is(Opcodes.Debugger);
function isAttribute(val) {
return val[0] === Opcodes.StaticAttr || val[0] === Opcodes.DynamicAttr;
}
Statements.isAttribute = isAttribute;
function isArgument(val) {
return val[0] === Opcodes.StaticArg || val[0] === Opcodes.DynamicArg;
}
Statements.isArgument = isArgument;
Statements.isParameter = function (val) {
return isAttribute(val) || isArgument(val);
};
Statements.getParameterName = function (s) {
return s[1];
};
})(Statements || (exports.Statements = Statements = {}));
exports.is = is;
exports.Expressions = Expressions;
exports.Statements = Statements;
exports.Ops = Opcodes;
});
enifed('backburner', ['exports'], function (exports) {
'use strict';
var NUMBER = /\d+/;
var now = Date.now;
function each(collection, callback) {
var i;
for (i = 0; i < collection.length; i++) {
callback(collection[i]);
}
}
function isString(suspect) {
return typeof suspect === 'string';
}
function isFunction(suspect) {
return typeof suspect === 'function';
}
function isNumber(suspect) {
return typeof suspect === 'number';
}
function isCoercableNumber(suspect) {
return isNumber(suspect) || NUMBER.test(suspect);
}
function noSuchQueue(name) {
throw new Error('You attempted to schedule an action in a queue (' + name + ') that doesn\'t exist');
}
function noSuchMethod(name) {
throw new Error('You attempted to schedule an action in a queue (' + name + ') for a method that doesn\'t exist');
}
function getOnError(options) {
return options.onError || options.onErrorTarget && options.onErrorTarget[options.onErrorMethod];
}
function findDebouncee(target, method, debouncees) {
return findItem(target, method, debouncees);
}
function findThrottler(target, method, throttlers) {
return findItem(target, method, throttlers);
}
function findItem(target, method, collection) {
var item = void 0,
i,
l;
var index = -1;
for (i = 0, l = collection.length; i < l; i++) {
item = collection[i];
if (item[0] === target && item[1] === method) {
index = i;
break;
}
}
return index;
}
function binarySearch(time, timers) {
var start = 0;
var end = timers.length - 2;
var middle = void 0;
var l = void 0;
while (start < end) {
// since timers is an array of pairs 'l' will always
// be an integer
l = (end - start) / 2;
// compensate for the index in case even number
// of pairs inside timers
middle = start + l - l % 2;
if (time >= timers[middle]) {
start = middle + 2;
} else {
end = middle;
}
}
return time >= timers[start] ? start + 2 : start;
}
var Queue = function () {
function Queue(name, options, globalOptions) {
this.name = name;
this.globalOptions = globalOptions || {};
this.options = options;
this._queue = [];
this.targetQueues = {};
this._queueBeingFlushed = undefined;
}
Queue.prototype.push = function (target, method, args, stack) {
var queue = this._queue;
queue.push(target, method, args, stack);
return {
queue: this,
target: target,
method: method
};
};
Queue.prototype.pushUnique = function (target, method, args, stack) {
var KEY = this.globalOptions.GUID_KEY,
guid;
if (target && KEY) {
guid = target[KEY];
if (guid) {
return this.pushUniqueWithGuid(guid, target, method, args, stack);
}
}
this.pushUniqueWithoutGuid(target, method, args, stack);
return {
queue: this,
target: target,
method: method
};
};
Queue.prototype.flush = function (sync) {
var queue = this._queue,
i;
var length = queue.length;
if (length === 0) {
return;
}
var globalOptions = this.globalOptions;
var options = this.options;
var before = options && options.before;
var after = options && options.after;
var onError = globalOptions.onError || globalOptions.onErrorTarget && globalOptions.onErrorTarget[globalOptions.onErrorMethod];
var target = void 0;
var method = void 0;
var args = void 0;
var errorRecordedForStack = void 0;
var invoke = onError ? this.invokeWithOnError : this.invoke;
this.targetQueues = Object.create(null);
var queueItems = this._queueBeingFlushed = this._queue;
this._queue = [];
if (before) {
before();
}
for (i = 0; i < length; i += 4) {
target = queueItems[i];
method = queueItems[i + 1];
args = queueItems[i + 2];
errorRecordedForStack = queueItems[i + 3]; // Debugging assistance
if (isString(method)) {
method = target[method];
}
// method could have been nullified / canceled during flush
if (method) {
//
// ** 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
//
invoke(target, method, args, onError, errorRecordedForStack);
}
}
if (after) {
after();
}
this._queueBeingFlushed = undefined;
if (sync !== false && this._queue.length > 0) {
// check if new items have been added
this.flush(true);
}
};
Queue.prototype.cancel = function (actionToCancel) {
var queue = this._queue,
targetQueue;
var currentTarget = void 0;
var currentMethod = void 0;
var i = void 0;
var l = void 0;
var target = actionToCancel.target,
method = actionToCancel.method;
var GUID_KEY = this.globalOptions.GUID_KEY;
if (GUID_KEY && this.targetQueues && target) {
targetQueue = this.targetQueues[target[GUID_KEY]];
if (targetQueue) {
for (i = 0, l = targetQueue.length; i < l; i++) {
if (targetQueue[i] === method) {
targetQueue.splice(i, 1);
}
}
}
}
for (i = 0, l = queue.length; i < l; i += 4) {
currentTarget = queue[i];
currentMethod = queue[i + 1];
if (currentTarget === target && currentMethod === method) {
queue.splice(i, 4);
return true;
}
}
// if not found in current queue
// could be in the queue that is being flushed
queue = this._queueBeingFlushed;
if (!queue) {
return;
}
for (i = 0, l = queue.length; i < l; i += 4) {
currentTarget = queue[i];
currentMethod = queue[i + 1];
if (currentTarget === target && currentMethod === method) {
// don't mess with array during flush
// just nullify the method
queue[i + 1] = null;
return true;
}
}
};
Queue.prototype.pushUniqueWithoutGuid = function (target, method, args, stack) {
var queue = this._queue,
i,
l,
currentTarget,
currentMethod;
for (i = 0, l = queue.length; i < l; i += 4) {
currentTarget = queue[i];
currentMethod = queue[i + 1];
if (currentTarget === target && currentMethod === method) {
queue[i + 2] = args; // replace args
queue[i + 3] = stack; // replace stack
return;
}
}
queue.push(target, method, args, stack);
};
Queue.prototype.targetQueue = function (_targetQueue, target, method, args, stack) {
var queue = this._queue,
i,
l,
currentMethod,
currentIndex;
for (i = 0, l = _targetQueue.length; i < l; i += 2) {
currentMethod = _targetQueue[i];
currentIndex = _targetQueue[i + 1];
if (currentMethod === method) {
queue[currentIndex + 2] = args; // replace args
queue[currentIndex + 3] = stack; // replace stack
return;
}
}
_targetQueue.push(method, queue.push(target, method, args, stack) - 4);
};
Queue.prototype.pushUniqueWithGuid = function (guid, target, method, args, stack) {
var hasLocalQueue = this.targetQueues[guid];
if (hasLocalQueue) {
this.targetQueue(hasLocalQueue, target, method, args, stack);
} else {
this.targetQueues[guid] = [method, this._queue.push(target, method, args, stack) - 4];
}
return {
queue: this,
target: target,
method: method
};
};
Queue.prototype.invoke = function (target, method, args /*, onError, errorRecordedForStack */) {
if (args && args.length > 0) {
method.apply(target, args);
} else {
method.call(target);
}
};
Queue.prototype.invokeWithOnError = function (target, method, args, onError, errorRecordedForStack) {
try {
if (args && args.length > 0) {
method.apply(target, args);
} else {
method.call(target);
}
} catch (error) {
onError(error, errorRecordedForStack);
}
};
return Queue;
}();
var DeferredActionQueues = function () {
function DeferredActionQueues(queueNames, options) {
var queues = this.queues = {};
this.queueNames = queueNames = queueNames || [];
this.options = options;
each(queueNames, function (queueName) {
queues[queueName] = new Queue(queueName, options[queueName], options);
});
}
DeferredActionQueues.prototype.schedule = function (name, target, method, args, onceFlag, stack) {
var queues = this.queues;
var queue = queues[name];
if (!queue) {
noSuchQueue(name);
}
if (!method) {
noSuchMethod(name);
}
if (onceFlag) {
return queue.pushUnique(target, method, args, stack);
} else {
return queue.push(target, method, args, stack);
}
};
DeferredActionQueues.prototype.flush = function () {
var queue = void 0;
var queueName = void 0;
var queueNameIndex = 0;
var numberOfQueues = this.queueNames.length;
while (queueNameIndex < numberOfQueues) {
queueName = this.queueNames[queueNameIndex];
queue = this.queues[queueName];
if (queue._queue.length === 0) {
queueNameIndex++;
} else {
queue.flush(false /* async */);
queueNameIndex = 0;
}
}
};
return DeferredActionQueues;
}();
var Backburner = function () {
function Backburner(queueNames, options) {
var _this = this;
this.DEBUG = false;
this._autorun = null;
this.queueNames = queueNames;
this.options = options || {};
if (!this.options.defaultQueue) {
this.options.defaultQueue = queueNames[0];
}
this.currentInstance = null;
this.instanceStack = [];
this._debouncees = [];
this._throttlers = [];
this._eventCallbacks = {
end: [],
begin: []
};
this._boundClearItems = function (item) {
_this._platform.clearTimeout(item[2]);
};
this._timerTimeoutId = undefined;
this._timers = [];
this._platform = this.options._platform || {
setTimeout: function (fn, ms) {
return setTimeout(fn, ms);
},
clearTimeout: function (id) {
clearTimeout(id);
}
};
this._boundRunExpiredTimers = function () {
_this._runExpiredTimers();
};
this._boundAutorunEnd = function () {
_this._autorun = null;
_this.end();
};
}
Backburner.prototype.begin = function () {
var options = this.options;
var onBegin = options && options.onBegin;
var previousInstance = this.currentInstance;
if (previousInstance) {
this.instanceStack.push(previousInstance);
}
var current = this.currentInstance = new DeferredActionQueues(this.queueNames, options);
this._trigger('begin', current, previousInstance);
if (onBegin) {
onBegin(current, previousInstance);
}
return current;
};
Backburner.prototype.end = function () {
var options = this.options;
var onEnd = options && options.onEnd;
var currentInstance = this.currentInstance;
var nextInstance = null;
if (!currentInstance) {
throw new Error('end called without begin');
}
// Prevent double-finally bug in Safari 6.0.2 and iOS 6
// This bug appears to be resolved in Safari 6.0.5 and iOS 7
var finallyAlreadyCalled = false;
try {
currentInstance.flush();
} finally {
if (!finallyAlreadyCalled) {
finallyAlreadyCalled = true;
this.currentInstance = null;
if (this.instanceStack.length) {
nextInstance = this.instanceStack.pop();
this.currentInstance = nextInstance;
}
this._trigger('end', currentInstance, nextInstance);
if (onEnd) {
onEnd(currentInstance, nextInstance);
}
}
}
};
Backburner.prototype.on = function (eventName, callback) {
if (typeof callback !== 'function') {
throw new TypeError('Callback must be a function');
}
var callbacks = this._eventCallbacks[eventName];
if (callbacks) {
callbacks.push(callback);
} else {
throw new TypeError('Cannot on() event ' + eventName + ' because it does not exist');
}
};
Backburner.prototype.off = function (eventName, callback) {
var callbacks, callbackFound, i;
if (eventName) {
callbacks = this._eventCallbacks[eventName];
callbackFound = false;
if (!callbacks) {
return;
}
if (callback) {
for (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');
}
} else {
throw new TypeError('Cannot off() event ' + eventName + ' because it does not exist');
}
};
Backburner.prototype.run = function (target, method) {
for (_len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
var length = arguments.length,
_len,
args,
_key;
var _method = void 0;
var _target = void 0;
if (length === 1) {
_method = target;
_target = null;
} else {
_target = target;
_method = method;
}
if (isString(_method)) {
_method = _target[_method];
}
var onError = getOnError(this.options);
this.begin();
if (onError) {
try {
return _method.apply(_target, args);
} catch (error) {
onError(error);
} finally {
this.end();
}
} else {
try {
return _method.apply(_target, args);
} finally {
this.end();
}
}
};
Backburner.prototype.join = function () {
if (!this.currentInstance) {
return this.run.apply(this, arguments);
}
var length = arguments.length,
args,
i;
var method = void 0;
var target = void 0;
if (length === 1) {
method = arguments[0];
target = null;
} else {
target = arguments[0];
method = arguments[1];
}
if (isString(method)) {
method = target[method];
}
if (length === 1) {
return method();
} else if (length === 2) {
return method.call(target);
} else {
args = new Array(length - 2);
for (i = 0; i < length - 2; i++) {
args[i] = arguments[i + 2];
}
return method.apply(target, args);
}
};
Backburner.prototype.defer = function (queueName /* , target, method, args */) {
var length = arguments.length,
i;
var method = void 0;
var target = void 0;
var args = void 0;
if (length === 2) {
method = arguments[1];
target = null;
} else {
target = arguments[1];
method = arguments[2];
}
if (isString(method)) {
method = target[method];
}
var stack = this.DEBUG ? new Error() : undefined;
if (length > 3) {
args = new Array(length - 3);
for (i = 3; i < length; i++) {
args[i - 3] = arguments[i];
}
} else {
args = undefined;
}
return this._ensureInstance().schedule(queueName, target, method, args, false, stack);
};
Backburner.prototype.deferOnce = function (queueName /* , target, method, args */) {
var length = arguments.length,
i;
var method = void 0;
var target = void 0;
var args = void 0;
if (length === 2) {
method = arguments[1];
target = null;
} else {
target = arguments[1];
method = arguments[2];
}
if (isString(method)) {
method = target[method];
}
var stack = this.DEBUG ? new Error() : undefined;
if (length > 3) {
args = new Array(length - 3);
for (i = 3; i < length; i++) {
args[i - 3] = arguments[i];
}
} else {
args = undefined;
}
var currentInstance = this._ensureInstance();
return currentInstance.schedule(queueName, target, method, args, true, stack);
};
Backburner.prototype.setTimeout = function () {
var l = arguments.length,
x,
last;
var args = new Array(l);
for (x = 0; x < l; x++) {
args[x] = arguments[x];
}
var length = args.length;
var method = void 0;
var wait = void 0;
var target = void 0;
var methodOrTarget = void 0;
var methodOrWait = void 0;
var methodOrArgs = void 0;
if (length === 0) {
return;
} else if (length === 1) {
method = args.shift();
wait = 0;
} else if (length === 2) {
methodOrTarget = args[0];
methodOrWait = args[1];
if (isFunction(methodOrWait) || isFunction(methodOrTarget[methodOrWait])) {
target = args.shift();
method = args.shift();
wait = 0;
} else if (isCoercableNumber(methodOrWait)) {
method = args.shift();
wait = args.shift();
} else {
method = args.shift();
wait = 0;
}
} else {
last = args[args.length - 1];
if (isCoercableNumber(last)) {
wait = args.pop();
} else {
wait = 0;
}
methodOrTarget = args[0];
methodOrArgs = args[1];
if (isFunction(methodOrArgs) || isString(methodOrArgs) && methodOrTarget !== null && methodOrArgs in methodOrTarget) {
target = args.shift();
method = args.shift();
} else {
method = args.shift();
}
}
var executeAt = now() + parseInt(wait !== wait ? 0 : wait, 10);
if (isString(method)) {
method = target[method];
}
var onError = getOnError(this.options);
return this._setTimeout(function () {
if (onError) {
try {
method.apply(target, args);
} catch (e) {
onError(e);
}
} else {
method.apply(target, args);
}
}, executeAt);
};
Backburner.prototype.throttle = function (target, method /* , args, wait, [immediate] */) {
var backburner = this,
i;
var args = new Array(arguments.length);
for (i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
var immediate = args.pop();
var wait = void 0;
var throttler = void 0;
var index = void 0;
var timer = void 0;
if (isNumber(immediate) || isString(immediate)) {
wait = immediate;
immediate = true;
} else {
wait = args.pop();
}
wait = parseInt(wait, 10);
index = findThrottler(target, method, this._throttlers);
if (index > -1) {
return this._throttlers[index];
} // throttled
timer = this._platform.setTimeout(function () {
if (!immediate) {
backburner.run.apply(backburner, args);
}
index = findThrottler(target, method, backburner._throttlers);
if (index > -1) {
backburner._throttlers.splice(index, 1);
}
}, wait);
if (immediate) {
this.join.apply(this, args);
}
throttler = [target, method, timer];
this._throttlers.push(throttler);
return throttler;
};
Backburner.prototype.debounce = function (target, method /* , args, wait, [immediate] */) {
var backburner = this,
i;
var args = new Array(arguments.length);
for (i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
var immediate = args.pop();
var wait = void 0;
var index = void 0;
var debouncee = void 0;
var timer = void 0;
if (isNumber(immediate) || isString(immediate)) {
wait = immediate;
immediate = false;
} else {
wait = args.pop();
}
wait = parseInt(wait, 10);
// Remove debouncee
index = findDebouncee(target, method, this._debouncees);
if (index > -1) {
debouncee = this._debouncees[index];
this._debouncees.splice(index, 1);
this._platform.clearTimeout(debouncee[2]);
}
timer = this._platform.setTimeout(function () {
if (!immediate) {
backburner.run.apply(backburner, args);
}
index = findDebouncee(target, method, backburner._debouncees);
if (index > -1) {
backburner._debouncees.splice(index, 1);
}
}, wait);
if (immediate && index === -1) {
backburner.run.apply(backburner, args);
}
debouncee = [target, method, timer];
backburner._debouncees.push(debouncee);
return debouncee;
};
Backburner.prototype.cancelTimers = function () {
each(this._throttlers, this._boundClearItems);
this._throttlers = [];
each(this._debouncees, this._boundClearItems);
this._debouncees = [];
this._clearTimerTimeout();
this._timers = [];
if (this._autorun) {
this._platform.clearTimeout(this._autorun);
this._autorun = null;
}
};
Backburner.prototype.hasTimers = function () {
return !!this._timers.length || !!this._debouncees.length || !!this._throttlers.length || this._autorun;
};
Backburner.prototype.cancel = function (timer) {
var timerType = typeof timer,
i,
l;
if (timer && timerType === 'object' && timer.queue && timer.method) {
return timer.queue.cancel(timer);
} else if (timerType === 'function') {
for (i = 0, l = this._timers.length; i < l; i += 2) {
if (this._timers[i + 1] === timer) {
this._timers.splice(i, 2); // remove the two elements
if (i === 0) {
this._reinstallTimerTimeout();
}
return true;
}
}
} else if (Object.prototype.toString.call(timer) === '[object Array]') {
return this._cancelItem(findThrottler, this._throttlers, timer) || this._cancelItem(findDebouncee, this._debouncees, timer);
} else {}
};
Backburner.prototype._setTimeout = function (fn, executeAt) {
if (this._timers.length === 0) {
this._timers.push(executeAt, fn);
this._installTimerTimeout();
return fn;
}
// find position to insert
var i = binarySearch(executeAt, this._timers);
this._timers.splice(i, 0, executeAt, fn);
// we should be the new earliest timer if i == 0
if (i === 0) {
this._reinstallTimerTimeout();
}
return fn;
};
Backburner.prototype._cancelItem = function (findMethod, array, timer) {
var item = void 0;
var index = void 0;
if (timer.length < 3) {
return false;
}
index = findMethod(timer[0], timer[1], array);
if (index > -1) {
item = array[index];
if (item[2] === timer[2]) {
array.splice(index, 1);
this._platform.clearTimeout(timer[2]);
return true;
}
}
return false;
};
Backburner.prototype._trigger = function (eventName, arg1, arg2) {
var callbacks = this._eventCallbacks[eventName],
i;
if (callbacks) {
for (i = 0; i < callbacks.length; i++) {
callbacks[i](arg1, arg2);
}
}
};
Backburner.prototype._runExpiredTimers = function () {
this._timerTimeoutId = undefined;
this.run(this, this._scheduleExpiredTimers);
};
Backburner.prototype._scheduleExpiredTimers = function () {
var n = now(),
executeAt,
fn;
var timers = this._timers;
var i = 0;
var l = timers.length;
for (; i < l; i += 2) {
executeAt = timers[i];
fn = timers[i + 1];
if (executeAt <= n) {
this.defer(this.options.defaultQueue, null, fn);
} else {
break;
}
}
timers.splice(0, i);
this._installTimerTimeout();
};
Backburner.prototype._reinstallTimerTimeout = function () {
this._clearTimerTimeout();
this._installTimerTimeout();
};
Backburner.prototype._clearTimerTimeout = function () {
if (!this._timerTimeoutId) {
return;
}
this._platform.clearTimeout(this._timerTimeoutId);
this._timerTimeoutId = undefined;
};
Backburner.prototype._installTimerTimeout = function () {
if (!this._timers.length) {
return;
}
var minExpiresAt = this._timers[0];
var n = now();
var wait = Math.max(0, minExpiresAt - n);
this._timerTimeoutId = this._platform.setTimeout(this._boundRunExpiredTimers, wait);
};
Backburner.prototype._ensureInstance = function () {
var currentInstance = this.currentInstance,
_setTimeout2;
if (!currentInstance) {
_setTimeout2 = this._platform.setTimeout;
currentInstance = this.begin();
this._autorun = _setTimeout2(this._boundAutorunEnd, 0);
}
return currentInstance;
};
return Backburner;
}();
Backburner.Queue = Queue;
Backburner.prototype.schedule = Backburner.prototype.defer;
Backburner.prototype.scheduleOnce = Backburner.prototype.deferOnce;
Backburner.prototype.later = Backburner.prototype.setTimeout;
exports.default = Backburner;
});
enifed('container', ['exports', 'ember-utils', 'ember-debug', 'ember-environment'], function (exports, _emberUtils, _emberDebug, _emberEnvironment) {
'use strict';
exports.buildFakeContainerWithDeprecations = exports.Container = exports.privatize = exports.Registry = undefined;
/* globals Proxy */
var CONTAINER_OVERRIDE = (0, _emberUtils.symbol)('CONTAINER_OVERRIDE');
/**
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
*/
function Container(registry, options) {
this.registry = registry;
this.owner = options && options.owner ? options.owner : null;
this.cache = (0, _emberUtils.dictionary)(options && options.cache ? options.cache : null);
this.factoryCache = (0, _emberUtils.dictionary)(options && options.factoryCache ? options.factoryCache : null);
this.factoryManagerCache = (0, _emberUtils.dictionary)(options && options.factoryManagerCache ? options.factoryManagerCache : null);
this.validationCache = (0, _emberUtils.dictionary)(options && options.validationCache ? options.validationCache : null);
this._fakeContainerToInject = buildFakeContainerWithDeprecations(this);
this[CONTAINER_OVERRIDE] = undefined;
this.isDestroyed = false;
}
Container.prototype = {
lookup: function (fullName, options) {
true && !this.registry.validateFullName(fullName) && (0, _emberDebug.assert)('fullName must be a proper full name', this.registry.validateFullName(fullName));
return lookup(this, this.registry.normalize(fullName), options);
},
lookupFactory: function (fullName, options) {
true && !this.registry.validateFullName(fullName) && (0, _emberDebug.assert)('fullName must be a proper full name', this.registry.validateFullName(fullName));
true && !false && (0, _emberDebug.deprecate)('Using "_lookupFactory" is deprecated. Please use container.factoryFor instead.', false, { id: 'container-lookupFactory', until: '2.13.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_migrating-from-_lookupfactory-to-factoryfor' });
return deprecatedFactoryFor(this, this.registry.normalize(fullName), options);
},
destroy: function () {
destroyDestroyables(this);
this.isDestroyed = true;
},
reset: function (fullName) {
if (arguments.length > 0) {
resetMember(this, this.registry.normalize(fullName));
} else {
resetCache(this);
}
},
ownerInjection: function () {
var _ref;
return _ref = {}, _ref[_emberUtils.OWNER] = this.owner, _ref;
},
factoryFor: function (fullName) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var normalizedName = this.registry.normalize(fullName);
true && !this.registry.validateFullName(normalizedName) && (0, _emberDebug.assert)('fullName must be a proper full name', this.registry.validateFullName(normalizedName));
if (options.source) {
normalizedName = this.registry.expandLocalLookup(fullName, options);
// if expandLocalLookup returns falsey, we do not support local lookup
if (!normalizedName) {
return;
}
}
var cached = this.factoryManagerCache[normalizedName];
if (cached) {
return cached;
}
var factory = this.registry.resolve(normalizedName);
if (factory === undefined) {
return;
}
if (true && factory && typeof factory._onLookup === 'function') {
factory._onLookup(fullName);
}
var manager = new FactoryManager(this, factory, fullName, normalizedName);
manager = wrapManagerInDeprecationProxy(manager);
this.factoryManagerCache[normalizedName] = manager;
return manager;
}
};
/*
* Wrap a factory manager in a proxy which will not permit properties to be
* set on the manager.
*/
function wrapManagerInDeprecationProxy(manager) {
var validator, m, proxiedManager;
if (_emberUtils.HAS_NATIVE_PROXY) {
validator = {
get: function (obj, prop) {
if (prop !== 'class' && prop !== 'create') {
throw new Error('You attempted to access "' + prop + '" on a factory manager created by container#factoryFor. "' + prop + '" is not a member of a factory manager."');
}
return obj[prop];
},
set: function (obj, prop) {
throw new Error('You attempted to set "' + prop + '" on a factory manager created by container#factoryFor. A factory manager is a read-only construct.');
}
};
// Note:
// We have to proxy access to the manager here so that private property
// access doesn't cause the above errors to occur.
m = manager;
proxiedManager = {
class: m.class,
create: function (props) {
return m.create(props);
}
};
return new Proxy(proxiedManager, validator);
}
return manager;
}
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) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (options.source) {
fullName = container.registry.expandLocalLookup(fullName, options);
// if expandLocalLookup returns falsey, we do not support local lookup
if (!fullName) {
return;
}
}
if (container.cache[fullName] !== undefined && options.singleton !== false) {
return container.cache[fullName];
}
return instantiateFactory(container, fullName, options);
}
function isSingletonClass(container, fullName, _ref2) {
var instantiate = _ref2.instantiate,
singleton = _ref2.singleton;
return singleton !== false && isSingleton(container, fullName) && !instantiate && !isInstantiatable(container, fullName);
}
function isSingletonInstance(container, fullName, _ref3) {
var instantiate = _ref3.instantiate,
singleton = _ref3.singleton;
return singleton !== false && isSingleton(container, fullName) && instantiate !== false && isInstantiatable(container, fullName);
}
function isFactoryClass(container, fullname, _ref4) {
var instantiate = _ref4.instantiate,
singleton = _ref4.singleton;
return (singleton === false || !isSingleton(container, fullname)) && instantiate === false && !isInstantiatable(container, fullname);
}
function isFactoryInstance(container, fullName, _ref5) {
var instantiate = _ref5.instantiate,
singleton = _ref5.singleton;
return (singleton !== false || isSingleton(container, fullName)) && instantiate !== false && isInstantiatable(container, fullName);
}
function instantiateFactory(container, fullName, options) {
var factoryManager = container.factoryFor(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)) {
return container.cache[fullName] = factoryManager.create();
}
// 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 markInjectionsAsDynamic(injections) {
injections._dynamic = true;
}
function areInjectionsDynamic(injections) {
return !!injections._dynamic;
}
function buildInjections() /* container, ...injections */{
var hash = {},
container,
injections,
injection,
i,
markAsDynamic,
_i;
if (arguments.length > 1) {
container = arguments[0];
injections = [];
injection = void 0;
for (i = 1; i < arguments.length; i++) {
if (arguments[i]) {
injections = injections.concat(arguments[i]);
}
}
container.registry.validateInjections(injections);
markAsDynamic = false;
for (_i = 0; _i < injections.length; _i++) {
injection = injections[_i];
hash[injection.property] = lookup(container, injection.fullName);
if (!markAsDynamic) {
markAsDynamic = !isSingleton(container, injection.fullName);
}
}
if (markAsDynamic) {
markInjectionsAsDynamic(hash);
}
}
return hash;
}
function deprecatedFactoryFor(container, fullName) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
injections,
factoryInjections,
cacheable,
injectedFactory;
var registry = container.registry;
if (options.source) {
fullName = registry.expandLocalLookup(fullName, options);
// if expandLocalLookup returns falsey, we do not support local lookup
if (!fullName) {
return;
}
}
var cache = container.factoryCache;
if (cache[fullName]) {
return cache[fullName];
}
var factory = registry.resolve(fullName);
if (factory === undefined) {
return;
}
var type = fullName.split(':')[0];
if (!factory || typeof factory.extend !== 'function' || !_emberEnvironment.ENV.MODEL_FACTORY_INJECTIONS && type === 'model') {
if (factory && typeof factory._onLookup === 'function') {
factory._onLookup(fullName);
}
// TODO: think about a 'safe' merge style extension
// for now just fallback to create time injection
cache[fullName] = factory;
return factory;
} else {
injections = injectionsFor(container, fullName);
factoryInjections = factoryInjectionsFor(container, fullName);
cacheable = !areInjectionsDynamic(injections) && !areInjectionsDynamic(factoryInjections);
factoryInjections[_emberUtils.NAME_KEY] = registry.makeToString(factory, fullName);
injections._debugContainerKey = fullName;
(0, _emberUtils.setOwner)(injections, container.owner);
injectedFactory = factory.extend(injections);
// TODO - remove all `container` injections when Ember reaches v3.0.0
injectDeprecatedContainer(injectedFactory.prototype, container);
injectedFactory.reopenClass(factoryInjections);
if (factory && typeof factory._onLookup === 'function') {
factory._onLookup(fullName);
}
if (cacheable) {
cache[fullName] = injectedFactory;
}
return injectedFactory;
}
}
function injectionsFor(container, fullName) {
var registry = container.registry;
var splitName = fullName.split(':');
var type = splitName[0];
var injections = buildInjections(container, registry.getTypeInjections(type), registry.getInjections(fullName));
return injections;
}
function factoryInjectionsFor(container, fullName) {
var registry = container.registry;
var splitName = fullName.split(':');
var type = splitName[0];
var factoryInjections = buildInjections(container, registry.getFactoryTypeInjections(type), registry.getFactoryInjections(fullName));
factoryInjections._debugContainerKey = fullName;
return factoryInjections;
}
var INJECTED_DEPRECATED_CONTAINER_DESC = {
configurable: true,
enumerable: false,
get: function () {
true && !false && (0, _emberDebug.deprecate)('Using the injected `container` is deprecated. Please use the `getOwner` helper instead to access the owner of this object.', false, { id: 'ember-application.injected-container', until: '2.13.0', url: 'http://emberjs.com/deprecations/v2.x#toc_injected-container-access' });
return this[CONTAINER_OVERRIDE] || (0, _emberUtils.getOwner)(this).__container__;
},
set: function (value) {
true && !false && (0, _emberDebug.deprecate)('Providing the `container` property to ' + this + ' is deprecated. Please use `Ember.setOwner` or `owner.ownerInjection()` instead to provide an owner to the instance being created.', false, { id: 'ember-application.injected-container', until: '2.13.0', url: 'http://emberjs.com/deprecations/v2.x#toc_injected-container-access' });
this[CONTAINER_OVERRIDE] = value;
return value;
}
};
// TODO - remove when Ember reaches v3.0.0
function injectDeprecatedContainer(object) {
if ('container' in object) {
return;
}
Object.defineProperty(object, 'container', INJECTED_DEPRECATED_CONTAINER_DESC);
}
function destroyDestroyables(container) {
var cache = container.cache,
i,
key,
value;
var keys = Object.keys(cache);
for (i = 0; i < keys.length; i++) {
key = keys[i];
value = cache[key];
if (isInstantiatable(container, key) && value.destroy) {
value.destroy();
}
}
}
function resetCache(container) {
destroyDestroyables(container);
container.cache.dict = (0, _emberUtils.dictionary)(null);
}
function resetMember(container, fullName) {
var member = container.cache[fullName];
delete container.factoryCache[fullName];
if (member) {
delete container.cache[fullName];
if (member.destroy) {
member.destroy();
}
}
}
function buildFakeContainerWithDeprecations(container) {
var fakeContainer = {};
var propertyMappings = {
lookup: 'lookup',
lookupFactory: '_lookupFactory'
};
for (var containerProperty in propertyMappings) {
fakeContainer[containerProperty] = buildFakeContainerFunction(container, containerProperty, propertyMappings[containerProperty]);
}
return fakeContainer;
}
function buildFakeContainerFunction(container, containerProperty, ownerProperty) {
return function () {
true && !false && (0, _emberDebug.deprecate)('Using the injected `container` is deprecated. Please use the `getOwner` helper to access the owner of this object and then call `' + ownerProperty + '` instead.', false, {
id: 'ember-application.injected-container',
until: '2.13.0',
url: 'http://emberjs.com/deprecations/v2.x#toc_injected-container-access'
});
return container[containerProperty].apply(container, arguments);
};
}
var FactoryManager = function () {
function FactoryManager(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;
}
FactoryManager.prototype.toString = function () {
if (!this.madeToString) {
this.madeToString = this.container.registry.makeToString(this.class, this.fullName);
}
return this.madeToString;
};
FactoryManager.prototype.create = function () {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var injections = this.injections;
if (injections === undefined) {
injections = injectionsFor(this.container, this.normalizedName);
if (areInjectionsDynamic(injections) === false) {
this.injections = injections;
}
}
var props = (0, _emberUtils.assign)({}, injections, options);
var lazyInjections = void 0;
var validationCache = this.container.validationCache;
// Ensure that all lazy injections are valid at instantiation time
if (!validationCache[this.fullName] && this.class && typeof this.class._lazyInjections === 'function') {
lazyInjections = this.class._lazyInjections();
lazyInjections = this.container.registry.normalizeInjectionsHash(lazyInjections);
this.container.registry.validateInjections(lazyInjections);
}
validationCache[this.fullName] = true;
if (!this.class.create) {
throw new Error('Failed to create an instance of \'' + this.normalizedName + '\'. Most likely an improperly defined class or' + ' an invalid module export.');
}
var prototype = this.class.prototype;
if (prototype) {
injectDeprecatedContainer(prototype, this.container);
}
// required to allow access to things like
// the customized toString, _debugContainerKey,
// owner, etc. without a double extend and without
// modifying the objects properties
if (typeof this.class._initFactory === 'function') {
this.class._initFactory(this);
} else {
// in the non-Ember.Object case we need to still setOwner
// this is required for supporting glimmer environment and
// template instantiation which rely heavily on
// `options[OWNER]` being passed into `create`
// TODO: clean this up, and remove in future versions
(0, _emberUtils.setOwner)(props, this.owner);
}
return this.class.create(props);
};
return FactoryManager;
}();
var VALID_FULL_NAME_REGEXP = /^[^:]+:[^:]+$/;
/**
A registry used to store factory and option information keyed
by type.
A `Registry` stores the factory and option information needed by a
`Container` to instantiate and cache objects.
The API for `Registry` is still in flux and should not be considered stable.
@private
@class Registry
@since 1.11.0
*/
function Registry(options) {
this.fallback = options && options.fallback ? options.fallback : null;
if (options && options.resolver) {
this.resolver = options.resolver;
if (typeof this.resolver === 'function') {
deprecateResolverFunction(this);
}
}
this.registrations = (0, _emberUtils.dictionary)(options && options.registrations ? options.registrations : null);
this._typeInjections = (0, _emberUtils.dictionary)(null);
this._injections = (0, _emberUtils.dictionary)(null);
this._factoryTypeInjections = (0, _emberUtils.dictionary)(null);
this._factoryInjections = (0, _emberUtils.dictionary)(null);
this._localLookupCache = Object.create(null);
this._normalizeCache = (0, _emberUtils.dictionary)(null);
this._resolveCache = (0, _emberUtils.dictionary)(null);
this._failCache = (0, _emberUtils.dictionary)(null);
this._options = (0, _emberUtils.dictionary)(null);
this._typeOptions = (0, _emberUtils.dictionary)(null);
}
Registry.prototype = {
/**
A backup registry for resolving registrations when no matches can be found.
@private
@property fallback
@type Registry
*/
fallback: null,
/**
An object that has a `resolve` method that resolves a name.
@private
@property resolver
@type Resolver
*/
resolver: null,
/**
@private
@property registrations
@type InheritingDict
*/
registrations: null,
/**
@private
@property _typeInjections
@type InheritingDict
*/
_typeInjections: null,
/**
@private
@property _injections
@type InheritingDict
*/
_injections: null,
/**
@private
@property _factoryTypeInjections
@type InheritingDict
*/
_factoryTypeInjections: null,
/**
@private
@property _factoryInjections
@type InheritingDict
*/
_factoryInjections: null,
/**
@private
@property _normalizeCache
@type InheritingDict
*/
_normalizeCache: null,
/**
@private
@property _resolveCache
@type InheritingDict
*/
_resolveCache: null,
/**
@private
@property _options
@type InheritingDict
*/
_options: null,
/**
@private
@property _typeOptions
@type InheritingDict
*/
_typeOptions: null,
container: function (options) {
return new Container(this, options);
},
register: function (fullName, factory) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
true && !this.validateFullName(fullName) && (0, _emberDebug.assert)('fullName must be a proper full name', this.validateFullName(fullName));
if (factory === undefined) {
throw new TypeError('Attempting to register an unknown factory: \'' + fullName + '\'');
}
var normalizedName = this.normalize(fullName);
if (this._resolveCache[normalizedName]) {
throw new Error('Cannot re-register: \'' + fullName + '\', as it has already been resolved.');
}
delete this._failCache[normalizedName];
this.registrations[normalizedName] = factory;
this._options[normalizedName] = options;
},
unregister: function (fullName) {
true && !this.validateFullName(fullName) && (0, _emberDebug.assert)('fullName must be a proper full name', this.validateFullName(fullName));
var normalizedName = this.normalize(fullName);
this._localLookupCache = Object.create(null);
delete this.registrations[normalizedName];
delete this._resolveCache[normalizedName];
delete this._failCache[normalizedName];
delete this._options[normalizedName];
},
resolve: function (fullName, options) {
true && !this.validateFullName(fullName) && (0, _emberDebug.assert)('fullName must be a proper full name', this.validateFullName(fullName));
var factory = resolve(this, this.normalize(fullName), options),
_fallback;
if (factory === undefined && this.fallback) {
factory = (_fallback = this.fallback).resolve.apply(_fallback, arguments);
}
return factory;
},
describe: function (fullName) {
if (this.resolver && this.resolver.lookupDescription) {
return this.resolver.lookupDescription(fullName);
} else if (this.fallback) {
return this.fallback.describe(fullName);
} else {
return fullName;
}
},
normalizeFullName: function (fullName) {
if (this.resolver && this.resolver.normalize) {
return this.resolver.normalize(fullName);
} else if (this.fallback) {
return this.fallback.normalizeFullName(fullName);
} else {
return fullName;
}
},
normalize: function (fullName) {
return this._normalizeCache[fullName] || (this._normalizeCache[fullName] = this.normalizeFullName(fullName));
},
makeToString: function (factory, fullName) {
if (this.resolver && this.resolver.makeToString) {
return this.resolver.makeToString(factory, fullName);
} else if (this.fallback) {
return this.fallback.makeToString(factory, fullName);
} else {
return factory.toString();
}
},
has: function (fullName, options) {
if (!this.isValidFullName(fullName)) {
return false;
}
var source = options && options.source && this.normalize(options.source);
return has(this, this.normalize(fullName), source);
},
optionsForType: function (type, options) {
this._typeOptions[type] = options;
},
getOptionsForType: function (type) {
var optionsForType = this._typeOptions[type];
if (optionsForType === undefined && this.fallback) {
optionsForType = this.fallback.getOptionsForType(type);
}
return optionsForType;
},
options: function (fullName) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var normalizedName = this.normalize(fullName);
this._options[normalizedName] = options;
},
getOptions: function (fullName) {
var normalizedName = this.normalize(fullName);
var options = this._options[normalizedName];
if (options === undefined && this.fallback) {
options = this.fallback.getOptions(fullName);
}
return options;
},
getOption: function (fullName, optionName) {
var options = this._options[fullName];
if (options && options[optionName] !== undefined) {
return options[optionName];
}
var type = fullName.split(':')[0];
options = this._typeOptions[type];
if (options && options[optionName] !== undefined) {
return options[optionName];
} else if (this.fallback) {
return this.fallback.getOption(fullName, optionName);
}
},
typeInjection: function (type, property, fullName) {
true && !this.validateFullName(fullName) && (0, _emberDebug.assert)('fullName must be a proper full name', this.validateFullName(fullName));
var fullNameType = fullName.split(':')[0];
if (fullNameType === type) {
throw new Error('Cannot inject a \'' + fullName + '\' on other ' + type + '(s).');
}
var injections = this._typeInjections[type] || (this._typeInjections[type] = []);
injections.push({
property: property,
fullName: fullName
});
},
injection: function (fullName, property, injectionName) {
this.validateFullName(injectionName);
var normalizedInjectionName = this.normalize(injectionName);
if (fullName.indexOf(':') === -1) {
return this.typeInjection(fullName, property, normalizedInjectionName);
}
true && !this.validateFullName(fullName) && (0, _emberDebug.assert)('fullName must be a proper full name', this.validateFullName(fullName));
var normalizedName = this.normalize(fullName);
var injections = this._injections[normalizedName] || (this._injections[normalizedName] = []);
injections.push({
property: property,
fullName: normalizedInjectionName
});
},
factoryTypeInjection: function (type, property, fullName) {
var injections = this._factoryTypeInjections[type] || (this._factoryTypeInjections[type] = []);
injections.push({
property: property,
fullName: this.normalize(fullName)
});
},
factoryInjection: function (fullName, property, injectionName) {
var normalizedName = this.normalize(fullName);
var normalizedInjectionName = this.normalize(injectionName);
this.validateFullName(injectionName);
if (fullName.indexOf(':') === -1) {
return this.factoryTypeInjection(normalizedName, property, normalizedInjectionName);
}
var injections = this._factoryInjections[normalizedName] || (this._factoryInjections[normalizedName] = []);
injections.push({
property: property,
fullName: normalizedInjectionName
});
},
knownForType: function (type) {
var fallbackKnown = void 0,
resolverKnown = void 0,
index,
fullName,
itemType;
var localKnown = (0, _emberUtils.dictionary)(null);
var registeredNames = Object.keys(this.registrations);
for (index = 0; index < registeredNames.length; index++) {
fullName = registeredNames[index];
itemType = fullName.split(':')[0];
if (itemType === type) {
localKnown[fullName] = true;
}
}
if (this.fallback) {
fallbackKnown = this.fallback.knownForType(type);
}
if (this.resolver && this.resolver.knownForType) {
resolverKnown = this.resolver.knownForType(type);
}
return (0, _emberUtils.assign)({}, fallbackKnown, localKnown, resolverKnown);
},
validateFullName: function (fullName) {
if (!this.isValidFullName(fullName)) {
throw new TypeError('Invalid Fullname, expected: \'type:name\' got: ' + fullName);
}
return true;
},
isValidFullName: function (fullName) {
return !!VALID_FULL_NAME_REGEXP.test(fullName);
},
validateInjections: function (injections) {
if (!injections) {
return;
}
var fullName = void 0,
i;
for (i = 0; i < injections.length; i++) {
fullName = injections[i].fullName;
true && !this.has(fullName) && (0, _emberDebug.assert)('Attempting to inject an unknown injection: \'' + fullName + '\'', this.has(fullName));
}
},
normalizeInjectionsHash: function (hash) {
var injections = [];
for (var key in hash) {
if (hash.hasOwnProperty(key)) {
true && !this.validateFullName(hash[key]) && (0, _emberDebug.assert)('Expected a proper full name, given \'' + hash[key] + '\'', this.validateFullName(hash[key]));
injections.push({
property: key,
fullName: hash[key]
});
}
}
return injections;
},
getInjections: function (fullName) {
var injections = this._injections[fullName] || [];
if (this.fallback) {
injections = injections.concat(this.fallback.getInjections(fullName));
}
return injections;
},
getTypeInjections: function (type) {
var injections = this._typeInjections[type] || [];
if (this.fallback) {
injections = injections.concat(this.fallback.getTypeInjections(type));
}
return injections;
},
getFactoryInjections: function (fullName) {
var injections = this._factoryInjections[fullName] || [];
if (this.fallback) {
injections = injections.concat(this.fallback.getFactoryInjections(fullName));
}
return injections;
},
getFactoryTypeInjections: function (type) {
var injections = this._factoryTypeInjections[type] || [];
if (this.fallback) {
injections = injections.concat(this.fallback.getFactoryTypeInjections(type));
}
return injections;
}
};
function deprecateResolverFunction(registry) {
true && !false && (0, _emberDebug.deprecate)('Passing a `resolver` function into a Registry is deprecated. Please pass in a Resolver object with a `resolve` method.', false, { id: 'ember-application.registry-resolver-as-function', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_registry-resolver-as-function' });
registry.resolver = {
resolve: registry.resolver
};
}
/**
Given a fullName and a source fullName returns the fully resolved
fullName. Used to allow for local lookup.
```javascript
let registry = new Registry();
// the twitter factory is added to the module system
registry.expandLocalLookup('component:post-title', { source: 'template:post' }) // => component:post/post-title
```
@private
@method expandLocalLookup
@param {String} fullName
@param {Object} [options]
@param {String} [options.source] the fullname of the request source (used for local lookups)
@return {String} fullName
*/
Registry.prototype.expandLocalLookup = function (fullName, options) {
var normalizedFullName, normalizedSource;
if (this.resolver && this.resolver.expandLocalLookup) {
true && !this.validateFullName(fullName) && (0, _emberDebug.assert)('fullName must be a proper full name', this.validateFullName(fullName));
true && !(options && options.source) && (0, _emberDebug.assert)('options.source must be provided to expandLocalLookup', options && options.source);
true && !this.validateFullName(options.source) && (0, _emberDebug.assert)('options.source must be a proper full name', this.validateFullName(options.source));
normalizedFullName = this.normalize(fullName);
normalizedSource = this.normalize(options.source);
return expandLocalLookup(this, normalizedFullName, normalizedSource);
} else if (this.fallback) {
return this.fallback.expandLocalLookup(fullName, options);
} else {
return null;
}
};
function expandLocalLookup(registry, normalizedName, normalizedSource) {
var cache = registry._localLookupCache;
var normalizedNameCache = cache[normalizedName];
if (!normalizedNameCache) {
normalizedNameCache = cache[normalizedName] = Object.create(null);
}
var cached = normalizedNameCache[normalizedSource];
if (cached !== undefined) {
return cached;
}
var expanded = registry.resolver.expandLocalLookup(normalizedName, normalizedSource);
return normalizedNameCache[normalizedSource] = expanded;
}
function resolve(registry, normalizedName, options) {
if (options && options.source) {
// when `source` is provided expand normalizedName
// and source into the full normalizedName
normalizedName = registry.expandLocalLookup(normalizedName, options);
// if expandLocalLookup returns falsey, we do not support local lookup
if (!normalizedName) {
return;
}
}
var cached = registry._resolveCache[normalizedName];
if (cached !== undefined) {
return cached;
}
if (registry._failCache[normalizedName]) {
return;
}
var resolved = void 0;
if (registry.resolver) {
resolved = registry.resolver.resolve(normalizedName);
}
if (resolved === undefined) {
resolved = registry.registrations[normalizedName];
}
if (resolved === undefined) {
registry._failCache[normalizedName] = true;
} else {
registry._resolveCache[normalizedName] = resolved;
}
return resolved;
}
function has(registry, fullName, source) {
return registry.resolve(fullName, { source: source }) !== undefined;
}
var privateNames = (0, _emberUtils.dictionary)(null);
var privateSuffix = '' + Math.random() + Date.now();
/*
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
*/
exports.Registry = Registry;
exports.privatize = function (_ref6) {
var fullName = _ref6[0];
var name = privateNames[fullName];
if (name) {
return name;
}
var _fullName$split = fullName.split(':'),
type = _fullName$split[0],
rawName = _fullName$split[1];
return privateNames[fullName] = (0, _emberUtils.intern)(type + ':' + rawName + '-' + privateSuffix);
};
exports.Container = Container;
exports.buildFakeContainerWithDeprecations = buildFakeContainerWithDeprecations;
});
enifed('ember-babel', ['exports'], function (exports) {
'use strict';
exports.inherits = function (subClass, superClass) {
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : defaults(subClass, superClass);
};
exports.taggedTemplateLiteralLoose = function (strings, raw) {
strings.raw = raw;
return strings;
};
exports.createClass = function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
exports.defaults = defaults;
function defineProperties(target, props) {
var i, descriptor;
for (i = 0; i < props.length; i++) {
descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ('value' in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function defaults(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults),
i,
key,
value;
for (i = 0; i < keys.length; i++) {
key = keys[i];
value = Object.getOwnPropertyDescriptor(defaults, key);
if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}
return obj;
}
exports.possibleConstructorReturn = function (self, call) {
return call && (typeof call === 'object' || typeof call === 'function') ? call : self;
};
exports.slice = Array.prototype.slice;
});
enifed('ember-console', ['exports', 'ember-environment'], function (exports, _emberEnvironment) {
'use strict';
function K() {}
function consoleMethod(name) {
var consoleObj = void 0;
if (_emberEnvironment.context.imports.console) {
consoleObj = _emberEnvironment.context.imports.console;
} else if (typeof console !== 'undefined') {
// eslint-disable-line no-undef
consoleObj = console; // eslint-disable-line no-undef
}
var method = typeof consoleObj === 'object' ? consoleObj[name] : null;
if (typeof method !== 'function') {
return;
}
if (typeof method.bind === 'function') {
return method.bind(consoleObj);
}
return function () {
method.apply(consoleObj, arguments);
};
}
/**
Inside Ember-Metal, simply uses the methods from `imports.console`.
Override this to provide more robust logging functionality.
@class Logger
@namespace Ember
@public
*/
var index = {
/**
Logs the arguments to the console.
You can pass as many arguments as you want and they will be joined together with a space.
```javascript
var foo = 1;
Ember.Logger.log('log value of foo:', foo);
// "log value of foo: 1" will be printed to the console
```
@method log
@for Ember.Logger
@param {*} arguments
@public
*/
log: consoleMethod('log') || K,
/**
Prints the arguments to the console with a warning icon.
You can pass as many arguments as you want and they will be joined together with a space.
```javascript
Ember.Logger.warn('Something happened!');
// "Something happened!" will be printed to the console with a warning icon.
```
@method warn
@for Ember.Logger
@param {*} arguments
@public
*/
warn: consoleMethod('warn') || K,
/**
Prints the arguments to the console with an error icon, red text and a stack trace.
You can pass as many arguments as you want and they will be joined together with a space.
```javascript
Ember.Logger.error('Danger! Danger!');
// "Danger! Danger!" will be printed to the console in red text.
```
@method error
@for Ember.Logger
@param {*} arguments
@public
*/
error: consoleMethod('error') || K,
/**
Logs the arguments to the console.
You can pass as many arguments as you want and they will be joined together with a space.
```javascript
var foo = 1;
Ember.Logger.info('log value of foo:', foo);
// "log value of foo: 1" will be printed to the console
```
@method info
@for Ember.Logger
@param {*} arguments
@public
*/
info: consoleMethod('info') || K,
/**
Logs the arguments to the console in blue text.
You can pass as many arguments as you want and they will be joined together with a space.
```javascript
var foo = 1;
Ember.Logger.debug('log value of foo:', foo);
// "log value of foo: 1" will be printed to the console
```
@method debug
@for Ember.Logger
@param {*} arguments
@public
*/
debug: consoleMethod('debug') || consoleMethod('info') || K,
/**
If the value passed into `Ember.Logger.assert` is not truthy it will throw an error with a stack trace.
```javascript
Ember.Logger.assert(true); // undefined
Ember.Logger.assert(true === false); // Throws an Assertion failed error.
Ember.Logger.assert(true === false, 'Something invalid'); // Throws an Assertion failed error with message.
```
@method assert
@for Ember.Logger
@param {Boolean} bool Value to test
@param {String} message Assertion message on failed
@public
*/
assert: consoleMethod('assert') || function (test, message) {
if (!test) {
try {
// attempt to preserve the stack
throw new Error('assertion failed: ' + message);
} catch (error) {
setTimeout(function () {
throw error;
}, 0);
}
}
}
};
exports.default = index;
});
enifed('ember-debug/deprecate', ['exports', 'ember-debug/error', 'ember-console', 'ember-environment', 'ember-debug/handlers'], function (exports, _error, _emberConsole, _emberEnvironment, _handlers) {
'use strict';
exports.missingOptionsUntilDeprecation = exports.missingOptionsIdDeprecation = exports.missingOptionsDeprecation = exports.registerHandler = undefined;
/**
@module ember
@submodule ember-debug
*/
/**
Allows for runtime registration of handler functions that override the default deprecation behavior.
Deprecations are invoked by calls to [Ember.deprecate](http://emberjs.com/api/classes/Ember.html#method_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
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:
message - The message received from the deprecation call.
options - An object passed in with the deprecation call containing additional information including:
id - An id of the deprecation in the form of package-name.specific-deprecation.
until - The Ember version number the feature and deprecation will be removed in.
next - A function that calls into the previously registered handler.
@public
@static
@method registerDeprecationHandler
@param handler {Function} A function to handle deprecation calls.
@since 2.1.0
*/
var registerHandler = function () {}; /*global __fail__*/
var missingOptionsDeprecation = void 0,
missingOptionsIdDeprecation = void 0,
missingOptionsUntilDeprecation = void 0,
deprecate = void 0;
exports.registerHandler = registerHandler = function (handler) {
(0, _handlers.registerHandler)('deprecate', handler);
};
var formatMessage = function (_message, options) {
var message = _message;
if (options && options.id) {
message = message + (' [deprecation id: ' + options.id + ']');
}
if (options && options.url) {
message += ' See ' + options.url + ' for more details.';
}
return message;
};
registerHandler(function (message, options) {
var updatedMessage = formatMessage(message, options);
_emberConsole.default.warn('DEPRECATION: ' + updatedMessage);
});
var captureErrorForStack = void 0;
if (new Error().stack) {
captureErrorForStack = function () {
return new Error();
};
} else {
captureErrorForStack = function () {
try {
__fail__.fail();
} catch (e) {
return e;
}
};
}
registerHandler(function (message, options, next) {
var stackStr, error, stack, updatedMessage;
if (_emberEnvironment.ENV.LOG_STACKTRACE_ON_DEPRECATION) {
stackStr = '';
error = captureErrorForStack();
stack = void 0;
if (error.stack) {
if (error['arguments']) {
// Chrome
stack = error.stack.replace(/^\s+at\s+/gm, '').replace(/^([^\(]+?)([\n$])/gm, '{anonymous}($1)$2').replace(/^Object.\s*\(([^\)]+)\)/gm, '{anonymous}($1)').split('\n');
stack.shift();
} else {
// Firefox
stack = error.stack.replace(/(?:\n@:0)?\s+$/m, '').replace(/^\(/gm, '{anonymous}(').split('\n');
}
stackStr = '\n ' + stack.slice(2).join('\n ');
}
updatedMessage = formatMessage(message, options);
_emberConsole.default.warn('DEPRECATION: ' + updatedMessage + stackStr);
} else {
next.apply(undefined, arguments);
}
});
registerHandler(function (message, options, next) {
var updatedMessage;
if (_emberEnvironment.ENV.RAISE_ON_DEPRECATION) {
updatedMessage = formatMessage(message);
throw new _error.default(updatedMessage);
} else {
next.apply(undefined, arguments);
}
});
exports.missingOptionsDeprecation = missingOptionsDeprecation = 'When calling `Ember.deprecate` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include `id` and `until` properties.';
exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation = 'When calling `Ember.deprecate` you must provide `id` in options.';
exports.missingOptionsUntilDeprecation = missingOptionsUntilDeprecation = 'When calling `Ember.deprecate` you must provide `until` in options.';
/**
Display a deprecation warning with the provided message and a stack trace
(Chrome and Firefox only).
* In a production build, this method is defined as an empty function (NOP).
Uses of this method in Ember itself are stripped from the ember.prod.js build.
@method deprecate
@param {String} message A description of the deprecation.
@param {Boolean} test A boolean. If falsy, the deprecation will be displayed.
@param {Object} options
@param {String} options.id A unique id for this deprecation. The id can be
used by Ember debugging tools to change the behavior (raise, log or silence)
for that specific deprecation. The id should be namespaced by dots, e.g.
"view.helper.select".
@param {string} options.until The version of Ember when this deprecation
warning will be removed.
@param {String} [options.url] An optional url to the transition guide on the
emberjs.com website.
@for Ember
@public
@since 1.0.0
*/
deprecate = function deprecate(message, test, options) {
if (!options || !options.id && !options.until) {
deprecate(missingOptionsDeprecation, false, {
id: 'ember-debug.deprecate-options-missing',
until: '3.0.0',
url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options'
});
}
if (options && !options.id) {
deprecate(missingOptionsIdDeprecation, false, {
id: 'ember-debug.deprecate-id-missing',
until: '3.0.0',
url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options'
});
}
if (options && !options.until) {
deprecate(missingOptionsUntilDeprecation, options && options.until, {
id: 'ember-debug.deprecate-until-missing',
until: '3.0.0',
url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options'
});
}
_handlers.invoke.apply(undefined, ['deprecate'].concat(Array.prototype.slice.call(arguments)));
};
exports.default = deprecate;
exports.registerHandler = registerHandler;
exports.missingOptionsDeprecation = missingOptionsDeprecation;
exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation;
exports.missingOptionsUntilDeprecation = missingOptionsUntilDeprecation;
});
enifed("ember-debug/error", ["exports", "ember-babel"], function (exports, _emberBabel) {
"use strict";
/**
A subclass of the JavaScript Error object for use in Ember.
@class Error
@namespace Ember
@extends Error
@constructor
@public
*/
var EmberError = function (_ExtendBuiltin) {
(0, _emberBabel.inherits)(EmberError, _ExtendBuiltin);
function EmberError(message) {
var _this = (0, _emberBabel.possibleConstructorReturn)(this, _ExtendBuiltin.call(this)),
_ret;
if (!(_this instanceof EmberError)) {
return _ret = new EmberError(message), (0, _emberBabel.possibleConstructorReturn)(_this, _ret);
}
var error = Error.call(_this, message);
if (Error.captureStackTrace) {
Error.captureStackTrace(_this, EmberError);
} else {
_this.stack = error.stack;
}
_this.description = error.description;
_this.fileName = error.fileName;
_this.lineNumber = error.lineNumber;
_this.message = error.message;
_this.name = error.name;
_this.number = error.number;
_this.code = error.code;
return _this;
}
return EmberError;
}(function (klass) {
function ExtendableBuiltin() {
klass.apply(this, arguments);
}
ExtendableBuiltin.prototype = Object.create(klass.prototype);
ExtendableBuiltin.prototype.constructor = ExtendableBuiltin;
return ExtendableBuiltin;
}(Error));
exports.default = EmberError;
});
enifed('ember-debug/features', ['exports', 'ember-environment', 'ember/features'], function (exports, _emberEnvironment, _features) {
'use strict';
exports.default =
/**
The hash of enabled Canary features. Add to this, any canary features
before creating your application.
Alternatively (and recommended), you can also define `EmberENV.FEATURES`
if you need to enable features flagged at runtime.
@class FEATURES
@namespace Ember
@static
@since 1.1.0
@public
*/
// Auto-generated
/**
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}
@for Ember.FEATURES
@since 1.1.0
@public
*/
function (feature) {
var featureValue = FEATURES[feature];
if (featureValue === true || featureValue === false || featureValue === undefined) {
return featureValue;
} else if (_emberEnvironment.ENV.ENABLE_OPTIONAL_FEATURES) {
return true;
} else {
return false;
}
};
var FEATURES = _features.FEATURES;
});
enifed('ember-debug/handlers', ['exports'], function (exports) {
'use strict';
var HANDLERS = exports.HANDLERS = {};
var registerHandler = function () {};
var invoke = function () {};
exports.registerHandler = registerHandler = function (type, callback) {
var nextHandler = HANDLERS[type] || function () {};
HANDLERS[type] = function (message, options) {
callback(message, options, nextHandler);
};
};
exports.invoke = invoke = function (type, message, test, options) {
if (test) {
return;
}
var handlerForType = HANDLERS[type];
if (handlerForType) {
handlerForType(message, options);
}
};
exports.registerHandler = registerHandler;
exports.invoke = invoke;
});
enifed('ember-debug/index', ['exports', 'ember-debug/warn', 'ember-debug/deprecate', 'ember-debug/features', 'ember-debug/error', 'ember-debug/testing', 'ember-environment', 'ember-console', 'ember/features'], function (exports, _warn2, _deprecate2, _features, _error, _testing, _emberEnvironment, _emberConsole, _features2) {
'use strict';
exports._warnIfUsingStrippedFeatureFlags = exports.getDebugFunction = exports.setDebugFunction = exports.deprecateFunc = exports.runInDebug = exports.debugFreeze = exports.debugSeal = exports.deprecate = exports.debug = exports.warn = exports.info = exports.assert = exports.setTesting = exports.isTesting = exports.Error = exports.isFeatureEnabled = exports.registerDeprecationHandler = exports.registerWarnHandler = undefined;
Object.defineProperty(exports, 'registerWarnHandler', {
enumerable: true,
get: function () {
return _warn2.registerHandler;
}
});
Object.defineProperty(exports, 'registerDeprecationHandler', {
enumerable: true,
get: function () {
return _deprecate2.registerHandler;
}
});
Object.defineProperty(exports, 'isFeatureEnabled', {
enumerable: true,
get: function () {
return _features.default;
}
});
Object.defineProperty(exports, 'Error', {
enumerable: true,
get: function () {
return _error.default;
}
});
Object.defineProperty(exports, 'isTesting', {
enumerable: true,
get: function () {
return _testing.isTesting;
}
});
Object.defineProperty(exports, 'setTesting', {
enumerable: true,
get: function () {
return _testing.setTesting;
}
});
var DEFAULT_FEATURES = _features2.DEFAULT_FEATURES,
FEATURES = _features2.FEATURES,
featuresWereStripped,
isFirefox,
isChrome;
// These are the default production build versions:
var assert = function () {};
var info = function () {};
var warn = function () {};
var debug = function () {};
var deprecate = function () {};
var debugSeal = function () {};
var debugFreeze = function () {};
var runInDebug = function () {};
var deprecateFunc = function () {
return arguments[arguments.length - 1];
};
var setDebugFunction = function () {};
var getDebugFunction = function () {};
exports.setDebugFunction = setDebugFunction = function (type, callback) {
switch (type) {
case 'assert':
return exports.assert = assert = callback;
case 'info':
return exports.info = info = callback;
case 'warn':
return exports.warn = warn = callback;
case 'debug':
return exports.debug = debug = callback;
case 'deprecate':
return exports.deprecate = deprecate = callback;
case 'debugSeal':
return exports.debugSeal = debugSeal = callback;
case 'debugFreeze':
return exports.debugFreeze = debugFreeze = callback;
case 'runInDebug':
return exports.runInDebug = runInDebug = callback;
case 'deprecateFunc':
return exports.deprecateFunc = deprecateFunc = callback;
}
};
exports.getDebugFunction = getDebugFunction = function (type) {
switch (type) {
case 'assert':
return assert;
case 'info':
return info;
case 'warn':
return warn;
case 'debug':
return debug;
case 'deprecate':
return deprecate;
case 'debugSeal':
return debugSeal;
case 'debugFreeze':
return debugFreeze;
case 'runInDebug':
return runInDebug;
case 'deprecateFunc':
return deprecateFunc;
}
};
/**
@module ember
@submodule ember-debug
*/
/**
@class Ember
@public
*/
/**
Define an assertion that will throw an exception if the condition is not met.
* In a production build, this method is defined as an empty function (NOP).
Uses of this method in Ember itself are stripped from the ember.prod.js build.
```javascript
// Test for truthiness
Ember.assert('Must pass a valid object', obj);
// Fail unconditionally
Ember.assert('This code path should never be run');
```
@method assert
@param {String} desc A description of the assertion. This will become
the text of the Error thrown if the assertion fails.
@param {Boolean} test Must be truthy for the assertion to pass. If
falsy, an exception will be thrown.
@public
@since 1.0.0
*/
setDebugFunction('assert', function (desc, test) {
if (!test) {
throw new _error.default('Assertion Failed: ' + desc);
}
});
/**
Display a debug notice.
* In a production build, this method is defined as an empty function (NOP).
Uses of this method in Ember itself are stripped from the ember.prod.js build.
```javascript
Ember.debug('I\'m a debug notice!');
```
@method debug
@param {String} message A debug message to display.
@public
*/
setDebugFunction('debug', function (message) {
_emberConsole.default.debug('DEBUG: ' + message);
});
/**
Display an info notice.
* In a production build, this method is defined as an empty function (NOP).
Uses of this method in Ember itself are stripped from the ember.prod.js build.
@method info
@private
*/
setDebugFunction('info', function () {
_emberConsole.default.info.apply(undefined, arguments);
});
/**
Alias an old, deprecated method with its new counterpart.
Display a deprecation warning with the provided message and a stack trace
(Chrome and Firefox only) when the assigned method is called.
* In a production build, this method is defined as an empty function (NOP).
```javascript
Ember.oldMethod = Ember.deprecateFunc('Please use the new, updated method', Ember.newMethod);
```
@method deprecateFunc
@param {String} message A description of the deprecation.
@param {Object} [options] The options object for Ember.deprecate.
@param {Function} func The new function called to replace its deprecated counterpart.
@return {Function} A new function that wraps the original function with a deprecation warning
@private
*/
setDebugFunction('deprecateFunc', function () {
var _len, args, _key, message, options, func, _message, _func;
for (_len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (args.length === 3) {
message = args[0], options = args[1], func = args[2];
return function () {
deprecate(message, false, options);
return func.apply(this, arguments);
};
} else {
_message = args[0], _func = args[1];
return function () {
deprecate(_message);
return _func.apply(this, arguments);
};
}
});
/**
Run a function meant for debugging.
* In a production build, this method is defined as an empty function (NOP).
Uses of this method in Ember itself are stripped from the ember.prod.js build.
```javascript
Ember.runInDebug(() => {
Ember.Component.reopen({
didInsertElement() {
console.log("I'm happy");
}
});
});
```
@method runInDebug
@param {Function} func The function to be executed.
@since 1.5.0
@public
*/
setDebugFunction('runInDebug', function (func) {
func();
});
setDebugFunction('debugSeal', function (obj) {
Object.seal(obj);
});
setDebugFunction('debugFreeze', function (obj) {
Object.freeze(obj);
});
setDebugFunction('deprecate', _deprecate2.default);
setDebugFunction('warn', _warn2.default);
var _warnIfUsingStrippedFeatureFlags = void 0;
if (true && !(0, _testing.isTesting)()) {
/**
Will call `Ember.warn()` if ENABLE_OPTIONAL_FEATURES or
any specific FEATURES flag is truthy.
This method is called automatically in debug canary builds.
@private
@method _warnIfUsingStrippedFeatureFlags
@return {void}
*/
exports._warnIfUsingStrippedFeatureFlags = _warnIfUsingStrippedFeatureFlags = function (FEATURES, knownFeatures, featuresWereStripped) {
var keys, i, key;
if (featuresWereStripped) {
warn('Ember.ENV.ENABLE_OPTIONAL_FEATURES is only available in canary builds.', !_emberEnvironment.ENV.ENABLE_OPTIONAL_FEATURES, { id: 'ember-debug.feature-flag-with-features-stripped' });
keys = Object.keys(FEATURES || {});
for (i = 0; i < keys.length; i++) {
key = keys[i];
if (key === 'isEnabled' || !(key in knownFeatures)) {
continue;
}
warn('FEATURE["' + key + '"] is set as enabled, but FEATURE flags are only available in canary builds.', !FEATURES[key], { id: 'ember-debug.feature-flag-with-features-stripped' });
}
}
};
// Complain if they're using FEATURE flags in builds other than canary
FEATURES['features-stripped-test'] = true;
featuresWereStripped = true;
if ((0, _features.default)('features-stripped-test')) {
featuresWereStripped = false;
}
delete FEATURES['features-stripped-test'];
_warnIfUsingStrippedFeatureFlags(_emberEnvironment.ENV.FEATURES, DEFAULT_FEATURES, featuresWereStripped);
// Inform the developer about the Ember Inspector if not installed.
isFirefox = _emberEnvironment.environment.isFirefox;
isChrome = _emberEnvironment.environment.isChrome;
if (typeof window !== 'undefined' && (isFirefox || isChrome) && window.addEventListener) {
window.addEventListener('load', function () {
var downloadURL;
if (document.documentElement && document.documentElement.dataset && !document.documentElement.dataset.emberExtension) {
downloadURL = void 0;
if (isChrome) {
downloadURL = 'https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi';
} else if (isFirefox) {
downloadURL = 'https://addons.mozilla.org/en-US/firefox/addon/ember-inspector/';
}
debug('For more advanced debugging, install the Ember Inspector from ' + downloadURL);
}
}, false);
}
}
exports.assert = assert;
exports.info = info;
exports.warn = warn;
exports.debug = debug;
exports.deprecate = deprecate;
exports.debugSeal = debugSeal;
exports.debugFreeze = debugFreeze;
exports.runInDebug = runInDebug;
exports.deprecateFunc = deprecateFunc;
exports.setDebugFunction = setDebugFunction;
exports.getDebugFunction = getDebugFunction;
exports._warnIfUsingStrippedFeatureFlags = _warnIfUsingStrippedFeatureFlags;
});
enifed("ember-debug/testing", ["exports"], function (exports) {
"use strict";
exports.isTesting = function () {
return testing;
};
exports.setTesting = function (value) {
testing = !!value;
};
var testing = false;
});
enifed('ember-debug/warn', ['exports', 'ember-console', 'ember-debug/deprecate', 'ember-debug/handlers'], function (exports, _emberConsole, _deprecate, _handlers) {
'use strict';
exports.missingOptionsDeprecation = exports.missingOptionsIdDeprecation = exports.registerHandler = undefined;
var registerHandler = function () {};
var warn = function () {};
var missingOptionsDeprecation = void 0,
missingOptionsIdDeprecation = void 0;
/**
@module ember
@submodule ember-debug
*/
/**
Allows for runtime registration of handler functions that override the default warning behavior.
Warnings are invoked by calls made to [Ember.warn](http://emberjs.com/api/classes/Ember.html#method_warn).
The following example demonstrates its usage by registering a handler that does nothing overriding Ember's
default warning behavior.
```javascript
// next is not called, so no warnings get the default behavior
Ember.Debug.registerWarnHandler(() => {});
```
The handler function takes the following arguments:
message - The message received from the warn call.
options - An object passed in with the warn call containing additional information including:
id - An id of the warning in the form of package-name.specific-warning.
next - A function that calls into the previously registered handler.
@public
@static
@method registerWarnHandler
@param handler {Function} A function to handle warnings.
@since 2.1.0
*/
exports.registerHandler = registerHandler = function (handler) {
(0, _handlers.registerHandler)('warn', handler);
};
registerHandler(function (message) {
_emberConsole.default.warn('WARNING: ' + message);
if ('trace' in _emberConsole.default) {
_emberConsole.default.trace();
}
});
exports.missingOptionsDeprecation = missingOptionsDeprecation = 'When calling `Ember.warn` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include an `id` property.';
exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation = 'When calling `Ember.warn` you must provide `id` in options.';
/**
Display a warning with the provided message.
* In a production build, this method is defined as an empty function (NOP).
Uses of this method in Ember itself are stripped from the ember.prod.js build.
@method warn
@param {String} message A warning to display.
@param {Boolean} test An optional boolean. If falsy, the warning
will be displayed.
@param {Object} options An object that can be used to pass a unique
`id` for this warning. The `id` can be used by Ember debugging tools
to change the behavior (raise, log, or silence) for that specific warning.
The `id` should be namespaced by dots, e.g. "ember-debug.feature-flag-with-features-stripped"
@for Ember
@public
@since 1.0.0
*/
warn = function (message, test, options) {
if (arguments.length === 2 && typeof test === 'object') {
options = test;
test = false;
}
if (!options) {
(0, _deprecate.default)(missingOptionsDeprecation, false, {
id: 'ember-debug.warn-options-missing',
until: '3.0.0',
url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options'
});
}
if (options && !options.id) {
(0, _deprecate.default)(missingOptionsIdDeprecation, false, {
id: 'ember-debug.warn-id-missing',
until: '3.0.0',
url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options'
});
}
(0, _handlers.invoke)('warn', message, test, options);
};
exports.default = warn;
exports.registerHandler = registerHandler;
exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation;
exports.missingOptionsDeprecation = missingOptionsDeprecation;
});
enifed('ember-environment', ['exports'], function (exports) {
'use strict';
/* globals global, window, self, mainContext */
// from lodash to catch fake globals
function checkGlobal(value) {
return value && value.Object === Object ? value : undefined;
}
// element ids can ruin global miss checks
// export real global
var global$1 = checkGlobal(function (value) {
return value && value.nodeType === undefined ? value : undefined;
}(typeof global === 'object' && global)) || checkGlobal(typeof self === 'object' && self) || checkGlobal(typeof window === 'object' && window) || mainContext || // set before strict mode in Ember loader/wrapper
new Function('return this')(); // eval outside of strict mode
function defaultTrue(v) {
return v === false ? false : true;
}
function defaultFalse(v) {
return v === true ? true : false;
}
/* globals module */
/**
The hash of environment variables used to control various configuration
settings. To specify your own or override default settings, add the
desired properties to a global hash named `EmberENV` (or `ENV` for
backwards compatibility with earlier versions of Ember). The `EmberENV`
hash must be created before loading Ember.
@class EmberENV
@type Object
@public
*/
var ENV = typeof global$1.EmberENV === 'object' && global$1.EmberENV || typeof global$1.ENV === 'object' && global$1.ENV || {};
// ENABLE_ALL_FEATURES was documented, but you can't actually enable non optional features.
if (ENV.ENABLE_ALL_FEATURES) {
ENV.ENABLE_OPTIONAL_FEATURES = true;
}
/**
Determines whether Ember should add to `Array`, `Function`, and `String`
native object prototypes, a few extra methods in order to provide a more
friendly API.
We generally recommend leaving this option set to true however, if you need
to turn it off, you can add the configuration property
`EXTEND_PROTOTYPES` to `EmberENV` and set it to `false`.
Note, when disabled (the default configuration for Ember Addons), you will
instead have to access all methods and functions from the Ember
namespace.
@property EXTEND_PROTOTYPES
@type Boolean
@default true
@for EmberENV
@public
*/
ENV.EXTEND_PROTOTYPES = function (obj) {
if (obj === false) {
return { String: false, Array: false, Function: false };
} else if (!obj || obj === true) {
return { String: true, Array: true, Function: true };
} else {
return {
String: defaultTrue(obj.String),
Array: defaultTrue(obj.Array),
Function: defaultTrue(obj.Function)
};
}
}(ENV.EXTEND_PROTOTYPES);
/**
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
*/
ENV.LOG_STACKTRACE_ON_DEPRECATION = defaultTrue(ENV.LOG_STACKTRACE_ON_DEPRECATION);
/**
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
*/
ENV.LOG_VERSION = defaultTrue(ENV.LOG_VERSION);
/**
Debug parameter you can turn on. This will log all bindings that fire to
the console. This should be disabled in production code. Note that you
can also enable this from the console or temporarily.
@property LOG_BINDINGS
@for EmberENV
@type Boolean
@default false
@public
*/
ENV.LOG_BINDINGS = defaultFalse(ENV.LOG_BINDINGS);
ENV.RAISE_ON_DEPRECATION = defaultFalse(ENV.RAISE_ON_DEPRECATION);
// check if window exists and actually is the global
var hasDOM = typeof window !== 'undefined' && window === global$1 && window.document && window.document.createElement && !ENV.disableBrowserEnvironment; // is this a public thing?
// legacy imports/exports/lookup stuff (should we keep this??)
var originalContext = global$1.Ember || {};
var context = {
// import jQuery
imports: originalContext.imports || global$1,
// export Ember
exports: originalContext.exports || global$1,
// search for Namespaces
lookup: originalContext.lookup || global$1
};
// TODO: cleanup single source of truth issues with this stuff
var environment = hasDOM ? {
hasDOM: true,
isChrome: !!window.chrome && !window.opera,
isFirefox: typeof InstallTrigger !== 'undefined',
isPhantom: !!window.callPhantom,
location: window.location,
history: window.history,
userAgent: window.navigator.userAgent,
window: window
} : {
hasDOM: false,
isChrome: false,
isFirefox: false,
isPhantom: false,
location: null,
history: null,
userAgent: 'Lynx (textmode)',
window: null
};
exports.ENV = ENV;
exports.context = context;
exports.environment = environment;
});
enifed('ember-metal', ['exports', 'ember-environment', 'ember-utils', 'ember-debug', 'ember-babel', 'ember/features', '@glimmer/reference', 'require', 'ember-console', 'backburner'], function (exports, emberEnvironment, emberUtils, emberDebug, emberBabel, ember_features, _glimmer_reference, require, Logger, Backburner) {
'use strict';
var require__default = 'default' in require ? require['default'] : require,
counter,
inTransaction,
shouldReflush,
debugStack,
_hasOwnProperty,
_propertyIsEnumerable,
getPrototypeOf,
metaStore,
setWithMandatorySetter,
makeEnumerable;
Logger = 'default' in Logger ? Logger['default'] : Logger;
Backburner = 'default' in Backburner ? Backburner['default'] : Backburner;
/**
@module ember
@submodule ember-metal
*/
/**
This namespace contains all Ember methods and functions. Future versions of
Ember may overwrite this namespace and therefore, you should avoid adding any
new properties.
At the heart of Ember is Ember-Runtime, a set of core functions that provide
cross-platform compatibility and object property observing. Ember-Runtime is
small and performance-focused so you can use it alongside other
cross-platform libraries such as jQuery. For more details, see
[Ember-Runtime](http://emberjs.com/api/modules/ember-runtime.html).
@class Ember
@static
@public
*/
var Ember = typeof emberEnvironment.context.imports.Ember === 'object' && emberEnvironment.context.imports.Ember || {};
// Make sure these are set whether Ember was already defined or not
Ember.isNamespace = true;
Ember.toString = function () {
return 'Ember';
};
/*
When we render a rich template hierarchy, the set of events that
*might* happen tends to be much larger than the set of events that
actually happen. This implies that we should make listener creation &
destruction cheap, even at the cost of making event dispatch more
expensive.
Thus we store a new listener with a single push and no new
allocations, without even bothering to do deduplication -- we can
save that for dispatch time, if an event actually happens.
*/
/* listener flags */
var ONCE = 1;
var SUSPENDED = 2;
var protoMethods = {
addToListeners: function (eventName, target, method, flags) {
if (!this._listeners) {
this._listeners = [];
}
this._listeners.push(eventName, target, method, flags);
},
_finalizeListeners: function () {
if (this._listenersFinalized) {
return;
}
if (!this._listeners) {
this._listeners = [];
}
var pointer = this.parent,
listeners;
while (pointer) {
listeners = pointer._listeners;
if (listeners) {
this._listeners = this._listeners.concat(listeners);
}
if (pointer._listenersFinalized) {
break;
}
pointer = pointer.parent;
}
this._listenersFinalized = true;
},
removeFromListeners: function (eventName, target, method, didRemove) {
var pointer = this,
listeners,
index;
while (pointer) {
listeners = pointer._listeners;
if (listeners) {
for (index = listeners.length - 4; index >= 0; index -= 4) {
if (listeners[index] === eventName && (!method || listeners[index + 1] === target && listeners[index + 2] === method)) {
if (pointer === this) {
// we are modifying our own list, so we edit directly
if (typeof didRemove === 'function') {
didRemove(eventName, target, listeners[index + 2]);
}
listeners.splice(index, 4);
} else {
// we are trying to remove an inherited listener, so we do
// just-in-time copying to detach our own listeners from
// our inheritance chain.
this._finalizeListeners();
return this.removeFromListeners(eventName, target, method);
}
}
}
}
if (pointer._listenersFinalized) {
break;
}
pointer = pointer.parent;
}
},
matchingListeners: function (eventName) {
var pointer = this,
listeners,
index,
susIndex,
resultIndex;
var result = void 0;
while (pointer !== undefined) {
listeners = pointer._listeners;
if (listeners !== undefined) {
for (index = 0; index < listeners.length - 3; index += 4) {
if (listeners[index] === eventName) {
result = result || [];
pushUniqueListener(result, listeners, index);
}
}
}
if (pointer._listenersFinalized === true) {
break;
}
pointer = pointer.parent;
}
var sus = this._suspendedListeners;
if (sus !== undefined && result !== undefined) {
for (susIndex = 0; susIndex < sus.length - 2; susIndex += 3) {
if (eventName === sus[susIndex]) {
for (resultIndex = 0; resultIndex < result.length - 2; resultIndex += 3) {
if (result[resultIndex] === sus[susIndex + 1] && result[resultIndex + 1] === sus[susIndex + 2]) {
result[resultIndex + 2] |= SUSPENDED;
}
}
}
}
}
return result;
},
suspendListeners: function (eventNames, target, method, callback) {
var sus = this._suspendedListeners,
i,
_i;
if (!sus) {
sus = this._suspendedListeners = [];
}
for (i = 0; i < eventNames.length; i++) {
sus.push(eventNames[i], target, method);
}
try {
return callback.call(target);
} finally {
if (sus.length === eventNames.length) {
this._suspendedListeners = undefined;
} else {
for (_i = sus.length - 3; _i >= 0; _i -= 3) {
if (sus[_i + 1] === target && sus[_i + 2] === method && eventNames.indexOf(sus[_i]) !== -1) {
sus.splice(_i, 3);
}
}
}
}
},
watchedEvents: function () {
var pointer = this,
listeners,
index;
var names = {};
while (pointer) {
listeners = pointer._listeners;
if (listeners) {
for (index = 0; index < listeners.length - 3; index += 4) {
names[listeners[index]] = true;
}
}
if (pointer._listenersFinalized) {
break;
}
pointer = pointer.parent;
}
return Object.keys(names);
},
_initializeListeners: function () {
this._listeners = undefined;
this._listenersFinalized = undefined;
this._suspendedListeners = undefined;
}
};
function pushUniqueListener(destination, source, index) {
var target = source[index + 1],
destinationIndex;
var method = source[index + 2];
for (destinationIndex = 0; destinationIndex < destination.length - 2; destinationIndex += 3) {
if (destination[destinationIndex] === target && destination[destinationIndex + 1] === method) {
return;
}
}
destination.push(target, method, source[index + 3]);
}
/**
@module ember
@submodule ember-metal
*/
/*
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:changed": [ // variable name: `actions`
target, method, flags
]
}
}
*/
function indexOf(array, target, method) {
var index = -1,
i;
// hashes are added to the end of the event array
// so it makes sense to start searching at the end
// of the array and search in reverse
for (i = array.length - 3; i >= 0; i -= 3) {
if (target === array[i] && method === array[i + 1]) {
index = i;
break;
}
}
return index;
}
function accumulateListeners(obj, eventName, otherActions) {
var meta$$1 = exports.peekMeta(obj),
i,
target,
method,
flags,
actionIndex;
if (!meta$$1) {
return;
}
var actions = meta$$1.matchingListeners(eventName);
if (actions === undefined) {
return;
}
var newActions = [];
for (i = actions.length - 3; i >= 0; i -= 3) {
target = actions[i];
method = actions[i + 1];
flags = actions[i + 2];
actionIndex = indexOf(otherActions, target, method);
if (actionIndex === -1) {
otherActions.push(target, method, flags);
newActions.push(target, method, flags);
}
}
return newActions;
}
/**
Add an event listener
@method addListener
@for Ember
@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) {
true && !(!!obj && !!eventName) && emberDebug.assert('You must pass at least an object and event name to Ember.addListener', !!obj && !!eventName);
true && !(eventName !== 'didInitAttrs') && emberDebug.deprecate('didInitAttrs called in ' + (obj && obj.toString && obj.toString()) + '.', eventName !== 'didInitAttrs', {
id: 'ember-views.did-init-attrs',
until: '3.0.0',
url: 'http://emberjs.com/deprecations/v2.x#toc_ember-component-didinitattrs'
});
if (!method && 'function' === typeof target) {
method = target;
target = null;
}
var flags = 0;
if (once) {
flags |= ONCE;
}
meta(obj).addToListeners(eventName, target, method, flags);
if ('function' === typeof obj.didAddListener) {
obj.didAddListener(eventName, target, method);
}
}
/**
Remove an event listener
Arguments should match those passed to `Ember.addListener`.
@method removeListener
@for Ember
@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, target, method) {
true && !(!!obj && !!eventName) && emberDebug.assert('You must pass at least an object and event name to Ember.removeListener', !!obj && !!eventName);
if (!method && 'function' === typeof target) {
method = target;
target = null;
}
meta(obj).removeFromListeners(eventName, target, method, function () {
if ('function' === typeof obj.didRemoveListener) {
obj.didRemoveListener.apply(obj, arguments);
}
});
}
/**
Suspend listener during callback.
This should only be used by the target of the event listener
when it is taking an action that would cause the event, e.g.
an object might suspend its property change listener while it is
setting that property.
@method suspendListener
@for Ember
@private
@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 {Function} callback
*/
function suspendListener(obj, eventName, target, method, callback) {
return suspendListeners(obj, [eventName], target, method, callback);
}
/**
Suspends multiple listeners during a callback.
@method suspendListeners
@for Ember
@private
@param obj
@param {Array} eventNames Array of event names
@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 {Function} callback
*/
function suspendListeners(obj, eventNames, target, method, callback) {
if (!method && 'function' === typeof target) {
method = target;
target = null;
}
return meta(obj).suspendListeners(eventNames, target, method, callback);
}
/**
Return a list of currently watched events
@private
@method watchedEvents
@for Ember
@param obj
*/
/**
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
@for Ember
@param obj
@param {String} eventName
@param {Array} params Optional parameters for each listener.
@param {Array} actions Optional array of actions (listeners).
@param {Meta} meta Optional meta to lookup listeners
@return true
@public
*/
function sendEvent(obj, eventName, params, actions, _meta) {
var meta$$1, i, target, method, flags;
if (actions === undefined) {
meta$$1 = _meta || exports.peekMeta(obj);
actions = typeof meta$$1 === 'object' && meta$$1 !== null && meta$$1.matchingListeners(eventName);
}
if (actions === undefined || actions.length === 0) {
return;
}
for (i = actions.length - 3; i >= 0; i -= 3) {
// looping in reverse for once listeners
target = actions[i];
method = actions[i + 1];
flags = actions[i + 2];
if (!method) {
continue;
}
if (flags & SUSPENDED) {
continue;
}
if (flags & ONCE) {
removeListener(obj, eventName, target, method);
}
if (!target) {
target = obj;
}
if ('string' === typeof method) {
if (params) {
emberUtils.applyStr(target, method, params);
} else {
target[method]();
}
} else {
if (params) {
method.apply(target, params);
} else {
method.call(target);
}
}
}
return true;
}
/**
@private
@method hasListeners
@for Ember
@param obj
@param {String} eventName
*/
/**
@private
@method listenersFor
@for Ember
@param obj
@param {String} eventName
*/
function listenersFor(obj, eventName) {
var ret = [],
i,
target,
method;
var meta$$1 = exports.peekMeta(obj);
var actions = meta$$1 && meta$$1.matchingListeners(eventName);
if (!actions) {
return ret;
}
for (i = 0; i < actions.length; i += 3) {
target = actions[i];
method = actions[i + 1];
ret.push([target, method]);
}
return ret;
}
/**
Define a property as a function that should be executed when
a specified event or events are triggered.
``` javascript
let Job = Ember.Object.extend({
logCompleted: Ember.on('completed', function() {
console.log('Job completed!');
})
});
let job = Job.create();
Ember.sendEvent(job, 'completed'); // Logs 'Job completed!'
```
@method on
@for Ember
@param {String} eventNames*
@param {Function} func
@return func
@public
*/
var hasViews = function () {
return false;
};
function makeTag() {
return new _glimmer_reference.DirtyableTag();
}
function tagFor(object, _meta) {
var meta$$1;
if (typeof object === 'object' && object) {
meta$$1 = _meta || meta(object);
return meta$$1.writableTag(makeTag);
} else {
return _glimmer_reference.CONSTANT_TAG;
}
}
function markObjectAsDirty(meta$$1, propertyKey) {
var objectTag = meta$$1.readableTag();
if (objectTag) {
objectTag.dirty();
}
var tags = meta$$1.readableTags();
var propertyTag = tags && tags[propertyKey];
if (propertyTag) {
propertyTag.dirty();
}
if (propertyKey === 'content' && meta$$1.isProxy()) {
meta$$1.getTag().contentDidChange();
}
if (objectTag || propertyTag) {
ensureRunloop();
}
}
var run = void 0;
function K() {}
function ensureRunloop() {
if (!run) {
run = require__default('ember-metal').run;
}
if (hasViews() && !run.backburner.currentInstance) {
run.schedule('actions', K);
}
}
/*
this.observerSet = {
[senderGuid]: { // variable name: `keySet`
[keyName]: listIndex
}
},
this.observers = [
{
sender: obj,
keyName: keyName,
eventName: eventName,
listeners: [
[target, method, flags]
]
},
...
]
*/
var ObserverSet = function () {
function ObserverSet() {
this.clear();
}
ObserverSet.prototype.add = function (sender, keyName, eventName) {
var observerSet = this.observerSet;
var observers = this.observers;
var senderGuid = emberUtils.guidFor(sender);
var keySet = observerSet[senderGuid];
var index = void 0;
if (!keySet) {
observerSet[senderGuid] = keySet = {};
}
index = keySet[keyName];
if (index === undefined) {
index = observers.push({
sender: sender,
keyName: keyName,
eventName: eventName,
listeners: []
}) - 1;
keySet[keyName] = index;
}
return observers[index].listeners;
};
ObserverSet.prototype.flush = function () {
var observers = this.observers;
var i = void 0,
observer = void 0,
sender = void 0;
this.clear();
for (i = 0; i < observers.length; ++i) {
observer = observers[i];
sender = observer.sender;
if (sender.isDestroying || sender.isDestroyed) {
continue;
}
sendEvent(sender, observer.eventName, [sender, observer.keyName], observer.listeners);
}
};
ObserverSet.prototype.clear = function () {
this.observerSet = {};
this.observers = [];
};
return ObserverSet;
}();
exports.runInTransaction = void 0;
exports.didRender = void 0;
exports.assertNotRendered = void 0;
// detect-backtracking-rerender by default is debug build only
// detect-glimmer-allow-backtracking-rerender can be enabled in custom builds
if (ember_features.EMBER_GLIMMER_DETECT_BACKTRACKING_RERENDER || ember_features.EMBER_GLIMMER_ALLOW_BACKTRACKING_RERENDER) {
counter = 0;
inTransaction = false;
shouldReflush = void 0;
debugStack = void 0;
exports.runInTransaction = function (context$$1, methodName) {
shouldReflush = false;
inTransaction = true;
{
debugStack = context$$1.env.debugStack;
}
context$$1[methodName]();
inTransaction = false;
counter++;
return shouldReflush;
};
exports.didRender = function (object, key, reference) {
if (!inTransaction) {
return;
}
var meta$$1 = meta(object),
referenceMap,
templateMap;
var lastRendered = meta$$1.writableLastRendered();
lastRendered[key] = counter;
{
referenceMap = meta$$1.writableLastRenderedReferenceMap();
referenceMap[key] = reference;
templateMap = meta$$1.writableLastRenderedTemplateMap();
if (templateMap[key] === undefined) {
templateMap[key] = debugStack.peek();
}
}
};
exports.assertNotRendered = function (object, key, _meta) {
var meta$$1 = _meta || meta(object),
templateMap,
lastRenderedIn,
currentlyIn,
referenceMap,
lastRef,
parts,
label,
message;
var lastRendered = meta$$1.readableLastRendered();
if (lastRendered && lastRendered[key] === counter) {
{
templateMap = meta$$1.readableLastRenderedTemplateMap();
lastRenderedIn = templateMap[key];
currentlyIn = debugStack.peek();
referenceMap = meta$$1.readableLastRenderedReferenceMap();
lastRef = referenceMap[key];
parts = [];
label = void 0;
if (lastRef) {
while (lastRef && lastRef._propertyKey) {
parts.unshift(lastRef._propertyKey);
lastRef = lastRef._parentReference;
}
label = parts.join('.');
} else {
label = 'the same value';
}
message = 'You modified "' + label + '" twice on ' + object + ' in a single render. It was rendered in ' + lastRenderedIn + ' and modified in ' + currentlyIn + '. This was unreliable and slow in Ember 1.x and';
if (ember_features.EMBER_GLIMMER_ALLOW_BACKTRACKING_RERENDER) {
true && !false && emberDebug.deprecate(message + ' will be removed in Ember 3.0.', false, { id: 'ember-views.render-double-modify', until: '3.0.0' });
} else {
true && !false && emberDebug.assert(message + ' is no longer supported. See https://github.com/emberjs/ember.js/issues/13948 for more details.', false);
}
}
shouldReflush = true;
}
};
} else {
// in production do nothing to detect reflushes
exports.runInTransaction = function (context$$1, methodName) {
context$$1[methodName]();
return false;
};
}
var PROPERTY_DID_CHANGE = emberUtils.symbol('PROPERTY_DID_CHANGE');
var beforeObserverSet = new ObserverSet();
var observerSet = new ObserverSet();
var deferred = 0;
// ..........................................................
// PROPERTY CHANGES
//
/**
This function is called just before an object property is about to change.
It will notify any before observers and prepare 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 along with `Ember.propertyDidChange()` which you should call just
after the property value changes.
@method propertyWillChange
@for Ember
@param {Object} obj The object with the property that will change
@param {String} keyName The property key (or path) that will change.
@return {void}
@private
*/
function propertyWillChange(obj, keyName, _meta) {
var meta$$1 = _meta || exports.peekMeta(obj);
if (meta$$1 && !meta$$1.isInitialized(obj)) {
return;
}
var watching = meta$$1 && meta$$1.peekWatching(keyName) > 0;
var possibleDesc = obj[keyName];
var desc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined;
if (desc && desc.willChange) {
desc.willChange(obj, keyName);
}
if (watching) {
dependentKeysWillChange(obj, keyName, meta$$1);
chainsWillChange(obj, keyName, meta$$1);
notifyBeforeObservers(obj, keyName, meta$$1);
}
}
/**
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 along with `Ember.propertyWillChange()` which you should call just
before the property value changes.
@method propertyDidChange
@for Ember
@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.
@return {void}
@private
*/
function propertyDidChange(obj, keyName, _meta) {
var meta$$1 = _meta || exports.peekMeta(obj);
var hasMeta = !!meta$$1;
if (hasMeta && !meta$$1.isInitialized(obj)) {
return;
}
var possibleDesc = obj[keyName];
var desc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined;
// shouldn't this mean that we're watching this key?
if (desc && desc.didChange) {
desc.didChange(obj, keyName);
}
if (hasMeta && meta$$1.peekWatching(keyName) > 0) {
if (meta$$1.hasDeps(keyName) && !meta$$1.isSourceDestroying()) {
dependentKeysDidChange(obj, keyName, meta$$1);
}
chainsDidChange(obj, keyName, meta$$1, false);
notifyObservers(obj, keyName, meta$$1);
}
if (obj[PROPERTY_DID_CHANGE]) {
obj[PROPERTY_DID_CHANGE](keyName);
}
if (hasMeta) {
if (meta$$1.isSourceDestroying()) {
return;
}
markObjectAsDirty(meta$$1, keyName);
}
if (ember_features.EMBER_GLIMMER_DETECT_BACKTRACKING_RERENDER || ember_features.EMBER_GLIMMER_ALLOW_BACKTRACKING_RERENDER) {
exports.assertNotRendered(obj, keyName, meta$$1);
}
}
var WILL_SEEN = void 0;
var DID_SEEN = void 0;
// called whenever a property is about to change to clear the cache of any dependent keys (and notify those properties of changes, etc...)
function dependentKeysWillChange(obj, depKey, meta$$1) {
var seen, top;
if (meta$$1.isSourceDestroying()) {
return;
}
if (meta$$1.hasDeps(depKey)) {
seen = WILL_SEEN;
top = !seen;
if (top) {
seen = WILL_SEEN = {};
}
iterDeps(propertyWillChange, obj, depKey, seen, meta$$1);
if (top) {
WILL_SEEN = null;
}
}
}
// called whenever a property has just changed to update dependent keys
function dependentKeysDidChange(obj, depKey, meta$$1) {
var seen = DID_SEEN;
var top = !seen;
if (top) {
seen = DID_SEEN = {};
}
iterDeps(propertyDidChange, obj, depKey, seen, meta$$1);
if (top) {
DID_SEEN = null;
}
}
function iterDeps(method, obj, depKey, seen, meta$$1) {
var possibleDesc = void 0,
desc = void 0;
var guid = emberUtils.guidFor(obj);
var current = seen[guid];
if (!current) {
current = seen[guid] = {};
}
if (current[depKey]) {
return;
}
current[depKey] = true;
meta$$1.forEachInDeps(depKey, function (key, value) {
if (!value) {
return;
}
possibleDesc = obj[key];
desc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined;
if (desc && desc._suspended === obj) {
return;
}
method(obj, key, meta$$1);
});
}
function chainsWillChange(obj, keyName, meta$$1) {
var chainWatchers = meta$$1.readableChainWatchers();
if (chainWatchers) {
chainWatchers.notify(keyName, false, propertyWillChange);
}
}
function chainsDidChange(obj, keyName, meta$$1) {
var chainWatchers = meta$$1.readableChainWatchers();
if (chainWatchers) {
chainWatchers.notify(keyName, true, propertyDidChange);
}
}
function overrideChains(obj, keyName, meta$$1) {
var chainWatchers = meta$$1.readableChainWatchers();
if (chainWatchers) {
chainWatchers.revalidate(keyName);
}
}
/**
@method beginPropertyChanges
@chainable
@private
*/
function beginPropertyChanges() {
deferred++;
}
/**
@method endPropertyChanges
@private
*/
function endPropertyChanges() {
deferred--;
if (deferred <= 0) {
beforeObserverSet.clear();
observerSet.flush();
}
}
/**
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
@param [binding]
@private
*/
function changeProperties(callback, binding) {
beginPropertyChanges();
try {
callback.call(binding);
} finally {
endPropertyChanges.call(binding);
}
}
function notifyBeforeObservers(obj, keyName, meta$$1) {
if (meta$$1.isSourceDestroying()) {
return;
}
var eventName = keyName + ':before';
var listeners = void 0,
added = void 0;
if (deferred) {
listeners = beforeObserverSet.add(obj, keyName, eventName);
added = accumulateListeners(obj, eventName, listeners);
sendEvent(obj, eventName, [obj, keyName], added);
} else {
sendEvent(obj, eventName, [obj, keyName]);
}
}
function notifyObservers(obj, keyName, meta$$1) {
if (meta$$1.isSourceDestroying()) {
return;
}
var eventName = keyName + ':change';
var listeners = void 0;
if (deferred) {
listeners = observerSet.add(obj, keyName, eventName);
accumulateListeners(obj, eventName, listeners);
} else {
sendEvent(obj, eventName, [obj, keyName]);
}
}
/**
@module ember-metal
*/
// ..........................................................
// DESCRIPTOR
//
/**
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
*/
function Descriptor() {
this.isDescriptor = true;
}
var REDEFINE_SUPPORTED = function () {
// https://github.com/spalger/kibana/commit/b7e35e6737df585585332857a4c397dc206e7ff9
var a = Object.create(Object.prototype, {
prop: {
configurable: true,
value: 1
}
});
Object.defineProperty(a, 'prop', {
configurable: true,
value: 2
});
return a.prop === 2;
}();
// ..........................................................
// DEFINING PROPERTIES API
//
function MANDATORY_SETTER_FUNCTION(name) {
function SETTER_FUNCTION(value) {
var m = exports.peekMeta(this);
if (!m.isInitialized(this)) {
m.writeValues(name, value);
} else {
true && !false && emberDebug.assert('You must use Ember.set() to set the `' + name + '` property (of ' + this + ') to `' + value + '`.', false);
}
}
SETTER_FUNCTION.isMandatorySetter = true;
return SETTER_FUNCTION;
}
function DEFAULT_GETTER_FUNCTION(name) {
return function () {
var meta$$1 = exports.peekMeta(this);
return meta$$1 && meta$$1.peekValues(name);
};
}
function INHERITING_GETTER_FUNCTION(name) {
function IGETTER_FUNCTION() {
var meta$$1 = exports.peekMeta(this),
proto;
var val = meta$$1 && meta$$1.readInheritedValue('values', name);
if (val === UNDEFINED) {
proto = Object.getPrototypeOf(this);
return proto && proto[name];
} else {
return val;
}
}
IGETTER_FUNCTION.isInheritingGetter = true;
return IGETTER_FUNCTION;
}
/**
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
`Ember.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
// ES5 compatible mode
Ember.defineProperty(contact, 'firstName', {
writable: true,
configurable: false,
enumerable: true,
value: 'Charles'
});
// define a simple property
Ember.defineProperty(contact, 'lastName', undefined, 'Jolley');
// define a computed property
Ember.defineProperty(contact, 'fullName', Ember.computed('firstName', 'lastName', function() {
return this.firstName+' '+this.lastName;
}));
```
@private
@method defineProperty
@for Ember
@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$$1) {
if (!meta$$1) {
meta$$1 = meta(obj);
}
var watchEntry = meta$$1.peekWatching(keyName),
defaultDescriptor;
var possibleDesc = obj[keyName];
var existingDesc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined;
var watching = watchEntry !== undefined && watchEntry > 0;
if (existingDesc) {
existingDesc.teardown(obj, keyName);
}
var value = void 0;
if (desc instanceof Descriptor) {
value = desc;
if (ember_features.MANDATORY_SETTER) {
if (watching) {
Object.defineProperty(obj, keyName, {
configurable: true,
enumerable: true,
writable: true,
value: value
});
} else {
obj[keyName] = value;
}
} else {
obj[keyName] = value;
}
didDefineComputedProperty(obj.constructor);
if (typeof desc.setup === 'function') {
desc.setup(obj, keyName);
}
} else {
if (desc == null) {
value = data;
if (ember_features.MANDATORY_SETTER) {
if (watching) {
meta$$1.writeValues(keyName, data);
defaultDescriptor = {
configurable: true,
enumerable: true,
set: MANDATORY_SETTER_FUNCTION(keyName),
get: DEFAULT_GETTER_FUNCTION(keyName)
};
if (REDEFINE_SUPPORTED) {
Object.defineProperty(obj, keyName, defaultDescriptor);
} else {
handleBrokenPhantomDefineProperty(obj, keyName, defaultDescriptor);
}
} else {
obj[keyName] = data;
}
} else {
obj[keyName] = data;
}
} else {
value = desc;
// fallback to ES5
Object.defineProperty(obj, keyName, desc);
}
}
// if key is being watched, override chains that
// were initialized with the prototype
if (watching) {
overrideChains(obj, keyName, meta$$1);
}
// The `value` passed to the `didDefineProperty` hook is
// either the descriptor or data, whichever was passed.
if (typeof obj.didDefineProperty === 'function') {
obj.didDefineProperty(obj, keyName, value);
}
return this;
}
var hasCachedComputedProperties = false;
function didDefineComputedProperty(constructor) {
if (hasCachedComputedProperties === false) {
return;
}
var cache = meta(constructor).readableCache();
if (cache && cache._computedProperties !== undefined) {
cache._computedProperties = undefined;
}
}
function handleBrokenPhantomDefineProperty(obj, keyName, desc) {
// https://github.com/ariya/phantomjs/issues/11856
Object.defineProperty(obj, keyName, { configurable: true, writable: true, value: 'iCry' });
Object.defineProperty(obj, keyName, desc);
}
var handleMandatorySetter = void 0;
function watchKey(obj, keyName, meta$$1) {
if (typeof obj !== 'object' || obj === null) {
return;
}
var m = meta$$1 || meta(obj),
possibleDesc,
desc;
// activate watching first time
if (!m.peekWatching(keyName)) {
m.writeWatching(keyName, 1);
possibleDesc = obj[keyName];
desc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined;
if (desc && desc.willWatch) {
desc.willWatch(obj, keyName);
}
if ('function' === typeof obj.willWatchProperty) {
obj.willWatchProperty(keyName);
}
if (ember_features.MANDATORY_SETTER) {
// NOTE: this is dropped for prod + minified builds
handleMandatorySetter(m, obj, keyName);
}
} else {
m.writeWatching(keyName, (m.peekWatching(keyName) || 0) + 1);
}
}
if (ember_features.MANDATORY_SETTER) {
_hasOwnProperty = function (obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
};
_propertyIsEnumerable = function (obj, key) {
return Object.prototype.propertyIsEnumerable.call(obj, key);
};
// Future traveler, although this code looks scary. It merely exists in
// development to aid in development asertions. Production builds of
// ember strip this entire block out
handleMandatorySetter = function (m, obj, keyName) {
var descriptor = emberUtils.lookupDescriptor(obj, keyName),
desc;
var configurable = descriptor ? descriptor.configurable : true;
var isWritable = descriptor ? descriptor.writable : true;
var hasValue = descriptor ? 'value' in descriptor : true;
var possibleDesc = descriptor && descriptor.value;
var isDescriptor = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor;
if (isDescriptor) {
return;
}
// this x in Y deopts, so keeping it in this function is better;
if (configurable && isWritable && hasValue && keyName in obj) {
desc = {
configurable: true,
set: MANDATORY_SETTER_FUNCTION(keyName),
enumerable: _propertyIsEnumerable(obj, keyName),
get: undefined
};
if (_hasOwnProperty(obj, keyName)) {
m.writeValues(keyName, obj[keyName]);
desc.get = DEFAULT_GETTER_FUNCTION(keyName);
} else {
desc.get = INHERITING_GETTER_FUNCTION(keyName);
}
Object.defineProperty(obj, keyName, desc);
}
};
}
function unwatchKey(obj, keyName, _meta) {
if (typeof obj !== 'object' || obj === null) {
return;
}
var meta$$1 = _meta || meta(obj),
possibleDesc,
desc,
maybeMandatoryDescriptor,
possibleValue;
// do nothing of this object has already been destroyed
if (meta$$1.isSourceDestroyed()) {
return;
}
var count = meta$$1.peekWatching(keyName);
if (count === 1) {
meta$$1.writeWatching(keyName, 0);
possibleDesc = obj[keyName];
desc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined;
if (desc && desc.didUnwatch) {
desc.didUnwatch(obj, keyName);
}
if ('function' === typeof obj.didUnwatchProperty) {
obj.didUnwatchProperty(keyName);
}
if (ember_features.MANDATORY_SETTER) {
// It is true, the following code looks quite WAT. But have no fear, It
// exists purely to improve development ergonomics and is removed from
// ember.min.js and ember.prod.js builds.
//
// Some further context: Once a property is watched by ember, bypassing `set`
// for mutation, will bypass observation. This code exists to assert when
// that occurs, and attempt to provide more helpful feedback. The alternative
// is tricky to debug partially observable properties.
if (!desc && keyName in obj) {
maybeMandatoryDescriptor = emberUtils.lookupDescriptor(obj, keyName);
if (maybeMandatoryDescriptor.set && maybeMandatoryDescriptor.set.isMandatorySetter) {
if (maybeMandatoryDescriptor.get && maybeMandatoryDescriptor.get.isInheritingGetter) {
possibleValue = meta$$1.readInheritedValue('values', keyName);
if (possibleValue === UNDEFINED) {
delete obj[keyName];
return;
}
}
Object.defineProperty(obj, keyName, {
configurable: true,
enumerable: Object.prototype.propertyIsEnumerable.call(obj, keyName),
writable: true,
value: meta$$1.peekValues(keyName)
});
meta$$1.deleteFromValues(keyName);
}
}
}
} else if (count > 1) {
meta$$1.writeWatching(keyName, count - 1);
}
}
// get the chains for the current object. If the current object has
// chains inherited from the proto they will be cloned and reconfigured for
// the current object.
function chainsFor(obj, meta$$1) {
return (meta$$1 || meta(obj)).writableChains(makeChainNode);
}
function makeChainNode(obj) {
return new ChainNode(null, null, obj);
}
function watchPath(obj, keyPath, meta$$1) {
if (typeof obj !== 'object' || obj === null) {
return;
}
var m = meta$$1 || meta(obj);
var counter = m.peekWatching(keyPath) || 0;
if (!counter) {
// activate watching first time
m.writeWatching(keyPath, 1);
chainsFor(obj, m).add(keyPath);
} else {
m.writeWatching(keyPath, counter + 1);
}
}
function unwatchPath(obj, keyPath, meta$$1) {
if (typeof obj !== 'object' || obj === null) {
return;
}
var m = meta$$1 || meta(obj);
var counter = m.peekWatching(keyPath) || 0;
if (counter === 1) {
m.writeWatching(keyPath, 0);
chainsFor(obj, m).remove(keyPath);
} else if (counter > 1) {
m.writeWatching(keyPath, counter - 1);
}
}
var FIRST_KEY = /^([^\.]+)/;
function firstKey(path) {
return path.match(FIRST_KEY)[0];
}
function isObject(obj) {
return typeof obj === 'object' && obj;
}
function isVolatile(obj) {
return !(isObject(obj) && obj.isDescriptor && obj._volatile === false);
}
var ChainWatchers = function () {
function ChainWatchers() {
// chain nodes that reference a key in this obj by key
// we only create ChainWatchers when we are going to add them
// so create this upfront
this.chains = Object.create(null);
}
ChainWatchers.prototype.add = function (key, node) {
var nodes = this.chains[key];
if (nodes === undefined) {
this.chains[key] = [node];
} else {
nodes.push(node);
}
};
ChainWatchers.prototype.remove = function (key, node) {
var nodes = this.chains[key],
i;
if (nodes) {
for (i = 0; i < nodes.length; i++) {
if (nodes[i] === node) {
nodes.splice(i, 1);
break;
}
}
}
};
ChainWatchers.prototype.has = function (key, node) {
var nodes = this.chains[key],
i;
if (nodes) {
for (i = 0; i < nodes.length; i++) {
if (nodes[i] === node) {
return true;
}
}
}
return false;
};
ChainWatchers.prototype.revalidateAll = function () {
for (var key in this.chains) {
this.notify(key, true, undefined);
}
};
ChainWatchers.prototype.revalidate = function (key) {
this.notify(key, true, undefined);
};
// key: the string key that is part of a path changed
// revalidate: boolean; the chains that are watching this value should revalidate
// callback: function that will be called with the object and path that
// will be/are invalidated by this key change, depending on
// whether the revalidate flag is passed
ChainWatchers.prototype.notify = function (key, revalidate, callback) {
var nodes = this.chains[key],
i,
_i,
obj,
path;
if (nodes === undefined || nodes.length === 0) {
return;
}
var affected = void 0;
if (callback) {
affected = [];
}
for (i = 0; i < nodes.length; i++) {
nodes[i].notify(revalidate, affected);
}
if (callback === undefined) {
return;
}
// we gather callbacks so we don't notify them during revalidation
for (_i = 0; _i < affected.length; _i += 2) {
obj = affected[_i];
path = affected[_i + 1];
callback(obj, path);
}
};
return ChainWatchers;
}();
function makeChainWatcher() {
return new ChainWatchers();
}
function addChainWatcher(obj, keyName, node) {
var m = meta(obj);
m.writableChainWatchers(makeChainWatcher).add(keyName, node);
watchKey(obj, keyName, m);
}
function removeChainWatcher(obj, keyName, node, _meta) {
if (!isObject(obj)) {
return;
}
var meta$$1 = _meta || exports.peekMeta(obj);
if (!meta$$1 || !meta$$1.readableChainWatchers()) {
return;
}
// make meta writable
meta$$1 = meta(obj);
meta$$1.readableChainWatchers().remove(keyName, node);
unwatchKey(obj, keyName, meta$$1);
}
// A ChainNode watches a single key on an object. If you provide a starting
// value for the key then the node won't actually watch it. For a root node
// pass null for parent and key and object for value.
var ChainNode = function () {
function ChainNode(parent, key, value) {
this._parent = parent;
this._key = key;
// _watching is true when calling get(this._parent, this._key) will
// return the value of this node.
//
// It is false for the root of a chain (because we have no parent)
// and for global paths (because the parent node is the object with
// the observer on it)
var isWatching = this._watching = value === undefined,
obj;
this._chains = undefined;
this._object = undefined;
this.count = 0;
this._value = value;
this._paths = undefined;
if (isWatching === true) {
obj = parent.value();
if (!isObject(obj) === true) {
return;
}
this._object = obj;
addChainWatcher(this._object, this._key, this);
}
}
ChainNode.prototype.value = function () {
var obj;
if (this._value === undefined && this._watching === true) {
obj = this._parent.value();
this._value = lazyGet(obj, this._key);
}
return this._value;
};
ChainNode.prototype.destroy = function () {
var obj;
if (this._watching === true) {
obj = this._object;
if (obj) {
removeChainWatcher(obj, this._key, this);
}
this._watching = false; // so future calls do nothing
}
};
// copies a top level object only
ChainNode.prototype.copy = function (obj) {
var ret = new ChainNode(null, null, obj);
var paths = this._paths;
var path = void 0;
if (paths !== undefined) {
for (path in paths) {
// this check will also catch non-number vals.
if (paths[path] <= 0) {
continue;
}
ret.add(path);
}
}
return ret;
};
// called on the root node of a chain to setup watchers on the specified
// path.
ChainNode.prototype.add = function (path) {
var paths = this._paths || (this._paths = {});
paths[path] = (paths[path] || 0) + 1;
var key = firstKey(path);
var tail = path.slice(key.length + 1);
this.chain(key, tail);
};
// called on the root node of a chain to teardown watcher on the specified
// path
ChainNode.prototype.remove = function (path) {
var paths = this._paths;
if (paths === undefined) {
return;
}
if (paths[path] > 0) {
paths[path]--;
}
var key = firstKey(path);
var tail = path.slice(key.length + 1);
this.unchain(key, tail);
};
ChainNode.prototype.chain = function (key, path) {
var chains = this._chains;
var node = void 0;
if (chains === undefined) {
chains = this._chains = Object.create(null);
} else {
node = chains[key];
}
if (node === undefined) {
node = chains[key] = new ChainNode(this, key, undefined);
}
node.count++; // count chains...
// chain rest of path if there is one
if (path) {
key = firstKey(path);
path = path.slice(key.length + 1);
node.chain(key, path);
}
};
ChainNode.prototype.unchain = function (key, path) {
var chains = this._chains,
nextKey,
nextPath;
var node = chains[key];
// unchain rest of path first...
if (path && path.length > 1) {
nextKey = firstKey(path);
nextPath = path.slice(nextKey.length + 1);
node.unchain(nextKey, nextPath);
}
// delete node if needed.
node.count--;
if (node.count <= 0) {
chains[node._key] = undefined;
node.destroy();
}
};
ChainNode.prototype.notify = function (revalidate, affected) {
if (revalidate && this._watching === true) {
parentValue = this._parent.value();
if (parentValue !== this._object) {
if (this._object !== undefined) {
removeChainWatcher(this._object, this._key, this);
}
if (isObject(parentValue)) {
this._object = parentValue;
addChainWatcher(parentValue, this._key, this);
} else {
this._object = undefined;
}
}
this._value = undefined;
}
// then notify chains...
var chains = this._chains,
parentValue;
var node = void 0;
if (chains !== undefined) {
for (var key in chains) {
node = chains[key];
if (node !== undefined) {
node.notify(revalidate, affected);
}
}
}
if (affected && this._parent) {
this._parent.populateAffected(this._key, 1, affected);
}
};
ChainNode.prototype.populateAffected = function (path, depth, affected) {
if (this._key) {
path = this._key + '.' + path;
}
if (this._parent) {
this._parent.populateAffected(path, depth + 1, affected);
} else {
if (depth > 1) {
affected.push(this.value(), path);
}
}
};
return ChainNode;
}();
function lazyGet(obj, key) {
if (!isObject(obj)) {
return;
}
var meta$$1 = exports.peekMeta(obj),
cache;
// check if object meant only to be a prototype
if (meta$$1 !== undefined && meta$$1.proto === obj) {
return;
}
// Use `get` if the return value is an EachProxy or an uncacheable value.
if (isVolatile(obj[key]) === true) {
return get(obj, key);
// Otherwise attempt to get the cached value of the computed property
} else {
cache = meta$$1.readableCache();
if (cache) {
return cacheFor.get(cache, key);
}
}
}
var counters = {
peekCalls: 0,
peekParentCalls: 0,
peekPrototypeWalks: 0,
setCalls: 0,
deleteCalls: 0,
metaCalls: 0,
metaInstantiated: 0
};
/**
@module ember-metal
*/
/*
This declares several meta-programmed members on the Meta class. Such
meta!
In general, the `readable` variants will give you an object (if it
already exists) that you can read but should not modify. The
`writable` variants will give you a mutable object, and they will
create it if it didn't already exist.
The following methods will get generated metaprogrammatically, and
I'm including them here for greppability:
writableCache, readableCache, writeWatching,
peekWatching, clearWatching, writeMixins,
peekMixins, clearMixins, writeBindings,
peekBindings, clearBindings, writeValues,
peekValues, clearValues, writeDeps, forEachInDeps
writableChainWatchers, readableChainWatchers, writableChains,
readableChains, writableTag, readableTag, writableTags,
readableTags
*/
var members = {
cache: ownMap,
weak: ownMap,
watching: inheritedMap,
mixins: inheritedMap,
bindings: inheritedMap,
values: inheritedMap,
chainWatchers: ownCustomObject,
chains:
// Implements a member that provides an inheritable, lazily-created
// object using the method you provide. We will derived children from
// their parents by calling your object's `copy()` method.
function (name, Meta) {
var key = memberProperty(name);
var capitalized = capitalize(name);
Meta.prototype['writable' + capitalized] = function (create) {
true && !!this.isMetaDestroyed() && emberDebug.assert('Cannot call writable' + capitalized + ' after the object is destroyed.', !this.isMetaDestroyed());
var ret = this[key];
if (ret === undefined) {
if (this.parent) {
ret = this[key] = this.parent['writable' + capitalized](create).copy(this.source);
} else {
ret = this[key] = create(this.source);
}
}
return ret;
};
Meta.prototype['readable' + capitalized] = function () {
return this._getInherited(key);
};
},
tag: ownCustomObject,
tags: ownMap
};
// FLAGS
var SOURCE_DESTROYING = 1 << 1;
var SOURCE_DESTROYED = 1 << 2;
var META_DESTROYED = 1 << 3;
var IS_PROXY = 1 << 4;
if (ember_features.EMBER_GLIMMER_DETECT_BACKTRACKING_RERENDER || ember_features.EMBER_GLIMMER_ALLOW_BACKTRACKING_RERENDER) {
members.lastRendered = ownMap;
if (require.has('ember-debug')) {
//https://github.com/emberjs/ember.js/issues/14732
members.lastRenderedReferenceMap = ownMap;
members.lastRenderedTemplateMap = ownMap;
}
}
var memberNames = Object.keys(members);
var META_FIELD = '__ember_meta__';
var Meta = function () {
function Meta(obj, parentMeta) {
{
counters.metaInstantiated++;
}
this._cache = undefined;
this._weak = undefined;
this._watching = undefined;
this._mixins = undefined;
this._bindings = undefined;
this._values = undefined;
this._deps = undefined;
this._chainWatchers = undefined;
this._chains = undefined;
this._tag = undefined;
this._tags = undefined;
this._factory = undefined;
// initial value for all flags right now is false
// see FLAGS const for detailed list of flags used
this._flags = 0;
// used only internally
this.source = obj;
// when meta(obj).proto === obj, the object is intended to be only a
// prototype and doesn't need to actually be observable itself
this.proto = undefined;
// The next meta in our inheritance chain. We (will) track this
// explicitly instead of using prototypical inheritance because we
// have detailed knowledge of how each property should really be
// inherited, and we can optimize it much better than JS runtimes.
this.parent = parentMeta;
if (ember_features.EMBER_GLIMMER_DETECT_BACKTRACKING_RERENDER || ember_features.EMBER_GLIMMER_ALLOW_BACKTRACKING_RERENDER) {
this._lastRendered = undefined;
{
this._lastRenderedReferenceMap = undefined;
this._lastRenderedTemplateMap = undefined;
}
}
this._initializeListeners();
}
Meta.prototype.isInitialized = function (obj) {
return this.proto !== obj;
};
Meta.prototype.setTag = function (tag) {
this._tag = tag;
};
Meta.prototype.getTag = function () {
return this._tag;
};
Meta.prototype.destroy = function () {
if (this.isMetaDestroyed()) {
return;
}
// remove chainWatchers to remove circular references that would prevent GC
var nodes = void 0,
key = void 0,
nodeObject = void 0,
foreignMeta;
var node = this.readableChains();
if (node) {
NODE_STACK.push(node);
// process tree
while (NODE_STACK.length > 0) {
node = NODE_STACK.pop();
// push children
nodes = node._chains;
if (nodes) {
for (key in nodes) {
if (nodes[key] !== undefined) {
NODE_STACK.push(nodes[key]);
}
}
}
// remove chainWatcher in node object
if (node._watching) {
nodeObject = node._object;
if (nodeObject) {
foreignMeta = exports.peekMeta(nodeObject);
// avoid cleaning up chain watchers when both current and
// foreign objects are being destroyed
// if both are being destroyed manual cleanup is not needed
// as they will be GC'ed and no non-destroyed references will
// be remaining
if (foreignMeta && !foreignMeta.isSourceDestroying()) {
removeChainWatcher(nodeObject, node._key, node, foreignMeta);
}
}
}
}
}
this.setMetaDestroyed();
};
Meta.prototype.isSourceDestroying = function () {
return (this._flags & SOURCE_DESTROYING) !== 0;
};
Meta.prototype.setSourceDestroying = function () {
this._flags |= SOURCE_DESTROYING;
};
Meta.prototype.isSourceDestroyed = function () {
return (this._flags & SOURCE_DESTROYED) !== 0;
};
Meta.prototype.setSourceDestroyed = function () {
this._flags |= SOURCE_DESTROYED;
};
Meta.prototype.isMetaDestroyed = function () {
return (this._flags & META_DESTROYED) !== 0;
};
Meta.prototype.setMetaDestroyed = function () {
this._flags |= META_DESTROYED;
};
Meta.prototype.isProxy = function () {
return (this._flags & IS_PROXY) !== 0;
};
Meta.prototype.setProxy = function () {
this._flags |= IS_PROXY;
};
Meta.prototype._getOrCreateOwnMap = function (key) {
return this[key] || (this[key] = Object.create(null));
};
Meta.prototype._getInherited = function (key) {
var pointer = this,
map;
while (pointer !== undefined) {
map = pointer[key];
if (map !== undefined) {
return map;
}
pointer = pointer.parent;
}
};
Meta.prototype._findInherited = function (key, subkey) {
var pointer = this,
map,
value;
while (pointer !== undefined) {
map = pointer[key];
if (map !== undefined) {
value = map[subkey];
if (value !== undefined) {
return value;
}
}
pointer = pointer.parent;
}
};
// Implements a member that provides a lazily created map of maps,
// with inheritance at both levels.
Meta.prototype.writeDeps = function (subkey, itemkey, value) {
true && !!this.isMetaDestroyed() && emberDebug.assert('Cannot call writeDeps after the object is destroyed.', !this.isMetaDestroyed());
var outerMap = this._getOrCreateOwnMap('_deps');
var innerMap = outerMap[subkey];
if (innerMap === undefined) {
innerMap = outerMap[subkey] = Object.create(null);
}
innerMap[itemkey] = value;
};
Meta.prototype.peekDeps = function (subkey, itemkey) {
var pointer = this,
map,
value,
itemvalue;
while (pointer !== undefined) {
map = pointer._deps;
if (map !== undefined) {
value = map[subkey];
if (value !== undefined) {
itemvalue = value[itemkey];
if (itemvalue !== undefined) {
return itemvalue;
}
}
}
pointer = pointer.parent;
}
};
Meta.prototype.hasDeps = function (subkey) {
var pointer = this,
deps;
while (pointer !== undefined) {
deps = pointer._deps;
if (deps !== undefined && deps[subkey] !== undefined) {
return true;
}
pointer = pointer.parent;
}
return false;
};
Meta.prototype.forEachInDeps = function (subkey, fn) {
return this._forEachIn('_deps', subkey, fn);
};
Meta.prototype._forEachIn = function (key, subkey, fn) {
var pointer = this,
map,
innerMap,
i,
_calls$i,
_innerKey,
value;
var seen = void 0;
var calls = void 0;
while (pointer !== undefined) {
map = pointer[key];
if (map !== undefined) {
innerMap = map[subkey];
if (innerMap !== undefined) {
for (var innerKey in innerMap) {
seen = seen || Object.create(null);
if (seen[innerKey] === undefined) {
seen[innerKey] = true;
calls = calls || [];
calls.push([innerKey, innerMap[innerKey]]);
}
}
}
}
pointer = pointer.parent;
}
if (calls !== undefined) {
for (i = 0; i < calls.length; i++) {
_calls$i = calls[i], _innerKey = _calls$i[0], value = _calls$i[1];
fn(_innerKey, value);
}
}
};
Meta.prototype.readInheritedValue = function (key, subkey) {
var pointer = this,
map,
value;
while (pointer !== undefined) {
map = pointer['_' + key];
if (map !== undefined) {
value = map[subkey];
if (value !== undefined || subkey in map) {
return value;
}
}
pointer = pointer.parent;
}
return UNDEFINED;
};
Meta.prototype.writeValue = function (obj, key, value) {
var descriptor = emberUtils.lookupDescriptor(obj, key);
var isMandatorySetter = descriptor !== undefined && descriptor.set && descriptor.set.isMandatorySetter;
if (isMandatorySetter) {
this.writeValues(key, value);
} else {
obj[key] = value;
}
};
emberBabel.createClass(Meta, [{
key: 'factory',
set: function (factory) {
this._factory = factory;
},
get: function () {
return this._factory;
}
}]);
return Meta;
}();
var NODE_STACK = [];
for (var name in protoMethods) {
Meta.prototype[name] = protoMethods[name];
}
memberNames.forEach(function (name) {
return members[name](name, Meta);
});
// Implements a member that is a lazily created, non-inheritable
// POJO.
function ownMap(name, Meta) {
var key = memberProperty(name);
var capitalized = capitalize(name);
Meta.prototype['writable' + capitalized] = function () {
return this._getOrCreateOwnMap(key);
};
Meta.prototype['readable' + capitalized] = function () {
return this[key];
};
}
// Implements a member that is a lazily created POJO with inheritable
// values.
function inheritedMap(name, Meta) {
var key = memberProperty(name);
var capitalized = capitalize(name);
Meta.prototype['write' + capitalized] = function (subkey, value) {
true && !!this.isMetaDestroyed() && emberDebug.assert('Cannot call write' + capitalized + ' after the object is destroyed.', !this.isMetaDestroyed());
var map = this._getOrCreateOwnMap(key);
map[subkey] = value;
};
Meta.prototype['peek' + capitalized] = function (subkey) {
return this._findInherited(key, subkey);
};
Meta.prototype['forEach' + capitalized] = function (fn) {
var pointer = this,
map;
var seen = void 0;
while (pointer !== undefined) {
map = pointer[key];
if (map !== undefined) {
for (var _key in map) {
seen = seen || Object.create(null);
if (seen[_key] === undefined) {
seen[_key] = true;
fn(_key, map[_key]);
}
}
}
pointer = pointer.parent;
}
};
Meta.prototype['clear' + capitalized] = function () {
true && !!this.isMetaDestroyed() && emberDebug.assert('Cannot call clear' + capitalized + ' after the object is destroyed.', !this.isMetaDestroyed());
this[key] = undefined;
};
Meta.prototype['deleteFrom' + capitalized] = function (subkey) {
delete this._getOrCreateOwnMap(key)[subkey];
};
Meta.prototype['hasIn' + capitalized] = function (subkey) {
return this._findInherited(key, subkey) !== undefined;
};
}
var UNDEFINED = emberUtils.symbol('undefined');
// Implements a member that provides a non-heritable, lazily-created
// object using the method you provide.
function ownCustomObject(name, Meta) {
var key = memberProperty(name);
var capitalized = capitalize(name);
Meta.prototype['writable' + capitalized] = function (create) {
true && !!this.isMetaDestroyed() && emberDebug.assert('Cannot call writable' + capitalized + ' after the object is destroyed.', !this.isMetaDestroyed());
var ret = this[key];
if (ret === undefined) {
ret = this[key] = create(this.source);
}
return ret;
};
Meta.prototype['readable' + capitalized] = function () {
return this[key];
};
}
function memberProperty(name) {
return '_' + name;
}
// there's a more general-purpose capitalize in ember-runtime, but we
// don't want to make ember-metal depend on ember-runtime.
function capitalize(name) {
return name.replace(/^\w/, function (m) {
return m.toUpperCase();
});
}
var META_DESC = {
writable: true,
configurable: true,
enumerable: false,
value: null
};
var EMBER_META_PROPERTY = {
name: META_FIELD,
descriptor: META_DESC
};
if (ember_features.MANDATORY_SETTER) {
Meta.prototype.readInheritedValue = function (key, subkey) {
var pointer = this,
map,
value;
while (pointer !== undefined) {
map = pointer['_' + key];
if (map !== undefined) {
value = map[subkey];
if (value !== undefined || subkey in map) {
return value;
}
}
pointer = pointer.parent;
}
return UNDEFINED;
};
Meta.prototype.writeValue = function (obj, key, value) {
var descriptor = emberUtils.lookupDescriptor(obj, key);
var isMandatorySetter = descriptor !== undefined && descriptor !== null && descriptor.set && descriptor.set.isMandatorySetter;
if (isMandatorySetter) {
this.writeValues(key, value);
} else {
obj[key] = value;
}
};
}
var setMeta = void 0;
exports.peekMeta = void 0;
// choose the one appropriate for given platform
if (emberUtils.HAS_NATIVE_WEAKMAP) {
getPrototypeOf = Object.getPrototypeOf;
metaStore = new WeakMap();
setMeta = function (obj, meta) {
{
counters.setCalls++;
}
metaStore.set(obj, meta);
};
exports.peekMeta = function (obj) {
{
counters.peekCalls++;
}
return metaStore.get(obj);
};
exports.peekMeta = function (obj) {
var pointer = obj;
var meta = void 0;
while (pointer !== undefined && pointer !== null) {
meta = metaStore.get(pointer);
// jshint loopfunc:true
{
counters.peekCalls++;
}
// stop if we find a `null` value, since
// that means the meta was deleted
// any other truthy value is a "real" meta
if (meta === null || meta !== undefined) {
return meta;
}
pointer = getPrototypeOf(pointer);
{
counters.peakPrototypeWalks++;
}
}
};
} else {
setMeta = function (obj, meta) {
// if `null` already, just set it to the new value
// otherwise define property first
if (obj[META_FIELD] !== null) {
if (obj.__defineNonEnumerable) {
obj.__defineNonEnumerable(EMBER_META_PROPERTY);
} else {
Object.defineProperty(obj, META_FIELD, META_DESC);
}
}
obj[META_FIELD] = meta;
};
exports.peekMeta = function (obj) {
return obj[META_FIELD];
};
}
function deleteMeta(obj) {
{
counters.deleteCalls++;
}
var meta = exports.peekMeta(obj);
if (meta !== undefined) {
meta.destroy();
}
}
/**
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
*/
function meta(obj) {
{
counters.metaCalls++;
}
var maybeMeta = exports.peekMeta(obj);
var parent = void 0;
// remove this code, in-favor of explicit parent
if (maybeMeta !== undefined && maybeMeta !== null) {
if (maybeMeta.source === obj) {
return maybeMeta;
}
parent = maybeMeta;
}
var newMeta = new Meta(obj, parent);
setMeta(obj, newMeta);
return newMeta;
}
var Cache = function () {
function Cache(limit, func, key, store) {
this.size = 0;
this.misses = 0;
this.hits = 0;
this.limit = limit;
this.func = func;
this.key = key;
this.store = store || new DefaultStore();
}
Cache.prototype.get = function (obj) {
var key = this.key === undefined ? obj : this.key(obj);
var value = this.store.get(key);
if (value === undefined) {
this.misses++;
value = this._set(key, this.func(obj));
} else if (value === UNDEFINED) {
this.hits++;
value = undefined;
} else {
this.hits++;
// nothing to translate
}
return value;
};
Cache.prototype.set = function (obj, value) {
var key = this.key === undefined ? obj : this.key(obj);
return this._set(key, value);
};
Cache.prototype._set = function (key, value) {
if (this.limit > this.size) {
this.size++;
if (value === undefined) {
this.store.set(key, UNDEFINED);
} else {
this.store.set(key, value);
}
}
return value;
};
Cache.prototype.purge = function () {
this.store.clear();
this.size = 0;
this.hits = 0;
this.misses = 0;
};
return Cache;
}();
var DefaultStore = function () {
function DefaultStore() {
this.data = Object.create(null);
}
DefaultStore.prototype.get = function (key) {
return this.data[key];
};
DefaultStore.prototype.set = function (key, value) {
this.data[key] = value;
};
DefaultStore.prototype.clear = function () {
this.data = Object.create(null);
};
return DefaultStore;
}();
var IS_GLOBAL = /^[A-Z$]/;
var IS_GLOBAL_PATH = /^[A-Z$].*[\.]/;
new Cache(1000, function (key) {
return IS_GLOBAL.test(key);
});
var isGlobalPathCache = new Cache(1000, function (key) {
return IS_GLOBAL_PATH.test(key);
});
var hasThisCache = new Cache(1000, function (key) {
return key.lastIndexOf('this.', 0) === 0;
});
var firstDotIndexCache = new Cache(1000, function (key) {
return key.indexOf('.');
});
var firstKeyCache = new Cache(1000, function (path) {
var index = firstDotIndexCache.get(path);
if (index === -1) {
return path;
} else {
return path.slice(0, index);
}
});
var tailPathCache = new Cache(1000, function (path) {
var index = firstDotIndexCache.get(path);
if (index !== -1) {
return path.slice(index + 1);
}
});
function isGlobalPath(path) {
return isGlobalPathCache.get(path);
}
function hasThis(path) {
return hasThisCache.get(path);
}
function isPath(path) {
return firstDotIndexCache.get(path) !== -1;
}
function getFirstKey(path) {
return firstKeyCache.get(path);
}
function getTailPath(path) {
return tailPathCache.get(path);
}
/**
@module ember-metal
*/
var ALLOWABLE_TYPES = {
object: true,
function: true,
string: true
};
// ..........................................................
// 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
Ember.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
@param {Object} obj The object to retrieve from.
@param {String} keyName The property key to retrieve
@return {Object} the property value or `null`.
@public
*/
function get(obj, keyName) {
true && !(arguments.length === 2) && emberDebug.assert('Get must be called with two arguments; an object and a property key', arguments.length === 2);
true && !(obj !== undefined && obj !== null) && emberDebug.assert('Cannot call get with \'' + keyName + '\' on an undefined object.', obj !== undefined && obj !== null);
true && !(typeof keyName === 'string') && emberDebug.assert('The key provided to get must be a string, you passed ' + keyName, typeof keyName === 'string');
true && !!hasThis(keyName) && emberDebug.assert('\'this\' in paths is not supported', !hasThis(keyName));
true && !(keyName !== '') && emberDebug.assert('Cannot call `Ember.get` with an empty string', keyName !== '');
var value = obj[keyName];
var desc = value !== null && typeof value === 'object' && value.isDescriptor ? value : undefined;
var ret = void 0;
if (desc === undefined && isPath(keyName)) {
return _getPath(obj, keyName);
}
if (desc) {
return desc.get(obj, keyName);
} else {
ret = value;
if (ret === undefined && 'object' === typeof obj && !(keyName in obj) && 'function' === typeof obj.unknownProperty) {
return obj.unknownProperty(keyName);
}
return ret;
}
}
function _getPath(root, path) {
var obj = root,
i;
var parts = path.split('.');
for (i = 0; i < parts.length; i++) {
if (!isGettable(obj)) {
return undefined;
}
obj = get(obj, parts[i]);
if (obj && obj.isDestroyed) {
return undefined;
}
}
return obj;
}
function isGettable(obj) {
if (obj == null) {
return false;
}
return ALLOWABLE_TYPES[typeof obj];
}
/**
Retrieves the value of a property from an Object, or a default value in the
case that the property returns `undefined`.
```javascript
Ember.getWithDefault(person, 'lastName', 'Doe');
```
@method getWithDefault
@for Ember
@param {Object} obj The object to retrieve from.
@param {String} keyName The name of the property to retrieve
@param {Object} defaultValue The value to return if the property value is undefined
@return {Object} The property value or the defaultValue.
@public
*/
/**
Sets the value of a property on an object, respecting computed properties
and notifying observers and other listeners of the change. If the
property is not defined but the object implements the `setUnknownProperty`
method then that will be invoked as well.
```javascript
Ember.set(obj, "name", value);
```
@method set
@for Ember
@param {Object} obj The object to modify.
@param {String} keyName The property key to set
@param {Object} value The value to set
@return {Object} the passed value.
@public
*/
function set(obj, keyName, value, tolerant) {
true && !(arguments.length === 3 || arguments.length === 4) && emberDebug.assert('Set must be called with three or four arguments; an object, a property key, a value and tolerant true/false', arguments.length === 3 || arguments.length === 4);
true && !(obj && typeof obj === 'object' || typeof obj === 'function') && emberDebug.assert('Cannot call set with \'' + keyName + '\' on an undefined object.', obj && typeof obj === 'object' || typeof obj === 'function');
true && !(typeof keyName === 'string') && emberDebug.assert('The key provided to set must be a string, you passed ' + keyName, typeof keyName === 'string');
true && !!hasThis(keyName) && emberDebug.assert('\'this\' in paths is not supported', !hasThis(keyName));
true && !!obj.isDestroyed && emberDebug.assert('calling set on destroyed object: ' + emberUtils.toString(obj) + '.' + keyName + ' = ' + emberUtils.toString(value), !obj.isDestroyed);
if (isPath(keyName)) {
return setPath(obj, keyName, value, tolerant);
}
var meta$$1 = exports.peekMeta(obj);
var possibleDesc = obj[keyName];
var desc = void 0,
currentValue = void 0;
if (possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor) {
desc = possibleDesc;
} else {
currentValue = possibleDesc;
}
if (desc) {
/* computed property */
desc.set(obj, keyName, value);
} else if (obj.setUnknownProperty && currentValue === undefined && !(keyName in obj)) {
/* unknown property */
true && !(typeof obj.setUnknownProperty === 'function') && emberDebug.assert('setUnknownProperty must be a function', typeof obj.setUnknownProperty === 'function');
obj.setUnknownProperty(keyName, value);
} else if (currentValue === value) {
/* no change */
return value;
} else {
propertyWillChange(obj, keyName, meta$$1);
if (ember_features.MANDATORY_SETTER) {
setWithMandatorySetter(meta$$1, obj, keyName, value);
} else {
obj[keyName] = value;
}
propertyDidChange(obj, keyName, meta$$1);
}
return value;
}
if (ember_features.MANDATORY_SETTER) {
setWithMandatorySetter = function (meta$$1, obj, keyName, value) {
if (meta$$1 && meta$$1.peekWatching(keyName) > 0) {
makeEnumerable(obj, keyName);
meta$$1.writeValue(obj, keyName, value);
} else {
obj[keyName] = value;
}
};
makeEnumerable = function (obj, key) {
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc && desc.set && desc.set.isMandatorySetter) {
desc.enumerable = true;
Object.defineProperty(obj, key, desc);
}
};
}
function setPath(root, path, value, tolerant) {
// get the last part of the path
var keyName = path.slice(path.lastIndexOf('.') + 1);
// get the first part of the part
path = path === keyName ? keyName : path.slice(0, path.length - (keyName.length + 1));
// unless the path is this, look up the first part to
// get the root
if (path !== 'this') {
root = _getPath(root, path);
}
if (!keyName || keyName.length === 0) {
throw new emberDebug.Error('Property set failed: You passed an empty path');
}
if (!root) {
if (tolerant) {
return;
} else {
throw new emberDebug.Error('Property set failed: object in path "' + path + '" could not be found or was destroyed.');
}
}
return set(root, keyName, value);
}
/**
Error-tolerant form of `Ember.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.
@method trySet
@for Ember
@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);
}
/**
@module ember
@submodule ember-metal
*/
var END_WITH_EACH_REGEX = /\.@each$/;
/**
Expands `pattern`, invoking `callback` for each expansion.
The only pattern supported is brace-expansion, anything else will be passed
once to `callback` directly.
Example
```js
function echo(arg){ console.log(arg); }
Ember.expandProperties('foo.bar', echo); //=> 'foo.bar'
Ember.expandProperties('{foo,bar}', echo); //=> 'foo', 'bar'
Ember.expandProperties('foo.{bar,baz}', echo); //=> 'foo.bar', 'foo.baz'
Ember.expandProperties('{foo,bar}.baz', echo); //=> 'foo.baz', 'bar.baz'
Ember.expandProperties('foo.{bar,baz}.[]', echo) //=> 'foo.bar.[]', 'foo.baz.[]'
Ember.expandProperties('{foo,bar}.{spam,eggs}', echo) //=> 'foo.spam', 'foo.eggs', 'bar.spam', 'bar.eggs'
Ember.expandProperties('{foo}.bar.{baz}') //=> 'foo.bar.baz'
```
@method expandProperties
@for Ember
@private
@param {String} pattern The property pattern to expand.
@param {Function} callback The callback to invoke. It is invoked once per
expansion, and is passed the expansion.
*/
function expandProperties(pattern, callback) {
true && !(typeof pattern === 'string') && emberDebug.assert('A computed property key must be a string, you passed ' + typeof pattern + ' ' + pattern, typeof pattern === 'string');
true && !(pattern.indexOf(' ') === -1) && emberDebug.assert('Brace expanded properties cannot contain spaces, e.g. "user.{firstName, lastName}" should be "user.{firstName,lastName}"', pattern.indexOf(' ') === -1);
// regex to look for double open, double close, or unclosed braces
true && !(pattern.match(/\{[^}{]*\{|\}[^}{]*\}|\{[^}]*$/g) === null) && emberDebug.assert('Brace expanded properties have to be balanced and cannot be nested, pattern: ' + pattern, pattern.match(/\{[^}{]*\{|\}[^}{]*\}|\{[^}]*$/g) === null);
var start = pattern.indexOf('{');
if (start < 0) {
callback(pattern.replace(END_WITH_EACH_REGEX, '.[]'));
} else {
dive('', pattern, start, callback);
}
}
function dive(prefix, pattern, start, callback) {
var end = pattern.indexOf('}'),
i = 0,
newStart = void 0,
arrayLength = void 0;
var tempArr = pattern.substring(start + 1, end).split(',');
var after = pattern.substring(end + 1);
prefix = prefix + pattern.substring(0, start);
arrayLength = tempArr.length;
while (i < arrayLength) {
newStart = after.indexOf('{');
if (newStart < 0) {
callback((prefix + tempArr[i++] + after).replace(END_WITH_EACH_REGEX, '.[]'));
} else {
dive(prefix + tempArr[i++], after, newStart, callback);
}
}
}
/**
@module ember-metal
*/
/**
Starts watching a property on an object. Whenever the property changes,
invokes `Ember.propertyWillChange` and `Ember.propertyDidChange`. This is the
primitive used by observers and dependent keys; usually you will never call
this method directly but instead use higher level methods like
`Ember.addObserver()`
@private
@method watch
@for Ember
@param obj
@param {String} _keyPath
*/
function watch(obj, _keyPath, m) {
if (!isPath(_keyPath)) {
watchKey(obj, _keyPath, m);
} else {
watchPath(obj, _keyPath, m);
}
}
function unwatch(obj, _keyPath, m) {
if (!isPath(_keyPath)) {
unwatchKey(obj, _keyPath, m);
} else {
unwatchPath(obj, _keyPath, m);
}
}
/**
Tears down the meta on an object so that it can be garbage collected.
Multiple calls will have no effect.
@method destroy
@for Ember
@param {Object} obj the object to destroy
@return {void}
@private
*/
/**
@module ember
@submodule ember-metal
*/
// ..........................................................
// DEPENDENT KEYS
//
function addDependentKeys(desc, obj, keyName, meta) {
// the descriptor has a list of dependent keys, so
// add all of its dependent keys.
var idx = void 0,
depKey = void 0;
var depKeys = desc._dependentKeys;
if (!depKeys) {
return;
}
for (idx = 0; idx < depKeys.length; idx++) {
depKey = depKeys[idx];
// Increment the number of times depKey depends on keyName.
meta.writeDeps(depKey, keyName, (meta.peekDeps(depKey, keyName) || 0) + 1);
// Watch the depKey
watch(obj, depKey, meta);
}
}
function removeDependentKeys(desc, obj, keyName, meta) {
// the descriptor has a list of dependent keys, so
// remove all of its dependent keys.
var depKeys = desc._dependentKeys,
idx,
depKey;
if (!depKeys) {
return;
}
for (idx = 0; idx < depKeys.length; idx++) {
depKey = depKeys[idx];
// Decrement the number of times depKey depends on keyName.
meta.writeDeps(depKey, keyName, (meta.peekDeps(depKey, keyName) || 0) - 1);
// Unwatch the depKey
unwatch(obj, depKey, meta);
}
}
/**
@module ember
@submodule ember-metal
*/
var DEEP_EACH_REGEX = /\.@each\.[^.]+\./;
/**
A computed property transforms an object literal with object's accessor function(s) into a property.
By default the function backing the computed property 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 recomputed if the dependencies are modified.
In the following example we declare a computed property - `fullName` - by calling
`.Ember.computed()` with property dependencies (`firstName` and `lastName`) as leading arguments and getter accessor function. The `fullName` getter function
will be called once (regardless of how many times it is accessed) as long
as its dependencies have not changed. Once `firstName` or `lastName` are updated
any future calls (or anything bound) to `fullName` will incorporate the new
values.
```javascript
let Person = Ember.Object.extend({
// these will be supplied by `create`
firstName: null,
lastName: null,
fullName: Ember.computed('firstName', 'lastName', function() {
let firstName = this.get('firstName'),
lastName = this.get('lastName');
return firstName + ' ' + lastName;
})
});
let tom = Person.create({
firstName: 'Tom',
lastName: 'Dale'
});
tom.get('fullName') // 'Tom Dale'
```
You can also define what Ember should do when setting a computed property by providing additional function (`set`) in hash argument.
If you try to set a computed property, it will try to invoke setter accessor function with the key and
value you want to set it to as arguments.
```javascript
let Person = Ember.Object.extend({
// these will be supplied by `create`
firstName: null,
lastName: null,
fullName: Ember.computed('firstName', 'lastName', {
get(key) {
let firstName = this.get('firstName'),
lastName = this.get('lastName');
return firstName + ' ' + lastName;
},
set(key, value) {
let [firstName, lastName] = value.split(' ');
this.set('firstName', firstName);
this.set('lastName', lastName);
return value;
}
})
});
let person = Person.create();
person.set('fullName', 'Peter Wagenet');
person.get('firstName'); // 'Peter'
person.get('lastName'); // 'Wagenet'
```
You can overwrite computed property with normal property (no longer computed), that won't change if dependencies change, if you set computed property and it won't have setter accessor function defined.
You can also mark computed property as `.readOnly()` and block all attempts to set it.
```javascript
let Person = Ember.Object.extend({
// these will be supplied by `create`
firstName: null,
lastName: null,
fullName: Ember.computed('firstName', 'lastName', {
get(key) {
let firstName = this.get('firstName');
let lastName = this.get('lastName');
return firstName + ' ' + lastName;
}
}).readOnly()
});
let person = Person.create();
person.set('fullName', 'Peter Wagenet'); // Uncaught Error: Cannot set read-only property "fullName" on object: <(...):emberXXX>
```
Additional resources:
- [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" ](http://emberjs.com/blog/2015/05/13/ember-1-12-released.html#toc_new-computed-syntax)
@class ComputedProperty
@namespace Ember
@public
*/
function ComputedProperty(config, opts) {
this.isDescriptor = true;
if (typeof config === 'function') {
this._getter = config;
} else {
true && !(typeof config === 'object' && !Array.isArray(config)) && emberDebug.assert('Ember.computed expects a function or an object as last argument.', typeof config === 'object' && !Array.isArray(config));
true && !function () {
var keys = Object.keys(config),
i;
for (i = 0; i < keys.length; i++) {
if (keys[i] !== 'get' && keys[i] !== 'set') {
return false;
}
}
return true;
}() && emberDebug.assert('Config object passed to an Ember.computed can only contain `get` or `set` keys.', function () {
var keys = Object.keys(config),
i;for (i = 0; i < keys.length; i++) {
if (keys[i] !== 'get' && keys[i] !== 'set') {
return false;
}
}return true;
}());
this._getter = config.get;
this._setter = config.set;
}
true && !(!!this._getter || !!this._setter) && emberDebug.assert('Computed properties must receive a getter or a setter, you passed none.', !!this._getter || !!this._setter);
this._dependentKeys = undefined;
this._suspended = undefined;
this._meta = undefined;
this._volatile = false;
this._dependentKeys = opts && opts.dependentKeys;
this._readOnly = false;
}
ComputedProperty.prototype = new Descriptor();
ComputedProperty.prototype.constructor = ComputedProperty;
var ComputedPropertyPrototype = ComputedProperty.prototype;
/**
Call on a computed property to set it into non-cached mode. When in this
mode the computed property will not automatically cache the return value.
It also does not automatically fire any change events. You must manually notify
any changes if you want to observe this property.
Dependency keys have no effect on volatile properties as they are for cache
invalidation and notification when cached value is invalidated.
```javascript
let outsideService = Ember.Object.extend({
value: Ember.computed(function() {
return OutsideService.getValue();
}).volatile()
}).create();
```
@method volatile
@return {Ember.ComputedProperty} this
@chainable
@public
*/
ComputedPropertyPrototype.volatile = function () {
this._volatile = true;
return this;
};
/**
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.
```javascript
let Person = Ember.Object.extend({
guid: Ember.computed(function() {
return 'guid-guid-guid';
}).readOnly()
});
let person = Person.create();
person.set('guid', 'new-guid'); // will throw an exception
```
@method readOnly
@return {Ember.ComputedProperty} this
@chainable
@public
*/
ComputedPropertyPrototype.readOnly = function () {
this._readOnly = true;
true && !!(this._readOnly && this._setter && this._setter !== this._getter) && emberDebug.assert('Computed properties that define a setter using the new syntax cannot be read-only', !(this._readOnly && this._setter && this._setter !== this._getter));
return this;
};
/**
Sets the dependent keys on this computed property. Pass any number of
arguments containing key paths that this computed property depends on.
```javascript
let President = Ember.Object.extend({
fullName: Ember.computed(function() {
return this.get('firstName') + ' ' + this.get('lastName');
// Tell Ember that this computed property depends on firstName
// and lastName
}).property('firstName', 'lastName')
});
let president = President.create({
firstName: 'Barack',
lastName: 'Obama'
});
president.get('fullName'); // 'Barack Obama'
```
@method property
@param {String} path* zero or more property paths
@return {Ember.ComputedProperty} this
@chainable
@public
*/
ComputedPropertyPrototype.property = function () {
var args = [],
i;
function addArg(property) {
true && emberDebug.warn('Dependent keys containing @each only work one level deep. ' + ('You used the key "' + property + '" which is invalid. ') + 'Please create an intermediary computed property.', DEEP_EACH_REGEX.test(property) === false, { id: 'ember-metal.computed-deep-each' });
args.push(property);
}
for (i = 0; i < arguments.length; i++) {
expandProperties(arguments[i], addArg);
}
this._dependentKeys = args;
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 like this:
```
person: Ember.computed(function() {
let personId = this.get('personId');
return App.Person.create({ id: personId });
}).meta({ type: App.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
*/
ComputedPropertyPrototype.meta = function (meta$$1) {
if (arguments.length === 0) {
return this._meta || {};
} else {
this._meta = meta$$1;
return this;
}
};
// invalidate cache when CP key changes
ComputedPropertyPrototype.didChange = function (obj, keyName) {
// _suspended is set via a CP.set to ensure we don't clear
// the cached value set by the setter
if (this._volatile || this._suspended === obj) {
return;
}
// don't create objects just to invalidate
var meta$$1 = exports.peekMeta(obj);
if (!meta$$1 || meta$$1.source !== obj) {
return;
}
var cache = meta$$1.readableCache();
if (cache && cache[keyName] !== undefined) {
cache[keyName] = undefined;
removeDependentKeys(this, obj, keyName, meta$$1);
}
};
ComputedPropertyPrototype.get = function (obj, keyName) {
if (this._volatile) {
return this._getter.call(obj, keyName);
}
var meta$$1 = meta(obj);
var cache = meta$$1.writableCache();
var result = cache[keyName];
if (result === UNDEFINED) {
return undefined;
} else if (result !== undefined) {
return result;
}
var ret = this._getter.call(obj, keyName);
if (ret === undefined) {
cache[keyName] = UNDEFINED;
} else {
cache[keyName] = ret;
}
var chainWatchers = meta$$1.readableChainWatchers();
if (chainWatchers) {
chainWatchers.revalidate(keyName);
}
addDependentKeys(this, obj, keyName, meta$$1);
return ret;
};
ComputedPropertyPrototype.set = function (obj, keyName, value) {
if (this._readOnly) {
this._throwReadOnlyError(obj, keyName);
}
if (!this._setter) {
return this.clobberSet(obj, keyName, value);
}
if (this._volatile) {
return this.volatileSet(obj, keyName, value);
}
return this.setWithSuspend(obj, keyName, value);
};
ComputedPropertyPrototype._throwReadOnlyError = function (obj, keyName) {
throw new emberDebug.Error('Cannot set read-only property "' + keyName + '" on object: ' + emberUtils.inspect(obj));
};
ComputedPropertyPrototype.clobberSet = function (obj, keyName, value) {
var cachedValue = cacheFor(obj, keyName);
defineProperty(obj, keyName, null, cachedValue);
set(obj, keyName, value);
return value;
};
ComputedPropertyPrototype.volatileSet = function (obj, keyName, value) {
return this._setter.call(obj, keyName, value);
};
ComputedPropertyPrototype.setWithSuspend = function (obj, keyName, value) {
var oldSuspended = this._suspended;
this._suspended = obj;
try {
return this._set(obj, keyName, value);
} finally {
this._suspended = oldSuspended;
}
};
ComputedPropertyPrototype._set = function (obj, keyName, value) {
// cache requires own meta
var meta$$1 = meta(obj);
// either there is a writable cache or we need one to update
var cache = meta$$1.writableCache();
var hadCachedValue = false;
var cachedValue = void 0;
if (cache[keyName] !== undefined) {
if (cache[keyName] !== UNDEFINED) {
cachedValue = cache[keyName];
}
hadCachedValue = true;
}
var ret = this._setter.call(obj, keyName, value, cachedValue);
// allows setter to return the same value that is cached already
if (hadCachedValue && cachedValue === ret) {
return ret;
}
propertyWillChange(obj, keyName, meta$$1);
if (hadCachedValue) {
cache[keyName] = undefined;
}
if (!hadCachedValue) {
addDependentKeys(this, obj, keyName, meta$$1);
}
if (ret === undefined) {
cache[keyName] = UNDEFINED;
} else {
cache[keyName] = ret;
}
propertyDidChange(obj, keyName, meta$$1);
return ret;
};
/* called before property is overridden */
ComputedPropertyPrototype.teardown = function (obj, keyName) {
if (this._volatile) {
return;
}
var meta$$1 = meta(obj);
var cache = meta$$1.readableCache();
if (cache && cache[keyName] !== undefined) {
removeDependentKeys(this, obj, keyName, meta$$1);
cache[keyName] = undefined;
}
};
/**
This helper returns a new property descriptor that wraps the passed
computed property function. You can use this helper to define properties
with mixins or via `Ember.defineProperty()`.
If you pass a function as an argument, it will be used as a getter. A computed
property defined in this way might look like this:
```js
let Person = Ember.Object.extend({
init() {
this._super(...arguments);
this.firstName = 'Betty';
this.lastName = 'Jones';
},
fullName: Ember.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 pass a hash with two functions, `get` and `set`, as an
argument to provide both a getter and setter:
```js
let Person = Ember.Object.extend({
init() {
this._super(...arguments);
this.firstName = 'Betty';
this.lastName = 'Jones';
},
fullName: Ember.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'
```
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](http://emberjs.com/guides/configuring-ember/disabling-prototype-extensions/) enabled._
The alternative syntax, with prototype extensions, might look like:
```js
fullName: function() {
return this.get('firstName') + ' ' + this.get('lastName');
}.property('firstName', 'lastName')
```
@class computed
@namespace Ember
@constructor
@static
@param {String} [dependentKeys*] Optional dependent keys that trigger this computed property.
@param {Function} func The computed property function.
@return {Ember.ComputedProperty} property descriptor instance
@public
*/
/**
Returns the cached value for a property, if one exists.
This can be useful for peeking at the value of a computed
property that is generated lazily, without accidentally causing
it to be created.
@method cacheFor
@for Ember
@param {Object} obj the object whose property you want to check
@param {String} key the name of the property whose cached value you want
to return
@return {Object} the cached value
@public
*/
function cacheFor(obj, key) {
var meta$$1 = exports.peekMeta(obj);
var cache = meta$$1 && meta$$1.source === obj && meta$$1.readableCache();
var ret = cache && cache[key];
if (ret === UNDEFINED) {
return undefined;
}
return ret;
}
cacheFor.set = function (cache, key, value) {
if (value === undefined) {
cache[key] = UNDEFINED;
} else {
cache[key] = value;
}
};
cacheFor.get = function (cache, key) {
var ret = cache[key];
if (ret === UNDEFINED) {
return undefined;
}
return ret;
};
cacheFor.remove = function (cache, key) {
cache[key] = undefined;
};
var CONSUMED = {};
var AliasedProperty = function (_Descriptor) {
emberBabel.inherits(AliasedProperty, _Descriptor);
function AliasedProperty(altKey) {
var _this = emberBabel.possibleConstructorReturn(this, _Descriptor.call(this));
_this.isDescriptor = true;
_this.altKey = altKey;
_this._dependentKeys = [altKey];
return _this;
}
AliasedProperty.prototype.setup = function (obj, keyName) {
true && !(this.altKey !== keyName) && emberDebug.assert('Setting alias \'' + keyName + '\' on self', this.altKey !== keyName);
var meta$$1 = meta(obj);
if (meta$$1.peekWatching(keyName)) {
addDependentKeys(this, obj, keyName, meta$$1);
}
};
AliasedProperty.prototype.teardown = function (obj, keyName) {
var meta$$1 = meta(obj);
if (meta$$1.peekWatching(keyName)) {
removeDependentKeys(this, obj, keyName, meta$$1);
}
};
AliasedProperty.prototype.willWatch = function (obj, keyName) {
addDependentKeys(this, obj, keyName, meta(obj));
};
AliasedProperty.prototype.didUnwatch = function (obj, keyName) {
removeDependentKeys(this, obj, keyName, meta(obj));
};
AliasedProperty.prototype.get = function (obj, keyName) {
var ret = get(obj, this.altKey);
var meta$$1 = meta(obj);
var cache = meta$$1.writableCache();
if (cache[keyName] !== CONSUMED) {
cache[keyName] = CONSUMED;
addDependentKeys(this, obj, keyName, meta$$1);
}
return ret;
};
AliasedProperty.prototype.set = function (obj, keyName, value) {
return set(obj, this.altKey, value);
};
AliasedProperty.prototype.readOnly = function () {
this.set = AliasedProperty_readOnlySet;
return this;
};
AliasedProperty.prototype.oneWay = function () {
this.set = AliasedProperty_oneWaySet;
return this;
};
return AliasedProperty;
}(Descriptor);
function AliasedProperty_readOnlySet(obj, keyName) {
throw new emberDebug.Error('Cannot set read-only property \'' + keyName + '\' on object: ' + emberUtils.inspect(obj));
}
function AliasedProperty_oneWaySet(obj, keyName, value) {
defineProperty(obj, keyName, null);
return set(obj, keyName, value);
}
// Backwards compatibility with Ember Data.
AliasedProperty.prototype._meta = undefined;
AliasedProperty.prototype.meta = ComputedProperty.prototype.meta;
/**
Merge the contents of two objects together into the first object.
```javascript
Ember.merge({ first: 'Tom' }, { last: 'Dale' }); // { first: 'Tom', last: 'Dale' }
var a = { first: 'Yehuda' };
var b = { last: 'Katz' };
Ember.merge(a, b); // a == { first: 'Yehuda', last: 'Katz' }, b == { last: 'Katz' }
```
@method merge
@for Ember
@param {Object} original The object to merge into
@param {Object} updates The object to copy properties from
@return {Object}
@public
*/
/**
@module ember
@submodule ember-metal
*/
/**
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
*/
/* eslint no-console:off */
/* global console */
/**
The purpose of the Ember Instrumentation module is
to provide efficient, general-purpose instrumentation
for Ember.
Subscribe to a listener by using `Ember.subscribe`:
```javascript
Ember.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 `Ember.instrument`:
```javascript
Ember.instrument("render.handlebars", payload, function() {
// rendering logic
}, binding);
```
Event names passed to `Ember.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
@namespace Ember
@static
@private
*/
var subscribers = [];
var cache = {};
function populateListeners(name) {
var listeners = [],
i;
var subscriber = void 0;
for (i = 0; i < subscribers.length; i++) {
subscriber = subscribers[i];
if (subscriber.regex.test(name)) {
listeners.push(subscriber.object);
}
}
cache[name] = listeners;
return listeners;
}
var time = function () {
var perf = 'undefined' !== typeof window ? window.performance || {} : {};
var fn = perf.now || perf.mozNow || perf.webkitNow || perf.msNow || perf.oNow;
// fn.bind will be available in all the browsers that support the advanced window.performance... ;-)
return fn ? fn.bind(perf) : function () {
return +new Date();
};
}();
/**
Notifies event's subscribers, calls `before` and `after` hooks.
@method instrument
@namespace Ember.Instrumentation
@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, _payload, callback, binding) {
if (arguments.length <= 3 && typeof _payload === 'function') {
binding = callback;
callback = _payload;
_payload = undefined;
}
if (subscribers.length === 0) {
return callback.call(binding);
}
var payload = _payload || {};
var finalizer = _instrumentStart(name, function () {
return payload;
});
if (finalizer) {
return withFinalizer(callback, finalizer, payload, binding);
} else {
return callback.call(binding);
}
}
exports.flaggedInstrument = void 0;
if (ember_features.EMBER_IMPROVED_INSTRUMENTATION) {
exports.flaggedInstrument = instrument;
} else {
exports.flaggedInstrument = function (name, payload, callback) {
return callback();
};
}
function withFinalizer(callback, finalizer, payload, binding) {
var result = void 0;
try {
result = callback.call(binding);
} catch (e) {
payload.exception = e;
result = payload;
} finally {
finalizer();
}
return result;
}
function NOOP() {}
// private for now
function _instrumentStart(name, _payload, _payloadParam) {
if (subscribers.length === 0) {
return NOOP;
}
var listeners = cache[name];
if (!listeners) {
listeners = populateListeners(name);
}
if (listeners.length === 0) {
return NOOP;
}
var payload = _payload(_payloadParam);
var STRUCTURED_PROFILE = emberEnvironment.ENV.STRUCTURED_PROFILE;
var timeName = void 0;
if (STRUCTURED_PROFILE) {
timeName = name + ': ' + payload.object;
console.time(timeName);
}
var beforeValues = new Array(listeners.length);
var i = void 0,
listener = void 0;
var timestamp = time();
for (i = 0; i < listeners.length; i++) {
listener = listeners[i];
beforeValues[i] = listener.before(name, timestamp, payload);
}
return function () {
var i = void 0,
listener = void 0;
var timestamp = time();
for (i = 0; i < listeners.length; i++) {
listener = listeners[i];
if (typeof listener.after === 'function') {
listener.after(name, timestamp, payload, beforeValues[i]);
}
}
if (STRUCTURED_PROFILE) {
console.timeEnd(timeName);
}
};
}
/**
Subscribes to a particular event or instrumented block of code.
@method subscribe
@namespace Ember.Instrumentation
@param {String} [pattern] Namespaced event name.
@param {Object} [object] Before and After hooks.
@return {Subscriber}
@private
*/
/**
Unsubscribes from a particular event or instrumented block of code.
@method unsubscribe
@namespace Ember.Instrumentation
@param {Object} [subscriber]
@private
*/
/**
Resets `Ember.Instrumentation` by flushing list of subscribers.
@method reset
@namespace Ember.Instrumentation
@private
*/
// To maintain stacktrace consistency across browsers
var getStack = function (error) {
var stack = error.stack;
var message = error.message;
if (stack && stack.indexOf(message) === -1) {
stack = message + '\n' + stack;
}
return stack;
};
var onerror = void 0;
// Ember.onerror getter
// Ember.onerror setter
function setOnerror(handler) {
onerror = handler;
}
var dispatchOverride = void 0;
// dispatch error
function dispatchError(error) {
if (dispatchOverride) {
dispatchOverride(error);
} else {
defaultDispatch(error);
}
}
// allows testing adapter to override dispatch
function defaultDispatch(error) {
if (emberDebug.isTesting()) {
throw error;
}
if (onerror) {
onerror(error);
} else {
Logger.error(getStack(error));
}
}
var id = 0;
// Returns whether Type(value) is Object according to the terminology in the spec
function isObject$1(value) {
return typeof value === 'object' && value !== null || typeof value === 'function';
}
/*
* @class Ember.WeakMap
* @public
* @category ember-metal-weakmap
*
* A partial polyfill for [WeakMap](http://www.ecma-international.org/ecma-262/6.0/#sec-weakmap-objects).
*
* There is a small but important caveat. This implementation assumes that the
* weak map will live longer (in the sense of garbage collection) than all of its
* keys, otherwise it is possible to leak the values stored in the weak map. In
* practice, most use cases satisfy this limitation which is why it is included
* in ember-metal.
*/
function WeakMap$1(iterable) {
var i, _iterable$i, key, value;
if (!(this instanceof WeakMap$1)) {
throw new TypeError('Constructor WeakMap requires \'new\'');
}
this._id = emberUtils.GUID_KEY + id++;
if (iterable === null || iterable === undefined) {} else if (Array.isArray(iterable)) {
for (i = 0; i < iterable.length; i++) {
_iterable$i = iterable[i], key = _iterable$i[0], value = _iterable$i[1];
this.set(key, value);
}
} else {
throw new TypeError('The weak map constructor polyfill only supports an array argument');
}
}
/*
* @method get
* @param key {Object | Function}
* @return {Any} stored value
*/
WeakMap$1.prototype.get = function (obj) {
if (!isObject$1(obj)) {
return undefined;
}
var meta$$1 = exports.peekMeta(obj),
map;
if (meta$$1) {
map = meta$$1.readableWeak();
if (map) {
if (map[this._id] === UNDEFINED) {
return undefined;
}
return map[this._id];
}
}
};
/*
* @method set
* @param key {Object | Function}
* @param value {Any}
* @return {WeakMap} the weak map
*/
WeakMap$1.prototype.set = function (obj, value) {
if (!isObject$1(obj)) {
throw new TypeError('Invalid value used as weak map key');
}
if (value === undefined) {
value = UNDEFINED;
}
meta(obj).writableWeak()[this._id] = value;
return this;
};
/*
* @method has
* @param key {Object | Function}
* @return {boolean} if the key exists
*/
WeakMap$1.prototype.has = function (obj) {
if (!isObject$1(obj)) {
return false;
}
var meta$$1 = exports.peekMeta(obj),
map;
if (meta$$1) {
map = meta$$1.readableWeak();
if (map) {
return map[this._id] !== undefined;
}
}
return false;
};
/*
* @method delete
* @param key {Object | Function}
* @return {boolean} if the key was deleted
*/
WeakMap$1.prototype.delete = function (obj) {
if (this.has(obj)) {
delete meta(obj).writableWeak()[this._id];
return true;
} else {
return false;
}
};
/*
* @method toString
* @return {String}
*/
WeakMap$1.prototype.toString = function () {
return '[object WeakMap]';
};
/**
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
Ember.isNone(); // true
Ember.isNone(null); // true
Ember.isNone(undefined); // true
Ember.isNone(''); // false
Ember.isNone([]); // false
Ember.isNone(function() {}); // false
```
@method isNone
@for Ember
@param {Object} obj Value to test
@return {Boolean}
@public
*/
function isNone(obj) {
return obj === null || obj === undefined;
}
/**
Verifies that a value is `null` or an empty string, empty array,
or empty function.
Constrains the rules on `Ember.isNone` by returning true for empty
string and empty arrays.
```javascript
Ember.isEmpty(); // true
Ember.isEmpty(null); // true
Ember.isEmpty(undefined); // true
Ember.isEmpty(''); // true
Ember.isEmpty([]); // true
Ember.isEmpty({}); // false
Ember.isEmpty('Adam Hawkins'); // false
Ember.isEmpty([0,1,2]); // false
Ember.isEmpty('\n\t'); // false
Ember.isEmpty(' '); // false
```
@method isEmpty
@for Ember
@param {Object} obj Value to test
@return {Boolean}
@public
*/
function isEmpty(obj) {
var none = isNone(obj),
size,
length;
if (none) {
return none;
}
if (typeof obj.size === 'number') {
return !obj.size;
}
var objectType = typeof obj;
if (objectType === 'object') {
size = get(obj, 'size');
if (typeof size === 'number') {
return !size;
}
}
if (typeof obj.length === 'number' && objectType !== 'function') {
return !obj.length;
}
if (objectType === 'object') {
length = get(obj, 'length');
if (typeof length === 'number') {
return !length;
}
}
return false;
}
/**
A value is blank if it is empty or a whitespace string.
```javascript
Ember.isBlank(); // true
Ember.isBlank(null); // true
Ember.isBlank(undefined); // true
Ember.isBlank(''); // true
Ember.isBlank([]); // true
Ember.isBlank('\n\t'); // true
Ember.isBlank(' '); // true
Ember.isBlank({}); // false
Ember.isBlank('\n\t Hello'); // false
Ember.isBlank('Hello world'); // false
Ember.isBlank([1,2,3]); // false
```
@method isBlank
@for Ember
@param {Object} obj Value to test
@return {Boolean}
@since 1.5.0
@public
*/
function isBlank(obj) {
return isEmpty(obj) || typeof obj === 'string' && obj.match(/\S/) === null;
}
/**
A value is present if it not `isBlank`.
```javascript
Ember.isPresent(); // false
Ember.isPresent(null); // false
Ember.isPresent(undefined); // false
Ember.isPresent(''); // false
Ember.isPresent(' '); // false
Ember.isPresent('\n\t'); // false
Ember.isPresent([]); // false
Ember.isPresent({ length: 0 }) // false
Ember.isPresent(false); // true
Ember.isPresent(true); // true
Ember.isPresent('string'); // true
Ember.isPresent(0); // true
Ember.isPresent(function() {}) // true
Ember.isPresent({}); // true
Ember.isPresent(false); // true
Ember.isPresent('\n\t Hello'); // true
Ember.isPresent([1,2,3]); // true
```
@method isPresent
@for Ember
@param {Object} obj Value to test
@return {Boolean}
@since 1.8.0
@public
*/
var onErrorTarget = {
get onerror() {
return dispatchError;
},
set onerror(handler) {
return setOnerror(handler);
}
};
var backburner = new Backburner(['sync', 'actions', 'destroy'], {
GUID_KEY: emberUtils.GUID_KEY,
sync: {
before: beginPropertyChanges,
after: endPropertyChanges
},
defaultQueue: 'actions',
onBegin: function (current) {
run$1.currentRunLoop = current;
},
onEnd: function (current, next) {
run$1.currentRunLoop = next;
},
onErrorTarget: onErrorTarget,
onErrorMethod: 'onerror'
});
// ..........................................................
// 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
run(function() {
// code to be executed within a RunLoop
});
```
@class run
@namespace Ember
@static
@constructor
@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() {
return backburner.run.apply(backburner, arguments);
}
/**
If no run-loop is present, it creates a new one. If a run loop is
present it will queue itself to run on the existing run-loops action
queue.
Please note: This is not for normal usage, and should be used sparingly.
If invoked when not within a run loop:
```javascript
run.join(function() {
// creates a new run-loop
});
```
Alternatively, if called within an existing run loop:
```javascript
run(function() {
// creates a new run-loop
run.join(function() {
// joins with the existing run-loop, and queues for invocation on
// the existing run-loops action queue.
});
});
```
@method join
@namespace Ember
@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
*/
run$1.join = function () {
return backburner.join.apply(backburner, arguments);
};
/**
Allows you to specify which context to call the specified function in while
adding the execution of that function to the Ember run loop. This ability
makes this method a great way to asynchronously integrate third-party libraries
into your Ember application.
`run.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:
```javascript
App.RichTextEditorComponent = Ember.Component.extend({
initializeTinyMCE: Ember.on('didInsertElement', function() {
tinymce.init({
selector: '#' + this.$().prop('id'),
setup: Ember.run.bind(this, this.setupEditor)
});
}),
setupEditor: function(editor) {
this.set('editor', editor);
editor.on('change', function() {
console.log('content changed!');
});
}
});
```
In this example, we use Ember.run.bind to bind the setupEditor method to the
context of the App.RichTextEditorComponent and to have the invocation of that
method be safely handled and executed by the Ember run loop.
@method bind
@namespace Ember
@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
*/
run$1.bind = function () {
var _len, curried, _key;
for (_len = arguments.length, curried = Array(_len), _key = 0; _key < _len; _key++) {
curried[_key] = arguments[_key];
}
return function () {
var _len2, args, _key2;
for (_len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return run$1.join.apply(run$1, curried.concat(args));
};
};
run$1.backburner = backburner;
run$1.currentRunLoop = null;
run$1.queues = backburner.queueNames;
/**
Begins a new RunLoop. Any deferred actions invoked after the begin will
be buffered until you invoke a matching call to `run.end()`. This is
a lower-level way to use a RunLoop instead of using `run()`.
```javascript
run.begin();
// code to be executed within a RunLoop
run.end();
```
@method begin
@return {void}
@public
*/
run$1.begin = function () {
backburner.begin();
};
/**
Ends a RunLoop. This must be called sometime after you call
`run.begin()` to flush any deferred actions. This is a lower-level way
to use a RunLoop instead of using `run()`.
```javascript
run.begin();
// code to be executed within a RunLoop
run.end();
```
@method end
@return {void}
@public
*/
run$1.end = function () {
backburner.end();
};
/**
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 ['sync', 'actions', 'destroy']
@private
*/
/**
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 `run.queues` property.
```javascript
run.schedule('sync', this, function() {
// this will be executed in the first RunLoop queue, when bindings are synced
console.log('scheduled on sync queue');
});
run.schedule('actions', this, function() {
// this will be executed in the 'actions' queue, after bindings have synced.
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 sync queue
// scheduled on actions queue
```
@method schedule
@param {String} queue The name of the queue to schedule against.
Default queues are 'sync' and '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 cancelling, see `run.cancel`.
@public
*/
run$1.schedule = function () /* queue, target, method */{
true && !(run$1.currentRunLoop || !emberDebug.isTesting()) && emberDebug.assert('You have turned on testing mode, which disabled the run-loop\'s autorun. ' + 'You will need to wrap any code with asynchronous side-effects in a run', run$1.currentRunLoop || !emberDebug.isTesting());
return backburner.schedule.apply(backburner, arguments);
};
// Used by global test teardown
run$1.hasScheduledTimers = function () {
return backburner.hasTimers();
};
// Used by global test teardown
run$1.cancelTimers = function () {
backburner.cancelTimers();
};
/**
Immediately flushes any events scheduled in the 'sync' queue. Bindings
use this queue so this method is a useful way to immediately force all
bindings in the application to sync.
You should call this method anytime you need any changed state to propagate
throughout the app immediately without repainting the UI (which happens
in the later 'render' queue added by the `ember-views` package).
```javascript
run.sync();
```
@method sync
@return {void}
@private
*/
run$1.sync = function () {
if (backburner.currentInstance) {
backburner.currentInstance.queues.sync.flush();
}
};
/**
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
run.later(myContext, function() {
// code here will execute within a RunLoop in about 500ms with this == myContext
}, 500);
```
@method later
@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 cancelling, see `run.cancel`.
@public
*/
run$1.later = function () /*target, method*/{
return backburner.later.apply(backburner, arguments);
};
/**
Schedule a function to run one time during the current RunLoop. This is equivalent
to calling `scheduleOnce` with the "actions" queue.
@method once
@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 cancelling, see `run.cancel`.
@public
*/
run$1.once = function () {
var _len3, args, _key3;
true && !(run$1.currentRunLoop || !emberDebug.isTesting()) && emberDebug.assert('You have turned on testing mode, which disabled the run-loop\'s autorun. ' + 'You will need to wrap any code with asynchronous side-effects in a run', run$1.currentRunLoop || !emberDebug.isTesting());
for (_len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
args.unshift('actions');
return backburner.scheduleOnce.apply(backburner, 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
function sayHi() {
console.log('hi');
}
run(function() {
run.scheduleOnce('afterRender', myContext, sayHi);
run.scheduleOnce('afterRender', myContext, sayHi);
// sayHi will only be executed once, in the afterRender queue of the RunLoop
});
```
Also note that passing an anonymous function to `run.scheduleOnce` will
not prevent additional calls with an identical anonymous function from
scheduling the items multiple times, e.g.:
```javascript
function scheduleIt() {
run.scheduleOnce('actions', myContext, function() {
console.log('Closure');
});
}
scheduleIt();
scheduleIt();
// "Closure" will print twice, even though we're using `run.scheduleOnce`,
// because the function we pass to it is anonymous and won't match the
// previously scheduled operation.
```
Available queues, and their order, can be found at `run.queues`
@method scheduleOnce
@param {String} [queue] The name of the queue to schedule against. Default queues are 'sync' and '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 cancelling, see `run.cancel`.
@public
*/
run$1.scheduleOnce = function () /*queue, target, method*/{
true && !(run$1.currentRunLoop || !emberDebug.isTesting()) && emberDebug.assert('You have turned on testing mode, which disabled the run-loop\'s autorun. ' + 'You will need to wrap any code with asynchronous side-effects in a run', run$1.currentRunLoop || !emberDebug.isTesting());
return backburner.scheduleOnce.apply(backburner, arguments);
};
/**
Schedules an item to run from within a separate run loop, after
control has been returned to the system. This is equivalent to calling
`run.later` with a wait time of 1ms.
```javascript
run.next(myContext, function() {
// code to be executed in the next run loop,
// which will be scheduled after the current one
});
```
Multiple operations scheduled with `run.next` will coalesce
into the same later run loop, along with any other operations
scheduled by `run.later` that expire right around the same
time that `run.next` operations will fire.
Note that there are often alternatives to using `run.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:
```javascript
export default Ember.Component.extend({
didInsertElement() {
this._super(...arguments);
run.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 `run.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 `run.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 `run.next`.
@method next
@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 cancelling, see `run.cancel`.
@public
*/
run$1.next = function () {
var _len4, args, _key4;
for (_len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
args.push(1);
return backburner.later.apply(backburner, args);
};
/**
Cancels a scheduled item. Must be a value returned by `run.later()`,
`run.once()`, `run.scheduleOnce()`, `run.next()`, `run.debounce()`, or
`run.throttle()`.
```javascript
let runNext = run.next(myContext, function() {
// will not be executed
});
run.cancel(runNext);
let runLater = run.later(myContext, function() {
// will not be executed
}, 500);
run.cancel(runLater);
let runScheduleOnce = run.scheduleOnce('afterRender', myContext, function() {
// will not be executed
});
run.cancel(runScheduleOnce);
let runOnce = run.once(myContext, function() {
// will not be executed
});
run.cancel(runOnce);
let throttle = run.throttle(myContext, function() {
// will not be executed
}, 1, false);
run.cancel(throttle);
let debounce = run.debounce(myContext, function() {
// will not be executed
}, 1);
run.cancel(debounce);
let debounceImmediate = run.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 cancelled
run.cancel(debounceImmediate);
```
@method cancel
@param {Object} timer Timer object to cancel
@return {Boolean} true if cancelled or false/undefined if it wasn't found
@public
*/
run$1.cancel = function (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
function whoRan() {
console.log(this.name + ' ran.');
}
let myContext = { name: 'debounce' };
run.debounce(myContext, whoRan, 150);
// less than 150ms passes
run.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
function whoRan() {
console.log(this.name + ' ran.');
}
let myContext = { name: 'debounce' };
run.debounce(myContext, whoRan, 150, true);
// console logs 'debounce ran.' one time immediately.
// 100ms passes
run.debounce(myContext, whoRan, 150, true);
// 150ms passes and nothing else is logged to the console and
// the debouncee is no longer being watched
run.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
@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 cancelling, see `run.cancel`.
@public
*/
run$1.debounce = function () {
return backburner.debounce.apply(backburner, arguments);
};
/**
Ensure that the target method is never called more frequently than
the specified spacing period. The target method is called immediately.
```javascript
function whoRan() {
console.log(this.name + ' ran.');
}
let myContext = { name: 'throttle' };
run.throttle(myContext, whoRan, 150);
// whoRan is invoked with context myContext
// console logs 'throttle ran.'
// 50ms passes
run.throttle(myContext, whoRan, 150);
// 50ms passes
run.throttle(myContext, whoRan, 150);
// 150ms passes
run.throttle(myContext, whoRan, 150);
// whoRan is invoked with context myContext
// console logs 'throttle ran.'
```
@method throttle
@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 cancelling, see `run.cancel`.
@public
*/
run$1.throttle = function () {
return backburner.throttle.apply(backburner, arguments);
};
/**
Add a new named queue after the specified queue.
The queue to add will only be added once.
@method _addQueue
@param {String} name the name of the queue to add.
@param {String} after the name of the queue to add after.
@private
*/
run$1._addQueue = function (name, after) {
if (run$1.queues.indexOf(name) === -1) {
run$1.queues.splice(run$1.queues.indexOf(after) + 1, 0, name);
}
};
/**
Helper class that allows you to register your library with Ember.
Singleton created at `Ember.libraries`.
@class Libraries
@constructor
@private
*/
var Libraries = function () {
function Libraries() {
this._registry = [];
this._coreLibIndex = 0;
}
Libraries.prototype.isRegistered = function (name) {
return !!this._getLibraryByName(name);
};
return Libraries;
}();
Libraries.prototype = {
constructor: Libraries,
_getLibraryByName: function (name) {
var libs = this._registry,
i;
var count = libs.length;
for (i = 0; i < count; i++) {
if (libs[i].name === name) {
return libs[i];
}
}
},
register: function (name, version, isCoreLibrary) {
var index = this._registry.length;
if (!this._getLibraryByName(name)) {
if (isCoreLibrary) {
index = this._coreLibIndex++;
}
this._registry.splice(index, 0, { name: name, version: version });
} else {
true && emberDebug.warn('Library "' + name + '" is already registered with Ember.', false, { id: 'ember-metal.libraries-register' });
}
},
registerCoreLibrary: function (name, version) {
this.register(name, version, true);
},
deRegister: function (name) {
var lib = this._getLibraryByName(name);
var index = void 0;
if (lib) {
index = this._registry.indexOf(lib);
this._registry.splice(index, 1);
}
}
};
if (ember_features.EMBER_LIBRARIES_ISREGISTERED) {
Libraries.prototype.isRegistered = function (name) {
return !!this._getLibraryByName(name);
};
}
var libraries = new Libraries();
/**
@module ember
@submodule ember-metal
*/
/*
JavaScript (before ES6) does not have a Map implementation. Objects,
which are often used as dictionaries, may only have Strings as keys.
Because Ember has a way to get a unique identifier for every object
via `Ember.guidFor`, we can implement a performant Map with arbitrary
keys. Because it is commonly used in low-level bookkeeping, Map is
implemented as a pure JavaScript object for performance.
This implementation follows the current iteration of the ES6 proposal for
maps (http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets),
with one exception: as we do not have the luxury of in-VM iteration, we implement a
forEach method for iteration.
Map is mocked out to look like an Ember object, so you can do
`Ember.Map.create()` for symmetry with other Ember classes.
*/
function missingFunction(fn) {
throw new TypeError(Object.prototype.toString.call(fn) + ' is not a function');
}
function missingNew(name) {
throw new TypeError('Constructor ' + name + ' requires \'new\'');
}
function copyNull(obj) {
var output = Object.create(null);
for (var prop in obj) {
// hasOwnPropery is not needed because obj is Object.create(null);
output[prop] = obj[prop];
}
return output;
}
function copyMap(original, newObject) {
var keys = original._keys.copy();
var values = copyNull(original._values);
newObject._keys = keys;
newObject._values = values;
newObject.size = original.size;
return newObject;
}
/**
This class is used internally by Ember and Ember Data.
Please do not use it at this time. We plan to clean it up
and add many tests soon.
@class OrderedSet
@namespace Ember
@constructor
@private
*/
function OrderedSet() {
if (this instanceof OrderedSet) {
this.clear();
} else {
missingNew('OrderedSet');
}
}
/**
@method create
@static
@return {Ember.OrderedSet}
@private
*/
OrderedSet.create = function () {
var Constructor = this;
return new Constructor();
};
OrderedSet.prototype = {
constructor: OrderedSet,
/**
@method clear
@private
*/
clear: function () {
this.presenceSet = Object.create(null);
this.list = [];
this.size = 0;
},
/**
@method add
@param obj
@param guid (optional, and for internal use)
@return {Ember.OrderedSet}
@private
*/
add: function (obj, _guid) {
var guid = _guid || emberUtils.guidFor(obj);
var presenceSet = this.presenceSet;
var list = this.list;
if (presenceSet[guid] !== true) {
presenceSet[guid] = true;
this.size = list.push(obj);
}
return this;
},
/**
@since 1.8.0
@method delete
@param obj
@param _guid (optional and for internal use only)
@return {Boolean}
@private
*/
delete: function (obj, _guid) {
var guid = _guid || emberUtils.guidFor(obj),
index;
var presenceSet = this.presenceSet;
var list = this.list;
if (presenceSet[guid] === true) {
delete presenceSet[guid];
index = list.indexOf(obj);
if (index > -1) {
list.splice(index, 1);
}
this.size = list.length;
return true;
} else {
return false;
}
},
/**
@method isEmpty
@return {Boolean}
@private
*/
isEmpty: function () {
return this.size === 0;
},
/**
@method has
@param obj
@return {Boolean}
@private
*/
has: function (obj) {
if (this.size === 0) {
return false;
}
var guid = emberUtils.guidFor(obj);
var presenceSet = this.presenceSet;
return presenceSet[guid] === true;
},
/**
@method forEach
@param {Function} fn
@param self
@private
*/
forEach: function (fn /*, ...thisArg*/) {
if (typeof fn !== 'function') {
missingFunction(fn);
}
if (this.size === 0) {
return;
}
var list = this.list,
i,
_i;
if (arguments.length === 2) {
for (i = 0; i < list.length; i++) {
fn.call(arguments[1], list[i]);
}
} else {
for (_i = 0; _i < list.length; _i++) {
fn(list[_i]);
}
}
},
/**
@method toArray
@return {Array}
@private
*/
toArray: function () {
return this.list.slice();
},
/**
@method copy
@return {Ember.OrderedSet}
@private
*/
copy: function () {
var Constructor = this.constructor;
var set = new Constructor();
set.presenceSet = copyNull(this.presenceSet);
set.list = this.toArray();
set.size = this.size;
return set;
}
};
/**
A Map stores values indexed by keys. Unlike JavaScript's
default Objects, the keys of a Map can be any JavaScript
object.
Internally, a Map has two data structures:
1. `keys`: an OrderedSet of all of the existing keys
2. `values`: a JavaScript Object indexed by the `Ember.guidFor(key)`
When a key/value pair is added for the first time, we
add the key to the `keys` OrderedSet, and create or
replace an entry in `values`. When an entry is deleted,
we delete its entry in `keys` and `values`.
@class Map
@namespace Ember
@private
@constructor
*/
function Map() {
if (this instanceof Map) {
this._keys = OrderedSet.create();
this._values = Object.create(null);
this.size = 0;
} else {
missingNew('Map');
}
}
/**
@method create
@static
@private
*/
Map.create = function () {
var Constructor = this;
return new Constructor();
};
Map.prototype = {
constructor: Map,
/**
This property will change as the number of objects in the map changes.
@since 1.8.0
@property size
@type number
@default 0
@private
*/
size: 0,
/**
Retrieve the value associated with a given key.
@method get
@param {*} key
@return {*} the value associated with the key, or `undefined`
@private
*/
get: function (key) {
if (this.size === 0) {
return;
}
var values = this._values;
var guid = emberUtils.guidFor(key);
return values[guid];
},
/**
Adds a value to the map. If a value for the given key has already been
provided, the new value will replace the old value.
@method set
@param {*} key
@param {*} value
@return {Ember.Map}
@private
*/
set: function (key, value) {
var keys = this._keys;
var values = this._values;
var guid = emberUtils.guidFor(key);
// ensure we don't store -0
var k = key === -0 ? 0 : key;
keys.add(k, guid);
values[guid] = value;
this.size = keys.size;
return this;
},
/**
Removes a value from the map for an associated key.
@since 1.8.0
@method delete
@param {*} key
@return {Boolean} true if an item was removed, false otherwise
@private
*/
delete: function (key) {
if (this.size === 0) {
return false;
}
// don't use ES6 "delete" because it will be annoying
// to use in browsers that are not ES6 friendly;
var keys = this._keys;
var values = this._values;
var guid = emberUtils.guidFor(key);
if (keys.delete(key, guid)) {
delete values[guid];
this.size = keys.size;
return true;
} else {
return false;
}
},
/**
Check whether a key is present.
@method has
@param {*} key
@return {Boolean} true if the item was present, false otherwise
@private
*/
has: function (key) {
return this._keys.has(key);
},
/**
Iterate over all the keys and values. Calls the function once
for each key, passing in value, key, and the map being iterated over,
in that order.
The keys are guaranteed to be iterated over in insertion order.
@method forEach
@param {Function} callback
@param {*} self if passed, the `this` value inside the
callback. By default, `this` is the map.
@private
*/
forEach: function (callback /*, ...thisArg*/) {
if (typeof callback !== 'function') {
missingFunction(callback);
}
if (this.size === 0) {
return;
}
var map = this;
var cb = void 0,
thisArg = void 0;
if (arguments.length === 2) {
thisArg = arguments[1];
cb = function (key) {
return callback.call(thisArg, map.get(key), key, map);
};
} else {
cb = function (key) {
return callback(map.get(key), key, map);
};
}
this._keys.forEach(cb);
},
/**
@method clear
@private
*/
clear: function () {
this._keys.clear();
this._values = Object.create(null);
this.size = 0;
},
/**
@method copy
@return {Ember.Map}
@private
*/
copy: function () {
return copyMap(this, new Map());
}
};
/**
@class MapWithDefault
@namespace Ember
@extends Ember.Map
@private
@constructor
@param [options]
@param {*} [options.defaultValue]
*/
function MapWithDefault(options) {
this._super$constructor();
this.defaultValue = options.defaultValue;
}
/**
@method create
@static
@param [options]
@param {*} [options.defaultValue]
@return {Ember.MapWithDefault|Ember.Map} If options are passed, returns
`Ember.MapWithDefault` otherwise returns `Ember.Map`
@private
*/
MapWithDefault.create = function (options) {
if (options) {
return new MapWithDefault(options);
} else {
return new Map();
}
};
MapWithDefault.prototype = Object.create(Map.prototype);
MapWithDefault.prototype.constructor = MapWithDefault;
MapWithDefault.prototype._super$constructor = Map;
MapWithDefault.prototype._super$get = Map.prototype.get;
/**
Retrieve the value associated with a given key.
@method get
@param {*} key
@return {*} the value associated with the key, or the default value
@private
*/
MapWithDefault.prototype.get = function (key) {
var hasValue = this.has(key),
defaultValue;
if (hasValue) {
return this._super$get(key);
} else {
defaultValue = this.defaultValue(key);
this.set(key, defaultValue);
return defaultValue;
}
};
/**
@method copy
@return {Ember.MapWithDefault}
@private
*/
MapWithDefault.prototype.copy = function () {
var Constructor = this.constructor;
return copyMap(this, new Constructor({
defaultValue: this.defaultValue
}));
};
/**
To get multiple properties at once, call `Ember.getProperties`
with an object followed by a list of strings or an array:
```javascript
Ember.getProperties(record, 'firstName', 'lastName', 'zipCode');
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
```
is equivalent to:
```javascript
Ember.getProperties(record, ['firstName', 'lastName', 'zipCode']);
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
```
@method getProperties
@for Ember
@param {Object} obj
@param {String...|Array} list of keys to get
@return {Object}
@public
*/
/**
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
let anObject = Ember.Object.create();
anObject.setProperties({
firstName: 'Stanley',
lastName: 'Stuart',
age: 21
});
```
@method setProperties
@param obj
@param {Object} properties
@return properties
@public
*/
/**
@module ember-metal
*/
function changeEvent(keyName) {
return keyName + ':change';
}
function beforeEvent(keyName) {
return keyName + ':before';
}
/**
@method addObserver
@for Ember
@param obj
@param {String} _path
@param {Object|Function} target
@param {Function|String} [method]
@public
*/
function addObserver(obj, _path, target, method) {
addListener(obj, changeEvent(_path), target, method);
watch(obj, _path);
return this;
}
/**
@method removeObserver
@for Ember
@param obj
@param {String} path
@param {Object|Function} target
@param {Function|String} [method]
@public
*/
function removeObserver(obj, path, target, method) {
unwatch(obj, path);
removeListener(obj, changeEvent(path), target, method);
return this;
}
/**
@method _addBeforeObserver
@for Ember
@param obj
@param {String} path
@param {Object|Function} target
@param {Function|String} [method]
@deprecated
@private
*/
function _addBeforeObserver(obj, path, target, method) {
addListener(obj, beforeEvent(path), target, method);
watch(obj, path);
return this;
}
// Suspend observer during callback.
//
// This should only be used by the target of the observer
// while it is setting the observed path.
function _suspendObserver(obj, path, target, method, callback) {
return suspendListener(obj, changeEvent(path), target, method, callback);
}
/**
@method removeBeforeObserver
@for Ember
@param obj
@param {String} path
@param {Object|Function} target
@param {Function|String} [method]
@deprecated
@private
*/
function _removeBeforeObserver(obj, path, target, method) {
unwatch(obj, path);
removeListener(obj, beforeEvent(path), target, method);
return this;
}
/**
@module ember
@submodule ember-metal
*/
// ..........................................................
// BINDING
//
var Binding = function () {
function Binding(toPath, fromPath) {
// Configuration
this._from = fromPath;
this._to = toPath;
this._oneWay = undefined;
// State
this._direction = undefined;
this._readyToSync = undefined;
this._fromObj = undefined;
this._fromPath = undefined;
this._toObj = undefined;
}
/**
@class Binding
@namespace Ember
@deprecated See http://emberjs.com/deprecations/v2.x#toc_ember-binding
@public
*/
/**
This copies the Binding so it can be connected to another object.
@method copy
@return {Ember.Binding} `this`
@public
*/
Binding.prototype.copy = function () {
var copy = new Binding(this._to, this._from);
if (this._oneWay) {
copy._oneWay = true;
}
return copy;
};
// ..........................................................
// CONFIG
//
/**
This will set `from` property path to the specified value. It will not
attempt to resolve this property path to an actual object until you
connect the binding.
The binding will search for the property path starting at the root object
you pass when you `connect()` the binding. It follows the same rules as
`get()` - see that method for more information.
@method from
@param {String} path The property path to connect to.
@return {Ember.Binding} `this`
@public
*/
Binding.prototype.from = function (path) {
this._from = path;
return this;
};
/**
This will set the `to` property path to the specified value. It will not
attempt to resolve this property path to an actual object until you
connect the binding.
The binding will search for the property path starting at the root object
you pass when you `connect()` the binding. It follows the same rules as
`get()` - see that method for more information.
@method to
@param {String|Tuple} path A property path or tuple.
@return {Ember.Binding} `this`
@public
*/
Binding.prototype.to = function (path) {
this._to = path;
return this;
};
/**
Configures the binding as one way. A one-way binding will relay changes
on the `from` side to the `to` side, but not the other way around. This
means that if you change the `to` side directly, the `from` side may have
a different value.
@method oneWay
@return {Ember.Binding} `this`
@public
*/
Binding.prototype.oneWay = function () {
this._oneWay = true;
return this;
};
/**
@method toString
@return {String} string representation of binding
@public
*/
Binding.prototype.toString = function () {
var oneWay = this._oneWay ? '[oneWay]' : '';
return 'Ember.Binding<' + emberUtils.guidFor(this) + '>(' + this._from + ' -> ' + this._to + ')' + oneWay;
};
// ..........................................................
// CONNECT AND SYNC
//
/**
Attempts to connect this binding instance so that it can receive and relay
changes. This method will raise an exception if you have not set the
from/to properties yet.
@method connect
@param {Object} obj The root object for this binding.
@return {Ember.Binding} `this`
@public
*/
Binding.prototype.connect = function (obj) {
true && !!!obj && emberDebug.assert('Must pass a valid object to Ember.Binding.connect()', !!obj);
var fromObj = void 0,
fromPath = void 0,
possibleGlobal = void 0,
name;
// If the binding's "from" path could be interpreted as a global, verify
// whether the path refers to a global or not by consulting `Ember.lookup`.
if (isGlobalPath(this._from)) {
name = getFirstKey(this._from);
possibleGlobal = emberEnvironment.context.lookup[name];
if (possibleGlobal) {
fromObj = possibleGlobal;
fromPath = getTailPath(this._from);
}
}
if (fromObj === undefined) {
fromObj = obj;
fromPath = this._from;
}
trySet(obj, this._to, get(fromObj, fromPath));
// Add an observer on the object to be notified when the binding should be updated.
addObserver(fromObj, fromPath, this, 'fromDidChange');
// If the binding is a two-way binding, also set up an observer on the target.
if (!this._oneWay) {
addObserver(obj, this._to, this, 'toDidChange');
}
addListener(obj, 'willDestroy', this, 'disconnect');
fireDeprecations(obj, this._to, this._from, possibleGlobal, this._oneWay, !possibleGlobal && !this._oneWay);
this._readyToSync = true;
this._fromObj = fromObj;
this._fromPath = fromPath;
this._toObj = obj;
return this;
};
/**
Disconnects the binding instance. Changes will no longer be relayed. You
will not usually need to call this method.
@method disconnect
@return {Ember.Binding} `this`
@public
*/
Binding.prototype.disconnect = function () {
true && !!!this._toObj && emberDebug.assert('Must pass a valid object to Ember.Binding.disconnect()', !!this._toObj);
// Remove an observer on the object so we're no longer notified of
// changes that should update bindings.
removeObserver(this._fromObj, this._fromPath, this, 'fromDidChange');
// If the binding is two-way, remove the observer from the target as well.
if (!this._oneWay) {
removeObserver(this._toObj, this._to, this, 'toDidChange');
}
this._readyToSync = false; // Disable scheduled syncs...
return this;
};
// ..........................................................
// PRIVATE
//
/* Called when the from side changes. */
Binding.prototype.fromDidChange = function () {
this._scheduleSync('fwd');
};
/* Called when the to side changes. */
Binding.prototype.toDidChange = function () {
this._scheduleSync('back');
};
Binding.prototype._scheduleSync = function (dir) {
var existingDir = this._direction;
// If we haven't scheduled the binding yet, schedule it.
if (existingDir === undefined) {
run$1.schedule('sync', this, '_sync');
this._direction = dir;
}
// If both a 'back' and 'fwd' sync have been scheduled on the same object,
// default to a 'fwd' sync so that it remains deterministic.
if (existingDir === 'back' && dir === 'fwd') {
this._direction = 'fwd';
}
};
Binding.prototype._sync = function () {
var log = emberEnvironment.ENV.LOG_BINDINGS,
fromValue,
toValue;
var toObj = this._toObj;
// Don't synchronize destroyed objects or disconnected bindings.
if (toObj.isDestroyed || !this._readyToSync) {
return;
}
// Get the direction of the binding for the object we are
// synchronizing from.
var direction = this._direction;
var fromObj = this._fromObj;
var fromPath = this._fromPath;
this._direction = undefined;
// If we're synchronizing from the remote object...
if (direction === 'fwd') {
fromValue = get(fromObj, fromPath);
if (log) {
Logger.log(' ', this.toString(), '->', fromValue, fromObj);
}
if (this._oneWay) {
trySet(toObj, this._to, fromValue);
} else {
_suspendObserver(toObj, this._to, this, 'toDidChange', function () {
trySet(toObj, this._to, fromValue);
});
}
// If we're synchronizing *to* the remote object.
} else if (direction === 'back') {
toValue = get(toObj, this._to);
if (log) {
Logger.log(' ', this.toString(), '<-', toValue, toObj);
}
_suspendObserver(fromObj, fromPath, this, 'fromDidChange', function () {
trySet(fromObj, fromPath, toValue);
});
}
};
return Binding;
}();
function fireDeprecations(obj, toPath, fromPath, deprecateGlobal, deprecateOneWay, deprecateAlias) {
var objectInfo = 'The `' + toPath + '` property of `' + obj + '` is an `Ember.Binding` connected to `' + fromPath + '`, but ';
true && !!deprecateGlobal && emberDebug.deprecate(objectInfo + ('`Ember.Binding` is deprecated. Since you' + ' are binding to a global consider using a service instead.'), !deprecateGlobal, {
id: 'ember-metal.binding',
until: '3.0.0',
url: 'http://emberjs.com/deprecations/v2.x#toc_ember-binding'
});
true && !!deprecateOneWay && emberDebug.deprecate(objectInfo + ('`Ember.Binding` is deprecated. Since you' + ' are using a `oneWay` binding consider using a `readOnly` computed' + ' property instead.'), !deprecateOneWay, {
id: 'ember-metal.binding',
until: '3.0.0',
url: 'http://emberjs.com/deprecations/v2.x#toc_ember-binding'
});
true && !!deprecateAlias && emberDebug.deprecate(objectInfo + ('`Ember.Binding` is deprecated. Consider' + ' using an `alias` computed property instead.'), !deprecateAlias, {
id: 'ember-metal.binding',
until: '3.0.0',
url: 'http://emberjs.com/deprecations/v2.x#toc_ember-binding'
});
}
(function (to, from) {
for (var key in from) {
if (from.hasOwnProperty(key)) {
to[key] = from[key];
}
}
})(Binding, {
/*
See `Ember.Binding.from`.
@method from
@static
*/
from: function (from) {
var C = this;
return new C(undefined, from);
},
/*
See `Ember.Binding.to`.
@method to
@static
*/
to: function (to) {
var C = this;
return new C(to, undefined);
}
});
/**
An `Ember.Binding` connects the properties of two objects so that whenever
the value of one property changes, the other property will be changed also.
## Automatic Creation of Bindings with `/^*Binding/`-named Properties.
You do not usually create Binding objects directly but instead describe
bindings in your class or object definition using automatic binding
detection.
Properties ending in a `Binding` suffix will be converted to `Ember.Binding`
instances. The value of this property should be a string representing a path
to another object or a custom binding instance created using Binding helpers
(see "One Way Bindings"):
```
valueBinding: "MyApp.someController.title"
```
This will create a binding from `MyApp.someController.title` to the `value`
property of your object instance automatically. Now the two values will be
kept in sync.
## One Way Bindings
One especially useful binding customization you can use is the `oneWay()`
helper. This helper tells Ember that you are only interested in
receiving changes on the object you are binding from. For example, if you
are binding to a preference and you want to be notified if the preference
has changed, but your object will not be changing the preference itself, you
could do:
```
bigTitlesBinding: Ember.Binding.oneWay("MyApp.preferencesController.bigTitles")
```
This way if the value of `MyApp.preferencesController.bigTitles` changes the
`bigTitles` property of your object will change also. However, if you
change the value of your `bigTitles` property, it will not update the
`preferencesController`.
One way bindings are almost twice as fast to setup and twice as fast to
execute because the binding only has to worry about changes to one side.
You should consider using one way bindings anytime you have an object that
may be created frequently and you do not intend to change a property; only
to monitor it for changes (such as in the example above).
## Adding Bindings Manually
All of the examples above show you how to configure a custom binding, but the
result of these customizations will be a binding template, not a fully active
Binding instance. The binding will actually become active only when you
instantiate the object the binding belongs to. It is useful, however, to
understand what actually happens when the binding is activated.
For a binding to function it must have at least a `from` property and a `to`
property. The `from` property path points to the object/key that you want to
bind from while the `to` path points to the object/key you want to bind to.
When you define a custom binding, you are usually describing the property
you want to bind from (such as `MyApp.someController.value` in the examples
above). When your object is created, it will automatically assign the value
you want to bind `to` based on the name of your binding key. In the
examples above, during init, Ember objects will effectively call
something like this on your binding:
```javascript
binding = Ember.Binding.from("valueBinding").to("value");
```
This creates a new binding instance based on the template you provide, and
sets the to path to the `value` property of the new object. Now that the
binding is fully configured with a `from` and a `to`, it simply needs to be
connected to become active. This is done through the `connect()` method:
```javascript
binding.connect(this);
```
Note that when you connect a binding you pass the object you want it to be
connected to. This object will be used as the root for both the from and
to side of the binding when inspecting relative paths. This allows the
binding to be automatically inherited by subclassed objects as well.
This also allows you to bind between objects using the paths you declare in
`from` and `to`:
```javascript
// Example 1
binding = Ember.Binding.from("App.someObject.value").to("value");
binding.connect(this);
// Example 2
binding = Ember.Binding.from("parentView.value").to("App.someObject.value");
binding.connect(this);
```
Now that the binding is connected, it will observe both the from and to side
and relay changes.
If you ever needed to do so (you almost never will, but it is useful to
understand this anyway), you could manually create an active binding by
using the `Ember.bind()` helper method. (This is the same method used by
to setup your bindings on objects):
```javascript
Ember.bind(MyApp.anotherObject, "value", "MyApp.someController.value");
```
Both of these code fragments have the same effect as doing the most friendly
form of binding creation like so:
```javascript
MyApp.anotherObject = Ember.Object.create({
valueBinding: "MyApp.someController.value",
// OTHER CODE FOR THIS OBJECT...
});
```
Ember's built in binding creation method makes it easy to automatically
create bindings for you. You should always use the highest-level APIs
available, even if you understand how it works underneath.
@class Binding
@namespace Ember
@since Ember 0.9
@public
*/
// Ember.Binding = Binding; ES6TODO: where to put this?
/**
Global helper method to create a new binding. Just pass the root object
along with a `to` and `from` path to create and connect the binding.
@method bind
@for Ember
@param {Object} obj The root object of the transform.
@param {String} to The path to the 'to' side of the binding.
Must be relative to obj.
@param {String} from The path to the 'from' side of the binding.
Must be relative to obj or a global path.
@return {Ember.Binding} binding instance
@public
*/
/**
@module ember
@submodule ember-metal
*/
var a_concat = Array.prototype.concat;
var isArray = Array.isArray;
function isMethod(obj) {
return 'function' === typeof obj && obj.isMethod !== false && obj !== Boolean && obj !== Object && obj !== Number && obj !== Array && obj !== Date && obj !== String;
}
var CONTINUE = {};
function mixinProperties(mixinsMeta, mixin) {
var guid = void 0;
if (mixin instanceof Mixin) {
guid = emberUtils.guidFor(mixin);
if (mixinsMeta.peekMixins(guid)) {
return CONTINUE;
}
mixinsMeta.writeMixins(guid, mixin);
return mixin.properties;
} else {
return mixin; // apply anonymous mixin properties
}
}
function concatenatedMixinProperties(concatProp, props, values, base) {
// reset before adding each new mixin to pickup concats from previous
var concats = values[concatProp] || base[concatProp];
if (props[concatProp]) {
concats = concats ? a_concat.call(concats, props[concatProp]) : props[concatProp];
}
return concats;
}
function giveDescriptorSuper(meta$$1, key, property, values, descs, base) {
var superProperty = void 0,
possibleDesc,
superDesc;
// Computed properties override methods, and do not call super to them
if (values[key] === undefined) {
// Find the original descriptor in a parent mixin
superProperty = descs[key];
}
// If we didn't find the original descriptor in a parent mixin, find
// it on the original object.
if (!superProperty) {
possibleDesc = base[key];
superDesc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined;
superProperty = superDesc;
}
if (superProperty === undefined || !(superProperty instanceof ComputedProperty)) {
return property;
}
// 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.
property = Object.create(property);
property._getter = emberUtils.wrap(property._getter, superProperty._getter);
if (superProperty._setter) {
if (property._setter) {
property._setter = emberUtils.wrap(property._setter, superProperty._setter);
} else {
property._setter = superProperty._setter;
}
}
return property;
}
function giveMethodSuper(obj, key, method, values, descs) {
var superMethod = void 0;
// Methods overwrite computed properties, and do not call super to them.
if (descs[key] === undefined) {
// Find the original method in a parent mixin
superMethod = values[key];
}
// If we didn't find the original value in a parent mixin, find it in
// the original object
superMethod = superMethod || obj[key];
// Only wrap the new method if the original method was a function
if (superMethod === undefined || 'function' !== typeof superMethod) {
return method;
}
return emberUtils.wrap(method, superMethod);
}
function applyConcatenatedProperties(obj, key, value, values) {
var baseValue = values[key] || obj[key];
var ret = void 0;
if (baseValue === null || baseValue === undefined) {
ret = emberUtils.makeArray(value);
} else {
if (isArray(baseValue)) {
if (value === null || value === undefined) {
ret = baseValue;
} else {
ret = a_concat.call(baseValue, value);
}
} else {
ret = a_concat.call(emberUtils.makeArray(baseValue), value);
}
}
{
// it is possible to use concatenatedProperties with strings (which cannot be frozen)
// only freeze objects...
if (typeof ret === 'object' && ret !== null) {
// prevent mutating `concatenatedProperties` array after it is applied
Object.freeze(ret);
}
}
return ret;
}
function applyMergedProperties(obj, key, value, values) {
var baseValue = values[key] || obj[key],
propValue;
{
if (isArray(value)) {
// use conditional to avoid stringifying every time
true && !false && emberDebug.assert('You passed in `' + JSON.stringify(value) + '` as the value for `' + key + '` but `' + key + '` cannot be an Array', false);
}
}
if (!baseValue) {
return value;
}
var newBase = emberUtils.assign({}, baseValue);
var hasFunction = false;
for (var prop in value) {
if (!value.hasOwnProperty(prop)) {
continue;
}
propValue = value[prop];
if (isMethod(propValue)) {
// TODO: support for Computed Properties, etc?
hasFunction = true;
newBase[prop] = giveMethodSuper(obj, prop, propValue, baseValue, {});
} else {
newBase[prop] = propValue;
}
}
if (hasFunction) {
newBase._super = emberUtils.ROOT;
}
return newBase;
}
function addNormalizedProperty(base, key, value, meta$$1, descs, values, concats, mergings) {
if (value instanceof Descriptor) {
if (value === REQUIRED && descs[key]) {
return CONTINUE;
}
// Wrap descriptor function to implement
// _super() if needed
if (value._getter) {
value = giveDescriptorSuper(meta$$1, key, value, values, descs, base);
}
descs[key] = value;
values[key] = undefined;
} else {
if (concats && concats.indexOf(key) >= 0 || key === 'concatenatedProperties' || key === 'mergedProperties') {
value = applyConcatenatedProperties(base, key, value, values);
} else if (mergings && mergings.indexOf(key) >= 0) {
value = applyMergedProperties(base, key, value, values);
} else if (isMethod(value)) {
value = giveMethodSuper(base, key, value, values, descs);
}
descs[key] = undefined;
values[key] = value;
}
}
function mergeMixins(mixins, meta$$1, descs, values, base, keys) {
var currentMixin = void 0,
props = void 0,
key = void 0,
concats = void 0,
mergings = void 0,
i;
function removeKeys(keyName) {
delete descs[keyName];
delete values[keyName];
}
for (i = 0; i < mixins.length; i++) {
currentMixin = mixins[i];
true && !(typeof currentMixin === 'object' && currentMixin !== null && Object.prototype.toString.call(currentMixin) !== '[object Array]') && emberDebug.assert('Expected hash or Mixin instance, got ' + Object.prototype.toString.call(currentMixin), typeof currentMixin === 'object' && currentMixin !== null && Object.prototype.toString.call(currentMixin) !== '[object Array]');
props = mixinProperties(meta$$1, currentMixin);
if (props === CONTINUE) {
continue;
}
if (props) {
if (base.willMergeMixin) {
base.willMergeMixin(props);
}
concats = concatenatedMixinProperties('concatenatedProperties', props, values, base);
mergings = concatenatedMixinProperties('mergedProperties', props, values, base);
for (key in props) {
if (!props.hasOwnProperty(key)) {
continue;
}
keys.push(key);
addNormalizedProperty(base, key, props[key], meta$$1, descs, values, concats, mergings);
}
// manually copy toString() because some JS engines do not enumerate it
if (props.hasOwnProperty('toString')) {
base.toString = props.toString;
}
} else if (currentMixin.mixins) {
mergeMixins(currentMixin.mixins, meta$$1, descs, values, base, keys);
if (currentMixin._without) {
currentMixin._without.forEach(removeKeys);
}
}
}
}
function detectBinding(key) {
var length = key.length;
return length > 7 && key.charCodeAt(length - 7) === 66 && key.indexOf('inding', length - 6) !== -1;
}
// warm both paths of above function
detectBinding('notbound');
detectBinding('fooBinding');
function connectBindings(obj, meta$$1) {
// TODO Mixin.apply(instance) should disconnect binding if exists
meta$$1.forEachBindings(function (key, binding) {
var to;
if (binding) {
to = key.slice(0, -7); // strip Binding off end
if (binding instanceof Binding) {
binding = binding.copy(); // copy prototypes' instance
binding.to(to);
} else {
// binding is string path
binding = new Binding(to, binding);
}
binding.connect(obj);
obj[key] = binding;
}
});
// mark as applied
meta$$1.clearBindings();
}
function finishPartial(obj, meta$$1) {
connectBindings(obj, meta$$1 || meta(obj));
return obj;
}
function followAlias(obj, desc, descs, values) {
var altKey = desc.methodName;
var value = void 0;
var possibleDesc = void 0;
if (descs[altKey] || values[altKey]) {
value = values[altKey];
desc = descs[altKey];
} else if ((possibleDesc = obj[altKey]) && possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor) {
desc = possibleDesc;
value = undefined;
} else {
desc = undefined;
value = obj[altKey];
}
return { desc: desc, value: value };
}
function updateObserversAndListeners(obj, key, observerOrListener, pathsKey, updateMethod) {
var paths = observerOrListener[pathsKey],
i;
if (paths) {
for (i = 0; i < paths.length; i++) {
updateMethod(obj, paths[i], null, key);
}
}
}
function replaceObserversAndListeners(obj, key, observerOrListener) {
var prev = obj[key];
if ('function' === typeof prev) {
updateObserversAndListeners(obj, key, prev, '__ember_observesBefore__', _removeBeforeObserver);
updateObserversAndListeners(obj, key, prev, '__ember_observes__', removeObserver);
updateObserversAndListeners(obj, key, prev, '__ember_listens__', removeListener);
}
if ('function' === typeof observerOrListener) {
updateObserversAndListeners(obj, key, observerOrListener, '__ember_observesBefore__', _addBeforeObserver);
updateObserversAndListeners(obj, key, observerOrListener, '__ember_observes__', addObserver);
updateObserversAndListeners(obj, key, observerOrListener, '__ember_listens__', addListener);
}
}
function applyMixin(obj, mixins, partial) {
var descs = {},
i,
followed;
var values = {};
var meta$$1 = meta(obj);
var keys = [];
var key = void 0,
value = void 0,
desc = void 0;
obj._super = emberUtils.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);
for (i = 0; i < keys.length; i++) {
key = keys[i];
if (key === 'constructor' || !values.hasOwnProperty(key)) {
continue;
}
desc = descs[key];
value = values[key];
if (desc === REQUIRED) {
continue;
}
while (desc && desc instanceof Alias) {
followed = followAlias(obj, desc, descs, values);
desc = followed.desc;
value = followed.value;
}
if (desc === undefined && value === undefined) {
continue;
}
replaceObserversAndListeners(obj, key, value);
if (detectBinding(key)) {
meta$$1.writeBindings(key, value);
}
defineProperty(obj, key, desc, value, meta$$1);
}
if (!partial) {
// don't apply to prototype
finishPartial(obj, meta$$1);
}
return obj;
}
/**
@method mixin
@for Ember
@param obj
@param mixins*
@return obj
@private
*/
/**
The `Ember.Mixin` class allows you to create mixins, whose properties can be
added to other classes. For instance,
```javascript
const EditableMixin = Ember.Mixin.create({
edit() {
console.log('starting to edit');
this.set('isEditing', true);
},
isEditing: false
});
// Mix mixins into classes by passing them as the first arguments to
// `.extend.`
const Comment = Ember.Object.extend(EditableMixin, {
post: null
});
let comment = Comment.create({
post: somePost
});
comment.edit(); // outputs 'starting to edit'
```
Note that Mixins are created with `Ember.Mixin.create`, not
`Ember.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
const FilterableMixin = Ember.Mixin.create({
filters: Ember.A()
});
// filters will be a separate array for every object implementing the mixin
const FilterableMixin = Ember.Mixin.create({
filters: Ember.computed(function() {
return Ember.A();
})
});
// filters will be created as a separate array during the object's initialization
const Filterable = Ember.Mixin.create({
init() {
this._super(...arguments);
this.set("filters", Ember.A());
}
});
```
@class Mixin
@namespace Ember
@public
*/
var Mixin = function () {
function Mixin(mixins, properties) {
this.properties = properties;
var length = mixins && mixins.length,
m,
i,
x;
if (length > 0) {
m = new Array(length);
for (i = 0; i < length; i++) {
x = mixins[i];
if (x instanceof Mixin) {
m[i] = x;
} else {
m[i] = new Mixin(undefined, x);
}
}
this.mixins = m;
} else {
this.mixins = undefined;
}
this.ownerConstructor = undefined;
this._without = undefined;
this[emberUtils.GUID_KEY] = null;
this[emberUtils.NAME_KEY] = null;
emberDebug.debugSeal(this);
}
Mixin.applyPartial = function (obj) {
var _len2, args, _key2;
for (_len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
return applyMixin(obj, args, true);
};
/**
@method create
@static
@param arguments*
@public
*/
Mixin.create = function () {
// ES6TODO: this relies on a global state?
unprocessedFlag = true;
var M = this,
_len3,
args,
_key3;
for (_len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
return new M(args, undefined);
};
// returns the mixins currently applied to the specified object
// TODO: Make Ember.mixin
Mixin.mixins = function (obj) {
var meta$$1 = exports.peekMeta(obj);
var ret = [];
if (!meta$$1) {
return ret;
}
meta$$1.forEachMixins(function (key, currentMixin) {
// skip primitive mixins since these are always anonymous
if (!currentMixin.properties) {
ret.push(currentMixin);
}
});
return ret;
};
return Mixin;
}();
Mixin._apply = applyMixin;
Mixin.finishPartial = finishPartial;
var unprocessedFlag = false;
var MixinPrototype = Mixin.prototype;
/**
@method reopen
@param arguments*
@private
*/
MixinPrototype.reopen = function () {
var currentMixin = void 0;
if (this.properties) {
currentMixin = new Mixin(undefined, this.properties);
this.properties = undefined;
this.mixins = [currentMixin];
} else if (!this.mixins) {
this.mixins = [];
}
var mixins = this.mixins;
var idx = void 0;
for (idx = 0; idx < arguments.length; idx++) {
currentMixin = arguments[idx];
true && !(typeof currentMixin === 'object' && currentMixin !== null && Object.prototype.toString.call(currentMixin) !== '[object Array]') && emberDebug.assert('Expected hash or Mixin instance, got ' + Object.prototype.toString.call(currentMixin), typeof currentMixin === 'object' && currentMixin !== null && Object.prototype.toString.call(currentMixin) !== '[object Array]');
if (currentMixin instanceof Mixin) {
mixins.push(currentMixin);
} else {
mixins.push(new Mixin(undefined, currentMixin));
}
}
return this;
};
/**
@method apply
@param obj
@return applied object
@private
*/
MixinPrototype.apply = function (obj) {
return applyMixin(obj, [this], false);
};
MixinPrototype.applyPartial = function (obj) {
return applyMixin(obj, [this], true);
};
MixinPrototype.toString = Object.toString;
function _detect(curMixin, targetMixin, seen) {
var guid = emberUtils.guidFor(curMixin);
if (seen[guid]) {
return false;
}
seen[guid] = true;
if (curMixin === targetMixin) {
return true;
}
var mixins = curMixin.mixins;
var loc = mixins ? mixins.length : 0;
while (--loc >= 0) {
if (_detect(mixins[loc], targetMixin, seen)) {
return true;
}
}
return false;
}
/**
@method detect
@param obj
@return {Boolean}
@private
*/
MixinPrototype.detect = function (obj) {
if (typeof obj !== 'object' || obj === null) {
return false;
}
if (obj instanceof Mixin) {
return _detect(obj, this, {});
}
var meta$$1 = exports.peekMeta(obj);
if (!meta$$1) {
return false;
}
return !!meta$$1.peekMixins(emberUtils.guidFor(this));
};
MixinPrototype.without = function () {
var ret = new Mixin([this]),
_len4,
args,
_key4;
for (_len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
ret._without = args;
return ret;
};
function _keys(ret, mixin, seen) {
var props, i, key;
if (seen[emberUtils.guidFor(mixin)]) {
return;
}
seen[emberUtils.guidFor(mixin)] = true;
if (mixin.properties) {
props = Object.keys(mixin.properties);
for (i = 0; i < props.length; i++) {
key = props[i];
ret[key] = true;
}
} else if (mixin.mixins) {
mixin.mixins.forEach(function (x) {
return _keys(ret, x, seen);
});
}
}
MixinPrototype.keys = function () {
var keys = {};
_keys(keys, this, {});
var ret = Object.keys(keys);
return ret;
};
emberDebug.debugSeal(MixinPrototype);
var REQUIRED = new Descriptor();
REQUIRED.toString = function () {
return '(Required Property)';
};
/**
Denotes a required property for a mixin
@method required
@for Ember
@private
*/
function Alias(methodName) {
this.isDescriptor = true;
this.methodName = methodName;
}
Alias.prototype = new Descriptor();
/**
Makes a method available via an additional name.
```javascript
App.Person = Ember.Object.extend({
name: function() {
return 'Tomhuda Katzdale';
},
moniker: Ember.aliasMethod('name')
});
let goodGuy = App.Person.create();
goodGuy.name(); // 'Tomhuda Katzdale'
goodGuy.moniker(); // 'Tomhuda Katzdale'
```
@method aliasMethod
@for Ember
@param {String} methodName name of the method to alias
@public
*/
// ..........................................................
// OBSERVER HELPER
//
/**
Specify a method that observes property changes.
```javascript
Ember.Object.extend({
valueObserver: Ember.observer('value', function() {
// Executes whenever the "value" property changes
})
});
```
Also available as `Function.prototype.observes` if prototype extensions are
enabled.
@method observer
@for Ember
@param {String} propertyNames*
@param {Function} func
@return func
@public
*/
function observer() {
for (_len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5];
}
var func = args.slice(-1)[0],
_len5,
args,
_key5,
i;
var paths = void 0;
var addWatchedProperty = function (path) {
paths.push(path);
};
var _paths = args.slice(0, -1);
if (typeof func !== 'function') {
// revert to old, soft-deprecated argument ordering
true && !false && emberDebug.deprecate('Passing the dependentKeys after the callback function in Ember.observer is deprecated. Ensure the callback function is the last argument.', false, { id: 'ember-metal.observer-argument-order', until: '3.0.0' });
func = args[0];
_paths = args.slice(1);
}
paths = [];
for (i = 0; i < _paths.length; ++i) {
expandProperties(_paths[i], addWatchedProperty);
}
if (typeof func !== 'function') {
throw new emberDebug.EmberError('Ember.observer called without a function');
}
func.__ember_observes__ = paths;
return func;
}
/**
Specify a method that observes property changes.
```javascript
Ember.Object.extend({
valueObserver: Ember.immediateObserver('value', function() {
// Executes whenever the "value" property changes
})
});
```
In the future, `Ember.observer` may become asynchronous. In this event,
`Ember.immediateObserver` will maintain the synchronous behavior.
Also available as `Function.prototype.observesImmediately` if prototype extensions are
enabled.
@method _immediateObserver
@for Ember
@param {String} propertyNames*
@param {Function} func
@deprecated Use `Ember.observer` instead.
@return func
@private
*/
/**
When observers fire, they are called with the arguments `obj`, `keyName`.
Note, `@each.property` observer is called per each add or replace of an element
and it's not called with a specific enumeration item.
A `_beforeObserver` fires before a property changes.
@method beforeObserver
@for Ember
@param {String} propertyNames*
@param {Function} func
@return func
@deprecated
@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} name (optional) The name the property will lookup, defaults
to the property's name
@private
*/
function InjectedProperty(type, name) {
this.type = type;
this.name = name;
this._super$Constructor(injectedPropertyGet);
AliasedPropertyPrototype.oneWay.call(this);
}
function injectedPropertyGet(keyName) {
var desc = this[keyName];
var owner = emberUtils.getOwner(this) || this.container; // fallback to `container` for backwards compat
true && !(desc && desc.isDescriptor && desc.type) && emberDebug.assert('InjectedProperties should be defined with the Ember.inject computed property macros.', desc && desc.isDescriptor && desc.type);
true && !owner && emberDebug.assert('Attempting to lookup an injected property on an object without a container, ensure that the object was instantiated via a container.', owner);
return owner.lookup(desc.type + ':' + (desc.name || keyName));
}
InjectedProperty.prototype = Object.create(Descriptor.prototype);
var InjectedPropertyPrototype = InjectedProperty.prototype;
var ComputedPropertyPrototype$1 = ComputedProperty.prototype;
var AliasedPropertyPrototype = AliasedProperty.prototype;
InjectedPropertyPrototype._super$Constructor = ComputedProperty;
InjectedPropertyPrototype.get = ComputedPropertyPrototype$1.get;
InjectedPropertyPrototype.readOnly = ComputedPropertyPrototype$1.readOnly;
InjectedPropertyPrototype.teardown = ComputedPropertyPrototype$1.teardown;
var splice = Array.prototype.splice;
/**
A wrapper for a native ES5 descriptor. In an ideal world, we wouldn't need
this at all, however, the way we currently flatten/merge our mixins require
a special value to denote a descriptor.
@class Descriptor
@private
*/
var Descriptor$1 = function (_EmberDescriptor) {
emberBabel.inherits(Descriptor$$1, _EmberDescriptor);
function Descriptor$$1(desc) {
var _this = emberBabel.possibleConstructorReturn(this, _EmberDescriptor.call(this));
_this.desc = desc;
return _this;
}
Descriptor$$1.prototype.setup = function (obj, key) {
Object.defineProperty(obj, key, this.desc);
};
Descriptor$$1.prototype.teardown = function () {};
return Descriptor$$1;
}(Descriptor);
/**
@module ember
@submodule ember-metal
*/
exports['default'] = Ember;
exports.computed = function (func) {
var args = void 0;
if (arguments.length > 1) {
args = [].slice.call(arguments);
func = args.pop();
}
var cp = new ComputedProperty(func);
if (args) {
cp.property.apply(cp, args);
}
return cp;
};
exports.cacheFor = cacheFor;
exports.ComputedProperty = ComputedProperty;
exports.alias = function (altKey) {
return new AliasedProperty(altKey);
};
exports.merge = function (original, updates) {
if (!updates || typeof updates !== 'object') {
return original;
}
var props = Object.keys(updates),
i;
var prop = void 0;
for (i = 0; i < props.length; i++) {
prop = props[i];
original[prop] = updates[prop];
}
return original;
};
exports.deprecateProperty = function (object, deprecatedKey, newKey, options) {
function _deprecate() {
true && !false && emberDebug.deprecate('Usage of `' + deprecatedKey + '` is deprecated, use `' + newKey + '` instead.', false, options);
}
Object.defineProperty(object, deprecatedKey, {
configurable: true,
enumerable: false,
set: function (value) {
_deprecate();
set(this, newKey, value);
},
get: function () {
_deprecate();
return get(this, newKey);
}
});
};
exports.instrument = instrument;
exports._instrumentStart = _instrumentStart;
exports.instrumentationReset = function () {
subscribers.length = 0;
cache = {};
};
exports.instrumentationSubscribe = function (pattern, object) {
var paths = pattern.split('.'),
i;
var path = void 0;
var regex = [];
for (i = 0; i < paths.length; i++) {
path = paths[i];
if (path === '*') {
regex.push('[^\\.]*');
} else {
regex.push(path);
}
}
regex = regex.join('\\.');
regex = regex + '(\\..*)?';
var subscriber = {
pattern: pattern,
regex: new RegExp('^' + regex + '$'),
object: object
};
subscribers.push(subscriber);
cache = {};
return subscriber;
};
exports.instrumentationUnsubscribe = function (subscriber) {
var index = void 0,
i;
for (i = 0; i < subscribers.length; i++) {
if (subscribers[i] === subscriber) {
index = i;
}
}
subscribers.splice(index, 1);
cache = {};
};
exports.getOnerror = function () {
return onerror;
};
exports.setOnerror = setOnerror;
exports.dispatchError = dispatchError;
exports.setDispatchOverride = function (handler) {
dispatchOverride = handler;
};
exports.getDispatchOverride = function () {
return dispatchOverride;
};
exports.META_DESC = META_DESC;
exports.meta = meta;
exports.Cache = Cache;
exports._getPath = _getPath;
exports.get = get;
exports.getWithDefault = function (root, key, defaultValue) {
var value = get(root, key);
if (value === undefined) {
return defaultValue;
}
return value;
};
exports.set = set;
exports.trySet = trySet;
exports.WeakMap = WeakMap$1;
exports.accumulateListeners = accumulateListeners;
exports.addListener = addListener;
exports.hasListeners = function (obj, eventName) {
var meta$$1 = exports.peekMeta(obj);
if (!meta$$1) {
return false;
}
var matched = meta$$1.matchingListeners(eventName);
return matched !== undefined && matched.length > 0;
};
exports.listenersFor = listenersFor;
exports.on = function () {
for (_len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var func = args.pop(),
_len,
args,
_key;
func.__ember_listens__ = args;
return func;
};
exports.removeListener = removeListener;
exports.sendEvent = sendEvent;
exports.suspendListener = suspendListener;
exports.suspendListeners = suspendListeners;
exports.watchedEvents = function (obj) {
return meta(obj).watchedEvents();
};
exports.isNone = isNone;
exports.isEmpty = isEmpty;
exports.isBlank = isBlank;
exports.isPresent = function (obj) {
return !isBlank(obj);
};
exports.run = run$1;
exports.ObserverSet = ObserverSet;
exports.beginPropertyChanges = beginPropertyChanges;
exports.changeProperties = changeProperties;
exports.endPropertyChanges = endPropertyChanges;
exports.overrideChains = overrideChains;
exports.propertyDidChange = propertyDidChange;
exports.propertyWillChange = propertyWillChange;
exports.PROPERTY_DID_CHANGE = PROPERTY_DID_CHANGE;
exports.defineProperty = defineProperty;
exports.Descriptor = Descriptor;
exports._hasCachedComputedProperties = function () {
hasCachedComputedProperties = true;
};
exports.watchKey = watchKey;
exports.unwatchKey = unwatchKey;
exports.ChainNode = ChainNode;
exports.finishChains = function (meta$$1) {
// finish any current chains node watchers that reference obj
var chainWatchers = meta$$1.readableChainWatchers();
if (chainWatchers !== undefined) {
chainWatchers.revalidateAll();
}
// ensure that if we have inherited any chains they have been
// copied onto our own meta.
if (meta$$1.readableChains() !== undefined) {
meta$$1.writableChains(makeChainNode);
}
};
exports.removeChainWatcher = removeChainWatcher;
exports.watchPath = watchPath;
exports.unwatchPath = unwatchPath;
exports.destroy = function (obj) {
deleteMeta(obj);
};
exports.isWatching = function (obj, key) {
if (typeof obj !== 'object' || obj === null) {
return false;
}
var meta$$1 = exports.peekMeta(obj);
return (meta$$1 && meta$$1.peekWatching(key)) > 0;
};
exports.unwatch = unwatch;
exports.watch = watch;
exports.watcherCount = function (obj, key) {
var meta$$1 = exports.peekMeta(obj);
return meta$$1 && meta$$1.peekWatching(key) || 0;
};
exports.libraries = libraries;
exports.Libraries = Libraries;
exports.Map = Map;
exports.MapWithDefault = MapWithDefault;
exports.OrderedSet = OrderedSet;
exports.getProperties = function (obj) {
var ret = {};
var propertyNames = arguments;
var i = 1;
if (arguments.length === 2 && Array.isArray(arguments[1])) {
i = 0;
propertyNames = arguments[1];
}
for (; i < propertyNames.length; i++) {
ret[propertyNames[i]] = get(obj, propertyNames[i]);
}
return ret;
};
exports.setProperties = function (obj, properties) {
if (!properties || typeof properties !== 'object') {
return properties;
}
changeProperties(function () {
var props = Object.keys(properties),
i;
var propertyName = void 0;
for (i = 0; i < props.length; i++) {
propertyName = props[i];
set(obj, propertyName, properties[propertyName]);
}
});
return properties;
};
exports.expandProperties = expandProperties;
exports._suspendObserver = _suspendObserver;
exports._suspendObservers = function (obj, paths, target, method, callback) {
var events = paths.map(changeEvent);
return suspendListeners(obj, events, target, method, callback);
};
exports.addObserver = addObserver;
exports.observersFor = function (obj, path) {
return listenersFor(obj, changeEvent(path));
};
exports.removeObserver = removeObserver;
exports._addBeforeObserver = _addBeforeObserver;
exports._removeBeforeObserver = _removeBeforeObserver;
exports.Mixin = Mixin;
exports.aliasMethod = function (methodName) {
return new Alias(methodName);
};
exports._immediateObserver = function () {
var i, arg;
true && !false && emberDebug.deprecate('Usage of `Ember.immediateObserver` is deprecated, use `Ember.observer` instead.', false, { id: 'ember-metal.immediate-observer', until: '3.0.0' });
for (i = 0; i < arguments.length; i++) {
arg = arguments[i];
true && !(typeof arg !== 'string' || arg.indexOf('.') === -1) && emberDebug.assert('Immediate observers must observe internal properties only, not properties on other objects.', typeof arg !== 'string' || arg.indexOf('.') === -1);
}
return observer.apply(this, arguments);
};
exports._beforeObserver = function () {
for (_len6 = arguments.length, args = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
args[_key6] = arguments[_key6];
}
var func = args.slice(-1)[0],
_len6,
args,
_key6,
i;
var paths = void 0;
var addWatchedProperty = function (path) {
paths.push(path);
};
var _paths = args.slice(0, -1);
if (typeof func !== 'function') {
// revert to old, soft-deprecated argument ordering
func = args[0];
_paths = args.slice(1);
}
paths = [];
for (i = 0; i < _paths.length; ++i) {
expandProperties(_paths[i], addWatchedProperty);
}
if (typeof func !== 'function') {
throw new emberDebug.EmberError('_beforeObserver called without a function');
}
func.__ember_observesBefore__ = paths;
return func;
};
exports.mixin = function (obj) {
var _len, args, _key;
for (_len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
applyMixin(obj, args, false);
return obj;
};
exports.observer = observer;
exports.required = function () {
true && !false && emberDebug.deprecate('Ember.required is deprecated as its behavior is inconsistent and unreliable.', false, { id: 'ember-metal.required', until: '3.0.0' });
return REQUIRED;
};
exports.REQUIRED = REQUIRED;
exports.hasUnprocessedMixins = function () {
return unprocessedFlag;
};
exports.clearUnprocessedMixins = function () {
unprocessedFlag = false;
};
exports.detectBinding = detectBinding;
exports.Binding = Binding;
exports.bind = function (obj, to, from) {
return new Binding(to, from).connect(obj);
};
exports.isGlobalPath = isGlobalPath;
exports.InjectedProperty = InjectedProperty;
exports.setHasViews = function (fn) {
hasViews = fn;
};
exports.tagForProperty = function (object, propertyKey, _meta) {
if (typeof object !== 'object' || object === null) {
return _glimmer_reference.CONSTANT_TAG;
}
var meta$$1 = _meta || meta(object);
if (meta$$1.isProxy()) {
return tagFor(object, meta$$1);
}
var tags = meta$$1.writableTags();
var tag = tags[propertyKey];
if (tag) {
return tag;
}
return tags[propertyKey] = makeTag();
};
exports.tagFor = tagFor;
exports.markObjectAsDirty = markObjectAsDirty;
exports.replace = function (array, idx, amt, objects) {
var args = [].concat(objects);
var ret = [];
// https://code.google.com/p/chromium/issues/detail?id=56588
var size = 60000;
var start = idx;
var ends = amt;
var count = void 0,
chunk = void 0;
while (args.length) {
count = ends > size ? size : ends;
if (count <= 0) {
count = 0;
}
chunk = args.splice(0, size);
chunk = [start, count].concat(chunk);
start += size;
ends -= count;
ret = ret.concat(splice.apply(array, chunk));
}
return ret;
};
exports.isProxy = function (value) {
var meta$$1;
if (typeof value === 'object' && value) {
meta$$1 = exports.peekMeta(value);
return meta$$1 && meta$$1.isProxy();
}
return false;
};
exports.descriptor = function (desc) {
return new Descriptor$1(desc);
};
Object.defineProperty(exports, '__esModule', { value: true });
});
enifed('ember-template-compiler/compat', ['ember-metal', 'ember-template-compiler/system/precompile', 'ember-template-compiler/system/compile', 'ember-template-compiler/system/compile-options'], function (_emberMetal, _precompile, _compile, _compileOptions) {
'use strict';
var EmberHandlebars = _emberMetal.default.Handlebars = _emberMetal.default.Handlebars || {}; // reexports
var EmberHTMLBars = _emberMetal.default.HTMLBars = _emberMetal.default.HTMLBars || {};
EmberHTMLBars.precompile = EmberHandlebars.precompile = _precompile.default;
EmberHTMLBars.compile = EmberHandlebars.compile = _compile.default;
EmberHTMLBars.registerPlugin = _compileOptions.registerPlugin;
});
enifed('ember-template-compiler/index', ['exports', 'ember-template-compiler/system/precompile', 'ember-template-compiler/system/compile', 'ember-template-compiler/system/compile-options', 'ember-template-compiler/plugins', 'ember-metal', 'ember/features', 'ember-environment', 'ember/version', 'ember-template-compiler/compat', 'ember-template-compiler/system/bootstrap'], function (exports, _precompile, _compile, _compileOptions, _plugins, _emberMetal, _features, _emberEnvironment, _version) {
'use strict';
exports.defaultPlugins = exports.registerPlugin = exports.compileOptions = exports.compile = exports.precompile = exports._Ember = undefined;
Object.defineProperty(exports, 'precompile', {
enumerable: true,
get: function () {
return _precompile.default;
}
});
Object.defineProperty(exports, 'compile', {
enumerable: true,
get: function () {
return _compile.default;
}
});
Object.defineProperty(exports, 'compileOptions', {
enumerable: true,
get: function () {
return _compileOptions.default;
}
});
Object.defineProperty(exports, 'registerPlugin', {
enumerable: true,
get: function () {
return _compileOptions.registerPlugin;
}
});
Object.defineProperty(exports, 'defaultPlugins', {
enumerable: true,
get: function () {
return _plugins.default;
}
});
// private API used by ember-cli-htmlbars to setup ENV and FEATURES
if (!_emberMetal.default.ENV) {
_emberMetal.default.ENV = _emberEnvironment.ENV;
}
if (!_emberMetal.default.FEATURES) {
_emberMetal.default.FEATURES = _features.FEATURES;
}
if (!_emberMetal.default.VERSION) {
_emberMetal.default.VERSION = _version.default;
}
exports._Ember = _emberMetal.default;
});
enifed('ember-template-compiler/plugins/assert-reserved-named-arguments', ['exports', 'ember-debug', 'ember-template-compiler/system/calculate-location-display'], function (exports, _emberDebug, _calculateLocationDisplay) {
'use strict';
exports.default = AssertReservedNamedArguments;
function AssertReservedNamedArguments(options) {
this.syntax = null;
this.options = options;
}
AssertReservedNamedArguments.prototype.transform = function (ast) {
var moduleName = this.options.meta.moduleName;
this.syntax.traverse(ast, {
PathExpression: function (node) {
if (node.original[0] === '@') {
true && !false && (0, _emberDebug.assert)(assertMessage(moduleName, node));
}
}
});
return ast;
};
function assertMessage(moduleName, node) {
var path = node.original;
var source = (0, _calculateLocationDisplay.default)(moduleName, node.loc);
return '\'' + path + '\' is not a valid path. ' + source;
}
});
enifed('ember-template-compiler/plugins/deprecate-render-model', ['exports', 'ember-debug', 'ember-template-compiler/system/calculate-location-display'], function (exports, _emberDebug, _calculateLocationDisplay) {
'use strict';
exports.default = DeprecateRenderModel;
function DeprecateRenderModel(options) {
this.syntax = null;
this.options = options;
}
DeprecateRenderModel.prototype.transform = function (ast) {
var moduleName = this.options.meta.moduleName;
var walker = new this.syntax.Walker();
walker.visit(ast, function (node) {
if (!validate(node)) {
return;
}
each(node.params, function (param) {
if (param.type !== 'PathExpression') {
return;
}
true && !false && (0, _emberDebug.deprecate)(deprecationMessage(moduleName, node, param), false, {
id: 'ember-template-compiler.deprecate-render-model',
until: '3.0.0',
url: 'http://emberjs.com/deprecations/v2.x#toc_model-param-in-code-render-code-helper'
});
});
});
return ast;
};
function validate(node) {
return node.type === 'MustacheStatement' && node.path.original === 'render' && node.params.length > 1;
}
function each(list, callback) {
var i, l;
for (i = 0, l = list.length; i < l; i++) {
callback(list[i]);
}
}
function deprecationMessage(moduleName, node, param) {
var sourceInformation = (0, _calculateLocationDisplay.default)(moduleName, node.loc);
var componentName = node.params[0].original;
var modelName = param.original;
return 'Please refactor `' + ('{{render "' + componentName + '" ' + modelName + '}}') + '` to a component and invoke via' + (' `' + ('{{' + componentName + ' model=' + modelName + '}}') + '`. ' + sourceInformation);
}
});
enifed('ember-template-compiler/plugins/deprecate-render', ['exports', 'ember-debug', 'ember-template-compiler/system/calculate-location-display'], function (exports, _emberDebug, _calculateLocationDisplay) {
'use strict';
exports.default = DeprecateRender;
function DeprecateRender(options) {
this.syntax = null;
this.options = options;
}
DeprecateRender.prototype.transform = function (ast) {
var moduleName = this.options.meta.moduleName;
var walker = new this.syntax.Walker();
walker.visit(ast, function (node) {
if (!validate(node)) {
return;
}
each(node.params, function (param) {
if (param.type !== 'StringLiteral') {
return;
}
true && !false && (0, _emberDebug.deprecate)(deprecationMessage(moduleName, node), false, {
id: 'ember-template-compiler.deprecate-render',
until: '3.0.0',
url: 'http://emberjs.com/deprecations/v2.x#toc_code-render-code-helper'
});
});
});
return ast;
};
function validate(node) {
return node.type === 'MustacheStatement' && node.path.original === 'render' && node.params.length === 1;
}
function each(list, callback) {
var i, l;
for (i = 0, l = list.length; i < l; i++) {
callback(list[i]);
}
}
function deprecationMessage(moduleName, node) {
var sourceInformation = (0, _calculateLocationDisplay.default)(moduleName, node.loc);
var componentName = node.params[0].original;
return 'Please refactor `' + ('{{render "' + componentName + '"}}') + '` to a component and invoke via' + (' `' + ('{{' + componentName + '}}') + '`. ' + sourceInformation);
}
});
enifed('ember-template-compiler/plugins/index', ['exports', 'ember-template-compiler/plugins/transform-old-binding-syntax', 'ember-template-compiler/plugins/transform-item-class', 'ember-template-compiler/plugins/transform-angle-bracket-components', 'ember-template-compiler/plugins/transform-input-on-to-onEvent', 'ember-template-compiler/plugins/transform-top-level-components', 'ember-template-compiler/plugins/transform-inline-link-to', 'ember-template-compiler/plugins/transform-old-class-binding-syntax', 'ember-template-compiler/plugins/transform-quoted-bindings-into-just-bindings', 'ember-template-compiler/plugins/deprecate-render-model', 'ember-template-compiler/plugins/deprecate-render', 'ember-template-compiler/plugins/assert-reserved-named-arguments', 'ember-template-compiler/plugins/transform-action-syntax', 'ember-template-compiler/plugins/transform-input-type-syntax', 'ember-template-compiler/plugins/transform-attrs-into-args', 'ember-template-compiler/plugins/transform-each-in-into-each', 'ember-template-compiler/plugins/transform-has-block-syntax', 'ember-template-compiler/plugins/transform-dot-component-invocation'], function (exports, _transformOldBindingSyntax, _transformItemClass, _transformAngleBracketComponents, _transformInputOnToOnEvent, _transformTopLevelComponents, _transformInlineLinkTo, _transformOldClassBindingSyntax, _transformQuotedBindingsIntoJustBindings, _deprecateRenderModel, _deprecateRender, _assertReservedNamedArguments, _transformActionSyntax, _transformInputTypeSyntax, _transformAttrsIntoArgs, _transformEachInIntoEach, _transformHasBlockSyntax, _transformDotComponentInvocation) {
'use strict';
exports.default = Object.freeze([_transformDotComponentInvocation.default, _transformOldBindingSyntax.default, _transformItemClass.default, _transformAngleBracketComponents.default, _transformInputOnToOnEvent.default, _transformTopLevelComponents.default, _transformInlineLinkTo.default, _transformOldClassBindingSyntax.default, _transformQuotedBindingsIntoJustBindings.default, _deprecateRenderModel.default, _deprecateRender.default, _assertReservedNamedArguments.default, _transformActionSyntax.default, _transformInputTypeSyntax.default, _transformAttrsIntoArgs.default, _transformEachInIntoEach.default, _transformHasBlockSyntax.default]);
});
enifed('ember-template-compiler/plugins/transform-action-syntax', ['exports'], function (exports) {
'use strict';
exports.default = TransformActionSyntax;
/**
@module ember
@submodule ember-glimmer
*/
/**
A Glimmer2 AST transformation that replaces all instances of
```handlebars