img2num
Version:
Img2Num is a raster vectorization library - it converts images to SVGs
59 lines (58 loc) • 1.9 kB
JavaScript
//#region src/target/node/webgpu.js
var gpuInitPromise;
/**
* @internal
* @summary Initialize a WebGPU implementation in Node.js.
*
* @description
* Creates a singleton WebGPU instance using the native `webgpu` package when
* one does not already exist on `globalThis.navigator.gpu`. The initialized
* instance is cached so repeated calls return the same promise.
*
* The `webgpu` package is ESM-only and MUST be loaded via dynamic `import()`.
* A static import compiles to a top-level CommonJS require of the package
* in the CJS build, which throws ERR_REQUIRE_ESM on Node < 22.12.
*
* @async
* @function initWebGPU
* @returns {Promise<GPU>} The initialized WebGPU implementation.
* @since 0.2.0
*/
async function initWebGPU() {
if (globalThis.navigator?.gpu) return globalThis.navigator.gpu;
if (!gpuInitPromise) gpuInitPromise = (async () => {
const { create } = await import("webgpu");
const nativeGpu = create(["backend=vulkan"]);
globalThis.navigator ??= {};
globalThis.navigator.gpu = nativeGpu;
return nativeGpu;
})();
return gpuInitPromise;
}
/**
* @internal
* @summary Release the Node.js WebGPU singleton.
*
* @description
* Removes references to the native WebGPU implementation from the global
* object and clears the module-level initialization cache. A short delay is
* introduced to allow the underlying native implementation to finish
* asynchronous cleanup before process termination.
*
* @async
* @function destroyWebGPU
* @returns {Promise<void>}
* @since 0.2.0
*/
async function destroyWebGPU() {
if (globalThis.navigator?.gpu) {
delete globalThis.navigator.gpu;
if (Object.keys(globalThis.navigator).length === 0) delete globalThis.navigator;
}
gpuInitPromise = null;
await new Promise((resolve) => setTimeout(resolve, 50));
}
//#endregion
exports.destroyWebGPU = destroyWebGPU;
exports.initWebGPU = initWebGPU;
//# sourceMappingURL=webgpu-D1RC9WhT.cjs.map