/* $Header$ */
// Contains the Omnis JavaScript worker module map
// Copyright (C) OLS Holdings Ltd 2018

/*********************************** Changes History **********************************
Date			Edit				Bug					Description
28-May-24	jmg_unmarked						Removed ignoreFolders, as new loading mechanism has no need for it.
21-May-24	jmg_unmarked						Converted omnis_test to an ES Module.
25-Apr-24	jmg1372		ST/AD/287		  JS Worker support for ES Modules.
17-May-23 caa2100b  ST/PF/1389    Lazy-load modules.
15-Apr-23	jmg1259		ST/JS/3247	  JS Worker now handles default error messages in the component, rather than sending with the response.
14-Apr-23 jmg1258                 Added 'ignoreFolders' array, and ignore node_modules folder by default.
16-Jan-23 caa2100a    ST/EC/1766  Do not lose information when automatically imported modules fail to import.
04-Dec-22	caa2100			ST/EC/1754	Automatically pick up user's modules.
28-Mar-19	jmg_unmarked						Updated to use local package for omnis_test.
11-Mar-19	jmg_unmarked						Simplified structure of this file + added error handling around missing module.
21-Nov-18	rmm_jsw									OW3 component - JavaScript Worker.
**************************************************************************************/

import { createRequire } from 'node:module'; // jmg1372
const require = createRequire(import.meta.url); // jmg1372


// Map of modules that can be called
// Each member of the object is a module name that can be used as the module parameter to $callmethod
let moduleMap = {
   test: await autoLoadModule('omnis_test'),
  //  another: await autoLoadModule('another') // Use autoLoadModule() to try loading any module format, anywhere on the module search path
};


// caa2100b start
async function autoLoadModule(moduleName) {
    
	try {
		const imported = await globalThis.loadModule(moduleName); // jmg1372
		return imported.default ? imported.default : imported; // jmg1372
	}
	catch (err) { return err; }
  
  
}
// caa2100b end

const omnis_modules = {
  call: async function (module, method, param, response) { // jmg1372
    if (!moduleMap[module]) moduleMap[module] = await autoLoadModule(module); // caa2100b // jmg1372
    // caa2100a start
    if (moduleMap[module] instanceof Error)
      throw new Error(
        `Error importing module ${module}:\n${moduleMap[module].message}`
      );
    else return moduleMap[module].call(method, param, response);
    // caa2100a end
  },
};

export default omnis_modules;