@kanorio/cli 0.0.0-stage → 1.0.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,469 @@
1
+ /**
2
+ * 子命令 → REST 呼叫。每個命令只做:取參數 → 組 request → 回伺服端 JSON。
3
+ * 唯一的「便利」是 replace-sections 在未給 ifUnmodifiedSince 時先讀頁面拿 updatedAt;仍是兩次 REST 呼叫,不含業務判斷。
4
+ */
5
+ import { execFileSync } 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, writeConfig } from "./config.js";
13
+ import { generateCollectionTypes } from "./types-codegen.js";
14
+ function need(cli, index, label) {
15
+ const value = cli.positionals[index];
16
+ if (!value)
17
+ throw new UsageError(`Missing <${label}>.`);
18
+ return value;
19
+ }
20
+ function readJsonFile(path) {
21
+ let text;
22
+ try {
23
+ text = readFileSync(path, "utf8");
24
+ }
25
+ catch (error) {
26
+ throw new UsageError(`Cannot read ${path}: ${error instanceof Error ? error.message : String(error)}`);
27
+ }
28
+ try {
29
+ return JSON.parse(text);
30
+ }
31
+ catch {
32
+ throw new UsageError(`${path} is not valid JSON.`);
33
+ }
34
+ }
35
+ function authed(cli, ctx) {
36
+ const auth = resolveAuth(cli.flags, ctx.env);
37
+ if (!auth.token) {
38
+ throw new ApiError("UNAUTHORIZED", 401, "No token. Run `kanorio login` or set KANORIO_TOKEN.");
39
+ }
40
+ const token = auth.token;
41
+ return {
42
+ apiUrl: auth.apiUrl,
43
+ call: (method, path, extra = {}) => request({ apiUrl: auth.apiUrl, token, method, path, fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent, onDeprecation: ctx.onDeprecation, ...extra }),
44
+ };
45
+ }
46
+ /** 互動輸入 token 時不回顯:輸出導到黑洞,只手動印提示字 */
47
+ async function promptSecret(prompt, stdin) {
48
+ const input = stdin ?? process.stdin;
49
+ if (!input.isTTY) {
50
+ return new Promise((resolve, reject) => {
51
+ let data = "";
52
+ input.setEncoding?.("utf8");
53
+ input.on("data", (chunk) => {
54
+ data += chunk;
55
+ });
56
+ input.on("end", () => resolve(data.trim()));
57
+ input.on("error", reject);
58
+ });
59
+ }
60
+ process.stderr.write(prompt);
61
+ const muted = new Writable({ write: (_chunk, _enc, cb) => cb() });
62
+ const rl = createInterface({ input, output: muted, terminal: true });
63
+ return new Promise((resolve) => {
64
+ rl.question("", (answer) => {
65
+ rl.close();
66
+ process.stderr.write("\n");
67
+ resolve(answer.trim());
68
+ });
69
+ });
70
+ }
71
+ const login = async (cli, ctx) => {
72
+ const token = cli.flags.token ?? (await promptSecret("Paste your personal access token (knr_pat_…): ", ctx.stdin));
73
+ if (!token)
74
+ throw new UsageError("Token is empty.");
75
+ if (!token.startsWith("knr_pat_")) {
76
+ throw new UsageError("Only personal access tokens (knr_pat_…) can be stored; OAuth tokens are for MCP clients.");
77
+ }
78
+ const apiUrl = resolveAuth({ api: cli.flags.api }, ctx.env).apiUrl;
79
+ // 先驗再存:壞 token 不落地。403 代表 token 有效但沒 console:view,仍可存
80
+ let verified = "ok";
81
+ try {
82
+ await request({ apiUrl, token, method: "GET", path: "/sites", fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent });
83
+ }
84
+ catch (error) {
85
+ if (error instanceof ApiError && error.status === 403)
86
+ verified = "limited";
87
+ else
88
+ throw error;
89
+ }
90
+ const current = readConfig(ctx.env);
91
+ const path = writeConfig({ ...current, token, ...(cli.flags.api ? { apiUrl } : {}) }, ctx.env);
92
+ return {
93
+ stored: path,
94
+ apiUrl,
95
+ tokenPrefix: token.slice(0, 12),
96
+ ...(verified === "limited" ? { warning: "Token lacks console:view; sites list/get will be forbidden." } : {}),
97
+ };
98
+ };
99
+ const logout = async (_cli, ctx) => {
100
+ clearToken(ctx.env);
101
+ return { removed: configPath(ctx.env) };
102
+ };
103
+ const sitesList = async (cli, ctx) => authed(cli, ctx).call("GET", "/sites");
104
+ const sitesGet = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}`);
105
+ const sitesCreate = async (cli, ctx) => {
106
+ const { call } = authed(cli, ctx);
107
+ if (cli.flags.brief) {
108
+ return call("POST", "/sites", { body: { mode: "brief", brief: readJsonFile(cli.flags.brief) } });
109
+ }
110
+ if (!cli.flags.name || !cli.flags.locale)
111
+ throw new UsageError("sites create needs --name and --locale, or --brief <file>.");
112
+ return call("POST", "/sites", {
113
+ body: {
114
+ mode: "blank",
115
+ name: cli.flags.name,
116
+ locale: cli.flags.locale,
117
+ ...(cli.flags.timezone ? { timezone: cli.flags.timezone } : {}),
118
+ ...(cli.flags.profile ? { siteProfile: cli.flags.profile } : {}),
119
+ ...(cli.flags.description ? { brandDescription: cli.flags.description } : {}),
120
+ },
121
+ });
122
+ };
123
+ const settingsGet = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/settings`);
124
+ const settingsUpdate = async (cli, ctx) => {
125
+ const settings = cli.flags.file ? readJsonFile(cli.flags.file) : {};
126
+ // 品牌身分(含外觀模式,立即生效)放 settings.brand;版面設計(草稿)放頂層(Headless ADR-0005 修訂一)
127
+ const brand = settings.brand ?? {};
128
+ if (cli.flags.brandColor) {
129
+ brand.brandColor = { light: cli.flags.brandColor, dark: cli.flags.brandColorDark ?? cli.flags.brandColor };
130
+ }
131
+ if (cli.flags.cornerRadius)
132
+ brand.cornerRadius = cli.flags.cornerRadius;
133
+ if (cli.flags.colorScheme)
134
+ brand.colorScheme = cli.flags.colorScheme;
135
+ if (Object.keys(brand).length > 0)
136
+ settings.brand = brand;
137
+ if (cli.flags.density)
138
+ settings.sectionDensity = cli.flags.density;
139
+ if (cli.flags.locale)
140
+ settings.locale = cli.flags.locale;
141
+ if (cli.flags.currency)
142
+ settings.currency = cli.flags.currency;
143
+ if (Object.keys(settings).length === 0) {
144
+ throw new UsageError("settings update needs at least one of --brand-color, --corner-radius, --color-scheme, --density, --locale, --currency or --file <settings.json>.");
145
+ }
146
+ return authed(cli, ctx).call("PATCH", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/settings`, { body: { settings } });
147
+ };
148
+ const globalsGet = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/globals`);
149
+ /** 全站層寫入:未給 --if-unmodified-since 時先讀 globals 拿 contentUpdatedAt(兩次 REST 呼叫,無業務判斷) */
150
+ async function globalsWrite(cli, ctx, method, suffix, bodyKey, label) {
151
+ if (!cli.flags.file)
152
+ throw new UsageError(`${label} needs --file <${bodyKey}.json>.`);
153
+ const siteId = encodeURIComponent(need(cli, 0, "siteId"));
154
+ const payload = readJsonFile(cli.flags.file);
155
+ const { call } = authed(cli, ctx);
156
+ let ifUnmodifiedSince = cli.flags.ifUnmodifiedSince;
157
+ if (!ifUnmodifiedSince) {
158
+ const globals = await call("GET", `/sites/${siteId}/globals`);
159
+ if (typeof globals.contentUpdatedAt !== "string") {
160
+ throw new ApiError("CLI_ERROR", 0, "globals.get did not return contentUpdatedAt; pass --if-unmodified-since explicitly.");
161
+ }
162
+ ifUnmodifiedSince = globals.contentUpdatedAt;
163
+ }
164
+ return call(method, `/sites/${siteId}/globals${suffix}`, { body: { ifUnmodifiedSince, [bodyKey]: payload } });
165
+ }
166
+ const globalsReplaceHeader = (cli, ctx) => globalsWrite(cli, ctx, "PUT", "/header", "header", "globals replace-header");
167
+ const globalsReplaceFooter = (cli, ctx) => globalsWrite(cli, ctx, "PUT", "/footer", "footer", "globals replace-footer");
168
+ const globalsUpdateSiteSettings = (cli, ctx) => globalsWrite(cli, ctx, "PATCH", "/site-settings", "siteSettings", "globals update-site-settings");
169
+ const jobsGet = async (cli, ctx) => authed(cli, ctx).call("GET", `/jobs/${encodeURIComponent(need(cli, 0, "jobId"))}`);
170
+ const pagesList = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/pages`);
171
+ const pagesGet = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/pages/${encodeURIComponent(need(cli, 1, "pageId"))}`);
172
+ const pagesCreate = async (cli, ctx) => {
173
+ if (!cli.flags.title)
174
+ throw new UsageError("pages create needs --title.");
175
+ return authed(cli, ctx).call("POST", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/pages`, {
176
+ body: {
177
+ title: cli.flags.title,
178
+ ...(cli.flags.slug ? { slug: cli.flags.slug } : {}),
179
+ ...(cli.flags.hidden ? { isVisible: false } : {}),
180
+ },
181
+ });
182
+ };
183
+ const pagesUpdate = async (cli, ctx) => {
184
+ const patch = cli.flags.file ? readJsonFile(cli.flags.file) : {};
185
+ if (cli.flags.title)
186
+ patch.title = cli.flags.title;
187
+ if (cli.flags.slug)
188
+ patch.slug = cli.flags.slug;
189
+ if (cli.flags.hidden)
190
+ patch.isVisible = false;
191
+ if (cli.flags.visible)
192
+ patch.isVisible = true;
193
+ if (Object.keys(patch).length === 0) {
194
+ throw new UsageError("pages update needs at least one of --title, --slug, --hidden, --visible or --file <patch.json>.");
195
+ }
196
+ return authed(cli, ctx).call("PATCH", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/pages/${encodeURIComponent(need(cli, 1, "pageId"))}`, { body: patch });
197
+ };
198
+ const pagesReorder = async (cli, ctx) => {
199
+ const pageIds = cli.positionals.slice(1);
200
+ if (pageIds.length === 0)
201
+ throw new UsageError("pages reorder needs <siteId> followed by every non-home pageId in order.");
202
+ return authed(cli, ctx).call("PUT", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/pages/order`, { body: { pageIds } });
203
+ };
204
+ const pagesDelete = async (cli, ctx) => authed(cli, ctx).call("DELETE", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/pages/${encodeURIComponent(need(cli, 1, "pageId"))}`);
205
+ const pagesReplaceSections = async (cli, ctx) => {
206
+ if (!cli.flags.file)
207
+ throw new UsageError("pages replace-sections needs --file <sections.json>.");
208
+ const siteId = encodeURIComponent(need(cli, 0, "siteId"));
209
+ const pageId = encodeURIComponent(need(cli, 1, "pageId"));
210
+ const payload = readJsonFile(cli.flags.file);
211
+ let sections;
212
+ let ifUnmodifiedSince = cli.flags.ifUnmodifiedSince;
213
+ if (Array.isArray(payload)) {
214
+ sections = payload;
215
+ }
216
+ else if (typeof payload === "object" && payload !== null && Array.isArray(payload.sections)) {
217
+ sections = payload.sections;
218
+ const fromFile = payload.ifUnmodifiedSince;
219
+ if (!ifUnmodifiedSince && typeof fromFile === "string")
220
+ ifUnmodifiedSince = fromFile;
221
+ }
222
+ else {
223
+ throw new UsageError(`${cli.flags.file} must be an array of sections or { "sections": [...] }.`);
224
+ }
225
+ const { call } = authed(cli, ctx);
226
+ if (!ifUnmodifiedSince) {
227
+ const page = await call("GET", `/sites/${siteId}/pages/${pageId}`);
228
+ if (typeof page.updatedAt !== "string")
229
+ throw new ApiError("CLI_ERROR", 0, "pages.get did not return updatedAt.");
230
+ ifUnmodifiedSince = page.updatedAt;
231
+ }
232
+ return call("PUT", `/sites/${siteId}/pages/${pageId}/sections`, { body: { ifUnmodifiedSince, sections } });
233
+ };
234
+ const publish = async (cli, ctx) => authed(cli, ctx).call("POST", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/publish`, {
235
+ body: cli.flags.subdomain ? { subdomain: cli.flags.subdomain } : {},
236
+ });
237
+ const unpublish = async (cli, ctx) => authed(cli, ctx).call("POST", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/unpublish`, { body: {} });
238
+ const domainsList = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/domains`);
239
+ const domainsStatus = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/domains/status`);
240
+ const domainsBind = async (cli, ctx) => authed(cli, ctx).call("PUT", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/domains`, {
241
+ body: { hostnames: cli.positionals.slice(1) },
242
+ });
243
+ const mediaList = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/media`);
244
+ const mediaUpload = async (cli, ctx) => {
245
+ const siteId = encodeURIComponent(need(cli, 0, "siteId"));
246
+ if (cli.flags.url) {
247
+ return authed(cli, ctx).call("POST", `/sites/${siteId}/media`, { body: { url: cli.flags.url } });
248
+ }
249
+ if (!cli.flags.file)
250
+ throw new UsageError("media upload needs --url <https://…> or --file <image>.");
251
+ const base64 = readFileSync(cli.flags.file).toString("base64");
252
+ return authed(cli, ctx).call("POST", `/sites/${siteId}/media`, { body: { base64 } });
253
+ };
254
+ const mediaUploadLink = async (cli, ctx) => authed(cli, ctx).call("POST", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/media/upload-links`, {
255
+ body: {
256
+ ...(cli.flags.max ? { maxFiles: Number(cli.flags.max) } : {}),
257
+ ...(cli.flags.purpose ? { purpose: cli.flags.purpose } : {}),
258
+ },
259
+ });
260
+ const mediaUploadLinkStatus = async (cli, ctx) => {
261
+ if (!cli.flags.uploadToken)
262
+ throw new UsageError("media upload-link-status needs --upload-token <token>.");
263
+ return authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/media/upload-links/status`, {
264
+ query: { token: cli.flags.uploadToken },
265
+ });
266
+ };
267
+ const mediaSearchStock = async (cli, ctx) => {
268
+ const query = cli.flags.query ?? cli.positionals.slice(1).join(" ");
269
+ if (!query)
270
+ throw new UsageError("media search-stock needs <siteId> and a query (positional or --query).");
271
+ return authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/media/stock`, {
272
+ query: { query, orientation: cli.flags.orientation, provider: cli.flags.provider, perPage: cli.flags.max },
273
+ });
274
+ };
275
+ const mediaImportStock = async (cli, ctx) => {
276
+ if (!cli.flags.provider || !cli.flags.stockId || !cli.flags.url) {
277
+ throw new UsageError("media import-stock needs --provider <pexels|pixabay> --stock-id <id> --url <downloadURL> (all from search-stock).");
278
+ }
279
+ return authed(cli, ctx).call("POST", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/media/stock`, {
280
+ body: { provider: cli.flags.provider, id: cli.flags.stockId, downloadURL: cli.flags.url },
281
+ });
282
+ };
283
+ const mediaPageImages = async (cli, ctx) => {
284
+ const url = cli.flags.url ?? cli.positionals[1];
285
+ if (!url)
286
+ throw new UsageError("media page-images needs <siteId> <url>.");
287
+ return authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/media/page-images`, {
288
+ query: { url, max: cli.flags.max },
289
+ });
290
+ };
291
+ const sectionsDescribe = async (cli, ctx) => authed(cli, ctx).call("GET", "/sections", {
292
+ query: {
293
+ types: cli.positionals.length > 0 ? cli.positionals : undefined,
294
+ detail: cli.flags.detail,
295
+ websiteId: cli.flags.site,
296
+ },
297
+ });
298
+ const typesGenerate = async (cli, ctx) => {
299
+ const target = cli.flags.site ?? cli.positionals[0];
300
+ if (!target) {
301
+ throw new UsageError("types needs --site <siteId|siteUrl> (or positional <siteId|siteUrl>).");
302
+ }
303
+ let collections;
304
+ const looksLikeUrlOrHost = /^https?:\/\//i.test(target) || target.includes(".");
305
+ if (looksLikeUrlOrHost) {
306
+ const base = /^https?:\/\//i.test(target) ? target.replace(/\/+$/, "") : `https://${target.replace(/\/+$/, "")}`;
307
+ const url = base.endsWith("/api/v1/collections")
308
+ ? base
309
+ : base.endsWith("/api/v1")
310
+ ? `${base}/collections`
311
+ : `${base}/api/v1/collections`;
312
+ const fetchFn = ctx.fetchImpl ?? fetch;
313
+ const res = await fetchFn(url, { headers: { accept: "application/json", "user-agent": ctx.userAgent } });
314
+ if (!res.ok) {
315
+ throw new ApiError("DELIVERY_ERROR", res.status, `Failed to fetch ${url} (HTTP ${res.status}).`);
316
+ }
317
+ const body = (await res.json());
318
+ collections = Array.isArray(body.data) ? body.data : [];
319
+ }
320
+ else {
321
+ const res = await authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(target)}/collections`);
322
+ collections = Array.isArray(res.data) ? res.data : [];
323
+ }
324
+ const code = generateCollectionTypes(collections);
325
+ if (cli.flags.out) {
326
+ writeFileSync(cli.flags.out, code, "utf8");
327
+ return { written: cli.flags.out, collections: collections.map((c) => c.key) };
328
+ }
329
+ return cli.flags.json ? { code, collections: collections.map((c) => c.key) } : code;
330
+ };
331
+ const doctorCheck = async (cli, ctx) => {
332
+ const siteId = cli.flags.site ?? cli.positionals[0];
333
+ if (!siteId) {
334
+ throw new UsageError("doctor needs --site <siteId> (or positional <siteId>).");
335
+ }
336
+ const switching = Boolean(cli.flags.switching);
337
+ return authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(siteId)}/external-frontend/check`, switching ? { query: { switching: "true" } } : undefined);
338
+ };
339
+ const SERVER_KEY_ENV_NAME = "KANORIO_SERVER_KEY";
340
+ const SERVER_KEY_ENV_LINE = /^[ \t]*(?:export[ \t]+)?KANORIO_SERVER_KEY[ \t]*=.*$/;
341
+ /**
342
+ * 把金鑰那一行寫進環境變數檔的內容:已有就換掉第一筆、其餘同名的行刪掉;沒有就加在結尾。
343
+ * 同名的行只留一筆:dotenv 取最後一筆,留著舊的那一行,主機會繼續用該作廢的那把金鑰。
344
+ */
345
+ function upsertServerKeyLine(existing, line) {
346
+ const lines = existing.split("\n");
347
+ const first = lines.findIndex((entry) => SERVER_KEY_ENV_LINE.test(entry));
348
+ if (first === -1)
349
+ return `${existing}${existing && !existing.endsWith("\n") ? "\n" : ""}${line}\n`;
350
+ return lines
351
+ .map((entry, index) => (index === first ? line : entry))
352
+ .filter((entry, index) => index === first || !SERVER_KEY_ENV_LINE.test(entry))
353
+ .join("\n");
354
+ }
355
+ /** 寫不寫得進去:檔案在就看檔案,不在就看它的資料夾(要存在且可寫) */
356
+ function assertEnvFileWritable(envFile) {
357
+ const target = existsSync(envFile) ? envFile : dirname(envFile);
358
+ if (target !== envFile && !existsSync(target))
359
+ throw new UsageError(`${target} does not exist. Create the folder first, or point --write-env at an existing one.`);
360
+ try {
361
+ accessSync(target, fsConstants.W_OK);
362
+ }
363
+ catch {
364
+ throw new UsageError(`${target} is not writable. Fix its permissions, or point --write-env somewhere else.`);
365
+ }
366
+ }
367
+ /** 檔案在不在 git 的忽略清單裡;不在 git 儲存庫裡、或沒有 git 回 null(無從判斷) */
368
+ function isGitIgnored(file) {
369
+ try {
370
+ execFileSync("git", ["check-ignore", "-q", file], { cwd: dirname(file), stdio: "ignore" });
371
+ return true;
372
+ }
373
+ catch (error) {
374
+ // exit 1=沒被忽略;其餘(128=不在儲存庫、ENOENT=沒有 git)無從判斷
375
+ return error.status === 1 ? false : null;
376
+ }
377
+ }
378
+ /**
379
+ * 簽發一把網站主機金鑰。`--write-env` 時把金鑰寫進環境變數檔、終端機不印明文:
380
+ * 明文只經過「API 回應 → 檔案」,不進 shell 歷史、不進終端機捲動紀錄,也不會被 AI 工具讀到輸出。
381
+ * 會不會覆寫、寫不寫得進去都在呼叫 API **之前**判斷,免得簽了金鑰卻寫不進去、留下一把沒人知道的金鑰。
382
+ * 簽發之後才寫入失敗(檢查之後檔案被改了權限)時,改把金鑰印出來一次,不讓它消失。
383
+ */
384
+ const keysCreate = async (cli, ctx) => {
385
+ const siteId = cli.flags.site ?? cli.positionals[0];
386
+ if (!siteId)
387
+ throw new UsageError("keys create needs --site <siteId> (or positional <siteId>).");
388
+ const envFile = cli.flags.writeEnv ? resolve(cli.flags.writeEnv) : null;
389
+ let existing = "";
390
+ if (envFile && existsSync(envFile)) {
391
+ if (!statSync(envFile).isFile())
392
+ throw new UsageError(`${envFile} is not a file.`);
393
+ existing = readFileSync(envFile, "utf8");
394
+ if (existing.split("\n").some((entry) => SERVER_KEY_ENV_LINE.test(entry)) && !cli.flags.force) {
395
+ throw new UsageError(`${envFile} already sets ${SERVER_KEY_ENV_NAME}. Pass --force to replace it, then revoke the old key under Site settings > Developer.`);
396
+ }
397
+ }
398
+ if (envFile)
399
+ assertEnvFileWritable(envFile);
400
+ const created = await authed(cli, ctx).call("POST", `/sites/${encodeURIComponent(siteId)}/server-keys`, {
401
+ body: { ...(cli.flags.name ? { name: cli.flags.name } : {}), ...(cli.flags.keyName ? { keyName: cli.flags.keyName } : {}) },
402
+ });
403
+ if (!envFile) {
404
+ return { ...created, note: `Shown once. Store it on your frontend host as ${created.envName}; never commit it or use it in browser code.` };
405
+ }
406
+ const next = upsertServerKeyLine(existing, `${SERVER_KEY_ENV_NAME}=${created.key}`);
407
+ const isNew = existing === "" && !existsSync(envFile);
408
+ try {
409
+ writeFileSync(envFile, next, { encoding: "utf8", mode: 0o600 });
410
+ }
411
+ catch (error) {
412
+ return {
413
+ ...created,
414
+ 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.`,
415
+ };
416
+ }
417
+ // 新建的檔案只給擁有者讀寫;既有的檔案不動它的權限(可能是團隊刻意設的)
418
+ if (isNew)
419
+ chmodSync(envFile, 0o600);
420
+ const warnings = [];
421
+ const ignored = isGitIgnored(envFile);
422
+ if (ignored === false)
423
+ warnings.push(`${envFile} is not ignored by git. Add it to .gitignore before committing.`);
424
+ if (!isNew && (statSync(envFile).mode & 0o077) !== 0)
425
+ warnings.push(`${envFile} is readable by other users on this machine (chmod 600 to restrict).`);
426
+ const { key: _key, ...safe } = created;
427
+ void _key;
428
+ return { ...safe, written: envFile, ...(warnings.length > 0 ? { warnings } : {}) };
429
+ };
430
+ export const COMMANDS = {
431
+ login,
432
+ logout,
433
+ types: typesGenerate,
434
+ doctor: doctorCheck,
435
+ "keys create": keysCreate,
436
+ "sites list": sitesList,
437
+ "sites get": sitesGet,
438
+ "sites create": sitesCreate,
439
+ "jobs get": jobsGet,
440
+ "settings get": settingsGet,
441
+ "settings update": settingsUpdate,
442
+ "globals get": globalsGet,
443
+ "globals replace-header": globalsReplaceHeader,
444
+ "globals replace-footer": globalsReplaceFooter,
445
+ "globals update-site-settings": globalsUpdateSiteSettings,
446
+ "pages list": pagesList,
447
+ "pages get": pagesGet,
448
+ "pages create": pagesCreate,
449
+ "pages update": pagesUpdate,
450
+ "pages reorder": pagesReorder,
451
+ "pages delete": pagesDelete,
452
+ "pages replace-sections": pagesReplaceSections,
453
+ publish,
454
+ unpublish,
455
+ "domains list": domainsList,
456
+ "domains status": domainsStatus,
457
+ "domains bind": domainsBind,
458
+ "media list": mediaList,
459
+ "media upload": mediaUpload,
460
+ "media upload-link": mediaUploadLink,
461
+ "media upload-link-status": mediaUploadLinkStatus,
462
+ "media search-stock": mediaSearchStock,
463
+ "media import-stock": mediaImportStock,
464
+ "media page-images": mediaPageImages,
465
+ "sections describe": sectionsDescribe,
466
+ };
467
+ export function resolveCommand(command) {
468
+ return COMMANDS[command.join(" ")] ?? null;
469
+ }
package/dist/config.js ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * 本機設定:`$XDG_CONFIG_HOME/kanorio/config.json`(預設 `~/.config/kanorio/config.json`)。
3
+ * 只存 PAT 與 API base;檔案 0600、目錄 0700。環境變數 `KANORIO_TOKEN` 永遠優先於檔案。
4
+ */
5
+ import { chmodSync, existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { join } from "node:path";
8
+ export const DEFAULT_API_URL = "https://app.kanorio.com";
9
+ export function configDir(env = process.env) {
10
+ const base = env.XDG_CONFIG_HOME && env.XDG_CONFIG_HOME.trim() ? env.XDG_CONFIG_HOME : join(env.HOME ?? homedir(), ".config");
11
+ return join(base, "kanorio");
12
+ }
13
+ export function configPath(env = process.env) {
14
+ return join(configDir(env), "config.json");
15
+ }
16
+ export function readConfig(env = process.env) {
17
+ const path = configPath(env);
18
+ if (!existsSync(path))
19
+ return {};
20
+ try {
21
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
22
+ if (typeof parsed !== "object" || parsed === null)
23
+ return {};
24
+ const obj = parsed;
25
+ return {
26
+ ...(typeof obj.token === "string" ? { token: obj.token } : {}),
27
+ ...(typeof obj.apiUrl === "string" ? { apiUrl: obj.apiUrl } : {}),
28
+ };
29
+ }
30
+ catch {
31
+ return {};
32
+ }
33
+ }
34
+ export function writeConfig(config, env = process.env) {
35
+ const dir = configDir(env);
36
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
37
+ const path = configPath(env);
38
+ writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
39
+ // writeFileSync 的 mode 只在建檔時生效;既有檔案(例如使用者手動建立)也要收緊
40
+ chmodSync(path, 0o600);
41
+ return path;
42
+ }
43
+ /** 只移除 token;其他設定(apiUrl)保留,什麼都不剩時刪檔 */
44
+ export function clearToken(env = process.env) {
45
+ const rest = { ...readConfig(env) };
46
+ delete rest.token;
47
+ if (Object.keys(rest).length === 0) {
48
+ if (existsSync(configPath(env)))
49
+ unlinkSync(configPath(env));
50
+ return;
51
+ }
52
+ writeConfig(rest, env);
53
+ }
54
+ export function resolveAuth(flags, env = process.env, config = readConfig(env)) {
55
+ const apiUrl = (flags.api ?? env.KANORIO_API_URL ?? config.apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, "");
56
+ if (flags.token)
57
+ return { token: flags.token, apiUrl, tokenSource: "flag" };
58
+ if (env.KANORIO_TOKEN)
59
+ return { token: env.KANORIO_TOKEN, apiUrl, tokenSource: "env" };
60
+ if (config.token)
61
+ return { token: config.token, apiUrl, tokenSource: "config" };
62
+ return { token: null, apiUrl, tokenSource: null };
63
+ }
package/dist/help.js ADDED
@@ -0,0 +1,83 @@
1
+ export const HELP = `kanorio - command-line wrapper around the Kanorio Management API
2
+
3
+ Usage: kanorio <command> [args] [--json] [--api <url>] [--token <pat>]
4
+
5
+ Auth
6
+ login [--token <pat>] Store a personal access token (~/.config/kanorio/config.json, 0600)
7
+ logout Remove the stored token
8
+ KANORIO_TOKEN=<pat> Environment variable; takes precedence over the config file
9
+
10
+ Sites
11
+ sites list
12
+ sites get <siteId>
13
+ sites create --name <n> --locale <bcp47> [--timezone <tz>] [--profile <siteProfile>] [--description <text>]
14
+ Blank site with default header/footer, returns websiteId
15
+ sites create --brief <brief.json> AI site from a brief, returns jobId
16
+ jobs get <jobId> Poll a generation job
17
+
18
+ Brand and site-wide layout
19
+ settings get <siteId> Brand (colors, fonts, corner radius, color scheme; live immediately), layout (draft), locale, currency
20
+ settings update <siteId> [--brand-color <#hex> [--brand-color-dark <#hex>]] [--corner-radius sharp|normal|soft]
21
+ [--color-scheme system|light|dark] [--density standard|compact] [--locale <bcp47>]
22
+ [--currency <code>] [--file <settings.json>]
23
+ --brand-color / --corner-radius / --color-scheme write settings.brand (live immediately on site, checkout, sign-in, emails);
24
+ --density writes the hosted layout draft (publish to go live).
25
+ globals get <siteId> Header, footer, siteSettings, contentUpdatedAt
26
+ globals update-site-settings <siteId> --file <siteSettings.json> [--if-unmodified-since <iso>]
27
+ Partial: { "customButtons": [...], "socialLinks": [...] }. Button ids come back in the response (use them in ctaIds).
28
+ globals replace-header <siteId> --file <header.json> [--if-unmodified-since <iso>]
29
+ globals replace-footer <siteId> --file <footer.json> [--if-unmodified-since <iso>]
30
+ Without --if-unmodified-since the CLI reads globals first and uses its current contentUpdatedAt.
31
+
32
+ Pages
33
+ pages list <siteId>
34
+ pages get <siteId> <pageId>
35
+ pages create <siteId> --title <t> [--slug </path>] [--hidden]
36
+ pages update <siteId> <pageId> [--title <t>] [--slug </path>] [--hidden | --visible] [--file <patch.json>]
37
+ pages reorder <siteId> <pageId> [pageId...] Every non-home page, in order
38
+ pages delete <siteId> <pageId>
39
+ pages replace-sections <siteId> <pageId> --file <sections.json> [--if-unmodified-since <iso>]
40
+ sections.json is either an array of sections or { "sections": [...], "ifUnmodifiedSince": "..." }.
41
+ Without --if-unmodified-since the CLI reads the page first and uses its current updatedAt.
42
+
43
+ Publish
44
+ publish <siteId> [--subdomain <name>]
45
+ unpublish <siteId>
46
+
47
+ Domains
48
+ domains list <siteId>
49
+ domains status <siteId>
50
+ domains bind <siteId> <hostname> [hostname...] First hostname is primary; empty list removes all
51
+
52
+ Images
53
+ media list <siteId>
54
+ media upload <siteId> --url <https://…> | --file <image>
55
+ media upload-link <siteId> [--max <n>] [--purpose <text>] Page for the user to send photos (15 min)
56
+ media upload-link-status <siteId> --upload-token <token>
57
+ media search-stock <siteId> <query…> [--orientation landscape] [--provider pexels|pixabay] [--max <n>]
58
+ media import-stock <siteId> --provider <p> --stock-id <id> --url <downloadURL>
59
+ media page-images <siteId> <url> [--max <n>] Images found on a page the user owns
60
+
61
+ Sections & Types
62
+ sections describe [type...] [--detail full] [--site <siteId>]
63
+ types --site <siteId|https://site> [--out <kanorio.d.ts>] Generate TypeScript types for collections (assets + expanded)
64
+ doctor --site <siteId> Check external storefront health (--switching is deprecated and ignored)
65
+
66
+ Server keys
67
+ keys create --site <siteId> [--name <account>] [--key-name <label>] [--write-env <.env.local>] [--force]
68
+ Issue a server key (knr_sa_…) so your own server can submit forms, exchange customer sign-in codes and report
69
+ crawler hits on behalf of visitors. The key cannot call the Management API.
70
+ --write-env writes KANORIO_SERVER_KEY=… into that file (created with mode 0600) and does not print the key;
71
+ an existing KANORIO_SERVER_KEY line is only replaced with --force. Without --write-env the key is printed once.
72
+ Rotate by running it again, deploying the new key, then revoking the old one under Site settings > Developer.
73
+
74
+ Global flags
75
+ --json Print raw JSON (errors too) for scripting
76
+ --api <url> API origin (default https://app.kanorio.com; or KANORIO_API_URL)
77
+ --token <pat> One-off token (not stored)
78
+ -h, --help Show this help
79
+ -v, --version Print version
80
+
81
+ Errors print as "<CODE> (HTTP <status>): <message>" on stderr and exit 1; usage errors exit 2.
82
+ OpenAPI: https://app.kanorio.com/api/v1/openapi.json
83
+ `;