@dhzh/foundry 7.3.0 → 7.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{defineCommand as e,runMain as t,showUsage as n}from"citty";import r from"node:path";import i from"node:process";import{spawn as a}from"node:child_process";import{chmodSync as o,closeSync as s,createReadStream as c,createWriteStream as l,existsSync as u,fsyncSync as d,mkdirSync as f,openSync as p,readFileSync as m,readdirSync as h,renameSync as ee,rmSync as g,rmdirSync as te,statSync as _,watch as ne,writeFileSync as re}from"node:fs";import ie,{homedir as ae,tmpdir as oe}from"node:os";import{createCipheriv as se,createDecipheriv as ce,createHash as le,randomBytes as ue,randomUUID as v,scrypt as de}from"node:crypto";import{chmod as fe,cp as pe,link as me,mkdir as he,mkdtemp as ge,open as _e,readFile as ve,readdir as ye,rename as be,rm as y,stat as xe,writeFile as Se}from"node:fs/promises";import{fileURLToPath as Ce}from"node:url";import{Buffer as b}from"node:buffer";import{pipeline as x}from"node:stream/promises";import we from"yauzl";import Te from"yazl";import{Readable as Ee,Transform as De}from"node:stream";import{parse as Oe,stringify as ke}from"yaml";import{serve as Ae}from"@hono/node-server";import{serveStatic as je}from"@hono/node-server/serve-static";import{Hono as S}from"hono";import{StringDecoder as Me}from"node:string_decoder";import{createZstdDecompress as Ne}from"node:zlib";import{streamSSE as Pe}from"hono/streaming";import{FirecrawlClient as Fe}from"firecrawl";import{parse as Ie}from"tldts";import{createServer as Le}from"node:net";var Re=`7.3.0`,C=class extends Error{code;status;constructor(e,t,n){super(t),this.code=e,this.status=n,this.name=`AgentError`}};function ze(e){if(!Ve(e)||!Array.isArray(e.instructionIds))throw new C(`INVALID_AGENT_INPUT`,`instructionIds must be an array`,400);let t=e.instructionIds.map(e=>{if(typeof e!=`string`||!e.trim())throw new C(`INVALID_AGENT_INPUT`,`instructionIds must contain non-empty strings`,400);return e});if(new Set(t).size!==t.length)throw new C(`DUPLICATE_INSTRUCTION`,`An instruction cannot be added to the same agent twice`,400);return{instructionIds:t}}function Be(e){if(!Ve(e)||typeof e.enabled!=`boolean`)throw new C(`INVALID_AGENT_INPUT`,`enabled must be a boolean`,400);return{enabled:e.enabled}}function Ve(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const He=[`chatgpt`,`claude-code`];function Ue(e){return[{id:`chatgpt`,name:`ChatGPT`,icon:`openai`,instructionFile:`~/.codex/AGENTS.md`,filePath:r.join(e,`.codex`,`AGENTS.md`)},{id:`claude-code`,name:`Claude Code`,icon:`claudecode`,instructionFile:`~/.claude/CLAUDE.md`,filePath:r.join(e,`.claude`,`CLAUDE.md`)}]}function We(e){let t=i.platform===`darwin`?`open`:i.platform===`win32`?`explorer`:`xdg-open`,n=a(t,[e],{detached:!0,stdio:`ignore`});n.on(`error`,t=>{console.error(`Unable to open ${e}: ${t.message}`)}),n.unref()}function Ge(){return r.join(ie.homedir(),`.foundry`)}function Ke(){let e=Ge();return f(e,{recursive:!0,mode:448}),i.platform!==`win32`&&o(e,448),e}const qe=[`system`,`light`,`dark`],Je=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],Ye=[`YYYY-MM-DD HH:mm:ss`,`YYYY-MM-DD`,`YYYY/MM/DD HH:mm:ss`,`DD/MM/YYYY HH:mm:ss`,`MM/DD/YYYY hh:mm:ss A`,`HH:mm:ss`],Xe=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],Ze=[`firecrawl`],w=`data/foundry.json`,Qe=`settings.changed`,$e=[`agents`,`claude`],T={workspace:{appearance:{"color-theme":`system`},"language-region":{language:`system`,"time-format":`YYYY-MM-DD HH:mm:ss`,"time-zone":`America/Los_Angeles`}},features:{library:{captures:{fetcher:null,maxAttempts:1,fetchConcurrency:2,firecrawl:{apiKey:``}}}}};function et(e){let t=O(e)?e:{},n=O(t.workspace)?t.workspace:{},r=O(n.appearance)?n.appearance:{},i=O(n[`language-region`])?n[`language-region`]:{},a=O(t.features)?t.features:{},o=O(a.library)?a.library:{},s=O(o.captures)?o.captures:{},c=O(s.firecrawl)?s.firecrawl:{};return{workspace:{appearance:{"color-theme":st(r[`color-theme`],qe,T.workspace.appearance[`color-theme`])},"language-region":{language:st(i.language,Je,T.workspace[`language-region`].language),"time-format":st(i[`time-format`],Ye,T.workspace[`language-region`][`time-format`]),"time-zone":st(i[`time-zone`],Xe,T.workspace[`language-region`][`time-zone`])}},features:{...a,library:{...o,captures:{fetcher:at(s.fetcher),maxAttempts:ct(s.maxAttempts,10,1),fetchConcurrency:ct(s.fetchConcurrency,5,2),firecrawl:{apiKey:dt(c.apiKey)}}}}}}function tt(e){if(!O(e))throw new E(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=D(e.theme,qe,`theme`)),`language`in e&&(t.language=D(e.language,Je,`language`)),`timeFormat`in e&&(t.timeFormat=D(e.timeFormat,Ye,`timeFormat`)),`timezone`in e&&(t.timezone=D(e.timezone,Xe,`timezone`)),`captures`in e&&(t.captures=it(e.captures)),t}function nt(e,t){let n=e.features.library.captures,r=t.captures;return{workspace:{appearance:{"color-theme":t.theme??e.workspace.appearance[`color-theme`]},"language-region":{language:t.language??e.workspace[`language-region`].language,"time-format":t.timeFormat??e.workspace[`language-region`][`time-format`],"time-zone":t.timezone??e.workspace[`language-region`][`time-zone`]}},features:{...e.features,library:{...e.features.library,captures:{...n,fetcher:r?.fetcher===void 0?n.fetcher:r.fetcher,maxAttempts:r?.maxAttempts??n.maxAttempts,fetchConcurrency:r?.fetchConcurrency??n.fetchConcurrency,firecrawl:{apiKey:r?.firecrawlApiKey??n.firecrawl.apiKey}}}}}}function rt(e){let t=e.features.library.captures;return{workspace:e.workspace,features:{...e.features,library:{...e.features.library,captures:{fetcher:t.fetcher,maxAttempts:t.maxAttempts,fetchConcurrency:t.fetchConcurrency,firecrawl:{apiKey:t.firecrawl.apiKey}}}}}}var E=class extends Error{code=`INVALID_SETTINGS_INPUT`;constructor(e){super(e),this.name=`SettingsInputError`}};function it(e){if(!O(e))throw new E(`captures must be an object`);let t={};return`fetcher`in e&&(t.fetcher=e.fetcher===null?null:D(e.fetcher,Ze,`captures.fetcher`)),`maxAttempts`in e&&(t.maxAttempts=lt(e.maxAttempts,10,`captures.maxAttempts`)),`fetchConcurrency`in e&&(t.fetchConcurrency=lt(e.fetchConcurrency,5,`captures.fetchConcurrency`)),`firecrawlApiKey`in e&&(t.firecrawlApiKey=ut(e.firecrawlApiKey,`captures.firecrawlApiKey`)),t}function at(e){return ot(e,Ze)}function ot(e,t){return typeof e==`string`&&t.includes(e)?e:null}function st(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function D(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new E(`Invalid ${n}`);return e}function ct(e,t,n){return typeof e==`number`&&Number.isSafeInteger(e)?Math.min(t,Math.max(1,e)):n}function lt(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1||e>t)throw new E(`${n} must be an integer from 1 to ${t}`);return e}function ut(e,t){if(typeof e!=`string`)throw new E(`${t} must be a string`);return e.trim()}function dt(e){return typeof e==`string`?e:``}function O(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ft(e){return e.readSettings()}function pt(e){return rt(ft(e))}function mt(e,t){return t.transaction(()=>{let n=nt(ft(t),e);return t.setSettings(n),rt(n)})}var ht=class{storage;configFolder;openFolder;constructor(e,t=Ge(),n=We){this.storage=e,this.configFolder=t,this.openFolder=n}read(){return{...pt(this.storage),configFolder:this.configFolder}}update(e){return{...mt(e,this.storage),configFolder:this.configFolder}}openConfigFolder(){return this.openFolder(this.configFolder),{configFolder:this.configFolder}}};const gt=r.dirname(Ce(import.meta.url)),k=`foundry`;var _t=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=ae()}={}){this.configuredSkillRoot=e,this.homeDirectory=r.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??vt();if(!u(r.join(t,`SKILL.md`)))throw new A(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);let n=this.getTargetParent(e),i=r.join(n,k),a=r.join(n,`.${k}-${v()}.tmp`),o=r.join(n,`.${k}-${v()}.backup`);try{return await he(n,{recursive:!0}),await pe(t,a,{recursive:!0,errorOnExist:!0}),await yt(a,i,o),{target:e,destination:i}}catch(e){throw await y(a,{recursive:!0,force:!0}),e instanceof A?e:new A(`SKILL_COPY_FAILED`,`Unable to copy the Foundry skill`,{cause:e})}}getTargetParent(e){return r.join(this.homeDirectory,e===`agents`?`.agents`:`.claude`,`skills`)}getTargets(){return{targets:[`agents`,`claude`].map(e=>({target:e,destination:r.join(this.getTargetParent(e),k)}))}}async copyToTargets(e){return{installed:await Array.fromAsync(e,e=>this.copyToTarget(e))}}},A=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BundledSkillCopyError`}};function vt(){let e=[r.resolve(gt,`skills`,k),r.resolve(gt,`..`,`..`,`..`,`skills`,k),r.resolve(i.cwd(),`skills`,k)].find(e=>u(r.join(e,`SKILL.md`)));if(!e)throw new A(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);return e}async function yt(e,t,n){let r=u(t);r&&await be(t,n);try{await be(e,t),r&&await y(n,{recursive:!0,force:!0})}catch(e){throw r&&!u(t)&&u(n)&&await be(n,t),e}}const bt=`manifest.json`,xt=/* @__PURE__ */ new Set([bt,w]);async function St(e,t){let n=new Te.ZipFile;for(let t of e)n.addFile(t.filePath,t.entryPath,{compress:!0});n.end(),await x(n.outputStream,l(t,{mode:384}))}async function Ct(e,t){let n=await wt(e),i=/* @__PURE__ */ new Map;try{await new Promise((e,a)=>{let o=e=>{a(e instanceof Error?e:Error(String(e)))},s=async e=>{if(!xt.has(e.fileName))throw Error(`The Foundry archive contains an unexpected file`);if(e.fileName.endsWith(`/`)||i.has(e.fileName))throw Error(`The Foundry archive contains an invalid file`);let a=r.join(t,e.fileName);await he(r.dirname(a),{recursive:!0,mode:448}),await x(await Tt(n,e),l(a,{mode:384})),i.set(e.fileName,a),n.readEntry()};n.on(`error`,o),n.on(`end`,e),n.on(`entry`,e=>{s(e).catch(o)}),n.readEntry()})}catch(e){throw await y(t,{recursive:!0,force:!0}),e}finally{n.close()}if(!i.has(bt)||!i.has(`data/foundry.json`))throw await y(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(i)}function wt(e){return new Promise((t,n)=>{we.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function Tt(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}var Et=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BackupCryptoError`}};const j=b.from(`FOUNDRYX`,`ascii`),M=`aes-256-gcm`,Dt=`scrypt`,N={N:131072,r:8,p:1};async function Ot(e,t,n){let r=ue(16),i=ue(12),a={version:1,cipher:M,kdf:{name:Dt,salt:r.toString(`base64`),...N,keyLength:32},nonce:i.toString(`base64`)},o=b.from(JSON.stringify(a),`utf8`),s=At(o.byteLength),u=b.concat([s,o]),d=await jt(n,r,N);try{let n=await _e(t,`w`,384);try{await n.write(u)}finally{await n.close()}await x(c(e),Mt(d,i,u),l(t,{flags:`r+`,mode:384,start:u.byteLength})),await fe(t,384)}catch(e){throw await y(t,{force:!0}),new Et(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function kt(e,t,n){let r;try{let i=(await xe(e)).size;if(i<=29)throw Error(`The export file is incomplete`);let a=await _e(e,`r`),o,s,u;try{if(o=await Ft(a,13,0),!o.subarray(0,j.byteLength).equals(j))throw Error(`The export file signature is invalid`);if(o.readUInt8(j.byteLength)!==1)throw Error(`The export envelope version is unsupported`);let e=o.readUInt32BE(j.byteLength+1);if(e===0||e>65536)throw Error(`The export header is invalid`);if(i<=13+e+16)throw Error(`The export file is incomplete`);s=await Ft(a,e,13),u=await Ft(a,16,i-16)}finally{await a.close()}let d=Pt(JSON.parse(s.toString(`utf8`)));r=await jt(n,d.salt,d.header.kdf);let f=b.concat([o,s]);await x(c(e,{start:13+s.byteLength,end:i-16-1}),Nt(r,d.nonce,f,u),l(t,{mode:384})),await fe(t,384)}catch(e){throw await y(t,{force:!0}),e instanceof Et?e:new Et(Lt(e)?`IO_ERROR`:`INVALID_PASSPHRASE`,Lt(e)?`Unable to read or decrypt the backup file`:`The passphrase is incorrect or the export file is corrupted`,{cause:e})}finally{r?.fill(0)}}function At(e){let t=b.alloc(13);return j.copy(t,0),t.writeUInt8(1,j.byteLength),t.writeUInt32BE(e,j.byteLength+1),t}function jt(e,t,n){return new Promise((r,i)=>{de(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function Mt(e,t,n){let r=se(M,e,t,{authTagLength:16});return r.setAAD(n),new De({transform(e,t,n){try{n(null,r.update(e))}catch(e){n(e instanceof Error?e:Error(String(e)))}},flush(e){try{e(null,b.concat([r.final(),r.getAuthTag()]))}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function Nt(e,t,n,r){let i=ce(M,e,t,{authTagLength:16});return i.setAAD(n),new De({transform(e,t,n){try{n(null,i.update(e))}catch(e){n(e instanceof Error?e:Error(String(e)))}},flush(e){try{i.setAuthTag(r),e(null,i.final())}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function Pt(e){if(!It(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==M||!It(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==Dt||typeof t.salt!=`string`||t.N!==N.N||t.r!==N.r||t.p!==N.p||t.keyLength!==32||typeof e.nonce!=`string`)throw Error(`Invalid export key derivation parameters`);let n=b.from(t.salt,`base64`),r=b.from(e.nonce,`base64`);if(n.byteLength!==16||r.byteLength!==12)throw Error(`Invalid export encryption parameters`);return{header:{version:1,cipher:M,kdf:{name:Dt,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function Ft(e,t,n){let r=b.alloc(t),{bytesRead:i}=await e.read(r,0,t,n);if(i!==t)throw Error(`Unexpected end of export file`);return r}function It(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Lt(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&/^E[A-Z]+$/u.test(e.code)}async function Rt(e){try{await y(e,{recursive:!0,force:!0})}catch{console.error(`Unable to remove backup temporary files`)}}function zt(e){f(e,{recursive:!0,mode:448}),i.platform!==`win32`&&o(e,448)}function P(e){if(i.platform===`win32`)return;let t=p(e,`r`);try{d(t)}finally{s(t)}}function Bt(e,t){Vt(e,`${JSON.stringify(t,null,2)}\n`)}function Vt(e,t){zt(r.dirname(e));let n=`${e}.${v()}.tmp`;try{let i=p(n,`wx`,384);try{re(i,t),d(i)}finally{s(i)}ee(n,e),P(r.dirname(e))}finally{g(n,{force:!0})}}const F=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;var I=class extends Error{code=`INVALID_INSTRUCTION_INPUT`;constructor(e){super(e),this.name=`InstructionInputError`}},Ht=class extends Error{code=`INSTRUCTION_NOT_FOUND`;constructor(e){super(`Instruction not found: ${e}`),this.name=`InstructionNotFoundError`}};function Ut(e){if(!Wt(e))throw new I(`Instruction input must be an object`);if(typeof e.name!=`string`)throw new I(`name is required`);let t=e.name.trim();if(!t)throw new I(`name is required`);if(t.length>200)throw new I(`name must be at most 200 characters`);if(typeof e.content!=`string`||!e.content.trim())throw new I(`content is required`);if(e.content.length>1e6)throw new I(`content must be at most 1000000 characters`);return{name:t,content:e.content}}function Wt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Gt=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;function Kt(e,t){let n=Date.now(),r={id:v(),name:e.name,content:e.content,createdAt:n,updatedAt:n},i=an(t,r.id),a=Zt(r);return t.transaction(()=>{Vt(i,a)}),r}function qt(e){let t=rn(e),n;try{n=h(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>e.name)}catch(e){if(on(e))return[];throw e}return n.map(e=>$t(r.join(t,e),e)).toSorted((e,t)=>t.updatedAt-e.updatedAt)}function Jt(e,t){if(!F.test(e))return;let n=`${e}.md`;try{return $t(r.join(rn(t),n),n)}catch(e){if(on(e))return;throw e}}function Yt(e,t,n){let r=Jt(e,n);if(!r)return;let i={...r,name:t.name,content:t.content,updatedAt:Date.now()};return n.transaction(()=>{Vt(an(n,i.id),Zt(i))}),i}function Xt(e,t){if(!F.test(e))return`missing`;let n=rn(t),i=r.join(n,`${e}.md`);return t.transaction(()=>{try{return g(i),P(n),`removed`}catch(e){if(on(e))return`missing`;throw e}})}function Zt(e){return`---\n${ke({id:e.id,name:e.name,createdAt:e.createdAt,updatedAt:e.updatedAt}).trimEnd()}\n---\n\n${e.content}`}function Qt(e,t){let n=Gt.exec(e);if(!n)throw L(t);let r=en(n[1]);if(`${r.id}.md`!==t)throw L(t);let i=e.slice(n[0].length);return i.startsWith(`\r
|
|
2
|
+
import{defineCommand as e,runMain as t,showUsage as n}from"citty";import r from"node:path";import i from"node:process";import{spawn as a}from"node:child_process";import{chmodSync as o,closeSync as s,createReadStream as c,createWriteStream as l,existsSync as u,fsyncSync as d,mkdirSync as f,openSync as p,readFileSync as m,readdirSync as h,renameSync as ee,rmSync as g,rmdirSync as te,statSync as _,watch as ne,writeFileSync as re}from"node:fs";import ie,{homedir as ae,tmpdir as oe}from"node:os";import{createCipheriv as se,createDecipheriv as ce,createHash as le,randomBytes as ue,randomUUID as v,scrypt as de}from"node:crypto";import{chmod as fe,cp as pe,link as me,mkdir as he,mkdtemp as ge,open as _e,readFile as ve,readdir as ye,rename as be,rm as y,stat as xe,writeFile as Se}from"node:fs/promises";import{fileURLToPath as Ce}from"node:url";import{Buffer as b}from"node:buffer";import{pipeline as x}from"node:stream/promises";import we from"yauzl";import Te from"yazl";import{Readable as Ee,Transform as De}from"node:stream";import{parse as Oe,stringify as ke}from"yaml";import{serve as Ae}from"@hono/node-server";import{serveStatic as je}from"@hono/node-server/serve-static";import{Hono as S}from"hono";import{StringDecoder as Me}from"node:string_decoder";import{createZstdDecompress as Ne}from"node:zlib";import{streamSSE as Pe}from"hono/streaming";import{FirecrawlClient as Fe}from"firecrawl";import{parse as Ie}from"tldts";import{createServer as Le}from"node:net";var Re=`7.3.1`,C=class extends Error{code;status;constructor(e,t,n){super(t),this.code=e,this.status=n,this.name=`AgentError`}};function ze(e){if(!Ve(e)||!Array.isArray(e.instructionIds))throw new C(`INVALID_AGENT_INPUT`,`instructionIds must be an array`,400);let t=e.instructionIds.map(e=>{if(typeof e!=`string`||!e.trim())throw new C(`INVALID_AGENT_INPUT`,`instructionIds must contain non-empty strings`,400);return e});if(new Set(t).size!==t.length)throw new C(`DUPLICATE_INSTRUCTION`,`An instruction cannot be added to the same agent twice`,400);return{instructionIds:t}}function Be(e){if(!Ve(e)||typeof e.enabled!=`boolean`)throw new C(`INVALID_AGENT_INPUT`,`enabled must be a boolean`,400);return{enabled:e.enabled}}function Ve(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const He=[`chatgpt`,`claude-code`];function Ue(e){return[{id:`chatgpt`,name:`ChatGPT`,icon:`openai`,instructionFile:`~/.codex/AGENTS.md`,filePath:r.join(e,`.codex`,`AGENTS.md`)},{id:`claude-code`,name:`Claude Code`,icon:`claudecode`,instructionFile:`~/.claude/CLAUDE.md`,filePath:r.join(e,`.claude`,`CLAUDE.md`)}]}function We(e){let t=i.platform===`darwin`?`open`:i.platform===`win32`?`explorer`:`xdg-open`,n=a(t,[e],{detached:!0,stdio:`ignore`});n.on(`error`,t=>{console.error(`Unable to open ${e}: ${t.message}`)}),n.unref()}function Ge(){return r.join(ie.homedir(),`.foundry`)}function Ke(){let e=Ge();return f(e,{recursive:!0,mode:448}),i.platform!==`win32`&&o(e,448),e}const qe=[`system`,`light`,`dark`],Je=[`system`,`en-US`,`zh-CN`,`zh-TW`,`ja-JP`],Ye=[`YYYY-MM-DD HH:mm:ss`,`YYYY-MM-DD`,`YYYY/MM/DD HH:mm:ss`,`DD/MM/YYYY HH:mm:ss`,`MM/DD/YYYY hh:mm:ss A`,`HH:mm:ss`],Xe=[`America/Los_Angeles`,`America/New_York`,`Asia/Shanghai`,`Asia/Taipei`,`Asia/Tokyo`,`UTC`],Ze=[`firecrawl`],w=`data/foundry.json`,Qe=`settings.changed`,$e=[`agents`,`claude`],T={workspace:{appearance:{"color-theme":`system`},"language-region":{language:`system`,"time-format":`YYYY-MM-DD HH:mm:ss`,"time-zone":`America/Los_Angeles`}},features:{library:{captures:{fetcher:null,maxAttempts:1,fetchConcurrency:2,firecrawl:{apiKey:``}}}}};function et(e){let t=O(e)?e:{},n=O(t.workspace)?t.workspace:{},r=O(n.appearance)?n.appearance:{},i=O(n[`language-region`])?n[`language-region`]:{},a=O(t.features)?t.features:{},o=O(a.library)?a.library:{},s=O(o.captures)?o.captures:{},c=O(s.firecrawl)?s.firecrawl:{};return{workspace:{appearance:{"color-theme":st(r[`color-theme`],qe,T.workspace.appearance[`color-theme`])},"language-region":{language:st(i.language,Je,T.workspace[`language-region`].language),"time-format":st(i[`time-format`],Ye,T.workspace[`language-region`][`time-format`]),"time-zone":st(i[`time-zone`],Xe,T.workspace[`language-region`][`time-zone`])}},features:{...a,library:{...o,captures:{fetcher:at(s.fetcher),maxAttempts:ct(s.maxAttempts,10,1),fetchConcurrency:ct(s.fetchConcurrency,5,2),firecrawl:{apiKey:dt(c.apiKey)}}}}}}function tt(e){if(!O(e))throw new E(`Settings patch must be an object`);let t={};return`theme`in e&&(t.theme=D(e.theme,qe,`theme`)),`language`in e&&(t.language=D(e.language,Je,`language`)),`timeFormat`in e&&(t.timeFormat=D(e.timeFormat,Ye,`timeFormat`)),`timezone`in e&&(t.timezone=D(e.timezone,Xe,`timezone`)),`captures`in e&&(t.captures=it(e.captures)),t}function nt(e,t){let n=e.features.library.captures,r=t.captures;return{workspace:{appearance:{"color-theme":t.theme??e.workspace.appearance[`color-theme`]},"language-region":{language:t.language??e.workspace[`language-region`].language,"time-format":t.timeFormat??e.workspace[`language-region`][`time-format`],"time-zone":t.timezone??e.workspace[`language-region`][`time-zone`]}},features:{...e.features,library:{...e.features.library,captures:{...n,fetcher:r?.fetcher===void 0?n.fetcher:r.fetcher,maxAttempts:r?.maxAttempts??n.maxAttempts,fetchConcurrency:r?.fetchConcurrency??n.fetchConcurrency,firecrawl:{apiKey:r?.firecrawlApiKey??n.firecrawl.apiKey}}}}}}function rt(e){let t=e.features.library.captures;return{workspace:e.workspace,features:{...e.features,library:{...e.features.library,captures:{fetcher:t.fetcher,maxAttempts:t.maxAttempts,fetchConcurrency:t.fetchConcurrency,firecrawl:{apiKey:t.firecrawl.apiKey}}}}}}var E=class extends Error{code=`INVALID_SETTINGS_INPUT`;constructor(e){super(e),this.name=`SettingsInputError`}};function it(e){if(!O(e))throw new E(`captures must be an object`);let t={};return`fetcher`in e&&(t.fetcher=e.fetcher===null?null:D(e.fetcher,Ze,`captures.fetcher`)),`maxAttempts`in e&&(t.maxAttempts=lt(e.maxAttempts,10,`captures.maxAttempts`)),`fetchConcurrency`in e&&(t.fetchConcurrency=lt(e.fetchConcurrency,5,`captures.fetchConcurrency`)),`firecrawlApiKey`in e&&(t.firecrawlApiKey=ut(e.firecrawlApiKey,`captures.firecrawlApiKey`)),t}function at(e){return ot(e,Ze)}function ot(e,t){return typeof e==`string`&&t.includes(e)?e:null}function st(e,t,n){return typeof e==`string`&&t.includes(e)?e:n}function D(e,t,n){if(typeof e!=`string`||!t.includes(e))throw new E(`Invalid ${n}`);return e}function ct(e,t,n){return typeof e==`number`&&Number.isSafeInteger(e)?Math.min(t,Math.max(1,e)):n}function lt(e,t,n){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1||e>t)throw new E(`${n} must be an integer from 1 to ${t}`);return e}function ut(e,t){if(typeof e!=`string`)throw new E(`${t} must be a string`);return e.trim()}function dt(e){return typeof e==`string`?e:``}function O(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ft(e){return e.readSettings()}function pt(e){return rt(ft(e))}function mt(e,t){return t.transaction(()=>{let n=nt(ft(t),e);return t.setSettings(n),rt(n)})}var ht=class{storage;configFolder;openFolder;constructor(e,t=Ge(),n=We){this.storage=e,this.configFolder=t,this.openFolder=n}read(){return{...pt(this.storage),configFolder:this.configFolder}}update(e){return{...mt(e,this.storage),configFolder:this.configFolder}}openConfigFolder(){return this.openFolder(this.configFolder),{configFolder:this.configFolder}}};const gt=r.dirname(Ce(import.meta.url)),k=`foundry`;var _t=class{configuredSkillRoot;homeDirectory;constructor({skillRoot:e,homeDirectory:t=ae()}={}){this.configuredSkillRoot=e,this.homeDirectory=r.resolve(t)}async copyToTarget(e){let t=this.configuredSkillRoot??vt();if(!u(r.join(t,`SKILL.md`)))throw new A(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);let n=this.getTargetParent(e),i=r.join(n,k),a=r.join(n,`.${k}-${v()}.tmp`),o=r.join(n,`.${k}-${v()}.backup`);try{return await he(n,{recursive:!0}),await pe(t,a,{recursive:!0,errorOnExist:!0}),await yt(a,i,o),{target:e,destination:i}}catch(e){throw await y(a,{recursive:!0,force:!0}),e instanceof A?e:new A(`SKILL_COPY_FAILED`,`Unable to copy the Foundry skill`,{cause:e})}}getTargetParent(e){return r.join(this.homeDirectory,e===`agents`?`.agents`:`.claude`,`skills`)}getTargets(){return{targets:[`agents`,`claude`].map(e=>({target:e,destination:r.join(this.getTargetParent(e),k)}))}}async copyToTargets(e){return{installed:await Array.fromAsync(e,e=>this.copyToTarget(e))}}},A=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BundledSkillCopyError`}};function vt(){let e=[r.resolve(gt,`skills`,k),r.resolve(gt,`..`,`..`,`..`,`skills`,k),r.resolve(i.cwd(),`skills`,k)].find(e=>u(r.join(e,`SKILL.md`)));if(!e)throw new A(`SKILL_NOT_FOUND`,`The bundled Foundry skill was not found`);return e}async function yt(e,t,n){let r=u(t);r&&await be(t,n);try{await be(e,t),r&&await y(n,{recursive:!0,force:!0})}catch(e){throw r&&!u(t)&&u(n)&&await be(n,t),e}}const bt=`manifest.json`,xt=/* @__PURE__ */ new Set([bt,w]);async function St(e,t){let n=new Te.ZipFile;for(let t of e)n.addFile(t.filePath,t.entryPath,{compress:!0});n.end(),await x(n.outputStream,l(t,{mode:384}))}async function Ct(e,t){let n=await wt(e),i=/* @__PURE__ */ new Map;try{await new Promise((e,a)=>{let o=e=>{a(e instanceof Error?e:Error(String(e)))},s=async e=>{if(!xt.has(e.fileName))throw Error(`The Foundry archive contains an unexpected file`);if(e.fileName.endsWith(`/`)||i.has(e.fileName))throw Error(`The Foundry archive contains an invalid file`);let a=r.join(t,e.fileName);await he(r.dirname(a),{recursive:!0,mode:448}),await x(await Tt(n,e),l(a,{mode:384})),i.set(e.fileName,a),n.readEntry()};n.on(`error`,o),n.on(`end`,e),n.on(`entry`,e=>{s(e).catch(o)}),n.readEntry()})}catch(e){throw await y(t,{recursive:!0,force:!0}),e}finally{n.close()}if(!i.has(bt)||!i.has(`data/foundry.json`))throw await y(t,{recursive:!0,force:!0}),Error(`The Foundry archive is incomplete`);return Object.fromEntries(i)}function wt(e){return new Promise((t,n)=>{we.open(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0},(e,r)=>{e?n(e):t(r)})})}function Tt(e,t){return new Promise((n,r)=>{e.openReadStream(t,(e,t)=>{e?r(e):n(t)})})}var Et=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=`BackupCryptoError`}};const j=b.from(`FOUNDRYX`,`ascii`),M=`aes-256-gcm`,Dt=`scrypt`,N={N:131072,r:8,p:1};async function Ot(e,t,n){let r=ue(16),i=ue(12),a={version:1,cipher:M,kdf:{name:Dt,salt:r.toString(`base64`),...N,keyLength:32},nonce:i.toString(`base64`)},o=b.from(JSON.stringify(a),`utf8`),s=At(o.byteLength),u=b.concat([s,o]),d=await jt(n,r,N);try{let n=await _e(t,`w`,384);try{await n.write(u)}finally{await n.close()}await x(c(e),Mt(d,i,u),l(t,{flags:`r+`,mode:384,start:u.byteLength})),await fe(t,384)}catch(e){throw await y(t,{force:!0}),new Et(`IO_ERROR`,`Unable to encrypt the Foundry export`,{cause:e})}finally{d.fill(0)}}async function kt(e,t,n){let r;try{let i=(await xe(e)).size;if(i<=29)throw Error(`The export file is incomplete`);let a=await _e(e,`r`),o,s,u;try{if(o=await Ft(a,13,0),!o.subarray(0,j.byteLength).equals(j))throw Error(`The export file signature is invalid`);if(o.readUInt8(j.byteLength)!==1)throw Error(`The export envelope version is unsupported`);let e=o.readUInt32BE(j.byteLength+1);if(e===0||e>65536)throw Error(`The export header is invalid`);if(i<=13+e+16)throw Error(`The export file is incomplete`);s=await Ft(a,e,13),u=await Ft(a,16,i-16)}finally{await a.close()}let d=Pt(JSON.parse(s.toString(`utf8`)));r=await jt(n,d.salt,d.header.kdf);let f=b.concat([o,s]);await x(c(e,{start:13+s.byteLength,end:i-16-1}),Nt(r,d.nonce,f,u),l(t,{mode:384})),await fe(t,384)}catch(e){throw await y(t,{force:!0}),e instanceof Et?e:new Et(Lt(e)?`IO_ERROR`:`INVALID_PASSPHRASE`,Lt(e)?`Unable to read or decrypt the backup file`:`The passphrase is incorrect or the export file is corrupted`,{cause:e})}finally{r?.fill(0)}}function At(e){let t=b.alloc(13);return j.copy(t,0),t.writeUInt8(1,j.byteLength),t.writeUInt32BE(e,j.byteLength+1),t}function jt(e,t,n){return new Promise((r,i)=>{de(e,t,32,{...n,maxmem:Math.max(67108864,256*n.N*n.r)},(e,t)=>{e?i(e):r(t)})})}function Mt(e,t,n){let r=se(M,e,t,{authTagLength:16});return r.setAAD(n),new De({transform(e,t,n){try{n(null,r.update(e))}catch(e){n(e instanceof Error?e:Error(String(e)))}},flush(e){try{e(null,b.concat([r.final(),r.getAuthTag()]))}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function Nt(e,t,n,r){let i=ce(M,e,t,{authTagLength:16});return i.setAAD(n),new De({transform(e,t,n){try{n(null,i.update(e))}catch(e){n(e instanceof Error?e:Error(String(e)))}},flush(e){try{i.setAuthTag(r),e(null,i.final())}catch(t){e(t instanceof Error?t:Error(String(t)))}}})}function Pt(e){if(!It(e)||e.version!==1)throw Error(`Unsupported export envelope`);if(e.cipher!==M||!It(e.kdf))throw Error(`Unsupported export encryption`);let t=e.kdf;if(t.name!==Dt||typeof t.salt!=`string`||t.N!==N.N||t.r!==N.r||t.p!==N.p||t.keyLength!==32||typeof e.nonce!=`string`)throw Error(`Invalid export key derivation parameters`);let n=b.from(t.salt,`base64`),r=b.from(e.nonce,`base64`);if(n.byteLength!==16||r.byteLength!==12)throw Error(`Invalid export encryption parameters`);return{header:{version:1,cipher:M,kdf:{name:Dt,salt:t.salt,N:t.N,r:t.r,p:t.p,keyLength:t.keyLength},nonce:e.nonce},salt:n,nonce:r}}async function Ft(e,t,n){let r=b.alloc(t),{bytesRead:i}=await e.read(r,0,t,n);if(i!==t)throw Error(`Unexpected end of export file`);return r}function It(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Lt(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&/^E[A-Z]+$/u.test(e.code)}async function Rt(e){try{await y(e,{recursive:!0,force:!0})}catch{console.error(`Unable to remove backup temporary files`)}}function zt(e){f(e,{recursive:!0,mode:448}),i.platform!==`win32`&&o(e,448)}function P(e){if(i.platform===`win32`)return;let t=p(e,`r`);try{d(t)}finally{s(t)}}function Bt(e,t){Vt(e,`${JSON.stringify(t,null,2)}\n`)}function Vt(e,t){zt(r.dirname(e));let n=`${e}.${v()}.tmp`;try{let i=p(n,`wx`,384);try{re(i,t),d(i)}finally{s(i)}ee(n,e),P(r.dirname(e))}finally{g(n,{force:!0})}}const F=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;var I=class extends Error{code=`INVALID_INSTRUCTION_INPUT`;constructor(e){super(e),this.name=`InstructionInputError`}},Ht=class extends Error{code=`INSTRUCTION_NOT_FOUND`;constructor(e){super(`Instruction not found: ${e}`),this.name=`InstructionNotFoundError`}};function Ut(e){if(!Wt(e))throw new I(`Instruction input must be an object`);if(typeof e.name!=`string`)throw new I(`name is required`);let t=e.name.trim();if(!t)throw new I(`name is required`);if(t.length>200)throw new I(`name must be at most 200 characters`);if(typeof e.content!=`string`||!e.content.trim())throw new I(`content is required`);if(e.content.length>1e6)throw new I(`content must be at most 1000000 characters`);return{name:t,content:e.content}}function Wt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Gt=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;function Kt(e,t){let n=Date.now(),r={id:v(),name:e.name,content:e.content,createdAt:n,updatedAt:n},i=an(t,r.id),a=Zt(r);return t.transaction(()=>{Vt(i,a)}),r}function qt(e){let t=rn(e),n;try{n=h(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>e.name)}catch(e){if(on(e))return[];throw e}return n.map(e=>$t(r.join(t,e),e)).toSorted((e,t)=>t.updatedAt-e.updatedAt)}function Jt(e,t){if(!F.test(e))return;let n=`${e}.md`;try{return $t(r.join(rn(t),n),n)}catch(e){if(on(e))return;throw e}}function Yt(e,t,n){let r=Jt(e,n);if(!r)return;let i={...r,name:t.name,content:t.content,updatedAt:Date.now()};return n.transaction(()=>{Vt(an(n,i.id),Zt(i))}),i}function Xt(e,t){if(!F.test(e))return`missing`;let n=rn(t),i=r.join(n,`${e}.md`);return t.transaction(()=>{try{return g(i),P(n),`removed`}catch(e){if(on(e))return`missing`;throw e}})}function Zt(e){return`---\n${ke({id:e.id,name:e.name,createdAt:e.createdAt,updatedAt:e.updatedAt}).trimEnd()}\n---\n\n${e.content}`}function Qt(e,t){let n=Gt.exec(e);if(!n)throw L(t);let r=en(n[1]);if(`${r.id}.md`!==t)throw L(t);let i=e.slice(n[0].length);return i.startsWith(`\r
|
|
3
3
|
`)?i=i.slice(2):i.startsWith(`
|
|
4
4
|
`)&&(i=i.slice(1)),{...r,content:i}}function $t(e,t){return Qt(m(e,`utf8`),t)}function en(e){let t;try{t=Oe(e)}catch{throw L(`frontmatter`)}if(!sn(t))throw L(`frontmatter`);let n=tn(t.id),r=tn(t.name);if(!r||r.length>200||!F.test(n))throw L(`frontmatter`);return{id:n,name:r,createdAt:nn(t.createdAt),updatedAt:nn(t.updatedAt)}}function tn(e){return typeof e==`string`?e:``}function nn(e){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw L(`frontmatter`);return e}function rn(e){return r.join(e.path,`instructions`)}function an(e,t){if(!F.test(t))throw Error(`Invalid instruction ID`);return r.join(rn(e),`${t}.md`)}function L(e){return/* @__PURE__ */ Error(`Invalid instruction file: ${e}`)}function on(e){return e instanceof Error&&Reflect.get(e,`code`)===`ENOENT`}function sn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cn(e){return e.transaction(()=>{let t=new Set(He);return{settings:e.readSettings(),instructions:qt(e),agents:e.all(`agents`).filter(({id:e})=>t.has(e)).toSorted((e,t)=>e.id.localeCompare(t.id))}})}var ln=class{storage;constructor(e){this.storage=e}async createExport(e){let t=cn(this.storage),n=await ge(r.join(oe(),`foundry-export-`));try{let i=(/* @__PURE__ */ new Date()).toISOString(),a=JSON.stringify(t,null,2),o=r.join(n,`foundry.json`),s=r.join(n,`manifest.json`),c=r.join(n,`foundry.zip`),l=r.join(n,`foundry.foundry-backup`),u={format:`foundry.data`,archiveVersion:2,appVersion:Re,createdAt:i,data:{path:w,bytes:b.byteLength(a,`utf8`),sha256:le(`sha256`).update(a).digest(`hex`)}};return await Se(o,a,{mode:384}),await Se(s,JSON.stringify(u,null,2),{mode:384}),await St([{entryPath:`manifest.json`,filePath:s},{entryPath:w,filePath:o}],c),await Ot(c,l,e),{fileName:`foundry-${i.replaceAll(`:`,`-`)}.foundry-backup`,contents:await ve(l)}}finally{await Rt(n)}}},R=class extends Error{code;constructor(e,t){super(t),this.code=e}};function z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function un(e){if(!z(e)||e.format!==`foundry.data`||e.archiveVersion!==2||!z(e.data)||e.data.path!==`data/foundry.json`||typeof e.data.bytes!=`number`||!Number.isSafeInteger(e.data.bytes)||e.data.bytes<=0||typeof e.data.sha256!=`string`||!/^[a-f0-9]{64}$/u.test(e.data.sha256))throw new R(`INVALID_BACKUP`,`Unsupported or invalid backup manifest`);return{data:{path:w,bytes:e.data.bytes,sha256:e.data.sha256}}}function dn(e){if(!z(e)||!z(e.settings)||!Array.isArray(e.instructions)||!Array.isArray(e.agents))throw B(`Backup data must contain settings, instructions, and agents`);let t=fn(e.instructions),n=new Set(t.map(({id:e})=>e));return{settings:et(e.settings),instructions:t,agents:pn(e.agents,n)}}function fn(e){let t=/* @__PURE__ */ new Set;return e.map((e,n)=>{if(!z(e))throw B(`Invalid instruction at index ${n}`);let r=e.id;if(typeof r!=`string`||!F.test(r)||t.has(r))throw B(`Invalid instruction at index ${n}`);let i=typeof e.name==`string`?e.name.trim():``;if(!i||i.length>200)throw B(`Invalid instruction name at index ${n}`);if(typeof e.content!=`string`||!e.content.trim()||e.content.length>1e6)throw B(`Invalid instruction content at index ${n}`);let a={id:r,name:i,content:e.content,createdAt:mn(e.createdAt,n),updatedAt:mn(e.updatedAt,n)};return t.add(r),a})}function pn(e,t){let n=new Set(He),r=/* @__PURE__ */ new Set;return e.map((e,i)=>{if(!z(e)||!z(e.instructions))throw B(`Invalid agent at index ${i}`);let a=e.id;if(typeof a!=`string`||!n.has(a)||r.has(a))throw B(`Invalid agent at index ${i}`);let o=e.instructions,s=o.instructionIds;if(!Array.isArray(s))throw B(`Invalid instruction assignment for agent ${a}`);let c=s.map(e=>{if(typeof e!=`string`)throw B(`Invalid instruction assignment for agent ${a}`);return e});if(new Set(c).size!==c.length||c.some(e=>!t.has(e)))throw B(`Invalid instruction assignment for agent ${a}`);if(typeof o.enabled!=`boolean`)throw B(`Invalid enabled state for agent ${a}`);if(o.enabled&&c.length===0)throw B(`Enabled agent ${a} has no instructions`);let l={id:a,instructions:{instructionIds:c,enabled:o.enabled,createdAt:mn(o.createdAt,i),updatedAt:mn(o.updatedAt,i)}};return r.add(a),l})}function mn(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw B(`Invalid timestamp at index ${t}`);return e}function B(e){return new R(`INVALID_BACKUP`,e)}function hn(e,t){e.transaction(()=>{let n=new Set(t.instructions.map(({id:e})=>e));for(let t of qt(e))n.has(t.id)||e.removeTextFile(gn(t.id));for(let n of t.instructions)e.putTextFile(gn(n.id),Zt(n));let r=new Set(t.agents.map(({id:e})=>e));for(let t of e.all(`agents`))r.has(t.id)||e.remove(`agents`,t.id);for(let n of t.agents)e.put(`agents`,n);e.setSettings(t.settings)})}function gn(e){return r.join(`instructions`,`${e}.md`)}var _n=class{storage;constructor(e){this.storage=e}async importData(e,t){let n=await ge(r.join(oe(),`foundry-import-`));try{let i=r.join(n,`backup.zip`);await kt(e,i,t);let a=await Ct(i,r.join(n,`extracted`)),o=un(JSON.parse(await ve(a[`manifest.json`],`utf8`))),s=await ve(a[w]);if(s.byteLength!==o.data.bytes||le(`sha256`).update(s).digest(`hex`)!==o.data.sha256)throw new R(`INVALID_BACKUP`,`Backup checksum does not match`);let c=dn(JSON.parse(s.toString(`utf8`)));try{hn(this.storage,c)}catch{throw new R(`IMPORT_FAILED`,`Unable to import data`)}}catch(e){throw e instanceof R?e:e instanceof Et?e.code===`INVALID_PASSPHRASE`?new R(`INVALID_PASSPHRASE`,`Incorrect passphrase or corrupted backup`):new R(`IMPORT_FAILED`,`Unable to read or decrypt the backup file`):new R(`INVALID_BACKUP`,`The backup is invalid or unsupported`)}finally{await Rt(n)}}};const vn=`<!-- foundry:instructions:start -->`,yn=`<!-- foundry:instructions:end -->`;function bn(e,t){let n=xn(e),r=Cn(t);return`${n}${Sn(n)}${r}\n`}function xn(e){let t=``,n=0;for(let r of wn(e)){let e=Tn(r);e===`start`?n+=1:e===`end`?n=Math.max(0,n-1):e===`other`||n>0||(t+=r)}return t}function Sn(e){return!e||e.endsWith(`
|
|
5
5
|
`)?``:`
|