@lwrjs/loader 0.6.0-alpha.9 → 0.6.2
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/assets/prod/lwr-loader-shim-legacy.bundle.js +326 -218
- package/build/assets/prod/lwr-loader-shim-legacy.bundle.min.js +2 -2
- package/build/assets/prod/lwr-loader-shim-legacy.js +289 -213
- package/build/assets/prod/lwr-loader-shim.bundle.js +324 -258
- package/build/assets/prod/lwr-loader-shim.bundle.min.js +2 -2
- package/build/assets/prod/lwr-loader-shim.js +289 -246
- package/build/bundle/prod/lwr/esmLoader/esmLoader.js +1 -1
- package/build/cjs/modules/lwr/esmLoader/esmLoader.cjs +9 -6
- package/build/cjs/modules/lwr/esmLoader/importResolver.cjs +24 -3
- package/build/cjs/modules/lwr/loader/constants/constants.cjs +0 -10
- package/build/cjs/modules/lwr/loader/moduleRegistry/importMetadataResolver.cjs +4 -3
- package/build/cjs/modules/lwr/loader/moduleRegistry/moduleRegistry.cjs +8 -3
- package/build/cjs/modules/lwr/loaderLegacy/moduleRegistry/moduleRegistry.cjs +12 -2
- package/build/modules/lwr/esmLoader/esmLoader.js +38 -10
- package/build/modules/lwr/loader/loader.js +35 -12
- package/build/modules/lwr/loaderLegacy/loaderLegacy.js +37 -5
- package/package.json +12 -7
|
@@ -4,5 +4,5 @@
|
|
|
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.6.
|
|
8
|
-
!function(){"use strict";var e;let t;function r(e){t=e}!function(e){e[e.Start=0]="Start"}(e||(e={}));const o=void 0!==globalThis.performance&&"function"==typeof globalThis.performance.mark;function i({id:r,specifier:i}){t?t({id:r,phase:e.Start,specifier:i}):o&&globalThis.performance.mark(r+(i?`.${i}`:""))}function n(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 s="function"==typeof setTimeout,a="undefined"!=typeof console;const l=globalThis;l.LWR.requiredModules=l.LWR.requiredModules||[],l.LWR.requiredModules.indexOf("lwr/loader/v/0_6_0-alpha_9")<0&&l.LWR.requiredModules.push("lwr/loader/v/0_6_0-alpha_9"),new class{constructor(e){this.defineCache={},this.orderedDefs=[],this.global=e,this.config=e.LWR,this.loaderModule="lwr/loader/v/0_6_0-alpha_9",this.profiler=function(){return{logOperationStart:i.bind(this)}}();const t=this.tempDefine.bind(this);e.LWR.define=t,this.bootReady=this.config.autoBoot,s&&(this.watchdogTimerId=this.startWatchdogTimer());try{n(Object.freeze(this.config),this.postCustomInit.bind(this),t,(e=>{this.errorHandler=e}))}catch(e){this.enterErrorState(e)}}canInit(){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()&&(s&&clearTimeout(this.watchdogTimerId),this.initApp())}postCustomInit(){this.bootReady=!0,this.canInit()&&this.initApp()}initApp(){try{const e={endpoints:this.config.endpoints,baseUrl:this.config.baseUrl,profiler:this.profiler},t=function(e,t,r,o){if(!t||"function"!=typeof t[2])throw new Error(`Expected loader with specifier "${e}" to be a module`);const i={};t[2].call(null,i);const{Loader:n}=i,s=new n(r);return o&&o.length&&s.registerExternalModules(o),s.define(e,["exports"],(e=>{Object.assign(e,{define:s.define.bind(s),load:s.load.bind(s),services:s.services})})),s}(this.loaderModule,this.defineCache[this.loaderModule],e,this.config.preloadModules);this.mountApp(t)}catch(e){this.enterErrorState(e)}}waitForDOMContentLoaded(){return void 0===typeof document||"interactive"===document.readyState||"complete"===document.readyState?Promise.resolve():new Promise((e=>{document.addEventListener("DOMContentLoaded",(()=>{e()}))}))}mountApp(e){const{bootstrapModule:t,rootComponent:r,rootComponents:o,endpoints:i,imports:n,index:s}=this.config;this.global.LWR=Object.freeze({define:e.define.bind(e),rootComponent:r,rootComponents:o,endpoints:i,imports:n||{},index:s||{}}),this.orderedDefs.forEach((t=>{t!==this.loaderModule&&e.define(...this.defineCache[t])}));const{disableInitDefer:a}=this.config;e.registerImportMappings({imports:n,index:s},[t,r]).then((()=>{if(!a)return this.waitForDOMContentLoaded()})).then((()=>e.load(t))).then((()=>{this.profiler.logOperationStart({id:"lwr.bootstrap.end"})})).catch((e=>{this.enterErrorState(new Error(`Application ${r} could not be loaded: ${e}`))}))}enterErrorState(e){this.profiler.logOperationStart({id:"lwr.bootstrap.error"}),this.errorHandler?this.errorHandler(e):a&&console.error(`An error occurred during LWR bootstrap. ${e.message}`,e.stack)}startWatchdogTimer(){return setTimeout((()=>{this.enterErrorState(new Error("Failed to load required modules - timed out"))}),3e5)}}(l)}(),LWR.define("lwr/loader/v/0_6_0-alpha_9",["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}"}),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"}),MODULE_ALREADY_LOADED=Object.freeze({code:3017,level:0,message:"Marking module(s) as externally loaded, but they are already loaded: {0}"}),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}"});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;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.charset="utf-8",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)}}))}hasDocument&&window.addEventListener("error",(e=>{lastWindowErrorUrl=e.filename,lastWindowError$1=e.error}));const MODULE_LOAD_TIMEOUT_TIMER=3e5,METRIC_MODULE_DEFINE="lwr.loader.module.define",METRIC_MODULE_FETCH="lwr.loader.module.fetch",METRIC_MAPPINGS_FETCH="lwr.loader.mappings.fetch",METRIC_MODULE_ERROR="lwr.loader.module.error",METRIC_MAPPINGS_ERROR="lwr.loader.mappings.error";class ImportMetadataResolver{constructor(e,t){this.importURICache=new Map,this.pendingURICache=new Map,this.loadMappingHooks=[],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.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:METRIC_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 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("function"!=typeof globalThis.fetch)throw new LoaderError(UNRESOLVED,[e]);const t=resolveUrl(this.buildMappingUrl(e),this.getBaseUrl());return globalThis.fetch(t).then((t=>{if(!t.ok)throw this.config.profiler.logOperationStart({id:METRIC_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))}}}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.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,[id]);code=`${code}\n//# sourceURL=${id}`;try{eval(code)}catch(e){throw new LoaderError(FAIL_LOAD,[id])}if(lastWindowError)throw new LoaderError(FAIL_LOAD,[id]);return!0})).finally((()=>{}))}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})),!hasSetTimeout&&hasConsole&&console.warn("setTimeout API is not available, watchdog timer on load hook will not be set");class ModuleRegistry{constructor(e){this.namedDefineRegistry=new Map,this.moduleRegistry=new Map,this.profiler=e.profiler,this.resolver=new ImportMetadataResolver(e,this.importMetadataInvalidationCallback.bind(this))}async load(e,t){const r=await this.resolve(e,t),o=this.getModuleRecord(r,e);return o.evaluated?o.module:(o.evaluationPromise||(o.evaluationPromise=this.topLevelEvaluation(o)),o.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),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)&&this.namedDefineRegistry.get(t).defined){const e=this.moduleRegistry.get(i);if(!e||!e.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:METRIC_MODULE_DEFINE,specifier:e}),this.namedDefineRegistry.set(e,i),this.lastDefine=i}registerExternalModules(e){const t=[];if(e.map((e=>{if(this.namedDefineRegistry.has(e))t.push(e);else{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)}})),t.length)throw new LoaderError(MODULE_ALREADY_LOADED,[t.join(", ")])}getImportMetadataResolver(){return this.resolver}getModuleRecord(e,t){let r=this.moduleRegistry.get(e);if(r)return r.aliases.has(t)||r.aliases.add(t),r;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)}));return r={id:e,aliases:new Set([t]),module:Object.create(null),dependencyRecords:i,instantiation:o,evaluated:!1,evaluationPromise:null},this.moduleRegistry.set(e,r),r}async getModuleDependencyRecord(e){const t=await this.resolve(e);return this.getModuleRecord(t,e)}async topLevelEvaluation(e){return await this.instantiateAll(e,{}),this.evaluateModule(e,{})}async instantiateAll(e,t){if(!t[e.id]){t[e.id]=!0;const r=await e.dependencyRecords;if(r)for(let e=0;e<r.length;e++){const o=r[e];await this.instantiateAll(o,t)}}}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=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=o(...s);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}),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:METRIC_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||(o=this.lastDefine),!o)throw new LoaderError(FAIL_INSTANTIATE,[e]);return o})).catch((e=>{throw this.profiler.logOperationStart({id:METRIC_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}):hasConsole&&console.warn(`stale module detected ${e}, current URL:${t}, new URL:${r}`)}registerHandleStaleModuleHook(e){this.handleStaleModuleHook?this.handleStaleModuleHook.push(e):this.handleStaleModuleHook=[e]}}class Loader{constructor(e){let t=e.baseUrl;const r=e.endpoints?e.endpoints.uris.mapping:void 0;let o=e.profiler;if(!r)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);o||(o={logOperationStart:()=>{}}),this.registry=new ModuleRegistry(Object.freeze({endpoints:e.endpoints,baseUrl:t,profiler:o})),this.services=Object.freeze({addLoaderPlugin:this.registry.addLoaderPlugin.bind(this.registry),handleStaleModule:this.registry.registerHandleStaleModuleHook.bind(this.registry)})}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 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)}}exports.Loader=Loader,Object.defineProperty(exports,"__esModule",{value:!0})}));
|
|
7
|
+
/* LWR Module Loader Shim v0.6.2 */
|
|
8
|
+
!function(){"use strict";var e;let t;function r(e){t=e}!function(e){e[e.Start=0]="Start",e[e.End=1]="End"}(e||(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({id:r,specifier:n}){t?t({id:r,phase:e.Start,specifier:n}):i&&o.mark(r+(n?`.${n}`:""))}function s({id:r,specifier:n}){if(t)t({id:r,phase:e.End,specifier:n});else if(i){const e=n?`.${n}`:"",t=r+e,i=`${r}.duration${e}`;o.measure(i,t),o.clearMarks(t),o.clearMeasures(i)}}function a(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 l="function"==typeof setTimeout,d="undefined"!=typeof console;const c=globalThis;c.LWR.requiredModules=c.LWR.requiredModules||[],c.LWR.requiredModules.indexOf("lwr/loader/v/0_6_2")<0&&c.LWR.requiredModules.push("lwr/loader/v/0_6_2"),new class{constructor(e){this.defineCache={},this.orderedDefs=[],this.global=e,this.config=e.LWR,this.loaderSpecifier="lwr/loader/v/0_6_2";const t=this.tempDefine.bind(this);e.LWR.define=t,this.bootReady=this.config.autoBoot,l&&(this.watchdogTimerId=this.startWatchdogTimer());try{a(Object.freeze(this.config),this.postCustomInit.bind(this),t,(e=>{this.errorHandler=e}))}catch(e){this.enterErrorState(e)}}canInit(){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()&&(l&&clearTimeout(this.watchdogTimerId),this.initApp())}postCustomInit(){this.bootReady=!0,this.canInit()&&this.initApp()}initApp(){try{const e={endpoints:this.config.endpoints,baseUrl:this.config.baseUrl,profiler:{logOperationStart:n,logOperationEnd:s},appMetadata:{appId:this.config.appId,bootstrapModule:this.config.bootstrapModule,rootComponent:this.config.rootComponent,rootComponents:this.config.rootComponents}},t=function(e,t,r,o){if(!t||"function"!=typeof t[2])throw new Error(`Expected loader with specifier "${e}" to be a module`);const i={};t[2].call(null,i);const{Loader:n}=i,s=new n(r);return o&&o.length&&s.registerExternalModules(o),s.define(e,["exports"],(e=>{Object.assign(e,{define:s.define.bind(s),load:s.load.bind(s),services:s.services})})),s}(this.loaderSpecifier,this.defineCache[this.loaderSpecifier],e,this.config.preloadModules);this.createProfilerModule(t),this.mountApp(t)}catch(e){this.enterErrorState(e)}}waitForDOMContentLoaded(){return void 0===typeof document||"interactive"===document.readyState||"complete"===document.readyState?Promise.resolve():new Promise((e=>{document.addEventListener("DOMContentLoaded",(()=>{e()}))}))}createProfilerModule(e){e.define("lwr/profiler/v/0_6_2",["exports"],(e=>{Object.assign(e,{logOperationStart:n,logOperationEnd:s})}))}mountApp(e){const{bootstrapModule:t,rootComponent:r,rootComponents:o,endpoints:i,imports:n,index:s}=this.config;this.global.LWR=Object.freeze({define:e.define.bind(e),rootComponent:r,rootComponents:o,endpoints:i,imports:n||{},index:s||{}}),this.orderedDefs.forEach((t=>{t!==this.loaderSpecifier&&e.define(...this.defineCache[t])}));const{disableInitDefer:a}=this.config;e.registerImportMappings({imports:n,index:s},[t,r]).then((()=>{if(!a)return this.waitForDOMContentLoaded()})).then((()=>e.load(t))).catch((e=>{this.enterErrorState(new Error(`Application ${r} could not be loaded: ${e}`))}))}enterErrorState(e){n({id:"lwr.bootstrap.error"}),this.errorHandler?this.errorHandler(e):d&&console.error(`An error occurred during LWR bootstrap. ${e.message}`,e.stack)}startWatchdogTimer(){return setTimeout((()=>{this.enterErrorState(new Error("Failed to load required modules - timed out"))}),3e5)}}(c)}(),LWR.define("lwr/loader/v/0_6_2",["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}"}),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"}),MODULE_ALREADY_LOADED=Object.freeze({code:3017,level:0,message:"Marking module(s) as externally loaded, but they are already loaded: {0}"}),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}"});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;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.charset="utf-8",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)}}))}hasDocument&&window.addEventListener("error",(e=>{lastWindowErrorUrl=e.filename,lastWindowError$1=e.error}));const LOADER_PREFIX="lwr.loader.",MODULE_DEFINE=`${LOADER_PREFIX}module.define`,MODULE_FETCH=`${LOADER_PREFIX}module.fetch`,MODULE_ERROR=`${LOADER_PREFIX}module.error`,MAPPINGS_FETCH=`${LOADER_PREFIX}mappings.fetch`,MAPPINGS_ERROR=`${LOADER_PREFIX}mappings.error`;class ImportMetadataResolver{constructor(e,t){this.importURICache=new Map,this.pendingURICache=new Map,this.loadMappingHooks=[],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.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("function"!=typeof globalThis.fetch)throw new LoaderError(UNRESOLVED,[e]);const t=resolveUrl(this.buildMappingUrl(e),this.getBaseUrl());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=3e5;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.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,[id]);code=`${code}\n//# sourceURL=${id}`;try{eval(code)}catch(e){throw new LoaderError(FAIL_LOAD,[id])}if(lastWindowError)throw new LoaderError(FAIL_LOAD,[id]);return!0})).finally((()=>{}))}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})),!hasSetTimeout&&hasConsole&&console.warn("setTimeout API is not available, watchdog timer on load hook will not be set");class ModuleRegistry{constructor(e){this.namedDefineRegistry=new Map,this.moduleRegistry=new Map,this.profiler=e.profiler,this.resolver=new ImportMetadataResolver(e,this.importMetadataInvalidationCallback.bind(this))}async load(e,t){const r=await this.resolve(e,t),o=this.getModuleRecord(r,e);return o.evaluated?o.module:(o.evaluationPromise||(o.evaluationPromise=this.topLevelEvaluation(o)),o.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),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)&&this.namedDefineRegistry.get(t).defined){const e=this.moduleRegistry.get(i);if(!e||!e.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){const t=[];if(e.map((e=>{if(this.namedDefineRegistry.has(e))t.push(e);else{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)}})),t.length)throw new LoaderError(MODULE_ALREADY_LOADED,[t.join(", ")])}getImportMetadataResolver(){return this.resolver}getModuleRecord(e,t){let r=this.moduleRegistry.get(e);if(r)return r.aliases.has(t)||r.aliases.add(t),r;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)}));return r={id:e,aliases:new Set([t]),module:Object.create(null),dependencyRecords:i,instantiation:o,evaluated:!1,evaluationPromise:null},this.moduleRegistry.set(e,r),r}async getModuleDependencyRecord(e){const t=await this.resolve(e);return this.getModuleRecord(t,e)}async topLevelEvaluation(e){return await this.instantiateAll(e,{}),this.evaluateModule(e,{})}async instantiateAll(e,t){if(!t[e.id]){t[e.id]=!0;const r=await e.dependencyRecords;if(r)for(let e=0;e<r.length;e++){const o=r[e];await this.instantiateAll(o,t)}}}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=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=o(...s);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||(o=this.lastDefine),!o)throw new LoaderError(FAIL_INSTANTIATE,[e]);return this.profiler.logOperationEnd({id:MODULE_FETCH,specifier:n}),o})).catch((e=>{throw 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}):hasConsole&&console.warn(`stale module detected ${e}, current URL:${t}, new URL:${r}`)}registerHandleStaleModuleHook(e){this.handleStaleModuleHook?this.handleStaleModuleHook.push(e):this.handleStaleModuleHook=[e]}}class Loader{constructor(e){let t=e.baseUrl;const r=e.endpoints?e.endpoints.uris.mapping:void 0;let o=e.profiler;if(!r)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})),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 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)}}exports.Loader=Loader,Object.defineProperty(exports,"__esModule",{value:!0})}));
|
|
@@ -4,260 +4,303 @@
|
|
|
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.6.
|
|
7
|
+
/* LWR Module Loader Shim v0.6.2 */
|
|
8
8
|
(function () {
|
|
9
|
-
|
|
9
|
+
'use strict';
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
}
|
|
15
|
-
// Create a Loader instance
|
|
16
|
-
const exports = {};
|
|
17
|
-
definition[2].call(null, exports);
|
|
18
|
-
const { Loader } = exports;
|
|
19
|
-
const loader = new Loader(config);
|
|
20
|
-
if (externalModules && externalModules.length) {
|
|
21
|
-
loader.registerExternalModules(externalModules);
|
|
22
|
-
}
|
|
23
|
-
// Define the loader module with public API: { define, load, services }
|
|
24
|
-
const exporter = (exports) => {
|
|
25
|
-
Object.assign(exports, {
|
|
26
|
-
define: loader.define.bind(loader),
|
|
27
|
-
load: loader.load.bind(loader),
|
|
28
|
-
services: loader.services,
|
|
29
|
-
});
|
|
30
|
-
return;
|
|
31
|
-
};
|
|
32
|
-
loader.define(name, ['exports'], exporter);
|
|
33
|
-
return loader;
|
|
34
|
-
}
|
|
11
|
+
// Bootstrap / shim
|
|
12
|
+
const BOOTSTRAP_PREFIX = 'lwr.bootstrap.';
|
|
13
|
+
const BOOTSTRAP_ERROR = `${BOOTSTRAP_PREFIX}error`;
|
|
35
14
|
|
|
36
|
-
|
|
37
|
-
const METRIC_END = 'lwr.bootstrap.end';
|
|
38
|
-
const METRIC_ERROR = 'lwr.bootstrap.error';
|
|
15
|
+
var Phase;
|
|
39
16
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
// Attach a custom dispatcher
|
|
45
|
-
let customDispatcher;
|
|
46
|
-
function attachDispatcher(dispatcher) {
|
|
47
|
-
customDispatcher = dispatcher;
|
|
48
|
-
}
|
|
49
|
-
// Check if the Performance API is available
|
|
50
|
-
// e.g. JSDom (used in Jest) doesn't implement these
|
|
51
|
-
const isPerfSupported = typeof globalThis.performance !== 'undefined' && typeof globalThis.performance.mark === 'function';
|
|
52
|
-
// For marking request metrics
|
|
53
|
-
// Fallback to the Performance API if there is no custom dispatcher
|
|
54
|
-
function logOperationStart({ id, specifier }) {
|
|
55
|
-
if (customDispatcher) {
|
|
56
|
-
customDispatcher({ id, phase: Phase.Start, specifier });
|
|
57
|
-
}
|
|
58
|
-
else if (isPerfSupported) {
|
|
59
|
-
globalThis.performance.mark(id + (specifier ? `.${specifier}` : ''));
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
function getProfilerAPI() {
|
|
63
|
-
// Create the public Profiler API
|
|
64
|
-
return { logOperationStart: logOperationStart.bind(this) };
|
|
65
|
-
}
|
|
17
|
+
(function (Phase) {
|
|
18
|
+
Phase[Phase["Start"] = 0] = "Start";
|
|
19
|
+
Phase[Phase["End"] = 1] = "End";
|
|
20
|
+
})(Phase || (Phase = {}));
|
|
66
21
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
}
|
|
78
|
-
// Process the customInit hook
|
|
79
|
-
function customInit(config, initializeApp, define, onBootstrapError) {
|
|
80
|
-
// Validate config
|
|
81
|
-
const { autoBoot, customInit } = config;
|
|
82
|
-
validatePreInit(autoBoot, customInit);
|
|
83
|
-
// Set up arguments and call the customInit hook, if available
|
|
84
|
-
if (customInit) {
|
|
85
|
-
const lwr = {
|
|
86
|
-
initializeApp,
|
|
87
|
-
define,
|
|
88
|
-
onBootstrapError,
|
|
89
|
-
attachDispatcher,
|
|
90
|
-
};
|
|
91
|
-
customInit(lwr, config);
|
|
92
|
-
}
|
|
93
|
-
}
|
|
22
|
+
// Attach a custom dispatcher
|
|
23
|
+
let customDispatcher;
|
|
24
|
+
function attachDispatcher(dispatcher) {
|
|
25
|
+
customDispatcher = dispatcher;
|
|
26
|
+
} // Check if the Performance API is available
|
|
27
|
+
// e.g. JSDom (used in Jest) doesn't implement these
|
|
28
|
+
|
|
29
|
+
const perf = globalThis.performance;
|
|
30
|
+
const isPerfSupported = typeof perf !== 'undefined' && typeof perf.mark === 'function' && typeof perf.clearMarks === 'function' && typeof perf.measure === 'function' && typeof perf.clearMeasures === 'function'; // For marking request metrics
|
|
31
|
+
// Fallback to the Performance API if there is no custom dispatcher
|
|
94
32
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
this.loaderModule = 'lwr/loader/v/0_6_0-alpha_9';
|
|
108
|
-
// Set up the profiler for instrumentation
|
|
109
|
-
this.profiler = getProfilerAPI();
|
|
110
|
-
// Set up the temporary LWR.define function and customInit hook
|
|
111
|
-
const tempDefine = this.tempDefine.bind(this);
|
|
112
|
-
global.LWR.define = tempDefine;
|
|
113
|
-
this.bootReady = this.config.autoBoot;
|
|
114
|
-
// Start watchdog timer
|
|
115
|
-
if (hasSetTimeout) {
|
|
116
|
-
this.watchdogTimerId = this.startWatchdogTimer();
|
|
117
|
-
}
|
|
118
|
-
try {
|
|
119
|
-
customInit(Object.freeze(this.config), this.postCustomInit.bind(this), tempDefine, (e) => {
|
|
120
|
-
this.errorHandler = e;
|
|
121
|
-
});
|
|
122
|
-
}
|
|
123
|
-
catch (e) {
|
|
124
|
-
this.enterErrorState(e);
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
// Return true if the app can be initialized
|
|
128
|
-
canInit() {
|
|
129
|
-
// Initialize the app if:
|
|
130
|
-
// - bootReady: autoBoot is on OR customInit has finished
|
|
131
|
-
// - all required modules are defined
|
|
132
|
-
const allDefined = this.config.requiredModules.every((m) => this.orderedDefs.includes(m));
|
|
133
|
-
return this.bootReady && allDefined;
|
|
134
|
-
}
|
|
135
|
-
/**
|
|
136
|
-
* Create a temporary LWR.define() function which captures all
|
|
137
|
-
* calls that occur BEFORE the full loader module is available
|
|
138
|
-
*
|
|
139
|
-
* Each call to LWR.define() is stored in 2 ways:
|
|
140
|
-
* - in a map as [moduleName, arguments] pairs
|
|
141
|
-
* - each moduleName is pushed onto an array, to preserve
|
|
142
|
-
* the order in which the modules were defined
|
|
143
|
-
*/
|
|
144
|
-
tempDefine(...args) {
|
|
145
|
-
// Cache the incoming module
|
|
146
|
-
const moduleName = args[0];
|
|
147
|
-
this.defineCache[moduleName] = args;
|
|
148
|
-
this.orderedDefs.push(moduleName);
|
|
149
|
-
if (this.canInit()) {
|
|
150
|
-
if (hasSetTimeout) {
|
|
151
|
-
// requiredModules are defined, clear watchdog timer
|
|
152
|
-
// eslint-disable-next-line lwr/no-unguarded-apis, no-undef
|
|
153
|
-
clearTimeout(this.watchdogTimerId);
|
|
154
|
-
}
|
|
155
|
-
this.initApp();
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
// Called by the customInit hook via lwr.initializeApp()
|
|
159
|
-
postCustomInit() {
|
|
160
|
-
this.bootReady = true;
|
|
161
|
-
if (this.canInit()) {
|
|
162
|
-
this.initApp();
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
// Create the loader and initialize the application
|
|
166
|
-
initApp() {
|
|
167
|
-
try {
|
|
168
|
-
const loaderConfig = {
|
|
169
|
-
endpoints: this.config.endpoints,
|
|
170
|
-
baseUrl: this.config.baseUrl,
|
|
171
|
-
profiler: this.profiler,
|
|
172
|
-
};
|
|
173
|
-
const loader = createLoader(this.loaderModule, this.defineCache[this.loaderModule], loaderConfig, this.config.preloadModules);
|
|
174
|
-
this.mountApp(loader);
|
|
175
|
-
}
|
|
176
|
-
catch (e) {
|
|
177
|
-
this.enterErrorState(e);
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
waitForDOMContentLoaded() {
|
|
181
|
-
// eslint-disable-next-line lwr/no-unguarded-apis
|
|
182
|
-
if (typeof document === undefined) {
|
|
183
|
-
return Promise.resolve();
|
|
184
|
-
}
|
|
185
|
-
// Resolve if document is already "ready" https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState
|
|
186
|
-
// eslint-disable-next-line lwr/no-unguarded-apis
|
|
187
|
-
if (document.readyState === 'interactive' || document.readyState === 'complete') {
|
|
188
|
-
return Promise.resolve();
|
|
189
|
-
}
|
|
190
|
-
return new Promise((resolve) => {
|
|
191
|
-
// eslint-disable-next-line lwr/no-unguarded-apis
|
|
192
|
-
document.addEventListener('DOMContentLoaded', () => {
|
|
193
|
-
resolve();
|
|
194
|
-
});
|
|
195
|
-
});
|
|
196
|
-
}
|
|
197
|
-
// Set up the application globals, import map, root custom element...
|
|
198
|
-
mountApp(loader) {
|
|
199
|
-
const { bootstrapModule, rootComponent, rootComponents, endpoints, imports, index } = this.config;
|
|
200
|
-
// Set global LWR.define to loader.define
|
|
201
|
-
this.global.LWR = Object.freeze({
|
|
202
|
-
define: loader.define.bind(loader),
|
|
203
|
-
rootComponent,
|
|
204
|
-
rootComponents,
|
|
205
|
-
endpoints,
|
|
206
|
-
imports: imports || {},
|
|
207
|
-
index: index || {},
|
|
208
|
-
});
|
|
209
|
-
// Redefine all modules in the temporary cache
|
|
210
|
-
this.orderedDefs.forEach((specifier) => {
|
|
211
|
-
if (specifier !== this.loaderModule) {
|
|
212
|
-
loader.define(...this.defineCache[specifier]);
|
|
213
|
-
}
|
|
214
|
-
});
|
|
215
|
-
// by default, app initialization is gated on waiting for document to be parsed (via DOMContentLoaded)
|
|
216
|
-
const { disableInitDefer } = this.config;
|
|
217
|
-
// Load the import mappings and application bootstrap module
|
|
218
|
-
loader
|
|
219
|
-
.registerImportMappings({ imports, index }, [bootstrapModule, rootComponent])
|
|
220
|
-
.then(() => {
|
|
221
|
-
if (!disableInitDefer) {
|
|
222
|
-
return this.waitForDOMContentLoaded();
|
|
223
|
-
}
|
|
224
|
-
})
|
|
225
|
-
.then(() => loader.load(bootstrapModule))
|
|
226
|
-
.then(() => {
|
|
227
|
-
this.profiler.logOperationStart({ id: METRIC_END });
|
|
228
|
-
})
|
|
229
|
-
.catch((reason) => {
|
|
230
|
-
this.enterErrorState(new Error(`Application ${rootComponent} could not be loaded: ${reason}`));
|
|
231
|
-
});
|
|
232
|
-
}
|
|
233
|
-
// Trigger bootstrap error state, and call error handler if registered
|
|
234
|
-
enterErrorState(error) {
|
|
235
|
-
this.profiler.logOperationStart({ id: METRIC_ERROR });
|
|
236
|
-
if (this.errorHandler) {
|
|
237
|
-
this.errorHandler(error);
|
|
238
|
-
}
|
|
239
|
-
else {
|
|
240
|
-
if (hasConsole) {
|
|
241
|
-
// eslint-disable-next-line lwr/no-unguarded-apis, no-undef
|
|
242
|
-
console.error(`An error occurred during LWR bootstrap. ${error.message}`, error.stack);
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
// eslint-disable-next-line no-undef, lwr/no-unguarded-apis
|
|
247
|
-
startWatchdogTimer() {
|
|
248
|
-
// eslint-disable-next-line lwr/no-unguarded-apis, no-undef
|
|
249
|
-
return setTimeout(() => {
|
|
250
|
-
this.enterErrorState(new Error('Failed to load required modules - timed out'));
|
|
251
|
-
}, REQUIRED_MODULES_TIMEOUT);
|
|
252
|
-
}
|
|
33
|
+
function logOperationStart({
|
|
34
|
+
id,
|
|
35
|
+
specifier
|
|
36
|
+
}) {
|
|
37
|
+
if (customDispatcher) {
|
|
38
|
+
customDispatcher({
|
|
39
|
+
id,
|
|
40
|
+
phase: Phase.Start,
|
|
41
|
+
specifier
|
|
42
|
+
});
|
|
43
|
+
} else if (isPerfSupported) {
|
|
44
|
+
perf.mark(id + (specifier ? `.${specifier}` : ''));
|
|
253
45
|
}
|
|
46
|
+
} // For measuring duration metrics
|
|
47
|
+
// Fallback to the Performance API if there is no custom dispatcher
|
|
254
48
|
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
49
|
+
/* istanbul ignore next */
|
|
50
|
+
|
|
51
|
+
function logOperationEnd({
|
|
52
|
+
id,
|
|
53
|
+
specifier
|
|
54
|
+
}) {
|
|
55
|
+
if (customDispatcher) {
|
|
56
|
+
customDispatcher({
|
|
57
|
+
id,
|
|
58
|
+
phase: Phase.End,
|
|
59
|
+
specifier
|
|
60
|
+
});
|
|
61
|
+
} else if (isPerfSupported) {
|
|
62
|
+
const suffix = specifier ? `.${specifier}` : '';
|
|
63
|
+
const markName = id + suffix;
|
|
64
|
+
const measureName = `${id}.duration${suffix}`;
|
|
65
|
+
perf.measure(measureName, markName); // Clear the created mark and measure to avoid filling the performance entry buffer
|
|
66
|
+
// Even if they get deleted, existing PerformanceObservers preserve copies of the entries
|
|
67
|
+
|
|
68
|
+
perf.clearMarks(markName);
|
|
69
|
+
perf.clearMeasures(measureName);
|
|
260
70
|
}
|
|
261
|
-
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function createLoader(name, definition, config, externalModules) {
|
|
74
|
+
if (!definition || typeof definition[2] !== 'function') {
|
|
75
|
+
throw new Error(`Expected loader with specifier "${name}" to be a module`);
|
|
76
|
+
}
|
|
77
|
+
// Create a Loader instance
|
|
78
|
+
const exports = {};
|
|
79
|
+
definition[2].call(null, exports);
|
|
80
|
+
const { Loader } = exports;
|
|
81
|
+
const loader = new Loader(config);
|
|
82
|
+
if (externalModules && externalModules.length) {
|
|
83
|
+
loader.registerExternalModules(externalModules);
|
|
84
|
+
}
|
|
85
|
+
// Define the loader module with public API: { define, load, services }
|
|
86
|
+
const exporter = (exports) => {
|
|
87
|
+
Object.assign(exports, {
|
|
88
|
+
define: loader.define.bind(loader),
|
|
89
|
+
load: loader.load.bind(loader),
|
|
90
|
+
services: loader.services,
|
|
91
|
+
});
|
|
92
|
+
};
|
|
93
|
+
loader.define(name, ['exports'], exporter);
|
|
94
|
+
return loader;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const REQUIRED_MODULES_TIMEOUT = 300 * 1000;
|
|
98
|
+
|
|
99
|
+
// Check for errors with autoBoot and customInit
|
|
100
|
+
function validatePreInit(autoBoot, customInit) {
|
|
101
|
+
// If autoBoot === false, there must be a customInit hook
|
|
102
|
+
if (!autoBoot && !customInit) {
|
|
103
|
+
throw new Error('The customInit hook is required when autoBoot is false');
|
|
104
|
+
}
|
|
105
|
+
// If autoBoot === true, there must NOT be a customInit hook
|
|
106
|
+
if (autoBoot && customInit) {
|
|
107
|
+
throw new Error('The customInit hook must not be defined when autoBoot is true');
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
// Process the customInit hook
|
|
111
|
+
function customInit(config, initializeApp, define, onBootstrapError) {
|
|
112
|
+
// Validate config
|
|
113
|
+
const { autoBoot, customInit } = config;
|
|
114
|
+
validatePreInit(autoBoot, customInit);
|
|
115
|
+
// Set up arguments and call the customInit hook, if available
|
|
116
|
+
if (customInit) {
|
|
117
|
+
const lwr = {
|
|
118
|
+
initializeApp,
|
|
119
|
+
define,
|
|
120
|
+
onBootstrapError,
|
|
121
|
+
attachDispatcher,
|
|
122
|
+
};
|
|
123
|
+
customInit(lwr, config);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/* global document */
|
|
128
|
+
/* eslint-disable lwr/no-unguarded-apis */
|
|
129
|
+
const hasSetTimeout = typeof setTimeout === 'function';
|
|
130
|
+
const hasConsole = typeof console !== 'undefined';
|
|
131
|
+
/* eslint-enable lwr/no-unguarded-apis */
|
|
132
|
+
class LoaderShim {
|
|
133
|
+
constructor(global) {
|
|
134
|
+
this.defineCache = {};
|
|
135
|
+
this.orderedDefs = [];
|
|
136
|
+
// Parse configuration
|
|
137
|
+
this.global = global;
|
|
138
|
+
this.config = global.LWR;
|
|
139
|
+
this.loaderSpecifier = 'lwr/loader/v/0_6_2';
|
|
140
|
+
// Set up the temporary LWR.define function and customInit hook
|
|
141
|
+
const tempDefine = this.tempDefine.bind(this);
|
|
142
|
+
global.LWR.define = tempDefine;
|
|
143
|
+
this.bootReady = this.config.autoBoot;
|
|
144
|
+
// Start watchdog timer
|
|
145
|
+
if (hasSetTimeout) {
|
|
146
|
+
this.watchdogTimerId = this.startWatchdogTimer();
|
|
147
|
+
}
|
|
148
|
+
try {
|
|
149
|
+
customInit(Object.freeze(this.config), this.postCustomInit.bind(this), tempDefine, (e) => {
|
|
150
|
+
this.errorHandler = e;
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
catch (e) {
|
|
154
|
+
this.enterErrorState(e);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
// Return true if the app can be initialized
|
|
158
|
+
canInit() {
|
|
159
|
+
// Initialize the app if:
|
|
160
|
+
// - bootReady: autoBoot is on OR customInit has finished
|
|
161
|
+
// - all required modules are defined
|
|
162
|
+
const allDefined = this.config.requiredModules.every((m) => this.orderedDefs.includes(m));
|
|
163
|
+
return this.bootReady && allDefined;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Create a temporary LWR.define() function which captures all
|
|
167
|
+
* calls that occur BEFORE the full loader module is available
|
|
168
|
+
*
|
|
169
|
+
* Each call to LWR.define() is stored in 2 ways:
|
|
170
|
+
* - in a map as [moduleName, arguments] pairs
|
|
171
|
+
* - each moduleName is pushed onto an array, to preserve
|
|
172
|
+
* the order in which the modules were defined
|
|
173
|
+
*/
|
|
174
|
+
tempDefine(...args) {
|
|
175
|
+
// Cache the incoming module
|
|
176
|
+
const moduleName = args[0];
|
|
177
|
+
this.defineCache[moduleName] = args;
|
|
178
|
+
this.orderedDefs.push(moduleName);
|
|
179
|
+
if (this.canInit()) {
|
|
180
|
+
if (hasSetTimeout) {
|
|
181
|
+
// requiredModules are defined, clear watchdog timer
|
|
182
|
+
// eslint-disable-next-line lwr/no-unguarded-apis, no-undef
|
|
183
|
+
clearTimeout(this.watchdogTimerId);
|
|
184
|
+
}
|
|
185
|
+
this.initApp();
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
// Called by the customInit hook via lwr.initializeApp()
|
|
189
|
+
postCustomInit() {
|
|
190
|
+
this.bootReady = true;
|
|
191
|
+
if (this.canInit()) {
|
|
192
|
+
this.initApp();
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
// Create the loader and initialize the application
|
|
196
|
+
initApp() {
|
|
197
|
+
try {
|
|
198
|
+
const loaderConfig = {
|
|
199
|
+
endpoints: this.config.endpoints,
|
|
200
|
+
baseUrl: this.config.baseUrl,
|
|
201
|
+
profiler: { logOperationStart, logOperationEnd },
|
|
202
|
+
// TODO: can be removed following https://github.com/salesforce/lwr/issues/1087
|
|
203
|
+
appMetadata: {
|
|
204
|
+
appId: this.config.appId,
|
|
205
|
+
bootstrapModule: this.config.bootstrapModule,
|
|
206
|
+
rootComponent: this.config.rootComponent,
|
|
207
|
+
rootComponents: this.config.rootComponents,
|
|
208
|
+
},
|
|
209
|
+
};
|
|
210
|
+
const loader = createLoader(this.loaderSpecifier, this.defineCache[this.loaderSpecifier], loaderConfig, this.config.preloadModules);
|
|
211
|
+
this.createProfilerModule(loader);
|
|
212
|
+
this.mountApp(loader);
|
|
213
|
+
}
|
|
214
|
+
catch (e) {
|
|
215
|
+
this.enterErrorState(e);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
waitForDOMContentLoaded() {
|
|
219
|
+
// eslint-disable-next-line lwr/no-unguarded-apis
|
|
220
|
+
if (typeof document === undefined) {
|
|
221
|
+
return Promise.resolve();
|
|
222
|
+
}
|
|
223
|
+
// Resolve if document is already "ready" https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState
|
|
224
|
+
// eslint-disable-next-line lwr/no-unguarded-apis
|
|
225
|
+
if (document.readyState === 'interactive' || document.readyState === 'complete') {
|
|
226
|
+
return Promise.resolve();
|
|
227
|
+
}
|
|
228
|
+
return new Promise((resolve) => {
|
|
229
|
+
// eslint-disable-next-line lwr/no-unguarded-apis
|
|
230
|
+
document.addEventListener('DOMContentLoaded', () => {
|
|
231
|
+
resolve();
|
|
232
|
+
});
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
// Create a module out of the profiler
|
|
236
|
+
// Note: The profiler is also available as a module through lwc module resolution (see package.json)
|
|
237
|
+
createProfilerModule(loader) {
|
|
238
|
+
const exporter = (exports) => {
|
|
239
|
+
Object.assign(exports, { logOperationStart, logOperationEnd });
|
|
240
|
+
};
|
|
241
|
+
loader.define('lwr/profiler/v/0_6_2', ['exports'], exporter);
|
|
242
|
+
}
|
|
243
|
+
// Set up the application globals, import map, root custom element...
|
|
244
|
+
mountApp(loader) {
|
|
245
|
+
const { bootstrapModule, rootComponent, rootComponents, endpoints, imports, index } = this.config;
|
|
246
|
+
// Set global LWR.define to loader.define
|
|
247
|
+
this.global.LWR = Object.freeze({
|
|
248
|
+
define: loader.define.bind(loader),
|
|
249
|
+
rootComponent,
|
|
250
|
+
rootComponents,
|
|
251
|
+
endpoints,
|
|
252
|
+
imports: imports || {},
|
|
253
|
+
index: index || {},
|
|
254
|
+
});
|
|
255
|
+
// Redefine all modules in the temporary cache
|
|
256
|
+
this.orderedDefs.forEach((specifier) => {
|
|
257
|
+
if (specifier !== this.loaderSpecifier) {
|
|
258
|
+
loader.define(...this.defineCache[specifier]);
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
// by default, app initialization is gated on waiting for document to be parsed (via DOMContentLoaded)
|
|
262
|
+
const { disableInitDefer } = this.config;
|
|
263
|
+
// Load the import mappings and application bootstrap module
|
|
264
|
+
loader
|
|
265
|
+
.registerImportMappings({ imports, index }, [bootstrapModule, rootComponent])
|
|
266
|
+
.then(() => {
|
|
267
|
+
if (!disableInitDefer) {
|
|
268
|
+
return this.waitForDOMContentLoaded();
|
|
269
|
+
}
|
|
270
|
+
})
|
|
271
|
+
.then(() => loader.load(bootstrapModule))
|
|
272
|
+
.catch((reason) => {
|
|
273
|
+
this.enterErrorState(new Error(`Application ${rootComponent} could not be loaded: ${reason}`));
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
// Trigger bootstrap error state, and call error handler if registered
|
|
277
|
+
enterErrorState(error) {
|
|
278
|
+
logOperationStart({ id: BOOTSTRAP_ERROR });
|
|
279
|
+
if (this.errorHandler) {
|
|
280
|
+
this.errorHandler(error);
|
|
281
|
+
}
|
|
282
|
+
else {
|
|
283
|
+
if (hasConsole) {
|
|
284
|
+
// eslint-disable-next-line lwr/no-unguarded-apis, no-undef
|
|
285
|
+
console.error(`An error occurred during LWR bootstrap. ${error.message}`, error.stack);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
// eslint-disable-next-line no-undef, lwr/no-unguarded-apis
|
|
290
|
+
startWatchdogTimer() {
|
|
291
|
+
// eslint-disable-next-line lwr/no-unguarded-apis, no-undef
|
|
292
|
+
return setTimeout(() => {
|
|
293
|
+
this.enterErrorState(new Error('Failed to load required modules - timed out'));
|
|
294
|
+
}, REQUIRED_MODULES_TIMEOUT);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// The loader module is ALWAYS required
|
|
299
|
+
const GLOBAL = globalThis;
|
|
300
|
+
GLOBAL.LWR.requiredModules = GLOBAL.LWR.requiredModules || [];
|
|
301
|
+
if (GLOBAL.LWR.requiredModules.indexOf('lwr/loader/v/0_6_2') < 0) {
|
|
302
|
+
GLOBAL.LWR.requiredModules.push('lwr/loader/v/0_6_2');
|
|
303
|
+
}
|
|
304
|
+
new LoaderShim(GLOBAL);
|
|
262
305
|
|
|
263
306
|
}());
|