@sola-air-ui/relay 1.0.3 → 2.0.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.
Files changed (3) hide show
  1. package/README.md +30 -8
  2. package/package.json +1 -1
  3. package/src/index.js +41 -25
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @sola-air-ui/relay
2
2
 
3
- A local data proxy for [Sola AIR](https://sola-air.dev)'s `createData`/`$data` primitive — keeps database credentials on your own machine (or server) instead of shipping them to the browser, and streams live query results to Sola components over a local connection.
3
+ A local data proxy for [Sola AIR](https://sola-air.dev)'s `createData`/`$data` primitive. It keeps database credentials on your own machine (or server) instead of shipping them to the browser, and answers Sola components' queries over a local HTTP endpoint.
4
4
 
5
5
  ## Install
6
6
 
@@ -8,35 +8,57 @@ A local data proxy for [Sola AIR](https://sola-air.dev)'s `createData`/`$data` p
8
8
  npm install @sola-air-ui/relay
9
9
  ```
10
10
 
11
+ ## Configure
12
+
13
+ The relay reads `sola-relay.json` from the directory you start it in. Each entry under `connections` is a name you choose plus its settings:
14
+
15
+ ```json
16
+ {
17
+ "connections": {
18
+ "postgres-primary": { "type": "postgres", "connectionString": "postgres://user:pass@localhost:5432/mydb" },
19
+ "orders-db": { "type": "mysql", "host": "localhost", "user": "reader", "password": "…", "database": "shop" }
20
+ }
21
+ }
22
+ ```
23
+
24
+ `postgres` settings go to `pg`'s `Pool`, and `mysql` settings to `mysql2`'s `createPool`. Give the relay a read-only database user.
25
+
11
26
  ## Run
12
27
 
13
28
  ```bash
14
- npx sola-relay --db postgres://user:pass@localhost:5432/mydb
29
+ npx sola-relay --port 4040
15
30
  ```
16
31
 
17
- By default this starts a local relay process that Sola's `createData()` calls connect to for real-time data sync — your Postgres/MySQL credentials never leave the process running the relay.
32
+ `--port` is the only option (default `4040`). The relay serves `POST /api/query`, `GET /api/schema?source=…` and `GET /api/status`, which lists each connection and whether it connected.
18
33
 
19
34
  ## Supported data sources
20
35
 
21
36
  - **PostgreSQL** (via `pg`)
22
37
  - **MySQL** (via `mysql2`)
23
- - Live updates pushed to connected clients over WebSocket (`ws`)
38
+ - **Google Sheets** (`type: "sheet"` with a `sheetId`): reads a sheet that is shared publicly, as CSV.
39
+ - **REST table API** (`type: "rest-table"`): reads, and can update, records through a table-style JSON API. Settings: `host` (a hostname such as `records.example.com`, or a full URL), `table` (default table name), and either `token` or `username` and `password`. Each can come from the environment instead: `REST_TABLE_HOST`, `REST_TABLE_BEARER_TOKEN`, `REST_TABLE_USERNAME`, `REST_TABLE_PASSWORD`. Queries pass `table`, `query`, `fields` and `limit` options.
40
+
41
+ ### Upgrading from 1.x
42
+
43
+ 2.0.0 renames the table connector. Change `type` from the old vendor-named type (or its short alias) to `rest-table`, put a full hostname or URL in `host`, and rename the `SN_*` environment variables to the `REST_TABLE_*` names above. A bare instance name no longer gets a vendor domain added. SQL and Google Sheets connections are unchanged.
24
44
 
25
45
  ## Usage from a component
26
46
 
27
47
  ```html
28
48
  <script>
29
- let customers = $data('postgres-primary:customers', { sync: 'realtime' });
49
+ let customers = $data('postgres-primary:customers', { refresh: '30s' });
30
50
  </script>
31
51
 
32
- <Table rows={customers} />
52
+ <Table rows={() => customers().data} />
33
53
  ```
34
54
 
35
- `postgres-primary` refers to the connection alias configured when you start the relay — see `sola-relay --help` for connection/alias options.
55
+ The source is `connection:table`. `postgres-primary` is a name from `sola-relay.json`, and `customers` is a table in that database (`schema.table` works too). Connection names may use letters, digits, `_` and `-`. Table names must be plain identifiers, because they go into the query. With no `:table`, the connection name is used as the table name. `refresh` re-runs the query on that interval.
36
56
 
37
57
  ## Security note
38
58
 
39
- The relay is designed to run somewhere trusted (your dev machine, or a backend service you control) — never expose its port directly to the public internet without your own auth layer in front of it.
59
+ - SQL connections run a single read-only `SELECT`; anything else gets a 400.
60
+ - Every query is appended to `sola-relay-audit.log` in the working directory.
61
+ - The relay has no authentication of its own. Run it somewhere trusted (your dev machine, or a backend service you control), and never expose its port to the public internet without your own auth layer in front of it.
40
62
 
41
63
  ## License
42
64
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sola-air-ui/relay",
3
- "version": "1.0.3",
3
+ "version": "2.0.0",
4
4
  "description": "Sola Relay — local data proxy that keeps credentials on-device and streams live data to Sola components",
5
5
  "type": "module",
6
6
  "bin": {
package/src/index.js CHANGED
@@ -31,6 +31,18 @@ export function isReadOnlySql(sql) {
31
31
  return true;
32
32
  }
33
33
 
34
+ // A source is `connection` or `connection:table` (as in $data('pg-primary:customers')).
35
+ // The connection is a name from sola-relay.json. The table goes into SQL, so it must
36
+ // be a plain identifier, optionally schema-qualified; anything else is rejected.
37
+ // Without a table, the connection name doubles as the table name, as before.
38
+ const SOURCE_PATTERN = /^([A-Za-z0-9_-]+)(?::([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?))?$/;
39
+
40
+ export function parseSource(source) {
41
+ const m = typeof source === 'string' ? SOURCE_PATTERN.exec(source) : null;
42
+ if (!m) return null;
43
+ return { connection: m[1], table: m[2] ?? null };
44
+ }
45
+
34
46
  // ─── Connectors ───
35
47
  const connectors = new Map();
36
48
 
@@ -137,18 +149,18 @@ class GoogleSheetsConnector {
137
149
  async disconnect() {}
138
150
  }
139
151
 
140
- class ServiceNowConnector {
152
+ class RestTableConnector {
141
153
  constructor(config) {
142
- this.instance = config.instance || config.host || process.env.SN_INSTANCE || '';
143
- this.username = config.username || config.user || process.env.SN_USERNAME || '';
144
- this.password = config.password || process.env.SN_PASSWORD || '';
145
- this.token = config.token || config.bearerToken || process.env.SN_BEARER_TOKEN || '';
154
+ this.instance = config.instance || config.host || process.env.REST_TABLE_HOST || '';
155
+ this.username = config.username || config.user || process.env.REST_TABLE_USERNAME || '';
156
+ this.password = config.password || process.env.REST_TABLE_PASSWORD || '';
157
+ this.token = config.token || config.bearerToken || process.env.REST_TABLE_BEARER_TOKEN || '';
146
158
  this.defaultTable = config.table || 'incident';
147
159
  }
148
160
 
149
161
  async connect() {
150
162
  if (!this.instance) {
151
- throw new Error("ServiceNow instance URL or domain is required (e.g. 'dev12345.service-now.com')");
163
+ throw new Error("REST table host (a hostname or full URL) is required (e.g. 'records.example.com')");
152
164
  }
153
165
  }
154
166
 
@@ -158,7 +170,7 @@ class ServiceNowConnector {
158
170
  const limit = options.limit || options.sysparm_limit || 20;
159
171
  const fields = options.fields || 'number,short_description,priority,state,assigned_to,assignment_group,sys_created_on';
160
172
 
161
- const baseUrl = this.instance.startsWith('http') ? this.instance : `https://${this.instance}.service-now.com`;
173
+ const baseUrl = this.instance.startsWith('http') ? this.instance : `https://${this.instance}`;
162
174
  const endpoint = `${baseUrl}/api/now/table/${table}?sysparm_query=${encodeURIComponent(query)}&sysparm_limit=${limit}&sysparm_display_value=true&sysparm_fields=${encodeURIComponent(fields)}`;
163
175
 
164
176
  const headers = {
@@ -176,7 +188,7 @@ class ServiceNowConnector {
176
188
  const res = await fetch(endpoint, { headers });
177
189
  if (!res.ok) {
178
190
  const errText = await res.text();
179
- throw new Error(`ServiceNow API error (${res.status} ${res.statusText}): ${errText}`);
191
+ throw new Error(`Table API error (${res.status} ${res.statusText}): ${errText}`);
180
192
  }
181
193
 
182
194
  const data = await res.json();
@@ -187,9 +199,9 @@ class ServiceNowConnector {
187
199
  async mutate(action, payload = {}) {
188
200
  const table = payload.table || this.defaultTable;
189
201
  const sysId = payload.sys_id || payload.id;
190
- if (!sysId) throw new Error("sys_id is required to mutate ServiceNow record");
202
+ if (!sysId) throw new Error("sys_id is required to mutate record");
191
203
 
192
- const baseUrl = this.instance.startsWith('http') ? this.instance : `https://${this.instance}.service-now.com`;
204
+ const baseUrl = this.instance.startsWith('http') ? this.instance : `https://${this.instance}`;
193
205
  const endpoint = `${baseUrl}/api/now/table/${table}/${sysId}`;
194
206
 
195
207
  const headers = {
@@ -213,7 +225,7 @@ class ServiceNowConnector {
213
225
 
214
226
  if (!res.ok) {
215
227
  const errText = await res.text();
216
- throw new Error(`ServiceNow mutation error (${res.status} ${res.statusText}): ${errText}`);
228
+ throw new Error(`Table mutation error (${res.status} ${res.statusText}): ${errText}`);
217
229
  }
218
230
 
219
231
  const data = await res.json();
@@ -314,9 +326,8 @@ export function addConnection(name, type, config) {
314
326
  case 'googlesheets':
315
327
  connector = new GoogleSheetsConnector(config);
316
328
  break;
317
- case 'servicenow':
318
- case 'now':
319
- connector = new ServiceNowConnector(config);
329
+ case 'rest-table':
330
+ connector = new RestTableConnector(config);
320
331
  break;
321
332
  default:
322
333
  throw new Error(`Unsupported connector type: ${type}`);
@@ -405,15 +416,16 @@ export class RelayServer {
405
416
  // ── Schema endpoint ──
406
417
  if (url.pathname === '/api/schema' && req.method === 'GET') {
407
418
  const source = url.searchParams.get('source');
408
- if (!source || !/^[a-zA-Z0-9_]+$/.test(source)) {
419
+ const parsedSource = parseSource(source);
420
+ if (!parsedSource) {
409
421
  res.writeHead(400, { 'Content-Type': 'application/json' });
410
422
  res.end(JSON.stringify({ error: 'Invalid source identifier' }));
411
423
  return;
412
424
  }
413
- const conn = connections.get(source);
425
+ const conn = connections.get(parsedSource.connection);
414
426
  if (!conn) {
415
427
  res.writeHead(404, { 'Content-Type': 'application/json' });
416
- res.end(JSON.stringify({ error: `Source '${source}' not found` }));
428
+ res.end(JSON.stringify({ error: `Source '${parsedSource.connection}' not found` }));
417
429
  return;
418
430
  }
419
431
  try {
@@ -447,23 +459,26 @@ export class RelayServer {
447
459
  const parsed = JSON.parse(body);
448
460
  const { source, query, limit } = parsed;
449
461
 
450
- if (!source || !/^[a-zA-Z0-9_]+$/.test(source)) {
462
+ const parsedSource = parseSource(source);
463
+ if (!parsedSource) {
451
464
  res.writeHead(400, { 'Content-Type': 'application/json' });
452
465
  res.end(JSON.stringify({ error: 'Invalid source identifier' }));
453
466
  return;
454
467
  }
468
+ const { connection } = parsedSource;
469
+ const table = parsedSource.table ?? connection;
455
470
 
456
- const conn = connections.get(source);
471
+ const conn = connections.get(connection);
457
472
 
458
473
  if (!conn) {
459
474
  res.writeHead(404, { 'Content-Type': 'application/json' });
460
- res.end(JSON.stringify({ error: `Source '${source}' not found` }));
475
+ res.end(JSON.stringify({ error: `Source '${connection}' not found` }));
461
476
  return;
462
477
  }
463
478
 
464
479
  if (conn.status !== 'connected') {
465
480
  res.writeHead(503, { 'Content-Type': 'application/json' });
466
- res.end(JSON.stringify({ error: `Source '${source}' is not connected` }));
481
+ res.end(JSON.stringify({ error: `Source '${connection}' is not connected` }));
467
482
  return;
468
483
  }
469
484
 
@@ -472,13 +487,14 @@ export class RelayServer {
472
487
  const isNonSql =
473
488
  conn.type === 'sheet' ||
474
489
  conn.type === 'googlesheets' ||
475
- conn.type === 'servicenow' ||
476
- conn.type === 'now';
490
+ conn.type === 'rest-table';
477
491
 
478
492
  let result;
479
493
  if (isNonSql) {
494
+ const options = typeof query === 'object' && query !== null ? query : (query == null ? {} : { query });
480
495
  result = await conn.connector.query({
481
- ...(typeof query === 'object' && query !== null ? query : { query }),
496
+ ...(parsedSource.table && options.table == null ? { table: parsedSource.table } : {}),
497
+ ...options,
482
498
  limit: safeLimit
483
499
  });
484
500
  } else if (typeof query === 'object' && query !== null && typeof query.text === 'string') {
@@ -497,7 +513,7 @@ export class RelayServer {
497
513
  }
498
514
  result = await conn.connector.query(query);
499
515
  } else if (query == null) {
500
- result = await conn.connector.query(`SELECT * FROM ${source} LIMIT ${safeLimit}`);
516
+ result = await conn.connector.query(`SELECT * FROM ${table} LIMIT ${safeLimit}`);
501
517
  } else {
502
518
  res.writeHead(400, { 'Content-Type': 'application/json' });
503
519
  res.end(JSON.stringify({ error: 'Only SELECT queries are permitted' }));