@arbidocs/react 0.4.13 → 0.4.14

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.
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunk3MFESAPI_cjs = require('../chunk-3MFESAPI.cjs');
3
+ var chunkMQRBPFOZ_cjs = require('../chunk-MQRBPFOZ.cjs');
4
4
  var chunkPATLJSAO_cjs = require('../chunk-PATLJSAO.cjs');
5
5
  var chunkWBWXP2DN_cjs = require('../chunk-WBWXP2DN.cjs');
6
6
  require('../chunk-S6A6FSG7.cjs');
@@ -134,7 +134,7 @@ function flattenChunks(chunks, options) {
134
134
  const text = (chunks ?? []).map((c) => (c.content ?? "").trim()).join("\n\n");
135
135
  if (!options?.unescape) return text;
136
136
  return chunkPATLJSAO_cjs.normalizeMarkdown(
137
- chunk3MFESAPI_cjs.repairParsedStructure(chunk3MFESAPI_cjs.repairParsedTitle(chunk3MFESAPI_cjs.unescapeMarkdown(text)))
137
+ chunkMQRBPFOZ_cjs.repairParsedStructure(chunkMQRBPFOZ_cjs.repairParsedTitle(chunkMQRBPFOZ_cjs.unescapeMarkdown(text)))
138
138
  ).replace(/\n$/, "");
139
139
  }
140
140
  var DOC_ID = /^doc/;
@@ -342,7 +342,7 @@ function useArtifactText(docId, options) {
342
342
  const enabled = (options?.enabled ?? true) && isDocumentId(docId) && arbi.hasWorkspace;
343
343
  const query = reactQuery.useQuery({
344
344
  // Under the shared `parsedDoc` key, so a document's invalidation reaches it too.
345
- queryKey: [...chunk3MFESAPI_cjs.arbiQueryKeys.parsedDoc(docId ?? "", "marker"), "artifact-text"],
345
+ queryKey: [...chunkMQRBPFOZ_cjs.arbiQueryKeys.parsedDoc(docId ?? "", "marker"), "artifact-text"],
346
346
  queryFn: async () => {
347
347
  const parsed = await arbi.documents.getParsedContent(docId, "marker");
348
348
  if (!parsed.chunks?.some((c) => c.content?.trim())) throw new NotParsedYetError();
@@ -384,7 +384,7 @@ function useArtifactText(docId, options) {
384
384
 
385
385
  // src/artifacts/useArtifactSession.ts
386
386
  function useArtifactVersions(workspaceId, docId) {
387
- const { data: documents } = chunk3MFESAPI_cjs.useDocuments(workspaceId);
387
+ const { data: documents } = chunkMQRBPFOZ_cjs.useDocuments(workspaceId);
388
388
  return react.useMemo(
389
389
  () => toArtifactVersions(buildVersionChain(documents ?? [], docId)),
390
390
  [documents, docId]
@@ -406,7 +406,7 @@ function useSaveArtifactVersion() {
406
406
  }
407
407
  );
408
408
  if (workspaceId) {
409
- await queryClient.invalidateQueries({ queryKey: chunk3MFESAPI_cjs.arbiQueryKeys.documents(workspaceId) });
409
+ await queryClient.invalidateQueries({ queryKey: chunkMQRBPFOZ_cjs.arbiQueryKeys.documents(workspaceId) });
410
410
  }
411
411
  return { docId: result.doc_ext_ids?.[0] };
412
412
  }
@@ -530,7 +530,8 @@ function useStreamedArtifact({
530
530
  artifacts,
531
531
  workspaceId,
532
532
  settled,
533
- clean = chunk3MFESAPI_cjs.cleanDraftMarkdown,
533
+ clean,
534
+ onCleaned,
534
535
  configId,
535
536
  parseRetry
536
537
  }) {
@@ -539,6 +540,7 @@ function useStreamedArtifact({
539
540
  const [saved, setSaved] = react.useState(null);
540
541
  const [saveError, setSaveError] = react.useState(null);
541
542
  const [attempt, setAttempt] = react.useState(0);
543
+ const [cleaned, setCleaned] = react.useState(null);
542
544
  const started = react.useRef(null);
543
545
  const content = artifact?.content ?? "";
544
546
  const title = artifact?.title ?? "Draft";
@@ -549,9 +551,22 @@ function useStreamedArtifact({
549
551
  if (!needsSave || started.current === key) return;
550
552
  started.current = key;
551
553
  setSaveError(null);
554
+ let stored;
555
+ if (clean) stored = clean(content);
556
+ else {
557
+ const report = chunkMQRBPFOZ_cjs.cleanDraftWithReport(content);
558
+ stored = report.text;
559
+ setCleaned(report);
560
+ onCleaned?.(report);
561
+ if (report.guarded) {
562
+ console.warn(
563
+ `[useStreamedArtifact] the draft cleanup would have lost content; stored the ${report.stage} text instead (kept ${Math.round(report.ratio * 100)}%, changed by: ${report.changedBy.join(", ") || "nothing"})`
564
+ );
565
+ }
566
+ }
552
567
  mutateAsync({
553
568
  title,
554
- content: clean(content),
569
+ content: stored,
555
570
  workspaceId,
556
571
  configId,
557
572
  wpType: "artifact"
@@ -575,36 +590,40 @@ function useStreamedArtifact({
575
590
  else if (text.status === "error" || text.status === "ready") phase = "error";
576
591
  else phase = "parsing";
577
592
  const error = phase !== "error" ? null : saveError ?? text.error ?? new Error("The document has no text to edit");
578
- return { phase, artifact, docId, error, retry };
593
+ return { phase, artifact, docId, error, cleaned, retry };
579
594
  }
580
595
 
581
596
  Object.defineProperty(exports, "cleanDraftMarkdown", {
582
597
  enumerable: true,
583
- get: function () { return chunk3MFESAPI_cjs.cleanDraftMarkdown; }
598
+ get: function () { return chunkMQRBPFOZ_cjs.cleanDraftMarkdown; }
599
+ });
600
+ Object.defineProperty(exports, "cleanDraftWithReport", {
601
+ enumerable: true,
602
+ get: function () { return chunkMQRBPFOZ_cjs.cleanDraftWithReport; }
584
603
  });
585
604
  Object.defineProperty(exports, "promoteBoldTitle", {
586
605
  enumerable: true,
587
- get: function () { return chunk3MFESAPI_cjs.promoteBoldTitle; }
606
+ get: function () { return chunkMQRBPFOZ_cjs.promoteBoldTitle; }
588
607
  });
589
608
  Object.defineProperty(exports, "repairParsedStructure", {
590
609
  enumerable: true,
591
- get: function () { return chunk3MFESAPI_cjs.repairParsedStructure; }
610
+ get: function () { return chunkMQRBPFOZ_cjs.repairParsedStructure; }
592
611
  });
593
612
  Object.defineProperty(exports, "repairParsedTitle", {
594
613
  enumerable: true,
595
- get: function () { return chunk3MFESAPI_cjs.repairParsedTitle; }
614
+ get: function () { return chunkMQRBPFOZ_cjs.repairParsedTitle; }
596
615
  });
597
616
  Object.defineProperty(exports, "stripAgentPreamble", {
598
617
  enumerable: true,
599
- get: function () { return chunk3MFESAPI_cjs.stripAgentPreamble; }
618
+ get: function () { return chunkMQRBPFOZ_cjs.stripAgentPreamble; }
600
619
  });
601
620
  Object.defineProperty(exports, "unescapeMarkdown", {
602
621
  enumerable: true,
603
- get: function () { return chunk3MFESAPI_cjs.unescapeMarkdown; }
622
+ get: function () { return chunkMQRBPFOZ_cjs.unescapeMarkdown; }
604
623
  });
605
624
  Object.defineProperty(exports, "unwrapCitationLinks", {
606
625
  enumerable: true,
607
- get: function () { return chunk3MFESAPI_cjs.unwrapCitationLinks; }
626
+ get: function () { return chunkMQRBPFOZ_cjs.unwrapCitationLinks; }
608
627
  });
609
628
  Object.defineProperty(exports, "buildHybridRedlineMarkdown", {
610
629
  enumerable: true,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/artifacts/redline-engine.ts","../../src/artifacts/useRedline.ts","../../src/artifacts/versions.ts","../../src/artifacts/useArtifactEditSession.ts","../../src/artifacts/useArtifactText.ts","../../src/artifacts/useArtifactSession.ts","../../src/artifacts/renderArtifactMarkdown.tsx","../../src/artifacts/useStreamedArtifact.ts"],"names":["buildHybridRedlineMarkdown","buildHybridRedlineWithRegions","revertRedlineRegion","useState","useRef","useEffect","normalizeMarkdown","useCallback","useMemo","repairParsedStructure","repairParsedTitle","unescapeMarkdown","content","useArbi","useQuery","arbiQueryKeys","useDocuments","useQueryClient","useMutation","jsx","MarkdownRenderer","cleanDraftMarkdown"],"mappings":";;;;;;;;;;;;AAsBO,IAAM,uBAAA,GAAyC;AAAA,EACpD,YAAA,EAAcA,4CAAA;AAAA,EACd,uBAAA,EAAyBC,+CAAA;AAAA,EACzB,YAAA,EAAcC;AAChB;ACUO,SAAS,UAAA,CAAW;AAAA,EACzB,QAAA;AAAA,EACA,WAAA;AAAA,EACA,SAAA,GAAY,KAAA;AAAA,EACZ,WAAA,GAAc,KAAA;AAAA,EACd,MAAA,GAAS;AACX,CAAA,EAAwC;AACtC,EAAA,MAAM,CAAC,OAAO,QAAQ,CAAA,GAAIC,eAAuB,EAAE,IAAA,EAAM,QAAQ,CAAA;AACjE,EAAA,MAAM,YAAA,GAA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,EAAW,SAAS,CAAC,CAAA;AAEzB,EAAA,IAAI,KAAA;AACJ,EAAA,IAAI,CAAC,OAAA,IAAW,CAAC,QAAA,EAAU,KAAA,GAAQ,WAAA;AAAA,OAAA,IAC1B,WAAW,KAAA,GAAQ,OAAA;AAAA,OAAA,IACnB,CAAC,KAAA,EAAO,KAAA,GAAQ,SAAA,GAAY,YAAA,GAAe,WAAA;AAAA,OAAA,IAC3C,IAAA,CAAK,MAAA,KAAW,OAAA,IAAW,IAAA,CAAK,MAAM,KAAA,GAAQ,OAAA;AAAA,OAAA,IAC9C,KAAK,MAAA,KAAW,OAAA,IAAW,IAAA,CAAK,MAAA,KAAW,SAAS,KAAA,GAAQ,OAAA;AAAA,OAChE,KAAA,GAAQ,SAAA;AAEb,EAAA,MAAM,KAAA,GACJ,UAAU,OAAA,GACN,IAAA,GACC,aAAa,IAAA,CAAK,KAAA,IAAS,IAAI,KAAA,CAAM,kCAAkC,CAAA;AAC9E,EAAA,OAAO,EAAE,KAAA,EAAO,QAAA,EAAU,KAAA,EAAO,OAAO,KAAA,EAAM;AAChD","file":"index.cjs","sourcesContent":["import {\n buildHybridRedlineMarkdown,\n buildHybridRedlineWithRegions,\n revertRedlineRegion,\n type RedlineWithRegions,\n} from './redline-diff'\n\n/**\n * Where a redline is computed. The default runs on the calling thread; a host with large\n * documents passes an engine backed by a Web Worker (for example a Comlink proxy exposing the same\n * three functions) so typing never waits on a diff.\n */\nexport interface RedlineEngine {\n buildRedline(baseText: string, compareText: string): string | Promise<string>\n buildRedlineWithRegions(\n baseText: string,\n compareText: string\n ): RedlineWithRegions | Promise<RedlineWithRegions>\n revertRegion(baseText: string, compareText: string, regionId: string): string | Promise<string>\n}\n\n/** Main-thread engine: the pure functions of `redline-diff`. */\nexport const mainThreadRedlineEngine: RedlineEngine = {\n buildRedline: buildHybridRedlineMarkdown,\n buildRedlineWithRegions: buildHybridRedlineWithRegions,\n revertRegion: revertRedlineRegion,\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { RedlineRegion } from './redline-diff'\nimport { normalizeMarkdown } from './normalize-markdown'\nimport { mainThreadRedlineEngine, type RedlineEngine } from './redline-engine'\n\n/** What a redline view can show. Mirrors the status parts of `@arbidocs/blocks/artifacts`. */\nexport type RedlineState =\n | { kind: 'idle' }\n | { kind: 'computing' }\n | { kind: 'ready'; markdown: string; regions: RedlineRegion[] }\n | { kind: 'identical' }\n | { kind: 'unavailable' }\n\nexport interface UseRedlineOptions {\n /** The older side. `null` means the text could not be loaded; `undefined` means not chosen. */\n baseText: string | null | undefined\n /** The newer side (a loaded version, or the live edit buffer). */\n compareText: string | null | undefined\n /** Either text is still being fetched. */\n isLoading?: boolean\n /** Tag every change with a stable id so a view can offer per-change undo. */\n withRegions?: boolean\n /** Defaults to the main thread; pass a worker-backed engine for big documents. */\n engine?: RedlineEngine\n}\n\nexport interface UseRedlineResult {\n state: RedlineState\n /** Undo one change: resolves with the compare text rebuilt without it (null if nothing changed). */\n revertRegion: (regionId: string) => Promise<string | null>\n}\n\n/**\n * Track-changes between two texts. Stale results are dropped when the inputs change mid-compute,\n * and a failed diff reports `unavailable` instead of throwing into the render.\n */\nexport function useRedline({\n baseText,\n compareText,\n isLoading = false,\n withRegions = false,\n engine = mainThreadRedlineEngine,\n}: UseRedlineOptions): UseRedlineResult {\n const [state, setState] = useState<RedlineState>({ kind: 'idle' })\n const requestIdRef = useRef(0)\n\n useEffect(() => {\n if (baseText === undefined || compareText === undefined) {\n setState({ kind: 'idle' })\n return\n }\n if (isLoading) {\n setState({ kind: 'computing' })\n return\n }\n if (baseText === null || compareText === null) {\n setState({ kind: 'unavailable' })\n return\n }\n if (\n baseText === compareText ||\n normalizeMarkdown(baseText) === normalizeMarkdown(compareText)\n ) {\n setState({ kind: 'identical' })\n return\n }\n\n const id = ++requestIdRef.current\n let cancelled = false\n setState({ kind: 'computing' })\n Promise.resolve(\n withRegions\n ? engine.buildRedlineWithRegions(baseText, compareText)\n : Promise.resolve(engine.buildRedline(baseText, compareText)).then((markdown) => ({\n markdown,\n regions: [] as RedlineRegion[],\n }))\n )\n .then((result) => {\n if (cancelled || id !== requestIdRef.current) return\n setState({ kind: 'ready', markdown: result.markdown, regions: result.regions })\n })\n .catch(() => {\n if (cancelled || id !== requestIdRef.current) return\n setState({ kind: 'unavailable' })\n })\n return () => {\n cancelled = true\n }\n }, [baseText, compareText, isLoading, withRegions, engine])\n\n // The latest texts, so `revertRegion` stays referentially stable while the user types.\n const latest = useRef({ baseText, compareText })\n useEffect(() => {\n latest.current = { baseText, compareText }\n }, [baseText, compareText])\n\n const revertRegion = useCallback(\n async (regionId: string): Promise<string | null> => {\n const { baseText: base, compareText: compare } = latest.current\n if (!base || !compare) return null\n try {\n const next = await engine.revertRegion(base, compare, regionId)\n return next !== normalizeMarkdown(compare) ? next : null\n } catch {\n return null\n }\n },\n [engine]\n )\n\n return useMemo(() => ({ state, revertRegion }), [state, revertRegion])\n}\n","/**\n * Version lineage of an artifact. Every save creates a NEW document whose `parent_ext_id` is the\n * version it was saved from, so a lineage is a tree (a save from an old version is a deliberate\n * branch). Computed from a document list the host already has; no extra request.\n */\n\nimport { repairParsedStructure, repairParsedTitle, unescapeMarkdown } from '../ai/stored-markdown'\nimport { normalizeMarkdown } from './normalize-markdown'\n\n/** The fields of a workspace document the lineage needs (structurally a subset of the API type). */\nexport interface VersionedDoc {\n external_id?: string | null\n parent_ext_id?: string | null\n file_name?: string | null\n created_at?: string | null\n}\n\n/** One row of a version list. Matches `VersionEntry` of `@arbidocs/blocks/artifacts`. */\nexport interface ArtifactVersion {\n id: string\n /** File name as stored. */\n name: string\n /** ISO timestamp. */\n createdAt: string\n /** The version this one was saved from. */\n parentId?: string | null\n}\n\n/**\n * The whole lineage of `docId` (root first, then oldest to newest), or `[]` when the document is\n * not in `docs`. Cycle-safe.\n */\nexport function buildVersionChain<T extends VersionedDoc>(\n docs: readonly T[],\n docId: string | null | undefined\n): T[] {\n if (!docId) return []\n const byId = new Map<string, T>()\n for (const d of docs) if (d.external_id) byId.set(d.external_id, d)\n\n const current = byId.get(docId)\n if (!current) return []\n\n let root = current\n const up = new Set<string>()\n while (\n root.parent_ext_id &&\n byId.has(root.parent_ext_id) &&\n root.external_id &&\n !up.has(root.external_id)\n ) {\n up.add(root.external_id)\n root = byId.get(root.parent_ext_id) as T\n }\n\n const byParent = new Map<string, T[]>()\n for (const d of docs) {\n if (d.parent_ext_id) {\n const siblings = byParent.get(d.parent_ext_id) ?? []\n siblings.push(d)\n byParent.set(d.parent_ext_id, siblings)\n }\n }\n const out: T[] = []\n const visited = new Set<string>()\n const walk = (d: T): void => {\n if (!d.external_id || visited.has(d.external_id)) return\n visited.add(d.external_id)\n out.push(d)\n for (const child of byParent.get(d.external_id) ?? []) walk(child)\n }\n walk(root)\n\n out.sort((a, b) => (a.created_at ?? '').localeCompare(b.created_at ?? ''))\n return out\n}\n\n/** The lineage of `docId` as plain version rows. */\nexport function toArtifactVersions(chain: readonly VersionedDoc[]): ArtifactVersion[] {\n return chain.flatMap((d) =>\n d.external_id\n ? [\n {\n id: d.external_id,\n name: d.file_name ?? '',\n createdAt: d.created_at ?? '',\n parentId: d.parent_ext_id,\n },\n ]\n : []\n )\n}\n\n/**\n * \"v2\": the 1-based position of `docId` in its lineage. `null` when there is nothing to tell apart\n * (the lineage is just this document, or it is unknown), so unversioned documents stay unlabelled.\n */\nexport function versionLabel(\n versions: readonly ArtifactVersion[],\n docId: string | null | undefined\n): string | null {\n if (!docId || versions.length <= 1) return null\n const index = versions.findIndex((v) => v.id === docId)\n return index === -1 ? null : `v${index + 1}`\n}\n\n/**\n * Join parsed chunks into one markdown text (blank line between chunks).\n *\n * `unescape: true` for an artifact stored from markdown: the backend's parse of a `.md` escapes\n * markdown punctuation, which `unescapeMarkdown` undoes (see its rule), and mangles its title\n * (`repairParsedTitle`, `repairParsedStructure`: doubled headings, `- ` stacked on list markers,\n * one-line tables), then normalised. Leave it off for the parse\n * of a PDF or Word file.\n */\nexport function flattenChunks(\n chunks: readonly { content?: string | null }[] | null | undefined,\n options?: { unescape?: boolean }\n): string {\n const text = (chunks ?? []).map((c) => (c.content ?? '').trim()).join('\\n\\n')\n if (!options?.unescape) return text\n // Canonical spelling last, so the text an editor starts from is what a save would persist.\n return normalizeMarkdown(\n repairParsedStructure(repairParsedTitle(unescapeMarkdown(text)))\n ).replace(/\\n$/, '')\n}\n\n/** The backend's pattern for a document id. Anything else (a streamed draft's placeholder) is local. */\nconst DOC_ID = /^doc/\n\n/** Is `id` a real, saved document id? Local drafts have placeholder ids and no backend document. */\nexport function isDocumentId(id: string | null | undefined): id is string {\n return !!id && DOC_ID.test(id)\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { normalizeMarkdown } from './normalize-markdown'\nimport { useRedline, type UseRedlineResult } from './useRedline'\nimport type { RedlineEngine } from './redline-engine'\n\n/** What a save reports back. `docId` is the new version when the backend already knows it. */\nexport interface ArtifactSaveResult {\n docId?: string\n /** 1-based number of the version that was just saved (1 for the first save of a draft). */\n version?: number\n}\n\nexport interface ArtifactEditSessionOptions {\n /** The artifact being edited. Changing it discards the buffer and any comparison. */\n docId: string | null | undefined\n /**\n * The saved text of the open version. `undefined` while it loads; whenever it changes the\n * baseline follows it (a version arriving from the realtime channel, a finished stream).\n */\n baseline: string | undefined\n /**\n * A new document the user types from scratch: open straight in the editor, seeded with\n * `initialContent`, instead of showing a read-only view. Read when `docId` changes.\n */\n startEditing?: boolean\n initialContent?: string\n /** The version this one was saved from. Offering \"compare with previous\" needs it. */\n parentId?: string | null\n /** Controlled comparison target. Omit for an uncontrolled one the session owns. */\n compareId?: string | null\n onCompareChange?: (id: string | null) => void\n /** The saved text of the compare target (the older side of the diff). */\n compareText?: string | null\n compareLoading?: boolean\n /** Starting a comparison opens the editor with track changes on (default true). */\n compareOpensEditor?: boolean\n /** Persist the buffer as a NEW version. Rejecting keeps the buffer so nothing is lost. */\n save: (content: string) => Promise<ArtifactSaveResult | void>\n onSaved?: (result: ArtifactSaveResult, content: string) => void\n onSaveError?: (error: unknown) => void\n /** Every buffer change (a host keeps a draft store in sync with it). */\n onContentChange?: (content: string) => void\n /** The unsaved-changes flag, for a host that warns before a panel is closed. */\n onDirtyChange?: (dirty: boolean) => void\n /** Where the diff runs. Defaults to the main thread. */\n redlineEngine?: RedlineEngine\n /** Typing is never debounced; the diff trails the buffer by this long. Default 300ms. */\n diffDelayMs?: number\n}\n\nexport interface ArtifactEditSession {\n isEditing: boolean\n /** The saved text of the open version. */\n baseline: string\n /** The text in the editor (the baseline until the first edit). */\n content: string\n hasChanges: boolean\n isSaving: boolean\n canCompare: boolean\n compareId: string | null\n showTrackChanges: boolean\n /** Track changes between the compare target and the (debounced) buffer. */\n redline: UseRedlineResult\n startEdit: () => void\n /** Discard the buffer and any comparison; back to the rendered view. */\n cancel: () => void\n /** Save the buffer as a new version. Resolves false when it failed (the buffer is kept). */\n save: () => Promise<boolean>\n /** The editor's `onChange`; also replaces the buffer (for example after an undo-this-change). */\n change: (markdown: string) => void\n /** The editor's `onNormalized`: adopt its canonical form as the baseline so Save does not fire. */\n normalized: (markdown: string) => void\n /** Compare with the previous version (when no id is given). */\n compare: (id?: string) => void\n stopCompare: () => void\n setShowTrackChanges: (show: boolean) => void\n /** Undo one tracked change in the buffer. */\n revertRegion: (regionId: string) => Promise<void>\n}\n\n/**\n * The state machine of an artifact edit session, with no SDK and no network: the edit buffer and\n * its baseline, the dirty flag, immutable-version saves and a track-changes comparison. A host\n * supplies the saved text and a `save` function (see `useArtifactSession` for the SDK binding).\n */\nexport function useArtifactEditSession(options: ArtifactEditSessionOptions): ArtifactEditSession {\n const {\n docId,\n baseline: loadedBaseline,\n startEditing = false,\n initialContent,\n parentId,\n compareId: controlledCompareId,\n onCompareChange,\n compareText,\n compareLoading = false,\n compareOpensEditor = true,\n save: persist,\n onSaved,\n onSaveError,\n onContentChange,\n onDirtyChange,\n redlineEngine,\n diffDelayMs = 300,\n } = options\n\n const [isEditing, setIsEditing] = useState(false)\n const [baseline, setBaseline] = useState('')\n const [buffer, setBuffer] = useState('')\n const [isSaving, setIsSaving] = useState(false)\n const [showTrackChanges, setShowTrackChanges] = useState(false)\n const [ownCompareId, setOwnCompareId] = useState<string | null>(null)\n const controlled = controlledCompareId !== undefined\n const compareId = controlled ? controlledCompareId : ownCompareId\n\n const setCompareId = useCallback(\n (id: string | null) => {\n if (!controlled) setOwnCompareId(id)\n onCompareChange?.(id)\n },\n [controlled, onCompareChange]\n )\n\n // The latest values for callbacks that must not change identity while the user types.\n const latest = useRef({ buffer, baseline, isEditing, initialContent })\n latest.current = { buffer, baseline, isEditing, initialContent }\n\n // The baseline follows the loaded text. A draft has none and seeds itself below.\n useEffect(() => {\n if (loadedBaseline !== undefined) setBaseline(loadedBaseline)\n }, [loadedBaseline])\n\n // Another artifact: drop stale edits and comparison. A new typed document starts in the editor.\n useEffect(() => {\n if (startEditing) {\n const seed = latest.current.initialContent ?? ''\n setIsEditing(true)\n setBaseline(seed)\n setBuffer(seed)\n } else {\n setIsEditing(false)\n setBuffer('')\n }\n setCompareId(null)\n setShowTrackChanges(false)\n // Only the identity of the artifact resets the session.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [docId])\n\n const startEdit = useCallback(() => {\n setBuffer(latest.current.baseline)\n setIsEditing(true)\n }, [])\n\n const stopCompare = useCallback(() => {\n setCompareId(null)\n setShowTrackChanges(false)\n }, [setCompareId])\n\n const cancel = useCallback(() => {\n setIsEditing(false)\n setBuffer('')\n stopCompare()\n }, [stopCompare])\n\n const compare = useCallback(\n (id?: string) => {\n const target = id ?? parentId\n if (target) setCompareId(target)\n },\n [parentId, setCompareId]\n )\n\n // Comparing and editing are one surface: a comparison opens the editor with the diff showing,\n // like Word's Compare yields tracked changes you can keep typing through.\n const hasBaseline = baseline !== ''\n useEffect(() => {\n if (!compareId || !compareOpensEditor || !hasBaseline) return\n if (!latest.current.isEditing) startEdit()\n setShowTrackChanges(true)\n }, [compareId, compareOpensEditor, hasBaseline, startEdit])\n\n const save = useCallback(async (): Promise<boolean> => {\n // Persist the canonical spelling so the editor's gratuitous escapes never reach a version.\n const raw = latest.current.buffer\n const normalised = normalizeMarkdown(raw)\n const content = raw.endsWith('\\n') ? normalised : normalised.replace(/\\n$/, '')\n setIsSaving(true)\n try {\n const result = (await persist(content)) ?? {}\n setBaseline(content)\n setIsEditing(false)\n stopCompare()\n onSaved?.(result, content)\n return true\n } catch (error) {\n onSaveError?.(error)\n return false\n } finally {\n setIsSaving(false)\n }\n }, [persist, stopCompare, onSaved, onSaveError])\n\n const content = buffer || baseline\n const hasChanges = isEditing && !!buffer && buffer !== baseline\n useEffect(() => {\n onDirtyChange?.(hasChanges)\n return () => onDirtyChange?.(false)\n }, [hasChanges, onDirtyChange])\n\n const setContent = useCallback(\n (markdown: string) => {\n setBuffer(markdown)\n onContentChange?.(markdown)\n },\n [onContentChange]\n )\n const normalized = useCallback((markdown: string) => {\n setBaseline(markdown)\n setBuffer(markdown)\n }, [])\n\n // The diff trails the buffer so it runs on a settled text.\n const [diffContent, setDiffContent] = useState(content)\n useEffect(() => {\n const id = setTimeout(() => setDiffContent(content), diffDelayMs)\n return () => clearTimeout(id)\n }, [content, diffDelayMs])\n\n const redline = useRedline({\n baseText: compareId ? compareText : undefined,\n compareText: compareId ? diffContent || baseline : undefined,\n isLoading: compareLoading,\n withRegions: true,\n engine: redlineEngine,\n })\n const { revertRegion: revertInRedline } = redline\n const revertRegion = useCallback(\n async (regionId: string): Promise<void> => {\n const next = await revertInRedline(regionId)\n if (next !== null) setContent(next)\n },\n [revertInRedline, setContent]\n )\n\n return useMemo(\n () => ({\n isEditing,\n baseline,\n content,\n hasChanges,\n isSaving,\n canCompare: !!parentId && !compareId,\n compareId,\n showTrackChanges,\n redline,\n startEdit,\n cancel,\n save,\n change: setContent,\n normalized,\n compare,\n stopCompare,\n setShowTrackChanges,\n revertRegion,\n }),\n [\n isEditing,\n baseline,\n content,\n hasChanges,\n isSaving,\n parentId,\n compareId,\n showTrackChanges,\n redline,\n startEdit,\n cancel,\n save,\n setContent,\n normalized,\n compare,\n stopCompare,\n revertRegion,\n ]\n )\n}\n","import { useCallback, useMemo } from 'react'\nimport { useQuery } from '@tanstack/react-query'\nimport { useArbi } from '../useArbi'\nimport { arbiQueryKeys } from '../hooks'\nimport { flattenChunks, isDocumentId } from './versions'\n\n/**\n * Where the text of a stored artifact is:\n * - `loading`: the first request is in flight (or there is no document yet);\n * - `parsing`: the backend has not finished parsing the upload (the endpoint answers 404, 422 or\n * 500, or an empty parse, for a few seconds after an upload) and the hook is retrying;\n * - `ready`: the text is here (an empty document is `ready` with `text: null`);\n * - `error`: the retries ran out, or the request was refused (401/403).\n */\nexport type ArtifactTextStatus = 'loading' | 'parsing' | 'ready' | 'error'\n\n/** How long `useArtifactText` keeps asking while a document is still being parsed. */\nexport interface ArtifactTextRetry {\n /** Retries after the first request. Default 12. */\n attempts?: number\n /** Delay before the first retry; it grows by 1.6x each time. Default 1000 ms. */\n baseDelayMs?: number\n /** Cap for one delay. Default 5000 ms (12 retries are about 50 s in all). */\n maxDelayMs?: number\n}\n\nexport const DEFAULT_ARTIFACT_TEXT_RETRY: Required<ArtifactTextRetry> = {\n attempts: 12,\n baseDelayMs: 1000,\n maxDelayMs: 5000,\n}\n\n/** Thrown inside the query when the parse has no text yet, so that it is retried like a 500. */\nclass NotParsedYetError extends Error {\n constructor() {\n super('The document has no parsed text yet')\n }\n}\n\nconst isRefusal = (error: unknown): boolean => {\n const status = error as { status?: number; response?: { status?: number } } | null\n const code = status?.status ?? status?.response?.status\n return code === 401 || code === 403\n}\n\nexport interface ArtifactText {\n /**\n * The markdown, clean: `undefined` while `loading` or `parsing`, `null` when there is none (an\n * empty document, or `error`).\n */\n text: string | null | undefined\n /** `status` is `loading` or `parsing`. */\n isLoading: boolean\n status: ArtifactTextStatus\n /** The last request error while `parsing` or after `error`. */\n error: Error | null\n /** Ask again now (after an `error`). */\n retry: () => void\n}\n\n/**\n * The saved markdown of an artifact version (its parsed chunks, joined and unescaped).\n *\n * A freshly uploaded document is parsed asynchronously, and for roughly 3 to 20 seconds the parsed\n * content endpoint answers 404, 422 or 500 (or an empty parse). The hook therefore retries with a\n * growing delay (see `ArtifactTextRetry`) and reports `status: 'parsing'` meanwhile, so a host can\n * show \"Preparing editor...\" instead of opening an editor on an empty baseline. After the last\n * retry the status is `error`; `retry()` starts a new round.\n *\n * The text is run through `unescapeMarkdown`: an artifact is always stored from markdown, and the\n * backend's parse of a `.md` escapes its punctuation.\n */\nexport function useArtifactText(\n docId: string | null | undefined,\n options?: { enabled?: boolean; retry?: ArtifactTextRetry }\n): ArtifactText {\n const arbi = useArbi()\n const { attempts, baseDelayMs, maxDelayMs } = {\n ...DEFAULT_ARTIFACT_TEXT_RETRY,\n ...options?.retry,\n }\n // A local draft (placeholder id) has no backend document: asking for its text would be a 422.\n const enabled = (options?.enabled ?? true) && isDocumentId(docId) && arbi.hasWorkspace\n const query = useQuery({\n // Under the shared `parsedDoc` key, so a document's invalidation reaches it too.\n queryKey: [...arbiQueryKeys.parsedDoc(docId ?? '', 'marker'), 'artifact-text'] as const,\n queryFn: async () => {\n const parsed = (await arbi.documents.getParsedContent(docId as string, 'marker')) as {\n chunks?: { content?: string | null }[]\n }\n if (!parsed.chunks?.some((c) => c.content?.trim())) throw new NotParsedYetError()\n return flattenChunks(parsed.chunks, { unescape: true })\n },\n enabled,\n retry: (failureCount, error) => !isRefusal(error) && failureCount < attempts,\n retryDelay: (failureCount) => Math.min(baseDelayMs * 1.6 ** failureCount, maxDelayMs),\n })\n\n const { refetch } = query\n const retry = useCallback(() => void refetch(), [refetch])\n\n return useMemo<ArtifactText>(() => {\n const error = query.error\n const neverParsed = error instanceof NotParsedYetError\n let status: ArtifactTextStatus = 'loading'\n if (!enabled) status = 'loading'\n else if (query.isSuccess || (query.isError && neverParsed)) status = 'ready'\n else if (query.isError) status = 'error'\n else if (query.failureCount > 0) status = 'parsing'\n const text = !enabled\n ? undefined\n : query.isSuccess\n ? query.data\n : status === 'ready' || status === 'error'\n ? null\n : undefined\n return {\n text,\n isLoading: enabled && (status === 'loading' || status === 'parsing'),\n status,\n error: status === 'ready' ? null : (error ?? query.failureReason ?? null),\n retry,\n }\n }, [\n enabled,\n query.isSuccess,\n query.isError,\n query.data,\n query.error,\n query.failureCount,\n query.failureReason,\n retry,\n ])\n}\n","import { useCallback, useMemo, useState } from 'react'\nimport { useMutation, useQueryClient } from '@tanstack/react-query'\nimport { useArbi } from '../useArbi'\nimport { arbiQueryKeys, useDocuments } from '../hooks'\nimport { useArtifactText, type ArtifactTextStatus } from './useArtifactText'\nimport {\n buildVersionChain,\n isDocumentId,\n toArtifactVersions,\n versionLabel,\n type ArtifactVersion,\n} from './versions'\nimport {\n useArtifactEditSession,\n type ArtifactEditSession,\n type ArtifactEditSessionOptions,\n type ArtifactSaveResult,\n} from './useArtifactEditSession'\n\n/** The version lineage of an artifact in a workspace, oldest first. */\nexport function useArtifactVersions(\n workspaceId: string | undefined,\n docId: string | null | undefined\n): ArtifactVersion[] {\n const { data: documents } = useDocuments(workspaceId)\n return useMemo(\n () => toArtifactVersions(buildVersionChain(documents ?? [], docId)),\n [documents, docId]\n )\n}\n\nexport interface SaveArtifactVersionInput {\n /** File name of the new version (`.md` is added when missing). */\n title: string\n content: string\n /** The version this one is saved from; omit for a first version. */\n parentId?: string | null\n /** The processing config (auto-title, parsing) to run the upload with. */\n configId?: string | null\n /** `artifact` (default) for AI-style drafts; `source` for a document the user typed. */\n wpType?: 'artifact' | 'source'\n}\n\n/**\n * Save markdown as a NEW immutable version (a child document of `parentId`) and refresh the\n * workspace document list so the version list picks it up. The id of the new version is often not\n * known yet (the document is parsed asynchronously); it then arrives through the list.\n */\nexport function useSaveArtifactVersion() {\n const arbi = useArbi()\n const queryClient = useQueryClient()\n return useMutation<\n ArtifactSaveResult,\n Error,\n SaveArtifactVersionInput & { workspaceId?: string }\n >({\n mutationFn: async ({ title, content, parentId, configId, wpType, workspaceId }) => {\n // The backend classifies uploads by extension: a title without one is silently dropped.\n const fileName = /\\.md$/i.test(title) ? title : `${title}.md`\n const result = await arbi.documents.uploadFile(\n new Blob([content], { type: 'text/markdown' }),\n fileName,\n {\n wpType: wpType ?? 'artifact',\n parentExtId: parentId ?? undefined,\n configExtId: configId ?? undefined,\n }\n )\n if (workspaceId) {\n await queryClient.invalidateQueries({ queryKey: arbiQueryKeys.documents(workspaceId) })\n }\n return { docId: result.doc_ext_ids?.[0] }\n },\n })\n}\n\nexport interface ArtifactSessionOptions extends Pick<\n ArtifactEditSessionOptions,\n | 'onSaved'\n | 'onSaveError'\n | 'onCompareChange'\n | 'compareId'\n | 'compareOpensEditor'\n | 'redlineEngine'\n | 'onDirtyChange'\n> {\n workspaceId: string | undefined\n /**\n * The open version, or the placeholder id of an unsaved local draft (anything that is not a\n * backend document id, i.e. does not start with `doc`).\n */\n docId: string | null | undefined\n /**\n * The text of a local draft (nothing is fetched for it). The FIRST save uploads it as a real\n * document with no parent and the session switches to the new id; later saves chain from it.\n */\n draftContent?: string\n /** Name for saved versions. Defaults to the open version's file name, else \"Untitled\". */\n title?: string\n /** Processing config for saved versions. */\n configId?: string | null\n}\n\n/** Everything `ArtifactEditor` (`@arbidocs/blocks/artifacts`) takes from a session, flat. */\nexport interface ArtifactSessionView {\n content: string\n isEditing: boolean\n hasChanges: boolean\n isSaving: boolean\n canCompare: boolean\n comparing: boolean\n compareId: string | null\n showTrackChanges: boolean\n versions: ArtifactVersion[]\n currentVersionId: string\n onStartEdit: () => void\n onCancel: () => void\n onSave: () => void\n onCompare: () => void\n onStopCompare: () => void\n onToggleTrackChanges: () => void\n /**\n * Whether the text is ready. `ArtifactEditor` renders \"Preparing editor...\" while it is\n * `loading` or `parsing` (a fresh upload is parsed for a few seconds) and an error with Retry.\n */\n status: ArtifactTextStatus\n /** Ask for the text again after an `error`. */\n onRetry: () => void\n}\n\nexport interface ArtifactSession extends ArtifactEditSession {\n /** The open document: the new real id once a local draft has been saved. */\n docId: string | null | undefined\n /** The open version is an unsaved local draft (no backend document yet). */\n isLocal: boolean\n isLoading: boolean\n /** See `ArtifactTextStatus`. */\n status: ArtifactTextStatus\n versions: ArtifactVersion[]\n /** \"v2\" for any version in the lineage. */\n labelOf: (id: string | null | undefined) => string | null\n /** Props for `<ArtifactEditor>`. */\n view: ArtifactSessionView\n /** Props for `<ArtifactMarkdownEditor>` (`@arbidocs/blocks/artifacts/editor`). */\n editorProps: {\n markdown: string\n onChange: (markdown: string) => void\n onNormalized: (markdown: string) => void\n }\n /** Props for `<ArtifactRedlineView>`. */\n redlineProps: {\n state: ArtifactEditSession['redline']['state']\n onRevert: (regionId: string) => void\n }\n}\n\n/**\n * Edit an artifact through the SDK: load it, edit it, save it as a new version, list its versions\n * and compare any two with track changes. Needs an `<ArbiProvider>` and a selected workspace.\n *\n * ```tsx\n * const session = useArtifactSession({ workspaceId, docId, onSaved: ({ docId }) => docId && open(docId) })\n * <ArtifactEditor {...session.view} onOpenVersion={open}\n * editor={<ArtifactMarkdownEditor {...session.editorProps} />}\n * redline={<ArtifactRedlineView {...session.redlineProps} />} />\n * ```\n */\nexport function useArtifactSession(options: ArtifactSessionOptions): ArtifactSession {\n const {\n workspaceId,\n docId: hostDocId,\n draftContent,\n title,\n configId,\n compareId,\n onCompareChange,\n onSaved,\n ...passthrough\n } = options\n // A saved local draft becomes this real document; another host docId resets it.\n const [saved, setSaved] = useState<{\n forId: string | null | undefined\n id: string\n text: string\n } | null>(null)\n const adopted = saved && saved.forId === hostDocId ? saved : null\n const docId = adopted?.id ?? hostDocId\n const isLocal = !isDocumentId(docId)\n\n // Owned here (not in the edit session) because the compare target's text must be loaded first.\n const [ownCompareId, setOwnCompareId] = useState<string | null>(null)\n const activeCompareId = compareId === undefined ? ownCompareId : compareId\n const changeCompare = useCallback(\n (id: string | null) => {\n setOwnCompareId(id)\n onCompareChange?.(id)\n },\n [onCompareChange]\n )\n\n const { text, isLoading, status, retry } = useArtifactText(docId)\n const versions = useArtifactVersions(workspaceId, isLocal ? null : docId)\n const { text: compareText, isLoading: compareLoading } = useArtifactText(activeCompareId, {\n enabled: !!activeCompareId,\n })\n const saveVersion = useSaveArtifactVersion()\n const current = versions.find((v) => v.id === docId)\n\n const save = useCallback(\n async (content: string) => {\n const result = await saveVersion.mutateAsync({\n title: title ?? current?.name ?? 'Untitled',\n content,\n parentId: isLocal ? null : docId,\n configId,\n workspaceId,\n })\n return { ...result, version: isLocal ? 1 : versions.length + 1 }\n },\n [saveVersion, title, current?.name, isLocal, docId, configId, workspaceId, versions.length]\n )\n\n const handleSaved = useCallback(\n (result: ArtifactSaveResult, content: string) => {\n // A host that keeps passing the local draft's placeholder id: follow every save to the real\n // document it created (the first save creates version 1, later ones chain from it).\n if (!isDocumentId(hostDocId) && result.docId)\n setSaved({ forId: hostDocId, id: result.docId, text: content })\n onSaved?.(result, content)\n },\n [hostDocId, onSaved]\n )\n\n const session = useArtifactEditSession({\n ...passthrough,\n docId,\n // A local draft has only its own text; a just-saved one shows what was saved until the parsed\n // text of the new document arrives.\n baseline: text ?? (isLocal ? draftContent : adopted?.text),\n parentId: current?.parentId,\n compareId: activeCompareId,\n onCompareChange: changeCompare,\n compareText,\n compareLoading,\n save,\n onSaved: handleSaved,\n })\n\n const { redline } = session\n return useMemo<ArtifactSession>(\n () => ({\n ...session,\n docId,\n isLocal,\n isLoading,\n status,\n versions,\n labelOf: (id) => versionLabel(versions, id),\n view: {\n content: session.baseline,\n isEditing: session.isEditing,\n hasChanges: session.hasChanges,\n isSaving: session.isSaving,\n canCompare: session.canCompare,\n comparing: !!session.compareId,\n compareId: session.compareId,\n showTrackChanges: session.showTrackChanges,\n versions,\n currentVersionId: docId ?? '',\n onStartEdit: session.startEdit,\n onCancel: session.cancel,\n onSave: () => void session.save(),\n onCompare: () => session.compare(),\n onStopCompare: session.stopCompare,\n onToggleTrackChanges: () => session.setShowTrackChanges(!session.showTrackChanges),\n // A local draft has its text already: it is ready.\n status: isLocal ? 'ready' : status,\n onRetry: retry,\n },\n editorProps: {\n markdown: session.content,\n onChange: session.change,\n onNormalized: session.normalized,\n },\n redlineProps: {\n state: redline.state,\n onRevert: (regionId) => void session.revertRegion(regionId),\n },\n }),\n [session, redline, isLoading, status, retry, isLocal, versions, docId]\n )\n}\n","import type { ComponentPropsWithoutRef, FC, ReactNode } from 'react'\nimport { MarkdownRenderer } from '../ai/MarkdownRenderer'\n\n/** The `<del>` / `<ins>` renderers `ArtifactRedlineView` hands to a markdown renderer. */\nexport interface ArtifactRedlineComponents {\n del: FC<ComponentPropsWithoutRef<'del'> & { 'data-cid'?: string }>\n ins: FC<ComponentPropsWithoutRef<'ins'> & { 'data-cid'?: string }>\n}\n\n/**\n * The kit's markdown renderer as the `renderMarkdown` slot of `ArtifactEditor` and\n * `ArtifactRedlineView`: full markdown (tables, lists, code) plus the raw `<del>` / `<ins>` tags\n * of a redline.\n */\nexport function renderArtifactMarkdown(\n markdown: string,\n components?: ArtifactRedlineComponents\n): ReactNode {\n return <MarkdownRenderer components={components}>{markdown}</MarkdownRenderer>\n}\n","import { useCallback, useEffect, useRef, useState } from 'react'\nimport type { ArtifactEvent } from '../ai/engine'\nimport { cleanDraftMarkdown } from '../ai/stored-markdown'\nimport { useSaveArtifactVersion } from './useArtifactSession'\nimport { isDocumentId } from './versions'\nimport { useArtifactText, type ArtifactTextRetry } from './useArtifactText'\n\n/**\n * Where a drafted artifact is in its STREAM -> PERSIST -> EDIT life:\n * - `streaming`: the agent is still working (or has produced nothing final): show the live canvas;\n * - `persisting`: the finished draft is being stored as version 1 of the artifact;\n * - `parsing`: stored; the backend is still parsing it, so there is no editable text yet;\n * - `ready`: the text is readable: mount the editor on `docId`;\n * - `error`: storing failed or the parse never produced text (`retry()` starts over).\n */\nexport type StreamedArtifactPhase = 'streaming' | 'persisting' | 'parsing' | 'ready' | 'error'\n\nexport interface UseStreamedArtifactOptions {\n /** The artifacts of the agent run (`useConnectedAiTask().artifacts`). */\n artifacts: ArtifactEvent[]\n workspaceId: string | undefined\n /**\n * The run has stopped: not busy and not failed. Nothing is stored before this, so a draft that\n * is still streaming is never persisted half-written.\n */\n settled: boolean\n /** Make the stored markdown from the streamed content. Defaults to `cleanDraftMarkdown`. */\n clean?: (streamed: string) => string\n /** Processing config for the stored version. */\n configId?: string | null\n /** How long to wait for the parse (see `useArtifactText`). */\n parseRetry?: ArtifactTextRetry\n}\n\nexport interface StreamedArtifact {\n phase: StreamedArtifactPhase\n /** The finished streamed artifact (its `title` names the stored versions). */\n artifact: ArtifactEvent | undefined\n /** The backend document to edit, once there is one (while `parsing` and `ready`). */\n docId: string | undefined\n error: Error | null\n /** After an `error`: store again or ask for the parse again. */\n retry: () => void\n}\n\n/**\n * The lifecycle of an agent-drafted artifact, so a host passes the stream and renders the phase.\n *\n * While the agent streams, the draft lives only on the canvas. Once the run is `settled` and the\n * draft is complete, a draft that is not yet a backend document is cleaned (`cleanDraftMarkdown`)\n * and stored ONCE as the artifact's first version (`wpType: 'artifact'`); a draft that already is a\n * backend document passes through. The hook then waits for the parse (`useArtifactText`, which\n * retries) and reports `ready` with the `docId` to open in an editor.\n *\n * Needs an `<ArbiProvider>` and a workspace. `@arbidocs/blocks/connect` has the whole thing as a\n * component (`StreamedArtifact`).\n */\nexport function useStreamedArtifact({\n artifacts,\n workspaceId,\n settled,\n clean = cleanDraftMarkdown,\n configId,\n parseRetry,\n}: UseStreamedArtifactOptions): StreamedArtifact {\n const artifact = artifacts.find((a) => a.is_complete)\n const { mutateAsync } = useSaveArtifactVersion()\n const [saved, setSaved] = useState<{ content: string; docId: string } | null>(null)\n const [saveError, setSaveError] = useState<Error | null>(null)\n const [attempt, setAttempt] = useState(0)\n const started = useRef<string | null>(null)\n\n const content = artifact?.content ?? ''\n const title = artifact?.title ?? 'Draft'\n const passThrough = !!artifact && isDocumentId(artifact.doc_ext_id)\n const needsSave = settled && !!artifact && !passThrough && !!content.trim() && !!workspaceId\n\n useEffect(() => {\n const key = `${attempt}:${content}`\n if (!needsSave || started.current === key) return\n started.current = key\n setSaveError(null)\n mutateAsync({\n title,\n content: clean(content),\n workspaceId,\n configId,\n wpType: 'artifact',\n })\n .then((r) => {\n if (r.docId) setSaved({ content, docId: r.docId })\n else setSaveError(new Error('The draft was stored but the server returned no document id'))\n })\n .catch((e: unknown) => setSaveError(e instanceof Error ? e : new Error(String(e))))\n // `clean` is deliberately not a dependency: a new function identity must not store twice.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [needsSave, content, title, workspaceId, configId, attempt, mutateAsync])\n\n const docId = !artifact\n ? undefined\n : passThrough\n ? artifact.doc_ext_id\n : saved?.content === content\n ? saved.docId\n : undefined\n\n const text = useArtifactText(docId, { enabled: settled, retry: parseRetry })\n const { retry: retryText } = text\n\n const retry = useCallback(() => {\n if (saveError) setAttempt((n) => n + 1)\n else retryText()\n }, [saveError, retryText])\n\n let phase: StreamedArtifactPhase\n if (!settled || !artifact) phase = 'streaming'\n else if (saveError) phase = 'error'\n else if (!docId) phase = needsSave ? 'persisting' : 'streaming'\n else if (text.status === 'ready' && text.text) phase = 'ready'\n else if (text.status === 'error' || text.status === 'ready') phase = 'error'\n else phase = 'parsing'\n\n const error =\n phase !== 'error'\n ? null\n : (saveError ?? text.error ?? new Error('The document has no text to edit'))\n return { phase, artifact, docId, error, retry }\n}\n"]}
1
+ {"version":3,"sources":["../../src/artifacts/redline-engine.ts","../../src/artifacts/useRedline.ts","../../src/artifacts/versions.ts","../../src/artifacts/useArtifactEditSession.ts","../../src/artifacts/useArtifactText.ts","../../src/artifacts/useArtifactSession.ts","../../src/artifacts/renderArtifactMarkdown.tsx","../../src/artifacts/useStreamedArtifact.ts"],"names":["buildHybridRedlineMarkdown","buildHybridRedlineWithRegions","revertRedlineRegion","useState","useRef","useEffect","normalizeMarkdown","useCallback","useMemo","repairParsedStructure","repairParsedTitle","unescapeMarkdown","content","useArbi","useQuery","arbiQueryKeys","useDocuments","useQueryClient","useMutation","jsx","MarkdownRenderer","cleanDraftWithReport"],"mappings":";;;;;;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,KAAA,GAAQ,SAAA,GAAY,YAAA,GAAe,WAAA;AAAA,OAAA,IAC3C,IAAA,CAAK,MAAA,KAAW,OAAA,IAAW,IAAA,CAAK,MAAM,KAAA,GAAQ,OAAA;AAAA,OAAA,IAC9C,KAAK,MAAA,KAAW,OAAA,IAAW,IAAA,CAAK,MAAA,KAAW,SAAS,KAAA,GAAQ,OAAA;AAAA,OAChE,KAAA,GAAQ,SAAA;AAEb,EAAA,MAAM,KAAA,GACJ,UAAU,OAAA,GACN,IAAA,GACC,aAAa,IAAA,CAAK,KAAA,IAAS,IAAI,KAAA,CAAM,kCAAkC,CAAA;AAC9E,EAAA,OAAO,EAAE,KAAA,EAAO,QAAA,EAAU,KAAA,EAAO,KAAA,EAAO,SAAS,KAAA,EAAM;AACzD","file":"index.cjs","sourcesContent":["import {\n buildHybridRedlineMarkdown,\n buildHybridRedlineWithRegions,\n revertRedlineRegion,\n type RedlineWithRegions,\n} from './redline-diff'\n\n/**\n * Where a redline is computed. The default runs on the calling thread; a host with large\n * documents passes an engine backed by a Web Worker (for example a Comlink proxy exposing the same\n * three functions) so typing never waits on a diff.\n */\nexport interface RedlineEngine {\n buildRedline(baseText: string, compareText: string): string | Promise<string>\n buildRedlineWithRegions(\n baseText: string,\n compareText: string\n ): RedlineWithRegions | Promise<RedlineWithRegions>\n revertRegion(baseText: string, compareText: string, regionId: string): string | Promise<string>\n}\n\n/** Main-thread engine: the pure functions of `redline-diff`. */\nexport const mainThreadRedlineEngine: RedlineEngine = {\n buildRedline: buildHybridRedlineMarkdown,\n buildRedlineWithRegions: buildHybridRedlineWithRegions,\n revertRegion: revertRedlineRegion,\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { RedlineRegion } from './redline-diff'\nimport { normalizeMarkdown } from './normalize-markdown'\nimport { mainThreadRedlineEngine, type RedlineEngine } from './redline-engine'\n\n/** What a redline view can show. Mirrors the status parts of `@arbidocs/blocks/artifacts`. */\nexport type RedlineState =\n | { kind: 'idle' }\n | { kind: 'computing' }\n | { kind: 'ready'; markdown: string; regions: RedlineRegion[] }\n | { kind: 'identical' }\n | { kind: 'unavailable' }\n\nexport interface UseRedlineOptions {\n /** The older side. `null` means the text could not be loaded; `undefined` means not chosen. */\n baseText: string | null | undefined\n /** The newer side (a loaded version, or the live edit buffer). */\n compareText: string | null | undefined\n /** Either text is still being fetched. */\n isLoading?: boolean\n /** Tag every change with a stable id so a view can offer per-change undo. */\n withRegions?: boolean\n /** Defaults to the main thread; pass a worker-backed engine for big documents. */\n engine?: RedlineEngine\n}\n\nexport interface UseRedlineResult {\n state: RedlineState\n /** Undo one change: resolves with the compare text rebuilt without it (null if nothing changed). */\n revertRegion: (regionId: string) => Promise<string | null>\n}\n\n/**\n * Track-changes between two texts. Stale results are dropped when the inputs change mid-compute,\n * and a failed diff reports `unavailable` instead of throwing into the render.\n */\nexport function useRedline({\n baseText,\n compareText,\n isLoading = false,\n withRegions = false,\n engine = mainThreadRedlineEngine,\n}: UseRedlineOptions): UseRedlineResult {\n const [state, setState] = useState<RedlineState>({ kind: 'idle' })\n const requestIdRef = useRef(0)\n\n useEffect(() => {\n if (baseText === undefined || compareText === undefined) {\n setState({ kind: 'idle' })\n return\n }\n if (isLoading) {\n setState({ kind: 'computing' })\n return\n }\n if (baseText === null || compareText === null) {\n setState({ kind: 'unavailable' })\n return\n }\n if (\n baseText === compareText ||\n normalizeMarkdown(baseText) === normalizeMarkdown(compareText)\n ) {\n setState({ kind: 'identical' })\n return\n }\n\n const id = ++requestIdRef.current\n let cancelled = false\n setState({ kind: 'computing' })\n Promise.resolve(\n withRegions\n ? engine.buildRedlineWithRegions(baseText, compareText)\n : Promise.resolve(engine.buildRedline(baseText, compareText)).then((markdown) => ({\n markdown,\n regions: [] as RedlineRegion[],\n }))\n )\n .then((result) => {\n if (cancelled || id !== requestIdRef.current) return\n setState({ kind: 'ready', markdown: result.markdown, regions: result.regions })\n })\n .catch(() => {\n if (cancelled || id !== requestIdRef.current) return\n setState({ kind: 'unavailable' })\n })\n return () => {\n cancelled = true\n }\n }, [baseText, compareText, isLoading, withRegions, engine])\n\n // The latest texts, so `revertRegion` stays referentially stable while the user types.\n const latest = useRef({ baseText, compareText })\n useEffect(() => {\n latest.current = { baseText, compareText }\n }, [baseText, compareText])\n\n const revertRegion = useCallback(\n async (regionId: string): Promise<string | null> => {\n const { baseText: base, compareText: compare } = latest.current\n if (!base || !compare) return null\n try {\n const next = await engine.revertRegion(base, compare, regionId)\n return next !== normalizeMarkdown(compare) ? next : null\n } catch {\n return null\n }\n },\n [engine]\n )\n\n return useMemo(() => ({ state, revertRegion }), [state, revertRegion])\n}\n","/**\n * Version lineage of an artifact. Every save creates a NEW document whose `parent_ext_id` is the\n * version it was saved from, so a lineage is a tree (a save from an old version is a deliberate\n * branch). Computed from a document list the host already has; no extra request.\n */\n\nimport { repairParsedStructure, repairParsedTitle, unescapeMarkdown } from '../ai/stored-markdown'\nimport { normalizeMarkdown } from './normalize-markdown'\n\n/** The fields of a workspace document the lineage needs (structurally a subset of the API type). */\nexport interface VersionedDoc {\n external_id?: string | null\n parent_ext_id?: string | null\n file_name?: string | null\n created_at?: string | null\n}\n\n/** One row of a version list. Matches `VersionEntry` of `@arbidocs/blocks/artifacts`. */\nexport interface ArtifactVersion {\n id: string\n /** File name as stored. */\n name: string\n /** ISO timestamp. */\n createdAt: string\n /** The version this one was saved from. */\n parentId?: string | null\n}\n\n/**\n * The whole lineage of `docId` (root first, then oldest to newest), or `[]` when the document is\n * not in `docs`. Cycle-safe.\n */\nexport function buildVersionChain<T extends VersionedDoc>(\n docs: readonly T[],\n docId: string | null | undefined\n): T[] {\n if (!docId) return []\n const byId = new Map<string, T>()\n for (const d of docs) if (d.external_id) byId.set(d.external_id, d)\n\n const current = byId.get(docId)\n if (!current) return []\n\n let root = current\n const up = new Set<string>()\n while (\n root.parent_ext_id &&\n byId.has(root.parent_ext_id) &&\n root.external_id &&\n !up.has(root.external_id)\n ) {\n up.add(root.external_id)\n root = byId.get(root.parent_ext_id) as T\n }\n\n const byParent = new Map<string, T[]>()\n for (const d of docs) {\n if (d.parent_ext_id) {\n const siblings = byParent.get(d.parent_ext_id) ?? []\n siblings.push(d)\n byParent.set(d.parent_ext_id, siblings)\n }\n }\n const out: T[] = []\n const visited = new Set<string>()\n const walk = (d: T): void => {\n if (!d.external_id || visited.has(d.external_id)) return\n visited.add(d.external_id)\n out.push(d)\n for (const child of byParent.get(d.external_id) ?? []) walk(child)\n }\n walk(root)\n\n out.sort((a, b) => (a.created_at ?? '').localeCompare(b.created_at ?? ''))\n return out\n}\n\n/** The lineage of `docId` as plain version rows. */\nexport function toArtifactVersions(chain: readonly VersionedDoc[]): ArtifactVersion[] {\n return chain.flatMap((d) =>\n d.external_id\n ? [\n {\n id: d.external_id,\n name: d.file_name ?? '',\n createdAt: d.created_at ?? '',\n parentId: d.parent_ext_id,\n },\n ]\n : []\n )\n}\n\n/**\n * \"v2\": the 1-based position of `docId` in its lineage. `null` when there is nothing to tell apart\n * (the lineage is just this document, or it is unknown), so unversioned documents stay unlabelled.\n */\nexport function versionLabel(\n versions: readonly ArtifactVersion[],\n docId: string | null | undefined\n): string | null {\n if (!docId || versions.length <= 1) return null\n const index = versions.findIndex((v) => v.id === docId)\n return index === -1 ? null : `v${index + 1}`\n}\n\n/**\n * Join parsed chunks into one markdown text (blank line between chunks).\n *\n * `unescape: true` for an artifact stored from markdown: the backend's parse of a `.md` escapes\n * markdown punctuation, which `unescapeMarkdown` undoes (see its rule), and mangles its title\n * (`repairParsedTitle`, `repairParsedStructure`: doubled headings, `- ` stacked on list markers,\n * one-line tables), then normalised. Leave it off for the parse\n * of a PDF or Word file.\n */\nexport function flattenChunks(\n chunks: readonly { content?: string | null }[] | null | undefined,\n options?: { unescape?: boolean }\n): string {\n const text = (chunks ?? []).map((c) => (c.content ?? '').trim()).join('\\n\\n')\n if (!options?.unescape) return text\n // Canonical spelling last, so the text an editor starts from is what a save would persist.\n return normalizeMarkdown(\n repairParsedStructure(repairParsedTitle(unescapeMarkdown(text)))\n ).replace(/\\n$/, '')\n}\n\n/** The backend's pattern for a document id. Anything else (a streamed draft's placeholder) is local. */\nconst DOC_ID = /^doc/\n\n/** Is `id` a real, saved document id? Local drafts have placeholder ids and no backend document. */\nexport function isDocumentId(id: string | null | undefined): id is string {\n return !!id && DOC_ID.test(id)\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { normalizeMarkdown } from './normalize-markdown'\nimport { useRedline, type UseRedlineResult } from './useRedline'\nimport type { RedlineEngine } from './redline-engine'\n\n/** What a save reports back. `docId` is the new version when the backend already knows it. */\nexport interface ArtifactSaveResult {\n docId?: string\n /** 1-based number of the version that was just saved (1 for the first save of a draft). */\n version?: number\n}\n\nexport interface ArtifactEditSessionOptions {\n /** The artifact being edited. Changing it discards the buffer and any comparison. */\n docId: string | null | undefined\n /**\n * The saved text of the open version. `undefined` while it loads; whenever it changes the\n * baseline follows it (a version arriving from the realtime channel, a finished stream).\n */\n baseline: string | undefined\n /**\n * A new document the user types from scratch: open straight in the editor, seeded with\n * `initialContent`, instead of showing a read-only view. Read when `docId` changes.\n */\n startEditing?: boolean\n initialContent?: string\n /** The version this one was saved from. Offering \"compare with previous\" needs it. */\n parentId?: string | null\n /** Controlled comparison target. Omit for an uncontrolled one the session owns. */\n compareId?: string | null\n onCompareChange?: (id: string | null) => void\n /** The saved text of the compare target (the older side of the diff). */\n compareText?: string | null\n compareLoading?: boolean\n /** Starting a comparison opens the editor with track changes on (default true). */\n compareOpensEditor?: boolean\n /** Persist the buffer as a NEW version. Rejecting keeps the buffer so nothing is lost. */\n save: (content: string) => Promise<ArtifactSaveResult | void>\n onSaved?: (result: ArtifactSaveResult, content: string) => void\n onSaveError?: (error: unknown) => void\n /** Every buffer change (a host keeps a draft store in sync with it). */\n onContentChange?: (content: string) => void\n /** The unsaved-changes flag, for a host that warns before a panel is closed. */\n onDirtyChange?: (dirty: boolean) => void\n /** Where the diff runs. Defaults to the main thread. */\n redlineEngine?: RedlineEngine\n /** Typing is never debounced; the diff trails the buffer by this long. Default 300ms. */\n diffDelayMs?: number\n}\n\nexport interface ArtifactEditSession {\n isEditing: boolean\n /** The saved text of the open version. */\n baseline: string\n /** The text in the editor (the baseline until the first edit). */\n content: string\n hasChanges: boolean\n isSaving: boolean\n canCompare: boolean\n compareId: string | null\n showTrackChanges: boolean\n /** Track changes between the compare target and the (debounced) buffer. */\n redline: UseRedlineResult\n startEdit: () => void\n /** Discard the buffer and any comparison; back to the rendered view. */\n cancel: () => void\n /** Save the buffer as a new version. Resolves false when it failed (the buffer is kept). */\n save: () => Promise<boolean>\n /** The editor's `onChange`; also replaces the buffer (for example after an undo-this-change). */\n change: (markdown: string) => void\n /** The editor's `onNormalized`: adopt its canonical form as the baseline so Save does not fire. */\n normalized: (markdown: string) => void\n /** Compare with the previous version (when no id is given). */\n compare: (id?: string) => void\n stopCompare: () => void\n setShowTrackChanges: (show: boolean) => void\n /** Undo one tracked change in the buffer. */\n revertRegion: (regionId: string) => Promise<void>\n}\n\n/**\n * The state machine of an artifact edit session, with no SDK and no network: the edit buffer and\n * its baseline, the dirty flag, immutable-version saves and a track-changes comparison. A host\n * supplies the saved text and a `save` function (see `useArtifactSession` for the SDK binding).\n */\nexport function useArtifactEditSession(options: ArtifactEditSessionOptions): ArtifactEditSession {\n const {\n docId,\n baseline: loadedBaseline,\n startEditing = false,\n initialContent,\n parentId,\n compareId: controlledCompareId,\n onCompareChange,\n compareText,\n compareLoading = false,\n compareOpensEditor = true,\n save: persist,\n onSaved,\n onSaveError,\n onContentChange,\n onDirtyChange,\n redlineEngine,\n diffDelayMs = 300,\n } = options\n\n const [isEditing, setIsEditing] = useState(false)\n const [baseline, setBaseline] = useState('')\n const [buffer, setBuffer] = useState('')\n const [isSaving, setIsSaving] = useState(false)\n const [showTrackChanges, setShowTrackChanges] = useState(false)\n const [ownCompareId, setOwnCompareId] = useState<string | null>(null)\n const controlled = controlledCompareId !== undefined\n const compareId = controlled ? controlledCompareId : ownCompareId\n\n const setCompareId = useCallback(\n (id: string | null) => {\n if (!controlled) setOwnCompareId(id)\n onCompareChange?.(id)\n },\n [controlled, onCompareChange]\n )\n\n // The latest values for callbacks that must not change identity while the user types.\n const latest = useRef({ buffer, baseline, isEditing, initialContent })\n latest.current = { buffer, baseline, isEditing, initialContent }\n\n // The baseline follows the loaded text. A draft has none and seeds itself below.\n useEffect(() => {\n if (loadedBaseline !== undefined) setBaseline(loadedBaseline)\n }, [loadedBaseline])\n\n // Another artifact: drop stale edits and comparison. A new typed document starts in the editor.\n useEffect(() => {\n if (startEditing) {\n const seed = latest.current.initialContent ?? ''\n setIsEditing(true)\n setBaseline(seed)\n setBuffer(seed)\n } else {\n setIsEditing(false)\n setBuffer('')\n }\n setCompareId(null)\n setShowTrackChanges(false)\n // Only the identity of the artifact resets the session.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [docId])\n\n const startEdit = useCallback(() => {\n setBuffer(latest.current.baseline)\n setIsEditing(true)\n }, [])\n\n const stopCompare = useCallback(() => {\n setCompareId(null)\n setShowTrackChanges(false)\n }, [setCompareId])\n\n const cancel = useCallback(() => {\n setIsEditing(false)\n setBuffer('')\n stopCompare()\n }, [stopCompare])\n\n const compare = useCallback(\n (id?: string) => {\n const target = id ?? parentId\n if (target) setCompareId(target)\n },\n [parentId, setCompareId]\n )\n\n // Comparing and editing are one surface: a comparison opens the editor with the diff showing,\n // like Word's Compare yields tracked changes you can keep typing through.\n const hasBaseline = baseline !== ''\n useEffect(() => {\n if (!compareId || !compareOpensEditor || !hasBaseline) return\n if (!latest.current.isEditing) startEdit()\n setShowTrackChanges(true)\n }, [compareId, compareOpensEditor, hasBaseline, startEdit])\n\n const save = useCallback(async (): Promise<boolean> => {\n // Persist the canonical spelling so the editor's gratuitous escapes never reach a version.\n const raw = latest.current.buffer\n const normalised = normalizeMarkdown(raw)\n const content = raw.endsWith('\\n') ? normalised : normalised.replace(/\\n$/, '')\n setIsSaving(true)\n try {\n const result = (await persist(content)) ?? {}\n setBaseline(content)\n setIsEditing(false)\n stopCompare()\n onSaved?.(result, content)\n return true\n } catch (error) {\n onSaveError?.(error)\n return false\n } finally {\n setIsSaving(false)\n }\n }, [persist, stopCompare, onSaved, onSaveError])\n\n const content = buffer || baseline\n const hasChanges = isEditing && !!buffer && buffer !== baseline\n useEffect(() => {\n onDirtyChange?.(hasChanges)\n return () => onDirtyChange?.(false)\n }, [hasChanges, onDirtyChange])\n\n const setContent = useCallback(\n (markdown: string) => {\n setBuffer(markdown)\n onContentChange?.(markdown)\n },\n [onContentChange]\n )\n const normalized = useCallback((markdown: string) => {\n setBaseline(markdown)\n setBuffer(markdown)\n }, [])\n\n // The diff trails the buffer so it runs on a settled text.\n const [diffContent, setDiffContent] = useState(content)\n useEffect(() => {\n const id = setTimeout(() => setDiffContent(content), diffDelayMs)\n return () => clearTimeout(id)\n }, [content, diffDelayMs])\n\n const redline = useRedline({\n baseText: compareId ? compareText : undefined,\n compareText: compareId ? diffContent || baseline : undefined,\n isLoading: compareLoading,\n withRegions: true,\n engine: redlineEngine,\n })\n const { revertRegion: revertInRedline } = redline\n const revertRegion = useCallback(\n async (regionId: string): Promise<void> => {\n const next = await revertInRedline(regionId)\n if (next !== null) setContent(next)\n },\n [revertInRedline, setContent]\n )\n\n return useMemo(\n () => ({\n isEditing,\n baseline,\n content,\n hasChanges,\n isSaving,\n canCompare: !!parentId && !compareId,\n compareId,\n showTrackChanges,\n redline,\n startEdit,\n cancel,\n save,\n change: setContent,\n normalized,\n compare,\n stopCompare,\n setShowTrackChanges,\n revertRegion,\n }),\n [\n isEditing,\n baseline,\n content,\n hasChanges,\n isSaving,\n parentId,\n compareId,\n showTrackChanges,\n redline,\n startEdit,\n cancel,\n save,\n setContent,\n normalized,\n compare,\n stopCompare,\n revertRegion,\n ]\n )\n}\n","import { useCallback, useMemo } from 'react'\nimport { useQuery } from '@tanstack/react-query'\nimport { useArbi } from '../useArbi'\nimport { arbiQueryKeys } from '../hooks'\nimport { flattenChunks, isDocumentId } from './versions'\n\n/**\n * Where the text of a stored artifact is:\n * - `loading`: the first request is in flight (or there is no document yet);\n * - `parsing`: the backend has not finished parsing the upload (the endpoint answers 404, 422 or\n * 500, or an empty parse, for a few seconds after an upload) and the hook is retrying;\n * - `ready`: the text is here (an empty document is `ready` with `text: null`);\n * - `error`: the retries ran out, or the request was refused (401/403).\n */\nexport type ArtifactTextStatus = 'loading' | 'parsing' | 'ready' | 'error'\n\n/** How long `useArtifactText` keeps asking while a document is still being parsed. */\nexport interface ArtifactTextRetry {\n /** Retries after the first request. Default 12. */\n attempts?: number\n /** Delay before the first retry; it grows by 1.6x each time. Default 1000 ms. */\n baseDelayMs?: number\n /** Cap for one delay. Default 5000 ms (12 retries are about 50 s in all). */\n maxDelayMs?: number\n}\n\nexport const DEFAULT_ARTIFACT_TEXT_RETRY: Required<ArtifactTextRetry> = {\n attempts: 12,\n baseDelayMs: 1000,\n maxDelayMs: 5000,\n}\n\n/** Thrown inside the query when the parse has no text yet, so that it is retried like a 500. */\nclass NotParsedYetError extends Error {\n constructor() {\n super('The document has no parsed text yet')\n }\n}\n\nconst isRefusal = (error: unknown): boolean => {\n const status = error as { status?: number; response?: { status?: number } } | null\n const code = status?.status ?? status?.response?.status\n return code === 401 || code === 403\n}\n\nexport interface ArtifactText {\n /**\n * The markdown, clean: `undefined` while `loading` or `parsing`, `null` when there is none (an\n * empty document, or `error`).\n */\n text: string | null | undefined\n /** `status` is `loading` or `parsing`. */\n isLoading: boolean\n status: ArtifactTextStatus\n /** The last request error while `parsing` or after `error`. */\n error: Error | null\n /** Ask again now (after an `error`). */\n retry: () => void\n}\n\n/**\n * The saved markdown of an artifact version (its parsed chunks, joined and unescaped).\n *\n * A freshly uploaded document is parsed asynchronously, and for roughly 3 to 20 seconds the parsed\n * content endpoint answers 404, 422 or 500 (or an empty parse). The hook therefore retries with a\n * growing delay (see `ArtifactTextRetry`) and reports `status: 'parsing'` meanwhile, so a host can\n * show \"Preparing editor...\" instead of opening an editor on an empty baseline. After the last\n * retry the status is `error`; `retry()` starts a new round.\n *\n * The text is run through `unescapeMarkdown`: an artifact is always stored from markdown, and the\n * backend's parse of a `.md` escapes its punctuation.\n */\nexport function useArtifactText(\n docId: string | null | undefined,\n options?: { enabled?: boolean; retry?: ArtifactTextRetry }\n): ArtifactText {\n const arbi = useArbi()\n const { attempts, baseDelayMs, maxDelayMs } = {\n ...DEFAULT_ARTIFACT_TEXT_RETRY,\n ...options?.retry,\n }\n // A local draft (placeholder id) has no backend document: asking for its text would be a 422.\n const enabled = (options?.enabled ?? true) && isDocumentId(docId) && arbi.hasWorkspace\n const query = useQuery({\n // Under the shared `parsedDoc` key, so a document's invalidation reaches it too.\n queryKey: [...arbiQueryKeys.parsedDoc(docId ?? '', 'marker'), 'artifact-text'] as const,\n queryFn: async () => {\n const parsed = (await arbi.documents.getParsedContent(docId as string, 'marker')) as {\n chunks?: { content?: string | null }[]\n }\n if (!parsed.chunks?.some((c) => c.content?.trim())) throw new NotParsedYetError()\n return flattenChunks(parsed.chunks, { unescape: true })\n },\n enabled,\n retry: (failureCount, error) => !isRefusal(error) && failureCount < attempts,\n retryDelay: (failureCount) => Math.min(baseDelayMs * 1.6 ** failureCount, maxDelayMs),\n })\n\n const { refetch } = query\n const retry = useCallback(() => void refetch(), [refetch])\n\n return useMemo<ArtifactText>(() => {\n const error = query.error\n const neverParsed = error instanceof NotParsedYetError\n let status: ArtifactTextStatus = 'loading'\n if (!enabled) status = 'loading'\n else if (query.isSuccess || (query.isError && neverParsed)) status = 'ready'\n else if (query.isError) status = 'error'\n else if (query.failureCount > 0) status = 'parsing'\n const text = !enabled\n ? undefined\n : query.isSuccess\n ? query.data\n : status === 'ready' || status === 'error'\n ? null\n : undefined\n return {\n text,\n isLoading: enabled && (status === 'loading' || status === 'parsing'),\n status,\n error: status === 'ready' ? null : (error ?? query.failureReason ?? null),\n retry,\n }\n }, [\n enabled,\n query.isSuccess,\n query.isError,\n query.data,\n query.error,\n query.failureCount,\n query.failureReason,\n retry,\n ])\n}\n","import { useCallback, useMemo, useState } from 'react'\nimport { useMutation, useQueryClient } from '@tanstack/react-query'\nimport { useArbi } from '../useArbi'\nimport { arbiQueryKeys, useDocuments } from '../hooks'\nimport { useArtifactText, type ArtifactTextStatus } from './useArtifactText'\nimport {\n buildVersionChain,\n isDocumentId,\n toArtifactVersions,\n versionLabel,\n type ArtifactVersion,\n} from './versions'\nimport {\n useArtifactEditSession,\n type ArtifactEditSession,\n type ArtifactEditSessionOptions,\n type ArtifactSaveResult,\n} from './useArtifactEditSession'\n\n/** The version lineage of an artifact in a workspace, oldest first. */\nexport function useArtifactVersions(\n workspaceId: string | undefined,\n docId: string | null | undefined\n): ArtifactVersion[] {\n const { data: documents } = useDocuments(workspaceId)\n return useMemo(\n () => toArtifactVersions(buildVersionChain(documents ?? [], docId)),\n [documents, docId]\n )\n}\n\nexport interface SaveArtifactVersionInput {\n /** File name of the new version (`.md` is added when missing). */\n title: string\n content: string\n /** The version this one is saved from; omit for a first version. */\n parentId?: string | null\n /** The processing config (auto-title, parsing) to run the upload with. */\n configId?: string | null\n /** `artifact` (default) for AI-style drafts; `source` for a document the user typed. */\n wpType?: 'artifact' | 'source'\n}\n\n/**\n * Save markdown as a NEW immutable version (a child document of `parentId`) and refresh the\n * workspace document list so the version list picks it up. The id of the new version is often not\n * known yet (the document is parsed asynchronously); it then arrives through the list.\n */\nexport function useSaveArtifactVersion() {\n const arbi = useArbi()\n const queryClient = useQueryClient()\n return useMutation<\n ArtifactSaveResult,\n Error,\n SaveArtifactVersionInput & { workspaceId?: string }\n >({\n mutationFn: async ({ title, content, parentId, configId, wpType, workspaceId }) => {\n // The backend classifies uploads by extension: a title without one is silently dropped.\n const fileName = /\\.md$/i.test(title) ? title : `${title}.md`\n const result = await arbi.documents.uploadFile(\n new Blob([content], { type: 'text/markdown' }),\n fileName,\n {\n wpType: wpType ?? 'artifact',\n parentExtId: parentId ?? undefined,\n configExtId: configId ?? undefined,\n }\n )\n if (workspaceId) {\n await queryClient.invalidateQueries({ queryKey: arbiQueryKeys.documents(workspaceId) })\n }\n return { docId: result.doc_ext_ids?.[0] }\n },\n })\n}\n\nexport interface ArtifactSessionOptions extends Pick<\n ArtifactEditSessionOptions,\n | 'onSaved'\n | 'onSaveError'\n | 'onCompareChange'\n | 'compareId'\n | 'compareOpensEditor'\n | 'redlineEngine'\n | 'onDirtyChange'\n> {\n workspaceId: string | undefined\n /**\n * The open version, or the placeholder id of an unsaved local draft (anything that is not a\n * backend document id, i.e. does not start with `doc`).\n */\n docId: string | null | undefined\n /**\n * The text of a local draft (nothing is fetched for it). The FIRST save uploads it as a real\n * document with no parent and the session switches to the new id; later saves chain from it.\n */\n draftContent?: string\n /** Name for saved versions. Defaults to the open version's file name, else \"Untitled\". */\n title?: string\n /** Processing config for saved versions. */\n configId?: string | null\n}\n\n/** Everything `ArtifactEditor` (`@arbidocs/blocks/artifacts`) takes from a session, flat. */\nexport interface ArtifactSessionView {\n content: string\n isEditing: boolean\n hasChanges: boolean\n isSaving: boolean\n canCompare: boolean\n comparing: boolean\n compareId: string | null\n showTrackChanges: boolean\n versions: ArtifactVersion[]\n currentVersionId: string\n onStartEdit: () => void\n onCancel: () => void\n onSave: () => void\n onCompare: () => void\n onStopCompare: () => void\n onToggleTrackChanges: () => void\n /**\n * Whether the text is ready. `ArtifactEditor` renders \"Preparing editor...\" while it is\n * `loading` or `parsing` (a fresh upload is parsed for a few seconds) and an error with Retry.\n */\n status: ArtifactTextStatus\n /** Ask for the text again after an `error`. */\n onRetry: () => void\n}\n\nexport interface ArtifactSession extends ArtifactEditSession {\n /** The open document: the new real id once a local draft has been saved. */\n docId: string | null | undefined\n /** The open version is an unsaved local draft (no backend document yet). */\n isLocal: boolean\n isLoading: boolean\n /** See `ArtifactTextStatus`. */\n status: ArtifactTextStatus\n versions: ArtifactVersion[]\n /** \"v2\" for any version in the lineage. */\n labelOf: (id: string | null | undefined) => string | null\n /** Props for `<ArtifactEditor>`. */\n view: ArtifactSessionView\n /** Props for `<ArtifactMarkdownEditor>` (`@arbidocs/blocks/artifacts/editor`). */\n editorProps: {\n markdown: string\n onChange: (markdown: string) => void\n onNormalized: (markdown: string) => void\n }\n /** Props for `<ArtifactRedlineView>`. */\n redlineProps: {\n state: ArtifactEditSession['redline']['state']\n onRevert: (regionId: string) => void\n }\n}\n\n/**\n * Edit an artifact through the SDK: load it, edit it, save it as a new version, list its versions\n * and compare any two with track changes. Needs an `<ArbiProvider>` and a selected workspace.\n *\n * ```tsx\n * const session = useArtifactSession({ workspaceId, docId, onSaved: ({ docId }) => docId && open(docId) })\n * <ArtifactEditor {...session.view} onOpenVersion={open}\n * editor={<ArtifactMarkdownEditor {...session.editorProps} />}\n * redline={<ArtifactRedlineView {...session.redlineProps} />} />\n * ```\n */\nexport function useArtifactSession(options: ArtifactSessionOptions): ArtifactSession {\n const {\n workspaceId,\n docId: hostDocId,\n draftContent,\n title,\n configId,\n compareId,\n onCompareChange,\n onSaved,\n ...passthrough\n } = options\n // A saved local draft becomes this real document; another host docId resets it.\n const [saved, setSaved] = useState<{\n forId: string | null | undefined\n id: string\n text: string\n } | null>(null)\n const adopted = saved && saved.forId === hostDocId ? saved : null\n const docId = adopted?.id ?? hostDocId\n const isLocal = !isDocumentId(docId)\n\n // Owned here (not in the edit session) because the compare target's text must be loaded first.\n const [ownCompareId, setOwnCompareId] = useState<string | null>(null)\n const activeCompareId = compareId === undefined ? ownCompareId : compareId\n const changeCompare = useCallback(\n (id: string | null) => {\n setOwnCompareId(id)\n onCompareChange?.(id)\n },\n [onCompareChange]\n )\n\n const { text, isLoading, status, retry } = useArtifactText(docId)\n const versions = useArtifactVersions(workspaceId, isLocal ? null : docId)\n const { text: compareText, isLoading: compareLoading } = useArtifactText(activeCompareId, {\n enabled: !!activeCompareId,\n })\n const saveVersion = useSaveArtifactVersion()\n const current = versions.find((v) => v.id === docId)\n\n const save = useCallback(\n async (content: string) => {\n const result = await saveVersion.mutateAsync({\n title: title ?? current?.name ?? 'Untitled',\n content,\n parentId: isLocal ? null : docId,\n configId,\n workspaceId,\n })\n return { ...result, version: isLocal ? 1 : versions.length + 1 }\n },\n [saveVersion, title, current?.name, isLocal, docId, configId, workspaceId, versions.length]\n )\n\n const handleSaved = useCallback(\n (result: ArtifactSaveResult, content: string) => {\n // A host that keeps passing the local draft's placeholder id: follow every save to the real\n // document it created (the first save creates version 1, later ones chain from it).\n if (!isDocumentId(hostDocId) && result.docId)\n setSaved({ forId: hostDocId, id: result.docId, text: content })\n onSaved?.(result, content)\n },\n [hostDocId, onSaved]\n )\n\n const session = useArtifactEditSession({\n ...passthrough,\n docId,\n // A local draft has only its own text; a just-saved one shows what was saved until the parsed\n // text of the new document arrives.\n baseline: text ?? (isLocal ? draftContent : adopted?.text),\n parentId: current?.parentId,\n compareId: activeCompareId,\n onCompareChange: changeCompare,\n compareText,\n compareLoading,\n save,\n onSaved: handleSaved,\n })\n\n const { redline } = session\n return useMemo<ArtifactSession>(\n () => ({\n ...session,\n docId,\n isLocal,\n isLoading,\n status,\n versions,\n labelOf: (id) => versionLabel(versions, id),\n view: {\n content: session.baseline,\n isEditing: session.isEditing,\n hasChanges: session.hasChanges,\n isSaving: session.isSaving,\n canCompare: session.canCompare,\n comparing: !!session.compareId,\n compareId: session.compareId,\n showTrackChanges: session.showTrackChanges,\n versions,\n currentVersionId: docId ?? '',\n onStartEdit: session.startEdit,\n onCancel: session.cancel,\n onSave: () => void session.save(),\n onCompare: () => session.compare(),\n onStopCompare: session.stopCompare,\n onToggleTrackChanges: () => session.setShowTrackChanges(!session.showTrackChanges),\n // A local draft has its text already: it is ready.\n status: isLocal ? 'ready' : status,\n onRetry: retry,\n },\n editorProps: {\n markdown: session.content,\n onChange: session.change,\n onNormalized: session.normalized,\n },\n redlineProps: {\n state: redline.state,\n onRevert: (regionId) => void session.revertRegion(regionId),\n },\n }),\n [session, redline, isLoading, status, retry, isLocal, versions, docId]\n )\n}\n","import type { ComponentPropsWithoutRef, FC, ReactNode } from 'react'\nimport { MarkdownRenderer } from '../ai/MarkdownRenderer'\n\n/** The `<del>` / `<ins>` renderers `ArtifactRedlineView` hands to a markdown renderer. */\nexport interface ArtifactRedlineComponents {\n del: FC<ComponentPropsWithoutRef<'del'> & { 'data-cid'?: string }>\n ins: FC<ComponentPropsWithoutRef<'ins'> & { 'data-cid'?: string }>\n}\n\n/**\n * The kit's markdown renderer as the `renderMarkdown` slot of `ArtifactEditor` and\n * `ArtifactRedlineView`: full markdown (tables, lists, code) plus the raw `<del>` / `<ins>` tags\n * of a redline.\n */\nexport function renderArtifactMarkdown(\n markdown: string,\n components?: ArtifactRedlineComponents\n): ReactNode {\n return <MarkdownRenderer components={components}>{markdown}</MarkdownRenderer>\n}\n","import { useCallback, useEffect, useRef, useState } from 'react'\nimport type { ArtifactEvent } from '../ai/engine'\nimport { cleanDraftWithReport, type DraftCleanReport } from '../ai/stored-markdown'\nimport { useSaveArtifactVersion } from './useArtifactSession'\nimport { isDocumentId } from './versions'\nimport { useArtifactText, type ArtifactTextRetry } from './useArtifactText'\n\n/**\n * Where a drafted artifact is in its STREAM -> PERSIST -> EDIT life:\n * - `streaming`: the agent is still working (or has produced nothing final): show the live canvas;\n * - `persisting`: the finished draft is being stored as version 1 of the artifact;\n * - `parsing`: stored; the backend is still parsing it, so there is no editable text yet;\n * - `ready`: the text is readable: mount the editor on `docId`;\n * - `error`: storing failed or the parse never produced text (`retry()` starts over).\n */\nexport type StreamedArtifactPhase = 'streaming' | 'persisting' | 'parsing' | 'ready' | 'error'\n\nexport interface UseStreamedArtifactOptions {\n /** The artifacts of the agent run (`useConnectedAiTask().artifacts`). */\n artifacts: ArtifactEvent[]\n workspaceId: string | undefined\n /**\n * The run has stopped: not busy and not failed. Nothing is stored before this, so a draft that\n * is still streaming is never persisted half-written.\n */\n settled: boolean\n /**\n * Make the stored markdown from the streamed content. Default `cleanDraftWithReport`, which is\n * guarded: it stores the raw streamed text (or links-only text) rather than a cleanup that would\n * lose content (see `DraftCleanReport`).\n */\n clean?: (streamed: string) => string\n /** Called once per stored draft with what the cleanup did (`stage` is not `cleaned` if guarded). */\n onCleaned?: (report: DraftCleanReport) => void\n /** Processing config for the stored version. */\n configId?: string | null\n /** How long to wait for the parse (see `useArtifactText`). */\n parseRetry?: ArtifactTextRetry\n}\n\nexport interface StreamedArtifact {\n phase: StreamedArtifactPhase\n /** The finished streamed artifact (its `title` names the stored versions). */\n artifact: ArtifactEvent | undefined\n /** The backend document to edit, once there is one (while `parsing` and `ready`). */\n docId: string | undefined\n error: Error | null\n /** What the cleanup did to the stored draft (`null` until it was stored, or with a custom `clean`). */\n cleaned: DraftCleanReport | null\n /** After an `error`: store again or ask for the parse again. */\n retry: () => void\n}\n\n/**\n * The lifecycle of an agent-drafted artifact, so a host passes the stream and renders the phase.\n *\n * While the agent streams, the draft lives only on the canvas. Once the run is `settled` and the\n * draft is complete, a draft that is not yet a backend document is cleaned (`cleanDraftMarkdown`)\n * and stored ONCE as the artifact's first version (`wpType: 'artifact'`); a draft that already is a\n * backend document passes through. The hook then waits for the parse (`useArtifactText`, which\n * retries) and reports `ready` with the `docId` to open in an editor.\n *\n * Needs an `<ArbiProvider>` and a workspace. `@arbidocs/blocks/connect` has the whole thing as a\n * component (`StreamedArtifact`).\n */\nexport function useStreamedArtifact({\n artifacts,\n workspaceId,\n settled,\n clean,\n onCleaned,\n configId,\n parseRetry,\n}: UseStreamedArtifactOptions): StreamedArtifact {\n const artifact = artifacts.find((a) => a.is_complete)\n const { mutateAsync } = useSaveArtifactVersion()\n const [saved, setSaved] = useState<{ content: string; docId: string } | null>(null)\n const [saveError, setSaveError] = useState<Error | null>(null)\n const [attempt, setAttempt] = useState(0)\n const [cleaned, setCleaned] = useState<DraftCleanReport | null>(null)\n const started = useRef<string | null>(null)\n\n const content = artifact?.content ?? ''\n const title = artifact?.title ?? 'Draft'\n const passThrough = !!artifact && isDocumentId(artifact.doc_ext_id)\n const needsSave = settled && !!artifact && !passThrough && !!content.trim() && !!workspaceId\n\n useEffect(() => {\n const key = `${attempt}:${content}`\n if (!needsSave || started.current === key) return\n started.current = key\n setSaveError(null)\n let stored: string\n if (clean) stored = clean(content)\n else {\n const report = cleanDraftWithReport(content)\n stored = report.text\n setCleaned(report)\n onCleaned?.(report)\n if (report.guarded) {\n console.warn(\n `[useStreamedArtifact] the draft cleanup would have lost content; stored the ${report.stage} text instead (kept ${Math.round(report.ratio * 100)}%, changed by: ${report.changedBy.join(', ') || 'nothing'})`\n )\n }\n }\n mutateAsync({\n title,\n content: stored,\n workspaceId,\n configId,\n wpType: 'artifact',\n })\n .then((r) => {\n if (r.docId) setSaved({ content, docId: r.docId })\n else setSaveError(new Error('The draft was stored but the server returned no document id'))\n })\n .catch((e: unknown) => setSaveError(e instanceof Error ? e : new Error(String(e))))\n // `clean` and `onCleaned` are deliberately not dependencies: a new function identity must not\n // store twice.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [needsSave, content, title, workspaceId, configId, attempt, mutateAsync])\n\n const docId = !artifact\n ? undefined\n : passThrough\n ? artifact.doc_ext_id\n : saved?.content === content\n ? saved.docId\n : undefined\n\n const text = useArtifactText(docId, { enabled: settled, retry: parseRetry })\n const { retry: retryText } = text\n\n const retry = useCallback(() => {\n if (saveError) setAttempt((n) => n + 1)\n else retryText()\n }, [saveError, retryText])\n\n let phase: StreamedArtifactPhase\n if (!settled || !artifact) phase = 'streaming'\n else if (saveError) phase = 'error'\n else if (!docId) phase = needsSave ? 'persisting' : 'streaming'\n else if (text.status === 'ready' && text.text) phase = 'ready'\n else if (text.status === 'error' || text.status === 'ready') phase = 'error'\n else phase = 'parsing'\n\n const error =\n phase !== 'error'\n ? null\n : (saveError ?? text.error ?? new Error('The document has no text to edit'))\n return { phase, artifact, docId, error, cleaned, retry }\n}\n"]}
@@ -1,7 +1,8 @@
1
1
  import { RedlineWithRegions, RedlineRegion } from './redline-core.cjs';
2
2
  export { RegionKind, buildHybridRedlineMarkdown, buildHybridRedlineWithRegions, normalizeMarkdown, revertRedlineRegion } from './redline-core.cjs';
3
3
  import * as _tanstack_react_query from '@tanstack/react-query';
4
- export { c as cleanDraftMarkdown, p as promoteBoldTitle, r as repairParsedStructure, a as repairParsedTitle, s as stripAgentPreamble, u as unescapeMarkdown, b as unwrapCitationLinks } from '../stored-markdown-BWTkS6wX.cjs';
4
+ import { D as DraftCleanReport } from '../stored-markdown-Bp18vrbr.cjs';
5
+ export { a as DraftCleanStage, c as cleanDraftMarkdown, b as cleanDraftWithReport, p as promoteBoldTitle, r as repairParsedStructure, d as repairParsedTitle, s as stripAgentPreamble, u as unescapeMarkdown, e as unwrapCitationLinks } from '../stored-markdown-Bp18vrbr.cjs';
5
6
  import { FC, ComponentPropsWithoutRef, ReactNode } from 'react';
6
7
  import { ArtifactEvent } from '@arbidocs/sdk/browser';
7
8
 
@@ -371,8 +372,14 @@ interface UseStreamedArtifactOptions {
371
372
  * is still streaming is never persisted half-written.
372
373
  */
373
374
  settled: boolean;
374
- /** Make the stored markdown from the streamed content. Defaults to `cleanDraftMarkdown`. */
375
+ /**
376
+ * Make the stored markdown from the streamed content. Default `cleanDraftWithReport`, which is
377
+ * guarded: it stores the raw streamed text (or links-only text) rather than a cleanup that would
378
+ * lose content (see `DraftCleanReport`).
379
+ */
375
380
  clean?: (streamed: string) => string;
381
+ /** Called once per stored draft with what the cleanup did (`stage` is not `cleaned` if guarded). */
382
+ onCleaned?: (report: DraftCleanReport) => void;
376
383
  /** Processing config for the stored version. */
377
384
  configId?: string | null;
378
385
  /** How long to wait for the parse (see `useArtifactText`). */
@@ -385,6 +392,8 @@ interface StreamedArtifact {
385
392
  /** The backend document to edit, once there is one (while `parsing` and `ready`). */
386
393
  docId: string | undefined;
387
394
  error: Error | null;
395
+ /** What the cleanup did to the stored draft (`null` until it was stored, or with a custom `clean`). */
396
+ cleaned: DraftCleanReport | null;
388
397
  /** After an `error`: store again or ask for the parse again. */
389
398
  retry: () => void;
390
399
  }
@@ -400,6 +409,6 @@ interface StreamedArtifact {
400
409
  * Needs an `<ArbiProvider>` and a workspace. `@arbidocs/blocks/connect` has the whole thing as a
401
410
  * component (`StreamedArtifact`).
402
411
  */
403
- declare function useStreamedArtifact({ artifacts, workspaceId, settled, clean, configId, parseRetry, }: UseStreamedArtifactOptions): StreamedArtifact;
412
+ declare function useStreamedArtifact({ artifacts, workspaceId, settled, clean, onCleaned, configId, parseRetry, }: UseStreamedArtifactOptions): StreamedArtifact;
404
413
 
405
- export { type ArtifactEditSession, type ArtifactEditSessionOptions, type ArtifactRedlineComponents, type ArtifactSaveResult, type ArtifactSession, type ArtifactSessionOptions, type ArtifactSessionView, type ArtifactText, type ArtifactTextRetry, type ArtifactTextStatus, type ArtifactVersion, DEFAULT_ARTIFACT_TEXT_RETRY, type RedlineEngine, RedlineRegion, type RedlineState, RedlineWithRegions, type SaveArtifactVersionInput, type StreamedArtifact, type StreamedArtifactPhase, type UseRedlineOptions, type UseRedlineResult, type UseStreamedArtifactOptions, type VersionedDoc, buildVersionChain, flattenChunks, isDocumentId, mainThreadRedlineEngine, renderArtifactMarkdown, toArtifactVersions, useArtifactEditSession, useArtifactSession, useArtifactText, useArtifactVersions, useRedline, useSaveArtifactVersion, useStreamedArtifact, versionLabel };
414
+ export { type ArtifactEditSession, type ArtifactEditSessionOptions, type ArtifactRedlineComponents, type ArtifactSaveResult, type ArtifactSession, type ArtifactSessionOptions, type ArtifactSessionView, type ArtifactText, type ArtifactTextRetry, type ArtifactTextStatus, type ArtifactVersion, DEFAULT_ARTIFACT_TEXT_RETRY, DraftCleanReport, type RedlineEngine, RedlineRegion, type RedlineState, RedlineWithRegions, type SaveArtifactVersionInput, type StreamedArtifact, type StreamedArtifactPhase, type UseRedlineOptions, type UseRedlineResult, type UseStreamedArtifactOptions, type VersionedDoc, buildVersionChain, flattenChunks, isDocumentId, mainThreadRedlineEngine, renderArtifactMarkdown, toArtifactVersions, useArtifactEditSession, useArtifactSession, useArtifactText, useArtifactVersions, useRedline, useSaveArtifactVersion, useStreamedArtifact, versionLabel };
@@ -1,7 +1,8 @@
1
1
  import { RedlineWithRegions, RedlineRegion } from './redline-core.js';
2
2
  export { RegionKind, buildHybridRedlineMarkdown, buildHybridRedlineWithRegions, normalizeMarkdown, revertRedlineRegion } from './redline-core.js';
3
3
  import * as _tanstack_react_query from '@tanstack/react-query';
4
- export { c as cleanDraftMarkdown, p as promoteBoldTitle, r as repairParsedStructure, a as repairParsedTitle, s as stripAgentPreamble, u as unescapeMarkdown, b as unwrapCitationLinks } from '../stored-markdown-BWTkS6wX.js';
4
+ import { D as DraftCleanReport } from '../stored-markdown-Bp18vrbr.js';
5
+ export { a as DraftCleanStage, c as cleanDraftMarkdown, b as cleanDraftWithReport, p as promoteBoldTitle, r as repairParsedStructure, d as repairParsedTitle, s as stripAgentPreamble, u as unescapeMarkdown, e as unwrapCitationLinks } from '../stored-markdown-Bp18vrbr.js';
5
6
  import { FC, ComponentPropsWithoutRef, ReactNode } from 'react';
6
7
  import { ArtifactEvent } from '@arbidocs/sdk/browser';
7
8
 
@@ -371,8 +372,14 @@ interface UseStreamedArtifactOptions {
371
372
  * is still streaming is never persisted half-written.
372
373
  */
373
374
  settled: boolean;
374
- /** Make the stored markdown from the streamed content. Defaults to `cleanDraftMarkdown`. */
375
+ /**
376
+ * Make the stored markdown from the streamed content. Default `cleanDraftWithReport`, which is
377
+ * guarded: it stores the raw streamed text (or links-only text) rather than a cleanup that would
378
+ * lose content (see `DraftCleanReport`).
379
+ */
375
380
  clean?: (streamed: string) => string;
381
+ /** Called once per stored draft with what the cleanup did (`stage` is not `cleaned` if guarded). */
382
+ onCleaned?: (report: DraftCleanReport) => void;
376
383
  /** Processing config for the stored version. */
377
384
  configId?: string | null;
378
385
  /** How long to wait for the parse (see `useArtifactText`). */
@@ -385,6 +392,8 @@ interface StreamedArtifact {
385
392
  /** The backend document to edit, once there is one (while `parsing` and `ready`). */
386
393
  docId: string | undefined;
387
394
  error: Error | null;
395
+ /** What the cleanup did to the stored draft (`null` until it was stored, or with a custom `clean`). */
396
+ cleaned: DraftCleanReport | null;
388
397
  /** After an `error`: store again or ask for the parse again. */
389
398
  retry: () => void;
390
399
  }
@@ -400,6 +409,6 @@ interface StreamedArtifact {
400
409
  * Needs an `<ArbiProvider>` and a workspace. `@arbidocs/blocks/connect` has the whole thing as a
401
410
  * component (`StreamedArtifact`).
402
411
  */
403
- declare function useStreamedArtifact({ artifacts, workspaceId, settled, clean, configId, parseRetry, }: UseStreamedArtifactOptions): StreamedArtifact;
412
+ declare function useStreamedArtifact({ artifacts, workspaceId, settled, clean, onCleaned, configId, parseRetry, }: UseStreamedArtifactOptions): StreamedArtifact;
404
413
 
405
- export { type ArtifactEditSession, type ArtifactEditSessionOptions, type ArtifactRedlineComponents, type ArtifactSaveResult, type ArtifactSession, type ArtifactSessionOptions, type ArtifactSessionView, type ArtifactText, type ArtifactTextRetry, type ArtifactTextStatus, type ArtifactVersion, DEFAULT_ARTIFACT_TEXT_RETRY, type RedlineEngine, RedlineRegion, type RedlineState, RedlineWithRegions, type SaveArtifactVersionInput, type StreamedArtifact, type StreamedArtifactPhase, type UseRedlineOptions, type UseRedlineResult, type UseStreamedArtifactOptions, type VersionedDoc, buildVersionChain, flattenChunks, isDocumentId, mainThreadRedlineEngine, renderArtifactMarkdown, toArtifactVersions, useArtifactEditSession, useArtifactSession, useArtifactText, useArtifactVersions, useRedline, useSaveArtifactVersion, useStreamedArtifact, versionLabel };
414
+ export { type ArtifactEditSession, type ArtifactEditSessionOptions, type ArtifactRedlineComponents, type ArtifactSaveResult, type ArtifactSession, type ArtifactSessionOptions, type ArtifactSessionView, type ArtifactText, type ArtifactTextRetry, type ArtifactTextStatus, type ArtifactVersion, DEFAULT_ARTIFACT_TEXT_RETRY, DraftCleanReport, type RedlineEngine, RedlineRegion, type RedlineState, RedlineWithRegions, type SaveArtifactVersionInput, type StreamedArtifact, type StreamedArtifactPhase, type UseRedlineOptions, type UseRedlineResult, type UseStreamedArtifactOptions, type VersionedDoc, buildVersionChain, flattenChunks, isDocumentId, mainThreadRedlineEngine, renderArtifactMarkdown, toArtifactVersions, useArtifactEditSession, useArtifactSession, useArtifactText, useArtifactVersions, useRedline, useSaveArtifactVersion, useStreamedArtifact, versionLabel };
@@ -1,5 +1,5 @@
1
- import { repairParsedStructure, repairParsedTitle, unescapeMarkdown, arbiQueryKeys, useDocuments, cleanDraftMarkdown } from '../chunk-EX4X2VTR.js';
2
- export { cleanDraftMarkdown, promoteBoldTitle, repairParsedStructure, repairParsedTitle, stripAgentPreamble, unescapeMarkdown, unwrapCitationLinks } from '../chunk-EX4X2VTR.js';
1
+ import { repairParsedStructure, repairParsedTitle, unescapeMarkdown, arbiQueryKeys, useDocuments, cleanDraftWithReport } from '../chunk-4XWSLFMN.js';
2
+ export { cleanDraftMarkdown, cleanDraftWithReport, promoteBoldTitle, repairParsedStructure, repairParsedTitle, stripAgentPreamble, unescapeMarkdown, unwrapCitationLinks } from '../chunk-4XWSLFMN.js';
3
3
  import { revertRedlineRegion, buildHybridRedlineWithRegions, buildHybridRedlineMarkdown, normalizeMarkdown } from '../chunk-43AKLNBC.js';
4
4
  export { buildHybridRedlineMarkdown, buildHybridRedlineWithRegions, normalizeMarkdown, revertRedlineRegion } from '../chunk-43AKLNBC.js';
5
5
  import { MarkdownRenderer } from '../chunk-TGGQGFS3.js';
@@ -530,7 +530,8 @@ function useStreamedArtifact({
530
530
  artifacts,
531
531
  workspaceId,
532
532
  settled,
533
- clean = cleanDraftMarkdown,
533
+ clean,
534
+ onCleaned,
534
535
  configId,
535
536
  parseRetry
536
537
  }) {
@@ -539,6 +540,7 @@ function useStreamedArtifact({
539
540
  const [saved, setSaved] = useState(null);
540
541
  const [saveError, setSaveError] = useState(null);
541
542
  const [attempt, setAttempt] = useState(0);
543
+ const [cleaned, setCleaned] = useState(null);
542
544
  const started = useRef(null);
543
545
  const content = artifact?.content ?? "";
544
546
  const title = artifact?.title ?? "Draft";
@@ -549,9 +551,22 @@ function useStreamedArtifact({
549
551
  if (!needsSave || started.current === key) return;
550
552
  started.current = key;
551
553
  setSaveError(null);
554
+ let stored;
555
+ if (clean) stored = clean(content);
556
+ else {
557
+ const report = cleanDraftWithReport(content);
558
+ stored = report.text;
559
+ setCleaned(report);
560
+ onCleaned?.(report);
561
+ if (report.guarded) {
562
+ console.warn(
563
+ `[useStreamedArtifact] the draft cleanup would have lost content; stored the ${report.stage} text instead (kept ${Math.round(report.ratio * 100)}%, changed by: ${report.changedBy.join(", ") || "nothing"})`
564
+ );
565
+ }
566
+ }
552
567
  mutateAsync({
553
568
  title,
554
- content: clean(content),
569
+ content: stored,
555
570
  workspaceId,
556
571
  configId,
557
572
  wpType: "artifact"
@@ -575,7 +590,7 @@ function useStreamedArtifact({
575
590
  else if (text.status === "error" || text.status === "ready") phase = "error";
576
591
  else phase = "parsing";
577
592
  const error = phase !== "error" ? null : saveError ?? text.error ?? new Error("The document has no text to edit");
578
- return { phase, artifact, docId, error, retry };
593
+ return { phase, artifact, docId, error, cleaned, retry };
579
594
  }
580
595
 
581
596
  export { DEFAULT_ARTIFACT_TEXT_RETRY, buildVersionChain, flattenChunks, isDocumentId, mainThreadRedlineEngine, renderArtifactMarkdown, toArtifactVersions, useArtifactEditSession, useArtifactSession, useArtifactText, useArtifactVersions, useRedline, useSaveArtifactVersion, useStreamedArtifact, versionLabel };