@eclipsa/optimizer 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mod.d.mts ADDED
@@ -0,0 +1,51 @@
1
+ //#region mod.d.ts
2
+ type CompilerTarget = 'client' | 'ssr';
3
+ interface SymbolRef {
4
+ filePath: string;
5
+ id: string;
6
+ }
7
+ type SymbolKind = 'action' | 'component' | 'event' | 'lazy' | 'loader' | 'watch';
8
+ interface ResumeSymbol {
9
+ captures: string[];
10
+ code: string;
11
+ filePath: string;
12
+ id: string;
13
+ kind: SymbolKind;
14
+ }
15
+ interface ResumeHmrSymbolEntry {
16
+ captures: string[];
17
+ hmrKey: string;
18
+ id: string;
19
+ kind: SymbolKind;
20
+ ownerComponentKey: string | null;
21
+ signature: string;
22
+ }
23
+ interface ResumeHmrComponentEntry {
24
+ captures: string[];
25
+ hmrKey: string;
26
+ id: string;
27
+ localSymbolKeys: string[];
28
+ signature: string;
29
+ }
30
+ interface AnalyzeResponse {
31
+ actions: [string, SymbolRef][];
32
+ code: string;
33
+ hmrManifest: {
34
+ components: [string, ResumeHmrComponentEntry][];
35
+ symbols: [string, ResumeHmrSymbolEntry][];
36
+ };
37
+ loaders: [string, SymbolRef][];
38
+ symbols: [string, ResumeSymbol][];
39
+ }
40
+ interface CompilerRequest {
41
+ hmr?: boolean;
42
+ id: string;
43
+ source: string;
44
+ target: CompilerTarget;
45
+ }
46
+ declare const resolveGeneratedArtifactPath: (fileName: string) => string | null;
47
+ declare const runRustCompiler: (request: CompilerRequest) => Promise<string>;
48
+ declare const runRustAnalyzeCompiler: (id: string, source: string) => Promise<AnalyzeResponse>;
49
+ //#endregion
50
+ export { resolveGeneratedArtifactPath, runRustAnalyzeCompiler, runRustCompiler };
51
+ //# sourceMappingURL=mod.d.mts.map
package/dist/mod.mjs ADDED
@@ -0,0 +1,105 @@
1
+ import { createRequire } from "node:module";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ //#region mod.ts
5
+ const OPTIMIZER_PACKAGE_NAME = "@eclipsa/optimizer";
6
+ const GENERATED_ARTIFACT_RELATIVE_DIRS = [
7
+ "./generated",
8
+ "../generated",
9
+ "../../generated"
10
+ ];
11
+ const require = createRequire(import.meta.url);
12
+ let bindingPromise = null;
13
+ const isFileMusl = (filePath) => filePath.includes("libc.musl-") || filePath.includes("ld-musl-");
14
+ const isMusl = () => {
15
+ if (process.platform !== "linux") return false;
16
+ try {
17
+ return readFileSync("/usr/bin/ldd", "utf8").includes("musl");
18
+ } catch {}
19
+ if (typeof process.report?.getReport === "function") {
20
+ const report = process.report.getReport();
21
+ if (report?.header && "glibcVersionRuntime" in report.header && report.header.glibcVersionRuntime) return false;
22
+ if (Array.isArray(report?.sharedObjects) && report.sharedObjects.some(isFileMusl)) return true;
23
+ }
24
+ try {
25
+ return require("node:child_process").execSync("ldd --version", { encoding: "utf8" }).includes("musl");
26
+ } catch {
27
+ return false;
28
+ }
29
+ };
30
+ const getTargetPackageName = (suffix) => `${OPTIMIZER_PACKAGE_NAME}-${suffix}`;
31
+ const resolveGeneratedArtifactPath = (fileName) => {
32
+ for (const relativeDir of GENERATED_ARTIFACT_RELATIVE_DIRS) {
33
+ const absolutePath = fileURLToPath(new URL(`${relativeDir}/${fileName}`, import.meta.url));
34
+ if (existsSync(absolutePath)) return absolutePath;
35
+ }
36
+ return null;
37
+ };
38
+ const loadErrors = [];
39
+ const requireGeneratedArtifact = (fileName) => {
40
+ const artifactPath = resolveGeneratedArtifactPath(fileName);
41
+ if (!artifactPath) return null;
42
+ try {
43
+ return require(artifactPath);
44
+ } catch (error) {
45
+ loadErrors.push(error);
46
+ return null;
47
+ }
48
+ };
49
+ const requireOptionalBinding = (packageName) => {
50
+ try {
51
+ return require(packageName);
52
+ } catch (error) {
53
+ loadErrors.push(error);
54
+ return null;
55
+ }
56
+ };
57
+ const requireWasiBinding = () => {
58
+ return requireGeneratedArtifact("optimizer.wasi.cjs") ?? requireOptionalBinding(getTargetPackageName("wasm32-wasi"));
59
+ };
60
+ const requirePreferredBinding = (fileName, packageName) => requireGeneratedArtifact(fileName) ?? requireOptionalBinding(packageName);
61
+ const requireNativeBinding = () => {
62
+ loadErrors.length = 0;
63
+ if (process.env.NAPI_RS_FORCE_WASI === "1") return requireWasiBinding();
64
+ if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) try {
65
+ return require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH);
66
+ } catch (error) {
67
+ loadErrors.push(error);
68
+ }
69
+ if (process.platform === "darwin") {
70
+ if (process.arch === "arm64") return requirePreferredBinding("optimizer.darwin-arm64.node", getTargetPackageName("darwin-arm64"));
71
+ if (process.arch === "x64") return requirePreferredBinding("optimizer.darwin-x64.node", getTargetPackageName("darwin-x64"));
72
+ }
73
+ if (process.platform === "win32") {
74
+ if (process.arch === "arm64") return requirePreferredBinding("optimizer.win32-arm64-msvc.node", getTargetPackageName("win32-arm64-msvc"));
75
+ if (process.arch === "x64") return requirePreferredBinding("optimizer.win32-x64-msvc.node", getTargetPackageName("win32-x64-msvc"));
76
+ }
77
+ if (process.platform === "linux") {
78
+ const libc = isMusl() ? "musl" : "gnu";
79
+ if (process.arch === "arm64") return requirePreferredBinding(`optimizer.linux-arm64-${libc}.node`, getTargetPackageName(`linux-arm64-${libc}`));
80
+ if (process.arch === "x64") return requirePreferredBinding(`optimizer.linux-x64-${libc}.node`, getTargetPackageName(`linux-x64-${libc}`));
81
+ }
82
+ return requireWasiBinding();
83
+ };
84
+ const loadNativeBinding = async () => {
85
+ if (!bindingPromise) bindingPromise = (async () => {
86
+ const binding = requireNativeBinding();
87
+ if (binding) return binding;
88
+ const localBuildHint = process.env.NAPI_RS_FORCE_WASI === "1" ? "Run \"bun run build:native --filter @eclipsa/optimizer -- --target wasm32-wasip1-threads\" or install the matching optional package." : "Run \"bun run build:native:dev --filter @eclipsa/optimizer\" before using the compiler in the workspace, or install the matching optional package.";
89
+ const details = loadErrors.length === 0 ? "No matching generated artifact or optional package was found." : loadErrors.map((error) => error.message).join("\n");
90
+ throw new Error(`Failed to load the Eclipsa compiler binding. ${localBuildHint}\n${details}`);
91
+ })();
92
+ return bindingPromise;
93
+ };
94
+ const runRustCompiler = async (request) => {
95
+ const binding = await loadNativeBinding();
96
+ if (request.target === "client") return binding.compileClient(request.source, request.id, request.hmr ?? false);
97
+ return binding.compileSsr(request.source, request.id);
98
+ };
99
+ const runRustAnalyzeCompiler = async (id, source) => {
100
+ return (await loadNativeBinding()).analyzeModule(source, id);
101
+ };
102
+ //#endregion
103
+ export { resolveGeneratedArtifactPath, runRustAnalyzeCompiler, runRustCompiler };
104
+
105
+ //# sourceMappingURL=mod.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.mjs","names":[],"sources":["../mod.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { fileURLToPath } from 'node:url'\n\ntype CompilerTarget = 'client' | 'ssr'\n\ninterface SymbolRef {\n filePath: string\n id: string\n}\n\ntype SymbolKind = 'action' | 'component' | 'event' | 'lazy' | 'loader' | 'watch'\n\ninterface ResumeSymbol {\n captures: string[]\n code: string\n filePath: string\n id: string\n kind: SymbolKind\n}\n\ninterface ResumeHmrSymbolEntry {\n captures: string[]\n hmrKey: string\n id: string\n kind: SymbolKind\n ownerComponentKey: string | null\n signature: string\n}\n\ninterface ResumeHmrComponentEntry {\n captures: string[]\n hmrKey: string\n id: string\n localSymbolKeys: string[]\n signature: string\n}\n\ninterface AnalyzeResponse {\n actions: [string, SymbolRef][]\n code: string\n hmrManifest: {\n components: [string, ResumeHmrComponentEntry][]\n symbols: [string, ResumeHmrSymbolEntry][]\n }\n loaders: [string, SymbolRef][]\n symbols: [string, ResumeSymbol][]\n}\n\ninterface NativeBinding {\n analyzeModule(source: string, id: string): AnalyzeResponse\n compileClient(source: string, id: string, hmr?: boolean | null): string\n compileSsr(source: string, id: string): string\n}\n\ninterface CompilerRequest {\n hmr?: boolean\n id: string\n source: string\n target: CompilerTarget\n}\n\nconst OPTIMIZER_PACKAGE_NAME = '@eclipsa/optimizer'\nconst GENERATED_ARTIFACT_RELATIVE_DIRS = ['./generated', '../generated', '../../generated']\n\nconst require = createRequire(import.meta.url)\n\nlet bindingPromise: Promise<NativeBinding> | null = null\n\ninterface ProcessReportLike {\n header?: {\n glibcVersionRuntime?: unknown\n }\n sharedObjects?: string[]\n}\n\nconst isFileMusl = (filePath: string) =>\n filePath.includes('libc.musl-') || filePath.includes('ld-musl-')\n\nconst isMusl = () => {\n if (process.platform !== 'linux') {\n return false\n }\n\n try {\n return readFileSync('/usr/bin/ldd', 'utf8').includes('musl')\n } catch {}\n\n if (typeof process.report?.getReport === 'function') {\n const report = process.report.getReport() as ProcessReportLike\n if (\n report?.header &&\n 'glibcVersionRuntime' in report.header &&\n report.header.glibcVersionRuntime\n ) {\n return false\n }\n if (Array.isArray(report?.sharedObjects) && report.sharedObjects.some(isFileMusl)) {\n return true\n }\n }\n\n try {\n return require('node:child_process')\n .execSync('ldd --version', { encoding: 'utf8' })\n .includes('musl')\n } catch {\n return false\n }\n}\n\nconst getTargetPackageName = (suffix: string) => `${OPTIMIZER_PACKAGE_NAME}-${suffix}`\n\nexport const resolveGeneratedArtifactPath = (fileName: string) => {\n for (const relativeDir of GENERATED_ARTIFACT_RELATIVE_DIRS) {\n const absolutePath = fileURLToPath(new URL(`${relativeDir}/${fileName}`, import.meta.url))\n if (existsSync(absolutePath)) {\n return absolutePath\n }\n }\n\n return null\n}\n\nconst loadErrors: Error[] = []\n\nconst requireGeneratedArtifact = (fileName: string) => {\n const artifactPath = resolveGeneratedArtifactPath(fileName)\n if (!artifactPath) {\n return null\n }\n\n try {\n return require(artifactPath) as NativeBinding\n } catch (error) {\n loadErrors.push(error as Error)\n return null\n }\n}\n\nconst requireOptionalBinding = (packageName: string) => {\n try {\n return require(packageName) as NativeBinding\n } catch (error) {\n loadErrors.push(error as Error)\n return null\n }\n}\n\nconst requireWasiBinding = () => {\n return (\n requireGeneratedArtifact('optimizer.wasi.cjs') ??\n requireOptionalBinding(getTargetPackageName('wasm32-wasi'))\n )\n}\n\nconst requirePreferredBinding = (fileName: string, packageName: string) =>\n requireGeneratedArtifact(fileName) ?? requireOptionalBinding(packageName)\n\nconst requireNativeBinding = () => {\n loadErrors.length = 0\n\n if (process.env.NAPI_RS_FORCE_WASI === '1') {\n return requireWasiBinding()\n }\n\n if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) {\n try {\n return require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH) as NativeBinding\n } catch (error) {\n loadErrors.push(error as Error)\n }\n }\n\n if (process.platform === 'darwin') {\n if (process.arch === 'arm64') {\n return requirePreferredBinding(\n 'optimizer.darwin-arm64.node',\n getTargetPackageName('darwin-arm64'),\n )\n }\n if (process.arch === 'x64') {\n return requirePreferredBinding(\n 'optimizer.darwin-x64.node',\n getTargetPackageName('darwin-x64'),\n )\n }\n }\n\n if (process.platform === 'win32') {\n if (process.arch === 'arm64') {\n return requirePreferredBinding(\n 'optimizer.win32-arm64-msvc.node',\n getTargetPackageName('win32-arm64-msvc'),\n )\n }\n if (process.arch === 'x64') {\n return requirePreferredBinding(\n 'optimizer.win32-x64-msvc.node',\n getTargetPackageName('win32-x64-msvc'),\n )\n }\n }\n\n if (process.platform === 'linux') {\n const libc = isMusl() ? 'musl' : 'gnu'\n if (process.arch === 'arm64') {\n return requirePreferredBinding(\n `optimizer.linux-arm64-${libc}.node`,\n getTargetPackageName(`linux-arm64-${libc}`),\n )\n }\n if (process.arch === 'x64') {\n return requirePreferredBinding(\n `optimizer.linux-x64-${libc}.node`,\n getTargetPackageName(`linux-x64-${libc}`),\n )\n }\n }\n\n return requireWasiBinding()\n}\n\nconst loadNativeBinding = async () => {\n if (!bindingPromise) {\n bindingPromise = (async () => {\n const binding = requireNativeBinding()\n if (binding) {\n return binding\n }\n\n const localBuildHint =\n process.env.NAPI_RS_FORCE_WASI === '1'\n ? 'Run \"bun run build:native --filter @eclipsa/optimizer -- --target wasm32-wasip1-threads\" or install the matching optional package.'\n : 'Run \"bun run build:native:dev --filter @eclipsa/optimizer\" before using the compiler in the workspace, or install the matching optional package.'\n const details =\n loadErrors.length === 0\n ? 'No matching generated artifact or optional package was found.'\n : loadErrors.map((error) => error.message).join('\\n')\n\n throw new Error(`Failed to load the Eclipsa compiler binding. ${localBuildHint}\\n${details}`)\n })()\n }\n\n return bindingPromise\n}\n\nexport const runRustCompiler = async (request: CompilerRequest) => {\n const binding = await loadNativeBinding()\n\n if (request.target === 'client') {\n return binding.compileClient(request.source, request.id, request.hmr ?? false)\n }\n return binding.compileSsr(request.source, request.id)\n}\n\nexport const runRustAnalyzeCompiler = async (id: string, source: string) => {\n const binding = await loadNativeBinding()\n return binding.analyzeModule(source, id)\n}\n"],"mappings":"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"}
@@ -0,0 +1 @@
1
+ export * from '@eclipsa/optimizer-wasm32-wasi'
File without changes
@@ -0,0 +1,60 @@
1
+ import {
2
+ createOnMessage as __wasmCreateOnMessageForFsProxy,
3
+ getDefaultContext as __emnapiGetDefaultContext,
4
+ instantiateNapiModuleSync as __emnapiInstantiateNapiModuleSync,
5
+ WASI as __WASI,
6
+ } from '@napi-rs/wasm-runtime'
7
+
8
+
9
+
10
+ const __wasi = new __WASI({
11
+ version: 'preview1',
12
+ })
13
+
14
+ const __wasmUrl = new URL('./optimizer.wasm32-wasi.wasm', import.meta.url).href
15
+ const __emnapiContext = __emnapiGetDefaultContext()
16
+
17
+
18
+ const __sharedMemory = new WebAssembly.Memory({
19
+ initial: 4000,
20
+ maximum: 65536,
21
+ shared: true,
22
+ })
23
+
24
+ const __wasmFile = await fetch(__wasmUrl).then((res) => res.arrayBuffer())
25
+
26
+ const {
27
+ instance: __napiInstance,
28
+ module: __wasiModule,
29
+ napiModule: __napiModule,
30
+ } = __emnapiInstantiateNapiModuleSync(__wasmFile, {
31
+ context: __emnapiContext,
32
+ asyncWorkPoolSize: 4,
33
+ wasi: __wasi,
34
+ onCreateWorker() {
35
+ const worker = new Worker(new URL('./wasi-worker-browser.mjs', import.meta.url), {
36
+ type: 'module',
37
+ })
38
+
39
+
40
+ return worker
41
+ },
42
+ overwriteImports(importObject) {
43
+ importObject.env = {
44
+ ...importObject.env,
45
+ ...importObject.napi,
46
+ ...importObject.emnapi,
47
+ memory: __sharedMemory,
48
+ }
49
+ return importObject
50
+ },
51
+ beforeInit({ instance }) {
52
+ for (const name of Object.keys(instance.exports)) {
53
+ if (name.startsWith('__napi_register__')) {
54
+ instance.exports[name]()
55
+ }
56
+ }
57
+ },
58
+ })
59
+ export default __napiModule.exports
60
+
@@ -0,0 +1,111 @@
1
+ /* eslint-disable */
2
+ /* prettier-ignore */
3
+
4
+ /* auto-generated by NAPI-RS */
5
+
6
+ const __nodeFs = require('node:fs')
7
+ const __nodePath = require('node:path')
8
+ const { WASI: __nodeWASI } = require('node:wasi')
9
+ const { Worker } = require('node:worker_threads')
10
+
11
+ const {
12
+ createOnMessage: __wasmCreateOnMessageForFsProxy,
13
+ getDefaultContext: __emnapiGetDefaultContext,
14
+ instantiateNapiModuleSync: __emnapiInstantiateNapiModuleSync,
15
+ } = require('@napi-rs/wasm-runtime')
16
+
17
+ const __rootDir = __nodePath.parse(process.cwd()).root
18
+
19
+ const __wasi = new __nodeWASI({
20
+ version: 'preview1',
21
+ env: process.env,
22
+ preopens: {
23
+ [__rootDir]: __rootDir,
24
+ }
25
+ })
26
+
27
+ const __emnapiContext = __emnapiGetDefaultContext()
28
+
29
+ const __sharedMemory = new WebAssembly.Memory({
30
+ initial: 4000,
31
+ maximum: 65536,
32
+ shared: true,
33
+ })
34
+
35
+ let __wasmFilePath = __nodePath.join(__dirname, 'optimizer.wasm32-wasi.wasm')
36
+ const __wasmDebugFilePath = __nodePath.join(__dirname, 'optimizer.wasm32-wasi.debug.wasm')
37
+
38
+ if (__nodeFs.existsSync(__wasmDebugFilePath)) {
39
+ __wasmFilePath = __wasmDebugFilePath
40
+ } else if (!__nodeFs.existsSync(__wasmFilePath)) {
41
+ try {
42
+ __wasmFilePath = require.resolve('@eclipsa/optimizer-wasm32-wasi/optimizer.wasm32-wasi.wasm')
43
+ } catch {
44
+ throw new Error('Cannot find optimizer.wasm32-wasi.wasm file, and @eclipsa/optimizer-wasm32-wasi package is not installed.')
45
+ }
46
+ }
47
+
48
+ const { instance: __napiInstance, module: __wasiModule, napiModule: __napiModule } = __emnapiInstantiateNapiModuleSync(__nodeFs.readFileSync(__wasmFilePath), {
49
+ context: __emnapiContext,
50
+ asyncWorkPoolSize: (function() {
51
+ const threadsSizeFromEnv = Number(process.env.NAPI_RS_ASYNC_WORK_POOL_SIZE ?? process.env.UV_THREADPOOL_SIZE)
52
+ // NaN > 0 is false
53
+ if (threadsSizeFromEnv > 0) {
54
+ return threadsSizeFromEnv
55
+ } else {
56
+ return 4
57
+ }
58
+ })(),
59
+ reuseWorker: true,
60
+ wasi: __wasi,
61
+ onCreateWorker() {
62
+ const worker = new Worker(__nodePath.join(__dirname, 'wasi-worker.mjs'), {
63
+ env: process.env,
64
+ })
65
+ worker.onmessage = ({ data }) => {
66
+ __wasmCreateOnMessageForFsProxy(__nodeFs)(data)
67
+ }
68
+
69
+ // The main thread of Node.js waits for all the active handles before exiting.
70
+ // But Rust threads are never waited without `thread::join`.
71
+ // So here we hack the code of Node.js to prevent the workers from being referenced (active).
72
+ // According to https://github.com/nodejs/node/blob/19e0d472728c79d418b74bddff588bea70a403d0/lib/internal/worker.js#L415,
73
+ // a worker is consist of two handles: kPublicPort and kHandle.
74
+ {
75
+ const kPublicPort = Object.getOwnPropertySymbols(worker).find(s =>
76
+ s.toString().includes("kPublicPort")
77
+ );
78
+ if (kPublicPort) {
79
+ worker[kPublicPort].ref = () => {};
80
+ }
81
+
82
+ const kHandle = Object.getOwnPropertySymbols(worker).find(s =>
83
+ s.toString().includes("kHandle")
84
+ );
85
+ if (kHandle) {
86
+ worker[kHandle].ref = () => {};
87
+ }
88
+
89
+ worker.unref();
90
+ }
91
+ return worker
92
+ },
93
+ overwriteImports(importObject) {
94
+ importObject.env = {
95
+ ...importObject.env,
96
+ ...importObject.napi,
97
+ ...importObject.emnapi,
98
+ memory: __sharedMemory,
99
+ }
100
+ return importObject
101
+ },
102
+ beforeInit({ instance }) {
103
+ for (const name of Object.keys(instance.exports)) {
104
+ if (name.startsWith('__napi_register__')) {
105
+ instance.exports[name]()
106
+ }
107
+ }
108
+ },
109
+ })
110
+ module.exports = __napiModule.exports
111
+
@@ -0,0 +1,36 @@
1
+ import { instantiateNapiModuleSync, MessageHandler, WASI } from '@napi-rs/wasm-runtime'
2
+
3
+ const errorOutputs = []
4
+
5
+ const handler = new MessageHandler({
6
+ onLoad({ wasmModule, wasmMemory }) {
7
+ const wasi = new WASI({
8
+ print: function () {
9
+ // eslint-disable-next-line no-console
10
+ console.log.apply(console, arguments)
11
+ },
12
+ printErr: function() {
13
+ // eslint-disable-next-line no-console
14
+ console.error.apply(console, arguments)
15
+
16
+ },
17
+ })
18
+ return instantiateNapiModuleSync(wasmModule, {
19
+ childThread: true,
20
+ wasi,
21
+ overwriteImports(importObject) {
22
+ importObject.env = {
23
+ ...importObject.env,
24
+ ...importObject.napi,
25
+ ...importObject.emnapi,
26
+ memory: wasmMemory,
27
+ }
28
+ },
29
+ })
30
+ },
31
+
32
+ })
33
+
34
+ globalThis.onmessage = function (e) {
35
+ handler.handle(e)
36
+ }
@@ -0,0 +1,63 @@
1
+ import fs from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { parse } from "node:path";
4
+ import { WASI } from "node:wasi";
5
+ import { parentPort, Worker } from "node:worker_threads";
6
+
7
+ const require = createRequire(import.meta.url);
8
+
9
+ const { instantiateNapiModuleSync, MessageHandler, getDefaultContext } = require("@napi-rs/wasm-runtime");
10
+
11
+ if (parentPort) {
12
+ parentPort.on("message", (data) => {
13
+ globalThis.onmessage({ data });
14
+ });
15
+ }
16
+
17
+ Object.assign(globalThis, {
18
+ self: globalThis,
19
+ require,
20
+ Worker,
21
+ importScripts: function (f) {
22
+ ;(0, eval)(fs.readFileSync(f, "utf8") + "//# sourceURL=" + f);
23
+ },
24
+ postMessage: function (msg) {
25
+ if (parentPort) {
26
+ parentPort.postMessage(msg);
27
+ }
28
+ },
29
+ });
30
+
31
+ const emnapiContext = getDefaultContext();
32
+
33
+ const __rootDir = parse(process.cwd()).root;
34
+
35
+ const handler = new MessageHandler({
36
+ onLoad({ wasmModule, wasmMemory }) {
37
+ const wasi = new WASI({
38
+ version: 'preview1',
39
+ env: process.env,
40
+ preopens: {
41
+ [__rootDir]: __rootDir,
42
+ },
43
+ });
44
+
45
+ return instantiateNapiModuleSync(wasmModule, {
46
+ childThread: true,
47
+ wasi,
48
+ context: emnapiContext,
49
+ overwriteImports(importObject) {
50
+ importObject.env = {
51
+ ...importObject.env,
52
+ ...importObject.napi,
53
+ ...importObject.emnapi,
54
+ memory: wasmMemory
55
+ };
56
+ },
57
+ });
58
+ },
59
+ });
60
+
61
+ globalThis.onmessage = function (e) {
62
+ handler.handle(e);
63
+ };
package/package.json ADDED
@@ -0,0 +1,97 @@
1
+ {
2
+ "name": "@eclipsa/optimizer",
3
+ "version": "0.0.0",
4
+ "homepage": "https://github.com/pnsk-lab/eclipsa",
5
+ "bugs": {
6
+ "url": "https://github.com/pnsk-lab/eclipsa/issues"
7
+ },
8
+ "license": "MIT",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/pnsk-lab/eclipsa.git",
12
+ "directory": "packages/optimizer"
13
+ },
14
+ "type": "module",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/mod.d.mts",
18
+ "import": "./dist/mod.mjs"
19
+ },
20
+ "./browser": {
21
+ "types": "./generated/index.d.ts",
22
+ "import": "./generated/optimizer.wasi-browser.js"
23
+ }
24
+ },
25
+ "publishConfig": {
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/mod.d.mts",
29
+ "import": "./dist/mod.mjs"
30
+ },
31
+ "./browser": {
32
+ "types": "./generated/index.d.ts",
33
+ "import": "./generated/optimizer.wasi-browser.js"
34
+ }
35
+ }
36
+ },
37
+ "scripts": {
38
+ "artifacts": "bun ./scripts/run-napi.ts artifacts --package-json-path ./package.json --output-dir ./generated --npm-dir ./npm --build-output-dir ./artifacts",
39
+ "build": "bun run build:js && bun run build:native",
40
+ "build:js": "vp pack",
41
+ "build:native:dev": "node -e \"require('node:fs').rmSync('./generated', { recursive: true, force: true })\" && bun ./scripts/run-napi.ts build --platform --manifest-path ../eclipsa/compiler/rust/Cargo.toml --package-json-path ./package.json --target-dir ../eclipsa/compiler/rust/target --output-dir ./generated --js-package-name @eclipsa/optimizer && bun ./scripts/sync-browser-wasm.ts",
42
+ "build:native": "node -e \"require('node:fs').rmSync('./generated', { recursive: true, force: true })\" && bun ./scripts/run-napi.ts build --platform --release --manifest-path ../eclipsa/compiler/rust/Cargo.toml --package-json-path ./package.json --target-dir ../eclipsa/compiler/rust/target --output-dir ./generated --js-package-name @eclipsa/optimizer && bun ./scripts/sync-browser-wasm.ts",
43
+ "create:npm-dirs": "bun ./scripts/create-npm-dirs.ts --package-json-path ./package.json --npm-dir ./npm",
44
+ "pack": "bun run build",
45
+ "prepublishOnly": "bun ./scripts/sync-package-manifest.ts publish && bun ./scripts/run-napi.ts pre-publish -t npm --package-json-path ./package.json --npm-dir ./npm",
46
+ "restore:manifest": "bun ./scripts/sync-package-manifest.ts dev",
47
+ "typecheck": "bunx tsc -p tsconfig.json --noEmit",
48
+ "version:napi": "bun ./scripts/run-napi.ts version --package-json-path ./package.json --npm-dir ./npm",
49
+ "test": "bun run build:native:dev && vp test --run"
50
+ },
51
+ "dependencies": {
52
+ "@emnapi/core": "^1.9.0",
53
+ "@emnapi/runtime": "^1.9.0",
54
+ "@emnapi/wasi-threads": "^1.2.0",
55
+ "@napi-rs/wasm-runtime": "^1.1.1"
56
+ },
57
+ "devDependencies": {
58
+ "@napi-rs/cli": "^3.5.1"
59
+ },
60
+ "napi": {
61
+ "binaryName": "optimizer",
62
+ "targets": [
63
+ "x86_64-apple-darwin",
64
+ "aarch64-apple-darwin",
65
+ "x86_64-unknown-linux-gnu",
66
+ "aarch64-unknown-linux-gnu",
67
+ "x86_64-unknown-linux-musl",
68
+ "aarch64-unknown-linux-musl",
69
+ "x86_64-pc-windows-msvc",
70
+ "aarch64-pc-windows-msvc",
71
+ "wasm32-wasip1-threads"
72
+ ]
73
+ },
74
+ "files": [
75
+ "dist/**/*.mjs",
76
+ "dist/**/*.mjs.map",
77
+ "dist/**/*.d.mts",
78
+ "generated/**/*.js",
79
+ "generated/**/*.d.ts",
80
+ "generated/**/*.cjs",
81
+ "generated/**/*.mjs",
82
+ "generated/**/*.wasm"
83
+ ],
84
+ "main": "./dist/mod.mjs",
85
+ "types": "./dist/mod.d.mts",
86
+ "optionalDependencies": {
87
+ "@eclipsa/optimizer-darwin-x64": "0.0.0",
88
+ "@eclipsa/optimizer-darwin-arm64": "0.0.0",
89
+ "@eclipsa/optimizer-linux-x64-gnu": "0.0.0",
90
+ "@eclipsa/optimizer-linux-arm64-gnu": "0.0.0",
91
+ "@eclipsa/optimizer-linux-x64-musl": "0.0.0",
92
+ "@eclipsa/optimizer-linux-arm64-musl": "0.0.0",
93
+ "@eclipsa/optimizer-win32-x64-msvc": "0.0.0",
94
+ "@eclipsa/optimizer-win32-arm64-msvc": "0.0.0",
95
+ "@eclipsa/optimizer-wasm32-wasi": "0.0.0"
96
+ }
97
+ }