@wirecat/drive-cli 0.60.0 → 0.62.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 (174) hide show
  1. package/README.md +4 -5
  2. package/dist/bin/drive.js +2 -2
  3. package/dist/browse.d.ts +20 -0
  4. package/dist/browse.d.ts.map +1 -0
  5. package/dist/browse.js +146 -0
  6. package/dist/browse.js.map +1 -0
  7. package/dist/bundle/{all-profiles-537I27Z4.js → all-profiles-CKD2DWUK.js} +14 -14
  8. package/dist/bundle/{anthropic-X4NWVHDF.js → anthropic-E3T4USLA.js} +9 -9
  9. package/dist/bundle/{app-server-KSHJKKS7.js → app-server-JB2AEWWL.js} +58 -55
  10. package/dist/bundle/{bun-WTBGGCUC.js → bun-CC44AAND.js} +2 -2
  11. package/dist/bundle/{bun-sqlite-T7Y3JFFD.js → bun-sqlite-AUMFKYVR.js} +8 -8
  12. package/dist/bundle/{chunk-2AXA5SKP.js → chunk-27YUUGXQ.js} +1 -1
  13. package/dist/bundle/{chunk-HIP43OGZ.js → chunk-2HF2MRXI.js} +1 -1
  14. package/dist/bundle/{chunk-AXWXQNTC.js → chunk-2KN35F32.js} +10 -10
  15. package/dist/bundle/{chunk-EBLA7GXY.js → chunk-4OSSOWDM.js} +2 -1
  16. package/dist/bundle/{chunk-XFXRGQXJ.js → chunk-4SIZEJ3M.js} +2 -2
  17. package/dist/bundle/{chunk-LQSRVQ3V.js → chunk-67ZQCWBV.js} +3 -3
  18. package/dist/bundle/{chunk-FO4TCH6P.js → chunk-6EY46GAN.js} +2 -2
  19. package/dist/bundle/{chunk-4XZXH2NM.js → chunk-7W5HYGVW.js} +4 -2
  20. package/dist/bundle/{chunk-FZOCQQ66.js → chunk-7ZXIWZQ6.js} +12 -12
  21. package/dist/bundle/{chunk-YGG7UA3C.js → chunk-AH5C3D3D.js} +5 -5
  22. package/dist/bundle/{chunk-YDN2RH5S.js → chunk-AQVUEZEP.js} +2 -2
  23. package/dist/bundle/{chunk-N7S2UPF3.js → chunk-CJHY5YIF.js} +494 -227
  24. package/dist/bundle/{chunk-MXP35VPO.js → chunk-CZ2GJHLL.js} +2 -2
  25. package/dist/bundle/{chunk-HQVIK6PM.js → chunk-DJOAMGF4.js} +262 -368
  26. package/dist/bundle/{chunk-HCJG7ENG.js → chunk-DRZZBN3V.js} +3 -3
  27. package/dist/bundle/{chunk-TXMTMEHW.js → chunk-DWJHL6DV.js} +4 -4
  28. package/dist/bundle/{chunk-S36HRPNS.js → chunk-E43ENLJJ.js} +1 -1
  29. package/dist/bundle/{chunk-4VHBDVY2.js → chunk-EOOGWUTP.js} +14 -10
  30. package/dist/bundle/{chunk-5XHLQZAG.js → chunk-EW7PKB4M.js} +58 -49
  31. package/dist/bundle/{chunk-TKW4QWCY.js → chunk-FEZF3TII.js} +12 -6
  32. package/dist/bundle/{chunk-KEXTTZJM.js → chunk-FNWIJ6EJ.js} +2 -2
  33. package/dist/bundle/{chunk-OYNUBWD2.js → chunk-FUITWY7O.js} +1 -1
  34. package/dist/bundle/{chunk-TVQDMP2F.js → chunk-HCNQT3QE.js} +1440 -771
  35. package/dist/bundle/{chunk-FTZNUZO7.js → chunk-HG6CAYJH.js} +3 -3
  36. package/dist/bundle/{chunk-SZXI4OXX.js → chunk-IR4SQLBR.js} +2 -2
  37. package/dist/bundle/{chunk-UTFATA4K.js → chunk-JK3U25QZ.js} +1 -1
  38. package/dist/bundle/{chunk-SBHSNOU4.js → chunk-JN5TVEEL.js} +96 -27
  39. package/dist/bundle/{chunk-IXN7Y6JA.js → chunk-KLFSRKHB.js} +1 -1
  40. package/dist/bundle/{chunk-57QVQGBE.js → chunk-L7K2MOIC.js} +22 -22
  41. package/dist/bundle/{chunk-JGUJJNGZ.js → chunk-LQKD257P.js} +582 -424
  42. package/dist/bundle/{chunk-GVRS5AIH.js → chunk-LWE4JGRN.js} +2 -2
  43. package/dist/bundle/{chunk-D6WIWOQC.js → chunk-MN4VXU3M.js} +4 -4
  44. package/dist/bundle/{chunk-QIJWSKZL.js → chunk-N7OZPKU7.js} +4 -4
  45. package/dist/bundle/{chunk-W62CON5K.js → chunk-O2XOX4HB.js} +34 -10
  46. package/dist/bundle/{chunk-PDYHEWKG.js → chunk-O7ALBI2I.js} +5 -5
  47. package/dist/bundle/{chunk-PETFPXLU.js → chunk-OBH5BA62.js} +3 -3
  48. package/dist/bundle/{chunk-246P2DCT.js → chunk-OD4U7GUY.js} +113 -51
  49. package/dist/bundle/{chunk-67QXMO2G.js → chunk-ONP2IBHY.js} +26 -26
  50. package/dist/bundle/{chunk-JQLIM6BH.js → chunk-OTROVC4E.js} +1 -1
  51. package/dist/bundle/{chunk-73TTP6ET.js → chunk-PEQA6LA5.js} +617 -243
  52. package/dist/bundle/{chunk-ALWTUDZF.js → chunk-Q2LRPOKL.js} +22 -14
  53. package/dist/bundle/{chunk-CKGHRWVR.js → chunk-QCKZ3GAA.js} +4 -4
  54. package/dist/bundle/chunk-QCX6XZLA.js +415 -0
  55. package/dist/bundle/{chunk-UVLSWLPZ.js → chunk-QH7DOVO3.js} +204 -58
  56. package/dist/bundle/{chunk-OMKUBCNN.js → chunk-QTI6IVHZ.js} +8 -8
  57. package/dist/bundle/{chunk-6HTKB4WC.js → chunk-R347FPYU.js} +1 -1
  58. package/dist/bundle/chunk-RIDQNVZM.js +64 -0
  59. package/dist/bundle/{chunk-ZPQS7XJA.js → chunk-RPMKG63Z.js} +18 -4
  60. package/dist/bundle/{chunk-XDIEQ2CE.js → chunk-RWSXVCSG.js} +3 -3
  61. package/dist/bundle/{chunk-3TQHIHZI.js → chunk-SVPCHFKI.js} +2 -2
  62. package/dist/bundle/{chunk-V2VMBM7O.js → chunk-SW4I5BR7.js} +2 -2
  63. package/dist/bundle/{chunk-EHAI773E.js → chunk-T5NWWXS2.js} +2 -2
  64. package/dist/bundle/{chunk-4CBZEAQ7.js → chunk-T7X53FCJ.js} +34 -34
  65. package/dist/bundle/{chunk-77C5XRH3.js → chunk-TDX4GZFO.js} +7 -7
  66. package/dist/bundle/{chunk-PPL5ASW2.js → chunk-U2BFYSQV.js} +14158 -2039
  67. package/dist/bundle/{chunk-DQDKLZAK.js → chunk-UGXN5D7U.js} +719 -128
  68. package/dist/bundle/{chunk-UNJE63JK.js → chunk-UOXOLGNG.js} +2 -2
  69. package/dist/bundle/{chunk-LJ77Y3TK.js → chunk-UQLWMGSD.js} +6 -5
  70. package/dist/bundle/{chunk-HFGR33KD.js → chunk-VAYB52HF.js} +33 -31
  71. package/dist/bundle/{chunk-GD6TQ6U4.js → chunk-VQDD64A4.js} +8 -8
  72. package/dist/bundle/{chunk-22ATLSNK.js → chunk-W4RTIL7S.js} +5 -5
  73. package/dist/bundle/{chunk-UVYVIHEA.js → chunk-WZKEU7WR.js} +4 -2
  74. package/dist/bundle/{chunk-5AMRCBMP.js → chunk-XEW2EN6F.js} +51 -37
  75. package/dist/bundle/{chunk-O37ESNAP.js → chunk-XFRRKZHQ.js} +242 -90
  76. package/dist/bundle/{chunk-K6XVRA6U.js → chunk-XS5POQST.js} +1 -1
  77. package/dist/bundle/{chunk-IRZ7OF3F.js → chunk-XZUS7XRO.js} +1 -1
  78. package/dist/bundle/{chunk-V7QMHMR3.js → chunk-YALI4C7C.js} +6 -6
  79. package/dist/bundle/{chunk-73MNUSP3.js → chunk-YMWENGKH.js} +1 -1
  80. package/dist/bundle/{chunk-MVNPE5FZ.js → chunk-YOJDGAPT.js} +8 -8
  81. package/dist/bundle/{chunk-DMHGWL5D.js → chunk-YPFUYQDP.js} +13 -13
  82. package/dist/bundle/{chunk-VVCZS42A.js → chunk-YUWPNG7B.js} +1 -1
  83. package/dist/bundle/{chunk-VRW6ZDTH.js → chunk-YXYTY4GF.js} +39 -26
  84. package/dist/bundle/{chunk-ZYCLPJ7U.js → chunk-ZMOUUOT2.js} +1 -1
  85. package/dist/bundle/command-contract-OB5BRABN.js +39 -0
  86. package/dist/bundle/{decode-35N57AFW.js → decode-WIIX3Y2X.js} +8 -8
  87. package/dist/bundle/{dispatch-CWXZW3PL.js → dispatch-GEFIXA6X.js} +9 -9
  88. package/dist/bundle/drive.js +11 -11
  89. package/dist/bundle/{echarts-3P3QZWMU.js → echarts-OYINM4C4.js} +2 -2
  90. package/dist/bundle/{embed-Q6Q5IOJQ.js → embed-DWZIYMBX.js} +9 -9
  91. package/dist/bundle/{embedder-D44JDTAA.js → embedder-ILWH7ZRM.js} +12 -12
  92. package/dist/bundle/entry-V5V3TOTY.js +22 -0
  93. package/dist/bundle/{failure-GRMMSDCZ.js → failure-GV77W3CD.js} +4 -4
  94. package/dist/bundle/first-run-V3VVLQF4.js +30 -0
  95. package/dist/bundle/first-screen-Y3RIN7FU.js +37 -0
  96. package/dist/bundle/{google-6ZZDKFBN.js → google-KLZSUAVY.js} +13 -13
  97. package/dist/bundle/{google-api-E6MOJ4ZD.js → google-api-HZQ5R4ZO.js} +83 -64
  98. package/dist/bundle/grants-L7XLHLUT.js +105 -0
  99. package/dist/bundle/{identity-TID7S5NE.js → identity-J2DON4IO.js} +6 -6
  100. package/dist/bundle/{instructions-ANJN4HV3.js → instructions-HGOJ23AJ.js} +1 -1
  101. package/dist/bundle/{login-BGMK2ABH.js → login-BD2TS4GY.js} +64 -64
  102. package/dist/bundle/{mcp-WBHKX5E3.js → mcp-GWDA3HOA.js} +2 -2
  103. package/dist/bundle/{node-VOB45ES2.js → node-CPKTDPH7.js} +2 -2
  104. package/dist/bundle/{node-sqlite-TSX6XQY2.js → node-sqlite-IXDCRLSX.js} +9 -9
  105. package/dist/bundle/oauth-HOGY4YBB.js +22 -0
  106. package/dist/bundle/{open-3USWHGNR.js → open-O7P3ZV3Y.js} +8 -8
  107. package/dist/bundle/{openai-YZ5VGPIP.js → openai-RCFQKCXC.js} +17 -17
  108. package/dist/bundle/{process-44JS2W7L.js → process-KXDRJO22.js} +1 -1
  109. package/dist/bundle/{program-TZLAFKJV.js → program-UCHFC7JQ.js} +266 -104
  110. package/dist/bundle/prompt-EVPPBN5W.js +17 -0
  111. package/dist/bundle/{reasons-ZK3U3CIN.js → reasons-57J2D77K.js} +5 -5
  112. package/dist/bundle/{recognize-OFW7HWTM.js → recognize-MRCYGP2J.js} +7 -7
  113. package/dist/bundle/{remote-YBDRZQZ5.js → remote-L3L4PHKF.js} +10 -10
  114. package/dist/bundle/{rerank-TQQNS5FJ.js → rerank-PSOE6XFT.js} +10 -10
  115. package/dist/bundle/{serve-OPZXMVLH.js → serve-72OGS3BF.js} +12 -12
  116. package/dist/bundle/server-C5TGNFXW.js +70 -0
  117. package/dist/bundle/{server-2D6DDIK5.js → server-SCXKYHBO.js} +44 -44
  118. package/dist/bundle/{services-34WKT3NN.js → services-YAFTELBI.js} +42 -32
  119. package/dist/bundle/{sqlite-runtime-WPUMKLUV.js → sqlite-runtime-DLK4SU33.js} +9 -9
  120. package/dist/bundle/{start-ZXUJZ4JV.js → start-AFFA3LKM.js} +9 -7
  121. package/dist/bundle/{state-AV2RB3AQ.js → state-T5VNAJSZ.js} +9 -9
  122. package/dist/bundle/{store-YKV4GAMS.js → store-4OFK7PKQ.js} +48 -28
  123. package/dist/bundle/{store-3M7N2Q5T.js → store-R6MSY2IM.js} +20 -18
  124. package/dist/bundle/store-maintenance-command-QDMCXGV6.js +60 -0
  125. package/dist/bundle/tokens-HIG36RNS.js +103 -0
  126. package/dist/commands/config.js +1 -1
  127. package/dist/commands/config.js.map +1 -1
  128. package/dist/commands/folders.d.ts +2 -1
  129. package/dist/commands/folders.d.ts.map +1 -1
  130. package/dist/commands/folders.js +16 -3
  131. package/dist/commands/folders.js.map +1 -1
  132. package/dist/commands/session.d.ts.map +1 -1
  133. package/dist/commands/session.js +10 -2
  134. package/dist/commands/session.js.map +1 -1
  135. package/dist/config.d.ts +16 -5
  136. package/dist/config.d.ts.map +1 -1
  137. package/dist/config.js +11 -17
  138. package/dist/config.js.map +1 -1
  139. package/dist/download.d.ts +3 -2
  140. package/dist/download.d.ts.map +1 -1
  141. package/dist/download.js +21 -9
  142. package/dist/download.js.map +1 -1
  143. package/dist/google-api.d.ts +3 -1
  144. package/dist/google-api.d.ts.map +1 -1
  145. package/dist/google-api.js +27 -7
  146. package/dist/google-api.js.map +1 -1
  147. package/dist/login.js +1 -1
  148. package/dist/login.js.map +1 -1
  149. package/dist/program.d.ts.map +1 -1
  150. package/dist/program.js +7 -7
  151. package/dist/program.js.map +1 -1
  152. package/dist/tokens.d.ts.map +1 -1
  153. package/dist/tokens.js +15 -6
  154. package/dist/tokens.js.map +1 -1
  155. package/dist/version.d.ts +1 -1
  156. package/dist/version.js +1 -1
  157. package/package.json +3 -3
  158. package/dist/bundle/chunk-77YTRBL6.js +0 -249
  159. package/dist/bundle/chunk-YYHKVOVK.js +0 -132
  160. package/dist/bundle/command-contract-NUIWUVYB.js +0 -39
  161. package/dist/bundle/entry-ZHCNI7XO.js +0 -22
  162. package/dist/bundle/first-run-3DC2SDWM.js +0 -30
  163. package/dist/bundle/first-screen-YJF4YODC.js +0 -37
  164. package/dist/bundle/grants-GWXDH5GM.js +0 -105
  165. package/dist/bundle/oauth-CEOYXW6C.js +0 -22
  166. package/dist/bundle/prompt-SG7LAOXW.js +0 -17
  167. package/dist/bundle/server-R6G2O772.js +0 -70
  168. package/dist/bundle/store-maintenance-command-WDXNY4ZF.js +0 -60
  169. package/dist/bundle/tokens-F63RXXEF.js +0 -103
  170. package/dist/oauth-application.d.ts +0 -5
  171. package/dist/oauth-application.d.ts.map +0 -1
  172. package/dist/oauth-application.js +0 -9
  173. package/dist/oauth-application.js.map +0 -1
  174. /package/dist/bundle/{chunk-LK2E2ELG.js → chunk-ZQ3GWKDQ.js} +0 -0
@@ -1,74 +1,48 @@
1
1
  import { createRequire as __bundleRequire } from "node:module";
2
2
  const require = __bundleRequire(import.meta.url);
3
3
  import {
4
- operations,
5
- privateFiles
6
- } from "./chunk-TVQDMP2F.js";
7
- import {
8
- commandPathKey,
9
- commandPermissions
10
- } from "./chunk-5XHLQZAG.js";
4
+ activeProfile,
5
+ paths
6
+ } from "./chunk-QCX6XZLA.js";
11
7
  import {
12
- AI_ENTRIES,
13
- checkConfigText,
14
- issueMessage,
15
- settingsFor,
16
- usableProfileName,
17
- withSettingDefaults
18
- } from "./chunk-73TTP6ET.js";
8
+ READ_SCOPE,
9
+ WRITE_SCOPE,
10
+ providerRequest
11
+ } from "./chunk-HCNQT3QE.js";
19
12
  import {
20
- acquireLock
21
- } from "./chunk-DMHGWL5D.js";
13
+ googleError
14
+ } from "./chunk-OTROVC4E.js";
22
15
  import {
23
- LEVELS
24
- } from "./chunk-HFGR33KD.js";
16
+ withTimeLimit
17
+ } from "./chunk-LQKD257P.js";
25
18
  import {
26
- MAX_TEXT_CHARS
27
- } from "./chunk-UNJE63JK.js";
28
- import {
29
- DRIVE_APP
30
- } from "./chunk-XFXRGQXJ.js";
19
+ acquireLock
20
+ } from "./chunk-YPFUYQDP.js";
31
21
  import {
32
22
  Credentials,
33
23
  isMovedRun,
34
24
  keyringService,
35
- resolvePaths,
36
- saveConfigFile,
37
25
  systemKeyring
38
- } from "./chunk-246P2DCT.js";
26
+ } from "./chunk-OD4U7GUY.js";
39
27
  import {
40
- array,
41
- boolean,
42
- integer,
43
- literal,
44
- maxValue,
45
28
  minLength,
46
- minValue,
29
+ nullable,
47
30
  number,
31
+ object,
48
32
  optional,
49
- parse,
50
- picklist,
51
33
  pipe,
52
- record,
53
- regex,
54
- strictObject,
55
- string,
56
- union
57
- } from "./chunk-TKW4QWCY.js";
34
+ safeParse,
35
+ string
36
+ } from "./chunk-FEZF3TII.js";
58
37
  import {
59
38
  CliError,
60
39
  isCliError
61
- } from "./chunk-EBLA7GXY.js";
40
+ } from "./chunk-4OSSOWDM.js";
62
41
  import {
63
42
  __name
64
43
  } from "./chunk-ZVVMGPBJ.js";
65
44
 
66
- // node_modules/.pnpm/@wirecat+cli-core@0.565.0_@wirecat+cli-base@0.75.2_commander@15.0.0_esbuild@0.28.2_type_ff8e334310c9524b6cc272472a342b2f/node_modules/@wirecat/cli-core/dist/oauth/keeper.js
67
- import { createHash as createHash2 } from "node:crypto";
68
- import { join } from "node:path";
69
- import { setTimeout as delay } from "node:timers/promises";
70
-
71
- // node_modules/.pnpm/@wirecat+cli-core@0.565.0_@wirecat+cli-base@0.75.2_commander@15.0.0_esbuild@0.28.2_type_ff8e334310c9524b6cc272472a342b2f/node_modules/@wirecat/cli-core/dist/oauth/authorize.js
45
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/oauth/authorize.js
72
46
  import { createHash, randomBytes } from "node:crypto";
73
47
  import { createServer } from "node:http";
74
48
  var DEFAULT_TIMEOUT_MS = 3e5;
@@ -204,28 +178,33 @@ var authorize = /* @__PURE__ */ __name(async (options) => {
204
178
  }
205
179
  }, "authorize");
206
180
 
207
- // node_modules/.pnpm/@wirecat+cli-core@0.565.0_@wirecat+cli-base@0.75.2_commander@15.0.0_esbuild@0.28.2_type_ff8e334310c9524b6cc272472a342b2f/node_modules/@wirecat/cli-core/dist/oauth/requests.js
181
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/oauth/keeper.js
182
+ import { createHash as createHash2 } from "node:crypto";
183
+ import { join } from "node:path";
184
+ import { setTimeout as delay } from "node:timers/promises";
185
+
186
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/oauth/requests.js
208
187
  var REQUEST_LIMIT_MS = 3e4;
209
188
  var TOKEN_LOG_EVENT = "oauth.token";
210
- var object = /* @__PURE__ */ __name((value) => {
189
+ var object2 = /* @__PURE__ */ __name((value) => {
211
190
  if (typeof value !== "object" || value === null || Array.isArray(value))
212
191
  throw new Error("not an object");
213
192
  return value;
214
193
  }, "object");
215
- var requestSignal = /* @__PURE__ */ __name((signal) => signal ? AbortSignal.any([signal, AbortSignal.timeout(REQUEST_LIMIT_MS)]) : AbortSignal.timeout(REQUEST_LIMIT_MS), "requestSignal");
194
+ var requestSignal = /* @__PURE__ */ __name((deadline, signal) => signal ? AbortSignal.any([signal, deadline]) : deadline, "requestSignal");
216
195
  var cancelledBy = /* @__PURE__ */ __name((signal) => {
217
196
  if (!signal?.aborted)
218
197
  return;
219
198
  throw isCliError(signal.reason) ? signal.reason : new CliError("cancelled", "sign-in was cancelled");
220
199
  }, "cancelledBy");
221
- var post = /* @__PURE__ */ __name(async (url, body, context) => {
200
+ var post = /* @__PURE__ */ __name(async (url, body, context, deadline) => {
222
201
  cancelledBy(context.signal);
223
202
  try {
224
203
  return await context.fetch(url, {
225
204
  method: "POST",
226
205
  headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
227
206
  body,
228
- signal: requestSignal(context.signal),
207
+ signal: requestSignal(deadline, context.signal),
229
208
  redirect: "error"
230
209
  });
231
210
  } catch {
@@ -237,19 +216,20 @@ var clientFields = /* @__PURE__ */ __name(({ client }) => ({
237
216
  client_id: client.clientId,
238
217
  ...client.clientSecret ? { client_secret: client.clientSecret } : {}
239
218
  }), "clientFields");
240
- var requestTokens = /* @__PURE__ */ __name(async (provider, params, context) => {
219
+ var requestTokens = /* @__PURE__ */ __name((provider, params, context) => withTimeLimit(REQUEST_LIMIT_MS, (deadline) => exchangeTokens(provider, params, context, deadline)), "requestTokens");
220
+ var exchangeTokens = /* @__PURE__ */ __name(async (provider, params, context, deadline) => {
241
221
  const operation = params.grant_type ?? "unknown";
242
- const record2 = /* @__PURE__ */ __name((level, fields) => context.log?.[level]({ event: TOKEN_LOG_EVENT, provider: provider.id, operation, pid: process.pid, ...fields }), "record");
222
+ const record = /* @__PURE__ */ __name((level, fields) => context.log?.[level]({ event: TOKEN_LOG_EVENT, provider: provider.id, operation, pid: process.pid, ...fields }), "record");
243
223
  const again = `run ${context.signInCommand} again`;
244
- const response = await post(provider.tokenUrl, new URLSearchParams({ ...params, ...clientFields(context) }), context);
224
+ const response = await post(provider.tokenUrl, new URLSearchParams({ ...params, ...clientFields(context) }), context, deadline);
245
225
  if (!response) {
246
- record2("warn", { outcome: "no_response" });
226
+ record("warn", { outcome: "no_response" });
247
227
  throw new CliError("outcome_unknown", `${provider.name} token request did not finish; ${again} if it keeps failing`, {
248
228
  reason: "oauth.no-response"
249
229
  });
250
230
  }
251
231
  if (!response.ok) {
252
- record2("warn", { outcome: "rejected", status: response.status });
232
+ record("warn", { outcome: "rejected", status: response.status });
253
233
  if (response.status === 429 || response.status >= 500)
254
234
  throw new CliError("provider_unavailable", `${provider.name} token request failed (HTTP ${response.status})`, {
255
235
  status: response.status,
@@ -263,9 +243,9 @@ var requestTokens = /* @__PURE__ */ __name(async (provider, params, context) =>
263
243
  }
264
244
  let body;
265
245
  try {
266
- body = object(await response.json());
246
+ body = object2(await response.json());
267
247
  } catch {
268
- record2("error", { outcome: "unreadable_response", status: response.status });
248
+ record("error", { outcome: "unreadable_response", status: response.status });
269
249
  throw new CliError("invalid_response", `${provider.name} returned an unreadable token response; ${again}`, {
270
250
  reason: "oauth.invalid-response"
271
251
  });
@@ -274,20 +254,20 @@ var requestTokens = /* @__PURE__ */ __name(async (provider, params, context) =>
274
254
  const refreshToken = typeof body.refresh_token === "string" && body.refresh_token ? body.refresh_token : previous?.refreshToken;
275
255
  const expiresIn = body.expires_in;
276
256
  if (typeof body.access_token !== "string" || !body.access_token || expiresIn !== void 0 && (typeof expiresIn !== "number" || !Number.isFinite(expiresIn) || expiresIn <= 0) || body.scope !== void 0 && typeof body.scope !== "string" || body.token_type !== void 0 && typeof body.token_type !== "string") {
277
- record2("error", { outcome: "invalid_response", status: response.status });
257
+ record("error", { outcome: "invalid_response", status: response.status });
278
258
  throw new CliError("invalid_response", `${provider.name} returned an invalid token response; ${again}`, {
279
259
  reason: "oauth.invalid-response"
280
260
  });
281
261
  }
282
262
  if (!refreshToken) {
283
- record2("error", { outcome: "no_refresh_token", status: response.status });
263
+ record("error", { outcome: "no_refresh_token", status: response.status });
284
264
  throw new CliError("authentication_error", `${provider.name} returned no offline refresh token; ${again}`, {
285
265
  reason: "oauth.failed"
286
266
  });
287
267
  }
288
268
  const scopes = typeof body.scope === "string" ? body.scope.split(/\s+/).filter(Boolean) : previous?.scopes ?? [];
289
269
  const tokenType = typeof body.token_type === "string" ? body.token_type : previous?.tokenType;
290
- record2("info", {
270
+ record("info", {
291
271
  outcome: "received",
292
272
  status: response.status,
293
273
  ...previous ? { rotated: refreshToken !== previous.refreshToken } : {}
@@ -299,13 +279,15 @@ var requestTokens = /* @__PURE__ */ __name(async (provider, params, context) =>
299
279
  scopes,
300
280
  ...tokenType ? { tokenType } : {}
301
281
  };
302
- }, "requestTokens");
282
+ }, "exchangeTokens");
303
283
  var revokeToken = /* @__PURE__ */ __name(async (provider, tokens, context) => {
304
284
  if (provider.revoke)
305
285
  return provider.revoke(tokens, context);
306
286
  if (!provider.revokeUrl)
307
287
  throw new CliError("validation_error", `${provider.name} declares no way to revoke a sign-in`);
308
- const response = await post(provider.revokeUrl, new URLSearchParams({ token: tokens.refreshToken, ...clientFields(context) }), context);
288
+ const { revokeUrl } = provider;
289
+ const form = new URLSearchParams({ token: tokens.refreshToken, ...clientFields(context) });
290
+ const response = await withTimeLimit(REQUEST_LIMIT_MS, (deadline) => post(revokeUrl, form, context, deadline));
309
291
  context.log?.[response?.ok ? "info" : "warn"]({
310
292
  event: TOKEN_LOG_EVENT,
311
293
  provider: provider.id,
@@ -321,7 +303,7 @@ var revokeToken = /* @__PURE__ */ __name(async (provider, tokens, context) => {
321
303
  });
322
304
  }, "revokeToken");
323
305
 
324
- // node_modules/.pnpm/@wirecat+cli-core@0.565.0_@wirecat+cli-base@0.75.2_commander@15.0.0_esbuild@0.28.2_type_ff8e334310c9524b6cc272472a342b2f/node_modules/@wirecat/cli-core/dist/oauth/keeper.js
306
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/oauth/keeper.js
325
307
  var inFlight = /* @__PURE__ */ new Map();
326
308
  var refreshedInMemory = /* @__PURE__ */ new Map();
327
309
  var tokenKeeper = /* @__PURE__ */ __name((options) => {
@@ -483,9 +465,9 @@ var tokenKeeper = /* @__PURE__ */ __name((options) => {
483
465
  };
484
466
  }, "tokenKeeper");
485
467
 
486
- // node_modules/.pnpm/@wirecat+cli-core@0.565.0_@wirecat+cli-base@0.75.2_commander@15.0.0_esbuild@0.28.2_type_ff8e334310c9524b6cc272472a342b2f/node_modules/@wirecat/cli-core/dist/oauth/storage.js
468
+ // node_modules/.pnpm/@wirecat+cli-core@0.604.0_@wirecat+cli-base@0.80.9_commander@15.0.0_esbuild@0.28.2_type_4b96f151b4ca40121094ad166c695991/node_modules/@wirecat/cli-core/dist/oauth/storage.js
487
469
  var invalid = /* @__PURE__ */ __name(() => new CliError("authentication_error", "the saved sign-in cannot be read; sign in again", { reason: "oauth.invalid" }), "invalid");
488
- var parse2 = /* @__PURE__ */ __name((raw) => {
470
+ var parse = /* @__PURE__ */ __name((raw) => {
489
471
  let value;
490
472
  try {
491
473
  value = JSON.parse(raw);
@@ -502,7 +484,7 @@ var previousOf = /* @__PURE__ */ __name((raw) => {
502
484
  if (raw === void 0)
503
485
  return {};
504
486
  try {
505
- return parse2(raw);
487
+ return parse(raw);
506
488
  } catch {
507
489
  return {};
508
490
  }
@@ -510,7 +492,7 @@ var previousOf = /* @__PURE__ */ __name((raw) => {
510
492
  var defined = /* @__PURE__ */ __name((value) => Object.fromEntries(Object.entries(value).filter(([, field]) => field !== void 0)), "defined");
511
493
  var driveSessionCodec = {
512
494
  decode: /* @__PURE__ */ __name((raw) => {
513
- const value = parse2(raw);
495
+ const value = parse(raw);
514
496
  const tokens = value.tokens;
515
497
  if (typeof tokens !== "object" || tokens === null || Array.isArray(tokens))
516
498
  throw invalid();
@@ -520,7 +502,11 @@ var driveSessionCodec = {
520
502
  if (!refreshToken || !clientId || typeof value.principal !== "string")
521
503
  throw invalid();
522
504
  return {
523
- client: defined({ clientId, clientSecret: text(value.clientSecret) }),
505
+ client: defined({
506
+ clientId,
507
+ clientSecret: text(value.clientSecret),
508
+ source: text(value.clientSource)
509
+ }),
524
510
  tokens: defined({
525
511
  accessToken: text(fields.access_token),
526
512
  refreshToken,
@@ -538,6 +524,7 @@ var driveSessionCodec = {
538
524
  ...extra,
539
525
  clientId: client.clientId,
540
526
  ...client.clientSecret ? { clientSecret: client.clientSecret } : {},
527
+ ...client.source ? { clientSource: client.source } : {},
541
528
  tokens: defined({
542
529
  ...oldTokens,
543
530
  access_token: tokens.accessToken,
@@ -561,20 +548,20 @@ var keyringFailure = /* @__PURE__ */ __name((thrown, secret) => {
561
548
  var credentialStorage = /* @__PURE__ */ __name((options) => {
562
549
  if (!options.credentials.keyring)
563
550
  throw new CliError("configuration_error", "a sign-in store needs its keyring passed in, never a default");
564
- const credentials = new Credentials(options.credentials);
551
+ const credentials2 = new Credentials(options.credentials);
565
552
  const { account, codec } = options;
566
553
  const moved = options.credentials.isolated === true || options.credentials.keyring === systemKeyring && isMovedRun({ appName: options.credentials.service, env: options.credentials.env ?? process.env });
567
554
  const service = keyringService(options.credentials.service, options.credentials.configDir, options.credentials.isolated);
568
555
  const raw = /* @__PURE__ */ __name((name) => {
569
556
  try {
570
- return credentials.read(name)?.secret;
557
+ return credentials2.read(name)?.secret;
571
558
  } catch (error) {
572
559
  throw keyringFailure(error);
573
560
  }
574
561
  }, "raw");
575
562
  const save = /* @__PURE__ */ __name((value, writeOptions) => {
576
563
  try {
577
- credentials.write(account, value, writeOptions);
564
+ credentials2.write(account, value, writeOptions);
578
565
  } catch (error) {
579
566
  throw keyringFailure(error, value);
580
567
  }
@@ -607,7 +594,7 @@ var credentialStorage = /* @__PURE__ */ __name((options) => {
607
594
  write: /* @__PURE__ */ __name((input, writeOptions) => save(codec.encode({ ...input, previous: raw(account) }), writeOptions), "write"),
608
595
  remove: /* @__PURE__ */ __name(() => {
609
596
  try {
610
- return credentials.remove(account);
597
+ return credentials2.remove(account);
611
598
  } catch (error) {
612
599
  throw keyringFailure(error);
613
600
  }
@@ -615,313 +602,220 @@ var credentialStorage = /* @__PURE__ */ __name((options) => {
615
602
  };
616
603
  }, "credentialStorage");
617
604
 
618
- // node_modules/.pnpm/@wirecat+cli-core@0.565.0_@wirecat+cli-base@0.75.2_commander@15.0.0_esbuild@0.28.2_type_ff8e334310c9524b6cc272472a342b2f/node_modules/@wirecat/cli-core/dist/oauth/client-file.js
619
- import { readFileSync } from "node:fs";
620
- var readClientFile = /* @__PURE__ */ __name((location, options = {}) => {
621
- if (!options.shipped && typeof location === "string") {
622
- const mode = privateFiles({ files: [location], dirs: [] }, options.platform);
623
- if (mode.checked && !mode.ok)
624
- throw new CliError("configuration_error", `the client file can be read by other users of this computer; run chmod 600 ${location} and try again`, { reason: "sign-in.client-file-open" });
625
- }
605
+ // dist/tokens.js
606
+ import { OAuth2Client } from "google-auth-library";
607
+ var Session = object({
608
+ principal: string(),
609
+ clientId: string(),
610
+ clientSecret: optional(string()),
611
+ tokens: object({
612
+ access_token: optional(nullable(string())),
613
+ refresh_token: pipe(string(), minLength(1)),
614
+ expiry_date: optional(nullable(number())),
615
+ scope: optional(string()),
616
+ token_type: optional(nullable(string()))
617
+ })
618
+ });
619
+ var credentialOptions = /* @__PURE__ */ __name((env, storage, keyring) => ({
620
+ configDir: paths(env).config,
621
+ service: "drive-cli",
622
+ // The keyring falls back to the private file by itself (WC-SECR-4); `file` skips the keyring.
623
+ storage: storage === "keyring" ? "auto" : storage,
624
+ env,
625
+ isolated: isMovedRun({ appName: "drive-cli", prefix: "DRIVE", env }),
626
+ ...keyring ? { keyring } : {}
627
+ }), "credentialOptions");
628
+ var credentials = /* @__PURE__ */ __name((env, storage, keyring) => new Credentials(credentialOptions(env, storage, keyring)), "credentials");
629
+ var notSaved = /* @__PURE__ */ __name(() => new CliError("configuration_error", "could not save Google sign-in: the private credentials file cannot be read; move it aside and sign in again", { reason: "oauth.not-saved" }), "notSaved");
630
+ var saveSession = /* @__PURE__ */ __name((env, name, session, storage, keyring) => {
626
631
  try {
627
- const { installed } = JSON.parse(readFileSync(location, "utf8"));
628
- const { client_id: clientId, client_secret: clientSecret } = installed;
629
- if (typeof clientId !== "string" || !clientId)
630
- throw new TypeError("client_id");
631
- if (clientSecret !== void 0 && typeof clientSecret !== "string")
632
- throw new TypeError("client_secret");
633
- return { clientId, ...clientSecret ? { clientSecret } : {} };
632
+ credentials(env, storage, keyring).write(name, JSON.stringify(session));
634
633
  } catch {
635
- throw options.invalid ?? new CliError("configuration_error", "could not read a Desktop app OAuth client JSON from the client file; its contents were not logged", { reason: "sign-in.client-file-invalid" });
634
+ throw notSaved();
636
635
  }
637
- }, "readClientFile");
638
-
639
- // dist/policy-keys.js
640
- var permissionKeys = /* @__PURE__ */ __name((paths2) => {
641
- const keys = /* @__PURE__ */ new Set([
642
- "mcp.authority",
643
- "mcp",
644
- "sheets.create",
645
- "sheets.rename",
646
- "sheets.insert",
647
- "sheets.format",
648
- "sheets.update"
649
- ]);
650
- for (const path of paths2)
651
- keys.add(path.join("."));
652
- for (const operation of operations)
653
- for (const key of methodPolicyKeys(operation.id))
654
- keys.add(key);
655
- return keys;
656
- }, "permissionKeys");
657
- var permissionNames = /* @__PURE__ */ __name((keys) => {
658
- const names = /* @__PURE__ */ new Set();
659
- for (const key of keys) {
660
- const parts = key.split(".");
661
- for (let end = 1; end <= parts.length; end++)
662
- names.add(parts.slice(0, end).join("."));
636
+ }, "saveSession");
637
+ var googleProvider = /* @__PURE__ */ __name((client) => ({
638
+ id: "google",
639
+ name: "Google",
640
+ authorizeUrl: "https://accounts.google.com/o/oauth2/v2/auth",
641
+ tokenUrl: "https://oauth2.googleapis.com/token",
642
+ revokeUrl: "https://oauth2.googleapis.com/revoke",
643
+ client,
644
+ redirect: { kind: "loopback" },
645
+ // Without offline access Google returns no refresh token; without consent it does not return one again.
646
+ authorizeParams: { access_type: "offline", prompt: "select_account consent" }
647
+ }), "googleProvider");
648
+ var sessionKeeper = /* @__PURE__ */ __name((options) => tokenKeeper({
649
+ provider: googleProvider(options.client),
650
+ storage: credentialStorage({
651
+ credentials: { ...credentialOptions(options.env, options.storage), keyring: options.keyring ?? systemKeyring },
652
+ account: options.name,
653
+ codec: driveSessionCodec
654
+ }),
655
+ lockDir: paths(options.env).config,
656
+ fetch: options.fetch ?? globalThis.fetch,
657
+ signInCommand: `drive ${options.name} session start`,
658
+ // Above the client's own 5-minute early refresh, so a token it asks to replace is replaced.
659
+ freshForMs: 6 * 6e4,
660
+ ...options.signal ? { signal: options.signal } : {}
661
+ }), "sessionKeeper");
662
+ var authorizedClient = /* @__PURE__ */ __name((env, name, keyring, signal) => {
663
+ const profile = activeProfile(env, name);
664
+ const unreadable = /* @__PURE__ */ __name(() => new CliError("authentication_error", `could not load Google sign-in \u2014 run drive ${name} session start again`, {
665
+ reason: "oauth.expired"
666
+ }), "unreadable");
667
+ let secret;
668
+ try {
669
+ secret = credentials(env, profile.storage, keyring).read(name)?.secret;
670
+ } catch {
671
+ throw unreadable();
663
672
  }
664
- return names;
665
- }, "permissionNames");
666
- var DEFAULT_LEVELS = {
667
- "mcp.authority": "deny",
668
- ...Object.fromEntries(operations.filter((op) => op.effect === "destructive").map((op) => [`api.${op.id}`, "ask"]))
669
- };
670
- var methodPolicyKeys = /* @__PURE__ */ __name((method, body) => {
671
- const parts = method.split(".");
672
- const verb = parts.at(-1);
673
- const alias = method.startsWith("drive.files.") ? `files.${verb}` : method.startsWith("docs.documents.") ? `documents.${verb === "batchUpdate" ? "update" : verb}` : method.startsWith("sheets.spreadsheets.") ? `sheets.${method === "sheets.spreadsheets.get" ? "info" : method === "sheets.spreadsheets.values.get" ? "show" : verb === "append" ? "add" : verb}` : method === "driveactivity.activity.query" ? "documents.history" : method.startsWith("drive.") ? `${parts[1]}.${verb}` : void 0;
674
- const keys = [`api.${method}`, ...alias ? [alias] : []];
675
- if (method === "drive.replies.create" && body)
676
- keys.push(body.action === "resolve" ? "comments.resolve" : body.action === "reopen" ? "comments.reopen" : "comments.reply");
677
- if (method === "drive.replies.create" && body?.content !== void 0)
678
- keys.push("comments.reply");
679
- if (method === "sheets.spreadsheets.batchUpdate" && Array.isArray(body?.requests)) {
680
- const object2 = /* @__PURE__ */ __name((value) => !!value && typeof value === "object" && !Array.isArray(value), "object");
681
- for (const request of body.requests) {
682
- if (!object2(request))
683
- continue;
684
- if (request.addSheet || request.duplicateSheet)
685
- keys.push("sheets.create");
686
- if (object2(request.updateSheetProperties)) {
687
- const update = request.updateSheetProperties;
688
- if (object2(update.properties) && update.properties.title !== void 0 || String(update.fields).split(",").some((field) => field.trim() === "title" || field.trim() === "*"))
689
- keys.push("sheets.rename");
690
- if (object2(update.properties) && update.properties.gridProperties)
691
- keys.push("sheets.insert");
692
- }
693
- if (request.insertDimension || request.appendDimension || request.insertRange)
694
- keys.push("sheets.insert");
695
- if (request.repeatCell || request.updateCells || request.appendCells || request.updateBorders || request.addConditionalFormatRule || request.updateConditionalFormatRule || request.deleteConditionalFormatRule || request.addBanding || request.updateBanding || request.deleteBanding)
696
- keys.push("sheets.format");
697
- if (request.updateCells || request.appendCells || request.findReplace || request.pasteData || request.copyPaste || request.cutPaste || request.autoFill)
698
- keys.push("sheets.update");
699
- if (request.pasteData || request.copyPaste || request.cutPaste || request.autoFill)
700
- keys.push("sheets.format");
701
- if (object2(request.repeatCell) && (String(request.repeatCell.fields).split(",").some((field) => field.trim() === "*" || field.includes("userEnteredValue")) || object2(request.repeatCell.cell) && request.repeatCell.cell.userEnteredValue !== void 0))
702
- keys.push("sheets.update");
703
- }
673
+ if (!secret)
674
+ throw new CliError("authentication_error", `this profile has no saved Google sign-in \u2014 run drive ${name} session start`, {
675
+ reason: "oauth.missing"
676
+ });
677
+ let parsed;
678
+ try {
679
+ parsed = safeParse(Session, JSON.parse(secret));
680
+ } catch {
681
+ throw unreadable();
704
682
  }
705
- return [...new Set(keys)];
706
- }, "methodPolicyKeys");
707
-
708
- // dist/config.js
709
- import { readFileSync as readFileSync2 } from "node:fs";
710
- import { join as join2 } from "node:path";
711
-
712
- // dist/oauth-application.js
713
- var WIRECAT_APPLICATION = Object.freeze({
714
- clientId: "240274586781-vssrlm9c0l3n1ti12ce7tg95ro4bghal.apps.googleusercontent.com",
715
- // biome-ignore lint/security/noSecrets: public installed-app OAuth identity, non-confidential per Google native-app guidance
716
- clientSecret: "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"
717
- // gitleaks:allow -- public installed-app identity
718
- });
719
-
720
- // dist/config.js
721
- var Common = {
722
- ...AI_ENTRIES,
723
- permissions: optional(record(string(), picklist(LEVELS))),
724
- max_text_chars: optional(pipe(number(), integer(), minValue(1), maxValue(MAX_TEXT_CHARS)))
725
- };
726
- var RunSettings = {
727
- record: optional(boolean()),
728
- keep_runs_for_days: optional(pipe(number(), integer(), minValue(1))),
729
- keep_successful_runs_for_days: optional(pipe(number(), integer(), minValue(1))),
730
- runs_size_limit_mb: optional(pipe(number(), integer(), minValue(1))),
731
- record_input: optional(union([boolean(), literal("failed")]))
732
- };
733
- var SharedDefaults = {
734
- limit: optional(pipe(number(), integer(), minValue(1))),
735
- sends_per_hour: optional(pipe(number(), integer(), minValue(0))),
736
- update_check: optional(boolean()),
737
- skill_hint: optional(boolean())
738
- };
739
- var DEFAULTS_ONLY = /* @__PURE__ */ new Set([...Object.keys(RunSettings), "update_check", "skill_hint"]);
740
- var SETTING_NAMES = /* @__PURE__ */ new Set([...Object.keys(Common), "picture_search", ...DEFAULTS_ONLY]);
741
- var Mirror = strictObject({
742
- id: pipe(string(), regex(/^[a-z0-9-]{1,40}$/)),
743
- path: pipe(string(), minLength(1)),
744
- folder: pipe(string(), regex(/^[A-Za-z0-9_-]{1,200}$/))
745
- });
746
- var Profile = strictObject({
747
- principal: string(),
748
- roots: optional(array(pipe(string(), regex(/^[A-Za-z0-9_-]{1,200}$/))), []),
749
- mirrors: optional(array(Mirror)),
750
- storage: picklist(["keyring", "file"]),
751
- picture_search: optional(boolean()),
752
- ...Common
753
- });
754
- var ConfigSchema = strictObject({
755
- profiles: optional(record(string(), Profile), {}),
756
- defaults: optional(strictObject({ ...Common, ...RunSettings, ...SharedDefaults }))
757
- });
758
- var keyOf = /* @__PURE__ */ __name((path) => {
759
- if (path[0] !== "api" || path[1] === void 0)
760
- return commandPathKey(path);
761
- if (["call", "list", "show"].includes(path[1]))
762
- return null;
763
- const operation = operations.find((one) => one.command === path[1]);
764
- return operation ? `api.${operation.id}` : commandPathKey(path);
765
- }, "keyOf");
766
- var configuration = settingsFor(DRIVE_APP, {
767
- configRepair: false,
768
- // drive's own schema decides what the file may hold, so `doctor` names a profile that lacks its principal.
769
- schema: ConfigSchema,
770
- profile: {
771
- principal: optional(string()),
772
- roots: optional(array(pipe(string(), regex(/^[A-Za-z0-9_-]{1,200}$/)))),
773
- mirrors: optional(array(Mirror)),
774
- storage: optional(picklist(["keyring", "file"])),
775
- max_text_chars: Common.max_text_chars
776
- },
777
- settings: [
778
- {
779
- key: "max_text_chars",
780
- default: MAX_TEXT_CHARS,
781
- description: "the most characters of text one file may have to be imported"
683
+ if (!parsed.success || parsed.output.principal !== profile.principal)
684
+ throw new CliError("authentication_error", "saved sign-in is invalid or belongs to another account", {
685
+ reason: "oauth.expired"
686
+ });
687
+ const session = parsed.output;
688
+ const keeper = sessionKeeper({
689
+ env,
690
+ name,
691
+ storage: profile.storage,
692
+ client: { clientId: session.clientId, ...session.clientSecret ? { clientSecret: session.clientSecret } : {} },
693
+ ...keyring ? { keyring } : {},
694
+ ...signal ? { signal } : {}
695
+ });
696
+ const client = new OAuth2Client({
697
+ clientId: session.clientId,
698
+ clientSecret: session.clientSecret,
699
+ transporterOptions: { timeout: 3e4, ...signal ? { signal } : {} }
700
+ });
701
+ client.refreshHandler = async () => {
702
+ try {
703
+ const tokens = await keeper.tokens();
704
+ if (!tokens.accessToken || tokens.expiresAt === void 0)
705
+ throw new Error("no access token");
706
+ return { access_token: tokens.accessToken, expiry_date: tokens.expiresAt };
707
+ } catch (error) {
708
+ if (isCliError(error) && error.code !== "authentication_error")
709
+ throw error;
710
+ throw new CliError("authentication_error", `Google sign-in expired \u2014 run drive ${name} session start again`, {
711
+ reason: "oauth.expired"
712
+ });
782
713
  }
783
- ],
784
- permissions: commandPermissions({ keyOf, extra: [...permissionKeys([])], defaults: DEFAULT_LEVELS })
785
- });
786
- var paths = /* @__PURE__ */ __name((env) => resolvePaths({ appName: "drive-cli", prefix: "DRIVE", env }), "paths");
787
- var configPath = /* @__PURE__ */ __name((env) => join2(paths(env).config, "config.json"), "configPath");
788
- var TOOL = "drive";
789
- var isNode = /* @__PURE__ */ __name((value) => typeof value === "object" && value !== null && !Array.isArray(value), "isNode");
790
- var withoutIncomplete = /* @__PURE__ */ __name((raw, issues) => {
791
- const incomplete = new Set(issues.flatMap((issue) => issue.kind === "missing_setting" && issue.profile ? [issue.profile] : []));
792
- if (!incomplete.size || !isNode(raw) || !isNode(raw.profiles))
793
- return void 0;
794
- return {
795
- ...raw,
796
- profiles: Object.fromEntries(Object.entries(raw.profiles).filter(([name]) => !incomplete.has(name)))
797
- };
798
- }, "withoutIncomplete");
799
- var examine = /* @__PURE__ */ __name((text2, file, knownPermissions) => {
800
- const check = /* @__PURE__ */ __name((body) => checkConfigText(body, {
801
- file,
802
- tool: TOOL,
803
- schema: ConfigSchema,
804
- repair: false,
805
- ...knownPermissions ? { knownPermissions } : {}
806
- }), "check");
807
- const first = check(text2);
808
- if (first.issues.some((issue) => issue.kind === "invalid_json"))
809
- return { raw: {}, config: { profiles: {} }, issues: first.issues };
810
- const raw = JSON.parse(text2);
811
- if (first.config)
812
- return { raw, config: first.config, issues: first.issues };
813
- const rest = withoutIncomplete(raw, first.issues);
814
- const second = rest && check(JSON.stringify(rest));
815
- return {
816
- raw,
817
- config: second?.config ?? { profiles: {} },
818
- // Saved permissions are checked only in what loads, and the first pass loaded nothing.
819
- issues: [...first.issues, ...(second?.issues ?? []).filter((issue) => issue.kind === "unknown_permission")]
820
714
  };
821
- }, "examine");
822
- var inspectConfig = /* @__PURE__ */ __name((env, knownPermissions) => {
823
- const path = configPath(env);
824
- let text2;
715
+ const { refresh_token: _refresh, ...current } = session.tokens;
716
+ client.setCredentials(current);
717
+ return observeRequests(client);
718
+ }, "authorizedClient");
719
+ var covers = /* @__PURE__ */ __name((granted, required) => granted.includes(required) || required === READ_SCOPE && granted.includes(WRITE_SCOPE), "covers");
720
+ var grantedScopes = /* @__PURE__ */ __name((env, name, keyring) => {
825
721
  try {
826
- text2 = readFileSync2(path, "utf8");
722
+ const secret = credentials(env, activeProfile(env, name).storage, keyring).read(name)?.secret;
723
+ const parsed = secret ? safeParse(Session, JSON.parse(secret)) : void 0;
724
+ if (!parsed?.success)
725
+ return [];
726
+ return parsed.output.tokens.scope?.split(/\s+/).filter(Boolean);
827
727
  } catch {
828
- return { path, found: false, raw: {}, config: { profiles: {} }, issues: [] };
728
+ return [];
829
729
  }
830
- return { path, found: true, ...examine(text2, path, knownPermissions) };
831
- }, "inspectConfig");
832
- var configIssues = /* @__PURE__ */ __name((raw, file, knownPermissions) => examine(JSON.stringify(raw), file, knownPermissions).issues, "configIssues");
833
- var refusal = /* @__PURE__ */ __name((issues) => new CliError("configuration_error", issueMessage(issues)), "refusal");
834
- var readConfig = /* @__PURE__ */ __name((env, knownPermissions) => {
835
- const { config, issues } = inspectConfig(env, knownPermissions);
836
- if (issues.length)
837
- throw refusal(issues);
838
- return config;
839
- }, "readConfig");
840
- var writeConfig = /* @__PURE__ */ __name((env, config) => {
841
- const [issue] = configIssues(config, "drive settings");
842
- if (issue)
843
- throw new CliError("configuration_error", `drive settings: ${issue.profile === void 0 ? "" : `profile ${issue.profile}: `}${issue.what}`);
844
- saveConfigFile(configPath(env), withDefaults(parse(ConfigSchema, config)));
845
- }, "writeConfig");
846
- var withDefaults = /* @__PURE__ */ __name((raw, except = []) => withSettingDefaults(isNode(raw) && !Object.hasOwn(raw, "defaults") ? { ...raw, defaults: {} } : raw, configuration.declaredSettings.filter(({ key }) => !except.includes(key))).config, "withDefaults");
847
- var profileName = usableProfileName;
848
- var fileId = /* @__PURE__ */ __name((input) => {
849
- let id = input;
850
- if (input.startsWith("https://")) {
851
- const url = new URL(input);
852
- if (url.hostname !== "drive.google.com" && url.hostname !== "docs.google.com")
853
- throw new CliError("validation_error", "use a Google Drive/Docs URL or file ID");
854
- id = url.pathname.match(/\/(?:folders|d)\/([^/]+)/)?.[1] ?? "";
730
+ }, "grantedScopes");
731
+ var checkAuthorization = /* @__PURE__ */ __name(async (client, required = READ_SCOPE) => {
732
+ try {
733
+ const { token } = await client.getAccessToken();
734
+ if (!token)
735
+ throw new CliError("authentication_error", "Google returned no access token");
736
+ const info = await client.getTokenInfo(token);
737
+ if (!covers(info.scopes, required))
738
+ throw new CliError("permission_error", "sign-in lacks the required permission; run drive <profile> session start --grant write, activity or apps when needed", { reason: "oauth.scope-missing" });
739
+ } catch (error) {
740
+ throw googleError(error);
855
741
  }
856
- if (!/^[A-Za-z0-9_-]{1,200}$/.test(id))
857
- throw new CliError("validation_error", "invalid Google file ID");
858
- return id;
859
- }, "fileId");
860
- var unknownProfile = /* @__PURE__ */ __name((name, profiles) => new CliError("validation_error", profiles.length ? `no profile ${name} here \u2014 profiles here: ${profiles.join(", ")}; a new one signs in with drive ${name} session start` : `no profiles here yet; create one with drive ${name} session start`, { reason: "profile.unknown", profiles }), "unknownProfile");
861
- var activeProfile = /* @__PURE__ */ __name((env, name) => {
862
- const config = readConfig(env);
863
- const profile = config.profiles[profileName(name)];
864
- if (!profile)
865
- throw unknownProfile(name, Object.keys(config.profiles).sort());
866
- return profile;
867
- }, "activeProfile");
868
- var checkTextLimit = /* @__PURE__ */ __name((value) => {
869
- if (typeof value !== "number" || !Number.isInteger(value) || value < 1)
870
- throw new CliError("validation_error", "max_text_chars must be a positive whole number of characters");
871
- if (value > MAX_TEXT_CHARS)
872
- throw new CliError("validation_error", `max_text_chars can be at most ${MAX_TEXT_CHARS}: the document readers return at most that many characters`);
873
- return value;
874
- }, "checkTextLimit");
875
- var textLimit = /* @__PURE__ */ __name((env, name) => activeProfile(env, name).max_text_chars ?? readConfig(env).defaults?.max_text_chars ?? MAX_TEXT_CHARS, "textLimit");
876
- var pictureSearch = /* @__PURE__ */ __name((env, name) => activeProfile(env, name).picture_search ?? false, "pictureSearch");
877
- var application = /* @__PURE__ */ __name((env, file) => {
878
- if (!file) {
879
- if (!env.DRIVE_GOOGLE_CLIENT_ID) {
880
- if (env.DRIVE_GOOGLE_CLIENT_SECRET)
881
- throw new CliError("configuration_error", "DRIVE_GOOGLE_CLIENT_SECRET requires DRIVE_GOOGLE_CLIENT_ID");
882
- return { ...WIRECAT_APPLICATION };
883
- }
884
- return {
885
- clientId: env.DRIVE_GOOGLE_CLIENT_ID,
886
- ...env.DRIVE_GOOGLE_CLIENT_SECRET ? { clientSecret: env.DRIVE_GOOGLE_CLIENT_SECRET } : {}
887
- };
742
+ }, "checkAuthorization");
743
+ var WORD = /^[a-z][a-z_]{0,23}$/;
744
+ var VERB = /^[a-z][A-Za-z]{0,31}$/;
745
+ var segment = /* @__PURE__ */ __name((part) => {
746
+ if (/^v\d+$/.test(part) || WORD.test(part))
747
+ return part;
748
+ const verb = part.split(":")[1];
749
+ return verb !== void 0 && VERB.test(verb) ? `:id:${verb}` : ":id";
750
+ }, "segment");
751
+ var operationOf = /* @__PURE__ */ __name((method, url) => {
752
+ let path = "";
753
+ try {
754
+ path = new URL(String(url ?? "")).pathname;
755
+ } catch {
888
756
  }
889
- return readClientFile(file, {
890
- invalid: new CliError("configuration_error", "could not read a valid Desktop OAuth client JSON; file contents were not logged", { reason: "sign-in.client-file-invalid" })
757
+ const template = path.split("/").filter(Boolean).map((part) => segment(decodeURIComponent(part))).join("/");
758
+ return `${(method ?? "GET").toUpperCase()} /${template}`;
759
+ }, "operationOf");
760
+ var reasonOf = /* @__PURE__ */ __name((data) => {
761
+ const error = data?.error;
762
+ const reason = error?.errors?.[0]?.reason ?? error?.status;
763
+ return typeof reason === "string" ? reason : void 0;
764
+ }, "reasonOf");
765
+ var observeRequests = /* @__PURE__ */ __name((client) => {
766
+ const transporter = client.transporter;
767
+ const request = transporter.request.bind(transporter);
768
+ transporter.request = (async (options) => {
769
+ const method = (options.method ?? "GET").toUpperCase();
770
+ const operation = operationOf(method, options.url);
771
+ const call = { method, endpointTemplate: operation.slice(method.length + 1), transport: "http" };
772
+ let ended;
773
+ const adapter = /* @__PURE__ */ __name(async (prepared, next) => {
774
+ const attempt = (prepared.retryConfig?.currentRetryAttempt ?? 0) + 1;
775
+ const waitMs = ended === void 0 ? void 0 : Math.round(performance.now() - ended);
776
+ const answered = providerRequest(operation, void 0, {
777
+ ...call,
778
+ attempt,
779
+ ...waitMs === void 0 ? {} : { waitMs }
780
+ });
781
+ try {
782
+ const response = await (options.adapter ? options.adapter(prepared, next) : next(prepared));
783
+ const failed = !(prepared.validateStatus?.(response.status) ?? response.status < 400);
784
+ const providerError = failed ? reasonOf(response.data) : void 0;
785
+ answered({
786
+ status: response.status,
787
+ ...failed ? { errorCode: "provider_error" } : {},
788
+ ...providerError ? { providerError } : {}
789
+ });
790
+ return response;
791
+ } catch (error) {
792
+ answered({ error, errorCode: googleError(error).code });
793
+ throw error;
794
+ } finally {
795
+ ended = performance.now();
796
+ }
797
+ }, "adapter");
798
+ try {
799
+ return await request({ ...options, adapter });
800
+ } catch (error) {
801
+ if (ended === void 0)
802
+ providerRequest(operation, void 0, { ...call, attempt: 1 })({ error, errorCode: googleError(error).code });
803
+ throw error;
804
+ }
891
805
  });
892
- }, "application");
893
- var selectedFolders = /* @__PURE__ */ __name((env, profile, filter = {}) => activeProfile(env, profile).roots.flatMap((id) => filter.id === void 0 || id === filter.id ? [{ id }] : []), "selectedFolders");
894
- var configuredMirrors = /* @__PURE__ */ __name((env, profile, filter = {}) => (activeProfile(env, profile).mirrors ?? []).filter((row) => Object.entries(filter).every(([key, value]) => row[key] === value)), "configuredMirrors");
895
- var configuredSessions = /* @__PURE__ */ __name((env, filter, knownPermissions) => Object.entries(readConfig(env, knownPermissions).profiles).flatMap(([name, row]) => (filter.profile === void 0 || filter.profile === name) && (filter.storage === void 0 || filter.storage === row.storage) ? [{ profile: name, selected_folders: row.roots.length, storage: row.storage }] : []), "configuredSessions");
806
+ return client;
807
+ }, "observeRequests");
896
808
 
897
809
  export {
898
- tokenKeeper,
899
- driveSessionCodec,
900
- credentialStorage,
901
- permissionKeys,
902
- permissionNames,
903
- DEFAULT_LEVELS,
904
- methodPolicyKeys,
905
- DEFAULTS_ONLY,
906
- SETTING_NAMES,
907
- configuration,
908
- paths,
909
- configPath,
910
- inspectConfig,
911
- configIssues,
912
- refusal,
913
- readConfig,
914
- writeConfig,
915
- withDefaults,
916
- profileName,
917
- fileId,
918
- unknownProfile,
919
- activeProfile,
920
- checkTextLimit,
921
- textLimit,
922
- pictureSearch,
923
- application,
924
- selectedFolders,
925
- configuredMirrors,
926
- configuredSessions
810
+ credentials,
811
+ notSaved,
812
+ saveSession,
813
+ googleProvider,
814
+ sessionKeeper,
815
+ authorizedClient,
816
+ covers,
817
+ grantedScopes,
818
+ checkAuthorization,
819
+ operationOf,
820
+ observeRequests
927
821
  };