Skip to content

Commit 0302b85

Browse files
committed
feat: compiling polykey in cjs mode for yao-pkg
1 parent 726c3dc commit 0302b85

File tree

7 files changed

+114
-13
lines changed

7 files changed

+114
-13
lines changed

flake.nix

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
let
1313
# The target systems and their vercel/pkg mapping
1414
systems = { "x86_64-linux" = [ "linux" "x64" ]; };
15+
1516
in flake-utils.lib.eachSystem (builtins.attrNames systems) (system:
1617
let
1718
pkgs = nixpkgs-matrix.legacyPackages.${system};
@@ -60,7 +61,7 @@
6061
postBuild = ''
6162
npm run pkg -- \
6263
--output=out \
63-
--bin=dist/polykey.mjs \
64+
--bin=dist/polykey.cjs \
6465
--node-version=${utils.nodeVersion} \
6566
--platform=${platform} \
6667
--arch=${arch}

package.json

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,7 @@
102102
"node_modules/sodium-native/prebuilds/darwin-arm64/node.napi.node",
103103
"node_modules/sodium-native/prebuilds/darwin-x64/node.napi.node",
104104
"node_modules/sodium-native/prebuilds/linux-x64/node.napi.node",
105-
"node_modules/sodium-native/prebuilds/win32-x64/node.napi.node",
106-
"node_modules/sodium-native/index.js"
105+
"node_modules/sodium-native/prebuilds/win32-x64/node.napi.node"
107106
],
108107
"scripts": [
109108
"dist/polykeyWorkerManifest.js"
@@ -121,7 +120,7 @@
121120
"lintfix": "eslint '{src,tests,scripts,benches}/**/*.{js,mjs,ts,mts,jsx,tsx}' --fix",
122121
"lint-shell": "find ./src ./tests ./scripts -type f -regextype posix-extended -regex '.*\\.(sh)' -exec shellcheck {} +",
123122
"docs": "shx rm -rf ./docs && typedoc --gitRevision master --tsconfig ./tsconfig.build.json --out ./docs src",
124-
"pkg": "node ./scripts/pkg.mjs",
123+
"pkg": "node ./scripts/build.mjs --pkg && node ./scripts/pkg.mjs",
125124
"polykey": "node dist/polykey.mjs",
126125
"start": "node dist/polykey.mjs -- agent start --verbose"
127126
},
@@ -173,4 +172,4 @@
173172
"typedoc": "^0.24.8",
174173
"typescript": "^5.1.6"
175174
}
176-
}
175+
}

pkg.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"assets":["node_modules/@matrixai/db/prebuilds/darwin-x64+arm64/node.napi.node","node_modules/@matrixai/db/prebuilds/linux-x64/node.napi.node","node_modules/@matrixai/db/prebuilds/win32-x64/node.napi.node","node_modules/@matrixai/mdns-linux-x64/node.napi.node","node_modules/@matrixai/mdns-linux-x64/package.json","node_modules/@matrixai/quic-darwin-universal/node.napi.node","node_modules/@matrixai/quic-darwin-universal/package.json","node_modules/@matrixai/quic-linux-x64/node.napi.node","node_modules/@matrixai/quic-linux-x64/package.json","node_modules/@matrixai/quic-win32-x64/node.napi.node","node_modules/@matrixai/quic-win32-x64/package.json","node_modules/@matrixai/exec-darwin-universal/node.napi.node","node_modules/@matrixai/exec-darwin-universal/package.json","node_modules/@matrixai/exec-linux-x64/node.napi.node","node_modules/@matrixai/exec-linux-x64/package.json","node_modules/fd-lock/prebuilds/linux-x64/node.napi.node","node_modules/fd-lock/prebuilds/darwin-x64/node.napi.node","node_modules/fd-lock/prebuilds/darwin-arm64/node.napi.node","node_modules/fd-lock/prebuilds/win32-x64/node.napi.node","node_modules/sodium-native/prebuilds/darwin-arm64/node.napi.node","node_modules/sodium-native/prebuilds/darwin-x64/node.napi.node","node_modules/sodium-native/prebuilds/linux-x64/node.napi.node","node_modules/sodium-native/prebuilds/win32-x64/node.napi.node","node_modules/sodium-native/index.js","dist/**","node_modules/@matrixai/db/prebuilds/linux-x64/node.napi.node","node_modules/fd-lock/prebuilds/linux-x64/node.napi.node","node_modules/sodium-native/prebuilds/linux-x64/node.napi.node"],"scripts":["dist/polykeyWorkerManifest.js"]}

scripts/build.mjs

Lines changed: 87 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,72 @@ import childProcess from 'node:child_process';
99
import esbuild from 'esbuild';
1010
import config from 'polykey/config.js';
1111
import packageJSON from '../package.json' assert { type: 'json' };
12+
import { createRequire } from 'node:module';
1213

1314
const projectPath = path.dirname(
1415
path.dirname(url.fileURLToPath(import.meta.url)),
1516
);
1617

1718
const platform = os.platform();
1819

20+
const nativeDirnameOverridePlugin = (nativePackages) => {
21+
return {
22+
name: 'native-dirname-override',
23+
setup(build) {
24+
const require = createRequire(import.meta.url);
25+
26+
for (const pkgName of nativePackages) {
27+
let pkgJsonPath;
28+
try {
29+
pkgJsonPath = require.resolve(`${pkgName}/package.json`);
30+
} catch {
31+
console.log('Skipping', pkgName);
32+
continue;
33+
}
34+
const pkgRoot = path.dirname(pkgJsonPath);
35+
36+
// Read package.json and resolve entry point
37+
const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8'));
38+
let relativeEntry;
39+
40+
if (pkgJson.exports && typeof pkgJson.exports === 'object') {
41+
const mainExport = pkgJson.exports['.'];
42+
if (typeof mainExport === 'string') {
43+
relativeEntry = mainExport;
44+
} else if (mainExport?.require) {
45+
relativeEntry = mainExport.require;
46+
} else if (mainExport?.import) {
47+
relativeEntry = mainExport.import;
48+
}
49+
}
50+
51+
if (!relativeEntry) {
52+
relativeEntry = 'index.js';
53+
}
54+
55+
const resolvedEntry = path.join(pkgRoot, relativeEntry);
56+
57+
build.onLoad({ filter: /.*/, namespace: 'file' }, async (args) => {
58+
if (path.resolve(args.path) !== path.resolve(resolvedEntry)) return;
59+
60+
return {
61+
contents: ` module.exports = require('node-gyp-build')(${JSON.stringify(
62+
pkgRoot,
63+
)}); `,
64+
loader: 'js',
65+
};
66+
});
67+
}
68+
},
69+
};
70+
};
71+
1972
/* eslint-disable no-console */
2073
async function main(argv = process.argv) {
2174
argv = argv.slice(2);
75+
const pkgIndex = argv.findIndex((v) => v == '--pkg');
76+
if (pkgIndex >= 0) argv.splice(pkgIndex, 1);
77+
const isPkg = pkgIndex >= 0;
2278
const buildPath = path.join(projectPath, 'build');
2379
const distPath = path.join(projectPath, 'dist');
2480
const gitPath = process.env.GIT_DIR ?? path.join(projectPath, '.git');
@@ -64,9 +120,11 @@ async function main(argv = process.argv) {
64120
path.join(buildPath, 'build.json'),
65121
JSON.stringify(buildJSON, null, 2),
66122
);
123+
67124
// This specifies import paths that is left as an external require
68125
// This is kept to packages that have a native binding
69126
const externalDependencies = Object.keys(packageJSON.optionalDependencies);
127+
/** @type { import('esbuild').BuildOptions } */
70128
const esbuildOptions = {
71129
// 2 entrypoints, the main script and the worker script
72130
entryPoints: [
@@ -77,26 +135,45 @@ async function main(argv = process.argv) {
77135
bundle: true,
78136
platform: 'node',
79137
outdir: distPath,
80-
external: externalDependencies,
138+
// external: isPkg ? ['*.node'] : externalDependencies,
139+
external: isPkg ? [] : externalDependencies,
140+
// external: externalDependencies,
81141
treeShaking: true,
82142
// External source map for debugging
83143
sourcemap: true,
84144
// Minify and keep the original names
85145
minify: false,
86146
keepNames: true,
87147
// Supporting ESM
88-
format: 'esm',
89-
inject: [path.join(projectPath, './shims/require-shim.mjs')],
90-
outExtension: { '.js': '.mjs' },
148+
format: isPkg ? 'cjs' : 'esm',
149+
// format: 'esm',
150+
inject: isPkg
151+
? [path.join(projectPath, './shims/import-meta-url-shim.mjs')]
152+
: [path.join(projectPath, './shims/require-shim.mjs')],
153+
// inject: [path.join(projectPath, './shims/require-shim.mjs')],
154+
// Fix import.meta.url in CJS output
155+
define: isPkg
156+
? {
157+
'import.meta.url': '__import_meta_url',
158+
}
159+
: {},
160+
outExtension: isPkg ? { '.js': '.cjs' } : { '.js': '.mjs' },
161+
// outExtension: { '.js': '.mjs' },
162+
plugins: isPkg ? [nativeDirnameOverridePlugin(externalDependencies)] : [],
91163
};
92164
console.error('Running esbuild:');
93165
console.error(esbuildOptions);
94166
await esbuild.build(esbuildOptions);
167+
95168
// Rename worker script
96169
console.error('Renaming worker script');
97170
childProcess.execFileSync(
98171
'mv',
99-
['dist/polykeyWorkerManifest.mjs', 'dist/polykeyWorkerManifest.js'],
172+
[
173+
`dist/polykeyWorkerManifest.${isPkg ? 'cjs' : 'mjs'}`,
174+
'dist/polykeyWorkerManifest.js',
175+
],
176+
// ['dist/polykeyWorkerManifest.mjs', 'dist/polykeyWorkerManifest.js'],
100177
{
101178
stdio: ['inherit', 'inherit', 'inherit'],
102179
windowsHide: true,
@@ -106,7 +183,11 @@ async function main(argv = process.argv) {
106183
);
107184
childProcess.execFileSync(
108185
'mv',
109-
['dist/polykeyWorkerManifest.mjs.map', 'dist/polykeyWorkerManifest.js.map'],
186+
[
187+
`dist/polykeyWorkerManifest.${isPkg ? 'cjs' : 'mjs'}.map`,
188+
'dist/polykeyWorkerManifest.js.map',
189+
],
190+
// ['dist/polykeyWorkerManifest.mjs.map', 'dist/polykeyWorkerManifest.js.map'],
110191
{
111192
stdio: ['inherit', 'inherit', 'inherit'],
112193
windowsHide: true,

scripts/pkg.mjs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,16 @@ async function main(argv = process.argv) {
103103
const { default: nodeGypBuild } = await import('node-gyp-build');
104104
const pkgConfig = packageJSON.pkg ?? {};
105105
pkgConfig.assets = pkgConfig.assets ?? {};
106+
107+
// //0---
108+
// const nativeAssetDir = path.join(projectPath, 'dist', 'native');
109+
// const nativeAssets = await find(nativeAssetDir, /\.node$/);
110+
111+
// pkgConfig.assets.push(
112+
// ...nativeAssets.map((p) => path.relative(projectPath, p))
113+
// );
114+
// //0---
115+
106116
const npmLsOut = childProcess.execFileSync(
107117
'npm',
108118
['ls', '--all', '--omit=dev', '--parseable'],
@@ -143,11 +153,11 @@ async function main(argv = process.argv) {
143153
`--config=${pkgConfigPath}`,
144154
`--targets=node${nodeVersion}-${pkgPlatform}-${pkgArch}`,
145155
'--no-bytecode',
146-
'--no-native-build',
147156
'--options=experimental-require-module',
148157
'--public',
149158
"--public-packages='*'",
150159
`--output=${outPath}`,
160+
'-d',
151161
...restArgs,
152162
];
153163
console.error('Running pkg:');

shims/import-meta-url-shim.mjs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
let __import_meta_url;
2+
if (typeof document === 'undefined') {
3+
const { pathToFileURL } = require('url');
4+
__import_meta_url = pathToFileURL(__filename).href;
5+
} else {
6+
__import_meta_url =
7+
(document.currentScript && document.currentScript.src) ||
8+
new URL('main.js', document.baseURI).href;
9+
}
10+
export { __import_meta_url };

shims/require-shim.mjs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,3 @@ import path from 'node:path';
1010
require = createRequire(import.meta.url);
1111
let __dirname = path.dirname(fileURLToPath(import.meta.url));
1212
export { __dirname };
13-

0 commit comments

Comments
 (0)