"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PluginDriver=void 0,exports.genResovleExtConf=genResovleExtConf,exports.getPluginContext=getPluginContext;const customError_1=require("../../../utils/customError"),workerThread_1=require("../original/workerThread"),worker_1=require("./worker"),debug_1=require("../../../utils/debug");function genResovleExtConf(r){const o={json:["json"],wxml:["wxml"],wxss:["wxss"],js:["js"],wxs:["wxs"]};for(const e of r)if(e.resolveExt)for(const r of["json","wxml","wxss","js","wxs"]){const t=e.resolveExt[r];if("string"==typeof t)o[r].includes(t)||o[r].push(t);else if(Array.isArray(t))for(const e of t)o[r].includes(e)||o[r].push(e)}return o}function throwPluginError(r,o,{hook:e,id:t}={}){const s=(0,customError_1.makeCustomError)(r);throw s.code||(s.code=customError_1.CustomErrors.SUMMER_PLUGIN_ERR),s.plugin=o,e&&(s.hook=e),t&&!s.path&&(s.path=t),r.stack&&(s.stack=r.stack),s}function getPluginContext(r,o){return{addWatchFile(){throw new Error("addWatchFile should be implemented by replaceContext")},async runWorkerMethod(e,...t){const s=await o.project.serialize(),n={command:"runMethod",plugin:r.name,projectInfo:s,pluginOption:{},method:e,args:t};let i;if(await(0,debug_1.shouldNotRunInWorker)())i=await(0,worker_1.runSummerPluginHook)(n);else try{i=await(0,workerThread_1.runTask)(workerThread_1.TASK_NAME.SUMMER_HOOK,n)}catch(r){throw r}if(i.error){if("CustomError"===i.error.type)throw new customError_1.CustomError(i.error);throw i.error}return i.result},error:o=>throwPluginError(o,r.name)}}class PluginDriver{constructor(r,o){this.graph=r,this.options=o,this.pluginContexts=new Map,this.plugins=o.plugins,this.resolveExtConf=genResovleExtConf(o.plugins);for(const o of this.plugins)this.pluginContexts.set(o,getPluginContext(o,r))}runHook(r,o,e,t){const s=e[r];if(!s)return;let n=this.pluginContexts.get(e);return t&&(n=t(n,e)),Promise.resolve().then(()=>s.apply(n,o)).catch(o=>throwPluginError(o,e.name,{hook:r}))}hookFirst(r,o,e){let t=Promise.resolve(void 0);for(const s of this.plugins)t=t.then(t=>t||this.runHook(r,o,s,e));return t}hookParallel(r,o,e){const t=[];for(const s of this.plugins){const n=this.runHook(r,o,s,e);n&&t.push(n)}return Promise.all(t).then(()=>{})}hookReduceArg0(r,[o,...e],t,s){let n=Promise.resolve(o);for(const o of this.plugins)n=n.then(n=>{const i=[n,...e],u=this.runHook(r,i,o,s);return u?u.then(r=>t.call(this.pluginContexts.get(o),n,r,o)):n});return n}}exports.PluginDriver=PluginDriver;