@loomcycle/explorer 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,17 +1,7 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("react"),l=require("react/jsx-runtime"),u=require("@loomcycle/client"),d=require("react-markdown");d=s(d,1);let f=require("remark-gfm");f=s(f,1);var p=`loomcycle.explorer.navigator`;function m(e){try{return e?.getItem(`loomcycle.explorer.navigator`)===`stars`?`stars`:`tree`}catch{return`tree`}}function h(e,t){try{e?.setItem(p,t)}catch{}}function g(e){return!!e&&!e.parent_id&&!!e.entity?.natural_key}function _(e){let t=e?.classes;if(!Array.isArray(t))return[];let n=new Set;for(let e of t){let{name:t,kind:r}=e??{};typeof t==`string`&&t!==``&&r!==`document`&&n.add(t)}return[...n].sort((e,t)=>e.localeCompare(t))}function v(e,t){let n=t??``;return n===``||e.some(e=>e.toLowerCase()===n.toLowerCase())?e:[n,...e]}function y(e){let t={op:e.op===`copy`?`copy_documents`:`move_documents`,scope:e.scope,to_scope:e.toScope,dry_run:e.dryRun};e.documentId&&(t.document_ids=[e.documentId]),e.underPath&&(t.under_path=e.underPath);let n=C(e.from),r=C(e.to);return n&&r&&n!==r&&(t.path_map={[n]:r}),e.op===`move`&&(e.dropDangling&&(t.dangling=`drop`),e.dryRun||(t.expect_count=e.expectCount??0)),t}function b(e){let t=e.to.trim();return t.startsWith(`/`)?e.op===`move`&&e.toScope===e.scope?`a move goes to another scope; to rename within this one, use rename / move`:e.op===`copy`&&e.toScope===e.scope&&C(t)===C(e.from)?`a copy into the same scope needs a new path`:null:`the new path must start with /`}function x(e,t){let n=t.counts??{},r=n.documents??0,i=e===`copy`?`copied`:`moved`,a=[],o=`${n.chunks??0} parts, ${n.revisions??0} revisions, ${n.statements??0} relations, ${n.assets??0} images`;if(t.dry_run)a.push(`${r} ${w(r,`document`)} would be ${i}: ${o}.`),t.to_finish?.length&&a.push(`${t.to_finish.length} ${w(t.to_finish.length,`document`)} left by an earlier interrupted move will be finished.`);else if(e===`move`){let e=t.moved?.length??0;a.push(`${e} ${w(e,`document`)} moved: ${o}.`)}else a.push(`${r} ${w(r,`document`)} copied: ${o}.`);let s=t.refused_count??t.refused?.length??0;if(s>0){a.push(`${s} ${w(s,`document`)} refused:`);for(let e of t.refused??[])a.push(` ${e.document_id}: ${e.code}${e.detail?` — ${e.detail}`:``}`)}if(t.dangling_count>0){e===`copy`?a.push(`${t.dangling_count} ${w(t.dangling_count,`relation`)} to documents outside the set stay behind.`):t.dropped===void 0?t.blocked_by===`dangling_relations`?a.push(`${t.dangling_count} ${w(t.dangling_count,`relation`)} join these documents to ones outside the set. A relation cannot span two scopes: include the other documents, or drop these relations.`):a.push(`${t.dangling_count} ${w(t.dangling_count,`relation`)} to documents outside the set will be dropped.`):a.push(`${t.dropped} ${w(t.dropped,`relation`)} to documents outside the set were dropped.`);for(let e of t.dangling??[])a.push(` ${e.kind}: ${e.from} → ${e.to} (outside: ${e.outside})`)}for(let e of t.unfinished??[])a.push(`not finished: ${e.document_id}: ${e.code}${e.detail?` — ${e.detail}`:``}. Run the move again.`);for(let e of t.name_failures??[])a.push(`no name ${e.path} for ${e.document_id}: ${e.error}`);return t.body_failures&&a.push(`${t.body_failures} ${w(t.body_failures,`body`,`bodies`)} could not be written.`),t.statements_failed&&a.push(`${t.statements_failed} ${w(t.statements_failed,`relation`)} could not be written${t.statement_error?`: ${t.statement_error}`:``}.`),a}function S(e,t,n){return e===`move`&&t.dangling_count>0&&!n||(t.counts?.documents??0)===0&&!(t.to_finish?.length??0)}function C(e){let t=e.trim(),n=t.length;for(;n>1&&t[n-1]===`/`;)n--;return t.slice(0,n)}function w(e,t,n=t+`s`){return e===1?t:n}function T(e){return e===`tenant`}var E=240,D=2e3,O=[`branch`,`document`,`path`];function k(e){return typeof e==`string`&&O.includes(e)}function A(e,t){return Array.isArray(e)?e.filter(e=>!!e&&typeof e==`object`&&e.chunk_id===t&&k(e.level)&&typeof e.brief==`string`&&e.brief.trim()!==``).sort((e,t)=>O.indexOf(e.level)-O.indexOf(t.level)):[]}async function j(e,t,n,r){return!T(n)||!e.documentGetAnnotation||!t?[]:A((await e.documentGetAnnotation(t,n,r))?.annotations,t)}function M(e){return e?`document`:`branch`}function N(e){return[...e].length}function ee(e,t){if(e.trim()===``)return`The brief is required.`;if(N(e)>240)return`The brief is longer than 240 characters.`;if(t.trim()===``)return`The abstract is required.`;if(N(t)>2e3)return`The abstract is longer than ${D} characters.`}function P(e,t){return{op:`set_annotation`,scope:t,id:e.id,level:e.level,brief:e.brief.trim(),abstract:e.abstract.trim(),manual:!0}}function F(e){if(e)return e.startsWith(`run:`)?`run ${e.slice(4)}`:e.startsWith(`principal:`)?e.slice(10):e}function I(e){if(!e)return;let t=Date.parse(e);return Number.isNaN(t)?e:new Date(t).toLocaleString()}function L(e){if(!e)return;let t=/filename\*\s*=\s*([^']*)'[^']*'([^;]+)/i.exec(e);if(t&&/^utf-8$/i.test(t[1].trim()))try{let e=R(decodeURIComponent(t[2].trim()));if(e)return e}catch{}let n=/(?:^|;)\s*filename\s*=\s*"((?:[^"\\]|\\.)*)"/i.exec(e);if(n)return R(n[1].replace(/\\(.)/g,`$1`))||void 0;let r=/(?:^|;)\s*filename\s*=\s*([^;\s"]+)/i.exec(e);if(r)return R(r[1])||void 0}function R(e){return e.slice(Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`))+1).trim()}function z(e,t,n=``){try{let t=JSON.parse(e);if(typeof t.error==`string`&&t.error)return t.error}catch{}return`${t} ${n}`.trim()}function te(e){return(e||`document`).replace(/[^\w.-]+/g,`_`)}function ne(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}var B=4,re=5e3;function ie(e,t,n){return{...ae(e,n),pathLs:(t,n,r,i,a)=>e.path({op:`ls`,path:t,scope:n,recursive:r,...a?.limit?{limit:a.limit}:{},...a?.cursor?{cursor:a.cursor}:{}},i),pathIsStored:(t,n,r)=>e.path({op:`stat`,path:t,scope:n},r).then(()=>!0,e=>{if(e?.name===`SubstrateToolRefusedError`)return!1;throw e}),documentPath:async(t,n,r)=>{let i;for(let a=0;a<B;a++){let a=await e.path({op:`ls`,path:`/`,scope:n,recursive:!0,kind_filter:`document`,limit:re,...i?{cursor:i}:{}},r),o=(a.entries??[]).find(e=>e.resource_ref?.document_id===t);if(o)return o.full_path;if(i=a.next_cursor||void 0,!i)return}},pathMkdir:(t,n,r)=>e.path({op:`mkdir`,path:t,scope:n},r),pathMv:(t,n,r,i)=>e.path({op:`mv`,path:t,to:n,scope:r},i),pathRm:(t,n,r,i)=>e.path({op:`rm`,path:t,scope:n,recursive:r},i),documentCreate:(t,n,r,i)=>e.document({op:`create_document`,title:t,path:n,scope:r},i),documentDelete:(t,n,r)=>e.document({op:`delete_document`,id:t,scope:n},r),documentsTransfer:(t,n)=>e.document(y(t),n),documentGet:(t,n,r)=>e.document({op:`get_document`,id:t,scope:n},r),documentsSummary:(t,n,r)=>e.document({op:`documents_summary`,scope:n,...t.documentIds?{document_ids:t.documentIds}:{},...t.underPath?{under_path:t.underPath}:{}},r),documentQueryChunks:(t,n,r)=>e.document({op:`query_chunks`,document_id:t,scope:n,limit:1e3},r),documentGetChunk:(t,n,r)=>e.document({op:`get_chunk`,id:t,scope:n},r),documentCreateChunk:(t,n,r,i,a,o)=>e.document({op:`create_chunk`,document_id:t,parent_id:n,scope:i,...o?{after_id:o}:{},...r},a),documentReorderChunk:(t,n,r,i)=>e.document({op:`reorder_chunk`,id:t,direction:n,scope:r},i),documentDeleteChunk:(t,n,r)=>e.document({op:`delete_chunk`,id:t,scope:n},r),documentSetAsset:(t,n,r,i,a,o)=>e.document({op:`set_asset`,id:t,media_type:n,data:r,...i?{filename:i}:{},scope:a},o),documentGetEdges:(t,n,r,i)=>e.document({op:`get_edges`,document_id:t,scope:n,...i?.after?{after:i.after}:{}},r),documentGetEdge:(t,n,r)=>e.document({op:`get_edge`,id:t,scope:n},r),documentAcceptStatement:(t,n,r,i)=>e.document({op:`accept_statement`,id:t,scope:n,...i?{reason:i}:{}},r),documentRejectStatement:(t,n,r,i)=>e.document({op:`reject_statement`,id:t,reason:n,scope:r},i),documentListStatements:(t,n,r)=>e.document({op:`list_statements`,scope:t,...r?.status?{status:r.status}:{},...r?.kind?{kind:r.kind}:{},...r?.limit?{limit:r.limit}:{},...r?.after?{after:r.after}:{}},n),documentClassify:(t,n,r,i)=>e.document({op:`classify`,document_id:t,write:n,scope:r},i),documentEntityTypes:(t,n)=>e.document({op:`describe_ontology`,scope:t},n).then(_),documentAcceptClassification:(t,n,r)=>e.document({op:`accept_classification`,document_id:t,scope:n},r),documentGetAnnotation:(t,n,r)=>e.document({op:`get_annotation`,id:t,scope:n},r),documentSetAnnotation:(t,n,r)=>e.document(P(t,n),r),documentUpdateChunk:(t,n,r,i,a)=>e.document({op:`update_chunk`,id:t,revision:n,scope:i,...r},a),documentExportMd:(t,n,r,i)=>e.document({op:`export_md`,document_id:t,scope:n,include_metadata:r},i),documentBacklinks:(t,n,r)=>e.document({op:`backlinks`,id:t,scope:n},r),documentRelated:(t,n,r,i)=>e.document({op:`related`,id:t,scope:n,...i?{limit:i}:{}},r),documentUnlinkedMentions:(t,n,r,i)=>e.document({op:`unlinked_mentions`,id:t,scope:n,...i?{limit:i}:{}},r),documentHistory:(t,n,r,i)=>e.document({op:`history`,id:t,scope:n,...i?{limit:i}:{}},r),documentGetVersion:(t,n,r,i)=>e.document({op:`get_version`,id:t,revision:n,scope:r},i),documentDiff:(t,n,r,i,a)=>e.document({op:`diff`,id:t,from_revision:n,to_revision:r,scope:i},a),documentExportCanvas:(t,n,r)=>e.document({op:`export_canvas`,document_id:t,scope:n},r),...t?{documentAssetObjectUrl:async(e,n,r)=>{let i=new URLSearchParams({scope:n});r?.scopeId&&i.set(`scope_id`,r.scopeId),r?.tenant&&i.set(`tenant`,r.tenant);let a=await t(`/v1/_document/asset/${encodeURIComponent(e)}?${i.toString()}`);if(!a.ok)throw Error(`asset fetch failed: ${a.status}`);let o=await a.blob();return URL.createObjectURL(o)},documentExportFile:async(e,n,r,i,a)=>{let o=await t(V(e,n,r,i,a));if(!o.ok)throw Error(z(await o.text(),o.status,o.statusText));return{blob:await o.blob(),filename:L(o.headers.get(`Content-Disposition`))??``}}}:{}}}function V(e,t,n,r,i){let a=new URLSearchParams({format:n,scope:t});return r?.scopeId&&a.set(`scope_id`,r.scopeId),r?.tenant&&a.set(`tenant`,r.tenant),i?.chunk&&a.set(`chunk`,i.chunk),i?.toc&&a.set(`toc`,`true`),i?.titlePage&&a.set(`title_page`,`true`),i?.pageSize&&a.set(`page_size`,i.pageSize),i?.language&&a.set(`language`,i.language),i?.provenance===!1&&a.set(`provenance`,`false`),`/v1/_document/export/${encodeURIComponent(e)}?${a.toString()}`}function ae(e,t){let n=e,r=e=>e?.tenant?`?tenant=${encodeURIComponent(e.tenant)}`:``,i={};typeof n.ruleStatements==`function`?i.documentRuleStatements=(e,t)=>n.ruleStatements(e.action,e.ids?{ids:e.ids}:{filter:e.filter},{reason:e.reason,dryRun:e.dry_run,expectCount:e.expect_count,max:e.max,scope:e.scope,scopeId:e.scope_id,tenant:t?.tenant}):t&&(i.documentRuleStatements=(e,n)=>t(`/v1/_statements/rule${r(n)}`,e));let a=(e,t)=>e===`user`&&t?.scopeId?t.scopeId:void 0;return typeof n.revertRuling==`function`?i.documentRevertRuling=(e,t,r)=>n.revertRuling(e,{scope:t,scopeId:a(t,r),tenant:r?.tenant}):t&&(i.documentRevertRuling=(e,n,i)=>{let o=a(n,i);return t(`/v1/_statements/revert${r(i)}`,{ruling_id:e,scope:n,...o?{scope_id:o}:{}})}),i}var oe=(0,c.createContext)(null);function se({value:e,children:t}){return(0,l.jsx)(oe.Provider,{value:e,children:t})}function H(){let e=(0,c.useContext)(oe);if(!e)throw Error(`useExplorerData must be used within <PathExplorer> or <DocumentViewer> (no ExplorerDataLayer in context)`);return e}var ce=5e3;function le(e){return e===``?`/`:e}function ue(e){let t=e.lastIndexOf(`/`);return t<=0?``:e.slice(0,t)}function U(e){let t=[``],n=e.split(`/`).filter(Boolean),r=``;for(let e=0;e<n.length-1;e++)r=`${r}/${n[e]}`,t.push(r);return t}function de(e){return e instanceof Error?e.message:String(e)}function W(e,t){return{entries:[...t,...e.entries??[]],nextCursor:e.next_cursor||void 0,loaded:!0,loading:!1}}var fe=class{data;scope;browse;pageLimit;dirs=new Map;snapshot=new Map;listeners=new Set;inflight=new Map;epoch=new Map;constructor(e,t,n,r=500){this.data=e,this.scope=t,this.browse=n,this.pageLimit=r}getSnapshot=()=>this.snapshot;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});publish(){this.snapshot=new Map(this.dirs),this.listeners.forEach(e=>e())}set(e,t){this.dirs.set(e,t),this.publish()}track(e,t){let n=t.finally(()=>{this.inflight.get(e)===n&&this.inflight.delete(e)});return this.inflight.set(e,n),n}loadDir(e){return this.inflight.get(e)||(this.dirs.get(e)?.loaded?Promise.resolve():this.fetchFirst(e,this.pageLimit))}reload(e){let t=this.dirs.get(e),n=t?.entries.length??0,r=t?.loaded&&!t.nextCursor?n+this.pageLimit:n;return this.fetchFirst(e,Math.min(ce,Math.max(this.pageLimit,r)))}fetchFirst(e,t){let n=(this.epoch.get(e)??0)+1;this.epoch.set(e,n);let r=this.dirs.get(e);this.set(e,{entries:r?.entries??[],nextCursor:r?.nextCursor,loaded:r?.loaded??!1,loading:!0});let i=this.data.pathLs(le(e),this.scope,!1,this.browse,{limit:t}).then(t=>{this.epoch.get(e)===n&&this.set(e,W(t,[]))},t=>{throw this.epoch.get(e)===n&&this.set(e,{entries:r?.entries??[],nextCursor:r?.nextCursor,loaded:r?.loaded??!1,loading:!1,error:de(t)}),t});return this.track(e,i)}loadMore(e){let t=this.inflight.get(e);if(t)return t;let n=this.dirs.get(e);if(!n?.nextCursor)return Promise.resolve();let r=this.epoch.get(e)??0;this.set(e,{...n,loading:!0,error:void 0});let i=this.data.pathLs(le(e),this.scope,!1,this.browse,{limit:this.pageLimit,cursor:n.nextCursor}).then(t=>{this.epoch.get(e)===r&&this.set(e,W(t,n.entries))},t=>{throw this.epoch.get(e)===r&&this.set(e,{...n,loading:!1,error:de(t)}),t});return this.track(e,i)}async reveal(e){let t=e.split(`/`).filter(Boolean),n=``;for(let e of t){for(await this.loadDir(n);;){let t=this.dirs.get(n);if(!t)return!1;if(t.entries.some(t=>t.name===e))break;let r=t.entries[t.entries.length-1];if(!t.nextCursor||r&&r.name>e)return!1;let i=t.nextCursor;if(await this.loadMore(n),this.dirs.get(n)?.nextCursor===i)return!1}n=`${n}/${e}`}return!0}async invalidate(e,t){if(t?.dropSubtree){for(let t of[...this.dirs.keys()])(t===e||t.startsWith(`${e}/`))&&(this.dirs.delete(t),this.epoch.set(t,(this.epoch.get(t)??0)+1),this.inflight.delete(t));this.publish()}let n=U(e).filter(e=>this.dirs.has(e));await Promise.all(n.map(e=>this.reload(e)))}async refresh(e){let t=new Set(e);t.add(``);for(let e of[...this.dirs.keys()])t.has(e)||(this.dirs.delete(e),this.epoch.set(e,(this.epoch.get(e)??0)+1),this.inflight.delete(e));this.publish();let n=[...t].filter(e=>e===``||this.dirs.has(e));await Promise.all(n.map(e=>this.reload(e)))}};async function G(e,t,n,r){let i=[],a;for(;;){let o=await e.pathLs(le(t),n,!0,r,{limit:ce,cursor:a});i.push(...o.entries??[]);let s=o.next_cursor||void 0;if(!s||s===a)return i;a=s}}function pe(e){let t=[];for(let n of e){if(n.kind!==`document`)continue;let e=n.resource_ref?.document_id;e&&t.push(e)}return t}function me(e){let t=e.fetch;return new u.LoomcycleClient({baseUrl:e.baseUrl,authToken:e.token||void 0,fetch:(e,n)=>t?t(e,n):fetch(e,n)})}function he(e){let t=e.fetch,n=(e,n)=>t?t(e,n):fetch(e,n);return t=>{let r={};return e.token&&(r.Authorization=`Bearer ${e.token}`),n(e.baseUrl+t,{headers:r})}}var K=class extends Error{status;code;constructor(e,t,n){super(e),this.name=`RequestError`,this.status=t,this.code=n}};function ge(e){let t=e.fetch,n=(e,n)=>t?t(e,n):fetch(e,n);return async(t,r)=>{let i={"Content-Type":`application/json`,Accept:`application/json`};e.token&&(i.Authorization=`Bearer ${e.token}`);let a=await n(e.baseUrl+t,{method:`POST`,headers:i,body:JSON.stringify(r)}),o=await a.text(),s;try{s=o?JSON.parse(o):void 0}catch{}if(!a.ok){let e=s&&typeof s==`object`?s:{};throw new K(typeof e.error==`string`&&e.error?e.error:`${a.status} ${a.statusText}`.trim(),a.status,typeof e.code==`string`?e.code:void 0)}return s}}function q(e){let{dataLayer:t,client:n,connection:r}=e;return(0,c.useMemo)(()=>t||(n?ie(n):r?ie(me(r),he(r),ge(r)):null),[t,n,r?.baseUrl,r?.token,r?.fetch])}function _e({theme:e,dataLayer:t,children:n}){let r=e?{"data-theme":e}:{};return t?(0,l.jsx)(`div`,{className:`loomcycle-explorer`,...r,children:(0,l.jsx)(se,{value:t,children:n})}):(0,l.jsx)(`div`,{className:`loomcycle-explorer`,...r,children:(0,l.jsxs)(`div`,{className:`error-banner`,children:[`@loomcycle/explorer: provide a `,(0,l.jsx)(`code`,{children:`connection`}),`, `,(0,l.jsx)(`code`,{children:`client`}),`, or`,` `,(0,l.jsx)(`code`,{children:`dataLayer`}),` prop.`]})})}function ve(e,t,n){let r=e[e.length-1];return[...r&&r.documentId===t.documentId?[...e.slice(0,-1),{...r,...xe(t)}]:[...e,t],n]}function ye(e,t){return t<0||t>=e.length-1?e:e.slice(0,t+1)}function be(e,t,n){let r=e[e.length-1];if(!r||r.documentId!==t)return e;let i={...r,...xe(n)};return i.title===r.title&&i.path===r.path?e:[...e.slice(0,-1),i]}function xe(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function Se(e){return e.title?e.title:e.path?e.path.slice(e.path.lastIndexOf(`/`)+1)||e.path:e.documentId.slice(0,8)}function Ce(e,t=4){let n=Array.from({length:e},(e,t)=>({kind:`crumb`,index:t}));if(e<=t||t<3)return n;let r=t-1,i=Array.from({length:e-1-r},(e,t)=>t+1);return[n[0],{kind:`gap`,hidden:i},...n.slice(e-r)]}function we(e,t){for(let n of e.values()){let e=n.entries.find(e=>Te(e)===t);if(e)return e.full_path}}function Te(e){if(e.kind===`document`)return e.resource_ref?.document_id||void 0}function Ee(e,t){return t&&e.some(e=>e.id===t)?t:e.find(e=>!e.parent_id)?.id}function De({trail:e,onJump:t}){let[n,r]=(0,c.useState)(!1);if(e.length<2)return null;let i=e.length-1,a=e[i-1],o=Ce(e.length,n?e.length:void 0);return(0,l.jsxs)(`nav`,{className:`doc-trail`,"aria-label":`Documents you came through`,children:[(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-back`,onClick:()=>t(i-1),title:`Back to ${Se(a)}`,children:`← Back`}),(0,l.jsx)(`ol`,{className:`doc-trail-list`,children:o.map(n=>n.kind===`gap`?(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-gap`,onClick:()=>r(!0),title:`Show ${n.hidden.length} more: ${n.hidden.map(t=>Se(e[t])).join(` › `)}`,"aria-label":`Show ${n.hidden.length} hidden documents`,children:`…`})},`gap`):n.index===i?(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`span`,{className:`doc-trail-current`,"aria-current":`page`,title:Se(e[i]),children:Se(e[i])})},n.index):(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-crumb`,onClick:()=>t(n.index),title:Se(e[n.index]),children:Se(e[n.index])})},n.index))})]})}function Oe({data:e,scope:t,browse:n,documentId:r,underPath:i,fromPath:a,onClose:o,onDone:s}){let[u,d]=(0,c.useState)(`copy`),[f,p]=(0,c.useState)(t===`tenant`?`user`:`tenant`),[m,h]=(0,c.useState)(a),[g,_]=(0,c.useState)(!1),[v,C]=(0,c.useState)(null),[w,T]=(0,c.useState)(null),[E,D]=(0,c.useState)(!1),[O,k]=(0,c.useState)(null),A=(0,c.useMemo)(()=>({op:u,scope:t,toScope:f,documentId:r,underPath:i,from:a,to:m,dropDangling:g,dryRun:!0}),[u,t,f,r,i,a,m,g]),j=JSON.stringify(y(A)),M=b(A),N=v&&v.key===j?v.res:null,ee=N?S(u,N,g):!1,P=N?u===`move`?(N.counts?.documents??0)+(N.to_finish?.length??0):N.counts?.documents??0:0,F=async t=>{if(t.preventDefault(),w)o();else if(!M&&e.documentsTransfer){D(!0),k(null);try{if(!N)C({key:j,res:await e.documentsTransfer(A,n)});else{let t={...A,dryRun:!1,expectCount:N.counts?.documents??0},r=await e.documentsTransfer(t,n);T(r),s(t,r)}}catch(e){k(e instanceof Error?e.message:String(e))}finally{D(!1)}}},I=w?`close`:E?`working…`:N?`${u} ${P} document${P===1?``:`s`}`:`check`,L=w??N;return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:E?void 0:o,children:(0,l.jsxs)(`form`,{className:`modal`,onClick:e=>e.stopPropagation(),onSubmit:F,children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsxs)(`h3`,{children:[`Copy or move the `,r?`document`:`documents under`,` `,a]}),(0,l.jsxs)(`div`,{className:`modal-buttons modal-buttons-top`,children:[!w&&(0,l.jsx)(`button`,{type:`button`,onClick:o,disabled:E,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:N&&u===`move`&&!w?`danger`:`primary`,disabled:E||!w&&(!!M||ee),children:I})]})]}),(0,l.jsxs)(`p`,{className:`modal-context`,children:[`A copy gets new ids and leaves the source as it is. A move keeps every id and removes the documents from `,(0,l.jsx)(`code`,{children:t}),`. Relations between the documents go with them.`]}),(0,l.jsx)(`div`,{className:`paths-nav-switch`,role:`group`,"aria-label":`Copy or move`,children:[`copy`,`move`].map(e=>(0,l.jsx)(`button`,{type:`button`,"aria-pressed":u===e,className:u===e?`active`:void 0,disabled:E||!!w,onClick:()=>d(e),children:e},e))}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`To scope`}),(0,l.jsxs)(`select`,{value:f,disabled:E||!!w,onChange:e=>p(e.target.value),children:[(0,l.jsx)(`option`,{value:`user`,children:`user`}),(0,l.jsx)(`option`,{value:`agent`,children:`agent`}),(0,l.jsx)(`option`,{value:`tenant`,children:`tenant`})]})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`New path`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:m,disabled:E||!!w,onChange:e=>h(e.target.value)})]}),u===`move`&&(0,l.jsx)(`label`,{className:`path-field`,children:(0,l.jsxs)(`span`,{children:[(0,l.jsx)(`input`,{type:`checkbox`,checked:g,disabled:E||!!w,onChange:e=>_(e.target.checked)}),` `,`Drop relations to documents outside the set`]})}),M&&(0,l.jsx)(`div`,{className:`modal-err`,children:M}),L&&(0,l.jsx)(`div`,{className:`modal-context`,"aria-live":`polite`,children:x(u,L).map((e,t)=>e.startsWith(` `)?(0,l.jsx)(`div`,{children:(0,l.jsx)(`code`,{children:e.trim()})},t):(0,l.jsx)(`div`,{children:e},t))}),O&&(0,l.jsx)(`div`,{className:`modal-err`,children:O})]})})}var ke=6;function Ae({children:e,defaultLeftWidth:t=380,minLeftWidth:n=180,minRightWidth:r=240,storageKey:i,className:a,hideRight:o=!1}){let s=()=>{if(i){let e=localStorage.getItem(i),t=e?parseInt(e,10):NaN;if(Number.isFinite(t)&&t>=n)return t}return t},[u,d]=(0,c.useState)(s),[f,p]=(0,c.useState)(i);f!==i&&(p(i),d(s()));let m=(0,c.useRef)(null),[h,g]=(0,c.useState)(!1);(0,c.useEffect)(()=>{i&&!h&&f===i&&localStorage.setItem(i,String(Math.round(u)))},[i,f,u,h]);let _=(0,c.useCallback)(e=>{e.preventDefault(),g(!0),e.target.setPointerCapture(e.pointerId)},[]),v=(0,c.useCallback)(e=>{if(!h||!m.current)return;let t=m.current.getBoundingClientRect(),i=e.clientX-t.left,a=t.width-r-ke;d(Math.max(n,Math.min(i,a)))},[h,n,r]),y=(0,c.useCallback)(e=>{g(!1);try{e.target.releasePointerCapture(e.pointerId)}catch{}},[]);return(0,l.jsxs)(`div`,{ref:m,className:`splitter ${a??``} ${h?`dragging`:``}`,style:{gridTemplateColumns:o?`1fr 0 0`:`min(${u}px, calc(100% - ${r+ke}px)) ${ke}px 1fr`},children:[(0,l.jsx)(`div`,{className:`splitter-pane splitter-left`,children:e[0]}),(0,l.jsx)(`div`,{hidden:o,className:`splitter-handle`,role:`separator`,"aria-orientation":`vertical`,"aria-valuenow":Math.round(u),onPointerDown:_,onPointerMove:v,onPointerUp:y,onPointerCancel:y}),(0,l.jsx)(`div`,{className:`splitter-pane splitter-right`,hidden:o,children:e[1]})]})}var je=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`];function J(e){return je.includes(e)}function Me(e){return new Promise((t,n)=>{if(!J(e.type)){n(Error(`unsupported image type "${e.type||`unknown`}" (png, jpeg, gif, webp only)`));return}let r=new FileReader;r.onerror=()=>n(r.error??Error(`failed to read file`)),r.onload=()=>{let i=String(r.result??``),a=i.indexOf(`,`);a<0?n(Error(`could not decode image data`)):t({mediaType:e.type,data:i.slice(a+1)})},r.readAsDataURL(e)})}function Ne(e){if(!e)return null;for(let t=0;t<e.length;t++){let n=e[t];if(n.kind===`file`&&J(n.type)){let e=n.getAsFile();if(e)return e}}return null}var Pe=20;async function Fe(e,t,n,r,i=20){let a=[],o;for(let s=0;s<i;s++){let i=await e.documentGetEdges(t,n,r,o?{after:o}:void 0);if(o&&i.next_cursor===o)return{edges:a,incomplete:!0};if(a.push(...i.edges??[]),!i.truncated)return{edges:a,incomplete:!1};if(!i.next_cursor)return{edges:a,incomplete:!0};o=i.next_cursor}return{edges:a,incomplete:!0}}function Ie(e,t){if(!t)return[];let n=new Map(e.map(e=>[e.id,e])),r=new Set([t]),i=[],a=n.get(t)?.parent_id;for(;a&&!r.has(a);){let e=n.get(a);if(!e)break;r.add(a),i.push(e),a=e.parent_id}return i.reverse()}var Le=new Set([`manual`,`wikilink`]),Y=280;function Re(e){return e.status&&e.status!==`asserted`?e.status:void 0}function X(e){return e.method&&!Le.has(e.method)?e.method:void 0}function Z(e){return e.status===`proposed`&&!!e.id}function Q(e){return new Date(Math.floor(e/1e6)).toISOString().slice(0,10)}function ze(e){let t=e.valid_at==null?void 0:Q(e.valid_at),n=e.invalid_at==null?void 0:Q(e.invalid_at);if(t&&n)return`valid ${t} → ${n}`;if(t)return`valid from ${t}`;if(n)return`valid until ${n}`}function Be(e){if(e.judged_at==null)return;let t=`judged by ${e.judged_by||`a judge`} on ${Q(e.judged_at)}`;return e.judge_reason?`${t}: ${e.judge_reason}`:t}function Ve(e,t=3){let n=(e.evidence??[]).slice(0,t),r=Math.max(e.evidence_count??0,e.evidence?.length??0);return{rows:n,more:Math.max(0,r-n.length)}}function He(e,t=Y){let n=e.replace(/\s+/g,` `).trim();return n.length>t?n.slice(0,t-1)+`…`:n}var $=1e3,Ue=3,We=1e3;function Ge(e){return!!e&&typeof e==`object`&&e.code===`queue_changed`}async function Ke(e,t,n={}){let r={action:t.action,...t.ids?{ids:t.ids}:{filter:t.filter??{}},...t.reason?{reason:t.reason}:{},...t.scope&&t.scope!==`tenant`?{scope:t.scope}:{},...t.scope===`user`&&t.scopeId?{scope_id:t.scopeId}:{}},i={rulingIds:[],ruled:0,failed:0,skipped:0,total:0,cancelled:!1,failures:[]},a=async()=>{let t=await e.rule({...r,dry_run:!0});return i.skipped=t.skipped,t},o=async(e,t)=>!n.confirm||await n.confirm(e,t)?(i.total=i.ruled+e.matched,!0):(i.cancelled=!0,!1),s;try{s=await a()}catch(e){return i.error=e,i}if(s.matched===0||!await o(s,`first`))return i;let c=0;for(let t=0;t<We&&s.to_rule!==0;t++){let t;try{t=await e.rule({...r,dry_run:!1,expect_count:s.matched})}catch(e){if(!Ge(e)||c>=3)return i.error=e,i;c++;try{s=await a()}catch(e){return i.error=e,i}if(s.matched===0||!await o(s,`queue_changed`))return i;continue}t.ruling_id&&i.rulingIds.push(t.ruling_id),i.ruled+=t.ruled,i.failed+=t.failed;for(let e of t.items??[])e.error&&i.failures.push(e);if(n.onProgress?.({ruled:i.ruled,failed:i.failed,total:i.total,chunks:i.rulingIds.length}),t.ruled===0||t.matched<=t.selected)break;try{s=await a()}catch(e){return i.error=e,i}if(s.matched===0)break;if(s.matched>i.total-i.ruled&&!await o(s,`grew`))return i}return i}async function qe(e,t){let n={reverted:0,changed:0,errors:[]};for(let r of[...t].reverse())try{let t=await e(r);n.reverted+=t.reverted,n.changed+=t.changed}catch(e){n.errors.push(e instanceof Error?e.message:String(e))}return n}function Je(e){return Math.max(1,Math.ceil(e/$))}function Ye(e){return e===`tenant`||e===`user`?e:void 0}function Xe(e,t){return e.documentRuleStatements?Ye(t):void 0}function Ze(e,t){return e.filter(e=>Z(e)&&!!e.id&&e.from_document_id===t)}function Qe(e,t,n,r){return e?{proposals:t,scope:e,incomplete:n,onChanged:r}:void 0}function $e(e,t,n){return e.documentRuleStatements?Ke({rule:n=>e.documentRuleStatements(n,t.browse)},{action:t.action,...t.ids&&t.ids.length>0?{ids:t.ids}:{filter:{from_document_id:t.documentId}},...t.reason?{reason:t.reason}:{},scope:t.scope,...t.scope===`user`&&t.browse?.scopeId?{scopeId:t.browse.scopeId}:{}},n):Promise.reject(Error(`this data layer cannot rule in bulk`))}function et(e,t){let n=e=>e.toLocaleString(`en-US`),r=[`${e===`accept`?`Accepted`:`Rejected`} ${n(t.ruled)} statement${t.ruled===1?``:`s`}`];return t.failed>0&&r.push(`${n(t.failed)} did not take the ruling`),t.skipped>0&&r.push(`${n(t.skipped)} skipped: not yours to rule`),r.join(`; `)+`.`}var tt={"doc.rfc.draft":`#c99a3a`,"doc.rfc.review":`#6a7bd6`,"doc.rfc.confirmed":`#3a9ad6`,"doc.rfc.done":`#3aa06a`,"doc.plan.draft":`#c99a3a`,"doc.plan.review":`#6a7bd6`,"doc.plan.confirmed":`#3a9ad6`,"doc.plan.done":`#3aa06a`,"doc.document.done":`#3aa06a`,"doc.research.done":`#8a6ad6`,"doc.publication.draft":`#c99a3a`,"doc.*.draft":`#c99a3a`,"doc.*.review":`#6a7bd6`,"doc.*.confirmed":`#3a9ad6`,"doc.*.done":`#3aa06a`,"chunk.draft":`#c99a3a`,"chunk.review":`#6a7bd6`,"chunk.confirmed":`#3a9ad6`,"chunk.done":`#3aa06a`,"chunk.backlog":`#8a8f98`,"chunk.implementation":`#d1863a`,"chunk.merged":`#3aa06a`},nt=.16;function rt(e){return e&&Object.keys(e).length>0?e:tt}function it(e,t){if(Object.prototype.hasOwnProperty.call(e,t)&&e[t])return e[t];let n=t.toLowerCase();for(let t of Object.keys(e))if(t.toLowerCase()===n&&e[t])return e[t]}function at(e,t,n){let r=e??``,i=t??``;return(r&&i?it(n,`doc.${r}.${i}`):void 0)??(r?it(n,`doc.${r}`):void 0)??(i?it(n,`doc.*.${i}`):void 0)??it(n,`doc.*`)}function ot(e,t){let n=e??``;return n?it(t,`chunk.${n}`):void 0}function st(e){let t=String(e[`chunk.inherit`]??``).trim().toLowerCase();return t!==`false`&&t!==`none`&&t!==`off`&&t!==`0`}function ct(e,t=nt){let n=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e.trim());if(!n)return;let r=n[1];return r.length===3&&(r=r[0]+r[0]+r[1]+r[1]+r[2]+r[2]),`rgba(${parseInt(r.slice(0,2),16)}, ${parseInt(r.slice(2,4),16)}, ${parseInt(r.slice(4,6),16)}, ${t})`}function lt(e){if(!e)return;let t=ct(e);if(t)return{background:t,borderLeft:`3px solid ${e}`}}function ut(e){if(!e)return;let t=ct(e,nt/2);return t?{background:t}:void 0}function dt(e){let{status:t,isRoot:n,documentColor:r,scheme:i}=e;if(i)return n?lt(r)??lt(ot(t,i)):lt(ot(t,i))??(st(i)?ut(r):void 0)}async function ft(e){try{return typeof navigator>`u`||!navigator.clipboard?!1:(await navigator.clipboard.writeText(e),!0)}catch{return!1}}function pt({value:e,label:t,compact:n,title:r}){let[i,a]=(0,c.useState)(`idle`),o=async t=>{t.stopPropagation(),t.preventDefault();let n=await ft(e);a(n?`copied`:`error`),window.setTimeout(()=>a(`idle`),n?1200:1500)},s=i===`copied`?`✓`:i===`error`?`✗`:`⎘`,u=r??`Copy ${t??`id`}: ${e}`,d=(0,l.jsx)(`button`,{type:`button`,className:`id-copy-btn id-copy-${i}`,onClick:o,title:u,"aria-label":u,children:s});return n?d:(0,l.jsxs)(`span`,{className:`id-copy`,children:[t&&(0,l.jsx)(`span`,{className:`id-copy-label`,children:t}),(0,l.jsx)(`code`,{className:`id-copy-value`,title:e,children:e}),d]})}function mt(e){let t=new Map;e.forEach(e=>t.set(e.id,{row:e,children:[]}));let n=[];e.forEach(e=>{let r=t.get(e.id);e.parent_id&&t.has(e.parent_id)?t.get(e.parent_id).children.push(r):n.push(r)});let r=e=>{e.sort((e,t)=>e.row.position-t.row.position),e.forEach(e=>r(e.children))};return r(n),n}function ht(e){return e===`image`?`🖼`:e===`mermaid`?`📊`:``}function gt(e,t){for(let n of e){if(n.row.id===t)return n;let e=gt(n.children,t);if(e)return e}}function _t({tree:e,selectedId:t,onSelect:n,colorEnabled:r,scheme:i,documentColor:a,linkedIds:o}){let[s,u]=(0,c.useState)(()=>new Map),d=(0,c.useCallback)(e=>{u(t=>{let n=new Map(t);return n.set(e,t.get(e)===!1),n})},[]);(0,c.useEffect)(()=>{if(!t)return;let n=vt(e,t);n.length!==0&&u(e=>{let t=!1,r=new Map(e);for(let e of n)r.get(e)===!1&&(r.set(e,!0),t=!0);return t?r:e})},[e,t]);let f=r?rt(i):null;return e.length===0?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`No chunks.`})}):(0,l.jsx)(`ul`,{className:`tree chunk-tree`,children:e.map(e=>(0,l.jsx)(yt,{node:e,expanded:s,toggle:d,selectedId:t,onSelect:n,tintScheme:f,documentColor:a,isRoot:!0,linkedIds:o},e.row.id))})}function vt(e,t){let n=[],r=(e,i)=>{for(let a of e){if(a.row.id===t)return n.push(...i),!0;if(r(a.children,[...i,a.row.id]))return!0}return!1};return r(e,[]),n}function yt({node:e,expanded:t,toggle:n,selectedId:r,onSelect:i,tintScheme:a,documentColor:o,isRoot:s=!1,linkedIds:c}){let u=e.children.length>0,d=t.get(e.row.id)!==!1,f=r===e.row.id,p=dt({status:e.row.status,isRoot:s,documentColor:o,scheme:a}),m=c?.has(e.row.id);return(0,l.jsxs)(`li`,{className:`node chunk-node ${f?`selected`:``}`,children:[(0,l.jsxs)(`div`,{className:`row chunk-row`,style:p,children:[(0,l.jsx)(`button`,{type:`button`,className:`tree-caret`,"aria-label":d?`collapse`:`expand`,disabled:!u,onClick:t=>{t.stopPropagation(),u&&n(e.row.id)},children:u?d?`▼`:`▶`:`·`}),(0,l.jsxs)(`button`,{type:`button`,className:`chunk-link`,onClick:()=>i(e),title:e.row.title,children:[ht(e.row.type)&&(0,l.jsx)(`span`,{className:`chunk-type-icon`,"aria-hidden":!0,children:ht(e.row.type)}),(0,l.jsx)(`span`,{className:`chunk-title`,children:e.row.title||`(untitled)`}),e.row.type&&(0,l.jsx)(`span`,{className:`chunk-badge`,children:e.row.type}),e.row.status&&(0,l.jsx)(`span`,{className:`chunk-badge chunk-status`,children:e.row.status}),m&&(0,l.jsx)(`span`,{className:`chunk-link-badge`,title:`Has cross-reference links`,"aria-label":`linked`,children:`🔗`})]}),(0,l.jsx)(pt,{value:e.row.id,compact:!0,title:`Copy chunk id: ${e.row.id}`})]}),u&&d&&(0,l.jsx)(`ul`,{className:`children chunk-children`,children:e.children.map(e=>(0,l.jsx)(yt,{node:e,expanded:t,toggle:n,selectedId:r,onSelect:i,tintScheme:a,documentColor:o,linkedIds:c},e.row.id))})]})}function bt({record:e}){return e?(0,l.jsxs)(`p`,{className:`annotation-brief`,title:`Annotation brief`,children:[e.brief,e.stale&&(0,l.jsx)(xt,{})]}):null}function xt(){return(0,l.jsx)(`span`,{className:`annotation-badge annotation-stale`,title:`The text has changed since this annotation was written`,children:`stale`})}function St({records:e,newLevel:t,onSave:n,onRegenerate:r,defaultOpen:i}){let[a,o]=(0,c.useState)(!!i),[s,u]=(0,c.useState)(null),[d,f]=(0,c.useState)(null),p=d!==null,[m,h]=(0,c.useState)(null);if(e.length===0&&!n&&!r)return null;let g=async e=>{if(r){f(e),h(null);try{await r(e)}catch(e){h(e instanceof Error?e.message:String(e))}finally{f(null)}}},_=e.some(e=>e.stale),v=e.some(e=>e.manual);return(0,l.jsxs)(`details`,{className:`annotation-panel`,open:a||s!==null,onToggle:e=>o(e.currentTarget.open),children:[(0,l.jsxs)(`summary`,{children:[(0,l.jsx)(`span`,{className:`annotation-title`,children:`Annotation`}),e.length===0?(0,l.jsx)(`span`,{className:`annotation-none`,children:`none`}):e.map(e=>(0,l.jsx)(`span`,{className:`annotation-badge`,children:e.level},e.level)),v&&(0,l.jsx)(`span`,{className:`annotation-badge annotation-manual`,title:`Written or edited by a person`,children:`manual`}),_&&(0,l.jsx)(xt,{})]}),e.map(t=>s===t.level?(0,l.jsx)(Ct,{level:t.level,brief:t.brief,abstract:t.abstract,onCancel:()=>u(null),onSave:async(e,r)=>{await n(t.level,e,r),u(null)}},t.level):(0,l.jsxs)(`div`,{className:`annotation-record`,children:[e.length>1&&(0,l.jsx)(`p`,{className:`annotation-brief`,children:t.brief}),t.abstract&&(0,l.jsx)(`p`,{className:`annotation-abstract`,children:t.abstract}),(0,l.jsxs)(`dl`,{className:`annotation-meta`,children:[(0,l.jsx)(`dt`,{children:`level`}),(0,l.jsx)(`dd`,{children:t.level}),t.language&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`language`}),(0,l.jsx)(`dd`,{children:t.language})]}),t.model&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`model`}),(0,l.jsx)(`dd`,{children:t.model})]}),t.written_at&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`written`}),(0,l.jsx)(`dd`,{title:t.written_at,children:I(t.written_at)})]}),t.written_by&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`by`}),(0,l.jsx)(`dd`,{children:F(t.written_by)})]}),t.manual&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`source`}),(0,l.jsx)(`dd`,{children:`written by hand`})]}),t.stale&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`state`}),(0,l.jsx)(`dd`,{children:`stale: the text changed after this was written`})]})]}),(n||r)&&(0,l.jsxs)(`div`,{className:`annotation-actions`,children:[n&&(0,l.jsx)(`button`,{type:`button`,disabled:p,onClick:()=>u(t.level),children:`edit`}),r&&!t.manual&&(0,l.jsx)(`button`,{type:`button`,disabled:p,onClick:()=>void g(t.level),title:`Ask for it to be written again from the current text`,children:d===t.level?`regenerating…`:`regenerate`})]})]},t.level)),e.length===0&&(s!==null&&n?(0,l.jsx)(Ct,{level:s,brief:``,abstract:``,onCancel:()=>u(null),onSave:async(e,t)=>{await n(s,e,t),u(null)}}):(0,l.jsxs)(`div`,{className:`annotation-record`,children:[(0,l.jsx)(`p`,{className:`annotation-empty`,children:`No annotation has been written for this yet.`}),(0,l.jsxs)(`div`,{className:`annotation-actions`,children:[n&&(0,l.jsx)(`button`,{type:`button`,disabled:p,onClick:()=>u(t),children:`write`}),r&&(0,l.jsx)(`button`,{type:`button`,disabled:p,onClick:()=>void g(t),children:p?`generating…`:`generate`})]})]})),m&&(0,l.jsx)(`p`,{className:`annotation-err`,children:m})]})}function Ct({level:e,brief:t,abstract:n,onSave:r,onCancel:i}){let[a,o]=(0,c.useState)(t),[s,u]=(0,c.useState)(n),[d,f]=(0,c.useState)(!1),[p,m]=(0,c.useState)(null),h=ee(a,s),g=async()=>{if(h)m(h);else{f(!0),m(null);try{await r(a,s)}catch(e){m(e instanceof Error?e.message:String(e))}finally{f(!1)}}};return(0,l.jsxs)(`form`,{className:`annotation-editor`,onSubmit:e=>{e.preventDefault(),g()},children:[(0,l.jsxs)(`label`,{children:[(0,l.jsxs)(`span`,{children:[`Brief (`,e,`) · `,N(a),`/`,240]}),(0,l.jsx)(`input`,{value:a,onChange:e=>o(e.target.value),placeholder:`One sentence`})]}),(0,l.jsxs)(`label`,{children:[(0,l.jsxs)(`span`,{children:[`Abstract · `,N(s),`/`,D]}),(0,l.jsx)(`textarea`,{rows:6,value:s,onChange:e=>u(e.target.value),placeholder:`One paragraph`})]}),(0,l.jsx)(`p`,{className:`annotation-hint`,children:`Saved as written by hand: the background walk will not replace it.`}),p&&(0,l.jsx)(`p`,{className:`annotation-err`,children:p}),(0,l.jsxs)(`div`,{className:`annotation-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:i,disabled:d,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:`primary`,disabled:d||!!h,children:d?`saving…`:`save`})]})]})}var wt=0;function Tt(e){let t=e?.closest(`g.node`);return t?/flowchart-(.+)-\d+$/.exec(t.id)?.[1]:void 0}function Et({code:e,onNodeClick:t}){let n=(0,c.useRef)(null),[r,i]=(0,c.useState)({});return(0,c.useEffect)(()=>{let t=!1;return(async()=>{try{let r=(await import(`mermaid`)).default,a=n.current?.closest(`[data-theme]`)?.getAttribute(`data-theme`),o=!a||a===`dark`;r.initialize({startOnLoad:!1,theme:o?`dark`:`default`,securityLevel:`strict`});let{svg:s}=await r.render(`lc-mmd-${wt++}`,e);t||i({svg:s})}catch{t||i({err:!0})}})(),()=>{t=!0}},[e]),r.err?(0,l.jsx)(`pre`,{className:`md-pre md-mermaid-error`,title:`diagram failed to render`,children:(0,l.jsx)(`code`,{children:e})}):r.svg?(0,l.jsx)(`div`,{ref:n,className:t?`md-mermaid md-mermaid-nav`:`md-mermaid`,onClick:t&&(e=>{let n=Tt(e.target);n&&t(n)}),dangerouslySetInnerHTML:{__html:r.svg}}):(0,l.jsx)(`div`,{ref:n,className:`md-mermaid md-mermaid-loading`,children:`rendering diagram…`})}function Dt({chunk:e,scope:t,browse:n,onClose:r,onSaved:i}){let a=H(),[o,s]=(0,c.useState)(e.title),[u,d]=(0,c.useState)(e.type??``),[f,p]=(0,c.useState)(e.status??``),[m,h]=(0,c.useState)(e.body??``),[g,_]=(0,c.useState)(e.fields?JSON.stringify(e.fields,null,2):``),[v,y]=(0,c.useState)((e.tags??[]).join(`, `)),[b,x]=(0,c.useState)(!1),[S,C]=(0,c.useState)(null),[w,T]=(0,c.useState)(!1),E=u===`mermaid`,D=u===`image`||!!e.asset,[O,k]=(0,c.useState)(m);(0,c.useEffect)(()=>{if(!E)return;let e=setTimeout(()=>k(m),400);return()=>clearTimeout(e)},[m,E]);let A=async o=>{C(null),x(!0);try{let{mediaType:s,data:c}=await Me(o);i(await a.documentSetAsset(e.id,s,c,o.name,t,n)),r()}catch(e){C(e instanceof Error?e.message:String(e)),x(!1)}},j=E?`Mermaid source`:D?`Caption (optional)`:`Body (Markdown)`;return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:r,children:(0,l.jsxs)(`form`,{className:`modal chunk-editor`,onClick:e=>e.stopPropagation(),onSubmit:async s=>{s.preventDefault(),C(null),T(!1);let c={body:m,title:o,type:u,status:f,tags:v.split(`,`).map(e=>e.trim()).filter(e=>e!==``)};if(g.trim()!==``)try{c.fields=JSON.parse(g)}catch{C(`fields must be valid JSON`);return}x(!0);try{i(await a.documentUpdateChunk(e.id,e.revision,c,t,n)),r()}catch(e){let t=e instanceof Error?e.message:String(e);C(t),T(/revision conflict/i.test(t)),x(!1)}},children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsx)(`h3`,{children:`Edit chunk`}),(0,l.jsxs)(`div`,{className:`modal-buttons modal-buttons-top`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:r,disabled:b,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:`primary`,disabled:b,children:b?`saving…`:`save`})]})]}),S&&(0,l.jsxs)(`div`,{className:`modal-err`,children:[S,w&&` — reopen the chunk to load the latest, then reapply your edit.`]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Title`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:o,onChange:e=>s(e.target.value)})]}),(0,l.jsxs)(`div`,{className:`chunk-editor-row`,children:[(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Type`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:u,placeholder:`(none)`,onChange:e=>d(e.target.value)})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Status`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:f,placeholder:`(none)`,onChange:e=>p(e.target.value)})]})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Tags`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:v,placeholder:`comma-separated, nest with a slash: area/sub, priority/high`,onChange:e=>y(e.target.value)})]}),D&&(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Replace image`}),(0,l.jsx)(`input`,{type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,disabled:b,onChange:e=>{let t=e.target.files?.[0];t&&A(t)}})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:j}),(0,l.jsx)(`textarea`,{className:`modal-textarea chunk-body-input`,rows:E?8:12,value:m,onChange:e=>h(e.target.value)})]}),E&&(0,l.jsxs)(`div`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Preview`}),(0,l.jsx)(`div`,{className:`chunk-mermaid-preview`,children:O.trim()?(0,l.jsx)(Et,{code:O}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(enter Mermaid source above)`})})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Fields (JSON, optional)`}),(0,l.jsx)(`textarea`,{className:`modal-textarea chunk-fields-input`,rows:4,value:g,placeholder:`{}`,onChange:e=>_(e.target.value)})]})]})})}function Ot({chunk:e,scope:t,browse:n,onClose:r,onSaved:i}){let a=H(),[o,s]=(0,c.useState)(null),[u,d]=(0,c.useState)(e.type??``),[f,p]=(0,c.useState)(!1),[m,h]=(0,c.useState)(null),[g,_]=(0,c.useState)(null);(0,c.useEffect)(()=>{let e=!1;return a.documentEntityTypes?.(t,n).then(t=>{e||s(t)}).catch(t=>{e||h(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[a,t,n]);let y=o?v(o,e.type):[],b=u.toLowerCase()===(e.type??``).toLowerCase();return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:r,children:(0,l.jsxs)(`form`,{className:`modal`,onClick:e=>e.stopPropagation(),onSubmit:async o=>{if(o.preventDefault(),!(b||f)){h(null),p(!0);try{let o=await a.documentUpdateChunk(e.id,e.revision,{type:u},t,n);if(i(o),o.not_announced){_(o.not_announced),p(!1);return}r()}catch(e){h(e instanceof Error?e.message:String(e)),p(!1)}}},children:[(0,l.jsx)(`h3`,{children:`Change type`}),(0,l.jsxs)(`p`,{className:`modal-context`,children:[`“`,e.title||`(untitled)`,`” is a subject (`,(0,l.jsx)(`code`,{children:e.entity?.natural_key}),`). Its key stays as it is; relations about it are re-checked against the new type.`]}),m&&(0,l.jsx)(`div`,{className:`modal-err`,children:m}),g?(0,l.jsxs)(`div`,{className:`modal-err`,children:[`The type was changed, but subscribers were not told: `,g]}):(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Type`}),o===null?(0,l.jsx)(`span`,{className:`doc-empty-body`,children:m?``:`loading types…`}):(0,l.jsx)(`select`,{className:`path-modal-input`,value:u,disabled:f,onChange:e=>d(e.target.value),children:y.map(e=>(0,l.jsx)(`option`,{value:e,children:e},e))})]}),(0,l.jsxs)(`div`,{className:`modal-buttons`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:r,disabled:f,children:g?`close`:`cancel`}),!g&&(0,l.jsx)(`button`,{type:`submit`,className:`primary`,disabled:f||b||o===null,children:f?`saving…`:`change type`})]})]})})}function kt(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function At(e){if(!e||typeof e!=`object`)return;let t=e.classification;if(!t||typeof t!=`object`||Array.isArray(t))return;let n=t,r={};return typeof n.by==`string`&&(r.by=n.by),typeof n.at==`number`&&(r.at=n.at),typeof n.applied_type==`string`&&n.applied_type&&(r.applied_type=n.applied_type),typeof n.proposed_type==`string`&&n.proposed_type&&(r.proposed_type=n.proposed_type),n.proposed_fields&&typeof n.proposed_fields==`object`&&!Array.isArray(n.proposed_fields)&&(r.proposed_fields=n.proposed_fields),kt(n.proposed_tags)&&(r.proposed_tags=n.proposed_tags),kt(n.statements)&&(r.statements=n.statements),r}function jt(e){let t=At(e);if(!t)return;let n=t.proposed_tags??[],r=t.statements?.length??0;if(t.proposed_type||n.length!==0||r!==0)return{proposedType:t.proposed_type,proposedTags:n,statementCount:r}}function Mt(e){let t=e.write===`report`;switch(e.result){case`classified`:return t?`would be classified`:`classified`;case`proposed`:return t?`would be proposed for review`:`proposed — waits for review`;case`kept`:return`kept — the type was set by hand`;case`unclassified`:return`unclassified — nothing decided`;default:return String(e.result)}}function Nt(e){if(!e.class)return;if(e.result===`kept`)return`not applied`;let t=e.write===`report`;return e.live?t?`would be applied`:`applied`:t?`would be proposed`:`proposed`}function Pt(e){return e.write===`report`?e.result===`classified`||e.result===`proposed`||(e.concepts?.length??0)>0||(e.issued_by?.length??0)>0:!1}function Ft(e){return e==null||!Number.isFinite(e)?``:`${Math.round(e*100)}%`}var It={rules:`Rules`,vote:`Neighbourhood vote`,model:`Model`};function Lt(e){return It[e]??e}function Rt(e){let t=[];e.quote&&t.push(e.from?`“${e.quote}” (${e.from})`:`“${e.quote}”`),e.votes!=null&&t.push(`${e.votes} vote${e.votes===1?``:`s`}`);let n=Ft(e.share);return n&&t.push(n),t.join(` · `)}function zt(e){return{label:Lt(e.step),...e.chosen?{chosen:e.chosen}:{},...e.method?{method:e.method}:{},...e.neighbours?{neighbours:e.neighbours}:{},...e.reason?{reason:e.reason}:{},candidates:(e.candidates??[]).map(e=>({class:e.class,detail:Rt(e)}))}}function Bt(e){let t=[];e.type&&t.push(`type ${e.type}`);let n=e.accepted_statements?.length??0;n>0&&t.push(`${n} statement${n===1?``:`s`}`),e.tags&&e.tags.length>0&&t.push(`tags ${e.tags.join(`, `)}`);let r=[];e.type_pending&&r.push(`The proposed class stays pending: another document already holds its identity.`),e.skipped_type&&r.push(`Class ${e.skipped_type} was not applied: it is not a declared document class.`);let i=e.skipped_statements?.length??0;return i>0&&r.push(`${i} statement${i===1?` was`:`s were`} skipped (already ruled on, or not this document's proposal).`),e.skipped_tags&&e.skipped_tags.length>0&&r.push(`Tags not applied (not concepts of the ontology): ${e.skipped_tags.join(`, `)}.`),r.push(...e.warnings??[]),{applied:t.length>0?`Accepted ${t.join(`, `)}.`:`Nothing was accepted.`,notices:r}}function Vt(e){let t=e instanceof Error?e.message:String(e);return t.includes(`nothing_pending`)?`Nothing is pending for this document — it may already have been accepted.`:t}function Ht({documentId:e,scope:t,browse:n,rootFields:r,requestKey:i,onClose:a,onChanged:o}){let s=H(),[u,d]=(0,c.useState)(null),[f,p]=(0,c.useState)(!1),[m,h]=(0,c.useState)(null),[g,_]=(0,c.useState)(!1),[v,y]=(0,c.useState)(null),[b,x]=(0,c.useState)(null),S=(0,c.useMemo)(()=>s.documentAcceptClassification?jt(r):void 0,[s,r]);(0,c.useEffect)(()=>{if(i===0||!s.documentClassify)return;let r=!1;return p(!0),h(null),d(null),s.documentClassify(e,`report`,t,n).then(e=>!r&&d(e)).catch(e=>!r&&h(Vt(e))).finally(()=>!r&&p(!1)),()=>{r=!0}},[s,e,t,n,i]);let C=async()=>{if(s.documentClassify){p(!0),h(null);try{d(await s.documentClassify(e,`propose`,t,n)),o()}catch(e){h(Vt(e))}finally{p(!1)}}},w=async()=>{if(s.documentAcceptClassification){_(!0),y(null);try{x(await s.documentAcceptClassification(e,t,n)),o()}catch(e){y(Vt(e))}finally{_(!1)}}},T=i>0;if(!T&&!S&&!b&&!v)return null;let E=b?Bt(b):void 0;return(0,l.jsxs)(`div`,{className:`doc-classify`,children:[S&&(0,l.jsxs)(`div`,{className:`doc-classify-pending`,children:[(0,l.jsx)(`span`,{className:`doc-classify-label`,children:`Pending classification`}),S.proposedType&&(0,l.jsxs)(`span`,{children:[`class `,(0,l.jsx)(`strong`,{children:S.proposedType})]}),S.proposedTags.length>0&&(0,l.jsxs)(`span`,{children:[`tags`,` `,S.proposedTags.map(e=>(0,l.jsx)(`span`,{className:`chunk-tag`,children:e},e))]}),S.statementCount>0&&(0,l.jsxs)(`span`,{children:[S.statementCount,` proposed statement`,S.statementCount===1?``:`s`]}),(0,l.jsx)(`button`,{type:`button`,disabled:g,onClick:()=>void w(),children:g?`Accepting…`:`Accept`})]}),v&&(0,l.jsxs)(`div`,{className:`doc-classify-err`,role:`alert`,children:[v,(0,l.jsx)(`button`,{type:`button`,className:`doc-classify-dismiss`,onClick:()=>y(null),"aria-label":`Dismiss`,children:`×`})]}),E&&(0,l.jsxs)(`div`,{className:`doc-classify-notice`,role:`status`,children:[(0,l.jsx)(`span`,{children:E.applied}),E.notices.map((e,t)=>(0,l.jsx)(`span`,{className:`doc-classify-warn`,children:e},t)),(0,l.jsx)(`button`,{type:`button`,className:`doc-classify-dismiss`,onClick:()=>x(null),"aria-label":`Dismiss`,children:`×`})]}),T&&(0,l.jsxs)(`div`,{className:`doc-classify-panel`,children:[(0,l.jsxs)(`div`,{className:`doc-classify-head`,children:[(0,l.jsx)(`h4`,{children:`Classify`}),u&&(0,l.jsx)(`span`,{className:`doc-classify-result ${u.result}`,children:Mt(u)}),u?.write===`report`&&(0,l.jsx)(`span`,{className:`doc-classify-hint`,children:`report only — nothing written`}),(0,l.jsx)(`button`,{type:`button`,className:`doc-classify-dismiss`,onClick:a,"aria-label":`Close`,children:`×`})]}),!u&&!m&&(0,l.jsx)(`p`,{className:`doc-classify-hint`,children:`Classifying…`}),m&&(0,l.jsx)(`p`,{className:`doc-classify-err`,role:`alert`,children:m}),u&&(0,l.jsx)(Ut,{answer:u}),u&&Pt(u)&&(0,l.jsx)(`div`,{className:`doc-classify-actions`,children:(0,l.jsx)(`button`,{type:`button`,disabled:f,onClick:()=>void C(),title:`Apply a unique rule match to the document; file everything else for review`,children:f?`Applying…`:`Apply`})})]})]})}function Ut({answer:e}){let t=Nt(e),n=Object.entries(e.fields??{}),r=e.issued_by??[],i=e.concepts??[],a=(e.steps??[]).map(zt),o=e.statements?.length??0;return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`dl`,{className:`doc-classify-rows`,children:[e.class&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`class`}),(0,l.jsxs)(`dd`,{children:[(0,l.jsx)(`strong`,{children:e.class}),t&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` (`,t,`)`]})]})]}),e.work_key&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`work key`}),(0,l.jsx)(`dd`,{className:`doc-classify-mono`,children:e.work_key})]}),n.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`fields`}),(0,l.jsx)(`dd`,{className:`doc-classify-mono`,children:n.map(([e,t])=>`${e}=${typeof t==`string`?t:JSON.stringify(t)}`).join(` · `)})]}),r.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`issued by`}),(0,l.jsx)(`dd`,{children:r.map((e,t)=>(0,l.jsxs)(`span`,{className:`doc-classify-item`,title:e.quote,children:[e.instance,e.quote&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` “`,e.quote,`”`]})]},`${e.instance}-${t}`))})]}),i.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`concepts`}),(0,l.jsx)(`dd`,{children:i.map(e=>(0,l.jsxs)(`span`,{className:`doc-classify-item`,title:e.tag,children:[e.concept,(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` `,Ft(e.share)]})]},e.tag))})]}),o>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`statements`}),(0,l.jsxs)(`dd`,{children:[o,` written`,e.statements.some(e=>e.status===`proposed`)&&(0,l.jsx)(`span`,{className:`doc-classify-hint`,children:` (proposed ones wait for review)`})]})]})]}),a.length>0&&(0,l.jsx)(`ol`,{className:`doc-classify-steps`,children:a.map((e,t)=>(0,l.jsxs)(`li`,{children:[(0,l.jsx)(`span`,{className:`doc-classify-step`,children:e.label}),e.method&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` [`,e.method,`]`]}),e.chosen?(0,l.jsxs)(l.Fragment,{children:[` → `,(0,l.jsx)(`strong`,{children:e.chosen})]}):(0,l.jsx)(`span`,{className:`doc-classify-hint`,children:` no choice`}),e.neighbours!=null&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` · `,e.neighbours,` neighbours`]}),e.reason&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` — `,e.reason]}),e.candidates.length>0&&(0,l.jsxs)(`details`,{className:`doc-classify-candidates`,children:[(0,l.jsxs)(`summary`,{children:[e.candidates.length,` candidate`,e.candidates.length===1?``:`s`]}),(0,l.jsx)(`ul`,{children:e.candidates.map((e,t)=>(0,l.jsxs)(`li`,{children:[(0,l.jsx)(`strong`,{children:e.class}),e.detail&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` `,e.detail]})]},`${e.class}-${t}`))})]})]},`${e.label}-${t}`))}),e.warnings&&e.warnings.length>0&&(0,l.jsx)(`ul`,{className:`doc-classify-warnings`,children:e.warnings.map((e,t)=>(0,l.jsx)(`li`,{className:`doc-classify-warn`,children:e},t))})]})}function Wt(e){let t=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((e??``).trim());if(!t)return`#888888`;let n=t[1];return n.length===3&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]),`#`+n.toLowerCase()}function Gt({documentId:e,rootChunkId:t,docType:n,docStatus:r,chunkStatuses:i,scope:a,browse:o,onClose:s,onSaved:u}){let d=H(),[f,p]=(0,c.useState)(null),[m,h]=(0,c.useState)(!1),[g,_]=(0,c.useState)({}),[v,y]=(0,c.useState)(!1),[b,x]=(0,c.useState)(null),[S,C]=(0,c.useState)(null),w=(0,c.useMemo)(()=>{let e=new Set(Object.keys(tt));n&&e.add(`doc.${n}.${r||`draft`}`);for(let t of i)t&&e.add(`chunk.${t}`);return[...e].sort()},[n,r,i]);(0,c.useEffect)(()=>{let e=!1;return d.documentGetChunk(t,a,o).then(t=>{if(e)return;p(t);let n=t.fields??{};h(n.color_enabled===!0);let r=n.color_scheme??{};_({...tt,...r})}).catch(t=>!e&&C(t instanceof Error?t.message:String(t))),()=>{e=!0}},[d,t,a,o]);let T=(e,t)=>_(n=>({...n,[e]:t})),E=e=>({...e??{},color_enabled:m,color_scheme:g}),D=async()=>{if(f){y(!0),C(null),x(null);try{await d.documentUpdateChunk(t,f.revision,{fields:E(f.fields)},a,o),u(),s()}catch(e){C(e instanceof Error?e.message:String(e)),y(!1)}}},O=async()=>{if(!n)C(`this document has no type to match`);else{y(!0),C(null),x(null);try{let{documents:t}=await d.documentsSummary({underPath:`/`},a,o),r=(t??[]).filter(t=>t.type===n&&t.document_id!==e&&t.root_chunk_id),i=0;for(let e of r)try{let t=await d.documentGetChunk(e.root_chunk_id,a,o);await d.documentUpdateChunk(e.root_chunk_id,t.revision,{fields:E(t.fields)},a,o),i++}catch{}x(`Applied to ${i} other ${n} document(s).`),u()}catch(e){C(e instanceof Error?e.message:String(e))}finally{y(!1)}}},k=w.filter(e=>e.startsWith(`doc.`)),A=w.filter(e=>e.startsWith(`chunk.`));return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:s,children:(0,l.jsxs)(`div`,{className:`modal scheme-editor`,onClick:e=>e.stopPropagation(),children:[(0,l.jsxs)(`div`,{className:`scheme-editor-head`,children:[(0,l.jsx)(`h3`,{children:`Document colors`}),(0,l.jsxs)(`div`,{className:`scheme-editor-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:s,disabled:v,children:`cancel`}),(0,l.jsx)(`button`,{type:`button`,className:`primary`,onClick:()=>void D(),disabled:v||!f,children:v?`saving…`:`save`})]})]}),S&&(0,l.jsx)(`div`,{className:`modal-err`,children:S}),f?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`label`,{className:`scheme-toggle`,children:[(0,l.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>h(e.target.checked)}),(0,l.jsx)(`span`,{children:`Enable coloring for this document`})]}),(0,l.jsx)(`p`,{className:`modal-context`,children:`Document rows are tinted by type + status; chunk tiles by status. Colors apply as a semi-transparent wash so text stays readable.`}),(0,l.jsxs)(`div`,{className:`scheme-group`,children:[(0,l.jsx)(`h4`,{children:`Document (type · status)`}),k.map(e=>(0,l.jsx)(Kt,{label:e.slice(4),value:g[e],onChange:t=>T(e,t)},e))]}),(0,l.jsxs)(`div`,{className:`scheme-group`,children:[(0,l.jsx)(`h4`,{children:`Chunks (status)`}),A.map(e=>(0,l.jsx)(Kt,{label:e.slice(6),value:g[e],onChange:t=>T(e,t)},e))]}),(0,l.jsxs)(`div`,{className:`scheme-editor-foot`,children:[(0,l.jsxs)(`button`,{type:`button`,onClick:()=>void O(),disabled:v||!n,title:n?`Apply this palette to every other ${n} document`:`This document has no type`,children:[`copy to all `,n||`same-type`,` documents`]}),b&&(0,l.jsx)(`span`,{className:`scheme-status`,children:b})]})]}):(0,l.jsx)(`p`,{className:`modal-context`,children:`Loading…`})]})})}function Kt({label:e,value:t,onChange:n}){let r=Wt(t);return(0,l.jsxs)(`label`,{className:`scheme-row`,children:[(0,l.jsx)(`input`,{type:`color`,value:r,onChange:e=>n(e.target.value)}),(0,l.jsx)(`span`,{className:`scheme-key`,children:e}),(0,l.jsx)(`code`,{className:`scheme-hex`,children:r})]})}function qt({id:e,title:t,targetDocumentId:n,documentId:r,onSelectChunk:i,onOpenDocument:a}){let o=t||e.slice(0,8);return!n||n===r?(0,l.jsx)(`button`,{type:`button`,className:`doc-ref-target`,onClick:()=>i(e),children:o}):a?(0,l.jsxs)(`button`,{type:`button`,className:`doc-ref-target external`,title:`In another document — opens it at this chunk`,onClick:()=>a(n,e,t),children:[o,` ↗`]}):(0,l.jsxs)(`span`,{className:`doc-ref-target external`,title:`In another document`,children:[o,` ↗`]})}function Jt({statement:e}){let t=Re(e),n=X(e),r=Be(e),i=ze(e),{rows:a,more:o}=Ve(e);return(0,l.jsxs)(l.Fragment,{children:[t&&(0,l.jsx)(`span`,{className:`doc-stmt-status ${t}`,children:t}),n&&(0,l.jsx)(`span`,{className:`doc-stmt-method`,title:`how this relation was made`,children:n}),r&&(0,l.jsx)(`span`,{className:`doc-stmt-verdict`,title:r,children:`judged`}),i&&(0,l.jsx)(`span`,{className:`doc-stmt-valid`,children:i}),a.length>0&&(0,l.jsxs)(`ul`,{className:`doc-stmt-evidence`,children:[a.map(e=>(0,l.jsxs)(`li`,{title:e.quote,children:[`“`,He(e.quote),`”`,e.part===`title`&&(0,l.jsx)(`span`,{className:`doc-stmt-part`,children:` (title)`}),e.stale&&(0,l.jsx)(`span`,{className:`doc-stmt-stale`,children:` (source changed)`})]},e.id)),o>0&&(0,l.jsxs)(`li`,{className:`doc-stmt-more`,children:[`+`,o,` more`]})]})]})}function Yt({id:e,onRule:t}){let[n,r]=(0,c.useState)(!1),[i,a]=(0,c.useState)(``),[o,s]=(0,c.useState)(!1),[u,d]=(0,c.useState)(null),f=async n=>{s(!0),d(null);try{await t(e,n,n?void 0:i.trim()),r(!1),a(``)}catch(e){d(e instanceof Error?e.message:String(e))}finally{s(!1)}};return(0,l.jsxs)(`span`,{className:`doc-stmt-review`,children:[n?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`input`,{type:`text`,"aria-label":`Reason for rejecting`,placeholder:`why reject?`,value:i,disabled:o,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&i.trim()&&f(!1),e.key===`Escape`&&r(!1)},autoFocus:!0}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,disabled:o||!i.trim(),onClick:()=>void f(!1),children:`Reject`}),(0,l.jsx)(`button`,{type:`button`,disabled:o,onClick:()=>r(!1),children:`Cancel`})]}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,disabled:o,onClick:()=>void f(!0),children:`Accept`}),(0,l.jsx)(`button`,{type:`button`,disabled:o,onClick:()=>r(!0),children:`Reject…`})]}),u&&(0,l.jsx)(`span`,{className:`doc-stmt-err`,role:`alert`,children:u})]})}var Xt=3;function Zt({documentId:e,proposals:t,incomplete:n,scope:r,browse:i,onChanged:a,onSelectChunk:o,onOpenDocument:s}){let u=H(),[d,f]=(0,c.useState)(new Set),[p,m]=(0,c.useState)({kind:`idle`}),[h,g]=(0,c.useState)(``),[_,v]=(0,c.useState)(null),[y,b]=(0,c.useState)(null),x=(0,c.useRef)(null),S=new Set(t.map(e=>e.id)),C=[...d].filter(e=>S.has(e)),w=p.kind!==`idle`&&p.kind!==`reason`,T=(e,t)=>{v(null),b(null),e===`reject`?m({kind:`reason`,action:e,all:t}):E(e,t,``)},E=async(t,n,o)=>{m({kind:`counting`,action:t,all:n});let s;try{s=await $e(u,{documentId:e,action:t,ids:n?void 0:C,reason:o.trim()||void 0,scope:r,browse:i},{confirm:(e,r)=>new Promise(i=>{x.current=i,m({kind:`confirm`,action:t,all:n,dry:e,changed:r!==`first`})}),onProgress:e=>m({kind:`ruling`,action:t,ruled:e.ruled,total:e.total})})}catch(e){s={rulingIds:[],ruled:0,failed:0,skipped:0,total:0,cancelled:!1,failures:[],error:e}}x.current=null,m({kind:`idle`}),g(``),s.rulingIds.length>0?(f(new Set),b({text:et(t,s),rulingIds:s.rulingIds}),a()):s.error===void 0&&!s.cancelled&&b({text:`Nothing to rule: no proposals match.`,rulingIds:[]}),s.error!==void 0&&v(s.error instanceof Error?s.error.message:String(s.error))},D=e=>{e&&p.kind===`confirm`&&m({kind:`ruling`,action:p.action}),x.current?.(e)},O=async()=>{if(!y||!u.documentRevertRuling)return;let e=y,t=await qe(e=>u.documentRevertRuling(e,r,i),e.rulingIds),n=[`${t.reverted} came back to review`];t.changed>0&&n.push(`${t.changed} changed since and left as ruled`),t.errors.length>0&&n.push(`not undone: ${t.errors.join(`; `)}`),b({...e,undone:!0,text:n.join(`; `)+`.`}),a()},k=e=>f(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),A=t.length>0&&C.length===t.length,j=t.length===0&&!n;return(0,l.jsxs)(`div`,{className:`doc-conn-group doc-bulk`,children:[(0,l.jsxs)(`h5`,{children:[`Proposals from this document (`,t.length,`)`]}),(0,l.jsxs)(`div`,{className:`doc-bulk-bar`,children:[(0,l.jsxs)(`label`,{children:[(0,l.jsx)(`input`,{type:`checkbox`,"aria-label":`select every proposal shown`,checked:A,disabled:w||t.length===0,onChange:()=>f(A?new Set:new Set(S))}),` `,`all shown`]}),(0,l.jsxs)(`button`,{type:`button`,disabled:w||C.length===0,onClick:()=>T(`accept`,!1),children:[`Accept selected (`,C.length,`)`]}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,disabled:w||C.length===0,onClick:()=>T(`reject`,!1),children:`Reject selected…`}),(0,l.jsx)(`button`,{type:`button`,disabled:w||j,onClick:()=>T(`accept`,!0),children:`Accept all from this document`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,disabled:w||j,onClick:()=>T(`reject`,!0),children:`Reject all…`})]}),p.kind===`reason`&&(0,l.jsxs)(`form`,{className:`doc-bulk-step`,onSubmit:e=>{e.preventDefault(),h.trim()&&E(p.action,p.all,h)},children:[(0,l.jsx)(`input`,{type:`text`,"aria-label":`Reason for rejecting`,placeholder:`why reject?`,value:h,onChange:e=>g(e.target.value),autoFocus:!0}),(0,l.jsx)(`button`,{type:`submit`,className:`danger`,disabled:!h.trim(),children:`Count`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>m({kind:`idle`}),children:`Cancel`})]}),p.kind===`counting`&&(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`counting…`}),p.kind===`confirm`&&(0,l.jsx)(Qt,{step:p,onAnswer:D}),p.kind===`ruling`&&(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:p.total?`ruled ${p.ruled??0} of ${p.total}…`:`ruling…`}),_&&(0,l.jsx)(`p`,{className:`doc-stmt-err`,role:`alert`,children:_}),y&&(0,l.jsxs)(`p`,{className:`doc-bulk-result`,role:`status`,children:[y.text,y.rulingIds.length>0&&!y.undone&&u.documentRevertRuling&&(0,l.jsx)(`button`,{type:`button`,onClick:()=>void O(),children:`Undo`})]}),t.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsx)(`ul`,{className:`doc-conn-list`,children:t.map(t=>(0,l.jsxs)(`li`,{className:`doc-conn-row`,children:[(0,l.jsx)(`input`,{type:`checkbox`,"aria-label":`select ${t.from_title??t.from_id} ${t.kind} ${t.to_title??t.to_id}`,checked:d.has(t.id),disabled:w,onChange:()=>k(t.id)}),(0,l.jsx)(qt,{id:t.from_id,title:t.from_title,targetDocumentId:t.from_document_id,documentId:e,onSelectChunk:o,onOpenDocument:s}),(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:t.kind}),(0,l.jsx)(qt,{id:t.to_id,title:t.to_title,targetDocumentId:t.to_document_id,documentId:e,onSelectChunk:o,onOpenDocument:s}),(0,l.jsx)(Jt,{statement:t})]},t.id))})]})}function Qt({step:e,onAnswer:t}){let{dry:n}=e,r=e.action===`accept`?`Accept`:`Reject`,i=Je(n.matched);return(0,l.jsxs)(`div`,{className:`doc-bulk-step doc-bulk-confirm`,children:[e.changed&&(0,l.jsx)(`p`,{className:`doc-bulk-warn`,children:`The proposals changed since the last count; counted again.`}),(0,l.jsxs)(`p`,{children:[r,` `,n.matched,` statement`,n.matched===1?``:`s`,e.all?` filed from this document`:``,i>1?`, in ${i} rulings of up to 1,000`:``,`?`,n.skipped>0&&` ${n.skipped} of them are not yours to rule and will be skipped.`]}),(n.sample??[]).length>0&&(0,l.jsx)(`ul`,{className:`doc-bulk-sample`,children:(n.sample??[]).slice(0,Xt).map(e=>(0,l.jsxs)(`li`,{children:[e.from_title||e.from_id,` `,(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:e.kind}),` `,e.to_title||e.to_id]},e.id))}),(0,l.jsxs)(`button`,{type:`button`,className:e.action===`reject`?`danger`:void 0,onClick:()=>t(!0),children:[r,` `,n.matched]}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>t(!1),children:`Cancel`})]})}var $t=8,en=20;function tn(e){return/embedder|embedding|vector|semantic|not configured/i.test(e)}function nn({documentId:e,selectedId:t,scope:n,browse:r,onSelectChunk:i,onOpenDocument:a,refreshKey:o,review:s}){let u=H(),[d,f]=(0,c.useState)(!1),[p,m]=(0,c.useState)(!1),[h,g]=(0,c.useState)(void 0),[_,v]=(0,c.useState)([]),[y,b]=(0,c.useState)([]),[x,S]=(0,c.useState)(null),[C,w]=(0,c.useState)([]),[T,E]=(0,c.useState)(!1);(0,c.useEffect)(()=>{if(!d||!t)return;let e=t,i=!1;return m(!0),Promise.allSettled([u.documentBacklinks(e,n,r),u.documentRelated(e,n,r,$t),u.documentUnlinkedMentions(e,n,r,en)]).then(([t,n,r])=>{if(!i){if(v(t.status===`fulfilled`?t.value.backlinks??[]:[]),n.status===`fulfilled`)b(n.value.related??[]),S(null);else{b([]);let e=n.reason instanceof Error?n.reason.message:String(n.reason);S(tn(e)?`semantic search not configured`:e)}r.status===`fulfilled`?(w(r.value.unlinked_mentions??[]),E(!!r.value.truncated)):(w([]),E(!1)),g(e),m(!1)}}),()=>{i=!0}},[u,d,t,n,r,o]);let D=(t,n,r)=>(0,l.jsx)(qt,{id:t,title:n,targetDocumentId:r,documentId:e,onSelectChunk:i,onOpenDocument:a}),O=!!(d&&t&&!p&&h===t);return(0,l.jsxs)(`div`,{className:`doc-conn`,children:[(0,l.jsxs)(`button`,{type:`button`,className:`doc-conn-toggle`,onClick:()=>f(e=>!e),children:[d?`▼`:`▶`,` Connections`]}),d&&(0,l.jsxs)(`div`,{className:`doc-conn-body`,children:[s&&(0,l.jsx)(Zt,{documentId:e,proposals:s.proposals,incomplete:s.incomplete,scope:s.scope,browse:r,onChanged:s.onChanged,onSelectChunk:i,onOpenDocument:a}),t?O?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`div`,{className:`doc-conn-group`,children:[(0,l.jsx)(`h5`,{children:`Backlinks`}),_.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsx)(`ul`,{className:`doc-conn-list`,children:_.map((e,t)=>(0,l.jsxs)(`li`,{className:`doc-conn-row`,children:[D(e.from_id,e.from_title,e.from_document_id),(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:e.kind}),e.auto&&(0,l.jsx)(`span`,{className:`doc-conn-auto`,title:`Auto-linked from a [[wikilink]]`,children:`auto`}),(0,l.jsx)(Jt,{statement:e})]},`${e.from_id}-${e.kind}-${t}`))})]}),(0,l.jsxs)(`div`,{className:`doc-conn-group`,children:[(0,l.jsx)(`h5`,{children:`Related`}),x?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:x}):y.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsx)(`ul`,{className:`doc-conn-list`,children:y.map((e,t)=>(0,l.jsxs)(`li`,{className:`doc-conn-row`,children:[D(e.chunk_id,e.title,e.document_id),(0,l.jsx)(`span`,{className:`doc-conn-score`,title:`similarity score`,children:e.score.toFixed(2)})]},`${e.chunk_id}-${t}`))})]}),(0,l.jsxs)(`div`,{className:`doc-conn-group`,children:[(0,l.jsx)(`h5`,{children:`Unlinked mentions`}),C.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsxs)(`ul`,{className:`doc-conn-list`,children:[C.map((e,t)=>(0,l.jsx)(`li`,{className:`doc-conn-row`,children:D(e.chunk_id,e.title,e.document_id)},`${e.chunk_id}-${t}`)),T&&(0,l.jsx)(`li`,{className:`doc-conn-more`,"aria-hidden":!0,children:`(more…)`})]})]})]}):(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`loading…`}):(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`Select a chunk.`})]})]})}var rn=24;function an({edges:e,documentId:t,selectedId:n,onSelectChunk:r,onOpenDocument:i,onRuleStatement:a,incomplete:o}){let[s,u]=(0,c.useState)(!1),[d,f]=(0,c.useState)(!1);if(e.length===0)return null;let p=n?e.filter(e=>e.from_id===n||e.to_id===n):[],m=d?e:e.slice(0,rn),h=sn(m);return(0,l.jsxs)(`div`,{className:`doc-refs`,children:[o&&(0,l.jsxs)(`p`,{className:`doc-refs-incomplete`,children:[`Showing the first `,e.length,` links of this document; it has more, which are not shown here or in the graph.`]}),n&&(0,l.jsxs)(`div`,{className:`doc-refs-list-wrap`,children:[(0,l.jsx)(`h4`,{children:`References`}),p.length===0?(0,l.jsx)(`p`,{className:`doc-refs-empty`,children:`This chunk has no links.`}):(0,l.jsx)(`ul`,{className:`doc-refs-list`,children:p.map((e,o)=>(0,l.jsx)(on,{edge:e,selectedId:n,documentId:t,onSelectChunk:r,onOpenDocument:i,onRuleStatement:a},`${e.from_id}-${e.to_id}-${e.kind}-${o}`))})]}),(0,l.jsxs)(`div`,{className:`doc-graph`,children:[(0,l.jsxs)(`button`,{type:`button`,className:`doc-graph-toggle`,onClick:()=>u(e=>!e),children:[s?`▼`:`▶`,` relationship graph (`,e.length,`)`]}),s&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Et,{code:h,onNodeClick:e=>{let n=cn(m,e);n&&(!n.documentId||n.documentId===t?r(n.id):i?.(n.documentId,n.id,n.title))}}),e.length>rn&&(0,l.jsx)(`button`,{type:`button`,className:`doc-graph-more`,onClick:()=>f(e=>!e),children:d?`show top ${rn}`:`show all ${e.length}`})]})]})]})}function on({edge:e,selectedId:t,documentId:n,onSelectChunk:r,onOpenDocument:i,onRuleStatement:a}){let o=e.from_id===t,s=o?e.to_id:e.from_id,c=o?e.to_title:e.from_title,u=o?e.to_document_id:e.from_document_id;return(0,l.jsxs)(`li`,{className:`doc-ref`,children:[(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:e.kind}),(0,l.jsx)(`span`,{className:`doc-ref-arrow`,"aria-hidden":!0,children:o?`→`:`←`}),(0,l.jsx)(qt,{id:s,title:c,targetDocumentId:u,documentId:n,onSelectChunk:r,onOpenDocument:i}),(0,l.jsx)(Jt,{statement:e}),a&&Z(e)&&(0,l.jsx)(Yt,{id:e.id,onRule:a})]})}function sn(e){let t=[`graph LR`];for(let n of e){let e=`${ln(n.from_id)}["${un(n.from_title,n.from_id)}"]`,r=`${ln(n.to_id)}["${un(n.to_title,n.to_id)}"]`,i=(n.kind||`link`).replace(/[|"]/g,` `),a=n.status===`proposed`?`-.->`:`-->`;t.push(` ${e} ${a}|${i}| ${r}`)}return t.join(`
2
- `)}function cn(e,t){for(let n of e){if(ln(n.from_id)===t)return{id:n.from_id,documentId:n.from_document_id,title:n.from_title};if(ln(n.to_id)===t)return{id:n.to_id,documentId:n.to_document_id,title:n.to_title}}}function ln(e){return`n`+e.replace(/[^a-zA-Z0-9]/g,``)}function un(e,t){let n=(e??``).replace(/["[\]{}|<>]/g,` `).replace(/\s+/g,` `).trim()||t.slice(0,6);return n.length>30?n.slice(0,29)+`…`:n}var dn=6;function fn(e,t,n,r){let i=Math.max(r,t-n-dn);return Math.round(Math.max(r,Math.min(e,i)))}function pn({children:e,defaultBottomHeight:t=240,minTopHeight:n=96,minBottomHeight:r=48,storageKey:i,className:a}){let[o,s]=(0,c.useState)(()=>{if(i)try{let e=parseInt(localStorage.getItem(i)??``,10);if(Number.isFinite(e)&&e>=r)return e}catch{}return t}),u=(0,c.useRef)(null),[d,f]=(0,c.useState)(!1);(0,c.useEffect)(()=>{if(i&&!d)try{localStorage.setItem(i,String(o))}catch{}},[i,o,d]);let p=(0,c.useCallback)(e=>{e.preventDefault(),f(!0),e.target.setPointerCapture(e.pointerId)},[]),m=(0,c.useCallback)(e=>{if(!d||!u.current)return;let t=u.current.getBoundingClientRect();s(fn(t.bottom-e.clientY,t.height,n,r))},[d,n,r]),h=(0,c.useCallback)(e=>{f(!1);try{e.target.releasePointerCapture(e.pointerId)}catch{}},[]);return(0,l.jsxs)(`div`,{ref:u,className:`stack-splitter ${a??``} ${d?`dragging`:``}`,style:{gridTemplateRows:`minmax(${n}px, 1fr) ${dn}px min(${o}px, calc(100% - ${n+dn}px))`},children:[(0,l.jsx)(`div`,{className:`stack-splitter-pane stack-splitter-top`,children:e[0]}),(0,l.jsx)(`div`,{className:`stack-splitter-handle`,role:`separator`,"aria-orientation":`horizontal`,"aria-valuenow":o,title:`Drag to share the space between the text and its links`,onPointerDown:p,onPointerMove:m,onPointerUp:h,onPointerCancel:h}),(0,l.jsx)(`div`,{className:`stack-splitter-pane stack-splitter-bottom`,children:e[1]})]})}function mn({documentId:e,scope:t,detail:n}){return(0,l.jsxs)(`div`,{className:`doc-unavailable`,role:`alert`,children:[(0,l.jsx)(`p`,{className:`doc-unavailable-lead`,children:`This document can’t be opened.`}),(0,l.jsxs)(`p`,{children:[`It may have been deleted, live in a scope other than `,(0,l.jsx)(`code`,{children:t}),`, or not be yours to read.`]}),(0,l.jsxs)(`p`,{className:`doc-unavailable-detail`,children:[(0,l.jsx)(`code`,{children:e}),n&&(0,l.jsxs)(l.Fragment,{children:[` — `,n]})]})]})}var hn=[{kind:`pdf`,label:`PDF`,title:`Render the whole document as a PDF file`,rendered:!0},{kind:`docx`,label:`Word (.docx)`,title:`Render the whole document as a Word document`,rendered:!0},{kind:`html`,label:`HTML`,title:`Render the whole document as a web page`,rendered:!0},{kind:`md`,label:`Markdown (.md)`,title:`Download the whole document as Markdown, with the metadata comments that let it be imported back`,rendered:!1},{kind:`canvas`,label:`Canvas (.canvas)`,title:`Download the whole document as a node/edge canvas graph (.canvas)`,rendered:!1}];function gn(e){return hn.filter(t=>!t.rendered||!!e.documentExportFile)}async function _n(e,t,n,r,i,a,o=ne){if(t===`md`){let t=await e.documentExportMd(n,r,!0,i);o(new Blob([t.markdown],{type:`text/markdown`}),te(t.title)+`.md`);return}if(t===`canvas`){let t=await e.documentExportCanvas(n,r,i);o(new Blob([JSON.stringify(t.canvas,null,2)],{type:`application/json`}),te(a)+`.canvas`);return}if(!e.documentExportFile)throw Error(`this connection cannot download rendered files`);let s=t,c=await e.documentExportFile(n,r,s,i);o(c.blob,c.filename||te(a)+`.`+s)}function vn({documentId:e,scope:t,browse:n,title:r,onError:i}){let a=H(),o=gn(a),[s,u]=(0,c.useState)(null),d=s!==null,[f,p]=(0,c.useState)(null),m=(0,c.useRef)(null),h=(0,c.useRef)(null),g=(0,c.useRef)([]),_=(0,c.useId)();(0,c.useEffect)(()=>{s!==null&&g.current[s]?.focus()},[s]),(0,c.useEffect)(()=>{if(!d)return;let e=e=>{m.current&&!m.current.contains(e.target)&&u(null)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[d]);let v=(0,c.useCallback)(async o=>{u(null),h.current?.focus(),p(o);try{await _n(a,o,e,t,n,r)}catch(e){i(e instanceof Error?e.message:String(e))}finally{p(null)}},[a,e,t,n,r,i]),y=e=>g.current[(e+o.length)%o.length]?.focus(),b=(e,t)=>{switch(e.key){case`ArrowDown`:e.preventDefault(),y(t+1);break;case`ArrowUp`:e.preventDefault(),y(t-1);break;case`Home`:e.preventDefault(),y(0);break;case`End`:e.preventDefault(),y(o.length-1);break;case`Escape`:e.preventDefault(),u(null),h.current?.focus();break;case`Tab`:u(null)}},x=f?hn.find(e=>e.kind===f)?.label:void 0;return(0,l.jsxs)(`div`,{className:`doc-download-menu`,ref:m,children:[(0,l.jsx)(`button`,{ref:h,type:`button`,className:d?`active`:``,title:x?`Preparing ${x}…`:`Download the whole document as a file`,"aria-haspopup":`menu`,"aria-expanded":d,"aria-controls":d?_:void 0,"aria-busy":f!==null,disabled:f!==null,onClick:()=>u(d?null:0),onKeyDown:e=>{e.key===`ArrowDown`?(e.preventDefault(),u(0)):e.key===`ArrowUp`?(e.preventDefault(),u(o.length-1)):e.key===`Escape`&&d&&(e.preventDefault(),u(null))},children:x?`↓ ${x}…`:`↓ download ▾`}),d&&(0,l.jsx)(`div`,{className:`doc-download-list`,role:`menu`,id:_,"aria-label":`Download as`,children:o.map((e,t)=>(0,l.jsx)(`button`,{ref:e=>{g.current[t]=e},type:`button`,role:`menuitem`,tabIndex:-1,title:e.title,"data-kind":e.kind,onClick:()=>void v(e.kind),onKeyDown:e=>b(e,t),children:e.label},e.kind))})]})}function yn(e){let t=typeof e==`number`?e/1e6:Date.parse(String(e));return!Number.isFinite(t)||t<=0?String(e??``):new Date(t).toLocaleString()}function bn({chunkId:e,chunkTitle:t,scope:n,browse:r,onClose:i}){let a=H(),[o,s]=(0,c.useState)([]),[u,d]=(0,c.useState)(!0),[f,p]=(0,c.useState)(null),[m,h]=(0,c.useState)(`none`),[g,_]=(0,c.useState)(null),[v,y]=(0,c.useState)(``),[b,x]=(0,c.useState)(!1),[S,C]=(0,c.useState)(null),[w,T]=(0,c.useState)(null),[E,D]=(0,c.useState)(``);(0,c.useEffect)(()=>{let t=!1;return d(!0),p(null),a.documentHistory(e,n,r).then(e=>{if(t)return;let n=e.revisions??[];if(s(n),n.length>=2){let e=n.map(e=>e.revision);C(Math.min(...e)),T(Math.max(...e))}}).catch(e=>!t&&p(e instanceof Error?e.message:String(e))).finally(()=>!t&&d(!1)),()=>{t=!0}},[a,e,n,r]);let O=async t=>{p(null),x(!0),_(t),h(`version`);try{let i=await a.documentGetVersion(e,t,n,r);y(i.body??``)}catch(e){p(e instanceof Error?e.message:String(e))}finally{x(!1)}},k=async()=>{if(S!==null&&w!==null){p(null),x(!0),h(`diff`);try{let t=await a.documentDiff(e,S,w,n,r);D(t.diff??``)}catch(e){p(e instanceof Error?e.message:String(e))}finally{x(!1)}}};return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:i,children:(0,l.jsxs)(`div`,{className:`modal history-modal`,onClick:e=>e.stopPropagation(),children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsxs)(`h3`,{children:[`History`,t?` — ${t}`:``]}),(0,l.jsx)(`div`,{className:`modal-buttons modal-buttons-top`,children:(0,l.jsx)(`button`,{type:`button`,onClick:i,children:`close`})})]}),f&&(0,l.jsx)(`div`,{className:`modal-err`,children:f}),u?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`loading…`}):o.length===0?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`No history recorded for this chunk.`}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`div`,{className:`doc-hist-revs`,children:o.map(e=>(0,l.jsxs)(`button`,{type:`button`,className:`doc-hist-rev`+(m===`version`&&g===e.revision?` active`:``),onClick:()=>void O(e.revision),children:[(0,l.jsxs)(`span`,{className:`doc-hist-rev-num`,children:[`rev `,e.revision]}),(0,l.jsx)(`span`,{className:`doc-hist-rev-time`,children:yn(e.created_at)}),(0,l.jsx)(`span`,{className:`doc-hist-rev-actor`,children:e.actor||`unknown`})]},e.revision))}),o.length>=2&&(0,l.jsxs)(`div`,{className:`doc-hist-diffbar`,children:[(0,l.jsx)(`span`,{children:`Compare`}),(0,l.jsx)(`select`,{value:S??``,onChange:e=>C(e.target.value===``?null:Number(e.target.value)),"aria-label":`diff from revision`,children:o.map(e=>(0,l.jsxs)(`option`,{value:e.revision,children:[`rev `,e.revision]},e.revision))}),(0,l.jsx)(`span`,{"aria-hidden":!0,children:`→`}),(0,l.jsx)(`select`,{value:w??``,onChange:e=>T(e.target.value===``?null:Number(e.target.value)),"aria-label":`diff to revision`,children:o.map(e=>(0,l.jsxs)(`option`,{value:e.revision,children:[`rev `,e.revision]},e.revision))}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void k(),disabled:b||S===null||w===null,children:`diff`})]}),(0,l.jsx)(`div`,{className:`doc-hist-output`,children:b?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`loading…`}):m===`diff`?(0,l.jsx)(xn,{text:E}):m===`version`?(0,l.jsx)(`pre`,{className:`md-pre doc-hist-version`,children:(0,l.jsx)(`code`,{children:v||`(empty)`})}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`Select a revision to view it, or compare two.`})})]})]})})}function xn({text:e}){if(!e.trim())return(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(no differences)`});let t=e.split(`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("react"),l=require("react/jsx-runtime"),u=require("@loomcycle/client"),d=require("react-dom");require("@loomcycle/code-editor/styles.css");let f=require("react-markdown");f=s(f,1);let p=require("remark-gfm");p=s(p,1);var m=`loomcycle.explorer.navigator`;function h(e){try{return e?.getItem(`loomcycle.explorer.navigator`)===`stars`?`stars`:`tree`}catch{return`tree`}}function g(e,t){try{e?.setItem(m,t)}catch{}}function _(e){return!!e&&!e.parent_id&&!!e.entity?.natural_key}function v(e){let t=e?.classes;if(!Array.isArray(t))return[];let n=new Set;for(let e of t){let{name:t,kind:r}=e??{};typeof t==`string`&&t!==``&&r!==`document`&&n.add(t)}return[...n].sort((e,t)=>e.localeCompare(t))}function y(e,t){let n=t??``;return n===``||e.some(e=>e.toLowerCase()===n.toLowerCase())?e:[n,...e]}function b(e){let t={op:e.op===`copy`?`copy_documents`:`move_documents`,scope:e.scope,to_scope:e.toScope,dry_run:e.dryRun};e.documentId&&(t.document_ids=[e.documentId]),e.underPath&&(t.under_path=e.underPath);let n=w(e.from),r=w(e.to);return n&&r&&n!==r&&(t.path_map={[n]:r}),e.op===`move`&&(e.dropDangling&&(t.dangling=`drop`),e.dryRun||(t.expect_count=e.expectCount??0)),t}function x(e){let t=e.to.trim();return t.startsWith(`/`)?e.op===`move`&&e.toScope===e.scope?`a move goes to another scope; to rename within this one, use rename / move`:e.op===`copy`&&e.toScope===e.scope&&w(t)===w(e.from)?`a copy into the same scope needs a new path`:null:`the new path must start with /`}function S(e,t){let n=t.counts??{},r=n.documents??0,i=e===`copy`?`copied`:`moved`,a=[],o=`${n.chunks??0} parts, ${n.revisions??0} revisions, ${n.statements??0} relations, ${n.assets??0} images`;if(t.dry_run)a.push(`${r} ${T(r,`document`)} would be ${i}: ${o}.`),t.to_finish?.length&&a.push(`${t.to_finish.length} ${T(t.to_finish.length,`document`)} left by an earlier interrupted move will be finished.`);else if(e===`move`){let e=t.moved?.length??0;a.push(`${e} ${T(e,`document`)} moved: ${o}.`)}else a.push(`${r} ${T(r,`document`)} copied: ${o}.`);let s=t.refused_count??t.refused?.length??0;if(s>0){a.push(`${s} ${T(s,`document`)} refused:`);for(let e of t.refused??[])a.push(` ${e.document_id}: ${e.code}${e.detail?` — ${e.detail}`:``}`)}if(t.dangling_count>0){e===`copy`?a.push(`${t.dangling_count} ${T(t.dangling_count,`relation`)} to documents outside the set stay behind.`):t.dropped===void 0?t.blocked_by===`dangling_relations`?a.push(`${t.dangling_count} ${T(t.dangling_count,`relation`)} join these documents to ones outside the set. A relation cannot span two scopes: include the other documents, or drop these relations.`):a.push(`${t.dangling_count} ${T(t.dangling_count,`relation`)} to documents outside the set will be dropped.`):a.push(`${t.dropped} ${T(t.dropped,`relation`)} to documents outside the set were dropped.`);for(let e of t.dangling??[])a.push(` ${e.kind}: ${e.from} → ${e.to} (outside: ${e.outside})`)}for(let e of t.unfinished??[])a.push(`not finished: ${e.document_id}: ${e.code}${e.detail?` — ${e.detail}`:``}. Run the move again.`);for(let e of t.name_failures??[])a.push(`no name ${e.path} for ${e.document_id}: ${e.error}`);return t.body_failures&&a.push(`${t.body_failures} ${T(t.body_failures,`body`,`bodies`)} could not be written.`),t.statements_failed&&a.push(`${t.statements_failed} ${T(t.statements_failed,`relation`)} could not be written${t.statement_error?`: ${t.statement_error}`:``}.`),a}function C(e,t,n){return e===`move`&&t.dangling_count>0&&!n||(t.counts?.documents??0)===0&&!(t.to_finish?.length??0)}function w(e){let t=e.trim(),n=t.length;for(;n>1&&t[n-1]===`/`;)n--;return t.slice(0,n)}function T(e,t,n=t+`s`){return e===1?t:n}function E(e){return e===`tenant`}var D=240,O=2e3,k=[`branch`,`document`,`path`,`scheme`,`concept`,`class`];function ee(e){return typeof e==`string`&&k.includes(e)}function A(e,t){return Array.isArray(e)?e.filter(e=>!!e&&typeof e==`object`&&e.chunk_id===t&&ee(e.level)&&typeof e.brief==`string`&&e.brief.trim()!==``).sort((e,t)=>k.indexOf(e.level)-k.indexOf(t.level)):[]}async function j(e,t,n,r){return!E(n)||!e.documentGetAnnotation||!t?[]:A((await e.documentGetAnnotation(t,n,r))?.annotations,t)}function M(e){return e?`document`:`branch`}function te(e){return[...e].length}function N(e,t){if(e.trim()===``)return`The brief is required.`;if(te(e)>240)return`The brief is longer than 240 characters.`;if(t.trim()===``)return`The abstract is required.`;if(te(t)>2e3)return`The abstract is longer than ${O} characters.`}function P(e,t){return{op:`set_annotation`,scope:t,id:e.id,level:e.level,brief:e.brief.trim(),abstract:e.abstract.trim(),manual:!0}}function F(e){if(e)return e.startsWith(`run:`)?`run ${e.slice(4)}`:e.startsWith(`principal:`)?e.slice(10):e}function I(e){if(!e)return;let t=Date.parse(e);return Number.isNaN(t)?e:new Date(t).toLocaleString()}function L(e){if(!e)return;let t=/filename\*\s*=\s*([^']*)'[^']*'([^;]+)/i.exec(e);if(t&&/^utf-8$/i.test(t[1].trim()))try{let e=R(decodeURIComponent(t[2].trim()));if(e)return e}catch{}let n=/(?:^|;)\s*filename\s*=\s*"((?:[^"\\]|\\.)*)"/i.exec(e);if(n)return R(n[1].replace(/\\(.)/g,`$1`))||void 0;let r=/(?:^|;)\s*filename\s*=\s*([^;\s"]+)/i.exec(e);if(r)return R(r[1])||void 0}function R(e){return e.slice(Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`))+1).trim()}function ne(e,t,n=``){try{let t=JSON.parse(e);if(typeof t.error==`string`&&t.error)return t.error}catch{}return`${t} ${n}`.trim()}function re(e){return(e||`document`).replace(/[^\w.-]+/g,`_`)}function z(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}var B=4,ie=5e3;function ae(e){let t={};return e?.name_contains&&(t.name_contains=e.name_contains),e?.type&&(t.type=e.type),e?.status&&(t.status=e.status),t}function V(e,t,n){return{...se(e,n),pathLs:(t,n,r,i,a)=>e.path({op:`ls`,path:t,scope:n,recursive:r,...a?.limit?{limit:a.limit}:{},...a?.cursor?{cursor:a.cursor}:{},...a?.withCounts?{with_counts:!0}:{},...ae(a?.filters)},i),pathIsStored:(t,n,r)=>e.path({op:`stat`,path:t,scope:n},r).then(()=>!0,e=>{if(e?.name===`SubstrateToolRefusedError`)return!1;throw e}),documentPath:async(t,n,r)=>{let i;for(let a=0;a<B;a++){let a=await e.path({op:`ls`,path:`/`,scope:n,recursive:!0,kind_filter:`document`,limit:ie,...i?{cursor:i}:{}},r),o=(a.entries??[]).find(e=>e.resource_ref?.document_id===t);if(o)return o.full_path;if(i=a.next_cursor||void 0,!i)return}},pathMkdir:(t,n,r)=>e.path({op:`mkdir`,path:t,scope:n},r),pathMv:(t,n,r,i)=>e.path({op:`mv`,path:t,to:n,scope:r},i),pathRm:(t,n,r,i)=>e.path({op:`rm`,path:t,scope:n,recursive:r},i),documentCreate:(t,n,r,i)=>e.document({op:`create_document`,title:t,path:n,scope:r},i),documentDelete:(t,n,r)=>e.document({op:`delete_document`,id:t,scope:n},r),documentsTransfer:(t,n)=>e.document(b(t),n),documentGet:(t,n,r)=>e.document({op:`get_document`,id:t,scope:n},r),documentsSummary:(t,n,r)=>e.document({op:`documents_summary`,scope:n,...t.documentIds?{document_ids:t.documentIds}:{},...t.underPath?{under_path:t.underPath}:{}},r),documentQueryChunks:(t,n,r)=>e.document({op:`query_chunks`,document_id:t,scope:n,limit:1e3,with_summary:!0},r),documentGetChunk:(t,n,r)=>e.document({op:`get_chunk`,id:t,scope:n},r),documentCreateChunk:(t,n,r,i,a,o)=>e.document({op:`create_chunk`,document_id:t,parent_id:n,scope:i,...o?{after_id:o}:{},...r},a),documentReorderChunk:(t,n,r,i)=>e.document({op:`reorder_chunk`,id:t,direction:n,scope:r},i),documentDeleteChunk:(t,n,r)=>e.document({op:`delete_chunk`,id:t,scope:n},r),documentSetAsset:(t,n,r,i,a,o)=>e.document({op:`set_asset`,id:t,media_type:n,data:r,...i?{filename:i}:{},scope:a},o),documentGetEdges:(t,n,r,i)=>e.document({op:`get_edges`,document_id:t,scope:n,...i?.after?{after:i.after}:{}},r),documentGetEdge:(t,n,r)=>e.document({op:`get_edge`,id:t,scope:n},r),documentAcceptStatement:(t,n,r,i)=>e.document({op:`accept_statement`,id:t,scope:n,...i?{reason:i}:{}},r),documentRejectStatement:(t,n,r,i)=>e.document({op:`reject_statement`,id:t,reason:n,scope:r},i),documentListStatements:(t,n,r)=>e.document({op:`list_statements`,scope:t,...r?.status?{status:r.status}:{},...r?.kind?{kind:r.kind}:{},...r?.limit?{limit:r.limit}:{},...r?.after?{after:r.after}:{}},n),documentClassify:(t,n,r,i)=>e.document({op:`classify`,document_id:t,write:n,scope:r},i),documentEntityTypes:(t,n)=>e.document({op:`describe_ontology`,scope:t},n).then(v),documentAcceptClassification:(t,n,r)=>e.document({op:`accept_classification`,document_id:t,scope:n},r),documentGetAnnotation:(t,n,r)=>e.document({op:`get_annotation`,id:t,scope:n},r),documentSetAnnotation:(t,n,r)=>e.document(P(t,n),r),documentUpdateChunk:(t,n,r,i,a)=>e.document({op:`update_chunk`,id:t,revision:n,scope:i,...r},a),documentExportMd:(t,n,r,i)=>e.document({op:`export_md`,document_id:t,scope:n,include_metadata:r},i),documentBacklinks:(t,n,r)=>e.document({op:`backlinks`,id:t,scope:n},r),documentRelated:(t,n,r,i)=>e.document({op:`related`,id:t,scope:n,...i?{limit:i}:{}},r),documentUnlinkedMentions:(t,n,r,i)=>e.document({op:`unlinked_mentions`,id:t,scope:n,...i?{limit:i}:{}},r),documentHistory:(t,n,r,i)=>e.document({op:`history`,id:t,scope:n,...i?{limit:i}:{}},r),documentGetVersion:(t,n,r,i)=>e.document({op:`get_version`,id:t,revision:n,scope:r},i),documentDiff:(t,n,r,i,a)=>e.document({op:`diff`,id:t,from_revision:n,to_revision:r,scope:i},a),documentExportCanvas:(t,n,r)=>e.document({op:`export_canvas`,document_id:t,scope:n},r),...t?{documentAssetObjectUrl:async(e,n,r)=>{let i=new URLSearchParams({scope:n});r?.scopeId&&i.set(`scope_id`,r.scopeId),r?.tenant&&i.set(`tenant`,r.tenant);let a=await t(`/v1/_document/asset/${encodeURIComponent(e)}?${i.toString()}`);if(!a.ok)throw Error(`asset fetch failed: ${a.status}`);let o=await a.blob();return URL.createObjectURL(o)},documentExportFile:async(e,n,r,i,a)=>{let o=await t(oe(e,n,r,i,a));if(!o.ok)throw Error(ne(await o.text(),o.status,o.statusText));return{blob:await o.blob(),filename:L(o.headers.get(`Content-Disposition`))??``}}}:{}}}function oe(e,t,n,r,i){let a=new URLSearchParams({format:n,scope:t});return r?.scopeId&&a.set(`scope_id`,r.scopeId),r?.tenant&&a.set(`tenant`,r.tenant),i?.chunk&&a.set(`chunk`,i.chunk),i?.toc&&a.set(`toc`,`true`),i?.titlePage&&a.set(`title_page`,`true`),i?.pageSize&&a.set(`page_size`,i.pageSize),i?.language&&a.set(`language`,i.language),i?.provenance===!1&&a.set(`provenance`,`false`),`/v1/_document/export/${encodeURIComponent(e)}?${a.toString()}`}function se(e,t){let n=e,r=e=>e?.tenant?`?tenant=${encodeURIComponent(e.tenant)}`:``,i={};typeof n.ruleStatements==`function`?i.documentRuleStatements=(e,t)=>n.ruleStatements(e.action,e.ids?{ids:e.ids}:{filter:e.filter},{reason:e.reason,dryRun:e.dry_run,expectCount:e.expect_count,max:e.max,scope:e.scope,scopeId:e.scope_id,tenant:t?.tenant}):t&&(i.documentRuleStatements=(e,n)=>t(`/v1/_statements/rule${r(n)}`,e));let a=(e,t)=>e===`user`&&t?.scopeId?t.scopeId:void 0;return typeof n.revertRuling==`function`?i.documentRevertRuling=(e,t,r)=>n.revertRuling(e,{scope:t,scopeId:a(t,r),tenant:r?.tenant}):t&&(i.documentRevertRuling=(e,n,i)=>{let o=a(n,i);return t(`/v1/_statements/revert${r(i)}`,{ruling_id:e,scope:n,...o?{scope_id:o}:{}})}),i}var ce=(0,c.createContext)(null);function le({value:e,children:t}){return(0,l.jsx)(ce.Provider,{value:e,children:t})}function ue(){let e=(0,c.useContext)(ce);if(!e)throw Error(`useExplorerData must be used within <PathExplorer> or <DocumentViewer> (no ExplorerDataLayer in context)`);return e}var de=5e3;function fe(e){return e===``?`/`:e}function pe(e){let t=e.lastIndexOf(`/`);return t<=0?``:e.slice(0,t)}function H(e){let t=[``],n=e.split(`/`).filter(Boolean),r=``;for(let e=0;e<n.length-1;e++)r=`${r}/${n[e]}`,t.push(r);return t}function me(e){return e instanceof Error?e.message:String(e)}function he(e,t){let n={entries:[...t,...e.entries??[]],nextCursor:e.next_cursor||void 0,loaded:!0,loading:!1};return e.filters&&typeof e.filters==`object`&&(n.appliedFilters=e.filters),Array.isArray(e.type_expanded_to)&&(n.typeExpandedTo=e.type_expanded_to),n}var ge=class{data;scope;browse;pageLimit;listing;dirs=new Map;snapshot=new Map;listeners=new Set;inflight=new Map;epoch=new Map;constructor(e,t,n,r=500,i={}){this.data=e,this.scope=t,this.browse=n,this.pageLimit=r,this.listing=i}getSnapshot=()=>this.snapshot;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});publish(){this.snapshot=new Map(this.dirs),this.listeners.forEach(e=>e())}set(e,t){this.dirs.set(e,t),this.publish()}track(e,t){let n=t.finally(()=>{this.inflight.get(e)===n&&this.inflight.delete(e)});return this.inflight.set(e,n),n}loadDir(e){return this.inflight.get(e)||(this.dirs.get(e)?.loaded?Promise.resolve():this.fetchFirst(e,this.pageLimit))}reload(e){let t=this.dirs.get(e),n=t?.entries.length??0,r=t?.loaded&&!t.nextCursor?n+this.pageLimit:n;return this.fetchFirst(e,Math.min(de,Math.max(this.pageLimit,r)))}fetchFirst(e,t){let n=(this.epoch.get(e)??0)+1;this.epoch.set(e,n);let r=this.dirs.get(e);this.set(e,{...r,entries:r?.entries??[],nextCursor:r?.nextCursor,loaded:r?.loaded??!1,loading:!0,error:void 0});let i=this.data.pathLs(fe(e),this.scope,!1,this.browse,{...this.listing,limit:t}).then(t=>{this.epoch.get(e)===n&&this.set(e,he(t,[]))},t=>{throw this.epoch.get(e)===n&&this.set(e,{...r,entries:r?.entries??[],nextCursor:r?.nextCursor,loaded:r?.loaded??!1,loading:!1,error:me(t)}),t});return this.track(e,i)}loadMore(e){let t=this.inflight.get(e);if(t)return t;let n=this.dirs.get(e);if(!n?.nextCursor)return Promise.resolve();let r=this.epoch.get(e)??0;this.set(e,{...n,loading:!0,error:void 0});let i=this.data.pathLs(fe(e),this.scope,!1,this.browse,{...this.listing,limit:this.pageLimit,cursor:n.nextCursor}).then(t=>{this.epoch.get(e)===r&&this.set(e,he(t,n.entries))},t=>{throw this.epoch.get(e)===r&&this.set(e,{...n,loading:!1,error:me(t)}),t});return this.track(e,i)}async reveal(e){let t=e.split(`/`).filter(Boolean),n=``;for(let e of t){for(await this.loadDir(n);;){let t=this.dirs.get(n);if(!t)return!1;if(t.entries.some(t=>t.name===e))break;let r=t.entries[t.entries.length-1];if(!t.nextCursor||r&&r.name>e)return!1;let i=t.nextCursor;if(await this.loadMore(n),this.dirs.get(n)?.nextCursor===i)return!1}n=`${n}/${e}`}return!0}async invalidate(e,t){if(t?.dropSubtree){for(let t of[...this.dirs.keys()])(t===e||t.startsWith(`${e}/`))&&(this.dirs.delete(t),this.epoch.set(t,(this.epoch.get(t)??0)+1),this.inflight.delete(t));this.publish()}let n=H(e).filter(e=>this.dirs.has(e));await Promise.all(n.map(e=>this.reload(e)))}async refresh(e){let t=new Set(e);t.add(``);for(let e of[...this.dirs.keys()])t.has(e)||(this.dirs.delete(e),this.epoch.set(e,(this.epoch.get(e)??0)+1),this.inflight.delete(e));this.publish();let n=[...t].filter(e=>e===``||this.dirs.has(e));await Promise.all(n.map(e=>this.reload(e)))}};async function _e(e,t,n,r){let i=[],a;for(;;){let o=await e.pathLs(fe(t),n,!0,r,{limit:de,cursor:a});i.push(...o.entries??[]);let s=o.next_cursor||void 0;if(!s||s===a)return i;a=s}}function ve(e){let t=[];for(let n of e){if(n.kind!==`document`)continue;let e=n.resource_ref?.document_id;e&&t.push(e)}return t}function U(e){let t=e.fetch;return new u.LoomcycleClient({baseUrl:e.baseUrl,authToken:e.token||void 0,fetch:(e,n)=>t?t(e,n):fetch(e,n)})}function ye(e){let t=e.fetch,n=(e,n)=>t?t(e,n):fetch(e,n);return t=>{let r={};return e.token&&(r.Authorization=`Bearer ${e.token}`),n(e.baseUrl+t,{headers:r})}}var be=class extends Error{status;code;constructor(e,t,n){super(e),this.name=`RequestError`,this.status=t,this.code=n}};function xe(e){let t=e.fetch,n=(e,n)=>t?t(e,n):fetch(e,n);return async(t,r)=>{let i={"Content-Type":`application/json`,Accept:`application/json`};e.token&&(i.Authorization=`Bearer ${e.token}`);let a=await n(e.baseUrl+t,{method:`POST`,headers:i,body:JSON.stringify(r)}),o=await a.text(),s;try{s=o?JSON.parse(o):void 0}catch{}if(!a.ok){let e=s&&typeof s==`object`?s:{};throw new be(typeof e.error==`string`&&e.error?e.error:`${a.status} ${a.statusText}`.trim(),a.status,typeof e.code==`string`?e.code:void 0)}return s}}var Se=(0,c.createContext)(null);function W({children:e}){let t=(0,c.useRef)(new Map);return(0,l.jsx)(Se.Provider,{value:t.current,children:e})}var Ce=(0,c.createContext)(null);function we(e,t){if(!t)return e;let n={...e};for(let e of Object.keys(t)){let r=t[e];r!==void 0&&r!==``&&(n[e]=r)}return n}function Te(e){let t=(0,c.useContext)(Se),n=(0,c.useRef)(new Map),r=t??n.current,i=(0,c.useRef)(e);i.current=e;let[a,o]=(0,c.useState)(!1),[s,u]=(0,c.useState)({key:void 0,done:!1}),f=(0,c.useRef)(null),p=(0,c.useRef)(null),m=(0,c.useRef)(void 0),h=(0,c.useRef)(!1),g=(0,c.useRef)(0),_=(0,c.useId)(),v=()=>{m.current!==void 0&&clearTimeout(m.current),m.current=void 0},y=(0,c.useCallback)(()=>{v(),g.current++,o(!1)},[]),b=(0,c.useCallback)(()=>{v();let e=i.current;if(!e)return;if(o(!0),!e.load){u({key:e.key,done:!0});return}let t=++g.current,n=e.key?r.get(e.key):void 0;n||(n=e.load().catch(()=>void 0),e.key&&r.set(e.key,n)),u({key:e.key,done:!1}),n.then(n=>{g.current===t&&u({key:e.key,info:n,done:!0})})},[r]);(0,c.useEffect)(()=>v,[]),(0,c.useEffect)(()=>{if(!a)return;let e=()=>y();return window.addEventListener(`scroll`,e,!0),()=>window.removeEventListener(`scroll`,e,!0)},[a,y]),(0,c.useLayoutEffect)(()=>{let e=p.current,t=f.current;if(!a||!e||!t)return;let n=t.getBoundingClientRect(),r=window.innerWidth||document.documentElement.clientWidth,i=window.innerHeight||document.documentElement.clientHeight,o=e.offsetWidth,s=e.offsetHeight,c=n.bottom+4,l=c+s<=i-8||n.top-4-s<8?c:n.top-4-s,u=Math.max(8,Math.min(n.left,r-o-8));e.style.top=`${Math.round(l)}px`,e.style.left=`${Math.round(u)}px`});let x=(0,c.useCallback)(e=>{f.current=e},[]),S=(0,c.useCallback)(()=>{h.current=!0,setTimeout(()=>{h.current=!1},0),y()},[y]),C=e&&a?we(e,s.key===e.key?s.info:void 0):void 0,w=!!e?.load&&a&&!(s.key===e.key&&s.done),T=typeof document>`u`?null:f.current?.closest(`.loomcycle-explorer`)??document.body,E=C&&T?(0,d.createPortal)((0,l.jsx)(`div`,{className:`ex-card`,id:_,role:`tooltip`,ref:p,children:(0,l.jsx)(Ee,{info:C,loading:w})}),T):null;return{anchorRef:x,hover:{onMouseEnter:()=>{i.current&&!h.current&&(v(),m.current=setTimeout(b,600))},onMouseLeave:y,onMouseDown:S},focus:{onFocus:e=>{e.target!==e.currentTarget||h.current||b()},onBlur:e=>{e.target===e.currentTarget&&y()},onKeyDown:e=>{e.key===`Escape`&&a&&y()},onMouseDown:S,"aria-describedby":C?_:void 0},card:E}}function Ee({info:e,loading:t}){let n=[e.type,e.status].filter(Boolean).join(` · `);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`div`,{className:`ex-card-title`,children:e.title}),(n||e.stale)&&(0,l.jsxs)(`div`,{className:`ex-card-meta`,children:[n,e.stale&&(0,l.jsxs)(`span`,{className:`ex-card-stale`,children:[n?` · `:``,`annotation out of date`]})]}),e.path&&(0,l.jsx)(`div`,{className:`ex-card-path`,children:e.path}),e.brief&&(0,l.jsx)(`p`,{className:`ex-card-brief`,children:e.brief}),e.abstract&&(0,l.jsx)(`p`,{className:`ex-card-abstract`,children:e.abstract}),t&&!e.brief&&(0,l.jsx)(`p`,{className:`ex-card-loading`,children:`Loading…`})]})}function De(e){let t=e.summary;if(t&&typeof t.brief==`string`)return{brief:t.brief,abstract:typeof t.abstract==`string`?t.abstract:void 0,stale:t.stale===!0||void 0}}function Oe(e,t,n){let r={title:e.title||`(untitled)`,type:e.type,status:e.status},i=De(e);return i?{...r,...i}:!t||n?r:{...r,key:`${t.scope}:${t.browse?.scopeId??``}:${t.browse?.tenant??``}:chunk:${e.id}`,load:async()=>{let n=(await j(t.data,e.id,t.scope,t.browse))[0];return n?{brief:n.brief,abstract:n.abstract,stale:n.stale||void 0}:void 0}}}function ke(e,t,n,r){let i={title:t,...r};return!n||r?.brief!==void 0?i:{...i,key:`${n.scope}:${n.browse?.scopeId??``}:${n.browse?.tenant??``}:doc:${e}`,load:async()=>{let t=(await n.data.documentsSummary({documentIds:[e]},n.scope,n.browse)).documents?.find(t=>t.document_id===e);return t?{title:t.title,type:t.type,status:t.status,brief:t.brief}:void 0}}}function G(e){let t=Te(e);return{props:{ref:t.anchorRef,onMouseEnter:t.hover.onMouseEnter,onMouseLeave:t.hover.onMouseLeave,onMouseDown:t.hover.onMouseDown,onFocus:t.focus.onFocus,onBlur:t.focus.onBlur,onKeyDown:t.focus.onKeyDown,"aria-describedby":t.focus[`aria-describedby`]},card:t.card}}function Ae(e){let{dataLayer:t,client:n,connection:r}=e;return(0,c.useMemo)(()=>t||(n?V(n):r?V(U(r),ye(r),xe(r)):null),[t,n,r?.baseUrl,r?.token,r?.fetch])}function je({theme:e,dataLayer:t,children:n}){let r=e?{"data-theme":e}:{};return t?(0,l.jsx)(`div`,{className:`loomcycle-explorer`,...r,children:(0,l.jsx)(le,{value:t,children:(0,l.jsx)(W,{children:n})})}):(0,l.jsx)(`div`,{className:`loomcycle-explorer`,...r,children:(0,l.jsxs)(`div`,{className:`error-banner`,children:[`@loomcycle/explorer: provide a `,(0,l.jsx)(`code`,{children:`connection`}),`, `,(0,l.jsx)(`code`,{children:`client`}),`, or`,` `,(0,l.jsx)(`code`,{children:`dataLayer`}),` prop.`]})})}function Me(e,t,n){let r=e[e.length-1];return[...r&&r.documentId===t.documentId?[...e.slice(0,-1),{...r,...Fe(t)}]:[...e,t],n]}function Ne(e,t){return t<0||t>=e.length-1?e:e.slice(0,t+1)}function Pe(e,t,n){let r=e[e.length-1];if(!r||r.documentId!==t)return e;let i={...r,...Fe(n)};return i.title===r.title&&i.path===r.path?e:[...e.slice(0,-1),i]}function Fe(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function Ie(e){return e.title?e.title:e.path?e.path.slice(e.path.lastIndexOf(`/`)+1)||e.path:e.documentId.slice(0,8)}function Le(e,t=4){let n=Array.from({length:e},(e,t)=>({kind:`crumb`,index:t}));if(e<=t||t<3)return n;let r=t-1,i=Array.from({length:e-1-r},(e,t)=>t+1);return[n[0],{kind:`gap`,hidden:i},...n.slice(e-r)]}function Re(e,t){for(let n of e.values()){let e=n.entries.find(e=>ze(e)===t);if(e)return e.full_path}}function ze(e){if(e.kind===`document`)return e.resource_ref?.document_id||void 0}function Be(e,t){return t&&e.some(e=>e.id===t)?t:e.find(e=>!e.parent_id)?.id}function Ve({trail:e,onJump:t}){let[n,r]=(0,c.useState)(!1);if(e.length<2)return null;let i=e.length-1,a=e[i-1],o=Le(e.length,n?e.length:void 0);return(0,l.jsxs)(`nav`,{className:`doc-trail`,"aria-label":`Documents you came through`,children:[(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-back`,onClick:()=>t(i-1),title:`Back to ${Ie(a)}`,children:`← Back`}),(0,l.jsx)(`ol`,{className:`doc-trail-list`,children:o.map(n=>n.kind===`gap`?(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-gap`,onClick:()=>r(!0),title:`Show ${n.hidden.length} more: ${n.hidden.map(t=>Ie(e[t])).join(` › `)}`,"aria-label":`Show ${n.hidden.length} hidden documents`,children:`…`})},`gap`):n.index===i?(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`span`,{className:`doc-trail-current`,"aria-current":`page`,title:Ie(e[i]),children:Ie(e[i])})},n.index):(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-crumb`,onClick:()=>t(n.index),title:Ie(e[n.index]),children:Ie(e[n.index])})},n.index))})]})}function He({data:e,scope:t,browse:n,documentId:r,underPath:i,fromPath:a,onClose:o,onDone:s}){let[u,d]=(0,c.useState)(`copy`),[f,p]=(0,c.useState)(t===`tenant`?`user`:`tenant`),[m,h]=(0,c.useState)(a),[g,_]=(0,c.useState)(!1),[v,y]=(0,c.useState)(null),[w,T]=(0,c.useState)(null),[E,D]=(0,c.useState)(!1),[O,k]=(0,c.useState)(null),ee=(0,c.useMemo)(()=>({op:u,scope:t,toScope:f,documentId:r,underPath:i,from:a,to:m,dropDangling:g,dryRun:!0}),[u,t,f,r,i,a,m,g]),A=JSON.stringify(b(ee)),j=x(ee),M=v&&v.key===A?v.res:null,te=M?C(u,M,g):!1,N=M?u===`move`?(M.counts?.documents??0)+(M.to_finish?.length??0):M.counts?.documents??0:0,P=async t=>{if(t.preventDefault(),w)o();else if(!j&&e.documentsTransfer){D(!0),k(null);try{if(!M)y({key:A,res:await e.documentsTransfer(ee,n)});else{let t={...ee,dryRun:!1,expectCount:M.counts?.documents??0},r=await e.documentsTransfer(t,n);T(r),s(t,r)}}catch(e){k(e instanceof Error?e.message:String(e))}finally{D(!1)}}},F=w?`close`:E?`working…`:M?`${u} ${N} document${N===1?``:`s`}`:`check`,I=w??M;return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:E?void 0:o,children:(0,l.jsxs)(`form`,{className:`modal`,onClick:e=>e.stopPropagation(),onSubmit:P,children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsxs)(`h3`,{children:[`Copy or move the `,r?`document`:`documents under`,` `,a]}),(0,l.jsxs)(`div`,{className:`modal-buttons modal-buttons-top`,children:[!w&&(0,l.jsx)(`button`,{type:`button`,onClick:o,disabled:E,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:M&&u===`move`&&!w?`danger`:`primary`,disabled:E||!w&&(!!j||te),children:F})]})]}),(0,l.jsxs)(`p`,{className:`modal-context`,children:[`A copy gets new ids and leaves the source as it is. A move keeps every id and removes the documents from `,(0,l.jsx)(`code`,{children:t}),`. Relations between the documents go with them.`]}),(0,l.jsx)(`div`,{className:`paths-nav-switch`,role:`group`,"aria-label":`Copy or move`,children:[`copy`,`move`].map(e=>(0,l.jsx)(`button`,{type:`button`,"aria-pressed":u===e,className:u===e?`active`:void 0,disabled:E||!!w,onClick:()=>d(e),children:e},e))}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`To scope`}),(0,l.jsxs)(`select`,{value:f,disabled:E||!!w,onChange:e=>p(e.target.value),children:[(0,l.jsx)(`option`,{value:`user`,children:`user`}),(0,l.jsx)(`option`,{value:`agent`,children:`agent`}),(0,l.jsx)(`option`,{value:`tenant`,children:`tenant`})]})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`New path`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:m,disabled:E||!!w,onChange:e=>h(e.target.value)})]}),u===`move`&&(0,l.jsx)(`label`,{className:`path-field`,children:(0,l.jsxs)(`span`,{children:[(0,l.jsx)(`input`,{type:`checkbox`,checked:g,disabled:E||!!w,onChange:e=>_(e.target.checked)}),` `,`Drop relations to documents outside the set`]})}),j&&(0,l.jsx)(`div`,{className:`modal-err`,children:j}),I&&(0,l.jsx)(`div`,{className:`modal-context`,"aria-live":`polite`,children:S(u,I).map((e,t)=>e.startsWith(` `)?(0,l.jsx)(`div`,{children:(0,l.jsx)(`code`,{children:e.trim()})},t):(0,l.jsx)(`div`,{children:e},t))}),O&&(0,l.jsx)(`div`,{className:`modal-err`,children:O})]})})}var Ue=6;function We({children:e,defaultLeftWidth:t=380,minLeftWidth:n=180,minRightWidth:r=240,storageKey:i,className:a,hideRight:o=!1,hideLeft:s=!1,leftRail:u,onHandleDoubleClick:d}){let f=()=>{if(i){let e=localStorage.getItem(i),t=e?parseInt(e,10):NaN;if(Number.isFinite(t)&&t>=n)return t}return t},[p,m]=(0,c.useState)(f),[h,g]=(0,c.useState)(i);h!==i&&(g(i),m(f()));let _=(0,c.useRef)(null),[v,y]=(0,c.useState)(!1);(0,c.useEffect)(()=>{i&&!v&&h===i&&localStorage.setItem(i,String(Math.round(p)))},[i,h,p,v]);let b=(0,c.useCallback)(e=>{e.preventDefault(),y(!0),e.target.setPointerCapture(e.pointerId)},[]),x=(0,c.useCallback)(e=>{if(!v||!_.current)return;let t=_.current.getBoundingClientRect(),i=e.clientX-t.left,a=t.width-r-Ue;m(Math.max(n,Math.min(i,a)))},[v,n,r]),S=(0,c.useCallback)(e=>{y(!1);try{e.target.releasePointerCapture(e.pointerId)}catch{}},[]);return(0,l.jsxs)(`div`,{ref:_,className:`splitter ${a??``} ${v?`dragging`:``}`,style:{gridTemplateColumns:o?`1fr 0 0`:s?u?`auto 1fr`:`1fr`:`min(${p}px, calc(100% - ${r+Ue}px)) ${Ue}px 1fr`},children:[(0,l.jsx)(`div`,{className:`splitter-pane splitter-left`,hidden:s&&!o,children:e[0]}),s&&!o&&u,(0,l.jsx)(`div`,{hidden:o||s,className:`splitter-handle`,role:`separator`,"aria-orientation":`vertical`,"aria-valuenow":Math.round(p),onPointerDown:b,onPointerMove:x,onPointerUp:S,onPointerCancel:S,onDoubleClick:d}),(0,l.jsx)(`div`,{className:`splitter-pane splitter-right`,hidden:o,children:e[1]})]})}var Ge=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`];function Ke(e){return Ge.includes(e)}function qe(e){return new Promise((t,n)=>{if(!Ke(e.type)){n(Error(`unsupported image type "${e.type||`unknown`}" (png, jpeg, gif, webp only)`));return}let r=new FileReader;r.onerror=()=>n(r.error??Error(`failed to read file`)),r.onload=()=>{let i=String(r.result??``),a=i.indexOf(`,`);a<0?n(Error(`could not decode image data`)):t({mediaType:e.type,data:i.slice(a+1)})},r.readAsDataURL(e)})}function Je(e){if(!e)return null;for(let t=0;t<e.length;t++){let n=e[t];if(n.kind===`file`&&Ke(n.type)){let e=n.getAsFile();if(e)return e}}return null}var Ye=20;async function Xe(e,t,n,r,i=20){let a=[],o;for(let s=0;s<i;s++){let i=await e.documentGetEdges(t,n,r,o?{after:o}:void 0);if(o&&i.next_cursor===o)return{edges:a,incomplete:!0};if(a.push(...i.edges??[]),!i.truncated)return{edges:a,incomplete:!1};if(!i.next_cursor)return{edges:a,incomplete:!0};o=i.next_cursor}return{edges:a,incomplete:!0}}var Ze=new Set([`manual`,`wikilink`]),Qe=280;function $e(e){return e.status&&e.status!==`asserted`?e.status:void 0}function K(e){return e.method&&!Ze.has(e.method)?e.method:void 0}function et(e){return e.status===`proposed`&&!!e.id}function tt(e){return new Date(Math.floor(e/1e6)).toISOString().slice(0,10)}function nt(e){let t=e.valid_at==null?void 0:tt(e.valid_at),n=e.invalid_at==null?void 0:tt(e.invalid_at);if(t&&n)return`valid ${t} → ${n}`;if(t)return`valid from ${t}`;if(n)return`valid until ${n}`}function rt(e){if(e.judged_at==null)return;let t=`judged by ${e.judged_by||`a judge`} on ${tt(e.judged_at)}`;return e.judge_reason?`${t}: ${e.judge_reason}`:t}function it(e,t=3){let n=(e.evidence??[]).slice(0,t),r=Math.max(e.evidence_count??0,e.evidence?.length??0);return{rows:n,more:Math.max(0,r-n.length)}}function at(e,t=Qe){let n=e.replace(/\s+/g,` `).trim();return n.length>t?n.slice(0,t-1)+`…`:n}var ot=1e3,st=3,q=1e3;function ct(e){return!!e&&typeof e==`object`&&e.code===`queue_changed`}async function lt(e,t,n={}){let r={action:t.action,...t.ids?{ids:t.ids}:{filter:t.filter??{}},...t.reason?{reason:t.reason}:{},...t.scope&&t.scope!==`tenant`?{scope:t.scope}:{},...t.scope===`user`&&t.scopeId?{scope_id:t.scopeId}:{}},i={rulingIds:[],ruled:0,failed:0,skipped:0,total:0,cancelled:!1,failures:[]},a=async()=>{let t=await e.rule({...r,dry_run:!0});return i.skipped=t.skipped,t},o=async(e,t)=>!n.confirm||await n.confirm(e,t)?(i.total=i.ruled+e.matched,!0):(i.cancelled=!0,!1),s;try{s=await a()}catch(e){return i.error=e,i}if(s.matched===0||!await o(s,`first`))return i;let c=0;for(let t=0;t<q&&s.to_rule!==0;t++){let t;try{t=await e.rule({...r,dry_run:!1,expect_count:s.matched})}catch(e){if(!ct(e)||c>=3)return i.error=e,i;c++;try{s=await a()}catch(e){return i.error=e,i}if(s.matched===0||!await o(s,`queue_changed`))return i;continue}t.ruling_id&&i.rulingIds.push(t.ruling_id),i.ruled+=t.ruled,i.failed+=t.failed;for(let e of t.items??[])e.error&&i.failures.push(e);if(n.onProgress?.({ruled:i.ruled,failed:i.failed,total:i.total,chunks:i.rulingIds.length}),t.ruled===0||t.matched<=t.selected)break;try{s=await a()}catch(e){return i.error=e,i}if(s.matched===0)break;if(s.matched>i.total-i.ruled&&!await o(s,`grew`))return i}return i}async function J(e,t){let n={reverted:0,changed:0,errors:[]};for(let r of[...t].reverse())try{let t=await e(r);n.reverted+=t.reverted,n.changed+=t.changed}catch(e){n.errors.push(e instanceof Error?e.message:String(e))}return n}function ut(e){return Math.max(1,Math.ceil(e/ot))}function Y(e){return e===`tenant`||e===`user`?e:void 0}function dt(e,t){return e.documentRuleStatements?Y(t):void 0}function ft(e,t){return e.filter(e=>et(e)&&!!e.id&&e.from_document_id===t)}function pt(e,t,n,r){return e?{proposals:t,scope:e,incomplete:n,onChanged:r}:void 0}function mt(e,t,n){return e.documentRuleStatements?lt({rule:n=>e.documentRuleStatements(n,t.browse)},{action:t.action,...t.ids&&t.ids.length>0?{ids:t.ids}:{filter:{from_document_id:t.documentId}},...t.reason?{reason:t.reason}:{},scope:t.scope,...t.scope===`user`&&t.browse?.scopeId?{scopeId:t.browse.scopeId}:{}},n):Promise.reject(Error(`this data layer cannot rule in bulk`))}function ht(e,t){let n=e=>e.toLocaleString(`en-US`),r=[`${e===`accept`?`Accepted`:`Rejected`} ${n(t.ruled)} statement${t.ruled===1?``:`s`}`];return t.failed>0&&r.push(`${n(t.failed)} did not take the ruling`),t.skipped>0&&r.push(`${n(t.skipped)} skipped: not yours to rule`),r.join(`; `)+`.`}function gt(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function _t(e){if(!e||typeof e!=`object`)return;let t=e.classification;if(!t||typeof t!=`object`||Array.isArray(t))return;let n=t,r={};return typeof n.by==`string`&&(r.by=n.by),typeof n.at==`number`&&(r.at=n.at),typeof n.applied_type==`string`&&n.applied_type&&(r.applied_type=n.applied_type),typeof n.proposed_type==`string`&&n.proposed_type&&(r.proposed_type=n.proposed_type),n.proposed_fields&&typeof n.proposed_fields==`object`&&!Array.isArray(n.proposed_fields)&&(r.proposed_fields=n.proposed_fields),gt(n.proposed_tags)&&(r.proposed_tags=n.proposed_tags),gt(n.statements)&&(r.statements=n.statements),r}function vt(e){let t=_t(e);if(!t)return;let n=t.proposed_tags??[],r=t.statements?.length??0;if(t.proposed_type||n.length!==0||r!==0)return{proposedType:t.proposed_type,proposedTags:n,statementCount:r}}function yt(e){let t=e.write===`report`;switch(e.result){case`classified`:return t?`would be classified`:`classified`;case`proposed`:return t?`would be proposed for review`:`proposed — waits for review`;case`kept`:return`kept — the type was set by hand`;case`unclassified`:return`unclassified — nothing decided`;default:return String(e.result)}}function X(e){if(!e.class)return;if(e.result===`kept`)return`not applied`;let t=e.write===`report`;return e.live?t?`would be applied`:`applied`:t?`would be proposed`:`proposed`}function bt(e){return e.write===`report`?e.result===`classified`||e.result===`proposed`||(e.concepts?.length??0)>0||(e.issued_by?.length??0)>0:!1}function xt(e){return e==null||!Number.isFinite(e)?``:`${Math.round(e*100)}%`}var St={rules:`Rules`,vote:`Neighbourhood vote`,model:`Model`};function Ct(e){return St[e]??e}function wt(e){let t=[];e.quote&&t.push(e.from?`“${e.quote}” (${e.from})`:`“${e.quote}”`),e.votes!=null&&t.push(`${e.votes} vote${e.votes===1?``:`s`}`);let n=xt(e.share);return n&&t.push(n),t.join(` · `)}function Tt(e){return{label:Ct(e.step),...e.chosen?{chosen:e.chosen}:{},...e.method?{method:e.method}:{},...e.neighbours?{neighbours:e.neighbours}:{},...e.reason?{reason:e.reason}:{},candidates:(e.candidates??[]).map(e=>({class:e.class,detail:wt(e)}))}}function Et(e){let t=[];e.type&&t.push(`type ${e.type}`);let n=e.accepted_statements?.length??0;n>0&&t.push(`${n} statement${n===1?``:`s`}`),e.tags&&e.tags.length>0&&t.push(`tags ${e.tags.join(`, `)}`);let r=[];e.type_pending&&r.push(`The proposed class stays pending: another document already holds its identity.`),e.skipped_type&&r.push(`Class ${e.skipped_type} was not applied: it is not a declared document class.`);let i=e.skipped_statements?.length??0;return i>0&&r.push(`${i} statement${i===1?` was`:`s were`} skipped (already ruled on, or not this document's proposal).`),e.skipped_tags&&e.skipped_tags.length>0&&r.push(`Tags not applied (not concepts of the ontology): ${e.skipped_tags.join(`, `)}.`),r.push(...e.warnings??[]),{applied:t.length>0?`Accepted ${t.join(`, `)}.`:`Nothing was accepted.`,notices:r}}function Dt(e){let t=e instanceof Error?e.message:String(e);return t.includes(`nothing_pending`)?`Nothing is pending for this document — it may already have been accepted.`:t}async function Ot(e){try{return typeof navigator>`u`||!navigator.clipboard?!1:(await navigator.clipboard.writeText(e),!0)}catch{return!1}}var kt=[{kind:`pdf`,label:`PDF`,title:`Render the whole document as a PDF file`,rendered:!0},{kind:`docx`,label:`Word (.docx)`,title:`Render the whole document as a Word document`,rendered:!0},{kind:`odt`,label:`OpenDocument (.odt)`,title:`Render the whole document as an OpenDocument text file`,rendered:!0},{kind:`epub`,label:`E-book (.epub)`,title:`Render the whole document as an EPUB e-book`,rendered:!0},{kind:`html`,label:`HTML`,title:`Render the whole document as a web page`,rendered:!0},{kind:`md`,label:`Markdown (.md)`,title:`Download the whole document as Markdown, with the metadata comments that let it be imported back`,rendered:!1},{kind:`canvas`,label:`Canvas (.canvas)`,title:`Download the whole document as a node/edge canvas graph (.canvas)`,rendered:!1}];function At(e){return kt.filter(t=>!t.rendered||!!e.documentExportFile)}async function Z(e,t,n,r,i,a,o=z){if(t===`md`){let t=await e.documentExportMd(n,r,!0,i);o(new Blob([t.markdown],{type:`text/markdown`}),re(t.title)+`.md`);return}if(t===`canvas`){let t=await e.documentExportCanvas(n,r,i);o(new Blob([JSON.stringify(t.canvas,null,2)],{type:`application/json`}),re(a)+`.canvas`);return}if(!e.documentExportFile)throw Error(`this connection cannot download rendered files`);let s=t,c=await e.documentExportFile(n,r,s,i);o(c.blob,c.filename||re(a)+`.`+s)}var jt={"doc.rfc.draft":`#c99a3a`,"doc.rfc.review":`#6a7bd6`,"doc.rfc.confirmed":`#3a9ad6`,"doc.rfc.done":`#3aa06a`,"doc.plan.draft":`#c99a3a`,"doc.plan.review":`#6a7bd6`,"doc.plan.confirmed":`#3a9ad6`,"doc.plan.done":`#3aa06a`,"doc.document.done":`#3aa06a`,"doc.research.done":`#8a6ad6`,"doc.publication.draft":`#c99a3a`,"doc.*.draft":`#c99a3a`,"doc.*.review":`#6a7bd6`,"doc.*.confirmed":`#3a9ad6`,"doc.*.done":`#3aa06a`,"chunk.draft":`#c99a3a`,"chunk.review":`#6a7bd6`,"chunk.confirmed":`#3a9ad6`,"chunk.done":`#3aa06a`,"chunk.backlog":`#8a8f98`,"chunk.implementation":`#d1863a`,"chunk.merged":`#3aa06a`},Mt=.16;function Nt(e){return e&&Object.keys(e).length>0?e:jt}function Pt(e,t){if(Object.prototype.hasOwnProperty.call(e,t)&&e[t])return e[t];let n=t.toLowerCase();for(let t of Object.keys(e))if(t.toLowerCase()===n&&e[t])return e[t]}function Ft(e,t,n){let r=e??``,i=t??``;return(r&&i?Pt(n,`doc.${r}.${i}`):void 0)??(r?Pt(n,`doc.${r}`):void 0)??(i?Pt(n,`doc.*.${i}`):void 0)??Pt(n,`doc.*`)}function It(e,t){let n=e??``;return n?Pt(t,`chunk.${n}`):void 0}function Lt(e){let t=String(e[`chunk.inherit`]??``).trim().toLowerCase();return t!==`false`&&t!==`none`&&t!==`off`&&t!==`0`}function Rt(e,t=Mt){let n=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e.trim());if(!n)return;let r=n[1];return r.length===3&&(r=r[0]+r[0]+r[1]+r[1]+r[2]+r[2]),`rgba(${parseInt(r.slice(0,2),16)}, ${parseInt(r.slice(2,4),16)}, ${parseInt(r.slice(4,6),16)}, ${t})`}function zt(e){if(!e)return;let t=Rt(e);if(t)return{background:t,borderLeft:`3px solid ${e}`}}function Bt(e){if(!e)return;let t=Rt(e,Mt/2);return t?{background:t}:void 0}function Vt(e){let t=Ut(e);if(t)return t.wash?Bt(t.color):zt(t.color)}function Ht(e){return e&&Rt(e)?e:void 0}function Ut(e){let{status:t,isRoot:n,documentColor:r,scheme:i}=e;if(!i)return;if(n){let e=Ht(r)??Ht(It(t,i));return e?{color:e,wash:!1}:void 0}let a=Ht(It(t,i));if(a)return{color:a,wash:!1};let o=Lt(i)?Ht(r):void 0;return o?{color:o,wash:!0}:void 0}var Wt=.3,Q=.22;function Gt(e,t=!1){if(!e)return;let n=Rt(e,t?Q:Wt);return n?{"--etree-tint":n}:void 0}function Kt(e){let t=Ut(e);return t?Gt(t.color,t.wash):void 0}function qt(e,t){if(e)return(t?Ht(It(e,t)):void 0)??Ht(It(e,jt))}function Jt({kind:e}){return(0,l.jsx)(`svg`,{className:`etree-svg etree-svg-${e}`,width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,focusable:`false`,children:Yt[e]})}var Yt={folder:(0,l.jsx)(`path`,{d:`M1.75 4.25v8a1 1 0 0 0 1 1h10.5a1 1 0 0 0 1-1v-6.5a1 1 0 0 0-1-1H8L6.5 3.25H2.75a1 1 0 0 0-1 1z`}),document:(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`path`,{d:`M9.25 1.75h-5a1 1 0 0 0-1 1v10.5a1 1 0 0 0 1 1h7.5a1 1 0 0 0 1-1v-8.25z`}),(0,l.jsx)(`path`,{d:`M9.25 1.75v3.5h3.5M5.5 8.5h5M5.5 11h3.5`})]}),volume:(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`rect`,{x:`1.75`,y:`4.25`,width:`12.5`,height:`7.5`,rx:`1`}),(0,l.jsx)(`path`,{d:`M4.5 8h.01M7 8h4.5`})]}),memory:(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`ellipse`,{cx:`8`,cy:`3.75`,rx:`5.25`,ry:`2`}),(0,l.jsx)(`path`,{d:`M2.75 3.75v8.5c0 1.1 2.35 2 5.25 2s5.25-.9 5.25-2v-8.5M2.75 8c0 1.1 2.35 2 5.25 2s5.25-.9 5.25-2`})]}),annotation:(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`path`,{d:`M9.25 1.75h-5a1 1 0 0 0-1 1v10.5a1 1 0 0 0 1 1h7.5a1 1 0 0 0 1-1v-8.25z`}),(0,l.jsx)(`path`,{d:`M9.25 1.75v3.5h3.5M5.5 8.5l1.5 1.5 3-3`})]}),image:(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`rect`,{x:`1.75`,y:`2.75`,width:`12.5`,height:`10.5`,rx:`1`}),(0,l.jsx)(`circle`,{cx:`5.5`,cy:`6.25`,r:`1.25`}),(0,l.jsx)(`path`,{d:`M14.25 10.5l-3.5-3.5-7.5 6.25`})]}),diagram:(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`rect`,{x:`1.75`,y:`1.75`,width:`4.5`,height:`3.5`,rx:`0.5`}),(0,l.jsx)(`rect`,{x:`9.75`,y:`10.75`,width:`4.5`,height:`3.5`,rx:`0.5`}),(0,l.jsx)(`path`,{d:`M4 5.25v4.5a1 1 0 0 0 1 1h4.75`})]}),link:(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`path`,{d:`M6.75 9.25a2.75 2.75 0 0 0 3.9 0l2-2a2.75 2.75 0 0 0-3.9-3.9l-.5.5`}),(0,l.jsx)(`path`,{d:`M9.25 6.75a2.75 2.75 0 0 0-3.9 0l-2 2a2.75 2.75 0 0 0 3.9 3.9l.5-.5`})]})};function Xt({type:e,status:t,statusColor:n,extra:r,bare:i}){return!e&&!t&&!r?null:(0,l.jsxs)(`span`,{className:`etree-marks`,children:[r,e&&(0,l.jsx)(`span`,{className:`etree-mark etree-mark-type`,title:i?void 0:`type: ${e}`,children:e}),t&&(0,l.jsx)(`span`,{className:`etree-mark etree-mark-status`,role:`img`,title:i?void 0:`status: ${t}`,"aria-label":`status ${t}`,style:n?{"--etree-dot":n}:void 0})]})}function Zt({depth:e,expandable:t,expanded:n,onToggle:r,selected:i,onSelect:a,tabbable:o,icon:s,name:c,title:u,marks:d,count:f,card:p,rowClassName:m,style:h,className:g,children:_}){let v=t&&n,y=Te(p);return(0,l.jsxs)(`li`,{className:`etree-node${g?` ${g}`:``}${i?` selected`:``}`,role:`treeitem`,"aria-level":e+1,"aria-selected":i,"aria-expanded":t?v:void 0,tabIndex:o?0:-1,...y.focus,children:[(0,l.jsxs)(`div`,{ref:y.anchorRef,className:`etree-row${m?` ${m}`:``}`,style:{...h,"--etree-depth":e},title:u,onClick:a,onMouseEnter:y.hover.onMouseEnter,onMouseLeave:y.hover.onMouseLeave,children:[(0,l.jsx)(`button`,{type:`button`,className:`etree-caret`,tabIndex:-1,"aria-label":v?`collapse`:`expand`,"aria-expanded":t?v:void 0,disabled:!t,onClick:e=>{e.stopPropagation(),t&&r()},children:t&&(0,l.jsx)(`svg`,{width:`10`,height:`10`,viewBox:`0 0 10 10`,"aria-hidden":`true`,focusable:`false`,children:(0,l.jsx)(`path`,{d:`M3.5 2l3 3-3 3`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,l.jsx)(`span`,{className:`etree-icon`,children:s}),(0,l.jsx)(`span`,{className:`etree-name`,children:c}),d,f]}),y.card,v&&_!==void 0&&(0,l.jsx)(`ul`,{className:`etree-children`,role:`group`,children:_})]})}function Qt(e){let t=e.target;if(t.getAttribute(`role`)!==`treeitem`||!e.currentTarget.contains(t))return;let n=Array.from(e.currentTarget.querySelectorAll(`[role="treeitem"]`)),r=n.indexOf(t),i=t.querySelector(`:scope > .etree-row`),a=i?.querySelector(`:scope > .etree-caret`),o=t.getAttribute(`aria-expanded`),s=e=>e?.focus();switch(e.key){case`ArrowDown`:s(n[r+1]);break;case`ArrowUp`:s(n[r-1]);break;case`Home`:s(n[0]);break;case`End`:s(n[n.length-1]);break;case`ArrowRight`:if(o===`false`)a?.click();else if(o===`true`)s(t.querySelector(`:scope > [role="group"] > [role="treeitem"]`));else return;break;case`ArrowLeft`:o===`true`?a?.click():s(t.parentElement?.closest(`[role="treeitem"]`));break;case`Enter`:case` `:i?.click();break;default:{if(e.key.length!==1||e.ctrlKey||e.metaKey||e.altKey)return;let t=e.key.toLowerCase();s([...n.slice(r+1),...n.slice(0,r+1)].find(e=>e.querySelector(`:scope > .etree-row > .etree-name`)?.textContent?.trim().toLowerCase().startsWith(t)))}}e.preventDefault(),e.stopPropagation()}function $t(e){let t=new Map;e.forEach(e=>t.set(e.id,{row:e,children:[]}));let n=[];e.forEach(e=>{let r=t.get(e.id);e.parent_id&&t.has(e.parent_id)?t.get(e.parent_id).children.push(r):n.push(r)});let r=e=>{e.sort((e,t)=>e.row.position-t.row.position),e.forEach(e=>r(e.children))};return r(n),n}function en(e){if(e===`image`)return`image`;if(e===`mermaid`)return`diagram`}function tn({tree:e,selectedId:t,onSelect:n,colorEnabled:r,scheme:i,documentColor:a,linkedIds:o,documentType:s,documentStatus:u}){let[d,f]=(0,c.useState)(()=>new Map),p=(0,c.useCallback)(e=>{f(t=>{let n=new Map(t);return n.set(e,t.get(e)===!1),n})},[]);(0,c.useEffect)(()=>{if(!t)return;let n=rn(e,t);n.length!==0&&f(e=>{let t=!1,r=new Map(e);for(let e of n)r.get(e)===!1&&(r.set(e,!0),t=!0);return t?r:e})},[e,t]);let m=r?Nt(i):null,h=(0,c.useMemo)(()=>nn(e,e=>e.summary!==void 0),[e]);if(e.length===0)return(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`No chunks.`})});let g=t&&(e.some(e=>e.row.id===t)||(()=>{let n=rn(e,t);return n.length>0&&n.every(e=>d.get(e)!==!1)})())?t:e[0].row.id;return(0,l.jsx)(`ul`,{className:`etree chunk-tree`,role:`tree`,"aria-label":`Chunk outline`,onKeyDown:Qt,children:e.map(e=>(0,l.jsx)(an,{node:e,depth:0,tabStop:g,expanded:d,toggle:p,selectedId:t,onSelect:n,tintScheme:m,documentColor:a,isRoot:!0,linkedIds:o,documentType:s,documentStatus:u,briefsListed:h},e.row.id))})}function nn(e,t){return e.some(e=>t(e.row)||nn(e.children,t))}function rn(e,t){let n=[],r=(e,i)=>{for(let a of e){if(a.row.id===t)return n.push(...i),!0;if(r(a.children,[...i,a.row.id]))return!0}return!1};return r(e,[]),n}function an({node:e,expanded:t,toggle:n,selectedId:r,onSelect:i,tintScheme:a,documentColor:o,isRoot:s=!1,linkedIds:u,documentType:d,documentStatus:f,depth:p,tabStop:m,briefsListed:h}){let g=e.children.length>0,_=t.get(e.row.id)!==!1,v=r===e.row.id,y=s?`document`:en(e.row.type),b=e.row.type===d?void 0:e.row.type,x=e.row.status===f?void 0:e.row.status,S=(0,c.useContext)(Ce);return(0,l.jsx)(Zt,{className:`chunk-node`,depth:p,expandable:g,expanded:_,onToggle:()=>n(e.row.id),selected:v,onSelect:()=>i(e),tabbable:e.row.id===m,icon:y?(0,l.jsx)(Jt,{kind:y}):void 0,name:e.row.title||`(untitled)`,card:Oe(e.row,S,h),marks:(0,l.jsx)(Xt,{bare:!0,type:b,status:x,statusColor:qt(x,a??void 0),extra:u?.has(e.row.id)?(0,l.jsx)(`span`,{className:`etree-mark etree-mark-link`,role:`img`,"aria-label":`linked`,children:(0,l.jsx)(Jt,{kind:`link`})}):void 0}),style:Kt({status:e.row.status,isRoot:s,documentColor:o,scheme:a}),children:g?e.children.map(e=>(0,l.jsx)(an,{node:e,expanded:t,toggle:n,selectedId:r,onSelect:i,tintScheme:a,documentColor:o,linkedIds:u,documentType:d,documentStatus:f,depth:p+1,tabStop:m,briefsListed:h},e.row.id)):void 0})}function on({record:e}){return e?(0,l.jsxs)(`p`,{className:`annotation-brief`,title:`Annotation brief`,children:[e.brief,e.stale&&(0,l.jsx)(sn,{})]}):null}function sn(){return(0,l.jsx)(`span`,{className:`annotation-badge annotation-stale`,title:`The text has changed since this annotation was written`,children:`stale`})}function cn({records:e,newLevel:t,onSave:n,onRegenerate:r,defaultOpen:i}){let[a,o]=(0,c.useState)(!!i),[s,u]=(0,c.useState)(null),[d,f]=(0,c.useState)(null),p=d!==null,[m,h]=(0,c.useState)(null);if(e.length===0&&!n&&!r)return null;let g=async e=>{if(r){f(e),h(null);try{await r(e)}catch(e){h(e instanceof Error?e.message:String(e))}finally{f(null)}}},_=e.some(e=>e.stale),v=e.some(e=>e.manual);return(0,l.jsxs)(`details`,{className:`annotation-panel`,open:a||s!==null,onToggle:e=>o(e.currentTarget.open),children:[(0,l.jsxs)(`summary`,{children:[(0,l.jsx)(`span`,{className:`annotation-title`,children:`Annotation`}),e.length===0?(0,l.jsx)(`span`,{className:`annotation-none`,children:`none`}):e.map(e=>(0,l.jsx)(`span`,{className:`annotation-badge`,children:e.level},e.level)),v&&(0,l.jsx)(`span`,{className:`annotation-badge annotation-manual`,title:`Written or edited by a person`,children:`manual`}),_&&(0,l.jsx)(sn,{})]}),e.map(t=>s===t.level?(0,l.jsx)(ln,{level:t.level,brief:t.brief,abstract:t.abstract,onCancel:()=>u(null),onSave:async(e,r)=>{await n(t.level,e,r),u(null)}},t.level):(0,l.jsxs)(`div`,{className:`annotation-record`,children:[e.length>1&&(0,l.jsx)(`p`,{className:`annotation-brief`,children:t.brief}),t.abstract&&(0,l.jsx)(`p`,{className:`annotation-abstract`,children:t.abstract}),(0,l.jsxs)(`dl`,{className:`annotation-meta`,children:[(0,l.jsx)(`dt`,{children:`level`}),(0,l.jsx)(`dd`,{children:t.level}),t.language&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`language`}),(0,l.jsx)(`dd`,{children:t.language})]}),t.model&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`model`}),(0,l.jsx)(`dd`,{children:t.model})]}),t.written_at&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`written`}),(0,l.jsx)(`dd`,{title:t.written_at,children:I(t.written_at)})]}),t.written_by&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`by`}),(0,l.jsx)(`dd`,{children:F(t.written_by)})]}),t.manual&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`source`}),(0,l.jsx)(`dd`,{children:`written by hand`})]}),t.stale&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`state`}),(0,l.jsx)(`dd`,{children:`stale: the text changed after this was written`})]})]}),(n||r)&&(0,l.jsxs)(`div`,{className:`annotation-actions`,children:[n&&(0,l.jsx)(`button`,{type:`button`,disabled:p,onClick:()=>u(t.level),children:`edit`}),r&&!t.manual&&(0,l.jsx)(`button`,{type:`button`,disabled:p,onClick:()=>void g(t.level),title:`Ask for it to be written again from the current text`,children:d===t.level?`regenerating…`:`regenerate`})]})]},t.level)),e.length===0&&(s!==null&&n?(0,l.jsx)(ln,{level:s,brief:``,abstract:``,onCancel:()=>u(null),onSave:async(e,t)=>{await n(s,e,t),u(null)}}):(0,l.jsxs)(`div`,{className:`annotation-record`,children:[(0,l.jsx)(`p`,{className:`annotation-empty`,children:`No annotation has been written for this yet.`}),(0,l.jsxs)(`div`,{className:`annotation-actions`,children:[n&&(0,l.jsx)(`button`,{type:`button`,disabled:p,onClick:()=>u(t),children:`write`}),r&&(0,l.jsx)(`button`,{type:`button`,disabled:p,onClick:()=>void g(t),children:p?`generating…`:`generate`})]})]})),m&&(0,l.jsx)(`p`,{className:`annotation-err`,children:m})]})}function ln({level:e,brief:t,abstract:n,onSave:r,onCancel:i}){let[a,o]=(0,c.useState)(t),[s,u]=(0,c.useState)(n),[d,f]=(0,c.useState)(!1),[p,m]=(0,c.useState)(null),h=N(a,s),g=async()=>{if(h)m(h);else{f(!0),m(null);try{await r(a,s)}catch(e){m(e instanceof Error?e.message:String(e))}finally{f(!1)}}};return(0,l.jsxs)(`form`,{className:`annotation-editor`,onSubmit:e=>{e.preventDefault(),g()},children:[(0,l.jsxs)(`label`,{children:[(0,l.jsxs)(`span`,{children:[`Brief (`,e,`) · `,te(a),`/`,240]}),(0,l.jsx)(`input`,{value:a,onChange:e=>o(e.target.value),placeholder:`One sentence`})]}),(0,l.jsxs)(`label`,{children:[(0,l.jsxs)(`span`,{children:[`Abstract · `,te(s),`/`,O]}),(0,l.jsx)(`textarea`,{rows:6,value:s,onChange:e=>u(e.target.value),placeholder:`One paragraph`})]}),(0,l.jsx)(`p`,{className:`annotation-hint`,children:`Saved as written by hand: the background walk will not replace it.`}),p&&(0,l.jsx)(`p`,{className:`annotation-err`,children:p}),(0,l.jsxs)(`div`,{className:`annotation-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:i,disabled:d,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:`primary`,disabled:d||!!h,children:d?`saving…`:`save`})]})]})}var un=0;function dn(e){let t=e?.closest(`g.node`);return t?/flowchart-(.+)-\d+$/.exec(t.id)?.[1]:void 0}function fn({code:e,onNodeClick:t}){let n=(0,c.useRef)(null),[r,i]=(0,c.useState)({});return(0,c.useEffect)(()=>{let t=!1;return(async()=>{try{let r=(await import(`mermaid`)).default,a=n.current?.closest(`[data-theme]`)?.getAttribute(`data-theme`),o=!a||a===`dark`;r.initialize({startOnLoad:!1,theme:o?`dark`:`default`,securityLevel:`strict`});let{svg:s}=await r.render(`lc-mmd-${un++}`,e);t||i({svg:s})}catch{t||i({err:!0})}})(),()=>{t=!0}},[e]),r.err?(0,l.jsx)(`pre`,{className:`md-pre md-mermaid-error`,title:`diagram failed to render`,children:(0,l.jsx)(`code`,{children:e})}):r.svg?(0,l.jsx)(`div`,{ref:n,className:t?`md-mermaid md-mermaid-nav`:`md-mermaid`,onClick:t&&(e=>{let n=dn(e.target);n&&t(n)}),dangerouslySetInnerHTML:{__html:r.svg}}):(0,l.jsx)(`div`,{ref:n,className:`md-mermaid md-mermaid-loading`,children:`rendering diagram…`})}var pn=(0,c.lazy)(()=>import(`@loomcycle/code-editor`).then(e=>({default:e.CodeEditor}))),mn=null;function hn(){return mn??=import(`@loomcycle/code-editor`).then(e=>e.parseJson),mn.catch(()=>{mn=null}),mn}function gn({chunk:e,scope:t,browse:n,onClose:r,onSaved:i}){let a=ue(),[o,s]=(0,c.useState)(e.title),[u,d]=(0,c.useState)(e.type??``),[f,p]=(0,c.useState)(e.status??``),[m,h]=(0,c.useState)(e.body??``),[g,_]=(0,c.useState)(e.fields?JSON.stringify(e.fields,null,2):``),[v,y]=(0,c.useState)((e.tags??[]).join(`, `)),[b,x]=(0,c.useState)(!1),[S,C]=(0,c.useState)(null),[w,T]=(0,c.useState)(!1),E=u===`mermaid`,D=u===`image`||!!e.asset,O=E||D?`text`:`markdown`,[k,ee]=(0,c.useState)(m);(0,c.useEffect)(()=>{if(!E)return;let e=setTimeout(()=>ee(m),400);return()=>clearTimeout(e)},[m,E]);let[A,j]=(0,c.useState)(null);(0,c.useEffect)(()=>{let e=!1;return hn().then(t=>!e&&j(()=>t)).catch(()=>{}),()=>{e=!0}},[]);let M=(0,c.useMemo)(()=>{if(g.trim()===``)return null;try{return JSON.parse(g),null}catch(e){let t=A?.(g);return t&&!t.ok?{from:t.error.offset,to:t.error.to,severity:`error`,message:t.error.message}:{from:0,to:0,severity:`error`,message:e instanceof Error?e.message:String(e)}}},[g,A]),te=(0,c.useMemo)(()=>M?[M]:[],[M]),N=async o=>{C(null),x(!0);try{let{mediaType:s,data:c}=await qe(o);i(await a.documentSetAsset(e.id,s,c,o.name,t,n)),r()}catch(e){C(e instanceof Error?e.message:String(e)),x(!1)}},P=E?`Mermaid source`:D?`Caption (optional)`:`Body (Markdown)`;return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:r,children:(0,l.jsxs)(`form`,{className:`modal chunk-editor`,onClick:e=>e.stopPropagation(),onSubmit:async s=>{if(s.preventDefault(),C(null),T(!1),M){C(`fields must be valid JSON: ${M.message}`);return}let c={body:m,title:o,type:u,status:f,tags:v.split(`,`).map(e=>e.trim()).filter(e=>e!==``)};g.trim()!==``&&(c.fields=JSON.parse(g)),x(!0);try{i(await a.documentUpdateChunk(e.id,e.revision,c,t,n)),r()}catch(e){let t=e instanceof Error?e.message:String(e);C(t),T(/revision conflict/i.test(t)),x(!1)}},children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsx)(`h3`,{children:`Edit chunk`}),(0,l.jsxs)(`div`,{className:`modal-buttons modal-buttons-top`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:r,disabled:b,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:`primary`,disabled:b||!!M,children:b?`saving…`:`save`})]})]}),S&&(0,l.jsxs)(`div`,{className:`modal-err`,children:[S,w&&` — reopen the chunk to load the latest, then reapply your edit.`]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Title`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:o,onChange:e=>s(e.target.value)})]}),(0,l.jsxs)(`div`,{className:`chunk-editor-row`,children:[(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Type`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:u,placeholder:`(none)`,onChange:e=>d(e.target.value)})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Status`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:f,placeholder:`(none)`,onChange:e=>p(e.target.value)})]}),(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Tags`}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:v,placeholder:`area/sub, priority/high`,title:`Comma-separated; nest with a slash: area/sub, priority/high`,onChange:e=>y(e.target.value)})]})]}),D&&(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Replace image`}),(0,l.jsx)(`input`,{type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,disabled:b,onChange:e=>{let t=e.target.files?.[0];t&&N(t)}})]}),(0,l.jsxs)(`div`,{className:`chunk-editor-main${E?` with-preview`:``}`,children:[(0,l.jsxs)(`div`,{className:`path-field chunk-editor-body`,children:[(0,l.jsx)(`span`,{children:P}),(0,l.jsx)(c.Suspense,{fallback:(0,l.jsx)(`textarea`,{className:`modal-textarea`,value:m,readOnly:!0,"aria-label":P}),children:(0,l.jsx)(pn,{value:m,onChange:h,language:O,wrap:!0,ariaLabel:P,className:`chunk-body-input`})})]}),E&&(0,l.jsxs)(`div`,{className:`path-field chunk-editor-preview`,children:[(0,l.jsx)(`span`,{children:`Preview`}),(0,l.jsx)(`div`,{className:`chunk-mermaid-preview`,children:k.trim()?(0,l.jsx)(fn,{code:k}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(enter Mermaid source)`})})]})]}),(0,l.jsxs)(`div`,{className:`path-field chunk-editor-fields`,children:[(0,l.jsx)(`span`,{children:`Fields (JSON, optional)`}),(0,l.jsx)(c.Suspense,{fallback:(0,l.jsx)(`textarea`,{className:`modal-textarea`,value:g,readOnly:!0,"aria-label":`Fields (JSON)`}),children:(0,l.jsx)(pn,{value:g,onChange:_,language:`json`,diagnostics:te,ariaLabel:`Fields (JSON)`,placeholder:`{}`,className:`chunk-fields-input`})}),M&&(0,l.jsx)(`span`,{className:`chunk-fields-error`,children:M.message})]})]})})}function _n({chunk:e,scope:t,browse:n,onClose:r,onSaved:i}){let a=ue(),[o,s]=(0,c.useState)(null),[u,d]=(0,c.useState)(e.type??``),[f,p]=(0,c.useState)(!1),[m,h]=(0,c.useState)(null),[g,_]=(0,c.useState)(null);(0,c.useEffect)(()=>{let e=!1;return a.documentEntityTypes?.(t,n).then(t=>{e||s(t)}).catch(t=>{e||h(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[a,t,n]);let v=o?y(o,e.type):[],b=u.toLowerCase()===(e.type??``).toLowerCase();return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:r,children:(0,l.jsxs)(`form`,{className:`modal`,onClick:e=>e.stopPropagation(),onSubmit:async o=>{if(o.preventDefault(),!(b||f)){h(null),p(!0);try{let o=await a.documentUpdateChunk(e.id,e.revision,{type:u},t,n);if(i(o),o.not_announced){_(o.not_announced),p(!1);return}r()}catch(e){h(e instanceof Error?e.message:String(e)),p(!1)}}},children:[(0,l.jsx)(`h3`,{children:`Change type`}),(0,l.jsxs)(`p`,{className:`modal-context`,children:[`“`,e.title||`(untitled)`,`” is a subject (`,(0,l.jsx)(`code`,{children:e.entity?.natural_key}),`). Its key stays as it is; relations about it are re-checked against the new type.`]}),m&&(0,l.jsx)(`div`,{className:`modal-err`,children:m}),g?(0,l.jsxs)(`div`,{className:`modal-err`,children:[`The type was changed, but subscribers were not told: `,g]}):(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:`Type`}),o===null?(0,l.jsx)(`span`,{className:`doc-empty-body`,children:m?``:`loading types…`}):(0,l.jsx)(`select`,{className:`path-modal-input`,value:u,disabled:f,onChange:e=>d(e.target.value),children:v.map(e=>(0,l.jsx)(`option`,{value:e,children:e},e))})]}),(0,l.jsxs)(`div`,{className:`modal-buttons`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:r,disabled:f,children:g?`close`:`cancel`}),!g&&(0,l.jsx)(`button`,{type:`submit`,className:`primary`,disabled:f||b||o===null,children:f?`saving…`:`change type`})]})]})})}function vn({documentId:e,scope:t,browse:n,rootFields:r,requestKey:i,onClose:a,onChanged:o}){let s=ue(),[u,d]=(0,c.useState)(null),[f,p]=(0,c.useState)(!1),[m,h]=(0,c.useState)(null),[g,_]=(0,c.useState)(!1),[v,y]=(0,c.useState)(null),[b,x]=(0,c.useState)(null),S=(0,c.useMemo)(()=>s.documentAcceptClassification?vt(r):void 0,[s,r]);(0,c.useEffect)(()=>{if(i===0||!s.documentClassify)return;let r=!1;return p(!0),h(null),d(null),s.documentClassify(e,`report`,t,n).then(e=>!r&&d(e)).catch(e=>!r&&h(Dt(e))).finally(()=>!r&&p(!1)),()=>{r=!0}},[s,e,t,n,i]);let C=async()=>{if(s.documentClassify){p(!0),h(null);try{d(await s.documentClassify(e,`propose`,t,n)),o()}catch(e){h(Dt(e))}finally{p(!1)}}},w=async()=>{if(s.documentAcceptClassification){_(!0),y(null);try{x(await s.documentAcceptClassification(e,t,n)),o()}catch(e){y(Dt(e))}finally{_(!1)}}},T=i>0;if(!T&&!S&&!b&&!v)return null;let E=b?Et(b):void 0;return(0,l.jsxs)(`div`,{className:`doc-classify`,children:[S&&(0,l.jsxs)(`div`,{className:`doc-classify-pending`,children:[(0,l.jsx)(`span`,{className:`doc-classify-label`,children:`Pending classification`}),S.proposedType&&(0,l.jsxs)(`span`,{children:[`class `,(0,l.jsx)(`strong`,{children:S.proposedType})]}),S.proposedTags.length>0&&(0,l.jsxs)(`span`,{children:[`tags`,` `,S.proposedTags.map(e=>(0,l.jsx)(`span`,{className:`chunk-tag`,children:e},e))]}),S.statementCount>0&&(0,l.jsxs)(`span`,{children:[S.statementCount,` proposed statement`,S.statementCount===1?``:`s`]}),(0,l.jsx)(`button`,{type:`button`,disabled:g,onClick:()=>void w(),children:g?`Accepting…`:`Accept`})]}),v&&(0,l.jsxs)(`div`,{className:`doc-classify-err`,role:`alert`,children:[v,(0,l.jsx)(`button`,{type:`button`,className:`doc-classify-dismiss`,onClick:()=>y(null),"aria-label":`Dismiss`,children:`×`})]}),E&&(0,l.jsxs)(`div`,{className:`doc-classify-notice`,role:`status`,children:[(0,l.jsx)(`span`,{children:E.applied}),E.notices.map((e,t)=>(0,l.jsx)(`span`,{className:`doc-classify-warn`,children:e},t)),(0,l.jsx)(`button`,{type:`button`,className:`doc-classify-dismiss`,onClick:()=>x(null),"aria-label":`Dismiss`,children:`×`})]}),T&&(0,l.jsxs)(`div`,{className:`doc-classify-panel`,children:[(0,l.jsxs)(`div`,{className:`doc-classify-head`,children:[(0,l.jsx)(`h4`,{children:`Classify`}),u&&(0,l.jsx)(`span`,{className:`doc-classify-result ${u.result}`,children:yt(u)}),u?.write===`report`&&(0,l.jsx)(`span`,{className:`doc-classify-hint`,children:`report only — nothing written`}),(0,l.jsx)(`button`,{type:`button`,className:`doc-classify-dismiss`,onClick:a,"aria-label":`Close`,children:`×`})]}),!u&&!m&&(0,l.jsx)(`p`,{className:`doc-classify-hint`,children:`Classifying…`}),m&&(0,l.jsx)(`p`,{className:`doc-classify-err`,role:`alert`,children:m}),u&&(0,l.jsx)(yn,{answer:u}),u&&bt(u)&&(0,l.jsx)(`div`,{className:`doc-classify-actions`,children:(0,l.jsx)(`button`,{type:`button`,disabled:f,onClick:()=>void C(),title:`Apply a unique rule match to the document; file everything else for review`,children:f?`Applying…`:`Apply`})})]})]})}function yn({answer:e}){let t=X(e),n=Object.entries(e.fields??{}),r=e.issued_by??[],i=e.concepts??[],a=(e.steps??[]).map(Tt),o=e.statements?.length??0;return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`dl`,{className:`doc-classify-rows`,children:[e.class&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`class`}),(0,l.jsxs)(`dd`,{children:[(0,l.jsx)(`strong`,{children:e.class}),t&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` (`,t,`)`]})]})]}),e.work_key&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`work key`}),(0,l.jsx)(`dd`,{className:`doc-classify-mono`,children:e.work_key})]}),n.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`fields`}),(0,l.jsx)(`dd`,{className:`doc-classify-mono`,children:n.map(([e,t])=>`${e}=${typeof t==`string`?t:JSON.stringify(t)}`).join(` · `)})]}),r.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`issued by`}),(0,l.jsx)(`dd`,{children:r.map((e,t)=>(0,l.jsxs)(`span`,{className:`doc-classify-item`,title:e.quote,children:[e.instance,e.quote&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` “`,e.quote,`”`]})]},`${e.instance}-${t}`))})]}),i.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`concepts`}),(0,l.jsx)(`dd`,{children:i.map(e=>(0,l.jsxs)(`span`,{className:`doc-classify-item`,title:e.tag,children:[e.concept,(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` `,xt(e.share)]})]},e.tag))})]}),o>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`statements`}),(0,l.jsxs)(`dd`,{children:[o,` written`,e.statements.some(e=>e.status===`proposed`)&&(0,l.jsx)(`span`,{className:`doc-classify-hint`,children:` (proposed ones wait for review)`})]})]})]}),a.length>0&&(0,l.jsx)(`ol`,{className:`doc-classify-steps`,children:a.map((e,t)=>(0,l.jsxs)(`li`,{children:[(0,l.jsx)(`span`,{className:`doc-classify-step`,children:e.label}),e.method&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` [`,e.method,`]`]}),e.chosen?(0,l.jsxs)(l.Fragment,{children:[` → `,(0,l.jsx)(`strong`,{children:e.chosen})]}):(0,l.jsx)(`span`,{className:`doc-classify-hint`,children:` no choice`}),e.neighbours!=null&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` · `,e.neighbours,` neighbours`]}),e.reason&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` — `,e.reason]}),e.candidates.length>0&&(0,l.jsxs)(`details`,{className:`doc-classify-candidates`,children:[(0,l.jsxs)(`summary`,{children:[e.candidates.length,` candidate`,e.candidates.length===1?``:`s`]}),(0,l.jsx)(`ul`,{children:e.candidates.map((e,t)=>(0,l.jsxs)(`li`,{children:[(0,l.jsx)(`strong`,{children:e.class}),e.detail&&(0,l.jsxs)(`span`,{className:`doc-classify-hint`,children:[` `,e.detail]})]},`${e.class}-${t}`))})]})]},`${e.label}-${t}`))}),e.warnings&&e.warnings.length>0&&(0,l.jsx)(`ul`,{className:`doc-classify-warnings`,children:e.warnings.map((e,t)=>(0,l.jsx)(`li`,{className:`doc-classify-warn`,children:e},t))})]})}function bn(e){let t=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((e??``).trim());if(!t)return`#888888`;let n=t[1];return n.length===3&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]),`#`+n.toLowerCase()}function xn({documentId:e,rootChunkId:t,docType:n,docStatus:r,chunkStatuses:i,scope:a,browse:o,onClose:s,onSaved:u}){let d=ue(),[f,p]=(0,c.useState)(null),[m,h]=(0,c.useState)(!1),[g,_]=(0,c.useState)({}),[v,y]=(0,c.useState)(!1),[b,x]=(0,c.useState)(null),[S,C]=(0,c.useState)(null),w=(0,c.useMemo)(()=>{let e=new Set(Object.keys(jt));n&&e.add(`doc.${n}.${r||`draft`}`);for(let t of i)t&&e.add(`chunk.${t}`);return[...e].sort()},[n,r,i]);(0,c.useEffect)(()=>{let e=!1;return d.documentGetChunk(t,a,o).then(t=>{if(e)return;p(t);let n=t.fields??{};h(n.color_enabled===!0);let r=n.color_scheme??{};_({...jt,...r})}).catch(t=>!e&&C(t instanceof Error?t.message:String(t))),()=>{e=!0}},[d,t,a,o]);let T=(e,t)=>_(n=>({...n,[e]:t})),E=e=>({...e??{},color_enabled:m,color_scheme:g}),D=async()=>{if(f){y(!0),C(null),x(null);try{await d.documentUpdateChunk(t,f.revision,{fields:E(f.fields)},a,o),u(),s()}catch(e){C(e instanceof Error?e.message:String(e)),y(!1)}}},O=async()=>{if(!n)C(`this document has no type to match`);else{y(!0),C(null),x(null);try{let{documents:t}=await d.documentsSummary({underPath:`/`},a,o),r=(t??[]).filter(t=>t.type===n&&t.document_id!==e&&t.root_chunk_id),i=0;for(let e of r)try{let t=await d.documentGetChunk(e.root_chunk_id,a,o);await d.documentUpdateChunk(e.root_chunk_id,t.revision,{fields:E(t.fields)},a,o),i++}catch{}x(`Applied to ${i} other ${n} document(s).`),u()}catch(e){C(e instanceof Error?e.message:String(e))}finally{y(!1)}}},k=w.filter(e=>e.startsWith(`doc.`)),ee=w.filter(e=>e.startsWith(`chunk.`));return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:s,children:(0,l.jsxs)(`div`,{className:`modal scheme-editor`,onClick:e=>e.stopPropagation(),children:[(0,l.jsxs)(`div`,{className:`scheme-editor-head`,children:[(0,l.jsx)(`h3`,{children:`Document colors`}),(0,l.jsxs)(`div`,{className:`scheme-editor-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:s,disabled:v,children:`cancel`}),(0,l.jsx)(`button`,{type:`button`,className:`primary`,onClick:()=>void D(),disabled:v||!f,children:v?`saving…`:`save`})]})]}),S&&(0,l.jsx)(`div`,{className:`modal-err`,children:S}),f?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`label`,{className:`scheme-toggle`,children:[(0,l.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>h(e.target.checked)}),(0,l.jsx)(`span`,{children:`Enable coloring for this document`})]}),(0,l.jsx)(`p`,{className:`modal-context`,children:`Document rows are tinted by type + status; chunk tiles by status. Colors apply as a semi-transparent wash so text stays readable.`}),(0,l.jsxs)(`div`,{className:`scheme-group`,children:[(0,l.jsx)(`h4`,{children:`Document (type · status)`}),k.map(e=>(0,l.jsx)(Sn,{label:e.slice(4),value:g[e],onChange:t=>T(e,t)},e))]}),(0,l.jsxs)(`div`,{className:`scheme-group`,children:[(0,l.jsx)(`h4`,{children:`Chunks (status)`}),ee.map(e=>(0,l.jsx)(Sn,{label:e.slice(6),value:g[e],onChange:t=>T(e,t)},e))]}),(0,l.jsxs)(`div`,{className:`scheme-editor-foot`,children:[(0,l.jsxs)(`button`,{type:`button`,onClick:()=>void O(),disabled:v||!n,title:n?`Apply this palette to every other ${n} document`:`This document has no type`,children:[`copy to all `,n||`same-type`,` documents`]}),b&&(0,l.jsx)(`span`,{className:`scheme-status`,children:b})]})]}):(0,l.jsx)(`p`,{className:`modal-context`,children:`Loading…`})]})})}function Sn({label:e,value:t,onChange:n}){let r=bn(t);return(0,l.jsxs)(`label`,{className:`scheme-row`,children:[(0,l.jsx)(`input`,{type:`color`,value:r,onChange:e=>n(e.target.value)}),(0,l.jsx)(`span`,{className:`scheme-key`,children:e}),(0,l.jsx)(`code`,{className:`scheme-hex`,children:r})]})}function Cn({id:e,title:t,targetDocumentId:n,documentId:r,onSelectChunk:i,onOpenDocument:a}){let o=t||e.slice(0,8),s=(0,c.useContext)(Ce),u=!!n&&n!==r,d=G(u?ke(n,o,s):Oe({id:e,document_id:r,title:o,position:0,revision:0},s));return u?a?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`button`,{type:`button`,className:`doc-ref-target external`,onClick:()=>a(n,e,t),...d.props,children:[o,` ↗`]}),d.card]}):(0,l.jsxs)(`span`,{className:`doc-ref-target external`,children:[o,` ↗`]}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,className:`doc-ref-target`,onClick:()=>i(e),...d.props,children:o}),d.card]})}function wn({statement:e}){let t=$e(e),n=K(e),r=rt(e),i=nt(e),{rows:a,more:o}=it(e);return(0,l.jsxs)(l.Fragment,{children:[t&&(0,l.jsx)(`span`,{className:`doc-stmt-status ${t}`,children:t}),n&&(0,l.jsx)(`span`,{className:`doc-stmt-method`,title:`how this relation was made`,children:n}),r&&(0,l.jsx)(`span`,{className:`doc-stmt-verdict`,title:r,children:`judged`}),i&&(0,l.jsx)(`span`,{className:`doc-stmt-valid`,children:i}),a.length>0&&(0,l.jsxs)(`ul`,{className:`doc-stmt-evidence`,children:[a.map(e=>(0,l.jsxs)(`li`,{title:e.quote,children:[`“`,at(e.quote),`”`,e.part===`title`&&(0,l.jsx)(`span`,{className:`doc-stmt-part`,children:` (title)`}),e.stale&&(0,l.jsx)(`span`,{className:`doc-stmt-stale`,children:` (source changed)`})]},e.id)),o>0&&(0,l.jsxs)(`li`,{className:`doc-stmt-more`,children:[`+`,o,` more`]})]})]})}function Tn({id:e,onRule:t}){let[n,r]=(0,c.useState)(!1),[i,a]=(0,c.useState)(``),[o,s]=(0,c.useState)(!1),[u,d]=(0,c.useState)(null),f=async n=>{s(!0),d(null);try{await t(e,n,n?void 0:i.trim()),r(!1),a(``)}catch(e){d(e instanceof Error?e.message:String(e))}finally{s(!1)}};return(0,l.jsxs)(`span`,{className:`doc-stmt-review`,children:[n?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`input`,{type:`text`,"aria-label":`Reason for rejecting`,placeholder:`why reject?`,value:i,disabled:o,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&i.trim()&&f(!1),e.key===`Escape`&&r(!1)},autoFocus:!0}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,disabled:o||!i.trim(),onClick:()=>void f(!1),children:`Reject`}),(0,l.jsx)(`button`,{type:`button`,disabled:o,onClick:()=>r(!1),children:`Cancel`})]}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,disabled:o,onClick:()=>void f(!0),children:`Accept`}),(0,l.jsx)(`button`,{type:`button`,disabled:o,onClick:()=>r(!0),children:`Reject…`})]}),u&&(0,l.jsx)(`span`,{className:`doc-stmt-err`,role:`alert`,children:u})]})}var En=3;function $({documentId:e,proposals:t,incomplete:n,scope:r,browse:i,onChanged:a,onSelectChunk:o,onOpenDocument:s}){let u=ue(),[d,f]=(0,c.useState)(new Set),[p,m]=(0,c.useState)({kind:`idle`}),[h,g]=(0,c.useState)(``),[_,v]=(0,c.useState)(null),[y,b]=(0,c.useState)(null),x=(0,c.useRef)(null),S=new Set(t.map(e=>e.id)),C=[...d].filter(e=>S.has(e)),w=p.kind!==`idle`&&p.kind!==`reason`,T=(e,t)=>{v(null),b(null),e===`reject`?m({kind:`reason`,action:e,all:t}):E(e,t,``)},E=async(t,n,o)=>{m({kind:`counting`,action:t,all:n});let s;try{s=await mt(u,{documentId:e,action:t,ids:n?void 0:C,reason:o.trim()||void 0,scope:r,browse:i},{confirm:(e,r)=>new Promise(i=>{x.current=i,m({kind:`confirm`,action:t,all:n,dry:e,changed:r!==`first`})}),onProgress:e=>m({kind:`ruling`,action:t,ruled:e.ruled,total:e.total})})}catch(e){s={rulingIds:[],ruled:0,failed:0,skipped:0,total:0,cancelled:!1,failures:[],error:e}}x.current=null,m({kind:`idle`}),g(``),s.rulingIds.length>0?(f(new Set),b({text:ht(t,s),rulingIds:s.rulingIds}),a()):s.error===void 0&&!s.cancelled&&b({text:`Nothing to rule: no proposals match.`,rulingIds:[]}),s.error!==void 0&&v(s.error instanceof Error?s.error.message:String(s.error))},D=e=>{e&&p.kind===`confirm`&&m({kind:`ruling`,action:p.action}),x.current?.(e)},O=async()=>{if(!y||!u.documentRevertRuling)return;let e=y,t=await J(e=>u.documentRevertRuling(e,r,i),e.rulingIds),n=[`${t.reverted} came back to review`];t.changed>0&&n.push(`${t.changed} changed since and left as ruled`),t.errors.length>0&&n.push(`not undone: ${t.errors.join(`; `)}`),b({...e,undone:!0,text:n.join(`; `)+`.`}),a()},k=e=>f(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),ee=t.length>0&&C.length===t.length,A=t.length===0&&!n;return(0,l.jsxs)(`div`,{className:`doc-conn-group doc-bulk`,children:[(0,l.jsxs)(`h5`,{children:[`Proposals from this document (`,t.length,`)`]}),(0,l.jsxs)(`div`,{className:`doc-bulk-bar`,children:[(0,l.jsxs)(`label`,{children:[(0,l.jsx)(`input`,{type:`checkbox`,"aria-label":`select every proposal shown`,checked:ee,disabled:w||t.length===0,onChange:()=>f(ee?new Set:new Set(S))}),` `,`all shown`]}),(0,l.jsxs)(`button`,{type:`button`,disabled:w||C.length===0,onClick:()=>T(`accept`,!1),children:[`Accept selected (`,C.length,`)`]}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,disabled:w||C.length===0,onClick:()=>T(`reject`,!1),children:`Reject selected…`}),(0,l.jsx)(`button`,{type:`button`,disabled:w||A,onClick:()=>T(`accept`,!0),children:`Accept all from this document`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,disabled:w||A,onClick:()=>T(`reject`,!0),children:`Reject all…`})]}),p.kind===`reason`&&(0,l.jsxs)(`form`,{className:`doc-bulk-step`,onSubmit:e=>{e.preventDefault(),h.trim()&&E(p.action,p.all,h)},children:[(0,l.jsx)(`input`,{type:`text`,"aria-label":`Reason for rejecting`,placeholder:`why reject?`,value:h,onChange:e=>g(e.target.value),autoFocus:!0}),(0,l.jsx)(`button`,{type:`submit`,className:`danger`,disabled:!h.trim(),children:`Count`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>m({kind:`idle`}),children:`Cancel`})]}),p.kind===`counting`&&(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`counting…`}),p.kind===`confirm`&&(0,l.jsx)(Dn,{step:p,onAnswer:D}),p.kind===`ruling`&&(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:p.total?`ruled ${p.ruled??0} of ${p.total}…`:`ruling…`}),_&&(0,l.jsx)(`p`,{className:`doc-stmt-err`,role:`alert`,children:_}),y&&(0,l.jsxs)(`p`,{className:`doc-bulk-result`,role:`status`,children:[y.text,y.rulingIds.length>0&&!y.undone&&u.documentRevertRuling&&(0,l.jsx)(`button`,{type:`button`,onClick:()=>void O(),children:`Undo`})]}),t.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsx)(`ul`,{className:`doc-conn-list`,children:t.map(t=>(0,l.jsxs)(`li`,{className:`doc-conn-row`,children:[(0,l.jsx)(`input`,{type:`checkbox`,"aria-label":`select ${t.from_title??t.from_id} ${t.kind} ${t.to_title??t.to_id}`,checked:d.has(t.id),disabled:w,onChange:()=>k(t.id)}),(0,l.jsx)(Cn,{id:t.from_id,title:t.from_title,targetDocumentId:t.from_document_id,documentId:e,onSelectChunk:o,onOpenDocument:s}),(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:t.kind}),(0,l.jsx)(Cn,{id:t.to_id,title:t.to_title,targetDocumentId:t.to_document_id,documentId:e,onSelectChunk:o,onOpenDocument:s}),(0,l.jsx)(wn,{statement:t})]},t.id))})]})}function Dn({step:e,onAnswer:t}){let{dry:n}=e,r=e.action===`accept`?`Accept`:`Reject`,i=ut(n.matched);return(0,l.jsxs)(`div`,{className:`doc-bulk-step doc-bulk-confirm`,children:[e.changed&&(0,l.jsx)(`p`,{className:`doc-bulk-warn`,children:`The proposals changed since the last count; counted again.`}),(0,l.jsxs)(`p`,{children:[r,` `,n.matched,` statement`,n.matched===1?``:`s`,e.all?` filed from this document`:``,i>1?`, in ${i} rulings of up to 1,000`:``,`?`,n.skipped>0&&` ${n.skipped} of them are not yours to rule and will be skipped.`]}),(n.sample??[]).length>0&&(0,l.jsx)(`ul`,{className:`doc-bulk-sample`,children:(n.sample??[]).slice(0,En).map(e=>(0,l.jsxs)(`li`,{children:[e.from_title||e.from_id,` `,(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:e.kind}),` `,e.to_title||e.to_id]},e.id))}),(0,l.jsxs)(`button`,{type:`button`,className:e.action===`reject`?`danger`:void 0,onClick:()=>t(!0),children:[r,` `,n.matched]}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>t(!1),children:`Cancel`})]})}var On=8,kn=20;function An(e){return/embedder|embedding|vector|semantic|not configured/i.test(e)}function jn({documentId:e,selectedId:t,scope:n,browse:r,onSelectChunk:i,onOpenDocument:a,refreshKey:o,review:s}){let u=ue(),[d,f]=(0,c.useState)(!1),[p,m]=(0,c.useState)(!1),[h,g]=(0,c.useState)(void 0),[_,v]=(0,c.useState)([]),[y,b]=(0,c.useState)([]),[x,S]=(0,c.useState)(null),[C,w]=(0,c.useState)([]),[T,E]=(0,c.useState)(!1);(0,c.useEffect)(()=>{if(!d||!t)return;let e=t,i=!1;return m(!0),Promise.allSettled([u.documentBacklinks(e,n,r),u.documentRelated(e,n,r,On),u.documentUnlinkedMentions(e,n,r,kn)]).then(([t,n,r])=>{if(!i){if(v(t.status===`fulfilled`?t.value.backlinks??[]:[]),n.status===`fulfilled`)b(n.value.related??[]),S(null);else{b([]);let e=n.reason instanceof Error?n.reason.message:String(n.reason);S(An(e)?`semantic search not configured`:e)}r.status===`fulfilled`?(w(r.value.unlinked_mentions??[]),E(!!r.value.truncated)):(w([]),E(!1)),g(e),m(!1)}}),()=>{i=!0}},[u,d,t,n,r,o]);let D=(t,n,r)=>(0,l.jsx)(Cn,{id:t,title:n,targetDocumentId:r,documentId:e,onSelectChunk:i,onOpenDocument:a}),O=!!(d&&t&&!p&&h===t);return(0,l.jsxs)(`div`,{className:`doc-conn`,children:[(0,l.jsxs)(`button`,{type:`button`,className:`doc-conn-toggle`,onClick:()=>f(e=>!e),children:[d?`▼`:`▶`,` Connections`]}),d&&(0,l.jsxs)(`div`,{className:`doc-conn-body`,children:[s&&(0,l.jsx)($,{documentId:e,proposals:s.proposals,incomplete:s.incomplete,scope:s.scope,browse:r,onChanged:s.onChanged,onSelectChunk:i,onOpenDocument:a}),t?O?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`div`,{className:`doc-conn-group`,children:[(0,l.jsx)(`h5`,{children:`Backlinks`}),_.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsx)(`ul`,{className:`doc-conn-list`,children:_.map((e,t)=>(0,l.jsxs)(`li`,{className:`doc-conn-row`,children:[D(e.from_id,e.from_title,e.from_document_id),(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:e.kind}),e.auto&&(0,l.jsx)(`span`,{className:`doc-conn-auto`,title:`Auto-linked from a [[wikilink]]`,children:`auto`}),(0,l.jsx)(wn,{statement:e})]},`${e.from_id}-${e.kind}-${t}`))})]}),(0,l.jsxs)(`div`,{className:`doc-conn-group`,children:[(0,l.jsx)(`h5`,{children:`Related`}),x?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:x}):y.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsx)(`ul`,{className:`doc-conn-list`,children:y.map((e,t)=>(0,l.jsxs)(`li`,{className:`doc-conn-row`,children:[D(e.chunk_id,e.title,e.document_id),(0,l.jsx)(`span`,{className:`doc-conn-score`,title:`similarity score`,children:e.score.toFixed(2)})]},`${e.chunk_id}-${t}`))})]}),(0,l.jsxs)(`div`,{className:`doc-conn-group`,children:[(0,l.jsx)(`h5`,{children:`Unlinked mentions`}),C.length===0?(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`none`}):(0,l.jsxs)(`ul`,{className:`doc-conn-list`,children:[C.map((e,t)=>(0,l.jsx)(`li`,{className:`doc-conn-row`,children:D(e.chunk_id,e.title,e.document_id)},`${e.chunk_id}-${t}`)),T&&(0,l.jsx)(`li`,{className:`doc-conn-more`,"aria-hidden":!0,children:`(more…)`})]})]})]}):(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`loading…`}):(0,l.jsx)(`p`,{className:`doc-conn-empty`,children:`Select a chunk.`})]})]})}var Mn=24;function Nn({edges:e,documentId:t,selectedId:n,onSelectChunk:r,onOpenDocument:i,onRuleStatement:a,incomplete:o}){let[s,u]=(0,c.useState)(!1),[d,f]=(0,c.useState)(!1);if(e.length===0)return null;let p=n?e.filter(e=>e.from_id===n||e.to_id===n):[],m=d?e:e.slice(0,Mn),h=Fn(m);return(0,l.jsxs)(`div`,{className:`doc-refs`,children:[o&&(0,l.jsxs)(`p`,{className:`doc-refs-incomplete`,children:[`Showing the first `,e.length,` links of this document; it has more, which are not shown here or in the graph.`]}),n&&(0,l.jsxs)(`div`,{className:`doc-refs-list-wrap`,children:[(0,l.jsx)(`h4`,{children:`References`}),p.length===0?(0,l.jsx)(`p`,{className:`doc-refs-empty`,children:`This chunk has no links.`}):(0,l.jsx)(`ul`,{className:`doc-refs-list`,children:p.map((e,o)=>(0,l.jsx)(Pn,{edge:e,selectedId:n,documentId:t,onSelectChunk:r,onOpenDocument:i,onRuleStatement:a},`${e.from_id}-${e.to_id}-${e.kind}-${o}`))})]}),(0,l.jsxs)(`div`,{className:`doc-graph`,children:[(0,l.jsxs)(`button`,{type:`button`,className:`doc-graph-toggle`,onClick:()=>u(e=>!e),children:[s?`▼`:`▶`,` relationship graph (`,e.length,`)`]}),s&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(fn,{code:h,onNodeClick:e=>{let n=In(m,e);n&&(!n.documentId||n.documentId===t?r(n.id):i?.(n.documentId,n.id,n.title))}}),e.length>Mn&&(0,l.jsx)(`button`,{type:`button`,className:`doc-graph-more`,onClick:()=>f(e=>!e),children:d?`show top ${Mn}`:`show all ${e.length}`})]})]})]})}function Pn({edge:e,selectedId:t,documentId:n,onSelectChunk:r,onOpenDocument:i,onRuleStatement:a}){let o=e.from_id===t,s=o?e.to_id:e.from_id,c=o?e.to_title:e.from_title,u=o?e.to_document_id:e.from_document_id;return(0,l.jsxs)(`li`,{className:`doc-ref`,children:[(0,l.jsx)(`span`,{className:`doc-ref-kind`,children:e.kind}),(0,l.jsx)(`span`,{className:`doc-ref-arrow`,"aria-hidden":!0,children:o?`→`:`←`}),(0,l.jsx)(Cn,{id:s,title:c,targetDocumentId:u,documentId:n,onSelectChunk:r,onOpenDocument:i}),(0,l.jsx)(wn,{statement:e}),a&&et(e)&&(0,l.jsx)(Tn,{id:e.id,onRule:a})]})}function Fn(e){let t=[`graph LR`];for(let n of e){let e=`${Ln(n.from_id)}["${Rn(n.from_title,n.from_id)}"]`,r=`${Ln(n.to_id)}["${Rn(n.to_title,n.to_id)}"]`,i=(n.kind||`link`).replace(/[|"]/g,` `),a=n.status===`proposed`?`-.->`:`-->`;t.push(` ${e} ${a}|${i}| ${r}`)}return t.join(`
2
+ `)}function In(e,t){for(let n of e){if(Ln(n.from_id)===t)return{id:n.from_id,documentId:n.from_document_id,title:n.from_title};if(Ln(n.to_id)===t)return{id:n.to_id,documentId:n.to_document_id,title:n.to_title}}}function Ln(e){return`n`+e.replace(/[^a-zA-Z0-9]/g,``)}function Rn(e,t){let n=(e??``).replace(/["[\]{}|<>]/g,` `).replace(/\s+/g,` `).trim()||t.slice(0,6);return n.length>30?n.slice(0,29)+`…`:n}function zn({documentId:e,scope:t,detail:n}){return(0,l.jsxs)(`div`,{className:`doc-unavailable`,role:`alert`,children:[(0,l.jsx)(`p`,{className:`doc-unavailable-lead`,children:`This document can’t be opened.`}),(0,l.jsxs)(`p`,{children:[`It may have been deleted, live in a scope other than `,(0,l.jsx)(`code`,{children:t}),`, or not be yours to read.`]}),(0,l.jsxs)(`p`,{className:`doc-unavailable-detail`,children:[(0,l.jsx)(`code`,{children:e}),n&&(0,l.jsxs)(l.Fragment,{children:[` — `,n]})]})]})}function Bn(e){let t=typeof e==`number`?e/1e6:Date.parse(String(e));return!Number.isFinite(t)||t<=0?String(e??``):new Date(t).toLocaleString()}function Vn({chunkId:e,chunkTitle:t,scope:n,browse:r,onClose:i}){return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:i,children:(0,l.jsxs)(`div`,{className:`modal history-modal`,onClick:e=>e.stopPropagation(),children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsxs)(`h3`,{children:[`History`,t?` — ${t}`:``]}),(0,l.jsx)(`div`,{className:`modal-buttons modal-buttons-top`,children:(0,l.jsx)(`button`,{type:`button`,onClick:i,children:`close`})})]}),(0,l.jsx)(Hn,{chunkId:e,scope:n,browse:r})]})})}function Hn({chunkId:e,scope:t,browse:n}){let r=ue(),[i,a]=(0,c.useState)([]),[o,s]=(0,c.useState)(!0),[u,d]=(0,c.useState)(null),[f,p]=(0,c.useState)(`none`),[m,h]=(0,c.useState)(null),[g,_]=(0,c.useState)(``),[v,y]=(0,c.useState)(!1),[b,x]=(0,c.useState)(null),[S,C]=(0,c.useState)(null),[w,T]=(0,c.useState)(``);(0,c.useEffect)(()=>{let i=!1;return s(!0),d(null),r.documentHistory(e,t,n).then(e=>{if(i)return;let t=e.revisions??[];if(a(t),t.length>=2){let e=t.map(e=>e.revision);x(Math.min(...e)),C(Math.max(...e))}}).catch(e=>!i&&d(e instanceof Error?e.message:String(e))).finally(()=>!i&&s(!1)),()=>{i=!0}},[r,e,t,n]);let E=async i=>{d(null),y(!0),h(i),p(`version`);try{let a=await r.documentGetVersion(e,i,t,n);_(a.body??``)}catch(e){d(e instanceof Error?e.message:String(e))}finally{y(!1)}},D=async()=>{if(b!==null&&S!==null){d(null),y(!0),p(`diff`);try{let i=await r.documentDiff(e,b,S,t,n);T(i.diff??``)}catch(e){d(e instanceof Error?e.message:String(e))}finally{y(!1)}}};return(0,l.jsxs)(l.Fragment,{children:[u&&(0,l.jsx)(`div`,{className:`modal-err`,children:u}),o?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`loading…`}):i.length===0?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`No history recorded for this chunk.`}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`div`,{className:`doc-hist-revs`,children:i.map(e=>(0,l.jsxs)(`button`,{type:`button`,className:`doc-hist-rev`+(f===`version`&&m===e.revision?` active`:``),onClick:()=>void E(e.revision),children:[(0,l.jsxs)(`span`,{className:`doc-hist-rev-num`,children:[`rev `,e.revision]}),(0,l.jsx)(`span`,{className:`doc-hist-rev-time`,children:Bn(e.created_at)}),(0,l.jsx)(`span`,{className:`doc-hist-rev-actor`,children:e.actor||`unknown`})]},e.revision))}),i.length>=2&&(0,l.jsxs)(`div`,{className:`doc-hist-diffbar`,children:[(0,l.jsx)(`span`,{children:`Compare`}),(0,l.jsx)(`select`,{value:b??``,onChange:e=>x(e.target.value===``?null:Number(e.target.value)),"aria-label":`diff from revision`,children:i.map(e=>(0,l.jsxs)(`option`,{value:e.revision,children:[`rev `,e.revision]},e.revision))}),(0,l.jsx)(`span`,{"aria-hidden":!0,children:`→`}),(0,l.jsx)(`select`,{value:S??``,onChange:e=>C(e.target.value===``?null:Number(e.target.value)),"aria-label":`diff to revision`,children:i.map(e=>(0,l.jsxs)(`option`,{value:e.revision,children:[`rev `,e.revision]},e.revision))}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void D(),disabled:v||b===null||S===null,children:`diff`})]}),(0,l.jsx)(`div`,{className:`doc-hist-output`,children:v?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`loading…`}):f===`diff`?(0,l.jsx)(Un,{text:w}):f===`version`?(0,l.jsx)(`pre`,{className:`md-pre doc-hist-version`,children:(0,l.jsx)(`code`,{children:g||`(empty)`})}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`Select a revision to view it, or compare two.`})})]})]})}function Un({text:e}){if(!e.trim())return(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(no differences)`});let t=e.split(`
3
3
  `);return(0,l.jsx)(`pre`,{className:`md-pre doc-hist-diff`,children:t.map((e,t)=>{let n=e.startsWith(`+`)&&!e.startsWith(`+++`)?`diff-add`:e.startsWith(`-`)&&!e.startsWith(`---`)?`diff-del`:e.startsWith(`@@`)?`diff-hunk`:``;return(0,l.jsxs)(`span`,{className:n,children:[e,`
4
- `]},t)})})}function Sn({source:e}){return(0,l.jsx)(`div`,{className:`md`,children:(0,l.jsx)(d.default,{remarkPlugins:[f.default],components:Cn,children:e})})}var Cn={a({href:e,children:t}){let n=e??``,r=/^https?:\/\//i.test(n);return(0,l.jsx)(`a`,{href:n,target:r?`_blank`:void 0,rel:r?`noopener noreferrer`:void 0,children:t})},pre({children:e}){return(0,l.jsx)(l.Fragment,{children:e})},code({className:e,children:t}){let n=/language-(\w+)/.exec(e??``)?.[1],r=String(t??``);return n===`mermaid`?(0,l.jsx)(Et,{code:r.replace(/\n$/,``)}):n||r.includes(`
5
- `)?(0,l.jsx)(`pre`,{className:`md-pre`,children:(0,l.jsx)(`code`,{className:e,children:t})}):(0,l.jsx)(`code`,{children:t})}};function wn(e){let t=e.fields??{};return typeof t.alt==`string`&&t.alt.trim()!==``?t.alt:e.title||`image`}function Tn({documentId:e,scope:t,titleHint:n,browse:r,principal:i,renderAssistant:a,initialChunkId:o,onOpenDocument:s,onTitle:u,onChunkSelect:d,focusChunk:f,onRegenerateAnnotation:p,canEditAnnotations:m,onAnnotationChanged:h}){let _=H(),v=(0,c.useMemo)(()=>r&&(r.scopeId||r.tenant)?{scopeId:r.scopeId,tenant:r.tenant}:void 0,[r?.scopeId,r?.tenant]),[y,b]=(0,c.useState)([]),[x,S]=(0,c.useState)(void 0),[C,w]=(0,c.useState)(null),[E,D]=(0,c.useState)(`chunks`),[O,k]=(0,c.useState)(null),[A,N]=(0,c.useState)(null),[ee,P]=(0,c.useState)(null),F=(0,c.useRef)(null),[I,L]=(0,c.useState)(null),[R,z]=(0,c.useState)(null),[te,ne]=(0,c.useState)(!1),[B,re]=(0,c.useState)(!1),[ie,V]=(0,c.useState)(null),[ae,oe]=(0,c.useState)(!1),[se,ce]=(0,c.useState)(void 0),[le,ue]=(0,c.useState)(null),[U,de]=(0,c.useState)(0),[W,fe]=(0,c.useState)(!1),[G,pe]=(0,c.useState)(null),[me,he]=(0,c.useState)(!1),[K,ge]=(0,c.useState)([]),[q,_e]=(0,c.useState)(!1),[ve,ye]=(0,c.useState)(0),[be,xe]=(0,c.useState)(0),[Se,Ce]=(0,c.useState)(void 0),[we,Te]=(0,c.useState)([]),[De,Oe]=(0,c.useState)([]),[ke,je]=(0,c.useState)(0),J=(0,c.useCallback)(()=>de(e=>e+1),[]),Pe=(0,c.useRef)(o);Pe.current=o;let Le=(0,c.useRef)(u);Le.current=u;let Y=(0,c.useMemo)(()=>mt(y),[y]),Re=(0,c.useMemo)(()=>y.find(e=>!e.parent_id)?.title||n||`document`,[y,n]),X=(0,c.useMemo)(()=>!!C&&!C.parent_id,[C]),Z=(0,c.useMemo)(()=>Ie(y,C?.id),[y,C]),Q=(0,c.useMemo)(()=>G?.root_chunk_id??y.find(e=>!e.parent_id)?.id,[G,y]),ze=(0,c.useRef)(d);ze.current=d,(0,c.useEffect)(()=>{x&&ze.current?.(x===Q?void 0:x)},[x,Q]);let Be=(0,c.useMemo)(()=>[...new Set(y.map(e=>e.status).filter(e=>!!e))],[y]),Ve=!!G?.color_enabled,He=(0,c.useMemo)(()=>{let e=new Set;for(let t of K)e.add(t.from_id),e.add(t.to_id);return e},[K]),$=(0,c.useMemo)(()=>Ve?at(G?.type,G?.status,rt(G?.color_scheme)):void 0,[Ve,G?.type,G?.status,G?.color_scheme]),Ue=(0,c.useMemo)(()=>lt($),[$]);(0,c.useEffect)(()=>{let n=!1;return oe(!0),V(null),ue(null),_.documentQueryChunks(e,t,v).then(r=>{if(n)return;let i=r.chunks??[];b(i),ce(`${t}:${e}`),S(e=>e??Ee(i,Pe.current))}).catch(e=>{n||(b([]),ue(e instanceof Error?e.message:String(e)))}).finally(()=>!n&&oe(!1)),()=>{n=!0}},[_,e,t,U,v]);let We=!ae&&(le!==null||se===`${t}:${e}`&&y.length===0),Ge=(0,c.useMemo)(()=>y.find(t=>!t.parent_id&&t.document_id===e)?.title,[y,e]);(0,c.useEffect)(()=>{Ge&&Le.current?.(e,Ge)},[e,Ge]),(0,c.useEffect)(()=>{let n=!1;return _.documentGet(e,t,v).then(e=>!n&&pe(e)).catch(()=>!n&&pe(null)),()=>{n=!0}},[_,e,t,U,v]),(0,c.useEffect)(()=>{let n=!1;return Fe(_,e,t,v).then(e=>{n||(ge(e.edges),_e(e.incomplete))}).catch(()=>{n||(ge([]),_e(!1))}),()=>{n=!0}},[_,e,t,U,v,ve]),(0,c.useEffect)(()=>{if(!Q||!_.documentAcceptClassification){Ce(void 0);return}let n=!1;return _.documentGetChunk(Q,t,v).then(t=>!n&&Ce(t.document_id===e?t.fields:void 0)).catch(()=>!n&&Ce(void 0)),()=>{n=!0}},[_,e,Q,t,U,v]),(0,c.useEffect)(()=>{if(!Q||!T(t)){Te([]);return}let e=!1;return j(_,Q,t,v).then(t=>!e&&Te(t)).catch(()=>!e&&Te([])),()=>{e=!0}},[_,Q,t,U,v,ke]),(0,c.useEffect)(()=>{if(!x||x===Q||!T(t)){Oe([]);return}let e=!1;return Oe([]),j(_,x,t,v).then(t=>!e&&Oe(t)).catch(()=>!e&&Oe([])),()=>{e=!0}},[_,x,Q,t,U,v,ke]);let Ke=(0,c.useMemo)(()=>{if(m&&_.documentSetAnnotation&&T(t))return e=>async(n,r,i)=>{await _.documentSetAnnotation({id:e,level:n,brief:r,abstract:i},t,v),je(e=>e+1),h?.()}},[_,t,v,m,h]),qe=(0,c.useMemo)(()=>{if(p&&T(t))return n=>async r=>{let i=[...we,...De].find(e=>e.chunk_id===n&&e.level===r)?.folder;try{await p({documentId:e,chunkId:n,level:r,scope:t,...i?{folder:i}:{}})}finally{je(e=>e+1),h?.()}}},[p,e,t,we,De,h]),Je=we.find(e=>e.level===`document`)??we.find(e=>e.level===`path`),Ye=(0,c.useMemo)(()=>De.filter(e=>e.chunk_id===C?.id),[De,C?.id]),$e=(0,c.useMemo)(()=>{if(_.documentAcceptStatement&&_.documentRejectStatement)return async(e,n,r)=>{n?await _.documentAcceptStatement(e,t,v,r):await _.documentRejectStatement(e,r??``,t,v),ye(e=>e+1)}},[_,t,v]),et=(0,c.useMemo)(()=>Xe(_,t),[_,t]),tt=(0,c.useMemo)(()=>Ze(K,e),[K,e]),nt=(0,c.useCallback)(()=>ye(e=>e+1),[]),it=(0,c.useMemo)(()=>Qe(et,tt,q,nt),[et,tt,q,nt]),ot=f?.seq,st=(0,c.useRef)(f);st.current=f;let ct=(0,c.useRef)(Q);ct.current=Q;let ut=(0,c.useRef)(y);ut.current=y,(0,c.useEffect)(()=>{if(ot===void 0)return;let e=st.current?.chunkId,t=ut.current.length>0?Ee(ut.current,e):e??ct.current;t&&S(t)},[ot]),(0,c.useEffect)(()=>{S(void 0),w(null),k(null),D(`chunks`),pe(null),ge([]),_e(!1),xe(0),Ce(void 0),Te([]),Oe([])},[e,t]),(0,c.useEffect)(()=>{if(!x){w(null);return}let e=!1;return _.documentGetChunk(x,t,v).then(t=>!e&&w(t)).catch(t=>!e&&V(t instanceof Error?t.message:String(t))),()=>{e=!0}},[_,x,t,U,v]),(0,c.useEffect)(()=>{let e=C?.type===`image`||!!C?.asset;if(!C||!e||!_.documentAssetObjectUrl){N(null),P(null);return}let n=!1,r=null;return P(null),_.documentAssetObjectUrl(C.id,t,v).then(e=>{n?URL.revokeObjectURL(e):(r=e,N(e))}).catch(e=>!n&&P(e instanceof Error?e.message:String(e))),()=>{n=!0,r&&URL.revokeObjectURL(r)}},[_,C,t,v]),(0,c.useEffect)(()=>{if(E!==`markdown`||!x){k(null);return}let e=gt(Y,x);if(!e)return;let n=!1,r=[],i=(e,t)=>{r.push({node:e,depth:t}),e.children.forEach(e=>i(e,t+1))};return i(e,0),Promise.all(r.map(e=>_.documentGetChunk(e.node.row.id,t,v))).then(e=>{if(n)return;let t=r.map((t,n)=>{let r=Math.min(t.depth+1,6),i=e[n],a=`#`.repeat(r)+` `+t.node.row.title;if(i.type===`mermaid`&&i.body)return a+`
6
-
7
- \`\`\`mermaid
8
- `+i.body+"\n```\n";if(i.type===`image`||i.asset){let e=i.body?` — `+i.body:``;return a+`
9
-
10
- _🖼 image chunk_`+e+`
11
- `}return a+(i.body?`
12
-
13
- `+i.body:``)+`
14
- `}).join(`
15
- `);k(t)}).catch(e=>!n&&V(e instanceof Error?e.message:String(e))),()=>{n=!0}},[_,E,x,Y,t,U,v]);let dt=(0,c.useCallback)(e=>S(e.row.id),[]),ft=(0,c.useCallback)((t,n,r)=>s?.({documentId:t,chunkId:n,title:r},{documentId:e,chunkId:x,title:Re}),[s,e,x,Re]),ht=!!_.documentCreateChunk&&!!Q,vt=(0,c.useCallback)(async n=>{if(!_.documentCreateChunk||!_.documentSetAsset)return;let r=x||Q;if(r){V(null);try{let{mediaType:i,data:a}=await Me(n),o=await _.documentCreateChunk(e,r,{title:n.name||`image`,type:`image`},t,v);await _.documentSetAsset(o.id,i,a,n.name,t,v),J(),S(o.id)}catch(e){V(e instanceof Error?e.message:String(e))}}},[_,e,t,v,x,Q,J]),yt=(0,c.useCallback)(async()=>{if(!_.documentCreateChunk)return;let n=x||Q;if(n){V(null);try{let r=await _.documentCreateChunk(e,n,{title:`Diagram`,type:`mermaid`,body:`graph TD
16
- A[Start] --> B[End]`},t,v);J(),S(r.id),L(r)}catch(e){V(e instanceof Error?e.message:String(e))}}},[_,e,t,v,x,Q,J]),xt=(0,c.useCallback)(async()=>{if(!_.documentCreateChunk)return;let n=x&&!X?x:void 0,r=x||Q;if(r){V(null);try{let i=await _.documentCreateChunk(e,n?``:r,{title:`Text`,body:``},t,v,n);J(),S(i.id),L(i)}catch(e){V(e instanceof Error?e.message:String(e))}}},[_,e,t,v,x,X,Q,J]),Ct=(0,c.useCallback)(async()=>{if(_.documentCreateChunk&&x){V(null);try{let n=await _.documentCreateChunk(e,x,{title:`Text`,body:``},t,v);J(),S(n.id),L(n)}catch(e){V(e instanceof Error?e.message:String(e))}}},[_,e,t,v,x,J]),wt=(0,c.useMemo)(()=>{if(!C||X)return{canUp:!1,canDown:!1};let e=C.parent_id??``,t=y.filter(t=>(t.parent_id??``)===e).sort((e,t)=>e.position-t.position||e.id.localeCompare(t.id)),n=t.findIndex(e=>e.id===C.id);return{canUp:n>0,canDown:n>=0&&n<t.length-1}},[y,C,X]),Tt=(0,c.useCallback)(async e=>{if(_.documentReorderChunk&&x){V(null);try{await _.documentReorderChunk(x,e,t,v),J()}catch(e){V(e instanceof Error?e.message:String(e))}}},[_,x,t,v,J]),kt=(0,c.useCallback)(async()=>{if(!_.documentDeleteChunk||!C)return;V(null);let e=C.parent_id;try{await _.documentDeleteChunk(C.id,t,v),re(!1),S(e||Q),J()}catch(e){V(e instanceof Error?e.message:String(e)),re(!1)}},[_,C,t,v,Q,J]);return(0,c.useEffect)(()=>{if(!ht)return;let e=e=>{if(I||me)return;let t=document.activeElement,n=t?.tagName;if(n===`INPUT`||n===`TEXTAREA`||t?.isContentEditable)return;let r=Ne(e.clipboardData?.items);r&&(e.preventDefault(),vt(r))};return window.addEventListener(`paste`,e),()=>window.removeEventListener(`paste`,e)},[ht,I,me,vt]),(0,l.jsxs)(`div`,{className:`doc-viewer`,children:[(0,l.jsx)(`input`,{ref:F,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,style:{display:`none`},onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&vt(t)}}),(0,l.jsxs)(`div`,{className:`doc-toolbar`,style:Ue,children:[(0,l.jsx)(`strong`,{className:`doc-title`,title:Re,children:Re}),(0,l.jsx)(pt,{value:e,label:`doc`}),(0,l.jsxs)(`div`,{className:`doc-toolbar-actions`,children:[ht&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,onClick:()=>void xt(),title:`Add a text chunk AFTER the selected chunk, at the same level`,children:`+ text`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void Ct(),disabled:!x,title:x?`Add a chunk NESTED UNDER the selected chunk (in the ontology, a child is a subclass)`:`Select a chunk first — this nests a new chunk under it`,children:`+ child`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>F.current?.click(),title:`Add an image chunk (upload — or paste a screenshot into the view)`,children:`+ image`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void yt(),title:`Add a Mermaid diagram chunk`,children:`+ diagram`})]}),(0,l.jsx)(`button`,{type:`button`,className:Ve?`active`:``,onClick:()=>he(!0),disabled:!Q,title:`Colors — tint chunk tiles + the Path tree by type/status`,children:`colors`}),_.documentClassify&&(0,l.jsx)(`button`,{type:`button`,className:be>0?`active`:``,onClick:()=>xe(e=>e>0?0:1),title:`Classify — what this document is, by the confirmed ontology (a report first; nothing is written until Apply)`,children:`classify`}),(0,l.jsx)(vn,{documentId:e,scope:t,browse:v,title:Re,onError:V}),a&&(0,l.jsx)(`button`,{type:`button`,className:W?`active`:``,onClick:()=>fe(e=>!e),title:`Document Assistant — instruct an agent to restructure/import/link chunks`,children:`assistant`}),(0,l.jsx)(`button`,{type:`button`,onClick:J,title:`Reload`,children:`↻`})]})]}),!We&&Q&&(we.length>0||Ke||qe)&&(0,l.jsxs)(`div`,{className:`doc-annotation`,children:[(0,l.jsx)(bt,{record:Je}),(0,l.jsx)(St,{records:we,newLevel:M(!0),onSave:Ke?.(Q),onRegenerate:qe?.(Q)},Q)]}),ie&&(0,l.jsx)(`div`,{className:`paths-err`,children:ie}),!We&&(0,l.jsx)(Ht,{documentId:e,scope:t,browse:v,rootFields:Se,requestKey:be,onClose:()=>xe(0),onChanged:J},`${t}:${e}`),We?(0,l.jsx)(mn,{documentId:e,scope:t,detail:le??void 0}):(0,l.jsxs)(Ae,{className:`doc-split`,defaultLeftWidth:320,minLeftWidth:160,minRightWidth:320,storageKey:`loomcycle.explorer.split.doc`,children:[(0,l.jsx)(`div`,{className:`doc-chunktree`,children:ae&&y.length===0?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Loading…`})}):(0,l.jsx)(_t,{tree:Y,selectedId:x,onSelect:dt,colorEnabled:Ve,scheme:G?.color_scheme,documentColor:$,linkedIds:He})}),(0,l.jsx)(`div`,{className:`doc-content`,children:C?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`div`,{className:`doc-content-head`,children:[Z.length>0&&(0,l.jsxs)(`nav`,{className:`chunk-ancestry`,"aria-label":`Chunks above this one`,children:[(0,l.jsx)(`button`,{type:`button`,className:`chunk-ancestry-up`,onClick:()=>S(Z[Z.length-1].id),title:`Up to ${Z[Z.length-1].title||`(untitled)`}`,children:`↰ Up`}),(0,l.jsxs)(`ol`,{className:`doc-trail-list`,children:[Z.map(e=>(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`button`,{type:`button`,className:`doc-trail-crumb`,onClick:()=>S(e.id),title:e.title||`(untitled)`,children:e.title||`(untitled)`})},e.id)),(0,l.jsx)(`li`,{className:`doc-trail-item`,children:(0,l.jsx)(`span`,{className:`doc-trail-current`,"aria-current":`location`,title:C.title||`(untitled)`,children:C.title||`(untitled)`})})]})]}),(0,l.jsx)(`h3`,{children:C.title||`(untitled)`}),!X&&(0,l.jsx)(bt,{record:Ye[0]}),(0,l.jsxs)(`div`,{className:`doc-content-meta`,children:[C.type&&(0,l.jsx)(`span`,{className:`chunk-badge`,children:C.type}),C.status&&(0,l.jsx)(`span`,{className:`chunk-badge chunk-status`,children:C.status}),(0,l.jsxs)(`span`,{className:`chunk-rev`,children:[`rev `,C.revision]}),C.tags?.map(e=>(0,l.jsx)(`span`,{className:`chunk-tag`,children:e},e)),(0,l.jsx)(pt,{value:C.id,label:`chunk`})]}),!X&&C.document_id===e&&(0,l.jsx)(St,{records:Ye,newLevel:M(!1),onSave:Ke?.(C.id),onRegenerate:qe?.(C.id)},C.id),(0,l.jsxs)(`div`,{className:`doc-content-controls`,children:[(0,l.jsxs)(`div`,{className:`doc-mode-toggle`,children:[(0,l.jsx)(`button`,{type:`button`,className:E===`chunks`?`active`:``,onClick:()=>D(`chunks`),title:`This chunk's own content`,children:`chunk`}),(0,l.jsx)(`button`,{type:`button`,className:E===`markdown`?`active`:``,onClick:()=>D(`markdown`),title:X?`Whole document as Markdown`:`This chunk + its sub-chunks as Markdown`,children:`markdown`})]}),(0,l.jsx)(`button`,{type:`button`,className:`chunk-edit`,onClick:()=>L(C),children:`edit`}),_.documentEntityTypes&&g(C)&&(0,l.jsx)(`button`,{type:`button`,onClick:()=>z(C),title:`Change this subject's type to another type in force`,children:`change type`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>ne(!0),title:`View this chunk's edit history + diffs`,children:`history`}),!X&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,onClick:()=>void Tt(`up`),disabled:!wt.canUp,title:`Move this chunk up within its level`,children:`↑`}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void Tt(`down`),disabled:!wt.canDown,title:`Move this chunk down within its level`,children:`↓`})]}),!X&&(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:()=>re(!0),title:`Delete this chunk and its sub-chunks`,children:`delete`})]})]}),(0,l.jsxs)(pn,{storageKey:`loomcycle.explorer.doc-links-height`,className:`doc-content-split`,children:[(0,l.jsx)(`div`,{className:`doc-content-body`,children:C.type===`mermaid`?C.body?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Et,{code:C.body}),E===`markdown`&&(0,l.jsx)(`pre`,{className:`md-pre doc-mermaid-source`,children:(0,l.jsx)(`code`,{children:C.body})})]}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(empty diagram)`}):C.type===`image`||C.asset?ee?(0,l.jsxs)(`p`,{className:`doc-empty-body`,children:[`Image failed to load: `,ee]}):A?(0,l.jsxs)(`figure`,{className:`doc-image`,children:[(0,l.jsx)(`img`,{src:A,alt:wn(C)}),C.body&&(0,l.jsx)(`figcaption`,{children:C.body})]}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`Loading image…`}):E===`markdown`?O===null?(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`Assembling Markdown…`}):(0,l.jsx)(Sn,{source:O}):C.body?(0,l.jsx)(Sn,{source:C.body}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(empty chunk)`})}),(0,l.jsxs)(`div`,{className:`doc-links-pane`,children:[(0,l.jsx)(an,{edges:K,incomplete:q,documentId:e,selectedId:x,onSelectChunk:S,onOpenDocument:s?ft:void 0,onRuleStatement:$e}),(0,l.jsx)(nn,{documentId:e,selectedId:x,scope:t,browse:v,onSelectChunk:S,onOpenDocument:s?ft:void 0,refreshKey:ve,review:it})]})]})]}):(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Select a chunk on the left.`})})})]}),W&&a&&(0,l.jsx)(`div`,{className:`doc-assistant`,children:a({documentId:e,scope:t,subject:i?.subject,onChanged:J})}),I&&(0,l.jsx)(Dt,{chunk:I,scope:t,browse:v,onClose:()=>L(null),onSaved:J}),R&&(0,l.jsx)(Ot,{chunk:R,scope:t,browse:v,onClose:()=>z(null),onSaved:J}),te&&C&&(0,l.jsx)(bn,{chunkId:C.id,chunkTitle:C.title,scope:t,browse:v,onClose:()=>ne(!1)}),me&&Q&&(0,l.jsx)(Gt,{documentId:e,rootChunkId:Q,docType:G?.type,docStatus:G?.status,chunkStatuses:Be,scope:t,browse:v,onClose:()=>he(!1),onSaved:J}),B&&C&&(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:()=>re(!1),children:(0,l.jsxs)(`div`,{className:`modal chunk-delete-confirm`,onClick:e=>e.stopPropagation(),children:[(0,l.jsx)(`h3`,{children:`Delete chunk`}),(0,l.jsxs)(`p`,{className:`modal-context`,children:[`Delete “`,C.title||`(untitled)`,`” and all of its sub-chunks? This cannot be undone.`]}),(0,l.jsxs)(`div`,{className:`modal-buttons`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:()=>re(!1),children:`cancel`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:()=>void kt(),children:`delete`})]})]})})]})}function En(e,t=``){let n=e.get(t);if(!n)return[];let r=n.entries.map(n=>{let r=n.kind!==`directory`&&n.has_children===!0,i=(n.kind===`directory`||r)&&n.full_path.startsWith(`${t}/`);return{name:n.name,fullPath:n.full_path,kind:n.kind,resourceRef:n.resource_ref,...r?{hasChildren:r}:{},listing:i?e.get(n.full_path):void 0,children:i?En(e,n.full_path):[]}});return r.sort((e,t)=>{let n=e.kind===`directory`;return n===(t.kind===`directory`)?e.name.localeCompare(t.name):n?-1:1}),r}var Dn={directory:`📁`,document:`📄`,volume_mount:`💾`,memory_entry:`🧠`},On=`📝`;function kn(e){return e.kind===`document`&&e.name===`_annotation`}function An(e,t){if(e.kind===`directory`){let n=e.children.find(kn);return n&&Nn(n,t)?.brief||void 0}if(!kn(e))return Nn(e,t)?.brief||void 0}function jn(e){let{tree:t,root:n}=e;return!n||!n.loaded&&n.loading?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Loading…`})}):n.loaded&&t.length===0&&!n.nextCursor?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`This tree is empty. Create a folder or document to begin.`})}):(0,l.jsxs)(`ul`,{className:`tree path-tree`,children:[t.map(t=>(0,l.jsx)(Pn,{node:t,...e},t.fullPath)),(0,l.jsx)(Mn,{dir:``,listing:n,...e})]})}function Mn({dir:e,listing:t,onLoadMore:n,onRetry:r}){let i=[];return!t||t.loading&&t.entries.length===0?i.push((0,l.jsx)(`li`,{className:`node path-status`,children:(0,l.jsx)(`span`,{className:`path-implicit`,children:`loading…`})},`status`)):t.error?i.push((0,l.jsxs)(`li`,{className:`node path-status`,children:[e!==``&&(0,l.jsxs)(`span`,{className:`path-err`,children:[`failed to load: `,t.error]}),` `,(0,l.jsx)(`button`,{type:`button`,className:`path-more`,onClick:()=>r(e),children:`retry`})]},`status`)):t.loaded&&t.entries.length===0&&e!==``&&i.push((0,l.jsx)(`li`,{className:`node path-status`,children:(0,l.jsx)(`span`,{className:`path-implicit`,children:`empty`})},`status`)),t?.nextCursor&&!t.error&&i.push((0,l.jsx)(`li`,{className:`node path-status`,children:(0,l.jsx)(`button`,{type:`button`,className:`path-more`,disabled:t.loading,onClick:()=>n(e),children:t.loading?`loading…`:`Load more (${t.entries.length} shown)`})},`more`)),(0,l.jsx)(l.Fragment,{children:i})}function Nn(e,t){if(e.kind!==`document`||!t)return;let n=e.resourceRef;return n?.document_id?t.get(n.document_id):void 0}function Pn(e){let{node:t,expanded:n,onToggle:r,selectedPath:i,onSelect:a,summaries:o}=e,s=t.kind===`directory`||t.hasChildren===!0,c=s&&n.has(t.fullPath),u=i===t.fullPath,d=Nn(t,o),f=An(t,o),p=d&&d.color_enabled?lt(at(d.type,d.status,rt(d.color_scheme))):void 0;return(0,l.jsxs)(`li`,{className:`node path-node kind-${t.kind} ${u?`selected`:``}`,children:[(0,l.jsxs)(`div`,{className:`row path-row`,style:p,children:[(0,l.jsx)(`button`,{type:`button`,className:`tree-caret`,"aria-label":c?`collapse`:`expand`,"aria-expanded":s?c:void 0,disabled:!s,onClick:e=>{e.stopPropagation(),s&&r(t.fullPath)},children:s?c?`▼`:`▶`:`·`}),(0,l.jsxs)(`button`,{type:`button`,className:`path-link`,onClick:()=>a(t),title:f?`${t.fullPath}\n${f}`:t.fullPath,children:[(0,l.jsx)(`span`,{className:`path-kind-icon`,"aria-hidden":!0,children:kn(t)?On:Dn[t.kind]??`•`}),(0,l.jsx)(`span`,{className:`path-name`,children:t.name}),d?.type&&(0,l.jsx)(`span`,{className:`chunk-badge`,children:d.type}),d?.status&&(0,l.jsx)(`span`,{className:`chunk-badge chunk-status`,children:d.status})]}),f&&(0,l.jsx)(`span`,{className:`path-brief`,children:f})]}),c&&(0,l.jsxs)(`ul`,{className:`children path-children`,children:[t.children.map(t=>(0,l.jsx)(Pn,{...e,node:t},t.fullPath)),(0,l.jsx)(Mn,{...e,dir:t.fullPath,listing:t.listing})]})]})}var Fn=/^[A-Za-z0-9._-]+$/;function In(e,t){return`${e}/${t}`}function Ln(e,t){for(let n of e){if(n.fullPath===t)return n;let e=Ln(n.children,t);if(e)return e}}function Rn(e){let{theme:t,defaultScope:n,path:r,onPathChange:i,browse:a,principal:o,renderAssistant:s,renderNavigator:c,navigator:u,onError:d,onRegenerateAnnotation:f,canEditAnnotations:p}=e,m=q(e);return(0,l.jsx)(_e,{theme:t,dataLayer:m,children:(0,l.jsx)(zn,{defaultScope:n,path:r,onPathChange:i,browse:a,principal:o,renderAssistant:s,renderNavigator:c,navigator:u,onError:d,onRegenerateAnnotation:f,canEditAnnotations:p})})}function zn({defaultScope:e,path:t,onPathChange:n,browse:r,principal:i,renderAssistant:a,renderNavigator:o,navigator:s,onError:u,onRegenerateAnnotation:d,canEditAnnotations:f}){let p=H(),[g,_]=(0,c.useState)(e??`user`),[v,y]=(0,c.useState)(void 0),[b,x]=(0,c.useState)(null),[S,C]=(0,c.useState)(null),[w,T]=(0,c.useState)(null),[E,D]=(0,c.useState)(()=>new Set),O=t===void 0?v:t,k=(0,c.useRef)(n);(0,c.useEffect)(()=>{k.current=n},[n]);let A=(0,c.useRef)(u);(0,c.useEffect)(()=>{A.current=u},[u]);let[j,M]=(0,c.useState)([]),N=(0,c.useRef)(0),ee=(0,c.useRef)(void 0),P=(0,c.useCallback)(e=>{ee.current=e,k.current?.(e),y(e)},[]),F=(0,c.useCallback)(e=>{N.current++,M(e=>e.length>0?[]:e),P(e)},[P]);(0,c.useEffect)(()=>{t!==void 0&&t!==ee.current&&(N.current++,M(e=>e.length>0?[]:e))},[t]);let I=(0,c.useMemo)(()=>r&&(r.scopeId||r.tenant)?{scopeId:r.scopeId,tenant:r.tenant}:void 0,[r?.scopeId,r?.tenant]),L=(0,c.useMemo)(()=>new fe(p,g,I),[p,g,I]),R=(0,c.useSyncExternalStore)(L.subscribe,L.getSnapshot),z=(0,c.useCallback)(e=>{A.current?.(e)},[]),[te,ne]=(0,c.useState)(()=>o?m(globalThis.localStorage):`tree`),B=!!o&&te===`stars`,re=(0,c.useCallback)(e=>{ne(e),h(globalThis.localStorage,e),e===`tree`&&V(!1)},[]),[ie,V]=(0,c.useState)(!1),[ae,oe]=(0,c.useState)(0);(0,c.useEffect)(()=>{o&&s&&re(s)},[s]);let[se,ce]=(0,c.useState)(),[le,de]=(0,c.useState)(),W=(0,c.useCallback)((e,t)=>(oe(e=>e+1),L.invalidate(e,t)),[L]),[me,he]=(0,c.useState)(()=>new Map),K=(0,c.useRef)(new Set),ge=(0,c.useRef)(0),q=(0,c.useCallback)(()=>{ge.current++,K.current=new Set,he(new Map)},[]),_e=(0,c.useRef)(!0);(0,c.useEffect)(()=>{_e.current?_e.current=!1:(F(void 0),x(null),D(new Set),q()),L.loadDir(``).catch(z)},[L,F,q,z]),(0,c.useEffect)(()=>{for(let e of E)R.has(e)||L.loadDir(e).catch(z)},[L,E,R,z]);let xe=(0,c.useRef)(null);(0,c.useEffect)(()=>{let e=xe.current!==null&&xe.current!==L;if(xe.current=L,!O||e)return;let t=U(O).filter(e=>e!==``);D(e=>{if(t.every(t=>e.has(t)))return e;let n=new Set(e);return t.forEach(e=>n.add(e)),n}),L.reveal(O).catch(z)},[L,O,z]),(0,c.useEffect)(()=>{let e=[];for(let t of R.values())for(let n of pe(t.entries))K.current.has(n)||(K.current.add(n),e.push(n));let t=ge.current;for(let n=0;n<e.length;n+=500)p.documentsSummary({documentIds:e.slice(n,n+500)},g,I).then(e=>{ge.current===t&&he(t=>{let n=new Map(t);for(let t of e.documents??[])n.set(t.document_id,t);return n})}).catch(()=>{})},[p,R,g,I]);let Ce=(0,c.useMemo)(()=>En(R),[R]),Te=(0,c.useCallback)(async()=>{x(null),q(),oe(e=>e+1),await L.refresh(E).catch(z),O&&await L.reveal(O).catch(z)},[L,E,O,q,z]),Ee=(0,c.useCallback)(e=>{D(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),ke=(0,c.useCallback)(e=>L.loadMore(e).catch(z),[L,z]),je=(0,c.useCallback)(e=>{(L.getSnapshot().get(e)?.loaded?L.loadMore(e):L.loadDir(e)).catch(z)},[L,z]),J=(0,c.useMemo)(()=>O?Ln(Ce,O):void 0,[Ce,O]),Me=R.get(``)?.error,Ne=J?.kind===`directory`?J.fullPath:void 0,[Pe,Fe]=(0,c.useState)(null);(0,c.useEffect)(()=>{if(!Ne||!p.pathIsStored)return;let e=!1;return p.pathIsStored(Ne,g,I).then(t=>{e||Fe({path:Ne,explicit:t})},()=>{}),()=>{e=!0}},[p,Ne,g,I]);let Ie=J?J.kind===`directory`?Pe?.path===J.fullPath?Pe.explicit?`yes`:`implicit (no entry)`:void 0:`yes`:void 0,Le=(0,c.useMemo)(()=>J?J.kind===`directory`?J.fullPath:ue(J.fullPath):``,[J]),Y=Le||`/`,Re=(0,c.useCallback)(()=>{C({title:`New folder in ${Y}`,fields:[{key:`name`,label:`Folder name`,placeholder:`e.g. launches`}],submitLabel:`Create`,onSubmit:async e=>{let t=e.name.trim();if(!Fn.test(t))throw Error(`name may contain only [A-Za-z0-9._-]`);let n=In(Le,t);await p.pathMkdir(n,g,I),await W(n).catch(z),F(n)}})},[p,L,Le,Y,g,I,z,F]),X=(0,c.useCallback)(()=>{C({title:`New document in ${Y}`,fields:[{key:`name`,label:`Path name`,placeholder:`e.g. launch-plan`},{key:`title`,label:`Title`,placeholder:`e.g. Launch Plan`}],submitLabel:`Create`,onSubmit:async e=>{let t=e.name.trim();if(!Fn.test(t))throw Error(`name may contain only [A-Za-z0-9._-]`);let n=e.title.trim()||t,r=In(Le,t);await p.documentCreate(n,r,g,I),await W(r).catch(z),F(r)}})},[p,L,Le,Y,g,I,z,F]),Z=(0,c.useCallback)(()=>{J&&C({title:`Rename / move ${J.fullPath}`,fields:[{key:`to`,label:`New path`,value:J.fullPath}],submitLabel:`Move`,onSubmit:async e=>{let t=e.to.trim();if(!t.startsWith(`/`))throw Error(`path must start with /`);await p.pathMv(J.fullPath,t,g,I),await Promise.all([W(J.fullPath,{dropSubtree:!0}),W(t)]).catch(z),F(t)}})},[p,L,J,g,I,z,F]),Q=(0,c.useCallback)(()=>{if(!J)return;if(J.kind===`document`){let e=J.resourceRef?.document_id;C({title:`Delete document ${J.fullPath}`,message:`This deletes the document, all its chunks, and its path entry. This cannot be undone.`,fields:[],submitLabel:`Delete`,danger:!0,onSubmit:async()=>{if(!e)throw Error(`this document dirent has no document_id`);await p.documentDelete(e,g,I),await W(J.fullPath).catch(z),F(void 0)}});return}let e=J;x(null),(async()=>{let t;try{t=await G(p,e.fullPath,g,I)}catch(t){x(`could not list ${e.fullPath} for delete: ${t instanceof Error?t.message:String(t)}`);return}let n=pe(t);C({title:`Delete branch ${e.fullPath}`,message:t.length===0?`This removes the (empty) folder.`:`This removes the folder and everything under it`+(n.length>0?` — including ${n.length} document(s), whose chunks are deleted.`:`.`),fields:[],submitLabel:`Delete`,danger:!0,onSubmit:async()=>{for(let e of n)await p.documentDelete(e,g,I);await p.pathRm(e.fullPath,g,!0,I),await W(e.fullPath,{dropSubtree:!0}).catch(z),F(void 0)}})})()},[p,L,J,g,I,z,F]),ze=J&&(J.kind===`directory`||J.kind===`document`),Be=!!p.documentsTransfer&&!!ze,Ve=(0,c.useCallback)(()=>{if(J){if(J.kind===`document`){let e=J.resourceRef?.document_id;if(!e){x(`this document entry has no document_id`);return}T({documentId:e,fromPath:J.fullPath})}else T({underPath:J.fullPath,fromPath:J.fullPath})}},[J]),He=(0,c.useCallback)(e=>{e.op===`move`?(W(e.from,{dropSubtree:!0}).catch(z),M([]),F(void 0)):e.toScope===g&&W(e.to).catch(z)},[W,z,g,F]),$=(0,c.useMemo)(()=>{if(j.length>0)return j[j.length-1];if(J?.kind===`document`)return{documentId:J.resourceRef?.document_id??``,path:J.fullPath,title:J.name}},[j,J]),Ue=(0,c.useCallback)((e,t)=>{let n=++N.current,r=we(L.getSnapshot(),e.documentId);M(ve(j,{...t,path:$?.path},{...e,path:r})),P(r),!r&&p.documentPath&&p.documentPath(e.documentId,g,I).then(t=>{t&&N.current===n&&(M(n=>be(n,e.documentId,{path:t})),P(t))},()=>{})},[p,L,j,$?.path,g,I,P]),We=(0,c.useCallback)(e=>{let t=ye(j,e);t!==j&&(N.current++,M(t),P(t[t.length-1].path))},[j,P]),Ge=(0,c.useCallback)((e,t)=>M(n=>be(n,e,{title:t})),[]),Ke=(0,c.useCallback)(e=>{de(t=>({documentId:e.documentId,chunkId:e.chunkId,seq:(t?.seq??0)+1})),$?.documentId!==e.documentId&&(e.path?F(e.path):(N.current++,M([{documentId:e.documentId,chunkId:e.chunkId}]),P(void 0)))},[$?.documentId,F,P]),qe=(0,c.useMemo)(()=>({scope:g,browse:I,selection:{documentId:$?.documentId,chunkId:se&&se.documentId===$?.documentId?se.chunkId:void 0,path:$?.path},onSelect:Ke,reloadToken:ae,maximized:ie,onToggleMaximize:()=>V(e=>!e),subject:i?.subject}),[g,I,$?.documentId,$?.path,se,Ke,ae,ie,i?.subject]),Je=le&&$&&le.documentId===$.documentId?le:void 0,Ye=!!$?.path&&J?.kind===`document`&&J.fullPath===$.path;return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(Ae,{className:B?`paths-view paths-view--stars`:`paths-view`,defaultLeftWidth:B?720:420,minLeftWidth:280,minRightWidth:300,storageKey:B?`loomcycle.explorer.split.stars`:`loomcycle.explorer.split.paths`,hideRight:B&&ie,children:[(0,l.jsxs)(`div`,{className:`left`,children:[(0,l.jsxs)(`div`,{className:`paths-toolbar`,children:[(0,l.jsxs)(`label`,{className:`paths-scope`,children:[(0,l.jsx)(`span`,{children:`scope`}),(0,l.jsxs)(`select`,{value:g,onChange:e=>_(e.target.value),children:[(0,l.jsx)(`option`,{value:`user`,children:`user`}),(0,l.jsx)(`option`,{value:`agent`,children:`agent`}),(0,l.jsx)(`option`,{value:`tenant`,children:`tenant`})]})]}),o&&(0,l.jsxs)(`div`,{className:`paths-nav-switch`,role:`group`,"aria-label":`Navigator`,children:[(0,l.jsx)(`button`,{type:`button`,"aria-pressed":!B,className:B?void 0:`active`,onClick:()=>re(`tree`),title:`Browse the Path tree`,children:`tree`}),(0,l.jsx)(`button`,{type:`button`,"aria-pressed":B,className:B?`active`:void 0,onClick:()=>re(`stars`),title:`Browse the scope as a 3D star map`,children:`stars`})]}),(0,l.jsxs)(`div`,{className:`paths-toolbar-actions`,children:[!B&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,onClick:Re,title:`New folder in ${Y}`,children:`+ folder`}),(0,l.jsx)(`button`,{type:`button`,onClick:X,title:`New document in ${Y}`,children:`+ document`})]}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void Te(),title:`Reload the tree`,children:`↻`})]})]}),!B&&(0,l.jsxs)(`p`,{className:`paths-context`,children:[`new items → `,(0,l.jsx)(`code`,{children:Y}),I?.scopeId&&(0,l.jsxs)(l.Fragment,{children:[` · `,`subject `,(0,l.jsx)(`code`,{children:I.scopeId})]}),I?.tenant&&(0,l.jsxs)(l.Fragment,{children:[` · `,`tenant `,(0,l.jsx)(`code`,{children:I.tenant})]})]}),(b||Me)&&(0,l.jsx)(`div`,{className:`paths-err`,children:b||Me}),B&&o?(0,l.jsx)(`div`,{className:`paths-navigator`,children:o(qe)}):(0,l.jsx)(jn,{tree:Ce,root:R.get(``),expanded:E,onToggle:Ee,onLoadMore:ke,onRetry:je,selectedPath:O,onSelect:e=>F(e.fullPath),summaries:me})]}),(0,l.jsx)(`div`,{className:`right`,children:$?(0,l.jsxs)(`div`,{className:`paths-doc`,children:[(0,l.jsx)(De,{trail:j,onJump:We}),(0,l.jsxs)(`div`,{className:`paths-doc-head`,children:[$.path?(0,l.jsx)(`code`,{className:`paths-doc-path`,children:$.path}):(0,l.jsxs)(`span`,{className:`paths-doc-path paths-doc-unfiled`,title:`Opened by id — no entry for this document was found in the Path tree`,children:[Se($),` `,(0,l.jsx)(`em`,{children:`· opened by id, not in the tree`})]}),Ye&&(0,l.jsxs)(`div`,{className:`paths-detail-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:Z,children:`rename / move`}),Be&&(0,l.jsx)(`button`,{type:`button`,onClick:Ve,title:`Copy or move to another scope`,children:`copy / move to…`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:Q,children:`delete`})]})]}),(0,l.jsx)(Tn,{documentId:$.documentId,scope:g,titleHint:$.title,browse:I,principal:i,renderAssistant:a,initialChunkId:$.chunkId??Je?.chunkId,onOpenDocument:Ue,onTitle:Ge,onChunkSelect:e=>ce({documentId:$.documentId,chunkId:e}),focusChunk:Je,onRegenerateAnnotation:d,canEditAnnotations:f,onAnnotationChanged:()=>void Te()},j.length)]}):J?(0,l.jsxs)(`div`,{className:`paths-detail`,children:[(0,l.jsxs)(`h2`,{children:[(0,l.jsx)(`span`,{className:`paths-detail-kind`,children:J.kind}),(0,l.jsx)(`code`,{children:J.fullPath})]}),(0,l.jsxs)(`dl`,{className:`paths-detail-meta`,children:[(0,l.jsx)(`dt`,{children:`scope`}),(0,l.jsx)(`dd`,{children:g}),Ie&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`stored`}),(0,l.jsx)(`dd`,{children:Ie})]})]}),ze?(0,l.jsxs)(`div`,{className:`paths-detail-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:Z,children:`rename / move`}),Be&&(0,l.jsx)(`button`,{type:`button`,onClick:Ve,title:`Copy or move to another scope`,children:`copy / move to…`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:Q,children:`delete`})]}):(0,l.jsxs)(`p`,{className:`paths-readonly`,children:[`Read-only — `,J.kind,` entries are managed by their own tool.`]})]}):(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Select a path on the left, or create a folder / document.`})})})]}),S&&(0,l.jsx)(Bn,{state:S,onClose:()=>C(null)}),w&&(0,l.jsx)(Oe,{data:p,scope:g,browse:I,documentId:w.documentId,underPath:w.underPath,fromPath:w.fromPath,onClose:()=>T(null),onDone:He})]})}function Bn({state:e,onClose:t}){let[n,r]=(0,c.useState)(()=>Object.fromEntries(e.fields.map(e=>[e.key,e.value??``]))),[i,a]=(0,c.useState)(!1),[o,s]=(0,c.useState)(null);return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:t,children:(0,l.jsxs)(`form`,{className:`modal`,onClick:e=>e.stopPropagation(),onSubmit:async r=>{r.preventDefault(),a(!0),s(null);try{await e.onSubmit(n),t()}catch(e){s(e instanceof Error?e.message:String(e)),a(!1)}},children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsx)(`h3`,{children:e.title}),(0,l.jsxs)(`div`,{className:`modal-buttons modal-buttons-top`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:t,disabled:i,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:e.danger?`danger`:`primary`,disabled:i,children:i?`working…`:e.submitLabel})]})]}),e.message&&(0,l.jsx)(`p`,{className:`modal-context`,children:e.message}),e.fields.map((e,t)=>(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:e.label}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:n[e.key],placeholder:e.placeholder,autoFocus:t===0,onChange:t=>r(n=>({...n,[e.key]:t.target.value}))})]},e.key)),o&&(0,l.jsx)(`div`,{className:`modal-err`,children:o})]})})}function Vn(e){let{documentId:t,scope:n,browse:r,theme:i}=e,a=q(e);return(0,l.jsx)(_e,{theme:i,dataLayer:a,children:(0,l.jsx)(Hn,{...e},`${n}:${t}:${r?.scopeId??``}:${r?.tenant??``}`)})}function Hn({documentId:e,chunkId:t,scope:n,titleHint:r,browse:i,principal:a,renderAssistant:o,onOpenDocument:s,onRegenerateAnnotation:u,canEditAnnotations:d}){let[f,p]=(0,c.useState)([]),m=f[f.length-1],[h,g]=(0,c.useState)(),_=(0,c.useRef)(t);(0,c.useEffect)(()=>{t!==_.current&&(_.current=t,f.length>0?(g(void 0),p([])):g(e=>({chunkId:t,seq:(e?.seq??0)+1})))},[t]);let v=(0,c.useCallback)((e,t)=>{s?s(e,t):p(n=>ve(n,t,e))},[s]),y=(0,c.useCallback)(e=>p(t=>ye(t,e)),[]),b=(0,c.useCallback)((e,t)=>p(n=>be(n,e,{title:t})),[]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(De,{trail:f,onJump:y}),(0,l.jsx)(Tn,{documentId:m?.documentId??e,scope:n,titleHint:m?m.title:r,browse:i,principal:a,renderAssistant:o,initialChunkId:m?m.chunkId:t,focusChunk:m?void 0:h,onOpenDocument:v,onTitle:b,onRegenerateAnnotation:u,canEditAnnotations:d},f.length)]})}exports.ABSTRACT_MAX_CHARS=D,exports.BRIEF_MAX_CHARS=E,exports.DEFAULT_SCHEME=tt,exports.DocumentViewer=Vn,exports.EDGE_PAGE_CAP=Pe,exports.PathExplorer=Rn,exports.QUEUE_CHANGED_RETRIES=Ue,exports.RULING_CHUNK=$,exports.RequestError=K,exports.annotationsApply=T,exports.assetFetchFromConnection=he,exports.chunkColor=ot,exports.chunkCount=Je,exports.chunkInheritsDocColor=st,exports.chunkRowStyle=dt,exports.createLoomcycleClient=me,exports.dataLayerFromClient=ie,exports.docColor=at,exports.effectiveScheme=rt,exports.hexToTint=ct,exports.isQueueChanged=Ge,exports.jsonPostFromConnection=ge,exports.loadDocumentEdges=Fe,exports.runRuling=Ke,exports.setAnnotationInput=P,exports.tintStyle=lt,exports.transferInput=y,exports.undoRulings=qe,exports.washStyle=ut;
4
+ `]},t)})})}var Wn=/^<br\s*\/?>$/i;function Gn(e){let t=e.children;if(t)for(let e=0;e<t.length;e++){let n=t[e];n.type===`html`&&Wn.test(n.value??``)?t[e]={type:`break`}:Gn(n)}}function Kn(){return e=>Gn(e)}function qn({source:e}){return(0,l.jsx)(`div`,{className:`md`,children:(0,l.jsx)(f.default,{remarkPlugins:[p.default,Kn],components:Jn,children:e})})}var Jn={a({href:e,children:t}){let n=e??``,r=/^https?:\/\//i.test(n);return(0,l.jsx)(`a`,{href:n,target:r?`_blank`:void 0,rel:r?`noopener noreferrer`:void 0,children:t})},pre({children:e}){return(0,l.jsx)(l.Fragment,{children:e})},code({className:e,children:t}){let n=/language-(\w+)/.exec(e??``)?.[1],r=String(t??``);return n===`mermaid`?(0,l.jsx)(fn,{code:r.replace(/\n$/,``)}):n||r.includes(`
5
+ `)?(0,l.jsx)(`pre`,{className:`md-pre`,children:(0,l.jsx)(`code`,{className:e,children:t})}):(0,l.jsx)(`code`,{children:t})}};function Yn({groups:e,busy:t,label:n=`More actions`}){let r=e.filter(e=>e.length>0),i=r.flat(),[a,o]=(0,c.useState)(null),s=a!==null,u=(0,c.useRef)(null),d=(0,c.useRef)(null),f=(0,c.useRef)([]),p=(0,c.useId)();(0,c.useEffect)(()=>{a!==null&&f.current[a]?.focus()},[a]),(0,c.useEffect)(()=>{if(!s)return;let e=e=>{u.current&&!u.current.contains(e.target)&&o(null)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[s]);let m=()=>{o(null),d.current?.focus()},h=e=>f.current[(e+i.length)%i.length]?.focus(),g=(e,t)=>{switch(e.key){case`ArrowDown`:e.preventDefault(),h(t+1);break;case`ArrowUp`:e.preventDefault(),h(t-1);break;case`Home`:e.preventDefault(),h(0);break;case`End`:e.preventDefault(),h(i.length-1);break;case`Escape`:e.preventDefault(),m();break;case`Tab`:o(null)}},_=0;return(0,l.jsxs)(`div`,{className:`doc-more-menu`,ref:u,children:[(0,l.jsx)(`button`,{ref:d,type:`button`,className:`doc-more-button${s?` active`:``}`,title:t?`${t}…`:n,"aria-label":n,"aria-haspopup":`menu`,"aria-expanded":s,"aria-controls":s?p:void 0,"aria-busy":t?!0:void 0,disabled:!!t||i.length===0,onClick:()=>o(s?null:0),onKeyDown:e=>{e.key===`ArrowDown`?(e.preventDefault(),o(0)):e.key===`ArrowUp`?(e.preventDefault(),o(i.length-1)):e.key===`Escape`&&s&&(e.preventDefault(),o(null))},children:t?(0,l.jsxs)(`span`,{className:`doc-more-busy`,children:[t,`…`]}):(0,l.jsx)(Xn,{})}),s&&(0,l.jsx)(`div`,{className:`doc-more-list`,role:`menu`,id:p,"aria-label":n,children:r.map((e,t)=>(0,l.jsxs)(`div`,{className:`doc-more-group`,role:`group`,children:[t>0&&(0,l.jsx)(`div`,{className:`doc-more-rule`,role:`separator`}),e.map(e=>{let t=_++;return(0,l.jsx)(`button`,{ref:e=>{f.current[t]=e},type:`button`,role:`menuitem`,tabIndex:-1,className:e.danger?`danger`:void 0,title:e.title,"aria-disabled":e.disabled||void 0,"data-key":e.key,onClick:()=>{e.disabled||(m(),e.run())},onKeyDown:e=>g(e,t),children:e.label},e.key)})]},t))})]})}function Xn(){return(0,l.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,fill:`currentColor`,children:[(0,l.jsx)(`circle`,{cx:`3.5`,cy:`8`,r:`1.4`}),(0,l.jsx)(`circle`,{cx:`8`,cy:`8`,r:`1.4`}),(0,l.jsx)(`circle`,{cx:`12.5`,cy:`8`,r:`1.4`})]})}function Zn({kind:e}){return(0,l.jsx)(`svg`,{className:`pane-svg`,width:`16`,height:`16`,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,focusable:`false`,children:Qn[e]})}var Qn={tree:(0,l.jsx)(`path`,{d:`M1.75 4.25v8a1 1 0 0 0 1 1h10.5a1 1 0 0 0 1-1v-6.5a1 1 0 0 0-1-1H8L6.5 3.25H2.75a1 1 0 0 0-1 1z`}),outline:(0,l.jsx)(`path`,{d:`M2.5 3.5h.01M5 3.5h8.5M4.5 8h.01M7 8h6.5M4.5 12.5h.01M7 12.5h6.5`}),annotation:(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`path`,{d:`M2.75 2.75h10.5v8h-6l-3 2.5v-2.5h-1.5z`}),(0,l.jsx)(`path`,{d:`M5.5 5.75h5M5.5 8h3`})]}),references:(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`path`,{d:`M6.75 9.25a2.75 2.75 0 0 0 3.9 0l2-2a2.75 2.75 0 0 0-3.9-3.9l-.5.5`}),(0,l.jsx)(`path`,{d:`M9.25 6.75a2.75 2.75 0 0 0-3.9 0l-2 2a2.75 2.75 0 0 0 3.9 3.9l.5-.5`})]}),classification:(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`path`,{d:`M8.5 1.75h5v5l-6.75 6.75-5-5z`}),(0,l.jsx)(`circle`,{cx:`11`,cy:`4.25`,r:`0.75`})]}),history:(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`circle`,{cx:`8`,cy:`8`,r:`5.75`}),(0,l.jsx)(`path`,{d:`M8 5v3.25l2 1.25`})]}),search:(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`circle`,{cx:`7`,cy:`7`,r:`4.25`}),(0,l.jsx)(`path`,{d:`M10.25 10.25l3.5 3.5`})]}),"collapse-left":(0,l.jsx)(`path`,{d:`M10 3.5L5.5 8l4.5 4.5`}),"collapse-right":(0,l.jsx)(`path`,{d:`M6 3.5L10.5 8 6 12.5`}),close:(0,l.jsx)(`path`,{d:`M4 4l8 8M12 4l-8 8`})};function $n({label:e,side:t,onClick:n,shortcut:r}){return(0,l.jsx)(`button`,{type:`button`,className:`pane-collapse`,onClick:n,"aria-label":`Collapse the ${e}`,title:`Collapse the ${e}${r?` (${r})`:``}`,"aria-keyshortcuts":r,children:(0,l.jsx)(Zn,{kind:t===`left`?`collapse-left`:`collapse-right`})})}function er({label:e,icon:t,count:n,countLabel:r,onExpand:i,shortcut:a,side:o}){let s=n!==void 0&&r?`, ${n} ${r}`:``;return(0,l.jsx)(`div`,{className:`pane-rail pane-rail-${o}`,children:(0,l.jsxs)(`button`,{type:`button`,className:`pane-rail-button`,onClick:i,"aria-label":`Show the ${e}${s}`,title:`Show the ${e}${a?` (${a})`:``}`,"aria-keyshortcuts":a,"aria-expanded":!1,children:[(0,l.jsx)(Zn,{kind:t}),n!==void 0&&(0,l.jsx)(`span`,{className:`pane-rail-count`,children:n})]})})}function tr(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function nr(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function rr(e,t=!1){let[n,r]=(0,c.useState)(()=>{let n=tr(e);return n===null?t:n===`1`});return[n,(0,c.useCallback)(t=>r(n=>{let r=typeof t==`function`?t(n):t;return nr(e,r?`1`:`0`),r}),[e])]}function ir(e,t){let[n,r]=(0,c.useState)(()=>{let n=tr(e);return n!==null&&t.includes(n)?n:null});return[n,(0,c.useCallback)(t=>r(n=>{let r=typeof t==`function`?t(n):t;return nr(e,r),r}),[e])]}function ar(e){let t=e;if(!t||!t.tagName)return!1;let n=t.tagName;return n===`INPUT`||n===`TEXTAREA`||n===`SELECT`||t.isContentEditable===!0}function or(e,t){if(e.defaultPrevented||e.ctrlKey||e.metaKey||e.altKey||ar(e.target))return!1;let n=e.target;return!t||n&&n.closest?.(`.modal-overlay`)?!1:n===document.body||n===document.documentElement||!!n&&t.contains(n)}function sr(e,t){let[n,r]=(0,c.useState)(!1);return(0,c.useEffect)(()=>{let n=e.current;if(!n)return;let i=e=>r(e>0&&e<t);if(i(n.getBoundingClientRect().width),typeof ResizeObserver>`u`)return;let a=new ResizeObserver(e=>{for(let t of e)i(t.contentRect.width)});return a.observe(n),()=>a.disconnect()},[e,t]),n}function cr(e){let t=e.fields??{};return typeof t.alt==`string`&&t.alt.trim()!==``?t.alt:e.title||`image`}var lr=8,ur=[`annotation`,`references`,`classification`,`history`],dr={annotation:`annotation`,references:`references`,classification:`classification`,history:`history`},fr=`loomcycle.explorer.panel`,pr=`loomcycle.explorer.collapsed.outline`,mr=640,hr=960,gr=1200;function _r({documentId:e,scope:t,titleHint:n,browse:r,principal:i,renderAssistant:a,initialChunkId:o,onOpenDocument:s,onTitle:u,onChunkSelect:d,focusChunk:f,onRegenerateAnnotation:p,canEditAnnotations:m,onAnnotationChanged:h,pathLabel:g,documentActions:v}){let y=ue(),b=(0,c.useMemo)(()=>r&&(r.scopeId||r.tenant)?{scopeId:r.scopeId,tenant:r.tenant}:void 0,[r?.scopeId,r?.tenant]),[x,S]=(0,c.useState)([]),[C,w]=(0,c.useState)(void 0),[T,D]=(0,c.useState)(()=>new Map),[O,k]=(0,c.useState)(()=>new Map),[ee,A]=(0,c.useState)(()=>new Set),te=(0,c.useRef)(null),[N,P]=(0,c.useState)(null),[F,I]=(0,c.useState)(null),[L,R]=(0,c.useState)(null),[ne,re]=(0,c.useState)(!1),[z,B]=(0,c.useState)(null),[ie,ae]=(0,c.useState)(!1),[V,oe]=(0,c.useState)(void 0),[se,ce]=(0,c.useState)(null),[le,de]=(0,c.useState)(0),[fe,pe]=(0,c.useState)(!1),[H,me]=(0,c.useState)(null),[he,ge]=(0,c.useState)(!1),[_e,ve]=(0,c.useState)([]),[U,ye]=(0,c.useState)(!1),[be,xe]=(0,c.useState)(0),[Se,W]=(0,c.useState)(0),[we,Te]=(0,c.useState)(void 0),[Ee,De]=(0,c.useState)([]),[Oe,ke]=(0,c.useState)([]),[G,Ae]=(0,c.useState)(0),[je,Me]=ir(fr,ur),[Ne,Pe]=(0,c.useState)(!1),Fe=(0,c.useCallback)(e=>{Pe(!0),Me(e)},[Me]),[Ie,Le]=rr(pr),Re=(0,c.useRef)(null),ze=sr(Re,mr),[Ve,He]=(0,c.useState)(!1),Ue=ze?!Ve:Ie,Ge=sr(Re,Ue?hr:gr),Ke=(0,c.useCallback)(e=>ze?He(!e):Le(e),[ze,Le]),[Ye,Ze]=(0,c.useState)(void 0),[Qe,$e]=(0,c.useState)(null),K=(0,c.useCallback)(()=>de(e=>e+1),[]),et=(0,c.useCallback)(()=>{D(new Map),k(new Map),de(e=>e+1)},[]),tt=(0,c.useRef)(o);tt.current=o;let nt=(0,c.useRef)(u);nt.current=u;let rt=(0,c.useRef)(null),it=(0,c.useRef)(null),at=(0,c.useRef)(null),[ot,st]=(0,c.useState)(0),q=(0,c.useCallback)(e=>{e&&(it.current=e,w(e),st(e=>e+1),He(!1))},[]),ct=(0,c.useMemo)(()=>$t(x),[x]),lt=(0,c.useMemo)(()=>{let e=[],t=(n,r)=>n.forEach(n=>{e.push({row:n.row,depth:r}),t(n.children,r+1)});return t(ct,0),e},[ct]),J=(0,c.useMemo)(()=>x.find(e=>!e.parent_id)?.title||n||`document`,[x,n]),ut=C&&T.get(C)||null,Y=(0,c.useMemo)(()=>H?.root_chunk_id??x.find(e=>!e.parent_id)?.id,[H,x]),mt=Y&&T.get(Y)||null,ht=(0,c.useRef)(d);ht.current=d,(0,c.useEffect)(()=>{C&&ht.current?.(C===Y?void 0:C)},[C,Y]);let gt=(0,c.useMemo)(()=>[...new Set(x.map(e=>e.status).filter(e=>!!e))],[x]),_t=!!H?.color_enabled,yt=_t?Nt(H?.color_scheme):void 0,X=(0,c.useMemo)(()=>{let e=new Set;for(let t of _e)e.add(t.from_id),e.add(t.to_id);return e},[_e]),bt=(0,c.useMemo)(()=>_t?Ft(H?.type,H?.status,Nt(H?.color_scheme)):void 0,[_t,H?.type,H?.status,H?.color_scheme]),xt=(0,c.useMemo)(()=>zt(bt),[bt]),St=(0,c.useMemo)(()=>x.find(e=>!e.parent_id),[x]),Ct=H?.type??St?.type,wt=H?.status??St?.status,Tt=(0,c.useRef)(C);Tt.current=C,(0,c.useEffect)(()=>{let n=!1;return ae(!0),B(null),ce(null),y.documentQueryChunks(e,t,b).then(r=>{if(n)return;let i=r.chunks??[];S(i),oe(`${t}:${e}`),it.current===null&&!Tt.current&&q(Be(i,tt.current))}).catch(e=>{n||(S([]),ce(e instanceof Error?e.message:String(e)))}).finally(()=>!n&&ae(!1)),()=>{n=!0}},[y,e,t,le,b,q]);let Et=(0,c.useRef)(T);Et.current=T,(0,c.useEffect)(()=>{let n=lt.map(e=>e.row).filter(t=>t.document_id===e&&Et.current.get(t.id)?.revision!==t.revision);if(n.length===0)return;let r=!1;return(async()=>{for(let e=0;e<n.length&&!r;e+=lr){let i=n.slice(e,e+lr),a=await Promise.allSettled(i.map(e=>y.documentGetChunk(e.id,t,b)));if(r)return;D(e=>{let t=new Map(e);return a.forEach((e,n)=>e.status===`fulfilled`&&t.set(i[n].id,e.value)),t}),k(e=>{let t=new Map(e);return a.forEach((e,n)=>{e.status===`rejected`?t.set(i[n].id,e.reason instanceof Error?e.reason.message:String(e.reason)):t.delete(i[n].id)}),t})}})(),()=>{r=!0}},[y,lt,e,t,b]);let Dt=!ie&&(se!==null||V===`${t}:${e}`&&x.length===0),kt=(0,c.useMemo)(()=>x.find(t=>!t.parent_id&&t.document_id===e)?.title,[x,e]);(0,c.useEffect)(()=>{kt&&nt.current?.(e,kt)},[e,kt]),(0,c.useEffect)(()=>{let n=!1;return y.documentGet(e,t,b).then(e=>!n&&me(e)).catch(()=>!n&&me(null)),()=>{n=!0}},[y,e,t,le,b]),(0,c.useEffect)(()=>{let n=!1;return Xe(y,e,t,b).then(e=>{n||(ve(e.edges),ye(e.incomplete))}).catch(()=>{n||(ve([]),ye(!1))}),()=>{n=!0}},[y,e,t,le,b,be]),(0,c.useEffect)(()=>{!y.documentAcceptClassification||!mt||mt.document_id!==e?Te(void 0):Te(mt.fields)},[y,e,mt]);let jt=(0,c.useMemo)(()=>{if(!y.documentAcceptClassification)return 0;let e=vt(we);return e?+!!e.proposedType+e.proposedTags.length+e.statementCount:0},[y,we]),Mt=jt>0;(0,c.useEffect)(()=>{if(!Y||!E(t)){De([]);return}let e=!1;return j(y,Y,t,b).then(t=>!e&&De(t)).catch(()=>!e&&De([])),()=>{e=!0}},[y,Y,t,le,b,G]);let Pt=je===`annotation`;(0,c.useEffect)(()=>{if(!Pt||!C||C===Y||!E(t)){ke([]);return}let e=!1;return ke([]),j(y,C,t,b).then(t=>!e&&ke(t)).catch(()=>!e&&ke([])),()=>{e=!0}},[y,Pt,C,Y,t,le,b,G]);let It=(0,c.useMemo)(()=>{if(m&&y.documentSetAnnotation&&E(t))return e=>async(n,r,i)=>{await y.documentSetAnnotation({id:e,level:n,brief:r,abstract:i},t,b),Ae(e=>e+1),h?.()}},[y,t,b,m,h]),Lt=(0,c.useMemo)(()=>{if(p&&E(t))return n=>async r=>{let i=[...Ee,...Oe].find(e=>e.chunk_id===n&&e.level===r)?.folder;try{await p({documentId:e,chunkId:n,level:r,scope:t,...i?{folder:i}:{}})}finally{Ae(e=>e+1),h?.()}}},[p,e,t,Ee,Oe,h]),Rt=Ee.find(e=>e.level===`document`)??Ee.find(e=>e.level===`path`),Bt=(0,c.useMemo)(()=>Oe.filter(e=>e.chunk_id===C),[Oe,C]),Vt=!!Y&&(Ee.length>0||!!It||!!Lt),Ht=(0,c.useMemo)(()=>{if(y.documentAcceptStatement&&y.documentRejectStatement)return async(e,n,r)=>{n?await y.documentAcceptStatement(e,t,b,r):await y.documentRejectStatement(e,r??``,t,b),xe(e=>e+1)}},[y,t,b]),Ut=(0,c.useMemo)(()=>dt(y,t),[y,t]),Wt=(0,c.useMemo)(()=>ft(_e,e),[_e,e]),Q=(0,c.useCallback)(()=>xe(e=>e+1),[]),Gt=(0,c.useMemo)(()=>pt(Ut,Wt,U,Q),[Ut,Wt,U,Q]),Kt=(0,c.useMemo)(()=>C?_e.filter(e=>e.from_id===C||e.to_id===C).length:0,[_e,C]),Jt=f?.seq,Yt=(0,c.useRef)(f);Yt.current=f;let Zt=(0,c.useRef)(Y);Zt.current=Y;let Qt=(0,c.useRef)(x);Qt.current=x,(0,c.useEffect)(()=>{if(Jt===void 0)return;let e=Yt.current?.chunkId,t=Qt.current.length>0?Be(Qt.current,e):e??Zt.current;q(t)},[Jt,q]),(0,c.useEffect)(()=>{it.current=null,w(void 0),D(new Map),k(new Map),A(new Set),me(null),ve([]),ye(!1),W(0),Te(void 0),De([]),ke([])},[e,t]),(0,c.useEffect)(()=>{let e=rt.current,t=it.current;if(!e||!t)return;let n=e.querySelector(`[data-chunk-id="${t}"]`);if(!n)return;let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop;e.scrollTop=Math.max(0,r-8),at.current=e.scrollTop},[ot,T,lt]),(0,c.useEffect)(()=>{let e=rt.current;if(!e)return;let t=()=>{it.current=null,at.current=null},n=()=>{if(it.current===null)return;let n=at.current;(n===null||Math.abs(e.scrollTop-n)>2)&&(t(),en.current())},r={passive:!0};return e.addEventListener(`wheel`,t,r),e.addEventListener(`touchstart`,t,r),e.addEventListener(`keydown`,t),e.addEventListener(`pointerdown`,t),e.addEventListener(`scroll`,n,r),()=>{e.removeEventListener(`wheel`,t),e.removeEventListener(`touchstart`,t),e.removeEventListener(`keydown`,t),e.removeEventListener(`pointerdown`,t),e.removeEventListener(`scroll`,n)}},[Dt]);let en=(0,c.useRef)(()=>{});(0,c.useEffect)(()=>{let e=rt.current;if(!e||typeof IntersectionObserver>`u`||lt.length===0)return;let t=new Map(lt.map((e,t)=>[e.row.id,t])),n=new Set,r=()=>{if(it.current)return;let e;for(let r of n)(e===void 0||t.get(r)<t.get(e))&&(e=r);e&&w(t=>t===e?t:e)};en.current=r;let i=new IntersectionObserver(e=>{for(let t of e){let e=t.target.dataset.chunkId;e&&(t.isIntersecting?n.add(e):n.delete(e))}r()},{root:e,rootMargin:`0px 0px -66% 0px`,threshold:0});return e.querySelectorAll(`[data-chunk-id]`).forEach(e=>i.observe(e)),()=>{i.disconnect(),en.current=()=>{}}},[lt]);let nn=(0,c.useCallback)(e=>q(e.row.id),[q]),rn=(0,c.useCallback)((t,n,r)=>s?.({documentId:t,chunkId:n,title:r},{documentId:e,chunkId:C,title:J}),[s,e,C,J]),an=!!y.documentCreateChunk&&!!Y,sn=(0,c.useCallback)(async n=>{if(!y.documentCreateChunk||!y.documentSetAsset)return;let r=C||Y;if(r){B(null);try{let{mediaType:i,data:a}=await qe(n),o=await y.documentCreateChunk(e,r,{title:n.name||`image`,type:`image`},t,b);await y.documentSetAsset(o.id,i,a,n.name,t,b),K(),q(o.id)}catch(e){B(e instanceof Error?e.message:String(e))}}},[y,e,t,b,C,Y,K,q]),ln=(0,c.useCallback)(async()=>{if(!y.documentCreateChunk)return;let n=C||Y;if(n){B(null);try{let r=await y.documentCreateChunk(e,n,{title:`Diagram`,type:`mermaid`,body:`graph TD
6
+ A[Start] --> B[End]`},t,b);K(),q(r.id),P(r)}catch(e){B(e instanceof Error?e.message:String(e))}}},[y,e,t,b,C,Y,K,q]),un=!!C&&C===Y,dn=(0,c.useCallback)(async()=>{if(!y.documentCreateChunk)return;let n=C&&!un?C:void 0,r=C||Y;if(r){B(null);try{let i=await y.documentCreateChunk(e,n?``:r,{title:`Text`,body:``},t,b,n);K(),q(i.id),P(i)}catch(e){B(e instanceof Error?e.message:String(e))}}},[y,e,t,b,C,un,Y,K,q]),fn=(0,c.useCallback)(async()=>{if(y.documentCreateChunk&&C){B(null);try{let n=await y.documentCreateChunk(e,C,{title:`Text`,body:``},t,b);K(),q(n.id),P(n)}catch(e){B(e instanceof Error?e.message:String(e))}}},[y,e,t,b,C,K,q]),pn=(0,c.useMemo)(()=>{let e=x.find(e=>e.id===C);if(!e||!e.parent_id)return{canUp:!1,canDown:!1};let t=x.filter(t=>(t.parent_id??``)===e.parent_id).sort((e,t)=>e.position-t.position||e.id.localeCompare(t.id)),n=t.findIndex(t=>t.id===e.id);return{canUp:n>0,canDown:n>=0&&n<t.length-1}},[x,C]),mn=(0,c.useCallback)(async e=>{if(y.documentReorderChunk&&C){B(null);try{await y.documentReorderChunk(C,e,t,b),K(),q(C)}catch(e){B(e instanceof Error?e.message:String(e))}}},[y,C,t,b,K,q]),hn=(0,c.useCallback)(async()=>{if(!y.documentDeleteChunk||!ut)return;B(null);let e=ut.parent_id;try{await y.documentDeleteChunk(ut.id,t,b),re(!1),q(e||Y),K()}catch(e){B(e instanceof Error?e.message:String(e)),re(!1)}},[y,ut,t,b,Y,K,q]);(0,c.useEffect)(()=>{if(!an)return;let e=e=>{if(N||he)return;let t=document.activeElement,n=t?.tagName;if(n===`INPUT`||n===`TEXTAREA`||t?.isContentEditable)return;let r=Je(e.clipboardData?.items);r&&(e.preventDefault(),sn(r))};return window.addEventListener(`paste`,e),()=>window.removeEventListener(`paste`,e)},[an,N,he,sn]);let yn=(0,c.useCallback)(async(e,t)=>{let n=await Ot(e);$e(n?`${t} copied`:`could not copy the ${t}`),window.setTimeout(()=>$e(null),1500)},[]),bn=(0,c.useCallback)(e=>w(t=>t===e?t:e),[]),Sn=(0,c.useCallback)(e=>A(t=>{let n=new Set(t);return n.delete(e)||n.add(e),n}),[]),Cn=(0,c.useCallback)(e=>void yn(e,`chunk id`),[yn]),wn=(0,c.useCallback)(async(n,r)=>{Ze(`Preparing ${r}`);try{await Z(y,n,e,t,b,J)}catch(e){B(e instanceof Error?e.message:String(e))}finally{Ze(void 0)}},[y,e,t,b,J]),Tn=!!y.documentClassify||Mt,En=[...Vt?[`annotation`]:[],`references`,...Tn?[`classification`]:[],`history`],$=je&&En.includes(je)&&(!Ge||Ne)?je:null,Dn=e=>Fe($===e?null:e),On=(0,c.useRef)(`references`);$&&(On.current=$);let kn=(0,c.useRef)(()=>{});kn.current=e=>{if(!Dt&&or(e,Re.current)){if(e.key===`{`)Ke(!Ue);else if(e.key===`]`)Fe($?null:En.includes(On.current)?On.current:`references`);else return;e.preventDefault()}},(0,c.useEffect)(()=>{let e=e=>kn.current(e);return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let An={title:J,type:Ct,status:wt,brief:Rt?.brief,abstract:Rt?.abstract,stale:Rt?.stale||void 0},Mn=Ee.some(e=>e.stale),Pn=(0,c.useMemo)(()=>({data:y,scope:t,browse:b}),[y,t,b]),Fn=ut?.title||x.find(e=>e.id===C)?.title||`(untitled)`,In=[an?[{key:`add-text`,label:`add text`,title:`Add a text chunk after “${Fn}”, at the same level`,run:()=>void dn()},{key:`add-child`,label:`add child`,title:C?`Add a chunk nested under “${Fn}” (in the ontology, a child is a subclass)`:`Select a chunk first — this nests a new chunk under it`,disabled:!C,run:()=>void fn()},{key:`add-image`,label:`add image`,title:`Add an image chunk (upload — or paste a screenshot into the view)`,run:()=>te.current?.click()},{key:`add-diagram`,label:`add diagram`,title:`Add a Mermaid diagram chunk`,run:()=>void ln()}]:[],C&&!un?[{key:`chunk-up`,label:`move chunk up`,title:`Move “${Fn}” up within its level`,disabled:!pn.canUp,run:()=>void mn(`up`)},{key:`chunk-down`,label:`move chunk down`,title:`Move “${Fn}” down within its level`,disabled:!pn.canDown,run:()=>void mn(`down`)},{key:`chunk-delete`,label:`delete chunk…`,title:`Delete “${Fn}” and its sub-chunks`,danger:!0,disabled:!ut,run:()=>re(!0)}]:[],[{key:`colors`,label:_t?`colours (on)`:`colours`,title:`Colours — tint chunk rows and the Path tree by type/status`,disabled:!Y,run:()=>ge(!0)},...y.documentClassify?[{key:`classify`,label:`classify`,title:`Classify — what this document is, by the confirmed ontology (a report first; nothing is written until Apply)`,run:()=>{W(e=>e+1),Fe(`classification`)}}]:[],...y.documentEntityTypes&&mt&&_(mt)?[{key:`change-type`,label:`change subject type`,title:`Change this subject's type to another type in force`,run:()=>I(mt)}]:[],...a?[{key:`assistant`,label:fe?`close assistant`:`assistant`,title:`Document Assistant — instruct an agent to restructure/import/link chunks`,run:()=>pe(e=>!e)}]:[]],At(y).map(e=>({key:`download-${e.kind}`,label:`download ${e.label}`,title:e.title,run:()=>void wn(e.kind,e.label)})),[...v?.rename?[{key:`rename`,label:`rename / move`,run:v.rename}]:[],...v?.transfer?[{key:`transfer`,label:`copy / move to…`,title:`Copy or move to another scope`,run:v.transfer}]:[],{key:`copy-id`,label:`copy document id`,title:`Copy this document's id, for a workflow over the MCP/HTTP API`,run:()=>void yn(e,`document id`)},{key:`copy-link`,label:`copy link`,title:`Copy a loom:doc link to this document, the form agents cite it by`,run:()=>void yn(vr(e,t),`link`)},{key:`reload`,label:`reload`,title:`Read the document again`,run:et}],v?.delete?[{key:`delete`,label:`delete document…`,danger:!0,run:v.delete}]:[]];return(0,l.jsx)(Ce.Provider,{value:Pn,children:(0,l.jsxs)(`div`,{className:`doc-viewer${ze?` narrow`:``}${Ge?` panel-over`:``}`,ref:Re,children:[(0,l.jsx)(`input`,{ref:te,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,style:{display:`none`},onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&sn(t)}}),(0,l.jsxs)(`div`,{className:`doc-header`,style:xt,children:[g&&(0,l.jsx)(`div`,{className:`doc-header-path`,children:g}),(0,l.jsx)(`h1`,{className:`doc-title`,title:J,children:J}),(0,l.jsx)(Xt,{type:Ct,status:wt,statusColor:qt(wt,yt)}),(0,l.jsxs)(`div`,{className:`doc-header-actions`,children:[Qe&&(0,l.jsx)(`span`,{className:`doc-header-note`,role:`status`,children:Qe}),(0,l.jsxs)(`button`,{type:`button`,className:`doc-edit`,onClick:()=>mt&&P(mt),disabled:!mt,title:`Edit the document's title, type, status and opening text`,children:[(0,l.jsx)(Sr,{kind:`edit`}),(0,l.jsx)(`span`,{className:`doc-edit-label`,children:`edit`})]}),(0,l.jsx)(Yn,{groups:In,busy:Ye,label:`Document actions`})]})]}),z&&(0,l.jsx)(`div`,{className:`paths-err`,children:z}),Dt?(0,l.jsx)(zn,{documentId:e,scope:t,detail:se??void 0}):(0,l.jsxs)(`div`,{className:`doc-body`,children:[(0,l.jsxs)(We,{className:`doc-split`,defaultLeftWidth:240,minLeftWidth:160,minRightWidth:320,storageKey:`loomcycle.explorer.split.doc`,hideLeft:Ue,hideRight:ze&&!Ue,onHandleDoubleClick:()=>Ke(!0),leftRail:(0,l.jsx)(er,{side:`left`,label:`chunk outline`,icon:`outline`,count:x.length,countLabel:x.length===1?`chunk`:`chunks`,shortcut:`{`,onExpand:()=>Ke(!1)}),children:[(0,l.jsxs)(`div`,{className:`doc-chunktree`,children:[(0,l.jsxs)(`div`,{className:`pane-head`,children:[(0,l.jsx)(`span`,{className:`pane-head-label`,children:`Outline`}),(0,l.jsx)(`span`,{className:`pane-head-count`,children:x.length}),(0,l.jsx)($n,{label:`chunk outline`,side:`left`,shortcut:`{`,onClick:()=>Ke(!0)})]}),ie&&x.length===0?(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Loading…`})}):(0,l.jsx)(tn,{tree:ct,selectedId:C,onSelect:nn,colorEnabled:_t,scheme:H?.color_scheme,documentColor:bt,linkedIds:X,documentType:Ct,documentStatus:wt})]}),(0,l.jsx)(`div`,{className:`doc-page`,ref:rt,tabIndex:-1,children:(0,l.jsx)(`article`,{className:`doc-article`,"aria-label":J,children:lt.map(({row:e,depth:n})=>(0,l.jsx)(yr,{row:e,depth:n,detail:T.get(e.id),error:O.get(e.id),current:e.id===C,source:ee.has(e.id),statusColor:qt(e.status,yt),scope:t,browse:b,onPick:bn,onToggleSource:Sn,onEdit:P,onHistory:R,onCopyId:Cn},e.id))})})]}),$&&(0,l.jsxs)(`aside`,{className:`doc-side`,id:`doc-side`,"aria-label":`${dr[$]} panel`,children:[(0,l.jsxs)(`div`,{className:`pane-head`,children:[(0,l.jsx)(`span`,{className:`pane-head-label`,children:dr[$]}),(0,l.jsx)($n,{label:`${dr[$]} panel`,side:`right`,shortcut:`]`,onClick:()=>Fe(null)})]}),(0,l.jsxs)(`div`,{className:`doc-side-body`,children:[$===`annotation`&&Y&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`div`,{className:`doc-annotation`,children:[(0,l.jsx)(`h2`,{className:`doc-panel-heading`,children:`Document`}),(0,l.jsx)(on,{record:Rt}),(0,l.jsx)(cn,{records:Ee,newLevel:M(!0),onSave:It?.(Y),onRegenerate:Lt?.(Y)},Y)]}),C&&C!==Y&&(0,l.jsxs)(`div`,{className:`doc-annotation`,children:[(0,l.jsx)(`h2`,{className:`doc-panel-heading`,children:Fn}),(0,l.jsx)(on,{record:Bt[0]}),(0,l.jsx)(cn,{records:Bt,newLevel:M(!1),onSave:It?.(C),onRegenerate:Lt?.(C)},C)]})]}),$===`references`&&(0,l.jsxs)(`div`,{className:`doc-links-pane`,children:[_e.length===0&&(0,l.jsx)(`p`,{className:`doc-refs-empty`,children:`This document has no links.`}),(0,l.jsx)(Nn,{edges:_e,incomplete:U,documentId:e,selectedId:C,onSelectChunk:q,onOpenDocument:s?rn:void 0,onRuleStatement:Ht}),(0,l.jsx)(jn,{documentId:e,selectedId:C,scope:t,browse:b,onSelectChunk:q,onOpenDocument:s?rn:void 0,refreshKey:be,review:Gt})]}),$===`classification`&&(Se===0&&!Mt?(0,l.jsxs)(`div`,{className:`doc-classify`,children:[(0,l.jsx)(`p`,{className:`doc-classify-hint`,children:`Nothing is waiting for review.`}),y.documentClassify&&(0,l.jsx)(`button`,{type:`button`,onClick:()=>W(e=>e+1),children:`classify this document`})]}):(0,l.jsx)(vn,{documentId:e,scope:t,browse:b,rootFields:we,requestKey:Se,onClose:()=>W(0),onChanged:K},`${t}:${e}`)),$===`history`&&(C?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`h2`,{className:`doc-panel-heading`,children:Fn}),(0,l.jsx)(Hn,{chunkId:C,scope:t,browse:b},C)]}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`Select a chunk to see its history.`}))]})]}),(0,l.jsx)(`nav`,{className:`doc-rail`,"aria-label":`Panels`,children:En.map(e=>(0,l.jsx)(xr,{panel:e,open:$===e,onClick:()=>Dn(e),count:e===`references`?Kt:e===`classification`?jt:void 0,dot:e===`annotation`&&Mn,card:e===`annotation`?An:void 0},e))})]}),fe&&a&&(0,l.jsx)(`div`,{className:`doc-assistant`,children:a({documentId:e,scope:t,subject:i?.subject,onChanged:K})}),N&&(0,l.jsx)(gn,{chunk:N,scope:t,browse:b,onClose:()=>P(null),onSaved:K}),F&&(0,l.jsx)(_n,{chunk:F,scope:t,browse:b,onClose:()=>I(null),onSaved:K}),L&&(0,l.jsx)(Vn,{chunkId:L.id,chunkTitle:L.title,scope:t,browse:b,onClose:()=>R(null)}),he&&Y&&(0,l.jsx)(xn,{documentId:e,rootChunkId:Y,docType:H?.type,docStatus:H?.status,chunkStatuses:gt,scope:t,browse:b,onClose:()=>ge(!1),onSaved:K}),ne&&ut&&(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:()=>re(!1),children:(0,l.jsxs)(`div`,{className:`modal chunk-delete-confirm`,onClick:e=>e.stopPropagation(),children:[(0,l.jsx)(`h3`,{children:`Delete chunk`}),(0,l.jsxs)(`p`,{className:`modal-context`,children:[`Delete “`,ut.title||`(untitled)`,`” and all of its sub-chunks? This cannot be undone.`]}),(0,l.jsxs)(`div`,{className:`modal-buttons`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:()=>re(!1),children:`cancel`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:()=>void hn(),children:`delete`})]})]})})]})})}function vr(e,t){return`loom:doc/${e}${t===`user`?``:`?scope=${t}`}`}var yr=(0,c.memo)(function({row:e,depth:t,detail:n,error:r,current:i,source:a,statusColor:o,scope:s,browse:c,onPick:u,onToggleSource:d,onEdit:f,onHistory:p,onCopyId:m}){let h=e.title||`(untitled)`,g=`h${Math.min(t+1,6)}`;return(0,l.jsxs)(`section`,{className:`doc-chunk${i?` current`:``}`,"data-chunk-id":e.id,"data-depth":t,"aria-label":t===0?void 0:h,onClick:()=>u(e.id),children:[(0,l.jsxs)(`div`,{className:`doc-chunk-bar`,role:`toolbar`,"aria-label":`${h} — chunk actions`,children:[(0,l.jsx)(Xt,{type:e.type,status:e.status,statusColor:o}),(0,l.jsxs)(`span`,{className:`doc-chunk-rev`,title:`Revision`,children:[`rev `,e.revision]}),n?.tags?.map(e=>(0,l.jsx)(`span`,{className:`chunk-tag`,children:e},e)),(0,l.jsx)(`button`,{type:`button`,className:`doc-chunk-icon`,"aria-pressed":a,onClick:()=>d(e.id),disabled:!n,"aria-label":`view source`,title:`Show this chunk's Markdown source`,children:(0,l.jsx)(Sr,{kind:`source`})}),(0,l.jsx)(`button`,{type:`button`,className:`doc-chunk-icon`,onClick:()=>n&&p(n),disabled:!n,"aria-label":`history`,title:`This chunk's edit history and diffs`,children:(0,l.jsx)(Sr,{kind:`history`})}),(0,l.jsx)(`button`,{type:`button`,className:`doc-chunk-icon`,onClick:()=>m(e.id),"aria-label":`copy id`,title:`Copy this chunk's id`,children:(0,l.jsx)(Sr,{kind:`copy`})}),(0,l.jsxs)(`button`,{type:`button`,className:`doc-chunk-edit`,onClick:()=>n&&f(n),disabled:!n,children:[(0,l.jsx)(Sr,{kind:`edit`}),`edit`]})]}),t>0&&(0,l.jsx)(g,{className:`doc-chunk-title`,children:h}),(0,l.jsx)(Cr,{detail:n,error:r,source:a,scope:s,browse:c})]})}),br={annotation:`annotation`,references:`references`,classification:`classification`,history:`history`};function xr({panel:e,open:t,onClick:n,count:r,dot:i,card:a}){let o=G(a),s=e===`references`?`${r??0} on this chunk`:e===`classification`?r?`${r} waiting for review`:`nothing waiting`:e===`annotation`&&i?`out of date`:void 0;return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`button`,{type:`button`,className:`doc-rail-button${r?` counted`:``}`,"aria-pressed":t,"aria-controls":t?`doc-side`:void 0,"aria-label":`${dr[e]}${s?`, ${s}`:``}`,title:a?void 0:dr[e],"aria-keyshortcuts":t?`]`:void 0,onClick:n,...o.props,children:[(0,l.jsx)(Zn,{kind:br[e]}),r?(0,l.jsx)(`span`,{className:`doc-rail-count`,children:r}):null,i&&(0,l.jsx)(`span`,{className:`doc-rail-dot`,"aria-hidden":`true`})]}),o.card]})}function Sr({kind:e}){return(0,l.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,focusable:`false`,children:[e===`source`&&(0,l.jsx)(`path`,{d:`M5.5 4.5L2 8l3.5 3.5M10.5 4.5L14 8l-3.5 3.5`}),e===`history`&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`circle`,{cx:`8`,cy:`8`,r:`5.75`}),(0,l.jsx)(`path`,{d:`M8 5v3.25l2 1.25`})]}),e===`edit`&&(0,l.jsx)(`path`,{d:`M10.75 2.75l2.5 2.5L5.5 13H3v-2.5zM9.25 4.25l2.5 2.5`}),e===`copy`&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`rect`,{x:`5.25`,y:`5.25`,width:`8`,height:`8`,rx:`1`}),(0,l.jsx)(`path`,{d:`M10.75 5.25v-1.5a1 1 0 0 0-1-1h-6a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h1.5`})]})]})}function Cr({detail:e,error:t,source:n,scope:r,browse:i}){return e?n?(0,l.jsx)(`pre`,{className:`md-pre doc-chunk-source`,children:(0,l.jsx)(`code`,{children:e.body})}):e.type===`mermaid`?e.body?(0,l.jsx)(fn,{code:e.body}):(0,l.jsx)(`p`,{className:`doc-empty-body`,children:`(empty diagram)`}):e.type===`image`||e.asset?(0,l.jsx)(wr,{detail:e,scope:r,browse:i}):e.body?(0,l.jsx)(qn,{source:e.body}):null:t?(0,l.jsxs)(`p`,{className:`doc-empty-body`,children:[`This chunk could not be read: `,t]}):(0,l.jsx)(`p`,{className:`doc-chunk-loading`,"aria-busy":`true`,children:`Loading…`})}function wr({detail:e,scope:t,browse:n}){let r=ue(),[i,a]=(0,c.useState)(null),[o,s]=(0,c.useState)(null);return(0,c.useEffect)(()=>{if(!r.documentAssetObjectUrl)return;let i=!1,o=null;return s(null),r.documentAssetObjectUrl(e.id,t,n).then(e=>{i?URL.revokeObjectURL(e):(o=e,a(e))}).catch(e=>!i&&s(e instanceof Error?e.message:String(e))),()=>{i=!0,o&&URL.revokeObjectURL(o)}},[r,e.id,e.revision,t,n]),o?(0,l.jsxs)(`p`,{className:`doc-empty-body`,children:[`Image failed to load: `,o]}):i?(0,l.jsxs)(`figure`,{className:`doc-image`,children:[(0,l.jsx)(`img`,{src:i,alt:cr(e)}),e.body&&(0,l.jsx)(`figcaption`,{children:e.body})]}):(0,l.jsx)(`p`,{className:`doc-chunk-loading`,children:`Loading image…`})}function Tr(e,t=``){let n=e.get(t);if(!n)return[];let r=n.entries.map(n=>{let r=n.kind!==`directory`&&n.has_children===!0,i=(n.kind===`directory`||r)&&n.full_path.startsWith(`${t}/`),a=Er(n);return{name:n.name,fullPath:n.full_path,kind:n.kind,resourceRef:n.resource_ref,...r?{hasChildren:r}:{},...a===void 0?{}:{documents:a},...a!==void 0&&n.documents_capped===!0?{documentsCapped:!0}:{},...n.matched===!0?{matched:!0}:{},listing:i?e.get(n.full_path):void 0,children:i?Tr(e,n.full_path):[]}});return r.sort((e,t)=>{let n=e.kind===`directory`;return n===(t.kind===`directory`)?e.name.localeCompare(t.name):n?-1:1}),r}function Er(e){if(e.kind!==`directory`&&e.has_children!==!0)return;let t=e.documents;return typeof t==`number`&&Number.isFinite(t)&&t>=0?Math.floor(t):void 0}function Dr(e,t){return t?`${e>=1e3?`${Math.floor(e/1e3)}k`:e}+`:e>=1e4?`${Math.floor(e/1e3)}k`:e.toLocaleString(`en-US`)}function Or(e,t,n){let r=n?e===1&&!t?`matching document`:`matching documents`:e===1&&!t?`document`:`documents`;return`${e.toLocaleString(`en-US`)}${t?` or more`:``} ${r}`}var kr={directory:`folder`,document:`document`,volume_mount:`volume`,memory_entry:`memory`};function Ar(e){return e.kind===`document`&&e.name===`_annotation`}function jr(e,t){if(e.kind===`directory`){let n=e.children.find(Ar);return n&&Fr(n,t)?.brief||void 0}if(!Ar(e))return Fr(e,t)?.brief||void 0}function Mr(e,t){let n=Fr(e,t);return{title:n?.title||e.name,type:e.kind===`directory`?`folder`:n?.type,status:n?.status,path:e.fullPath,brief:jr(e,t)}}function Nr(e){let{tree:t,root:n}=e;if(!n||!n.loaded&&n.loading)return(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Loading…`})});if(n.loaded&&t.length===0&&!n.nextCursor)return(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:e.filtered?`Nothing in this tree matches the filter.`:`This tree is empty. Create a folder or document to begin.`})});let r=Ir(t),i=e.selectedPath&&Lr(r,e.expanded,e.selectedPath)?e.selectedPath:r[0]?.fullPath;return(0,l.jsxs)(`ul`,{className:`etree path-tree`,role:`tree`,"aria-label":`Path tree`,onKeyDown:Qt,children:[r.map(t=>(0,l.jsx)(Rr,{node:t,depth:0,tabStop:i,...e},t.fullPath)),(0,l.jsx)(Pr,{dir:``,listing:n,...e})]})}function Pr({dir:e,listing:t,depth:n,onLoadMore:r,onRetry:i,filtered:a}){let o=[],s={"--etree-depth":n===void 0?0:n+1},c=t?t.entries.filter(e=>!Ar(e)).length:0;return!t||t.loading&&t.entries.length===0?o.push((0,l.jsx)(`li`,{className:`path-status`,role:`none`,style:s,children:(0,l.jsx)(`span`,{className:`path-implicit`,children:`loading…`})},`status`)):t.error?o.push((0,l.jsxs)(`li`,{className:`path-status`,role:`none`,style:s,children:[e!==``&&(0,l.jsxs)(`span`,{className:`path-err`,children:[`failed to load: `,t.error]}),` `,(0,l.jsx)(`button`,{type:`button`,className:`path-more`,onClick:()=>i(e),children:`retry`})]},`status`)):t.loaded&&c===0&&!t.nextCursor&&e!==``&&o.push((0,l.jsx)(`li`,{className:`path-status`,role:`none`,style:s,children:(0,l.jsx)(`span`,{className:`path-implicit`,children:a?`no match`:`empty`})},`status`)),t?.nextCursor&&!t.error&&o.push((0,l.jsx)(`li`,{className:`path-status`,role:`none`,style:s,children:(0,l.jsx)(`button`,{type:`button`,className:`path-more`,disabled:t.loading,onClick:()=>r(e),children:t.loading?a?`looking…`:`loading…`:a?`Look for more matches`:`Load more (${t.entries.length} shown)`})},`more`)),(0,l.jsx)(l.Fragment,{children:o})}function Fr(e,t){if(e.kind!==`document`||!t)return;let n=e.resourceRef;return n?.document_id?t.get(n.document_id):void 0}function Ir(e){return e.filter(e=>!Ar(e))}function Lr(e,t,n){for(let r of Ir(e))if(r.fullPath===n||(r.kind===`directory`||r.hasChildren===!0)&&t.has(r.fullPath)&&n.startsWith(`${r.fullPath}/`)&&Lr(r.children,t,n))return!0;return!1}function Rr(e){let{node:t,depth:n,tabStop:r,expanded:i,onToggle:a,selectedPath:o,onSelect:s,summaries:c,searchHits:u,searchCurrent:d,filtered:f}=e,p=t.kind===`directory`||t.hasChildren===!0,m=p&&i.has(t.fullPath),h=o===t.fullPath,g=Fr(t,c),_=g?Nt(g.color_scheme):void 0,v=!!g?.color_enabled,y=u?.has(t.fullPath),b=f&&t.kind!==`directory`?t.matched?`filter-match`:`filter-kept`:void 0;return(0,l.jsx)(Zt,{className:`path-node kind-${t.kind}`,rowClassName:d===t.fullPath?`search-hit search-current`:y?`search-hit`:b,card:Mr(t,c),count:t.kind===`directory`||t.documents!==void 0?(0,l.jsx)(`span`,{className:`etree-count${t.documentsCapped?` capped`:``}`,"aria-label":t.documents===void 0?void 0:Or(t.documents,t.documentsCapped,f),children:t.documents===void 0?void 0:Dr(t.documents,t.documentsCapped)}):void 0,depth:n,expandable:p,expanded:m,onToggle:()=>a(t.fullPath),selected:h,onSelect:()=>s(t),tabbable:t.fullPath===r,icon:(0,l.jsx)(Jt,{kind:Ar(t)?`annotation`:kr[t.kind]??`document`}),name:t.name,marks:(0,l.jsx)(Xt,{bare:!0,type:g?.type,status:g?.status,statusColor:qt(g?.status,v?_:void 0)}),style:v&&_?Gt(Ft(g?.type,g?.status,_)):void 0,children:m?(0,l.jsxs)(l.Fragment,{children:[Ir(t.children).map(t=>(0,l.jsx)(Rr,{...e,node:t,depth:n+1},t.fullPath)),(0,l.jsx)(Pr,{...e,dir:t.fullPath,listing:t.listing})]}):void 0})}function zr({dir:e,onNewFolder:t,onNewDocument:n}){let r=[{key:`folder`,label:`folder`,title:`New folder in ${e}`,run:t},{key:`document`,label:`document`,title:`New document in ${e}`,run:n}],[i,a]=(0,c.useState)(null),o=i!==null,s=(0,c.useRef)(null),u=(0,c.useRef)(null),d=(0,c.useRef)([]),f=(0,c.useId)();(0,c.useEffect)(()=>{i!==null&&d.current[i]?.focus()},[i]),(0,c.useEffect)(()=>{if(!o)return;let e=e=>{s.current&&!s.current.contains(e.target)&&a(null)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[o]);let p=()=>{a(null),u.current?.focus()},m=(e,t)=>{let n=r.length;e.key===`ArrowDown`||e.key===`ArrowUp`?(e.preventDefault(),d.current[(t+(e.key===`ArrowDown`?1:-1)+n)%n]?.focus()):e.key===`Escape`?(e.preventDefault(),p()):e.key===`Tab`&&a(null)};return(0,l.jsxs)(`div`,{className:`paths-create-menu`,ref:s,children:[(0,l.jsx)(`button`,{ref:u,type:`button`,className:o?`active`:void 0,title:`New folder or document in ${e}`,"aria-label":`New`,"aria-haspopup":`menu`,"aria-expanded":o,"aria-controls":o?f:void 0,onClick:()=>a(o?null:0),onKeyDown:e=>{e.key===`ArrowDown`?(e.preventDefault(),a(0)):e.key===`Escape`&&o&&(e.preventDefault(),a(null))},children:`+`}),o&&(0,l.jsx)(`div`,{className:`paths-create-list`,role:`menu`,id:f,"aria-label":`New`,children:r.map((e,t)=>(0,l.jsx)(`button`,{ref:e=>{d.current[t]=e},type:`button`,role:`menuitem`,tabIndex:-1,title:e.title,onClick:()=>{a(null),e.run()},onKeyDown:e=>m(e,t),children:e.label},e.key))})]})}function Br(e){let t=e.split(`/`).filter(Boolean);return t.map((e,n)=>({name:e,path:`/${t.slice(0,n+1).join(`/`)}`}))}function Vr({path:e,onFolder:t,cardFor:n}){let r=Br(e);return(0,l.jsx)(`nav`,{className:`doc-crumbs`,"aria-label":`Where this document is filed`,children:(0,l.jsx)(`ol`,{className:`doc-crumbs-list`,children:r.map((e,i)=>i===r.length-1?(0,l.jsx)(`li`,{className:`doc-crumbs-item`,children:(0,l.jsx)(Hr,{name:e.name,card:n?.(e.path,!0)})},e.path):(0,l.jsx)(`li`,{className:`doc-crumbs-item`,children:(0,l.jsx)(Hr,{name:e.name,card:n?.(e.path,!1),onClick:()=>t(e.path)})},e.path))})})}function Hr({name:e,card:t,onClick:n}){let r=G(t);return n?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`button`,{type:`button`,className:`doc-crumbs-folder`,onClick:n,...r.props,children:e}),r.card]}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`span`,{className:`doc-crumbs-current`,"aria-current":`page`,tabIndex:t?0:void 0,...r.props,children:e}),r.card]})}var Ur={name:``,type:``,status:``};function Wr(e){return e.name.trim()!==``||e.type.trim()!==``||e.status.trim()!==``}var Gr=[`draft`,`review`,`confirmed`,`done`];function Kr(e){return e?.appliedFilters==null?`opened`:`subtree`}function qr(e,t){let n=e===`search`?`searching`:`filtering`;return t===`subtree`?`${n} the whole tree`:`${n} opened folders`}function Jr(e){if(!Wr(e))return;let t={},n=e.name.trim(),r=e.type.trim(),i=e.status.trim();return n&&(t.name_contains=n),r&&(t.type=r),i&&(t.status=i),t}function Yr(e,t,n,r=8){let i=r-n.size;if(i<=0)return[];let a=[],o=e;for(;o.length>0&&a.length<i;){let e=[];for(let r of o)Ar(r)||(r.kind===`directory`||r.hasChildren===!0&&(!r.matched||(r.documents??0)>0))&&(t.has(r.fullPath)?e.push(...r.children):!n.has(r.fullPath)&&a.length<i&&a.push(r.fullPath));o=e}return a}var Xr=e=>e.toLocaleLowerCase();function Zr(e,t,n){let r=Xr(n.trim());if(!r)return[];let i=[],a=e=>{for(let n of e){if(Ar(n))continue;let e=t===``||n.fullPath.startsWith(`${t}/`);e&&Xr(n.name).includes(r)&&i.push(n),(e||n.fullPath===t||t.startsWith(`${n.fullPath}/`))&&a(n.children)}};return a(e),i}function Qr(e,t,n){let r=Fr(e,n),i=Xr(t.name.trim());if(i&&!Xr(e.name).includes(i)&&!Xr(r?.title??``).includes(i))return!1;let a=t.type.trim(),o=t.status.trim();return!(a&&Xr(r?.type??``)!==Xr(a)||o&&Xr(r?.status??``)!==Xr(o))}function $r(e,t,n){let r=new Set,i=t.type.trim()===``&&t.status.trim()===``,a=Xr(t.name.trim()),o=e=>{let s=[];for(let c of e){if(Ar(c)){s.push(c);continue}let e=c.kind===`directory`,l=o(c.children);l.some(e=>!Ar(e))?(r.add(c.fullPath),s.push({...c,children:l})):(e?i&&a!==``&&Xr(c.name).includes(a):Qr(c,t,n))&&s.push(c)}return s};return{tree:o(e),open:r}}function ei(e,t){let n=new Set,r=new Set(Gr),i=e=>{for(let a of e){if(!Ar(a)){let e=Fr(a,t);e?.type&&Xr(e.type)!==`annotation`&&n.add(e.type),e?.status&&r.add(e.status)}i(a.children)}};e.forEach(i);let a=(e,t)=>e.localeCompare(t);return{types:[...n].sort(a),statuses:[...r].sort(a)}}var ti=/^[A-Za-z0-9._-]+$/,ni=[`user`,`agent`,`tenant`],ri=`loomcycle.explorer.collapsed.paths`,ii=720,ai=320,oi=250,si=new Map,ci=()=>si,li=()=>()=>{};function ui(e,t){return`${e}/${t}`}function di(e,t){for(let n of e){if(n.fullPath===t)return n;let e=di(n.children,t);if(e)return e}}function fi(e){let{theme:t,defaultScope:n,path:r,onPathChange:i,browse:a,principal:o,renderAssistant:s,renderNavigator:c,navigator:u,onError:d,onRegenerateAnnotation:f,canEditAnnotations:p}=e,m=Ae(e);return(0,l.jsx)(je,{theme:t,dataLayer:m,children:(0,l.jsx)(pi,{defaultScope:n,path:r,onPathChange:i,browse:a,principal:o,renderAssistant:s,renderNavigator:c,navigator:u,onError:d,onRegenerateAnnotation:f,canEditAnnotations:p})})}function pi({defaultScope:e,path:t,onPathChange:n,browse:r,principal:i,renderAssistant:a,renderNavigator:o,navigator:s,onError:u,onRegenerateAnnotation:d,canEditAnnotations:f}){let p=ue(),[m,_]=(0,c.useState)(e??`user`),[v,y]=(0,c.useState)(void 0),[b,x]=(0,c.useState)(null),[S,C]=(0,c.useState)(null),[w,T]=(0,c.useState)(null),[E,D]=(0,c.useState)(()=>new Set),O=t===void 0?v:t,k=(0,c.useRef)(n);(0,c.useEffect)(()=>{k.current=n},[n]);let ee=(0,c.useRef)(u);(0,c.useEffect)(()=>{ee.current=u},[u]);let[A,j]=(0,c.useState)([]),M=(0,c.useRef)(0),te=(0,c.useRef)(void 0),N=(0,c.useCallback)(e=>{te.current=e,k.current?.(e),y(e)},[]),P=(0,c.useCallback)(e=>{M.current++,j(e=>e.length>0?[]:e),N(e)},[N]);(0,c.useEffect)(()=>{t!==void 0&&t!==te.current&&(M.current++,j(e=>e.length>0?[]:e))},[t]);let F=(0,c.useMemo)(()=>r&&(r.scopeId||r.tenant)?{scopeId:r.scopeId,tenant:r.tenant}:void 0,[r?.scopeId,r?.tenant]),I=(0,c.useCallback)(e=>{ee.current?.(e)},[]),L=(0,c.useMemo)(()=>new ge(p,m,F,500,{withCounts:!0}),[p,m,F]),R=(0,c.useSyncExternalStore)(L.subscribe,L.getSnapshot),[ne,re]=(0,c.useState)(!1),[z,B]=(0,c.useState)(`search`),[ie,ae]=(0,c.useState)(``),[V,oe]=(0,c.useState)(Ur),se=ne&&z===`filter`&&Wr(V),[ce,le]=(0,c.useState)(Ur);(0,c.useEffect)(()=>{let e=se?V:Ur,t=setTimeout(()=>le(e),se?oi:0);return()=>clearTimeout(t)},[se,V]);let[de,fe]=(0,c.useState)(null),me=de===L,he=`${ce.name.trim()}\u0000${ce.type}\u0000${ce.status}`,U=(0,c.useMemo)(()=>{let e=Jr(ce);return e&&!me?new ge(p,m,F,500,{withCounts:!0,filters:e}):null},[p,m,F,he,me]),ye=(0,c.useSyncExternalStore)(U?.subscribe??li,U?.getSnapshot??ci),[be,xe]=(0,c.useState)(()=>new Set),Se=(0,c.useRef)(new Set);(0,c.useEffect)(()=>{xe(new Set),Se.current=new Set,U?.loadDir(``).catch(()=>{})},[U]);let W=ye.get(``),Ce=!!U&&!!W?.loaded&&Kr(W)===`subtree`,we=!!W&&!W.loading&&(W.loaded||W.error!==void 0);(0,c.useEffect)(()=>{U&&we&&!Ce&&fe(L)},[U,we,Ce,L]),(0,c.useEffect)(()=>{if(U)for(let e of be)ye.has(e)||U.loadDir(e).catch(I)},[U,be,ye,I]);let Te=(0,c.useMemo)(()=>Ce?Tr(ye):[],[Ce,ye]);(0,c.useEffect)(()=>{if(!Ce)return;let e=Yr(Te,be,Se.current);e.length!==0&&(e.forEach(e=>Se.current.add(e)),xe(t=>new Set([...t,...e])))},[Ce,Te,be]);let[De,Oe]=(0,c.useState)(()=>o?h(globalThis.localStorage):`tree`),G=!!o&&De===`stars`,Ae=(0,c.useCallback)(e=>{Oe(e),g(globalThis.localStorage,e),e===`tree`&&Fe(!1)},[]),[je,Fe]=(0,c.useState)(!1),[Ie,Le]=(0,c.useState)(0),ze=(0,c.useRef)(null),Be=sr(ze,ii),[Ue,Ge]=rr(ri),[Ke,qe]=(0,c.useState)(()=>!t),Je=Be?!Ke:Ue&&!G,Ye=(0,c.useCallback)(e=>Be?qe(!e):Ge(e),[Be,Ge]);(0,c.useEffect)(()=>{o&&s&&Ae(s)},[s]);let[Xe,Ze]=(0,c.useState)(),[Qe,$e]=(0,c.useState)(),K=(0,c.useCallback)((e,t)=>(Le(e=>e+1),U?.invalidate(e,t).catch(()=>{}),L.invalidate(e,t)),[L,U]),[et,tt]=(0,c.useState)(()=>new Map),nt=(0,c.useRef)(new Set),rt=(0,c.useRef)(0),it=(0,c.useCallback)(()=>{rt.current++,nt.current=new Set,tt(new Map)},[]),at=(0,c.useRef)(!0);(0,c.useEffect)(()=>{at.current?at.current=!1:(P(void 0),x(null),D(new Set),it()),L.loadDir(``).catch(I)},[L,P,it,I]),(0,c.useEffect)(()=>{for(let e of E)R.has(e)||L.loadDir(e).catch(I)},[L,E,R,I]);let ot=(0,c.useRef)(null);(0,c.useEffect)(()=>{let e=ot.current!==null&&ot.current!==L;if(ot.current=L,!O||e)return;let t=H(O).filter(e=>e!==``);D(e=>{if(t.every(t=>e.has(t)))return e;let n=new Set(e);return t.forEach(e=>n.add(e)),n}),L.reveal(O).catch(I)},[L,O,I]),(0,c.useEffect)(()=>{let e=[];for(let t of[...R.values(),...ye.values()])for(let n of ve(t.entries))nt.current.has(n)||(nt.current.add(n),e.push(n));let t=rt.current;for(let n=0;n<e.length;n+=500)p.documentsSummary({documentIds:e.slice(n,n+500)},m,F).then(e=>{rt.current===t&&tt(t=>{let n=new Map(t);for(let t of e.documents??[])n.set(t.document_id,t);return n})}).catch(()=>{})},[p,R,ye,m,F]);let st=(0,c.useMemo)(()=>Tr(R),[R]),[q,ct]=(0,c.useState)(0),lt=(0,c.useRef)(null),J=se&&Ce,ut=Kr(z===`filter`&&J?W:R.get(``)),Y=(0,c.useId)(),dt=J&&V.type!==``?Math.max(0,(W?.typeExpandedTo?.length??0)-1):0,ft=(0,c.useMemo)(()=>se&&!J?$r(st,V,et):void 0,[se,J,st,V,et]),pt=(0,c.useMemo)(()=>ne&&z===`filter`?ei([st,Te],et):{types:[],statuses:[]},[ne,z,st,Te,et]),mt=(0,c.useCallback)(async()=>{x(null),it(),Le(e=>e+1),fe(null),await Promise.all([L.refresh(E).catch(I),U?.refresh(be).catch(()=>{})]),O&&await L.reveal(O).catch(I)},[L,U,E,be,O,it,I]),ht=(0,c.useCallback)(e=>{D(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),gt=(0,c.useCallback)(e=>{xe(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),_t=J&&U?U:L,vt=(0,c.useCallback)(e=>_t.loadMore(e).catch(I),[_t,I]),yt=(0,c.useCallback)(e=>{(_t.getSnapshot().get(e)?.loaded?_t.loadMore(e):_t.loadDir(e)).catch(I)},[_t,I]),X=(0,c.useMemo)(()=>O?di(st,O)??(J?di(Te,O):void 0):void 0,[st,Te,J,O]),bt=R.get(``)?.error,xt=X?.kind===`directory`?X.children.find(Ar):void 0,St=X?.kind===`directory`?X.fullPath:void 0,[Ct,wt]=(0,c.useState)(null);(0,c.useEffect)(()=>{if(!St||!p.pathIsStored)return;let e=!1;return p.pathIsStored(St,m,F).then(t=>{e||wt({path:St,explicit:t})},()=>{}),()=>{e=!0}},[p,St,m,F]);let Tt=X?X.kind===`directory`?Ct?.path===X.fullPath?Ct.explicit?`yes`:`implicit (no entry)`:void 0:`yes`:void 0,Et=(0,c.useMemo)(()=>X?X.kind===`directory`?X.fullPath:pe(X.fullPath):``,[X]),Dt=Et||`/`,[Ot,kt]=(0,c.useState)(``),At=ne&&z===`search`&&ie.trim()!==``,Z=(0,c.useMemo)(()=>At?Zr(st,Ot,ie):[],[At,st,Ot,ie]),jt=(0,c.useMemo)(()=>new Set(Z.map(e=>e.fullPath)),[Z]),Mt=Z.length>0?Z[Math.min(q,Z.length-1)]:void 0;(0,c.useEffect)(()=>{if(!Mt)return;let e=H(Mt.fullPath).filter(e=>e!==``);D(t=>{if(e.every(e=>t.has(e)))return t;let n=new Set(t);return e.forEach(e=>n.add(e)),n})},[Mt]);let Nt=(0,c.useRef)(null);(0,c.useEffect)(()=>{Mt&&(Nt.current?.querySelector(`.etree-row.search-current`))?.scrollIntoView?.({block:`nearest`})},[Mt,E]);let Pt=(0,c.useCallback)(()=>{kt(X?.kind===`directory`?X.fullPath:``),re(!0),ct(0),setTimeout(()=>lt.current?.focus(),0)},[X]),Ft=(0,c.useCallback)(()=>{re(!1),ae(``),oe(Ur),ct(0)},[]),It=e=>{Z.length!==0&&ct(t=>((Math.min(t,Z.length-1)+e)%Z.length+Z.length)%Z.length)},Lt=(0,c.useCallback)(()=>{C({title:`New folder in ${Dt}`,fields:[{key:`name`,label:`Folder name`,placeholder:`e.g. launches`}],submitLabel:`Create`,onSubmit:async e=>{let t=e.name.trim();if(!ti.test(t))throw Error(`name may contain only [A-Za-z0-9._-]`);let n=ui(Et,t);await p.pathMkdir(n,m,F),await K(n).catch(I),P(n)}})},[p,K,Et,Dt,m,F,I,P]),Rt=(0,c.useCallback)(()=>{C({title:`New document in ${Dt}`,fields:[{key:`name`,label:`Path name`,placeholder:`e.g. launch-plan`},{key:`title`,label:`Title`,placeholder:`e.g. Launch Plan`}],submitLabel:`Create`,onSubmit:async e=>{let t=e.name.trim();if(!ti.test(t))throw Error(`name may contain only [A-Za-z0-9._-]`);let n=e.title.trim()||t,r=ui(Et,t);await p.documentCreate(n,r,m,F),await K(r).catch(I),P(r)}})},[p,K,Et,Dt,m,F,I,P]),zt=(0,c.useCallback)(()=>{X&&C({title:`Rename / move ${X.fullPath}`,fields:[{key:`to`,label:`New path`,value:X.fullPath}],submitLabel:`Move`,onSubmit:async e=>{let t=e.to.trim();if(!t.startsWith(`/`))throw Error(`path must start with /`);await p.pathMv(X.fullPath,t,m,F),await Promise.all([K(X.fullPath,{dropSubtree:!0}),K(t)]).catch(I),P(t)}})},[p,K,X,m,F,I,P]),Bt=(0,c.useCallback)(()=>{if(!X)return;if(X.kind===`document`){let e=X.resourceRef?.document_id;C({title:`Delete document ${X.fullPath}`,message:`This deletes the document, all its chunks, and its path entry. This cannot be undone.`,fields:[],submitLabel:`Delete`,danger:!0,onSubmit:async()=>{if(!e)throw Error(`this document dirent has no document_id`);await p.documentDelete(e,m,F),await K(X.fullPath).catch(I),P(void 0)}});return}let e=X;x(null),(async()=>{let t;try{t=await _e(p,e.fullPath,m,F)}catch(t){x(`could not list ${e.fullPath} for delete: ${t instanceof Error?t.message:String(t)}`);return}let n=ve(t);C({title:`Delete branch ${e.fullPath}`,message:t.length===0?`This removes the (empty) folder.`:`This removes the folder and everything under it`+(n.length>0?` — including ${n.length} document(s), whose chunks are deleted.`:`.`),fields:[],submitLabel:`Delete`,danger:!0,onSubmit:async()=>{for(let e of n)await p.documentDelete(e,m,F);await p.pathRm(e.fullPath,m,!0,F),await K(e.fullPath,{dropSubtree:!0}).catch(I),P(void 0)}})})()},[p,K,X,m,F,I,P]),Vt=X&&(X.kind===`directory`||X.kind===`document`),Ht=!!p.documentsTransfer&&!!Vt,Ut=(0,c.useCallback)(()=>{if(X){if(X.kind===`document`){let e=X.resourceRef?.document_id;if(!e){x(`this document entry has no document_id`);return}T({documentId:e,fromPath:X.fullPath})}else T({underPath:X.fullPath,fromPath:X.fullPath})}},[X]),Wt=(0,c.useCallback)(e=>{e.op===`move`?(K(e.from,{dropSubtree:!0}).catch(I),j([]),P(void 0)):e.toScope===m&&K(e.to).catch(I)},[K,I,m,P]),Q=(0,c.useMemo)(()=>{if(A.length>0)return A[A.length-1];if(X?.kind===`document`)return{documentId:X.resourceRef?.document_id??``,path:X.fullPath,title:X.name}},[A,X]),Gt=(0,c.useCallback)((e,t)=>{let n=++M.current,r=Re(L.getSnapshot(),e.documentId);j(Me(A,{...t,path:Q?.path},{...e,path:r})),N(r),!r&&p.documentPath&&p.documentPath(e.documentId,m,F).then(t=>{t&&M.current===n&&(j(n=>Pe(n,e.documentId,{path:t})),N(t))},()=>{})},[p,L,A,Q?.path,m,F,N]),Kt=(0,c.useCallback)(e=>{let t=Ne(A,e);t!==A&&(M.current++,j(t),N(t[t.length-1].path))},[A,N]),qt=(0,c.useCallback)((e,t)=>j(n=>Pe(n,e,{title:t})),[]),Jt=(0,c.useCallback)(e=>{$e(t=>({documentId:e.documentId,chunkId:e.chunkId,seq:(t?.seq??0)+1})),Q?.documentId!==e.documentId&&(e.path?P(e.path):(M.current++,j([{documentId:e.documentId,chunkId:e.chunkId}]),N(void 0)))},[Q?.documentId,P,N]),Yt=(0,c.useMemo)(()=>({scope:m,browse:F,selection:{documentId:Q?.documentId,chunkId:Xe&&Xe.documentId===Q?.documentId?Xe.chunkId:void 0,path:Q?.path},onSelect:Jt,reloadToken:Ie,maximized:je,onToggleMaximize:()=>Fe(e=>!e),subject:i?.subject}),[m,F,Q?.documentId,Q?.path,Xe,Jt,Ie,je,i?.subject]),Xt=Qe&&Q&&Qe.documentId===Q.documentId?Qe:void 0,Zt=!!Q?.path&&X?.kind===`document`&&X.fullPath===Q.path,Qt=(0,c.useCallback)(e=>{P(e.fullPath),Be&&e.kind!==`directory`&&qe(!1)},[Be,P]),$t=(0,c.useCallback)(e=>{P(e),D(t=>t.has(e)?t:new Set(t).add(e)),Ye(!1),De===`stars`&&Ae(`tree`)},[P,Ye,De,Ae]),en=(0,c.useCallback)((e,t)=>{let n=di(st,e);if(!t)return n?Mr(n,et):{title:e.slice(e.lastIndexOf(`/`)+1),type:`folder`,path:e};if(!Q?.documentId)return;let r=n?Fr(n,et):void 0;return ke(Q.documentId,r?.title||Q.title||e.slice(e.lastIndexOf(`/`)+1),{data:p,scope:m,browse:F},r?{type:r.type,status:r.status,brief:r.brief??``}:void 0)},[st,et,Q?.documentId,Q?.title,p,m,F]),tn=(0,c.useRef)(()=>{});tn.current=e=>{if(or(e,ze.current)){if(e.key===`[`&&!G)Ye(!Je);else if(e.key===`/`&&!G)Ye(!1),Pt();else return;e.preventDefault()}},(0,c.useEffect)(()=>{let e=e=>tn.current(e);return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let nn=X?.kind===`directory`?Mr(X,et):void 0;return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`div`,{className:`paths-console${Be?` narrow`:``}`,ref:ze,children:(0,l.jsxs)(We,{className:G?`paths-view paths-view--stars`:`paths-view`,defaultLeftWidth:G?720:ai,minLeftWidth:280,minRightWidth:300,storageKey:G?`loomcycle.explorer.split.stars`:`loomcycle.explorer.split.paths`,hideRight:G&&je||Be&&!Je,hideLeft:Je,onHandleDoubleClick:G?void 0:()=>Ye(!0),leftRail:(0,l.jsx)(er,{side:`left`,label:`Path tree`,icon:`tree`,shortcut:`[`,onExpand:()=>Ye(!1)}),children:[(0,l.jsxs)(`div`,{className:`left`,children:[(0,l.jsxs)(`div`,{className:`paths-toolbar`,children:[(0,l.jsx)(`div`,{className:`paths-scope`,role:`group`,"aria-label":`Scope`,children:ni.map(e=>(0,l.jsx)(`button`,{type:`button`,"aria-pressed":m===e,className:m===e?`active`:void 0,onClick:()=>_(e),title:`Browse the ${e} scope`,children:e},e))}),o&&(0,l.jsxs)(`div`,{className:`paths-nav-switch`,role:`group`,"aria-label":`Navigator`,children:[(0,l.jsx)(`button`,{type:`button`,"aria-pressed":!G,className:G?void 0:`active`,onClick:()=>Ae(`tree`),title:`Browse the Path tree`,children:`tree`}),(0,l.jsx)(`button`,{type:`button`,"aria-pressed":G,className:G?`active`:void 0,onClick:()=>Ae(`stars`),title:`Browse the scope as a 3D star map`,children:`stars`})]}),(0,l.jsxs)(`div`,{className:`paths-toolbar-actions`,children:[!G&&(0,l.jsx)(`button`,{type:`button`,className:`paths-find-toggle`,"aria-pressed":ne,"aria-controls":`paths-find`,"aria-keyshortcuts":`/`,onClick:()=>ne?Ft():Pt(),title:`Search and filter the tree (/)`,"aria-label":`Search and filter the tree`,children:(0,l.jsx)(Zn,{kind:`search`})}),!G&&(0,l.jsx)(zr,{dir:Dt,onNewFolder:Lt,onNewDocument:Rt}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>void mt(),title:`Reload the tree`,"aria-label":`Reload the tree`,children:`↻`}),!G&&(0,l.jsx)($n,{label:`Path tree`,side:`left`,shortcut:`[`,onClick:()=>Ye(!0)})]})]}),ne&&!G&&(0,l.jsxs)(`div`,{className:`paths-find`,id:`paths-find`,role:`search`,children:[(0,l.jsx)(`div`,{className:`paths-find-mode`,role:`group`,"aria-label":`Search or filter`,children:[`search`,`filter`].map(e=>(0,l.jsx)(`button`,{type:`button`,"aria-pressed":z===e,className:z===e?`active`:void 0,onClick:()=>{B(e),ct(0)},children:e},e))}),(0,l.jsx)(`input`,{ref:lt,className:`paths-find-input`,type:`search`,value:z===`search`?ie:V.name,placeholder:z===`search`?`Find a name`:`Name`,"aria-label":z===`search`?`Find a name in the tree`:`Filter by name`,"aria-describedby":`paths-find-note`,onChange:e=>{let t=e.target.value;z===`search`?(ae(t),ct(0)):oe(e=>({...e,name:t}))},onKeyDown:e=>{e.key===`Escape`?(e.preventDefault(),Ft()):e.key===`Enter`&&z===`search`&&(e.preventDefault(),It(e.shiftKey?-1:1))}}),z===`filter`&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`input`,{className:`paths-find-field`,type:`search`,value:V.type,placeholder:`any type`,"aria-label":`Filter by type`,list:`${Y}-types`,autoComplete:`off`,spellCheck:!1,onChange:e=>oe(t=>({...t,type:e.target.value})),onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),Ft())}}),(0,l.jsx)(`datalist`,{id:`${Y}-types`,children:pt.types.map(e=>(0,l.jsx)(`option`,{value:e},e))}),(0,l.jsx)(`input`,{className:`paths-find-field`,type:`search`,value:V.status,placeholder:`any status`,"aria-label":`Filter by status`,list:`${Y}-statuses`,autoComplete:`off`,spellCheck:!1,onChange:e=>oe(t=>({...t,status:e.target.value})),onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),Ft())}}),(0,l.jsx)(`datalist`,{id:`${Y}-statuses`,children:pt.statuses.map(e=>(0,l.jsx)(`option`,{value:e},e))})]}),(0,l.jsxs)(`span`,{className:`paths-find-note`,id:`paths-find-note`,role:`status`,children:[z===`search`&&ie.trim()!==``&&(0,l.jsx)(`span`,{className:`paths-find-count`,children:Z.length===0?`no match`:`${Math.min(q,Z.length-1)+1} of ${Z.length}`}),qr(z,ut),z===`search`&&Ot!==``&&` under ${Ot}`,dt>0&&` · ${V.type} with ${dt} subtype${dt===1?``:`s`}`]}),(0,l.jsx)(`button`,{type:`button`,className:`paths-find-close`,onClick:Ft,"aria-label":`Close search`,children:(0,l.jsx)(Zn,{kind:`close`})})]}),(b||bt)&&(0,l.jsx)(`div`,{className:`paths-err`,children:b||bt}),G&&o?(0,l.jsx)(`div`,{className:`paths-navigator`,children:o(Yt)}):(0,l.jsx)(`div`,{className:`paths-tree-box`,ref:Nt,children:(0,l.jsx)(Nr,{tree:J?Te:ft?ft.tree:st,root:J?W:R.get(``),expanded:J?be:ft?new Set([...E,...ft.open]):E,onToggle:J?gt:ht,filtered:J,onLoadMore:vt,onRetry:yt,selectedPath:O,onSelect:Qt,summaries:et,searchHits:At?jt:void 0,searchCurrent:Mt?.fullPath})})]}),(0,l.jsx)(`div`,{className:`right`,children:Q?(0,l.jsxs)(`div`,{className:`paths-doc`,children:[(0,l.jsx)(Ve,{trail:A,onJump:Kt}),(0,l.jsx)(_r,{documentId:Q.documentId,scope:m,titleHint:Q.title,browse:F,principal:i,renderAssistant:a,initialChunkId:Q.chunkId??Xt?.chunkId,onOpenDocument:Gt,onTitle:qt,onChunkSelect:e=>Ze({documentId:Q.documentId,chunkId:e}),focusChunk:Xt,onRegenerateAnnotation:d,canEditAnnotations:f,onAnnotationChanged:()=>void mt(),pathLabel:Q.path?(0,l.jsx)(Vr,{path:Q.path,onFolder:$t,cardFor:en}):(0,l.jsx)(`span`,{className:`paths-doc-path paths-doc-unfiled`,title:`Opened by id — no entry for this document was found in the Path tree`,children:(0,l.jsx)(`em`,{children:`not in the tree`})}),documentActions:Zt?{rename:zt,transfer:Ht?Ut:void 0,delete:Bt}:void 0},A.length)]}):X?(0,l.jsxs)(`div`,{className:`paths-detail`,children:[(0,l.jsxs)(`h2`,{children:[(0,l.jsx)(`span`,{className:`paths-detail-kind`,children:X.kind}),(0,l.jsx)(`code`,{children:X.fullPath})]}),nn&&(0,l.jsx)(`div`,{className:`paths-detail-card`,children:(0,l.jsx)(Ee,{info:{...nn,path:void 0}})}),(0,l.jsxs)(`dl`,{className:`paths-detail-meta`,children:[(0,l.jsx)(`dt`,{children:`scope`}),(0,l.jsx)(`dd`,{children:m}),Tt&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(`dt`,{children:`stored`}),(0,l.jsx)(`dd`,{children:Tt})]})]}),Vt?(0,l.jsxs)(`div`,{className:`paths-detail-actions`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:zt,children:`rename / move`}),Ht&&(0,l.jsx)(`button`,{type:`button`,onClick:Ut,title:`Copy or move to another scope`,children:`copy / move to…`}),xt&&(0,l.jsx)(`button`,{type:`button`,onClick:()=>P(xt.fullPath),title:`Open the folder's annotation document to edit it`,children:`edit folder annotation`}),(0,l.jsx)(`button`,{type:`button`,className:`danger`,onClick:Bt,children:`delete`})]}):(0,l.jsxs)(`p`,{className:`paths-readonly`,children:[`Read-only — `,X.kind,` entries are managed by their own tool.`]})]}):(0,l.jsx)(`div`,{className:`empty`,children:(0,l.jsx)(`p`,{children:`Select a path on the left, or create a folder / document.`})})})]})}),S&&(0,l.jsx)(mi,{state:S,onClose:()=>C(null)}),w&&(0,l.jsx)(He,{data:p,scope:m,browse:F,documentId:w.documentId,underPath:w.underPath,fromPath:w.fromPath,onClose:()=>T(null),onDone:Wt})]})}function mi({state:e,onClose:t}){let[n,r]=(0,c.useState)(()=>Object.fromEntries(e.fields.map(e=>[e.key,e.value??``]))),[i,a]=(0,c.useState)(!1),[o,s]=(0,c.useState)(null);return(0,l.jsx)(`div`,{className:`modal-overlay`,onClick:t,children:(0,l.jsxs)(`form`,{className:`modal`,onClick:e=>e.stopPropagation(),onSubmit:async r=>{r.preventDefault(),a(!0),s(null);try{await e.onSubmit(n),t()}catch(e){s(e instanceof Error?e.message:String(e)),a(!1)}},children:[(0,l.jsxs)(`div`,{className:`modal-header sticky-top`,children:[(0,l.jsx)(`h3`,{children:e.title}),(0,l.jsxs)(`div`,{className:`modal-buttons modal-buttons-top`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:t,disabled:i,children:`cancel`}),(0,l.jsx)(`button`,{type:`submit`,className:e.danger?`danger`:`primary`,disabled:i,children:i?`working…`:e.submitLabel})]})]}),e.message&&(0,l.jsx)(`p`,{className:`modal-context`,children:e.message}),e.fields.map((e,t)=>(0,l.jsxs)(`label`,{className:`path-field`,children:[(0,l.jsx)(`span`,{children:e.label}),(0,l.jsx)(`input`,{className:`path-modal-input`,value:n[e.key],placeholder:e.placeholder,autoFocus:t===0,onChange:t=>r(n=>({...n,[e.key]:t.target.value}))})]},e.key)),o&&(0,l.jsx)(`div`,{className:`modal-err`,children:o})]})})}function hi(e){let{documentId:t,scope:n,browse:r,theme:i}=e,a=Ae(e);return(0,l.jsx)(je,{theme:i,dataLayer:a,children:(0,l.jsx)(gi,{...e},`${n}:${t}:${r?.scopeId??``}:${r?.tenant??``}`)})}function gi({documentId:e,chunkId:t,scope:n,titleHint:r,browse:i,principal:a,renderAssistant:o,onOpenDocument:s,onRegenerateAnnotation:u,canEditAnnotations:d}){let[f,p]=(0,c.useState)([]),m=f[f.length-1],[h,g]=(0,c.useState)(),_=(0,c.useRef)(t);(0,c.useEffect)(()=>{t!==_.current&&(_.current=t,f.length>0?(g(void 0),p([])):g(e=>({chunkId:t,seq:(e?.seq??0)+1})))},[t]);let v=(0,c.useCallback)((e,t)=>{s?s(e,t):p(n=>Me(n,t,e))},[s]),y=(0,c.useCallback)(e=>p(t=>Ne(t,e)),[]),b=(0,c.useCallback)((e,t)=>p(n=>Pe(n,e,{title:t})),[]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Ve,{trail:f,onJump:y}),(0,l.jsx)(_r,{documentId:m?.documentId??e,scope:n,titleHint:m?m.title:r,browse:i,principal:a,renderAssistant:o,initialChunkId:m?m.chunkId:t,focusChunk:m?void 0:h,onOpenDocument:v,onTitle:b,onRegenerateAnnotation:u,canEditAnnotations:d},f.length)]})}exports.ABSTRACT_MAX_CHARS=O,exports.BRIEF_MAX_CHARS=D,exports.DEFAULT_SCHEME=jt,exports.DocumentViewer=hi,exports.EDGE_PAGE_CAP=Ye,exports.PathExplorer=fi,exports.QUEUE_CHANGED_RETRIES=st,exports.RULING_CHUNK=ot,exports.RequestError=be,exports.annotationsApply=E,exports.assetFetchFromConnection=ye,exports.chunkColor=It,exports.chunkCount=ut,exports.chunkInheritsDocColor=Lt,exports.chunkRowStyle=Vt,exports.createLoomcycleClient=U,exports.dataLayerFromClient=V,exports.docColor=Ft,exports.effectiveScheme=Nt,exports.hexToTint=Rt,exports.isQueueChanged=ct,exports.jsonPostFromConnection=xe,exports.loadDocumentEdges=Xe,exports.runRuling=lt,exports.setAnnotationInput=P,exports.tintStyle=zt,exports.transferInput=b,exports.undoRulings=J,exports.washStyle=Bt;
17
7
  //# sourceMappingURL=index.cjs.map