mdedit-cli 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,13 +1,15 @@
1
1
  #!/usr/bin/env node
2
-
3
- // src/index.ts
4
- import { Command as Command8 } from "commander";
5
- import { readFileSync as readFileSync3 } from "fs";
6
- import { dirname as dirname2, join as join3 } from "path";
7
- import { fileURLToPath as fileURLToPath2 } from "url";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res) => function __init() {
5
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
+ };
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
8
11
 
9
12
  // ../sdk/dist/index.js
10
- var _defaultFetchers = null;
11
13
  function createFetchers(config) {
12
14
  const baseUrlV1 = (config.baseUrlV1 ?? "").replace(/\/$/, "");
13
15
  const baseUrlV2 = (config.baseUrlV2 ?? "").replace(/\/$/, "");
@@ -16,6 +18,7 @@ function createFetchers(config) {
16
18
  const authHeaders = await getAuthHeaders?.() ?? {};
17
19
  return fetch(`${baseUrlV1}${input}`, {
18
20
  ...init,
21
+ signal: init?.signal ?? config.signal,
19
22
  headers: {
20
23
  ...init?.headers,
21
24
  ...authHeaders,
@@ -29,6 +32,7 @@ function createFetchers(config) {
29
32
  const authHeaders = await getAuthHeaders?.() ?? {};
30
33
  return fetch(`${baseUrlV2}${input}`, {
31
34
  ...init,
35
+ signal: init?.signal ?? config.signal,
32
36
  headers: {
33
37
  ...init?.headers,
34
38
  ...authHeaders,
@@ -38,7 +42,7 @@ function createFetchers(config) {
38
42
  }
39
43
  });
40
44
  };
41
- return { customFetch, customFetchV2: customFetchV22 };
45
+ return { customFetch, customFetchV2: customFetchV22, signal: config.signal };
42
46
  }
43
47
  function getDefaultFetchers() {
44
48
  if (_defaultFetchers) return _defaultFetchers;
@@ -46,164 +50,6 @@ function getDefaultFetchers() {
46
50
  "MDEdit API client is not initialized. Call initApiClient(config) at app bootstrap (e.g. pages/_app.jsx) before using API functions."
47
51
  );
48
52
  }
49
- var customFetchV2 = (input, init) => getDefaultFetchers().customFetchV2(input, init);
50
- var FetchError = class extends Error {
51
- name;
52
- type;
53
- status;
54
- data;
55
- constructor(message, type, data) {
56
- super(message);
57
- this.name = "FetchError";
58
- this.type = type;
59
- this.status = typeof type === "number" ? type : 500;
60
- this.data = data;
61
- }
62
- };
63
- var errors_default = FetchError;
64
- var createArticle = async (workspaceId, articleRequest, fetchers) => {
65
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
66
- const response = await fetchV2(`/workspaces/${workspaceId}/articles`, {
67
- method: "POST",
68
- body: JSON.stringify({
69
- articleId: articleRequest.articleId,
70
- title: articleRequest.title,
71
- folderId: articleRequest.folderId,
72
- collaborative: articleRequest.collaborative ?? false,
73
- articleSettings: articleRequest.articleSettings
74
- })
75
- });
76
- if (!response.ok) {
77
- const errorText = await response.text();
78
- let errorData;
79
- try {
80
- errorData = JSON.parse(errorText);
81
- } catch {
82
- throw new errors_default(`Error creating article. ${errorText}`, response.status);
83
- }
84
- if (errorData.error && errorData.error.type === "QUOTA_EXCEEDED") {
85
- const quotaError = new errors_default(`Error creating article. ${errorText}`, response.status);
86
- quotaError.error = errorData.error;
87
- throw quotaError;
88
- }
89
- throw new errors_default(`Error creating article. ${errorText}`, response.status);
90
- }
91
- return response.json();
92
- };
93
- var updateArticle = async (workspaceId, articleRequest, fetchers) => {
94
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
95
- const body = {
96
- title: articleRequest.title,
97
- isPinned: articleRequest.isPinned,
98
- isArchived: articleRequest.isArchived,
99
- articleSettings: articleRequest.articleSettings
100
- };
101
- if (articleRequest.folderId !== void 0) {
102
- body.folderId = articleRequest.folderId;
103
- }
104
- if (articleRequest.preview) {
105
- body.preview = articleRequest.preview;
106
- }
107
- if (articleRequest.wordCount !== void 0) {
108
- body.wordCount = articleRequest.wordCount;
109
- }
110
- if (articleRequest.contentHash !== void 0) {
111
- body.contentHash = articleRequest.contentHash;
112
- }
113
- if (articleRequest.baseArticleRevision !== void 0) {
114
- body.baseArticleRevision = articleRequest.baseArticleRevision;
115
- }
116
- const response = await fetchV2(
117
- `/workspaces/${workspaceId}/articles/${articleRequest.articleId}`,
118
- {
119
- method: "PUT",
120
- body: JSON.stringify(body)
121
- }
122
- );
123
- if (!response.ok) {
124
- const errorText = await response.text();
125
- let errorData;
126
- try {
127
- errorData = JSON.parse(errorText);
128
- } catch {
129
- throw new errors_default(`Error updating article metadata. ${errorText}`, response.status);
130
- }
131
- if (errorData.error && errorData.error.type === "QUOTA_EXCEEDED") {
132
- const quotaError = new errors_default(
133
- `Error updating article metadata. ${errorText}`,
134
- response.status
135
- );
136
- quotaError.error = errorData.error;
137
- throw quotaError;
138
- }
139
- throw new errors_default(`Error updating article metadata. ${errorText}`, response.status, errorData);
140
- }
141
- return response.json();
142
- };
143
- var getArticles = async (workspaceId, fetchers) => {
144
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
145
- const response = await fetchV2(`/workspaces/${workspaceId}/articles`);
146
- if (!response.ok) {
147
- const errorText = await response.text();
148
- const looksLikeWorkspaceAccessDenied = response.status === 403 && errorText.toLowerCase().includes("access denied to workspace");
149
- if (looksLikeWorkspaceAccessDenied) {
150
- throw new errors_default(`Error fetching articles. ${errorText}`, response.status);
151
- }
152
- throw new errors_default(`Error fetching articles. ${errorText}`, response.status);
153
- }
154
- return response.json();
155
- };
156
- var getArticlesByFolder = async (workspaceId, folderId, fetchers) => {
157
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
158
- const qs = `?folderId=${encodeURIComponent(folderId)}`;
159
- const response = await fetchV2(`/workspaces/${workspaceId}/articles${qs}`);
160
- if (!response.ok) {
161
- const errorText = await response.text();
162
- throw new errors_default(`Error fetching articles. ${errorText}`, response.status);
163
- }
164
- return response.json();
165
- };
166
- var getArticle = async (workspaceId, articleId, fetchers) => {
167
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
168
- const response = await fetchV2(
169
- `/workspaces/${workspaceId}/articles/${articleId}`
170
- );
171
- if (!response.ok) {
172
- throw new errors_default(
173
- `Error fetching article. ${await response.text()}`,
174
- response.status
175
- );
176
- }
177
- return response.json();
178
- };
179
- var deleteArticle = async (workspaceId, articleId, fetchers) => {
180
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
181
- const response = await fetchV2(
182
- `/workspaces/${workspaceId}/articles/${articleId}`,
183
- { method: "DELETE" }
184
- );
185
- if (!response.ok) {
186
- throw new errors_default(
187
- `Error deleting article. ${await response.text()}`,
188
- response.status
189
- );
190
- }
191
- return true;
192
- };
193
- var exportArticleZip = async (workspaceId, articleId, fetchers) => {
194
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
195
- const response = await fetchV2(
196
- `/workspaces/${workspaceId}/articles/${articleId}/export/zip`,
197
- { method: "GET" }
198
- );
199
- if (!response.ok) {
200
- throw new errors_default(
201
- `Failed to export article ZIP. ${await response.text()}`,
202
- response.status
203
- );
204
- }
205
- return response.blob();
206
- };
207
53
  async function fetchErrorFromResponse(prefix, response) {
208
54
  const text = await response.text();
209
55
  let data;
@@ -214,407 +60,6 @@ async function fetchErrorFromResponse(prefix, response) {
214
60
  }
215
61
  return new errors_default(`${prefix}. ${text}`, response.status, data);
216
62
  }
217
- var saveArticleContent = async (workspaceId, articleId, content, optionsOrFetchers, fetchers) => {
218
- const maybeFetchers = optionsOrFetchers && "customFetchV2" in optionsOrFetchers ? optionsOrFetchers : fetchers;
219
- const options = optionsOrFetchers && !("customFetchV2" in optionsOrFetchers) ? optionsOrFetchers : void 0;
220
- const fetchV2 = maybeFetchers?.customFetchV2 ?? customFetchV2;
221
- const urlResponse = await fetchV2(
222
- `/workspaces/${workspaceId}/articles/${articleId}/content-upload-url`,
223
- {
224
- method: "POST",
225
- ...options ? {
226
- body: JSON.stringify({
227
- baseContentRevision: options.baseContentRevision,
228
- baseContentHash: options.baseContentHash,
229
- contentHash: options.contentHash,
230
- contentLength: new TextEncoder().encode(content).byteLength
231
- })
232
- } : {}
233
- }
234
- );
235
- if (!urlResponse.ok) {
236
- throw await fetchErrorFromResponse("Error getting upload URL", urlResponse);
237
- }
238
- const { uploadUrl, uploadId } = await urlResponse.json();
239
- if (!uploadUrl) {
240
- throw new errors_default("No upload URL returned", 500);
241
- }
242
- const uploadResponse = await fetch(uploadUrl, {
243
- method: "PUT",
244
- headers: { "Content-Type": "text/markdown" },
245
- body: content
246
- });
247
- if (!uploadResponse.ok) {
248
- throw await fetchErrorFromResponse("Error uploading content to S3", uploadResponse);
249
- }
250
- if (!options) {
251
- return;
252
- }
253
- if (!uploadId) {
254
- throw new errors_default("No uploadId returned for conditional content upload", 500);
255
- }
256
- const commitResponse = await fetchV2(
257
- `/workspaces/${workspaceId}/articles/${articleId}/content-commit`,
258
- {
259
- method: "POST",
260
- body: JSON.stringify({
261
- uploadId,
262
- baseContentRevision: options.baseContentRevision,
263
- baseContentHash: options.baseContentHash,
264
- contentHash: options.contentHash,
265
- title: options.title,
266
- preview: options.preview,
267
- wordCount: options.wordCount,
268
- folderId: options.folderId,
269
- isPinned: options.isPinned,
270
- isArchived: options.isArchived,
271
- articleSettings: options.articleSettings
272
- })
273
- }
274
- );
275
- if (!commitResponse.ok) {
276
- throw await fetchErrorFromResponse("Error committing article content", commitResponse);
277
- }
278
- return commitResponse.json();
279
- };
280
- var getWorkspaces = async (fetchers) => {
281
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
282
- const response = await fetchV2("/workspaces");
283
- if (!response.ok) {
284
- throw new errors_default(
285
- `Error fetching workspaces. ${await response.text()}`,
286
- response.status
287
- );
288
- }
289
- return response.json();
290
- };
291
- var createWorkspace = async (request, fetchers) => {
292
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
293
- const response = await fetchV2("/workspaces", {
294
- method: "POST",
295
- body: JSON.stringify(request)
296
- });
297
- if (!response.ok) {
298
- throw new errors_default(
299
- `Error creating workspace. ${await response.text()}`,
300
- response.status
301
- );
302
- }
303
- return response.json();
304
- };
305
- var updateWorkspace = async (workspaceId, request, fetchers) => {
306
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
307
- const response = await fetchV2(`/workspaces/${workspaceId}`, {
308
- method: "PUT",
309
- body: JSON.stringify(request)
310
- });
311
- if (!response.ok) {
312
- throw new errors_default(
313
- `Error updating workspace. ${await response.text()}`,
314
- response.status
315
- );
316
- }
317
- return response.json();
318
- };
319
- var deleteWorkspace = async (workspaceId, fetchers) => {
320
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
321
- const response = await fetchV2(`/workspaces/${workspaceId}`, {
322
- method: "DELETE"
323
- });
324
- if (!response.ok) {
325
- throw new errors_default(
326
- `Error deleting workspace. ${await response.text()}`,
327
- response.status
328
- );
329
- }
330
- try {
331
- return await response.json();
332
- } catch {
333
- return;
334
- }
335
- };
336
- var getWorkspace = async (workspaceId, fetchers) => {
337
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
338
- const response = await fetchV2(`/workspaces/${workspaceId}`);
339
- if (!response.ok) {
340
- throw new errors_default(
341
- `Error fetching workspace. ${await response.text()}`,
342
- response.status
343
- );
344
- }
345
- return response.json();
346
- };
347
- var normalizeTimestampMs = (value) => {
348
- const n = typeof value === "number" ? value : Number(value);
349
- if (!Number.isFinite(n)) return Date.now();
350
- return n < 1e12 ? n * 1e3 : n;
351
- };
352
- var readFolderErrorMessage = async (response, fallback) => {
353
- const errorText = await response.text();
354
- try {
355
- const body = JSON.parse(errorText);
356
- const message = body?.error?.message ?? body?.message;
357
- if (typeof message === "string" && message.trim()) {
358
- return message;
359
- }
360
- } catch {
361
- }
362
- return errorText.trim() || fallback;
363
- };
364
- var normalizeFolder = (raw) => {
365
- const id = raw?.id ?? raw?.folderId;
366
- const parentId = raw?.parentId ?? raw?.parentFolderId ?? null;
367
- const workspaceId = raw?.workspaceId;
368
- const name = raw?.name ?? "";
369
- if (!id || !workspaceId) {
370
- throw new Error("Invalid folder payload from API: missing id or workspaceId");
371
- }
372
- if (!name || typeof name !== "string" || name.trim().length === 0) {
373
- throw new Error("Invalid folder payload from API: name cannot be empty");
374
- }
375
- if (name.length > 255) {
376
- throw new Error("Invalid folder payload from API: name exceeds 255 characters");
377
- }
378
- return {
379
- id,
380
- name: name.trim(),
381
- parentId: parentId ?? null,
382
- workspaceId,
383
- createdAt: normalizeTimestampMs(raw?.createdAt),
384
- updatedAt: normalizeTimestampMs(raw?.updatedAt),
385
- ...raw?.deletedAt ? { deletedAt: normalizeTimestampMs(raw?.deletedAt) } : {},
386
- deletedBy: raw?.deletedBy,
387
- color: raw?.color,
388
- icon: raw?.icon,
389
- order: raw?.order
390
- };
391
- };
392
- var createFolder = async (workspaceId, folderRequest, fetchers) => {
393
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
394
- const response = await fetchV2(`/workspaces/${workspaceId}/folders`, {
395
- method: "POST",
396
- body: JSON.stringify({
397
- folderId: folderRequest.id,
398
- id: folderRequest.id,
399
- name: folderRequest.name,
400
- parentId: folderRequest.parentId === null ? null : folderRequest.parentId ?? void 0
401
- })
402
- });
403
- if (!response.ok) {
404
- throw new errors_default(
405
- await readFolderErrorMessage(response, "Error creating folder"),
406
- response.status
407
- );
408
- }
409
- return normalizeFolder(await response.json());
410
- };
411
- var updateFolder = async (workspaceId, folderId, folderRequest, fetchers) => {
412
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
413
- const response = await fetchV2(`/workspaces/${workspaceId}/folders/${folderId}`, {
414
- method: "PUT",
415
- body: JSON.stringify({
416
- name: folderRequest.name,
417
- parentId: folderRequest.parentId === null ? null : folderRequest.parentId ?? void 0
418
- })
419
- });
420
- if (!response.ok) {
421
- throw new errors_default(
422
- await readFolderErrorMessage(response, "Error updating folder"),
423
- response.status
424
- );
425
- }
426
- const result = await response.json();
427
- try {
428
- return normalizeFolder(result);
429
- } catch {
430
- return normalizeFolder({
431
- ...folderRequest,
432
- id: folderId,
433
- workspaceId,
434
- parentId: folderRequest.parentId ?? null
435
- });
436
- }
437
- };
438
- var getFolders = async (workspaceId, options, fetchers) => {
439
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
440
- const qs = options?.includeDeleted ? "?includeDeleted=true" : "";
441
- const response = await fetchV2(`/workspaces/${workspaceId}/folders${qs}`);
442
- if (!response.ok) {
443
- const errorText = await response.text();
444
- throw new errors_default(`Error fetching folders. ${errorText}`, response.status);
445
- }
446
- const folders = await response.json();
447
- return Array.isArray(folders) ? folders.map(normalizeFolder) : [];
448
- };
449
- var getFolder = async (workspaceId, folderId, fetchers) => {
450
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
451
- const response = await fetchV2(`/workspaces/${workspaceId}/folders/${folderId}`);
452
- if (!response.ok) {
453
- throw new errors_default(
454
- `Error fetching folder. ${await response.text()}`,
455
- response.status
456
- );
457
- }
458
- return normalizeFolder(await response.json());
459
- };
460
- var deleteFolder = async (workspaceId, folderId, fetchers) => {
461
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
462
- const response = await fetchV2(`/workspaces/${workspaceId}/folders/${folderId}`, {
463
- method: "DELETE"
464
- });
465
- if (!response.ok) {
466
- const errorText = await response.text();
467
- throw new errors_default(`Error deleting folder. ${errorText}`, response.status);
468
- }
469
- return true;
470
- };
471
- var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
472
- var isRetriableStatus = (status) => status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
473
- var withRetries = async (fn, maxAttempts = 3) => {
474
- let lastError;
475
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
476
- try {
477
- const response = await fn();
478
- if (response.ok) return response;
479
- if (attempt < maxAttempts && isRetriableStatus(response.status)) {
480
- const backoffMs = 250 * Math.pow(2, attempt - 1) + Math.floor(Math.random() * 150);
481
- await sleep(backoffMs);
482
- continue;
483
- }
484
- return response;
485
- } catch (e) {
486
- lastError = e;
487
- if (attempt < maxAttempts) {
488
- const backoffMs = 250 * Math.pow(2, attempt - 1) + Math.floor(Math.random() * 150);
489
- await sleep(backoffMs);
490
- continue;
491
- }
492
- throw lastError;
493
- }
494
- }
495
- throw lastError;
496
- };
497
- var listApiKeys = async (fetchers) => {
498
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
499
- const response = await withRetries(() => fetchV2("/api-keys", { method: "GET" }), 3);
500
- if (!response.ok) {
501
- throw new Error(`Failed to list API keys: ${response.status} ${response.statusText}`);
502
- }
503
- return response.json();
504
- };
505
- var createApiKey = async (request, fetchers) => {
506
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
507
- const response = await withRetries(
508
- () => fetchV2("/api-keys", {
509
- method: "POST",
510
- body: JSON.stringify(request)
511
- }),
512
- 3
513
- );
514
- if (!response.ok) {
515
- throw new Error(`Failed to create API key: ${response.status} ${response.statusText}`);
516
- }
517
- return response.json();
518
- };
519
- var revokeApiKey = async (keyId, fetchers) => {
520
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
521
- const response = await withRetries(
522
- () => fetchV2(`/api-keys/${encodeURIComponent(keyId)}`, {
523
- method: "DELETE"
524
- }),
525
- 3
526
- );
527
- if (!response.ok) {
528
- throw new Error(`Failed to revoke API key: ${response.status} ${response.statusText}`);
529
- }
530
- return response.json();
531
- };
532
- var checkpointCollaboration = async (workspaceId, articleId, fetchers) => {
533
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
534
- const response = await fetchV2(
535
- `/workspaces/${workspaceId}/articles/${articleId}/collaboration/checkpoint`,
536
- { method: "POST" }
537
- );
538
- if (!response.ok) {
539
- throw new errors_default(
540
- `Error checkpointing collaboration. ${await response.text()}`,
541
- response.status
542
- );
543
- }
544
- return response.json();
545
- };
546
- var publishArticle = async (workspaceId, articleId, body, fetchers) => {
547
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
548
- const response = await fetchV2(
549
- `/workspaces/${workspaceId}/articles/${articleId}/publish`,
550
- {
551
- method: "POST",
552
- body: JSON.stringify(body)
553
- }
554
- );
555
- if (!response.ok) {
556
- throw new errors_default(
557
- `Error publishing article: ${await response.text()}`,
558
- response.status
559
- );
560
- }
561
- return response.json();
562
- };
563
- var unpublishArticle = async (workspaceId, articleId, fetchers) => {
564
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
565
- const response = await fetchV2(
566
- `/workspaces/${workspaceId}/articles/${articleId}/publish`,
567
- { method: "DELETE" }
568
- );
569
- if (!response.ok) {
570
- throw new errors_default(
571
- `Error unpublishing article: ${await response.text()}`,
572
- response.status
573
- );
574
- }
575
- return response.json();
576
- };
577
- var getPublishStatus = async (workspaceId, articleId, fetchers) => {
578
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
579
- const response = await fetchV2(
580
- `/workspaces/${workspaceId}/articles/${articleId}/publish`,
581
- { method: "GET" }
582
- );
583
- if (!response.ok) {
584
- throw new errors_default(
585
- `Error fetching publish status: ${await response.text()}`,
586
- response.status
587
- );
588
- }
589
- return response.json();
590
- };
591
- var updatePublishedArticle = async (workspaceId, articleId, body, fetchers) => {
592
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
593
- const response = await fetchV2(
594
- `/workspaces/${workspaceId}/articles/${articleId}/publish`,
595
- {
596
- method: "PUT",
597
- body: JSON.stringify(body)
598
- }
599
- );
600
- if (!response.ok) {
601
- throw new errors_default(
602
- `Error updating published article: ${await response.text()}`,
603
- response.status
604
- );
605
- }
606
- return response.json();
607
- };
608
- var FetchError2 = class extends Error {
609
- status;
610
- data;
611
- constructor(message, status, data) {
612
- super(message);
613
- this.name = "FetchError";
614
- this.status = status;
615
- this.data = data;
616
- }
617
- };
618
63
  function coerceToFetchError(err) {
619
64
  const anyErr = err;
620
65
  const status = typeof anyErr?.status === "number" ? anyErr.status : 500;
@@ -677,92 +122,649 @@ function createSdkClient(config) {
677
122
  }
678
123
  };
679
124
  }
680
-
681
- // src/index.ts
682
- import { AgentClientHttpError } from "@mdedit/agent-client";
683
-
684
- // src/commands/article.ts
685
- import { Command } from "commander";
686
- import inquirer from "inquirer";
687
- import { v4 as uuidv4 } from "uuid";
688
- import { readFile, writeFile } from "fs/promises";
689
- import { createHash } from "crypto";
690
- import { basename, extname } from "path";
691
- import {
692
- openArticleSession
693
- } from "@mdedit/agent-client";
694
-
695
- // src/utils/output.ts
696
- import chalk from "chalk";
125
+ var _defaultFetchers, customFetchV2, FetchError, errors_default, createArticle, updateArticle, getArticles, getArticlesByFolder, getArticle, deleteArticle, exportArticleZip, saveArticleContent, getWorkspaces, createWorkspace, updateWorkspace, deleteWorkspace, getWorkspace, normalizeTimestampMs, readFolderErrorMessage, normalizeFolder, createFolder, updateFolder, getFolders, getFolder, deleteFolder, sleep, isRetriableStatus, withRetries, listApiKeys, createApiKey, revokeApiKey, checkpointCollaboration, publishArticle, unpublishArticle, getPublishStatus, updatePublishedArticle, FetchError2;
126
+ var init_dist = __esm({
127
+ "../sdk/dist/index.js"() {
128
+ "use strict";
129
+ _defaultFetchers = null;
130
+ customFetchV2 = (input, init) => getDefaultFetchers().customFetchV2(input, init);
131
+ FetchError = class extends Error {
132
+ name;
133
+ type;
134
+ status;
135
+ data;
136
+ constructor(message, type, data) {
137
+ super(message);
138
+ this.name = "FetchError";
139
+ this.type = type;
140
+ this.status = typeof type === "number" ? type : 500;
141
+ this.data = data;
142
+ }
143
+ };
144
+ errors_default = FetchError;
145
+ createArticle = async (workspaceId, articleRequest, fetchers) => {
146
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
147
+ const response = await fetchV2(`/workspaces/${workspaceId}/articles`, {
148
+ method: "POST",
149
+ body: JSON.stringify({
150
+ articleId: articleRequest.articleId,
151
+ title: articleRequest.title,
152
+ folderId: articleRequest.folderId,
153
+ collaborative: articleRequest.collaborative ?? false,
154
+ articleSettings: articleRequest.articleSettings
155
+ })
156
+ });
157
+ if (!response.ok) {
158
+ const errorText = await response.text();
159
+ let errorData;
160
+ try {
161
+ errorData = JSON.parse(errorText);
162
+ } catch {
163
+ throw new errors_default(`Error creating article. ${errorText}`, response.status);
164
+ }
165
+ if (errorData.error && errorData.error.type === "QUOTA_EXCEEDED") {
166
+ const quotaError = new errors_default(`Error creating article. ${errorText}`, response.status);
167
+ quotaError.error = errorData.error;
168
+ throw quotaError;
169
+ }
170
+ throw new errors_default(`Error creating article. ${errorText}`, response.status);
171
+ }
172
+ return response.json();
173
+ };
174
+ updateArticle = async (workspaceId, articleRequest, fetchers) => {
175
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
176
+ const body = {
177
+ title: articleRequest.title,
178
+ isPinned: articleRequest.isPinned,
179
+ isArchived: articleRequest.isArchived,
180
+ articleSettings: articleRequest.articleSettings
181
+ };
182
+ if (articleRequest.folderId !== void 0) {
183
+ body.folderId = articleRequest.folderId;
184
+ }
185
+ if (articleRequest.preview) {
186
+ body.preview = articleRequest.preview;
187
+ }
188
+ if (articleRequest.wordCount !== void 0) {
189
+ body.wordCount = articleRequest.wordCount;
190
+ }
191
+ if (articleRequest.contentHash !== void 0) {
192
+ body.contentHash = articleRequest.contentHash;
193
+ }
194
+ if (articleRequest.baseArticleRevision !== void 0) {
195
+ body.baseArticleRevision = articleRequest.baseArticleRevision;
196
+ }
197
+ const response = await fetchV2(
198
+ `/workspaces/${workspaceId}/articles/${articleRequest.articleId}`,
199
+ {
200
+ method: "PUT",
201
+ body: JSON.stringify(body)
202
+ }
203
+ );
204
+ if (!response.ok) {
205
+ const errorText = await response.text();
206
+ let errorData;
207
+ try {
208
+ errorData = JSON.parse(errorText);
209
+ } catch {
210
+ throw new errors_default(`Error updating article metadata. ${errorText}`, response.status);
211
+ }
212
+ if (errorData.error && errorData.error.type === "QUOTA_EXCEEDED") {
213
+ const quotaError = new errors_default(
214
+ `Error updating article metadata. ${errorText}`,
215
+ response.status
216
+ );
217
+ quotaError.error = errorData.error;
218
+ throw quotaError;
219
+ }
220
+ throw new errors_default(`Error updating article metadata. ${errorText}`, response.status, errorData);
221
+ }
222
+ return response.json();
223
+ };
224
+ getArticles = async (workspaceId, fetchers) => {
225
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
226
+ const response = await fetchV2(`/workspaces/${workspaceId}/articles`);
227
+ if (!response.ok) {
228
+ const errorText = await response.text();
229
+ const looksLikeWorkspaceAccessDenied = response.status === 403 && errorText.toLowerCase().includes("access denied to workspace");
230
+ if (looksLikeWorkspaceAccessDenied) {
231
+ throw new errors_default(`Error fetching articles. ${errorText}`, response.status);
232
+ }
233
+ throw new errors_default(`Error fetching articles. ${errorText}`, response.status);
234
+ }
235
+ return response.json();
236
+ };
237
+ getArticlesByFolder = async (workspaceId, folderId, fetchers) => {
238
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
239
+ const qs = `?folderId=${encodeURIComponent(folderId)}`;
240
+ const response = await fetchV2(`/workspaces/${workspaceId}/articles${qs}`);
241
+ if (!response.ok) {
242
+ const errorText = await response.text();
243
+ throw new errors_default(`Error fetching articles. ${errorText}`, response.status);
244
+ }
245
+ return response.json();
246
+ };
247
+ getArticle = async (workspaceId, articleId, fetchers) => {
248
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
249
+ const response = await fetchV2(
250
+ `/workspaces/${workspaceId}/articles/${articleId}`
251
+ );
252
+ if (!response.ok) {
253
+ throw new errors_default(
254
+ `Error fetching article. ${await response.text()}`,
255
+ response.status
256
+ );
257
+ }
258
+ return response.json();
259
+ };
260
+ deleteArticle = async (workspaceId, articleId, fetchers) => {
261
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
262
+ const response = await fetchV2(
263
+ `/workspaces/${workspaceId}/articles/${articleId}`,
264
+ { method: "DELETE" }
265
+ );
266
+ if (!response.ok) {
267
+ throw new errors_default(
268
+ `Error deleting article. ${await response.text()}`,
269
+ response.status
270
+ );
271
+ }
272
+ return true;
273
+ };
274
+ exportArticleZip = async (workspaceId, articleId, fetchers) => {
275
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
276
+ const response = await fetchV2(
277
+ `/workspaces/${workspaceId}/articles/${articleId}/export/zip`,
278
+ { method: "GET" }
279
+ );
280
+ if (!response.ok) {
281
+ throw new errors_default(
282
+ `Failed to export article ZIP. ${await response.text()}`,
283
+ response.status
284
+ );
285
+ }
286
+ return response.blob();
287
+ };
288
+ saveArticleContent = async (workspaceId, articleId, content, optionsOrFetchers, fetchers) => {
289
+ const maybeFetchers = optionsOrFetchers && "customFetchV2" in optionsOrFetchers ? optionsOrFetchers : fetchers;
290
+ const options = optionsOrFetchers && !("customFetchV2" in optionsOrFetchers) ? optionsOrFetchers : void 0;
291
+ const fetchV2 = maybeFetchers?.customFetchV2 ?? customFetchV2;
292
+ const urlResponse = await fetchV2(
293
+ `/workspaces/${workspaceId}/articles/${articleId}/content-upload-url`,
294
+ {
295
+ method: "POST",
296
+ ...options ? {
297
+ body: JSON.stringify({
298
+ baseContentRevision: options.baseContentRevision,
299
+ baseContentHash: options.baseContentHash,
300
+ contentHash: options.contentHash,
301
+ contentLength: new TextEncoder().encode(content).byteLength
302
+ })
303
+ } : {}
304
+ }
305
+ );
306
+ if (!urlResponse.ok) {
307
+ throw await fetchErrorFromResponse("Error getting upload URL", urlResponse);
308
+ }
309
+ const { uploadUrl, uploadId } = await urlResponse.json();
310
+ if (!uploadUrl) {
311
+ throw new errors_default("No upload URL returned", 500);
312
+ }
313
+ const uploadResponse = await fetch(uploadUrl, {
314
+ method: "PUT",
315
+ headers: { "Content-Type": "text/markdown" },
316
+ body: content,
317
+ signal: maybeFetchers?.signal
318
+ });
319
+ if (!uploadResponse.ok) {
320
+ throw await fetchErrorFromResponse("Error uploading content to S3", uploadResponse);
321
+ }
322
+ if (!options) {
323
+ return;
324
+ }
325
+ if (!uploadId) {
326
+ throw new errors_default("No uploadId returned for conditional content upload", 500);
327
+ }
328
+ const commitResponse = await fetchV2(
329
+ `/workspaces/${workspaceId}/articles/${articleId}/content-commit`,
330
+ {
331
+ method: "POST",
332
+ body: JSON.stringify({
333
+ uploadId,
334
+ baseContentRevision: options.baseContentRevision,
335
+ baseContentHash: options.baseContentHash,
336
+ contentHash: options.contentHash,
337
+ title: options.title,
338
+ preview: options.preview,
339
+ wordCount: options.wordCount,
340
+ folderId: options.folderId,
341
+ isPinned: options.isPinned,
342
+ isArchived: options.isArchived,
343
+ articleSettings: options.articleSettings
344
+ })
345
+ }
346
+ );
347
+ if (!commitResponse.ok) {
348
+ throw await fetchErrorFromResponse("Error committing article content", commitResponse);
349
+ }
350
+ return commitResponse.json();
351
+ };
352
+ getWorkspaces = async (fetchers) => {
353
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
354
+ const response = await fetchV2("/workspaces");
355
+ if (!response.ok) {
356
+ throw new errors_default(
357
+ `Error fetching workspaces. ${await response.text()}`,
358
+ response.status
359
+ );
360
+ }
361
+ return response.json();
362
+ };
363
+ createWorkspace = async (request, fetchers) => {
364
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
365
+ const response = await fetchV2("/workspaces", {
366
+ method: "POST",
367
+ body: JSON.stringify(request)
368
+ });
369
+ if (!response.ok) {
370
+ throw new errors_default(
371
+ `Error creating workspace. ${await response.text()}`,
372
+ response.status
373
+ );
374
+ }
375
+ return response.json();
376
+ };
377
+ updateWorkspace = async (workspaceId, request, fetchers) => {
378
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
379
+ const response = await fetchV2(`/workspaces/${workspaceId}`, {
380
+ method: "PUT",
381
+ body: JSON.stringify(request)
382
+ });
383
+ if (!response.ok) {
384
+ throw new errors_default(
385
+ `Error updating workspace. ${await response.text()}`,
386
+ response.status
387
+ );
388
+ }
389
+ return response.json();
390
+ };
391
+ deleteWorkspace = async (workspaceId, fetchers) => {
392
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
393
+ const response = await fetchV2(`/workspaces/${workspaceId}`, {
394
+ method: "DELETE"
395
+ });
396
+ if (!response.ok) {
397
+ throw new errors_default(
398
+ `Error deleting workspace. ${await response.text()}`,
399
+ response.status
400
+ );
401
+ }
402
+ try {
403
+ return await response.json();
404
+ } catch {
405
+ return;
406
+ }
407
+ };
408
+ getWorkspace = async (workspaceId, fetchers) => {
409
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
410
+ const response = await fetchV2(`/workspaces/${workspaceId}`);
411
+ if (!response.ok) {
412
+ throw new errors_default(
413
+ `Error fetching workspace. ${await response.text()}`,
414
+ response.status
415
+ );
416
+ }
417
+ return response.json();
418
+ };
419
+ normalizeTimestampMs = (value) => {
420
+ const n = typeof value === "number" ? value : Number(value);
421
+ if (!Number.isFinite(n)) return Date.now();
422
+ return n < 1e12 ? n * 1e3 : n;
423
+ };
424
+ readFolderErrorMessage = async (response, fallback) => {
425
+ const errorText = await response.text();
426
+ try {
427
+ const body = JSON.parse(errorText);
428
+ const message = body?.error?.message ?? body?.message;
429
+ if (typeof message === "string" && message.trim()) {
430
+ return message;
431
+ }
432
+ } catch {
433
+ }
434
+ return errorText.trim() || fallback;
435
+ };
436
+ normalizeFolder = (raw) => {
437
+ const id = raw?.id ?? raw?.folderId;
438
+ const parentId = raw?.parentId ?? raw?.parentFolderId ?? null;
439
+ const workspaceId = raw?.workspaceId;
440
+ const name = raw?.name ?? "";
441
+ if (!id || !workspaceId) {
442
+ throw new Error("Invalid folder payload from API: missing id or workspaceId");
443
+ }
444
+ if (!name || typeof name !== "string" || name.trim().length === 0) {
445
+ throw new Error("Invalid folder payload from API: name cannot be empty");
446
+ }
447
+ if (name.length > 255) {
448
+ throw new Error("Invalid folder payload from API: name exceeds 255 characters");
449
+ }
450
+ return {
451
+ id,
452
+ name: name.trim(),
453
+ parentId: parentId ?? null,
454
+ workspaceId,
455
+ createdAt: normalizeTimestampMs(raw?.createdAt),
456
+ updatedAt: normalizeTimestampMs(raw?.updatedAt),
457
+ ...raw?.deletedAt ? { deletedAt: normalizeTimestampMs(raw?.deletedAt) } : {},
458
+ deletedBy: raw?.deletedBy,
459
+ color: raw?.color,
460
+ icon: raw?.icon,
461
+ order: raw?.order
462
+ };
463
+ };
464
+ createFolder = async (workspaceId, folderRequest, fetchers) => {
465
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
466
+ const response = await fetchV2(`/workspaces/${workspaceId}/folders`, {
467
+ method: "POST",
468
+ body: JSON.stringify({
469
+ folderId: folderRequest.id,
470
+ id: folderRequest.id,
471
+ name: folderRequest.name,
472
+ parentId: folderRequest.parentId === null ? null : folderRequest.parentId ?? void 0
473
+ })
474
+ });
475
+ if (!response.ok) {
476
+ throw new errors_default(
477
+ await readFolderErrorMessage(response, "Error creating folder"),
478
+ response.status
479
+ );
480
+ }
481
+ return normalizeFolder(await response.json());
482
+ };
483
+ updateFolder = async (workspaceId, folderId, folderRequest, fetchers) => {
484
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
485
+ const response = await fetchV2(`/workspaces/${workspaceId}/folders/${folderId}`, {
486
+ method: "PUT",
487
+ body: JSON.stringify({
488
+ name: folderRequest.name,
489
+ parentId: folderRequest.parentId === null ? null : folderRequest.parentId ?? void 0
490
+ })
491
+ });
492
+ if (!response.ok) {
493
+ throw new errors_default(
494
+ await readFolderErrorMessage(response, "Error updating folder"),
495
+ response.status
496
+ );
497
+ }
498
+ const result = await response.json();
499
+ try {
500
+ return normalizeFolder(result);
501
+ } catch {
502
+ return normalizeFolder({
503
+ ...folderRequest,
504
+ id: folderId,
505
+ workspaceId,
506
+ parentId: folderRequest.parentId ?? null
507
+ });
508
+ }
509
+ };
510
+ getFolders = async (workspaceId, options, fetchers) => {
511
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
512
+ const qs = options?.includeDeleted ? "?includeDeleted=true" : "";
513
+ const response = await fetchV2(`/workspaces/${workspaceId}/folders${qs}`);
514
+ if (!response.ok) {
515
+ const errorText = await response.text();
516
+ throw new errors_default(`Error fetching folders. ${errorText}`, response.status);
517
+ }
518
+ const folders = await response.json();
519
+ return Array.isArray(folders) ? folders.map(normalizeFolder) : [];
520
+ };
521
+ getFolder = async (workspaceId, folderId, fetchers) => {
522
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
523
+ const response = await fetchV2(`/workspaces/${workspaceId}/folders/${folderId}`);
524
+ if (!response.ok) {
525
+ throw new errors_default(
526
+ `Error fetching folder. ${await response.text()}`,
527
+ response.status
528
+ );
529
+ }
530
+ return normalizeFolder(await response.json());
531
+ };
532
+ deleteFolder = async (workspaceId, folderId, fetchers) => {
533
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
534
+ const response = await fetchV2(`/workspaces/${workspaceId}/folders/${folderId}`, {
535
+ method: "DELETE"
536
+ });
537
+ if (!response.ok) {
538
+ const errorText = await response.text();
539
+ throw new errors_default(`Error deleting folder. ${errorText}`, response.status);
540
+ }
541
+ return true;
542
+ };
543
+ sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
544
+ isRetriableStatus = (status) => status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
545
+ withRetries = async (fn, maxAttempts = 3) => {
546
+ let lastError;
547
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
548
+ try {
549
+ const response = await fn();
550
+ if (response.ok) return response;
551
+ if (attempt < maxAttempts && isRetriableStatus(response.status)) {
552
+ const backoffMs = 250 * Math.pow(2, attempt - 1) + Math.floor(Math.random() * 150);
553
+ await sleep(backoffMs);
554
+ continue;
555
+ }
556
+ return response;
557
+ } catch (e) {
558
+ lastError = e;
559
+ if (attempt < maxAttempts) {
560
+ const backoffMs = 250 * Math.pow(2, attempt - 1) + Math.floor(Math.random() * 150);
561
+ await sleep(backoffMs);
562
+ continue;
563
+ }
564
+ throw lastError;
565
+ }
566
+ }
567
+ throw lastError;
568
+ };
569
+ listApiKeys = async (fetchers) => {
570
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
571
+ const response = await withRetries(() => fetchV2("/api-keys", { method: "GET" }), 3);
572
+ if (!response.ok) {
573
+ throw new Error(`Failed to list API keys: ${response.status} ${response.statusText}`);
574
+ }
575
+ return response.json();
576
+ };
577
+ createApiKey = async (request, fetchers) => {
578
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
579
+ const response = await withRetries(
580
+ () => fetchV2("/api-keys", {
581
+ method: "POST",
582
+ body: JSON.stringify(request)
583
+ }),
584
+ 3
585
+ );
586
+ if (!response.ok) {
587
+ throw new Error(`Failed to create API key: ${response.status} ${response.statusText}`);
588
+ }
589
+ return response.json();
590
+ };
591
+ revokeApiKey = async (keyId, fetchers) => {
592
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
593
+ const response = await withRetries(
594
+ () => fetchV2(`/api-keys/${encodeURIComponent(keyId)}`, {
595
+ method: "DELETE"
596
+ }),
597
+ 3
598
+ );
599
+ if (!response.ok) {
600
+ throw new Error(`Failed to revoke API key: ${response.status} ${response.statusText}`);
601
+ }
602
+ return response.json();
603
+ };
604
+ checkpointCollaboration = async (workspaceId, articleId, fetchers) => {
605
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
606
+ const response = await fetchV2(
607
+ `/workspaces/${workspaceId}/articles/${articleId}/collaboration/checkpoint`,
608
+ { method: "POST" }
609
+ );
610
+ if (!response.ok) {
611
+ throw new errors_default(
612
+ `Error checkpointing collaboration. ${await response.text()}`,
613
+ response.status
614
+ );
615
+ }
616
+ return response.json();
617
+ };
618
+ publishArticle = async (workspaceId, articleId, body, fetchers) => {
619
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
620
+ const response = await fetchV2(
621
+ `/workspaces/${workspaceId}/articles/${articleId}/publish`,
622
+ {
623
+ method: "POST",
624
+ body: JSON.stringify(body)
625
+ }
626
+ );
627
+ if (!response.ok) {
628
+ throw new errors_default(
629
+ `Error publishing article: ${await response.text()}`,
630
+ response.status
631
+ );
632
+ }
633
+ return response.json();
634
+ };
635
+ unpublishArticle = async (workspaceId, articleId, fetchers) => {
636
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
637
+ const response = await fetchV2(
638
+ `/workspaces/${workspaceId}/articles/${articleId}/publish`,
639
+ { method: "DELETE" }
640
+ );
641
+ if (!response.ok) {
642
+ throw new errors_default(
643
+ `Error unpublishing article: ${await response.text()}`,
644
+ response.status
645
+ );
646
+ }
647
+ return response.json();
648
+ };
649
+ getPublishStatus = async (workspaceId, articleId, fetchers) => {
650
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
651
+ const response = await fetchV2(
652
+ `/workspaces/${workspaceId}/articles/${articleId}/publish`,
653
+ { method: "GET" }
654
+ );
655
+ if (!response.ok) {
656
+ throw new errors_default(
657
+ `Error fetching publish status: ${await response.text()}`,
658
+ response.status
659
+ );
660
+ }
661
+ return response.json();
662
+ };
663
+ updatePublishedArticle = async (workspaceId, articleId, body, fetchers) => {
664
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
665
+ const response = await fetchV2(
666
+ `/workspaces/${workspaceId}/articles/${articleId}/publish`,
667
+ {
668
+ method: "PUT",
669
+ body: JSON.stringify(body)
670
+ }
671
+ );
672
+ if (!response.ok) {
673
+ throw new errors_default(
674
+ `Error updating published article: ${await response.text()}`,
675
+ response.status
676
+ );
677
+ }
678
+ return response.json();
679
+ };
680
+ FetchError2 = class extends Error {
681
+ status;
682
+ data;
683
+ constructor(message, status, data) {
684
+ super(message);
685
+ this.name = "FetchError";
686
+ this.status = status;
687
+ this.data = data;
688
+ }
689
+ };
690
+ }
691
+ });
697
692
 
698
693
  // src/utils/config.ts
699
694
  import { homedir } from "os";
700
695
  import { join } from "path";
701
696
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
702
- var CONFIG_DIR = process.env.MDEDIT_CONFIG_DIR || join(homedir(), ".mdedit-cli");
703
- var CONFIG_FILE = process.env.MDEDIT_CONFIG_FILE || join(CONFIG_DIR, "config.json");
704
- var ConfigManager = class {
705
- config = {};
706
- constructor() {
707
- this.load();
708
- }
709
- load() {
710
- try {
711
- if (existsSync(CONFIG_FILE)) {
712
- const data = readFileSync(CONFIG_FILE, "utf8");
713
- this.config = JSON.parse(data);
697
+ var CONFIG_DIR, CONFIG_FILE, ConfigManager, configManager;
698
+ var init_config = __esm({
699
+ "src/utils/config.ts"() {
700
+ "use strict";
701
+ CONFIG_DIR = process.env.MDEDIT_CONFIG_DIR || join(homedir(), ".mdedit-cli");
702
+ CONFIG_FILE = process.env.MDEDIT_CONFIG_FILE || join(CONFIG_DIR, "config.json");
703
+ ConfigManager = class {
704
+ config = {};
705
+ constructor() {
706
+ this.load();
714
707
  }
715
- } catch {
716
- }
717
- }
718
- save() {
719
- try {
720
- if (!existsSync(CONFIG_DIR)) {
721
- mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
708
+ load() {
709
+ try {
710
+ if (existsSync(CONFIG_FILE)) {
711
+ const data = readFileSync(CONFIG_FILE, "utf8");
712
+ this.config = JSON.parse(data);
713
+ }
714
+ } catch {
715
+ }
722
716
  }
723
- writeFileSync(CONFIG_FILE, JSON.stringify(this.config, null, 2), { mode: 384 });
724
- try {
725
- chmodSync(CONFIG_DIR, 448);
726
- } catch {
717
+ save() {
718
+ try {
719
+ if (!existsSync(CONFIG_DIR)) {
720
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
721
+ }
722
+ writeFileSync(CONFIG_FILE, JSON.stringify(this.config, null, 2), { mode: 384 });
723
+ try {
724
+ chmodSync(CONFIG_DIR, 448);
725
+ } catch {
726
+ }
727
+ try {
728
+ chmodSync(CONFIG_FILE, 384);
729
+ } catch {
730
+ }
731
+ } catch (error) {
732
+ console.error("Failed to save config:", error.message);
733
+ }
727
734
  }
728
- try {
729
- chmodSync(CONFIG_FILE, 384);
730
- } catch {
735
+ get(key) {
736
+ const envMap = {
737
+ apiUrl: "MDEDIT_API_URL",
738
+ apiKey: "MDEDIT_API_KEY",
739
+ userId: "MDEDIT_USER_ID",
740
+ workspaceId: "MDEDIT_WORKSPACE_ID",
741
+ outputFormat: "MDEDIT_OUTPUT_FORMAT",
742
+ oauthProfile: "MDEDIT_PROFILE"
743
+ };
744
+ const envKey = envMap[key];
745
+ if (envKey && process.env[envKey] !== void 0) {
746
+ return process.env[envKey];
747
+ }
748
+ return this.config[key];
749
+ }
750
+ set(key, value) {
751
+ this.config[key] = value;
752
+ this.save();
753
+ }
754
+ getAll() {
755
+ return { ...this.config };
756
+ }
757
+ clear() {
758
+ this.config = {};
759
+ this.save();
731
760
  }
732
- } catch (error) {
733
- console.error("Failed to save config:", error.message);
734
- }
735
- }
736
- get(key) {
737
- const envMap = {
738
- apiUrl: "MDEDIT_API_URL",
739
- apiKey: "MDEDIT_API_KEY",
740
- userId: "MDEDIT_USER_ID",
741
- workspaceId: "MDEDIT_WORKSPACE_ID",
742
- outputFormat: "MDEDIT_OUTPUT_FORMAT"
743
761
  };
744
- const envKey = envMap[key];
745
- if (envKey && process.env[envKey] !== void 0) {
746
- return process.env[envKey];
747
- }
748
- return this.config[key];
762
+ configManager = new ConfigManager();
749
763
  }
750
- set(key, value) {
751
- this.config[key] = value;
752
- this.save();
753
- }
754
- getAll() {
755
- return { ...this.config };
756
- }
757
- clear() {
758
- this.config = {};
759
- this.save();
760
- }
761
- };
762
- var configManager = new ConfigManager();
764
+ });
763
765
 
764
766
  // src/utils/output.ts
765
- var MAX_TABLE_CELL_WIDTH = 80;
767
+ import chalk from "chalk";
766
768
  function normalizeFormat(value) {
767
769
  const raw = String(value || "").trim().toLowerCase();
768
770
  if (raw === "json" || raw === "table" || raw === "plain") return raw;
@@ -773,172 +775,373 @@ function truncateCell(value, max = MAX_TABLE_CELL_WIDTH) {
773
775
  if (text.length <= max) return text;
774
776
  return text.slice(0, Math.max(0, max - 1)).trimEnd() + "\u2026";
775
777
  }
776
- var OutputFormatter = class {
777
- format;
778
- constructor() {
779
- this.format = normalizeFormat(configManager.get("outputFormat") || "table");
780
- }
781
- setFormat(format) {
782
- this.format = normalizeFormat(format);
783
- }
784
- getFormat() {
785
- return this.format;
786
- }
787
- isJson() {
788
- return this.format === "json";
789
- }
790
- log(message) {
791
- if (this.format === "json") {
792
- console.error(message);
793
- return;
794
- }
795
- console.log(message);
796
- }
797
- success(message) {
798
- this.log(`${chalk.green("\u2713")} ${message}`);
799
- }
800
- error(message) {
801
- const text = this.stringify(message);
802
- console.error(`${chalk.red("\u2717")} ${text}`);
803
- }
804
- warning(message) {
805
- const text = this.stringify(message);
806
- console.warn(`${chalk.yellow("\u26A0")} ${text}`);
807
- }
808
- info(message) {
809
- const text = this.stringify(message);
810
- this.log(`${chalk.blue("\u2139")} ${text}`);
811
- }
812
- output(data) {
813
- if (this.format === "json") {
814
- console.log(JSON.stringify(data, null, 2));
815
- return;
816
- }
817
- if (this.format === "table") {
818
- if (Array.isArray(data)) {
819
- this.printTable(data);
820
- return;
778
+ var MAX_TABLE_CELL_WIDTH, OutputFormatter, output;
779
+ var init_output = __esm({
780
+ "src/utils/output.ts"() {
781
+ "use strict";
782
+ init_config();
783
+ MAX_TABLE_CELL_WIDTH = 80;
784
+ OutputFormatter = class {
785
+ format;
786
+ constructor() {
787
+ this.format = normalizeFormat(configManager.get("outputFormat") || "table");
821
788
  }
822
- if (typeof data === "object" && data !== null) {
823
- this.printObject(data);
824
- return;
789
+ setFormat(format) {
790
+ this.format = normalizeFormat(format);
825
791
  }
826
- }
827
- if (this.format === "plain") {
828
- if (typeof data === "object" && data !== null) {
829
- this.printObject(data);
830
- } else {
792
+ getFormat() {
793
+ return this.format;
794
+ }
795
+ isJson() {
796
+ return this.format === "json";
797
+ }
798
+ log(message) {
799
+ if (this.format === "json") {
800
+ console.error(message);
801
+ return;
802
+ }
803
+ console.log(message);
804
+ }
805
+ success(message) {
806
+ this.log(`${chalk.green("\u2713")} ${message}`);
807
+ }
808
+ error(message) {
809
+ const text = this.stringify(message);
810
+ console.error(`${chalk.red("\u2717")} ${text}`);
811
+ }
812
+ warning(message) {
813
+ const text = this.stringify(message);
814
+ console.warn(`${chalk.yellow("\u26A0")} ${text}`);
815
+ }
816
+ info(message) {
817
+ const text = this.stringify(message);
818
+ this.log(`${chalk.blue("\u2139")} ${text}`);
819
+ }
820
+ output(data) {
821
+ if (this.format === "json") {
822
+ console.log(JSON.stringify(data, null, 2));
823
+ return;
824
+ }
825
+ if (this.format === "table") {
826
+ if (Array.isArray(data)) {
827
+ this.printTable(data);
828
+ return;
829
+ }
830
+ if (typeof data === "object" && data !== null) {
831
+ this.printObject(data);
832
+ return;
833
+ }
834
+ }
835
+ if (this.format === "plain") {
836
+ if (typeof data === "object" && data !== null) {
837
+ this.printObject(data);
838
+ } else {
839
+ console.log(data);
840
+ }
841
+ return;
842
+ }
831
843
  console.log(data);
832
844
  }
833
- return;
834
- }
835
- console.log(data);
836
- }
837
- header(text) {
838
- this.log(`
845
+ header(text) {
846
+ this.log(`
839
847
  ${chalk.bold.underline(text)}
840
848
  `);
841
- }
842
- printTable(rowsRaw) {
843
- if (rowsRaw.length === 0) {
844
- console.log("(no results)");
845
- return;
846
- }
847
- const rows = rowsRaw.map((row) => {
848
- if (row && typeof row === "object" && !Array.isArray(row)) return row;
849
- return { value: row };
850
- });
851
- const columns = [];
852
- const seen = /* @__PURE__ */ new Set();
853
- const addColumn = (col) => {
854
- if (seen.has(col)) return;
855
- seen.add(col);
856
- columns.push(col);
857
- };
858
- addColumn("(index)");
859
- for (const key of Object.keys(rows[0] || {})) addColumn(key);
860
- for (const row of rows) {
861
- for (const key of Object.keys(row)) addColumn(key);
862
- }
863
- const cell = (value) => {
864
- if (value === null || value === void 0) return "";
865
- if (typeof value === "string") return truncateCell(value);
866
- if (typeof value === "number" || typeof value === "boolean") return String(value);
867
- try {
868
- return truncateCell(JSON.stringify(value));
869
- } catch {
870
- return truncateCell(String(value));
849
+ }
850
+ printTable(rowsRaw) {
851
+ if (rowsRaw.length === 0) {
852
+ console.log("(no results)");
853
+ return;
854
+ }
855
+ const rows = rowsRaw.map((row) => {
856
+ if (row && typeof row === "object" && !Array.isArray(row)) return row;
857
+ return { value: row };
858
+ });
859
+ const columns = [];
860
+ const seen = /* @__PURE__ */ new Set();
861
+ const addColumn = (col) => {
862
+ if (seen.has(col)) return;
863
+ seen.add(col);
864
+ columns.push(col);
865
+ };
866
+ addColumn("(index)");
867
+ for (const key of Object.keys(rows[0] || {})) addColumn(key);
868
+ for (const row of rows) {
869
+ for (const key of Object.keys(row)) addColumn(key);
870
+ }
871
+ const cell = (value) => {
872
+ if (value === null || value === void 0) return "";
873
+ if (typeof value === "string") return truncateCell(value);
874
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
875
+ try {
876
+ return truncateCell(JSON.stringify(value));
877
+ } catch {
878
+ return truncateCell(String(value));
879
+ }
880
+ };
881
+ const grid = rows.map((row, idx) => {
882
+ const record = { ...row };
883
+ return columns.map((col) => {
884
+ if (col === "(index)") return String(idx);
885
+ return cell(record[col]);
886
+ });
887
+ });
888
+ const widths = columns.map((col, i) => {
889
+ const headerWidth = col.length;
890
+ const cellsWidth = Math.max(...grid.map((r) => (r[i] ?? "").length), 0);
891
+ return Math.min(MAX_TABLE_CELL_WIDTH, Math.max(headerWidth, cellsWidth));
892
+ });
893
+ const pad = (text, width) => text.length >= width ? text.slice(0, width) : text + " ".repeat(width - text.length);
894
+ const line = (left, mid, right) => left + widths.map((w) => "\u2500".repeat(w + 2)).join(mid) + right;
895
+ const rowLine = (values) => "\u2502" + values.map((v, i) => ` ${pad(v, widths[i])} `).join("\u2502") + "\u2502";
896
+ console.log(line("\u250C", "\u252C", "\u2510"));
897
+ console.log(rowLine(columns.map((c, i) => pad(c, widths[i]))));
898
+ console.log(line("\u251C", "\u253C", "\u2524"));
899
+ for (const r of grid) console.log(rowLine(r.map((v, i) => pad(v, widths[i]))));
900
+ console.log(line("\u2514", "\u2534", "\u2518"));
901
+ }
902
+ printObject(obj, indent = 0) {
903
+ if (Array.isArray(obj)) {
904
+ obj.forEach((item, index) => {
905
+ console.log(" ".repeat(indent) + chalk.cyan(`[${index}]`));
906
+ this.printObject(item, indent + 1);
907
+ });
908
+ return;
909
+ }
910
+ if (typeof obj === "object" && obj !== null) {
911
+ Object.entries(obj).forEach(([key, value]) => {
912
+ if (typeof value === "object" && value !== null) {
913
+ console.log(" ".repeat(indent) + chalk.cyan(key) + ":");
914
+ this.printObject(value, indent + 1);
915
+ } else {
916
+ console.log(" ".repeat(indent) + chalk.cyan(key) + ":", value);
917
+ }
918
+ });
919
+ return;
920
+ }
921
+ console.log(" ".repeat(indent) + String(obj));
922
+ }
923
+ stringify(value) {
924
+ if (typeof value === "string") return value;
925
+ if (value instanceof Error) return value.message || String(value);
926
+ try {
927
+ return JSON.stringify(value);
928
+ } catch {
929
+ return String(value);
930
+ }
871
931
  }
872
932
  };
873
- const grid = rows.map((row, idx) => {
874
- const record = { ...row };
875
- return columns.map((col) => {
876
- if (col === "(index)") return String(idx);
877
- return cell(record[col]);
878
- });
879
- });
880
- const widths = columns.map((col, i) => {
881
- const headerWidth = col.length;
882
- const cellsWidth = Math.max(...grid.map((r) => (r[i] ?? "").length), 0);
883
- return Math.min(MAX_TABLE_CELL_WIDTH, Math.max(headerWidth, cellsWidth));
884
- });
885
- const pad = (text, width) => text.length >= width ? text.slice(0, width) : text + " ".repeat(width - text.length);
886
- const line = (left, mid, right) => left + widths.map((w) => "\u2500".repeat(w + 2)).join(mid) + right;
887
- const rowLine = (values) => "\u2502" + values.map((v, i) => ` ${pad(v, widths[i])} `).join("\u2502") + "\u2502";
888
- console.log(line("\u250C", "\u252C", "\u2510"));
889
- console.log(rowLine(columns.map((c, i) => pad(c, widths[i]))));
890
- console.log(line("\u251C", "\u253C", "\u2524"));
891
- for (const r of grid) console.log(rowLine(r.map((v, i) => pad(v, widths[i]))));
892
- console.log(line("\u2514", "\u2534", "\u2518"));
933
+ output = new OutputFormatter();
893
934
  }
894
- printObject(obj, indent = 0) {
895
- if (Array.isArray(obj)) {
896
- obj.forEach((item, index) => {
897
- console.log(" ".repeat(indent) + chalk.cyan(`[${index}]`));
898
- this.printObject(item, indent + 1);
899
- });
900
- return;
901
- }
902
- if (typeof obj === "object" && obj !== null) {
903
- Object.entries(obj).forEach(([key, value]) => {
904
- if (typeof value === "object" && value !== null) {
905
- console.log(" ".repeat(indent) + chalk.cyan(key) + ":");
906
- this.printObject(value, indent + 1);
907
- } else {
908
- console.log(" ".repeat(indent) + chalk.cyan(key) + ":", value);
909
- }
910
- });
911
- return;
912
- }
913
- console.log(" ".repeat(indent) + String(obj));
935
+ });
936
+
937
+ // src/utils/oauth.ts
938
+ var oauth_exports = {};
939
+ __export(oauth_exports, {
940
+ loginWithOAuth: () => loginWithOAuth,
941
+ logoutOAuth: () => logoutOAuth,
942
+ oauthStatus: () => oauthStatus,
943
+ qualifyOAuthScopes: () => qualifyOAuthScopes,
944
+ storedOAuthAccessToken: () => storedOAuthAccessToken
945
+ });
946
+ import { randomBytes } from "crypto";
947
+ import { spawn } from "child_process";
948
+ import {
949
+ NodeOAuthClient,
950
+ OsCredentialStore,
951
+ createPkcePair,
952
+ startLoopbackCallback
953
+ } from "@mdedit/node-auth";
954
+ function activeProfile(profile) {
955
+ return profile?.trim() || configManager.get("oauthProfile") || DEFAULT_PROFILE;
956
+ }
957
+ function profileIndex() {
958
+ return configManager.get("oauthProfiles") || [];
959
+ }
960
+ function setProfileIndex(profiles) {
961
+ configManager.set("oauthProfiles", [...new Set(profiles)].sort());
962
+ }
963
+ async function discoverOAuthConfiguration() {
964
+ const clientId = process.env.MDEDIT_OAUTH_CLIENT_ID;
965
+ const authorizationEndpoint = process.env.MDEDIT_OAUTH_AUTHORIZATION_ENDPOINT;
966
+ const tokenEndpoint = process.env.MDEDIT_OAUTH_TOKEN_ENDPOINT;
967
+ const revocationEndpoint = process.env.MDEDIT_OAUTH_REVOCATION_ENDPOINT;
968
+ if (clientId && authorizationEndpoint && tokenEndpoint && revocationEndpoint) {
969
+ return {
970
+ authorizationEndpoint,
971
+ clientId,
972
+ defaultScopes: (process.env.MDEDIT_OAUTH_SCOPES || "").split(",").map((scope) => scope.trim()).filter(Boolean),
973
+ resource: process.env.MDEDIT_OAUTH_RESOURCE || "https://apiv2.mdedit.ai/api",
974
+ revocationEndpoint,
975
+ tokenEndpoint
976
+ };
914
977
  }
915
- stringify(value) {
916
- if (typeof value === "string") return value;
917
- if (value instanceof Error) return value.message || String(value);
918
- try {
919
- return JSON.stringify(value);
920
- } catch {
921
- return String(value);
922
- }
978
+ const response = await fetch(`${getApiBaseUrlRoot()}/.well-known/mdedit-cli-oauth`);
979
+ if (!response.ok) {
980
+ throw new Error(`OAuth discovery failed (${response.status})`);
923
981
  }
924
- };
925
- var output = new OutputFormatter();
926
-
927
- // src/utils/context.ts
928
- function resolveWorkspaceId(cliWorkspaceId) {
929
- return cliWorkspaceId || configManager.get("workspaceId") || process.env.MDEDIT_WORKSPACE_ID;
982
+ const document = await response.json();
983
+ if (!document.clientId || !document.authorizationEndpoint || !document.tokenEndpoint || !document.revocationEndpoint || !document.resource || !Array.isArray(document.defaultScopes)) {
984
+ throw new Error("OAuth discovery response is incomplete");
985
+ }
986
+ return document;
930
987
  }
931
- function requireWorkspaceId(cliWorkspaceId) {
932
- const workspaceId = resolveWorkspaceId(cliWorkspaceId);
933
- if (!workspaceId) {
934
- throw new Error(
935
- "workspaceId is required. Pass --workspace <id> or set a default with: mdedit config set workspaceId <id>"
936
- );
988
+ function credentialStore() {
989
+ return new OsCredentialStore({
990
+ loadProfileIndex: async () => profileIndex(),
991
+ saveProfileIndex: async (profiles) => setProfileIndex(profiles)
992
+ });
993
+ }
994
+ function qualifyOAuthScopes(scopes, resource) {
995
+ const prefix = `${resource.replace(/\/+$/, "")}/`;
996
+ return [...new Set(scopes.map((scope) => {
997
+ const normalized = scope.trim();
998
+ if (!normalized) return "";
999
+ if (normalized.startsWith(prefix)) return normalized;
1000
+ if (normalized.includes("://") || normalized.includes("/")) {
1001
+ throw new Error(`OAuth scope is for a different resource: ${normalized}`);
1002
+ }
1003
+ return `${prefix}${normalized}`;
1004
+ }).filter(Boolean))];
1005
+ }
1006
+ async function oauthClient(scopes) {
1007
+ const discovery = await discoverOAuthConfiguration();
1008
+ const selectedScopes = scopes?.length ? scopes : discovery.defaultScopes;
1009
+ const configuration = {
1010
+ authorizationEndpoint: discovery.authorizationEndpoint,
1011
+ clientId: discovery.clientId,
1012
+ redirectUri: FIXED_REDIRECT_URI,
1013
+ resource: discovery.resource,
1014
+ revocationEndpoint: discovery.revocationEndpoint,
1015
+ scopes: qualifyOAuthScopes(selectedScopes, discovery.resource),
1016
+ tokenEndpoint: discovery.tokenEndpoint
1017
+ };
1018
+ const cacheKey = JSON.stringify(configuration);
1019
+ const existing = oauthClientsByConfiguration.get(cacheKey);
1020
+ if (existing) return existing;
1021
+ const client = new NodeOAuthClient({
1022
+ configuration,
1023
+ credentialStore: credentialStore()
1024
+ });
1025
+ oauthClientsByConfiguration.set(cacheKey, client);
1026
+ return client;
1027
+ }
1028
+ function launchBrowser(url) {
1029
+ const command = process.platform === "darwin" ? { executable: "open", args: [url] } : process.platform === "win32" ? { executable: "rundll32.exe", args: ["url.dll,FileProtocolHandler", url] } : { executable: "xdg-open", args: [url] };
1030
+ const child = spawn(command.executable, command.args, {
1031
+ detached: true,
1032
+ stdio: "ignore"
1033
+ });
1034
+ child.unref();
1035
+ }
1036
+ async function loginWithOAuth({
1037
+ noBrowser = false,
1038
+ profile,
1039
+ scopes
1040
+ }) {
1041
+ const normalizedProfile = activeProfile(profile);
1042
+ const client = await oauthClient(scopes);
1043
+ const pkce = createPkcePair();
1044
+ const state = randomBytes(32).toString("base64url");
1045
+ const callback = await startLoopbackCallback({
1046
+ redirectUri: FIXED_REDIRECT_URI,
1047
+ state
1048
+ });
1049
+ const authorization = client.createAuthorizationRequest({
1050
+ challenge: pkce.challenge,
1051
+ state
1052
+ });
1053
+ output.info(
1054
+ noBrowser ? `Open this URL in a browser on this machine: ${authorization.url}` : "Opening a browser for mdedit sign-in\u2026"
1055
+ );
1056
+ if (!noBrowser) launchBrowser(authorization.url);
1057
+ try {
1058
+ const code = await callback.result;
1059
+ const tokenSet = await client.exchangeAuthorizationCode({
1060
+ code,
1061
+ profile: normalizedProfile,
1062
+ verifier: pkce.verifier
1063
+ });
1064
+ configManager.set("oauthProfile", normalizedProfile);
1065
+ return {
1066
+ expiresAt: tokenSet.expiresAt,
1067
+ profile: normalizedProfile,
1068
+ scope: [...tokenSet.scope]
1069
+ };
1070
+ } finally {
1071
+ await callback.close();
937
1072
  }
938
- return workspaceId;
939
1073
  }
1074
+ async function oauthStatus(profile) {
1075
+ const normalizedProfile = activeProfile(profile);
1076
+ return (await oauthClient()).status(normalizedProfile);
1077
+ }
1078
+ async function logoutOAuth({
1079
+ all,
1080
+ profile
1081
+ }) {
1082
+ const client = await oauthClient();
1083
+ if (all) {
1084
+ await client.logoutAll();
1085
+ configManager.set("oauthProfile", void 0);
1086
+ return { all: true };
1087
+ }
1088
+ const normalizedProfile = activeProfile(profile);
1089
+ await client.logout(normalizedProfile);
1090
+ if (configManager.get("oauthProfile") === normalizedProfile) {
1091
+ configManager.set("oauthProfile", void 0);
1092
+ }
1093
+ return { all: false, profile: normalizedProfile };
1094
+ }
1095
+ async function storedOAuthAccessToken(profile, forceRefresh = false) {
1096
+ const normalizedProfile = activeProfile(profile);
1097
+ if (!profileIndex().includes(normalizedProfile)) return null;
1098
+ return (await oauthClient()).getAccessToken(normalizedProfile, { forceRefresh });
1099
+ }
1100
+ var DEFAULT_PROFILE, FIXED_REDIRECT_URI, oauthClientsByConfiguration;
1101
+ var init_oauth = __esm({
1102
+ "src/utils/oauth.ts"() {
1103
+ "use strict";
1104
+ init_config();
1105
+ init_api();
1106
+ init_output();
1107
+ DEFAULT_PROFILE = "default";
1108
+ FIXED_REDIRECT_URI = "http://localhost:17643/oauth/callback";
1109
+ oauthClientsByConfiguration = /* @__PURE__ */ new Map();
1110
+ }
1111
+ });
940
1112
 
941
1113
  // src/utils/api.ts
1114
+ function selectAuthentication({
1115
+ explicitApiKey,
1116
+ oauthAccessToken,
1117
+ storedApiKey
1118
+ }) {
1119
+ const normalizedExplicitKey = explicitApiKey?.trim();
1120
+ if (normalizedExplicitKey) {
1121
+ return {
1122
+ headers: { "x-api-key": normalizedExplicitKey },
1123
+ method: "apiKey",
1124
+ websocketToken: normalizedExplicitKey
1125
+ };
1126
+ }
1127
+ const normalizedOAuthToken = oauthAccessToken?.trim();
1128
+ if (normalizedOAuthToken) {
1129
+ return {
1130
+ headers: { Authorization: `Bearer ${normalizedOAuthToken}` },
1131
+ method: "oauth",
1132
+ websocketToken: normalizedOAuthToken
1133
+ };
1134
+ }
1135
+ const normalizedStoredKey = storedApiKey?.trim();
1136
+ if (normalizedStoredKey) {
1137
+ return {
1138
+ headers: { "x-api-key": normalizedStoredKey },
1139
+ method: "apiKey",
1140
+ websocketToken: normalizedStoredKey
1141
+ };
1142
+ }
1143
+ return null;
1144
+ }
942
1145
  function trimTrailingSlashes(value) {
943
1146
  return value.replace(/\/+$/, "");
944
1147
  }
@@ -957,35 +1160,99 @@ function getApiBaseUrlV2() {
957
1160
  if (raw.endsWith("/api") || raw.endsWith("/api/v2")) return raw;
958
1161
  return `${raw}/api`;
959
1162
  }
960
- function requireApiKey() {
961
- const apiKey = configManager.get("apiKey") || process.env.MDEDIT_API_KEY;
962
- if (!apiKey) {
1163
+ function requireAuthentication() {
1164
+ const activeProfile2 = configManager.get("oauthProfile") || "default";
1165
+ const oauthConfigured = (configManager.get("oauthProfiles") || []).includes(activeProfile2);
1166
+ const apiKey = process.env.MDEDIT_API_KEY || configManager.getAll().apiKey;
1167
+ if (!apiKey && !oauthConfigured) {
963
1168
  throw new Error(
964
- "No authentication configured. Set an API key with: mdedit config set apiKey <key> (or pass --api-key / set MDEDIT_API_KEY). Get an API key: https://docs.mdedit.ai/api-keys"
1169
+ "Login required. Run `mdedit auth login`; for headless/CI use --api-key, MDEDIT_API_KEY, or a stored API key."
965
1170
  );
966
1171
  }
967
- return String(apiKey);
968
1172
  }
969
- var _cachedKey = null;
970
- var _cachedClient = null;
1173
+ async function resolveAuthentication(forceOAuthRefresh = false) {
1174
+ const explicitApiKey = process.env.MDEDIT_API_KEY;
1175
+ const { storedOAuthAccessToken: storedOAuthAccessToken2 } = await Promise.resolve().then(() => (init_oauth(), oauth_exports));
1176
+ const authentication = selectAuthentication({
1177
+ explicitApiKey,
1178
+ oauthAccessToken: explicitApiKey ? null : await storedOAuthAccessToken2(void 0, forceOAuthRefresh),
1179
+ storedApiKey: configManager.getAll().apiKey
1180
+ });
1181
+ if (authentication) return authentication;
1182
+ throw new Error(
1183
+ "Login required. Run `mdedit auth login`; for headless/CI use --api-key or MDEDIT_API_KEY."
1184
+ );
1185
+ }
1186
+ function getAgentCredentialProvider() {
1187
+ return {
1188
+ getCredential: () => resolveAuthentication(),
1189
+ refreshCredential: () => resolveAuthentication(true)
1190
+ };
1191
+ }
971
1192
  function getApiClient() {
972
1193
  const baseUrlV2 = getApiBaseUrlV2();
973
- const apiKey = configManager.get("apiKey") || process.env.MDEDIT_API_KEY || "";
974
- const cacheKey = `${baseUrlV2}::${apiKey}`;
1194
+ const cacheKey = baseUrlV2;
975
1195
  if (_cachedClient && _cachedKey === cacheKey) return _cachedClient;
976
1196
  const client = createSdkClient({
977
1197
  baseUrlV2,
978
1198
  getAuthHeaders: async () => {
979
- const key = configManager.get("apiKey") || process.env.MDEDIT_API_KEY;
980
- const headers = {};
981
- if (key) headers["x-api-key"] = String(key);
982
- return headers;
1199
+ return (await resolveAuthentication()).headers;
983
1200
  }
984
1201
  });
985
1202
  _cachedKey = cacheKey;
986
1203
  _cachedClient = client;
987
1204
  return client;
988
1205
  }
1206
+ var requireApiKey, _cachedKey, _cachedClient;
1207
+ var init_api = __esm({
1208
+ "src/utils/api.ts"() {
1209
+ "use strict";
1210
+ init_dist();
1211
+ init_config();
1212
+ requireApiKey = requireAuthentication;
1213
+ _cachedKey = null;
1214
+ _cachedClient = null;
1215
+ }
1216
+ });
1217
+
1218
+ // src/index.ts
1219
+ init_dist();
1220
+ import { Command as Command9 } from "commander";
1221
+ import { readFileSync as readFileSync3 } from "fs";
1222
+ import { dirname as dirname2, join as join3 } from "path";
1223
+ import { fileURLToPath as fileURLToPath2 } from "url";
1224
+ import { AgentClientHttpError } from "@mdedit/agent-client";
1225
+
1226
+ // src/commands/article.ts
1227
+ init_dist();
1228
+ init_output();
1229
+ import { Command } from "commander";
1230
+ import inquirer from "inquirer";
1231
+ import { v4 as uuidv4 } from "uuid";
1232
+ import { readFile, writeFile } from "fs/promises";
1233
+ import { createHash } from "crypto";
1234
+ import { basename, extname } from "path";
1235
+ import {
1236
+ openArticleSession
1237
+ } from "@mdedit/agent-client";
1238
+
1239
+ // src/utils/context.ts
1240
+ init_config();
1241
+ function resolveWorkspaceId(cliWorkspaceId) {
1242
+ return cliWorkspaceId || configManager.get("workspaceId") || process.env.MDEDIT_WORKSPACE_ID;
1243
+ }
1244
+ function requireWorkspaceId(cliWorkspaceId) {
1245
+ const workspaceId = resolveWorkspaceId(cliWorkspaceId);
1246
+ if (!workspaceId) {
1247
+ throw new Error(
1248
+ "workspaceId is required. Pass --workspace <id> or set a default with: mdedit config set workspaceId <id>"
1249
+ );
1250
+ }
1251
+ return workspaceId;
1252
+ }
1253
+
1254
+ // src/commands/article.ts
1255
+ init_api();
989
1256
 
990
1257
  // src/utils/exitCodes.ts
991
1258
  import {
@@ -1257,7 +1524,8 @@ function createArticleCommands() {
1257
1524
  output.info("Hint: use `mdedit article get <articleId> --content-only` to print markdown, or `--include-content` to include it in the output.");
1258
1525
  });
1259
1526
  article.command("create").description("Create a new article").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-i, --id <articleId>", "Article ID (defaults to a UUID)").option("-t, --title <title>", "Article title").option("-f, --folder <folderId>", "Folder ID").option("-c, --collaborative", "Enable collaborative editing").option("--file <path>", "Read initial article content from a file (use - for stdin)").option("--content <text>", "Set initial article content as an inline string").option("--publish", "Publish the created article to a public mded.it link").option("--slug <slug>", "Custom public-link slug (requires --publish)").option("--seo-title <title>", "SEO/social title for the public page (requires --publish)").option("--seo-description <description>", "SEO/social description for the public page (requires --publish)").option("-y, --yes", "Skip public-publishing confirmation").action(async (options) => {
1260
- const apiKey = requireApiKey();
1527
+ requireAuthentication();
1528
+ const credentialProvider = getAgentCredentialProvider();
1261
1529
  const client = getApiClient();
1262
1530
  const workspaceId = requireWorkspaceId(options.workspace);
1263
1531
  if (options.content !== void 0 && options.file !== void 0) {
@@ -1299,8 +1567,7 @@ function createArticleCommands() {
1299
1567
  try {
1300
1568
  if (options.collaborative) {
1301
1569
  const session = await openArticleSession({
1302
- apiKey,
1303
- websocketToken: apiKey,
1570
+ credentialProvider,
1304
1571
  workspaceId,
1305
1572
  articleId,
1306
1573
  agent: { name: "mdedit-cli" },
@@ -1464,7 +1731,8 @@ function createArticleCommands() {
1464
1731
  output.output(result);
1465
1732
  });
1466
1733
  article.command("watch <articleId>").description("Stream article and review changes as newline-delimited JSON").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("--agent <name>", "Agent presence name", "mdedit-cli").option("--poll-interval <milliseconds>", "REST fallback polling interval", "2000").action(async (articleId, options) => {
1467
- const apiKey = requireApiKey();
1734
+ requireAuthentication();
1735
+ const credentialProvider = getAgentCredentialProvider();
1468
1736
  const workspaceId = requireWorkspaceId(options.workspace);
1469
1737
  const pollIntervalMs = Number(options.pollInterval);
1470
1738
  if (!Number.isFinite(pollIntervalMs) || pollIntervalMs < 100) {
@@ -1479,8 +1747,7 @@ function createArticleCommands() {
1479
1747
  const testEventLimit = Number(process.env.MDEDIT_WATCH_TEST_EVENTS || 0);
1480
1748
  try {
1481
1749
  session = await openArticleSession({
1482
- apiKey,
1483
- websocketToken: apiKey,
1750
+ credentialProvider,
1484
1751
  workspaceId,
1485
1752
  articleId,
1486
1753
  agent: { name: options.agent },
@@ -1498,7 +1765,8 @@ function createArticleCommands() {
1498
1765
  }
1499
1766
  });
1500
1767
  article.command("edit <articleId>").description("Apply an anchored one-shot edit through an agent article session").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("--replace <text>", "Replace the unique matching text").option("--with <text>", "Replacement text (used with --replace)").option("--ops-file <path>", "Read a JSON array of edit operations from a file").action(async (articleId, options) => {
1501
- const apiKey = requireApiKey();
1768
+ requireAuthentication();
1769
+ const credentialProvider = getAgentCredentialProvider();
1502
1770
  const workspaceId = requireWorkspaceId(options.workspace);
1503
1771
  const hasInlineOption = options.replace !== void 0 || options.with !== void 0;
1504
1772
  if (options.opsFile && hasInlineOption) {
@@ -1513,8 +1781,7 @@ function createArticleCommands() {
1513
1781
  let result;
1514
1782
  try {
1515
1783
  session = await openArticleSession({
1516
- apiKey,
1517
- websocketToken: apiKey,
1784
+ credentialProvider,
1518
1785
  workspaceId,
1519
1786
  articleId,
1520
1787
  agent: { name: "mdedit-cli" },
@@ -1574,6 +1841,8 @@ function createArticleCommands() {
1574
1841
  }
1575
1842
 
1576
1843
  // src/commands/workspace.ts
1844
+ init_output();
1845
+ init_api();
1577
1846
  import { Command as Command2 } from "commander";
1578
1847
  import inquirer2 from "inquirer";
1579
1848
 
@@ -1681,9 +1950,11 @@ function createWorkspaceCommands() {
1681
1950
  }
1682
1951
 
1683
1952
  // src/commands/folder.ts
1953
+ init_output();
1684
1954
  import { Command as Command3 } from "commander";
1685
1955
  import inquirer3 from "inquirer";
1686
1956
  import { v4 as uuidv42 } from "uuid";
1957
+ init_api();
1687
1958
 
1688
1959
  // src/presenters/folder.ts
1689
1960
  function presentFolderListRow(folder) {
@@ -1796,6 +2067,9 @@ function createFolderCommands() {
1796
2067
  }
1797
2068
 
1798
2069
  // src/commands/config.ts
2070
+ init_config();
2071
+ init_output();
2072
+ init_api();
1799
2073
  import { Command as Command4 } from "commander";
1800
2074
  import inquirer4 from "inquirer";
1801
2075
  function redactSecret(value) {
@@ -1905,6 +2179,8 @@ function createConfigCommands() {
1905
2179
  }
1906
2180
 
1907
2181
  // src/commands/apikey.ts
2182
+ init_output();
2183
+ init_api();
1908
2184
  import { Command as Command5 } from "commander";
1909
2185
  import inquirer5 from "inquirer";
1910
2186
 
@@ -2016,6 +2292,7 @@ function createApiKeyCommands() {
2016
2292
  }
2017
2293
 
2018
2294
  // src/commands/skill.ts
2295
+ init_output();
2019
2296
  import { Command as Command6 } from "commander";
2020
2297
  import { readFileSync as readFileSync2, mkdirSync as mkdirSync2, existsSync as existsSync2, appendFileSync, writeFileSync as writeFileSync2 } from "fs";
2021
2298
  import { dirname, join as join2, resolve } from "path";
@@ -2111,13 +2388,20 @@ function createSkillCommands() {
2111
2388
  }
2112
2389
 
2113
2390
  // src/commands/review.ts
2391
+ init_output();
2114
2392
  import { Command as Command7 } from "commander";
2115
2393
  import {
2116
2394
  openArticleReviewSession
2117
2395
  } from "@mdedit/agent-client";
2396
+ init_api();
2118
2397
  async function withReview(articleId, workspaceId, operation) {
2119
- const apiKey = requireApiKey();
2120
- const review = openArticleReviewSession({ apiKey, workspaceId, articleId, apiUrl: getApiUrlRaw() });
2398
+ requireAuthentication();
2399
+ const review = openArticleReviewSession({
2400
+ credentialProvider: getAgentCredentialProvider(),
2401
+ workspaceId,
2402
+ articleId,
2403
+ apiUrl: getApiUrlRaw()
2404
+ });
2121
2405
  return { mode: "rest", result: await operation(review) };
2122
2406
  }
2123
2407
  function quoteAnchor(options) {
@@ -2210,7 +2494,54 @@ function createSuggestCommand() {
2210
2494
  });
2211
2495
  }
2212
2496
 
2497
+ // src/commands/auth.ts
2498
+ init_output();
2499
+ init_oauth();
2500
+ import { Command as Command8 } from "commander";
2501
+ var defaultRuntime = {
2502
+ login: loginWithOAuth,
2503
+ logout: logoutOAuth,
2504
+ status: oauthStatus
2505
+ };
2506
+ function profileOption(command) {
2507
+ return command.option("--profile <name>", "OAuth profile name");
2508
+ }
2509
+ function createAuthCommands(runtime = defaultRuntime) {
2510
+ const auth = new Command8("auth").description("Manage OAuth sign-in profiles").action(() => auth.help());
2511
+ profileOption(auth.command("login").description("Sign in with browser authorization-code + PKCE").option(
2512
+ "--no-browser",
2513
+ "Print the same browser URL; the browser must run on this callback-capable machine"
2514
+ ).option("--scopes <scopes>", "Comma-separated OAuth scopes")).action(async (options) => {
2515
+ const scopes = options.scopes ? String(options.scopes).split(",").map((scope) => scope.trim()).filter(Boolean) : void 0;
2516
+ const result = await runtime.login({
2517
+ noBrowser: Boolean(options.browser === false),
2518
+ profile: options.profile,
2519
+ ...scopes ? { scopes } : {}
2520
+ });
2521
+ if (!output.isJson()) output.success(`Signed in with OAuth profile ${result.profile}`);
2522
+ output.output(result);
2523
+ });
2524
+ profileOption(auth.command("status").description("Show OAuth status without printing tokens")).action(async (options) => {
2525
+ const result = await runtime.status(options.profile);
2526
+ output.output(result);
2527
+ });
2528
+ profileOption(auth.command("logout").description("Revoke refresh access and remove stored OAuth credentials").option("--all", "Revoke and remove every stored OAuth profile")).action(async (options) => {
2529
+ const result = await runtime.logout({
2530
+ all: Boolean(options.all),
2531
+ profile: options.profile
2532
+ });
2533
+ if (!output.isJson()) {
2534
+ output.success(result.all ? "Logged out every OAuth profile" : `Logged out OAuth profile ${result.profile}`);
2535
+ }
2536
+ output.output(result);
2537
+ });
2538
+ return auth;
2539
+ }
2540
+
2213
2541
  // src/index.ts
2542
+ init_output();
2543
+ init_config();
2544
+ init_api();
2214
2545
  var __filename2 = fileURLToPath2(import.meta.url);
2215
2546
  var __dirname2 = dirname2(__filename2);
2216
2547
  var version = "0.0.0";
@@ -2219,7 +2550,7 @@ try {
2219
2550
  version = packageJson.version || version;
2220
2551
  } catch {
2221
2552
  }
2222
- var program = new Command8();
2553
+ var program = new Command9();
2223
2554
  program.name("mdedit").description("MDEdit.ai CLI - Command-line interface for the markdown editor platform").version(version).option("-F, --format <format>", "Output format: json, table, or plain (default: table)").option("--local", "Use local API at http://localhost:8080").option("--api-url <url>", "Override API URL for this invocation").option("--api-key <key>", "Override API key for this invocation (use env/config in preference)").option("--workspace <workspaceId>", "Override default workspaceId for this invocation").option("--debug", "Show debug output (stacks, request info)").hook("preAction", (thisCommand) => {
2224
2555
  const opts = typeof thisCommand.optsWithGlobals === "function" ? (
2225
2556
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -2240,6 +2571,7 @@ program.addCommand(createApiKeyCommands());
2240
2571
  program.addCommand(createSkillCommands());
2241
2572
  program.addCommand(createReviewCommands());
2242
2573
  program.addCommand(createSuggestCommand());
2574
+ program.addCommand(createAuthCommands());
2243
2575
  program.command("health").description("Check API health status").action(async () => {
2244
2576
  const base = getApiBaseUrlRoot();
2245
2577
  const response = await fetch(`${base}/health`, { method: "GET" });
@@ -2258,9 +2590,11 @@ program.command("health").description("Check API health status").action(async ()
2258
2590
  });
2259
2591
  program.command("info").description("Display CLI and API information").action(async () => {
2260
2592
  const apiUrl = configManager.get("apiUrl") || process.env.MDEDIT_API_URL || "https://apiv2.mdedit.ai";
2261
- const apiKey = configManager.get("apiKey");
2593
+ const apiKey = process.env.MDEDIT_API_KEY || configManager.getAll().apiKey;
2594
+ const activeProfile2 = configManager.get("oauthProfile") || "default";
2595
+ const oauthConfigured = (configManager.get("oauthProfiles") || []).includes(activeProfile2);
2262
2596
  const workspaceId = configManager.get("workspaceId") || process.env.MDEDIT_WORKSPACE_ID || null;
2263
- const authMethod = apiKey ? "apiKey" : "none";
2597
+ const authMethod = process.env.MDEDIT_API_KEY ? "apiKey" : oauthConfigured ? "oauth" : apiKey ? "apiKey" : "none";
2264
2598
  let health = void 0;
2265
2599
  let apiStatus = "unavailable";
2266
2600
  try {
@@ -2271,7 +2605,7 @@ program.command("info").description("Display CLI and API information").action(as
2271
2605
  apiStatus = "unavailable";
2272
2606
  }
2273
2607
  let authOk = null;
2274
- if (apiKey) {
2608
+ if (authMethod !== "none") {
2275
2609
  try {
2276
2610
  const client = getApiClient();
2277
2611
  await client.workspace.list();
@@ -2296,7 +2630,7 @@ program.command("info").description("Display CLI and API information").action(as
2296
2630
  output.info(`CLI Version: ${version}`);
2297
2631
  output.info(`API URL: ${apiUrl}`);
2298
2632
  if (workspaceId) output.info(`Workspace: ${workspaceId}`);
2299
- output.info(`Auth Method: ${authMethod === "apiKey" ? "API Key" : "None"}`);
2633
+ output.info(`Auth Method: ${authMethod === "apiKey" ? "API Key" : authMethod === "oauth" ? `OAuth (${activeProfile2})` : "None"}`);
2300
2634
  if (apiStatus === "healthy") output.success("API Status: Healthy");
2301
2635
  else output.warning("API Status: Unavailable");
2302
2636
  if (authOk === true) output.success("Auth: OK");
@@ -2349,7 +2683,7 @@ async function main() {
2349
2683
  } else if (err instanceof FetchError2) {
2350
2684
  output.error(`API request failed (${err.status}): ${err.message}`);
2351
2685
  if (err.status === 401) {
2352
- output.info("Hint: set an API key via `mdedit config set apiKey <key>` or pass `--api-key <key>`.");
2686
+ output.info("Hint: run `mdedit auth login`; for headless/CI set MDEDIT_API_KEY or pass `--api-key <key>`.");
2353
2687
  } else if (err.status === 403) {
2354
2688
  if (err.message.includes("publishing:write")) {
2355
2689
  output.info("Hint: publishing requires an API key with publishing:write scope.");