You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@weex.apache.org by ha...@apache.org on 2017/12/29 11:13:55 UTC
[3/4] incubator-weex git commit: [jsfm] Enhance the multi-instance
isolation (sandbox) (resolve #960)
http://git-wip-us.apache.org/repos/asf/incubator-weex/blob/dc428443/packages/weex-js-framework/index.js
----------------------------------------------------------------------
diff --git a/packages/weex-js-framework/index.js b/packages/weex-js-framework/index.js
index 95ec054..0ae167e 100644
--- a/packages/weex-js-framework/index.js
+++ b/packages/weex-js-framework/index.js
@@ -1,5 +1,5 @@
-(this.nativeLog || function(s) {console.log(s)})('START JS FRAMEWORK 0.22.4, Build 2017-09-25 11:14.');
-;(this.getJSFMVersion = function(){return "0.22.4"});
+(this.nativeLog || function(s) {console.log(s)})('START JS FRAMEWORK 0.23.6, Build 2017-12-29 15:36.');
+;(this.getJSFMVersion = function(){return "0.23.6"});
var global = this, process = { env: {} };var setTimeout = global.setTimeout;
(function (global, factory) {
@@ -8,7 +8,7 @@ var global = this, process = { env: {} };var setTimeout = global.setTimeout;
(factory());
}(this, (function () { 'use strict';
-var subversion = {"browser":"0.5.0","framework":"0.22.4","vue-render":"0.12.3","transformer":">=0.1.5 <0.5"};
+var subversion = {"framework":"0.23.6","transformer":">=0.1.5 <0.5"};
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -138,7 +138,7 @@ if (typeof __g == 'number') { __g = global; } // eslint-disable-line no-undef
});
var _core = createCommonjsModule(function (module) {
-var core = module.exports = { version: '2.5.1' };
+var core = module.exports = { version: '2.5.3' };
if (typeof __e == 'number') { __e = core; } // eslint-disable-line no-undef
});
@@ -838,7 +838,7 @@ var _iterDefine = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORC
var VALUES_BUG = false;
var proto = Base.prototype;
var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
- var $default = $native || getMethod(DEFAULT);
+ var $default = (!BUGGY && $native) || getMethod(DEFAULT);
var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
var methods, key, IteratorPrototype;
@@ -1099,7 +1099,7 @@ var global$5 = _global;
var process$2 = global$5.process;
var setTask = global$5.setImmediate;
var clearTask = global$5.clearImmediate;
-var MessageChannel = global$5.MessageChannel;
+var MessageChannel$1 = global$5.MessageChannel;
var Dispatch = global$5.Dispatch;
var counter = 0;
var queue = {};
@@ -1148,8 +1148,8 @@ if (!setTask || !clearTask) {
Dispatch.now(ctx$2(run$1, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
- } else if (MessageChannel) {
- channel = new MessageChannel();
+ } else if (MessageChannel$1) {
+ channel = new MessageChannel$1();
port = channel.port2;
channel.port1.onmessage = listener;
defer = ctx$2(port.postMessage, port, 1);
@@ -1212,8 +1212,8 @@ var _microtask = function () {
notify = function () {
process$3.nextTick(flush);
};
- // browsers with MutationObserver
- } else if (Observer) {
+ // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339
+ } else if (Observer && !(global$6.navigator && global$6.navigator.standalone)) {
var toggle = true;
var node = document.createTextNode('');
new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new
@@ -1442,14 +1442,7 @@ var onUnhandled = function (promise) {
});
};
var isUnhandled = function (promise) {
- if (promise._h == 1) { return false; }
- var chain = promise._a || promise._c;
- var i = 0;
- var reaction;
- while (chain.length > i) {
- reaction = chain[i++];
- if (reaction.fail || !isUnhandled(reaction.promise)) { return false; }
- } return true;
+ return promise._h !== 1 && (promise._a || promise._c).length === 0;
};
var onHandleUnhandled = function (promise) {
task.call(global$4, function () {
@@ -2019,6 +2012,23 @@ function base64ToBuffer (base64) {
return array.buffer
}
+/**
+ * Detect if the param is falsy or empty
+ * @param {any} any
+ */
+function isEmpty$1 (any) {
+ if (!any || typeof any !== 'object') {
+ return true
+ }
+
+ for (var key in any) {
+ if (Object.prototype.hasOwnProperty.call(any, key)) {
+ return false
+ }
+ }
+ return true
+}
+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -2128,6 +2138,10 @@ function decodePrimitive (data) {
* under the License.
*/
+function getHookKey (componentId, type, hookName) {
+ return (type + "@" + hookName + "#" + componentId)
+}
+
/**
* For general callback management of a certain Weex instance.
* Because function can not passed into native, so we create callback
@@ -2136,9 +2150,10 @@ function decodePrimitive (data) {
* callback through the callback id we have passed before.
*/
var CallbackManager = function CallbackManager (instanceId) {
- this.instanceId = instanceId;
+ this.instanceId = String(instanceId);
this.lastCallbackId = 0;
this.callbacks = {};
+ this.hooks = {};
};
CallbackManager.prototype.add = function add (callback) {
this.lastCallbackId++;
@@ -2150,6 +2165,33 @@ CallbackManager.prototype.remove = function remove (callbackId) {
delete this.callbacks[callbackId];
return callback
};
+CallbackManager.prototype.registerHook = function registerHook (componentId, type, hookName, hookFunction) {
+ // TODO: validate arguments
+ var key = getHookKey(componentId, type, hookName);
+ if (this.hooks[key]) {
+ console.warn(("[JS Framework] Override an existing component hook \"" + key + "\"."));
+ }
+ this.hooks[key] = hookFunction;
+};
+CallbackManager.prototype.triggerHook = function triggerHook (componentId, type, hookName, options) {
+ if ( options === void 0 ) options = {};
+
+ // TODO: validate arguments
+ var key = getHookKey(componentId, type, hookName);
+ var hookFunction = this.hooks[key];
+ if (typeof hookFunction !== 'function') {
+ console.error(("[JS Framework] Invalid hook function type (" + (typeof hookFunction) + ") on \"" + key + "\"."));
+ return null
+ }
+ var result = null;
+ try {
+ result = hookFunction.apply(null, options.args || []);
+ }
+ catch (e) {
+ console.error(("[JS Framework] Failed to execute the hook function on \"" + key + "\"."));
+ }
+ return result
+};
CallbackManager.prototype.consume = function consume (callbackId, data, ifKeepAlive) {
var callback = this.callbacks[callbackId];
if (typeof ifKeepAlive === 'undefined' || ifKeepAlive === false) {
@@ -2162,6 +2204,7 @@ CallbackManager.prototype.consume = function consume (callbackId, data, ifKeepAl
};
CallbackManager.prototype.close = function close () {
this.callbacks = {};
+ this.hooks = {};
};
/*
@@ -2282,15 +2325,9 @@ function appendBody (doc, node, before) {
function sendBody (doc, node) {
var body = node.toJSON();
- var children = body.children;
- delete body.children;
- var result = doc.taskCenter.send('dom', { action: 'createBody' }, [body]);
- if (children) {
- children.forEach(function (child) {
- result = doc.taskCenter.send('dom', { action: 'addElement' }, [body.ref, child, -1]);
- });
+ if (doc && doc.taskCenter && typeof doc.taskCenter.send === 'function') {
+ doc.taskCenter.send('dom', { action: 'createBody' }, [body]);
}
- return result
}
/**
@@ -2586,74 +2623,6 @@ function getWeexElement (type) {
* under the License.
*/
-// match the binding delimiter
-var delimiterRE = /\[\[((?:.|\n)+?)\]\]/g;
-
-function generateBinding (text) {
- if (typof(text) === 'String') {
- return { '@binding': text }
- }
- return text
-}
-
-function parseString (string) {
- var tokens = [];
- var lastIndex = delimiterRE.lastIndex = 0;
- var match, index;
- while ((match = delimiterRE.exec(string))) {
- index = match.index;
- if (index > lastIndex) {
- tokens.push(string.slice(lastIndex, index));
- }
- var binding = generateBinding(match[1].trim());
- tokens.push(binding);
- lastIndex = index + match[0].length;
- }
- if (lastIndex < string.length) {
- tokens.push(string.slice(lastIndex));
- }
- if (tokens.length === 1) {
- return tokens[0]
- }
- return tokens
-}
-
-function filterDirective (value) {
- if (typof(value) === 'String' && delimiterRE.test(value)) {
- return parseString(value)
- }
- if (typof(value) === 'Object') {
- var realData = {};
- for (var key in value) {
- realData[key] = filterDirective(value[key]);
- }
- return realData
- }
- if (typof(value) === 'Array') {
- return value.map(filterDirective)
- }
- return value
-}
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
var DEFAULT_TAG_NAME = 'div';
var BUBBLE_EVENTS = [
'click', 'longpress', 'touchstart', 'touchmove', 'touchend',
@@ -2917,7 +2886,7 @@ var Element = (function (Node$$1) {
var taskCenter = getTaskCenter(this.docId);
if (!silent && taskCenter) {
var result = {};
- result[key] = filterDirective(value);
+ result[key] = value;
taskCenter.send(
'dom',
{ action: 'updateAttrs' },
@@ -2927,6 +2896,34 @@ var Element = (function (Node$$1) {
};
/**
+ * Set batched attributes.
+ * @param {object} batchedAttrs
+ * @param {boolean} silent
+ */
+ Element.prototype.setAttrs = function setAttrs (batchedAttrs, silent) {
+ var this$1 = this;
+
+ if (isEmpty$1(batchedAttrs)) { return }
+ var mutations = {};
+ for (var key in batchedAttrs) {
+ if (this$1.attr[key] !== batchedAttrs[key]) {
+ this$1.attr[key] = batchedAttrs[key];
+ mutations[key] = batchedAttrs[key];
+ }
+ }
+ if (!isEmpty$1(mutations)) {
+ var taskCenter = getTaskCenter(this.docId);
+ if (!silent && taskCenter) {
+ taskCenter.send(
+ 'dom',
+ { action: 'updateAttrs' },
+ [this.ref, mutations]
+ );
+ }
+ }
+ };
+
+ /**
* Set a style property, and decide whether the task should be send to native.
* @param {string} key
* @param {string | number} value
@@ -2950,6 +2947,34 @@ var Element = (function (Node$$1) {
};
/**
+ * Set batched style properties.
+ * @param {object} batchedStyles
+ * @param {boolean} silent
+ */
+ Element.prototype.setStyles = function setStyles (batchedStyles, silent) {
+ var this$1 = this;
+
+ if (isEmpty$1(batchedStyles)) { return }
+ var mutations = {};
+ for (var key in batchedStyles) {
+ if (this$1.style[key] !== batchedStyles[key]) {
+ this$1.style[key] = batchedStyles[key];
+ mutations[key] = batchedStyles[key];
+ }
+ }
+ if (!isEmpty$1(mutations)) {
+ var taskCenter = getTaskCenter(this.docId);
+ if (!silent && taskCenter) {
+ taskCenter.send(
+ 'dom',
+ { action: 'updateStyle' },
+ [this.ref, mutations]
+ );
+ }
+ }
+ };
+
+ /**
* Set style properties from class.
* @param {object} classStyle
*/
@@ -3039,7 +3064,7 @@ var Element = (function (Node$$1) {
if (!isStopPropagation
&& isBubble
- && BUBBLE_EVENTS.includes(type)
+ && (BUBBLE_EVENTS.indexOf(type) !== -1)
&& this.parentNode
&& this.parentNode.fireEvent) {
event.currentTarget = this.parentNode;
@@ -3067,7 +3092,7 @@ var Element = (function (Node$$1) {
var result = {
ref: this.ref.toString(),
type: this.type,
- attr: filterDirective(this.attr),
+ attr: this.attr,
style: this.toStyle()
};
var event = [];
@@ -3132,7 +3157,7 @@ var fallback = function () {};
var TaskCenter = function TaskCenter (id, sendTasks) {
Object.defineProperty(this, 'instanceId', {
enumerable: true,
- value: id
+ value: String(id)
});
Object.defineProperty(this, 'callbackManager', {
enumerable: true,
@@ -3145,6 +3170,29 @@ TaskCenter.prototype.callback = function callback (callbackId, data, ifKeepAlive
return this.callbackManager.consume(callbackId, data, ifKeepAlive)
};
+TaskCenter.prototype.registerHook = function registerHook () {
+ var args = [], len = arguments.length;
+ while ( len-- ) args[ len ] = arguments[ len ];
+
+ return (ref = this.callbackManager).registerHook.apply(ref, args)
+ var ref;
+};
+
+TaskCenter.prototype.triggerHook = function triggerHook () {
+ var args = [], len = arguments.length;
+ while ( len-- ) args[ len ] = arguments[ len ];
+
+ return (ref = this.callbackManager).triggerHook.apply(ref, args)
+ var ref;
+};
+
+TaskCenter.prototype.updateData = function updateData (componentId, newData, callback) {
+ this.send('module', {
+ module: 'dom',
+ method: 'updateComponentData'
+ }, [componentId, newData, callback]);
+};
+
TaskCenter.prototype.destroyCallback = function destroyCallback () {
return this.callbackManager.close()
};
@@ -3256,6 +3304,185 @@ function init$2 () {
* under the License.
*/
+function fireEvent$1 (document, nodeId, type, event, domChanges, params) {
+ var el = document.getRef(nodeId);
+ if (el) {
+ return document.fireEvent(el, type, event, domChanges, params)
+ }
+ return new Error(("invalid element reference \"" + nodeId + "\""))
+}
+
+function callback$1 (document, callbackId, data, ifKeepAlive) {
+ return document.taskCenter.callback(callbackId, data, ifKeepAlive)
+}
+
+function componentHook (document, componentId, type, hook, options) {
+ if (!document || !document.taskCenter) {
+ console.error("[JS Framework] Can't find \"document\" or \"taskCenter\".");
+ return null
+ }
+ var result = null;
+ try {
+ result = document.taskCenter.triggerHook(componentId, type, hook, options);
+ }
+ catch (e) {
+ console.error(("[JS Framework] Failed to trigger the \"" + type + "@" + hook + "\" hook on " + componentId + "."));
+ }
+ return result
+}
+
+/**
+ * Accept calls from native (event or callback).
+ *
+ * @param {string} id
+ * @param {array} tasks list with `method` and `args`
+ */
+function receiveTasks (id, tasks) {
+ var document = getDoc(id);
+ if (!document) {
+ return new Error("[JS Framework] Failed to receiveTasks, "
+ + "instance (" + id + ") is not available.")
+ }
+ if (Array.isArray(tasks)) {
+ return tasks.map(function (task) {
+ switch (task.method) {
+ case 'callback': return callback$1.apply(void 0, [ document ].concat( task.args ))
+ case 'fireEventSync':
+ case 'fireEvent': return fireEvent$1.apply(void 0, [ document ].concat( task.args ))
+ case 'componentHook': return componentHook.apply(void 0, [ document ].concat( task.args ))
+ }
+ })
+ }
+}
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+var weexModules = {};
+
+/**
+ * Register native modules information.
+ * @param {object} newModules
+ */
+function registerModules (newModules) {
+ var loop = function ( name ) {
+ if (!weexModules[name]) {
+ weexModules[name] = {};
+ }
+ newModules[name].forEach(function (method) {
+ if (typeof method === 'string') {
+ weexModules[name][method] = true;
+ }
+ else {
+ weexModules[name][method.name] = method.args;
+ }
+ });
+ };
+
+ for (var name in newModules) loop( name );
+}
+
+/**
+ * Check whether the module or the method has been registered.
+ * @param {String} module name
+ * @param {String} method name (optional)
+ */
+function isRegisteredModule (name, method) {
+ if (typeof method === 'string') {
+ return !!(weexModules[name] && weexModules[name][method])
+ }
+ return !!weexModules[name]
+}
+
+function getModuleDescription (name) {
+ return weexModules[name]
+}
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+var weexComponents = {};
+
+/**
+ * Register native components information.
+ * @param {array} newComponents
+ */
+function registerComponents (newComponents) {
+ if (Array.isArray(newComponents)) {
+ newComponents.forEach(function (component) {
+ if (!component) {
+ return
+ }
+ if (typeof component === 'string') {
+ weexComponents[component] = true;
+ }
+ else if (typeof component === 'object' && typeof component.type === 'string') {
+ weexComponents[component.type] = component;
+ registerElement(component.type, component.methods);
+ }
+ });
+ }
+}
+
+/**
+ * Check whether the component has been registered.
+ * @param {String} component name
+ */
+function isRegisteredComponent (name) {
+ return !!weexComponents[name]
+}
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
// JS Services
var services = [];
@@ -3334,223 +3561,30 @@ function indexOf (name) {
* under the License.
*/
-var frameworks;
-var runtimeConfig;
-
-var versionRegExp = /^\s*\/\/ *(\{[^}]*\}) *\r?\n/;
-
-/**
- * Detect a JS Bundle code and make sure which framework it's based to. Each JS
- * Bundle should make sure that it starts with a line of JSON comment and is
- * more that one line.
- * @param {string} code
- * @return {object}
- */
-function getBundleType (code) {
- var result = versionRegExp.exec(code);
- if (result) {
- try {
- var info = JSON.parse(result[1]);
- return info.framework
- }
- catch (e) {}
- }
-
- // default bundle type
- return 'Weex'
-}
-
-function createServices (id, env, config) {
- // Init JavaScript services for this instance.
- var serviceMap = Object.create(null);
- serviceMap.service = Object.create(null);
- services.forEach(function (ref) {
- var name = ref.name;
- var options = ref.options;
-
- {
- console.debug(("[JS Runtime] create service " + name + "."));
- }
- var create = options.create;
- if (create) {
- var result = create(id, env, config);
- Object.assign(serviceMap.service, result);
- Object.assign(serviceMap, result.instance);
- }
- });
- delete serviceMap.service.instance;
- Object.freeze(serviceMap.service);
- return serviceMap
-}
-
-var instanceMap = {};
-
-function getFrameworkType (id) {
- if (instanceMap[id]) {
- return instanceMap[id].framework
- }
-}
-
-/**
- * Check which framework a certain JS Bundle code based to. And create instance
- * by this framework.
- * @param {string} id
- * @param {string} code
- * @param {object} config
- * @param {object} data
- */
-function createInstance (id, code, config, data) {
- if (instanceMap[id]) {
- return new Error(("invalid instance id \"" + id + "\""))
- }
-
- // Init instance info.
- var bundleType = getBundleType(code);
-
- // Init instance config.
- config = JSON.parse(JSON.stringify(config || {}));
- config.env = JSON.parse(JSON.stringify(global.WXEnvironment || {}));
-
- var context = {
- config: config,
- created: Date.now(),
- framework: bundleType
- };
- context.services = createServices(id, context, runtimeConfig);
- instanceMap[id] = context;
-
- {
- console.debug(("[JS Framework] create an " + bundleType + " instance"));
+function track (id, type, value) {
+ var taskCenter = getTaskCenter(id);
+ if (!taskCenter || typeof taskCenter.send !== 'function') {
+ console.error("[JS Framework] Failed to create tracker!");
+ return
}
-
- var fm = frameworks[bundleType];
- if (!fm) {
- return new Error(("invalid bundle type \"" + bundleType + "\"."))
+ if (!type || !value) {
+ console.warn(("[JS Framework] Invalid track type (" + type + ") or value (" + value + ")"));
+ return
}
-
- return fm.createInstance(id, code, config, data, context)
-}
-
-var methods = {
- createInstance: createInstance,
- registerService: register$1,
- unregisterService: unregister
-};
-
-/**
- * Register methods which init each frameworks.
- * @param {string} methodName
- */
-function genInit (methodName) {
- methods[methodName] = function () {
- var args = [], len = arguments.length;
- while ( len-- ) args[ len ] = arguments[ len ];
-
- if (methodName === 'registerComponents') {
- checkComponentMethods(args[0]);
- }
- for (var name in frameworks) {
- var framework = frameworks[name];
- if (framework && framework[methodName]) {
- framework[methodName].apply(framework, args);
- }
+ var label = "jsfm." + type + "." + value;
+ try {
+ if (isRegisteredModule('userTrack', 'addPerfPoint')) {
+ var message = Object.create(null);
+ message[label] = '4';
+ taskCenter.send('module', {
+ module: 'userTrack',
+ method: 'addPerfPoint'
+ }, [message]);
}
- };
-}
-
-function checkComponentMethods (components) {
- if (Array.isArray(components)) {
- components.forEach(function (name) {
- if (name && name.type && name.methods) {
- registerElement(name.type, name.methods);
- }
- });
}
-}
-
-/**
- * Register methods which will be called for each instance.
- * @param {string} methodName
- */
-function genInstance (methodName) {
- methods[methodName] = function () {
- var args = [], len = arguments.length;
- while ( len-- ) args[ len ] = arguments[ len ];
-
- var id = args[0];
- var type = getFrameworkType(id);
- if (type && frameworks[type]) {
- var result = (ref = frameworks[type])[methodName].apply(ref, args);
- var info = { framework: type };
-
- // Lifecycle methods
- if (methodName === 'refreshInstance') {
- services.forEach(function (service) {
- var refresh = service.options.refresh;
- if (refresh) {
- refresh(id, { info: info, runtime: runtimeConfig });
- }
- });
- }
- else if (methodName === 'destroyInstance') {
- services.forEach(function (service) {
- var destroy = service.options.destroy;
- if (destroy) {
- destroy(id, { info: info, runtime: runtimeConfig });
- }
- });
- delete instanceMap[id];
- }
-
- return result
- }
- return new Error(("invalid instance id \"" + id + "\""))
- var ref;
- };
-}
-
-/**
- * Adapt some legacy method(s) which will be called for each instance. These
- * methods should be deprecated and removed later.
- * @param {string} methodName
- * @param {string} nativeMethodName
- */
-function adaptInstance (methodName, nativeMethodName) {
- methods[nativeMethodName] = function () {
- var args = [], len = arguments.length;
- while ( len-- ) args[ len ] = arguments[ len ];
-
- var id = args[0];
- var type = getFrameworkType(id);
- if (type && frameworks[type]) {
- return (ref = frameworks[type])[methodName].apply(ref, args)
- }
- return new Error(("invalid instance id \"" + id + "\""))
- var ref;
- };
-}
-
-function init$1 (config) {
- runtimeConfig = config || {};
- frameworks = runtimeConfig.frameworks || {};
- init$2();
-
- // Init each framework by `init` method and `config` which contains three
- // virtual-DOM Class: `Document`, `Element` & `Comment`, and a JS bridge method:
- // `sendTasks(...args)`.
- for (var name in frameworks) {
- var framework = frameworks[name];
- framework.init(config);
+ catch (err) {
+ console.error(("[JS Framework] Failed to trace \"" + label + "\"!"));
}
-
- // @todo: The method `registerMethods` will be re-designed or removed later.
- ['registerComponents', 'registerModules', 'registerMethods'].forEach(genInit)
-
- ; ['destroyInstance', 'refreshInstance', 'receiveTasks', 'getRoot'].forEach(genInstance);
-
- adaptInstance('receiveTasks', 'callJS');
-
- return methods
}
/*
@@ -4078,7 +4112,7 @@ Document.prototype.fireEvent = function fireEvent (el, type, event, domChanges,
return
}
event = event || {};
- event.type = type;
+ event.type = event.type || type;
event.target = el;
event.currentTarget = el;
event.timestamp = Date.now();
@@ -4122,40 +4156,119 @@ Document.handler = null;
* under the License.
*/
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
+var moduleProxies = {};
-var config = {
- Document: Document, Element: Element, Comment: Comment, Listener: Listener,
- TaskCenter: TaskCenter,
- sendTasks: function sendTasks () {
+function setId (weex, id) {
+ Object.defineProperty(weex, '[[CurrentInstanceId]]', { value: id });
+}
+
+function getId (weex) {
+ return weex['[[CurrentInstanceId]]']
+}
+
+function moduleGetter$1 (id, module, method) {
+ var taskCenter = getTaskCenter(id);
+ if (!taskCenter || typeof taskCenter.send !== 'function') {
+ console.error(("[JS Framework] Failed to find taskCenter (" + id + ")."));
+ return null
+ }
+ return function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
- if (typeof callNative === 'function') {
- return callNative.apply(void 0, args)
+ return taskCenter.send('module', { module: module, method: method }, args);
+ }
+}
+
+function moduleSetter$1 (id, module, method, fn) {
+ var taskCenter = getTaskCenter(id);
+ if (!taskCenter || typeof taskCenter.send !== 'function') {
+ console.error(("[JS Framework] Failed to find taskCenter (" + id + ")."));
+ return null
+ }
+ if (typeof fn !== 'function') {
+ console.error(("[JS Framework] " + module + "." + method + " must be assigned as a function."));
+ return null
+ }
+ return function (fn) { return taskCenter.send('module', { module: module, method: method }, [fn]); }
+}
+
+var WeexInstance = function WeexInstance (id, config) {
+ setId(this, String(id));
+ this.config = config || {};
+ this.document = new Document(id, this.config.bundleUrl);
+ this.requireModule = this.requireModule.bind(this);
+ this.isRegisteredModule = isRegisteredModule;
+ this.isRegisteredComponent = isRegisteredComponent;
+};
+
+WeexInstance.prototype.requireModule = function requireModule (moduleName) {
+ var id = getId(this);
+ if (!(id && this.document && this.document.taskCenter)) {
+ console.error("[JS Framework] Failed to requireModule(\"" + moduleName + "\"), "
+ + "instance (" + id + ") doesn't exist anymore.");
+ return
+ }
+
+ // warn for unknown module
+ if (!isRegisteredModule(moduleName)) {
+ console.warn(("[JS Framework] using unregistered weex module \"" + moduleName + "\""));
+ return
+ }
+
+ // create new module proxy
+ var proxyName = moduleName + "#" + id;
+ if (!moduleProxies[proxyName]) {
+ // create registered module apis
+ var moduleDefine = getModuleDescription(moduleName);
+ var moduleApis = {};
+ var loop = function ( methodName ) {
+ Object.defineProperty(moduleApis, methodName, {
+ enumerable: true,
+ configurable: true,
+ get: function () { return moduleGetter$1(id, moduleName, methodName); },
+ set: function (fn) { return moduleSetter$1(id, moduleName, methodName, fn); }
+ });
+ };
+
+ for (var methodName in moduleDefine) loop( methodName );
+
+ // create module Proxy
+ if (typeof Proxy === 'function') {
+ moduleProxies[proxyName] = new Proxy(moduleApis, {
+ get: function get (target, methodName) {
+ if (methodName in target) {
+ return target[methodName]
+ }
+ console.warn(("[JS Framework] using unregistered method \"" + moduleName + "." + methodName + "\""));
+ return moduleGetter$1(id, moduleName, methodName)
+ }
+ });
+ }
+ else {
+ moduleProxies[proxyName] = moduleApis;
}
- return (global.callNative || (function () {})).apply(void 0, args)
}
+
+ return moduleProxies[proxyName]
};
-Document.handler = config.sendTasks;
+WeexInstance.prototype.supports = function supports (condition) {
+ if (typeof condition !== 'string') { return null }
+
+ var res = condition.match(/^@(\w+)\/(\w+)(\.(\w+))?$/i);
+ if (res) {
+ var type = res[1];
+ var name = res[2];
+ var method = res[4];
+ switch (type) {
+ case 'module': return isRegisteredModule(name, method)
+ case 'component': return isRegisteredComponent(name)
+ }
+ }
+
+ return null
+};
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -4176,37 +4289,291 @@ Document.handler = config.sendTasks;
* under the License.
*/
-/**
- * @fileOverview
- * Register framework(s) in JS runtime. Weex supply two layers for 3rd-party
- * framework(s): one is the instance management layer, another is the
- * virtual-DOM layer.
+var frameworks;
+var runtimeConfig;
+
+var versionRegExp = /^\s*\/\/ *(\{[^}]*\}) *\r?\n/;
+
+/**
+ * Detect a JS Bundle code and make sure which framework it's based to. Each JS
+ * Bundle should make sure that it starts with a line of JSON comment and is
+ * more that one line.
+ * @param {string} code
+ * @return {object}
*/
+function getBundleType (code) {
+ var result = versionRegExp.exec(code);
+ if (result) {
+ try {
+ var info = JSON.parse(result[1]);
+ return info.framework
+ }
+ catch (e) {}
+ }
-/* istanbul ignore next */
-function freezePrototype$$1 () {
- freezePrototype$1();
+ // default bundle type
+ return 'Weex'
+}
- // Object.freeze(config.Element)
- Object.freeze(config.Comment);
- Object.freeze(config.Listener);
- Object.freeze(config.Document.prototype);
- // Object.freeze(config.Element.prototype)
- Object.freeze(config.Comment.prototype);
- Object.freeze(config.Listener.prototype);
+function createServices (id, env, config) {
+ // Init JavaScript services for this instance.
+ var serviceMap = Object.create(null);
+ serviceMap.service = Object.create(null);
+ services.forEach(function (ref) {
+ var name = ref.name;
+ var options = ref.options;
+
+ {
+ console.debug(("[JS Runtime] create service " + name + "."));
+ }
+ var create = options.create;
+ if (create) {
+ var result = create(id, env, config);
+ Object.assign(serviceMap.service, result);
+ Object.assign(serviceMap, result.instance);
+ }
+ });
+ delete serviceMap.service.instance;
+ Object.freeze(serviceMap.service);
+ return serviceMap
}
-var runtime = {
- setNativeConsole: setNativeConsole,
- resetNativeConsole: resetNativeConsole,
- setNativeTimer: setNativeTimer,
- resetNativeTimer: resetNativeTimer,
- service: { register: register$1, unregister: unregister, has: has$5 },
- freezePrototype: freezePrototype$$1,
- init: init$1,
- config: config
+var instanceTypeMap = {};
+function getFrameworkType (id) {
+ return instanceTypeMap[id]
+}
+
+function createInstanceContext (id, options, data) {
+ if ( options === void 0 ) options = {};
+
+ var weex = new WeexInstance(id, options);
+ Object.freeze(weex);
+
+ var bundleType = options.bundleType || 'Vue';
+ instanceTypeMap[id] = bundleType;
+ var framework = runtimeConfig.frameworks[bundleType];
+ if (!framework) {
+ return new Error(("[JS Framework] Invalid bundle type \"" + bundleType + "\"."))
+ }
+ track(id, 'bundleType', bundleType);
+
+ // prepare js service
+ var services$$1 = createServices(id, { weex: weex, bundleType: bundleType }, runtimeConfig);
+ Object.freeze(services$$1);
+
+ // prepare runtime context
+ var runtimeContext = Object.create(null);
+ Object.assign(runtimeContext, services$$1, {
+ weex: weex,
+ services: services$$1 // Temporary compatible with some legacy APIs in Rax
+ });
+ Object.freeze(runtimeContext);
+
+ // prepare instance context
+ var instanceContext = Object.create(runtimeContext);
+ if (typeof framework.createInstanceContext === 'function') {
+ Object.assign(instanceContext, framework.createInstanceContext(id, runtimeContext, data));
+ }
+ Object.freeze(instanceContext);
+ return instanceContext
+}
+
+/**
+ * Check which framework a certain JS Bundle code based to. And create instance
+ * by this framework.
+ * @param {string} id
+ * @param {string} code
+ * @param {object} config
+ * @param {object} data
+ */
+function createInstance (id, code, config, data) {
+ if (instanceTypeMap[id]) {
+ return new Error(("The instance id \"" + id + "\" has already been used!"))
+ }
+
+ // Init instance info.
+ var bundleType = getBundleType(code);
+ instanceTypeMap[id] = bundleType;
+
+ // Init instance config.
+ config = JSON.parse(JSON.stringify(config || {}));
+ config.env = JSON.parse(JSON.stringify(global.WXEnvironment || {}));
+ config.bundleType = bundleType;
+
+ var framework = runtimeConfig.frameworks[bundleType];
+ if (!framework) {
+ return new Error(("[JS Framework] Invalid bundle type \"" + bundleType + "\"."))
+ }
+ if (bundleType === 'Weex') {
+ console.error("[JS Framework] COMPATIBILITY WARNING: "
+ + "Weex DSL 1.0 (.we) framework is no longer supported! "
+ + "It will be removed in the next version of WeexSDK, "
+ + "your page would be crash if you still using the \".we\" framework. "
+ + "Please upgrade it to Vue.js or Rax.");
+ }
+
+ var instanceContext = createInstanceContext(id, config, data);
+ if (typeof framework.createInstance === 'function') {
+ // Temporary compatible with some legacy APIs in Rax,
+ // some Rax page is using the legacy ".we" framework.
+ if (bundleType === 'Rax' || bundleType === 'Weex') {
+ var raxInstanceContext = Object.assign({
+ config: config,
+ created: Date.now(),
+ framework: bundleType
+ }, instanceContext);
+ return framework.createInstance(id, code, config, data, raxInstanceContext)
+ }
+ return framework.createInstance(id, code, config, data, instanceContext)
+ }
+ // console.error(`[JS Framework] Can't find available "createInstance" method in ${bundleType}!`)
+ runInContext(code, instanceContext);
+}
+
+/**
+ * Run js code in a specific context.
+ * @param {string} code
+ * @param {object} context
+ */
+function runInContext (code, context) {
+ var keys = [];
+ var args = [];
+ for (var key in context) {
+ keys.push(key);
+ args.push(context[key]);
+ }
+
+ var bundle = "\n (function (global) {\n " + code + "\n })(Object.create(this))\n ";
+
+ return (new (Function.prototype.bind.apply( Function, [ null ].concat( keys, [bundle]) ))).apply(void 0, args)
+}
+
+/**
+ * Get the JSON object of the root element.
+ * @param {string} instanceId
+ */
+function getRoot (instanceId) {
+ var document = getDoc(instanceId);
+ try {
+ if (document && document.body) {
+ return document.body.toJSON()
+ }
+ }
+ catch (e) {
+ console.error("[JS Framework] Failed to get the virtual dom tree.");
+ return
+ }
+}
+
+var methods = {
+ createInstance: createInstance,
+ createInstanceContext: createInstanceContext,
+ getRoot: getRoot,
+ getDocument: getDoc,
+ registerService: register$1,
+ unregisterService: unregister,
+ callJS: function callJS (id, tasks) {
+ var framework = frameworks[getFrameworkType(id)];
+ if (framework && typeof framework.receiveTasks === 'function') {
+ return framework.receiveTasks(id, tasks)
+ }
+ return receiveTasks(id, tasks)
+ }
};
+/**
+ * Register methods which will be called for each instance.
+ * @param {string} methodName
+ */
+function genInstance (methodName) {
+ methods[methodName] = function () {
+ var args = [], len = arguments.length;
+ while ( len-- ) args[ len ] = arguments[ len ];
+
+ var id = args[0];
+ var type = getFrameworkType(id);
+ if (type && frameworks[type]) {
+ var result = (ref = frameworks[type])[methodName].apply(ref, args);
+ var info = { framework: type };
+
+ // Lifecycle methods
+ if (methodName === 'refreshInstance') {
+ services.forEach(function (service) {
+ var refresh = service.options.refresh;
+ if (refresh) {
+ refresh(id, { info: info, runtime: runtimeConfig });
+ }
+ });
+ }
+ else if (methodName === 'destroyInstance') {
+ services.forEach(function (service) {
+ var destroy = service.options.destroy;
+ if (destroy) {
+ destroy(id, { info: info, runtime: runtimeConfig });
+ }
+ });
+ delete instanceTypeMap[id];
+ }
+
+ return result
+ }
+ return new Error("[JS Framework] Using invalid instance id "
+ + "\"" + id + "\" when calling " + methodName + ".")
+ var ref;
+ };
+}
+
+/**
+ * Register methods which init each frameworks.
+ * @param {string} methodName
+ * @param {function} sharedMethod
+ */
+function adaptMethod (methodName, sharedMethod) {
+ methods[methodName] = function () {
+ var args = [], len = arguments.length;
+ while ( len-- ) args[ len ] = arguments[ len ];
+
+ if (typeof sharedMethod === 'function') {
+ sharedMethod.apply(void 0, args);
+ }
+
+ // TODO: deprecated
+ for (var name in runtimeConfig.frameworks) {
+ var framework = runtimeConfig.frameworks[name];
+ if (framework && framework[methodName]) {
+ framework[methodName].apply(framework, args);
+ }
+ }
+ };
+}
+
+function init$1 (config) {
+ runtimeConfig = config || {};
+ frameworks = runtimeConfig.frameworks || {};
+ init$2();
+
+ // Init each framework by `init` method and `config` which contains three
+ // virtual-DOM Class: `Document`, `Element` & `Comment`, and a JS bridge method:
+ // `sendTasks(...args)`.
+ for (var name in frameworks) {
+ var framework = frameworks[name];
+ if (typeof framework.init === 'function') {
+ try {
+ framework.init(config);
+ }
+ catch (e) {}
+ }
+ }
+
+ adaptMethod('registerComponents', registerComponents);
+ adaptMethod('registerModules', registerModules);
+ adaptMethod('registerMethods')
+
+ ; ['destroyInstance', 'refreshInstance'].forEach(genInstance);
+
+ return methods
+}
+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -4226,30 +4593,6 @@ var runtime = {
* under the License.
*/
-/**
- * Mock MessageEvent type
- * @param {string} type
- * @param {object} dict { data, origin, source, ports }
- *
- * This type has been simplified.
- * https://html.spec.whatwg.org/multipage/comms.html#messageevent
- * https://dom.spec.whatwg.org/#interface-event
- */
-function MessageEvent (type, dict) {
- if ( dict === void 0 ) dict = {};
-
- this.type = type || 'message';
-
- this.data = dict.data || null;
- this.origin = dict.origin || '';
- this.source = dict.source || null;
- this.ports = dict.ports || [];
-
- // inherit properties
- this.target = null;
- this.timeStamp = Date.now();
-}
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -4269,18 +4612,146 @@ function MessageEvent (type, dict) {
* under the License.
*/
-/**
- * @fileOverview
- * The polyfill of BroadcastChannel API.
- * This api can be used to achieve inter-instance communications.
- *
- * https://html.spec.whatwg.org/multipage/comms.html#broadcasting-to-other-browsing-contexts
- */
+var config = {
+ Document: Document, Element: Element, Comment: Comment, Listener: Listener,
+ TaskCenter: TaskCenter,
+ sendTasks: function sendTasks () {
+ var args = [], len = arguments.length;
+ while ( len-- ) args[ len ] = arguments[ len ];
-var channels = {};
-var instances = {};
+ if (typeof callNative === 'function') {
+ return callNative.apply(void 0, args)
+ }
+ return (global.callNative || (function () {})).apply(void 0, args)
+ }
+};
-/**
+Document.handler = config.sendTasks;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * @fileOverview
+ * Register framework(s) in JS runtime. Weex supply two layers for 3rd-party
+ * framework(s): one is the instance management layer, another is the
+ * virtual-DOM layer.
+ */
+
+/* istanbul ignore next */
+function freezePrototype$$1 () {
+ freezePrototype$1();
+
+ // Object.freeze(config.Element)
+ Object.freeze(config.Comment);
+ Object.freeze(config.Listener);
+ Object.freeze(config.Document.prototype);
+ // Object.freeze(config.Element.prototype)
+ Object.freeze(config.Comment.prototype);
+ Object.freeze(config.Listener.prototype);
+}
+
+var runtime = {
+ setNativeConsole: setNativeConsole,
+ resetNativeConsole: resetNativeConsole,
+ setNativeTimer: setNativeTimer,
+ resetNativeTimer: resetNativeTimer,
+ service: { register: register$1, unregister: unregister, has: has$5 },
+ freezePrototype: freezePrototype$$1,
+ init: init$1,
+ config: config
+};
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * Mock MessageEvent type
+ * @param {string} type
+ * @param {object} dict { data, origin, source, ports }
+ *
+ * This type has been simplified.
+ * https://html.spec.whatwg.org/multipage/comms.html#messageevent
+ * https://dom.spec.whatwg.org/#interface-event
+ */
+function MessageEvent (type, dict) {
+ if ( dict === void 0 ) dict = {};
+
+ this.type = type || 'message';
+
+ this.data = dict.data || null;
+ this.origin = dict.origin || '';
+ this.source = dict.source || null;
+ this.ports = dict.ports || [];
+
+ // inherit properties
+ this.target = null;
+ this.timeStamp = Date.now();
+}
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * @fileOverview
+ * The polyfill of BroadcastChannel API.
+ * This api can be used to achieve inter-instance communications.
+ *
+ * https://html.spec.whatwg.org/multipage/comms.html#broadcasting-to-other-browsing-contexts
+ */
+
+var channels = {};
+var instances = {};
+
+/**
* An empty constructor for BroadcastChannel polyfill.
* The real constructor will be defined when a Weex instance created because
* we need to track the channel by Weex instance id.
@@ -4482,7 +4953,7 @@ var setup = function (frameworks) {
*/
var config$2 = {};
-var instanceMap$1 = {};
+var instanceMap = {};
function init$3 (cfg) {
config$2.Document = cfg.Document;
@@ -4513,7 +4984,7 @@ function createInstance$1 (id, code, options, data, serviceObjects) {
}
return callback(data)
};
- instanceMap$1[id] = instance;
+ instanceMap[id] = instance;
var globalObjects = Object.assign({
Document: config$2.Document,
@@ -4541,30 +5012,30 @@ function createInstance$1 (id, code, options, data, serviceObjects) {
}
function destroyInstance (id) {
- delete instanceMap$1[id];
+ delete instanceMap[id];
}
-function getRoot (id) {
- return instanceMap$1[id].document.body.toJSON()
+function getRoot$1 (id) {
+ return instanceMap[id].document.body.toJSON()
}
-function receiveTasks (id, tasks) {
+function receiveTasks$1 (id, tasks) {
var jsHandlers = {
fireEvent: function (id, ref, type, data, domChanges) {
- var ref$1 = instanceMap$1[id];
+ var ref$1 = instanceMap[id];
var document = ref$1.document;
var el = document.getRef(ref);
return document.fireEvent(el, type, data, domChanges)
},
callback: function (id, funcId, data, ifLast) {
- var ref = instanceMap$1[id];
+ var ref = instanceMap[id];
var document = ref.document;
return document.handleCallback(funcId, data, ifLast)
}
};
- var ref = instanceMap$1[id] || {};
+ var ref = instanceMap[id] || {};
var document = ref.document;
if (document && Array.isArray(tasks)) {
var results = [];
@@ -4585,17 +5056,19 @@ var Vanilla = Object.freeze({
init: init$3,
createInstance: createInstance$1,
destroyInstance: destroyInstance,
- getRoot: getRoot,
- receiveTasks: receiveTasks
+ getRoot: getRoot$1,
+ receiveTasks: receiveTasks$1
});
var factory = createCommonjsModule(function (module) {
'use strict';
-module.exports = function weexFactory (exports, renderer) {
+module.exports = function weexFactory (exports, document) {
/* */
+var emptyObject = Object.freeze({});
+
// these helpers produces better vm code in JS engines due to their
// explicitness and function inlining
function isUndef (v) {
@@ -4634,8 +5107,15 @@ function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
+/**
+ * Get the raw type string of a value e.g. [object Object]
+ */
var _toString = Object.prototype.toString;
+function toRawType (value) {
+ return _toString.call(value).slice(8, -1)
+}
+
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
@@ -4652,7 +5132,7 @@ function isRegExp (v) {
* Check if val is a valid array index.
*/
function isValidArrayIndex (val) {
- var n = parseFloat(val);
+ var n = parseFloat(String(val));
return n >= 0 && Math.floor(n) === n && isFinite(val)
}
@@ -4702,7 +5182,7 @@ var isBuiltInTag = makeMap('slot,component', true);
/**
* Check if a attribute is a reserved attribute.
*/
-var isReservedAttribute = makeMap('key,ref,slot,is');
+var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is');
/**
* Remove an item from an array
@@ -4908,7 +5388,8 @@ var LIFECYCLE_HOOKS = [
'beforeDestroy',
'destroyed',
'activated',
- 'deactivated'
+ 'deactivated',
+ 'errorCaptured'
];
/* */
@@ -4917,6 +5398,7 @@ var config = ({
/**
* Option merge strategies (used in core/util/options)
*/
+ // $flow-disable-line
optionMergeStrategies: Object.create(null),
/**
@@ -4957,6 +5439,7 @@ var config = ({
/**
* Custom user key aliases for v-on
*/
+ // $flow-disable-line
keyCodes: Object.create(null),
/**
@@ -5001,8 +5484,6 @@ var config = ({
/* */
-var emptyObject = Object.freeze({});
-
/**
* Check if a string starts with $ or _
*/
@@ -5043,9 +5524,99 @@ function parsePath (path) {
/* */
+
+// can we use __proto__?
+var hasProto = '__proto__' in {};
+
+// Browser environment sniffing
+var inBrowser = typeof window !== 'undefined';
+var inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform;
+var weexPlatform = inWeex && WXEnvironment.platform.toLowerCase();
+var UA = inBrowser && window.navigator.userAgent.toLowerCase();
+var isIE = UA && /msie|trident/.test(UA);
+var isIE9 = UA && UA.indexOf('msie 9.0') > 0;
+var isEdge = UA && UA.indexOf('edge/') > 0;
+var isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android');
+var isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios');
+var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
+
+// Firefox has a "watch" function on Object.prototype...
+var nativeWatch = ({}).watch;
+
+
+if (inBrowser) {
+ try {
+ var opts = {};
+ Object.defineProperty(opts, 'passive', ({
+ get: function get () {
+ /* istanbul ignore next */
+
+ }
+ })); // https://github.com/facebook/flow/issues/285
+ window.addEventListener('test-passive', null, opts);
+ } catch (e) {}
+}
+
+// this needs to be lazy-evaled because vue may be required before
+// vue-server-renderer can set VUE_ENV
+var _isServer;
+var isServerRendering = function () {
+ if (_isServer === undefined) {
+ /* istanbul ignore if */
+ if (!inBrowser && typeof commonjsGlobal !== 'undefined') {
+ // detect presence of vue-server-renderer and avoid
+ // Webpack shimming the process
+ _isServer = commonjsGlobal['process'].env.VUE_ENV === 'server';
+ } else {
+ _isServer = false;
+ }
+ }
+ return _isServer
+};
+
+// detect devtools
+var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;
+
+/* istanbul ignore next */
+function isNative (Ctor) {
+ return typeof Ctor === 'function' && /native code/.test(Ctor.toString())
+}
+
+var hasSymbol =
+ typeof Symbol !== 'undefined' && isNative(Symbol) &&
+ typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys);
+
+var _Set;
+/* istanbul ignore if */ // $flow-disable-line
+if (typeof Set !== 'undefined' && isNative(Set)) {
+ // use native Set when available.
+ _Set = Set;
+} else {
+ // a non-standard Set polyfill that only works with primitive keys.
+ _Set = (function () {
+ function Set () {
+ this.set = Object.create(null);
+ }
+ Set.prototype.has = function has (key) {
+ return this.set[key] === true
+ };
+ Set.prototype.add = function add (key) {
+ this.set[key] = true;
+ };
+ Set.prototype.clear = function clear () {
+ this.set = Object.create(null);
+ };
+
+ return Set;
+ }());
+}
+
+/* */
+
var warn = noop;
var tip = noop;
-var formatComponentName = (null); // work around flow check
+var generateComponentTrace = (noop); // work around flow check
+var formatComponentName = (noop);
{
var hasConsole = typeof console !== 'undefined';
@@ -5076,15 +5647,13 @@ var formatComponentName = (null); // work around flow check
if (vm.$root === vm) {
return '<Root>'
}
- var name = typeof vm === 'string'
- ? vm
- : typeof vm === 'function' && vm.options
- ? vm.options.name
- : vm._isVue
- ? vm.$options.name || vm.$options._componentTag
- : vm.name;
-
- var file = vm._isVue && vm.$options.__file;
+ var options = typeof vm === 'function' && vm.cid != null
+ ? vm.options
+ : vm._isVue
+ ? vm.$options || vm.constructor.options
+ : vm || {};
+ var name = options.name || options._componentTag;
+ var file = options.__file;
if (!name && file) {
var match = file.match(/([^/\\]+)\.vue$/);
name = match && match[1];
@@ -5106,7 +5675,7 @@ var formatComponentName = (null); // work around flow check
return res
};
- var generateComponentTrace = function (vm) {
+ generateComponentTrace = function (vm) {
if (vm._isVue && vm.$parent) {
var tree = [];
var currentRecursiveSequence = 0;
@@ -5138,208 +5707,17 @@ var formatComponentName = (null); // work around flow check
/* */
-function handleError (err, vm, info) {
- if (config.errorHandler) {
- config.errorHandler.call(null, err, vm, info);
- } else {
- {
- warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm);
- }
- /* istanbul ignore else */
- if (inBrowser && typeof console !== 'undefined') {
- console.error(err);
- } else {
- throw err
- }
- }
-}
-
-/* */
-/* globals MutationObserver */
-// can we use __proto__?
-var hasProto = '__proto__' in {};
+var uid$1 = 0;
-// Browser environment sniffing
-var inBrowser = typeof window !== 'undefined';
-var UA = inBrowser && window.navigator.userAgent.toLowerCase();
-var isIE = UA && /msie|trident/.test(UA);
-var isIE9 = UA && UA.indexOf('msie 9.0') > 0;
-var isEdge = UA && UA.indexOf('edge/') > 0;
-var isAndroid = UA && UA.indexOf('android') > 0;
-var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA);
-var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
-
-// Firefox has a "watch" function on Object.prototype...
-var nativeWatch = ({}).watch;
-
-var supportsPassive = false;
-if (inBrowser) {
- try {
- var opts = {};
- Object.defineProperty(opts, 'passive', ({
- get: function get () {
- /* istanbul ignore next */
- supportsPassive = true;
- }
- })); // https://github.com/facebook/flow/issues/285
- window.addEventListener('test-passive', null, opts);
- } catch (e) {}
-}
-
-// this needs to be lazy-evaled because vue may be required before
-// vue-server-renderer can set VUE_ENV
-var _isServer;
-var isServerRendering = function () {
- if (_isServer === undefined) {
- /* istanbul ignore if */
- if (!inBrowser && typeof commonjsGlobal !== 'undefined') {
- // detect presence of vue-server-renderer and avoid
- // Webpack shimming the process
- _isServer = commonjsGlobal['process'].env.VUE_ENV === 'server';
- } else {
- _isServer = false;
- }
- }
- return _isServer
-};
-
-// detect devtools
-var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;
-
-/* istanbul ignore next */
-function isNative (Ctor) {
- return typeof Ctor === 'function' && /native code/.test(Ctor.toString())
-}
-
-var hasSymbol =
- typeof Symbol !== 'undefined' && isNative(Symbol) &&
- typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys);
-
-/**
- * Defer a task to execute it asynchronously.
- */
-var nextTick = (function () {
- var callbacks = [];
- var pending = false;
- var timerFunc;
-
- function nextTickHandler () {
- pending = false;
- var copies = callbacks.slice(0);
- callbacks.length = 0;
- for (var i = 0; i < copies.length; i++) {
- copies[i]();
- }
- }
-
- // the nextTick behavior leverages the microtask queue, which can be accessed
- // via either native Promise.then or MutationObserver.
- // MutationObserver has wider support, however it is seriously bugged in
- // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
- // completely stops working after triggering a few times... so, if native
- // Promise is available, we will use it:
- /* istanbul ignore if */
- if (typeof Promise !== 'undefined' && isNative(Promise)) {
- var p = Promise.resolve();
- var logError = function (err) { console.error(err); };
- timerFunc = function () {
- p.then(nextTickHandler).catch(logError);
- // in problematic UIWebViews, Promise.then doesn't completely break, but
- // it can get stuck in a weird state where callbacks are pushed into the
- // microtask queue but the queue isn't being flushed, until the browser
- // needs to do some other work, e.g. handle a timer. Therefore we can
- // "force" the microtask queue to be flushed by adding an empty timer.
- if (isIOS) { setTimeout(noop); }
- };
- } else if (typeof MutationObserver !== 'undefined' && (
- isNative(MutationObserver) ||
- // PhantomJS and iOS 7.x
- MutationObserver.toString() === '[object MutationObserverConstructor]'
- )) {
- // use MutationObserver where native Promise is not available,
- // e.g. PhantomJS IE11, iOS7, Android 4.4
- var counter = 1;
- var observer = new MutationObserver(nextTickHandler);
- var textNode = document.createTextNode(String(counter));
- observer.observe(textNode, {
- characterData: true
- });
- timerFunc = function () {
- counter = (counter + 1) % 2;
- textNode.data = String(counter);
- };
- } else {
- // fallback to setTimeout
- /* istanbul ignore next */
- timerFunc = function () {
- setTimeout(nextTickHandler, 0);
- };
- }
-
- return function queueNextTick (cb, ctx) {
- var _resolve;
- callbacks.push(function () {
- if (cb) {
- try {
- cb.call(ctx);
- } catch (e) {
- handleError(e, ctx, 'nextTick');
- }
- } else if (_resolve) {
- _resolve(ctx);
- }
- });
- if (!pending) {
- pending = true;
- timerFunc();
- }
- if (!cb && typeof Promise !== 'undefined') {
- return new Promise(function (resolve, reject) {
- _resolve = resolve;
- })
- }
- }
-})();
-
-var _Set;
-/* istanbul ignore if */
-if (typeof Set !== 'undefined' && isNative(Set)) {
- // use native Set when available.
- _Set = Set;
-} else {
- // a non-standard Set polyfill that only works with primitive keys.
- _Set = (function () {
- function Set () {
- this.set = Object.create(null);
- }
- Set.prototype.has = function has (key) {
- return this.set[key] === true
- };
- Set.prototype.add = function add (key) {
- this.set[key] = true;
- };
- Set.prototype.clear = function clear () {
- this.set = Object.create(null);
- };
-
- return Set;
- }());
-}
-
-/* */
-
-
-var uid$1 = 0;
-
-/**
- * A dep is an observable that can have multiple
- * directives subscribing to it.
- */
-var Dep = function Dep () {
- this.id = uid$1++;
- this.subs = [];
-};
+/**
+ * A dep is an observable that can have multiple
+ * directives subscribing to it.
+ */
+var Dep = function Dep () {
+ this.id = uid$1++;
+ this.subs = [];
+};
Dep.prototype.addSub = function addSub (sub) {
this.subs.push(sub);
@@ -5378,6 +5756,110 @@ function popTarget () {
Dep.target = targetStack.pop();
}
+/* */
+
+var VNode = function VNode (
+ tag,
+ data,
+ children,
+ text,
+ elm,
+ context,
+ componentOptions,
+ asyncFactory
+) {
+ this.tag = tag;
+ this.data = data;
+ this.children = children;
+ this.text = text;
+ this.elm = elm;
+ this.ns = undefined;
+ this.context = context;
+ this.fnContext = undefined;
+ this.fnOptions = undefined;
+ this.fnScopeId = undefined;
+ this.key = data && data.key;
+ this.componentOptions = componentOptions;
+ this.componentInstance = undefined;
+ this.parent = undefined;
+ this.raw = false;
+ this.isStatic = false;
+ this.isRootInsert = true;
+ this.isComment = false;
+ this.isCloned = false;
+ this.isOnce = false;
+ this.asyncFactory = asyncFactory;
+ this.asyncMeta = undefined;
+ this.isAsyncPlaceholder = false;
+};
+
+var prototypeAccessors = { child: { configurable: true } };
+
+// DEPRECATED: alias for componentInstance for backwards compat.
+/* istanbul ignore next */
+prototypeAccessors.child.get = function () {
+ return this.componentInstance
+};
+
+Object.defineProperties( VNode.prototype, prototypeAccessors );
+
+var createEmptyVNode = function (text) {
+ if ( text === void 0 ) { text = ''; }
+
+ var node = new VNode();
+ node.text = text;
+ node.isComment = true;
+ return node
+};
+
+function createTextVNode (val) {
+ return new VNode(undefined, undefined, undefined, String(val))
+}
+
+// optimized shallow clone
+// used for static nodes and slot nodes because they may be reused across
+// multiple renders, cloning them avoids errors when DOM manipulations rely
+// on their elm reference.
+function cloneVNode (vnode, deep) {
+ var componentOptions = vnode.componentOptions;
+ var cloned = new VNode(
+ vnode.tag,
+ vnode.data,
+ vnode.children,
+ vnode.text,
+ vnode.elm,
+ vnode.context,
+ componentOptions,
+ vnode.asyncFactory
+ );
+ cloned.ns = vnode.ns;
+ cloned.isStatic = vnode.isStatic;
+ cloned.key = vnode.key;
+ cloned.isComment = vnode.isComment;
+ cloned.fnContext = vnode.fnContext;
+ cloned.fnOptions = vnode.fnOptions;
+ cloned.fnScopeId = vnode.fnScopeId;
+ cloned.isCloned = true;
+ if (deep) {
+ if (vnode.children) {
+ cloned.children = cloneVNodes(vnode.children, true);
+ }
+ if (componentOptions && componentOptions.children) {
+ componentOptions.children = cloneVNodes(componentOptions.children, true);
+ }
+ }
+ return cloned
+}
+
+function cloneVNodes (vnodes, deep) {
+ var len = vnodes.length;
+ var res = new Array(len);
+ for (var i = 0; i < len; i++) {
+ res[i] = cloneVNode(vnodes[i], deep);
+ }
+ return res
+}
+
/*
* not type checking this file because flow doesn't play well with
* dynamically accessing methods on Array prototype
@@ -5392,8 +5874,7 @@ var arrayMethods = Object.create(arrayProto);[
'splice',
'sort',
'reverse'
-]
-.forEach(function (method) {
+].forEach(function (method) {
// cache original method
var original = arrayProto[method];
def(arrayMethods, method, function mutator () {
@@ -5465,7 +5946,7 @@ var Observer = function Observer (value) {
Observer.prototype.walk = function walk (obj) {
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
- defineReactive$$1(obj, keys[i], obj[keys[i]]);
+ defineReactive(obj, keys[i], obj[keys[i]]);
}
};
@@ -5508,7 +5989,7 @@ function copyAugment (target, src, keys) {
* or the existing observer if the value already has one.
*/
function observe (value, asRootData) {
- if (!isObject(value)) {
+ if (!isObject(value) || value instanceof VNode) {
return
}
var ob;
@@ -5532,7 +6013,7 @@ function observe (value, asRootData) {
/**
* Define a reactive property on an Object.
*/
-function defineReactive$$1 (
+function defineReactive (
obj,
key,
val,
@@ -5560,9 +6041,9 @@ function defineReactive$$1 (
dep.depend();
if (childOb) {
childOb.dep.depend();
- }
- if (Array.isArray(value)) {
- dependArray(value);
+ if (Array.isArray(value)) {
+ dependArray(value);
+ }
}
}
return value
@@ -5599,7 +6080,7 @@ function set (target, key, val) {
target.splice(key, 1, val);
return val
}
- if (hasOwn(target, key)) {
+ if (key in target && !(key in Object.prototype)) {
target[key] = val;
return val
}
@@ -5615,7 +6096,7 @@ function set (target, key, val) {
target[key] = val;
return val
}
- defineReactive$$1(ob.value, key, val);
+ defineReactive(ob.value, key, val);
ob.dep.notify();
return val
}
@@ -5727,18 +6208,18 @@ function mergeDataOrFn (
// it has to be a function to pass previous merges.
return function mergedDataFn () {
return mergeData(
- typeof childVal === 'function' ? childVal.call(this) : childVal,
- typeof parentVal === 'function' ? parentVal.call(this) : parentVal
+ typeof childVal === 'function' ? childVal.call(this, this) : childVal,
+ typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal
)
}
- } else if (parentVal || childVal) {
+ } else {
return function mergedInstanceDataFn () {
// instance merge
var instanceData = typeof childVal === 'function'
- ? childVal.call(vm)
+ ? childVal.call(vm, vm)
: childVal;
var defaultData = typeof parentVal === 'function'
- ? parentVal.call(vm)
+ ? parentVal.call(vm, vm)
: parentVal;
if (instanceData) {
return mergeData(instanceData, defaultData)
@@ -5765,7 +6246,7 @@ strats.data = function (
return parentVal
}
- return mergeDataOrFn.call(this, parentVal, childVal)
+ return mergeDataOrFn(parentVal, childVal)
}
return mergeDataOrFn(parentVal, childVal, vm)
@@ -5798,11 +6279,19 @@ LIFECYCLE_HOOKS.forEach(function (hook) {
* a three-way merge between constructor options, instance
* options and parent options.
*/
-function mergeAssets (parentVal, childVal) {
+function mergeAssets (
+ parentVal,
+ childVal,
+ vm,
+ key
+) {
var res = Object.create(parentVal || null);
- return childVal
- ? extend(res, childVal)
- : res
+ if (childVal) {
+ "development" !== 'production' && assertObjectType(key, childVal, vm);
+ return extend(res, childVal)
+ } else {
+ return res
+ }
}
ASSET_TYPES.forEach(function (type) {
@@ -5815,22 +6304,30 @@ ASSET_TYPES.forEach(function (type) {
* Watchers hashes should not overwrite one
* another, so we merge them as arrays.
*/
-strats.watch = function (parentVal, childVal) {
+strats.watch = function (
+ parentVal,
+ childVal,
+ vm,
+ key
+) {
// work around Firefox's Object.prototype.watch...
if (parentVal === nativeWatch) { parentVal = undefined; }
if (childVal === nativeWatch) { childVal = undefined; }
/* istanbul ignore if */
if (!childVal) { return Object.create(parentVal || null) }
+ {
+ assertObjectType(key, childVal, vm);
+ }
if (!parentVal) { return childVal }
var ret = {};
extend(ret, parentVal);
- for (var key in childVal) {
- var parent = ret[key];
- var child = childVal[key];
+ for (var key$1 in childVal) {
+ var parent = ret[key$1];
+ var child = childVal[key$1];
if (parent && !Array.isArray(parent)) {
parent = [parent];
}
- ret[key] = parent
+ ret[key$1] = parent
? parent.concat(child)
: Array.isArray(child) ? child : [child];
}
@@ -5843,7 +6340,15 @@ strats.watch = function (parentVal, childVal) {
strats.props =
strats.methods =
strats.inject =
-strats.computed = function (parentVal, childVal) {
+strats.computed = function (
+ parentVal,
+ childVal,
+ vm,
+ key
+) {
+ if (childVal && "development" !== 'production') {
+ assertObjectType(key, childVal, vm);
+ }
if (!parentVal) { return childVal }
var ret = Object.create(null);
extend(ret, parentVal);
@@ -5866,13 +6371,23 @@ var defaultStrat = function (parentVal, childVal) {
*/
function checkComponents (options) {
for (var key in options.components) {
- var lower = key.toLowerCase();
- if (isBuiltInTag(lower) || config.isReservedTag(lower)) {
- warn(
- 'Do not use built-in or reserved HTML elements as component ' +
- 'id: ' + key
- );
- }
+ validateComponentName(key);
+ }
+}
+
+function validateComponentName (name) {
+ if (!/^[a-zA-Z][\w-]*$/.test(name)) {
+ warn(
+ 'Invalid component name: "' + name + '". Component names ' +
+ 'can only contain alphanumeric characters and the hyphen, ' +
+ 'and must start with a letter.'
+ );
+ }
+ if (isBuiltInTag(name) || config.isReservedTag(name)) {
+ warn(
+ 'Do not use built-in or reserved HTML elements as component ' +
+ 'id: ' + name
+ );
}
}
@@ -5880,7 +6395,7 @@ function checkComponents (options) {
* Ensure all props option syntax are normalized into the
* Object-based format.
*/
-function normalizeProps (options) {
+function normalizeProps (options, vm) {
var props = options.props;
if (!props) { return }
var res = {};
@@ -5900,32 +6415,75 @@ function normalizeProps (options) {
for (var key in props) {
val = props[key];
name = camelize(key);
+ if ("development" !== 'production' && isPlainObject(val)) {
+ validatePropObject(name, val, vm);
+ }
res[name] = isPlainObject(val)
? val
: { type: val };
}
+ } else {
+ warn(
+ "Invalid value for option \"props\": expected an Array or an Object, " +
+ "but got " + (toRawType(props)) + ".",
+ vm
+ );
}
options.props = res;
}
/**
- * Normalize all injections into Object-based format
+ * Validate whether a prop object keys are valid.
*/
-function normalizeInject (options) {
- var inject = options.inject;
- if (Array.isArray(inject)) {
- var normalized = options.inject = {};
- for (var i = 0; i < inject.length; i++) {
- normalized[inject[i]] = inject[i];
+var propOptionsRE = /^(type|default|required|validator)$/;
+
+function validatePropObject (
+ propName,
+ prop,
+ vm
+) {
+ for (var key in prop) {
+ if (!propOptionsRE.test(key)) {
+ warn(
+ ("Invalid key \"" + key + "\" in validation rules object for prop \"" + propName + "\"."),
+ vm
+ );
}
}
}
/**
- * Normalize raw function directives into object format.
+ * Normalize all injections into Object-based format
*/
-function normalizeDirectives (options) {
- var dirs = options.directives;
+function normalizeInject (options, vm) {
+ var inject = options.inject;
+ if (!inject) { return }
+ var normalized = options.inject = {};
+ if (Array.isArray(inject)) {
+ for (var i = 0; i < inject.length; i++) {
+ normalized[inject[i]] = { from: inject[i] };
+ }
+ } else if (isPlainObject(inject)) {
+ for (var key in inject) {
+ var val = inject[key];
+ normalized[key] = isPlainObject(val)
+ ? extend({ from: key }, val)
+ : { from: val };
+ }
+ } else {
+ warn(
+ "Invalid value for option \"inject\": expected an Array or an Object, " +
+ "but got " + (toRawType(inject)) + ".",
+ vm
+ );
+ }
+}
+
+/**
+ * Normalize raw function directives into object format.
+ */
+function normalizeDirectives (options) {
+ var dirs = options.directives;
if (dirs) {
for (var key in dirs) {
var def = dirs[key];
@@ -5936,6 +6494,16 @@ function normalizeDirectives (options) {
}
}
+function assertObjectType (name, value, vm) {
+ if (!isPlainObject(value)) {
+ warn(
+ "Invalid value for option \"" + name + "\": expected an Object, " +
+ "but got " + (toRawType(value)) + ".",
+ vm
+ );
+ }
+}
+
/**
* Merge two option objects into a new one.
* Core utility used in both instantiation and inheritance.
@@ -5953,8 +6521,8 @@ function mergeOptions (
child = child.options;
}
- normalizeProps(child);
- normalizeInject(child);
+ normalizeProps(child, vm);
+ normalizeInject(child, vm);
normalizeDirectives(child);
var extendsFrom = child.extends;
if (extendsFrom) {
@@ -6044,7 +6612,11 @@ function validateProp (
observe(value);
observerState.shouldConvert = prevShouldConvert;
}
- {
+ if (
+ "development" !== 'production' &&
+ // skip validation for weex recycle-list child component props
+ !(true && isObject(value) && ('@binding' in value))
+ ) {
assertProp(prop, key, value, vm, absent);
}
return value
@@ -6118,9 +6690,9 @@ function assertProp (
}
if (!valid) {
warn(
- 'Invalid prop: type check failed for prop "' + name + '".' +
- ' Expected ' + expectedTypes.map(capitalize).join(', ') +
- ', got ' + Object.prototype.toString.call(value).slice(8, -1) + '.',
+ "Invalid prop: type check failed for prop \"" + name + "\"." +
+ " Expected " + (expectedTypes.map(capitalize).join(', ')) +
+ ", got " + (toRawType(value)) + ".",
vm
);
return
@@ -6186,6 +6758,158 @@ function isType (type, fn) {
/* */
+function handleError (err, vm, info) {
+ if (vm) {
+ var cur = vm;
+ while ((cur = cur.$parent)) {
+ var hooks = cur.$options.errorCaptured;
+ if (hooks) {
+ for (var i = 0; i < hooks.length; i++) {
+ try {
+ var capture = hooks[i].call(cur, err, vm, info) === false;
+ if (capture) { return }
+ } catch (e) {
+ globalHandleError(e, cur, 'errorCaptured hook');
+ }
+ }
+ }
+ }
+ }
+ globalHandleError(err, vm, info);
+}
+
+function globalHandleError (err, vm, info) {
+ if (config.errorHandler) {
+ try {
+ return config.errorHandler.call(null, err, vm, info)
+ } catch (e) {
+ logError(e, null, 'config.errorHandler');
+ }
+ }
+ logError(err, vm, info);
+}
+
+function logError (err, vm, info) {
+ {
+ warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm);
+ }
+ /* istanbul ignore else */
+ if ((inBrowser || inWeex) && typeof console !== 'undefined') {
+ console.error(err);
+ } else {
+ throw err
+ }
+}
+
+/* */
+/* globals MessageChannel */
+
+var callbacks = [];
+var pending = false;
+
+function flushCallbacks () {
+ pending = false;
+ var copies = callbacks.slice(0);
+ callbacks.length = 0;
+ for (var i = 0; i < copies.length; i++) {
+ copies[i]();
+ }
+}
+
+// Here we have async deferring wrappers using both micro and macro tasks.
+// In < 2.4 we used micro tasks everywhere, but there are some scenarios where
+// micro tasks have too high a priority and fires in between supposedly
+// sequential events (e.g. #4521, #6690) or even between bubbling of the same
+// event (#6566). However, using macro tasks everywhere also has subtle problems
+// when state is changed right before repaint (e.g. #6813, out-in transitions).
+// Here we use micro task by default, but expose a way to force macro task when
+// needed (e.g. in event handlers attached by v-on).
+var microTimerFunc;
+var macroTimerFunc;
+var useMacroTask = false;
+
+// Determine (macro) Task defer implementation.
+// Technically setImmediate should be the ideal choice, but it's only available
+// in IE. The only polyfill that consistently queues the callback after all DOM
+// events triggered in the same loop is by using MessageChannel.
+/* istanbul ignore if */
+if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
+ macroTimerFunc = function () {
+ setImmediate(flushCallbacks);
+ };
+} else if (typeof MessageChannel !== 'undefined' && (
+ isNative(MessageChannel) ||
+ // PhantomJS
+ MessageChannel.toString() === '[object MessageChannelConstructor]'
+)) {
+ var channel = new MessageChannel();
+ var port = channel.port2;
+ channel.port1.onmessage = flushCallbacks;
+ macroTimerFunc = function () {
+ port.postMessage(1);
+ };
+} else {
+ /* istanbul ignore next */
+ macroTimerFunc = function () {
+ setTimeout(flushCallbacks, 0);
+ };
+}
+
+// Determine MicroTask defer implementation.
+/* istanbul ignore next, $flow-disable-line */
+if (typeof Promise !== 'undefined' && isNative(Promise)) {
+ var p = Promise.resolve();
+ microTimerFunc = function () {
+ p.then(flushCallbacks);
+ // in problematic UIWebViews, Promise.then doesn't completely break, but
+ // it can get stuck in a weird state where callbacks are pushed into the
+ // microtask queue but the queue isn't being flushed, until the browser
+ // needs to do some other work, e.g. handle a timer. Therefore we can
+ // "force" the microtask queue to be flushed by adding an empty timer.
+ if (isIOS) { setTimeout(noop); }
+ };
+} else {
+ // fallback to macro
+ microTimerFunc = macroTimerFunc;
+}
+
+/**
+ * Wrap a function so that if any code inside triggers state change,
+ * the changes are queued using a Task instead of a MicroTask.
+ */
+
+
+function nextTick (cb, ctx) {
+ var _resolve;
+ callbacks.push(function () {
+ if (cb) {
+ try {
+ cb.call(ctx);
+ } catch (e) {
+ handleError(e, ctx, 'nextTick');
+ }
+ } else if (_resolve) {
+ _resolve(ctx);
+ }
+ });
+ if (!pending) {
+ pending = true;
+ if (useMacroTask) {
+ macroTimerFunc();
+ } else {
+ microTimerFunc();
+ }
+ }
+ // $flow-disable-line
+ if (!cb && typeof Promise !== 'undefined') {
+ return new Promise(function (resolve) {
+ _resolve = resolve;
+ })
+ }
+}
+
+/* */
+
/* not type checking this file because flow doesn't play well with Proxy */
var initProxy;
@@ -6201,8 +6925,10 @@ var initProxy;
var warnNonPresent = function (target, key) {
warn(
"Property or method \"" + key + "\" is not defined on the instance but " +
- "referenced during render. Make sure to declare reactive data " +
- "properties in the data option.",
+ 'referenced during render. Make sure that this property is reactive, ' +
+ 'either in the data option, or for class-based components, by ' +
+ 'initializing the property. ' +
+ 'See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.',
target
);
};
@@ -6212,7 +6938,7 @@ var initProxy;
Proxy.toString().match(/native code/);
if (hasProxy) {
- var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta');
+ var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact');
config.keyCodes = new Proxy(config.keyCodes, {
set: function set (target, key, value) {
if (isBuiltInModifier(key)) {
@@ -6260,6 +6986,43 @@ var initProxy;
};
}
+/* */
+
+var seenObjects = new _Set();
+
+/**
+ * Recursively traverse an object to evoke all converted
+ * getters, so that every nested property inside the object
+ * is collected as a "deep" dependency.
+ */
+function traverse (val) {
+ _traverse(val, seenObjects);
+ seenObjects.clear();
+}
+
+function _traverse (val, seen) {
+ var i, keys;
+ var isA = Array.isArray(val);
+ if ((!isA && !isObject(val)) || Object.isFrozen(val)) {
+ return
+ }
+ if (val.__ob__) {
+ var depId = val.__ob__.dep.id;
+ if (seen.has(depId)) {
+ return
+ }
+ seen.add(depId);
+ }
+ if (isA) {
+ i = val.length;
+ while (i--) { _traverse(val[i], seen); }
+ } else {
+ keys = Object.keys(val);
+ i = keys.length;
+ while (i--) { _traverse(val[keys[i]], seen); }
+ }
+}
+
var mark;
var measure;
@@ -6285,99 +7048,6 @@ var measure;
/* */
-var VNode = function VNode (
- tag,
- data,
- children,
- text,
- elm,
- context,
- componentOptions,
- asyncFactory
-) {
- this.tag = tag;
- this.data = data;
- this.children = children;
- this.text = text;
- this.elm = elm;
- this.ns = undefined;
- this.context = context;
- this.functionalContext = undefined;
- this.key = data && data.key;
- this.componentOptions = componentOptions;
- this.componentInstance = undefined;
- this.parent = undefined;
- this.raw = false;
- this.isStatic = false;
- this.isRootInsert = true;
- this.isComment = false;
- this.isCloned = false;
- this.isOnce = false;
- this.asyncFactory = asyncFactory;
- this.asyncMeta = undefined;
- this.isAsyncPlaceholder = false;
-};
-
-var prototypeAccessors = { child: {} };
-
-// DEPRECATED: alias for componentInstance for backwards compat.
-/* istanbul ignore next */
-prototypeAccessors.child.get = function () {
- return this.componentInstance
-};
-
-Object.defineProperties( VNode.prototype, prototypeAccessors );
-
-var createEmptyVNode = function (text) {
- if ( text === void 0 ) { text = ''; }
-
- var node = new VNode();
- node.text = text;
- node.isComment = true;
- return node
-};
-
-function createTextVNode (val) {
- return new VNode(undefined, undefined, undefined, String(val))
-}
-
-// optimized shallow clone
-// used for static nodes and slot nodes because they may be reused across
-// multiple renders, cloning them avoids errors when DOM manipulations rely
-// on their elm reference.
-function cloneVNode (vnode, deep) {
- var cloned = new VNode(
- vnode.tag,
- vnode.data,
- vnode.children,
- vnode.text,
- vnode.elm,
- vnode.context,
- vnode.componentOptions,
- vnode.asyncFactory
- );
- cloned.ns = vnode.ns;
- cloned.isStatic = vnode.isStatic;
- cloned.key = vnode.key;
- cloned.isComment = vnode.isComment;
- cloned.isCloned = true;
- if (deep && vnode.children) {
- cloned.children = cloneVNodes(vnode.children);
- }
- return cloned
-}
-
-function cloneVNodes (vnodes, deep) {
- var len = vnodes.length;
- var res = new Array(len);
- for (var i = 0; i < len; i++) {
- res[i] = cloneVNode(vnodes[i], deep);
- }
- return res
-}
-
-/* */
-
var normalizeEvent = cached(function (name) {
var passive = name.charAt(0) === '&';
name = passive ? name.slice(1) : name;
@@ -6419,14 +7089,15 @@ function updateListeners (
remove$$1,
vm
) {
- var name, def$$1, cur, old, event;
+ var name, def, cur, old, event;
for (name in on) {
- def$$1 = cur = on[name];
+ def = cur = on[name];
old = oldOn[name];
event = normalizeEvent(name);
- if (isPlainObject(def$$1)) {
- cur = def$$1.handler;
- event.params = def$$1.params;
+ /* istanbul ignore if */
+ if (true && isPlainObject(def)) {
+ cur = def.handler;
+ event.params = def.params;
}
if (isUndef(cur)) {
"development" !== 'production' && warn(
@@ -6454,6 +7125,9 @@ function updateListeners (
/* */
function mergeVNodeHook (def, hookKey, hook) {
+ if (def instanceof VNode) {
+ def = def.data.hook || (def.data.hook = {});
+ }
var invoker;
var oldHook = def[hookKey];
@@ -6592,20 +7266,29 @@ function isTextNode (node) {
function normalizeArrayChildren (children, nestedIndex) {
var res = [];
- var i, c, last;
+ var i, c, lastIndex, last;
for (i = 0; i < children.length; i++) {
c = children[i];
if (isUndef(c) || typeof c === 'boolean') { continue }
- last = res[res.length - 1];
+ lastIndex = res.length - 1;
+ last = res[lastIndex];
// nested
if (Array.isArray(c)) {
- res.push.apply(res, normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i)));
+ if (c.length > 0) {
+ c = normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i));
+ // merge adjacent text nodes
+ if (isTextNode(c[0]) && isTextNode(last)) {
+ res[lastIndex] = createTextVNode(last.text + (c[0]).text);
+ c.shift();
+ }
+ res.push.apply(res, c);
+ }
} else if (isPrimitive(c)) {
if (isTextNode(last)) {
// merge adjacent text nodes
// this is necessary for SSR hydration because text nodes are
// essentially merged when rendered to HTML strings
- (last).text += String(c);
+ res[lastIndex] = createTextVNode(last.text + c);
} else if (c !== '') {
// convert primitive to vnode
res.push(createTextVNode(c));
@@ -6613,7 +7296,7 @@ function normalizeArrayChildren (children, nestedIndex) {
} else {
if (isTextNode(c) && isTextNode(last)) {
// merge adjacent text nodes
- res[res.length - 1] = createTextVNode(last.text + c.text);
+ res[lastIndex] = createTextVNode(last.text + c.text);
} else {
// default key for nested array children (likely generated by v-for)
if (isTrue(children._isVList) &&
@@ -6632,7 +7315,10 @@ function normalizeArrayChildren (children, nestedIndex) {
/* */
function ensureCtor (comp, base) {
- if (comp.__esModule && comp.default) {
+ if (
+ comp.__esModule ||
+ (hasSymbol && comp[Symbol.toStringTag] === 'Module')
+ ) {
comp = comp.default;
}
return isObject(comp)
@@ -6788,8 +7474,8 @@ function initEvents (vm) {
var target;
-function add (event, fn, once$$1) {
- if (once$$1) {
+function add (event, fn, once) {
+ if (once) {
target.$once(event, fn);
} else {
target.$on(event, fn);
@@ -6807,6 +7493,7 @@ function updateComponentListeners (
) {
target = vm;
updateListeners(listeners, oldListeners || {}, add, remove$1, vm);
+ target = undefined;
}
function eventsMixin (Vue) {
@@ -6852,8 +7539,8 @@ function eventsMixin (Vue) {
}
// array of events
if (Array.isArray(event)) {
- for (var i$1 = 0, l = event.length; i$1 < l; i$1++) {
- this$1.$off(event[i$1], fn);
+ for (var i = 0, l = event.length; i < l; i++) {
+ this$1.$off(event[i], fn);
}
return vm
}
@@ -6862,18 +7549,20 @@ function eventsMixin (Vue) {
if (!cbs) {
return vm
}
- if (arguments.length === 1) {
+ if (!fn) {
vm._events[event] = null;
return vm
}
- // specific handler
- var cb;
- var i = cbs.length;
- while (i--) {
- cb = cbs[i];
- if (cb === fn || cb.fn === fn) {
- cbs.splice(i, 1);
- break
+ if (fn) {
+ // specific handler
+ var cb;
+ var i$1 = cbs.length;
+ while (i$1--) {
+ cb = cbs[i$1];
+ if (cb === fn || cb.fn === fn) {
+ cbs.splice(i$1, 1);
+ break
+ }
}
}
return vm
@@ -6911,6 +7600,8 @@ function eventsMixin (Vue) {
/* */
+
+
/**
* Runtime helper for resolving raw children VNodes into a slot object.
*/
@@ -6922,34 +7613,40 @@ function resolveSlots (
if (!children) {
return slots
}
- var defaultSlot = [];
for (var i = 0, l = children.length; i < l; i++) {
var child = children[i];
+ var data = child.data;
+ // remove slot attribute if the node is resolved as a Vue slot node
+ if (data && data.attrs && data.attrs.slot) {
+ delete data.attrs.slot;
+ }
// named slots should only be respected if the vnode was rendered in the
// same context.
- if ((child.context === context || child.functionalContext === context) &&
- child.data && child.data.slot != null
+ if ((child.context === context || child.fnContext === context) &&
+ data && data.slot != null
) {
- var name = child.data.slot;
+ var name = data.slot;
var slot = (slots[name] || (slots[name] = []));
if (child.tag === 'template') {
- slot.push.apply(slot, child.children);
+ slot.p
<TRUNCATED>