@gjsify/webserial 0.0.0-stage → 0.64.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,69 @@
1
- # Temporary Holding Version
1
+ # @gjsify/webserial
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The [Web Serial API](https://wicg.github.io/serial/) for GJS: `Serial`, `SerialPort` and `navigator.serial`, with streams for reading and writing. The Linux backend opens a **classic Bluetooth serial port** (RFCOMM, Serial Port Profile) through BlueZ. It needs no `rfcomm` binary and no `/dev/rfcomm*` node.
4
+
5
+ Part of the [gjsify](https://github.com/gjsify/gjsify) project — Node.js and Web APIs for GJS (GNOME JavaScript).
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ gjsify install @gjsify/webserial
11
+
12
+ # npm or yarn also work (e.g. adding it to an existing project):
13
+ npm install @gjsify/webserial
14
+ yarn add @gjsify/webserial
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ Pair and trust the device first (`bluetoothctl pair <mac>`, `bluetoothctl trust <mac>`). Most devices accept one connection at a time, so disconnect a phone before opening the port.
20
+
21
+ ```typescript
22
+ import { BluezRfcommSource, Serial } from '@gjsify/webserial';
23
+
24
+ const serial = new Serial(new BluezRfcommSource());
25
+
26
+ const [port] = await serial.getPorts(); // bonded devices that offer a serial port
27
+ await port.open({ baudRate: 115200 }); // a Bluetooth link ignores the rate
28
+
29
+ const writer = port.writable!.getWriter();
30
+ await writer.write(new Uint8Array([0x1f, 0x11, 0x38]));
31
+ writer.releaseLock();
32
+
33
+ await port.close();
34
+ ```
35
+
36
+ `requestPort()` takes the same filters as the browser API. A GJS program has no chooser dialog, so pass your own to the `Serial` constructor; the default takes the first candidate:
37
+
38
+ ```typescript
39
+ const serial = new Serial(new BluezRfcommSource(), {
40
+ chooser: async (candidates) => candidates.find((c) => c.name === 'P12Pro') ?? null,
41
+ });
42
+ const port = await serial.requestPort({ filters: [{ bluetoothServiceClassId: '00001101-0000-1000-8000-00805f9b34fb' }] });
43
+ ```
44
+
45
+ ### Globals
46
+
47
+ ```typescript
48
+ import '@gjsify/webserial/register'; // or let `--globals auto` do it
49
+ ```
50
+
51
+ sets `navigator.serial`, `Serial` and `SerialPort`, and never replaces ones a runtime already has.
52
+
53
+ ### Other platforms
54
+
55
+ The backend sits behind the small `PortSource` interface (`available`, `list`, `connect`, optional `subscribe`). `FakeSource` implements it in memory for tests; another driver (USB serial, macOS IOBluetooth) only has to provide the same four calls.
56
+
57
+ ## What is not implemented
58
+
59
+ - Control signals: `setSignals()` and `getSignals()` throw `NotSupportedError`. A Bluetooth serial link has none.
60
+ - USB serial ports.
61
+ - Baud rate, parity and flow control are accepted and ignored on the RFCOMM link.
62
+
63
+ ## Verification
64
+
65
+ The BlueZ recipe was measured against a real Bluetooth label printer: the initialisation exchange answered on all six packets, and a printed label followed. `FakeSource` covers the stream and error behaviour in the unit tests; no CI runner has a Bluetooth device.
66
+
67
+ ## License
68
+
69
+ MIT
@@ -0,0 +1 @@
1
+ var e=Object.defineProperty,__name=(t,n)=>e(t,`name`,{value:n,configurable:!0});export{__name};
@@ -0,0 +1,11 @@
1
+ import"./_virtual/_rolldown/runtime.js";import{serialError as e}from"./errors.js";import{canonicalUuid as t}from"./filter.js";import n from"gi://Gio?version=2.0";import r from"gi://GioUnix?version=2.0";import i from"gi://GLib?version=2.0";const a=`00001101-0000-1000-8000-00805f9b34fb`,o=`org.bluez`,s=`org.bluez.Device1`,c=`org.freedesktop.DBus.ObjectManager`,l=`org.bluez.ProfileManager1`,promisify=e=>new Promise(e);function addressOf(e){return e.slice(e.lastIndexOf(`dev_`)+4).replaceAll(`_`,`:`)}var BluezRfcommSource=class{#e;#t;#n;#r;#i;#a;#o=0;constructor(e={}){this.#e=t(e.serviceClass??`00001101-0000-1000-8000-00805f9b34fb`),this.#t=e.connectTimeoutMs??3e4,this.#n=e.includeUnpaired??!1,this.#r=e.profileName??`gjsify-webserial`,this.#i=e.profilePathPrefix??`/org/gjsify/webserial/profile`,this.#a=e.bus??null}async#s(e){return(await this.#l(e,`/`,c,`GetManagedObjects`,null)).get_child_value(0).recursiveUnpack()}async#c(){return this.#a||=await promisify((e,t)=>n.bus_get(n.BusType.SYSTEM,null,(r,i)=>{try{e(n.bus_get_finish(i))}catch(e){t(e)}})),this.#a}#l(e,t,r,i,a,s=3e4){return promisify((c,l)=>e.call(o,t,r,i,a,null,n.DBusCallFlags.NONE,s,null,(t,n)=>{try{c(e.call_finish(n))}catch(e){l(e)}}))}async available(){try{let e=await this.#c();return await this.#l(e,`/org/bluez`,`org.freedesktop.DBus.Peer`,`Ping`,null,2e3),!0}catch{return!1}}async list(){let e=await this.#c(),t=await this.#s(e),n=[];for(let[e,r]of Object.entries(t)){let t=r[s];!t||!(t.UUIDs??[]).map(e=>e.toLowerCase()).includes(this.#e)||!this.#n&&t.Paired!==!0||n.push({id:addressOf(e),name:String(t.Alias??t.Name??addressOf(e)),info:{bluetoothServiceClassId:this.#e}})}return n}async open(t){let a=await this.#c(),o=Object.entries(await this.#s(a)).find(([e,n])=>n[s]&&addressOf(e)===t)?.[0];if(!o)throw e(`NotFoundError`,`No Bluetooth device ${t}.`);let c=`${this.#i}${++this.#o}`,u,d,f=new Promise((e,t)=>{u=e,d=t});f.catch(()=>void 0);let p=n.DBusNodeInfo.new_for_xml(`<node>
2
+ <interface name="org.bluez.Profile1">
3
+ <method name="Release"/>
4
+ <method name="NewConnection">
5
+ <arg type="o" direction="in"/>
6
+ <arg type="h" direction="in"/>
7
+ <arg type="a{sv}" direction="in"/>
8
+ </method>
9
+ <method name="RequestDisconnection"><arg type="o" direction="in"/></method>
10
+ </interface>
11
+ </node>`).interfaces[0],onMethodCall=(e,t,n,i,a,o,s)=>{if(a===`NewConnection`){try{let e=s.get_message().get_unix_fd_list();if(!e)throw Error(`BlueZ sent no file descriptor`);let t=o.get_child_value(1).get_handle(),n=r.InputStream.new(e.get(t),!0),i=r.OutputStream.new(e.get(t),!0);s.return_value(null),u({input:n,output:i})}catch(e){s.return_dbus_error(`org.bluez.Error.Rejected`,e instanceof Error?e.message:String(e)),d(e)}return}s.return_value(null)},m=a.register_object(c,p,onMethodCall,null,null),h=!1,cleanup=async()=>{h&&(h=!1,await this.#l(a,`/org/bluez`,l,`UnregisterProfile`,new i.Variant(`(o)`,[c])).catch(()=>void 0)),a.unregister_object(m)};try{let t={Name:i.Variant.new_string(this.#r),Role:i.Variant.new_string(`client`),RequireAuthentication:i.Variant.new_boolean(!1),RequireAuthorization:i.Variant.new_boolean(!1)};await this.#l(a,`/org/bluez`,l,`RegisterProfile`,new i.Variant(`(osa{sv})`,[c,this.#e,t])),h=!0,this.#l(a,o,s,`ConnectProfile`,new i.Variant(`(s)`,[this.#e]),this.#t).catch(e=>d(e));let n=i.timeout_add(i.PRIORITY_DEFAULT,this.#t,()=>(d(e(`NetworkError`,`The device did not connect in time.`)),i.SOURCE_REMOVE)),r;try{r=await f}finally{i.source_remove(n)}return new RfcommConnection(r.input,r.output,cleanup)}catch(e){throw await cleanup(),e}}subscribe(e){let t=null,r=!1,i=[],watch=async()=>{if(t=await this.#c(),r)return;let handler=t=>(n,r,i,a,o,c)=>{let l=c.get_child_value(0).get_string()[0];if(!l.includes(`/dev_`))return;let u=c.get_child_value(1),d={id:addressOf(l),name:addressOf(l),info:{bluetoothServiceClassId:this.#e}};t?this.list().then(t=>{let n=t.find(e=>e.id===d.id);n&&e({type:`connect`,handle:n})}):String(u.recursiveUnpack()).includes(s)&&e({type:`disconnect`,handle:d})};i=[t.signal_subscribe(o,c,`InterfacesAdded`,`/`,null,n.DBusSignalFlags.NONE,handler(!0)),t.signal_subscribe(o,c,`InterfacesRemoved`,`/`,null,n.DBusSignalFlags.NONE,handler(!1))]};return watch(),()=>{r=!0;for(let e of i)t?.signal_unsubscribe(e);i=[]}}},RfcommConnection=class{#e;#t;#n;#r=new n.Cancellable;#i=!1;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}async read(){if(this.#i)return null;try{let e=await promisify((e,t)=>this.#e.read_bytes_async(4096,i.PRIORITY_DEFAULT,this.#r,(n,r)=>{try{e(this.#e.read_bytes_finish(r))}catch(e){t(e)}}));return e.get_size()===0?null:new Uint8Array(e.toArray())}catch(e){if(this.#i||this.#r.is_cancelled())return null;throw e}}async write(e){if(this.#i)throw Error(`connection closed`);await promisify((t,n)=>this.#t.write_all_async(e,i.PRIORITY_DEFAULT,this.#r,(e,r)=>{try{this.#t.write_all_finish(r),t()}catch(e){n(e)}}))}async close(){if(!this.#i){this.#i=!0,this.#r.cancel();try{this.#e.close(null)}catch{}try{this.#t.close(null)}catch{}await this.#n()}}};export{BluezRfcommSource,a as SERIAL_PORT_PROFILE_UUID};
@@ -0,0 +1 @@
1
+ import"./_virtual/_rolldown/runtime.js";import{DOMException as e}from"@gjsify/dom-exception";function serialError(t,n,r){let i=new e(n,t);return r!==void 0&&(i.cause=r),i}function asNetworkError(t,n){if(n instanceof e)return n;let r=n instanceof Error?n.message:String(n);return serialError(`NetworkError`,r?`${t} ${r}`:t,n)}export{asNetworkError,serialError};
@@ -0,0 +1 @@
1
+ import"./_virtual/_rolldown/runtime.js";var FakeConnection=class{written=[];closed=!1;failWrites=null;#e=[];#t=[];push(e){this.#n(e)}end(){this.#n(null)}#n(e){let t=this.#t.shift();t?t(e):this.#e.push(e)}read(){return this.#e.length>0?Promise.resolve(this.#e.shift()??null):this.closed?Promise.resolve(null):new Promise(e=>this.#t.push(e))}async write(e){if(this.closed)throw Error(`connection closed`);if(this.failWrites)throw this.failWrites;this.written.push(e.slice())}async close(){if(!this.closed){this.closed=!0;for(let e of this.#t.splice(0))e(null)}}},FakeSource=class{connections=[];openCalls=[];isAvailable=!0;#e;#t=new Set;subscribed=0;constructor(e=[]){this.#e=[...e]}async available(){return this.isAvailable}async list(){return[...this.#e]}async open(e){if(this.openCalls.push(e),!this.#e.some(t=>t.id===e))throw Error(`no such port: ${e}`);let t=new FakeConnection;return this.connections.push(t),t}subscribe(e){return this.subscribed++,this.#t.add(e),()=>{this.#t.delete(e)}}get listenerCount(){return this.#t.size}add(e){this.#e.push(e);for(let t of this.#t)t({type:`connect`,handle:e})}remove(e){let t=this.#e.find(t=>t.id===e);if(t){this.#e=this.#e.filter(t=>t.id!==e);for(let e of this.#t)e({type:`disconnect`,handle:t})}}};export{FakeConnection,FakeSource};
@@ -0,0 +1 @@
1
+ import"./_virtual/_rolldown/runtime.js";const e=`-0000-1000-8000-00805f9b34fb`;function canonicalUuid(t){if(typeof t==`number`){if(!Number.isInteger(t)||t<0||t>4294967295)throw TypeError(`not a service class id: ${t}`);return`${t.toString(16).padStart(8,`0`)}${e}`}let n=t.toLowerCase();if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(n))return n;if(/^[0-9a-f]{4}$/.test(n))return`0000${n}${e}`;if(/^[0-9a-f]{8}$/.test(n))return`${n}${e}`;throw TypeError(`not a service class id: ${t}`)}function validateFilters(e){for(let t of e??[]){let{usbVendorId:e,usbProductId:n,bluetoothServiceClassId:r}=t;if(e===void 0&&n===void 0&&r===void 0)throw TypeError(`A filter must provide a property to filter by.`);if(n!==void 0&&e===void 0)throw TypeError(`A filter containing a usbProductId must also contain a usbVendorId.`);if(r!==void 0){if(e!==void 0||n!==void 0)throw TypeError(`A filter containing a bluetoothServiceClassId cannot also contain USB properties.`);canonicalUuid(r)}}}function matches(e,t){let{info:n}=e;return t.bluetoothServiceClassId===void 0?!(t.usbVendorId!==void 0&&n.usbVendorId!==t.usbVendorId||t.usbProductId!==void 0&&n.usbProductId!==t.usbProductId):n.bluetoothServiceClassId===void 0?!1:canonicalUuid(n.bluetoothServiceClassId)===canonicalUuid(t.bluetoothServiceClassId)}function applyFilters(e,t){return!t||t.length===0?e:e.filter(e=>t.some(t=>matches(e,t)))}export{applyFilters,canonicalUuid,validateFilters};
@@ -0,0 +1 @@
1
+ import{canonicalUuid as e}from"./filter.js";import{BluezRfcommSource as t,SERIAL_PORT_PROFILE_UUID as n}from"./bluez-rfcomm-source.js";import{FakeConnection as r,FakeSource as i}from"./fake-source.js";import{SerialPort as a}from"./serial-port.js";import{Serial as o}from"./serial.js";export{t as BluezRfcommSource,r as FakeConnection,i as FakeSource,n as SERIAL_PORT_PROFILE_UUID,o as Serial,a as SerialPort,e as canonicalUuid};
File without changes
@@ -0,0 +1 @@
1
+ import{BluezRfcommSource as e}from"./bluez-rfcomm-source.js";import{SerialPort as t}from"./serial-port.js";import{Serial as n}from"./serial.js";import"@gjsify/node-globals/register/navigator";const r=globalThis;r.navigator.serial===void 0&&(r.navigator.serial=new n(new e)),r.Serial===void 0&&(r.Serial=n),r.SerialPort===void 0&&(r.SerialPort=t);
@@ -0,0 +1 @@
1
+ import"./_virtual/_rolldown/runtime.js";import{asNetworkError as e,serialError as t}from"./errors.js";import{Event as n,EventTarget as r}from"@gjsify/dom-events";import{ReadableStream as i,WritableStream as a}from"@gjsify/web-streams";var SerialPort=class extends r{#e;#t;#n=null;#r=null;#i=null;#a=!1;#o=!1;#s=!1;#c=!1;onconnect=null;ondisconnect=null;constructor(e,t){super(),this.#e=e,this.#t=t}get handle(){return this.#t}get connected(){return this.#n!==null&&!this.#c&&!this.#s}get readable(){return this.#r}get writable(){return this.#i}getInfo(){return{...this.#t.info}}async open(n){if(!n||!Number.isInteger(n.baudRate)||n.baudRate<1)throw TypeError(`Failed to execute 'open' on 'SerialPort': baudRate must be a positive integer.`);let r=n.bufferSize??255;if(!Number.isInteger(r)||r<1)throw TypeError(`Failed to execute 'open' on 'SerialPort': bufferSize must be a positive integer.`);if(this.#a||this.#n||this.#o)throw t(`InvalidStateError`,`The port is already open.`);this.#a=!0;try{this.#n=await this.#e.open(this.#t.id)}catch(t){throw e(`Failed to open serial port.`,t)}finally{this.#a=!1}this.#l(this.#n)}#l(n){this.#r=new i({pull:async r=>{try{let e=await n.read();if(e===null){if(this.#o)return;this.#c=!0,r.error(t(`NetworkError`,`The device has been lost.`)),this.#r=null,this.#i=null;return}r.enqueue(e)}catch(t){r.error(e(`Read failed.`,t)),this.#r=null}},cancel:async()=>{}},{highWaterMark:0}),this.#i=new a({write:async t=>{try{await n.write(t)}catch(t){throw e(`Write failed.`,t)}}},{highWaterMark:1})}async close(){if(!this.#n)throw t(`InvalidStateError`,`The port is already closed.`);if(this.#r?.locked||this.#i?.locked)throw TypeError(`Failed to execute 'close' on 'SerialPort': a locked stream cannot be closed.`);this.#o=!0;let e=this.#n,n=this.#r,r=this.#i;try{await e.close(),await n?.cancel().catch(()=>void 0),await r?.close().catch(()=>void 0)}finally{this.#c=!1,this.#n=null,this.#r=null,this.#i=null,this.#o=!1}}async forget(){this.#n&&await this.close().catch(()=>void 0),this.#s=!0}get forgotten(){return this.#s}async setSignals(e){throw t(`NotSupportedError`,`A Bluetooth serial port has no control signals to set.`)}async getSignals(){throw t(`NotSupportedError`,`A Bluetooth serial port has no control signals to read.`)}_notifyDisconnect(){this.#c=!0,this.#r=null,this.#i=null;let e=new n(`disconnect`,{bubbles:!0});this.dispatchEvent(e),this.ondisconnect?.(e)}};export{SerialPort};
@@ -0,0 +1 @@
1
+ import"./_virtual/_rolldown/runtime.js";import{serialError as e}from"./errors.js";import{applyFilters as t,validateFilters as n}from"./filter.js";import{SerialPort as r}from"./serial-port.js";import{Event as i,EventTarget as a}from"@gjsify/dom-events";const firstCandidate=e=>e[0]??null;var Serial=class extends a{#e;#t;#n=new Map;#r=null;#i=null;#a=null;constructor(e,t={}){super(),this.#e=e,this.#t=t.chooser??firstCandidate}get onconnect(){return this.#i}set onconnect(e){e&&this.#c(),this.#i=e}get ondisconnect(){return this.#a}set ondisconnect(e){e&&this.#c(),this.#a=e}#o(e){let t=this.#n.get(e.id);return t||(t=new r(this.#e,e),this.#n.set(e.id,t)),t}async#s(){return await this.#e.available()?this.#e.list():[]}async getPorts(){let e=await this.#s(),t=new Set(e.map(e=>e.id));for(let e of this.#n.keys())t.has(e)||this.#n.delete(e);return e.map(e=>this.#o(e)).filter(e=>!e.forgotten)}async requestPort(r={}){if(n(r.filters),!await this.#e.available())throw e(`NotSupportedError`,`No serial port service is available on this system.`);let i=t(await this.#e.list(),r.filters);if(i.length===0)throw e(`NotFoundError`,`No port selected by the user.`);let a=await this.#t(i);if(!a)throw e(`NotFoundError`,`No port selected by the user.`);return this.#o(a)}addEventListener(...e){this.#c(),super.addEventListener(...e)}#c(){this.#r||!this.#e.subscribe||(this.#r=this.#e.subscribe(e=>{let t=this.#o(e.handle),n=new i(e.type,{bubbles:!0});e.type===`disconnect`?(t._notifyDisconnect(),this.dispatchEvent(n),this.#a?.(n)):(this.dispatchEvent(n),this.#i?.(n))}))}dispose(){this.#r?.(),this.#r=null}};export{Serial};
File without changes
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Classic Bluetooth serial ports through BlueZ, with no `rfcomm` binary and no `/dev/rfcomm*`.
3
+ *
4
+ * The recipe, measured against a real label printer: register a client `org.bluez.Profile1` for
5
+ * the Serial Port Profile on the system bus, ask the device to `ConnectProfile`, and BlueZ calls
6
+ * our `NewConnection` with the connected RFCOMM socket as a file descriptor. That descriptor is
7
+ * the serial port. Closing it closes the link; the profile registration lives as long as the port.
8
+ *
9
+ * Raw `register_object`, not `Gio.DBusExportedObject`: the wrapper is a GJS-only override.
10
+ */
11
+ import Gio from 'gi://Gio?version=2.0';
12
+ import type { PortChange, PortConnection, PortHandle, PortSource } from './port-source.js';
13
+ export declare const SERIAL_PORT_PROFILE_UUID = "00001101-0000-1000-8000-00805f9b34fb";
14
+ export interface BluezRfcommOptions {
15
+ /** Service class to expose as ports. Default: the Serial Port Profile. */
16
+ serviceClass?: string;
17
+ /** How long to wait for the device to connect, in ms. Default 30 s. */
18
+ connectTimeoutMs?: number;
19
+ /** Include devices that are not paired. Default false: opening one would need pairing first. */
20
+ includeUnpaired?: boolean;
21
+ /** Custom bus, for tests. Default: the system bus. */
22
+ bus?: Gio.DBusConnection;
23
+ /** Name BlueZ shows for our profile registration. Default `gjsify-webserial`. */
24
+ profileName?: string;
25
+ /** D-Bus object path prefix for the client profile; a counter is appended. A valid object path. */
26
+ profilePathPrefix?: string;
27
+ }
28
+ export declare class BluezRfcommSource implements PortSource {
29
+ #private;
30
+ constructor(options?: BluezRfcommOptions);
31
+ available(): Promise<boolean>;
32
+ list(): Promise<PortHandle[]>;
33
+ open(id: string): Promise<PortConnection>;
34
+ subscribe(listener: (change: PortChange) => void): () => void;
35
+ }
@@ -0,0 +1,5 @@
1
+ import { DOMException } from '@gjsify/dom-exception';
2
+ export type SerialErrorName = 'InvalidStateError' | 'NetworkError' | 'NotFoundError' | 'NotSupportedError' | 'SecurityError';
3
+ export declare function serialError(name: SerialErrorName, message: string, cause?: unknown): DOMException;
4
+ /** A driver error becomes a DOMException; one already shaped like that passes through. */
5
+ export declare function asNetworkError(message: string, cause: unknown): DOMException;
@@ -0,0 +1,30 @@
1
+ import type { PortChange, PortConnection, PortHandle, PortSource } from './port-source.js';
2
+ /** A scripted device for tests: what the host writes is recorded, replies are pushed by the test. */
3
+ export declare class FakeConnection implements PortConnection {
4
+ #private;
5
+ readonly written: Uint8Array[];
6
+ closed: boolean;
7
+ failWrites: Error | null;
8
+ /** The device sends bytes to the host. */
9
+ push(bytes: Uint8Array): void;
10
+ /** The device ends the channel (unplugged, powered off). */
11
+ end(): void;
12
+ read(): Promise<Uint8Array | null>;
13
+ write(bytes: Uint8Array): Promise<void>;
14
+ close(): Promise<void>;
15
+ }
16
+ export declare class FakeSource implements PortSource {
17
+ #private;
18
+ readonly connections: FakeConnection[];
19
+ openCalls: string[];
20
+ isAvailable: boolean;
21
+ subscribed: number;
22
+ constructor(handles?: PortHandle[]);
23
+ available(): Promise<boolean>;
24
+ list(): Promise<PortHandle[]>;
25
+ open(id: string): Promise<PortConnection>;
26
+ subscribe(listener: (change: PortChange) => void): () => void;
27
+ get listenerCount(): number;
28
+ add(handle: PortHandle): void;
29
+ remove(id: string): void;
30
+ }
@@ -0,0 +1,8 @@
1
+ import type { PortHandle } from './port-source.js';
2
+ import type { SerialPortFilter } from './types.js';
3
+ /** 16-bit, 32-bit or full UUID in, canonical lower-case 128-bit UUID out. */
4
+ export declare function canonicalUuid(value: number | string): string;
5
+ /** Reject what the spec rejects: empty filters, a product id without a vendor, mixed transports. */
6
+ export declare function validateFilters(filters: SerialPortFilter[] | undefined): void;
7
+ /** No filters (or an empty list) means every port is a candidate. */
8
+ export declare function applyFilters(handles: PortHandle[], filters: SerialPortFilter[] | undefined): PortHandle[];
@@ -0,0 +1,10 @@
1
+ export type { PortChange, PortConnection, PortHandle, PortSource } from './port-source.js';
2
+ export type { SerialOptions, SerialPortFilter, SerialPortInfo, SerialPortRequestOptions } from './types.js';
3
+ export { canonicalUuid } from './filter.js';
4
+ export { FakeConnection, FakeSource } from './fake-source.js';
5
+ export { SerialPort } from './serial-port.js';
6
+ export type { SerialInputSignals, SerialOutputSignals } from './serial-port.js';
7
+ export { Serial } from './serial.js';
8
+ export type { PortChooser, SerialOptionsInit } from './serial.js';
9
+ export { BluezRfcommSource, SERIAL_PORT_PROFILE_UUID } from './bluez-rfcomm-source.js';
10
+ export type { BluezRfcommOptions } from './bluez-rfcomm-source.js';
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The seam. The Web Serial classes speak the standard; a platform driver speaks whatever its
3
+ * system does (BlueZ over D-Bus, a fake in tests) and is reduced to this vocabulary. Nothing above
4
+ * this file knows which driver is underneath, which is what lets another platform come later
5
+ * without touching the API surface.
6
+ */
7
+ import type { SerialPortInfo } from './types.js';
8
+ /** A port the platform knows about and the user may use. `id` is stable across calls. */
9
+ export interface PortHandle {
10
+ readonly id: string;
11
+ /** Human-readable name for a chooser; not part of the Web Serial API. */
12
+ readonly name: string;
13
+ readonly info: SerialPortInfo;
14
+ }
15
+ /** An open byte channel. Raw bytes in and out; the streams are built on top of it. */
16
+ export interface PortConnection {
17
+ /** Next bytes from the device, or `null` once the channel has ended. */
18
+ read(): Promise<Uint8Array | null>;
19
+ write(bytes: Uint8Array): Promise<void>;
20
+ /** Idempotent. Resolves a pending `read()` with `null`. */
21
+ close(): Promise<void>;
22
+ }
23
+ export interface PortChange {
24
+ readonly type: 'connect' | 'disconnect';
25
+ readonly handle: PortHandle;
26
+ }
27
+ export interface PortSource {
28
+ /** A quiet capability test: `false` when the platform service is missing, never an exception. */
29
+ available(): Promise<boolean>;
30
+ /** The ports already allowed for use (for Bluetooth: bonded devices). */
31
+ list(): Promise<PortHandle[]>;
32
+ open(id: string): Promise<PortConnection>;
33
+ /** Optional. Called lazily, on the first `connect`/`disconnect` listener. Returns the unsubscribe. */
34
+ subscribe?(listener: (change: PortChange) => void): () => void;
35
+ }
@@ -0,0 +1 @@
1
+ import '@gjsify/node-globals/register/navigator';
@@ -0,0 +1,2 @@
1
+ declare const _default: () => Promise<void>;
2
+ export default _default;
@@ -0,0 +1,39 @@
1
+ import { Event, EventTarget } from '@gjsify/dom-events';
2
+ import type { PortHandle, PortSource } from './port-source.js';
3
+ import type { SerialOptions, SerialPortInfo } from './types.js';
4
+ export interface SerialOutputSignals {
5
+ dataTerminalReady?: boolean;
6
+ requestToSend?: boolean;
7
+ break?: boolean;
8
+ }
9
+ export interface SerialInputSignals {
10
+ dataCarrierDetect: boolean;
11
+ clearToSend: boolean;
12
+ ringIndicator: boolean;
13
+ dataSetReady: boolean;
14
+ }
15
+ /**
16
+ * Web Serial's `SerialPort` over a `PortSource`. Follows the spec's state rules: one `open()` at a
17
+ * time, `readable`/`writable` are `null` while closed or after a fatal error, `close()` waits for
18
+ * the streams to be released. Control signals do not exist on a Bluetooth serial port, so those
19
+ * calls say so instead of pretending.
20
+ */
21
+ export declare class SerialPort extends EventTarget {
22
+ #private;
23
+ onconnect: ((event: Event) => void) | null;
24
+ ondisconnect: ((event: Event) => void) | null;
25
+ constructor(source: PortSource, handle: PortHandle);
26
+ get handle(): PortHandle;
27
+ get connected(): boolean;
28
+ get readable(): globalThis.ReadableStream<Uint8Array> | null;
29
+ get writable(): globalThis.WritableStream<Uint8Array> | null;
30
+ getInfo(): SerialPortInfo;
31
+ open(options: SerialOptions): Promise<void>;
32
+ close(): Promise<void>;
33
+ forget(): Promise<void>;
34
+ get forgotten(): boolean;
35
+ setSignals(_signals?: SerialOutputSignals): Promise<void>;
36
+ getSignals(): Promise<SerialInputSignals>;
37
+ /** Internal: the transport reported the device gone. */
38
+ _notifyDisconnect(): void;
39
+ }
@@ -0,0 +1,26 @@
1
+ import { Event, EventTarget } from '@gjsify/dom-events';
2
+ import type { PortHandle, PortSource } from './port-source.js';
3
+ import { SerialPort } from './serial-port.js';
4
+ import type { SerialPortRequestOptions } from './types.js';
5
+ /**
6
+ * Picks one port out of the candidates. The browser shows a chooser; a CLI or a GTK dialog
7
+ * supplies its own. Returning `null` is "the user cancelled".
8
+ */
9
+ export type PortChooser = (candidates: PortHandle[]) => Promise<PortHandle | null> | PortHandle | null;
10
+ export interface SerialOptionsInit {
11
+ chooser?: PortChooser;
12
+ }
13
+ /** `navigator.serial`. Hands out one `SerialPort` object per port id, so identity comparisons hold. */
14
+ export declare class Serial extends EventTarget {
15
+ #private;
16
+ constructor(source: PortSource, init?: SerialOptionsInit);
17
+ get onconnect(): ((event: Event) => void) | null;
18
+ set onconnect(handler: ((event: Event) => void) | null);
19
+ get ondisconnect(): ((event: Event) => void) | null;
20
+ set ondisconnect(handler: ((event: Event) => void) | null);
21
+ getPorts(): Promise<SerialPort[]>;
22
+ requestPort(options?: SerialPortRequestOptions): Promise<SerialPort>;
23
+ addEventListener(...args: Parameters<EventTarget['addEventListener']>): void;
24
+ /** Not part of the spec: stop listening to the platform. */
25
+ dispose(): void;
26
+ }
@@ -0,0 +1,28 @@
1
+ /** What `SerialPort.getInfo()` reports. Bluetooth ports carry the service class they were found by. */
2
+ export interface SerialPortInfo {
3
+ usbVendorId?: number;
4
+ usbProductId?: number;
5
+ bluetoothServiceClassId?: number | string;
6
+ }
7
+ export interface SerialPortFilter {
8
+ usbVendorId?: number;
9
+ usbProductId?: number;
10
+ bluetoothServiceClassId?: number | string;
11
+ }
12
+ export interface SerialPortRequestOptions {
13
+ filters?: SerialPortFilter[];
14
+ /**
15
+ * Accepted and ignored: on this backend every bonded device that advertises a matching service
16
+ * class is already known, so there is nothing further to unlock.
17
+ */
18
+ allowedBluetoothServiceClassIds?: Array<number | string>;
19
+ }
20
+ export interface SerialOptions {
21
+ /** Required by the spec. A Bluetooth serial port has no baud rate, so the value is not used. */
22
+ baudRate: number;
23
+ dataBits?: number;
24
+ stopBits?: number;
25
+ parity?: 'none' | 'even' | 'odd';
26
+ bufferSize?: number;
27
+ flowControl?: 'none' | 'hardware';
28
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: () => Promise<void>;
2
+ export default _default;
package/package.json CHANGED
@@ -1,6 +1,89 @@
1
1
  {
2
- "name": "@gjsify/webserial",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@gjsify/webserial",
3
+ "version": "0.64.52",
4
+ "description": "Web Serial API for GJS. The Linux backend opens a classic Bluetooth serial port (RFCOMM, SPP) through BlueZ, with no rfcomm binary and no /dev/rfcomm*",
5
+ "type": "module",
6
+ "module": "lib/esm/index.js",
7
+ "types": "lib/types/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./lib/types/index.d.ts",
11
+ "default": "./lib/esm/index.js"
12
+ },
13
+ "./register": {
14
+ "types": "./lib/types/register.d.ts",
15
+ "default": "./lib/esm/register.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "lib"
20
+ ],
21
+ "sideEffects": [
22
+ "./lib/esm/register.js"
23
+ ],
24
+ "scripts": {
25
+ "clear": "gjsify clear lib tsconfig.tsbuildinfo tsconfig.types.tsbuildinfo test.gjs.mjs",
26
+ "check": "gjsify tsc --noEmit",
27
+ "build": "gjsify run build:gjsify && gjsify run build:types",
28
+ "build:gjsify": "gjsify build --library 'src/**/*.{ts,js}' --exclude 'src/**/*.spec.{mts,ts}' 'src/test*.{mts,ts}'",
29
+ "build:types": "gjsify tsc",
30
+ "build:test": "gjsify run build:test:gjs",
31
+ "build:test:gjs": "gjsify build src/test.mts --app gjs --outfile test.gjs.mjs",
32
+ "test": "gjsify run build:gjsify && gjsify run build:test && gjsify run test:gjs",
33
+ "test:gjs": "gjsify run test.gjs.mjs"
34
+ },
35
+ "keywords": [
36
+ "gjs",
37
+ "web-serial",
38
+ "serial",
39
+ "bluetooth",
40
+ "bluez",
41
+ "rfcomm",
42
+ "spp"
43
+ ],
44
+ "dependencies": {
45
+ "@gjsify/dom-events": "^0.64.52",
46
+ "@gjsify/dom-exception": "^0.64.52",
47
+ "@gjsify/node-globals": "^0.64.52",
48
+ "@gjsify/web-streams": "^0.64.52"
49
+ },
50
+ "devDependencies": {
51
+ "@girs/gio-2.0": "5.4.0",
52
+ "@girs/giounix-2.0": "5.4.0",
53
+ "@girs/gjs": "5.4.0",
54
+ "@girs/glib-2.0": "5.4.0",
55
+ "@girs/gobject-2.0": "5.4.0",
56
+ "@gjsify/cli": "^0.64.52",
57
+ "@gjsify/unit": "^0.64.52",
58
+ "@types/node": "^25.9.2",
59
+ "typescript": "^6.0.3"
60
+ },
61
+ "gjsify": {
62
+ "runtimes": {
63
+ "gjs": "polyfill",
64
+ "node": "none",
65
+ "browser": "none",
66
+ "nativescript": "none"
67
+ },
68
+ "os": {
69
+ "linux": "supported",
70
+ "darwin": "none",
71
+ "win32": "none"
72
+ },
73
+ "osNotes": {
74
+ "darwin": "The only backend, `BluezRfcommSource`, talks to BlueZ over the system D-Bus, and BlueZ exists on Linux only. On macOS the same `PortSource` seam would be filled by an IOBluetooth driver, which does not exist yet. Until then `navigator.serial` reports no ports there; the package is not usable, so it claims `none` rather than `partial`.",
75
+ "win32": "The only backend, `BluezRfcommSource`, talks to BlueZ over the system D-Bus, and BlueZ exists on Linux only. There is also no GJS host on Windows at all (ADR 0024 § 4), so the route would be Node with a Windows Bluetooth driver behind the `PortSource` seam, which does not exist yet. The package is not usable on win32 and claims `none`."
76
+ },
77
+ "tier": 1
78
+ },
79
+ "license": "MIT",
80
+ "repository": {
81
+ "type": "git",
82
+ "url": "git+https://github.com/gjsify/gjsify.git",
83
+ "directory": "packages/web/webserial"
84
+ },
85
+ "bugs": {
86
+ "url": "https://github.com/gjsify/gjsify/issues"
87
+ },
88
+ "homepage": "https://github.com/gjsify/gjsify/tree/main/packages/web/webserial#readme"
89
+ }