mdedit-cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1503 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { Command as Command7 } from "commander";
5
+ import { readFileSync as readFileSync2 } from "fs";
6
+ import { dirname, join as join2 } from "path";
7
+ import { fileURLToPath } from "url";
8
+
9
+ // ../sdk/dist/index.js
10
+ var _defaultFetchers = null;
11
+ function createFetchers(config) {
12
+ const baseUrlV1 = (config.baseUrlV1 ?? "").replace(/\/$/, "");
13
+ const baseUrlV2 = (config.baseUrlV2 ?? "").replace(/\/$/, "");
14
+ const getAuthHeaders = config.getAuthHeaders;
15
+ const customFetch = async (input, init) => {
16
+ const authHeaders = await getAuthHeaders?.() ?? {};
17
+ return fetch(`${baseUrlV1}${input}`, {
18
+ ...init,
19
+ headers: {
20
+ ...init?.headers,
21
+ ...authHeaders,
22
+ ...init && (init.method === "PUT" || init.method === "POST") && {
23
+ "Content-Type": "application/json"
24
+ }
25
+ }
26
+ });
27
+ };
28
+ const customFetchV22 = async (input, init) => {
29
+ const authHeaders = await getAuthHeaders?.() ?? {};
30
+ return fetch(`${baseUrlV2}${input}`, {
31
+ ...init,
32
+ headers: {
33
+ ...init?.headers,
34
+ ...authHeaders,
35
+ ...init && (init.method === "PUT" || init.method === "POST") && {
36
+ "Content-Type": "application/json"
37
+ }
38
+ }
39
+ });
40
+ };
41
+ return { customFetch, customFetchV2: customFetchV22 };
42
+ }
43
+ function getDefaultFetchers() {
44
+ if (_defaultFetchers) return _defaultFetchers;
45
+ throw new Error(
46
+ "MDEdit API client is not initialized. Call initApiClient(config) at app bootstrap (e.g. pages/_app.jsx) before using API functions."
47
+ );
48
+ }
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
+ const response = await fetchV2(
114
+ `/workspaces/${workspaceId}/articles/${articleRequest.articleId}`,
115
+ {
116
+ method: "PUT",
117
+ body: JSON.stringify(body)
118
+ }
119
+ );
120
+ if (!response.ok) {
121
+ const errorText = await response.text();
122
+ let errorData;
123
+ try {
124
+ errorData = JSON.parse(errorText);
125
+ } catch {
126
+ throw new errors_default(`Error updating article metadata. ${errorText}`, response.status);
127
+ }
128
+ if (errorData.error && errorData.error.type === "QUOTA_EXCEEDED") {
129
+ const quotaError = new errors_default(
130
+ `Error updating article metadata. ${errorText}`,
131
+ response.status
132
+ );
133
+ quotaError.error = errorData.error;
134
+ throw quotaError;
135
+ }
136
+ throw new errors_default(`Error updating article metadata. ${errorText}`, response.status);
137
+ }
138
+ return response.json();
139
+ };
140
+ var getArticles = async (workspaceId, fetchers) => {
141
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
142
+ const response = await fetchV2(`/workspaces/${workspaceId}/articles`);
143
+ if (!response.ok) {
144
+ const errorText = await response.text();
145
+ const looksLikeWorkspaceAccessDenied = response.status === 403 && errorText.toLowerCase().includes("access denied to workspace");
146
+ if (looksLikeWorkspaceAccessDenied) {
147
+ throw new errors_default(`Error fetching articles. ${errorText}`, response.status);
148
+ }
149
+ throw new errors_default(`Error fetching articles. ${errorText}`, response.status);
150
+ }
151
+ return response.json();
152
+ };
153
+ var getArticlesByFolder = async (workspaceId, folderId, fetchers) => {
154
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
155
+ const qs = `?folderId=${encodeURIComponent(folderId)}`;
156
+ const response = await fetchV2(`/workspaces/${workspaceId}/articles${qs}`);
157
+ if (!response.ok) {
158
+ const errorText = await response.text();
159
+ throw new errors_default(`Error fetching articles. ${errorText}`, response.status);
160
+ }
161
+ return response.json();
162
+ };
163
+ var getArticle = async (workspaceId, articleId, fetchers) => {
164
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
165
+ const response = await fetchV2(
166
+ `/workspaces/${workspaceId}/articles/${articleId}`
167
+ );
168
+ if (!response.ok) {
169
+ throw new errors_default(
170
+ `Error fetching article. ${await response.text()}`,
171
+ response.status
172
+ );
173
+ }
174
+ return response.json();
175
+ };
176
+ var deleteArticle = async (workspaceId, articleId, fetchers) => {
177
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
178
+ const response = await fetchV2(
179
+ `/workspaces/${workspaceId}/articles/${articleId}`,
180
+ { method: "DELETE" }
181
+ );
182
+ if (!response.ok) {
183
+ throw new errors_default(
184
+ `Error deleting article. ${await response.text()}`,
185
+ response.status
186
+ );
187
+ }
188
+ return true;
189
+ };
190
+ var exportArticleZip = async (workspaceId, articleId, fetchers) => {
191
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
192
+ const response = await fetchV2(
193
+ `/workspaces/${workspaceId}/articles/${articleId}/export/zip`,
194
+ { method: "GET" }
195
+ );
196
+ if (!response.ok) {
197
+ throw new errors_default(
198
+ `Failed to export article ZIP. ${await response.text()}`,
199
+ response.status
200
+ );
201
+ }
202
+ return response.blob();
203
+ };
204
+ var saveArticleContent = async (workspaceId, articleId, content, fetchers) => {
205
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
206
+ const urlResponse = await fetchV2(
207
+ `/workspaces/${workspaceId}/articles/${articleId}/content-upload-url`,
208
+ { method: "POST" }
209
+ );
210
+ if (!urlResponse.ok) {
211
+ throw new errors_default(
212
+ `Error getting upload URL. ${await urlResponse.text()}`,
213
+ urlResponse.status
214
+ );
215
+ }
216
+ const { uploadUrl } = await urlResponse.json();
217
+ if (!uploadUrl) {
218
+ throw new errors_default("No upload URL returned", 500);
219
+ }
220
+ const uploadResponse = await fetch(uploadUrl, {
221
+ method: "PUT",
222
+ headers: { "Content-Type": "text/markdown" },
223
+ body: content
224
+ });
225
+ if (!uploadResponse.ok) {
226
+ throw new errors_default(
227
+ `Error uploading content to S3. ${await uploadResponse.text()}`,
228
+ uploadResponse.status
229
+ );
230
+ }
231
+ };
232
+ var getWorkspaces = async (fetchers) => {
233
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
234
+ const response = await fetchV2("/workspaces");
235
+ if (!response.ok) {
236
+ throw new errors_default(
237
+ `Error fetching workspaces. ${await response.text()}`,
238
+ response.status
239
+ );
240
+ }
241
+ return response.json();
242
+ };
243
+ var createWorkspace = async (request, fetchers) => {
244
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
245
+ const response = await fetchV2("/workspaces", {
246
+ method: "POST",
247
+ body: JSON.stringify(request)
248
+ });
249
+ if (!response.ok) {
250
+ throw new errors_default(
251
+ `Error creating workspace. ${await response.text()}`,
252
+ response.status
253
+ );
254
+ }
255
+ return response.json();
256
+ };
257
+ var updateWorkspace = async (workspaceId, request, fetchers) => {
258
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
259
+ const response = await fetchV2(`/workspaces/${workspaceId}`, {
260
+ method: "PUT",
261
+ body: JSON.stringify(request)
262
+ });
263
+ if (!response.ok) {
264
+ throw new errors_default(
265
+ `Error updating workspace. ${await response.text()}`,
266
+ response.status
267
+ );
268
+ }
269
+ return response.json();
270
+ };
271
+ var deleteWorkspace = async (workspaceId, fetchers) => {
272
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
273
+ const response = await fetchV2(`/workspaces/${workspaceId}`, {
274
+ method: "DELETE"
275
+ });
276
+ if (!response.ok) {
277
+ throw new errors_default(
278
+ `Error deleting workspace. ${await response.text()}`,
279
+ response.status
280
+ );
281
+ }
282
+ try {
283
+ return await response.json();
284
+ } catch {
285
+ return;
286
+ }
287
+ };
288
+ var getWorkspace = async (workspaceId, fetchers) => {
289
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
290
+ const response = await fetchV2(`/workspaces/${workspaceId}`);
291
+ if (!response.ok) {
292
+ throw new errors_default(
293
+ `Error fetching workspace. ${await response.text()}`,
294
+ response.status
295
+ );
296
+ }
297
+ return response.json();
298
+ };
299
+ var normalizeTimestampMs = (value) => {
300
+ const n = typeof value === "number" ? value : Number(value);
301
+ if (!Number.isFinite(n)) return Date.now();
302
+ return n < 1e12 ? n * 1e3 : n;
303
+ };
304
+ var normalizeFolder = (raw) => {
305
+ const id = raw?.id ?? raw?.folderId;
306
+ const parentId = raw?.parentId ?? raw?.parentFolderId ?? null;
307
+ const workspaceId = raw?.workspaceId;
308
+ const name = raw?.name ?? "";
309
+ if (!id || !workspaceId) {
310
+ throw new Error("Invalid folder payload from API: missing id or workspaceId");
311
+ }
312
+ if (!name || typeof name !== "string" || name.trim().length === 0) {
313
+ throw new Error("Invalid folder payload from API: name cannot be empty");
314
+ }
315
+ if (name.length > 255) {
316
+ throw new Error("Invalid folder payload from API: name exceeds 255 characters");
317
+ }
318
+ return {
319
+ id,
320
+ name: name.trim(),
321
+ parentId: parentId ?? null,
322
+ workspaceId,
323
+ createdAt: normalizeTimestampMs(raw?.createdAt),
324
+ updatedAt: normalizeTimestampMs(raw?.updatedAt),
325
+ ...raw?.deletedAt ? { deletedAt: normalizeTimestampMs(raw?.deletedAt) } : {},
326
+ deletedBy: raw?.deletedBy,
327
+ color: raw?.color,
328
+ icon: raw?.icon,
329
+ order: raw?.order
330
+ };
331
+ };
332
+ var createFolder = async (workspaceId, folderRequest, fetchers) => {
333
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
334
+ const response = await fetchV2(`/workspaces/${workspaceId}/folders`, {
335
+ method: "POST",
336
+ body: JSON.stringify({
337
+ folderId: folderRequest.id,
338
+ id: folderRequest.id,
339
+ name: folderRequest.name,
340
+ parentId: folderRequest.parentId === null ? null : folderRequest.parentId ?? void 0
341
+ })
342
+ });
343
+ if (!response.ok) {
344
+ const errorText = await response.text();
345
+ throw new errors_default(`Error creating folder. ${errorText}`, response.status);
346
+ }
347
+ return normalizeFolder(await response.json());
348
+ };
349
+ var updateFolder = async (workspaceId, folderId, folderRequest, fetchers) => {
350
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
351
+ const response = await fetchV2(`/workspaces/${workspaceId}/folders/${folderId}`, {
352
+ method: "PUT",
353
+ body: JSON.stringify({
354
+ name: folderRequest.name,
355
+ parentId: folderRequest.parentId === null ? null : folderRequest.parentId ?? void 0
356
+ })
357
+ });
358
+ if (!response.ok) {
359
+ const errorText = await response.text();
360
+ throw new errors_default(`Error updating folder. ${errorText}`, response.status);
361
+ }
362
+ const result = await response.json();
363
+ try {
364
+ return normalizeFolder(result);
365
+ } catch {
366
+ return normalizeFolder({
367
+ ...folderRequest,
368
+ id: folderId,
369
+ workspaceId,
370
+ parentId: folderRequest.parentId ?? null
371
+ });
372
+ }
373
+ };
374
+ var getFolders = async (workspaceId, options, fetchers) => {
375
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
376
+ const qs = options?.includeDeleted ? "?includeDeleted=true" : "";
377
+ const response = await fetchV2(`/workspaces/${workspaceId}/folders${qs}`);
378
+ if (!response.ok) {
379
+ const errorText = await response.text();
380
+ throw new errors_default(`Error fetching folders. ${errorText}`, response.status);
381
+ }
382
+ const folders = await response.json();
383
+ return Array.isArray(folders) ? folders.map(normalizeFolder) : [];
384
+ };
385
+ var getFolder = async (workspaceId, folderId, fetchers) => {
386
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
387
+ const response = await fetchV2(`/workspaces/${workspaceId}/folders/${folderId}`);
388
+ if (!response.ok) {
389
+ throw new errors_default(
390
+ `Error fetching folder. ${await response.text()}`,
391
+ response.status
392
+ );
393
+ }
394
+ return normalizeFolder(await response.json());
395
+ };
396
+ var deleteFolder = async (workspaceId, folderId, fetchers) => {
397
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
398
+ const response = await fetchV2(`/workspaces/${workspaceId}/folders/${folderId}`, {
399
+ method: "DELETE"
400
+ });
401
+ if (!response.ok) {
402
+ const errorText = await response.text();
403
+ throw new errors_default(`Error deleting folder. ${errorText}`, response.status);
404
+ }
405
+ return true;
406
+ };
407
+ var listTemplates = async (workspaceId, fetchers) => {
408
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
409
+ const response = await fetchV2(`/workspaces/${workspaceId}/templates`, {
410
+ method: "GET"
411
+ });
412
+ if (!response.ok) {
413
+ throw new Error(`Failed to fetch templates: ${response.statusText}`);
414
+ }
415
+ return response.json();
416
+ };
417
+ var getTemplateById = async (templateId, fetchers) => {
418
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
419
+ const response = await fetchV2(`/templates/${templateId}`, { method: "GET" });
420
+ if (!response.ok) {
421
+ throw new Error(`Failed to fetch template: ${response.statusText}`);
422
+ }
423
+ return response.json();
424
+ };
425
+ var getTemplateBySlug = async (slug, fetchers) => {
426
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
427
+ const response = await fetchV2(`/templates/slug/${encodeURIComponent(slug)}`, { method: "GET" });
428
+ if (!response.ok) {
429
+ throw new Error(`Failed to fetch template by slug: ${response.statusText}`);
430
+ }
431
+ return response.json();
432
+ };
433
+ var saveArticleAsTemplate = async (workspaceId, articleId, templateData, fetchers) => {
434
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
435
+ const response = await fetchV2(
436
+ `/workspaces/${workspaceId}/articles/${articleId}/save-as-template`,
437
+ { method: "POST", body: JSON.stringify(templateData) }
438
+ );
439
+ if (!response.ok) {
440
+ throw new Error(`Failed to save template: ${response.statusText}`);
441
+ }
442
+ return response.json();
443
+ };
444
+ var updateTemplate = async (templateId, updates, fetchers) => {
445
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
446
+ const response = await fetchV2(`/templates/${templateId}`, {
447
+ method: "PUT",
448
+ body: JSON.stringify(updates)
449
+ });
450
+ if (!response.ok) {
451
+ throw new Error(`Failed to update template: ${response.statusText}`);
452
+ }
453
+ return response.json();
454
+ };
455
+ var deleteTemplate = async (templateId, fetchers) => {
456
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
457
+ const response = await fetchV2(`/templates/${templateId}`, { method: "DELETE" });
458
+ if (!response.ok) {
459
+ throw new Error(`Failed to delete template: ${response.statusText}`);
460
+ }
461
+ };
462
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
463
+ var isRetriableStatus = (status) => status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
464
+ var withRetries = async (fn, maxAttempts = 3) => {
465
+ let lastError;
466
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
467
+ try {
468
+ const response = await fn();
469
+ if (response.ok) return response;
470
+ if (attempt < maxAttempts && isRetriableStatus(response.status)) {
471
+ const backoffMs = 250 * Math.pow(2, attempt - 1) + Math.floor(Math.random() * 150);
472
+ await sleep(backoffMs);
473
+ continue;
474
+ }
475
+ return response;
476
+ } catch (e) {
477
+ lastError = e;
478
+ if (attempt < maxAttempts) {
479
+ const backoffMs = 250 * Math.pow(2, attempt - 1) + Math.floor(Math.random() * 150);
480
+ await sleep(backoffMs);
481
+ continue;
482
+ }
483
+ throw lastError;
484
+ }
485
+ }
486
+ throw lastError;
487
+ };
488
+ var listApiKeys = async (fetchers) => {
489
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
490
+ const response = await withRetries(() => fetchV2("/api-keys", { method: "GET" }), 3);
491
+ if (!response.ok) {
492
+ throw new Error(`Failed to list API keys: ${response.status} ${response.statusText}`);
493
+ }
494
+ return response.json();
495
+ };
496
+ var createApiKey = async (request, fetchers) => {
497
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
498
+ const response = await withRetries(
499
+ () => fetchV2("/api-keys", {
500
+ method: "POST",
501
+ body: JSON.stringify(request)
502
+ }),
503
+ 3
504
+ );
505
+ if (!response.ok) {
506
+ throw new Error(`Failed to create API key: ${response.status} ${response.statusText}`);
507
+ }
508
+ return response.json();
509
+ };
510
+ var revokeApiKey = async (keyId, fetchers) => {
511
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
512
+ const response = await withRetries(
513
+ () => fetchV2(`/api-keys/${encodeURIComponent(keyId)}`, {
514
+ method: "DELETE"
515
+ }),
516
+ 3
517
+ );
518
+ if (!response.ok) {
519
+ throw new Error(`Failed to revoke API key: ${response.status} ${response.statusText}`);
520
+ }
521
+ return response.json();
522
+ };
523
+ var FetchError2 = class extends Error {
524
+ status;
525
+ data;
526
+ constructor(message, status, data) {
527
+ super(message);
528
+ this.name = "FetchError";
529
+ this.status = status;
530
+ this.data = data;
531
+ }
532
+ };
533
+ function coerceToFetchError(err) {
534
+ const anyErr = err;
535
+ const status = typeof anyErr?.status === "number" ? anyErr.status : 500;
536
+ const message = typeof anyErr?.message === "string" && anyErr.message.trim() ? anyErr.message : "Request failed";
537
+ return new FetchError2(message, status, anyErr?.data ?? anyErr?.error);
538
+ }
539
+ async function withFetchError(fn) {
540
+ try {
541
+ return await fn();
542
+ } catch (err) {
543
+ throw coerceToFetchError(err);
544
+ }
545
+ }
546
+ function createSdkClient(config) {
547
+ const fetchers = createFetchers(config);
548
+ return {
549
+ apiKeys: {
550
+ list: () => withFetchError(() => listApiKeys(fetchers)),
551
+ create: (req) => withFetchError(() => createApiKey(req, fetchers)),
552
+ revoke: (keyId) => withFetchError(() => revokeApiKey(keyId, fetchers))
553
+ },
554
+ workspace: {
555
+ list: () => withFetchError(() => getWorkspaces(fetchers)),
556
+ get: (workspaceId) => withFetchError(() => getWorkspace(workspaceId, fetchers)),
557
+ create: (req) => withFetchError(() => createWorkspace(req, fetchers)),
558
+ update: (workspaceId, req) => withFetchError(() => updateWorkspace(workspaceId, req, fetchers)),
559
+ delete: async (workspaceId) => {
560
+ await withFetchError(() => deleteWorkspace(workspaceId, fetchers));
561
+ }
562
+ },
563
+ folder: {
564
+ list: (workspaceId, opts) => withFetchError(() => getFolders(workspaceId, opts, fetchers)),
565
+ get: (workspaceId, folderId) => withFetchError(() => getFolder(workspaceId, folderId, fetchers)),
566
+ create: (workspaceId, req) => withFetchError(() => createFolder(workspaceId, req, fetchers)),
567
+ update: (workspaceId, folderId, req) => withFetchError(() => updateFolder(workspaceId, folderId, req, fetchers)),
568
+ delete: async (workspaceId, folderId) => {
569
+ await withFetchError(() => deleteFolder(workspaceId, folderId, fetchers));
570
+ }
571
+ },
572
+ article: {
573
+ list: async (workspaceId) => await withFetchError(() => getArticles(workspaceId, fetchers)) ?? [],
574
+ listByFolder: async (workspaceId, folderId) => await withFetchError(() => getArticlesByFolder(workspaceId, folderId, fetchers)) ?? [],
575
+ get: async (workspaceId, articleId) => await withFetchError(() => getArticle(workspaceId, articleId, fetchers)),
576
+ create: (workspaceId, req) => withFetchError(() => createArticle(workspaceId, req, fetchers)),
577
+ update: (workspaceId, req) => withFetchError(() => updateArticle(workspaceId, req, fetchers)),
578
+ delete: async (workspaceId, articleId) => {
579
+ await withFetchError(() => deleteArticle(workspaceId, articleId, fetchers));
580
+ },
581
+ saveContent: (workspaceId, articleId, content) => withFetchError(() => saveArticleContent(workspaceId, articleId, content, fetchers)),
582
+ exportZip: (workspaceId, articleId) => withFetchError(() => exportArticleZip(workspaceId, articleId, fetchers))
583
+ },
584
+ template: {
585
+ list: (workspaceId) => withFetchError(() => listTemplates(workspaceId, fetchers)),
586
+ get: (templateId) => withFetchError(() => getTemplateById(templateId, fetchers)),
587
+ getBySlug: (slug) => withFetchError(() => getTemplateBySlug(slug, fetchers)),
588
+ createFromArticle: (workspaceId, articleId, req) => withFetchError(() => saveArticleAsTemplate(workspaceId, articleId, req, fetchers)),
589
+ update: (templateId, updates) => withFetchError(() => updateTemplate(templateId, updates, fetchers)),
590
+ delete: (templateId) => withFetchError(() => deleteTemplate(templateId, fetchers))
591
+ }
592
+ };
593
+ }
594
+
595
+ // src/commands/article.ts
596
+ import { Command } from "commander";
597
+ import inquirer from "inquirer";
598
+ import { v4 as uuidv4 } from "uuid";
599
+ import { readFile, writeFile } from "fs/promises";
600
+
601
+ // src/utils/output.ts
602
+ import chalk from "chalk";
603
+
604
+ // src/utils/config.ts
605
+ import { homedir } from "os";
606
+ import { join } from "path";
607
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
608
+ var CONFIG_DIR = process.env.MDEDIT_CONFIG_DIR || join(homedir(), ".mdedit-cli");
609
+ var CONFIG_FILE = process.env.MDEDIT_CONFIG_FILE || join(CONFIG_DIR, "config.json");
610
+ var ConfigManager = class {
611
+ config = {};
612
+ constructor() {
613
+ this.load();
614
+ }
615
+ load() {
616
+ try {
617
+ if (existsSync(CONFIG_FILE)) {
618
+ const data = readFileSync(CONFIG_FILE, "utf8");
619
+ this.config = JSON.parse(data);
620
+ }
621
+ } catch {
622
+ }
623
+ }
624
+ save() {
625
+ try {
626
+ if (!existsSync(CONFIG_DIR)) {
627
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
628
+ }
629
+ writeFileSync(CONFIG_FILE, JSON.stringify(this.config, null, 2), { mode: 384 });
630
+ try {
631
+ chmodSync(CONFIG_DIR, 448);
632
+ } catch {
633
+ }
634
+ try {
635
+ chmodSync(CONFIG_FILE, 384);
636
+ } catch {
637
+ }
638
+ } catch (error) {
639
+ console.error("Failed to save config:", error.message);
640
+ }
641
+ }
642
+ get(key) {
643
+ const envMap = {
644
+ apiUrl: "MDEDIT_API_URL",
645
+ apiKey: "MDEDIT_API_KEY",
646
+ userId: "MDEDIT_USER_ID",
647
+ workspaceId: "MDEDIT_WORKSPACE_ID",
648
+ outputFormat: "MDEDIT_OUTPUT_FORMAT"
649
+ };
650
+ const envKey = envMap[key];
651
+ if (envKey && process.env[envKey] !== void 0) {
652
+ return process.env[envKey];
653
+ }
654
+ return this.config[key];
655
+ }
656
+ set(key, value) {
657
+ this.config[key] = value;
658
+ this.save();
659
+ }
660
+ getAll() {
661
+ return { ...this.config };
662
+ }
663
+ clear() {
664
+ this.config = {};
665
+ this.save();
666
+ }
667
+ };
668
+ var configManager = new ConfigManager();
669
+
670
+ // src/utils/output.ts
671
+ var OutputFormatter = class {
672
+ format;
673
+ constructor() {
674
+ this.format = configManager.get("outputFormat") || "plain";
675
+ }
676
+ setFormat(format) {
677
+ this.format = format;
678
+ }
679
+ success(message) {
680
+ console.log(chalk.green("\u2713"), message);
681
+ }
682
+ error(message) {
683
+ const text = this.stringify(message);
684
+ console.error(chalk.red("\u2717"), text);
685
+ }
686
+ warning(message) {
687
+ const text = this.stringify(message);
688
+ console.warn(chalk.yellow("\u26A0"), text);
689
+ }
690
+ info(message) {
691
+ const text = this.stringify(message);
692
+ console.log(chalk.blue("\u2139"), text);
693
+ }
694
+ output(data) {
695
+ if (this.format === "json") {
696
+ console.log(JSON.stringify(data, null, 2));
697
+ return;
698
+ }
699
+ if (this.format === "table" && Array.isArray(data)) {
700
+ console.table(data);
701
+ return;
702
+ }
703
+ if (this.format === "plain") {
704
+ if (typeof data === "object" && data !== null) {
705
+ this.printObject(data);
706
+ } else {
707
+ console.log(data);
708
+ }
709
+ return;
710
+ }
711
+ console.log(data);
712
+ }
713
+ header(text) {
714
+ console.log(`
715
+ ${chalk.bold.underline(text)}
716
+ `);
717
+ }
718
+ printObject(obj, indent = 0) {
719
+ if (Array.isArray(obj)) {
720
+ obj.forEach((item, index) => {
721
+ console.log(" ".repeat(indent) + chalk.cyan(`[${index}]`));
722
+ this.printObject(item, indent + 1);
723
+ });
724
+ return;
725
+ }
726
+ if (typeof obj === "object" && obj !== null) {
727
+ Object.entries(obj).forEach(([key, value]) => {
728
+ if (typeof value === "object" && value !== null) {
729
+ console.log(" ".repeat(indent) + chalk.cyan(key) + ":");
730
+ this.printObject(value, indent + 1);
731
+ } else {
732
+ console.log(" ".repeat(indent) + chalk.cyan(key) + ":", value);
733
+ }
734
+ });
735
+ return;
736
+ }
737
+ console.log(" ".repeat(indent) + String(obj));
738
+ }
739
+ stringify(value) {
740
+ if (typeof value === "string") return value;
741
+ if (value instanceof Error) return value.message || String(value);
742
+ try {
743
+ return JSON.stringify(value);
744
+ } catch {
745
+ return String(value);
746
+ }
747
+ }
748
+ };
749
+ var output = new OutputFormatter();
750
+
751
+ // src/utils/context.ts
752
+ function resolveWorkspaceId(cliWorkspaceId) {
753
+ return cliWorkspaceId || configManager.get("workspaceId") || process.env.MDEDIT_WORKSPACE_ID;
754
+ }
755
+ function requireWorkspaceId(cliWorkspaceId) {
756
+ const workspaceId = resolveWorkspaceId(cliWorkspaceId);
757
+ if (!workspaceId) {
758
+ throw new Error(
759
+ "workspaceId is required. Pass --workspace <id> or set a default with: mdedit config set workspaceId <id>"
760
+ );
761
+ }
762
+ return workspaceId;
763
+ }
764
+
765
+ // src/utils/api.ts
766
+ function trimTrailingSlashes(value) {
767
+ return value.replace(/\/+$/, "");
768
+ }
769
+ function getApiUrlRaw() {
770
+ const raw = configManager.get("apiUrl") || process.env.MDEDIT_API_URL || "https://apiv2.mdedit.ai";
771
+ return String(raw).trim();
772
+ }
773
+ function getApiBaseUrlRoot() {
774
+ const raw = trimTrailingSlashes(getApiUrlRaw());
775
+ if (raw.endsWith("/api/v2")) return raw.slice(0, -7);
776
+ if (raw.endsWith("/api")) return raw.slice(0, -4);
777
+ return raw;
778
+ }
779
+ function getApiBaseUrlV2() {
780
+ const raw = trimTrailingSlashes(getApiUrlRaw());
781
+ if (raw.endsWith("/api") || raw.endsWith("/api/v2")) return raw;
782
+ return `${raw}/api`;
783
+ }
784
+ function requireApiKey() {
785
+ const apiKey = configManager.get("apiKey") || process.env.MDEDIT_API_KEY;
786
+ if (!apiKey) {
787
+ throw new Error(
788
+ "No authentication configured. Set an API key with: mdedit config set apiKey <key> (or pass --api-key / set MDEDIT_API_KEY)."
789
+ );
790
+ }
791
+ return String(apiKey);
792
+ }
793
+ var _cachedKey = null;
794
+ var _cachedClient = null;
795
+ function getApiClient() {
796
+ const baseUrlV2 = getApiBaseUrlV2();
797
+ const apiKey = configManager.get("apiKey") || process.env.MDEDIT_API_KEY || "";
798
+ const cacheKey = `${baseUrlV2}::${apiKey}`;
799
+ if (_cachedClient && _cachedKey === cacheKey) return _cachedClient;
800
+ const client = createSdkClient({
801
+ baseUrlV2,
802
+ getAuthHeaders: async () => {
803
+ const key = configManager.get("apiKey") || process.env.MDEDIT_API_KEY;
804
+ const headers = {};
805
+ if (key) headers["x-api-key"] = String(key);
806
+ return headers;
807
+ }
808
+ });
809
+ _cachedKey = cacheKey;
810
+ _cachedClient = client;
811
+ return client;
812
+ }
813
+
814
+ // src/commands/article.ts
815
+ async function readContentFromFile(filePath) {
816
+ if (filePath === "-") {
817
+ return new Promise((resolve, reject) => {
818
+ const chunks = [];
819
+ process.stdin.on("data", (d) => chunks.push(Buffer.isBuffer(d) ? d : Buffer.from(d)));
820
+ process.stdin.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8")));
821
+ process.stdin.on("error", reject);
822
+ });
823
+ }
824
+ return readFile(filePath, "utf-8");
825
+ }
826
+ async function writeBlobToFile(blob, filePath) {
827
+ const buffer = Buffer.from(await blob.arrayBuffer());
828
+ await writeFile(filePath, buffer);
829
+ }
830
+ function createArticleCommands() {
831
+ const article = new Command("article").description("Manage articles").action(() => article.help());
832
+ article.command("list").description("List all articles").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-f, --folder <folderId>", "Filter by folder ID").option("-l, --limit <number>", "Limit number of results (client-side)", "50").option("-o, --offset <number>", "Offset for pagination (client-side)", "0").action(async (options) => {
833
+ requireApiKey();
834
+ const client = getApiClient();
835
+ const workspaceId = requireWorkspaceId(options.workspace);
836
+ const articles = options.folder ? await client.article.listByFolder(workspaceId, options.folder) : await client.article.list(workspaceId);
837
+ output.header("Articles");
838
+ const offset = Number(options.offset) || 0;
839
+ const limit = Number(options.limit) || articles.length;
840
+ output.output(articles.slice(offset, offset + limit));
841
+ });
842
+ article.command("get <articleId>").description("Get article details").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-o, --output <file>", "Save article content (markdown) to this file path; use - for stdout").option("--content-only", "Print only the article markdown content to stdout (useful for piping / AI agents)").action(async (articleId, options) => {
843
+ requireApiKey();
844
+ const client = getApiClient();
845
+ const workspaceId = requireWorkspaceId(options.workspace);
846
+ const result = await client.article.get(workspaceId, articleId);
847
+ if (options.contentOnly) {
848
+ process.stdout.write(result?.content ?? "");
849
+ return;
850
+ }
851
+ if (options.output) {
852
+ const content = result?.content ?? "";
853
+ if (options.output === "-") {
854
+ process.stdout.write(content);
855
+ } else {
856
+ await writeFile(options.output, content, "utf-8");
857
+ output.success(`Article content saved to ${options.output}`);
858
+ }
859
+ return;
860
+ }
861
+ output.header(`Article: ${articleId}`);
862
+ output.output(result);
863
+ });
864
+ 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").action(async (options) => {
865
+ requireApiKey();
866
+ const client = getApiClient();
867
+ const workspaceId = requireWorkspaceId(options.workspace);
868
+ if (options.content !== void 0 && options.file !== void 0) {
869
+ throw new Error("--content and --file are mutually exclusive. Provide only one.");
870
+ }
871
+ let title = options.title;
872
+ if (!title) {
873
+ const answers = await inquirer.prompt([
874
+ {
875
+ type: "input",
876
+ name: "title",
877
+ message: "Article title:",
878
+ validate: (input) => input.length > 0 || "Title is required"
879
+ }
880
+ ]);
881
+ title = String(answers.title);
882
+ }
883
+ const articleId = options.id || uuidv4();
884
+ const created = await client.article.create(workspaceId, {
885
+ articleId,
886
+ title: String(title),
887
+ folderId: options.folder ?? null,
888
+ collaborative: Boolean(options.collaborative)
889
+ });
890
+ output.success("Article created successfully");
891
+ output.output(created);
892
+ let contentText = null;
893
+ if (options.content !== void 0) contentText = options.content;
894
+ else if (options.file) contentText = await readContentFromFile(options.file);
895
+ if (contentText !== null) {
896
+ await client.article.saveContent(workspaceId, articleId, contentText);
897
+ output.success("Article content uploaded");
898
+ }
899
+ });
900
+ article.command("update <articleId>").description("Update an article").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-t, --title <title>", "New title").option("--archive", "Archive the article").option("--pin", "Pin the article").option("--file <path>", "Update article content from a file (use - for stdin)").option("--content <text>", "Update article content as an inline string").action(async (articleId, options) => {
901
+ requireApiKey();
902
+ const client = getApiClient();
903
+ const workspaceId = requireWorkspaceId(options.workspace);
904
+ if (options.content !== void 0 && options.file !== void 0) {
905
+ throw new Error("--content and --file are mutually exclusive. Provide only one.");
906
+ }
907
+ const body = {};
908
+ if (options.title) body.title = options.title;
909
+ if (options.archive) body.isArchived = true;
910
+ if (options.pin) body.isPinned = true;
911
+ if (Object.keys(body).length > 0) {
912
+ const result = await client.article.update(workspaceId, { articleId, ...body });
913
+ output.success("Article updated successfully");
914
+ output.output(result);
915
+ }
916
+ let contentText = null;
917
+ if (options.content !== void 0) contentText = options.content;
918
+ else if (options.file) contentText = await readContentFromFile(options.file);
919
+ if (contentText !== null) {
920
+ await client.article.saveContent(workspaceId, articleId, contentText);
921
+ output.success("Article content updated");
922
+ }
923
+ if (Object.keys(body).length === 0 && contentText === null) {
924
+ output.warning("No changes provided. Use --title, --archive, --pin, --file, or --content.");
925
+ }
926
+ });
927
+ article.command("delete <articleId>").description("Delete an article").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-y, --yes", "Skip confirmation").action(async (articleId, options) => {
928
+ requireApiKey();
929
+ const client = getApiClient();
930
+ const workspaceId = requireWorkspaceId(options.workspace);
931
+ if (!options.yes) {
932
+ const { confirm } = await inquirer.prompt([
933
+ {
934
+ type: "confirm",
935
+ name: "confirm",
936
+ message: `Are you sure you want to delete article ${articleId}?`,
937
+ default: false
938
+ }
939
+ ]);
940
+ if (!confirm) {
941
+ output.info("Delete cancelled");
942
+ return;
943
+ }
944
+ }
945
+ await client.article.delete(workspaceId, articleId);
946
+ output.success("Article deleted successfully");
947
+ });
948
+ article.command("export <articleId>").description("Export article as ZIP").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-o, --output <path>", "Output file path", "./article.zip").action(async (articleId, options) => {
949
+ requireApiKey();
950
+ const client = getApiClient();
951
+ const workspaceId = requireWorkspaceId(options.workspace);
952
+ output.info(`Exporting article ${articleId}...`);
953
+ const zipBlob = await client.article.exportZip(workspaceId, articleId);
954
+ await writeBlobToFile(zipBlob, options.output);
955
+ output.success(`Exported to ${options.output}`);
956
+ });
957
+ return article;
958
+ }
959
+
960
+ // src/commands/workspace.ts
961
+ import { Command as Command2 } from "commander";
962
+ import inquirer2 from "inquirer";
963
+ function createWorkspaceCommands() {
964
+ const workspace = new Command2("workspace").description("Manage workspaces").action(() => workspace.help());
965
+ workspace.command("list").description("List all workspaces").action(async () => {
966
+ requireApiKey();
967
+ const client = getApiClient();
968
+ const workspaces = await client.workspace.list();
969
+ output.header("Workspaces");
970
+ output.output(workspaces);
971
+ });
972
+ workspace.command("get <workspaceId>").description("Get workspace details").action(async (workspaceId) => {
973
+ requireApiKey();
974
+ const client = getApiClient();
975
+ const result = await client.workspace.get(workspaceId);
976
+ output.header(`Workspace: ${workspaceId}`);
977
+ output.output(result);
978
+ });
979
+ workspace.command("create").description("Create a new workspace").option("-n, --name <name>", "Workspace name").action(async (options) => {
980
+ requireApiKey();
981
+ const client = getApiClient();
982
+ let name = options.name;
983
+ if (!name) {
984
+ const answers = await inquirer2.prompt([
985
+ {
986
+ type: "input",
987
+ name: "name",
988
+ message: "Workspace name:",
989
+ validate: (input) => input.length > 0 || "Name is required"
990
+ }
991
+ ]);
992
+ name = String(answers.name);
993
+ }
994
+ const result = await client.workspace.create({ name: String(name) });
995
+ output.success("Workspace created successfully");
996
+ output.output(result);
997
+ });
998
+ workspace.command("update <workspaceId>").description("Update a workspace").option("-n, --name <name>", "New name").action(async (workspaceId, options) => {
999
+ requireApiKey();
1000
+ const client = getApiClient();
1001
+ if (!options.name) {
1002
+ output.warning("No changes provided. Use --name.");
1003
+ return;
1004
+ }
1005
+ const result = await client.workspace.update(workspaceId, { name: options.name });
1006
+ output.success("Workspace updated successfully");
1007
+ output.output(result);
1008
+ });
1009
+ workspace.command("delete <workspaceId>").description("Delete a workspace").option("-y, --yes", "Skip confirmation").action(async (workspaceId, options) => {
1010
+ requireApiKey();
1011
+ const client = getApiClient();
1012
+ if (!options.yes) {
1013
+ const { confirm } = await inquirer2.prompt([
1014
+ {
1015
+ type: "confirm",
1016
+ name: "confirm",
1017
+ message: `Are you sure you want to delete workspace ${workspaceId}?`,
1018
+ default: false
1019
+ }
1020
+ ]);
1021
+ if (!confirm) {
1022
+ output.info("Delete cancelled");
1023
+ return;
1024
+ }
1025
+ }
1026
+ await client.workspace.delete(workspaceId);
1027
+ output.success("Workspace deleted successfully");
1028
+ });
1029
+ return workspace;
1030
+ }
1031
+
1032
+ // src/commands/folder.ts
1033
+ import { Command as Command3 } from "commander";
1034
+ import inquirer3 from "inquirer";
1035
+ import { v4 as uuidv42 } from "uuid";
1036
+ function createFolderCommands() {
1037
+ const folder = new Command3("folder").description("Manage folders").action(() => folder.help());
1038
+ folder.command("list").description("List all folders").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("--include-deleted", "Include deleted/tombstoned folders").action(async (options) => {
1039
+ requireApiKey();
1040
+ const client = getApiClient();
1041
+ const workspaceId = requireWorkspaceId(options.workspace);
1042
+ const folders = await client.folder.list(workspaceId, { includeDeleted: Boolean(options.includeDeleted) });
1043
+ output.header("Folders");
1044
+ output.output(folders);
1045
+ });
1046
+ folder.command("get <folderId>").description("Get folder details").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").action(async (folderId, options) => {
1047
+ requireApiKey();
1048
+ const client = getApiClient();
1049
+ const workspaceId = requireWorkspaceId(options.workspace);
1050
+ const result = await client.folder.get(workspaceId, folderId);
1051
+ output.header(`Folder: ${folderId}`);
1052
+ output.output(result);
1053
+ });
1054
+ folder.command("create").description("Create a new folder").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-i, --id <folderId>", "Folder ID (optional)").option("-n, --name <name>", "Folder name").option("-p, --parent <parentId>", "Parent folder ID").action(async (options) => {
1055
+ requireApiKey();
1056
+ const client = getApiClient();
1057
+ const workspaceId = requireWorkspaceId(options.workspace);
1058
+ let name = options.name;
1059
+ if (!name) {
1060
+ const answers = await inquirer3.prompt([
1061
+ {
1062
+ type: "input",
1063
+ name: "name",
1064
+ message: "Folder name:",
1065
+ validate: (input) => input.length > 0 || "Name is required"
1066
+ }
1067
+ ]);
1068
+ name = String(answers.name);
1069
+ }
1070
+ const result = await client.folder.create(workspaceId, {
1071
+ id: options.id || uuidv42(),
1072
+ name: String(name),
1073
+ parentId: options.parent ?? null
1074
+ });
1075
+ output.success("Folder created successfully");
1076
+ output.output(result);
1077
+ });
1078
+ folder.command("update <folderId>").description("Update a folder").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-n, --name <name>", "New name").action(async (folderId, options) => {
1079
+ requireApiKey();
1080
+ const client = getApiClient();
1081
+ const workspaceId = requireWorkspaceId(options.workspace);
1082
+ if (!options.name) {
1083
+ output.warning("No changes provided. Use --name.");
1084
+ return;
1085
+ }
1086
+ const result = await client.folder.update(workspaceId, folderId, { name: options.name });
1087
+ output.success("Folder updated successfully");
1088
+ output.output(result);
1089
+ });
1090
+ folder.command("delete <folderId>").description("Delete a folder").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-y, --yes", "Skip confirmation").action(async (folderId, options) => {
1091
+ requireApiKey();
1092
+ const client = getApiClient();
1093
+ const workspaceId = requireWorkspaceId(options.workspace);
1094
+ if (!options.yes) {
1095
+ const { confirm } = await inquirer3.prompt([
1096
+ {
1097
+ type: "confirm",
1098
+ name: "confirm",
1099
+ message: `Are you sure you want to delete folder ${folderId}?`,
1100
+ default: false
1101
+ }
1102
+ ]);
1103
+ if (!confirm) {
1104
+ output.info("Delete cancelled");
1105
+ return;
1106
+ }
1107
+ }
1108
+ await client.folder.delete(workspaceId, folderId);
1109
+ output.success("Folder deleted successfully");
1110
+ });
1111
+ return folder;
1112
+ }
1113
+
1114
+ // src/commands/template.ts
1115
+ import { Command as Command4 } from "commander";
1116
+ import inquirer4 from "inquirer";
1117
+ function slugify(input) {
1118
+ return input.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
1119
+ }
1120
+ function createTemplateCommands() {
1121
+ const template = new Command4("template").description("Manage templates").action(() => template.help());
1122
+ template.command("list").description("List all templates").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").action(async (options) => {
1123
+ requireApiKey();
1124
+ const client = getApiClient();
1125
+ const workspaceId = requireWorkspaceId(options.workspace);
1126
+ const templates = await client.template.list(workspaceId);
1127
+ output.header("Templates");
1128
+ output.output(templates);
1129
+ });
1130
+ template.command("get <templateId>").description("Get template details").action(async (templateId) => {
1131
+ requireApiKey();
1132
+ const client = getApiClient();
1133
+ const result = await client.template.get(templateId);
1134
+ output.header(`Template: ${templateId}`);
1135
+ output.output(result);
1136
+ });
1137
+ template.command("get-by-slug <slug>").description("Get template details by slug").action(async (slug) => {
1138
+ requireApiKey();
1139
+ const client = getApiClient();
1140
+ const result = await client.template.getBySlug(slug);
1141
+ output.header(`Template: ${slug}`);
1142
+ output.output(result);
1143
+ });
1144
+ template.command("create <articleId>").description("Create a template from an article").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-n, --name <name>", "Template name").option("--slug <slug>", "Template slug (defaults to slugified name)").option("-d, --description <desc>", "Template description").option("-c, --category <category>", "Category: writing|documentation|planning|general|custom", "custom").option("-t, --tags <tags>", "Comma-separated tags", "").option("-v, --visibility <visibility>", "Visibility: private|workspace", "workspace").action(async (articleId, options) => {
1145
+ requireApiKey();
1146
+ const client = getApiClient();
1147
+ const workspaceId = requireWorkspaceId(options.workspace);
1148
+ let name = options.name;
1149
+ if (!name) {
1150
+ const answers = await inquirer4.prompt([
1151
+ {
1152
+ type: "input",
1153
+ name: "name",
1154
+ message: "Template name:",
1155
+ validate: (input) => input.length > 0 || "Name is required"
1156
+ }
1157
+ ]);
1158
+ name = String(answers.name);
1159
+ }
1160
+ const desc = options.description || "";
1161
+ const slug = options.slug || slugify(String(name));
1162
+ const tags = String(options.tags || "").split(",").map((t) => t.trim()).filter(Boolean);
1163
+ const result = await client.template.createFromArticle(workspaceId, articleId, {
1164
+ name: String(name),
1165
+ slug,
1166
+ category: options.category,
1167
+ description: desc,
1168
+ tags,
1169
+ visibility: options.visibility
1170
+ });
1171
+ output.success("Template created successfully");
1172
+ output.output(result);
1173
+ });
1174
+ template.command("update <templateId>").description("Update a template").option("-n, --name <name>", "Template name").option("-d, --description <desc>", "Template description").option("-c, --category <category>", "Category: writing|documentation|planning|general|custom").option("-t, --tags <tags>", "Comma-separated tags").action(async (templateId, options) => {
1175
+ requireApiKey();
1176
+ const client = getApiClient();
1177
+ const body = {};
1178
+ if (options.name) body.name = options.name;
1179
+ if (options.description) body.description = options.description;
1180
+ if (options.category) body.category = options.category;
1181
+ if (typeof options.tags === "string") {
1182
+ body.tags = options.tags.split(",").map((t) => t.trim()).filter(Boolean);
1183
+ }
1184
+ if (Object.keys(body).length === 0) {
1185
+ output.warning("No changes provided. Use --name, --description, --category, or --tags.");
1186
+ return;
1187
+ }
1188
+ const result = await client.template.update(templateId, body);
1189
+ output.success("Template updated successfully");
1190
+ output.output(result);
1191
+ });
1192
+ template.command("delete <templateId>").description("Delete a template").option("-y, --yes", "Skip confirmation").action(async (templateId, options) => {
1193
+ requireApiKey();
1194
+ const client = getApiClient();
1195
+ if (!options.yes) {
1196
+ const { confirm } = await inquirer4.prompt([
1197
+ {
1198
+ type: "confirm",
1199
+ name: "confirm",
1200
+ message: `Are you sure you want to delete template ${templateId}?`,
1201
+ default: false
1202
+ }
1203
+ ]);
1204
+ if (!confirm) {
1205
+ output.info("Delete cancelled");
1206
+ return;
1207
+ }
1208
+ }
1209
+ await client.template.delete(templateId);
1210
+ output.success("Template deleted successfully");
1211
+ });
1212
+ return template;
1213
+ }
1214
+
1215
+ // src/commands/config.ts
1216
+ import { Command as Command5 } from "commander";
1217
+ import inquirer5 from "inquirer";
1218
+ function redactSecret(value) {
1219
+ if (!value) return value;
1220
+ if (value.length <= 8) return "********";
1221
+ return `${value.slice(0, 4)}\u2026${value.slice(-4)}`;
1222
+ }
1223
+ var ALLOWED_KEYS = [
1224
+ "apiUrl",
1225
+ "apiKey",
1226
+ "userId",
1227
+ "workspaceId",
1228
+ "outputFormat"
1229
+ ];
1230
+ function createConfigCommands() {
1231
+ const config = new Command5("config").description("Manage CLI configuration").action(() => config.help());
1232
+ config.command("show").description("Show current configuration (effective values including environment variable overrides)").action(() => {
1233
+ const effectiveConfig = {};
1234
+ for (const key of ALLOWED_KEYS) {
1235
+ effectiveConfig[key] = configManager.get(key);
1236
+ }
1237
+ const safeConfig = {
1238
+ ...effectiveConfig,
1239
+ apiKey: redactSecret(effectiveConfig.apiKey)
1240
+ };
1241
+ output.header("Current Configuration");
1242
+ output.output(safeConfig);
1243
+ });
1244
+ config.command("set <key> <value>").description("Set a configuration value").action((key, value) => {
1245
+ if (!ALLOWED_KEYS.includes(key)) {
1246
+ throw new Error(`Unknown config key "${key}". Allowed keys: ${ALLOWED_KEYS.join(", ")}`);
1247
+ }
1248
+ configManager.set(key, value);
1249
+ const displayValue = key === "apiKey" ? redactSecret(String(value)) : value;
1250
+ output.success(`Configuration updated: ${key} = ${displayValue}`);
1251
+ });
1252
+ config.command("use-workspace <workspaceId>").description("Set default workspaceId for workspace-scoped commands").action((workspaceId) => {
1253
+ configManager.set("workspaceId", workspaceId);
1254
+ output.success(`Default workspace set: ${workspaceId}`);
1255
+ });
1256
+ config.command("local").description("Configure CLI to use local API (http://localhost:8080)").action(() => {
1257
+ configManager.set("apiUrl", "http://localhost:8080");
1258
+ output.success("API URL set to http://localhost:8080");
1259
+ });
1260
+ config.command("login").description("Set API key authentication").option("-k, --api-key <key>", "API key").option("-u, --url <url>", "API URL").action(async (options) => {
1261
+ let apiKey = options.apiKey || process.env.MDEDIT_API_KEY;
1262
+ if (!apiKey) {
1263
+ const answers = await inquirer5.prompt([
1264
+ {
1265
+ type: "password",
1266
+ name: "apiKey",
1267
+ message: "Enter your API key:",
1268
+ mask: "*",
1269
+ validate: (input) => input.length > 0 || "API key is required"
1270
+ }
1271
+ ]);
1272
+ apiKey = answers.apiKey;
1273
+ }
1274
+ configManager.set("apiKey", apiKey);
1275
+ if (options.url) {
1276
+ configManager.set("apiUrl", options.url);
1277
+ }
1278
+ output.success("API key configured successfully");
1279
+ if (!configManager.get("workspaceId")) {
1280
+ try {
1281
+ requireApiKey();
1282
+ const client = getApiClient();
1283
+ const workspaces = await client.workspace.list();
1284
+ if (workspaces.length === 1) {
1285
+ configManager.set("workspaceId", workspaces[0].workspaceId);
1286
+ output.success(`Default workspace set: ${workspaces[0].name} (${workspaces[0].workspaceId})`);
1287
+ } else if (workspaces.length > 1) {
1288
+ output.info(`You have ${workspaces.length} workspaces. Set a default with:`);
1289
+ output.info(" mdedit config use-workspace <workspaceId>");
1290
+ output.info("Or choose from:");
1291
+ workspaces.forEach((ws) => output.info(` ${ws.workspaceId} ${ws.name}`));
1292
+ }
1293
+ } catch {
1294
+ output.info("Set a default workspace with: mdedit config use-workspace <workspaceId>");
1295
+ }
1296
+ }
1297
+ });
1298
+ config.command("logout").description("Clear authentication").action(() => {
1299
+ configManager.set("apiKey", void 0);
1300
+ output.success("Logged out successfully");
1301
+ });
1302
+ config.command("clear").description("Clear all configuration").option("-y, --yes", "Skip confirmation").action(async (options) => {
1303
+ if (!options.yes) {
1304
+ const { confirm } = await inquirer5.prompt([
1305
+ {
1306
+ type: "confirm",
1307
+ name: "confirm",
1308
+ message: "Are you sure you want to clear all configuration?",
1309
+ default: false
1310
+ }
1311
+ ]);
1312
+ if (!confirm) {
1313
+ output.info("Clear cancelled");
1314
+ return;
1315
+ }
1316
+ }
1317
+ configManager.clear();
1318
+ output.success("Configuration cleared");
1319
+ });
1320
+ return config;
1321
+ }
1322
+
1323
+ // src/commands/apikey.ts
1324
+ import { Command as Command6 } from "commander";
1325
+ import inquirer6 from "inquirer";
1326
+ function createApiKeyCommands() {
1327
+ const apiKey = new Command6("api-key").description("Manage API keys for authentication").aliases(["apikey"]).action(() => apiKey.help());
1328
+ 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)").action(async (options) => {
1329
+ requireApiKey();
1330
+ const client = getApiClient();
1331
+ let name = options.name;
1332
+ if (!name) {
1333
+ const answers = await inquirer6.prompt([
1334
+ {
1335
+ type: "input",
1336
+ name: "name",
1337
+ message: "API key name:",
1338
+ validate: (input) => input.length > 0 || "Name is required"
1339
+ }
1340
+ ]);
1341
+ name = String(answers.name);
1342
+ }
1343
+ const expiresRaw = options.expires;
1344
+ let expiresInDays = void 0;
1345
+ if (expiresRaw !== void 0) {
1346
+ const days = Number.parseInt(String(expiresRaw), 10);
1347
+ if (!Number.isFinite(days) || days <= 0) {
1348
+ throw new Error("--expires must be a positive integer (number of days).");
1349
+ }
1350
+ expiresInDays = days;
1351
+ }
1352
+ output.info("Creating API key...");
1353
+ const req = { name };
1354
+ if (options.description) req.description = options.description;
1355
+ if (expiresInDays !== void 0) req.expiresInDays = expiresInDays;
1356
+ const result = await client.apiKeys.create(req);
1357
+ output.success("API key created successfully!");
1358
+ output.warning("\n\u26A0\uFE0F IMPORTANT: Save this API key now. It will not be shown again!\n");
1359
+ console.log("API Key ID:", result.keyId);
1360
+ console.log("API Key: ", result.key);
1361
+ console.log("Name: ", result.name);
1362
+ console.log("Created: ", result.createdAt);
1363
+ if (result.expiresAt) {
1364
+ console.log("Expires: ", result.expiresAt);
1365
+ }
1366
+ output.info("\nTo use this key with the CLI:");
1367
+ output.info(` mdedit config set apiKey ${result.key}`);
1368
+ output.info("\nOr set environment variable:");
1369
+ output.info(` export MDEDIT_API_KEY="${result.key}"`);
1370
+ });
1371
+ apiKey.command("list").description("List your API keys").action(async () => {
1372
+ requireApiKey();
1373
+ const client = getApiClient();
1374
+ const result = await client.apiKeys.list();
1375
+ if (result.keys.length === 0) {
1376
+ output.info("No API keys found. Create one with: mdedit apikey create");
1377
+ return;
1378
+ }
1379
+ output.header("Your API Keys");
1380
+ output.output(result.keys);
1381
+ });
1382
+ apiKey.command("revoke <keyId>").description("Revoke an API key").option("-y, --yes", "Skip confirmation").action(async (keyId, options) => {
1383
+ requireApiKey();
1384
+ const client = getApiClient();
1385
+ if (!options.yes) {
1386
+ const { confirm } = await inquirer6.prompt([
1387
+ {
1388
+ type: "confirm",
1389
+ name: "confirm",
1390
+ message: `Are you sure you want to revoke API key ${keyId}?`,
1391
+ default: false
1392
+ }
1393
+ ]);
1394
+ if (!confirm) {
1395
+ output.info("Revoke cancelled");
1396
+ return;
1397
+ }
1398
+ }
1399
+ await client.apiKeys.revoke(keyId);
1400
+ output.success("API key revoked successfully");
1401
+ output.warning("This key can no longer be used for authentication");
1402
+ });
1403
+ return apiKey;
1404
+ }
1405
+
1406
+ // src/index.ts
1407
+ var __filename = fileURLToPath(import.meta.url);
1408
+ var __dirname = dirname(__filename);
1409
+ var version = "0.0.0";
1410
+ try {
1411
+ const packageJson = JSON.parse(readFileSync2(join2(__dirname, "../package.json"), "utf-8"));
1412
+ version = packageJson.version || version;
1413
+ } catch {
1414
+ }
1415
+ var program = new Command7();
1416
+ 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", "plain").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) => {
1417
+ const opts = typeof thisCommand.optsWithGlobals === "function" ? (
1418
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1419
+ thisCommand.optsWithGlobals()
1420
+ ) : thisCommand.opts();
1421
+ if (opts.format) output.setFormat(opts.format);
1422
+ if (opts.local) process.env.MDEDIT_API_URL = "http://localhost:8080";
1423
+ if (opts.apiUrl) process.env.MDEDIT_API_URL = opts.apiUrl;
1424
+ if (opts.apiKey) process.env.MDEDIT_API_KEY = opts.apiKey;
1425
+ if (opts.workspace) process.env.MDEDIT_WORKSPACE_ID = opts.workspace;
1426
+ if (opts.debug) process.env.MDEDIT_DEBUG = "1";
1427
+ });
1428
+ program.addCommand(createArticleCommands());
1429
+ program.addCommand(createWorkspaceCommands());
1430
+ program.addCommand(createFolderCommands());
1431
+ program.addCommand(createTemplateCommands());
1432
+ program.addCommand(createConfigCommands());
1433
+ program.addCommand(createApiKeyCommands());
1434
+ program.command("health").description("Check API health status").action(async () => {
1435
+ const base = getApiBaseUrlRoot();
1436
+ const response = await fetch(`${base}/health`, { method: "GET" });
1437
+ if (!response.ok) {
1438
+ throw new Error(`Health check failed (${response.status}): ${response.statusText}`);
1439
+ }
1440
+ const result = await response.json().catch(() => ({}));
1441
+ output.success("API is healthy");
1442
+ output.output(result);
1443
+ });
1444
+ program.command("info").description("Display CLI and API information").action(async () => {
1445
+ output.header("MDEdit.ai CLI Information");
1446
+ output.info(`CLI Version: ${version}`);
1447
+ const apiUrl = configManager.get("apiUrl") || process.env.MDEDIT_API_URL || "https://apiv2.mdedit.ai";
1448
+ output.info(`API URL: ${apiUrl}`);
1449
+ const apiKey = configManager.get("apiKey");
1450
+ output.info(`Auth Method: ${apiKey ? "API Key" : "None"}`);
1451
+ try {
1452
+ const base = getApiBaseUrlRoot();
1453
+ const health = await fetch(`${base}/health`, { method: "GET" }).then((r) => r.json());
1454
+ output.success("API Status: Healthy");
1455
+ output.output(health);
1456
+ } catch {
1457
+ output.warning("API Status: Unavailable");
1458
+ }
1459
+ try {
1460
+ if (apiKey) {
1461
+ const client = getApiClient();
1462
+ await client.workspace.list();
1463
+ output.success("Auth: OK");
1464
+ }
1465
+ } catch {
1466
+ output.warning("Auth: Failed");
1467
+ }
1468
+ });
1469
+ program.action(() => {
1470
+ program.outputHelp();
1471
+ });
1472
+ program.showSuggestionAfterError(true);
1473
+ async function main() {
1474
+ if (!process.argv.slice(2).length) {
1475
+ program.outputHelp();
1476
+ process.exitCode = 0;
1477
+ return;
1478
+ }
1479
+ try {
1480
+ await program.parseAsync(process.argv);
1481
+ } catch (err) {
1482
+ const debug = process.env.MDEDIT_DEBUG === "1";
1483
+ if (err instanceof FetchError2) {
1484
+ output.error(`API request failed (${err.status}): ${err.message}`);
1485
+ if (err.status === 401) {
1486
+ output.info("Hint: set an API key via `mdedit config set apiKey <key>` or pass `--api-key <key>`.");
1487
+ } else if (err.status === 403) {
1488
+ output.info("Hint: check that the API key user has permission for this workspace/resource.");
1489
+ } else if (err.status === 404) {
1490
+ output.info("Hint: verify your `apiUrl` and that the API build matches the CLI routes.");
1491
+ }
1492
+ if (debug && err.stack) output.warning(err.stack);
1493
+ } else if (err instanceof Error) {
1494
+ output.error(err.message);
1495
+ if (debug && err.stack) output.warning(err.stack);
1496
+ } else {
1497
+ output.error(err);
1498
+ }
1499
+ process.exitCode = 1;
1500
+ }
1501
+ }
1502
+ await main();
1503
+ //# sourceMappingURL=index.js.map