oneie 5.7.6 → 5.8.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.
Files changed (245) hide show
  1. package/README.md +19 -1
  2. package/dist/package.json +7 -8
  3. package/dist/src/age-yefbe8pe.js +1 -0
  4. package/dist/src/evm-tx-ee2q0e3w.js +1 -0
  5. package/dist/src/hl-run-tgrkrk69.js +1 -0
  6. package/dist/src/index-0rj9wdk9.js +4 -0
  7. package/dist/src/index-91y484c2.js +2052 -0
  8. package/dist/src/index-940y3rnv.js +12 -0
  9. package/dist/src/index.js +1047 -121
  10. package/dist/src/message-key-db1xjdkw.js +1 -0
  11. package/dist/src/message-lock-5vr8079x.js +5 -0
  12. package/dist/src/sweep-order-c2p6rk8c.js +1 -0
  13. package/dist/src/sweep-runner-t68xe7vx.js +1 -0
  14. package/package.json +7 -8
  15. package/dist/src/agent.d.ts +0 -75
  16. package/dist/src/agent.js +0 -1334
  17. package/dist/src/agentverse.d.ts +0 -26
  18. package/dist/src/agentverse.js +0 -171
  19. package/dist/src/args.d.ts +0 -9
  20. package/dist/src/args.js +0 -61
  21. package/dist/src/auth.d.ts +0 -6
  22. package/dist/src/auth.js +0 -121
  23. package/dist/src/balances.d.ts +0 -89
  24. package/dist/src/balances.js +0 -202
  25. package/dist/src/banner.d.ts +0 -1
  26. package/dist/src/banner.js +0 -17
  27. package/dist/src/broadcast.d.ts +0 -8
  28. package/dist/src/broadcast.js +0 -175
  29. package/dist/src/catalog.d.ts +0 -12
  30. package/dist/src/catalog.js +0 -76
  31. package/dist/src/chat.d.ts +0 -2
  32. package/dist/src/chat.js +0 -92
  33. package/dist/src/client.d.ts +0 -5
  34. package/dist/src/client.js +0 -157
  35. package/dist/src/compiler.d.ts +0 -36
  36. package/dist/src/compiler.js +0 -366
  37. package/dist/src/config.d.ts +0 -24
  38. package/dist/src/config.js +0 -70
  39. package/dist/src/connect.d.ts +0 -2
  40. package/dist/src/connect.js +0 -64
  41. package/dist/src/coordinate.d.ts +0 -3
  42. package/dist/src/coordinate.js +0 -58
  43. package/dist/src/create.d.ts +0 -2
  44. package/dist/src/create.js +0 -113
  45. package/dist/src/deploy.d.ts +0 -2
  46. package/dist/src/deploy.js +0 -19
  47. package/dist/src/dev.d.ts +0 -2
  48. package/dist/src/dev.js +0 -75
  49. package/dist/src/device-flow.d.ts +0 -57
  50. package/dist/src/device-flow.js +0 -173
  51. package/dist/src/doctor.d.ts +0 -26
  52. package/dist/src/doctor.js +0 -146
  53. package/dist/src/draw.d.ts +0 -18
  54. package/dist/src/draw.js +0 -156
  55. package/dist/src/endpoint.d.ts +0 -2
  56. package/dist/src/endpoint.js +0 -250
  57. package/dist/src/env.d.ts +0 -3
  58. package/dist/src/env.js +0 -37
  59. package/dist/src/eval.d.ts +0 -2
  60. package/dist/src/eval.js +0 -43
  61. package/dist/src/fn.d.ts +0 -2
  62. package/dist/src/fn.js +0 -70
  63. package/dist/src/group.d.ts +0 -2
  64. package/dist/src/group.js +0 -117
  65. package/dist/src/hl-run.d.ts +0 -119
  66. package/dist/src/hl-run.js +0 -480
  67. package/dist/src/hl.d.ts +0 -17
  68. package/dist/src/hl.js +0 -148
  69. package/dist/src/index.d.ts +0 -2
  70. package/dist/src/init.d.ts +0 -76
  71. package/dist/src/init.js +0 -278
  72. package/dist/src/join.d.ts +0 -11
  73. package/dist/src/join.js +0 -293
  74. package/dist/src/key-publish.d.ts +0 -40
  75. package/dist/src/key-publish.js +0 -232
  76. package/dist/src/key-seal.d.ts +0 -21
  77. package/dist/src/key-seal.js +0 -142
  78. package/dist/src/key-sweep.d.ts +0 -93
  79. package/dist/src/key-sweep.js +0 -263
  80. package/dist/src/key.d.ts +0 -26
  81. package/dist/src/key.js +0 -338
  82. package/dist/src/lib/age-plugin.d.ts +0 -51
  83. package/dist/src/lib/age-plugin.js +0 -130
  84. package/dist/src/lib/agent-env.d.ts +0 -12
  85. package/dist/src/lib/agent-env.js +0 -48
  86. package/dist/src/lib/api-path.d.ts +0 -2
  87. package/dist/src/lib/api-path.js +0 -40
  88. package/dist/src/lib/asker.d.ts +0 -34
  89. package/dist/src/lib/asker.js +0 -126
  90. package/dist/src/lib/client.d.ts +0 -20
  91. package/dist/src/lib/client.js +0 -71
  92. package/dist/src/lib/env-sealed.d.ts +0 -53
  93. package/dist/src/lib/env-sealed.js +0 -184
  94. package/dist/src/lib/flow-tag.d.ts +0 -86
  95. package/dist/src/lib/flow-tag.js +0 -230
  96. package/dist/src/lib/hl-core/actions.d.ts +0 -99
  97. package/dist/src/lib/hl-core/actions.js +0 -69
  98. package/dist/src/lib/hl-core/eip712.d.ts +0 -33
  99. package/dist/src/lib/hl-core/eip712.js +0 -107
  100. package/dist/src/lib/hl-core/errors.d.ts +0 -10
  101. package/dist/src/lib/hl-core/errors.js +0 -15
  102. package/dist/src/lib/hl-core/exchange.d.ts +0 -24
  103. package/dist/src/lib/hl-core/exchange.js +0 -47
  104. package/dist/src/lib/hl-core/index.d.ts +0 -13
  105. package/dist/src/lib/hl-core/index.js +0 -14
  106. package/dist/src/lib/hl-core/meta.d.ts +0 -57
  107. package/dist/src/lib/hl-core/meta.js +0 -110
  108. package/dist/src/lib/hl-core/msgpack.d.ts +0 -18
  109. package/dist/src/lib/hl-core/msgpack.js +0 -136
  110. package/dist/src/lib/hl-core/net.d.ts +0 -2
  111. package/dist/src/lib/hl-core/net.js +0 -7
  112. package/dist/src/lib/hl-core/signing.d.ts +0 -103
  113. package/dist/src/lib/hl-core/signing.js +0 -295
  114. package/dist/src/lib/hl-core/wire.d.ts +0 -34
  115. package/dist/src/lib/hl-core/wire.js +0 -81
  116. package/dist/src/lib/invoked-as.d.ts +0 -2
  117. package/dist/src/lib/invoked-as.js +0 -24
  118. package/dist/src/lib/journey-words.d.ts +0 -84
  119. package/dist/src/lib/journey-words.js +0 -360
  120. package/dist/src/lib/journey.d.ts +0 -148
  121. package/dist/src/lib/journey.js +0 -245
  122. package/dist/src/lib/key-receipt.d.ts +0 -48
  123. package/dist/src/lib/key-receipt.js +0 -116
  124. package/dist/src/lib/key-source.d.ts +0 -9
  125. package/dist/src/lib/key-source.js +0 -33
  126. package/dist/src/lib/keyfile.d.ts +0 -136
  127. package/dist/src/lib/keyfile.js +0 -397
  128. package/dist/src/lib/launch-claude.d.ts +0 -5
  129. package/dist/src/lib/launch-claude.js +0 -45
  130. package/dist/src/lib/lock-lookup.d.ts +0 -40
  131. package/dist/src/lib/lock-lookup.js +0 -92
  132. package/dist/src/lib/message-seal.d.ts +0 -63
  133. package/dist/src/lib/message-seal.js +0 -150
  134. package/dist/src/lib/network.d.ts +0 -15
  135. package/dist/src/lib/network.js +0 -41
  136. package/dist/src/lib/paths.d.ts +0 -41
  137. package/dist/src/lib/paths.js +0 -91
  138. package/dist/src/lib/plan-draw.d.ts +0 -56
  139. package/dist/src/lib/plan-draw.js +0 -219
  140. package/dist/src/lib/plan-live.d.ts +0 -20
  141. package/dist/src/lib/plan-live.js +0 -192
  142. package/dist/src/lib/qr.d.ts +0 -21
  143. package/dist/src/lib/qr.js +0 -402
  144. package/dist/src/lib/roster.d.ts +0 -20
  145. package/dist/src/lib/roster.js +0 -79
  146. package/dist/src/lib/sale-card.d.ts +0 -117
  147. package/dist/src/lib/sale-card.js +0 -261
  148. package/dist/src/lib/shop-init.d.ts +0 -62
  149. package/dist/src/lib/shop-init.js +0 -63
  150. package/dist/src/lib/sui-grpc-send.d.ts +0 -50
  151. package/dist/src/lib/sui-grpc-send.js +0 -89
  152. package/dist/src/lib/swap-core.d.ts +0 -163
  153. package/dist/src/lib/swap-core.js +0 -405
  154. package/dist/src/lib/tasks-digest.d.ts +0 -66
  155. package/dist/src/lib/tasks-digest.js +0 -200
  156. package/dist/src/lib/tasks-graph.d.ts +0 -79
  157. package/dist/src/lib/tasks-graph.js +0 -463
  158. package/dist/src/lib/tasks-lens.d.ts +0 -31
  159. package/dist/src/lib/tasks-lens.js +0 -47
  160. package/dist/src/lib/tasks-next.d.ts +0 -25
  161. package/dist/src/lib/tasks-next.js +0 -103
  162. package/dist/src/lib/tasks-prove.d.ts +0 -15
  163. package/dist/src/lib/tasks-prove.js +0 -68
  164. package/dist/src/lib/tasks-route.d.ts +0 -29
  165. package/dist/src/lib/tasks-route.js +0 -151
  166. package/dist/src/lib/tasks-score.d.ts +0 -36
  167. package/dist/src/lib/tasks-score.js +0 -152
  168. package/dist/src/lib/tasks-workspace.d.ts +0 -18
  169. package/dist/src/lib/tasks-workspace.js +0 -73
  170. package/dist/src/lib/vault-read.d.ts +0 -24
  171. package/dist/src/lib/vault-read.js +0 -77
  172. package/dist/src/lib/vaultfile.d.ts +0 -88
  173. package/dist/src/lib/vaultfile.js +0 -222
  174. package/dist/src/lib/wallet-money.d.ts +0 -222
  175. package/dist/src/lib/wallet-money.js +0 -578
  176. package/dist/src/lib/wallet-request.d.ts +0 -50
  177. package/dist/src/lib/wallet-request.js +0 -86
  178. package/dist/src/links.d.ts +0 -5
  179. package/dist/src/links.js +0 -45
  180. package/dist/src/media.d.ts +0 -29
  181. package/dist/src/media.js +0 -487
  182. package/dist/src/message-receipt.d.ts +0 -25
  183. package/dist/src/message-receipt.js +0 -71
  184. package/dist/src/message.d.ts +0 -13
  185. package/dist/src/message.js +0 -92
  186. package/dist/src/onboard.d.ts +0 -16
  187. package/dist/src/onboard.js +0 -149
  188. package/dist/src/plugin.d.ts +0 -2
  189. package/dist/src/plugin.js +0 -193
  190. package/dist/src/push.d.ts +0 -2
  191. package/dist/src/push.js +0 -115
  192. package/dist/src/render.d.ts +0 -21
  193. package/dist/src/render.js +0 -32
  194. package/dist/src/secrets-device.d.ts +0 -32
  195. package/dist/src/secrets-device.js +0 -127
  196. package/dist/src/secrets-give.d.ts +0 -125
  197. package/dist/src/secrets-give.js +0 -236
  198. package/dist/src/secrets-list.d.ts +0 -27
  199. package/dist/src/secrets-list.js +0 -84
  200. package/dist/src/secrets-run.d.ts +0 -31
  201. package/dist/src/secrets-run.js +0 -182
  202. package/dist/src/secrets.d.ts +0 -33
  203. package/dist/src/secrets.js +0 -200
  204. package/dist/src/setup.d.ts +0 -6
  205. package/dist/src/setup.js +0 -127
  206. package/dist/src/ship.d.ts +0 -2
  207. package/dist/src/ship.js +0 -18
  208. package/dist/src/shop.d.ts +0 -10
  209. package/dist/src/shop.js +0 -110
  210. package/dist/src/skill-parser.d.ts +0 -14
  211. package/dist/src/skill-parser.js +0 -113
  212. package/dist/src/skill.d.ts +0 -2
  213. package/dist/src/skill.js +0 -493
  214. package/dist/src/slug.d.ts +0 -2
  215. package/dist/src/slug.js +0 -6
  216. package/dist/src/social.d.ts +0 -2
  217. package/dist/src/social.js +0 -106
  218. package/dist/src/staff.d.ts +0 -2
  219. package/dist/src/staff.js +0 -104
  220. package/dist/src/start.d.ts +0 -15
  221. package/dist/src/start.js +0 -203
  222. package/dist/src/status.d.ts +0 -2
  223. package/dist/src/status.js +0 -52
  224. package/dist/src/substrate.d.ts +0 -2
  225. package/dist/src/substrate.js +0 -258
  226. package/dist/src/swap.d.ts +0 -93
  227. package/dist/src/swap.js +0 -622
  228. package/dist/src/tasks.d.ts +0 -2
  229. package/dist/src/tasks.js +0 -743
  230. package/dist/src/templates.d.ts +0 -1
  231. package/dist/src/templates.js +0 -213
  232. package/dist/src/trade.d.ts +0 -2
  233. package/dist/src/trade.js +0 -91
  234. package/dist/src/trail.d.ts +0 -2
  235. package/dist/src/trail.js +0 -41
  236. package/dist/src/validate.d.ts +0 -13
  237. package/dist/src/validate.js +0 -35
  238. package/dist/src/wallet-money.d.ts +0 -152
  239. package/dist/src/wallet-money.js +0 -564
  240. package/dist/src/wallet.d.ts +0 -167
  241. package/dist/src/wallet.js +0 -855
  242. package/dist/src/workflow.d.ts +0 -2
  243. package/dist/src/workflow.js +0 -166
  244. package/dist/src/write.d.ts +0 -43
  245. package/dist/src/write.js +0 -180
@@ -1,86 +0,0 @@
1
- /**
2
- * wallet-request.ts — the agent's half of "an agent asks, the owner's fingerprint decides".
3
- *
4
- * The agent builds a SENTENCE the owner's own chat already understands and wraps it in a link:
5
- * `https://one.ie/chat#money=<sentence>`. Opening it types the sentence as the owner's line and
6
- * shows the send card they sign with Touch ID. Nothing here signs, holds or opens a key; it only
7
- * names the agent's own PUBLIC receiving address.
8
- *
9
- * The grammar is MIRRORED from one.ie/web/src/lib/chat/money-intent.ts (SEND, amountOk,
10
- * chainsFor, moneyLink) — copied, never imported: the CLI ships alone. If the web's send pattern
11
- * moves, tests/wallet-request.test.ts is the place that says so.
12
- */
13
- import { SUI } from './wallet-money.js';
14
- const WORD = { ethereum: 'ethereum', eth: 'ethereum', base: 'base', sui: 'sui' };
15
- /** `USDC` · `SUI` · `ETH@base` · `USDC@ethereum` — anything the web grammar would not read is refused by name. */
16
- export function parseRequestAsset(word) {
17
- const [a = '', c] = word.trim().split('@');
18
- const asset = a.toUpperCase();
19
- if (asset !== 'ETH' && asset !== 'USDC' && asset !== 'SUI') {
20
- return { ok: false, error: 'unsupported_asset', message: `Ask for USDC or SUI on Sui, or ETH or USDC on Ethereum or Base — not "${word}".` };
21
- }
22
- if (c === undefined) {
23
- if (asset === 'ETH')
24
- return { ok: false, error: 'chain_needed', message: 'ETH lives on Ethereum and Base — say which: ETH@ethereum or ETH@base.' };
25
- return { ok: true, asset, chain: 'sui', defaulted: asset === 'USDC' };
26
- }
27
- const chain = WORD[c.toLowerCase()];
28
- if (!chain)
29
- return { ok: false, error: 'unsupported_chain', message: `"${c}" is not a chain a request link can name — ethereum, base or sui.` };
30
- if (asset === 'ETH' && chain === 'sui')
31
- return { ok: false, error: 'asset_not_on_chain', message: 'ETH does not live on Sui.' };
32
- if (asset === 'SUI' && chain !== 'sui')
33
- return { ok: false, error: 'asset_not_on_chain', message: `SUI lives on Sui, not ${chain}.` };
34
- return { ok: true, asset, chain, defaulted: false };
35
- }
36
- /** The web's amountOk: a positive plain decimal, at most 18 places. */
37
- export const amountOk = (a) => /^(?:\d+(?:\.\d{1,18})?|\.\d{1,18})$/.test(a) && Number.parseFloat(a) > 0;
38
- /** `send 20 USDC on sui to 0x…` — the chain is always said, so the card never has to ask which. */
39
- export const sentenceFor = (amount, asset, chain, to) => `send ${amount} ${asset} on ${chain} to ${to}`;
40
- /** The web's moneyLink: the sentence is capped at 200 characters. */
41
- export const linkFor = (sentence, origin = 'https://one.ie') => `${origin.replace(/\/$/, '')}/chat#money=${encodeURIComponent(sentence.trim().slice(0, 200))}`;
42
- // The web's SEND pattern (money-intent.ts), verbatim.
43
- const LEAD = "(?:(?:please|pls|ok|okay)\\s+)?(?:(?:can|could|will|would)\\s+you\\s+)?(?:(?:i\\s+(?:want|need)\\s+to|i'?d\\s+like\\s+to|let'?s|lets)\\s+)?";
44
- const END = '[\\s.!]*$';
45
- const AMOUNT = '(\\d+(?:\\.\\d+)?|\\.\\d+)';
46
- const SEND = new RegExp(`^${LEAD}(?:send|pay|transfer)\\s+${AMOUNT}\\s*(eth|usdc|sui)(?:\\s*(?:on\\s+|@)(ethereum|eth|mainnet|base|sui))?\\s+to\\s+(\\S+)(?:\\s+on\\s+(ethereum|eth|mainnet|base|sui))?${END}`, 'i');
47
- /** What the web's `matchMoneyIntent` would make of this sentence, as far as a send goes — or null. */
48
- export function matchSend(text) {
49
- const line = text.trim().replace(/\s+/g, ' ');
50
- if (!line || line.length > 200)
51
- return null;
52
- const m = SEND.exec(line);
53
- if (!m || !amountOk(m[1]))
54
- return null;
55
- const symbol = m[2].toUpperCase();
56
- const to = m[4];
57
- const family = /^0x[0-9a-fA-F]{40}$/.test(to) ? 'evm' : /^0x[0-9a-fA-F]{64}$/.test(to) ? 'sui' : null;
58
- if (!family)
59
- return null;
60
- const possible = symbol === 'SUI' ? (family === 'evm' ? [] : ['sui']) : symbol === 'ETH' ? (family === 'sui' ? [] : ['eth', 'base']) : family === 'sui' ? ['sui'] : ['eth', 'base'];
61
- if (possible.length === 0)
62
- return null;
63
- const said = (m[3] ?? m[5])?.toLowerCase();
64
- const word = said === undefined ? null : { ethereum: 'eth', eth: 'eth', mainnet: 'eth', base: 'base', sui: 'sui' }[said] ?? null;
65
- if (word && !possible.includes(word))
66
- return null;
67
- return { amount: m[1], symbol, chain: word ?? (possible.length === 1 ? possible[0] : null), to };
68
- }
69
- export const shortAddr = (a) => (a.length > 14 ? `${a.slice(0, 6)}…${a.slice(-4)}` : a);
70
- /** The latest transaction that touched `address` on Sui — what an arrival most likely is. Null when it cannot be read. */
71
- export async function latestSuiDigest(f, net, address) {
72
- try {
73
- const res = await f(SUI[net].graphql, {
74
- method: 'POST', headers: { 'content-type': 'application/json' },
75
- body: JSON.stringify({ query: 'query($a: SuiAddress!) { transactions(last: 1, filter: { affectedAddress: $a }) { nodes { digest } } }', variables: { a: address } }),
76
- });
77
- if (!res.ok)
78
- return null;
79
- const r = (await res.json());
80
- const d = r.data?.transactions?.nodes?.[0]?.digest;
81
- return typeof d === 'string' && d ? d : null;
82
- }
83
- catch {
84
- return null;
85
- }
86
- }
@@ -1,5 +0,0 @@
1
- import { Command } from 'commander';
2
- /** `one links` — mint personalised, actor-bound tracked links from the terminal.
3
- * Thin wrapper over the `links:create` receiver via ask() (no new route). The
4
- * receiver walks authority server-side; the API key identifies the caller. */
5
- export declare function linksCmd(): Command;
package/dist/src/links.js DELETED
@@ -1,45 +0,0 @@
1
- import { Command } from 'commander';
2
- import { authHeaders, resolveBase } from './lib/client.js';
3
- import { askPath } from './lib/api-path.js';
4
- const DEFAULT_API = resolveBase({}, 'https://api.one.ie');
5
- async function ask(api, receiver, data) {
6
- const res = await fetch(askPath(api.replace(/\/$/, ''), receiver), {
7
- method: 'POST',
8
- headers: authHeaders(),
9
- body: JSON.stringify({ data }),
10
- });
11
- if (!res.ok) {
12
- process.stderr.write(`POST /api/ask/${receiver} → ${res.status}\n`);
13
- process.exit(1);
14
- }
15
- return res.json();
16
- }
17
- function out(data) {
18
- process.stdout.write(JSON.stringify(data, null, 2) + '\n');
19
- }
20
- /** `one links` — mint personalised, actor-bound tracked links from the terminal.
21
- * Thin wrapper over the `links:create` receiver via ask() (no new route). The
22
- * receiver walks authority server-side; the API key identifies the caller. */
23
- export function linksCmd() {
24
- const cmd = new Command('links').description('Create personalised, actor-bound tracked links');
25
- cmd
26
- .command('create <actorId>')
27
- .description('Create a tracked link bound to a contact (rung-4 identity on click)')
28
- .option('--to <path>', "Destination path, e.g. '/pricing'", '/')
29
- .option('--context <text>', "Context injected into the agent's system prompt")
30
- .option('--greeting <text>', "Override the chat agent's opening line")
31
- .option('--campaign <id>', 'Group clicks under a campaign')
32
- .option('--expires <days>', 'Link TTL in days (omit = never)')
33
- .option('--api <url>', 'API base URL', DEFAULT_API)
34
- .action(async (actorId, opts) => {
35
- out(await ask(opts.api, 'links:create', {
36
- actorId,
37
- destination: opts.to,
38
- context: opts.context,
39
- greeting: opts.greeting,
40
- campaignId: opts.campaign,
41
- expiresInDays: opts.expires ? Number(opts.expires) : undefined,
42
- }));
43
- });
44
- return cmd;
45
- }
@@ -1,29 +0,0 @@
1
- import { Command } from 'commander';
2
- /** The three containers PUT /api/media/video-upload sniffs. `.avi`/`.mkv` are
3
- * refused locally — the door would store them, sniff them, and 415 after the
4
- * whole upload; nothing is gained by sending 100 MB to learn that. */
5
- export declare const VIDEO_CONTENT_TYPES: Record<string, string>;
6
- /** The door's own ceiling (video-upload.ts MAX_BYTES) — refused before a byte is sent. */
7
- export declare const VIDEO_MAX_BYTES: number;
8
- /** The library hands back ROOT-RELATIVE urls. Meta, TikTok and every social
9
- * platform fetch media by URL from their own servers, so the printed url is
10
- * made absolute against the web host — the one form that works off this machine. */
11
- export declare function absoluteUrl(base: string, url: string | undefined): string;
12
- /** `{workspace}/media/{name}` — the receipt names where the bytes landed. */
13
- export declare function workspaceOfKey(key: string | undefined): string;
14
- export type MediaDims = {
15
- width?: number;
16
- height?: number;
17
- durationS?: number;
18
- };
19
- /** ffprobe's `-print_format json -show_streams -show_format` → the dims the
20
- * content:everywhere door plans on. The first video stream's width/height; the
21
- * container's duration when it has one (an image has none). Anything unreadable
22
- * is `{}` — a dimension is measured or absent, never guessed. */
23
- export declare function parseProbe(json: string): MediaDims;
24
- /** Neither upload door reports dimensions (video-upload.ts and media:upload answer
25
- * key/url/contentType/size only), so the CLI measures the LOCAL file with ffprobe
26
- * when there is one on this machine (`ONE_FFPROBE` names the binary; default
27
- * `ffprobe` on PATH). `null` means it could not measure — the caller says so. */
28
- export declare function probeMedia(path: string): MediaDims | null;
29
- export declare function mediaCmd(): Command;
package/dist/src/media.js DELETED
@@ -1,487 +0,0 @@
1
- import { Command } from 'commander';
2
- import { spawnSync } from 'node:child_process';
3
- import { readFileSync, statSync } from 'node:fs';
4
- import { basename, extname } from 'node:path';
5
- import { mediaListAllWith } from '@oneie/sdk';
6
- import { authHeaders, jsonMode, resolveBase } from './lib/client.js';
7
- import { askPath } from './lib/api-path.js';
8
- import { webBase } from './lib/roster.js';
9
- // `one media` — the two media doors a JSON body cannot serve comfortably.
10
- //
11
- // WHAT IS DELIBERATELY NOT HERE, and why. The CLI already reaches every receiver:
12
- // `one ask <receiver> --data '<json>'` (substrate.ts). So a subcommand has to earn
13
- // its place the way `one tasks board` does — by doing work the raw ask cannot.
14
- //
15
- // list EARNS IT — media:list is ONE R2 scan per call with a budget and a
16
- // cursor, and its `total` is per-page AND a floor whenever `truncated`
17
- // is present. A raw ask prints scan one and READS AS COMPLETE. That is
18
- // the 200-row-clamp defect, and it is what this renderer refuses to do.
19
- // upload EARNS IT — media:upload takes `{ url | base64 }`. You cannot put a
20
- // local file in a JSON body by hand. This reads it, sizes it against the
21
- // door's own 5 MiB cap before spending a request, and encodes it.
22
- // generate DECLINED — it is a prompt string in a JSON body. The answer is
23
- // `one ask media:generate --data '{"prompt":"a red bicycle"}'`, which is
24
- // not worse than a wrapper would be. Documented, not built.
25
- //
26
- // WORKSPACE. `--workspace` is offered on BOTH verbs because media:upload REFUSES a
27
- // workspace you may not write ("A refusal is never a downgrade to your own
28
- // workspace" — its own error describe()). That is the one thing that makes a write
29
- // flag safe here: the older HTTP doors derive the slug from the session and ignore
30
- // what they are handed, so an agency's upload landed in the agency's library and
31
- // looked like it worked. This receiver does not, and the printed `key` proves it —
32
- // it names the workspace prefix the bytes actually reached.
33
- const DEFAULT_API = 'https://api.one.ie';
34
- /** The door's own hard cap (media:upload: "5 MiB hard cap"). Checked here so a
35
- * doomed 6.7 MiB base64 body is never sent — the refusal is instant and names the number. */
36
- const UPLOAD_MAX_BYTES = 5 * 1024 * 1024;
37
- /** media:list's `prefix` is an enum, not a free string — refuse locally rather than
38
- * spend a request on a value the zod schema will reject. */
39
- const PREFIXES = ['media', 'chat', 'ads', 'products', 'pages', 'brand', 'courses'];
40
- const VIDEO_EXT = new Set(['.mp4', '.webm', '.mov', '.m4v', '.avi', '.mkv']);
41
- /** The three containers PUT /api/media/video-upload sniffs. `.avi`/`.mkv` are
42
- * refused locally — the door would store them, sniff them, and 415 after the
43
- * whole upload; nothing is gained by sending 100 MB to learn that. */
44
- export const VIDEO_CONTENT_TYPES = {
45
- '.mp4': 'video/mp4',
46
- '.m4v': 'video/mp4',
47
- '.webm': 'video/webm',
48
- '.mov': 'video/quicktime',
49
- };
50
- /** The door's own ceiling (video-upload.ts MAX_BYTES) — refused before a byte is sent. */
51
- export const VIDEO_MAX_BYTES = 100 * 1024 * 1024;
52
- /** The library hands back ROOT-RELATIVE urls. Meta, TikTok and every social
53
- * platform fetch media by URL from their own servers, so the printed url is
54
- * made absolute against the web host — the one form that works off this machine. */
55
- export function absoluteUrl(base, url) {
56
- if (!url)
57
- return '';
58
- return /^https?:\/\//i.test(url) ? url : `${webBase(base).replace(/\/$/, '')}${url.startsWith('/') ? '' : '/'}${url}`;
59
- }
60
- /** `{workspace}/media/{name}` — the receipt names where the bytes landed. */
61
- export function workspaceOfKey(key) {
62
- return key ? key.split('/')[0] ?? '' : '';
63
- }
64
- /** ffprobe's `-print_format json -show_streams -show_format` → the dims the
65
- * content:everywhere door plans on. The first video stream's width/height; the
66
- * container's duration when it has one (an image has none). Anything unreadable
67
- * is `{}` — a dimension is measured or absent, never guessed. */
68
- export function parseProbe(json) {
69
- let parsed;
70
- try {
71
- parsed = JSON.parse(json);
72
- }
73
- catch {
74
- return {};
75
- }
76
- const out = {};
77
- const stream = (parsed.streams ?? []).find((s) => s.codec_type === 'video' && typeof s.width === 'number' && typeof s.height === 'number');
78
- if (stream) {
79
- out.width = stream.width;
80
- out.height = stream.height;
81
- }
82
- const d = Number(parsed.format?.duration);
83
- if (Number.isFinite(d) && d > 0)
84
- out.durationS = d;
85
- return out;
86
- }
87
- /** Neither upload door reports dimensions (video-upload.ts and media:upload answer
88
- * key/url/contentType/size only), so the CLI measures the LOCAL file with ffprobe
89
- * when there is one on this machine (`ONE_FFPROBE` names the binary; default
90
- * `ffprobe` on PATH). `null` means it could not measure — the caller says so. */
91
- export function probeMedia(path) {
92
- const bin = process.env.ONE_FFPROBE || 'ffprobe';
93
- try {
94
- const r = spawnSync(bin, ['-v', 'error', '-print_format', 'json', '-show_streams', '-show_format', path], {
95
- encoding: 'utf8',
96
- timeout: 15_000,
97
- });
98
- if (r.error || r.status !== 0 || !r.stdout)
99
- return null;
100
- const dims = parseProbe(r.stdout);
101
- return dims.width !== undefined ? dims : null;
102
- }
103
- catch {
104
- return null;
105
- }
106
- }
107
- /** One `skip`/`impossible` row from the door, however it spells its fields —
108
- * `platform`/`network`, `format`/`key`/`label`, and the `reason`. */
109
- function misfitLine(row) {
110
- if (!row || typeof row !== 'object')
111
- return String(row);
112
- const r = row;
113
- const where = [r.platform ?? r.network, r.format ?? r.key ?? r.label].filter((x) => typeof x === 'string' && x).join('/');
114
- const why = typeof r.reason === 'string' ? r.reason : typeof r.why === 'string' ? r.why : '';
115
- return `${where || '?'}${why ? ` — ${why}` : ''}`;
116
- }
117
- /** The door's counts and misfits, as lines. Counts are every top-level number the
118
- * door answered (posts, ads, derived, …) — printed by name, never summed into a
119
- * claim. The one sentence this never prints is "published": the door drafts. */
120
- function renderEverywhere(res, review) {
121
- const w = process.stdout;
122
- const counts = Object.entries(res)
123
- .filter(([, v]) => typeof v === 'number')
124
- .map(([k, v]) => `${k}=${v}`)
125
- .join(' ');
126
- w.write(`everywhere ${counts || 'no counts answered'} — drafts only, nothing was published\n`);
127
- for (const row of res.skipped ?? [])
128
- w.write(`skip ${misfitLine(row)}\n`);
129
- for (const row of res.impossible ?? [])
130
- w.write(`impossible ${misfitLine(row)}\n`);
131
- if (res.truncated !== undefined)
132
- w.write(`TRUNCATED the door cut its answer short: ${JSON.stringify(res.truncated)}\n`);
133
- w.write(`review ${review}\n`);
134
- }
135
- const CONTENT_TYPES = {
136
- '.png': 'image/png',
137
- '.jpg': 'image/jpeg',
138
- '.jpeg': 'image/jpeg',
139
- '.gif': 'image/gif',
140
- '.webp': 'image/webp',
141
- '.avif': 'image/avif',
142
- };
143
- function fail(msg) {
144
- process.stderr.write(`error ${msg}\n`);
145
- process.exitCode = 1;
146
- }
147
- function asker(api) {
148
- const base = resolveBase({ api }, DEFAULT_API);
149
- return async (receiver, data, timeoutMs) => {
150
- const res = await fetch(askPath(base, receiver), {
151
- method: 'POST',
152
- headers: authHeaders(),
153
- body: JSON.stringify(timeoutMs ? { data, timeoutMs } : { data }),
154
- });
155
- const text = await res.text();
156
- let body;
157
- try {
158
- body = text ? JSON.parse(text) : undefined;
159
- }
160
- catch {
161
- throw new Error(`${receiver} → ${res.status} ${text.slice(0, 200)}`);
162
- }
163
- // A refusal wears an envelope at HTTP 200 as readily as at 4xx — read the envelope, not the status.
164
- if (!res.ok && !(body && typeof body === 'object' && 'outcome' in body)) {
165
- throw new Error(`${receiver} → ${res.status} ${text.slice(0, 200)}`);
166
- }
167
- return unwrap(receiver, body);
168
- };
169
- }
170
- /** Unwrap the ask door's `{ outcome, result }`. A failure whose result is a receiver
171
- * body (`{ ok:false, error }`) is RETURNED, not thrown — the caller keeps its receipt. */
172
- function unwrap(receiver, raw) {
173
- if (!raw || typeof raw !== 'object')
174
- throw new Error(`${receiver}: empty response`);
175
- const o = raw;
176
- if ('outcome' in o) {
177
- if (o.outcome === 'result')
178
- return o.result ?? {};
179
- const inner = o.result;
180
- if (inner && typeof inner === 'object' && ('ok' in inner || 'error' in inner)) {
181
- return { ok: false, ...inner, error: inner.error ?? String(o.outcome) };
182
- }
183
- const why = typeof o.reason === 'string' ? ` (${o.reason})` : '';
184
- throw new Error(`${receiver}: ${String(o.outcome)}${why}`);
185
- }
186
- if ('result' in o)
187
- return o.result ?? {};
188
- return o;
189
- }
190
- function human(bytes) {
191
- if (bytes === null || bytes === undefined)
192
- return '?';
193
- if (bytes < 1024)
194
- return `${bytes}B`;
195
- if (bytes < 1024 * 1024)
196
- return `${(bytes / 1024).toFixed(1)}K`;
197
- return `${(bytes / 1024 / 1024).toFixed(1)}M`;
198
- }
199
- function counts(rec) {
200
- const rows = Object.entries(rec ?? {}).sort((a, b) => b[1] - a[1]);
201
- return rows.length ? rows.map(([k, v]) => `${k || '(root)'}=${v}`).join(' ') : '-';
202
- }
203
- function renderList(res) {
204
- const items = res.items ?? [];
205
- const w = process.stdout;
206
- // ABSENT IS NOT FALSE: a complete answer carries no `truncated` key at all.
207
- const short = res.truncated !== undefined;
208
- // THE RULE: a total beside a present `truncated` is a FLOOR, never a count.
209
- const totalTxt = res.total === undefined ? '?' : short ? `at least ${res.total}` : `${res.total}`;
210
- w.write(`${items.length} rows, ${totalTxt} media` +
211
- `${res.scanned !== undefined ? ` scanned=${res.scanned} objects` : ''}` +
212
- `${res.pages ? ` pages=${res.pages}` : ''}\n`);
213
- if (short) {
214
- w.write(`TRUNCATED: the scan budget bit — "${res.total ?? '?'}" is a FLOOR, not a count ` +
215
- `${JSON.stringify(res.truncated)}\n`);
216
- }
217
- if (res.nextCursor) {
218
- w.write(`MORE: nextCursor=${res.nextCursor} — rerun with --all to walk every page\n`);
219
- }
220
- // scanned far above total means most of the bucket is not media — following the
221
- // cursor is the right move, and concluding "empty workspace" is the wrong one.
222
- if (!short && res.scanned !== undefined && res.total !== undefined && res.scanned > res.total * 4) {
223
- w.write(`note most of what was scanned is not media (${res.total} of ${res.scanned})\n`);
224
- }
225
- if (res.byPrefix)
226
- w.write(`byPrefix ${counts(res.byPrefix)}\n`);
227
- if (items.length)
228
- w.write('\n');
229
- for (const it of items) {
230
- w.write(`${it.key} ${it.kind} ${human(it.size)} ${it.contentType} ${it.uploaded ?? '-'}\n`);
231
- }
232
- }
233
- /**
234
- * PUT the file to the streamed video door. It lives on the WEB host, never the
235
- * gateway: api.one.ie forwards receivers, not this route, so webBase() picks the
236
- * host whatever --api says. 100 MB fits in memory here; reading it whole gives fetch
237
- * a Content-Length, which lets the door refuse an oversized body before writing.
238
- */
239
- async function uploadVideo(api, path, contentType, workspace) {
240
- const base = webBase(resolveBase({ api }, DEFAULT_API)).replace(/\/$/, '');
241
- const qs = workspace ? `?workspace=${encodeURIComponent(workspace)}` : '';
242
- const headers = { ...authHeaders(), 'Content-Type': contentType };
243
- const res = await fetch(`${base}/api/media/video-upload${qs}`, {
244
- method: 'PUT',
245
- headers,
246
- body: readFileSync(path),
247
- });
248
- const text = await res.text();
249
- let body;
250
- try {
251
- body = text ? JSON.parse(text) : {};
252
- }
253
- catch {
254
- throw new Error(`video-upload → ${res.status} ${text.slice(0, 200)}`);
255
- }
256
- if (!res.ok) {
257
- const why = body.reason ?? body.error ?? text.slice(0, 200);
258
- const hint = res.status === 401
259
- ? ' — no valid key: run `one login`'
260
- : res.status === 403
261
- ? ` — your key may not write ${workspace ?? 'this workspace'}`
262
- : '';
263
- return { ok: false, error: `video-upload → ${res.status} ${why}${hint}` };
264
- }
265
- return { ...body, kind: 'video', workspace: body.workspace ?? workspaceOfKey(body.key) };
266
- }
267
- /** Draft a post carrying the uploaded media. Drafts only: the posts door refuses
268
- * scheduledAt/status from a key, because a scheduled post publishes itself. */
269
- async function draftPost(api, group, caption, platforms, mediaUrl, mediaType) {
270
- const base = webBase(resolveBase({ api }, DEFAULT_API)).replace(/\/$/, '');
271
- const res = await fetch(`${base}/api/social/posts`, {
272
- method: 'POST',
273
- headers: authHeaders(),
274
- body: JSON.stringify({ groupId: group, content: caption, platforms, mediaUrl, mediaType }),
275
- });
276
- const text = await res.text();
277
- if (!res.ok)
278
- return { ok: false, error: `social/posts → ${res.status} ${text.slice(0, 200)}` };
279
- try {
280
- return { ok: true, id: JSON.parse(text).post?.id };
281
- }
282
- catch {
283
- return { ok: false, error: `social/posts → ${res.status} unreadable body` };
284
- }
285
- }
286
- /**
287
- * The same door the Everywhere panel presses: ONE ask, the pinned fields and no
288
- * others — `{ workspace, campaignId, mediaUrl, mediaType, width, height,
289
- * durationS, text, stageKey }`. Dims come from a local ffprobe; when there is
290
- * none they are OMITTED (the door measures what it can), and the omission is
291
- * returned so it is printed. Nothing here publishes — the door drafts.
292
- */
293
- async function runEverywhere(opts, workspace, mediaUrl, mediaType) {
294
- const dims = probeMedia(opts.path);
295
- const text = opts.text ?? basename(opts.path, extname(opts.path));
296
- const data = {
297
- workspace,
298
- campaignId: opts.campaign,
299
- mediaUrl,
300
- mediaType,
301
- ...(dims?.width !== undefined ? { width: dims.width } : {}),
302
- ...(dims?.height !== undefined ? { height: dims.height } : {}),
303
- ...(dims?.durationS !== undefined ? { durationS: dims.durationS } : {}),
304
- text,
305
- ...(opts.stage ? { stageKey: opts.stage } : {}),
306
- };
307
- try {
308
- // 30s is the ask door's own ceiling; the door derives and drafts inside it.
309
- const res = (await asker(opts.api)('content:everywhere', data, 30_000));
310
- return { res, probed: dims !== null };
311
- }
312
- catch (e) {
313
- return { res: { ok: false, error: e instanceof Error ? e.message : String(e) }, probed: dims !== null };
314
- }
315
- }
316
- async function finish(sub, res, sent, opts) {
317
- if (res.ok === false) {
318
- if (jsonMode(sub))
319
- process.stdout.write(JSON.stringify(res, null, 2) + '\n');
320
- return fail(res.error ?? 'upload failed');
321
- }
322
- const url = absoluteUrl(resolveBase({ api: opts.api }, DEFAULT_API), res.url);
323
- const workspace = res.workspace ?? workspaceOfKey(res.key);
324
- const mediaType = res.kind === 'video' || (res.contentType ?? '').startsWith('video/') ? 'video' : 'image';
325
- let post;
326
- if (opts.post) {
327
- const platforms = opts.platforms.split(',').map((p) => p.trim()).filter(Boolean);
328
- post = await draftPost(opts.api, workspace, opts.post, platforms, url, mediaType);
329
- }
330
- let everywhere;
331
- if (opts.everywhere)
332
- everywhere = await runEverywhere(opts, workspace, url, mediaType);
333
- const review = `${webBase(resolveBase({ api: opts.api }, DEFAULT_API)).replace(/\/$/, '')}/u/${workspace}/marketing/social`;
334
- if (jsonMode(sub)) {
335
- process.stdout.write(JSON.stringify({ ...res, url, ...(post ? { post, review } : {}), ...(everywhere ? { everywhere: everywhere.res, review, probed: everywhere.probed } : {}) }, null, 2) + '\n');
336
- }
337
- else {
338
- // The `key` is the receipt: it names the workspace prefix the bytes ACTUALLY
339
- // reached. Printed always, so a --workspace upload can never merely look right.
340
- process.stdout.write(`ok key=${res.key ?? '?'} kind=${res.kind ?? '?'} type=${res.contentType ?? '?'} stored=${human(res.size)} sent=${human(sent)}\n` +
341
- ` ${url}\n`);
342
- if (post?.ok)
343
- process.stdout.write(`draft post=${post.id ?? '?'} — publish it here: ${review}\n`);
344
- if (everywhere) {
345
- if (!everywhere.probed) {
346
- process.stdout.write('note no ffprobe on this machine — width/height/duration were not sent, the door measures what it can\n');
347
- }
348
- if (everywhere.res.ok !== false)
349
- renderEverywhere(everywhere.res, review);
350
- }
351
- }
352
- if (post && !post.ok)
353
- fail(`uploaded, but the post draft failed: ${post.error}`);
354
- if (everywhere && everywhere.res.ok === false) {
355
- fail(`uploaded, but content:everywhere refused: ${everywhere.res.error ?? 'unknown'}`);
356
- }
357
- }
358
- export function mediaCmd() {
359
- const cmd = new Command('media').description('A workspace media library — list the WHOLE of it, upload a local file. ' +
360
- '(generate has no subcommand on purpose: one ask media:generate --data \'{"prompt":"..."}\')');
361
- cmd
362
- .command('list')
363
- .description('List media (media:list) — rows, an honest total, and a loud word when the scan was cut short')
364
- .option('--workspace <slug>', 'Group slug to read (default: your own). Honoured only if you may read it.')
365
- .option('--kind <k>', 'image | video — filters the rows on a page, does not change what is scanned')
366
- .option('--prefix <p>', `Only this namespace: ${PREFIXES.join(' | ')}`)
367
- .option('--limit <n>', 'R2 objects to SCAN per page BEFORE filtering — not a row count. Default 500, max 1000.')
368
- .option('--all', 'Follow nextCursor until every page is read (ceiling 20 pages)')
369
- .option('--api <url>', 'API base URL', DEFAULT_API)
370
- .option('--json', 'Print the raw response')
371
- .action(async (opts, sub) => {
372
- if (opts.kind && opts.kind !== 'image' && opts.kind !== 'video') {
373
- return fail("--kind must be 'image' or 'video'");
374
- }
375
- if (opts.prefix && !PREFIXES.includes(opts.prefix)) {
376
- return fail(`--prefix must be one of: ${PREFIXES.join(', ')}`);
377
- }
378
- const limit = opts.limit === undefined ? undefined : Number(opts.limit);
379
- if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > 1000)) {
380
- return fail('--limit must be a whole number from 1 to 1000 (R2\'s own ceiling)');
381
- }
382
- const req = {
383
- ...(opts.workspace ? { workspace: opts.workspace } : {}),
384
- ...(opts.kind ? { kind: opts.kind } : {}),
385
- ...(opts.prefix ? { prefix: opts.prefix } : {}),
386
- ...(limit !== undefined ? { limit } : {}),
387
- };
388
- const ask = asker(opts.api);
389
- let res;
390
- try {
391
- res = opts.all
392
- ? await mediaListAllWith((r, d) => ask(r, d), req)
393
- : (await ask('media:list', req));
394
- }
395
- catch (e) {
396
- return fail(e instanceof Error ? e.message : String(e));
397
- }
398
- if (jsonMode(sub))
399
- process.stdout.write(JSON.stringify(res, null, 2) + '\n');
400
- else if (res.ok !== false)
401
- renderList(res);
402
- if (res.ok === false)
403
- fail(res.error ?? 'media:list failed');
404
- });
405
- cmd
406
- .command('upload <path>')
407
- .description('Upload a LOCAL image (media:upload, 5 MiB) or video (.mp4/.mov/.webm, streamed, 100 MB) into the library. ' +
408
- 'Add --post "<caption>" [--platforms facebook] to draft a social post with it — a person publishes it. ' +
409
- 'For a remote image URL: one ask media:upload --data \'{"url":"https://…"}\'')
410
- .option('--workspace <slug>', 'Group slug to write (default: your own). A workspace you may not write is REFUSED, never downgraded.')
411
- .option('--content-type <ct>', 'A HINT only — the stored type is decided by the magic bytes')
412
- .option('--filename <name>', 'A LABEL for the key, not a path (default: the basename). The extension always comes from the sniffed bytes.')
413
- .option('--post <caption>', 'Also draft a social post carrying this media (drafts only — publish on the social page)')
414
- .option('--platforms <list>', 'With --post: comma-separated platforms. Default facebook — the one platform that posts the video itself; linkedin/twitter post the caption only', 'facebook')
415
- .option('--campaign <id>', 'The campaign (world_groups gid) this media is for — required by --everywhere')
416
- .option('--everywhere', 'After the upload, run content:everywhere: draft it for every social format and ad format it fits, in the campaign. Drafts only; prints the skips. Dims come from a local ffprobe when there is one.')
417
- .option('--text <text>', 'With --everywhere: the message the formats carry (default: the file name)')
418
- .option('--stage <key>', 'With --everywhere: the campaign stage the drafts belong to')
419
- .option('--api <url>', 'API base URL', DEFAULT_API)
420
- .option('--json', 'Print the raw response')
421
- .action(async (path, opts, sub) => {
422
- if (opts.everywhere && !opts.campaign) {
423
- return fail('--everywhere needs --campaign <id>: the drafts belong to a campaign. Nothing was sent.');
424
- }
425
- let size;
426
- try {
427
- const st = statSync(path);
428
- if (!st.isFile())
429
- return fail(`${path} is not a file`);
430
- size = st.size;
431
- }
432
- catch (e) {
433
- return fail(`${path}: ${e instanceof Error ? e.message : String(e)}`);
434
- }
435
- if (size === 0)
436
- return fail(`${path} is empty`);
437
- const ext = extname(path).toLowerCase();
438
- if (VIDEO_EXT.has(ext)) {
439
- const videoType = VIDEO_CONTENT_TYPES[ext];
440
- if (!videoType) {
441
- return fail(`${path} is ${ext} — the library takes .mp4, .mov and .webm. Nothing was sent. Convert it first (ffmpeg -i ${basename(path)} out.mp4).`);
442
- }
443
- if (size > VIDEO_MAX_BYTES) {
444
- return fail(`${path} is ${human(size)} — the video door caps at ${human(VIDEO_MAX_BYTES)}. Nothing was sent.`);
445
- }
446
- let res;
447
- try {
448
- res = await uploadVideo(opts.api, path, videoType, opts.workspace);
449
- }
450
- catch (e) {
451
- return fail(e instanceof Error ? e.message : String(e));
452
- }
453
- return finish(sub, res, size, { ...opts, path });
454
- }
455
- if (ext === '.svg') {
456
- return fail(`${path} is SVG, which media:upload refuses deliberately (the public reader serves the stored type verbatim). Nothing was sent.`);
457
- }
458
- if (size > UPLOAD_MAX_BYTES) {
459
- return fail(`${path} is ${human(size)} — media:upload caps at ${human(UPLOAD_MAX_BYTES)}. Nothing was sent. ` +
460
- 'Host the file and pass a URL instead: one ask media:upload --data \'{"url":"https://…"}\'');
461
- }
462
- const contentType = opts.contentType ?? CONTENT_TYPES[ext];
463
- let base64;
464
- try {
465
- base64 = readFileSync(path).toString('base64');
466
- }
467
- catch (e) {
468
- return fail(`${path}: ${e instanceof Error ? e.message : String(e)}`);
469
- }
470
- const data = {
471
- base64,
472
- filename: opts.filename ?? basename(path, ext),
473
- ...(opts.workspace ? { workspace: opts.workspace } : {}),
474
- ...(contentType ? { contentType } : {}),
475
- };
476
- let res;
477
- try {
478
- // 30s is the ask door's own ceiling, and a 5 MiB body measured 6.6s wall to prod.
479
- res = (await asker(opts.api)('media:upload', data, 30_000));
480
- }
481
- catch (e) {
482
- return fail(e instanceof Error ? e.message : String(e));
483
- }
484
- return finish(sub, res, size, { ...opts, path });
485
- });
486
- return cmd;
487
- }