mdedit-cli 0.4.4 → 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
@@ -236,6 +236,28 @@ async function fetchErrorFromResponse(prefix, response) {
236
236
  }
237
237
  return new errors_default(`${prefix}. ${text}`, response.status, data);
238
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
+ }
239
261
  function coerceToFetchError(err) {
240
262
  const anyErr = err;
241
263
  const status = typeof anyErr?.status === "number" ? anyErr.status : 500;
@@ -310,7 +332,7 @@ function createSdkClient(config) {
310
332
  safeGists: async (workspaceId, articleId, urls) => (await withFetchError(() => getArticleSafeGists(workspaceId, articleId, urls, fetchers))).gists
311
333
  },
312
334
  collaboration: {
313
- checkpoint: (workspaceId, articleId) => withFetchError(() => checkpointCollaboration(workspaceId, articleId, fetchers))
335
+ checkpoint: (workspaceId, articleId, request = {}) => withFetchError(() => checkpointCollaboration(workspaceId, articleId, request, fetchers))
314
336
  },
315
337
  tools: {
316
338
  createUpload: (request) => withFetchError(() => createConversionUploadUrl(request, fetchers)),
@@ -328,7 +350,7 @@ function createSdkClient(config) {
328
350
  }
329
351
  };
330
352
  }
331
- 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, 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;
332
354
  var init_dist = __esm({
333
355
  "../sdk/dist/index.js"() {
334
356
  "use strict";
@@ -357,7 +379,8 @@ var init_dist = __esm({
357
379
  title: articleRequest.title,
358
380
  folderId: articleRequest.folderId,
359
381
  collaborative: articleRequest.collaborative ?? false,
360
- articleSettings: articleRequest.articleSettings
382
+ articleSettings: articleRequest.articleSettings,
383
+ tags: articleRequest.tags
361
384
  })
362
385
  });
363
386
  if (!response.ok) {
@@ -388,6 +411,9 @@ var init_dist = __esm({
388
411
  if (articleRequest.folderId !== void 0) {
389
412
  body.folderId = articleRequest.folderId;
390
413
  }
414
+ if (articleRequest.tags !== void 0) {
415
+ body.tags = articleRequest.tags;
416
+ }
391
417
  if (articleRequest.preview) {
392
418
  body.preview = articleRequest.preview;
393
419
  }
@@ -631,7 +657,8 @@ var init_dist = __esm({
631
657
  folderId: options.folderId,
632
658
  isPinned: options.isPinned,
633
659
  isArchived: options.isArchived,
634
- articleSettings: options.articleSettings
660
+ articleSettings: options.articleSettings,
661
+ tags: options.tags
635
662
  })
636
663
  }
637
664
  );
@@ -892,20 +919,6 @@ var init_dist = __esm({
892
919
  }
893
920
  return response.json();
894
921
  };
895
- checkpointCollaboration = async (workspaceId, articleId, fetchers) => {
896
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
897
- const response = await fetchV2(
898
- `/workspaces/${workspaceId}/articles/${articleId}/collaboration/checkpoint`,
899
- { method: "POST" }
900
- );
901
- if (!response.ok) {
902
- throw new errors_default(
903
- `Error checkpointing collaboration. ${await response.text()}`,
904
- response.status
905
- );
906
- }
907
- return response.json();
908
- };
909
922
  publishArticle = async (workspaceId, articleId, body, fetchers) => {
910
923
  const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
911
924
  const response = await fetchV2(
@@ -1876,7 +1889,6 @@ import { fileURLToPath as fileURLToPath2 } from "url";
1876
1889
  import { AgentClientHttpError } from "@mdedit/agent-client";
1877
1890
 
1878
1891
  // src/commands/article.ts
1879
- init_dist();
1880
1892
  init_output();
1881
1893
  import { Command, Option } from "commander";
1882
1894
  import inquirer from "inquirer";
@@ -2238,26 +2250,14 @@ function createDocumentCommand(commandName, deprecated) {
2238
2250
  anchor: { range: { from: 0, to: currentContent.length } },
2239
2251
  text: contentText
2240
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
+ }
2241
2258
  } finally {
2242
2259
  await session.close();
2243
2260
  }
2244
- const expectedContentHash = sha256Hex(contentText);
2245
- let checkpointedContentHash;
2246
- for (let attempt = 0; attempt < 20; attempt += 1) {
2247
- try {
2248
- const checkpoint = await client.collaboration.checkpoint(workspaceId, articleId);
2249
- checkpointedContentHash = checkpoint.targetHashes["content.md"];
2250
- if (checkpointedContentHash === expectedContentHash) break;
2251
- } catch (error) {
2252
- if (!(error instanceof FetchError2) || error.status !== 409 && error.status !== 503) {
2253
- throw error;
2254
- }
2255
- }
2256
- await new Promise((resolve) => setTimeout(resolve, 500));
2257
- }
2258
- if (checkpointedContentHash !== expectedContentHash) {
2259
- throw new Error("Collaborative content did not reach a durable checkpoint within 10 seconds.");
2260
- }
2261
2261
  } else {
2262
2262
  await client.article.saveContent(workspaceId, articleId, contentText, {
2263
2263
  baseContentRevision: 0,
@@ -2433,6 +2433,7 @@ function createDocumentCommand(commandName, deprecated) {
2433
2433
  let session;
2434
2434
  let editError;
2435
2435
  let result;
2436
+ let receipt;
2436
2437
  try {
2437
2438
  session = await openArticleSession({
2438
2439
  credentialProvider,
@@ -2442,6 +2443,7 @@ function createDocumentCommand(commandName, deprecated) {
2442
2443
  apiUrl: getApiUrlRaw()
2443
2444
  });
2444
2445
  result = await session.edit(operations);
2446
+ receipt = await session.ensureDurable();
2445
2447
  } catch (error) {
2446
2448
  editError = error;
2447
2449
  throw error;
@@ -2454,8 +2456,15 @@ function createDocumentCommand(commandName, deprecated) {
2454
2456
  }
2455
2457
  }
2456
2458
  }
2457
- if (!session || !result) throw new Error("Document edit did not return a result.");
2458
- 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
+ });
2459
2468
  if (result.conflicts.length > 0) {
2460
2469
  output.warning("The edit was applied with overlapping remote changes; re-read the document before continuing.");
2461
2470
  process.exitCode = CLI_EXIT_CODES.EDIT_CONFLICT;
@@ -3401,6 +3410,43 @@ function defaultOutputPath(inputFile, outputFormat) {
3401
3410
  const ext = outputFormat === "markdown" ? "md" : outputFormat;
3402
3411
  return `${stem}.${ext}`;
3403
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
+ }
3404
3450
  function createConvertCommands() {
3405
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", `
3406
3452
  Examples:
@@ -3408,7 +3454,7 @@ Examples:
3408
3454
  $ mdedit convert notes.md --to pdf --out notes.pdf
3409
3455
  $ mdedit convert report.docx --to md
3410
3456
  `).action(async (inputFile, options) => {
3411
- requireApiKey();
3457
+ await ensureConvertAuthentication();
3412
3458
  const client = getApiClient();
3413
3459
  const conversion = resolveConversion(inputFile, options.to, options.from);
3414
3460
  const outPath = options.out || defaultOutputPath(inputFile, conversion.outputFormat);