@cappitolian/http-local-server-swifter 0.0.13 → 0.0.14

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/dist/docs.json CHANGED
@@ -2,38 +2,16 @@
2
2
  "api": {
3
3
  "name": "HttpLocalServerSwifterPlugin",
4
4
  "slug": "httplocalserverswifterplugin",
5
- "docs": "Plugin para ejecutar un servidor HTTP local en dispositivos iOS y Android.\n\nPermite recibir peticiones HTTP desde otros dispositivos en la red local\ny responder desde JavaScript/TypeScript.",
6
- "tags": [
7
- {
8
- "text": "0.1.0",
9
- "name": "since"
10
- }
11
- ],
5
+ "docs": "",
6
+ "tags": [],
12
7
  "methods": [
13
8
  {
14
9
  "name": "connect",
15
10
  "signature": "() => Promise<HttpConnectResult>",
16
11
  "parameters": [],
17
12
  "returns": "Promise<HttpConnectResult>",
18
- "tags": [
19
- {
20
- "name": "returns",
21
- "text": "Promesa con la IP y puerto del servidor"
22
- },
23
- {
24
- "name": "throws",
25
- "text": "Error si el servidor no puede iniciarse (ej: puerto ocupado)"
26
- },
27
- {
28
- "name": "example",
29
- "text": "```typescript\nconst { ip, port } = await HttpLocalServerSwifter.connect();\nconsole.log(`Servidor corriendo en http://${ip}:${port}`);\n```"
30
- },
31
- {
32
- "name": "since",
33
- "text": "0.1.0"
34
- }
35
- ],
36
- "docs": "Inicia el servidor HTTP local en el dispositivo.\n\nEl servidor escucha en todas las interfaces de red (0.0.0.0)\ny es accesible desde otros dispositivos en la misma red local.",
13
+ "tags": [],
14
+ "docs": "",
37
15
  "complexTypes": [
38
16
  "HttpConnectResult"
39
17
  ],
@@ -44,21 +22,8 @@
44
22
  "signature": "() => Promise<void>",
45
23
  "parameters": [],
46
24
  "returns": "Promise<void>",
47
- "tags": [
48
- {
49
- "name": "returns",
50
- "text": "Promesa que se resuelve cuando el servidor se detiene"
51
- },
52
- {
53
- "name": "example",
54
- "text": "```typescript\nawait HttpLocalServerSwifter.disconnect();\nconsole.log('Servidor detenido');\n```"
55
- },
56
- {
57
- "name": "since",
58
- "text": "0.1.0"
59
- }
60
- ],
61
- "docs": "Detiene el servidor HTTP local.\n\nCierra todas las conexiones activas y libera el puerto.\nLas peticiones pendientes recibirán un timeout.",
25
+ "tags": [],
26
+ "docs": "",
62
27
  "complexTypes": [],
63
28
  "slug": "disconnect"
64
29
  },
@@ -68,34 +33,13 @@
68
33
  "parameters": [
69
34
  {
70
35
  "name": "options",
71
- "docs": "- Objeto con requestId y cuerpo de la respuesta",
36
+ "docs": "",
72
37
  "type": "HttpSendResponseOptions"
73
38
  }
74
39
  ],
75
40
  "returns": "Promise<void>",
76
- "tags": [
77
- {
78
- "name": "param",
79
- "text": "options - Objeto con requestId y cuerpo de la respuesta"
80
- },
81
- {
82
- "name": "returns",
83
- "text": "Promesa que se resuelve cuando la respuesta se envía"
84
- },
85
- {
86
- "name": "throws",
87
- "text": "Error si faltan requestId o body"
88
- },
89
- {
90
- "name": "example",
91
- "text": "```typescript\nawait HttpLocalServerSwifter.sendResponse({\n requestId: '123-456-789',\n body: JSON.stringify({ status: 'ok', data: { id: 1 } })\n});\n```"
92
- },
93
- {
94
- "name": "since",
95
- "text": "0.1.0"
96
- }
97
- ],
98
- "docs": "Envía una respuesta HTTP de vuelta al cliente.\n\nDebe llamarse con el `requestId` recibido en el evento 'onRequest'.\nSi no se llama dentro de 5 segundos, el cliente recibirá un timeout (408).",
41
+ "tags": [],
42
+ "docs": "Sends a response back to the client.\nNow supports status and headers to handle CORS Preflight correctly.",
99
43
  "complexTypes": [
100
44
  "HttpSendResponseOptions"
101
45
  ],
@@ -107,39 +51,18 @@
107
51
  "parameters": [
108
52
  {
109
53
  "name": "eventName",
110
- "docs": "- Debe ser 'onRequest'",
54
+ "docs": "",
111
55
  "type": "'onRequest'"
112
56
  },
113
57
  {
114
58
  "name": "listenerFunc",
115
- "docs": "- Callback que recibe los datos de la petición",
59
+ "docs": "",
116
60
  "type": "(data: HttpRequestData) => void | Promise<void>"
117
61
  }
118
62
  ],
119
63
  "returns": "Promise<PluginListenerHandle>",
120
- "tags": [
121
- {
122
- "name": "param",
123
- "text": "eventName - Debe ser 'onRequest'"
124
- },
125
- {
126
- "name": "param",
127
- "text": "listenerFunc - Callback que recibe los datos de la petición"
128
- },
129
- {
130
- "name": "returns",
131
- "text": "Handle para remover el listener posteriormente"
132
- },
133
- {
134
- "name": "example",
135
- "text": "```typescript\nconst listener = await HttpLocalServerSwifter.addListener('onRequest', async (data) => {\n console.log(`${data.method} ${data.path}`);\n \n const response = {\n message: 'Hello from device',\n timestamp: Date.now()\n };\n \n await HttpLocalServerSwifter.sendResponse({\n requestId: data.requestId,\n body: JSON.stringify(response)\n });\n});\n\n// Remover listener cuando ya no sea necesario\nawait listener.remove();\n```"
136
- },
137
- {
138
- "name": "since",
139
- "text": "0.1.0"
140
- }
141
- ],
142
- "docs": "Registra un listener para recibir peticiones HTTP entrantes.\n\nEste evento se dispara cada vez que el servidor recibe una petición.\nDebes responder usando `sendResponse()` con el mismo `requestId`.",
64
+ "tags": [],
65
+ "docs": "",
143
66
  "complexTypes": [
144
67
  "PluginListenerHandle",
145
68
  "HttpRequestData"
@@ -151,21 +74,8 @@
151
74
  "signature": "() => Promise<void>",
152
75
  "parameters": [],
153
76
  "returns": "Promise<void>",
154
- "tags": [
155
- {
156
- "name": "returns",
157
- "text": "Promesa que se resuelve cuando se eliminan los listeners"
158
- },
159
- {
160
- "name": "example",
161
- "text": "```typescript\nawait HttpLocalServerSwifter.removeAllListeners();\n```"
162
- },
163
- {
164
- "name": "since",
165
- "text": "0.1.0"
166
- }
167
- ],
168
- "docs": "Elimina todos los listeners del evento 'onRequest'.",
77
+ "tags": [],
78
+ "docs": "",
169
79
  "complexTypes": [],
170
80
  "slug": "removealllisteners"
171
81
  }
@@ -176,21 +86,21 @@
176
86
  {
177
87
  "name": "HttpConnectResult",
178
88
  "slug": "httpconnectresult",
179
- "docs": "Resultado de la conexión del servidor HTTP local",
89
+ "docs": "",
180
90
  "tags": [],
181
91
  "methods": [],
182
92
  "properties": [
183
93
  {
184
94
  "name": "ip",
185
95
  "tags": [],
186
- "docs": "Dirección IP del servidor (ej: \"192.168.1.100\")",
96
+ "docs": "",
187
97
  "complexTypes": [],
188
98
  "type": "string"
189
99
  },
190
100
  {
191
101
  "name": "port",
192
102
  "tags": [],
193
- "docs": "Puerto en el que escucha el servidor (típicamente 8080)",
103
+ "docs": "",
194
104
  "complexTypes": [],
195
105
  "type": "number"
196
106
  }
@@ -199,23 +109,39 @@
199
109
  {
200
110
  "name": "HttpSendResponseOptions",
201
111
  "slug": "httpsendresponseoptions",
202
- "docs": "Opciones para enviar una respuesta HTTP",
112
+ "docs": "Options for sending an HTTP response.\nUpdated to support custom status codes and headers for CORS.",
203
113
  "tags": [],
204
114
  "methods": [],
205
115
  "properties": [
206
116
  {
207
117
  "name": "requestId",
208
118
  "tags": [],
209
- "docs": "ID de la petición (recibido en el evento 'onRequest')",
119
+ "docs": "The ID received in the 'onRequest' event",
210
120
  "complexTypes": [],
211
121
  "type": "string"
212
122
  },
213
123
  {
214
124
  "name": "body",
215
125
  "tags": [],
216
- "docs": "Cuerpo de la respuesta. Típicamente un JSON stringificado.\nEjemplo: JSON.stringify({ success: true, data: {...} })",
126
+ "docs": "The response body (usually stringified JSON)",
217
127
  "complexTypes": [],
218
128
  "type": "string"
129
+ },
130
+ {
131
+ "name": "status",
132
+ "tags": [],
133
+ "docs": "* NEW: HTTP Status code (e.g., 200, 204, 404). \nDefault is 200.",
134
+ "complexTypes": [],
135
+ "type": "number | undefined"
136
+ },
137
+ {
138
+ "name": "headers",
139
+ "tags": [],
140
+ "docs": "* NEW: Custom HTTP headers.\nCrucial for fixing CORS by providing 'Access-Control-Allow-Origin'.",
141
+ "complexTypes": [
142
+ "Record"
143
+ ],
144
+ "type": "Record<string, string>"
219
145
  }
220
146
  ]
221
147
  },
@@ -238,42 +164,42 @@
238
164
  {
239
165
  "name": "HttpRequestData",
240
166
  "slug": "httprequestdata",
241
- "docs": "Datos de una petición HTTP entrante",
167
+ "docs": "",
242
168
  "tags": [],
243
169
  "methods": [],
244
170
  "properties": [
245
171
  {
246
172
  "name": "requestId",
247
173
  "tags": [],
248
- "docs": "ID único de la petición. Debe usarse en sendResponse()",
174
+ "docs": "",
249
175
  "complexTypes": [],
250
176
  "type": "string"
251
177
  },
252
178
  {
253
179
  "name": "method",
254
180
  "tags": [],
255
- "docs": "Método HTTP (GET, POST, PUT, PATCH, DELETE, OPTIONS)",
181
+ "docs": "",
256
182
  "complexTypes": [],
257
183
  "type": "string"
258
184
  },
259
185
  {
260
186
  "name": "path",
261
187
  "tags": [],
262
- "docs": "Ruta de la petición (ej: \"/api/users\")",
188
+ "docs": "",
263
189
  "complexTypes": [],
264
190
  "type": "string"
265
191
  },
266
192
  {
267
193
  "name": "body",
268
194
  "tags": [],
269
- "docs": "Cuerpo de la petición (opcional, presente en POST/PUT/PATCH)\nTípicamente es un string JSON",
195
+ "docs": "",
270
196
  "complexTypes": [],
271
197
  "type": "string | undefined"
272
198
  },
273
199
  {
274
200
  "name": "headers",
275
201
  "tags": [],
276
- "docs": "Encabezados HTTP de la petición",
202
+ "docs": "",
277
203
  "complexTypes": [
278
204
  "Record"
279
205
  ],
@@ -282,7 +208,7 @@
282
208
  {
283
209
  "name": "query",
284
210
  "tags": [],
285
- "docs": "Parámetros de query string (ej: { id: \"123\", name: \"test\" })",
211
+ "docs": "",
286
212
  "complexTypes": [
287
213
  "Record"
288
214
  ],
@@ -1,170 +1,42 @@
1
1
  import type { PluginListenerHandle } from '@capacitor/core';
2
- /**
3
- * Resultado de la conexión del servidor HTTP local
4
- */
5
2
  export interface HttpConnectResult {
6
- /**
7
- * Dirección IP del servidor (ej: "192.168.1.100")
8
- */
9
3
  ip: string;
10
- /**
11
- * Puerto en el que escucha el servidor (típicamente 8080)
12
- */
13
4
  port: number;
14
5
  }
15
- /**
16
- * Datos de una petición HTTP entrante
17
- */
18
6
  export interface HttpRequestData {
19
- /**
20
- * ID único de la petición. Debe usarse en sendResponse()
21
- */
22
7
  requestId: string;
23
- /**
24
- * Método HTTP (GET, POST, PUT, PATCH, DELETE, OPTIONS)
25
- */
26
8
  method: string;
27
- /**
28
- * Ruta de la petición (ej: "/api/users")
29
- */
30
9
  path: string;
31
- /**
32
- * Cuerpo de la petición (opcional, presente en POST/PUT/PATCH)
33
- * Típicamente es un string JSON
34
- */
35
10
  body?: string;
36
- /**
37
- * Encabezados HTTP de la petición
38
- */
39
11
  headers?: Record<string, string>;
40
- /**
41
- * Parámetros de query string (ej: { id: "123", name: "test" })
42
- */
43
12
  query?: Record<string, string>;
44
13
  }
45
14
  /**
46
- * Opciones para enviar una respuesta HTTP
15
+ * Options for sending an HTTP response.
16
+ * Updated to support custom status codes and headers for CORS.
47
17
  */
48
18
  export interface HttpSendResponseOptions {
49
- /**
50
- * ID de la petición (recibido en el evento 'onRequest')
51
- */
19
+ /** The ID received in the 'onRequest' event */
52
20
  requestId: string;
53
- /**
54
- * Cuerpo de la respuesta. Típicamente un JSON stringificado.
55
- * Ejemplo: JSON.stringify({ success: true, data: {...} })
56
- */
21
+ /** The response body (usually stringified JSON) */
57
22
  body: string;
23
+ /** * NEW: HTTP Status code (e.g., 200, 204, 404).
24
+ * Default is 200.
25
+ */
26
+ status?: number;
27
+ /** * NEW: Custom HTTP headers.
28
+ * Crucial for fixing CORS by providing 'Access-Control-Allow-Origin'.
29
+ */
30
+ headers?: Record<string, string>;
58
31
  }
59
- /**
60
- * Plugin para ejecutar un servidor HTTP local en dispositivos iOS y Android.
61
- *
62
- * Permite recibir peticiones HTTP desde otros dispositivos en la red local
63
- * y responder desde JavaScript/TypeScript.
64
- *
65
- * @since 0.1.0
66
- */
67
32
  export interface HttpLocalServerSwifterPlugin {
68
- /**
69
- * Inicia el servidor HTTP local en el dispositivo.
70
- *
71
- * El servidor escucha en todas las interfaces de red (0.0.0.0)
72
- * y es accesible desde otros dispositivos en la misma red local.
73
- *
74
- * @returns Promesa con la IP y puerto del servidor
75
- * @throws Error si el servidor no puede iniciarse (ej: puerto ocupado)
76
- *
77
- * @example
78
- * ```typescript
79
- * const { ip, port } = await HttpLocalServerSwifter.connect();
80
- * console.log(`Servidor corriendo en http://${ip}:${port}`);
81
- * ```
82
- *
83
- * @since 0.1.0
84
- */
85
33
  connect(): Promise<HttpConnectResult>;
86
- /**
87
- * Detiene el servidor HTTP local.
88
- *
89
- * Cierra todas las conexiones activas y libera el puerto.
90
- * Las peticiones pendientes recibirán un timeout.
91
- *
92
- * @returns Promesa que se resuelve cuando el servidor se detiene
93
- *
94
- * @example
95
- * ```typescript
96
- * await HttpLocalServerSwifter.disconnect();
97
- * console.log('Servidor detenido');
98
- * ```
99
- *
100
- * @since 0.1.0
101
- */
102
34
  disconnect(): Promise<void>;
103
35
  /**
104
- * Envía una respuesta HTTP de vuelta al cliente.
105
- *
106
- * Debe llamarse con el `requestId` recibido en el evento 'onRequest'.
107
- * Si no se llama dentro de 5 segundos, el cliente recibirá un timeout (408).
108
- *
109
- * @param options - Objeto con requestId y cuerpo de la respuesta
110
- * @returns Promesa que se resuelve cuando la respuesta se envía
111
- * @throws Error si faltan requestId o body
112
- *
113
- * @example
114
- * ```typescript
115
- * await HttpLocalServerSwifter.sendResponse({
116
- * requestId: '123-456-789',
117
- * body: JSON.stringify({ status: 'ok', data: { id: 1 } })
118
- * });
119
- * ```
120
- *
121
- * @since 0.1.0
36
+ * Sends a response back to the client.
37
+ * Now supports status and headers to handle CORS Preflight correctly.
122
38
  */
123
39
  sendResponse(options: HttpSendResponseOptions): Promise<void>;
124
- /**
125
- * Registra un listener para recibir peticiones HTTP entrantes.
126
- *
127
- * Este evento se dispara cada vez que el servidor recibe una petición.
128
- * Debes responder usando `sendResponse()` con el mismo `requestId`.
129
- *
130
- * @param eventName - Debe ser 'onRequest'
131
- * @param listenerFunc - Callback que recibe los datos de la petición
132
- * @returns Handle para remover el listener posteriormente
133
- *
134
- * @example
135
- * ```typescript
136
- * const listener = await HttpLocalServerSwifter.addListener('onRequest', async (data) => {
137
- * console.log(`${data.method} ${data.path}`);
138
- *
139
- * const response = {
140
- * message: 'Hello from device',
141
- * timestamp: Date.now()
142
- * };
143
- *
144
- * await HttpLocalServerSwifter.sendResponse({
145
- * requestId: data.requestId,
146
- * body: JSON.stringify(response)
147
- * });
148
- * });
149
- *
150
- * // Remover listener cuando ya no sea necesario
151
- * await listener.remove();
152
- * ```
153
- *
154
- * @since 0.1.0
155
- */
156
40
  addListener(eventName: 'onRequest', listenerFunc: (data: HttpRequestData) => void | Promise<void>): Promise<PluginListenerHandle>;
157
- /**
158
- * Elimina todos los listeners del evento 'onRequest'.
159
- *
160
- * @returns Promesa que se resuelve cuando se eliminan los listeners
161
- *
162
- * @example
163
- * ```typescript
164
- * await HttpLocalServerSwifter.removeAllListeners();
165
- * ```
166
- *
167
- * @since 0.1.0
168
- */
169
41
  removeAllListeners(): Promise<void>;
170
42
  }
@@ -1 +1 @@
1
- {"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["import type { PluginListenerHandle } from '@capacitor/core';\n\n/**\n * Resultado de la conexión del servidor HTTP local\n */\nexport interface HttpConnectResult {\n /**\n * Dirección IP del servidor (ej: \"192.168.1.100\")\n */\n ip: string;\n\n /**\n * Puerto en el que escucha el servidor (típicamente 8080)\n */\n port: number;\n}\n\n/**\n * Datos de una petición HTTP entrante\n */\nexport interface HttpRequestData {\n /**\n * ID único de la petición. Debe usarse en sendResponse()\n */\n requestId: string;\n\n /**\n * Método HTTP (GET, POST, PUT, PATCH, DELETE, OPTIONS)\n */\n method: string;\n\n /**\n * Ruta de la petición (ej: \"/api/users\")\n */\n path: string;\n\n /**\n * Cuerpo de la petición (opcional, presente en POST/PUT/PATCH)\n * Típicamente es un string JSON\n */\n body?: string;\n\n /**\n * Encabezados HTTP de la petición\n */\n headers?: Record<string, string>;\n\n /**\n * Parámetros de query string (ej: { id: \"123\", name: \"test\" })\n */\n query?: Record<string, string>;\n}\n\n/**\n * Opciones para enviar una respuesta HTTP\n */\nexport interface HttpSendResponseOptions {\n /**\n * ID de la petición (recibido en el evento 'onRequest')\n */\n requestId: string;\n\n /**\n * Cuerpo de la respuesta. Típicamente un JSON stringificado.\n * Ejemplo: JSON.stringify({ success: true, data: {...} })\n */\n body: string;\n}\n\n/**\n * Plugin para ejecutar un servidor HTTP local en dispositivos iOS y Android.\n * \n * Permite recibir peticiones HTTP desde otros dispositivos en la red local\n * y responder desde JavaScript/TypeScript.\n * \n * @since 0.1.0\n */\nexport interface HttpLocalServerSwifterPlugin {\n /**\n * Inicia el servidor HTTP local en el dispositivo.\n * \n * El servidor escucha en todas las interfaces de red (0.0.0.0)\n * y es accesible desde otros dispositivos en la misma red local.\n * \n * @returns Promesa con la IP y puerto del servidor\n * @throws Error si el servidor no puede iniciarse (ej: puerto ocupado)\n * \n * @example\n * ```typescript\n * const { ip, port } = await HttpLocalServerSwifter.connect();\n * console.log(`Servidor corriendo en http://${ip}:${port}`);\n * ```\n * \n * @since 0.1.0\n */\n connect(): Promise<HttpConnectResult>;\n\n /**\n * Detiene el servidor HTTP local.\n * \n * Cierra todas las conexiones activas y libera el puerto.\n * Las peticiones pendientes recibirán un timeout.\n * \n * @returns Promesa que se resuelve cuando el servidor se detiene\n * \n * @example\n * ```typescript\n * await HttpLocalServerSwifter.disconnect();\n * console.log('Servidor detenido');\n * ```\n * \n * @since 0.1.0\n */\n disconnect(): Promise<void>;\n\n /**\n * Envía una respuesta HTTP de vuelta al cliente.\n * \n * Debe llamarse con el `requestId` recibido en el evento 'onRequest'.\n * Si no se llama dentro de 5 segundos, el cliente recibirá un timeout (408).\n * \n * @param options - Objeto con requestId y cuerpo de la respuesta\n * @returns Promesa que se resuelve cuando la respuesta se envía\n * @throws Error si faltan requestId o body\n * \n * @example\n * ```typescript\n * await HttpLocalServerSwifter.sendResponse({\n * requestId: '123-456-789',\n * body: JSON.stringify({ status: 'ok', data: { id: 1 } })\n * });\n * ```\n * \n * @since 0.1.0\n */\n sendResponse(options: HttpSendResponseOptions): Promise<void>;\n\n /**\n * Registra un listener para recibir peticiones HTTP entrantes.\n * \n * Este evento se dispara cada vez que el servidor recibe una petición.\n * Debes responder usando `sendResponse()` con el mismo `requestId`.\n * \n * @param eventName - Debe ser 'onRequest'\n * @param listenerFunc - Callback que recibe los datos de la petición\n * @returns Handle para remover el listener posteriormente\n * \n * @example\n * ```typescript\n * const listener = await HttpLocalServerSwifter.addListener('onRequest', async (data) => {\n * console.log(`${data.method} ${data.path}`);\n * \n * const response = {\n * message: 'Hello from device',\n * timestamp: Date.now()\n * };\n * \n * await HttpLocalServerSwifter.sendResponse({\n * requestId: data.requestId,\n * body: JSON.stringify(response)\n * });\n * });\n * \n * // Remover listener cuando ya no sea necesario\n * await listener.remove();\n * ```\n * \n * @since 0.1.0\n */\n addListener(\n eventName: 'onRequest',\n listenerFunc: (data: HttpRequestData) => void | Promise<void>\n ): Promise<PluginListenerHandle>;\n\n /**\n * Elimina todos los listeners del evento 'onRequest'.\n * \n * @returns Promesa que se resuelve cuando se eliminan los listeners\n * \n * @example\n * ```typescript\n * await HttpLocalServerSwifter.removeAllListeners();\n * ```\n * \n * @since 0.1.0\n */\n removeAllListeners(): Promise<void>;\n}"]}
1
+ {"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["import type { PluginListenerHandle } from '@capacitor/core';\n\nexport interface HttpConnectResult {\n ip: string;\n port: number;\n}\n\nexport interface HttpRequestData {\n requestId: string;\n method: string;\n path: string;\n body?: string;\n headers?: Record<string, string>;\n query?: Record<string, string>;\n}\n\n/**\n * Options for sending an HTTP response.\n * Updated to support custom status codes and headers for CORS.\n */\nexport interface HttpSendResponseOptions {\n /** The ID received in the 'onRequest' event */\n requestId: string;\n\n /** The response body (usually stringified JSON) */\n body: string;\n\n /** * NEW: HTTP Status code (e.g., 200, 204, 404). \n * Default is 200.\n */\n status?: number;\n\n /** * NEW: Custom HTTP headers.\n * Crucial for fixing CORS by providing 'Access-Control-Allow-Origin'.\n */\n headers?: Record<string, string>;\n}\n\nexport interface HttpLocalServerSwifterPlugin {\n connect(): Promise<HttpConnectResult>;\n disconnect(): Promise<void>;\n\n /**\n * Sends a response back to the client.\n * Now supports status and headers to handle CORS Preflight correctly.\n */\n sendResponse(options: HttpSendResponseOptions): Promise<void>;\n\n addListener(\n eventName: 'onRequest',\n listenerFunc: (data: HttpRequestData) => void | Promise<void>\n ): Promise<PluginListenerHandle>;\n\n removeAllListeners(): Promise<void>;\n}"]}
@@ -1,32 +1,9 @@
1
1
  import type { HttpLocalServerSwifterPlugin } from './definitions';
2
2
  /**
3
- * Plugin de servidor HTTP local para Android e iOS.
4
- *
5
- * Permite crear un servidor HTTP en el dispositivo que puede recibir
6
- * peticiones desde otros dispositivos en la misma red local.
7
- *
8
- * @example
9
- * ```typescript
10
- * import { HttpLocalServerSwifter } from '@cappitolian/http-local-server-swifter';
11
- *
12
- * // Iniciar servidor
13
- * const { ip, port } = await HttpLocalServerSwifter.connect();
14
- * console.log(`Servidor en http://${ip}:${port}`);
15
- *
16
- * // Escuchar peticiones
17
- * await HttpLocalServerSwifter.addListener('onRequest', async (data) => {
18
- * console.log('Petición recibida:', data);
19
- *
20
- * // Procesar y responder
21
- * await HttpLocalServerSwifter.sendResponse({
22
- * requestId: data.requestId,
23
- * body: JSON.stringify({ success: true })
24
- * });
25
- * });
26
- *
27
- * // Detener servidor
28
- * await HttpLocalServerSwifter.disconnect();
29
- * ```
3
+ * Local HTTP server plugin for Android and iOS.
4
+ * * Allows creating an HTTP server on the device that can receive
5
+ * requests from other devices on the same local network or
6
+ * from the app's own WebView (fixing CORS issues).
30
7
  */
31
8
  declare const HttpLocalServerSwifter: HttpLocalServerSwifterPlugin;
32
9
  export * from './definitions';
package/dist/esm/index.js CHANGED
@@ -1,36 +1,15 @@
1
1
  import { registerPlugin } from '@capacitor/core';
2
2
  /**
3
- * Plugin de servidor HTTP local para Android e iOS.
4
- *
5
- * Permite crear un servidor HTTP en el dispositivo que puede recibir
6
- * peticiones desde otros dispositivos en la misma red local.
7
- *
8
- * @example
9
- * ```typescript
10
- * import { HttpLocalServerSwifter } from '@cappitolian/http-local-server-swifter';
11
- *
12
- * // Iniciar servidor
13
- * const { ip, port } = await HttpLocalServerSwifter.connect();
14
- * console.log(`Servidor en http://${ip}:${port}`);
15
- *
16
- * // Escuchar peticiones
17
- * await HttpLocalServerSwifter.addListener('onRequest', async (data) => {
18
- * console.log('Petición recibida:', data);
19
- *
20
- * // Procesar y responder
21
- * await HttpLocalServerSwifter.sendResponse({
22
- * requestId: data.requestId,
23
- * body: JSON.stringify({ success: true })
24
- * });
25
- * });
26
- *
27
- * // Detener servidor
28
- * await HttpLocalServerSwifter.disconnect();
29
- * ```
3
+ * Local HTTP server plugin for Android and iOS.
4
+ * * Allows creating an HTTP server on the device that can receive
5
+ * requests from other devices on the same local network or
6
+ * from the app's own WebView (fixing CORS issues).
30
7
  */
31
8
  const HttpLocalServerSwifter = registerPlugin('HttpLocalServerSwifter', {
9
+ // We point to the web mock for browser development
32
10
  web: () => import('./web').then(m => new m.HttpLocalServerSwifterWeb()),
33
11
  });
12
+ // Re-export everything from definitions so they are available to the app
34
13
  export * from './definitions';
35
14
  export { HttpLocalServerSwifter };
36
15
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAGjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,sBAAsB,GAAG,cAAc,CAA+B,wBAAwB,EAAE;IACpG,GAAG,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,yBAAyB,EAAE,CAAC;CACxE,CAAC,CAAC;AAEH,cAAc,eAAe,CAAC;AAC9B,OAAO,EAAE,sBAAsB,EAAE,CAAC","sourcesContent":["import { registerPlugin } from '@capacitor/core';\nimport type { HttpLocalServerSwifterPlugin } from './definitions';\n\n/**\n * Plugin de servidor HTTP local para Android e iOS.\n * \n * Permite crear un servidor HTTP en el dispositivo que puede recibir\n * peticiones desde otros dispositivos en la misma red local.\n * \n * @example\n * ```typescript\n * import { HttpLocalServerSwifter } from '@cappitolian/http-local-server-swifter';\n * \n * // Iniciar servidor\n * const { ip, port } = await HttpLocalServerSwifter.connect();\n * console.log(`Servidor en http://${ip}:${port}`);\n * \n * // Escuchar peticiones\n * await HttpLocalServerSwifter.addListener('onRequest', async (data) => {\n * console.log('Petición recibida:', data);\n * \n * // Procesar y responder\n * await HttpLocalServerSwifter.sendResponse({\n * requestId: data.requestId,\n * body: JSON.stringify({ success: true })\n * });\n * });\n * \n * // Detener servidor\n * await HttpLocalServerSwifter.disconnect();\n * ```\n */\nconst HttpLocalServerSwifter = registerPlugin<HttpLocalServerSwifterPlugin>('HttpLocalServerSwifter', {\n web: () => import('./web').then(m => new m.HttpLocalServerSwifterWeb()),\n});\n\nexport * from './definitions';\nexport { HttpLocalServerSwifter };"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAGjD;;;;;GAKG;AACH,MAAM,sBAAsB,GAAG,cAAc,CAA+B,wBAAwB,EAAE;IACpG,mDAAmD;IACnD,GAAG,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,yBAAyB,EAAE,CAAC;CACxE,CAAC,CAAC;AAEH,yEAAyE;AACzE,cAAc,eAAe,CAAC;AAC9B,OAAO,EAAE,sBAAsB,EAAE,CAAC","sourcesContent":["import { registerPlugin } from '@capacitor/core';\nimport type { HttpLocalServerSwifterPlugin } from './definitions';\n\n/**\n * Local HTTP server plugin for Android and iOS.\n * * Allows creating an HTTP server on the device that can receive\n * requests from other devices on the same local network or \n * from the app's own WebView (fixing CORS issues).\n */\nconst HttpLocalServerSwifter = registerPlugin<HttpLocalServerSwifterPlugin>('HttpLocalServerSwifter', {\n // We point to the web mock for browser development\n web: () => import('./web').then(m => new m.HttpLocalServerSwifterWeb()),\n});\n\n// Re-export everything from definitions so they are available to the app\nexport * from './definitions';\nexport { HttpLocalServerSwifter };"]}
package/dist/esm/web.d.ts CHANGED
@@ -1,11 +1,5 @@
1
1
  import { WebPlugin } from '@capacitor/core';
2
2
  import type { HttpLocalServerSwifterPlugin, HttpConnectResult, HttpSendResponseOptions } from './definitions';
3
- /**
4
- * Implementación web (mock) del plugin HttpLocalServerSwifter.
5
- *
6
- * Proporciona funcionalidad simulada para desarrollo en navegador.
7
- * El servidor real solo funciona en dispositivos iOS/Android nativos.
8
- */
9
3
  export declare class HttpLocalServerSwifterWeb extends WebPlugin implements HttpLocalServerSwifterPlugin {
10
4
  private isRunning;
11
5
  connect(): Promise<HttpConnectResult>;
package/dist/esm/web.js CHANGED
@@ -1,49 +1,23 @@
1
1
  import { WebPlugin } from '@capacitor/core';
2
- /**
3
- * Implementación web (mock) del plugin HttpLocalServerSwifter.
4
- *
5
- * Proporciona funcionalidad simulada para desarrollo en navegador.
6
- * El servidor real solo funciona en dispositivos iOS/Android nativos.
7
- */
8
2
  export class HttpLocalServerSwifterWeb extends WebPlugin {
9
3
  constructor() {
10
4
  super(...arguments);
11
5
  this.isRunning = false;
12
6
  }
13
7
  async connect() {
14
- if (this.isRunning) {
15
- console.warn('[HttpLocalServerSwifter Web] El servidor ya está ejecutándose (Mock).');
16
- return { ip: '127.0.0.1', port: 8080 };
17
- }
18
- console.warn('[HttpLocalServerSwifter Web] El servidor HTTP nativo no está disponible en navegador.\n' +
19
- 'Retornando valores mock para desarrollo.\n' +
20
- 'Para funcionalidad real, ejecuta en un dispositivo iOS/Android.');
21
8
  this.isRunning = true;
22
- return {
23
- ip: '127.0.0.1',
24
- port: 8080
25
- };
9
+ console.warn('[HttpLocalServerSwifter Web] Mock server started at 127.0.0.1:8080');
10
+ return { ip: '127.0.0.1', port: 8080 };
26
11
  }
27
12
  async disconnect() {
28
- if (!this.isRunning) {
29
- console.log('[HttpLocalServerSwifter Web] El servidor ya está detenido (Mock).');
30
- return;
31
- }
32
- console.log('[HttpLocalServerSwifter Web] Servidor detenido (Mock).');
33
13
  this.isRunning = false;
14
+ console.log('[HttpLocalServerSwifter Web] Mock server stopped.');
34
15
  }
35
16
  async sendResponse(options) {
36
- if (!this.isRunning) {
37
- throw new Error('Server is not running. Call connect() first.');
38
- }
39
- const { requestId, body } = options;
40
- if (!requestId) {
41
- throw new Error('Missing requestId');
42
- }
43
- if (!body) {
44
- throw new Error('Missing body');
45
- }
46
- console.log(`[HttpLocalServerSwifter Web] Mock response sent for requestId: ${requestId}`, '\nBody preview:', body.substring(0, 100) + (body.length > 100 ? '...' : ''));
17
+ if (!this.isRunning)
18
+ throw new Error('Server not running');
19
+ const { requestId, body, status, headers } = options;
20
+ console.log(`[HttpLocalServerSwifter Web] Mock Response:`, { requestId, status: status !== null && status !== void 0 ? status : 200, headers: headers !== null && headers !== void 0 ? headers : {}, bodyLength: body.length });
47
21
  }
48
22
  }
49
23
  //# sourceMappingURL=web.js.map