mdedit-cli 0.4.3 → 0.4.5

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/README.md CHANGED
@@ -18,9 +18,11 @@ All APIs require authentication. Create an API key here:
18
18
 
19
19
  - [API key docs](https://mdedit.ai/docs/api-keys)
20
20
 
21
- Interactive browser OAuth is also available in explicitly enabled cohorts. It
22
- uses authorization code + PKCE, a fixed loopback callback, and the operating
23
- system credential manager:
21
+ Signing in through your browser is being rolled out gradually. If it is available
22
+ for your account, you can sign in this way instead of creating a key. If it is
23
+ not available yet, use an API key. Sign-in uses authorization code with PKCE and
24
+ a fixed loopback callback, and your credentials are kept in your operating system
25
+ credential manager:
24
26
 
25
27
  ```bash
26
28
  mdedit auth login
@@ -28,8 +30,8 @@ mdedit auth status
28
30
  mdedit auth logout
29
31
  ```
30
32
 
31
- Headless and CI environments should continue to use scoped API keys. Browser
32
- OAuth remains release-gated and `--no-browser` is not a device flow.
33
+ Headless and CI environments should keep using scoped API keys. There is no
34
+ device-code flow, so `--no-browser` does not replace browser sign-in.
33
35
 
34
36
  ## Configure
35
37
 
@@ -66,7 +68,8 @@ mdedit document edit <documentId> --ops-file ops.json --format json
66
68
  An ops file is a non-empty JSON array of `replace`, `insert`, or `delete` operations with
67
69
  quote, heading, section, or range anchors. The command exits `2` when an anchor is missing,
68
70
  `3` when an anchor is ambiguous, and `4` when an edit conflict is reported. In JSON mode,
69
- the result or typed error is the only value written to stdout.
71
+ the result or typed error is the only value written to stdout. Successful JSON results
72
+ include `authority`, `contentHash`, and `contentRevision` from the durable backend commit.
70
73
 
71
74
  ## Public links
72
75
 
package/dist/index.js CHANGED
@@ -74,6 +74,158 @@ async function getToolJobStatus(jobId, fetchers) {
74
74
  if (!resp.ok) throw await buildApiError(resp);
75
75
  return resp.json();
76
76
  }
77
+ async function createConversionUploadUrl(request, fetchers, signal) {
78
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
79
+ const resp = await fetchV2("/conversions/uploads", {
80
+ method: "POST",
81
+ body: JSON.stringify(request),
82
+ headers: { "Content-Type": "application/json" },
83
+ signal
84
+ });
85
+ if (!resp.ok) throw await buildApiError(resp);
86
+ return resp.json();
87
+ }
88
+ async function startConversion(request, fetchers, signal) {
89
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
90
+ const resp = await fetchV2("/conversions", {
91
+ method: "POST",
92
+ body: JSON.stringify(request),
93
+ headers: { "Content-Type": "application/json" },
94
+ signal
95
+ });
96
+ if (!resp.ok) throw await buildApiError(resp);
97
+ return resp.json();
98
+ }
99
+ async function getConversionStatus(jobId, fetchers, signal) {
100
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
101
+ const resp = await fetchV2(`/conversions/${encodeURIComponent(jobId)}`, { signal });
102
+ if (!resp.ok) throw await buildApiError(resp);
103
+ return resp.json();
104
+ }
105
+ async function downloadConversion(jobId, fetchers, signal) {
106
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
107
+ const resp = await fetchV2(`/conversions/${encodeURIComponent(jobId)}/download`, { signal });
108
+ if (!resp.ok) throw await buildApiError(resp);
109
+ return resp.blob();
110
+ }
111
+ function newJobId() {
112
+ if (typeof globalThis.crypto?.randomUUID === "function") return globalThis.crypto.randomUUID();
113
+ const bytes = new Uint8Array(16);
114
+ globalThis.crypto.getRandomValues(bytes);
115
+ bytes[6] = bytes[6] & 15 | 64;
116
+ bytes[8] = bytes[8] & 63 | 128;
117
+ const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
118
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
119
+ }
120
+ function safeFileName(fileName) {
121
+ const base = fileName.split(/[\\/]/).pop() || "input";
122
+ return base.replace(/[^\w.\-]+/g, "_").slice(0, 128) || "input";
123
+ }
124
+ function abortReason(signal) {
125
+ const reason = signal?.reason;
126
+ return reason instanceof Error ? reason : new Error("Conversion aborted");
127
+ }
128
+ function withDeadline(timeoutMs, signal) {
129
+ const controller = new AbortController();
130
+ const onAbort = () => controller.abort(abortReason(signal));
131
+ if (signal?.aborted) {
132
+ onAbort();
133
+ } else {
134
+ signal?.addEventListener("abort", onAbort, { once: true });
135
+ }
136
+ const timer = setTimeout(
137
+ () => controller.abort(new Error(`Conversion timed out after ${Math.round(timeoutMs / 1e3)}s`)),
138
+ timeoutMs
139
+ );
140
+ return {
141
+ signal: controller.signal,
142
+ dispose: () => {
143
+ clearTimeout(timer);
144
+ signal?.removeEventListener("abort", onAbort);
145
+ }
146
+ };
147
+ }
148
+ async function startConversionFromBytes(input, fetchers) {
149
+ const {
150
+ data,
151
+ type,
152
+ inputFormat,
153
+ outputFormat,
154
+ outputFileName,
155
+ contentType = "application/octet-stream",
156
+ toolRunId,
157
+ signal
158
+ } = input;
159
+ const jobId = newJobId();
160
+ const fileName = safeFileName(input.fileName);
161
+ const inputKey = `tools/input/${jobId}/${fileName}`;
162
+ const { signedUrl } = await createConversionUploadUrl(
163
+ { key: inputKey, action: "putObject", contentType },
164
+ fetchers,
165
+ signal
166
+ );
167
+ const body = data instanceof Uint8Array ? data : new Uint8Array(data);
168
+ const uploadResponse = await fetch(signedUrl, {
169
+ method: "PUT",
170
+ body,
171
+ headers: { "Content-Type": contentType },
172
+ signal
173
+ });
174
+ if (!uploadResponse.ok) {
175
+ throw new Error(`Upload failed with status ${uploadResponse.status}`);
176
+ }
177
+ await startConversion(
178
+ {
179
+ type,
180
+ inputKey,
181
+ inputFormat,
182
+ ...outputFormat ? { outputFormat } : {},
183
+ ...outputFileName ? { outputFileName } : {},
184
+ ...toolRunId ? { toolRunId } : {}
185
+ },
186
+ fetchers,
187
+ signal
188
+ );
189
+ return { jobId };
190
+ }
191
+ async function convertFile(input, fetchers) {
192
+ const {
193
+ outputFileName,
194
+ onProgress,
195
+ pollIntervalMs = DEFAULT_POLL_INTERVAL_MS,
196
+ timeoutMs = DEFAULT_TIMEOUT_MS,
197
+ signal
198
+ } = input;
199
+ const deadline = withDeadline(timeoutMs, signal);
200
+ try {
201
+ const { jobId } = await startConversionFromBytes(
202
+ { ...input, signal: deadline.signal },
203
+ fetchers
204
+ );
205
+ for (; ; ) {
206
+ const status = await getConversionStatus(jobId, fetchers, deadline.signal);
207
+ onProgress?.(status);
208
+ if (status.status === "completed") {
209
+ const blob = await downloadConversion(jobId, fetchers, deadline.signal);
210
+ return {
211
+ blob,
212
+ jobId,
213
+ fileName: status.fileName || outputFileName || `${jobId}.out`,
214
+ mimeType: status.mimeType || "application/octet-stream"
215
+ };
216
+ }
217
+ if (status.status === "failed") {
218
+ const error = new Error(status.failedReason || "Conversion failed");
219
+ error.errorCode = status.errorCode;
220
+ error.errorDetails = status.errorDetails;
221
+ throw error;
222
+ }
223
+ await sleep(pollIntervalMs, deadline.signal);
224
+ }
225
+ } finally {
226
+ deadline.dispose();
227
+ }
228
+ }
77
229
  async function fetchErrorFromResponse(prefix, response) {
78
230
  const text = await response.text();
79
231
  let data;
@@ -84,6 +236,28 @@ async function fetchErrorFromResponse(prefix, response) {
84
236
  }
85
237
  return new errors_default(`${prefix}. ${text}`, response.status, data);
86
238
  }
239
+ async function checkpointCollaboration(workspaceId, articleId, requestOrFetchers = {}, suppliedFetchers) {
240
+ const legacyFetchers = "customFetchV2" in requestOrFetchers ? requestOrFetchers : void 0;
241
+ const request = legacyFetchers ? {} : requestOrFetchers;
242
+ const fetchers = legacyFetchers ?? suppliedFetchers;
243
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
244
+ const hasExpectedContentHash = typeof request.expectedContentHash === "string";
245
+ const response = await fetchV2(
246
+ `/workspaces/${workspaceId}/articles/${articleId}/collaboration/checkpoint`,
247
+ hasExpectedContentHash ? {
248
+ method: "POST",
249
+ headers: { "Content-Type": "application/json" },
250
+ body: JSON.stringify(request)
251
+ } : { method: "POST" }
252
+ );
253
+ if (!response.ok) {
254
+ throw new errors_default(
255
+ `Error checkpointing collaboration. ${await response.text()}`,
256
+ response.status
257
+ );
258
+ }
259
+ return response.json();
260
+ }
87
261
  function coerceToFetchError(err) {
88
262
  const anyErr = err;
89
263
  const status = typeof anyErr?.status === "number" ? anyErr.status : 500;
@@ -158,7 +332,15 @@ function createSdkClient(config) {
158
332
  safeGists: async (workspaceId, articleId, urls) => (await withFetchError(() => getArticleSafeGists(workspaceId, articleId, urls, fetchers))).gists
159
333
  },
160
334
  collaboration: {
161
- checkpoint: (workspaceId, articleId) => withFetchError(() => checkpointCollaboration(workspaceId, articleId, fetchers))
335
+ checkpoint: (workspaceId, articleId, request = {}) => withFetchError(() => checkpointCollaboration(workspaceId, articleId, request, fetchers))
336
+ },
337
+ tools: {
338
+ createUpload: (request) => withFetchError(() => createConversionUploadUrl(request, fetchers)),
339
+ convert: (request) => withFetchError(() => startConversion(request, fetchers)),
340
+ jobStatus: (jobId) => withFetchError(() => getConversionStatus(jobId, fetchers)),
341
+ download: (jobId) => withFetchError(() => downloadConversion(jobId, fetchers)),
342
+ convertFile: (input) => withFetchError(() => convertFile(input, fetchers)),
343
+ startConversion: (input) => withFetchError(() => startConversionFromBytes(input, fetchers))
162
344
  },
163
345
  publish: {
164
346
  publish: (workspaceId, articleId, request = {}) => withFetchError(() => publishArticle(workspaceId, articleId, request, fetchers)),
@@ -168,7 +350,7 @@ function createSdkClient(config) {
168
350
  }
169
351
  };
170
352
  }
171
- var _defaultFetchers, customFetchV2, FetchError, errors_default, createArticle, updateArticle, getArticles, getArticlesByFolder, getArticle, getArticlePresentation, getArticleAssetDownloadUrls, getArticleMediaProxyUrls, getArticleSafeGists, deleteArticle, exportArticleZip, createArticleExportJob, ApiError, 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;
353
+ var _defaultFetchers, customFetchV2, FetchError, errors_default, createArticle, updateArticle, getArticles, getArticlesByFolder, getArticle, getArticlePresentation, getArticleAssetDownloadUrls, getArticleMediaProxyUrls, getArticleSafeGists, deleteArticle, exportArticleZip, createArticleExportJob, ApiError, DEFAULT_POLL_INTERVAL_MS, DEFAULT_TIMEOUT_MS, sleep, saveArticleContent, getWorkspaces, createWorkspace, updateWorkspace, deleteWorkspace, getWorkspace, normalizeTimestampMs, readFolderErrorMessage, normalizeFolder, createFolder, updateFolder, getFolders, getFolder, deleteFolder, sleep2, isRetriableStatus, withRetries, listApiKeys, createApiKey, revokeApiKey, publishArticle, unpublishArticle, getPublishStatus, updatePublishedArticle, FetchError2;
172
354
  var init_dist = __esm({
173
355
  "../sdk/dist/index.js"() {
174
356
  "use strict";
@@ -197,7 +379,8 @@ var init_dist = __esm({
197
379
  title: articleRequest.title,
198
380
  folderId: articleRequest.folderId,
199
381
  collaborative: articleRequest.collaborative ?? false,
200
- articleSettings: articleRequest.articleSettings
382
+ articleSettings: articleRequest.articleSettings,
383
+ tags: articleRequest.tags
201
384
  })
202
385
  });
203
386
  if (!response.ok) {
@@ -228,6 +411,9 @@ var init_dist = __esm({
228
411
  if (articleRequest.folderId !== void 0) {
229
412
  body.folderId = articleRequest.folderId;
230
413
  }
414
+ if (articleRequest.tags !== void 0) {
415
+ body.tags = articleRequest.tags;
416
+ }
231
417
  if (articleRequest.preview) {
232
418
  body.preview = articleRequest.preview;
233
419
  }
@@ -402,6 +588,20 @@ var init_dist = __esm({
402
588
  this.data = data;
403
589
  }
404
590
  };
591
+ DEFAULT_POLL_INTERVAL_MS = 1500;
592
+ DEFAULT_TIMEOUT_MS = 10 * 60 * 1e3;
593
+ sleep = (ms, signal) => new Promise((resolve, reject) => {
594
+ if (signal?.aborted) return reject(abortReason(signal));
595
+ const timer = setTimeout(() => {
596
+ signal?.removeEventListener("abort", onAbort);
597
+ resolve();
598
+ }, ms);
599
+ const onAbort = () => {
600
+ clearTimeout(timer);
601
+ reject(abortReason(signal));
602
+ };
603
+ signal?.addEventListener("abort", onAbort, { once: true });
604
+ });
405
605
  saveArticleContent = async (workspaceId, articleId, content, optionsOrFetchers, fetchers) => {
406
606
  const maybeFetchers = optionsOrFetchers && "customFetchV2" in optionsOrFetchers ? optionsOrFetchers : fetchers;
407
607
  const options = optionsOrFetchers && !("customFetchV2" in optionsOrFetchers) ? optionsOrFetchers : void 0;
@@ -457,7 +657,8 @@ var init_dist = __esm({
457
657
  folderId: options.folderId,
458
658
  isPinned: options.isPinned,
459
659
  isArchived: options.isArchived,
460
- articleSettings: options.articleSettings
660
+ articleSettings: options.articleSettings,
661
+ tags: options.tags
461
662
  })
462
663
  }
463
664
  );
@@ -657,7 +858,7 @@ var init_dist = __esm({
657
858
  }
658
859
  return true;
659
860
  };
660
- sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
861
+ sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
661
862
  isRetriableStatus = (status) => status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
662
863
  withRetries = async (fn, maxAttempts = 3) => {
663
864
  let lastError;
@@ -667,7 +868,7 @@ var init_dist = __esm({
667
868
  if (response.ok) return response;
668
869
  if (attempt < maxAttempts && isRetriableStatus(response.status)) {
669
870
  const backoffMs = 250 * Math.pow(2, attempt - 1) + Math.floor(Math.random() * 150);
670
- await sleep(backoffMs);
871
+ await sleep2(backoffMs);
671
872
  continue;
672
873
  }
673
874
  return response;
@@ -675,7 +876,7 @@ var init_dist = __esm({
675
876
  lastError = e;
676
877
  if (attempt < maxAttempts) {
677
878
  const backoffMs = 250 * Math.pow(2, attempt - 1) + Math.floor(Math.random() * 150);
678
- await sleep(backoffMs);
879
+ await sleep2(backoffMs);
679
880
  continue;
680
881
  }
681
882
  throw lastError;
@@ -718,20 +919,6 @@ var init_dist = __esm({
718
919
  }
719
920
  return response.json();
720
921
  };
721
- checkpointCollaboration = async (workspaceId, articleId, fetchers) => {
722
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
723
- const response = await fetchV2(
724
- `/workspaces/${workspaceId}/articles/${articleId}/collaboration/checkpoint`,
725
- { method: "POST" }
726
- );
727
- if (!response.ok) {
728
- throw new errors_default(
729
- `Error checkpointing collaboration. ${await response.text()}`,
730
- response.status
731
- );
732
- }
733
- return response.json();
734
- };
735
922
  publishArticle = async (workspaceId, articleId, body, fetchers) => {
736
923
  const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
737
924
  const response = await fetchV2(
@@ -1695,14 +1882,13 @@ var init_api = __esm({
1695
1882
 
1696
1883
  // src/index.ts
1697
1884
  init_dist();
1698
- import { Command as Command9 } from "commander";
1885
+ import { Command as Command10 } from "commander";
1699
1886
  import { readFileSync as readFileSync3 } from "fs";
1700
1887
  import { dirname as dirname2, join as join3 } from "path";
1701
1888
  import { fileURLToPath as fileURLToPath2 } from "url";
1702
1889
  import { AgentClientHttpError } from "@mdedit/agent-client";
1703
1890
 
1704
1891
  // src/commands/article.ts
1705
- init_dist();
1706
1892
  init_output();
1707
1893
  import { Command, Option } from "commander";
1708
1894
  import inquirer from "inquirer";
@@ -2064,26 +2250,14 @@ function createDocumentCommand(commandName, deprecated) {
2064
2250
  anchor: { range: { from: 0, to: currentContent.length } },
2065
2251
  text: contentText
2066
2252
  }]);
2253
+ const receipt = await session.ensureDurable();
2254
+ const expectedContentHash = sha256Hex(contentText);
2255
+ if (receipt.contentHash !== expectedContentHash) {
2256
+ throw new Error("Collaborative content durability receipt did not match the created content.");
2257
+ }
2067
2258
  } finally {
2068
2259
  await session.close();
2069
2260
  }
2070
- const expectedContentHash = sha256Hex(contentText);
2071
- let checkpointedContentHash;
2072
- for (let attempt = 0; attempt < 20; attempt += 1) {
2073
- try {
2074
- const checkpoint = await client.collaboration.checkpoint(workspaceId, articleId);
2075
- checkpointedContentHash = checkpoint.targetHashes["content.md"];
2076
- if (checkpointedContentHash === expectedContentHash) break;
2077
- } catch (error) {
2078
- if (!(error instanceof FetchError2) || error.status !== 409 && error.status !== 503) {
2079
- throw error;
2080
- }
2081
- }
2082
- await new Promise((resolve) => setTimeout(resolve, 500));
2083
- }
2084
- if (checkpointedContentHash !== expectedContentHash) {
2085
- throw new Error("Collaborative content did not reach a durable checkpoint within 10 seconds.");
2086
- }
2087
2261
  } else {
2088
2262
  await client.article.saveContent(workspaceId, articleId, contentText, {
2089
2263
  baseContentRevision: 0,
@@ -2259,6 +2433,7 @@ function createDocumentCommand(commandName, deprecated) {
2259
2433
  let session;
2260
2434
  let editError;
2261
2435
  let result;
2436
+ let receipt;
2262
2437
  try {
2263
2438
  session = await openArticleSession({
2264
2439
  credentialProvider,
@@ -2268,6 +2443,7 @@ function createDocumentCommand(commandName, deprecated) {
2268
2443
  apiUrl: getApiUrlRaw()
2269
2444
  });
2270
2445
  result = await session.edit(operations);
2446
+ receipt = await session.ensureDurable();
2271
2447
  } catch (error) {
2272
2448
  editError = error;
2273
2449
  throw error;
@@ -2280,8 +2456,15 @@ function createDocumentCommand(commandName, deprecated) {
2280
2456
  }
2281
2457
  }
2282
2458
  }
2283
- if (!session || !result) throw new Error("Document edit did not return a result.");
2284
- output.output({ articleId, mode: session.mode, ...result });
2459
+ if (!session || !result || !receipt) throw new Error("Document edit did not return a durable result.");
2460
+ output.output({
2461
+ articleId,
2462
+ mode: session.mode,
2463
+ authority: receipt.authority,
2464
+ contentHash: receipt.contentHash,
2465
+ contentRevision: receipt.contentRevision,
2466
+ ...result
2467
+ });
2285
2468
  if (result.conflicts.length > 0) {
2286
2469
  output.warning("The edit was applied with overlapping remote changes; re-read the document before continuing.");
2287
2470
  process.exitCode = CLI_EXIT_CODES.EDIT_CONFLICT;
@@ -3137,6 +3320,170 @@ function createAuthCommands(runtime = defaultRuntime) {
3137
3320
  return auth;
3138
3321
  }
3139
3322
 
3323
+ // src/commands/convert.ts
3324
+ init_output();
3325
+ init_api();
3326
+ import { Command as Command9 } from "commander";
3327
+ import { readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
3328
+ import { basename as basename2, extname as extname2 } from "path";
3329
+ var MARKDOWN_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".markdown", ".mdown", ".mkd"]);
3330
+ var HTML_EXTENSIONS = /* @__PURE__ */ new Set([".html", ".htm"]);
3331
+ var PANDOC_INPUT_FORMATS = /* @__PURE__ */ new Set([
3332
+ "markdown",
3333
+ "md",
3334
+ "html",
3335
+ "latex",
3336
+ "tex",
3337
+ "rst",
3338
+ "rtf",
3339
+ "docx",
3340
+ "odt",
3341
+ "epub",
3342
+ "ipynb",
3343
+ "asciidoc",
3344
+ "txt",
3345
+ "org",
3346
+ "mediawiki",
3347
+ "typst",
3348
+ "docbook"
3349
+ ]);
3350
+ var PANDOC_OUTPUT_FORMATS = /* @__PURE__ */ new Set([...PANDOC_INPUT_FORMATS, "pdf", "pptx"]);
3351
+ var MARKITDOWN_INPUT_FORMATS = /* @__PURE__ */ new Set(["pdf", "pptx", "xlsx", "xls", "msg"]);
3352
+ var MARKDOWN_OUTPUT_ALIASES = /* @__PURE__ */ new Set(["md", "markdown"]);
3353
+ function resolveConversion(inputFile, to, from) {
3354
+ const outputFormat = to.trim().toLowerCase().replace(/^\./, "");
3355
+ if (!outputFormat) {
3356
+ throw new Error("--to is required, for example --to docx");
3357
+ }
3358
+ const ext = extname2(inputFile).toLowerCase().replace(/^\./, "");
3359
+ const explicitFrom = from?.trim().toLowerCase().replace(/^\./, "");
3360
+ const rawInput = explicitFrom || ext;
3361
+ if (!rawInput) {
3362
+ throw new Error("Cannot tell the input format from the file name. Pass --from, for example --from md.");
3363
+ }
3364
+ const isMarkdown = explicitFrom ? MARKDOWN_OUTPUT_ALIASES.has(explicitFrom) : MARKDOWN_EXTENSIONS.has(`.${ext}`);
3365
+ const isHtml = explicitFrom ? ["html", "htm"].includes(explicitFrom) : HTML_EXTENSIONS.has(`.${ext}`);
3366
+ if (isMarkdown || isHtml) {
3367
+ const inputFormat = isMarkdown ? "markdown" : "html";
3368
+ if (outputFormat === "pdf") return { type: "pdf", inputFormat, outputFormat };
3369
+ if (outputFormat === "mp3") return { type: "mp3", inputFormat, outputFormat };
3370
+ if (outputFormat === "zip") {
3371
+ if (!isMarkdown) {
3372
+ throw new Error("Only Markdown can be converted to zip. Convert the HTML to Markdown first.");
3373
+ }
3374
+ return { type: "zip", inputFormat, outputFormat };
3375
+ }
3376
+ if (!PANDOC_OUTPUT_FORMATS.has(outputFormat)) {
3377
+ throw new Error(
3378
+ `Cannot convert ${inputFormat} to ${outputFormat}. Supported: ${[...PANDOC_OUTPUT_FORMATS].sort().join(", ")}, mp3, zip.`
3379
+ );
3380
+ }
3381
+ return { type: "pandoc", inputFormat, outputFormat };
3382
+ }
3383
+ if (PANDOC_INPUT_FORMATS.has(rawInput)) {
3384
+ if (outputFormat === "mp3" || outputFormat === "zip") {
3385
+ throw new Error(
3386
+ `Cannot convert ${rawInput} to ${outputFormat}. Convert to Markdown first, then to ${outputFormat}.`
3387
+ );
3388
+ }
3389
+ if (!PANDOC_OUTPUT_FORMATS.has(outputFormat)) {
3390
+ throw new Error(
3391
+ `Cannot convert ${rawInput} to ${outputFormat}. Supported: ${[...PANDOC_OUTPUT_FORMATS].sort().join(", ")}.`
3392
+ );
3393
+ }
3394
+ return { type: "pandoc", inputFormat: rawInput, outputFormat };
3395
+ }
3396
+ if (MARKITDOWN_INPUT_FORMATS.has(rawInput)) {
3397
+ if (!MARKDOWN_OUTPUT_ALIASES.has(outputFormat)) {
3398
+ throw new Error(
3399
+ `${rawInput} can only be converted to Markdown. Run a second conversion to reach ${outputFormat}.`
3400
+ );
3401
+ }
3402
+ return { type: "markitdown", inputFormat: rawInput, outputFormat: "markdown" };
3403
+ }
3404
+ throw new Error(
3405
+ `Unsupported input format: ${rawInput}. Supported inputs: ${[.../* @__PURE__ */ new Set([...PANDOC_INPUT_FORMATS, ...MARKITDOWN_INPUT_FORMATS])].sort().join(", ")}.`
3406
+ );
3407
+ }
3408
+ function defaultOutputPath(inputFile, outputFormat) {
3409
+ const stem = basename2(inputFile, extname2(inputFile));
3410
+ const ext = outputFormat === "markdown" ? "md" : outputFormat;
3411
+ return `${stem}.${ext}`;
3412
+ }
3413
+ var CONVERSION_SCOPE = "conversions:execute";
3414
+ function isInteractive() {
3415
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY) && !output.isJson();
3416
+ }
3417
+ async function ensureConvertAuthentication() {
3418
+ const usingApiKey = Boolean(process.env.MDEDIT_API_KEY?.trim());
3419
+ let needsLogin = false;
3420
+ try {
3421
+ requireAuthentication();
3422
+ } catch (error) {
3423
+ if (!isInteractive()) throw error;
3424
+ needsLogin = true;
3425
+ }
3426
+ if (!needsLogin && !usingApiKey) {
3427
+ const { oauthStatus: oauthStatus2 } = await Promise.resolve().then(() => (init_oauth(), oauth_exports));
3428
+ const status = await oauthStatus2().catch(() => null);
3429
+ if (status?.authenticated) {
3430
+ const hasConversionScope = (status.scope || []).some(
3431
+ (scope) => scope === CONVERSION_SCOPE || scope.endsWith(`/${CONVERSION_SCOPE}`)
3432
+ );
3433
+ if (!hasConversionScope) {
3434
+ if (!isInteractive()) {
3435
+ throw new Error(
3436
+ "Your sign-in predates conversion access. Run `mdedit auth login` to re-authorize, or pass an API key with the conversions:execute scope."
3437
+ );
3438
+ }
3439
+ output.info("Your sign-in predates conversion access. Re-authorizing in your browser...");
3440
+ needsLogin = true;
3441
+ }
3442
+ }
3443
+ }
3444
+ if (!needsLogin) return;
3445
+ output.info("Converting needs a one-time sign-in. Opening your browser...");
3446
+ const { loginWithOAuth: loginWithOAuth2 } = await Promise.resolve().then(() => (init_oauth(), oauth_exports));
3447
+ await loginWithOAuth2({});
3448
+ output.info("Signed in. Continuing with the conversion.");
3449
+ }
3450
+ function createConvertCommands() {
3451
+ return new Command9("convert").description("Convert a document between formats").argument("<input>", "Path to the file to convert").requiredOption("-t, --to <format>", "Target format, for example docx, pdf, md").option("-f, --from <format>", "Override the input format (inferred from the extension)").option("-o, --out <path>", "Where to write the result (defaults to the input name with the new extension)").addHelpText("after", `
3452
+ Examples:
3453
+ $ mdedit convert README.md --to docx
3454
+ $ mdedit convert notes.md --to pdf --out notes.pdf
3455
+ $ mdedit convert report.docx --to md
3456
+ `).action(async (inputFile, options) => {
3457
+ await ensureConvertAuthentication();
3458
+ const client = getApiClient();
3459
+ const conversion = resolveConversion(inputFile, options.to, options.from);
3460
+ const outPath = options.out || defaultOutputPath(inputFile, conversion.outputFormat);
3461
+ const data = await readFile2(inputFile);
3462
+ if (!output.isJson()) {
3463
+ output.info(`Converting ${basename2(inputFile)} to ${conversion.outputFormat}...`);
3464
+ }
3465
+ const result = await client.tools.convertFile({
3466
+ data: new Uint8Array(data),
3467
+ fileName: basename2(inputFile),
3468
+ type: conversion.type,
3469
+ inputFormat: conversion.inputFormat,
3470
+ outputFormat: conversion.outputFormat
3471
+ });
3472
+ await writeFile2(outPath, Buffer.from(await result.blob.arrayBuffer()));
3473
+ if (output.isJson()) {
3474
+ output.output({
3475
+ input: inputFile,
3476
+ output: outPath,
3477
+ jobId: result.jobId,
3478
+ mimeType: result.mimeType,
3479
+ conversion
3480
+ });
3481
+ return;
3482
+ }
3483
+ output.success(`Wrote ${outPath}`);
3484
+ });
3485
+ }
3486
+
3140
3487
  // src/index.ts
3141
3488
  init_output();
3142
3489
  init_config();
@@ -3149,7 +3496,7 @@ try {
3149
3496
  version = packageJson.version || version;
3150
3497
  } catch {
3151
3498
  }
3152
- var program = new Command9();
3499
+ var program = new Command10();
3153
3500
  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) => {
3154
3501
  const opts = typeof thisCommand.optsWithGlobals === "function" ? (
3155
3502
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -3172,6 +3519,7 @@ program.addCommand(createSkillCommands());
3172
3519
  program.addCommand(createReviewCommands());
3173
3520
  program.addCommand(createSuggestCommand());
3174
3521
  program.addCommand(createAuthCommands());
3522
+ program.addCommand(createConvertCommands());
3175
3523
  program.command("health").description("Check API health status").action(async () => {
3176
3524
  const base = getApiBaseUrlRoot();
3177
3525
  const response = await fetch(`${base}/health`, { method: "GET" });
@@ -3287,6 +3635,10 @@ async function main() {
3287
3635
  } else if (err.status === 403) {
3288
3636
  if (err.message.includes("publishing:write")) {
3289
3637
  output.info("Hint: publishing requires an API key with publishing:write scope.");
3638
+ } else if (err.message.includes("conversions:execute")) {
3639
+ output.info("Hint: converting requires an API key with conversions:execute scope.");
3640
+ } else if (/quota|Quota/.test(err.message)) {
3641
+ output.info("Hint: the conversion quota for this plan is spent. It resets at the start of the next period.");
3290
3642
  } else {
3291
3643
  output.info("Hint: check that the API key has the required scope and permission for this workspace/resource.");
3292
3644
  }