Rename dev branch to v1 and next branch to v2

Committed via a GitHub action: https://github.com/tauri-apps/plugins-workspace/actions/runs/4869194441

Co-authored-by: FabianLars <FabianLars@users.noreply.github.com>
This commit is contained in:
FabianLars
2023-05-03 07:03:57 +00:00
committed by tauri-bot
commit 8facde5df5
50 changed files with 4428 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
node_modules

21
Cargo.toml Normal file
View File

@@ -0,0 +1,21 @@
[package]
name = "tauri-plugin-websocket"
version = "0.0.0"
authors.workspace = true
license.workspace = true
edition.workspace = true
rust-version.workspace = true
exclude = ["/examples"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
serde.workspace = true
serde_json.workspace = true
tauri.workspace = true
log.workspace = true
thiserror.workspace = true
rand = "0.8"
futures-util = "0.3"
tokio = { version = "1", features = ["net", "sync"] }
tokio-tungstenite = { version = "0.18", features = ["native-tls"] }

20
LICENSE.spdx Normal file
View File

@@ -0,0 +1,20 @@
SPDXVersion: SPDX-2.1
DataLicense: CC0-1.0
PackageName: tauri
DataFormat: SPDXRef-1
PackageSupplier: Organization: The Tauri Programme in the Commons Conservancy
PackageHomePage: https://tauri.app
PackageLicenseDeclared: Apache-2.0
PackageLicenseDeclared: MIT
PackageCopyrightText: 2019-2022, The Tauri Programme in the Commons Conservancy
PackageSummary: <text>Tauri is a rust project that enables developers to make secure
and small desktop applications using a web frontend.
</text>
PackageComment: <text>The package includes the following libraries; see
Relationship information.
</text>
Created: 2019-05-20T09:00:00Z
PackageDownloadLocation: git://github.com/tauri-apps/tauri
PackageDownloadLocation: git+https://github.com/tauri-apps/tauri.git
PackageDownloadLocation: git+ssh://github.com/tauri-apps/tauri.git
Creator: Person: Daniel Thompson-Yvetot

177
LICENSE_APACHE-2.0 Normal file
View File

@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

21
LICENSE_MIT Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 - Present Tauri Apps Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

71
README.md Normal file
View File

@@ -0,0 +1,71 @@
![plugin-websocket](banner.png)
<!-- description -->
## Install
_This plugin requires a Rust version of at least **1.64**_
There are three general methods of installation that we can recommend.
1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked)
2. Pull sources directly from Github using git tags / revision hashes (most secure)
3. Git submodule install this repo in your tauri project and then use file protocol to ingest the source (most secure, but inconvenient to use)
Install the Core plugin by adding the following to your `Cargo.toml` file:
`src-tauri/Cargo.toml`
```toml
[dependencies]
tauri-plugin-websocket = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" }
```
You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
> Note: Since most JavaScript package managers are unable to install packages from git monorepos we provide read-only mirrors of each plugin. This makes installation option 2 more ergonomic to use.
```sh
pnpm add https://github.com/tauri-apps/tauri-plugin-websocket
# or
npm add https://github.com/tauri-apps/tauri-plugin-websocket
# or
yarn add https://github.com/tauri-apps/tauri-plugin-websocket
```
## Usage
First you need to register the core plugin with Tauri:
`src-tauri/src/main.rs`
```rust
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_websocket::init())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
```
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
```javascript
import { WebSocket } from "tauri-plugin-websocket-api";
const ws = await WebSocket.connect("wss://example.com");
await ws.send("Hello World");
await ws.disconnect();
```
## Contributing
PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
## License
Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
MIT or MIT/Apache 2.0 where applicable.

BIN
banner.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

18
dist-js/index.d.ts vendored Normal file
View File

@@ -0,0 +1,18 @@
export interface MessageKind<T, D> {
type: T;
data: D;
}
export interface CloseFrame {
code: number;
reason: string;
}
export type Message = MessageKind<"Text", string> | MessageKind<"Binary", number[]> | MessageKind<"Ping", number[]> | MessageKind<"Pong", number[]> | MessageKind<"Close", CloseFrame | null>;
export default class WebSocket {
id: number;
private readonly listeners;
constructor(id: number, listeners: Array<(arg: Message) => void>);
static connect(url: string, options?: unknown): Promise<WebSocket>;
addListener(cb: (arg: Message) => void): void;
send(message: Message | string | number[]): Promise<void>;
disconnect(): Promise<void>;
}

55
dist-js/index.min.js vendored Normal file
View File

@@ -0,0 +1,55 @@
var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:!0});};
var f={};e(f,{convertFileSrc:()=>w,invoke:()=>c,transformCallback:()=>s});function u(){return window.crypto.getRandomValues(new Uint32Array(1))[0]}function s(e,r=!1){let n=u(),t=`_${n}`;return Object.defineProperty(window,t,{value:o=>(r&&Reflect.deleteProperty(window,t),e==null?void 0:e(o)),writable:!1,configurable:!0}),n}async function c(e,r={}){return new Promise((n,t)=>{let o=s(i=>{n(i),Reflect.deleteProperty(window,`_${a}`);},!0),a=s(i=>{t(i),Reflect.deleteProperty(window,`_${o}`);},!0);window.__TAURI_IPC__({cmd:e,callback:o,error:a,...r});})}function w(e,r="asset"){let n=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${r}.localhost/${n}`:`${r}://localhost/${n}`}
class WebSocket {
constructor(id, listeners) {
this.id = id;
this.listeners = listeners;
}
static async connect(url, options) {
const listeners = [];
const handler = (message) => {
listeners.forEach((l) => l(message));
};
return await c("plugin:websocket|connect", {
url,
callbackFunction: s(handler),
options,
}).then((id) => new WebSocket(id, listeners));
}
addListener(cb) {
this.listeners.push(cb);
}
async send(message) {
let m;
if (typeof message === "string") {
m = { type: "Text", data: message };
}
else if (typeof message === "object" && "type" in message) {
m = message;
}
else if (Array.isArray(message)) {
m = { type: "Binary", data: message };
}
else {
throw new Error("invalid `message` type, expected a `{ type: string, data: any }` object, a string or a numeric array");
}
return await c("plugin:websocket|send", {
id: this.id,
message: m,
});
}
async disconnect() {
return await this.send({
type: "Close",
data: {
code: 1000,
reason: "Disconnected by client",
},
});
}
}
export { WebSocket as default };
//# sourceMappingURL=index.min.js.map

1
dist-js/index.min.js.map Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"index.min.js","sources":["../../../node_modules/.pnpm/@tauri-apps+api@1.2.0/node_modules/@tauri-apps/api/chunk-FEIY7W7S.js","../../../node_modules/.pnpm/@tauri-apps+api@1.2.0/node_modules/@tauri-apps/api/chunk-RCPA6UVN.js","../guest-js/index.ts"],"sourcesContent":["var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:!0})};export{e as a};\n","import{a as d}from\"./chunk-FEIY7W7S.js\";var f={};d(f,{convertFileSrc:()=>w,invoke:()=>c,transformCallback:()=>s});function u(){return window.crypto.getRandomValues(new Uint32Array(1))[0]}function s(e,r=!1){let n=u(),t=`_${n}`;return Object.defineProperty(window,t,{value:o=>(r&&Reflect.deleteProperty(window,t),e==null?void 0:e(o)),writable:!1,configurable:!0}),n}async function c(e,r={}){return new Promise((n,t)=>{let o=s(i=>{n(i),Reflect.deleteProperty(window,`_${a}`)},!0),a=s(i=>{t(i),Reflect.deleteProperty(window,`_${o}`)},!0);window.__TAURI_IPC__({cmd:e,callback:o,error:a,...r})})}function w(e,r=\"asset\"){let n=encodeURIComponent(e);return navigator.userAgent.includes(\"Windows\")?`https://${r}.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MAAM,EAAE,wBAAwB;AACjC,aAAA;AACF,SAAA,CAAC,CAAC;KACJ;AACF;;;;","x_google_ignoreList":[0,1]}

53
dist-js/index.mjs Normal file
View File

@@ -0,0 +1,53 @@
import { invoke, transformCallback } from '@tauri-apps/api/tauri';
class WebSocket {
constructor(id, listeners) {
this.id = id;
this.listeners = listeners;
}
static async connect(url, options) {
const listeners = [];
const handler = (message) => {
listeners.forEach((l) => l(message));
};
return await invoke("plugin:websocket|connect", {
url,
callbackFunction: transformCallback(handler),
options,
}).then((id) => new WebSocket(id, listeners));
}
addListener(cb) {
this.listeners.push(cb);
}
async send(message) {
let m;
if (typeof message === "string") {
m = { type: "Text", data: message };
}
else if (typeof message === "object" && "type" in message) {
m = message;
}
else if (Array.isArray(message)) {
m = { type: "Binary", data: message };
}
else {
throw new Error("invalid `message` type, expected a `{ type: string, data: any }` object, a string or a numeric array");
}
return await invoke("plugin:websocket|send", {
id: this.id,
message: m,
});
}
async disconnect() {
return await this.send({
type: "Close",
data: {
code: 1000,
reason: "Disconnected by client",
},
});
}
}
export { WebSocket as default };
//# sourceMappingURL=index.mjs.map

1
dist-js/index.mjs.map Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"index.mjs","sources":["../guest-js/index.ts"],"sourcesContent":[null],"names":[],"mappings":";;AAmBc,MAAO,SAAS,CAAA;IAI5B,WAAY,CAAA,EAAU,EAAE,SAAwC,EAAA;AAC9D,QAAA,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;AACb,QAAA,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;KAC5B;AAED,IAAA,aAAa,OAAO,CAAC,GAAW,EAAE,OAAiB,EAAA;QACjD,MAAM,SAAS,GAAkC,EAAE,CAAC;AACpD,QAAA,MAAM,OAAO,GAAG,CAAC,OAAgB,KAAU;AACzC,YAAA,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;AACvC,SAAC,CAAC;AAEF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,aAAA;AACF,SAAA,CAAC,CAAC;KACJ;AACF;;;;"}

10
examples/svelte-app/.gitignore vendored Normal file
View File

@@ -0,0 +1,10 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

View File

@@ -0,0 +1,27 @@
{
"name": "svelte-app",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"tauri": "tauri"
},
"devDependencies": {
"@sveltejs/adapter-auto": "^2.0.0",
"@sveltejs/kit": "^1.15.5",
"@tauri-apps/cli": "^1.2.3",
"svelte": "^3.58.0",
"svelte-check": "^3.2.0",
"tslib": "^2.5.0",
"typescript": "^5.0.4",
"vite": "^4.2.1"
},
"dependencies": {
"tauri-plugin-websocket-api": "link:../../"
},
"type": "module"
}

View File

@@ -0,0 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/
WixTools
# These are backup files generated by rustfmt
**/*.rs.bk

3363
examples/svelte-app/src-tauri/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,23 @@
[workspace]
[package]
name = "app"
version = "0.1.0"
description = "A Tauri App"
edition = "2021"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tauri = { version = "1", features = [] }
tokio = { version = "1", features = ["net"] }
futures-util = "0.3"
tauri-plugin-websocket = { path = "../../../" }
tokio-tungstenite = "0.18"
[build-dependencies]
tauri-build = { version = "1", features = [] }
[features]
default = [ "custom-protocol" ]
custom-protocol = [ "tauri/custom-protocol" ]

View File

@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

View File

@@ -0,0 +1,13 @@
max_width = 100
hard_tabs = false
tab_spaces = 2
newline_style = "Auto"
use_small_heuristics = "Default"
reorder_imports = true
reorder_modules = true
remove_nested_parens = true
edition = "2018"
merge_derives = true
use_try_shorthand = false
use_field_init_shorthand = false
force_explicit_abi = true

View File

@@ -0,0 +1,38 @@
#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
use futures_util::StreamExt;
use tokio::net::{TcpListener, TcpStream};
async fn start_server() {
let addr = "127.0.0.1:8080".to_string();
// Create the event loop and TCP listener we'll accept connections on.
let try_socket = TcpListener::bind(&addr).await;
let listener = try_socket.expect("Failed to bind");
while let Ok((stream, _)) = listener.accept().await {
tokio::spawn(accept_connection(stream));
}
}
async fn accept_connection(stream: TcpStream) {
let ws_stream = tokio_tungstenite::accept_async(stream)
.await
.expect("Error during the websocket handshake occurred");
let (write, read) = ws_stream.split();
if let Err(e) = read.forward(write).await {
eprintln!("Error: {}", e);
}
}
fn main() {
tauri::async_runtime::spawn(start_server());
tauri::Builder::default()
.plugin(tauri_plugin_websocket::init())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

View File

@@ -0,0 +1,52 @@
{
"build": {
"distDir": "../dist",
"devPath": "http://localhost:5173/",
"beforeDevCommand": "pnpm dev",
"beforeBuildCommand": "pnpm build",
"withGlobalTauri": false
},
"tauri": {
"bundle": {
"active": true,
"targets": "all",
"identifier": "com.tauri.dev",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"resources": [],
"externalBin": [],
"copyright": "",
"category": "DeveloperTool",
"shortDescription": "",
"longDescription": "",
"deb": {
"depends": []
},
"macOS": {
"frameworks": [],
"minimumSystemVersion": "",
"exceptionDomain": ""
}
},
"allowlist": {
"all": false
},
"windows": [
{
"title": "Tauri App",
"width": 800,
"height": 600,
"resizable": true,
"fullscreen": false
}
],
"security": {
"csp": null
}
}
}

9
examples/svelte-app/src/app.d.ts vendored Normal file
View File

@@ -0,0 +1,9 @@
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
// and what to do when importing types
declare namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface Platform {}
}

View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" href="/global.css" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

View File

@@ -0,0 +1,35 @@
<script lang="ts">
import WebSocket from 'tauri-plugin-websocket-api'
import { onMount } from 'svelte'
let ws
let response = ''
let message = ''
onMount(async () => {
ws = await WebSocket.connect('ws://127.0.0.1:8080').then(r => {
_updateResponse('Connected')
return r
}).catch(_updateResponse)
ws.addListener(_updateResponse)
})
function _updateResponse(returnValue) {
response += (typeof returnValue === 'string' ? returnValue : JSON.stringify(returnValue)) + '<br>'
}
function send() {
ws.send(message).then(() => _updateResponse('Message sent')).catch(_updateResponse)
}
function disconnect() {
ws.disconnect().then(() => _updateResponse('Disconnected')).catch(_updateResponse)
}
</script>
<div>
<input bind:value={message}>
<button on:click={send}>Send</button>
<button on:click={disconnect}>Disconnect</button>
</div>
<div>{@html response}</div>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,68 @@
html,
body {
position: relative;
width: 100%;
height: 100%;
}
body {
color: #333;
margin: 0;
padding: 8px;
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
}
a {
color: rgb(0, 100, 200);
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
a:visited {
color: rgb(0, 80, 160);
}
label {
display: block;
}
input,
button,
select,
textarea {
font-family: inherit;
font-size: inherit;
-webkit-padding: 0.4em 0;
padding: 0.4em;
margin: 0 0 0.5em 0;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 2px;
}
input:disabled {
color: #ccc;
}
button {
color: #333;
background-color: #f4f4f4;
outline: none;
}
button:disabled {
color: #999;
}
button:not(:disabled):active {
background-color: #ddd;
}
button:focus {
border-color: #666;
}

View File

@@ -0,0 +1,15 @@
import adapter from "@sveltejs/adapter-auto";
import { vitePreprocess } from "@sveltejs/kit/vite";
/** @type {import('@sveltejs/kit').Config} */
const config = {
// Consult https://kit.svelte.dev/docs/integrations#preprocessors
// for more information about preprocessors
preprocess: vitePreprocess(),
kit: {
adapter: adapter(),
},
};
export default config;

View File

@@ -0,0 +1,17 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true
}
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}

View File

@@ -0,0 +1,8 @@
import { sveltekit } from "@sveltejs/kit/vite";
import type { UserConfig } from "vite";
const config: UserConfig = {
plugins: [sveltekit()],
};
export default config;

74
guest-js/index.ts Normal file
View File

@@ -0,0 +1,74 @@
import { invoke, transformCallback } from "@tauri-apps/api/tauri";
export interface MessageKind<T, D> {
type: T;
data: D;
}
export interface CloseFrame {
code: number;
reason: string;
}
export type Message =
| MessageKind<"Text", string>
| MessageKind<"Binary", number[]>
| MessageKind<"Ping", number[]>
| MessageKind<"Pong", number[]>
| MessageKind<"Close", CloseFrame | null>;
export default class WebSocket {
id: number;
private readonly listeners: Array<(arg: Message) => void>;
constructor(id: number, listeners: Array<(arg: Message) => void>) {
this.id = id;
this.listeners = listeners;
}
static async connect(url: string, options?: unknown): Promise<WebSocket> {
const listeners: Array<(arg: Message) => void> = [];
const handler = (message: Message): void => {
listeners.forEach((l) => l(message));
};
return await invoke<number>("plugin:websocket|connect", {
url,
callbackFunction: transformCallback(handler),
options,
}).then((id) => new WebSocket(id, listeners));
}
addListener(cb: (arg: Message) => void): void {
this.listeners.push(cb);
}
async send(message: Message | string | number[]): Promise<void> {
let m: Message;
if (typeof message === "string") {
m = { type: "Text", data: message };
} else if (typeof message === "object" && "type" in message) {
m = message;
} else if (Array.isArray(message)) {
m = { type: "Binary", data: message };
} else {
throw new Error(
"invalid `message` type, expected a `{ type: string, data: any }` object, a string or a numeric array"
);
}
return await invoke("plugin:websocket|send", {
id: this.id,
message: m,
});
}
async disconnect(): Promise<void> {
return await this.send({
type: "Close",
data: {
code: 1000,
reason: "Disconnected by client",
},
});
}
}

32
package.json Normal file
View File

@@ -0,0 +1,32 @@
{
"name": "tauri-plugin-websocket-api",
"version": "0.0.0",
"license": "MIT or APACHE-2.0",
"authors": [
"Tauri Programme within The Commons Conservancy"
],
"type": "module",
"browser": "dist-js/index.min.js",
"module": "dist-js/index.mjs",
"types": "dist-js/index.d.ts",
"exports": {
"import": "./dist-js/index.mjs",
"types": "./dist-js/index.d.ts",
"browser": "./dist-js/index.min.js"
},
"scripts": {
"build": "rollup -c"
},
"files": [
"dist-js",
"!dist-js/**/*.map",
"README.md",
"LICENSE"
],
"devDependencies": {
"tslib": "^2.5.0"
},
"dependencies": {
"@tauri-apps/api": "^1.2.0"
}
}

11
rollup.config.mjs Normal file
View File

@@ -0,0 +1,11 @@
import { readFileSync } from "fs";
import { createConfig } from "../../shared/rollup.config.mjs";
export default createConfig({
input: "guest-js/index.ts",
pkg: JSON.parse(
readFileSync(new URL("./package.json", import.meta.url), "utf8")
),
external: [/^@tauri-apps\/api/],
});

170
src/lib.rs Normal file
View File

@@ -0,0 +1,170 @@
use futures_util::{stream::SplitSink, SinkExt, StreamExt};
use serde::{ser::Serializer, Deserialize, Serialize};
use tauri::{
api::ipc::{format_callback, CallbackFn},
plugin::{Builder as PluginBuilder, TauriPlugin},
Manager, Runtime, State, Window,
};
use tokio::{net::TcpStream, sync::Mutex};
use tokio_tungstenite::{
connect_async_with_config,
tungstenite::{
protocol::{CloseFrame as ProtocolCloseFrame, WebSocketConfig},
Message,
},
MaybeTlsStream, WebSocketStream,
};
use std::collections::HashMap;
type Id = u32;
type WebSocket = WebSocketStream<MaybeTlsStream<TcpStream>>;
type WebSocketWriter = SplitSink<WebSocket, Message>;
type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, thiserror::Error)]
enum Error {
#[error(transparent)]
Websocket(#[from] tokio_tungstenite::tungstenite::Error),
#[error("connection not found for the given id: {0}")]
ConnectionNotFound(Id),
}
impl Serialize for Error {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.to_string().as_str())
}
}
#[derive(Default)]
struct ConnectionManager(Mutex<HashMap<Id, WebSocketWriter>>);
#[derive(Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConnectionConfig {
pub max_send_queue: Option<usize>,
pub max_message_size: Option<usize>,
pub max_frame_size: Option<usize>,
pub accept_unmasked_frames: bool,
}
impl From<ConnectionConfig> for WebSocketConfig {
fn from(config: ConnectionConfig) -> Self {
Self {
max_send_queue: config.max_send_queue,
max_message_size: config.max_message_size,
max_frame_size: config.max_frame_size,
accept_unmasked_frames: config.accept_unmasked_frames,
}
}
}
#[derive(Deserialize, Serialize)]
struct CloseFrame {
pub code: u16,
pub reason: String,
}
#[derive(Deserialize, Serialize)]
#[serde(tag = "type", content = "data")]
enum WebSocketMessage {
Text(String),
Binary(Vec<u8>),
Ping(Vec<u8>),
Pong(Vec<u8>),
Close(Option<CloseFrame>),
}
#[tauri::command]
async fn connect<R: Runtime>(
window: Window<R>,
url: String,
callback_function: CallbackFn,
config: Option<ConnectionConfig>,
) -> Result<Id> {
let id = rand::random();
let (ws_stream, _) = connect_async_with_config(url, config.map(Into::into)).await?;
tauri::async_runtime::spawn(async move {
let (write, read) = ws_stream.split();
let manager = window.state::<ConnectionManager>();
manager.0.lock().await.insert(id, write);
read.for_each(move |message| {
let window_ = window.clone();
async move {
if let Ok(Message::Close(_)) = message {
let manager = window_.state::<ConnectionManager>();
manager.0.lock().await.remove(&id);
}
let response = match message {
Ok(Message::Text(t)) => {
serde_json::to_value(WebSocketMessage::Text(t)).unwrap()
}
Ok(Message::Binary(t)) => {
serde_json::to_value(WebSocketMessage::Binary(t)).unwrap()
}
Ok(Message::Ping(t)) => {
serde_json::to_value(WebSocketMessage::Ping(t)).unwrap()
}
Ok(Message::Pong(t)) => {
serde_json::to_value(WebSocketMessage::Pong(t)).unwrap()
}
Ok(Message::Close(t)) => {
serde_json::to_value(WebSocketMessage::Close(t.map(|v| CloseFrame {
code: v.code.into(),
reason: v.reason.into_owned(),
})))
.unwrap()
}
Ok(Message::Frame(_)) => serde_json::Value::Null, // This value can't be recieved.
Err(e) => serde_json::to_value(Error::from(e)).unwrap(),
};
let js = format_callback(callback_function, &response)
.expect("unable to serialize websocket message");
let _ = window_.eval(js.as_str());
}
})
.await;
});
Ok(id)
}
#[tauri::command]
async fn send(
manager: State<'_, ConnectionManager>,
id: Id,
message: WebSocketMessage,
) -> Result<()> {
if let Some(write) = manager.0.lock().await.get_mut(&id) {
write
.send(match message {
WebSocketMessage::Text(t) => Message::Text(t),
WebSocketMessage::Binary(t) => Message::Binary(t),
WebSocketMessage::Ping(t) => Message::Ping(t),
WebSocketMessage::Pong(t) => Message::Pong(t),
WebSocketMessage::Close(t) => Message::Close(t.map(|v| ProtocolCloseFrame {
code: v.code.into(),
reason: std::borrow::Cow::Owned(v.reason),
})),
})
.await?;
Ok(())
} else {
Err(Error::ConnectionNotFound(id))
}
}
pub fn init<R: Runtime>() -> TauriPlugin<R> {
PluginBuilder::new("websocket")
.invoke_handler(tauri::generate_handler![connect, send])
.setup(|app| {
app.manage(ConnectionManager::default());
Ok(())
})
.build()
}

1
tsconfig.json Symbolic link
View File

@@ -0,0 +1 @@
../../shared/tsconfig.json