opush-sdk 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/LICENSE +21 -0
- package/README.md +351 -2
- package/dist/cli.js +1737 -0
- package/dist/index.cjs +890 -0
- package/dist/index.d.cts +506 -0
- package/dist/index.d.ts +506 -0
- package/dist/index.js +867 -0
- package/package.json +72 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1737 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli/run.ts
|
|
4
|
+
import { spawn as nodeSpawn } from "child_process";
|
|
5
|
+
import { fstatSync } from "fs";
|
|
6
|
+
|
|
7
|
+
// src/crypto.ts
|
|
8
|
+
import { Aes256Gcm, CipherSuite, DhkemP256HkdfSha256, HkdfSha256 } from "@hpke/core";
|
|
9
|
+
|
|
10
|
+
// src/errors.ts
|
|
11
|
+
var OpushError = class extends Error {
|
|
12
|
+
name = "OpushError";
|
|
13
|
+
status;
|
|
14
|
+
code;
|
|
15
|
+
retryAfter;
|
|
16
|
+
/** The parsed response body, or the raw text when it was not JSON. `undefined` when no response arrived. */
|
|
17
|
+
body;
|
|
18
|
+
constructor(message, options) {
|
|
19
|
+
super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
|
|
20
|
+
this.status = options.status;
|
|
21
|
+
this.code = options.code ?? null;
|
|
22
|
+
this.retryAfter = options.retryAfter ?? null;
|
|
23
|
+
this.body = options.body;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
function parseRetryAfter(value) {
|
|
27
|
+
if (!value) return null;
|
|
28
|
+
const seconds = Number(value);
|
|
29
|
+
if (Number.isFinite(seconds) && seconds >= 0) return seconds;
|
|
30
|
+
const date = Date.parse(value);
|
|
31
|
+
if (Number.isNaN(date)) return null;
|
|
32
|
+
return Math.max(0, Math.ceil((date - Date.now()) / 1e3));
|
|
33
|
+
}
|
|
34
|
+
function errorFromResponse(status, body, retryAfter) {
|
|
35
|
+
let message = `HTTP ${status}`;
|
|
36
|
+
let code = null;
|
|
37
|
+
if (body && typeof body === "object") {
|
|
38
|
+
const b = body;
|
|
39
|
+
if (b.error && typeof b.error === "object") {
|
|
40
|
+
const e = b.error;
|
|
41
|
+
if (typeof e.message === "string") message = e.message;
|
|
42
|
+
if (typeof e.code === "string") code = e.code;
|
|
43
|
+
} else if (typeof b.message === "string") {
|
|
44
|
+
message = b.message;
|
|
45
|
+
}
|
|
46
|
+
} else if (typeof body === "string" && body.trim()) {
|
|
47
|
+
message = body.trim().slice(0, 500);
|
|
48
|
+
}
|
|
49
|
+
return new OpushError(message, { status, code, retryAfter, body });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// src/crypto.ts
|
|
53
|
+
var HPKE_INFO = "opush v1";
|
|
54
|
+
var AES = {
|
|
55
|
+
"aes-128-gcm": { name: "AES-GCM", keyLength: 16, ivLength: 12 },
|
|
56
|
+
"aes-192-gcm": { name: "AES-GCM", keyLength: 24, ivLength: 12 },
|
|
57
|
+
"aes-256-gcm": { name: "AES-GCM", keyLength: 32, ivLength: 12 },
|
|
58
|
+
"aes-128-cbc": { name: "AES-CBC", keyLength: 16, ivLength: 16 },
|
|
59
|
+
"aes-192-cbc": { name: "AES-CBC", keyLength: 24, ivLength: 16 },
|
|
60
|
+
"aes-256-cbc": { name: "AES-CBC", keyLength: 32, ivLength: 16 }
|
|
61
|
+
};
|
|
62
|
+
var cached;
|
|
63
|
+
async function getCrypto() {
|
|
64
|
+
if (cached) return cached;
|
|
65
|
+
const g = globalThis.crypto;
|
|
66
|
+
if (g?.subtle) return cached = g;
|
|
67
|
+
const specifier = "node:crypto";
|
|
68
|
+
const mod = await import(
|
|
69
|
+
/* @vite-ignore */
|
|
70
|
+
specifier
|
|
71
|
+
);
|
|
72
|
+
return cached = mod.webcrypto;
|
|
73
|
+
}
|
|
74
|
+
function invalid(message) {
|
|
75
|
+
return new OpushError(message, { status: 0, code: "invalid_argument" });
|
|
76
|
+
}
|
|
77
|
+
function toBase64(bytes) {
|
|
78
|
+
let binary = "";
|
|
79
|
+
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
|
|
80
|
+
return btoa(binary);
|
|
81
|
+
}
|
|
82
|
+
function fromBase64(value) {
|
|
83
|
+
const normalized = value.replace(/\s+/g, "").replace(/-/g, "+").replace(/_/g, "/");
|
|
84
|
+
const binary = atob(normalized);
|
|
85
|
+
const out = new Uint8Array(binary.length);
|
|
86
|
+
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
var BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
90
|
+
async function randomBase62(length) {
|
|
91
|
+
const crypto = await getCrypto();
|
|
92
|
+
let out = "";
|
|
93
|
+
while (out.length < length) {
|
|
94
|
+
const bytes = crypto.getRandomValues(new Uint8Array(length * 2));
|
|
95
|
+
for (const b of bytes) {
|
|
96
|
+
if (b < 248 && out.length < length) out += BASE62[b % 62];
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
function arrayBuffer(bytes) {
|
|
102
|
+
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
103
|
+
}
|
|
104
|
+
async function encryptAes(plaintext, key, algorithm = "aes-256-gcm") {
|
|
105
|
+
const spec = AES[algorithm];
|
|
106
|
+
if (!spec) throw invalid(`Unsupported algorithm: ${algorithm}`);
|
|
107
|
+
const keyBytes = new TextEncoder().encode(key);
|
|
108
|
+
if (keyBytes.length !== spec.keyLength) {
|
|
109
|
+
throw invalid(`${algorithm} needs a ${spec.keyLength}-character key, got ${keyBytes.length}`);
|
|
110
|
+
}
|
|
111
|
+
const crypto = await getCrypto();
|
|
112
|
+
const iv = await randomBase62(spec.ivLength);
|
|
113
|
+
const cryptoKey = await crypto.subtle.importKey("raw", arrayBuffer(keyBytes), { name: spec.name }, false, ["encrypt"]);
|
|
114
|
+
const encrypted = await crypto.subtle.encrypt(
|
|
115
|
+
{ name: spec.name, iv: arrayBuffer(new TextEncoder().encode(iv)) },
|
|
116
|
+
cryptoKey,
|
|
117
|
+
arrayBuffer(new TextEncoder().encode(plaintext))
|
|
118
|
+
);
|
|
119
|
+
return { ciphertext: toBase64(new Uint8Array(encrypted)), iv };
|
|
120
|
+
}
|
|
121
|
+
function suite() {
|
|
122
|
+
return new CipherSuite({ kem: new DhkemP256HkdfSha256(), kdf: new HkdfSha256(), aead: new Aes256Gcm() });
|
|
123
|
+
}
|
|
124
|
+
async function rawPublicKey(publicKey) {
|
|
125
|
+
const text = publicKey.trim();
|
|
126
|
+
if (text.startsWith("-----BEGIN")) {
|
|
127
|
+
const body = text.replace(/-----(BEGIN|END)[^-]*-----/g, "");
|
|
128
|
+
const der = fromBase64(body);
|
|
129
|
+
const crypto = await getCrypto();
|
|
130
|
+
let key;
|
|
131
|
+
try {
|
|
132
|
+
key = await crypto.subtle.importKey("spki", arrayBuffer(der), { name: "ECDH", namedCurve: "P-256" }, true, []);
|
|
133
|
+
} catch {
|
|
134
|
+
throw invalid("The PEM public key is not a P-256 SPKI key");
|
|
135
|
+
}
|
|
136
|
+
return new Uint8Array(await crypto.subtle.exportKey("raw", key));
|
|
137
|
+
}
|
|
138
|
+
let raw;
|
|
139
|
+
try {
|
|
140
|
+
raw = fromBase64(text);
|
|
141
|
+
} catch {
|
|
142
|
+
throw invalid("The public key is not valid base64");
|
|
143
|
+
}
|
|
144
|
+
if (raw.length !== 65 || raw[0] !== 4) {
|
|
145
|
+
throw invalid("The public key must be a 65-byte uncompressed P-256 point (base64) or a PEM key");
|
|
146
|
+
}
|
|
147
|
+
return raw;
|
|
148
|
+
}
|
|
149
|
+
async function sealHpke(plaintext, publicKey) {
|
|
150
|
+
await getCrypto();
|
|
151
|
+
const raw = await rawPublicKey(publicKey);
|
|
152
|
+
const s = suite();
|
|
153
|
+
const recipientPublicKey = await s.kem.deserializePublicKey(arrayBuffer(raw));
|
|
154
|
+
const sender = await s.createSenderContext({
|
|
155
|
+
recipientPublicKey,
|
|
156
|
+
info: arrayBuffer(new TextEncoder().encode(HPKE_INFO))
|
|
157
|
+
});
|
|
158
|
+
const ct = new Uint8Array(await sender.seal(arrayBuffer(new TextEncoder().encode(plaintext))));
|
|
159
|
+
const enc = new Uint8Array(sender.enc);
|
|
160
|
+
const out = new Uint8Array(enc.length + ct.length);
|
|
161
|
+
out.set(enc);
|
|
162
|
+
out.set(ct, enc.length);
|
|
163
|
+
return toBase64(out);
|
|
164
|
+
}
|
|
165
|
+
var INNER = /* @__PURE__ */ new Set(["title", "subtitle", "body", "markdown", "url", "copy", "icon", "image", "action"]);
|
|
166
|
+
var BUTTON_KEY = /^button\d+(_url|_method|_style)?$/;
|
|
167
|
+
function isInnerParam(name) {
|
|
168
|
+
return INNER.has(name) || BUTTON_KEY.test(name);
|
|
169
|
+
}
|
|
170
|
+
async function encryptParams(params, options) {
|
|
171
|
+
const inner = {};
|
|
172
|
+
const outer = {};
|
|
173
|
+
for (const [k, v] of Object.entries(params)) {
|
|
174
|
+
if (isInnerParam(k)) inner[k] = v;
|
|
175
|
+
else outer[k] = v;
|
|
176
|
+
}
|
|
177
|
+
if (Object.keys(inner).length === 0) return params;
|
|
178
|
+
const json = JSON.stringify(inner);
|
|
179
|
+
if (options.publicKey) {
|
|
180
|
+
return { ...outer, sealed: await sealHpke(json, options.publicKey) };
|
|
181
|
+
}
|
|
182
|
+
if (!options.key) throw invalid("encrypt needs either key or publicKey");
|
|
183
|
+
const { ciphertext, iv } = await encryptAes(json, options.key, options.algorithm ?? "aes-256-gcm");
|
|
184
|
+
return { ...outer, ciphertext, iv };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// src/target.ts
|
|
188
|
+
var DEFAULT_SERVER = "https://opu.sh";
|
|
189
|
+
function normalizeServer(server) {
|
|
190
|
+
const trimmed = server.trim().replace(/\/+$/, "");
|
|
191
|
+
let url;
|
|
192
|
+
try {
|
|
193
|
+
url = new URL(trimmed);
|
|
194
|
+
} catch {
|
|
195
|
+
throw new OpushError(`Invalid server URL: ${server}`, { status: 0, code: "invalid_argument" });
|
|
196
|
+
}
|
|
197
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
|
198
|
+
throw new OpushError(`Server URL must use http or https: ${server}`, { status: 0, code: "invalid_argument" });
|
|
199
|
+
}
|
|
200
|
+
return trimmed;
|
|
201
|
+
}
|
|
202
|
+
function isUrl(value) {
|
|
203
|
+
return /^https?:\/\//i.test(value.trim());
|
|
204
|
+
}
|
|
205
|
+
function parsePushUrl(value) {
|
|
206
|
+
let url;
|
|
207
|
+
try {
|
|
208
|
+
url = new URL(value.trim());
|
|
209
|
+
} catch {
|
|
210
|
+
throw new OpushError(`Invalid push URL: ${value}`, { status: 0, code: "invalid_argument" });
|
|
211
|
+
}
|
|
212
|
+
const segments = url.pathname.split("/").filter(Boolean);
|
|
213
|
+
const key = segments.pop();
|
|
214
|
+
if (!key) throw new OpushError(`Push URL has no key: ${value}`, { status: 0, code: "invalid_argument" });
|
|
215
|
+
let channel = false;
|
|
216
|
+
if (segments[segments.length - 1] === "c") {
|
|
217
|
+
channel = true;
|
|
218
|
+
segments.pop();
|
|
219
|
+
}
|
|
220
|
+
const prefix = segments.length ? `/${segments.join("/")}` : "";
|
|
221
|
+
const result = { server: `${url.protocol}//${url.host}${prefix}`, key: decodeURIComponent(key), channel };
|
|
222
|
+
if (url.username) {
|
|
223
|
+
result.basicAuth = { username: decodeURIComponent(url.username), password: decodeURIComponent(url.password) };
|
|
224
|
+
}
|
|
225
|
+
return result;
|
|
226
|
+
}
|
|
227
|
+
function parseHeartbeat(value) {
|
|
228
|
+
if (!isUrl(value)) return { id: value.trim() };
|
|
229
|
+
const url = new URL(value.trim());
|
|
230
|
+
const segments = url.pathname.split("/").filter(Boolean);
|
|
231
|
+
const hb = segments.lastIndexOf("hb");
|
|
232
|
+
if (hb < 0 || !segments[hb + 1]) {
|
|
233
|
+
throw new OpushError(`Not a heartbeat URL: ${value}`, { status: 0, code: "invalid_argument" });
|
|
234
|
+
}
|
|
235
|
+
const prefix = hb > 0 ? `/${segments.slice(0, hb).join("/")}` : "";
|
|
236
|
+
const out = {
|
|
237
|
+
server: `${url.protocol}//${url.host}${prefix}`,
|
|
238
|
+
id: decodeURIComponent(segments[hb + 1])
|
|
239
|
+
};
|
|
240
|
+
if (url.username) out.basicAuth = { username: decodeURIComponent(url.username), password: decodeURIComponent(url.password) };
|
|
241
|
+
return out;
|
|
242
|
+
}
|
|
243
|
+
function normalizeBasicAuth(value) {
|
|
244
|
+
if (value === void 0 || value === "") return void 0;
|
|
245
|
+
if (typeof value === "string") {
|
|
246
|
+
const i = value.indexOf(":");
|
|
247
|
+
if (i < 0) throw new OpushError('basicAuth must be "user:password"', { status: 0, code: "invalid_argument" });
|
|
248
|
+
return { username: value.slice(0, i), password: value.slice(i + 1) };
|
|
249
|
+
}
|
|
250
|
+
return value;
|
|
251
|
+
}
|
|
252
|
+
function basicAuthHeader(auth) {
|
|
253
|
+
const bytes = new TextEncoder().encode(`${auth.username}:${auth.password}`);
|
|
254
|
+
let binary = "";
|
|
255
|
+
for (const b of bytes) binary += String.fromCharCode(b);
|
|
256
|
+
return `Basic ${btoa(binary)}`;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// src/client.ts
|
|
260
|
+
var MAX_RETRY_WAIT_SECONDS = 60;
|
|
261
|
+
function defaultEnv() {
|
|
262
|
+
const p = globalThis.process;
|
|
263
|
+
return p?.env ?? {};
|
|
264
|
+
}
|
|
265
|
+
var Opush = class {
|
|
266
|
+
/** Server base URL in use, without a trailing slash. */
|
|
267
|
+
server;
|
|
268
|
+
#target;
|
|
269
|
+
#auth;
|
|
270
|
+
#timeout;
|
|
271
|
+
#retries;
|
|
272
|
+
#fetch;
|
|
273
|
+
#encrypt;
|
|
274
|
+
/** Progress cards on the Lock Screen, Dynamic Island and Android status bar. */
|
|
275
|
+
progress;
|
|
276
|
+
/** Escalating alerts created with `escalate`. */
|
|
277
|
+
alerts;
|
|
278
|
+
constructor(options = {}) {
|
|
279
|
+
const env = options.env === false ? {} : options.env ?? defaultEnv();
|
|
280
|
+
let server;
|
|
281
|
+
let auth = normalizeBasicAuth(options.basicAuth);
|
|
282
|
+
const adopt = (parsed) => {
|
|
283
|
+
if (server && server !== parsed.server) {
|
|
284
|
+
throw new OpushError(`All push URLs must use the same server (${server} vs ${parsed.server})`, {
|
|
285
|
+
status: 0,
|
|
286
|
+
code: "invalid_argument"
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
server = parsed.server;
|
|
290
|
+
if (!auth && parsed.basicAuth) auth = parsed.basicAuth;
|
|
291
|
+
};
|
|
292
|
+
const fromKey = (value) => {
|
|
293
|
+
if (!isUrl(value)) return { key: value.trim(), channel: false };
|
|
294
|
+
const parsed = parsePushUrl(value);
|
|
295
|
+
adopt(parsed);
|
|
296
|
+
return { key: parsed.key, channel: parsed.channel };
|
|
297
|
+
};
|
|
298
|
+
const given = [options.key, options.keys, options.channel].filter((v) => v !== void 0 && v !== "").length;
|
|
299
|
+
if (given > 1) {
|
|
300
|
+
throw new OpushError("Pass only one of key, keys or channel", { status: 0, code: "invalid_argument" });
|
|
301
|
+
}
|
|
302
|
+
let target = { kind: "none" };
|
|
303
|
+
const keyInput = given ? options.key : env.OPUSH_KEY;
|
|
304
|
+
const keysInput = given ? options.keys : void 0;
|
|
305
|
+
const channelInput = given ? options.channel : env.OPUSH_KEY ? void 0 : env.OPUSH_CHANNEL;
|
|
306
|
+
if (keysInput && keysInput.length) {
|
|
307
|
+
const parsed = keysInput.map(fromKey);
|
|
308
|
+
if (parsed.some((p) => p.channel)) {
|
|
309
|
+
throw new OpushError("keys can't contain channel URLs", { status: 0, code: "invalid_argument" });
|
|
310
|
+
}
|
|
311
|
+
target = parsed.length === 1 ? { kind: "key", key: parsed[0].key } : { kind: "keys", keys: parsed.map((p) => p.key) };
|
|
312
|
+
} else if (keyInput) {
|
|
313
|
+
const parts = keyInput.split(",").map((s) => s.trim()).filter(Boolean);
|
|
314
|
+
const parsed = parts.map(fromKey);
|
|
315
|
+
if (parsed.length === 1 && parsed[0].channel) target = { kind: "channel", channel: parsed[0].key };
|
|
316
|
+
else if (parsed.some((p) => p.channel)) {
|
|
317
|
+
throw new OpushError("Several keys can't contain channel URLs", { status: 0, code: "invalid_argument" });
|
|
318
|
+
} else if (parsed.length === 1) target = { kind: "key", key: parsed[0].key };
|
|
319
|
+
else target = { kind: "keys", keys: parsed.map((p) => p.key) };
|
|
320
|
+
} else if (channelInput) {
|
|
321
|
+
if (isUrl(channelInput)) {
|
|
322
|
+
const parsed = parsePushUrl(channelInput);
|
|
323
|
+
adopt(parsed);
|
|
324
|
+
target = { kind: "channel", channel: parsed.key };
|
|
325
|
+
} else {
|
|
326
|
+
target = { kind: "channel", channel: channelInput.trim() };
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
this.server = normalizeServer(options.server ?? server ?? env.OPUSH_SERVER ?? DEFAULT_SERVER);
|
|
330
|
+
this.#target = target;
|
|
331
|
+
this.#auth = auth;
|
|
332
|
+
this.#timeout = options.timeout ?? 3e4;
|
|
333
|
+
this.#retries = Math.max(0, Math.floor(options.retries ?? 0));
|
|
334
|
+
const f = options.fetch ?? globalThis.fetch;
|
|
335
|
+
if (!f) throw new OpushError("No fetch available. Pass the fetch option.", { status: 0, code: "invalid_argument" });
|
|
336
|
+
this.#fetch = f;
|
|
337
|
+
this.#encrypt = options.encrypt;
|
|
338
|
+
this.progress = {
|
|
339
|
+
start: (o) => this.#progress("start", o),
|
|
340
|
+
update: (o) => this.#progress("update", o),
|
|
341
|
+
end: (o) => this.#progress("end", o)
|
|
342
|
+
};
|
|
343
|
+
this.alerts = {
|
|
344
|
+
get: async (id) => alertState((await this.#request("GET", `/alerts/${encodeURIComponent(alertId(id))}`)).body),
|
|
345
|
+
cancel: async (id) => alertState((await this.#request("DELETE", `/alerts/${encodeURIComponent(alertId(id))}`)).body)
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
/** The configured target: `"key"`, `"keys"`, `"channel"` or `"none"`. */
|
|
349
|
+
get targetKind() {
|
|
350
|
+
return this.#target.kind;
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Sends a push. A string is sent as the body.
|
|
354
|
+
*
|
|
355
|
+
* @example
|
|
356
|
+
* ```ts
|
|
357
|
+
* await opush.push({ title: "Deploy failed", body: "main #128", level: "timeSensitive", url: "https://ci.example.com/128" });
|
|
358
|
+
* ```
|
|
359
|
+
*/
|
|
360
|
+
async push(message) {
|
|
361
|
+
const msg = typeof message === "string" ? { body: message } : message;
|
|
362
|
+
const target = this.#requireTarget();
|
|
363
|
+
if (msg.oncall && target.kind !== "channel") {
|
|
364
|
+
throw new OpushError("oncall only works with a channel", { status: 0, code: "invalid_argument" });
|
|
365
|
+
}
|
|
366
|
+
let params = buildPushParams(msg);
|
|
367
|
+
const encrypt = msg.encrypt === false ? void 0 : msg.encrypt ?? this.#encrypt;
|
|
368
|
+
if (encrypt) params = await encryptParams(params, encrypt);
|
|
369
|
+
return this.#send(target, params, msg.attachments);
|
|
370
|
+
}
|
|
371
|
+
/** Removes a push (by its `id`) from Notification Center and the inbox. Also cancels a schedule or alert with that `id`. */
|
|
372
|
+
async recall(id) {
|
|
373
|
+
if (!id) throw new OpushError("recall needs an id", { status: 0, code: "invalid_argument" });
|
|
374
|
+
return this.#send(this.#requireTarget(), { id, delete: "1" });
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* Pushes a question and returns a `Question` you can wait on.
|
|
378
|
+
*
|
|
379
|
+
* @example
|
|
380
|
+
* ```ts
|
|
381
|
+
* const q = await opush.ask({ title: "Merge PR #42?", options: ["Merge", "Close"] });
|
|
382
|
+
* const state = await q.wait({ timeout: 10 * 60_000 });
|
|
383
|
+
* if (state.answer?.option === "Merge") await merge();
|
|
384
|
+
* ```
|
|
385
|
+
*/
|
|
386
|
+
async ask(options) {
|
|
387
|
+
const target = this.#requireTarget();
|
|
388
|
+
if (target.kind !== "key") {
|
|
389
|
+
throw new OpushError("ask needs a single device key", { status: 0, code: "invalid_argument" });
|
|
390
|
+
}
|
|
391
|
+
const body = { device_key: target.key, title: options.title };
|
|
392
|
+
if (options.body !== void 0) body.body = options.body;
|
|
393
|
+
if (options.options !== void 0) body.options = options.options;
|
|
394
|
+
if (options.allowText !== void 0) body.allow_text = options.allowText;
|
|
395
|
+
if (options.placeholder !== void 0) body.placeholder = options.placeholder;
|
|
396
|
+
if (options.timeout !== void 0) body.timeout = options.timeout;
|
|
397
|
+
if (options.callbackUrl !== void 0) body.callback_url = options.callbackUrl;
|
|
398
|
+
if (options.group !== void 0) body.group = options.group;
|
|
399
|
+
const res = await this.#request("POST", "/ask", { json: body });
|
|
400
|
+
const r = res.body ?? {};
|
|
401
|
+
return new Question(this, {
|
|
402
|
+
id: String(r.question_id),
|
|
403
|
+
answerUrl: String(r.answer_url ?? `${this.server}/ask/${r.question_id}`),
|
|
404
|
+
expiresAt: String(r.expires_at ?? ""),
|
|
405
|
+
callbackSecret: typeof r.callback_secret === "string" ? r.callback_secret : null
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Reads a question. With `wait` (seconds, up to 50) the server holds the request until the
|
|
410
|
+
* question is no longer pending or the time runs out.
|
|
411
|
+
*/
|
|
412
|
+
async getQuestion(id, options = {}) {
|
|
413
|
+
const wait = Math.max(0, Math.min(50, Math.floor(options.wait ?? 0)));
|
|
414
|
+
const res = await this.#request("GET", `/ask/${encodeURIComponent(questionId(id))}`, {
|
|
415
|
+
query: wait ? { wait: String(wait) } : void 0,
|
|
416
|
+
extraSeconds: wait,
|
|
417
|
+
signal: options.signal
|
|
418
|
+
});
|
|
419
|
+
return questionState(res.body);
|
|
420
|
+
}
|
|
421
|
+
/** Cancels a pending question and removes its notification. */
|
|
422
|
+
async cancelQuestion(id) {
|
|
423
|
+
const res = await this.#request("DELETE", `/ask/${encodeURIComponent(questionId(id))}`);
|
|
424
|
+
return questionState(res.body);
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Returns a heartbeat reporter for a check ID or a full heartbeat URL (`https://opu.sh/hb/CHECK_ID`).
|
|
428
|
+
* Heartbeats don't need a device key.
|
|
429
|
+
*
|
|
430
|
+
* @example
|
|
431
|
+
* ```ts
|
|
432
|
+
* const hb = opush.heartbeat("CHECK_ID");
|
|
433
|
+
* await hb.start();
|
|
434
|
+
* try { await backup(); await hb.ok(); } catch (e) { await hb.fail(String(e)); }
|
|
435
|
+
* ```
|
|
436
|
+
*/
|
|
437
|
+
heartbeat(checkIdOrUrl) {
|
|
438
|
+
const parsed = parseHeartbeat(checkIdOrUrl);
|
|
439
|
+
if (!parsed.id) throw new OpushError("heartbeat needs a check ID", { status: 0, code: "invalid_argument" });
|
|
440
|
+
const send2 = async (signal, message) => {
|
|
441
|
+
const text = message === void 0 ? void 0 : message.slice(0, 1e3);
|
|
442
|
+
await this.#request("POST", `/hb/${encodeURIComponent(parsed.id)}${signal}`, {
|
|
443
|
+
text: text ?? "",
|
|
444
|
+
server: parsed.server ? normalizeServer(parsed.server) : void 0
|
|
445
|
+
});
|
|
446
|
+
};
|
|
447
|
+
return {
|
|
448
|
+
id: parsed.id,
|
|
449
|
+
ok: (message) => send2("", message),
|
|
450
|
+
fail: (message) => send2("/fail", message),
|
|
451
|
+
start: () => send2("/start")
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
// ── internals ────────────────────────────────────────────────────
|
|
455
|
+
#requireTarget() {
|
|
456
|
+
if (this.#target.kind === "none") {
|
|
457
|
+
throw new OpushError("No device key or channel. Pass key, keys or channel, or set OPUSH_KEY.", {
|
|
458
|
+
status: 0,
|
|
459
|
+
code: "invalid_argument"
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
return this.#target;
|
|
463
|
+
}
|
|
464
|
+
async #progress(live, o) {
|
|
465
|
+
if (!o?.id) throw new OpushError("Progress cards need an id", { status: 0, code: "invalid_argument" });
|
|
466
|
+
if (live === "start" && !o.title) throw new OpushError("progress.start needs a title", { status: 0, code: "invalid_argument" });
|
|
467
|
+
const params = { live, id: o.id };
|
|
468
|
+
if (o.title !== void 0) params.title = o.title;
|
|
469
|
+
if (o.status !== void 0) params.status = o.status;
|
|
470
|
+
if (o.progress !== void 0) {
|
|
471
|
+
if (!(o.progress >= 0 && o.progress <= 100)) {
|
|
472
|
+
throw new OpushError("progress must be between 0 and 100", { status: 0, code: "invalid_argument" });
|
|
473
|
+
}
|
|
474
|
+
params.progress = o.progress;
|
|
475
|
+
}
|
|
476
|
+
if ("state" in o && o.state !== void 0) params.state = o.state;
|
|
477
|
+
if ("alert" in o && o.alert) params.alert = "1";
|
|
478
|
+
return this.#send(this.#requireTarget(), params);
|
|
479
|
+
}
|
|
480
|
+
async #send(target, params, attachments) {
|
|
481
|
+
const files = attachments ?? [];
|
|
482
|
+
if (files.length > 5) throw new OpushError("At most 5 attachments per push", { status: 0, code: "invalid_argument" });
|
|
483
|
+
let res;
|
|
484
|
+
if (target.kind === "keys") {
|
|
485
|
+
if (files.length) {
|
|
486
|
+
throw new OpushError("Attachments can't be sent to several keys at once", { status: 0, code: "invalid_argument" });
|
|
487
|
+
}
|
|
488
|
+
res = await this.#request("POST", "/push", { json: { device_keys: target.keys, ...params } });
|
|
489
|
+
} else if (target.kind === "channel") {
|
|
490
|
+
const path = `/c/${encodeURIComponent(target.channel)}`;
|
|
491
|
+
res = files.length ? await this.#request("POST", path, { form: await buildForm(params, files) }) : await this.#request("POST", path, { json: params });
|
|
492
|
+
} else {
|
|
493
|
+
res = files.length ? await this.#request("POST", `/${encodeURIComponent(target.key)}`, { form: await buildForm(params, files) }) : await this.#request("POST", "/push", { json: { device_key: target.key, ...params } });
|
|
494
|
+
}
|
|
495
|
+
return pushResult(res.body);
|
|
496
|
+
}
|
|
497
|
+
/** @internal Sends a request with timeout and retries. */
|
|
498
|
+
async #request(method, path, options = {}) {
|
|
499
|
+
let url = `${options.server ?? this.server}${path}`;
|
|
500
|
+
if (options.query) url += `?${new URLSearchParams(options.query).toString()}`;
|
|
501
|
+
const headers = { accept: "application/json" };
|
|
502
|
+
if (this.#auth) headers.authorization = basicAuthHeader(this.#auth);
|
|
503
|
+
let body;
|
|
504
|
+
if (options.json !== void 0) {
|
|
505
|
+
headers["content-type"] = "application/json";
|
|
506
|
+
body = JSON.stringify(options.json);
|
|
507
|
+
} else if (options.form) {
|
|
508
|
+
body = options.form;
|
|
509
|
+
} else if (options.text !== void 0) {
|
|
510
|
+
headers["content-type"] = "text/plain; charset=utf-8";
|
|
511
|
+
body = options.text;
|
|
512
|
+
}
|
|
513
|
+
for (let attempt = 0; ; attempt++) {
|
|
514
|
+
const timeoutMs = this.#timeout + (options.extraSeconds ?? 0) * 1e3;
|
|
515
|
+
const controller = new AbortController();
|
|
516
|
+
let timedOut = false;
|
|
517
|
+
const timer = setTimeout(() => {
|
|
518
|
+
timedOut = true;
|
|
519
|
+
controller.abort();
|
|
520
|
+
}, timeoutMs);
|
|
521
|
+
const onAbort = () => controller.abort();
|
|
522
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
523
|
+
let response;
|
|
524
|
+
try {
|
|
525
|
+
response = await this.#fetch(url, { method, headers, body, signal: controller.signal });
|
|
526
|
+
} catch (error) {
|
|
527
|
+
clearTimeout(timer);
|
|
528
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
529
|
+
if (options.signal?.aborted) throw error;
|
|
530
|
+
if (timedOut) {
|
|
531
|
+
throw new OpushError(`Request timed out after ${timeoutMs} ms`, { status: 0, code: "timeout", cause: error });
|
|
532
|
+
}
|
|
533
|
+
if (attempt < this.#retries) {
|
|
534
|
+
await sleep(backoff(attempt), options.signal);
|
|
535
|
+
continue;
|
|
536
|
+
}
|
|
537
|
+
throw new OpushError(`Network error: ${error?.message ?? String(error)}`, {
|
|
538
|
+
status: 0,
|
|
539
|
+
code: "network_error",
|
|
540
|
+
cause: error
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
let parsed;
|
|
544
|
+
try {
|
|
545
|
+
const text = await response.text();
|
|
546
|
+
try {
|
|
547
|
+
parsed = text ? JSON.parse(text) : void 0;
|
|
548
|
+
} catch {
|
|
549
|
+
parsed = text;
|
|
550
|
+
}
|
|
551
|
+
} finally {
|
|
552
|
+
clearTimeout(timer);
|
|
553
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
554
|
+
}
|
|
555
|
+
if (response.ok) return { status: response.status, body: parsed };
|
|
556
|
+
const retryAfter = response.status === 429 || response.status === 503 ? parseRetryAfter(response.headers.get("retry-after")) : null;
|
|
557
|
+
if ((response.status === 429 || response.status === 503) && attempt < this.#retries) {
|
|
558
|
+
const wait = retryAfter ?? backoff(attempt) / 1e3;
|
|
559
|
+
if (wait <= MAX_RETRY_WAIT_SECONDS) {
|
|
560
|
+
await sleep(wait * 1e3, options.signal);
|
|
561
|
+
continue;
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
throw errorFromResponse(response.status, parsed, retryAfter);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
};
|
|
568
|
+
var Question = class {
|
|
569
|
+
/** Question ID (`q_…`). It is also the secret for reading the answer. */
|
|
570
|
+
id;
|
|
571
|
+
/** Where to GET or DELETE the question. */
|
|
572
|
+
answerUrl;
|
|
573
|
+
/** When the question expires (ISO 8601). */
|
|
574
|
+
expiresAt;
|
|
575
|
+
/** Only when `callbackUrl` was passed. Use it with `verifySignature`. */
|
|
576
|
+
callbackSecret;
|
|
577
|
+
#client;
|
|
578
|
+
constructor(client, fields) {
|
|
579
|
+
this.#client = client;
|
|
580
|
+
this.id = fields.id;
|
|
581
|
+
this.answerUrl = fields.answerUrl;
|
|
582
|
+
this.expiresAt = fields.expiresAt;
|
|
583
|
+
this.callbackSecret = fields.callbackSecret;
|
|
584
|
+
}
|
|
585
|
+
/** Reads the current state without waiting. */
|
|
586
|
+
get() {
|
|
587
|
+
return this.#client.getQuestion(this.id);
|
|
588
|
+
}
|
|
589
|
+
/**
|
|
590
|
+
* Waits until the question is answered, expires or is cancelled, using long polling.
|
|
591
|
+
* Returns the last state, which is still `pending` if `timeout` (milliseconds) ran out first.
|
|
592
|
+
* Without `timeout` it waits until the question expires.
|
|
593
|
+
*/
|
|
594
|
+
async wait(options = {}) {
|
|
595
|
+
const expires = Date.parse(this.expiresAt);
|
|
596
|
+
const deadline = options.timeout !== void 0 ? Date.now() + options.timeout : Number.isNaN(expires) ? Infinity : expires + 5e3;
|
|
597
|
+
for (; ; ) {
|
|
598
|
+
const remaining = Math.ceil((deadline - Date.now()) / 1e3);
|
|
599
|
+
const state = await this.#client.getQuestion(this.id, {
|
|
600
|
+
wait: Math.max(0, Math.min(50, remaining)),
|
|
601
|
+
signal: options.signal
|
|
602
|
+
});
|
|
603
|
+
if (state.status !== "pending" || remaining <= 0 || Date.now() >= deadline) return state;
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
/** Cancels the question and removes its notification. */
|
|
607
|
+
cancel() {
|
|
608
|
+
return this.#client.cancelQuestion(this.id);
|
|
609
|
+
}
|
|
610
|
+
};
|
|
611
|
+
function backoff(attempt) {
|
|
612
|
+
return Math.min(3e4, 1e3 * 2 ** attempt);
|
|
613
|
+
}
|
|
614
|
+
function sleep(ms, signal) {
|
|
615
|
+
return new Promise((resolve, reject) => {
|
|
616
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
617
|
+
const timer = setTimeout(() => {
|
|
618
|
+
signal?.removeEventListener("abort", onAbort);
|
|
619
|
+
resolve();
|
|
620
|
+
}, ms);
|
|
621
|
+
const onAbort = () => {
|
|
622
|
+
clearTimeout(timer);
|
|
623
|
+
reject(signal.reason);
|
|
624
|
+
};
|
|
625
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
function alertId(value) {
|
|
629
|
+
if (!isUrl(value)) return value.trim();
|
|
630
|
+
const segments = new URL(value).pathname.split("/").filter(Boolean);
|
|
631
|
+
return decodeURIComponent(segments[segments.length - 1] ?? "");
|
|
632
|
+
}
|
|
633
|
+
function questionId(value) {
|
|
634
|
+
return alertId(value);
|
|
635
|
+
}
|
|
636
|
+
var PLAIN_FIELDS = [
|
|
637
|
+
"title",
|
|
638
|
+
"subtitle",
|
|
639
|
+
"body",
|
|
640
|
+
"markdown",
|
|
641
|
+
"icon",
|
|
642
|
+
"image",
|
|
643
|
+
"group",
|
|
644
|
+
"sound",
|
|
645
|
+
"voice",
|
|
646
|
+
"url",
|
|
647
|
+
"copy",
|
|
648
|
+
"action",
|
|
649
|
+
"id",
|
|
650
|
+
"repeat",
|
|
651
|
+
"tz",
|
|
652
|
+
"level"
|
|
653
|
+
];
|
|
654
|
+
function buildPushParams(msg) {
|
|
655
|
+
const p = {};
|
|
656
|
+
for (const name of PLAIN_FIELDS) {
|
|
657
|
+
const v = msg[name];
|
|
658
|
+
if (v !== void 0 && v !== null) p[name] = v;
|
|
659
|
+
}
|
|
660
|
+
if (msg.badge !== void 0) p.badge = msg.badge;
|
|
661
|
+
if (msg.volume !== void 0) p.volume = msg.volume;
|
|
662
|
+
if (msg.ttl !== void 0) p.ttl = msg.ttl;
|
|
663
|
+
if (msg.delay !== void 0) p.delay = msg.delay;
|
|
664
|
+
if (msg.at !== void 0) p.at = msg.at instanceof Date ? msg.at.toISOString() : msg.at;
|
|
665
|
+
if (msg.call !== void 0 && msg.call !== false) p.call = msg.call === true ? "1" : msg.call;
|
|
666
|
+
if (msg.archive !== void 0) p.isArchive = msg.archive ? "1" : "0";
|
|
667
|
+
if (msg.sms) p.sms = "1";
|
|
668
|
+
if (msg.phone) p.phone = "1";
|
|
669
|
+
if (msg.oncall) p.oncall = "1";
|
|
670
|
+
if (msg.escalate !== void 0 && msg.escalate !== false) {
|
|
671
|
+
p.escalate = msg.escalate === true ? "1" : msg.escalate.join(",");
|
|
672
|
+
}
|
|
673
|
+
if (msg.escalateAfter !== void 0) p.escalate_after = msg.escalateAfter;
|
|
674
|
+
if (msg.callbackUrl !== void 0) p.callback_url = msg.callbackUrl;
|
|
675
|
+
if (msg.buttons?.length) {
|
|
676
|
+
if (msg.buttons.length > 2) throw new OpushError("At most 2 buttons", { status: 0, code: "invalid_argument" });
|
|
677
|
+
msg.buttons.forEach((b, i) => {
|
|
678
|
+
const n = i + 1;
|
|
679
|
+
p[`button${n}`] = b.title;
|
|
680
|
+
p[`button${n}_url`] = b.url;
|
|
681
|
+
if (b.method) p[`button${n}_method`] = b.method;
|
|
682
|
+
if (b.style) p[`button${n}_style`] = b.style;
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
return p;
|
|
686
|
+
}
|
|
687
|
+
async function buildForm(params, files) {
|
|
688
|
+
const form = new FormData();
|
|
689
|
+
for (const [k, v] of Object.entries(params)) {
|
|
690
|
+
if (v === void 0 || v === null) continue;
|
|
691
|
+
form.append(k, typeof v === "string" ? v : typeof v === "object" ? JSON.stringify(v) : String(v));
|
|
692
|
+
}
|
|
693
|
+
for (const file of files) {
|
|
694
|
+
const { blob, name } = await toBlob(file);
|
|
695
|
+
form.append("file", blob, name);
|
|
696
|
+
}
|
|
697
|
+
return form;
|
|
698
|
+
}
|
|
699
|
+
async function readPath(path) {
|
|
700
|
+
const fsName = "node:fs/promises";
|
|
701
|
+
const pathName = "node:path";
|
|
702
|
+
let fs;
|
|
703
|
+
let pathMod;
|
|
704
|
+
try {
|
|
705
|
+
fs = await import(
|
|
706
|
+
/* @vite-ignore */
|
|
707
|
+
fsName
|
|
708
|
+
);
|
|
709
|
+
pathMod = await import(
|
|
710
|
+
/* @vite-ignore */
|
|
711
|
+
pathName
|
|
712
|
+
);
|
|
713
|
+
} catch (error) {
|
|
714
|
+
throw new OpushError("File paths need Node, Bun or Deno. Pass a Blob or Uint8Array instead.", {
|
|
715
|
+
status: 0,
|
|
716
|
+
code: "invalid_argument",
|
|
717
|
+
cause: error
|
|
718
|
+
});
|
|
719
|
+
}
|
|
720
|
+
return { data: await fs.readFile(path), name: pathMod.basename(path) };
|
|
721
|
+
}
|
|
722
|
+
async function toBlob(file) {
|
|
723
|
+
if (typeof file === "string") {
|
|
724
|
+
const { data, name } = await readPath(file);
|
|
725
|
+
return { blob: new Blob([data]), name };
|
|
726
|
+
}
|
|
727
|
+
if (file instanceof Blob) {
|
|
728
|
+
const name = file.name || "file";
|
|
729
|
+
return { blob: file, name };
|
|
730
|
+
}
|
|
731
|
+
if (file instanceof Uint8Array || file instanceof ArrayBuffer) {
|
|
732
|
+
return { blob: new Blob([file]), name: "file" };
|
|
733
|
+
}
|
|
734
|
+
if ("path" in file) {
|
|
735
|
+
const { data, name } = await readPath(file.path);
|
|
736
|
+
return { blob: new Blob([data], file.type ? { type: file.type } : void 0), name: file.name ?? name };
|
|
737
|
+
}
|
|
738
|
+
const blob = file.data instanceof Blob ? file.data : new Blob([file.data], file.type ? { type: file.type } : void 0);
|
|
739
|
+
return { blob, name: file.name };
|
|
740
|
+
}
|
|
741
|
+
function schedule(data) {
|
|
742
|
+
if (!data || typeof data !== "object") return null;
|
|
743
|
+
const d = data;
|
|
744
|
+
if (typeof d.id !== "string" || !("fire_at" in d)) return null;
|
|
745
|
+
return { id: d.id, fireAt: String(d.fire_at), repeat: typeof d.repeat === "string" ? d.repeat : null };
|
|
746
|
+
}
|
|
747
|
+
function escalation(data) {
|
|
748
|
+
if (!data || typeof data !== "object") return null;
|
|
749
|
+
const e = data.escalation;
|
|
750
|
+
if (!e || typeof e !== "object") return null;
|
|
751
|
+
const x = e;
|
|
752
|
+
return {
|
|
753
|
+
alertId: String(x.alert_id),
|
|
754
|
+
steps: Array.isArray(x.steps) ? x.steps.map(String) : [],
|
|
755
|
+
everyMinutes: Number(x.every_minutes),
|
|
756
|
+
nextAt: typeof x.next_at === "string" ? x.next_at : null,
|
|
757
|
+
statusUrl: String(x.status_url),
|
|
758
|
+
callbackSecret: typeof x.callback_secret === "string" ? x.callback_secret : null
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
function pushResult(body) {
|
|
762
|
+
const b = body && typeof body === "object" ? body : {};
|
|
763
|
+
const data = b.data;
|
|
764
|
+
const message = typeof b.message === "string" ? b.message : "success";
|
|
765
|
+
let results = null;
|
|
766
|
+
if (Array.isArray(data)) {
|
|
767
|
+
results = data.map((entry) => {
|
|
768
|
+
const e = entry ?? {};
|
|
769
|
+
return {
|
|
770
|
+
code: Number(e.code),
|
|
771
|
+
deviceKey: String(e.device_key ?? ""),
|
|
772
|
+
message: typeof e.message === "string" ? e.message : null,
|
|
773
|
+
schedule: schedule(e.schedule),
|
|
774
|
+
escalation: escalation(e),
|
|
775
|
+
raw: e
|
|
776
|
+
};
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
return {
|
|
780
|
+
message,
|
|
781
|
+
timestamp: Number(b.timestamp ?? 0),
|
|
782
|
+
data,
|
|
783
|
+
schedule: message === "scheduled" && !Array.isArray(data) ? schedule(data) : null,
|
|
784
|
+
escalation: Array.isArray(data) ? null : escalation(data),
|
|
785
|
+
results
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
function questionState(body) {
|
|
789
|
+
const b = body ?? {};
|
|
790
|
+
const a = b.answer;
|
|
791
|
+
return {
|
|
792
|
+
id: String(b.question_id),
|
|
793
|
+
status: b.status,
|
|
794
|
+
title: String(b.title ?? ""),
|
|
795
|
+
body: typeof b.body === "string" ? b.body : null,
|
|
796
|
+
options: Array.isArray(b.options) ? b.options.map(String) : [],
|
|
797
|
+
allowText: Boolean(b.allow_text),
|
|
798
|
+
createdAt: String(b.created_at ?? ""),
|
|
799
|
+
expiresAt: String(b.expires_at ?? ""),
|
|
800
|
+
answer: a ? {
|
|
801
|
+
option: typeof a.option === "string" ? a.option : null,
|
|
802
|
+
optionIndex: typeof a.option_index === "number" ? a.option_index : null,
|
|
803
|
+
text: typeof a.text === "string" ? a.text : null,
|
|
804
|
+
answeredAt: String(a.answered_at ?? "")
|
|
805
|
+
} : null
|
|
806
|
+
};
|
|
807
|
+
}
|
|
808
|
+
function alertState(body) {
|
|
809
|
+
const b = body ?? {};
|
|
810
|
+
const str = (v) => typeof v === "string" ? v : null;
|
|
811
|
+
return {
|
|
812
|
+
id: String(b.alert_id),
|
|
813
|
+
status: b.status,
|
|
814
|
+
steps: Array.isArray(b.steps) ? b.steps.map(String) : [],
|
|
815
|
+
nextStep: str(b.next_step),
|
|
816
|
+
nextAt: str(b.next_at),
|
|
817
|
+
ackedAt: str(b.acked_at),
|
|
818
|
+
ackedBy: str(b.acked_by),
|
|
819
|
+
ackedAccountId: str(b.acked_account_id),
|
|
820
|
+
channelId: str(b.channel_id),
|
|
821
|
+
history: Array.isArray(b.history) ? b.history.map((h) => {
|
|
822
|
+
const x = h ?? {};
|
|
823
|
+
return { step: String(x.step), at: String(x.at), result: String(x.result) };
|
|
824
|
+
}) : [],
|
|
825
|
+
createdAt: String(b.created_at ?? "")
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
// src/version.ts
|
|
830
|
+
var VERSION = true ? "0.1.1" : "0.0.0-dev";
|
|
831
|
+
|
|
832
|
+
// src/cli/args.ts
|
|
833
|
+
import { parseArgs } from "util";
|
|
834
|
+
var UsageError = class extends Error {
|
|
835
|
+
name = "UsageError";
|
|
836
|
+
};
|
|
837
|
+
var GLOBAL_OPTIONS = {
|
|
838
|
+
key: { type: "string", short: "k" },
|
|
839
|
+
channel: { type: "string", short: "c" },
|
|
840
|
+
server: { type: "string" },
|
|
841
|
+
"basic-auth": { type: "string" },
|
|
842
|
+
json: { type: "boolean" },
|
|
843
|
+
timeout: { type: "string" },
|
|
844
|
+
retries: { type: "string" },
|
|
845
|
+
help: { type: "boolean", short: "h" }
|
|
846
|
+
};
|
|
847
|
+
var PUSH_OPTIONS = {
|
|
848
|
+
title: { type: "string", short: "t" },
|
|
849
|
+
subtitle: { type: "string" },
|
|
850
|
+
body: { type: "string", short: "b" },
|
|
851
|
+
markdown: { type: "string", short: "m" },
|
|
852
|
+
icon: { type: "string" },
|
|
853
|
+
image: { type: "string" },
|
|
854
|
+
group: { type: "string", short: "g" },
|
|
855
|
+
badge: { type: "string" },
|
|
856
|
+
level: { type: "string", short: "l" },
|
|
857
|
+
volume: { type: "string" },
|
|
858
|
+
sound: { type: "string", short: "s" },
|
|
859
|
+
call: { type: "string" },
|
|
860
|
+
voice: { type: "string" },
|
|
861
|
+
url: { type: "string", short: "u" },
|
|
862
|
+
copy: { type: "string" },
|
|
863
|
+
action: { type: "string" },
|
|
864
|
+
button: { type: "string", multiple: true },
|
|
865
|
+
buttons: { type: "string" },
|
|
866
|
+
id: { type: "string" },
|
|
867
|
+
archive: { type: "boolean" },
|
|
868
|
+
"no-archive": { type: "boolean" },
|
|
869
|
+
ttl: { type: "string" },
|
|
870
|
+
at: { type: "string" },
|
|
871
|
+
delay: { type: "string" },
|
|
872
|
+
repeat: { type: "string" },
|
|
873
|
+
tz: { type: "string" },
|
|
874
|
+
sms: { type: "boolean" },
|
|
875
|
+
phone: { type: "boolean" },
|
|
876
|
+
escalate: { type: "string" },
|
|
877
|
+
"escalate-after": { type: "string" },
|
|
878
|
+
"callback-url": { type: "string" },
|
|
879
|
+
file: { type: "string", short: "f", multiple: true },
|
|
880
|
+
oncall: { type: "boolean" },
|
|
881
|
+
"encrypt-key": { type: "string" },
|
|
882
|
+
"encrypt-algorithm": { type: "string" },
|
|
883
|
+
"public-key": { type: "string" }
|
|
884
|
+
};
|
|
885
|
+
var LEVELS = ["active", "timeSensitive", "passive", "critical"];
|
|
886
|
+
var REPEATS = ["hourly", "daily", "weekdays", "weekly", "monthly"];
|
|
887
|
+
var STEPS = ["push", "voice", "sms", "phone"];
|
|
888
|
+
var ESCALATE_VALUE = /^(1|true|push|voice|sms|phone|[a-z]+(,[a-z]+)+)$/;
|
|
889
|
+
function normalizeOptionalValues(argv) {
|
|
890
|
+
const out = [];
|
|
891
|
+
for (let i = 0; i < argv.length; i++) {
|
|
892
|
+
const arg = argv[i];
|
|
893
|
+
out.push(arg);
|
|
894
|
+
if (arg === "--") {
|
|
895
|
+
out.push(...argv.slice(i + 1));
|
|
896
|
+
break;
|
|
897
|
+
}
|
|
898
|
+
const next = argv[i + 1];
|
|
899
|
+
if (arg === "--call" && !(next !== void 0 && /^(1|true|voice)$/.test(next))) out.push("1");
|
|
900
|
+
if (arg === "--escalate" && !(next !== void 0 && ESCALATE_VALUE.test(next))) out.push("1");
|
|
901
|
+
}
|
|
902
|
+
return out;
|
|
903
|
+
}
|
|
904
|
+
function parse(argv, options) {
|
|
905
|
+
try {
|
|
906
|
+
return parseArgs({
|
|
907
|
+
args: normalizeOptionalValues(argv),
|
|
908
|
+
options: { ...GLOBAL_OPTIONS, ...options },
|
|
909
|
+
allowPositionals: true,
|
|
910
|
+
strict: true
|
|
911
|
+
});
|
|
912
|
+
} catch (error) {
|
|
913
|
+
throw new UsageError(error.message);
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
function int(name, value, min, max) {
|
|
917
|
+
if (value === void 0) return void 0;
|
|
918
|
+
const n = Number(value);
|
|
919
|
+
if (!Number.isFinite(n) || min !== void 0 && n < min || max !== void 0 && n > max) {
|
|
920
|
+
const range = min !== void 0 && max !== void 0 ? ` (${min}\u2013${max})` : "";
|
|
921
|
+
throw new UsageError(`--${name} must be a number${range}, got "${value}"`);
|
|
922
|
+
}
|
|
923
|
+
return n;
|
|
924
|
+
}
|
|
925
|
+
function number(name, value, min, max) {
|
|
926
|
+
return int(name, value, min, max);
|
|
927
|
+
}
|
|
928
|
+
function oneOf(name, value, allowed) {
|
|
929
|
+
if (value === void 0) return void 0;
|
|
930
|
+
if (!allowed.includes(value)) {
|
|
931
|
+
throw new UsageError(`--${name} must be one of ${allowed.join(", ")}, got "${value}"`);
|
|
932
|
+
}
|
|
933
|
+
return value;
|
|
934
|
+
}
|
|
935
|
+
function parseButton(value) {
|
|
936
|
+
const i = value.indexOf("=");
|
|
937
|
+
if (i <= 0 || i === value.length - 1) throw new UsageError(`--button must be "Label=URL", got "${value}"`);
|
|
938
|
+
return { title: value.slice(0, i), url: value.slice(i + 1) };
|
|
939
|
+
}
|
|
940
|
+
function pushMessageFrom(values) {
|
|
941
|
+
const m = {};
|
|
942
|
+
const copy = ["title", "subtitle", "body", "markdown", "icon", "image", "group", "sound", "voice", "url", "copy", "id", "tz"];
|
|
943
|
+
for (const name of copy) if (values[name] !== void 0) m[name] = values[name];
|
|
944
|
+
m.level = oneOf("level", values.level, LEVELS);
|
|
945
|
+
m.repeat = oneOf("repeat", values.repeat, REPEATS);
|
|
946
|
+
m.action = oneOf("action", values.action, ["none", "alert"]);
|
|
947
|
+
m.badge = int("badge", values.badge, 0);
|
|
948
|
+
m.volume = int("volume", values.volume, 0, 10);
|
|
949
|
+
m.ttl = int("ttl", values.ttl, 0);
|
|
950
|
+
m.delay = int("delay", values.delay, 0);
|
|
951
|
+
if (values.at !== void 0) m.at = /^\d+$/.test(values.at) ? Number(values.at) : values.at;
|
|
952
|
+
if (values.call !== void 0) {
|
|
953
|
+
const c = oneOf("call", values.call, ["1", "true", "voice"]);
|
|
954
|
+
m.call = c === "voice" ? "voice" : true;
|
|
955
|
+
}
|
|
956
|
+
if (values.archive && values["no-archive"]) throw new UsageError("Use either --archive or --no-archive");
|
|
957
|
+
if (values.archive) m.archive = true;
|
|
958
|
+
if (values["no-archive"]) m.archive = false;
|
|
959
|
+
if (values.sms) m.sms = true;
|
|
960
|
+
if (values.phone) m.phone = true;
|
|
961
|
+
if (values.oncall) m.oncall = true;
|
|
962
|
+
if (values.escalate !== void 0) {
|
|
963
|
+
if (values.escalate === "1" || values.escalate === "true") m.escalate = true;
|
|
964
|
+
else {
|
|
965
|
+
const steps = values.escalate.split(",").map((s) => s.trim());
|
|
966
|
+
for (const s of steps) oneOf("escalate", s, STEPS);
|
|
967
|
+
m.escalate = steps;
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
m.escalateAfter = int("escalate-after", values["escalate-after"], 1, 60);
|
|
971
|
+
if (values["callback-url"] !== void 0) m.callbackUrl = values["callback-url"];
|
|
972
|
+
const buttons = [];
|
|
973
|
+
if (values.buttons !== void 0) {
|
|
974
|
+
let parsed;
|
|
975
|
+
try {
|
|
976
|
+
parsed = JSON.parse(values.buttons);
|
|
977
|
+
} catch {
|
|
978
|
+
throw new UsageError("--buttons must be a JSON array");
|
|
979
|
+
}
|
|
980
|
+
if (!Array.isArray(parsed)) throw new UsageError("--buttons must be a JSON array");
|
|
981
|
+
buttons.push(...parsed);
|
|
982
|
+
}
|
|
983
|
+
for (const b of values.button ?? []) buttons.push(parseButton(b));
|
|
984
|
+
if (buttons.length > 2) throw new UsageError("At most 2 buttons");
|
|
985
|
+
if (buttons.length) m.buttons = buttons;
|
|
986
|
+
if (values.file?.length) {
|
|
987
|
+
if (values.file.length > 5) throw new UsageError("At most 5 files");
|
|
988
|
+
m.attachments = values.file;
|
|
989
|
+
}
|
|
990
|
+
const encrypt = encryptFrom(values);
|
|
991
|
+
if (encrypt) m.encrypt = encrypt;
|
|
992
|
+
for (const k of Object.keys(m)) if (m[k] === void 0) delete m[k];
|
|
993
|
+
return m;
|
|
994
|
+
}
|
|
995
|
+
function encryptFrom(values) {
|
|
996
|
+
const key = values["encrypt-key"];
|
|
997
|
+
const publicKey = values["public-key"];
|
|
998
|
+
if (key && publicKey) throw new UsageError("Use either --encrypt-key or --public-key");
|
|
999
|
+
if (publicKey) return { publicKey };
|
|
1000
|
+
if (key) {
|
|
1001
|
+
const algorithm = oneOf("encrypt-algorithm", values["encrypt-algorithm"] ?? "aes-256-gcm", [
|
|
1002
|
+
"aes-128-gcm",
|
|
1003
|
+
"aes-192-gcm",
|
|
1004
|
+
"aes-256-gcm",
|
|
1005
|
+
"aes-128-cbc",
|
|
1006
|
+
"aes-192-cbc",
|
|
1007
|
+
"aes-256-cbc"
|
|
1008
|
+
]);
|
|
1009
|
+
return { key, algorithm };
|
|
1010
|
+
}
|
|
1011
|
+
if (values["encrypt-algorithm"]) throw new UsageError("--encrypt-algorithm needs --encrypt-key");
|
|
1012
|
+
return void 0;
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
// src/cli/config.ts
|
|
1016
|
+
import { chmod, mkdir, readFile, rename, writeFile } from "fs/promises";
|
|
1017
|
+
import { homedir } from "os";
|
|
1018
|
+
import { dirname, join } from "path";
|
|
1019
|
+
var CONFIG_NAMES = {
|
|
1020
|
+
key: "key",
|
|
1021
|
+
server: "server",
|
|
1022
|
+
channel: "channel",
|
|
1023
|
+
"basic-auth": "basicAuth",
|
|
1024
|
+
basicauth: "basicAuth",
|
|
1025
|
+
basic_auth: "basicAuth"
|
|
1026
|
+
};
|
|
1027
|
+
function configPath(env = process.env) {
|
|
1028
|
+
const base = env.XDG_CONFIG_HOME || join(homedir(), ".config");
|
|
1029
|
+
return join(base, "opush", "config.json");
|
|
1030
|
+
}
|
|
1031
|
+
async function readConfig(path = configPath()) {
|
|
1032
|
+
let text;
|
|
1033
|
+
try {
|
|
1034
|
+
text = await readFile(path, "utf8");
|
|
1035
|
+
} catch (error) {
|
|
1036
|
+
if (error.code === "ENOENT") return {};
|
|
1037
|
+
throw error;
|
|
1038
|
+
}
|
|
1039
|
+
try {
|
|
1040
|
+
const parsed = JSON.parse(text);
|
|
1041
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
1042
|
+
} catch {
|
|
1043
|
+
throw new Error(`${path} is not valid JSON`);
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
async function writeConfig(config2, path = configPath()) {
|
|
1047
|
+
await mkdir(dirname(path), { recursive: true, mode: 448 });
|
|
1048
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
1049
|
+
await writeFile(tmp, `${JSON.stringify(config2, null, 2)}
|
|
1050
|
+
`, { mode: 384 });
|
|
1051
|
+
await chmod(tmp, 384);
|
|
1052
|
+
await rename(tmp, path);
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
// src/cli/help.ts
|
|
1056
|
+
var TARGET = `Target:
|
|
1057
|
+
-k, --key KEY Device key or push URL (comma-separate several keys)
|
|
1058
|
+
-c, --channel KEY Channel push key or channel URL
|
|
1059
|
+
--server URL Server, default https://opu.sh (or an enterprise server)
|
|
1060
|
+
--basic-auth U:P Basic Auth credentials for enterprise servers
|
|
1061
|
+
The key is read from --key, then OPUSH_KEY, then the config file.
|
|
1062
|
+
|
|
1063
|
+
Output:
|
|
1064
|
+
--json Print the raw JSON response
|
|
1065
|
+
--timeout SEC Request timeout in seconds (default 30)
|
|
1066
|
+
--retries N Retry after 429, 503 or network errors (default 0)
|
|
1067
|
+
-h, --help Show help`;
|
|
1068
|
+
var PUSH = `Content:
|
|
1069
|
+
-t, --title TEXT Title
|
|
1070
|
+
--subtitle TEXT Line below the title
|
|
1071
|
+
-b, --body TEXT Body (or the first argument, or stdin)
|
|
1072
|
+
-m, --markdown TEXT Body in Markdown
|
|
1073
|
+
--icon URL Icon image
|
|
1074
|
+
--image URL Attached image
|
|
1075
|
+
-f, --file PATH Attach a file (repeat up to 5 times)
|
|
1076
|
+
|
|
1077
|
+
Behavior:
|
|
1078
|
+
-l, --level LEVEL active | timeSensitive | passive | critical
|
|
1079
|
+
--volume 0-10 Volume for critical pushes
|
|
1080
|
+
-s, --sound NAME Sound name
|
|
1081
|
+
--call [voice] Repeat the sound (or ring like a call with "voice")
|
|
1082
|
+
--voice NAME Recorded message: alert, down, recovered, failed, done, security
|
|
1083
|
+
-g, --group NAME Group
|
|
1084
|
+
--badge N App icon badge
|
|
1085
|
+
-u, --url URL Open this link on tap
|
|
1086
|
+
--copy TEXT Text the Copy button copies
|
|
1087
|
+
--action none Tap opens Opush instead of the URL
|
|
1088
|
+
--button L=URL Custom button (repeat up to 2 times)
|
|
1089
|
+
--buttons JSON Buttons as a JSON array of {title,url,method,style}
|
|
1090
|
+
--id ID Push ID (replace or recall later)
|
|
1091
|
+
--archive Save in the inbox (--no-archive: don't)
|
|
1092
|
+
--ttl SEC Remove after this many seconds
|
|
1093
|
+
|
|
1094
|
+
Schedule:
|
|
1095
|
+
--at TIME Unix seconds, ISO 8601, 2026-12-01T09:00 or 09:00
|
|
1096
|
+
--delay SEC Deliver after this many seconds
|
|
1097
|
+
--repeat RULE hourly | daily | weekdays | weekly | monthly
|
|
1098
|
+
--tz ZONE IANA time zone, such as Asia/Taipei
|
|
1099
|
+
|
|
1100
|
+
Urgent:
|
|
1101
|
+
--sms Also send a text message
|
|
1102
|
+
--phone Also place a phone call
|
|
1103
|
+
--escalate [STEPS] Escalate until acknowledged (push,voice,sms,phone)
|
|
1104
|
+
--escalate-after M Minutes between steps (1-60)
|
|
1105
|
+
--callback-url URL POST here when acknowledged
|
|
1106
|
+
--oncall Channel only: send to the person on call
|
|
1107
|
+
|
|
1108
|
+
Encryption:
|
|
1109
|
+
--encrypt-key KEY Shared AES key from the app
|
|
1110
|
+
--encrypt-algorithm ALG aes-256-gcm (default), aes-128-cbc, ...
|
|
1111
|
+
--public-key KEY End-to-end: the device's public key (base64 or PEM)`;
|
|
1112
|
+
var HELP = {
|
|
1113
|
+
main: `opush - send push notifications with Opush (https://opu.sh)
|
|
1114
|
+
|
|
1115
|
+
Usage:
|
|
1116
|
+
opush [send] [BODY] [options] Send a push (body from stdin if piped)
|
|
1117
|
+
opush recall ID Remove a push by its id
|
|
1118
|
+
opush ask QUESTION [options] Ask a question, optionally wait for the answer
|
|
1119
|
+
opush progress start|update|end Show a live progress card
|
|
1120
|
+
opush hb CHECK_ID [--fail|--start] [MESSAGE]
|
|
1121
|
+
Report a heartbeat check-in
|
|
1122
|
+
opush run [options] -- COMMAND Run a command and push the result
|
|
1123
|
+
opush config set|get|unset|path Save the key and server
|
|
1124
|
+
|
|
1125
|
+
Examples:
|
|
1126
|
+
opush "Backup done"
|
|
1127
|
+
opush -t Deploy "v2 is live" --level timeSensitive --url https://example.com
|
|
1128
|
+
echo "log output" | opush -t Nightly
|
|
1129
|
+
opush ask "Merge PR #42?" --option Merge --option Close --wait
|
|
1130
|
+
opush run --title Backup -- ./backup.sh
|
|
1131
|
+
|
|
1132
|
+
Run "opush COMMAND --help" for the options of a command.
|
|
1133
|
+
Docs: https://opu.sh/docs`,
|
|
1134
|
+
send: `Usage: opush [send] [BODY] [options]
|
|
1135
|
+
|
|
1136
|
+
Sends a push. BODY can also come from --body or stdin ("-" reads stdin).
|
|
1137
|
+
|
|
1138
|
+
${PUSH}
|
|
1139
|
+
|
|
1140
|
+
${TARGET}`,
|
|
1141
|
+
recall: `Usage: opush recall ID [options]
|
|
1142
|
+
|
|
1143
|
+
Removes the push with this id from Notification Center and the inbox.
|
|
1144
|
+
Also cancels a scheduled push or an escalating alert with the same id.
|
|
1145
|
+
|
|
1146
|
+
${TARGET}`,
|
|
1147
|
+
ask: `Usage: opush ask QUESTION [options]
|
|
1148
|
+
|
|
1149
|
+
Pushes a question and, with --wait, prints the answer.
|
|
1150
|
+
|
|
1151
|
+
Options:
|
|
1152
|
+
-o, --option TEXT A choice (repeat up to 4 times)
|
|
1153
|
+
--text Allow a typed answer
|
|
1154
|
+
--placeholder TEXT Hint in the text field
|
|
1155
|
+
-b, --body TEXT More context under the question
|
|
1156
|
+
--expires SEC Seconds until the question expires (60-604800, default 3600)
|
|
1157
|
+
--callback-url URL POST the answered question here
|
|
1158
|
+
-g, --group NAME Inbox group
|
|
1159
|
+
-w, --wait Wait for the answer and print it
|
|
1160
|
+
--wait-timeout SEC Stop waiting after this many seconds
|
|
1161
|
+
|
|
1162
|
+
Exit codes with --wait:
|
|
1163
|
+
0 answered, 1 error, 2 expired, 3 cancelled, 4 still pending after --wait-timeout
|
|
1164
|
+
|
|
1165
|
+
${TARGET}`,
|
|
1166
|
+
progress: `Usage: opush progress start|update|end --id ID [options]
|
|
1167
|
+
|
|
1168
|
+
Shows a live progress card on the Lock Screen, Dynamic Island or Android status bar.
|
|
1169
|
+
|
|
1170
|
+
Options:
|
|
1171
|
+
--id ID Names the card (required)
|
|
1172
|
+
-t, --title TEXT Card title (required for start)
|
|
1173
|
+
--status TEXT Status line
|
|
1174
|
+
-p, --progress N 0-100
|
|
1175
|
+
--state STATE running | success | failed (end: success | failed)
|
|
1176
|
+
--alert Also alert on this update
|
|
1177
|
+
|
|
1178
|
+
${TARGET}`,
|
|
1179
|
+
hb: `Usage: opush hb CHECK_ID|URL [MESSAGE] [--fail|--start]
|
|
1180
|
+
|
|
1181
|
+
Reports a heartbeat check-in. MESSAGE "-" reads it from stdin.
|
|
1182
|
+
|
|
1183
|
+
Options:
|
|
1184
|
+
--fail Report a failure (you get a push right away)
|
|
1185
|
+
--start Mark the start of a run
|
|
1186
|
+
|
|
1187
|
+
${TARGET}`,
|
|
1188
|
+
run: `Usage: opush run [options] -- COMMAND [ARGS...]
|
|
1189
|
+
|
|
1190
|
+
Runs COMMAND, then pushes whether it succeeded or failed, how long it took and the
|
|
1191
|
+
last lines of output. Exits with the command's exit code.
|
|
1192
|
+
|
|
1193
|
+
Options:
|
|
1194
|
+
-n, --lines N How many output lines to include (default 10, 0 for none)
|
|
1195
|
+
--failure-only Only push when the command fails
|
|
1196
|
+
Failed runs default to --level timeSensitive.
|
|
1197
|
+
|
|
1198
|
+
${PUSH}
|
|
1199
|
+
|
|
1200
|
+
${TARGET}`,
|
|
1201
|
+
config: `Usage:
|
|
1202
|
+
opush config set NAME VALUE Save a setting
|
|
1203
|
+
opush config get [NAME] Print one or all settings
|
|
1204
|
+
opush config unset NAME Remove a setting
|
|
1205
|
+
opush config path Print the config file path
|
|
1206
|
+
|
|
1207
|
+
Names: key, server, channel, basic-auth
|
|
1208
|
+
The file is ~/.config/opush/config.json (or $XDG_CONFIG_HOME/opush), mode 0600.`
|
|
1209
|
+
};
|
|
1210
|
+
|
|
1211
|
+
// src/cli/run.ts
|
|
1212
|
+
function defaultIO() {
|
|
1213
|
+
return {
|
|
1214
|
+
stdout: (t) => process.stdout.write(t),
|
|
1215
|
+
stderr: (t) => process.stderr.write(t),
|
|
1216
|
+
readStdin: async () => {
|
|
1217
|
+
if (process.stdin.isTTY) return null;
|
|
1218
|
+
try {
|
|
1219
|
+
const st = fstatSync(0);
|
|
1220
|
+
if (!st.isFIFO() && !st.isFile()) return null;
|
|
1221
|
+
} catch {
|
|
1222
|
+
return null;
|
|
1223
|
+
}
|
|
1224
|
+
const chunks = [];
|
|
1225
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
1226
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
1227
|
+
},
|
|
1228
|
+
env: process.env,
|
|
1229
|
+
runCommand: spawnCommand
|
|
1230
|
+
};
|
|
1231
|
+
}
|
|
1232
|
+
var COMMANDS = /* @__PURE__ */ new Set(["send", "recall", "ask", "progress", "hb", "heartbeat", "run", "config", "help"]);
|
|
1233
|
+
async function runCli(argv, io = defaultIO()) {
|
|
1234
|
+
try {
|
|
1235
|
+
if (argv[0] === "--version" || argv[0] === "-v") {
|
|
1236
|
+
io.stdout(`${VERSION}
|
|
1237
|
+
`);
|
|
1238
|
+
return 0;
|
|
1239
|
+
}
|
|
1240
|
+
if (argv.length === 0) {
|
|
1241
|
+
const stdin = await io.readStdin();
|
|
1242
|
+
if (stdin === null) {
|
|
1243
|
+
io.stdout(`${HELP.main}
|
|
1244
|
+
`);
|
|
1245
|
+
return 0;
|
|
1246
|
+
}
|
|
1247
|
+
return await send([], io, stdin);
|
|
1248
|
+
}
|
|
1249
|
+
if (argv[0] === "--help" || argv[0] === "-h") {
|
|
1250
|
+
io.stdout(`${HELP.main}
|
|
1251
|
+
`);
|
|
1252
|
+
return 0;
|
|
1253
|
+
}
|
|
1254
|
+
const first = argv[0];
|
|
1255
|
+
const command = COMMANDS.has(first) ? first : "send";
|
|
1256
|
+
const rest = COMMANDS.has(first) ? argv.slice(1) : argv;
|
|
1257
|
+
switch (command) {
|
|
1258
|
+
case "help": {
|
|
1259
|
+
const topic = rest[0] === "heartbeat" ? "hb" : rest[0];
|
|
1260
|
+
io.stdout(`${topic && HELP[topic] || HELP.main}
|
|
1261
|
+
`);
|
|
1262
|
+
return 0;
|
|
1263
|
+
}
|
|
1264
|
+
case "send":
|
|
1265
|
+
return await send(rest, io);
|
|
1266
|
+
case "recall":
|
|
1267
|
+
return await recall(rest, io);
|
|
1268
|
+
case "ask":
|
|
1269
|
+
return await ask(rest, io);
|
|
1270
|
+
case "progress":
|
|
1271
|
+
return await progress(rest, io);
|
|
1272
|
+
case "hb":
|
|
1273
|
+
case "heartbeat":
|
|
1274
|
+
return await heartbeat(rest, io);
|
|
1275
|
+
case "run":
|
|
1276
|
+
return await run(rest, io);
|
|
1277
|
+
case "config":
|
|
1278
|
+
return await config(rest, io);
|
|
1279
|
+
}
|
|
1280
|
+
return 1;
|
|
1281
|
+
} catch (error) {
|
|
1282
|
+
if (error instanceof UsageError) {
|
|
1283
|
+
io.stderr(`opush: ${error.message}
|
|
1284
|
+
Run "opush --help" for usage.
|
|
1285
|
+
`);
|
|
1286
|
+
return 2;
|
|
1287
|
+
}
|
|
1288
|
+
if (error instanceof OpushError) {
|
|
1289
|
+
const status = error.status ? ` (HTTP ${error.status})` : "";
|
|
1290
|
+
io.stderr(`opush: ${error.message}${status}
|
|
1291
|
+
`);
|
|
1292
|
+
return 1;
|
|
1293
|
+
}
|
|
1294
|
+
io.stderr(`opush: ${error?.message ?? String(error)}
|
|
1295
|
+
`);
|
|
1296
|
+
return 1;
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
async function clientFrom(values, io, needsTarget = true) {
|
|
1300
|
+
const cfg = await readConfig(io.configPath ?? configPath(io.env));
|
|
1301
|
+
const env = io.env;
|
|
1302
|
+
let key = values.key;
|
|
1303
|
+
let channel = values.channel;
|
|
1304
|
+
if (!key && !channel) {
|
|
1305
|
+
if (env.OPUSH_KEY) key = env.OPUSH_KEY;
|
|
1306
|
+
else if (env.OPUSH_CHANNEL) channel = env.OPUSH_CHANNEL;
|
|
1307
|
+
else if (cfg.key) key = cfg.key;
|
|
1308
|
+
else if (cfg.channel) channel = cfg.channel;
|
|
1309
|
+
}
|
|
1310
|
+
if (needsTarget && !key && !channel) {
|
|
1311
|
+
throw new UsageError('No push key. Pass --key, set OPUSH_KEY, or run "opush config set key KEY".');
|
|
1312
|
+
}
|
|
1313
|
+
const targetIsUrl = key && isUrl(key) || channel && isUrl(channel);
|
|
1314
|
+
const server = values.server ?? env.OPUSH_SERVER ?? (targetIsUrl ? void 0 : cfg.server);
|
|
1315
|
+
const keys = key?.split(",").map((s) => s.trim()).filter(Boolean);
|
|
1316
|
+
const timeout = number("timeout", values.timeout, 1);
|
|
1317
|
+
const retries = number("retries", values.retries, 0, 10);
|
|
1318
|
+
return new Opush({
|
|
1319
|
+
...keys && keys.length > 1 ? { keys } : key ? { key } : channel ? { channel } : {},
|
|
1320
|
+
server,
|
|
1321
|
+
basicAuth: values["basic-auth"] ?? env.OPUSH_BASIC_AUTH ?? cfg.basicAuth,
|
|
1322
|
+
timeout: timeout === void 0 ? void 0 : timeout * 1e3,
|
|
1323
|
+
retries,
|
|
1324
|
+
fetch: io.fetch,
|
|
1325
|
+
env: false
|
|
1326
|
+
});
|
|
1327
|
+
}
|
|
1328
|
+
function printJson(io, value) {
|
|
1329
|
+
io.stdout(`${JSON.stringify(value, null, 2)}
|
|
1330
|
+
`);
|
|
1331
|
+
}
|
|
1332
|
+
function describePush(result) {
|
|
1333
|
+
const lines = [];
|
|
1334
|
+
if (result.results) {
|
|
1335
|
+
for (const r of result.results) {
|
|
1336
|
+
lines.push(`${r.deviceKey} ${r.code === 200 ? "sent" : `${r.code} ${r.message ?? ""}`.trim()}`);
|
|
1337
|
+
}
|
|
1338
|
+
} else if (result.schedule) {
|
|
1339
|
+
const repeat = result.schedule.repeat ? `, repeats ${result.schedule.repeat}` : "";
|
|
1340
|
+
lines.push(`Scheduled ${result.schedule.id} for ${result.schedule.fireAt}${repeat}.`);
|
|
1341
|
+
} else if (result.message.startsWith("queued")) {
|
|
1342
|
+
lines.push("Queued: the progress card is still starting on the device.");
|
|
1343
|
+
} else {
|
|
1344
|
+
const d = result.data;
|
|
1345
|
+
if (d && typeof d === "object" && typeof d.channel === "string") {
|
|
1346
|
+
lines.push(`Sent to ${d.sent ?? 0} of ${d.devices ?? 0} devices in channel ${d.channel}.`);
|
|
1347
|
+
} else {
|
|
1348
|
+
lines.push("Sent.");
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
if (result.escalation) {
|
|
1352
|
+
const e = result.escalation;
|
|
1353
|
+
lines.push(`Alert ${e.alertId}: ${e.steps.join(", ")} every ${e.everyMinutes} min until acknowledged.`);
|
|
1354
|
+
lines.push(`Status: ${e.statusUrl}`);
|
|
1355
|
+
if (e.callbackSecret) lines.push(`Callback secret: ${e.callbackSecret}`);
|
|
1356
|
+
}
|
|
1357
|
+
return `${lines.join("\n")}
|
|
1358
|
+
`;
|
|
1359
|
+
}
|
|
1360
|
+
async function send(argv, io, piped) {
|
|
1361
|
+
const { values, positionals } = parse(argv, PUSH_OPTIONS);
|
|
1362
|
+
if (values.help) {
|
|
1363
|
+
io.stdout(`${HELP.send}
|
|
1364
|
+
`);
|
|
1365
|
+
return 0;
|
|
1366
|
+
}
|
|
1367
|
+
if (positionals.length > 1) throw new UsageError(`Too many arguments: ${positionals.join(" ")}. Quote the body.`);
|
|
1368
|
+
const message = pushMessageFrom(values);
|
|
1369
|
+
let body = positionals[0];
|
|
1370
|
+
if (body !== void 0 && message.body !== void 0) throw new UsageError("Give the body either as an argument or with --body");
|
|
1371
|
+
if (body === "-" || body === void 0 && message.body === void 0 && message.markdown === void 0) {
|
|
1372
|
+
const text = piped ?? await io.readStdin();
|
|
1373
|
+
if (text !== null && text.trim() !== "") body = text.replace(/\s+$/, "");
|
|
1374
|
+
else if (body === "-") body = void 0;
|
|
1375
|
+
}
|
|
1376
|
+
if (body !== void 0) message.body = body;
|
|
1377
|
+
if (message.title === void 0 && message.body === void 0 && message.markdown === void 0 && !message.attachments) {
|
|
1378
|
+
throw new UsageError("Nothing to send. Give a body, --title or --file.");
|
|
1379
|
+
}
|
|
1380
|
+
const client = await clientFrom(values, io);
|
|
1381
|
+
const result = await client.push(message);
|
|
1382
|
+
if (values.json) printJson(io, result);
|
|
1383
|
+
else io.stdout(describePush(result));
|
|
1384
|
+
return 0;
|
|
1385
|
+
}
|
|
1386
|
+
async function recall(argv, io) {
|
|
1387
|
+
const { values, positionals } = parse(argv, {});
|
|
1388
|
+
if (values.help) {
|
|
1389
|
+
io.stdout(`${HELP.recall}
|
|
1390
|
+
`);
|
|
1391
|
+
return 0;
|
|
1392
|
+
}
|
|
1393
|
+
const id = positionals[0];
|
|
1394
|
+
if (!id || positionals.length > 1) throw new UsageError("Usage: opush recall ID");
|
|
1395
|
+
const result = await (await clientFrom(values, io)).recall(id);
|
|
1396
|
+
if (values.json) printJson(io, result);
|
|
1397
|
+
else io.stdout(`Recalled ${id}.
|
|
1398
|
+
`);
|
|
1399
|
+
return 0;
|
|
1400
|
+
}
|
|
1401
|
+
var ASK_OPTIONS = {
|
|
1402
|
+
option: { type: "string", short: "o", multiple: true },
|
|
1403
|
+
text: { type: "boolean" },
|
|
1404
|
+
placeholder: { type: "string" },
|
|
1405
|
+
body: { type: "string", short: "b" },
|
|
1406
|
+
expires: { type: "string" },
|
|
1407
|
+
"callback-url": { type: "string" },
|
|
1408
|
+
group: { type: "string", short: "g" },
|
|
1409
|
+
wait: { type: "boolean", short: "w" },
|
|
1410
|
+
"wait-timeout": { type: "string" }
|
|
1411
|
+
};
|
|
1412
|
+
var ASK_EXIT = { answered: 0, expired: 2, cancelled: 3, pending: 4 };
|
|
1413
|
+
function answerText(state) {
|
|
1414
|
+
const a = state.answer;
|
|
1415
|
+
if (!a) return "";
|
|
1416
|
+
if (a.option !== null && a.text) return `${a.option}
|
|
1417
|
+
${a.text}`;
|
|
1418
|
+
return a.option ?? a.text ?? "";
|
|
1419
|
+
}
|
|
1420
|
+
async function ask(argv, io) {
|
|
1421
|
+
const { values, positionals } = parse(argv, ASK_OPTIONS);
|
|
1422
|
+
if (values.help) {
|
|
1423
|
+
io.stdout(`${HELP.ask}
|
|
1424
|
+
`);
|
|
1425
|
+
return 0;
|
|
1426
|
+
}
|
|
1427
|
+
const title = positionals.join(" ").trim();
|
|
1428
|
+
if (!title) throw new UsageError('Usage: opush ask "QUESTION" --option A --option B [--wait]');
|
|
1429
|
+
const options = values.option ?? [];
|
|
1430
|
+
if (!options.length && !values.text) throw new UsageError("Give at least one --option, or --text");
|
|
1431
|
+
if (options.length > 4) throw new UsageError("At most 4 options");
|
|
1432
|
+
const client = await clientFrom(values, io);
|
|
1433
|
+
const question = await client.ask({
|
|
1434
|
+
title,
|
|
1435
|
+
body: values.body,
|
|
1436
|
+
options: options.length ? options : void 0,
|
|
1437
|
+
allowText: values.text ? true : void 0,
|
|
1438
|
+
placeholder: values.placeholder,
|
|
1439
|
+
timeout: number("expires", values.expires, 60, 604800),
|
|
1440
|
+
callbackUrl: values["callback-url"],
|
|
1441
|
+
group: values.group
|
|
1442
|
+
});
|
|
1443
|
+
if (!values.wait) {
|
|
1444
|
+
if (values.json) {
|
|
1445
|
+
printJson(io, {
|
|
1446
|
+
question_id: question.id,
|
|
1447
|
+
answer_url: question.answerUrl,
|
|
1448
|
+
expires_at: question.expiresAt,
|
|
1449
|
+
...question.callbackSecret ? { callback_secret: question.callbackSecret } : {}
|
|
1450
|
+
});
|
|
1451
|
+
} else {
|
|
1452
|
+
io.stdout(`${question.id}
|
|
1453
|
+
`);
|
|
1454
|
+
if (question.callbackSecret) io.stderr(`Callback secret: ${question.callbackSecret}
|
|
1455
|
+
`);
|
|
1456
|
+
}
|
|
1457
|
+
return 0;
|
|
1458
|
+
}
|
|
1459
|
+
const waitSeconds = number("wait-timeout", values["wait-timeout"], 0);
|
|
1460
|
+
const state = await question.wait(waitSeconds === void 0 ? {} : { timeout: waitSeconds * 1e3 });
|
|
1461
|
+
if (values.json) printJson(io, state);
|
|
1462
|
+
else if (state.status === "answered") io.stdout(`${answerText(state)}
|
|
1463
|
+
`);
|
|
1464
|
+
else io.stderr(`opush: question ${state.status === "pending" ? "not answered in time" : state.status}
|
|
1465
|
+
`);
|
|
1466
|
+
return ASK_EXIT[state.status] ?? 1;
|
|
1467
|
+
}
|
|
1468
|
+
var PROGRESS_OPTIONS = {
|
|
1469
|
+
id: { type: "string" },
|
|
1470
|
+
title: { type: "string", short: "t" },
|
|
1471
|
+
status: { type: "string" },
|
|
1472
|
+
progress: { type: "string", short: "p" },
|
|
1473
|
+
state: { type: "string" },
|
|
1474
|
+
alert: { type: "boolean" }
|
|
1475
|
+
};
|
|
1476
|
+
async function progress(argv, io) {
|
|
1477
|
+
const { values, positionals } = parse(argv, PROGRESS_OPTIONS);
|
|
1478
|
+
const action = positionals[0];
|
|
1479
|
+
if (values.help || !action) {
|
|
1480
|
+
io.stdout(`${HELP.progress}
|
|
1481
|
+
`);
|
|
1482
|
+
return values.help ? 0 : 2;
|
|
1483
|
+
}
|
|
1484
|
+
if (action !== "start" && action !== "update" && action !== "end") {
|
|
1485
|
+
throw new UsageError(`progress needs start, update or end, got "${action}"`);
|
|
1486
|
+
}
|
|
1487
|
+
if (!values.id) throw new UsageError("progress needs --id");
|
|
1488
|
+
const pct = number("progress", values.progress, 0, 100);
|
|
1489
|
+
const states = action === "end" ? ["success", "failed"] : ["running", "success", "failed"];
|
|
1490
|
+
if (values.state !== void 0 && !states.includes(values.state)) {
|
|
1491
|
+
throw new UsageError(`--state must be one of ${states.join(", ")}`);
|
|
1492
|
+
}
|
|
1493
|
+
if (action === "start" && values.state !== void 0) throw new UsageError("--state can't be used with start");
|
|
1494
|
+
const client = await clientFrom(values, io);
|
|
1495
|
+
let result;
|
|
1496
|
+
if (action === "start") {
|
|
1497
|
+
if (!values.title) throw new UsageError("progress start needs --title");
|
|
1498
|
+
if (values.alert) throw new UsageError("--alert isn't needed with start: starting a card always alerts");
|
|
1499
|
+
result = await client.progress.start({ id: values.id, title: values.title, status: values.status, progress: pct });
|
|
1500
|
+
} else if (action === "update") {
|
|
1501
|
+
result = await client.progress.update({
|
|
1502
|
+
id: values.id,
|
|
1503
|
+
title: values.title,
|
|
1504
|
+
status: values.status,
|
|
1505
|
+
progress: pct,
|
|
1506
|
+
state: values.state,
|
|
1507
|
+
alert: values.alert
|
|
1508
|
+
});
|
|
1509
|
+
} else {
|
|
1510
|
+
result = await client.progress.end({
|
|
1511
|
+
id: values.id,
|
|
1512
|
+
title: values.title,
|
|
1513
|
+
status: values.status,
|
|
1514
|
+
progress: pct,
|
|
1515
|
+
state: values.state,
|
|
1516
|
+
alert: values.alert
|
|
1517
|
+
});
|
|
1518
|
+
}
|
|
1519
|
+
if (values.json) printJson(io, result);
|
|
1520
|
+
else io.stdout(describePush(result));
|
|
1521
|
+
return 0;
|
|
1522
|
+
}
|
|
1523
|
+
async function heartbeat(argv, io) {
|
|
1524
|
+
const { values, positionals } = parse(argv, { fail: { type: "boolean" }, start: { type: "boolean" } });
|
|
1525
|
+
if (values.help) {
|
|
1526
|
+
io.stdout(`${HELP.hb}
|
|
1527
|
+
`);
|
|
1528
|
+
return 0;
|
|
1529
|
+
}
|
|
1530
|
+
const [check, ...words] = positionals;
|
|
1531
|
+
if (!check) throw new UsageError("Usage: opush hb CHECK_ID [MESSAGE] [--fail|--start]");
|
|
1532
|
+
if (values.fail && values.start) throw new UsageError("Use either --fail or --start");
|
|
1533
|
+
let message = words.length ? words.join(" ") : void 0;
|
|
1534
|
+
if (message === "-") message = await io.readStdin() ?? void 0;
|
|
1535
|
+
if (values.start && message !== void 0) throw new UsageError("--start doesn't take a message");
|
|
1536
|
+
const client = await clientFrom(values, io, false);
|
|
1537
|
+
const hb = client.heartbeat(check);
|
|
1538
|
+
if (values.start) await hb.start();
|
|
1539
|
+
else if (values.fail) await hb.fail(message);
|
|
1540
|
+
else await hb.ok(message);
|
|
1541
|
+
if (values.json) printJson(io, { ok: true });
|
|
1542
|
+
else io.stdout(values.start ? "Started.\n" : values.fail ? "Failure reported.\n" : "Checked in.\n");
|
|
1543
|
+
return 0;
|
|
1544
|
+
}
|
|
1545
|
+
var RUN_OPTIONS = {
|
|
1546
|
+
...PUSH_OPTIONS,
|
|
1547
|
+
lines: { type: "string", short: "n" },
|
|
1548
|
+
"failure-only": { type: "boolean" }
|
|
1549
|
+
};
|
|
1550
|
+
function formatDuration(ms) {
|
|
1551
|
+
if (ms < 1e3) return `${Math.round(ms)}ms`;
|
|
1552
|
+
const s = Math.round(ms / 1e3);
|
|
1553
|
+
if (s < 60) return `${s}s`;
|
|
1554
|
+
const m = Math.floor(s / 60);
|
|
1555
|
+
if (m < 60) return `${m}m ${s % 60}s`;
|
|
1556
|
+
return `${Math.floor(m / 60)}h ${m % 60}m`;
|
|
1557
|
+
}
|
|
1558
|
+
var TailBuffer = class {
|
|
1559
|
+
constructor(max) {
|
|
1560
|
+
this.max = max;
|
|
1561
|
+
}
|
|
1562
|
+
max;
|
|
1563
|
+
#partial = "";
|
|
1564
|
+
#lines = [];
|
|
1565
|
+
push(chunk) {
|
|
1566
|
+
const text = (this.#partial + chunk).replace(/\u001b\[[0-9;?]*[A-Za-z]/g, "").replace(/\r(?!\n)/g, "\n");
|
|
1567
|
+
const parts = text.split(/\r?\n/);
|
|
1568
|
+
this.#partial = parts.pop() ?? "";
|
|
1569
|
+
for (const line of parts) this.#add(line);
|
|
1570
|
+
}
|
|
1571
|
+
#add(line) {
|
|
1572
|
+
if (!line.trim() || this.max <= 0) return;
|
|
1573
|
+
this.#lines.push(line.length > 200 ? `${line.slice(0, 199)}\u2026` : line);
|
|
1574
|
+
if (this.#lines.length > this.max) this.#lines.shift();
|
|
1575
|
+
}
|
|
1576
|
+
lines() {
|
|
1577
|
+
if (this.#partial) {
|
|
1578
|
+
this.#add(this.#partial);
|
|
1579
|
+
this.#partial = "";
|
|
1580
|
+
}
|
|
1581
|
+
const out = [...this.#lines];
|
|
1582
|
+
while (out.join("\n").length > 1500 && out.length > 1) out.shift();
|
|
1583
|
+
return out;
|
|
1584
|
+
}
|
|
1585
|
+
};
|
|
1586
|
+
async function run(argv, io) {
|
|
1587
|
+
const dash = argv.indexOf("--");
|
|
1588
|
+
const own = dash >= 0 ? argv.slice(0, dash) : argv;
|
|
1589
|
+
const { values, positionals } = parse(own, RUN_OPTIONS);
|
|
1590
|
+
if (values.help) {
|
|
1591
|
+
io.stdout(`${HELP.run}
|
|
1592
|
+
`);
|
|
1593
|
+
return 0;
|
|
1594
|
+
}
|
|
1595
|
+
const commandLine = dash >= 0 ? argv.slice(dash + 1) : positionals;
|
|
1596
|
+
if (dash >= 0 && positionals.length) throw new UsageError(`Unexpected arguments before "--": ${positionals.join(" ")}`);
|
|
1597
|
+
if (!commandLine.length) throw new UsageError("Usage: opush run [options] -- COMMAND [ARGS...]");
|
|
1598
|
+
const lines = number("lines", values.lines, 0, 50) ?? 10;
|
|
1599
|
+
const base = pushMessageFrom(values);
|
|
1600
|
+
const client = await clientFrom(values, io);
|
|
1601
|
+
const runner = io.runCommand ?? spawnCommand;
|
|
1602
|
+
const tail = new TailBuffer(lines);
|
|
1603
|
+
const started = Date.now();
|
|
1604
|
+
const [command, ...args] = commandLine;
|
|
1605
|
+
let code;
|
|
1606
|
+
try {
|
|
1607
|
+
code = await runner(command, args, (chunk, stream) => {
|
|
1608
|
+
if (stream === "stdout") io.stdout(chunk);
|
|
1609
|
+
else io.stderr(chunk);
|
|
1610
|
+
tail.push(chunk);
|
|
1611
|
+
});
|
|
1612
|
+
} catch (error) {
|
|
1613
|
+
io.stderr(`opush: could not run ${command}: ${error.message}
|
|
1614
|
+
`);
|
|
1615
|
+
code = 127;
|
|
1616
|
+
}
|
|
1617
|
+
const duration = formatDuration(Date.now() - started);
|
|
1618
|
+
const ok = code === 0;
|
|
1619
|
+
if (ok && values["failure-only"]) return code;
|
|
1620
|
+
const status = ok ? `Succeeded in ${duration}` : `Failed with exit code ${code} after ${duration}`;
|
|
1621
|
+
const output = tail.lines();
|
|
1622
|
+
const message = {
|
|
1623
|
+
...base,
|
|
1624
|
+
title: base.title ?? commandLine.join(" ").slice(0, 100),
|
|
1625
|
+
body: base.body ?? [status, ...output.length ? ["", ...output] : []].join("\n")
|
|
1626
|
+
};
|
|
1627
|
+
if (!ok && base.level === void 0) message.level = "timeSensitive";
|
|
1628
|
+
try {
|
|
1629
|
+
const result = await client.push(message);
|
|
1630
|
+
if (values.json) printJson(io, result);
|
|
1631
|
+
} catch (error) {
|
|
1632
|
+
io.stderr(`opush: the push failed: ${error.message}
|
|
1633
|
+
`);
|
|
1634
|
+
}
|
|
1635
|
+
return code;
|
|
1636
|
+
}
|
|
1637
|
+
function spawnCommand(command, args, onOutput) {
|
|
1638
|
+
return new Promise((resolve, reject) => {
|
|
1639
|
+
const useShell = args.length === 0 && /\s/.test(command);
|
|
1640
|
+
const child = nodeSpawn(command, args, { stdio: ["inherit", "pipe", "pipe"], shell: useShell });
|
|
1641
|
+
child.stdout?.setEncoding("utf8").on("data", (d) => onOutput(d, "stdout"));
|
|
1642
|
+
child.stderr?.setEncoding("utf8").on("data", (d) => onOutput(d, "stderr"));
|
|
1643
|
+
const forward = (signal) => () => child.kill(signal);
|
|
1644
|
+
const onInt = forward("SIGINT");
|
|
1645
|
+
const onTerm = forward("SIGTERM");
|
|
1646
|
+
process.on("SIGINT", onInt);
|
|
1647
|
+
process.on("SIGTERM", onTerm);
|
|
1648
|
+
const cleanup = () => {
|
|
1649
|
+
process.off("SIGINT", onInt);
|
|
1650
|
+
process.off("SIGTERM", onTerm);
|
|
1651
|
+
};
|
|
1652
|
+
child.on("error", (error) => {
|
|
1653
|
+
cleanup();
|
|
1654
|
+
reject(error);
|
|
1655
|
+
});
|
|
1656
|
+
child.on("close", (code, signal) => {
|
|
1657
|
+
cleanup();
|
|
1658
|
+
if (code !== null) resolve(code);
|
|
1659
|
+
else resolve(128 + (signal ? signalNumber(signal) : 1));
|
|
1660
|
+
});
|
|
1661
|
+
});
|
|
1662
|
+
}
|
|
1663
|
+
function signalNumber(signal) {
|
|
1664
|
+
const table = { SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGKILL: 9, SIGTERM: 15 };
|
|
1665
|
+
return table[signal] ?? 1;
|
|
1666
|
+
}
|
|
1667
|
+
async function config(argv, io) {
|
|
1668
|
+
const { values, positionals } = parse(argv, {});
|
|
1669
|
+
const [action, rawName, ...rest] = positionals;
|
|
1670
|
+
if (values.help || !action) {
|
|
1671
|
+
io.stdout(`${HELP.config}
|
|
1672
|
+
`);
|
|
1673
|
+
return values.help ? 0 : 2;
|
|
1674
|
+
}
|
|
1675
|
+
const path = io.configPath ?? configPath(io.env);
|
|
1676
|
+
if (action === "path") {
|
|
1677
|
+
io.stdout(`${path}
|
|
1678
|
+
`);
|
|
1679
|
+
return 0;
|
|
1680
|
+
}
|
|
1681
|
+
const cfg = await readConfig(path);
|
|
1682
|
+
const name = rawName === void 0 ? void 0 : CONFIG_NAMES[rawName.toLowerCase()];
|
|
1683
|
+
if (rawName !== void 0 && !name) {
|
|
1684
|
+
throw new UsageError(`Unknown setting "${rawName}". Use key, server, channel or basic-auth.`);
|
|
1685
|
+
}
|
|
1686
|
+
switch (action) {
|
|
1687
|
+
case "set": {
|
|
1688
|
+
const value = rest.join(" ").trim();
|
|
1689
|
+
if (!name || !value) throw new UsageError("Usage: opush config set NAME VALUE");
|
|
1690
|
+
if (name === "server" && !isUrl(value)) throw new UsageError("server must start with http:// or https://");
|
|
1691
|
+
cfg[name] = value;
|
|
1692
|
+
await writeConfig(cfg, path);
|
|
1693
|
+
io.stdout(`Saved ${rawName} to ${path}
|
|
1694
|
+
`);
|
|
1695
|
+
return 0;
|
|
1696
|
+
}
|
|
1697
|
+
case "get": {
|
|
1698
|
+
if (name) {
|
|
1699
|
+
const value = cfg[name];
|
|
1700
|
+
if (value === void 0) return 1;
|
|
1701
|
+
io.stdout(`${value}
|
|
1702
|
+
`);
|
|
1703
|
+
} else if (values.json) {
|
|
1704
|
+
printJson(io, cfg);
|
|
1705
|
+
} else {
|
|
1706
|
+
for (const [k, v] of Object.entries(cfg)) {
|
|
1707
|
+
const label = k === "basicAuth" ? "basic-auth" : k;
|
|
1708
|
+
io.stdout(`${label}=${v}
|
|
1709
|
+
`);
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
return 0;
|
|
1713
|
+
}
|
|
1714
|
+
case "unset": {
|
|
1715
|
+
if (!name) throw new UsageError("Usage: opush config unset NAME");
|
|
1716
|
+
delete cfg[name];
|
|
1717
|
+
await writeConfig(cfg, path);
|
|
1718
|
+
io.stdout(`Removed ${rawName}
|
|
1719
|
+
`);
|
|
1720
|
+
return 0;
|
|
1721
|
+
}
|
|
1722
|
+
default:
|
|
1723
|
+
throw new UsageError(`config needs set, get, unset or path, got "${action}"`);
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
// src/cli/main.ts
|
|
1728
|
+
runCli(process.argv.slice(2)).then(
|
|
1729
|
+
(code) => {
|
|
1730
|
+
process.exitCode = code;
|
|
1731
|
+
},
|
|
1732
|
+
(error) => {
|
|
1733
|
+
process.stderr.write(`opush: ${error?.message ?? String(error)}
|
|
1734
|
+
`);
|
|
1735
|
+
process.exitCode = 1;
|
|
1736
|
+
}
|
|
1737
|
+
);
|