From dafc1fc469aac1a44e3f10d86af4706a3bf60457 Mon Sep 17 00:00:00 2001 From: Roland Bewick Date: Wed, 6 Dec 2023 16:27:48 +0700 Subject: [PATCH] fix: do not dynamically import crypto --- README.md | 16 ++++++++++++++-- examples/request-invoice.js | 2 ++ package.json | 2 +- src/utils/sha256.ts | 5 ----- 4 files changed, 17 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 8c8320d..b3c9061 100644 --- a/README.md +++ b/README.md @@ -272,13 +272,25 @@ This library uses a [proxy](https://github.com/getAlby/lightning-address-details You can disable the proxy by explicitly setting the proxy to false when initializing a lightning address: +```js +const lightningAddress = new LightningAddress("hello@getalby.com", { + proxy: false, +}); ``` -const lightningAddress = new LightningAddress("hello@getalby.com", {proxy: false}); + +## crypto dependency + +If you get an `crypto is not defined` in NodeJS error you have to import it first: + +```js +import * as crypto from 'crypto'; // or 'node:crypto' +globalThis.crypto = crypto as any; +//or: global.crypto = require('crypto'); ``` ## fetch() dependency -This library relies on a global fetch object which will work in browsers and node v18.x or newer. In old version yoi can manually install a global fetch option or polyfill if needed. +This library relies on a global fetch object which will work in browsers and node v18.x or newer. In old version you can manually install a global fetch option or polyfill if needed. For example: diff --git a/examples/request-invoice.js b/examples/request-invoice.js index 024f4be..7d2f60f 100644 --- a/examples/request-invoice.js +++ b/examples/request-invoice.js @@ -1,3 +1,5 @@ +import * as crypto from "crypto"; // or 'node:crypto' +global.crypto = crypto; import { LightningAddress } from "@getalby/lightning-tools"; const ln = new LightningAddress("hello@getalby.com"); diff --git a/package.json b/package.json index 663b494..363fd88 100644 --- a/package.json +++ b/package.json @@ -38,7 +38,7 @@ "format:fix": "prettier --loglevel silent --write '**/*.(md|json)' 'src/**/*.(js|ts)' 'examples/**/*.js'", "test": "jest", "clean": "rm -rf dist", - "build": "microbundle --no-sourcemap --external crypto", + "build": "microbundle --no-sourcemap", "dev": "microbundle watch", "prepare": "husky install" }, diff --git a/src/utils/sha256.ts b/src/utils/sha256.ts index 27ad003..83c9753 100644 --- a/src/utils/sha256.ts +++ b/src/utils/sha256.ts @@ -1,10 +1,5 @@ // from https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest export async function sha256(message: string | Uint8Array) { - let crypto = globalThis.crypto as Pick; - if (!crypto) { - crypto = await import("crypto"); - } - // encode as UTF-8 const msgBuffer = typeof message === "string" ? new TextEncoder().encode(message) : message;