@yoltra/devtools-server 0.5.0 → 0.7.0
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.es.md +162 -0
- package/dist/devtools-server.cjs +2 -4
- package/dist/devtools-server.mjs +2 -4
- package/package.json +7 -7
package/README.es.md
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+

|
|
2
|
+
|
|
3
|
+
# @yoltra/devtools-server
|
|
4
|
+
|
|
5
|
+
> 👉 🇲🇽 Versión en Español | [ 🇺🇸 English Version](./README.md)
|
|
6
|
+
|
|
7
|
+
**Hub WebSocket central que intermedia el tráfico del protocolo DevTools entre los stores de
|
|
8
|
+
Yoltra y las extensiones.**
|
|
9
|
+
|
|
10
|
+
`@yoltra/devtools-server` levanta un servidor WebSocket accesible solo desde localhost que atiende
|
|
11
|
+
los handshakes del protocolo, enruta mensajes entre stores y UIs de DevTools, y mantiene un búfer
|
|
12
|
+
circular de eventos recientes para las extensiones que se conectan tarde.
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## Instalación
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install @yoltra/devtools-server
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## Inicio rápido
|
|
25
|
+
|
|
26
|
+
### Como librería
|
|
27
|
+
|
|
28
|
+
Empotra el hub en tu propio proceso (runner de pruebas, servidor de desarrollo, extensión de
|
|
29
|
+
VSCode):
|
|
30
|
+
|
|
31
|
+
```typescript
|
|
32
|
+
import { DevtoolsHub } from "@yoltra/devtools-server";
|
|
33
|
+
|
|
34
|
+
const hub = new DevtoolsHub({ port: 9800 });
|
|
35
|
+
await hub.start();
|
|
36
|
+
|
|
37
|
+
console.log("Hub escuchando en ws://127.0.0.1:9800");
|
|
38
|
+
console.log("Stores conectados:", hub.storeCount);
|
|
39
|
+
console.log("Extensiones conectadas:", hub.extensionCount);
|
|
40
|
+
|
|
41
|
+
// Más tarde...
|
|
42
|
+
await hub.stop();
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### Como CLI independiente
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
npx @yoltra/devtools-server --port 9800 --history-size 1000
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
O mediante el binario del proyecto:
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
node ./bin/devtools-server.js --port 9800
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
## Cómo funciona
|
|
60
|
+
|
|
61
|
+
```
|
|
62
|
+
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
|
|
63
|
+
│ Store de │ ──── │ Hub de │ ──── │ UI de │
|
|
64
|
+
│ Yoltra │ WS │ DevTools │ WS │ DevTools │
|
|
65
|
+
│ │ ───► │ (este pkg) │ ───► │ (Extensión) │
|
|
66
|
+
└─────────────┘ └──────────────┘ └───────────────┘
|
|
67
|
+
│
|
|
68
|
+
Búfer circular
|
|
69
|
+
(historial de eventos)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
1. Los **stores** se conectan y realizan el handshake del protocolo
|
|
73
|
+
2. Los eventos del store se **difunden** a todas las extensiones conectadas
|
|
74
|
+
3. Los comandos de las extensiones (peticiones de estado, viaje en el tiempo) se **enrutan** al
|
|
75
|
+
store destino por su `storeId`
|
|
76
|
+
4. Los eventos recientes se **guardan en un búfer circular**, así que una extensión que se conecta
|
|
77
|
+
tarde recibe el historial
|
|
78
|
+
|
|
79
|
+
---
|
|
80
|
+
|
|
81
|
+
## Configuración
|
|
82
|
+
|
|
83
|
+
```typescript
|
|
84
|
+
interface DevtoolsHubOptions {
|
|
85
|
+
/** Puerto en el que escuchar. @default 9800 */
|
|
86
|
+
port?: number;
|
|
87
|
+
/** Host en el que escuchar. @default "127.0.0.1" */
|
|
88
|
+
host?: string;
|
|
89
|
+
/** Máximo de eventos retenidos para extensiones que se conectan tarde. @default 1000 */
|
|
90
|
+
historySize?: number;
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
---
|
|
95
|
+
|
|
96
|
+
## Referencia de la API
|
|
97
|
+
|
|
98
|
+
### `DevtoolsHub`
|
|
99
|
+
|
|
100
|
+
| Método / Propiedad | Descripción |
|
|
101
|
+
| ------------------------- | -------------------------------------------------- |
|
|
102
|
+
| `new DevtoolsHub(opts?)` | Crea una instancia del hub |
|
|
103
|
+
| `hub.start()` | Arranca el servidor WS (devuelve una Promise) |
|
|
104
|
+
| `hub.stop()` | Detiene el servidor y cierra todas las conexiones |
|
|
105
|
+
| `DevtoolsHub.probe(port)` | Comprueba si ya hay un hub corriendo en un puerto |
|
|
106
|
+
| `hub.storeCount` | Número de stores conectados |
|
|
107
|
+
| `hub.extensionCount` | Número de extensiones conectadas |
|
|
108
|
+
| `hub.historySize` | Número de eventos en el búfer circular |
|
|
109
|
+
|
|
110
|
+
### `RingBuffer<T>`
|
|
111
|
+
|
|
112
|
+
Un búfer circular de tamaño fijo, usado internamente para el historial de eventos:
|
|
113
|
+
|
|
114
|
+
```typescript
|
|
115
|
+
import { RingBuffer } from "@yoltra/devtools-server";
|
|
116
|
+
|
|
117
|
+
const buf = new RingBuffer<string>(100);
|
|
118
|
+
buf.push("event-1");
|
|
119
|
+
buf.push("event-2");
|
|
120
|
+
buf.toArray(); // ['event-1', 'event-2']
|
|
121
|
+
buf.size; // 2
|
|
122
|
+
buf.clear();
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
---
|
|
126
|
+
|
|
127
|
+
## Sondear antes de arrancar
|
|
128
|
+
|
|
129
|
+
Evita conflictos de puerto comprobando si ya hay un hub corriendo:
|
|
130
|
+
|
|
131
|
+
```typescript
|
|
132
|
+
import { DevtoolsHub } from "@yoltra/devtools-server";
|
|
133
|
+
|
|
134
|
+
const alreadyRunning = await DevtoolsHub.probe(9800);
|
|
135
|
+
|
|
136
|
+
if (!alreadyRunning) {
|
|
137
|
+
const hub = new DevtoolsHub({ port: 9800 });
|
|
138
|
+
await hub.start();
|
|
139
|
+
}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
## Seguridad
|
|
145
|
+
|
|
146
|
+
El hub escucha en `127.0.0.1` (solo localhost) por defecto. Es una restricción de seguridad
|
|
147
|
+
deliberada para v1: el hub no se expone a la red.
|
|
148
|
+
|
|
149
|
+
---
|
|
150
|
+
|
|
151
|
+
## Paquetes relacionados
|
|
152
|
+
|
|
153
|
+
- **[@yoltra/devtools-protocol](../devtools-protocol/README.md)** — Formato de cable y tipos de
|
|
154
|
+
mensaje
|
|
155
|
+
- **[@yoltra/devtools-browser-agent](../devtools-browser-agent/README.md)** — Conecta stores del
|
|
156
|
+
navegador a este hub
|
|
157
|
+
|
|
158
|
+
---
|
|
159
|
+
|
|
160
|
+
## Licencia
|
|
161
|
+
|
|
162
|
+
**MIT** — De uso libre en proyectos comerciales y de código abierto.
|
package/dist/devtools-server.cjs
CHANGED
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @yoltra/devtools-server v0.
|
|
2
|
+
* @yoltra/devtools-server v0.7.0
|
|
3
3
|
* (c) 2026 Manu Ramirez <@pixerael>
|
|
4
|
-
* License: MIT
|
|
5
|
-
* Homepage: https://yoltra.dev
|
|
6
|
-
*/
|
|
4
|
+
* License: MIT */
|
|
7
5
|
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@yoltra/devtools-protocol"),h=require("ws");class d{constructor(e){if(this.capacity=e,this.head=0,this.count=0,e<1)throw new Error("RingBuffer capacity must be >= 1");this.items=new Array(e)}push(e){this.items[this.head]=e,this.head=(this.head+1)%this.capacity,this.count<this.capacity&&this.count++}toArray(){if(this.count===0)return[];const e=[],t=this.count<this.capacity?0:this.head;for(let s=0;s<this.count;s++)e.push(this.items[(t+s)%this.capacity]);return e}get size(){return this.count}clear(){this.items.fill(void 0),this.head=0,this.count=0}}class S{constructor(){this.stores=new Map,this.extensions=new Map}register(e){e.role===i.DevtoolsRole.STORE?this.stores.set(e.id,e):this.extensions.set(e.id,e)}unregister(e,t){t===i.DevtoolsRole.STORE?this.stores.delete(e):this.extensions.delete(e)}getStoreSocket(e){return this.stores.get(e)?.ws}fanOutToExtensions(e,t){for(const[,s]of this.extensions)s.ws.readyState===s.ws.OPEN&&(t!==void 0&&!t(s.extensionInfo?.capabilities)||s.ws.send(e))}storeIds(){return[...this.stores.keys()]}sendToStore(e,t){const s=this.stores.get(e);return!s||s.ws.readyState!==s.ws.OPEN?!1:(s.ws.send(t),!0)}buildStoreConnectedMessage(e){if(!e.storeInfo)return null;const t={type:"STORE_CONNECTED",timestamp:new Date().toISOString(),sourceId:"hub",sourceRole:i.DevtoolsRole.HUB,store:{id:e.id,name:e.storeInfo.name,capabilities:e.storeInfo.capabilities}};return JSON.stringify(t)}buildStoreDisconnectedMessage(e,t){const s={type:"STORE_DISCONNECTED",timestamp:new Date().toISOString(),sourceId:"hub",sourceRole:i.DevtoolsRole.HUB,storeId:e,reason:t};return JSON.stringify(s)}buildRegistryMessage(){const e={type:"STORE_REGISTRY",timestamp:new Date().toISOString(),sourceId:"hub",sourceRole:i.DevtoolsRole.HUB,stores:Array.from(this.stores.values()).flatMap(t=>t.storeInfo?[{id:t.id,name:t.storeInfo.name,status:"connected",capabilities:t.storeInfo.capabilities,connectedAt:t.connectedAt}]:[])};return JSON.stringify(e)}get storeCount(){return this.stores.size}get extensionCount(){return this.extensions.size}}const p=5e3,g=8*1024*1024;function y(o,e){if(typeof e!="string"||e.length!==o.length)return!1;let t=0;for(let s=0;s<o.length;s+=1)t|=o.charCodeAt(s)^e.charCodeAt(s);return t===0}function O(o,e,t){if(!o||e.includes(o))return!0;let s;try{s=new URL(o)}catch{return!1}return s.protocol==="chrome-extension:"||s.protocol==="moz-extension:"||s.protocol==="safari-web-extension:"?t.length===0?!0:t.includes(s.hostname):w(s.hostname)}function m(o,e){try{const t=JSON.parse(o);return typeof t.storeId=="string"?e.has(t.storeId):!0}catch{return!0}}function w(o){const e=o.replace(/^\[|\]$/g,"");return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e.startsWith("127.")||e==="::1"||e==="0:0:0:0:0:0:0:1"}class f{constructor(e={}){this.router=new S,this.wss=null,this.port=e.port??9800,this.host=e.host??"127.0.0.1",this.allowedOrigins=e.allowedOrigins??[],this.authToken=e.authToken,this.allowedExtensionIds=e.allowedExtensionIds??[],this.maxMessagesPerSecond=e.maxMessagesPerSecond??200,this.history=new d(e.historySize??1e3)}async start(){return new Promise((e,t)=>{this.wss=new h.WebSocketServer({port:this.port,host:this.host,maxPayload:g,verifyClient:s=>O(s.origin,this.allowedOrigins,this.allowedExtensionIds)?!0:(console.warn(`[yoltra devtools] Rejected WebSocket connection from disallowed origin: ${s.origin}`),!1)}),this.wss.on("listening",()=>{this.authToken===void 0&&console.warn("[yoltra devtools] Hub is running without an auth token: any process on this machine can read and drive the connected stores. Pass { authToken } (and the same value to each agent) on a shared or containerised host."),e()}),this.wss.on("error",s=>{t(s)}),this.wss.on("connection",s=>{this.handleConnection(s)})})}async stop(){return new Promise(e=>{if(!this.wss){e();return}this.wss.close(()=>{this.wss=null,e()});for(const t of this.wss.clients)t.close(1001,"Hub shutting down")})}static async probe(e){return new Promise(t=>{const s=new h.WebSocket(`ws://127.0.0.1:${e}`),n=setTimeout(()=>{s.close(),t(!1)},2e3);s.on("open",()=>{clearTimeout(n),s.close(),t(!0)}),s.on("error",()=>{clearTimeout(n),t(!1)})})}handleConnection(e){let t=null,s=Date.now(),n=0;const l=setTimeout(()=>{t||e.close(1008,"Handshake timeout")},p);e.on("message",c=>{let r;try{r=JSON.parse(c.toString())}catch{return}if(r===null||typeof r!="object"||Array.isArray(r)||typeof r.type!="string")return;const a=Date.now();if(a-s>=1e3&&(s=a,n=0),n+=1,n>this.maxMessagesPerSecond){n===this.maxMessagesPerSecond+1&&console.warn(`[yoltra devtools] A ${t?.role??"handshaking"} client exceeded ${this.maxMessagesPerSecond} messages/second; the excess is being dropped.`);return}if(!t){r.type==="HANDSHAKE_REQUEST"&&(clearTimeout(l),t=this.handleHandshake(e,r),t||e.close(1008,"Handshake failed"));return}this.routeMessage(t,r)}),e.on("close",()=>{clearTimeout(l),t&&this.handleDisconnect(t)}),e.on("error",()=>{})}handleHandshake(e,t){if(this.authToken!==void 0&&!y(this.authToken,t.authToken)){const a={type:"HANDSHAKE_RESPONSE",success:!1,negotiatedVersion:i.PROTOCOL_VERSION,hubCapabilities:{maxHistorySize:this.history.capacity,supportedFeatures:[]},error:"Invalid or missing auth token"};return e.send(JSON.stringify(a)),console.warn(`[yoltra devtools] Rejected a ${t.role} handshake: wrong or missing auth token`),null}const s=parseInt(t.protocolVersion?.split(".")[0]??"0"),n=parseInt(i.PROTOCOL_VERSION.split(".")[0]);if(s!==n){const a={type:"HANDSHAKE_RESPONSE",success:!1,negotiatedVersion:i.PROTOCOL_VERSION,hubCapabilities:{maxHistorySize:this.history.capacity,supportedFeatures:[]},error:`Incompatible protocol version: ${t.protocolVersion} (hub: ${i.PROTOCOL_VERSION})`};return e.send(JSON.stringify(a)),null}const l=t.role===i.DevtoolsRole.STORE?t.store?.id:t.extension?.id;if(!l)return console.warn(`[yoltra devtools] Rejected handshake: role ${t.role} without a matching id payload`),null;const c={ws:e,role:t.role,id:l,connectedAt:new Date().toISOString()};t.role===i.DevtoolsRole.STORE&&t.store?c.storeInfo={name:t.store.name,capabilities:t.store.capabilities}:t.role===i.DevtoolsRole.EXTENSION&&t.extension&&(c.extensionInfo={name:t.extension.name,capabilities:t.extension.capabilities}),this.router.register(c);const r={type:"HANDSHAKE_RESPONSE",success:!0,negotiatedVersion:i.PROTOCOL_VERSION,hubCapabilities:{maxHistorySize:this.history.capacity,supportedFeatures:[]}};if(e.send(JSON.stringify(r)),t.role===i.DevtoolsRole.STORE){const a=this.router.buildStoreConnectedMessage(c);a&&this.router.fanOutToExtensions(a)}else if(t.role===i.DevtoolsRole.EXTENSION){e.send(this.router.buildRegistryMessage());const a=new Set(this.router.storeIds());for(const u of this.history.toArray())m(u,a)&&e.send(u)}return c}routeMessage(e,t){const s=JSON.stringify(t);if(e.role===i.DevtoolsRole.STORE)t.type==="STORE_METRICS"?this.router.fanOutToExtensions(s,n=>n?.performanceMetrics!==!1):this.router.fanOutToExtensions(s),t.type==="STORE_EVENT"&&this.history.push(s);else{const n=t.storeId;n&&this.router.sendToStore(n,s)}}handleDisconnect(e){if(this.router.unregister(e.id,e.role),e.role===i.DevtoolsRole.STORE){const t=this.router.buildStoreDisconnectedMessage(e.id,"disconnected");this.router.fanOutToExtensions(t)}}get storeCount(){return this.router.storeCount}get extensionCount(){return this.router.extensionCount}get historySize(){return this.history.size}}async function T(o=process.argv){const e=o.indexOf("--port"),t=parseInt(o.find(r=>r.startsWith("--port="))?.split("=")[1]??(e!==-1?o[e+1]:void 0)??"9800"),s=o.indexOf("--history-size"),n=parseInt(o.find(r=>r.startsWith("--history-size="))?.split("=")[1]??(s!==-1?o[s+1]:void 0)??"1000"),l=new f({port:t,historySize:n}),c=async()=>{console.log(`
|
|
8
6
|
Shutting down DevTools hub...`),await l.stop(),process.exit(0)};process.on("SIGINT",c),process.on("SIGTERM",c);try{await l.start(),console.log(`Yoltra DevTools hub running on ws://127.0.0.1:${t}`),console.log(`History buffer: ${n} events`)}catch(r){console.error("Failed to start DevTools hub:",r),process.exit(1)}}exports.DevtoolsHub=f;exports.RingBuffer=d;exports.startCli=T;
|
|
9
7
|
//# sourceMappingURL=devtools-server.cjs.map
|
package/dist/devtools-server.mjs
CHANGED
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @yoltra/devtools-server v0.
|
|
2
|
+
* @yoltra/devtools-server v0.7.0
|
|
3
3
|
* (c) 2026 Manu Ramirez <@pixerael>
|
|
4
|
-
* License: MIT
|
|
5
|
-
* Homepage: https://yoltra.dev
|
|
6
|
-
*/
|
|
4
|
+
* License: MIT */
|
|
7
5
|
import { DevtoolsRole as r, PROTOCOL_VERSION as u } from "@yoltra/devtools-protocol";
|
|
8
6
|
import { WebSocketServer as d, WebSocket as f } from "ws";
|
|
9
7
|
class p {
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yoltra/devtools-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Hub WebSocket server for Yoltra DevTools — standalone CLI and embeddable library",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "Manu Ramirez <@pixerael>",
|
|
8
|
-
"email": "
|
|
8
|
+
"email": "opensource@yoltra.dev"
|
|
9
9
|
},
|
|
10
10
|
"maintainers": [],
|
|
11
11
|
"homepage": "https://yoltra.dev",
|
|
@@ -42,23 +42,23 @@
|
|
|
42
42
|
"sideEffects": false,
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"ws": "^8.19.0",
|
|
45
|
-
"@yoltra/devtools-protocol": "0.
|
|
45
|
+
"@yoltra/devtools-protocol": "0.7.0"
|
|
46
46
|
},
|
|
47
47
|
"devDependencies": {
|
|
48
48
|
"@types/node": "^24.0.12",
|
|
49
49
|
"@types/ws": "^8.18.1",
|
|
50
|
-
"@vitest/coverage-v8": "3.2.
|
|
50
|
+
"@vitest/coverage-v8": "3.2.7",
|
|
51
51
|
"typedoc": "^0.28.13",
|
|
52
52
|
"typedoc-plugin-localization": "3.0.6",
|
|
53
53
|
"typedoc-plugin-markdown": "4.9.0",
|
|
54
54
|
"typescript": "5.9.3",
|
|
55
|
-
"vite": "^7.
|
|
55
|
+
"vite": "^7.3.6",
|
|
56
56
|
"vite-plugin-banner": "0.8.1",
|
|
57
57
|
"vite-plugin-dts": "^4.5.4",
|
|
58
|
-
"vitest": "3.2.
|
|
58
|
+
"vitest": "3.2.7"
|
|
59
59
|
},
|
|
60
60
|
"engines": {
|
|
61
|
-
"node": ">=18
|
|
61
|
+
"node": ">=18"
|
|
62
62
|
},
|
|
63
63
|
"publishConfig": {
|
|
64
64
|
"access": "public"
|