wed
Version:
Wed is a schema-aware editor for XML documents.
15 lines • 16.9 kB
JavaScript
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("salve")):"function"==typeof define&&define.amd?define(["salve"],t):"object"==typeof exports?exports["salve-dom"]=t(require("salve")):e["salve-dom"]=t(e.salve)}(window,function(e){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var s=t[n]={i:n,l:!1,exports:{}};return e[n].call(s.exports,s,s.exports,r),s.l=!0,s.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var s in e)r.d(n,s,function(t){return e[t]}.bind(null,s));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=0)}([function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});
/**
* Main module of salve-dom.
* @author Louis-Dominique Dubeau
* @license MPL 2.0
* @copyright Mangalam Research Center for Buddhist Languages
*/
const n=r(1),s=r(2),i=r(3);function o(e,t){return Array.prototype.indexOf.call(e,t)}t.version="5.0.1";const a=Node.ATTRIBUTE_NODE;var l;t.isAttr=void 0!==a?e=>e.nodeType===a:e=>e instanceof Attr,function(e){e[e.INCOMPLETE=1]="INCOMPLETE",e[e.WORKING=2]="WORKING",e[e.INVALID=3]="INVALID",e[e.VALID=4]="VALID"}(l=t.WorkingState||(t.WorkingState={}));class d{constructor(e,t){this.partDone=e,this.portion=t}}class h extends Error{constructor(){super("undefined event_index; _validateUpTo should have taken care of that"),i.fixPrototype(this,h)}}class c{constructor(e,t,r={}){this.schema=e,this.root=t,this._cycleEntered=0,this._timeout=200,this._maxTimespan=100,this._resetting=!1,this._errors=[],this._errorsSeen=Object.create(null),this._boundWrapper=this._workWrapper.bind(this),this._validationEvents=[],this._workingState=l.INCOMPLETE,this._partDone=0,this._validationStage=2,this._previousChild=null,this._validationStack=[new d(0,1)],this._walkerCache=Object.create(null),this._walkerCacheMax=-1,this._prefix="salveDom",this._walkerCacheGap=100,this._events=new s.EventEmitter;const i=["timeout","maxTimespan","walkerCacheGap"];for(const e of i){const t=r[e];if(void 0!==t){if(t<0)throw new Error(`the value for ${e} cannot be negative`);this[`_${e}`]=r[e]}}void 0!==r.prefix&&(this._prefix=r.prefix),this._curEl=this.root,this._setNodeProperty(this._curEl,"EventIndexAfterStart",this._validationEvents.length),this._setWorkingState(l.INCOMPLETE,0),this._validationWalker=this.schema.newWalker(new n.DefaultNameResolver),this.events=this._events}makeKey(e){return`${this._prefix}${e}`}getNodeProperty(e,t){return e[this.makeKey(t)]}_setNodeProperty(e,t,r){e[this.makeKey(t)]=r}_clearNodeProperties(e){const t=e;delete t[this.makeKey("EventIndexAfter")],delete t[this.makeKey("EventIndexAfterStart")],delete t[this.makeKey("EventIndexBeforeAttributes")],delete t[this.makeKey("EventIndexAfterAttributes")],delete t[this.makeKey("PossibleDueToWildcard")],delete t[this.makeKey("ErrorId")]}start(){void 0!==this._timeoutId&&this._stop(l.WORKING),this._timeoutId=setTimeout(this._boundWrapper,0)}getSchemaNamespaces(){return this.schema.getNamespaces()}getDocumentNamespaces(){const e={};return function t(r){if(null===r)return;const n=r.attributes.length;for(let t=0;t<n;++t){const n=r.attributes[t];if(0===n.name.lastIndexOf("xmlns",0)){const t=n.name.slice(6);let r=e[t];void 0===r&&(r=e[t]=[]),r.push(n.value)}}let s=r.firstChild;for(;null!==s;)s.nodeType===Node.ELEMENT_NODE&&t(s),s=s.nextSibling}(this.root.firstChild),e}_workWrapper(){this._work()&&(this._timeoutId=setTimeout(this._boundWrapper,this._timeout))}_work(){const e=Date.now();for(;;){if(this._maxTimespan>0&&Date.now()-e>=this._maxTimespan)return!0;if(!this._cycle())return!1}}_cycle(){if(this._resetting=!1,this._cycleEntered>0)throw new Error("internal error: _cycle is being reentered");if(this._cycleEntered<0)throw new Error("internal error: _cycleEntered negative");this._cycleEntered++;const e=this._validationWalker,t=this._validationStack,r=this._validationEvents;let s=t[0].portion,i=this._validationStage;e:for(;;){let a=this._curEl;switch(i){case 1:{a=a,t.unshift(new d(this._partDone,s)),this._fireAndProcessEvent(e,"enterContext",[],a,0);const l=a.attributes.length;for(let t=0;t<l;++t){const r=a.attributes[t];let n;"xmlns"===r.name?n="":0===r.name.lastIndexOf("xmlns:",0)&&(n=r.name.slice(6)),void 0!==n&&this._fireAndProcessEvent(e,"definePrefix",[n,r.value],a,0)}const h=a.tagName,c=a.parentNode,u=o(c.childNodes,a);let _=e.nameResolver.resolveName(h,!1);return void 0===_&&(this._processEventResult([new n.ValidationError(`cannot resolve the name ${h}`)],c,u),_=new n.EName("",h)),this._setPossibleDueToWildcard(a,e,"enterStartTag",_.ns,_.name),this._fireAndProcessEvent(e,"enterStartTag",[_.ns,_.name],c,u),this._setNodeProperty(a,"EventIndexBeforeAttributes",r.length),this._fireAttributeEvents(e,a),this._setNodeProperty(a,"EventIndexAfterAttributes",r.length),this._fireAndProcessEvent(e,"leaveStartTag",[],a,0),i=this._validationStage=2,this._setNodeProperty(a,"EventIndexAfterStart",r.length),this._cycleEntered--,!0}case 2:{let t,r=null===this._previousChild?a.firstChild:this._previousChild.nextSibling,n="";const l=()=>{if(""!==n){const r=e.fireEvent("text",[n]);if(r instanceof Array){if(void 0===t)throw new Error("flushText running with undefined node");const e=t.parentNode;this._processEventResult(r,e,o(e.childNodes,t))}}n="",t=void 0};for(;null!==r;){switch(r.nodeType){case Node.TEXT_NODE:n+=r.data,void 0===t&&(t=r);break;case Node.ELEMENT_NODE:l(),s/=a.childElementCount,this._curEl=a=r,i=this._validationStage=1,this._previousChild=null;continue e;case Node.COMMENT_NODE:break;default:throw new Error(`unexpected node type: ${r.nodeType}`)}r=r.nextSibling}l(),i=this._validationStage=3;break}case 3:{if(a===this.root){const t=e.end();return t instanceof Array&&this._processEventResult(t,a,a.childNodes.length),this._runDocumentValidation(),this._setNodeProperty(a,"EventIndexAfter",r.length),this._partDone=1,this._stop(this._errors.length>0?l.INVALID:l.VALID),this._cycleEntered--,!1}const o=a,d=a.tagName;let h=e.nameResolver.resolveName(d,!1);void 0===h&&(h=new n.EName("",d)),this._fireAndProcessEvent(e,"endTag",[h.ns,h.name],a,a.childNodes.length),this._fireAndProcessEvent(e,"leaveContext",[],a,a.childNodes.length),this._previousChild=a,this._curEl=a=a.parentNode;let c=this._partDone;if(a!==this.root){t.shift();const e=t[0];c=e.partDone+=s,s=e.portion}return this._setWorkingState(l.WORKING,c),this._setNodeProperty(o,"EventIndexAfter",this._validationEvents.length),i=this._validationStage=2,this._cycleEntered--,!0}default:throw new Error("unexpected state")}}}stop(){this._stop()}_stop(e){void 0!==this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0,void 0===e?this._workingState===l.WORKING&&this._setWorkingState(l.INCOMPLETE,this._partDone):this._setWorkingState(e,this._partDone)}_runDocumentValidation(){}restartAt(e){this.resetTo(e),this.start()}resetTo(e){this._resetting||(this._resetting=!0,this._resetTo(e))}_erase(e){this._clearNodeProperties(e);let t=e.firstElementChild;for(;null!==t;)this._erase(t),t=t.nextElementSibling}_resetTo(e){this._erase(this.root),this._validationStage=2,this._previousChild=null,this._validationWalker=this.schema.newWalker(new n.DefaultNameResolver),this._validationEvents=[],this._curEl=this.root,this._partDone=0,this._errors=[],this._errorsSeen=Object.create(null),this._walkerCache=Object.create(null),this._walkerCacheMax=-1,this._events._emit("reset-errors",{at:0})}_setWorkingState(e,t){let r=!1;this._workingState!==e&&(this._workingState=e,r=!0),this._partDone!==t&&(this._partDone=t,r=!0),r&&this._events._emit("state-update",{state:e,partDone:t})}getWorkingState(){return{state:this._workingState,partDone:this._partDone}}get errors(){return this._errors.slice()}_processEventResult(e,t,r){for(const n of e)this._processError({error:n,node:t,index:r})}_processError(e){const t=e.node,r=`${null==t?"":String((e=>{let t=this.getNodeProperty(e,"ErrorId");return void 0===t&&(t=this._errors.length,this._setNodeProperty(e,"ErrorId",t)),t})(t))},${e.error.toString()}`;!0!==this._errorsSeen[r]&&(this._errorsSeen[r]=!0,this._errors.push(e),this._events._emit("error",e))}_fireAttributeEvents(e,t){const r=t.attributes;for(let t=0;t<r.length;++t){const n=r[t];"xmlns"!==n.name&&0!==n.name.lastIndexOf("xmlns",0)&&(this._fireAttributeNameEvent(e,n)&&this._fireAndProcessEvent(e,"attributeValue",[n.value],n,0))}}_fireAttributeNameEvent(e,t){const r=t.name,s=e.nameResolver.resolveName(r,!0);return void 0===s?(this._processError({error:new n.ValidationError(`cannot resolve attribute name ${r}`),node:t,index:0}),!1):(this._setPossibleDueToWildcard(t,e,"attributeName",s.ns,s.name),this._fireAndProcessEvent(e,"attributeName",[s.ns,s.name],t,0),!0)}_fireAndProcessEvent(e,t,r,n,s){switch(this._validationEvents.push({name:t,params:r}),t){case"enterContext":return void e.nameResolver.enterContext();case"leaveContext":return void e.nameResolver.leaveContext();case"definePrefix":return void e.nameResolver.definePrefix(r[0],r[1]);default:const i=e.fireEvent(t,r);i instanceof Array&&(null!=n&&void 0!==s&&"number"!=typeof s&&(s=o(n.childNodes,s)),this._processEventResult(i,n,s))}}_validateUpTo(e,r,n=!1){if((n=!!n)&&(void 0===e.childNodes||e.childNodes[r].nodeType!==Node.ELEMENT_NODE))throw new Error("trying to validate after attributes but before the end of the start tag on a node which is not an element node");let s=e,i="EventIndexAfter";if(e===this.root&&r<=0){if(n)i="EventIndexAfterAttributes",s=e.childNodes[r];else if(0===r)return}else if(t.isAttr(e))s=e.ownerElement,i="EventIndexBeforeAttributes";else switch(e.nodeType){case Node.TEXT_NODE:null===(s=e.previousElementSibling)&&(s=e.parentNode,i="EventIndexAfterStart");break;case Node.ELEMENT_NODE:case Node.DOCUMENT_FRAGMENT_NODE:case Node.DOCUMENT_NODE:const t=e.childNodes[r],o=void 0===t?e.lastElementChild:t.previousElementSibling;n?(i="EventIndexAfterAttributes",s=t):null!==o?s=o:i="EventIndexAfterStart";break;default:throw new Error(`unexpected node type: ${e.nodeType}`)}for(;void 0===this.getNodeProperty(s,i);)this._cycle()}_getWalkerAt(e,r,s=!1){if((s=!!s)&&(void 0===e.childNodes||e.childNodes[r].nodeType!==Node.ELEMENT_NODE))throw new Error("trying to get a walker for attribute events on a node which is not an element node");if(this._validateUpTo(e,r,s),e===this.root&&r<=0&&!s)return 0===r?this.schema.newWalker(new n.DefaultNameResolver):this._validationWalker;let i;function o(e){if(void 0===i)throw new Error("calling fireTextEvent without a walker");i.fireEvent("text",[e.data])}if(t.isAttr(e)){const t=e.ownerElement;i=this.readyWalker(this.getNodeProperty(t,"EventIndexBeforeAttributes")),"xmlns"!==e.name&&"xmlns"!==e.prefix&&(i=i.clone(),this._fireAttributeNameEvent(i,e))}else switch(e.nodeType){case Node.TEXT_NODE:{const t=e.previousElementSibling;let n,s;null!==t?(n=t,s="EventIndexAfter"):(n=e.parentNode,s="EventIndexAfterStart"),i=this.readyWalker(this.getNodeProperty(n,s)),r>0&&(i=i.clone(),o(e));break}case Node.ELEMENT_NODE:case Node.DOCUMENT_NODE:case Node.DOCUMENT_FRAGMENT_NODE:{const t=e.childNodes[r];let n,a,l;if(s?(a=t,l="EventIndexAfterAttributes"):null!==(n=void 0===t?e.lastElementChild:t.previousElementSibling)?(a=n,l="EventIndexAfter"):(a=e,l="EventIndexAfterStart"),i=this.readyWalker(this.getNodeProperty(a,l)),!s){const e=null!=t?t.previousSibling:null;null!==e&&e!==n&&e.nodeType===Node.TEXT_NODE&&(i=i.clone(),o(e))}break}default:throw new Error(`unexpected node type: ${e.nodeType}`)}return i}readyWalker(e){if(void 0===e)throw new h;const t=this._walkerCache,r=this._walkerCacheMax;let s=t[e];if(void 0!==s)return s;let i=e;if(i>=r)s=t[i=r];else for(;void 0===s&&--i>=0;)s=t[i];void 0!==s?s=s.clone():(s=this.schema.newWalker(new n.DefaultNameResolver),i=0);for(let t=i;t<e;++t){const{name:e,params:r}=this._validationEvents[t];switch(e){case"enterContext":s.nameResolver.enterContext();break;case"leaveContext":s.nameResolver.leaveContext();break;case"definePrefix":s.nameResolver.definePrefix(r[0],r[1]);break;default:s.fireEvent(e,r)}}return e-i>=this._walkerCacheGap&&(t[e]=s,this._walkerCacheMax=Math.max(e,r)),s}possibleAt(e,t,r=!1){return this._getWalkerAt(e,t,r).possible()}possibleWhere(e,t){const r=[],n=t.params;for(const e of n)if("string"!=typeof e)throw new Error("this method does not accept event with name patterns: convert the pattern to a uri, localPart pair");const s=n[0];if("startTagAndAttributes"===s||"attributeNameAndValue"===s)throw new Error(`this method does not support ${s}: you must use granular events instead`);const i=t.toString(),o="enterStartTag"===s||"attributeName"===s;for(let t=0;t<=e.childNodes.length;++t){const a=this.possibleAt(e,t);if(o){for(const e of a)if(e.params[0]===s&&e.params[1].match(n[1],n[2])){r.push(t);break}}else for(const e of a)if(e.toString()===i){r.push(t);break}}return r}speculativelyValidate(e,t,r){let n;if(r instanceof Array){n=e.ownerDocument.createDocumentFragment();for(const e of r)n.insertBefore(e.cloneNode(!0),null)}else n=r.cloneNode(!0);const s=e.ownerDocument.createElement("div");return s.insertBefore(n,null),this.speculativelyValidateFragment(e,t,s)}speculativelyValidateFragment(e,t,r){if(r.nodeType!==Node.ELEMENT_NODE)throw new Error("toParse is not an element");const n=new c(this.schema,r);return n._validationWalker=this._getWalkerAt(e,t).clone(),n._validateUpTo(r,r.childNodes.length),0!==n._errors.length&&n._errors}getErrorsFor(e){const t=e.parentNode;if(null===t)throw new Error("node without a parent!");this._validateUpTo(t,o(t.childNodes,e)+1);const r=[];for(const t of this._errors)t.node===e&&r.push(t);return r}_setPossibleDueToWildcard(e,t,r,n,s){const i=this.getNodeProperty(e,"PossibleDueToWildcard"),o=function(e,t,r,n){const s=e.possible();let i=!1;for(const e of s){if(e.params[0]!==t)continue;const s=e.params[1];if(s.match(r,n)){if(!s.wildcardMatch(r,n))return!1;i=!0}}return i}(t,r,n,s);this._setNodeProperty(e,"PossibleDueToWildcard",o),void 0!==i&&i===o||this._events._emit("possible-due-to-wildcard-change",e)}resolveNameAt(e,t,r,n=!1){return this._getWalkerAt(e,t).nameResolver.resolveName(r,n)}unresolveNameAt(e,t,r,n){return this._getWalkerAt(e,t).nameResolver.unresolveName(r,n)}}t.Validator=c;class u extends Error{constructor(e){super(),this.xmlErrors=e;const t=new Error("cannot parse");this.name="ParsingError",this.stack=t.stack,this.message=t.message,i.fixPrototype(this,u)}}t.ParsingError=u;const _="http://www.w3.org/1999/xhtml",f="http://www.mozilla.org/newlayout/xml/parsererror.xml";t.safeParse=function(e,t=window){const r=new t.DOMParser;let n;try{n=r.parseFromString(e,"text/xml")}catch(e){if("SyntaxError"!==e.name||12!==e.code)throw e;throw new u("no error information available")}if(void 0!==n.getElementsByTagNameNS(f,"parsererror")[0]||void 0!==n.getElementsByTagNameNS(_,"parsererror")[0])throw new u(n.documentElement.outerHTML);return n}},function(t,r){t.exports=e},function(e,t,r){"use strict";
/**
* A listener class.
* @author Louis-Dominique Dubeau
* @license MPL 2.0
* @copyright Mangalam Research Center for Buddhist Languages
*/Object.defineProperty(t,"__esModule",{value:!0});t.EventEmitter=class{constructor(){this._eventListeners=Object.create(null),this._generalListeners=[],this._trace=!1}addEventListener(e,t){if("*"===e)this._generalListeners.push(t);else{let r=this._eventListeners[e];void 0===r&&(r=this._eventListeners[e]=[]),r.push(t)}}addOneTimeEventListener(e,t){const r=(...n)=>(this.removeEventListener(e,r),t.apply(this,n));return this.addEventListener(e,r),r}removeEventListener(e,t){const r="*"===e?this._generalListeners:this._eventListeners[e];if(void 0===r)return;const n=r.lastIndexOf(t);-1!==n&&r.splice(n,1)}removeAllListeners(e){"*"===e?this._generalListeners=[]:this._eventListeners[e]=[]}_emit(e,t){this._trace&&console.log("simple_event_emitter emitting:",e,"with:",t);{let r=this._generalListeners;if(r.length>0){r=r.slice();for(const n of r)if(!1===n.call(void 0,e,t))return}}{let r=this._eventListeners[e];if(void 0!==r&&r.length>0){r=r.slice();for(const e of r)if(!1===e.call(void 0,t))return}}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fixPrototype=function(e,t){(void 0!==Object.getPrototypeOf?Object.getPrototypeOf(e):e.__proto__)!==t&&(void 0!==Object.setPrototypeOf?Object.setPrototypeOf(e,t.prototype):e.__proto__=t.prototype)}}])});
//# sourceMappingURL=salve-dom.min.map.js