Skip to content

Commit 9bf127f

Browse files
committed
Allow module to work in both node and browser environments
1 parent 0467534 commit 9bf127f

File tree

5 files changed

+21
-8
lines changed

5 files changed

+21
-8
lines changed

js/format.ts

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,34 @@
1-
import fs from 'node:fs/promises';
2-
import './wasm_exec.cjs';
3-
import path from 'node:path';
4-
import { fileURLToPath } from 'url';
1+
import './wasm_exec.js';
52

6-
export interface FormatOptions {
3+
interface FormatOptions {
74
indent: number;
85
trailingNewline: boolean;
96
}
107

8+
const isNode: boolean = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
9+
1110
const formatDockerfile = async (fileName: string, options: FormatOptions) => {
11+
if (!isNode) {
12+
throw new Error('formatDockerfile is only supported in Node.js');
13+
}
14+
const fs = require('node:fs/promises');
15+
1216
// This would only work in Node.js, so we don't add a wasmDownload function
1317
const fileBuffer = await fs.readFile(fileName);
1418
const fileContents = fileBuffer.toString();
1519
return formatDockerfileContents(fileContents, options);
1620
}
1721

18-
const getWasmModule = () => fs.readFile(path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'format.wasm'))
22+
const getWasmModule = () => {
23+
if (isNode) {
24+
const path = require('node:path');
25+
const url = require('node:url');
26+
const fs = require('node:fs/promises');
27+
return fs.readFile(path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), 'format.wasm'));
28+
}
29+
// In the browser, we need to fetch the wasm module
30+
throw new Error('WASM module not found. Please provide a function to fetch the WASM module.');
31+
}
1932

2033
const formatDockerfileContents = async (fileContents: string, options: FormatOptions, getWasm: () => Promise<Buffer> = getWasmModule) => {
2134
const go = new Go() // Defined in wasm_exec.js
@@ -64,4 +77,4 @@ const formatDockerfileContents = async (fileContents: string, options: FormatOpt
6477
return result
6578
}
6679

67-
export { formatDockerfile, formatDockerfileContents }
80+
export { formatDockerfile, formatDockerfileContents, FormatOptions }

js/format.wasm

1.21 KB
Binary file not shown.

js/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
"test": "echo \"Error: no test specified\" && exit 1",
77
"//": "Requires tinygo 0.38.0 or later",
88
"build-go": "tinygo build -o format.wasm -target wasm --no-debug",
9-
"build-js": "tsc && cp format.wasm wasm_exec.cjs dist",
9+
"build-js": "tsc && cp format.wasm wasm_exec.js dist",
1010
"build": "npm run build-go && npm run build-js"
1111
},
1212
"files": [
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)