mdedit-cli 0.3.0 → 0.3.2

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";
697
-
698
- // src/utils/config.ts
699
- import { homedir } from "os";
700
- import { join } from "path";
701
- 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);
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;
714
142
  }
715
- } catch {
716
- }
717
- }
718
- save() {
719
- try {
720
- if (!existsSync(CONFIG_DIR)) {
721
- mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
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
+ );
722
401
  }
723
- writeFileSync(CONFIG_FILE, JSON.stringify(this.config, null, 2), { mode: 384 });
724
402
  try {
725
- chmodSync(CONFIG_DIR, 448);
403
+ return await response.json();
726
404
  } catch {
405
+ return;
727
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();
728
426
  try {
729
- chmodSync(CONFIG_FILE, 384);
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
+ }
730
432
  } catch {
731
433
  }
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"
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
+ }
743
689
  };
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
690
  }
757
- clear() {
758
- this.config = {};
759
- this.save();
691
+ });
692
+
693
+ // src/utils/config.ts
694
+ import { homedir } from "os";
695
+ import { join } from "path";
696
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
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();
707
+ }
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
+ }
716
+ }
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
+ }
734
+ }
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();
760
+ }
761
+ };
762
+ configManager = new ConfigManager();
760
763
  }
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,734 @@ 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
- });
935
+ });
936
+
937
+ // ../node-auth/dist/index.js
938
+ import { timingSafeEqual } from "crypto";
939
+ import { createServer } from "http";
940
+ import { Entry } from "@napi-rs/keyring";
941
+ import { createHash, randomBytes } from "crypto";
942
+ function required(value, name) {
943
+ const normalized = value?.trim();
944
+ if (!normalized) throw new TypeError(`${name} is required`);
945
+ return normalized;
946
+ }
947
+ async function responsePayload(response) {
948
+ const payload = await response.json().catch(() => ({}));
949
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
950
+ }
951
+ function stringField(payload, name) {
952
+ const value = payload[name];
953
+ return typeof value === "string" ? value : "";
954
+ }
955
+ function statesMatch(actual, expected) {
956
+ const actualBuffer = Buffer.from(actual);
957
+ const expectedBuffer = Buffer.from(expected);
958
+ return actualBuffer.length === expectedBuffer.length && timingSafeEqual(actualBuffer, expectedBuffer);
959
+ }
960
+ async function startLoopbackCallback({
961
+ redirectUri,
962
+ state,
963
+ listenPort,
964
+ timeoutMs = 12e4
965
+ }) {
966
+ const redirect = new URL(redirectUri);
967
+ if (redirect.protocol !== "http:" || redirect.hostname !== "localhost") {
968
+ throw new TypeError("OAuth redirect URI must use http://localhost");
969
+ }
970
+ const port = listenPort ?? Number(redirect.port);
971
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
972
+ throw new TypeError("OAuth redirect URI must include a valid port");
973
+ }
974
+ let resolveResult;
975
+ let rejectResult;
976
+ const result = new Promise((resolve2, reject) => {
977
+ resolveResult = resolve2;
978
+ rejectResult = reject;
979
+ });
980
+ let settled = false;
981
+ let timeout;
982
+ const server = createServer((request, response) => {
983
+ const url = new URL(request.url || "/", "http://localhost");
984
+ if (request.method !== "GET" || url.pathname !== redirect.pathname) {
985
+ response.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
986
+ response.end("Not found");
900
987
  return;
901
988
  }
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
- }
989
+ const finish = (error, code2) => {
990
+ if (settled) return;
991
+ settled = true;
992
+ if (timeout) clearTimeout(timeout);
993
+ response.writeHead(error ? 400 : 200, {
994
+ "content-type": "text/plain; charset=utf-8"
910
995
  });
996
+ response.end(error ? "OAuth login failed. Return to the terminal." : "OAuth login complete. You can close this window.");
997
+ server.close();
998
+ if (error) rejectResult(error);
999
+ else resolveResult(code2);
1000
+ };
1001
+ const actualState = url.searchParams.get("state") || "";
1002
+ if (!statesMatch(actualState, state)) {
1003
+ finish(new OAuthClientError(
1004
+ "OAuth callback state did not match",
1005
+ "OAUTH_STATE_MISMATCH"
1006
+ ));
911
1007
  return;
912
1008
  }
913
- console.log(" ".repeat(indent) + String(obj));
914
- }
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);
1009
+ const oauthError = url.searchParams.get("error");
1010
+ if (oauthError) {
1011
+ finish(new OAuthClientError(
1012
+ `OAuth authorization failed: ${oauthError}`,
1013
+ "OAUTH_AUTHORIZATION_DENIED"
1014
+ ));
1015
+ return;
1016
+ }
1017
+ const code = url.searchParams.get("code");
1018
+ if (!code) {
1019
+ finish(new OAuthClientError(
1020
+ "OAuth callback did not include an authorization code",
1021
+ "OAUTH_CALLBACK_INVALID"
1022
+ ));
1023
+ return;
922
1024
  }
1025
+ finish(void 0, code);
1026
+ });
1027
+ await new Promise((resolve2, reject) => {
1028
+ server.once("error", (error) => {
1029
+ if (error.code === "EADDRINUSE") {
1030
+ reject(new OAuthClientError(
1031
+ `OAuth callback port ${port} is already in use`,
1032
+ "OAUTH_CALLBACK_PORT_IN_USE",
1033
+ { port }
1034
+ ));
1035
+ return;
1036
+ }
1037
+ reject(error);
1038
+ });
1039
+ server.listen(port, "127.0.0.1", resolve2);
1040
+ });
1041
+ const address = server.address();
1042
+ const boundPort = typeof address === "object" && address ? address.port : port;
1043
+ timeout = setTimeout(() => {
1044
+ if (settled) return;
1045
+ settled = true;
1046
+ server.close();
1047
+ rejectResult(new OAuthClientError(
1048
+ "OAuth callback timed out",
1049
+ "OAUTH_CALLBACK_TIMEOUT"
1050
+ ));
1051
+ }, timeoutMs);
1052
+ return {
1053
+ port: boundPort,
1054
+ result,
1055
+ close: () => new Promise((resolve2) => {
1056
+ if (timeout) clearTimeout(timeout);
1057
+ if (!server.listening) {
1058
+ resolve2();
1059
+ return;
1060
+ }
1061
+ server.close(() => resolve2());
1062
+ })
1063
+ };
1064
+ }
1065
+ function normalizeProfiles(profiles) {
1066
+ return [...new Set(profiles.map((profile) => profile.trim()).filter(Boolean))].sort();
1067
+ }
1068
+ function createPkcePair() {
1069
+ const verifier = randomBytes(48).toString("base64url");
1070
+ return {
1071
+ verifier,
1072
+ challenge: createHash("sha256").update(verifier).digest("base64url"),
1073
+ method: "S256"
1074
+ };
1075
+ }
1076
+ var OAuthClientError, refreshesByCredentialStore, NodeOAuthClient, DEFAULT_SERVICE, OsCredentialStore;
1077
+ var init_dist2 = __esm({
1078
+ "../node-auth/dist/index.js"() {
1079
+ "use strict";
1080
+ OAuthClientError = class extends Error {
1081
+ constructor(message, code, details) {
1082
+ super(message);
1083
+ this.code = code;
1084
+ this.details = details;
1085
+ this.name = "OAuthClientError";
1086
+ }
1087
+ };
1088
+ refreshesByCredentialStore = /* @__PURE__ */ new WeakMap();
1089
+ NodeOAuthClient = class {
1090
+ configuration;
1091
+ credentialStore;
1092
+ fetch;
1093
+ refreshes;
1094
+ constructor({
1095
+ configuration,
1096
+ credentialStore: credentialStore2,
1097
+ fetch: fetch2 = globalThis.fetch
1098
+ }) {
1099
+ this.configuration = configuration;
1100
+ this.credentialStore = credentialStore2;
1101
+ this.fetch = fetch2;
1102
+ const existingRefreshes = refreshesByCredentialStore.get(credentialStore2);
1103
+ this.refreshes = existingRefreshes ?? /* @__PURE__ */ new Map();
1104
+ if (!existingRefreshes) {
1105
+ refreshesByCredentialStore.set(credentialStore2, this.refreshes);
1106
+ }
1107
+ }
1108
+ createAuthorizationRequest({
1109
+ challenge,
1110
+ state
1111
+ }) {
1112
+ const url = new URL(this.configuration.authorizationEndpoint);
1113
+ url.search = new URLSearchParams({
1114
+ client_id: required(this.configuration.clientId, "clientId"),
1115
+ code_challenge: required(challenge, "challenge"),
1116
+ code_challenge_method: "S256",
1117
+ redirect_uri: required(this.configuration.redirectUri, "redirectUri"),
1118
+ resource: required(this.configuration.resource, "resource"),
1119
+ response_type: "code",
1120
+ scope: this.configuration.scopes.join(" "),
1121
+ state: required(state, "state")
1122
+ }).toString();
1123
+ return { url: url.toString() };
1124
+ }
1125
+ async exchangeAuthorizationCode({
1126
+ code,
1127
+ profile,
1128
+ verifier
1129
+ }) {
1130
+ const tokenSet = await this.tokenRequest(new URLSearchParams({
1131
+ client_id: this.configuration.clientId,
1132
+ code: required(code, "code"),
1133
+ code_verifier: required(verifier, "verifier"),
1134
+ grant_type: "authorization_code",
1135
+ redirect_uri: this.configuration.redirectUri,
1136
+ resource: this.configuration.resource
1137
+ }), "OAUTH_CODE_EXCHANGE_FAILED");
1138
+ await this.credentialStore.set(required(profile, "profile"), tokenSet);
1139
+ return tokenSet;
1140
+ }
1141
+ async getAccessToken(profile, { forceRefresh = false } = {}) {
1142
+ const normalizedProfile = required(profile, "profile");
1143
+ const tokenSet = await this.credentialStore.get(normalizedProfile);
1144
+ if (!tokenSet) {
1145
+ throw new OAuthClientError(
1146
+ `OAuth profile "${normalizedProfile}" is not logged in`,
1147
+ "OAUTH_LOGIN_REQUIRED"
1148
+ );
1149
+ }
1150
+ if (!forceRefresh && tokenSet.expiresAt > Date.now() + 3e4) {
1151
+ return tokenSet.accessToken;
1152
+ }
1153
+ const refreshKey = JSON.stringify([
1154
+ this.configuration.tokenEndpoint,
1155
+ this.configuration.clientId,
1156
+ this.configuration.resource,
1157
+ normalizedProfile
1158
+ ]);
1159
+ let refresh = this.refreshes.get(refreshKey);
1160
+ if (!refresh) {
1161
+ refresh = this.refresh(normalizedProfile, tokenSet).finally(() => this.refreshes.delete(refreshKey));
1162
+ this.refreshes.set(refreshKey, refresh);
1163
+ }
1164
+ return (await refresh).accessToken;
1165
+ }
1166
+ async status(profile) {
1167
+ const normalizedProfile = required(profile, "profile");
1168
+ const tokenSet = await this.credentialStore.get(normalizedProfile);
1169
+ return tokenSet ? {
1170
+ authenticated: true,
1171
+ expiresAt: tokenSet.expiresAt,
1172
+ profile: normalizedProfile,
1173
+ scope: [...tokenSet.scope]
1174
+ } : { authenticated: false, profile: normalizedProfile };
1175
+ }
1176
+ async logout(profile) {
1177
+ const normalizedProfile = required(profile, "profile");
1178
+ const tokenSet = await this.credentialStore.get(normalizedProfile);
1179
+ if (!tokenSet) return;
1180
+ await this.revoke(tokenSet.refreshToken);
1181
+ await this.credentialStore.delete(normalizedProfile);
1182
+ }
1183
+ async logoutAll() {
1184
+ for (const profile of await this.credentialStore.listProfiles()) {
1185
+ await this.logout(profile);
1186
+ }
1187
+ }
1188
+ async refresh(profile, current) {
1189
+ const replacement = await this.tokenRequest(new URLSearchParams({
1190
+ client_id: this.configuration.clientId,
1191
+ grant_type: "refresh_token",
1192
+ refresh_token: current.refreshToken,
1193
+ resource: this.configuration.resource
1194
+ }), "OAUTH_REFRESH_FAILED", {
1195
+ refreshToken: current.refreshToken,
1196
+ scopes: current.scope
1197
+ });
1198
+ await this.credentialStore.set(profile, replacement);
1199
+ return replacement;
1200
+ }
1201
+ async revoke(refreshToken) {
1202
+ if (!this.configuration.revocationEndpoint) {
1203
+ throw new OAuthClientError(
1204
+ "OAuth revocation endpoint is not configured",
1205
+ "OAUTH_REVOCATION_UNAVAILABLE"
1206
+ );
1207
+ }
1208
+ const response = await this.fetch(this.configuration.revocationEndpoint, {
1209
+ method: "POST",
1210
+ headers: { "content-type": "application/x-www-form-urlencoded" },
1211
+ body: new URLSearchParams({
1212
+ client_id: this.configuration.clientId,
1213
+ token: refreshToken
1214
+ })
1215
+ });
1216
+ if (!response.ok) {
1217
+ throw new OAuthClientError(
1218
+ `OAuth revocation failed with status ${response.status}`,
1219
+ "OAUTH_REVOCATION_FAILED",
1220
+ { status: response.status }
1221
+ );
1222
+ }
1223
+ }
1224
+ async tokenRequest(body, errorCode, fallback) {
1225
+ const response = await this.fetch(this.configuration.tokenEndpoint, {
1226
+ method: "POST",
1227
+ headers: { "content-type": "application/x-www-form-urlencoded" },
1228
+ body
1229
+ });
1230
+ const payload = await responsePayload(response);
1231
+ if (!response.ok) {
1232
+ throw new OAuthClientError(
1233
+ `OAuth token request failed with status ${response.status}`,
1234
+ errorCode,
1235
+ {
1236
+ error: stringField(payload, "error") || void 0,
1237
+ status: response.status
1238
+ }
1239
+ );
1240
+ }
1241
+ const accessToken = stringField(payload, "access_token");
1242
+ const refreshToken = stringField(payload, "refresh_token") || fallback?.refreshToken || "";
1243
+ const tokenType = stringField(payload, "token_type") || "Bearer";
1244
+ const expiresIn = Number(payload.expires_in);
1245
+ if (!accessToken || !refreshToken || !Number.isFinite(expiresIn) || expiresIn <= 0) {
1246
+ throw new OAuthClientError("OAuth token response is incomplete", errorCode);
1247
+ }
1248
+ const returnedScopes = stringField(payload, "scope").split(/\s+/).filter(Boolean);
1249
+ return {
1250
+ accessToken,
1251
+ expiresAt: Date.now() + expiresIn * 1e3,
1252
+ refreshToken,
1253
+ scope: returnedScopes.length > 0 ? returnedScopes : [...fallback?.scopes || []],
1254
+ tokenType
1255
+ };
1256
+ }
1257
+ };
1258
+ DEFAULT_SERVICE = "ai.mdedit.oauth";
1259
+ OsCredentialStore = class {
1260
+ createEntry;
1261
+ loadProfileIndex;
1262
+ saveProfileIndex;
1263
+ service;
1264
+ constructor({
1265
+ createEntry = (service2, account) => new Entry(service2, account),
1266
+ loadProfileIndex,
1267
+ saveProfileIndex,
1268
+ service = DEFAULT_SERVICE
1269
+ }) {
1270
+ this.createEntry = createEntry;
1271
+ this.loadProfileIndex = loadProfileIndex;
1272
+ this.saveProfileIndex = saveProfileIndex;
1273
+ this.service = service;
1274
+ }
1275
+ async delete(profile) {
1276
+ this.createEntry(this.service, profile).deletePassword();
1277
+ const profiles = (await this.listProfiles()).filter((item) => item !== profile);
1278
+ await this.saveProfileIndex(profiles);
1279
+ }
1280
+ async get(profile) {
1281
+ const serialized = this.createEntry(this.service, profile).getPassword();
1282
+ if (!serialized) return null;
1283
+ const parsed = JSON.parse(serialized);
1284
+ if (!parsed || typeof parsed.accessToken !== "string" || typeof parsed.refreshToken !== "string" || typeof parsed.expiresAt !== "number" || !Array.isArray(parsed.scope)) {
1285
+ throw new Error(`Stored OAuth profile "${profile}" is invalid`);
1286
+ }
1287
+ return parsed;
1288
+ }
1289
+ async listProfiles() {
1290
+ return normalizeProfiles(await this.loadProfileIndex());
1291
+ }
1292
+ async set(profile, tokenSet) {
1293
+ this.createEntry(this.service, profile).setPassword(JSON.stringify(tokenSet));
1294
+ await this.saveProfileIndex(normalizeProfiles([
1295
+ ...await this.loadProfileIndex(),
1296
+ profile
1297
+ ]));
1298
+ }
1299
+ };
923
1300
  }
924
- };
925
- var output = new OutputFormatter();
1301
+ });
926
1302
 
927
- // src/utils/context.ts
928
- function resolveWorkspaceId(cliWorkspaceId) {
929
- return cliWorkspaceId || configManager.get("workspaceId") || process.env.MDEDIT_WORKSPACE_ID;
1303
+ // src/utils/oauth.ts
1304
+ var oauth_exports = {};
1305
+ __export(oauth_exports, {
1306
+ loginWithOAuth: () => loginWithOAuth,
1307
+ logoutOAuth: () => logoutOAuth,
1308
+ oauthStatus: () => oauthStatus,
1309
+ qualifyOAuthScopes: () => qualifyOAuthScopes,
1310
+ storedOAuthAccessToken: () => storedOAuthAccessToken
1311
+ });
1312
+ import { randomBytes as randomBytes2 } from "crypto";
1313
+ import { spawn } from "child_process";
1314
+ function activeProfile(profile) {
1315
+ return profile?.trim() || configManager.get("oauthProfile") || DEFAULT_PROFILE;
930
1316
  }
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
- );
1317
+ function profileIndex() {
1318
+ return configManager.get("oauthProfiles") || [];
1319
+ }
1320
+ function setProfileIndex(profiles) {
1321
+ configManager.set("oauthProfiles", [...new Set(profiles)].sort());
1322
+ }
1323
+ async function discoverOAuthConfiguration() {
1324
+ const clientId = process.env.MDEDIT_OAUTH_CLIENT_ID;
1325
+ const authorizationEndpoint = process.env.MDEDIT_OAUTH_AUTHORIZATION_ENDPOINT;
1326
+ const tokenEndpoint = process.env.MDEDIT_OAUTH_TOKEN_ENDPOINT;
1327
+ const revocationEndpoint = process.env.MDEDIT_OAUTH_REVOCATION_ENDPOINT;
1328
+ if (clientId && authorizationEndpoint && tokenEndpoint && revocationEndpoint) {
1329
+ return {
1330
+ authorizationEndpoint,
1331
+ clientId,
1332
+ defaultScopes: (process.env.MDEDIT_OAUTH_SCOPES || "").split(",").map((scope) => scope.trim()).filter(Boolean),
1333
+ resource: process.env.MDEDIT_OAUTH_RESOURCE || "https://apiv2.mdedit.ai/api",
1334
+ revocationEndpoint,
1335
+ tokenEndpoint
1336
+ };
937
1337
  }
938
- return workspaceId;
1338
+ const response = await fetch(`${getApiBaseUrlRoot()}/.well-known/mdedit-cli-oauth`);
1339
+ if (!response.ok) {
1340
+ throw new Error(`OAuth discovery failed (${response.status})`);
1341
+ }
1342
+ const document = await response.json();
1343
+ if (!document.clientId || !document.authorizationEndpoint || !document.tokenEndpoint || !document.revocationEndpoint || !document.resource || !Array.isArray(document.defaultScopes)) {
1344
+ throw new Error("OAuth discovery response is incomplete");
1345
+ }
1346
+ return document;
1347
+ }
1348
+ function credentialStore() {
1349
+ return new OsCredentialStore({
1350
+ loadProfileIndex: async () => profileIndex(),
1351
+ saveProfileIndex: async (profiles) => setProfileIndex(profiles)
1352
+ });
1353
+ }
1354
+ function qualifyOAuthScopes(scopes, resource) {
1355
+ const prefix = `${resource.replace(/\/+$/, "")}/`;
1356
+ return [...new Set(scopes.map((scope) => {
1357
+ const normalized = scope.trim();
1358
+ if (!normalized) return "";
1359
+ if (normalized.startsWith(prefix)) return normalized;
1360
+ if (normalized.includes("://") || normalized.includes("/")) {
1361
+ throw new Error(`OAuth scope is for a different resource: ${normalized}`);
1362
+ }
1363
+ return `${prefix}${normalized}`;
1364
+ }).filter(Boolean))];
1365
+ }
1366
+ async function oauthClient(scopes) {
1367
+ const discovery = await discoverOAuthConfiguration();
1368
+ const selectedScopes = scopes?.length ? scopes : discovery.defaultScopes;
1369
+ const configuration = {
1370
+ authorizationEndpoint: discovery.authorizationEndpoint,
1371
+ clientId: discovery.clientId,
1372
+ redirectUri: FIXED_REDIRECT_URI,
1373
+ resource: discovery.resource,
1374
+ revocationEndpoint: discovery.revocationEndpoint,
1375
+ scopes: qualifyOAuthScopes(selectedScopes, discovery.resource),
1376
+ tokenEndpoint: discovery.tokenEndpoint
1377
+ };
1378
+ const cacheKey = JSON.stringify(configuration);
1379
+ const existing = oauthClientsByConfiguration.get(cacheKey);
1380
+ if (existing) return existing;
1381
+ const client = new NodeOAuthClient({
1382
+ configuration,
1383
+ credentialStore: credentialStore()
1384
+ });
1385
+ oauthClientsByConfiguration.set(cacheKey, client);
1386
+ return client;
1387
+ }
1388
+ function launchBrowser(url) {
1389
+ 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] };
1390
+ const child = spawn(command.executable, command.args, {
1391
+ detached: true,
1392
+ stdio: "ignore"
1393
+ });
1394
+ child.unref();
1395
+ }
1396
+ async function loginWithOAuth({
1397
+ noBrowser = false,
1398
+ profile,
1399
+ scopes
1400
+ }) {
1401
+ const normalizedProfile = activeProfile(profile);
1402
+ const client = await oauthClient(scopes);
1403
+ const pkce = createPkcePair();
1404
+ const state = randomBytes2(32).toString("base64url");
1405
+ const callback = await startLoopbackCallback({
1406
+ redirectUri: FIXED_REDIRECT_URI,
1407
+ state
1408
+ });
1409
+ const authorization = client.createAuthorizationRequest({
1410
+ challenge: pkce.challenge,
1411
+ state
1412
+ });
1413
+ output.info(
1414
+ noBrowser ? `Open this URL in a browser on this machine: ${authorization.url}` : "Opening a browser for mdedit sign-in\u2026"
1415
+ );
1416
+ if (!noBrowser) launchBrowser(authorization.url);
1417
+ try {
1418
+ const code = await callback.result;
1419
+ const tokenSet = await client.exchangeAuthorizationCode({
1420
+ code,
1421
+ profile: normalizedProfile,
1422
+ verifier: pkce.verifier
1423
+ });
1424
+ configManager.set("oauthProfile", normalizedProfile);
1425
+ return {
1426
+ expiresAt: tokenSet.expiresAt,
1427
+ profile: normalizedProfile,
1428
+ scope: [...tokenSet.scope]
1429
+ };
1430
+ } finally {
1431
+ await callback.close();
1432
+ }
1433
+ }
1434
+ async function oauthStatus(profile) {
1435
+ const normalizedProfile = activeProfile(profile);
1436
+ return (await oauthClient()).status(normalizedProfile);
939
1437
  }
1438
+ async function logoutOAuth({
1439
+ all,
1440
+ profile
1441
+ }) {
1442
+ const client = await oauthClient();
1443
+ if (all) {
1444
+ await client.logoutAll();
1445
+ configManager.set("oauthProfile", void 0);
1446
+ return { all: true };
1447
+ }
1448
+ const normalizedProfile = activeProfile(profile);
1449
+ await client.logout(normalizedProfile);
1450
+ if (configManager.get("oauthProfile") === normalizedProfile) {
1451
+ configManager.set("oauthProfile", void 0);
1452
+ }
1453
+ return { all: false, profile: normalizedProfile };
1454
+ }
1455
+ async function storedOAuthAccessToken(profile, forceRefresh = false) {
1456
+ const normalizedProfile = activeProfile(profile);
1457
+ if (!profileIndex().includes(normalizedProfile)) return null;
1458
+ return (await oauthClient()).getAccessToken(normalizedProfile, { forceRefresh });
1459
+ }
1460
+ var DEFAULT_PROFILE, FIXED_REDIRECT_URI, oauthClientsByConfiguration;
1461
+ var init_oauth = __esm({
1462
+ "src/utils/oauth.ts"() {
1463
+ "use strict";
1464
+ init_dist2();
1465
+ init_config();
1466
+ init_api();
1467
+ init_output();
1468
+ DEFAULT_PROFILE = "default";
1469
+ FIXED_REDIRECT_URI = "http://localhost:17643/oauth/callback";
1470
+ oauthClientsByConfiguration = /* @__PURE__ */ new Map();
1471
+ }
1472
+ });
940
1473
 
941
1474
  // src/utils/api.ts
1475
+ function selectAuthentication({
1476
+ explicitApiKey,
1477
+ oauthAccessToken,
1478
+ storedApiKey
1479
+ }) {
1480
+ const normalizedExplicitKey = explicitApiKey?.trim();
1481
+ if (normalizedExplicitKey) {
1482
+ return {
1483
+ headers: { "x-api-key": normalizedExplicitKey },
1484
+ method: "apiKey",
1485
+ websocketToken: normalizedExplicitKey
1486
+ };
1487
+ }
1488
+ const normalizedOAuthToken = oauthAccessToken?.trim();
1489
+ if (normalizedOAuthToken) {
1490
+ return {
1491
+ headers: { Authorization: `Bearer ${normalizedOAuthToken}` },
1492
+ method: "oauth",
1493
+ websocketToken: normalizedOAuthToken
1494
+ };
1495
+ }
1496
+ const normalizedStoredKey = storedApiKey?.trim();
1497
+ if (normalizedStoredKey) {
1498
+ return {
1499
+ headers: { "x-api-key": normalizedStoredKey },
1500
+ method: "apiKey",
1501
+ websocketToken: normalizedStoredKey
1502
+ };
1503
+ }
1504
+ return null;
1505
+ }
942
1506
  function trimTrailingSlashes(value) {
943
1507
  return value.replace(/\/+$/, "");
944
1508
  }
@@ -957,35 +1521,99 @@ function getApiBaseUrlV2() {
957
1521
  if (raw.endsWith("/api") || raw.endsWith("/api/v2")) return raw;
958
1522
  return `${raw}/api`;
959
1523
  }
960
- function requireApiKey() {
961
- const apiKey = configManager.get("apiKey") || process.env.MDEDIT_API_KEY;
962
- if (!apiKey) {
1524
+ function requireAuthentication() {
1525
+ const activeProfile2 = configManager.get("oauthProfile") || "default";
1526
+ const oauthConfigured = (configManager.get("oauthProfiles") || []).includes(activeProfile2);
1527
+ const apiKey = process.env.MDEDIT_API_KEY || configManager.getAll().apiKey;
1528
+ if (!apiKey && !oauthConfigured) {
963
1529
  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"
1530
+ "Login required. Run `mdedit auth login`; for headless/CI use --api-key, MDEDIT_API_KEY, or a stored API key."
965
1531
  );
966
1532
  }
967
- return String(apiKey);
968
1533
  }
969
- var _cachedKey = null;
970
- var _cachedClient = null;
1534
+ async function resolveAuthentication(forceOAuthRefresh = false) {
1535
+ const explicitApiKey = process.env.MDEDIT_API_KEY;
1536
+ const { storedOAuthAccessToken: storedOAuthAccessToken2 } = await Promise.resolve().then(() => (init_oauth(), oauth_exports));
1537
+ const authentication = selectAuthentication({
1538
+ explicitApiKey,
1539
+ oauthAccessToken: explicitApiKey ? null : await storedOAuthAccessToken2(void 0, forceOAuthRefresh),
1540
+ storedApiKey: configManager.getAll().apiKey
1541
+ });
1542
+ if (authentication) return authentication;
1543
+ throw new Error(
1544
+ "Login required. Run `mdedit auth login`; for headless/CI use --api-key or MDEDIT_API_KEY."
1545
+ );
1546
+ }
1547
+ function getAgentCredentialProvider() {
1548
+ return {
1549
+ getCredential: () => resolveAuthentication(),
1550
+ refreshCredential: () => resolveAuthentication(true)
1551
+ };
1552
+ }
971
1553
  function getApiClient() {
972
1554
  const baseUrlV2 = getApiBaseUrlV2();
973
- const apiKey = configManager.get("apiKey") || process.env.MDEDIT_API_KEY || "";
974
- const cacheKey = `${baseUrlV2}::${apiKey}`;
1555
+ const cacheKey = baseUrlV2;
975
1556
  if (_cachedClient && _cachedKey === cacheKey) return _cachedClient;
976
1557
  const client = createSdkClient({
977
1558
  baseUrlV2,
978
1559
  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;
1560
+ return (await resolveAuthentication()).headers;
983
1561
  }
984
1562
  });
985
1563
  _cachedKey = cacheKey;
986
1564
  _cachedClient = client;
987
1565
  return client;
988
1566
  }
1567
+ var requireApiKey, _cachedKey, _cachedClient;
1568
+ var init_api = __esm({
1569
+ "src/utils/api.ts"() {
1570
+ "use strict";
1571
+ init_dist();
1572
+ init_config();
1573
+ requireApiKey = requireAuthentication;
1574
+ _cachedKey = null;
1575
+ _cachedClient = null;
1576
+ }
1577
+ });
1578
+
1579
+ // src/index.ts
1580
+ init_dist();
1581
+ import { Command as Command9 } from "commander";
1582
+ import { readFileSync as readFileSync3 } from "fs";
1583
+ import { dirname as dirname2, join as join3 } from "path";
1584
+ import { fileURLToPath as fileURLToPath2 } from "url";
1585
+ import { AgentClientHttpError } from "@mdedit/agent-client";
1586
+
1587
+ // src/commands/article.ts
1588
+ init_dist();
1589
+ init_output();
1590
+ import { Command } from "commander";
1591
+ import inquirer from "inquirer";
1592
+ import { v4 as uuidv4 } from "uuid";
1593
+ import { readFile, writeFile } from "fs/promises";
1594
+ import { createHash as createHash2 } from "crypto";
1595
+ import { basename, extname } from "path";
1596
+ import {
1597
+ openArticleSession
1598
+ } from "@mdedit/agent-client";
1599
+
1600
+ // src/utils/context.ts
1601
+ init_config();
1602
+ function resolveWorkspaceId(cliWorkspaceId) {
1603
+ return cliWorkspaceId || configManager.get("workspaceId") || process.env.MDEDIT_WORKSPACE_ID;
1604
+ }
1605
+ function requireWorkspaceId(cliWorkspaceId) {
1606
+ const workspaceId = resolveWorkspaceId(cliWorkspaceId);
1607
+ if (!workspaceId) {
1608
+ throw new Error(
1609
+ "workspaceId is required. Pass --workspace <id> or set a default with: mdedit config set workspaceId <id>"
1610
+ );
1611
+ }
1612
+ return workspaceId;
1613
+ }
1614
+
1615
+ // src/commands/article.ts
1616
+ init_api();
989
1617
 
990
1618
  // src/utils/exitCodes.ts
991
1619
  import {
@@ -1156,7 +1784,7 @@ async function writeBlobToFile(blob, filePath) {
1156
1784
  await writeFile(filePath, buffer);
1157
1785
  }
1158
1786
  function sha256Hex(content) {
1159
- return createHash("sha256").update(content).digest("hex");
1787
+ return createHash2("sha256").update(content).digest("hex");
1160
1788
  }
1161
1789
  function inferFileTitle(filePath, content) {
1162
1790
  const firstHeading = content?.match(/^\s*#\s+(.+?)\s*$/m)?.[1]?.trim();
@@ -1257,7 +1885,8 @@ function createArticleCommands() {
1257
1885
  output.info("Hint: use `mdedit article get <articleId> --content-only` to print markdown, or `--include-content` to include it in the output.");
1258
1886
  });
1259
1887
  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();
1888
+ requireAuthentication();
1889
+ const credentialProvider = getAgentCredentialProvider();
1261
1890
  const client = getApiClient();
1262
1891
  const workspaceId = requireWorkspaceId(options.workspace);
1263
1892
  if (options.content !== void 0 && options.file !== void 0) {
@@ -1299,8 +1928,7 @@ function createArticleCommands() {
1299
1928
  try {
1300
1929
  if (options.collaborative) {
1301
1930
  const session = await openArticleSession({
1302
- apiKey,
1303
- websocketToken: apiKey,
1931
+ credentialProvider,
1304
1932
  workspaceId,
1305
1933
  articleId,
1306
1934
  agent: { name: "mdedit-cli" },
@@ -1464,7 +2092,8 @@ function createArticleCommands() {
1464
2092
  output.output(result);
1465
2093
  });
1466
2094
  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();
2095
+ requireAuthentication();
2096
+ const credentialProvider = getAgentCredentialProvider();
1468
2097
  const workspaceId = requireWorkspaceId(options.workspace);
1469
2098
  const pollIntervalMs = Number(options.pollInterval);
1470
2099
  if (!Number.isFinite(pollIntervalMs) || pollIntervalMs < 100) {
@@ -1479,8 +2108,7 @@ function createArticleCommands() {
1479
2108
  const testEventLimit = Number(process.env.MDEDIT_WATCH_TEST_EVENTS || 0);
1480
2109
  try {
1481
2110
  session = await openArticleSession({
1482
- apiKey,
1483
- websocketToken: apiKey,
2111
+ credentialProvider,
1484
2112
  workspaceId,
1485
2113
  articleId,
1486
2114
  agent: { name: options.agent },
@@ -1498,7 +2126,8 @@ function createArticleCommands() {
1498
2126
  }
1499
2127
  });
1500
2128
  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();
2129
+ requireAuthentication();
2130
+ const credentialProvider = getAgentCredentialProvider();
1502
2131
  const workspaceId = requireWorkspaceId(options.workspace);
1503
2132
  const hasInlineOption = options.replace !== void 0 || options.with !== void 0;
1504
2133
  if (options.opsFile && hasInlineOption) {
@@ -1513,8 +2142,7 @@ function createArticleCommands() {
1513
2142
  let result;
1514
2143
  try {
1515
2144
  session = await openArticleSession({
1516
- apiKey,
1517
- websocketToken: apiKey,
2145
+ credentialProvider,
1518
2146
  workspaceId,
1519
2147
  articleId,
1520
2148
  agent: { name: "mdedit-cli" },
@@ -1574,6 +2202,8 @@ function createArticleCommands() {
1574
2202
  }
1575
2203
 
1576
2204
  // src/commands/workspace.ts
2205
+ init_output();
2206
+ init_api();
1577
2207
  import { Command as Command2 } from "commander";
1578
2208
  import inquirer2 from "inquirer";
1579
2209
 
@@ -1681,9 +2311,11 @@ function createWorkspaceCommands() {
1681
2311
  }
1682
2312
 
1683
2313
  // src/commands/folder.ts
2314
+ init_output();
1684
2315
  import { Command as Command3 } from "commander";
1685
2316
  import inquirer3 from "inquirer";
1686
2317
  import { v4 as uuidv42 } from "uuid";
2318
+ init_api();
1687
2319
 
1688
2320
  // src/presenters/folder.ts
1689
2321
  function presentFolderListRow(folder) {
@@ -1796,6 +2428,9 @@ function createFolderCommands() {
1796
2428
  }
1797
2429
 
1798
2430
  // src/commands/config.ts
2431
+ init_config();
2432
+ init_output();
2433
+ init_api();
1799
2434
  import { Command as Command4 } from "commander";
1800
2435
  import inquirer4 from "inquirer";
1801
2436
  function redactSecret(value) {
@@ -1905,6 +2540,8 @@ function createConfigCommands() {
1905
2540
  }
1906
2541
 
1907
2542
  // src/commands/apikey.ts
2543
+ init_output();
2544
+ init_api();
1908
2545
  import { Command as Command5 } from "commander";
1909
2546
  import inquirer5 from "inquirer";
1910
2547
 
@@ -1922,58 +2559,12 @@ function presentApiKeyListRow(key) {
1922
2559
  }
1923
2560
 
1924
2561
  // src/commands/apikey.ts
1925
- var DEFAULT_API_KEY_SCOPES = ["articles:read", "articles:write"];
1926
2562
  function createApiKeyCommands() {
1927
2563
  const apiKey = new Command5("api-key").description("Manage API keys for authentication").aliases(["apikey"]).action(() => apiKey.help());
1928
- apiKey.command("create").description("Create a new API key").option("-n, --name <name>", 'Key name (e.g., "Local Dev", "CI/CD")').option("-d, --description <desc>", "Key description").option("--expires <days>", "Expiration in days (optional)").option("--scopes <scopes>", "Comma-separated least-privilege scopes").action(async (options) => {
1929
- requireApiKey();
1930
- const client = getApiClient();
1931
- let name = options.name;
1932
- if (!name) {
1933
- const answers = await inquirer5.prompt([
1934
- {
1935
- type: "input",
1936
- name: "name",
1937
- message: "API key name:",
1938
- validate: (input) => input.length > 0 || "Name is required"
1939
- }
1940
- ]);
1941
- name = String(answers.name);
1942
- }
1943
- const expiresRaw = options.expires;
1944
- let expiresInDays = void 0;
1945
- if (expiresRaw !== void 0) {
1946
- const days = Number.parseInt(String(expiresRaw), 10);
1947
- if (!Number.isFinite(days) || days <= 0) {
1948
- throw new Error("--expires must be a positive integer (number of days).");
1949
- }
1950
- expiresInDays = days;
1951
- }
1952
- const scopesRaw = options.scopes;
1953
- const scopes = scopesRaw === void 0 ? DEFAULT_API_KEY_SCOPES : [...new Set(scopesRaw.split(",").map((scope) => scope.trim()).filter(Boolean))];
1954
- if (scopesRaw !== void 0 && scopes?.length === 0) {
1955
- throw new Error("--scopes must contain at least one scope.");
1956
- }
1957
- output.info("Creating API key...");
1958
- const req = { name };
1959
- if (options.description) req.description = options.description;
1960
- if (expiresInDays !== void 0) req.expiresInDays = expiresInDays;
1961
- req.scopes = scopes;
1962
- const result = await client.apiKeys.create(req);
1963
- output.success("API key created successfully!");
1964
- output.warning("IMPORTANT: Save this API key now. It will not be shown again.");
1965
- output.output({
1966
- keyId: result.keyId,
1967
- keyPrefix: result.keyPrefix,
1968
- name: result.name,
1969
- createdAt: result.createdAt,
1970
- expiresAt: result.expiresAt,
1971
- key: result.key
1972
- });
1973
- output.info("\nTo use this key with the CLI:");
1974
- output.info(` mdedit config set apiKey ${result.key}`);
1975
- output.info("\nOr set environment variable:");
1976
- output.info(` export MDEDIT_API_KEY="${result.key}"`);
2564
+ apiKey.command("create").description("Open the web app to create a new API key").option("-n, --name <name>", 'Key name (e.g., "Local Dev", "CI/CD")').option("-d, --description <desc>", "Key description").option("--expires <days>", "Expiration in days (optional)").option("--scopes <scopes>", "Comma-separated least-privilege scopes").action(async () => {
2565
+ throw new Error(
2566
+ "API key creation is no longer supported in the CLI. Create scoped keys in mdedit.ai Settings -> Integrations -> API Keys, then configure the CLI with `mdedit config login --api-key <key>` or MDEDIT_API_KEY."
2567
+ );
1977
2568
  });
1978
2569
  apiKey.command("list").description("List your API keys").option("--full", "Show full API key objects (all fields)").action(async (options) => {
1979
2570
  requireApiKey();
@@ -1986,7 +2577,7 @@ function createApiKeyCommands() {
1986
2577
  }
1987
2578
  if (result.keys.length === 0) {
1988
2579
  output.output([]);
1989
- output.info("No API keys found. Create one with: mdedit apikey create");
2580
+ output.info("No API keys found. Create one in mdedit.ai Settings -> Integrations -> API Keys.");
1990
2581
  return;
1991
2582
  }
1992
2583
  output.output(result.keys.map(presentApiKeyListRow));
@@ -2016,6 +2607,7 @@ function createApiKeyCommands() {
2016
2607
  }
2017
2608
 
2018
2609
  // src/commands/skill.ts
2610
+ init_output();
2019
2611
  import { Command as Command6 } from "commander";
2020
2612
  import { readFileSync as readFileSync2, mkdirSync as mkdirSync2, existsSync as existsSync2, appendFileSync, writeFileSync as writeFileSync2 } from "fs";
2021
2613
  import { dirname, join as join2, resolve } from "path";
@@ -2111,13 +2703,20 @@ function createSkillCommands() {
2111
2703
  }
2112
2704
 
2113
2705
  // src/commands/review.ts
2706
+ init_output();
2114
2707
  import { Command as Command7 } from "commander";
2115
2708
  import {
2116
2709
  openArticleReviewSession
2117
2710
  } from "@mdedit/agent-client";
2711
+ init_api();
2118
2712
  async function withReview(articleId, workspaceId, operation) {
2119
- const apiKey = requireApiKey();
2120
- const review = openArticleReviewSession({ apiKey, workspaceId, articleId, apiUrl: getApiUrlRaw() });
2713
+ requireAuthentication();
2714
+ const review = openArticleReviewSession({
2715
+ credentialProvider: getAgentCredentialProvider(),
2716
+ workspaceId,
2717
+ articleId,
2718
+ apiUrl: getApiUrlRaw()
2719
+ });
2121
2720
  return { mode: "rest", result: await operation(review) };
2122
2721
  }
2123
2722
  function quoteAnchor(options) {
@@ -2210,7 +2809,54 @@ function createSuggestCommand() {
2210
2809
  });
2211
2810
  }
2212
2811
 
2812
+ // src/commands/auth.ts
2813
+ init_output();
2814
+ init_oauth();
2815
+ import { Command as Command8 } from "commander";
2816
+ var defaultRuntime = {
2817
+ login: loginWithOAuth,
2818
+ logout: logoutOAuth,
2819
+ status: oauthStatus
2820
+ };
2821
+ function profileOption(command) {
2822
+ return command.option("--profile <name>", "OAuth profile name");
2823
+ }
2824
+ function createAuthCommands(runtime = defaultRuntime) {
2825
+ const auth = new Command8("auth").description("Manage OAuth sign-in profiles").action(() => auth.help());
2826
+ profileOption(auth.command("login").description("Sign in with browser authorization-code + PKCE").option(
2827
+ "--no-browser",
2828
+ "Print the same browser URL; the browser must run on this callback-capable machine"
2829
+ ).option("--scopes <scopes>", "Comma-separated OAuth scopes")).action(async (options) => {
2830
+ const scopes = options.scopes ? String(options.scopes).split(",").map((scope) => scope.trim()).filter(Boolean) : void 0;
2831
+ const result = await runtime.login({
2832
+ noBrowser: Boolean(options.browser === false),
2833
+ profile: options.profile,
2834
+ ...scopes ? { scopes } : {}
2835
+ });
2836
+ if (!output.isJson()) output.success(`Signed in with OAuth profile ${result.profile}`);
2837
+ output.output(result);
2838
+ });
2839
+ profileOption(auth.command("status").description("Show OAuth status without printing tokens")).action(async (options) => {
2840
+ const result = await runtime.status(options.profile);
2841
+ output.output(result);
2842
+ });
2843
+ 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) => {
2844
+ const result = await runtime.logout({
2845
+ all: Boolean(options.all),
2846
+ profile: options.profile
2847
+ });
2848
+ if (!output.isJson()) {
2849
+ output.success(result.all ? "Logged out every OAuth profile" : `Logged out OAuth profile ${result.profile}`);
2850
+ }
2851
+ output.output(result);
2852
+ });
2853
+ return auth;
2854
+ }
2855
+
2213
2856
  // src/index.ts
2857
+ init_output();
2858
+ init_config();
2859
+ init_api();
2214
2860
  var __filename2 = fileURLToPath2(import.meta.url);
2215
2861
  var __dirname2 = dirname2(__filename2);
2216
2862
  var version = "0.0.0";
@@ -2219,7 +2865,7 @@ try {
2219
2865
  version = packageJson.version || version;
2220
2866
  } catch {
2221
2867
  }
2222
- var program = new Command8();
2868
+ var program = new Command9();
2223
2869
  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
2870
  const opts = typeof thisCommand.optsWithGlobals === "function" ? (
2225
2871
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -2240,6 +2886,7 @@ program.addCommand(createApiKeyCommands());
2240
2886
  program.addCommand(createSkillCommands());
2241
2887
  program.addCommand(createReviewCommands());
2242
2888
  program.addCommand(createSuggestCommand());
2889
+ program.addCommand(createAuthCommands());
2243
2890
  program.command("health").description("Check API health status").action(async () => {
2244
2891
  const base = getApiBaseUrlRoot();
2245
2892
  const response = await fetch(`${base}/health`, { method: "GET" });
@@ -2258,9 +2905,11 @@ program.command("health").description("Check API health status").action(async ()
2258
2905
  });
2259
2906
  program.command("info").description("Display CLI and API information").action(async () => {
2260
2907
  const apiUrl = configManager.get("apiUrl") || process.env.MDEDIT_API_URL || "https://apiv2.mdedit.ai";
2261
- const apiKey = configManager.get("apiKey");
2908
+ const apiKey = process.env.MDEDIT_API_KEY || configManager.getAll().apiKey;
2909
+ const activeProfile2 = configManager.get("oauthProfile") || "default";
2910
+ const oauthConfigured = (configManager.get("oauthProfiles") || []).includes(activeProfile2);
2262
2911
  const workspaceId = configManager.get("workspaceId") || process.env.MDEDIT_WORKSPACE_ID || null;
2263
- const authMethod = apiKey ? "apiKey" : "none";
2912
+ const authMethod = process.env.MDEDIT_API_KEY ? "apiKey" : oauthConfigured ? "oauth" : apiKey ? "apiKey" : "none";
2264
2913
  let health = void 0;
2265
2914
  let apiStatus = "unavailable";
2266
2915
  try {
@@ -2271,7 +2920,7 @@ program.command("info").description("Display CLI and API information").action(as
2271
2920
  apiStatus = "unavailable";
2272
2921
  }
2273
2922
  let authOk = null;
2274
- if (apiKey) {
2923
+ if (authMethod !== "none") {
2275
2924
  try {
2276
2925
  const client = getApiClient();
2277
2926
  await client.workspace.list();
@@ -2296,7 +2945,7 @@ program.command("info").description("Display CLI and API information").action(as
2296
2945
  output.info(`CLI Version: ${version}`);
2297
2946
  output.info(`API URL: ${apiUrl}`);
2298
2947
  if (workspaceId) output.info(`Workspace: ${workspaceId}`);
2299
- output.info(`Auth Method: ${authMethod === "apiKey" ? "API Key" : "None"}`);
2948
+ output.info(`Auth Method: ${authMethod === "apiKey" ? "API Key" : authMethod === "oauth" ? `OAuth (${activeProfile2})` : "None"}`);
2300
2949
  if (apiStatus === "healthy") output.success("API Status: Healthy");
2301
2950
  else output.warning("API Status: Unavailable");
2302
2951
  if (authOk === true) output.success("Auth: OK");
@@ -2349,7 +2998,7 @@ async function main() {
2349
2998
  } else if (err instanceof FetchError2) {
2350
2999
  output.error(`API request failed (${err.status}): ${err.message}`);
2351
3000
  if (err.status === 401) {
2352
- output.info("Hint: set an API key via `mdedit config set apiKey <key>` or pass `--api-key <key>`.");
3001
+ output.info("Hint: run `mdedit auth login`; for headless/CI set MDEDIT_API_KEY or pass `--api-key <key>`.");
2353
3002
  } else if (err.status === 403) {
2354
3003
  if (err.message.includes("publishing:write")) {
2355
3004
  output.info("Hint: publishing requires an API key with publishing:write scope.");