@lwrjs/router 0.19.0-alpha.1 → 0.19.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/bundle/prod/lwr/navigation/navigation.js +1 -1
- package/build/bundle/prod/lwr/router/router.js +1 -1
- package/build/bundle/prod/lwr/routerContainer/routerContainer.js +1 -1
- package/build/cjs/modules/lwr/domRouter/domRouter.cjs +10 -0
- package/build/cjs/modules/lwr/domRouterUtils/domRouterUtils.cjs +1 -0
- package/build/cjs/modules/lwr/domRouterUtils/uriUtils.cjs +9 -1
- package/build/cjs/modules/lwr/historyRouter/historyRouter.cjs +6 -1
- package/build/cjs/modules/lwr/navigation/navigationApi.cjs +5 -0
- package/build/cjs/modules/lwr/navigation/navigationMixin.cjs +1 -1
- package/build/cjs/modules/lwr/router/router.cjs +12 -1
- package/build/cjs/modules/lwr/routerContainer/routerContainer.cjs +17 -2
- package/build/cjs/modules/lwr/serverRouter/serverRouter.cjs +4 -0
- package/build/es/modules/lwr/contextUtils/navigationApiStore.d.ts +1 -0
- package/build/es/modules/lwr/domRouter/domRouter.d.ts +8 -2
- package/build/es/modules/lwr/domRouter/domRouter.js +16 -2
- package/build/es/modules/lwr/domRouterUtils/domRouterUtils.d.ts +1 -1
- package/build/es/modules/lwr/domRouterUtils/domRouterUtils.js +1 -1
- package/build/es/modules/lwr/domRouterUtils/uriUtils.d.ts +7 -0
- package/build/es/modules/lwr/domRouterUtils/uriUtils.js +13 -0
- package/build/es/modules/lwr/historyRouter/historyRouter.d.ts +1 -0
- package/build/es/modules/lwr/historyRouter/historyRouter.js +8 -2
- package/build/es/modules/lwr/navigation/navigationApi.d.ts +6 -1
- package/build/es/modules/lwr/navigation/navigationApi.js +9 -1
- package/build/es/modules/lwr/navigation/navigationMixin.js +2 -2
- package/build/es/modules/lwr/router/router.d.ts +2 -2
- package/build/es/modules/lwr/router/router.js +19 -1
- package/build/es/modules/lwr/routerContainer/routerContainer.js +18 -2
- package/build/es/modules/lwr/routerUtils/routerUtils.d.ts +1 -1
- package/build/es/modules/lwr/routerUtils/types.d.ts +9 -2
- package/build/es/modules/lwr/serverRouter/serverRouter.d.ts +4 -0
- package/build/es/modules/lwr/serverRouter/serverRouter.js +7 -0
- package/build/modules/lwr/domRouter/domRouter.js +17 -2
- package/build/modules/lwr/domRouterUtils/domRouterUtils.js +1 -1
- package/build/modules/lwr/domRouterUtils/uriUtils.js +14 -0
- package/build/modules/lwr/historyRouter/historyRouter.js +8 -2
- package/build/modules/lwr/navigation/navigationApi.js +10 -1
- package/build/modules/lwr/navigation/navigationMixin.js +2 -2
- package/build/modules/lwr/router/router.js +21 -0
- package/build/modules/lwr/routerContainer/routerContainer.js +18 -2
- package/build/modules/lwr/serverRouter/serverRouter.js +8 -0
- package/package.json +7 -6
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(e){if(null==e)throw new TypeError("Provider must be defined.")}class t{constructor(e){this.infoMap=new WeakMap,this.defaultValue=void 0,this.defaultValue=e}getInfo(e){let t=this.infoMap.get(e);return void 0===t&&(t={consumers:new Set},this.infoMap.set(e,t)),t}setContext(t,
|
|
1
|
+
function e(e){if(null==e)throw new TypeError("Provider must be defined.")}class t{constructor(e){this.infoMap=new WeakMap,this.defaultValue=void 0,this.defaultValue=e}getInfo(e){let t=this.infoMap.get(e);return void 0===t&&(t={consumers:new Set},this.infoMap.set(e,t)),t}setContext(t,n){e(t);const o=n,s=this.getInfo(t);s.contextValue=n,s.consumers.forEach((e=>e.provide(o))),0===s.consumers.size&&o?.onComplete&&o.onComplete()}getContext(t){e(t);const{contextValue:n}=this.getInfo(t);return void 0!==n?n:this.defaultValue}clearContext(t){e(t),this.infoMap.delete(t)}subscribeContext(t,n){e(t);const{consumers:o,contextValue:s}=this.getInfo(t);o.has(n)||(o.add(n),n.provide(s))}unsubscribeContext(t,n){e(t),this.getInfo(t).consumers.delete(n)}}const n="LWR",o=1;function s(e,t){return Array.isArray(t)?e.replace(/\{([0-9]+)\}/g,((e,n)=>t[n])):e}function a(e,t){return`${e.code}: ${s(e.message,t)}`}function i(e,t){const n={...e,message:s(e.message,t)};return e.address&&(n.address=s(e.address,t)),e.stack&&(n.stack=s(e.stack,t)),n}const r={INVALID_MIXIN_CMP:{code:`${n}4001`,message:"{0} must be an Element type",level:o},MISSING_CONTEXT:{code:`${n}4002`,message:"Could not find context to perform navigation action.",level:o},INVALID_CONTEXT:{code:`${n}4003`,message:"Cannot register navigation context; it must have this shape: { navigate, generateUrl, subscribe }",level:o},MULTIPLE_ROOTS:{code:`${n}4004`,message:"Router connection failed. There can only be one root router.",level:o},MULTIPLE_CHILDREN:{code:`${n}4005`,message:"Could not add to the navigation hierarchy. There can only be one child per navigation node.",level:o},MISSING_ROUTE:{code:`${n}4006`,message:'A route cannot be created to navigate to URL "{0}"',level:o,address:"{0}"},MISSING_URL:{code:`${n}4007`,message:'A URL cannot be created to navigate to route "{0}"',level:o,address:"{0}"},PRENAV_FAILED:{code:`${n}4008`,message:'A preNavigate hook listener blocked routing to "{0}"',level:2,address:"{0}"},MISSING_ROUTE_TEMPLATE:{code:`${n}4009`,message:'Route definition with id "{0}" is missing a "uri" property.',level:o,address:"{0}"},MISSING_ROUTE_CMP:{code:`${n}4016`,message:"Expected a route view component with a default export.",level:o},MISSING_DATA_CONTEXT:{code:`${n}4018`,message:"Could not find context to retrieve navigation data.",level:o},INVALID_ROUTE_QUERY:{code:`${n}4019`,message:"Invalid query param in route definition.",level:o},MISSING_PAGE_BINDING:{code:`${n}4020`,message:'Route definition with id "{0}" is missing a "page" binding.',level:o,address:"{0}"},INVALID_PAGE_BINDING:{code:`${n}4021`,message:'Route definition with id "{0}" has an invalid "page" binding.',level:o,address:"{0}"},INVALID_URI_SYNTAX:{code:`${n}4022`,message:'Route definition with id "{0}" has invalid "uri" syntax. URI cannot contain *, +, (, ), ',level:o,address:"{0}"},VIEW_IMPORT_FAILED:{code:`${n}4023`,message:'Error importing view with name "{0}", failure was: {1}',level:o,stack:"{2}"},VIEW_MISSING:{code:`${n}4024`,message:'Expected a view with name "{0}" in the viewset',level:o},VIEW_IMPORT_FAILED_WITH_SPECIFIER:{code:`${n}4025`,message:'Error importing module "{0}" from view with name "{1}", failure was: {2}',level:o,stack:"{3}"},NO_ROUTE_MATCH:{code:`${n}4026`,message:"A routing match cannot be found for: {0}",level:o},INVALID_ROUTE_HANDLER:{code:`${n}4027`,message:'Route definition "{0}" does not have a valid route handler module',level:o},DESTINATION_NOT_FOUND:{code:`${n}4028`,message:"Route handler returned 404: Not Found",level:o},DESTINATION_ERROR:{code:`${n}4029`,message:"Route handler returned error status {0}: {1}",level:o,stack:"{2}"},NO_INIT_URL:{code:`${n}4030`,message:'Cannot initialize a server router without a "url"',level:o}},c=new WeakMap;function l(e){const t=c.get(e);if(!t||!t.value)throw new Error(a(r.MISSING_CONTEXT));return t.value}function d(e,t){const n={id:e,value:t,update:e=>{n.value=e}};return c.set(n.id,n),n}function u(e){var t;return(t=class{constructor(e){this._callback=void 0,this._callback=e}connect(){}disconnect(){}update(e,t){t&&this._callback(t)}static setContext(t,n){e.setContext(t,n)}static getContext(t){return e.getContext(t)}static clearContext(t){e.clearContext(t)}static subscribeContext(t,n){e.subscribeContext(t,n)}static unsubscribeContext(t,n){e.unsubscribeContext(t,n)}}).contextSchema={value:"required"},t}const I=u(new t(void 0)),v=u(new t(void 0)),g=new t(void 0),m=class extends(u(g)){async update(e,t){if(t){const n=e&&e.viewName?e.viewName:"default",o=t.viewset[n],s=o,a=s&&s.module||o;let c;if(a)try{const e=await a(),t=e&&e.default;if(!t||void 0===t.constructor)throw new Error("error occurred with view import");this._callback(t)}catch(e){const t=e;c=s.specifier?i(r.VIEW_IMPORT_FAILED_WITH_SPECIFIER,[s.specifier,n,t.message,t.stack||""]):i(r.VIEW_IMPORT_FAILED,[n,t.message,t.stack||""])}else c=i(r.VIEW_MISSING,[n]);t.onComplete&&t.onComplete(c)}}};function h(e,t,n,o){l(e).navigate(t,n,o)}function f(e,t,n){return l(e).generateUrl(t,n)}const _=`universalcontainergetnavigationcontext${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}`,E=Symbol("Navigate"),N=Symbol("GenerateUrl"),p=Symbol("NavContext"),w=Symbol("NavContext"),C="undefined"==typeof window;function T(e){!function(e,t,n){if(!e)throw new Error(a(t,n))}("function"==typeof e.prototype.dispatchEvent,r.INVALID_MIXIN_CMP,[e.toString()]);return class extends e{[w](){if(!this[p]&&(this.dispatchEvent(new CustomEvent(_,{bubbles:!0,composed:!0,detail:{callback:e=>{this[p]=e}}})),!this[p]))throw new Error(a(r.MISSING_CONTEXT))}[E](e,t,n){C||(this[w](),h(this[p],e,t,n))}async[N](e,t){return C?null:(this[w](),function(e,t,n){return l(e).generateUrlAsync(t,n)}(this[p],e,t))}}}T.Navigate=E,T.GenerateUrl=N,T.NavContext=p;export{t as ContextInfo,v as CurrentPageReference,m as CurrentView,I as NavigationContext,T as NavigationMixin,u as generateContextualWireAdapter,f as generateUrl,l as getNavigationHelm,h as navigate,d as registerNavigationHelm};
|
|
2
2
|
//# sourceMappingURL=navigation.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(e=""){return e=e||"",decodeURIComponent(e)}function t(e){"/"!==(e=e||"/").charAt(0)&&(e="/"+e);const t=e.match(/^[^#?]+/);if(null!==t){const e=t[0];return"/"===e?"/":e.replace(/\/$/,"")}return"/"}function n(t){const n=(t=t||"").indexOf("#");n>=0&&(t=t.substring(0,n));const r=t.indexOf("?"),o=r>=0?t.substr(r+1):null,i={};return o&&o.split("&").forEach((t=>{if(t.indexOf("=")>=0){const[n,r=""]=t.split("=");i[e(n)]=e(r)}else i[e(t)]=null})),i}function r(e={}){const t=Object.keys(e);return t.length?`?${t.map((t=>{const n=e[t];return null===n?t:`${t}=${function(e=""){return e=e||"",encodeURIComponent(e)}(n)}`})).join("&")}`:""}function o(e){return!!(e&&e.length>1)&&e.startsWith(":")}function i(e){return!!e&&(!!o(e)&&e.substr(1))}function s(e){return Object.values(e).reduce(((e,{routeParamName:t})=>{const n=i(t);return n&&e.push(n),e}),[])}function a(t,n){const{regex:r,params:o}=n,i=r.exec(t);if(i){const[,...t]=i,n={};return o.forEach(((r,o)=>{const{name:i}=r,s=t[o];n[i]=s?e(s):s})),n}return null}function c(t,n){if(t&&n){const{queryMatcher:r}=n,o=r(t);if(o){const t={};return Object.keys(o).forEach((n=>{const r=o[n],{value:i,routeParamName:s}=r,a=s?s.substr(1):n;t[a]=i?e(i):i})),t}}return null}function u(e,r){if(r){const{original:{page:{type:i="",attributes:s={},state:u={}}={}}={}}=r,l=t(e),f=n(e),d=a(l,r),p=c(f,r);if(d&&p){const e={...d,...p},t={};Object.keys(s).forEach((n=>{const r=s[n];let i;if(r&&o(r)){const t=r.substr(1);i=e[t]}else i=r;t[n]=i}));const n={};Object.keys(u).forEach((t=>{const r=u[t];let i;if(r&&o(r)){const t=r.substr(1);i=e[t]}else i=r;n[t]=i}));const a=function(e,t){const{compiledQuery:n}=t,r=Object.keys(n).filter((e=>{const{literalValue:t}=n[e];return!t})),o={};return Object.keys(e).forEach((t=>{const n=e[t];r.indexOf(t)<0&&(o[t]=n)})),o}(f,r);return{type:i,attributes:{...t},state:{...a,...n}}}}return null}const l={locale:"en-US",defaultLocale:"en-US"};function f(e,r){const o=t(e),i=n(e),s=r?r.filter((e=>e.regex.test(o))):[],[u]=s.filter((e=>{const{queryMatcher:t}=e;return t(i)&&function(e,t,n){const{original:{patterns:r=null}={}}=n||{};if(r){const o={...a(e,n),...c(t,n)};return Object.keys(r).every((e=>{const t=r[e],n=new RegExp(t),i=o[e]||"";return n.test(i)}))}return!0}(o,i,e)}));return u||null}function d(e,t,n="",r=l,o){if(!n||e!==n&&0!==e?.search(new RegExp(`^${n}[/?#]`))||(e=e.replace(n,"")),o?.locale||r?.locale){const t=`/${o?.locale||r.locale}`;e!==t&&0!==e?.search(new RegExp(`^${t}[/?#]`))||(e=e.replace(t,""))}const i=f(e,t);let s;if(!i)return null;{const t=u(e,i);if(t){return s={route:{id:i.original.id,attributes:{...t.attributes},state:{...t.state},pageReference:{type:t.type,attributes:{...t.attributes},state:{...t.state}}},routeDefinition:i},s}}return null}function p(e,t,n="",r=l,i){const s=function(e,t){if(!e)return null;const{type:n,attributes:r={},state:i={}}=e;if(n){const[e]=t.filter((e=>{const{original:{page:{type:t=null,attributes:s={},state:a={}}={}}}=e,c=t===n,u=Object.keys(s).every((e=>Object.keys(r).indexOf(e)>=0)),l=Object.keys(s).length===Object.keys(r).length,f=Object.keys(a).every((e=>Object.keys(i).indexOf(e)>=0)),d=Object.keys(s).filter((e=>{const t=s[e];return!t||!o(t)})).every((e=>s[e]===r[e])),p=Object.keys(a).filter((e=>{const t=a[e];return null===t||!o(t)})).every((e=>a[e]===i[e]));return c&&u&&l&&d&&f&&p}));return e||null}return null}(e,t);return s?g(e,s,n,r,i):null}function h(e,t,n){const{attributeBindings:r,stateBindings:o}=n,{attributes:s,state:a}=t,c={};return e.forEach((e=>{const[t]=Object.keys(r).filter((t=>i(r[t])===e));if(t)c[e]=s[t];else{const[t]=Object.keys(o).filter((t=>i(o[t])===e));t&&(c[e]=a[t])}})),c}function g(e,t,n="",a=l,c){const{params:u,original:{page:f={}}={},toPath:d,compiledQuery:p}=t,{attributes:g={},state:m={}}=f,E=d(h(u.filter((({name:e})=>"string"==typeof e)).map((({name:e})=>e)),e,{attributeBindings:g,stateBindings:m})),y=function(e,t,n){const{compiledQuery:r,original:{page:{state:s={}}}}=n,{state:a={}}=e||{},c={};Object.keys(a).filter((e=>!o(s[e]))).forEach((e=>c[e]=a[e]));const u={};return Object.keys(t).forEach((e=>{const n=t[e],[o]=Object.keys(r).filter((t=>{const n=r[t],{routeParamName:o}=n;return i(o)===e}));if(o){u[o]=n}})),{...c,...u}}(e,h(s(p),e,{attributeBindings:g,stateBindings:m}),t),b=r(y),R=c?.locale||a&&a.locale;return`${n}${R!==a.defaultLocale?`/${R}`:""}${E}${b}`}function m(e,t=2){if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e))try{Object.freeze(e),t>0&&Object.keys(e).forEach((n=>{if(function(e,t){return t in e}(e,n)){const r=e[n];r&&"object"==typeof r&&m(r,t-1)}}))}catch(e){}return e}const E="LWR",y=1;function b(e,t){return Array.isArray(t)?e.replace(/\{([0-9]+)\}/g,((e,n)=>t[n])):e}function R(e,t){return`${e.code}: ${b(e.message,t)}`}function I(e,t){const n={...e,message:b(e.message,t)};return e.address&&(n.address=b(e.address,t)),e.stack&&(n.stack=b(e.stack,t)),n}function v(e,t,n){if(!e)throw new Error(R(t,n))}const $={INVALID_MIXIN_CMP:{code:`${E}4001`,message:"{0} must be an Element type",level:y},MISSING_CONTEXT:{code:`${E}4002`,message:"Could not find context to perform navigation action.",level:y},INVALID_CONTEXT:{code:`${E}4003`,message:"Cannot register navigation context; it must have this shape: { navigate, generateUrl, subscribe }",level:y},MULTIPLE_ROOTS:{code:`${E}4004`,message:"Router connection failed. There can only be one root router.",level:y},MULTIPLE_CHILDREN:{code:`${E}4005`,message:"Could not add to the navigation hierarchy. There can only be one child per navigation node.",level:y},MISSING_ROUTE:{code:`${E}4006`,message:'A route cannot be created to navigate to URL "{0}"',level:y,address:"{0}"},MISSING_URL:{code:`${E}4007`,message:'A URL cannot be created to navigate to route "{0}"',level:y,address:"{0}"},PRENAV_FAILED:{code:`${E}4008`,message:'A preNavigate hook listener blocked routing to "{0}"',level:2,address:"{0}"},MISSING_ROUTE_TEMPLATE:{code:`${E}4009`,message:'Route definition with id "{0}" is missing a "uri" property.',level:y,address:"{0}"},MISSING_ROUTE_CMP:{code:`${E}4016`,message:"Expected a route view component with a default export.",level:y},MISSING_DATA_CONTEXT:{code:`${E}4018`,message:"Could not find context to retrieve navigation data.",level:y},INVALID_ROUTE_QUERY:{code:`${E}4019`,message:"Invalid query param in route definition.",level:y},MISSING_PAGE_BINDING:{code:`${E}4020`,message:'Route definition with id "{0}" is missing a "page" binding.',level:y,address:"{0}"},INVALID_PAGE_BINDING:{code:`${E}4021`,message:'Route definition with id "{0}" has an invalid "page" binding.',level:y,address:"{0}"},INVALID_URI_SYNTAX:{code:`${E}4022`,message:'Route definition with id "{0}" has invalid "uri" syntax. URI cannot contain *, +, (, ), ',level:y,address:"{0}"},VIEW_IMPORT_FAILED:{code:`${E}4023`,message:'Error importing view with name "{0}", failure was: {1}',level:y,stack:"{2}"},VIEW_MISSING:{code:`${E}4024`,message:'Expected a view with name "{0}" in the viewset',level:y},VIEW_IMPORT_FAILED_WITH_SPECIFIER:{code:`${E}4025`,message:'Error importing module "{0}" from view with name "{1}", failure was: {2}',level:y,stack:"{3}"},NO_ROUTE_MATCH:{code:`${E}4026`,message:"A routing match cannot be found for: {0}",level:y},INVALID_ROUTE_HANDLER:{code:`${E}4027`,message:'Route definition "{0}" does not have a valid route handler module',level:y},DESTINATION_NOT_FOUND:{code:`${E}4028`,message:"Route handler returned 404: Not Found",level:y},DESTINATION_ERROR:{code:`${E}4029`,message:"Route handler returned error status {0}: {1}",level:y,stack:"{2}"},NO_INIT_URL:{code:`${E}4030`,message:'Cannot initialize a server router without a "url"',level:y}};function O(e){return e.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}function N(e){return e&&e.sensitive?"":"i"}function _(e,t={}){const n=function(e){const t=[];let n=0;for(;n<e.length;){const r=e[n];if("*"!==r&&"+"!==r&&"?"!==r)if("\\"!==r)if("{"!==r)if("}"!==r)if(":"!==r)if("("!==r)t.push({type:"CHAR",index:n,value:e[n++]});else{let r=1,o="",i=n+1;if("?"===e[i])throw new TypeError(`Pattern cannot start with "?" at ${i}`);for(;i<e.length;)if("\\"!==e[i]){if(")"===e[i]){if(r--,0===r){i++;break}}else if("("===e[i]&&(r++,"?"!==e[i+1]))throw new TypeError(`Capturing groups are not allowed at ${i}`);o+=e[i++]}else o+=e[i++]+e[i++];if(r)throw new TypeError(`Unbalanced pattern at ${n}`);if(!o)throw new TypeError(`Missing pattern at ${n}`);t.push({type:"PATTERN",index:n,value:o}),n=i}else{let r="",o=n+1;for(;o<e.length;){const t=e.charCodeAt(o);if(!(t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95===t))break;r+=e[o++]}if(!r)throw new TypeError(`Missing parameter name at ${n}`);t.push({type:"NAME",index:n,value:r}),n=o}else t.push({type:"CLOSE",index:n,value:e[n++]});else t.push({type:"OPEN",index:n,value:e[n++]});else t.push({type:"ESCAPED_CHAR",index:n++,value:e[n++]});else t.push({type:"MODIFIER",index:n,value:e[n++]})}return t.push({type:"END",index:n,value:""}),t}(e),{prefixes:r="./"}=t,o=`[^${O(t.delimiter||"/#?")}]+?`,i=[];let s=0,a=0,c="";const u=e=>{if(a<n.length&&n[a].type===e)return n[a++].value},l=e=>{const t=u(e);if(void 0!==t)return t;const{type:r,index:o}=n[a];throw new TypeError(`Unexpected ${r} at ${o}, expected ${e}`)},f=()=>{let e,t="";for(;e=u("CHAR")||u("ESCAPED_CHAR");)t+=e;return t};for(;a<n.length;){const e=u("CHAR"),t=u("NAME"),n=u("PATTERN");if(t||n){let a=e||"";-1===r.indexOf(a)&&(c+=a,a=""),c&&(i.push(c),c=""),i.push({name:t||s++,prefix:a,suffix:"",pattern:n||o,modifier:u("MODIFIER")||""});continue}const a=e||u("ESCAPED_CHAR");if(a){c+=a;continue}c&&(i.push(c),c="");if(u("OPEN")){const e=f(),t=u("NAME")||"",n=u("PATTERN")||"",r=f();l("CLOSE"),i.push({name:t||(n?s++:""),pattern:t&&!n?o:n,prefix:e,suffix:r,modifier:u("MODIFIER")||""})}else l("END")}return i}function w(e,t){return function(e,t={}){const n=N(t),{encode:r=e=>e,validate:o=!0}=t,i=e.map((e=>{if("object"==typeof e)return new RegExp(`^(?:${e.pattern})$`,n)}));return t=>{let n="";for(let s=0;s<e.length;s++){const a=e[s];if("string"==typeof a){n+=a;continue}const c=t?t[a.name]:void 0,u="?"===a.modifier||"*"===a.modifier,l="*"===a.modifier||"+"===a.modifier;if(Array.isArray(c)){if(!l)throw new TypeError(`Expected "${a.name}" to not repeat, but got an array`);if(0===c.length){if(u)continue;throw new TypeError(`Expected "${a.name}" to not be empty`)}for(let e=0;e<c.length;e++){const t=r(c[e],a);if(o&&!i[s].test(t))throw new TypeError(`Expected all "${a.name}" to match "${a.pattern}", but got "${t}"`);n+=a.prefix+t+a.suffix}continue}if("string"==typeof c||"number"==typeof c){const e=r(String(c),a);if(o&&!i[s].test(e))throw new TypeError(`Expected "${a.name}" to match "${a.pattern}", but got "${e}"`);n+=a.prefix+e+a.suffix;continue}if(u)continue;const f=l?"an array":"a string";throw new TypeError(`Expected "${a.name}" to be ${f}`)}return n}}(_(e,t),t)}function x(e,t,n){return function(e,t,n={}){const{strict:r=!1,start:o=!0,end:i=!0,encode:s=e=>e}=n,a=`[${O(n.endsWith||"")}]|$`,c=`[${O(n.delimiter||"/#?")}]`;let u=o?"^":"";for(const n of e)if("string"==typeof n)u+=O(s(n));else{const e=O(s(n.prefix)),r=O(s(n.suffix));if(n.pattern)if(t&&t.push(n),e||r)if("+"===n.modifier||"*"===n.modifier){const t="*"===n.modifier?"?":"";u+=`(?:${e}((?:${n.pattern})(?:${r}${e}(?:${n.pattern}))*)${r})${t}`}else u+=`(?:${e}(${n.pattern})${r})${n.modifier}`;else u+=`(${n.pattern})${n.modifier}`;else u+=`(?:${e}${r})${n.modifier}`}if(i)r||(u+=`${c}?`),u+=n.endsWith?`(?=${a})`:"$";else{const t=e[e.length-1],n="string"==typeof t?c.indexOf(t[t.length-1])>-1:void 0===t;r||(u+=`(?:${c}(?=${a}))?`),n||(u+=`(?=${c}|${a})`)}return new RegExp(u,N(n))}(_(e,n),t,n)}function A(e,t,n){return e instanceof RegExp?function(e,t){if(!t)return e;const n=e.source.match(/\((?!\?)/g);if(n)for(let e=0;e<n.length;e++)t.push({name:e,prefix:"",suffix:"",modifier:"",pattern:""});return e}(e,t):Array.isArray(e)?function(e,t,n){const r=e.map((e=>A(e,t,n).source));return new RegExp(`(?:${r.join("|")})`,N(n))}(e,t,n):x(e,t,n)}const{INVALID_ROUTE_QUERY:T,MISSING_ROUTE_TEMPLATE:D,MISSING_PAGE_BINDING:U,INVALID_PAGE_BINDING:P,INVALID_URI_SYNTAX:C}=$;function S(e){const{routes:r,caseSensitive:a}=e;return r.map((e=>function(e,r=!1){const a=[],{id:c,uri:u,page:l}=e;v(!!u,I(D,[c])),v(function(e=""){const t=["*","(",")",";"].some((t=>e.indexOf(t)>=0));return!t}(u),I(C,[c])),v(!!l,I(U,[c]));const f=t(u),d=n(u),p=A(f,a,{sensitive:r,end:!1!==e.exact}),h=w(f,{encode:encodeURIComponent}),g=function(e){const t={};return Object.keys(e).forEach((n=>{const r=e[n];v(!o(n)||null===r,T),o(n)?t[n.substr(1)]={routeParamName:n}:r&&o(r)?t[n]={routeParamName:r}:t[n]={literalValue:null===r?null:r}})),t}(d),m=function(e,t=!1){const n=n=>{const r=Object.keys(n),o=Object.keys(e);return o.every((e=>r.indexOf(e)>=0))?o.reduce(((r,o)=>{if(null===r)return null;const{literalValue:i,routeParamName:s}=e[o],a=n[o];let c=!0;return"string"==typeof i?c=t?i===a:i.toUpperCase()===(null==a?a:a.toUpperCase()):null===i&&(c=a===i),r=c?{...r,[o]:{value:a,routeParamName:s}}:null}),{}):null};return n}(g,r),E={original:e,regex:p,params:a,toPath:h,compiledQuery:g,queryMatcher:m};return v(function(e){const{original:{page:t}={},params:n,compiledQuery:r}=e,a=t?t.type:t,c=(t?t.attributes:t)||{},u=(t?t.state:t)||{};if("string"!=typeof a||"object"!=typeof c||"object"!=typeof u)return!1;const l=Object.values(n).map((({name:e})=>e)),f=s(r),d=[...l,...f],p=Object.values(c).filter(o).map(i),h=Object.values(u).filter(o).map(i),g=d.every((e=>"string"==typeof e&&(p.indexOf(e)>=0||h.indexOf(e)>=0))),m=d.length===p.length+h.length;return!!(t&&a&&c&&u&&g&&m)}(E),I(P,[c])),E}(e,a)))}function j(){let e,t,n=[];const r=r=>{n.filter((e=>null!==e)).forEach((e=>e.error&&e.error(r))),e=void 0,t=r};return{next:r=>{n.filter((e=>null!==e)).forEach((e=>e.next&&e.next(r))),e=r,t=void 0},error:r,complete:()=>{n.filter((e=>null!==e)).forEach((e=>e.complete&&e.complete())),n=[],e=void 0,t=void 0},subscribe:(o,i=!0)=>{(e=>{n.push(e)})(o),e&&i&&o.next(e),t&&r(t);const s=n.length-1;return{unsubscribe:()=>(e=>{n=[...n.slice(0,e),...n.slice(e+1)]})(s)}}}}class M{constructor(e){this.deprecatedConfig={},this.routeHandlerId=0,this.compiledRoutes=[],this.routeObservable=j(),this.config={basePath:e.basePath||"",i18n:e.i18n||l,caseSensitive:Boolean(e.caseSensitive),routes:e.routes||[],generateUrl:(e,t)=>p(e,this.compiledRoutes,this.config.basePath,this.config.i18n,t),parseUrl:e=>function(e,t,n="",r=l){const o=d(e,t,n,r);return o&&o.route&&o.route.pageReference?o.route.pageReference:null}(e,this.compiledRoutes,this.config.basePath,this.config.i18n)};const{DEPRECATED_getRouteFromUrl:t,DEPRECATED_getUrlFromRoute:n}=e;t&&(this.deprecatedConfig.DEPRECATED_getRouteFromUrl=t),n&&(this.deprecatedConfig.DEPRECATED_getUrlFromRoute=n),this.compiledRoutes=S(this.config)}generateUrl(e,t){const{DEPRECATED_getUrlFromRoute:n}=this.deprecatedConfig;return n?n(e,this.config.generateUrl,t):this.config.generateUrl(e,t)}parseUrl(e){const{DEPRECATED_getRouteFromUrl:t}=this.deprecatedConfig;return t?t(e,this.config.parseUrl):this.config.parseUrl(e)}matchRoute(e,t){const n="string"==typeof e?e:this.generateUrl(e,t);if(null===n)return null;const r=d(n,this.compiledRoutes,this.config.basePath,this.config.i18n,t),o=r&&g(r.route.pageReference,r.routeDefinition,this.config.basePath,this.config.i18n,t);return r&&o?{pathMatch:o,route:r.route,routeDefinition:r.routeDefinition.original}:null}async resolveView(e,t){return new Promise(((n,r)=>{const o=this.matchRoute(e,t);return o?o.routeDefinition.handler?.().then((e=>{const t=e.default;if(!t)return r(R($.INVALID_ROUTE_HANDLER,[o.routeDefinition.id]));const i=new t(n);i&&i.update(o.route)})):r(R($.NO_ROUTE_MATCH,[JSON.stringify(e)]))}))}navigate(e,t){const n=this.matchRoute(e,t);if(!n)throw new Error(R($.MISSING_ROUTE,[JSON.stringify(e)]));this.pendingRoute={...n},this._mapView(this.pendingRoute)}subscribe(e,t){return this.routeObservable.subscribe({next:e,error:()=>{},complete:()=>{}},Boolean(t))}async _mapView(e){const t=Math.random();this.routeHandlerId=t;const n=await(e.routeDefinition.handler?.()),r=n?.default;if(!r)throw new Error(R($.INVALID_ROUTE_HANDLER,[e.routeDefinition.id]));return this.routeHandler=new r((e=>{this._updateView(t,e)})),this.routeHandler&&this.routeHandler.update(e.route),!0}_updateView(e,t){if(!t||e!==this.routeHandlerId)return;if(!this.pendingRoute)throw new Error("Trying to commit route state without a route");const n=m(t.viewset);this.routeObservable.next({...this.pendingRoute,...t,viewset:n})}}function k(e={}){return new M(e)}export{k as createRouter};
|
|
1
|
+
function e(e=""){return e=e||"",decodeURIComponent(e)}function t(e){"/"!==(e=e||"/").charAt(0)&&(e="/"+e);const t=e.match(/^[^#?]+/);if(null!==t){const e=t[0];return"/"===e?"/":e.replace(/\/$/,"")}return"/"}function n(t){const n=(t=t||"").indexOf("#");n>=0&&(t=t.substring(0,n));const r=t.indexOf("?"),o=r>=0?t.substr(r+1):null,i={};return o&&o.split("&").forEach((t=>{if(t.indexOf("=")>=0){const[n,r=""]=t.split("=");i[e(n)]=e(r)}else i[e(t)]=null})),i}function r(e={}){const t=Object.keys(e);return t.length?`?${t.map((t=>{const n=e[t];return null===n?t:`${t}=${function(e=""){return e=e||"",encodeURIComponent(e)}(n)}`})).join("&")}`:""}function o(e){return!!(e&&e.length>1)&&e.startsWith(":")}function i(e){return!!e&&(!!o(e)&&e.substr(1))}function s(e){return Object.values(e).reduce(((e,{routeParamName:t})=>{const n=i(t);return n&&e.push(n),e}),[])}function a(t,n){const{regex:r,params:o}=n,i=r.exec(t);if(i){const[,...t]=i,n={};return o.forEach(((r,o)=>{const{name:i}=r,s=t[o];n[i]=s?e(s):s})),n}return null}function c(t,n){if(t&&n){const{queryMatcher:r}=n,o=r(t);if(o){const t={};return Object.keys(o).forEach((n=>{const r=o[n],{value:i,routeParamName:s}=r,a=s?s.substr(1):n;t[a]=i?e(i):i})),t}}return null}function u(e,r){if(r){const{original:{page:{type:i="",attributes:s={},state:u={}}={}}={}}=r,l=t(e),f=n(e),d=a(l,r),p=c(f,r);if(d&&p){const e={...d,...p},t={};Object.keys(s).forEach((n=>{const r=s[n];let i;if(r&&o(r)){const t=r.substr(1);i=e[t]}else i=r;t[n]=i}));const n={};Object.keys(u).forEach((t=>{const r=u[t];let i;if(r&&o(r)){const t=r.substr(1);i=e[t]}else i=r;n[t]=i}));const a=function(e,t){const{compiledQuery:n}=t,r=Object.keys(n).filter((e=>{const{literalValue:t}=n[e];return!t})),o={};return Object.keys(e).forEach((t=>{const n=e[t];r.indexOf(t)<0&&(o[t]=n)})),o}(f,r);return{type:i,attributes:{...t},state:{...a,...n}}}}return null}const l={locale:"en-US",defaultLocale:"en-US"};function f(e,r){const o=t(e),i=n(e),s=r?r.filter((e=>e.regex.test(o))):[],[u]=s.filter((e=>{const{queryMatcher:t}=e;return t(i)&&function(e,t,n){const{original:{patterns:r=null}={}}=n||{};if(r){const o={...a(e,n),...c(t,n)};return Object.keys(r).every((e=>{const t=r[e],n=new RegExp(t),i=o[e]||"";return n.test(i)}))}return!0}(o,i,e)}));return u||null}function d(e,t,n="",r=l,o){if(!n||e!==n&&0!==e?.search(new RegExp(`^${n}[/?#]`))||(e=e.replace(n,"")),o?.locale||r?.locale){const t=`/${o?.locale||r.locale}`;e!==t&&0!==e?.search(new RegExp(`^${t}[/?#]`))||(e=e.replace(t,""))}const i=f(e,t);let s;if(!i)return null;{const t=u(e,i);if(t){return s={route:{id:i.original.id,attributes:{...t.attributes},state:{...t.state},pageReference:{type:t.type,attributes:{...t.attributes},state:{...t.state}}},routeDefinition:i},s}}return null}function p(e,t,n="",r=l,i){const s=function(e,t){if(!e)return null;const{type:n,attributes:r={},state:i={}}=e;if(n){const[e]=t.filter((e=>{const{original:{page:{type:t=null,attributes:s={},state:a={}}={}}}=e,c=t===n,u=Object.keys(s).every((e=>Object.keys(r).indexOf(e)>=0)),l=Object.keys(s).length===Object.keys(r).length,f=Object.keys(a).every((e=>Object.keys(i).indexOf(e)>=0)),d=Object.keys(s).filter((e=>{const t=s[e];return!t||!o(t)})).every((e=>s[e]===r[e])),p=Object.keys(a).filter((e=>{const t=a[e];return null===t||!o(t)})).every((e=>a[e]===i[e]));return c&&u&&l&&d&&f&&p}));return e||null}return null}(e,t);return s?g(e,s,n,r,i):null}function h(e,t,n){const{attributeBindings:r,stateBindings:o}=n,{attributes:s,state:a}=t,c={};return e.forEach((e=>{const[t]=Object.keys(r).filter((t=>i(r[t])===e));if(t)c[e]=s[t];else{const[t]=Object.keys(o).filter((t=>i(o[t])===e));t&&(c[e]=a[t])}})),c}function g(e,t,n="",a=l,c){const{params:u,original:{page:f={}}={},toPath:d,compiledQuery:p}=t,{attributes:g={},state:m={}}=f,E=d(h(u.filter((({name:e})=>"string"==typeof e)).map((({name:e})=>e)),e,{attributeBindings:g,stateBindings:m})),y=function(e,t,n){const{compiledQuery:r,original:{page:{state:s={}}}}=n,{state:a={}}=e||{},c={};Object.keys(a).filter((e=>!o(s[e]))).forEach((e=>c[e]=a[e]));const u={};return Object.keys(t).forEach((e=>{const n=t[e],[o]=Object.keys(r).filter((t=>{const n=r[t],{routeParamName:o}=n;return i(o)===e}));if(o){u[o]=n}})),{...c,...u}}(e,h(s(p),e,{attributeBindings:g,stateBindings:m}),t),b=r(y),R=c?.locale||a&&a.locale;return`${n}${R!==a.defaultLocale?`/${R}`:""}${E}${b}`}function m(e,t=2){if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e))try{Object.freeze(e),t>0&&Object.keys(e).forEach((n=>{if(function(e,t){return t in e}(e,n)){const r=e[n];r&&"object"==typeof r&&m(r,t-1)}}))}catch(e){}return e}const E="LWR",y=1;function b(e,t){return Array.isArray(t)?e.replace(/\{([0-9]+)\}/g,((e,n)=>t[n])):e}function R(e,t){return`${e.code}: ${b(e.message,t)}`}function I(e,t){const n={...e,message:b(e.message,t)};return e.address&&(n.address=b(e.address,t)),e.stack&&(n.stack=b(e.stack,t)),n}function v(e,t,n){if(!e)throw new Error(R(t,n))}const $={INVALID_MIXIN_CMP:{code:`${E}4001`,message:"{0} must be an Element type",level:y},MISSING_CONTEXT:{code:`${E}4002`,message:"Could not find context to perform navigation action.",level:y},INVALID_CONTEXT:{code:`${E}4003`,message:"Cannot register navigation context; it must have this shape: { navigate, generateUrl, subscribe }",level:y},MULTIPLE_ROOTS:{code:`${E}4004`,message:"Router connection failed. There can only be one root router.",level:y},MULTIPLE_CHILDREN:{code:`${E}4005`,message:"Could not add to the navigation hierarchy. There can only be one child per navigation node.",level:y},MISSING_ROUTE:{code:`${E}4006`,message:'A route cannot be created to navigate to URL "{0}"',level:y,address:"{0}"},MISSING_URL:{code:`${E}4007`,message:'A URL cannot be created to navigate to route "{0}"',level:y,address:"{0}"},PRENAV_FAILED:{code:`${E}4008`,message:'A preNavigate hook listener blocked routing to "{0}"',level:2,address:"{0}"},MISSING_ROUTE_TEMPLATE:{code:`${E}4009`,message:'Route definition with id "{0}" is missing a "uri" property.',level:y,address:"{0}"},MISSING_ROUTE_CMP:{code:`${E}4016`,message:"Expected a route view component with a default export.",level:y},MISSING_DATA_CONTEXT:{code:`${E}4018`,message:"Could not find context to retrieve navigation data.",level:y},INVALID_ROUTE_QUERY:{code:`${E}4019`,message:"Invalid query param in route definition.",level:y},MISSING_PAGE_BINDING:{code:`${E}4020`,message:'Route definition with id "{0}" is missing a "page" binding.',level:y,address:"{0}"},INVALID_PAGE_BINDING:{code:`${E}4021`,message:'Route definition with id "{0}" has an invalid "page" binding.',level:y,address:"{0}"},INVALID_URI_SYNTAX:{code:`${E}4022`,message:'Route definition with id "{0}" has invalid "uri" syntax. URI cannot contain *, +, (, ), ',level:y,address:"{0}"},VIEW_IMPORT_FAILED:{code:`${E}4023`,message:'Error importing view with name "{0}", failure was: {1}',level:y,stack:"{2}"},VIEW_MISSING:{code:`${E}4024`,message:'Expected a view with name "{0}" in the viewset',level:y},VIEW_IMPORT_FAILED_WITH_SPECIFIER:{code:`${E}4025`,message:'Error importing module "{0}" from view with name "{1}", failure was: {2}',level:y,stack:"{3}"},NO_ROUTE_MATCH:{code:`${E}4026`,message:"A routing match cannot be found for: {0}",level:y},INVALID_ROUTE_HANDLER:{code:`${E}4027`,message:'Route definition "{0}" does not have a valid route handler module',level:y},DESTINATION_NOT_FOUND:{code:`${E}4028`,message:"Route handler returned 404: Not Found",level:y},DESTINATION_ERROR:{code:`${E}4029`,message:"Route handler returned error status {0}: {1}",level:y,stack:"{2}"},NO_INIT_URL:{code:`${E}4030`,message:'Cannot initialize a server router without a "url"',level:y}};function O(e){return e.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}function N(e){return e&&e.sensitive?"":"i"}function _(e,t={}){const n=function(e){const t=[];let n=0;for(;n<e.length;){const r=e[n];if("*"!==r&&"+"!==r&&"?"!==r)if("\\"!==r)if("{"!==r)if("}"!==r)if(":"!==r)if("("!==r)t.push({type:"CHAR",index:n,value:e[n++]});else{let r=1,o="",i=n+1;if("?"===e[i])throw new TypeError(`Pattern cannot start with "?" at ${i}`);for(;i<e.length;)if("\\"!==e[i]){if(")"===e[i]){if(r--,0===r){i++;break}}else if("("===e[i]&&(r++,"?"!==e[i+1]))throw new TypeError(`Capturing groups are not allowed at ${i}`);o+=e[i++]}else o+=e[i++]+e[i++];if(r)throw new TypeError(`Unbalanced pattern at ${n}`);if(!o)throw new TypeError(`Missing pattern at ${n}`);t.push({type:"PATTERN",index:n,value:o}),n=i}else{let r="",o=n+1;for(;o<e.length;){const t=e.charCodeAt(o);if(!(t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95===t))break;r+=e[o++]}if(!r)throw new TypeError(`Missing parameter name at ${n}`);t.push({type:"NAME",index:n,value:r}),n=o}else t.push({type:"CLOSE",index:n,value:e[n++]});else t.push({type:"OPEN",index:n,value:e[n++]});else t.push({type:"ESCAPED_CHAR",index:n++,value:e[n++]});else t.push({type:"MODIFIER",index:n,value:e[n++]})}return t.push({type:"END",index:n,value:""}),t}(e),{prefixes:r="./"}=t,o=`[^${O(t.delimiter||"/#?")}]+?`,i=[];let s=0,a=0,c="";const u=e=>{if(a<n.length&&n[a].type===e)return n[a++].value},l=e=>{const t=u(e);if(void 0!==t)return t;const{type:r,index:o}=n[a];throw new TypeError(`Unexpected ${r} at ${o}, expected ${e}`)},f=()=>{let e,t="";for(;e=u("CHAR")||u("ESCAPED_CHAR");)t+=e;return t};for(;a<n.length;){const e=u("CHAR"),t=u("NAME"),n=u("PATTERN");if(t||n){let a=e||"";-1===r.indexOf(a)&&(c+=a,a=""),c&&(i.push(c),c=""),i.push({name:t||s++,prefix:a,suffix:"",pattern:n||o,modifier:u("MODIFIER")||""});continue}const a=e||u("ESCAPED_CHAR");if(a){c+=a;continue}c&&(i.push(c),c="");if(u("OPEN")){const e=f(),t=u("NAME")||"",n=u("PATTERN")||"",r=f();l("CLOSE"),i.push({name:t||(n?s++:""),pattern:t&&!n?o:n,prefix:e,suffix:r,modifier:u("MODIFIER")||""})}else l("END")}return i}function A(e,t){return function(e,t={}){const n=N(t),{encode:r=e=>e,validate:o=!0}=t,i=e.map((e=>{if("object"==typeof e)return new RegExp(`^(?:${e.pattern})$`,n)}));return t=>{let n="";for(let s=0;s<e.length;s++){const a=e[s];if("string"==typeof a){n+=a;continue}const c=t?t[a.name]:void 0,u="?"===a.modifier||"*"===a.modifier,l="*"===a.modifier||"+"===a.modifier;if(Array.isArray(c)){if(!l)throw new TypeError(`Expected "${a.name}" to not repeat, but got an array`);if(0===c.length){if(u)continue;throw new TypeError(`Expected "${a.name}" to not be empty`)}for(let e=0;e<c.length;e++){const t=r(c[e],a);if(o&&!i[s].test(t))throw new TypeError(`Expected all "${a.name}" to match "${a.pattern}", but got "${t}"`);n+=a.prefix+t+a.suffix}continue}if("string"==typeof c||"number"==typeof c){const e=r(String(c),a);if(o&&!i[s].test(e))throw new TypeError(`Expected "${a.name}" to match "${a.pattern}", but got "${e}"`);n+=a.prefix+e+a.suffix;continue}if(u)continue;const f=l?"an array":"a string";throw new TypeError(`Expected "${a.name}" to be ${f}`)}return n}}(_(e,t),t)}function w(e,t,n){return function(e,t,n={}){const{strict:r=!1,start:o=!0,end:i=!0,encode:s=e=>e}=n,a=`[${O(n.endsWith||"")}]|$`,c=`[${O(n.delimiter||"/#?")}]`;let u=o?"^":"";for(const n of e)if("string"==typeof n)u+=O(s(n));else{const e=O(s(n.prefix)),r=O(s(n.suffix));if(n.pattern)if(t&&t.push(n),e||r)if("+"===n.modifier||"*"===n.modifier){const t="*"===n.modifier?"?":"";u+=`(?:${e}((?:${n.pattern})(?:${r}${e}(?:${n.pattern}))*)${r})${t}`}else u+=`(?:${e}(${n.pattern})${r})${n.modifier}`;else u+=`(${n.pattern})${n.modifier}`;else u+=`(?:${e}${r})${n.modifier}`}if(i)r||(u+=`${c}?`),u+=n.endsWith?`(?=${a})`:"$";else{const t=e[e.length-1],n="string"==typeof t?c.indexOf(t[t.length-1])>-1:void 0===t;r||(u+=`(?:${c}(?=${a}))?`),n||(u+=`(?=${c}|${a})`)}return new RegExp(u,N(n))}(_(e,n),t,n)}function x(e,t,n){return e instanceof RegExp?function(e,t){if(!t)return e;const n=e.source.match(/\((?!\?)/g);if(n)for(let e=0;e<n.length;e++)t.push({name:e,prefix:"",suffix:"",modifier:"",pattern:""});return e}(e,t):Array.isArray(e)?function(e,t,n){const r=e.map((e=>x(e,t,n).source));return new RegExp(`(?:${r.join("|")})`,N(n))}(e,t,n):w(e,t,n)}const{INVALID_ROUTE_QUERY:T,MISSING_ROUTE_TEMPLATE:U,MISSING_PAGE_BINDING:D,INVALID_PAGE_BINDING:P,INVALID_URI_SYNTAX:C}=$;function S(e){const{routes:r,caseSensitive:a}=e;return r.map((e=>function(e,r=!1){const a=[],{id:c,uri:u,page:l}=e;v(!!u,I(U,[c])),v(function(e=""){const t=["*","(",")",";"].some((t=>e.indexOf(t)>=0));return!t}(u),I(C,[c])),v(!!l,I(D,[c]));const f=t(u),d=n(u),p=x(f,a,{sensitive:r,end:!1!==e.exact}),h=A(f,{encode:encodeURIComponent}),g=function(e){const t={};return Object.keys(e).forEach((n=>{const r=e[n];v(!o(n)||null===r,T),o(n)?t[n.substr(1)]={routeParamName:n}:r&&o(r)?t[n]={routeParamName:r}:t[n]={literalValue:null===r?null:r}})),t}(d),m=function(e,t=!1){const n=n=>{const r=Object.keys(n),o=Object.keys(e);return o.every((e=>r.indexOf(e)>=0))?o.reduce(((r,o)=>{if(null===r)return null;const{literalValue:i,routeParamName:s}=e[o],a=n[o];let c=!0;return"string"==typeof i?c=t?i===a:i.toUpperCase()===(null==a?a:a.toUpperCase()):null===i&&(c=a===i),r=c?{...r,[o]:{value:a,routeParamName:s}}:null}),{}):null};return n}(g,r),E={original:e,regex:p,params:a,toPath:h,compiledQuery:g,queryMatcher:m};return v(function(e){const{original:{page:t}={},params:n,compiledQuery:r}=e,a=t?t.type:t,c=(t?t.attributes:t)||{},u=(t?t.state:t)||{};if("string"!=typeof a||"object"!=typeof c||"object"!=typeof u)return!1;const l=Object.values(n).map((({name:e})=>e)),f=s(r),d=[...l,...f],p=Object.values(c).filter(o).map(i),h=Object.values(u).filter(o).map(i),g=d.every((e=>"string"==typeof e&&(p.indexOf(e)>=0||h.indexOf(e)>=0))),m=d.length===p.length+h.length;return!!(t&&a&&c&&u&&g&&m)}(E),I(P,[c])),E}(e,a)))}function j(){let e,t,n=[];const r=r=>{n.filter((e=>null!==e)).forEach((e=>e.error&&e.error(r))),e=void 0,t=r};return{next:r=>{n.filter((e=>null!==e)).forEach((e=>e.next&&e.next(r))),e=r,t=void 0},error:r,complete:()=>{n.filter((e=>null!==e)).forEach((e=>e.complete&&e.complete())),n=[],e=void 0,t=void 0},subscribe:(o,i=!0)=>{(e=>{n.push(e)})(o),e&&i&&o.next(e),t&&r(t);const s=n.length-1;return{unsubscribe:()=>(e=>{n=[...n.slice(0,e),...n.slice(e+1)]})(s)}}}}class M{constructor(e){this.deprecatedConfig={},this.routeHandlerId=0,this.compiledRoutes=[],this.routeObservable=j(),this.config={basePath:e.basePath||"",i18n:e.i18n||l,caseSensitive:Boolean(e.caseSensitive),routes:e.routes||[],generateUrl:(e,t)=>p(e,this.compiledRoutes,this.config.basePath,this.config.i18n,t),parseUrl:e=>function(e,t,n="",r=l){const o=d(e,t,n,r);return o&&o.route&&o.route.pageReference?o.route.pageReference:null}(e,this.compiledRoutes,this.config.basePath,this.config.i18n)};const{generateUrlFilter:t,DEPRECATED_getRouteFromUrl:n,DEPRECATED_getUrlFromRoute:r}=e;t&&(this.config.generateUrlFilter=t),n&&(this.deprecatedConfig.DEPRECATED_getRouteFromUrl=n),r&&(this.deprecatedConfig.DEPRECATED_getUrlFromRoute=r),this.compiledRoutes=S(this.config)}generateUrl(e,t){const{DEPRECATED_getUrlFromRoute:n}=this.deprecatedConfig;return n?n(e,this.config.generateUrl,t):this.config.generateUrl(e,t)}generateUrlAsync(e,t){const{generateUrlFilter:n}=this.config;return n?n(e,this.config.generateUrl,t):Promise.resolve(this.generateUrl(e,t))}parseUrl(e){const{DEPRECATED_getRouteFromUrl:t}=this.deprecatedConfig;return t?t(e,this.config.parseUrl):this.config.parseUrl(e)}matchRoute(e,t){const n="string"==typeof e?e:this.generateUrl(e,t);if(null===n)return null;const r=d(n,this.compiledRoutes,this.config.basePath,this.config.i18n,t),o=r&&g(r.route.pageReference,r.routeDefinition,this.config.basePath,this.config.i18n,t);return r&&o?{pathMatch:o,route:r.route,routeDefinition:r.routeDefinition.original}:null}async resolveView(e,t){return new Promise(((n,r)=>{const o=this.matchRoute(e,t);return o?o.routeDefinition.handler?.().then((e=>{const t=e.default;if(!t)return r(R($.INVALID_ROUTE_HANDLER,[o.routeDefinition.id]));const i=new t(n);i&&i.update(o.route)})):r(R($.NO_ROUTE_MATCH,[JSON.stringify(e)]))}))}navigate(e,t){const n=this.matchRoute(e,t);if(!n)throw new Error(R($.MISSING_ROUTE,[JSON.stringify(e)]));this.pendingRoute={...n},this._mapView(this.pendingRoute)}subscribe(e,t){return this.routeObservable.subscribe({next:e,error:()=>{},complete:()=>{}},Boolean(t))}async _mapView(e){const t=Math.random();this.routeHandlerId=t;const n=await(e.routeDefinition.handler?.()),r=n?.default;if(!r)throw new Error(R($.INVALID_ROUTE_HANDLER,[e.routeDefinition.id]));return this.routeHandler=new r((e=>{this._updateView(t,e)})),this.routeHandler&&this.routeHandler.update(e.route),!0}_updateView(e,t){if(!t||e!==this.routeHandlerId)return;if(!this.pendingRoute)throw new Error("Trying to commit route state without a route");const n=m(t.viewset);this.routeObservable.next({...this.pendingRoute,...t,viewset:n})}}function k(e={}){return new M(e)}export{k as createRouter};
|
|
2
2
|
//# sourceMappingURL=router.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{parseFragment as e,registerTemplate as t,freezeTemplate as i,createContextProvider as s,registerDecorators as r,registerComponent as o,LightningElement as n}from"lwc";import{ROUTER_VIEW as a,ROUTER_NAV as c,ROUTER_ERROR as d}from"lwr/metrics";import{logOperationEnd as h,logOperationStart as l}from"lwr/profiler";function u(e,t,i){return"span.router-title"+(e?"."+e:"")+" {position: absolute;margin: -1px;border: 0;padding: 0;width: 1px;height: 1px;overflow: hidden;clip: rect(0 0 0 0);text-transform: none;white-space: nowrap;}"}u.$scoped$=!0;var p=[u];const v=e`<span class="router-title${0}" aria-live="polite" aria-atomic="true"${2}></span>`,g={key:0},m=[],f={ref:"title"};function E(e,t,i,s){const{s:r,sp:o,st:n}=e;return[r("",g,m,i),n(v,2,[o(0,f,null)])]}var I=t(E);function b(e){if(null==e)throw new TypeError("Provider must be defined.")}E.slots=[""],E.renderMode="light",E.hasRefs=!0,E.stylesheets=[],E.stylesheetToken="lwc-7bis3qj4jjc",E.legacyStylesheetToken="lwr-routerContainer_routerContainer",p&&E.stylesheets.push.apply(E.stylesheets,p),i(E);class N{constructor(e){this.infoMap=new WeakMap,this.defaultValue=void 0,this.defaultValue=e}getInfo(e){let t=this.infoMap.get(e);return void 0===t&&(t={consumers:new Set},this.infoMap.set(e,t)),t}setContext(e,t){b(e);const i=t,s=this.getInfo(e);s.contextValue=t,s.consumers.forEach((e=>e.provide(i))),0===s.consumers.size&&i?.onComplete&&i.onComplete()}getContext(e){b(e);const{contextValue:t}=this.getInfo(e);return void 0!==t?t:this.defaultValue}clearContext(e){b(e),this.infoMap.delete(e)}subscribeContext(e,t){b(e);const{consumers:i,contextValue:s}=this.getInfo(e);i.has(t)||(i.add(t),t.provide(s))}unsubscribeContext(e,t){b(e),this.getInfo(e).consumers.delete(t)}}const w="LWR",_=1;function R(e,t){return Array.isArray(t)?e.replace(/\{([0-9]+)\}/g,((e,i)=>t[i])):e}function x(e,t){const i={...e,message:R(e.message,t)};return e.address&&(i.address=R(e.address,t)),e.stack&&(i.stack=R(e.stack,t)),i}function C(e,t,i){if(!e)throw new Error(function(e,t){return`${e.code}: ${R(e.message,t)}`}(t,i))}const T={INVALID_MIXIN_CMP:{code:`${w}4001`,message:"{0} must be an Element type",level:_},MISSING_CONTEXT:{code:`${w}4002`,message:"Could not find context to perform navigation action.",level:_},INVALID_CONTEXT:{code:`${w}4003`,message:"Cannot register navigation context; it must have this shape: { navigate, generateUrl, subscribe }",level:_},MULTIPLE_ROOTS:{code:`${w}4004`,message:"Router connection failed. There can only be one root router.",level:_},MULTIPLE_CHILDREN:{code:`${w}4005`,message:"Could not add to the navigation hierarchy. There can only be one child per navigation node.",level:_},MISSING_ROUTE:{code:`${w}4006`,message:'A route cannot be created to navigate to URL "{0}"',level:_,address:"{0}"},MISSING_URL:{code:`${w}4007`,message:'A URL cannot be created to navigate to route "{0}"',level:_,address:"{0}"},PRENAV_FAILED:{code:`${w}4008`,message:'A preNavigate hook listener blocked routing to "{0}"',level:2,address:"{0}"},MISSING_ROUTE_TEMPLATE:{code:`${w}4009`,message:'Route definition with id "{0}" is missing a "uri" property.',level:_,address:"{0}"},MISSING_ROUTE_CMP:{code:`${w}4016`,message:"Expected a route view component with a default export.",level:_},MISSING_DATA_CONTEXT:{code:`${w}4018`,message:"Could not find context to retrieve navigation data.",level:_},INVALID_ROUTE_QUERY:{code:`${w}4019`,message:"Invalid query param in route definition.",level:_},MISSING_PAGE_BINDING:{code:`${w}4020`,message:'Route definition with id "{0}" is missing a "page" binding.',level:_,address:"{0}"},INVALID_PAGE_BINDING:{code:`${w}4021`,message:'Route definition with id "{0}" has an invalid "page" binding.',level:_,address:"{0}"},INVALID_URI_SYNTAX:{code:`${w}4022`,message:'Route definition with id "{0}" has invalid "uri" syntax. URI cannot contain *, +, (, ), ',level:_,address:"{0}"},VIEW_IMPORT_FAILED:{code:`${w}4023`,message:'Error importing view with name "{0}", failure was: {1}',level:_,stack:"{2}"},VIEW_MISSING:{code:`${w}4024`,message:'Expected a view with name "{0}" in the viewset',level:_},VIEW_IMPORT_FAILED_WITH_SPECIFIER:{code:`${w}4025`,message:'Error importing module "{0}" from view with name "{1}", failure was: {2}',level:_,stack:"{3}"},NO_ROUTE_MATCH:{code:`${w}4026`,message:"A routing match cannot be found for: {0}",level:_},INVALID_ROUTE_HANDLER:{code:`${w}4027`,message:'Route definition "{0}" does not have a valid route handler module',level:_},DESTINATION_NOT_FOUND:{code:`${w}4028`,message:"Route handler returned 404: Not Found",level:_},DESTINATION_ERROR:{code:`${w}4029`,message:"Route handler returned error status {0}: {1}",level:_,stack:"{2}"},NO_INIT_URL:{code:`${w}4030`,message:'Cannot initialize a server router without a "url"',level:_}},P=new WeakMap;function y(e){var t;return(t=class{constructor(e){this._callback=void 0,this._callback=e}connect(){}disconnect(){}update(e,t){t&&this._callback(t)}static setContext(t,i){e.setContext(t,i)}static getContext(t){return e.getContext(t)}static clearContext(t){e.clearContext(t)}static subscribeContext(t,i){e.subscribeContext(t,i)}static unsubscribeContext(t,i){e.unsubscribeContext(t,i)}}).contextSchema={value:"required"},t}const $=y(new N(void 0)),O=y(new N(void 0)),S=new N(void 0),A=class extends(y(S)){async update(e,t){if(t){const i=e&&e.viewName?e.viewName:"default",s=t.viewset[i],r=s,o=r&&r.module||s;let n;if(o)try{const e=await o(),t=e&&e.default;if(!t||void 0===t.constructor)throw new Error("error occurred with view import");this._callback(t)}catch(e){const t=e;n=r.specifier?x(T.VIEW_IMPORT_FAILED_WITH_SPECIFIER,[r.specifier,i,t.message,t.stack||""]):x(T.VIEW_IMPORT_FAILED,[i,t.message,t.stack||""])}else n=x(T.VIEW_MISSING,[i]);t.onComplete&&t.onComplete(n)}}};function M(){const e=[],t=t=>{"function"==typeof t&&e.push(t)};return{add:(e=[])=>{Array.isArray(e)?e.forEach((e=>t(e))):t(e)},compile:t=>0===e.length?Promise.resolve(!0):e.reduce(((e,i)=>e.then((e=>!1===e?Promise.reject():Promise.resolve(i(t))))),Promise.resolve(!0)).then((e=>!1!==e)).catch((e=>{if(e instanceof Error)throw e;return!1})),empty:()=>0===e.length}}function L(e=""){return e=e||"",decodeURIComponent(e)}function D(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}const U="undefined"!=typeof document,k=`universalcontainergetnavigationcontext${D()}`,F=s(O),V=U?s(A):void 0,G=s($);function W(e,t,i,s){i&&s&&(s.setContext(t,e),i(t,{consumerConnectedCallback:s.subscribeContext.bind(s,t),consumerDisconnectedCallback:s.unsubscribeContext.bind(s,t)}))}function j(){let e,t,i=[];const s=s=>{i.filter((e=>null!==e)).forEach((e=>e.error&&e.error(s))),e=void 0,t=s};return{next:s=>{i.filter((e=>null!==e)).forEach((e=>e.next&&e.next(s))),e=s,t=void 0},error:s,complete:()=>{i.filter((e=>null!==e)).forEach((e=>e.complete&&e.complete())),i=[],e=void 0,t=void 0},subscribe:(r,o=!0)=>{(e=>{i.push(e)})(r),e&&o&&r.next(e),t&&s(t);const n=i.length-1;return{unsubscribe:()=>(e=>{i=[...i.slice(0,e),...i.slice(e+1)]})(n)}}}}const H=`universalcontainernavigationevent${D()}`,B=`universalcontainerparentevent${D()}`;class X{constructor(e,t,i){this.config=void 0,this.target=void 0,this.router=void 0,this.pendingRoute=null,this.committedRoute=null,this.routeObservable=void 0,this.eventId=void 0,this.contextId=Object.freeze((()=>{})),this.connected=!1,this.parent=void 0,this.child=void 0,this.preNavFilters=M(),this.errorNavFilters=M(),this._handleNavigationEvent=e=>{const t=e;if(t.detail&&"object"==typeof t.detail){const{url:e,replace:i,address:s}=t.detail;this.config.handleNavigation(s,i)?this.root&&!e?this.root.processError(x(T.MISSING_URL,[JSON.stringify(s)])):this.parent||this.process(e,i):t.stopPropagation()}},this._handleParentEvent=e=>{e.stopImmediatePropagation();const t=e;t&&t.detail&&"function"==typeof t.detail&&t.detail(this)},this.config={handleNavigation:e.handleNavigation||(()=>!0)},this.target=i||window,this.router=t,this.router.contextId=this.contextId,this.routeObservable=j()}get root(){if(!this.parent)return this;let e=this.parent;for(;e;){if(!e.parent)return e;e=e.parent}throw new Error("No root router could be found")}updateWires(e,t,i){if(i)this.processError(i);else{if(this.committedRoute&&e.route===this.committedRoute.route)return;h({id:a,specifier:this.eventId}),this.pendingRoute=this.pendingRoute||{...e,url:t},this.committedRoute={...this.pendingRoute,...e},O.setContext(this.target,e.route.pageReference),this.routeObservable.next({...this.committedRoute,viewset:e.viewset}),h({id:c,specifier:this.eventId}),this.child&&this.child.process(this._stripUrlForChild(this.committedRoute.url))}}connect(){this._sendEvent(B,(e=>{this.parent=e,e.addChild(this)}));const e={navigate:(e,t)=>this.navigate(e,t),generateUrl:(e,t)=>this.generateUrl(e,t),subscribe:(e,t)=>this.subscribe(e,t)};!function(e,t){const i={id:e,value:t,update:e=>{i.value=e}};P.set(i.id,i)}(this.contextId,e),W(this.contextId,this.target,G,$),W(void 0,this.target,F,O),W(void 0,this.target,V,A),this.router.subscribe((e=>{if(404===e.status)return void this.processError(x(T.DESTINATION_NOT_FOUND));if(e.status&&e.status>=400){const t=e.error||new Error;return void this.processError(x(T.DESTINATION_ERROR,[e.status.toString(),t.message,t.stack||""]))}const t=e.route.pageReference||{},i=this.router.generateUrl(t)||"";if(l({id:a,specifier:this.eventId}),e.viewset){const t={viewset:e.viewset,onComplete:this.updateWires.bind(this,e,i)};A.setContext(this.target,t)}else e.route.pageReference&&this.updateWires(e,i)}),!0),U&&(this.target.addEventListener(H,this._handleNavigationEvent),this.target.addEventListener(B,this._handleParentEvent),this.target.addEventListener(k,(e=>{const t=e;t.detail.callback&&t.detail.callback(this.contextId)}))),this.connected=!0}disconnect(){this.target.removeEventListener(H,this._handleNavigationEvent),this.target.removeEventListener(B,this._handleParentEvent),this.parent&&(this.parent.child=void 0),this.parent=void 0,this.child&&(this.child.parent=void 0),this.child=void 0,this.connected=!1}addPreNavigate(e){this.preNavFilters.add(e)}addErrorNavigate(e){this.errorNavFilters.add(e)}async addChild(e){if(await new Promise((t=>{setTimeout((()=>{C(!this.child,T.MULTIPLE_CHILDREN),this.child=e,t()}),0)})),this.child&&this.committedRoute){const e=this._stripUrlForChild(this.committedRoute.url);await this.child.preProcess(e)&&this.child.process(e)}}async process(e,t,i,s){this.eventId=(new Date).getTime().toString(),l({id:c,specifier:this.eventId});try{this.parent||await this.preProcess(e,i)}catch(e){if(e.code)return this.processError(e),!1;throw e}const r=this.router.parseUrl(e);return r&&this.router.navigate(r,i),!0}preProcess(e,t){const i=this.router.parseUrl(e),s=i&&this.router.matchRoute(i,t);if(!s)return Promise.reject(x(T.MISSING_ROUTE,[e]));this.pendingRoute={url:e,...s};return(this.preNavFilters.empty()?Promise.resolve(!0):this.preNavFilters.compile({current:this.committedRoute||void 0,next:this.pendingRoute})).then((t=>t&&this.child?this.child.preProcess(this._stripUrlForChild(e)):t)).then((t=>t||Promise.reject(x(T.PRENAV_FAILED,[e]))))}processError(e){l({id:d}),this.errorNavFilters.compile(e),this.child&&this.child.processError(e)}navigate(e,t,i){const s=this.filterNavigateOptions(i);let r=this.router.generateUrl(e,s);if(r){r=(this.parent&&this.parent.committedRoute&&this.parent.committedRoute.pathMatch||"").concat(r)}this._sendEvent(H,{url:r,replace:t,address:e})}generateUrl(e,t){const i=this.filterNavigateOptions(t),s=this.router.generateUrl(e,i);if(!s)return null;return`${this.parent&&this.parent.committedRoute&&this.parent.committedRoute.pathMatch||""}${s}`}subscribe(e,t){return this.routeObservable.subscribe({next:e,error:()=>{},complete:()=>{}},Boolean(t))}_sendEvent(e,t){U&&this.target.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:t}))}_stripUrlForChild(e){return this.pendingRoute&&0===e.indexOf(this.pendingRoute.pathMatch)?e.replace(this.pendingRoute.pathMatch,""):e}filterNavigateOptions(e){const t=!this.parent;return{...e,locale:t?e?.locale:void 0}}}function q(e){const t=function(e=""){if((e=e||"").indexOf("://")<0){const t=window.location.port?`:${window.location.port}`:"",i=`${window.location.protocol}//${window.location.hostname}${t}`,s="/"===e.charAt(0)?"":"/";e=i+s+e}const t={},i=document.createElement("a");i.href=e;const s=i.search.substring(1);return s&&s.split("&").forEach((e=>{const[i,s=""]=e.split("=");t[L(i)]=L(s)})),{href:i.href,origin:`${i.protocol}//${i.hostname}${i.port?`:${i.port}`:""}`,pathname:i.pathname.replace(/(\/)?/,"/"),searchParams:t}}(e),i=t.href.replace(/:\d+/,""),s=t.origin.replace(/:\d+/,"");return i.replace(s,"")}class z extends X{constructor(...e){super(...e),this.historyDisabled=!1}connect(){super.connect(),this.historyDisabled||(U&&window.addEventListener("popstate",this.onpopstate.bind(this)),this.onpopstate())}onpopstate(){!this.parent&&U&&this.catchBrowserUpdate(q(window.location.href))}disconnect(){super.disconnect(),U&&window.removeEventListener("popstate",this.onpopstate)}async process(e,t,i,s=!0){const r=await super.process(e,t,i,s);return r&&!this.historyDisabled&&s&&this.connected&&!this.parent&&(t?function(e,t){const i=t||{};window.history.replaceState(i,"",e)}(e):function(e,t){const i=t||{};window.history.pushState(i,"",e)}(e)),r}catchBrowserUpdate(e){this.process(e,!1,{},!1)}}r(z,{fields:["historyDisabled"]});let Y=!1;class J extends n{constructor(){super(),this.router=void 0,this.historyDisabled=!1,this.currentTitle=U?document.title:""}connectedCallback(){const e={historyDisabled:this.historyDisabled,handleNavigation:this.handleNavigation.bind(this)};U&&this.router&&(this.routerApi=function(e,t={},i){const s=t.historyDisabled?new X(t,i,e):new z(t,i,e),r={addPreNavigate:e=>(s.addPreNavigate(e),r),addPostNavigate:e=>(s.subscribe(e),r),addErrorNavigate:e=>(s.addErrorNavigate(e),r),connect:()=>{s.connect(),C(!Y||!!s.parent,T.MULTIPLE_ROOTS),Y=Y||!s.parent,r.id=s.contextId},disconnect:()=>{Y=Y&&!!s.parent,s.disconnect()}};return r}(this,e,this.router),this.routerApi.addPreNavigate(this.preNavigate.bind(this)).addPostNavigate(this.postNavigate.bind(this)).addErrorNavigate(this.errorNavigate.bind(this)).connect())}preNavigate(e){const t=this._createEvent("prenavigate",e,!0);return this.dispatchEvent(t),!t.defaultPrevented}postNavigate(e){this.dispatchEvent(this._createEvent("postnavigate",e));const t=e.routeDefinition.metadata&&e.routeDefinition.metadata.title;t&&(this.currentTitle=t,document.title=t);const i=this.refs?.title;i&&(i.innerHTML=this.currentTitle)}errorNavigate(e){return this.dispatchEvent(this._createEvent("errornavigate",e)),!0}handleNavigation(e,t){const i=this._createEvent("handlenavigation",{address:e,replace:t},!0);return this.dispatchEvent(i),!i.defaultPrevented}disconnectedCallback(){this.routerApi&&this.routerApi.disconnect()}_createEvent(e,t,i){return new CustomEvent(e,{detail:t,bubbles:!1,composed:!1,cancelable:i})}}J.renderMode="light",r(J,{publicProps:{router:{config:0},historyDisabled:{config:0}}});const Q=o(J,{tmpl:I,sel:"lwr-router-container",apiVersion:63});export{Q as default};
|
|
1
|
+
import{parseFragment as e,registerTemplate as t,freezeTemplate as i,createContextProvider as r,registerDecorators as s,registerComponent as n,LightningElement as o}from"lwc";import{ROUTER_VIEW as a,ROUTER_NAV as c,ROUTER_ERROR as d}from"lwr/metrics";import{logOperationEnd as h,logOperationStart as l}from"lwr/profiler";function u(e,t,i){return"span.router-title"+(e?"."+e:"")+" {position: absolute;margin: -1px;border: 0;padding: 0;width: 1px;height: 1px;overflow: hidden;clip: rect(0 0 0 0);text-transform: none;white-space: nowrap;}"}u.$scoped$=!0;var p=[u];const v=e`<span class="router-title${0}" aria-live="polite" aria-atomic="true"${2}></span>`,g={key:0},m=[],f={ref:"title"};function E(e,t,i,r){const{s:s,sp:n,st:o}=e;return[s("",g,m,i),o(v,2,[n(0,f,null)])]}var I=t(E);function b(e){if(null==e)throw new TypeError("Provider must be defined.")}E.slots=[""],E.renderMode="light",E.hasRefs=!0,E.stylesheets=[],E.stylesheetToken="lwc-7bis3qj4jjc",E.legacyStylesheetToken="lwr-routerContainer_routerContainer",p&&E.stylesheets.push.apply(E.stylesheets,p),i(E);class w{constructor(e){this.infoMap=new WeakMap,this.defaultValue=void 0,this.defaultValue=e}getInfo(e){let t=this.infoMap.get(e);return void 0===t&&(t={consumers:new Set},this.infoMap.set(e,t)),t}setContext(e,t){b(e);const i=t,r=this.getInfo(e);r.contextValue=t,r.consumers.forEach((e=>e.provide(i))),0===r.consumers.size&&i?.onComplete&&i.onComplete()}getContext(e){b(e);const{contextValue:t}=this.getInfo(e);return void 0!==t?t:this.defaultValue}clearContext(e){b(e),this.infoMap.delete(e)}subscribeContext(e,t){b(e);const{consumers:i,contextValue:r}=this.getInfo(e);i.has(t)||(i.add(t),t.provide(r))}unsubscribeContext(e,t){b(e),this.getInfo(e).consumers.delete(t)}}const N="LWR",_=1;function R(e,t){return Array.isArray(t)?e.replace(/\{([0-9]+)\}/g,((e,i)=>t[i])):e}function x(e,t){const i={...e,message:R(e.message,t)};return e.address&&(i.address=R(e.address,t)),e.stack&&(i.stack=R(e.stack,t)),i}function C(e,t,i){if(!e)throw new Error(function(e,t){return`${e.code}: ${R(e.message,t)}`}(t,i))}const T={INVALID_MIXIN_CMP:{code:`${N}4001`,message:"{0} must be an Element type",level:_},MISSING_CONTEXT:{code:`${N}4002`,message:"Could not find context to perform navigation action.",level:_},INVALID_CONTEXT:{code:`${N}4003`,message:"Cannot register navigation context; it must have this shape: { navigate, generateUrl, subscribe }",level:_},MULTIPLE_ROOTS:{code:`${N}4004`,message:"Router connection failed. There can only be one root router.",level:_},MULTIPLE_CHILDREN:{code:`${N}4005`,message:"Could not add to the navigation hierarchy. There can only be one child per navigation node.",level:_},MISSING_ROUTE:{code:`${N}4006`,message:'A route cannot be created to navigate to URL "{0}"',level:_,address:"{0}"},MISSING_URL:{code:`${N}4007`,message:'A URL cannot be created to navigate to route "{0}"',level:_,address:"{0}"},PRENAV_FAILED:{code:`${N}4008`,message:'A preNavigate hook listener blocked routing to "{0}"',level:2,address:"{0}"},MISSING_ROUTE_TEMPLATE:{code:`${N}4009`,message:'Route definition with id "{0}" is missing a "uri" property.',level:_,address:"{0}"},MISSING_ROUTE_CMP:{code:`${N}4016`,message:"Expected a route view component with a default export.",level:_},MISSING_DATA_CONTEXT:{code:`${N}4018`,message:"Could not find context to retrieve navigation data.",level:_},INVALID_ROUTE_QUERY:{code:`${N}4019`,message:"Invalid query param in route definition.",level:_},MISSING_PAGE_BINDING:{code:`${N}4020`,message:'Route definition with id "{0}" is missing a "page" binding.',level:_,address:"{0}"},INVALID_PAGE_BINDING:{code:`${N}4021`,message:'Route definition with id "{0}" has an invalid "page" binding.',level:_,address:"{0}"},INVALID_URI_SYNTAX:{code:`${N}4022`,message:'Route definition with id "{0}" has invalid "uri" syntax. URI cannot contain *, +, (, ), ',level:_,address:"{0}"},VIEW_IMPORT_FAILED:{code:`${N}4023`,message:'Error importing view with name "{0}", failure was: {1}',level:_,stack:"{2}"},VIEW_MISSING:{code:`${N}4024`,message:'Expected a view with name "{0}" in the viewset',level:_},VIEW_IMPORT_FAILED_WITH_SPECIFIER:{code:`${N}4025`,message:'Error importing module "{0}" from view with name "{1}", failure was: {2}',level:_,stack:"{3}"},NO_ROUTE_MATCH:{code:`${N}4026`,message:"A routing match cannot be found for: {0}",level:_},INVALID_ROUTE_HANDLER:{code:`${N}4027`,message:'Route definition "{0}" does not have a valid route handler module',level:_},DESTINATION_NOT_FOUND:{code:`${N}4028`,message:"Route handler returned 404: Not Found",level:_},DESTINATION_ERROR:{code:`${N}4029`,message:"Route handler returned error status {0}: {1}",level:_,stack:"{2}"},NO_INIT_URL:{code:`${N}4030`,message:'Cannot initialize a server router without a "url"',level:_}},y=new WeakMap;function P(e){var t;return(t=class{constructor(e){this._callback=void 0,this._callback=e}connect(){}disconnect(){}update(e,t){t&&this._callback(t)}static setContext(t,i){e.setContext(t,i)}static getContext(t){return e.getContext(t)}static clearContext(t){e.clearContext(t)}static subscribeContext(t,i){e.subscribeContext(t,i)}static unsubscribeContext(t,i){e.unsubscribeContext(t,i)}}).contextSchema={value:"required"},t}const U=P(new w(void 0)),$=P(new w(void 0)),A=new w(void 0),O=class extends(P(A)){async update(e,t){if(t){const i=e&&e.viewName?e.viewName:"default",r=t.viewset[i],s=r,n=s&&s.module||r;let o;if(n)try{const e=await n(),t=e&&e.default;if(!t||void 0===t.constructor)throw new Error("error occurred with view import");this._callback(t)}catch(e){const t=e;o=s.specifier?x(T.VIEW_IMPORT_FAILED_WITH_SPECIFIER,[s.specifier,i,t.message,t.stack||""]):x(T.VIEW_IMPORT_FAILED,[i,t.message,t.stack||""])}else o=x(T.VIEW_MISSING,[i]);t.onComplete&&t.onComplete(o)}}};function M(){const e=[],t=t=>{"function"==typeof t&&e.push(t)};return{add:(e=[])=>{Array.isArray(e)?e.forEach((e=>t(e))):t(e)},compile:t=>0===e.length?Promise.resolve(!0):e.reduce(((e,i)=>e.then((e=>!1===e?Promise.reject():Promise.resolve(i(t))))),Promise.resolve(!0)).then((e=>!1!==e)).catch((e=>{if(e instanceof Error)throw e;return!1})),empty:()=>0===e.length}}function S(e=""){return e=e||"",decodeURIComponent(e)}function L(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}const D="undefined"!=typeof document,k=`universalcontainergetnavigationcontext${L()}`,F=r($),V=D?r(O):void 0,G=r(U);function W(e,t,i,r){i&&r&&(r.setContext(t,e),i(t,{consumerConnectedCallback:r.subscribeContext.bind(r,t),consumerDisconnectedCallback:r.unsubscribeContext.bind(r,t)}))}function j(){let e,t,i=[];const r=r=>{i.filter((e=>null!==e)).forEach((e=>e.error&&e.error(r))),e=void 0,t=r};return{next:r=>{i.filter((e=>null!==e)).forEach((e=>e.next&&e.next(r))),e=r,t=void 0},error:r,complete:()=>{i.filter((e=>null!==e)).forEach((e=>e.complete&&e.complete())),i=[],e=void 0,t=void 0},subscribe:(s,n=!0)=>{(e=>{i.push(e)})(s),e&&n&&s.next(e),t&&r(t);const o=i.length-1;return{unsubscribe:()=>(e=>{i=[...i.slice(0,e),...i.slice(e+1)]})(o)}}}}const H=`universalcontainernavigationevent${L()}`,B=`universalcontainerparentevent${L()}`;class X{constructor(e,t,i){this.config=void 0,this.target=void 0,this.router=void 0,this.pendingRoute=null,this.committedRoute=null,this.routeObservable=void 0,this.eventId=void 0,this.contextId=Object.freeze((()=>{})),this.connected=!1,this.parent=void 0,this.child=void 0,this.preNavFilters=M(),this.errorNavFilters=M(),this._handleNavigationEvent=e=>{const t=e;if(t.detail&&"object"==typeof t.detail){const{url:e,replace:i,address:r}=t.detail;this.config.handleNavigation(r,i)?this.root&&!e?this.root.processError(x(T.MISSING_URL,[JSON.stringify(r)])):this.parent||this.process(e,i):t.stopPropagation()}},this._handleParentEvent=e=>{e.stopImmediatePropagation();const t=e;t&&t.detail&&"function"==typeof t.detail&&t.detail(this)},this.config={handleNavigation:e.handleNavigation||(()=>!0)},this.target=i||window,this.router=t,this.router.contextId=this.contextId,this.routeObservable=j()}get root(){if(!this.parent)return this;let e=this.parent;for(;e;){if(!e.parent)return e;e=e.parent}throw new Error("No root router could be found")}updateWires(e,t,i){if(i)this.processError(i);else{if(this.committedRoute&&e.route===this.committedRoute.route)return;h({id:a,specifier:this.eventId}),this.pendingRoute=this.pendingRoute||{...e,url:t},this.committedRoute={...this.pendingRoute,...e},$.setContext(this.target,e.route.pageReference),this.routeObservable.next({...this.committedRoute,viewset:e.viewset}),h({id:c,specifier:this.eventId}),this.child&&this.child.process(this._stripUrlForChild(this.committedRoute.url))}}connect(){this._sendEvent(B,(e=>{this.parent=e,e.addChild(this)}));const e={navigate:(e,t)=>this.navigate(e,t),generateUrl:(e,t)=>this.generateUrl(e,t),generateUrlAsync:(e,t)=>this.generateUrlAsync(e,t),subscribe:(e,t)=>this.subscribe(e,t)};!function(e,t){const i={id:e,value:t,update:e=>{i.value=e}};y.set(i.id,i)}(this.contextId,e),W(this.contextId,this.target,G,U),W(void 0,this.target,F,$),W(void 0,this.target,V,O),this.router.subscribe((e=>{if(404===e.status)return void this.processError(x(T.DESTINATION_NOT_FOUND));if(e.status&&e.status>=400){const t=e.error||new Error;return void this.processError(x(T.DESTINATION_ERROR,[e.status.toString(),t.message,t.stack||""]))}const t=e.route.pageReference||{},i=this.router.generateUrl(t)||"";if(l({id:a,specifier:this.eventId}),e.viewset){const t={viewset:e.viewset,onComplete:this.updateWires.bind(this,e,i)};O.setContext(this.target,t)}else e.route.pageReference&&this.updateWires(e,i)}),!0),D&&(this.target.addEventListener(H,this._handleNavigationEvent),this.target.addEventListener(B,this._handleParentEvent),this.target.addEventListener(k,(e=>{const t=e;t.detail.callback&&t.detail.callback(this.contextId)}))),this.connected=!0}disconnect(){this.target.removeEventListener(H,this._handleNavigationEvent),this.target.removeEventListener(B,this._handleParentEvent),this.parent&&(this.parent.child=void 0),this.parent=void 0,this.child&&(this.child.parent=void 0),this.child=void 0,this.connected=!1}addPreNavigate(e){this.preNavFilters.add(e)}addErrorNavigate(e){this.errorNavFilters.add(e)}async addChild(e){if(await new Promise((t=>{setTimeout((()=>{C(!this.child,T.MULTIPLE_CHILDREN),this.child=e,t()}),0)})),this.child&&this.committedRoute){const e=this._stripUrlForChild(this.committedRoute.url);await this.child.preProcess(e)&&this.child.process(e)}}async process(e,t,i,r){this.eventId=(new Date).getTime().toString(),l({id:c,specifier:this.eventId});try{this.parent||await this.preProcess(e,i)}catch(e){if(e.code)return this.processError(e),!1;throw e}const s=this.router.parseUrl(e);return s&&this.router.navigate(s,i),!0}preProcess(e,t){const i=this.router.parseUrl(e),r=i&&this.router.matchRoute(i,t);if(!r)return Promise.reject(x(T.MISSING_ROUTE,[e]));this.pendingRoute={url:e,...r};return(this.preNavFilters.empty()?Promise.resolve(!0):this.preNavFilters.compile({current:this.committedRoute||void 0,next:this.pendingRoute})).then((t=>t&&this.child?this.child.preProcess(this._stripUrlForChild(e)):t)).then((t=>t||Promise.reject(x(T.PRENAV_FAILED,[e]))))}processError(e){l({id:d}),this.errorNavFilters.compile(e),this.child&&this.child.processError(e)}navigate(e,t,i){const r=this.filterNavigateOptions(i);let s=this.router.generateUrl(e,r);if(s){s=(this.parent&&this.parent.committedRoute&&this.parent.committedRoute.pathMatch||"").concat(s)}this._sendEvent(H,{url:s,replace:t,address:e})}generateUrl(e,t){const i=this.filterNavigateOptions(t),r=this.router.generateUrl(e,i);if(!r)return null;return`${this.parent&&this.parent.committedRoute&&this.parent.committedRoute.pathMatch||""}${r}`}async generateUrlAsync(e,t){const i=this.filterNavigateOptions(t),r=await this.router.generateUrlAsync(e,i);if(!r)return null;return`${this.parent&&this.parent.committedRoute&&this.parent.committedRoute.pathMatch||""}${r}`}subscribe(e,t){return this.routeObservable.subscribe({next:e,error:()=>{},complete:()=>{}},Boolean(t))}_sendEvent(e,t){D&&this.target.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:t}))}_stripUrlForChild(e){return this.pendingRoute&&0===e.indexOf(this.pendingRoute.pathMatch)?e.replace(this.pendingRoute.pathMatch,""):e}filterNavigateOptions(e){const t=!this.parent;return{...e,locale:t?e?.locale:void 0}}}function q(e){const t=function(e=""){if((e=e||"").indexOf("://")<0){const t=window.location.port?`:${window.location.port}`:"",i=`${window.location.protocol}//${window.location.hostname}${t}`,r="/"===e.charAt(0)?"":"/";e=i+r+e}const t={},i=document.createElement("a");i.href=e;const r=i.search.substring(1);return r&&r.split("&").forEach((e=>{const[i,r=""]=e.split("=");t[S(i)]=S(r)})),{href:i.href,origin:`${i.protocol}//${i.hostname}${i.port?`:${i.port}`:""}`,pathname:i.pathname.replace(/(\/)?/,"/"),searchParams:t}}(e),i=t.href.replace(/:\d+/,""),r=t.origin.replace(/:\d+/,"");return i.replace(r,"")}class z extends X{constructor(...e){super(...e),this.historyDisabled=!1,this.currentUrl=""}connect(){super.connect(),this.historyDisabled||(D&&window.addEventListener("popstate",this.onpopstate.bind(this)),this.onpopstate())}onpopstate(){if(!this.parent&&D){const e=function(e){const t=e.indexOf("#");return-1!==t?e.substring(0,t):e}(q(window.location.href));e!==this.currentUrl&&this.catchBrowserUpdate(e)}}disconnect(){super.disconnect(),D&&window.removeEventListener("popstate",this.onpopstate)}async process(e,t,i,r=!0){const s=await super.process(e,t,i,r);return s&&!this.historyDisabled&&r&&this.connected&&!this.parent&&(t?function(e,t){const i=t||{};window.history.replaceState(i,"",e)}(e):function(e,t){const i=t||{};window.history.pushState(i,"",e)}(e),this.currentUrl=e),s}catchBrowserUpdate(e){this.process(e,!1,{},!1)}}s(z,{fields:["historyDisabled","currentUrl"]});let Y=!1;class J extends o{constructor(){super(),this.router=void 0,this.historyDisabled=!1,this.currentTitle=D?document.title:""}connectedCallback(){const e={historyDisabled:this.historyDisabled,handleNavigation:this.handleNavigation.bind(this)};D&&this.router&&(this.routerApi=function(e,t={},i){const r=t.historyDisabled?new X(t,i,e):new z(t,i,e),s={addPreNavigate:e=>(r.addPreNavigate(e),s),addPostNavigate:e=>(r.subscribe(e),s),addErrorNavigate:e=>(r.addErrorNavigate(e),s),connect:()=>{r.connect(),C(!Y||!!r.parent,T.MULTIPLE_ROOTS),Y=Y||!r.parent,s.id=r.contextId},disconnect:()=>{Y=Y&&!!r.parent,r.disconnect()}};return s}(this,e,this.router),this.routerApi.addPreNavigate(this.preNavigate.bind(this)).addPostNavigate(this.postNavigate.bind(this)).addErrorNavigate(this.errorNavigate.bind(this)).connect())}preNavigate(e){const t=this._createEvent("prenavigate",e,!0);return this.dispatchEvent(t),!t.defaultPrevented}postNavigate(e){this.dispatchEvent(this._createEvent("postnavigate",e));const t=e.routeDefinition.metadata&&e.routeDefinition.metadata.title;t&&(this.currentTitle=t.replace(/[<>&"']/g,(e=>{switch(e){case"<":return"<";case">":return">";case"&":return"&";case'"':return""";case"'":return"'";default:return e}})),document.title=this.currentTitle);const i=this.refs?.title;i&&(i.innerHTML=this.currentTitle)}errorNavigate(e){return this.dispatchEvent(this._createEvent("errornavigate",e)),!0}handleNavigation(e,t){const i=this._createEvent("handlenavigation",{address:e,replace:t},!0);return this.dispatchEvent(i),!i.defaultPrevented}disconnectedCallback(){this.routerApi&&this.routerApi.disconnect()}_createEvent(e,t,i){return new CustomEvent(e,{detail:t,bubbles:!1,composed:!1,cancelable:i})}}J.renderMode="light",s(J,{publicProps:{router:{config:0},historyDisabled:{config:0}}});const Q=n(J,{tmpl:I,sel:"lwr-router-container",apiVersion:63});export{Q as default};
|
|
2
2
|
//# sourceMappingURL=routerContainer.js.map
|
|
@@ -117,6 +117,7 @@ var DomRouterImpl = class {
|
|
|
117
117
|
const contextApi = {
|
|
118
118
|
navigate: (address, replace) => this.navigate(address, replace),
|
|
119
119
|
generateUrl: (address, options) => this.generateUrl(address, options),
|
|
120
|
+
generateUrlAsync: (address, options) => this.generateUrlAsync(address, options),
|
|
120
121
|
subscribe: (callback, replay) => this.subscribe(callback, replay)
|
|
121
122
|
};
|
|
122
123
|
(0, import_navigation.registerNavigationHelm)(this.contextId, contextApi);
|
|
@@ -259,6 +260,15 @@ var DomRouterImpl = class {
|
|
|
259
260
|
const parentPath = this.parent && this.parent.committedRoute && this.parent.committedRoute.pathMatch || "";
|
|
260
261
|
return `${parentPath}${url}`;
|
|
261
262
|
}
|
|
263
|
+
async generateUrlAsync(address, options) {
|
|
264
|
+
const routerOptions = this.filterNavigateOptions(options);
|
|
265
|
+
const url = await this.router.generateUrlAsync(address, routerOptions);
|
|
266
|
+
if (!url) {
|
|
267
|
+
return null;
|
|
268
|
+
}
|
|
269
|
+
const parentPath = this.parent && this.parent.committedRoute && this.parent.committedRoute.pathMatch || "";
|
|
270
|
+
return `${parentPath}${url}`;
|
|
271
|
+
}
|
|
262
272
|
subscribe(callback, replay) {
|
|
263
273
|
return this.routeObservable.subscribe({
|
|
264
274
|
next: callback,
|
|
@@ -25,6 +25,7 @@ var __toModule = (module2) => {
|
|
|
25
25
|
__markAsModule(exports);
|
|
26
26
|
__export(exports, {
|
|
27
27
|
getRelativeUrl: () => import_uriUtils.getRelativeUrl,
|
|
28
|
+
removeFragment: () => import_uriUtils.removeFragment,
|
|
28
29
|
replace: () => import_historyUtils.replace,
|
|
29
30
|
set: () => import_historyUtils.set
|
|
30
31
|
});
|
|
@@ -25,7 +25,8 @@ var __toModule = (module2) => {
|
|
|
25
25
|
__markAsModule(exports);
|
|
26
26
|
__export(exports, {
|
|
27
27
|
getRelativeUrl: () => getRelativeUrl,
|
|
28
|
-
getUrlObject: () => getUrlObject
|
|
28
|
+
getUrlObject: () => getUrlObject,
|
|
29
|
+
removeFragment: () => removeFragment
|
|
29
30
|
});
|
|
30
31
|
var import_routerUtils = __toModule(require("lwr/routerUtils"));
|
|
31
32
|
function getUrlObject(url = "") {
|
|
@@ -59,3 +60,10 @@ function getRelativeUrl(url) {
|
|
|
59
60
|
const origin = urlObj.origin.replace(/:\d+/, "");
|
|
60
61
|
return href.replace(origin, "");
|
|
61
62
|
}
|
|
63
|
+
function removeFragment(url) {
|
|
64
|
+
const hashIndex = url.indexOf("#");
|
|
65
|
+
if (hashIndex !== -1) {
|
|
66
|
+
return url.substring(0, hashIndex);
|
|
67
|
+
}
|
|
68
|
+
return url;
|
|
69
|
+
}
|
|
@@ -34,6 +34,7 @@ var HistoryRouter = class extends import_domRouter.DomRouterImpl {
|
|
|
34
34
|
constructor() {
|
|
35
35
|
super(...arguments);
|
|
36
36
|
this.historyDisabled = false;
|
|
37
|
+
this.currentUrl = "";
|
|
37
38
|
}
|
|
38
39
|
connect() {
|
|
39
40
|
super.connect();
|
|
@@ -44,7 +45,10 @@ var HistoryRouter = class extends import_domRouter.DomRouterImpl {
|
|
|
44
45
|
}
|
|
45
46
|
onpopstate() {
|
|
46
47
|
if (!this.parent && import_routerUtils.hasDocument) {
|
|
47
|
-
|
|
48
|
+
const relativeUrl = (0, import_domRouterUtils.removeFragment)((0, import_domRouterUtils.getRelativeUrl)(window.location.href));
|
|
49
|
+
if (relativeUrl !== this.currentUrl) {
|
|
50
|
+
this.catchBrowserUpdate(relativeUrl);
|
|
51
|
+
}
|
|
48
52
|
}
|
|
49
53
|
}
|
|
50
54
|
disconnect() {
|
|
@@ -59,6 +63,7 @@ var HistoryRouter = class extends import_domRouter.DomRouterImpl {
|
|
|
59
63
|
} else {
|
|
60
64
|
(0, import_domRouterUtils.set)(url);
|
|
61
65
|
}
|
|
66
|
+
this.currentUrl = url;
|
|
62
67
|
}
|
|
63
68
|
return canContinue;
|
|
64
69
|
}
|
|
@@ -25,6 +25,7 @@ var __toModule = (module2) => {
|
|
|
25
25
|
__markAsModule(exports);
|
|
26
26
|
__export(exports, {
|
|
27
27
|
generateUrl: () => generateUrl,
|
|
28
|
+
generateUrlAsync: () => generateUrlAsync,
|
|
28
29
|
navigate: () => navigate
|
|
29
30
|
});
|
|
30
31
|
var import_contextUtils = __toModule(require("lwr/contextUtils"));
|
|
@@ -36,3 +37,7 @@ function generateUrl(context, pageReference, options) {
|
|
|
36
37
|
const api = (0, import_contextUtils.getNavigationHelm)(context);
|
|
37
38
|
return api.generateUrl(pageReference, options);
|
|
38
39
|
}
|
|
40
|
+
function generateUrlAsync(context, pageReference, options) {
|
|
41
|
+
const api = (0, import_contextUtils.getNavigationHelm)(context);
|
|
42
|
+
return api.generateUrlAsync(pageReference, options);
|
|
43
|
+
}
|
|
@@ -61,7 +61,7 @@ function NavigationMixin(Base) {
|
|
|
61
61
|
async [import_constants.GenerateUrl](pageRef, options) {
|
|
62
62
|
if (!isSSR) {
|
|
63
63
|
this[import_constants.GetContext]();
|
|
64
|
-
return (0, import_navigationApi.
|
|
64
|
+
return (0, import_navigationApi.generateUrlAsync)(this[import_constants.NavContext], pageRef, options);
|
|
65
65
|
} else {
|
|
66
66
|
return null;
|
|
67
67
|
}
|
|
@@ -43,7 +43,10 @@ var RouterImpl = class {
|
|
|
43
43
|
generateUrl: (address, options) => (0, import_routerUtils.getUrlFromPageReference)(address, this.compiledRoutes, this.config.basePath, this.config.i18n, options),
|
|
44
44
|
parseUrl: (url) => (0, import_routerUtils.getPageReferenceFromUrl)(url, this.compiledRoutes, this.config.basePath, this.config.i18n)
|
|
45
45
|
};
|
|
46
|
-
const {DEPRECATED_getRouteFromUrl, DEPRECATED_getUrlFromRoute} = config;
|
|
46
|
+
const {generateUrlFilter, DEPRECATED_getRouteFromUrl, DEPRECATED_getUrlFromRoute} = config;
|
|
47
|
+
if (generateUrlFilter) {
|
|
48
|
+
this.config.generateUrlFilter = generateUrlFilter;
|
|
49
|
+
}
|
|
47
50
|
if (DEPRECATED_getRouteFromUrl) {
|
|
48
51
|
this.deprecatedConfig.DEPRECATED_getRouteFromUrl = DEPRECATED_getRouteFromUrl;
|
|
49
52
|
}
|
|
@@ -60,6 +63,14 @@ var RouterImpl = class {
|
|
|
60
63
|
return this.config.generateUrl(address, options);
|
|
61
64
|
}
|
|
62
65
|
}
|
|
66
|
+
generateUrlAsync(address, options) {
|
|
67
|
+
const {generateUrlFilter} = this.config;
|
|
68
|
+
if (generateUrlFilter) {
|
|
69
|
+
return generateUrlFilter(address, this.config.generateUrl, options);
|
|
70
|
+
} else {
|
|
71
|
+
return Promise.resolve(this.generateUrl(address, options));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
63
74
|
parseUrl(url) {
|
|
64
75
|
const {DEPRECATED_getRouteFromUrl: getRouteFromUrl} = this.deprecatedConfig;
|
|
65
76
|
if (getRouteFromUrl) {
|
|
@@ -63,8 +63,23 @@ var RouterContainer = class extends import_lwc.LightningElement {
|
|
|
63
63
|
this.dispatchEvent(this._createEvent("postnavigate", routingResult));
|
|
64
64
|
const title = routingResult.routeDefinition.metadata && routingResult.routeDefinition.metadata.title;
|
|
65
65
|
if (title) {
|
|
66
|
-
this.currentTitle = title
|
|
67
|
-
|
|
66
|
+
this.currentTitle = title.replace(/[<>&"']/g, (char) => {
|
|
67
|
+
switch (char) {
|
|
68
|
+
case "<":
|
|
69
|
+
return "<";
|
|
70
|
+
case ">":
|
|
71
|
+
return ">";
|
|
72
|
+
case "&":
|
|
73
|
+
return "&";
|
|
74
|
+
case '"':
|
|
75
|
+
return """;
|
|
76
|
+
case "'":
|
|
77
|
+
return "'";
|
|
78
|
+
default:
|
|
79
|
+
return char;
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
document.title = this.currentTitle;
|
|
68
83
|
}
|
|
69
84
|
const a11yTitle = this.refs?.title;
|
|
70
85
|
if (a11yTitle)
|
|
@@ -59,6 +59,9 @@ var ServerRouter = class {
|
|
|
59
59
|
generateUrl(address, options) {
|
|
60
60
|
return this.router.generateUrl(address, options);
|
|
61
61
|
}
|
|
62
|
+
generateUrlAsync(address, options) {
|
|
63
|
+
return this.router.generateUrlAsync(address, options);
|
|
64
|
+
}
|
|
62
65
|
initWires(url) {
|
|
63
66
|
if (!url && import_routerUtils.hasDocument) {
|
|
64
67
|
url = document.location.href;
|
|
@@ -72,6 +75,7 @@ var ServerRouter = class {
|
|
|
72
75
|
(0, import_navigation.registerNavigationHelm)(this.contextId, {
|
|
73
76
|
navigate: (address, replace, options) => this.navigate(address, replace, options),
|
|
74
77
|
generateUrl: (address, options) => this.generateUrl(address, options),
|
|
78
|
+
generateUrlAsync: (address, options) => this.generateUrlAsync(address, options),
|
|
75
79
|
subscribe: () => {
|
|
76
80
|
throw new Error("The server router does not support the subscribe API");
|
|
77
81
|
}
|
|
@@ -16,6 +16,7 @@ import type { NavigateOptions } from '../routerUtils/types.js';
|
|
|
16
16
|
export interface NavigationHelm {
|
|
17
17
|
navigate: (address: PageReference, replace?: boolean, options?: NavigateOptions) => void;
|
|
18
18
|
generateUrl: (address: PageReference, options?: NavigateOptions) => string | null;
|
|
19
|
+
generateUrlAsync: (address: PageReference, options?: NavigateOptions) => Promise<string | null>;
|
|
19
20
|
subscribe: (callback: RouteCallback, replay?: boolean) => Unsubscriber;
|
|
20
21
|
}
|
|
21
22
|
interface NavigationContextData {
|
|
@@ -40,6 +40,7 @@ export interface DomRouter extends DomRouterNode {
|
|
|
40
40
|
addErrorNavigate(filters: Filter<MessageObject> | Filter<MessageObject>[]): void;
|
|
41
41
|
navigate(address: PageReference, replace?: boolean, options?: NavigateOptions): void;
|
|
42
42
|
generateUrl(address: PageReference, options?: NavigateOptions): string | null;
|
|
43
|
+
generateUrlAsync(address: PageReference, options?: NavigateOptions): Promise<string | null>;
|
|
43
44
|
subscribe(callback: RouteCallback, replay?: boolean): Unsubscriber;
|
|
44
45
|
}
|
|
45
46
|
export declare class DomRouterImpl implements DomRouter {
|
|
@@ -144,13 +145,18 @@ export declare class DomRouterImpl implements DomRouter {
|
|
|
144
145
|
/**
|
|
145
146
|
* lightning/navigation
|
|
146
147
|
* Generate a URL based on the given route.
|
|
147
|
-
* Return
|
|
148
|
+
* Return the URL string.
|
|
148
149
|
*
|
|
149
150
|
* @param {object} route - Route to generate a url for
|
|
150
151
|
*
|
|
151
|
-
* @returns {
|
|
152
|
+
* @returns {string}
|
|
152
153
|
*/
|
|
153
154
|
generateUrl(address: PageReference, options?: NavigateOptions): string | null;
|
|
155
|
+
/**
|
|
156
|
+
* Async version of generateUrl, used by the NavigationMixin and goes through the generateUrlFilter.
|
|
157
|
+
* @returns {Promise<string>}
|
|
158
|
+
*/
|
|
159
|
+
generateUrlAsync(address: PageReference, options?: NavigateOptions): Promise<string | null>;
|
|
154
160
|
/**
|
|
155
161
|
* lightning/navigation
|
|
156
162
|
* Subscribe a callback to the Observable on the current route of this router.
|
|
@@ -114,6 +114,7 @@ export class DomRouterImpl {
|
|
|
114
114
|
const contextApi = {
|
|
115
115
|
navigate: (address, replace) => this.navigate(address, replace),
|
|
116
116
|
generateUrl: (address, options) => this.generateUrl(address, options),
|
|
117
|
+
generateUrlAsync: (address, options) => this.generateUrlAsync(address, options),
|
|
117
118
|
subscribe: (callback, replay) => this.subscribe(callback, replay),
|
|
118
119
|
};
|
|
119
120
|
registerNavigationHelm(this.contextId, contextApi);
|
|
@@ -342,11 +343,11 @@ export class DomRouterImpl {
|
|
|
342
343
|
/**
|
|
343
344
|
* lightning/navigation
|
|
344
345
|
* Generate a URL based on the given route.
|
|
345
|
-
* Return
|
|
346
|
+
* Return the URL string.
|
|
346
347
|
*
|
|
347
348
|
* @param {object} route - Route to generate a url for
|
|
348
349
|
*
|
|
349
|
-
* @returns {
|
|
350
|
+
* @returns {string}
|
|
350
351
|
*/
|
|
351
352
|
generateUrl(address, options) {
|
|
352
353
|
const routerOptions = this.filterNavigateOptions(options);
|
|
@@ -360,6 +361,19 @@ export class DomRouterImpl {
|
|
|
360
361
|
const parentPath = (this.parent && this.parent.committedRoute && this.parent.committedRoute.pathMatch) || '';
|
|
361
362
|
return `${parentPath}${url}`;
|
|
362
363
|
}
|
|
364
|
+
/**
|
|
365
|
+
* Async version of generateUrl, used by the NavigationMixin and goes through the generateUrlFilter.
|
|
366
|
+
* @returns {Promise<string>}
|
|
367
|
+
*/
|
|
368
|
+
async generateUrlAsync(address, options) {
|
|
369
|
+
const routerOptions = this.filterNavigateOptions(options);
|
|
370
|
+
const url = await this.router.generateUrlAsync(address, routerOptions);
|
|
371
|
+
if (!url) {
|
|
372
|
+
return null;
|
|
373
|
+
}
|
|
374
|
+
const parentPath = (this.parent && this.parent.committedRoute && this.parent.committedRoute.pathMatch) || '';
|
|
375
|
+
return `${parentPath}${url}`;
|
|
376
|
+
}
|
|
363
377
|
/**
|
|
364
378
|
* lightning/navigation
|
|
365
379
|
* Subscribe a callback to the Observable on the current route of this router.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { getRelativeUrl } from './uriUtils.js';
|
|
1
|
+
export { getRelativeUrl, removeFragment } from './uriUtils.js';
|
|
2
2
|
export { set, replace } from './historyUtils.js';
|
|
3
3
|
export type { DomRouterConfig, NavigationHandler, RouteChange } from './types.js';
|
|
4
4
|
//# sourceMappingURL=domRouterUtils.d.ts.map
|
|
@@ -27,4 +27,11 @@ export declare function getUrlObject(url?: string): UrlObject;
|
|
|
27
27
|
* @return {string}
|
|
28
28
|
*/
|
|
29
29
|
export declare function getRelativeUrl(url: string): string;
|
|
30
|
+
/**
|
|
31
|
+
* Remove the fragment identifier from a URL.
|
|
32
|
+
*
|
|
33
|
+
* @param {string} url - The URL to remove the fragment identifier from.
|
|
34
|
+
* @returns {string} The URL without the fragment identifier.
|
|
35
|
+
*/
|
|
36
|
+
export declare function removeFragment(url: string): string;
|
|
30
37
|
//# sourceMappingURL=uriUtils.d.ts.map
|
|
@@ -66,4 +66,17 @@ export function getRelativeUrl(url) {
|
|
|
66
66
|
const origin = urlObj.origin.replace(/:\d+/, '');
|
|
67
67
|
return href.replace(origin, '');
|
|
68
68
|
}
|
|
69
|
+
/**
|
|
70
|
+
* Remove the fragment identifier from a URL.
|
|
71
|
+
*
|
|
72
|
+
* @param {string} url - The URL to remove the fragment identifier from.
|
|
73
|
+
* @returns {string} The URL without the fragment identifier.
|
|
74
|
+
*/
|
|
75
|
+
export function removeFragment(url) {
|
|
76
|
+
const hashIndex = url.indexOf('#');
|
|
77
|
+
if (hashIndex !== -1) {
|
|
78
|
+
return url.substring(0, hashIndex);
|
|
79
|
+
}
|
|
80
|
+
return url;
|
|
81
|
+
}
|
|
69
82
|
//# sourceMappingURL=uriUtils.js.map
|
|
@@ -10,6 +10,7 @@ import type { DomRouterConfig } from 'lwr/domRouterUtils';
|
|
|
10
10
|
import type { NavigateOptions } from '../routerUtils/types.js';
|
|
11
11
|
export declare class HistoryRouter extends DomRouterImpl {
|
|
12
12
|
historyDisabled: boolean;
|
|
13
|
+
currentUrl: string;
|
|
13
14
|
/**
|
|
14
15
|
* Override.
|
|
15
16
|
* Initialize with the current route and listen to the popstate event for future changes.
|
|
@@ -5,13 +5,14 @@
|
|
|
5
5
|
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
|
|
6
6
|
*/
|
|
7
7
|
import { DomRouterImpl } from 'lwr/domRouter';
|
|
8
|
-
import { getRelativeUrl, replace, set } from 'lwr/domRouterUtils';
|
|
8
|
+
import { getRelativeUrl, removeFragment, replace, set } from 'lwr/domRouterUtils';
|
|
9
9
|
import { hasDocument } from 'lwr/routerUtils';
|
|
10
10
|
/*
|
|
11
11
|
* Provides a Router rooted to the window, which controls the browser history by default.
|
|
12
12
|
*/
|
|
13
13
|
export class HistoryRouter extends DomRouterImpl {
|
|
14
14
|
historyDisabled = false;
|
|
15
|
+
currentUrl = '';
|
|
15
16
|
/**
|
|
16
17
|
* Override.
|
|
17
18
|
* Initialize with the current route and listen to the popstate event for future changes.
|
|
@@ -28,7 +29,11 @@ export class HistoryRouter extends DomRouterImpl {
|
|
|
28
29
|
onpopstate() {
|
|
29
30
|
// Only the root should update the url since it has the full context
|
|
30
31
|
if (!this.parent && hasDocument) {
|
|
31
|
-
|
|
32
|
+
// Remove fragment identifier from URL, we never want to navigate for fragment changes
|
|
33
|
+
const relativeUrl = removeFragment(getRelativeUrl(window.location.href));
|
|
34
|
+
if (relativeUrl !== this.currentUrl) {
|
|
35
|
+
this.catchBrowserUpdate(relativeUrl);
|
|
36
|
+
}
|
|
32
37
|
}
|
|
33
38
|
}
|
|
34
39
|
disconnect() {
|
|
@@ -57,6 +62,7 @@ export class HistoryRouter extends DomRouterImpl {
|
|
|
57
62
|
else {
|
|
58
63
|
set(url);
|
|
59
64
|
}
|
|
65
|
+
this.currentUrl = url;
|
|
60
66
|
}
|
|
61
67
|
return canContinue;
|
|
62
68
|
}
|
|
@@ -17,7 +17,12 @@ export declare function navigate(context: ContextId, pageReference: PageReferenc
|
|
|
17
17
|
* @param {HTMLElement} context - The navigation context
|
|
18
18
|
* @param {PageReference} pageReference - A page reference location
|
|
19
19
|
*
|
|
20
|
-
* @returns {
|
|
20
|
+
* @returns {string | null}
|
|
21
21
|
*/
|
|
22
22
|
export declare function generateUrl(context: ContextId, pageReference: PageReference, options?: NavigateOptions): string | null;
|
|
23
|
+
/**
|
|
24
|
+
* Async version of generateUrl, used by the NavigationMixin.
|
|
25
|
+
* @returns {Promise<string | null>}
|
|
26
|
+
*/
|
|
27
|
+
export declare function generateUrlAsync(context: ContextId, pageReference: PageReference, options?: NavigateOptions): Promise<string | null>;
|
|
23
28
|
//# sourceMappingURL=navigationApi.d.ts.map
|
|
@@ -18,10 +18,18 @@ export function navigate(context, pageReference, replace, options) {
|
|
|
18
18
|
* @param {HTMLElement} context - The navigation context
|
|
19
19
|
* @param {PageReference} pageReference - A page reference location
|
|
20
20
|
*
|
|
21
|
-
* @returns {
|
|
21
|
+
* @returns {string | null}
|
|
22
22
|
*/
|
|
23
23
|
export function generateUrl(context, pageReference, options) {
|
|
24
24
|
const api = getNavigationHelm(context);
|
|
25
25
|
return api.generateUrl(pageReference, options);
|
|
26
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* Async version of generateUrl, used by the NavigationMixin.
|
|
29
|
+
* @returns {Promise<string | null>}
|
|
30
|
+
*/
|
|
31
|
+
export function generateUrlAsync(context, pageReference, options) {
|
|
32
|
+
const api = getNavigationHelm(context);
|
|
33
|
+
return api.generateUrlAsync(pageReference, options);
|
|
34
|
+
}
|
|
27
35
|
//# sourceMappingURL=navigationApi.js.map
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// symbols as indexes, which typescript does not like, necessitating 'any'
|
|
9
9
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
10
10
|
import { invariant, generateMessage, messages } from 'lwr/routerErrors';
|
|
11
|
-
import {
|
|
11
|
+
import { generateUrlAsync, navigate } from './navigationApi.js';
|
|
12
12
|
import { CONTEXT_ID_BACKDOOR } from 'lwr/navigationMixinHacks';
|
|
13
13
|
import { Navigate, GenerateUrl, NavContext, GetContext } from './constants.js';
|
|
14
14
|
// eslint-disable-next-line lwr/no-unguarded-apis
|
|
@@ -66,7 +66,7 @@ function NavigationMixin(Base) {
|
|
|
66
66
|
async [GenerateUrl](pageRef, options) {
|
|
67
67
|
if (!isSSR) {
|
|
68
68
|
this[GetContext]();
|
|
69
|
-
return
|
|
69
|
+
return generateUrlAsync(this[NavContext], pageRef, options);
|
|
70
70
|
}
|
|
71
71
|
else {
|
|
72
72
|
return null;
|
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
* SPDX-License-Identifier: MIT
|
|
5
5
|
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
|
|
6
6
|
*/
|
|
7
|
-
import type { PageReference, RouteCallback, RouteDefinition, RouteHandler, RouteHandlerClass, Router, RouterConfig, RouteDestination, RoutingMatch, RoutingResult, ViewSet, ViewInfo } from 'lwr/routerUtils';
|
|
7
|
+
import type { GenerateUrlFilter, PageReference, RouteCallback, RouteDefinition, RouteHandler, RouteHandlerClass, Router, RouterConfig, RouteDestination, RoutingMatch, RoutingResult, ViewSet, ViewInfo } from 'lwr/routerUtils';
|
|
8
8
|
export declare function createRouter(config?: RouterConfig<PageReference>): Router<PageReference>;
|
|
9
|
-
export type { PageReference, Router, RouterConfig, RouteCallback, RouteDefinition, RouteDestination, RouteHandler, RouteHandlerClass, RoutingMatch, RoutingResult, ViewSet, ViewInfo, };
|
|
9
|
+
export type { GenerateUrlFilter, PageReference, Router, RouterConfig, RouteCallback, RouteDefinition, RouteDestination, RouteHandler, RouteHandlerClass, RoutingMatch, RoutingResult, ViewSet, ViewInfo, };
|
|
10
10
|
export type { Module, RouteHandlerCallback, RouteHandlerModule, RouteInstance, StringAttributes, } from 'lwr/routerUtils';
|
|
11
11
|
//# sourceMappingURL=router.d.ts.map
|
|
@@ -32,7 +32,11 @@ class RouterImpl {
|
|
|
32
32
|
generateUrl: (address, options) => getUrlFromPageReference(address, this.compiledRoutes, this.config.basePath, this.config.i18n, options),
|
|
33
33
|
parseUrl: (url) => getPageReferenceFromUrl(url, this.compiledRoutes, this.config.basePath, this.config.i18n),
|
|
34
34
|
};
|
|
35
|
-
const { DEPRECATED_getRouteFromUrl, DEPRECATED_getUrlFromRoute } = config;
|
|
35
|
+
const { generateUrlFilter, DEPRECATED_getRouteFromUrl, DEPRECATED_getUrlFromRoute } = config;
|
|
36
|
+
if (generateUrlFilter) {
|
|
37
|
+
// used in generateUrlAsync
|
|
38
|
+
this.config.generateUrlFilter = generateUrlFilter;
|
|
39
|
+
}
|
|
36
40
|
if (DEPRECATED_getRouteFromUrl) {
|
|
37
41
|
this.deprecatedConfig.DEPRECATED_getRouteFromUrl = DEPRECATED_getRouteFromUrl;
|
|
38
42
|
}
|
|
@@ -55,6 +59,20 @@ class RouterImpl {
|
|
|
55
59
|
return this.config.generateUrl(address, options);
|
|
56
60
|
}
|
|
57
61
|
}
|
|
62
|
+
/**
|
|
63
|
+
* Async version of generateUrl.
|
|
64
|
+
* @returns {Promise<string | null>}
|
|
65
|
+
*/
|
|
66
|
+
generateUrlAsync(address, options) {
|
|
67
|
+
const { generateUrlFilter } = this.config;
|
|
68
|
+
if (generateUrlFilter) {
|
|
69
|
+
return generateUrlFilter(address, this.config.generateUrl, options);
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
// fallback to the sync version
|
|
73
|
+
return Promise.resolve(this.generateUrl(address, options));
|
|
74
|
+
}
|
|
75
|
+
}
|
|
58
76
|
/**
|
|
59
77
|
* Convert url string to address.
|
|
60
78
|
*
|
|
@@ -67,8 +67,24 @@ export default class RouterContainer extends LightningElement {
|
|
|
67
67
|
// If the current route definition metadata contains a title, set it as the document title
|
|
68
68
|
const title = routingResult.routeDefinition.metadata && routingResult.routeDefinition.metadata.title;
|
|
69
69
|
if (title) {
|
|
70
|
-
|
|
71
|
-
|
|
70
|
+
// sanitize the title to prevent XSS attacks
|
|
71
|
+
this.currentTitle = title.replace(/[<>&"']/g, (char) => {
|
|
72
|
+
switch (char) {
|
|
73
|
+
case '<':
|
|
74
|
+
return '<';
|
|
75
|
+
case '>':
|
|
76
|
+
return '>';
|
|
77
|
+
case '&':
|
|
78
|
+
return '&';
|
|
79
|
+
case '"':
|
|
80
|
+
return '"';
|
|
81
|
+
case "'":
|
|
82
|
+
return ''';
|
|
83
|
+
default:
|
|
84
|
+
return char;
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
document.title = this.currentTitle;
|
|
72
88
|
}
|
|
73
89
|
// Update the inner HTML of the aria-live region for screen readers
|
|
74
90
|
// This DOM node must be touched for every route change
|
|
@@ -18,5 +18,5 @@ export { getPathFromUrl, getQueryFromUrl, getQueryString, encode, decode } from
|
|
|
18
18
|
export { hasDocument } from './domUtils.js';
|
|
19
19
|
export type { Key } from './pathToRegexp.js';
|
|
20
20
|
export type { Filter, FilterChain } from './filterUtils.js';
|
|
21
|
-
export type { CompiledRouteDefinition, CompiledRoutingMatch, Constructor, Constructable, MessageObject, Module, PageReference, RouteCallback, RouteDefinition, RouteHandler, RouteHandlerCallback, RouteHandlerClass, RouteHandlerModule, Router, RouterConfig, RouteDestination, RouteInstance, RoutingMatch, RoutingResult, StringAttributes, UrlMapper, ViewSet, ViewInfo, RouterSerializationConfig, } from './types.js';
|
|
21
|
+
export type { CompiledRouteDefinition, CompiledRoutingMatch, Constructor, Constructable, GenerateUrlFilter, MessageObject, Module, PageReference, RouteCallback, RouteDefinition, RouteHandler, RouteHandlerCallback, RouteHandlerClass, RouteHandlerModule, Router, RouterConfig, RouteDestination, RouteInstance, RoutingMatch, RoutingResult, StringAttributes, UrlMapper, ViewSet, ViewInfo, RouterSerializationConfig, } from './types.js';
|
|
22
22
|
//# sourceMappingURL=routerUtils.d.ts.map
|
|
@@ -6,10 +6,13 @@ export type Constructor<T = object> = new (...args: any[]) => T;
|
|
|
6
6
|
export interface Constructable<T = object> {
|
|
7
7
|
constructor: Constructor<T>;
|
|
8
8
|
}
|
|
9
|
-
export type
|
|
9
|
+
export type UrlMapperAPI<TAddress> = {
|
|
10
10
|
generateUrl(address: TAddress, options?: NavigateOptions): string | null;
|
|
11
11
|
parseUrl(url: string): TAddress | null;
|
|
12
12
|
};
|
|
13
|
+
export type UrlMapper<TAddress> = UrlMapperAPI<TAddress> & {
|
|
14
|
+
generateUrlAsync(address: TAddress, options?: NavigateOptions): Promise<string | null>;
|
|
15
|
+
};
|
|
13
16
|
export type RouteMatcher<TAddress> = {
|
|
14
17
|
matchRoute(address: TAddress, options?: NavigateOptions): RoutingMatch | null;
|
|
15
18
|
};
|
|
@@ -20,6 +23,7 @@ export type ViewMapper<TAddress> = {
|
|
|
20
23
|
contextId?: ContextId;
|
|
21
24
|
};
|
|
22
25
|
export type Router<TAddress = string> = ViewMapper<TAddress> & UrlMapper<TAddress> & RouteMatcher<TAddress>;
|
|
26
|
+
export type GenerateUrlFilter<TAddress> = (route: TAddress, defaultImpl: UrlMapper<TAddress>['generateUrl'], options?: NavigateOptions) => Promise<string | null>;
|
|
23
27
|
export type DEPRECATED_getRouteFromUrl<TAddress> = (url: string, defaultImpl: UrlMapper<TAddress>['parseUrl']) => TAddress | null;
|
|
24
28
|
export type DEPRECATED_getUrlFromRoute<TAddress> = (route: TAddress, defaultImpl: UrlMapper<TAddress>['generateUrl'], options?: NavigateOptions) => string | null;
|
|
25
29
|
export type I18nRouterConfig = {
|
|
@@ -31,10 +35,13 @@ export type RouterConfig<TAddress> = {
|
|
|
31
35
|
i18n?: I18nRouterConfig;
|
|
32
36
|
routes?: RouteDefinition[];
|
|
33
37
|
caseSensitive?: boolean;
|
|
38
|
+
generateUrlFilter?: GenerateUrlFilter<TAddress>;
|
|
34
39
|
DEPRECATED_getRouteFromUrl?: DEPRECATED_getRouteFromUrl<TAddress>;
|
|
35
40
|
DEPRECATED_getUrlFromRoute?: DEPRECATED_getUrlFromRoute<TAddress>;
|
|
36
41
|
};
|
|
37
|
-
export type RouterSerializationConfig<TAddress> = Required<Omit<RouterConfig<TAddress>, 'DEPRECATED_getRouteFromUrl' | 'DEPRECATED_getUrlFromRoute'> &
|
|
42
|
+
export type RouterSerializationConfig<TAddress> = Required<Omit<RouterConfig<TAddress>, 'generateUrlFilter' | 'DEPRECATED_getRouteFromUrl' | 'DEPRECATED_getUrlFromRoute'> & UrlMapperAPI<TAddress>> & {
|
|
43
|
+
generateUrlFilter?: GenerateUrlFilter<TAddress>;
|
|
44
|
+
};
|
|
38
45
|
export type RouteParameterPatterns = {
|
|
39
46
|
[paramName: string]: string;
|
|
40
47
|
};
|
|
@@ -32,6 +32,10 @@ export declare class ServerRouter {
|
|
|
32
32
|
* Generate a URL based on the given page reference
|
|
33
33
|
*/
|
|
34
34
|
generateUrl(address: PageReference, options?: NavigateOptions): string | null;
|
|
35
|
+
/**
|
|
36
|
+
* Async version of generateUrl
|
|
37
|
+
*/
|
|
38
|
+
generateUrlAsync(address: PageReference, options?: NavigateOptions): Promise<string | null>;
|
|
35
39
|
/**
|
|
36
40
|
* Initialize the CurrentPageReference & NavigationContext wires plus the client-only NavigationMixin
|
|
37
41
|
* On the server, use the URL from the config
|
|
@@ -48,6 +48,12 @@ export class ServerRouter {
|
|
|
48
48
|
generateUrl(address, options) {
|
|
49
49
|
return this.router.generateUrl(address, options);
|
|
50
50
|
}
|
|
51
|
+
/**
|
|
52
|
+
* Async version of generateUrl
|
|
53
|
+
*/
|
|
54
|
+
generateUrlAsync(address, options) {
|
|
55
|
+
return this.router.generateUrlAsync(address, options);
|
|
56
|
+
}
|
|
51
57
|
/**
|
|
52
58
|
* Initialize the CurrentPageReference & NavigationContext wires plus the client-only NavigationMixin
|
|
53
59
|
* On the server, use the URL from the config
|
|
@@ -71,6 +77,7 @@ export class ServerRouter {
|
|
|
71
77
|
registerNavigationHelm(this.contextId, {
|
|
72
78
|
navigate: (address, replace, options) => this.navigate(address, replace, options),
|
|
73
79
|
generateUrl: (address, options) => this.generateUrl(address, options),
|
|
80
|
+
generateUrlAsync: (address, options) => this.generateUrlAsync(address, options),
|
|
74
81
|
// the JS context is lost during hard navigation, so subscribing to route changes will not work
|
|
75
82
|
subscribe: () => {
|
|
76
83
|
throw new Error('The server router does not support the subscribe API');
|
|
@@ -135,6 +135,7 @@ export class DomRouterImpl {
|
|
|
135
135
|
const contextApi = {
|
|
136
136
|
navigate: (address, replace) => this.navigate(address, replace),
|
|
137
137
|
generateUrl: (address, options) => this.generateUrl(address, options),
|
|
138
|
+
generateUrlAsync: (address, options) => this.generateUrlAsync(address, options),
|
|
138
139
|
subscribe: (callback, replay) => this.subscribe(callback, replay)
|
|
139
140
|
};
|
|
140
141
|
registerNavigationHelm(this.contextId, contextApi);
|
|
@@ -387,11 +388,11 @@ export class DomRouterImpl {
|
|
|
387
388
|
/**
|
|
388
389
|
* lightning/navigation
|
|
389
390
|
* Generate a URL based on the given route.
|
|
390
|
-
* Return
|
|
391
|
+
* Return the URL string.
|
|
391
392
|
*
|
|
392
393
|
* @param {object} route - Route to generate a url for
|
|
393
394
|
*
|
|
394
|
-
* @returns {
|
|
395
|
+
* @returns {string}
|
|
395
396
|
*/
|
|
396
397
|
generateUrl(address, options) {
|
|
397
398
|
const routerOptions = this.filterNavigateOptions(options);
|
|
@@ -408,6 +409,20 @@ export class DomRouterImpl {
|
|
|
408
409
|
return `${parentPath}${url}`;
|
|
409
410
|
}
|
|
410
411
|
|
|
412
|
+
/**
|
|
413
|
+
* Async version of generateUrl, used by the NavigationMixin and goes through the generateUrlFilter.
|
|
414
|
+
* @returns {Promise<string>}
|
|
415
|
+
*/
|
|
416
|
+
async generateUrlAsync(address, options) {
|
|
417
|
+
const routerOptions = this.filterNavigateOptions(options);
|
|
418
|
+
const url = await this.router.generateUrlAsync(address, routerOptions);
|
|
419
|
+
if (!url) {
|
|
420
|
+
return null;
|
|
421
|
+
}
|
|
422
|
+
const parentPath = this.parent && this.parent.committedRoute && this.parent.committedRoute.pathMatch || '';
|
|
423
|
+
return `${parentPath}${url}`;
|
|
424
|
+
}
|
|
425
|
+
|
|
411
426
|
/**
|
|
412
427
|
* lightning/navigation
|
|
413
428
|
* Subscribe a callback to the Observable on the current route of this router.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { getRelativeUrl } from './uriUtils.js';
|
|
1
|
+
export { getRelativeUrl, removeFragment } from './uriUtils.js';
|
|
2
2
|
export { set, replace } from './historyUtils.js';
|
|
@@ -70,4 +70,18 @@ export function getRelativeUrl(url) {
|
|
|
70
70
|
const href = urlObj.href.replace(/:\d+/, '');
|
|
71
71
|
const origin = urlObj.origin.replace(/:\d+/, '');
|
|
72
72
|
return href.replace(origin, '');
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Remove the fragment identifier from a URL.
|
|
77
|
+
*
|
|
78
|
+
* @param {string} url - The URL to remove the fragment identifier from.
|
|
79
|
+
* @returns {string} The URL without the fragment identifier.
|
|
80
|
+
*/
|
|
81
|
+
export function removeFragment(url) {
|
|
82
|
+
const hashIndex = url.indexOf('#');
|
|
83
|
+
if (hashIndex !== -1) {
|
|
84
|
+
return url.substring(0, hashIndex);
|
|
85
|
+
}
|
|
86
|
+
return url;
|
|
73
87
|
}
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { DomRouterImpl } from 'lwr/domRouter';
|
|
9
|
-
import { getRelativeUrl, replace, set } from 'lwr/domRouterUtils';
|
|
9
|
+
import { getRelativeUrl, removeFragment, replace, set } from 'lwr/domRouterUtils';
|
|
10
10
|
import { hasDocument } from 'lwr/routerUtils';
|
|
11
11
|
/*
|
|
12
12
|
* Provides a Router rooted to the window, which controls the browser history by default.
|
|
@@ -14,6 +14,7 @@ import { hasDocument } from 'lwr/routerUtils';
|
|
|
14
14
|
|
|
15
15
|
export class HistoryRouter extends DomRouterImpl {
|
|
16
16
|
historyDisabled = false;
|
|
17
|
+
currentUrl = '';
|
|
17
18
|
|
|
18
19
|
/**
|
|
19
20
|
* Override.
|
|
@@ -32,7 +33,11 @@ export class HistoryRouter extends DomRouterImpl {
|
|
|
32
33
|
onpopstate() {
|
|
33
34
|
// Only the root should update the url since it has the full context
|
|
34
35
|
if (!this.parent && hasDocument) {
|
|
35
|
-
|
|
36
|
+
// Remove fragment identifier from URL, we never want to navigate for fragment changes
|
|
37
|
+
const relativeUrl = removeFragment(getRelativeUrl(window.location.href));
|
|
38
|
+
if (relativeUrl !== this.currentUrl) {
|
|
39
|
+
this.catchBrowserUpdate(relativeUrl);
|
|
40
|
+
}
|
|
36
41
|
}
|
|
37
42
|
}
|
|
38
43
|
disconnect() {
|
|
@@ -62,6 +67,7 @@ export class HistoryRouter extends DomRouterImpl {
|
|
|
62
67
|
} else {
|
|
63
68
|
set(url);
|
|
64
69
|
}
|
|
70
|
+
this.currentUrl = url;
|
|
65
71
|
}
|
|
66
72
|
return canContinue;
|
|
67
73
|
}
|
|
@@ -19,9 +19,18 @@ export function navigate(context, pageReference, replace, options) {
|
|
|
19
19
|
* @param {HTMLElement} context - The navigation context
|
|
20
20
|
* @param {PageReference} pageReference - A page reference location
|
|
21
21
|
*
|
|
22
|
-
* @returns {
|
|
22
|
+
* @returns {string | null}
|
|
23
23
|
*/
|
|
24
24
|
export function generateUrl(context, pageReference, options) {
|
|
25
25
|
const api = getNavigationHelm(context);
|
|
26
26
|
return api.generateUrl(pageReference, options);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Async version of generateUrl, used by the NavigationMixin.
|
|
31
|
+
* @returns {Promise<string | null>}
|
|
32
|
+
*/
|
|
33
|
+
export function generateUrlAsync(context, pageReference, options) {
|
|
34
|
+
const api = getNavigationHelm(context);
|
|
35
|
+
return api.generateUrlAsync(pageReference, options);
|
|
27
36
|
}
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
11
11
|
|
|
12
12
|
import { invariant, generateMessage, messages } from 'lwr/routerErrors';
|
|
13
|
-
import {
|
|
13
|
+
import { generateUrlAsync, navigate } from './navigationApi.js';
|
|
14
14
|
import { CONTEXT_ID_BACKDOOR } from 'lwr/navigationMixinHacks';
|
|
15
15
|
import { Navigate, GenerateUrl, NavContext, GetContext } from './constants.js';
|
|
16
16
|
// eslint-disable-next-line lwr/no-unguarded-apis
|
|
@@ -68,7 +68,7 @@ function NavigationMixin(Base) {
|
|
|
68
68
|
async [GenerateUrl](pageRef, options) {
|
|
69
69
|
if (!isSSR) {
|
|
70
70
|
this[GetContext]();
|
|
71
|
-
return
|
|
71
|
+
return generateUrlAsync(this[NavContext], pageRef, options);
|
|
72
72
|
} else {
|
|
73
73
|
return null;
|
|
74
74
|
}
|
|
@@ -32,9 +32,14 @@ class RouterImpl {
|
|
|
32
32
|
parseUrl: url => getPageReferenceFromUrl(url, this.compiledRoutes, this.config.basePath, this.config.i18n)
|
|
33
33
|
};
|
|
34
34
|
const {
|
|
35
|
+
generateUrlFilter,
|
|
35
36
|
DEPRECATED_getRouteFromUrl,
|
|
36
37
|
DEPRECATED_getUrlFromRoute
|
|
37
38
|
} = config;
|
|
39
|
+
if (generateUrlFilter) {
|
|
40
|
+
// used in generateUrlAsync
|
|
41
|
+
this.config.generateUrlFilter = generateUrlFilter;
|
|
42
|
+
}
|
|
38
43
|
if (DEPRECATED_getRouteFromUrl) {
|
|
39
44
|
this.deprecatedConfig.DEPRECATED_getRouteFromUrl = DEPRECATED_getRouteFromUrl;
|
|
40
45
|
}
|
|
@@ -60,6 +65,22 @@ class RouterImpl {
|
|
|
60
65
|
}
|
|
61
66
|
}
|
|
62
67
|
|
|
68
|
+
/**
|
|
69
|
+
* Async version of generateUrl.
|
|
70
|
+
* @returns {Promise<string | null>}
|
|
71
|
+
*/
|
|
72
|
+
generateUrlAsync(address, options) {
|
|
73
|
+
const {
|
|
74
|
+
generateUrlFilter
|
|
75
|
+
} = this.config;
|
|
76
|
+
if (generateUrlFilter) {
|
|
77
|
+
return generateUrlFilter(address, this.config.generateUrl, options);
|
|
78
|
+
} else {
|
|
79
|
+
// fallback to the sync version
|
|
80
|
+
return Promise.resolve(this.generateUrl(address, options));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
63
84
|
/**
|
|
64
85
|
* Convert url string to address.
|
|
65
86
|
*
|
|
@@ -67,8 +67,24 @@ export default class RouterContainer extends LightningElement {
|
|
|
67
67
|
// If the current route definition metadata contains a title, set it as the document title
|
|
68
68
|
const title = routingResult.routeDefinition.metadata && routingResult.routeDefinition.metadata.title;
|
|
69
69
|
if (title) {
|
|
70
|
-
|
|
71
|
-
|
|
70
|
+
// sanitize the title to prevent XSS attacks
|
|
71
|
+
this.currentTitle = title.replace(/[<>&"']/g, char => {
|
|
72
|
+
switch (char) {
|
|
73
|
+
case '<':
|
|
74
|
+
return '<';
|
|
75
|
+
case '>':
|
|
76
|
+
return '>';
|
|
77
|
+
case '&':
|
|
78
|
+
return '&';
|
|
79
|
+
case '"':
|
|
80
|
+
return '"';
|
|
81
|
+
case "'":
|
|
82
|
+
return ''';
|
|
83
|
+
default:
|
|
84
|
+
return char;
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
document.title = this.currentTitle;
|
|
72
88
|
}
|
|
73
89
|
// Update the inner HTML of the aria-live region for screen readers
|
|
74
90
|
// This DOM node must be touched for every route change
|
|
@@ -48,6 +48,13 @@ export class ServerRouter {
|
|
|
48
48
|
return this.router.generateUrl(address, options);
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
+
/**
|
|
52
|
+
* Async version of generateUrl
|
|
53
|
+
*/
|
|
54
|
+
generateUrlAsync(address, options) {
|
|
55
|
+
return this.router.generateUrlAsync(address, options);
|
|
56
|
+
}
|
|
57
|
+
|
|
51
58
|
/**
|
|
52
59
|
* Initialize the CurrentPageReference & NavigationContext wires plus the client-only NavigationMixin
|
|
53
60
|
* On the server, use the URL from the config
|
|
@@ -73,6 +80,7 @@ export class ServerRouter {
|
|
|
73
80
|
registerNavigationHelm(this.contextId, {
|
|
74
81
|
navigate: (address, replace, options) => this.navigate(address, replace, options),
|
|
75
82
|
generateUrl: (address, options) => this.generateUrl(address, options),
|
|
83
|
+
generateUrlAsync: (address, options) => this.generateUrlAsync(address, options),
|
|
76
84
|
// the JS context is lost during hard navigation, so subscribing to route changes will not work
|
|
77
85
|
subscribe: () => {
|
|
78
86
|
throw new Error('The server router does not support the subscribe API');
|
package/package.json
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
7
7
|
},
|
|
8
|
-
"version": "0.19.0-alpha.
|
|
8
|
+
"version": "0.19.0-alpha.10",
|
|
9
9
|
"homepage": "https://developer.salesforce.com/docs/platform/lwr/overview",
|
|
10
10
|
"repository": {
|
|
11
11
|
"type": "git",
|
|
@@ -53,14 +53,14 @@
|
|
|
53
53
|
"test:server": "jest --config ./jest.server.config.cjs"
|
|
54
54
|
},
|
|
55
55
|
"dependencies": {
|
|
56
|
-
"@lwrjs/client-modules": "0.19.0-alpha.
|
|
57
|
-
"@lwrjs/diagnostics": "0.19.0-alpha.
|
|
58
|
-
"@lwrjs/shared-utils": "0.19.0-alpha.
|
|
56
|
+
"@lwrjs/client-modules": "0.19.0-alpha.10",
|
|
57
|
+
"@lwrjs/diagnostics": "0.19.0-alpha.10",
|
|
58
|
+
"@lwrjs/shared-utils": "0.19.0-alpha.10",
|
|
59
59
|
"ajv": "6.12.6"
|
|
60
60
|
},
|
|
61
61
|
"devDependencies": {
|
|
62
62
|
"@lwc/jest-preset": "^18.1.2",
|
|
63
|
-
"@lwrjs/fs-watch": "0.19.0-alpha.
|
|
63
|
+
"@lwrjs/fs-watch": "0.19.0-alpha.10",
|
|
64
64
|
"@rollup/plugin-typescript": "^11.1.6",
|
|
65
65
|
"jest": "29.7.0",
|
|
66
66
|
"memfs": "^4.13.0",
|
|
@@ -90,6 +90,7 @@
|
|
|
90
90
|
"lwr/router",
|
|
91
91
|
"lwr/routerErrors",
|
|
92
92
|
"lwr/routerBridge",
|
|
93
|
+
"lwr/routerUtils",
|
|
93
94
|
"lwr/serverRouter"
|
|
94
95
|
]
|
|
95
96
|
},
|
|
@@ -99,5 +100,5 @@
|
|
|
99
100
|
"volta": {
|
|
100
101
|
"extends": "../../../package.json"
|
|
101
102
|
},
|
|
102
|
-
"gitHead": "
|
|
103
|
+
"gitHead": "1c0d9cbabc81c0ded8080664debf86b9533bfc27"
|
|
103
104
|
}
|