@lwrjs/loader 0.22.12 → 0.23.0

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.
@@ -4,9 +4,9 @@
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
- /* LWR Module Loader Shim v0.22.12 */
8
- !function(){"use strict";var e=function(e){return e[e.Start=0]="Start",e[e.End=1]="End",e}(e||{});let t;function r(e){t=e}const o=globalThis.performance,i=void 0!==o&&"function"==typeof o.mark&&"function"==typeof o.clearMarks&&"function"==typeof o.measure&&"function"==typeof o.clearMeasures;function n(e,t){return t?`${e}-${t}`:e}function s(e,t,r){const o=n(e,t);return t&&r?`${o}_${r}`:o}function a(e,t){const r=e||t?{...t}:null;return r&&e&&(r.specifier=e),r}function l({id:r,specifier:n,specifierIndex:l,metadata:d}){if(t)t({id:r,phase:e.Start,specifier:n,metadata:d,specifierIndex:l});else if(i){const e=s(r,n,l),t=a(n,d);o.mark(e,{detail:t})}}function d({id:r,specifier:l,specifierIndex:d,metadata:c}){if(t)t({id:r,phase:e.End,specifier:l,metadata:c,specifierIndex:d});else if(i){const e=s(r,l,d),t=n(r,l),i=a(l,c);o.measure(t,{start:e,detail:i}),o.clearMarks(e),o.clearMeasures(t)}}function c(e){const[,t,r]=e;if(Array.isArray(t)&&"function"==typeof r)return{deps:t,factory:r};if("function"==typeof t)return{deps:[],factory:t};throw new Error("Invalid module definition")}function p(e,t,r){if("exports"===e)return t;const o=r[e];if(!o)throw new Error(`Dependency "${e}" not found in defineCache for loader`);try{return function(e){const{deps:t,factory:r}=c(e);if(t.length>1||1===t.length&&"exports"!==t[0])throw new Error(`Loader dependencies must have no deps or only ['exports']; got [${t.join(", ")}]`);const o={},i=r(o);return void 0!==i?i:o}(o)}catch(t){const r=t instanceof Error?t.message:String(t);throw new Error(`Loader dependency "${e}" has invalid definition: ${r}`)}}function u(e,t,r){try{const{deps:e,factory:o}=function(e){const{deps:t,factory:r}=c(e);if(t.includes("exports"))return{deps:t,factory:r};const o=0===t.length;return{deps:["exports",...t],factory:(e,...t)=>{const i=o?r(e):r(...t);void 0!==i&&"object"==typeof i&&Object.assign(e,i)}}}(t),i={};return{factory:o,args:e.map((e=>p(e,i,r))),exportsObj:i}}catch(t){const r=t instanceof Error?t.message:String(t);throw new Error(`Expected loader with specifier "${e}" to be a module. ${r}`)}}function h(e,t,o,i){const{autoBoot:n,customInit:s}=e;if(function(e,t){if(!e&&!t)throw new Error("The customInit hook is required when autoBoot is false");if(e&&t)throw new Error("The customInit hook must not be defined when autoBoot is true")}(n,s),s){s({initializeApp:t,define:o,onBootstrapError:i,attachDispatcher:r},e)}}const f="function"==typeof setTimeout,g="undefined"!=typeof console;class E{__init(){this.defineCache={}}__init2(){this.orderedDefs=[]}constructor(e){E.prototype.__init.call(this),E.prototype.__init2.call(this),f&&(this.watchdogTimerId=this.startWatchdogTimer()),this.global=e,this.config=e.LWR,this.loaderSpecifier="lwr/loader/v/0_22_12",this.errorHandler=this.config.onError,this.initAppHandler=this.config.onInitApp;const t=this.tempDefine.bind(this);e.LWR.define=t,this.bootReady=this.config.autoBoot;try{this.createProfilerModule(e.LWR.define),h(Object.freeze(this.config),this.postCustomInit.bind(this),t,(e=>{this.errorHandler=e}))}catch(e){this.enterErrorState(e)}}canInit(){if(!this.config.requiredModules)throw new Error("Unexpected missing requiredModules");const e=this.config.requiredModules.every((e=>this.orderedDefs.includes(e)));return this.bootReady&&e}tempDefine(...e){const t=e[0];this.defineCache[t]=e,this.orderedDefs.push(t),this.canInit()&&(f&&clearTimeout(this.watchdogTimerId),this.initApp())}postCustomInit(){this.bootReady=!0,this.canInit()&&(f&&clearTimeout(this.watchdogTimerId),this.initApp())}initApp(){try{this.initAppHandler&&this.initAppHandler()}catch(e){console.error(`An error occurred in the onInitApp function. ${e.message}`,e.stack)}try{const e={endpoints:this.config.endpoints,baseUrl:this.config.baseUrl,flags:this.config.flags,profiler:{logOperationStart:l,logOperationEnd:d},appMetadata:{appId:this.config.appId,bootstrapModule:this.config.bootstrapModule,rootComponent:this.config.rootComponent,rootComponents:this.config.rootComponents}},t=function(e,t,r,o,i){if(!t||"function"!=typeof t[2])throw new Error(`Expected loader with specifier "${e}" to be a module`);const n={};if(i){const{factory:r,args:o,exportsObj:s}=u(e,t,i);r(...o),Object.assign(n,s)}else t[2].call(null,n);const{Loader:s}=n;if(!s)throw new Error("Expected Loader class to be defined");const a=new s(r);return o&&o.length&&a.registerExternalModules(o),a.define(e,["exports"],(e=>{Object.assign(e,{define:a.define.bind(a),load:a.load.bind(a),services:a.services})})),a}(this.loaderSpecifier,this.defineCache[this.loaderSpecifier],e,this.config.preloadModules,this.defineCache);this.mountApp(t),t&&t.getModuleWarnings}catch(e){this.enterErrorState(e)}}waitForBody(){return new Promise((e=>{if(document.body)e();else{const t=new MutationObserver((()=>{document.body&&(t.disconnect(),e())}));t.observe(document.documentElement,{childList:!0})}}))}waitForDOMContentLoaded(){return"interactive"===document.readyState||"complete"===document.readyState?Promise.resolve():new Promise((e=>{document.addEventListener("DOMContentLoaded",(()=>{e()}))}))}createProfilerModule(e){e("lwr/profiler/v/0_22_12",["exports"],(e=>{Object.assign(e,{logOperationStart:l,logOperationEnd:d})}))}mountApp(e){const{bootstrapModule:t,rootComponent:r,rootComponents:o,serverData:i,endpoints:n,imports:s,index:a}=this.config,l=s||{};this.global.LWR=Object.freeze({define:e.define.bind(e),rootComponent:r,rootComponents:o,serverData:i||{},endpoints:n,imports:l,index:a||{},env:this.global.LWR.env}),this.orderedDefs.forEach((t=>{t!==this.loaderSpecifier&&e.define(...this.defineCache[t])}));const{initDeferDOM:d}=this.config;e.registerImportMappings({imports:l,index:a},[t,r]).then((()=>"undefined"==typeof window||"undefined"==typeof document?Promise.resolve():d?this.waitForDOMContentLoaded():this.waitForBody())).then((()=>e.load(t))).catch((e=>{this.enterErrorState(new Error(`Application ${r||t} could not be loaded: ${e}`))}))}enterErrorState(e){l({id:"lwr.bootstrap.error"}),this.errorHandler?this.errorHandler(e):g&&console.error(`An error occurred during LWR bootstrap. ${e.message}`,e.stack)}startWatchdogTimer(){return setTimeout((()=>{const e=this.config.requiredModules&&this.config.requiredModules.filter((e=>!this.orderedDefs.includes(e)))||[];this.enterErrorState(new Error(`Failed to load required modules - timed out: ${e.join(", ")}`))}),6e4)}logWarnings(e){for(const t in e)e[t].length&&console.warn(t,e[t])}}const m=globalThis;m.LWR.requiredModules=m.LWR.requiredModules||[],m.LWR.requiredModules.indexOf("lwr/loader/v/0_22_12")<0&&m.LWR.requiredModules.push("lwr/loader/v/0_22_12"),new E(m)}(),LWR.define("lwr/loader/v/0_22_12",["exports"],(function(exports){"use strict";const templateRegex=/\{([0-9]+)\}/g;function templateString(e,t){return e.replace(templateRegex,((e,r)=>t[r]))}function generateErrorMessage(e,t){const r=Array.isArray(t)?templateString(e.message,t):e.message;return`LWR${e.code}: ${r}`}class LoaderError extends Error{constructor(e,t){super(),this.message=generateErrorMessage(e,t)}}function invariant(e,t){if(!e)throw new LoaderError(t)}const MISSING_NAME=Object.freeze({code:3e3,message:"A module name is required.",level:0}),FAIL_INSTANTIATE=Object.freeze({code:3004,message:"Failed to instantiate module: {0}",level:0}),NO_AMD_REQUIRE=Object.freeze({code:3005,message:"AMD require not supported.",level:0}),FAILED_DEP=Object.freeze({code:3006,level:0,message:"Failed to load dependency: {0}"}),INVALID_DEPS=Object.freeze({code:3007,message:"Unexpected value received for dependencies argument; expected an array.",level:0}),FAIL_LOAD=Object.freeze({code:3008,level:0,message:"Error loading {0}"});Object.freeze({code:3008,level:0,message:"Error loading empty code for {0}"});const UNRESOLVED=Object.freeze({code:3009,level:0,message:"Unable to resolve bare specifier: {0}"}),NO_BASE_URL=Object.freeze({code:3010,level:0,message:"baseUrl not set"});Object.freeze({code:3011,level:0,message:"Cannot set a loader service multiple times"});const INVALID_HOOK=Object.freeze({code:3012,level:0,message:"Invalid hook received"}),INVALID_LOADER_SERVICE_RESPONSE=Object.freeze({code:3013,level:0,message:"Invalid response received from hook"}),MODULE_LOAD_TIMEOUT=Object.freeze({code:3014,level:0,message:"Error loading {0} - timed out"}),HTTP_FAIL_LOAD=Object.freeze({code:3015,level:0,message:"Error loading {0}, status code {1}"}),STALE_HOOK_ERROR=Object.freeze({code:3016,level:0,message:"An error occurred handling module conflict"});Object.freeze({code:3017,level:0,message:"Marking module(s) as externally loaded, but they are already loaded:"});const FAIL_HOOK_LOAD=Object.freeze({code:3018,level:0,message:'Error loading "{0}" from hook'}),NO_MAPPING_URL=Object.freeze({code:3019,level:0,message:"Mapping endpoint not set"}),BAD_IMPORT_METADATA=Object.freeze({code:3020,level:0,message:"Invalid import metadata: {0} {1}"}),EXPORTER_ERROR=Object.freeze({code:3021,level:0,message:'Error evaluating module "{0}", error was "{1}"'}),UNRESOLVEABLE_MAPPING_ERROR=Object.freeze({code:3022,level:0,message:'Unexpected undefined URI resolving mapping for "{0}"'}),NO_IMPORT_LWC=Object.freeze({code:3023,level:0,message:'Cannot dynamically import "lwc" with importer "{0}"'}),NO_IMPORT_LOADER=Object.freeze({code:3024,level:0,message:'Cannot dynamically import the LWR loader with importer "{0}"'}),NO_BLOB_IMPORT=Object.freeze({code:3024,level:0,message:"Cannot import a blob URL"}),NO_IMPORT_TRANSPORT=Object.freeze({code:3025,level:0,message:'Cannot dynamically import "transport" with importer "{0}"'});Object.freeze({code:3011,level:0,message:"import map is not valid"});const hasDocument="undefined"!=typeof document,hasSetTimeout="function"==typeof setTimeout,hasConsole="undefined"!=typeof console,hasProcess="undefined"!=typeof process;function getBaseUrl(){let e;if(hasDocument){const t=document.querySelector("base[href]");e=t&&t.href}if(!e&&"undefined"!=typeof location){e=location.href.split("#")[0].split("?")[0];const t=e.lastIndexOf("/");-1!==t&&(e=e.slice(0,t+1))}return e}function isUrl(e){return-1!==e.indexOf("://")}function resolveIfNotPlainOrUrl(e,t){if(-1!==e.indexOf("\\")&&(e=e.replace(/\\/g,"/")),"/"===e[0]&&"/"===e[1])return t.slice(0,t.indexOf(":")+1)+e;if("."===e[0]&&("/"===e[1]||"."===e[1]&&("/"===e[2]||2===e.length&&(e+="/"))||1===e.length&&(e+="/"))||"/"===e[0]){const r=t.slice(0,t.indexOf(":")+1);let o;if("/"===t[r.length+1]?"file:"!==r?(o=t.slice(r.length+2),o=o.slice(o.indexOf("/")+1)):o=t.slice(8):o=t.slice(r.length+("/"===t[r.length]?1:0)),"/"===e[0])return t.slice(0,t.length-o.length-1)+e;const i=o.slice(0,o.lastIndexOf("/")+1)+e,n=[];let s=-1;for(let e=0;e<i.length;e++)-1!==s?"/"===i[e]&&(n.push(i.slice(s,e+1)),s=-1):"."===i[e]?"."!==i[e+1]||"/"!==i[e+2]&&e+2!==i.length?"/"===i[e+1]||e+1===i.length?e+=1:s=e:(n.pop(),e+=2):s=e;return-1!==s&&n.push(i.slice(s)),t.slice(0,t.length-o.length)+n.join("")}}function resolveUrl(e,t){return resolveIfNotPlainOrUrl(e,t)||(isUrl(e)?e:resolveIfNotPlainOrUrl("./"+e,t))}function createScript(e){const t=document.createElement("script");return t.async=!0,t.crossOrigin="anonymous",t.src=e,t}let lastWindowError$1,lastWindowErrorUrl;function loadModuleDef(e){return new Promise((function(t,r){if(hasDocument){const o=createScript(e);o.addEventListener("error",(()=>{r(new LoaderError(FAIL_LOAD,[e]))})),o.addEventListener("load",(()=>{document.head.removeChild(o),lastWindowErrorUrl===e?r(lastWindowError$1):t()})),document.head.appendChild(o)}}))}hasProcess&&process.env,hasDocument&&window.addEventListener("error",(e=>{lastWindowErrorUrl=e.filename,lastWindowError$1=e.error}));const LOADER_PREFIX="lwr.loader.",MODULE_DEFINE=`${LOADER_PREFIX}module.define`,MODULE_DYNAMIC_LOAD=`${LOADER_PREFIX}module.dynamicLoad`,MODULE_FETCH=`${LOADER_PREFIX}module.fetch`,MODULE_ERROR=`${LOADER_PREFIX}module.error`,MAPPINGS_FETCH=`${LOADER_PREFIX}mappings.fetch`,MAPPINGS_ERROR=`${LOADER_PREFIX}mappings.error`;function _optionalChain(e){let t,r=e[0],o=1;for(;o<e.length;){const i=e[o],n=e[o+1];if(o+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=n(r)):"call"!==i&&"optionalCall"!==i||(r=n(((...e)=>r.call(t,...e))),t=void 0)}return r}class ImportMetadataResolver{__init(){this.importURICache=new Map}__init2(){this.pendingURICache=new Map}__init3(){this.loadMappingHooks=[]}__init4(){this.batchSpecifiers=[]}constructor(e,t){ImportMetadataResolver.prototype.__init.call(this),ImportMetadataResolver.prototype.__init2.call(this),ImportMetadataResolver.prototype.__init3.call(this),ImportMetadataResolver.prototype.__init4.call(this),this.config=e,this.invalidationCallback=t}addLoadMappingHook(e){this.loadMappingHooks.push(e)}getMappingEndpoint(){return this.config.endpoints&&this.config.endpoints.uris?this.config.endpoints.uris.mapping:void 0}getModifiersAsUrlParams(){const e=this.config.endpoints?this.config.endpoints.modifiers:void 0;if(e){return`?${Object.keys(e).map((t=>`${encodeURIComponent(t)}=${encodeURIComponent(e[t])}`)).join("&")}`}return""}buildMappingUrl(e){return`${this.getMappingEndpoint()}${encodeURIComponent(e)}${this.getModifiersAsUrlParams()}`}getBaseUrl(){return this.config.baseUrl||""}registerImportMappings(e,t){if(!t||0===t.length){const r=e?JSON.stringify(e):"undefined";throw new LoaderError(BAD_IMPORT_METADATA,[r,t?"[]":"undefined"])}if(!e)throw new LoaderError(BAD_IMPORT_METADATA,["undefined",JSON.stringify(t)]);if(!e.imports||0===Object.keys(e.imports).length)throw new LoaderError(BAD_IMPORT_METADATA,[JSON.stringify(e),JSON.stringify(t)]);const r=e.index||{};for(const[o,i]of Object.entries(e.imports))i.forEach((e=>{const i=r[e],n=this.importURICache.get(e);if(n){const t=i||o,r=n.identity||n.uri;r!==t&&this.invalidationCallback({name:e,oldUrl:r,newUrl:t})}else this.saveImportURIRecord(e,o,i,t.includes(e))}))}getURI(e){return this.importURICache&&this.importURICache.has(e)?resolveUrl(this.importURICache.get(e).uri,this.getBaseUrl()):void 0}resolveLocal(e){const t=this.getURI(e);return t||(isUrl(e)||e.startsWith("/")?e:void 0)}async resolve(e){let t=this.getURI(e);if(t)return t;if(isUrl(e)||e.startsWith("/"))return e;{const r=this.pendingURICache.get(e);if(r)return r;this.config.profiler.logOperationStart({id:MAPPINGS_FETCH,specifier:e});const o=(this.hasMappingHooks()?this.evaluateMappingHooks:this.fetchNewMappings).bind(this)(e).then((r=>{if(!r||!r.imports)throw new LoaderError(UNRESOLVED,[e]);if(this.registerImportMappings(r,[e]),t=this.getURI(e),!t)throw new LoaderError(UNRESOLVED,[e]);return this.config.profiler.logOperationEnd({id:MAPPINGS_FETCH,specifier:e}),t})).finally((()=>{this.pendingURICache.delete(e)}));return this.pendingURICache.set(e,o),o}}hasMappingHooks(){return this.loadMappingHooks.length>0}async evaluateMappingHooks(e){const t=this.loadMappingHooks;if(t.length){const r=Array.from(this.importURICache.keys());for(let o=0;o<t.length;o++){const i=t[o],n=await i(e,{knownModules:r});if(n||void 0===n)return n}}return this.fetchNewMappings(e)}async fetchNewMappings(e){if(!hasSetTimeout||!_optionalChain([this,"access",e=>e.config,"optionalAccess",e=>e.flags,"optionalAccess",e=>e.batchMappings]))return this.fetchNewMappingsInner(e);const t=()=>{const e=this.batchSpecifiers.join(",");return this.batchSpecifiers=[],clearTimeout(this.batchTimer),this.batchTimer=void 0,this.fetchNewMappingsInner(e)};return this.batchPromise&&0!==this.batchSpecifiers.length||(this.batchPromise=new Promise((e=>{this.batchTimer=setTimeout((()=>e(t())),0)}))),this.batchSpecifiers.push(e),this.batchPromise}async fetchNewMappingsInner(e){if("function"!=typeof globalThis.fetch)throw new LoaderError(UNRESOLVED,[e]);const t=resolveUrl(this.buildMappingUrl(e),this.getBaseUrl());if(!t)throw new LoaderError(UNRESOLVEABLE_MAPPING_ERROR,[e]);return globalThis.fetch(t).then((t=>{if(!t.ok)throw this.config.profiler.logOperationStart({id:MAPPINGS_ERROR,specifier:e}),new LoaderError(UNRESOLVED,[e]);return t.json().then((e=>e))})).catch((t=>{throw new LoaderError(UNRESOLVED,[e])}))}saveImportURIRecord(e,t,r,o){r&&t!==r?this.importURICache.set(e,{uri:t,identity:r,isRoot:o}):this.importURICache.set(e,{uri:t,isRoot:o})}}function reportError(e){hasConsole&&console.error(e)}function evaluateHandleStaleModuleHooks(e,t){const{name:r,oldUrl:o,newUrl:i}=t;for(let t=0;t<e.length;t++){const n=e[t];try{if(null!==n({name:r,oldUrl:o,newUrl:i}))break}catch(e){reportError(new LoaderError(STALE_HOOK_ERROR))}}}const MODULE_LOAD_TIMEOUT_TIMER=6e4;var MODULE_WARNING;!function(e){e.MODULE_REDEFINE="Module redefine attempted";e.MODULE_ALREADY_LOADED="Marking module(s) as externally loaded, but they are already loaded";e.ALIAS_UPDATE="Alias update attempt"}(MODULE_WARNING||(MODULE_WARNING={}));
7
+ /* LWR Module Loader Shim v0.23.0 */
8
+ !function(){"use strict";var e=function(e){return e[e.Start=0]="Start",e[e.End=1]="End",e}(e||{});let t;function r(e){t=e}const o=globalThis.performance,i=void 0!==o&&"function"==typeof o.mark&&"function"==typeof o.clearMarks&&"function"==typeof o.measure&&"function"==typeof o.clearMeasures;function n(e,t){return t?`${e}-${t}`:e}function s(e,t,r){const o=n(e,t);return t&&r?`${o}_${r}`:o}function a(e,t){const r=e||t?{...t}:null;return r&&e&&(r.specifier=e),r}function l({id:r,specifier:n,specifierIndex:l,metadata:d}){if(t)t({id:r,phase:e.Start,specifier:n,metadata:d,specifierIndex:l});else if(i){const e=s(r,n,l),t=a(n,d);o.mark(e,{detail:t})}}function d({id:r,specifier:l,specifierIndex:d,metadata:c}){if(t)t({id:r,phase:e.End,specifier:l,metadata:c,specifierIndex:d});else if(i){const e=s(r,l,d),t=n(r,l),i=a(l,c);o.measure(t,{start:e,detail:i}),o.clearMarks(e),o.clearMeasures(t)}}function c(e){const[,t,r]=e;if(Array.isArray(t)&&"function"==typeof r)return{deps:t,factory:r};if("function"==typeof t)return{deps:[],factory:t};throw new Error("Invalid module definition")}function p(e,t,r){if("exports"===e)return t;const o=r[e];if(!o)throw new Error(`Dependency "${e}" not found in defineCache for loader`);try{return function(e){const{deps:t,factory:r}=c(e);if(t.length>1||1===t.length&&"exports"!==t[0])throw new Error(`Loader dependencies must have no deps or only ['exports']; got [${t.join(", ")}]`);const o={},i=r(o);return void 0!==i?i:o}(o)}catch(t){const r=t instanceof Error?t.message:String(t);throw new Error(`Loader dependency "${e}" has invalid definition: ${r}`)}}function u(e,t,r){try{const{deps:e,factory:o}=function(e){const{deps:t,factory:r}=c(e);if(t.includes("exports"))return{deps:t,factory:r};const o=0===t.length;return{deps:["exports",...t],factory:(e,...t)=>{const i=o?r(e):r(...t);void 0!==i&&"object"==typeof i&&Object.assign(e,i)}}}(t),i={};return{factory:o,args:e.map((e=>p(e,i,r))),exportsObj:i}}catch(t){const r=t instanceof Error?t.message:String(t);throw new Error(`Expected loader with specifier "${e}" to be a module. ${r}`)}}function h(e,t,o,i){const{autoBoot:n,customInit:s}=e;if(function(e,t){if(!e&&!t)throw new Error("The customInit hook is required when autoBoot is false");if(e&&t)throw new Error("The customInit hook must not be defined when autoBoot is true")}(n,s),s){s({initializeApp:t,define:o,onBootstrapError:i,attachDispatcher:r},e)}}const f="function"==typeof setTimeout,g="undefined"!=typeof console;class m{__init(){this.defineCache={}}__init2(){this.orderedDefs=[]}constructor(e){m.prototype.__init.call(this),m.prototype.__init2.call(this),f&&(this.watchdogTimerId=this.startWatchdogTimer()),this.global=e,this.config=e.LWR,this.loaderSpecifier="lwr/loader/v/0_23_0",this.errorHandler=this.config.onError,this.initAppHandler=this.config.onInitApp;const t=this.tempDefine.bind(this);e.LWR.define=t,this.bootReady=this.config.autoBoot;try{this.createProfilerModule(e.LWR.define),h(Object.freeze(this.config),this.postCustomInit.bind(this),t,(e=>{this.errorHandler=e}))}catch(e){this.enterErrorState(e)}}canInit(){if(!this.config.requiredModules)throw new Error("Unexpected missing requiredModules");const e=this.config.requiredModules.every((e=>this.orderedDefs.includes(e)));return this.bootReady&&e}tempDefine(...e){const t=e[0];this.defineCache[t]=e,this.orderedDefs.push(t),this.canInit()&&(f&&clearTimeout(this.watchdogTimerId),this.initApp())}postCustomInit(){this.bootReady=!0,this.canInit()&&(f&&clearTimeout(this.watchdogTimerId),this.initApp())}initApp(){try{this.initAppHandler&&this.initAppHandler()}catch(e){console.error(`An error occurred in the onInitApp function. ${e.message}`,e.stack)}try{const e={endpoints:this.config.endpoints,baseUrl:this.config.baseUrl,flags:this.config.flags,profiler:{logOperationStart:l,logOperationEnd:d},appMetadata:{appId:this.config.appId,bootstrapModule:this.config.bootstrapModule,rootComponent:this.config.rootComponent,rootComponents:this.config.rootComponents}},t=function(e,t,r,o,i){if(!t||"function"!=typeof t[2])throw new Error(`Expected loader with specifier "${e}" to be a module`);const n={};if(i){const{factory:r,args:o,exportsObj:s}=u(e,t,i);r(...o),Object.assign(n,s)}else t[2].call(null,n);const{Loader:s}=n;if(!s)throw new Error("Expected Loader class to be defined");const a=new s(r);return o&&o.length&&a.registerExternalModules(o),a.define(e,["exports"],(e=>{Object.assign(e,{define:a.define.bind(a),load:a.load.bind(a),services:a.services})})),a}(this.loaderSpecifier,this.defineCache[this.loaderSpecifier],e,this.config.preloadModules,this.defineCache);this.mountApp(t),t&&t.getModuleWarnings}catch(e){this.enterErrorState(e)}}waitForBody(){return new Promise((e=>{if(document.body)e();else{const t=new MutationObserver((()=>{document.body&&(t.disconnect(),e())}));t.observe(document.documentElement,{childList:!0})}}))}waitForDOMContentLoaded(){return"interactive"===document.readyState||"complete"===document.readyState?Promise.resolve():new Promise((e=>{document.addEventListener("DOMContentLoaded",(()=>{e()}))}))}createProfilerModule(e){e("lwr/profiler/v/0_23_0",["exports"],(e=>{Object.assign(e,{logOperationStart:l,logOperationEnd:d})}))}mountApp(e){const{bootstrapModule:t,rootComponent:r,rootComponents:o,serverData:i,endpoints:n,imports:s,index:a}=this.config,l=s||{};this.global.LWR=Object.freeze({define:e.define.bind(e),importMap:t=>e.importMap(t),rootComponent:r,rootComponents:o,serverData:i||{},endpoints:n,imports:l,index:a||{},env:this.global.LWR.env}),this.orderedDefs.forEach((t=>{t!==this.loaderSpecifier&&e.define(...this.defineCache[t])}));const{initDeferDOM:d}=this.config;e.importMap({imports:l,index:a},[t,r]).then((()=>"undefined"==typeof window||"undefined"==typeof document?Promise.resolve():d?this.waitForDOMContentLoaded():this.waitForBody())).then((()=>e.load(t))).catch((e=>{this.enterErrorState(new Error(`Application ${r||t} could not be loaded: ${e}`))}))}enterErrorState(e){l({id:"lwr.bootstrap.error"}),this.errorHandler?this.errorHandler(e):g&&console.error(`An error occurred during LWR bootstrap. ${e.message}`,e.stack)}startWatchdogTimer(){return setTimeout((()=>{const e=this.config.requiredModules&&this.config.requiredModules.filter((e=>!this.orderedDefs.includes(e)))||[];this.enterErrorState(new Error(`Failed to load required modules - timed out: ${e.join(", ")}`))}),6e4)}logWarnings(e){for(const t in e)e[t].length&&console.warn(t,e[t])}}const E=globalThis;E.LWR.requiredModules=E.LWR.requiredModules||[],E.LWR.requiredModules.indexOf("lwr/loader/v/0_23_0")<0&&E.LWR.requiredModules.push("lwr/loader/v/0_23_0"),new m(E)}(),LWR.define("lwr/loader/v/0_23_0",["exports"],(function(exports){"use strict";const templateRegex=/\{([0-9]+)\}/g;function templateString(e,t){return e.replace(templateRegex,((e,r)=>t[r]))}function generateErrorMessage(e,t){const r=Array.isArray(t)?templateString(e.message,t):e.message;return`LWR${e.code}: ${r}`}class LoaderError extends Error{constructor(e,t){super(),this.message=generateErrorMessage(e,t)}}function invariant(e,t){if(!e)throw new LoaderError(t)}const MISSING_NAME=Object.freeze({code:3e3,message:"A module name is required.",level:0}),FAIL_INSTANTIATE=Object.freeze({code:3004,message:"Failed to instantiate module: {0}",level:0}),NO_AMD_REQUIRE=Object.freeze({code:3005,message:"AMD require not supported.",level:0}),FAILED_DEP=Object.freeze({code:3006,level:0,message:"Failed to load dependency: {0}"}),INVALID_DEPS=Object.freeze({code:3007,message:"Unexpected value received for dependencies argument; expected an array.",level:0}),FAIL_LOAD=Object.freeze({code:3008,level:0,message:"Error loading {0}"});Object.freeze({code:3008,level:0,message:"Error loading empty code for {0}"});const UNRESOLVED=Object.freeze({code:3009,level:0,message:"Unable to resolve bare specifier: {0}"}),NO_BASE_URL=Object.freeze({code:3010,level:0,message:"baseUrl not set"});Object.freeze({code:3011,level:0,message:"Cannot set a loader service multiple times"});const INVALID_HOOK=Object.freeze({code:3012,level:0,message:"Invalid hook received"}),INVALID_LOADER_SERVICE_RESPONSE=Object.freeze({code:3013,level:0,message:"Invalid response received from hook"}),MODULE_LOAD_TIMEOUT=Object.freeze({code:3014,level:0,message:"Error loading {0} - timed out"}),HTTP_FAIL_LOAD=Object.freeze({code:3015,level:0,message:"Error loading {0}, status code {1}"}),STALE_HOOK_ERROR=Object.freeze({code:3016,level:0,message:"An error occurred handling module conflict"});Object.freeze({code:3017,level:0,message:"Marking module(s) as externally loaded, but they are already loaded:"});const FAIL_HOOK_LOAD=Object.freeze({code:3018,level:0,message:'Error loading "{0}" from hook'}),NO_MAPPING_URL=Object.freeze({code:3019,level:0,message:"Mapping endpoint not set"}),BAD_IMPORT_METADATA=Object.freeze({code:3020,level:0,message:"Invalid import metadata: {0} {1}"}),EXPORTER_ERROR=Object.freeze({code:3021,level:0,message:'Error evaluating module "{0}", error was "{1}"'}),UNRESOLVEABLE_MAPPING_ERROR=Object.freeze({code:3022,level:0,message:'Unexpected undefined URI resolving mapping for "{0}"'}),NO_IMPORT_LWC=Object.freeze({code:3023,level:0,message:'Cannot dynamically import "lwc" with importer "{0}"'}),NO_IMPORT_LOADER=Object.freeze({code:3024,level:0,message:'Cannot dynamically import the LWR loader with importer "{0}"'}),NO_BLOB_IMPORT=Object.freeze({code:3024,level:0,message:"Cannot import a blob URL"}),NO_IMPORT_TRANSPORT=Object.freeze({code:3025,level:0,message:'Cannot dynamically import "transport" with importer "{0}"'});Object.freeze({code:3011,level:0,message:"import map is not valid"});const hasDocument="undefined"!=typeof document,hasSetTimeout="function"==typeof setTimeout,hasConsole="undefined"!=typeof console,hasProcess="undefined"!=typeof process;function getBaseUrl(){let e;if(hasDocument){const t=document.querySelector("base[href]");e=t&&t.href}if(!e&&"undefined"!=typeof location){e=location.href.split("#")[0].split("?")[0];const t=e.lastIndexOf("/");-1!==t&&(e=e.slice(0,t+1))}return e}function isUrl(e){return-1!==e.indexOf("://")}function resolveIfNotPlainOrUrl(e,t){if(-1!==e.indexOf("\\")&&(e=e.replace(/\\/g,"/")),"/"===e[0]&&"/"===e[1])return t.slice(0,t.indexOf(":")+1)+e;if("."===e[0]&&("/"===e[1]||"."===e[1]&&("/"===e[2]||2===e.length&&(e+="/"))||1===e.length&&(e+="/"))||"/"===e[0]){const r=t.slice(0,t.indexOf(":")+1);let o;if("/"===t[r.length+1]?"file:"!==r?(o=t.slice(r.length+2),o=o.slice(o.indexOf("/")+1)):o=t.slice(8):o=t.slice(r.length+("/"===t[r.length]?1:0)),"/"===e[0])return t.slice(0,t.length-o.length-1)+e;const i=o.slice(0,o.lastIndexOf("/")+1)+e,n=[];let s=-1;for(let e=0;e<i.length;e++)-1!==s?"/"===i[e]&&(n.push(i.slice(s,e+1)),s=-1):"."===i[e]?"."!==i[e+1]||"/"!==i[e+2]&&e+2!==i.length?"/"===i[e+1]||e+1===i.length?e+=1:s=e:(n.pop(),e+=2):s=e;return-1!==s&&n.push(i.slice(s)),t.slice(0,t.length-o.length)+n.join("")}}function resolveUrl(e,t){return resolveIfNotPlainOrUrl(e,t)||(isUrl(e)?e:resolveIfNotPlainOrUrl("./"+e,t))}function createScript(e){const t=document.createElement("script");return t.async=!0,t.crossOrigin="anonymous",t.src=e,t}let lastWindowError$1,lastWindowErrorUrl;function loadModuleDef(e){return new Promise((function(t,r){if(hasDocument){const o=createScript(e);o.addEventListener("error",(()=>{r(new LoaderError(FAIL_LOAD,[e]))})),o.addEventListener("load",(()=>{document.head.removeChild(o),lastWindowErrorUrl===e?r(lastWindowError$1):t()})),document.head.appendChild(o)}}))}hasProcess&&process.env,hasDocument&&window.addEventListener("error",(e=>{lastWindowErrorUrl=e.filename,lastWindowError$1=e.error}));const LOADER_PREFIX="lwr.loader.",MODULE_DEFINE=`${LOADER_PREFIX}module.define`,MODULE_DYNAMIC_LOAD=`${LOADER_PREFIX}module.dynamicLoad`,MODULE_FETCH=`${LOADER_PREFIX}module.fetch`,MODULE_ERROR=`${LOADER_PREFIX}module.error`,MAPPINGS_FETCH=`${LOADER_PREFIX}mappings.fetch`,MAPPINGS_ERROR=`${LOADER_PREFIX}mappings.error`;function _optionalChain(e){let t,r=e[0],o=1;for(;o<e.length;){const i=e[o],n=e[o+1];if(o+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=n(r)):"call"!==i&&"optionalCall"!==i||(r=n(((...e)=>r.call(t,...e))),t=void 0)}return r}class ImportMetadataResolver{__init(){this.importURICache=new Map}__init2(){this.pendingURICache=new Map}__init3(){this.loadMappingHooks=[]}__init4(){this.batchSpecifiers=[]}constructor(e,t){ImportMetadataResolver.prototype.__init.call(this),ImportMetadataResolver.prototype.__init2.call(this),ImportMetadataResolver.prototype.__init3.call(this),ImportMetadataResolver.prototype.__init4.call(this),this.config=e,this.invalidationCallback=t}addLoadMappingHook(e){this.loadMappingHooks.push(e)}getMappingEndpoint(){return this.config.endpoints&&this.config.endpoints.uris?this.config.endpoints.uris.mapping:void 0}getModifiersAsUrlParams(){const e=this.config.endpoints?this.config.endpoints.modifiers:void 0;if(e){return`?${Object.keys(e).map((t=>`${encodeURIComponent(t)}=${encodeURIComponent(e[t])}`)).join("&")}`}return""}buildMappingUrl(e){return`${this.getMappingEndpoint()}${encodeURIComponent(e)}${this.getModifiersAsUrlParams()}`}getBaseUrl(){return this.config.baseUrl||""}registerImportMappings(e,t=[]){if(!e)throw new LoaderError(BAD_IMPORT_METADATA,["undefined",JSON.stringify(t)]);if(!e.imports||0===Object.keys(e.imports).length)throw new LoaderError(BAD_IMPORT_METADATA,[JSON.stringify(e),JSON.stringify(t)]);const r=e.index||{};for(const[o,i]of Object.entries(e.imports))i.forEach((e=>{const i=r[e],n=this.importURICache.get(e);if(n){const t=i||o,r=n.identity||n.uri;r!==t&&this.invalidationCallback({name:e,oldUrl:r,newUrl:t})}else this.saveImportURIRecord(e,o,i,t.includes(e))}))}getMappingUri(e){return _optionalChain([this,"access",e=>e.importURICache,"access",e=>e.get,"call",t=>t(e),"optionalAccess",e=>e.uri])}getURI(e){return this.importURICache&&this.importURICache.has(e)?resolveUrl(this.importURICache.get(e).uri,this.getBaseUrl()):void 0}resolveLocal(e){const t=this.getURI(e);return t||(isUrl(e)||e.startsWith("/")?e:void 0)}async resolve(e){let t=this.getURI(e);if(t)return t;if(isUrl(e)||e.startsWith("/"))return e;{const r=this.pendingURICache.get(e);if(r)return r;this.config.profiler.logOperationStart({id:MAPPINGS_FETCH,specifier:e});const o=(this.hasMappingHooks()?this.evaluateMappingHooks:this.fetchNewMappings).bind(this)(e).then((r=>{if(!r||!r.imports)throw new LoaderError(UNRESOLVED,[e]);if(this.registerImportMappings(r,[e]),t=this.getURI(e),!t)throw new LoaderError(UNRESOLVED,[e]);return this.config.profiler.logOperationEnd({id:MAPPINGS_FETCH,specifier:e}),t})).finally((()=>{this.pendingURICache.delete(e)}));return this.pendingURICache.set(e,o),o}}hasMappingHooks(){return this.loadMappingHooks.length>0}async evaluateMappingHooks(e){const t=this.loadMappingHooks;if(t.length){const r=Array.from(this.importURICache.keys());for(let o=0;o<t.length;o++){const i=t[o],n=await i(e,{knownModules:r});if(n||void 0===n)return n}}return this.fetchNewMappings(e)}async fetchNewMappings(e){if(!hasSetTimeout||!_optionalChain([this,"access",e=>e.config,"optionalAccess",e=>e.flags,"optionalAccess",e=>e.batchMappings]))return this.fetchNewMappingsInner(e);const t=()=>{const e=this.batchSpecifiers.join(",");return this.batchSpecifiers=[],clearTimeout(this.batchTimer),this.batchTimer=void 0,this.fetchNewMappingsInner(e)};return this.batchPromise&&0!==this.batchSpecifiers.length||(this.batchPromise=new Promise((e=>{this.batchTimer=setTimeout((()=>e(t())),0)}))),this.batchSpecifiers.push(e),this.batchPromise}async fetchNewMappingsInner(e){if("function"!=typeof globalThis.fetch)throw new LoaderError(UNRESOLVED,[e]);const t=resolveUrl(this.buildMappingUrl(e),this.getBaseUrl());if(!t)throw new LoaderError(UNRESOLVEABLE_MAPPING_ERROR,[e]);return globalThis.fetch(t).then((t=>{if(!t.ok)throw this.config.profiler.logOperationStart({id:MAPPINGS_ERROR,specifier:e}),new LoaderError(UNRESOLVED,[e]);return t.json().then((e=>e))})).catch((t=>{throw new LoaderError(UNRESOLVED,[e])}))}saveImportURIRecord(e,t,r,o){r&&t!==r?this.importURICache.set(e,{uri:t,identity:r,isRoot:o}):this.importURICache.set(e,{uri:t,isRoot:o})}}function reportError(e){hasConsole&&console.error(e)}function evaluateHandleStaleModuleHooks(e,t){const{name:r,oldUrl:o,newUrl:i}=t;for(let t=0;t<e.length;t++){const n=e[t];try{if(null!==n({name:r,oldUrl:o,newUrl:i}))break}catch(e){reportError(new LoaderError(STALE_HOOK_ERROR))}}}const MODULE_LOAD_TIMEOUT_TIMER=6e4;var MODULE_WARNING;!function(e){e.MODULE_REDEFINE="Module redefine attempted";e.MODULE_ALREADY_LOADED="Marking module(s) as externally loaded, but they are already loaded";e.ALIAS_UPDATE="Alias update attempt"}(MODULE_WARNING||(MODULE_WARNING={}));
9
9
  /*!
10
10
  * Copyright (C) 2023 salesforce.com, inc.
11
11
  */
12
- const SUPPORTS_TRUSTED_TYPES="undefined"!=typeof trustedTypes,trustedTypePolicyRegistry={__proto__:null};function createDuplicateSafeTrustedTypesPolicy(e,t){return trustedTypePolicyRegistry[e]?trustedTypePolicyRegistry[e]:trustedTypePolicyRegistry[e]=trustedTypes.createPolicy(e,t)}function createDuplicateSafeFallbackPolicy(e,t){return trustedTypePolicyRegistry[e]?trustedTypePolicyRegistry[e]:trustedTypePolicyRegistry[e]=t}const createPolicy=SUPPORTS_TRUSTED_TYPES?createDuplicateSafeTrustedTypesPolicy:createDuplicateSafeFallbackPolicy,policyOptions={createHTML:e=>e,createScript:e=>e,createScriptURL:e=>e};try{createPolicy("default",{createHTML:e=>e,createScript(e){if("null"===e||"undefined"===e)return e},createScriptURL:e=>e})}catch(e){}const trusted=createPolicy("trusted",policyOptions);let lastWindowError;function isCustomResponse(e){return Object.prototype.hasOwnProperty.call(e,"data")&&!Object.prototype.hasOwnProperty.call(e,"blob")}function isFetchResponse(e){return"function"==typeof e.blob}function isResponseAPromise(e){return!(!e||!e.then)}async function evaluateLoadHookResponse(response,id){return Promise.resolve().then((async()=>{if(!response||!response.status)throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);if(200!==response.status)throw new LoaderError(HTTP_FAIL_LOAD,[id,`${response.status}`]);const isResponse=isFetchResponse(response);let code;if(isCustomResponse(response))code=response.data;else{if(!isResponse)throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);code=await response.text()}if(!code)throw new LoaderError(FAIL_LOAD,[`empty code for ${id}`]);code=`${code}\n//# sourceURL=${id}`;try{eval(trusted.createScript(code))}catch(e){throw new LoaderError(FAIL_LOAD,[`"${id}": ${e instanceof Error?e.message:String(e)}`])}if(lastWindowError)throw new LoaderError(FAIL_LOAD,[`"${id}": window error ${lastWindowError instanceof Error?lastWindowError.message:String(lastWindowError)}`]);return!0}))}async function evaluateLoadHook(e,t){return hasSetTimeout?new Promise(((r,o)=>{const i=setTimeout((()=>{o(new LoaderError(MODULE_LOAD_TIMEOUT,[e]))}),MODULE_LOAD_TIMEOUT_TIMER);t.then((e=>{r(e)})).catch((()=>{o(new LoaderError(FAIL_HOOK_LOAD,[e]))})).finally((()=>{clearTimeout(i)}))})):t}hasDocument&&globalThis.addEventListener("error",(e=>{lastWindowError=e.error}));class ModuleRegistry{__init(){this.isAppMounted=!1}constructor(e){ModuleRegistry.prototype.__init.call(this),ModuleRegistry.prototype.__init2.call(this),ModuleRegistry.prototype.__init3.call(this),ModuleRegistry.prototype.__init4.call(this),this.profiler=e.profiler,this.resolver=new ImportMetadataResolver(e,this.importMetadataInvalidationCallback.bind(this)),this.warnings={[MODULE_WARNING.MODULE_REDEFINE]:[],[MODULE_WARNING.MODULE_ALREADY_LOADED]:[],[MODULE_WARNING.ALIAS_UPDATE]:[]}}async load(e,t){const r=t?{importer:t}:{};this.profiler.logOperationStart({id:MODULE_DYNAMIC_LOAD,specifier:e,metadata:r});const o=await this.resolve(e,t),i=await this.getModuleRecord(o,e);return i.evaluated?i.module:(i.evaluationPromise||(i.evaluationPromise=this.topLevelEvaluation(i)),i.evaluationPromise)}async resolve(e,t){const r=this.resolver.getBaseUrl();let o,i=e;const n=this.resolveHook;if(n){for(let e=0;e<n.length;e++){const t=(0,n[e])(i,{parentUrl:r});let s;if((t||null===t)&&(s=isResponseAPromise(t)?await t:t),!this.isValidResolveResponse(s))throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);if(null!==s){if("string"==typeof s){if(resolveIfNotPlainOrUrl(s,r))throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);i=s;continue}if(o=s&&s.url&&(resolveIfNotPlainOrUrl(s.url,r)||s.url),!o)throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);break}}if(i!==e){if(!o&&this.namedDefineRegistry.has(i))return i;e=i}}if(!o){const t=resolveIfNotPlainOrUrl(e,r)||e;if(this.moduleRegistry.has(t))return t;const i=this.resolver.resolveLocal(t);if(i){if(this.namedDefineRegistry.has(t)){const e=this.namedDefineRegistry.get(t);if(e.external||e.defined){if(!this.moduleRegistry.get(i)||!this.aliases.has(t))return t}}return i}if(this.namedDefineRegistry.has(t))return t;try{o=await this.resolver.resolve(t)}catch(e){}}if(!o||!isUrl(o)){if(this.namedDefineRegistry.has(e))return e;throw new LoaderError(UNRESOLVED,[e])}return t&&isUrl(o)&&(o+=`?importer=${encodeURIComponent(t)}`),o}has(e){return this.moduleRegistry.has(e)}define(e,t,r){const o=this.namedDefineRegistry.get(e);if(o&&o.defined)return void(this.lastDefine=o);const i={name:e,dependencies:t,exporter:r,defined:!0};o&&o.external&&o.external.resolveExternal(i),this.profiler.logOperationStart({id:MODULE_DEFINE,specifier:e}),this.namedDefineRegistry.set(e,i),this.lastDefine=i}registerExternalModules(e){e.map((e=>{if(!this.namedDefineRegistry.has(e)){let t,r;const o=new Promise(((o,i)=>{t=o,r=setTimeout((()=>{i(new LoaderError(MODULE_LOAD_TIMEOUT,[e]))}),MODULE_LOAD_TIMEOUT_TIMER)})).finally((()=>{clearTimeout(r)})),i={name:e,defined:!1,external:{resolveExternal:t,moduleDefPromise:o}};this.namedDefineRegistry.set(e,i)}}))}__init2(){this.namedDefineRegistry=new Map}__init3(){this.moduleRegistry=new Map}__init4(){this.aliases=new Map}getImportMetadataResolver(){return this.resolver}async getModuleRecord(e,t){const r=this.moduleRegistry.get(e);if(r)if(isUrl(e)){const o=await r.instantiation,i=await this.resolve(t);if(isUrl(i)||o.name===i)return this.storeModuleAlias(t,i),r;{e=i;const r=this.moduleRegistry.get(e);if(r)return this.storeModuleAlias(t,i),r}}else if(r)return this.storeModuleAlias(t,e),r;if(e!==t){const e=this.aliases.get(t);if(e){const t=this.moduleRegistry.get(e);if(t)return t}}const o=this.getModuleDef(e,t),i=o.then((e=>{const t=(e.dependencies||[]).map((e=>{if("exports"!==e)return invariant("require"!==e,NO_AMD_REQUIRE),this.getModuleDependencyRecord.call(this,e)})).filter((e=>void 0!==e));return Promise.all(t)})),n={id:e,originalId:t,module:Object.create(null),dependencyRecords:i,instantiation:o,evaluated:!1,evaluationPromise:null};return this.moduleRegistry.set(e,n),e!==t&&this.storeModuleAlias(t,e),i.then((()=>n))}storeModuleAlias(e,t){e!==t&&(this.aliases.has(e)||this.aliases.set(e,t))}async getModuleDependencyRecord(e){let t=await this.resolve(e);if(isUrl(t)){const r=this.moduleRegistry.get(t);r&&!this.aliases.has(e)&&(await r.instantiation,t=await this.resolve(e))}return this.getModuleRecord(t,e)}async topLevelEvaluation(e){return this.evaluateModule(e,{})}async evaluateModule(e,t){const r=await e.dependencyRecords;r.length>0&&(t[e.id]=!0,await this.evaluateModuleDependencies(r,t));const{exporter:o,dependencies:i}=await e.instantiation,n={},s=i?await Promise.all(i.map((async e=>{if("exports"===e)return n;const t=await this.resolve(e),r=this.moduleRegistry.get(t);if(!r)throw new LoaderError(FAILED_DEP,[t]);const o=r.module;if(!r.evaluated)return this.getCircularDependencyWrapper(o);if(o)return o.__defaultInterop?o.default:o;throw new LoaderError(FAILED_DEP,[t])}))):[];if(e.evaluated)return e.module;let a;try{a=o(...s)}catch(t){throw new LoaderError(EXPORTER_ERROR,[e.id,t.message||t])}void 0!==a?(a={default:a},Object.defineProperty(a,"__defaultInterop",{value:!0})):this.isNamedExportDefaultOnly(n)&&Object.defineProperty(n,"__useDefault",{value:!0});const l=a||n;for(const t in l)Object.defineProperty(e.module,t,{enumerable:!0,set(e){l[t]=e},get:()=>l[t]});return l.__useDefault&&Object.defineProperty(e.module,"__useDefault",{value:!0}),l.__defaultInterop&&Object.defineProperty(e.module,"__defaultInterop",{value:!0}),l.__esModule&&Object.defineProperty(e.module,"__esModule",{value:!0}),e.evaluated=!0,Object.freeze(e.module),e.module}isNamedExportDefaultOnly(e){return void 0!==e&&2===Object.getOwnPropertyNames(e).length&&Object.prototype.hasOwnProperty.call(e,"default")&&Object.prototype.hasOwnProperty.call(e,"__esModule")}getCircularDependencyWrapper(e){const t=()=>e.__useDefault||e.__defaultInterop?e.default:e;return t.__circular__=!0,t}async evaluateModuleDependencies(e,t){for(let r=0;r<e.length;r++){const o=e[r];o.evaluated||t[o.id]||(t[o.id]=!0,await this.evaluateModule(o,t))}}async getModuleDef(e,t){this.lastDefine=void 0;const r=isUrl(e)?t!==e?t:void 0:e;let o=r&&this.namedDefineRegistry.get(r);if(o&&o.external)return o.external.moduleDefPromise;if(o&&o.defined)return o;const i=this.resolver.getBaseUrl(),n=r||t;return this.profiler.logOperationStart({id:MODULE_FETCH,specifier:n}),Promise.resolve().then((async()=>{const t=this.loadHook;if(t)for(let r=0;r<t.length;r++){const o=(0,t[r])(e,i),n=isResponseAPromise(o)?await evaluateLoadHook(e,o):o;if(void 0===n)throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);if(n&&null!==n)return evaluateLoadHookResponse(n,e)}return!1})).then((t=>{if(!0!==t&&hasDocument)return loadModuleDef(e)})).then((()=>{if(o=r&&this.namedDefineRegistry.get(r),o||(this.logMessage("warning",`${r} not found, falling back to the last loader.define call`),o=this.lastDefine),!o)throw new LoaderError(FAIL_INSTANTIATE,[e]);return this.profiler.logOperationEnd({id:MODULE_FETCH,specifier:n}),o})).catch((e=>{throw e instanceof LoaderError||this.profiler.logOperationStart({id:MODULE_ERROR,specifier:n}),e}))}addLoaderPlugin(e){if("object"!=typeof e)throw new LoaderError(INVALID_HOOK);const{loadModule:t,resolveModule:r,loadMapping:o}=e;r&&(this.resolveHook?this.resolveHook.push(r):this.resolveHook=[r]),t&&(this.loadHook?this.loadHook.push(t):this.loadHook=[t]),o&&this.resolver.addLoadMappingHook(o)}importMetadataInvalidationCallback({name:e,oldUrl:t,newUrl:r}){const o=this.handleStaleModuleHook;o&&evaluateHandleStaleModuleHooks(o,{name:e,oldUrl:t,newUrl:r})}registerHandleStaleModuleHook(e){this.handleStaleModuleHook?this.handleStaleModuleHook.push(e):this.handleStaleModuleHook=[e]}isValidResolveResponse(e){return null===e||"string"==typeof e||e&&"string"==typeof e.url}getModuleWarnings(e=!1){return this.isAppMounted=e,this.warnings}logMessage(e,t){}}function _nullishCoalesce(e,t){return null!=e?e:t()}function validateLoadSpecifier(e,t,r,o){const{LoaderError:i,NO_IMPORT_LWC:n,NO_IMPORT_LOADER:s,NO_IMPORT_TRANSPORT:a,NO_BLOB_IMPORT:l}=o;if("lwc"===e||e.startsWith("lwc/v/"))throw new i(n,[_nullishCoalesce(t,(()=>"unknown"))]);if(e===r||e.startsWith(`${r}/v/`))throw new i(s,[_nullishCoalesce(t,(()=>"unknown"))]);if("transport"===e||e.startsWith("transport/v/")||"webruntime/transport"===e||e.startsWith("webruntime/transport/v/"))throw new i(a,[_nullishCoalesce(t,(()=>"unknown"))]);if(e.toLowerCase().startsWith("blob:"))throw new i(l)}class Loader{constructor(e){let t=e.baseUrl;const r=e.endpoints?e.endpoints.uris.mapping:void 0;let o=e.profiler;if(!r||!e.endpoints)throw new LoaderError(NO_MAPPING_URL);if(e.endpoints.uris.mapping=r.replace(/\/?$/,"/"),t&&(t=t.replace(/\/?$/,"/")),t||(t=getBaseUrl()),!t)throw new LoaderError(NO_BASE_URL);if(o||(o={logOperationStart:()=>{},logOperationEnd:()=>{}}),this.registry=new ModuleRegistry(Object.freeze({endpoints:e.endpoints,baseUrl:t,profiler:o,flags:e.flags||{}})),e.appMetadata&&!e.appMetadata.appId){const t=e.appMetadata.bootstrapModule.match(/@lwr-bootstrap\/(.+)\/v\/.+/),r=t&&t[1];e.appMetadata.appId=r}this.services=Object.freeze({addLoaderPlugin:this.registry.addLoaderPlugin.bind(this.registry),handleStaleModule:this.registry.registerHandleStaleModuleHook.bind(this.registry),appMetadata:e.appMetadata})}define(e,t,r){invariant("string"==typeof e,MISSING_NAME);let o=r,i=t;"function"==typeof i&&(o=t,i=[]),invariant(Array.isArray(i),INVALID_DEPS),this.registry.define(e,i,o)}async load(e,t){return validateLoadSpecifier(e,t,"lwr/loader",{LoaderError:LoaderError,NO_IMPORT_LWC:NO_IMPORT_LWC,NO_IMPORT_LOADER:NO_IMPORT_LOADER,NO_IMPORT_TRANSPORT:NO_IMPORT_TRANSPORT,NO_BLOB_IMPORT:NO_BLOB_IMPORT}),this.registry.load(e,t)}has(e){return this.registry.has(e)}async resolve(e,t){return this.registry.resolve(e,t)}async registerImportMappings(e,t){this.registry.getImportMetadataResolver().registerImportMappings(e,t)}registerExternalModules(e){this.registry.registerExternalModules(e)}getModuleWarnings(e=!1){return this.registry.getModuleWarnings(e)}}exports.Loader=Loader,Object.defineProperty(exports,"__esModule",{value:!0})}));
12
+ const SUPPORTS_TRUSTED_TYPES="undefined"!=typeof trustedTypes,trustedTypePolicyRegistry={__proto__:null};function createDuplicateSafeTrustedTypesPolicy(e,t){return trustedTypePolicyRegistry[e]?trustedTypePolicyRegistry[e]:trustedTypePolicyRegistry[e]=trustedTypes.createPolicy(e,t)}function createDuplicateSafeFallbackPolicy(e,t){return trustedTypePolicyRegistry[e]?trustedTypePolicyRegistry[e]:trustedTypePolicyRegistry[e]=t}const createPolicy=SUPPORTS_TRUSTED_TYPES?createDuplicateSafeTrustedTypesPolicy:createDuplicateSafeFallbackPolicy,policyOptions={createHTML:e=>e,createScript:e=>e,createScriptURL:e=>e};try{createPolicy("default",{createHTML:e=>e,createScript(e){if("null"===e||"undefined"===e)return e},createScriptURL:e=>e})}catch(e){}const trusted=createPolicy("trusted",policyOptions);let lastWindowError;function isCustomResponse(e){return Object.prototype.hasOwnProperty.call(e,"data")&&!Object.prototype.hasOwnProperty.call(e,"blob")}function isFetchResponse(e){return"function"==typeof e.blob}function isResponseAPromise(e){return!(!e||!e.then)}async function evaluateLoadHookResponse(response,id){return Promise.resolve().then((async()=>{if(!response||!response.status)throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);if(200!==response.status)throw new LoaderError(HTTP_FAIL_LOAD,[id,`${response.status}`]);const isResponse=isFetchResponse(response);let code;if(isCustomResponse(response))code=response.data;else{if(!isResponse)throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);code=await response.text()}if(!code)throw new LoaderError(FAIL_LOAD,[`empty code for ${id}`]);code=`${code}\n//# sourceURL=${id}`;try{eval(trusted.createScript(code))}catch(e){throw new LoaderError(FAIL_LOAD,[`"${id}": ${e instanceof Error?e.message:String(e)}`])}if(lastWindowError)throw new LoaderError(FAIL_LOAD,[`"${id}": window error ${lastWindowError instanceof Error?lastWindowError.message:String(lastWindowError)}`]);return!0}))}async function evaluateLoadHook(e,t){return hasSetTimeout?new Promise(((r,o)=>{const i=setTimeout((()=>{o(new LoaderError(MODULE_LOAD_TIMEOUT,[e]))}),MODULE_LOAD_TIMEOUT_TIMER);t.then((e=>{r(e)})).catch((()=>{o(new LoaderError(FAIL_HOOK_LOAD,[e]))})).finally((()=>{clearTimeout(i)}))})):t}hasDocument&&globalThis.addEventListener("error",(e=>{lastWindowError=e.error}));class ModuleRegistry{__init(){this.isAppMounted=!1}constructor(e){ModuleRegistry.prototype.__init.call(this),ModuleRegistry.prototype.__init2.call(this),ModuleRegistry.prototype.__init3.call(this),ModuleRegistry.prototype.__init4.call(this),this.profiler=e.profiler,this.resolver=new ImportMetadataResolver(e,this.importMetadataInvalidationCallback.bind(this)),this.warnings={[MODULE_WARNING.MODULE_REDEFINE]:[],[MODULE_WARNING.MODULE_ALREADY_LOADED]:[],[MODULE_WARNING.ALIAS_UPDATE]:[]}}async load(e,t){const r=t?{importer:t}:{};this.profiler.logOperationStart({id:MODULE_DYNAMIC_LOAD,specifier:e,metadata:r});const o=await this.resolve(e,t),i=await this.getModuleRecord(o,e);return i.evaluated?i.module:(i.evaluationPromise||(i.evaluationPromise=this.topLevelEvaluation(i)),i.evaluationPromise)}async resolve(e,t){const r=this.resolver.getBaseUrl();let o,i=e;const n=this.resolveHook;if(n){for(let e=0;e<n.length;e++){const t=(0,n[e])(i,{parentUrl:r});let s;if((t||null===t)&&(s=isResponseAPromise(t)?await t:t),!this.isValidResolveResponse(s))throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);if(null!==s){if("string"==typeof s){if(resolveIfNotPlainOrUrl(s,r))throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);i=s;continue}if(o=s&&s.url&&(resolveIfNotPlainOrUrl(s.url,r)||s.url),!o)throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);break}}if(i!==e){if(!o&&this.namedDefineRegistry.has(i))return i;e=i}}if(!o){const t=resolveIfNotPlainOrUrl(e,r)||e;if(this.moduleRegistry.has(t))return t;const i=this.resolver.resolveLocal(t);if(i){if(this.namedDefineRegistry.has(t)){const e=this.namedDefineRegistry.get(t);if(e.external||e.defined){if(!this.moduleRegistry.get(i)||!this.aliases.has(t))return t}}return i}if(this.namedDefineRegistry.has(t))return t;try{o=await this.resolver.resolve(t)}catch(e){}}if(!o||!isUrl(o)){if(this.namedDefineRegistry.has(e))return e;throw new LoaderError(UNRESOLVED,[e])}return t&&isUrl(o)&&(o+=`?importer=${encodeURIComponent(t)}`),o}has(e){return this.moduleRegistry.has(e)}define(e,t,r){const o=this.namedDefineRegistry.get(e);if(o&&o.defined)return void(this.lastDefine=o);const i={name:e,dependencies:t,exporter:r,defined:!0};o&&o.external&&o.external.resolveExternal(i),this.profiler.logOperationStart({id:MODULE_DEFINE,specifier:e}),this.namedDefineRegistry.set(e,i),this.lastDefine=i}registerExternalModules(e){e.map((e=>{if(!this.namedDefineRegistry.has(e)){let t,r;const o=new Promise(((o,i)=>{t=o,r=setTimeout((()=>{i(new LoaderError(MODULE_LOAD_TIMEOUT,[e]))}),MODULE_LOAD_TIMEOUT_TIMER)})).finally((()=>{clearTimeout(r)})),i={name:e,defined:!1,external:{resolveExternal:t,moduleDefPromise:o}};this.namedDefineRegistry.set(e,i)}}))}__init2(){this.namedDefineRegistry=new Map}__init3(){this.moduleRegistry=new Map}__init4(){this.aliases=new Map}getImportMetadataResolver(){return this.resolver}async getModuleRecord(e,t){const r=this.moduleRegistry.get(e);if(r)if(isUrl(e)){const o=await r.instantiation,i=await this.resolve(t);if(isUrl(i)||o.name===i)return this.storeModuleAlias(t,i),r;{e=i;const r=this.moduleRegistry.get(e);if(r)return this.storeModuleAlias(t,i),r}}else if(r)return this.storeModuleAlias(t,e),r;if(e!==t){const e=this.aliases.get(t);if(e){const t=this.moduleRegistry.get(e);if(t)return t}}const o=this.getModuleDef(e,t),i=o.then((e=>{const t=(e.dependencies||[]).map((e=>{if("exports"!==e)return invariant("require"!==e,NO_AMD_REQUIRE),this.getModuleDependencyRecord.call(this,e)})).filter((e=>void 0!==e));return Promise.all(t)})),n={id:e,originalId:t,module:Object.create(null),dependencyRecords:i,instantiation:o,evaluated:!1,evaluationPromise:null};return this.moduleRegistry.set(e,n),e!==t&&this.storeModuleAlias(t,e),i.then((()=>n))}storeModuleAlias(e,t){e!==t&&(this.aliases.has(e)||this.aliases.set(e,t))}async getModuleDependencyRecord(e){let t=await this.resolve(e);if(isUrl(t)){const r=this.moduleRegistry.get(t);r&&!this.aliases.has(e)&&(await r.instantiation,t=await this.resolve(e))}return this.getModuleRecord(t,e)}async topLevelEvaluation(e){return this.evaluateModule(e,{})}async evaluateModule(e,t){const r=await e.dependencyRecords;r.length>0&&(t[e.id]=!0,await this.evaluateModuleDependencies(r,t));const{exporter:o,dependencies:i}=await e.instantiation,n={},s=i?await Promise.all(i.map((async e=>{if("exports"===e)return n;const t=await this.resolve(e),r=this.moduleRegistry.get(t);if(!r)throw new LoaderError(FAILED_DEP,[t]);const o=r.module;if(!r.evaluated)return this.getCircularDependencyWrapper(o);if(o)return o.__defaultInterop?o.default:o;throw new LoaderError(FAILED_DEP,[t])}))):[];if(e.evaluated)return e.module;let a;try{a=o(...s)}catch(t){throw new LoaderError(EXPORTER_ERROR,[e.id,t.message||t])}void 0!==a?(a={default:a},Object.defineProperty(a,"__defaultInterop",{value:!0})):this.isNamedExportDefaultOnly(n)&&Object.defineProperty(n,"__useDefault",{value:!0});const l=a||n;for(const t in l)Object.defineProperty(e.module,t,{enumerable:!0,set(e){l[t]=e},get:()=>l[t]});return l.__useDefault&&Object.defineProperty(e.module,"__useDefault",{value:!0}),l.__defaultInterop&&Object.defineProperty(e.module,"__defaultInterop",{value:!0}),l.__esModule&&Object.defineProperty(e.module,"__esModule",{value:!0}),e.evaluated=!0,Object.freeze(e.module),e.module}isNamedExportDefaultOnly(e){return void 0!==e&&2===Object.getOwnPropertyNames(e).length&&Object.prototype.hasOwnProperty.call(e,"default")&&Object.prototype.hasOwnProperty.call(e,"__esModule")}getCircularDependencyWrapper(e){const t=()=>e.__useDefault||e.__defaultInterop?e.default:e;return t.__circular__=!0,t}async evaluateModuleDependencies(e,t){for(let r=0;r<e.length;r++){const o=e[r];o.evaluated||t[o.id]||(t[o.id]=!0,await this.evaluateModule(o,t))}}async getModuleDef(e,t){this.lastDefine=void 0;const r=isUrl(e)?t!==e?t:void 0:e;let o=r&&this.namedDefineRegistry.get(r);if(o&&o.external)return o.external.moduleDefPromise;if(o&&o.defined)return o;const i=this.resolver.getBaseUrl(),n=r||t;return this.profiler.logOperationStart({id:MODULE_FETCH,specifier:n}),Promise.resolve().then((async()=>{const t=this.loadHook;if(t)for(let r=0;r<t.length;r++){const o=(0,t[r])(e,i),n=isResponseAPromise(o)?await evaluateLoadHook(e,o):o;if(void 0===n)throw new LoaderError(INVALID_LOADER_SERVICE_RESPONSE);if(n&&null!==n)return evaluateLoadHookResponse(n,e)}return!1})).then((t=>{if(!0!==t&&hasDocument)return loadModuleDef(e)})).then((()=>{if(o=r&&this.namedDefineRegistry.get(r),o||(this.logMessage("warning",`${r} not found, falling back to the last loader.define call`),o=this.lastDefine),!o)throw new LoaderError(FAIL_INSTANTIATE,[e]);return this.profiler.logOperationEnd({id:MODULE_FETCH,specifier:n}),o})).catch((e=>{throw e instanceof LoaderError||this.profiler.logOperationStart({id:MODULE_ERROR,specifier:n}),e}))}addLoaderPlugin(e){if("object"!=typeof e)throw new LoaderError(INVALID_HOOK);const{loadModule:t,resolveModule:r,loadMapping:o}=e;r&&(this.resolveHook?this.resolveHook.push(r):this.resolveHook=[r]),t&&(this.loadHook?this.loadHook.push(t):this.loadHook=[t]),o&&this.resolver.addLoadMappingHook(o)}importMetadataInvalidationCallback({name:e,oldUrl:t,newUrl:r}){const o=this.handleStaleModuleHook;o&&evaluateHandleStaleModuleHooks(o,{name:e,oldUrl:t,newUrl:r})}registerHandleStaleModuleHook(e){this.handleStaleModuleHook?this.handleStaleModuleHook.push(e):this.handleStaleModuleHook=[e]}isValidResolveResponse(e){return null===e||"string"==typeof e||e&&"string"==typeof e.url}getModuleWarnings(e=!1){return this.isAppMounted=e,this.warnings}logMessage(e,t){}}function _nullishCoalesce(e,t){return null!=e?e:t()}function validateLoadSpecifier(e,t,r,o){const{LoaderError:i,NO_IMPORT_LWC:n,NO_IMPORT_LOADER:s,NO_IMPORT_TRANSPORT:a,NO_BLOB_IMPORT:l}=o;if("lwc"===e||e.startsWith("lwc/v/"))throw new i(n,[_nullishCoalesce(t,(()=>"unknown"))]);if(e===r||e.startsWith(`${r}/v/`))throw new i(s,[_nullishCoalesce(t,(()=>"unknown"))]);if("transport"===e||e.startsWith("transport/v/")||"webruntime/transport"===e||e.startsWith("webruntime/transport/v/"))throw new i(a,[_nullishCoalesce(t,(()=>"unknown"))]);if(e.toLowerCase().startsWith("blob:"))throw new i(l)}function assertValidImportMapUrlKey(e){const t=e.toLowerCase();if(t.startsWith("blob:"))throw new Error(`Cannot map ${e} to blob: URL`);if(t.startsWith("data:"))throw new Error(`Cannot map ${e} to data: URL`);if(!/^[./]|^https?:/.test(e))throw new Error(`LWR.importMap(): "${e}" is not a valid URL key. Keys must be URL paths (e.g. "/path/to/module.js"), not module specifiers. Transitive specifier aliasing is not supported by this loader.`)}function validateAndWrapAsImportMetadata(e){if(!e||"object"!=typeof e)throw new Error("LWR.importMap() requires an object argument");const t=Object.entries(e);if(0===t.length)return null;const r=new Set,o={};for(const[e,i]of t){if(!e||"string"!=typeof e)throw new Error("moduleScriptURL must be a string");if(!Array.isArray(i))throw new Error("moduleNames must be an array");assertValidImportMapUrlKey(e);const t=[];for(const e of i){if("string"!=typeof e||0===e.length)throw new Error("Specifier must be a non-empty string");r.has(e)||(r.add(e),t.push(e))}t.length>0&&(o[e]=t)}return 0===Object.keys(o).length?null:{imports:o}}function isImportMetadata(e){const t=e;return null!==t&&"object"==typeof t&&"imports"in t&&"object"==typeof t.imports&&!Array.isArray(t.imports)}class Loader{constructor(e){let t=e.baseUrl;const r=e.endpoints?e.endpoints.uris.mapping:void 0;let o=e.profiler;if(!r||!e.endpoints)throw new LoaderError(NO_MAPPING_URL);if(e.endpoints.uris.mapping=r.replace(/\/?$/,"/"),t&&(t=t.replace(/\/?$/,"/")),t||(t=getBaseUrl()),!t)throw new LoaderError(NO_BASE_URL);if(o||(o={logOperationStart:()=>{},logOperationEnd:()=>{}}),this.registry=new ModuleRegistry(Object.freeze({endpoints:e.endpoints,baseUrl:t,profiler:o,flags:e.flags||{}})),e.appMetadata&&!e.appMetadata.appId){const t=e.appMetadata.bootstrapModule.match(/@lwr-bootstrap\/(.+)\/v\/.+/),r=t&&t[1];e.appMetadata.appId=r}this.services=Object.freeze({addLoaderPlugin:this.registry.addLoaderPlugin.bind(this.registry),handleStaleModule:this.registry.registerHandleStaleModuleHook.bind(this.registry),appMetadata:e.appMetadata})}define(e,t,r){invariant("string"==typeof e,MISSING_NAME);let o=r,i=t;"function"==typeof i&&(o=t,i=[]),invariant(Array.isArray(i),INVALID_DEPS),this.registry.define(e,i,o)}async load(e,t){return validateLoadSpecifier(e,t,"lwr/loader",{LoaderError:LoaderError,NO_IMPORT_LWC:NO_IMPORT_LWC,NO_IMPORT_LOADER:NO_IMPORT_LOADER,NO_IMPORT_TRANSPORT:NO_IMPORT_TRANSPORT,NO_BLOB_IMPORT:NO_BLOB_IMPORT}),this.registry.load(e,t)}has(e){return this.registry.has(e)}async resolve(e,t){return this.registry.resolve(e,t)}async importMap(e,t){if(isImportMetadata(e))return void this.registry.getImportMetadataResolver().registerImportMappings(e,t);const r=this.registry.getImportMetadataResolver(),o=validateAndWrapAsImportMetadata(e);if(!o)return;const i={};for(const[e,t]of Object.entries(o.imports)){const o=[];for(const e of t){void 0!==r.getMappingUri(e)||o.push(e)}o.length>0&&(i[e]=o)}if(0===Object.keys(i).length)return;const n={imports:i},s=Object.values(n.imports).flat();r.registerImportMappings(n,s)}async registerImportMappings(e,t){return hasConsole&&console.warn("registerImportMappings() is deprecated. Use importMap() instead."),this.importMap(e,t)}registerExternalModules(e){this.registry.registerExternalModules(e)}getModuleWarnings(e=!1){return this.registry.getModuleWarnings(e)}}exports.Loader=Loader,Object.defineProperty(exports,"__esModule",{value:!0})}));
@@ -4,7 +4,7 @@
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
- /* LWR Module Loader Shim v0.22.12 */
7
+ /* LWR Module Loader Shim v0.23.0 */
8
8
  (function () {
9
9
  'use strict';
10
10
 
@@ -283,6 +283,7 @@
283
283
 
284
284
 
285
285
 
286
+
286
287
  /* eslint-disable lwr/no-unguarded-apis */
287
288
  const hasSetTimeout = typeof setTimeout === 'function';
288
289
  const hasConsole = typeof console !== 'undefined';
@@ -309,7 +310,7 @@
309
310
  // Parse configuration
310
311
  this.global = global;
311
312
  this.config = global.LWR ;
312
- this.loaderSpecifier = 'lwr/loader/v/0_22_12';
313
+ this.loaderSpecifier = 'lwr/loader/v/0_23_0';
313
314
 
314
315
  // Set up error handler
315
316
  this.errorHandler = this.config.onError ;
@@ -317,7 +318,7 @@
317
318
  // Set up onAppInit handler
318
319
  this.initAppHandler = this.config.onInitApp ;
319
320
 
320
- // Set up the temporary LWR.define function and customInit hook
321
+ // Set up the temporary LWR.define function
321
322
  const tempDefine = this.tempDefine.bind(this);
322
323
  global.LWR.define = tempDefine;
323
324
  this.bootReady = this.config.autoBoot;
@@ -474,7 +475,7 @@
474
475
  const exporter = (exports) => {
475
476
  Object.assign(exports, { logOperationStart, logOperationEnd });
476
477
  };
477
- define('lwr/profiler/v/0_22_12', ['exports'], exporter);
478
+ define('lwr/profiler/v/0_23_0', ['exports'], exporter);
478
479
  }
479
480
 
480
481
  // Set up the application globals, import map, root custom element...
@@ -483,9 +484,13 @@
483
484
  this.config;
484
485
 
485
486
  const importsObj = imports || {};
486
- // Set global LWR.define to loader.define
487
+
488
+ // Set global LWR.define to loader.define and expose the public-only importMap.
489
+ // The wrapper intentionally omits the internal rootSpecifiers parameter so external
490
+ // callers cannot bypass runtime validation by triggering the bootstrap path.
487
491
  this.global.LWR = Object.freeze({
488
492
  define: loader.define.bind(loader),
493
+ importMap: (update) => loader.importMap(update),
489
494
  rootComponent,
490
495
  rootComponents,
491
496
  serverData: serverData || {},
@@ -508,10 +513,7 @@
508
513
 
509
514
  // Load the import mappings and application bootstrap module
510
515
  loader
511
- .registerImportMappings({ imports: importsObj, index }, [
512
- bootstrapModule,
513
- rootComponent ,
514
- ])
516
+ .importMap({ imports: importsObj, index }, [bootstrapModule, rootComponent ])
515
517
  .then(() => {
516
518
  // eslint-disable-next-line lwr/no-unguarded-apis
517
519
  if (typeof window === 'undefined' || typeof document === 'undefined') {
@@ -574,8 +576,8 @@
574
576
  // The loader module is ALWAYS required
575
577
  const GLOBAL = globalThis ;
576
578
  GLOBAL.LWR.requiredModules = GLOBAL.LWR.requiredModules || [];
577
- if (GLOBAL.LWR.requiredModules.indexOf('lwr/loader/v/0_22_12') < 0) {
578
- GLOBAL.LWR.requiredModules.push('lwr/loader/v/0_22_12');
579
+ if (GLOBAL.LWR.requiredModules.indexOf('lwr/loader/v/0_23_0') < 0) {
580
+ GLOBAL.LWR.requiredModules.push('lwr/loader/v/0_23_0');
579
581
  }
580
582
  new LoaderShim(GLOBAL);
581
583
 
@@ -63,11 +63,7 @@ var ImportMetadataResolver = class {
63
63
  getBaseUrl() {
64
64
  return this.config.baseUrl || "";
65
65
  }
66
- registerImportMappings(newImportMetadata, rootSpecifiers) {
67
- if (!rootSpecifiers || rootSpecifiers.length === 0) {
68
- const imports = newImportMetadata ? JSON.stringify(newImportMetadata) : "undefined";
69
- throw new import_messages.LoaderError(import_messages.BAD_IMPORT_METADATA, [imports, rootSpecifiers ? "[]" : "undefined"]);
70
- }
66
+ registerImportMappings(newImportMetadata, rootSpecifiers = []) {
71
67
  if (!newImportMetadata) {
72
68
  throw new import_messages.LoaderError(import_messages.BAD_IMPORT_METADATA, ["undefined", JSON.stringify(rootSpecifiers)]);
73
69
  }
@@ -98,6 +94,9 @@ var ImportMetadataResolver = class {
98
94
  });
99
95
  }
100
96
  }
97
+ getMappingUri(specifier) {
98
+ return this.importURICache.get(specifier)?.uri;
99
+ }
101
100
  getURI(specifier) {
102
101
  return this.importURICache && this.importURICache.has(specifier) ? (0, import_url.resolveUrl)(this.importURICache.get(specifier).uri, this.getBaseUrl()) : void 0;
103
102
  }
@@ -0,0 +1,61 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __markAsModule = (target) => __defProp(target, "__esModule", {value: true});
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, {get: all[name], enumerable: true});
6
+ };
7
+
8
+ // packages/@lwrjs/loader/src/modules/lwr/loader/utils/validation.ts
9
+ __markAsModule(exports);
10
+ __export(exports, {
11
+ validateAndWrapAsImportMetadata: () => validateAndWrapAsImportMetadata
12
+ });
13
+ function assertValidImportMapUrlKey(moduleScriptURL) {
14
+ const lowerUri = moduleScriptURL.toLowerCase();
15
+ if (lowerUri.startsWith("blob:")) {
16
+ throw new Error(`Cannot map ${moduleScriptURL} to blob: URL`);
17
+ }
18
+ if (lowerUri.startsWith("data:")) {
19
+ throw new Error(`Cannot map ${moduleScriptURL} to data: URL`);
20
+ }
21
+ if (!/^[./]|^https?:/.test(moduleScriptURL)) {
22
+ throw new Error(`LWR.importMap(): "${moduleScriptURL}" is not a valid URL key. Keys must be URL paths (e.g. "/path/to/module.js"), not module specifiers. Transitive specifier aliasing is not supported by this loader.`);
23
+ }
24
+ }
25
+ function validateAndWrapAsImportMetadata(update) {
26
+ if (!update || typeof update !== "object") {
27
+ throw new Error("LWR.importMap() requires an object argument");
28
+ }
29
+ const entries = Object.entries(update);
30
+ if (entries.length === 0) {
31
+ return null;
32
+ }
33
+ const seenSpecifiers = new Set();
34
+ const validatedImports = {};
35
+ for (const [moduleScriptURL, moduleNames] of entries) {
36
+ if (!moduleScriptURL || typeof moduleScriptURL !== "string") {
37
+ throw new Error("moduleScriptURL must be a string");
38
+ }
39
+ if (!Array.isArray(moduleNames)) {
40
+ throw new Error("moduleNames must be an array");
41
+ }
42
+ assertValidImportMapUrlKey(moduleScriptURL);
43
+ const validatedNames = [];
44
+ for (const moduleName of moduleNames) {
45
+ if (typeof moduleName !== "string" || moduleName.length === 0) {
46
+ throw new Error("Specifier must be a non-empty string");
47
+ }
48
+ if (!seenSpecifiers.has(moduleName)) {
49
+ seenSpecifiers.add(moduleName);
50
+ validatedNames.push(moduleName);
51
+ }
52
+ }
53
+ if (validatedNames.length > 0) {
54
+ validatedImports[moduleScriptURL] = validatedNames;
55
+ }
56
+ }
57
+ if (Object.keys(validatedImports).length === 0) {
58
+ return null;
59
+ }
60
+ return {imports: validatedImports};
61
+ }
@@ -4,7 +4,7 @@
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
- /* LWR ESM Module Loader v0.22.12 */
7
+ /* LWR ESM Module Loader v0.23.0 */
8
8
  function _optionalChain$1(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
9
9
 
10
10
 
@@ -1,5 +1,5 @@
1
1
  import { Module } from './moduleRegistry/moduleRegistry.js';
2
- import type { ServiceAPI, ImportMetadata } from '@lwrjs/types';
2
+ import type { ServiceAPI, ImportMetadata, ImportMapUpdate } from '@lwrjs/types';
3
3
  import type { FingerprintsLoaderConfig as LoaderConfig } from '../../../types.js';
4
4
  /**
5
5
  * The LWR loader is inspired and borrows from the algorithms and native browser principles of https://github.com/systemjs/systemjs
@@ -42,6 +42,36 @@ export declare class Loader {
42
42
  * @return {string}
43
43
  */
44
44
  resolve(id: string, importer?: string): Promise<string>;
45
+ /**
46
+ * Apply import map updates at runtime, or register bootstrap import mappings.
47
+ *
48
+ * **Runtime usage** (public API, consistent with `LWR.importMap()` on the legacy loader):
49
+ * `importMap({ [moduleScriptURL]: [moduleName1, moduleName2, ...] })`
50
+ * Validates the update and registers the new mappings dynamically.
51
+ *
52
+ * **Bootstrap / internal usage** (replaces `registerImportMappings`):
53
+ * `importMap(importMetadata)` or `importMap(importMetadata, rootSpecifiers)`
54
+ * Detected at runtime by the `ImportMetadata` shape (presence of an `imports` object).
55
+ * This branch **does not** run `validateAndWrapAsImportMetadata` (URL-key checks /
56
+ * runtime-payload dedupe). That is intentional: bootstrap must preserve
57
+ * `index` fingerprints and use `ImportMetadataResolver.registerImportMappings` merge
58
+ * semantics unchanged from the pre-`importMap` API.
59
+ *
60
+ * **Who may use this branch:** Platform/shim code with trusted config (see
61
+ * `shim/shim.ts`, which calls `loader.importMap({ imports, index }, roots)`). The
62
+ * public `LWR.importMap` wrapper only forwards the flat runtime update shape; any
63
+ * code with a direct `Loader` reference could still pass an `ImportMetadata`-shaped
64
+ * object — same trust boundary as calling `registerImportMappings` before.
65
+ *
66
+ * @param update - Runtime: `ImportMapUpdate` mapping script URLs to the module names they define.
67
+ * Bootstrap: `ImportMetadata` with an `imports` object (and optional `index`).
68
+ * @param rootSpecifiers - Bootstrap only: root module specifiers for the initial registration.
69
+ * Optional — omit when the root specifiers are not known.
70
+ */
71
+ importMap(update: ImportMapUpdate | ImportMetadata, rootSpecifiers?: string[]): Promise<void>;
72
+ /**
73
+ * @deprecated Use `importMap(metadata, rootSpecifiers)` instead.
74
+ */
45
75
  registerImportMappings(mappings: ImportMetadata, rootSpecifiers: string[]): Promise<void>;
46
76
  /**
47
77
  * Marks modules as "externally" loaded/provided (e.g. preloaded), so that the loader does not attempt to load them.
@@ -4,7 +4,7 @@
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
- /* LWR Module Loader v0.22.12 */
7
+ /* LWR Module Loader v0.23.0 */
8
8
  const templateRegex = /\{([0-9]+)\}/g;
9
9
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
10
  function templateString(template, args) {
@@ -436,11 +436,7 @@ class ImportMetadataResolver {
436
436
  return this.config.baseUrl || '';
437
437
  }
438
438
 
439
- registerImportMappings(newImportMetadata, rootSpecifiers) {
440
- if (!rootSpecifiers || rootSpecifiers.length === 0) {
441
- const imports = newImportMetadata ? JSON.stringify(newImportMetadata) : 'undefined';
442
- throw new LoaderError(BAD_IMPORT_METADATA, [imports, rootSpecifiers ? '[]' : 'undefined']);
443
- }
439
+ registerImportMappings(newImportMetadata, rootSpecifiers = []) {
444
440
  if (!newImportMetadata) {
445
441
  throw new LoaderError(BAD_IMPORT_METADATA, ['undefined', JSON.stringify(rootSpecifiers)]);
446
442
  }
@@ -450,6 +446,8 @@ class ImportMetadataResolver {
450
446
  JSON.stringify(rootSpecifiers),
451
447
  ]);
452
448
  }
449
+ // An empty rootSpecifiers list is valid for non-bootstrap registrations;
450
+ // any specifier not in the list receives isRoot: false.
453
451
  const index = newImportMetadata.index || {};
454
452
  for (const [uri, specifiers] of Object.entries(newImportMetadata.imports)) {
455
453
  specifiers.forEach((specifier) => {
@@ -472,6 +470,16 @@ class ImportMetadataResolver {
472
470
  }
473
471
  }
474
472
 
473
+ /**
474
+ * Returns the raw URI stored for a specifier, or `undefined` if not yet mapped.
475
+ * Used by the runtime `importMap()` path to detect cross-call duplicates while
476
+ * allowing truly idempotent re-registrations (same specifier, same URI) to pass
477
+ * through silently.
478
+ */
479
+ getMappingUri(specifier) {
480
+ return _optionalChain([this, 'access', _ => _.importURICache, 'access', _2 => _2.get, 'call', _3 => _3(specifier), 'optionalAccess', _4 => _4.uri]);
481
+ }
482
+
475
483
  // Get URL from the local cache or return undefiend
476
484
  getURI(specifier) {
477
485
  return this.importURICache && this.importURICache.has(specifier)
@@ -569,7 +577,7 @@ class ImportMetadataResolver {
569
577
  }
570
578
 
571
579
  async fetchNewMappings(specifier) {
572
- if (!hasSetTimeout || !_optionalChain([this, 'access', _ => _.config, 'optionalAccess', _2 => _2.flags, 'optionalAccess', _3 => _3.batchMappings])) {
580
+ if (!hasSetTimeout || !_optionalChain([this, 'access', _5 => _5.config, 'optionalAccess', _6 => _6.flags, 'optionalAccess', _7 => _7.batchMappings])) {
573
581
  return this.fetchNewMappingsInner(specifier);
574
582
  }
575
583
 
@@ -1659,6 +1667,101 @@ function validateLoadSpecifier(
1659
1667
  }
1660
1668
  }
1661
1669
 
1670
+ /**
1671
+ * Ensures the update object key is a safe, loader-supported script URL (not a bare specifier).
1672
+ * Covers dangerous schemes and URL-key shape in one place.
1673
+ */
1674
+ function assertValidImportMapUrlKey(moduleScriptURL) {
1675
+ const lowerUri = moduleScriptURL.toLowerCase();
1676
+
1677
+ if (lowerUri.startsWith('blob:')) {
1678
+ throw new Error(`Cannot map ${moduleScriptURL} to blob: URL`);
1679
+ }
1680
+
1681
+ if (lowerUri.startsWith('data:')) {
1682
+ throw new Error(`Cannot map ${moduleScriptURL} to data: URL`);
1683
+ }
1684
+
1685
+ if (!/^[./]|^https?:/.test(moduleScriptURL)) {
1686
+ throw new Error(
1687
+ `LWR.importMap(): "${moduleScriptURL}" is not a valid URL key. Keys must be URL paths (e.g. "/path/to/module.js"), not module specifiers. Transitive specifier aliasing is not supported by this loader.`,
1688
+ );
1689
+ }
1690
+ }
1691
+
1692
+ /**
1693
+ * Validates an ImportMapUpdate and wraps it as ImportMetadata for the fingerprints loader.
1694
+ *
1695
+ * Does not apply legacy-style protected-specifier blocking; system modules are expected to be
1696
+ * defined at bootstrap, and `importMap` write-once semantics handle redundant runtime entries.
1697
+ *
1698
+ * Duplicate specifiers in the same update are de-duplicated silently (first occurrence wins).
1699
+ * An empty object is a silent no-op (returns null).
1700
+ */
1701
+ function validateAndWrapAsImportMetadata(update) {
1702
+ if (!update || typeof update !== 'object') {
1703
+ throw new Error('LWR.importMap() requires an object argument');
1704
+ }
1705
+
1706
+ const entries = Object.entries(update);
1707
+ if (entries.length === 0) {
1708
+ return null;
1709
+ }
1710
+
1711
+ const seenSpecifiers = new Set();
1712
+ const validatedImports = {};
1713
+
1714
+ for (const [moduleScriptURL, moduleNames] of entries) {
1715
+ if (!moduleScriptURL || typeof moduleScriptURL !== 'string') {
1716
+ throw new Error('moduleScriptURL must be a string');
1717
+ }
1718
+
1719
+ if (!Array.isArray(moduleNames)) {
1720
+ throw new Error('moduleNames must be an array');
1721
+ }
1722
+
1723
+ assertValidImportMapUrlKey(moduleScriptURL);
1724
+
1725
+ const validatedNames = [];
1726
+ for (const moduleName of moduleNames) {
1727
+ if (typeof moduleName !== 'string' || moduleName.length === 0) {
1728
+ throw new Error('Specifier must be a non-empty string');
1729
+ }
1730
+
1731
+ if (!seenSpecifiers.has(moduleName)) {
1732
+ seenSpecifiers.add(moduleName);
1733
+ validatedNames.push(moduleName);
1734
+ }
1735
+ }
1736
+
1737
+ if (validatedNames.length > 0) {
1738
+ validatedImports[moduleScriptURL] = validatedNames;
1739
+ }
1740
+ }
1741
+
1742
+ if (Object.keys(validatedImports).length === 0) {
1743
+ return null;
1744
+ }
1745
+
1746
+ return { imports: validatedImports };
1747
+ }
1748
+
1749
+ /**
1750
+ * Returns true when `update` carries the `ImportMetadata` shape (an `imports` object key),
1751
+ * signalling that it should be passed through to the resolver directly rather than treated
1752
+ * as a public-API `ImportMapUpdate`.
1753
+ */
1754
+ function isImportMetadata(update) {
1755
+ const candidate = update ;
1756
+ return (
1757
+ candidate !== null &&
1758
+ typeof candidate === 'object' &&
1759
+ 'imports' in candidate &&
1760
+ typeof candidate.imports === 'object' &&
1761
+ !Array.isArray(candidate.imports)
1762
+ );
1763
+ }
1764
+
1662
1765
  /**
1663
1766
  * The LWR loader is inspired and borrows from the algorithms and native browser principles of https://github.com/systemjs/systemjs
1664
1767
  */
@@ -1792,8 +1895,75 @@ class Loader {
1792
1895
  return this.registry.resolve(id, importer);
1793
1896
  }
1794
1897
 
1898
+ /**
1899
+ * Apply import map updates at runtime, or register bootstrap import mappings.
1900
+ *
1901
+ * **Runtime usage** (public API, consistent with `LWR.importMap()` on the legacy loader):
1902
+ * `importMap({ [moduleScriptURL]: [moduleName1, moduleName2, ...] })`
1903
+ * Validates the update and registers the new mappings dynamically.
1904
+ *
1905
+ * **Bootstrap / internal usage** (replaces `registerImportMappings`):
1906
+ * `importMap(importMetadata)` or `importMap(importMetadata, rootSpecifiers)`
1907
+ * Detected at runtime by the `ImportMetadata` shape (presence of an `imports` object).
1908
+ * This branch **does not** run `validateAndWrapAsImportMetadata` (URL-key checks /
1909
+ * runtime-payload dedupe). That is intentional: bootstrap must preserve
1910
+ * `index` fingerprints and use `ImportMetadataResolver.registerImportMappings` merge
1911
+ * semantics unchanged from the pre-`importMap` API.
1912
+ *
1913
+ * **Who may use this branch:** Platform/shim code with trusted config (see
1914
+ * `shim/shim.ts`, which calls `loader.importMap({ imports, index }, roots)`). The
1915
+ * public `LWR.importMap` wrapper only forwards the flat runtime update shape; any
1916
+ * code with a direct `Loader` reference could still pass an `ImportMetadata`-shaped
1917
+ * object — same trust boundary as calling `registerImportMappings` before.
1918
+ *
1919
+ * @param update - Runtime: `ImportMapUpdate` mapping script URLs to the module names they define.
1920
+ * Bootstrap: `ImportMetadata` with an `imports` object (and optional `index`).
1921
+ * @param rootSpecifiers - Bootstrap only: root module specifiers for the initial registration.
1922
+ * Optional — omit when the root specifiers are not known.
1923
+ */
1924
+ async importMap(update, rootSpecifiers) {
1925
+ if (isImportMetadata(update)) {
1926
+ this.registry.getImportMetadataResolver().registerImportMappings(update, rootSpecifiers);
1927
+ return;
1928
+ }
1929
+ const resolver = this.registry.getImportMetadataResolver();
1930
+ const importMetadata = validateAndWrapAsImportMetadata(update );
1931
+ if (!importMetadata) {
1932
+ return;
1933
+ }
1934
+
1935
+ const dedupedImports = {};
1936
+ for (const [uri, specifiers] of Object.entries(importMetadata.imports)) {
1937
+ const newSpecifiers = [];
1938
+ for (const specifier of specifiers) {
1939
+ const existingUri = resolver.getMappingUri(specifier);
1940
+ if (existingUri !== undefined) ; else {
1941
+ newSpecifiers.push(specifier);
1942
+ }
1943
+ }
1944
+ if (newSpecifiers.length > 0) {
1945
+ dedupedImports[uri] = newSpecifiers;
1946
+ }
1947
+ }
1948
+
1949
+ if (Object.keys(dedupedImports).length === 0) {
1950
+ return;
1951
+ }
1952
+
1953
+ const filtered = { imports: dedupedImports };
1954
+ const specs = Object.values(filtered.imports).flat();
1955
+ resolver.registerImportMappings(filtered, specs);
1956
+ }
1957
+
1958
+ /**
1959
+ * @deprecated Use `importMap(metadata, rootSpecifiers)` instead.
1960
+ */
1795
1961
  async registerImportMappings(mappings, rootSpecifiers) {
1796
- this.registry.getImportMetadataResolver().registerImportMappings(mappings, rootSpecifiers);
1962
+ if (hasConsole) {
1963
+ // eslint-disable-next-line lwr/no-unguarded-apis
1964
+ console.warn('registerImportMappings() is deprecated. Use importMap() instead.');
1965
+ }
1966
+ return this.importMap(mappings, rootSpecifiers);
1797
1967
  }
1798
1968
 
1799
1969
  /**
@@ -20,7 +20,14 @@ export declare class ImportMetadataResolver {
20
20
  getModifiersAsUrlParams(): string;
21
21
  buildMappingUrl(specifier: string): string;
22
22
  getBaseUrl(): string;
23
- registerImportMappings(newImportMetadata: ImportMetadata, rootSpecifiers: string[]): void;
23
+ registerImportMappings(newImportMetadata: ImportMetadata, rootSpecifiers?: string[]): void;
24
+ /**
25
+ * Returns the raw URI stored for a specifier, or `undefined` if not yet mapped.
26
+ * Used by the runtime `importMap()` path to detect cross-call duplicates while
27
+ * allowing truly idempotent re-registrations (same specifier, same URI) to pass
28
+ * through silently.
29
+ */
30
+ getMappingUri(specifier: string): string | undefined;
24
31
  private getURI;
25
32
  resolveLocal(specifier: string): string | undefined;
26
33
  /**