Skip to content

Commit

Permalink
Add crypto to Polyfills improving Blueprint compatibility for Node (#…
Browse files Browse the repository at this point in the history
…1000)

- Similar to #875
- Related to WordPress/playground-tools#113

## What is this PR doing?
It imports the native library `crypto` and makes it globally available
in the runtime.

## What problem is it solving?

When using blueprints that install plugins or themes, it generates a
random folder using
[`crypto`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto)`.
That library is available in the browsers by default, but for node we
need to import it.

Note that it do not install any dependency since Crypto is already built
in NodeJS, but it's not imported by default.
I decided to use [`node:crypto`](https://nodejs.org/api/webcrypto.html)
which has `webcrypto` and will be a better match. It's available sine
Node v15.

The other alternative is normal
[crypto](https://nodejs.org/api/crypto.html)
https://nodejs.org/docs/latest-v14.x/api/crypto.html, which also has
`crypto.randomUUID`. It's available since Node v14.

## How is the problem addressed?

It adds a new Polyfill for crypto.

## Testing Instructions

1. Comment the first line `import './crypto';` on
`packages/php-wasm/node-polyfills/src/lib/crypto.spec.ts`
2. Run `npx nx test php-wasm-node-polyfills`
3. Observe the tests fail
4. Uncomment first line `import './crypto';` on
`packages/php-wasm/node-polyfills/src/lib/crypto.spec.ts`
5. Run `npx nx test php-wasm-node-polyfills`
6. Observe the tests pass
  • Loading branch information
sejas authored Feb 5, 2024
1 parent 9f134e0 commit a4d1bd6
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/php-wasm/node-polyfills/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
import './lib/blob';
import './lib/custom-event';
import './lib/crypto';
10 changes: 10 additions & 0 deletions packages/php-wasm/node-polyfills/src/lib/crypto.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import './crypto';

describe('crypto is loaded', () => {
it('Should exist', () => {
expect(crypto).not.toBe(undefined);
});
it('Returns a random', () => {
expect(crypto.randomUUID().length).toBe(36);
});
});
5 changes: 5 additions & 0 deletions packages/php-wasm/node-polyfills/src/lib/crypto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
if (typeof crypto === 'undefined') {
import('crypto').then((module) => {
global.crypto = module as Crypto;
});
}
1 change: 1 addition & 0 deletions packages/php-wasm/node/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export default defineConfig(() => {
'util',
'dns',
'ws',
'crypto',
],
output: {
entryFileNames: '[name].js',
Expand Down

0 comments on commit a4d1bd6

Please sign in to comment.