/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */
const FLAG_USE_REQUIRE_JS=1,FLAG_USE_IMPORTMAP=2,FLAG_USE_TOP_WINDOW=16,deniedProperties=["__proto__","prototype","constructor"],allowedJavaScriptItemTypes=["assign","invoke","instance"];let useShim=!1;const moduleImporter=e=>useShim?window.importShim(e):import(e).catch((()=>(useShim=!0,moduleImporter(e))));export function loadModule(e){if(!e.name)throw new Error("JavaScript module name is required");if((e.flags&FLAG_USE_IMPORTMAP)===FLAG_USE_IMPORTMAP){if(e.flags&FLAG_USE_TOP_WINDOW){const t=new CustomEvent("typo3:import-javascript-module",{detail:{specifier:e.name,importPromise:null}});return top.document.dispatchEvent(t),t.detail.importPromise||Promise.reject(new Error("Top-level import failed"))}return moduleImporter(e.name)}if((e.flags&FLAG_USE_REQUIRE_JS)===FLAG_USE_REQUIRE_JS)return new Promise(((t,r)=>{((e.flags&FLAG_USE_TOP_WINDOW)===FLAG_USE_TOP_WINDOW?top.window:window).require([e.name],(e=>t(e)),(e=>r(e)))}));throw new Error("Unknown JavaScript module type")}export function resolveSubjectRef(e,t){const r=t.exportName;return"string"==typeof r?e[r]:(t.flags&FLAG_USE_REQUIRE_JS)===FLAG_USE_REQUIRE_JS?e:e.default}export function executeJavaScriptModuleInstruction(e){if(!e.name)throw new Error("JavaScript module name is required");if(!e.items)return loadModule(e);const t=e.items.filter((e=>allowedJavaScriptItemTypes.includes(e.type))).map((t=>"assign"===t.type?r=>{mergeRecursive(resolveSubjectRef(r,e),t.assignments)}:"invoke"===t.type?r=>{const o=resolveSubjectRef(r,e);return"method"in t&&t.method?o[t.method](...t.args):o(...t.args)}:"instance"===t.type?r=>{const o=[null].concat(t.args);return new(resolveSubjectRef(r,e).bind(...o))}:()=>{}));return loadModule(e).then((e=>t.map((t=>t.call(null,e)))))}function isObjectInstance(e){return e instanceof Object&&!(e instanceof Array)}function mergeRecursive(e,t){Object.keys(t).forEach((r=>{if(-1!==deniedProperties.indexOf(r))throw new Error("Property "+r+" is not allowed");isObjectInstance(t[r])&&void 0!==e[r]?mergeRecursive(e[r],t[r]):Object.assign(e,{[r]:t[r]})}))}export class JavaScriptItemProcessor{constructor(){this.invokableNames=["globalAssignment","javaScriptModuleInstruction"]}processItems(e){e.forEach((e=>this.invoke(e.type,e.payload)))}invoke(e,t){if(!this.invokableNames.includes(e)||"function"!=typeof this[e])throw new Error('Unknown handler name "'+e+'"');this[e].call(this,t)}globalAssignment(e){mergeRecursive(window,e)}javaScriptModuleInstruction(e){executeJavaScriptModuleInstruction(e)}}