UNPKG

@haxtheweb/haxcms-nodejs

Version:

HAXcms single and multisite nodejs server, api, and administration

1 lines 2.5 kB
import e from"./path-to-regexp.js";import t from"./matchRoute.js";import r from"./resolveRoute.js";import{toArray as o,ensureRoutes as n,isString as s,getNotFoundError as i,notFoundResult as a}from"../utils.js";class Resolver{constructor(e,t={}){if(Object(e)!==e)throw new TypeError("Invalid routes");this.baseUrl=t.baseUrl||"",this.errorHandler=t.errorHandler,this.resolveRoute=t.resolveRoute||r,this.context=Object.assign({resolver:this},t.context),this.root=Array.isArray(e)?{path:"",__children:e,parent:null,__synthetic:!0}:e,this.root.parent=null}getRoutes(){return[...this.root.__children]}setRoutes(e){n(e);const t=[...o(e)];this.root.__children=t}addRoutes(e){return n(e),this.root.__children.push(...o(e)),this.getRoutes()}removeRoutes(){this.setRoutes([])}resolve(e){const r=Object.assign({},this.context,s(e)?{pathname:e}:e),o=t(this.root,this.__normalizePathname(r.pathname),this.baseUrl),n=this.resolveRoute;let l=null,h=null,u=r;function next(e,t=l.value.route,s){const c=null===s&&l.value.route;return l=h||o.next(c),h=null,e||!l.done&&function isChildRoute(e,t){let r=t;for(;r;)if(r=r.parent,r===e)return!0;return!1}(t,l.value.route)?l.done?Promise.reject(i(r)):(u=Object.assign(u?{chain:u.chain?u.chain.slice(0):[]}:{},r,l.value),function updateChainForRoute(e,t){const{route:r,path:o}=t;if(r&&!r.__synthetic){const t={path:o,route:r};if(e.chain){if(r.parent){let t=e.chain.length;for(;t--&&e.chain[t].route&&e.chain[t].route!==r.parent;)e.chain.pop()}}else e.chain=[];e.chain.push(t)}}(u,l.value),Promise.resolve(n(u)).then((r=>null!=r&&r!==a?(u.result=r.result||r,u):next(e,t,r)))):(h=l,Promise.resolve(a))}return r.next=next,Promise.resolve().then((()=>next(!0,this.root))).catch((e=>{const t=function generateErrorMessage(e){let t=`Path '${e.pathname}' is not properly resolved due to an error.`;const r=(e.route||{}).path;return r&&(t+=` Resolution had failed on route: '${r}'`),t}(u);if(e?console.warn(t):e=new Error(t),e.context=e.context||u,e instanceof DOMException||(e.code=e.code||500),this.errorHandler)return u.result=this.errorHandler(e),u;throw e}))}static __createUrl(e,t){return new URL(e,t)}get __effectiveBaseUrl(){return this.baseUrl?this.constructor.__createUrl(this.baseUrl,document.baseURI||document.URL).href.replace(/[^\/]*$/,""):""}__normalizePathname(e){if(!this.baseUrl)return e;const t=this.__effectiveBaseUrl,r=this.constructor.__createUrl(e,t).href;return r.slice(0,t.length)===t?r.slice(t.length):void 0}}Resolver.pathToRegexp=e;export default Resolver;