Skip to content

Commit

Permalink
refactor(sdk): force browser compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
ChesterSim committed Dec 6, 2024
1 parent 2388c82 commit f8ee2ff
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 1 deletion.
Binary file modified sdk/bun.lockb
Binary file not shown.
3 changes: 2 additions & 1 deletion sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"scripts": {
"lint": "eslint './**/*.{ts,tsx}' --quiet",
"build": "yarn clean && tsc -p tsconfig.json && tsc -p tsconfig.browser.json && node scripts/postbuild.js",
"build:browser": "yarn clean && tsc -p tsconfig.json && tsc -p tsconfig.browser.json && node scripts/post-browser-build.js",
"clean": "rm -rf lib",
"test": "mocha -r ts-node/register tests/**/*.ts",
"test:inspect": "mocha --inspect-brk -r ts-node/register tests/**/*.ts",
Expand Down Expand Up @@ -87,4 +88,4 @@
"@solana/errors": "2.0.0-preview.4",
"@solana/codecs-data-structures": "2.0.0-preview.4"
}
}
}
67 changes: 67 additions & 0 deletions sdk/scripts/post-browser-build.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// README
// This script is used to ensure that all isomorphic packages are browser compatible.
// Even if the browser build has server code (e.g. NextJS APIs), they will import the browser compatible versions of the isomorphic packages.

// scripts/postbuild.js
const fs = require('fs');
const path = require('path');

const isomorphicPackages = ['grpc'];

const BROWSER_ENVIRONMENT = 'browser';

const environments = ['node', BROWSER_ENVIRONMENT];

environments.forEach((environment) => {
console.log(`Running ${environment} environment postbuild script`);
console.log(``);

isomorphicPackages.forEach((package) => {
const isomorphPath = path.join(
__dirname,
'..',
'lib',
environment,
'isomorphic',
package + '.js'
);

const targetPath = path.join(
__dirname,
'..',
'lib',
environment,
'isomorphic',
`${package}.${BROWSER_ENVIRONMENT}.js` // force all isomorphic packages to be browser compatible
);

try {
const content = fs.readFileSync(targetPath, 'utf8');
fs.writeFileSync(isomorphPath, content);
} catch (error) {
console.error(
`Error processing isomophic package : ${package} :: ${error.message}`
);
}

// Delete other environment files for safety
environments.forEach((otherEnvironment) => {
if (otherEnvironment === environment) {
return;
}

const otherTargetPath = path.join(
__dirname,
'..',
'lib',
environment,
'isomorphic',
`${package}.${otherEnvironment}.js`
);

if (fs.existsSync(otherTargetPath)) {
fs.unlinkSync(otherTargetPath);
}
});
});
});

0 comments on commit f8ee2ff

Please sign in to comment.