@inkeep/open-knowledge 0.9.0-beta.4 → 0.9.0-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/skills/discovery/SKILL.md +1 -1
- package/dist/assets/skills/project/SKILL.md +1 -1
- package/dist/cli.mjs +5 -5
- package/dist/constants-Bz06c8hN.mjs +2 -0
- package/dist/{dist-BXBvUD1t.mjs → dist-BkOSFGR2.mjs} +2 -2
- package/dist/{dist-Ck52TFc0.mjs → dist-CcwJUIV6.mjs} +1 -1
- package/dist/{gh-detect-D7VnGgqQ.mjs → gh-detect-CXkelKVd.mjs} +2 -2
- package/dist/index.mjs +1 -1
- package/dist/{init-DY0Tg0Hn.mjs → init-DwLGKHOJ.mjs} +4 -4
- package/dist/init-jTViq3OZ.mjs +1 -0
- package/dist/loader-B0gRV8ky.mjs +1 -0
- package/dist/{loader-CT-f0ckE.mjs → loader-DwAApXf7.mjs} +2 -2
- package/dist/{preview-CGN29pIo.mjs → preview-DQUlTvw4.mjs} +2 -2
- package/dist/preview-le3hO-Wh.mjs +1 -0
- package/dist/public/assets/{ActivityModeContent-23W6IyBi.js → ActivityModeContent-DJXpiZd9.js} +1 -1
- package/dist/public/assets/{DocumentContext-SHvJNWIX.js → DocumentContext-DTuvLW_x.js} +3 -3
- package/dist/public/assets/{GraphPanel-DVJ6eGSP.js → GraphPanel-CkyBCnW-.js} +1 -1
- package/dist/public/assets/{SettingsDialogBody-DZKro5Ny.js → SettingsDialogBody-BaPvetlg.js} +2 -2
- package/dist/public/assets/SourceEditor-B1_Gixe_.js +2 -0
- package/dist/public/assets/{config-validation-events-D8972EJ5.js → config-validation-events-BL3EPRrw.js} +5 -5
- package/dist/public/assets/index-D1S1GyyV.js +1914 -0
- package/dist/public/assets/{index-D77KFmom.css → index-D4TqB27u.css} +1 -1
- package/dist/public/assets/{prop-types-cyYYFQkG.js → prop-types-CMBUMzzz.js} +1 -1
- package/dist/public/assets/{target-navigation-intent-DAk_BTjV.js → target-navigation-intent-DK3GQaQx.js} +1 -1
- package/dist/public/assets/{toggle-group-niHrqjkN.js → toggle-group-Dx4VUJtk.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-ujD0pffB.js → typing-burst-detector-BC-nkePC.js} +2 -2
- package/dist/public/index.html +8 -8
- package/dist/{repair-launch-json-BYRMkqp3.mjs → repair-launch-json-vIRa-3co.mjs} +2 -2
- package/dist/{repair-mcp-configs-BwHZViW-.mjs → repair-mcp-configs-Dlc--ykk.mjs} +2 -2
- package/dist/repair-skills-9sqdgFxP.mjs +1 -0
- package/dist/{repair-skills-Cm2uNESR.mjs → repair-skills-B2NKABTJ.mjs} +2 -2
- package/dist/{src-BDiegEyp.mjs → src-iCrNc821.mjs} +2 -2
- package/dist/{start-CcdbaFqg.mjs → start-7ediTKw1.mjs} +2 -2
- package/dist/start-DLG9QOtB.mjs +1 -0
- package/dist/{write-project-skill-G5GcPARq.mjs → write-project-skill-Dol4FEz9.mjs} +2 -2
- package/package.json +1 -1
- package/dist/constants-BM8w0hds.mjs +0 -2
- package/dist/init-g5qA1EwQ.mjs +0 -1
- package/dist/loader-B2727ILW.mjs +0 -1
- package/dist/preview-ByuVOyc1.mjs +0 -1
- package/dist/public/assets/SourceEditor-AKMYQzoN.js +0 -2
- package/dist/public/assets/index-DzW0JF0b.js +0 -1914
- package/dist/repair-skills-cKMnX9L9.mjs +0 -1
- package/dist/start-BH8M2iSB.mjs +0 -1
|
@@ -387,7 +387,7 @@ $2`).split(`
|
|
|
387
387
|
});
|
|
388
388
|
<\/script>
|
|
389
389
|
</div>`}];function previewEmbedFence(e){return["```html preview",e.html,"```"].join(`
|
|
390
|
-
`)}const PREVIEW_THEME_TOKENS=[{name:`--chart-1`,light:`oklch(0.62 0.19 259)`,dark:`oklch(0.72 0.14 259)`},{name:`--chart-2`,light:`oklch(0.58 0.14 145)`,dark:`oklch(0.73 0.13 145)`},{name:`--chart-3`,light:`oklch(0.62 0.15 70)`,dark:`oklch(0.77 0.14 70)`},{name:`--chart-4`,light:`oklch(0.55 0.18 290)`,dark:`oklch(0.72 0.16 290)`},{name:`--chart-5`,light:`oklch(0.58 0.21 25)`,dark:`oklch(0.72 0.2 25)`},{name:`--primary`,light:`oklch(0.6321 0.1983 259.59)`,dark:`#69a3ff`},{name:`--primary-foreground`,light:`oklch(0.985 0 0)`,dark:`oklch(0.205 0 0)`},{name:`--foreground`,light:`oklch(0.145 0 0)`,dark:`oklch(0.985 0 0)`},{name:`--background`,light:`oklch(1 0 0)`,dark:`oklch(0.145 0 0)`},{name:`--card`,light:`oklch(1 0 0)`,dark:`oklch(0.205 0 0)`},{name:`--card-foreground`,light:`oklch(0.145 0 0)`,dark:`oklch(0.985 0 0)`},{name:`--muted-foreground`,light:`oklch(0.556 0 0)`,dark:`oklch(0.708 0 0)`},{name:`--border`,light:`oklch(0.922 0 0)`,dark:`oklch(1 0 0 / 10%)`},{name:`--destructive`,light:`oklch(0.577 0.245 27.325)`,dark:`oklch(0.704 0.191 22.216)`},{name:`--radius`,light:`0.625rem`,dark:`0.625rem`}],DEFAULT_SERVER_HOST=`localhost`,ALLOWED_IMAGE_MIME_TYPES=[`image/jpeg`,`image/png`,`image/gif`,`image/webp`,`image/svg+xml`],ALLOWED_VIDEO_MIME_TYPES=[`video/mp4`,`video/webm`,`video/ogg`],ALLOWED_AUDIO_MIME_TYPES=[`audio/mpeg`,`audio/wav`,`audio/ogg`],ALLOWED_PDF_MIME_TYPES=[`application/pdf`],IMAGE_EXTENSIONS=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`,`svg`]),VIDEO_EXTENSIONS=new Set([`mp4`,`webm`,`mov`,`m4v`,`mkv`]),PDF_EXTENSIONS=new Set([`pdf`]),AUDIO_EXTENSIONS=new Set([`mp3`,`wav`,`ogg`,`m4a`,`flac`,`aac`,`opus`]),FILE_ATTACHMENT_EXTENSIONS=new Set(`pdf.docx.xlsx.pptx.doc.xls.ppt.zip.7z.tar.gz.rar.csv.tsv.rtf.json.yaml.yml.xml.txt.pages.numbers.key.odt.ods.odp.epub.mobi`.split(`.`)),EXECUTABLE_BLOCKLIST_EXTENSIONS=new Set(`exe.bat.cmd.ps1.com.msi.vbs.js.jse.wsf.wsh.hta.sh.command.csh.ksh.bash.zsh.fish.desktop.action.workflow.html.htm.svg.xml.mhtml.svgz.dmg.pkg.mpkg.scpt.applescript.terminal.prefpane.webloc.inetloc.fileloc.jar.appimage.deb.rpm.msix.appx.ipa.apk.pif.scr.lnk.url`.split(`.`)),ASSET_EXTENSIONS=new Set(`png.jpg.jpeg.gif.webp.avif.svg.apng.heic.heif.tiff.bmp.ico.pdf.mp4.webm.mov.m4v.mkv.avi.flv.wmv.mpeg.mpg.mp3.wav.ogg.m4a.flac.aac.opus.zip.woff.woff2.ttf.otf.eot.docx.xlsx.pptx.csv.txt.rtf.json.toml.lock`.split(`.`)),INLINE_RENDERABLE_EXTENSIONS=new Set(`png.jpg.jpeg.gif.webp.avif.apng.heic.heif.tiff.bmp.ico.svg.pdf.mp4.webm.mov.m4v.mkv.mp3.wav.ogg.m4a.flac.aac.opus.json.toml.lock`.split(`.`)),DEFAULT_DEDUP_MODE=`same-dir`,WIKI_EMBED_EXTENSIONS=new Set(`png.jpg.jpeg.gif.webp.avif.svg.pdf.mp4.webm.mov.m4v.mkv.mp3.wav.ogg.m4a.flac.aac.opus.docx.xlsx.pptx.doc.xls.ppt.zip.7z.tar.gz.rar.csv.tsv.rtf.json.yaml.yml.xml.txt.pages.numbers.key.odt.ods.odp.epub.mobi`.split(`.`)),SIDEBAR_IMAGE_EXTENSIONS=[`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`],SIDEBAR_VIDEO_EXTENSIONS=[`mp4`,`webm`,`mov`,`m4v`],SIDEBAR_AUDIO_EXTENSIONS=[`mp3`,`wav`,`ogg`,`m4a`,`flac`,`aac`,`opus`],SIDEBAR_PDF_EXTENSIONS=[`pdf`],SIDEBAR_TEXT_EXTENSIONS=[`json`,`toml`,`lock`];function assertSubset(e,t,S){for(let w of t)if(!S.has(w))throw Error(`${e}: ${w} is not present in canonical upload constants`)}assertSubset(`SIDEBAR_IMAGE_ASSET_EXTENSIONS`,SIDEBAR_IMAGE_EXTENSIONS,IMAGE_EXTENSIONS),assertSubset(`SIDEBAR_VIDEO_ASSET_EXTENSIONS`,SIDEBAR_VIDEO_EXTENSIONS,VIDEO_EXTENSIONS),assertSubset(`SIDEBAR_AUDIO_ASSET_EXTENSIONS`,SIDEBAR_AUDIO_EXTENSIONS,AUDIO_EXTENSIONS),assertSubset(`SIDEBAR_PDF_ASSET_EXTENSIONS`,SIDEBAR_PDF_EXTENSIONS,PDF_EXTENSIONS),assertSubset(`FILE_ATTACHMENT_EXTENSIONS`,[...FILE_ATTACHMENT_EXTENSIONS],WIKI_EMBED_EXTENSIONS);const SIDEBAR_IMAGE_ASSET_EXTENSIONS=new Set(SIDEBAR_IMAGE_EXTENSIONS),SIDEBAR_VIDEO_ASSET_EXTENSIONS=new Set(SIDEBAR_VIDEO_EXTENSIONS),SIDEBAR_AUDIO_ASSET_EXTENSIONS=new Set(SIDEBAR_AUDIO_EXTENSIONS),SIDEBAR_PDF_ASSET_EXTENSIONS=new Set(SIDEBAR_PDF_EXTENSIONS),SIDEBAR_TEXT_ASSET_EXTENSIONS=new Set(SIDEBAR_TEXT_EXTENSIONS),SIDEBAR_RENDERABLE_ASSET_EXTENSIONS=new Set([...SIDEBAR_IMAGE_EXTENSIONS,...SIDEBAR_VIDEO_EXTENSIONS,...SIDEBAR_AUDIO_EXTENSIONS,...SIDEBAR_PDF_EXTENSIONS,...SIDEBAR_TEXT_EXTENSIONS]);assertSubset(`SIDEBAR_RENDERABLE_ASSET_EXTENSIONS`,[...SIDEBAR_RENDERABLE_ASSET_EXTENSIONS],INLINE_RENDERABLE_EXTENSIONS);function mediaKindForSidebarAssetExtension(e){let t=e.toLowerCase().replace(/^\./,``);return SIDEBAR_IMAGE_ASSET_EXTENSIONS.has(t)?`image`:SIDEBAR_VIDEO_ASSET_EXTENSIONS.has(t)?`video`:SIDEBAR_AUDIO_ASSET_EXTENSIONS.has(t)?`audio`:SIDEBAR_PDF_ASSET_EXTENSIONS.has(t)?`pdf`:SIDEBAR_TEXT_ASSET_EXTENSIONS.has(t)?`text`:null}const CodeBlockFidelity=index_default$11.extend({priority:60,addAttributes(){return{...this.parent?.(),fenceDelimiter:{default:"`"},fenceLength:{default:3},meta:{default:null},sourceStyle:{default:`fenced`}}}}),EmphasisFidelity=index_default$9.extend({name:`emphasis`,priority:60,addAttributes(){return{...this.parent?.(),sourceDelimiter:{default:`*`}}},addInputRules(){return[markInputRule({find:starInputRegex,type:this.type,getAttributes:{sourceDelimiter:`*`}}),markInputRule({find:underscoreInputRegex,type:this.type,getAttributes:{sourceDelimiter:`_`}})]}}),StrongFidelity=index_default$10.extend({name:`strong`,priority:60,addAttributes(){return{...this.parent?.(),sourceDelimiter:{default:`**`}}},addInputRules(){return[markInputRule({find:starInputRegex$1,type:this.type,getAttributes:{sourceDelimiter:`**`}}),markInputRule({find:underscoreInputRegex$1,type:this.type,getAttributes:{sourceDelimiter:`__`}})]}}),EscapeMark=Mark.create({name:`escapeMark`,priority:10,excludes:``,inclusive:!1,parseHTML(){return[{tag:`span[data-escape-mark]`}]},renderHTML(){return[`span`,{"data-escape-mark":``},0]}}),HardBreakFidelity=index_default$8.extend({priority:60,addAttributes(){return{...this.parent?.(),hardBreakStyle:{default:`backslash`}}}}),HeadingFidelity=index_default$7.extend({priority:60,addAttributes(){return{...this.parent?.(),headingStyle:{default:`atx`},sourceTrailingHashes:{default:null},sourceUnderlineLength:{default:null},sourceContiguousNext:{default:!1}}}}),HtmlBlockFidelity=Node3.create({name:`htmlBlock`,group:`block`,atom:!0,priority:60,addAttributes(){return{content:{default:``}}},parseHTML(){return[{tag:`div[data-html-block]`}]},renderHTML({node:e}){return[`div`,{"data-html-block":``,class:`html-block`},e.attrs.content]}});function toDesktopAssetHref(e){if(typeof e!=`string`||!e.startsWith(`/`))return e;let t=globalThis.window?.okDesktop?.config?.apiOrigin;return typeof t==`string`&&t?t+e:e}const ImageSrcFidelity=index_default$6.extend({priority:60,addAttributes(){return{...this.parent?.(),sourceUrl:{default:null,rendered:!1}}},renderHTML({HTMLAttributes:e}){let t=mergeAttributes(this.options.HTMLAttributes,e);return typeof t.src==`string`&&(t.src=toDesktopAssetHref(t.src)),[`img`,t]}}),JsxComponent=Node3.create({name:`jsxComponent`,group:`block`,atom:!1,content:`block*`,isolating:!0,selectable:!0,defining:!0,priority:60,addAttributes(){return{componentName:{default:``},kind:{default:`element`},attributes:{default:[]},sourceRaw:{default:``},sourceDirty:{default:!1},props:{default:{}}}},parseHTML(){return[{tag:`div[data-jsx-component]`,getAttrs:e=>typeof e==`string`?!1:{componentName:e.getAttribute(`data-component-name`)||``,sourceRaw:e.getAttribute(`data-source-raw`)||``}}]},renderHTML({HTMLAttributes:e}){return[`div`,{"data-jsx-component":``,"data-component-name":e.componentName,"data-source-raw":e.sourceRaw},0]},addCommands(){return{insertJsxComponent:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{sourceRaw:e}})}}}),JsxInline=Node3.create({name:`jsxInline`,group:`inline`,inline:!0,atom:!1,content:`text*`,isolating:!1,selectable:!0,priority:60,addAttributes(){return{}},parseHTML(){return[{tag:`span[data-jsx-inline]`}]},renderHTML(){return[`span`,{"data-jsx-inline":``},0]}}),SAFE_URL_SCHEMES=[`https`,`http`,`mailto`,`tel`,`ftp`,`sms`],SCHEME_ALT=SAFE_URL_SCHEMES.map(e=>`${e}:`).join(`|`),SAFE_URL_SCHEME_RE=RegExp(`^(?:${SCHEME_ALT}|\\/|#|\\?|\\.\\/|\\.\\.\\/)`,`i`);function isRelativeUrl(e){let t=e.trim();if(t===``)return!0;let S=t.indexOf(`:`);if(S===-1)return!0;let w=t.indexOf(`/`),E=t.indexOf(`?`),D=t.indexOf(`#`);return S>Math.min(w===-1?1/0:w,E===-1?1/0:E,D===-1?1/0:D)}const ALLOWED_LINK_SCHEMES=new Set(SAFE_URL_SCHEMES.map(e=>`${e}:`)),PLACEHOLDER_BASE=`https://placeholder.invalid`;function isAllowedLinkUri(e){try{let t=new URL(e,PLACEHOLDER_BASE);return ALLOWED_LINK_SCHEMES.has(t.protocol.toLowerCase())}catch{return!1}}const LinkFidelity=index_default$5.extend({priority:60,addOptions(){return{openOnClick:!1,enableClickSelection:!1,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:`http`,HTMLAttributes:{target:`_blank`,rel:`noopener noreferrer`},isAllowedUri:isAllowedLinkUri,validate:isAllowedLinkUri,shouldAutoLink:()=>!0}},addAttributes(){return{...this.parent?.(),linkStyle:{default:`inline`,rendered:!1},refLabel:{default:null,rendered:!1},sourceForm:{default:null,rendered:!1},target:{default:null,rendered:!1},anchor:{default:null,rendered:!1},alias:{default:null,rendered:!1},sourceUrlForm:{default:null,rendered:!1},sourceTitleMarker:{default:null,rendered:!1}}}}),LinkRefDefFidelity=Node3.create({name:`linkRefDef`,group:`block`,atom:!0,priority:60,addAttributes(){return{label:{default:``},href:{default:``},title:{default:null},sourceLayout:{default:null},sourceTitleMarker:{default:null}}},parseHTML(){return[{tag:`div[data-link-ref-def]`}]},renderHTML({node:e}){let{label:t,href:S,title:w}=e.attrs,E=w?`[${t}]: ${S} "${w}"`:`[${t}]: ${S}`;return[`div`,{"data-link-ref-def":``,class:`link-ref-def`},E]}});function isBulletList(e){return e.type.name===`list`&&!e.attrs.ordered}function isOrderedList(e){return e.type.name===`list`&&!!e.attrs.ordered}function hasTaskItems(e){let t=!1;return e.forEach(e=>{e.type.name===`listItem`&&e.attrs.checked!==null&&(t=!0)}),t}function toggleListKind(e,t,S,w,E,D,O){let k=findParentNode(e=>e.type.name===`list`)(e.selection);if(k&&E(k.node)){let{$from:S,$to:E}=e.selection;return S.blockRange(E)?liftListItem$1(w)(e,t):!1}if(k){if(!t)return!0;let{tr:S}=e;return S.setNodeMarkup(k.pos,void 0,{...k.node.attrs,...D}),O!==void 0&&k.node.forEach((e,t)=>{if(e.type.name===`listItem`){let w=k.pos+1+t;S.setNodeMarkup(w,void 0,{...e.attrs,...O})}}),t(S),!0}return wrapInList$1(S,D)(e,void 0)?t?wrapInList$1(S,D)(e,S=>{if(O){let t=S.mapping.map(e.selection.$from.pos),w=S.doc.resolve(t);for(let e=w.depth;e>0;e--){let t=w.node(e);if(t.type.name===`listItem`){S.setNodeMarkup(w.before(e),void 0,{...t.attrs,...O});break}}}t(S)}):!0:!1}const ListNode=Node3.create({name:`list`,group:`block list`,content:`listItem+`,priority:60,addAttributes(){return{ordered:{default:!1},start:{default:1},spread:{default:!1},bulletMarker:{default:null},listMarkerDelimiter:{default:null}}},parseHTML(){return[{tag:`ul`,getAttrs:()=>({ordered:!1})},{tag:`ol`,getAttrs:e=>({ordered:!0,start:e.getAttribute(`start`)?Number(e.getAttribute(`start`)):1})}]},renderHTML({node:e,HTMLAttributes:t}){let S=e.attrs.ordered?`ol`:`ul`,w={};return e.attrs.ordered&&e.attrs.start!==1&&(w.start=e.attrs.start),[S,mergeAttributes(t,w),0]},addCommands(){return{toggleBulletList:()=>({state:e,dispatch:t})=>{let S=e.schema.nodes.list,w=e.schema.nodes.listItem;return!S||!w?!1:toggleListKind(e,t,S,w,e=>isBulletList(e)&&!hasTaskItems(e),{ordered:!1},{checked:null})},toggleOrderedList:()=>({state:e,dispatch:t})=>{let S=e.schema.nodes.list,w=e.schema.nodes.listItem;return!S||!w?!1:toggleListKind(e,t,S,w,e=>isOrderedList(e),{ordered:!0},{checked:null})},toggleTaskList:()=>({state:e,dispatch:t})=>{let S=e.schema.nodes.list,w=e.schema.nodes.listItem;return!S||!w?!1:toggleListKind(e,t,S,w,e=>isBulletList(e)&&hasTaskItems(e),{ordered:!1},{checked:!1})}}},addInputRules(){return[wrappingInputRule({find:/^\s*([-+*])(?!\s*\[[ xX]\])\s$/,type:this.type,getAttributes:e=>({ordered:!1,bulletMarker:e[1]})}),wrappingInputRule({find:/^\s*(\d+)([.)])\s$/,type:this.type,getAttributes:e=>({ordered:!0,start:Number(e[1]),listMarkerDelimiter:e[2]})}),new InputRule({find:/^\s*[-*+]\s\[([ xX])\]\s$/,handler:({state:e,range:t,match:S})=>{let w=e.schema.nodes.list;if(!w)return null;let E=S[1]!==` `,D=e.tr.delete(t.from,t.to),O=D.doc.resolve(t.from).blockRange();if(!O)return null;let k=findWrapping(O,w,{ordered:!1});if(!k)return null;D.wrap(O,k);let j=D.doc.resolve(D.mapping.map(t.from));for(let e=j.depth;e>0;e--){let t=j.node(e);if(t.type.name===`listItem`){D.setNodeMarkup(j.before(e),void 0,{...t.attrs,checked:E});break}}}})]},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList(),"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList(),"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}}),ListItemNode=Node3.create({name:`listItem`,content:`paragraph block*`,defining:!0,addAttributes(){return{checked:{default:null},spread:{default:!1}}},parseHTML(){return[{tag:`li`,getAttrs:e=>{let t=e.querySelector(`input[type="checkbox"]`);return{checked:t?t.checked:null}}}]},renderHTML({node:e,HTMLAttributes:t}){return e.attrs.checked===null?[`li`,mergeAttributes(t),0]:[`li`,mergeAttributes(t,{"data-type":`taskItem`,"data-checked":e.attrs.checked?`true`:`false`}),[`label`,{contenteditable:`false`},[`input`,{type:`checkbox`,...e.attrs.checked?{checked:`checked`}:{}}]],[`div`,0]]},addNodeView(){return({node:e,getPos:t,editor:S,HTMLAttributes:w})=>{let E=document.createElement(`li`);Object.entries(mergeAttributes(w,e.attrs.checked===null?{}:{"data-type":`taskItem`,"data-checked":String(!!e.attrs.checked)})).forEach(([e,t])=>{t!=null&&E.setAttribute(e,String(t))});let D=null,O=null,k=document.createElement(`div`);return e.attrs.checked!==null&&(D=document.createElement(`label`),D.contentEditable=`false`,O=document.createElement(`input`),O.type=`checkbox`,O.checked=!!e.attrs.checked,S.isEditable||(O.disabled=!0),O.addEventListener(`change`,()=>{let w=t();w===void 0||typeof w!=`number`||S.view.dispatch(S.view.state.tr.setNodeMarkup(w,void 0,{...e.attrs,checked:O?.checked??!1}))}),D.appendChild(O),E.appendChild(D)),E.appendChild(k),{dom:E,contentDOM:k,update(t){return t.type!==e.type||t.attrs.checked!==null!=(e.attrs.checked!==null)?!1:(O&&t.attrs.checked!==null&&(O.checked=!!t.attrs.checked,E.setAttribute(`data-checked`,String(!!t.attrs.checked))),e=t,!0)}}}},addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>{let{$from:e}=this.editor.state.selection;for(let t=e.depth;t>0;t--)if(e.node(t).type.name===`listItem`)return this.editor.commands.sinkListItem(this.name);return!1},"Shift-Tab":()=>{let{$from:e}=this.editor.state.selection;for(let t=e.depth;t>0;t--)if(e.node(t).type.name===`listItem`)return this.editor.commands.liftListItem(this.name);return!1}}}}),List=ListNode,ListItem=ListItemNode,MathInline=Node3.create({name:`mathInline`,group:`inline`,inline:!0,atom:!0,selectable:!0,priority:60,addAttributes(){return{formula:{default:``},id:{default:null},language:{default:`latex`}}},parseHTML(){return[{tag:`span[data-math-inline]`,getAttrs:e=>typeof e==`string`?!1:{formula:e.getAttribute(`data-formula`)||``,id:e.getAttribute(`id`)||null,language:e.getAttribute(`data-language`)||`latex`}}]},renderHTML({HTMLAttributes:e}){return[`span`,{"data-math-inline":``,"data-formula":e.formula,"data-language":e.language,...e.id?{id:e.id}:{}}]},addCommands(){return{insertMathInline:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{formula:e}})}}}),RawMdxFallback=Node3.create({name:`rawMdxFallback`,group:`block`,atom:!1,content:`text*`,isolating:!0,selectable:!0,defining:!0,priority:60,addAttributes(){return{reason:{default:``},originalSpan:{default:{start:0,end:0}}}},parseHTML(){let e=e=>typeof e==`string`?!1:{reason:e.getAttribute(`data-reason`)||``};return[{tag:`div[data-raw-mdx-fallback]`,getAttrs:e},{tag:`pre[data-raw-mdx-fallback]`,getAttrs:e}]},renderHTML({HTMLAttributes:e}){return[`div`,{"data-raw-mdx-fallback":``,"data-raw-badge":`raw`,"data-reason":e.reason,contenteditable:`false`,class:`raw-mdx-fallback`},0]},addNodeView(){return({HTMLAttributes:e})=>{let t=document.createElement(`div`);t.setAttribute(`data-raw-mdx-fallback`,``),t.setAttribute(`data-raw-badge`,`raw`),t.setAttribute(`contenteditable`,`false`),t.classList.add(`raw-mdx-fallback`),e.reason&&t.setAttribute(`data-reason`,e.reason);let S=document.createElement(`pre`);return S.classList.add(`raw-mdx-fallback-content`),S.setAttribute(`contenteditable`,`false`),t.appendChild(S),{dom:t,contentDOM:S,ignoreMutation:()=>!0}}}}),BlockquoteFidelity=index_default$3.extend({priority:60,addAttributes(){return{...this.parent?.(),sourceMarkerSpacings:{default:null}}}}),CodeMarkFidelity=index_default$2.extend({excludes:``,addAttributes(){return{...this.parent?.(),sourceFenceChar:{default:"`"},sourceFenceLength:{default:1}}}}),CommentBlock=Node3.create({name:`commentBlock`,group:`block`,content:`block+`,defining:!0,priority:60,addAttributes(){return{sourceForm:{default:`percent`,parseHTML:e=>e.getAttribute(`data-source-form`)===`html`?`html`:`percent`,renderHTML:e=>e.sourceForm===`html`?{"data-source-form":`html`}:{}},sourceLayout:{default:`block`,parseHTML:e=>e.getAttribute(`data-source-layout`)===`inline`?`inline`:`block`,renderHTML:e=>e.sourceLayout===`inline`?{"data-source-layout":`inline`}:{}}}},parseHTML(){return[{tag:`aside[data-comment-block]`},{tag:`aside.comment-block`}]},renderHTML({HTMLAttributes:e}){return[`aside`,{"data-comment-block":``,"data-clipboard-omit":`true`,class:`comment-block`,style:`display: none;`,...e},0]},addCommands(){return{setCommentBlock:()=>({commands:e})=>e.wrapIn(this.name),toggleCommentBlock:()=>({commands:e})=>e.toggleWrap(this.name),unsetCommentBlock:()=>({commands:e})=>e.lift(this.name)}}}),CommentMark=Mark.create({name:`comment`,priority:10,excludes:``,inclusive:!1,addAttributes(){return{sourceForm:{default:`percent`,parseHTML:e=>e.getAttribute(`data-source-form`)===`html`?`html`:`percent`,renderHTML:e=>e.sourceForm===`html`?{"data-source-form":`html`}:{}}}},parseHTML(){return[{tag:`span[data-comment-mark]`}]},renderHTML({HTMLAttributes:e}){return[`span`,{"data-comment-mark":``,"data-clipboard-omit":`true`,class:`comment-mark`,style:`display: none;`,...e},0]},addCommands(){return{setComment:()=>({commands:e})=>e.setMark(this.name),toggleComment:()=>({commands:e})=>e.toggleMark(this.name),unsetComment:()=>({commands:e})=>e.unsetMark(this.name)}}}),FootnoteDefinition=Node3.create({name:`footnoteDefinition`,group:`block`,content:`block+`,defining:!0,priority:60,addAttributes(){return{identifier:{default:``},label:{default:null}}},parseHTML(){let e=e=>{if(typeof e==`string`)return!1;let t=e.getAttribute(`data-footnote-id`)||``;return{identifier:t,label:t||null}};return[{tag:`aside[data-footnote-def]`,getAttrs:e},{tag:`aside.footnote-def`,getAttrs:e}]},renderHTML({node:e,HTMLAttributes:t}){let S=String(e.attrs.identifier??``);return[`aside`,{...t,"data-footnote-def":``,"data-footnote-id":S,id:`fn-${S}`,class:`footnote-def`},[`div`,{class:`footnote-body`},0],[`a`,{href:`#fnref-${S}`,class:`footnote-backref`,contentEditable:`false`,"aria-label":`Back to reference`},`↩`]]},addCommands(){return{insertFootnoteDefinition:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{identifier:e,label:e},content:[{type:`paragraph`}]})}}}),FootnoteReference=Node3.create({name:`footnoteReference`,group:`inline`,inline:!0,atom:!0,selectable:!0,draggable:!1,priority:60,addAttributes(){return{identifier:{default:``},label:{default:null}}},parseHTML(){return[{tag:`sup[data-footnote-ref]`,getAttrs:e=>{if(typeof e==`string`)return!1;let t=e.getAttribute(`data-footnote-id`)||``;return{identifier:t,label:t||null}}}]},renderHTML({node:e}){let t=String(e.attrs.identifier??``);return[`sup`,{id:`fnref-${t}`,"data-footnote-ref":``,"data-footnote-id":t,class:`footnote-ref`},[`a`,{href:`#fn-${t}`,class:`footnote-ref-link`},`[${t}]`]]},addCommands(){return{insertFootnoteReference:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{identifier:e,label:e}})}}}),ImageReferenceFidelity=Node3.create({name:`imageReference`,group:`inline`,inline:!0,atom:!0,priority:60,addAttributes(){return{alt:{default:``},label:{default:``},identifier:{default:``},referenceType:{default:`shortcut`}}},parseHTML(){return[{tag:`img[data-image-reference]`}]},renderHTML({node:e}){let{alt:t,label:S,referenceType:w}=e.attrs,E=t||S;return[`img`,{"data-image-reference":``,"data-reference-type":w,"data-label":S,alt:E}]}}),SourceLiteralMark=Mark.create({name:`sourceLiteral`,priority:10,excludes:``,inclusive:!1,addAttributes(){return{sourceRaw:{default:``}}},parseHTML(){return[{tag:`span[data-source-literal]`}]},renderHTML({HTMLAttributes:e}){return[`span`,{"data-source-literal":``,...e},0]}});function isValidSourceLiteralRaw(e,t){if(typeof e!=`string`||typeof t!=`string`||/[\x00-\x1F\x7F]/.test(e))return!1;let S=e.replaceAll(`\xA0`,` `),w=t.replaceAll(`\xA0`,` `);return S===w?!0:stripMarkdownBackslashEscapes(S)===w}function stripMarkdownBackslashEscapes(e){return e.replace(/\\([!-/:-@[-`{-~])/g,`$1`)}const TableFidelity=Table.extend({priority:60,addAttributes(){return{...this.parent?.(),sourceDashCounts:{default:null}}}}),TableCellFidelity=TableCell.extend({priority:60,addAttributes(){return{...this.parent?.(),sourcePadding:{default:null}}}}),TableHeaderFidelity=TableHeader.extend({priority:60,addAttributes(){return{...this.parent?.(),sourcePadding:{default:null}}}}),Tag=Node3.create({name:`tag`,group:`inline`,inline:!0,atom:!0,selectable:!0,priority:60,addAttributes(){return{value:{default:``}}},parseHTML(){return[{tag:`a[data-tag]`,getAttrs:e=>typeof e==`string`?!1:{value:e.getAttribute(`data-tag`)||``}}]},renderHTML({node:e,HTMLAttributes:t}){let S=String(e.attrs.value??``);return[`a`,{...t,"data-tag":S,href:`#tag/${S}`,class:`tag`},`#${S}`]},addCommands(){return{insertTag:e=>({chain:t})=>t().insertContent({type:`tag`,attrs:{value:e}}).run()}}}),THEMATIC_BREAK_INPUT_RE=/^(?:---|—-|___\s|\*\*\*\s)$/;function thematicBreakSourceRawFromMatch(e){let t=String(e[0]??``).replace(/\s+$/,``);return t===`—-`?`---`:t}const ThematicBreakFidelity=index_default$1.extend({name:`thematicBreak`,priority:60,addAttributes(){return{...this.parent?.(),sourceRaw:{default:`---`}}},addInputRules(){return[nodeInputRule({find:THEMATIC_BREAK_INPUT_RE,type:this.type,getAttributes:e=>({sourceRaw:thematicBreakSourceRawFromMatch(e)})})]}});function normalizeNullableString(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function getWikiLinkText(e){return e.alias?e.alias:e.anchor?`${e.target}#${e.anchor}`:e.target}const WikiLink=Node3.create({name:`wikiLink`,group:`inline`,inline:!0,atom:!0,priority:60,addAttributes(){return{target:{default:``},alias:{default:null},anchor:{default:null},resolved:{default:!1}}},parseHTML(){return[{tag:`span[data-wiki-link]`,getAttrs:e=>typeof e==`string`?!1:{target:e.getAttribute(`data-target`)||``,alias:normalizeNullableString(e.getAttribute(`data-alias`)),anchor:normalizeNullableString(e.getAttribute(`data-anchor`)),resolved:e.getAttribute(`data-resolved`)===`true`}},{tag:`a.wiki-link[data-target]`,priority:100,getAttrs:e=>{if(typeof e==`string`)return!1;let t=e.getAttribute(`data-target`)??``;return t?{target:t,alias:normalizeNullableString(e.getAttribute(`data-alias`)),anchor:normalizeNullableString(e.getAttribute(`data-anchor`)),resolved:!1}:!1}}]},renderHTML({node:e,HTMLAttributes:t}){let S=String(e.attrs.target??``),w=normalizeNullableString(e.attrs.alias),E=normalizeNullableString(e.attrs.anchor),D=e.attrs.resolved===!0;return[`span`,{...t,"data-wiki-link":``,"data-target":S,"data-alias":w??``,"data-anchor":E??``,"data-resolved":D?`true`:`false`},getWikiLinkText({target:S,alias:w,anchor:E})]}});function extensionOf(e){let t=e.split(`/`).pop()??e,S=t.lastIndexOf(`.`);return S<=0||S===t.length-1?``:t.slice(S+1).toLowerCase()}function labelFor(e){return e.alias?e.alias:e.anchor?`${e.target}#${e.anchor}`:e.target}const WikiLinkEmbed=Node3.create({name:`wikiLinkEmbed`,group:`inline`,inline:!0,atom:!0,priority:60,addAttributes(){return{target:{default:``},alias:{default:null},anchor:{default:null},resolvedSrc:{default:null,rendered:!1,parseHTML:()=>null}}},parseHTML(){let e=e=>typeof e==`string`||!e.hasAttribute(`data-wiki-embed`)?!1:{target:e.getAttribute(`data-target`)||``,alias:normalizeNullableString(e.getAttribute(`data-alias`)),anchor:normalizeNullableString(e.getAttribute(`data-anchor`))};return[{tag:`img[data-wiki-embed]`,getAttrs:e,priority:100},{tag:`a[data-wiki-embed]`,getAttrs:e,priority:100}]},renderHTML({node:e,HTMLAttributes:t}){let S=String(e.attrs.target??``),w=normalizeNullableString(e.attrs.alias),E=normalizeNullableString(e.attrs.anchor),D=normalizeNullableString(e.attrs.resolvedSrc),O=extensionOf(S);if(IMAGE_EXTENSIONS.has(O))return[`img`,{...t,"data-wiki-embed":``,"data-target":S,"data-alias":w??``,"data-anchor":E??``,src:D??S,alt:w??S}];let k=D??S;return[`a`,{...t,"data-wiki-embed":``,"data-target":S,"data-alias":w??``,"data-anchor":E??``,href:E?`${k}#${E}`:k,target:`_blank`,rel:`noopener noreferrer`},labelFor({target:S,alias:w,anchor:E})]}}),sharedExtensions=[JsxComponent,RawMdxFallback,JsxInline,MathInline,WikiLink,WikiLinkEmbed,Tag,List,ListItem,EmphasisFidelity,StrongFidelity,CodeMarkFidelity,CodeBlockFidelity,BlockquoteFidelity,HeadingFidelity,ThematicBreakFidelity,LinkFidelity,HtmlBlockFidelity,LinkRefDefFidelity,HardBreakFidelity,EscapeMark,SourceLiteralMark,index_default.configure({undoRedo:!1,bulletList:!1,orderedList:!1,listItem:!1,italic:!1,bold:!1,code:!1,codeBlock:!1,heading:!1,horizontalRule:!1,hardBreak:!1,link:!1,blockquote:!1,dropcursor:{color:`color-mix(in oklch, var(--primary) 50%, transparent)`,width:2}}),TableFidelity.configure({resizable:!0}),TableRow,TableHeaderFidelity,TableCellFidelity,ImageSrcFidelity.configure({inline:!0}),ImageReferenceFidelity,index_default$4,CommentMark,CommentBlock,FootnoteReference,FootnoteDefinition],FRONTMATTER_TAG_VALUE_RE=/^[a-zA-Z][\w/-]*$/;function stripLeadingHash(e){return e.startsWith(`#`)?e.slice(1):e}function coerceCandidates(e){return typeof e==`string`?[e]:Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function extractFrontmatterTags(e){if(!e||e.trim()===``)return[];let{map:t}=parseFrontmatterYaml(e);if(!t)return[];let S=coerceCandidates(t.tags),w=[];for(let e of S){let t=stripLeadingHash(e);FRONTMATTER_TAG_VALUE_RE.test(t)?w.push(t):console.warn(`[frontmatter-tags] dropping invalid tag entry: ${JSON.stringify(e)}`)}return w}const safeDocNameField=string$2().refine(e=>!e.includes(`..`)&&!e.startsWith(`/`)&&!e.includes(`\0`)&&!e.includes(`\\`),{message:`docName contains unsafe path characters`}).optional(),agentIdentityFields={agentId:string$2().optional(),agentName:string$2().optional(),colorSeed:string$2().optional(),clientName:string$2().optional(),clientVersion:string$2().optional(),label:string$2().optional()},summaryField=string$2().optional(),URN_UUID_RE=/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ShareConstructUrlRequestSchema=object$1({docPath:string$2().min(1)}).loose(),ShareConstructUrlErrorCodeSchema=_enum([`no-remote`,`detached-head`,`branch-not-on-origin`,`non-github-remote`,`invalid-path`]),ShareConstructUrlResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),shareUrl:string$2().min(1),blobUrl:string$2().min(1),branch:string$2().min(1)}).loose(),object$1({ok:literal(!1),error:ShareConstructUrlErrorCodeSchema,branch:string$2().min(1).optional()}).loose()]),SharePublishOwnerKindSchema=_enum([`user`,`org`]),SharePublishOwnerSchema=object$1({login:string$2().min(1),kind:SharePublishOwnerKindSchema,avatarUrl:string$2().optional()}).loose(),SharePublishOwnersErrorCodeSchema=_enum([`auth-required`,`network`]),SharePublishOwnersResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),owners:array(SharePublishOwnerSchema)}).loose(),object$1({ok:literal(!1),error:SharePublishOwnersErrorCodeSchema}).loose()]),SharePublishNameCheckResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),available:boolean$1()}).loose(),object$1({ok:literal(!1),error:SharePublishOwnersErrorCodeSchema}).loose()]),SharePublishVisibilitySchema=_enum([`public`,`private`]),SharePublishRequestSchema=object$1({owner:string$2().min(1),name:string$2().min(1),visibility:SharePublishVisibilitySchema,description:string$2().optional()}).loose(),SharePublishErrorCodeSchema=_enum([`name-conflict`,`saml-sso`,`auth-required`,`push-failed`,`init-failed`,`network`,`no-project`]),SharePublishResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),ownerLogin:string$2().min(1),repoName:string$2().min(1),cloneUrl:string$2().min(1),defaultBranch:string$2().min(1)}).loose(),object$1({ok:literal(!1),error:SharePublishErrorCodeSchema}).loose()]);function isValidBranchName(e){return!(typeof e!=`string`||e.length===0||e.startsWith(`-`)||/[\x00-\x1F\x7F]/.test(e)||/\s/.test(e)||e.includes(`:`)||e.split(`/`).includes(`..`))}const refineBranchName=e=>e.refine(isValidBranchName,`invalid branch name`);function isBranchNotFoundGitError(e){if(e==null)return!1;let t=e instanceof Error?e.message:String(e);return/couldn'?t find remote ref|Remote branch .+ not found/i.test(t)}const BranchInfoSharedFields={shareFileExists:boolean$1(),dirtyConflicts:object$1({conflicts:boolean$1(),files:array(string$2().min(1))}).loose(),branchIsLocal:boolean$1()},BranchInfoResponseSchema=discriminatedUnion(`detached`,[object$1({detached:literal(!1),currentBranch:string$2().min(1).nullable(),currentHeadSha:_null(),...BranchInfoSharedFields}).loose(),object$1({detached:literal(!0),currentBranch:_null(),currentHeadSha:string$2().min(1),...BranchInfoSharedFields}).loose()]),CheckoutRequestSchema=object$1({branch:refineBranchName(string$2().min(1)),principalId:string$2().optional()}).loose(),CheckoutFailureReasonSchema=_enum([`dirty-conflict`,`branch-not-found`,`fetch-failed`,`checkout-failed`,`branch-in-other-worktree`]),CheckoutResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0)}).loose(),object$1({ok:literal(!1),reason:CheckoutFailureReasonSchema,files:array(string$2().min(1)).optional(),otherWorktreePath:string$2().min(1).optional()}).loose()]),ServerInfoSuccessSchema=object$1({serverInstanceId:string$2().min(1),currentBranch:string$2().min(1).optional(),currentDiskAckSVs:record(string$2().min(1),string$2().min(1)).optional()}).loose(),PrincipalSuccessSchema=object$1({id:string$2().min(1),display_name:string$2().min(1),display_email:string$2(),source:_enum([`git-config`,`synthesized`]),created_at:string$2().min(1)}).loose(),ProblemTypeSchema=_enum(`urn:ok:error:malformed-upload.urn:ok:error:collision-exhaustion.urn:ok:error:storage-full.urn:ok:error:storage-readonly.urn:ok:error:storage-error.urn:ok:error:no-file-received.urn:ok:error:path-escape.urn:ok:error:method-not-allowed.urn:ok:error:invalid-request.urn:ok:error:payload-too-large.urn:ok:error:request-timeout.urn:ok:error:internal-server-error.urn:ok:error:loopback-required.urn:ok:error:invalid-origin.urn:ok:error:url-not-allowed.urn:ok:error:dir-outside-home.urn:ok:error:concurrent-operation.urn:ok:error:clone-failed.urn:ok:error:clone-timeout.urn:ok:error:server-start-failed.urn:ok:error:reserved-doc-name.urn:ok:error:target-not-found.urn:ok:error:stale-target.urn:ok:error:frontmatter-edit-not-supported.urn:ok:error:invalid-frontmatter-patch.urn:ok:error:frontmatter-malformed.urn:ok:error:no-active-session.urn:ok:error:too-many-agent-sessions.urn:ok:error:doc-not-found.urn:ok:error:doc-already-exists.urn:ok:error:doc-not-open.urn:ok:error:rollback-not-configured.urn:ok:error:doc-not-available.urn:ok:error:backlink-index-not-configured.urn:ok:error:file-rescan-not-configured.urn:ok:error:shadow-not-configured.urn:ok:error:host-not-allowed.urn:ok:error:principal-not-available.urn:ok:error:not-found.urn:ok:error:auth-failed.urn:ok:error:no-project-dir.urn:ok:error:server-open-failed.urn:ok:error:doc-in-conflict.urn:ok:error:no-conflict-tracked.urn:ok:error:sync-not-active.urn:ok:error:project-repo-not-configured.urn:ok:error:seed-prerequisite-missing.urn:ok:error:seed-invalid-root.urn:ok:error:tag-index-not-configured.urn:ok:error:template-not-found.urn:ok:error:unsupported-asset-type.urn:ok:error:asset-not-found.urn:ok:error:collab-server-not-running.urn:ok:error:gateway-timeout.urn:ok:error:cursor-not-installed.urn:ok:error:cursor-spawn-timeout.urn:ok:error:cursor-spawn-failed.urn:ok:error:handoff-target-not-installed.urn:ok:error:handoff-spawn-timeout.urn:ok:error:handoff-spawn-failed`.split(`.`));function assertNeverProblemType(e){throw Error(`Unexpected ProblemType variant: ${JSON.stringify(e)}`)}const ProblemDetailsSchema=object$1({type:ProblemTypeSchema,title:string$2().min(1),status:number$1().int().min(400).max(599),instance:string$2().regex(URN_UUID_RE,`instance must be urn:uuid:<uuid>`).optional(),detail:string$2().optional()}).loose(),UploadRequestSchema=object$1({parentDocName:string$2().min(1),agentId:string$2().min(1).optional(),agentName:string$2().min(1).optional()}).loose(),UploadAssetSuccessSchema=object$1({src:string$2().min(1),path:string$2().min(1).optional(),deduped:boolean$1().optional()}).loose(),LocalOpCloneRequestSchema=object$1({url:string$2().min(1),dir:string$2().min(1),branch:string$2().min(1).refine(isValidBranchName,`invalid branch name`).optional()}).loose(),StreamingProblemEventSchema=object$1({type:literal(`error`),problem:ProblemDetailsSchema}).loose();function reconstructAttrs(e,t){let S=Array.isArray(e.attrs.attributes)?e.attrs.attributes.filter(e=>typeof e==`object`&&!!e&&`type`in e):[],w=e.attrs.props??{},E=new Map,D=new Set;if(t)for(let e of t)e.omitOnDefault===!0&&`defaultValue`in e&&e.defaultValue!==void 0&&E.set(e.name,e.defaultValue),e.type===`string`&&e.required===!1&&e.defaultValue===void 0&&D.add(e.name);for(let[e,t]of Object.entries(w)){let w=S.findIndex(t=>t.type===`mdxJsxAttribute`&&t.name===e);if(E.has(e)&&Object.is(E.get(e),t)){w>=0&&S.splice(w,1);continue}if(D.has(e)&&t===``){w>=0&&S.splice(w,1);continue}let O=propToMdxJsxAttribute(e,t);w>=0?S[w]=O:S.push(O)}return S}function propToMdxJsxAttribute(e,t){if(t===!0)return{type:`mdxJsxAttribute`,name:e,value:null};if(t===!1)return{type:`mdxJsxAttribute`,name:e,value:{type:`mdxJsxAttributeValueExpression`,value:`false`}};if(t==null)return{type:`mdxJsxAttribute`,name:e,value:null};if(typeof t==`string`)return{type:`mdxJsxAttribute`,name:e,value:t};if(typeof t==`number`)return{type:`mdxJsxAttribute`,name:e,value:{type:`mdxJsxAttributeValueExpression`,value:JSON.stringify(t)}};if(typeof t==`object`){let S;try{S=JSON.stringify(t)}catch{S=String(t)}return{type:`mdxJsxAttribute`,name:e,value:{type:`mdxJsxAttributeValueExpression`,value:S}}}return{type:`mdxJsxAttribute`,name:e,value:String(t)}}function emitMdxJsx(e,t,S,w){return{type:`mdxJsxFlowElement`,name:e,attributes:reconstructAttrs(t,w),children:S.all(t),data:{}}}const LOOM_ID_RE=/^[A-Za-z0-9]{20,}$/,LOOM_TIMESTAMP_RE=/^(?:\d+s?|(?:\d+h)?(?:\d+m)?(?:\d+s)?)$/;function isLoomHost(e){let t=e.toLowerCase();return t===`loom.com`||t===`www.loom.com`}function extractLoomId(e){let t=e.pathname.match(/^\/(?:share|embed)\/([A-Za-z0-9]+)\/?$/);if(!t)return null;let S=t[1]??``;return LOOM_ID_RE.test(S)?S:null}function parseLoomUrl(e){if(typeof e!=`string`||e.length===0)return null;let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`||!isLoomHost(t.hostname))return null;let S=extractLoomId(t);if(!S)return null;let w=t.searchParams.get(`t`);return{id:S,startRaw:w&&w.length>0&&LOOM_TIMESTAMP_RE.test(w)?w:null}}function isLoomUrl(e){return parseLoomUrl(e)!==null}function isVimeoHost(e){let t=e.toLowerCase();return t===`vimeo.com`||t===`www.vimeo.com`||t===`player.vimeo.com`}function isVimeoUrl(e){if(typeof e!=`string`||e.length===0)return!1;let t;try{t=new URL(e)}catch{return!1}return t.protocol!==`http:`&&t.protocol!==`https:`?!1:isVimeoHost(t.hostname)}const YOUTUBE_VIDEO_ID_RE=/^[A-Za-z0-9_-]{11}$/;function isYouTubeHost(e){let t=e.toLowerCase();return t===`youtube.com`||t===`www.youtube.com`||t===`m.youtube.com`||t===`music.youtube.com`||t===`youtu.be`||t===`youtube-nocookie.com`||t===`www.youtube-nocookie.com`}function parseTimestampToSeconds(e){if(e.length===0)return null;if(/^[0-9]+$/.test(e)){let t=Number.parseInt(e,10);return t>0?t:null}let t=e.match(/^(?:([0-9]+)h)?(?:([0-9]+)m)?(?:([0-9]+)s?)?$/);if(!t)return null;let S=t[1]?Number.parseInt(t[1],10):0,w=t[2]?Number.parseInt(t[2],10):0,E=t[3]?Number.parseInt(t[3],10):0,D=S*3600+w*60+E;return D>0?D:null}function extractVideoId(e){if(e.hostname.toLowerCase()===`youtu.be`){let t=e.pathname.replace(/^\//,``).split(`/`)[0]??``;return YOUTUBE_VIDEO_ID_RE.test(t)?t:null}if(e.pathname===`/watch`){let t=e.searchParams.get(`v`)??``;return YOUTUBE_VIDEO_ID_RE.test(t)?t:null}let t=e.pathname.match(/^\/(?:embed|shorts|v)\/([A-Za-z0-9_-]{11})\/?$/);return t?t[1]??null:null}function parseYouTubeUrl(e){if(typeof e!=`string`||e.length===0)return null;let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`||!isYouTubeHost(t.hostname))return null;let S=extractVideoId(t);if(!S)return null;let w=t.searchParams.get(`t`)??t.searchParams.get(`start`)??``;return{id:S,startSeconds:w.length>0?parseTimestampToSeconds(w):null,noCookie:t.hostname.toLowerCase().endsWith(`youtube-nocookie.com`)}}const calloutProps=[{name:`type`,type:`enum`,enumValues:[`note`,`tip`,`important`,`warning`,`caution`,`abstract`,`info`,`todo`,`success`,`question`,`failure`,`danger`,`bug`,`example`,`quote`],defaultValue:`note`,required:!1,description:`Callout variant`},{name:`title`,type:`string`,required:!1,description:`Optional heading shown above the body`},{name:`icon`,type:`string`,required:!1,advanced:!0,description:"Custom lucide icon override (e.g. `lucide:Lightbulb`)"},{name:`color`,type:`string`,required:!1,advanced:!0,description:"Optional accent color override (hex — e.g. `#F05032`)"},{name:`collapsible`,type:`boolean`,required:!1,defaultValue:!1,advanced:!0,description:"Render as a foldable `<details>` (Obsidian `[!TYPE]+/-`)"},{name:`defaultOpen`,type:`boolean`,required:!1,defaultValue:!0,advanced:!0,description:`When collapsible, start in the open state`},{name:`children`,type:`reactnode`,required:!0,description:`Callout content`}],htmlImgProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`Image source URL`,accept:ALLOWED_IMAGE_MIME_TYPES,autoFocus:!0},{name:`alt`,type:`string`,required:!0,description:`Alt text`},{name:`width`,type:`number`,required:!1,advanced:!0,description:`Image width`},{name:`height`,type:`number`,required:!1,advanced:!0,description:`Image height`},{name:`srcset`,type:`string`,required:!1,advanced:!0,description:`Responsive image candidate set (e.g. "x.png 1x, y.png 2x")`},{name:`sizes`,type:`string`,required:!1,advanced:!0,description:`Responsive image sizes hint paired with srcset`},{name:`loading`,type:`enum`,enumValues:[`eager`,`lazy`],defaultValue:`lazy`,required:!1,advanced:!0,omitOnDefault:!0,description:`Native img loading strategy (defaults to lazy)`},{name:`title`,type:`string`,required:!1,advanced:!0,description:`Native HTML title attribute (tooltip)`},{name:`decoding`,type:`enum`,enumValues:[`sync`,`async`,`auto`],defaultValue:`auto`,required:!1,advanced:!0,omitOnDefault:!0,description:`Hint for how the browser should decode the image`},{name:`fetchpriority`,type:`enum`,enumValues:[`high`,`low`,`auto`],defaultValue:`auto`,required:!1,advanced:!0,omitOnDefault:!0,description:`Resource fetch priority hint`},{name:`crossorigin`,type:`enum`,enumValues:[`anonymous`,`use-credentials`],required:!1,advanced:!0,description:`CORS mode for the image fetch`},{name:`referrerpolicy`,type:`string`,required:!1,advanced:!0,description:`Referrer policy for the image fetch (HTML referrerpolicy values)`},{name:`align`,type:`enum`,enumValues:[`center`,`left`,`right`],defaultValue:`center`,required:!1,omitOnDefault:!0,description:`Alignment within the column`}],embedProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`Embedded page URL (must start with http:// or https://)`,autoFocus:!0},{name:`title`,type:`string`,required:!1,description:`Iframe title (accessible label for screen readers)`},{name:`width`,type:`string`,required:!1,advanced:!0,description:`Embed width as a CSS length (e.g. "100%", "640px")`},{name:`height`,type:`string`,required:!1,advanced:!0,description:`Embed height as a CSS length (e.g. "26rem", "480px")`},{name:`align`,type:`enum`,enumValues:[`center`,`left`,`right`],defaultValue:`center`,required:!1,omitOnDefault:!0,description:`Alignment within the column`}],htmlVideoProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`Video source URL`,accept:ALLOWED_VIDEO_MIME_TYPES,autoFocus:!0},{name:`controls`,type:`boolean`,required:!1,defaultValue:!0,advanced:!0,omitOnDefault:!0,description:`Show native HTML5 video controls (defaults to true)`,hideWhen:e=>typeof e.src==`string`&&(isVimeoUrl(e.src)||isLoomUrl(e.src))},{name:`autoplay`,type:`boolean`,required:!1,advanced:!0,description:`Begin playback as soon as possible (usually requires muted)`},{name:`poster`,type:`string`,required:!1,advanced:!0,description:`Poster image URL shown before playback`,accept:ALLOWED_IMAGE_MIME_TYPES,hideWhen:e=>typeof e.src==`string`&&(isVimeoUrl(e.src)||isLoomUrl(e.src))},{name:`width`,type:`number`,required:!1,advanced:!0,description:`Video width`},{name:`height`,type:`number`,required:!1,advanced:!0,description:`Video height`},{name:`title`,type:`string`,required:!1,advanced:!0,description:`Native HTML title attribute (tooltip)`},{name:`muted`,type:`boolean`,required:!1,advanced:!0,description:`Mute audio on load`},{name:`loop`,type:`boolean`,required:!1,advanced:!0,description:`Restart from the beginning when playback ends`,hideWhen:e=>typeof e.src==`string`&&isLoomUrl(e.src)},{name:`playsinline`,type:`boolean`,required:!1,advanced:!0,description:`Play inline on iOS rather than entering fullscreen`,hideWhen:e=>typeof e.src==`string`&&(isVimeoUrl(e.src)||isLoomUrl(e.src))},{name:`preload`,type:`enum`,enumValues:[`none`,`metadata`,`auto`],required:!1,advanced:!0,description:`Hint for how much of the video to preload`,hideWhen:e=>typeof e.src==`string`&&(parseYouTubeUrl(e.src)!==null||isVimeoUrl(e.src)||isLoomUrl(e.src))}],htmlAudioProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`Audio source URL`,accept:ALLOWED_AUDIO_MIME_TYPES,autoFocus:!0},{name:`controls`,type:`boolean`,required:!1,defaultValue:!0,advanced:!0,omitOnDefault:!0,description:`Show native HTML5 audio controls (defaults to true)`},{name:`autoplay`,type:`boolean`,required:!1,advanced:!0,description:`Begin playback as soon as possible (usually requires muted)`},{name:`title`,type:`string`,required:!1,advanced:!0,description:`Native HTML title attribute (tooltip)`},{name:`muted`,type:`boolean`,required:!1,advanced:!0,description:`Mute audio on load`},{name:`loop`,type:`boolean`,required:!1,advanced:!0,description:`Restart from the beginning when playback ends`},{name:`preload`,type:`enum`,enumValues:[`none`,`metadata`,`auto`],required:!1,advanced:!0,description:`Hint for how much of the audio to preload`}],accordionProps=[{name:`title`,type:`string`,required:!0,description:`Accordion heading shown inside the <summary>`},{name:`defaultOpen`,type:`boolean`,required:!1,defaultValue:!1,description:`When true, the accordion renders expanded on initial load`},{name:`icon`,type:`string`,required:!1,advanced:!0,description:"Custom lucide icon override (e.g. `lucide:Rocket`)"},{name:`description`,type:`string`,required:!1,advanced:!0,description:`Optional subtitle rendered below the title inside <summary>`},{name:`id`,type:`string`,required:!1,advanced:!0,description:"HTML id attribute for deep-linking (e.g. `#advanced-options`)"},{name:`name`,type:`string`,required:!1,advanced:!0,description:`HTML5 <details name=> group — siblings with the same name are mutually exclusive`}],gfmCalloutProps=[calloutProps[0],calloutProps[1],calloutProps[4],calloutProps[5],calloutProps[6]],commonMarkImageProps=[htmlImgProps[0],htmlImgProps[1],htmlImgProps[7]],htmlDetailsAccordionProps=[accordionProps[0],accordionProps[1],accordionProps[4],accordionProps[5]],wikiEmbedImageProps=[{name:`alias`,type:`string`,required:!1,defaultValue:``,description:"Alt text (Obsidian alias syntax: `![[file.png|alt text]]`)"}],wikiEmbedVideoProps=[{name:`alias`,type:`string`,required:!1,defaultValue:``,description:"Title text (Obsidian alias syntax: `![[clip.mp4|title]]`)"}],wikiEmbedAudioProps=[{name:`alias`,type:`string`,required:!1,defaultValue:``,description:"Title text (Obsidian alias syntax: `![[song.mp3|title]]`)"}],tabsProps=[{name:`id`,type:`string`,required:!1,advanced:!0,description:"HTML id attribute for deep-linking (e.g. `#install-tabs`)"}],tabProps=[{name:`label`,type:`string`,required:!0,autoFocus:!0,defaultValue:`Tab`,description:`Tab strip label — shown in the clickable pill at the top`},{name:`id`,type:`string`,required:!1,advanced:!0,description:"HTML id attribute for deep-linking (e.g. `#tab-npm`)"}],mathProps=[{name:`formula`,type:`string`,required:!0,autoFocus:!0,language:`latex`,description:`LaTeX math source (rendered with KaTeX in the browser)`},{name:`id`,type:`string`,required:!1,advanced:!0,description:"HTML id attribute for deep-linking (e.g. `#eq-pythagoras`)"},{name:`language`,type:`string`,required:!1,advanced:!0,description:"Forward-compat hint for the math source language (default `latex`). Reserved for future MathJax / Typst / AsciiMath substrates."}],dollarMathProps=[mathProps[0]],mathFenceProps=[mathProps[0]],mermaidProps=[{name:`chart`,type:`string`,required:!0,autoFocus:!0,language:`mermaid`,description:`Mermaid chart source (graph / flowchart / sequenceDiagram / class / state / etc.)`}],wikiEmbedFileProps=[{name:`alias`,type:`string`,required:!1,defaultValue:``,description:"Display name override (Obsidian alias syntax: `![[file.zip|label]]`)"}],fileProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`File URL`,accept:[`*/*`],autoFocus:!0}],pdfProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`PDF source URL`,accept:ALLOWED_PDF_MIME_TYPES,autoFocus:!0},{name:`title`,type:`string`,required:!1,advanced:!0,description:`Accessible label for the embedded PDF viewer`},{name:`anchor`,type:`string`,required:!1,advanced:!0,description:"PDF viewer parameters as a single URL-fragment string (e.g. `page=3&height=600`)"}],mirrorProps=[{name:`src`,type:`string`,required:!0,description:"Path of the source doc, extension-less (e.g. `api-spec`).",autoFocus:!0},{name:`anchor`,type:`string`,required:!0,description:"Id of the `<MirrorSource>` block within the source doc."}],mirrorSourceProps=[{name:`id`,type:`string`,required:!0,description:"Stable id agents and authors use to reference this block from `<Mirror>` elsewhere.",autoFocus:!0},{name:`children`,type:`reactnode`,required:!0,description:`Block content this MirrorSource owns — paragraphs, callouts, code, nested JSX, anything.`}];function escapeHtmlAttr(e){return e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function escapeHtmlText(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`)}function serializeWikiEmbed(e){let t=e.attrs.props,S=t?.target??``,w=typeof t?.alias==`string`&&t.alias.length>0?t.alias:null,E=typeof t?.anchor==`string`&&t.anchor.length>0?t.anchor:null,D=w??(E?`${S}#${E}`:S);return{type:`wikiLinkEmbed`,value:D,data:{target:S,anchor:E,alias:w},children:[{type:`text`,value:D}]}}const builtInComponents=[{name:`Callout`,surface:`canonical`,hasChildren:!0,props:calloutProps,icon:`MessageSquareWarning`,category:`content`,displayName:`Callout`,description:`Alert / admonition with 15 type variants — 5 GFM (note, tip, important, warning, caution) plus 10 Obsidian-parity (abstract, info, todo, success, question, failure, danger, bug, example, quote)`,searchTerms:[`note`,`tip`,`important`,`warning`,`caution`,`abstract`,`info`,`todo`,`success`,`question`,`failure`,`danger`,`bug`,`example`,`quote`,`alert`,`admonition`,`callout`],serialize:(e,t)=>emitMdxJsx(`Callout`,e,t,calloutProps)},{name:`img`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:htmlImgProps,icon:`Image`,category:`media`,displayName:`Image`,description:`Image with click-to-zoom and HTML-native attributes`,searchTerms:[`image`,`zoom`,`picture`,`photo`],placeholder:{label:`Add an image`},serialize:(e,t)=>emitMdxJsx(`img`,e,t,htmlImgProps)},{name:`video`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:htmlVideoProps,icon:`SquarePlay`,category:`media`,displayName:`Video`,description:`HTML5 video player with native controls`,searchTerms:[`video`,`media`,`player`,`mp4`,`webm`,`movie`],placeholder:{label:`Add a video`},serialize:(e,t)=>emitMdxJsx(`video`,e,t,htmlVideoProps)},{name:`audio`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:htmlAudioProps,icon:`Volume2`,category:`media`,displayName:`Audio`,description:`HTML5 audio player with native controls`,searchTerms:[`audio`,`sound`,`music`,`mp3`,`podcast`,`player`],placeholder:{label:`Add audio`},serialize:(e,t)=>emitMdxJsx(`audio`,e,t,htmlAudioProps)},{name:`Pdf`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:pdfProps,icon:`FileText`,category:`media`,displayName:`PDF`,description:"Embedded PDF viewer (`#page=N` to open at page N, `#height=N` for viewer height)",searchTerms:[`pdf`,`document`,`embed`,`pdfjs`],placeholder:{label:`Add a PDF`},serialize:(e,t)=>emitMdxJsx(`Pdf`,e,t,pdfProps)},{name:`File`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:fileProps,icon:`Paperclip`,category:`media`,displayName:`File`,description:`Downloadable file attachment — inline row with name + size + download link`,searchTerms:[`file`,`attachment`,`download`,`document`,`zip`,`docx`,`doc`],placeholder:{label:`Add a file`},serialize:(e,t)=>emitMdxJsx(`File`,e,t,fileProps)},{name:`Embed`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:embedProps,icon:`AppWindow`,category:`media`,displayName:`Embed`,description:`Inline web embed (iframe) — drop a URL, get a resizable preview pane`,searchTerms:[`embed`,`iframe`,`website`,`page`,`inline`,`frame`,`preview`],placeholder:{label:`Embed a URL`},serialize:(e,t)=>emitMdxJsx(`Embed`,e,t,embedProps)},{name:`Accordion`,surface:`canonical`,hasChildren:!0,props:accordionProps,icon:`ChevronRight`,category:`content`,displayName:`Accordion`,description:"Standalone expand/collapse via native HTML5 <details>/<summary>. Group siblings with the `name` prop for exclusive-accordion UX.",searchTerms:[`toggle`,`accordion`,`expandable`,`details`,`disclosure`,`collapse`,`fold`],exampleBody:`Body content revealed when the accordion is expanded.`,serialize:(e,t)=>emitMdxJsx(`Accordion`,e,t,accordionProps)},{name:`Tabs`,surface:`canonical`,hasChildren:!0,emptyChildName:`Tab`,props:tabsProps,icon:`LayoutPanelTop`,category:`content`,displayName:`Tabs`,description:"Horizontal tab strip + active panel below. Each `<Tab>` child is one panel; clickable pills at the top switch the active one. Active selection is ephemeral (resets on reload).",searchTerms:[`tabs`,`tabbed`,`panels`,`tabgroup`,`switcher`],exampleBody:`<Tab label="One">Body of the first tab panel.</Tab>
|
|
390
|
+
`)}const PREVIEW_THEME_TOKENS=[{name:`--chart-1`,light:`oklch(0.62 0.19 259)`,dark:`oklch(0.72 0.14 259)`},{name:`--chart-2`,light:`oklch(0.58 0.14 145)`,dark:`oklch(0.73 0.13 145)`},{name:`--chart-3`,light:`oklch(0.62 0.15 70)`,dark:`oklch(0.77 0.14 70)`},{name:`--chart-4`,light:`oklch(0.55 0.18 290)`,dark:`oklch(0.72 0.16 290)`},{name:`--chart-5`,light:`oklch(0.58 0.21 25)`,dark:`oklch(0.72 0.2 25)`},{name:`--primary`,light:`oklch(0.6321 0.1983 259.59)`,dark:`#69a3ff`},{name:`--primary-foreground`,light:`oklch(0.985 0 0)`,dark:`oklch(0.205 0 0)`},{name:`--foreground`,light:`oklch(0.145 0 0)`,dark:`oklch(0.985 0 0)`},{name:`--background`,light:`oklch(1 0 0)`,dark:`oklch(0.145 0 0)`},{name:`--card`,light:`oklch(1 0 0)`,dark:`oklch(0.205 0 0)`},{name:`--card-foreground`,light:`oklch(0.145 0 0)`,dark:`oklch(0.985 0 0)`},{name:`--muted-foreground`,light:`oklch(0.556 0 0)`,dark:`oklch(0.708 0 0)`},{name:`--border`,light:`oklch(0.922 0 0)`,dark:`oklch(1 0 0 / 10%)`},{name:`--destructive`,light:`oklch(0.577 0.245 27.325)`,dark:`oklch(0.704 0.191 22.216)`},{name:`--radius`,light:`0.625rem`,dark:`0.625rem`}],DEFAULT_SERVER_HOST=`localhost`,ALLOWED_IMAGE_MIME_TYPES=[`image/jpeg`,`image/png`,`image/gif`,`image/webp`,`image/svg+xml`],ALLOWED_VIDEO_MIME_TYPES=[`video/mp4`,`video/webm`,`video/ogg`],ALLOWED_AUDIO_MIME_TYPES=[`audio/mpeg`,`audio/wav`,`audio/ogg`],ALLOWED_PDF_MIME_TYPES=[`application/pdf`],IMAGE_EXTENSIONS=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`,`svg`]),VIDEO_EXTENSIONS=new Set([`mp4`,`webm`,`mov`,`m4v`,`mkv`]),PDF_EXTENSIONS=new Set([`pdf`]),AUDIO_EXTENSIONS=new Set([`mp3`,`wav`,`ogg`,`m4a`,`flac`,`aac`,`opus`]),FILE_ATTACHMENT_EXTENSIONS=new Set(`pdf.docx.xlsx.pptx.doc.xls.ppt.zip.7z.tar.gz.rar.csv.tsv.rtf.json.yaml.yml.xml.txt.pages.numbers.key.odt.ods.odp.epub.mobi`.split(`.`)),EXECUTABLE_BLOCKLIST_EXTENSIONS=new Set(`exe.bat.cmd.ps1.com.msi.vbs.js.jse.wsf.wsh.hta.sh.command.csh.ksh.bash.zsh.fish.desktop.action.workflow.html.htm.svg.xml.mhtml.svgz.dmg.pkg.mpkg.scpt.applescript.terminal.prefpane.webloc.inetloc.fileloc.jar.appimage.deb.rpm.msix.appx.ipa.apk.pif.scr.lnk.url`.split(`.`)),ASSET_EXTENSIONS=new Set(`png.jpg.jpeg.gif.webp.avif.svg.apng.heic.heif.tiff.bmp.ico.pdf.mp4.webm.mov.m4v.mkv.avi.flv.wmv.mpeg.mpg.mp3.wav.ogg.m4a.flac.aac.opus.zip.woff.woff2.ttf.otf.eot.docx.xlsx.pptx.csv.txt.rtf.json.toml.lock`.split(`.`)),INLINE_RENDERABLE_EXTENSIONS=new Set(`png.jpg.jpeg.gif.webp.avif.apng.heic.heif.tiff.bmp.ico.svg.pdf.mp4.webm.mov.m4v.mkv.mp3.wav.ogg.m4a.flac.aac.opus.json.toml.lock`.split(`.`)),DEFAULT_DEDUP_MODE=`same-dir`,WIKI_EMBED_EXTENSIONS=new Set(`png.jpg.jpeg.gif.webp.avif.svg.pdf.mp4.webm.mov.m4v.mkv.mp3.wav.ogg.m4a.flac.aac.opus.docx.xlsx.pptx.doc.xls.ppt.zip.7z.tar.gz.rar.csv.tsv.rtf.json.yaml.yml.xml.txt.pages.numbers.key.odt.ods.odp.epub.mobi`.split(`.`)),SIDEBAR_IMAGE_EXTENSIONS=[`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`],SIDEBAR_VIDEO_EXTENSIONS=[`mp4`,`webm`,`mov`,`m4v`],SIDEBAR_AUDIO_EXTENSIONS=[`mp3`,`wav`,`ogg`,`m4a`,`flac`,`aac`,`opus`],SIDEBAR_PDF_EXTENSIONS=[`pdf`],SIDEBAR_TEXT_EXTENSIONS=[`json`,`toml`,`lock`];function assertSubset(e,t,S){for(let w of t)if(!S.has(w))throw Error(`${e}: ${w} is not present in canonical upload constants`)}assertSubset(`SIDEBAR_IMAGE_ASSET_EXTENSIONS`,SIDEBAR_IMAGE_EXTENSIONS,IMAGE_EXTENSIONS),assertSubset(`SIDEBAR_VIDEO_ASSET_EXTENSIONS`,SIDEBAR_VIDEO_EXTENSIONS,VIDEO_EXTENSIONS),assertSubset(`SIDEBAR_AUDIO_ASSET_EXTENSIONS`,SIDEBAR_AUDIO_EXTENSIONS,AUDIO_EXTENSIONS),assertSubset(`SIDEBAR_PDF_ASSET_EXTENSIONS`,SIDEBAR_PDF_EXTENSIONS,PDF_EXTENSIONS),assertSubset(`FILE_ATTACHMENT_EXTENSIONS`,[...FILE_ATTACHMENT_EXTENSIONS],WIKI_EMBED_EXTENSIONS);const SIDEBAR_IMAGE_ASSET_EXTENSIONS=new Set(SIDEBAR_IMAGE_EXTENSIONS),SIDEBAR_VIDEO_ASSET_EXTENSIONS=new Set(SIDEBAR_VIDEO_EXTENSIONS),SIDEBAR_AUDIO_ASSET_EXTENSIONS=new Set(SIDEBAR_AUDIO_EXTENSIONS),SIDEBAR_PDF_ASSET_EXTENSIONS=new Set(SIDEBAR_PDF_EXTENSIONS),SIDEBAR_TEXT_ASSET_EXTENSIONS=new Set(SIDEBAR_TEXT_EXTENSIONS),SIDEBAR_RENDERABLE_ASSET_EXTENSIONS=new Set([...SIDEBAR_IMAGE_EXTENSIONS,...SIDEBAR_VIDEO_EXTENSIONS,...SIDEBAR_AUDIO_EXTENSIONS,...SIDEBAR_PDF_EXTENSIONS,...SIDEBAR_TEXT_EXTENSIONS]);assertSubset(`SIDEBAR_RENDERABLE_ASSET_EXTENSIONS`,[...SIDEBAR_RENDERABLE_ASSET_EXTENSIONS],INLINE_RENDERABLE_EXTENSIONS);function mediaKindForSidebarAssetExtension(e){let t=e.toLowerCase().replace(/^\./,``);return SIDEBAR_IMAGE_ASSET_EXTENSIONS.has(t)?`image`:SIDEBAR_VIDEO_ASSET_EXTENSIONS.has(t)?`video`:SIDEBAR_AUDIO_ASSET_EXTENSIONS.has(t)?`audio`:SIDEBAR_PDF_ASSET_EXTENSIONS.has(t)?`pdf`:SIDEBAR_TEXT_ASSET_EXTENSIONS.has(t)?`text`:null}const CodeBlockFidelity=index_default$11.extend({priority:60,addAttributes(){return{...this.parent?.(),fenceDelimiter:{default:"`"},fenceLength:{default:3},meta:{default:null},sourceStyle:{default:`fenced`}}}}),EmphasisFidelity=index_default$9.extend({name:`emphasis`,priority:60,addAttributes(){return{...this.parent?.(),sourceDelimiter:{default:`*`}}},addInputRules(){return[markInputRule({find:starInputRegex,type:this.type,getAttributes:{sourceDelimiter:`*`}}),markInputRule({find:underscoreInputRegex,type:this.type,getAttributes:{sourceDelimiter:`_`}})]}}),StrongFidelity=index_default$10.extend({name:`strong`,priority:60,addAttributes(){return{...this.parent?.(),sourceDelimiter:{default:`**`}}},addInputRules(){return[markInputRule({find:starInputRegex$1,type:this.type,getAttributes:{sourceDelimiter:`**`}}),markInputRule({find:underscoreInputRegex$1,type:this.type,getAttributes:{sourceDelimiter:`__`}})]}}),EscapeMark=Mark.create({name:`escapeMark`,priority:10,excludes:``,inclusive:!1,parseHTML(){return[{tag:`span[data-escape-mark]`}]},renderHTML(){return[`span`,{"data-escape-mark":``},0]}}),HardBreakFidelity=index_default$8.extend({priority:60,addAttributes(){return{...this.parent?.(),hardBreakStyle:{default:`backslash`}}}}),HeadingFidelity=index_default$7.extend({priority:60,addAttributes(){return{...this.parent?.(),headingStyle:{default:`atx`},sourceTrailingHashes:{default:null},sourceUnderlineLength:{default:null},sourceContiguousNext:{default:!1}}}}),HtmlBlockFidelity=Node3.create({name:`htmlBlock`,group:`block`,atom:!0,priority:60,addAttributes(){return{content:{default:``}}},parseHTML(){return[{tag:`div[data-html-block]`}]},renderHTML({node:e}){return[`div`,{"data-html-block":``,class:`html-block`},e.attrs.content]}});function toDesktopAssetHref(e){if(typeof e!=`string`||!e.startsWith(`/`))return e;let t=globalThis.window?.okDesktop?.config?.apiOrigin;return typeof t==`string`&&t?t+e:e}const ImageSrcFidelity=index_default$6.extend({priority:60,addAttributes(){return{...this.parent?.(),sourceUrl:{default:null,rendered:!1}}},renderHTML({HTMLAttributes:e}){let t=mergeAttributes(this.options.HTMLAttributes,e);return typeof t.src==`string`&&(t.src=toDesktopAssetHref(t.src)),[`img`,t]}}),JsxComponent=Node3.create({name:`jsxComponent`,group:`block`,atom:!1,content:`block*`,isolating:!0,selectable:!0,defining:!0,priority:60,addAttributes(){return{componentName:{default:``},kind:{default:`element`},attributes:{default:[]},sourceRaw:{default:``},sourceDirty:{default:!1},props:{default:{}}}},parseHTML(){return[{tag:`div[data-jsx-component]`,getAttrs:e=>typeof e==`string`?!1:{componentName:e.getAttribute(`data-component-name`)||``,sourceRaw:e.getAttribute(`data-source-raw`)||``}}]},renderHTML({HTMLAttributes:e}){return[`div`,{"data-jsx-component":``,"data-component-name":e.componentName,"data-source-raw":e.sourceRaw},0]},addCommands(){return{insertJsxComponent:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{sourceRaw:e}})}}}),JsxInline=Node3.create({name:`jsxInline`,group:`inline`,inline:!0,atom:!1,content:`text*`,isolating:!1,selectable:!0,priority:60,addAttributes(){return{}},parseHTML(){return[{tag:`span[data-jsx-inline]`}]},renderHTML(){return[`span`,{"data-jsx-inline":``},0]}}),SAFE_URL_SCHEMES=[`https`,`http`,`mailto`,`tel`,`ftp`,`sms`],SCHEME_ALT=SAFE_URL_SCHEMES.map(e=>`${e}:`).join(`|`),SAFE_URL_SCHEME_RE=RegExp(`^(?:${SCHEME_ALT}|\\/|#|\\?|\\.\\/|\\.\\.\\/)`,`i`);function isRelativeUrl(e){let t=e.trim();if(t===``)return!0;let S=t.indexOf(`:`);if(S===-1)return!0;let w=t.indexOf(`/`),E=t.indexOf(`?`),D=t.indexOf(`#`);return S>Math.min(w===-1?1/0:w,E===-1?1/0:E,D===-1?1/0:D)}const ALLOWED_LINK_SCHEMES=new Set(SAFE_URL_SCHEMES.map(e=>`${e}:`)),PLACEHOLDER_BASE=`https://placeholder.invalid`;function isAllowedLinkUri(e){try{let t=new URL(e,PLACEHOLDER_BASE);return ALLOWED_LINK_SCHEMES.has(t.protocol.toLowerCase())}catch{return!1}}const LinkFidelity=index_default$5.extend({priority:60,addOptions(){return{openOnClick:!1,enableClickSelection:!1,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:`http`,HTMLAttributes:{target:`_blank`,rel:`noopener noreferrer`},isAllowedUri:isAllowedLinkUri,validate:isAllowedLinkUri,shouldAutoLink:()=>!0}},addAttributes(){return{...this.parent?.(),linkStyle:{default:`inline`,rendered:!1},refLabel:{default:null,rendered:!1},sourceForm:{default:null,rendered:!1},target:{default:null,rendered:!1},anchor:{default:null,rendered:!1},alias:{default:null,rendered:!1},sourceUrlForm:{default:null,rendered:!1},sourceTitleMarker:{default:null,rendered:!1}}}}),LinkRefDefFidelity=Node3.create({name:`linkRefDef`,group:`block`,atom:!0,priority:60,addAttributes(){return{label:{default:``},href:{default:``},title:{default:null},sourceLayout:{default:null},sourceTitleMarker:{default:null}}},parseHTML(){return[{tag:`div[data-link-ref-def]`}]},renderHTML({node:e}){let{label:t,href:S,title:w}=e.attrs,E=w?`[${t}]: ${S} "${w}"`:`[${t}]: ${S}`;return[`div`,{"data-link-ref-def":``,class:`link-ref-def`},E]}});function isBulletList(e){return e.type.name===`list`&&!e.attrs.ordered}function isOrderedList(e){return e.type.name===`list`&&!!e.attrs.ordered}function hasTaskItems(e){let t=!1;return e.forEach(e=>{e.type.name===`listItem`&&e.attrs.checked!==null&&(t=!0)}),t}function toggleListKind(e,t,S,w,E,D,O){let k=findParentNode(e=>e.type.name===`list`)(e.selection);if(k&&E(k.node)){let{$from:S,$to:E}=e.selection;return S.blockRange(E)?liftListItem$1(w)(e,t):!1}if(k){if(!t)return!0;let{tr:S}=e;return S.setNodeMarkup(k.pos,void 0,{...k.node.attrs,...D}),O!==void 0&&k.node.forEach((e,t)=>{if(e.type.name===`listItem`){let w=k.pos+1+t;S.setNodeMarkup(w,void 0,{...e.attrs,...O})}}),t(S),!0}return wrapInList$1(S,D)(e,void 0)?t?wrapInList$1(S,D)(e,S=>{if(O){let t=S.mapping.map(e.selection.$from.pos),w=S.doc.resolve(t);for(let e=w.depth;e>0;e--){let t=w.node(e);if(t.type.name===`listItem`){S.setNodeMarkup(w.before(e),void 0,{...t.attrs,...O});break}}}t(S)}):!0:!1}const ListNode=Node3.create({name:`list`,group:`block list`,content:`listItem+`,priority:60,addAttributes(){return{ordered:{default:!1},start:{default:1},spread:{default:!1},bulletMarker:{default:null},listMarkerDelimiter:{default:null}}},parseHTML(){return[{tag:`ul`,getAttrs:()=>({ordered:!1})},{tag:`ol`,getAttrs:e=>({ordered:!0,start:e.getAttribute(`start`)?Number(e.getAttribute(`start`)):1})}]},renderHTML({node:e,HTMLAttributes:t}){let S=e.attrs.ordered?`ol`:`ul`,w={};return e.attrs.ordered&&e.attrs.start!==1&&(w.start=e.attrs.start),[S,mergeAttributes(t,w),0]},addCommands(){return{toggleBulletList:()=>({state:e,dispatch:t})=>{let S=e.schema.nodes.list,w=e.schema.nodes.listItem;return!S||!w?!1:toggleListKind(e,t,S,w,e=>isBulletList(e)&&!hasTaskItems(e),{ordered:!1},{checked:null})},toggleOrderedList:()=>({state:e,dispatch:t})=>{let S=e.schema.nodes.list,w=e.schema.nodes.listItem;return!S||!w?!1:toggleListKind(e,t,S,w,e=>isOrderedList(e),{ordered:!0},{checked:null})},toggleTaskList:()=>({state:e,dispatch:t})=>{let S=e.schema.nodes.list,w=e.schema.nodes.listItem;return!S||!w?!1:toggleListKind(e,t,S,w,e=>isBulletList(e)&&hasTaskItems(e),{ordered:!1},{checked:!1})}}},addInputRules(){return[wrappingInputRule({find:/^\s*([-+*])(?!\s*\[[ xX]\])\s$/,type:this.type,getAttributes:e=>({ordered:!1,bulletMarker:e[1]})}),wrappingInputRule({find:/^\s*(\d+)([.)])\s$/,type:this.type,getAttributes:e=>({ordered:!0,start:Number(e[1]),listMarkerDelimiter:e[2]})}),new InputRule({find:/^\s*[-*+]\s\[([ xX])\]\s$/,handler:({state:e,range:t,match:S})=>{let w=e.schema.nodes.list;if(!w)return null;let E=S[1]!==` `,D=e.tr.delete(t.from,t.to),O=D.doc.resolve(t.from).blockRange();if(!O)return null;let k=findWrapping(O,w,{ordered:!1});if(!k)return null;D.wrap(O,k);let j=D.doc.resolve(D.mapping.map(t.from));for(let e=j.depth;e>0;e--){let t=j.node(e);if(t.type.name===`listItem`){D.setNodeMarkup(j.before(e),void 0,{...t.attrs,checked:E});break}}}})]},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList(),"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList(),"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}}),ListItemNode=Node3.create({name:`listItem`,content:`paragraph block*`,defining:!0,addAttributes(){return{checked:{default:null},spread:{default:!1}}},parseHTML(){return[{tag:`li`,getAttrs:e=>{let t=e.querySelector(`input[type="checkbox"]`);return{checked:t?t.checked:null}}}]},renderHTML({node:e,HTMLAttributes:t}){return e.attrs.checked===null?[`li`,mergeAttributes(t),0]:[`li`,mergeAttributes(t,{"data-type":`taskItem`,"data-checked":e.attrs.checked?`true`:`false`}),[`label`,{contenteditable:`false`},[`input`,{type:`checkbox`,...e.attrs.checked?{checked:`checked`}:{}}]],[`div`,0]]},addNodeView(){return({node:e,getPos:t,editor:S,HTMLAttributes:w})=>{let E=document.createElement(`li`);Object.entries(mergeAttributes(w,e.attrs.checked===null?{}:{"data-type":`taskItem`,"data-checked":String(!!e.attrs.checked)})).forEach(([e,t])=>{t!=null&&E.setAttribute(e,String(t))});let D=null,O=null,k=document.createElement(`div`);return e.attrs.checked!==null&&(D=document.createElement(`label`),D.contentEditable=`false`,O=document.createElement(`input`),O.type=`checkbox`,O.checked=!!e.attrs.checked,S.isEditable||(O.disabled=!0),O.addEventListener(`change`,()=>{let w=t();w===void 0||typeof w!=`number`||S.view.dispatch(S.view.state.tr.setNodeMarkup(w,void 0,{...e.attrs,checked:O?.checked??!1}))}),D.appendChild(O),E.appendChild(D)),E.appendChild(k),{dom:E,contentDOM:k,update(t){return t.type!==e.type||t.attrs.checked!==null!=(e.attrs.checked!==null)?!1:(O&&t.attrs.checked!==null&&(O.checked=!!t.attrs.checked,E.setAttribute(`data-checked`,String(!!t.attrs.checked))),e=t,!0)}}}},addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>{let{$from:e}=this.editor.state.selection;for(let t=e.depth;t>0;t--)if(e.node(t).type.name===`listItem`)return this.editor.commands.sinkListItem(this.name);return!1},"Shift-Tab":()=>{let{$from:e}=this.editor.state.selection;for(let t=e.depth;t>0;t--)if(e.node(t).type.name===`listItem`)return this.editor.commands.liftListItem(this.name);return!1}}}}),List=ListNode,ListItem=ListItemNode,MathInline=Node3.create({name:`mathInline`,group:`inline`,inline:!0,atom:!0,selectable:!0,priority:60,addAttributes(){return{formula:{default:``},id:{default:null},language:{default:`latex`}}},parseHTML(){return[{tag:`span[data-math-inline]`,getAttrs:e=>typeof e==`string`?!1:{formula:e.getAttribute(`data-formula`)||``,id:e.getAttribute(`id`)||null,language:e.getAttribute(`data-language`)||`latex`}}]},renderHTML({HTMLAttributes:e}){return[`span`,{"data-math-inline":``,"data-formula":e.formula,"data-language":e.language,...e.id?{id:e.id}:{}}]},addCommands(){return{insertMathInline:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{formula:e}})}}}),RawMdxFallback=Node3.create({name:`rawMdxFallback`,group:`block`,atom:!1,content:`text*`,isolating:!0,selectable:!0,defining:!0,priority:60,addAttributes(){return{reason:{default:``},originalSpan:{default:{start:0,end:0}}}},parseHTML(){let e=e=>typeof e==`string`?!1:{reason:e.getAttribute(`data-reason`)||``};return[{tag:`div[data-raw-mdx-fallback]`,getAttrs:e},{tag:`pre[data-raw-mdx-fallback]`,getAttrs:e}]},renderHTML({HTMLAttributes:e}){return[`div`,{"data-raw-mdx-fallback":``,"data-raw-badge":`raw`,"data-reason":e.reason,contenteditable:`false`,class:`raw-mdx-fallback`},0]},addNodeView(){return({HTMLAttributes:e})=>{let t=document.createElement(`div`);t.setAttribute(`data-raw-mdx-fallback`,``),t.setAttribute(`data-raw-badge`,`raw`),t.setAttribute(`contenteditable`,`false`),t.classList.add(`raw-mdx-fallback`),e.reason&&t.setAttribute(`data-reason`,e.reason);let S=document.createElement(`pre`);return S.classList.add(`raw-mdx-fallback-content`),S.setAttribute(`contenteditable`,`false`),t.appendChild(S),{dom:t,contentDOM:S,ignoreMutation:()=>!0}}}}),BlockquoteFidelity=index_default$3.extend({priority:60,addAttributes(){return{...this.parent?.(),sourceMarkerSpacings:{default:null}}}}),CodeMarkFidelity=index_default$2.extend({excludes:``,addAttributes(){return{...this.parent?.(),sourceFenceChar:{default:"`"},sourceFenceLength:{default:1}}}}),CommentBlock=Node3.create({name:`commentBlock`,group:`block`,content:`block+`,defining:!0,priority:60,addAttributes(){return{sourceForm:{default:`percent`,parseHTML:e=>e.getAttribute(`data-source-form`)===`html`?`html`:`percent`,renderHTML:e=>e.sourceForm===`html`?{"data-source-form":`html`}:{}},sourceLayout:{default:`block`,parseHTML:e=>e.getAttribute(`data-source-layout`)===`inline`?`inline`:`block`,renderHTML:e=>e.sourceLayout===`inline`?{"data-source-layout":`inline`}:{}}}},parseHTML(){return[{tag:`aside[data-comment-block]`},{tag:`aside.comment-block`}]},renderHTML({HTMLAttributes:e}){return[`aside`,{"data-comment-block":``,"data-clipboard-omit":`true`,class:`comment-block`,style:`display: none;`,...e},0]},addCommands(){return{setCommentBlock:()=>({commands:e})=>e.wrapIn(this.name),toggleCommentBlock:()=>({commands:e})=>e.toggleWrap(this.name),unsetCommentBlock:()=>({commands:e})=>e.lift(this.name)}}}),CommentMark=Mark.create({name:`comment`,priority:10,excludes:``,inclusive:!1,addAttributes(){return{sourceForm:{default:`percent`,parseHTML:e=>e.getAttribute(`data-source-form`)===`html`?`html`:`percent`,renderHTML:e=>e.sourceForm===`html`?{"data-source-form":`html`}:{}}}},parseHTML(){return[{tag:`span[data-comment-mark]`}]},renderHTML({HTMLAttributes:e}){return[`span`,{"data-comment-mark":``,"data-clipboard-omit":`true`,class:`comment-mark`,style:`display: none;`,...e},0]},addCommands(){return{setComment:()=>({commands:e})=>e.setMark(this.name),toggleComment:()=>({commands:e})=>e.toggleMark(this.name),unsetComment:()=>({commands:e})=>e.unsetMark(this.name)}}}),FootnoteDefinition=Node3.create({name:`footnoteDefinition`,group:`block`,content:`block+`,defining:!0,priority:60,addAttributes(){return{identifier:{default:``},label:{default:null}}},parseHTML(){let e=e=>{if(typeof e==`string`)return!1;let t=e.getAttribute(`data-footnote-id`)||``;return{identifier:t,label:t||null}};return[{tag:`aside[data-footnote-def]`,getAttrs:e},{tag:`aside.footnote-def`,getAttrs:e}]},renderHTML({node:e,HTMLAttributes:t}){let S=String(e.attrs.identifier??``);return[`aside`,{...t,"data-footnote-def":``,"data-footnote-id":S,id:`fn-${S}`,class:`footnote-def`},[`div`,{class:`footnote-body`},0],[`a`,{href:`#fnref-${S}`,class:`footnote-backref`,contentEditable:`false`,"aria-label":`Back to reference`},`↩`]]},addCommands(){return{insertFootnoteDefinition:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{identifier:e,label:e},content:[{type:`paragraph`}]})}}}),FootnoteReference=Node3.create({name:`footnoteReference`,group:`inline`,inline:!0,atom:!0,selectable:!0,draggable:!1,priority:60,addAttributes(){return{identifier:{default:``},label:{default:null}}},parseHTML(){return[{tag:`sup[data-footnote-ref]`,getAttrs:e=>{if(typeof e==`string`)return!1;let t=e.getAttribute(`data-footnote-id`)||``;return{identifier:t,label:t||null}}}]},renderHTML({node:e}){let t=String(e.attrs.identifier??``);return[`sup`,{id:`fnref-${t}`,"data-footnote-ref":``,"data-footnote-id":t,class:`footnote-ref`},[`a`,{href:`#fn-${t}`,class:`footnote-ref-link`},`[${t}]`]]},addCommands(){return{insertFootnoteReference:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{identifier:e,label:e}})}}}),ImageReferenceFidelity=Node3.create({name:`imageReference`,group:`inline`,inline:!0,atom:!0,priority:60,addAttributes(){return{alt:{default:``},label:{default:``},identifier:{default:``},referenceType:{default:`shortcut`}}},parseHTML(){return[{tag:`img[data-image-reference]`}]},renderHTML({node:e}){let{alt:t,label:S,referenceType:w}=e.attrs,E=t||S;return[`img`,{"data-image-reference":``,"data-reference-type":w,"data-label":S,alt:E}]}}),SourceLiteralMark=Mark.create({name:`sourceLiteral`,priority:10,excludes:``,inclusive:!1,addAttributes(){return{sourceRaw:{default:``}}},parseHTML(){return[{tag:`span[data-source-literal]`}]},renderHTML({HTMLAttributes:e}){return[`span`,{"data-source-literal":``,...e},0]}});function isValidSourceLiteralRaw(e,t){if(typeof e!=`string`||typeof t!=`string`||/[\x00-\x1F\x7F]/.test(e))return!1;let S=e.replaceAll(`\xA0`,` `),w=t.replaceAll(`\xA0`,` `);return S===w?!0:stripMarkdownBackslashEscapes(S)===w}function stripMarkdownBackslashEscapes(e){return e.replace(/\\([!-/:-@[-`{-~])/g,`$1`)}const TableFidelity=Table.extend({priority:60,addAttributes(){return{...this.parent?.(),sourceDashCounts:{default:null}}}}),TableCellFidelity=TableCell.extend({priority:60,addAttributes(){return{...this.parent?.(),sourcePadding:{default:null}}}}),TableHeaderFidelity=TableHeader.extend({priority:60,addAttributes(){return{...this.parent?.(),sourcePadding:{default:null}}}}),Tag=Node3.create({name:`tag`,group:`inline`,inline:!0,atom:!0,selectable:!0,priority:60,addAttributes(){return{value:{default:``}}},parseHTML(){return[{tag:`a[data-tag]`,getAttrs:e=>typeof e==`string`?!1:{value:e.getAttribute(`data-tag`)||``}}]},renderHTML({node:e,HTMLAttributes:t}){let S=String(e.attrs.value??``);return[`a`,{...t,"data-tag":S,href:`#tag/${S}`,class:`tag`},`#${S}`]},addCommands(){return{insertTag:e=>({chain:t})=>t().insertContent({type:`tag`,attrs:{value:e}}).run()}}}),THEMATIC_BREAK_INPUT_RE=/^(?:---|—-|___\s|\*\*\*\s)$/;function thematicBreakSourceRawFromMatch(e){let t=String(e[0]??``).replace(/\s+$/,``);return t===`—-`?`---`:t}const ThematicBreakFidelity=index_default$1.extend({name:`thematicBreak`,priority:60,addAttributes(){return{...this.parent?.(),sourceRaw:{default:`---`}}},addInputRules(){return[nodeInputRule({find:THEMATIC_BREAK_INPUT_RE,type:this.type,getAttributes:e=>({sourceRaw:thematicBreakSourceRawFromMatch(e)})})]}});function normalizeNullableString(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function getWikiLinkText(e){return e.alias?e.alias:e.anchor?`${e.target}#${e.anchor}`:e.target}const WikiLink=Node3.create({name:`wikiLink`,group:`inline`,inline:!0,atom:!0,priority:60,addAttributes(){return{target:{default:``},alias:{default:null},anchor:{default:null},resolved:{default:!1}}},parseHTML(){return[{tag:`span[data-wiki-link]`,getAttrs:e=>typeof e==`string`?!1:{target:e.getAttribute(`data-target`)||``,alias:normalizeNullableString(e.getAttribute(`data-alias`)),anchor:normalizeNullableString(e.getAttribute(`data-anchor`)),resolved:e.getAttribute(`data-resolved`)===`true`}},{tag:`a.wiki-link[data-target]`,priority:100,getAttrs:e=>{if(typeof e==`string`)return!1;let t=e.getAttribute(`data-target`)??``;return t?{target:t,alias:normalizeNullableString(e.getAttribute(`data-alias`)),anchor:normalizeNullableString(e.getAttribute(`data-anchor`)),resolved:!1}:!1}}]},renderHTML({node:e,HTMLAttributes:t}){let S=String(e.attrs.target??``),w=normalizeNullableString(e.attrs.alias),E=normalizeNullableString(e.attrs.anchor),D=e.attrs.resolved===!0;return[`span`,{...t,"data-wiki-link":``,"data-target":S,"data-alias":w??``,"data-anchor":E??``,"data-resolved":D?`true`:`false`},getWikiLinkText({target:S,alias:w,anchor:E})]}});function extensionOf(e){let t=e.split(`/`).pop()??e,S=t.lastIndexOf(`.`);return S<=0||S===t.length-1?``:t.slice(S+1).toLowerCase()}function labelFor(e){return e.alias?e.alias:e.anchor?`${e.target}#${e.anchor}`:e.target}const WikiLinkEmbed=Node3.create({name:`wikiLinkEmbed`,group:`inline`,inline:!0,atom:!0,priority:60,addAttributes(){return{target:{default:``},alias:{default:null},anchor:{default:null},resolvedSrc:{default:null,rendered:!1,parseHTML:()=>null}}},parseHTML(){let e=e=>typeof e==`string`||!e.hasAttribute(`data-wiki-embed`)?!1:{target:e.getAttribute(`data-target`)||``,alias:normalizeNullableString(e.getAttribute(`data-alias`)),anchor:normalizeNullableString(e.getAttribute(`data-anchor`))};return[{tag:`img[data-wiki-embed]`,getAttrs:e,priority:100},{tag:`a[data-wiki-embed]`,getAttrs:e,priority:100}]},renderHTML({node:e,HTMLAttributes:t}){let S=String(e.attrs.target??``),w=normalizeNullableString(e.attrs.alias),E=normalizeNullableString(e.attrs.anchor),D=normalizeNullableString(e.attrs.resolvedSrc),O=extensionOf(S);if(IMAGE_EXTENSIONS.has(O))return[`img`,{...t,"data-wiki-embed":``,"data-target":S,"data-alias":w??``,"data-anchor":E??``,src:D??S,alt:w??S}];let k=D??S;return[`a`,{...t,"data-wiki-embed":``,"data-target":S,"data-alias":w??``,"data-anchor":E??``,href:E?`${k}#${E}`:k,target:`_blank`,rel:`noopener noreferrer`},labelFor({target:S,alias:w,anchor:E})]}}),sharedExtensions=[JsxComponent,RawMdxFallback,JsxInline,MathInline,WikiLink,WikiLinkEmbed,Tag,List,ListItem,EmphasisFidelity,StrongFidelity,CodeMarkFidelity,CodeBlockFidelity,BlockquoteFidelity,HeadingFidelity,ThematicBreakFidelity,LinkFidelity,HtmlBlockFidelity,LinkRefDefFidelity,HardBreakFidelity,EscapeMark,SourceLiteralMark,index_default.configure({undoRedo:!1,bulletList:!1,orderedList:!1,listItem:!1,italic:!1,bold:!1,code:!1,codeBlock:!1,heading:!1,horizontalRule:!1,hardBreak:!1,link:!1,blockquote:!1,dropcursor:{color:`color-mix(in oklch, var(--primary) 50%, transparent)`,width:2}}),TableFidelity.configure({resizable:!0}),TableRow,TableHeaderFidelity,TableCellFidelity,ImageSrcFidelity.configure({inline:!0}),ImageReferenceFidelity,index_default$4,CommentMark,CommentBlock,FootnoteReference,FootnoteDefinition],FRONTMATTER_TAG_VALUE_RE=/^[a-zA-Z][\w/-]*$/;function stripLeadingHash(e){return e.startsWith(`#`)?e.slice(1):e}function coerceCandidates(e){return typeof e==`string`?[e]:Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function extractFrontmatterTags(e){if(!e||e.trim()===``)return[];let{map:t}=parseFrontmatterYaml(e);if(!t)return[];let S=coerceCandidates(t.tags),w=[];for(let e of S){let t=stripLeadingHash(e);FRONTMATTER_TAG_VALUE_RE.test(t)?w.push(t):console.warn(`[frontmatter-tags] dropping invalid tag entry: ${JSON.stringify(e)}`)}return w}const safeDocNameField=string$2().refine(e=>!e.includes(`..`)&&!e.startsWith(`/`)&&!e.includes(`\0`)&&!e.includes(`\\`),{message:`docName contains unsafe path characters`}).optional(),agentIdentityFields={agentId:string$2().optional(),agentName:string$2().optional(),colorSeed:string$2().optional(),clientName:string$2().optional(),clientVersion:string$2().optional(),label:string$2().optional()},summaryField=string$2().optional(),URN_UUID_RE=/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ShareConstructUrlRequestSchema=object$1({docPath:string$2().min(1)}).loose(),ShareConstructUrlErrorCodeSchema=_enum([`no-remote`,`detached-head`,`branch-not-on-origin`,`non-github-remote`,`invalid-path`]),ShareConstructUrlResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),shareUrl:string$2().min(1),blobUrl:string$2().min(1),branch:string$2().min(1)}).loose(),object$1({ok:literal(!1),error:ShareConstructUrlErrorCodeSchema,branch:string$2().min(1).optional()}).loose()]),SharePublishOwnerKindSchema=_enum([`user`,`org`]),SharePublishOwnerSchema=object$1({login:string$2().min(1),kind:SharePublishOwnerKindSchema,avatarUrl:string$2().optional()}).loose(),SharePublishOwnersErrorCodeSchema=_enum([`auth-required`,`network`]),SharePublishOwnersResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),owners:array(SharePublishOwnerSchema)}).loose(),object$1({ok:literal(!1),error:SharePublishOwnersErrorCodeSchema}).loose()]),SharePublishNameCheckResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),available:boolean$1()}).loose(),object$1({ok:literal(!1),error:SharePublishOwnersErrorCodeSchema}).loose()]),SharePublishVisibilitySchema=_enum([`public`,`private`]),SharePublishRequestSchema=object$1({owner:string$2().min(1),name:string$2().min(1),visibility:SharePublishVisibilitySchema,description:string$2().optional()}).loose(),SharePublishErrorCodeSchema=_enum([`name-conflict`,`saml-sso`,`auth-required`,`push-failed`,`init-failed`,`network`,`no-project`]),SharePublishResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),ownerLogin:string$2().min(1),repoName:string$2().min(1),cloneUrl:string$2().min(1),defaultBranch:string$2().min(1)}).loose(),object$1({ok:literal(!1),error:SharePublishErrorCodeSchema}).loose()]);function isValidBranchName(e){return!(typeof e!=`string`||e.length===0||e.startsWith(`-`)||/[\x00-\x1F\x7F]/.test(e)||/\s/.test(e)||e.includes(`:`)||e.split(`/`).includes(`..`))}const refineBranchName=e=>e.refine(isValidBranchName,`invalid branch name`);function isBranchNotFoundGitError(e){if(e==null)return!1;let t=e instanceof Error?e.message:String(e);return/couldn'?t find remote ref|Remote branch .+ not found/i.test(t)}const BranchInfoSharedFields={shareFileExists:boolean$1(),dirtyConflicts:object$1({conflicts:boolean$1(),files:array(string$2().min(1))}).loose(),branchIsLocal:boolean$1()},BranchInfoResponseSchema=discriminatedUnion(`detached`,[object$1({detached:literal(!1),currentBranch:string$2().min(1).nullable(),currentHeadSha:_null(),...BranchInfoSharedFields}).loose(),object$1({detached:literal(!0),currentBranch:_null(),currentHeadSha:string$2().min(1),...BranchInfoSharedFields}).loose()]),CheckoutRequestSchema=object$1({branch:refineBranchName(string$2().min(1)),principalId:string$2().optional()}).loose(),CheckoutFailureReasonSchema=_enum([`dirty-conflict`,`branch-not-found`,`fetch-failed`,`checkout-failed`,`branch-in-other-worktree`]),CheckoutResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0)}).loose(),object$1({ok:literal(!1),reason:CheckoutFailureReasonSchema,files:array(string$2().min(1)).optional(),otherWorktreePath:string$2().min(1).optional()}).loose()]),ServerInfoSuccessSchema=object$1({serverInstanceId:string$2().min(1),currentBranch:string$2().min(1).optional(),currentDiskAckSVs:record(string$2().min(1),string$2().min(1)).optional()}).loose(),PrincipalSuccessSchema=object$1({id:string$2().min(1),display_name:string$2().min(1),display_email:string$2(),source:_enum([`git-config`,`synthesized`]),created_at:string$2().min(1)}).loose(),ProblemTypeSchema=_enum(`urn:ok:error:malformed-upload.urn:ok:error:collision-exhaustion.urn:ok:error:storage-full.urn:ok:error:storage-readonly.urn:ok:error:storage-error.urn:ok:error:no-file-received.urn:ok:error:path-escape.urn:ok:error:method-not-allowed.urn:ok:error:invalid-request.urn:ok:error:payload-too-large.urn:ok:error:request-timeout.urn:ok:error:internal-server-error.urn:ok:error:loopback-required.urn:ok:error:invalid-origin.urn:ok:error:url-not-allowed.urn:ok:error:dir-outside-home.urn:ok:error:concurrent-operation.urn:ok:error:clone-failed.urn:ok:error:clone-timeout.urn:ok:error:server-start-failed.urn:ok:error:reserved-doc-name.urn:ok:error:target-not-found.urn:ok:error:stale-target.urn:ok:error:frontmatter-edit-not-supported.urn:ok:error:invalid-frontmatter-patch.urn:ok:error:frontmatter-malformed.urn:ok:error:no-active-session.urn:ok:error:too-many-agent-sessions.urn:ok:error:doc-not-found.urn:ok:error:doc-already-exists.urn:ok:error:doc-not-open.urn:ok:error:rollback-not-configured.urn:ok:error:doc-not-available.urn:ok:error:backlink-index-not-configured.urn:ok:error:file-rescan-not-configured.urn:ok:error:shadow-not-configured.urn:ok:error:host-not-allowed.urn:ok:error:principal-not-available.urn:ok:error:not-found.urn:ok:error:auth-failed.urn:ok:error:no-project-dir.urn:ok:error:server-open-failed.urn:ok:error:doc-in-conflict.urn:ok:error:no-conflict-tracked.urn:ok:error:sync-not-active.urn:ok:error:project-repo-not-configured.urn:ok:error:seed-prerequisite-missing.urn:ok:error:seed-invalid-root.urn:ok:error:tag-index-not-configured.urn:ok:error:template-not-found.urn:ok:error:unsupported-asset-type.urn:ok:error:asset-not-found.urn:ok:error:collab-server-not-running.urn:ok:error:gateway-timeout.urn:ok:error:cursor-not-installed.urn:ok:error:cursor-spawn-timeout.urn:ok:error:cursor-spawn-failed.urn:ok:error:handoff-target-not-installed.urn:ok:error:handoff-spawn-timeout.urn:ok:error:handoff-spawn-failed`.split(`.`));function assertNeverProblemType(e){throw Error(`Unexpected ProblemType variant: ${JSON.stringify(e)}`)}const ProblemDetailsSchema=object$1({type:ProblemTypeSchema,title:string$2().min(1),status:number$1().int().min(400).max(599),instance:string$2().regex(URN_UUID_RE,`instance must be urn:uuid:<uuid>`).optional(),detail:string$2().optional()}).loose(),UploadRequestSchema=object$1({parentDocName:string$2().min(1),agentId:string$2().min(1).optional(),agentName:string$2().min(1).optional()}).loose(),UploadAssetSuccessSchema=object$1({src:string$2().min(1),path:string$2().min(1).optional(),deduped:boolean$1().optional()}).loose(),LocalOpCloneRequestSchema=object$1({url:string$2().min(1),dir:string$2().min(1),branch:string$2().min(1).refine(isValidBranchName,`invalid branch name`).optional()}).loose(),StreamingProblemEventSchema=object$1({type:literal(`error`),problem:ProblemDetailsSchema}).loose();function reconstructAttrs(e,t){let S=Array.isArray(e.attrs.attributes)?e.attrs.attributes.filter(e=>typeof e==`object`&&!!e&&`type`in e):[],w=e.attrs.props??{},E=new Map,D=new Set;if(t)for(let e of t)e.omitOnDefault===!0&&`defaultValue`in e&&e.defaultValue!==void 0&&E.set(e.name,e.defaultValue),e.type===`string`&&e.required===!1&&e.defaultValue===void 0&&D.add(e.name);for(let[e,t]of Object.entries(w)){let w=S.findIndex(t=>t.type===`mdxJsxAttribute`&&t.name===e);if(E.has(e)&&Object.is(E.get(e),t)){w>=0&&S.splice(w,1);continue}if(D.has(e)&&t===``){w>=0&&S.splice(w,1);continue}let O=propToMdxJsxAttribute(e,t);w>=0?S[w]=O:S.push(O)}return S}function propToMdxJsxAttribute(e,t){if(t===!0)return{type:`mdxJsxAttribute`,name:e,value:null};if(t===!1)return{type:`mdxJsxAttribute`,name:e,value:{type:`mdxJsxAttributeValueExpression`,value:`false`}};if(t==null)return{type:`mdxJsxAttribute`,name:e,value:null};if(typeof t==`string`)return{type:`mdxJsxAttribute`,name:e,value:t};if(typeof t==`number`)return{type:`mdxJsxAttribute`,name:e,value:{type:`mdxJsxAttributeValueExpression`,value:JSON.stringify(t)}};if(typeof t==`object`){let S;try{S=JSON.stringify(t)}catch{S=String(t)}return{type:`mdxJsxAttribute`,name:e,value:{type:`mdxJsxAttributeValueExpression`,value:S}}}return{type:`mdxJsxAttribute`,name:e,value:String(t)}}function emitMdxJsx(e,t,S,w){return{type:`mdxJsxFlowElement`,name:e,attributes:reconstructAttrs(t,w),children:S.all(t),data:{}}}const LOOM_ID_RE=/^[A-Za-z0-9]{20,}$/,LOOM_TIMESTAMP_RE=/^(?:\d+s?|(?:\d+h)?(?:\d+m)?(?:\d+s)?)$/;function isLoomHost(e){let t=e.toLowerCase();return t===`loom.com`||t===`www.loom.com`}function extractLoomId(e){let t=e.pathname.match(/^\/(?:share|embed)\/([A-Za-z0-9]+)\/?$/);if(!t)return null;let S=t[1]??``;return LOOM_ID_RE.test(S)?S:null}function parseLoomUrl(e){if(typeof e!=`string`||e.length===0)return null;let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`||!isLoomHost(t.hostname))return null;let S=extractLoomId(t);if(!S)return null;let w=t.searchParams.get(`t`);return{id:S,startRaw:w&&w.length>0&&LOOM_TIMESTAMP_RE.test(w)?w:null}}function isLoomUrl(e){return parseLoomUrl(e)!==null}function isVimeoHost(e){let t=e.toLowerCase();return t===`vimeo.com`||t===`www.vimeo.com`||t===`player.vimeo.com`}function isVimeoUrl(e){if(typeof e!=`string`||e.length===0)return!1;let t;try{t=new URL(e)}catch{return!1}return t.protocol!==`http:`&&t.protocol!==`https:`?!1:isVimeoHost(t.hostname)}const YOUTUBE_VIDEO_ID_RE=/^[A-Za-z0-9_-]{11}$/;function isYouTubeHost(e){let t=e.toLowerCase();return t===`youtube.com`||t===`www.youtube.com`||t===`m.youtube.com`||t===`music.youtube.com`||t===`youtu.be`||t===`youtube-nocookie.com`||t===`www.youtube-nocookie.com`}function parseTimestampToSeconds(e){if(e.length===0)return null;if(/^[0-9]+$/.test(e)){let t=Number.parseInt(e,10);return t>0?t:null}let t=e.match(/^(?:([0-9]+)h)?(?:([0-9]+)m)?(?:([0-9]+)s?)?$/);if(!t)return null;let S=t[1]?Number.parseInt(t[1],10):0,w=t[2]?Number.parseInt(t[2],10):0,E=t[3]?Number.parseInt(t[3],10):0,D=S*3600+w*60+E;return D>0?D:null}function extractVideoId(e){if(e.hostname.toLowerCase()===`youtu.be`){let t=e.pathname.replace(/^\//,``).split(`/`)[0]??``;return YOUTUBE_VIDEO_ID_RE.test(t)?t:null}if(e.pathname===`/watch`){let t=e.searchParams.get(`v`)??``;return YOUTUBE_VIDEO_ID_RE.test(t)?t:null}let t=e.pathname.match(/^\/(?:embed|shorts|v)\/([A-Za-z0-9_-]{11})\/?$/);return t?t[1]??null:null}function parseYouTubeUrl(e){if(typeof e!=`string`||e.length===0)return null;let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`||!isYouTubeHost(t.hostname))return null;let S=extractVideoId(t);if(!S)return null;let w=t.searchParams.get(`t`)??t.searchParams.get(`start`)??``;return{id:S,startSeconds:w.length>0?parseTimestampToSeconds(w):null,noCookie:t.hostname.toLowerCase().endsWith(`youtube-nocookie.com`)}}const calloutProps=[{name:`type`,type:`enum`,enumValues:[`note`,`tip`,`important`,`warning`,`caution`,`abstract`,`info`,`todo`,`success`,`question`,`failure`,`danger`,`bug`,`example`,`quote`],defaultValue:`note`,required:!1,description:`Callout variant`},{name:`title`,type:`string`,required:!1,description:`Optional heading shown above the body`},{name:`icon`,type:`string`,required:!1,advanced:!0,description:"Custom lucide icon override (e.g. `lucide:Lightbulb`)"},{name:`color`,type:`string`,required:!1,advanced:!0,description:"Optional accent color override (hex — e.g. `#F05032`)"},{name:`collapsible`,type:`boolean`,required:!1,defaultValue:!1,advanced:!0,description:"Render as a foldable `<details>` (Obsidian `[!TYPE]+/-`)"},{name:`defaultOpen`,type:`boolean`,required:!1,defaultValue:!0,advanced:!0,description:`When collapsible, start in the open state`},{name:`children`,type:`reactnode`,required:!0,description:`Callout content`}],htmlImgProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`Image source URL`,accept:ALLOWED_IMAGE_MIME_TYPES,autoFocus:!0},{name:`alt`,type:`string`,required:!0,description:`Alt text`},{name:`width`,type:`number`,required:!1,advanced:!0,description:`Image width`},{name:`height`,type:`number`,required:!1,advanced:!0,description:`Image height`},{name:`srcset`,type:`string`,required:!1,advanced:!0,description:`Responsive image candidate set (e.g. "x.png 1x, y.png 2x")`},{name:`sizes`,type:`string`,required:!1,advanced:!0,description:`Responsive image sizes hint paired with srcset`},{name:`loading`,type:`enum`,enumValues:[`eager`,`lazy`],defaultValue:`lazy`,required:!1,advanced:!0,omitOnDefault:!0,description:`Native img loading strategy (defaults to lazy)`},{name:`title`,type:`string`,required:!1,advanced:!0,description:`Native HTML title attribute (tooltip)`},{name:`decoding`,type:`enum`,enumValues:[`sync`,`async`,`auto`],defaultValue:`auto`,required:!1,advanced:!0,omitOnDefault:!0,description:`Hint for how the browser should decode the image`},{name:`fetchpriority`,type:`enum`,enumValues:[`high`,`low`,`auto`],defaultValue:`auto`,required:!1,advanced:!0,omitOnDefault:!0,description:`Resource fetch priority hint`},{name:`crossorigin`,type:`enum`,enumValues:[`anonymous`,`use-credentials`],required:!1,advanced:!0,description:`CORS mode for the image fetch`},{name:`referrerpolicy`,type:`string`,required:!1,advanced:!0,description:`Referrer policy for the image fetch (HTML referrerpolicy values)`},{name:`align`,type:`enum`,enumValues:[`center`,`left`,`right`],defaultValue:`center`,required:!1,omitOnDefault:!0,description:`Alignment within the column`}],embedProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`Embedded page URL (must start with http:// or https://)`,autoFocus:!0},{name:`title`,type:`string`,required:!1,description:`Iframe title (accessible label for screen readers)`},{name:`width`,type:`string`,required:!1,advanced:!0,description:`Embed width as a CSS length (e.g. "100%", "640px")`},{name:`height`,type:`string`,required:!1,advanced:!0,description:`Embed height as a CSS length (e.g. "26rem", "480px")`},{name:`align`,type:`enum`,enumValues:[`center`,`left`,`right`],defaultValue:`center`,required:!1,omitOnDefault:!0,description:`Alignment within the column`}],htmlVideoProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`Video source URL`,accept:ALLOWED_VIDEO_MIME_TYPES,autoFocus:!0},{name:`controls`,type:`boolean`,required:!1,defaultValue:!0,advanced:!0,omitOnDefault:!0,description:`Show native HTML5 video controls (defaults to true)`,hideWhen:e=>typeof e.src==`string`&&(isVimeoUrl(e.src)||isLoomUrl(e.src))},{name:`autoplay`,type:`boolean`,required:!1,advanced:!0,description:`Begin playback as soon as possible (usually requires muted)`},{name:`poster`,type:`string`,required:!1,advanced:!0,description:`Poster image URL shown before playback`,accept:ALLOWED_IMAGE_MIME_TYPES,hideWhen:e=>typeof e.src==`string`&&(isVimeoUrl(e.src)||isLoomUrl(e.src))},{name:`width`,type:`number`,required:!1,advanced:!0,description:`Video width`},{name:`height`,type:`number`,required:!1,advanced:!0,description:`Video height`},{name:`title`,type:`string`,required:!1,advanced:!0,description:`Native HTML title attribute (tooltip)`},{name:`muted`,type:`boolean`,required:!1,advanced:!0,description:`Mute audio on load`},{name:`loop`,type:`boolean`,required:!1,advanced:!0,description:`Restart from the beginning when playback ends`,hideWhen:e=>typeof e.src==`string`&&isLoomUrl(e.src)},{name:`playsinline`,type:`boolean`,required:!1,advanced:!0,description:`Play inline on iOS rather than entering fullscreen`,hideWhen:e=>typeof e.src==`string`&&(isVimeoUrl(e.src)||isLoomUrl(e.src))},{name:`preload`,type:`enum`,enumValues:[`none`,`metadata`,`auto`],required:!1,advanced:!0,description:`Hint for how much of the video to preload`,hideWhen:e=>typeof e.src==`string`&&(parseYouTubeUrl(e.src)!==null||isVimeoUrl(e.src)||isLoomUrl(e.src))},{name:`align`,type:`enum`,enumValues:[`center`,`left`,`right`],defaultValue:`center`,required:!1,omitOnDefault:!0,description:`Alignment within the column`}],htmlAudioProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`Audio source URL`,accept:ALLOWED_AUDIO_MIME_TYPES,autoFocus:!0},{name:`controls`,type:`boolean`,required:!1,defaultValue:!0,advanced:!0,omitOnDefault:!0,description:`Show native HTML5 audio controls (defaults to true)`},{name:`autoplay`,type:`boolean`,required:!1,advanced:!0,description:`Begin playback as soon as possible (usually requires muted)`},{name:`title`,type:`string`,required:!1,advanced:!0,description:`Native HTML title attribute (tooltip)`},{name:`muted`,type:`boolean`,required:!1,advanced:!0,description:`Mute audio on load`},{name:`loop`,type:`boolean`,required:!1,advanced:!0,description:`Restart from the beginning when playback ends`},{name:`preload`,type:`enum`,enumValues:[`none`,`metadata`,`auto`],required:!1,advanced:!0,description:`Hint for how much of the audio to preload`}],accordionProps=[{name:`title`,type:`string`,required:!0,description:`Accordion heading shown inside the <summary>`},{name:`defaultOpen`,type:`boolean`,required:!1,defaultValue:!1,description:`When true, the accordion renders expanded on initial load`},{name:`icon`,type:`string`,required:!1,advanced:!0,description:"Custom lucide icon override (e.g. `lucide:Rocket`)"},{name:`description`,type:`string`,required:!1,advanced:!0,description:`Optional subtitle rendered below the title inside <summary>`},{name:`id`,type:`string`,required:!1,advanced:!0,description:"HTML id attribute for deep-linking (e.g. `#advanced-options`)"},{name:`name`,type:`string`,required:!1,advanced:!0,description:`HTML5 <details name=> group — siblings with the same name are mutually exclusive`}],gfmCalloutProps=[calloutProps[0],calloutProps[1],calloutProps[4],calloutProps[5],calloutProps[6]],commonMarkImageProps=[htmlImgProps[0],htmlImgProps[1],htmlImgProps[7]],htmlDetailsAccordionProps=[accordionProps[0],accordionProps[1],accordionProps[4],accordionProps[5]],wikiEmbedImageProps=[{name:`alias`,type:`string`,required:!1,defaultValue:``,description:"Alt text (Obsidian alias syntax: `![[file.png|alt text]]`)"}],wikiEmbedVideoProps=[{name:`alias`,type:`string`,required:!1,defaultValue:``,description:"Title text (Obsidian alias syntax: `![[clip.mp4|title]]`)"}],wikiEmbedAudioProps=[{name:`alias`,type:`string`,required:!1,defaultValue:``,description:"Title text (Obsidian alias syntax: `![[song.mp3|title]]`)"}],tabsProps=[{name:`id`,type:`string`,required:!1,advanced:!0,description:"HTML id attribute for deep-linking (e.g. `#install-tabs`)"}],tabProps=[{name:`label`,type:`string`,required:!0,autoFocus:!0,defaultValue:`Tab`,description:`Tab strip label — shown in the clickable pill at the top`},{name:`id`,type:`string`,required:!1,advanced:!0,description:"HTML id attribute for deep-linking (e.g. `#tab-npm`)"}],mathProps=[{name:`formula`,type:`string`,required:!0,autoFocus:!0,language:`latex`,description:`LaTeX math source (rendered with KaTeX in the browser)`},{name:`id`,type:`string`,required:!1,advanced:!0,description:"HTML id attribute for deep-linking (e.g. `#eq-pythagoras`)"},{name:`language`,type:`string`,required:!1,advanced:!0,description:"Forward-compat hint for the math source language (default `latex`). Reserved for future MathJax / Typst / AsciiMath substrates."}],dollarMathProps=[mathProps[0]],mathFenceProps=[mathProps[0]],mermaidProps=[{name:`chart`,type:`string`,required:!0,autoFocus:!0,language:`mermaid`,description:`Mermaid chart source (graph / flowchart / sequenceDiagram / class / state / etc.)`}],wikiEmbedFileProps=[{name:`alias`,type:`string`,required:!1,defaultValue:``,description:"Display name override (Obsidian alias syntax: `![[file.zip|label]]`)"}],fileProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`File URL`,accept:[`*/*`],autoFocus:!0}],pdfProps=[{name:`src`,type:`string`,required:!0,defaultValue:``,description:`PDF source URL`,accept:ALLOWED_PDF_MIME_TYPES,autoFocus:!0},{name:`title`,type:`string`,required:!1,advanced:!0,description:`Accessible label for the embedded PDF viewer`},{name:`anchor`,type:`string`,required:!1,advanced:!0,description:"PDF viewer parameters as a single URL-fragment string (e.g. `page=3&height=600`)"}],mirrorProps=[{name:`src`,type:`string`,required:!0,description:"Path of the source doc, extension-less (e.g. `api-spec`).",autoFocus:!0},{name:`anchor`,type:`string`,required:!0,description:"Id of the `<MirrorSource>` block within the source doc."}],mirrorSourceProps=[{name:`id`,type:`string`,required:!0,description:"Stable id agents and authors use to reference this block from `<Mirror>` elsewhere.",autoFocus:!0},{name:`children`,type:`reactnode`,required:!0,description:`Block content this MirrorSource owns — paragraphs, callouts, code, nested JSX, anything.`}];function escapeHtmlAttr(e){return e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function escapeHtmlText(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`)}function serializeWikiEmbed(e){let t=e.attrs.props,S=t?.target??``,w=typeof t?.alias==`string`&&t.alias.length>0?t.alias:null,E=typeof t?.anchor==`string`&&t.anchor.length>0?t.anchor:null,D=w??(E?`${S}#${E}`:S);return{type:`wikiLinkEmbed`,value:D,data:{target:S,anchor:E,alias:w},children:[{type:`text`,value:D}]}}const builtInComponents=[{name:`Callout`,surface:`canonical`,hasChildren:!0,props:calloutProps,icon:`MessageSquareWarning`,category:`content`,displayName:`Callout`,description:`Alert / admonition with 15 type variants — 5 GFM (note, tip, important, warning, caution) plus 10 Obsidian-parity (abstract, info, todo, success, question, failure, danger, bug, example, quote)`,searchTerms:[`note`,`tip`,`important`,`warning`,`caution`,`abstract`,`info`,`todo`,`success`,`question`,`failure`,`danger`,`bug`,`example`,`quote`,`alert`,`admonition`,`callout`],serialize:(e,t)=>emitMdxJsx(`Callout`,e,t,calloutProps)},{name:`img`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:htmlImgProps,icon:`Image`,category:`media`,displayName:`Image`,description:`Image with click-to-zoom and HTML-native attributes`,searchTerms:[`image`,`zoom`,`picture`,`photo`],placeholder:{label:`Add an image`},serialize:(e,t)=>emitMdxJsx(`img`,e,t,htmlImgProps)},{name:`video`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:htmlVideoProps,icon:`SquarePlay`,category:`media`,displayName:`Video`,description:`HTML5 video player with native controls`,searchTerms:[`video`,`media`,`player`,`mp4`,`webm`,`movie`],placeholder:{label:`Add a video`},serialize:(e,t)=>emitMdxJsx(`video`,e,t,htmlVideoProps)},{name:`audio`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:htmlAudioProps,icon:`Volume2`,category:`media`,displayName:`Audio`,description:`HTML5 audio player with native controls`,searchTerms:[`audio`,`sound`,`music`,`mp3`,`podcast`,`player`],placeholder:{label:`Add audio`},serialize:(e,t)=>emitMdxJsx(`audio`,e,t,htmlAudioProps)},{name:`Pdf`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:pdfProps,icon:`FileText`,category:`media`,displayName:`PDF`,description:"Embedded PDF viewer (`#page=N` to open at page N, `#height=N` for viewer height)",searchTerms:[`pdf`,`document`,`embed`,`pdfjs`],placeholder:{label:`Add a PDF`},serialize:(e,t)=>emitMdxJsx(`Pdf`,e,t,pdfProps)},{name:`File`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:fileProps,icon:`Paperclip`,category:`media`,displayName:`File`,description:`Downloadable file attachment — inline row with name + size + download link`,searchTerms:[`file`,`attachment`,`download`,`document`,`zip`,`docx`,`doc`],placeholder:{label:`Add a file`},serialize:(e,t)=>emitMdxJsx(`File`,e,t,fileProps)},{name:`Embed`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:embedProps,icon:`AppWindow`,category:`media`,displayName:`Embed`,description:`Inline web embed (iframe) — drop a URL, get a resizable preview pane`,searchTerms:[`embed`,`iframe`,`website`,`page`,`inline`,`frame`,`preview`],placeholder:{label:`Embed a URL`},serialize:(e,t)=>emitMdxJsx(`Embed`,e,t,embedProps)},{name:`Accordion`,surface:`canonical`,hasChildren:!0,props:accordionProps,icon:`ChevronRight`,category:`content`,displayName:`Accordion`,description:"Standalone expand/collapse via native HTML5 <details>/<summary>. Group siblings with the `name` prop for exclusive-accordion UX.",searchTerms:[`toggle`,`accordion`,`expandable`,`details`,`disclosure`,`collapse`,`fold`],exampleBody:`Body content revealed when the accordion is expanded.`,serialize:(e,t)=>emitMdxJsx(`Accordion`,e,t,accordionProps)},{name:`Tabs`,surface:`canonical`,hasChildren:!0,emptyChildName:`Tab`,props:tabsProps,icon:`LayoutPanelTop`,category:`content`,displayName:`Tabs`,description:"Horizontal tab strip + active panel below. Each `<Tab>` child is one panel; clickable pills at the top switch the active one. Active selection is ephemeral (resets on reload).",searchTerms:[`tabs`,`tabbed`,`panels`,`tabgroup`,`switcher`],exampleBody:`<Tab label="One">Body of the first tab panel.</Tab>
|
|
391
391
|
<Tab label="Two">Body of the second tab panel.</Tab>`,serialize:(e,t)=>emitMdxJsx(`Tabs`,e,t,tabsProps)},{name:`Tab`,surface:`canonical`,hasChildren:!0,props:tabProps,icon:`PanelTop`,category:`content`,displayName:`Tab`,description:"A single tab panel inside a `<Tabs>` container — carries the strip label and the block-content body.",searchTerms:[`tab`,`panel`],exampleBody:"Panel content — must be nested inside a `<Tabs>` parent.",serialize:(e,t)=>emitMdxJsx(`Tab`,e,t,tabProps)},{name:`Math`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:mathProps,icon:`Sigma`,category:`content`,displayName:`Math`,description:`Block math equation rendered with KaTeX from a LaTeX source string`,searchTerms:[`math`,`latex`,`equation`,`formula`,`katex`,`tex`],serialize:(e,t)=>emitMdxJsx(`Math`,e,t,mathProps)},{name:`MermaidFence`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:mermaidProps,icon:`Workflow`,category:`content`,displayName:`Mermaid`,description:"Diagram rendered from Mermaid source (flowchart, sequence, class, state, ER, gantt, pie). Authored exclusively as ` ```mermaid ` fenced code.",searchTerms:[`mermaid`,`diagram`,`flowchart`,`graph`,`sequence`,`sequencediagram`,`class`,`state`,`er`,`erdiagram`,`gantt`,`pie`,`chart`],serialize:e=>({type:`code`,lang:`mermaid`,meta:null,value:e.attrs.props?.chart??``})},{name:`Mirror`,surface:`canonical`,hasChildren:!1,isSelfClosing:!0,props:mirrorProps,icon:`CopyPlus`,category:`content`,displayName:`Mirror`,description:"Render a read-only copy of a `<MirrorSource>` block from another doc. Use to keep the same content in sync across multiple docs without copy-paste — edits land at the source, every Mirror reflects the change.",searchTerms:[`mirror`,`sync`,`synced`,`transclude`,`embed`,`reference`,`shared block`],serialize:(e,t)=>emitMdxJsx(`Mirror`,e,t,mirrorProps)},{name:`MirrorSource`,surface:`canonical`,hasChildren:!0,props:mirrorSourceProps,icon:`GitBranch`,category:`content`,displayName:`Mirror Source`,description:'Mark a block as the source of truth for content that appears in multiple docs. Wrap any block content; `<Mirror src="…" anchor="<id>">` references render this verbatim read-only at every call-site. Edit here, propagate everywhere.',searchTerms:[`mirror source`,`sync source`,`source block`,`master block`,`shared`],exampleBody:"Authoritative content lives inside this block — edits here propagate to every `<Mirror>` that references this id.",serialize:(e,t)=>emitMdxJsx(`MirrorSource`,e,t,mirrorSourceProps)},{name:`GFMCallout`,surface:`compat`,hasChildren:!0,props:gfmCalloutProps,icon:`MessageSquareWarning`,category:`content`,displayName:`GFM Callout`,description:"GFM blockquote alert (`> [!NOTE]`) — read-only compat. Preserves `> [!NOTE]` syntax on round-trip; insert a fresh Callout block for the full prop surface.",rendersAs:`Callout`,translateProps:e=>e,serialize:(e,t)=>{let S=e.attrs.props,w=new Set([`note`,`tip`,`important`,`warning`,`caution`,`abstract`,`info`,`todo`,`success`,`question`,`failure`,`danger`,`bug`,`example`,`quote`]),E=S?.type??`note`;return{type:`blockquote`,children:[{type:`html`,value:`[!${(w.has(E.toLowerCase())?E:`note`).toUpperCase()}]${S?.collapsible?S.defaultOpen===!1?`-`:`+`:``}${S?.title?` ${S.title}`:``}`},...t.all(e).filter(e=>{if(e.type!==`paragraph`)return!0;let t=e;return Array.isArray(t.children)&&t.children.length>0})]}}},{name:`CommonMarkImage`,surface:`compat`,hasChildren:!1,isSelfClosing:!0,props:commonMarkImageProps,icon:`Image`,category:`media`,displayName:`CommonMark Image`,description:'CommonMark image (``) — read-only compat. Preserves `` syntax on round-trip; insert a fresh Image block for the full HTML-native attribute surface (srcset, sizes, decoding, etc.).',rendersAs:`img`,translateProps:e=>e,serialize:e=>{let t=e.attrs.props;return{type:`paragraph`,children:[{type:`image`,url:t?.sourceUrl??t?.src??``,alt:t?.alt??``,title:t?.title??null}]}}},{name:`WikiEmbedImage`,surface:`compat`,hasChildren:!1,isSelfClosing:!0,props:wikiEmbedImageProps,icon:`ZoomIn`,category:`media`,displayName:`Wiki Embed Image`,description:"Obsidian-style `![[file.png]]` wiki-embed — read-only compat. Edit the alt-text via the alias slot; the embed target / anchor stay on the prop bag and round-trip byte-identical.",rendersAs:`img`,translateProps:e=>{let t=typeof e.alias==`string`&&e.alias.length>0?e.alias:null,S=typeof e.target==`string`?e.target:``;return{src:e.src,alt:t??S}},serialize:serializeWikiEmbed},{name:`WikiEmbedVideo`,surface:`compat`,hasChildren:!1,isSelfClosing:!0,props:wikiEmbedVideoProps,icon:`Film`,category:`media`,displayName:`Wiki Embed Video`,description:"Obsidian-style `![[clip.mp4]]` wiki-embed — read-only compat. Edit the title via the alias slot; the embed target / anchor stay on the prop bag and round-trip byte-identical.",rendersAs:`video`,translateProps:e=>{let t=typeof e.alias==`string`&&e.alias.length>0?e.alias:null,S=typeof e.target==`string`?e.target:``;return{src:e.src,title:t??S}},serialize:serializeWikiEmbed},{name:`WikiEmbedAudio`,surface:`compat`,hasChildren:!1,isSelfClosing:!0,props:wikiEmbedAudioProps,icon:`Volume2`,category:`media`,displayName:`Wiki Embed Audio`,description:"Obsidian-style `![[song.mp3]]` wiki-embed — read-only compat. Edit the title via the alias slot; the embed target / anchor stay on the prop bag and round-trip byte-identical.",rendersAs:`audio`,translateProps:e=>{let t=typeof e.alias==`string`&&e.alias.length>0?e.alias:null,S=typeof e.target==`string`?e.target:``;return{src:e.src,title:t??S}},serialize:serializeWikiEmbed},{name:`WikiEmbedFile`,surface:`compat`,hasChildren:!1,isSelfClosing:!0,props:wikiEmbedFileProps,icon:`Paperclip`,category:`media`,displayName:`Wiki Embed File`,description:"Obsidian-style `![[file.zip]]` wiki-embed — read-only compat for arbitrary downloadable attachments. Renders through the `File` canonical (inline row with file-up icon + bold name + optional dim size). Edit the display name via the alias slot.",rendersAs:`File`,translateProps:e=>{let t=typeof e.alias==`string`&&e.alias.length>0?e.alias:null,S=typeof e.size==`string`&&e.size.length>0?e.size:null;return{src:e.src,name:t??void 0,size:S??void 0}},serialize:serializeWikiEmbed},{name:`HtmlDetailsAccordion`,surface:`compat`,hasChildren:!0,props:htmlDetailsAccordionProps,icon:`ChevronRight`,category:`content`,displayName:`HTML5 Details`,description:"HTML5 `<details><summary>` collapsible — read-only compat. Preserves `<details>` syntax on round-trip; insert a fresh Accordion block for icon / description / group-name props.",rendersAs:`Accordion`,translateProps:e=>e,serialize:(e,t)=>{let S=e.attrs.props,w=S?.defaultOpen?` open`:``,E=S?.name?` name="${escapeHtmlAttr(S.name)}"`:``,D=S?.id?` id="${escapeHtmlAttr(S.id)}"`:``,O=S?.title?.trim(),k=O?`<summary>${escapeHtmlText(O)}</summary>`:``;return{type:`mdxJsxFlowElement`,name:`HtmlDetailsAccordion`,attributes:[],children:t.all(e),data:{htmlBoundary:{opener:`<details${w}${E}${D}>\n${k}`,closer:`</details>`}}}}},{name:`DollarMath`,surface:`compat`,hasChildren:!1,isSelfClosing:!0,props:dollarMathProps,icon:`Sigma`,category:`content`,displayName:`Dollar Math`,description:"Block math via `$$…$$` syntax — read-only compat. Preserves `$$…$$` form on round-trip; insert a fresh Math block for the full prop surface (id, language).",rendersAs:`Math`,translateProps:e=>e,serialize:e=>({type:`math`,value:e.attrs.props?.formula??``})},{name:`MathFence`,surface:`compat`,hasChildren:!1,isSelfClosing:!0,props:mathFenceProps,icon:`Sigma`,category:`content`,displayName:`Math Fence`,description:"Block math via ` ```math ` fenced code syntax — read-only compat. Preserves the fence form on round-trip; insert a fresh Math block for the full prop surface (id, language).",rendersAs:`Math`,translateProps:e=>e,serialize:e=>({type:`code`,lang:`math`,meta:null,value:e.attrs.props?.formula??``})}],wildcardMeta={name:`*`,surface:`canonical`,hasChildren:!0,props:[],description:`Unregistered component — children editable as markdown`,serialize:(e,t)=>emitMdxJsx(e.attrs.componentName||`*`,e,t)};function createRegistry(){let e=new Map;e.set(`*`,wildcardMeta);for(let t of builtInComponents)e.set(t.name,t);return{get(t){return e.get(t)},getOrWildcard(t){return e.get(t)??e.get(`*`)},set(t,S){e.set(t,S)},has(t){return e.has(t)},entries(){return e.entries()}}}function ypsCounters(){let e=globalThis;return e.__okYpsCounters||={block:0,inline:0},e.__okYpsCounters}const metrics={parseFallback:{blockLevel:0,wholeDoc:0},jsxRenderFailure:{},jsxAutoConvertFailed:{},jsxAutoConvertSucceeded:{},jsxPropDropped:{},jsxMoveFailed:{},jsxStuckCopyFailed:{},jsxStuckDeleteFailed:{},jsxPopoverCloseRestoreFailed:{},jsxKeyboardDeleteFailed:{},blockGripClickSelectFailed:{},jsxArrowNodeSelectFailed:{}};function incrementBlockFallback(){metrics.parseFallback.blockLevel++}function incrementWholeDocFallback(){metrics.parseFallback.wholeDoc++}function getParseHealth(){let e=ypsCounters();return{parseFallback:{...metrics.parseFallback},ypsMismatch:{block:e.block,inline:e.inline},jsxRenderFailure:{...metrics.jsxRenderFailure},jsxAutoConvertFailed:{...metrics.jsxAutoConvertFailed},jsxAutoConvertSucceeded:{...metrics.jsxAutoConvertSucceeded},jsxPropDropped:{...metrics.jsxPropDropped},jsxMoveFailed:{...metrics.jsxMoveFailed},jsxStuckCopyFailed:{...metrics.jsxStuckCopyFailed},jsxStuckDeleteFailed:{...metrics.jsxStuckDeleteFailed},jsxPopoverCloseRestoreFailed:{...metrics.jsxPopoverCloseRestoreFailed},jsxKeyboardDeleteFailed:{...metrics.jsxKeyboardDeleteFailed},blockGripClickSelectFailed:{...metrics.blockGripClickSelectFailed},jsxArrowNodeSelectFailed:{...metrics.jsxArrowNodeSelectFailed}}}const FENCE_RE=/^(`{3,}|~{3,})/gm;function findFencedRegions(e){let t=[],S=null;for(let w of e.matchAll(FENCE_RE)){let e=w[1],E=w.index;S?e[0]===S.marker[0]&&e.length>=S.marker.length&&(t.push([S.offset,E+w[0].length]),S=null):S={marker:e,offset:E}}return S&&t.push([S.offset,e.length]),t}function isInsideFence(e,t){return t.some(([t,S])=>e>=t&&e<S)}const REF_DEF_RE=/^[ \t]{0,3}\[([^\]]+)\]:\s*(\S+)(\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\s*$/gm;function hoistRefDefs(e){let t=findFencedRegions(e),S=[];for(let w of e.matchAll(REF_DEF_RE))isInsideFence(w.index,t)||S.push(w[0].trimEnd());return S.length>0?`${S.join(`
|
|
392
392
|
`)}\n\n`:``}const MAX_PARSE_WALLCLOCK_MS=500,MAX_TOTAL_PARSE_CALLS=1e3;function parseWithFallback(e,t){let S={startMs:typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now(),calls:0};return parseRecursive(e,t.parse,0,S)}function budgetExhausted(e){return e.calls>=MAX_TOTAL_PARSE_CALLS?!0:(typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now())-e.startMs>=MAX_PARSE_WALLCLOCK_MS}const MAX_ERROR_MESSAGE_LEN=500;function errorPayload(e){return e instanceof Error?{name:e.name,message:e.message.slice(0,MAX_ERROR_MESSAGE_LEN),stack:e.stack?.split(`
|
|
393
393
|
`).slice(0,4).join(`
|
|
@@ -3508,4 +3508,4 @@ In headless mode, write the recap into the research article's "Further reading"
|
|
|
3508
3508
|
`),S=[],w=!1,E=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){w?RegExp(`^\\s{0,3}${E[0]==="`"?"`":`~`}{${E.length},}\\s*$`).test(e)&&(w=!1,E=``):(w=!0,E=t[1]);continue}if(w)continue;let D=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(D);if(e===null)break;let t=e[2];t&&S.push(t)}}return S}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:S,body:w}=stripFrontmatter(t),E=extractFrontmatterTags(S?unwrapFrontmatterFences(S):``),D=extractInlineTagsFromBody(w),O=new Set([...E,...D]),k=new Set;for(let e of O)for(let t of expandTagToHierarchy(e))k.add(t);this.applyDocSnapshot(e,O,k)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let S of t){let t=this.state.byTag.get(S);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(S))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,S){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,S)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let S=[];for(let w of t){let t=this.state.byDocLiteral.get(w);if(!t)continue;let E=tagsMatchingPrefix(t,e);S.push({docName:w,matchingTags:[...E].sort((e,t)=>e.localeCompare(t))})}return S.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),S=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&S.add(e.slice(0,t));let w=t;for(;w>0;)S.add(e.slice(0,w)),w=e.indexOf(`/`,w+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!S.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=this.listDocsWithPaths();for(let{docName:t,filePath:S}of e)try{let e=readFileSync(S,`utf-8`);this.updateDocumentFromMarkdown(t,e)}catch(e){console.warn(`[tag-index] Failed to read ${t} during init:`,e)}}applyDocSnapshot(e,t,S){let w=this.state.byDoc.get(e)??new Set;for(let t of w){if(S.has(t))continue;let w=this.state.byTag.get(t);w&&(w.delete(e),w.size===0&&this.state.byTag.delete(t))}for(let t of S){let S=this.state.byTag.get(t);S||(S=new Set,this.state.byTag.set(t,S)),S.add(e)}S.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,S),this.state.byDocLiteral.set(e,t))}listDocsWithPaths(){let e=[];this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}walkContentDir(e,t){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let w of S){let S=join(e,w.name);if(w.isDirectory()){let e=relative(this.contentDir,S);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(S,t);continue}if(!w.isFile()||!isSupportedDocFile(w.name))continue;let E=relative(this.contentDir,S);this.contentFilter?.isExcluded(E)||t.push({docName:stripDocExtension(E),filePath:S})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:S=t,quiet:w=!0,debounce:E=2e3,maxDebounce:D=1e4,gitEnabled:O=!0,commitDebounceMs:k=3e4,wipRef:j=`refs/wip/main`,configHomedirOverride:F,enableTestRoutes:L=!1,shadowRepo:B,contentRoot:H,destroyTimeoutMs:q=1e4,localOpCliArgs:J,skipStateManifestCheck:Y=!1}=e,ee=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||ee.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}initTelemetry();let ne=randomUUID(),ae=getLocalDir(S);if(acquireServerLock(ae,{port:e.port??0,worktreeRoot:S,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!Y)try{assertCompatibleStateManifest({lockDir:ae,shadowRepoDir:resolveShadowDir(S)})}catch(e){throw releaseServerLock(ae),e}let oe=createBasenameIndex(),se=(e,t)=>oe.resolveEmbed(e,t),ce=(e,S)=>{let w=oe.resolveEmbed(e,S);if(!w&&e.includes(`/`)&&(w=e.replace(/^\.?\//,``)),!w)return null;let E=resolve(t,w),D=resolve(t);if(E!==D&&!E.startsWith(`${D}/`))return null;try{let e=statSync(E);return e.isFile()?e.size:null}catch{return null}},ue,de,fe,me,ge,_e,ve,ye=null,Ce=null,we=null,Te=null,De=null,je=new Set,Me=!1,Pe,Ie,Re,ze=new Promise((e,t)=>{Ie=e,Re=t});function Be(e){ye?.signal(e)}let Ve=2e3,Ue=null;function We(){Ue!==null&&clearTimeout(Ue),Ue=setTimeout(()=>{Ue=null,de.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let Ge=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),Ke=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||Ge.setRenamed(e,t)},Xe=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(Ge.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Ge.setDeleted(e)}},$e=e=>{isSystemDoc(e)||isConfigDoc(e)||Ge.delete(e)};try{ue=createContentFilter({projectDir:S,contentDir:t,onAfterRebuild:()=>{de.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)});try{fe.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}try{let{prunedFiles:e,prunedFolders:t}=reconcileFileIndexAfterFilterRebuild(zt),S=e+t;S>0?getLogger(`server-factory`).info({pruned:S,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):getLogger(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)}}}),de=new BacklinkIndex({projectDir:S,contentDir:t,contentFilter:ue}),fe=new TagIndex({contentDir:t,contentFilter:ue});try{fe.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}me={current:B},ge=createPersistenceExtension({contentDir:t,projectDir:S,gitEnabled:O,commitDebounceMs:k,wipRef:j,shadowRef:me,contentRoot:H,backlinkIndex:de,configHomedirOverride:F,getCurrentBranch:()=>Bt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce,getPrincipal:()=>De,onAgentCommit:()=>ye?.signal(`session-activity`),onDiskFlush:(e,t,S,w)=>{ye?.emitDiskAck(e,t),!(isSystemDoc(e)||isConfigDoc(e))&&assetReferencesChanged(w,S)&&(Te?.(),Be(`files`))},onConfigRejected:(e,t)=>ye?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),_e=new Hocuspocus({quiet:w,debounce:E,maxDebounce:D,extensions:[ge.extension]});let q=_e.shouldUnloadDocument.bind(_e);_e.shouldUnloadDocument=e=>{if(je.has(e)||Me&&q(e))return!0;let t=e.name;return isSystemDoc(t)||isConfigDoc(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:q(e)},Pe=async e=>{je.add(e);try{await _e.unloadDocument(e)}finally{je.delete(e)}},ye=new CC1Broadcaster(_e),Ce=new AgentFocusBroadcaster(_e),we=new AgentPresenceBroadcaster(_e),ve=new AgentSessionManager(_e);let Y=createLiveDerivedIndexExtension({backlinkIndex:de,tagIndex:fe,signalChannel:Be});_e.configuration.extensions.push(Y),_e.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,S=parseHocuspocusAuthToken(t),w=S?.expectedServerInstanceId;if(typeof w==`string`&&w.length>0&&w!==ne)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${w}, this server is ${ne}`);let E=S?.expectedBranch,D=getActiveBranch();if(typeof E==`string`&&E.length>0&&E!==D)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${E}, server is on ${D}`);if(!S)return;let O=e.context;typeof S.principalId==`string`&&(De&&S.principalId===De.id?O.principalId=De.id:De?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:S.principalId,loaded:De.id})):O.principalId=S.principalId),typeof S.tabSessionId==`string`&&(O.tabSessionId=S.tabSessionId),O.kind=`human`}}),_e.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName))return;let t=e.request,S=t.socket?.remoteAddress;if(S!==void 0&&!isLoopbackAddress(S))throw Error(`config-doc admission requires loopback peer (peer=${S}, doc=${e.documentName})`);let w=e.requestHeaders,E=(w&&typeof w.get==`function`?w.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(E))throw Error(`config-doc admission requires loopback Host header (host=${E??`<absent>`}, doc=${e.documentName})`)}});let ee=resolve(t);function te(e){if(!isSafeDocName(e))return null;let t=resolve(ee,`${e}${getDocExtension(e)}`);return!t.startsWith(`${ee}/`)&&t!==ee?null:t}_e.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:Ge,resolveFilePath:te,fileExists:existsSync})}}),_e.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let ae=createApiExtension({hocuspocus:_e,sessionManager:ve,contentDir:t,contentFilter:ue,serverInstanceId:ne,getFileIndex:()=>zt?zt.getFileIndex():new Map,getFolderIndex:()=>zt?zt.getFolderIndex():new Map,getAliasMap:()=>zt?zt.getAliasMap():new Map,rescanFiles:()=>zt?.rescanFromDisk(),enableTestRoutes:L,shadowRef:me,flushGitCommit:()=>ge.flushPendingGitCommit(),flushContributors:()=>ge.flushContributors(),getCurrentBranch:()=>Bt?.getLastKnownBranch()??null,getDiskAckSVs:()=>ye?.getLatestDiskAckSVsAsBase64()??{},contentRoot:H,backlinkIndex:de,tagIndex:fe,signalChannel:Be,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Vt,localOpCliArgs:J,projectDir:S,resolveEmbed:se,getPrincipal:()=>De,forceUnloadDocument:Pe,ready:ze,recentlyRemovedDocs:Ge,serializeDoc:st,onReferencedAssetsCacheInvalidator:e=>{Te=e}});_e.configuration.extensions.push(ae),_e.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:me,contentRoot:H,getCurrentBranch:()=>Bt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce})),_e.configuration.extensions.push(createSyncHandshakeSpanExtension()),_e.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>Vt,projectDir:S,contentDir:t}))}catch(e){throw releaseServerLock(ae),e}let nt=null,rt=new Map,it=[];function at(e,t){let S=resolve(e,`rescue`),w=resolve(S,`${t}${getDocExtension(t)}`);return w.startsWith(`${S}/`)?w:null}function st(e){let t=_e.documents.get(e);if(!t)return null;let{frontmatter:S,body:w}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(S,w)}let vt=(e,t)=>applyExternalChange(_e,e,t,se,ce);function Tt(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Et=e=>{if(!e)return;let t=`[[${e}]]`;for(let[S]of _e.documents){if(isSystemDoc(S)||isConfigDoc(S))continue;let w=_e.documents.get(S);if(!w)continue;let E=w.getText(`source`).toString();if(E.includes(t))try{w.transact(()=>{applyDiskContentToDoc(w,E,se,S)},FILE_WATCHER_ORIGIN)}catch(t){ee.error({err:t,docName:S,assetBasename:e},`[asset-event] failed to re-render ${S} for asset basename ${e}`)}}},Dt=null,jt=e=>{e&&(Dt===null&&(Dt=new Set,setImmediate(()=>{let e=Dt;if(Dt=null,e)try{for(let t of e)Et(t)}catch(t){ee.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Dt.add(e))};function Mt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function Ft(e){try{switch(e.kind){case`create`:ee.info({docName:e.docName},`[reconcile] create: ${e.docName}`),de.updateDocumentFromMarkdown(e.docName,e.content),We(),fe.updateDocumentFromMarkdown(e.docName,e.content),Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`),$e(e.docName);break;case`update`:{let{docName:t,content:S}=e,w=_e.documents.get(t);if(!w){de.updateDocumentFromMarkdown(t,S),We(),fe.updateDocumentFromMarkdown(t,S),Be(`backlinks`),Be(`graph`),Be(`tags`);return}let E=getReconciledBase(t)??``,D=st(t)??E,O=reconcile({docName:t,base:E,ours:D,theirs:S}),k=contentHash(E).slice(0,6),j=contentHash(D).slice(0,6),F=contentHash(S).slice(0,6);switch(ee.info({docName:t,base:k,ours:j,theirs:F,result:O.kind},`[reconcile] ${t} base=${k} ours=${j} theirs=${F} result=${O.kind}`),O.kind){case`noop`:Tt(w),de.updateDocumentFromMarkdown(t,S),We(),fe.updateDocumentFromMarkdown(t,S),Be(`backlinks`),Be(`graph`),Be(`tags`);break;case`clean`:try{vt(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),Tt(w),de.updateDocumentFromMarkdown(t,S),We(),fe.updateDocumentFromMarkdown(t,S),Be(`backlinks`),Be(`graph`),Be(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,S),Tt(w)}break;case`merged`:try{vt(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),Tt(w),de.updateDocumentFromMarkdown(t,S),We(),fe.updateDocumentFromMarkdown(t,S),Be(`backlinks`),Be(`graph`),Be(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,S),Tt(w)}break;case`conflicts`:try{vt(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),incrementConflict(),de.updateDocumentFromMarkdown(t,S),We(),fe.updateDocumentFromMarkdown(t,S),Be(`backlinks`),Be(`graph`),Be(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,S)}{let e=w.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}break;case`refused`:{incrementConflict();let e=w.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,O.reason);break}}break}case`delete`:{let{docName:t}=e,S=_e.documents.get(t);if(!S){de.deleteDocument(t),We(),fe.deleteDocument(t),Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`),Xe(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let w=getReconciledBase(t)??``,E=st(t)??``,D=E!==w;if(D&&me.current){let e=me.current,S=Bt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,H??``,{kind:`external-change-rescue`,docName:t,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:S,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{ee.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),de.deleteDocument(t),We(),fe.deleteDocument(t),ee.info({docName:t,isDirty:D},`[reconcile] delete: ${t} (dirty=${D})`),_e.closeConnections(t),await Pe(S),Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`),Xe(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:S,content:w}=e,E=_e.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(S,w),de.renameDocument(t,S,w),We(),fe.renameDocument(t,S,w),E){let e=E.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,S)}ee.info({oldDocName:t,newDocName:S},`[reconcile] rename: ${t} → ${S}`),Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`),Ke(t,S),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:S,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,S=_e.documents.get(t);if(!S)return;let w=st(t);w===null?ee.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):setReconciledBase(t,w);let E=S.getMap(`lifecycle`);E.set(`status`,`conflict`),E.set(`reason`,`conflict-markers`),ee.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:oe.add(e.relativePath),Be(`files`),jt(basename(e.relativePath));break;case`asset-delete`:oe.remove(e.relativePath),Be(`files`),jt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:Be(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let S=Mt(e);ee.error({err:t,kind:e.kind,label:S},`[reconcile] failed to handle ${e.kind} for ${S}`)}}let It=[];async function Lt(e){if(isBatchInProgress()){It.push(e);return}await Ft(e)}async function Rt(){let e=It.splice(0,It.length);for(let t of e)await Ft(t)}let zt=null,Bt=null,Vt=null,Ht=null;async function Ut(e){if(_e.documents.size===0)return;let t=!1,S=new Promise(e=>{_e.configuration.extensions.push({async afterUnloadDocument({instance:S}){!t&&S.getDocumentsCount()===0&&(t=!0,e())}})}),w=Array.from(_e.documents.keys());_e.closeConnections(),_e.flushPendingStores();for(let e of _e.documents.values())e.getConnectionsCount()===0&&_e.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let E,D=new Promise((S,D)=>{E=setTimeout(()=>{t=!0;let S=Array.from(_e.documents.keys()),E=[],O=[];if(me.current){for(let e of S)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=st(e);if(t===null){ee.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),O.push(e);continue}let S=at(me.current.gitDir,e);if(!S){ee.warn({docName:e,gitDir:me.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),O.push(e);continue}mkdirSync(dirname(S),{recursive:!0}),writeFileSync(S,t,`utf-8`),incrementRescueBuffer(),E.push(e),ee.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){O.push(e),ee.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else ee.warn({stillLoadedCount:S.length},`[rescue] shadow repo unavailable at flush timeout — ${S.length} doc(s) will be lost: [${S.join(`, `)}]`),O.push(...S);let k=E.length>0||O.length>0?` — rescued [${E.join(`, `)}]${O.length>0?`, lost [${O.join(`, `)}]`:``}`:``;D(Error(`flushAllStoresAndWait timeout after ${e}ms — ${S.length}/${w.length} docs did not unload: [${S.join(`, `)}]${k}`))},e)});try{await Promise.race([S,D])}finally{E!==void 0&&clearTimeout(E)}}async function Wt(){return Ht||(Ht=(async()=>{let e=Date.now(),t=[];Me=!0,Ue!==null&&(clearTimeout(Ue),Ue=null);let w,E=await Promise.race([ze.then(()=>`completed`,e=>(ee.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{w=setTimeout(()=>e(`timeout`),5e3)})]);w!==void 0&&clearTimeout(w),E===`timeout`&&ee.warn({},`[server] init did not complete within 5s during shutdown`);let D=_e.documents.size;try{try{try{Bt&&=(await Bt.unsubscribe(),null),zt&&=(await zt.unsubscribe(),null);for(let{docName:e,cleanup:t}of it)try{await t()}catch(t){ee.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}it.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{ye?.destroy(),we?.destroy(),nt&&=(await nt.disconnect(),null);for(let[e,t]of rt)try{await t.disconnect()}catch(t){ee.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}rt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await ve.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Ut(q)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await ge.flushPendingGitCommit(),await ge.waitForPendingCommits()})(),new Promise((t,S)=>{e=setTimeout(()=>S(Error(`L2 git flush timeout`)),q)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{Vt&&=(await Vt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(me.current){try{let e=(await esm_default({baseDir:S,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(me.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(me.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let w=Date.now()-e;t.length===0?ee.info({documentCount:D,durationMs:w},`[server] shutdown flushed ${D} documents in ${w}ms`):ee.warn({documentCount:D,durationMs:w,phaseErrors:t},`[server] shutdown flushed ${D} documents in ${w}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(ae)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),Ht)}let Kt=[];async function $t(){try{De=await loadPrincipal(S),ee.info({principalId:De.id},`[server] principal loaded`)}catch(e){ee.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!me.current)try{me.current=await initShadowRepo(S),ee.info({gitDir:me.current.gitDir},`[server] history repo initialized at ${me.current.gitDir}`)}catch(e){ee.error({err:e},`[server] history repo init failed`),Kt.push(`shadow-repo`)}if(me.current){let e=null;try{e=loadRenameLogIndex(me.current.gitDir),sweepLazyPopOrphans(me.current.gitDir,e),setRenameLogIndex(me.current.gitDir,e),ee.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){ee.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(me.current,e,{rebuild:!0}),new Promise((e,S)=>setTimeout(()=>S(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){ee.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}}if(me.current)try{await shadowGit(me.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){ee.warn({},`[server] history repo appears corrupted — reinitializing`);try{me.current=await initShadowRepo(S)}catch(e){ee.error({err:e},`[server] history repo reinit failed`),me.current=void 0,Kt.includes(`shadow-repo`)||Kt.push(`shadow-repo`)}}else ee.error({err:e},`[server] history repo check failed (transient?)`)}if(me.current)try{let e=resolve(me.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let w=null;try{w=(await esm_default({baseDir:S,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(w!==null){if(w!==t){let e=`main`;try{let t=(await esm_default({baseDir:S,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}ee.info({lastKnownHead:t,currentHead:w,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=import`);try{await commitUpstreamImport(me.current,H??``,t,w,e),incrementUpstreamImport()}catch(e){ee.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else ee.info({currentHead:w},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=noop`);try{writeFileSync(e,w,`utf-8`)}catch(e){ee.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){ee.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,S);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,S=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;ee.warn({journalVersion:e.journal.version,fromPath:t,toPath:S,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${S}`)}}catch(e){ee.error({err:e},`[server] managed rename recovery failed`),Kt.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(S);(e.deleted>0||e.errors>0)&&ee.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){ee.error({err:e},`[server] upload-tempfile sweep failed`),Kt.push(`upload-tempfile-sweep`)}try{nt=await _e.openDirectConnection(SYSTEM_DOC_NAME),ye?.emitServerInfo(ne,getActiveBranch())}catch(e){ee.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Kt.push(`cc1-push`)}for(let e of CONFIG_DOC_NAMES)try{let t=await _e.openDirectConnection(e);rt.set(e,t)}catch(t){ee.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Kt.push(`config-doc:${e}`)}let w=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,S)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,S)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,S,F)]]);for(let e of CONFIG_DOC_NAMES){let t=w.get(e);if(t)try{ee.info({docName:e,path:t},`[config-file-watcher] starting`);let S=await startConfigFileWatcher(t,t=>{let S=_e.documents.get(e);ee.info({docName:e,hasDocument:S!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let w=applyExternalConfigChange(S??null,e,t,ge.configPersistenceCtx);if(ee.info({docName:e,outcome:w},`[config-file-watcher] applyExternalConfigChange outcome`),e===`__config__/project`||e===`__local__/project`){let e=te();Vt?.setEnabled(e).catch(t=>{ee.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}});it.push({docName:e,cleanup:S}),ee.info({docName:e,path:t},`[config-file-watcher] started`)}catch(S){ee.warn({err:S,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),Kt.push(`config-file-watcher:${e}`)}}try{let e=resolve(t,`.okignore`),w=resolve(S,`.gitignore`),E=null;try{let e=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:S,encoding:`utf-8`,timeout:5e3});if(e.status===0&&e.stdout){let t=join(resolve(S,e.stdout.trim()),`info`,`exclude`);existsSync(dirname(t))&&(E=t)}}catch{}let D=E?[e,w,E]:[e,w],O=ee;O.info({okignorePath:e,gitignorePath:w,gitInfoExcludePath:E},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let k=await startMultiPathConfigFileWatcher(D,(t,w)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(_e.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,w,ge.configPersistenceCtx);O.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){O.error({err:e,changedPath:relative(S,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let E=await ue.rebuildIgnorePatterns();if(E.ok)O.info({changedPath:relative(S,t),patternCount:E.patternCount,nestedFileCount:E.nestedFileCount,durationMs:E.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ye?.signal(`files`);else{let e=relative(S,t)||`.`;O.warn({changedPath:e,error:E.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ye?.emitConfigIgnoreNestedError(e,E.error.message)}})().catch(e=>{O.error({err:e,changedPath:relative(S,t)||`.`},`[ignore-watcher] handler threw`)})});it.push({docName:`__ignore-files__`,cleanup:k}),O.info({okignorePath:e,gitignorePath:w},`[ignore-watcher] multi-path watcher started`)}catch(e){ee.warn({err:e,projectDir:S,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Kt.push(`ignore-files-watcher`)}let E=resolveGitDir(S),D=E?readBranchFromHead(E)??`main`:`main`;switchReconciledBaseScope(D),de.switchBranch(D);try{{let e=getActiveBranch();try{if(await de.loadFromDisk(e)){let t=await de.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&ee.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await de.rebuildFromDisk(e);de.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){ee.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}zt=await startWatcher(t,Lt,ue),fe.init();let e=0;try{seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,w)=>{e++,ee.warn({reason:t,code:S,path:w},`[basename-index] skipped entry during seed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Kt.push(`basename-index-partial`))}catch(e){ee.error({err:e},`[basename-index] startup seed failed`),Kt.push(`basename-index`)}}catch(e){ee.error({err:e},`[server] disk bridge watcher failed to start`),Kt.push(`file-watcher`)}try{Bt=await startHeadWatcher(S,async({trigger:e})=>{if(ee.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),_e.flushPendingStores(),await ge.flushPendingGitCommit(),setBatchInProgress(!0),me.current){let e=getActiveBranch(),t=resolveGitDir(S),w=t?readBranchFromHead(t)??e:e,E=[];for(let[e,t]of _e.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let S=null;if(t.transact(()=>{S=st(e)},PARK_SNAPSHOT_ORIGIN),S===null)continue;let w=getReconciledBase(e)??S;E.push({docName:e,markdown:S,diskSnapshot:w})}if(E.length>0)try{let t=await parkBranch(me.current,e,SERVICE_WRITER.id,E,w);t&&(incrementPark(),ee.info({count:E.length,branch:e,sha:t.slice(0,8)},`[history] parked ${E.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){ee.error({err:e},`[shadow] park failed`)}}},async e=>{let S=It.length,w=e.newBranch??`main`;if(ee.info({kind:e.batchKind,headMoved:e.headMoved,docs:S,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${S}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await Rt(),await ge.flushDeferredStores(`within-branch`),Vt!==null)try{await Vt.reconcileConflictsFromGit()}catch(e){ee.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),It.splice(0,It.length),switchReconciledBaseScope(w),Ue!==null&&(clearTimeout(Ue),Ue=null),de.switchBranch(w),ue.rebuildDirCount();try{let e=0;oe.clear(),seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,E)=>{e++,ee.warn({reason:t,code:S,path:E,branch:w},`[basename-index] skipped entry during branch-switch reseed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e,branch:w},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Kt.includes(`basename-index-partial`)||Kt.push(`basename-index-partial`))}catch(e){ee.error({err:e,branch:w},`[basename-index] branch-switch reseed failed`)}for(let[e,S]of _e.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let E=safeContentPath(e,t);if(!existsSync(E)){let t=getReconciledBase(e)??``,E=st(e)??``;if(E!==t&&me.current){let t=me.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,H??``,{kind:`external-change-rescue`,docName:e,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:w,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{ee.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),ee.info({docName:e,branch:w},`[branch-switch] tombstone: ${e} (not on ${w})`);continue}let D=readFileSync(E,`utf-8`);vt(e,D),setReconciledBase(e,D),ee.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){ee.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}ee.info({branch:w,docCount:_e.documents.size},`[branch-switch] loaded branch ${w} (${_e.documents.size} docs)`);try{if(await de.loadFromDisk(w)){let e=await de.reconcileWithDisk(w);(e.added>0||e.updated>0||e.deleted>0)&&ee.info(e,`[backlinks] branch-switch reconcile for ${w}`)}else await de.rebuildFromDisk(w);de.saveToDisk(w).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${w}:`,e)})}catch(e){ee.error({err:e,branch:w},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(fe.init(),me.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of _e.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let S=await readParkedState(me.current,w,SERVICE_WRITER.id,t);if(!S||S.markdown===S.diskSnapshot)continue;let E=getReconciledBase(t);if(!E)continue;let D=reconcile({docName:t,base:S.diskSnapshot,ours:S.markdown,theirs:E});switch(D.kind){case`merged`:case`clean`:vt(t,D.newContent),setReconciledBase(t,D.newContent),e++;break;case`conflicts`:vt(t,D.newContent),setReconciledBase(t,D.newContent),incrementConflict(),e++;{let e=_e.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){ee.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&ee.info({count:e,branch:w},`[branch-switch] restored ${e} parked docs on ${w}`)}if(e.oldBranch?.startsWith(`detached-`)&&me.current)try{let t=shadowGit(me.current),S=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(S){for(let e of S.split(`
|
|
3509
3509
|
`))e&&await t.raw(`update-ref`,`-d`,e);ee.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){ee.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await ge.flushDeferredStores(`discard-stale`),ye?.emitBranchSwitched(w)}if(e.headMoved&&e.newHead&&me.current&&S>0){let t=H??`.`;try{let S=await commitUpstreamImport(me.current,t,e.oldHead,e.newHead,w);incrementUpstreamImport(),ee.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:S.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${S.slice(0,8)}`)}catch(e){ee.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){ee.error({err:e},`[server] HEAD watcher failed to start`),Kt.push(`head-watcher`)}function O(e){for(let w of e)try{let e=relative(t,join(S,w));if(e.startsWith(`..`))continue;let E=stripDocExtension(e),D=_e.documents.get(E);if(!D)continue;let O=st(E);O===null?ee.warn({docName:E,file:w},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(E,O);let k=D.getMap(`lifecycle`);k.set(`status`,`conflict`),k.set(`reason`,`sync-merge-conflict`),ee.info({docName:E,file:w},`[sync] marked loaded content conflict`)}catch(e){ee.warn({err:e,file:w},`[sync] failed to mark loaded content conflict`)}}let k=J?.[0]??`open-knowledge`,j=[`-c`,`credential.helper=!${J&&J.length>1?J.join(` `):k} auth git-credential`];try{Vt=new SyncEngine({projectDir:S,contentDir:t,contentFilter:ue,contentRoot:H,syncEnabled:te(),credentialArgs:j,cc1Broadcaster:ye,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||ge.flushDeferredStores(`within-branch`).catch(e=>{ee.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{ee.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:O,onAutoDisable:async e=>{ee.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:S,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||ee.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,S)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await Vt.start()}catch(e){ee.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Vt=null}Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`)}return $t().then(Ie,Re),{hocuspocus:_e,sessionManager:ve,cc1Broadcaster:ye,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,contentFilter:ue,basenameIndex:oe,serverInstanceId:ne,destroy:Wt,ready:ze,degraded:Kt,lockDir:ae,get syncEngine(){return Vt}}}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let S=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&S.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let w=resolve(e,t);try{existsSync(w)&&statSync(w).isDirectory()&&S.push(`${t}/`)}catch{}}return S}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3;async function bootServer(e){let t=resolveLocalSinkConfig({projectDir:e.projectDir??e.contentDir,contentDir:e.contentDir});if(t){let e=t.telemetry.attributeDenylist,S=[];for(let t of e)S.push(t),S.push(`*.${t}`);loggerFactory.configure({pinoConfig:{fileSink:t.logs,redactPaths:S}})}initTelemetry({localSink:t?.telemetry});let{kind:S,gitdir:w}=computeWorktreeAttributes(e.projectDir??e.contentDir),E={"ok.worktree.kind":S};return w!==null&&(E[`ok.worktree.gitdir`]=normalizeFsPath(w)),withSpan(`ok.boot`,{attributes:E},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,S=e.attachUiSibling??!0,w=e.idleShutdownMs,E=e.log??getLogger(`boot`),D=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,O=e.lockKind??D??`interactive`,{createServer:k}=await import(`node:http`),{updateServerLockPort:j}=await import(`./server-lock-v2ktHD7l-C-3wEnoU.mjs`),F=!1;if(!t&&e.autoInitFn)try{F=!!await e.autoInitFn()}catch(e){E.warn({err:e},`autoInitFn failed`)}let L=e.projectDir??e.contentDir,B=resolve(L,`.ok`);if(!existsSync(resolve(B,`config.yml`)))throw new MissingOkConfigError(existsSync(B)?`config`:`okdir`,L);existsSync(resolve(B,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let H=e.gitPreflight??assertGitAvailable;try{H()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,S=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),E.warn({event:`git_preflight_fail`,platform:e.platform,reason:S,detectedVersion:t},S===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),e}let q=findLegacyRuntimeFiles(B);q.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${q.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let J=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:O,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore}),{hocuspocus:Y,destroy:ee,ready:te,degraded:ne,lockDir:ae,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce}=J,ue=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),de=e.port??0,fe=createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ue}:${de}`,log:E}),me=k();me.headersTimeout=3e4,me.requestTimeout=6e4;let ge=e.serveContentAssets?createAssetServeMiddleware({contentFilter:J.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,_e=!1;if(e.reactShellDistDir)try{acquireUiLock(ae,{port:0,worktreeRoot:e.projectDir??e.contentDir}),_e=!0}catch(e){if(e instanceof UiLockCollisionError)E.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:ae},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await ee().catch(()=>{}),e}let ve=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ye=mountMcpAndApi({httpServer:me,hocuspocus:Y,mcpHttpHandler:fe,log:E,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:ge,reactShellMiddleware:ve}),Ce=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},we=null;w!==null&&(we=attachIdleShutdown({httpServer:me,thresholdMs:w??DEFAULT_IDLE_THRESHOLD_MS,log:E,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await Ce()})})),await restoreLifecycleFromConflictsJson({hocuspocus:Y,projectDir:e.projectDir??e.contentDir,log:E});try{await new Promise((t,S)=>{let w=e=>S(e);me.once(`error`,w),me.listen(e.port,e.host,()=>{me.removeListener(`error`,w),t()})})}catch(e){if(_e)try{releaseUiLock(ae)}catch(e){E.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await ee().catch(()=>{}),e}let Te=me.address(),De=typeof Te==`object`&&Te?Te.port:e.port??0;if(de=De,j(ae,De),_e&&updateUiLockPort(ae,De),S&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ae,log:E})}catch(e){E.warn({err:e},`spawnUiSiblingFn failed`)}let je=!1,Me=async(e,t)=>{let S;try{await Promise.race([t(),new Promise((t,w)=>{S=setTimeout(()=>{w(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),S.unref?.()})])}finally{S!==void 0&&clearTimeout(S)}};return Ce=async()=>{if(je)return;je=!0;let e=[],t=async(t,S)=>{try{await Me(t,S)}catch(S){e.push(S),E.warn({err:S,step:t},`bootServer destroy step failed`)}};try{we?.detach()}catch(t){e.push(t),E.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>ye.shutdown()),await t(`mcpHttpHandler.close`,()=>fe.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ye.wss.close(S=>S?t(S):e())})),await t(`httpServer.closeAllConnections`,async()=>{me.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{me.close(S=>S&&S.code!==`ERR_SERVER_NOT_RUNNING`?t(S):e())})),await t(`destroyHocuspocus`,()=>ee()),_e&&await t(`releaseUiLock`,async()=>releaseUiLock(ae)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},{httpServer:me,destroy:Ce,lockDir:ae,contentDir:e.contentDir,port:De,ready:te,degraded:ne,didAutoInit:F,serverInstance:J}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:S,log:w}=e,E,D;try{E=new ConflictStore(S),D=E.list()}catch(e){w.warn({err:e,projectDir:S},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(D.length===0)return;let O=null;try{let e=resolveGitDir(S),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){E.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:D.length}));return}let w=(await simpleGit({baseDir:S,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();O=new Set(w?w.split(`
|
|
3510
3510
|
`).map(e=>e.trim()).filter(Boolean):[])}catch(e){w.warn({err:e,projectDir:S},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(O!==null){let e=0;for(let t of D)O.has(t.file)||(E.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:D.length-e})),D=D.filter(e=>O?.has(e.file)),D.length===0)return}for(let e of D){let S=stripDocExtension(e.file),E=null,D=!1;try{E=await t.openDirectConnection(S);let e=E.document;if(!e)continue;let w=e.getMap(`lifecycle`);w.set(`status`,`conflict`),w.set(`reason`,`conflict-markers`),D=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":S}))}catch(e){w.warn({err:e,docName:S},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(E)try{await E.disconnect()}catch(e){w.warn({err:e,docName:S,restored:D},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),S=e.platformName??process.platform,w=e.env??process.env;return S===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):S===`win32`?existsSync(join(w.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],S=e.toLowerCase();if(t.includes(S))return S}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let S=t===1?e:`${e}.${t-1}`,w=`${e}.${t}`;try{renameSync(S,w)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),S=MAX_AGE_DAYS*24*60*60*1e3,w=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let S=statSync(join(e,t));return{name:t,mtime:S.mtimeMs,size:S.size}}catch{return null}}).filter(Boolean);for(let E of w)if(t-E.mtime>S)try{unlinkSync(join(e,E.name))}catch{}let E=w.filter(e=>t-e.mtime<=S).sort((e,t)=>e.mtime-t.mtime),D=E.reduce((e,t)=>e+t.size,0);for(let t of E){if(D<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),D-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),S=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(S),setTimeout(()=>pruneLogsDir(OK_LOGS_DIR),5e3);let w=import_pino.default.destination({dest:S,append:!0,sync:!1});return(0,import_pino.default)({level:resolveLogLevel(),name:e.name,redact:{paths:REDACT_PATHS,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:import_pino.default.stdTimeFunctions.isoTime,...e.additionalOptions},w)}function getLogFilePath(e){return join(OK_LOGS_DIR,`${e}.${todayDateString()}.log`)}function getLogsDir(){return OK_LOGS_DIR}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),S=0;for(;S<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:S};let w=dirname(t);if(w===t)return null;t=w,S+=1}return null}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,S){super(e,S),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){try{let{stdout:t}=await execFileAsync(`git`,[`rev-parse`,`--is-inside-work-tree`],{cwd:e});return t.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),S=resolve(t,`.git`),w=resolve(S,`HEAD`),E=!1;if(existsSync(S)){if(!statSync(S).isDirectory()||existsSync(w))return{didInit:!1};console.log(`[project-git] detected partial .git/ — running git init to repair`),E=!0}else if(await isInsideExistingWorkTree(t))return{didInit:!1};let D=``;try{D=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let S=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,S,{cause:e})}if(!existsSync(w))throw new ProjectGitInitError(`git init reported success but ${S}/HEAD is missing (partial init detected)`,D);return E?(console.log(`[project-git] backfilled missing .git/HEAD at ${t}`),{didInit:!0,repaired:!0}):(console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{didInit:!0})}async function resolvePackageVersion(e,t){let S;try{S=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(S),w=0;w<32;w+=1){let S=join(t,`package.json`);if(existsSync(S))try{let t=JSON.parse(await readFile$1(S,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let w=dirname(t);if(w===t)return;t=w}}const MAX_CAUSE_DEPTH=5,HOME_PATH_PATTERNS=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function scrubPaths(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:S}of HOME_PATH_PATTERNS)t=t.replace(e,S);return t}function serializeError(e,t=0,S=new WeakSet){if(t>=MAX_CAUSE_DEPTH)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > ${MAX_CAUSE_DEPTH}; truncated`};if(typeof e==`object`&&e){if(S.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};S.add(e)}if(e instanceof Error)return{name:e.name,message:scrubPaths(e.message)??``,stack:scrubPaths(e.stack),code:e.code,cause:e.cause===void 0?void 0:serializeError(e.cause,t+1,S)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:scrubPaths(e)??e};if(typeof e==`object`){let w=e;return{name:String(w.name??`ObjectError`),message:scrubPaths(String(w.message??``))??``,stack:scrubPaths(w.stack),code:w.code,cause:w.cause===void 0?void 0:serializeError(w.cause,t+1,S)}}return{name:`UnknownError`,message:String(e)}}export{TagIndex as $,array as $i,readTargetRecordedAt as $n,tracedUnlinkSync as $r,formatAuthRejectionWire as $t,MCP_CONNECTION_ID_HEADER as A,DEFAULT_GITHUB_OAUTH_CLIENT_ID as Ai,isSelfWrite as An,saveInMemoryCheckpoint as Ar,createContentFilter as At,ROLLBACK_ORIGIN as B,SYSTEM_DOC_NAME as Bi,normalizeFsPath as Bn,splitMarkdownBlocks as Br,createStreamingErrorWriter as Bt,HocuspocusAuthRejection as C,writeConfigPatch as Ci,isConfigDoc as Cn,runCloneSubprocess as Cr,commitWipFromTree as Ct,LOG_MD_TEMPLATE as D,ALL_EDITOR_IDS as Di,isPairedWriteOrigin as Dn,safeSubdir as Dr,contributorCount as Dt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as E,resolveShadowDir as Ei,isLoopbackAddress as En,safeContentPath as Er,contentHash as Et,MissingOkConfigError as F,INLINE_RENDERABLE_EXTENSIONS as Fi,loadPrincipal as Fn,shadowGit as Fr,createMcpHttpHandler as Ft,STARTER_FOLDER_FRONTMATTER_FILENAME as G,isBranchNotFoundGitError as Gi,parseKeepaliveConnectionId as Gn,tracedAppendFileSync as Gr,emitPreflightFailureSpan as Gt,SERVICE_WRITER as H,defaultScheduler as Hi,parseAuthRejectionWire as Hn,streamingProblemEvent as Hr,detectClaudeDesktopPresence as Ht,OBSERVER_SYNC_ORIGIN as I,ORPHAN_MODES as Ii,loggerFactory as In,shutdownTelemetry as Ir,createOsProbe as It,STARTER_TEMPLATES as J,DEFAULT_SPANS_MAX_BYTES as Ji,readAllTargets as Jn,tracedMkdirSync as Jr,evictStaleTrackerEntries as Jt,STARTER_PACKS as K,isOrphanMode as Ki,pathToDocName as Kn,tracedLinkSync as Kr,ensureProjectGit as Kt,OK_OKIGNORE_TEMPLATE as L,ProblemDetailsSchema as Li,logsCurrentPath as Ln,spansCurrentPath as Lr,createPersistenceExtension as Lt,MIN_GIT_VERSION as M,DEFAULT_SIGTERM_GRACE_MS as Mi,lastKnownHash as Mn,seedBasenameIndex as Mr,createExternalChangeHandler as Mt,MISSING_OK_CONFIG_MESSAGE as N,EDITOR_LABELS as Ni,listRescueCheckpoints as Nn,serializeError as Nr,createFileLogger as Nt,MANAGED_RENAME_ORIGIN as O,ASSET_EXTENSIONS as Oi,isPathWithinDir as On,safetyCheckpoint as Or,createApiExtension as Ot,McpLogger as P,EXECUTABLE_BLOCKLIST_EXTENSIONS as Pi,listStarterPacks as Pn,setActiveSpanAttributes as Pr,createLiveDerivedIndexExtension as Pt,StateManifestError as Q,any$1 as Qi,readStateManifest as Qn,tracedRmdirSync as Qr,findEnclosingProjectRoot as Qt,PinoLogger as R,SKILL_STATE_TARGETS as Ri,logsPreviousPath as Rn,spansPreviousPath as Rr,createServer$1 as Rt,HOCUSPOCUS_AUTH_REJECTION_REASONS as S,withFileLockSync as Si,isAllowedWorkspaceHostHeader as Sn,runAuthStatusSubprocess as Sr,commitWip as St,INSTALLED_AGENTS_SCHEMES as T,MalformedGitPointerError as Ti,isKnownPackId as Tn,runWithMcpLogger as Tr,containsConflictMarkers as Tt,SKILL_INSTALL_EVENTS_FILE_REL as U,humanFormat as Ui,parseGitVersion as Un,swapContributors as Ur,detectGit as Ut,ROOT_GITIGNORE_TEMPLATE as V,colorFromSeed as Vi,packageVersionMajorMinor as Vn,startWatcher as Vr,createTestLogger as Vt,STARTER_FOLDERS as W,iconFromClientName as Wi,parseHocuspocusAuthToken as Wn,toBroadcasterKey as Wr,detectProjectShape as Wt,SeedPrerequisiteError as X,locateIssue as Xi,readServerPackageVersion as Xn,tracedRenameSync as Xr,fallbackPaths as Xt,STATE_MANIFEST_FILENAME as Y,OK_PROJECT_MARKER as Yi,readBranchFromHead as Yn,tracedRename as Yr,extractWikiLinksFromMarkdown as Yt,SeedRootDirError as Z,ZodNumber$1 as Zi,readSkillInstallStateSnapshot as Zn,tracedRmSync as Zr,findEnclosingGitRoot as Zt,FILE_WATCHER_ORIGIN as _,isJSONRPCRequest as _i,initTelemetry as _n,restoreContributors as _r,classifyEvents as _t,AgentPresenceBroadcaster as a,string$2 as aa,validateCloneInputs as ai,getLogFilePath as an,registerAllTools as ar,assertCompatibleStateManifest as at,GitNotAvailableError as b,readConfigSafely as bi,installUserSkill as bn,rewriteWikiLinksForDocumentRename as br,coercePackId as bt,BacklinkIndex as c,NEVER as ca,withSpanSync as ci,getMeter as cn,removeLastKnownHash as cr,attachIdleShutdown as ct,CONFLICT_MARKER_RE as d,writeTargetVersion as di,handleCollabSocketError as dn,resolveContentDir as dr,buildConfigYmlContent as dt,boolean$1 as ea,tracedWriteFile as ei,formatContributors as en,readTargetVersion as er,UiLockCollisionError as et,CURSOR_BUNDLE_PATHS_BY_PLATFORM as f,writeTracker as fi,handleSpawnCursor as fn,resolveCursorBinaryDefault as fr,buildExecResult as ft,FILE_SYSTEM_WRITER as g,isInitializedNotification as gi,initShadowRepo as gn,resolvePackageVersion as gr,buildWipTree as gt,DEFAULT_PACK_ID as h,LATEST_PROTOCOL_VERSION as hi,initContent as hn,resolvePack as hr,buildStarterFolderFrontmatterYaml as ht,AgentFocusBroadcaster as i,object$1 as ia,validateAgentId as ii,getLocalDir as in,recordSkillInstallEvent as ir,applySeed as it,MCP_SERVER_NAME as j,DEFAULT_SERVER_HOST as ji,isSystemDoc as jn,saveVersion as jr,createContentFilterAsync as jt,MAX_AGENT_SESSIONS as k,CC1_CONTRACT_VERSION as ki,isProjectRoot as kn,sanitizeClientName as kr,createAssetServeMiddleware as kt,CC1Broadcaster as l,require_dist$1 as la,writeRootGitignoreForNewRepo as li,getMetrics as ln,resetMetrics as lr,bootServer as lt,DEFAULT_CHECKPOINT_RETENTION as m,JSONRPCMessageSchema as mi,incrementServerObserverFire as mn,resolveLockDir as mr,buildSkillZip as mt,AGENT_ID_RE as n,looseObject as na,updateLastKnownHash as ni,gcCheckpointRefs as nn,reconcile as nr,applyAgentMarkdownWrite as nt,AgentSessionCapacityError as o,url as oa,validateSkillZip as oi,getLogger as on,registerWrite as or,assertGitAvailable as ot,ConfigSchema as p,McpServer as pi,incrementCollabSocketFilteredError as pn,resolveCursorSpawnInvocation as pr,buildInstructions as pt,STARTER_PACK_IDS as q,DEFAULT_LOGS_MAX_BYTES as qi,planSeed as qn,tracedMkdir as qr,errorResponse as qt,AGENT_WRITE_ORIGIN as r,number$1 as ra,updateUiLockPort as ri,getCurrentMcpLogger as rn,recordContributor as rr,applyExternalChange as rt,AgentSessionManager as s,_coercedNumber as sa,withSpan as si,getLogsDir as sn,releaseUiLock as sr,assertNeverDiskEvent as st,AGENT_ID_MAX_LEN as t,literal as ta,tracedWriteFileSync as ti,formatContributorsFrom as tn,readUiLock as tr,acquireUiLock as tt,CONFIG_FILENAME as u,writeStateManifest as ui,getTracer as un,resolveBundledSkillDir as ur,buildAndOpenSkill as ut,GIT_PREFLIGHT_FAIL_SPAN_NAME as v,isJSONRPCResultResponse as vi,installPrettyZodErrors as vn,restoreLifecycleFromConflictsJson as vr,classifyFsPath as vt,HocuspocusAuthTokenSchema as w,GitDirAccessError as wi,isHocuspocusAuthRejectionReason as wn,runDeviceFlowSubprocess as wr,compareSemver as wt,GitTooOldError as x,resolveConfigPath as xi,isAllowedApiOrigin as xn,runAuthReposSubprocess as xr,commitUpstreamImport as xt,GIT_UPSTREAM_WRITER as y,atomicWriteFileSync as yi,installTestLoggers as yn,rewriteMarkdownLinksForDocumentRename as yr,clearContributors as yt,ProjectGitInitError as z,SPAWN_ERROR_LOG as zi,mountMcpAndApi as zn,spawnDetached as zr,createServerObserverExtension as zt};
|
|
3511
|
-
//# sourceMappingURL=dist-
|
|
3511
|
+
//# sourceMappingURL=dist-BkOSFGR2.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as e,$n as t,$r as n,$t as r,A as i,An as a,Ar as o,At as s,B as c,Bi as l,Bn as u,Br as d,Bt as f,C as p,Cn as m,Cr as h,Ct as g,D as _,Dn as v,Dr as y,Dt as b,E as x,En as S,Er as C,Et as w,F as T,Fn as E,Fr as D,Ft as O,G as k,Gn as A,Gr as j,Gt as M,H as N,Hn as P,Hr as F,Ht as I,I as L,Ii as R,In as z,Ir as B,It as V,J as H,Jn as U,Jr as W,Jt as G,K,Ki as q,Kn as J,Kr as Y,Kt as X,L as Z,Ln as Q,Lr as $,Lt as ee,M as te,Mn as ne,Mr as re,Mt as ie,N as ae,Nn as oe,Nr as se,Nt as ce,O as le,On as ue,Or as de,Ot as fe,P as pe,Pn as me,Pr as he,Pt as ge,Q as _e,Qn as ve,Qr as ye,Qt as be,R as xe,Ri as Se,Rn as Ce,Rr as we,Rt as Te,S as Ee,Sn as De,Sr as Oe,St as ke,T as Ae,Ti as je,Tn as Me,Tr as Ne,Tt as Pe,U as Fe,Un as Ie,Ur as Le,Ut as Re,V as ze,Vi as Be,Vn as Ve,Vr as He,Vt as Ue,W as We,Wi as Ge,Wn as Ke,Wr as qe,Wt as Je,X as Ye,Xn as Xe,Xr as Ze,Xt as Qe,Y as $e,Yn as et,Yr as tt,Yt as nt,Z as rt,Zn as it,Zr as at,Zt as ot,_ as st,_n as ct,_r as lt,_t as ut,a as dt,ai as ft,an as pt,ar as mt,at as ht,b as gt,bn as _t,br as vt,bt as yt,c as bt,ci as xt,cn as St,cr as Ct,ct as wt,d as Tt,di as Et,dn as Dt,dr as Ot,dt as kt,ei as At,en as jt,er as Mt,et as Nt,f as Pt,fi as Ft,fn as It,fr as Lt,ft as Rt,g as zt,gn as Bt,gr as Vt,gt as Ht,h as Ut,hn as Wt,hr as Gt,ht as Kt,i as qt,ii as Jt,in as Yt,ir as Xt,it as Zt,j as Qt,jn as $t,jr as en,jt as tn,k as nn,ki as rn,kn as an,kr as on,kt as sn,l as cn,li as ln,ln as un,lr as dn,lt as fn,m as pn,mn,mr as hn,mt as gn,n as _n,ni as vn,nn as yn,nr as bn,nt as xn,o as Sn,oi as Cn,on as wn,or as Tn,ot as En,p as Dn,pn as On,pr as kn,pt as An,q as jn,qn as Mn,qr as Nn,qt as Pn,r as Fn,ri as In,rn as Ln,rr as Rn,rt as zn,s as Bn,si as Vn,sn as Hn,sr as Un,st as Wn,t as Gn,ti as Kn,tn as qn,tr as Jn,tt as Yn,u as Xn,ui as Zn,un as Qn,ur as $n,ut as er,v as tr,vn as nr,vr as rr,vt as ir,w as ar,wi as or,wn as sr,wr as cr,wt as lr,x as ur,xn as dr,xr as fr,xt as pr,y as mr,yn as hr,yr as gr,yt as _r,z as vr,zn as yr,zr as br,zt as xr}from"./dist-
|
|
1
|
+
import{$ as e,$n as t,$r as n,$t as r,A as i,An as a,Ar as o,At as s,B as c,Bi as l,Bn as u,Br as d,Bt as f,C as p,Cn as m,Cr as h,Ct as g,D as _,Dn as v,Dr as y,Dt as b,E as x,En as S,Er as C,Et as w,F as T,Fn as E,Fr as D,Ft as O,G as k,Gn as A,Gr as j,Gt as M,H as N,Hn as P,Hr as F,Ht as I,I as L,Ii as R,In as z,Ir as B,It as V,J as H,Jn as U,Jr as W,Jt as G,K,Ki as q,Kn as J,Kr as Y,Kt as X,L as Z,Ln as Q,Lr as $,Lt as ee,M as te,Mn as ne,Mr as re,Mt as ie,N as ae,Nn as oe,Nr as se,Nt as ce,O as le,On as ue,Or as de,Ot as fe,P as pe,Pn as me,Pr as he,Pt as ge,Q as _e,Qn as ve,Qr as ye,Qt as be,R as xe,Ri as Se,Rn as Ce,Rr as we,Rt as Te,S as Ee,Sn as De,Sr as Oe,St as ke,T as Ae,Ti as je,Tn as Me,Tr as Ne,Tt as Pe,U as Fe,Un as Ie,Ur as Le,Ut as Re,V as ze,Vi as Be,Vn as Ve,Vr as He,Vt as Ue,W as We,Wi as Ge,Wn as Ke,Wr as qe,Wt as Je,X as Ye,Xn as Xe,Xr as Ze,Xt as Qe,Y as $e,Yn as et,Yr as tt,Yt as nt,Z as rt,Zn as it,Zr as at,Zt as ot,_ as st,_n as ct,_r as lt,_t as ut,a as dt,ai as ft,an as pt,ar as mt,at as ht,b as gt,bn as _t,br as vt,bt as yt,c as bt,ci as xt,cn as St,cr as Ct,ct as wt,d as Tt,di as Et,dn as Dt,dr as Ot,dt as kt,ei as At,en as jt,er as Mt,et as Nt,f as Pt,fi as Ft,fn as It,fr as Lt,ft as Rt,g as zt,gn as Bt,gr as Vt,gt as Ht,h as Ut,hn as Wt,hr as Gt,ht as Kt,i as qt,ii as Jt,in as Yt,ir as Xt,it as Zt,j as Qt,jn as $t,jr as en,jt as tn,k as nn,ki as rn,kn as an,kr as on,kt as sn,l as cn,li as ln,ln as un,lr as dn,lt as fn,m as pn,mn,mr as hn,mt as gn,n as _n,ni as vn,nn as yn,nr as bn,nt as xn,o as Sn,oi as Cn,on as wn,or as Tn,ot as En,p as Dn,pn as On,pr as kn,pt as An,q as jn,qn as Mn,qr as Nn,qt as Pn,r as Fn,ri as In,rn as Ln,rr as Rn,rt as zn,s as Bn,si as Vn,sn as Hn,sr as Un,st as Wn,t as Gn,ti as Kn,tn as qn,tr as Jn,tt as Yn,u as Xn,ui as Zn,un as Qn,ur as $n,ut as er,v as tr,vn as nr,vr as rr,vt as ir,w as ar,wi as or,wn as sr,wr as cr,wt as lr,x as ur,xn as dr,xr as fr,xt as pr,y as mr,yn as hr,yr as gr,yt as _r,z as vr,zn as yr,zr as br,zt as xr}from"./dist-BkOSFGR2.mjs";import{a as Sr,c as Cr,d as wr,f as Tr,g as Er,h as Dr,i as Or,l as kr,m as Ar,n as jr,o as Mr,p as Nr,r as Pr,s as Fr,t as Ir,u as Lr}from"./server-lock-BIY3RMaC-CfCHCMTe.mjs";export{Gn as AGENT_ID_MAX_LEN,_n as AGENT_ID_RE,Fn as AGENT_WRITE_ORIGIN,qt as AgentFocusBroadcaster,dt as AgentPresenceBroadcaster,Sn as AgentSessionCapacityError,Bn as AgentSessionManager,bt as BacklinkIndex,cn as CC1Broadcaster,rn as CC1_CONTRACT_VERSION,Xn as CONFIG_FILENAME,Tt as CONFLICT_MARKER_RE,Pt as CURSOR_BUNDLE_PATHS_BY_PLATFORM,Dn as ConfigSchema,pn as DEFAULT_CHECKPOINT_RETENTION,Ut as DEFAULT_PACK_ID,zt as FILE_SYSTEM_WRITER,st as FILE_WATCHER_ORIGIN,tr as GIT_PREFLIGHT_FAIL_SPAN_NAME,mr as GIT_UPSTREAM_WRITER,or as GitDirAccessError,gt as GitNotAvailableError,ur as GitTooOldError,Ee as HOCUSPOCUS_AUTH_REJECTION_REASONS,p as HocuspocusAuthRejection,ar as HocuspocusAuthTokenSchema,Ae as INSTALLED_AGENTS_SCHEMES,x as LIVE_DERIVED_INDEX_DEBOUNCE_MS,_ as LOG_MD_TEMPLATE,le as MANAGED_RENAME_ORIGIN,nn as MAX_AGENT_SESSIONS,i as MCP_CONNECTION_ID_HEADER,Qt as MCP_SERVER_NAME,te as MIN_GIT_VERSION,ae as MISSING_OK_CONFIG_MESSAGE,je as MalformedGitPointerError,pe as McpLogger,T as MissingOkConfigError,L as OBSERVER_SYNC_ORIGIN,Z as OK_OKIGNORE_TEMPLATE,R as ORPHAN_MODES,xe as PinoLogger,Ir as ProcessLockCollisionError,vr as ProjectGitInitError,c as ROLLBACK_ORIGIN,ze as ROOT_GITIGNORE_TEMPLATE,jr as RUNTIME_VERSION,N as SERVICE_WRITER,Fe as SKILL_INSTALL_EVENTS_FILE_REL,Se as SKILL_STATE_TARGETS,We as STARTER_FOLDERS,k as STARTER_FOLDER_FRONTMATTER_FILENAME,K as STARTER_PACKS,jn as STARTER_PACK_IDS,H as STARTER_TEMPLATES,$e as STATE_MANIFEST_FILENAME,Pr as STATE_SCHEMA_VERSION,l as SYSTEM_DOC_NAME,Ye as SeedPrerequisiteError,rt as SeedRootDirError,Or as ServerLockCollisionError,_e as StateManifestError,e as TagIndex,Nt as UiLockCollisionError,Sr as acquireProcessLock,Mr as acquireServerLock,Yn as acquireUiLock,xn as applyAgentMarkdownWrite,zn as applyExternalChange,Zt as applySeed,ht as assertCompatibleStateManifest,En as assertGitAvailable,Wn as assertNeverDiskEvent,wt as attachIdleShutdown,fn as bootServer,er as buildAndOpenSkill,kt as buildConfigYmlContent,Rt as buildExecResult,An as buildInstructions,gn as buildSkillZip,Kt as buildStarterFolderFrontmatterYaml,Ht as buildWipTree,ut as classifyEvents,ir as classifyFsPath,_r as clearContributors,yt as coercePackId,Be as colorFromSeed,pr as commitUpstreamImport,ke as commitWip,g as commitWipFromTree,lr as compareSemver,Pe as containsConflictMarkers,w as contentHash,b as contributorCount,fe as createApiExtension,sn as createAssetServeMiddleware,s as createContentFilter,tn as createContentFilterAsync,ie as createExternalChangeHandler,ce as createFileLogger,ge as createLiveDerivedIndexExtension,O as createMcpHttpHandler,V as createOsProbe,ee as createPersistenceExtension,Te as createServer,xr as createServerObserverExtension,f as createStreamingErrorWriter,Ue as createTestLogger,I as detectClaudeDesktopPresence,Re as detectGit,Je as detectProjectShape,M as emitPreflightFailureSpan,X as ensureProjectGit,Pn as errorResponse,G as evictStaleTrackerEntries,nt as extractWikiLinksFromMarkdown,Qe as fallbackPaths,ot as findEnclosingGitRoot,be as findEnclosingProjectRoot,r as formatAuthRejectionWire,jt as formatContributors,qn as formatContributorsFrom,yn as gcCheckpointRefs,Ln as getCurrentMcpLogger,Yt as getLocalDir,pt as getLogFilePath,wn as getLogger,Hn as getLogsDir,St as getMeter,un as getMetrics,Qn as getTracer,Dt as handleCollabSocketError,It as handleSpawnCursor,Ge as iconFromClientName,On as incrementCollabSocketFilteredError,mn as incrementServerObserverFire,Wt as initContent,Bt as initShadowRepo,ct as initTelemetry,nr as installPrettyZodErrors,hr as installTestLoggers,_t as installUserSkill,dr as isAllowedApiOrigin,De as isAllowedWorkspaceHostHeader,m as isConfigDoc,sr as isHocuspocusAuthRejectionReason,Me as isKnownPackId,S as isLoopbackAddress,q as isOrphanMode,v as isPairedWriteOrigin,ue as isPathWithinDir,Fr as isProcessAlive,an as isProjectRoot,a as isSelfWrite,$t as isSystemDoc,Cr as isValidLockPid,ne as lastKnownHash,oe as listRescueCheckpoints,me as listStarterPacks,E as loadPrincipal,kr as lockFilePath,z as loggerFactory,Q as logsCurrentPath,Ce as logsPreviousPath,yr as mountMcpAndApi,u as normalizeFsPath,Ve as packageVersionMajorMinor,P as parseAuthRejectionWire,Ie as parseGitVersion,Ke as parseHocuspocusAuthToken,A as parseKeepaliveConnectionId,J as pathToDocName,Mn as planSeed,U as readAllTargets,et as readBranchFromHead,Lr as readProcessLock,wr as readProcessLockDetailed,Tr as readServerLock,Xe as readServerPackageVersion,it as readSkillInstallStateSnapshot,ve as readStateManifest,t as readTargetRecordedAt,Mt as readTargetVersion,Jn as readUiLock,bn as reconcile,Rn as recordContributor,Xt as recordSkillInstallEvent,mt as registerAllTools,Tn as registerWrite,Nr as releaseProcessLock,Ar as releaseServerLock,Un as releaseUiLock,Ct as removeLastKnownHash,dn as resetMetrics,$n as resolveBundledSkillDir,Ot as resolveContentDir,Lt as resolveCursorBinaryDefault,kn as resolveCursorSpawnInvocation,hn as resolveLockDir,Gt as resolvePack,Vt as resolvePackageVersion,lt as restoreContributors,rr as restoreLifecycleFromConflictsJson,gr as rewriteMarkdownLinksForDocumentRename,vt as rewriteWikiLinksForDocumentRename,fr as runAuthReposSubprocess,Oe as runAuthStatusSubprocess,h as runCloneSubprocess,cr as runDeviceFlowSubprocess,Ne as runWithMcpLogger,C as safeContentPath,y as safeSubdir,de as safetyCheckpoint,on as sanitizeClientName,o as saveInMemoryCheckpoint,en as saveVersion,re as seedBasenameIndex,se as serializeError,he as setActiveSpanAttributes,D as shadowGit,B as shutdownTelemetry,$ as spansCurrentPath,we as spansPreviousPath,br as spawnDetached,d as splitMarkdownBlocks,He as startWatcher,F as streamingProblemEvent,Le as swapContributors,qe as toBroadcasterKey,j as tracedAppendFileSync,Y as tracedLinkSync,Nn as tracedMkdir,W as tracedMkdirSync,tt as tracedRename,Ze as tracedRenameSync,at as tracedRmSync,ye as tracedRmdirSync,n as tracedUnlinkSync,At as tracedWriteFile,Kn as tracedWriteFileSync,vn as updateLastKnownHash,Dr as updateProcessLockPort,Er as updateServerLockPort,In as updateUiLockPort,Jt as validateAgentId,ft as validateCloneInputs,Cn as validateSkillZip,Vn as withSpan,xt as withSpanSync,ln as writeRootGitignoreForNewRepo,Zn as writeStateManifest,Et as writeTargetVersion,Ft as writeTracker};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{la as e}from"./dist-
|
|
1
|
+
import{la as e}from"./dist-BkOSFGR2.mjs";import{execFileSync as t}from"node:child_process";import{dirname as n,join as r}from"node:path";import{existsSync as i,mkdirSync as a,readFileSync as o,writeFileSync as s}from"node:fs";import{homedir as c}from"node:os";var l=e();const u=`open-knowledge`;var d=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(u,e).getPassword();return n==null?null:JSON.parse(n)}catch{return null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(u,e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(u,e).deletePassword()}catch{}}},f=class{backend=`file`;authFile;constructor(e){this.authFile=e??r(c(),`.ok`,`auth.yml`)}read(){if(!i(this.authFile))return{};try{return(0,l.parse)(o(this.authFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=n(this.authFile);i(t)||a(t,{recursive:!0,mode:448}),s(this.authFile,(0,l.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}};async function p(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(u,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
|
|
2
2
|
`),new d}catch{return process.stderr.write(`[auth] token storage: file (~/.ok/auth.yml)
|
|
3
3
|
`),new f(e)}}function m(e){let t=null;return function(){if(t)return t;let n=2e3;return t=(async()=>{let t=null,r=new Promise(r=>{t=setTimeout(()=>{process.stderr.write(`[auth] token storage: keyring init exceeded ${n}ms; falling back to file (~/.ok/auth.yml)\n`),r(new f(e))},n)});try{return await Promise.race([p(e),r])}catch{return new f(e)}finally{t!==null&&clearTimeout(t)}})(),t}}function h(e){let t=m(e);return{async get(e){let n=await(await t()).get(e);return n===null?null:{token:n.token}}}}function g(e){let t=m(e);return{backend:`file`,async get(e){return(await t()).get(e)},async set(e,n,r,i){return(await t()).set(e,n,r,i)},async clear(e){return(await t()).clear(e)}}}async function _(e,t){let n=[],r=new f(t);await r.get(e)!=null&&(await r.clear(e),n.push(`file`));try{let{Entry:t}=await import(`@napi-rs/keyring`);new t(u,`__probe__`);let r=new d;await r.get(e)!=null&&(await r.clear(e),n.push(`keychain`))}catch{}return{touched:n}}const v=[`/opt/homebrew/bin/gh`,`/usr/local/bin/gh`,`/opt/local/bin/gh`,`/snap/bin/gh`,`/usr/bin/gh`];function y(e,n={}){let r=n._exec??t,a=n._fileExists??i,o=[`auth`,`token`,...e?[`--hostname`,e]:[]],s=[`gh`,...v.filter(a)];for(let e of s)try{let t=r(e,o,{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3}).toString().trim();if(t.length>0)return{available:!0,token:t}}catch{}return{available:!1}}export{g as a,h as i,_ as n,p as r,y as t};
|
|
4
|
-
//# sourceMappingURL=gh-detect-
|
|
4
|
+
//# sourceMappingURL=gh-detect-CXkelKVd.mjs.map
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e,r as t,t as n}from"./gh-detect-
|
|
1
|
+
import{i as e,r as t,t as n}from"./gh-detect-CXkelKVd.mjs";import{_ as r,d as i,f as a,g as o,h as s,i as c,m as l,r as u,s as d,t as f,u as p,v as m,y as h}from"./init-DwLGKHOJ.mjs";import{i as g,n as _,r as v,t as y}from"./src-iCrNc821.mjs";import{n as b}from"./loader-DwAApXf7.mjs";import{n as x}from"./preview-DQUlTvw4.mjs";import{n as S,t as C}from"./mcp-migrate-event-BF8ILHwp.mjs";export{l as ALL_EDITOR_IDS,s as EDITOR_LABELS,o as EDITOR_TARGETS,f as LAUNCH_CONFIG_NAME,r as buildManagedServerEntry,C as buildMcpConfigMigrateEvent,u as classifyExistingMcpEntry,t as createTokenStore,n as detectGh,c as detectInstalledEditors,m as isEntryUpToDate,b as loadConfig,e as makeLazyProbeTokenStore,v as parseGitHubBlobUrl,g as parseGitUrl,x as previewContent,d as readExistingMcpEntry,h as resolveProjectRoot,p as scaffoldLaunchJson,S as truncatePriorEntry,_ as validateLocalFolderForShare,i as writeEditorMcpConfig,y as writeProjectAiIntegrations,a as writeUserMcpConfigs};
|