Skip to content

Commit

Permalink
inline wasm/workers for seamless integration
Browse files Browse the repository at this point in the history
  • Loading branch information
dskvr committed Oct 25, 2024
1 parent 16ce641 commit e3556fc
Show file tree
Hide file tree
Showing 37 changed files with 5,971 additions and 3,735 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
tmp/
dist/
node_modules
rust
rust
src/wasm
106 changes: 61 additions & 45 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
# notemine js
# note⛏️ (js)

![build](https://img.shields.io/npm/v/notemine)
![build](https://github.com/github/docs/actions/workflows/main.yml/badge.svg)
![test](https://github.com/github/docs/actions/workflows/main.yml/badge.svg)
![coverage](https://github.com/github/docs/actions/workflows/main.yml/badge.svg)
[![npm](https://img.shields.io/npm/v/notemine)]( https://www.npmjs.com/package/notemine )
[![build](https://github.com/sandwichfarm/notemine-js/actions/workflows/build.yaml/badge.svg)]( https://github.com/sandwichfarm/notemine-js/actions/workflows/build.yaml )
[![test](https://github.com/sandwichfarm/notemine-js/actions/workflows/test.yaml/badge.svg)]( https://github.com/sandwichfarm/notemine-js/actions/workflows/test.yaml )

a module for implementing [notemine](https://github.com/sandwichfarm/notemine) wasm nostr event miner in modern web applications with observables.
`notemine` is a typescript module that wraps [notemine](https://github.com/sandwichfarm/notemine) `wasm-bindgen` interfaces. More convenient and has added observables for more consistent use throughout modern web stacks.

## install
package name: `notemine`
Expand Down Expand Up @@ -42,31 +41,31 @@ _untested_
const tags = [ "#t", "introduction"]
const pubkey = "e771af0b05c8e95fcdf6feb3500544d2fb1ccd384788e9f490bb3ee28e8ed66f"

//set options for miner
//set options for notemine
const difficulty = 21
const numberOfWorkers = 7


const noteminer = new Noteminer({
const notemine = new Notemine({
content,
tags,
difficulty,
numberOfWorkers
})

//you can also set content, tags and pubkey via assessors after initialization.
noteminer.pubkey = pubkey
notemine.pubkey = pubkey

//start miner
noteminer.mine()
//start notemine
notemine.mine()
```

Updates to noteminer can be accessed via observables.
Updates to notemine can be accessed via observables.
```
noteminer.progress$
noteminer.error$
noteminer.progress$
noteminer.progress$
notemine.progress$
notemine.error$
notemine.cancelled$
notemine.success$
```


Expand All @@ -78,29 +77,40 @@ noteminer.progress$
<script lang="ts">
import { onMount } from 'svelte';
import { type Writable, writable } from 'svelte/store'
import { type ProgressEvent, NostrMiner } from 'nostr-miner';
import { type ProgressEvent, Notemine } from 'notemine';
const numberOfMiners = 8
let miner: NostrMiner;
let notemine: Notemine;
let progress: Writable<ProgressEvent[]> = new writable(new Array(numberOfMiners))
let success: Writeable<SuccessEvent> = new writable(null)
onMount(() => {
miner = new NostrMiner({ content: 'Hello, Nostr!', numberOfMiners });
notemine = new Notemine({ content: 'Hello, Nostr!', numberOfMiners });
const subscription = miner.progress$.subscribe(progress_ => {
const progress$ = miner.progress$.subscribe(progress_ => {
progress.update( _progress => {
_progress[progress_.workerId] = progress_
return _progress
})
});
miner.mine();
const success$ = miner.progress$.subscribe(success_ => {
const {event, totalTime, hashRate}
success.update( _success => {
_success = success_
return _success
})
miner.cancel();
});
notemine.mine();
return () => {
subscription.unsubscribe();
progress$.unsubscribe();
success$.unsubscribe();
miner.cancel();
};
});
$: miners = $progress
</script>
Expand All @@ -110,6 +120,12 @@ noteminer.progress$
<span>Miner #{miner.workerId}: {miner.hashRate}kH/s [Best PoW: ${miner.bestPowData}]
{/each}
{#if($success !== null)}
<pre>
{$success.event}
</pre>
{/if}
</div>
```
</details>
Expand All @@ -121,21 +137,21 @@ noteminer.progress$

```reactjs
import React, { useEffect } from 'react';
import { NostrMiner } from 'nostr-miner';
import { Notemine } from 'notemine';
const MyComponent = () => {
const miner = new NostrMiner({ content: 'Hello, Nostr!' });
const notemine = new Notemine({ content: 'Hello, Nostr!' });
useEffect(() => {
const subscription = miner.progress$.subscribe(progress => {
// Update progress bar or display miner's progress
const subscription = notemine.progress$.subscribe(progress => {
// Update progress bar or display notemine's progress
});
miner.mine();
notemine.mine();
return () => {
subscription.unsubscribe();
miner.cancel();
notemine.cancel();
};
}, []);
Expand All @@ -161,23 +177,23 @@ noteminer.progress$
<script lang="ts">
import { defineComponent, onMounted, onUnmounted } from 'vue';
import { NostrMiner } from 'nostr-miner';
import { Notemine } from 'notemine';
export default defineComponent({
name: 'MinerComponent',
setup() {
const miner = new NostrMiner({ content: 'Hello, Nostr!' });
const notemine = new Notemine({ content: 'Hello, Nostr!' });
onMounted(() => {
const subscription = miner.progress$.subscribe(progress => {
// Update progress bar or display miner's progress
const subscription = notemine.progress$.subscribe(progress => {
// Update progress bar or display notemine's progress
});
miner.mine();
notemine.mine();
onUnmounted(() => {
subscription.unsubscribe();
miner.cancel();
notemine.cancel();
});
});
Expand All @@ -194,29 +210,29 @@ export default defineComponent({

```javascript
import { Component, OnInit, OnDestroy } from '@angular/core';
import { NostrMiner } from 'nostr-miner';
import { Notemine } from 'notemine';
import { Subscription } from 'rxjs';

@Component({
selector: 'app-miner',
templateUrl: './miner.component.html',
selector: 'app-notemine',
templateUrl: './notemine.component.html',
})
export class MinerComponent implements OnInit, OnDestroy {
miner: NostrMiner;
notemine: Notemine;
progressSubscription: Subscription;

ngOnInit() {
this.miner = new NostrMiner({ content: 'Hello, Nostr!' });
this.progressSubscription = this.miner.progress$.subscribe(progress => {
// Update progress bar or display miner's progress
this.notemine = new Notemine({ content: 'Hello, Nostr!' });
this.progressSubscription = this.notemine.progress$.subscribe(progress => {
// Update progress bar or display notemine's progress
});

this.miner.mine();
this.notemine.mine();
}

ngOnDestroy() {
this.progressSubscription.unsubscribe();
this.miner.cancel();
this.notemine.cancel();
}
}
```
Expand Down Expand Up @@ -302,4 +318,4 @@ Build the package with `build`
```bash
yarn build
```
</details>
</details>
Empty file added build-worker.js
Empty file.
137 changes: 137 additions & 0 deletions build.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

import getPort from 'get-port';
import esbuild from 'esbuild';
import { clean } from 'esbuild-plugin-clean';
import esbuildPluginTsc from 'esbuild-plugin-tsc';
import inlineWorkerPlugin from 'esbuild-plugin-inline-worker';
import { polyfillNode } from 'esbuild-plugin-polyfill-node';
import { wasmLoader } from 'esbuild-plugin-wasm';
import copy from 'esbuild-plugin-copy';
import { minify } from 'terser';

import { handleWasmUrl } from './handleWasmUrl.cjs';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const production = process.env.NODE_ENV === 'production';

export async function buildWithWatch() {
await fs.mkdir(path.resolve(__dirname, 'dist'), { recursive: true });
const watch = !production;
const livereloadPort = await getPort({ port: 53100 });

const workerBuildOptions = {
entryPoints: ['src/mine.worker.ts'],
bundle: true,
format: 'iife',
platform: 'browser',
target: ['esnext'],
minify: true,
plugins: [
handleWasmUrl,
wasmLoader(),
],
loader: {
'.ts': 'ts',
'.js': 'js',
'.wasm': 'file',
},
define: {
'import.meta.url': 'self.location.href',
},
outdir: 'dist',
write: true,
};

let workerResult;
try {
workerResult = await esbuild.build(workerBuildOptions);
} catch (error) {
console.error('Worker build failed:', error);
process.exit(1);
}

if (!workerResult || workerResult.errors?.length > 0) {
console.error('Worker build output is missing or contains errors.');
process.exit(1);
}

const workerFilePath = path.resolve(__dirname, 'dist', 'mine.worker.js');
const workerCode = await fs.readFile(workerFilePath, 'utf8');
const minifiedWorkerCode = await minify(workerCode);

if (minifiedWorkerCode.error) {
console.error('Terser minification failed:', minifiedWorkerCode.error);
process.exit(1);
}

await fs.writeFile(workerFilePath, minifiedWorkerCode.code);

const distPath = path.resolve(__dirname, 'dist');
await fs.mkdir(distPath, { recursive: true });

const mainBuildOptions = {
entryPoints: ['src/index.ts'],
outdir: 'dist',
bundle: true,
splitting: true,
format: 'esm',
platform: 'browser',
target: ['esnext'],
sourcemap: true,
minify: production,
plugins: [
esbuildPluginTsc({
force: true,
}),
handleWasmUrl,
inlineWorkerPlugin({
entryPoints: ['dist/mine.worker.js'],
minify: true,
target: 'esnext',
format: 'iife',
}),
polyfillNode({
polyfills: {
fs: false,
path: false,
util: true,
assert: true,
stream: true,
os: true,
},
}),
copy({
assets: {
from: '../node_modules/notemine/notemine_bg.wasm',
to: 'dist',
},
}),
].filter(Boolean),
loader: {
'.ts': 'ts',
'.js': 'js',
'.wasm': 'file',
},
define: {
'import.meta.url': 'self.location.href',
},
};

try {
if (watch) {
const mainContext = await esbuild.context(mainBuildOptions);
await mainContext.watch();
} else {
await esbuild.build(mainBuildOptions);
}
} catch (error) {
console.error('Main build failed:', error);
process.exit(1);
}
}

buildWithWatch();
5 changes: 5 additions & 0 deletions demo/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rules": {
"jsx-a11y/rule-name": "off"
}
}
4 changes: 4 additions & 0 deletions demo/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/node_modules/
/public/build/

.DS_Store
Loading

0 comments on commit e3556fc

Please sign in to comment.