bpmn-moddle
Version:
A moddle wrapper for BPMN 2.0
2,075 lines (1,668 loc) • 156 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.BpmnModdle = factory());
}(this, function () { 'use strict';
/**
* Flatten array, one level deep.
*
* @param {Array<?>} arr
*
* @return {Array<?>}
*/
var nativeToString = Object.prototype.toString;
var nativeHasOwnProperty = Object.prototype.hasOwnProperty;
function isUndefined(obj) {
return obj === undefined;
}
function isArray(obj) {
return nativeToString.call(obj) === '[object Array]';
}
function isObject(obj) {
return nativeToString.call(obj) === '[object Object]';
}
function isFunction(obj) {
var tag = nativeToString.call(obj);
return tag === '[object Function]' || tag === '[object AsyncFunction]' || tag === '[object GeneratorFunction]' || tag === '[object AsyncGeneratorFunction]' || tag === '[object Proxy]';
}
function isString(obj) {
return nativeToString.call(obj) === '[object String]';
}
/**
* Return true, if target owns a property with the given key.
*
* @param {Object} target
* @param {String} key
*
* @return {Boolean}
*/
function has(target, key) {
return nativeHasOwnProperty.call(target, key);
}
/**
* Find element in collection.
*
* @param {Array|Object} collection
* @param {Function|Object} matcher
*
* @return {Object}
*/
function find(collection, matcher) {
matcher = toMatcher(matcher);
var match;
forEach(collection, function (val, key) {
if (matcher(val, key)) {
match = val;
return false;
}
});
return match;
}
/**
* Find element in collection.
*
* @param {Array|Object} collection
* @param {Function} matcher
*
* @return {Array} result
*/
function filter(collection, matcher) {
var result = [];
forEach(collection, function (val, key) {
if (matcher(val, key)) {
result.push(val);
}
});
return result;
}
/**
* Iterate over collection; returning something
* (non-undefined) will stop iteration.
*
* @param {Array|Object} collection
* @param {Function} iterator
*
* @return {Object} return result that stopped the iteration
*/
function forEach(collection, iterator) {
var val, result;
if (isUndefined(collection)) {
return;
}
var convertKey = isArray(collection) ? toNum : identity;
for (var key in collection) {
if (has(collection, key)) {
val = collection[key];
result = iterator(val, convertKey(key));
if (result === false) {
return val;
}
}
}
}
/**
* Transform a collection into another collection
* by piping each member through the given fn.
*
* @param {Object|Array} collection
* @param {Function} fn
*
* @return {Array} transformed collection
*/
function map(collection, fn) {
var result = [];
forEach(collection, function (val, key) {
result.push(fn(val, key));
});
return result;
}
function toMatcher(matcher) {
return isFunction(matcher) ? matcher : function (e) {
return e === matcher;
};
}
function identity(arg) {
return arg;
}
function toNum(arg) {
return Number(arg);
}
/**
* Bind function against target <this>.
*
* @param {Function} fn
* @param {Object} target
*
* @return {Function} bound function
*/
function bind(fn, target) {
return fn.bind(target);
}
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
/**
* Convenience wrapper for `Object.assign`.
*
* @param {Object} target
* @param {...Object} others
*
* @return {Object} the target
*/
function assign(target) {
for (var _len = arguments.length, others = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
others[_key - 1] = arguments[_key];
}
return _extends.apply(void 0, [target].concat(others));
}
/**
* Pick given properties from the target object.
*
* @param {Object} target
* @param {Array} properties
*
* @return {Object} target
*/
function pick(target, properties) {
var result = {};
var obj = Object(target);
forEach(properties, function (prop) {
if (prop in obj) {
result[prop] = target[prop];
}
});
return result;
}
/**
* Moddle base element.
*/
function Base() { }
Base.prototype.get = function(name) {
return this.$model.properties.get(this, name);
};
Base.prototype.set = function(name, value) {
this.$model.properties.set(this, name, value);
};
/**
* A model element factory.
*
* @param {Moddle} model
* @param {Properties} properties
*/
function Factory(model, properties) {
this.model = model;
this.properties = properties;
}
Factory.prototype.createType = function(descriptor) {
var model = this.model;
var props = this.properties,
prototype = Object.create(Base.prototype);
// initialize default values
forEach(descriptor.properties, function(p) {
if (!p.isMany && p.default !== undefined) {
prototype[p.name] = p.default;
}
});
props.defineModel(prototype, model);
props.defineDescriptor(prototype, descriptor);
var name = descriptor.ns.name;
/**
* The new type constructor
*/
function ModdleElement(attrs) {
props.define(this, '$type', { value: name, enumerable: true });
props.define(this, '$attrs', { value: {} });
props.define(this, '$parent', { writable: true });
forEach(attrs, bind(function(val, key) {
this.set(key, val);
}, this));
}
ModdleElement.prototype = prototype;
ModdleElement.hasType = prototype.$instanceOf = this.model.hasType;
// static links
props.defineModel(ModdleElement, model);
props.defineDescriptor(ModdleElement, descriptor);
return ModdleElement;
};
/**
* Built-in moddle types
*/
var BUILTINS = {
String: true,
Boolean: true,
Integer: true,
Real: true,
Element: true
};
/**
* Converters for built in types from string representations
*/
var TYPE_CONVERTERS = {
String: function(s) { return s; },
Boolean: function(s) { return s === 'true'; },
Integer: function(s) { return parseInt(s, 10); },
Real: function(s) { return parseFloat(s, 10); }
};
/**
* Convert a type to its real representation
*/
function coerceType(type, value) {
var converter = TYPE_CONVERTERS[type];
if (converter) {
return converter(value);
} else {
return value;
}
}
/**
* Return whether the given type is built-in
*/
function isBuiltIn(type) {
return !!BUILTINS[type];
}
/**
* Return whether the given type is simple
*/
function isSimple(type) {
return !!TYPE_CONVERTERS[type];
}
/**
* Parses a namespaced attribute name of the form (ns:)localName to an object,
* given a default prefix to assume in case no explicit namespace is given.
*
* @param {String} name
* @param {String} [defaultPrefix] the default prefix to take, if none is present.
*
* @return {Object} the parsed name
*/
function parseName(name, defaultPrefix) {
var parts = name.split(/:/),
localName, prefix;
// no prefix (i.e. only local name)
if (parts.length === 1) {
localName = name;
prefix = defaultPrefix;
} else
// prefix + local name
if (parts.length === 2) {
localName = parts[1];
prefix = parts[0];
} else {
throw new Error('expected <prefix:localName> or <localName>, got ' + name);
}
name = (prefix ? prefix + ':' : '') + localName;
return {
name: name,
prefix: prefix,
localName: localName
};
}
/**
* A utility to build element descriptors.
*/
function DescriptorBuilder(nameNs) {
this.ns = nameNs;
this.name = nameNs.name;
this.allTypes = [];
this.allTypesByName = {};
this.properties = [];
this.propertiesByName = {};
}
DescriptorBuilder.prototype.build = function() {
return pick(this, [
'ns',
'name',
'allTypes',
'allTypesByName',
'properties',
'propertiesByName',
'bodyProperty',
'idProperty'
]);
};
/**
* Add property at given index.
*
* @param {Object} p
* @param {Number} [idx]
* @param {Boolean} [validate=true]
*/
DescriptorBuilder.prototype.addProperty = function(p, idx, validate) {
if (typeof idx === 'boolean') {
validate = idx;
idx = undefined;
}
this.addNamedProperty(p, validate !== false);
var properties = this.properties;
if (idx !== undefined) {
properties.splice(idx, 0, p);
} else {
properties.push(p);
}
};
DescriptorBuilder.prototype.replaceProperty = function(oldProperty, newProperty, replace) {
var oldNameNs = oldProperty.ns;
var props = this.properties,
propertiesByName = this.propertiesByName,
rename = oldProperty.name !== newProperty.name;
if (oldProperty.isId) {
if (!newProperty.isId) {
throw new Error(
'property <' + newProperty.ns.name + '> must be id property ' +
'to refine <' + oldProperty.ns.name + '>');
}
this.setIdProperty(newProperty, false);
}
if (oldProperty.isBody) {
if (!newProperty.isBody) {
throw new Error(
'property <' + newProperty.ns.name + '> must be body property ' +
'to refine <' + oldProperty.ns.name + '>');
}
// TODO: Check compatibility
this.setBodyProperty(newProperty, false);
}
// validate existence and get location of old property
var idx = props.indexOf(oldProperty);
if (idx === -1) {
throw new Error('property <' + oldNameNs.name + '> not found in property list');
}
// remove old property
props.splice(idx, 1);
// replacing the named property is intentional
//
// * validate only if this is a "rename" operation
// * add at specific index unless we "replace"
//
this.addProperty(newProperty, replace ? undefined : idx, rename);
// make new property available under old name
propertiesByName[oldNameNs.name] = propertiesByName[oldNameNs.localName] = newProperty;
};
DescriptorBuilder.prototype.redefineProperty = function(p, targetPropertyName, replace) {
var nsPrefix = p.ns.prefix;
var parts = targetPropertyName.split('#');
var name = parseName(parts[0], nsPrefix);
var attrName = parseName(parts[1], name.prefix).name;
var redefinedProperty = this.propertiesByName[attrName];
if (!redefinedProperty) {
throw new Error('refined property <' + attrName + '> not found');
} else {
this.replaceProperty(redefinedProperty, p, replace);
}
delete p.redefines;
};
DescriptorBuilder.prototype.addNamedProperty = function(p, validate) {
var ns = p.ns,
propsByName = this.propertiesByName;
if (validate) {
this.assertNotDefined(p, ns.name);
this.assertNotDefined(p, ns.localName);
}
propsByName[ns.name] = propsByName[ns.localName] = p;
};
DescriptorBuilder.prototype.removeNamedProperty = function(p) {
var ns = p.ns,
propsByName = this.propertiesByName;
delete propsByName[ns.name];
delete propsByName[ns.localName];
};
DescriptorBuilder.prototype.setBodyProperty = function(p, validate) {
if (validate && this.bodyProperty) {
throw new Error(
'body property defined multiple times ' +
'(<' + this.bodyProperty.ns.name + '>, <' + p.ns.name + '>)');
}
this.bodyProperty = p;
};
DescriptorBuilder.prototype.setIdProperty = function(p, validate) {
if (validate && this.idProperty) {
throw new Error(
'id property defined multiple times ' +
'(<' + this.idProperty.ns.name + '>, <' + p.ns.name + '>)');
}
this.idProperty = p;
};
DescriptorBuilder.prototype.assertNotDefined = function(p, name) {
var propertyName = p.name,
definedProperty = this.propertiesByName[propertyName];
if (definedProperty) {
throw new Error(
'property <' + propertyName + '> already defined; ' +
'override of <' + definedProperty.definedBy.ns.name + '#' + definedProperty.ns.name + '> by ' +
'<' + p.definedBy.ns.name + '#' + p.ns.name + '> not allowed without redefines');
}
};
DescriptorBuilder.prototype.hasProperty = function(name) {
return this.propertiesByName[name];
};
DescriptorBuilder.prototype.addTrait = function(t, inherited) {
var typesByName = this.allTypesByName,
types = this.allTypes;
var typeName = t.name;
if (typeName in typesByName) {
return;
}
forEach(t.properties, bind(function(p) {
// clone property to allow extensions
p = assign({}, p, {
name: p.ns.localName,
inherited: inherited
});
Object.defineProperty(p, 'definedBy', {
value: t
});
var replaces = p.replaces,
redefines = p.redefines;
// add replace/redefine support
if (replaces || redefines) {
this.redefineProperty(p, replaces || redefines, replaces);
} else {
if (p.isBody) {
this.setBodyProperty(p);
}
if (p.isId) {
this.setIdProperty(p);
}
this.addProperty(p);
}
}, this));
types.push(t);
typesByName[typeName] = t;
};
/**
* A registry of Moddle packages.
*
* @param {Array<Package>} packages
* @param {Properties} properties
*/
function Registry(packages, properties) {
this.packageMap = {};
this.typeMap = {};
this.packages = [];
this.properties = properties;
forEach(packages, bind(this.registerPackage, this));
}
Registry.prototype.getPackage = function(uriOrPrefix) {
return this.packageMap[uriOrPrefix];
};
Registry.prototype.getPackages = function() {
return this.packages;
};
Registry.prototype.registerPackage = function(pkg) {
// copy package
pkg = assign({}, pkg);
var pkgMap = this.packageMap;
ensureAvailable(pkgMap, pkg, 'prefix');
ensureAvailable(pkgMap, pkg, 'uri');
// register types
forEach(pkg.types, bind(function(descriptor) {
this.registerType(descriptor, pkg);
}, this));
pkgMap[pkg.uri] = pkgMap[pkg.prefix] = pkg;
this.packages.push(pkg);
};
/**
* Register a type from a specific package with us
*/
Registry.prototype.registerType = function(type, pkg) {
type = assign({}, type, {
superClass: (type.superClass || []).slice(),
extends: (type.extends || []).slice(),
properties: (type.properties || []).slice(),
meta: assign((type.meta || {}))
});
var ns = parseName(type.name, pkg.prefix),
name = ns.name,
propertiesByName = {};
// parse properties
forEach(type.properties, bind(function(p) {
// namespace property names
var propertyNs = parseName(p.name, ns.prefix),
propertyName = propertyNs.name;
// namespace property types
if (!isBuiltIn(p.type)) {
p.type = parseName(p.type, propertyNs.prefix).name;
}
assign(p, {
ns: propertyNs,
name: propertyName
});
propertiesByName[propertyName] = p;
}, this));
// update ns + name
assign(type, {
ns: ns,
name: name,
propertiesByName: propertiesByName
});
forEach(type.extends, bind(function(extendsName) {
var extended = this.typeMap[extendsName];
extended.traits = extended.traits || [];
extended.traits.push(name);
}, this));
// link to package
this.definePackage(type, pkg);
// register
this.typeMap[name] = type;
};
/**
* Traverse the type hierarchy from bottom to top,
* calling iterator with (type, inherited) for all elements in
* the inheritance chain.
*
* @param {Object} nsName
* @param {Function} iterator
* @param {Boolean} [trait=false]
*/
Registry.prototype.mapTypes = function(nsName, iterator, trait) {
var type = isBuiltIn(nsName.name) ? { name: nsName.name } : this.typeMap[nsName.name];
var self = this;
/**
* Traverse the selected trait.
*
* @param {String} cls
*/
function traverseTrait(cls) {
return traverseSuper(cls, true);
}
/**
* Traverse the selected super type or trait
*
* @param {String} cls
* @param {Boolean} [trait=false]
*/
function traverseSuper(cls, trait) {
var parentNs = parseName(cls, isBuiltIn(cls) ? '' : nsName.prefix);
self.mapTypes(parentNs, iterator, trait);
}
if (!type) {
throw new Error('unknown type <' + nsName.name + '>');
}
forEach(type.superClass, trait ? traverseTrait : traverseSuper);
// call iterator with (type, inherited=!trait)
iterator(type, !trait);
forEach(type.traits, traverseTrait);
};
/**
* Returns the effective descriptor for a type.
*
* @param {String} type the namespaced name (ns:localName) of the type
*
* @return {Descriptor} the resulting effective descriptor
*/
Registry.prototype.getEffectiveDescriptor = function(name) {
var nsName = parseName(name);
var builder = new DescriptorBuilder(nsName);
this.mapTypes(nsName, function(type, inherited) {
builder.addTrait(type, inherited);
});
var descriptor = builder.build();
// define package link
this.definePackage(descriptor, descriptor.allTypes[descriptor.allTypes.length - 1].$pkg);
return descriptor;
};
Registry.prototype.definePackage = function(target, pkg) {
this.properties.define(target, '$pkg', { value: pkg });
};
///////// helpers ////////////////////////////
function ensureAvailable(packageMap, pkg, identifierKey) {
var value = pkg[identifierKey];
if (value in packageMap) {
throw new Error('package with ' + identifierKey + ' <' + value + '> already defined');
}
}
/**
* A utility that gets and sets properties of model elements.
*
* @param {Model} model
*/
function Properties(model) {
this.model = model;
}
/**
* Sets a named property on the target element.
* If the value is undefined, the property gets deleted.
*
* @param {Object} target
* @param {String} name
* @param {Object} value
*/
Properties.prototype.set = function(target, name, value) {
var property = this.model.getPropertyDescriptor(target, name);
var propertyName = property && property.name;
if (isUndefined$1(value)) {
// unset the property, if the specified value is undefined;
// delete from $attrs (for extensions) or the target itself
if (property) {
delete target[propertyName];
} else {
delete target.$attrs[name];
}
} else {
// set the property, defining well defined properties on the fly
// or simply updating them in target.$attrs (for extensions)
if (property) {
if (propertyName in target) {
target[propertyName] = value;
} else {
defineProperty(target, property, value);
}
} else {
target.$attrs[name] = value;
}
}
};
/**
* Returns the named property of the given element
*
* @param {Object} target
* @param {String} name
*
* @return {Object}
*/
Properties.prototype.get = function(target, name) {
var property = this.model.getPropertyDescriptor(target, name);
if (!property) {
return target.$attrs[name];
}
var propertyName = property.name;
// check if access to collection property and lazily initialize it
if (!target[propertyName] && property.isMany) {
defineProperty(target, property, []);
}
return target[propertyName];
};
/**
* Define a property on the target element
*
* @param {Object} target
* @param {String} name
* @param {Object} options
*/
Properties.prototype.define = function(target, name, options) {
Object.defineProperty(target, name, options);
};
/**
* Define the descriptor for an element
*/
Properties.prototype.defineDescriptor = function(target, descriptor) {
this.define(target, '$descriptor', { value: descriptor });
};
/**
* Define the model for an element
*/
Properties.prototype.defineModel = function(target, model) {
this.define(target, '$model', { value: model });
};
function isUndefined$1(val) {
return typeof val === 'undefined';
}
function defineProperty(target, property, value) {
Object.defineProperty(target, property.name, {
enumerable: !property.isReference,
writable: true,
value: value,
configurable: true
});
}
//// Moddle implementation /////////////////////////////////////////////////
/**
* @class Moddle
*
* A model that can be used to create elements of a specific type.
*
* @example
*
* var Moddle = require('moddle');
*
* var pkg = {
* name: 'mypackage',
* prefix: 'my',
* types: [
* { name: 'Root' }
* ]
* };
*
* var moddle = new Moddle([pkg]);
*
* @param {Array<Package>} packages the packages to contain
*/
function Moddle(packages) {
this.properties = new Properties(this);
this.factory = new Factory(this, this.properties);
this.registry = new Registry(packages, this.properties);
this.typeCache = {};
}
/**
* Create an instance of the specified type.
*
* @method Moddle#create
*
* @example
*
* var foo = moddle.create('my:Foo');
* var bar = moddle.create('my:Bar', { id: 'BAR_1' });
*
* @param {String|Object} descriptor the type descriptor or name know to the model
* @param {Object} attrs a number of attributes to initialize the model instance with
* @return {Object} model instance
*/
Moddle.prototype.create = function(descriptor, attrs) {
var Type = this.getType(descriptor);
if (!Type) {
throw new Error('unknown type <' + descriptor + '>');
}
return new Type(attrs);
};
/**
* Returns the type representing a given descriptor
*
* @method Moddle#getType
*
* @example
*
* var Foo = moddle.getType('my:Foo');
* var foo = new Foo({ 'id' : 'FOO_1' });
*
* @param {String|Object} descriptor the type descriptor or name know to the model
* @return {Object} the type representing the descriptor
*/
Moddle.prototype.getType = function(descriptor) {
var cache = this.typeCache;
var name = isString(descriptor) ? descriptor : descriptor.ns.name;
var type = cache[name];
if (!type) {
descriptor = this.registry.getEffectiveDescriptor(name);
type = cache[name] = this.factory.createType(descriptor);
}
return type;
};
/**
* Creates an any-element type to be used within model instances.
*
* This can be used to create custom elements that lie outside the meta-model.
* The created element contains all the meta-data required to serialize it
* as part of meta-model elements.
*
* @method Moddle#createAny
*
* @example
*
* var foo = moddle.createAny('vendor:Foo', 'http://vendor', {
* value: 'bar'
* });
*
* var container = moddle.create('my:Container', 'http://my', {
* any: [ foo ]
* });
*
* // go ahead and serialize the stuff
*
*
* @param {String} name the name of the element
* @param {String} nsUri the namespace uri of the element
* @param {Object} [properties] a map of properties to initialize the instance with
* @return {Object} the any type instance
*/
Moddle.prototype.createAny = function(name, nsUri, properties) {
var nameNs = parseName(name);
var element = {
$type: name,
$instanceOf: function(type) {
return type === this.$type;
}
};
var descriptor = {
name: name,
isGeneric: true,
ns: {
prefix: nameNs.prefix,
localName: nameNs.localName,
uri: nsUri
}
};
this.properties.defineDescriptor(element, descriptor);
this.properties.defineModel(element, this);
this.properties.define(element, '$parent', { enumerable: false, writable: true });
forEach(properties, function(a, key) {
if (isObject(a) && a.value !== undefined) {
element[a.name] = a.value;
} else {
element[key] = a;
}
});
return element;
};
/**
* Returns a registered package by uri or prefix
*
* @return {Object} the package
*/
Moddle.prototype.getPackage = function(uriOrPrefix) {
return this.registry.getPackage(uriOrPrefix);
};
/**
* Returns a snapshot of all known packages
*
* @return {Object} the package
*/
Moddle.prototype.getPackages = function() {
return this.registry.getPackages();
};
/**
* Returns the descriptor for an element
*/
Moddle.prototype.getElementDescriptor = function(element) {
return element.$descriptor;
};
/**
* Returns true if the given descriptor or instance
* represents the given type.
*
* May be applied to this, if element is omitted.
*/
Moddle.prototype.hasType = function(element, type) {
if (type === undefined) {
type = element;
element = this;
}
var descriptor = element.$model.getElementDescriptor(element);
return (type in descriptor.allTypesByName);
};
/**
* Returns the descriptor of an elements named property
*/
Moddle.prototype.getPropertyDescriptor = function(element, property) {
return this.getElementDescriptor(element).propertiesByName[property];
};
/**
* Returns a mapped type's descriptor
*/
Moddle.prototype.getTypeDescriptor = function(type) {
return this.registry.typeMap[type];
};
var fromCharCode = String.fromCharCode;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var ENTITY_PATTERN = /&#(\d+);|&#x([0-9a-f]+);|&(\w+);/ig;
var ENTITY_MAPPING = {
'amp': '&',
'apos': '\'',
'gt': '>',
'lt': '<',
'quot': '"'
};
// map UPPERCASE variants of supported special chars
Object.keys(ENTITY_MAPPING).forEach(function(k) {
ENTITY_MAPPING[k.toUpperCase()] = ENTITY_MAPPING[k];
});
function replaceEntities(_, d, x, z) {
// reserved names, i.e.
if (z) {
if (hasOwnProperty.call(ENTITY_MAPPING, z)) {
return ENTITY_MAPPING[z];
} else {
// fall back to original value
return '&' + z + ';';
}
}
// decimal encoded char
if (d) {
return fromCharCode(d);
}
// hex encoded char
return fromCharCode(parseInt(x, 16));
}
/**
* A basic entity decoder that can decode a minimal
* sub-set of reserved names (&) as well as
* hex (ય) and decimal (ӏ) encoded characters.
*
* @param {string} str
*
* @return {string} decoded string
*/
function decodeEntities(s) {
if (s.length > 3 && s.indexOf('&') !== -1) {
return s.replace(ENTITY_PATTERN, replaceEntities);
}
return s;
}
var XSI_URI = 'http://www.w3.org/2001/XMLSchema-instance';
var XSI_PREFIX = 'xsi';
var XSI_TYPE = 'xsi:type';
var NON_WHITESPACE_OUTSIDE_ROOT_NODE = 'non-whitespace outside of root node';
function error(msg) {
return new Error(msg);
}
function missingNamespaceForPrefix(prefix) {
return 'missing namespace for prefix <' + prefix + '>';
}
function getter(getFn) {
return {
'get': getFn,
'enumerable': true
};
}
function cloneNsMatrix(nsMatrix) {
var clone = {}, key;
for (key in nsMatrix) {
clone[key] = nsMatrix[key];
}
return clone;
}
function uriPrefix(prefix) {
return prefix + '$uri';
}
function buildNsMatrix(nsUriToPrefix) {
var nsMatrix = {},
uri,
prefix;
for (uri in nsUriToPrefix) {
prefix = nsUriToPrefix[uri];
nsMatrix[prefix] = prefix;
nsMatrix[uriPrefix(prefix)] = uri;
}
return nsMatrix;
}
function noopGetContext() {
return { 'line': 0, 'column': 0 };
}
function throwFunc(err) {
throw err;
}
/**
* Creates a new parser with the given options.
*
* @constructor
*
* @param {!Object<string, ?>=} options
*/
function Parser(options) {
if (!this) {
return new Parser(options);
}
var proxy = options && options['proxy'];
var onText,
onOpenTag,
onCloseTag,
onCDATA,
onError = throwFunc,
onWarning,
onComment,
onQuestion,
onAttention;
var getContext = noopGetContext;
/**
* Do we need to parse the current elements attributes for namespaces?
*
* @type {boolean}
*/
var maybeNS = false;
/**
* Do we process namespaces at all?
*
* @type {boolean}
*/
var isNamespace = false;
/**
* The caught error returned on parse end
*
* @type {Error}
*/
var returnError = null;
/**
* Should we stop parsing?
*
* @type {boolean}
*/
var parseStop = false;
/**
* A map of { uri: prefix } used by the parser.
*
* This map will ensure we can normalize prefixes during processing;
* for each uri, only one prefix will be exposed to the handlers.
*
* @type {!Object<string, string>}}
*/
var nsUriToPrefix;
/**
* Handle parse error.
*
* @param {string|Error} err
*/
function handleError(err) {
if (!(err instanceof Error)) {
err = error(err);
}
returnError = err;
onError(err, getContext);
}
/**
* Handle parse error.
*
* @param {string|Error} err
*/
function handleWarning(err) {
if (!onWarning) {
return;
}
if (!(err instanceof Error)) {
err = error(err);
}
onWarning(err, getContext);
}
/**
* Register parse listener.
*
* @param {string} name
* @param {Function} cb
*
* @return {Parser}
*/
this['on'] = function(name, cb) {
if (typeof cb !== 'function') {
throw error('required args <name, cb>');
}
switch (name) {
case 'openTag': onOpenTag = cb; break;
case 'text': onText = cb; break;
case 'closeTag': onCloseTag = cb; break;
case 'error': onError = cb; break;
case 'warn': onWarning = cb; break;
case 'cdata': onCDATA = cb; break;
case 'attention': onAttention = cb; break; // <!XXXXX zzzz="eeee">
case 'question': onQuestion = cb; break; // <? .... ?>
case 'comment': onComment = cb; break;
default:
throw error('unsupported event: ' + name);
}
return this;
};
/**
* Set the namespace to prefix mapping.
*
* @example
*
* parser.ns({
* 'http://foo': 'foo',
* 'http://bar': 'bar'
* });
*
* @param {!Object<string, string>} nsMap
*
* @return {Parser}
*/
this['ns'] = function(nsMap) {
if (typeof nsMap === 'undefined') {
nsMap = {};
}
if (typeof nsMap !== 'object') {
throw error('required args <nsMap={}>');
}
var _nsUriToPrefix = {}, k;
for (k in nsMap) {
_nsUriToPrefix[k] = nsMap[k];
}
// FORCE default mapping for schema instance
_nsUriToPrefix[XSI_URI] = XSI_PREFIX;
isNamespace = true;
nsUriToPrefix = _nsUriToPrefix;
return this;
};
/**
* Parse xml string.
*
* @param {string} xml
*
* @return {Error} returnError, if not thrown
*/
this['parse'] = function(xml) {
if (typeof xml !== 'string') {
throw error('required args <xml=string>');
}
returnError = null;
parse(xml);
getContext = noopGetContext;
parseStop = false;
return returnError;
};
/**
* Stop parsing.
*/
this['stop'] = function() {
parseStop = true;
};
/**
* Parse string, invoking configured listeners on element.
*
* @param {string} xml
*/
function parse(xml) {
var nsMatrixStack = isNamespace ? [] : null,
nsMatrix = isNamespace ? buildNsMatrix(nsUriToPrefix) : null,
_nsMatrix,
nodeStack = [],
anonymousNsCount = 0,
tagStart = false,
tagEnd = false,
i = 0, j = 0,
x, y, q, w, v,
xmlns,
elementName,
_elementName,
elementProxy
;
var attrsString = '',
attrsStart = 0,
cachedAttrs // false = parsed with errors, null = needs parsing
;
/**
* Parse attributes on demand and returns the parsed attributes.
*
* Return semantics: (1) `false` on attribute parse error,
* (2) object hash on extracted attrs.
*
* @return {boolean|Object}
*/
function getAttrs() {
if (cachedAttrs !== null) {
return cachedAttrs;
}
var nsUri,
nsUriPrefix,
nsName,
defaultAlias = isNamespace && nsMatrix['xmlns'],
attrList = isNamespace && maybeNS ? [] : null,
i = attrsStart,
s = attrsString,
l = s.length,
hasNewMatrix,
newalias,
value,
alias,
name,
attrs = {},
seenAttrs = {},
skipAttr,
w,
j;
parseAttr:
for (; i < l; i++) {
skipAttr = false;
w = s.charCodeAt(i);
if (w === 32 || (w < 14 && w > 8)) { // WHITESPACE={ \f\n\r\t\v}
continue;
}
// wait for non whitespace character
if (w < 65 || w > 122 || (w > 90 && w < 97)) {
if (w !== 95 && w !== 58) { // char 95"_" 58":"
handleWarning('illegal first char attribute name');
skipAttr = true;
}
}
// parse attribute name
for (j = i + 1; j < l; j++) {
w = s.charCodeAt(j);
if (
w > 96 && w < 123 ||
w > 64 && w < 91 ||
w > 47 && w < 59 ||
w === 46 || // '.'
w === 45 || // '-'
w === 95 // '_'
) {
continue;
}
// unexpected whitespace
if (w === 32 || (w < 14 && w > 8)) { // WHITESPACE
handleWarning('missing attribute value');
i = j;
continue parseAttr;
}
// expected "="
if (w === 61) { // "=" == 61
break;
}
handleWarning('illegal attribute name char');
skipAttr = true;
}
name = s.substring(i, j);
if (name === 'xmlns:xmlns') {
handleWarning('illegal declaration of xmlns');
skipAttr = true;
}
w = s.charCodeAt(j + 1);
if (w === 34) { // '"'
j = s.indexOf('"', i = j + 2);
if (j === -1) {
j = s.indexOf('\'', i);
if (j !== -1) {
handleWarning('attribute value quote missmatch');
skipAttr = true;
}
}
} else if (w === 39) { // "'"
j = s.indexOf('\'', i = j + 2);
if (j === -1) {
j = s.indexOf('"', i);
if (j !== -1) {
handleWarning('attribute value quote missmatch');
skipAttr = true;
}
}
} else {
handleWarning('missing attribute value quotes');
skipAttr = true;
// skip to next space
for (j = j + 1; j < l; j++) {
w = s.charCodeAt(j + 1);
if (w === 32 || (w < 14 && w > 8)) { // WHITESPACE
break;
}
}
}
if (j === -1) {
handleWarning('missing closing quotes');
j = l;
skipAttr = true;
}
if (!skipAttr) {
value = s.substring(i, j);
}
i = j;
// ensure SPACE follows attribute
// skip illegal content otherwise
// example a="b"c
for (; j + 1 < l; j++) {
w = s.charCodeAt(j + 1);
if (w === 32 || (w < 14 && w > 8)) { // WHITESPACE
break;
}
// FIRST ILLEGAL CHAR
if (i === j) {
handleWarning('illegal character after attribute end');
skipAttr = true;
}
}
// advance cursor to next attribute
i = j + 1;
if (skipAttr) {
continue parseAttr;
}
// check attribute re-declaration
if (name in seenAttrs) {
handleWarning('attribute <' + name + '> already defined');
continue;
}
seenAttrs[name] = true;
if (!isNamespace) {
attrs[name] = value;
continue;
}
// try to extract namespace information
if (maybeNS) {
newalias = (
name === 'xmlns'
? 'xmlns'
: (name.charCodeAt(0) === 120 && name.substr(0, 6) === 'xmlns:')
? name.substr(6)
: null
);
// handle xmlns(:alias) assignment
if (newalias !== null) {
nsUri = decodeEntities(value);
nsUriPrefix = uriPrefix(newalias);
alias = nsUriToPrefix[nsUri];
if (!alias) {
// no prefix defined or prefix collision
if (
(newalias === 'xmlns') ||
(nsUriPrefix in nsMatrix && nsMatrix[nsUriPrefix] !== nsUri)
) {
// alocate free ns prefix
do {
alias = 'ns' + (anonymousNsCount++);
} while (typeof nsMatrix[alias] !== 'undefined');
} else {
alias = newalias;
}
nsUriToPrefix[nsUri] = alias;
}
if (nsMatrix[newalias] !== alias) {
if (!hasNewMatrix) {
nsMatrix = cloneNsMatrix(nsMatrix);
hasNewMatrix = true;
}
nsMatrix[newalias] = alias;
if (newalias === 'xmlns') {
nsMatrix[uriPrefix(alias)] = nsUri;
defaultAlias = alias;
}
nsMatrix[nsUriPrefix] = nsUri;
}
// expose xmlns(:asd)="..." in attributes
attrs[name] = value;
continue;
}
// collect attributes until all namespace
// declarations are processed
attrList.push(name, value);
continue;
} /** end if (maybeNs) */
// handle attributes on element without
// namespace declarations
w = name.indexOf(':');
if (w === -1) {
attrs[name] = value;
continue;
}
// normalize ns attribute name
if (!(nsName = nsMatrix[name.substring(0, w)])) {
handleWarning(missingNamespaceForPrefix(name.substring(0, w)));
continue;
}
name = defaultAlias === nsName
? name.substr(w + 1)
: nsName + name.substr(w);
// end: normalize ns attribute name
// normalize xsi:type ns attribute value
if (name === XSI_TYPE) {
w = value.indexOf(':');
if (w !== -1) {
nsName = value.substring(0, w);
// handle default prefixes, i.e. xs:String gracefully
nsName = nsMatrix[nsName] || nsName;
value = nsName + value.substring(w);
} else {
value = defaultAlias + ':' + value;
}
}
// end: normalize xsi:type ns attribute value
attrs[name] = value;
}
// handle deferred, possibly namespaced attributes
if (maybeNS) {
// normalize captured attributes
for (i = 0, l = attrList.length; i < l; i++) {
name = attrList[i++];
value = attrList[i];
w = name.indexOf(':');
if (w !== -1) {
// normalize ns attribute name
if (!(nsName = nsMatrix[name.substring(0, w)])) {
handleWarning(missingNamespaceForPrefix(name.substring(0, w)));
continue;
}
name = defaultAlias === nsName
? name.substr(w + 1)
: nsName + name.substr(w);
// end: normalize ns attribute name
// normalize xsi:type ns attribute value
if (name === XSI_TYPE) {
w = value.indexOf(':');
if (w !== -1) {
nsName = value.substring(0, w);
// handle default prefixes, i.e. xs:String gracefully
nsName = nsMatrix[nsName] || nsName;
value = nsName + value.substring(w);
} else {
value = defaultAlias + ':' + value;
}
}
// end: normalize xsi:type ns attribute value
}
attrs[name] = value;
}
// end: normalize captured attributes
}
return cachedAttrs = attrs;
}
/**
* Extract the parse context { line, column, part }
* from the current parser position.
*
* @return {Object} parse context
*/
function getParseContext() {
var splitsRe = /(\r\n|\r|\n)/g;
var line = 0;
var column = 0;
var startOfLine = 0;
var endOfLine = j;
var match;
var data;
while (i >= startOfLine) {
match = splitsRe.exec(xml);
if (!match) {
break;
}
// end of line = (break idx + break chars)
endOfLine = match[0].length + match.index;
if (endOfLine > i) {
break;
}
// advance to next line
line += 1;
startOfLine = endOfLine;
}
// EOF errors
if (i == -1) {
column = endOfLine;
data = xml.substring(j);
} else
// start errors
if (j === 0) {
data = xml.substring(j, i);
}
// other errors
else {
column = i - startOfLine;
data = (j == -1 ? xml.substring(i) : xml.substring(i, j + 1));
}
return {
'data': data,
'line': line,
'column': column
};
}
getContext = getParseContext;
if (proxy) {
elementProxy = Object.create({}, {
'name': getter(function() {
return elementName;
}),
'originalName': getter(function() {
return _elementName;
}),
'attrs': getter(getAttrs),
'ns': getter(function() {
return nsMatrix;
})
});
}
// actual parse logic
while (j !== -1) {
if (xml.charCodeAt(j) === 60) { // "<"
i = j;
} else {
i = xml.indexOf('<', j);
}
// parse end
if (i === -1) {
if (nodeStack.length) {
return handleError('unexpected end of file');
}
if (j === 0) {
return handleError('missing start tag');
}
if (j < xml.length) {
if (xml.substring(j).trim()) {
handleWarning(NON_WHITESPACE_OUTSIDE_ROOT_NODE);
}
}
return;
}
// parse text
if (j !== i) {
if (nodeStack.length) {
if (onText) {
onText(xml.substring(j, i), decodeEntities, getContext);
if (parseStop) {
return;
}
}
} else {
if (xml.substring(j, i).trim()) {
handleWarning(NON_WHITESPACE_OUTSIDE_ROOT_NODE);
if (parseStop) {
return;
}
}
}
}
w = xml.charCodeAt(i+1);
// parse comments + CDATA
if (w === 33) { // "!"
q = xml.charCodeAt(i+2);
// CDATA section
if (q === 91 && xml.substr(i + 3, 6) === 'CDATA[') { // 91 == "["
j = xml.indexOf(']]>', i);
if (j === -1) {
return handleError('unclosed cdata');
}
if (onCDATA) {
onCDATA(xml.substring(i + 9, j), getContext);
if (parseStop) {
return;
}
}
j += 3;
continue;
}
// comment
if (q === 45 && xml.charCodeAt(i + 3) === 45) { // 45 == "-"
j = xml.indexOf('-->', i);
if (j === -1) {
return handleError('unclosed comment');
}
if (onComment) {
onComment(xml.substring(i + 4, j), decodeEntities, getContext);
if (parseStop) {
return;
}
}
j += 3;
continue;
}
}
// parse question <? ... ?>
if (w === 63) { // "?"
j = xml.indexOf('?>', i);
if (j === -1) {
return handleError('unclosed question');
}
if (onQuestion) {
onQuestion(xml.substring(i, j + 2), getContext);
if (parseStop) {
return;
}
}
j += 2;
continue;
}
// find matching closing tag for attention or standard tags
// for that we must skip through attribute values
// (enclosed in single or double quotes)
for (x = i + 1; ; x++) {
v = xml.charCodeAt(x);
if (isNaN(v)) {
j = -1;
return handleError('unclosed tag');
}
// [10] AttValue ::= '"' ([^<&"] | Reference)* '"' | "'" ([^<&'] | Reference)* "'"
// skips the quoted string
// (double quotes) does not appear in a literal enclosed by (double quotes)
// (single quote) does not appear in a literal enclosed by (single quote)
if (v === 34) { // '"'
q = xml.indexOf('"', x + 1);
x = q !== -1 ? q : x;
} else if (v === 39) { // "'"
q = xml.indexOf("'", x + 1);
x = q !== -1 ? q : x;
} else if (v === 62) { // '>'
j = x;
break;
}
}
// parse attention <! ...>
// previously comment and CDATA have already been parsed
if (w === 33) { // "!"
if (onAttention) {
onAttention(xml.substring(i, j + 1), decodeEntities, getContext);
if (parseStop) {
return;
}
}
j += 1;
continue;
}
// don't process attributes;
// there are none
cachedAttrs = {};
// if (xml.charCodeAt(i+1) === 47) { // </...
if (w === 47) { // </...
tagStart = false;
tagEnd = true;
if (!nodeStack.length) {
return handleError('missing open tag');
}
// verify open <-> close tag match
x = elementName = nodeStack.pop();
q = i + 2 + x.length;
if (xml.substring(i + 2, q) !== x) {
return handleError('closing tag mismatch');
}
// verify chars in close tag
for (; q < j; q++) {
w = xml.charCodeAt(q);
if (w === 32 || (w > 8 && w < 14)) { // \f\n\r\t\v space
continue;
}
return handleError('close tag');
}
} else {
if (xml.charCodeAt(j - 1) === 47) { // .../>
x = elementName = xml.substring(i + 1, j - 1);
tagStart = true;
tagEnd = true;
} else {
x = elementName = xml.substring(i + 1, j);
tagStart = true;
tagEnd = false;
}
if (!(w > 96 && w < 123 || w > 64 && w < 91 || w === 95 || w === 58)) { // char 95"_" 58":"
return handleError('illegal first char nodeName');
}
for (q = 1, y = x.length; q < y; q++) {
w = x.charCodeAt(q);
if (w > 96 && w < 123 || w > 64 && w < 91 || w > 47 && w < 59 || w === 45 || w === 95 || w == 46) {
continue;
}
if (w === 32 || (w < 14 && w > 8)) { // \f\n\r\t\v space
elementName = x.substring(0, q);
// maybe there are attributes
cachedAttrs = null;
break;
}
retur