├── .gitignore ├── LICENSE ├── README.md ├── deno.json ├── deno.lock ├── example ├── main.ts └── worker.ts └── index.ts /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 TANIGUCHI Masaya 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # UnAsync 2 | 3 | Synchronously execute asynchronous functions on browsers, Node.js, and Deno. 4 | This package is a successor of [synckit](https://npmjs.com/package/synckit) and 5 | [sync-threads](https://npmjs.com/package/sync-threads). 6 | 7 | ## Usage 8 | 9 | https://jsr.io/@tani/unasync 10 | 11 | This package provides two functions `runAsWorker` and `createSyncFn`. 12 | 13 | 1. Wrap an asynchronous function by `runAsWorker` 14 | 2. Create a synchronous function by `createSyncFn` 15 | 16 | ```js 17 | //worker.js 18 | import { runAsWorker } from "unasync"; 19 | runAsWorker(async (x) => { 20 | await new Promise((resolve) => setTimeout(() => resolve(1), 1000)); 21 | return x + 1; 22 | }); 23 | ``` 24 | 25 | ```js 26 | //main.js 27 | import { createSyncFn } from "unasync"; 28 | using syncFn = createSyncFn(import.meta.resolve("./worker.js")); 29 | console.log(syncFn(1)); // 2 30 | ``` 31 | 32 | ## Technical Details 33 | 34 | In the modern JavaScript platform, we can use shared memory `SharedArrayBuffer`. 35 | we employ it as a semaphore. First, we lock the semaphore to suspend the main 36 | thread and run the asyncrhonous function in the worker thread. After the 37 | execution, we unlock the semaphore to resume the main thread. 38 | 39 | The strong point of this idea, we do not need to modify event-loop in the target 40 | virtual machine by FFI. 41 | 42 | ## Copyright and License 43 | 44 | (c) 2024 TANIGUCHI Masaya, MIT License 45 | -------------------------------------------------------------------------------- /deno.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@tani/unasync", 3 | "version": "1.0.1", 4 | "exports": "./index.ts", 5 | "imports": { 6 | "@apacheli/web-workers": "npm:@apacheli/web-workers@^2.0.0", 7 | "flatted": "npm:flatted@^3.3.2" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /deno.lock: -------------------------------------------------------------------------------- 1 | { 2 | "version": "4", 3 | "specifiers": { 4 | "npm:@apacheli/web-workers@2": "2.0.0", 5 | "npm:flatted@^3.3.2": "3.3.2" 6 | }, 7 | "npm": { 8 | "@apacheli/web-workers@2.0.0": { 9 | "integrity": "sha512-we156R+GAZodBz4By9jcRmhJdg+fkr9tZ58ptP0m98yhi64p6lqtM5Nc1P81A/cblWaD52mWJOSI8XKZF4Q6yQ==" 10 | }, 11 | "flatted@3.3.2": { 12 | "integrity": "sha512-AiwGJM8YcNOaobumgtng+6NHuOqC3A7MixFeDafM3X9cIUM+xUXoS5Vfgf+OihAYe20fxqNM9yPBXJzRtZ/4eA==" 13 | } 14 | }, 15 | "workspace": { 16 | "dependencies": [ 17 | "npm:@apacheli/web-workers@2", 18 | "npm:flatted@^3.3.2" 19 | ] 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /example/main.ts: -------------------------------------------------------------------------------- 1 | import { createSyncFn } from "../index.ts"; 2 | { 3 | using syncFn = createSyncFn(import.meta.resolve("./worker.ts")); 4 | console.log(syncFn(1)); 5 | } 6 | -------------------------------------------------------------------------------- /example/worker.ts: -------------------------------------------------------------------------------- 1 | import { runAsWorker } from "../index.ts"; 2 | runAsWorker(async (x) => { 3 | await new Promise((resolve) => setTimeout(() => resolve(1), 1000)); 4 | return x + 1; 5 | }); 6 | -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- 1 | // (c) 2024 TANIGUCHI Masaya https://git.io/mit-license. 2 | import * as flatted from "flatted"; 3 | import { Worker } from "@apacheli/web-workers"; 4 | 5 | type SyncFn = (...args: unknown[]) => unknown 6 | type AsyncFn = (...args: unknown[]) => Promise 7 | 8 | /** 9 | * @param {string | URL} filename 10 | * @param {number} bufferSize 11 | * @returns {SyncFn & Disposable} 12 | */ 13 | export function createSyncFn( 14 | filename: string | URL, 15 | bufferSize: number = 64 * 1024, 16 | ): SyncFn & Disposable { 17 | const worker = new Worker(filename, { type: "module" }); 18 | const syncFn: SyncFn & Disposable = (...args: unknown[]): unknown => { 19 | const buffer = new SharedArrayBuffer(bufferSize); 20 | const semaphore = new Int32Array(buffer); 21 | worker.postMessage({ args, buffer }); 22 | worker.addEventListener("error", (err) => { 23 | throw err; 24 | }); 25 | Atomics.wait(semaphore, 0, 0); 26 | let length = semaphore[0]; 27 | let didThrow = false; 28 | if (length < 0) { 29 | didThrow = true; 30 | length *= -1; 31 | } 32 | const decoder = new TextDecoder(); 33 | const binary = new Uint8Array(buffer).slice(4, 4 + length); 34 | const data = flatted.parse(decoder.decode(binary)); 35 | if (didThrow) { 36 | throw data; 37 | } 38 | return data; 39 | }; 40 | syncFn[Symbol.dispose] = () => { 41 | worker.terminate(); 42 | }; 43 | return syncFn; 44 | } 45 | 46 | /** 47 | * @param {AsyncFn} workerAsyncFn 48 | */ 49 | export function runAsWorker( 50 | workerAsyncFn: AsyncFn 51 | ) { 52 | addEventListener("message", async (ev: any) => { 53 | const { args, buffer } = ev.data; 54 | let data, didThrow = false; 55 | try { 56 | data = await workerAsyncFn(...args); 57 | } catch (err) { 58 | data = err; 59 | didThrow = true; 60 | } 61 | const encoder = new TextEncoder(); 62 | const binary = encoder.encode(flatted.stringify(data)); 63 | new Uint8Array(buffer).set(binary, 4); 64 | const semaphore = new Int32Array(buffer); 65 | Atomics.store(semaphore, 0, didThrow ? -binary.length : binary.length); 66 | Atomics.notify(semaphore, 0); 67 | }); 68 | } 69 | --------------------------------------------------------------------------------