kamoji-dev 0.0.0-stage → 0.1.1
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 +134 -2
- package/bin/kamoji.js +9 -0
- package/package.json +31 -4
- package/spec/VALIDATION.md +68 -0
- package/src/ble.js +215 -0
- package/src/check.js +77 -0
- package/src/cli.js +293 -0
- package/src/core/bytes.js +112 -0
- package/src/core/check.js +222 -0
- package/src/core/dev.js +398 -0
- package/src/core/protocol.js +749 -0
- package/src/dev.js +62 -0
- package/src/keys.js +37 -0
- package/src/logfilter.js +91 -0
- package/src/protocol.js +47 -0
- package/src/serial.js +169 -0
- package/src/watch.js +106 -0
package/src/dev.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// One development session of the command line: a Kamoji link (reconnected when it drops), the app folder,
|
|
2
|
+
// the USB log. Used by `kamoji dev` (watch), `kamoji install` (once), `kamoji apps`, `kamoji shot`, `kamoji
|
|
3
|
+
// forget`. The session itself is core/dev.js (shared with the web IDE); this file reads the folder, runs
|
|
4
|
+
// luac, saves screenshots to disk and prints to the terminal.
|
|
5
|
+
import fs from 'node:fs'
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
import { checkApp } from './check.js'
|
|
8
|
+
import { DevSession as CoreDevSession } from './core/dev.js'
|
|
9
|
+
import { Session } from './protocol.js'
|
|
10
|
+
|
|
11
|
+
export * from './core/dev.js'
|
|
12
|
+
|
|
13
|
+
/** Terminal output: one place, so tests can collect it. */
|
|
14
|
+
export function makeUi({ stream = process.stdout, color = stream.isTTY && !process.env.NO_COLOR, verbose = false } = {}) {
|
|
15
|
+
const paint = (code, s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s)
|
|
16
|
+
const stamp = () => paint('2', new Date().toTimeString().slice(0, 8))
|
|
17
|
+
let progressShown = false
|
|
18
|
+
const line = (s) => {
|
|
19
|
+
if (progressShown) {
|
|
20
|
+
stream.write('\r\x1b[K')
|
|
21
|
+
progressShown = false
|
|
22
|
+
}
|
|
23
|
+
stream.write(`${stamp()} ${s}\n`)
|
|
24
|
+
}
|
|
25
|
+
return {
|
|
26
|
+
verbose,
|
|
27
|
+
info: (s) => line(s),
|
|
28
|
+
ok: (s) => line(paint('32', s)),
|
|
29
|
+
warn: (s) => line(paint('33', `warning: ${s}`)),
|
|
30
|
+
error: (s, hint) => {
|
|
31
|
+
line(paint('31', `error: ${s}`))
|
|
32
|
+
if (hint) for (const h of String(hint).split('\n')) stream.write(` ${h}\n`)
|
|
33
|
+
},
|
|
34
|
+
log: (kind, s) => {
|
|
35
|
+
const tags = { lua: '36', error: '31', crash: '31;1', stopped: '31', cpu: '33', warn: '33', entered: '32', boot: '35', usb: '35', app: '0' }
|
|
36
|
+
line(`${paint(tags[kind] ?? '0', `[${kind === 'lua' ? 'print' : kind}]`)} ${s}`)
|
|
37
|
+
},
|
|
38
|
+
raw: (s) => line(paint('2', s)),
|
|
39
|
+
progress: (s) => {
|
|
40
|
+
if (!stream.isTTY) return
|
|
41
|
+
stream.write(`\r\x1b[K${stamp()} ${s}`)
|
|
42
|
+
progressShown = true
|
|
43
|
+
},
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export class DevSession extends CoreDevSession {
|
|
48
|
+
makeSession(link, opts) {
|
|
49
|
+
return new Session(link, opts)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
runChecks() {
|
|
53
|
+
return checkApp(this.folder, { lua: this.lua })
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
saveShot(dir, name, jpeg) {
|
|
57
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
58
|
+
const file = path.join(dir, name)
|
|
59
|
+
fs.writeFileSync(file, jpeg)
|
|
60
|
+
return file
|
|
61
|
+
}
|
|
62
|
+
}
|
package/src/keys.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// This computer's key for one Kamoji: 32 random bytes in ~/.config/kamoji/<board>.key (hex, mode 0600).
|
|
2
|
+
// The Python worker/rig/kamoji_dev.py of kamoji-cms uses the same files, so either tool works without
|
|
3
|
+
// enrolling twice. The key is never printed: whoever has it can control that Kamoji.
|
|
4
|
+
import crypto from 'node:crypto'
|
|
5
|
+
import fs from 'node:fs'
|
|
6
|
+
import os from 'node:os'
|
|
7
|
+
import path from 'node:path'
|
|
8
|
+
|
|
9
|
+
export function configDir() {
|
|
10
|
+
return process.env.KAMOJI_CONFIG_DIR || path.join(os.homedir(), '.config', 'kamoji')
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** A file name from the board's Bluetooth name (KMJ-1A2B): letters, digits, - and _ only. */
|
|
14
|
+
export function keyPath(board) {
|
|
15
|
+
const safe = String(board || 'kamoji').replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 64)
|
|
16
|
+
return path.join(configDir(), `${safe}.key`)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The key for `board`, created on first use. Returns { key: Buffer, created: boolean, file }. */
|
|
20
|
+
export function loadOrCreateKey(board) {
|
|
21
|
+
const file = keyPath(board)
|
|
22
|
+
try {
|
|
23
|
+
const hex = fs.readFileSync(file, 'utf8').trim()
|
|
24
|
+
if (/^[0-9a-fA-F]{64}$/.test(hex)) return { key: Buffer.from(hex, 'hex'), created: false, file }
|
|
25
|
+
throw new Error(`${file} is not a Kamoji key (64 hex characters expected): delete it to start again`)
|
|
26
|
+
} catch (e) {
|
|
27
|
+
if (e.code !== 'ENOENT') throw e
|
|
28
|
+
}
|
|
29
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
|
|
30
|
+
const key = crypto.randomBytes(32)
|
|
31
|
+
fs.writeFileSync(file, `${key.toString('hex')}\n`, { mode: 0o600, flag: 'wx' })
|
|
32
|
+
return { key, created: true, file }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function deleteKey(board) {
|
|
36
|
+
fs.rmSync(keyPath(board), { force: true })
|
|
37
|
+
}
|
package/src/logfilter.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Which lines of Kamoji's USB log a mini app developer wants to see. Formats from kamoji-esphome
|
|
2
|
+
// kamoji_app_manager.cpp (print() → [app.lua], "[<id>] entered in N ms", "[<id>] stopped: …", "CPU budget
|
|
3
|
+
// exceeded", "app <id> ok (mode N)" / "unavailable: …", "APP_COMMIT <id>: …"), ESPHome and ESP-IDF
|
|
4
|
+
// (panics, resets). Same patterns as kamoji-cms worker/rig/logparse.py.
|
|
5
|
+
|
|
6
|
+
const ANSI = /\x1b\[[0-9;]*m/g
|
|
7
|
+
const CRASH = /Guru Meditation|abort\(\) was called|assert failed|Backtrace:|Rebooting\.\.\.|rst:0x[0-9a-f]+ \(|Stack canary|LoadProhibited|StoreProhibited|IllegalInstruction|task_wdt/
|
|
8
|
+
const SECRETS = /\b(password|passwd|pass|psk|token|secret|api[_-]?key|authorization)(\s*[:=]\s*)("[^"]*"|\S+)/gi
|
|
9
|
+
const ECODE = /\bE3[0-9]\d\d\b/
|
|
10
|
+
|
|
11
|
+
export function clean(line) {
|
|
12
|
+
return String(line).replace(ANSI, '').replace(/\r/g, '').trimEnd()
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function redact(s) {
|
|
16
|
+
return s.replace(SECRETS, (_m, k, sep) => `${k}${sep}***`)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
20
|
+
/** The message part of an ESPHome log line ("[I][apps:123]: text" → "text"). */
|
|
21
|
+
const message = (ln) => {
|
|
22
|
+
const i = ln.indexOf(']: ')
|
|
23
|
+
return i >= 0 ? ln.slice(i + 3) : ln
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @returns {null | {kind: 'lua'|'error'|'warn'|'cpu'|'stopped'|'entered'|'app'|'crash'|'boot'|'usb', text: string}}
|
|
28
|
+
*/
|
|
29
|
+
export function classify(raw, appId) {
|
|
30
|
+
const ln = clean(raw)
|
|
31
|
+
if (!ln) return null
|
|
32
|
+
if (ln.startsWith('### ')) return { kind: 'usb', text: ln.slice(4) }
|
|
33
|
+
if (CRASH.test(ln)) return { kind: 'crash', text: redact(ln).slice(0, 300) }
|
|
34
|
+
if (ln.includes('setup() finished')) return { kind: 'boot', text: 'Kamoji started (setup finished)' }
|
|
35
|
+
if (ln.includes('[app.lua')) return { kind: 'lua', text: redact(message(ln)).slice(0, 400) }
|
|
36
|
+
const level = /^\[([EWI])\]/.exec(ln)?.[1]
|
|
37
|
+
if (ln.includes('[apps:')) {
|
|
38
|
+
const msg = message(ln)
|
|
39
|
+
if (msg.startsWith('BLE: ')) return null // the install itself, echoed
|
|
40
|
+
if (appId) {
|
|
41
|
+
const tag = `[${appId}]`
|
|
42
|
+
const mentions = msg.includes(tag) || new RegExp(`\\b(app|APP_COMMIT|APP_PUT) ${esc(appId)}\\b`).test(msg)
|
|
43
|
+
if (!mentions) return ECODE.test(msg) ? { kind: 'error', text: redact(msg) } : null
|
|
44
|
+
const rest = msg.includes(tag) ? msg.split(tag).slice(1).join(tag).trim() : msg
|
|
45
|
+
if (rest.startsWith('stopped:')) return { kind: 'stopped', text: redact(msg) }
|
|
46
|
+
if (rest.includes('CPU budget exceeded')) return { kind: 'cpu', text: redact(msg) }
|
|
47
|
+
if (rest.startsWith('entered in')) return { kind: 'entered', text: msg }
|
|
48
|
+
if (level === 'E') return { kind: 'error', text: redact(msg) }
|
|
49
|
+
if (level === 'W') return { kind: 'warn', text: redact(msg) }
|
|
50
|
+
return { kind: 'app', text: redact(msg) }
|
|
51
|
+
}
|
|
52
|
+
return level === 'E' || level === 'W' ? { kind: level === 'E' ? 'error' : 'warn', text: redact(msg) } : null
|
|
53
|
+
}
|
|
54
|
+
if (ECODE.test(ln)) return { kind: 'error', text: redact(message(ln)) }
|
|
55
|
+
return null
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const DROPPED = /^(\d+) line\(s\) dropped$/
|
|
59
|
+
const LIFECYCLE = /^(entered in|exited|stopped)\b/
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* An app log line over Bluetooth (firmware 0.3.3: `APP:LOG:<L>:<app_id>:<text>`, parsed by
|
|
63
|
+
* protocol.parseLogLine) → the same { kind, text } as classify() gives for the USB line, or null.
|
|
64
|
+
* L = I (print, lifecycle, timings), W (CPU budget, long operations, warnings), E (Lua errors, E30xx/E36xx).
|
|
65
|
+
* Text is a print() line, or a "[<id>] …" line (a bare "entered in …" / "stopped: …" counts as one too).
|
|
66
|
+
* @param {{level:string, appId:string, text:string}} log
|
|
67
|
+
* @param {string|null} [appId] only this app's lines
|
|
68
|
+
*/
|
|
69
|
+
export function classifyBle(log, appId) {
|
|
70
|
+
if (appId && log.appId !== appId) return null
|
|
71
|
+
let text = clean(log.text).replace(/^\[app\.lua[^\]]*\]:?\s*/, '')
|
|
72
|
+
const tag = `[${log.appId}]`
|
|
73
|
+
const dropped = DROPPED.exec(text)
|
|
74
|
+
if (dropped && log.level === 'W')
|
|
75
|
+
return { kind: 'warn', text: `[${log.appId}] Kamoji dropped ${dropped[1]} log line(s) (more than 20 a second)` }
|
|
76
|
+
let tagged = text.startsWith(tag)
|
|
77
|
+
let rest = tagged ? text.slice(tag.length).trim() : text
|
|
78
|
+
if (!tagged && LIFECYCLE.test(text)) {
|
|
79
|
+
tagged = true
|
|
80
|
+
text = `${tag} ${text}`
|
|
81
|
+
}
|
|
82
|
+
if (tagged) {
|
|
83
|
+
if (rest.startsWith('stopped:')) return { kind: 'stopped', text: redact(text) }
|
|
84
|
+
if (rest.includes('CPU budget exceeded')) return { kind: 'cpu', text: redact(text) }
|
|
85
|
+
if (rest.startsWith('entered in')) return { kind: 'entered', text }
|
|
86
|
+
}
|
|
87
|
+
if (log.level === 'E') return { kind: 'error', text: redact(text) }
|
|
88
|
+
if (log.level === 'W') return { kind: rest.includes('CPU budget exceeded') ? 'cpu' : 'warn', text: redact(text) }
|
|
89
|
+
if (tagged) return { kind: 'app', text: redact(text) }
|
|
90
|
+
return { kind: 'lua', text: redact(text).slice(0, 400) }
|
|
91
|
+
}
|
package/src/protocol.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// The Kamoji Bluetooth command channel for Node (the `kamoji` command line). The protocol itself is in
|
|
2
|
+
// core/protocol.js (environment-neutral, shared with the web IDE on developer.kamoji.bot); this file adds
|
|
3
|
+
// the key's hashing with node:crypto and gives Buffers back, as the command line always had them.
|
|
4
|
+
import crypto from 'node:crypto'
|
|
5
|
+
import { Session as CoreSession } from './core/protocol.js'
|
|
6
|
+
|
|
7
|
+
export * from './core/protocol.js'
|
|
8
|
+
|
|
9
|
+
export function keyId(key) {
|
|
10
|
+
return crypto.createHash('sha256').update(key).digest().subarray(0, 8).toString('hex')
|
|
11
|
+
}
|
|
12
|
+
export function hmacHex(key, data) {
|
|
13
|
+
return crypto.createHmac('sha256', key).update(data).digest('hex')
|
|
14
|
+
}
|
|
15
|
+
export function md5Hex(data) {
|
|
16
|
+
return crypto.createHash('md5').update(data).digest('hex')
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The crypto provider of core/protocol.js for a key that is a Buffer (~/.config/kamoji/<board>.key). */
|
|
20
|
+
export const nodeCrypto = {
|
|
21
|
+
md5Hex,
|
|
22
|
+
keyId,
|
|
23
|
+
hmacHex,
|
|
24
|
+
enrollHex: (key) => Buffer.from(key).toString('hex'),
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const asBuffer = (b) => (Buffer.isBuffer(b) ? b : Buffer.from(b.buffer, b.byteOffset, b.byteLength))
|
|
28
|
+
|
|
29
|
+
/** core/protocol.js Session with node:crypto, binary writes as Buffers and the screenshot as a Buffer. */
|
|
30
|
+
export class Session extends CoreSession {
|
|
31
|
+
constructor(link, opts = {}) {
|
|
32
|
+
super(
|
|
33
|
+
{
|
|
34
|
+
send: (text) => link.send(text),
|
|
35
|
+
sendRaw: (bytes) => link.sendRaw(asBuffer(bytes)),
|
|
36
|
+
maxWrite: () => link.maxWrite(),
|
|
37
|
+
onMessage: (h) => link.onMessage(h),
|
|
38
|
+
disconnect: async () => link.disconnect?.(),
|
|
39
|
+
},
|
|
40
|
+
{ crypto: nodeCrypto, ...opts },
|
|
41
|
+
)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async screenshot() {
|
|
45
|
+
return asBuffer(await super.screenshot())
|
|
46
|
+
}
|
|
47
|
+
}
|
package/src/serial.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// Kamoji on USB: its log, the `app.*` serial commands and `app.shot` screenshots. Same rules as
|
|
2
|
+
// kamoji-cms worker/rig/device.py:
|
|
3
|
+
// - DTR on, RTS off (DTR off with RTS on resets the ESP32-S3);
|
|
4
|
+
// - long command lines in 256-byte pieces, 20 ms apart (the USB RX ring holds 512 bytes);
|
|
5
|
+
// - after a reset the USB device goes away and comes back: re-open and carry on;
|
|
6
|
+
// - `app.shot:<q>` answers SHOT:BEGIN:<w>:<h>:<size>, SHOT:<base64>…, SHOT:END as log lines.
|
|
7
|
+
// Installing over USB is not possible without rewriting the whole storage partition (see README).
|
|
8
|
+
import { clean } from './logfilter.js'
|
|
9
|
+
|
|
10
|
+
export const ESPRESSIF_VID = '303a'
|
|
11
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
12
|
+
|
|
13
|
+
/** The Espressif USB serial ports (macOS: the /dev/cu.* ones). */
|
|
14
|
+
export async function findPorts() {
|
|
15
|
+
const { SerialPort } = await import('serialport')
|
|
16
|
+
const all = await SerialPort.list()
|
|
17
|
+
const found = all.filter((p) => String(p.vendorId ?? '').toLowerCase() === ESPRESSIF_VID).map((p) => p.path)
|
|
18
|
+
const cu = found.filter((p) => p.includes('/cu.'))
|
|
19
|
+
return cu.length ? cu : found
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Opens a real port: resolves to { onData(cb), onClose(cb), write(buf), close() }. */
|
|
23
|
+
export async function openSerialPort(path) {
|
|
24
|
+
const { SerialPort } = await import('serialport')
|
|
25
|
+
const port = new SerialPort({ path, baudRate: 115200, autoOpen: false, hupcl: false })
|
|
26
|
+
await new Promise((res, rej) => port.open((e) => (e ? rej(e) : res())))
|
|
27
|
+
// Opening raises DTR and RTS together (no reset); drop RTS, keep DTR, in one call.
|
|
28
|
+
await new Promise((res) => port.set({ dtr: true, rts: false }, () => res()))
|
|
29
|
+
return {
|
|
30
|
+
onData: (cb) => port.on('data', cb),
|
|
31
|
+
onClose: (cb) => port.on('close', cb),
|
|
32
|
+
write: (buf) => new Promise((res, rej) => port.write(buf, (e) => (e ? rej(e) : port.drain(() => res())))),
|
|
33
|
+
close: () => new Promise((res) => (port.isOpen ? port.close(() => res()) : res())),
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export class SerialLog {
|
|
38
|
+
/**
|
|
39
|
+
* @param {string} path
|
|
40
|
+
* @param {{open?: (path:string)=>Promise<any>, onLine?: (line:string)=>void, reopenMs?: number}} [opts]
|
|
41
|
+
*/
|
|
42
|
+
constructor(path, opts = {}) {
|
|
43
|
+
this.path = path
|
|
44
|
+
this.opener = opts.open ?? openSerialPort
|
|
45
|
+
this.onLine = opts.onLine
|
|
46
|
+
this.reopenMs = opts.reopenMs ?? 20000
|
|
47
|
+
this.lines = []
|
|
48
|
+
this.listeners = new Set()
|
|
49
|
+
this.port = null
|
|
50
|
+
this.closed = false
|
|
51
|
+
this.buf = ''
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async start() {
|
|
55
|
+
this.port = await this.opener(this.path)
|
|
56
|
+
this._wire()
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
_wire() {
|
|
60
|
+
this.port.onData((d) => {
|
|
61
|
+
this.buf += Buffer.from(d).toString('utf8')
|
|
62
|
+
let i
|
|
63
|
+
while ((i = this.buf.indexOf('\n')) >= 0) {
|
|
64
|
+
const line = this.buf.slice(0, i).replace(/\r$/, '')
|
|
65
|
+
this.buf = this.buf.slice(i + 1)
|
|
66
|
+
this._add(line)
|
|
67
|
+
}
|
|
68
|
+
})
|
|
69
|
+
this.port.onClose(() => {
|
|
70
|
+
if (this.closed) return
|
|
71
|
+
this._add('### USB port lost (Kamoji restarted, or the cable was unplugged)')
|
|
72
|
+
this._reopen()
|
|
73
|
+
})
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async _reopen() {
|
|
77
|
+
const end = Date.now() + this.reopenMs
|
|
78
|
+
while (!this.closed && Date.now() < end) {
|
|
79
|
+
await sleep(300)
|
|
80
|
+
try {
|
|
81
|
+
this.port = await this.opener(this.path)
|
|
82
|
+
this.buf = ''
|
|
83
|
+
this._wire()
|
|
84
|
+
this._add('### USB port back')
|
|
85
|
+
return
|
|
86
|
+
} catch {
|
|
87
|
+
// not there yet (USB re-enumerating)
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (!this.closed) this._add('### USB port did not come back: USB log stopped')
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
_add(line) {
|
|
94
|
+
this.lines.push(line)
|
|
95
|
+
if (this.lines.length > 5000) this.lines.splice(0, 1000)
|
|
96
|
+
for (const l of this.listeners) l(line)
|
|
97
|
+
try {
|
|
98
|
+
this.onLine?.(line)
|
|
99
|
+
} catch {
|
|
100
|
+
// a printing error never stops the reader
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async close() {
|
|
105
|
+
this.closed = true
|
|
106
|
+
await this.port?.close().catch(() => undefined)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async send(line) {
|
|
110
|
+
const data = Buffer.from(`${line}\n`)
|
|
111
|
+
for (let i = 0; i < data.length; i += 256) {
|
|
112
|
+
if (i) await sleep(20)
|
|
113
|
+
await this.port.write(data.subarray(i, i + 256))
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Resolves with the first line (cleaned) for which pred is true, or null after ms. */
|
|
118
|
+
waitLine(pred, ms) {
|
|
119
|
+
return new Promise((resolve) => {
|
|
120
|
+
const l = (raw) => {
|
|
121
|
+
const c = clean(raw)
|
|
122
|
+
if (pred(c)) done(c)
|
|
123
|
+
}
|
|
124
|
+
const timer = setTimeout(() => done(null), ms)
|
|
125
|
+
const done = (v) => {
|
|
126
|
+
clearTimeout(timer)
|
|
127
|
+
this.listeners.delete(l)
|
|
128
|
+
resolve(v)
|
|
129
|
+
}
|
|
130
|
+
this.listeners.add(l)
|
|
131
|
+
})
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** One `app.shot` JPEG (3 tries, like the rig). */
|
|
135
|
+
async screenshot(quality = 90, timeoutMs = 20000) {
|
|
136
|
+
let last = 'screenshot failed'
|
|
137
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
138
|
+
let size = null
|
|
139
|
+
let parts = []
|
|
140
|
+
const r = new Promise((resolve) => {
|
|
141
|
+
const l = (raw) => {
|
|
142
|
+
const ln = clean(raw)
|
|
143
|
+
let m
|
|
144
|
+
if ((m = /SHOT:BEGIN:(\d+):(\d+):(\d+)/.exec(ln))) {
|
|
145
|
+
size = Number(m[3])
|
|
146
|
+
parts = []
|
|
147
|
+
} else if (ln.includes('SHOT:END') && size !== null) {
|
|
148
|
+
const data = Buffer.from(parts.join(''), 'base64')
|
|
149
|
+
done(data.length === size ? data : `screenshot size ${data.length} != ${size} (a line was lost)`)
|
|
150
|
+
} else if ((m = /SHOT:([A-Za-z0-9+/=]+)$/.exec(ln)) && size !== null) parts.push(m[1])
|
|
151
|
+
else if (ln.includes('APP:ERR:')) done(ln.split('APP:ERR:')[1])
|
|
152
|
+
}
|
|
153
|
+
const timer = setTimeout(() => done('screenshot timed out'), timeoutMs)
|
|
154
|
+
const done = (v) => {
|
|
155
|
+
clearTimeout(timer)
|
|
156
|
+
this.listeners.delete(l)
|
|
157
|
+
resolve(v)
|
|
158
|
+
}
|
|
159
|
+
this.listeners.add(l)
|
|
160
|
+
})
|
|
161
|
+
await this.send(`app.shot:${quality}`)
|
|
162
|
+
const v = await r
|
|
163
|
+
if (Buffer.isBuffer(v)) return v
|
|
164
|
+
last = v
|
|
165
|
+
await sleep(1000)
|
|
166
|
+
}
|
|
167
|
+
throw new Error(last)
|
|
168
|
+
}
|
|
169
|
+
}
|
package/src/watch.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// Saves → one reload: a burst of file events (an editor writes a temp file, renames, touches) waits
|
|
2
|
+
// until the folder has been quiet for `quietMs`, and a save during a reload runs one more reload after it.
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { isJunk } from './check.js'
|
|
6
|
+
|
|
7
|
+
export class Reloader {
|
|
8
|
+
/**
|
|
9
|
+
* @param {() => Promise<void>} run
|
|
10
|
+
* @param {{quietMs?: number, timers?: {setTimeout: Function, clearTimeout: Function}}} [opts]
|
|
11
|
+
*/
|
|
12
|
+
constructor(run, opts = {}) {
|
|
13
|
+
this.run = run
|
|
14
|
+
this.quietMs = opts.quietMs ?? 400
|
|
15
|
+
this.timers = opts.timers ?? { setTimeout, clearTimeout }
|
|
16
|
+
this.timer = null
|
|
17
|
+
this.running = false
|
|
18
|
+
this.pending = false
|
|
19
|
+
this.idle = Promise.resolve()
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** A file changed. */
|
|
23
|
+
trigger() {
|
|
24
|
+
if (this.timer) this.timers.clearTimeout(this.timer)
|
|
25
|
+
this.timer = this.timers.setTimeout(() => {
|
|
26
|
+
this.timer = null
|
|
27
|
+
this.fire()
|
|
28
|
+
}, this.quietMs)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Reload now (or right after the reload in progress). */
|
|
32
|
+
fire() {
|
|
33
|
+
if (this.running) {
|
|
34
|
+
this.pending = true
|
|
35
|
+
return this.idle
|
|
36
|
+
}
|
|
37
|
+
this.running = true
|
|
38
|
+
this.idle = (async () => {
|
|
39
|
+
try {
|
|
40
|
+
do {
|
|
41
|
+
this.pending = false
|
|
42
|
+
await this.run()
|
|
43
|
+
} while (this.pending)
|
|
44
|
+
} finally {
|
|
45
|
+
this.running = false
|
|
46
|
+
}
|
|
47
|
+
})()
|
|
48
|
+
return this.idle
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
stop() {
|
|
52
|
+
if (this.timer) this.timers.clearTimeout(this.timer)
|
|
53
|
+
this.timer = null
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Calls onChange(relPath) for every change in the folder that is not an editor / OS file. Returns stop(). */
|
|
58
|
+
export function watchFolder(folder, onChange) {
|
|
59
|
+
const ignored = (rel) => !rel || rel.split(/[\\/]/).some((part) => isJunk(part))
|
|
60
|
+
try {
|
|
61
|
+
const w = fs.watch(folder, { recursive: true }, (_ev, name) => {
|
|
62
|
+
const rel = name ? String(name) : ''
|
|
63
|
+
if (rel && ignored(rel)) return
|
|
64
|
+
onChange(rel)
|
|
65
|
+
})
|
|
66
|
+
return () => w.close()
|
|
67
|
+
} catch {
|
|
68
|
+
// No recursive fs.watch here: poll the folder's file times instead.
|
|
69
|
+
let last = snapshot(folder)
|
|
70
|
+
const t = setInterval(() => {
|
|
71
|
+
const now = snapshot(folder)
|
|
72
|
+
if (now !== last) {
|
|
73
|
+
last = now
|
|
74
|
+
onChange('')
|
|
75
|
+
}
|
|
76
|
+
}, 500)
|
|
77
|
+
return () => clearInterval(t)
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function snapshot(folder) {
|
|
82
|
+
const out = []
|
|
83
|
+
const walk = (dir, rel) => {
|
|
84
|
+
let ents = []
|
|
85
|
+
try {
|
|
86
|
+
ents = fs.readdirSync(dir, { withFileTypes: true })
|
|
87
|
+
} catch {
|
|
88
|
+
return
|
|
89
|
+
}
|
|
90
|
+
for (const e of ents) {
|
|
91
|
+
if (isJunk(e.name)) continue
|
|
92
|
+
const full = path.join(dir, e.name)
|
|
93
|
+
const r = rel ? `${rel}/${e.name}` : e.name
|
|
94
|
+
if (e.isDirectory()) walk(full, r)
|
|
95
|
+
else
|
|
96
|
+
try {
|
|
97
|
+
const st = fs.statSync(full)
|
|
98
|
+
out.push(`${r}:${st.size}:${st.mtimeMs}`)
|
|
99
|
+
} catch {
|
|
100
|
+
// gone meanwhile
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
walk(folder, '')
|
|
105
|
+
return out.sort().join('\n')
|
|
106
|
+
}
|