@swipt/cli 0.1.0-nightly.78 → 0.1.0-nightly.79

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 (68) hide show
  1. package/dist/availability.d.ts +5 -0
  2. package/dist/availability.js +349 -0
  3. package/dist/availability.js.map +1 -0
  4. package/dist/client.d.ts +25 -0
  5. package/dist/client.js +248 -0
  6. package/dist/client.js.map +1 -0
  7. package/dist/connection.d.ts +24 -0
  8. package/dist/connection.js +293 -0
  9. package/dist/connection.js.map +1 -0
  10. package/dist/coredevice.d.ts +22 -0
  11. package/dist/coredevice.js +329 -0
  12. package/dist/coredevice.js.map +1 -0
  13. package/dist/device.d.ts +130 -0
  14. package/dist/device.js +539 -0
  15. package/dist/device.js.map +1 -0
  16. package/dist/i18n.d.ts +2 -0
  17. package/dist/i18n.js +57 -0
  18. package/dist/i18n.js.map +1 -0
  19. package/dist/ignore.d.ts +8 -0
  20. package/dist/ignore.js +112 -0
  21. package/dist/ignore.js.map +1 -0
  22. package/dist/metro.d.ts +10 -0
  23. package/dist/metro.js +349 -0
  24. package/dist/metro.js.map +1 -0
  25. package/dist/output.d.ts +20 -0
  26. package/dist/output.js +116 -0
  27. package/dist/output.js.map +1 -0
  28. package/dist/project.d.ts +18 -0
  29. package/dist/project.js +696 -0
  30. package/dist/project.js.map +1 -0
  31. package/dist/proto/common_pb.js +34 -0
  32. package/dist/proto/common_pb.js.map +1 -0
  33. package/dist/proto/logs_pb.js +15 -0
  34. package/dist/proto/logs_pb.js.map +1 -0
  35. package/dist/proto/repl_pb.js +15 -0
  36. package/dist/proto/repl_pb.js.map +1 -0
  37. package/dist/proto/swiplets_pb.js +28 -0
  38. package/dist/proto/swiplets_pb.js.map +1 -0
  39. package/dist/proto/system_pb.js +15 -0
  40. package/dist/proto/system_pb.js.map +1 -0
  41. package/dist/sideload.d.ts +17 -0
  42. package/dist/sideload.js +1098 -0
  43. package/dist/sideload.js.map +1 -0
  44. package/dist/swipt.d.ts +1 -0
  45. package/dist/swipt.js +631 -0
  46. package/dist/swipt.js.map +1 -0
  47. package/dist/version.d.ts +2 -0
  48. package/dist/version.js +15 -0
  49. package/dist/version.js.map +1 -0
  50. package/package.json +21 -7
  51. package/availability.mjs +0 -642
  52. package/client.mjs +0 -375
  53. package/connection.mjs +0 -450
  54. package/coredevice.mjs +0 -464
  55. package/device.mjs +0 -837
  56. package/i18n.mjs +0 -71
  57. package/ignore.mjs +0 -149
  58. package/metro.mjs +0 -432
  59. package/output.mjs +0 -177
  60. package/project.mjs +0 -1013
  61. package/proto/common_pb.js +0 -98
  62. package/proto/logs_pb.js +0 -34
  63. package/proto/repl_pb.js +0 -55
  64. package/proto/swiplets_pb.js +0 -179
  65. package/proto/system_pb.js +0 -27
  66. package/sideload.mjs +0 -1696
  67. package/swipt.mjs +0 -726
  68. package/version.mjs +0 -16
package/connection.mjs DELETED
@@ -1,450 +0,0 @@
1
- import dgram from "node:dgram";
2
- import { on } from "node:events";
3
- import fs from "node:fs";
4
- import os from "node:os";
5
- import path from "node:path";
6
- import { setTimeout as sleep } from "node:timers/promises";
7
-
8
- import Bonjour from "bonjour-service";
9
- import multicastDNS from "multicast-dns";
10
-
11
- import { Code, RpcError, UsageError, open } from "./client.mjs";
12
- import { tr } from "./i18n.mjs";
13
- import { columns } from "./output.mjs";
14
- import {
15
- DeviceConnectionProblem,
16
- DeviceConnectionState,
17
- } from "./proto/common_pb.js";
18
-
19
- const browseLimit = 1500;
20
- const browseRequery = 300;
21
- const publishLimit = 10_000;
22
- const answerLimit = 5000;
23
-
24
- const storeFile = path.join(
25
- process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"),
26
- "swipt",
27
- "devices.json",
28
- );
29
-
30
- function load() {
31
- let text;
32
- try {
33
- text = fs.readFileSync(storeFile, "utf8");
34
- } catch (error) {
35
- if (error.code === "ENOENT") {
36
- return {};
37
- }
38
- throw error;
39
- }
40
- return JSON.parse(text);
41
- }
42
-
43
- function save(devices) {
44
- fs.mkdirSync(path.dirname(storeFile), { recursive: true, mode: 0o700 });
45
- fs.writeFileSync(storeFile, `${JSON.stringify(devices, null, 2)}\n`, {
46
- mode: 0o600,
47
- });
48
- }
49
-
50
- export function label(name) {
51
- const slug = [...name.replaceAll(/['’]/g, "")]
52
- .map((character) => (/[A-Za-z0-9]/.test(character) ? character : "-"))
53
- .join("")
54
- .split("-")
55
- .filter((part) => part !== "")
56
- .join("-");
57
- return slug === "" ? name : slug;
58
- }
59
-
60
- export const sameName = (a, b) => a.toLowerCase() === b.toLowerCase();
61
-
62
- const storedName = (stored, name) =>
63
- Object.keys(stored).find((it) => sameName(it, name));
64
-
65
- function parseURL(text) {
66
- let parsed;
67
- try {
68
- parsed = new URL(text.includes("://") ? text : `http://${text}`);
69
- } catch {
70
- throw new UsageError(tr("{text} is not a URL", { text }));
71
- }
72
- if (
73
- parsed.hostname === "" ||
74
- (parsed.protocol !== "http:" && parsed.protocol !== "https:")
75
- ) {
76
- throw new UsageError(tr("{text} is not an http or https URL", { text }));
77
- }
78
- let token;
79
- try {
80
- token = decodeURIComponent(parsed.username);
81
- } catch {
82
- token = parsed.username;
83
- }
84
- return {
85
- url: `${parsed.protocol}//${parsed.host}${parsed.pathname.replace(/\/+$/, "")}`,
86
- token,
87
- };
88
- }
89
-
90
- export const withToken = (url) => url.replace("://", "://TOKEN@");
91
-
92
- async function browse(signal, until, limit = browseLimit) {
93
- const bonjour = new Bonjour({
94
- socket: dgram.createSocket("udp4"),
95
- bind: false,
96
- });
97
- const found = new Map();
98
- const enough = new AbortController();
99
- try {
100
- const browser = bonjour.find({ type: "swipt" }, (service) => {
101
- if (!service.host || found.has(service.name)) {
102
- return;
103
- }
104
- const host = service.host.replace(/\.$/, "").toLowerCase();
105
- found.set(service.name, {
106
- name: label(service.name),
107
- url: `http://${host.includes(":") ? `[${host}]` : host}:${service.port}`,
108
- authenticates: service.txt?.auth === "1",
109
- });
110
- if (until?.([...found.values()])) {
111
- enough.abort();
112
- }
113
- });
114
- const requery = setInterval(() => browser.update(), browseRequery);
115
- try {
116
- await sleep(limit, undefined, {
117
- signal: AbortSignal.any([signal, enough.signal]),
118
- });
119
- } catch (error) {
120
- if (signal.aborted) {
121
- throw error;
122
- }
123
- } finally {
124
- clearInterval(requery);
125
- }
126
- browser.stop();
127
- } finally {
128
- bonjour.destroy();
129
- }
130
- return [...found.values()];
131
- }
132
-
133
- export async function findPublished(name, signal) {
134
- const wanted = label(name);
135
- const matches = (service) => sameName(service.name, wanted);
136
- const found = await browse(
137
- signal,
138
- (services) => services.some(matches),
139
- publishLimit,
140
- );
141
- return found.find(matches);
142
- }
143
-
144
- export async function runningSwipt(name, signal) {
145
- const wanted = label(name);
146
- const stored = load();
147
- await discover(signal, stored, (services) =>
148
- services.some((it) => sameName(it.name, wanted)),
149
- );
150
- const known = storedName(stored, wanted);
151
- if (known === undefined) {
152
- return undefined;
153
- }
154
- const client = open(parseURL(stored[known]));
155
- try {
156
- await client.system.getInfo(
157
- {},
158
- { signal: AbortSignal.any([signal, AbortSignal.timeout(answerLimit)]) },
159
- );
160
- } catch (error) {
161
- if (signal.aborted || !(error instanceof RpcError)) {
162
- throw error;
163
- }
164
- if (error.code === Code.Unauthenticated) {
165
- console.error(tr("error: {message}", { message: error.message }));
166
- }
167
- return undefined;
168
- }
169
- return client;
170
- }
171
-
172
- export async function tryUnlock(client, signal) {
173
- try {
174
- for await (const response of client.repl.execute(
175
- { code: "await device.unlock()", args: [], program: false },
176
- { signal },
177
- )) {
178
- if (response.part.case === "error") {
179
- return response.part.value.message;
180
- }
181
- }
182
- } catch (error) {
183
- if (signal.aborted || !(error instanceof RpcError)) {
184
- throw error;
185
- }
186
- return error.message;
187
- }
188
- return undefined;
189
- }
190
-
191
- async function discover(signal, stored, until) {
192
- const found = await browse(signal, until);
193
- let changed = false;
194
- for (const it of found) {
195
- if (it.authenticates) {
196
- continue;
197
- }
198
- const name = storedName(stored, it.name);
199
- if (name === undefined) {
200
- stored[it.name] = it.url;
201
- changed = true;
202
- } else {
203
- const current = parseURL(stored[name]);
204
- if (current.token === "" && current.url !== it.url) {
205
- stored[name] = it.url;
206
- changed = true;
207
- }
208
- }
209
- }
210
- if (changed) {
211
- save(stored);
212
- }
213
- return found;
214
- }
215
-
216
- const requiresToken = (found) =>
217
- tr("{device} requires a token: swipt device add {url}", {
218
- device: found.name,
219
- url: withToken(found.url),
220
- });
221
-
222
- export async function attach(context) {
223
- const given = context.options.device;
224
- const stored = load();
225
- let device;
226
- if (given && /[:/]/.test(given)) {
227
- device = parseURL(given);
228
- } else if (given) {
229
- const name = label(given);
230
- let known = storedName(stored, name);
231
- if (known === undefined) {
232
- const found = (
233
- await discover(context.signal, stored, (services) =>
234
- services.some((it) => sameName(it.name, name)),
235
- )
236
- ).find((it) => sameName(it.name, name));
237
- if (!found) {
238
- throw new Error(
239
- tr('there is no device {device}; "swipt device list" lists them', {
240
- device: name,
241
- }),
242
- );
243
- }
244
- if (found.authenticates) {
245
- throw new Error(requiresToken(found));
246
- }
247
- known = found.name;
248
- }
249
- device = parseURL(stored[known]);
250
- } else {
251
- let found = [];
252
- if (Object.keys(stored).length === 0) {
253
- found = await discover(context.signal, stored);
254
- }
255
- const names = Object.keys(stored);
256
- if (names.length === 0) {
257
- const locked = found.filter((it) => it.authenticates);
258
- if (locked.length > 0) {
259
- throw new Error(locked.map(requiresToken).join("\n"));
260
- }
261
- throw new Error(
262
- tr(
263
- 'there is no device; turn on Swipt › Developer › Local Network, or connect one with "swipt device add URL"',
264
- ),
265
- );
266
- }
267
- if (names.length > 1) {
268
- throw new Error(
269
- tr("there is more than one device: {devices}; choose one with -d", {
270
- devices: names.join(", "),
271
- }),
272
- );
273
- }
274
- device = parseURL(stored[names[0]]);
275
- }
276
- context.target.url = device.url;
277
- return open(device);
278
- }
279
-
280
- const connectionStates = {
281
- [DeviceConnectionState.UNSPECIFIED]: tr("unspecified"),
282
- [DeviceConnectionState.STOPPED]: tr("stopped"),
283
- [DeviceConnectionState.CONNECTING]: tr("connecting"),
284
- [DeviceConnectionState.PREPARING]: tr("preparing"),
285
- [DeviceConnectionState.RUNNING]: tr("running"),
286
- [DeviceConnectionState.FAILED]: tr("failed"),
287
- };
288
-
289
- const connectionProblems = {
290
- [DeviceConnectionProblem.UNREACHABLE]: tr("unreachable"),
291
- [DeviceConnectionProblem.PAIRING_REJECTED]: tr("pairing rejected"),
292
- [DeviceConnectionProblem.DEVELOPER_MODE_OFF]: tr("developer mode off"),
293
- [DeviceConnectionProblem.DISK_IMAGE_MISSING]: tr("disk image missing"),
294
- [DeviceConnectionProblem.DISK_IMAGE_MOUNT_FAILED]: tr(
295
- "disk image mount failed",
296
- ),
297
- [DeviceConnectionProblem.DEVICE_UNSUPPORTED]: tr("device unsupported"),
298
- [DeviceConnectionProblem.SCREEN_IN_USE]: tr("screen in use"),
299
- [DeviceConnectionProblem.VPN_PEER_ADDRESS_MISSING]: tr(
300
- "VPN peer address missing",
301
- ),
302
- [DeviceConnectionProblem.OTHER]: tr("other"),
303
- };
304
-
305
- function connectionText(connection) {
306
- let text = connectionStates[connection?.state ?? 0];
307
- if (
308
- connection &&
309
- connection.problem !== DeviceConnectionProblem.UNSPECIFIED
310
- ) {
311
- text += `, ${connectionProblems[connection.problem]}`;
312
- }
313
- if (connection?.message) {
314
- text += `: ${connection.message}`;
315
- }
316
- return text;
317
- }
318
-
319
- async function onLocalNetwork(host, signal) {
320
- const mdns = multicastDNS({
321
- socket: dgram.createSocket("udp4"),
322
- bind: false,
323
- });
324
- const query = () =>
325
- mdns.query([
326
- { name: host, type: "A" },
327
- { name: host, type: "AAAA" },
328
- ]);
329
- const requery = setInterval(query, browseRequery);
330
- query();
331
- try {
332
- for await (const [response] of on(mdns, "response", { signal })) {
333
- if (response.answers.some((it) => sameName(it.name, host))) {
334
- return true;
335
- }
336
- }
337
- } catch (error) {
338
- if (!signal.aborted) {
339
- throw error;
340
- }
341
- } finally {
342
- clearInterval(requery);
343
- mdns.destroy();
344
- }
345
- return false;
346
- }
347
-
348
- async function probe(url, signal) {
349
- try {
350
- const device = parseURL(url);
351
- const { hostname } = new URL(device.url);
352
- if (
353
- hostname.endsWith(".local") &&
354
- !(await onLocalNetwork(hostname, signal))
355
- ) {
356
- return { cells: [tr("offline")] };
357
- }
358
- const info = await open(device).system.getInfo({}, { signal });
359
- return {
360
- cells: [
361
- `${info.appVersion} (${info.appBuild})`,
362
- connectionText(info.deviceConnection),
363
- ],
364
- };
365
- } catch (error) {
366
- if (error instanceof RpcError && error.code === Code.Unauthenticated) {
367
- return { cells: [tr("requires a token")] };
368
- }
369
- return {
370
- cells: [tr("offline")],
371
- failure: signal.aborted ? undefined : error.message,
372
- };
373
- }
374
- }
375
-
376
- export async function list({ signal }) {
377
- const stored = load();
378
- const deadline = AbortSignal.any([signal, AbortSignal.timeout(browseLimit)]);
379
- const probes = new Map(
380
- Object.values(stored).map((url) => [url, probe(url, deadline)]),
381
- );
382
- const locked = (await discover(signal, stored)).filter(
383
- (it) => it.authenticates && storedName(stored, it.name) === undefined,
384
- );
385
- const names = Object.keys(stored).sort((a, b) => a.localeCompare(b));
386
- if (names.length === 0 && locked.length === 0) {
387
- console.error(
388
- tr(
389
- 'no device publishes Swipt on the local network; turn on Swipt › Developer › Local Network, or connect one with "swipt device add URL"',
390
- ),
391
- );
392
- return;
393
- }
394
- const late = AbortSignal.any([signal, AbortSignal.timeout(browseLimit)]);
395
- const probed = await Promise.all(
396
- names.map(async (name) => ({
397
- name,
398
- ...(await (probes.get(stored[name]) ?? probe(stored[name], late))),
399
- })),
400
- );
401
- console.log(
402
- columns(
403
- [
404
- ...probed.map(({ name, cells }) => [
405
- name,
406
- parseURL(stored[name]).url,
407
- ...cells,
408
- ]),
409
- ...locked.map((it) => [it.name, it.url, tr("requires a token")]),
410
- ].sort((a, b) => a[0].localeCompare(b[0])),
411
- ),
412
- );
413
- for (const { name, failure } of probed) {
414
- if (failure !== undefined) {
415
- console.error(`${name}: ${failure}`);
416
- }
417
- }
418
- for (const it of locked) {
419
- console.error(requiresToken(it));
420
- }
421
- }
422
-
423
- export async function add(context) {
424
- const device = parseURL(context.args[0]);
425
- context.target.url = device.url;
426
- const info = await open(device).system.getInfo(
427
- {},
428
- { signal: context.signal },
429
- );
430
- const name = label(info.deviceName) || new URL(device.url).hostname;
431
- const stored = load();
432
- const previous = storedName(stored, name);
433
- if (previous !== undefined) {
434
- delete stored[previous];
435
- }
436
- stored[name] = context.args[0];
437
- save(stored);
438
- console.log(tr("added {device}", { device: name }));
439
- }
440
-
441
- export function remove({ args }) {
442
- const stored = load();
443
- const name = storedName(stored, label(args[0]));
444
- if (name === undefined) {
445
- throw new Error(tr("there is no device {device}", { device: args[0] }));
446
- }
447
- delete stored[name];
448
- save(stored);
449
- console.log(tr("removed {name}", { name }));
450
- }