@kanorio/cli 0.0.0-stage → 1.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.
@@ -0,0 +1,682 @@
1
+ /**
2
+ * Subcommand to REST call. Each command only reads its arguments, builds the request and returns the server's JSON.
3
+ * The one convenience: replace-sections reads the page for its updatedAt when ifUnmodifiedSince is not given. That is still two REST calls and no business logic.
4
+ */
5
+ import { execFileSync, spawn } from "node:child_process";
6
+ import { accessSync, chmodSync, constants as fsConstants, existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
7
+ import { dirname, resolve } from "node:path";
8
+ import { createInterface } from "node:readline";
9
+ import { Writable } from "node:stream";
10
+ import { UsageError } from "./args.js";
11
+ import { ApiError, request } from "./client.js";
12
+ import { clearToken, configPath, readConfig, resolveAuth, withConfigLock, writeConfig } from "./config.js";
13
+ import { buildAuthorizeUrl, createPkce, exchangeAuthorizationCode, OAuthLoginError, randomState, refreshTokens, revokeToken, startLoopbackListener, } from "./oauth.js";
14
+ import { generateCollectionTypes } from "./types-codegen.js";
15
+ function need(cli, index, label) {
16
+ const value = cli.positionals[index];
17
+ if (!value)
18
+ throw new UsageError(`Missing <${label}>.`);
19
+ return value;
20
+ }
21
+ function readJsonFile(path) {
22
+ let text;
23
+ try {
24
+ text = readFileSync(path, "utf8");
25
+ }
26
+ catch (error) {
27
+ throw new UsageError(`Cannot read ${path}: ${error instanceof Error ? error.message : String(error)}`);
28
+ }
29
+ try {
30
+ return JSON.parse(text);
31
+ }
32
+ catch {
33
+ throw new UsageError(`${path} is not valid JSON.`);
34
+ }
35
+ }
36
+ /** Refresh the access token when less than this is left, so it does not expire halfway through a request */
37
+ const REFRESH_SKEW_MS = 60_000;
38
+ /**
39
+ * The token for this call. `--token`, `KANORIO_TOKEN` or a stored PAT is used as is; a browser sign-in's access token is refreshed with the refresh token when it is about to expire.
40
+ * The refresh happens under a lock, and the config file is read again once the lock is held (another process may have just refreshed). If the refresh token is rejected (expired or revoked), the sign-in is cleared and the user is asked to sign in again.
41
+ */
42
+ async function resolveToken(cli, ctx) {
43
+ const auth = resolveAuth(cli.flags, ctx.env);
44
+ if (!auth.token) {
45
+ throw new ApiError("UNAUTHORIZED", 401, "Not signed in. Run `kanorio login` or set KANORIO_TOKEN.");
46
+ }
47
+ if (auth.tokenSource !== "oauth" || !auth.oauth || auth.oauth.expiresAt - Date.now() > REFRESH_SKEW_MS) {
48
+ return { token: auth.token, apiUrl: auth.apiUrl };
49
+ }
50
+ return withConfigLock(ctx.env, async () => {
51
+ const current = readConfig(ctx.env);
52
+ const session = current.oauth;
53
+ if (!session || session.apiUrl !== auth.apiUrl) {
54
+ throw new ApiError("UNAUTHORIZED", 401, "Not signed in. Run `kanorio login` or set KANORIO_TOKEN.");
55
+ }
56
+ if (session.expiresAt - Date.now() > REFRESH_SKEW_MS)
57
+ return { token: session.accessToken, apiUrl: auth.apiUrl };
58
+ try {
59
+ const tokens = await refreshTokens({ apiUrl: auth.apiUrl, refreshToken: session.refreshToken, fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent });
60
+ writeConfig({ ...current, oauth: { ...tokens, apiUrl: auth.apiUrl } }, ctx.env);
61
+ return { token: tokens.accessToken, apiUrl: auth.apiUrl };
62
+ }
63
+ catch (error) {
64
+ if (error instanceof OAuthLoginError && error.code === "invalid_grant") {
65
+ clearToken(ctx.env);
66
+ throw new ApiError("UNAUTHORIZED", 401, "The session has expired or was revoked. Run `kanorio login` again.");
67
+ }
68
+ throw error;
69
+ }
70
+ });
71
+ }
72
+ function authed(cli, ctx) {
73
+ // Being signed out must fail before anything is sent (as before: thrown synchronously); the token refresh waits until the call is actually made
74
+ const auth = resolveAuth(cli.flags, ctx.env);
75
+ if (!auth.token) {
76
+ throw new ApiError("UNAUTHORIZED", 401, "Not signed in. Run `kanorio login` or set KANORIO_TOKEN.");
77
+ }
78
+ return {
79
+ apiUrl: auth.apiUrl,
80
+ call: async (method, path, extra = {}) => {
81
+ const { token, apiUrl } = await resolveToken(cli, ctx);
82
+ return request({ apiUrl, token, method, path, fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent, onDeprecation: ctx.onDeprecation, ...extra });
83
+ },
84
+ };
85
+ }
86
+ /** Typing a token interactively does not echo: output goes to a sink and only the prompt is printed by hand */
87
+ async function promptSecret(prompt, stdin) {
88
+ const input = stdin ?? process.stdin;
89
+ if (!input.isTTY) {
90
+ return new Promise((resolve, reject) => {
91
+ let data = "";
92
+ input.setEncoding?.("utf8");
93
+ input.on("data", (chunk) => {
94
+ data += chunk;
95
+ });
96
+ input.on("end", () => resolve(data.trim()));
97
+ input.on("error", reject);
98
+ });
99
+ }
100
+ process.stderr.write(prompt);
101
+ const muted = new Writable({ write: (_chunk, _enc, cb) => cb() });
102
+ const rl = createInterface({ input, output: muted, terminal: true });
103
+ return new Promise((resolve) => {
104
+ rl.question("", (answer) => {
105
+ rl.close();
106
+ process.stderr.write("\n");
107
+ resolve(answer.trim());
108
+ });
109
+ });
110
+ }
111
+ /** A pasted PAT is verified before it is stored, so a bad one is never written (403 means valid but without console:view, which is still stored) */
112
+ async function storePersonalToken(cli, ctx, token) {
113
+ if (!token)
114
+ throw new UsageError("Token is empty.");
115
+ if (!token.startsWith("knr_pat_")) {
116
+ throw new UsageError("Only personal access tokens (knr_pat_…) can be pasted. To sign in without a token, run `kanorio login` and approve it in the browser.");
117
+ }
118
+ const apiUrl = resolveAuth({ api: cli.flags.api }, ctx.env).apiUrl;
119
+ let verified = "ok";
120
+ try {
121
+ await request({ apiUrl, token, method: "GET", path: "/sites", fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent });
122
+ }
123
+ catch (error) {
124
+ if (error instanceof ApiError && error.status === 403)
125
+ verified = "limited";
126
+ else
127
+ throw error;
128
+ }
129
+ const { oauth: _replaced, ...current } = readConfig(ctx.env);
130
+ void _replaced;
131
+ const path = writeConfig({ ...current, token, ...(cli.flags.api ? { apiUrl } : {}) }, ctx.env);
132
+ return {
133
+ stored: path,
134
+ apiUrl,
135
+ tokenPrefix: token.slice(0, 12),
136
+ ...(verified === "limited" ? { warning: "Token lacks console:view; sites list/get will be forbidden." } : {}),
137
+ };
138
+ }
139
+ /**
140
+ * A PAT piped in (`echo $TOKEN | kanorio login`, supported since 1.0). When stdin is not a terminal, wait briefly:
141
+ * data means a token; no data (a coding assistant running the command usually leaves stdin empty or open) means browser sign-in.
142
+ */
143
+ async function readPipedToken(stdin, waitMs = 300) {
144
+ const input = stdin ?? process.stdin;
145
+ if (input.isTTY)
146
+ return null;
147
+ return new Promise((resolve) => {
148
+ let data = "";
149
+ let done = false;
150
+ const finish = (value) => {
151
+ if (done)
152
+ return;
153
+ done = true;
154
+ clearTimeout(timer);
155
+ input.removeListener("data", onData);
156
+ input.removeListener("end", onEnd);
157
+ input.pause?.();
158
+ resolve(value);
159
+ };
160
+ const onData = (chunk) => {
161
+ data += String(chunk);
162
+ // Data arrived: wait for the rest (the pipe will end), no longer bound by the timeout
163
+ clearTimeout(timer);
164
+ };
165
+ const onEnd = () => finish(data.trim() || null);
166
+ const timer = setTimeout(() => finish(null), waitMs);
167
+ input.setEncoding?.("utf8");
168
+ input.on("data", onData);
169
+ input.on("end", onEnd);
170
+ input.on("error", () => finish(null));
171
+ });
172
+ }
173
+ function openInBrowser(url) {
174
+ const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
175
+ try {
176
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
177
+ child.on("error", () => { });
178
+ child.unref();
179
+ }
180
+ catch {
181
+ // Failing to open the browser is not an error: the link is already printed and the user can open it
182
+ }
183
+ }
184
+ /**
185
+ * Browser sign-in: prints (and tries to open) Kanorio's approval page, waits for the user to approve, then stores the tokens in the config file.
186
+ * No key is copied or pasted along the way; when a coding assistant runs the command, it only has to hand the link to the user.
187
+ */
188
+ async function loginWithBrowser(cli, ctx) {
189
+ const apiUrl = resolveAuth({ api: cli.flags.api }, ctx.env).apiUrl;
190
+ const log = ctx.log ?? ((line) => void process.stderr.write(`${line}\n`));
191
+ const listener = await startLoopbackListener();
192
+ try {
193
+ const { verifier, challenge } = createPkce();
194
+ const state = randomState();
195
+ const url = buildAuthorizeUrl({ apiUrl, redirectUri: listener.redirectUri, challenge, state });
196
+ log("Open this link to sign in to Kanorio and choose what the CLI may do:");
197
+ log(` ${url}`);
198
+ log("Waiting for approval in the browser (the link works for 5 minutes)…");
199
+ if (!cli.flags.noBrowser)
200
+ (ctx.openBrowser ?? openInBrowser)(url);
201
+ const code = await listener.waitForCode(state);
202
+ const tokens = await exchangeAuthorizationCode({ apiUrl, code, verifier, redirectUri: listener.redirectUri, fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent });
203
+ const { token: _replaced, ...current } = readConfig(ctx.env);
204
+ void _replaced;
205
+ const path = writeConfig({ ...current, oauth: { ...tokens, apiUrl }, ...(cli.flags.api ? { apiUrl } : {}) }, ctx.env);
206
+ // Show the user who is signed in and which sites can be changed; failing to ask does not affect the sign-in
207
+ const who = await request({
208
+ apiUrl,
209
+ token: tokens.accessToken,
210
+ method: "GET",
211
+ path: "/whoami",
212
+ fetchImpl: ctx.fetchImpl,
213
+ userAgent: ctx.userAgent,
214
+ }).catch(() => null);
215
+ return {
216
+ stored: path,
217
+ apiUrl,
218
+ ...(who ? { signedInAs: who.principal, websiteScope: who.websiteScope, websiteIds: who.websiteIds } : {}),
219
+ note: "Signed in. Manage or revoke this connection under Account settings > API access > Authorized apps.",
220
+ };
221
+ }
222
+ finally {
223
+ listener.close();
224
+ }
225
+ }
226
+ /**
227
+ * `kanorio login`: opens the browser for approval by default (no key to copy).
228
+ * `--token <pat>` or a PAT on stdin stores that token; `--with-token` pastes one in the terminal (not echoed).
229
+ */
230
+ const login = async (cli, ctx) => {
231
+ if (cli.flags.token !== undefined)
232
+ return storePersonalToken(cli, ctx, cli.flags.token);
233
+ if (cli.flags.withToken) {
234
+ return storePersonalToken(cli, ctx, await promptSecret("Paste your personal access token (knr_pat_…): ", ctx.stdin));
235
+ }
236
+ const piped = await readPipedToken(ctx.stdin);
237
+ if (piped)
238
+ return storePersonalToken(cli, ctx, piped);
239
+ return loginWithBrowser(cli, ctx);
240
+ };
241
+ /** Sign out: a browser sign-in is also revoked on the server (a failed revoke does not block; the local tokens are always cleared) */
242
+ const logout = async (cli, ctx) => {
243
+ const session = readConfig(ctx.env).oauth;
244
+ const revoked = session ? await revokeToken({ apiUrl: session.apiUrl, token: session.refreshToken, fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent }) : undefined;
245
+ void cli;
246
+ clearToken(ctx.env);
247
+ return { removed: configPath(ctx.env), ...(revoked !== undefined ? { revoked } : {}) };
248
+ };
249
+ const sitesList = async (cli, ctx) => authed(cli, ctx).call("GET", "/sites");
250
+ const sitesGet = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}`);
251
+ const sitesCreate = async (cli, ctx) => {
252
+ const { call } = authed(cli, ctx);
253
+ if (cli.flags.brief) {
254
+ return call("POST", "/sites", { body: { mode: "brief", brief: readJsonFile(cli.flags.brief) } });
255
+ }
256
+ if (!cli.flags.name || !cli.flags.locale)
257
+ throw new UsageError("sites create needs --name and --locale, or --brief <file>.");
258
+ return call("POST", "/sites", {
259
+ body: {
260
+ mode: "blank",
261
+ name: cli.flags.name,
262
+ locale: cli.flags.locale,
263
+ ...(cli.flags.timezone ? { timezone: cli.flags.timezone } : {}),
264
+ ...(cli.flags.profile ? { siteProfile: cli.flags.profile } : {}),
265
+ ...(cli.flags.description ? { brandDescription: cli.flags.description } : {}),
266
+ },
267
+ });
268
+ };
269
+ const settingsGet = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/settings`);
270
+ const settingsUpdate = async (cli, ctx) => {
271
+ const settings = cli.flags.file ? readJsonFile(cli.flags.file) : {};
272
+ // Brand identity (including color scheme, effective immediately) goes under settings.brand; layout design (draft) stays at the top level
273
+ const brand = settings.brand ?? {};
274
+ if (cli.flags.brandColor) {
275
+ brand.brandColor = { light: cli.flags.brandColor, dark: cli.flags.brandColorDark ?? cli.flags.brandColor };
276
+ }
277
+ if (cli.flags.cornerRadius)
278
+ brand.cornerRadius = cli.flags.cornerRadius;
279
+ if (cli.flags.colorScheme)
280
+ brand.colorScheme = cli.flags.colorScheme;
281
+ if (Object.keys(brand).length > 0)
282
+ settings.brand = brand;
283
+ if (cli.flags.density)
284
+ settings.sectionDensity = cli.flags.density;
285
+ if (cli.flags.locale)
286
+ settings.locale = cli.flags.locale;
287
+ if (cli.flags.currency)
288
+ settings.currency = cli.flags.currency;
289
+ if (Object.keys(settings).length === 0) {
290
+ throw new UsageError("settings update needs at least one of --brand-color, --corner-radius, --color-scheme, --density, --locale, --currency or --file <settings.json>.");
291
+ }
292
+ return authed(cli, ctx).call("PATCH", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/settings`, { body: { settings } });
293
+ };
294
+ const globalsGet = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/globals`);
295
+ /** Site-wide writes: without --if-unmodified-since, read globals first for contentUpdatedAt (two REST calls, no business logic) */
296
+ async function globalsWrite(cli, ctx, method, suffix, bodyKey, label) {
297
+ if (!cli.flags.file)
298
+ throw new UsageError(`${label} needs --file <${bodyKey}.json>.`);
299
+ const siteId = encodeURIComponent(need(cli, 0, "siteId"));
300
+ const payload = readJsonFile(cli.flags.file);
301
+ const { call } = authed(cli, ctx);
302
+ let ifUnmodifiedSince = cli.flags.ifUnmodifiedSince;
303
+ if (!ifUnmodifiedSince) {
304
+ const globals = await call("GET", `/sites/${siteId}/globals`);
305
+ if (typeof globals.contentUpdatedAt !== "string") {
306
+ throw new ApiError("CLI_ERROR", 0, "globals.get did not return contentUpdatedAt; pass --if-unmodified-since explicitly.");
307
+ }
308
+ ifUnmodifiedSince = globals.contentUpdatedAt;
309
+ }
310
+ return call(method, `/sites/${siteId}/globals${suffix}`, { body: { ifUnmodifiedSince, [bodyKey]: payload } });
311
+ }
312
+ const globalsReplaceHeader = (cli, ctx) => globalsWrite(cli, ctx, "PUT", "/header", "header", "globals replace-header");
313
+ const globalsReplaceFooter = (cli, ctx) => globalsWrite(cli, ctx, "PUT", "/footer", "footer", "globals replace-footer");
314
+ const globalsUpdateSiteSettings = (cli, ctx) => globalsWrite(cli, ctx, "PATCH", "/site-settings", "siteSettings", "globals update-site-settings");
315
+ const jobsGet = async (cli, ctx) => authed(cli, ctx).call("GET", `/jobs/${encodeURIComponent(need(cli, 0, "jobId"))}`);
316
+ const pagesList = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/pages`);
317
+ const pagesGet = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/pages/${encodeURIComponent(need(cli, 1, "pageId"))}`);
318
+ const pagesCreate = async (cli, ctx) => {
319
+ if (!cli.flags.title)
320
+ throw new UsageError("pages create needs --title.");
321
+ return authed(cli, ctx).call("POST", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/pages`, {
322
+ body: {
323
+ title: cli.flags.title,
324
+ ...(cli.flags.slug ? { slug: cli.flags.slug } : {}),
325
+ ...(cli.flags.hidden ? { isVisible: false } : {}),
326
+ },
327
+ });
328
+ };
329
+ const pagesUpdate = async (cli, ctx) => {
330
+ const patch = cli.flags.file ? readJsonFile(cli.flags.file) : {};
331
+ if (cli.flags.title)
332
+ patch.title = cli.flags.title;
333
+ if (cli.flags.slug)
334
+ patch.slug = cli.flags.slug;
335
+ if (cli.flags.hidden)
336
+ patch.isVisible = false;
337
+ if (cli.flags.visible)
338
+ patch.isVisible = true;
339
+ if (Object.keys(patch).length === 0) {
340
+ throw new UsageError("pages update needs at least one of --title, --slug, --hidden, --visible or --file <patch.json>.");
341
+ }
342
+ return authed(cli, ctx).call("PATCH", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/pages/${encodeURIComponent(need(cli, 1, "pageId"))}`, { body: patch });
343
+ };
344
+ const pagesReorder = async (cli, ctx) => {
345
+ const pageIds = cli.positionals.slice(1);
346
+ if (pageIds.length === 0)
347
+ throw new UsageError("pages reorder needs <siteId> followed by every non-home pageId in order.");
348
+ return authed(cli, ctx).call("PUT", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/pages/order`, { body: { pageIds } });
349
+ };
350
+ const pagesDelete = async (cli, ctx) => authed(cli, ctx).call("DELETE", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/pages/${encodeURIComponent(need(cli, 1, "pageId"))}`);
351
+ const pagesReplaceSections = async (cli, ctx) => {
352
+ if (!cli.flags.file)
353
+ throw new UsageError("pages replace-sections needs --file <sections.json>.");
354
+ const siteId = encodeURIComponent(need(cli, 0, "siteId"));
355
+ const pageId = encodeURIComponent(need(cli, 1, "pageId"));
356
+ const payload = readJsonFile(cli.flags.file);
357
+ let sections;
358
+ let ifUnmodifiedSince = cli.flags.ifUnmodifiedSince;
359
+ if (Array.isArray(payload)) {
360
+ sections = payload;
361
+ }
362
+ else if (typeof payload === "object" && payload !== null && Array.isArray(payload.sections)) {
363
+ sections = payload.sections;
364
+ const fromFile = payload.ifUnmodifiedSince;
365
+ if (!ifUnmodifiedSince && typeof fromFile === "string")
366
+ ifUnmodifiedSince = fromFile;
367
+ }
368
+ else {
369
+ throw new UsageError(`${cli.flags.file} must be an array of sections or { "sections": [...] }.`);
370
+ }
371
+ const { call } = authed(cli, ctx);
372
+ if (!ifUnmodifiedSince) {
373
+ const page = await call("GET", `/sites/${siteId}/pages/${pageId}`);
374
+ if (typeof page.updatedAt !== "string")
375
+ throw new ApiError("CLI_ERROR", 0, "pages.get did not return updatedAt.");
376
+ ifUnmodifiedSince = page.updatedAt;
377
+ }
378
+ return call("PUT", `/sites/${siteId}/pages/${pageId}/sections`, { body: { ifUnmodifiedSince, sections } });
379
+ };
380
+ const publish = async (cli, ctx) => authed(cli, ctx).call("POST", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/publish`, {
381
+ body: cli.flags.subdomain ? { subdomain: cli.flags.subdomain } : {},
382
+ });
383
+ const unpublish = async (cli, ctx) => authed(cli, ctx).call("POST", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/unpublish`, { body: {} });
384
+ const domainsList = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/domains`);
385
+ const domainsStatus = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/domains/status`);
386
+ const domainsBind = async (cli, ctx) => authed(cli, ctx).call("PUT", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/domains`, {
387
+ body: { hostnames: cli.positionals.slice(1) },
388
+ });
389
+ const mediaList = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/media`);
390
+ const mediaUpload = async (cli, ctx) => {
391
+ const siteId = encodeURIComponent(need(cli, 0, "siteId"));
392
+ if (cli.flags.url) {
393
+ return authed(cli, ctx).call("POST", `/sites/${siteId}/media`, { body: { url: cli.flags.url } });
394
+ }
395
+ if (!cli.flags.file)
396
+ throw new UsageError("media upload needs --url <https://…> or --file <image>.");
397
+ const base64 = readFileSync(cli.flags.file).toString("base64");
398
+ return authed(cli, ctx).call("POST", `/sites/${siteId}/media`, { body: { base64 } });
399
+ };
400
+ const mediaUploadLink = async (cli, ctx) => authed(cli, ctx).call("POST", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/media/upload-links`, {
401
+ body: {
402
+ ...(cli.flags.max ? { maxFiles: Number(cli.flags.max) } : {}),
403
+ ...(cli.flags.purpose ? { purpose: cli.flags.purpose } : {}),
404
+ },
405
+ });
406
+ const mediaUploadLinkStatus = async (cli, ctx) => {
407
+ if (!cli.flags.uploadToken)
408
+ throw new UsageError("media upload-link-status needs --upload-token <token>.");
409
+ return authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/media/upload-links/status`, {
410
+ query: { token: cli.flags.uploadToken },
411
+ });
412
+ };
413
+ const mediaSearchStock = async (cli, ctx) => {
414
+ const query = cli.flags.query ?? cli.positionals.slice(1).join(" ");
415
+ if (!query)
416
+ throw new UsageError("media search-stock needs <siteId> and a query (positional or --query).");
417
+ return authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/media/stock`, {
418
+ query: { query, orientation: cli.flags.orientation, provider: cli.flags.provider, perPage: cli.flags.max },
419
+ });
420
+ };
421
+ const mediaImportStock = async (cli, ctx) => {
422
+ if (!cli.flags.provider || !cli.flags.stockId || !cli.flags.url) {
423
+ throw new UsageError("media import-stock needs --provider <pexels|pixabay> --stock-id <id> --url <downloadURL> (all from search-stock).");
424
+ }
425
+ return authed(cli, ctx).call("POST", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/media/stock`, {
426
+ body: { provider: cli.flags.provider, id: cli.flags.stockId, downloadURL: cli.flags.url },
427
+ });
428
+ };
429
+ const mediaPageImages = async (cli, ctx) => {
430
+ const url = cli.flags.url ?? cli.positionals[1];
431
+ if (!url)
432
+ throw new UsageError("media page-images needs <siteId> <url>.");
433
+ return authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/media/page-images`, {
434
+ query: { url, max: cli.flags.max },
435
+ });
436
+ };
437
+ const sectionsDescribe = async (cli, ctx) => authed(cli, ctx).call("GET", "/sections", {
438
+ query: {
439
+ types: cli.positionals.length > 0 ? cli.positionals : undefined,
440
+ detail: cli.flags.detail,
441
+ websiteId: cli.flags.site,
442
+ },
443
+ });
444
+ const typesGenerate = async (cli, ctx) => {
445
+ const target = cli.flags.site ?? cli.positionals[0];
446
+ if (!target) {
447
+ throw new UsageError("types needs --site <siteId|siteUrl> (or positional <siteId|siteUrl>).");
448
+ }
449
+ let collections;
450
+ const looksLikeUrlOrHost = /^https?:\/\//i.test(target) || target.includes(".");
451
+ if (looksLikeUrlOrHost) {
452
+ const base = /^https?:\/\//i.test(target) ? target.replace(/\/+$/, "") : `https://${target.replace(/\/+$/, "")}`;
453
+ const url = base.endsWith("/api/v1/collections")
454
+ ? base
455
+ : base.endsWith("/api/v1")
456
+ ? `${base}/collections`
457
+ : `${base}/api/v1/collections`;
458
+ const fetchFn = ctx.fetchImpl ?? fetch;
459
+ const res = await fetchFn(url, { headers: { accept: "application/json", "user-agent": ctx.userAgent } });
460
+ if (!res.ok) {
461
+ throw new ApiError("DELIVERY_ERROR", res.status, `Failed to fetch ${url} (HTTP ${res.status}).`);
462
+ }
463
+ const body = (await res.json());
464
+ collections = Array.isArray(body.data) ? body.data : [];
465
+ }
466
+ else {
467
+ const res = await authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(target)}/collections`);
468
+ collections = Array.isArray(res.data) ? res.data : [];
469
+ }
470
+ const code = generateCollectionTypes(collections);
471
+ if (cli.flags.out) {
472
+ writeFileSync(cli.flags.out, code, "utf8");
473
+ return { written: cli.flags.out, collections: collections.map((c) => c.key) };
474
+ }
475
+ return cli.flags.json ? { code, collections: collections.map((c) => c.key) } : code;
476
+ };
477
+ const doctorCheck = async (cli, ctx) => {
478
+ const siteId = cli.flags.site ?? cli.positionals[0];
479
+ if (!siteId) {
480
+ throw new UsageError("doctor needs --site <siteId> (or positional <siteId>).");
481
+ }
482
+ const switching = Boolean(cli.flags.switching);
483
+ return authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(siteId)}/external-frontend/check`, switching ? { query: { switching: "true" } } : undefined);
484
+ };
485
+ const SERVER_KEY_ENV_NAME = "KANORIO_SERVER_KEY";
486
+ const SERVER_KEY_ENV_LINE = /^[ \t]*(?:export[ \t]+)?KANORIO_SERVER_KEY[ \t]*=.*$/;
487
+ /**
488
+ * Writes the key line into the contents of an env file: replaces the first existing line and removes other lines with the same name, or appends one.
489
+ * Only one line with that name is kept: dotenv takes the last one, so a leftover old line would keep the host on the revoked key.
490
+ */
491
+ function upsertServerKeyLine(existing, line) {
492
+ const lines = existing.split("\n");
493
+ const first = lines.findIndex((entry) => SERVER_KEY_ENV_LINE.test(entry));
494
+ if (first === -1)
495
+ return `${existing}${existing && !existing.endsWith("\n") ? "\n" : ""}${line}\n`;
496
+ return lines
497
+ .map((entry, index) => (index === first ? line : entry))
498
+ .filter((entry, index) => index === first || !SERVER_KEY_ENV_LINE.test(entry))
499
+ .join("\n");
500
+ }
501
+ /** Whether the write can succeed: check the file when it exists, otherwise its folder (which must exist and be writable) */
502
+ function assertEnvFileWritable(envFile) {
503
+ const target = existsSync(envFile) ? envFile : dirname(envFile);
504
+ if (target !== envFile && !existsSync(target))
505
+ throw new UsageError(`${target} does not exist. Create the folder first, or point --write-env at an existing one.`);
506
+ try {
507
+ accessSync(target, fsConstants.W_OK);
508
+ }
509
+ catch {
510
+ throw new UsageError(`${target} is not writable. Fix its permissions, or point --write-env somewhere else.`);
511
+ }
512
+ }
513
+ /** Whether git ignores the file; null when outside a git repository or without git (cannot tell) */
514
+ function isGitIgnored(file) {
515
+ try {
516
+ execFileSync("git", ["check-ignore", "-q", file], { cwd: dirname(file), stdio: "ignore" });
517
+ return true;
518
+ }
519
+ catch (error) {
520
+ // exit 1 means not ignored; anything else (128 outside a repository, ENOENT without git) cannot tell
521
+ return error.status === 1 ? false : null;
522
+ }
523
+ }
524
+ /**
525
+ * Issues a server key. With `--write-env` the key is written to the env file and never printed:
526
+ * the plaintext only travels from the API response to the file. It does not enter shell history or terminal scrollback, and an AI tool reading the output never sees it.
527
+ * Whether it would overwrite and whether the write can succeed are both checked **before** calling the API, so a key is never issued that cannot be written and that nobody knows.
528
+ * If the write fails after issuing (permissions changed after the check), the key is printed once instead of being lost.
529
+ */
530
+ const keysCreate = async (cli, ctx) => {
531
+ const siteId = cli.flags.site ?? cli.positionals[0];
532
+ if (!siteId)
533
+ throw new UsageError("keys create needs --site <siteId> (or positional <siteId>).");
534
+ const envFile = cli.flags.writeEnv ? resolve(cli.flags.writeEnv) : null;
535
+ let existing = "";
536
+ if (envFile && existsSync(envFile)) {
537
+ if (!statSync(envFile).isFile())
538
+ throw new UsageError(`${envFile} is not a file.`);
539
+ existing = readFileSync(envFile, "utf8");
540
+ if (existing.split("\n").some((entry) => SERVER_KEY_ENV_LINE.test(entry)) && !cli.flags.force) {
541
+ throw new UsageError(`${envFile} already sets ${SERVER_KEY_ENV_NAME}. Pass --force to replace it, then revoke the old key under Site settings > Developer.`);
542
+ }
543
+ }
544
+ if (envFile)
545
+ assertEnvFileWritable(envFile);
546
+ const created = await authed(cli, ctx).call("POST", `/sites/${encodeURIComponent(siteId)}/server-keys`, {
547
+ body: { ...(cli.flags.name ? { name: cli.flags.name } : {}), ...(cli.flags.keyName ? { keyName: cli.flags.keyName } : {}) },
548
+ });
549
+ if (!envFile) {
550
+ return { ...created, note: `Shown once. Store it on your frontend host as ${created.envName}; never commit it or use it in browser code.` };
551
+ }
552
+ const next = upsertServerKeyLine(existing, `${SERVER_KEY_ENV_NAME}=${created.key}`);
553
+ const isNew = existing === "" && !existsSync(envFile);
554
+ try {
555
+ writeFileSync(envFile, next, { encoding: "utf8", mode: 0o600 });
556
+ }
557
+ catch (error) {
558
+ return {
559
+ ...created,
560
+ note: `Could not write ${envFile} (${error instanceof Error ? error.message : String(error)}). The key was created and is shown once here: store it on your frontend host as ${created.envName}, or revoke it under Site settings > Developer.`,
561
+ };
562
+ }
563
+ // A new file is readable and writable by its owner only; an existing file keeps its permissions (the team may have set them on purpose)
564
+ if (isNew)
565
+ chmodSync(envFile, 0o600);
566
+ const warnings = [];
567
+ const ignored = isGitIgnored(envFile);
568
+ if (ignored === false)
569
+ warnings.push(`${envFile} is not ignored by git. Add it to .gitignore before committing.`);
570
+ if (!isNew && (statSync(envFile).mode & 0o077) !== 0)
571
+ warnings.push(`${envFile} is readable by other users on this machine (chmod 600 to restrict).`);
572
+ const { key: _key, ...safe } = created;
573
+ void _key;
574
+ return { ...safe, written: envFile, ...(warnings.length > 0 ? { warnings } : {}) };
575
+ };
576
+ const API_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
577
+ /** Reads all of stdin (`--file -`) */
578
+ async function readStdin(stdin) {
579
+ const input = stdin ?? process.stdin;
580
+ return new Promise((resolve, reject) => {
581
+ let data = "";
582
+ input.setEncoding?.("utf8");
583
+ input.on("data", (chunk) => {
584
+ data += chunk;
585
+ });
586
+ input.on("end", () => resolve(data));
587
+ input.on("error", reject);
588
+ });
589
+ }
590
+ /**
591
+ * General entry point: calls any Management API operation with the stored credential (like `gh api` and `vercel api`).
592
+ * For operations without a dedicated command, and so a coding assistant never handles the token: it runs the command while the token stays in the config file or the environment.
593
+ * Paths are relative to `/api/v1`; only the configured API host is called and full URLs are refused (the token is never sent to another host).
594
+ */
595
+ const apiCall = async (cli, ctx) => {
596
+ const method = need(cli, 0, "method").toUpperCase();
597
+ if (!API_METHODS.includes(method)) {
598
+ throw new UsageError(`Unknown method ${cli.positionals[0]}. Use one of ${API_METHODS.join(", ")}.`);
599
+ }
600
+ const raw = need(cli, 1, "path");
601
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)) {
602
+ throw new UsageError("Pass a path such as /sites/<siteId>/posts, not a URL. The API origin comes from --api or KANORIO_API_URL.");
603
+ }
604
+ const withoutBase = raw.replace(/^\/?api\/v1(?=\/|\?|$)/, "");
605
+ const [pathname = "", search = ""] = withoutBase.split("?", 2);
606
+ if (!pathname || pathname === "/")
607
+ throw new UsageError("Missing <path>, for example /whoami or /sites/<siteId>/posts.");
608
+ const query = {};
609
+ for (const [key, value] of new URLSearchParams(search))
610
+ query[key] = value;
611
+ if (cli.flags.file && cli.flags.data)
612
+ throw new UsageError("Pass the body with --file or --data, not both.");
613
+ let body;
614
+ if (cli.flags.file === "-") {
615
+ const text = await readStdin(ctx.stdin);
616
+ try {
617
+ body = JSON.parse(text);
618
+ }
619
+ catch {
620
+ throw new UsageError("The body read from stdin is not valid JSON.");
621
+ }
622
+ }
623
+ else if (cli.flags.file) {
624
+ body = readJsonFile(cli.flags.file);
625
+ }
626
+ else if (cli.flags.data !== undefined) {
627
+ try {
628
+ body = JSON.parse(cli.flags.data);
629
+ }
630
+ catch {
631
+ throw new UsageError("--data is not valid JSON.");
632
+ }
633
+ }
634
+ if (body !== undefined && method === "GET")
635
+ throw new UsageError("GET takes no body. Put filters in the path's query string.");
636
+ const headers = cli.flags.idempotencyKey ? { "idempotency-key": cli.flags.idempotencyKey } : undefined;
637
+ return authed(cli, ctx).call(method, pathname.startsWith("/") ? pathname : `/${pathname}`, { query, body, headers });
638
+ };
639
+ /** Who the stored credential is, what it can do, and which operations it cannot call and why (`GET /whoami`; service account tokens can ask too) */
640
+ const whoami = async (cli, ctx) => authed(cli, ctx).call("GET", "/whoami", { query: { websiteId: cli.flags.site } });
641
+ export const COMMANDS = {
642
+ login,
643
+ logout,
644
+ api: apiCall,
645
+ whoami,
646
+ types: typesGenerate,
647
+ doctor: doctorCheck,
648
+ "keys create": keysCreate,
649
+ "sites list": sitesList,
650
+ "sites get": sitesGet,
651
+ "sites create": sitesCreate,
652
+ "jobs get": jobsGet,
653
+ "settings get": settingsGet,
654
+ "settings update": settingsUpdate,
655
+ "globals get": globalsGet,
656
+ "globals replace-header": globalsReplaceHeader,
657
+ "globals replace-footer": globalsReplaceFooter,
658
+ "globals update-site-settings": globalsUpdateSiteSettings,
659
+ "pages list": pagesList,
660
+ "pages get": pagesGet,
661
+ "pages create": pagesCreate,
662
+ "pages update": pagesUpdate,
663
+ "pages reorder": pagesReorder,
664
+ "pages delete": pagesDelete,
665
+ "pages replace-sections": pagesReplaceSections,
666
+ publish,
667
+ unpublish,
668
+ "domains list": domainsList,
669
+ "domains status": domainsStatus,
670
+ "domains bind": domainsBind,
671
+ "media list": mediaList,
672
+ "media upload": mediaUpload,
673
+ "media upload-link": mediaUploadLink,
674
+ "media upload-link-status": mediaUploadLinkStatus,
675
+ "media search-stock": mediaSearchStock,
676
+ "media import-stock": mediaImportStock,
677
+ "media page-images": mediaPageImages,
678
+ "sections describe": sectionsDescribe,
679
+ };
680
+ export function resolveCommand(command) {
681
+ return COMMANDS[command.join(" ")] ?? null;
682
+ }