@foleo/cli 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +51 -0
- package/dist/index.d.ts +58 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1436 -0
- package/dist/index.js.map +1 -0
- package/package.json +53 -0
- package/skills/foleo/SKILL.md +59 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1436 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
4
|
+
import { constants } from "node:fs";
|
|
5
|
+
import { lstat as defaultLstat, readFile, realpath } from "node:fs/promises";
|
|
6
|
+
import { open } from "node:fs/promises";
|
|
7
|
+
import { lstat, readdir } from "node:fs/promises";
|
|
8
|
+
import { createServer } from "node:http";
|
|
9
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
10
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
11
|
+
const KEYCHAIN_SERVICE = "com.contraverse.foleo.cli";
|
|
12
|
+
const APP_SESSION_KEYCHAIN_SERVICE = "app.foleo.publish";
|
|
13
|
+
const CLI_KEY_SCOPES = [
|
|
14
|
+
"docs:write",
|
|
15
|
+
"docs:unpublish",
|
|
16
|
+
"html:write",
|
|
17
|
+
"html:unpublish",
|
|
18
|
+
];
|
|
19
|
+
const HTML_BUNDLE_MAX_FILES = 1_000;
|
|
20
|
+
const HTML_BUNDLE_MAX_BYTES = 100 * 1024 * 1024;
|
|
21
|
+
const HTML_BUNDLE_MAX_FILE_BYTES = 8 * 1024 * 1024;
|
|
22
|
+
const LIVE_DOC_ASSET_MAX_FILES = 50;
|
|
23
|
+
const LIVE_DOC_ASSET_MAX_BYTES = 25 * 1024 * 1024;
|
|
24
|
+
const LIVE_DOC_ASSET_MAX_FILE_BYTES = 8 * 1024 * 1024;
|
|
25
|
+
const HTML_UPLOAD_FILE_PUTS_PER_WINDOW = 7;
|
|
26
|
+
const HTML_UPLOAD_FILE_WINDOW_MS = 10_500;
|
|
27
|
+
const LIVE_DOC_ASSET_MEDIA_TYPES = {
|
|
28
|
+
".png": "image/png",
|
|
29
|
+
".jpg": "image/jpeg",
|
|
30
|
+
".jpeg": "image/jpeg",
|
|
31
|
+
".gif": "image/gif",
|
|
32
|
+
".webp": "image/webp",
|
|
33
|
+
".avif": "image/avif",
|
|
34
|
+
};
|
|
35
|
+
export async function runCli(argv, deps = {
|
|
36
|
+
fetch,
|
|
37
|
+
readFile,
|
|
38
|
+
env: process.env,
|
|
39
|
+
stdout: (message) => process.stdout.write(message),
|
|
40
|
+
stderr: (message) => process.stderr.write(message),
|
|
41
|
+
}) {
|
|
42
|
+
try {
|
|
43
|
+
const global = parseGlobalFlags(argv);
|
|
44
|
+
const commandDeps = global.environment
|
|
45
|
+
? { ...deps, env: { ...deps.env, FOLEO_ENV: global.environment } }
|
|
46
|
+
: deps;
|
|
47
|
+
const [command, ...rest] = global.argv;
|
|
48
|
+
if (command === undefined ||
|
|
49
|
+
command === "help" ||
|
|
50
|
+
command === "--help" ||
|
|
51
|
+
command === "-h") {
|
|
52
|
+
commandDeps.stdout(help());
|
|
53
|
+
return 0;
|
|
54
|
+
}
|
|
55
|
+
if (command === "publish")
|
|
56
|
+
return await publish(rest, commandDeps);
|
|
57
|
+
if (command === "update")
|
|
58
|
+
return await update(rest, commandDeps);
|
|
59
|
+
if (command === "unpublish")
|
|
60
|
+
return await unpublish(rest, commandDeps);
|
|
61
|
+
if (command === "status")
|
|
62
|
+
return await status(rest, commandDeps);
|
|
63
|
+
if (command === "html-publish")
|
|
64
|
+
return await htmlPublish(rest, commandDeps);
|
|
65
|
+
if (command === "html-update")
|
|
66
|
+
return await htmlUpdate(rest, commandDeps);
|
|
67
|
+
if (command === "html-status")
|
|
68
|
+
return await htmlStatus(rest, commandDeps);
|
|
69
|
+
if (command === "html-visibility")
|
|
70
|
+
return await htmlVisibility(rest, commandDeps);
|
|
71
|
+
if (command === "html-password")
|
|
72
|
+
return await htmlPassword(rest, commandDeps);
|
|
73
|
+
if (command === "html-unpublish")
|
|
74
|
+
return await htmlUnpublish(rest, commandDeps);
|
|
75
|
+
if (command === "login")
|
|
76
|
+
return await login(rest, commandDeps);
|
|
77
|
+
if (command === "list")
|
|
78
|
+
return await list(rest, commandDeps);
|
|
79
|
+
if (command === "whoami")
|
|
80
|
+
return await whoami(rest, commandDeps);
|
|
81
|
+
if (command === "environment")
|
|
82
|
+
return environmentCommand(rest, commandDeps);
|
|
83
|
+
if (command === "skill")
|
|
84
|
+
return await skill(rest, commandDeps);
|
|
85
|
+
if (command === "doctor")
|
|
86
|
+
return await doctor(rest, commandDeps);
|
|
87
|
+
commandDeps.stderr(help());
|
|
88
|
+
return 2;
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
deps.stderr(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
92
|
+
return error instanceof UsageError ? 2 : 1;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
class UsageError extends Error {
|
|
96
|
+
}
|
|
97
|
+
const SKILL_PATH = fileURLToPath(new URL("../skills/foleo/SKILL.md", import.meta.url));
|
|
98
|
+
async function skill(args, deps) {
|
|
99
|
+
const parsed = parseFlags(args);
|
|
100
|
+
const [action] = parsed.positionals;
|
|
101
|
+
if (parsed.positionals.length !== 1 ||
|
|
102
|
+
(action !== "get" && action !== "path")) {
|
|
103
|
+
throw new UsageError("Usage: foleo skill get|path");
|
|
104
|
+
}
|
|
105
|
+
if (action === "path") {
|
|
106
|
+
deps.stdout(`${SKILL_PATH}\n`);
|
|
107
|
+
return 0;
|
|
108
|
+
}
|
|
109
|
+
deps.stdout(await readFile(SKILL_PATH, "utf8"));
|
|
110
|
+
return 0;
|
|
111
|
+
}
|
|
112
|
+
async function doctor(args, deps) {
|
|
113
|
+
const parsed = parseFlags(args);
|
|
114
|
+
if (parsed.positionals.length > 0)
|
|
115
|
+
throw new UsageError("Usage: foleo doctor [--json]");
|
|
116
|
+
const platform = deps.platform ?? process.platform;
|
|
117
|
+
const nodeVersion = deps.nodeVersion ?? process.versions.node;
|
|
118
|
+
const parsedNodeMajor = Number(nodeVersion.split(".")[0]);
|
|
119
|
+
const checks = [
|
|
120
|
+
{
|
|
121
|
+
key: "platform",
|
|
122
|
+
status: platform === "darwin" ? "pass" : "fail",
|
|
123
|
+
...(platform === "darwin"
|
|
124
|
+
? {}
|
|
125
|
+
: { message: "Foleo CLI requires macOS." }),
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
key: "node",
|
|
129
|
+
status: Number.isFinite(parsedNodeMajor) && parsedNodeMajor >= 22
|
|
130
|
+
? "pass"
|
|
131
|
+
: "fail",
|
|
132
|
+
...(Number.isFinite(parsedNodeMajor) && parsedNodeMajor >= 22
|
|
133
|
+
? {}
|
|
134
|
+
: { message: "Foleo CLI requires Node.js 22 or later." }),
|
|
135
|
+
},
|
|
136
|
+
];
|
|
137
|
+
const info = environmentInfo(deps);
|
|
138
|
+
let apiReachable = false;
|
|
139
|
+
try {
|
|
140
|
+
const response = await deps.fetch(`${apiBase(deps)}/health`, {
|
|
141
|
+
method: "GET",
|
|
142
|
+
});
|
|
143
|
+
apiReachable = response.ok;
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
// The diagnostic is deliberately best-effort; it must not make setup worse.
|
|
147
|
+
}
|
|
148
|
+
checks.push({
|
|
149
|
+
key: "api",
|
|
150
|
+
status: apiReachable ? "pass" : "fail",
|
|
151
|
+
...(apiReachable ? {} : { message: "Foleo API could not be reached." }),
|
|
152
|
+
});
|
|
153
|
+
const credential = await resolveCredentialWithSource(deps, {
|
|
154
|
+
mintAppSession: false,
|
|
155
|
+
});
|
|
156
|
+
if (!credential) {
|
|
157
|
+
checks.push({
|
|
158
|
+
key: "credential",
|
|
159
|
+
status: "warn",
|
|
160
|
+
message: "Run `foleo login` to sign in.",
|
|
161
|
+
});
|
|
162
|
+
checks.push({
|
|
163
|
+
key: "account",
|
|
164
|
+
status: "warn",
|
|
165
|
+
message: "Sign in to inspect account readiness.",
|
|
166
|
+
});
|
|
167
|
+
checks.push({
|
|
168
|
+
key: "markdownPublish",
|
|
169
|
+
status: "warn",
|
|
170
|
+
message: "Sign in to inspect Markdown access.",
|
|
171
|
+
});
|
|
172
|
+
checks.push({
|
|
173
|
+
key: "htmlAlpha",
|
|
174
|
+
status: "warn",
|
|
175
|
+
message: "Sign in to inspect HTML alpha access.",
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
checks.push({ key: "credential", status: "pass" });
|
|
180
|
+
try {
|
|
181
|
+
const me = await requestJsonWithToken(deps, "/me", credential.token, { method: "GET", body: undefined });
|
|
182
|
+
const bootstrapRequired = me.bootstrapRequired === true;
|
|
183
|
+
const scopes = stringArray(me.scopes);
|
|
184
|
+
const entitlements = stringArray(me.entitlements);
|
|
185
|
+
const markdown = !bootstrapRequired && scopes.includes("docs:write");
|
|
186
|
+
const html = !bootstrapRequired &&
|
|
187
|
+
(scopes.includes("html:write") ||
|
|
188
|
+
entitlements.includes("publish.html_artifact.create"));
|
|
189
|
+
checks.push({
|
|
190
|
+
key: "account",
|
|
191
|
+
status: bootstrapRequired ? "warn" : "pass",
|
|
192
|
+
...(bootstrapRequired
|
|
193
|
+
? { message: "Account bootstrap is required." }
|
|
194
|
+
: {}),
|
|
195
|
+
});
|
|
196
|
+
checks.push({
|
|
197
|
+
key: "markdownPublish",
|
|
198
|
+
status: markdown ? "pass" : "fail",
|
|
199
|
+
...(markdown
|
|
200
|
+
? {}
|
|
201
|
+
: {
|
|
202
|
+
message: "Markdown publishing is unavailable for this account.",
|
|
203
|
+
}),
|
|
204
|
+
});
|
|
205
|
+
checks.push({
|
|
206
|
+
key: "htmlAlpha",
|
|
207
|
+
status: html ? "pass" : "warn",
|
|
208
|
+
...(html
|
|
209
|
+
? {}
|
|
210
|
+
: { message: "HTML alpha is not enabled for this account." }),
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
checks.push({
|
|
215
|
+
key: "account",
|
|
216
|
+
status: "fail",
|
|
217
|
+
message: `Account check failed: ${errorMessage(error)}`,
|
|
218
|
+
});
|
|
219
|
+
checks.push({
|
|
220
|
+
key: "markdownPublish",
|
|
221
|
+
status: "warn",
|
|
222
|
+
message: "Account access could not be determined.",
|
|
223
|
+
});
|
|
224
|
+
checks.push({
|
|
225
|
+
key: "htmlAlpha",
|
|
226
|
+
status: "warn",
|
|
227
|
+
message: "Account access could not be determined.",
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
const result = {
|
|
232
|
+
ok: !checks.some((check) => check.status === "fail"),
|
|
233
|
+
environment: info.name,
|
|
234
|
+
apiOrigin: new URL(info.apiBase).origin,
|
|
235
|
+
checks,
|
|
236
|
+
};
|
|
237
|
+
if (parsed.json)
|
|
238
|
+
deps.stdout(`${JSON.stringify(result, null, 2)}\n`);
|
|
239
|
+
else
|
|
240
|
+
for (const check of checks)
|
|
241
|
+
deps.stdout(`${check.status.toUpperCase()} ${check.key}${check.message ? `: ${check.message}` : ""}\n`);
|
|
242
|
+
return result.ok ? 0 : 1;
|
|
243
|
+
}
|
|
244
|
+
function stringArray(value) {
|
|
245
|
+
return Array.isArray(value) && value.every((item) => typeof item === "string")
|
|
246
|
+
? value
|
|
247
|
+
: [];
|
|
248
|
+
}
|
|
249
|
+
async function login(args, deps) {
|
|
250
|
+
const parsed = parseFlags(args);
|
|
251
|
+
if (parsed.positionals.length > 0)
|
|
252
|
+
throw new Error("Usage: foleo login [--json]");
|
|
253
|
+
const base = apiBase(deps);
|
|
254
|
+
announceApi(deps, parsed.json);
|
|
255
|
+
const verifyStore = deps.verifyCredentialStore ?? verifyKeychainWritable;
|
|
256
|
+
const saveCredential = deps.saveCredential ?? saveKeychainCredential;
|
|
257
|
+
const deleteCredential = deps.deleteCredential ?? deleteKeychainCredential;
|
|
258
|
+
const createCallback = deps.createBrowserCallback ?? createLoopbackCallback;
|
|
259
|
+
const openUrl = deps.openUrl ?? openBrowser;
|
|
260
|
+
await verifyStore(base);
|
|
261
|
+
const nonce = createHash("sha256").update(randomUUID()).digest("hex");
|
|
262
|
+
const callback = await createCallback(nonce);
|
|
263
|
+
let appSessionToken = null;
|
|
264
|
+
let loginResult = null;
|
|
265
|
+
let operationError = null;
|
|
266
|
+
try {
|
|
267
|
+
const start = await requestPublicJson(deps, "/desktop/handoff/start", { nonce, callbackUrl: callback.callbackUrl });
|
|
268
|
+
deps.stderr("Opening Foleo sign-in in your browser...\n");
|
|
269
|
+
try {
|
|
270
|
+
await openUrl(start.authorizeUrl);
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
deps.stderr(`Open this URL to continue:\n${start.authorizeUrl}\n`);
|
|
274
|
+
}
|
|
275
|
+
const code = await callback.waitForCode();
|
|
276
|
+
const exchanged = await requestPublicJson(deps, "/desktop/handoff/exchange", {
|
|
277
|
+
code,
|
|
278
|
+
nonce,
|
|
279
|
+
name: "Foleo CLI",
|
|
280
|
+
sessionTtlSeconds: 600,
|
|
281
|
+
});
|
|
282
|
+
appSessionToken = exchanged.token;
|
|
283
|
+
const key = await requestJsonWithToken(deps, "/keys", appSessionToken, {
|
|
284
|
+
method: "POST",
|
|
285
|
+
body: {
|
|
286
|
+
name: "Foleo CLI",
|
|
287
|
+
scopes: CLI_KEY_SCOPES,
|
|
288
|
+
deferredActivation: true,
|
|
289
|
+
},
|
|
290
|
+
});
|
|
291
|
+
try {
|
|
292
|
+
await saveCredential(base, key.token);
|
|
293
|
+
await requestJsonWithToken(deps, `/keys/${encodeURIComponent(key.id)}/activate`, appSessionToken, { method: "POST", body: {} });
|
|
294
|
+
}
|
|
295
|
+
catch (error) {
|
|
296
|
+
await deleteCredential(base).catch(() => undefined);
|
|
297
|
+
const revoked = await requestJsonWithToken(deps, `/keys/${encodeURIComponent(key.id)}/revoke`, appSessionToken, { method: "POST", body: {} }).then(() => true, () => false);
|
|
298
|
+
if (!revoked)
|
|
299
|
+
throw new Error(`Foleo login failed and pending key cleanup must be retried from the dashboard (key ${key.id}).`);
|
|
300
|
+
throw error;
|
|
301
|
+
}
|
|
302
|
+
loginResult = {
|
|
303
|
+
ok: true,
|
|
304
|
+
org: exchanged.org.handle,
|
|
305
|
+
keyId: key.id,
|
|
306
|
+
scopes: key.scopes,
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
catch (error) {
|
|
310
|
+
operationError = error;
|
|
311
|
+
}
|
|
312
|
+
finally {
|
|
313
|
+
const cleanup = [callback.close()];
|
|
314
|
+
if (appSessionToken)
|
|
315
|
+
cleanup.push(requestJsonWithToken(deps, "/desktop/session/revoke", appSessionToken, {
|
|
316
|
+
method: "POST",
|
|
317
|
+
body: {},
|
|
318
|
+
}).then(() => undefined));
|
|
319
|
+
const results = await Promise.allSettled(cleanup);
|
|
320
|
+
if (results.some((result) => result.status === "rejected")) {
|
|
321
|
+
const cleanupError = "Foleo login could not revoke its transient browser session; it will expire within 10 minutes.";
|
|
322
|
+
operationError = new Error(operationError === null
|
|
323
|
+
? cleanupError
|
|
324
|
+
: `${errorMessage(operationError)} ${cleanupError}`);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
if (operationError !== null)
|
|
328
|
+
throw operationError;
|
|
329
|
+
if (loginResult === null)
|
|
330
|
+
throw new Error("Foleo login did not complete");
|
|
331
|
+
if (parsed.json)
|
|
332
|
+
deps.stdout(`${JSON.stringify(loginResult, null, 2)}\n`);
|
|
333
|
+
else
|
|
334
|
+
deps.stdout(`Signed in to ${loginResult.org}. Credential saved in macOS Keychain.\n`);
|
|
335
|
+
return 0;
|
|
336
|
+
}
|
|
337
|
+
async function htmlPublish(args, deps) {
|
|
338
|
+
const parsed = parseFlags(args);
|
|
339
|
+
const root = parsed.positionals[0];
|
|
340
|
+
if (!root || parsed.positionals.length !== 1 || !parsed.acceptHostingRisk)
|
|
341
|
+
throw new Error("Usage: foleo html-publish <bundle-root> --accept-hosting-risk [--json]\nHosted HTML is executable and may run JavaScript, show forms, or initiate downloads. A human must inspect the source and explicitly approve this risk; an agent must not infer approval.");
|
|
342
|
+
announceApi(deps, parsed.json);
|
|
343
|
+
const result = await publishBundle(root, deps, null, true);
|
|
344
|
+
writeResult(deps, result, parsed.json);
|
|
345
|
+
return 0;
|
|
346
|
+
}
|
|
347
|
+
async function htmlUpdate(args, deps) {
|
|
348
|
+
const parsed = parseFlags(args);
|
|
349
|
+
const [id, root] = parsed.positionals;
|
|
350
|
+
if (!id ||
|
|
351
|
+
!root ||
|
|
352
|
+
parsed.positionals.length !== 2 ||
|
|
353
|
+
parsed.revision === undefined)
|
|
354
|
+
throw new Error("Usage: foleo html-update <id> <bundle-root> --revision <stateRevision> [--json]");
|
|
355
|
+
const result = await publishBundle(root, deps, {
|
|
356
|
+
id,
|
|
357
|
+
revision: parsed.revision,
|
|
358
|
+
});
|
|
359
|
+
writeResult(deps, result, parsed.json);
|
|
360
|
+
return 0;
|
|
361
|
+
}
|
|
362
|
+
async function htmlStatus(args, deps) {
|
|
363
|
+
const parsed = parseFlags(args);
|
|
364
|
+
if (!parsed.positionals[0] || parsed.positionals.length !== 1)
|
|
365
|
+
throw new Error("Usage: foleo html-status <id> [--json]");
|
|
366
|
+
writeStatusResult(deps, await requestJson(deps, `/artifacts/html/${encodeURIComponent(parsed.positionals[0])}`, { method: "GET", body: undefined }), parsed.json);
|
|
367
|
+
return 0;
|
|
368
|
+
}
|
|
369
|
+
async function htmlVisibility(args, deps) {
|
|
370
|
+
const parsed = parseFlags(args);
|
|
371
|
+
const id = parsed.positionals[0];
|
|
372
|
+
if (!id ||
|
|
373
|
+
parsed.positionals.length !== 1 ||
|
|
374
|
+
parsed.revision === undefined ||
|
|
375
|
+
!parsed.set ||
|
|
376
|
+
!["unlisted", "password", "private"].includes(parsed.set))
|
|
377
|
+
throw new Error("Usage: foleo html-visibility <id> --set unlisted|password|private --revision <stateRevision> [--json]");
|
|
378
|
+
announceApi(deps, parsed.json);
|
|
379
|
+
const result = await requestJson(deps, `/artifacts/html/${encodeURIComponent(id)}/visibility`, {
|
|
380
|
+
method: "PATCH",
|
|
381
|
+
body: { visibility: parsed.set },
|
|
382
|
+
headers: revisionHeaders(parsed.revision),
|
|
383
|
+
});
|
|
384
|
+
writeResult(deps, result, parsed.json);
|
|
385
|
+
return 0;
|
|
386
|
+
}
|
|
387
|
+
async function htmlPassword(args, deps) {
|
|
388
|
+
const parsed = parseFlags(args);
|
|
389
|
+
const id = parsed.positionals[0];
|
|
390
|
+
if (!id ||
|
|
391
|
+
parsed.positionals.length !== 1 ||
|
|
392
|
+
parsed.revision === undefined ||
|
|
393
|
+
!parsed.password)
|
|
394
|
+
throw new Error("Usage: foleo html-password <id> --password <12–256 characters> --revision <stateRevision> [--json]");
|
|
395
|
+
announceApi(deps, parsed.json);
|
|
396
|
+
const result = await requestJson(deps, `/artifacts/html/${encodeURIComponent(id)}/password`, {
|
|
397
|
+
method: "PATCH",
|
|
398
|
+
body: { password: parsed.password },
|
|
399
|
+
headers: revisionHeaders(parsed.revision),
|
|
400
|
+
});
|
|
401
|
+
writeResult(deps, result, parsed.json);
|
|
402
|
+
return 0;
|
|
403
|
+
}
|
|
404
|
+
async function htmlUnpublish(args, deps) {
|
|
405
|
+
const parsed = parseFlags(args);
|
|
406
|
+
const id = parsed.positionals[0];
|
|
407
|
+
if (!id || parsed.positionals.length !== 1 || parsed.revision === undefined)
|
|
408
|
+
throw new Error("Usage: foleo html-unpublish <id> --revision <stateRevision> [--json]");
|
|
409
|
+
const result = await requestJson(deps, `/artifacts/html/${encodeURIComponent(id)}/unpublish`, {
|
|
410
|
+
method: "POST",
|
|
411
|
+
body: {},
|
|
412
|
+
headers: {
|
|
413
|
+
"if-match": `"r${parsed.revision}"`,
|
|
414
|
+
"idempotency-key": randomUUID(),
|
|
415
|
+
},
|
|
416
|
+
});
|
|
417
|
+
writeResult(deps, result, parsed.json);
|
|
418
|
+
return 0;
|
|
419
|
+
}
|
|
420
|
+
async function publishBundle(root, deps, update, hostingRiskAcknowledged = false) {
|
|
421
|
+
const files = await scanBundle(root, deps);
|
|
422
|
+
const manifest = files.map(({ bytes: _bytes, ...file }) => file);
|
|
423
|
+
const upload = await requestJson(deps, "/uploads", {
|
|
424
|
+
method: "POST",
|
|
425
|
+
body: {
|
|
426
|
+
kind: "html-artifact-bundle",
|
|
427
|
+
manifest,
|
|
428
|
+
declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
|
|
429
|
+
},
|
|
430
|
+
headers: { "idempotency-key": randomUUID() },
|
|
431
|
+
});
|
|
432
|
+
const beforeFilePut = createHtmlUploadPacer(deps);
|
|
433
|
+
for (const plan of upload.files) {
|
|
434
|
+
const file = files.find((candidate) => candidate.path === plan.path);
|
|
435
|
+
if (!file)
|
|
436
|
+
throw new Error("Server returned an unexpected upload file");
|
|
437
|
+
await beforeFilePut();
|
|
438
|
+
await requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) });
|
|
439
|
+
}
|
|
440
|
+
await requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
|
|
441
|
+
method: "POST",
|
|
442
|
+
body: {},
|
|
443
|
+
headers: { "idempotency-key": randomUUID() },
|
|
444
|
+
});
|
|
445
|
+
return update
|
|
446
|
+
? requestJson(deps, `/artifacts/html/${encodeURIComponent(update.id)}`, {
|
|
447
|
+
method: "PUT",
|
|
448
|
+
body: { uploadId: upload.uploadId, manifestHash: upload.manifestHash },
|
|
449
|
+
headers: {
|
|
450
|
+
"if-match": `"r${update.revision}"`,
|
|
451
|
+
"idempotency-key": randomUUID(),
|
|
452
|
+
},
|
|
453
|
+
})
|
|
454
|
+
: requestJson(deps, "/artifacts/html", {
|
|
455
|
+
method: "POST",
|
|
456
|
+
body: {
|
|
457
|
+
uploadId: upload.uploadId,
|
|
458
|
+
manifestHash: upload.manifestHash,
|
|
459
|
+
hostingRiskAcknowledged,
|
|
460
|
+
},
|
|
461
|
+
headers: { "idempotency-key": randomUUID() },
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
function revisionHeaders(revision) {
|
|
465
|
+
return { "if-match": `"r${revision}"`, "idempotency-key": randomUUID() };
|
|
466
|
+
}
|
|
467
|
+
function createHtmlUploadPacer(deps) {
|
|
468
|
+
const now = deps.now ?? Date.now;
|
|
469
|
+
const sleep = deps.sleep ??
|
|
470
|
+
((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
|
|
471
|
+
let windowStartedAt = now();
|
|
472
|
+
let requests = 0;
|
|
473
|
+
return async () => {
|
|
474
|
+
const elapsed = now() - windowStartedAt;
|
|
475
|
+
if (elapsed >= HTML_UPLOAD_FILE_WINDOW_MS) {
|
|
476
|
+
windowStartedAt = now();
|
|
477
|
+
requests = 0;
|
|
478
|
+
}
|
|
479
|
+
else if (requests >= HTML_UPLOAD_FILE_PUTS_PER_WINDOW) {
|
|
480
|
+
await sleep(HTML_UPLOAD_FILE_WINDOW_MS - elapsed);
|
|
481
|
+
windowStartedAt = now();
|
|
482
|
+
requests = 0;
|
|
483
|
+
}
|
|
484
|
+
requests += 1;
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
export async function scanBundle(root, deps) {
|
|
488
|
+
const base = resolve(root);
|
|
489
|
+
const realBase = deps.readFileBytes ? base : await realpath(base);
|
|
490
|
+
const list = deps.readdir ?? (async (path) => readdir(path));
|
|
491
|
+
const stat = deps.lstat ?? (async (path) => lstat(path));
|
|
492
|
+
const bytesFor = deps.readFileBytes ??
|
|
493
|
+
((path) => boundedReadFileBytes(path, HTML_BUNDLE_MAX_FILE_BYTES, realBase));
|
|
494
|
+
const files = [];
|
|
495
|
+
let fileCount = 0;
|
|
496
|
+
let totalBytes = 0;
|
|
497
|
+
async function walk(dir) {
|
|
498
|
+
for (const name of await list(dir)) {
|
|
499
|
+
if (name.startsWith(".") ||
|
|
500
|
+
name === "node_modules" ||
|
|
501
|
+
name.startsWith(".env"))
|
|
502
|
+
continue;
|
|
503
|
+
const absolute = join(dir, name);
|
|
504
|
+
const info = await stat(absolute);
|
|
505
|
+
if (info.isSymbolicLink())
|
|
506
|
+
continue;
|
|
507
|
+
if (info.isDirectory()) {
|
|
508
|
+
await walk(absolute);
|
|
509
|
+
continue;
|
|
510
|
+
}
|
|
511
|
+
const rel = relative(base, absolute);
|
|
512
|
+
if (rel.startsWith("..") || rel.split(sep).some((part) => part === ""))
|
|
513
|
+
continue;
|
|
514
|
+
const path = `/${rel.split(sep).join("/")}`;
|
|
515
|
+
if (!info.isFile())
|
|
516
|
+
throw new Error(`Unsupported bundle file: ${path}`);
|
|
517
|
+
if (info.size > HTML_BUNDLE_MAX_FILE_BYTES ||
|
|
518
|
+
totalBytes + info.size > HTML_BUNDLE_MAX_BYTES)
|
|
519
|
+
throw new Error("Bundle exceeds Foleo limits");
|
|
520
|
+
if (fileCount + 1 > HTML_BUNDLE_MAX_FILES)
|
|
521
|
+
throw new Error("Bundle exceeds Foleo limits");
|
|
522
|
+
if (path !== "/index.html" && /\.html?$/i.test(path))
|
|
523
|
+
throw new Error("Only index.html may be published");
|
|
524
|
+
const mediaType = mediaTypeFor(path);
|
|
525
|
+
if (!mediaType)
|
|
526
|
+
throw new Error(`Unsupported bundle file: ${path}`);
|
|
527
|
+
const bytes = await bytesFor(absolute);
|
|
528
|
+
if (bytes.byteLength > HTML_BUNDLE_MAX_FILE_BYTES ||
|
|
529
|
+
totalBytes + bytes.byteLength > HTML_BUNDLE_MAX_BYTES)
|
|
530
|
+
throw new Error("Bundle exceeds Foleo limits");
|
|
531
|
+
fileCount += 1;
|
|
532
|
+
totalBytes += bytes.byteLength;
|
|
533
|
+
files.push({
|
|
534
|
+
path,
|
|
535
|
+
sha256: createHash("sha256").update(bytes).digest("hex"),
|
|
536
|
+
byteSize: bytes.byteLength,
|
|
537
|
+
mediaType,
|
|
538
|
+
bytes,
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
await walk(base);
|
|
543
|
+
if (!files.some((file) => file.path === "/index.html"))
|
|
544
|
+
throw new Error("Bundle root must contain index.html");
|
|
545
|
+
return files.sort((a, b) => a.path.localeCompare(b.path));
|
|
546
|
+
}
|
|
547
|
+
function mediaTypeFor(path) {
|
|
548
|
+
if (path === "/index.html")
|
|
549
|
+
return "text/html; charset=utf-8";
|
|
550
|
+
const extension = path.slice(path.lastIndexOf(".")).toLowerCase();
|
|
551
|
+
return ({
|
|
552
|
+
".css": "text/css; charset=utf-8",
|
|
553
|
+
".js": "text/javascript; charset=utf-8",
|
|
554
|
+
".mjs": "text/javascript; charset=utf-8",
|
|
555
|
+
".json": "application/json",
|
|
556
|
+
".wasm": "application/wasm",
|
|
557
|
+
".svg": "image/svg+xml",
|
|
558
|
+
".png": "image/png",
|
|
559
|
+
".jpg": "image/jpeg",
|
|
560
|
+
".jpeg": "image/jpeg",
|
|
561
|
+
".gif": "image/gif",
|
|
562
|
+
".webp": "image/webp",
|
|
563
|
+
".avif": "image/avif",
|
|
564
|
+
".ico": "image/x-icon",
|
|
565
|
+
".woff": "font/woff",
|
|
566
|
+
".woff2": "font/woff2",
|
|
567
|
+
".ttf": "font/ttf",
|
|
568
|
+
".otf": "font/otf",
|
|
569
|
+
}[extension] ?? null);
|
|
570
|
+
}
|
|
571
|
+
async function boundedReadFileBytes(path, maxBytes, realBase) {
|
|
572
|
+
const flags = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | constants.O_NONBLOCK;
|
|
573
|
+
const file = await open(path, flags);
|
|
574
|
+
const chunks = [];
|
|
575
|
+
let total = 0;
|
|
576
|
+
try {
|
|
577
|
+
const stat = await file.stat();
|
|
578
|
+
if (!stat.isFile())
|
|
579
|
+
throw new Error("Bundle path is not a regular file");
|
|
580
|
+
if (stat.nlink > 1)
|
|
581
|
+
throw new Error("Bundle path has multiple hard links");
|
|
582
|
+
if (stat.size > maxBytes)
|
|
583
|
+
throw new Error("Bundle exceeds Foleo limits");
|
|
584
|
+
const resolved = await realpath(path);
|
|
585
|
+
if (resolved !== realBase && !resolved.startsWith(`${realBase}${sep}`))
|
|
586
|
+
throw new Error("Bundle path escaped root");
|
|
587
|
+
const current = await defaultLstat(path);
|
|
588
|
+
if (current.dev !== stat.dev || current.ino !== stat.ino)
|
|
589
|
+
throw new Error("Bundle path changed during scan");
|
|
590
|
+
const buffer = Buffer.alloc(Math.min(64 * 1024, maxBytes + 1));
|
|
591
|
+
while (true) {
|
|
592
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, null);
|
|
593
|
+
if (bytesRead === 0)
|
|
594
|
+
break;
|
|
595
|
+
total += bytesRead;
|
|
596
|
+
if (total > maxBytes)
|
|
597
|
+
throw new Error("Bundle exceeds Foleo limits");
|
|
598
|
+
chunks.push(new Uint8Array(buffer.subarray(0, bytesRead)));
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
finally {
|
|
602
|
+
await file.close();
|
|
603
|
+
}
|
|
604
|
+
const result = new Uint8Array(total);
|
|
605
|
+
let offset = 0;
|
|
606
|
+
for (const chunk of chunks) {
|
|
607
|
+
result.set(chunk, offset);
|
|
608
|
+
offset += chunk.byteLength;
|
|
609
|
+
}
|
|
610
|
+
return result;
|
|
611
|
+
}
|
|
612
|
+
async function publish(args, deps) {
|
|
613
|
+
const parsed = parseFlags(args);
|
|
614
|
+
const file = parsed.positionals[0];
|
|
615
|
+
if (!file || parsed.positionals.length !== 1)
|
|
616
|
+
throw new Error("Usage: foleo publish <file> [--title <title>] [--json]");
|
|
617
|
+
const markdown = await deps.readFile(file, "utf8");
|
|
618
|
+
const assets = await uploadMarkdownAssets(file, markdown, deps);
|
|
619
|
+
const result = await requestJson(deps, "/docs", {
|
|
620
|
+
method: "POST",
|
|
621
|
+
body: {
|
|
622
|
+
markdown,
|
|
623
|
+
...(parsed.title ? { title: parsed.title } : {}),
|
|
624
|
+
...(assets
|
|
625
|
+
? { uploadId: assets.uploadId, manifestHash: assets.manifestHash }
|
|
626
|
+
: {}),
|
|
627
|
+
},
|
|
628
|
+
});
|
|
629
|
+
writeResult(deps, result, parsed.json);
|
|
630
|
+
return 0;
|
|
631
|
+
}
|
|
632
|
+
async function update(args, deps) {
|
|
633
|
+
const parsed = parseFlags(args);
|
|
634
|
+
const [id, file] = parsed.positionals;
|
|
635
|
+
if (!id ||
|
|
636
|
+
!file ||
|
|
637
|
+
parsed.positionals.length !== 2 ||
|
|
638
|
+
parsed.version === undefined) {
|
|
639
|
+
throw new Error("Usage: foleo update <id> <file> --version <version> [--json]");
|
|
640
|
+
}
|
|
641
|
+
const markdown = await deps.readFile(file, "utf8");
|
|
642
|
+
const assets = await uploadMarkdownAssets(file, markdown, deps);
|
|
643
|
+
const result = await requestJson(deps, `/docs/${encodeURIComponent(id)}`, {
|
|
644
|
+
method: "PUT",
|
|
645
|
+
body: {
|
|
646
|
+
markdown,
|
|
647
|
+
version: parsed.version,
|
|
648
|
+
...(assets
|
|
649
|
+
? { uploadId: assets.uploadId, manifestHash: assets.manifestHash }
|
|
650
|
+
: {}),
|
|
651
|
+
},
|
|
652
|
+
});
|
|
653
|
+
writeResult(deps, result, parsed.json);
|
|
654
|
+
return 0;
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Scan Markdown for relative raster image references and build a live-doc
|
|
658
|
+
* assets manifest (spec 065). Absolute http(s) / data: / rooted paths skipped.
|
|
659
|
+
*/
|
|
660
|
+
export async function scanMarkdownAssets(markdownPath, markdown, deps) {
|
|
661
|
+
const baseDir = dirname(resolve(markdownPath));
|
|
662
|
+
const refs = collectRelativeImageRefs(markdown);
|
|
663
|
+
if (refs.length === 0)
|
|
664
|
+
return [];
|
|
665
|
+
const bytesFor = deps.readFileBytes ??
|
|
666
|
+
((path) => boundedReadFileBytes(path, LIVE_DOC_ASSET_MAX_FILE_BYTES, baseDir));
|
|
667
|
+
const files = [];
|
|
668
|
+
const seen = new Set();
|
|
669
|
+
let totalBytes = 0;
|
|
670
|
+
for (const ref of refs) {
|
|
671
|
+
const logical = normalizeLiveDocAssetLogicalPath(ref);
|
|
672
|
+
if (!logical)
|
|
673
|
+
continue;
|
|
674
|
+
if (seen.has(logical))
|
|
675
|
+
continue;
|
|
676
|
+
const mediaType = liveDocAssetMediaType(logical);
|
|
677
|
+
if (!mediaType) {
|
|
678
|
+
throw new Error(`Unsupported live-doc asset type: ${ref}`);
|
|
679
|
+
}
|
|
680
|
+
const absolute = resolve(baseDir, ref.replace(/^\.\//, ""));
|
|
681
|
+
// Spec 065 §F: a referenced-but-absent image must NOT fail the publish —
|
|
682
|
+
// it degrades to the styled missing-asset placeholder server-side. A typo
|
|
683
|
+
// in one image path should never block publishing the whole document.
|
|
684
|
+
let bytes;
|
|
685
|
+
try {
|
|
686
|
+
bytes = await bytesFor(absolute);
|
|
687
|
+
}
|
|
688
|
+
catch (error) {
|
|
689
|
+
const code = error?.code;
|
|
690
|
+
if (code === "ENOENT" || code === "EISDIR") {
|
|
691
|
+
deps.stderr(`Skipping missing local image (will render as unavailable): ${ref}\n`);
|
|
692
|
+
continue;
|
|
693
|
+
}
|
|
694
|
+
throw error;
|
|
695
|
+
}
|
|
696
|
+
if (bytes.byteLength > LIVE_DOC_ASSET_MAX_FILE_BYTES) {
|
|
697
|
+
throw new Error("Live-doc assets exceed Foleo limits");
|
|
698
|
+
}
|
|
699
|
+
if (files.length + 1 > LIVE_DOC_ASSET_MAX_FILES) {
|
|
700
|
+
throw new Error("Live-doc assets exceed Foleo limits");
|
|
701
|
+
}
|
|
702
|
+
if (totalBytes + bytes.byteLength > LIVE_DOC_ASSET_MAX_BYTES) {
|
|
703
|
+
throw new Error("Live-doc assets exceed Foleo limits");
|
|
704
|
+
}
|
|
705
|
+
seen.add(logical);
|
|
706
|
+
totalBytes += bytes.byteLength;
|
|
707
|
+
files.push({
|
|
708
|
+
path: logical,
|
|
709
|
+
sha256: createHash("sha256").update(bytes).digest("hex"),
|
|
710
|
+
byteSize: bytes.byteLength,
|
|
711
|
+
mediaType,
|
|
712
|
+
bytes,
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
return files.sort((a, b) => a.path.localeCompare(b.path));
|
|
716
|
+
}
|
|
717
|
+
function collectRelativeImageRefs(markdown) {
|
|
718
|
+
const refs = [];
|
|
719
|
+
const imageRe = /!\[[^\]]*]\(([^)\s]+)(?:\s+"[^"]*")?\)/g;
|
|
720
|
+
for (const match of markdown.matchAll(imageRe)) {
|
|
721
|
+
const raw = match[1];
|
|
722
|
+
if (!raw)
|
|
723
|
+
continue;
|
|
724
|
+
if (/^(?:https?:)?\/\//i.test(raw) ||
|
|
725
|
+
raw.startsWith("/") ||
|
|
726
|
+
/^[a-z][a-z0-9+.-]*:/i.test(raw)) {
|
|
727
|
+
continue;
|
|
728
|
+
}
|
|
729
|
+
refs.push(raw);
|
|
730
|
+
}
|
|
731
|
+
return refs;
|
|
732
|
+
}
|
|
733
|
+
function normalizeLiveDocAssetLogicalPath(rawSrc) {
|
|
734
|
+
if (!rawSrc || rawSrc !== rawSrc.normalize("NFC"))
|
|
735
|
+
return null;
|
|
736
|
+
if (rawSrc.includes("\\") ||
|
|
737
|
+
[...rawSrc].some((char) => {
|
|
738
|
+
const codePoint = char.codePointAt(0) ?? 0;
|
|
739
|
+
return codePoint <= 0x1f || codePoint === 0x7f;
|
|
740
|
+
}) ||
|
|
741
|
+
/%(?:2f|5c)/i.test(rawSrc)) {
|
|
742
|
+
return null;
|
|
743
|
+
}
|
|
744
|
+
let relativePath = rawSrc;
|
|
745
|
+
if (relativePath.startsWith("./"))
|
|
746
|
+
relativePath = relativePath.slice(2);
|
|
747
|
+
let segments = relativePath.split("/");
|
|
748
|
+
if (!segments.length ||
|
|
749
|
+
segments.some((segment) => !segment || segment === "." || segment === "..")) {
|
|
750
|
+
return null;
|
|
751
|
+
}
|
|
752
|
+
// Match publish `normalizeLiveDocRelativeAssetPath`: a leading on-disk
|
|
753
|
+
// `assets/` folder is the deploy mount — do not emit `/assets/assets/…`.
|
|
754
|
+
if (segments[0] === "assets") {
|
|
755
|
+
segments = segments.slice(1);
|
|
756
|
+
}
|
|
757
|
+
if (!segments.length)
|
|
758
|
+
return null;
|
|
759
|
+
return `/assets/${segments.join("/")}`;
|
|
760
|
+
}
|
|
761
|
+
function liveDocAssetMediaType(path) {
|
|
762
|
+
const extension = path.slice(path.lastIndexOf(".")).toLowerCase();
|
|
763
|
+
return LIVE_DOC_ASSET_MEDIA_TYPES[extension] ?? null;
|
|
764
|
+
}
|
|
765
|
+
async function uploadMarkdownAssets(markdownPath, markdown, deps) {
|
|
766
|
+
const files = await scanMarkdownAssets(markdownPath, markdown, deps);
|
|
767
|
+
if (files.length === 0)
|
|
768
|
+
return null;
|
|
769
|
+
const manifest = files.map(({ bytes: _bytes, ...file }) => file);
|
|
770
|
+
const upload = await requestJson(deps, "/uploads", {
|
|
771
|
+
method: "POST",
|
|
772
|
+
body: {
|
|
773
|
+
kind: "live-doc-assets",
|
|
774
|
+
manifest,
|
|
775
|
+
declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
|
|
776
|
+
},
|
|
777
|
+
headers: { "idempotency-key": randomUUID() },
|
|
778
|
+
});
|
|
779
|
+
const beforeFilePut = createHtmlUploadPacer(deps);
|
|
780
|
+
for (const plan of upload.files) {
|
|
781
|
+
const file = files.find((candidate) => candidate.path === plan.path);
|
|
782
|
+
if (!file)
|
|
783
|
+
throw new Error("Server returned an unexpected upload file");
|
|
784
|
+
await beforeFilePut();
|
|
785
|
+
await requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) });
|
|
786
|
+
}
|
|
787
|
+
await requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
|
|
788
|
+
method: "POST",
|
|
789
|
+
body: {},
|
|
790
|
+
headers: { "idempotency-key": randomUUID() },
|
|
791
|
+
});
|
|
792
|
+
return { uploadId: upload.uploadId, manifestHash: upload.manifestHash };
|
|
793
|
+
}
|
|
794
|
+
async function unpublish(args, deps) {
|
|
795
|
+
const parsed = parseFlags(args);
|
|
796
|
+
const id = parsed.positionals[0];
|
|
797
|
+
if (!id || parsed.positionals.length !== 1)
|
|
798
|
+
throw new Error("Usage: foleo unpublish <id> [--json]");
|
|
799
|
+
const result = await requestJson(deps, `/docs/${encodeURIComponent(id)}/unpublish`, {
|
|
800
|
+
method: "POST",
|
|
801
|
+
body: {},
|
|
802
|
+
});
|
|
803
|
+
writeResult(deps, result, parsed.json);
|
|
804
|
+
return 0;
|
|
805
|
+
}
|
|
806
|
+
async function status(args, deps) {
|
|
807
|
+
const parsed = parseFlags(args);
|
|
808
|
+
const id = parsed.positionals[0];
|
|
809
|
+
if (!id || parsed.positionals.length !== 1) {
|
|
810
|
+
throw new Error("Usage: foleo status <id> [--json]");
|
|
811
|
+
}
|
|
812
|
+
const result = await requestJson(deps, `/docs/${encodeURIComponent(id)}`, {
|
|
813
|
+
method: "GET",
|
|
814
|
+
body: undefined,
|
|
815
|
+
});
|
|
816
|
+
writeStatusResult(deps, result, parsed.json);
|
|
817
|
+
return 0;
|
|
818
|
+
}
|
|
819
|
+
async function list(args, deps) {
|
|
820
|
+
const parsed = parseFlags(args);
|
|
821
|
+
if (parsed.positionals.length > 0 ||
|
|
822
|
+
!["all", "docs", "html"].includes(parsed.kind ?? "all")) {
|
|
823
|
+
throw new Error("Usage: foleo list [--kind all|docs|html] [--limit <n>] [--json]");
|
|
824
|
+
}
|
|
825
|
+
const credential = await resolveCredentialWithSource(deps, {
|
|
826
|
+
mintAppSession: false,
|
|
827
|
+
});
|
|
828
|
+
if (!credential)
|
|
829
|
+
throw new Error("No Foleo credential found. Run `foleo login` or set FOLEO_TOKEN.");
|
|
830
|
+
const kind = parsed.kind ?? "all";
|
|
831
|
+
const [docsResult, htmlResult] = await Promise.all([
|
|
832
|
+
kind === "html"
|
|
833
|
+
? Promise.resolve(null)
|
|
834
|
+
: requestJsonWithToken(deps, "/docs", credential.token, { method: "GET", body: undefined }),
|
|
835
|
+
kind === "docs"
|
|
836
|
+
? Promise.resolve(null)
|
|
837
|
+
: requestJsonWithToken(deps, "/artifacts/html", credential.token, { method: "GET", body: undefined }).catch((error) => {
|
|
838
|
+
if (error instanceof ApiRequestError &&
|
|
839
|
+
error.status === 404 &&
|
|
840
|
+
kind === "all")
|
|
841
|
+
return null;
|
|
842
|
+
throw error;
|
|
843
|
+
}),
|
|
844
|
+
]);
|
|
845
|
+
const docs = docsResult && Array.isArray(docsResult.docs) ? docsResult.docs : [];
|
|
846
|
+
const html = htmlResult && Array.isArray(htmlResult.artifacts)
|
|
847
|
+
? htmlResult.artifacts
|
|
848
|
+
: [];
|
|
849
|
+
const allItems = [
|
|
850
|
+
...docs.map((item) => ({
|
|
851
|
+
...(isRecord(item) ? item : { value: item }),
|
|
852
|
+
kind: "doc",
|
|
853
|
+
})),
|
|
854
|
+
...html.map((item) => ({
|
|
855
|
+
...(isRecord(item) ? item : { value: item }),
|
|
856
|
+
kind: "html",
|
|
857
|
+
})),
|
|
858
|
+
];
|
|
859
|
+
const items = parsed.limit === undefined ? allItems : allItems.slice(0, parsed.limit);
|
|
860
|
+
const truncated = docs.length === 500 ? { docs: true } : undefined;
|
|
861
|
+
const result = {
|
|
862
|
+
items,
|
|
863
|
+
...(truncated ? { truncated } : {}),
|
|
864
|
+
credentialSource: credential.source,
|
|
865
|
+
...(kind === "all" && htmlResult === null
|
|
866
|
+
? { unavailable: { html: true } }
|
|
867
|
+
: {}),
|
|
868
|
+
};
|
|
869
|
+
if (parsed.json) {
|
|
870
|
+
deps.stdout(`${JSON.stringify(result, null, 2)}\n`);
|
|
871
|
+
return 0;
|
|
872
|
+
}
|
|
873
|
+
if (items.length === 0) {
|
|
874
|
+
deps.stdout("No published artifacts.\n");
|
|
875
|
+
return 0;
|
|
876
|
+
}
|
|
877
|
+
for (const item of items)
|
|
878
|
+
deps.stdout(`${artifactLine(item)}\n`);
|
|
879
|
+
if (truncated)
|
|
880
|
+
deps.stderr("Warning: Markdown results reached the 500-item server limit and may be incomplete.\n");
|
|
881
|
+
if (kind === "all" && htmlResult === null)
|
|
882
|
+
deps.stderr("Note: HTML publishing is unavailable for this account; Markdown results are shown.\n");
|
|
883
|
+
return 0;
|
|
884
|
+
}
|
|
885
|
+
async function whoami(args, deps) {
|
|
886
|
+
const parsed = parseFlags(args);
|
|
887
|
+
if (parsed.positionals.length > 0)
|
|
888
|
+
throw new Error("Usage: foleo whoami [--json]");
|
|
889
|
+
const credential = await resolveCredentialWithSource(deps, {
|
|
890
|
+
mintAppSession: false,
|
|
891
|
+
});
|
|
892
|
+
if (!credential)
|
|
893
|
+
throw new Error("No Foleo credential found. Run `foleo login` or set FOLEO_TOKEN.");
|
|
894
|
+
const result = await requestJsonWithToken(deps, "/me", credential.token, {
|
|
895
|
+
method: "GET",
|
|
896
|
+
body: undefined,
|
|
897
|
+
});
|
|
898
|
+
if (parsed.json) {
|
|
899
|
+
deps.stdout(`${JSON.stringify({ ...(isRecord(result) ? result : { me: result }), credentialSource: credential.source, environment: environmentInfo(deps) }, null, 2)}\n`);
|
|
900
|
+
return 0;
|
|
901
|
+
}
|
|
902
|
+
deps.stdout(`${whoamiText(result, credential.source)}Environment: ${environmentInfo(deps).name}\nAPI: ${environmentInfo(deps).apiBase}\n`);
|
|
903
|
+
return 0;
|
|
904
|
+
}
|
|
905
|
+
function environmentCommand(args, deps) {
|
|
906
|
+
const parsed = parseFlags(args);
|
|
907
|
+
if (parsed.positionals.length > 0)
|
|
908
|
+
throw new Error("Usage: foleo environment [--json]");
|
|
909
|
+
const info = environmentInfo(deps);
|
|
910
|
+
if (parsed.json)
|
|
911
|
+
deps.stdout(`${JSON.stringify(info, null, 2)}\n`);
|
|
912
|
+
else
|
|
913
|
+
deps.stdout(`Environment: ${info.name}\nAPI: ${info.apiBase}\n`);
|
|
914
|
+
return 0;
|
|
915
|
+
}
|
|
916
|
+
async function requestJson(deps, path, init) {
|
|
917
|
+
const credential = await resolveCredentialWithSource(deps, {
|
|
918
|
+
mintAppSession: init.mintAppSession ?? init.method !== "GET",
|
|
919
|
+
});
|
|
920
|
+
if (!credential)
|
|
921
|
+
throw new Error("No Foleo credential found. Run `foleo login` or set FOLEO_TOKEN.");
|
|
922
|
+
return requestJsonWithToken(deps, path, credential.token, init);
|
|
923
|
+
}
|
|
924
|
+
async function requestJsonWithToken(deps, path, token, init) {
|
|
925
|
+
const headers = init.body === undefined
|
|
926
|
+
? { authorization: `Bearer ${token}`, ...init.headers }
|
|
927
|
+
: {
|
|
928
|
+
authorization: `Bearer ${token}`,
|
|
929
|
+
"content-type": "application/json",
|
|
930
|
+
...init.headers,
|
|
931
|
+
};
|
|
932
|
+
const response = await deps.fetch(`${apiBase(deps)}${path}`, {
|
|
933
|
+
method: init.method,
|
|
934
|
+
headers,
|
|
935
|
+
...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
|
|
936
|
+
});
|
|
937
|
+
const body = await response.json().catch(() => null);
|
|
938
|
+
if (!response.ok) {
|
|
939
|
+
const code = body !== null &&
|
|
940
|
+
typeof body === "object" &&
|
|
941
|
+
"error" in body &&
|
|
942
|
+
typeof body.error === "object" &&
|
|
943
|
+
body.error !== null &&
|
|
944
|
+
"code" in body.error
|
|
945
|
+
? String(body.error.code)
|
|
946
|
+
: `HTTP ${response.status}`;
|
|
947
|
+
throw new ApiRequestError(response.status, code);
|
|
948
|
+
}
|
|
949
|
+
return body;
|
|
950
|
+
}
|
|
951
|
+
class ApiRequestError extends Error {
|
|
952
|
+
status;
|
|
953
|
+
code;
|
|
954
|
+
constructor(status, code) {
|
|
955
|
+
super(`Foleo API error: ${code}`);
|
|
956
|
+
this.status = status;
|
|
957
|
+
this.code = code;
|
|
958
|
+
this.name = "ApiRequestError";
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
async function requestPublicJson(deps, path, body) {
|
|
962
|
+
const response = await deps.fetch(`${apiBase(deps)}${path}`, {
|
|
963
|
+
method: "POST",
|
|
964
|
+
headers: { "content-type": "application/json" },
|
|
965
|
+
body: JSON.stringify(body),
|
|
966
|
+
});
|
|
967
|
+
const parsed = await response.json().catch(() => null);
|
|
968
|
+
if (!response.ok)
|
|
969
|
+
throw apiResponseError(response.status, parsed);
|
|
970
|
+
return parsed;
|
|
971
|
+
}
|
|
972
|
+
async function requestRaw(deps, path, body, headers) {
|
|
973
|
+
const credential = await resolveCredentialWithSource(deps, {
|
|
974
|
+
mintAppSession: true,
|
|
975
|
+
});
|
|
976
|
+
if (!credential)
|
|
977
|
+
throw new Error("No Foleo credential found. Run `foleo login` or set FOLEO_TOKEN.");
|
|
978
|
+
const bytes = body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength);
|
|
979
|
+
const response = await deps.fetch(`${apiBase(deps)}${path}`, {
|
|
980
|
+
method: "PUT",
|
|
981
|
+
headers: { authorization: `Bearer ${credential.token}`, ...headers },
|
|
982
|
+
body: bytes,
|
|
983
|
+
});
|
|
984
|
+
if (!response.ok)
|
|
985
|
+
throw new Error(`Foleo API error: HTTP ${response.status}`);
|
|
986
|
+
}
|
|
987
|
+
function apiResponseError(status, body) {
|
|
988
|
+
const code = body !== null &&
|
|
989
|
+
typeof body === "object" &&
|
|
990
|
+
"error" in body &&
|
|
991
|
+
typeof body.error === "object" &&
|
|
992
|
+
body.error !== null &&
|
|
993
|
+
"code" in body.error
|
|
994
|
+
? String(body.error.code)
|
|
995
|
+
: `HTTP ${status}`;
|
|
996
|
+
return new Error(`Foleo API error: ${code}`);
|
|
997
|
+
}
|
|
998
|
+
function apiBase(deps) {
|
|
999
|
+
const selected = deps.env.FOLEO_ENV ?? "production";
|
|
1000
|
+
const known = {
|
|
1001
|
+
production: "https://api.foleo.app/v1",
|
|
1002
|
+
staging: "https://api-staging.foleo.app/v1",
|
|
1003
|
+
local: "http://127.0.0.1:8787/v1",
|
|
1004
|
+
};
|
|
1005
|
+
if (!deps.env.FOLEO_API_BASE && !(selected in known))
|
|
1006
|
+
throw new Error("FOLEO_ENV must be production, staging, or local");
|
|
1007
|
+
const url = new URL(deps.env.FOLEO_API_BASE ?? known[selected]);
|
|
1008
|
+
if (url.username || url.password || url.search || url.hash)
|
|
1009
|
+
throw new Error("FOLEO_API_BASE must not contain credentials, query parameters, or a fragment");
|
|
1010
|
+
if (url.protocol !== "https:" &&
|
|
1011
|
+
!(url.protocol === "http:" &&
|
|
1012
|
+
["127.0.0.1", "localhost", "::1", "[::1]"].includes(url.hostname)))
|
|
1013
|
+
throw new Error("FOLEO_API_BASE must use HTTPS except for loopback development");
|
|
1014
|
+
return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
|
|
1015
|
+
}
|
|
1016
|
+
function environmentInfo(deps) {
|
|
1017
|
+
const base = apiBase(deps);
|
|
1018
|
+
const name = deps.env.FOLEO_API_BASE
|
|
1019
|
+
? "custom"
|
|
1020
|
+
: deps.env.FOLEO_ENV === "staging"
|
|
1021
|
+
? "staging"
|
|
1022
|
+
: deps.env.FOLEO_ENV === "local"
|
|
1023
|
+
? "local"
|
|
1024
|
+
: "production";
|
|
1025
|
+
return { name, apiBase: base };
|
|
1026
|
+
}
|
|
1027
|
+
function announceApi(deps, json) {
|
|
1028
|
+
if (!json)
|
|
1029
|
+
deps.stderr(`API: ${apiBase(deps)}\n`);
|
|
1030
|
+
}
|
|
1031
|
+
function errorMessage(error) {
|
|
1032
|
+
return error instanceof Error ? error.message : String(error);
|
|
1033
|
+
}
|
|
1034
|
+
async function resolveCredentialWithSource(deps, options = {}) {
|
|
1035
|
+
if (deps.env.FOLEO_TOKEN)
|
|
1036
|
+
return { token: deps.env.FOLEO_TOKEN, source: "env" };
|
|
1037
|
+
const base = apiBase(deps);
|
|
1038
|
+
const cliToken = await (deps.loadCredential ?? loadKeychainCredential)(base);
|
|
1039
|
+
if (cliToken)
|
|
1040
|
+
return { token: cliToken, source: "cli-keychain" };
|
|
1041
|
+
if (deps.env.FOLEO_NO_APP_SESSION === "1")
|
|
1042
|
+
return null;
|
|
1043
|
+
const appSessionToken = await (deps.loadAppSession ?? loadAppSessionCredential)(base);
|
|
1044
|
+
if (!appSessionToken)
|
|
1045
|
+
return null;
|
|
1046
|
+
if (options.mintAppSession)
|
|
1047
|
+
await mintAndCacheCliKey(deps, base, appSessionToken).catch(() => undefined);
|
|
1048
|
+
return { token: appSessionToken, source: "app-session" };
|
|
1049
|
+
}
|
|
1050
|
+
async function mintAndCacheCliKey(deps, base, appSessionToken) {
|
|
1051
|
+
const saveCredential = deps.saveCredential ?? saveKeychainCredential;
|
|
1052
|
+
const key = await requestJsonWithToken(deps, "/keys", appSessionToken, {
|
|
1053
|
+
method: "POST",
|
|
1054
|
+
body: { name: "Foleo CLI", scopes: CLI_KEY_SCOPES },
|
|
1055
|
+
});
|
|
1056
|
+
if (!isRecord(key) || typeof key.token !== "string" || key.token.length === 0)
|
|
1057
|
+
throw new Error("Foleo API did not return a CLI key token");
|
|
1058
|
+
await saveCredential(base, key.token);
|
|
1059
|
+
}
|
|
1060
|
+
function keychainAccount(apiBaseUrl) {
|
|
1061
|
+
return createHash("sha256").update(apiBaseUrl).digest("hex");
|
|
1062
|
+
}
|
|
1063
|
+
async function keyringAsyncEntry() {
|
|
1064
|
+
const module = (await Function("specifier", "return import(specifier)")("@napi-rs/keyring"));
|
|
1065
|
+
return module.AsyncEntry;
|
|
1066
|
+
}
|
|
1067
|
+
async function keychainEntry(apiBaseUrl, suffix = "") {
|
|
1068
|
+
const AsyncEntry = await keyringAsyncEntry();
|
|
1069
|
+
return new AsyncEntry(KEYCHAIN_SERVICE, `${keychainAccount(apiBaseUrl)}${suffix}`);
|
|
1070
|
+
}
|
|
1071
|
+
async function appSessionKeychainEntry(apiBaseUrl) {
|
|
1072
|
+
const AsyncEntry = await keyringAsyncEntry();
|
|
1073
|
+
return new AsyncEntry(APP_SESSION_KEYCHAIN_SERVICE, `desktop-app-session:${keychainAccount(apiBaseUrl)}`);
|
|
1074
|
+
}
|
|
1075
|
+
async function loadKeychainCredential(apiBaseUrl) {
|
|
1076
|
+
try {
|
|
1077
|
+
return (await (await keychainEntry(apiBaseUrl)).getPassword()) ?? null;
|
|
1078
|
+
}
|
|
1079
|
+
catch {
|
|
1080
|
+
return null;
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
async function loadAppSessionCredential(apiBaseUrl) {
|
|
1084
|
+
try {
|
|
1085
|
+
return ((await (await appSessionKeychainEntry(apiBaseUrl)).getPassword()) ?? null);
|
|
1086
|
+
}
|
|
1087
|
+
catch {
|
|
1088
|
+
return null;
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
async function saveKeychainCredential(apiBaseUrl, token) {
|
|
1092
|
+
await (await keychainEntry(apiBaseUrl)).setPassword(token);
|
|
1093
|
+
}
|
|
1094
|
+
async function deleteKeychainCredential(apiBaseUrl) {
|
|
1095
|
+
await (await keychainEntry(apiBaseUrl)).deleteCredential();
|
|
1096
|
+
}
|
|
1097
|
+
async function verifyKeychainWritable(apiBaseUrl) {
|
|
1098
|
+
const entry = await keychainEntry(apiBaseUrl, ":probe");
|
|
1099
|
+
const probe = `foleo_probe_${randomUUID()}`;
|
|
1100
|
+
try {
|
|
1101
|
+
await entry.setPassword(probe);
|
|
1102
|
+
if ((await entry.getPassword()) !== probe)
|
|
1103
|
+
throw new Error("macOS Keychain verification failed");
|
|
1104
|
+
}
|
|
1105
|
+
catch (error) {
|
|
1106
|
+
throw new Error(`Unable to use macOS Keychain: ${error instanceof Error ? error.message : String(error)}`);
|
|
1107
|
+
}
|
|
1108
|
+
finally {
|
|
1109
|
+
await entry.deleteCredential().catch(() => undefined);
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
async function openBrowser(url) {
|
|
1113
|
+
await new Promise((resolveOpen, rejectOpen) => {
|
|
1114
|
+
const child = spawn("open", [url], { stdio: "ignore" });
|
|
1115
|
+
child.once("error", rejectOpen);
|
|
1116
|
+
child.once("spawn", () => {
|
|
1117
|
+
child.unref();
|
|
1118
|
+
resolveOpen();
|
|
1119
|
+
});
|
|
1120
|
+
});
|
|
1121
|
+
}
|
|
1122
|
+
export async function createLoopbackCallback(nonce, timeoutMs = 5 * 60_000) {
|
|
1123
|
+
let resolveCode;
|
|
1124
|
+
let rejectCode;
|
|
1125
|
+
let settled = false;
|
|
1126
|
+
const codePromise = new Promise((resolvePromise, rejectPromise) => {
|
|
1127
|
+
resolveCode = resolvePromise;
|
|
1128
|
+
rejectCode = rejectPromise;
|
|
1129
|
+
});
|
|
1130
|
+
let closePromise = null;
|
|
1131
|
+
const server = createServer((request, response) => {
|
|
1132
|
+
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
1133
|
+
const code = url.searchParams.get("code");
|
|
1134
|
+
const receivedNonce = url.searchParams.get("nonce");
|
|
1135
|
+
if (settled ||
|
|
1136
|
+
request.method !== "GET" ||
|
|
1137
|
+
url.pathname !== "/publish-auth/callback" ||
|
|
1138
|
+
!code ||
|
|
1139
|
+
receivedNonce !== nonce) {
|
|
1140
|
+
response.writeHead(400, callbackHeaders("text/plain; charset=utf-8"));
|
|
1141
|
+
response.end("Invalid Foleo sign-in callback.");
|
|
1142
|
+
return;
|
|
1143
|
+
}
|
|
1144
|
+
response.writeHead(200, callbackHeaders("text/html; charset=utf-8"));
|
|
1145
|
+
response.end('<!doctype html><meta charset="utf-8"><title>Foleo sign-in complete</title><p>Foleo CLI is signed in. You can close this tab.</p>');
|
|
1146
|
+
settled = true;
|
|
1147
|
+
resolveCode(code);
|
|
1148
|
+
void closeServer();
|
|
1149
|
+
response.once("finish", () => server.closeAllConnections());
|
|
1150
|
+
});
|
|
1151
|
+
const closeServer = (force = false) => {
|
|
1152
|
+
if (closePromise) {
|
|
1153
|
+
if (force)
|
|
1154
|
+
server.closeAllConnections();
|
|
1155
|
+
return closePromise;
|
|
1156
|
+
}
|
|
1157
|
+
closePromise = new Promise((resolveClose) => {
|
|
1158
|
+
if (!server.listening) {
|
|
1159
|
+
resolveClose();
|
|
1160
|
+
return;
|
|
1161
|
+
}
|
|
1162
|
+
server.close(() => resolveClose());
|
|
1163
|
+
});
|
|
1164
|
+
if (force)
|
|
1165
|
+
server.closeAllConnections();
|
|
1166
|
+
return closePromise;
|
|
1167
|
+
};
|
|
1168
|
+
await new Promise((resolveListen, rejectListen) => {
|
|
1169
|
+
server.once("error", rejectListen);
|
|
1170
|
+
server.listen(0, "127.0.0.1", resolveListen);
|
|
1171
|
+
});
|
|
1172
|
+
const address = server.address();
|
|
1173
|
+
if (address === null || typeof address === "string") {
|
|
1174
|
+
server.close();
|
|
1175
|
+
throw new Error("Unable to bind Foleo CLI callback server");
|
|
1176
|
+
}
|
|
1177
|
+
const timeout = setTimeout(() => {
|
|
1178
|
+
if (!settled) {
|
|
1179
|
+
settled = true;
|
|
1180
|
+
rejectCode(new Error("Foleo sign-in timed out"));
|
|
1181
|
+
codePromise.catch(() => undefined);
|
|
1182
|
+
void closeServer(true);
|
|
1183
|
+
}
|
|
1184
|
+
}, timeoutMs);
|
|
1185
|
+
timeout.unref();
|
|
1186
|
+
return {
|
|
1187
|
+
callbackUrl: `http://127.0.0.1:${address.port}/publish-auth/callback`,
|
|
1188
|
+
waitForCode: () => codePromise,
|
|
1189
|
+
close: async () => {
|
|
1190
|
+
clearTimeout(timeout);
|
|
1191
|
+
if (!settled) {
|
|
1192
|
+
settled = true;
|
|
1193
|
+
rejectCode(new Error("Foleo sign-in cancelled"));
|
|
1194
|
+
codePromise.catch(() => undefined);
|
|
1195
|
+
}
|
|
1196
|
+
await closeServer(true);
|
|
1197
|
+
},
|
|
1198
|
+
};
|
|
1199
|
+
}
|
|
1200
|
+
function callbackHeaders(contentType) {
|
|
1201
|
+
return {
|
|
1202
|
+
"content-type": contentType,
|
|
1203
|
+
"cache-control": "no-store",
|
|
1204
|
+
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'",
|
|
1205
|
+
"x-content-type-options": "nosniff",
|
|
1206
|
+
"referrer-policy": "no-referrer",
|
|
1207
|
+
};
|
|
1208
|
+
}
|
|
1209
|
+
function isRecord(value) {
|
|
1210
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1211
|
+
}
|
|
1212
|
+
function stringField(value, field) {
|
|
1213
|
+
return isRecord(value) &&
|
|
1214
|
+
typeof value[field] === "string" &&
|
|
1215
|
+
value[field].length > 0
|
|
1216
|
+
? value[field]
|
|
1217
|
+
: null;
|
|
1218
|
+
}
|
|
1219
|
+
function artifactLine(artifact) {
|
|
1220
|
+
const kind = stringField(artifact, "kind") ?? "-";
|
|
1221
|
+
const id = stringField(artifact, "id") ?? "-";
|
|
1222
|
+
const url = stringField(artifact, "url") ?? "-";
|
|
1223
|
+
const status = stringField(artifact, "status") ?? "-";
|
|
1224
|
+
const visibility = stringField(artifact, "visibility") ?? "-";
|
|
1225
|
+
const title = stringField(artifact, "title");
|
|
1226
|
+
return [kind, id, url, status, visibility, ...(title ? [title] : [])].join(" ");
|
|
1227
|
+
}
|
|
1228
|
+
function nestedRecord(value, field) {
|
|
1229
|
+
return isRecord(value) && isRecord(value[field]) ? value[field] : null;
|
|
1230
|
+
}
|
|
1231
|
+
function stringList(value) {
|
|
1232
|
+
return Array.isArray(value)
|
|
1233
|
+
? value.map((item) => String(item)).filter((item) => item.length > 0)
|
|
1234
|
+
: [];
|
|
1235
|
+
}
|
|
1236
|
+
function whoamiText(value, source) {
|
|
1237
|
+
const explicitActor = nestedRecord(value, "actor");
|
|
1238
|
+
const user = nestedRecord(value, "user");
|
|
1239
|
+
const actor = explicitActor ?? user ?? (isRecord(value) ? value : {});
|
|
1240
|
+
const org = nestedRecord(value, "org");
|
|
1241
|
+
const scopes = stringList(isRecord(value) ? value.scopes : undefined);
|
|
1242
|
+
const actorType = stringField(actor, "type") ?? (user ? "user" : "-");
|
|
1243
|
+
const lines = [
|
|
1244
|
+
`Credential source: ${source}`,
|
|
1245
|
+
`Actor: ${actorType} ${stringField(actor, "id") ?? "-"}`,
|
|
1246
|
+
];
|
|
1247
|
+
const email = stringField(actor, "email") ??
|
|
1248
|
+
(isRecord(value) ? stringField(value, "email") : null);
|
|
1249
|
+
const name = stringField(actor, "name") ??
|
|
1250
|
+
(isRecord(value) ? stringField(value, "name") : null);
|
|
1251
|
+
const orgHandle = org
|
|
1252
|
+
? stringField(org, "handle")
|
|
1253
|
+
: isRecord(value)
|
|
1254
|
+
? stringField(value, "orgHandle")
|
|
1255
|
+
: null;
|
|
1256
|
+
if (email)
|
|
1257
|
+
lines.push(`Email: ${email}`);
|
|
1258
|
+
if (name)
|
|
1259
|
+
lines.push(`Name: ${name}`);
|
|
1260
|
+
if (orgHandle)
|
|
1261
|
+
lines.push(`Org: ${orgHandle}`);
|
|
1262
|
+
lines.push(`Scopes: ${scopes.length > 0 ? scopes.join(", ") : "-"}`);
|
|
1263
|
+
return `${lines.join("\n")}\n`;
|
|
1264
|
+
}
|
|
1265
|
+
function writeResult(deps, result, json) {
|
|
1266
|
+
if (json) {
|
|
1267
|
+
deps.stdout(`${JSON.stringify(result, null, 2)}\n`);
|
|
1268
|
+
return;
|
|
1269
|
+
}
|
|
1270
|
+
if (result !== null && typeof result === "object" && "url" in result) {
|
|
1271
|
+
deps.stdout(`${String(result.url)}\n`);
|
|
1272
|
+
return;
|
|
1273
|
+
}
|
|
1274
|
+
deps.stdout(`${JSON.stringify(result)}\n`);
|
|
1275
|
+
}
|
|
1276
|
+
function writeStatusResult(deps, result, json) {
|
|
1277
|
+
if (json) {
|
|
1278
|
+
writeResult(deps, result, true);
|
|
1279
|
+
return;
|
|
1280
|
+
}
|
|
1281
|
+
if (!isRecord(result)) {
|
|
1282
|
+
writeResult(deps, result, false);
|
|
1283
|
+
return;
|
|
1284
|
+
}
|
|
1285
|
+
const lines = [
|
|
1286
|
+
`ID: ${stringField(result, "id") ?? "-"}`,
|
|
1287
|
+
`URL: ${stringField(result, "url") ?? "-"}`,
|
|
1288
|
+
`Status: ${stringField(result, "status") ?? "-"}`,
|
|
1289
|
+
`Visibility: ${stringField(result, "visibility") ?? "-"}`,
|
|
1290
|
+
];
|
|
1291
|
+
if (typeof result.version === "number")
|
|
1292
|
+
lines.push(`Version: ${result.version}`);
|
|
1293
|
+
if (typeof result.stateRevision === "number")
|
|
1294
|
+
lines.push(`State revision: ${result.stateRevision}`);
|
|
1295
|
+
const title = stringField(result, "title");
|
|
1296
|
+
if (title)
|
|
1297
|
+
lines.push(`Title: ${title}`);
|
|
1298
|
+
deps.stdout(`${lines.join("\n")}\n`);
|
|
1299
|
+
}
|
|
1300
|
+
function parseFlags(args) {
|
|
1301
|
+
const positionals = [];
|
|
1302
|
+
let json = false;
|
|
1303
|
+
let title;
|
|
1304
|
+
let version;
|
|
1305
|
+
let revision;
|
|
1306
|
+
let kind;
|
|
1307
|
+
let set;
|
|
1308
|
+
let password;
|
|
1309
|
+
let limit;
|
|
1310
|
+
let acceptHostingRisk = false;
|
|
1311
|
+
for (let i = 0; i < args.length; i++) {
|
|
1312
|
+
const arg = args[i];
|
|
1313
|
+
if (arg === "--json") {
|
|
1314
|
+
json = true;
|
|
1315
|
+
continue;
|
|
1316
|
+
}
|
|
1317
|
+
if (arg === "--title") {
|
|
1318
|
+
title = args[++i];
|
|
1319
|
+
if (!title)
|
|
1320
|
+
throw new Error("--title requires a value");
|
|
1321
|
+
continue;
|
|
1322
|
+
}
|
|
1323
|
+
if (arg === "--version") {
|
|
1324
|
+
const raw = args[++i];
|
|
1325
|
+
const parsed = raw === undefined ? Number.NaN : Number(raw);
|
|
1326
|
+
if (!Number.isInteger(parsed))
|
|
1327
|
+
throw new Error("--version requires an integer");
|
|
1328
|
+
version = parsed;
|
|
1329
|
+
continue;
|
|
1330
|
+
}
|
|
1331
|
+
if (arg === "--revision") {
|
|
1332
|
+
const raw = args[++i];
|
|
1333
|
+
const parsed = raw === undefined ? Number.NaN : Number(raw);
|
|
1334
|
+
if (!Number.isInteger(parsed))
|
|
1335
|
+
throw new Error("--revision requires an integer");
|
|
1336
|
+
revision = parsed;
|
|
1337
|
+
continue;
|
|
1338
|
+
}
|
|
1339
|
+
if (arg === "--kind") {
|
|
1340
|
+
kind = args[++i];
|
|
1341
|
+
if (!kind)
|
|
1342
|
+
throw new Error("--kind requires a value");
|
|
1343
|
+
continue;
|
|
1344
|
+
}
|
|
1345
|
+
if (arg === "--set") {
|
|
1346
|
+
set = args[++i];
|
|
1347
|
+
if (!set)
|
|
1348
|
+
throw new Error("--set requires a value");
|
|
1349
|
+
continue;
|
|
1350
|
+
}
|
|
1351
|
+
if (arg === "--password") {
|
|
1352
|
+
password = args[++i];
|
|
1353
|
+
if (!password)
|
|
1354
|
+
throw new Error("--password requires a value");
|
|
1355
|
+
continue;
|
|
1356
|
+
}
|
|
1357
|
+
if (arg === "--limit") {
|
|
1358
|
+
const raw = args[++i];
|
|
1359
|
+
const parsed = raw === undefined ? Number.NaN : Number(raw);
|
|
1360
|
+
if (!Number.isInteger(parsed) || parsed < 1)
|
|
1361
|
+
throw new Error("--limit requires a positive integer");
|
|
1362
|
+
limit = parsed;
|
|
1363
|
+
continue;
|
|
1364
|
+
}
|
|
1365
|
+
if (arg === "--accept-hosting-risk") {
|
|
1366
|
+
acceptHostingRisk = true;
|
|
1367
|
+
continue;
|
|
1368
|
+
}
|
|
1369
|
+
if (arg.startsWith("-"))
|
|
1370
|
+
throw new Error(`Unknown option: ${arg}`);
|
|
1371
|
+
positionals.push(arg);
|
|
1372
|
+
}
|
|
1373
|
+
return {
|
|
1374
|
+
positionals,
|
|
1375
|
+
json,
|
|
1376
|
+
...(title !== undefined ? { title } : {}),
|
|
1377
|
+
...(version !== undefined ? { version } : {}),
|
|
1378
|
+
...(revision !== undefined ? { revision } : {}),
|
|
1379
|
+
...(kind !== undefined ? { kind } : {}),
|
|
1380
|
+
...(set !== undefined ? { set } : {}),
|
|
1381
|
+
...(password !== undefined ? { password } : {}),
|
|
1382
|
+
...(limit !== undefined ? { limit } : {}),
|
|
1383
|
+
acceptHostingRisk,
|
|
1384
|
+
};
|
|
1385
|
+
}
|
|
1386
|
+
function parseGlobalFlags(argv) {
|
|
1387
|
+
const selected = argv.filter((arg) => ["--production", "--staging", "--local"].includes(arg));
|
|
1388
|
+
if (new Set(selected).size > 1)
|
|
1389
|
+
throw new Error("Choose only one of --production, --staging, or --local");
|
|
1390
|
+
const environment = selected[0]?.slice(2);
|
|
1391
|
+
return {
|
|
1392
|
+
argv: argv.filter((arg) => !["--production", "--staging", "--local"].includes(arg)),
|
|
1393
|
+
...(environment ? { environment } : {}),
|
|
1394
|
+
};
|
|
1395
|
+
}
|
|
1396
|
+
function help() {
|
|
1397
|
+
return [
|
|
1398
|
+
"Usage:",
|
|
1399
|
+
" foleo login [--json]",
|
|
1400
|
+
" foleo whoami [--json]",
|
|
1401
|
+
" foleo doctor [--json]",
|
|
1402
|
+
" foleo skill get|path",
|
|
1403
|
+
" foleo environment [--json]",
|
|
1404
|
+
" foleo list [--kind all|docs|html] [--limit <n>] [--json]",
|
|
1405
|
+
" foleo publish <file> [--title <title>] [--json]",
|
|
1406
|
+
" foleo update <id> <file> --version <version> [--json]",
|
|
1407
|
+
" foleo status <id> [--json]",
|
|
1408
|
+
" foleo unpublish <id> [--json]",
|
|
1409
|
+
" foleo html-publish <bundle-root> --accept-hosting-risk [--json]",
|
|
1410
|
+
" foleo html-update <id> <bundle-root> --revision <stateRevision> [--json]",
|
|
1411
|
+
" foleo html-status <id> [--json]",
|
|
1412
|
+
" foleo html-visibility <id> --set unlisted|password|private --revision <stateRevision> [--json]",
|
|
1413
|
+
" foleo html-password <id> --password <secret> --revision <stateRevision> [--json]",
|
|
1414
|
+
" foleo html-unpublish <id> --revision <stateRevision> [--json]",
|
|
1415
|
+
"",
|
|
1416
|
+
"Environment:",
|
|
1417
|
+
" --production (default), --staging, or --local selects a known API.",
|
|
1418
|
+
" FOLEO_ENV=production|staging|local provides the same selection.",
|
|
1419
|
+
" FOLEO_API_BASE explicitly overrides the selected API.",
|
|
1420
|
+
" FOLEO_TOKEN uses an explicit API token.",
|
|
1421
|
+
" FOLEO_NO_APP_SESSION=1 disables desktop app session reuse.",
|
|
1422
|
+
"",
|
|
1423
|
+
"Agent guidance: https://foleo.app/agents.md",
|
|
1424
|
+
"Foleo MCP is not available during this beta.",
|
|
1425
|
+
"",
|
|
1426
|
+
].join("\n");
|
|
1427
|
+
}
|
|
1428
|
+
const invokedPath = process.argv[1];
|
|
1429
|
+
const isDirectInvocation = invokedPath !== undefined &&
|
|
1430
|
+
(invokedPath.endsWith(`${sep}foleo`) ||
|
|
1431
|
+
(await realpath(invokedPath).then((path) => import.meta.url === pathToFileURL(path).href, () => false)));
|
|
1432
|
+
if (isDirectInvocation) {
|
|
1433
|
+
const code = await runCli(process.argv.slice(2));
|
|
1434
|
+
process.exitCode = code;
|
|
1435
|
+
}
|
|
1436
|
+
//# sourceMappingURL=index.js.map
|