@pact-toolbox/unplugin
Version:
241 lines (239 loc) • 8.36 kB
JavaScript
const require_chunk = require('./chunk-CUT6urMc.cjs');
const require_utils = require('./utils-DOhsgEZO.cjs');
const require_pactToJS = require('./pactToJS-CT_lR0T8.cjs');
const __pact_toolbox_config = require_chunk.__toESM(require("@pact-toolbox/config"));
const __pact_toolbox_runtime = require_chunk.__toESM(require("@pact-toolbox/runtime"));
const __pact_toolbox_utils = require_chunk.__toESM(require("@pact-toolbox/utils"));
const unplugin = require_chunk.__toESM(require("unplugin"));
const node_path = require_chunk.__toESM(require("node:path"));
//#region src/plugin/factory.ts
/**
* Factory function to create the Vite plugin.
* @param options Plugin options including transformation hooks.
* @returns An instance of the Unplugin.
*/
const unpluginFactory = (options = {}) => {
const { startNetwork = true } = options;
const cache = /* @__PURE__ */ new Map();
const toolboxConfigPromise = (0, __pact_toolbox_config.resolveConfig)();
let resolvedConfig;
let networkConfig;
let client = options.client;
let network = null;
let isTest = process.env.NODE_ENV === "test";
let isServe = false;
const deploySpinner = (0, __pact_toolbox_utils.spinner)({ indicator: "dots" });
const transformPactToJS = require_pactToJS.createPactToJSTransformer();
/**
* Asynchronous function to handle server configuration.
*/
const configureServer = async () => {
try {
resolvedConfig = await toolboxConfigPromise;
networkConfig = (0, __pact_toolbox_config.getNetworkConfig)(resolvedConfig);
client = new __pact_toolbox_runtime.PactToolboxClient(resolvedConfig);
if (startNetwork) {
const { network: networkInstance, client: networkClient } = await require_utils.createPactToolboxNetwork({
isServe,
isTest,
client,
networkConfig
}, resolvedConfig, options);
network = networkInstance;
client = networkClient;
}
} catch (error) {
console.error("Error during server configuration:", error);
}
};
/**
* Asynchronous function to handle configuration resolution.
* @param config Vite resolved configuration.
*/
const onConfig = async (config, { command }) => {
try {
resolvedConfig = await toolboxConfigPromise;
isTest = command === "test" || isTest;
isServe = command === "serve";
if (!isTest) {
const serializableNetworkConfig = (0, __pact_toolbox_config.getSerializableNetworkConfig)(resolvedConfig);
config.define = config.define || {};
config.define["globalThis.__PACT_TOOLBOX_NETWORK_CONFIG__"] = JSON.stringify(serializableNetworkConfig);
}
} catch (error) {
console.error("Error during config resolution:", error);
}
};
/**
* Asynchronous function to handle file transformation.
* @param src Source code of the `.pact` file.
* @param id File identifier (path).
* @returns Transformed code and source map.
*/
const transformFile = async (src, id) => {
if (!id.endsWith(".pact")) return null;
const cached = cache.get(id);
const shouldTransform = !cached || cached.src !== src;
const cleanName = node_path.default.basename(id);
if (!shouldTransform) return {
code: cached.code,
map: null
};
try {
const { code, types, modules } = transformPactToJS(src);
const isDeployed = modules.length > 0 ? (await Promise.all(modules.map((m) => client?.isContractDeployed(m.path)))).every(Boolean) : false;
cache.set(id, {
code,
types,
src,
isDeployed
});
if ((0, __pact_toolbox_config.isLocalNetwork)(networkConfig) && network) deployContract(id, src, isDeployed).catch((error) => {
require_utils.prettyPrintError(`Failed to deploy contract ${cleanName}`, error);
});
return {
code,
map: null
};
} catch (error) {
if (error instanceof require_pactToJS.ParsingError) {
console.error(`Parsing error in ${id}:`);
error.errors.forEach((err) => {
console.error(` Line ${err.line}, Column ${err.column}: ${err.message}`);
});
return null;
}
console.error(`Unexpected error during transformation of ${id}:`, error);
throw error;
}
};
/**
* Asynchronous function to handle contract deployment.
* @param id File identifier (path).
* @param src Source code of the `.pact` file.
* @param isDeployed Flag indicating if the contract is already deployed.
*/
const deployContract = async (id, src, isDeployed) => {
if (!client) {
console.error("PactToolboxClient is not initialized.");
return;
}
deploySpinner.start(`Deploying contract ${node_path.default.basename(id)}...`);
return Promise.all([(0, __pact_toolbox_utils.writeFile)(`${id}.d.ts`, cache.get(id).types), client.deployCode(src, { build: {
upgrade: isDeployed,
init: !isDeployed
} }).then(() => {
const cached = cache.get(id);
if (cached) {
cached.isDeployed = true;
cache.set(id, cached);
}
deploySpinner.stop(`Contract ${node_path.default.basename(id)} deployed successfully.`);
})]);
};
/**
* Asynchronous function to handle Rspack integration.
* @param compiler Rspack compiler instance.
*/
const configureRspack = async (compiler) => {
try {
const { DefinePlugin } = await import("@rspack/core");
resolvedConfig = await toolboxConfigPromise;
const serializableNetworkConfig = (0, __pact_toolbox_config.getSerializableNetworkConfig)(resolvedConfig);
const definePlugin = new DefinePlugin({ "globalThis.__PACT_TOOLBOX_NETWORK_CONFIG__": JSON.stringify(serializableNetworkConfig) });
if (!client) client = new __pact_toolbox_runtime.PactToolboxClient(resolvedConfig);
if (!networkConfig) networkConfig = (0, __pact_toolbox_config.getNetworkConfig)(resolvedConfig);
definePlugin.apply(compiler);
if (compiler.options.mode === "development") {
const { network: networkInstance, client: networkClient } = await require_utils.createPactToolboxNetwork({
isServe: true,
isTest: false,
client,
networkConfig
}, resolvedConfig, options);
network = networkInstance;
client = networkClient;
}
compiler.hooks.shutdown.tap(require_utils.PLUGIN_NAME, async () => {
const shutdownSpinner = (0, __pact_toolbox_utils.spinner)({ indicator: "timer" });
if (network) try {
shutdownSpinner.start("Shutting down network...");
await Promise.race([network.stop(), new Promise((resolve) => setTimeout(resolve, 1e4))]);
} finally {
shutdownSpinner.stop("Network stopped!");
}
});
} catch (error) {
console.error("Error during Rspack configuration:", error);
}
};
/**
* Sets up Esbuild options for the plugin.
* @param build Esbuild build instance.
*/
const setupEsbuild = async (build) => {
try {
const serializableNetworkConfig = (0, __pact_toolbox_config.getSerializableNetworkConfig)(await toolboxConfigPromise);
build.initialOptions.define = {
...build.initialOptions.define,
"globalThis.__PACT_TOOLBOX_NETWORK_CONFIG__": JSON.stringify(serializableNetworkConfig)
};
} catch (error) {
console.error("Error during Esbuild setup:", error);
}
};
/**
* Main plugin object created by Unplugin.
*/
return {
name: require_utils.PLUGIN_NAME,
enforce: "post",
transformInclude(id) {
return id.endsWith(".pact");
},
transform: transformFile,
configureServer,
vite: {
config: onConfig,
closeBundle: async (error) => {
const shutdownSpinner = (0, __pact_toolbox_utils.spinner)({ indicator: "timer" });
if (error) console.error("Error during Vite bundle:", error);
if (network) try {
shutdownSpinner.start("Shutting down network...");
await Promise.race([network.stop(), new Promise((resolve) => setTimeout(resolve, 1e4))]);
} finally {
shutdownSpinner.stop("Network stopped!");
}
}
},
esbuild: { setup: setupEsbuild },
rspack: configureRspack
};
};
/**
* Create and export the Unplugin instance with default options.
*/
const unplugin$1 = /* @__PURE__ */ (0, unplugin.createUnplugin)(unpluginFactory);
/**
* Default export of the plugin.
*/
var factory_default = unplugin$1;
//#endregion
Object.defineProperty(exports, 'factory_default', {
enumerable: true,
get: function () {
return factory_default;
}
});
Object.defineProperty(exports, 'unplugin', {
enumerable: true,
get: function () {
return unplugin$1;
}
});
Object.defineProperty(exports, 'unpluginFactory', {
enumerable: true,
get: function () {
return unpluginFactory;
}
});