Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: unadlib/data-transport
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: v4.3.6
Choose a base ref
...
head repository: unadlib/data-transport
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: master
Choose a head ref
  • 10 commits
  • 15 files changed
  • 1 contributor

Commits on Sep 8, 2024

  1. Copy the full SHA
    d5fef5f View commit details
  2. Copy the full SHA
    82f5bc9 View commit details

Commits on Dec 12, 2024

  1. Copy the full SHA
    2cff9b2 View commit details
  2. chore(deps): upgrade dev deps

    unadlib committed Dec 12, 2024
    Copy the full SHA
    f848cef View commit details
  3. ci(action): update ci config

    unadlib committed Dec 12, 2024
    Copy the full SHA
    a8ccd8a View commit details

Commits on Jan 1, 2025

  1. Copy the full SHA
    6607495 View commit details

Commits on Jan 2, 2025

  1. Copy the full SHA
    742c994 View commit details
  2. Copy the full SHA
    f46866d View commit details

Commits on Jan 11, 2025

  1. Copy the full SHA
    0df947f View commit details

Commits on Jan 20, 2025

  1. docs(readme): update

    unadlib committed Jan 20, 2025
    Copy the full SHA
    a8b5894 View commit details
2 changes: 1 addition & 1 deletion .github/workflows/nodejs.yml
Original file line number Diff line number Diff line change
@@ -9,7 +9,7 @@ jobs:

strategy:
matrix:
node-version: [18.x, 20.x]
node-version: [18.x, 20.x, 22.x]

steps:
- uses: actions/checkout@v1
2 changes: 1 addition & 1 deletion .github/workflows/npm-publish.yml
Original file line number Diff line number Diff line change
@@ -12,7 +12,7 @@ jobs:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18.x'
node-version: '20.x'
registry-url: 'https://registry.npmjs.org'
- run: yarn
- run: yarn build
13 changes: 9 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -3,17 +3,19 @@
![Node CI](https://github.com/unadlib/data-transport/workflows/Node%20CI/badge.svg)
[![npm version](https://badge.fury.io/js/data-transport.svg)](http://badge.fury.io/js/data-transport)

A simple and responsible transport
A simple and responsive transport

## Motivation

Many front-end communication APIs based on JavaScript are almost one-way communication, and their communication interface are often different. In terms of communication interaction protocols, we need an universal and responsive communication library that will help us communicate in any scenario very simply and easily.
Many front-end communication APIs based on JavaScript are almost one-way communication, and their communication interface are often different. In terms of communication interaction protocols, we need an universal and responsive communication library that will help us communicate in any scenario very simply and easily.

And It is also very easy to mock to be used for testing, and it is also easy to design an common interface that is compatible with multiple communication APIs.

You can use `data-transport` to communicate between different front-end communication APIs.

## Support Transport

`data-transport` is a generic and responsible communication transporter
`data-transport` is a generic and responsive communication transporter

- iframe
- Broadcast
@@ -90,5 +92,8 @@ expect(await internal.emit('hello', 42).toEqual({ text: 'hello 42' });
## Example
- [More examples](./examples)
- [Online with Broadcast](https://codesandbox.io/s/data-transport-example-lkg8k)
## License
[MIT](./LICENSE)
4 changes: 4 additions & 0 deletions examples/browser-extension/src/background/index.ts
Original file line number Diff line number Diff line change
@@ -37,6 +37,10 @@ transport.onConnect((id) => {
console.log('connect:', id);
});

transport.onDisconnect((id) => {
console.log('disconnect:', id);
});

// @ts-ignore
transport.listen('contentToBg', async (a, b) => a);

3 changes: 3 additions & 0 deletions examples/webrtc/src/index.ts
Original file line number Diff line number Diff line change
@@ -29,6 +29,9 @@ const init = () => {
const peer = new SimplePeer({
initiator: true,
trickle: false,
config: {
iceServers: [],
}
});

peer.on('signal', (data) => {
3 changes: 3 additions & 0 deletions examples/webrtc/src/other.ts
Original file line number Diff line number Diff line change
@@ -22,6 +22,9 @@ const init = () => {
const peer = new SimplePeer({
initiator: false,
trickle: false,
config: {
iceServers: [],
}
});

peer.on('signal', (data) => {
19 changes: 13 additions & 6 deletions examples/webworker/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { WorkerTransport, listen } from 'data-transport';
import { WorkerTransport, listen, createTransport } from 'data-transport';
import { Worker, Main } from './interface';

class MainTransport
extends WorkerTransport.Main<{ emit: Main }>
implements Worker {
implements Worker
{
async help() {
const response = await this.emit('help', { text: 'SOS!!!' });
return response;
@@ -21,13 +22,19 @@ class MainTransport

const worker = new Worker('worker.bundle.js');

(window as any).mainTransport = new MainTransport({
worker,
});

document.getElementById('btn')?.addEventListener('click', async () => {
const response = await (window as any).mainTransport.help();
const div = document.createElement('div');
div.innerText = `${new Date()}: ${JSON.stringify(response)}`;
document.body.appendChild(div);
});

// mock async init worker
setTimeout(() => {
(window as any).mainTransport = new MainTransport({
worker,
});
(window as any).mainTransport.onConnect(() => {
console.log('connected');
});
}, 1000);
9 changes: 8 additions & 1 deletion examples/webworker/src/worker.ts
Original file line number Diff line number Diff line change
@@ -18,4 +18,11 @@ class WebWorkerTransport
}
}

(self as any).webWorkerTransport = new WebWorkerTransport();
// mock async init worker
setTimeout(() => {
(self as any).webWorkerTransport = new WebWorkerTransport();

(self as any).webWorkerTransport.onConnect(() => {
console.log('connected');
});
}, 2000);
24 changes: 12 additions & 12 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "data-transport",
"version": "4.3.6",
"description": "A simple and responsible transport",
"version": "4.5.1",
"description": "A simple and responsive transport",
"main": "lib/index.js",
"unpkg": "dist/index.umd.js",
"types": "dist/index.d.ts",
@@ -41,31 +41,31 @@
"@rollup/plugin-commonjs": "^15.0.0",
"@rollup/plugin-node-resolve": "^9.0.0",
"@rollup/plugin-replace": "^2.3.3",
"@rollup/plugin-terser": "^0.4.4",
"@types/chrome": "^0.0.193",
"@types/firefox-webext-browser": "^94.0.1",
"@types/jest": "^27.4.0",
"@types/node": "^14.6.0",
"@types/simple-peer": "^9.6.0",
"@types/uuid": "^8.3.0",
"@typescript-eslint/eslint-plugin": "^7.4.0",
"@typescript-eslint/parser": "^7.4.0",
"@typescript-eslint/eslint-plugin": "^8.18.0",
"@typescript-eslint/parser": "^8.18.0",
"commitizen": "^4.3.0",
"electron": "^23.1.4",
"eslint": "^8.36.0",
"eslint": "^9.16.0",
"eslint-config-airbnb": "^19.0.4",
"eslint-config-prettier": "^8.7.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-prettier": "^4.2.1",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-prettier": "^5.2.1",
"jest": "^29.5.0",
"jest-environment-jsdom": "^29.5.0",
"prettier": "^2.8.5",
"rimraf": "^3.0.2",
"rollup": "^2.26.5",
"rollup-plugin-terser": "^7.0.0",
"ts-jest": "^29.1.0",
"ts-node": "^10.9.1",
"tslib": "^2.5.0",
"typescript": "^5.4.3",
"ts-node": "^10.9.2",
"tslib": "^2.8.1",
"typescript": "^5.7.2",
"yargs": "^15.1.0"
},
"config": {
2 changes: 1 addition & 1 deletion rollup.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import replace from '@rollup/plugin-replace';
import { terser } from 'rollup-plugin-terser';
import terser from '@rollup/plugin-terser';
import pkg from './package.json';

const isProduction = process.env.NODE_ENV === 'production';
12 changes: 6 additions & 6 deletions src/createTransport.ts
Original file line number Diff line number Diff line change
@@ -56,8 +56,8 @@ export interface TransportOptionsMap {
ElectronRenderer: ElectronRendererTransportOptions;
ServiceWorkerClient: ServiceWorkerClientTransportOptions;
ServiceWorkerService: ServiceWorkerServiceTransportOptions;
WorkerMain: WorkerMainTransportOptions;
WorkerInternal: WorkerInternalTransportOptions;
WebWorkerClient: WorkerMainTransportOptions;
WebWorkerInternal: WorkerInternalTransportOptions;
WebRTC: WebRTCTransportOptions;
Broadcast: BroadcastTransportOptions;
SharedWorkerClient: SharedWorkerClientTransportOptions;
@@ -77,8 +77,8 @@ export interface Transports {
SharedWorkerInternal: SharedWorkerInternalTransport;
ServiceWorkerClient: ServiceWorkerClientTransport;
ServiceWorkerService: ServiceWorkerServiceTransport;
WorkerMain: WorkerMainTransport;
WorkerInternal: WorkerInternalTransport;
WebWorkerClient: WorkerMainTransport;
WebWorkerInternal: WorkerInternalTransport;
BrowserExtensions: BrowserExtensionsGenericTransport;
BrowserExtensionsMain: BrowserExtensionsMainTransport;
BrowserExtensionsClient: BrowserExtensionsClientTransport;
@@ -102,8 +102,8 @@ export const TransportMap = {
ElectronRenderer: ElectronTransport.Renderer,
ServiceWorkerClient: ServiceWorkerTransport.Client,
ServiceWorkerService: ServiceWorkerTransport.Service,
WorkerMain: WorkerTransport.Main,
WorkerInternal: WorkerTransport.Worker,
WebWorkerClient: WorkerTransport.Main,
WebWorkerInternal: WorkerTransport.Worker,
WebRTC: WebRTCTransport,
Broadcast: BroadcastTransport,
SharedWorkerClient: SharedWorkerTransport.Client,
3 changes: 3 additions & 0 deletions src/transports/browserExtensionsTransport.ts
Original file line number Diff line number Diff line change
@@ -163,6 +163,9 @@ export abstract class BrowserExtensionsMainTransport<
this.ports.delete(id);
}
});
this._onDisconnectCallback.forEach((callback) => {
callback(id);
});
});

// @ts-ignore
74 changes: 74 additions & 0 deletions src/transports/workerTransport.ts
Original file line number Diff line number Diff line change
@@ -10,6 +10,10 @@ import { Transport } from '../transport';
// workaround: `tsc --skipLibCheck`.
declare var self: WorkerGlobalScope;

type ClientCallback = () => void | Promise<void>;

const connectEventName = 'worker-connect';

export interface WorkerMainTransportOptions
extends Partial<TransportOptions<TransferableWorker>> {
/**
@@ -50,6 +54,41 @@ export abstract class WorkerMainTransport<
listener,
sender,
});

this.emit({
// @ts-ignore
name: connectEventName,
respond: true,
silent: true,
}).then(this._handleConnectCallbacks);

// @ts-ignore
this.listen(connectEventName, this._handleConnectCallbacks);
}

private _connected = false;

private _handleConnectCallbacks = async () => {
if (this._connected) {
return;
}
this._connected = true;
this._onConnectCallback.forEach((callback) => {
callback();
});
this._onConnectCallback.clear();
};

private _onConnectCallback = new Set<ClientCallback>();

onConnect(callback: ClientCallback) {
if (this._connected) {
return callback();
}
this._onConnectCallback.add(callback);
return () => {
this._onConnectCallback.delete(callback);
};
}
}

@@ -79,6 +118,41 @@ export abstract class WorkerInternalTransport<
listener,
sender,
});

this.emit({
// @ts-ignore
name: connectEventName,
respond: true,
silent: true,
}).then(this._handleConnectCallbacks);

// @ts-ignore
this.listen(connectEventName, this._handleConnectCallbacks);
}

private _handleConnectCallbacks = async () => {
if (this._connected) {
return;
}
this._connected = true;
this._onConnectCallback.forEach((callback) => {
callback();
});
this._onConnectCallback.clear();
};

private _connected = false;

private _onConnectCallback = new Set<ClientCallback>();

onConnect(callback: ClientCallback) {
if (this._connected) {
return callback();
}
this._onConnectCallback.add(callback);
return () => {
this._onConnectCallback.delete(callback);
};
}
}

4 changes: 2 additions & 2 deletions test/createTransport.test.ts
Original file line number Diff line number Diff line change
@@ -26,8 +26,8 @@ test('base merge transport by main', async () => {
'ElectronRenderer',
'ServiceWorkerClient',
'ServiceWorkerService',
'WorkerMain',
'WorkerInternal',
'WebWorkerClient',
'WebWorkerInternal',
'WebRTC',
'Broadcast',
'SharedWorkerClient',
Loading