diff --git a/flatn/flatn-cjs.js b/flatn/flatn-cjs.js index 1a2dc06779..ed96409027 100644 --- a/flatn/flatn-cjs.js +++ b/flatn/flatn-cjs.js @@ -15493,7 +15493,7 @@ const requestMap = {}; class ESMResource extends Resource { static normalize (esmUrl) { - const id = esmUrl.replaceAll(/esm:\/\/(run|cache)\//g, ''); + const id = esmUrl.replaceAll(/esm:\/\/([^\/]*)\//g, ''); let pathStructure = id.split('/').filter(Boolean); @@ -15511,7 +15511,6 @@ class ESMResource extends Resource { pathStructure.push(fileName); } - if (pathStructure[pathStructure.length - 1].endsWith('+esm')) { pathStructure[pathStructure.length - 1] = pathStructure[pathStructure.length - 1].replace('+esm', 'esm.js'); } @@ -15527,13 +15526,22 @@ class ESMResource extends Resource { return pathStructure; } - async read () { - let module; - - const id = this.url.replace(/esm:\/\/(run|cache)\//g, ''); - let baseUrl = 'https://jspm.dev/'; + getEsmURL () { + let baseUrl; if (this.url.startsWith('esm://run/npm/')) baseUrl = 'https://cdn.jsdelivr.net/'; else if (this.url.startsWith('esm://run/')) baseUrl = 'https://esm.run/'; + else if (this.url.startsWith('esm://cache/')) baseUrl = 'https://jspm.dev/'; + else { + const domain = this.url.match(/esm:\/\/([^\/]*)\//)?.[1]; + baseUrl = `https://${domain}/`; + } + return baseUrl; + } + + async read () { + let module; + const id = this.url.replace(/esm:\/\/([^\/]*)\//g, ''); + const esmURL = this.getEsmURL(); let pathStructure = ESMResource.normalize(id); @@ -15544,7 +15552,7 @@ class ESMResource extends Resource { if (typeof lively !== 'undefined' && (hit = lively.memory_esm?.get(shortName))) return await hit.blob.text(); module = await res.read(); } else { - module = await resource((baseUrl + id)).read(); + module = await resource((esmURL + id)).read(); res.write(module); } return module; @@ -15627,7 +15635,9 @@ class ESMResource extends Resource { } async exists () { - // stub that needs to exist + const id = this.url.replace(/esm:\/\/([^\/]*)\//g, ''); + const baseUrl = this.getEsmURL(); + return await resource(baseUrl).join(id).exists(); } async remove () { diff --git a/lively.ast/lib/mozilla-ast-visitors.js b/lively.ast/lib/mozilla-ast-visitors.js index 5c480d1f70..e12a39e5eb 100644 --- a/lively.ast/lib/mozilla-ast-visitors.js +++ b/lively.ast/lib/mozilla-ast-visitors.js @@ -395,6 +395,52 @@ class ScopeVisitor extends Visitor { return node; } + visitForStatement (node, scope, path) { + const visitor = this; + // init is of types VariableDeclaration, Expression + if (node.init) { + node.init = visitor.accept(node.init, scope, path.concat(['init'])); + } + // test is of types Expression + if (node.test) { + node.test = visitor.accept(node.test, scope, path.concat(['test'])); + } + // update is of types Expression + if (node.update) { + node.update = visitor.accept(node.update, scope, path.concat(['update'])); + } + // body is of types Statement + node.body = visitor.accept(node.body, this.newScope(node, scope), path.concat(['body'])); + return node; + } + + visitForInStatement (node, scope, path) { + const visitor = this; + // left is of types VariableDeclaration, Pattern + node.left = visitor.accept(node.left, scope, path.concat(['left'])); + // right is of types Expression + node.right = visitor.accept(node.right, scope, path.concat(['right'])); + // body is of types Statement + node.body = visitor.accept(node.body, this.newScope(node, scope), path.concat(['body'])); + return node; + } + + visitIfStatement (node, scope, path) { + const visitor = this; + + node.test = visitor.accept(node.test, scope, path.concat(['test'])); + + const consequentScope = this.newScope(node, scope); + node.consequent = visitor.accept(node.consequent, consequentScope, path.concat(['consequent'])); + + if (node.alternate) { + const alternateScope = this.newScope(node, scope); + node.alternate = visitor.accept(node.alternate, alternateScope, path.concat(['alternate'])); + } + + return node; + } + visitLabeledStatement (node, scope, path) { const visitor = this; // ignore label diff --git a/lively.ast/lib/nodes.js b/lively.ast/lib/nodes.js index fe6ae995bc..07238f699e 100644 --- a/lively.ast/lib/nodes.js +++ b/lively.ast/lib/nodes.js @@ -32,7 +32,7 @@ function binaryExpr (left, op, right) { }; } -function funcExpr ({ arrow, id: funcId, expression, generator }, params = [], ...statements) { +function funcExpr ({ arrow, id: funcId, expression, generator, isAsync }, params = [], ...statements) { // lively.ast.stringify(funcExpr({id: "foo"}, ["a"], exprStmt(id("3")))) // // => "function foo(a) { 3; }" params = params.map(ea => typeof ea === 'string' ? id(ea) : ea); @@ -44,7 +44,8 @@ function funcExpr ({ arrow, id: funcId, expression, generator }, params = [], .. ? statements[0] : { body: statements, type: 'BlockStatement' }, expression: expression || false, - generator: generator || false + generator: generator || false, + async: isAsync }; } diff --git a/lively.ast/lib/query.js b/lively.ast/lib/query.js index 63ccf25760..8635b8b262 100644 --- a/lively.ast/lib/query.js +++ b/lively.ast/lib/query.js @@ -443,7 +443,7 @@ function statementOf (parsed, node, options) { // Find the statement that a target node is in. Example: // let source be "var x = 1; x + 1;" and we are looking for the // Identifier "x" in "x+1;". The second statement is what will be found. - const nodes = nodesAt(node.start, parsed); + const nodes = nodesAt(node.start + 1, parsed); const found = nodes.reverse().find(node => _stmtTypes.includes(node.type)); if (options && options.asPath) { const v = new BaseVisitor(); let foundPath; diff --git a/lively.ast/tests/es6-test.js b/lively.ast/tests/es6-test.js index 490050e824..7b48f2a7ff 100644 --- a/lively.ast/tests/es6-test.js +++ b/lively.ast/tests/es6-test.js @@ -1,16 +1,14 @@ -/*global process, require, beforeEach, afterEach, describe, it*/ +/* global process, require, beforeEach, afterEach, describe, it */ -import { expect } from "mocha-es6"; +import { expect } from 'mocha-es6'; -import { parse } from "../lib/parser.js"; +import { parse } from '../lib/parser.js'; -describe('es6', function() { - - it("arrow function", function() { - var code = '() => 23;' - var parsed = parse(code); - expect(parsed).deep.property("body[0].expression.type") - .equals("ArrowFunctionExpression"); +describe('es6', function () { + it('arrow function', function () { + let code = '() => 23;'; + let parsed = parse(code); + expect(parsed).has.nested.property('body[0].expression.type') + .equals('ArrowFunctionExpression'); }); - }); diff --git a/lively.ast/tests/parser-test.js b/lively.ast/tests/parser-test.js index 2abfc05702..23a0dae7d3 100644 --- a/lively.ast/tests/parser-test.js +++ b/lively.ast/tests/parser-test.js @@ -1,53 +1,48 @@ -/*global beforeEach, afterEach, describe, it*/ +/* global beforeEach, afterEach, describe, it */ -import { expect } from "mocha-es6"; +import { expect } from 'mocha-es6'; -import { printAst } from "../lib/mozilla-ast-visitor-interface.js"; -import { parse, parseFunction } from "../lib/parser.js"; - -describe('parse', function() { +import { printAst } from '../lib/mozilla-ast-visitor-interface.js'; +import { parse, parseFunction } from '../lib/parser.js'; +describe('parse', function () { it('JavaScript code', () => - expect(parse("1 + 2")) - .deep.property("body[0].type") - .equals("ExpressionStatement")); - - describe("async / await", () => { - - it("parses nested awaits", () => { - var src = "await (await foo()).bar()", - parsed = parse(src), - expected = ":Program(0-25)\n" - + "\\-.body[0]:ExpressionStatement(0-25)\n" - + " \\-.body[0].expression:AwaitExpression(0-25)\n" - + " \\-.body[0].expression.argument:CallExpression(6-25)\n" - + " \\-.body[0].expression.argument.callee:MemberExpression(6-23)\n" - + " |-.body[0].expression.argument.callee.object:AwaitExpression(7-18)\n" - + " | \\-.body[0].expression.argument.callee.object.argument:CallExpression(13-18)\n" - + " | \\-.body[0].expression.argument.callee.object.argument.callee:Identifier(13-16)\n" - + " \\-.body[0].expression.argument.callee.property:Identifier(20-23)" - expect(printAst(parsed, {printPositions: true})).to.equal(expected); + expect(parse('1 + 2')) + .nested.property('body[0].type') + .equals('ExpressionStatement')); + + describe('async / await', () => { + it('parses nested awaits', () => { + let src = 'await (await foo()).bar()'; + let parsed = parse(src); + let expected = ':Program(0-25)\n' + + '\\-.body[0]:ExpressionStatement(0-25)\n' + + ' \\-.body[0].expression:AwaitExpression(0-25)\n' + + ' \\-.body[0].expression.argument:CallExpression(6-25)\n' + + ' \\-.body[0].expression.argument.callee:MemberExpression(6-23)\n' + + ' |-.body[0].expression.argument.callee.object:AwaitExpression(7-18)\n' + + ' | \\-.body[0].expression.argument.callee.object.argument:CallExpression(13-18)\n' + + ' | \\-.body[0].expression.argument.callee.object.argument.callee:Identifier(13-16)\n' + + ' \\-.body[0].expression.argument.callee.property:Identifier(20-23)'; + expect(printAst(parsed, { printPositions: true })).to.equal(expected); }); - }); - describe("parseFunction", () => { - - it("anonmyous function", () => { - expect(parseFunction("function(x) { return x + 1; }").type).equals("FunctionExpression") + describe('parseFunction', () => { + it('anonmyous function', () => { + expect(parseFunction('function(x) { return x + 1; }').type).equals('FunctionExpression'); }); - it("named function", () => { - expect(parseFunction("function foo(x) { return x + 1; }")).containSubset({type: "FunctionExpression", id: {name: "foo"}}) + it('named function', () => { + expect(parseFunction('function foo(x) { return x + 1; }')).containSubset({ type: 'FunctionExpression', id: { name: 'foo' } }); }); - it("arrow function", () => { - expect(parseFunction("(x) => { return x + 1; }")).containSubset({type: "ArrowFunctionExpression"}) + it('arrow function', () => { + expect(parseFunction('(x) => { return x + 1; }')).containSubset({ type: 'ArrowFunctionExpression' }); }); - it("short function", () => { - expect(parseFunction("x => x + 1")).containSubset({type: "ArrowFunctionExpression"}) + it('short function', () => { + expect(parseFunction('x => x + 1')).containSubset({ type: 'ArrowFunctionExpression' }); }); - }); }); diff --git a/lively.classes/class-to-function-transform.js b/lively.classes/class-to-function-transform.js index 20d354695d..88b9462d99 100644 --- a/lively.classes/class-to-function-transform.js +++ b/lively.classes/class-to-function-transform.js @@ -1,21 +1,48 @@ -import { Path } from 'lively.lang'; +import { Path, arr } from 'lively.lang'; import { parse, stringify, query, nodes, BaseVisitor as Visitor } from 'lively.ast'; import { queryNodes } from 'lively.ast/lib/query.js'; - -let { - assign, - member, - id, - funcCall, - literal, - objectLiteral, - varDecl, - funcExpr, - returnStmt, - binaryExpr, - ifStmt, - block -} = nodes; +const acornNodes = { + exportDefaultDecl: (declaration) => { + return { + declaration, + type: 'ExportDefaultDeclaration' + }; + }, + conditional: nodes.conditional, + binaryExpr: (op, left, right) => nodes.binaryExpr(left, op, right), + logicalExpr: (op, left, right) => nodes.binaryExpr(left, op, right), + unaryExpr: (operator, argument) => { + return { type: 'UnaryExpression', operator, argument }; + }, + arrayExpr: (elements) => { + return { + elements, type: 'ArrayExpression' + }; + }, + exprStmt: (expr) => nodes.exprStmt(expr), + ifStmt: nodes.ifStmt, + funcCall: (func, args) => nodes.funcCall(func, ...args), + id: (name) => nodes.id(name), + assign: (operator, left, right) => nodes.assign(left, right), + member: nodes.member, + block: (stmts) => nodes.block(...stmts), + literal: (val) => nodes.literal(val), + property: (kind, key, val) => nodes.prop(key, val), + returnStmt: nodes.returnStmt, + arrowFuncExpr: (args, body, generator, isAsync) => nodes.funcExpr({ arrow: true, expression: false, generator, isAsync }, args, ...body.body), + funcExpr: (id, args, body, generator, isAsync) => nodes.funcExpr({ id, expression: false, generator, isAsync }, args, ...body.body), + objectLiteral: (props) => nodes.objectLiteral(props.map(prop => [prop.key, prop.value]).flat()), + varDecl: nodes.varDecl, + declaration: (kind, declarations) => ({ + type: 'VariableDeclaration', + kind: kind || 'var', + declarations: declarations || [] + }), + declarator: (id, init) => ({ + type: 'VariableDeclarator', id, init + }), + parse +}; function isFunctionNode (node) { return node.type === 'ArrowFunctionExpression' || @@ -31,11 +58,13 @@ function ensureIdentifier (name) { .replace(trailingIdRe, '_'); } -function classFieldsInitialization (nodes) { +function classFieldsInitialization (nodes, options) { + const { assign, member, id, exprStmt } = options.nodes; return nodes.map(({ key, value }) => { let name = key.name; if (key.type === 'PrivateIdentifier') name = '_' + name; - return assign(member('this', name), value); + if (key.type === 'PrivateName') name = '_' + key.id.name; + return exprStmt(assign('=', member(id('this'), id(name)), value === null ? id('null') : value)); }); } @@ -57,21 +86,23 @@ function classFieldsInitialization (nodes) { * @param {string} name - The name of the class that is being defined. * @param {object[]} fields - The set of custom class fields that were defined by the code. */ -function constructorTemplate (name, fields) { - return funcExpr({ id: name ? id(name) : null }, ['__first_arg__'], - ifStmt( - binaryExpr( - id('__first_arg__'), + +function constructorTemplate (name, fields, options) { + const n = options.nodes; + return n.funcExpr(name ? n.id(name) : null, [n.id('__first_arg__')], + n.block([n.ifStmt( + n.logicalExpr( '&&', - member('__first_arg__', funcCall(member('Symbol', 'for'), literal('lively-instance-restorer')), true)), - block(), - block( - ...classFieldsInitialization(fields), - returnStmt( - funcCall( - member( - member('this', funcCall(member('Symbol', 'for'), literal('lively-instance-initialize')), true), - 'apply'), id('this'), id('arguments')))))); + n.id('__first_arg__'), + n.member(n.id('__first_arg__'), n.funcCall(n.member(n.id('Symbol'), n.id('for')), [n.literal('lively-instance-restorer')]), true)), + n.block([]), + n.block( + [...classFieldsInitialization(fields, options), + n.returnStmt( + n.funcCall( + n.member( + n.member(n.id('this'), n.funcCall(n.member(n.id('Symbol'), n.id('for')), [n.literal('lively-instance-initialize')]), true), + n.id('apply')), [n.id('this'), n.id('arguments')]))]))])); } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- @@ -81,18 +112,17 @@ const methodKindSymbol = Symbol(); const tempLivelyClassVar = '__lively_class__'; const tempLivelyClassHolderVar = '__lively_classholder__'; -function splitExportDefaultWithClass (node, classHolder, path, options) { +function splitExportDefaultWithClass (node, classHolder, options) { + const n = options.nodes; return !node.declaration || !node.declaration[isTransformedClassVarDeclSymbol] ? node - : [node.declaration, { - declaration: node.declaration.declarations[0].id, - type: 'ExportDefaultDeclaration' - }]; + : [node.declaration, n.exportDefaultDecl(node.declaration.declarations[0].id)]; } function replaceSuper (node, state, path, options) { // just super console.assert(node.type === 'Super'); + const n = options.nodes; let { currentMethod } = state; if (!currentMethod) { @@ -103,8 +133,8 @@ function replaceSuper (node, state, path, options) { if ((parentReferencedAs === 'callee' && referencedAs === 'object') || referencedAs === 'callee') { return node; } // deal with this in replaceSuperCall let methodHolder = currentMethod && currentMethod[methodKindSymbol] === 'static' - ? funcCall(member('Object', 'getPrototypeOf'), id(tempLivelyClassVar)) - : funcCall(member('Object', 'getPrototypeOf'), member(id(tempLivelyClassVar), 'prototype')); + ? n.funcCall(n.member(n.id('Object'), n.id('getPrototypeOf')), [n.id(tempLivelyClassVar)]) + : n.funcCall(n.member(n.id('Object'), n.id('getPrototypeOf')), [n.member(n.id(tempLivelyClassVar), n.id('prototype'))]); return methodHolder; } @@ -113,90 +143,94 @@ function replaceSuperMethodCall (node, state, path, options) { // like super.foo() console.assert(node.type === 'CallExpression'); console.assert(node.callee.object.type === 'Super'); - - return funcCall( - member( - funcCall( - member(options.functionNode, '_get'), - replaceSuper(node.callee.object, state, path.concat(['callee', 'object']), options), - literal(node.callee.property.value || node.callee.property.name), - id('this')), - 'call'), - id('this'), ...node.arguments); + const n = options.nodes; + return n.funcCall( + n.member( + n.funcCall( + n.member(options.functionNode, n.id('_get')), + [replaceSuper(node.callee.object, state, path.concat(['callee', 'object']), options), + n.literal(node.callee.property.value || node.callee.property.name), + n.id('this')]), + n.id('call')), + [n.id('this'), ...node.arguments]); } function replaceDirectSuperCall (node, state, path, options) { // like super() console.assert(node.type === 'CallExpression'); console.assert(node.callee.type === 'Super'); - const f = funcCall( - member( - funcCall( - member(options.functionNode, '_get'), - replaceSuper(node.callee, state, path.concat(['callee']), options), - funcCall(member('Symbol', 'for'), literal('lively-instance-initialize')), - id('this')), - 'call'), - id('this'), ...node.arguments); - return assign(id('_this'), f); + const n = options.nodes; + const f = n.funcCall( + n.member( + n.funcCall( + n.member(options.functionNode, n.id('_get')), + [replaceSuper(node.callee, state, path.concat(['callee']), options), + n.funcCall(n.member(n.id('Symbol'), n.id('for')), [n.literal('lively-instance-initialize')]), + n.id('this')]), + n.id('call')), + [n.id('this'), ...node.arguments]); + return n.assign('=', n.id('_this'), f); } function replaceSuperGetter (node, state, path, options) { console.assert(node.type === 'MemberExpression'); console.assert(node.object.type === 'Super'); - return funcCall( - member(options.functionNode, '_get'), - replaceSuper(node.object, state, path.concat(['object']), options), - literal(node.property.value || node.property.name), - id('this')); + const n = options.nodes; + return n.funcCall( + n.member(options.functionNode, n.id('_get')), + [replaceSuper(node.object, state, path.concat(['object']), options), + n.literal(node.property.value || node.property.name), + n.id('this')]); } function replaceSuperSetter (node, state, path, options) { console.assert(node.type === 'AssignmentExpression'); console.assert(node.left.object.type === 'Super'); - - return funcCall( - member(options.functionNode, '_set'), - replaceSuper(node.left.object, state, path.concat(['left', 'object']), options), - literal(node.left.property.value || node.left.property.name), - node.right, - id('this')); + const n = options.nodes; + return n.funcCall( + n.member(options.functionNode, n.id('_set')), + [replaceSuper(node.left.object, state, path.concat(['left', 'object']), options), + n.literal(node.left.property.value || node.left.property.name), + node.right, + n.id('this')]); } function checkForDirectSuperCall (body) { return queryNodes(body, '// CallExpression [ /:callee \'*\' [ type() == \'Super\']]').length > 0; } -function insertThisReturn (functionBody) { +function insertThisReturn (functionBody, options) { if (!checkForDirectSuperCall(functionBody)) { return functionBody; } + const n = options.nodes; return { // block ...functionBody, body: [ - varDecl(id('_this')), + n.varDecl(n.id('_this')), ...functionBody.body, - returnStmt(id('_this')) + n.returnStmt(n.id('_this')) ] }; } -function replaceClass (node, state, path, options) { +function replaceClass (node, state, options) { console.assert(node.type === 'ClassDeclaration' || node.type === 'ClassExpression'); - + const n = options.nodes; let { body: { body }, superClass, id: classId, type, start, end } = node; let { addClassNameGetter = true } = options; - let instanceProps = id('undefined'); - let classProps = id('undefined'); + let instanceProps = n.id('undefined'); + let classProps = n.id('undefined'); let className = classId ? classId.name : 'anonymous_class'; let evalId = options.evalId; let sourceAccessorName = options.sourceAccessorName; - let loc = node['x-lively-object-meta'] || { start, end }; - const validMemberIdentifiers = ['Literal', 'Identifier', 'PrivateIdentifier', 'MemberExpression', 'CallExpression']; + let loc = { start, end, ...node['x-lively-object-meta'] || {} }; + const validMemberIdentifiers = ['Literal', 'StringLiteral', 'Identifier', 'PrivateIdentifier', 'PrivateName', 'MemberExpression', 'CallExpression']; let { inst, clazz, fields } = body.reduce((props, propNode) => { let decl; let { key, kind, value, static: classSide, type } = propNode; + if (!value) value = propNode; if (!validMemberIdentifiers.includes(key.type)) { console.warn(`Unexpected key in classToFunctionTransform! ${JSON.stringify(key)} -> ${stringify(propNode)}`); @@ -213,28 +247,30 @@ function replaceClass (node, state, path, options) { let methodName = key.name || key.value || Path('property.name').get(key); let methodId; if (isMemberExpr) { - methodId = id(className + '_' + stringify(key.property).replaceAll('.', '_') + '_'); - } else methodId = id(className + '_' + ensureIdentifier(methodName || Path('arguments.0.value').get(key)) + '_'); + methodId = n.id(className + '_' + stringify(key.property).replaceAll('.', '_') + '_'); + } else methodId = n.id(className + '_' + ensureIdentifier(methodName || Path('arguments.0.value').get(key)) + '_'); + let props = [ - 'key', !isMemberExpr && methodName ? literal(methodName) : key, - 'value', { ...value, id: methodId, [methodKindSymbol]: classSide ? 'static' : 'proto' }]; + n.property('init', n.id('key'), !isMemberExpr && methodName ? n.literal(methodName) : key), + + n.property('init', n.id('value'), (value = n.funcExpr(methodId, value.params, value.body, value.generator, value.async), value[methodKindSymbol] = classSide ? 'static' : 'proto', value))]; - decl = objectLiteral(props); + decl = n.objectLiteral(props); } else if (kind === 'get' || kind === 'set') { - decl = objectLiteral([ - 'key', literal(key.name || key.value || Path('property.name').get(key)), - kind, Object.assign({}, value, { id: id(kind), [methodKindSymbol]: classSide ? 'static' : 'proto' })]); + decl = n.objectLiteral([ + n.property('init', n.id('key'), n.literal(key.name || key.value || Path('property.name').get(key))), + n.property('init', n.id(kind), (value = n.funcExpr(n.id(kind), value.params, value.body, value.generator, value.async), value[methodKindSymbol] = classSide ? 'static' : 'proto', value))]); } else if (kind === 'constructor') { let props = [ - 'key', funcCall(member('Symbol', 'for'), literal('lively-instance-initialize')), - 'value', { - ...value, - id: id(className + '_initialize_'), - [methodKindSymbol]: 'proto', - body: insertThisReturn(value.body) - }]; - decl = objectLiteral(props); - } else if (type === 'PropertyDefinition') { + n.property('init', n.id('key'), n.funcCall(n.member(n.id('Symbol'), n.id('for')), [n.literal('lively-instance-initialize')])), + n.property('init', n.id('value'), (value = n.funcExpr( + n.id(className + '_initialize_'), + value.params, + insertThisReturn(value.body, options), + value.generator, value.async + ), value[methodKindSymbol] = 'proto', value))]; + decl = n.objectLiteral(props); + } else if (['PropertyDefinition', 'ClassPrivateProperty', 'ClassProperty'].includes(type)) { // collect these for class field initializiation props.fields.push(propNode); } else { @@ -248,13 +284,13 @@ function replaceClass (node, state, path, options) { clazz: addClassNameGetter ? [ // explicitly add in a static property to ensure the class name is accessible also in google closure env - parse(`({ key: Symbol.for("__LivelyClassName__"), get: function get() { return "${className}"; } })`).body[0].expression + n.parse(`({ key: Symbol.for("__LivelyClassName__"), get: function get() { return "${className}"; } })`).body[0].expression ] : [] }); - if (inst.length) instanceProps = { type: 'ArrayExpression', elements: inst }; - if (clazz.length) classProps = { type: 'ArrayExpression', elements: clazz }; + if (inst.length) instanceProps = n.arrayExpr(inst); + if (clazz.length) classProps = n.arrayExpr(clazz); let scope = options.scope; let superClassReferencedAs; @@ -265,8 +301,8 @@ function replaceClass (node, state, path, options) { superClassRef = superClass; superClassReferencedAs = superClass.property.name; } else { - let found = scope && scope.resolvedRefMap && scope.resolvedRefMap.get(superClass); - let isTopLevel = found && found.decl && scope.decls && scope.decls.find(([decl]) => decl === found.decl); + let found = scope?.resolvedRefMap?.get(superClass); + let isTopLevel = found?.decl && scope.decls?.find(([decl]) => decl === found.decl); if (isTopLevel) { superClassRef = superClass; superClassReferencedAs = superClass.name; @@ -275,77 +311,74 @@ function replaceClass (node, state, path, options) { } let superClassSpec = superClassRef - ? objectLiteral(['referencedAs', literal(superClassReferencedAs), 'value', superClassRef]) - : superClass || id('undefined'); + // this is inserting incorrect nodes into the ast since scope ist always acorn nodes + ? n.objectLiteral([n.property('init', n.id('referencedAs'), n.literal(superClassReferencedAs)), n.property('init', n.id('value'), superClassRef)]) + : superClass || n.id('undefined'); // For persistent storage and retrieval of pre-existing classes in "classHolder" object let { useClassHolder = classId && (type === 'ClassDeclaration' || type === 'ClassExpression') } = options; // if the class is assigned this will not work - let locKeyVals = ['start', literal(loc.start), 'end', literal(loc.end)]; - if (typeof evalId !== 'undefined') locKeyVals.push('evalId', literal(evalId)); - if (sourceAccessorName) locKeyVals.push('moduleSource', nodes.id(sourceAccessorName)); - let locNode = objectLiteral(locKeyVals); - - let classCreator = - funcCall( - funcExpr({}, ['superclass'], - varDecl(tempLivelyClassHolderVar, state.classHolder), - varDecl(tempLivelyClassVar, - useClassHolder - ? { - type: 'ConditionalExpression', - test: binaryExpr( - funcCall(member(tempLivelyClassHolderVar, 'hasOwnProperty'), literal(classId.name)), - '&&', - binaryExpr( - { - argument: member(tempLivelyClassHolderVar, classId), - operator: 'typeof', - prefix: true, - type: 'UnaryExpression' - }, '===', literal('function'))), - consequent: member(tempLivelyClassHolderVar, classId), - alternate: assign( - member(tempLivelyClassHolderVar, classId), - constructorTemplate(classId.name, fields)) - } - : classId ? constructorTemplate(classId.name, fields) : constructorTemplate(null, fields)), - ifStmt(funcCall(member(id('Object'), id('isFrozen')), id(tempLivelyClassHolderVar)), block(returnStmt(id(tempLivelyClassVar))), false), - returnStmt( - funcCall( - options.functionNode, - id(tempLivelyClassVar), - id('superclass'), + let locKeyVals = [n.property('init', n.id('start'), n.literal(loc.start)), n.property('init', n.id('end'), n.literal(loc.end))]; + if (typeof evalId !== 'undefined') locKeyVals.push(n.property('init', n.id('evalId'), n.literal(evalId))); + if (sourceAccessorName) locKeyVals.push(n.property('init', n.id('moduleSource'), nodes.id(sourceAccessorName))); + let locNode = n.objectLiteral(locKeyVals); + let funcParts = [[n.id('superclass')], + n.block([ + n.varDecl(n.id(tempLivelyClassHolderVar), state.classHolder), + ...useClassHolder + ? [n.varDecl(n.id(tempLivelyClassVar), + n.conditional( + n.logicalExpr( + '&&', + n.funcCall(n.member(n.id(tempLivelyClassHolderVar), n.id('hasOwnProperty')), [n.literal(classId.name)]), + n.binaryExpr( + '===', + n.unaryExpr('typeof', n.member(n.id(tempLivelyClassHolderVar), classId), true), + n.literal('function'))), + n.member(n.id(tempLivelyClassHolderVar), classId), + n.assign( + '=', + n.member(n.id(tempLivelyClassHolderVar), classId), + constructorTemplate(classId.name, fields, options))) + )] + : classId + ? [n.varDecl(classId, constructorTemplate(classId.name, fields, options)), n.varDecl(n.id(tempLivelyClassVar), classId)] + : [n.varDecl(n.id(tempLivelyClassVar), constructorTemplate(null, fields, options))], + n.ifStmt(n.funcCall(n.member(n.id('Object'), n.id('isFrozen')), [n.id(tempLivelyClassHolderVar)]), n.block([n.returnStmt(n.id(tempLivelyClassVar))]), null), + n.returnStmt( + n.funcCall( + options.functionNode, + [n.id(tempLivelyClassVar), + n.id('superclass'), instanceProps, classProps, - useClassHolder ? id(tempLivelyClassHolderVar) : id('null'), - options.currentModuleAccessor || id('undefined'), - locNode - ))), - superClassSpec); + useClassHolder ? n.id(tempLivelyClassHolderVar) : n.id('null'), + options.currentModuleAccessor || n.id('undefined'), + locNode] + ))])]; - if (type === 'ClassExpression') return classCreator; + if (type === 'ClassExpression') return n.funcCall(n.arrowFuncExpr(...funcParts), [superClassSpec]); - let result = classCreator; + let result = n.funcCall(n.funcExpr(null, ...funcParts), [superClassSpec]); if (options.declarationWrapper && state.classHolder === options.classHolder /* i.e. toplevel */) { - result = funcCall( + result = n.funcCall( options.declarationWrapper, - literal(classId.name), - literal('class'), - result, - options.classHolder, - locNode); + [n.literal(classId.name), + n.literal('class'), + result, + options.classHolder, + locNode]); } // since it is a declaration and we removed the class construct we need to add a var-decl - result = varDecl(classId, result, 'var'); + result = n.varDecl(classId, result, 'var'); result[isTransformedClassVarDeclSymbol] = true; return result; } -function replacePrivateIdentifier (node) { - return { ...node, type: 'Identifier', name: '_' + node.name }; +function replacePrivateIdentifier (node, options) { + return options.nodes.id('_' + node.name); } /** @@ -353,18 +386,25 @@ function replacePrivateIdentifier (node) { * we need to implement the custom lively class notation. */ class ClassReplaceVisitor extends Visitor { + static run (parsed, options) { + let v = new this(); + let classHolder = options.classHolder || nodes.objectLiteral([]); + return v.accept(parsed, { options, classHolder }, []); + } + + // FIXME: this is an extremely obscure way of implementing a custom visitor accept (node, state, path) { if (isFunctionNode(node)) { state = { ...state, - classHolder: objectLiteral([]), + classHolder: nodes.objectLiteral([]), currentMethod: node[methodKindSymbol] ? node : state.currentMethod }; } if (node.type === 'ClassExpression' || node.type === 'ClassDeclaration') { if (node._skipClassHolder) state.options.useClassHolder = false; - node = replaceClass(node, state, path, state.options); + node = replaceClass(node, state, state.options); delete state.options.useClassHolder; } @@ -376,7 +416,7 @@ class ClassReplaceVisitor extends Visitor { node.right._skipClassHolder = true; } - if (node.type === 'PrivateIdentifier') node = replacePrivateIdentifier(node); + if (node.type === 'PrivateIdentifier') node = replacePrivateIdentifier(node, state.options); if (node.type === 'Super') { node = replaceSuper(node, state, path, state.options); } @@ -391,17 +431,114 @@ class ClassReplaceVisitor extends Visitor { node = super.accept(node, state, path); if (node.type === 'ExportDefaultDeclaration') { - return splitExportDefaultWithClass(node, state, path, state.options); + return splitExportDefaultWithClass(node, state, state.options); } return node; } +} - static run (parsed, options) { - let v = new this(); - let classHolder = options.classHolder || objectLiteral([]); - return v.accept(parsed, { options, classHolder }, []); +export function classToFunctionTransformBabel (path, state, options) { + function getPropPath (path) { + const propPath = [path.name]; + while (path = path.parent) { + propPath.push(String(path.name)); + } + return propPath; } + + function handleFunctionDefinition (path, state) { + const { nodes: n } = options; + const { classHolder, currentMethodStack, currentMethod } = state; + currentMethodStack.push(path.node[methodKindSymbol] ? path.node : currentMethod); + state.currentMethod = arr.last(currentMethodStack); + } + + function handleClass (path, state) { + const { node } = path; + if (node._skipClassHolder) options.useClassHolder = false; + + path.replaceWith(replaceClass(node, state, options)); + path.traverse(this.visitor, state); + delete options.useClassHolder; + } + + const currentMethodStack = []; + Object.assign(state, { + classHolder: options.classHolder || options.nodes.objectLiteral([]), + currentMethodStack + }); + + path.traverse({ + 'ArrowFunctionExpression|FunctionDeclaration|FunctionExpression': { + enter: handleFunctionDefinition, + exit (path, state) { + state.currentMethodStack.pop(); + state.currentMethod = arr.last(state.currentMethodStack); + } + }, + + ClassExpression (path, state) { + handleClass.bind(this)(path, state); + }, + + ClassDeclaration (path, state) { + handleClass.bind(this)(path, state); + }, + + VariableDeclarator (path, state) { + const { node } = path; + if (node.init?.type === 'ClassExpression' || node.init?.type === 'ClassDeclaration') { + node.init._skipClassHolder = true; + } + }, + + AssignmentExpression (path, state) { + const { node } = path; + if (node.right?.type === 'ClassExpression' || node.right?.type === 'ClassDeclaration') { + node.right._skipClassHolder = true; + } + if (node.left.type === 'MemberExpression' && node.left.object.type === 'Super') { + path.replaceWith(replaceSuperSetter(node, state, getPropPath(path), options)); + } + }, + + PrivateName (path, state) { + path.replaceWith(replacePrivateIdentifier(path.node, options)); + path.skip(); + }, + + Super (path, state) { + path.replaceWith(replaceSuper(path.node, state, getPropPath(path), options)); + path.skip(); + }, + + MemberExpression (path, state) { + const { node } = path; + if (node.object?.type === 'Super') { + path.replaceWith(replaceSuperGetter(node, state, getPropPath(path), options)); + } + }, + + CallExpression (path, state) { + const { node } = path; + if (node.callee.type === 'Super') { + path.replaceWith(replaceDirectSuperCall(node, state, getPropPath(path), options)); + } + if (node.callee.object && node.callee.object.type === 'Super') { + path.replaceWith(replaceSuperMethodCall(node, state, getPropPath(path), options)); + } + }, + + ExportDefaultDeclaration (path, state) { + const { node } = path; + const { nodes: n } = options; + if (node.declaration.type === 'ClassDeclaration') { + path.insertAfter([replaceClass(node.declaration, state, options), n.exportDefaultDecl(node.declaration.id)]); + path.remove(); + } + } + }, state); } /** @@ -422,6 +559,7 @@ class ClassReplaceVisitor extends Visitor { export function classToFunctionTransform (sourceOrAst, options) { let parsed = typeof sourceOrAst === 'string' ? parse(sourceOrAst) : sourceOrAst; options.scope = query.resolveReferences(query.scopes(parsed)); + if (!options.nodes) options = { ...options, nodes: acornNodes }; let replaced = ClassReplaceVisitor.run(parsed, options); diff --git a/lively.classes/tests/class-to-function-transform-test.js b/lively.classes/tests/class-to-function-transform-test.js index 3cbb6988da..e5481589c3 100644 --- a/lively.classes/tests/class-to-function-transform-test.js +++ b/lively.classes/tests/class-to-function-transform-test.js @@ -8,31 +8,35 @@ import { member } from 'lively.ast/lib/nodes.js'; import { parse } from 'lively.ast/lib/parser.js'; import stringify from 'lively.ast/lib/stringify.js'; -function classTemplate (className, superClassName, methodString, classMethodString, classHolder, moduleMeta, useClassHolder = true, start, end) { - if (methodString.includes('\n')) methodString = string.indent(methodString, ' ', 2).replace(/^\s+/, ''); - if (classMethodString.includes('\n')) classMethodString = string.indent(classMethodString, ' ', 2).replace(/^\s+/, ''); +function classTemplate (className, superClassName, methodString, classMethodString, classHolder, moduleMeta, useClassHolder = true, start, end, evalId) { + if (methodString.includes('\n')) methodString = string.indent(methodString, ' ', 4).replace(/^\s+/, ''); + if (classMethodString.includes('\n')) classMethodString = string.indent(classMethodString, ' ', 4).replace(/^\s+/, ''); if (!className) useClassHolder = false; let classFunctionHeader = className ? `function ${className}` : 'function '; if (useClassHolder) { classFunctionHeader = `__lively_classholder__.hasOwnProperty("${className}") && typeof __lively_classholder__.${className} === "function" ? __lively_classholder__.${className} : __lively_classholder__.${className} = ${classFunctionHeader}`; } - return `function (superclass) { + let pos = ''; + if (start !== undefined && end !== undefined) { + pos = `, { + start: ${start}, + end: ${end}${evalId ? `,\n evalId: ${evalId}` : ''} + }`; + } + return `${useClassHolder ? 'function (superclass)' : '(superclass =>'} { var __lively_classholder__ = ${classHolder}; - var __lively_class__ = ${classFunctionHeader}(__first_arg__) { + var ${useClassHolder ? '__lively_class__' : (className ? 'Foo' : '__lively_class__')} = ${classFunctionHeader}(__first_arg__) { if (__first_arg__ && __first_arg__[Symbol.for("lively-instance-restorer")]) { } else { return this[Symbol.for("lively-instance-initialize")].apply(this, arguments); } - }; + };${(useClassHolder || !className) ? '' : '\n var __lively_class__ = Foo;'} if (Object.isFrozen(__lively_classholder__)) { return __lively_class__; } - return initializeClass(__lively_class__, superclass, ${methodString}, ${classMethodString}, ${ useClassHolder ? '__lively_classholder__' : 'null'}, ${moduleMeta}, { - start: ${start}, - end: ${end} - }); -}(${superClassName});`; + return initializeClass(__lively_class__, superclass, ${methodString}, ${classMethodString}, ${ useClassHolder ? '__lively_classholder__' : 'null'}, ${moduleMeta}${pos}); +}${useClassHolder ? '' : ')'}(${superClassName});`; } function classTemplateDecl (className, superClassName, methodString, classMethodString, classHolder, moduleMeta, start, end) { diff --git a/lively.classes/tests/object-class-test.js b/lively.classes/tests/object-class-test.js index f5739939b9..32df94722b 100644 --- a/lively.classes/tests/object-class-test.js +++ b/lively.classes/tests/object-class-test.js @@ -27,9 +27,9 @@ let S, opts, packagesToRemove; describe('object package', function () { beforeEach(async () => { S = getSystem('test', { baseURL: testBaseURL }); - S.set('lively.transpiler', System.get('lively.transpiler')); - S.config({ transpiler: 'lively.transpiler' }); - S.translate = async (load) => await System.translate.bind(S)(load); + S.set('lively.transpiler.babel', System.get('lively.transpiler.babel')); + S.config({ transpiler: 'lively.transpiler.babel' }); + S.translate = async (load, opts) => await System.translate.bind(S)(load, opts); S._scripting = scripting; opts = { baseURL: testBaseURL, System: S }; await createFiles(testBaseURL, testResources); diff --git a/lively.classes/tests/properties-test.js b/lively.classes/tests/properties-test.js index d4d931014d..208fd1cc97 100644 --- a/lively.classes/tests/properties-test.js +++ b/lively.classes/tests/properties-test.js @@ -85,13 +85,13 @@ describe('properties', function () { let obj = new classA(); prepareInstanceForProperties(obj, { valueStoreProperty: '_store' }, { test: {} }); expect(obj).has.property('_store'); - expect(obj).has.deep.property('_store.test', undefined); + expect(obj).has.nested.property('_store.test', undefined); }); it('sets default values', () => { let obj = new classA(); prepareInstanceForProperties(obj, { valueStoreProperty: '_store' }, { test: { defaultValue: 23 } }); - expect(obj).has.deep.property('_store.test', 23); + expect(obj).has.nested.property('_store.test', 23); }); it('sets default value with initializer for derived value', () => { @@ -140,7 +140,7 @@ describe('properties', function () { let x = 3; let obj = new classA(); prepareInstanceForProperties(obj, { valueStoreProperty: '_store' }, { test: { initialize: () => x += 2 } }); expect(x).equals(5); - expect(obj).has.deep.property('_store.test', undefined); + expect(obj).has.nested.property('_store.test', undefined); }); it('initialize uses values from outside', () => { diff --git a/lively.classes/tests/source-descriptor-test.js b/lively.classes/tests/source-descriptor-test.js index 33513a8827..640a2fccea 100644 --- a/lively.classes/tests/source-descriptor-test.js +++ b/lively.classes/tests/source-descriptor-test.js @@ -23,9 +23,9 @@ let S; describe('source descriptors', function () { beforeEach(async () => { S = getSystem('test', { baseURL: testDir }); - S.set('lively.transpiler', System.get('lively.transpiler')); - S.config({ transpiler: 'lively.transpiler' }); - S.translate = async (load) => await System.translate.bind(S)(load); + S.set('lively.transpiler.babel', System.get('lively.transpiler.babel')); + S.config({ transpiler: 'lively.transpiler.babel' }); + S.translate = async (load, opts) => await System.translate.bind(S)(load, opts); S._scripting = System._scripting; await createFiles(testDir, testResources); await importPackage(S, 'project1'); diff --git a/lively.freezer/index.js b/lively.freezer/index.js index 3ec0741a3b..c889f40eae 100644 --- a/lively.freezer/index.js +++ b/lively.freezer/index.js @@ -17,25 +17,6 @@ import BrowserResolver from './src/resolvers/browser.js'; import { lively } from './src/plugins/rollup.js'; // for rollup import { currentUsername } from 'lively.user'; - -/* - -How to build the bootstrap and memory adapters with the freezer. Will replace build scripts completely in the future. - -await bootstrapLibrary('lively.classes/runtime.js', '/classes.runtime.min.js',); -await bootstrapLibrary('/lively.server/index-base.js', 'lively.server/bin/server.min.js', false) -await bootstrapLibrary('lively.morphic/web/bootstrap.js', 'lively.morphic/web/lively.bootstrap.min.js'); -await bootstrapLibrary('lively.modules/tools/bootstrap.js', 'lively.modules/dist/new_lively.modules.bootstrap.min.js', false, 'lively.modules'); - -await jspmCompile( - url = 'https://dev.jspm.io/pouchdb-adapter-memory', - out = 'lively.storage/dist/pouchdb-adapter-mem.min.js', - globalName = 'window.pouchdbAdapterMem', redirect = { - "https://dev.jspm.io/npm:ltgt@2.1.3/index.dew.js": "https://dev.jspm.io/npm:ltgt@2.2.1/index.dew.js" - } -) -*/ - // fixme: Why is that a difference between parts and worlds? Why do we need kld-intersections at all? const DEFAULT_EXCLUDED_MODULES_PART = [ 'kld-intersections' diff --git a/lively.freezer/package.json b/lively.freezer/package.json index 62931e6f6d..832c6f1b8d 100644 --- a/lively.freezer/package.json +++ b/lively.freezer/package.json @@ -12,7 +12,9 @@ "google-closure-compiler-linux": "^20200927.0.0", "google-closure-compiler-osx": "^20200927.0.0", "wasm-brotli": "1.0.2", - "rollup": "2.68.0", + "rollup": "4.27.3", + "@rollup/rollup-linux-x64-gnu": "4.27.3", + "@rollup/rollup-darwin-arm64": "4.27.3", "css": "3.0.0", "@rollup/plugin-babel": "5.3.1", "@rollup/plugin-json": "6.0.0", diff --git a/lively.freezer/src/bundler.js b/lively.freezer/src/bundler.js index f5191f77bc..8bdbf3ab32 100644 --- a/lively.freezer/src/bundler.js +++ b/lively.freezer/src/bundler.js @@ -49,7 +49,7 @@ const CLASS_INSTRUMENTATION_MODULES = [ 'https://jspm.dev/npm:rollup@2.28.2' // this contains a bunch of class definitions which right now screws up the closure compiler ]; -const ESM_CDNS = ['jspm.dev', 'jspm.io', 'skypack.dev', 'esm://cache', 'esm://run']; +const ESM_CDNS = ['jspm.dev', 'jspm.io', 'skypack.dev', 'esm://cache', 'esm://run', /esm:\/\/([^\/]*)\//]; // fixme: Why is a blacklist nessecary if there is a whitelist? const CLASS_INSTRUMENTATION_MODULES_EXCLUSION = ['lively.lang']; @@ -71,6 +71,32 @@ const ADVANCED_EXCLUDED_MODULES = [ const baseURL = typeof System !== 'undefined' ? System.baseURL : ensureFolder(process.env.lv_next_dir || process.cwd()); +export function bulletProofNamespaces (code) { + let rewrites = []; + let parsed = ast.parse(code, { withComments: true }); + const pureComments = parsed.allComments.filter(c => c.text === '#__PURE__'); + if (pureComments.length === 0) return null; + parsed = ast.ReplaceVisitor.run(parsed, (node) => { + if (node.type === 'VariableDeclaration') { + const matchingComment = pureComments.find(c => node.start < c.start && c.end > node.end); + if (!matchingComment) return node; + const matchingGetter = node.declarations[0]?.init?.arguments?.[0]?.properties?.find(prop => prop.key.name === 'default' && prop.kind === 'get'); + if (!matchingGetter) return node; + const getterBody = matchingGetter.value.body; + const [returnStmt] = getterBody.body; + rewrites.push([getterBody, `\nif (typeof ${returnStmt.argument.name} === 'undefined') throw new Error('Module not yet initialized!');\n`]) + } + return node; + }); + if (rewrites.length > 0) { + arr.sortBy(rewrites, ([node]) => node.start).forEach(([node, snippet]) => { + code = code.slice(0, node.start + 1) + snippet + code.slice(node.start + 1); + }); + return code; + } + return null; +} + /** * Custom warn() that is triggered by RollupJS to inidicate problems with the bundle. * @param { object } warning - The warning object. @@ -125,9 +151,10 @@ function resolutionId (id, importer) { * @returns { boolean } Wether or not the module was served from an ESM CDN. */ function isCdnImport (id, importer, resolver) { - if (ESM_CDNS.find(cdn => id.includes(cdn) || importer.includes(cdn)) && importer && importer !== ROOT_ID) { + + if (ESM_CDNS.find(cdn => id.match(cdn) || importer.match(cdn)) && importer && importer !== ROOT_ID) { const { url } = resource(resolver.ensureFileFormat(importer)).root(); // get the cdn host root - return ESM_CDNS.find(cdn => url.includes(cdn)); + return ESM_CDNS.find(cdn => url.match(cdn)); } return false; } @@ -177,6 +204,7 @@ export default class LivelyRollup { this.projectAssets = []; this.customFontFiles = []; this.projectsInBundle = new Set(); + this.moduleToPkg = new Map(); this.resolver.setStatus({ label: 'Freezing in Progress' }); } @@ -320,7 +348,7 @@ export default class LivelyRollup { * @returns { boolean } */ wasFetchedFromEsmCdn (moduleId) { - return !!ESM_CDNS.find(url => moduleId.includes(url)); + return !!ESM_CDNS.find(url => moduleId.match(url)); } /** @@ -457,14 +485,32 @@ export default class LivelyRollup { if (isCdnImport(id, importer, this.resolver)) { if (id.startsWith('.')) { id = resource(importer).parent().join(id).withRelativePartsResolved().url; - } else { + } else if (id.startsWith('/')) { id = resource(importer).root().join(id).withRelativePartsResolved().url; } } - const importingPackage = this.resolver.resolvePackage(importer); + const importingPackage = this.resolver.resolvePackage(importer) || this.moduleToPkg.get(importer); // honor the systemjs options within the package config - const mapping = importingPackage?.systemjs?.map; + const { map: mapping, importMap } = importingPackage?.systemjs || {}; + if (importMap) { + let remapped; + if (remapped = importMap.imports?.[id]) { + id = remapped; + } + let scope, prefix; + if (scope = Object.entries(importMap.scopes) + .filter(([k, v]) => importer.startsWith(k)) + .sort((a, b) => a[0].length - b[0].length) + .map(([prefix, scope]) => scope) + .reduce((a, b) => ({ ...a, ...b }), false)) { + remapped = scope[id]; + } + if (remapped) { + id = remapped; + } + } + this.moduleToPkg.set(id, importingPackage); if (mapping) { this.globalMap = { ...this.globalMap, ...mapping }; if (mapping[id] || this.globalMap[id]) { diff --git a/lively.freezer/src/plugins/rollup.js b/lively.freezer/src/plugins/rollup.js index 33d190a4dc..b82a069c06 100644 --- a/lively.freezer/src/plugins/rollup.js +++ b/lively.freezer/src/plugins/rollup.js @@ -1,4 +1,4 @@ -import LivelyRollup, { customWarn } from '../bundler.js'; +import LivelyRollup, { customWarn, bulletProofNamespaces } from '../bundler.js'; import { ROOT_ID } from '../util/helpers.js'; import { obj, arr } from 'lively.lang'; @@ -35,7 +35,7 @@ export function lively (args) { name: 'rollup-plugin-lively', buildStart () { return bundler.buildStart(this); }, resolveId: async (id, importer) => { - if (isBuiltin(id, bundler.resolver) || id.startsWith('\0')) return null; + if (importer?.startsWith('\0') || id.startsWith('\0')) return null; let res = await bundler.resolveId(map[id] || id, importer); return res; }, @@ -106,6 +106,12 @@ export function lively (args) { } return opts; }, + renderChunk(code) { + if (code.includes('get default ()')) { + return bulletProofNamespaces(code); + } + return null; + }, renderDynamicImport: () => { bundler.hasDynamicImports = true; // set flag to handle dynamic imports return null; // render via default diff --git a/lively.freezer/src/resolvers/node.cjs b/lively.freezer/src/resolvers/node.cjs index 3a6b56a893..7386759be8 100644 --- a/lively.freezer/src/resolvers/node.cjs +++ b/lively.freezer/src/resolvers/node.cjs @@ -42,11 +42,15 @@ async function availableFonts(fontCSSFile) { ] } +function isCdnImport(url) { + return url.includes('jspm.dev') || + url.includes('esm://'); +} + function isAlreadyResolved(url) { if (url.startsWith('file://') || url.startsWith('https://') || - url.includes('jspm.dev') || - url.includes('esm://') || + isCdnImport(url) || url.startsWith('node:')) return true; } @@ -85,6 +89,9 @@ function decanonicalizeFileName (fileName) { } function resolvePackage (moduleName) { + // if the moduleName is from a ESM cdn, we cannot determine the + // package based on the module path + if (isCdnImport(moduleName)) return; return findPackageConfig(moduleName); } @@ -208,6 +215,10 @@ function supportingPlugins(context = 'node', self) { } } }, + { + name: 'lively-resolve', + resolveId: (id, importer) => self.resolveId(id, importer) + }, // but only do resolutions so that polyfills does not screw us up context == 'browser' && nodePolyfills(), // only if we bundle for the browser commonjs({ sourceMap: false, diff --git a/lively.freezer/src/util/bootstrap.js b/lively.freezer/src/util/bootstrap.js index fa49559209..995497ac03 100644 --- a/lively.freezer/src/util/bootstrap.js +++ b/lively.freezer/src/util/bootstrap.js @@ -10,7 +10,7 @@ import { updateBundledModules } from 'lively.modules/src/module.js'; import { Project } from 'lively.project/project.js'; import { pathForBrowserHistory } from 'lively.morphic/helpers.js'; import { installLinter } from 'lively.ide/js/linter.js'; - +import { setupBabelTranspiler } from 'lively.source-transform/babel/plugin.js'; import untar from 'esm://cache/js-untar'; import bowser from 'bowser'; @@ -232,8 +232,8 @@ function bootstrapLivelySystem (progress, fastLoad = query.fastLoad !== false || lively.modules.changeSystem(System, true); $world.env.installSystemChangeHandlers(); - await loadViaScript(resource(baseURL).join('/lively.modules/systemjs-init.js').url); installLinter(System); + setupBabelTranspiler(System); logInfo('Setup SystemJS:', Date.now() - ts + 'ms'); // load packages diff --git a/lively.freezer/tools/build.landing-page.mjs b/lively.freezer/tools/build.landing-page.mjs index a665ee1800..69650b1934 100644 --- a/lively.freezer/tools/build.landing-page.mjs +++ b/lively.freezer/tools/build.landing-page.mjs @@ -21,8 +21,6 @@ try { head: ` - - ` }, minify, diff --git a/lively.freezer/tools/build.loading-screen.mjs b/lively.freezer/tools/build.loading-screen.mjs index 277d914044..3a181b986f 100644 --- a/lively.freezer/tools/build.loading-screen.mjs +++ b/lively.freezer/tools/build.loading-screen.mjs @@ -20,8 +20,6 @@ try { head: ` - - ` }, minify, diff --git a/lively.installer/install.js b/lively.installer/install.js index c5aea14cb9..75966a1c07 100644 --- a/lively.installer/install.js +++ b/lively.installer/install.js @@ -262,7 +262,6 @@ export async function setupSystem(baseURL) { modules = await import("lively.modules"); let livelySystem = modules.getSystem("lively", {baseURL, _nodeRequire: System._nodeRequire }); modules.changeSystem(livelySystem, true); - await import("lively.modules/systemjs-init.js"); var registry = livelySystem["__lively.modules__packageRegistry"] = new modules.PackageRegistry(livelySystem); registry.packageBaseDirs = process.env.FLATN_PACKAGE_COLLECTION_DIRS.split(":").map(ea => resource(`file://${ea}`)); registry.devPackageDirs = process.env.FLATN_DEV_PACKAGE_DIRS.split(":").map(ea => resource(`file://${ea}`)); @@ -270,6 +269,10 @@ export async function setupSystem(baseURL) { await registry.update(); // also reset the flatn package map, so that native requires wont fail resetPackageMap(); + + const { setupBabelTranspiler } = await import('lively.source-transform/babel/plugin.js'); + await setupBabelTranspiler(livelySystem); + return livelySystem; } diff --git a/lively.installer/package.json b/lively.installer/package.json index 4788fc7695..b6d9c0411e 100644 --- a/lively.installer/package.json +++ b/lively.installer/package.json @@ -8,6 +8,11 @@ "url": "https://github.com/LivelyKernel/lively.installer" }, "systemjs": { + "meta": { + "packages-config.json": { + "format": "json" + } + }, "map": { "child_process": { "node": "@node/child_process", diff --git a/lively.lang/tests/array-test.js b/lively.lang/tests/array-test.js index 365c099c62..d5d5cd469a 100644 --- a/lively.lang/tests/array-test.js +++ b/lively.lang/tests/array-test.js @@ -186,8 +186,8 @@ describe('arr', function () { describe('batchify', function () { it('splits array ccording to constraint', function () { - function batchConstrained (batch) { return batch.length === 1 || sum(batch) < batchMaxSize; } const batchMaxSize = Math.pow(2, 28)/* 256MB */; + function batchConstrained (batch) { return batch.length === 1 || sum(batch) < batchMaxSize; } const sizes = [ Math.pow(2, 15), // 32KB Math.pow(2, 29), // 512MB @@ -204,8 +204,8 @@ describe('arr', function () { }); it('needs to consume', function () { - function batchConstrained (batch) { return sum(batch) < batchMaxSize; } const batchMaxSize = 3; + function batchConstrained (batch) { return sum(batch) < batchMaxSize; } let sizes = [1, 4, 2, 3]; expect(() => batchify(sizes, batchConstrained)) .throws(/does not ensure consumption of at least one/); diff --git a/lively.lang/tests/function-test.js b/lively.lang/tests/function-test.js index 132263e752..90c62e4a51 100644 --- a/lively.lang/tests/function-test.js +++ b/lively.lang/tests/function-test.js @@ -50,7 +50,7 @@ describe('fun', function () { it('can extract a function body a string', function () { let f = function (arg1, arg2, arg4) { let x = { n: 33 }; return x.n + arg2 + arg4; }; - expect(fun.extractBody(f)).to.equal('let x = { n: 33 };\nreturn x.n + arg2 + arg4;'); + expect(fun.extractBody(f)).to.equal('let x = {\n n: 33\n};\nreturn x.n + arg2 + arg4;'); expect(fun.extractBody(function () {})).to.equal(''); expect(fun.extractBody(function () { 123; })).to.equal('123;'); }); diff --git a/lively.modules/src/cache.js b/lively.modules/src/cache.js index 61e8504636..db2fe18f7f 100644 --- a/lively.modules/src/cache.js +++ b/lively.modules/src/cache.js @@ -135,7 +135,7 @@ export class BrowserModuleTranslationCache extends ModuleTranslationCache { }); } - async cacheModuleSource (moduleId, hash, source, exports = []) { + async cacheModuleSource (moduleId, hash, source, exports = [], sourceMap = {}) { const db = await this.db; return new Promise((resolve, reject) => { const transaction = db.transaction([this.sourceCodeCacheStoreName], 'readwrite'); @@ -146,6 +146,7 @@ export class BrowserModuleTranslationCache extends ModuleTranslationCache { hash, source, timestamp, + sourceMap: JSON.stringify(sourceMap), exports: JSON.stringify(exports.map(({ type, exported, local, fromModule }) => ({ type, exported, local, fromModule }))) diff --git a/lively.modules/src/instrumentation.js b/lively.modules/src/instrumentation.js index ff5314fb79..c5be678bb0 100644 --- a/lively.modules/src/instrumentation.js +++ b/lively.modules/src/instrumentation.js @@ -15,6 +15,19 @@ import { BrowserModuleTranslationCache, NodeModuleTranslationCache } from './cac const isNode = System.get('@system-env').node; +// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +// Functions below are for re-loading modules from change.js. We typically +// start with a load object that skips the normalize / fetch step. Since we need +// to jump in the "middle" of the load process and SystemJS does not provide an +// interface to this, we need to invoke the translate / instantiate / execute +// manually +// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +let sourceMapPrefix = '\n//# sourceMapping' + 'URL=data:application/json;base64,'; +function inlineSourceMap (sourceMapString) { + if (!sourceMapString) return ''; + return sourceMapPrefix + string.base64EncodeUnicode(sourceMapString); +} + // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // code instrumentation // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- @@ -206,7 +219,7 @@ export async function customTranslate (load) { // to define it here to avoid an // undefined entry later! meta.deps = []; - + if (stored.sourceMap) meta.sourceMap = JSON.parse(stored.sourceMap); debug && console.log('[lively.modules customTranslate] loaded %s from browser cache after %sms', load.name, Date.now() - start); return Promise.resolve(stored.source); } @@ -240,29 +253,19 @@ export async function customTranslate (load) { console.error(`[lively.modules customTranslate] error reading module translation cache: ${e.stack}`); } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + // FIXME: move all of the stuff below into the transpilation step, it is not needed here, just wrecks performance by + // needlessly stringifying AST nodes over and over. We achieve this by implementing a custom plugin called "lively-pre-transpile" + // The reason this was placed outside of babel in the first place was that a decade ago, babel was not yet supporting a majority + // of the ecmascript syntax out of the box. - let options = meta.compileOptions = {}; + meta.compileOptions = {}; let source = load.source; - if (isEsm) { - mod.recorderName = '__lvVarRecorder'; - if (mod.recorder === System.global) { mod.unloadEnv(); } - load.metadata.format = 'esm'; - ({ options, source } = prepareCodeForCustomCompile(System, source, load.name, mod, debug)); - load.source = source; - load.metadata['lively.modules instrumented'] = true; - instrumented = true; - debug && console.log('[lively.modules] loaded %s as es6 module', load.name); - } else if (load.metadata.format === 'global') { - mod.recorderName = 'System.global'; - mod.recorder = System.global; - load.metadata.format = 'global'; - ({ options, source } = prepareCodeForCustomCompile(System, source, load.name, mod, debug)); - load.source = source; - load.metadata['lively.modules instrumented'] = true; - instrumented = true; - debug && console.log('[lively.modules] loaded %s as instrumented global module', load.name); - } + mod.recorderName = '__lvVarRecorder'; + if (mod.recorder === System.global) { mod.unloadEnv(); } + load.metadata['lively.modules instrumented'] = true; + if (isEsm) load.metadata.format = 'esm'; + load.metadata.module = mod; if (!instrumented) { debug && console.log("[lively.modules] customTranslate ignoring %s b/c don't know how to handle format %s", load.name, load.metadata.format); @@ -272,19 +275,15 @@ export async function customTranslate (load) { } export async function postCustomTranslate (load) { + // FIXME: Move this too into the transpilation step via a custom babel plugin "lively-post-transpile" const start = load.metadata.ts; if (!load.metadata['lively.modules instrumented']) return; // if we already retrieved the source from cache, not need to store it again let translated = load.source; const debug = System.debug; const indexdb = System.global.indexedDB; - const mod = module(System, load.name); - const hashForCache = load.metadata.hashForCache; - const options = load.metadata.compileOptions; const useCache = System.useModuleTranslationCache; - if (translated.indexOf('System.register(') === 0) { - debug && console.log('[lively.modules customTranslate] Installing System.register setter captures for %s', load.name); - translated = prepareTranslatedCodeForSetterCapture(System, translated, load.name, mod, options, debug); - } + const { hashForCache, compileOptions: options, sourceMap = {} } = load.metadata; + const mod = load.metadata.module; // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // cache experiment part 2 @@ -292,7 +291,7 @@ export async function postCustomTranslate (load) { let cache = System._livelyModulesTranslationCache || (System._livelyModulesTranslationCache = new NodeModuleTranslationCache()); try { - await cache.cacheModuleSource(load.name, hashForCache, translated, await mod.exports()); + await cache.cacheModuleSource(load.name, hashForCache, translated, await mod.exports(), sourceMap); debug && console.log('[lively.modules customTranslate] stored cached version in filesystem for %s', load.name); } catch (e) { console.error(`[lively.modules customTranslate] failed storing module cache: ${e.stack}`); @@ -301,7 +300,7 @@ export async function postCustomTranslate (load) { let cache = System._livelyModulesTranslationCache || (System._livelyModulesTranslationCache = new BrowserModuleTranslationCache()); try { - await cache.cacheModuleSource(load.name, hashForCache, translated, await mod.exports()); + await cache.cacheModuleSource(load.name, hashForCache, translated, await mod.exports(), sourceMap); debug && console.log('[lively.modules customTranslate] stored cached version for %s', load.name); } catch (e) { console.error(`[lively.modules customTranslate] failed storing module cache: ${e.stack}`); @@ -313,14 +312,6 @@ export async function postCustomTranslate (load) { load.source = translated; } -// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -// Functions below are for re-loading modules from change.js. We typically -// start with a load object that skips the normalize / fetch step. Since we need -// to jumo in the "middle" of the load process and SystemJS does not provide an -// interface to this, we need to invoke the translate / instantiate / execute -// manually -// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- - async function instrumentSourceOfEsmModuleLoad (System, load) { // brittle, since it relies on the particular format that SystemJS returns us! // The result of System.translate is source code for a call to @@ -328,33 +319,13 @@ async function instrumentSourceOfEsmModuleLoad (System, load) { // details from it that we will use to re-define the module // (dependencies, setters, execute) // Note: this only works for esm modules! - load.source = await customTranslate.bind(System)(load) // do that beforehand - const translated = await System.translate(load); - // translated looks like - // (function(__moduleName){System.register(["./some-es6-module.js", ...], function (_export) { - // "use strict"; - // var x, z, y; - // return { - // setters: [function (_someEs6ModuleJs) { ... }], - // execute: function () {...} - // }; - // }); - - const parsed = parse(translated); - const callExpression = parsed.body.find( - ea => - ea.expression && - ea.expression.type === 'CallExpression' && - ea.expression.callee.property.name === 'register'); - if (!callExpression) throw new Error(`Cannot find register call in translated source of ${load.name}`); - const registerCall = callExpression.expression; - const depNames = registerCall.arguments[0].elements.map(ea => ea.value); - const declareFuncNode = registerCall.arguments[1]; - const declareFuncSource = translated.slice(declareFuncNode.start, declareFuncNode.end); - const declare = eval(`var SystemJS = System; var __moduleName = "${load.name}";\n(${declareFuncSource});\n//# sourceURL=${load.name}\n`); - if (System.debug && $world !== 'undefined' && $world.get('log') && $world.get('log').isText) { $world.get('log').textString = declare; } - - return { localDeps: depNames, declare: declare }; + load.source = await customTranslate.bind(System)(load); // do that beforehand + // invoke the babel transpiler directly without doing the funny Systemjs dance + const localDeps = []; + let declareSource = await System.translate(load, { depNames: localDeps, esmLoad: true }); + declareSource += `//# sourceURL=${load.name}!transpiled`; + if (load.metadata.sourceMap) declareSource += inlineSourceMap(JSON.stringify(load.metadata.sourceMap)); + return { declare: eval(declareSource), localDeps }; } function instrumentSourceOfGlobalModuleLoad (System, load) { diff --git a/lively.modules/src/module.js b/lively.modules/src/module.js index 5bfc19c180..4e5f8d0efa 100644 --- a/lively.modules/src/module.js +++ b/lively.modules/src/module.js @@ -1,5 +1,5 @@ import { arr, obj, graph, string } from 'lively.lang'; -import { parse, query } from 'lively.ast'; +import { parse, fuzzyParse, query } from 'lively.ast'; import { computeRequireMap } from './dependencies.js'; import { moduleSourceChange } from './change.js'; import { scheduleModuleExportsChange, runScheduledExportChanges } from './import-export.js'; @@ -17,7 +17,7 @@ export const detectModuleFormat = (function () { const esmFormatCommentRegExp = /['"]format (esm|es6)['"];/; const cjsFormatCommentRegExp = /['"]format cjs['"];/; // Stolen from SystemJS - const esmRegEx = /(^\s*|[}\);\n]\s*)(import\s+(['"]|(\*\s+as\s+)?[^"'\(\)\n;]+\s+from\s+['"]|\{)|export\s+\*\s+from\s+["']|export\s+(\{|default|function|class|var|const|let|async\s+function))/; + const esmRegEx = /(^\s*|[}\);\n]\s*)(import\s*(['"]|(\*\s*as\s+)?[^"'\(\)\n;]+\s+from\s*['"]|\{)|export\s+\*\s+from\s+["']|export\s*(\{|default|function|class|var|const|let|async\s+function))/; return (source, metadata) => { if (metadata && metadata.format) { @@ -473,7 +473,7 @@ class ModuleInterface { isMochaTest () { if (!this._source) { return false; } - const scope = this._scope || (this._scope = query.topLevelDeclsAndRefs(parse(this._source)).scope); + const scope = this._scope || (this._scope = query.topLevelDeclsAndRefs(fuzzyParse(this._source)).scope); const deps = query.imports(scope).map(imp => imp.fromModule); if (!deps.some(ea => ea.endsWith('mocha-es6') || ea.endsWith('mocha-es6/index.js'))) { return false; } return true; @@ -527,6 +527,11 @@ class ModuleInterface { const require = _require.bind(null, this); require.resolve = _resolve.bind(null, this); nodejsDescriptors.require = { configurable: true, writable: true, value: require }; + nodejsDescriptors.Buffer = { + configurable: true, + get: () => this._overriddenBuffer || Buffer, + set: (buf) => this._overriddenBuffer = buf + }; } this._recorder = Object.create(S.global, { @@ -627,8 +632,10 @@ class ModuleInterface { recorder[varName] = value; // exports update - scheduleModuleExportsChange( - System, id, varName, value, false/* force adding export */); + if (!meta?.exportConflict) { + scheduleModuleExportsChange( + System, id, varName, value, false/* force adding export */); + } // system event this.notifyTopLevelObservers(varName); diff --git a/lively.modules/src/packages/package-registry.js b/lively.modules/src/packages/package-registry.js index 7619e7e156..0f1855c726 100644 --- a/lively.modules/src/packages/package-registry.js +++ b/lively.modules/src/packages/package-registry.js @@ -273,7 +273,6 @@ export class PackageRegistry { findPackageHavingURL (url) { // does url identify a resource inside pkg, maybe pkg.url === url? if (url.isResource) url = url.url; - if (url.startsWith('esm://')) return null; if (url.endsWith('/')) url = url.slice(0, -1); if (this.moduleUrlToPkg.has(url)) return this.moduleUrlToPkg.get(url); let penaltySoFar = Infinity; let found = null; let { byURL } = this; @@ -454,7 +453,7 @@ export class PackageRegistry { let pkg = (existingPackageMap && existingPackageMap[url]) || new Package(this.System, url); let config = await pkg.tryToLoadPackageConfig(); - if (url.includes('local_projects')){ + if (url.includes('local_projects')) { const forkInfoFile = resource(url).join('.livelyForkInformation'); if ((await forkInfoFile.exists())) { const forkInfo = JSON.parse((await forkInfoFile.read())); diff --git a/lively.modules/src/resource.js b/lively.modules/src/resource.js index caf3049aac..8e274c4fec 100644 --- a/lively.modules/src/resource.js +++ b/lively.modules/src/resource.js @@ -53,6 +53,7 @@ export async function fetchResource (proceed, load) { if (normalizedName.startsWith('esm://cache')) { normalizedName = '/esm_cache/' + ESMResource.normalize(normalizedName).join('/'); } if (stored && (jsFileHashMap?.[normalizedName] === Number.parseInt(stored.hash))) { load.metadata.instrument = false; // skip instrumentation + if (stored.sourceMap) load.metadata.sourceMap = JSON.parse(stored.sourceMap); return stored.source; } } diff --git a/lively.modules/src/system.js b/lively.modules/src/system.js index e795358bad..4cb11fe659 100644 --- a/lively.modules/src/system.js +++ b/lively.modules/src/system.js @@ -255,7 +255,7 @@ function prepareSystem (System, config) { fetch: function (load, proceed) { const s = this.moduleSources?.[load.name]; if (s) return s; - if (this.transpiler !== 'lively.transpiler') return proceed(load); + if (this.transpiler !== 'lively.transpiler.babel') return proceed(load); return fetchResource.call(this, proceed, load); }, translate: function (load, opts) { @@ -317,11 +317,11 @@ function prepareSystem (System, config) { if (!config.transpiler && System.transpiler === 'traceur') { const initialSystem = GLOBAL.System; - if (initialSystem.transpiler === 'lively.transpiler') { - System.set('lively.transpiler', initialSystem.get('lively.transpiler')); + if (initialSystem.transpiler === 'lively.transpiler.babel') { + System.set('lively.transpiler.babel', initialSystem.get('lively.transpiler.babel')); System._loader.transpilerPromise = initialSystem._loader.transpilerPromise; System.config({ - transpiler: 'lively.transpiler', + transpiler: 'lively.transpiler.babel', babelOptions: Object.assign(initialSystem.babelOptions || {}, config.babelOptions) }); } else { @@ -386,32 +386,54 @@ function preNormalize (System, name, parent) { // '{node: "events", "~node": "@empty"}' mapping but we need it const { packageRegistry } = System.get('@lively-env'); if (packageRegistry) { + let importMap, mappedObject, packageURL; const pkg = parent && packageRegistry.findPackageHavingURL(parent); if (pkg) { - const { map, url: packageURL } = pkg; - let mappedObject = (map && map[name]) || System.map[name]; - if (mappedObject) { - if (typeof mappedObject === 'object') { - mappedObject = normalize_doMapWithObject(mappedObject, pkg, System); - } - if (typeof mappedObject === 'string' && mappedObject !== '') { - name = mappedObject; - } - // relative to package - if (name.startsWith('.')) name = urlResolve(join(packageURL, name)); + let map, systemjs; + ({ map, url: packageURL, systemjs } = pkg); + importMap = !isNode && systemjs?.importMap; // only works in the browser + mappedObject = map?.[name] || System.map[name]; + } + + if (importMap) { + let remapped = importMap.imports?.[name]; + let scope, prefix; + if (scope = Object.entries(importMap.scopes) + .filter(([k, v]) => parent.startsWith(k)) + .sort((a, b) => a[0].length - b[0].length) + .map(([prefix, scope]) => scope) + .reduce((a, b) => ({ ...a, ...b }), false)) { + if (scope[name]) remapped = scope[name]; + } + if (remapped) { + name = remapped; + if (mappedObject) mappedObject = name; + packageRegistry.moduleUrlToPkg.set(name, pkg); } } - } - // experimental - if (packageRegistry) { + + if (mappedObject) { + if (typeof mappedObject === 'object') { + mappedObject = normalize_doMapWithObject(mappedObject, pkg, System); + } + if (typeof mappedObject === 'string' && mappedObject !== '') { + name = mappedObject; + } + // relative to package + if (name.startsWith('.')) name = urlResolve(join(packageURL, name)); + } + let resolved = packageRegistry.resolvePath(name, parent); if (resolved) { if (resolved.endsWith('/') && !name.endsWith('/')) resolved = resolved.slice(0, -1); if (!resolved.endsWith('/') && name.endsWith('/')) resolved = resolved + '/'; name = resolved; } + + if (pkg && importMap && !packageRegistry.moduleUrlToPkg.get(name)) { + packageRegistry.moduleUrlToPkg.set(name, pkg); + } } - // experimental System.debug && console.log(`>> [preNormalize] ${name}`); return name; @@ -449,18 +471,7 @@ function postNormalize (System, normalizeResult, isSync) { } } - // Fix issue with accidentally adding .js - const jsonPath = normalizeResult.match(jsonJsExtRe); - // if (!jsExtRe.test(normalizeResult) && - // !jsxExtRe.test(normalizeResult) && - // !jsonExtRe.test(normalizeResult) && - // !nodeModRe.test(normalizeResult) && - // !nodeExtRe.test(normalizeResult)) { - // // make sure this is not a package name - // normalizeResult += '.js'; - // } - System.debug && console.log(`>> [postNormalize] ${jsonPath ? jsonPath[1] : normalizeResult}`); - return jsonPath ? jsonPath[1] : normalizeResult; + return normalizeResult; } async function checkExistence (url, System) { @@ -476,7 +487,7 @@ async function checkExistence (url, System) { async function normalizeHook (proceed, name, parent, parentAddress) { const System = this; - if (System.transpiler !== 'lively.transpiler') return await proceed(name, parent, true); + if (System.transpiler !== 'lively.transpiler.babel') return await proceed(name, parent, true); if (parent && name === 'cjs') { return 'cjs'; } @@ -514,7 +525,7 @@ async function normalizeHook (proceed, name, parent, parentAddress) { const indexjs = stage3.replace('.js', '/index.js'); if (await checkExistence(indexjs, System) || !isNodePath) return indexjs; return stage3.replace('.js', '/index.node'); - } else if (!stage3.includes('jspm.dev') && stage3 !== '@empty') { + } else if (!stage3.startsWith('esm://') && !stage3.includes('jspm.dev') && stage3 !== '@empty') { if (await checkExistence(stage3 + '.js', System)) return stage3 + '.js'; if (await checkExistence(stage3 + '/index.js', System)) return stage3 + '/index.js'; } diff --git a/lively.modules/systemjs-init.js b/lively.modules/systemjs-init.js deleted file mode 100644 index 0ea382db9e..0000000000 --- a/lively.modules/systemjs-init.js +++ /dev/null @@ -1,239 +0,0 @@ -/* global System,Babel,global,require,__dirname,self */ -/* eslint-disable no-use-before-define */ -'format global'; -(function configure () { - if (typeof System === 'undefined') System = global.System; - System.useModuleTranslationCache = !urlQuery().noModuleCache; - - if (System.get('lively.transpiler') || - (System.map['plugin-babel'] && System.map['systemjs-plugin-babel'])) { - console.log('[lively.modules] System seems already to be configured'); - return; - } - - let features = featureTest(); - let transpiler = decideAboutTranspiler(features); - - if (transpiler === 'lively.transpiler') setupLivelyTranspiler(features); - else if (transpiler === 'plugin-babel') setupPluginBabelTranspiler(features); - else console.error('[lively.modules] could not find System transpiler for platform!'); - - if (typeof require !== 'undefined') { System._nodeRequire = eval('require'); } // hack to enable dynamic requires in bundles - if (typeof global !== 'undefined') { global.__webpack_require__ = global.__non_webpack_require__ = System._nodeRequire; } - // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- - - System.global = typeof global === 'undefined' ? window : global; - System.trace = true; // in order to harvest more metadata for lively.modules - if (System._nodeRequire) { - const Module = System._nodeRequire('module'); - // wrap _load() such that it attaches the __esModule flag to each imported native module - // this ensures the interoperability to 0.21 SystemJS - const origLoad = Module._load; - // this also overrides native requires, which is not what we want really - Module._load = (...args) => { - let exports = origLoad(...args); - const isCoreModule = !!System.loads['@node/' + args[0]]; - if (isCoreModule && !args[1].loaded && !exports.prototype) { - exports = Object.assign(Object.create(exports.prototype || {}), exports) - if (!exports.default) exports.default = exports; - exports.__esModule = true; - }; - return exports; - } - } - - function decideAboutTranspiler (features) { - return features.supportsAsyncAwait ? 'lively.transpiler' : 'plugin-babel'; - } - - function setupLivelyTranspiler (features) { - if (features.isBrowser) { - if (typeof Babel !== 'undefined') { - System.global.babel = Babel; - delete System.global.Babel; - } - if (!System.global.babel) { - console.error('[lively.modules] in browser environments babel is required to be loaded before lively.modules!'); - return; - } - } else { - System.global.babel = loadBabel_node(); - } - - console.log('[lively.modules] SystemJS configured with lively.transpiler & babel'); - - function Transpiler (System, moduleId, env) { - this.System = System; - this.moduleId = moduleId; - this.env = env; - } - Transpiler.prototype.transpileDoit = function transpileDoit (source, options) { - // wrap in async function so we can use await top-level - let System = this.System; - var source = '(async function(__rec) {\n' + source.replace(/(\/\/# sourceURL=.+)$|$/, '\n}).call(this);\n$1'); // eslint-disable-line no-var - let opts = System.babelOptions; - let needsBabel = (opts.plugins && opts.plugins.length) || (opts.presets && opts.presets.length); - return needsBabel - ? System.global.babel.transform(source, opts).code - : source; - }; - Transpiler.prototype.transpileModule = function transpileModule (source, options) { - let System = this.System; - let opts = Object.assign({}, System.babelOptions); - opts.plugins = opts.plugins ? opts.plugins.slice() : []; - opts.plugins.push(System._nodeRequire ? System._nodeRequire('@babel/plugin-proposal-dynamic-import') : 'proposal-dynamic-import'); - opts.plugins.push(System._nodeRequire ? System._nodeRequire('@babel/plugin-proposal-class-properties') : 'proposal-class-properties'); - opts.plugins.push(System._nodeRequire ? System._nodeRequire('@babel/plugin-transform-modules-systemjs') : 'transform-modules-systemjs'); - return System.global.babel.transform(source, opts).code; - }; - - function translate (load, traceOpts) { - return new Transpiler(this, load.name, {}).transpileModule(load.source, {}); - } - System.set('lively.transpiler', System.newModule({ default: Transpiler, translate })); - System._loader.transpilerPromise = Promise.resolve({ translate }); - System.translate = async (load) => await translate.bind(System)(load); - System.config({ - transpiler: 'lively.transpiler', - babelOptions: { - sourceMaps: false, - compact: 'auto', - comments: true, - presets: features.supportsAsyncAwait ? [] : ['es2015'] - } - }); - } - - function setupPluginBabelTranspiler (features) { - let isBrowser = !!System.get('@system-env').browser; - let pluginBabelPath = isBrowser ? findSystemJSPluginBabel_browser() : findSystemJSPluginBabel_node(); - let babel = System.global.babel; - - if (!pluginBabelPath && !babel) { - console.error('[lively.modules] Could not find path to systemjs-plugin-babel nor a babel global! This will likely break lively.modules!'); - return; - } - - if (!pluginBabelPath) { - console.warn("[lively.modules] Could not find path to systemjs-plugin-babel but babel! Will fallback but there might be features in lively.modules that won't work!"); - System.config({ transpiler: 'babel' }); - } else { - console.log('[lively.modules] SystemJS configured with systemjs-plugin-babel transpiler from ' + pluginBabelPath); - System.config({ - map: { - 'plugin-babel': pluginBabelPath + '/plugin-babel.js', - 'systemjs-babel-build': pluginBabelPath + (isBrowser ? '/systemjs-babel-browser.js' : '/systemjs-babel-node.js') - }, - transpiler: 'plugin-babel', - babelOptions: Object.assign({ - sourceMaps: 'inline', - stage3: true, - es2015: true, - modularRuntime: true - }, System.babelOptions) - }); - } - } - - function featureTest () { - let isBrowser = System.get('@system-env').browser || typeof self !== 'undefined'; - - // "feature test": we assume if the browser supports async/await it will also - // support other es6/7/8 features we care about. In this case only use the - // system-register transform. Otherwise use full transpilation. - let supportsAsyncAwait = false; - try { eval('async function foo() {}'); supportsAsyncAwait = true; } catch (e) {} - - return { supportsAsyncAwait, isBrowser }; - } - - function loadBabel_node () { - if (global.Babel && !global.babel) global.babel = global.Babel; - if (global.babel) return global.babel; - let parent; - try { parent = require.cache[require.resolve('lively.modules')]; } catch (err) {} - try { parent = require.cache[require.resolve(__dirname + '/../')]; } catch (err) {} - if (!parent) throw new Error('Cannot find batch to babel-standalone module'); - let babelPath = require('module').Module._resolveFilename('babel-standalone', parent); - global.window = global; - global.navigator = {}; - let babel = require(babelPath); - delete global.navigator; - delete global.window; - return babel; - } - - function urlQuery () { - if (typeof document === 'undefined' || !document.location) return {}; - return (document.location.search || '').replace(/^\?/, '').split('&') - .reduce(function (query, ea) { - let split = ea.split('='); let key = split[0]; let value = split[1]; - if (value === 'true' || value === 'false') value = eval(value); - else if (!isNaN(Number(value))) value = Number(value); - query[key] = value; - return query; - }, {}); - } - - // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- - - function findSystemJSPluginBabel_browser () { - // walks the script tags - let scripts = [].slice.call(document.getElementsByTagName('script')); - let pluginBabelPath; - - for (let i = scripts.length - 1; i >= 0; i--) { - let src = scripts[i].src; - // is lively.modules loaded? Use it's node_modules folder - let index1 = src.indexOf('lively.modules/'); - if (index1 > -1) { - pluginBabelPath = src.slice(0, index1) + 'lively.next-node_modules/systemjs-plugin-babel'; - break; - } - - // is systemjs loaded? Assume that systemjs-plugin-babel sits in the same folder... - let index2 = src.indexOf('systemjs/dist/system'); - if (index2 > -1) { - pluginBabelPath = src.slice(0, index2) + 'systemjs-plugin-babel'; - break; - } - - // for LivelyKernel environments - let index3 = src.indexOf('core/lively/bootstrap.js'); - if (index3 > -1) { - pluginBabelPath = src.slice(0, index3) + 'node_modules/lively.modules/node_modules/systemjs-plugin-babel'; - break; - } - - let match = src.match(/(.*)generated\/[^\/]+\/combinedModules.js/); - if (match) { - pluginBabelPath = match[1] + 'node_modules/lively.modules/node_modules/systemjs-plugin-babel'; - break; - } - } - - return pluginBabelPath; - } - - function findSystemJSPluginBabel_node () { - if (global.systemjsPluginBabel) return global.systemjsPluginBabel; - let attempts = [attempt1, attempt2, attempt3]; - for (let i = 0; i < attempts.length; i++) { try { return attempts[i](); } catch (err) {} } - return null; - - function attempt1 () { - let parent = require.cache[require.resolve('lively.modules')]; - let pluginBabelPath = require('module').Module._resolveFilename('systemjs-plugin-babel', parent); - if (pluginBabelPath) return require('path').dirname(pluginBabelPath); - } - - function attempt2 () { - let pluginBabelPath = require.resolve('systemjs-plugin-babel'); - if (pluginBabelPath) return require('path').dirname(pluginBabelPath); - } - function attempt3 () { - let pluginBabelPath = require.resolve(require('path').join(__dirname, 'systemjs-babel-node.js')); - if (pluginBabelPath) return require('path').dirname(pluginBabelPath); - } - } -})(); diff --git a/lively.modules/tests/binding-test.js b/lively.modules/tests/binding-test.js index 1a6a763336..df99385b5a 100644 --- a/lively.modules/tests/binding-test.js +++ b/lively.modules/tests/binding-test.js @@ -1,13 +1,14 @@ /* global System, beforeEach, afterEach, describe, it */ import { expect } from 'mocha-es6'; -import { removeDir, createFiles } from './helpers.js'; +import { createFiles, resource } from 'lively.resources'; +import { prepareSystem } from './helpers.js'; -import { getSystem } from '../src/system.js'; +import { removeSystem } from '../src/system.js'; import module from '../src/module.js'; import { registerPackage } from '../src/packages/package.js'; -let dir = System.decanonicalize('lively.modules/tests/'); +let dir = 'local://lively.modules-bindings-test/'; let testProjectDir = dir + 'test-dir-imports-exports/'; let testProjectSpec = { 'package.json': '{"name": "imports-exports-test-project", "main": "file2.js"}', @@ -51,12 +52,12 @@ let testProjectSpec = { describe('binding', () => { let S, modules; beforeEach(async () => { - S = getSystem('import-export-test'); + S = prepareSystem('import-export-test', testProjectDir); modules = Object.keys(testProjectSpec) .map(k => module(S, testProjectDir + k)); await createFiles(testProjectDir, testProjectSpec); }); - afterEach(() => removeDir(testProjectDir)); + afterEach(async () => { removeSystem('import-export-test'); await resource(testProjectDir).remove(); }); it('within module', async () => { const decls = await modules[1].bindingPathForRefAt(19); diff --git a/lively.modules/tests/changes-test.js b/lively.modules/tests/changes-test.js index 2ede0c72d2..916947eb91 100644 --- a/lively.modules/tests/changes-test.js +++ b/lively.modules/tests/changes-test.js @@ -2,8 +2,9 @@ import { expect } from 'mocha-es6'; import { createFiles, resource } from 'lively.resources'; +import { prepareSystem } from './helpers.js'; -import { getSystem, removeSystem } from '../src/system.js'; +import { removeSystem } from '../src/system.js'; import module from '../src/module.js'; const dir = 'local://lively.modules-changes-test/'; @@ -31,11 +32,7 @@ describe('code changes of esm format module', function () { this.timeout(5000); beforeEach(async () => { - S = getSystem('test', { baseURL: testProjectDir }); - S.set('lively.transpiler', System.get('lively.transpiler')); - S.config({ transpiler: 'lively.transpiler' }); - S.translate = async (load) => await System.translate.bind(S)(load); - S.useModuleTranslationCache = false; + S = prepareSystem('test', testProjectDir); module1 = module(S, file1m); module2 = module(S, file2m); module4 = module(S, file4m); @@ -45,7 +42,7 @@ describe('code changes of esm format module', function () { afterEach(async () => { removeSystem('test'); await resource(testProjectDir).remove(); }); it('modifies module and its exports', async () => { - const m1 = await S.import(file1m); + let m1 = await S.import(file1m); const m2 = await S.import(file2m); expect(module2.env().recorder.internal).to.equal(1, 'internal state of module2 before change'); @@ -91,10 +88,10 @@ describe('code changes of esm format module', function () { it('affects dependent modules', async () => { let m1 = await S.import(file1m); - expect(module1.env()).deep.property('recorder.y').equal(1, 'internal state before change'); + expect(module1.env()).nested.property('recorder.y').equal(1, 'internal state before change'); expect(m1.x).to.equal(3, 'before change'); await changeModule2Source(); - expect(module1.env()).deep.property('recorder.y').to.equal(2, 'internal state after change'); + expect(module1.env()).nested.property('recorder.y').to.equal(2, 'internal state after change'); // We expect to still have the same internal computed state b/c module 1 // won't get re-run! expect(m1.x).to.equal(3, 'state after change'); @@ -174,10 +171,7 @@ describe('code changes of global format module', () => { let S, module1; beforeEach(async () => { - S = getSystem('test', { baseURL: dir }); - S.set('lively.transpiler', System.get('lively.transpiler')); - S.config({ transpiler: 'lively.transpiler' }); - S.translate = async (load) => await System.translate.bind(S)(load); + S = prepareSystem('test', dir); module1 = module(S, file1m); await createFiles(testProjectDir, testProjectSpec); await S.import(testProjectDir + 'file1.js'); @@ -222,10 +216,7 @@ describe('persistent definitions', () => { let S, module1; beforeEach(async () => { - S = getSystem('test', { baseURL: testProjectDir }); - S.set('lively.transpiler', System.get('lively.transpiler')); - S.config({ transpiler: 'lively.transpiler' }); - S.translate = async (load) => await System.translate.bind(S)(load); + S = prepareSystem('test', testProjectDir); module1 = module(S, file1m); await createFiles(testProjectDir, testProjectSpec); }); @@ -259,10 +250,7 @@ describe('persistent definitions', () => { describe('notifications of toplevel changes', () => { let S, module1, module2, module4; beforeEach(async () => { - S = getSystem('test', { baseURL: testProjectDir }); - S.set('lively.transpiler', System.get('lively.transpiler')); - S.config({ transpiler: 'lively.transpiler' }); - S.translate = async (load) => await System.translate.bind(S)(load); + S = prepareSystem('test', testProjectDir); module1 = module(S, file1m); module2 = module(S, file2m); module4 = module(S, file4m); diff --git a/lively.modules/tests/eval-test.js b/lively.modules/tests/eval-test.js index 66d5e8a1ef..db6c3102c5 100644 --- a/lively.modules/tests/eval-test.js +++ b/lively.modules/tests/eval-test.js @@ -1,10 +1,10 @@ /* global System, beforeEach, afterEach, describe, it */ -import { removeDir, createFiles } from './helpers.js'; +import { removeDir, prepareSystem, createFiles } from './helpers.js'; import { expect } from 'mocha-es6'; import { promise } from 'lively.lang'; -import { getSystem, removeSystem } from 'lively.modules/src/system.js'; +import { removeSystem } from 'lively.modules/src/system.js'; import module from 'lively.modules/src/module.js'; import { runEval } from 'lively.vm'; @@ -27,11 +27,7 @@ describe('lively.modules aware eval', function () { let S, module1, module2, module3, module4; beforeEach(async () => { - S = getSystem('test', { baseURL: testProjectDir }); - S.set('lively.transpiler', System.get('lively.transpiler')); - S.config({ transpiler: 'lively.transpiler' }); - S.babelOptions = System.babelOptions; - S.translate = async (load) => await System.translate.bind(S)(load); + S = prepareSystem('test', testProjectDir); module1 = module(S, file1m); module2 = module(S, file2m); module3 = module(S, file3m); diff --git a/lively.modules/tests/export-lookup-test.js b/lively.modules/tests/export-lookup-test.js index 822bfcdfc6..631dad9c66 100644 --- a/lively.modules/tests/export-lookup-test.js +++ b/lively.modules/tests/export-lookup-test.js @@ -2,10 +2,11 @@ import { expect } from 'mocha-es6'; import { createFiles, resource } from 'lively.resources'; -import { getSystem, removeSystem } from '../src/system.js'; +import { removeSystem } from '../src/system.js'; import module from '../src/module.js'; import ExportLookup from '../src/export-lookup.js'; import { importPackage } from '../src/packages/package.js'; +import { prepareSystem } from './helpers.js'; let dir = 'local://lively.modules.export-lookup-test/'; let testProjectDir = dir + 'project/'; @@ -38,11 +39,8 @@ let testProject2Spec = { let S; describe('export lookup', () => { beforeEach(async () => { - S = getSystem('test', { baseURL: testProjectDir }); - S.set('lively.transpiler', System.get('lively.transpiler')); - S.config({ transpiler: 'lively.transpiler' }); - S.babelOptions = System.babelOptions; - S.translate = async (load) => await System.translate.bind(S)(load); + S = prepareSystem('test', testProjectDir); + S.useModuleTranslationCache = true; await createFiles(testProjectDir, testProjectSpec); await importPackage(S, testProjectDir); }); diff --git a/lively.modules/tests/helpers.js b/lively.modules/tests/helpers.js index 1b86f27db5..70c434acc1 100644 --- a/lively.modules/tests/helpers.js +++ b/lively.modules/tests/helpers.js @@ -12,6 +12,7 @@ import { writeFileSync as node_writeFileSync, mkdirSync as node_mkdirSync } from 'fs'; +import { getSystem } from '../index.js'; import { obj } from 'lively.lang'; @@ -127,10 +128,21 @@ function runInIframe (id, func) { .catch(err => { iframe && iframe.parentNode.removeChild(iframe); throw err; }); } +function prepareSystem (name, testProjectDir) { + const S = getSystem(name, { baseURL: testProjectDir }); + S.set('lively.transpiler.babel', System.get('lively.transpiler.babel')); + S.config({ transpiler: 'lively.transpiler.babel' }); + S.translate = async (load, opts) => await System.translate.bind(S)(load, opts); + S.useModuleTranslationCache = false; + S.babelOptions = System.babelOptions; + return S; +} + export { createFiles, removeDir, modifyFile, modifyJSON, readFile, writeFile, removeFile, noTrailingSlash, inspect, - runInIframe + runInIframe, + prepareSystem }; diff --git a/lively.modules/tests/instrumentation-test.js b/lively.modules/tests/instrumentation-test.js index 0952b314be..e04be17a28 100644 --- a/lively.modules/tests/instrumentation-test.js +++ b/lively.modules/tests/instrumentation-test.js @@ -1,8 +1,9 @@ /* global beforeEach, afterEach, describe, it */ import { expect } from 'mocha-es6'; +import { prepareSystem } from './helpers.js'; -import { getSystem, removeSystem } from '../src/system.js'; +import { removeSystem } from '../src/system.js'; import module from '../src/module.js'; import { registerPackage } from '../src/packages/package.js'; import { runEval } from 'lively.vm'; @@ -27,11 +28,7 @@ let testProjectSpec = { let S, module1, module3, module4, module5; async function setup () { - S = getSystem('test', { baseURL: dir }); - S.set('lively.transpiler', System.get('lively.transpiler')); - S.config({ transpiler: 'lively.transpiler' }); - S.babelOptions = System.babelOptions; - S.translate = async (load) => await System.translate.bind(S)(load); + S = prepareSystem('test', dir); module1 = module(S, testProjectDir + 'file1.js'); module3 = module(S, testProjectDir + 'file3.js'); module4 = module(S, testProjectDir + 'file4.js'); @@ -52,8 +49,8 @@ describe('instrumentation', () => { afterEach(teardown); it('gets access to internal module state', async () => { - expect(module1).to.have.deep.property('recorder.y', 1); - expect(module1).to.have.deep.property('recorder.x', 3); + expect(module1).to.have.nested.property('recorder.y', 1); + expect(module1).to.have.nested.property('recorder.x', 3); }); it('modules can (re)define captures', async () => { @@ -103,7 +100,7 @@ describe('instrumentation', () => { it('can access local state', () => S.import(`${testProjectDir}file3.js`) .then(() => { - expect(module3).to.have.deep.property('recorder.zzz', 4); + expect(module3).to.have.nested.property('recorder.zzz', 4); expect(S.get(testProjectDir + 'file3.js').default).to.have.property('z', 2); })); }); @@ -114,7 +111,7 @@ describe('instrumentation', () => { it('class export is recorded', async () => { let exports = await S.import(`${testProjectDir}file4.js`); expect(exports.default).is.a('function'); - expect(module4).to.have.deep.property('recorder.Foo'); + expect(module4).to.have.nested.property('recorder.Foo'); expect(exports.default).to.equal(module4.recorder.Foo); }); diff --git a/lively.modules/tests/module-dependency-test.js b/lively.modules/tests/module-dependency-test.js index 435af0ea45..37ba1b2b2c 100644 --- a/lively.modules/tests/module-dependency-test.js +++ b/lively.modules/tests/module-dependency-test.js @@ -1,9 +1,9 @@ /* global System, beforeEach, afterEach, describe, it */ import { expect } from 'mocha-es6'; -import { removeDir, createFiles } from './helpers.js'; +import { removeDir, prepareSystem, createFiles } from './helpers.js'; -import { getSystem, removeSystem } from '../src/system.js'; +import { removeSystem } from '../src/system.js'; import module from '../src/module.js'; let dir = System.decanonicalize('lively.modules/tests/'); @@ -22,11 +22,7 @@ let S, module1, module2, module3; describe('dependencies', () => { beforeEach(async () => { - S = getSystem('test', { baseURL: testProjectDir }); - S.set('lively.transpiler', System.get('lively.transpiler')); - S.config({ transpiler: 'lively.transpiler' }); - S.babelOptions = System.babelOptions; - S.translate = async (load) => await System.translate.bind(S)(load); + S = prepareSystem('test', testProjectDir); module1 = module(S, file1m); module2 = module(S, file2m); module3 = module(S, file3m); diff --git a/lively.modules/tests/module-test.js b/lively.modules/tests/module-test.js index 401ddf2b92..bfae4f1790 100644 --- a/lively.modules/tests/module-test.js +++ b/lively.modules/tests/module-test.js @@ -2,9 +2,10 @@ import { expect } from 'mocha-es6'; import { promise } from 'lively.lang'; +import { prepareSystem } from './helpers.js'; import module, { isModuleLoaded, doesModuleExist } from '../src/module.js'; -import { getSystem, removeSystem, loadedModules, whenLoaded } from '../src/system.js'; +import { removeSystem, loadedModules, whenLoaded } from '../src/system.js'; import { registerPackage, importPackage } from '../src/packages/package.js'; import { createFiles, resource } from 'lively.resources'; @@ -15,11 +16,7 @@ let S; describe('module loading', () => { beforeEach(async () => { - S = getSystem('test', { baseURL: dir }); - S.set('lively.transpiler', System.get('lively.transpiler')); - S.config({ transpiler: 'lively.transpiler' }); - S.babelOptions = System.babelOptions; - S.translate = async (load) => await System.translate.bind(S)(load); + S = prepareSystem('test', dir); await createFiles(testDir, { 'file1.js': "import { y } from './file2.js'; export var x = y + 1;", 'file2.js': "import { z } from './file3.js'; export var y = 1 + z;", diff --git a/lively.modules/tests/notify-test.js b/lively.modules/tests/notify-test.js index 0eb4057c0f..808023d6b7 100644 --- a/lively.modules/tests/notify-test.js +++ b/lively.modules/tests/notify-test.js @@ -3,8 +3,8 @@ import { expect } from 'mocha-es6'; import { subscribe, unsubscribe } from 'lively.notifications'; -import { removeDir, createFiles } from './helpers.js'; -import { getSystem, removeSystem } from '../src/system.js'; +import { removeDir, prepareSystem, createFiles } from './helpers.js'; +import { removeSystem } from '../src/system.js'; import module from '../src/module.js'; import { ensurePackage } from '../src/packages/package.js'; import { promise } from 'lively.lang'; @@ -34,11 +34,7 @@ describe('notify', () => { function onPackageRemoved (n) { packageremoved.push(n); } beforeEach(() => { - system = getSystem('test', { baseURL: dir }); - system.set('lively.transpiler', System.get('lively.transpiler')); - system.config({ transpiler: 'lively.transpiler' }); - system.babelOptions = System.babelOptions; - system.translate = async (load) => await System.translate.bind(system)(load); + system = prepareSystem('test', dir); modulechanged = []; moduleloaded = []; moduleunloaded = []; diff --git a/lively.modules/tests/package-test.js b/lively.modules/tests/package-test.js index f0ce9a6030..ede611a1f4 100644 --- a/lively.modules/tests/package-test.js +++ b/lively.modules/tests/package-test.js @@ -1,12 +1,12 @@ /* global System, beforeEach, afterEach, describe, it */ import { expect } from 'mocha-es6'; -import { modifyJSON, noTrailingSlash } from './helpers.js'; +import { modifyJSON, prepareSystem, noTrailingSlash } from './helpers.js'; import { arr } from 'lively.lang'; import { resource, createFiles } from 'lively.resources'; import module from '../src/module.js'; -import { getSystem, removeSystem } from '../src/system.js'; +import { removeSystem } from '../src/system.js'; import { getPackage, ensurePackage, applyConfig, getPackageSpecs } from '../src/packages/package.js'; import { PackageRegistry } from '../src/packages/package-registry.js'; @@ -41,11 +41,7 @@ describe('package loading', function () { let S; beforeEach(async () => { - S = getSystem('test', { baseURL: testDir }); - S.set('lively.transpiler', System.get('lively.transpiler')); - S.config({ transpiler: 'lively.transpiler' }); - S.babelOptions = System.babelOptions; - S.translate = async (load) => await System.translate.bind(S)(load); + S = prepareSystem('test', testDir); await createFiles(testDir, testResources); }); @@ -295,7 +291,7 @@ describe('package loading', function () { expect(await resource(newURL + '/entry-a.js').exists()).equals(true, 'entry-a.js does not exist'); expect(await resource(newURL + '/package.json').exists()).equals(true, 'package.json does not exist'); - expect(S.get(newURL + '/entry-a.js')).deep.equals({ version: 'a', x: 2 }); + expect(S.get(newURL + '/entry-a.js')).containSubset({ version: 'a', x: 2 }); expect(S.get(newURL + '/package.json').default).containSubset({ main: 'entry-a.js', name: 'some-project' }); }); @@ -330,7 +326,7 @@ describe('package loading', function () { expect(await resource(newURL + '/package.json').exists()).equals(true, 'package.json does not exist'); expect(JSON.parse(await resource(newURL + '/package.json').read())).containSubset({ main: 'entry-a.js', name: 'some-project-copied' }); - expect(S.get(newURL + '/entry-a.js')).deep.equals({ version: 'a', x: 2 }); + expect(S.get(newURL + '/entry-a.js')).containSubset({ version: 'a', x: 2 }); expect(S.get(newURL + '/package.json').default).containSubset({ main: 'entry-a.js', name: 'some-project-copied' }); }); }); @@ -340,11 +336,7 @@ describe('package configuration test', () => { let S; beforeEach(async () => { - S = getSystem('test', { baseURL: testDir }); - S.set('lively.transpiler', System.get('lively.transpiler')); - S.config({ transpiler: 'lively.transpiler' }); - S.babelOptions = System.babelOptions; - S.translate = async (load) => await System.translate.bind(S)(load); + S = prepareSystem('test', testDir); await createFiles(testDir, testResources); }); @@ -415,11 +407,7 @@ describe('mutual dependent packages', () => { let S; beforeEach(async () => { - S = getSystem('test', { baseURL: testDir }); - S.set('lively.transpiler', System.get('lively.transpiler')); - S.config({ transpiler: 'lively.transpiler' }); - S.babelOptions = System.babelOptions; - S.translate = async (load) => await System.translate.bind(S)(load); + S = prepareSystem('test', testDir); await createFiles(testDir, testResources); }); @@ -466,11 +454,7 @@ describe('package registry', () => { } } }); - S = getSystem('test', { baseURL: testDir }); - S.set('lively.transpiler', System.get('lively.transpiler')); - S.config({ transpiler: 'lively.transpiler' }); - S.babelOptions = System.babelOptions; - S.translate = async (load) => await System.translate.bind(S)(load); + S = prepareSystem('test', testDir); registry = PackageRegistry.ofSystem(S); registry.packageBaseDirs = [resource(testDir).join('packages/')]; await registry.update(); diff --git a/lively.modules/tests/search-test.js b/lively.modules/tests/search-test.js index a5a854e494..b8365d5709 100644 --- a/lively.modules/tests/search-test.js +++ b/lively.modules/tests/search-test.js @@ -2,9 +2,9 @@ import { expect } from 'mocha-es6'; -import { removeDir, createFiles } from './helpers.js'; +import { removeDir, prepareSystem, createFiles } from './helpers.js'; -import { getSystem, searchLoadedModules } from '../src/system.js'; +import { searchLoadedModules } from '../src/system.js'; import mod from '../src/module.js'; import { importPackage, removePackage, getPackage } from '../src/packages/package.js'; @@ -23,11 +23,7 @@ describe('search', () => { before(async () => { await createFiles(testProjectDir, testProjectSpec); - S = getSystem('test', { baseURL: dir }); - S.set('lively.transpiler', System.get('lively.transpiler')); - S.config({ transpiler: 'lively.transpiler' }); - S.babelOptions = System.babelOptions; - S.translate = async (load) => await System.translate.bind(S)(load); + S = prepareSystem('test', dir); module1 = mod(S, file1m); module2 = mod(S, file2m); }); diff --git a/lively.modules/tests/virtual-modules-test.js b/lively.modules/tests/virtual-modules-test.js index e7766261e0..a063b8345f 100644 --- a/lively.modules/tests/virtual-modules-test.js +++ b/lively.modules/tests/virtual-modules-test.js @@ -1,9 +1,9 @@ /* global System, beforeEach, afterEach, describe, it */ -import { removeDir, createFiles } from './helpers.js'; +import { removeDir, prepareSystem, createFiles } from './helpers.js'; import { expect } from 'mocha-es6'; -import { getSystem, removeSystem } from 'lively.modules/src/system.js'; +import { removeSystem } from 'lively.modules/src/system.js'; import module from 'lively.modules/src/module.js'; import { runEval } from 'lively.vm'; @@ -18,11 +18,7 @@ const file1m = testProjectDir + 'file1.js'; describe('lively.modules aware eval', () => { let S, module1; beforeEach(async () => { - S = getSystem('test', { baseURL: testProjectDir }); - S.set('lively.transpiler', System.get('lively.transpiler')); - S.config({ transpiler: 'lively.transpiler' }); - S.babelOptions = System.babelOptions; - S.translate = async (load) => await System.translate.bind(S)(load); + S = prepareSystem('test', testProjectDir); await createFiles(testProjectDir, testProjectSpec); module1 = module(S, file1m); }); @@ -40,10 +36,10 @@ describe('lively.modules aware eval', () => { await module1.load(); let virtualModule = module(S, 'local://foo/mod1'); await runEval(`import { x } from '${module1.id}';`, { targetModule: virtualModule.id, System: S }); - expect(virtualModule).to.have.deep.property('recorder.x', 23); + expect(virtualModule).to.have.nested.property('recorder.x', 23); await runEval(`import { x } from '${module1.id}';`, { targetModule: virtualModule.id, System: S }); await module1.changeSource('export var x = 24;'); - expect(virtualModule).to.have.deep.property('recorder.x', 24); + expect(virtualModule).to.have.nested.property('recorder.x', 24); }); it('exports and imports are updated on eval', async () => { @@ -51,10 +47,10 @@ describe('lively.modules aware eval', () => { let m2 = S.get('@lively-env').moduleEnv('local://foo/mod2'); await runEval('export var z = 23;', { targetModule: m1.id, System: S }); await runEval(`import { z } from '${m1.id}';`, { targetModule: m2.id, System: S }); - expect(m2).to.have.deep.property('recorder.z', 23); + expect(m2).to.have.nested.property('recorder.z', 23); expect(m1.record().importers).to.containSubset([{ name: m2.id }]); expect(m2.record().dependencies).to.containSubset([{ name: m1.id }]); await runEval('export var z = 24;', { targetModule: m1.id, System: S }); - expect(m2).to.have.deep.property('recorder.z', 24); + expect(m2).to.have.nested.property('recorder.z', 24); }); }); diff --git a/lively.morphic/tests/changes-test.js b/lively.morphic/tests/changes-test.js index 8412c39436..8cb67fd17a 100644 --- a/lively.morphic/tests/changes-test.js +++ b/lively.morphic/tests/changes-test.js @@ -33,8 +33,8 @@ describe('changes', function () { m2.fill = Color.yellow; expect(m1Changes).equals([]); - expect(m1SubmorphChanges).deep.property('[0].change').containSubset({ prop: 'fill', value: Color.yellow }); - expect(m1SubmorphChanges).deep.property('[0].morph', m2); + expect(m1SubmorphChanges).nested.property('[0].change').containSubset({ prop: 'fill', value: Color.yellow }); + expect(m1SubmorphChanges).nested.property('[0].morph', m2); expect(m2Changes).containSubset([{ prop: 'fill', value: Color.yellow }]); expect(m2SubmorphChanges).equals([]); }); @@ -164,7 +164,7 @@ describe('changes', function () { }); }); }); - + describe('animations', () => { it('enques a new animation when setting prop animated', () => { let m = morph({ extent: pt(10, 20), fill: Color.red }); @@ -172,7 +172,7 @@ describe('changes', function () { q.registerAnimation({ fill: Color.green, extent: pt(50, 50), easing: 'easInOut', onFinish: () => m.remove() }); expect(q.animations[0].animatedProps).deep.equals({ fill: Color.green, extent: pt(50, 50) }); }); - + it('does not enqueue the same prop animation more than once', () => { let m = morph({ extent: pt(10, 20), fill: Color.red }); let q = m._animationQueue; @@ -183,7 +183,7 @@ describe('changes', function () { expect(q.animations.length).equals(1); expect(new PropertyAnimation(null, m, a1).equals(new PropertyAnimation(null, m, a2))).to.be.true; }); - + it('does not enqueue animations that have no effect', () => { let m = morph({ extent: pt(10, 20), fill: Color.red }); let q = m._animationQueue; diff --git a/lively.morphic/tests/components-test.cp.js b/lively.morphic/tests/components-test.cp.js index 5317ae161a..094a9cfcbd 100644 --- a/lively.morphic/tests/components-test.cp.js +++ b/lively.morphic/tests/components-test.cp.js @@ -250,6 +250,10 @@ const c6 = ComponentDescriptor.for(() => component(c5, { moduleId }); +function structCompare (a, b, message) { + expect(JSON.parse(JSON.stringify(a))).to.eql(JSON.parse(JSON.stringify(b)), message); +} + describe('spec based components', () => { afterEach(() => { detach(e2); @@ -257,7 +261,7 @@ describe('spec based components', () => { it('specs are always fully expanded', () => { let alicePolicy = c2.stylePolicy.getSubSpecFor('alice'); - expect(d3.stylePolicy.spec).to.eql({ + structCompare(d3.stylePolicy.spec, { name: 'd3', fill: Color.cyan, defaultViewModel: TestViewModel, @@ -272,7 +276,7 @@ describe('spec based components', () => { const fooPolicy = c3.stylePolicy.getSubSpecFor('foo'); alicePolicy = fooPolicy.getSubSpecFor('alice'); - expect(c4.stylePolicy.spec).to.eql({ + structCompare(c4.stylePolicy.spec, { name: 'c4', submorphs: [ new PolicyApplicator({ @@ -336,7 +340,7 @@ describe('spec based components', () => { ] })); - const expectedBuildSpec = { + const expectedBuildSpec = JSON.parse(JSON.stringify({ name: 'e2', master: internalSpec, submorphs: [ @@ -380,9 +384,9 @@ describe('spec based components', () => { }, { name: 'bar', __wasAddedToDerived__: true } ] - }; - expect(internalSpec.asBuildSpec()).to.eql(expectedBuildSpec, 'equals generated'); - expect(e2.stylePolicy.asBuildSpec()).to.eql(expectedBuildSpec, 'equals defined'); + })); + expect(JSON.parse(JSON.stringify(internalSpec.asBuildSpec()))).to.eql(JSON.parse(JSON.stringify(expectedBuildSpec)), 'equals generated'); + expect(JSON.parse(JSON.stringify(e2.stylePolicy.asBuildSpec()))).to.eql(expectedBuildSpec, 'equals defined'); const pa = new PolicyApplicator({}, c3); const bs = pa.asBuildSpec(); @@ -433,7 +437,7 @@ describe('spec based components', () => { submorphs: [{ name: 'bob', fill: Color.green }] }, e1); p2.__wasAddedToDerived__ = true; - expect(e2.stylePolicy.synthesizeSubSpec('foo')).to.eql(p2); + expect(JSON.parse(JSON.stringify(e2.stylePolicy.synthesizeSubSpec('foo')))).to.eql(JSON.parse(JSON.stringify(p2))); expect(sanitizeSpec(e3.stylePolicy.synthesizeSubSpec('alice'))).to.eql({ ...sanitizeSpec(getDefaultValuesFor('text')), fill: Color.black, @@ -820,7 +824,7 @@ describe('components', () => { }); expect(part(T1).get('bob').master.parent).to.eql(T1.stylePolicy.getSubSpecFor('bob')); - expect(part(T1).get('bob').master.parent.parent).not.to.be.defined; + expect(part(T1).get('bob').master.parent.parent).to.be.undefined; }); it('includes added morphs into inline policies', () => { diff --git a/lively.morphic/tests/input-event-test.js b/lively.morphic/tests/input-event-test.js index de63fc9d4e..8ecf379ff8 100644 --- a/lively.morphic/tests/input-event-test.js +++ b/lively.morphic/tests/input-event-test.js @@ -363,7 +363,7 @@ describe('key events', () => { await env.eventDispatcher.simulateDOMEvents({ type: 'keydown', key: 'x' }); await env.eventDispatcher.simulateDOMEvents({ type: 'keydown', key: 'y' }); expect(log).equals('!'); - expect(env).deep.property('eventDispatcher.eventState.keyInputState') + expect(env).nested.property('eventDispatcher.eventState.keyInputState') .deep.equals({ count: undefined, keyChain: '' }); }); @@ -377,7 +377,7 @@ describe('key events', () => { await env.eventDispatcher.simulateDOMEvents({ type: 'keydown', ctrlKey: true, key: 'x' }); await env.eventDispatcher.simulateDOMEvents({ type: 'keydown', ctrlKey: true, key: 'x' }); expect(log).equals('2'); - expect(env).deep.property('eventDispatcher.eventState.keyInputState') + expect(env).nested.property('eventDispatcher.eventState.keyInputState') .deep.equals({ count: undefined, keyChain: '' }); }); @@ -405,7 +405,7 @@ describe('key events', () => { !e.propagationStopped && await env.eventDispatcher.simulateDOMEvents({ type: 'input', key: 'z', isPrimary: true }); expect(log).equals('!'); expect(submorph5.textString).equals('ztext'); - expect(env).deep.property('eventDispatcher.eventState.keyInputState') + expect(env).nested.property('eventDispatcher.eventState.keyInputState') .deep.equals({ count: undefined, keyChain: '' }); }); }); diff --git a/lively.morphic/tests/rendering-tests.js b/lively.morphic/tests/rendering-tests.js index e387b233d6..423b7d06d1 100644 --- a/lively.morphic/tests/rendering-tests.js +++ b/lively.morphic/tests/rendering-tests.js @@ -55,7 +55,7 @@ describe('rendering', function () { submorph1.rotateBy(num.toRadians(45)); submorph1.renderOnGPU = true; env.forceUpdate(); - expect(env.renderer.getNodeForMorph(submorph1)).deep.property('style.transform') + expect(env.renderer.getNodeForMorph(submorph1)).nested.property('style.transform') .match(/translate.*10px/) .match(/rotate\(0\.78\d*rad\)/) .match(/scale\(1,\s*1\)/); @@ -65,7 +65,7 @@ describe('rendering', function () { submorph1.origin = pt(20, 10); env.forceUpdate(); expect(env.renderer.getNodeForMorph(submorph1)) - .deep.property('style.transformOrigin').match(/20px 10px/); + .nested.property('style.transformOrigin').match(/20px 10px/); }); }); diff --git a/lively.morphic/tests/text/rendering-test.js b/lively.morphic/tests/text/rendering-test.js index e82791d32b..5acdcb4ba8 100644 --- a/lively.morphic/tests/text/rendering-test.js +++ b/lively.morphic/tests/text/rendering-test.js @@ -1,4 +1,4 @@ -/* global it, describe, beforeEach, afterEach */ +/* global it, describe, beforeEach, afterEach, CSS */ import { expect } from 'mocha-es6'; import { Text } from '../../text/morph.js'; import { Rectangle, Color, pt } from 'lively.graphics'; @@ -11,7 +11,7 @@ const defaultStyle = { fontWeight: 'normal', fontColor: Color.black, fontStyle: 'normal', - textDecoration: 'none solid color(display-p3 0 0 0)' + textDecoration: `none solid ${CSS.supports('color', 'color(display-p3 0 0 0)') ? 'color(display-p3 0 0 0)' : 'rgb(0,0,0)'}` }; let padding = Rectangle.inset(3); @@ -72,7 +72,7 @@ describe('text rendering', () => { const visibleLines = 2; const paddingLines = 1; expect(textBounds.height).closeTo(lineHeight * (scrolledLines + visibleLines + paddingLines) + (padTop + padBot), 30, 'text layer does not have size of all lines'); - expect(node.querySelector('.newtext-text-layer.actual').textContent).lessThan(10111213, 'text layer renders more than necessary'); + expect(Number(node.querySelector('.newtext-text-layer.actual').textContent)).lessThan(10111213, 'text layer renders more than necessary'); }); it('can resize on content change', async () => { diff --git a/lively.morphic/web/bootstrap.js b/lively.morphic/web/bootstrap.js deleted file mode 100644 index 2be8c20507..0000000000 --- a/lively.morphic/web/bootstrap.js +++ /dev/null @@ -1,178 +0,0 @@ -/*global System*/ -// import 'systemjs'; -import { resource, loadViaScript } from 'lively.resources'; -import { promise, obj } from 'lively.lang'; -import * as modulePackage from 'lively.modules'; -import 'lively.modules/systemjs-init.js'; - -lively.modules = modulePackage; // temporary modules package used for bootstrapping -lively.FreezerRuntime = null; - -if (document.location.host !== "lively-next.org") - document.title = `lively.next (${document.location.host})`; -let status = document.getElementById("dom-loading-status"); -function log() { - console.log(...arguments); - status.innerText = [...arguments].join(" "); -} -var loc = document.location, - origin = loc.origin, - query = resource(loc.href).query(), - loadingIndicator = document.getElementById("dom-loading-indicator"), - worldNameMatch = decodeURIComponent(loc.pathname).match(/\/worlds\/(.+)/), - worldName = worldNameMatch - ? worldNameMatch[1].replace(/(\.json)?($|\?.*)/, ".json$2") - : "default", - res = resource(origin + "/" + "lively.morphic/worlds/" + worldName), - loginDone = false, - worldLoaded = false, - isBenchmark = worldNameMatch && worldNameMatch[1].startsWith("morph benchmark")/*FIXME!!!2017-11-15*/, - doBootstrap = !query.quickload && !isBenchmark, - askBeforeQuit = 'askBeforeQuit' in query ? !!query.askBeforeQuit : true; - -Promise.resolve() - .then(polyfills) - .then(function() { return (doBootstrap) ? bootstrapLivelySystem() : fastPrepLivelySystem(); }) - .then(function() { - let t = Date.now() - window._livelyLoadStart; - log(`...lively systems are ready`); - console.log(`load time ${t}ms`); - }) - .then(function() { - log("Loading lively.2lively..."); - return lively.modules.registerPackage('lively.2lively'); - }) - .then(function() { - if (askBeforeQuit) { - window.addEventListener('beforeunload', function(evt) { - var msg = "Really?"; - evt.returnValue = msg; - return msg; - }, true); - } - return { - resource: res, - showWorldLoadDialog: !worldNameMatch, - }; - }) - .then(function(worldLocation) { - log("Loading lively.morphic..."); - return Promise.all([ - lively.modules.importPackage('lively.morphic'), - promise.waitFor(function() { return loginDone; }) - ]).then(function([morphic]) { - log("Loading world..."); - return morphic.World.loadWorldFromURL(worldLocation.resource, null, { - verbose: true, - localconfig: true, - l2l: true, - shell: true, - worldLoadDialog: worldLocation.showWorldLoadDialog, - browserURL: "/worlds/" + worldLocation.resource.name().replace(/\.json($|\?)/, "") - }); - }) - }) - .then(function() { - worldLoaded = true; - let t = Date.now() - window._livelyLoadStart; - log(`...lively.morphic world ready`); - console.log(`load time ${t}ms`); - }) - .catch(function(err) { - //if (err.originalErr) err = err.originalErr; // do not hide vital information! - console.error(err); - var printed = err.message; - if (err.stack !== err.message) { - printed += err.stack.includes(err.message) ? err.stack.replace(err.message, "\n") : err.stack; - console.error(printed); - } - let pre = document.createElement("pre"); - pre.innerText = printed; - document.body.appendChild(pre); - }); - -function fastPrepLivelySystem() { - return Promise.resolve() - .then(function() { log("starting fast system preparation..."); }) - .then(function() { return resource(origin).join("package-registry.json").readJson(); }) - .then(function (packageCached) { - System["__lively.modules__packageRegistry"] = lively.modules.PackageRegistry.fromJSON(System, packageCached); - return System; - }) -} - -function bootstrapLivelySystem() { - // for loading an instrumented version of the packages comprising the lively.system - return Promise.resolve() - .then(function() { log("starting bootstrap process..."); }) - - .then(function() { return resource(origin).join("package-registry.json").readJson(); }) - .then(function (packageCached) { - var System = lively.modules.getSystem("bootstrapped", {baseURL: origin}); - // System.debug = true; - lively.modules.changeSystem(System, true); - System["__lively.modules__packageRegistry"] = lively.modules.PackageRegistry.fromJSON(System, packageCached); - return System; - }) - .then(function() { - return importPackageAndDo( - "lively.lang", - function(m) { delete m._prevLivelyGlobal; }); }) - - .then(function() { - return importPackageAndDo( - "lively.ast", - function(m) { lively.ast = m; }); }) - - .then(function() { - return importPackageAndDo( - "lively.source-transform", - function(m) { lively.sourceTransform = m; }); }) - - .then(function() { - return importPackageAndDo( - "lively.classes", - function(m) { lively.classes = m; }); }) - - .then(function() { - return importPackageAndDo( - "lively.vm", - function(m) { lively.vm = m; }); }) - - .then(function() { - return importPackageAndDo( - "lively.modules", - function(m) { - lively.modules = m; - lively.modules.unwrapModuleLoad(); - lively.modules.unwrapModuleResolution(); - lively.modules.wrapModuleLoad(); - lively.modules.wrapModuleResolution(); - let oldRegistry = System["__lively.modules__packageRegistry"]; - delete System["__lively.modules__packageRegistry"]; - let newRegistry = System["__lively.modules__packageRegistry"] = m.PackageRegistry.ofSystem(System); - Object.assign(newRegistry, obj.select(oldRegistry, ["packageMap", "individualPackageDirs", "devPackageDirs", "packageBaseDirs"])) - newRegistry.resetByURL(); - })}) - - .then(function() { - return importPackageAndDo( - "lively.storage", - function(m) { lively.storage = m; })}) -} - -function importPackageAndDo(packageURL, doFunc) { - var name = packageURL.split("/").slice(-1)[0]; - log(`...loading ${name}...`); - return lively.modules.importPackage(packageURL) - .then(doFunc || function() {}); -} - -function polyfills() { - var loads = []; - if (!("PointerEvent" in window)) - loads.push(loadViaScript(`${origin}/lively.next-node_modules/pepjs/dist/pep.js`)); - if (!("fetch" in window)) - loads.push(loadViaScript(`//cdnjs.cloudflare.com/ajax/libs/fetch/1.0.0/fetch.js`)); - return Promise.all(loads); -} \ No newline at end of file diff --git a/lively.morphic/web/lively.bootstrap.min.js b/lively.morphic/web/lively.bootstrap.min.js deleted file mode 100644 index 3cc7852449..0000000000 --- a/lively.morphic/web/lively.bootstrap.min.js +++ /dev/null @@ -1,1119 +0,0 @@ -/* - PEP v0.4.3 | https://github.com/jquery/PEP - Copyright jQuery Foundation and other contributors | http://jquery.org/license -*/ -var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.arrayIteratorImpl=function(h){var p=0;return function(){return p=C}},"es6","es3"); -$jscomp.polyfill("String.prototype.endsWith",function(h){return h?h:function(h,c){var p=$jscomp.checkStringArgs(this,h,"endsWith");h+="";void 0===c&&(c=p.length);c=Math.max(0,Math.min(c|0,p.length));for(var g=h.length;0=g}},"es6","es3");$jscomp.polyfill("Object.is",function(h){return h?h:function(h,c){return h===c?0!==h||1/h===1/c:h!==h&&c!==c}},"es6","es3"); -$jscomp.polyfill("Array.prototype.includes",function(h){return h?h:function(h,c){var p=this;p instanceof String&&(p=String(p));var g=p.length;c=c||0;for(0>c&&(c=Math.max(c+g,0));ch||1342177279>>=1)c+=c;return p}},"es6","es3"); -$jscomp.polyfill("Array.prototype.values",function(h){return h?h:function(){return $jscomp.iteratorFromArray(this,function(h,c){return c})}},"es8","es3");$jscomp.polyfill("Object.getOwnPropertySymbols",function(h){return h?h:function(){return[]}},"es6","es5"); -var _slicedToArray=function(){return function(h,p){if(Array.isArray(h))return h;$jscomp.initSymbol();$jscomp.initSymbolIterator();if(Symbol.iterator in Object(h)){var c=[],F=!0,g=!1,C=void 0;try{$jscomp.initSymbol();$jscomp.initSymbolIterator();for(var v=h[Symbol.iterator](),t;!(F=(t=v.next()).done)&&(c.push(t.value),!p||c.length!==p);F=!0);}catch(d){g=!0,C=d}finally{try{if(!F&&v["return"])v["return"]()}finally{if(g)throw C;}}return c}throw new TypeError("Invalid attempt to destructure non-iterable instance"); -}}();$jscomp.initSymbol();$jscomp.initSymbol();$jscomp.initSymbolIterator();var _typeof="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(h){return typeof h}:function(h){$jscomp.initSymbol();$jscomp.initSymbol();$jscomp.initSymbol();return h&&"function"===typeof Symbol&&h.constructor===Symbol&&h!==Symbol.prototype?"symbol":typeof h};function _toConsumableArray(h){if(Array.isArray(h)){for(var p=0,c=Array(h.length);pm)L=!0;!L&&(isNaN(x)|| -!isNaN(b)&&b>x)&&(L=!0);!L&&(isNaN(D)||!isNaN(a)&&a>D)&&(L=!0);if(!L)return;C=g.lively.FreezerRuntime.registry}v["@lively-env"]={executed:!0,options:{},moduleEnv:function(a){a=System.get(a,!1)||System.fetchStandaloneFor(a)||System.get(a+"index.js",!1);return{recorder:a.recorder||a.exports}}};v["@system-env"]={executed:!0,browser:!0};g.lively.FreezerRuntime={global:g,version:void 0,registry:C,globalModules:v,get:function(a){var b=1v||(k.length===v&&d(k,t,O)?(O.push(K),C.push(E)):(v=k.length,d(k,t,O)&&(O=[K],C=[E])))}if(0==O.length)break;for(E=C.length;E--;)K=m[C[E]],m.splice(C[E],1);t.push.apply(t,_toConsumableArray(O))}k=m;var X;m=!0;L=!1;var da=void 0;try{$jscomp.initSymbol();$jscomp.initSymbolIterator();for(var ra=t[Symbol.iterator](),Y;!(m=(Y=ra.next()).done);m=!0){var Z=Y.value;for(X=h[Z].modules;X.length;){v=Infinity;O=[];C=[];F=[];for(E=0;E< -X.length;E++){K=X[E];var M=g[K]||[];if(!(M.length>v))if(M.length===v&&d(M,a,O)){var I;O.push(K);C.push(E);(I=F).push.apply(I,_toConsumableArray(D[K]||[]))}else v=M.length,d(M,a,O)&&(O=[K],C=[E],F=(D[K]||[]).slice())}if(0==O.length)break;for(E=C.length;E--;)K=X[C[E]],D[K]=[],X.splice(C[E],1);t=!0;var Ia=!1,Na=void 0;try{$jscomp.initSymbol();$jscomp.initSymbolIterator();for(var Da=F[Symbol.iterator](),Oa;!(t=(Oa=Da.next()).done);t=!0)K=Oa.value,g[K]=g[K].filter(function(u){return!O.includes(u)})}catch(T){Ia= -!0,Na=T}finally{try{!t&&Da.return&&Da.return()}finally{if(Ia)throw Na;}}a.push.apply(a,_toConsumableArray(O))}a.push.apply(a,_toConsumableArray(X))}}catch(T){L=!0,da=T}finally{try{!m&&ra.return&&ra.return()}finally{if(L)throw da;}}m=x;F=!0;v=!1;C=void 0;try{$jscomp.initSymbol();$jscomp.initSymbolIterator();for(var R=k[Symbol.iterator](),ta;!(F=(ta=R.next()).done);F=!0){var ka;Z=ta.value;(ka=m).push.apply(ka,_toConsumableArray(h[Z].modules))}}catch(T){v=!0,C=T}finally{try{!F&&R.return&&R.return()}finally{if(v)throw C; -}}for(;m.length;){v=Infinity;O=[];C=[];F=[];for(E=0;Ev))if(Z.length===v&&d(Z,a,O)){var xa;O.push(K);C.push(E);(xa=F).push.apply(xa,_toConsumableArray(D[K]||[]))}else v=Z.length,d(Z,a,O)&&(O=[K],C=[E],F=(D[K]||[]).slice());if(0==O.length)break;for(E=C.length;E--;)K=m[C[E]],D[K]=[],m.splice(C[E],1);Z=!0;R=!1;ta=void 0;try{$jscomp.initSymbol();$jscomp.initSymbolIterator();for(var pa=F[Symbol.iterator](),u;!(Z=(u=pa.next()).done);Z=!0)K=u.value,g[K]=g[K].filter(function(u){return!O.includes(u)})}catch(T){R= -!0,ta=T}finally{try{!Z&&pa.return&&pa.return()}finally{if(R)throw ta;}}a.push.apply(a,_toConsumableArray(O))}K=[];for(var W in a)(g[W]||[]).length&&K.push(W);console.log("async modules due to preserved module structures: ",[].concat(K,_toConsumableArray(m)));return[a,m]},initializeClass:function(a,b){var c=2D;D++)d(c);return this.get(a).exports}};g.System||(g.System=g.lively.FreezerRuntime)})(); -!function(h,p){"object"==typeof exports&&"undefined"!=typeof module?module.exports=p():"function"==typeof define&&define.amd?define(p):h.PointerEventsPolyfill=p()}(this,function(){function h(b,c){c=c||Object.create(null);var k=document.createEvent("Event");k.initEvent(b,c.bubbles||!1,c.cancelable||!1);for(var m=2;m=Math.abs(d-b.x)&&25>=l)return!0}},prepareEvent:function(a){var b=y.cloneEvent(a),c=b.preventDefault;return b.preventDefault=function(){a.preventDefault();c()},b.pointerId=this.POINTER_ID,b.isPrimary=!0,b.pointerType=this.POINTER_TYPE,b},prepareButtonsForMove:function(a, -b){var c=V.get(this.POINTER_ID);0!==b.which&&c?a.buttons=c.buttons:a.buttons=0;b.buttons=a.buttons},mousedown:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=V.get(this.POINTER_ID),c=this.prepareEvent(a);S||(c.buttons=sa[c.button],b&&(c.buttons|=b.buttons),a.buttons=c.buttons);V.set(this.POINTER_ID,a);b&&0!==b.buttons?y.move(c):y.down(c)}},mousemove:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);S||this.prepareButtonsForMove(b,a);b.button=-1;V.set(this.POINTER_ID, -a);y.move(b)}},mouseup:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=V.get(this.POINTER_ID),c=this.prepareEvent(a);if(!S){var d=sa[c.button];c.buttons=b?b.buttons&~d:0;a.buttons=c.buttons}V.set(this.POINTER_ID,a);c.buttons&=~sa[c.button];0===c.buttons?y.up(c):y.move(c)}},mouseover:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);S||this.prepareButtonsForMove(b,a);b.button=-1;V.set(this.POINTER_ID,a);y.enterOver(b)}},mouseout:function(a){if(!this.isEventSimulatedFromTouch(a)){var b= -this.prepareEvent(a);S||this.prepareButtonsForMove(b,a);b.button=-1;y.leaveOut(b)}},cancel:function(a){a=this.prepareEvent(a);y.cancel(a);this.deactivateMouse()},deactivateMouse:function(){V["delete"](this.POINTER_ID)}},qa=y.captureInfo,ba=N.findTarget.bind(N),E=N.allShadows.bind(N),K=y.pointermap,X={events:["touchstart","touchmove","touchend","touchcancel"],register:function(a){da.enableOnSubtree(a)},unregister:function(){},elementAdded:function(a){var b=a.getAttribute("touch-action"),c=this.touchActionToScrollType(b); -c&&(a._scrollType=c,y.listen(a,this.events),E(a).forEach(function(a){a._scrollType=c;y.listen(a,this.events)},this))},elementRemoved:function(a){a._scrollType=void 0;y.unlisten(a,this.events);E(a).forEach(function(a){a._scrollType=void 0;y.unlisten(a,this.events)},this)},elementChanged:function(a,b){var c=a.getAttribute("touch-action"),d=this.touchActionToScrollType(c);b=this.touchActionToScrollType(b);d&&b?(a._scrollType=d,E(a).forEach(function(a){a._scrollType=d},this)):b?this.elementRemoved(a): -d&&this.elementAdded(a)},scrollTypes:{EMITTER:"none",XSCROLLER:"pan-x",YSCROLLER:"pan-y",SCROLLER:/^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/},touchActionToScrollType:function(a){var b=this.scrollTypes;return"none"===a?"none":a===b.XSCROLLER?"X":a===b.YSCROLLER?"Y":b.SCROLLER.exec(a)?"XY":void 0},POINTER_TYPE:"touch",firstTouch:null,isPrimaryTouch:function(a){return this.firstTouch===a.identifier},setPrimaryTouch:function(a){(0===K.size||1===K.size&&K.has(1))&&(this.firstTouch=a.identifier,this.firstXY= -{X:a.clientX,Y:a.clientY},this.scrolling=!1,this.cancelResetClickCount())},removePrimaryPointer:function(a){a.isPrimary&&(this.firstTouch=null,this.firstXY=null,this.resetClickCount())},clickCount:0,resetId:null,resetClickCount:function(){var a=function(){this.clickCount=0;this.resetId=null}.bind(this);this.resetId=setTimeout(a,200)},cancelResetClickCount:function(){this.resetId&&clearTimeout(this.resetId)},typeToButtons:function(a){var b=0;return"touchstart"!==a&&"touchmove"!==a||(b=1),b},touchToPointer:function(a){var b= -this.currentTouchEvent,c=y.cloneEvent(a),d=c.pointerId=a.identifier+2;c.target=qa[d]||ba(c);c.bubbles=!0;c.cancelable=!0;c.detail=this.clickCount;c.button=0;c.buttons=this.typeToButtons(b.type);c.width=2*(a.radiusX||a.webkitRadiusX||0);c.height=2*(a.radiusY||a.webkitRadiusY||0);c.pressure=a.force||a.webkitForce||.5;c.isPrimary=this.isPrimaryTouch(a);c.pointerType=this.POINTER_TYPE;c.altKey=b.altKey;c.ctrlKey=b.ctrlKey;c.metaKey=b.metaKey;c.shiftKey=b.shiftKey;var k=this;return c.preventDefault=function(){k.scrolling= -!1;k.firstXY=null;b.preventDefault()},c},processTouches:function(a,b){var c=a.changedTouches;this.currentTouchEvent=a;for(var d=0;d=Math.abs(a["client"+c]-this.firstXY[c])}return this.firstXY=null,b}},findTouch:function(a,b){for(var c, -d=0,k=a.length;d=b.length){var c=[];K.forEach(function(a,d){1===d||this.findTouch(b,d-2)||c.push(a.out)},this);c.forEach(this.cancelOut,this)}},touchstart:function(a){this.vacuumTouches(a);this.setPrimaryTouch(a.changedTouches[0]);this.dedupSynthMouse(a);this.scrolling||(this.clickCount++,this.processTouches(a,this.overDown))},overDown:function(a){K.set(a.pointerId,{target:a.target,out:a,outTarget:a.target}); -y.enterOver(a);y.down(a)},touchmove:function(a){this.scrolling||(this.shouldScroll(a)?(this.scrolling=!0,this.touchcancel(a)):(a.preventDefault(),this.processTouches(a,this.moveOverOut)))},moveOverOut:function(a){var b=K.get(a.pointerId);if(b){var c=b.out,d=b.outTarget;y.move(a);c&&d!==a.target&&(c.relatedTarget=a.target,a.relatedTarget=d,c.target=d,a.target?(y.leaveOut(c),y.enterOver(a)):(a.target=d,a.relatedTarget=null,this.cancelOut(a)));b.out=a;b.outTarget=a.target}},touchend:function(a){this.dedupSynthMouse(a); -this.processTouches(a,this.upOut)},upOut:function(a){this.scrolling||(y.up(a),y.leaveOut(a));this.cleanUpPointer(a)},touchcancel:function(a){this.processTouches(a,this.cancelOut)},cancelOut:function(a){y.cancel(a);y.leaveOut(a);this.cleanUpPointer(a)},cleanUpPointer:function(a){K["delete"](a.pointerId);this.removePrimaryPointer(a)},dedupSynthMouse:function(a){var b=O.lastTouches;a=a.changedTouches[0];this.isPrimaryTouch(a)&&(a={x:a.clientX,y:a.clientY},b.push(a),b=function(a,b){b=a.indexOf(b);-1< -b&&a.splice(b,1)}.bind(null,b,a),setTimeout(b,2500))}};var da=new c(X.elementAdded,X.elementRemoved,X.elementChanged,X);var ra,Y,Z=y.pointermap,M=window.MSPointerEvent&&"number"==typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE,I={events:"MSPointerDown MSPointerMove MSPointerUp MSPointerOut MSPointerOver MSPointerCancel MSGotPointerCapture MSLostPointerCapture".split(" "),register:function(a){y.listen(a,this.events)},unregister:function(a){y.unlisten(a,this.events)},POINTER_TYPES:["","unavailable", -"touch","pen","mouse"],prepareEvent:function(a){var b=a;return M&&(b=y.cloneEvent(a),b.pointerType=this.POINTER_TYPES[a.pointerType]),b},cleanup:function(a){Z["delete"](a)},MSPointerDown:function(a){Z.set(a.pointerId,a);a=this.prepareEvent(a);y.down(a)},MSPointerMove:function(a){a=this.prepareEvent(a);y.move(a)},MSPointerUp:function(a){var b=this.prepareEvent(a);y.up(b);this.cleanup(a.pointerId)},MSPointerOut:function(a){a=this.prepareEvent(a);y.leaveOut(a)},MSPointerOver:function(a){a=this.prepareEvent(a); -y.enterOver(a)},MSPointerCancel:function(a){var b=this.prepareEvent(a);y.cancel(b);this.cleanup(a.pointerId)},MSLostPointerCapture:function(a){a=y.makeEvent("lostpointercapture",a);y.dispatchEvent(a)},MSGotPointerCapture:function(a){a=y.makeEvent("gotpointercapture",a);y.dispatchEvent(a)}};window.navigator.msPointerEnabled?(ra=function(a){v(a);t(this);0!==y.pointermap.get(a).buttons&&(y.setCapture(a,this,!0),this.msSetPointerCapture(a))},Y=function(a){v(a);y.releaseCapture(a,!0);this.msReleasePointerCapture(a)}): -(ra=function(a){v(a);t(this);0!==y.pointermap.get(a).buttons&&y.setCapture(a,this)},Y=function(a){v(a);y.releaseCapture(a)});var Ia=function(a){return!!y.captureInfo[a]};(function(){if(ja){U.forEach(function(a){String(a)===a?(H+=g(a)+C(a)+"\n",k&&(H+=F(a)+C(a)+"\n")):(H+=a.selectors.map(g)+C(a.rule)+"\n",k&&(H+=a.selectors.map(F)+C(a.rule)+"\n"))});var a=document.createElement("style");a.textContent=H;document.head.appendChild(a)}})();window.PointerEvent||((window.PointerEvent=h,window.navigator.msPointerEnabled)? -(Object.defineProperty(window.navigator,"maxTouchPoints",{value:window.navigator.msMaxTouchPoints,enumerable:!0}),y.registerSource("ms",I)):(Object.defineProperty(window.navigator,"maxTouchPoints",{value:0,enumerable:!0}),y.registerSource("mouse",O),void 0!==window.ontouchstart&&y.registerSource("touch",X)),y.register(document));window.Element&&!Element.prototype.setPointerCapture&&Object.defineProperties(Element.prototype,{setPointerCapture:{value:ra},releasePointerCapture:{value:Y},hasPointerCapture:{value:Ia}}); -return{dispatcher:y,Installer:c,PointerEvent:h,PointerMap:b,targetFinding:N}}); -(function(h,p){"object"===typeof exports&&"undefined"!==typeof module?p(exports):"function"===typeof define&&define.amd?define(["exports"],p):p(h.WHATWGFetch={})})(this,function(h){function p(a){"string"!==typeof a&&(a=String(a));if(/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(a))throw new TypeError("Invalid character in header field name");return a.toLowerCase()}function c(a){"string"!==typeof a&&(a=String(a));return a}function F(a){var b={next:function(){var b=a.shift();return{done:void 0===b,value:b}}};l.iterable&& -($jscomp.initSymbol(),$jscomp.initSymbolIterator(),b[Symbol.iterator]=function(){return b});return b}function g(a){this.map={};a instanceof g?a.forEach(function(a,b){this.append(b,a)},this):Array.isArray(a)?a.forEach(function(a){this.append(a[0],a[1])},this):a&&Object.getOwnPropertyNames(a).forEach(function(b){this.append(b,a[b])},this)}function C(a){if(a.bodyUsed)return Promise.reject(new TypeError("Already read"));a.bodyUsed=!0}function v(a){return new Promise(function(b,c){a.onload=function(){b(a.result)}; -a.onerror=function(){c(a.error)}})}function t(a){var b=new FileReader,c=v(b);b.readAsArrayBuffer(a);return c}function d(a){a=new Uint8Array(a);for(var b=Array(a.length),c=0;cthis.status;this.statusText="statusText"in b?b.statusText:"OK"; -this.headers=new g(b.headers);this.url=b.url||"";this._initBody(a)}function y(a,b){return new Promise(function(c,d){function k(){g.abort()}var q=new m(a,b);if(q.signal&&q.signal.aborted)return d(new h.DOMException("Aborted","AbortError"));var g=new XMLHttpRequest;g.onload=function(){var a={status:g.status,statusText:g.statusText,headers:x(g.getAllResponseHeaders()||"")};a.url="responseURL"in g?g.responseURL:a.headers.get("X-Request-URL");c(new L("response"in g?g.response:g.responseText,a))};g.onerror= -function(){d(new TypeError("Network request failed"))};g.ontimeout=function(){d(new TypeError("Network request failed"))};g.onabort=function(){d(new h.DOMException("Aborted","AbortError"))};g.open(q.method,q.url,!0);"include"===q.credentials?g.withCredentials=!0:"omit"===q.credentials&&(g.withCredentials=!1);"responseType"in g&&l.blob&&(g.responseType="blob");q.headers.forEach(function(a,b){g.setRequestHeader(b,a)});q.signal&&(q.signal.addEventListener("abort",k),g.onreadystatechange=function(){4=== -g.readyState&&q.signal.removeEventListener("abort",k)});g.send("undefined"===typeof q._bodyInit?null:q._bodyInit)})}$jscomp.initSymbol();var N="Symbol"in self&&"iterator"in Symbol,q;if(q="FileReader"in self&&"Blob"in self)try{new Blob,q=!0}catch(U){q=!1}var l={searchParams:"URLSearchParams"in self,iterable:N,blob:q,formData:"FormData"in self,arrayBuffer:"ArrayBuffer"in self};if(l.arrayBuffer)var G="[object Int8Array];[object Uint8Array];[object Uint8ClampedArray];[object Int16Array];[object Uint16Array];[object Int32Array];[object Uint32Array];[object Float32Array];[object Float64Array]".split(";"), -Ma=ArrayBuffer.isView||function(a){return a&&-1a)return!1;u+=b[c+1];if(u>=a)return!0}}function p(a,b){return 65>a?36===a:91>a?!0:97>a?95===a:123>a?!0:65535>=a?170<=a&&G.test(String.fromCharCode(a)):!1===b?!1:c(a,ha)}function g(a,b){return 48>a?36===a:58>a?!0:65>a?!1:91>a?!0:97>a?95===a:123>a?!0:65535>=a?170<= -a&&Ma.test(String.fromCharCode(a)):!1===b?!1:c(a,ha)||c(a,Ba)}function C(a,b){return new U(a,{beforeExpr:!0,binop:b})}function v(a,b){void 0===b&&(b={});b.keyword=a;return ja[a]=new U(a,b)}function t(a){return 10===a||13===a||8232===a||8233===a}function d(a,b){for(var u=1,c=0;;){sa.lastIndex=c;var d=sa.exec(a);if(d&&d.indexu.ecmaVersion);if(E(u.onToken)){var d=u.onToken;u.onToken=function(a){return d.push(a)}}E(u.onComment)&&(u.onComment=b(u,u.onComment));return u}function b(a,b){return function(u,c,d,m,A,W){u={type:u?"Block":"Line",value:c,start:d,end:m};a.locations&&(u.loc=new X(this,A,W));a.ranges&&(u.range=[d,m]);b.push(u)}}function m(a){return new RegExp("^(?:"+a.replace(/ /g,"|")+")$")}function D(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=-1}function x(a, -b,c,d){a.type=b;a.end=c;this.options.locations&&(a.loc.end=d);this.options.ranges&&(a.range[1]=c);return a}function L(a,b,c,d){try{return new RegExp(a,b)}catch(Sa){if(void 0!==c)throw Sa instanceof SyntaxError&&d.raise(c,"Error parsing regular expression: "+Sa.message),Sa;}}function y(a){if(65535>=a)return String.fromCharCode(a);a-=65536;return String.fromCharCode((a>>10)+55296,(a&1023)+56320)}var N={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", -5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},q={5:"break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",6:"break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this const class extends export import super"}, -l="\u00aa\u00b5\u00ba\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fd5\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ae\ua7b0-\ua7b7\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc", -G=new RegExp("["+l+"]"),Ma=new RegExp("["+l+"\u200c\u200d\u00b7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d4-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d01-\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf8\u1cf9\u1dc0-\u1df5\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f]"); -l=null;var ha=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25, -391,63,32,0,449,56,264,8,2,36,18,0,50,29,881,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,0,32,6124,20,754,9486,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148, -12,221,3,5761,10591,541],Ba=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,838,7,2,7,17,9,57,21,2,13,19882,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239],U=function(a,b){void 0=== -b&&(b={});this.label=a;this.keyword=b.keyword;this.beforeExpr=!!b.beforeExpr;this.startsExpr=!!b.startsExpr;this.isLoop=!!b.isLoop;this.isAssign=!!b.isAssign;this.prefix=!!b.prefix;this.postfix=!!b.postfix;this.binop=b.binop||null;this.updateContext=null};l={beforeExpr:!0};var H={startsExpr:!0},ja={},k={num:new U("num",H),regexp:new U("regexp",H),string:new U("string",H),name:new U("name",H),eof:new U("eof"),bracketL:new U("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new U("]"),braceL:new U("{",{beforeExpr:!0, -startsExpr:!0}),braceR:new U("}"),parenL:new U("(",{beforeExpr:!0,startsExpr:!0}),parenR:new U(")"),comma:new U(",",l),semi:new U(";",l),colon:new U(":",l),dot:new U("."),question:new U("?",l),arrow:new U("=>",l),template:new U("template"),invalidTemplate:new U("invalidTemplate"),ellipsis:new U("...",l),backQuote:new U("`",H),dollarBraceL:new U("${",{beforeExpr:!0,startsExpr:!0}),eq:new U("=",{beforeExpr:!0,isAssign:!0}),assign:new U("_=",{beforeExpr:!0,isAssign:!0}),incDec:new U("++/--",{prefix:!0, -postfix:!0,startsExpr:!0}),prefix:new U("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:C("||",1),logicalAND:C("&&",2),bitwiseOR:C("|",3),bitwiseXOR:C("^",4),bitwiseAND:C("&",5),equality:C("==/!=/===/!==",6),relational:C("/<=/>=",7),bitShift:C("<>/>>>",8),plusMin:new U("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:C("%",10),star:C("*",10),slash:C("/",10),starstar:new U("**",{beforeExpr:!0}),_break:v("break"),_case:v("case",l),_catch:v("catch"),_continue:v("continue"), -_debugger:v("debugger"),_default:v("default",l),_do:v("do",{isLoop:!0,beforeExpr:!0}),_else:v("else",l),_finally:v("finally"),_for:v("for",{isLoop:!0}),_function:v("function",H),_if:v("if"),_return:v("return",l),_switch:v("switch"),_throw:v("throw",l),_try:v("try"),_var:v("var"),_const:v("const"),_while:v("while",{isLoop:!0}),_with:v("with"),_new:v("new",{beforeExpr:!0,startsExpr:!0}),_this:v("this",H),_super:v("super",H),_class:v("class",H),_extends:v("extends",l),_export:v("export"),_import:v("import"), -_null:v("null",H),_true:v("true",H),_false:v("false",H),_in:v("in",{beforeExpr:!0,binop:7}),_instanceof:v("instanceof",{beforeExpr:!0,binop:7}),_typeof:v("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:v("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:v("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},V=/\r\n?|\n|\u2028|\u2029/,sa=new RegExp(V.source,"g"),S=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/,O=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;l=Object.prototype;var qa=l.hasOwnProperty, -ba=l.toString,E=Array.isArray||function(a){return"[object Array]"===ba.call(a)},K=function(a,b){this.line=a;this.column=b};K.prototype.offset=function(a){return new K(this.line,this.column+a)};var X=function(a,b,c){this.start=b;this.end=c;null!==a.sourceFile&&(this.source=a.sourceFile)},da={ecmaVersion:7,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowHashBang:!1,locations:!1,onToken:null,onComment:null, -ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1,plugins:{}},ra={},Y=function(b,c,d){this.options=b=a(b);this.sourceFile=b.sourceFile;this.keywords=m(q[6<=b.ecmaVersion?6:5]);var u="";if(!b.allowReserved){for(var W=b.ecmaVersion;!(u=N[W]);W--);"module"==b.sourceType&&(u+=" await")}this.reservedWords=m(u);u=(u?u+" ":"")+N.strict;this.reservedWordsStrict=m(u);this.reservedWordsStrictBind=m(u+" "+N.strictBind);this.input=String(c);this.containsEsc=!1;this.loadPlugins(b.plugins); -d?(this.pos=d,this.lineStart=this.input.lastIndexOf("\n",d-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(V).length):(this.pos=this.lineStart=0,this.curLine=1);this.type=k.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=!0;this.strict=(this.inModule="module"===b.sourceType)||this.strictDirective(this.pos); -this.potentialArrowAt=-1;this.inFunction=this.inGenerator=this.inAsync=!1;this.yieldPos=this.awaitPos=0;this.labels=[];0===this.pos&&b.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2);this.scopeStack=[];this.enterFunctionScope()};Y.prototype.isKeyword=function(a){return this.keywords.test(a)};Y.prototype.isReservedWord=function(a){return this.reservedWords.test(a)};Y.prototype.extend=function(a,b){this[a]=b(this[a])};Y.prototype.loadPlugins=function(a){for(var b in a){var c=ra[b]; -if(!c)throw Error("Plugin '"+b+"' not found");c(this,a[b])}};Y.prototype.parse=function(){var a=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(a)};l=Y.prototype;var Z=/^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)"|;)/;l.strictDirective=function(a){for(;;){O.lastIndex=a;a+=O.exec(this.input)[0].length;var b=Z.exec(this.input.slice(a));if(!b)return!1;if("use strict"==(b[1]||b[2]))return!0;a+=b[0].length}};l.eat=function(a){return this.type===a?(this.next(),!0):!1};l.isContextual= -function(a){return this.type===k.name&&this.value===a};l.eatContextual=function(a){return this.value===a&&this.eat(k.name)};l.expectContextual=function(a){this.eatContextual(a)||this.unexpected()};l.canInsertSemicolon=function(){return this.type===k.eof||this.type===k.braceR||V.test(this.input.slice(this.lastTokEnd,this.start))};l.insertSemicolon=function(){if(this.canInsertSemicolon()){if(this.options.onInsertedSemicolon)this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc);return!0}}; -l.semicolon=function(){this.eat(k.semi)||this.insertSemicolon()||this.unexpected()};l.afterTrailingComma=function(a,b){if(this.type==a){if(this.options.onTrailingComma)this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc);b||this.next();return!0}};l.expect=function(a){this.eat(a)||this.unexpected()};l.unexpected=function(a){this.raise(null!=a?a:this.start,"Unexpected token")};l.checkPatternErrors=function(a,b){a&&(-1this.options.ecmaVersion||"let"!=this.value)return!1;O.lastIndex=this.pos;var a=O.exec(this.input);a=this.pos+a[0].length;var b=this.input.charCodeAt(a);if(91===b||123==b)return!0;if(p(b,!0)){for(b=a+1;g(this.input.charCodeAt(b),!0);)++b;a=this.input.slice(a,b);if(!this.isKeyword(a))return!0}return!1};l.isAsyncFunction=function(){if(this.type!==k.name||8>this.options.ecmaVersion||"async"!=this.value)return!1;O.lastIndex=this.pos;var a=O.exec(this.input); -a=this.pos+a[0].length;return!V.test(this.input.slice(this.pos,a))&&"function"===this.input.slice(a,a+8)&&(a+8==this.input.length||!g(this.input.charAt(a+8)))};l.parseStatement=function(a,b,c){var u=this.type,d=this.startNode();if(this.isLet()){u=k._var;var m="let"}switch(u){case k._break:case k._continue:return this.parseBreakContinueStatement(d,u.keyword);case k._debugger:return this.parseDebuggerStatement(d);case k._do:return this.parseDoStatement(d);case k._for:return this.parseForStatement(d); -case k._function:return!a&&6<=this.options.ecmaVersion&&this.unexpected(),this.parseFunctionStatement(d,!1);case k._class:return a||this.unexpected(),this.parseClass(d,!0);case k._if:return this.parseIfStatement(d);case k._return:return this.parseReturnStatement(d);case k._switch:return this.parseSwitchStatement(d);case k._throw:return this.parseThrowStatement(d);case k._try:return this.parseTryStatement(d);case k._const:case k._var:return m=m||this.value,a||"var"==m||this.unexpected(),this.parseVarStatement(d, -m);case k._while:return this.parseWhileStatement(d);case k._with:return this.parseWithStatement(d);case k.braceL:return this.parseBlock();case k.semi:return this.parseEmptyStatement(d);case k._export:case k._import:return this.options.allowImportExportEverywhere||(b||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),u===k._import?this.parseImport(d):this.parseExport(d, -c);default:if(this.isAsyncFunction()&&a)return this.next(),this.parseFunctionStatement(d,!0);a=this.value;b=this.parseExpression();return u===k.name&&"Identifier"===b.type&&this.eat(k.colon)?this.parseLabeledStatement(d,a,b):this.parseExpressionStatement(d,b)}};l.parseBreakContinueStatement=function(a,b){var c="break"==b;this.next();this.eat(k.semi)||this.insertSemicolon()?a.label=null:this.type!==k.name?this.unexpected():(a.label=this.parseIdent(),this.semicolon());for(var u=0;ud){var A=this.type===k.logicalOR||this.type===k.logicalAND,l=this.value;this.next();var q=this.start,g=this.startLoc;u=this.parseExprOp(this.parseMaybeUnary(null,!1),q,g,u,m);a=this.buildBinary(b,c,a,u,l,A);return this.parseExprOp(a,b,c,d,m)}return a};l.buildBinary=function(a,b,c,d,m, -l){a=this.startNodeAt(a,b);a.left=c;a.operator=m;a.right=d;return this.finishNode(a,l?"LogicalExpression":"BinaryExpression")};l.parseMaybeUnary=function(a,b){var c=this.start,d=this.startLoc;if(this.inAsync&&this.isContextual("await")){var u=this.parseAwait();b=!0}else if(this.type.prefix){u=this.startNode();var m=this.type===k.incDec;u.operator=this.value;u.prefix=!0;this.next();u.argument=this.parseMaybeUnary(null,!0);this.checkExpressionErrors(a,!0);m?this.checkLVal(u.argument):this.strict&&"delete"=== -u.operator&&"Identifier"===u.argument.type?this.raiseRecoverable(u.start,"Deleting local variable in strict mode"):b=!0;u=this.finishNode(u,m?"UpdateExpression":"UnaryExpression")}else{u=this.parseExprSubscripts(a);if(this.checkExpressionErrors(a))return u;for(;this.type.postfix&&!this.canInsertSemicolon();)a=this.startNodeAt(c,d),a.operator=this.value,a.prefix=!1,a.argument=u,this.checkLVal(u),this.next(),u=this.finishNode(a,"UpdateExpression")}return!b&&this.eat(k.starstar)?this.buildBinary(c,d, -u,this.parseMaybeUnary(null,!1),"**",!1):u};l.parseExprSubscripts=function(a){var b=this.start,c=this.startLoc,d=this.parseExprAtom(a),u="ArrowFunctionExpression"===d.type&&")"!==this.input.slice(this.lastTokStart,this.lastTokEnd);if(this.checkExpressionErrors(a)||u)return d;b=this.parseSubscripts(d,b,c);a&&"MemberExpression"===b.type&&(a.parenthesizedAssign>=b.start&&(a.parenthesizedAssign=-1),a.parenthesizedBind>=b.start&&(a.parenthesizedBind=-1));return b};l.parseSubscripts=function(a,b,c,d){for(var u= -8<=this.options.ecmaVersion&&"Identifier"===a.type&&"async"===a.name&&this.lastTokEnd==a.end&&!this.canInsertSemicolon(),m;;)if((m=this.eat(k.bracketL))||this.eat(k.dot)){var A=this.startNodeAt(b,c);A.object=a;A.property=m?this.parseExpression():this.parseIdent(!0);A.computed=!!m;m&&this.expect(k.bracketR);a=this.finishNode(A,"MemberExpression")}else if(!d&&this.eat(k.parenL)){A=new D;var l=this.yieldPos,q=this.awaitPos;this.awaitPos=this.yieldPos=0;m=this.parseExprList(k.parenR,8<=this.options.ecmaVersion, -!1,A);if(u&&!this.canInsertSemicolon()&&this.eat(k.arrow))return this.checkPatternErrors(A,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=l,this.awaitPos=q,this.parseArrowExpression(this.startNodeAt(b,c),m,!0);this.checkExpressionErrors(A,!0);this.yieldPos=l||this.yieldPos;this.awaitPos=q||this.awaitPos;A=this.startNodeAt(b,c);A.callee=a;A.arguments=m;a=this.finishNode(A,"CallExpression")}else if(this.type===k.backQuote)m=this.startNodeAt(b,c),m.tag=a,m.quasi=this.parseTemplate({isTagged:!0}), -a=this.finishNode(m,"TaggedTemplateExpression");else return a};l.parseExprAtom=function(a){var b=this.potentialArrowAt==this.start;switch(this.type){case k._super:return this.inFunction||this.raise(this.start,"'super' outside of function or class"),b=this.startNode(),this.next(),this.type!==k.dot&&this.type!==k.bracketL&&this.type!==k.parenL&&this.unexpected(),this.finishNode(b,"Super");case k._this:return b=this.startNode(),this.next(),this.finishNode(b,"ThisExpression");case k.name:a=this.start; -var c=this.startLoc,d=this.parseIdent(this.type!==k.name);if(8<=this.options.ecmaVersion&&"async"===d.name&&!this.canInsertSemicolon()&&this.eat(k._function))return this.parseFunction(this.startNodeAt(a,c),!1,!1,!0);if(b&&!this.canInsertSemicolon()){if(this.eat(k.arrow))return this.parseArrowExpression(this.startNodeAt(a,c),[d],!1);if(8<=this.options.ecmaVersion&&"async"===d.name&&this.type===k.name)return d=this.parseIdent(),!this.canInsertSemicolon()&&this.eat(k.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(a, -c),[d],!0)}return d;case k.regexp:return a=this.value,b=this.parseLiteral(a.value),b.regex={pattern:a.pattern,flags:a.flags},b;case k.num:case k.string:return this.parseLiteral(this.value);case k._null:case k._true:case k._false:return b=this.startNode(),b.value=this.type===k._null?null:this.type===k._true,b.raw=this.type.keyword,this.next(),this.finishNode(b,"Literal");case k.parenL:return c=this.start,b=this.parseParenAndDistinguishExpression(b),a&&(0>a.parenthesizedAssign&&!this.isSimpleAssignTarget(b)&& -(a.parenthesizedAssign=c),0>a.parenthesizedBind&&(a.parenthesizedBind=c)),b;case k.bracketL:return b=this.startNode(),this.next(),b.elements=this.parseExprList(k.bracketR,!0,!0,a),this.finishNode(b,"ArrayExpression");case k.braceL:return this.parseObj(!1,a);case k._function:return b=this.startNode(),this.next(),this.parseFunction(b,!1);case k._class:return this.parseClass(this.startNode(),!1);case k._new:return this.parseNew();case k.backQuote:return this.parseTemplate();default:this.unexpected()}}; -l.parseLiteral=function(a){var b=this.startNode();b.value=a;b.raw=this.input.slice(this.start,this.end);this.next();return this.finishNode(b,"Literal")};l.parseParenExpression=function(){this.expect(k.parenL);var a=this.parseExpression();this.expect(k.parenR);return a};l.parseParenAndDistinguishExpression=function(a){var b=this.start,c=this.startLoc,d=8<=this.options.ecmaVersion;if(6<=this.options.ecmaVersion){this.next();var m=this.start,u=this.startLoc,A=[],l=!0,q=!1,g=new D,h=this.yieldPos,Ga= -this.awaitPos;for(this.awaitPos=this.yieldPos=0;this.type!==k.parenR;)if(l?l=!1:this.expect(k.comma),d&&this.afterTrailingComma(k.parenR,!0)){q=!0;break}else if(this.type===k.ellipsis){var y=this.start;A.push(this.parseParenItem(this.parseRestBinding()));this.type===k.comma&&this.raise(this.start,"Comma is not permitted after the rest element");break}else{if(this.type===k.parenL&&!x)var x=this.start;A.push(this.parseMaybeAssign(!1,g,this.parseParenItem))}d=this.start;l=this.startLoc;this.expect(k.parenR); -if(a&&!this.canInsertSemicolon()&&this.eat(k.arrow))return this.checkPatternErrors(g,!1),this.checkYieldAwaitInDefaultParams(),x&&this.unexpected(x),this.yieldPos=h,this.awaitPos=Ga,this.parseParenArrowList(b,c,A);A.length&&!q||this.unexpected(this.lastTokStart);y&&this.unexpected(y);this.checkExpressionErrors(g,!0);this.yieldPos=h||this.yieldPos;this.awaitPos=Ga||this.awaitPos;1A.shorthandAssign&&(A.shorthandAssign=this.start),a.value=this.parseMaybeDefault(m,l,a.key)):a.value=a.key,a.shorthand=!0):this.unexpected():((c||d)&&this.unexpected(),a.kind=a.key.name,this.parsePropertyName(a), -a.value=this.parseMethod(!1),a.value.params.length!==("get"===a.kind?0:1)?(b=a.value.start,"get"===a.kind?this.raiseRecoverable(b,"getter should have no params"):this.raiseRecoverable(b,"setter should have exactly one param")):"set"===a.kind&&"RestElement"===a.value.params[0].type&&this.raiseRecoverable(a.value.params[0].start,"Setter cannot use rest params"))};l.parsePropertyName=function(a){if(6<=this.options.ecmaVersion){if(this.eat(k.bracketL))return a.computed=!0,a.key=this.parseMaybeAssign(), -this.expect(k.bracketR),a.key;a.computed=!1}return a.key=this.type===k.num||this.type===k.string?this.parseExprAtom():this.parseIdent(!0)};l.initFunction=function(a){a.id=null;6<=this.options.ecmaVersion&&(a.generator=!1,a.expression=!1);8<=this.options.ecmaVersion&&(a.async=!1)};l.parseMethod=function(a,b){var c=this.startNode(),d=this.inGenerator,m=this.inAsync,l=this.yieldPos,A=this.awaitPos,q=this.inFunction;this.initFunction(c);6<=this.options.ecmaVersion&&(c.generator=a);8<=this.options.ecmaVersion&& -(c.async=!!b);this.inGenerator=c.generator;this.inAsync=c.async;this.awaitPos=this.yieldPos=0;this.inFunction=!0;this.enterFunctionScope();this.expect(k.parenL);c.params=this.parseBindingList(k.parenR,!1,8<=this.options.ecmaVersion);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(c,!1);this.inGenerator=d;this.inAsync=m;this.yieldPos=l;this.awaitPos=A;this.inFunction=q;return this.finishNode(c,"FunctionExpression")};l.parseArrowExpression=function(a,b,c){var d=this.inGenerator,m=this.inAsync, -l=this.yieldPos,A=this.awaitPos,q=this.inFunction;this.enterFunctionScope();this.initFunction(a);8<=this.options.ecmaVersion&&(a.async=!!c);this.inGenerator=!1;this.inAsync=a.async;this.awaitPos=this.yieldPos=0;this.inFunction=!0;a.params=this.toAssignableList(b,!0);this.parseFunctionBody(a,!0);this.inGenerator=d;this.inAsync=m;this.yieldPos=l;this.awaitPos=A;this.inFunction=q;return this.finishNode(a,"ArrowFunctionExpression")};l.parseFunctionBody=function(a,b){var c=this.strict,d=!1;if(b&&this.type!== -k.braceL)a.body=this.parseMaybeAssign(),a.expression=!0,this.checkParams(a,!1);else{var m=7<=this.options.ecmaVersion&&!this.isSimpleParamList(a.params);(!c||m)&&(d=this.strictDirective(this.end))&&m&&this.raiseRecoverable(a.start,"Illegal 'use strict' directive in function with non-simple parameter list");m=this.labels;this.labels=[];d&&(this.strict=!0);this.checkParams(a,!c&&!d&&!b&&this.isSimpleParamList(a.params));a.body=this.parseBlock(!1);a.expression=!1;this.adaptDirectivePrologue(a.body.body); -this.labels=m}this.exitFunctionScope();this.strict&&a.id&&this.checkLVal(a.id,"none");this.strict=c};l.isSimpleParamList=function(a){for(var b=0;bd.trailingComma&&(d.trailingComma=this.start)):A=this.parseMaybeAssign(!1,d);m.push(A)}return m};l.checkUnreserved=function(a){var b=a.start,c=a.end;a=a.name;this.inGenerator&&"yield"===a&&this.raiseRecoverable(b,"Can not use 'yield' as identifier inside a generator");this.inAsync&&"await"===a&&this.raiseRecoverable(b,"Can not use 'await' as identifier inside an async function");this.isKeyword(a)&&this.raise(b,"Unexpected keyword '"+a+"'"); -6>this.options.ecmaVersion&&-1!=this.input.slice(b,c).indexOf("\\")||(this.strict?this.reservedWordsStrict:this.reservedWords).test(a)&&this.raiseRecoverable(b,"The keyword '"+a+"' is reserved")};l.parseIdent=function(a,b){b=this.startNode();a&&"never"==this.options.allowReserved&&(a=!1);this.type===k.name?b.name=this.value:this.type.keyword?(b.name=this.type.keyword,"class"!==b.name&&"function"!==b.name||this.lastTokEnd===this.lastTokStart+1&&46===this.input.charCodeAt(this.lastTokStart)||this.context.pop()): -this.unexpected();this.next();this.finishNode(b,"Identifier");a||this.checkUnreserved(b);return b};l.parseYield=function(){this.yieldPos||(this.yieldPos=this.start);var a=this.startNode();this.next();this.type==k.semi||this.canInsertSemicolon()||this.type!=k.star&&!this.type.startsExpr?(a.delegate=!1,a.argument=null):(a.delegate=this.eat(k.star),a.argument=this.parseMaybeAssign());return this.finishNode(a,"YieldExpression")};l.parseAwait=function(){this.awaitPos||(this.awaitPos=this.start);var a= -this.startNode();this.next();a.argument=this.parseMaybeUnary(null,!0);return this.finishNode(a,"AwaitExpression")};l=Y.prototype;l.raise=function(a,b){var c=d(this.input,a);b+=" ("+c.line+":"+c.column+")";b=new SyntaxError(b);b.pos=a;b.loc=c;b.raisedAt=this.pos;throw b;};l.raiseRecoverable=l.raise;l.curPosition=function(){if(this.options.locations)return new K(this.curLine,this.pos-this.lineStart)};l=Y.prototype;var Da=Object.assign||function(a){for(var b=[],c=arguments.length-1;0=this.input.length)return this.finishToken(k.eof);if(a.override)return a.override(this); -this.readToken(this.fullCharCodeAtPos())};H.readToken=function(a){return p(a,6<=this.options.ecmaVersion)||92===a?this.readWord():this.getTokenFromCode(a)};H.fullCharCodeAtPos=function(){var a=this.input.charCodeAt(this.pos);if(55295>=a||57344<=a)return a;var b=this.input.charCodeAt(this.pos+1);return(a<<10)+b-56613888};H.skipBlockComment=function(){var a=this.options.onComment&&this.curPosition(),b=this.pos,c=this.input.indexOf("*/",this.pos+=2);-1===c&&this.raise(this.pos-2,"Unterminated comment"); -this.pos=c+2;if(this.options.locations){sa.lastIndex=b;for(var d;(d=sa.exec(this.input))&&d.indexa||5760<=a&&S.test(String.fromCharCode(a)))++this.pos;else break a}}};H.finishToken=function(a,b){this.end=this.pos;this.options.locations&&(this.endLoc=this.curPosition());var c=this.type;this.type=a;this.value=b;this.updateContext(c)};H.readToken_dot=function(){var a=this.input.charCodeAt(this.pos+1);if(48<=a&&57>=a)return this.readNumber(!0);var b=this.input.charCodeAt(this.pos+2);if(6<=this.options.ecmaVersion&&46===a&&46===b)return this.pos+=3,this.finishToken(k.ellipsis); -++this.pos;return this.finishToken(k.dot)};H.readToken_slash=function(){var a=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===a?this.finishOp(k.assign,2):this.finishOp(k.slash,1)};H.readToken_mult_modulo_exp=function(a){var b=this.input.charCodeAt(this.pos+1),c=1,d=42===a?k.star:k.modulo;7<=this.options.ecmaVersion&&42==a&&42===b&&(++c,d=k.starstar,b=this.input.charCodeAt(this.pos+2));return 61===b?this.finishOp(k.assign,c+1):this.finishOp(d,c)};H.readToken_pipe_amp= -function(a){var b=this.input.charCodeAt(this.pos+1);return b===a?this.finishOp(124===a?k.logicalOR:k.logicalAND,2):61===b?this.finishOp(k.assign,2):this.finishOp(124===a?k.bitwiseOR:k.bitwiseAND,1)};H.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(k.assign,2):this.finishOp(k.bitwiseXOR,1)};H.readToken_plus_min=function(a){var b=this.input.charCodeAt(this.pos+1);return b===a?45!=b||this.inModule||62!=this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!V.test(this.input.slice(this.lastTokEnd, -this.pos))?this.finishOp(k.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===b?this.finishOp(k.assign,2):this.finishOp(k.plusMin,1)};H.readToken_lt_gt=function(a){var b=this.input.charCodeAt(this.pos+1),c=1;if(b===a)return c=62===a&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+c)?this.finishOp(k.assign,c+1):this.finishOp(k.bitShift,c);if(33==b&&60==a&&!this.inModule&&45==this.input.charCodeAt(this.pos+2)&&45==this.input.charCodeAt(this.pos+ -3))return this.skipLineComment(4),this.skipSpace(),this.nextToken();61===b&&(c=2);return this.finishOp(k.relational,c)};H.readToken_eq_excl=function(a){var b=this.input.charCodeAt(this.pos+1);return 61===b?this.finishOp(k.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===a&&62===b&&6<=this.options.ecmaVersion?(this.pos+=2,this.finishToken(k.arrow)):this.finishOp(61===a?k.eq:k.prefix,1)};H.getTokenFromCode=function(a){switch(a){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(k.parenL); -case 41:return++this.pos,this.finishToken(k.parenR);case 59:return++this.pos,this.finishToken(k.semi);case 44:return++this.pos,this.finishToken(k.comma);case 91:return++this.pos,this.finishToken(k.bracketL);case 93:return++this.pos,this.finishToken(k.bracketR);case 123:return++this.pos,this.finishToken(k.braceL);case 125:return++this.pos,this.finishToken(k.braceR);case 58:return++this.pos,this.finishToken(k.colon);case 63:return++this.pos,this.finishToken(k.question);case 96:if(6>this.options.ecmaVersion)break; -++this.pos;return this.finishToken(k.backQuote);case 48:a=this.input.charCodeAt(this.pos+1);if(120===a||88===a)return this.readRadixNumber(16);if(6<=this.options.ecmaVersion){if(111===a||79===a)return this.readRadixNumber(8);if(98===a||66===a)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(a);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(a); -case 124:case 38:return this.readToken_pipe_amp(a);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(a);case 60:case 62:return this.readToken_lt_gt(a);case 61:case 33:return this.readToken_eq_excl(a);case 126:return this.finishOp(k.prefix,1)}this.raise(this.pos,"Unexpected character '"+y(a)+"'")};H.finishOp=function(a,b){var c=this.input.slice(this.pos,this.pos+b);this.pos+=b;return this.finishToken(a,c)};var xa=!!L("\uffff","u");H.readRegexp=function(){for(var a= -this,b,c,d=this.pos;;){a.pos>=a.input.length&&a.raise(d,"Unterminated regular expression");var m=a.input.charAt(a.pos);V.test(m)&&a.raise(d,"Unterminated regular expression");if(b)b=!1;else{if("["===m)c=!0;else if("]"===m&&c)c=!1;else if("/"===m&&!c)break;b="\\"===m}++a.pos}b=this.input.slice(d,this.pos);++this.pos;c=this.readWord1();m=b;var l="";if(c){var A=/^[gim]*$/;6<=this.options.ecmaVersion&&(A=/^[gimuy]*$/);A.test(c)||this.raise(d,"Invalid regular expression flag");0<=c.indexOf("u")&&(xa?l= -"u":(m=m.replace(/\\u\{([0-9a-fA-F]+)\}/g,function(b,c,A){c=Number("0x"+c);1114111=A?A-48:Infinity; -if(A>=a)break;++this.pos;d=d*a+A}return this.pos===c||null!=b&&this.pos-c!==b?null:d};H.readRadixNumber=function(a){this.pos+=2;var b=this.readInt(a);null==b&&this.raise(this.start+2,"Expected number in radix "+a);p(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");return this.finishToken(k.num,b)};H.readNumber=function(a){var b=this.pos,c=!1,d=48===this.input.charCodeAt(this.pos);a||null!==this.readInt(10)||this.raise(b,"Invalid number");d&&this.pos==b+1&&(d=!1); -a=this.input.charCodeAt(this.pos);46!==a||d||(++this.pos,this.readInt(10),c=!0,a=this.input.charCodeAt(this.pos));69!==a&&101!==a||d||(a=this.input.charCodeAt(++this.pos),43!==a&&45!==a||++this.pos,null===this.readInt(10)&&this.raise(b,"Invalid number"),c=!0);p(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");a=this.input.slice(b,this.pos);var m;c?m=parseFloat(a):d&&1!==a.length?this.strict?this.raise(b,"Invalid number"):m=/[89]/.test(a)?parseInt(a,10):parseInt(a, -8):m=parseInt(a,10);return this.finishToken(k.num,m)};H.readCodePoint=function(){if(123===this.input.charCodeAt(this.pos)){6>this.options.ecmaVersion&&this.unexpected();var a=++this.pos;var b=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;1114111=this.input.length&&this.raise(this.start,"Unterminated string constant"); -var d=this.input.charCodeAt(this.pos);if(d===a)break;92===d?(b+=this.input.slice(c,this.pos),b+=this.readEscapedChar(!1),c=this.pos):(t(d)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}b+=this.input.slice(c,this.pos++);return this.finishToken(k.string,b)};var pa={};H.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(u){if(u===pa)this.readInvalidTemplateToken();else throw u;}this.inTemplateElement=!1};H.invalidStringToken=function(a,b){if(this.inTemplateElement&& -9<=this.options.ecmaVersion)throw pa;this.raise(a,b)};H.readTmplToken=function(){for(var a="",b=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var c=this.input.charCodeAt(this.pos);if(96===c||36===c&&123===this.input.charCodeAt(this.pos+1)){if(this.pos===this.start&&(this.type===k.template||this.type===k.invalidTemplate)){if(36===c)return this.pos+=2,this.finishToken(k.dollarBraceL);++this.pos;return this.finishToken(k.backQuote)}a+=this.input.slice(b,this.pos); -return this.finishToken(k.template,a)}if(92===c)a+=this.input.slice(b,this.pos),a+=this.readEscapedChar(!0),b=this.pos;else if(t(c)){a+=this.input.slice(b,this.pos);++this.pos;switch(c){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:a+="\n";break;default:a+=String.fromCharCode(c)}this.options.locations&&(++this.curLine,this.lineStart=this.pos);b=this.pos}else++this.pos}};H.readInvalidTemplateToken=function(){for(;this.pos=b){b=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var c=parseInt(b,8);255=m?1:2;else if(92===m)this.containsEsc=!0,a+=this.input.slice(c,this.pos),c=this.pos,117!=this.input.charCodeAt(++this.pos)&&this.invalidStringToken(this.pos,"Expecting Unicode escape sequence \\uXXXX"),++this.pos,m=this.readCodePoint(), -(b?p:g)(m,d)||this.invalidStringToken(c,"Invalid Unicode escape"),a+=y(m),c=this.pos;else break;b=!1}return a+this.input.slice(c,this.pos)};H.readWord=function(){var a=this.readWord1(),b=k.name;this.keywords.test(a)&&(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword "+a),b=ja[a]);return this.finishToken(b,a)};h.version="5.2.1";h.parse=function(a,b){return(new Y(b,a)).parse()};h.parseExpressionAt=function(a,b,c){a=new Y(c,a,b);a.nextToken();return a.parseExpression()}; -h.tokenizer=function(a,b){return new Y(b,a)};h.addLooseExports=function(a,b,c){h.parse_dammit=a;h.LooseParser=b;h.pluginsLoose=c};h.Parser=Y;h.plugins=ra;h.defaultOptions=da;h.Position=K;h.SourceLocation=X;h.getLineInfo=d;h.Node=Oa;h.TokenType=U;h.tokTypes=k;h.keywordTypes=ja;h.TokContext=l;h.tokContexts=R;h.isIdentifierChar=g;h.isIdentifierStart=p;h.Token=ta;h.isNewLine=t;h.lineBreak=V;h.lineBreakG=sa;h.nonASCIIwhitespace=S;Object.defineProperty(h,"__esModule",{value:!0})});(function(h,c){c((h.acorn= -h.acorn||{},h.acorn.walk=h.acorn.walk||{}))})(this,function(h){function c(c){return"string"==typeof c?function(a){return a==c}:c?c:function(){return!0}}function p(c,a,b){b(c,a)}function g(c,a,b){}var C=function(c,a){this.node=c;this.state=a},v=Object.create||function(c){function a(){}a.prototype=c;return new a},t={};t.Program=t.BlockStatement=function(c,a,b){var d=0;for(c=c.body;d=b))g[q](c,d,l);if(!(null!=a&&c.start!=a||null!=b&&c.end!=b)&&m(q,c))throw new C(c,d);})(d,x)}catch(L){if(L instanceof C)return L;throw L;}};h.findNodeAround=function(d,a,b,m,g){b=c(b);m||(m=h.base);try{(function q(c,d,g){g=g||c.type;if(!(c.start>a||c.end=a&&b(g,c))throw new C(c,d);m[g](c,d,q)}})(d,g)}catch(x){if(x instanceof C)return x;throw x;}};h.findNodeBefore=function(d,a,b,m,g){b=c(b);m||(m=h.base);var D;(function l(c,d,g){c.start>a||(g=g||c.type,c.end<=a&&(!D||D.node.enda&&8=b;b++)if(this.lookAhead(b).type==a){for(a=0;a= -this.input.length||this.indentationAfter(this.nextLineStart)=this.curLineStart;--a){var b=this.input.charCodeAt(a);if(9!==b&&32!==b)return!1}return!0};t.prototype.extend=function(a,b){this[a]=b(this[a])};t.prototype.loadPlugins=function(a){for(var b in a){var c=v[b];if(!c)throw Error("Plugin '"+b+"' not found");c(this,a[b])}};t.prototype.parse=function(){this.next();return this.parseTopLevel()};var d=t.prototype;d.next=function(){this.last= -this.tok;this.tok=this.ahead.length?this.ahead.shift():this.readToken();if(this.tok.start>=this.nextLineStart){for(;this.tok.start>=this.nextLineStart;)this.curLineStart=this.nextLineStart,this.nextLineStart=this.lineEnd(this.curLineStart)+1;this.curIndent=this.indentationAfter(this.curLineStart)}};d.readToken=function(){for(;;)try{return this.toks.next(),this.toks.type===c.tokTypes.dot&&"."===this.input.substr(this.toks.end,1)&&6<=this.options.ecmaVersion&&(this.toks.end++,this.toks.type=c.tokTypes.ellipsis), -new c.Token(this.toks)}catch(D){if(!(D instanceof SyntaxError))throw D;var a=D.message,b=D.raisedAt,d=!0;if(/unterminated/i.test(a))if(b=this.lineEnd(D.pos+1),/string/.test(a))d={start:D.pos,end:b,type:c.tokTypes.string,value:this.input.slice(D.pos+1,b)};else if(/regular expr/i.test(a)){d=this.input.slice(D.pos,b);try{d=new RegExp(d)}catch(x){}d={start:D.pos,end:b,type:c.tokTypes.regexp,value:d}}else d=/template/.test(a)?{start:D.pos,end:b,type:c.tokTypes.template,value:this.input.slice(D.pos,b)}: -!1;else if(/invalid (unicode|regexp|number)|expecting unicode|octal literal|is reserved|directly after number|expected number in radix/i.test(a))for(;b]/.test(b)||/[enwfd]/.test(b)&&/\b(keywords|case|else|return|throw|new|in|(instance|type)of|delete|void)$/.test(this.input.slice(a-10,a));if(this.options.locations){this.toks.curLine=1;this.toks.lineStart=c.lineBreakG.lastIndex= -0;for(var d;(d=c.lineBreakG.exec(this.input))&&d.indexthis.ahead.length;)this.ahead.push(this.readToken());return this.ahead[a-1]};d=t.prototype;d.parseTopLevel=function(){var a=this.startNodeAt(this.options.locations?[0,c.getLineInfo(this.input,0)]:0);for(a.body=[];this.tok.type!==c.tokTypes.eof;)a.body.push(this.parseStatement());this.toks.adaptDirectivePrologue(a.body);this.last=this.tok;6<=this.options.ecmaVersion&& -(a.sourceType=this.options.sourceType);return this.finishNode(a,"Program")};d.parseStatement=function(){var a=this.tok.type,b=this.startNode();if(this.toks.isLet()){a=c.tokTypes._var;var d="let"}switch(a){case c.tokTypes._break:case c.tokTypes._continue:this.next();var h=a===c.tokTypes._break;this.semicolon()||this.canInsertSemicolon()?b.label=null:(b.label=this.tok.type===c.tokTypes.name?this.parseIdent():null,this.semicolon());return this.finishNode(b,h?"BreakStatement":"ContinueStatement");case c.tokTypes._debugger:return this.next(), -this.semicolon(),this.finishNode(b,"DebuggerStatement");case c.tokTypes._do:return this.next(),b.body=this.parseStatement(),b.test=this.eat(c.tokTypes._while)?this.parseParenExpression():this.dummyIdent(),this.semicolon(),this.finishNode(b,"DoWhileStatement");case c.tokTypes._for:this.next();this.pushCx();this.expect(c.tokTypes.parenL);if(this.tok.type===c.tokTypes.semi)return this.parseFor(b,null);if((h=this.toks.isLet())||this.tok.type===c.tokTypes._var||this.tok.type===c.tokTypes._const)return h= -this.parseVar(!0,h?"let":this.tok.value),1!==h.declarations.length||this.tok.type!==c.tokTypes._in&&!this.isContextual("of")?this.parseFor(b,h):this.parseForIn(b,h);h=this.parseExpression(!0);return this.tok.type===c.tokTypes._in||this.isContextual("of")?this.parseForIn(b,this.toAssignable(h)):this.parseFor(b,h);case c.tokTypes._function:return this.next(),this.parseFunction(b,!0);case c.tokTypes._if:return this.next(),b.test=this.parseParenExpression(),b.consequent=this.parseStatement(),b.alternate= -this.eat(c.tokTypes._else)?this.parseStatement():null,this.finishNode(b,"IfStatement");case c.tokTypes._return:return this.next(),this.eat(c.tokTypes.semi)||this.canInsertSemicolon()?b.argument=null:(b.argument=this.parseExpression(),this.semicolon()),this.finishNode(b,"ReturnStatement");case c.tokTypes._switch:a=this.curIndent;d=this.curLineStart;this.next();b.discriminant=this.parseParenExpression();b.cases=[];this.pushCx();for(this.expect(c.tokTypes.braceL);!this.closes(c.tokTypes.braceR,a,d,!0);)if(this.tok.type=== -c.tokTypes._case||this.tok.type===c.tokTypes._default){var x=this.tok.type===c.tokTypes._case;h&&this.finishNode(h,"SwitchCase");b.cases.push(h=this.startNode());h.consequent=[];this.next();h.test=x?this.parseExpression():null;this.expect(c.tokTypes.colon)}else h||(b.cases.push(h=this.startNode()),h.consequent=[],h.test=null),h.consequent.push(this.parseStatement());h&&this.finishNode(h,"SwitchCase");this.popCx();this.eat(c.tokTypes.braceR);return this.finishNode(b,"SwitchStatement");case c.tokTypes._throw:return this.next(), -b.argument=this.parseExpression(),this.semicolon(),this.finishNode(b,"ThrowStatement");case c.tokTypes._try:return this.next(),b.block=this.parseBlock(),b.handler=null,this.tok.type===c.tokTypes._catch&&(h=this.startNode(),this.next(),this.expect(c.tokTypes.parenL),h.param=this.toAssignable(this.parseExprAtom(),!0),this.expect(c.tokTypes.parenR),h.body=this.parseBlock(),b.handler=this.finishNode(h,"CatchClause")),b.finalizer=this.eat(c.tokTypes._finally)?this.parseBlock():null,b.handler||b.finalizer? -this.finishNode(b,"TryStatement"):b.block;case c.tokTypes._var:case c.tokTypes._const:return this.parseVar(!1,d||this.tok.value);case c.tokTypes._while:return this.next(),b.test=this.parseParenExpression(),b.body=this.parseStatement(),this.finishNode(b,"WhileStatement");case c.tokTypes._with:return this.next(),b.object=this.parseParenExpression(),b.body=this.parseStatement(),this.finishNode(b,"WithStatement");case c.tokTypes.braceL:return this.parseBlock();case c.tokTypes.semi:return this.next(), -this.finishNode(b,"EmptyStatement");case c.tokTypes._class:return this.parseClass(!0);case c.tokTypes._import:return this.parseImport();case c.tokTypes._export:return this.parseExport();default:if(this.toks.isAsyncFunction())return this.next(),this.next(),this.parseFunction(b,!0,!0);h=this.parseExpression();if(g(h))return this.next(),this.tok.type===c.tokTypes.eof?this.finishNode(b,"EmptyStatement"):this.parseStatement();if(a===c.tokTypes.name&&"Identifier"===h.type&&this.eat(c.tokTypes.colon))return b.body= -this.parseStatement(),b.label=h,this.finishNode(b,"LabeledStatement");b.expression=h;this.semicolon();return this.finishNode(b,"ExpressionStatement")}};d.parseBlock=function(){var a=this.startNode();this.pushCx();this.expect(c.tokTypes.braceL);var b=this.curIndent,d=this.curLineStart;for(a.body=[];!this.closes(c.tokTypes.braceR,b,d,!0);)a.body.push(this.parseStatement());this.popCx();this.eat(c.tokTypes.braceR);return this.finishNode(a,"BlockStatement")};d.parseFor=function(a,b){a.init=b;a.test=a.update= -null;this.eat(c.tokTypes.semi)&&this.tok.type!==c.tokTypes.semi&&(a.test=this.parseExpression());this.eat(c.tokTypes.semi)&&this.tok.type!==c.tokTypes.parenR&&(a.update=this.parseExpression());this.popCx();this.expect(c.tokTypes.parenR);a.body=this.parseStatement();return this.finishNode(a,"ForStatement")};d.parseForIn=function(a,b){var d=this.tok.type===c.tokTypes._in?"ForInStatement":"ForOfStatement";this.next();a.left=b;a.right=this.parseExpression();this.popCx();this.expect(c.tokTypes.parenR); -a.body=this.parseStatement();return this.finishNode(a,d)};d.parseVar=function(a,b){var d=this.startNode();d.kind=b;this.next();d.declarations=[];do b=this.startNode(),b.id=6<=this.options.ecmaVersion?this.toAssignable(this.parseExprAtom(),!0):this.parseIdent(),b.init=this.eat(c.tokTypes.eq)?this.parseMaybeAssign(a):null,d.declarations.push(this.finishNode(b,"VariableDeclarator"));while(this.eat(c.tokTypes.comma));d.declarations.length||(b=this.startNode(),b.id=this.dummyIdent(),d.declarations.push(this.finishNode(b, -"VariableDeclarator")));a||this.semicolon();return this.finishNode(d,"VariableDeclaration")};d.parseClass=function(a){var b=this.startNode();this.next();b.id=this.tok.type===c.tokTypes.name?this.parseIdent():!0===a?this.dummyIdent():null;b.superClass=this.eat(c.tokTypes._extends)?this.parseExpression():null;b.body=this.startNode();b.body.body=[];this.pushCx();var d=this.curIndent+1,h=this.curLineStart;this.eat(c.tokTypes.braceL);this.curIndent+1h&&(h=this.curLineStart);for(;!this.closes(c.tokTypes.braceR,b+(this.curLineStart<=h?1:0),d);){var x=this.startNode();if(this.eat(c.tokTypes.star))x.local=this.eatContextual("as")?this.parseIdent():this.dummyIdent(),this.finishNode(x,"ImportNamespaceSpecifier");else{if(this.isContextual("from"))break; -x.imported=this.parseIdent();if(g(x.imported))break;x.local=this.eatContextual("as")?this.parseIdent():x.imported;this.finishNode(x,"ImportSpecifier")}a.push(x);this.eat(c.tokTypes.comma)}this.eat(c.tokTypes.braceR);this.popCx()}return a};d.parseExportSpecifierList=function(){var a=[],b=this.curIndent,d=this.curLineStart,h=this.nextLineStart;this.pushCx();this.eat(c.tokTypes.braceL);this.curLineStart>h&&(h=this.curLineStart);for(;!this.closes(c.tokTypes.braceR,b+(this.curLineStart<=h?1:0),d)&&!this.isContextual("from");){var x= -this.startNode();x.local=this.parseIdent();if(g(x.local))break;x.exported=this.eatContextual("as")?this.parseIdent():x.local;this.finishNode(x,"ExportSpecifier");a.push(x);this.eat(c.tokTypes.comma)}this.eat(c.tokTypes.braceR);this.popCx();return a};d=t.prototype;d.checkLVal=function(a){if(!a)return a;switch(a.type){case "Identifier":case "MemberExpression":return a;case "ParenthesizedExpression":return a.expression=this.checkLVal(a.expression),a;default:return this.dummyIdent()}};d.parseExpression= -function(a){var b=this.storeCurrentPos(),d=this.parseMaybeAssign(a);if(this.tok.type===c.tokTypes.comma){b=this.startNodeAt(b);for(b.expressions=[d];this.eat(c.tokTypes.comma);)b.expressions.push(this.parseMaybeAssign(a));return this.finishNode(b,"SequenceExpression")}return d};d.parseParenExpression=function(){this.pushCx();this.expect(c.tokTypes.parenL);var a=this.parseExpression();this.popCx();this.expect(c.tokTypes.parenR);return a};d.parseMaybeAssign=function(a){if(this.toks.isContextual("yield"))return a= -this.startNode(),this.next(),this.semicolon()||this.canInsertSemicolon()||this.tok.type!=c.tokTypes.star&&!this.tok.type.startsExpr?(a.delegate=!1,a.argument=null):(a.delegate=this.eat(c.tokTypes.star),a.argument=this.parseMaybeAssign()),this.finishNode(a,"YieldExpression");var b=this.storeCurrentPos(),d=this.parseMaybeConditional(a);return this.tok.type.isAssign?(b=this.startNodeAt(b),b.operator=this.tok.value,b.left=this.tok.type===c.tokTypes.eq?this.toAssignable(d):this.checkLVal(d),this.next(), -b.right=this.parseMaybeAssign(a),this.finishNode(b,"AssignmentExpression")):d};d.parseMaybeConditional=function(a){var b=this.storeCurrentPos(),d=this.parseExprOps(a);return this.eat(c.tokTypes.question)?(b=this.startNodeAt(b),b.test=d,b.consequent=this.parseMaybeAssign(),b.alternate=this.expect(c.tokTypes.colon)?this.parseMaybeAssign(a):this.dummyIdent(),this.finishNode(b,"ConditionalExpression")):d};d.parseExprOps=function(a){var b=this.storeCurrentPos(),c=this.curIndent,d=this.curLineStart;return this.parseExprOp(this.parseMaybeUnary(!1), -b,-1,a,c,d)};d.parseExprOp=function(a,b,d,g,h,L){if(this.curLineStart!=L&&this.curIndentd){var D=this.startNodeAt(b);D.left=a;D.operator=this.tok.value;this.next();this.curLineStart!=L&&this.curIndentthis.options.ecmaVersion)return this.dummyIdent();if("ObjectExpression"==a.type){a.type="ObjectPattern";for(var c=0,d=a.properties;c=g.end||this.input.slice(g.end).match(C)?delete b.__maybeStaticAsyncGetter:"set"===b.kind||"set"===g.name?this.raise(g.start,"'set (value)' cannot be be async"):(this.__isAsyncProp=!0,g=a.apply(this,arguments),"Identifier"===g.type&&"set"===g.name&&this.raise(g.start, -"'set (value)' cannot be be async"));return g}});h.extend("parseClassMethod",function(a){return function(b,c,d){var g=a.apply(this,arguments);c.__maybeStaticAsyncGetter&&(delete c.__maybeStaticAsyncGetter,"get"!==c.key.name&&(c.kind="get"));return g}});h.extend("parseFunctionBody",function(a){return function(b,c){var d=this.inAsync;this.__isAsyncProp&&(this.inAsync=b.async=!0,delete this.__isAsyncProp);var g=a.apply(this,arguments);this.inAsync=d;return g}})};h.plugins.asyncawait=p})(this.acorn); -(function(h){var c={exports:{}};"use strict";c.exports=function(c){function g(c,a){var b=this.startNode(),d=!0,g={};b.properties=[];for(this.next();!this.eat(h.braceR);){if(d)d=!1;else if(this.expect(h.comma),this.afterTrailingComma(h.braceR))break;var x=this.startNode(),L;if(6<=this.options.ecmaVersion){if(this.type===h.ellipsis){c?(this.next(),x.argument=this.parseIdent(),this.finishNode(x,"RestElement")):x=this.parseSpread(a);b.properties.push(x);this.type===h.comma&&(c?this.raise(this.start,"Comma is not permitted after the rest element"): -a&&0>a.trailingComma&&(a.trailingComma=this.start));continue}x.method=!1;x.shorthand=!1;if(c||a){var y=this.start;var t=this.startLoc}c||(L=this.eat(h.star))}this.parsePropertyName(x);if(!c&&8<=this.options.ecmaVersion&&!L&&this.isAsyncProp(x)){var q=!0;this.parsePropertyName(x,a)}else q=!1;this.parsePropertyValue(x,c,L,q,y,t,a);c||this.checkPropClash(x,g);b.properties.push(this.finishNode(x,"Property"))}return this.finishNode(b,c?"ObjectPattern":"ObjectExpression")}if("5"!==c.version.substr(0,1))throw Error("Unsupported acorn version "+ -c.version+", please use acorn 5");var h=c.tokTypes,p=c.Parser.prototype,t=function(c){return function(a,b,d){if("ObjectPattern"==a.type)for(var g=$jscomp.makeIterator(a.properties),h=g.next();!h.done;h=g.next())this.checkLVal(h.value,b,d);else return"Property"===a.type?this.checkLVal(a.value,b,d):c.apply(this,arguments)}};c.plugins.objectSpread=function(c){p.parseObj=g;c.extend("checkLVal",t);c.extend("toAssignable",function(a){return function(b,c){if(6<=this.options.ecmaVersion&&b){if("ObjectExpression"== -b.type){b.type="ObjectPattern";for(var d=$jscomp.makeIterator(b.properties),g=d.next();!g.done;g=d.next())this.toAssignable(g.value,c);return b}if("Property"===b.type)return"init"!==b.kind&&this.raise(b.key.start,"Object pattern can't contain getter or setter"),this.toAssignable(b.value,c);if("SpreadElement"===b.type)return b.type="RestElement",this.toAssignable(b.argument,c)}return a.apply(this,arguments)}});c.extend("checkPatternExport",function(a){return function(b,c){if("ObjectPattern"==c.type)for(var d= -$jscomp.makeIterator(c.properties),g=d.next();!g.done;g=d.next())this.checkPatternExport(b,g.value);else{if("Property"===c.type)return this.checkPatternExport(b,c.value);if("RestElement"===c.type)return this.checkPatternExport(b,c.argument);a.apply(this,arguments)}}})};return c};c.exports(h)})(this.acorn);(function(h){var c={exports:{}};"use strict";var p={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:"\u00a0",iexcl:"\u00a1",cent:"\u00a2",pound:"\u00a3",curren:"\u00a4",yen:"\u00a5",brvbar:"\u00a6", -sect:"\u00a7",uml:"\u00a8",copy:"\u00a9",ordf:"\u00aa",laquo:"\u00ab",not:"\u00ac",shy:"\u00ad",reg:"\u00ae",macr:"\u00af",deg:"\u00b0",plusmn:"\u00b1",sup2:"\u00b2",sup3:"\u00b3",acute:"\u00b4",micro:"\u00b5",para:"\u00b6",middot:"\u00b7",cedil:"\u00b8",sup1:"\u00b9",ordm:"\u00ba",raquo:"\u00bb",frac14:"\u00bc",frac12:"\u00bd",frac34:"\u00be",iquest:"\u00bf",Agrave:"\u00c0",Aacute:"\u00c1",Acirc:"\u00c2",Atilde:"\u00c3",Auml:"\u00c4",Aring:"\u00c5",AElig:"\u00c6",Ccedil:"\u00c7",Egrave:"\u00c8", -Eacute:"\u00c9",Ecirc:"\u00ca",Euml:"\u00cb",Igrave:"\u00cc",Iacute:"\u00cd",Icirc:"\u00ce",Iuml:"\u00cf",ETH:"\u00d0",Ntilde:"\u00d1",Ograve:"\u00d2",Oacute:"\u00d3",Ocirc:"\u00d4",Otilde:"\u00d5",Ouml:"\u00d6",times:"\u00d7",Oslash:"\u00d8",Ugrave:"\u00d9",Uacute:"\u00da",Ucirc:"\u00db",Uuml:"\u00dc",Yacute:"\u00dd",THORN:"\u00de",szlig:"\u00df",agrave:"\u00e0",aacute:"\u00e1",acirc:"\u00e2",atilde:"\u00e3",auml:"\u00e4",aring:"\u00e5",aelig:"\u00e6",ccedil:"\u00e7",egrave:"\u00e8",eacute:"\u00e9", -ecirc:"\u00ea",euml:"\u00eb",igrave:"\u00ec",iacute:"\u00ed",icirc:"\u00ee",iuml:"\u00ef",eth:"\u00f0",ntilde:"\u00f1",ograve:"\u00f2",oacute:"\u00f3",ocirc:"\u00f4",otilde:"\u00f5",ouml:"\u00f6",divide:"\u00f7",oslash:"\u00f8",ugrave:"\u00f9",uacute:"\u00fa",ucirc:"\u00fb",uuml:"\u00fc",yacute:"\u00fd",thorn:"\u00fe",yuml:"\u00ff",OElig:"\u0152",oelig:"\u0153",Scaron:"\u0160",scaron:"\u0161",Yuml:"\u0178",fnof:"\u0192",circ:"\u02c6",tilde:"\u02dc",Alpha:"\u0391",Beta:"\u0392",Gamma:"\u0393",Delta:"\u0394", -Epsilon:"\u0395",Zeta:"\u0396",Eta:"\u0397",Theta:"\u0398",Iota:"\u0399",Kappa:"\u039a",Lambda:"\u039b",Mu:"\u039c",Nu:"\u039d",Xi:"\u039e",Omicron:"\u039f",Pi:"\u03a0",Rho:"\u03a1",Sigma:"\u03a3",Tau:"\u03a4",Upsilon:"\u03a5",Phi:"\u03a6",Chi:"\u03a7",Psi:"\u03a8",Omega:"\u03a9",alpha:"\u03b1",beta:"\u03b2",gamma:"\u03b3",delta:"\u03b4",epsilon:"\u03b5",zeta:"\u03b6",eta:"\u03b7",theta:"\u03b8",iota:"\u03b9",kappa:"\u03ba",lambda:"\u03bb",mu:"\u03bc",nu:"\u03bd",xi:"\u03be",omicron:"\u03bf",pi:"\u03c0", -rho:"\u03c1",sigmaf:"\u03c2",sigma:"\u03c3",tau:"\u03c4",upsilon:"\u03c5",phi:"\u03c6",chi:"\u03c7",psi:"\u03c8",omega:"\u03c9",thetasym:"\u03d1",upsih:"\u03d2",piv:"\u03d6",ensp:"\u2002",emsp:"\u2003",thinsp:"\u2009",zwnj:"\u200c",zwj:"\u200d",lrm:"\u200e",rlm:"\u200f",ndash:"\u2013",mdash:"\u2014",lsquo:"\u2018",rsquo:"\u2019",sbquo:"\u201a",ldquo:"\u201c",rdquo:"\u201d",bdquo:"\u201e",dagger:"\u2020",Dagger:"\u2021",bull:"\u2022",hellip:"\u2026",permil:"\u2030",prime:"\u2032",Prime:"\u2033",lsaquo:"\u2039", -rsaquo:"\u203a",oline:"\u203e",frasl:"\u2044",euro:"\u20ac",image:"\u2111",weierp:"\u2118",real:"\u211c",trade:"\u2122",alefsym:"\u2135",larr:"\u2190",uarr:"\u2191",rarr:"\u2192",darr:"\u2193",harr:"\u2194",crarr:"\u21b5",lArr:"\u21d0",uArr:"\u21d1",rArr:"\u21d2",dArr:"\u21d3",hArr:"\u21d4",forall:"\u2200",part:"\u2202",exist:"\u2203",empty:"\u2205",nabla:"\u2207",isin:"\u2208",notin:"\u2209",ni:"\u220b",prod:"\u220f",sum:"\u2211",minus:"\u2212",lowast:"\u2217",radic:"\u221a",prop:"\u221d",infin:"\u221e", -ang:"\u2220",and:"\u2227",or:"\u2228",cap:"\u2229",cup:"\u222a","int":"\u222b",there4:"\u2234",sim:"\u223c",cong:"\u2245",asymp:"\u2248",ne:"\u2260",equiv:"\u2261",le:"\u2264",ge:"\u2265",sub:"\u2282",sup:"\u2283",nsub:"\u2284",sube:"\u2286",supe:"\u2287",oplus:"\u2295",otimes:"\u2297",perp:"\u22a5",sdot:"\u22c5",lceil:"\u2308",rceil:"\u2309",lfloor:"\u230a",rfloor:"\u230b",lang:"\u2329",rang:"\u232a",loz:"\u25ca",spades:"\u2660",clubs:"\u2663",hearts:"\u2665",diams:"\u2666"},g=/^[\da-fA-F]+$/,C= -/^\d+$/;c.exports=function(c){function h(a){if(!a)return a;if("JSXIdentifier"===a.type)return a.name;if("JSXNamespacedName"===a.type)return a.namespace.name+":"+a.name.name;if("JSXMemberExpression"===a.type)return h(a.object)+"."+h(a.property)}var d=c.tokTypes,a=c.tokContexts;a.j_oTag=new c.TokContext("...",!0,!0);d.jsxName=new c.TokenType("jsxName");d.jsxText=new c.TokenType("jsxText",{beforeExpr:!0});d.jsxTagStart= -new c.TokenType("jsxTagStart");d.jsxTagEnd=new c.TokenType("jsxTagEnd");d.jsxTagStart.updateContext=function(){this.context.push(a.j_expr);this.context.push(a.j_oTag);this.exprAllowed=!1};d.jsxTagEnd.updateContext=function(b){var c=this.context.pop();c===a.j_oTag&&b===d.slash||c===a.j_cTag?(this.context.pop(),this.exprAllowed=this.curContext()===a.j_expr):this.exprAllowed=!0};var b=c.Parser.prototype;b.jsx_readToken=function(){for(var a="",b=this.pos;;){this.pos>=this.input.length&&this.raise(this.start, -"Unterminated JSX contents");var g=this.input.charCodeAt(this.pos);switch(g){case 60:case 123:if(this.pos===this.start)return 60===g&&this.exprAllowed?(++this.pos,this.finishToken(d.jsxTagStart)):this.getTokenFromCode(g);a+=this.input.slice(b,this.pos);return this.finishToken(d.jsxText,a);case 38:a+=this.input.slice(b,this.pos);a+=this.jsx_readEntity();b=this.pos;break;default:c.isNewLine(g)?(a+=this.input.slice(b,this.pos),a+=this.jsx_readNewLine(!0),b=this.pos):++this.pos}}};b.jsx_readNewLine=function(a){var b= -this.input.charCodeAt(this.pos);++this.pos;13===b&&10===this.input.charCodeAt(this.pos)?(++this.pos,a=a?"\n":"\r\n"):a=String.fromCharCode(b);this.options.locations&&(++this.curLine,this.lineStart=this.pos);return a};b.jsx_readString=function(a){for(var b="",g=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var h=this.input.charCodeAt(this.pos);if(h===a)break;38===h?(b+=this.input.slice(g,this.pos),b+=this.jsx_readEntity(),g=this.pos):c.isNewLine(h)? -(b+=this.input.slice(g,this.pos),b+=this.jsx_readNewLine(!1),g=this.pos):++this.pos}b+=this.input.slice(g,this.pos++);return this.finishToken(d.string,b)};b.jsx_readEntity=function(){var a="",b=0,c,d=this.input[this.pos];"&"!==d&&this.raise(this.pos,"Entity must start with an ampersand");for(var h=++this.pos;this.posb++;){d=this.input[this.pos++];if(";"===d){"#"===a[0]?"x"===a[1]?(a=a.substr(2),g.test(a)&&(c=String.fromCharCode(parseInt(a,16)))):(a=a.substr(1),C.test(a)&&(c= -String.fromCharCode(parseInt(a,10)))):c=p[a];break}a+=d}return c?c:(this.pos=h,"&")};b.jsx_readWord=function(){var a=this.pos;do var b=this.input.charCodeAt(++this.pos);while(c.isIdentifierChar(b)||45===b);return this.finishToken(d.jsxName,this.input.slice(a,this.pos))};b.jsx_parseIdentifier=function(){var a=this.startNode();this.type===d.jsxName?a.name=this.value:this.type.keyword?a.name=this.type.keyword:this.unexpected();this.next();return this.finishNode(a,"JSXIdentifier")};b.jsx_parseNamespacedName= -function(){var a=this.start,b=this.startLoc,c=this.jsx_parseIdentifier();if(!this.options.plugins.jsx.allowNamespaces||!this.eat(d.colon))return c;a=this.startNodeAt(a,b);a.namespace=c;a.name=this.jsx_parseIdentifier();return this.finishNode(a,"JSXNamespacedName")};b.jsx_parseElementName=function(){if(this.type===d.jsxTagEnd)return"";var a=this.start,b=this.startLoc,c=this.jsx_parseNamespacedName();for(this.type!==d.dot||"JSXNamespacedName"!==c.type||this.options.plugins.jsx.allowNamespacedObjects|| -this.unexpected();this.eat(d.dot);){var g=this.startNodeAt(a,b);g.object=c;g.property=this.jsx_parseIdentifier();c=this.finishNode(g,"JSXMemberExpression")}return c};b.jsx_parseAttributeValue=function(){switch(this.type){case d.braceL:var a=this.jsx_parseExpressionContainer();"JSXEmptyExpression"===a.expression.type&&this.raise(a.start,"JSX attributes must only be assigned a non-empty expression");return a;case d.jsxTagStart:case d.string:return this.parseExprAtom();default:this.raise(this.start, -"JSX value should be either an expression or a quoted JSX text")}};b.jsx_parseEmptyExpression=function(){var a=this.startNodeAt(this.lastTokEnd,this.lastTokEndLoc);return this.finishNodeAt(a,"JSXEmptyExpression",this.start,this.startLoc)};b.jsx_parseExpressionContainer=function(){var a=this.startNode();this.next();a.expression=this.type===d.braceR?this.jsx_parseEmptyExpression():this.parseExpression();this.expect(d.braceR);return this.finishNode(a,"JSXExpressionContainer")};b.jsx_parseAttribute=function(){var a= -this.startNode();if(this.eat(d.braceL))return this.expect(d.ellipsis),a.argument=this.parseMaybeAssign(),this.expect(d.braceR),this.finishNode(a,"JSXSpreadAttribute");a.name=this.jsx_parseNamespacedName();a.value=this.eat(d.eq)?this.jsx_parseAttributeValue():null;return this.finishNode(a,"JSXAttribute")};b.jsx_parseOpeningElementAt=function(a,b){a=this.startNodeAt(a,b);a.attributes=[];for(a.name=this.jsx_parseElementName();this.type!==d.slash&&this.type!==d.jsxTagEnd;)a.attributes.push(this.jsx_parseAttribute()); -a.selfClosing=this.eat(d.slash);this.expect(d.jsxTagEnd);return this.finishNode(a,"JSXOpeningElement")};b.jsx_parseClosingElementAt=function(a,b){a=this.startNodeAt(a,b);a.name=this.jsx_parseElementName();this.expect(d.jsxTagEnd);return this.finishNode(a,"JSXClosingElement")};b.jsx_parseElementAt=function(a,b){var c=this.startNodeAt(a,b),g=[],m=this.jsx_parseOpeningElementAt(a,b);a=null;if(!m.selfClosing){a:for(;;)switch(this.type){case d.jsxTagStart:a=this.start;b=this.startLoc;this.next();if(this.eat(d.slash)){a= -this.jsx_parseClosingElementAt(a,b);break a}g.push(this.jsx_parseElementAt(a,b));break;case d.jsxText:g.push(this.parseExprAtom());break;case d.braceL:g.push(this.jsx_parseExpressionContainer());break;default:this.unexpected()}h(a.name)!==h(m.name)&&this.raise(a.start,"Expected corresponding JSX closing tag for <"+h(m.name)+">")}c.openingElement=m;c.closingElement=a;c.children=g;this.type===d.relational&&"<"===this.value&&this.raise(this.start,"Adjacent JSX elements must be wrapped in an enclosing tag"); -return this.finishNode(c,m.name?"JSXElement":"JSXFragment")};b.jsx_parseText=function(a){a=this.parseLiteral(a);a.type="JSXText";return a};b.jsx_parseElement=function(){var a=this.start,b=this.startLoc;this.next();return this.jsx_parseElementAt(a,b)};c.plugins.jsx=function(b,g){g&&("object"!==typeof g&&(g={}),b.options.plugins.jsx={allowNamespaces:!1!==g.allowNamespaces,allowNamespacedObjects:!!g.allowNamespacedObjects},b.extend("parseExprAtom",function(a){return function(b){return this.type===d.jsxText? -this.jsx_parseText(this.value):this.type===d.jsxTagStart?this.jsx_parseElement():a.call(this,b)}}),b.extend("readToken",function(b){return function(g){var h=this.curContext();if(h===a.j_expr)return this.jsx_readToken();if(h===a.j_oTag||h===a.j_cTag){if(c.isIdentifierStart(g))return this.jsx_readWord();if(62==g)return++this.pos,this.finishToken(d.jsxTagEnd);if((34===g||39===g)&&h==a.j_oTag)return this.jsx_readString(g)}return 60===g&&this.exprAllowed&&33!==this.input.charCodeAt(this.pos+1)?(++this.pos, -this.finishToken(d.jsxTagStart)):b.call(this,g)}}),b.extend("updateContext",function(b){return function(c){if(this.type==d.braceL){var g=this.curContext();g==a.j_oTag?this.context.push(a.b_expr):g==a.j_expr?this.context.push(a.b_tmpl):b.call(this,c);this.exprAllowed=!0}else if(this.type===d.slash&&c===d.jsxTagStart)this.context.length-=2,this.context.push(a.j_cTag),this.exprAllowed=!1;else return b.call(this,c)}}))};return c};c.exports(h)})(this.acorn);return this.acorn})();return h()}(),escodegenbrowser= -function(){var h=prepareGlobal("https://admin.typeshift.io/lively.ast/dist/escodegen.browser.js");(function(h){function c(g,h){if({}.hasOwnProperty.call(c.cache,g))return c.cache[g];var p=c.resolve(g);if(!p)throw Error("Failed to resolve module "+g);var t={id:g,require:c,filename:g,exports:{},loaded:!1,parent:h,children:[]};h&&h.children.push(t);h=g.slice(0,g.lastIndexOf("/")+1);c.cache[g]=t.exports;p.call(t.exports,t,t.exports,h,g);t.loaded=!0;return c.cache[g]=t.exports}c.modules={};c.cache={}; -c.resolve=function(g){return{}.hasOwnProperty.call(c.modules,g)?c.modules[g]:void 0};c.define=function(g,h){c.modules[g]=h};var p=function(){var c="/";return{title:"browser",version:"v9.11.2",browser:!0,env:{},argv:[],nextTick:h.setImmediate||function(c){setTimeout(c,0)},cwd:function(){return c},chdir:function(g){c=g}}}();c.define("/tools/entry-point.js",function(g,p,v,t){h.escodegen=c("/escodegen.js",g);escodegen.browser=!0});c.define("/escodegen.js",function(g,p,v,t){(function(){function d(){return{indent:null, -base:null,parse:null,comment:!1,format:{indent:{style:" ",base:0,adjustMultilineComment:!1},newline:"\n",space:" ",json:!1,renumber:!1,hexadecimal:!1,quotes:"single",escapeless:!1,compact:!1,parentheses:!0,semicolons:!0,safeConcatenation:!1,preserveBlankLines:!1},moz:{comprehensionExpressionStartsWithAssignment:!1,starlessGenerator:!1},sourceMap:null,sourceMapRoot:null,sourceMapWithCode:!1,directive:!1,raw:!0,verbatim:null,sourceCode:null}}function a(a,b){var c="";for(b|=0;0>>=1,a+=a)b&1&& -(c+=a);return c}function b(a){var b=a.length;return b&&W.code.isLineTerminator(a.charCodeAt(b-1))}function m(a,b){for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}function D(a,b){function c(a){return"object"===typeof a&&a instanceof Object&&!(a instanceof RegExp)}var d;for(d in b)if(b.hasOwnProperty(d)){var A=b[d];c(A)?c(a[d])?D(a[d],A):a[d]=D({},A):a[d]=A}return a}function x(a,b){return 8232===(a&-2)?(b?"u":"\\u")+(8232===a?"2028":"2029"):10===a||13===a?(b?"":"\\")+(10===a?"n":"r"):String.fromCharCode(a)} -function t(a,b){if(8===a)return"\\b";if(12===a)return"\\f";if(9===a)return"\\t";var c=a.toString(16).toUpperCase();return X||255A&&(g=A)}"undefined"!==typeof c?(l=E,"*"===a[1][g]&&(c+=" "),E=c):(g&1&&--g,l=E);h=1;for(d=a.length;h":z.Relational,"<=":z.Relational,">=":z.Relational,"in":z.Relational,"instanceof":z.Relational,"<<":z.BitwiseSHIFT,">>":z.BitwiseSHIFT,">>>":z.BitwiseSHIFT,"+":z.Additive,"-":z.Additive,"*":z.Multiplicative,"%":z.Multiplicative,"/":z.Multiplicative,"**":z.Exponentiation}; -(ba=Array.isArray)||(ba=function(a){return"[object Array]"===Object.prototype.toString.call(a)});k.prototype.maybeBlock=function(a,b){var c,d=this;var A=!R.comment||!a.leadingComments;if(a.type===T.BlockStatement&&A)return[I,this.generateStatement(a,b)];if(a.type===T.EmptyStatement&&A)return";";v(function(){c=[M,[E,d.generateStatement(a,b)]]});return c};k.prototype.maybeBlockSuffix=function(a,c){var d=b(q(c).toString());return a.type!==T.BlockStatement||R.comment&&a.leadingComments||d?d?[c,E]:[c, -M,E]:[c,I]};k.prototype.generatePattern=function(a,b,c){return a.type===T.Identifier?V(a):this.generateExpression(a,b,c)};k.prototype.generateFunctionParams=function(a){var b;var c=!1;if(a.type!==T.ArrowFunctionExpression||a.rest||a.defaults&&0!==a.defaults.length||1!==a.params.length||a.params[0].type!==T.Identifier){var d=a.type===T.ArrowFunctionExpression?[sa(a,!1)]:[];d.push("(");a.defaults&&(c=!0);var A=0;for(b=a.params.length;A"));a.expression?(b.push(I),a=this.generateExpression(a.body,z.Assignment,7),"{"===a.toString().charAt(0)&&(a=["(",a,")"]), -b.push(a)):b.push(this.maybeBlock(a.body,9));return b};k.prototype.generateIterationForStatement=function(a,b,c){var d=["for"+I+"("],A=this;v(function(){b.left.type===T.VariableDeclaration?v(function(){d.push(b.left.kind+l());d.push(A.generateStatement(b.left.declarations[0],0))}):d.push(A.generateExpression(b.left,z.Call,7));d=G(d,a);d=[G(d,A.generateExpression(b.right,z.Sequence+("of"===a?1:0),7)),")"]});d.push(this.maybeBlock(b.body,c));return d};k.prototype.generatePropertyKey=function(a,b){var c= -[];b&&c.push("[");c.push(this.generateExpression(a,z.Sequence,7));b&&c.push("]");return c};k.prototype.generateAssignment=function(a,b,c,d,g){z.Assignmentc.indexOf(".")&&!/[eExX]/.test(c)&&W.code.isDecimalDigit(c.charCodeAt(c.length-1))&&!(2<=c.length&&48===c.charCodeAt(0))&&d.push(".")),d.push("."),d.push(V(a.property)));return H(d,z.Member,b)},MetaProperty:function(a,b,c){return H([a.meta&&"string"===typeof a.meta.type&& -a.meta.type===T.Identifier?a.meta.name:a.meta,".",a.property&&"string"===typeof a.property.type&&a.property.type===T.Identifier?a.property.name:a.property],z.Member,b)},UnaryExpression:function(a,b,c){var d=this.generateExpression(a.argument,z.Unary,7);if(""===I)c=G(a.operator,d);else if(c=[a.operator],2k||!X&&!Z&&(32>k||126a||0===a&&0>1/a)throw Error("Numeric literal whose value is negative");if(a===1/0)a=X?"null":da?"1e400":"1e+400";else{b=""+a;if(da&&!(3>b.length)){c=b.indexOf(".");X||48!==b.charCodeAt(0)||1!==c||(c=0,b=b.slice(1));d=b;b=b.replace("e+","e");k=0;0<(g=d.indexOf("e"))&&(k=+d.slice(g+1),d=d.slice(0,g));0<=c&&(k-=d.length-c-1,d=+(d.slice(0, -c)+d.slice(c+1))+"");for(g=0;48===d.charCodeAt(d.length+g-1);)--g;0!==g&&(k-=g,d=d.slice(0,g));0!==k&&(d+="e"+k);(d.length"]},JSXElement:function(a, -b,c){var d=[],g=this;c&256||(E+=K);var h=this.generateExpression(a.openingElement,z.JSXElement,{allowIn:!0,allowCall:!0});d.push(h);var l=[],k,m;v(function(b){k=0;for(m=a.children.length;k":">");return d},JSXSpreadAttribute:function(a,b,c){return["{...",this.generateExpression(a.argument,z.Sequence,{allowIn:!0,allowCall:!0}),"}"]}};m(k.prototype,k.Expression);k.prototype.generateExpression=function(a,b,c){var d=a.type||T.Property;if(R.verbatim&&a.hasOwnProperty(R.verbatim))return d=a[R.verbatim],"string"===typeof d?c=H(ja(d),z.Sequence,b):(c=ja(d.content),d=null!=d.precedence?d.precedence: -z.Sequence,c=H(c,d,b)),q(c,a);b=this[d](a,b,c);R.comment&&(b=C(a,b));return q(b,a)};k.prototype.generateStatement=function(a,b){b=this[a.type](a,b);R.comment&&(b=C(a,b));var c=q(b).toString();a.type!==T.Program||Da||""!==M||"\n"!==c.charAt(c.length-1)||(b=ka?q(b).replaceRight(/\s+$/,""):c.replace(/\s+$/,""));return q(b,a)};var Va=d().format;p.version=c("/package.json",g).version;p.generate=function(b,l){var q=d();null!=l?("string"===typeof l.indent&&(q.format.indent.style=l.indent),"number"===typeof l.base&& -(q.format.indent.base=l.base),l=D(q,l),K=l.format.indent.style,E="string"===typeof l.base?l.base:a(K,l.format.indent.base)):(l=q,K=l.format.indent.style,E=a(K,l.format.indent.base));X=l.format.json;da=l.format.renumber;ra=X?!1:l.format.hexadecimal;Y=X?"double":l.format.quotes;Z=l.format.escapeless;M=l.format.newline;I=l.format.space;l.format.compact&&(M=I=K=E="");Ia=l.format.parentheses;Na=l.format.semicolons;Da=l.format.safeConcatenation;Oa=l.directive;ta=X?null:l.parse;ka=l.sourceMap;xa=l.sourceCode; -pa=l.format.preserveBlankLines&&null!==xa;R=l;ka&&(qa=p.browser?h.sourceMap.SourceNode:c("/node_modules/source-map/lib/source-map.js",g).SourceNode);q=new k;if(k.Statement.hasOwnProperty(b.type))b=q.generateStatement(b,1);else if(k.Expression.hasOwnProperty(b.type))b=q.generateExpression(b,z.Sequence,7);else throw Error("Unknown node type: "+b.type);if(!ka)return b={code:b.toString(),map:null},l.sourceMapWithCode?b:b.code;b=b.toStringWithSourceMap({file:l.file,sourceRoot:l.sourceMapRoot});l.sourceContent&& -b.map.setSourceContent(l.sourceMap,l.sourceContent);return l.sourceMapWithCode?b:b.map.toString()};p.attachComments=u.attachComments;p.Precedence=D({},z);p.browser=!1;p.FORMAT_MINIFY={indent:{style:"",base:0},renumber:!0,hexadecimal:!0,quotes:"auto",escapeless:!0,compact:!0,parentheses:!1,semicolons:!1};p.FORMAT_DEFAULTS=Va})()});c.define("/package.json",function(c,h,p,t){c.exports={name:"escodegen-wallaby",description:"ECMAScript code generator with JSX support",homepage:"http://github.com/wallabyjs/escodegen", -main:"escodegen.js",bin:{esgenerate:"./bin/esgenerate.js",escodegen:"./bin/escodegen.js"},files:"LICENSE.BSD LICENSE.source-map README.md bin escodegen.js package.json".split(" "),version:"1.6.12",engines:{node:">=0.10.0"},maintainers:[{name:"Artem Govorov",email:"artem.govorov@gmail.com",web:"http://dm.gl"}],repository:{type:"git",url:"http://github.com/wallabyjs/escodegen.git"},dependencies:{estraverse:"^1.9.1",esutils:"^2.0.2",esprima:"^2.7.1",optionator:"^0.8.1"},optionalDependencies:{"source-map":"~0.2.0"}, -devDependencies:{acorn:"^2.7.0","acorn-babel":"^0.11.1-38",bluebird:"^2.3.11","bower-registry-client":"^0.2.1",chai:"^1.10.0","commonjs-everywhere":"^0.9.7",gulp:"^3.8.10","gulp-eslint":"^0.2.0","gulp-mocha":"^2.0.0",semver:"^5.1.0"},licenses:[{type:"BSD",url:"http://github.com/wallabyjs/escodegen/raw/master/LICENSE.BSD"}],scripts:{test:"gulp travis","unit-test":"gulp test",lint:"gulp lint",release:"node tools/release.js","build-min":"./node_modules/.bin/cjsify -ma path: tools/entry-point.js > escodegen.browser.min.js", -build:"./node_modules/.bin/cjsify -a path: tools/entry-point.js > escodegen.browser.js"}}});c.define("/node_modules/source-map/lib/source-map.js",function(g,h,p,t){h.SourceMapGenerator=c("/node_modules/source-map/lib/source-map/source-map-generator.js",g).SourceMapGenerator;h.SourceMapConsumer=c("/node_modules/source-map/lib/source-map/source-map-consumer.js",g).SourceMapConsumer;h.SourceNode=c("/node_modules/source-map/lib/source-map/source-node.js",g).SourceNode});c.define("/node_modules/source-map/lib/source-map/source-node.js", -function(g,h,p,t){if("function"!==typeof d)var d=c("/node_modules/amdefine/amdefine.js",g)(g,c);d(function(a,b,c){function d(a,b,c,d,g){this.children=[];this.sourceContents={};this.line=null==a?null:a;this.column=null==b?null:b;this.source=null==c?null:c;this.name=null==g?null:g;this.$$$isSourceNode$$$=!0;null!=d&&this.add(d)}var g=a("/node_modules/source-map/lib/source-map/source-map-generator.js",c).SourceMapGenerator,h=a("/node_modules/source-map/lib/source-map/util.js",c),m=/(\r?\n)/;d.fromStringWithSourceMap= -function(a,b,c){function g(a,b){if(null===a||void 0===a.source)l.add(b);else{var g=c?h.join(c,a.source):a.source;l.add(new d(a.originalLine,a.originalColumn,g,b,a.name))}}var l=new d,q=a.split(m),y=function(){var a=q.shift(),b=q.shift()||"";return a+b},x=1,p=0,t=null;b.eachMapping(function(a){if(null!==t)if(xb)-(ac||d==c&&m>=h||0>=g.compareByGeneratedPositions(b,a)?this._last=a:this._sorted=!1;this._array.push(a)};d.prototype.toArray=function(){this._sorted||(this._array.sort(g.compareByGeneratedPositions),this._sorted=!0);return this._array};b.MappingList=d})});c.define("/node_modules/source-map/lib/source-map/array-set.js",function(g,h,p,t){if("function"!==typeof d)var d=c("/node_modules/amdefine/amdefine.js",g)(g,c); -d(function(a,b,c){function d(){this._array=[];this._set={}}var g=a("/node_modules/source-map/lib/source-map/util.js",c);d.fromArray=function(a,b){for(var c=new d,g=0,h=a.length;ga?(-a<<1)+1:a<<1;do a=c&31,c>>>=5,0=g)throw Error("Expected more digits in base 64 VLQ value.");var m=d.decode(a.charAt(c++));var p=!!(m&32);m&=31;h+=m<>1;b.value=1===(h&1)?-g:g;b.rest=a.slice(c)}})});c.define("/node_modules/source-map/lib/source-map/base64.js",function(g,h,p,t){if("function"!==typeof d)var d=c("/node_modules/amdefine/amdefine.js",g)(g,c);d(function(a, -b,c){var d={},g={};"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").forEach(function(a,b){d[a]=b;g[b]=a});b.encode=function(a){if(a in g)return g[a];throw new TypeError("Must be between 0 and 63: "+a);};b.decode=function(a){if(a in d)return d[a];throw new TypeError("Not a valid base 64 digit: "+a);}})});c.define("/node_modules/source-map/lib/source-map/source-map-consumer.js",function(g,h,p,t){if("function"!==typeof d)var d=c("/node_modules/amdefine/amdefine.js",g)(g,c); -d(function(a,b,c){function d(b){var d=b;"string"===typeof b&&(d=JSON.parse(b.replace(/^\)\]\}'/,"")));return null!=d.sections?new (a("/node_modules/source-map/lib/source-map/indexed-source-map-consumer.js",c).IndexedSourceMapConsumer)(d):new (a("/node_modules/source-map/lib/source-map/basic-source-map-consumer.js",c).BasicSourceMapConsumer)(d)}var g=a("/node_modules/source-map/lib/source-map/util.js",c);d.fromSourceMap=function(b){return a("/node_modules/source-map/lib/source-map/basic-source-map-consumer.js", -c).BasicSourceMapConsumer.fromSourceMap(b)};d.prototype._version=3;d.prototype.__generatedMappings=null;Object.defineProperty(d.prototype,"_generatedMappings",{get:function(){this.__generatedMappings||(this.__generatedMappings=[],this.__originalMappings=[],this._parseMappings(this._mappings,this.sourceRoot));return this.__generatedMappings}});d.prototype.__originalMappings=null;Object.defineProperty(d.prototype,"_originalMappings",{get:function(){this.__originalMappings||(this.__generatedMappings= -[],this.__originalMappings=[],this._parseMappings(this._mappings,this.sourceRoot));return this.__originalMappings}});d.prototype._nextCharIsMappingSeparator=function(a){a=a.charAt(0);return";"===a||","===a};d.prototype._parseMappings=function(a,b){throw Error("Subclasses must implement _parseMappings");};d.GENERATED_ORDER=1;d.ORIGINAL_ORDER=2;d.prototype.eachMapping=function(a,b,c){b=b||null;switch(c||d.GENERATED_ORDER){case d.GENERATED_ORDER:c=this._generatedMappings;break;case d.ORIGINAL_ORDER:c= -this._originalMappings;break;default:throw Error("Unknown order of iteration.");}var h=this.sourceRoot;c.map(function(a){var b=a.source;null!=b&&null!=h&&(b=g.join(h,b));return{source:b,generatedLine:a.generatedLine,generatedColumn:a.generatedColumn,originalLine:a.originalLine,originalColumn:a.originalColumn,name:a.name}}).forEach(a,b)};d.prototype.allGeneratedPositionsFor=function(a){a={source:g.getArg(a,"source"),originalLine:g.getArg(a,"line"),originalColumn:Infinity};null!=this.sourceRoot&&(a.source= -g.relative(this.sourceRoot,a.source));var b=[],c=this._findMapping(a,this._originalMappings,"originalLine","originalColumn",g.compareByOriginalPositions);if(0<=c)for(var d=this._originalMappings[c];d&&d.originalLine===a.originalLine;)b.push({line:g.getArg(d,"generatedLine",null),column:g.getArg(d,"generatedColumn",null),lastColumn:g.getArg(d,"lastGeneratedColumn",null)}),d=this._originalMappings[--c];return b.reverse()};b.SourceMapConsumer=d})});c.define("/node_modules/source-map/lib/source-map/basic-source-map-consumer.js", -function(g,h,p,t){if("function"!==typeof d)var d=c("/node_modules/amdefine/amdefine.js",g)(g,c);d(function(a,b,c){function d(a){var b=a;"string"===typeof a&&(b=JSON.parse(a.replace(/^\)\]\}'/,"")));a=g.getArg(b,"version");var c=g.getArg(b,"sources"),d=g.getArg(b,"names",[]),h=g.getArg(b,"sourceRoot",null),q=g.getArg(b,"sourcesContent",null),p=g.getArg(b,"mappings");b=g.getArg(b,"file",null);if(a!=this._version)throw Error("Unsupported version: "+a);c=c.map(g.normalize);this._names=m.fromArray(d,!0); -this._sources=m.fromArray(c,!0);this.sourceRoot=h;this.sourcesContent=q;this._mappings=p;this.file=b}var g=a("/node_modules/source-map/lib/source-map/util.js",c),h=a("/node_modules/source-map/lib/source-map/binary-search.js",c),m=a("/node_modules/source-map/lib/source-map/array-set.js",c).ArraySet,p=a("/node_modules/source-map/lib/source-map/base64-vlq.js",c);a=a("/node_modules/source-map/lib/source-map/source-map-consumer.js",c).SourceMapConsumer;d.prototype=Object.create(a.prototype);d.prototype.consumer= -a;d.fromSourceMap=function(a){var b=Object.create(d.prototype);b._names=m.fromArray(a._names.toArray(),!0);b._sources=m.fromArray(a._sources.toArray(),!0);b.sourceRoot=a._sourceRoot;b.sourcesContent=a._generateSourcesContent(b._sources.toArray(),b.sourceRoot);b.file=a._file;b.__generatedMappings=a._mappings.toArray().slice();b.__originalMappings=a._mappings.toArray().slice().sort(g.compareByOriginalPositions);return b};d.prototype._version=3;Object.defineProperty(d.prototype,"sources",{get:function(){return this._sources.toArray().map(function(a){return null!= -this.sourceRoot?g.join(this.sourceRoot,a):a},this)}});d.prototype._parseMappings=function(a,b){b=1;for(var c=0,d=0,h=0,l=0,m=0,q={},y;0=a[c])throw new TypeError("Line must be greater than or equal to 1, got "+a[c]);if(0>a[d])throw new TypeError("Column must be greater than or equal to 0, got "+a[d]);return h.search(a,b,g)};d.prototype.computeColumnSpans=function(){for(var a=0;aa?-1:a}b.search=function(a,b,c){return 0===b.length?-1:d(-1,b.length,a,b,c)}})});c.define("/node_modules/source-map/lib/source-map/indexed-source-map-consumer.js",function(g,h,p,t){if("function"!==typeof d)var d=c("/node_modules/amdefine/amdefine.js",g)(g,c);d(function(a,b,c){function d(a){var b=a;"string"===typeof a&&(b=JSON.parse(a.replace(/^\)\]\}'/,"")));a=g.getArg(b,"version");b=g.getArg(b,"sections");if(a!=this._version)throw Error("Unsupported version: "+ -a);var c={line:-1,column:0};this._sections=b.map(function(a){if(a.url)throw Error("Support for url field in sections not implemented.");var b=g.getArg(a,"offset"),d=g.getArg(b,"line"),h=g.getArg(b,"column");if(d= -g){++d;if(d>=b)return!1;var h=a.charCodeAt(d);if(!(56320<=h&&57343>=h))return!1;g=1024*(g-55296)+(h-56320)+65536}if(!c(g))return!1;c=v.isIdentifierPartES6}return!0}var v=c("/node_modules/esutils/lib/code.js",g);g.exports={isKeywordES5:d,isKeywordES6:a,isReservedWordES5:b,isReservedWordES6:h,isRestrictedWord:function(a){return"eval"===a||"arguments"===a},isIdentifierNameES5:p,isIdentifierNameES6:t,isIdentifierES5:function(a,c){return p(a)&&!b(a,c)},isIdentifierES6:function(a,b){return t(a)&&!h(a,b)}}})()}); -c.define("/node_modules/esutils/lib/code.js",function(c,h,p,t){(function(){function d(a){if(65535>=a)return String.fromCharCode(a);var b=String.fromCharCode(Math.floor((a-65536)/1024)+55296);a=String.fromCharCode((a-65536)%1024+56320);return b+a}var a;var b=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/; -var g=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/; -var h=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/; -var p=/[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/; -var t=[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279];var v=Array(128);for(a=0;128>a;++a)v[a]=97<=a&&122>=a||65<=a&&90>=a||36===a||95===a;var F=Array(128);for(a=0;128>a;++a)F[a]=97<=a&&122>=a||65<=a&&90>=a||48<=a&&57>=a||36===a||95===a;c.exports={isDecimalDigit:function(a){return 48<=a&&57>=a},isHexDigit:function(a){return 48<=a&&57>=a||97<=a&&102>=a||65<=a&&70>=a},isOctalDigit:function(a){return 48<=a&&55>=a},isWhiteSpace:function(a){return 32===a||9===a|| -11===a||12===a||160===a||5760<=a&&0<=t.indexOf(a)},isLineTerminator:function(a){return 10===a||13===a||8232===a||8233===a},isIdentifierStartES5:function(a){return 128>a?v[a]:b.test(d(a))},isIdentifierPartES5:function(a){return 128>a?F[a]:g.test(d(a))},isIdentifierStartES6:function(a){return 128>a?v[a]:h.test(d(a))},isIdentifierPartES6:function(a){return 128>a?F[a]:p.test(d(a))}}})()});c.define("/node_modules/esutils/lib/ast.js",function(c,h,p,t){(function(){function d(a){if(null==a)return!1;switch(a.type){case "BlockStatement":case "BreakStatement":case "ContinueStatement":case "DebuggerStatement":case "DoWhileStatement":case "EmptyStatement":case "ExpressionStatement":case "ForInStatement":case "ForStatement":case "IfStatement":case "LabeledStatement":case "ReturnStatement":case "SwitchStatement":case "ThrowStatement":case "TryStatement":case "VariableDeclaration":case "WhileStatement":case "WithStatement":return!0}return!1} -function a(a){switch(a.type){case "IfStatement":return null!=a.alternate?a.alternate:a.consequent;case "LabeledStatement":case "ForStatement":case "ForInStatement":case "WhileStatement":case "WithStatement":return a.body}return null}c.exports={isExpression:function(a){if(null==a)return!1;switch(a.type){case "ArrayExpression":case "AssignmentExpression":case "BinaryExpression":case "CallExpression":case "ConditionalExpression":case "FunctionExpression":case "Identifier":case "Literal":case "LogicalExpression":case "MemberExpression":case "NewExpression":case "ObjectExpression":case "SequenceExpression":case "ThisExpression":case "UnaryExpression":case "UpdateExpression":return!0}return!1}, -isStatement:d,isIterationStatement:function(a){if(null==a)return!1;switch(a.type){case "DoWhileStatement":case "ForInStatement":case "ForStatement":case "WhileStatement":return!0}return!1},isSourceElement:function(a){return d(a)||null!=a&&"FunctionDeclaration"===a.type},isProblematicIfStatement:function(b){if("IfStatement"!==b.type||null==b.alternate)return!1;b=b.consequent;do{if("IfStatement"===b.type&&null==b.alternate)return!0;b=a(b)}while(b);return!1},trailingStatement:a}})()});c.define("/node_modules/estraverse/estraverse.js", -function(c,h,p,t){(function(c,a){"function"===typeof define&&define.amd?define(["exports"],a):"undefined"!==typeof h?a(h):a(c.estraverse={})})(this,function b(a){function c(a){var b={},g;for(g in a)if(a.hasOwnProperty(g)){var h=a[g];b[g]="object"===typeof h&&null!==h?c(h):h}return b}function g(a,b){var c;var g=a.length;for(c=0;g;){var h=g>>>1;var k=c+h;b(a[k])?g=h:(c=k+1,g-=h+1)}return c}function h(a,b){this.parent=a;this.key=b}function p(a,b,c,g){this.node=a;this.path=b;this.wrap=c;this.ref=g}function t(){} -function v(a){return null==a?!1:"object"===typeof a&&"string"===typeof a.type}function q(a,b){return(new t).traverse(a,b)}function l(a,b){var c=g(b,function(b){return b.range[0]>a.range[0]});a.extendedRange=[a.range[0],a.range[1]];c!==b.length&&(a.extendedRange[1]=b[c].range[0]);--c;0<=c&&(a.extendedRange[0]=b[c].range[1]);return a}var F;(F=Array.isArray)||(F=function(a){return"[object Array]"===Object.prototype.toString.call(a)});var C=Object.create||function(){function a(){}return function(b){a.prototype= -b;return new a}}();var ha=Object.keys||function(a){var b=[],c;for(c in a)b.push(c);return b};var Ba={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration", -ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportBatchSpecifier:"ExportBatchSpecifier",ExportDeclaration:"ExportDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement", -ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression", -MemberExpression:"MemberExpression",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral", -ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"};var U={AssignmentExpression:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"], -AwaitExpression:["argument"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body", -"test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent", -"alternate"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["id"],ImportNamespaceSpecifier:["id"],ImportSpecifier:["id","name"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"], -SpreadElement:["argument"],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object", -"body"],YieldExpression:["argument"]};var H={};var ja={};var k={};var V={Break:H,Skip:ja,Remove:k};h.prototype.replace=function(a){this.parent[this.key]=a};h.prototype.remove=function(){if(F(this.parent))return this.parent.splice(this.key,1),!0;this.replace(null);return!1};t.prototype.path=function(){function a(a,b){if(F(b))for(c=0,g=b.length;ca.range[0])break;b.extendedRange[1]===a.range[0]?(a.leadingComments||(a.leadingComments=[]),a.leadingComments.push(b),h.splice(p,1)):p+=1}if(p===h.length)return V.Break;if(h[p].extendedRange[0]>a.range[1])return V.Skip}});p=0;q(a,{leave:function(a){for(var b;pa.range[1])return V.Skip}});return a};a.VisitorKeys=U;a.VisitorOption=V;a.Controller=t;a.cloneEnvironment=function(){return b({})};return a})});c("/tools/entry-point.js")}).call(this,this);return h()}(),semver; -(function(h){var p=0O||!(b.loose?ba[Na]:ba[Ia]).test(a))return null;try{return new v(a,b)}catch(mc){return null}}function v(a,b){b&&"object"===typeof b||(b={loose:!!b,includePrerelease:!1});if(a instanceof v){if(a.loose===b.loose)return a;a=a.version}else if("string"!==typeof a)throw new TypeError("Invalid Version: "+ -a);if(a.length>O)throw new TypeError("version is longer than "+O+" characters");if(!(this instanceof v))return new v(a,b);S("SemVer",a,b);this.options=b;this.loose=!!b.loose;b=a.trim().match(b.loose?ba[Na]:ba[Ia]);if(!b)throw new TypeError("Invalid Version: "+a);this.raw=a;this.major=+b[1];this.minor=+b[2];this.patch=+b[3];if(this.major>qa||0>this.major)throw new TypeError("Invalid major version");if(this.minor>qa||0>this.minor)throw new TypeError("Invalid minor version");if(this.patch>qa||0>this.patch)throw new TypeError("Invalid patch version"); -this.prerelease=b[4]?b[4].split(".").map(function(a){if(/^[0-9]+$/.test(a)){var b=+a;if(0<=b&&bd(a,b,c)}function m(a,b,c){return 0===d(a,b,c)}function D(a,b,c){return 0!==d(a,b,c)}function x(a,b,c){return 0<= -d(a,b,c)}function F(a,b,c){return 0>=d(a,b,c)}function y(c,d,g,h){switch(d){case "===":return"object"===typeof c&&(c=c.version),"object"===typeof g&&(g=g.version),c===g;case "!==":return"object"===typeof c&&(c=c.version),"object"===typeof g&&(g=g.version),c!==g;case "":case "=":case "==":return m(c,g,h);case "!=":return D(c,g,h);case ">":return a(c,g,h);case ">=":return x(c,g,h);case "<":return b(c,g,h);case "<=":return F(c,g,h);default:throw new TypeError("Invalid operator: "+d);}}function N(a,b){b&& -"object"===typeof b||(b={loose:!!b,includePrerelease:!1});if(a instanceof N){if(a.loose===!!b.loose)return a;a=a.value}if(!(this instanceof N))return new N(a,b);S("comparator",a,b);this.options=b;this.loose=!!b.loose;this.parse(a);this.value=this.semver===sb?"":this.operator+this.semver.version;S("comp",this)}function q(a,b){b&&"object"===typeof b||(b={loose:!!b,includePrerelease:!1});if(a instanceof q)return a.loose===!!b.loose&&a.includePrerelease===!!b.includePrerelease?a:new q(a.raw,b);if(a instanceof -N)return new q(a.value,b);if(!(this instanceof q))return new q(a,b);this.options=b;this.loose=!!b.loose;this.includePrerelease=!!b.includePrerelease;this.raw=a;this.set=a.split(/\s*\|\|\s*/).map(function(a){return this.parseRange(a.trim())},this).filter(function(a){return a.length});if(!this.set.length)throw new TypeError("Invalid SemVer Range: "+a);this.format()}function l(a,b){var c=!0;a=a.slice();for(var d=a.pop();c&&a.length;)c=a.every(function(a){return d.intersects(a,b)}),d=a.pop();return c} -function G(a){return!a||"x"===a.toLowerCase()||"*"===a}function Ma(a,b){return a.trim().split(/\s+/).map(function(a){return ha(a,b)}).join(" ")}function ha(a,b){return a.replace(b.loose?ba[pa]:ba[xa],function(b,c,d,g,h){S("tilde",a,b,c,d,g,h);G(c)?b="":G(d)?b=">="+c+".0.0 <"+(+c+1)+".0.0":G(g)?b=">="+c+"."+d+".0 <"+c+"."+(+d+1)+".0":h?(S("replaceTilde pr",h),b=">="+c+"."+d+"."+g+"-"+h+" <"+c+"."+(+d+1)+".0"):b=">="+c+"."+d+"."+g+" <"+c+"."+(+d+1)+".0";S("tilde return",b);return b})}function Ba(a, -b){return a.trim().split(/\s+/).map(function(a){return U(a,b)}).join(" ")}function U(a,b){S("caret",a,b);return a.replace(b.loose?ba[T]:ba[W],function(b,c,d,g,h){S("caret",a,b,c,d,g,h);G(c)?b="":G(d)?b=">="+c+".0.0 <"+(+c+1)+".0.0":G(g)?b="0"===c?">="+c+"."+d+".0 <"+c+"."+(+d+1)+".0":">="+c+"."+d+".0 <"+(+c+1)+".0.0":h?(S("replaceCaret pr",h),b="0"===c?"0"===d?">="+c+"."+d+"."+g+"-"+h+" <"+c+"."+d+"."+(+g+1):">="+c+"."+d+"."+g+"-"+h+" <"+c+"."+(+d+1)+".0":">="+c+"."+d+"."+g+"-"+h+" <"+(+c+1)+".0.0"): -(S("no pr"),b="0"===c?"0"===d?">="+c+"."+d+"."+g+" <"+c+"."+d+"."+(+g+1):">="+c+"."+d+"."+g+" <"+c+"."+(+d+1)+".0":">="+c+"."+d+"."+g+" <"+(+c+1)+".0.0");S("caret return",b);return b})}function H(a,b){S("replaceXRanges",a,b);return a.split(/\s+/).map(function(a){return ja(a,b)}).join(" ")}function ja(a,b){a=a.trim();return a.replace(b.loose?ba[R]:ba[Oa],function(b,c,d,g,h,k){S("xRange",a,b,c,d,g,h,k);var l=(k=G(d))||G(g);h=l||G(h);"="===c&&h&&(c="");k?b=">"===c||"<"===c?"<0.0.0":"*":c&&h?(l&&(g=0), -h=0,">"===c?(c=">=",l?(d=+d+1,g=0):g=+g+1,h=0):"<="===c&&(c="<",l?d=+d+1:g=+g+1),b=c+d+"."+g+"."+h):l?b=">="+d+".0.0 <"+(+d+1)+".0.0":h&&(b=">="+d+"."+g+".0 <"+d+"."+(+g+1)+".0");S("xRange return",b);return b})}function k(a,b,c,d,g,h,k,l,m,p,q,t,u){b=G(c)?"":G(d)?">="+c+".0.0":G(g)?">="+c+"."+d+".0":">="+b;l=G(m)?"":G(p)?"<"+(+m+1)+".0.0":G(q)?"<"+m+"."+(+p+1)+".0":t?"<="+m+"."+p+"."+q+"-"+t:"<="+l;return(b+" "+l).trim()}function V(a,b,c){try{b=new q(b,c)}catch(Vc){return!1}return b.test(a)}function sa(c, -d,g,h){c=new v(c,h);d=new q(d,h);switch(g){case ">":var k=a;g=F;var l=b;var m=">";var p=">=";break;case "<":k=b;g=x;l=a;m="<";p="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"');}if(V(c,d,h))return!1;for(var t=0;t=0.0.0"));u=u||a;Ga=Ga||a;k(a.semver,u.semver,h)?u=a:l(a.semver,Ga.semver,h)&&(Ga=a)});if(u.operator===m||u.operator===p||(!Ga.operator||Ga.operator===m)&&g(c,Ga.semver)|| -Ga.operator===p&&l(c,Ga.semver))return!1}return!0}c=h.exports=v;var S="object"===typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?function(){var a=Array.prototype.slice.call(arguments,0);a.unshift("SEMVER");console.log.apply(console,a)}:function(){};c.SEMVER_SPEC_VERSION="2.0.0";var O=256,qa=Number.MAX_SAFE_INTEGER||9007199254740991,ba=c.re=[];g=c.src=[];var E=0,K=E++;g[K]="0|[1-9]\\d*";var X=E++;g[X]="[0-9]+";var da=E++;g[da]="\\d*[a-zA-Z-][a-zA-Z0-9-]*"; -var ra=E++;g[ra]="("+g[K]+")\\.("+g[K]+")\\.("+g[K]+")";var Y=E++;g[Y]="("+g[X]+")\\.("+g[X]+")\\.("+g[X]+")";var Z=E++;g[Z]="(?:"+g[K]+"|"+g[da]+")";var M=E++;g[M]="(?:"+g[X]+"|"+g[da]+")";da=E++;g[da]="(?:-("+g[Z]+"(?:\\."+g[Z]+")*))";Z=E++;g[Z]="(?:-?("+g[M]+"(?:\\."+g[M]+")*))";var I=E++;g[I]="[0-9A-Za-z-]+";M=E++;g[M]="(?:\\+("+g[I]+"(?:\\."+g[I]+")*))";var Ia=E++;ra="v?"+g[ra]+g[da]+"?"+g[M]+"?";g[Ia]="^"+ra+"$";Y="[v=\\s]*"+g[Y]+g[Z]+"?"+g[M]+"?";var Na=E++;g[Na]="^"+Y+"$";I=E++;g[I]="((?:<|>)?=?)"; -var Da=E++;g[Da]=g[X]+"|x|X|\\*";X=E++;g[X]=g[K]+"|x|X|\\*";K=E++;g[K]="[v=\\s]*("+g[X]+")(?:\\.("+g[X]+")(?:\\.("+g[X]+")(?:"+g[da]+")?"+g[M]+"?)?)?";da=E++;g[da]="[v=\\s]*("+g[Da]+")(?:\\.("+g[Da]+")(?:\\.("+g[Da]+")(?:"+g[Z]+")?"+g[M]+"?)?)?";var Oa=E++;g[Oa]="^"+g[I]+"\\s*"+g[K]+"$";var R=E++;g[R]="^"+g[I]+"\\s*"+g[da]+"$";var ta=E++;g[ta]="(?:^|[^\\d])(\\d{1,16})(?:\\.(\\d{1,16}))?(?:\\.(\\d{1,16}))?(?:$|[^\\d])";Z=E++;g[Z]="(?:~>?)";var ka=E++;g[ka]="(\\s*)"+g[Z]+"\\s+";ba[ka]=new RegExp(g[ka], -"g");var xa=E++;g[xa]="^"+g[Z]+g[K]+"$";var pa=E++;g[pa]="^"+g[Z]+g[da]+"$";Z=E++;g[Z]="(?:\\^)";var u=E++;g[u]="(\\s*)"+g[Z]+"\\s+";ba[u]=new RegExp(g[u],"g");var W=E++;g[W]="^"+g[Z]+g[K]+"$";var T=E++;g[T]="^"+g[Z]+g[da]+"$";var z=E++;g[z]="^"+g[I]+"\\s*("+Y+")$|^$";var Sa=E++;g[Sa]="^"+g[I]+"\\s*("+ra+")$|^$";var Va=E++;g[Va]="(\\s*)"+g[I]+"\\s*("+Y+"|"+g[K]+")";ba[Va]=new RegExp(g[Va],"g");var A=E++;g[A]="^\\s*("+g[K]+")\\s+-\\s+("+g[K]+")\\s*$";var Ca=E++;g[Ca]="^\\s*("+g[da]+")\\s+-\\s+("+g[da]+ -")\\s*$";var Yb=E++;g[Yb]="(<|>)?=?\\s*\\*";for(K=0;K="===this.operator||">"===this.operator)&&(">="===a.operator||">"===a.operator);var d=("<="===this.operator||"<"===this.operator)&&("<="===a.operator||"<"===a.operator),g=this.semver.version===a.semver.version,h=(">="===this.operator||"<="===this.operator)&&(">="===a.operator||"<="===a.operator),k=y(this.semver,"<",a.semver,b)&&(">="===this.operator||">"===this.operator)&&("<="===a.operator||"<"===a.operator);a=y(this.semver,">",a.semver,b)&&("<="===this.operator||"<"===this.operator)&& -(">="===a.operator||">"===a.operator);return c||d||g&&h||k||a};c.Range=q;q.prototype.format=function(){return this.range=this.set.map(function(a){return a.join(" ").trim()}).join("||").trim()};q.prototype.toString=function(){return this.range};q.prototype.parseRange=function(a){var b=this.options.loose;a=a.trim();a=a.replace(b?ba[Ca]:ba[A],k);S("hyphen replace",a);a=a.replace(ba[Va],"$1$2$3");S("comparator trim",a,ba[Va]);a=a.replace(ba[ka],"$1~");a=a.replace(ba[u],"$1^");a=a.split(/\s+/).join(" "); -var c=b?ba[z]:ba[Sa];a=a.split(" ").map(function(a){var b=a;a=this.options;S("comp",b,a);b=Ba(b,a);S("caret",b);b=Ma(b,a);S("tildes",b);b=H(b,a);S("xrange",b);S("replaceStars",b,a);b=b.trim().replace(ba[Yb],"");S("stars",b);return b},this).join(" ").split(/\s+/);this.options.loose&&(a=a.filter(function(a){return!!a.match(c)}));return a=a.map(function(a){return new N(a,this.options)},this)};q.prototype.intersects=function(a,b){if(!(a instanceof q))throw new TypeError("a Range is required");return this.set.some(function(c){return l(c, -b)&&a.set.some(function(a){return l(a,b)&&c.every(function(c){return a.every(function(a){return c.intersects(a,b)})})})})};c.toComparators=function(a,b){return(new q(a,b)).set.map(function(a){return a.map(function(a){return a.value}).join(" ").trim().split(" ")})};q.prototype.test=function(a){if(!a)return!1;"string"===typeof a&&(a=new v(a,this.options));for(var b=0;b":0===c.prerelease.length?c.patch++:c.prerelease.push(0),c.raw=c.format();case "":case ">=":if(!d||a(d,c))d=c;break;case "<":case "<=":break;default:throw Error("Unexpected operation: "+ -b.operator);}});return d&&b.test(d)?d:null};c.validRange=function(a,b){try{return(new q(a,b)).range||"*"}catch(mc){return null}};c.ltr=function(a,b,c){return sa(a,b,"<",c)};c.gtr=function(a,b,c){return sa(a,b,">",c)};c.outside=sa;c.prerelease=function(a,b){return(a=p(a,b))&&a.prerelease.length?a.prerelease:null};c.intersects=function(a,b,c){a=new q(a,c);b=new q(b,c);return a.intersects(b)};c.coerce=function(a){if(a instanceof v)return a;if("string"!==typeof a)return null;a=a.match(ba[ta]);return null== -a?null:p(a[1]+"."+(a[2]||"0")+"."+(a[3]||"0"))}};c(p,1=b&&(b=-b||1);e<=a;e+=b)f.push(e);else for(0<=b&&(b=-b||-1);e>=a;e+=b)f.push(e);return f}function v(e,a){return e.filter(function(e){return e!==a})}function t(e,a){return e.filter(function(e){return-1===a.indexOf(e)})}function d(e,a){if(!e.length)return e;var f=[e[0]];if(a)for(a=1;a=a)return e;a--}return e.reduce(function(e,f){return e.concat(Array.isArray(f)?b(f,a):[f])},[])}function m(e,a,b){for(var f=[],n=0;na?1:0}),"value")}function N(e){return e[e.length-1]}function q(e,a,b){e.splice(b,0,a)}function l(a,f){a.splice(f,1)}function G(a,f){var e=a.indexOf(f);0<=e&&l(a,e);return f}function Ma(a,f){a.includes(f)||a.push(f)}function ha(a,f){for(var e=0;e/);b?a=b[1]||b[2]||"":(e=e.match(/^[\s\(]*function[^(]*\(([^)]*)\)/))&&e[1]&&(a=e[1]);return a.replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g,"").replace(/\s+/g,"").split(",").map(function(a){return a.trim()}).filter(function(a){return!!a})} -function O(a){var e="";a.declaredClass?e+=a.declaredClass+">>":a.declaredObject&&(e+=a.declaredObject+".");return e+(a.methodName||a.displayName||a.name||"anonymous")}function qa(a,f){var e=Array.prototype.slice.call(arguments),b=e.shift();f=1E3*e.shift();return setTimeout(function(){return b.apply(b,e)},f)}function ba(a,f){var e,b,c,d,g,h,ua=E(f,function(){g=d=!1});return function(){e=this;b=arguments;c||(c=setTimeout(function(){c=null;g&&a.apply(e,b);ua()},f));d?g=!0:h=a.apply(e,b);ua();d=!0;return h}} -function E(a,f,b){var e;return function(){var n=this,c=arguments;b&&!e&&f.apply(n,c);clearTimeout(e);e=setTimeout(function(){e=null;b||f.apply(n,c)},a)}}function K(a,f,b,c){var e=of;return e[a]?e[a]:e[a]=E(f,function(){delete e[a];b.apply(this,arguments)},c)}function X(a,f){a&&console.error("lively.lang.composeAsync error",a)}function da(a,f){var e=function(){var e=Array.prototype.slice.call(arguments);e=f.isWrapper?e:[a.bind(this)].concat(e);return f.apply(this,e)};e.isWrapper=!0;e.originalFunction= -a;return e}function ra(a){if(a){if("function"!==typeof a)throw Error("once() expecting a function");var e=!1,b;return function(){if(e)return b;e=!0;return b=a.apply(this,arguments)}}}function Y(a){return eval(a)}function Z(a){return Y("("+a.toString()+");")}function M(a,f){return za.fromFunction(a,f).recreateFunc()}function I(a,f,b,c){var e=b||a.name;if(!e)throw Error("Function that wants to be a script needs a name: "+this);b=Object.getPrototypeOf(f);var n={"this":f};c&&(n=T([n,c]));b&&b[e]&&(n.$super= -za.fromFunction(function(){try{return Object.getPrototypeOf(f)[e].apply(f,arguments)}catch(ya){return"undefined"!==typeof $world?$world.logError(ya,"Error in $super call"):console.error("Error in $super call: "+ya+"\n"+ya.stack),null}},{obj:f,name:e}).recreateFunc());return Ia(M(a,n),f,e)}function Ia(a,f,b){a.displayName=b;var e=f.attributeConnections?f.attributeConnections.filter(function(a){return"update"===a.getSourceAttrName()}):[];e&&e.forEach(function(a){a.disconnect()});f[b]=a;typeof f&&(a.declaredObject= -zb(f));"undefined"!==typeof lively&&f&&lively.Tracing&&lively.Tracing.stackTracingEnabled&&lively.Tracing.instrumentMethod(f,b,{declaredObject:zb(f)});e&&e.forEach(function(a){a.connect()});return a}function Na(a){if(a&&Array.isArray(a))return"["+a.map(Na)+"]";if("string"!==typeof a)return String(a);a=String(a);a=a.replace(/\n/g,"\\n\\\n");a=a.replace(/(")/g,"\\$1");return'"'+a+'"'}function Da(a,f,b){if(!b||0>=b)return a;for(;0=f.maxDepth)return e+"/*...*/"+n;var d=[];if(c)d=a.map(function(a){return W(a,f,b+1)}); -else for(var g=Object.keys(a).sort(function(e,f){var b="function"===typeof a[e];return b===("function"===typeof a[f])?ef?1:0:b?1:-1}),h=0;h(f.maxNumberOfKeys||Infinity)){g=g.length-h;d.push("..."+g+" hidden "+(1=f.minLengthForNewLine);var m= -Da("",f.indent||" ",b);k=Da("",f.indent||" ",b+1);l=h&&!c?"\n"+k:"";c=h&&!c?"\n"+m:"";h&&(g=d.join(","+(h?"\n"+k:"")));return e+l+g+c+n}function T(a){return 1a.length&&(e=e.concat(f.slice(a.length)));return e}return"object"!==typeof a||"object"!==typeof f?f:Object.keys(a).concat(Object.keys(f)).reduce(function(e,b){e[b]=a[b]?f[b]?"object"!==typeof a[b]||"object"!==typeof f[b]?f[b]:z(a[b],f[b]):a[b]:f[b];return e},{})}function Sa(a,f){f=[];for(var e in a){var c=a[e],w=c.hasOwnProperty("before")?c.before:c.before=[];c=c.hasOwnProperty("after")?c.after:c.after=[];for(var d=w.length;d--;){var g=w[d],h=a[g];h?(h.hasOwnProperty("after")||(h.after=[]), -h.after.push(e)):(console.warn("[initializeProperties] "+this+" sortProperties: "+("Property "+e+" requires to be initialized before "+g+" ")+"but that property cannot be found."),w.splice(d,1))}for(w=c.length;w--;)d=c[w],a[d]||(console.warn("[initializeProperties] "+this+" sortProperties: "+("Property "+e+" requires to be initialized after "+d+" ")+"but that property cannot be found."),c.splice(w,1));f.push(e)}e=[];c=[];for(w=f.length+1;f.length;){if(w===f.length)throw Error("Circular dependencies in handler order, could not resolve properties "+ -f.map(function(e){var f=a[e].before,b=a[e].after;if(!(f&&f.length||b&&b.length))return"";e+="\n";f&&f.length&&(e+=" - before "+f.join(",")+"\n");b&&b.length&&(e+=" - after "+b.join(",")+"\n");return e}).join(""));w=f.length;d=[];for(g=f.length;g--;)h=f[g],ha(a[h].after,c)&&(f.splice(g,1),c.push(h),d.push(h));e.push(d)}return b(e,1)}function Va(a,f){for(var e=[];a;)a.hasOwnProperty(f)&&e.unshift(a[f]),a=Object.getPrototypeOf(a);return e}function A(a){if(!a||"object"!==typeof a||a instanceof RegExp)return a; -var e=Array.isArray(a)?Array(a.length):{},b;for(b in a)a.hasOwnProperty(b)&&(e[b]=A(a[b]));return e}function Ca(a){return null===a?"null":"undefined"===typeof a?"undefined":a.constructor.name}function Yb(a){return-1===["null","undefined","Boolean","Number","String"].indexOf(Ca(a))}function zb(a){try{return(a?a.toString():String(a)).replace("\n","")}catch(f){return""}}function sb(a){function e(a,e){return""+a}function b(a,e){return a.toString()}function c(a,e){return W(a)}var w= -a.shift();w||console.log("Error in Strings>>formatFromArray, first arg is undefined");var d={s:e,d:b,i:b,f:function(a,e,f){return-1=b)return a;for(var e="";0=f-a-c}function Od(a,f){f=1/f;return Math.round(a*f)/f}function vf(a,f){return Object.getOwnPropertyNames(a).reduce(function(e,b){(f?f(a,b):1)&&e.push(b);return e},[])}function kb(a){return"function"===typeof a?kb.convertCallbackFun(a):Promise.resolve(a)}function Pd(a,f,b,c,d){var e=a.shift();if(e)try{Promise.resolve(e(f,b)).then(function(e){return Pd(a,e,b,c,d)}).catch(function(a){d(a)})}catch(ya){d(ya)}else c(f)}function Aa(a,f){if(a instanceof Aa)return a; -if(!(this instanceof Aa))return new Aa(a,f);this.setSplitter(f||".");this.fromPath(a)}function Qd(a,f,b,c){b=void 0===b?[]:b;c=void 0===c?Infinity:c;if(!Array.isArray(a[f]))return[];for(var e=[],n={},r={},d=0;dc)&&(e.push(h),n[h]=!0,h=a[h])))for(var k=0;k"+a.slice(c.raisedAt,c.raisedAt+20),f.verbose&&show("parse error: "+e),c.parseErrorSource=e):c&&f.verbose&&show(""+c+c.stack);b|| -(b=Gf.parse_dammit(a,f),f.addSource&&tc(b,a),b.isFuzzy=!0,b.parseError=c);return b}function Ua(a,f){function e(a){a=c(b(a));g.allComments=a.comments}function b(a){d.forEach(function(e){var f=Qb(Ff(e.start,g).reverse(),function(a){return"BlockStatement"===a.type||"Program"===a.type});f||(f=g);f.comments||(f.comments=[]);f.comments.push(e);a.nodesWithComments.push(f)});return a}function c(e){e.nodesWithComments.forEach(function(f){V(f.comments).reduce(function(b,c){if(c.isBlock)return b.lastComment= -null,b;if(!b.lastComment)return b.lastComment=c,b;var n=b.lastComment;if(Qb(f.body,function(a){return a.start>=n.end&&a.end<=c.start}))return b.lastComment=c,b;var r=a.slice(n.end,c.start);if(/[\n\r][\n\r]+/.test(r))return b.lastComment=c,b;n.text+="\n"+c.text;n.end=c.end;G(f.comments,c);G(e.comments,c);return b},{lastComment:null})});return e}f=f||{};f.ecmaVersion=f.ecmaVersion||8;f.sourceType=f.sourceType||"module";f.hasOwnProperty("allowImportExportEverywhere")||(f.allowImportExportEverywhere= -!0);f.plugins=f.plugins||{};f.plugins.jsx=f.plugins.hasOwnProperty("jsx")?f.plugins.jsx:!0;f.plugins.asyncawait=f.plugins.hasOwnProperty("asyncawait")?f.plugins.asyncawait:{inAsyncFunction:!0};f.plugins.objectSpread=f.plugins.hasOwnProperty("objectSpread")?f.plugins.objectSpread:!0;if(f.withComments){delete f.withComments;var d=[];f.onComment=function(a,e,f,b,c,n){d.push({isBlock:a,text:e,node:null,start:f,end:b,line:c,column:n})}}try{var g=p.parse(a,f)}catch(ab){if("undefined"!==typeof SyntaxError&& -ab instanceof SyntaxError&&ab.loc){var h=a.split("\n"),ua=ab,k=ua.loc;f=k.line;k=k.column;var l=ua.pos;h=h[f-1];ua="Syntax error at line "+f+" column "+k+" (index "+l+') "'+ua.message+'"\nsource: '+h.slice(0,k)+"<--SyntaxError--\x3e"+h.slice(k);ua=new SyntaxError(ua);ua.loc={line:f,column:k};ua.pos=l;throw ua;}throw ab;}f.addSource&&tc(g,a);f.addAstIndex&&!g.hasOwnProperty("astIndex")&&sc(g);g&&d&&e({ast:g,comments:d,nodesWithComments:[]});return g}function Ud(a){return Hf.test(a)&&-1===a.indexOf("-")} -function la(a){return"this"===a?{type:"ThisExpression"}:{name:String(a),type:"Identifier"}}function Cb(a){return{type:"Literal",value:a}}function lb(a){return{type:"ExpressionStatement",expression:a}}function Vd(a,f,b){return{left:a,right:b,operator:f,type:"BinaryExpression"}}function Wd(a,f,b){for(var e=[],c=2;c=n.declaration.declarations.length)e.push(n);else for(var d=n.declaration.declarations,g=0;g=ib.earliestDate&&x.source)return d.format="register",d.deps=[],c&&console.log("[lively.modules customTranslate] loaded %s from filesystem cache after %sms",f.name,Date.now()-h),n.return(Promise.resolve(x.source));n.jumpTo(5);break;case 8:if((x=n.yieldResult)&&x.hash==v&&x.timestamp>=hb.earliestDate&&x.source)return d.format="register",d.deps=[],c&&console.log("[lively.modules customTranslate] loaded %s from browser cache after %sms",f.name,Date.now()-h),n.return(Promise.resolve(x.source)); -case 5:n.leaveTryBlock(3);break;case 2:B=n.enterCatchBlock(),console.error("[lively.modules customTranslate] error reading module translation cache: "+B.stack);case 3:return A={},p?(l.recorderName="__lvVarRecorder",l.recorder===b.global&&l.unloadEnv(),f.metadata.format="esm",z=ue(b,f.source,f.name,l,c),A=z.options,D=z.source,f.source=D,m=f.metadata["lively.modules instrumented"]=!0,c&&console.log("[lively.modules] loaded %s as es6 module",f.name)):"global"===f.metadata.format&&(l.recorderName="System.global", -l.recorder=b.global,f.metadata.format="global",C=ue(b,f.source,f.name,l,c),A=C.options,D=C.source,f.source=D,m=f.metadata["lively.modules instrumented"]=!0,c&&console.log("[lively.modules] loaded %s as instrumented global module",f.name)),m||c&&console.log("[lively.modules] customTranslate ignoring %s b/c don't know how to handle format %s",f.name,f.metadata.format),n.return(a(f).then(function(a){var e,n,d;return $jscomp.asyncExecutePromiseGeneratorProgram(function(r){switch(r.nextAddress){case 1:if(0=== -a.indexOf("System.register(")){c&&console.log("[lively.modules customTranslate] Installing System.register setter captures for %s",f.name);var w=a,g=f.name,J=l,ya=c;w=String(w);J=Object.assign({},A,{topLevelVarRecorder:J.recorder,varRecorderName:J.recorderName,dontTransform:J.dontTransform,recordGlobals:!0,declarationWrapperName:J.varDefinitionCallbackName,currentModuleAccessor:Jc(Tb(Jc(Tb(Tb("__lvVarRecorder","System"),"get"),Kc("@lively-env")),"moduleEnv"),Kc(g))});try{g=w;J=void 0===J?{}:J;if(J.topLevelVarRecorder){if("function"=== -typeof J.declarationCallback||J.declarationWrapperName){var k=J.declarationWrapperName||"lively.capturing-declaration-wrapper";J.declarationWrapper=md(Ec(J.varRecorderName),re(k),!0);J.declarationCallback&&(J.topLevelVarRecorder[k]=J.declarationCallback)}var m=Ua(g),ua=(J.dontTransform||[]).concat(["arguments"]);J.recordGlobals||t(Object.keys(J.topLevelVarRecorder),ua);var Ab=fg(m,Ec(J.varRecorderName||"__lvVarRecorder"),Object.assign({},{exclude:ua},J));var Wc=cb(Ab)}else Wc=g;ya&&"undefined"!== -typeof $world&&$world.get("log")&&$world.get("log").isText&&($world.get("log").textString+=Wc);a=Wc}catch(zg){console.error("Error in prepareTranslatedCodeForSetterCapture",zg.stack),a=w}}if(rd&&q&&p)return e=b._livelyModulesTranslationCache||(b._livelyModulesTranslationCache=new ib),r.setCatchFinallyBlocks(8),r.yield(e.cacheModuleSource(f.name,v,a),10);if(!(q&&u&&p)){r.jumpTo(3);break}e=b._livelyModulesTranslationCache||(b._livelyModulesTranslationCache=new hb);r.setCatchFinallyBlocks(5);return r.yield(e.cacheModuleSource(f.name, -v,a),7);case 7:c&&console.log("[lively.modules customTranslate] stored cached version for %s",f.name);r.leaveTryBlock(3);break;case 5:n=r.enterCatchBlock();console.error("[lively.modules customTranslate] failed storing module cache: "+n.stack);r.jumpTo(3);break;case 10:c&&console.log("[lively.modules customTranslate] stored cached version in filesystem for %s",f.name);r.leaveTryBlock(3);break;case 8:d=r.enterCatchBlock(),console.error("[lively.modules customTranslate] failed storing module cache: "+ -d.stack);case 3:return c&&console.log("[lively.modules customTranslate] done %s after %sms",f.name,Date.now()-h),r.return(a)}})}))}})}function Ag(a,f){return a.translate(f).then(function(e){var b=Ua(e).body.find(function(a){return a.expression&&"CallExpression"===a.expression.type&&"register"===a.expression.callee.property.name});if(!b)throw Error("Cannot find register call in translated source of "+f.name);var c=b.expression;b=c.arguments[0].elements.map(function(a){return a.value});c=c.arguments[1]; -e=e.slice(c.start,c.end);e=eval('var __moduleName = "'+f.name+'";('+e+");\n//# sourceURL="+f.name+"\n");a.debug&&"undefined"!==$world&&$world.get("log")&&$world.get("log").isText&&($world.get("log").textString=e);return{localDeps:b,declare:e}})}function Bg(a,f){return a.translate(f).then(function(a){return{translated:a}})}function we(a){fb(a,"translate","lively_modules_translate_hook")||eb(a,"translate",function(e,b){return xg.call(a,e,b)},"lively_modules_translate_hook")}function sd(a,f,b,c,d){var e= -a.get("@lively-env").pendingExportChanges;(a=fa(a,f).record())&&(b in a.exports||d)&&((e[f]||(e[f]={}))[b]=c)}function xe(a,f){var e=a.get("@lively-env").pendingExportChanges[f];e&&(delete a.get("@lively-env").pendingExportChanges[f],Cg(a,f,e))}function Cg(a,f,b){var e=a.debug;fa(a,f).updateRecord(function(c){var n=[],d=[];Object.keys(b).forEach(function(a){var r=b[a];e&&console.log("[lively.vm es6 updateModuleExports] %s export %s = %s",f,a,String(r).slice(0,30).replace(/\n/g,"")+"...");var w=!(a in -c.exports);w&&(c.__lively_modules__.evalOnlyExport[a]=!0);c.exports[a]=r;w?n.push(a):d.push(a)});if(n.length){var r=a.get(f);Object.isFrozen(r)?(console.warn("[lively.vm es6 updateModuleExports] Since module %s is frozen a new module object was installed in the system. Note that only(!) exisiting module bindings are updated. New exports that were added will only be available in already loaded modules after those are reloaded!",f),a.set(f,a.newModule(c.exports))):(e&&console.log("[lively.vm es6 updateModuleExports] adding new exports to %s", -f),n.forEach(function(a){Object.defineProperty(r,a,{configurable:!1,enumerable:!0,get:function(){return c.exports[a]},set:function(){throw Error("exports cannot be changed from the outside");}})}))}if(d.length){e&&console.log("[lively.vm es6 updateModuleExports] updating %s dependents of %s",c.importers.length,f);for(var w=0,g=c.importers.length;w "+g);if(ic.test(b)||vd.test(b)||ah.test(g)||bh.test(g)||ch.test(g)||f.loads&&f.loads[g]||!ic.test(g)){w.jumpTo(3);break}return w.yield(ea(g).exists(),4);case 4:if(w.yieldResult)return w.return(g);k=g.replace(".js","/index.js");return w.yield(ea(k).exists(), -5);case 5:return w.yieldResult||!h?w.return(k):w.return(g.replace(".js","/index.node"));case 3:return dh.test(g)&&(g=g.replace(".jsx.js",".jsx")),w.return(g)}})}function Ge(a,b,c,d){var e=Je(this,b,c);a=a(e,c,d);a=Ke(this,a);ic.test(b)||vd.test(b)||ic.test(a)||vd.test(a)||console.log("[failed resolution]"+a);this.debug&&console.log("[normalizeSync] "+b+" => "+a);return a}function Zg(a,b,c){b=c.get(b.map["@env"]||"@system-env");var e;for(e in a){c="~"==e[0];var f=c?e.substr(1):e;var n=b;for(f=f.split(".");f.length;)n= -n[f.shift()];if(!c&&n||c&&!n){var d=a[e];break}}if(d&&"string"!=typeof d)throw Error("Unable to map a package conditional to a package conditional.");return d}function Sg(a,b){var e=Object.freeze;Object.freeze=function(a){return a};a=a(b);Object.freeze=e;return a}function Tg(a,b){var e=this;return a(b).then(function(a){var f={};kb.waitFor(6E4,function(){return e.get(b.name)},f).then(function(a){if(a===f)console.warn("[lively.modules] instantiate_triggerOnLoadCallbacks for "+b.name+" timed out");else{a= -b.name;for(var c=fa(e,a),n=e.get("@lively-env").onLoadCallbacks,d=n.length;d--;){var r=n[d],w=r.moduleName,g=r.callback;if((r.resolved?w:e.decanonicalize(w))===a){n.splice(d,1);try{g(c)}catch(Bb){console.error(Bb)}}}Sb("lively.modules/moduleloaded",{module:b.name},Date.now(),e)}});return a})}function Ne(a,b,c,d){b=void 0===b?{maxDepth:0,excludes:[]}:b;c=void 0===c?{}:c;d=void 0===d?0:d;var e,f,n,r,g,h,k,l,m,p,q,t,u;return $jscomp.asyncExecutePromiseGeneratorProgram(function(w){switch(w.nextAddress){case 1:e= -b;f=e.maxDepth;n=e.excludes;if(0f)return w.return(c);w.setCatchFinallyBlocks(2);r=JSON;g=r.parse;return w.yield(ea(a).join("package.json").read(),4);case 4:h=g.call(r,w.yieldResult);k=h.name+"@"+h.version;if(c[k]||n.includes(h.name))return w.return(c);c[k]=Object.assign({},{url:a},ka(h,["name","version","dependencies","devDependencies","main"]));w.leaveTryBlock(3);break;case 2:return w.enterCatchBlock(),w.return(c);case 3:return w.setCatchFinallyBlocks(5),w.yield(ea(a).join("node_modules").dirList(1), -7);case 7:l=w.yieldResult;w.leaveTryBlock(6);break;case 5:return w.enterCatchBlock(),w.return(c);case 6:m=$jscomp.makeIterator(l),p=m.next();case 8:if(p.done){w.jumpTo(10);break}t=q=p.value;u=t.url;return w.yield(Ne(u,b,c,d+1),11);case 11:c=w.yieldResult;p=m.next();w.jumpTo(8);break;case 10:return w.return(c)}})}function Oe(){return od(na)}function wd(a){var e=[];do e.push(a),a=a[Wb];while(a&&a.name);return e.map(function(a){return a.name}).join("->")}function Pe(a){var e=xd(a),b=e.properties;e=e.propertySettings; -a[Oc]={properties:b,order:Sa(b),propertySettings:e,classHierarchy:wd(a)};b&&"object"===typeof b?Qe(a,e,b):console.warn("Class "+a.name+" indicates it has managed properties but its properties accessor (properties) does not return a valid property descriptor map")}function Qe(a,b,c){eh(a);var e=b.valueStoreProperty,f=b.defaultGetter,n=b.defaultSetter,d=a.prototype;Object.keys(c).forEach(function(a){var b=c[a],r=d.hasOwnProperty(a)&&d.__lookupGetter__(a);if(!r||r._wasGenerated)r=b.get||"function"=== -typeof f&&function(){return f.call(this,a)}||function(){return this[e][a]},r._wasGenerated=!0,d.__defineGetter__(a,r);r=d.hasOwnProperty(a)&&d.__lookupSetter__(a);if(!r||r._wasGenerated)if(b.hasOwnProperty("set")||!b.readOnly)b=b.set||"function"===typeof n&&function(e){n.call(this,a,e)}||function(b){this[e][a]=b},b._wasGenerated=!0,d.__defineSetter__(a,b)})}function eh(a){Object.defineProperty(a.prototype,"propertiesAndPropertySettings",{enumerable:!1,configurable:!0,writable:!0,value:function(){var a= -this.constructor,e=a[Oc];if(e)if(e.classHierarchy!=wd(a)){var b=xd(a);e=b.properties;b=b.propertySettings;a[Oc]={properties:e,propertySettings:b,order:Sa(e),classHierarchy:wd(a)};Qe(a,b,e)}else return e;return a[Oc]||xd(a)}});Object.defineProperty(a.prototype,"initializeProperties",{enumerable:!1,configurable:!0,writable:!0,value:function(a){var e=this.propertiesAndPropertySettings(),b=e.properties,f=e.order,c=e.propertySettings.valueStoreProperty;f=f||Sa(b);e=[];var d={};this.hasOwnProperty(c)|| -(this[c]={});for(var g=0;g/,za=function(a,b,c,d){this.originalFunc=a;this.varMapping=b||{};this.setFuncSource(c||a);this.setFuncProperties(a||d)};za.fromFunction=function(a,b){return new this(a,b||{})};za.fromSource=function(a,b){return new this(null,b||{},a)};za.prototype.setFuncSource= -function(a){return this.source=a="undefined"!==typeof lively&&lively.sourceTransform&&"function"===typeof lively.sourceTransform.stringifyFunctionWithoutToplevelRecorder?lively.sourceTransform.stringifyFunctionWithoutToplevelRecorder(a):String(a)};za.prototype.getFuncSource=function(){return this.source||this.setFuncSource(this.originalFunc)};za.prototype.hasFuncSource=function(){return this.source&&!0};za.prototype.getFunc=function(){return this.originalFunc||this.recreateFunc()};za.prototype.getFuncProperties= -function(){return this.funcProperties||(this.funcProperties={})};za.prototype.setFuncProperties=function(a){var e=this.getFuncProperties(),b;for(b in a)a.hasOwnProperty(b)&&(e[b]=a[b])};za.prototype.lookup=function(a){return this.varMapping[a]};za.prototype.parameterNames=function(a){return"undefined"!==typeof lively&&lively.ast&&lively.ast.parseFunction?(lively.ast.parseFunction(a).params||[]).map(function(a){return"Identifier"===a.type?a.name:a.left&&"Identifier"===a.left.type?a.left.name:null}).filter(Boolean): -(a=oh.exec(a))?(a[1]||a[2]||"").split(",").map(function(a){return a.trim()}):[]};za.prototype.firstParameter=function(a){return this.parameterNames(a)[0]||null};za.prototype.recreateFunc=function(){return this.recreateFuncFromSource(this.getFuncSource(),this.originalFunc)};za.prototype.recreateFuncFromSource=function(a,b){b=[];var e="$super"===this.firstParameter(a);for(f in this.varMapping)this.varMapping.hasOwnProperty(f)&&"this"!=f&&b.push("var "+f+" = this.varMapping."+f+";\n");var f="";0a[b])return!1;return!0},sort:function(a,b){return a.sort(b)},sortBy:y,sortByKey:function(a,b){return y(a,function(a){return a[b]})},reverse:function(a){return a.reverse()},reversed:function(a){return a.slice().reverse()},reMatches:function(a,b,c){c=c||String;return a.map(function(a){return c(a).match(b)})}, -first:function(a){return a[0]},last:N,intersect:function(a,b){return d(a).filter(function(a){return-1b&&(b=a.length+b);0>c&&(c=a.length+c);var e=a[b];a[b]=a[c];a[c]=e;return a},rotate:function(a,b){b=b||1;return a.slice(b).concat(a.slice(0,b))},groupBy:Ba,groupByKey:function(a,b){return Ba(a,function(a){return a[b]})},partition:U,batchify:function(a,b,c){function e(a,f){if(!f.length)return[a,[]];var n=f[0];f=f.slice(1);var d=a.concat([n]);if(b.call(c,d))return e(d, -f);a=e(a,f);return[a[0],[n].concat(a[1])]}function f(a,b){if(!b.length)return a;b=e([],b);if(!b[0].length)throw Error("Batchify constrained does not ensure consumption of at least one item per batch!");return f(a.concat([b[0]]),b[1])}return f([],a)},toTuples:function(a,b){b=b||1;return C(0,Math.ceil(a.length/b)-1).map(function(e){return a.slice(e*b,e*b+b)},a)},permutations:rh,combinationsPick:H,combinations:function(a){for(var e=a.reduce(function(a,e){return a*e.length},1),b=a.map(function(a){return 0}), -c=Array(e),d=0;d=b[f]&&(!b[f+1]|| -e<=b[f+1]))return a[f].push(e),a;throw Error("Histogram creation: Cannot group data "+e+" into thresholds "+b);},C(1,b.length).map(function(){return[]}))},clone:V,toArray:function(a){return Qc(a)},each:function(a,b,c){return a.forEach(b,c)},all:function(a,b,c){return a.every(b,c)},any:function(a,b,c){return a.some(b,c)},collect:function(a,b,c){return a.map(b,c)},findAll:function(a,b,c){return a.filter(b,c)},inject:function(a,b,c,d){d&&(c=c.bind(d));return a.reduce(c,b)},mapAsyncSeries:function(a, -b,c){function e(a,e){if(!n&&(a||e)){n=!0;try{c(a,f)}catch(ua){console.error("Error in mapAsyncSeries - callback invocation error:\n"+(ua.stack||ua))}}}var f=[],n=!1;return a.reduceRight(function(a,c,d){if(!n)return function(n,r){if(n)return e(n);0=d)return c(Error("timeout"));d=arguments.length)return arguments[0];var f=Array.prototype.slice.call(arguments);a=f.shift();e.isWrapper=!0;e.originalFunction=a;return e},wrap:da,binds:function(a,b){return za.fromFunction(a,b||{}).recreateFunc()},getOriginal:function(a){for(;a.originalFunction;)a=a.originalFunction;return a},wrapperChain:function(a){var b=[];do b.push(a), -a=a.originalFunction;while(a);return b},replaceMethodForOneCall:function(a,b,c){c.originalFunction=a[b];var e=a.hasOwnProperty(b);a[b]=function(){e?a[b]=c.originalFunction:delete a[b];return c.apply(this,arguments)};return a},once:ra,either:function(){var a=!1;return Array.prototype.slice.call(arguments).map(function(b){return function(){if(!a)return a=!0,b.apply(this,arguments)}})},eitherNamed:function(a,b){a=Array.prototype.slice.call(arguments).shift();var e=Bd[a]||(Bd[a]={wasCalled:!1,callsLeft:0}); -e.callsLeft++;return function(){e.callsLeft--;0>=e.callsLeft&&delete Bd[a];if(!e.wasCalled)return e.wasCalled=!0,b.apply(this,arguments)}},evalJS:Y,fromString:Z,asScript:M,asScriptOf:I,addToObject:Ia,setLocalVarValue:function(a,b,c){a.hasLivelyClosure&&(a.livelyClosure.funcProperties[b]=c)},getVarMapping:function(a){return a.hasLivelyClosure?a.livelyClosure.varMapping:a.isWrapper?a.originalFunction.varMapping:a.varMapping?a.varMapping:{}},setProperty:function(a,b,c){a[b]=c;a.hasLivelyClosure&&(a.livelyClosure.funcProperties[b]= -c)},functionNames:function(a){for(var b=[],e=a.prototype;e;)b=Object.keys(e).reduce(function(a,b){"function"===typeof e[b]&&-1===a.indexOf(b)&&a.push(b);return a},b),e=Object.getPrototypeOf(e);return b},localFunctionNames:function(a){return Object.keys(a.prototype).filter(function(b){return"function"===typeof a.prototype[b]})},logErrors:function(a,b){var e=function(e){var c=Array.prototype.slice.call(arguments);c.shift();try{return e.apply(a,c)}catch(J){if("undefined"!==typeof lively&&lively.morphic&& -lively.morphic.World&&lively.morphic.World.current())throw lively.morphic.World.current().logError(J),J;b?console.warn("ERROR: %s.%s(%s): err: %s %s",a,b,c,J,J.stack||""):console.warn("ERROR: %s %s",J,J.stack||"");throw J;}};e.methodName="$logErrorsAdvice";e=da(a,e);e.originalFunction=a;e.methodName="$logErrorsWrapper";return e},logCompletion:function(a,b){var e=function(e){var c=Array.prototype.slice.call(arguments);c.shift();try{var f=e.apply(a,c)}catch(ya){throw console.warn("failed to load "+ -b+": "+ya),"undefined"!==typeof lively&&lively.lang.Execution&&lively.lang.Execution.showStack(),ya;}console.log("completed "+b);return f};e.methodName="$logCompletionAdvice::"+b;e=da(a,e);e.methodName="$logCompletionWrapper::"+b;e.originalFunction=a;return e},logCalls:function(a,b){var e=function(e){var f=Array.prototype.slice.call(arguments);f.shift();c=e.apply(a,f);b?console.warn("%s(%s) -> %s",O(a),f,c):console.log("%s(%s) -> %s",O(a),f,c);return c};e.methodName="$logCallsAdvice::"+O(a);var c= -da(a,e);c.originalFunction=a;c.methodName="$logCallsWrapper::"+O(a);return c},traceCalls:function(a,b){return da(a,function(e){var c=Array.prototype.slice.call(arguments);c.shift();b.push(c);c=e.apply(a,c);b.pop();return c})},webkitStack:function(){try{throw Error();}catch(e){return String(e.stack).split(/\n/).slice(2).map(function(a){return a.replace(/^\s*at\s*([^\s]+).*/,"$1")}).join("\n")}}}),Ld="function"===typeof Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors:function(a){var b= -{},e;for(e in a)Object.prototype.hasOwnProperty.call(a,e)&&Object.defineProperty(b,e,{configurable:!0,enumerable:!0,writable:!0,value:Object.getOwnPropertyDescriptor(a,e)});return b},Af=Object.freeze({isArray:function(a){return Array.isArray(a)},isElement:function(a){return a&&1==a.nodeType},isFunction:function(a){return a instanceof Function},isBoolean:function(a){return"boolean"==typeof a},isString:function(a){return"string"==typeof a},isNumber:function(a){return"number"==typeof a},isUndefined:function(a){return"undefined"== -typeof a},isRegExp:function(a){return a instanceof RegExp},isObject:function(a){return"object"==typeof a},isPrimitive:Oa,isEmpty:function(a){for(var b in a)if(a.hasOwnProperty(b))return!1;return!0},equals:R,keys:Object.keys,values:ta,select:ka,dissoc:xa,addScript:function(a,b,c,d){b=Z(b);return I(b,a,c,d)},extend:pa,clone:u,extract:function(a,b,c){for(var e={},f=0;f>>32-f,e)}function e(a,e,c,f,d,n,g){return b(e& -c|~e&f,a,e,d,n,g)}function c(a,e,c,f,d,n,g){return b(e&f|c&~f,a,e,d,n,g)}function d(a,e,c,f,d,n,g){return b(c^(e|~f),a,e,d,n,g)}function g(a,f){var n=a[0],g=a[1],w=a[2],r=a[3];n=e(n,g,w,r,f[0],7,-680876936);r=e(r,n,g,w,f[1],12,-389564586);w=e(w,r,n,g,f[2],17,606105819);g=e(g,w,r,n,f[3],22,-1044525330);n=e(n,g,w,r,f[4],7,-176418897);r=e(r,n,g,w,f[5],12,1200080426);w=e(w,r,n,g,f[6],17,-1473231341);g=e(g,w,r,n,f[7],22,-45705983);n=e(n,g,w,r,f[8],7,1770035416);r=e(r,n,g,w,f[9],12,-1958414417);w=e(w,r, -n,g,f[10],17,-42063);g=e(g,w,r,n,f[11],22,-1990404162);n=e(n,g,w,r,f[12],7,1804603682);r=e(r,n,g,w,f[13],12,-40341101);w=e(w,r,n,g,f[14],17,-1502002290);g=e(g,w,r,n,f[15],22,1236535329);n=c(n,g,w,r,f[1],5,-165796510);r=c(r,n,g,w,f[6],9,-1069501632);w=c(w,r,n,g,f[11],14,643717713);g=c(g,w,r,n,f[0],20,-373897302);n=c(n,g,w,r,f[5],5,-701558691);r=c(r,n,g,w,f[10],9,38016083);w=c(w,r,n,g,f[15],14,-660478335);g=c(g,w,r,n,f[4],20,-405537848);n=c(n,g,w,r,f[9],5,568446438);r=c(r,n,g,w,f[14],9,-1019803690); -w=c(w,r,n,g,f[3],14,-187363961);g=c(g,w,r,n,f[8],20,1163531501);n=c(n,g,w,r,f[13],5,-1444681467);r=c(r,n,g,w,f[2],9,-51403784);w=c(w,r,n,g,f[7],14,1735328473);g=c(g,w,r,n,f[12],20,-1926607734);n=b(g^w^r,n,g,f[5],4,-378558);r=b(n^g^w,r,n,f[8],11,-2022574463);w=b(r^n^g,w,r,f[11],16,1839030562);g=b(w^r^n,g,w,f[14],23,-35309556);n=b(g^w^r,n,g,f[1],4,-1530992060);r=b(n^g^w,r,n,f[4],11,1272893353);w=b(r^n^g,w,r,f[7],16,-155497632);g=b(w^r^n,g,w,f[10],23,-1094730640);n=b(g^w^r,n,g,f[13],4,681279174);r=b(n^ -g^w,r,n,f[0],11,-358537222);w=b(r^n^g,w,r,f[3],16,-722521979);g=b(w^r^n,g,w,f[6],23,76029189);n=b(g^w^r,n,g,f[9],4,-640364487);r=b(n^g^w,r,n,f[12],11,-421815835);w=b(r^n^g,w,r,f[15],16,530742520);g=b(w^r^n,g,w,f[2],23,-995338651);n=d(n,g,w,r,f[0],6,-198630844);r=d(r,n,g,w,f[7],10,1126891415);w=d(w,r,n,g,f[14],15,-1416354905);g=d(g,w,r,n,f[5],21,-57434055);n=d(n,g,w,r,f[12],6,1700485571);r=d(r,n,g,w,f[3],10,-1894986606);w=d(w,r,n,g,f[10],15,-1051523);g=d(g,w,r,n,f[1],21,-2054922799);n=d(n,g,w,r,f[8], -6,1873313359);r=d(r,n,g,w,f[15],10,-30611744);w=d(w,r,n,g,f[6],15,-1560198380);g=d(g,w,r,n,f[13],21,1309151649);n=d(n,g,w,r,f[4],6,-145523070);r=d(r,n,g,w,f[11],10,-1120210379);w=d(w,r,n,g,f[2],15,718787259);g=d(g,w,r,n,f[9],21,-343485551);a[0]=h(n,a[0]);a[1]=h(g,a[1]);a[2]=h(w,a[2]);a[3]=h(r,a[3])}var h=function(a,b){var e=(a&65535)+(b&65535);return(a>>16)+(b>>16)+(e>>16)<<16|e&65535},k="0123456789abcdef".split("");return function(a){for(var b=a.length,e=0;e -n;n++)d+=k[f>>8*n+4&15]+k[f>>8*n&15];a[c]=d}return a.join("")}(function(a){var b=a.length,e=[1732584193,-271733879,-1732584194,271733878],c;for(c=64;c<=b;c+=64){var f,d=a.substring(c-64,c),n=[];for(f=0;64>f;f+=4)n[f>>2]=d.charCodeAt(f)+(d.charCodeAt(f+1)<<8)+(d.charCodeAt(f+2)<<16)+(d.charCodeAt(f+3)<<24);g(e,n)}a=a.substring(c-64);f=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];d=a.length;for(c=0;c>2]|=a.charCodeAt(c)<<(c%4<<3);f[c>>2]|=128<<(c%4<<3);if(55=c[0]&&ad)c=f;else return f}return-1},regexIndexOf:function(a,b,c){c=void 0===c?0:c;a=this.substring(c||0).search(b);return 0<=a?a+(c||0):a},regexLastIndexOf:function(a,b,c){c=void 0===c?a.length:c;b=b.global?b:new RegExp(b.source,"g"+(b.ignoreCase?"i":"")+(b.multiLine?"m":""));a=this.substring(0,c+1);c=-1;for(var e=0,f;null!=(f=b.exec(a));)c=f.index,b.lastIndex=++e;return c},lineRanges:Xc, -diff:function(a,b){return"undefined"===typeof JsDiff?"diff not supported":JsDiff.convertChangesToXML(JsDiff.diffWordsWithSpace(a,b))},empty:function(a){return""==a},includes:bf,include:bf,startsWith:String.prototype.startsWith?function(a,b){return a.startsWith(b)}:function(a,b){return 0===a.indexOf(b)},startsWithVowel:function(a){a=a[0];return"A"===a||"E"===a||"I"===a||"O"===a||"U"===a||"a"===a||"e"===a||"i"===a||"o"===a||"u"===a||!1},endsWith:String.prototype.endsWith?function(a,b){return a.endsWith(b)}: -function(a,b){var e=a.length-b.length;return 0<=e&&a.lastIndexOf(b)===e},withDecimalPrecision:function(a,b){var e=parseFloat(a);return isNaN(e)?a:e.toFixed(b)},capitalize:Md,camelCaseString:function(a){return a.split(" ").map(Md).join("")},camelize:function(a){var b=a.split("-"),e=b.length;if(1==e)return b[0];a="-"==a.charAt(0)?b[0].charAt(0).toUpperCase()+b[0].substring(1):b[0];for(var c=1;cb?a.slice(0,b-c.length)+c:String(a)},truncateLeft:function(a,b,c){b=b||30;return a.length>b?(void 0===c?"...":c)+a.slice(-b):String(a)},regExpEscape:function(a){return a.replace(/([-()\[\]{}+?*.$\^|,:# -b?"":Array(b+1).join(a)},longestCommonSubstring:function(a,b){for(var e=[],c=0;cb.length){var c=a;a=b;b=c}var f=Array(a.length+1);for(c=0;c<=a.length;c++)f[c]=c;for(c=1;c<=b.length;c++){var d=c;for(e=1;e<=a.length;e++){var g=b[c-1]===a[e-1]?f[e-1]:Math.min(f[e-1]+1,Math.min(d+1,f[e]+1));f[e-1]=d;d=g}f[a.length]=d}return f[a.length]}}),th=function(a,b){var e,c=!1;return function(a,b){if(c)return c=!1,e*b+a;do{var f=2*Math.random()-1;var d=2*Math.random()-1;var n= -f*f+d*d}while(1<=n||0==n);n=Math.sqrt(-2*Math.log(n)/n);e=d*n;c=!0;return a+b*f*n}}(),cf=function(){function a(b,e){if("cm"===e)return b;if("mm"===e)return.1*b;if("in"===e)return 2.54*b;if("px"===e)return b*a(1/96,"in");if("pt"===e)return b*a(1/72,"in");if("pc"===e)return b*a(12,"pt")}return function J(b,e,c){return e===c?b:"cm"===c?a(b,e):"cm"===e?b/a(1,c):J(J(b,e,"cm"),"cm",c)}}(),Cf=Object.freeze({random:function(a,b){a=a||0;return Math.round(Math.random()*((b||100)-a)+a)},normalRandom:th,randomSmallerInteger:function(a){return Math.floor(Math.random()* -a)},humanReadableByteSize:function(a){if(1E3>a)return String(Math.round(100*a)/100)+"B";a/=1024;return 1E3>a?String(Math.round(100*a)/100)+"KB":String(Math.round(a/1024*100)/100)+"MB"},average:function(a){return a.reduce(function(a,b){return a+b},0)/a.length},averageInc:function(a,b,c){return(a-b)/c+b},median:function(a){var b=a.sort(function(a,b){return b-a});a=a.length;return 0===a%2?.5*(b[a/2-1]+b[a/2]):b[(a-1)/2]},between:Yc,sort:function(a){return a.sort(function(a,b){return a-b})},parseLength:function(a, -b){b=b||"px";if((a=a.match(/([0-9\.]+)\s*(.*)/))&&a[1]){var e=parseFloat(a[1]);return cf(e,a[2],b)}},convertLength:cf,roundTo:Od,detent:function(a,b,c,d){var e=Od(a,c);return Math.abs(a-e)m?"a":"p",tt:12>m?"am":"pm",T:12>m?"A":"P",TT:12>m?"AM":"PM",Z:g?"UTC":(String(f).match(e)||[""]).pop().replace(c,""),o:(0g)k.push(h),1h&&0===g)k.push(b),1b&&0===h&&0===g)k.push(a),1 "+b;l&&(f+="\n"+("undefined"!==typeof lively?lively.printStack():console.trace()));a.verbose&&(console.log(f),"undefined"!==typeof show&&show(f));if(k)debugger;return e[d]=b}),e.__defineGetter__(c,function(){if(a.onGet)a.onGet(e[d]);return e[d]}),b="Watcher for "+ -e+"."+c+" installed",console.log(b),"undefined"!==typeof show&&show(b)))}},debugFunctionWrapper:function(a){var b=a.target,e=this.get(b,-1),c=this.parts().slice(-1)[0],d=void 0===a.haltWhenChanged?!0:a.haltWhenChanged,g=a.showStack,h=e&&c&&e[c],k=h&&h.isDebugFunctionWrapper;b&&c&&h&&e&&(a.uninstall?k&&(e[c]=e[c].debugTargetFunction,h="Uninstalled debugFunctionWrapper for "+e+"."+c,console.log(h),"undefined"!==typeof show&&show(h),show(h)):(k?h="debugFunctionWrapper for "+e+"."+c+" already installed": -(b=e[c]=h.wrap(function(b){var f=Array.from(arguments);if(d)debugger;g&&show(lively.printStack());a.verbose&&show(c+" called");return f.shift().apply(e,f)}),b.isDebugFunctionWrapper=!0,b.debugTargetFunction=h,h="debugFunctionWrapper for "+e+"."+c+" installed"),console.log(h),"undefined"!==typeof show&&show(h)))}});var se="undefined"!==typeof process&&process.versions&&process.versions.node?function(a,b){if(a.on&&a.removeListener)return a;var e="undefined"!==typeof System?System._nodeRequire("events"): -require("events");Object.assign(a,e.EventEmitter.prototype);e.EventEmitter.call(a);b&&b.maxListenerLimit&&a.setMaxListeners(b.maxListenerLimit);return a}:function(a){if(a.on&&a.removeListener)return a;a.listeners={};a.on=function(b,e){e&&(a.listeners[b]||(a.listeners[b]=[]),a.listeners[b].push(e))};a.once=function(b,e){function c(){a.removeListener(b,c);e.apply(this,arguments)}if(e)a.on(b,c)};a.removeListener=function(b,e){a.listeners[b]&&(a.listeners[b]=a.listeners[b].filter(function(a){return a!== -e}))};a.removeAllListeners=function(b){a.listeners[b]&&(a.listeners[b]=[])};a.emit=function(){var b=Array.prototype.slice.call(arguments),e=b.shift();(e=a.listeners[e])&&e.length&&e.forEach(function(a){try{a.apply(null,b)}catch(w){console.error("Error in event handler: %s",w.stack||String(w))}})};return a};B.prototype.accept=function(a,b,c){if(!a)throw Error("Undefined AST node in Visitor.accept:\n "+c.join(".")+"\n "+a);if(!a.type)throw Error("Strangee AST node without type in Visitor.accept:\n "+ -c.join(".")+"\n "+JSON.stringify(a));switch(a.type){case "Node":return this.visitNode(a,b,c);case "SourceLocation":return this.visitSourceLocation(a,b,c);case "Position":return this.visitPosition(a,b,c);case "Program":return this.visitProgram(a,b,c);case "Function":return this.visitFunction(a,b,c);case "Statement":return this.visitStatement(a,b,c);case "Directive":return this.visitDirective(a,b,c);case "SwitchCase":return this.visitSwitchCase(a,b,c);case "CatchClause":return this.visitCatchClause(a, -b,c);case "VariableDeclarator":return this.visitVariableDeclarator(a,b,c);case "Expression":return this.visitExpression(a,b,c);case "Property":return this.visitProperty(a,b,c);case "Pattern":return this.visitPattern(a,b,c);case "Super":return this.visitSuper(a,b,c);case "SpreadElement":return this.visitSpreadElement(a,b,c);case "TemplateElement":return this.visitTemplateElement(a,b,c);case "Class":return this.visitClass(a,b,c);case "ClassBody":return this.visitClassBody(a,b,c);case "MethodDefinition":return this.visitMethodDefinition(a, -b,c);case "ModuleDeclaration":return this.visitModuleDeclaration(a,b,c);case "ModuleSpecifier":return this.visitModuleSpecifier(a,b,c);case "JSXEmptyExpression":return this.visitJSXEmptyExpression(a,b,c);case "JSXExpressionContainer":return this.visitJSXExpressionContainer(a,b,c);case "JSXSpreadChild":return this.visitJSXSpreadChild(a,b,c);case "JSXBoundaryElement":return this.visitJSXBoundaryElement(a,b,c);case "JSXAttribute":return this.visitJSXAttribute(a,b,c);case "JSXText":return this.visitJSXText(a, -b,c);case "JSXOpeningFragment":return this.visitJSXOpeningFragment(a,b,c);case "JSXClosingFragment":return this.visitJSXClosingFragment(a,b,c);case "Identifier":return this.visitIdentifier(a,b,c);case "Literal":return this.visitLiteral(a,b,c);case "ExpressionStatement":return this.visitExpressionStatement(a,b,c);case "BlockStatement":return this.visitBlockStatement(a,b,c);case "EmptyStatement":return this.visitEmptyStatement(a,b,c);case "DebuggerStatement":return this.visitDebuggerStatement(a,b,c); -case "WithStatement":return this.visitWithStatement(a,b,c);case "ReturnStatement":return this.visitReturnStatement(a,b,c);case "LabeledStatement":return this.visitLabeledStatement(a,b,c);case "BreakStatement":return this.visitBreakStatement(a,b,c);case "ContinueStatement":return this.visitContinueStatement(a,b,c);case "IfStatement":return this.visitIfStatement(a,b,c);case "SwitchStatement":return this.visitSwitchStatement(a,b,c);case "ThrowStatement":return this.visitThrowStatement(a,b,c);case "TryStatement":return this.visitTryStatement(a, -b,c);case "WhileStatement":return this.visitWhileStatement(a,b,c);case "DoWhileStatement":return this.visitDoWhileStatement(a,b,c);case "ForStatement":return this.visitForStatement(a,b,c);case "ForInStatement":return this.visitForInStatement(a,b,c);case "Declaration":return this.visitDeclaration(a,b,c);case "ThisExpression":return this.visitThisExpression(a,b,c);case "ArrayExpression":return this.visitArrayExpression(a,b,c);case "ObjectExpression":return this.visitObjectExpression(a,b,c);case "FunctionExpression":return this.visitFunctionExpression(a, -b,c);case "UnaryExpression":return this.visitUnaryExpression(a,b,c);case "UpdateExpression":return this.visitUpdateExpression(a,b,c);case "BinaryExpression":return this.visitBinaryExpression(a,b,c);case "AssignmentExpression":return this.visitAssignmentExpression(a,b,c);case "LogicalExpression":return this.visitLogicalExpression(a,b,c);case "MemberExpression":return this.visitMemberExpression(a,b,c);case "ConditionalExpression":return this.visitConditionalExpression(a,b,c);case "CallExpression":return this.visitCallExpression(a, -b,c);case "NewExpression":return this.visitNewExpression(a,b,c);case "SequenceExpression":return this.visitSequenceExpression(a,b,c);case "ArrowFunctionExpression":return this.visitArrowFunctionExpression(a,b,c);case "YieldExpression":return this.visitYieldExpression(a,b,c);case "TemplateLiteral":return this.visitTemplateLiteral(a,b,c);case "TaggedTemplateExpression":return this.visitTaggedTemplateExpression(a,b,c);case "AssignmentProperty":return this.visitAssignmentProperty(a,b,c);case "ObjectPattern":return this.visitObjectPattern(a, -b,c);case "ArrayPattern":return this.visitArrayPattern(a,b,c);case "RestElement":return this.visitRestElement(a,b,c);case "AssignmentPattern":return this.visitAssignmentPattern(a,b,c);case "ClassExpression":return this.visitClassExpression(a,b,c);case "MetaProperty":return this.visitMetaProperty(a,b,c);case "ImportDeclaration":return this.visitImportDeclaration(a,b,c);case "ImportSpecifier":return this.visitImportSpecifier(a,b,c);case "ImportDefaultSpecifier":return this.visitImportDefaultSpecifier(a, -b,c);case "ImportNamespaceSpecifier":return this.visitImportNamespaceSpecifier(a,b,c);case "ExportNamedDeclaration":return this.visitExportNamedDeclaration(a,b,c);case "ExportSpecifier":return this.visitExportSpecifier(a,b,c);case "ExportDefaultDeclaration":return this.visitExportDefaultDeclaration(a,b,c);case "ExportAllDeclaration":return this.visitExportAllDeclaration(a,b,c);case "AwaitExpression":return this.visitAwaitExpression(a,b,c);case "JSXMemberExpression":return this.visitJSXMemberExpression(a, -b,c);case "JSXNamespacedName":return this.visitJSXNamespacedName(a,b,c);case "JSXOpeningElement":return this.visitJSXOpeningElement(a,b,c);case "JSXClosingElement":return this.visitJSXClosingElement(a,b,c);case "JSXSpreadAttribute":return this.visitJSXSpreadAttribute(a,b,c);case "JSXElement":return this.visitJSXElement(a,b,c);case "JSXFragment":return this.visitJSXFragment(a,b,c);case "RegExpLiteral":return this.visitRegExpLiteral(a,b,c);case "FunctionBody":return this.visitFunctionBody(a,b,c);case "FunctionDeclaration":return this.visitFunctionDeclaration(a, -b,c);case "VariableDeclaration":return this.visitVariableDeclaration(a,b,c);case "ForOfStatement":return this.visitForOfStatement(a,b,c);case "ClassDeclaration":return this.visitClassDeclaration(a,b,c);case "JSXIdentifier":return this.visitJSXIdentifier(a,b,c)}throw Error("No visit function in AST visitor Visitor for:\n "+c.join(".")+"\n "+JSON.stringify(a));};B.prototype.visitNode=function(a,b,c){return a};B.prototype.visitSourceLocation=function(a,b,c){a.start=this.accept(a.start,b,c.concat(["start"])); -a.end=this.accept(a.end,b,c.concat(["end"]));return a};B.prototype.visitPosition=function(a,b,c){return a};B.prototype.visitProgram=function(a,b,c){for(var e=[],f=0;f=a&&(a=1);return 1===a?n.yield(c._propfind(),5):n.yield(c.dirList(1,b),4)}if(5!=n.nextAddress)return d=n.yieldResult,g=d.filter(function(a){return a.isDirectory()}),n.return(Promise.all(g.map(function(c){return c.dirList("number"=== -typeof a?a-1:a,b)})).then(function(a){return a.reduce(function(a,b){return a.concat(b)},d)}));h=n.yieldResult;h.shift();f&&(h=pd(f,h));return n.return(h)})};Ha.prototype.readProperties=function(a){var b=this,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(a){if(1==a.nextAddress)return a.yield(b._propfind(),2);c=a.yieldResult[0];return a.return(b.assignProperties(c))})};Ha.prototype.post=function(a){a=void 0===a?null:a;var b=this,c,e,d;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){switch(f.nextAddress){case 1:return"string"!== -typeof a&&(a=JSON.stringify(a)),f.yield(gb(b,"POST",a,{}),2);case 2:return c=f.yieldResult,f.setCatchFinallyBlocks(3),f.yield(c.text(),5);case 5:e=f.yieldResult;f.leaveTryBlock(4);break;case 3:f.enterCatchBlock();case 4:if(e&&"application/json"===c.headers.get("content-type"))try{d=JSON.parse(e)}catch(ya){}if(!c.ok&&b.errorOnHTTPStatusCodes)throw Error("Error in POST "+b.url+": "+(e||c.statusText));return f.return(d||e)}})};Ha.prototype.copyTo=function(a,b){b=void 0===b?!0:b;var c=this,e;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){if(c.isFile()&& -(e=a.isFile()?a:a.join(c.name()),Dh)){if(e.isHTTPResource)return d.return(c._copyTo_file_nodejs_http(e,b));if(e.isNodeJSFileResource)return d.return(c._copyTo_file_nodejs_fs(e,b))}return d.return(Q.prototype.copyTo.call(c,a,b))})};Ha.prototype._copyFrom_file_nodejs_fs=function(a,b){b=void 0===b?!0:b;var c=this,e,d,f;return $jscomp.asyncExecutePromiseGeneratorProgram(function(g){if(1==g.nextAddress)return b?g.yield(c.parent().ensureExistance(),2):g.jumpTo(2);if(4!=g.nextAddress)return d=a._createReadStream(), -d.on("error",function(a){return e=a}),g.yield(gb(c,"PUT",d),4);f=g.yieldResult;if(e)throw e;if(!f.ok&&c.errorOnHTTPStatusCodes)throw Error("copyTo: Cannot GET: "+f.statusText+" "+f.status);return g.return(c)})};Ha.prototype._copyTo_file_nodejs_fs=function(a,b){b=void 0===b?!0:b;var c=this,e,d;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){if(1==f.nextAddress)return b?f.yield(a.parent().ensureExistance(),2):f.jumpTo(2);if(4!=f.nextAddress)return f.yield(gb(c,"GET"),4);e=f.yieldResult; -if(!e.ok&&c.errorOnHTTPStatusCodes)throw Error("copyTo: Cannot GET: "+e.statusText+" "+e.status);return f.return(new Promise(function(b,f){return e.body.pipe(a._createWriteStream()).on("error",function(a){return d=a}).on("finish",function(){return d?f(d):b(c)})}))})};Ha.prototype._copyTo_file_nodejs_http=function(a,b){b=void 0===b?!0:b;var c=this,e,d;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){switch(f.nextAddress){case 1:if(!b){f.jumpTo(2);break}return f.yield(a.parent().ensureExistance(), -2);case 2:return f.yield(gb(c,"GET"),4);case 4:e=f.yieldResult;if(!e.ok&&c.errorOnHTTPStatusCodes)throw Error("copyTo: Cannot GET: "+e.statusText+" "+e.status);return f.yield(gb(a,"PUT",e.body),5);case 5:d=f.yieldResult;if(!e.ok&&c.errorOnHTTPStatusCodes)throw Error("copyTo: Cannot PUT: "+d.statusText+" "+d.status);f.jumpToEnd()}})};$jscomp.global.Object.defineProperties(Ha.prototype,{isHTTPResource:{configurable:!0,enumerable:!0,get:function(){return!0}}});var Eh={name:"http-webdav-resource",matches:function(a){return a.startsWith("http:")|| -a.startsWith("https:")},resourceClass:Ha},Fh=vb(F.readFile),Gh=vb(F.writeFile),Hh=function(a){return new Promise(function(b,c){return F.exists(a,function(a){return b(!!a)})})},Ih=vb(F.readdir),Jh=vb(F.mkdir),Kh=vb(F.rmdir),Lh=vb(F.unlink),Mh=vb(F.lstat),Nh=vb(F.rename),Fa=function(){return Q.apply(this,arguments)||this};$jscomp.inherits(Fa,Q);Fa.prototype.path=function(){return this.url.replace("file://","")};Fa.prototype.stat=function(){var a=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(b){return b.return(Mh(a.path()))})}; -Fa.prototype.read=function(){var a=this,b;return $jscomp.asyncExecutePromiseGeneratorProgram(function(c){b=Fh(a.path());return c.return(a.binary?b:b.then(String))})};Fa.prototype.write=function(a){var b=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(c){if(1==c.nextAddress){if(b.isDirectory())throw Error("Cannot write into a directory: "+b.path());return c.yield(Gh(b.path(),a),2)}return c.return(b)})};Fa.prototype.mkdir=function(){var a=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(b){if(1== -b.nextAddress){if(a.isFile())throw Error("Cannot mkdir on a file: "+a.path());return b.yield(Jh(a.path()),2)}return b.return(a)})};Fa.prototype.exists=function(){var a=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(b){return b.return(a.isRoot()?!0:Hh(a.path()))})};Fa.prototype.dirList=function(a,b){a=void 0===a?1:a;b=void 0===b?{}:b;var c=this,e,d,f,g,h,k,l,m,p,q,t,u;return $jscomp.asyncExecutePromiseGeneratorProgram(function(n){switch(n.nextAddress){case 1:if("number"!==typeof a&& -"infinity"!==a)throw Error("dirList \u2013 invalid depth argument: "+a);e=b;d=e.exclude;0>=a&&(a=1);if(1!==a){n.jumpTo(2);break}f=[];g=$jscomp;h=g.makeIterator;return n.yield(Ih(c.path()),3);case 3:k=h.call(g,n.yieldResult),l=k.next();case 4:if(l.done){n.jumpTo(6);break}m=l.value;p=c.join(m);return n.yield(p.stat(),7);case 7:q=n.yieldResult;p=q.isDirectory()?p.asDirectory():p;p._assignPropsFromStat(q);f.push(p);l=k.next();n.jumpTo(4);break;case 6:return d&&(f=pd(d,f)),n.return(f);case 2:return n.yield(c.dirList(1, -b),8);case 8:return t=n.yieldResult,u=t.filter(function(a){return a.isDirectory()}),n.return(Promise.all(u.map(function(c){return c.dirList("number"===typeof a?a-1:a,b)})).then(function(a){return a.reduce(function(a,b){return a.concat(b)},t)}))}})};Fa.prototype.isEmptyDirectory=function(){var a=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(b){return 1==b.nextAddress?b.yield(a.dirList(),2):b.return(0===b.yieldResult.length)})};Fa.prototype.rename=function(a){var b=this,c,e,d,g,h, -k,l,m,p,q,t,u,v;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){switch(f.nextAddress){case 1:if(!(a instanceof b.constructor))return f.return(Q.prototype.rename.call(b,a));if(b.isFile()){a=a.asFile();Nh(b.path(),a.path());f.jumpTo(2);break}a=a.asDirectory();return f.yield(a.ensureExistance(),3);case 3:return c=[],e=[],d=$jscomp,g=d.makeIterator,f.yield(b.dirList("infinity"),4);case 4:h=g.call(d,f.yieldResult);for(k=h.next();!k.done;k=h.next())l=k.value,l.isDirectory()?e.push(l):c.push(l); -m=$jscomp.makeIterator(e);p=m.next();case 5:if(p.done){f.jumpTo(7);break}q=p.value;return f.yield(a.join(q.relativePathFrom(b)).ensureExistance(),6);case 6:p=m.next();f.jumpTo(5);break;case 7:t=$jscomp.makeIterator(c),u=t.next();case 9:if(u.done)return f.yield(b.remove(),2);v=u.value;return f.yield(v.rename(a.join(v.relativePathFrom(b))),10);case 10:u=t.next();f.jumpTo(9);break;case 2:return f.return(a)}})};Fa.prototype.remove=function(){var a=this,b,c,d,g,h;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){switch(e.nextAddress){case 1:return e.yield(a.exists(), -2);case 2:if(!e.yieldResult){e.jumpTo(3);break}return a.isDirectory()?(b=$jscomp,c=b.makeIterator,e.yield(a.dirList(),7)):e.yield(Lh(a.path()),3);case 7:d=c.call(b,e.yieldResult),g=d.next();case 8:if(g.done)return e.yield(Kh(a.path()),3);h=g.value;return e.yield(h.remove(),9);case 9:g=d.next();e.jumpTo(8);break;case 3:return e.return(a)}})};Fa.prototype.readProperties=function(){var a=this,b,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){return 1==e.nextAddress?(b=a,c=b._assignPropsFromStat, -e.yield(a.stat(),2)):e.return(c.call(b,e.yieldResult))})};Fa.prototype.copyTo=function(a,b){b=void 0===b?!0:b;var c=this,e;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){return c.isFile()&&(e=a.isFile()?a:a.join(c.name()),e.isHTTPResource)?d.return(e._copyFrom_file_nodejs_fs(c,b=!0)):d.return(Q.prototype.copyTo.call(c,a,b))})};Fa.prototype._assignPropsFromStat=function(a){return this.assignProperties({lastModified:a.mtime,created:a.ctime,size:a.size,type:a.isDirectory()?"directory": -"file",isLink:a.isSymbolicLink()})};Fa.prototype._createWriteStream=function(){return F.createWriteStream(this.path())};Fa.prototype._createReadStream=function(){return F.createReadStream(this.path())};$jscomp.global.Object.defineProperties(Fa.prototype,{isNodeJSFileResource:{configurable:!0,enumerable:!0,get:function(){return!0}}});var kc=function(a,b){"file:///"!==a.slice(0,8)&&"file://"===a.slice(0,7)&&(a="file:///"+a.slice(7));a.includes("\\")&&(a=a.replace(/\\/g,"/"));return Fa.call(this,a,b)|| -this};$jscomp.inherits(kc,Fa);kc.prototype.path=function(){return this.url.replace("file:///","")};kc.prototype.isRoot=function(){return!!this.path().match(yh)};kc.prototype.root=function(){if(this.isRoot())return this;console.log(this.url);var a=this.url.match(wh);if(a)return this.newResource(a[0]);throw Error("Could not determine root path of windows file resource for url "+this.url);};var Oh={name:"nodejs-file-resource",matches:function(a){return a.startsWith("file:")},resourceClass:"undefined"!= -typeof process&&"win32"===process.platform?kc:Fa},gf=/\//g,Za=function(a,b){b=void 0===b?{}:b;if(!a||"string"!==typeof a)throw Error("LocalResourceInMemoryBackend needs name!");this.name=a;this._filespec=b};Za.removeHost=function(a){delete this.hosts[a]};Za.ensure=function(a,b){var c=this;b=void 0===b?{}:b;var e=this.named(b.host);return Promise.resolve().then(function(){return a?te("local://"+e.name,a):null}).then(function(){return c})};Za.named=function(a){a||(a="default");return this.hosts[a]|| -(this.hosts[a]=new this(a))};Za.prototype.get=function(a){return this._filespec[a]};Za.prototype.set=function(a,b){this._filespec[a]=b};Za.prototype.write=function(a,b){var c=this._filespec[a];c||(c=this._filespec[a]={created:new Date});c.content=b;c.isDirectory=!1;c.lastModified=new Date};Za.prototype.read=function(a){return(a=this._filespec[a])&&a.content?a.content:""};Za.prototype.mkdir=function(a){var b=this._filespec[a];b&&b.isDirectory||(b||(b=this._filespec[a]={created:new Date}),b.content&& -delete b.content,b.isDirectory=!0,b.lastModified=new Date)};Za.prototype.partialFilespec=function(a,b){a=void 0===a?"/":a;b=void 0===b?Infinity:b;for(var c={},e=this.filespec,d=Object.keys(e),f=0;fb||(c[g]=e[g])}}return c};$jscomp.global.Object.defineProperties(Za.prototype,{filespec:{configurable:!0,enumerable:!0,get:function(){return this._filespec},set:function(a){this._filespec= -a}}});$jscomp.global.Object.defineProperties(Za,{hosts:{configurable:!0,enumerable:!0,get:function(){return this._hosts||(this._hosts={})}}});var jb=function(){return Q.apply(this,arguments)||this};$jscomp.inherits(jb,Q);jb.prototype.read=function(){return Promise.resolve(this.localBackend.read(this.path()))};jb.prototype.write=function(a){if(this.isDirectory())throw Error("Cannot write into a directory! ("+this.url+")");var b=this.localBackend.get(this.path());if(b&&b.isDirectory)throw Error(this.url+ -" already exists and is a directory (cannot write into it!)");this.localBackend.write(this.path(),a);return Promise.resolve(this)};jb.prototype.mkdir=function(){if(!this.isDirectory())throw Error("Cannot mkdir a file! ("+this.url+")");var a=this.localBackend.get(this.path());if(a&&a.isDirectory)return Promise.resolve(this);if(a&&!a.isDirectory)throw Error(this.url+" already exists and is a file (cannot mkdir it!)");this.localBackend.mkdir(this.path());return Promise.resolve(this)};jb.prototype.exists= -function(){return Promise.resolve(this.isRoot()||this.path()in this.localBackend.filespec)};jb.prototype.remove=function(){var a=this,b=this.path();Object.keys(this.localBackend.filespec).forEach(function(c){return c.startsWith(b)&&delete a.localBackend.filespec[c]});return Promise.resolve(this)};jb.prototype.readProperties=function(){throw Error("not yet implemented");};jb.prototype.dirList=function(a,b){a=void 0===a?1:a;b=void 0===b?{}:b;if(!this.isDirectory())return this.asDirectory().dirList(a, -b);b=b.exclude;var c=this.path(),e=[],d=Object.keys(this.localBackend.filespec);"infinity"===a&&(a=Infinity);for(var f={},g=0;ga?(f.$jscomp$loop$prop$dirToChild$120=this.join(h.split("/").slice(0,a).join("/")+"/"),e.some(function(a){return function(b){return b.equals(a.$jscomp$loop$prop$dirToChild$120)}}(f))||e.push(f.$jscomp$loop$prop$dirToChild$120)): -(h=this.join(h),b&&!tg(h,b)||e.push(h)))}return Promise.resolve(e)};$jscomp.global.Object.defineProperties(jb.prototype,{localBackend:{configurable:!0,enumerable:!0,get:function(){return Za.named(this.host())}}});Hc({name:"local-resource",matches:function(a){return a.startsWith("local:")},resourceClass:jb});Hc(Eh);Hc(Oh);var Jc=ia.funcCall,Tb=ia.member,Kc=ia.literal,rd=System.get("@system-env").node,Jb=function(){};Jb.prototype.cacheModuleSource=function(a,b,c){throw Error("not yet implemented"); -};Jb.prototype.fetchStoredModuleSource=function(a){throw Error("not yet implemented");};Jb.prototype.deleteCachedData=function(a){throw Error("not yet implemented");};$jscomp.global.Object.defineProperties(Jb,{earliestDate:{configurable:!0,enumerable:!0,get:function(){return+new Date("Sun Nov 06 2016 16:00:00 GMT-0800 (PST)")}}});var Dd=null,ib=function(){return Jb.apply(this,arguments)||this};$jscomp.inherits(ib,Jb);ib.prototype.ensurePath=function(a){var b=this,c,e,d,g,h,k,l;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){switch(f.nextAddress){case 1:return f.yield(b.moduleCacheDir.join(a).exists(), -2);case 2:if(f.yieldResult)return f.return();c="";g=$jscomp.makeIterator(a.split("/"));h=g.next();case 3:if(h.done){f.jumpTo(0);break}k=h.value;c+=k+"/";e=b.moduleCacheDir.join(c);return f.yield(e.exists(),6);case 6:if(f.yieldResult){f.jumpTo(7);break}f.setCatchFinallyBlocks(8);return f.yield(e.mkdir(),10);case 10:f.leaveTryBlock(7);break;case 8:if(l=f.enterCatchBlock(),"EEXIST"!=l.code)throw l;case 7:return e=ea("file://"+c+"/package.json"),f.yield(e.exists(),11);case 11:if(!f.yieldResult){f.jumpTo(4); -break}return f.yield(e.read(),13);case 13:return d=f.yieldResult,f.yield(b.moduleCacheDir.join(c+"/package.json").write(d),4);case 4:h=g.next(),f.jumpTo(3)}})};ib.prototype.dumpModuleCache=function(){var a=this,b,c,d,g,h,k;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){switch(e.nextAddress){case 1:c=e.forIn(System._nodeRequire("module").Module._cache);case 2:if(null==(b=c.getNext())){e.jumpTo(0);break}d=ea("file://"+b);return e.yield(d.exists(),5);case 5:if(!e.yieldResult){e.jumpTo(2); -break}g=a;h=g.cacheModuleSource;k=b;return e.yield(d.read(),8);case 8:return e.yield(h.call(g,k,"NO_HASH",e.yieldResult),2)}})};ib.prototype.fetchStoredModuleSource=function(a){var b=this,c,e,d,g,h,k,l;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){switch(f.nextAddress){case 1:return a=a.replace("file://",""),c=a.match(/([^\/]*.)\.js/)[0],e=a.replace(c,""),d=b.moduleCacheDir.join(a),f.yield(d.exists(),2);case 2:return f.yieldResult?f.yield(d.stat(),3):f.return(null);case 3:return g= -f.yieldResult,h=g.birthtime,f.yield(d.read(),4);case 4:return k=f.yieldResult,f.yield(b.moduleCacheDir.join(e+"/.hash_"+c).read(),5);case 5:return l=f.yieldResult,f.return({source:k,timestamp:h,hash:l})}})};ib.prototype.cacheModuleSource=function(a,b,c){var e=this,d,f;return $jscomp.asyncExecutePromiseGeneratorProgram(function(g){return 1==g.nextAddress?(a=a.replace("file://",""),d=a.match(/([^\/]*.)\.js/)[0],f=a.replace(d,""),g.yield(e.ensurePath(f),2)):3!=g.nextAddress?g.yield(e.moduleCacheDir.join(a).write(c), -3):g.yield(e.moduleCacheDir.join(f+"/.hash_"+d).write(b),0)})};ib.prototype.deleteCachedData=function(a){var b=this,c,e;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){return 1==d.nextAddress?(a=a.replace("file://",""),c=a.match(/([^\/]*.)\.js/)[0],a.replace(c,""),e=b.moduleCacheDir.join(a),d.yield(e.exists(),2)):3!=d.nextAddress?d.yieldResult?d.yield(e.remove(),3):d.return(!1):d.return(!0)})};$jscomp.global.Object.defineProperties(ib.prototype,{moduleCacheDir:{configurable:!0,enumerable:!0, -get:function(){if(!Dd){var a=System._nodeRequire("fs"),b=System._nodeRequire("path"),c="win32"===process.platform;b=c||"/"!==process.cwd()?process.cwd():b.join(process.env.HOME,".lively.next");Dd=c?"file:///"+b.replace(/\\/g,"/"):"file://"+b;a.existsSync(b)||a.mkdirSync(b)}return ea(Dd+"/.module_cache/")}}});var hb=function(a){this.version=2;this.sourceCodeCacheStoreName="sourceCodeStore";this.dbName=void 0===a?"lively.modules-module-translation-cache":a;this.db=this.openDb();return this};$jscomp.inherits(hb, -Jb);hb.prototype.openDb=function(){var a=this,b=System.global.indexedDB.open(this.version);return new Promise(function(c,e){b.onsuccess=function(a){c(this.result)};b.onerror=function(a){return e(a.target)};b.onupgradeneeded=function(b){return b.currentTarget.result.createObjectStore(a.sourceCodeCacheStoreName,{keyPath:"moduleId"})}})};hb.prototype.deleteDb=function(){var a=System.global.indexedDB.deleteDatabase(this.dbName);return new Promise(function(b,c){a.onerror=function(a){return c(a.target)}; -a.onsuccess=function(a){return b(a)}})};hb.prototype.closeDb=function(){var a=this,b,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){if(1==e.nextAddress)return e.yield(a.db,2);b=e.yieldResult;c=b.close();return e.return(new Promise(function(a,b){c.onsuccess=function(b){a(this.result)};c.onerror=function(a){return b(a.target.errorCode)}}))})};hb.prototype.cacheModuleSource=function(a,b,c){var e=this,d;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){if(1==f.nextAddress)return f.yield(e.db, -2);d=f.yieldResult;return f.return(new Promise(function(f,g){var h=d.transaction([e.sourceCodeCacheStoreName],"readwrite"),n=h.objectStore(e.sourceCodeCacheStoreName),k=Date.now();n.put({moduleId:a,hash:b,source:c,timestamp:k});h.oncomplete=f;h.onerror=g}))})};hb.prototype.fetchStoredModuleSource=function(a){var b=this,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){if(1==e.nextAddress)return e.yield(b.db,2);c=e.yieldResult;return e.return(new Promise(function(e,d){var f=c.transaction([b.sourceCodeCacheStoreName]).objectStore(b.sourceCodeCacheStoreName).get(a); -f.onerror=d;f.onsuccess=function(a){return e(f.result)}}))})};hb.prototype.deleteCachedData=function(a){var b=this,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){if(1==e.nextAddress)return e.yield(b.db,2);c=e.yieldResult;return e.return(new Promise(function(e,d){var f=c.transaction([b.sourceCodeCacheStoreName],"readwrite").objectStore(b.sourceCodeCacheStoreName).delete(a);f.onerror=d;f.onsuccess=function(a){return e(f.result)}}))})};System.decanonicalize("lively.modules/node_modules/"); -var yg=[function(a){return!a.endsWith(".js")&&!a.endsWith(".jsx")},function(a){return a.endsWith("dist/acorn.js")||a.endsWith("dist/escodegen.browser.js")||a.endsWith("bowser.js")||a.endsWith("TweenMax.min.js")},function(a){return a.endsWith("babel-core/browser.js")||a.endsWith("system.src.js")||a.includes("systemjs-plugin-babel")}],La=function(a){this.System=a;this._notificationHandlers=null;this.clearCache();this.subscribeToSystemChanges()};La.forSystem=function(a){var b=a["__lively.modules__modulePackageMapCache"]; -if(b)return b;b=new this(a);return a["__lively.modules__modulePackageMapCache"]=b};La.prototype.subscribeToSystemChanges=function(){var a=this;if(!this._notificationHandlers){var b=this.System;this._notificationHandlers=[ub("lively.modules/moduleloaded",function(b){return a.addModuleIdToCache(b.module)},b),ub("lively.modules/moduleunloaded",function(b){return a.removeModuleFromCache(b.module)},b),ub("lively.modules/packageregistered",function(b){return a.clearCache()},b),ub("lively.modules/packageremoved", -function(b){return a.clearCache()},b)]}};La.prototype.unsubscribeFromSystemChanges=function(){if(this._notificationHandlers){var a=this.System;Gb("lively.modules/moduleloaded",this._notificationHandlers[0],a);Gb("lively.modules/moduleunloaded",this._notificationHandlers[1],a);Gb("lively.modules/packageregistered",this._notificationHandlers[2],a);Gb("lively.modules/packageremoved",this._notificationHandlers[3],a);this._notificationHandlers=null}};La.prototype.clearCache=function(){this._cacheInitialized= -!1;this.packageToModule={};this.modulesToPackage={};this.modulesWithoutPackage={}};La.prototype.ensureCache=function(){var a=this.System,b=this.packageToModule,c=this.modulesToPackage,g=this.modulesWithoutPackage;if(this._cacheInitialized)return this;for(var h=ca.allPackageURLs(a),k=0;k>lookup of "+a+": Invalid version - "+b);e=ta(e.versions).filter(function(e){return c.matches(e,a,b)});return 1>=e.length? -e[0]:N(this.sortPackagesByVersion(e))};aa.prototype.findPackageDependency=function(a,b,c){c||(c=a.dependencies[b]||a.devDependencies[b]);g.validRange(c,!0)||(c=null);return this.lookup(b,c)};aa.prototype.findPackageWithURL=function(a){a.isResource&&(a=a.url);a.endsWith("/")&&(a=a.slice(0,-1));return this.byURL[a]};aa.prototype.findPackageHavingURL=function(a){a.isResource&&(a=a.url);a.endsWith("/")&&(a=a.slice(0,-1));var b=Infinity,c=null,e=this.byURL,d;for(d in e)if(0===a.indexOf(d)){var g=a.slice(d.length).length; -g>=b||(b=g,c=e[d])}return c};aa.prototype.findPackageForPath=function(a,b){if(Lc(a))return this.findPackageHavingURL(a);if(a.startsWith("."))return null;a=$jscomp.makeIterator(a.split("/")).next().value;if(!a)return null;var c=a.indexOf("@");if(-1>updateNameAndVersionOf] No version entry "+ -c+" of "+b+" found in registry ("+a.url+")"):console.warn("[PackageRegistry>>updateNameAndVersionOf] "+b+"@"+c+" not found in registry ("+a.url+")");this._addToPackageMap(a,d,g);e[b]&&e[b].versions[c]&&(delete e[b].versions[c],0===Object.keys(e[b].versions).length&&delete e[b]);this._updateLatestPackages(a.name)};aa.prototype._updateLatestPackages=function(a){var b=this.packageMap;if(a&&b[a])b[a].latest=N(g.sort(Object.keys(b[a].versions),!0));else for(var c in b)b[c].latest=N(g.sort(Object.keys(b[c].versions), -!0))};aa.prototype._discoverPackagesIn=function(a,b,c,d){d=void 0===d?null:d;var e=this,f,g,h,n,k,l;return $jscomp.asyncExecutePromiseGeneratorProgram(function(r){if(1==r.nextAddress){if(!a.isDirectory())return r.return(b);f=a.asFile().url;if(b.hasOwnProperty(f))return r.return(b);r.setCatchFinallyBlocks(2);g=d&&d[f]||new ca(e.System,f);return r.yield(g.tryToLoadPackageConfig(),4)}if(2!=r.nextAddress)return h=r.yieldResult,g.setConfig(h),b[f]={pkg:g,config:h,covered:c},e.System.debug&&(n=h,k=n.name, -l=n.version,console.log("[lively.modules] package "+k+"@"+l+" discovered in "+a.url)),r.return(b);r.enterCatchBlock();return r.return(b)})};aa.prototype._addToPackageMap=function(a,b,c,d){if(!b)throw Error("Cannot add package without name");c||(c="0.0.0");var e=this.packageMap;b=e[b]||(e[b]={versions:{},latest:null});if(b.versions[c])if(e="Redefining version "+c+" of package "+a.url,void 0===d||d)console.warn(e);else throw Error(e+" not allowed");b.versions[c]=a};aa.prototype._addPackageWithConfig= -function(a,b,c,d){(void 0===d?0:d)||this._addPackageDir(c,"individualPackageDirs",!0);a.registerWithConfig(b);this._addToPackageMap(a,a.name,a.version);return a};aa.prototype._addPackageDir=function(b,c,d){c=void 0===c?"individualPackageDirs":c;d=void 0===d?!0:d;b=Ub(b).asDirectory();if(("packageCollectionDirs"===c||"maybe packageCollectionDirs"===c)&&(this.coversDirectory(b)||"").includes("packageCollectionDirs"))return"packageCollectionDirs";b=this[c].concat(b);this[c]=d?a(b,function(a,b){return a.equals(b)}): -b;return c};$jscomp.global.Object.defineProperties(aa.prototype,{byURL:{configurable:!0,enumerable:!0,get:function(){if(!this._byURL){this._byURL={};for(var a=$jscomp.makeIterator(this.allPackages()),b=a.next();!b.done;b=a.next())b=b.value,this._byURL[b.url]=b}return this._byURL}}});var ca=function(a,b,c,d,g){g=void 0===g?{}:g;this.System=a;this.url=b;this.registerProcess=null;this.map={};this.setConfig(g)};ca.allPackages=function(a){return ta(aa.ofSystem(a).byURL)};ca.allPackageURLs=function(a){return aa.ofSystem(a).allPackageURLs()}; -ca.forModule=function(a,b){return this.forModuleId(a,b.id)};ca.forModuleId=function(a,b){return(b=La.forSystem(a).getPackageURLForModuleId(b))?Nc(a,b,!0):null};ca.fromJSON=function(a,b){return(new ca(a)).fromJSON(b)};ca.prototype.setConfig=function(a){this._name=a.name;this.version=a.version;this.dependencies=a.dependencies||{};this.devDependencies=a.devDependencies||{};this.main=a.main||"index.js";this.systemjs=a.systemjs;this.lively=a.lively};ca.prototype.toJSON=function(){var a=this.System,b=ka(this, -"url _name version map dependencies devDependencies main systemjs lively".split(" "));b.url.startsWith(a.baseURL)&&(b.url=b.url.slice(a.baseURL.length).replace(/^\//,""));return b};ca.prototype.fromJSON=function(a){var b=this.System;this.url=a.url;this._name=a._name;this.version=a.version;this.map=a.map||{};this.main=a.main;this.dependencies=a.dependencies||{};this.devDependencies=a.devDependencies||{};this.systemjs=a.systemjs;this.lively=a.lively;gc(this.url)||(this.url=ud(b.baseURL,this.url));this.registerWithConfig(); -return this};ca.prototype.asSpec=function(){return Object.assign({},ka(this,"name main map meta url address version lively".split(" ")),{modules:this.modules().map(function(a){return{name:a.id,deps:a.directRequirements().map(function(a){return a.id})}})})};ca.prototype.path=function(){var a=this.System.baseURL;return 0===this.url.indexOf(a)?this.url.slice(a.length):this.url};ca.prototype.modules=function(){var a=this.url,b=this.System;return La.forSystem(b).getModuleIdsForPackageURL(a).map(function(a){return fa(b, -a)})};ca.prototype.resources=function(a,b){b=void 0===b?[".git","node_modules",".module_cache","lively.next-node_modules"]:b;var c=this,d,e,f,g,h,k,l,m;return $jscomp.asyncExecutePromiseGeneratorProgram(function(n){if(1==n.nextAddress)return d=c,e=d.System,f=d.url,g=ca.allPackageURLs(e),h=g.filter(function(a){return a!==f&&!f.startsWith(a)}),n.yield(ea(f).dirList("infinity",{exclude:b}),2);k=n.yieldResult;l=k.filter(function(a){return!a.isDirectory()&&!h.some(function(b){return a.url.startsWith(b)})}).map(function(a){return a.url}); -m=x(c.modules(),"id");a&&(l=l.filter(a));return n.return(l.map(function(a){var b=a.replace(f,"").replace(/^\//,"");return{isLoaded:m.includes(a),url:a,nameInPackage:b,package:c}}))})};ca.prototype.hasResource=function(a){var b=this.url;return(a.startsWith(b)?ea(a):ea(b).join(a)).exists()};ca.prototype.toString=function(){return"Package("+this.name+" - "+this.path()+"/)"};ca.prototype.mergeWithConfig=function(a){var b=a=Object.assign({},a),c=b.name;b=b.map;c&&(delete a.name,this._name=c);b&&(delete a.map, -Object.assign(this.map,b));Object.assign(this,a);return this};ca.prototype.addMapping=function(a,b){this.map[a]=b;var c={},d={};this.System.config({packages:(d[this.url]={map:(c[a]=b,c)},d)})};ca.prototype.tryToLoadPackageConfig=function(){var a=this,b,c,d,g,h,k,l,m,p,q;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){switch(e.nextAddress){case 1:b=a;c=b.System;d=b.url;g=d+"/package.json";h={};k={};c.config({meta:(h[g]={format:"json"},h),packages:(k[d]={meta:{"package.json":{format:"json"}}}, -k)});c.debug&&console.log("[lively.modules package reading config] %s",g);e.setCatchFinallyBlocks(2);if(l=c.get(g)){e.jumpTo(4);break}return e.yield(c.import(g),5);case 5:l=e.yieldResult;case 4:return m=l,Ma(c.packageConfigPaths,g),e.return(m);case 2:return p=e.enterCatchBlock(),console.log("[lively.modules package] Unable loading package config %s for package: ",g,p),delete c.meta[g],q=d.split("/").slice(-1)[0],e.return({name:q})}})};ca.prototype.import=function(){var a=this,b,c,d,g,h,k,l;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){switch(e.nextAddress){case 1:return e.yield(a.register(), -2);case 2:return b=a,c=b.url,d=b.System,g=fa,h=d,e.yield(d.normalize(c),3);case 3:return k=g(h,e.yieldResult),e.yield(d.import(k.id),4);case 4:return l=e.yieldResult,e.yield(kb.waitFor(1E3,function(){return k.isLoaded()}),5);case 5:return e.return(l)}})};ca.prototype.isRegistering=function(){return!!this.registerProcess};ca.prototype.register=function(a){var b=this,c,d,e,g,h,k,l;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){switch(f.nextAddress){case 1:if(b.isRegistering())return f.return(b.registerProcess.promise); -c=b;d=c.System;e=c.url;b.registerProcess=kb.deferred();g=b.registerProcess.promise;d.debug&&console.log("[lively.modules package register] %s",e);f.setCatchFinallyBlocks(2,3);if(h=a){f.jumpTo(5);break}return f.yield(b.tryToLoadPackageConfig(),6);case 6:h=f.yieldResult;case 5:k=h,b.registerWithConfig(k),b.registerProcess.resolve(k);case 3:f.enterFinallyBlock();delete b.registerProcess;f.leaveFinallyBlock(4);break;case 2:throw l=f.enterCatchBlock(),b.registerProcess.reject(l),l;case 4:return f.return(g)}})}; -ca.prototype.updateConfig=function(a){a=Object.assign({},this.runtimeConfig,a);var b=this.name,c=this.version,d=a,e=d.name;d=d.version;(new qb(this)).applyConfig(a);if(b!==a.name||c!==a.version)console.log("[lively.modules] Updating registry "+b+"@"+c+" => "+e+"@"+d),aa.ofSystem(this.System).updateNameAndVersionOf(this,b,c,e,d)};ca.prototype.registerWithConfig=function(a){a=void 0===a?this.runtimeConfig:a;var b=this.System,c=this.url,d=(new qb(this)).applyConfig(a),e=ud(c,"package.json");b.get(e)|| -b.set(e,b.newModule(Object.assign({},a,{default:a})));Sb("lively.modules/packageregistered",{"package":c},Date.now(),b);return d};ca.prototype.remove=function(a){a=Object.assign({},{forgetEnv:!0,forgetDeps:!1,unloadModules:!0},a);var b=this.System,c=this.url;c=c.replace(/\/$/,"");a.unloadModules&&this.modules().forEach(function(b){return b.unload(a)});aa.ofSystem(b).removePackage(this);var d=b.getConfig(),e=c+"/package.json";b.delete(String(e));G(d.packageConfigPaths||[],e);var g={},h={};b.config({meta:(g[e]= -{},g),packages:(h[c]={},h),packageConfigPaths:d.packageConfigPaths});delete b.packages[c];Sb("lively.modules/packageremoved",{"package":this.url},Date.now(),b)};ca.prototype.reload=function(a){var b=this.url,c=aa.ofSystem(this.System),d=c.coversDirectory(b);this.remove(a);a={};c.addPackageAt(b,d||"devPackageDirs",(a[b]=this,a));return this.import()};ca.prototype.fork=function(a,b){var c=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){return 1==d.nextAddress?(b||(b=ea(c.url).join("../"+ -a).withRelativePartsResolved().url),d.yield(c.changeAddress(b,a,!1),2)):d.return(d.yieldResult)})};ca.prototype.rename=function(a){var b=this,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){return 1==d.nextAddress?(c=ea(b.url).join("../"+a).withRelativePartsResolved().url,d.yield(b.changeAddress(c,a,!0),2)):d.return(d.yieldResult)})};ca.prototype.changeAddress=function(a,b,c){b=void 0===b?null:b;c=void 0===c?!0:c;var d=this,e,f,g,h,n,k,l,m,p,q,t,u,v,x,y,A,B,z,D,C,F,E,G,H;return $jscomp.asyncExecutePromiseGeneratorProgram(function(r){switch(r.nextAddress){case 1:return a= -a.replace(/\/?/,""),e=d,f=e.System,g=e.url,r.yield(d.runtimeConfig,2);case 2:return h=r.yieldResult,n=ea(g).asDirectory(),k=new ca(f,a),r.yield(ea(a).asDirectory(),3);case 3:return l=r.yieldResult,h.name=b||d.name,m=aa.ofSystem(f),p=m.coversDirectory(g),La.forSystem(f).clearCache(),f.packages[g]&&(f.packages[a]=f.packages[g],c&&delete f.packages[g]),Object.assign(k,ka(d,["_name","map","config"])),r.yield(l.ensureExistance(),4);case 4:return r.yield(d.resources(void 0,[]),5);case 5:q=r.yieldResult.map(function(a){return a.url}), -t=d.modules(),u=$jscomp.makeIterator(t),v=u.next();case 6:if(v.done){r.jumpTo(8);break}x=v.value;y=l.join(x.pathInPackage()).url;return c?r.yield(x.renameTo(y),10):r.yield(x.copyTo(y),10);case 10:A=q.indexOf(x.id);-1c)return null;d=(a||f)+",";g=e.slice(0,c);e=e.slice(c);g.endsWith(" ")&&g.endsWith("\n")||(d=" "+d);e.startsWith(" ")|| -(d+=" ");return{status:"modified",newSource:""+g+d+e,generated:d,standaloneImport:b,importedVarName:a||f,from:c,to:c+d.length}}c=d?d.end:c.end;h=(f=a&&a!==g)?g+" as "+a:g;d=d?", "+h:", { "+h+" }";return{status:"modified",newSource:""+e.slice(0,c)+d+e.slice(c),generated:d,standaloneImport:b,importedVarName:f?a:g,from:c,to:c+d.length}};rb.prototype.insertNewImport=function(a,b,c,d){d=void 0===d?0:d;a&&a.length&&(d=N(a).end);var e=this.intoModuleSource;a=e.slice(0,d);e=e.slice(d);var f=b;a.length&&!a.endsWith("\n")&& -(f="\n"+f);e.length&&!e.startsWith("\n")&&(f+="\n");return{status:"modified",newSource:a+f+e,generated:f,standaloneImport:b,importedVarName:c,from:d,to:d+f.length}};var hf=function(){};hf.run=function(a,b,c){c=c||Pb(a,{withComments:!0});var d=(c=c.comments?c.comments.find(function(a){return a.isBlock&&a.text.startsWith("global")}):null)?c.text.replace(/^global\s*/,"").split(",").map(function(a){return a.trim()}).filter(Boolean):[],e=b.filter(function(a){return!d.includes(a)});if(!e.length)return{status:"not modified", -newSource:a,generated:"",from:0,to:0};if(!c)return c="/*global "+e.join(",")+"*/\n",{status:"modified",newSource:c+a,generated:c,from:0,to:c.length};b=c.start+2+c.text.length;e=e.join(",");d.length?e=","+e:c.text.startsWith("global ")||(e=" "+e);c=b+e.length;return{status:"modified",newSource:a.slice(0,b)+e+a.slice(b),generated:e,from:b,to:c}};var Sc=function(){};Sc.removeImports=function(a,b,c){c=c||Pb(a);var e=m(c.body,function(a){return"ImportDeclaration"===a.type&&a.specifiers.length?a.specifiers.map(function(b){return{local:b.local, -importStmt:a}}):[]}).filter(function(a){return b.some(function(b){return b.local===a.local.name})});c=e.map(function(a){return{local:a.local.name,from:a.importStmt.source.value}});a=d(e.map(function(a){var b=a.importStmt.specifiers.find(function(b){return a.local===b.local});G(a.importStmt.specifiers,b);return a.importStmt})).slice().reverse().reduce(function(a,b){var c=a.source;a=a.changes;var d=b.start,e=b.end,f=b.specifiers,g=c.slice(0,d),h=c.slice(e);c=c.slice(d,e);(b=f.length?cb(b):"")&&b.includes("\n")&& -!c.includes("\n")&&(b=b.replace(/\s+/g," "));c=g+b+h;a=a.concat({replacement:b,start:d,end:e});return{source:c,changes:a}},{source:a,changes:[]});return Object.assign({},a,{removedImports:c})};Sc.findUnusedImports=function(a){var b="string"===typeof a?Pb(a):a;a=m(b.body,function(a){return"ImportDeclaration"===a.type&&a.specifiers.length?a.specifiers.map(function(b){return{local:b.local,from:a.source?a.source.value:"",importStmt:a}}):[]});var c=a.map(function(a){return a.local});b=ac($b(b));b=Array.from(b.resolvedRefMap.keys()).filter(function(a){return!c.includes(a)}); -var e=d(b.map(function(a){return a.name}));return a.filter(function(a){return!e.includes(a.local.name)}).map(function(a){return Object.assign({},a,{local:a.local.name})})};Sc.removeUnusedImports=function(a){var b=Pb(a);return this.removeImports(a,this.findUnusedImports(b),b)};var ve=function(){var a=/['"]format (esm|es6)['"];/,b=/['"]format cjs['"];/,c=/(^\s*|[}\);\n]\s*)(import\s+(['"]|(\*\s+as\s+)?[^"'\(\)\n;]+\s+from\s+['"]|\{)|export\s+\*\s+from\s+["']|export\s+(\{|default|function|class|var|const|let|async\s+function))/; -return function(d,e){return e&&e.format?("es6"==e.format&&"esm"==e.format,e.format):a.test(d.slice(0,5E3))||!b.test(d.slice(0,5E3))&&c.test(d)?"esm":"global"}}(),jf=!1,kf={},P=function(a,b){var c=this;if(!gc(b)&&!/^@/.test(b))throw Error("ModuleInterface constructor called with "+b+" that does not seem to be a fully normalized module id.");this.System=a;this.id=b;this.recorderName="__lvVarRecorder";this.sourceAccessorName="__lvOriginalCode";this._scope=this._ast=this._source=this._recorder=null;this._observersOfTopLevelState= -[];this._evaluationsInProgress=0;this._evalId=1;this.createdAt=this.lastModifiedAt=new Date;ub("lively.modules/modulechanged",function(a){a.module===c.id&&c.reset()})};P.prototype.fullName=function(){return this.id};P.prototype.shortName=function(){return this.package().name+"/"+this.pathInPackage()};P.prototype.source=function(){var a=this;return"@empty"===this.id?Promise.resolve(""):this._source?Promise.resolve(this._source):this.System.resource(this.id).read().then(function(b){return a._source= -b})};P.prototype.setSource=function(a){this.sourceAccessorName&&this.recorderName&&a.includes("var "+this.recorderName)&&a.includes("var "+this.sourceAccessorName)||this._source===a||(this.reset(),this._source=a)};P.prototype.ast=function(){var a=this,b,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){if(1==d.nextAddress){if(a._ast)return d.return(a._ast);b=a;c=Ua;return d.yield(a.source(),2)}return d.return(b._ast=c(d.yieldResult))})};P.prototype.scope=function(){var a=this,b;return $jscomp.asyncExecutePromiseGeneratorProgram(function(c){if(1== -c.nextAddress)return a._scope?c.return(a._scope):c.yield(a.ast(),2);b=c.yieldResult;return c.return(a._scope=xc(b).scope)})};P.prototype.resolvedScope=function(){var a=this,b,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){return 1==d.nextAddress?(b=a,c=ac,d.yield(a.scope(),2)):d.return(b._scope=c(d.yieldResult))})};P.prototype.metadata=function(){var a=this.System.loads?this.System.loads[this.id]:null;return a?a.metadata:null};P.prototype.addMetadata=function(a){var b=this.System, -c=this.id,d=this.metadata();a=d?Object.assign(d,a):a;d={};b.config({meta:(d[c]=a,d)});return b.meta[c]};P.prototype.format=function(){var a=this.metadata();return a&&a.format?a.format:this._source?ve(this._source):"global"};P.prototype.setFormat=function(a){return this.addMetadata({format:a})};P.prototype.reset=function(){this._scope=this._ast=this._source=null};P.prototype.get=function(){return this.System.get(this.id)};P.prototype.load=function(a){var b=this,c,d,e,g;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){if(1== -f.nextAddress)return c=b,d=c.id,e=c.System,a&&b.addMetadata(a),(g=e.get(d))?f.jumpTo(2):f.yield(e.import(d),3);2!=f.nextAddress&&(g=f.yieldResult);return f.return(g)})};P.prototype.isLoaded=function(){return!!this.System.get(this.id)};P.prototype.unloadEnv=function(){this._recorder=null;this._observersOfTopLevelState=[];delete Vb(this.System).loadedModules[this.id]};P.prototype.unloadDeps=function(a){var b=this;a=T({forgetDeps:!0,forgetEnv:!0},a);this.dependents().forEach(function(c){b.System.delete(c.id); -b.System.loads&&delete b.System.loads[c.id];a.forgetEnv&&c.unloadEnv()})};P.prototype.unload=function(a){var b=this,c,d,e,g;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){if(1==f.nextAddress)return a=Object.assign({},{reset:!0,forgetDeps:!0,forgetEnv:!0},a),c=b,d=c.System,e=c.id,a.reset&&b.reset(),a.forgetDeps&&b.unloadDeps(a),b.System.delete(e),d.loads&&delete d.loads[e],d.meta&&delete d.meta[e],a.forgetEnv&&b.unloadEnv(),(g=d._livelyModulesTranslationCache)?f.yield(g.deleteCachedData(e), -2):f.jumpTo(2);Sb("lively.modules/moduleunloaded",{module:b.id},Date.now(),b.System);f.jumpToEnd()})};P.prototype.reload=function(a){var b=this,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){return 1==d.nextAddress?(a=T({reloadDeps:!0,resetEnv:!0},a),c=[b],a.reloadDeps&&(c=b.dependents().concat(c)),d.yield(b.unload({forgetDeps:a.reloadDeps,forgetEnv:a.resetEnv}),2)):3!=d.nextAddress?d.yield(Promise.all(c.map(function(a){return a.id!==b.id&&a.load()})),3):d.yield(b.load(),0)})};P.prototype.copyTo= -function(a){var b=this,c,d,e,g,h,k;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){if(1==f.nextAddress)return c=b.System.resource(a),d=c.write,f.yield(b.source(),3);if(2!=f.nextAddress)return f.yield(d.call(c,f.yieldResult),2);e=b;g=e.System;h=fa(g,a);k=ka(b,"_observersOfTopLevelState _scope _ast _source _recorder sourceAccessorName recorderName".split(" "));Object.assign(h,k);g.set(a,g.newModule(g.get(b.id)));return f.return(h)})};P.prototype.renameTo=function(a,b){b=void 0===b?{}: -b;var c=this,d,e,f,g;return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){switch(h.nextAddress){case 1:return d=b,e=void 0===d.unload?!0:d.unload,f=void 0===d.removeFile?!0:d.removeFile,h.yield(c.copyTo(a),2);case 2:g=h.yieldResult;if(!e){h.jumpTo(3);break}return h.yield(c.unload({reset:!0,forgetDeps:!1,forgetEnv:!0}),3);case 3:if(!f){h.jumpTo(5);break}return h.yield(c.System.resource(c.id).remove(),5);case 5:return h.return(g)}})};P.prototype.whenLoaded=function(a){if(this.isLoaded())try{a(this)}catch(f){console.error(f)}else Vb(this.System).onLoadCallbacks.push({moduleName:this.id, -resolved:!0,callback:a})};P.prototype.changeSourceAction=function(a){var b=this;return Promise.resolve(this.source()).then(function(b){return a(b)}).then(function(a){return b.changeSource(a)})};P.prototype.changeSource=function(a,b){b=Object.assign({},{doSave:!0,doEval:!0},b);var c=this.System,d=this.id,e=this.format(),f;this.reset();this.lastModifiedAt=new Date;return Promise.all([b.doSave&&this.System.resource(d).write(a),b.doEval&&ye(c,d,a,e,b).then(function(a){return f=a})]).then(function(){return f})}; -P.prototype.addDependencyToModuleRecord=function(a,b){var c=this;b=void 0===b?function(){}:b;var d=this.record(),e=a.record();if(d&&e){var f,g=d.dependencies.some(function(b,c){if(b)return f=c,b&&b.name===a.id});g?e!==d.dependencies[f]&&d.dependencies.splice(f,1,e):d.dependencies.push(e);g&&d.setters[f]||(d.setters[g?f:d.dependencies.length-1]=b);var h;e.importers.some(function(a,b){if(a)return h=b,a&&a.name===c.id})?d!==e.importers[h]&&e.importers.splice(h,1,d):e.importers.push(d)}};P.prototype.dependents= -function(){var a=this;return Qd(wf(od(this.System)),this.id).map(function(b){return fa(a.System,b)})};P.prototype.requirements=function(){var a=this;return Qd(od(this.System),this.id).map(function(b){return fa(a.System,b)})};P.prototype.directRequirements=function(){var a=this,b=(this.record()||{}).dependencies||[];return x(b.filter(Boolean),"name").map(function(b){return fa(a.System,b)})};P.prototype.define=function(a,b,c,d){c=void 0===c?!0:c;var e=this.System,f=this.id,g=this.recorder;$jscomp.initSymbol(); -$jscomp.initSymbol();var h=Symbol.for("lively-object-meta"),k=Symbol.for("lively-module-meta");"function"!==typeof b||!d||"function"!==d.kind&&"class"!==d.kind||(b[h]=d);b&&b[h]&&!b[k]&&(d=this.pathInPackage(),h=this.package(),b[k]={package:h?{name:h.name,version:h.version}:{},pathInPackage:d});g[a]=b;sd(e,f,a,b,!1);this.notifyTopLevelObservers(a);(c=c||!this.isEvalutionInProgress())&&xe(e,f);return b};P.prototype.undefine=function(a){delete this.recorder[a]};P.prototype.subscribeToToplevelDefinitionChanges= -function(a){this._observersOfTopLevelState.push(a);return a};P.prototype.notifyTopLevelObservers=function(a){var b=this.recorder;yc(["createOrExtendES6ClassForLively","lively.capturing-declaration-wrapper"],a)||this._observersOfTopLevelState.forEach(function(c){return c(a,b[a])})};P.prototype.unsubscribeFromToplevelDefinitionChanges=function(a){this._observersOfTopLevelState="string"===typeof a?this._observersOfTopLevelState.filter(function(b){return b.name!==a}):this._observersOfTopLevelState.filter(function(b){return b!== -a})};P.prototype.evaluationStart=function(){this._evaluationsInProgress++};P.prototype.evaluationEnd=function(){this._evaluationsInProgress--;xe(this.System,this.id)};P.prototype.nextEvalId=function(){return this._evalId++};P.prototype.isEvalutionInProgress=function(){return 0e.length)return f.return([null,null]);g=e[e.length-1];h=e[e.length-2];if("Identifier"!=g.type||"MemberExpression"!=h.type||h.computed||"Identifier"!==h.object.type)return f.return([null,null]);k=c.resolvedRefMap.get(h.object)||{};l=k.decl;if(!l||"ImportDeclaration"!==l.type)return f.return([null,null]);m=h.object.name;p=l.specifiers.find(function(a){return a.local.name===m});return f.return("ImportNamespaceSpecifier"!==p.type?[null,null]:[l,p.local,g.name])})}; -P.prototype._resolveImportedDecl=function(a){var b=this,c,d,e,g,h,k,l;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){switch(f.nextAddress){case 1:if(!a)return f.return([]);c=a.id;d=c.name;return f.yield(b.imports(),2);case 2:e=f.yieldResult;g=e.find(function(a){return a.local==d});if(!g){f.jumpTo(3);break}h=fa(b.System,g.fromModule,b.id);k=[a];l=k.concat;return f.yield(h.bindingPathForExport(g.imported),4);case 4:return f.return(l.call(k,f.yieldResult));case 3:return f.return([a])}})}; -P.prototype.bindingPathFor=function(a){var b=this,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){return 1==d.nextAddress?d.yield(b._localDeclForName(a),2):4!=d.nextAddress?(c=d.yieldResult)?d.yield(b._resolveImportedDecl(c),4):d.jumpTo(0):d.return(d.yieldResult)})};P.prototype.bindingPathForExport=function(a){var b=this,c,d,e,g,h,k;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){switch(f.nextAddress){case 1:return f.yield(b.resolvedScope(),2);case 2:return f.yield(b.exports(), -3);case 3:c=f.yieldResult;d=c.find(function(b){return b.exported===a});if(!d.fromModule)return f.return(b._resolveImportedDecl({decl:d.decl,id:d.declId,declModule:d&&d.decl?b:null}));e=fa(b.System,d.fromModule,b.id);g={decl:d.node,id:d.declId,declModule:b};h=[g];k=h.concat;return f.yield(e.bindingPathForExport(d.imported),5);case 5:return f.return(k.call(h,f.yieldResult))}})};P.prototype.bindingPathForRefAt=function(a){var b=this,c,d,e,g,h,k,l,m,p,q;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){switch(f.nextAddress){case 1:return f.yield(b._localDeclForRefAt(a), -2);case 2:c=f.yieldResult;if(!c){f.jumpTo(3);break}return f.yield(b._resolveImportedDecl(c),4);case 4:return f.return(f.yieldResult);case 3:return d=$jscomp,e=d.makeIterator,f.yield(b._importForNSRefAt(a),5);case 5:g=e.call(d,f.yieldResult);h=g.next().value;k=g.next().value;l=g.next().value;if(!h)return f.return([]);m=fa(b.System,h.source.value,b.id);p=[{decl:h,declModule:b,id:k}];q=p.concat;return f.yield(m.bindingPathForExport(l),6);case 6:return f.return(q.call(p,f.yieldResult))}})};P.prototype.definitionForRefAt= -function(a){var b=this,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){if(1==d.nextAddress)return d.yield(b.bindingPathForRefAt(a),2);c=d.yieldResult;return d.return(1>c.length?null:c[c.length-1].decl)})};P.prototype.ensureRecord=function(){var a=this.System,b=a._loader.moduleRecords;return b[this.id]?b[this.id]:b[this.id]={name:this.id,exports:a.newModule({}),dependencies:[],importers:[],setters:[]}};P.prototype.record=function(){var a=this.System._loader.moduleRecords[this.id]; -if(!a)return null;a.hasOwnProperty("__lively_modules__")||(a.__lively_modules__={evalOnlyExport:{}});return a};P.prototype.updateRecord=function(a){var b=this.record();if(!b)throw Error("es6 environment global of "+this.id+": module not loaded, cannot get export object!");b.locked=!0;try{return a(b)}finally{b.locked=!1}};P.prototype.search=function(a,b){var c=this,d,e,f,g,h,k,l,m,p,q,t,u,v,x;return $jscomp.asyncExecutePromiseGeneratorProgram(function(n){if(1==n.nextAddress)return b=Object.assign({}, -{excludedModules:[]},b),b.excludedModules.some(function(a){return"string"===typeof a?a===c.id:a instanceof RegExp?a.test(c.id):"function"===typeof a?a(c.id):!1})?n.return([]):n.yield(c.source(),2);d=n.yieldResult;a instanceof RegExp?(f="g",a.ignoreCase&&(f+="i"),a.multiline&&(f+="m"),e=RegExp(a.source,f)):e=RegExp(a,"g");for(h=[];null!==(g=e.exec(d));)h.push([g.index,g[0].length]);l=k=0;m=1;for(p=0;kb%50&&a.progress.step&&a.progress.step("Scanning ...",b/e.length)},f.yield(Promise.all(e.map(function(c,d){a.progress&&h(d);return b.rawExportsOfModule(c,a,g).then(function(a){return a?g[c]=a:null})})),2)):f.return(g)})};$a.prototype.rawExportsOfModule=function(a,b){b=void 0===b?{}:b;var c=this,d,e,f,g,h,k,l,m,p,q,t,u,v,x,y,A,z,B,D,C,E,F;return $jscomp.asyncExecutePromiseGeneratorProgram(function(n){switch(n.nextAddress){case 1:d= -c;e=d.System;f=d.exportByModuleCache;g=b.excludedPackages||[];h=b.excludedURLs||(b.excludedURLs=g.filter(function(a){return"string"===typeof a}));k=b.excludeFns||(b.excludeFns=g.filter(function(a){return"function"===typeof a}));l=b.excludedPackageURLs||(b.excludedPackageURLs=h.concat(h.map(function(a){return e.decanonicalize(a.replace(/\/?$/,"/")).replace(/\/$/,"")})));m=b.livelyEnv||(b.livelyEnv=e.get("@lively-env")||{});b.modes||(b.modes=Object.keys(m.loadedModules||{}));if(f[a])return p=f[a].rawExports, -n.return(l.includes(p.packageURL)||k.some(function(a){return a(p.packageURL)})?null:f[a]);q=fa(e,a);t=q.pathInPackage();v=(u=q.package())&&u.main&&t===u.main;x=u?u.url:"";y=u?u.name:"";A=u?u.version:"";z={moduleId:a,isMain:v,pathInPackage:t,packageName:y,packageURL:x,packageVersion:A,exports:[]};if(l.includes(x)||k.some(function(a){return a(x)}))return n.return(null);n.setCatchFinallyBlocks(2);B=q.format();return["register","es6","esm"].includes(B)?(E=z,n.yield(q.exports(),7)):n.yield(q.load(),6); -case 6:D=n.yieldResult;z.exports=[];for(C in D)"__useDefault"!==C&&"default"!==C&&z.exports.push({exported:C,local:C,type:"id"});n.jumpTo(5);break;case 7:E.exports=n.yieldResult;case 5:n.leaveTryBlock(3);break;case 2:F=n.enterCatchBlock(),z.error=F;case 3:return n.return(f[a]={rawExports:z})}})};$a.prototype.resolveExportsOfModule=function(a,b,c){var d=this;c=void 0===c?{}:c;if(!c[a]){c[a]=!0;var e=b[a];if(e&&!e.resolvedExports){var f=this.System,g=ka(e.rawExports,"moduleId isMain packageName packageURL packageVersion pathInPackage".split(" ")); -e.resolvedExports=m(e.rawExports.exports,function(e){var h=e.type,k=e.exported,l=e.local,m=e.fromModule;if("all"!==h)return[Object.assign({},g,{type:h,exported:k,local:l,fromModule:m})];e=f.decanonicalize(m,a);d.resolveExportsOfModule(e,b,c);return(b[e].resolvedExports||[]).map(function(a){return Object.assign({},g,{type:a.type,exported:a.exported,local:a.local,fromModule:a.fromModule||m})})});c[a]=!1}}};$jscomp.global.Object.defineProperties($a.prototype,{exportByModuleCache:{configurable:!0,enumerable:!0, -get:function(){return this._exportByModuleCache||(this._exportByModuleCache={})}}});var Ph=Object.freeze({buildPackageMap:Ne,resolvePackageDependencies:function(a,b){var c=Object.assign({},a.dependencies,a.devDependencies);return Object.keys(c).reduce(function(a,d){var e=c[d],f=ta(b).find(function(a){var b=a.version;return a.name===d&&lively.modules.semver.satisfies(b,e)})||{},g=f.name;f=f.version;a[d]=g?g+"@"+f:void 0;return a},{})},dependencyGraph:function(a){function b(a,b){var e=a+"@"+b;if(e in -d)return d[e];var f=c.find(function(c){var d=c.version;return c.name===a&&lively.modules.semver.satisfies(d,b)})||{},g=f.name;f=f.version;return d[e]=g?g+"@"+f:void 0}var c=ta(a),d={};return Object.keys(a).reduce(function(c,d){var e=a[d],f=Object.assign({},e.dependencies,e.devDependencies);c[d]=Object.keys(f).map(function(a){return b(a,f[a])}).filter(function(a){return!!a});return c},{})}}),lf="undefined"!==typeof window?window:"undefined"!==typeof global?global:"undefined"!==typeof self?self:void 0, -na=na||Ie(lf.System),Qh=Object.freeze({get System(){return na},getSystem:He,removeSystem:function(a){a=a&&"string"!==typeof a?Vg(a):a;delete wb.systems[a]},loadedModules:function(){return Object.keys(Oe())},printSystemConfig:function(){var a=na;a=He(a);return JSON.stringify({baseURL:a.baseURL,transpiler:a.transpiler,defaultJSExtensions:a.defaultJSExtensions,defaultExtension:a.defaultExtension,map:a.map,meta:a.meta,packages:a.packages,paths:a.paths,packageConfigPaths:a.packageConfigPaths,bundles:a.bundles}, -null,2)},whenLoaded:function(a,b){var c=na,d=c.decanonicalize(a);if(c.get(d))try{b(fa(c,d))}catch(w){console.error(w)}else c.get("@lively-env").onLoadCallbacks.push({moduleName:a,resolved:!1,callback:b})},changeSystem:function(a,b){na=a;b&&(lf.System=a);return a},module:function(a){return fa(na,a)},doesModuleExist:function(a,b){return Og(na,a,b)},isModuleLoaded:function(a,b){return De(na,a,b)},unwrapModuleResolution:function(){var a=na;ob(a,"normalize","normalizeHook");ob(a,"decanonicalize","decanonicalizeHook"); -ob(a,"normalizeSync","decanonicalizeHook");ob(a,"newModule","newModule_volatile");ob(a,"instantiate","instantiate_triggerOnLoadCallbacks")},wrapModuleResolution:function(){Fe(na)},importPackage:function(a){return ze(na,a)},registerPackage:function(a,b){return Ae(na,a,b)},removePackage:function(a){return(a=hc(na,a).pkg)?a.remove():null},reloadPackage:function(a,b){return Nc(na,a).reload(b)},getPackages:function(){return Lg(na)},getPackage:function(a,b){return Nc(na,a,void 0===b?!1:b)},getPackageOfModule:function(a){return ca.forModuleId(na, -a)},ensurePackage:function(a){return Mc(na,a)},applyPackageConfig:function(a,b){return Nc(na,b).updateConfig(a)},lookupPackage:function(a,b){return hc(na,a,void 0===b?!1:b)},moduleSourceChange:function(a,b,c){return ye(na,a,b,c)},requireMap:Oe,isHookInstalled:function(a,b){return fb(na,a,b)},installHook:function(a,b){return eb(na,a,b)},removeHook:function(a,b){return ob(na,a,b)},wrapModuleLoad:function(){we(na)},unwrapModuleLoad:function(){ob(na,"translate","lively_modules_translate_hook")},cjs:Ph, -scripting:{module:fa,ensurePackage:Mc,registerPackage:Ae,importPackage:ze,lookupPackage:hc,ImportInjector:rb},PackageRegistry:aa,ExportLookup:$a,semver:g});$jscomp.initSymbol();$jscomp.initSymbol();$jscomp.initSymbol();$jscomp.initSymbol();$jscomp.initSymbol();var Ya=Symbol.for("lively-instance-initialize"),Wb=Symbol.for("lively-instance-superclass"),Pc=Symbol.for("lively-module-meta"),jh=Symbol.for("lively-object-meta"),yd=Symbol.for("lively-klass-changes-subscriber");$jscomp.initSymbol();var Oc= -Symbol.for("lively.classes-properties-and-settings"),fh={defaultSetter:null,defaultGetter:null,valueStoreProperty:"_state"},kh=/\([^\\)]*\)/,ih={enumerable:!1,configurable:!0},hh={enumerable:!1,configurable:!0,writable:!0},Se="function"===typeof Object.setPrototypeOf?function(a,b){return Object.setPrototypeOf(a,b)}:function(a,b){return a.__proto__=b};Fc._get=function w(a,b,c){null===a&&(a=Function.prototype);var d=Object.getOwnPropertyDescriptor(a,b);if(void 0===d)return a=Object.getPrototypeOf(a), -null===a?void 0:w(a,b,c);if("value"in d)return d.value;b=d.get;return void 0===b?void 0:b.call(c)};Fc._set=function ya(a,b,c,d){var g=Object.getOwnPropertyDescriptor(a,b);void 0===g?(a=Object.getPrototypeOf(a),null!==a&&ya(a,b,c,d)):"value"in g&&g.writable?g.value=c:(b=g.set,void 0!==b&&b.call(d,c));return c};lively.modules=Qh;lively.FreezerRuntime=null;"lively-next.org"!==document.location.host&&(document.title="lively.next ("+document.location.host+")");var lh=document.getElementById("dom-loading-status"), -Ed=document.location,Xb=Ed.origin,lc=ea(Ed.href).query(),mf=document.getElementById("dom-loading-indicator"),Tc=decodeURIComponent(Ed.pathname).match(/\/worlds\/(.+)/),Rh=Tc?Tc[1].replace(/(\.json)?($|\?.*)/,".json$2"):"default",Sh=ea(Xb+"/lively.morphic/worlds/"+Rh),Uc=!1,nf=Tc[1].startsWith("morph benchmark"),Th=!lc.quickload&&!nf,Uh="askBeforeQuit"in lc?!!lc.askBeforeQuit:!0;kb.waitFor(function(){return!!lively.user}).then(function(){var a=lively.user.UserRegistry.current;if(a.hasUserStored()&& -!lc.login)Uc=!0;else{if(lc.nologin||nf)return a.login(lively.user.ClientUser.guest).then(function(a){Uc=!0});ea(Xb+"/lively.user/html/html-ui.fragment").read().then(function(a){document.body.insertAdjacentHTML("beforeend",a);mf.style.display="none";return Ic("/lively.user/html/html-ui.js")}).then(function(){return lively.user.html.openUserUI()}).then(function(a){mf.style.display="";Uc=!0}).catch(function(a){console.error(a)})}});Promise.resolve().then(function(){var a=[];"PointerEvent"in window|| -a.push(Ic(Xb+"/lively.next-node_modules/pepjs/dist/pep.js"));"fetch"in window||a.push(Ic("//cdnjs.cloudflare.com/ajax/libs/fetch/1.0.0/fetch.js"));return Promise.all(a)}).then(function(){return Th?nh():mh()}).then(function(){var a=Date.now()-window._livelyLoadStart;xb("...lively systems are ready");console.log("load time "+a+"ms")}).then(function(){xb("Loading lively.2lively...");return lively.modules.registerPackage("lively.2lively")}).then(function(){Uh&&window.addEventListener("beforeunload",function(a){return a.returnValue= -"Really?"},!0);return{resource:Sh,showWorldLoadDialog:!Tc}}).then(function(a){xb("Loading lively.morphic...");return Promise.all([lively.modules.importPackage("lively.morphic"),kb.waitFor(function(){return Uc})]).then(function(b){b=b[0];xb("Loading world...");return b.World.loadWorldFromURL(a.resource,null,{verbose:!0,localconfig:!0,l2l:!0,shell:!0,worldLoadDialog:a.showWorldLoadDialog,browserURL:"/worlds/"+a.resource.name().replace(/\.json($|\?)/,"")})})}).then(function(){var a=Date.now()-window._livelyLoadStart; -xb("...lively.morphic world ready");console.log("load time "+a+"ms")}).catch(function(a){console.error(a);var b=a.message;a.stack!==a.message&&(b+=a.stack.includes(a.message)?a.stack.replace(a.message,"\n"):a.stack,console.error(b));a=document.createElement("pre");a.innerText=b;document.body.appendChild(a)})})(escodegenbrowser,acorn,babelPluginTransformJsx,fs,semver); diff --git a/lively.morphic/web/static-world-listing.css b/lively.morphic/web/static-world-listing.css deleted file mode 100644 index 4e8bac0af3..0000000000 --- a/lively.morphic/web/static-world-listing.css +++ /dev/null @@ -1,182 +0,0 @@ -.body { - width: 100%; - margin: 0; -} - -a, a:-webkit-any-link { - color: black; - text-decoration: none; -} - -.content { - font-family: sans-serif; - margin-left: 20px; - margin-right: 20px; -/* width: 70%;*/ -/* max-width: 800px;*/ -} - -.hidden { - display: none !important; -} - -/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*/ -/* tabs */ - -.world-tabs { - height: 1.6em; - display: flex; - flex-direction: row; - justify-content: center; - background-color: #eee; -} - -.world-tabs button { - font-size: medium; - padding-left: 20px; - padding-right: 20px; - border: none; - background-color: #eee; - cursor: pointer; - outline: 0 !important; -} - -.world-tabs button:hover { - background-color: #ccc; - color: white; -} - -.world-tabs button.selected { - background-color: #888; - color: white; -} - -.filter-worlds { - margin-top: 18px; - height: 1.6em; - display: flex; - flex-direction: row; - justify-content: center; -} - -.filter-worlds input { - padding: 12px; - font-size: medium; -} - -.lively-next-logo { - position: absolute; - left: 5px; - height: 1.6em; -} - -.lively-next-logo img { - height: 80%; - padding: 3px; -} - -/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*/ -/* user flap */ - -.user-flap { - position: absolute; - right: 5px; - height: 1.6em; - cursor: pointer; -} - -.user-flap { - position: absolute; - right: 5px; - height: 1.6em; - cursor: pointer; -} - -.user-flap .label { - display: inline-block; - pointer-events: none; - font-family: sans-serif; - font-size: 12px; - font-famliy: Helvetica Neue, Verdana, Sans Serif; - font-weight: bold; - color: rgb(102, 102, 102); - padding: 4px; - margin-top: 3px; -} - - -/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*/ -/* world listing */ - -.list { - display: flex; - flex-flow: wrap; - justify-content: center; - align-items: center; - margin-top: 30px; - margin-bottom: 30px; -} - -.world-link { - width: 350px; - margin: 10px 8px; - border: 2px #d4d4d4; - border-radius: 8px; - box-sizing: border-box; - border-style: solid; - overflow: hidden; -} - -.world-name { - text-align: center; - font-weight: bold; - padding: 3px; - bottom: 0; - width: 100%; - position: absolute; - margin: auto; - padding: 0; -} - -.world-preview { - font-size: small; - display: flex; - flex-direction: row; -} - -.world-preview .description { - width: 60%; - margin: 6px; - display: flex; - flex-direction: column; - align-items: flex-end; -} - -.world-preview .description .description-text { - flex-grow: 2; - display: flex; - align-items: center; -} - -.world-preview p { - margin: 0px; padding: 0; - margin-bottom: 10px; -} - -.world-preview .image { - margin: 3px; - width: 40%; - border-right: 2px solid lightgray; - position: relative; -} - -.world-preview .image img { - width: 100%; -} - -.world-preview .image-title { - position: absolute; - text-align: center; - bottom: 0; - width: 100% -} diff --git a/lively.morphic/web/static-world-listing.html b/lively.morphic/web/static-world-listing.html deleted file mode 100644 index 420eb43eab..0000000000 --- a/lively.morphic/web/static-world-listing.html +++ /dev/null @@ -1,112 +0,0 @@ - - - - lively.next worlds - - - - - - -
-
-
Loading
- -
-
- - - - - - - -
-
-
-
-
- - - - - - - - - - - - - - diff --git a/lively.morphic/web/static-world-listing.js b/lively.morphic/web/static-world-listing.js deleted file mode 100644 index 4ab7fb862a..0000000000 --- a/lively.morphic/web/static-world-listing.js +++ /dev/null @@ -1,141 +0,0 @@ -// import { resource } from "lively.resources"; -const { resource } = lively.resources; -const { arr } = lively.lang; -const { ObjectDBHTTPInterface } = lively.storage; -const { promise } = lively.lang; - -const $ = sel => document.querySelector(sel); -const $$ = sel => document.querySelectorAll(sel); -const addClass = (el, className) => el.className = arr.uniq( - el.className.split(" ") - .concat(className) - .filter(ea => !!ea.trim())) - .join(" "); -const removeClass = (el, className) => el.className = arr.uniq( - el.className.split(" ") - .filter(ea => !!ea.trim() && ea !== className)) - .join(" "); - -export function showWorldsLastChoice(user) { - let loc = "public"; - try { - let choice = JSON.parse(localStorage.getItem("lively.next-worlds-last-filter-choice")); - if (choice) loc = choice.location; - - if (loc === "search") - $('.filter-worlds input').value = choice.query || ""; - - } catch (err) {} - return showWorlds(loc, user); -} - -// public, mine, latest, search -export async function showWorlds(loc, user) { - - let choice = {location: loc}; - - { - let f = !user || user.isGuestUser ? addClass : removeClass - f($(".world-tabs button.mine"), "hidden"); - } - - { - Array.from($$(".world-tabs button")).forEach(ea => removeClass(ea, "selected")); - addClass($(`.world-tabs button.${loc}`), "selected"); - } - - let filterFn = `(ea, i) => ea.tags.includes("front-page")`; - - if (loc === "mine") { - if (!user) loc = "public" - else { - let userName = user.name; - filterFn = `(ea, i) => ea.author.name === "${userName}"`; - } - } - - if (loc === "latest") { - if (!user) loc = "public" - else { - let userName = user.name; - filterFn = `(ea, i) => !ea.tags.includes("hidden")`; - } - } - - if (loc === "search") { - removeClass($(".filter-worlds"), "hidden"); - let input = $('.filter-worlds input'), - q = input.value.toLowerCase(); - choice.query = q; - input.focus(); - filterFn = `(ea, i) => { - let q = ${JSON.stringify(q)}; - if (ea.name.toLowerCase().includes(q)) return true; - if (ea.author.name.toLowerCase().includes(q)) return true; - if (ea.description.toLowerCase().includes(q)) return true; - if ((ea.tags || []).some(t => t.toLowerCase().includes(q))) return true; - return false; - }`; - } else { - addClass($(".filter-worlds"), "hidden"); - } - - saveChoice(choice); - - let db = new ObjectDBHTTPInterface(), - // filterFn = `(ea, i) => ea.tags.includes("front-page") || ea.author.name === "${userName}"`, - commits = await db.fetchCommits({ - db: "lively.morphic/objectdb/morphicdb", - type: "world", filterFn - }); - - if (loc === "latest") { - commits = arr.sortBy(commits, ea => -ea.timestamp); - } - - return listWorlds(commits); -} - -async function listWorlds(worldCommits) { - let i = $("#dom-loading-indicator"); - if (i) i.style.display = "none"; - - $(`.worlds .list`).innerHTML = ""; - - for (let commit of worldCommits) { - let {tags, author} = commit; - // if (tags.includes("front-page")) addPreview(commit); - addPreview(commit); - } -} - -function saveChoice(choice) { - try { - localStorage.setItem( - "lively.next-worlds-last-filter-choice", - JSON.stringify(choice)); - } catch (err) {} -} - -async function addPreview(commit, dbName) { - let dbQuery = dbName ? `?db=${dbName}` : "", - { - name, author: {name: authorName}, - preview, timestamp, description - } = commit, - date = lively.lang.date.format(new Date(timestamp), "yyyy-mm-dd HH:MM"); - $(`.worlds .list`).insertAdjacentHTML( - "beforeEnd", - ` -
-
- -
${name}
-
-
-
${authorName} ${date}
-

${description}

-
-
-
`) -} diff --git a/lively.resources/src/esm-resource.js b/lively.resources/src/esm-resource.js index 6846d92925..018ddff9e3 100644 --- a/lively.resources/src/esm-resource.js +++ b/lively.resources/src/esm-resource.js @@ -7,7 +7,7 @@ const requestMap = {}; export class ESMResource extends Resource { static normalize (esmUrl) { - const id = esmUrl.replaceAll(/esm:\/\/(run|cache)\//g, ''); + const id = esmUrl.replaceAll(/esm:\/\/([^\/]*)\//g, ''); let pathStructure = id.split('/').filter(Boolean); @@ -25,7 +25,6 @@ export class ESMResource extends Resource { pathStructure.push(fileName); } - if (pathStructure[pathStructure.length - 1].endsWith('+esm')) { pathStructure[pathStructure.length - 1] = pathStructure[pathStructure.length - 1].replace('+esm', 'esm.js'); } @@ -41,13 +40,22 @@ export class ESMResource extends Resource { return pathStructure; } - async read () { - let module; - - const id = this.url.replace(/esm:\/\/(run|cache)\//g, ''); - let baseUrl = 'https://jspm.dev/'; + getEsmURL () { + let baseUrl; if (this.url.startsWith('esm://run/npm/')) baseUrl = 'https://cdn.jsdelivr.net/'; else if (this.url.startsWith('esm://run/')) baseUrl = 'https://esm.run/'; + else if (this.url.startsWith('esm://cache/')) baseUrl = 'https://jspm.dev/'; + else { + const domain = this.url.match(/esm:\/\/([^\/]*)\//)?.[1]; + baseUrl = `https://${domain}/`; + } + return baseUrl; + } + + async read () { + let module; + const id = this.url.replace(/esm:\/\/([^\/]*)\//g, ''); + const esmURL = this.getEsmURL(); let pathStructure = ESMResource.normalize(id); @@ -58,7 +66,7 @@ export class ESMResource extends Resource { if (typeof lively !== 'undefined' && (hit = lively.memory_esm?.get(shortName))) return await hit.blob.text(); module = await res.read(); } else { - module = await resource((baseUrl + id)).read(); + module = await resource((esmURL + id)).read(); res.write(module); } return module; @@ -141,7 +149,9 @@ export class ESMResource extends Resource { } async exists () { - // stub that needs to exist + const id = this.url.replace(/esm:\/\/([^\/]*)\//g, ''); + const baseUrl = this.getEsmURL(); + return await resource(baseUrl).join(id).exists(); } async remove () { diff --git a/lively.serializer2/tests/test.js b/lively.serializer2/tests/test.js index 981350e7e9..41c17d3509 100644 --- a/lively.serializer2/tests/test.js +++ b/lively.serializer2/tests/test.js @@ -182,7 +182,7 @@ describe('marshalling', () => { let obj = { foo: exprObj }; let snap = objPool.snapshotObject(obj); let obj2 = ObjectPool.resolveFromSnapshotAndId(snap, objPool.options); - expect(obj2).deep.property('foo.n', 2); + expect(obj2).has.nested.property('foo.n', 2); expect(obj2.foo).property('__serialize__').to.be.a('function'); }); diff --git a/lively.source-transform/babel/helpers.js b/lively.source-transform/babel/helpers.js new file mode 100644 index 0000000000..290c8b8c38 --- /dev/null +++ b/lively.source-transform/babel/helpers.js @@ -0,0 +1,315 @@ +import t from '@babel/types'; +import { helpers } from 'lively.ast/lib/query.js'; +import { Path } from 'lively.lang'; + +export function getAncestryPath (path) { + return path.getAncestry().map(m => m.inList ? [m.key, m.listKey] : m.key).flat().slice(0, -1).reverse(); +} + +// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +// code generation helpers +// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +function varDecl (name, init = null, kind = 'var') { + if (typeof name === 'string') name = t.Identifier(name); + return t.VariableDeclaration(kind, [t.VariableDeclarator(name, init)]); +} + +export function varDeclOrAssignment (declaredNames, id, init, kind) { + const name = id.name; + return declaredNames.has(name) + // only create a new declaration if necessary + ? t.ExpressionStatement(t.AssignmentExpression('=', id, init)) + : varDecl(id, init, kind || 'var'); +} + +export function assignExpr (assignee, propId, value, computed) { + return t.ExpressionStatement( + t.AssignmentExpression('=', + t.MemberExpression(assignee, propId, computed), + value || t.Identifier('undefined'))); +} + +export function importCall (imported, moduleSource, moduleImportFunc) { + if (typeof imported === 'string') imported = t.StringLiteral(imported); + return { + arguments: [moduleSource].concat(imported || []), + callee: moduleImportFunc, + type: 'CallExpression' + }; +} + +export function varDeclAndImportCall (localId, imported, moduleSource, moduleImportFunc) { + return varDecl(localId, importCall(imported, moduleSource, moduleImportFunc)); +} + +export function importCallStmt (imported, moduleSource, moduleImportFunc) { + return t.ExpressionStatement(importCall(imported, moduleSource, moduleImportFunc)); +} + +function exportCall (exportFunc, local, exportedObj) { + if (typeof local === 'string') local = t.StringLiteral(local); + exportedObj = { ...exportedObj }; // this wont work with recast nodes + return t.CallExpression(exportFunc, [local, exportedObj]); +} + +export function exportFromImport (keyLeft, keyRight, moduleId, moduleExportFunc, moduleImportFunc) { + return exportCall(moduleExportFunc, keyLeft, importCall(keyRight, moduleId, moduleImportFunc)); +} + +export function exportCallStmt (exportFunc, local, exportedObj) { + return t.ExpressionStatement(exportCall(exportFunc, local, exportedObj)); +} + +// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +// naming +// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +export function generateUniqueName (declaredNames, hint) { + let unique = hint; let n = 1; + if (!declaredNames.has) declaredNames = new Set(declaredNames); + while (declaredNames.has(unique)) { + if (n > 1000) throw new Error('Endless loop searching for unique variable ' + unique); + unique = unique.replace(/_[0-9]+$|$/, '_' + (++n)); + } + return unique; +} + +// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +// capturing oobject patters / destructuring +// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +export const annotationSym = Symbol.for('lively.ast-destructuring-transform'); + +function transformArrayPattern (pattern, transformState) { + const declaredNames = transformState.declaredNames; + const p = annotationSym; + const transformed = []; + + for (let i = 0; i < pattern.elements.length; i++) { + const el = pattern.elements[i]; + + // like [a] + if (el.type === 'Identifier') { + let decl = varDecl(el, t.MemberExpression(transformState.parent, t.Identifier(String(i)), true)); + decl[p] = { capture: true }; + transformed.push(decl); + + // like [...foo] + } else if (el.type === 'RestElement') { + let decl = varDecl(el.argument, { + type: 'CallExpression', + arguments: [t.NumericLiteral(i)], + callee: t.MemberExpression(transformState.parent, t.Identifier('slice'), false) + }); + decl[p] = { capture: true }; + transformed.push(decl); + } else if (el.type === 'AssignmentPattern') { + // like [x = 23] + let decl = varDecl( + el.left/* id */, + t.ConditionalExpression( + t.BinaryExpression('===', t.MemberExpression(transformState.parent, t.Identifier(String(i)), true), t.Identifier('undefined')), + el.right, + t.MemberExpression(transformState.parent, t.NumericLiteral(i), true))); + decl[p] = { capture: true }; + transformed.push(decl); + + // like [{x}] + } else { + const helperVarId = t.Identifier(generateUniqueName(declaredNames, transformState.parent.name + '$' + i)); + const helperVar = varDecl(helperVarId, t.MemberExpression(transformState.parent, t.NumericLiteral(i), true)); + // helperVar[p] = {capture: true}; + declaredNames.push(helperVarId.name); + transformed.push(helperVar); + transformed.push(...transformPattern(el, { parent: helperVarId, declaredNames })); // eslint-disable-line no-use-before-define + } + } + return transformed; +} + +function transformObjectPattern (pattern, transformState) { + const declaredNames = transformState.declaredNames; + const p = annotationSym; + const transformed = []; + + for (let i = 0; i < pattern.properties.length; i++) { + const prop = pattern.properties[i]; + + if (prop.type === 'RestElement') { + const knownKeys = pattern.properties.map(ea => ea.key && ea.key.name).filter(Boolean); + let decl = varDecl(prop.argument.name, t.ObjectExpression([])); + const captureDecl = varDecl(prop.argument.name, t.Identifier(prop.argument.name)); + const defCall = t.ExpressionStatement(t.CallExpression(t.FunctionExpression(null, [], + t.BlockStatement([ + t.ForInStatement(varDecl('__key'), transformState.parent, + t.BlockStatement( + [...(knownKeys.length + ? knownKeys.map(knownKey => + t.IfStatement( + t.BinaryExpression('===', t.Identifier('__key'), t.StringLiteral(knownKey)), + t.ContinueStatement(null), null)) + : []), + t.ExpressionStatement( + t.AssignmentExpression('=', + t.MemberExpression(t.Identifier(prop.argument.name), t.Identifier('__key'), true), + t.MemberExpression(transformState.parent, t.Identifier('__key'), true)))] + ))])), [])); + + captureDecl[p] = { capture: true }; + transformed.push(decl, captureDecl, defCall); + } else if (prop.value.type === 'Identifier') { + // like {x: y} + let decl = varDecl(prop.value, t.MemberExpression(transformState.parent, prop.key)); + decl[p] = { capture: true }; + transformed.push(decl); + } else if (prop.value.type === 'AssignmentPattern') { + // like {x = 23} + let decl = varDecl( + prop.value.left/* id */, + t.ConditionalExpression( + t.BinaryExpression('===', t.MemberExpression(transformState.parent, prop.key), t.Identifier('undefined')), + prop.value.right, + t.MemberExpression(transformState.parent, prop.key))); + decl[p] = { capture: true }; + transformed.push(decl); + } else { + // like {x: {z}} or {x: [a]} + const helperVarId = t.Identifier(generateUniqueName( + declaredNames, + transformState.parent.name + '$' + prop.key.name)); + const helperVar = varDecl(helperVarId, t.MemberExpression(transformState.parent, prop.key)); + helperVar[p] = { capture: false }; + declaredNames.push(helperVarId.name); + transformed.push( + ...[helperVar].concat( + transformPattern(prop.value, { parent: helperVarId, declaredNames: declaredNames }))); // eslint-disable-line no-use-before-define + } + } + + return transformed; +} + +export function transformPattern (pattern, transformState) { + // For transforming destructuring expressions into plain vars and member access. + // Takes a var or argument pattern node (of type ArrayPattern or + // ObjectPattern) and transforms it into a set of var declarations that will + // "pull out" the nested properties + // Example: + // var parsed = parse("var [{b: {c: [a]}}] = foo;"); + // var state = {parent: {type: "Identifier", name: "arg"}, declaredNames: ["foo"]} + // transformPattern(parsed.body[0].declarations[0].id, state).map(stringify).join("\n"); + // // => "var arg$0 = arg[0];\n" + // // + "var arg$0$b = arg$0.b;\n" + // // + "var arg$0$b$c = arg$0$b.c;\n" + // // + "var a = arg$0$b$c[0];" + return pattern.type === 'ArrayPattern' + ? transformArrayPattern(pattern, transformState) + : pattern.type === 'ObjectPattern' + ? transformObjectPattern(pattern, transformState) + : []; +} + +// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +// replacement helpers +// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +export function shouldDeclBeCaptured (decl, options) { + return options.excludeDecls.indexOf(decl.id.name) === -1 && + options.excludeDecls.indexOf(decl.id) === -1 && + (!options.includeDecls || options.includeDecls.indexOf(decl.id.name) > -1); +} + +export function shouldRefBeCaptured (ref, options) { + const { topLevel } = options; + if (topLevel.scope.importSpecifiers.includes(ref)) return false; + for (let i = 0; i < topLevel.scope.exportDecls.length; i++) { + const ea = topLevel.scope.exportDecls[i]; + if (ea.declarations && ea.declarations.includes(ref)) return false; + if (ea.declaration === ref) return false; + } + if (options.excludeRefs.includes(ref.object?.name)) return false; + if (options.excludeRefs.includes(ref.name)) return false; + if (options.includeRefs && !options.includeRefs.includes(ref.name)) return false; + return true; +} + +// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +// exclude / include helpers +// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +export function additionalIgnoredDecls ({ varDecls, catches }) { + // const { topLevel } = options; + const ignoreDecls = []; + varDecls.forEach(pathToNode => { + const decl = pathToNode.node; + const parent = pathToNode.parentPath; + if (parent.type === 'ForStatement' || + parent.type === 'ForInStatement' || + parent.type === 'ForOfStatement' || + parent.type === 'ExportNamedDeclaration' + ) ignoreDecls.push(...decl.declarations); + }); + + return catches.map(ea => ea.name) + .concat(ignoreDecls.map(ea => { + if (ea.id.type === 'ArrayPattern') return ea.id; + else if (ea.id.type === 'ObjectPattern') return ea.id; + return ea.id.name; + }).flat()); +} + +export function additionalIgnoredRefs ({ varDecls, catches, importSpecifiers }, options) { + const ignoreDecls = []; + varDecls.forEach(pathToNode => { + const decl = pathToNode.node; + const parent = pathToNode.parentPath; + if (parent.type === 'ForStatement' || + parent.type === 'ForInStatement' || + parent.type === 'ForOfStatement' + ) ignoreDecls.push(...decl.declarations); + }); + + return catches.map(ea => ea.name) + .concat(helpers.declIds(ignoreDecls.map(ea => ea.id || ea.name)) + .concat(options.captureImports ? [] : importSpecifiers) + .map(ea => ea.name)); +} + +export function declarationWrapperCall ( + declarationWrapperNode, + declNode, + varNameLiteral, + varKindLiteral, + valueNode, + recorder, + options +) { + if (declNode) { + // here we pass compile-time meta data into the runtime + const keyVals = []; + let start; let end; let evalId; let sourceAccessorName; let exportConflict; + if (declNode['x-lively-object-meta']) { + ({ start, end, evalId, sourceAccessorName, exportConflict } = declNode['x-lively-object-meta']); + } + if (start !== undefined) keyVals.push(t.ObjectProperty(t.Identifier('start'), t.NumericLiteral(start))); + if (end !== undefined) keyVals.push(t.ObjectProperty(t.Identifier('end'), t.NumericLiteral(end))); + if (exportConflict !== undefined) keyVals.push(t.ObjectProperty(t.Identifier('exportConflict'), t.StringLiteral(exportConflict))); + if (evalId === undefined && options.hasOwnProperty('evalId')) { + evalId = options.evalId; + } + if (sourceAccessorName === undefined && options.hasOwnProperty('sourceAccessorName')) { + sourceAccessorName = options.sourceAccessorName; + } + + if (evalId !== undefined) keyVals.push(t.ObjectProperty(t.Identifier('evalId'), t.NumericLiteral(evalId))); + if (sourceAccessorName) keyVals.push(t.ObjectProperty(t.Identifier('moduleSource'), t.Identifier(sourceAccessorName))); + if (keyVals.length > 0) { + return t.CallExpression( + declarationWrapperNode, [varNameLiteral, varKindLiteral, valueNode, recorder, + t.ObjectExpression(keyVals)/* meta node */]); + } + } + + return t.CallExpression(declarationWrapperNode, [varNameLiteral, varKindLiteral, valueNode, recorder]); +} diff --git a/lively.source-transform/babel/plugin.js b/lively.source-transform/babel/plugin.js new file mode 100644 index 0000000000..9dffc5a359 --- /dev/null +++ b/lively.source-transform/babel/plugin.js @@ -0,0 +1,1273 @@ +/* global require,global */ +import t from '@babel/types'; +import babel from '@babel/core'; +import systemjsTransform from '@babel/plugin-transform-modules-systemjs'; +import dynamicImport from '@babel/plugin-proposal-dynamic-import'; +import { arr, Path } from 'lively.lang'; +import { topLevelFuncDecls } from 'lively.ast/lib/visitors.js'; +import { query } from 'lively.ast'; +import { getGlobal } from 'lively.vm/lib/util.js'; +import { declarationWrapperCall, annotationSym, assignExpr, varDeclOrAssignment, transformPattern, generateUniqueName, varDeclAndImportCall, importCallStmt, shouldDeclBeCaptured, importCall, exportCallStmt, exportFromImport, additionalIgnoredDecls, additionalIgnoredRefs } from './helpers.js'; +import { classToFunctionTransformBabel } from 'lively.classes/class-to-function-transform.js'; + +/* +import { module } from 'lively.modules' +let mod = module('lively.morphic/morph.js'); +s = await mod.source() +fun.timeToRunN(() => { + let res = babel.transform(s, { + sourceMaps: 'inline', + //compact: true, + comments: false, + plugins: [ + [livelyPreTranspile, { module: mod, }], + systemjsTransform, + [livelyPostTranspile, { module: mod }] + ] + }); +}, 10) +*/ + +export const defaultDeclarationWrapperName = 'lively.capturing-declaration-wrapper'; +export const defaultClassToFunctionConverter = t.Identifier('initializeES6ClassForLively'); + +function varDecl (name, init = null, kind = 'var') { + if (typeof name === 'string') name = t.Identifier(name); + return t.VariableDeclaration(kind, [t.VariableDeclarator(name, init)]); +} + +function getVarDecls (scope) { + return new Set(Object.values(scope.bindings).filter(decl => decl.kind !== 'module' && decl.kind !== 'hoisted').map(m => m.path.parentPath).filter(node => node.type === 'VariableDeclaration')); +} + +const babelNodes = { + member: t.MemberExpression, + property: t.ObjectProperty, + property: (kind, key, val) => t.ObjectProperty(key, val), + varDecl, + parse: src => babel.parse(src).program, + assign: t.AssignmentExpression, + assignPattern: t.AssignmentPattern, + id: t.Identifier, + block: t.BlockStatement, + literal: (v) => typeof v === 'string' ? t.StringLiteral(v) : t.NumericLiteral(v), + forInStmt: t.ForInStatement, + continueStmt: t.ContinueStatement, + objectLiteral: t.ObjectExpression, + objectProperty: t.ObjectProperty, + declareVariable: t.DeclareVariable, + logicalExpr: t.LogicalExpression, + exportNamedDeclaration: t.ExportNamedDeclaration, + exportSpecifier: t.ExportSpecifier, + ifStmt: t.IfStatement, + funcExpr: t.FunctionExpression, + arrowFuncExpr: t.ArrowFunctionExpression, + sqncExpr: t.SequenceExpression, + exprStmt: t.ExpressionStatement, + unaryExpr: t.UnaryExpression, + conditional: t.ConditionalExpression, + binaryExpr: t.BinaryExpression, + funcCall: t.CallExpression, + arrayExpr: t.ArrayExpression, + returnStmt: t.ReturnStatement, + exportDefaultDecl: t.ExportDefaultDeclaration +}; + +function processInlineCodeTransformOptions (path, options) { + if (!path.node.comments) return options; + let livelyComment = path.node.comments.map(ea => ea.value).find(v => v?.startsWith('lively.vm ')); + if (!livelyComment) return options; + try { + let inlineOptions = eval('({' + livelyComment.slice('lively.vm '.length) + '});'); + return Object.assign(options, inlineOptions); + } catch (err) { return options; } +} + +function sanitizeOptions (options) { + options = { + ignoreUndeclaredExcept: null, + includeRefs: null, + excludeRefs: (options && options.exclude) || [], + includeDecls: null, + excludeDecls: (options && options.exclude) || [], + es6ExportFuncId: null, + es6ImportFuncId: null, + captureObj: t.Identifier('__rec'), + captureImports: true, + moduleExportFunc: t.Identifier(options && options.es6ExportFuncId || '_moduleExport'), + moduleImportFunc: t.Identifier(options && options.es6ImportFuncId || '_moduleImport'), + declarationWrapper: undefined, + classTransform: (parsed) => parsed, + ...options + }; + + return options; +} + +function wrapInStartEndCall (path, options, parsed) { + // Wraps a piece of code into two function calls: One before the first + // statement and one after the last. Also wraps the entire thing into a try / + // catch block. The end call gets the result of the last statement (if it is + // something that returns a value, i.e. an expression) passed as the second + // argument. If an error occurs the end function is called with an error as + // first parameter + // Why? This allows to easily track execution of code, especially for + // asynchronus / await code! + // Example: + // stringify(wrapInStartEndCall("var y = x + 23; y")) + // // generates code + // try { + // __start_execution(); + // __lvVarRecorder.y = x + 23; + // return __end_execution(null, __lvVarRecorder.y); + // } catch (err) { + // return __end_execution(err, undefined); + // } + + const outerBody = []; + const isProgram = parsed.type === 'Program'; + const funcDecls = topLevelFuncDecls(parsed); + let startFuncNode = options.startFuncNode || t.Identifier('__start_execution'); + let endFuncNode = options.endFuncNode || t.Identifier('__end_execution'); + if (typeof startFuncNode == 'string') startFuncNode = babel.parse(startFuncNode).program.body[0].expression; + if (typeof endFuncNode == 'string') endFuncNode = babel.parse(endFuncNode).program.body[0].expression; + + // 1. Hoist func decls outside the actual eval start - end code. The async / + // generator transforms require this! + funcDecls.forEach(({ node, path }) => { + Path(path).set(parsed, t.ExpressionStatement(node.id)); + outerBody.push(node); + }); + + // 2. add start-eval call + path.pushContainer('body', t.ExpressionStatement(t.CallExpression(startFuncNode, []))); + + // 3. if last statement is an expression, transform it so we can pass it to + // the end-eval call, replacing the original expression. If it's a + // non-expression we record undefined as the eval result + const last = arr.last(path.get('body')); + if (last.node.type === 'ExpressionStatement') { + last.remove(); + path.pushContainer('body', t.ExpressionStatement(t.CallExpression(endFuncNode, [t.Identifier('null'), last.expression]))); + } else if (last.node.type === 'VariableDeclaration' && arr.last(last.node.declarations).id.type === 'Identifier') { + path.pushContainer('body', t.ExpressionStatement(t.CallExpression(endFuncNode, [t.Identifier('null'), arr.last(last.declarations).id]))); + } else { + path.pushContainer('body', t.ExpressionStatement(t.CallExpression(endFuncNode, [t.Identifier('null'), t.Identifier('undefined')]))); + } + + // 4. Wrap that stuff in a try stmt + outerBody.push( + t.TryStatement( + t.BlockStatement(path.node.body), + t.CatchClause(t.Identifier('err'), null, + t.BlockStatement([t.ExpressionStatement(t.CallExpression(endFuncNode, [t.Identifierd('err'), t.Identifier('undefined')]))]) + ))); + + path.replaceWith(isProgram ? t.Program(outerBody) : t.BlockStatement(outerBody)); +} + +function analyzeParsed (path, options, footer, header) { + const undeclaredNames = Object.keys(path.scope.globals); + const varDecls = getVarDecls(path.scope); + const catches = []; + + if (options.footer) footer.push(...babel.parse(options.footer).program.body); + if (options.header) header.push(...babel.parse(options.header).program.body); + + // "ignoreUndeclaredExcept" is null if we want to capture all globals in the toplevel scope + // if it is a list of names we will capture all refs with those names + if (options.ignoreUndeclaredExcept) { + options.excludeRefs = arr.withoutAll(undeclaredNames, options.ignoreUndeclaredExcept).concat(options.excludeRefs); + options.excludeDecls = arr.withoutAll(undeclaredNames, options.ignoreUndeclaredExcept).concat(options.excludeDecls); + } + + options.excludeRefs = options.excludeRefs.concat(options.captureObj.name); + options.excludeDecls = options.excludeDecls.concat(options.captureObj.name); + + // 2. find those var declarations that should not be rewritten. we + // currently ignore var declarations in for loops and the error parameter + // declaration in catch clauses. Also es6 import / export declaration need + // a special treatment + // DO NOT rewrite exports like "export { foo as bar }" => "export { _rec.foo as bar }" + // as this is not valid syntax. Instead we add a var declaration using the + // recorder as init for those exports later + options.excludeRefs = options.excludeRefs.concat(additionalIgnoredRefs({ varDecls, catches }, options)); + options.excludeDecls = options.excludeDecls.concat(additionalIgnoredDecls({ varDecls, catches }, options)); + + if (options.es6ExportFuncId) { + options.excludeRefs.push(options.es6ExportFuncId); + options.excludeRefs.push(options.es6ImportFuncId); + } + + return options; +} + +function getRefs (scope, options) { + const bindings = Object.values(scope.bindings); + const globalRefs = []; + scope.traverse(scope.block, { + AssignmentExpression (path) { + const name = path.node.left?.name; + if (name && scope.globals[name]) { + globalRefs.push(path.node.left); + } + }, + ReferencedIdentifier (path) { + if (scope.globals[path.node.name]) { + globalRefs.push(path.node); + } + } + }); + const exportRe = /ExportDefaultDeclaration|ExportNamedDeclaration|ExportSpecifier/; + function extractRef (ref) { + if (ref.type === 'ObjectPattern') { + return ref.get('properties').map(prop => { + return prop.node?.value ? prop.get('value') : prop.get('key'); + }); + } + if (ref.type === 'ArrayPattern') { + return ref.get('elements').map(extractRef).flat(); + } + return ref; + } + return bindings.map(binding => + binding.referencePaths + .filter(path => !path.parentPath.type.match(exportRe) && !path.type.match(exportRe)) + .concat(binding.constantViolations.filter(path => path.type === 'AssignmentExpression').map(path => path.get('left')).map(extractRef)).flat()) + .flat().map(m => m.node).concat(globalRefs).filter(ref => !options?.excludeRefs.includes(ref.name)); +} + +function es6ModuleTransforms (path, options) { + let moduleId; + path.traverse({ + ExportNamedDeclaration (path) { + const stmt = path.node; + if (stmt.source) { + moduleId = stmt.source; + path.insertAfter(stmt.specifiers.map(specifier => t.ExpressionStatement( + exportFromImport( + t.StringLiteral(specifier.exported.name), + t.StringLiteral(specifier.local.name), + moduleId, options.moduleExportFunc, options.moduleImportFunc)))); + path.remove(); + } else if (stmt.declaration) { + const decls = stmt.declaration.declarations; + if (!decls) { // func decl or class + path.insertAfter([stmt.declaration].concat( + exportCallStmt(options.moduleExportFunc, stmt.declaration.id.name, stmt.declaration.id))); + path.remove(); + } else { + path.insertAfter(decls.map(decl => { + options.excludeDecls.push(decl.id); + return varDecl(decl.id, + t.AssignmentExpression('=', t.MemberExpression(options.captureObj, decl.id, false), options.declarationWrapper + ? declarationWrapperCall( + options.declarationWrapper, + decl, + t.StringLiteral(decl.id.name), + t.StringLiteral(stmt.declaration.kind), + decl.init, options.captureObj, + options) + : decl.init), + stmt.declaration.kind); + }) + .concat(decls.map(decl => exportCallStmt(options.moduleExportFunc, decl.id.name, decl.id)))); + path.remove(); + } + } else { + path.insertAfter(stmt.specifiers.map(specifier => + exportCallStmt(options.moduleExportFunc, specifier.exported.name, + shouldDeclBeCaptured({ id: specifier.local }, options) + ? t.MemberExpression(options.captureObj, specifier.local) + : specifier.local))); + path.remove(); + } + return path.skip(); + }, + ExportDefaultDeclaration (path) { + const stmt = path.node; + if (stmt.declaration && stmt.declaration.id) { + path.insertAfter([stmt.declaration, exportCallStmt(options.moduleExportFunc, 'default', stmt.declaration.id)]); + } else { + let exported = stmt.declaration; + if (exported.type === 'FunctionDeclaration') { + const { params, body, generator } = exported; + exported = t.FunctionExpression(null, params, body, generator); + } + path.insertAfter(exportCallStmt(options.moduleExportFunc, 'default', exported)); + } + path.remove(); + path.skip(); + }, + ExportAllDeclaration (path) { + const stmt = path.node; + const key = t.Identifier(options.es6ExportFuncId + '__iterator__'); + moduleId = stmt.source; + path.replaceWith(t.ForInStatement( + varDecl(key, null), + importCall(null, moduleId, options.moduleImportFunc), + t.ExpressionStatement(exportFromImport(key, key, moduleId, options.moduleExportFunc, options.moduleImportFunc)))); + options.excludeRefs.push(key.name); + options.excludeDecls.push(key.name); + path.skip(); + }, + ImportDeclaration (path) { + const stmt = path.node; + path.insertAfter(stmt.specifiers.length + ? stmt.specifiers.map(specifier => { + const local = specifier.local; + const imported = (specifier.type === 'ImportSpecifier' && specifier.imported.name) || + (specifier.type === 'ImportDefaultSpecifier' && 'default') || + null; + return varDeclAndImportCall(local, imported || null, stmt.source, options.moduleImportFunc); + }) + : [importCallStmt(null, stmt.source, options.moduleImportFunc)]); + path.remove(); + path.skip(); + } + }); +} + +const globalRegex = /(?:"undefined"\s*!==\s*typeof\s+(globalThis|self|global|window)\s*\?\s*\1\s*:)+\s*(globalThis|self|global|window)/; + +function isGlobalRef (identifierPath) { + const variableName = identifierPath.node.name; + const binding = identifierPath.scope.getBinding(variableName); + + if (!binding) { + return false; + } + + const { path: declarationPath } = binding; + + if (declarationPath.isVariableDeclarator()) { + if (declarationPath.node.init) { + return globalRegex.test(declarationPath.get('init').toString()); + } + } + + return false; +} + +function ensureGlobalBinding (ref, options) { + // handles cases where we capture functions that need to be bound to the global + // object in order to be run successfully. + if (ref.type === 'MemberExpression') { + const propName = ref.node.property?.name; + if (['setInterval', 'setTimeout', 'clearTimeout'].includes(propName) && isGlobalRef(ref.get('object'))) { + const globalRef = t.MemberExpression(options.captureObj, t.cloneNode(ref.get('object').node)); + return t.CallExpression(t.MemberExpression(t.MemberExpression(globalRef, t.Identifier(propName)), t.Identifier('bind')), [globalRef]); + } + } + return ref.node; +} + +function replaceVarDeclsAndRefs (path, options) { + const globalInitStmt = '_global = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : global'; + const refsToReplace = new Set(options.scope.refs.filter(ref => !options?.excludeRefs.includes(ref.name))); + const varDeclsToReplace = getVarDecls(path.scope); + const declaredNames = Object.keys(path.scope.bindings); + const currentModuleAccessor = options.classToFunction?.currentModuleAccessor; + let globalDeclarationFound = false; + let intermediateCounter = 0; + + path.traverse({ + MetaProperty (path) { + if (path.node.meta.name === 'import') { + path.replaceWith(currentModuleAccessor + ? t.ObjectExpression( + [ + t.ObjectProperty( + t.Identifier('url'), + t.MemberExpression(currentModuleAccessor, t.Identifier('id'))) + ]) + : t.ObjectExpression([ + t.objectProperty( + t.Identifier('url'), + t.MemberExpression(t.CallExpression(t.Identifier('eval'), [t.StringLiteral("typeof _context !== \'undefined\' ? _context : {}")]), t.Identifier('id')))])); + path.skip(); + } + }, + LogicalExpression (path) { + if (globalDeclarationFound && path.node.right.name === '_global') { + path.replaceWith(path.node.left); + path.skip(); + } + }, + Identifier (path) { + const { node } = path; + if (refsToReplace.has(node)) { + const newNode = t.MemberExpression(options.captureObj, node); + newNode.loc = node.loc; + path.replaceWith(newNode); + path.skip(); + } + }, + Property (path) { + if (refsToReplace.has(path.node) && path.node.shorthand) { + path.replaceWith(t.Property(t.Identifier(path.node.key.name), path.node.value)); + path.skip(); + } + }, + ClassMethod (path) { + // for computed method names we need to insert the capture + // object such that the correct values are retrieved + if (path.node.computed) { + const { key } = path.node; + if (refsToReplace.has(key)) { + if (key.type === 'MemberExpression') { + let curr = path.get('key'); + while (curr.get('object').type === 'MemberExpression') { + curr = curr.get('object'); + } + curr.get('object').replaceWith(t.MemberExpression(options.captureObj, curr.node.object)); + path.skip(); + } + } + } + }, + AssignmentExpression (path) { + // declaration wrapper function for assignments + // "a = 3" => "a = _define('a', 'assignment', 3, _rec)" + const { node } = path; + if (refsToReplace.has(node.left) && options.declarationWrapper) { + path.get('right').replaceWith(declarationWrapperCall( + options.declarationWrapper, + path.get('left').node, + t.StringLiteral(node.left.name), + t.StringLiteral('assignment'), + node.right, + options.captureObj, + options)); + return; + } + // declaration wrapper for destructuring assignments like + // ({ a: blub, b, c } = d); => (_inter = d, _rec.a = _inter.a, _rec.b = _inter.b, _rec.c = _inter.c); + if (node.left.type === 'ObjectPattern') { + const intermediate = t.Identifier(`__inter${intermediateCounter++}__`); + path.replaceWith(t.SequenceExpression( + [t.AssignmentExpression('=', t.MemberExpression(options.captureObj, intermediate), node.right), + ...node.left.properties.map(prop => { + if (prop.type === 'RestElement') { + return t.AssignmentExpression('=', prop.argument.name, t.MemberExpression(options.captureObj, intermediate)); + } + let key = prop.value || prop.key; + // what if the key is itself an assignment? that will not end well. + // something like a = 1 = n; is not valid syntax. + let value = t.MemberExpression(t.MemberExpression(options.captureObj, intermediate), prop.key); + if (key.type === 'AssignmentPattern' && key.right?.type.includes('Literal')) { + // replace instead by a ternary expression that alternates between the default value + // and the actual value present inside the struct + const defaultValue = key.right; + key = refsToReplace.has(key) ? t.MemberExpression(options.captureObj, key.left) : key.left; + value = t.ConditionalExpression(t.BinaryExpression('===', t.UnaryExpression('typeof', value), t.StringLiteral('undefined')), defaultValue, value); + } + return t.AssignmentExpression('=', key, value); + }), t.MemberExpression(options.captureObj, intermediate)])); + } + }, + VariableDeclarator (path) { + if (!globalDeclarationFound && path.node.id.name === '_global') { + globalDeclarationFound = path.getSource() === globalInitStmt; + } + }, + VariableDeclaration (path) { + if (!varDeclsToReplace.has(path) || + path.node.declarations.every(decl => !shouldDeclBeCaptured(decl, options))) { + return; + } + + const replaced = []; const { node } = path; + for (let i = 0; i < node.declarations.length; i++) { + const decl = node.declarations[i]; + + if (!shouldDeclBeCaptured(decl, options)) { + replaced.push(t.VariableDeclaration(node.kind || 'var', [decl])); + continue; + } + + let init = ensureGlobalBinding(path.get('declarations.' + i + '.init'), options) || t.LogicalExpression('||', t.MemberExpression(options.captureObj, decl.id), t.Identifier('undefined')); + + const initWrapped = options.declarationWrapper && decl.id.name + ? declarationWrapperCall( + options.declarationWrapper, + decl, + t.StringLiteral(decl.id.name), + t.StringLiteral(node.kind), + init, + options.captureObj, + options) + : init; + + // Here we create the object pattern / destructuring replacements + if (decl.id.type.includes('Pattern')) { + const declRootName = generateUniqueName(declaredNames, 'destructured_1'); + const declRoot = t.Identifier(declRootName); + const state = { parent: declRoot, declaredNames }; + const extractions = transformPattern(decl.id, state).map(decl => + decl[annotationSym] && decl[annotationSym].capture + ? assignExpr( + options.captureObj, + decl.declarations[0].id, + options.declarationWrapper + ? declarationWrapperCall( + options.declarationWrapper, + null, + t.StringLiteral(decl.declarations[0].id.name), + t.StringLiteral(node.kind), + decl.declarations[0].init, + options.captureObj, + options) + : decl.declarations[0].init, + false) + : decl); + declaredNames.push(declRootName); + options.excludeRefs.push(declRootName); + options.excludeDecls.push(declRootName); + replaced.push(...[varDecl(declRoot, initWrapped, node.kind)].concat(extractions)); + continue; + } + + const rewrittenDecl = assignExpr(options.captureObj, decl.id, initWrapped, false); + rewrittenDecl.loc = decl.loc; + // This is rewriting normal vars + replaced.push(rewrittenDecl); // FIXME: also update the refs here + + if (options.keepTopLevelVarDecls) { + replaced.push(varDecl(decl.id, t.MemberExpression(options.captureObj, decl.id))); + } + } + + if (path.parent.type === 'IfStatement') { + path.replaceWith(t.BlockStatement(replaced)); + return; + } + + if (replaced.length > 1) path.replaceWithMultiple(replaced); // this seems to fuck up the source map? + else path.replaceWith(replaced[0]); + } + }); +} + +function clearEmptyExports (path) { + for (const exp of path.get('body')) { + if (exp.type !== 'ExportNamedDeclaration') continue; + if (!exp.node.declaration && exp.node.specifiers && !exp.node.specifiers.length) { + exp.remove(); + } + } +} + +function getClassDecls (scope) { + return Object.values(scope.bindings).filter(m => m.path.type === 'ClassDeclaration').map(m => m.path); +} + +function replaceClassDecls (path, options) { + if (options.classToFunction && options.classToFunction.transform) { + return options.classToFunction.transform(path, { + ...options.classToFunction, + captureObj: options.captureObj + }); + } + + const classDecls = getClassDecls(path.scope); + if (!classDecls.length) return; + + for (let i = classDecls.length - 1; i >= 0; i--) { + const stmt = classDecls[i]; + if (stmt.parentPath.type.match(/ExportNamedDeclaration|ExportDefaultDeclaration/)) continue; + stmt.insertAfter(assignExpr(options.captureObj, stmt.node.id, stmt.node.id, false)); + } +} + +function splitExportDeclarations (path) { + const stmts = path.get('body'); + for (let stmt of stmts) { + const { declaration, type } = stmt.node; + if (type !== 'ExportNamedDeclaration' || + !declaration || declaration.type !== 'VariableDeclaration' || + declaration.declarations.length <= 1) { continue; } + + const decls = declaration.declarations; + const newNodes = []; + for (let j = 0; j < decls.length; j++) { + newNodes.push(t.ExportNamedDeclaration(varDecl(decls[j].id, decls[j].init, declaration.kind), [])); + } + stmt.replaceWithMultiple(newNodes); + } +} + +function insertCapturesForImportAndExportDeclarations (path, options) { + const declaredNames = new Set(Object.keys(path.scope.bindings)); + function handleDeclarations (path) { + const stmt = path.node; + path.insertAfter(stmt.declaration.declarations.map(decl => { + let assignVal = decl.id; + if (options.declarationWrapper) { + const alreadyWrapped = decl.init.callee && + decl.init.callee.name === options.declarationWrapper.name; + if (!alreadyWrapped) { + assignVal = declarationWrapperCall( + options.declarationWrapper, + decl, + t.StringLiteral(decl.id.name), + t.StringLiteral('assignment'), + decl.id, + options.captureObj, + options); + } + } + return assignExpr(options.captureObj, decl.id, assignVal, false); + })); + } + return path.traverse({ + ExportNamedDeclaration (path) { + const stmt = path.node; + + if (stmt.declaration?.declarations) { + handleDeclarations(path); + } else if (stmt.declaration?.type === 'ClassDeclaration') { + path.insertAfter(assignExpr(options.captureObj, stmt.declaration.id, stmt.declaration.id, false)); + } + + if (stmt.specifiers.length && !stmt.source) { + path.insertBefore(arr.compact(stmt.specifiers.map(specifier => + declaredNames.has(specifier.local.name) + ? null + : varDeclOrAssignment(declaredNames, specifier.local, t.MemberExpression(options.captureObj, specifier.local))))); + } + }, + ExportDefaultDeclaration (path) { + const stmt = path.node; + if (!stmt.declaration) return; + if (stmt.declaration.type.match(/StringLiteral|NumericLiteral/)) { + // default export of an unnamed primitive value, i.e. + // "export default "foo"", "export default 27;" + const decl = stmt.declaration; + const refId = generateUniqueName(declaredNames, '$' + decl.extra.raw.split('"').join('')); + path.insertBefore(assignExpr(options.captureObj, t.Identifier(refId), stmt.declaration, false)); + path.get('declaration').replaceWith(t.Identifier(refId)); + } else if (stmt.declaration.declarations) { + handleDeclarations(path); + } else if (stmt.declaration.type === 'ClassDeclaration') { + path.insertAfter(assignExpr(options.captureObj, stmt.declaration.id, stmt.declaration.id, false)); + } + if (!stmt.declaration.type.includes('Declaration') && + (stmt.declaration.type === 'Identifier' || stmt.declaration.id) && + !declaredNames.has(stmt.declaration.name)) { + path.insertBefore( + varDeclOrAssignment(declaredNames, stmt.declaration, t.MemberExpression(options.captureObj, stmt.declaration))); + } + }, + ImportDeclaration (path) { + if (!options.captureImports) return; + const stmt = path.node; + if (!stmt.specifiers.length) return; + path.insertAfter(stmt.specifiers.map(specifier => + assignExpr(options.captureObj, specifier.local, specifier.local, false))); + } + }); +} + +function getFuncDecls (scope) { + return Object.values(scope.bindings).filter(m => m.kind === 'hoisted').map(m => m.path); +} + +function putFunctionDeclsInFront (path, options) { + let funcDecls = getFuncDecls(path.scope, options); + if (!funcDecls.length) return; + const putInFront = []; + + for (let i = funcDecls.length; i--;) { + const declPath = funcDecls[i]; + const parentPath = declPath.parentPath; + const decl = declPath.node; + const funcId = decl.id; + + if (!funcId || !shouldDeclBeCaptured(decl, options)) continue; + // ge the parent so we can replace the original function: + const init = options.declarationWrapper + ? declarationWrapperCall( + options.declarationWrapper, + decl, // FIXME: this is not babel compatible + t.StringLiteral(funcId.name), + t.StringLiteral('function'), + funcId, options.captureObj, + options) + : funcId; + + const declFront = t.cloneNode(decl); + + if (parentPath.type === 'Program') { + if (declPath.getAllNextSiblings().length > 0) declPath.remove(); + else declPath.replaceWith(funcId); + } else if (parentPath.type === 'ExportNamedDeclaration') { + // If the function is exported we change the export declaration into a reference + // const parentIndexInBody = scope.node.body.indexOf(parent); + parentPath.replaceWith(t.ExportNamedDeclaration(null, [t.ExportSpecifier(funcId, funcId)], null)); + } else if (parentPath.type === 'ExportDefaultDeclaration') { + parentPath.replaceWith(t.ExportDefaultDeclaration(funcId)); + } + + // hoist the function to the front, also it's capture + putInFront.unshift(assignExpr(options.captureObj, funcId, init, false)); + putInFront.unshift(declFront); + } + path.unshiftContainer('body', putInFront); +} + +export function rewriteToCaptureTopLevelVariables (path, options) { + let footer = []; + let header = []; + + options = sanitizeOptions(options); + + options = analyzeParsed(path, options, footer, header); + + if (options.es6ExportFuncId) { + es6ModuleTransforms(path, options); + path.scope.crawl(); + options.scope.refs = getRefs(path.scope, options); + } + + replaceVarDeclsAndRefs(path, options); + + clearEmptyExports(path, options); + + replaceClassDecls(path, options); + + splitExportDeclarations(path, options); + + path.scope.crawl(); + + insertCapturesForImportAndExportDeclarations(path, options); + + putFunctionDeclsInFront(path, options); + path.scope.crawl(); + + path.unshiftContainer('body', header); + path.pushContainer('body', footer); +} + +function ensureComponentDescriptors (path, moduleId, options) { + // check first for top level decls + const varDecls = getVarDecls(path.scope); + let earlyReturn = false; + + path.traverse({ + ExpressionStatement (sub) { + if (sub.node.expression?.callee?.name === 'component') { + sub.stop(); + path.replaceWith(t.CallExpression(t.MemberExpression(t.Identifier('component'), t.Identifier('for')), [ + t.ArrowFunctionExpression([], t.CallExpression(t.Identifier('component'), sub.node.expression.arguments)), + t.ObjectExpression([t.ObjectProperty(t.Identifier('module'), t.StringLiteral(moduleId))]) + ])); + earlyReturn = true; + } + } + }); + + if (earlyReturn) return; + + path.traverse({ + VariableDeclarator (path) { + const node = path.node; + const isCaptured = varDecls.has(path); + const componentRef = node.id.name; + if (node.init?.callee?.name !== 'component') return path.skip(); + const spec = node.init.arguments; + path.replaceWith( + t.VariableDeclarator(t.Identifier(componentRef), t.CallExpression(t.MemberExpression(t.Identifier('component'), t.Identifier('for')), [ + t.ArrowFunctionExpression([], t.CallExpression(t.Identifier('component'), spec)), + t.ObjectExpression([ + t.ObjectProperty(t.Identifier('module'), t.StringLiteral(moduleId)), + t.ObjectProperty(t.Identifier('export'), t.StringLiteral(componentRef)), + t.ObjectProperty(t.Identifier('range'), t.ObjectExpression([ + t.ObjectProperty(t.Identifier('start'), t.NumericLiteral(node.start)), + t.ObjectProperty(t.Identifier('end'), t.NumericLiteral(node.end)) + ])) + ]), + t.Identifier('System'), + ...isCaptured ? [t.Identifier(options.varRecorderName), t.StringLiteral(componentRef)] : [] + ])) + ); + } + }); +} + +function getExportDecls (scope) { + return [...new Set(Object.values(scope.bindings).map(m => m.referencePaths.filter(m => m.parentPath.parentPath?.type.match(/ExportNamedDeclaration|ExportDefaultDeclaration/))).flat().map(m => m.parent))]; +} + +function evalCodeTransform (path, state, options) { + // A: Rewrite the component definitions to create component descriptors. + let { moduleName } = options; + const renamedExports = {}; + if (state.opts.module) state.opts.module._renamedExports = renamedExports; + + getExportDecls(path.scope) + .filter(stmt => stmt.local?.name !== stmt.exported?.name) + .forEach(stmt => renamedExports[stmt.exported.name] = stmt.local?.name || stmt.imported?.name); + + let annotation = {}; + + processInlineCodeTransformOptions(path, options); + + if ((moduleName && moduleName.endsWith('cp.js') || options.wrapInStartEndCall) && state.file.code) { + ensureComponentDescriptors(path, moduleName, options); + } + + // 2. Annotate definitions with code location. This is being used by the + // function-wrapper-source transform. + options.scope = { + classDecls: getClassDecls(path.scope), + funcDecls: getFuncDecls(path.scope), + refs: getRefs(path.scope), + varDecls: getVarDecls(path.scope) + }; + + if (options.hasOwnProperty('evalId')) annotation.evalId = options.evalId; + if (options.sourceAccessorName) annotation.sourceAccessorName = options.sourceAccessorName; + if (options.addSourceMeta !== false) { + [...options.scope.classDecls, ...options.scope.funcDecls].forEach(({ node }) => { + node['x-lively-object-meta'] = { ...annotation, start: node.start, end: node.end }; + if (renamedExports.hasOwnProperty(node.id.name)) { node['x-lively-object-meta'] = { exportConflict: renamedExports[node.id.name] }; } + }); + options.scope.refs.forEach(ref => { + if (renamedExports.hasOwnProperty(ref.name)) { ref['x-lively-object-meta'] = { exportConflict: renamedExports[ref.name] }; } + }); + options.scope.varDecls.forEach(({ node }) => + node.declarations.forEach(decl => { + decl['x-lively-object-meta'] = { ...annotation, start: decl.start, end: decl.end }; + if (renamedExports.hasOwnProperty(decl.id.name)) { + decl['x-lively-object-meta'].exportConflict = renamedExports[decl.id.name]; + } + })); + } + + // transforming experimental ES features into accepted es6 form... + // This can be done by babel... + // objectSpreadTransform(path); + + // 3. capture top level vars into topLevelVarRecorder "environment" + + if (!options.topLevelVarRecorder && options.topLevelVarRecorderName) { + let G = getGlobal(); + if (options.topLevelVarRecorderName === 'GLOBAL') { // "magic" + options.topLevelVarRecorder = getGlobal(); + } else { + options.topLevelVarRecorder = Path(options.topLevelVarRecorderName).get(G); + } + } + + if (options.topLevelVarRecorder) { + // capture and wrap logic + let blacklist = (options.dontTransform || []).concat(['arguments']); + let undeclaredToTransform = options.recordGlobals ? null/* all */ : arr.withoutAll(Object.keys(options.topLevelVarRecorder), blacklist); + let varRecorder = t.Identifier(options.varRecorderName || '__lvVarRecorder'); + let es6ClassToFunctionOptions = null; + + if (options.declarationWrapperName || typeof options.declarationCallback === 'function') { + // 2.1 declare a function that wraps all definitions, i.e. all var + // decls, functions, classes etc that get captured will be wrapped in this + // function. This allows to define some behavior that is run whenever + // variables get initialized or changed as well as transform values. + // The parameters passed are: + // name, kind, value, recorder + // Note that the return value of declarationCallback is used as the + // actual value in the code being executed. This allows to transform the + // value as necessary but also means that declarationCallback needs to + // return sth meaningful! + let declarationWrapperName = options.declarationWrapperName || defaultDeclarationWrapperName; + + options.declarationWrapper = t.MemberExpression( + t.Identifier(options.varRecorderName || '__lvVarRecorder'), + t.StringLiteral(declarationWrapperName), true); + + if (options.declarationCallback) { options.topLevelVarRecorder[declarationWrapperName] = options.declarationCallback; } + } + + let transformES6Classes = options.hasOwnProperty('transformES6Classes') + ? options.transformES6Classes + : true; + if (transformES6Classes) { + // Class declarations and expressions are converted into a function call + // to `createOrExtendClass`, a helper that will produce (or extend an + // existing) constructor function in a way that allows us to redefine + // methods and properties of the class while keeping the class object + // identical + const scope = { + decls: [], + resolvedRefMap: new Map() + }; + Object.values(path.scope.bindings).map(binding => { + let decl = binding.path.node; + if (decl.type === 'ImportSpecifier' || decl.type === 'ImportDefaultSpecifier') decl = binding.path.parent; + scope.decls.push([decl, binding.identifier]); // this data format is just weird af? + binding.referencePaths.forEach(ref => { + scope.resolvedRefMap.set(ref.node, { decl, declId: binding.identifier, ref }); + }); + }); + es6ClassToFunctionOptions = { + currentModuleAccessor: options.currentModuleAccessor, + classHolder: varRecorder, + functionNode: t.MemberExpression(varRecorder, defaultClassToFunctionConverter), + declarationWrapper: options.declarationWrapper, + evalId: options.evalId, + sourceAccessorName: options.sourceAccessorName, + scope, + nodes: babelNodes, + ...options.classToFunction, + transform: (parsed, options) => { + classToFunctionTransformBabel(path, state, options); + } + }; + } + + // 3.2 Here we call out to the actual code transformation that installs the captured top level vars + rewriteToCaptureTopLevelVariables( + path, + // FIXME: this weird remapping should be removed, completely unnessecary + { + footer: options.footer, + header: options.header, + topLevel: options.topLevel, + scope: options.scope, + es6ImportFuncId: options.es6ImportFuncId, + es6ExportFuncId: options.es6ExportFuncId, + ignoreUndeclaredExcept: undeclaredToTransform, + exclude: blacklist, + captureObj: varRecorder, + declarationWrapper: options.declarationWrapper || undefined, + classToFunction: es6ClassToFunctionOptions, + evalId: options.evalId, + sourceAccessorName: options.sourceAccessorName, + keepTopLevelVarDecls: options.keepTopLevelVarDecls + }); + } + + if (options.wrapInStartEndCall) { + wrapInStartEndCall(path, { + startFuncNode: options.startFuncNode, + endFuncNode: options.endFuncNode + }, state.parsed); + } + + if (options.sourceURL) { + t.addComment(path.node, 'trailing', '# sourceURL=' + options.sourceURL.replace(/\s/g, '_')); + } +} + +function isMochaTest (scope) { + return !!Object.values(scope.bindings).filter(binding => binding.path.type === 'ImportSpecifier').map(binding => binding.path.parentPath).find(binding => binding.get('source.extra.rawValue').node?.match(/(mocha-es6|mocha-es6\/index\.js)$/)); +} + +export function livelyPreTranspile (api, options) { + let isGlobal = true; + + if (options.module) { + const { module } = options; + let { + sourceAccessorName, + recorder, + recorderName, + // dontTransform, + varDefinitionCallbackName, + embedOriginalCode = true + } = module; + + isGlobal = recorderName === 'System.global'; + + sourceAccessorName = embedOriginalCode ? sourceAccessorName : undefined; + + options = { + ...options, + moduleName: module.shortName(), + topLevelVarRecorder: recorder, + varRecorderName: recorderName, + sourceAccessorName, + dontTransform: [ + 'global', 'self', + '_moduleExport', '_moduleImport', + 'localStorage', // for Firefox, see fetch + // doesn't like to be called as a method, i.e. __lvVarRecorder.fetch + module.recorderName, module.sourceAccessorName, + 'prompt', 'alert', 'fetch', 'getComputedStyle' + ].concat(query.knownGlobals), + recordGlobals: true, + declarationWrapperName: varDefinitionCallbackName, + evalId: module.nextEvalId(), + currentModuleAccessor: t.CallExpression( + t.MemberExpression( + t.CallExpression( + t.MemberExpression(t.MemberExpression(t.Identifier(recorderName), t.Identifier('System')), t.Identifier('get')), + [t.StringLiteral('@lively-env')]), + t.Identifier('moduleEnv')), + [t.StringLiteral(module.id)]) + }; + + options.header = (options.header || '') + (options.debug ? `console.log("[lively.modules] executing module ${module.id}");\n` : ''); + options.footer = options.footer || ''; + if (isGlobal) { + // FIXME how to update exports in that case? + delete options.declarationWrapperName; + } + } + + return { + visitor: { + Program (path, state) { + if (!isGlobal) { + const { module, sourceAccessorName, varRecorderName } = options; + options.header += `SystemJS.get("@lively-env").evaluationStart("${module.id}");\n` + + `var ${varRecorderName} = SystemJS.get("@lively-env").moduleEnv("${module.id}").recorder;\n` + + (sourceAccessorName ? `\nvar ${sourceAccessorName} = ${JSON.stringify(state.file.code)};\n` : ''); + options.footer += `\nSystemJS.get("@lively-env").evaluationEnd("${module.id}");`; + // also check for the mocha test! + if (!isMochaTest(path.scope)) options.dontTransform?.push(...Object.keys(path.scope.globals)); + } + + evalCodeTransform(path, state, options); + } + } + }; +} + +function rewriteToRegisterModuleToCaptureSetters (path, state, options) { + // for rewriting the setters part in code like + // ```js + // System.register(["a.js"], function (_export, _context) { + // var a, _rec; + // return { + // setters: [function(foo_a_js) { a = foo_a_js.x }], + // execute: function () { _rec.x = 23 + _rec.a; } + // }; + // }); + // ``` + // This allows us to capture (and potentially re-export) imports and their + // changes without actively running the module again. + + options = { + captureObj: t.Identifier(options.varRecorderName || '__rec'), + exclude: [], + declarationWrapper: undefined, + ...options + }; + + const { _renamedExports: renamedExports = {} } = state.opts.module || {}; + + const registerCall = path.get('body.0.expression'); + + const printAst = () => babel.transformFromAstSync(path.node).code.slice(0, 300); + if (registerCall.node.callee.object.name !== 'System') { + throw new Error(`rewriteToRegisterModuleToCaptureSetters: input doesn't seem to be a System.register call: ${printAst()}...`); + } + if (registerCall.node.callee.property.name !== 'register') { + throw new Error(`rewriteToRegisterModuleToCaptureSetters: input doesn't seem to be a System.register call: ${printAst()}...`); + } + const registerBody = registerCall.get('arguments.1.body.body'); + const registerReturn = arr.last(registerBody); + + if (registerReturn.node.type !== 'ReturnStatement') { + throw new Error(`rewriteToRegisterModuleToCaptureSetters: input doesn't seem to be a System.register call, at return statement: ${printAst()}...`); + } + const setters = registerReturn.get('argument.properties').find(({ node: prop }) => prop.key.name === 'setters'); + if (!setters) { + throw new Error(`rewriteToRegisterModuleToCaptureSetters: input doesn't seem to be a System.register call, at finding setters: ${printAst()}...`); + } + const execute = registerReturn.get('argument.properties').find(({ node: prop }) => prop.key.name === 'execute'); + if (!execute) { + throw new Error(`rewriteToRegisterModuleToCaptureSetters: input doesn't seem to be a System.register call, at finding execute: ${printAst()}...`); + } + + path.get('directives').find(d => d.get('value.value').node === 'format esm')?.remove(); // remove esm directive if still present + + // in each setter function: intercept the assignments to local vars and inject capture object + setters.get('value.elements').forEach(pathToFun => { + const fun = pathToFun.node; + pathToFun.replaceWith(t.FunctionExpression(fun.id, [t.AssignmentPattern(fun.params[0], t.ObjectExpression([]))], t.BlockStatement(fun.body.body.map(stmt => { + if (stmt.type !== 'ExpressionStatement' || + stmt.expression.type !== 'AssignmentExpression' || + stmt.expression.left.type !== 'Identifier' || + options.exclude.includes(stmt.expression.left.name)) return stmt; + + const id = stmt.expression.left; + if (renamedExports.hasOwnProperty(id.name)) { + id['x-lively-object-meta'] = { exportConflict: renamedExports[id.name] }; + } + // FIXME: at this point, we lost the info about the renamed export from preTranspile... how do we get that info to here? + const rhs = options.declarationWrapper + ? declarationWrapperCall( + options.declarationWrapper, + id, + t.StringLiteral(id.name), + t.StringLiteral('var'), + stmt.expression, + options.captureObj, + options) + : stmt.expression; + return t.ExpressionStatement(t.AssignmentExpression('=', t.MemberExpression(options.captureObj, id), rhs)); + })))); + }); + const execFunctionBody = execute.get('value.body.body'); + let captureInitialize = execFunctionBody.find(({ node: stmt }) => + stmt.type === 'ExpressionStatement' && + stmt.expression.type === 'AssignmentExpression' && + stmt.expression.left.name === options.captureObj.name) || execFunctionBody.find(({ node: stmt }) => + stmt.type === 'VariableDeclaration' && + stmt.declarations[0].id && + stmt.declarations[0].id.name === options.captureObj.name); + + if (captureInitialize) { + registerBody[0].insertAfter(captureInitialize.node); + captureInitialize.remove(); + } + + // FIXME: is this ever a thing? + if (options.sourceAccessorName) { + let origSourceInitialize = execFunctionBody.find(stmt => + stmt.type === 'ExpressionStatement' && + stmt.expression.type === 'AssignmentExpression' && + stmt.expression.left.name === options.sourceAccessorName) || + execFunctionBody.find(stmt => + stmt.type === 'VariableDeclaration' && + stmt.declarations[0].id && + stmt.declarations[0].id.name === options.sourceAccessorName); + if (origSourceInitialize) { + registerBody[0].insertAfter(origSourceInitialize.node); + origSourceInitialize.remove(); + } + } +} + +export function livelyPostTranspile (api, options) { + if (options.module) { + const { module } = options; + const captureObj = t.Identifier(module.recorderName); + options = { + captureObj, + topLevelVarRecorder: module.recorder, + dontTransform: module.dontTransform, + declarationWrapper: t.MemberExpression( + captureObj, + t.StringLiteral(module.varDefinitionCallbackName), true) + }; + } + + return { + visitor: { + Program: { + exit (path, state) { + if (!options.topLevelVarRecorder) { + path.stop(); + return; + } + + let blacklist = (options.dontTransform || []).concat(['arguments']); + rewriteToRegisterModuleToCaptureSetters(path, state, { exclude: blacklist, ...options }); + } + } + } + }; +} + +export function livelyModuleLoadTranspile (api, options) { + return { + visitor: { + CallExpression (path) { + if (path.get('callee.property').node?.name === 'register') { + options.depNames.push(...path.node.arguments[0].elements.map(ea => ea.value)); + const declareFuncNode = path.node.arguments[1]; + const body = path.parentPath; + // maybe need to be all wrapped in expression statements? + body.replaceWithMultiple([ + varDecl('SystemJS', t.Identifier('System')), + varDecl('__moduleName', t.StringLiteral(options.module.fullName())), + t.ExpressionStatement(declareFuncNode) + ]); + t.addComment(body.node, 'trailing', '# sourceURL=' + options.module.fullName()); + + path.stop(); // do not proceed with anything + } + } + } + }; +} + +class BabelTranspiler { + constructor (System, moduleId, env) { + this.System = System; + this.moduleId = moduleId; + this.env = env; + } + + transpileDoit (source) { + // wrap in async function so we can use await top-level + let System = this.System; + var source = '(async function(__rec) {\n' + source.replace(/(\/\/# sourceURL=.+)$|$/, '\n}).call(this);\n$1'); // eslint-disable-line no-var + let opts = System.babelOptions; + let needsBabel = (opts.plugins && opts.plugins.length) || (opts.presets && opts.presets.length); + return needsBabel + ? System.global.babel.transform(source, opts).code + : source; + } + + transpileModule (source, options) { + let System = this.System; + let opts = Object.assign({}, System.babelOptions); + opts.sourceFileName = options.module?.id; + opts.plugins = opts.plugins + ? opts.plugins.slice() + : [ + [livelyPreTranspile, options], + dynamicImport, + systemjsTransform, + // choose either one + options.esmLoad ? [livelyModuleLoadTranspile, options] : [livelyPostTranspile, options] + ]; + return babel.transform(source, opts); + } +} +// setupBabelTranspiler(System) +export function setupBabelTranspiler (System) { + if (typeof require !== 'undefined') { System._nodeRequire = eval('require'); } // hack to enable dynamic requires in bundles + if (typeof global !== 'undefined') { global.__webpack_require__ = global.__non_webpack_require__ = System._nodeRequire; } + + System.global = typeof global === 'undefined' ? window : global; + System.trace = true; // in order to harvest more metadata for lively.modules + if (System._nodeRequire) { + const Module = System._nodeRequire('module'); + // wrap _load() such that it attaches the __esModule flag to each imported native module + // this ensures the interoperability to 0.21 SystemJS + const origLoad = Module._load; + // this also overrides native requires, which is not what we want really + Module._load = (...args) => { + let exports = origLoad(...args); + const isCoreModule = !!System.loads?.['@node/' + args[0]]; + if (isCoreModule && !args[1].loaded && !exports.prototype) { + exports = Object.assign(Object.create(exports.prototype || {}), exports); + if (!exports.default) exports.default = exports; + exports.__esModule = true; + } + return exports; + }; + } + + function translate (load, opts) { + const { code, map } = new BabelTranspiler(this, load.name, {}).transpileModule(load.source, { ...opts, module: load.metadata.module }); + load.metadata.sourceMap = map; + return code; + } + System.set('lively.transpiler.babel', System.newModule({ default: BabelTranspiler, translate })); + System._loader.transpilerPromise = Promise.resolve({ translate }); + System.translate = async (load, opts) => await translate.bind(System)(load, opts); + System.config({ + transpiler: 'lively.transpiler.babel', + babelOptions: { + sourceMaps: true, + compact: false, + comments: true, + presets: [] + } + }); +} diff --git a/lively.source-transform/babel/scopes.js b/lively.source-transform/babel/scopes.js new file mode 100644 index 0000000000..cce9effee3 --- /dev/null +++ b/lively.source-transform/babel/scopes.js @@ -0,0 +1,256 @@ +import { getAncestryPath } from './helpers.js'; +import { arr } from 'lively.lang'; + +export function scopes (path) { + function newScope (path, parentScope) { + const scope = { + node: path.node, + varDecls: [], + varDeclPaths: [], + funcDecls: [], + funcDeclPaths: [], + classDecls: [], + classDeclPaths: [], + classExprs: [], + classExprPaths: [], + methodDecls: [], + methodDeclPaths: [], + importSpecifiers: [], + importSpecifierPaths: [], + exportDecls: [], + exportDeclPaths: [], + refs: [], + refPaths: [], + thisRefs: [], + params: [], + catches: [], + subScopes: [], + resolvedRefMap: new Map() + }; + if (parentScope) parentScope.subScopes.push(scope); + return scope; + } + + function visitFunctionParameters (params) { + params.forEach((param, i) => { + if (param.type === 'ObjectPattern') { + visitFunctionParameters(param.get('properties')); + } + if (param.type === 'Property' && param.value.type === 'AssignmentPattern') { + param.get('value.right').visit(); + } + // AssignmentPattern = default params + // only visit the right side of a default param, we track the declarations + // in scope.params specificially + if (param.type === 'AssignmentPattern') { + param.get('right').visit(); + } + }); + } + + function withScopeDo(nextScope, cb) { + currScope = nextScope; + scopeStack.push(currScope); + cb(); + scopeStack.pop(); + currScope = arr.last(scopeStack); + } + + function visitFunction (path, scope) { + scope = newScope(path, scope); + withScopeDo(scope, () => visitFunctionParameters(path.get('params'))); + scope.params = Array.prototype.slice.call(path.node.params); + return scope; + } + + let currScope = newScope(path); + const scopeStack = [currScope]; + + const visitor = { + VariableDeclaration (path) { + currScope.varDecls.push(path.node); + currScope.varDeclPaths.push(getAncestryPath(path)); + }, + + VariableDeclarator (path) { + path.skip(); + path.get('init').visit(); + }, + + FunctionDeclaration (path) { + path.skip(); + const newScope = visitFunction(path, currScope); + currScope.funcDecls.push(path.node); + currScope.funcDeclPaths.push(getAncestryPath(path)); + withScopeDo(newScope, () => path.get('body').visit()); + }, + + FunctionExpression (path) { + path.skip(); + withScopeDo(visitFunction(path, currScope), () => path.get('body').visit()) + }, + + ArrowFunctionExpression (path) { + path.skip(); + withScopeDo(visitFunction(path, currScope), () => path.get('body').visit()) + }, + + Identifier (path) { + currScope.refs.push(path.node); + currScope.refPaths.push(getAncestryPath(path)); + }, + + 'MemberExpression|OptionalMemberExpression' (path) { + path.skip(); + path.get('object').visit(); + if (path.node.computed) { + path.get('property').visit(); + } + }, + + ObjectProperty (path) { + path.skip(); + if (path.node.computed) { + path.get('key').visit(); + } + // value is of types Expression + path.get('value').visit(); + }, + + ThisExpression (path) { + currScope.thisRefs.push(path.node); + }, + + TryStatement (path) { + path.skip(); + const { node } = path; + // block is of types BlockStatement + path.get('block').visit(); + // handler is of types CatchClause + if (node.handler) { + path.get('handler').visit(); + currScope.catches.push(node.handler.param); + } + // finalizer is of types BlockStatement + if (node.finalizer) { + path.get('finalizer').visit(); + } + }, + + IfStatement (path) { + path.skip(); + path.get('test').visit(); + + withScopeDo(newScope(path, currScope), () => path.get('consequent').visit()) + + if (path.node.alternate) { + withScopeDo(newScope(path, currScope), () => path.get('alternate').visit()) + } + }, + + For (path) { + path.skip(); + const loopScope = newScope(path, currScope); + withScopeDo(path.get('left').node?.kind === 'var' ? currScope : loopScope, () => path.get('left').visit()); + withScopeDo(path.get('right').node?.kind === 'var' ? currScope : loopScope, () => path.get('right').visit()); + withScopeDo(path.get('init').node?.kind === 'var' ? currScope : loopScope, () => path.get('init').visit()); + withScopeDo(loopScope, () => { + path.get('update').visit(); + path.get('test').visit(); + path.get('body').visit(); + }); + }, + + LabeledStatement (path) { + path.skip(); + path.get('body').visit(); + }, + + ClassDeclaration (path) { + path.skip(); + currScope.classDecls.push(path.node); + currScope.classDeclPaths.push(getAncestryPath(path)); + + if (path.node.superClass) path.get('superClass').visit(); + + path.get('body').visit(); + }, + + ClassExpression (path) { + path.skip(); + + if (path.node.id) { + currScope.classExprs.push(path.node); + currScope.classExprPaths.push(getAncestryPath(path)); + } + + if (path.node.superClass) path.get('superClass').visit(); + + path.get('body').visit(); + }, + + 'ClassMethod|ObjectMethod' (path) { + const { node } = path; + if (node.computed) { + let curr = node.key; + while (curr.type === 'MemberExpression') curr = curr.object; + if (curr.type === 'Identifier') { + currScope.refs.push(curr); + } + } + path.skip(); + withScopeDo(visitFunction(path, currScope), () => path.get('body').visit()) + }, + + MetaProperty (path) { path.skip(); }, + + BreakStatement (path) { path.skip(); }, + + ContinueStatement (path) { path.skip(); }, + + // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + // es6 modules + ImportSpecifier (path) { + path.skip(); + currScope.importSpecifiers.push(path.node.local); + currScope.importSpecifierPaths.push(getAncestryPath(path)); + }, + + ImportDefaultSpecifier (path) { + path.skip(); + currScope.importSpecifiers.push(path.node.local); + currScope.importSpecifierPaths.push(getAncestryPath(path)); + }, + + ImportNamespaceSpecifier (path) { + path.skip(); + currScope.importSpecifiers.push(path.node.local); + currScope.importSpecifierPaths.push(getAncestryPath(path)); + }, + + ExportSpecifier (path) { + path.skip(); + path.get('local').visit(); + }, + + ExportNamedDeclaration (path) { + currScope.exportDecls.push(path.node); + currScope.exportDeclPaths.push(getAncestryPath(path)); + if (path.node.source) path.skip(); + }, + + ExportDefaultDeclaration (path) { + currScope.exportDecls.push(path.node); + currScope.exportDeclPaths.push(getAncestryPath(path)); + }, + + ExportAllDeclaration (path) { + currScope.exportDecls.push(path.node); + currScope.exportDeclPaths.push(getAncestryPath(path)); + } + }; + + path.traverse(visitor); + + return currScope; +} diff --git a/lively.source-transform/capturing.js b/lively.source-transform/capturing.js index 9728b23b2b..be48e72277 100644 --- a/lively.source-transform/capturing.js +++ b/lively.source-transform/capturing.js @@ -1,9 +1,8 @@ -import { obj, chain, arr, Path } from 'lively.lang'; +import { obj, arr, Path } from 'lively.lang'; import { parse, stringify, query, - transform, nodes, ReplaceManyVisitor, ReplaceVisitor @@ -19,146 +18,9 @@ const { exprStmt, conditional, binaryExpr, - funcCall, - block + funcCall } = nodes; const { topLevelDeclsAndRefs, helpers: queryHelpers } = query; -const { transformSingleExpression, wrapInStartEndCall } = transform; - -export function rewriteToCaptureTopLevelVariables (parsed, assignToObj, options) { - /* replaces var and function declarations with assignment statements. - * Example: - stringify( - rewriteToCaptureTopLevelVariables( - parse("var x = 3, y = 2, z = 4"), - {name: "A", type: "Identifier"}, - {exclude: ['z']})); - // => "A.x = 3; A.y = 2; z = 4" - */ - - if (!assignToObj) assignToObj = { type: 'Identifier', name: '__rec' }; - - options = { - ignoreUndeclaredExcept: null, - includeRefs: null, - excludeRefs: (options && options.exclude) || [], - includeDecls: null, - excludeDecls: (options && options.exclude) || [], - recordDefRanges: false, - es6ExportFuncId: null, - es6ImportFuncId: null, - captureObj: assignToObj, - captureImports: true, - moduleExportFunc: { name: options && options.es6ExportFuncId || '_moduleExport', type: 'Identifier' }, - moduleImportFunc: { name: options && options.es6ImportFuncId || '_moduleImport', type: 'Identifier' }, - declarationWrapper: undefined, - classTransform: (parsed) => parsed, // no transform - // classToFunction: options && options.hasOwnProperty("classToFunction") ? - // options.classToFunction : { - // classHolder: assignToObj, - // functionNode: {type: "Identifier", name: "_createOrExtendClass"}, - // declarationWrapper: options && options.declarationWrapper, - // evalId: options && options.evalId, - // sourceAccessorName: options && options.sourceAccessorName - // }, - ...options - }; - - let rewritten = parsed; - - rewritten = removeJspmGlobalRef(rewritten, options); - - // "ignoreUndeclaredExcept" is null if we want to capture all globals in the toplevel scope - // if it is a list of names we will capture all refs with those names - if (options.ignoreUndeclaredExcept) { - const topLevel = topLevelDeclsAndRefs(parsed); - options.excludeRefs = arr.withoutAll(topLevel.undeclaredNames, options.ignoreUndeclaredExcept).concat(options.excludeRefs); - options.excludeDecls = arr.withoutAll(topLevel.undeclaredNames, options.ignoreUndeclaredExcept).concat(options.excludeDecls); - } - - options.excludeRefs = options.excludeRefs.concat(options.captureObj.name); - options.excludeDecls = options.excludeDecls.concat(options.captureObj.name); - - // 1. def ranges so that we know at which source code positions the - // definitions are - const defRanges = options.recordDefRanges ? computeDefRanges(rewritten, options) : null; - - // 2. find those var declarations that should not be rewritten. we - // currently ignore var declarations in for loops and the error parameter - // declaration in catch clauses. Also es6 import / export declaration need - // a special treatment - // DO NOT rewrite exports like "export { foo as bar }" => "export { _rec.foo as bar }" - // as this is not valid syntax. Instead we add a var declaration using the - // recorder as init for those exports later - options.excludeRefs = options.excludeRefs.concat(additionalIgnoredRefs(parsed, options)); - options.excludeDecls = options.excludeDecls.concat(additionalIgnoredDecls(parsed, options)); - - rewritten = fixDefaultAsyncFunctionExportForRegeneratorBug(rewritten, options); - - // 3. if the es6ExportFuncId options is defined we rewrite the es6 form into an - // obj assignment, converting es6 code to es5 using the extra - // options.moduleExportFunc and options.moduleImportFunc as capture / sources - if (options.es6ExportFuncId) { - options.excludeRefs.push(options.es6ExportFuncId); - options.excludeRefs.push(options.es6ImportFuncId); - rewritten = es6ModuleTransforms(rewritten, options); - } - - // 4. make all references declared in the toplevel scope into property - // reads of captureObj - // Example "var foo = 3; 99 + foo;" -> "var foo = 3; 99 + Global.foo;" - rewritten = replaceRefs(rewritten, options); - - // 5.a turn var declarations into assignments to captureObj - // Example: "var foo = 3; 99 + foo;" -> "Global.foo = 3; 99 + foo;" - // if declarationWrapper is requested: - // "var foo = 3;" -> "Global.foo = _define(3, 'foo', _rec, 'var');" - rewritten = replaceVarDecls(rewritten, options); - - // clear empty exports - // rms 26.05.20: removes statements of the sort "export {}" - // This is technically illegal ESM syntax, however - // this sometimes is served by jspm due to auto generated esm modules - // It's therefore worth tolerating this kind of syntax for convenience sake. - rewritten = clearEmptyExports(rewritten, options); - - // 5.b record class declarations - // Example: "class Foo {}" -> "class Foo {}; Global.Foo = Foo;" - // if declarationWrapper is requested: - // "class Foo {}" -> "Global.Foo = _define(class Foo {});" - rewritten = replaceClassDecls(rewritten, options); - - rewritten = splitExportDeclarations(rewritten, options); - - // 6. es6 export declaration are left untouched but a capturing assignment - // is added after the export so that we get the value: - // "export var x = 23;" => "export var x = 23; Global.x = x;" - rewritten = insertCapturesForExportDeclarations(rewritten, options); - - // 7. es6 import declaration are left untouched but a capturing assignment - // is added after the import so that we get the value: - // "import x from './some-es6-module.js';" => - // "import x from './some-es6-module.js';\n_rec.x = x;" - if (options.captureImports) rewritten = insertCapturesForImportDeclarations(rewritten, options); - - // 8. Since variable declarations like "var x = 23" were transformed to sth - // like "_rex.x = 23" exports can't simply reference vars anymore and - // "export { _rec.x }" is invalid syntax. So in front of those exports we add - // var decls manually - rewritten = insertDeclarationsForExports(rewritten, options); - - // 9. assignments for function declarations in the top level scope are - // put in front of everything else to mirror the func hoisting: - // "return bar(); function bar() { return 23 }" -> - // "Global.bar = bar; return bar(); function bar() { return 23 }" - // if declarationWrapper is requested: - // "Global.bar = _define(bar, 'bar', _rec, 'function'); function bar() {}" - rewritten = putFunctionDeclsInFront(rewritten, options); - - rewritten = transformImportMeta(rewritten, options); - - return rewritten; -} function removeJspmGlobalRef (parsed) { // do not replace until the @@ -166,11 +28,11 @@ function removeJspmGlobalRef (parsed) { // declaration has been detected let declarationFound = false; return ReplaceVisitor.run(parsed, (node) => { - if (!declarationFound && node.type == 'VariableDeclarator' && node.id.name == '_global') { - declarationFound = stringify(node) == '_global = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : global'; + if (!declarationFound && node.type === 'VariableDeclarator' && node.id.name === '_global') { + declarationFound = stringify(node) === '_global = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : global'; } - if (declarationFound && node.type == 'LogicalExpression' && - node.right.name == '_global') { + if (declarationFound && node.type === 'LogicalExpression' && + node.right.name === '_global') { return node.left; } return node; @@ -179,7 +41,7 @@ function removeJspmGlobalRef (parsed) { function transformImportMeta (parsed, options) { return ReplaceVisitor.run(parsed, (node) => { - if (node.type == 'MetaProperty' && node.meta.name == 'import') { + if (node.type === 'MetaProperty' && node.meta.name === 'import') { return options.classToFunction.currentModuleAccessor ? nodes.objectLiteral(['url', nodes.member(options.classToFunction.currentModuleAccessor, 'id')]) : parse('({url: eval("typeof _context !== \'undefined\' ? _context : {}").id})').body[0].expression; @@ -188,6 +50,44 @@ function transformImportMeta (parsed, options) { }); } +function declarationWrapperCall ( + declarationWrapperNode, + declNode, + varNameLiteral, + varKindLiteral, + valueNode, + recorder, + options +) { + if (declNode) { + // here we pass compile-time meta data into the runtime + const keyVals = []; + let addMeta = false; let start; let end; let evalId; let sourceAccessorName; + if (declNode['x-lively-object-meta']) { + ({ start, end, evalId, sourceAccessorName } = declNode['x-lively-object-meta']); + addMeta = true; + keyVals.push('start', nodes.literal(start), 'end', nodes.literal(end)); + } + if (evalId === undefined && options.hasOwnProperty('evalId')) { + evalId = options.evalId; + addMeta = true; + } + if (sourceAccessorName === undefined && options.hasOwnProperty('sourceAccessorName')) { + sourceAccessorName = options.sourceAccessorName; + addMeta = true; + } + if (evalId !== undefined) keyVals.push('evalId', nodes.literal(evalId)); + if (sourceAccessorName) keyVals.push('moduleSource', nodes.id(sourceAccessorName)); + if (addMeta) { + return funcCall( + declarationWrapperNode, varNameLiteral, varKindLiteral, valueNode, recorder, + nodes.objectLiteral(keyVals)/* meta node */); + } + } + + return funcCall(declarationWrapperNode, varNameLiteral, varKindLiteral, valueNode, recorder); +} + export function rewriteToRegisterModuleToCaptureSetters (parsed, assignToObj, options) { // for rewriting the setters part in code like // ```js @@ -246,7 +146,7 @@ export function rewriteToRegisterModuleToCaptureSetters (parsed, assignToObj, op let captureInitialize = execute.value.body.body.find(stmt => stmt.type === 'ExpressionStatement' && - stmt.expression.type == 'AssignmentExpression' && + stmt.expression.type === 'AssignmentExpression' && stmt.expression.left.name === options.captureObj.name); if (!captureInitialize) { captureInitialize = execute.value.body.body.find(stmt => @@ -262,7 +162,7 @@ export function rewriteToRegisterModuleToCaptureSetters (parsed, assignToObj, op if (options.sourceAccessorName) { let origSourceInitialize = execute.value.body.body.find(stmt => stmt.type === 'ExpressionStatement' && - stmt.expression.type == 'AssignmentExpression' && + stmt.expression.type === 'AssignmentExpression' && stmt.expression.left.name === options.sourceAccessorName); if (!origSourceInitialize) { origSourceInitialize = execute.value.body.body.find(stmt => @@ -282,7 +182,7 @@ export function rewriteToRegisterModuleToCaptureSetters (parsed, assignToObj, op // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // replacement helpers -function clearEmptyExports (parsed, options) { +function clearEmptyExports (parsed) { const topLevel = topLevelDeclsAndRefs(parsed); for (const exp of topLevel.scope.exportDecls) { if (!exp.declaration && exp.specifiers && !exp.specifiers.length) { arr.remove(parsed.body, exp); } @@ -290,13 +190,32 @@ function clearEmptyExports (parsed, options) { return parsed; } +function shouldDeclBeCaptured (decl, options) { + return options.excludeDecls.indexOf(decl.id.name) === -1 && + options.excludeDecls.indexOf(decl.id) === -1 && + (!options.includeDecls || options.includeDecls.indexOf(decl.id.name) > -1); +} + +function shouldRefBeCaptured (ref, toplevel, options) { + if (toplevel.scope.importSpecifiers.includes(ref)) return false; + for (let i = 0; i < toplevel.scope.exportDecls.length; i++) { + const ea = toplevel.scope.exportDecls[i]; + if (ea.declarations && ea.declarations.includes(ref)) return false; + if (ea.declaration === ref) return false; + } + if (options.excludeRefs.includes(ref.object?.name)) return false; + if (options.excludeRefs.includes(ref.name)) return false; + if (options.includeRefs && !options.includeRefs.includes(ref.name)) return false; + return true; +} + function replaceRefs (parsed, options) { const topLevel = topLevelDeclsAndRefs(parsed); const refsToReplace = topLevel.refs.filter(ref => shouldRefBeCaptured(ref, topLevel, options)); const locallyIgnored = []; let intermediateCounter = 0; - const replaced = ReplaceVisitor.run(parsed, (node, path) => { + const replaced = ReplaceVisitor.run(parsed, (node) => { // cs 2016/06/27, 1a4661 // ensure keys of shorthand properties are not renamed while capturing if (node.type === 'Property' && @@ -360,58 +279,265 @@ function replaceRefs (parsed, options) { } const key = prop.value || prop.key; return assign(key, member(member(options.captureObj, intermediate), prop.key)); - })); + }), member(options.captureObj, intermediate)); } return node; }); - return ReplaceVisitor.run(replaced, (node, path, parent) => + return ReplaceVisitor.run(replaced, (node) => refsToReplace.includes(node) && !locallyIgnored.includes(node) ? member(options.captureObj, node) : node); } -function replaceVarDecls (parsed, options) { - // rewrites var declarations so that they can be captured by - // `options.captureObj`. - // For normal vars we will do a transform like - // "var x = 23;" => "_rec.x = 23"; - // For patterns (destructuring assignments) we will create assignments for - // all properties that are being destructured, creating helper vars as needed - // "var {x: [y]} = foo" => "var _1 = foo; var _1$x = _1.x; __rec.y = _1$x[0];" - - const topLevel = topLevelDeclsAndRefs(parsed); - return ReplaceManyVisitor.run(parsed, node => { - if (!topLevel.varDecls.includes(node) || - node.declarations.every(decl => !shouldDeclBeCaptured(decl, options)) - ) return node; +// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +// naming +// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- - const replaced = []; - for (let i = 0; i < node.declarations.length; i++) { - const decl = node.declarations[i]; +function generateUniqueName (declaredNames, hint) { + let unique = hint; let n = 1; + while (declaredNames.indexOf(unique) > -1) { + if (n > 1000) throw new Error('Endless loop searching for unique variable ' + unique); + unique = unique.replace(/_[0-9]+$|$/, '_' + (++n)); + } + return unique; +} - if (!shouldDeclBeCaptured(decl, options)) { - replaced.push({ type: 'VariableDeclaration', kind: node.kind || 'var', declarations: [decl] }); - continue; - } +// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +// code generation helpers +// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- - const init = decl.init || { - operator: '||', - type: 'LogicalExpression', - left: { computed: false, object: options.captureObj, property: decl.id, type: 'MemberExpression' }, - right: { name: 'undefined', type: 'Identifier' } +function varDeclOrAssignment (parsed, declarator, kind) { + const topLevel = topLevelDeclsAndRefs(parsed); + const name = declarator.id.name; + return topLevel.declaredNames.indexOf(name) > -1 + // only create a new declaration if necessary + ? exprStmt(assign(declarator.id, declarator.init)) + : { + declarations: [declarator], + kind: kind || 'var', + type: 'VariableDeclaration' }; +} - const initWrapped = options.declarationWrapper && decl.id.name - ? declarationWrapperCall( - options.declarationWrapper, - decl, - literal(decl.id.name), - literal(node.kind), - init, options.captureObj, - options) - : init; +function assignExpr (assignee, propId, value, computed) { + return exprStmt( + assign( + member(assignee, propId, computed), + value || id('undefined'))); +} + +function importCall (imported, moduleSource, moduleImportFunc) { + if (typeof imported === 'string') imported = literal(imported); + return { + arguments: [moduleSource].concat(imported || []), + callee: moduleImportFunc, + type: 'CallExpression' + }; +} + +function varDeclAndImportCall (parsed, localId, imported, moduleSource, moduleImportFunc) { + // return varDeclOrAssignment(parsed, { + // type: "VariableDeclarator", + // id: localId, + // init: importCall(imported, moduleSource, moduleImportFunc) + // }); + return varDecl(localId, importCall(imported, moduleSource, moduleImportFunc)); +} + +function importCallStmt (imported, moduleSource, moduleImportFunc) { + return exprStmt(importCall(imported, moduleSource, moduleImportFunc)); +} + +function exportCall (exportFunc, local, exportedObj) { + if (typeof local === 'string') local = literal(local); + exportedObj = obj.deepCopy(exportedObj); + return funcCall(exportFunc, local, exportedObj); +} + +function exportFromImport (keyLeft, keyRight, moduleId, moduleExportFunc, moduleImportFunc) { + return exportCall(moduleExportFunc, keyLeft, importCall(keyRight, moduleId, moduleImportFunc)); +} + +function exportCallStmt (exportFunc, local, exportedObj) { + return exprStmt(exportCall(exportFunc, local, exportedObj)); +} + +// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +// capturing oobject patters / destructuring +// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + +let annotationSym = Symbol('lively.ast-destructuring-transform'); + +function transformArrayPattern (pattern, transformState) { + const declaredNames = transformState.declaredNames; + const p = annotationSym; + const transformed = []; + + for (let i = 0; i < pattern.elements.length; i++) { + const el = pattern.elements[i]; + + // like [a] + if (el.type === 'Identifier') { + let decl = varDecl(el, member(transformState.parent, id(i), true)); + decl[p] = { capture: true }; + transformed.push(decl); + + // like [...foo] + } else if (el.type === 'RestElement') { + let decl = varDecl(el.argument, { + type: 'CallExpression', + arguments: [{ type: 'Literal', value: i }], + callee: member(transformState.parent, id('slice'), false) + }); + decl[p] = { capture: true }; + transformed.push(decl); + } else if (el.type === 'AssignmentPattern') { + // like [x = 23] + let decl = varDecl( + el.left/* id */, + conditional( + binaryExpr(member(transformState.parent, id(i), true), '===', id('undefined')), + el.right, + member(transformState.parent, id(i), true))); + decl[p] = { capture: true }; + transformed.push(decl); + + // like [{x}] + } else { + const helperVarId = id(generateUniqueName(declaredNames, transformState.parent.name + '$' + i)); + const helperVar = varDecl(helperVarId, member(transformState.parent, i)); + // helperVar[p] = {capture: true}; + declaredNames.push(helperVarId.name); + transformed.push(helperVar); + transformed.push(...transformPattern(el, { parent: helperVarId, declaredNames })); // eslint-disable-line no-use-before-define + } + } + return transformed; +} + +function transformObjectPattern (pattern, transformState) { + const declaredNames = transformState.declaredNames; + const p = annotationSym; + const transformed = []; + + for (let i = 0; i < pattern.properties.length; i++) { + const prop = pattern.properties[i]; + + if (prop.type === 'RestElement') { + const knownKeys = pattern.properties.map(ea => ea.key && ea.key.name).filter(Boolean); + let decl = nodes.varDecl(prop.argument.name, nodes.objectLiteral([])); + const captureDecl = nodes.varDecl(prop.argument.name, id(prop.argument.name)); + const defCall = nodes.exprStmt(nodes.funcCall(nodes.funcExpr({}, [], + nodes.forIn('__key', transformState.parent, + nodes.block( + ...(knownKeys.length + ? knownKeys.map(knownKey => + nodes.ifStmt( + nodes.binaryExpr(nodes.id('__key'), '===', nodes.literal(knownKey)), + { type: 'ContinueStatement', label: null }, null)) + : []), + nodes.exprStmt( + nodes.assign( + nodes.member(prop.argument.name, nodes.id('__key'), true), + nodes.member(transformState.parent, nodes.id('__key'), true))) + ))))); + + captureDecl[p] = { capture: true }; + transformed.push(decl, captureDecl, defCall); + } else if (prop.value.type === 'Identifier') { + // like {x: y} + let decl = varDecl(prop.value, member(transformState.parent, prop.key)); + decl[p] = { capture: true }; + transformed.push(decl); + } else if (prop.value.type === 'AssignmentPattern') { + // like {x = 23} + let decl = varDecl( + prop.value.left/* id */, + conditional( + binaryExpr(member(transformState.parent, prop.key), '===', id('undefined')), + prop.value.right, + member(transformState.parent, prop.key))); + decl[p] = { capture: true }; + transformed.push(decl); + } else { + // like {x: {z}} or {x: [a]} + const helperVarId = id(generateUniqueName( + declaredNames, + transformState.parent.name + '$' + prop.key.name)); + const helperVar = varDecl(helperVarId, member(transformState.parent, prop.key)); + helperVar[p] = { capture: false }; + declaredNames.push(helperVarId.name); + transformed.push( + ...[helperVar].concat( + transformPattern(prop.value, { parent: helperVarId, declaredNames: declaredNames }))); // eslint-disable-line no-use-before-define + } + } + + return transformed; +} + +function transformPattern (pattern, transformState) { + // For transforming destructuring expressions into plain vars and member access. + // Takes a var or argument pattern node (of type ArrayPattern or + // ObjectPattern) and transforms it into a set of var declarations that will + // "pull out" the nested properties + // Example: + // var parsed = parse("var [{b: {c: [a]}}] = foo;"); + // var state = {parent: {type: "Identifier", name: "arg"}, declaredNames: ["foo"]} + // transformPattern(parsed.body[0].declarations[0].id, state).map(stringify).join("\n"); + // // => "var arg$0 = arg[0];\n" + // // + "var arg$0$b = arg$0.b;\n" + // // + "var arg$0$b$c = arg$0$b.c;\n" + // // + "var a = arg$0$b$c[0];" + return pattern.type === 'ArrayPattern' + ? transformArrayPattern(pattern, transformState) + : pattern.type === 'ObjectPattern' + ? transformObjectPattern(pattern, transformState) + : []; +} + +function replaceVarDecls (parsed, options) { + // rewrites var declarations so that they can be captured by + // `options.captureObj`. + // For normal vars we will do a transform like + // "var x = 23;" => "_rec.x = 23"; + // For patterns (destructuring assignments) we will create assignments for + // all properties that are being destructured, creating helper vars as needed + // "var {x: [y]} = foo" => "var _1 = foo; var _1$x = _1.x; __rec.y = _1$x[0];" + + const topLevel = topLevelDeclsAndRefs(parsed); + return ReplaceManyVisitor.run(parsed, node => { + if (!topLevel.varDecls.includes(node) || + node.declarations.every(decl => !shouldDeclBeCaptured(decl, options)) + ) return node; + + const replaced = []; + for (let i = 0; i < node.declarations.length; i++) { + const decl = node.declarations[i]; + + if (!shouldDeclBeCaptured(decl, options)) { + replaced.push({ type: 'VariableDeclaration', kind: node.kind || 'var', declarations: [decl] }); + continue; + } + + const init = decl.init || { + operator: '||', + type: 'LogicalExpression', + left: { computed: false, object: options.captureObj, property: decl.id, type: 'MemberExpression' }, + right: { name: 'undefined', type: 'Identifier' } + }; + + const initWrapped = options.declarationWrapper && decl.id.name + ? declarationWrapperCall( + options.declarationWrapper, + decl, + literal(decl.id.name), + literal(node.kind), + init, options.captureObj, + options) + : init; // Here we create the object pattern / destructuring replacements if (decl.id.type.includes('Pattern')) { @@ -449,24 +575,11 @@ function replaceVarDecls (parsed, options) { }); } -// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -// naming -// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- - -function generateUniqueName (declaredNames, hint) { - let unique = hint; let n = 1; - while (declaredNames.indexOf(unique) > -1) { - if (n > 1000) throw new Error('Endless loop searching for unique variable ' + unique); - unique = unique.replace(/_[0-9]+$|$/, '_' + (++n)); - } - return unique; -} - // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // exclude / include helpers // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -function additionalIgnoredDecls (parsed, options) { +function additionalIgnoredDecls (parsed) { const topLevel = topLevelDeclsAndRefs(parsed); const ignoreDecls = []; for (let i = 0; i < topLevel.scope.varDecls.length; i++) { const decl = topLevel.scope.varDecls[i]; @@ -510,25 +623,6 @@ function additionalIgnoredRefs (parsed, options) { .map(ea => ea.name)); } -function shouldDeclBeCaptured (decl, options) { - return options.excludeDecls.indexOf(decl.id.name) === -1 && - options.excludeDecls.indexOf(decl.id) === -1 && - (!options.includeDecls || options.includeDecls.indexOf(decl.id.name) > -1); -} - -function shouldRefBeCaptured (ref, toplevel, options) { - if (toplevel.scope.importSpecifiers.includes(ref)) return false; - for (let i = 0; i < toplevel.scope.exportDecls.length; i++) { - const ea = toplevel.scope.exportDecls[i]; - if (ea.declarations && ea.declarations.includes(ref)) return false; - if (ea.declaration === ref) return false; - } - if (options.excludeRefs.includes(ref.object?.name)) return false; - if (options.excludeRefs.includes(ref.name)) return false; - if (options.includeRefs && !options.includeRefs.includes(ref.name)) return false; - return true; -} - // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // capturing specific code // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- @@ -548,7 +642,7 @@ function replaceClassDecls (parsed, options) { return parsed; } -function splitExportDeclarations (parsed, options) { +function splitExportDeclarations (parsed) { const stmts = parsed.body; const newNodes = parsed.body = []; for (let i = 0; i < stmts.length; i++) { const stmt = stmts[i]; @@ -605,7 +699,8 @@ export function insertCapturesForExportedImports (parsed, options) { nodes = nodes.concat(parse( sourceImport + decls.map(([exp, imp]) => { - return `${recorder}.${exp} = ${imp};\n` + (imp !== exp ? `${recorder}.${imp} = ${imp};\n` : ''); + if (exp === 'default') return `${recorder}.${exp} = ${imp};\n` + (imp !== exp ? `${recorder}.${imp} = ${imp};\n` : ''); + return `${recorder}.${imp} = ${imp};\n`; }).join('\n'))); } if (stmt.type === 'ExportAllDeclaration') { @@ -637,7 +732,6 @@ function insertCapturesForExportDeclarations (parsed, options) { // default export of an unnamed primitive value, i.e. // "export default "foo"", "export default 27;" const decl = stmt.declaration; - const assignVal = decl.raw; const refId = generateUniqueName(topLevelDeclsAndRefs(parsed).declaredNames, '$' + decl.raw.split('"').join('')); stmt.declaration = id(refId); arr.pushAt(body, assignExpr(options.captureObj, refId, decl.raw, false), body.indexOf(stmt)); @@ -736,7 +830,7 @@ function insertDeclarationsForExports (parsed, options) { return parsed; } -function fixDefaultAsyncFunctionExportForRegeneratorBug (parsed, options) { +function fixDefaultAsyncFunctionExportForRegeneratorBug (parsed) { // rk 2016-06-02: see https://github.com/LivelyKernel/lively.modules/issues/9 // FIXME this needs to be removed as soon as the cause for the issue is fixed const body = []; @@ -756,11 +850,12 @@ function fixDefaultAsyncFunctionExportForRegeneratorBug (parsed, options) { } function es6ModuleTransforms (parsed, options) { + let moduleId; parsed.body = parsed.body.reduce((stmts, stmt) => { let nodes; if (stmt.type === 'ExportNamedDeclaration') { if (stmt.source) { - var key = moduleId = stmt.source; + moduleId = stmt.source; nodes = stmt.specifiers.map(specifier => ({ type: 'ExpressionStatement', expression: exportFromImport( @@ -785,10 +880,10 @@ function es6ModuleTransforms (parsed, options) { null, literal(decl.id.name), literal(stmt.declaration.kind), - decl, options.captureObj, + decl.init, options.captureObj, options) : decl.init, - false), + false).expression, stmt.declaration.kind); }) .concat(decls.map(decl => exportCallStmt(options.moduleExportFunc, decl.id.name, decl.id))); @@ -807,7 +902,7 @@ function es6ModuleTransforms (parsed, options) { nodes = [exportCallStmt(options.moduleExportFunc, 'default', stmt.declaration)]; } } else if (stmt.type === 'ExportAllDeclaration') { - var key = { name: options.es6ExportFuncId + '__iterator__', type: 'Identifier' }; var moduleId = stmt.source; + const key = { name: options.es6ExportFuncId + '__iterator__', type: 'Identifier' }; moduleId = stmt.source; nodes = [ { type: 'ForInStatement', @@ -887,246 +982,137 @@ function putFunctionDeclsInFront (parsed, options) { return parsed; } -function computeDefRanges (parsed, options) { - const topLevel = topLevelDeclsAndRefs(parsed); - return chain(topLevel.scope.varDecls) - .pluck('declarations').flat().value() - .concat(topLevel.scope.funcDecls.filter(ea => ea.id)) - .reduce((defs, decl) => { - if (!defs[decl.id.name]) defs[decl.id.name] = []; - defs[decl.id.name].push({ type: decl.type, start: decl.start, end: decl.end }); - return defs; - }, {}); -} - -// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -// capturing oobject patters / destructuring -// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +export function rewriteToCaptureTopLevelVariables (parsed, assignToObj, options) { + /* replaces var and function declarations with assignment statements. + * Example: + stringify( + rewriteToCaptureTopLevelVariables( + parse("var x = 3, y = 2, z = 4"), + {name: "A", type: "Identifier"}, + {exclude: ['z']})); + // => "A.x = 3; A.y = 2; z = 4" + */ -var annotationSym = Symbol('lively.ast-destructuring-transform'); + if (!assignToObj) assignToObj = { type: 'Identifier', name: '__rec' }; -function transformPattern (pattern, transformState) { - // For transforming destructuring expressions into plain vars and member access. - // Takes a var or argument pattern node (of type ArrayPattern or - // ObjectPattern) and transforms it into a set of var declarations that will - // "pull out" the nested properties - // Example: - // var parsed = parse("var [{b: {c: [a]}}] = foo;"); - // var state = {parent: {type: "Identifier", name: "arg"}, declaredNames: ["foo"]} - // transformPattern(parsed.body[0].declarations[0].id, state).map(stringify).join("\n"); - // // => "var arg$0 = arg[0];\n" - // // + "var arg$0$b = arg$0.b;\n" - // // + "var arg$0$b$c = arg$0$b.c;\n" - // // + "var a = arg$0$b$c[0];" - return pattern.type === 'ArrayPattern' - ? transformArrayPattern(pattern, transformState) - : pattern.type === 'ObjectPattern' - ? transformObjectPattern(pattern, transformState) - : []; -} - -function transformArrayPattern (pattern, transformState) { - const declaredNames = transformState.declaredNames; - const p = annotationSym; - const transformed = []; - - for (let i = 0; i < pattern.elements.length; i++) { - const el = pattern.elements[i]; + options = { + ignoreUndeclaredExcept: null, + includeRefs: null, + excludeRefs: (options && options.exclude) || [], + includeDecls: null, + excludeDecls: (options && options.exclude) || [], + recordDefRanges: false, + es6ExportFuncId: null, + es6ImportFuncId: null, + captureObj: assignToObj, + captureImports: true, + moduleExportFunc: { name: options && options.es6ExportFuncId || '_moduleExport', type: 'Identifier' }, + moduleImportFunc: { name: options && options.es6ImportFuncId || '_moduleImport', type: 'Identifier' }, + declarationWrapper: undefined, + classTransform: (parsed) => parsed, // no transform + // classToFunction: options && options.hasOwnProperty("classToFunction") ? + // options.classToFunction : { + // classHolder: assignToObj, + // functionNode: {type: "Identifier", name: "_createOrExtendClass"}, + // declarationWrapper: options && options.declarationWrapper, + // evalId: options && options.evalId, + // sourceAccessorName: options && options.sourceAccessorName + // }, + ...options + }; - // like [a] - if (el.type === 'Identifier') { - var decl = varDecl(el, member(transformState.parent, id(i), true)); - decl[p] = { capture: true }; - transformed.push(decl); + let rewritten = parsed; - // like [...foo] - } else if (el.type === 'RestElement') { - var decl = varDecl(el.argument, { - type: 'CallExpression', - arguments: [{ type: 'Literal', value: i }], - callee: member(transformState.parent, id('slice'), false) - }); - decl[p] = { capture: true }; - transformed.push(decl); - } else if (el.type == 'AssignmentPattern') { - // like [x = 23] - var decl = varDecl( - el.left/* id */, - conditional( - binaryExpr(member(transformState.parent, id(i), true), '===', id('undefined')), - el.right, - member(transformState.parent, id(i), true))); - decl[p] = { capture: true }; - transformed.push(decl); + rewritten = removeJspmGlobalRef(rewritten, options); - // like [{x}] - } else { - const helperVarId = id(generateUniqueName(declaredNames, transformState.parent.name + '$' + i)); - const helperVar = varDecl(helperVarId, member(transformState.parent, i)); - // helperVar[p] = {capture: true}; - declaredNames.push(helperVarId.name); - transformed.push(helperVar); - transformed.push(...transformPattern(el, { parent: helperVarId, declaredNames })); - } + // "ignoreUndeclaredExcept" is null if we want to capture all globals in the toplevel scope + // if it is a list of names we will capture all refs with those names + if (options.ignoreUndeclaredExcept) { + const topLevel = topLevelDeclsAndRefs(parsed); + options.excludeRefs = arr.withoutAll(topLevel.undeclaredNames, options.ignoreUndeclaredExcept).concat(options.excludeRefs); + options.excludeDecls = arr.withoutAll(topLevel.undeclaredNames, options.ignoreUndeclaredExcept).concat(options.excludeDecls); } - return transformed; -} -function transformObjectPattern (pattern, transformState) { - const declaredNames = transformState.declaredNames; - const p = annotationSym; - const transformed = []; + options.excludeRefs = options.excludeRefs.concat(options.captureObj.name); + options.excludeDecls = options.excludeDecls.concat(options.captureObj.name); - for (let i = 0; i < pattern.properties.length; i++) { - const prop = pattern.properties[i]; + // 1. def ranges so that we know at which source code positions the + // definitions are + // const defRanges = options.recordDefRanges ? computeDefRanges(rewritten, options) : null; - if (prop.type == 'RestElement') { - const knownKeys = pattern.properties.map(ea => ea.key && ea.key.name).filter(Boolean); - var decl = nodes.varDecl(prop.argument.name, nodes.objectLiteral([])); - const captureDecl = nodes.varDecl(prop.argument.name, id(prop.argument.name)); - const defCall = nodes.exprStmt(nodes.funcCall(nodes.funcExpr({}, [], - nodes.forIn('__key', transformState.parent, - nodes.block( - ...(knownKeys.length - ? knownKeys.map(knownKey => - nodes.ifStmt( - nodes.binaryExpr(nodes.id('__key'), '===', nodes.literal(knownKey)), - { type: 'ContinueStatement', label: null }, null)) - : []), - nodes.exprStmt( - nodes.assign( - nodes.member(prop.argument.name, nodes.id('__key'), true), - nodes.member(transformState.parent, nodes.id('__key'), true))) - ))))); + // 2. find those var declarations that should not be rewritten. we + // currently ignore var declarations in for loops and the error parameter + // declaration in catch clauses. Also es6 import / export declaration need + // a special treatment + // DO NOT rewrite exports like "export { foo as bar }" => "export { _rec.foo as bar }" + // as this is not valid syntax. Instead we add a var declaration using the + // recorder as init for those exports later + options.excludeRefs = options.excludeRefs.concat(additionalIgnoredRefs(parsed, options)); + options.excludeDecls = options.excludeDecls.concat(additionalIgnoredDecls(parsed, options)); - captureDecl[p] = { capture: true }; - transformed.push(decl, captureDecl, defCall); - } else if (prop.value.type == 'Identifier') { - // like {x: y} - var decl = varDecl(prop.value, member(transformState.parent, prop.key)); - decl[p] = { capture: true }; - transformed.push(decl); - } else if (prop.value.type == 'AssignmentPattern') { - // like {x = 23} - var decl = varDecl( - prop.value.left/* id */, - conditional( - binaryExpr(member(transformState.parent, prop.key), '===', id('undefined')), - prop.value.right, - member(transformState.parent, prop.key))); - decl[p] = { capture: true }; - transformed.push(decl); - } else { - // like {x: {z}} or {x: [a]} - const helperVarId = id(generateUniqueName( - declaredNames, - transformState.parent.name + '$' + prop.key.name)); - const helperVar = varDecl(helperVarId, member(transformState.parent, prop.key)); - helperVar[p] = { capture: false }; - declaredNames.push(helperVarId.name); - transformed.push( - ...[helperVar].concat( - transformPattern(prop.value, { parent: helperVarId, declaredNames: declaredNames }))); - } - } + rewritten = fixDefaultAsyncFunctionExportForRegeneratorBug(rewritten, options); - return transformed; -} + // 3. if the es6ExportFuncId options is defined we rewrite the es6 form into an + // obj assignment, converting es6 code to es5 using the extra + // options.moduleExportFunc and options.moduleImportFunc as capture / sources + if (options.es6ExportFuncId) { + options.excludeRefs.push(options.es6ExportFuncId); + options.excludeRefs.push(options.es6ImportFuncId); + rewritten = es6ModuleTransforms(rewritten, options); + } -// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -// code generation helpers -// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + // 4. make all references declared in the toplevel scope into property + // reads of captureObj + // Example "var foo = 3; 99 + foo;" -> "var foo = 3; 99 + Global.foo;" + rewritten = replaceRefs(rewritten, options); -function varDeclOrAssignment (parsed, declarator, kind) { - const topLevel = topLevelDeclsAndRefs(parsed); - const name = declarator.id.name; - return topLevel.declaredNames.indexOf(name) > -1 - // only create a new declaration if necessary - ? exprStmt(assign(declarator.id, declarator.init)) - : { - declarations: [declarator], - kind: kind || 'var', - type: 'VariableDeclaration' - }; -} + // 5.a turn var declarations into assignments to captureObj + // Example: "var foo = 3; 99 + foo;" -> "Global.foo = 3; 99 + foo;" + // if declarationWrapper is requested: + // "var foo = 3;" -> "Global.foo = _define(3, 'foo', _rec, 'var');" + rewritten = replaceVarDecls(rewritten, options); -function assignExpr (assignee, propId, value, computed) { - return exprStmt( - assign( - member(assignee, propId, computed), - value || id('undefined'))); -} + // clear empty exports + // rms 26.05.20: removes statements of the sort "export {}" + // This is technically illegal ESM syntax, however + // this sometimes is served by jspm due to auto generated esm modules + // It's therefore worth tolerating this kind of syntax for convenience sake. + rewritten = clearEmptyExports(rewritten, options); -function exportFromImport (keyLeft, keyRight, moduleId, moduleExportFunc, moduleImportFunc) { - return exportCall(moduleExportFunc, keyLeft, importCall(keyRight, moduleId, moduleImportFunc)); -} + // 5.b record class declarations + // Example: "class Foo {}" -> "class Foo {}; Global.Foo = Foo;" + // if declarationWrapper is requested: + // "class Foo {}" -> "Global.Foo = _define(class Foo {});" + rewritten = replaceClassDecls(rewritten, options); -function varDeclAndImportCall (parsed, localId, imported, moduleSource, moduleImportFunc) { - // return varDeclOrAssignment(parsed, { - // type: "VariableDeclarator", - // id: localId, - // init: importCall(imported, moduleSource, moduleImportFunc) - // }); - return varDecl(localId, importCall(imported, moduleSource, moduleImportFunc)); -} + rewritten = splitExportDeclarations(rewritten, options); -function importCall (imported, moduleSource, moduleImportFunc) { - if (typeof imported === 'string') imported = literal(imported); - return { - arguments: [moduleSource].concat(imported || []), - callee: moduleImportFunc, - type: 'CallExpression' - }; -} + // 6. es6 export declaration are left untouched but a capturing assignment + // is added after the export so that we get the value: + // "export var x = 23;" => "export var x = 23; Global.x = x;" + rewritten = insertCapturesForExportDeclarations(rewritten, options); -function importCallStmt (imported, moduleSource, moduleImportFunc) { - return exprStmt(importCall(imported, moduleSource, moduleImportFunc)); -} + // 7. es6 import declaration are left untouched but a capturing assignment + // is added after the import so that we get the value: + // "import x from './some-es6-module.js';" => + // "import x from './some-es6-module.js';\n_rec.x = x;" + if (options.captureImports) rewritten = insertCapturesForImportDeclarations(rewritten, options); -function exportCall (exportFunc, local, exportedObj) { - if (typeof local === 'string') local = literal(local); - exportedObj = obj.deepCopy(exportedObj); - return funcCall(exportFunc, local, exportedObj); -} + // 8. Since variable declarations like "var x = 23" were transformed to sth + // like "_rex.x = 23" exports can't simply reference vars anymore and + // "export { _rec.x }" is invalid syntax. So in front of those exports we add + // var decls manually + rewritten = insertDeclarationsForExports(rewritten, options); -function exportCallStmt (exportFunc, local, exportedObj) { - return exprStmt(exportCall(exportFunc, local, exportedObj)); -} + // 9. assignments for function declarations in the top level scope are + // put in front of everything else to mirror the func hoisting: + // "return bar(); function bar() { return 23 }" -> + // "Global.bar = bar; return bar(); function bar() { return 23 }" + // if declarationWrapper is requested: + // "Global.bar = _define(bar, 'bar', _rec, 'function'); function bar() {}" + rewritten = putFunctionDeclsInFront(rewritten, options); -function declarationWrapperCall ( - declarationWrapperNode, - declNode, - varNameLiteral, - varKindLiteral, - valueNode, - recorder, - options -) { - if (declNode) { - // here we pass compile-time meta data into the runtime - const keyVals = []; - let addMeta = false; - if (declNode['x-lively-object-meta']) { - var { start, end, evalId, sourceAccessorName } = declNode['x-lively-object-meta']; - addMeta = true; - keyVals.push('start', nodes.literal(start), 'end', nodes.literal(end)); - } - if (evalId === undefined && options.hasOwnProperty('evalId')) { - evalId = options.evalId; - addMeta = true; - } - if (sourceAccessorName === undefined && options.hasOwnProperty('sourceAccessorName')) { - sourceAccessorName = options.sourceAccessorName; - addMeta = true; - } - if (evalId !== undefined) keyVals.push('evalId', nodes.literal(evalId)); - if (sourceAccessorName) keyVals.push('moduleSource', nodes.id(sourceAccessorName)); - if (addMeta) { - return funcCall( - declarationWrapperNode, varNameLiteral, varKindLiteral, valueNode, recorder, - nodes.objectLiteral(keyVals)/* meta node */); - } - } + rewritten = transformImportMeta(rewritten, options); - return funcCall(declarationWrapperNode, varNameLiteral, varKindLiteral, valueNode, recorder); + return rewritten; } diff --git a/lively.source-transform/index.js b/lively.source-transform/index.js index 3f87a88d7a..cb885b5a0a 100644 --- a/lively.source-transform/index.js +++ b/lively.source-transform/index.js @@ -6,7 +6,7 @@ import importMeta from '@babel/plugin-syntax-import-meta'; import * as capturing from './capturing.js'; import { topLevelDeclsAndRefs, queryNodes } from 'lively.ast/lib/query.js'; -import { arr, string } from 'lively.lang'; +import { arr } from 'lively.lang'; export { capturing }; // fixme: this is a sort of bad placement diff --git a/lively.source-transform/package.json b/lively.source-transform/package.json index 59fee535f4..9e15101ecf 100644 --- a/lively.source-transform/package.json +++ b/lively.source-transform/package.json @@ -28,7 +28,10 @@ "lively.lang": "https://github.com/LivelyKernel/lively.lang", "lively.classes": "https://github.com/LivelyKernel/lively.classes", "@babel/plugin-proposal-optional-catch-binding": "7.16.7", - "@babel/plugin-syntax-import-meta": "7.10.4" + "@babel/plugin-syntax-import-meta": "7.10.4", + "@babel/plugin-proposal-dynamic-import": "7.18.6", + "@babel/types": "7.26.0", + "@babel/core": "7.26.0" }, "devDependencies": { "lively.vm": "*", @@ -43,6 +46,66 @@ }, "systemjs": { "main": "index.js", + "importMap": { + "imports": { + "@babel/core": "esm://ga.jspm.io/npm:@babel/core@7.26.0/lib/dev.index.js", + "@babel/plugin-proposal-dynamic-import": "esm://ga.jspm.io/npm:@babel/plugin-proposal-dynamic-import@7.18.6/lib/index.js", + "@babel/plugin-transform-modules-systemjs": "esm://ga.jspm.io/npm:@babel/plugin-transform-modules-systemjs@7.25.9/lib/index.js", + "@babel/types": "esm://ga.jspm.io/npm:@babel/types@7.26.0/lib/index.js" + }, + "scopes": { + "esm://ga.jspm.io/": { + "#lib/config/files/index.js": "esm://ga.jspm.io/npm:@babel/core@7.26.0/lib/config/files/index-browser.js", + "#lib/config/resolve-targets.js": "esm://ga.jspm.io/npm:@babel/core@7.26.0/lib/config/resolve-targets-browser.js", + "#lib/transform-file.js": "esm://ga.jspm.io/npm:@babel/core@7.26.0/lib/transform-file-browser.js", + "#node.js": "esm://ga.jspm.io/npm:browserslist@4.24.2/browser.js", + "@ampproject/remapping": "esm://ga.jspm.io/npm:@ampproject/remapping@2.3.0/dist/remapping.umd.js", + "@babel/code-frame": "esm://ga.jspm.io/npm:@babel/code-frame@7.26.2/lib/index.js", + "@babel/compat-data/native-modules": "esm://ga.jspm.io/npm:@babel/compat-data@7.26.3/native-modules.js", + "@babel/compat-data/plugins": "esm://ga.jspm.io/npm:@babel/compat-data@7.26.3/plugins.js", + "@babel/generator": "esm://ga.jspm.io/npm:@babel/generator@7.26.3/lib/index.js", + "@babel/helper-compilation-targets": "esm://ga.jspm.io/npm:@babel/helper-compilation-targets@7.25.9/lib/index.js", + "@babel/helper-module-imports": "esm://ga.jspm.io/npm:@babel/helper-module-imports@7.25.9/lib/index.js", + "@babel/helper-module-transforms": "esm://ga.jspm.io/npm:@babel/helper-module-transforms@7.26.0/lib/index.js", + "@babel/helper-plugin-utils": "esm://ga.jspm.io/npm:@babel/helper-plugin-utils@7.25.9/lib/index.js", + "@babel/helper-string-parser": "esm://ga.jspm.io/npm:@babel/helper-string-parser@7.25.9/lib/index.js", + "@babel/helper-validator-identifier": "esm://ga.jspm.io/npm:@babel/helper-validator-identifier@7.25.9/lib/index.js", + "@babel/helper-validator-option": "esm://ga.jspm.io/npm:@babel/helper-validator-option@7.25.9/lib/index.js", + "@babel/plugin-syntax-dynamic-import": "esm://ga.jspm.io/npm:@babel/plugin-syntax-dynamic-import@7.8.3/lib/index.js", + "@babel/helpers": "esm://ga.jspm.io/npm:@babel/helpers@7.26.0/lib/index.js", + "@babel/parser": "esm://ga.jspm.io/npm:@babel/parser@7.26.3/lib/index.js", + "@babel/template": "esm://ga.jspm.io/npm:@babel/template@7.25.9/lib/index.js", + "@babel/traverse": "esm://ga.jspm.io/npm:@babel/traverse@7.26.4/lib/index.js", + "@babel/types": "esm://ga.jspm.io/npm:@babel/types@7.26.3/lib/index.js", + "@jridgewell/gen-mapping": "esm://ga.jspm.io/npm:@jridgewell/gen-mapping@0.3.5/dist/gen-mapping.umd.js", + "@jridgewell/resolve-uri": "esm://ga.jspm.io/npm:@jridgewell/resolve-uri@3.1.2/dist/resolve-uri.umd.js", + "@jridgewell/set-array": "esm://ga.jspm.io/npm:@jridgewell/set-array@1.2.1/dist/set-array.umd.js", + "@jridgewell/sourcemap-codec": "esm://ga.jspm.io/npm:@jridgewell/sourcemap-codec@1.5.0/dist/sourcemap-codec.umd.js", + "@jridgewell/trace-mapping": "esm://ga.jspm.io/npm:@jridgewell/trace-mapping@0.3.25/dist/trace-mapping.umd.js", + "assert": "esm://ga.jspm.io/npm:@jspm/core@2.1.0/nodelibs/browser/assert.js", + "browserslist": "esm://ga.jspm.io/npm:browserslist@4.24.2/index.js", + "buffer": "esm://ga.jspm.io/npm:@jspm/core@2.1.0/nodelibs/browser/buffer.js", + "caniuse-lite/dist/unpacker/agents": "esm://ga.jspm.io/npm:caniuse-lite@1.0.30001687/dist/unpacker/agents.js", + "convert-source-map": "esm://ga.jspm.io/npm:convert-source-map@2.0.0/index.js", + "debug": "esm://ga.jspm.io/npm:debug@4.3.7/src/browser.js", + "electron-to-chromium/versions": "esm://ga.jspm.io/npm:electron-to-chromium@1.5.71/versions.js", + "fs": "esm://ga.jspm.io/npm:@jspm/core@2.1.0/nodelibs/browser/fs.js", + "gensync": "esm://ga.jspm.io/npm:gensync@1.0.0-beta.2/index.js", + "globals": "esm://ga.jspm.io/npm:globals@11.12.0/index.js", + "js-tokens": "esm://ga.jspm.io/npm:js-tokens@4.0.0/index.js", + "jsesc": "esm://ga.jspm.io/npm:jsesc@3.0.2/jsesc.js", + "lru-cache": "esm://ga.jspm.io/npm:lru-cache@5.1.1/index.js", + "ms": "esm://ga.jspm.io/npm:ms@2.1.3/index.js", + "node-releases/data/processed/envs.json": "esm://ga.jspm.io/npm:node-releases@2.0.18/data/processed/envs.json.js", + "node-releases/data/release-schedule/release-schedule.json": "esm://ga.jspm.io/npm:node-releases@2.0.18/data/release-schedule/release-schedule.json.js", + "path": "esm://ga.jspm.io/npm:@jspm/core@2.1.0/nodelibs/browser/path.js", + "picocolors": "esm://ga.jspm.io/npm:picocolors@1.1.1/picocolors.browser.js", + "process": "esm://ga.jspm.io/npm:@jspm/core@2.1.0/nodelibs/browser/process.js", + "semver": "esm://ga.jspm.io/npm:semver@6.3.1/semver.js", + "yallist": "esm://ga.jspm.io/npm:yallist@3.1.1/yallist.js" + } + } + }, "map": { "@babel/plugin-proposal-optional-catch-binding": { "~node": "esm://cache/@babel/plugin-proposal-optional-catch-binding", @@ -54,4 +117,4 @@ } } } -} \ No newline at end of file +} diff --git a/lively.source-transform/tests/babel-test.js b/lively.source-transform/tests/babel-test.js new file mode 100644 index 0000000000..2d2e6fdab8 --- /dev/null +++ b/lively.source-transform/tests/babel-test.js @@ -0,0 +1,909 @@ +/* global describe, it */ +import { expect } from 'mocha-es6'; +import babel from '@babel/core'; +import t from '@babel/types'; +import { string, fun } from 'lively.lang'; +import { parse, query, transform, nodes, stringify } from 'lively.ast'; +import { rewriteToCaptureTopLevelVariables, rewriteToRegisterModuleToCaptureSetters } from '../capturing.js'; +import { classToFunctionTransform } from 'lively.classes'; +import { defaultClassToFunctionConverterName } from 'lively.vm'; +import { objectSpreadTransform } from 'lively.source-transform'; +import lint from 'lively.ide/js/linter.js'; +import { livelyPreTranspile, livelyPostTranspile } from '../babel/plugin.js'; +import { classToFunctionTransformBabel } from 'lively.classes/class-to-function-transform.js'; + +function _testVarTfm (descr, options, code, expected, only) { + // options = 'var y, z = foo + bar; baz.foo(z, 3)'; + // code = '_rec.y = _rec.y || undefined;\n_rec.z = _rec.foo + _rec.bar;\n_rec.baz.foo(_rec.z, 3);' + if (typeof options === 'string') { + only = expected; + expected = code; + code = options; + options = { + recordGlobals: true, + captureObj: t.Identifier('_rec'), + varRecorderName: '_rec', + topLevelVarRecorder: t.Identifier('_rec'), + topLevelVarRecorderName: '_rec', + plugin: livelyPreTranspile, + classToFunction: { + classHolder: t.Identifier('_rec'), + functionNode: t.Identifier('_createOrExtendClass') + } + }; + } else { + options = { + recordGlobals: true, + captureObj: t.Identifier('_rec'), + varRecorderName: '_rec', + topLevelVarRecorder: t.Identifier('_rec'), + topLevelVarRecorderName: '_rec', + classToFunction: { + classHolder: t.Identifier('_rec'), + functionNode: t.Identifier('_createOrExtendClass') + }, + plugin: livelyPreTranspile, + ...options + }; + } + return (only ? it.only : it)(descr, () => { + let { code: result } = babel.transform(code, { + plugins: [[options.plugin, options]] + }); + expect(stringify(parse(result))).equals(stringify(parse(expected))); + }); +} + +function ignoreFormatCompare (result, expected) { + return expect(stringify(parse(result))).equals(stringify(parse(expected))); +} + +function testVarTfm (descr, options, code, expected) { return _testVarTfm(descr, options, code, expected, false); } +function only_testVarTfm (descr, options, code, expected) { return _testVarTfm(descr, options, code, expected, true); } + +function classTemplate (className, superClassName, methodString, classMethodString, classHolder, moduleMeta, useClassHolder = true, start, end, evalId) { + if (methodString.includes('\n')) methodString = string.indent(methodString, ' ', 2).replace(/^\s+/, ''); + if (classMethodString.includes('\n')) classMethodString = string.indent(classMethodString, ' ', 2).replace(/^\s+/, ''); + + if (!className) useClassHolder = false; + + let classFunctionHeader = className ? `function ${className}` : 'function '; + if (useClassHolder) { classFunctionHeader = `__lively_classholder__.hasOwnProperty("${className}") && typeof __lively_classholder__.${className} === "function" ? __lively_classholder__.${className} : __lively_classholder__.${className} = ${classFunctionHeader}`; } + + let pos = ''; + if (start !== undefined && end !== undefined) { + pos = `, { + start: ${start}, + end: ${end}${evalId ? `,\n evalId: ${evalId}` : ''} + }`; + } + return `${useClassHolder ? 'function(superclass)' : '(superclass =>'} { + var __lively_classholder__ = ${classHolder}; + var ${useClassHolder ? '__lively_class__' : 'Foo'} = ${classFunctionHeader}(__first_arg__) { + if (__first_arg__ && __first_arg__[Symbol.for("lively-instance-restorer")]) + {} else { + return this[Symbol.for("lively-instance-initialize")].apply(this, arguments); + } + };${useClassHolder ? '' : '\nvar __lively_class__ = Foo;'} + if (Object.isFrozen(__lively_classholder__)) { + return __lively_class__; + } + return _createOrExtendClass(__lively_class__, superclass, ${methodString}, ${classMethodString}, ${ useClassHolder ? '__lively_classholder__' : 'null'}, ${moduleMeta}${pos}); +}${useClassHolder ? '' : ')'}(${superClassName})`; +} + +function classTemplateDecl (className, superClassName, methodString, classMethodString, classHolder, moduleMeta, start, end, evalId) { + return `var ${className} = ${classTemplate(className, superClassName, methodString, classMethodString, classHolder, moduleMeta, true, start, end, evalId)};`; +} + +describe('ast.capturing', function () { + testVarTfm('transformTopLevelVarDeclsForCapturing', + 'var y, z = foo + bar; baz.foo(z, 3)', + '_rec.y = _rec.y || undefined;\n_rec.z = _rec.foo + _rec.bar;\n_rec.baz.foo(_rec.z, 3);'); + + testVarTfm('transformTopLevelVarAndFuncDeclsForCapturing', + 'var z = 3, y = 4; function foo() { var x = 5; }', + 'function foo() {\n var x = 5;\n}\n\n_rec.foo = foo;\n_rec.z = 3;\n_rec.y = 4;\nfoo;'); + + testVarTfm('transformTopLevelVarDeclsAndVarUsageForCapturing', + 'var z = 3, y = 42, obj = {a: "123", b: function b(n) { return 23 + n; }};\n' + + 'function foo(y) { var x = 5 + y.b(z); }\n', + 'function foo(y) {\n var x = 5 + y.b(_rec.z);\n}\n\n' + + '_rec.foo = foo;\n' + + '_rec.z = 3;\n' + + '_rec.y = 42;\n\n' + + '_rec.obj = {\n' + + ' a: "123",\n\n' + + ' b: function b(n) {\n' + + ' return 23 + n;\n' + + ' }\n\n' + + '};\nfoo;'); + + testVarTfm('dont capture excludes / globals', + { varRecorderName: 'foo', dontTransform: ['baz', 'z'] }, + 'var x = 2; y = 3; z = 4; baz(x, y, z)', + 'foo.x = 2;\nfoo.y = 3;\nz = 4;\nbaz(foo.x, foo.y, z);'); + + testVarTfm('keep var decls when requested', + { varRecorderName: 'foo', keepTopLevelVarDecls: true }, + 'var x = 2, y = 3; baz(x, y)', + 'foo.x = 2;\n' + + 'var x = foo.x;\n' + + 'foo.y = 3;\n' + + 'var y = foo.y;\n' + + 'foo.baz(foo.x, foo.y);'); + + testVarTfm('properly captures global vars even if redefined in sub-scopes', + { varRecorderName: 'foo', keepTopLevelVarDecls: true }, + 'const baz = 42; function bar(y) { const x = baz + 10; if (y > 10) { const baz = 33; return baz + 10 } return x; }', + `function bar(y) { + const x = foo.baz + 10; + + if (y > 10) { + const baz = 33; + return baz + 10; + } + + return x; +} + +foo.bar = bar; +foo.baz = 42; +var baz = foo.baz; +bar;`); + + describe('try-catch', () => { + testVarTfm("isn't transformed", + 'try { throw {} } catch (e) { e }\n', + 'try {\n throw {};\n} catch (e) {\n e;\n}'); + }); + + describe('for statement', function () { + testVarTfm("standard for won't get rewritten", + 'for (var i = 0; i < 5; i ++) { i; }', + 'for (var i = 0; i < 5; i++) {\n i;\n}'); + + testVarTfm("for-in won't get rewritten", + 'for (var x in {}) { x; }', + 'for (var x in {}) {\n x;\n}'); + + testVarTfm("for-of won't get rewritten", + 'for (let x of foo) { x; }', + 'for (let x of _rec.foo) {\n x;\n}'); + + testVarTfm('for-of wont get rewritten 2', + 'for (let [x, y] of foo) { x + y; }', + 'for (let [x, y] of _rec.foo) {\n x + y;\n}'); + }); + + describe('labels', function () { + testVarTfm('ignores continue', + 'loop1:\nfor (var i = 0; i < 3; i++) continue loop1;', + 'loop1:\nfor (var i = 0; i < 3; i++)\n continue loop1;'); + + testVarTfm('ignores break', + 'loop1:\nfor (var i = 0; i < 3; i++) break loop1;', + 'loop1:\nfor (var i = 0; i < 3; i++)\n break loop1;'); + }); + + describe('es6', () => { + describe('let + const', () => { + testVarTfm('captures let as var (...for now)', + 'let x = 23, y = x + 1;', + '_rec.x = 23;\n_rec.y = _rec.x + 1;'); + + testVarTfm('captures const as var (...for now)', + 'const x = 23, y = x + 1;', + '_rec.x = 23;\n_rec.y = _rec.x + 1;'); + }); + + // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + + describe('enhanced object literals', () => { + testVarTfm('captures shorthand properties', + 'var x = 23, y = {x};', + '_rec.x = 23;\n\n_rec.y = {\n x: _rec.x\n};'); + }); + + // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + + describe('default args', () => { + testVarTfm('captures default arg', + 'function x(arg = foo) {}', + 'function x(arg = _rec.foo) {}\n_rec.x = x;\nx;'); + }); + + // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- + + describe('class', () => { + describe('with class-to-func transform', () => { + testVarTfm('normal def', + 'class Foo {\n a() {\n return 23;\n }\n}', + classTemplateDecl('Foo', 'undefined', '[{\n' + + ' key: "a",\n' + + ' value: function Foo_a_() {\n' + + ' return 23;\n' + + ' }\n' + + '}]', '[{\n' + + ' key: Symbol.for("__LivelyClassName__"),\n' + + ' get: function get() {\n' + + ' return "Foo";\n' + + ' }\n' + + '}]', '_rec', 'undefined', 0, 38)); + + testVarTfm('exported def', + 'export class Foo {}', + `export ${classTemplateDecl('Foo', 'undefined', 'undefined', '[{\n' + + ' key: Symbol.for("__LivelyClassName__"),\n' + + ' get: function get() {\n' + + ' return "Foo";\n' + + ' }\n' + + '}]', '_rec', 'undefined', 7, 19)}\n_rec.Foo = Foo;`); + + testVarTfm('exported default def', + 'export default class Foo {}', + `${classTemplateDecl('Foo', 'undefined', 'undefined', '[{\n' + + ' key: Symbol.for("__LivelyClassName__"),\n' + + ' get: function get() {\n' + + ' return "Foo";\n' + + ' }\n' + + '}]', '_rec', 'undefined', 15, 27)}\nexport default Foo;`); + + testVarTfm('does not capture class expr', + 'var bar = class Foo {}', + `_rec.bar = ${classTemplate('Foo', 'undefined', 'undefined', '[{\n' + + ' key: Symbol.for("__LivelyClassName__"),\n' + + ' get: function get() {\n' + + ' return "Foo";\n' + + ' }\n' + + '}]', '_rec', 'undefined', false, 10, 22)};`); + + testVarTfm('captures var that has same name as class expr', + 'var Foo = class Foo {}; new Foo();', + `_rec.Foo = ${classTemplate('Foo', 'undefined', 'undefined', '[{\n' + + ' key: Symbol.for("__LivelyClassName__"),\n' + + ' get: function get() {\n' + + ' return "Foo";\n' + + ' }\n' + + '}]', '_rec', 'undefined', false, 10, 22)};\nnew _rec.Foo();`); + }); + + describe('without class-to-func transform', () => { + let opts = { transformES6Classes: false, captureObj: nodes.id('_rec') }; + + testVarTfm('class def', + opts, + 'class Foo {\n a() {\n return 23;\n }\n}', + 'class Foo {\n a() {\n return 23;\n }\n}\n_rec.Foo = Foo;'); + + testVarTfm('exported def', + opts, + 'export class Foo {}', + 'export class Foo {\n}\n_rec.Foo = Foo;'); + + testVarTfm('exported default def', + opts, + 'export default class Foo {}', + 'export default class Foo {\n}\n_rec.Foo = Foo;'); + + testVarTfm('does not capture class expr', + opts, + 'var bar = class Foo {}', + '_rec.bar = class Foo {\n};'); + + testVarTfm('captures var that has same name as class expr', + opts, + 'var Foo = class Foo {}; new Foo();', + '_rec.Foo = class Foo {\n};\nnew _rec.Foo();'); + }); + }); + + describe('template strings', () => { + testVarTfm('ref inside', + '`${foo}`', + '`${ _rec.foo }`;'); + }); + + describe('computed prop in object literal', () => { + testVarTfm('is dereferenced via var recorder', + 'var x = {[x]: y};', + '_rec.x = { [_rec.x]: _rec.y };'); + }); + + describe('patterns', () => { + testVarTfm('captures destructured obj var', + 'var {x} = {x: 3};', + 'var destructured_1 = { x: 3 };\n' + + '_rec.x = destructured_1.x;'); + + testVarTfm('captures destructured obj var with init', + 'var {x = 4} = {x: 3};', + 'var destructured_1 = { x: 3 };\n' + + '_rec.x = destructured_1.x === undefined ? 4 : destructured_1.x;'); + + testVarTfm('captures destructured obj var with list', + 'var {x: [y]} = foo, z = 23;', + 'var destructured_1 = _rec.foo;\n' + + 'var destructured_1$x = destructured_1.x;\n' + + '_rec.y = destructured_1$x[0];\n' + + '_rec.z = 23;'); + + testVarTfm('captures destructured var with alias', + 'var {x: y} = foo;', + 'var destructured_1 = _rec.foo;\n' + + '_rec.y = destructured_1.x;'); + + testVarTfm('captures destructured deep', + 'var {x: {x: {x}}, y: {y: x}} = foo;', + 'var destructured_1 = _rec.foo;\n' + + 'var destructured_1$x = destructured_1.x;\n' + + 'var destructured_1$x$x = destructured_1$x.x;\n' + + '_rec.x = destructured_1$x$x.x;\n' + + 'var destructured_1$y = destructured_1.y;\n' + + '_rec.x = destructured_1$y.y;'); + + testVarTfm('captures destructured list with spread', + 'var [a, b, ...rest] = foo;', + 'var destructured_1 = _rec.foo;\n' + + '_rec.a = destructured_1[0];\n' + + '_rec.b = destructured_1[1];\n' + + '_rec.rest = destructured_1.slice(2);'); + + testVarTfm('captures destructured list with obj', + 'var [{b}] = foo;', + 'var destructured_1 = _rec.foo;\n' + + 'var destructured_1$0 = destructured_1[0];\n' + + '_rec.b = destructured_1$0.b;'); + + testVarTfm('captures destructured list nested', + 'var [[b]] = foo;', + 'var destructured_1 = _rec.foo;\n' + + 'var destructured_1$0 = destructured_1[0];\n' + + '_rec.b = destructured_1$0[0];'); + + testVarTfm('captures destructured list with obj with default', + 'var [a = 3] = foo;', + 'var destructured_1 = _rec.foo;\n' + + '_rec.a = destructured_1[0] === undefined ? 3 : destructured_1[0];'); + + testVarTfm('captures destructured list with obj with nested default', + 'var [[a = 3]] = foo;', + 'var destructured_1 = _rec.foo;\n' + + 'var destructured_1$0 = destructured_1[0];\n' + + '_rec.a = destructured_1$0[0] === undefined ? 3 : destructured_1$0[0];'); + + testVarTfm('captures destructured list with obj deep', + 'var [{b: {c: [a]}}] = foo;', + 'var destructured_1 = _rec.foo;\n' + + 'var destructured_1$0 = destructured_1[0];\n' + + 'var destructured_1$0$b = destructured_1$0.b;\n' + + 'var destructured_1$0$b$c = destructured_1$0$b.c;\n' + + '_rec.a = destructured_1$0$b$c[0];'); + + testVarTfm('captures rest prop', + 'var {a, b, ...rest} = foo;', + 'var destructured_1 = _rec.foo;\n' + + '_rec.a = destructured_1.a;\n' + + '_rec.b = destructured_1.b;\n' + + 'var rest = {};\n' + + '_rec.rest = rest;\n' + + '(function () {\n' + + ' for (var __key in destructured_1) {\n' + + ' if (__key === "a")\n' + + ' continue;\n' + + ' if (__key === "b")\n' + + ' continue;\n' + + ' rest[__key] = destructured_1[__key];\n' + + ' }\n' + + '}());'); + }); + + describe('async', () => { + testVarTfm('function', + 'async function foo() { return 23 }', + 'async function foo() {\n return 23;\n}\n_rec.foo = foo;\nfoo;'); + + testVarTfm('await', + 'var x = await foo();', + '_rec.x = await _rec.foo();'); + + testVarTfm('exported function', + 'export async function foo() { return 23; }', + 'async function foo() {\n return 23;\n}\n_rec.foo = foo;\nexport {\n foo\n};'); + + testVarTfm('exported default', + 'export default async function foo() { return 23; }', + 'async function foo() {\n return 23;\n}\n_rec.foo = foo;\n\nexport default foo;'); + + // testVarTfm("export default async function foo() { return 23; }", + // "_rec.foo = foo;\nexport default async function foo() {\n return 23;\n}"); + }); + + describe('import', () => { + testVarTfm('default', + 'import x from "./some-es6-module.js";', + 'import x from "./some-es6-module.js";\n_rec.x = x;'); + + testVarTfm('*', + 'import * as name from "module-name";', + 'import * as name from "module-name";\n_rec.name = name;'); + + testVarTfm('member', + 'import { member } from "module-name";', + 'import { member } from "module-name";\n_rec.member = member;'); + + testVarTfm('member with alias', + 'import { member as alias } from "module-name";', + 'import { member as alias } from "module-name";\n_rec.alias = alias;'); + + testVarTfm('multiple members', + 'import { member1 , member2 } from "module-name";', + 'import {\n member1,\n member2\n} from "module-name";\n_rec.member1 = member1;\n_rec.member2 = member2;'); + + testVarTfm('multiple members with alias', + 'import { member1 , member2 as alias} from "module-name";', + 'import {\n member1,\n member2 as alias\n} from "module-name";\n_rec.member1 = member1;\n_rec.alias = alias;'); + + testVarTfm('default and member', + 'import defaultMember, { member } from "module-name";', + 'import defaultMember, { member } from "module-name";\n_rec.defaultMember = defaultMember;\n_rec.member = member;'); + + testVarTfm('default and *', + 'import defaultMember, * as name from "module-name";', + 'import defaultMember, * as name from "module-name";\n_rec.defaultMember = defaultMember;\n_rec.name = name;'); + + testVarTfm('without binding', + 'import "module-name";', + 'import "module-name";'); + }); + + describe('manual import', () => { + let opts = { es6ExportFuncId: '_moduleExport', es6ImportFuncId: '_moduleImport', captureObj: nodes.id('_rec') }; + + testVarTfm('default', + opts, + 'import x from "./some-es6-module.js";', + '_rec.x = _moduleImport("./some-es6-module.js", "default");'); + + testVarTfm('default, declarationWrapper', + Object.assign({}, opts, { declarationWrapper: { name: '_define', type: 'Identifier' } }), + 'import x from "./some-es6-module.js";', + '_rec.x = _define("x", "var", _moduleImport("./some-es6-module.js", "default"), _rec);'); + + testVarTfm('*', + opts, + 'import * as name from "module-name";', + '_rec.name = _moduleImport("module-name");'); + + testVarTfm('member', + opts, + 'import { member } from "module-name";', + '_rec.member = _moduleImport("module-name", "member");'); + + testVarTfm('member with alias', + opts, + 'import { member as alias } from "module-name";', + '_rec.alias = _moduleImport("module-name", "member");'); + + testVarTfm('multiple members', + opts, + 'import { member1 , member2 } from "module-name";', + '_rec.member1 = _moduleImport("module-name", "member1");\n_rec.member2 = _moduleImport("module-name", "member2");'); + + testVarTfm('multiple members with alias', + opts, + 'import { member1 , member2 as alias} from "module-name";', + '_rec.member1 = _moduleImport("module-name", "member1");\n_rec.alias = _moduleImport("module-name", "member2");'); + + testVarTfm('default and member', + opts, + 'import defaultMember, { member } from "module-name";', + '_rec.defaultMember = _moduleImport("module-name", "default");\n_rec.member = _moduleImport("module-name", "member");'); + + testVarTfm('default and *', + opts, + 'import defaultMember, * as name from "module-name";', + '_rec.defaultMember = _moduleImport("module-name", "default");\n_rec.name = _moduleImport("module-name");'); + + testVarTfm('without binding', + opts, + 'import "module-name";', + '_moduleImport("module-name");'); + }); + + describe('export', () => { + testVarTfm('default named', + { keepTopLevelVarDecls: true }, + 'var x = {x: 23}; export default x;', + '_rec.x = { x: 23 };\nvar x = _rec.x;\nexport default x;'); + + testVarTfm('does not rewrite exports but adds capturing statement', + 'var a = 23;\n' + + 'export var x = a + 1, y = x + 2;' + + 'export default function f() {}\n', + 'function f() {\n}\n' + + '_rec.f = f;\n' + + '_rec.a = 23;\n' + + 'export var x = _rec.a + 1;\n' + + '_rec.x = x;\n' + + 'export var y = _rec.x + 2;\n' + + '_rec.y = y;\nexport default f;'); + + testVarTfm('var', + { keepTopLevelVarDecls: true }, + 'var x = 23; export { x };', + '_rec.x = 23;\nvar x = _rec.x;\nexport {\n x\n};'); + + testVarTfm('aliased var', + { keepTopLevelVarDecls: true }, + 'var x = 23; export { x as y };', + '_rec.x = 23;\nvar x = _rec.x;\nexport {\n x as y\n};'); + + testVarTfm('const', + 'export const x = 23;', + 'export const x = 23;\n_rec.x = x;'); + + testVarTfm('function decl', + 'export function x() {};', + 'function x() {\n}\n_rec.x = x;\nexport {\n x\n};\n;'); + + testVarTfm('default function decl', + 'export default function x() {};', + 'function x() {\n}\n_rec.x = x;\nexport default x;\n;'); + + testVarTfm('class decl', + 'export class Foo {};', + `export ${classTemplateDecl('Foo', 'undefined', 'undefined', '[{\n' + + ' key: Symbol.for("__LivelyClassName__"),\n' + + ' get: function get() {\n' + + ' return "Foo";\n' + + ' }\n' + + '}]', '_rec', 'undefined', 7, 19)}\n_rec.Foo = Foo;\n;`); + + testVarTfm('default class decl', + 'export default class Foo {};', + `${classTemplateDecl('Foo', 'undefined', 'undefined', '[{\n' + + ' key: Symbol.for("__LivelyClassName__"),\n' + + ' get: function get() {\n' + + ' return "Foo";\n' + + ' }\n' + + '}]', '_rec', 'undefined', 15, 27)}\nexport default Foo;\n;`); + + testVarTfm('class decl without classToFunction', + { transformES6Classes: false, captureObj: nodes.id('_rec') }, + 'export class Foo {};', + 'export class Foo {\n}\n_rec.Foo = Foo;\n;'); + + testVarTfm('default class decl without classToFunction', + { transformES6Classes: false, captureObj: nodes.id('_rec') }, + 'export default class Foo {};', + 'export default class Foo {\n}\n_rec.Foo = Foo;\n;'); + + testVarTfm('export default expression', + 'export default foo(1, 2, 3);', + 'export default _rec.foo(1, 2, 3);'); + + testVarTfm('re-export * import', + 'import * as completions from "./lib/completions.js";\n' + + 'export { completions }', + 'import * as completions from "./lib/completions.js";\n' + + '_rec.completions = completions;\n' + + 'export {\n completions\n};'); + + testVarTfm('re-export named', + 'export { name1, name2 } from "foo";', + 'export {\n name1,\n name2\n} from "foo";'); + + testVarTfm('export from named', + 'export { name1 as foo1, name2 as bar2 } from "foo";', + 'export {\n name1 as foo1,\n name2 as bar2\n} from "foo";'); + + testVarTfm('export bug 1', + 'foo();\nexport function a() {}\nexport function b() {}', + 'function a() {\n}\n_rec.a = a;\nfunction b() {\n}\n_rec.b = b;\n_rec.foo();\nexport {\n a\n};\nexport {\n b\n};'); + + testVarTfm('export bug 2', + 'export { a } from "./package-commands.js";\n' + + 'export function b() {}\n' + + 'export function c() {}\n', + 'function b() {\n}\n' + + '_rec.b = b;\n' + + 'function c() {\n}\n' + + '_rec.c = c;\n' + + 'export {\n a\n} from "./package-commands.js";\n' + + 'export {\n b\n};\n' + + 'export {\n c\n};'); + }); + + describe('export obj', () => { + let opts = { + es6ExportFuncId: '_moduleExport', + es6ImportFuncId: '_moduleImport', + captureObj: nodes.id('_rec'), + classToFunction: { + classHolder: nodes.id('_rec'), + functionNode: nodes.id('_createOrExtendClass'), + transform: classToFunctionTransform + } + }; + + testVarTfm('func decl', + opts, + 'export function foo(a) { return a + 3; };', + 'function foo(a) {\n return a + 3;\n}\n_rec.foo = foo;\n_moduleExport("foo", _rec.foo);\n;'); + + testVarTfm('default anonym func decl', + opts, + 'export default function () {};', + '_moduleExport("default", function () {\n});\n;'); + + testVarTfm('default func* decl', + opts, + 'export default function* () {};', + '_moduleExport("default", function* () {\n});\n;'); + + testVarTfm('default function', + opts, + 'export default function foo() {};', + 'function foo() {\n}\n_rec.foo = foo;\n_moduleExport("default", _rec.foo);\n;'); + + testVarTfm('default async func decl', + opts, + 'export default async function foo() {};', + 'async function foo() {\n}\n_rec.foo = foo;\n_moduleExport("default", _rec.foo);\n;'); + + testVarTfm('default class decl', + opts, + 'export default class Foo {a() { return 23; }};', + classTemplateDecl('Foo', 'undefined', '[{\n' + + ' key: "a",\n' + + ' value: function Foo_a_() {\n' + + ' return 23;\n' + + ' }\n' + + '}]', '[{\n' + + ' key: Symbol.for("__LivelyClassName__"),\n' + + ' get: function get() {\n' + + ' return "Foo";\n' + + ' }\n' + + '}]', '_rec', 'undefined', 15, 45) + + '\n_moduleExport("default", _rec.Foo);\n;'); + + testVarTfm('class decl, declarationWrapper', + { + ...opts, + classToFunction: { + classHolder: nodes.id('_rec'), + functionNode: nodes.id('_createOrExtendClass'), + declarationWrapper: { name: '_define', type: 'Identifier' }, + transform: classToFunctionTransform + } + }, + 'export class Foo {a() { return 23; }};', + 'var Foo = _define("Foo", "class", ' + + classTemplate('Foo', 'undefined', '[{\n' + + ' key: "a",\n' + + ' value: function Foo_a_() {\n' + + ' return 23;\n' + + ' }\n' + + '}]', '[{\n' + + ' key: Symbol.for("__LivelyClassName__"),\n' + + ' get: function get() {\n' + + ' return "Foo";\n' + + ' }\n' + + '}]', '_rec', 'undefined', 'undefined', 7, 37) + + ', _rec, {\n' + + ' start: 7,\n' + + ' end: 37\n' + + '});\n' + + '_moduleExport("Foo", _rec.Foo);\n;' + + ); + + testVarTfm('named', + opts, + 'let name1, name2; export { name1, name2 };', + '_rec.name1 = _rec.name1 || undefined;\n_rec.name2 = _rec.name2 || undefined;\n_moduleExport("name1", _rec.name1);\n_moduleExport("name2", _rec.name2);'); + + testVarTfm('var decl, double', + opts, + 'export var x = 34, y = x + 3;', + 'var x = _rec.x = 34;\nvar y = _rec.y = _rec.x + 3;\n_moduleExport("x", _rec.x);\n_moduleExport("y", _rec.y);'); + + testVarTfm('let decl', + opts, + 'export let x = 34;', + 'let x = _rec.x = 34;\n_moduleExport("x", _rec.x);'); + + testVarTfm('let decl, declarationWrapper', + Object.assign({}, opts, { declarationWrapper: { name: '_define', type: 'Identifier' } }), + 'export let x = 34;', + 'let x = _rec.x = _rec._define("x", "let", 34, _rec, { start: 11, end: 17 });\n_moduleExport("x", _rec.x);'); + + testVarTfm('name aliased', + opts, + 'let name1; export { name1 as default };', + '_rec.name1 = _rec.name1 || undefined;\n_moduleExport("default", _rec.name1);'); + + testVarTfm('* from', + opts, + 'export * from "foo";', + 'for (var _moduleExport__iterator__ in _moduleImport("foo"))\n' + + ' _moduleExport(_moduleExport__iterator__, _moduleImport("foo", _moduleExport__iterator__));'); + + testVarTfm('named from', + opts, + 'export { name1, name2 } from "foo"', + '_moduleExport("name1", _moduleImport("foo", "name1"));\n_moduleExport("name2", _moduleImport("foo", "name2"));'); + + testVarTfm('named from aliased', + opts, + 'export { name1 as foo1, name2 as bar2 } from "foo";', + '_moduleExport("foo1", _moduleImport("foo", "name1"));\n_moduleExport("bar2", _moduleImport("foo", "name2"));'); + }); + }); +}); + +describe('declarations', () => { + let opts = { + // es6ExportFuncId: '_moduleExport', + // es6ImportFuncId: '_moduleImport', + keepTopLevelVarDecls: true, + declarationWrapper: t.Identifier('_define'), + captureObj: nodes.id('_rec'), + addSourceMeta: false, + classToFunction: { + classHolder: nodes.id('_rec'), + functionNode: nodes.id('_createOrExtendClass') + } + }; + + testVarTfm( + 'wraps literals that are exported as defaults', + opts, + 'export default 32', + '_rec.$32 = 32;\nvar $32 = _rec.$32;\nexport default $32;'); + + testVarTfm( + 'can be wrapped in define call', + { ...opts, keepTopLevelVarDecls: false }, + 'var x = 23;', + '_rec.x = _define("x", "var", 23, _rec);'); + + testVarTfm( + 'assignments are wrapped in define call', + opts, + 'x = 23;', + '_rec.x = _define("x", "assignment", 23, _rec);' + ); + + testVarTfm('define call works for exports 1', opts, 'export var x = 23;', + 'export var x = 23;\n_rec.x = _define("x", "assignment", x, _rec);'); + + testVarTfm('define call works for exports 2', opts, 'export function foo() {}', + 'function foo() {}\n_rec.foo = _define(\"foo\", \"function\", foo, _rec);\nexport { foo };'); + + testVarTfm( + 'define call works for exports 3', + opts, + 'export class Foo {}', + `export var Foo = _define(\"Foo\", \"class\", ${classTemplate('Foo', 'undefined', 'undefined', '[{\n' + + ' key: Symbol.for("__LivelyClassName__"),\n' + + ' get: function get() {\n' + + ' return "Foo";\n' + + ' }\n' + + '}]', '_rec', 'undefined', 'undefined', 7, 19)}, _rec, {\n start: 7,\n end: 19\n});\n_rec.Foo = Foo;`); + + testVarTfm( + 'define call works for exports 4', + opts, + 'var x, y; x = 23; export { x, y };', `_rec.x = _define("x", "var", _rec.x || undefined, _rec); +var x = _rec.x; +_rec.y = _define("y", "var", _rec.y || undefined, _rec); +var y = _rec.y; +_rec.x = _define("x", "assignment", 23, _rec); +export { x, y };`); + + testVarTfm('wraps class decls', + opts, + 'class Foo {}', + `var Foo = _define(\"Foo\", \"class\", ${classTemplate('Foo', 'undefined', 'undefined', '[{\n' + + ' key: Symbol.for("__LivelyClassName__"),\n' + + ' get: function get() {\n' + + ' return "Foo";\n' + + ' }\n' + + '}]', '_rec', 'undefined', 'undefined', 0, 12)}, _rec, {\n start: 0,\n end: 12\n});`); + + testVarTfm('wraps function decls', opts, 'function bar() {}', + 'function bar() {\n}\n_rec.bar = _define("bar", "function", bar, _rec);\nbar;'); + + testVarTfm('wraps destructuring', opts, 'var [{x}, y] = foo', +`var destructured_1 = _rec.foo; +var destructured_1$0 = destructured_1[0]; +_rec.x = _define(\"x\", \"var\", destructured_1$0.x, _rec); +_rec.y = _define(\"y\", \"var\", destructured_1[1], _rec);`); + + testVarTfm('evalId and sourceAccessorName', { + ...opts, evalId: 1, sourceAccessorName: '__source' + }, + 'function foo() {}', + 'function foo() {\n' + + '}\n' + + '_rec.foo = _define(\"foo\", \"function\", foo, _rec, {\n' + + ' evalId: 1,\n' + + ' moduleSource: __source\n' + + '});\n' + + 'foo;'); +}); + +describe('System.register', () => { + describe('setters', () => { + let input = +`System.register(["foo:a.js", "http://zork/b.js"], function (_export, _context) { +"use strict"; +var x, y, z, _rec; +return { + setters: [ + function(foo_a_js) { x = foo_a_js.x }, + function (_zork_b_js) { y = _zork_b_js.default; z = _zork_b_js.z; }], + execute: function () { + _rec = System.get("@lively-env").moduleEnv("c.js").recorder; + _rec.x = 23; + } +}; +});`; + + testVarTfm( + 'captures setters of registered module', + { varRecorderName: '_rec', dontTransform: ['z'], plugin: livelyPostTranspile }, + input, + `System.register([ + \"foo:a.js\", + \"http://zork/b.js\" +], function (_export, _context) { + \"use strict\"; + var x, y, z, _rec; + _rec = System.get(\"@lively-env\").moduleEnv(\"c.js\").recorder; + return { + setters: [ + function (foo_a_js = {}) { + _rec.x = x = foo_a_js.x; + }, + function (_zork_b_js = {}) { + _rec.y = y = _zork_b_js.default; + z = _zork_b_js.z; + } + ], + execute: function () { + _rec.x = 23; + } + }; +});`); + + testVarTfm( + 'captures setters of registered module with declarationWrapper', + { plugin: livelyPostTranspile, varRecorderName: '_rec', declarationWrapper: t.Identifier('_define') }, + input, + `System.register([ + \"foo:a.js\", + \"http://zork/b.js\" +], function (_export, _context) { + \"use strict\"; + var x, y, z, _rec; + _rec = System.get(\"@lively-env\").moduleEnv(\"c.js\").recorder; + return { + setters: [ + function (foo_a_js = {}) { + _rec.x = _define(\"x\", \"var\", x = foo_a_js.x, _rec); + }, + function (_zork_b_js = {}) { + _rec.y = _define(\"y\", \"var\", y = _zork_b_js.default, _rec); + _rec.z = _define(\"z\", \"var\", z = _zork_b_js.z, _rec); + } + ], + execute: function () { + _rec.x = 23; + } + }; +});`); + }); +}); diff --git a/lively.source-transform/tests/capturing-test.js b/lively.source-transform/tests/capturing-test.js index e34bc5a31a..349f245f9c 100644 --- a/lively.source-transform/tests/capturing-test.js +++ b/lively.source-transform/tests/capturing-test.js @@ -1,17 +1,20 @@ /* global describe, it */ import { expect } from 'mocha-es6'; import { string, fun } from 'lively.lang'; -import { stringify, parse, transform, nodes } from 'lively.ast'; +import { parse, nodes, stringify } from 'lively.ast'; import { rewriteToCaptureTopLevelVariables, rewriteToRegisterModuleToCaptureSetters } from '../capturing.js'; import { classToFunctionTransform } from 'lively.classes'; -import { defaultClassToFunctionConverterName } from 'lively.vm'; +import objectSpreadTransform from 'lively.ast/lib/object-spread-transform.js'; function _testVarTfm (descr, options, code, expected, only) { + // options = 'var y, z = foo + bar; baz.foo(z, 3)'; + // code = '_rec.y = _rec.y || undefined;\n_rec.z = _rec.foo + _rec.bar;\n_rec.baz.foo(_rec.z, 3);' if (typeof options === 'string') { only = expected; expected = code; code = options; options = { + captureObj: nodes.id('_rec'), classToFunction: { classHolder: nodes.id('_rec'), functionNode: nodes.id('_createOrExtendClass'), @@ -21,21 +24,22 @@ function _testVarTfm (descr, options, code, expected, only) { } return (only ? it.only : it)(descr, () => { let result = stringify( - fun.compose(rewriteToCaptureTopLevelVariables, transform.objectSpreadTransform)( - parse(code), { - name: '_rec', - type: 'Identifier' - }, options)); - expect(result).equals(expected); + fun.compose(rewriteToCaptureTopLevelVariables, objectSpreadTransform)( + parse(code), nodes.id('_rec'), options)); + expect(result).equals(stringify(parse(expected))); }); } +function ignoreFormatCompare (result, expected) { + return expect(stringify(parse(result))).equals(stringify(parse(expected))); +} + function testVarTfm (descr, options, code, expected) { return _testVarTfm(descr, options, code, expected, false); } function only_testVarTfm (descr, options, code, expected) { return _testVarTfm(descr, options, code, expected, true); } function classTemplate (className, superClassName, methodString, classMethodString, classHolder, moduleMeta, useClassHolder = true, start, end, evalId) { - if (methodString.includes('\n')) methodString = string.indent(methodString, ' ', 2).replace(/^\s+/, ''); - if (classMethodString.includes('\n')) classMethodString = string.indent(classMethodString, ' ', 2).replace(/^\s+/, ''); + if (methodString.includes('\n')) methodString = string.indent(methodString, ' ', 2).replace(/^\s+/, ''); + if (classMethodString.includes('\n')) classMethodString = string.indent(classMethodString, ' ', 2).replace(/^\s+/, ''); if (!className) useClassHolder = false; @@ -49,19 +53,19 @@ function classTemplate (className, superClassName, methodString, classMethodStri end: ${end}${evalId ? `,\n evalId: ${evalId}` : ''} }`; } - return `function (superclass) { + return `${useClassHolder ? 'function(superclass)' : '(superclass =>'} { var __lively_classholder__ = ${classHolder}; - var __lively_class__ = ${classFunctionHeader}(__first_arg__) { - if (__first_arg__ && __first_arg__[Symbol.for("lively-instance-restorer")]) { - } else { + var ${useClassHolder ? '__lively_class__' : 'Foo'} = ${classFunctionHeader}(__first_arg__) { + if (__first_arg__ && __first_arg__[Symbol.for("lively-instance-restorer")]) + {} else { return this[Symbol.for("lively-instance-initialize")].apply(this, arguments); } - }; + };${useClassHolder ? '' : '\nvar __lively_class__ = Foo;'} if (Object.isFrozen(__lively_classholder__)) { return __lively_class__; } return _createOrExtendClass(__lively_class__, superclass, ${methodString}, ${classMethodString}, ${ useClassHolder ? '__lively_classholder__' : 'null'}, ${moduleMeta}${pos}); -}(${superClassName})`; +}${useClassHolder ? '' : ')'}(${superClassName})`; } function classTemplateDecl (className, superClassName, methodString, classMethodString, classHolder, moduleMeta, start, end, evalId) { @@ -75,21 +79,21 @@ describe('ast.capturing', function () { testVarTfm('transformTopLevelVarAndFuncDeclsForCapturing', 'var z = 3, y = 4; function foo() { var x = 5; }', - 'function foo() {\n var x = 5;\n}\n_rec.foo = foo;\n_rec.z = 3;\n_rec.y = 4;\nfoo;'); + 'function foo() {\n var x = 5;\n}\n\n_rec.foo = foo;\n_rec.z = 3;\n_rec.y = 4;\nfoo;'); testVarTfm('transformTopLevelVarDeclsAndVarUsageForCapturing', 'var z = 3, y = 42, obj = {a: "123", b: function b(n) { return 23 + n; }};\n' + 'function foo(y) { var x = 5 + y.b(z); }\n', - 'function foo(y) {\n var x = 5 + y.b(_rec.z);\n}\n' + + 'function foo(y) {\n var x = 5 + y.b(_rec.z);\n}\n\n' + '_rec.foo = foo;\n' + '_rec.z = 3;\n' + - '_rec.y = 42;\n' + + '_rec.y = 42;\n\n' + '_rec.obj = {\n' + - ' a: "123",\n' + + ' a: "123",\n\n' + ' b: function b(n) {\n' + ' return 23 + n;\n' + - ' }\n' + - '};\n' + + ' }\n\n' + + '};\n\n' + 'foo;'); it("don't capture excludes / globals", function () { @@ -97,8 +101,8 @@ describe('ast.capturing', function () { let expected = 'foo.x = 2;\nfoo.y = 3;\nz = 4;\nbaz(foo.x, foo.y, z);'; let recorder = { name: 'foo', type: 'Identifier' }; let result = stringify(rewriteToCaptureTopLevelVariables( - parse(code), recorder, { exclude: ['baz', 'z'] })); - expect(result).equals(expected); + parse(code), recorder, { captureObj: recorder, exclude: ['baz', 'z'] })); + expect(result).equals(stringify(parse(expected))); }); it('keep var decls when requested', function () { @@ -110,10 +114,32 @@ describe('ast.capturing', function () { 'foo.baz(foo.x, foo.y);'; let recorder = { name: 'foo', type: 'Identifier' }; let result = stringify(rewriteToCaptureTopLevelVariables( - parse(code), recorder, { keepTopLevelVarDecls: true })); + parse(code), recorder, { captureObj: recorder, keepTopLevelVarDecls: true })); expect(result).equals(expected); }); + it('properly captures global vars even if redefined in sub-scopes', function () { + let code = 'const baz = 42; function bar(y) { const x = baz + 10; if (y > 10) { const baz = 33; return baz + 10 } return x; }'; + let recorder = { name: 'foo', type: 'Identifier' }; + let result = stringify(rewriteToCaptureTopLevelVariables( + parse(code), recorder, { captureObj: recorder, keepTopLevelVarDecls: true })); + ignoreFormatCompare(result, `function bar(y) { + const x = foo.baz + 10; + + if (y > 10) { + const baz = 33; + return baz + 10; + } + + return x; +} + +foo.bar = bar; +foo.baz = 42; +var baz = foo.baz; +bar;`); + }); + describe('try-catch', () => { testVarTfm("isn't transformed", 'try { throw {} } catch (e) { e }\n', @@ -141,11 +167,11 @@ describe('ast.capturing', function () { describe('labels', function () { testVarTfm('ignores continue', 'loop1:\nfor (var i = 0; i < 3; i++) continue loop1;', - 'loop1:\n for (var i = 0; i < 3; i++)\n continue loop1;'); + 'loop1:\nfor (var i = 0; i < 3; i++)\n continue loop1;'); testVarTfm('ignores break', 'loop1:\nfor (var i = 0; i < 3; i++) break loop1;', - 'loop1:\n for (var i = 0; i < 3; i++)\n break loop1;'); + 'loop1:\nfor (var i = 0; i < 3; i++)\n break loop1;'); }); describe('es6', () => { @@ -164,7 +190,7 @@ describe('ast.capturing', function () { describe('enhanced object literals', () => { testVarTfm('captures shorthand properties', 'var x = 23, y = {x};', - '_rec.x = 23;\n_rec.y = { x: _rec.x };'); + '_rec.x = 23;\n\n_rec.y = {\n x: _rec.x\n};'); }); // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- @@ -172,7 +198,7 @@ describe('ast.capturing', function () { describe('default args', () => { testVarTfm('captures default arg', 'function x(arg = foo) {}', - 'function x(arg = _rec.foo) {\n}\n_rec.x = x;\nx;'); + 'function x(arg = _rec.foo) {}\n_rec.x = x;\nx;'); }); // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- @@ -231,7 +257,7 @@ describe('ast.capturing', function () { }); describe('without class-to-func transform', () => { - let opts = { classToFunction: null }; + let opts = { classToFunction: null, captureObj: nodes.id('_rec') }; testVarTfm('class def', opts, @@ -420,7 +446,7 @@ describe('ast.capturing', function () { }); describe('manual import', () => { - let opts = { es6ExportFuncId: '_moduleExport', es6ImportFuncId: '_moduleImport' }; + let opts = { es6ExportFuncId: '_moduleExport', es6ImportFuncId: '_moduleImport', captureObj: nodes.id('_rec') }; testVarTfm('default', opts, @@ -529,12 +555,12 @@ describe('ast.capturing', function () { '}]', '_rec', 'undefined', 15, 27)}\nexport default Foo;\n;`); testVarTfm('class decl without classToFunction', - { classToFunction: null }, + { classToFunction: null, captureObj: nodes.id('_rec') }, 'export class Foo {};', 'export class Foo {\n}\n_rec.Foo = Foo;\n;'); testVarTfm('default class decl without classToFunction', - { classToFunction: null }, + { classToFunction: null, captureObj: nodes.id('_rec') }, 'export default class Foo {};', 'export default class Foo {\n}\n_rec.Foo = Foo;\n;'); @@ -578,6 +604,7 @@ describe('ast.capturing', function () { let opts = { es6ExportFuncId: '_moduleExport', es6ImportFuncId: '_moduleImport', + captureObj: nodes.id('_rec'), classToFunction: { classHolder: nodes.id('_rec'), functionNode: nodes.id('_createOrExtendClass'), @@ -665,17 +692,17 @@ describe('ast.capturing', function () { testVarTfm('var decl, double', opts, 'export var x = 34, y = x + 3;', - 'var x = _rec.x = 34;;\nvar y = _rec.y = _rec.x + 3;;\n_moduleExport("x", _rec.x);\n_moduleExport("y", _rec.y);'); + 'var x = _rec.x = 34;\nvar y = _rec.y = _rec.x + 3;\n_moduleExport("x", _rec.x);\n_moduleExport("y", _rec.y);'); testVarTfm('let decl', opts, 'export let x = 34;', - 'let x = _rec.x = 34;;\n_moduleExport("x", _rec.x);'); + 'let x = _rec.x = 34;\n_moduleExport("x", _rec.x);'); testVarTfm('let decl, declarationWrapper', Object.assign({}, opts, { declarationWrapper: { name: '_define', type: 'Identifier' } }), 'export let x = 34;', - 'let x = _rec.x = _rec._define("x", "let", x = 34, _rec);;\n_moduleExport("x", _rec.x);'); + 'let x = _rec.x = _rec._define("x", "let", 34, _rec);\n_moduleExport("x", _rec.x);'); testVarTfm('name aliased', opts, @@ -712,8 +739,11 @@ describe('declarations', () => { }) { return stringify( rewriteToCaptureTopLevelVariables( - parse(code), { name: '_rec', type: 'Identifier' }, - { declarationWrapper: { name: '_define', type: 'Identifier' }, ...opts })); + parse(code), nodes.id('_rec'), { + declarationWrapper: { name: '_define', type: 'Identifier' }, + captureObj: nodes.id('_rec'), + ...opts + })); } it('wraps literals that are exported as defaults', () => { @@ -729,24 +759,24 @@ describe('declarations', () => { }); it('define call works for exports', () => { - expect(rewriteWithWrapper('export var x = 23;')) - .equals('export var x = 23;\n_rec.x = _define("x", "assignment", x, _rec);'); + ignoreFormatCompare(rewriteWithWrapper('export var x = 23;'), + 'export var x = 23;\n_rec.x = _define("x", "assignment", x, _rec);'); - expect(rewriteWithWrapper('export function foo() {};')) - .equals('function foo() {\n}\n_rec.foo = _define(\"foo\", \"function\", foo, _rec);\nexport {\n foo\n};\n;'); + ignoreFormatCompare(rewriteWithWrapper('export function foo() {}'), + 'function foo() {}\n_rec.foo = _define(\"foo\", \"function\", foo, _rec);\nexport { foo };'); - expect(rewriteWithWrapper('export class Foo {}')).equals(`export var Foo = _define(\"Foo\", \"class\", ${classTemplate('Foo', 'undefined', 'undefined', '[{\n' + + ignoreFormatCompare(rewriteWithWrapper('export class Foo {}'), `export var Foo = _define(\"Foo\", \"class\", ${classTemplate('Foo', 'undefined', 'undefined', '[{\n' + ' key: Symbol.for("__LivelyClassName__"),\n' + ' get: function get() {\n' + ' return "Foo";\n' + ' }\n' + '}]', '_rec', 'undefined', 'undefined', 7, 19)}, _rec, {\n start: 7,\n end: 19\n});\n_rec.Foo = Foo;`); - expect(rewriteWithWrapper('var x, y; x = 23; export { x, y };')).equals('_rec.x = _define("x", "var", _rec.x || undefined, _rec);\n_rec.y = _define("y", "var", _rec.y || undefined, _rec);\n_rec.x = _define("x", "assignment", 23, _rec);\nvar x = _rec.x;\nvar y = _rec.y;\nexport {\n x,\n y\n};'); + ignoreFormatCompare(rewriteWithWrapper('var x, y; x = 23; export { x, y };'), '_rec.x = _define("x", "var", _rec.x || undefined, _rec);\n_rec.y = _define("y", "var", _rec.y || undefined, _rec);\n_rec.x = _define("x", "assignment", 23, _rec);\nvar x = _rec.x;\nvar y = _rec.y;\nexport {\n x,\n y\n};'); }); it('wraps class decls', () => { - expect(rewriteWithWrapper('class Foo {}')).equals(`var Foo = _define(\"Foo\", \"class\", ${classTemplate('Foo', 'undefined', 'undefined', '[{\n' + + ignoreFormatCompare(rewriteWithWrapper('class Foo {}'), `var Foo = _define(\"Foo\", \"class\", ${classTemplate('Foo', 'undefined', 'undefined', '[{\n' + ' key: Symbol.for("__LivelyClassName__"),\n' + ' get: function get() {\n' + ' return "Foo";\n' + @@ -755,8 +785,8 @@ describe('declarations', () => { }); it('wraps function decls', () => { - expect(rewriteWithWrapper('function bar() {}')) - .equals('function bar() {\n}\n_rec.bar = _define("bar", "function", bar, _rec);\nbar;'); + ignoreFormatCompare(rewriteWithWrapper('function bar() {}'), + 'function bar() {\n}\n_rec.bar = _define("bar", "function", bar, _rec);\nbar;'); }); it('wraps destructuring', () => { @@ -768,9 +798,9 @@ _rec.y = _define(\"y\", \"var\", destructured_1[1], _rec);`); }); it('evalId and sourceAccessorName', () => { - expect( - rewriteWithWrapper('function foo() {}', { evalId: 1, sourceAccessorName: '__source' })) - .equals('function foo() {\n' + + ignoreFormatCompare( + rewriteWithWrapper('function foo() {}', { evalId: 1, sourceAccessorName: '__source' }), + 'function foo() {\n' + '}\n' + '_rec.foo = _define(\"foo\", \"function\", foo, _rec, {\n' + ' evalId: 1,\n' + @@ -798,12 +828,12 @@ return { });`; it('captures setters of registered module', () => { - expect(stringify( + ignoreFormatCompare(stringify( rewriteToRegisterModuleToCaptureSetters( parse(input), { name: '_rec', type: 'Identifier' }, - { exclude: ['z'] }))) - .equals(`System.register([ + { exclude: ['z'] })), + `System.register([ \"foo:a.js\", \"http://zork/b.js\" ], function (_export, _context) { @@ -828,12 +858,12 @@ return { }); it('captures setters of registered module with declarationWrapper', () => { - expect(stringify( + ignoreFormatCompare(stringify( rewriteToRegisterModuleToCaptureSetters( parse(input), { name: '_rec', type: 'Identifier' }, - { declarationWrapper: { name: '_define', type: 'Identifier' } }))) - .equals(`System.register([ + { declarationWrapper: { name: '_define', type: 'Identifier' } })), + `System.register([ \"foo:a.js\", \"http://zork/b.js\" ], function (_export, _context) { diff --git a/lively.vm/lib/esm-eval.js b/lively.vm/lib/esm-eval.js index f7009e7bab..ef94859c87 100644 --- a/lively.vm/lib/esm-eval.js +++ b/lively.vm/lib/esm-eval.js @@ -113,8 +113,8 @@ function getEs6Transpiler (System, options, env) { babelPluginTranspilerForAsyncAwaitCode(System, babelPlugin, options.targetModule, env)); } - if (System.transpiler === 'lively.transpiler') { - let Transpiler = System.get('lively.transpiler').default; + if (System.transpiler === 'lively.transpiler.babel') { + let Transpiler = System.get('lively.transpiler.babel').default; let transpiler = new Transpiler(System, options.targetModule, env); return (source, options) => transpiler.transpileDoit(source, options); } diff --git a/lively.vm/tests/esm-eval-test.js b/lively.vm/tests/esm-eval-test.js index ae5f586418..d978b4f398 100644 --- a/lively.vm/tests/esm-eval-test.js +++ b/lively.vm/tests/esm-eval-test.js @@ -20,9 +20,9 @@ describe('eval', () => { if (modules) { S = modules.getSystem('test', { baseURL: dir }); S.babelOptions = System.babelOptions; - S.set('lively.transpiler', System.get('lively.transpiler')); - S.config({ transpiler: 'lively.transpiler' }); - S.translate = async (load) => await System.translate.bind(S)(load); + S.set('lively.transpiler.babel', System.get('lively.transpiler.babel')); + S.config({ transpiler: 'lively.transpiler.babel' }); + S.translate = async (load, opts) => await System.translate.bind(S)(load, opts); } return S.import(module1); diff --git a/mocha-es6/index.js b/mocha-es6/index.js index ce1eab0e6e..bcfd156842 100644 --- a/mocha-es6/index.js +++ b/mocha-es6/index.js @@ -4,6 +4,12 @@ import * as modules from 'lively.modules'; import { withMozillaAstDo } from 'lively.ast'; import mocha from 'mocha'; import chai from 'chai'; +import chaiSubset from 'chai-subset'; + +System.global.chai = chai; +System.global.mocha = mocha; + +chai.use(chaiSubset); // FIXME: This is a temporary solution since we can not easily bundle mocha and chai into the frozen bundle because the esm builds are temporarily broken. // For now we just inject them manually into the frozen bundle by setting the modules namespaces here: diff --git a/mocha-es6/package.json b/mocha-es6/package.json index 621dc8c418..90ac42938d 100644 --- a/mocha-es6/package.json +++ b/mocha-es6/package.json @@ -10,7 +10,8 @@ "minimist": "^1.2.0", "systemjs": "^0.21.6", "mocha": "^10.0.0", - "chai": "^4.3.6" + "chai": "^4.3.6", + "chai-subset": "1.6.0" }, "devDependencies": { "babel-plugin-external-helpers": "^6.18.0", @@ -34,6 +35,45 @@ "author": "Robert Krahn", "systemjs": { "main": "index.js", + "importMap": { + "imports": { + "chai": "esm://ga.jspm.io/npm:chai@4.3.6/index.mjs", + "mocha": "esm://ga.jspm.io/npm:mocha@10.0.0/dev.browser-entry.js" + }, + "scopes": { + "esm://ga.jspm.io/": { + "#lib/nodejs/esm-utils.js": "esm://ga.jspm.io/npm:@jspm/core@2.1.0/nodelibs/@empty.js", + "#lib/nodejs/file-unloader.js": "esm://ga.jspm.io/npm:@jspm/core@2.1.0/nodelibs/@empty.js", + "#lib/nodejs/parallel-buffered-runner.js": "esm://ga.jspm.io/npm:@jspm/core@2.1.0/nodelibs/@empty.js", + "assertion-error": "esm://ga.jspm.io/npm:assertion-error@1.1.0/index.js", + "browser-stdout": "esm://ga.jspm.io/npm:browser-stdout@1.3.1/index.js", + "buffer": "esm://ga.jspm.io/npm:@jspm/core@2.1.0/nodelibs/browser/buffer.js", + "check-error": "esm://ga.jspm.io/npm:check-error@1.0.3/index.js", + "debug": "esm://ga.jspm.io/npm:debug@4.3.4/src/browser.js", + "deep-eql": "esm://ga.jspm.io/npm:deep-eql@3.0.1/index.js", + "diff": "esm://ga.jspm.io/npm:diff@5.0.0/lib/index.js", + "escape-string-regexp": "esm://ga.jspm.io/npm:escape-string-regexp@4.0.0/index.js", + "events": "esm://ga.jspm.io/npm:@jspm/core@2.1.0/nodelibs/browser/events.js", + "fs": "esm://ga.jspm.io/npm:@jspm/core@2.1.0/nodelibs/browser/fs.js", + "get-func-name": "esm://ga.jspm.io/npm:get-func-name@2.0.2/index.js", + "he": "esm://ga.jspm.io/npm:he@1.2.0/he.js", + "log-symbols": "esm://ga.jspm.io/npm:log-symbols@4.1.0/browser.js", + "loupe": "esm://ga.jspm.io/npm:loupe@2.3.7/loupe.js", + "ms": "esm://ga.jspm.io/npm:ms@2.1.3/index.js", + "nanoid/non-secure": "esm://ga.jspm.io/npm:nanoid@3.3.3/non-secure/index.cjs", + "path": "esm://ga.jspm.io/npm:@jspm/core@2.1.0/nodelibs/browser/path.js", + "pathval": "esm://ga.jspm.io/npm:pathval@1.1.1/index.js", + "process": "esm://ga.jspm.io/npm:@jspm/core@2.1.0/nodelibs/browser/process.js", + "stream": "esm://ga.jspm.io/npm:@jspm/core@2.1.0/nodelibs/browser/stream.js", + "supports-color": "esm://ga.jspm.io/npm:supports-color@8.1.1/browser.js", + "type-detect": "esm://ga.jspm.io/npm:type-detect@4.1.0/type-detect.js", + "util": "esm://ga.jspm.io/npm:@jspm/core@2.1.0/nodelibs/browser/util.js" + }, + "esm://ga.jspm.io/npm:debug@4.3.4/": { + "ms": "esm://ga.jspm.io/npm:ms@2.1.2/index.js" + } + } + }, "meta": { "dist/mocha.js": { "format": "global", @@ -45,8 +85,15 @@ } }, "map": { - "chai": "./dist/chai.js", - "mocha": "./dist/mocha.js", + "chai-subset": { + "~node": "esm://ga.jspm.io/npm:chai-subset@1.6.0/lib/chai-subset.js" + }, + "chai": { + "node": "./dist/chai.js" + }, + "mocha": { + "node": "./dist/mocha.js" + }, "fs": { "node": "@node/fs", "~node": "@empty" @@ -57,4 +104,4 @@ } } } -} +} \ No newline at end of file