@bypane/cli 0.0.0-stage → 0.2.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/dist/expr.js ADDED
@@ -0,0 +1,460 @@
1
+ /**
2
+ * Safe, zero-eval, scriptc-compatible expression and template evaluator
3
+ * for reactive declarative `ui` surfaces in bypane.
4
+ */
5
+ const TWO_CHAR_OPS = new Set(["==", "!=", "<=", ">=", "&&", "||"]);
6
+ const ONE_CHAR_OPS = new Set(["+", "-", "*", "/", "%", "<", ">", "!"]);
7
+ function tokenize(src) {
8
+ const tokens = [];
9
+ let i = 0;
10
+ const n = src.length;
11
+ while (i < n) {
12
+ const ch = src[i];
13
+ if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") {
14
+ i++;
15
+ continue;
16
+ }
17
+ if ((ch >= "0" && ch <= "9") || (ch === "." && i + 1 < n && src[i + 1] >= "0" && src[i + 1] <= "9")) {
18
+ const start = i;
19
+ let seenDot = false;
20
+ while (i < n) {
21
+ const c = src[i];
22
+ if (c >= "0" && c <= "9") {
23
+ i++;
24
+ }
25
+ else if (c === "." && !seenDot) {
26
+ seenDot = true;
27
+ i++;
28
+ }
29
+ else {
30
+ break;
31
+ }
32
+ }
33
+ const text = src.slice(start, i);
34
+ tokens.push({ kind: "num", text, num: Number(text) });
35
+ continue;
36
+ }
37
+ if (ch === '"' || ch === "'") {
38
+ const quote = ch;
39
+ i++;
40
+ let out = "";
41
+ while (i < n && src[i] !== quote) {
42
+ if (src[i] === "\\" && i + 1 < n) {
43
+ const next = src[i + 1];
44
+ out += next === "n" ? "\n" : next === "t" ? "\t" : next;
45
+ i += 2;
46
+ }
47
+ else {
48
+ out += src[i];
49
+ i++;
50
+ }
51
+ }
52
+ if (i < n && src[i] === quote)
53
+ i++;
54
+ tokens.push({ kind: "str", text: out });
55
+ continue;
56
+ }
57
+ if ((ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z") || ch === "_" || ch === "$") {
58
+ const start = i;
59
+ while (i < n) {
60
+ const c = src[i];
61
+ if ((c >= "a" && c <= "z") ||
62
+ (c >= "A" && c <= "Z") ||
63
+ (c >= "0" && c <= "9") ||
64
+ c === "_" ||
65
+ c === "$") {
66
+ i++;
67
+ }
68
+ else {
69
+ break;
70
+ }
71
+ }
72
+ tokens.push({ kind: "ident", text: src.slice(start, i) });
73
+ continue;
74
+ }
75
+ if (i + 1 < n && TWO_CHAR_OPS.has(src.slice(i, i + 2))) {
76
+ tokens.push({ kind: "op", text: src.slice(i, i + 2) });
77
+ i += 2;
78
+ continue;
79
+ }
80
+ if (ONE_CHAR_OPS.has(ch)) {
81
+ tokens.push({ kind: "op", text: ch });
82
+ i++;
83
+ continue;
84
+ }
85
+ if (ch === "(") {
86
+ tokens.push({ kind: "lparen", text: ch });
87
+ i++;
88
+ continue;
89
+ }
90
+ if (ch === ")") {
91
+ tokens.push({ kind: "rparen", text: ch });
92
+ i++;
93
+ continue;
94
+ }
95
+ if (ch === ",") {
96
+ tokens.push({ kind: "comma", text: ch });
97
+ i++;
98
+ continue;
99
+ }
100
+ if (ch === ".") {
101
+ tokens.push({ kind: "dot", text: ch });
102
+ i++;
103
+ continue;
104
+ }
105
+ if (ch === "?") {
106
+ tokens.push({ kind: "qmark", text: ch });
107
+ i++;
108
+ continue;
109
+ }
110
+ if (ch === ":") {
111
+ tokens.push({ kind: "colon", text: ch });
112
+ i++;
113
+ continue;
114
+ }
115
+ i++;
116
+ }
117
+ tokens.push({ kind: "eof", text: "" });
118
+ return tokens;
119
+ }
120
+ function toNum(v) {
121
+ if (typeof v === "number")
122
+ return Number.isFinite(v) ? v : 0;
123
+ if (typeof v === "boolean")
124
+ return v ? 1 : 0;
125
+ if (typeof v === "string") {
126
+ const n = Number(v);
127
+ return Number.isFinite(n) ? n : 0;
128
+ }
129
+ return 0;
130
+ }
131
+ function callBuiltin(name, args) {
132
+ switch (name) {
133
+ case "min":
134
+ return args.length ? Math.min(...args.map(toNum)) : 0;
135
+ case "max":
136
+ return args.length ? Math.max(...args.map(toNum)) : 0;
137
+ case "clamp": {
138
+ const v = toNum(args[0]);
139
+ const lo = toNum(args[1]);
140
+ const hi = toNum(args[2]);
141
+ return Math.max(lo, Math.min(hi, v));
142
+ }
143
+ case "round": {
144
+ const v = toNum(args[0]);
145
+ const digits = args.length >= 2 ? Math.max(0, Math.min(6, Math.trunc(toNum(args[1])))) : 0;
146
+ if (digits === 0)
147
+ return Math.round(v);
148
+ const factor = Math.pow(10, digits);
149
+ return Math.round(v * factor) / factor;
150
+ }
151
+ case "floor":
152
+ return Math.floor(toNum(args[0]));
153
+ case "ceil":
154
+ return Math.ceil(toNum(args[0]));
155
+ case "abs":
156
+ return Math.abs(toNum(args[0]));
157
+ case "sqrt":
158
+ return Math.sqrt(Math.max(0, toNum(args[0])));
159
+ case "pow":
160
+ return Math.pow(toNum(args[0]), toNum(args[1]));
161
+ case "sin":
162
+ return Math.sin(toNum(args[0]));
163
+ case "cos":
164
+ return Math.cos(toNum(args[0]));
165
+ case "exp":
166
+ return Math.exp(toNum(args[0]));
167
+ case "log":
168
+ return Math.log(Math.max(1e-9, toNum(args[0])));
169
+ case "fixed": {
170
+ const v = toNum(args[0]);
171
+ const d = args.length >= 2 ? Math.max(0, Math.min(6, Math.trunc(toNum(args[1])))) : 2;
172
+ return v.toFixed(d);
173
+ }
174
+ case "len": {
175
+ const v = args[0];
176
+ if (typeof v === "string" || Array.isArray(v))
177
+ return v.length;
178
+ return 0;
179
+ }
180
+ case "upper":
181
+ return String(args[0] ?? "").toUpperCase();
182
+ case "lower":
183
+ return String(args[0] ?? "").toLowerCase();
184
+ case "if":
185
+ return args[0] ? args[1] : args[2];
186
+ default:
187
+ return undefined;
188
+ }
189
+ }
190
+ class Parser {
191
+ tokens;
192
+ scope;
193
+ pos = 0;
194
+ constructor(tokens, scope) {
195
+ this.tokens = tokens;
196
+ this.scope = scope;
197
+ }
198
+ peek() {
199
+ return this.tokens[this.pos] ?? { kind: "eof", text: "" };
200
+ }
201
+ next() {
202
+ const t = this.peek();
203
+ if (this.pos < this.tokens.length - 1)
204
+ this.pos++;
205
+ return t;
206
+ }
207
+ matchOp(op) {
208
+ const t = this.peek();
209
+ if (t.kind === "op" && t.text === op) {
210
+ this.next();
211
+ return true;
212
+ }
213
+ return false;
214
+ }
215
+ parse() {
216
+ return this.parseTernary();
217
+ }
218
+ parseTernary() {
219
+ const cond = this.parseOr();
220
+ if (this.peek().kind === "qmark") {
221
+ this.next();
222
+ const whenTrue = this.parseTernary();
223
+ if (this.peek().kind === "colon")
224
+ this.next();
225
+ const whenFalse = this.parseTernary();
226
+ return cond ? whenTrue : whenFalse;
227
+ }
228
+ return cond;
229
+ }
230
+ parseOr() {
231
+ let left = this.parseAnd();
232
+ while (this.matchOp("||")) {
233
+ const right = this.parseAnd();
234
+ left = left || right;
235
+ }
236
+ return left;
237
+ }
238
+ parseAnd() {
239
+ let left = this.parseEquality();
240
+ while (this.matchOp("&&")) {
241
+ const right = this.parseEquality();
242
+ left = left && right;
243
+ }
244
+ return left;
245
+ }
246
+ parseEquality() {
247
+ let left = this.parseComparison();
248
+ while (true) {
249
+ if (this.matchOp("==")) {
250
+ const right = this.parseComparison();
251
+ left = left === right;
252
+ }
253
+ else if (this.matchOp("!=")) {
254
+ const right = this.parseComparison();
255
+ left = left !== right;
256
+ }
257
+ else {
258
+ break;
259
+ }
260
+ }
261
+ return left;
262
+ }
263
+ parseComparison() {
264
+ let left = this.parseAdditive();
265
+ while (true) {
266
+ if (this.matchOp("<"))
267
+ left = toNum(left) < toNum(this.parseAdditive());
268
+ else if (this.matchOp("<="))
269
+ left = toNum(left) <= toNum(this.parseAdditive());
270
+ else if (this.matchOp(">"))
271
+ left = toNum(left) > toNum(this.parseAdditive());
272
+ else if (this.matchOp(">="))
273
+ left = toNum(left) >= toNum(this.parseAdditive());
274
+ else
275
+ break;
276
+ }
277
+ return left;
278
+ }
279
+ parseAdditive() {
280
+ let left = this.parseMultiplicative();
281
+ while (true) {
282
+ if (this.matchOp("+")) {
283
+ const right = this.parseMultiplicative();
284
+ if (typeof left === "string" || typeof right === "string") {
285
+ left = `${formatExprValue(left)}${formatExprValue(right)}`;
286
+ }
287
+ else {
288
+ left = toNum(left) + toNum(right);
289
+ }
290
+ }
291
+ else if (this.matchOp("-")) {
292
+ left = toNum(left) - toNum(this.parseMultiplicative());
293
+ }
294
+ else {
295
+ break;
296
+ }
297
+ }
298
+ return left;
299
+ }
300
+ parseMultiplicative() {
301
+ let left = this.parseUnary();
302
+ while (true) {
303
+ if (this.matchOp("*")) {
304
+ left = toNum(left) * toNum(this.parseUnary());
305
+ }
306
+ else if (this.matchOp("/")) {
307
+ const denom = toNum(this.parseUnary());
308
+ left = denom === 0 ? 0 : toNum(left) / denom;
309
+ }
310
+ else if (this.matchOp("%")) {
311
+ const denom = toNum(this.parseUnary());
312
+ left = denom === 0 ? 0 : toNum(left) % denom;
313
+ }
314
+ else {
315
+ break;
316
+ }
317
+ }
318
+ return left;
319
+ }
320
+ parseUnary() {
321
+ if (this.matchOp("!"))
322
+ return !this.parseUnary();
323
+ if (this.matchOp("-"))
324
+ return -toNum(this.parseUnary());
325
+ if (this.matchOp("+"))
326
+ return toNum(this.parseUnary());
327
+ return this.parsePrimary();
328
+ }
329
+ parsePrimary() {
330
+ const t = this.peek();
331
+ if (t.kind === "num") {
332
+ this.next();
333
+ return t.num ?? 0;
334
+ }
335
+ if (t.kind === "str") {
336
+ this.next();
337
+ return t.text;
338
+ }
339
+ if (t.kind === "lparen") {
340
+ this.next();
341
+ const val = this.parseTernary();
342
+ if (this.peek().kind === "rparen")
343
+ this.next();
344
+ return val;
345
+ }
346
+ if (t.kind === "ident") {
347
+ this.next();
348
+ const name = t.text;
349
+ if (this.peek().kind === "lparen") {
350
+ this.next();
351
+ const args = [];
352
+ if (this.peek().kind !== "rparen") {
353
+ while (true) {
354
+ args.push(this.parseTernary());
355
+ if (this.peek().kind === "comma") {
356
+ this.next();
357
+ }
358
+ else {
359
+ break;
360
+ }
361
+ }
362
+ }
363
+ if (this.peek().kind === "rparen")
364
+ this.next();
365
+ return callBuiltin(name, args);
366
+ }
367
+ let cur;
368
+ if (name === "true")
369
+ cur = true;
370
+ else if (name === "false")
371
+ cur = false;
372
+ else if (name === "null")
373
+ cur = null;
374
+ else if (name === "state")
375
+ cur = this.scope;
376
+ else
377
+ cur = this.scope[name];
378
+ while (this.peek().kind === "dot") {
379
+ this.next();
380
+ const prop = this.next();
381
+ if (prop.kind !== "ident")
382
+ break;
383
+ if (cur === null || cur === undefined) {
384
+ cur = undefined;
385
+ }
386
+ else if ((typeof cur === "string" || Array.isArray(cur)) && prop.text === "length") {
387
+ cur = cur.length;
388
+ }
389
+ else if (typeof cur === "object") {
390
+ cur = cur[prop.text];
391
+ }
392
+ else {
393
+ cur = undefined;
394
+ }
395
+ }
396
+ return cur;
397
+ }
398
+ return undefined;
399
+ }
400
+ }
401
+ export function formatExprValue(v) {
402
+ if (v === undefined || v === null)
403
+ return "";
404
+ if (typeof v === "number") {
405
+ if (!Number.isFinite(v))
406
+ return "0";
407
+ if (Number.isInteger(v))
408
+ return String(v);
409
+ return String(Math.round(v * 1000) / 1000);
410
+ }
411
+ if (typeof v === "boolean")
412
+ return v ? "true" : "false";
413
+ if (Array.isArray(v))
414
+ return v.map(formatExprValue).join(", ");
415
+ return String(v);
416
+ }
417
+ export function evalExpr(expr, scope) {
418
+ const trimmed = expr.trim();
419
+ if (!trimmed)
420
+ return "";
421
+ const parser = new Parser(tokenize(trimmed), scope);
422
+ return parser.parse();
423
+ }
424
+ const TEMPLATE_RE = /\{\{([\s\S]*?)\}\}/g;
425
+ export function interpolateText(template, scope) {
426
+ if (!template.includes("{{"))
427
+ return template;
428
+ return template.replace(TEMPLATE_RE, (_m, inner) => {
429
+ const val = evalExpr(inner, scope);
430
+ return formatExprValue(val);
431
+ });
432
+ }
433
+ export function evalNumber(input, scope, fallback = 0) {
434
+ if (typeof input === "number")
435
+ return Number.isFinite(input) ? input : fallback;
436
+ if (typeof input !== "string")
437
+ return fallback;
438
+ const trimmed = input.trim();
439
+ if (!trimmed)
440
+ return fallback;
441
+ const unwrapped = trimmed.startsWith("{{") && trimmed.endsWith("}}")
442
+ ? trimmed.slice(2, -2).trim()
443
+ : trimmed;
444
+ const val = evalExpr(unwrapped, scope);
445
+ const num = typeof val === "number" ? val : Number(val);
446
+ return Number.isFinite(num) ? num : fallback;
447
+ }
448
+ export function evalSeriesValues(spec, scope) {
449
+ if (Array.isArray(spec)) {
450
+ return spec.map((item) => evalNumber(item, scope, 0));
451
+ }
452
+ const points = Math.max(2, Math.min(240, Math.trunc(spec.points || 16)));
453
+ const out = [];
454
+ for (let i = 0; i < points; i++) {
455
+ const t = points > 1 ? i / (points - 1) : 0;
456
+ const val = evalNumber(spec.expr, { ...scope, i, t, n: points }, 0);
457
+ out.push(val);
458
+ }
459
+ return out;
460
+ }
package/dist/ipc.js ADDED
@@ -0,0 +1,201 @@
1
+ import { chmodSync, existsSync, mkdirSync, unlinkSync } from "node:fs";
2
+ import { createConnection, createServer } from "node:net";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { loadConfig } from "./config.js";
6
+ import { autoDockPane, canAutoDock } from "./multiplexer.js";
7
+ export function socketDir() {
8
+ const uid = process.getuid?.() ?? 0;
9
+ const dir = join(tmpdir(), `bypane-${uid}`);
10
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
11
+ try {
12
+ chmodSync(dir, 0o700);
13
+ }
14
+ catch {
15
+ // Ignore on platforms that disallow chmod.
16
+ }
17
+ return dir;
18
+ }
19
+ export function socketPathFor(session) {
20
+ const safe = session.replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, 72);
21
+ return join(socketDir(), `${safe}.sock`);
22
+ }
23
+ function createLineParser(onLine) {
24
+ const decoder = new TextDecoder();
25
+ let buf = "";
26
+ return (chunk) => {
27
+ buf += decoder.decode(chunk, { stream: true });
28
+ let nl = buf.indexOf("\n");
29
+ while (nl >= 0) {
30
+ const line = buf.slice(0, nl).trim();
31
+ buf = buf.slice(nl + 1);
32
+ if (line)
33
+ onLine(line);
34
+ nl = buf.indexOf("\n");
35
+ }
36
+ };
37
+ }
38
+ export function startIpcServer(session, handler) {
39
+ const path = socketPathFor(session);
40
+ try {
41
+ if (existsSync(path))
42
+ unlinkSync(path);
43
+ }
44
+ catch {
45
+ // Ignore stale unlink races.
46
+ }
47
+ const server = createServer((socket) => {
48
+ socket.on("data", createLineParser((line) => {
49
+ let parsed;
50
+ try {
51
+ parsed = JSON.parse(line);
52
+ }
53
+ catch {
54
+ const errRes = { id: "", ok: false, error: "Invalid JSON request" };
55
+ socket.write(`${JSON.stringify(errRes)}\n`);
56
+ return;
57
+ }
58
+ Promise.resolve(handler(parsed))
59
+ .then((res) => {
60
+ if (!socket.destroyed) {
61
+ socket.write(`${JSON.stringify(res)}\n`);
62
+ }
63
+ })
64
+ .catch((err) => {
65
+ if (!socket.destroyed) {
66
+ const errRes = {
67
+ id: parsed.id ?? "",
68
+ ok: false,
69
+ error: err.message,
70
+ };
71
+ socket.write(`${JSON.stringify(errRes)}\n`);
72
+ }
73
+ });
74
+ }));
75
+ socket.on("error", () => {
76
+ // Client disconnected mid-request; ignore cleanly.
77
+ });
78
+ });
79
+ server.listen(path, () => {
80
+ try {
81
+ chmodSync(path, 0o600);
82
+ }
83
+ catch {
84
+ // Ignore chmod failure.
85
+ }
86
+ });
87
+ let closed = false;
88
+ const close = () => {
89
+ if (closed)
90
+ return;
91
+ closed = true;
92
+ try {
93
+ server.close();
94
+ }
95
+ catch {
96
+ // Ignore.
97
+ }
98
+ try {
99
+ if (existsSync(path))
100
+ unlinkSync(path);
101
+ }
102
+ catch {
103
+ // Ignore.
104
+ }
105
+ };
106
+ process.once("exit", close);
107
+ return { path, close };
108
+ }
109
+ function sendOnce(path, req, timeoutMs) {
110
+ return new Promise((resolvePromise, rejectPromise) => {
111
+ const socket = createConnection(path);
112
+ let settled = false;
113
+ const timer = timeoutMs > 0
114
+ ? setTimeout(() => {
115
+ if (!settled) {
116
+ settled = true;
117
+ socket.destroy();
118
+ rejectPromise(new Error(`bypane request timed out after ${timeoutMs}ms`));
119
+ }
120
+ }, timeoutMs)
121
+ : null;
122
+ const finish = (fn) => {
123
+ if (settled)
124
+ return;
125
+ settled = true;
126
+ if (timer)
127
+ clearTimeout(timer);
128
+ fn();
129
+ };
130
+ socket.on("data", createLineParser((line) => {
131
+ finish(() => {
132
+ socket.end();
133
+ try {
134
+ resolvePromise(JSON.parse(line));
135
+ }
136
+ catch {
137
+ rejectPromise(new Error("Malformed JSON response from bypane"));
138
+ }
139
+ });
140
+ }));
141
+ socket.on("error", (err) => {
142
+ finish(() => rejectPromise(err));
143
+ });
144
+ socket.on("close", () => {
145
+ finish(() => rejectPromise(new Error("bypane closed connection before responding")));
146
+ });
147
+ socket.write(`${JSON.stringify(req)}\n`);
148
+ });
149
+ }
150
+ function sleep(ms) {
151
+ return new Promise((r) => setTimeout(r, ms));
152
+ }
153
+ /**
154
+ * Sends a request to the running `bypane` instance for `session`.
155
+ * If no instance is running and `autoDock` is enabled inside Rex/tmux, automatically splits
156
+ * a companion pane, waits briefly for its socket, and retries.
157
+ */
158
+ export async function sendIpc(session, req, options = {}) {
159
+ const path = socketPathFor(session);
160
+ const timeoutMs = options.timeoutMs ?? (req.op === "ask_wait" ? 0 : 5000);
161
+ try {
162
+ return await sendOnce(path, req, timeoutMs);
163
+ }
164
+ catch (err) {
165
+ const code = err.code;
166
+ const notRunning = code === "ENOENT" || code === "ECONNREFUSED";
167
+ if (!notRunning)
168
+ throw err;
169
+ if (code === "ECONNREFUSED") {
170
+ try {
171
+ unlinkSync(path);
172
+ }
173
+ catch {
174
+ // Stale socket cleanup.
175
+ }
176
+ }
177
+ const cfg = loadConfig();
178
+ if (options.autoDock !== false && cfg.autoDock && canAutoDock()) {
179
+ const docked = autoDockPane(session);
180
+ if (!docked.ok) {
181
+ throw new Error(`bypane is not running for session "${session}" and auto-dock failed (${docked.error}). Start \`bypane --session ${session}\` in another pane.`);
182
+ }
183
+ const deadline = Date.now() + 4000;
184
+ while (Date.now() < deadline) {
185
+ await sleep(60);
186
+ if (!existsSync(path))
187
+ continue;
188
+ try {
189
+ return await sendOnce(path, req, timeoutMs);
190
+ }
191
+ catch (retryErr) {
192
+ const rc = retryErr.code;
193
+ if (rc !== "ENOENT" && rc !== "ECONNREFUSED")
194
+ throw retryErr;
195
+ }
196
+ }
197
+ throw new Error(`Auto-docked bypane via ${docked.via}, but socket did not become ready within 4s.`);
198
+ }
199
+ throw new Error(`bypane is not running for session "${session}". Run \`bypane\` in a split pane first.`);
200
+ }
201
+ }