saturndocs 0.2.0 → 0.3.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.
Files changed (63) hide show
  1. package/dist/auth-OIEL34E4.js +16 -0
  2. package/dist/{chunk-GGGL4O7Z.js → chunk-32ATWMIS.js} +3 -3
  3. package/dist/{chunk-QF2ADHQZ.js → chunk-3EW6ZPL6.js} +5 -5
  4. package/dist/{chunk-ADZOBRZE.js → chunk-3KCCCMQY.js} +325 -35
  5. package/dist/{chunk-2RZEC3VH.js → chunk-3X2NBWZN.js} +123 -35
  6. package/dist/{chunk-EB7RWFQA.js → chunk-5ZYUBLEH.js} +1463 -130
  7. package/dist/{chunk-WBI4EI3D.js → chunk-6EKGBIUR.js} +2 -2
  8. package/dist/{chunk-W3GKH5DY.js → chunk-BOWRQKXR.js} +12 -6
  9. package/dist/{chunk-FGKHDJOC.js → chunk-E3G56DR2.js} +287 -35
  10. package/dist/chunk-FUZE54DG.js +905 -0
  11. package/dist/chunk-HBSJ4Z4S.js +53 -0
  12. package/dist/{chunk-DBMFJXKP.js → chunk-IJOYWJVM.js} +5 -5
  13. package/dist/chunk-IWIVHHZI.js +426 -0
  14. package/dist/{chunk-Z5CBPJ2L.js → chunk-PU37LVIF.js} +3 -3
  15. package/dist/{chunk-4ORVQCHY.js → chunk-RKM7YWPD.js} +25 -6
  16. package/dist/{chunk-2YTD2XNI.js → chunk-T3MCJYSF.js} +1 -1
  17. package/dist/{chunk-YSFP37B7.js → chunk-TEYHAN2L.js} +20 -6
  18. package/dist/{chunk-WUPP3THV.js → chunk-VDGVERLX.js} +5 -5
  19. package/dist/{chunk-SVDVBZPA.js → chunk-W3FZTCKV.js} +6 -4
  20. package/dist/chunk-WMS6FUKK.js +414 -0
  21. package/dist/chunk-WXLJZ7RD.js +115 -0
  22. package/dist/{chunk-56U46JVN.js → chunk-YGVC4N4V.js} +2 -1
  23. package/dist/{chunk-6JGAA5TF.js → chunk-YPWPLIEZ.js} +4 -4
  24. package/dist/cli.js +6 -6
  25. package/dist/{coverage-EBWULNQQ.js → coverage-SRIA65FT.js} +5 -5
  26. package/dist/{dist-XISZDQTR.js → dist-LJSALT4X.js} +33 -3
  27. package/dist/index.d.ts +69 -37
  28. package/dist/index.js +112 -47
  29. package/dist/{init-PI4VTG7V.js → init-Y3GDNDWW.js} +5 -3
  30. package/dist/{lint-SXBP37G3.js → lint-XM26WIGE.js} +3 -3
  31. package/dist/login-HIXLPRUI.js +22 -0
  32. package/dist/{manage-OB6DQK3Q.js → manage-3HEBB3EQ.js} +6 -2
  33. package/dist/{nav-R4OORY2G.js → nav-K43WZJ4J.js} +4 -4
  34. package/dist/openapiCheck-CL2AH3YC.js +105 -0
  35. package/dist/pages-4VWB7Z4S.js +16 -0
  36. package/dist/{read-VECMKHBW.js → read-DYGYUOFK.js} +5 -4
  37. package/dist/{read-WWOMA67R.js → read-RKT6HUZ7.js} +41 -7
  38. package/dist/requests-CZYE6GI3.js +13 -0
  39. package/dist/{schema-NKOXZHQH.js → schema-QMJMGD5P.js} +3 -3
  40. package/dist/{sites-XMMGWPY2.js → sites-JKS25SEM.js} +5 -4
  41. package/dist/{status-SYIUUSSU.js → status-FM2ALQUJ.js} +4 -4
  42. package/dist/{suggestions-GX5CQK26.js → suggestions-Z6XIHMFN.js} +13 -7
  43. package/dist/unavailable-DVPNUO3J.js +40 -0
  44. package/dist/validate-X42T4TJ6.js +12 -0
  45. package/package.json +15 -9
  46. package/dist/auth-DUYYFNEZ.js +0 -14
  47. package/dist/brokenLinks-E364XYH3.js +0 -48
  48. package/dist/build-F5PWGP57.js +0 -39
  49. package/dist/chunk-4J33CCAC.js +0 -49
  50. package/dist/chunk-D3CLXV7D.js +0 -131
  51. package/dist/chunk-GLI3OUYL.js +0 -637
  52. package/dist/chunk-K5YY6NSF.js +0 -71
  53. package/dist/chunk-KOJJUISB.js +0 -39
  54. package/dist/chunk-O72DR5FK.js +0 -152
  55. package/dist/chunk-VNYDYHXM.js +0 -22
  56. package/dist/chunk-VXEUNRVA.js +0 -26
  57. package/dist/chunk-WHNL6UYJ.js +0 -57
  58. package/dist/deploy-QUVLOGII.js +0 -13
  59. package/dist/dev-VDSDCBO2.js +0 -43
  60. package/dist/openapiCheck-X2QQGETY.js +0 -66
  61. package/dist/pages-MKFZAVGI.js +0 -15
  62. package/dist/requests-A7WC3B4M.js +0 -13
  63. package/dist/validate-D4I3DY2W.js +0 -32
@@ -0,0 +1,53 @@
1
+ // src/adapter/registry.ts
2
+ var UNAVAILABLE_SUMMARY = "Not available in this release. Use validate and lint to check pages.";
3
+ var COMMAND_GROUPS = Object.freeze([
4
+ { name: "manage", summary: "Call one management operation through the dashboard API", renderer: false, load: () => import("./manage-3HEBB3EQ.js").then((m) => m.registerManage), metadata: () => import("./manage-3HEBB3EQ.js").then((m) => m.MANAGE_METADATA) },
5
+ { name: "requests", summary: "Documentation requests and the conversations behind them", renderer: false, load: () => import("./requests-CZYE6GI3.js").then((m) => m.registerRequests), metadata: () => import("./requests-CZYE6GI3.js").then((m) => m.REQUESTS_METADATA) },
6
+ { name: "suggestions", summary: "Read a site's suggestions and diff the content they carry", renderer: false, load: () => import("./suggestions-Z6XIHMFN.js").then((m) => m.registerSuggestions), metadata: () => import("./suggestions-Z6XIHMFN.js").then((m) => m.SUGGESTIONS_METADATA) },
7
+ { name: "schema", summary: "Print this CLI's own command metadata, locally", renderer: false, load: () => import("./schema-QMJMGD5P.js").then((m) => m.registerSchema), metadata: () => import("./schema-QMJMGD5P.js").then((m) => m.SCHEMA_METADATA) },
8
+ { name: "login", summary: "Ask a person to approve this agent for one site, then save the login", renderer: false, load: () => import("./login-HIXLPRUI.js").then((m) => m.registerLogin), metadata: () => import("./login-HIXLPRUI.js").then((m) => m.LOGIN_METADATA) },
9
+ { name: "logout", summary: "Revoke a saved login and delete it from this computer", renderer: false, load: () => import("./login-HIXLPRUI.js").then((m) => m.registerLogout), metadata: () => import("./login-HIXLPRUI.js").then((m) => m.LOGOUT_METADATA) },
10
+ { name: "auth", summary: "Check the credential this CLI will use", renderer: false, load: () => import("./auth-OIEL34E4.js").then((m) => m.registerAuth), metadata: () => import("./auth-OIEL34E4.js").then((m) => m.AUTH_METADATA) },
11
+ { name: "sites", summary: "Create a site, or discover and inspect the sites this credential reaches", renderer: false, load: () => import("./sites-JKS25SEM.js").then((m) => m.registerSites), metadata: () => import("./sites-JKS25SEM.js").then((m) => m.SITES_METADATA) },
12
+ { name: "pages", summary: "Read the published pages of the release readers are seeing", renderer: false, load: () => import("./pages-4VWB7Z4S.js").then((m) => m.registerPages), metadata: () => import("./pages-4VWB7Z4S.js").then((m) => m.PAGES_METADATA) },
13
+ { name: "releases", summary: "Read this site's release history and one release by id", renderer: false, load: () => import("./read-RKT6HUZ7.js").then((m) => m.registerReleases), metadata: () => import("./read-RKT6HUZ7.js").then((m) => m.RELEASES_METADATA) },
14
+ { name: "status", summary: "One bounded briefing on a site, section by section", renderer: false, load: () => import("./status-FM2ALQUJ.js").then((m) => m.registerStatus), metadata: () => import("./status-FM2ALQUJ.js").then((m) => m.STATUS_METADATA) },
15
+ { name: "activity", summary: "Read what the platform did, and one job by id", renderer: false, load: () => import("./read-DYGYUOFK.js").then((m) => m.registerActivity), metadata: () => import("./read-DYGYUOFK.js").then((m) => m.ACTIVITY_METADATA) },
16
+ { name: "nav", summary: "Rewrite docs.json navigation from an approved outline", renderer: false, load: () => import("./nav-K43WZJ4J.js").then((m) => m.registerNav), metadata: () => import("./nav-K43WZJ4J.js").then((m) => m.NAV_METADATA) },
17
+ { name: "lint", summary: "Content lint and the known-pitfalls catalog over every page; exits 2 when any finding is an error", renderer: false, load: () => import("./lint-XM26WIGE.js").then((m) => m.registerLint), metadata: () => import("./lint-XM26WIGE.js").then((m) => m.LINT_METADATA) },
18
+ { name: "coverage", summary: "Check local pages against an approved outline", renderer: false, load: () => import("./coverage-SRIA65FT.js").then((m) => m.registerCoverage), metadata: () => import("./coverage-SRIA65FT.js").then((m) => m.COVERAGE_METADATA) },
19
+ { name: "init", summary: "Scaffold a docs project", renderer: true, load: () => import("./init-Y3GDNDWW.js").then((m) => m.registerInit) },
20
+ { name: "validate", summary: "Validate docs.json, models.toml, page files, and OpenAPI specs", renderer: true, load: () => import("./validate-X42T4TJ6.js").then((m) => m.registerValidate) },
21
+ { name: "dev", summary: UNAVAILABLE_SUMMARY, renderer: true, hidden: true, load: () => import("./unavailable-DVPNUO3J.js").then((m) => m.registerUnavailable("dev")) },
22
+ { name: "build", summary: UNAVAILABLE_SUMMARY, renderer: true, hidden: true, load: () => import("./unavailable-DVPNUO3J.js").then((m) => m.registerUnavailable("build")) },
23
+ { name: "broken-links", summary: UNAVAILABLE_SUMMARY, renderer: true, hidden: true, load: () => import("./unavailable-DVPNUO3J.js").then((m) => m.registerUnavailable("broken-links")) },
24
+ { name: "openapi-check", summary: "Parse OpenAPI specs and print an operation table", renderer: true, load: () => import("./openapiCheck-CL2AH3YC.js").then((m) => m.registerOpenapiCheck) }
25
+ ]);
26
+ var COMMAND_GROUP_NAMES = Object.freeze(COMMAND_GROUPS.map((group) => group.name));
27
+ var LISTED_COMMAND_GROUPS = Object.freeze(COMMAND_GROUPS.filter((group) => group.hidden !== true));
28
+ function findCommandGroup(name) {
29
+ return COMMAND_GROUPS.find((group) => group.name === name);
30
+ }
31
+ var VALUE_FLAGS = /* @__PURE__ */ new Set(["--site", "--api", "--timeout"]);
32
+ function selectCommandGroup(argv) {
33
+ for (let index = 2; index < argv.length; index += 1) {
34
+ const token = argv[index];
35
+ if (token === "--") break;
36
+ if (VALUE_FLAGS.has(token)) {
37
+ index += 1;
38
+ continue;
39
+ }
40
+ if (token.startsWith("-")) continue;
41
+ const group = findCommandGroup(token);
42
+ if (group !== void 0) return group;
43
+ }
44
+ return void 0;
45
+ }
46
+
47
+ export {
48
+ UNAVAILABLE_SUMMARY,
49
+ COMMAND_GROUPS,
50
+ COMMAND_GROUP_NAMES,
51
+ findCommandGroup,
52
+ selectCommandGroup
53
+ };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  COMMAND_GROUPS
3
- } from "./chunk-4J33CCAC.js";
3
+ } from "./chunk-HBSJ4Z4S.js";
4
4
  import {
5
5
  applyCommandHelp
6
6
  } from "./chunk-M2BZEDAS.js";
@@ -15,11 +15,11 @@ import {
15
15
  commandMetadata,
16
16
  createResultWriter,
17
17
  failureResult,
18
- invalidInput,
18
+ invalidInput2 as invalidInput,
19
19
  resolveGlobalOptions,
20
20
  selectorFor,
21
21
  successResult
22
- } from "./chunk-ADZOBRZE.js";
22
+ } from "./chunk-3KCCCMQY.js";
23
23
 
24
24
  // src/commands/schema.ts
25
25
  var SCHEMA_METADATA = Object.freeze([
@@ -55,7 +55,7 @@ function sharedContract() {
55
55
  }
56
56
  async function rootDocument(groups) {
57
57
  const listed = await Promise.all(
58
- groups.map(async (group) => ({
58
+ groups.filter((group) => group.hidden !== true).map(async (group) => ({
59
59
  name: group.name,
60
60
  summary: group.summary,
61
61
  commands: (await metadataOf(group)).map((entry) => entry.selector)
@@ -73,7 +73,7 @@ async function schemaDocument(selector, groups = COMMAND_GROUPS) {
73
73
  if (selector === null || selector === "") return rootDocument(groups);
74
74
  const normalized = selectorFor(selector.trim());
75
75
  if (normalized === CONTRACT_SELECTOR) {
76
- const { contentContract } = await import("./dist-XISZDQTR.js");
76
+ const { contentContract } = await import("./dist-LJSALT4X.js");
77
77
  return { ...sharedContract(), contract: contentContract() };
78
78
  }
79
79
  const groupName = normalized.split(".")[0];
@@ -0,0 +1,426 @@
1
+ import {
2
+ TOKEN_VARIABLE,
3
+ allRecords,
4
+ asCliError,
5
+ assertSameOrigin,
6
+ emptyRecord,
7
+ environmentToken,
8
+ flowContext,
9
+ grantFromTokens,
10
+ grantStatus,
11
+ hasAnyStore,
12
+ loadRecord,
13
+ lockOptions,
14
+ loginEnvironment,
15
+ normalizeScope,
16
+ pollDevice,
17
+ readStoredRecord,
18
+ revokeToken,
19
+ saveRecord,
20
+ selectStore,
21
+ startDevice,
22
+ storesFor,
23
+ validateNewSite,
24
+ windowsUnsupported,
25
+ withCredentialLock,
26
+ withPollLock
27
+ } from "./chunk-FUZE54DG.js";
28
+ import {
29
+ applyCommandHelp
30
+ } from "./chunk-M2BZEDAS.js";
31
+ import {
32
+ CliError,
33
+ commandMetadata,
34
+ createResultWriter,
35
+ failureResult,
36
+ invalidInput2 as invalidInput,
37
+ parseOrigin,
38
+ resolveGlobalOptions,
39
+ successResult
40
+ } from "./chunk-3KCCCMQY.js";
41
+
42
+ // src/commands/login.ts
43
+ import { execFile } from "child_process";
44
+ import { createHash } from "crypto";
45
+ var LOGIN_ERRORS = ["invalid_input", "forbidden", "conflict", "rate_limited", "service_unavailable", "transport_failure", "wait_timeout", "interrupted"];
46
+ var LOGIN_METADATA = Object.freeze([
47
+ commandMetadata("login", {
48
+ description: "Start the device approval flow: print a link and a code, wait while a person approves this agent for one site in the browser, then save the login. The person chooses the site and the permissions on the approval page; --site or --new-site only proposes one. The login is kept in the macOS Keychain when it answers, otherwise in a file only this user can read (on Linux, always the file; Windows is not supported yet), and every later command uses it when SATURNDOCS_MANAGEMENT_TOKEN is not set.",
49
+ target: { arguments: [] },
50
+ effect: "Creates nothing until the person approves. On approval the server records a grant for the one site, and the CLI saves its tokens on this computer.",
51
+ output: { fields: ["status", "site_id", "scope", "store", "access_expires_at", "primary_host", "repo_connected", "replaced_grant_revoked", "verification_uri_complete", "user_code", "expires_at"], ids: [], limitations: [] },
52
+ errors: [...LOGIN_ERRORS],
53
+ examples: [
54
+ { command: "saturndocs login", description: "Ask a person to approve this agent; they pick the site." },
55
+ { command: "saturndocs login --site acme", description: "Propose the existing site acme on the approval page." },
56
+ { command: "saturndocs login --new-site acme-docs --json", description: "Propose a new site; the person creates it while approving." },
57
+ { command: "saturndocs login --no-wait --json", description: "Print the link and exit at once, for an agent that must show the link before it waits." },
58
+ { command: "saturndocs login --resume --json", description: "Wait for the approval that --no-wait started." }
59
+ ]
60
+ })
61
+ ]);
62
+ var LOGOUT_METADATA = Object.freeze([
63
+ commandMetadata("logout", {
64
+ description: "Revoke the saved login on the server, then delete it from this computer. Without --site it acts on the default saved site. The local copy is deleted even when revocation cannot be confirmed; the result then says so, and a person can revoke the grant from the dashboard. SATURNDOCS_MANAGEMENT_TOKEN is never touched.",
65
+ target: { arguments: [] },
66
+ effect: "Revokes one grant, or every saved grant with --all, and deletes the saved tokens.",
67
+ output: { fields: ["revoked", "failed", "remaining", "unchecked"], ids: [], limitations: [] },
68
+ errors: ["invalid_input", "service_unavailable", "transport_failure", "interrupted"],
69
+ examples: [
70
+ { command: "saturndocs logout", description: "Revoke and forget the default saved login." },
71
+ { command: "saturndocs logout --site acme --json", description: "Revoke and forget the login for acme." },
72
+ { command: "saturndocs logout --all", description: "Revoke and forget every saved login for this API origin." }
73
+ ]
74
+ })
75
+ ]);
76
+ var SITES_CREATE_METADATA = commandMetadata("sites create", {
77
+ description: "Propose a new site and run the device approval flow for it. The person signs in, can edit the address, creates the site, and can install the GitHub App in the same visit. The login for the new site is then saved, exactly as saturndocs login --new-site would save it.",
78
+ target: { arguments: [{ name: "address", required: true, description: "The proposed site address: lowercase letters, digits, and hyphens, up to 63 characters." }] },
79
+ effect: "Creates nothing until the person approves. Approval creates the site and a grant for it.",
80
+ output: { fields: ["status", "site_id", "scope", "store", "access_expires_at", "primary_host", "repo_connected", "verification_uri_complete", "user_code", "expires_at"], ids: [], limitations: [] },
81
+ errors: [...LOGIN_ERRORS],
82
+ examples: [
83
+ { command: "saturndocs sites create acme-docs", description: "Ask a person to create acme-docs and approve this agent for it." },
84
+ { command: "saturndocs sites create acme-docs --no-wait --json", description: "Print the link at once; finish with saturndocs login --resume." }
85
+ ]
86
+ });
87
+ function originOf(globals) {
88
+ return parseOrigin(globals.api ?? void 0);
89
+ }
90
+ function pendingResult(pending, store) {
91
+ return {
92
+ status: "pending",
93
+ verification_uri_complete: pending.verification_uri_complete,
94
+ verification_uri: pending.verification_uri,
95
+ user_code: pending.user_code,
96
+ expires_at: pending.expires_at,
97
+ store
98
+ };
99
+ }
100
+ function approvalNotice(pending) {
101
+ return [
102
+ "Ask the person who manages the site to open this link and approve:",
103
+ ` ${pending.verification_uri_complete}`,
104
+ `Code: ${pending.user_code} (it must match the code on the page)`,
105
+ `The link expires at ${pending.expires_at}.`,
106
+ ""
107
+ ].join("\n");
108
+ }
109
+ function openBrowser(url) {
110
+ const [file, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
111
+ execFile(file, args, { windowsHide: true }, () => void 0).unref();
112
+ }
113
+ function storesOrRefuse(environment) {
114
+ const choice = storesFor(environment);
115
+ if (!hasAnyStore(choice)) throw windowsUnsupported();
116
+ return choice;
117
+ }
118
+ async function beginLogin(origin, request, environment, deadlineAt) {
119
+ const now = environment.now ?? Date.now;
120
+ const choice = storesOrRefuse(environment);
121
+ const started = await startDevice(flowContext(origin, environment), request, deadlineAt);
122
+ const pending = {
123
+ device_code: started.device_code,
124
+ user_code: started.user_code,
125
+ verification_uri: started.verification_uri,
126
+ verification_uri_complete: started.verification_uri_complete,
127
+ interval: started.interval,
128
+ expires_at: new Date(now() + started.expires_in * 1e3).toISOString(),
129
+ site: request.site,
130
+ new_site: request.newSite,
131
+ scope: request.scope
132
+ };
133
+ const store = await withCredentialLock(choice, async () => {
134
+ const selection = await selectStore(choice, origin.origin);
135
+ if (selection === null) throw windowsUnsupported();
136
+ return saveRecord(selection.store, { ...selection.record ?? emptyRecord(origin.origin), pending });
137
+ }, lockOptions(environment));
138
+ return { pending, store: store.label };
139
+ }
140
+ async function updatePending(origin, environment, deviceCode, change) {
141
+ const choice = storesOrRefuse(environment);
142
+ await withCredentialLock(choice, async () => {
143
+ const loaded = await loadRecord(choice, origin.origin);
144
+ const pending = loaded?.record.pending ?? null;
145
+ if (loaded === null || pending === null || pending.device_code !== deviceCode) return;
146
+ await saveRecord(loaded.store, { ...loaded.record, pending: change(pending) });
147
+ }, lockOptions(environment));
148
+ }
149
+ function pollKey(deviceCode) {
150
+ return createHash("sha256").update(deviceCode).digest("hex").slice(0, 16);
151
+ }
152
+ async function finishLogin(origin, pending, environment, deadlineAt) {
153
+ const now = environment.now ?? Date.now;
154
+ const ctx = flowContext(origin, environment);
155
+ const choice = storesOrRefuse(environment);
156
+ const stillWaiting = async () => {
157
+ const holder2 = await loadRecord(choice, origin.origin);
158
+ if (holder2 === null || holder2.record.pending?.device_code !== pending.device_code) throw new CliError("conflict", "This approval is no longer waiting. Run saturndocs login again for a new link.");
159
+ return holder2;
160
+ };
161
+ const holder = await stillWaiting();
162
+ const result = await withPollLock(choice, holder.store, pollKey(pending.device_code), async () => {
163
+ await stillWaiting();
164
+ const outcome = await pollDevice(ctx, pending, deadlineAt, (seconds) => updatePending(origin, environment, pending.device_code, (current) => ({ ...current, interval: seconds })).catch(() => void 0));
165
+ if (outcome.kind === "timeout") {
166
+ throw new CliError("wait_timeout", "No one approved the request before --timeout. The request is still open until it expires.", {
167
+ recovery: { command: "saturndocs login --resume", replay: null, message: "Run saturndocs login --resume to keep waiting for the same approval." }
168
+ });
169
+ }
170
+ if (outcome.kind !== "approved") {
171
+ await updatePending(origin, environment, pending.device_code, () => null);
172
+ if (outcome.kind === "denied") throw new CliError("forbidden", "The person denied the request in the browser. Nothing was saved.");
173
+ if (outcome.kind === "expired") throw new CliError("wait_timeout", "The approval link expired before anyone approved it. Run saturndocs login again for a new link.", { mutation: "known" });
174
+ throw new CliError("conflict", "This approval was already used or is no longer valid. Run saturndocs login again for a new link.");
175
+ }
176
+ const grant = grantFromTokens(outcome.tokens, now());
177
+ const revoked = (token) => revokeToken(ctx, token).then(() => true, () => false);
178
+ let displaced = null;
179
+ let writeAttempted = false;
180
+ let saving;
181
+ try {
182
+ saving = await withCredentialLock(choice, async () => {
183
+ const loaded = await loadRecord(choice, origin.origin);
184
+ if (loaded === null || loaded.record.pending?.device_code !== pending.device_code) return { kind: "canceled" };
185
+ const previous = loaded.record.grants[grant.site_id]?.refresh_token ?? null;
186
+ displaced = previous;
187
+ const record = { ...loaded.record, default_site: grant.site_id, grants: { ...loaded.record.grants, [grant.site_id]: grant }, pending: null };
188
+ writeAttempted = true;
189
+ try {
190
+ return { kind: "saved", store: await saveRecord(loaded.store, record) };
191
+ } catch (error) {
192
+ const reason = error instanceof Error ? error.message : String(error);
193
+ const code = error instanceof CliError ? error.code : "service_unavailable";
194
+ try {
195
+ const stored = await readStoredRecord(loaded.store, origin.origin);
196
+ const token = stored?.grants[grant.site_id]?.refresh_token ?? null;
197
+ if (token === grant.refresh_token) return { kind: "saved", store: loaded.store };
198
+ return { kind: "not_stored", reason, code, previousKept: previous !== null && token === previous };
199
+ } catch {
200
+ return { kind: "unknown", reason };
201
+ }
202
+ }
203
+ }, lockOptions(environment));
204
+ } catch (error) {
205
+ const reason = error instanceof Error ? error.message : String(error);
206
+ if (writeAttempted) saving = { kind: "unknown", reason };
207
+ else {
208
+ const cleaned = await revoked(grant.refresh_token);
209
+ throw new CliError(error instanceof CliError ? error.code : "service_unavailable", `The approval succeeded, but the saved logins could not be read to store it: ${reason} ${cleaned ? "The approved grant was revoked; run saturndocs login again." : `The approved grant for ${grant.site_id} could not be revoked; a person can revoke it from the dashboard.`}`, { mutation: cleaned ? "known" : "unknown", cause: error });
210
+ }
211
+ }
212
+ if (saving.kind === "unknown") {
213
+ throw new CliError("service_unavailable", `The approval succeeded, but saving the login failed (${saving.reason}) and the store could not be read back, so neither the new grant nor the earlier one was revoked. Run saturndocs auth status to see which login is kept, and revoke the other from the dashboard.`, { mutation: "unknown" });
214
+ }
215
+ if (saving.kind === "not_stored") {
216
+ const cleaned = await revoked(grant.refresh_token);
217
+ throw new CliError(saving.code, `The approval succeeded, but the login could not be saved: ${saving.reason} ${cleaned ? "The approved grant was revoked" : `The approved grant for ${grant.site_id} could not be revoked; a person can revoke it from the dashboard`}${saving.previousKept ? ", and the earlier login for this site is unchanged." : "."}`, { mutation: "unknown" });
218
+ }
219
+ const saved = saving.kind === "saved" ? saving.store : null;
220
+ if (saved === null) {
221
+ const cleaned = await revoked(grant.refresh_token);
222
+ throw new CliError("conflict", cleaned ? "The login was canceled while it waited for approval, so the approved grant was revoked and nothing was saved." : `The login was canceled while it waited for approval and nothing was saved, but the approved grant for ${grant.site_id} could not be revoked. A person can revoke it from the dashboard.`, { mutation: cleaned ? "known" : "unknown" });
223
+ }
224
+ const replacedToken = displaced;
225
+ const replaced = replacedToken === null ? null : await revoked(replacedToken);
226
+ return { grant, store: saved, replaced };
227
+ });
228
+ let status = null;
229
+ try {
230
+ status = await grantStatus(ctx, result.grant.access_token, deadlineAt);
231
+ } catch {
232
+ status = null;
233
+ }
234
+ return {
235
+ status: "approved",
236
+ site_id: result.grant.site_id,
237
+ scope: result.grant.scope,
238
+ store: result.store.label,
239
+ access_expires_at: result.grant.access_expires_at,
240
+ primary_host: status?.primary_host ?? null,
241
+ repo_connected: status?.repo_connected ?? null,
242
+ replaced_grant_revoked: result.replaced
243
+ };
244
+ }
245
+ function approvedText(result) {
246
+ const lines = [
247
+ `Logged in to ${result.site_id} with ${result.scope.join(", ")}.`,
248
+ `Saved in the ${result.store}.`
249
+ ];
250
+ if (result.primary_host !== null) lines.push(`Site address: https://${result.primary_host}`);
251
+ if (result.repo_connected === false) lines.push("The site has no connected documentation repository yet. The person can connect one from the dashboard.");
252
+ if (result.replaced_grant_revoked === false) lines.push(`The earlier login for ${result.site_id} could not be revoked on the server. A person can revoke it from the dashboard.`);
253
+ return lines.join("\n");
254
+ }
255
+ async function runLogin(globals, request, environment, command) {
256
+ const writer = createResultWriter({ json: globals.json });
257
+ const context = { command, siteId: request.site };
258
+ const login = loginEnvironment(environment);
259
+ const startedAt = (login.now ?? Date.now)();
260
+ try {
261
+ const origin = originOf(globals);
262
+ let pending;
263
+ let store;
264
+ if (request.resume) {
265
+ const loaded = await loadRecord(storesOrRefuse(login), origin.origin);
266
+ const waiting = loaded?.record.pending ?? null;
267
+ if (loaded === null || waiting === null) throw invalidInput("No login is waiting for approval. Run saturndocs login to start one.");
268
+ assertSameOrigin(origin, waiting.verification_uri, "verification link");
269
+ assertSameOrigin(origin, waiting.verification_uri_complete, "verification link");
270
+ pending = waiting;
271
+ store = loaded.store.label;
272
+ } else {
273
+ ({ pending, store } = await beginLogin(origin, request, login, globals.timeout === null ? null : startedAt + globals.timeout * 1e3));
274
+ }
275
+ process.stderr.write(approvalNotice(pending));
276
+ if (request.open && globals.input) openBrowser(pending.verification_uri_complete);
277
+ if (!request.wait) {
278
+ process.exitCode = writer.write(successResult(context, pendingResult(pending, store)), {
279
+ text: "Waiting is off. After the person approves, run saturndocs login --resume."
280
+ });
281
+ return;
282
+ }
283
+ const deadlineAt = globals.timeout === null ? null : startedAt + globals.timeout * 1e3;
284
+ const result = await finishLogin(origin, pending, login, deadlineAt);
285
+ context.siteId = result.site_id;
286
+ process.exitCode = writer.write(successResult(context, result), { text: approvedText(result) });
287
+ } catch (error) {
288
+ process.exitCode = writer.write(failureResult(asCliError(error), context));
289
+ }
290
+ }
291
+ function loginRequest(globals, options) {
292
+ const resume = options.resume === true;
293
+ const newSite = options.newSite === void 0 ? null : validateNewSite(options.newSite);
294
+ if (globals.site !== null && newSite !== null) throw invalidInput("Pass --site for an existing site or --new-site for a new one, not both.");
295
+ if (resume && (globals.site !== null || newSite !== null || options.scope !== void 0)) {
296
+ throw invalidInput("--resume continues the waiting login as it was started; it takes no --site, --new-site, or --scope.");
297
+ }
298
+ if (resume && options.wait === false) throw invalidInput("--resume waits; it cannot be combined with --no-wait.");
299
+ return { site: globals.site, newSite, scope: normalizeScope(options.scope), wait: options.wait !== false, resume, open: options.open === true };
300
+ }
301
+ function registerLogin(program, _cliDir, environment = {}) {
302
+ const login = program.command("login").option("--new-site <address>", "Propose a new site address; the person creates the site while approving.").option("--scope <permissions>", "Comma-separated permissions to request: read, draft, build, publish.").option("--no-wait", "Print the approval link and exit; finish later with --resume.").option("--resume", "Wait for the approval started by an earlier --no-wait.").option("--open", "Open the approval link in the default browser.").action(async (options, self) => {
303
+ const globals = resolveGlobalOptions(self);
304
+ let request;
305
+ try {
306
+ request = loginRequest(globals, options);
307
+ } catch (error) {
308
+ process.exitCode = createResultWriter({ json: globals.json }).write(failureResult(error, { command: "login", siteId: globals.site }));
309
+ return;
310
+ }
311
+ await runLogin(globals, request, environment, "login");
312
+ });
313
+ applyCommandHelp(login, LOGIN_METADATA[0]);
314
+ }
315
+ function registerSitesCreate(sites, environment = {}) {
316
+ const create = sites.command("create").argument("<address>", "The proposed site address.").option("--scope <permissions>", "Comma-separated permissions to request: read, draft, build, publish.").option("--no-wait", "Print the approval link and exit; finish later with saturndocs login --resume.").option("--open", "Open the approval link in the default browser.").action(async (address, options, self) => {
317
+ const globals = resolveGlobalOptions(self);
318
+ let request;
319
+ try {
320
+ if (globals.site !== null) throw invalidInput("sites create proposes a new site; it takes no --site.");
321
+ request = loginRequest(globals, { ...options, newSite: address, resume: false });
322
+ } catch (error) {
323
+ process.exitCode = createResultWriter({ json: globals.json }).write(failureResult(error, { command: "sites create", siteId: null }));
324
+ return;
325
+ }
326
+ await runLogin(globals, request, environment, "sites create");
327
+ });
328
+ applyCommandHelp(create, SITES_CREATE_METADATA);
329
+ }
330
+ function registerLogout(program, _cliDir, environment = {}) {
331
+ const logout = program.command("logout").option("--all", "Revoke and forget every saved login for this API origin.").action(async (options, self) => {
332
+ const globals = resolveGlobalOptions(self);
333
+ const writer = createResultWriter({ json: globals.json });
334
+ const context = { command: "logout", siteId: globals.site };
335
+ const login = loginEnvironment(environment);
336
+ try {
337
+ if (options.all === true && globals.site !== null) throw invalidInput("Pass --site for one login or --all for every login, not both.");
338
+ const origin = originOf(globals);
339
+ const choice = storesOrRefuse(login);
340
+ const outcome = await withCredentialLock(choice, async () => {
341
+ const { loaded, unreadable } = await allRecords(choice, origin.origin);
342
+ const unchecked = unreadable.map((entry) => ({ store: entry.store.label, reason: entry.reason }));
343
+ const everyStoreAnswered = unreadable.length === 0;
344
+ const known = [...new Set(loaded.flatMap((entry) => Object.keys(entry.record.grants)))];
345
+ const pendingAnywhere = loaded.some((entry) => entry.record.pending !== null);
346
+ if (everyStoreAnswered && known.length === 0 && !pendingAnywhere) throw invalidInput("No login is saved for this API origin.");
347
+ let site = null;
348
+ if (options.all !== true) {
349
+ const primary = loaded[0]?.record ?? null;
350
+ site = globals.site ?? (primary !== null && primary.default_site !== null && primary.default_site in primary.grants ? primary.default_site : null) ?? (known.length === 1 ? known[0] : null);
351
+ if (site === null && everyStoreAnswered) {
352
+ throw invalidInput(known.length === 0 ? "No site has a saved login. Run saturndocs logout --all to cancel a login that is waiting for approval." : "Several sites have saved logins. Pass --site, or --all.");
353
+ }
354
+ if (site !== null && !known.includes(site) && everyStoreAnswered) throw invalidInput(`No login is saved for ${site}.`);
355
+ }
356
+ const revoked = [];
357
+ const failed = [];
358
+ const remaining = [];
359
+ for (const entry of loaded) {
360
+ const record = { ...entry.record, grants: { ...entry.record.grants } };
361
+ const targets = options.all === true ? Object.keys(record.grants) : Object.keys(record.grants).filter((name) => name === site);
362
+ const clearsPending = options.all === true && record.pending !== null;
363
+ if (targets.length === 0 && !clearsPending) {
364
+ remaining.push(...Object.keys(record.grants));
365
+ continue;
366
+ }
367
+ for (const name of targets) {
368
+ const grant = record.grants[name];
369
+ try {
370
+ await revokeToken(flowContext(origin, login), grant.refresh_token);
371
+ revoked.push({ site_id: name, store: entry.store.label });
372
+ } catch (error) {
373
+ failed.push({ site_id: name, store: entry.store.label, reason: error instanceof Error ? error.message : String(error) });
374
+ }
375
+ delete record.grants[name];
376
+ }
377
+ if (clearsPending) record.pending = null;
378
+ if (record.default_site !== null && !(record.default_site in record.grants)) record.default_site = Object.keys(record.grants)[0] ?? null;
379
+ try {
380
+ await saveRecord(entry.store, record);
381
+ remaining.push(...Object.keys(record.grants));
382
+ } catch (error) {
383
+ const reason = error instanceof Error ? error.message : String(error);
384
+ try {
385
+ const stored = await readStoredRecord(entry.store, origin.origin);
386
+ const left = Object.keys(stored?.grants ?? {});
387
+ remaining.push(...left);
388
+ const stillThere = targets.filter((name) => left.includes(name));
389
+ const pendingKept = clearsPending && (stored?.pending ?? null) !== null;
390
+ const kept = [...stillThere.length > 0 ? [`the login for ${stillThere.join(", ")}`] : [], ...pendingKept ? ["the login waiting for approval"] : []];
391
+ failed.push({ site_id: null, store: entry.store.label, reason: kept.length > 0 ? `${kept.join(" and ")} could not be removed there: ${reason}` : `The login was removed there, but the change could not be confirmed on disk: ${reason}` });
392
+ } catch {
393
+ unchecked.push({ store: entry.store.label, reason: `the delete may or may not have landed (${reason}), and the store could not be read back` });
394
+ }
395
+ }
396
+ }
397
+ return { revoked, failed, remaining, unchecked };
398
+ }, lockOptions(login));
399
+ const environmentNote = environmentToken(login.env) === void 0 ? "" : `
400
+ ${TOKEN_VARIABLE} is still set; logout does not change it.`;
401
+ const problems = [
402
+ ...outcome.failed.map((entry) => entry.site_id === null ? `${entry.store}: ${entry.reason}` : `${entry.site_id} (${entry.store}): the server did not confirm revocation; a person can revoke it from the dashboard`),
403
+ ...outcome.unchecked.map((entry) => `${entry.store} could not be read, so a login kept there may still work; run saturndocs logout again when it can be read`)
404
+ ];
405
+ if (problems.length > 0) {
406
+ throw new CliError("service_unavailable", `Logout did not finish everywhere. ${problems.join(". ")}.`, { data: outcome, mutation: "unknown" });
407
+ }
408
+ process.exitCode = writer.write(successResult(context, outcome), {
409
+ text: `${outcome.revoked.length === 0 ? "Nothing to revoke." : `Revoked and deleted: ${[...new Set(outcome.revoked.map((entry) => entry.site_id))].join(", ")}.`}${environmentNote}`
410
+ });
411
+ } catch (error) {
412
+ process.exitCode = writer.write(failureResult(asCliError(error), context));
413
+ }
414
+ });
415
+ applyCommandHelp(logout, LOGOUT_METADATA[0]);
416
+ }
417
+
418
+ export {
419
+ LOGIN_METADATA,
420
+ LOGOUT_METADATA,
421
+ SITES_CREATE_METADATA,
422
+ runLogin,
423
+ registerLogin,
424
+ registerSitesCreate,
425
+ registerLogout
426
+ };
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  requestedSite
3
- } from "./chunk-W3GKH5DY.js";
3
+ } from "./chunk-BOWRQKXR.js";
4
4
  import {
5
5
  asCliError,
6
6
  clientFor
7
- } from "./chunk-KOJJUISB.js";
7
+ } from "./chunk-FUZE54DG.js";
8
8
  import {
9
9
  applyCommandHelp
10
10
  } from "./chunk-M2BZEDAS.js";
@@ -18,7 +18,7 @@ import {
18
18
  resolveGlobalOptions,
19
19
  resolveTarget,
20
20
  successResult
21
- } from "./chunk-ADZOBRZE.js";
21
+ } from "./chunk-3KCCCMQY.js";
22
22
 
23
23
  // src/commands/pages.ts
24
24
  import { InvalidArgumentError } from "commander";
@@ -1,3 +1,9 @@
1
+ import {
2
+ asCliError,
3
+ environmentToken,
4
+ loginEnvironment,
5
+ resolveSavedLogin
6
+ } from "./chunk-FUZE54DG.js";
1
7
  import {
2
8
  applyCommandHelp
3
9
  } from "./chunk-M2BZEDAS.js";
@@ -7,18 +13,27 @@ import {
7
13
  createClient,
8
14
  createResultWriter,
9
15
  failureResult,
10
- invalidInput,
16
+ invalidInput2 as invalidInput,
11
17
  isManagementError,
18
+ parseOrigin,
12
19
  requireCommitSha,
13
20
  resolveGlobalOptions,
14
21
  resolveTarget,
15
22
  successResult
16
- } from "./chunk-ADZOBRZE.js";
23
+ } from "./chunk-3KCCCMQY.js";
17
24
 
18
25
  // src/commands/manage.ts
19
26
  import { readFile } from "fs/promises";
20
27
  var METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
21
28
  var PUBLIC_READS = /* @__PURE__ */ new Set(["", "openapi.json"]);
29
+ function isPublicRead(method, path, site) {
30
+ if (method.toUpperCase() !== "GET" || site !== void 0) return false;
31
+ try {
32
+ return PUBLIC_READS.has(routeOf(path));
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
22
37
  var SITELESS_READS = /* @__PURE__ */ new Set(["", "openapi.json", "sites"]);
23
38
  var SIDE_EFFECTING_GETS = [
24
39
  /^suggestions\/[^/]+\/session\/ws$/u,
@@ -213,15 +228,18 @@ function registerManage(program) {
213
228
  const site = globals.site ?? options.site;
214
229
  const context = { command: "manage", siteId: site ?? null };
215
230
  try {
231
+ const api = globals.api ?? options.api;
232
+ const login = loginEnvironment();
233
+ const token = environmentToken(login.env) ?? (isPublicRead(method, path ?? "", site) ? void 0 : (await resolveSavedLogin(parseOrigin(api), site ?? null, login))?.token);
216
234
  const data = await callManagement(method, path ?? "", {
217
235
  ...options,
218
236
  site,
219
- ...globals.api === null ? {} : { api: globals.api },
237
+ api,
220
238
  ...globals.timeout === null ? {} : { timeout: globals.timeout }
221
- }, process.env.SATURNDOCS_MANAGEMENT_TOKEN);
239
+ }, token);
222
240
  process.exitCode = writer.write(successResult(context, data), { text: JSON.stringify(data, null, 2) });
223
241
  } catch (error) {
224
- process.exitCode = writer.write(failureResult(error, context));
242
+ process.exitCode = writer.write(failureResult(asCliError(error), context));
225
243
  }
226
244
  });
227
245
  applyCommandHelp(command, metadata);
@@ -233,13 +251,14 @@ function registerManage(program) {
233
251
  " Every non-GET, and GET on credentials, github/install, slack/install, or a suggestion session stream, needs --site.",
234
252
  " A raw approve or dismiss needs --base and --head, or expected_base_sha and expected_head_sha in --data.",
235
253
  " Without --site only GET, GET openapi.json, and GET sites answer; the first two need no credential.",
236
- " Authentication: SATURNDOCS_MANAGEMENT_TOKEN. Provider installation returns an authorization URL.",
254
+ " Authentication: SATURNDOCS_MANAGEMENT_TOKEN, or the saved login from saturndocs login. Provider installation returns an authorization URL.",
237
255
  ""
238
256
  ].join("\n")
239
257
  );
240
258
  }
241
259
 
242
260
  export {
261
+ isPublicRead,
243
262
  callManagement,
244
263
  MANAGE_METADATA,
245
264
  registerManage
@@ -2,7 +2,7 @@ import {
2
2
  EXIT,
3
3
  failureResult,
4
4
  interrupted
5
- } from "./chunk-ADZOBRZE.js";
5
+ } from "./chunk-3KCCCMQY.js";
6
6
 
7
7
  // src/adapter/signals.ts
8
8
  var active = null;