@inkeep/open-knowledge 0.26.1-beta.1 → 0.27.0-beta.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/assets/skills/discovery/SKILL.md +1 -1
- package/dist/assets/skills/project/SKILL.md +2 -2
- package/dist/assets/skills/project/references/preview.md +4 -4
- package/dist/assets/skills/write-skill/SKILL.md +1 -1
- package/dist/cli.mjs +63 -63
- package/dist/constants-FPRBLLHv.mjs +2 -0
- package/dist/{dist-D8lHZNr8.mjs → dist-CZ4COUHS.mjs} +1 -1
- package/dist/{dist-CUbAo1yS.mjs → dist-CdVqgoPq.mjs} +5 -5
- package/dist/{gh-detect-BUJyWvGO.mjs → gh-detect-KLjG6xCR.mjs} +2 -2
- package/dist/index.d.mts +16 -3
- package/dist/index.mjs +1 -1
- package/dist/init-DdgQk34k.mjs +660 -0
- package/dist/init-NQBVedkZ.mjs +1 -0
- package/dist/loader-B67yXEGv.mjs +1 -0
- package/dist/{loader-DLBG2Jf0.mjs → loader-XWkMJYxk.mjs} +2 -2
- package/dist/{preview-DMdR22hR.mjs → preview-BLauTAym.mjs} +2 -2
- package/dist/preview-BUda_ENP.mjs +1 -0
- package/dist/public/assets/{ActivityModeContent-ZV1oiH21.js → ActivityModeContent-Bu-aPWfE.js} +1 -1
- package/dist/public/assets/{ConsentDialogBody-ClEtx_H4.js → ConsentDialogBody-u7A2_0jL.js} +1 -1
- package/dist/public/assets/{DocumentContext-CNrQKGNw.js → DocumentContext-BNan6rEA.js} +1 -1
- package/dist/public/assets/{EnableSyncConfirmDialog-BhMvTv-2.js → EnableSyncConfirmDialog-DLAmAtNx.js} +1 -1
- package/dist/public/assets/{GraphPanel-B_Rx6o7k.js → GraphPanel-BXSu0qzO.js} +1 -1
- package/dist/public/assets/{ManagedArtifactProperties-CabIneyc.js → ManagedArtifactProperties-DCf7FSvm.js} +1 -1
- package/dist/public/assets/{McpConsentDialogBody-DW0Ku8h2.js → McpConsentDialogBody-DHnMMoKv.js} +1 -1
- package/dist/public/assets/{PropertyPanel-BGGPGg8z.js → PropertyPanel-CLRxrKmQ.js} +1 -1
- package/dist/public/assets/{SettingsDialogBody-D9Spbasa.js → SettingsDialogBody-BU_CWPpQ.js} +1 -1
- package/dist/public/assets/{ShareBranchSwitchDialog-MF01jVyK.js → ShareBranchSwitchDialog-DqhVt0LE.js} +1 -1
- package/dist/public/assets/{ShareReceiveDialog-BeDLlUWc.js → ShareReceiveDialog-COOji2w1.js} +1 -1
- package/dist/public/assets/{ShareReceiveMissDialog-CErdFiaW.js → ShareReceiveMissDialog-BIUsfWwx.js} +1 -1
- package/dist/public/assets/{SkillEditorActions--NrMimEw.js → SkillEditorActions-Cwen9r7n.js} +1 -1
- package/dist/public/assets/{SourceEditor-DR04Kk-L.js → SourceEditor-B8i0Zuc4.js} +1 -1
- package/dist/public/assets/{TerminalPanel-CDlxv5DM.js → TerminalPanel-CFHapL_S.js} +1 -1
- package/dist/public/assets/{auth-state-cache-XGzST2ZD.js → auth-state-cache-DbOzyU3U.js} +1 -1
- package/dist/public/assets/{config-provider-CNEpgM_S.js → config-provider-Do7HkFaK.js} +1 -1
- package/dist/public/assets/{dist-CQyX-suk.js → dist-IJIMi_KI.js} +2 -2
- package/dist/public/assets/{doc-hash-DK_ofUpp.js → doc-hash-B9qR3wab.js} +1 -1
- package/dist/public/assets/{documents-events-DWU2wzVY.js → documents-events-5sCrqLAB.js} +1 -1
- package/dist/public/assets/{file-tree-adapter-Co_rTNFv.js → file-tree-adapter-DeCSzJFc.js} +1 -1
- package/dist/public/assets/{index-CyAGZpgf.js → index-CfFNwC-k.js} +7 -7
- package/dist/public/assets/{index-CLrcKKoN.css → index-CwH3jLSk.css} +1 -1
- package/dist/public/assets/{keyboard-shortcuts-B_CAsza0.js → keyboard-shortcuts-DoqeoYey.js} +1 -1
- package/dist/public/assets/{navigation-targets-B88nmSdU.js → navigation-targets-CSLWdrg5.js} +1 -1
- package/dist/public/assets/{open-managed-artifact-tab-Bk_tqTdp.js → open-managed-artifact-tab-D6l9ALAm.js} +1 -1
- package/dist/public/assets/{pending-receive-nav-store-DpqQxXOd.js → pending-receive-nav-store-OU-qfx40.js} +1 -1
- package/dist/public/assets/{prop-types-YLAnoO2T.js → prop-types-Cak_LhNF.js} +1 -1
- package/dist/public/assets/{receive-store-BVPHm3DM.js → receive-store-DM0i5Ybb.js} +1 -1
- package/dist/public/assets/{selection-context-ythQq0B9.js → selection-context-Br-4VUmJ.js} +1 -1
- package/dist/public/assets/skill-actions-C1QaoF_v.js +1 -0
- package/dist/public/assets/{skills-api-9bY3Jtgz.js → skills-api-DJJ_LIKc.js} +1 -1
- package/dist/public/assets/{target-navigation-intent-CwZkFyaW.js → target-navigation-intent-DksqRbJO.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-BwvPMOYl.js → typing-burst-detector-ClZLBemU.js} +1 -1
- package/dist/public/index.html +22 -22
- package/dist/{repair-launch-json-CWUTx3IW.mjs → repair-launch-json-Bk99TDG5.mjs} +2 -2
- package/dist/{repair-mcp-configs-BYRhVChI.mjs → repair-mcp-configs-D3XsTqKa.mjs} +2 -2
- package/dist/{repair-skills-B2AtzCSn.mjs → repair-skills-D7TJAZll.mjs} +2 -2
- package/dist/repair-skills-DCZqW9al.mjs +1 -0
- package/dist/server-lock-GuuouVft-CeF2bXVd.mjs +1 -0
- package/dist/{server-lock-iLcBw_q0-BF_u0tGL.mjs → server-lock-iLcBw_q0-CdrK5Xfo.mjs} +2 -2
- package/dist/{src-BWAFlazs.mjs → src-D0hiW4nw.mjs} +2 -2
- package/dist/{start-CnXUmVrI.mjs → start-B3yMZZZG.mjs} +2 -2
- package/dist/start-DAdXMVff.mjs +1 -0
- package/dist/write-project-skill-BEzL3S1a.mjs +36 -0
- package/package.json +1 -1
- package/dist/constants-BfJcirqe.mjs +0 -2
- package/dist/init-9d1LNBPj.mjs +0 -1
- package/dist/init-Dvj0QJzs.mjs +0 -321
- package/dist/loader-z1b3_1sK.mjs +0 -1
- package/dist/preview-C9s_wKIU.mjs +0 -1
- package/dist/public/assets/skill-actions-CbRk7LAn.js +0 -1
- package/dist/repair-skills-B8ePNziA.mjs +0 -1
- package/dist/server-lock-GuuouVft-CWlICi2c.mjs +0 -1
- package/dist/start-CY3HKbBn.mjs +0 -1
- package/dist/write-project-skill-Cjym3mlY.mjs +0 -36
|
@@ -301,7 +301,7 @@ Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#pl
|
|
|
301
301
|
`,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration.
|
|
302
302
|
Please provide a chat model before proceeding with creating an answer session.
|
|
303
303
|
Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#plugin-secure-proxy
|
|
304
|
-
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:`The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.`,PLUGIN_COMPONENT_CONFLICT:`The component "%s" is already defined. The plugin "%s" is trying to redefine it.`};function fH(e,...t){let n=Error(UV(dH[e]??`Unsupported Orama Error code: ${e}`,...t));return n.code=e,`captureStackTrace`in Error.prototype&&Error.captureStackTrace(n),n}function pH(e){return{raw:Number(e),formatted:qV(e)}}function mH(e){if(e.id){if(typeof e.id!=`string`)throw fH(`DOCUMENT_ID_MUST_BE_STRING`,typeof e.id);return e.id}return YV()}function hH(e,t){for(let[n,r]of Object.entries(t)){let t=e[n];if(t!==void 0&&!(r===`geopoint`&&typeof t==`object`&&typeof t.lon==`number`&&typeof t.lat==`number`)&&!(r===`enum`&&(typeof t==`string`||typeof t==`number`))){if(r===`enum[]`&&Array.isArray(t)){let e=t.length;for(let r=0;r<e;r++)if(typeof t[r]!=`string`&&typeof t[r]!=`number`)return n+`.`+r;continue}if(yH(r)){let e=SH(r);if(!Array.isArray(t)||t.length!==e)throw fH(`INVALID_INPUT_VECTOR`,n,e,t.length);continue}if(bH(r)){if(!Array.isArray(t))return n;let e=xH(r),i=t.length;for(let r=0;r<i;r++)if(typeof t[r]!==e)return n+`.`+r;continue}if(typeof r==`object`){if(!t||typeof t!=`object`)return n;let e=hH(t,r);if(e)return n+`.`+e;continue}if(typeof t!==r)return n}}}const gH={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},_H={"string[]":`string`,"number[]":`number`,"boolean[]":`boolean`,"enum[]":`enum`};function vH(e){return e===`geopoint`}function yH(e){return typeof e==`string`&&/^vector\[\d+\]$/.test(e)}function bH(e){return typeof e==`string`&&gH[e]}function xH(e){return _H[e]}function SH(e){let t=Number(e.slice(7,-1));switch(!0){case isNaN(t):throw fH(`INVALID_VECTOR_VALUE`,e);case t<=0:throw fH(`INVALID_VECTOR_SIZE`,e);default:return t}}function CH(){return{idToInternalId:new Map,internalIdToId:[],save:wH,load:TH}}function wH(e){return{internalIdToId:e.internalIdToId}}function TH(e,t){let{internalIdToId:n}=t;e.internalDocumentIDStore.idToInternalId.clear(),e.internalDocumentIDStore.internalIdToId=[];let r=n.length;for(let t=0;t<r;t++){let r=n[t];e.internalDocumentIDStore.idToInternalId.set(r,t+1),e.internalDocumentIDStore.internalIdToId.push(r)}}function EH(e,t){if(typeof t==`string`){let n=e.idToInternalId.get(t);if(n)return n;let r=e.idToInternalId.size+1;return e.idToInternalId.set(t,r),e.internalIdToId.push(t),r}return t>e.internalIdToId.length?EH(e,t.toString()):t}function DH(e,t){if(e.internalIdToId.length<t)throw Error(`Invalid internalId ${t}`);return e.internalIdToId[t-1]}function OH(e,t){return{sharedInternalDocumentStore:t,docs:{},count:0}}function kH(e,t){let n=EH(e.sharedInternalDocumentStore,t);return e.docs[n]}function AH(e,t){let n=t.length,r=Array.from({length:n});for(let i=0;i<n;i++){let n=EH(e.sharedInternalDocumentStore,t[i]);r[i]=e.docs[n]}return r}function jH(e){return e.docs}function MH(e,t,n,r){return e.docs[n]===void 0?(e.docs[n]=r,e.count++,!0):!1}function NH(e,t){let n=EH(e.sharedInternalDocumentStore,t);return e.docs[n]===void 0?!1:(delete e.docs[n],e.count--,!0)}function PH(e){return e.count}function FH(e,t){let n=t;return{docs:n.docs,count:n.count,sharedInternalDocumentStore:e}}function IH(e){return{docs:e.docs,count:e.count}}function LH(){return{create:OH,get:kH,getMultiple:AH,getAll:jH,store:MH,remove:NH,count:PH,load:FH,save:IH}}const RH=[`beforeInsert`,`afterInsert`,`beforeRemove`,`afterRemove`,`beforeUpdate`,`afterUpdate`,`beforeUpsert`,`afterUpsert`,`beforeSearch`,`afterSearch`,`beforeInsertMultiple`,`afterInsertMultiple`,`beforeRemoveMultiple`,`afterRemoveMultiple`,`beforeUpdateMultiple`,`afterUpdateMultiple`,`beforeUpsertMultiple`,`afterUpsertMultiple`,`beforeLoad`,`afterLoad`,`afterCreate`];function zH(e,t){let n=[],r=e.plugins?.length;if(!r)return n;for(let i=0;i<r;i++)try{let r=e.plugins[i];typeof r[t]==`function`&&n.push(r[t])}catch(e){throw console.error(`Caught error in getAllPluginsByHook:`,e),fH(`PLUGIN_CRASHED`)}return n}const BH=[`tokenizer`,`index`,`documentsStore`,`sorter`,`pinning`],VH=[`validateSchema`,`getDocumentIndexId`,`getDocumentProperties`,`formatElapsedTime`];function HH(e,t,n,r){if(e.some(iH))return(async()=>{for(let i of e)await i(t,n,r)})();for(let i of e)i(t,n,r)}function UH(e,t,n){if(e.some(iH))return(async()=>{for(let r of e)await r(t,n)})();for(let r of e)r(t,n)}function WH(e,t,n,r,i){if(e.some(iH))return(async()=>{for(let a of e)await a(t,n,r,i)})();for(let a of e)a(t,n,r,i)}function GH(e,t,n,r){if(e.some(iH))return(async()=>{for(let i of e)await i(t,n,r)})();for(let i of e)i(t,n,r)}function KH(e,t){if(e.some(iH))return(async()=>{for(let n of e)await n(t)})();for(let n of e)n(t)}var qH=class e{k;v;l=null;r=null;h=1;constructor(e,t){this.k=e,this.v=new Set(t)}updateHeight(){this.h=Math.max(e.getHeight(this.l),e.getHeight(this.r))+1}static getHeight(e){return e?e.h:0}getBalanceFactor(){return e.getHeight(this.l)-e.getHeight(this.r)}rotateLeft(){let e=this.r;return this.r=e.l,e.l=this,this.updateHeight(),e.updateHeight(),e}rotateRight(){let e=this.l;return this.l=e.r,e.r=this,this.updateHeight(),e.updateHeight(),e}toJSON(){return{k:this.k,v:Array.from(this.v),l:this.l?this.l.toJSON():null,r:this.r?this.r.toJSON():null,h:this.h}}static fromJSON(t){let n=new e(t.k,t.v);return n.l=t.l?e.fromJSON(t.l):null,n.r=t.r?e.fromJSON(t.r):null,n.h=t.h,n}},JH=class e{root=null;insertCount=0;constructor(e,t){e!==void 0&&t!==void 0&&(this.root=new qH(e,t))}insert(e,t,n=1e3){this.root=this.insertNode(this.root,e,t,n)}insertMultiple(e,t,n=1e3){for(let r of t)this.insert(e,r,n)}rebalance(){this.root&&=this.rebalanceNode(this.root)}toJSON(){return{root:this.root?this.root.toJSON():null,insertCount:this.insertCount}}static fromJSON(t){let n=new e;return n.root=t.root?qH.fromJSON(t.root):null,n.insertCount=t.insertCount||0,n}insertNode(e,t,n,r){if(e===null)return new qH(t,[n]);let i=[],a=e,o=null;for(;a!==null;)if(i.push({parent:o,node:a}),t<a.k)if(a.l===null){a.l=new qH(t,[n]),i.push({parent:a,node:a.l});break}else o=a,a=a.l;else if(t>a.k)if(a.r===null){a.r=new qH(t,[n]),i.push({parent:a,node:a.r});break}else o=a,a=a.r;else return a.v.add(n),e;let s=!1;this.insertCount++%r===0&&(s=!0);for(let t=i.length-1;t>=0;t--){let{parent:n,node:r}=i[t];if(r.updateHeight(),s){let t=this.rebalanceNode(r);n?n.l===r?n.l=t:n.r===r&&(n.r=t):e=t}}return e}rebalanceNode(e){let t=e.getBalanceFactor();if(t>1){if(e.l&&e.l.getBalanceFactor()>=0)return e.rotateRight();if(e.l)return e.l=e.l.rotateLeft(),e.rotateRight()}if(t<-1){if(e.r&&e.r.getBalanceFactor()<=0)return e.rotateLeft();if(e.r)return e.r=e.r.rotateRight(),e.rotateLeft()}return e}find(e){let t=this.findNodeByKey(e);return t?t.v:null}contains(e){return this.find(e)!==null}getSize(){let e=0,t=[],n=this.root;for(;n||t.length>0;){for(;n;)t.push(n),n=n.l;n=t.pop(),e++,n=n.r}return e}isBalanced(){if(!this.root)return!0;let e=[this.root];for(;e.length>0;){let t=e.pop(),n=t.getBalanceFactor();if(Math.abs(n)>1)return!1;t.l&&e.push(t.l),t.r&&e.push(t.r)}return!0}remove(e){this.root=this.removeNode(this.root,e)}removeDocument(e,t){let n=this.findNodeByKey(e);n&&(n.v.size===1?this.root=this.removeNode(this.root,e):n.v=new Set([...n.v.values()].filter(e=>e!==t)))}findNodeByKey(e){let t=this.root;for(;t;)if(e<t.k)t=t.l;else if(e>t.k)t=t.r;else return t;return null}removeNode(e,t){if(e===null)return null;let n=[],r=e;for(;r!==null&&r.k!==t;)n.push(r),r=t<r.k?r.l:r.r;if(r===null)return e;if(r.l===null||r.r===null){let t=r.l?r.l:r.r;if(n.length===0)e=t;else{let e=n[n.length-1];e.l===r?e.l=t:e.r=t}}else{let e=r,t=r.r;for(;t.l!==null;)e=t,t=t.l;r.k=t.k,r.v=t.v,e.l===t?e.l=t.r:e.r=t.r,r=e}n.push(r);for(let t=n.length-1;t>=0;t--){let r=n[t];r.updateHeight();let i=this.rebalanceNode(r);if(t>0){let e=n[t-1];e.l===r?e.l=i:e.r===r&&(e.r=i)}else e=i}return e}rangeSearch(e,t){let n=new Set,r=[],i=this.root;for(;i||r.length>0;){for(;i;)r.push(i),i=i.l;if(i=r.pop(),i.k>=e&&i.k<=t)for(let e of i.v)n.add(e);if(i.k>t)break;i=i.r}return n}greaterThan(e,t=!1){let n=new Set,r=[],i=this.root;for(;i||r.length>0;){for(;i;)r.push(i),i=i.r;if(i=r.pop(),t&&i.k>=e||!t&&i.k>e)for(let e of i.v)n.add(e);else if(i.k<=e)break;i=i.l}return n}lessThan(e,t=!1){let n=new Set,r=[],i=this.root;for(;i||r.length>0;){for(;i;)r.push(i),i=i.l;if(i=r.pop(),t&&i.k<=e||!t&&i.k<e)for(let e of i.v)n.add(e);else if(i.k>e)break;i=i.r}return n}},YH=class e{numberToDocumentId;constructor(){this.numberToDocumentId=new Map}insert(e,t){this.numberToDocumentId.has(e)?this.numberToDocumentId.get(e).add(t):this.numberToDocumentId.set(e,new Set([t]))}find(e){let t=this.numberToDocumentId.get(e);return t?Array.from(t):null}remove(e){this.numberToDocumentId.delete(e)}removeDocument(e,t){let n=this.numberToDocumentId.get(t);n&&(n.delete(e),n.size===0&&this.numberToDocumentId.delete(t))}contains(e){return this.numberToDocumentId.has(e)}getSize(){let e=0;for(let t of this.numberToDocumentId.values())e+=t.size;return e}filter(e){let t=Object.keys(e);if(t.length!==1)throw Error(`Invalid operation`);let n=t[0];switch(n){case`eq`:{let t=e[n],r=this.numberToDocumentId.get(t);return r?Array.from(r):[]}case`in`:{let t=e[n],r=new Set;for(let e of t){let t=this.numberToDocumentId.get(e);if(t)for(let e of t)r.add(e)}return Array.from(r)}case`nin`:{let t=new Set(e[n]),r=new Set;for(let[e,n]of this.numberToDocumentId.entries())if(!t.has(e))for(let e of n)r.add(e);return Array.from(r)}default:throw Error(`Invalid operation`)}}filterArr(e){let t=Object.keys(e);if(t.length!==1)throw Error(`Invalid operation`);let n=t[0];switch(n){case`containsAll`:{let t=e[n].map(e=>this.numberToDocumentId.get(e)??new Set);if(t.length===0)return[];let r=t.reduce((e,t)=>new Set([...e].filter(e=>t.has(e))));return Array.from(r)}case`containsAny`:{let t=e[n].map(e=>this.numberToDocumentId.get(e)??new Set);if(t.length===0)return[];let r=t.reduce((e,t)=>new Set([...e,...t]));return Array.from(r)}default:throw Error(`Invalid operation`)}}static fromJSON(t){if(!t.numberToDocumentId)throw Error(`Invalid Flat Tree JSON`);let n=new e;for(let[e,r]of t.numberToDocumentId)n.numberToDocumentId.set(e,new Set(r));return n}toJSON(){return{numberToDocumentId:Array.from(this.numberToDocumentId.entries()).map(([e,t])=>[e,Array.from(t)])}}};function XH(e,t,n){if(n<0)return-1;if(e===t)return 0;let r=e.length,i=t.length;if(r===0)return i<=n?i:-1;if(i===0)return r<=n?r:-1;let a=Math.abs(r-i);if(e.startsWith(t))return a<=n?a:-1;if(t.startsWith(e))return 0;if(a>n)return-1;let o=[];for(let e=0;e<=r;e++){o[e]=[e];for(let t=1;t<=i;t++)o[e][t]=e===0?t:0}for(let a=1;a<=r;a++){let r=1/0;for(let n=1;n<=i;n++)e[a-1]===t[n-1]?o[a][n]=o[a-1][n-1]:o[a][n]=Math.min(o[a-1][n]+1,o[a][n-1]+1,o[a-1][n-1]+1),r=Math.min(r,o[a][n]);if(r>n)return-1}return o[r][i]<=n?o[r][i]:-1}function ZH(e,t,n){let r=XH(e,t,n);return{distance:r,isBounded:r>=0}}var QH=class e{k;s;c=new Map;d=new Set;e;w=``;constructor(e,t,n){this.k=e,this.s=t,this.e=n}updateParent(e){this.w=e.w+this.s}addDocument(e){this.d.add(e)}removeDocument(e){return this.d.delete(e)}findAllWords(e,t,n,r){let i=[this];for(;i.length>0;){let a=i.pop();if(a.e){let{w:i,d:o}=a;if(n&&i!==t)continue;if(XV(e,i)!==null)if(r)if(Math.abs(t.length-i.length)<=r&&ZH(t,i,r).isBounded)e[i]=[];else continue;else e[i]=[];if(XV(e,i)!=null&&o.size>0){let t=e[i];for(let e of o)t.includes(e)||t.push(e)}}a.c.size>0&&i.push(...a.c.values())}return e}insert(t,n){let r=this,i=0,a=t.length;for(;i<a;){let o=t[i],s=r.c.get(o);if(s){let o=s.s,c=o.length,l=0;for(;l<c&&i+l<a&&o[l]===t[i+l];)l++;if(l===c){if(r=s,i+=l,i===a){s.e||=!0,s.addDocument(n);return}continue}let u=o.slice(0,l),d=o.slice(l),f=t.slice(i+l),p=new e(u[0],u,!1);if(r.c.set(u[0],p),p.updateParent(r),s.s=d,s.k=d[0],p.c.set(d[0],s),s.updateParent(p),f){let t=new e(f[0],f,!0);t.addDocument(n),p.c.set(f[0],t),t.updateParent(p)}else p.e=!0,p.addDocument(n);return}else{let a=new e(o,t.slice(i),!0);a.addDocument(n),r.c.set(o,a),a.updateParent(r);return}}r.e||=!0,r.addDocument(n)}_findLevenshtein(e,t,n,r,i){let a=[{node:this,index:t,tolerance:n}];for(;a.length>0;){let{node:t,index:n,tolerance:o}=a.pop();if(t.w.startsWith(e)){t.findAllWords(i,e,!1,0);continue}if(o<0)continue;if(t.e){let{w:n,d:a}=t;if(n&&(ZH(e,n,r).isBounded&&(i[n]=[]),XV(i,n)!==void 0&&a.size>0)){let e=new Set(i[n]);for(let t of a)e.add(t);i[n]=Array.from(e)}}if(n>=e.length)continue;let s=e[n];if(t.c.has(s)){let e=t.c.get(s);a.push({node:e,index:n+1,tolerance:o})}a.push({node:t,index:n+1,tolerance:o-1});for(let[e,r]of t.c)a.push({node:r,index:n,tolerance:o-1}),e!==s&&a.push({node:r,index:n+1,tolerance:o-1})}}find(e){let{term:t,exact:n,tolerance:r}=e;if(r&&!n){let e={};return this._findLevenshtein(t,0,r,r,e),e}else{let e=this,i=0,a=t.length;for(;i<a;){let o=t[i],s=e.c.get(o);if(s){let o=s.s,c=o.length,l=0;for(;l<c&&i+l<a&&o[l]===t[i+l];)l++;if(l===c)e=s,i+=l;else if(i+l===a)if(l===a-i){if(n)return{};{let e={};return s.findAllWords(e,t,n,r),e}}else return{};else return{}}else return{}}let o={};return e.findAllWords(o,t,n,r),o}}contains(e){let t=this,n=0,r=e.length;for(;n<r;){let i=e[n],a=t.c.get(i);if(a){let i=a.s,o=i.length,s=0;for(;s<o&&n+s<r&&i[s]===e[n+s];)s++;if(s<o)return!1;n+=o,t=a}else return!1}return!0}removeWord(e){if(!e)return!1;let t=this,n=e.length,r=[];for(let i=0;i<n;i++){let n=e[i];if(t.c.has(n)){let e=t.c.get(n);r.push({parent:t,character:n}),i+=e.s.length-1,t=e}else return!1}for(t.d.clear(),t.e=!1;r.length>0&&t.c.size===0&&!t.e&&t.d.size===0;){let{parent:e,character:n}=r.pop();e.c.delete(n),t=e}return!0}removeDocumentByWord(e,t,n=!0){if(!e)return!0;let r=this,i=e.length;for(let a=0;a<i;a++){let i=e[a];if(r.c.has(i)){let o=r.c.get(i);a+=o.s.length-1,r=o,n&&r.w!==e||r.removeDocument(t)}else return!1}return!0}static getCommonPrefix(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e.charCodeAt(r)===t.charCodeAt(r);)r++;return e.slice(0,r)}toJSON(){return{w:this.w,s:this.s,e:this.e,k:this.k,d:Array.from(this.d),c:Array.from(this.c?.entries())?.map(([e,t])=>[e,t.toJSON()])}}static fromJSON(t){let n=new e(t.k,t.s,t.e);return n.w=t.w,n.d=new Set(t.d),n.c=new Map(t?.c?.map(([t,n])=>[t,e.fromJSON(n)])||[]),n}},$H=class e extends QH{constructor(){super(``,``,!1)}static fromJSON(t){let n=new e;return n.w=t.w,n.s=t.s,n.e=t.e,n.k=t.k,n.d=new Set(t.d),n.c=new Map(t?.c?.map(([e,t])=>[e,QH.fromJSON(t)])||[]),n}toJSON(){return super.toJSON()}},eU=class e{point;docIDs;left;right;parent;constructor(e,t){this.point=e,this.docIDs=new Set(t),this.left=null,this.right=null,this.parent=null}toJSON(){return{point:this.point,docIDs:Array.from(this.docIDs),left:this.left?this.left.toJSON():null,right:this.right?this.right.toJSON():null}}static fromJSON(t,n=null){let r=new e(t.point,t.docIDs);return r.parent=n,t.left&&(r.left=e.fromJSON(t.left,r)),t.right&&(r.right=e.fromJSON(t.right,r)),r}},tU=class e{root;nodeMap;constructor(){this.root=null,this.nodeMap=new Map}getPointKey(e){return`${e.lon},${e.lat}`}insert(e,t){let n=this.getPointKey(e),r=this.nodeMap.get(n);if(r){t.forEach(e=>r.docIDs.add(e));return}let i=new eU(e,t);if(this.nodeMap.set(n,i),this.root==null){this.root=i;return}let a=this.root,o=0;for(;;){if(o%2==0)if(e.lon<a.point.lon){if(a.left==null){a.left=i,i.parent=a;return}a=a.left}else{if(a.right==null){a.right=i,i.parent=a;return}a=a.right}else if(e.lat<a.point.lat){if(a.left==null){a.left=i,i.parent=a;return}a=a.left}else{if(a.right==null){a.right=i,i.parent=a;return}a=a.right}o++}}contains(e){let t=this.getPointKey(e);return this.nodeMap.has(t)}getDocIDsByCoordinates(e){let t=this.getPointKey(e),n=this.nodeMap.get(t);return n?Array.from(n.docIDs):null}removeDocByID(e,t){let n=this.getPointKey(e),r=this.nodeMap.get(n);r&&(r.docIDs.delete(t),r.docIDs.size===0&&(this.nodeMap.delete(n),this.deleteNode(r)))}deleteNode(e){let t=e.parent,n=e.left?e.left:e.right;n&&(n.parent=t),t?t.left===e?t.left=n:t.right===e&&(t.right=n):(this.root=n,this.root&&(this.root.parent=null))}searchByRadius(t,n,r=!0,i=`asc`,a=!1){let o=a?e.vincentyDistance:e.haversineDistance,s=[{node:this.root,depth:0}],c=[];for(;s.length>0;){let{node:e,depth:i}=s.pop();if(e==null)continue;let a=o(t,e.point);(r?a<=n:a>n)&&c.push({point:e.point,docIDs:Array.from(e.docIDs)}),e.left!=null&&s.push({node:e.left,depth:i+1}),e.right!=null&&s.push({node:e.right,depth:i+1})}return i&&c.sort((e,n)=>{let r=o(t,e.point),a=o(t,n.point);return i.toLowerCase()===`asc`?r-a:a-r}),c}searchByPolygon(t,n=!0,r=null,i=!1){let a=[{node:this.root,depth:0}],o=[];for(;a.length>0;){let{node:r,depth:i}=a.pop();if(r==null)continue;r.left!=null&&a.push({node:r.left,depth:i+1}),r.right!=null&&a.push({node:r.right,depth:i+1});let s=e.isPointInPolygon(t,r.point);(s&&n||!s&&!n)&&o.push({point:r.point,docIDs:Array.from(r.docIDs)})}let s=e.calculatePolygonCentroid(t);if(r){let t=i?e.vincentyDistance:e.haversineDistance;o.sort((e,n)=>{let i=t(s,e.point),a=t(s,n.point);return r.toLowerCase()===`asc`?i-a:a-i})}return o}toJSON(){return{root:this.root?this.root.toJSON():null}}static fromJSON(t){let n=new e;return t.root&&(n.root=eU.fromJSON(t.root),n.buildNodeMap(n.root)),n}buildNodeMap(e){if(e==null)return;let t=this.getPointKey(e.point);this.nodeMap.set(t,e),e.left&&this.buildNodeMap(e.left),e.right&&this.buildNodeMap(e.right)}static calculatePolygonCentroid(e){let t=0,n=0,r=0,i=e.length;for(let a=0,o=i-1;a<i;o=a++){let i=e[a].lon,s=e[a].lat,c=e[o].lon,l=e[o].lat,u=i*l-c*s;t+=u,n+=(i+c)*u,r+=(s+l)*u}t/=2;let a=6*t;return n/=a,r/=a,{lon:n,lat:r}}static isPointInPolygon(e,t){let n=!1,r=t.lon,i=t.lat,a=e.length;for(let t=0,o=a-1;t<a;o=t++){let a=e[t].lon,s=e[t].lat,c=e[o].lon,l=e[o].lat;s>i!=l>i&&r<(c-a)*(i-s)/(l-s)+a&&(n=!n)}return n}static haversineDistance(e,t){let n=Math.PI/180,r=e.lat*n,i=t.lat*n,a=(t.lat-e.lat)*n,o=(t.lon-e.lon)*n,s=Math.sin(a/2)*Math.sin(a/2)+Math.cos(r)*Math.cos(i)*Math.sin(o/2)*Math.sin(o/2);return 6371e3*(2*Math.atan2(Math.sqrt(s),Math.sqrt(1-s)))}static vincentyDistance(e,t){let n=6378137,r=1/298.257223563,i=(1-r)*n,a=Math.PI/180,o=e.lat*a,s=t.lat*a,c=(t.lon-e.lon)*a,l=Math.atan((1-r)*Math.tan(o)),u=Math.atan((1-r)*Math.tan(s)),d=Math.sin(l),f=Math.cos(l),p=Math.sin(u),m=Math.cos(u),h=c,g,_=1e3,v,y,b,x,S,C;do{let e=Math.sin(h),t=Math.cos(h);if(v=Math.sqrt(m*e*(m*e)+(f*p-d*m*t)*(f*p-d*m*t)),v===0)return 0;y=d*p+f*m*t,b=Math.atan2(v,y),x=f*m*e/v,S=1-x*x,C=y-2*d*p/S,isNaN(C)&&(C=0);let n=r/16*S*(4+r*(4-3*S));g=h,h=c+(1-n)*r*x*(b+n*v*(C+n*y*(-1+2*C*C)))}while(Math.abs(h-g)>1e-12&&--_>0);if(_===0)return NaN;let w=S*(n*n-i*i)/(i*i),T=1+w/16384*(4096+w*(-768+w*(320-175*w))),E=w/1024*(256+w*(-128+w*(74-47*w))),ee=E*v*(C+E/4*(y*(-1+2*C*C)-E/6*C*(-3+4*v*v)*(-3+4*C*C)));return i*T*(b-ee)}},nU=class e{true;false;constructor(){this.true=new Set,this.false=new Set}insert(e,t){t?this.true.add(e):this.false.add(e)}delete(e,t){t?this.true.delete(e):this.false.delete(e)}getSize(){return this.true.size+this.false.size}toJSON(){return{true:Array.from(this.true),false:Array.from(this.false)}}static fromJSON(t){let n=new e;return n.true=new Set(t.true),n.false=new Set(t.false),n}};function rU(e,t,n,r,i,{k:a,b:o,d:s}){return Math.log(1+(n-t+.5)/(t+.5))*(s+e*(a+1))/(e+a*(1-o+o*r/i))}var iU=class e{size;vectors=new Map;constructor(e){this.size=e}add(e,t){t instanceof Float32Array||(t=new Float32Array(t));let n=aU(t,this.size);this.vectors.set(e,[n,t])}remove(e){this.vectors.delete(e)}find(e,t,n){return e instanceof Float32Array||(e=new Float32Array(e)),oU(e,n,this.vectors,this.size,t)}toJSON(){let e=[];for(let[t,[n,r]]of this.vectors)e.push([t,[n,Array.from(r)]]);return{size:this.size,vectors:e}}static fromJSON(t){let n=t,r=new e(n.size);for(let[e,[t,i]]of n.vectors)r.vectors.set(e,[t,new Float32Array(i)]);return r}};function aU(e,t){let n=0;for(let r=0;r<t;r++)n+=e[r]*e[r];return Math.sqrt(n)}function oU(e,t,n,r,i){let a=aU(e,r),o=[],s=t||n.keys();for(let t of s){let s=n.get(t);if(!s)continue;let c=s[0],l=s[1],u=0;for(let t=0;t<r;t++)u+=e[t]*l[t];let d=u/(a*c);d>=i&&o.push([t,d])}return o}function sU(e,t,n,r,i){let a=EH(e.sharedInternalDocumentStore,n);e.avgFieldLength[t]=((e.avgFieldLength[t]??0)*(i-1)+r.length)/i,e.fieldLengths[t][a]=r.length,e.frequencies[t][a]={}}function cU(e,t,n,r,i){let a=0;for(let e of r)e===i&&a++;let o=EH(e.sharedInternalDocumentStore,n),s=a/r.length;e.frequencies[t][o][i]=s,i in e.tokenOccurrences[t]||(e.tokenOccurrences[t][i]=0),e.tokenOccurrences[t][i]=(e.tokenOccurrences[t][i]??0)+1}function lU(e,t,n,r){let i=EH(e.sharedInternalDocumentStore,n);r>1?e.avgFieldLength[t]=(e.avgFieldLength[t]*r-e.fieldLengths[t][i])/(r-1):e.avgFieldLength[t]=void 0,e.fieldLengths[t][i]=void 0,e.frequencies[t][i]=void 0}function uU(e,t,n){e.tokenOccurrences[t][n]--}function dU(e,t,n,r,i=``){r||={sharedInternalDocumentStore:t,indexes:{},vectorIndexes:{},searchableProperties:[],searchablePropertiesWithTypes:{},frequencies:{},tokenOccurrences:{},avgFieldLength:{},fieldLengths:{}};for(let[a,o]of Object.entries(n)){let n=`${i}${i?`.`:``}${a}`;if(typeof o==`object`&&!Array.isArray(o)){dU(e,t,o,r,n);continue}if(yH(o))r.searchableProperties.push(n),r.searchablePropertiesWithTypes[n]=o,r.vectorIndexes[n]={type:`Vector`,node:new iU(SH(o)),isArray:!1};else{let e=/\[/.test(o);switch(o){case`boolean`:case`boolean[]`:r.indexes[n]={type:`Bool`,node:new nU,isArray:e};break;case`number`:case`number[]`:r.indexes[n]={type:`AVL`,node:new JH(0,[]),isArray:e};break;case`string`:case`string[]`:r.indexes[n]={type:`Radix`,node:new $H,isArray:e},r.avgFieldLength[n]=0,r.frequencies[n]={},r.tokenOccurrences[n]={},r.fieldLengths[n]={};break;case`enum`:case`enum[]`:r.indexes[n]={type:`Flat`,node:new YH,isArray:e};break;case`geopoint`:r.indexes[n]={type:`BKD`,node:new tU,isArray:e};break;default:throw fH(`INVALID_SCHEMA_TYPE`,Array.isArray(o)?`array`:o,n)}r.searchableProperties.push(n),r.searchablePropertiesWithTypes[n]=o}}return r}function fU(e,t,n,r,i,a,o,s){return c=>{let{type:l,node:u}=t.indexes[n];switch(l){case`Bool`:u[c?`true`:`false`].add(r);break;case`AVL`:{let e=s?.avlRebalanceThreshold??1;u.insert(c,r,e);break}case`Radix`:{let s=a.tokenize(c,i,n,!1);e.insertDocumentScoreParameters(t,n,r,s,o);for(let i of s)e.insertTokenScoreParameters(t,n,r,s,i),u.insert(i,r);break}case`Flat`:u.insert(c,r);break;case`BKD`:u.insert(c,[r]);break}}}function pU(e,t,n,r,i,a,o,s,c,l,u){if(yH(o))return mU(t,n,a,r,i);let d=fU(e,t,n,i,s,c,l,u);if(!bH(o))return d(a);let f=a,p=f.length;for(let e=0;e<p;e++)d(f[e])}function mU(e,t,n,r,i){e.vectorIndexes[t].node.add(i,n)}function hU(e,t,n,r,i,a,o,s,c,l){if(yH(o))return t.vectorIndexes[n].node.remove(i),!0;let{type:u,node:d}=t.indexes[n];switch(u){case`AVL`:return d.removeDocument(a,i),!0;case`Bool`:return d[a?`true`:`false`].delete(i),!0;case`Radix`:{let o=c.tokenize(a,s,n);e.removeDocumentScoreParameters(t,n,r,l);for(let r of o)e.removeTokenScoreParameters(t,n,r),d.removeDocumentByWord(r,i);return!0}case`Flat`:return d.removeDocument(i,a),!0;case`BKD`:return d.removeDocByID(a,i),!1}}function gU(e,t,n,r,i,a,o,s,c,l){if(!bH(o))return hU(e,t,n,r,i,a,o,s,c,l);let u=xH(o),d=a,f=d.length;for(let a=0;a<f;a++)hU(e,t,n,r,i,d[a],u,s,c,l);return!0}function _U(e,t,n,r,i,a,o,s,c,l){let u=Array.from(r),d=e.avgFieldLength[t],f=e.fieldLengths[t],p=e.tokenOccurrences[t],m=e.frequencies[t],h=typeof p[n]==`number`?p[n]??0:0,g=u.length;for(let e=0;e<g;e++){let r=u[e];if(c&&!c.has(r))continue;l.has(r)||l.set(r,new Map);let p=l.get(r);p.set(t,(p.get(t)||0)+1);let g=rU(m?.[r]?.[n]??0,h,i,f[r],d,a);o.has(r)?o.set(r,o.get(r)+g*s):o.set(r,g*s)}}function vU(e,t,n,r,i,a,o,s,c,l,u,d=0){let f=n.tokenize(t,r),p=f.length||1,m=new Map,h=new Map,g=new Map;for(let n of i){if(!(n in e.indexes))continue;let r=e.indexes[n],{type:i}=r;if(i!==`Radix`)throw fH(`WRONG_SEARCH_PROPERTY_TYPE`,n);let d=s[n]??1;if(d<=0)throw fH(`INVALID_BOOST_VALUE`,d);f.length===0&&!t&&f.push(``);let p=f.length;for(let t=0;t<p;t++){let i=f[t],s=r.node.find({term:i,exact:a,tolerance:o}),p=Object.keys(s);p.length>0&&h.set(i,!0);let _=p.length;for(let t=0;t<_;t++){let r=p[t],i=s[r];_U(e,n,r,i,l,c,g,d,u,m)}}}let _=Array.from(g.entries()).map(([e,t])=>[e,t]).sort((e,t)=>t[1]-e[1]);if(_.length===0)return[];if(d===1)return _;if(d===0){if(p===1)return _;for(let e of f)if(!h.get(e))return[];return _.filter(([e])=>{let t=m.get(e);return t?Array.from(t.values()).some(e=>e===p):!1})}let v=_.filter(([e])=>{let t=m.get(e);return t?Array.from(t.values()).some(e=>e===p):!1});if(v.length>0){let e=_.filter(([e])=>!v.some(([t])=>t===e)),t=Math.ceil(e.length*d);return[...v,...e.slice(0,t)]}return _}function yU(e,t,n,r){if(`and`in n&&n.and&&Array.isArray(n.and)){let i=n.and;return i.length===0?new Set:oH(...i.map(n=>yU(e,t,n,r)))}if(`or`in n&&n.or&&Array.isArray(n.or)){let i=n.or;return i.length===0?new Set:i.map(n=>yU(e,t,n,r)).reduce((e,t)=>cH(e,t),new Set)}if(`not`in n&&n.not){let i=n.not,a=new Set,o=e.sharedInternalDocumentStore;for(let e=1;e<=o.internalIdToId.length;e++)a.add(e);return lH(a,yU(e,t,i,r))}let i=Object.keys(n),a=i.reduce((e,t)=>({[t]:new Set,...e}),{});for(let o of i){let i=n[o];if(e.indexes[o]===void 0)throw fH(`UNKNOWN_FILTER_PROPERTY`,o);let{node:s,type:c,isArray:l}=e.indexes[o];if(c===`Bool`){let e=s,t=i?e.true:e.false;a[o]=cH(a[o],t);continue}if(c===`BKD`){let e;if(`radius`in i)e=`radius`;else if(`polygon`in i)e=`polygon`;else throw Error(`Invalid operation ${i}`);if(e===`radius`){let{value:t,coordinates:n,unit:r=`m`,inside:c=!0,highPrecision:l=!1}=i[e],u=nH(t,r),d=s.searchByRadius(n,u,c,void 0,l);a[o]=TU(a[o],d)}else{let{coordinates:t,inside:n=!0,highPrecision:r=!1}=i[e],c=s.searchByPolygon(t,n,void 0,r);a[o]=TU(a[o],c)}continue}if(c===`Radix`&&(typeof i==`string`||Array.isArray(i))){for(let e of[i].flat()){let n=t.tokenize(e,r,o);for(let e of n){let t=s.find({term:e,exact:!0});a[o]=kU(a[o],t)}}continue}let u=Object.keys(i);if(u.length>1)throw fH(`INVALID_FILTER_OPERATION`,u.length);if(c===`Flat`){let e=new Set(l?s.filterArr(i):s.filter(i));a[o]=cH(a[o],e);continue}if(c===`AVL`){let e=u[0],t=i[e],n;switch(e){case`gt`:n=s.greaterThan(t,!1);break;case`gte`:n=s.greaterThan(t,!0);break;case`lt`:n=s.lessThan(t,!1);break;case`lte`:n=s.lessThan(t,!0);break;case`eq`:n=s.find(t)??new Set;break;case`between`:{let[e,r]=t;n=s.rangeSearch(e,r);break}default:throw fH(`INVALID_FILTER_OPERATION`,e)}a[o]=cH(a[o],n)}}return oH(...Object.values(a))}function bU(e){return e.searchableProperties}function xU(e){return e.searchablePropertiesWithTypes}function SU(e,t){let{indexes:n,vectorIndexes:r,searchableProperties:i,searchablePropertiesWithTypes:a,frequencies:o,tokenOccurrences:s,avgFieldLength:c,fieldLengths:l}=t,u={},d={};for(let e of Object.keys(n)){let{node:t,type:r,isArray:i}=n[e];switch(r){case`Radix`:u[e]={type:`Radix`,node:$H.fromJSON(t),isArray:i};break;case`Flat`:u[e]={type:`Flat`,node:YH.fromJSON(t),isArray:i};break;case`AVL`:u[e]={type:`AVL`,node:JH.fromJSON(t),isArray:i};break;case`BKD`:u[e]={type:`BKD`,node:tU.fromJSON(t),isArray:i};break;case`Bool`:u[e]={type:`Bool`,node:nU.fromJSON(t),isArray:i};break;default:u[e]=n[e]}}for(let e of Object.keys(r))d[e]={type:`Vector`,isArray:!1,node:iU.fromJSON(r[e])};return{sharedInternalDocumentStore:e,indexes:u,vectorIndexes:d,searchableProperties:i,searchablePropertiesWithTypes:a,frequencies:o,tokenOccurrences:s,avgFieldLength:c,fieldLengths:l}}function CU(e){let{indexes:t,vectorIndexes:n,searchableProperties:r,searchablePropertiesWithTypes:i,frequencies:a,tokenOccurrences:o,avgFieldLength:s,fieldLengths:c}=e,l={};for(let e of Object.keys(n))l[e]=n[e].node.toJSON();let u={};for(let e of Object.keys(t)){let{type:n,node:r,isArray:i}=t[e];n===`Flat`||n===`Radix`||n===`AVL`||n===`BKD`||n===`Bool`?u[e]={type:n,node:r.toJSON(),isArray:i}:(u[e]=t[e],u[e].node=u[e].node.toJSON())}return{indexes:u,vectorIndexes:l,searchableProperties:r,searchablePropertiesWithTypes:i,frequencies:a,tokenOccurrences:o,avgFieldLength:s,fieldLengths:c}}function wU(){return{create:dU,insert:pU,remove:gU,insertDocumentScoreParameters:sU,insertTokenScoreParameters:cU,removeDocumentScoreParameters:lU,removeTokenScoreParameters:uU,calculateResultScores:_U,search:vU,searchByWhereClause:yU,getSearchableProperties:bU,getSearchablePropertiesWithTypes:xU,load:SU,save:CU}}function TU(e,t){e||=new Set;let n=t.length;for(let r=0;r<n;r++){let n=t[r].docIDs,i=n.length;for(let t=0;t<i;t++)e.add(n[t])}return e}function EU(e,t,n=!1){let r=n?tU.vincentyDistance:tU.haversineDistance,i=[],a=[];for(let{point:n}of e)a.push(r(t,n));let o=Math.max(...a),s=0;for(let{docIDs:t}of e){let e=o-a[s]+1;for(let n of t)i.push([n,e]);s++}return i.sort((e,t)=>t[1]-e[1]),i}function DU(e,t){let n=Object.keys(e);if(n.length!==1)return{isGeoOnly:!1};let r=n[0],i=e[r];if(t.indexes[r]===void 0)return{isGeoOnly:!1};let{type:a}=t.indexes[r];return a===`BKD`&&i&&(`radius`in i||`polygon`in i)?{isGeoOnly:!0,geoProperty:r,geoOperation:i}:{isGeoOnly:!1}}function OU(e,t){let n=e,r=DU(t,n);if(!r.isGeoOnly||!r.geoProperty||!r.geoOperation)return null;let{node:i}=n.indexes[r.geoProperty],a=r.geoOperation,o=i,s;if(`radius`in a){let{value:e,coordinates:t,unit:n=`m`,inside:r=!0,highPrecision:i=!1}=a.radius,c=t,l=nH(e,n);return s=o.searchByRadius(c,l,r,`asc`,i),EU(s,c,i)}else if(`polygon`in a){let{coordinates:e,inside:t=!0,highPrecision:n=!1}=a.polygon;s=o.searchByPolygon(e,t,`asc`,n);let r=tU.calculatePolygonCentroid(e);return EU(s,r,n)}return null}function kU(e,t){e||=new Set;let n=Object.keys(t),r=n.length;for(let i=0;i<r;i++){let r=t[n[i]],a=r.length;for(let t=0;t<a;t++)e.add(r[t])}return e}function AU(e,t,n,r,i){let a={language:e.tokenizer.language,sharedInternalDocumentStore:t,enabled:!0,isSorted:!0,sortableProperties:[],sortablePropertiesWithTypes:{},sorts:{}};for(let[o,s]of Object.entries(n)){let n=`${i}${i?`.`:``}${o}`;if(!r.includes(n)){if(typeof s==`object`&&!Array.isArray(s)){let i=AU(e,t,s,r,n);HV(a.sortableProperties,i.sortableProperties),a.sorts={...a.sorts,...i.sorts},a.sortablePropertiesWithTypes={...a.sortablePropertiesWithTypes,...i.sortablePropertiesWithTypes};continue}if(!yH(s))switch(s){case`boolean`:case`number`:case`string`:a.sortableProperties.push(n),a.sortablePropertiesWithTypes[n]=s,a.sorts[n]={docs:new Map,orderedDocsToRemove:new Map,orderedDocs:[],type:s};break;case`geopoint`:case`enum`:continue;case`enum[]`:case`boolean[]`:case`number[]`:case`string[]`:continue;default:throw fH(`INVALID_SORT_SCHEMA_TYPE`,Array.isArray(s)?`array`:s,n)}}}return a}function jU(e,t,n,r){return r?.enabled===!1?{disabled:!0}:AU(e,t,n,(r||{}).unsortableProperties||[],``)}function MU(e,t,n,r){if(!e.enabled)return;e.isSorted=!1;let i=EH(e.sharedInternalDocumentStore,n),a=e.sorts[t];a.orderedDocsToRemove.has(i)&&zU(e,t),a.docs.set(i,a.orderedDocs.length),a.orderedDocs.push([i,r])}function NU(e){if(e.isSorted||!e.enabled)return;let t=Object.keys(e.sorts);for(let n of t)LU(e,n);e.isSorted=!0}function PU(e,t,n){return t[1].localeCompare(n[1],FV(e))}function FU(e,t){return e[1]-t[1]}function IU(e,t){return t[1]?-1:1}function LU(e,t){let n=e.sorts[t],r;switch(n.type){case`string`:r=PU.bind(null,e.language);break;case`number`:r=FU.bind(null);break;case`boolean`:r=IU.bind(null);break}n.orderedDocs.sort(r);let i=n.orderedDocs.length;for(let e=0;e<i;e++){let t=n.orderedDocs[e][0];n.docs.set(t,e)}}function RU(e){let t=Object.keys(e.sorts);for(let n of t)zU(e,n)}function zU(e,t){let n=e.sorts[t];n.orderedDocsToRemove.size&&(n.orderedDocs=n.orderedDocs.filter(e=>!n.orderedDocsToRemove.has(e[0])),n.orderedDocsToRemove.clear())}function BU(e,t,n){if(!e.enabled)return;let r=e.sorts[t],i=EH(e.sharedInternalDocumentStore,n);r.docs.get(i)&&(r.docs.delete(i),r.orderedDocsToRemove.set(i,!0))}function VU(e,t,n){if(!e.enabled)throw fH(`SORT_DISABLED`);let r=n.property,i=n.order===`DESC`,a=e.sorts[r];if(!a)throw fH(`UNABLE_TO_SORT_ON_UNKNOWN_FIELD`,r,e.sortableProperties.join(`, `));return zU(e,r),NU(e),t.sort((t,n)=>{let r=a.docs.get(EH(e.sharedInternalDocumentStore,t[0])),o=a.docs.get(EH(e.sharedInternalDocumentStore,n[0])),s=r!==void 0,c=o!==void 0;return!s&&!c?0:s?c?i?o-r:r-o:-1:1}),t}function HU(e){return e.enabled?e.sortableProperties:[]}function UU(e){return e.enabled?e.sortablePropertiesWithTypes:{}}function WU(e,t){let n=t;if(!n.enabled)return{enabled:!1};let r=Object.keys(n.sorts).reduce((e,t)=>{let{docs:r,orderedDocs:i,type:a}=n.sorts[t];return e[t]={docs:new Map(Object.entries(r).map(([e,t])=>[+e,t])),orderedDocsToRemove:new Map,orderedDocs:i,type:a},e},{});return{sharedInternalDocumentStore:e,language:n.language,sortableProperties:n.sortableProperties,sortablePropertiesWithTypes:n.sortablePropertiesWithTypes,sorts:r,enabled:!0,isSorted:n.isSorted}}function GU(e){if(!e.enabled)return{enabled:!1};RU(e),NU(e);let t=Object.keys(e.sorts).reduce((t,n)=>{let{docs:r,orderedDocs:i,type:a}=e.sorts[n];return t[n]={docs:Object.fromEntries(r.entries()),orderedDocs:i,type:a},t},{});return{language:e.language,sortableProperties:e.sortableProperties,sortablePropertiesWithTypes:e.sortablePropertiesWithTypes,sorts:t,enabled:e.enabled,isSorted:e.isSorted}}function KU(){return{create:jU,insert:MU,remove:BU,save:GU,load:WU,sortBy:VU,getSortableProperties:HU,getSortablePropertiesWithTypes:UU}}const qU=[65,65,65,65,65,65,65,67,69,69,69,69,73,73,73,73,69,78,79,79,79,79,79,null,79,85,85,85,85,89,80,115,97,97,97,97,97,97,97,99,101,101,101,101,105,105,105,105,101,110,111,111,111,111,111,null,111,117,117,117,117,121,112,121,65,97,65,97,65,97,67,99,67,99,67,99,67,99,68,100,68,100,69,101,69,101,69,101,69,101,69,101,71,103,71,103,71,103,71,103,72,104,72,104,73,105,73,105,73,105,73,105,73,105,73,105,74,106,75,107,107,76,108,76,108,76,108,76,108,76,108,78,110,78,110,78,110,110,78,110,79,111,79,111,79,111,79,111,82,114,82,114,82,114,83,115,83,115,83,115,83,115,84,116,84,116,84,116,85,117,85,117,85,117,85,117,85,117,85,117,87,119,89,121,89,90,122,90,122,90,122,115];function JU(e){return e<192||e>383?e:qU[e-192]||e}function YU(e){let t=[];for(let n=0;n<e.length;n++)t[n]=JU(e.charCodeAt(n));return String.fromCharCode(...t)}const XU={ational:`ate`,tional:`tion`,enci:`ence`,anci:`ance`,izer:`ize`,bli:`ble`,alli:`al`,entli:`ent`,eli:`e`,ousli:`ous`,ization:`ize`,ation:`ate`,ator:`ate`,alism:`al`,iveness:`ive`,fulness:`ful`,ousness:`ous`,aliti:`al`,iviti:`ive`,biliti:`ble`,logi:`log`},ZU={icate:`ic`,ative:``,alize:`al`,iciti:`ic`,ical:`ic`,ful:``,ness:``},QU=`[aeiouy]`,$U=`[^aeiou][^aeiouy]*`;QU+``;const eW=`^(`+$U+`)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*`;``+$U;const tW=`^(`+$U+`)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*[aeiouy][aeiou]*[^aeiou][^aeiouy]*`,nW=`^(`+$U+`)?[aeiouy]`;function rW(e){let t,n,r,i,a,o;if(e.length<3)return e;let s=e.substring(0,1);if(s==`y`&&(e=s.toUpperCase()+e.substring(1)),r=/^(.+?)(ss|i)es$/,i=/^(.+?)([^s])s$/,r.test(e)?e=e.replace(r,`$1$2`):i.test(e)&&(e=e.replace(i,`$1$2`)),r=/^(.+?)eed$/,i=/^(.+?)(ed|ing)$/,r.test(e)){let t=r.exec(e);r=new RegExp(eW),r.test(t[1])&&(r=/.$/,e=e.replace(r,``))}else i.test(e)&&(t=i.exec(e)[1],i=new RegExp(nW),i.test(t)&&(e=t,i=/(at|bl|iz)$/,a=RegExp(`([^aeiouylsz])\\1$`),o=RegExp(`^`+$U+QU+`[^aeiouwxy]$`),i.test(e)?e+=`e`:a.test(e)?(r=/.$/,e=e.replace(r,``)):o.test(e)&&(e+=`e`)));if(r=/^(.+?)y$/,r.test(e)&&(t=r.exec(e)?.[1],r=new RegExp(nW),t&&r.test(t)&&(e=t+`i`)),r=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,r.test(e)){let i=r.exec(e);t=i?.[1],n=i?.[2],r=new RegExp(eW),t&&r.test(t)&&(e=t+XU[n])}if(r=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,r.test(e)){let i=r.exec(e);t=i?.[1],n=i?.[2],r=new RegExp(eW),t&&r.test(t)&&(e=t+ZU[n])}if(r=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/,i=/^(.+?)(s|t)(ion)$/,r.test(e))t=r.exec(e)?.[1],r=new RegExp(tW),t&&r.test(t)&&(e=t);else if(i.test(e)){let n=i.exec(e);t=n?.[1]??``+n?.[2]??``,i=new RegExp(tW),i.test(t)&&(e=t)}return r=/^(.+?)e$/,r.test(e)&&(t=r.exec(e)?.[1],r=new RegExp(tW),i=RegExp(`^([^aeiou][^aeiouy]*)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*([aeiouy][aeiou]*)?$`),a=RegExp(`^`+$U+QU+`[^aeiouwxy]$`),t&&(r.test(t)||i.test(t)&&!a.test(t))&&(e=t)),r=/ll$/,i=new RegExp(tW),r.test(e)&&i.test(e)&&(r=/.$/,e=e.replace(r,``)),s==`y`&&(e=s.toLowerCase()+e.substring(1)),e}function iW(e,t,n=!0){let r=`${this.language}:${e}:${t}`;return n&&this.normalizationCache.has(r)?this.normalizationCache.get(r):this.stopWords?.includes(t)?(n&&this.normalizationCache.set(r,``),``):(this.stemmer&&!this.stemmerSkipProperties.has(e)&&(t=this.stemmer(t)),t=YU(t),n&&this.normalizationCache.set(r,t),t)}function aW(e){for(;e[e.length-1]===``;)e.pop();for(;e[0]===``;)e.shift();return e}function oW(e,t,n,r=!0){if(t&&t!==this.language)throw fH(`LANGUAGE_NOT_SUPPORTED`,t);if(typeof e!=`string`)return[e];let i=this.normalizeToken.bind(this,n??``),a;if(n&&this.tokenizeSkipProperties.has(n))a=[i(e,r)];else{let t=NV[this.language];a=e.toLowerCase().split(t).map(e=>i(e,r)).filter(Boolean)}let o=aW(a);return this.allowDuplicates?o:Array.from(new Set(o))}function sW(e={}){if(!e.language)e.language=`english`;else if(!PV.includes(e.language))throw fH(`LANGUAGE_NOT_SUPPORTED`,e.language);let t;if(e.stemming||e.stemmer&&!(`stemming`in e))if(e.stemmer){if(typeof e.stemmer!=`function`)throw fH(`INVALID_STEMMER_FUNCTION_TYPE`);t=e.stemmer}else if(e.language===`english`)t=rW;else throw fH(`MISSING_STEMMER`,e.language);let n;if(e.stopWords!==!1){if(n=[],Array.isArray(e.stopWords))n=e.stopWords;else if(typeof e.stopWords==`function`)n=e.stopWords(n);else if(e.stopWords)throw fH(`CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY`);if(!Array.isArray(n))throw fH(`CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY`);for(let e of n)if(typeof e!=`string`)throw fH(`CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY`)}let r={tokenize:oW,language:e.language,stemmer:t,stemmerSkipProperties:new Set(e.stemmerSkipProperties?[e.stemmerSkipProperties].flat():[]),tokenizeSkipProperties:new Set(e.tokenizeSkipProperties?[e.tokenizeSkipProperties].flat():[]),stopWords:n,allowDuplicates:!!e.allowDuplicates,normalizeToken:iW,normalizationCache:new Map};return r.tokenize=oW.bind(r),r.normalizeToken=iW,r}function cW(e){return{sharedInternalDocumentStore:e,rules:new Map}}function lW(e,t){if(e.rules.has(t.id))throw Error(`PINNING_RULE_ALREADY_EXISTS: A pinning rule with id "${t.id}" already exists. Use updateRule to modify it.`);e.rules.set(t.id,t)}function uW(e,t){if(!e.rules.has(t.id))throw Error(`PINNING_RULE_NOT_FOUND: Cannot update pinning rule with id "${t.id}" because it does not exist. Use addRule to create it.`);e.rules.set(t.id,t)}function dW(e,t){return e.rules.delete(t)}function fW(e,t){return e.rules.get(t)}function pW(e){return Array.from(e.rules.values())}function mW(e,t){let n=e.toLowerCase().trim(),r=t.pattern.toLowerCase().trim();switch(t.anchoring){case`is`:return n===r;case`starts_with`:return n.startsWith(r);case`contains`:return n.includes(r);default:return!1}}function hW(e,t){return e?t.conditions.every(t=>mW(e,t)):!1}function gW(e,t){if(!t)return[];let n=[];for(let r of e.rules.values())hW(t,r)&&n.push(r);return n}function _W(e,t){return{sharedInternalDocumentStore:e,rules:new Map(t?.rules??[])}}function vW(e){return{rules:Array.from(e.rules.entries())}}function yW(){return{create:cW,addRule:lW,updateRule:uW,removeRule:dW,getRule:fW,getAllRules:pW,getMatchingRules:gW,load:_W,save:vW}}function bW(e){let t={formatElapsedTime:pH,getDocumentIndexId:mH,getDocumentProperties:$V,validateSchema:hH};for(let n of VH){let r=n;if(e[r]){if(typeof e[r]!=`function`)throw fH(`COMPONENT_MUST_BE_FUNCTION`,r)}else e[r]=t[r]}for(let t of Object.keys(e))if(!BH.includes(t)&&!VH.includes(t))throw fH(`UNSUPPORTED_COMPONENT`,t)}function xW({schema:e,sort:t,language:n,components:r,id:i,plugins:a}){r||={};for(let t of a??[]){if(!(`getComponents`in t)||typeof t.getComponents!=`function`)continue;let n=t.getComponents(e),i=Object.keys(n);for(let e of i)if(r[e])throw fH(`PLUGIN_COMPONENT_CONFLICT`,e,t.name);r={...r,...n}}i||=YV();let o=r.tokenizer,s=r.index,c=r.documentsStore,l=r.sorter,u=r.pinning;if(o=o?o.tokenize?o:sW(o):sW({language:n??`english`}),r.tokenizer&&n)throw fH(`NO_LANGUAGE_WITH_CUSTOM_TOKENIZER`);let d=CH();s||=wU(),l||=KU(),c||=LH(),u||=yW(),bW(r);let{getDocumentProperties:f,getDocumentIndexId:p,validateSchema:m,formatElapsedTime:h}=r,g={data:{},caches:{},schema:e,tokenizer:o,index:s,sorter:l,documentsStore:c,pinning:u,internalDocumentIDStore:d,getDocumentProperties:f,getDocumentIndexId:p,validateSchema:m,beforeInsert:[],afterInsert:[],beforeRemove:[],afterRemove:[],beforeUpdate:[],afterUpdate:[],beforeUpsert:[],afterUpsert:[],beforeSearch:[],afterSearch:[],beforeInsertMultiple:[],afterInsertMultiple:[],beforeRemoveMultiple:[],afterRemoveMultiple:[],beforeUpdateMultiple:[],afterUpdateMultiple:[],beforeUpsertMultiple:[],afterUpsertMultiple:[],afterCreate:[],formatElapsedTime:h,id:i,plugins:a,version:SW()};g.data={index:g.index.create(g,d,e),docs:g.documentsStore.create(g,d),sorting:g.sorter.create(g,d,e,t),pinning:g.pinning.create(d)};for(let e of RH)g[e]=(g[e]??[]).concat(zH(g,e));let _=g.afterCreate;return _&&KH(_,g),g}function SW(){return`{{VERSION}}`}function CW(e){return e.documentsStore.count(e.data.docs)}function wW(e,t,n,r,i){let a=e.validateSchema(t,e.schema);if(a)throw fH(`SCHEMA_VALIDATION_FAILURE`,a);return iH(e.beforeInsert)||iH(e.afterInsert)||iH(e.index.beforeInsert)||iH(e.index.insert)||iH(e.index.afterInsert)?DW(e,t,n,r,i):OW(e,t,n,r,i)}const TW=new Set([`enum`,`enum[]`]),EW=new Set([`string`,`number`]);async function DW(e,t,n,r,i){let{index:a,docs:o}=e.data,s=e.getDocumentIndexId(t);if(typeof s!=`string`)throw fH(`DOCUMENT_ID_MUST_BE_STRING`,typeof s);let c=EH(e.internalDocumentIDStore,s);if(r||await HH(e.beforeInsert,e,s,t),!e.documentsStore.store(o,s,c,t))throw fH(`DOCUMENT_ALREADY_EXISTS`,s);let l=e.documentsStore.count(o),u=e.index.getSearchableProperties(a),d=e.index.getSearchablePropertiesWithTypes(a),f=e.getDocumentProperties(t,u);for(let[e,t]of Object.entries(f)){if(t===void 0)continue;let n=typeof t,r=d[e];kW(n,r,e,t)}return await AW(e,s,u,f,l,n,t,i),r||await HH(e.afterInsert,e,s,t),s}function OW(e,t,n,r,i){let{index:a,docs:o}=e.data,s=e.getDocumentIndexId(t);if(typeof s!=`string`)throw fH(`DOCUMENT_ID_MUST_BE_STRING`,typeof s);let c=EH(e.internalDocumentIDStore,s);if(r||HH(e.beforeInsert,e,s,t),!e.documentsStore.store(o,s,c,t))throw fH(`DOCUMENT_ALREADY_EXISTS`,s);let l=e.documentsStore.count(o),u=e.index.getSearchableProperties(a),d=e.index.getSearchablePropertiesWithTypes(a),f=e.getDocumentProperties(t,u);for(let[e,t]of Object.entries(f)){if(t===void 0)continue;let n=typeof t,r=d[e];kW(n,r,e,t)}return jW(e,s,u,f,l,n,t,i),r||HH(e.afterInsert,e,s,t),s}function kW(e,t,n,r){if(!(vH(t)&&typeof r==`object`&&typeof r.lon==`number`&&typeof r.lat==`number`)&&!(yH(t)&&Array.isArray(r))&&!(bH(t)&&Array.isArray(r))&&!(TW.has(t)&&EW.has(e))&&e!==t)throw fH(`INVALID_DOCUMENT_PROPERTY`,n,t,e)}async function AW(e,t,n,r,i,a,o,s){for(let o of n){let n=r[o];if(n===void 0)continue;let c=e.index.getSearchablePropertiesWithTypes(e.data.index)[o];await e.index.beforeInsert?.(e.data.index,o,t,n,c,a,e.tokenizer,i);let l=e.internalDocumentIDStore.idToInternalId.get(t);await e.index.insert(e.index,e.data.index,o,t,l,n,c,a,e.tokenizer,i,s),await e.index.afterInsert?.(e.data.index,o,t,n,c,a,e.tokenizer,i)}let c=e.sorter.getSortableProperties(e.data.sorting),l=e.getDocumentProperties(o,c);for(let n of c){let r=l[n];if(r===void 0)continue;let i=e.sorter.getSortablePropertiesWithTypes(e.data.sorting)[n];e.sorter.insert(e.data.sorting,n,t,r,i,a)}}function jW(e,t,n,r,i,a,o,s){for(let o of n){let n=r[o];if(n===void 0)continue;let c=e.index.getSearchablePropertiesWithTypes(e.data.index)[o],l=EH(e.internalDocumentIDStore,t);e.index.beforeInsert?.(e.data.index,o,t,n,c,a,e.tokenizer,i),e.index.insert(e.index,e.data.index,o,t,l,n,c,a,e.tokenizer,i,s),e.index.afterInsert?.(e.data.index,o,t,n,c,a,e.tokenizer,i)}let c=e.sorter.getSortableProperties(e.data.sorting),l=e.getDocumentProperties(o,c);for(let n of c){let r=l[n];if(r===void 0)continue;let i=e.sorter.getSortablePropertiesWithTypes(e.data.sorting)[n];e.sorter.insert(e.data.sorting,n,t,r,i,a)}}function MW(e,t,n,r,i,a){return iH(e.afterInsertMultiple)||iH(e.beforeInsertMultiple)||iH(e.index.beforeInsert)||iH(e.index.insert)||iH(e.index.afterInsert)?NW(e,t,n,r,i,a):PW(e,t,n,r,i,a)}async function NW(e,t,n=1e3,r,i,a=0){let o=[],s=async a=>{let s=Math.min(a+n,t.length),c=t.slice(a,s);for(let t of c){let n=await wW(e,t,r,i,{avlRebalanceThreshold:c.length});o.push(n)}return s};return await(async()=>{let e=0;for(;e<t.length;){let t=Date.now();if(e=await s(e),a>0){let e=a-(Date.now()-t);e>0&&uH(e)}}})(),i||await UH(e.afterInsertMultiple,e,t),o}function PW(e,t,n=1e3,r,i,a=0){let o=[],s=0;function c(){let a=t.slice(s*n,(s+1)*n);if(a.length===0)return!1;for(let t of a){let n=wW(e,t,r,i,{avlRebalanceThreshold:a.length});o.push(n)}return s++,!0}function l(){let e=Date.now();for(;c();)if(a>0){let t=Date.now()-e;if(t>=a){let e=a-t%a;e>0&&uH(e)}}}return l(),i||UH(e.afterInsertMultiple,e,t),o}function FW(e,t){return e[1]-t[1]}function IW(e,t){return t[1]-e[1]}function LW(e=`desc`){return e.toLowerCase()===`asc`?FW:IW}function RW(e,t,n){let r={},i=t.map(([e])=>e),a=e.documentsStore.getMultiple(e.data.docs,i),o=Object.keys(n),s=e.index.getSearchablePropertiesWithTypes(e.data.index);for(let e of o){let t;if(s[e]===`number`){let{ranges:r}=n[e],i=r.length,a=Array.from({length:i});for(let e=0;e<i;e++){let t=r[e];a[e]=[`${t.from}-${t.to}`,0]}t=Object.fromEntries(a)}r[e]={count:0,values:t??{}}}let c=a.length;for(let e=0;e<c;e++){let t=a[e];for(let e of o){let i=e.includes(`.`)?eH(t,e):t[e],a=s[e],o=r[e].values;switch(a){case`number`:{let t=n[e].ranges;zW(t,o)(i);break}case`number[]`:{let t=new Set,r=n[e].ranges,a=zW(r,o,t);for(let e of i)a(e);break}case`boolean`:case`enum`:case`string`:BW(o,a)(i);break;case`boolean[]`:case`enum[]`:case`string[]`:{let e=BW(o,a===`boolean[]`?`boolean`:`string`,new Set);for(let t of i)e(t);break}default:throw fH(`FACET_NOT_SUPPORTED`,a)}}}for(let e of o){let t=r[e];if(t.count=Object.keys(t.values).length,s[e]===`string`){let r=n[e],i=LW(r.sort);t.values=Object.fromEntries(Object.entries(t.values).sort(i).slice(r.offset??0,r.limit??10))}}return r}function zW(e,t,n){return r=>{for(let i of e){let e=`${i.from}-${i.to}`;n?.has(e)||r>=i.from&&r<=i.to&&(t[e]===void 0?t[e]=1:(t[e]++,n?.add(e)))}}}function BW(e,t,n){let r=t===`boolean`?`false`:``;return t=>{let i=t?.toString()??r;n?.has(i)||(e[i]=(e[i]??0)+1,n?.add(i))}}const VW={reducer:(e,t,n,r)=>(t[r]=n,t),getInitialValue:e=>Array.from({length:e})},HW=[`string`,`number`,`boolean`];function UW(e,t,n){let r=n.properties,i=r.length,a=e.index.getSearchablePropertiesWithTypes(e.data.index);for(let e=0;e<i;e++){let t=r[e];if(a[t]===void 0)throw fH(`UNKNOWN_GROUP_BY_PROPERTY`,t);if(!HW.includes(a[t]))throw fH(`INVALID_GROUP_BY_PROPERTY`,t,HW.join(`, `),a[t])}let o=t.map(([t])=>DH(e.internalDocumentIDStore,t)),s=e.documentsStore.getMultiple(e.data.docs,o),c=s.length,l=n.maxResult||2**53-1,u=[],d={};for(let e=0;e<i;e++){let t=r[e],n={property:t,perValue:{}},i=new Set;for(let e=0;e<c;e++){let r=s[e],a=eH(r,t);if(a===void 0)continue;let o=typeof a==`boolean`?``+a:a,c=n.perValue[o]??{indexes:[],count:0};c.count>=l||(c.indexes.push(e),c.count++,n.perValue[o]=c,i.add(a))}u.push(Array.from(i)),d[t]=n}let f=WW(u),p=f.length,m=[];for(let e=0;e<p;e++){let t=f[e],n=t.length,i={values:[],indexes:[]},a=[];for(let e=0;e<n;e++){let n=t[e],o=r[e];a.push(d[o].perValue[typeof n==`boolean`?``+n:n].indexes),i.values.push(n)}i.indexes=QV(a).sort((e,t)=>e-t),i.indexes.length!==0&&m.push(i)}let h=m.length,g=Array.from({length:h});for(let e=0;e<h;e++){let r=m[e],i=n.reduce||VW,a=r.indexes.map(e=>({id:o[e],score:t[e][1],document:s[e]})),c=i.reducer.bind(null,r.values),l=i.getInitialValue(r.indexes.length),u=a.reduce(c,l);g[e]={values:r.values,result:u}}return g}function WW(e,t=0){if(t+1===e.length)return e[t].map(e=>[e]);let n=e[t],r=WW(e,t+1),i=[];for(let e of n)for(let t of r){let n=[e];HV(n,t),i.push(n)}return i}function GW(e,t,n,r){let i=gW(t,r);if(i.length===0)return n;let a=i.flatMap(e=>e.consequence.promote);a.sort((e,t)=>e.position-t.position);let o=new Set,s=new Map,c=new Set;for(let t of a){let n=EH(e.internalDocumentIDStore,t.doc_id);if(n!==void 0){if(s.has(n)){let e=s.get(n);t.position<e&&s.set(n,t.position);continue}c.has(t.position)||(o.add(n),s.set(n,t.position),c.add(t.position))}}if(s.size===0)return n;let l=n.filter(([e])=>!o.has(e)),u=[];for(let[t,r]of s.entries())n.find(([e])=>e===t)?u.push([t,1e6-r]):e.documentsStore.get(e.data.docs,t)&&u.push([t,0]);u.sort((e,t)=>(s.get(e[0])??1/0)-(s.get(t[0])??1/0));let d=[],f=new Map;for(let e of u){let t=s.get(e[0]);f.set(t,e)}let p=0,m=0;for(;m<l.length+u.length;)if(f.has(m))d.push(f.get(m)),m++;else if(p<l.length)d.push(l[p]),p++,m++;else break;for(let[e,t]of f.entries())e>=d.length&&d.push(t);return d}function KW(e,t,n){let{term:r,properties:i}=t,a=e.data.index,o=e.caches.propertiesToSearch;if(!o){let t=e.index.getSearchablePropertiesWithTypes(a);o=e.index.getSearchableProperties(a),o=o.filter(e=>t[e].startsWith(`string`)),e.caches.propertiesToSearch=o}if(i&&i!==`*`){for(let e of i)if(!o.includes(e))throw fH(`UNKNOWN_INDEX`,e,o.join(`, `));o=o.filter(e=>i.includes(e))}let s=Object.keys(t.where??{}).length>0,c;s&&(c=e.index.searchByWhereClause(a,e.tokenizer,t.where,n));let l,u=t.threshold!==void 0&&t.threshold!==null?t.threshold:1;if(r||i){let i=CW(e);if(l=e.index.search(a,r||``,e.tokenizer,n,o,t.exact||!1,t.tolerance||0,t.boost||{},ZW(t.relevance),i,c,u),t.exact&&r){let t=r.trim().split(/\s+/);l=l.filter(([n])=>{let r=e.documentsStore.get(e.data.docs,n);if(!r)return!1;for(let e of o){let n=JW(r,e);if(typeof n==`string`&&t.every(e=>RegExp(`\\b${qW(e)}\\b`).test(n)))return!0}return!1})}}else l=s?OU(a,t.where)||(c?Array.from(c):[]).map(e=>[+e,0]):Object.keys(e.documentsStore.getAll(e.data.docs)).map(e=>[+e,0]);return l}function qW(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function JW(e,t){let n=t.split(`.`),r=e;for(let e of n)if(r&&typeof r==`object`&&e in r)r=r[e];else return;return r}function YW(e,t,n){let r=JV();function i(){let i=Object.keys(e.data.index.vectorIndexes),a=t.facets&&Object.keys(t.facets).length>0,{limit:o=10,offset:s=0,distinctOn:c,includeVectors:l=!1}=t,u=t.preflight===!0,d=KW(e,t,n);if(t.sortBy)if(typeof t.sortBy==`function`){let n=d.map(([e])=>e),r=e.documentsStore.getMultiple(e.data.docs,n).map((e,t)=>[d[t][0],d[t][1],e]);r.sort(t.sortBy),d=r.map(([e,t])=>[e,t])}else d=e.sorter.sortBy(e.data.sorting,d,t.sortBy).map(([t,n])=>[EH(e.internalDocumentIDStore,t),n]);else d=d.sort(ZV);d=GW(e,e.data.pinning,d,t.term);let f;u||(f=c?lG(e,d,s,o,c):uG(e,d,s,o));let p={elapsed:{formatted:``,raw:0},hits:[],count:d.length};return f!==void 0&&(p.hits=f.filter(Boolean),l||rH(p,i)),a&&(p.facets=RW(e,d,t.facets)),t.groupBy&&(p.groups=UW(e,d,t.groupBy)),p.elapsed=e.formatElapsedTime(JV()-r),p}async function a(){e.beforeSearch&&await GH(e.beforeSearch,e,t,n);let r=i();return e.afterSearch&&await WH(e.afterSearch,e,t,n,r),r}return e.beforeSearch?.length||e.afterSearch?.length?a():i()}const XW={k:1.2,b:.75,d:.5};function ZW(e){let t=e??{};return t.k=t.k??XW.k,t.b=t.b??XW.b,t.d=t.d??XW.d,t}function QW(e,t,n){let r=t.vector;if(r&&(!(`value`in r)||!(`property`in r)))throw fH(`INVALID_VECTOR_INPUT`,Object.keys(r).join(`, `));let i=e.data.index.vectorIndexes[r.property];if(!i)throw fH(`UNKNOWN_VECTOR_PROPERTY`,r.property);let a=i.node.size;if(r?.value.length!==a)throw r?.property===void 0||r?.value.length===void 0?fH(`INVALID_INPUT_VECTOR`,`undefined`,a,`undefined`):fH(`INVALID_INPUT_VECTOR`,r.property,a,r.value.length);let o=e.data.index,s;return Object.keys(t.where??{}).length>0&&(s=e.index.searchByWhereClause(o,e.tokenizer,t.where,n)),i.node.find(r.value,t.similarity??.8,s)}function $W(e,t,n=`english`){let r=JV();function i(){let i=QW(e,t,n).sort(ZV);i=GW(e,e.data.pinning,i,void 0);let a=[];t.facets&&Object.keys(t.facets).length>0&&(a=RW(e,i,t.facets));let o=t.vector.property,s=t.includeVectors??!1,c=t.limit??10,l=t.offset??0,u=Array.from({length:c});for(let t=0;t<c;t++){let n=i[t+l];if(!n)break;let r=e.data.docs.docs[n[0]];r&&(s||(r[o]=null),u[t]={id:DH(e.internalDocumentIDStore,n[0]),score:n[1],document:r})}let d=[];t.groupBy&&(d=UW(e,i,t.groupBy));let f=JV()-r;return{count:i.length,hits:u.filter(Boolean),elapsed:{raw:Number(f),formatted:qV(f)},...a?{facets:a}:{},...d?{groups:d}:{}}}async function a(){e.beforeSearch&&await GH(e.beforeSearch,e,t,n);let r=i();return e.afterSearch&&await WH(e.afterSearch,e,t,n,r),r}return e.beforeSearch?.length||e.afterSearch?.length?a():i()}function eG(e,t,n){let r=rG(KW(e,t,n)),i=QW(e,t,n),a=t.hybridWeights;return oG(r,i,t.term??``,a)}function tG(e,t,n){let r=JV();function i(){let i=eG(e,t,n);i=GW(e,e.data.pinning,i,t.term);let a;t.facets&&Object.keys(t.facets).length>0&&(a=RW(e,i,t.facets));let o;t.groupBy&&(o=UW(e,i,t.groupBy));let s=t.offset??0,c=t.limit??10,l=uG(e,i,s,c).filter(Boolean),u=JV(),d={count:i.length,elapsed:{raw:Number(u-r),formatted:qV(u-r)},hits:l,...a?{facets:a}:{},...o?{groups:o}:{}};return(t.includeVectors??!1)||rH(d,Object.keys(e.data.index.vectorIndexes)),d}async function a(){e.beforeSearch&&await GH(e.beforeSearch,e,t,n);let r=i();return e.afterSearch&&await WH(e.afterSearch,e,t,n,r),r}return e.beforeSearch?.length||e.afterSearch?.length?a():i()}function nG(e){return e[1]}function rG(e){let t=Math.max.apply(Math,e.map(nG));return e.map(([e,n])=>[e,n/t])}function iG(e,t){return e/t}function aG(e,t){return(n,r)=>n*e+r*t}function oG(e,t,n,r){let i=Math.max.apply(Math,e.map(nG)),a=Math.max.apply(Math,t.map(nG)),{text:o,vector:s}=r&&r.text&&r.vector?r:sG(n),c=new Map,l=e.length,u=aG(o,s);for(let t=0;t<l;t++){let[n,r]=e[t],a=u(iG(r,i),0);c.set(n,a)}let d=t.length;for(let e=0;e<d;e++){let[n,r]=t[e],i=iG(r,a),o=c.get(n)??0;c.set(n,o+u(0,i))}return[...c].sort((e,t)=>t[1]-e[1])}function sG(e){return{text:.5,vector:.5}}function cG(e,t,n){let r=t.mode??`fulltext`;if(r===`fulltext`)return YW(e,t,n);if(r===`vector`)return $W(e,t);if(r===`hybrid`)return tG(e,t);throw fH(`INVALID_SEARCH_MODE`,r)}function lG(e,t,n,r,i){let a=e.data.docs,o=new Map,s=[],c=new Set,l=t.length,u=0;for(let d=0;d<l;d++){let l=t[d];if(l===void 0)continue;let[f,p]=l;if(c.has(f))continue;let m=e.documentsStore.get(a,f),h=eH(m,i);if(!(h===void 0||o.has(h))&&(o.set(h,!0),u++,!(u<=n)&&(s.push({id:DH(e.internalDocumentIDStore,f),score:p,document:m}),c.add(f),u>=n+r)))break}return s}function uG(e,t,n,r){let i=e.data.docs,a=Array.from({length:r}),o=new Set;for(let s=n;s<r+n;s++){let n=t[s];if(n===void 0)break;let[r,c]=n;if(!o.has(r)){let t=e.documentsStore.get(i,r);a[s]={id:DH(e.internalDocumentIDStore,r),score:c,document:t},o.add(r)}}return a}var dG=n(DV(),1);const fG=1,pG={protocol:`x-ok-client-protocol`,runtime:`x-ok-client-runtime`,kind:`x-ok-client-kind`};function mG({kind:e,runtimeVersion:t}){return{[pG.protocol]:`1`,[pG.runtime]:t,[pG.kind]:e}}const hG=`__system__`,gG=1,_G=`__config__/project`,vG=`__user__/config.yml`,yG=`__local__/project`,bG=`__config__/okignore`,xG=Object.freeze([_G,yG,vG,bG]),SG=`__skill__/`,CG=`__template__/`,wG=[`project`,`global`];function TG(e){return e.startsWith(`__skill__/`)||e.startsWith(`__template__/`)}const EG=`.ok/skills`;function DG(e){return`${EG}/${e}/SKILL`}const OG=[`references`,`scripts`];function kG(e,t){let n=/^(\.ok\/skills\/[^/]+)\/SKILL$/.exec(t);if(!n)return null;let r=n[1],i=e.trim().replace(/\.mdx?$/i,``).split(`/`).filter(e=>e!==``&&e!==`.`),[a]=i;return!a||!OG.includes(a)||i.includes(`..`)||i.length<2?null:`${r}/${i.join(`/`)}`}const AG=/^\.ok\/skills\/([^/]+)\/(SKILL|references\/.+)$/;function jG(e){let t=AG.exec(e);if(!t)return null;let n=t[1],r=t[2];return r===`SKILL`?{name:n,kind:`skill`,rel:null}:{name:n,kind:`reference`,rel:r.slice(11)}}const MG=/^__skill__\/global\/([^/]+)(?:\/(references\/.+))?$/;function NG(e){let t=MG.exec(e);if(!t)return null;let n=t[1],r=t[2];return r===void 0?{name:n,kind:`skill`,rel:null}:{name:n,kind:`reference`,rel:r.slice(11)}}function PG(e,t){return e===`project`?DG(t):`${SG}${e}/${t}`}function FG(e){if(e===``)return``;try{return e.split(`/`).map(e=>decodeURIComponent(e)).join(`/`)}catch{return e}}function IG(e){if(e.startsWith(`__skill__/`)){let t=e.slice(10),n=t.indexOf(`/`);if(n<0)return null;let r=t.slice(0,n);if(r!==`global`&&r!==`project`)return null;let i=t.slice(n+1);return i?{kind:`skill`,scope:r,name:FG(i)}:null}if(e.startsWith(`__template__/`)){let t=e.slice(13);if(!t)return null;let n=t.lastIndexOf(`/`),r=n<0?t:t.slice(n+1);return r?{kind:`template`,folder:FG(n<0?``:t.slice(0,n)),name:FG(r)}:null}return null}const LG=/^(?:(.+)\/)?\.ok\/templates\/([^/]+?)(?:\.mdx?)?$/;function RG(e){let t=LG.exec(e);if(t){let e=(t[1]??``).replace(/^\/+|\/+$/g,``);return`${CG}${e?`${e}/`:``}${t[2]}`}return null}const zG=[`.mdx`,`.md`],BG=`epoch`,VG=512*1024,HG=[`claude`,`claude-desktop`,`cursor`,`codex`,`opencode`,`openclaw`],UG={claude:`Claude`,"claude-desktop":`Claude Desktop`,cursor:`Cursor`,codex:`Codex`,opencode:`OpenCode`,openclaw:`OpenClaw`},WG={claude:`.claude/skills`,"claude-desktop":null,cursor:`.cursor/skills`,codex:`.codex/skills`,opencode:`.opencode/skills`,openclaw:null},GG=HG.filter(e=>WG[e]!==null),KG=GG.map(e=>({hostDir:(WG[e]??``).split(`/`)[0],editorId:e})),qG={claude:`.mcp.json`,"claude-desktop":null,cursor:`.cursor/mcp.json`,codex:`.codex/config.toml`,opencode:`opencode.json`,openclaw:null},JG={cursor:/\bCursor(?:\([^)]+\))?\/\d/,codex:/\bCodex(?:\([^)]+\))?\/\d/,"claude-desktop":/\bClaude(?:\([^)]+\))?\/\d/},YG=`Ov23liqlSd0V1MwR6rhI`,XG=[`incoming`,`outgoing`,`both`];function ZG(e){return XG.includes(e)}const QG=`open-knowledge`,$G=[{id:`chart`,title:`Chart`,description:`A bar chart whose series colors track the OK chart palette.`,html:`<div style="font-family:system-ui,sans-serif;padding:20px;color:var(--foreground)">
|
|
304
|
+
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:`The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.`,PLUGIN_COMPONENT_CONFLICT:`The component "%s" is already defined. The plugin "%s" is trying to redefine it.`};function fH(e,...t){let n=Error(UV(dH[e]??`Unsupported Orama Error code: ${e}`,...t));return n.code=e,`captureStackTrace`in Error.prototype&&Error.captureStackTrace(n),n}function pH(e){return{raw:Number(e),formatted:qV(e)}}function mH(e){if(e.id){if(typeof e.id!=`string`)throw fH(`DOCUMENT_ID_MUST_BE_STRING`,typeof e.id);return e.id}return YV()}function hH(e,t){for(let[n,r]of Object.entries(t)){let t=e[n];if(t!==void 0&&!(r===`geopoint`&&typeof t==`object`&&typeof t.lon==`number`&&typeof t.lat==`number`)&&!(r===`enum`&&(typeof t==`string`||typeof t==`number`))){if(r===`enum[]`&&Array.isArray(t)){let e=t.length;for(let r=0;r<e;r++)if(typeof t[r]!=`string`&&typeof t[r]!=`number`)return n+`.`+r;continue}if(yH(r)){let e=SH(r);if(!Array.isArray(t)||t.length!==e)throw fH(`INVALID_INPUT_VECTOR`,n,e,t.length);continue}if(bH(r)){if(!Array.isArray(t))return n;let e=xH(r),i=t.length;for(let r=0;r<i;r++)if(typeof t[r]!==e)return n+`.`+r;continue}if(typeof r==`object`){if(!t||typeof t!=`object`)return n;let e=hH(t,r);if(e)return n+`.`+e;continue}if(typeof t!==r)return n}}}const gH={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},_H={"string[]":`string`,"number[]":`number`,"boolean[]":`boolean`,"enum[]":`enum`};function vH(e){return e===`geopoint`}function yH(e){return typeof e==`string`&&/^vector\[\d+\]$/.test(e)}function bH(e){return typeof e==`string`&&gH[e]}function xH(e){return _H[e]}function SH(e){let t=Number(e.slice(7,-1));switch(!0){case isNaN(t):throw fH(`INVALID_VECTOR_VALUE`,e);case t<=0:throw fH(`INVALID_VECTOR_SIZE`,e);default:return t}}function CH(){return{idToInternalId:new Map,internalIdToId:[],save:wH,load:TH}}function wH(e){return{internalIdToId:e.internalIdToId}}function TH(e,t){let{internalIdToId:n}=t;e.internalDocumentIDStore.idToInternalId.clear(),e.internalDocumentIDStore.internalIdToId=[];let r=n.length;for(let t=0;t<r;t++){let r=n[t];e.internalDocumentIDStore.idToInternalId.set(r,t+1),e.internalDocumentIDStore.internalIdToId.push(r)}}function EH(e,t){if(typeof t==`string`){let n=e.idToInternalId.get(t);if(n)return n;let r=e.idToInternalId.size+1;return e.idToInternalId.set(t,r),e.internalIdToId.push(t),r}return t>e.internalIdToId.length?EH(e,t.toString()):t}function DH(e,t){if(e.internalIdToId.length<t)throw Error(`Invalid internalId ${t}`);return e.internalIdToId[t-1]}function OH(e,t){return{sharedInternalDocumentStore:t,docs:{},count:0}}function kH(e,t){let n=EH(e.sharedInternalDocumentStore,t);return e.docs[n]}function AH(e,t){let n=t.length,r=Array.from({length:n});for(let i=0;i<n;i++){let n=EH(e.sharedInternalDocumentStore,t[i]);r[i]=e.docs[n]}return r}function jH(e){return e.docs}function MH(e,t,n,r){return e.docs[n]===void 0?(e.docs[n]=r,e.count++,!0):!1}function NH(e,t){let n=EH(e.sharedInternalDocumentStore,t);return e.docs[n]===void 0?!1:(delete e.docs[n],e.count--,!0)}function PH(e){return e.count}function FH(e,t){let n=t;return{docs:n.docs,count:n.count,sharedInternalDocumentStore:e}}function IH(e){return{docs:e.docs,count:e.count}}function LH(){return{create:OH,get:kH,getMultiple:AH,getAll:jH,store:MH,remove:NH,count:PH,load:FH,save:IH}}const RH=[`beforeInsert`,`afterInsert`,`beforeRemove`,`afterRemove`,`beforeUpdate`,`afterUpdate`,`beforeUpsert`,`afterUpsert`,`beforeSearch`,`afterSearch`,`beforeInsertMultiple`,`afterInsertMultiple`,`beforeRemoveMultiple`,`afterRemoveMultiple`,`beforeUpdateMultiple`,`afterUpdateMultiple`,`beforeUpsertMultiple`,`afterUpsertMultiple`,`beforeLoad`,`afterLoad`,`afterCreate`];function zH(e,t){let n=[],r=e.plugins?.length;if(!r)return n;for(let i=0;i<r;i++)try{let r=e.plugins[i];typeof r[t]==`function`&&n.push(r[t])}catch(e){throw console.error(`Caught error in getAllPluginsByHook:`,e),fH(`PLUGIN_CRASHED`)}return n}const BH=[`tokenizer`,`index`,`documentsStore`,`sorter`,`pinning`],VH=[`validateSchema`,`getDocumentIndexId`,`getDocumentProperties`,`formatElapsedTime`];function HH(e,t,n,r){if(e.some(iH))return(async()=>{for(let i of e)await i(t,n,r)})();for(let i of e)i(t,n,r)}function UH(e,t,n){if(e.some(iH))return(async()=>{for(let r of e)await r(t,n)})();for(let r of e)r(t,n)}function WH(e,t,n,r,i){if(e.some(iH))return(async()=>{for(let a of e)await a(t,n,r,i)})();for(let a of e)a(t,n,r,i)}function GH(e,t,n,r){if(e.some(iH))return(async()=>{for(let i of e)await i(t,n,r)})();for(let i of e)i(t,n,r)}function KH(e,t){if(e.some(iH))return(async()=>{for(let n of e)await n(t)})();for(let n of e)n(t)}var qH=class e{k;v;l=null;r=null;h=1;constructor(e,t){this.k=e,this.v=new Set(t)}updateHeight(){this.h=Math.max(e.getHeight(this.l),e.getHeight(this.r))+1}static getHeight(e){return e?e.h:0}getBalanceFactor(){return e.getHeight(this.l)-e.getHeight(this.r)}rotateLeft(){let e=this.r;return this.r=e.l,e.l=this,this.updateHeight(),e.updateHeight(),e}rotateRight(){let e=this.l;return this.l=e.r,e.r=this,this.updateHeight(),e.updateHeight(),e}toJSON(){return{k:this.k,v:Array.from(this.v),l:this.l?this.l.toJSON():null,r:this.r?this.r.toJSON():null,h:this.h}}static fromJSON(t){let n=new e(t.k,t.v);return n.l=t.l?e.fromJSON(t.l):null,n.r=t.r?e.fromJSON(t.r):null,n.h=t.h,n}},JH=class e{root=null;insertCount=0;constructor(e,t){e!==void 0&&t!==void 0&&(this.root=new qH(e,t))}insert(e,t,n=1e3){this.root=this.insertNode(this.root,e,t,n)}insertMultiple(e,t,n=1e3){for(let r of t)this.insert(e,r,n)}rebalance(){this.root&&=this.rebalanceNode(this.root)}toJSON(){return{root:this.root?this.root.toJSON():null,insertCount:this.insertCount}}static fromJSON(t){let n=new e;return n.root=t.root?qH.fromJSON(t.root):null,n.insertCount=t.insertCount||0,n}insertNode(e,t,n,r){if(e===null)return new qH(t,[n]);let i=[],a=e,o=null;for(;a!==null;)if(i.push({parent:o,node:a}),t<a.k)if(a.l===null){a.l=new qH(t,[n]),i.push({parent:a,node:a.l});break}else o=a,a=a.l;else if(t>a.k)if(a.r===null){a.r=new qH(t,[n]),i.push({parent:a,node:a.r});break}else o=a,a=a.r;else return a.v.add(n),e;let s=!1;this.insertCount++%r===0&&(s=!0);for(let t=i.length-1;t>=0;t--){let{parent:n,node:r}=i[t];if(r.updateHeight(),s){let t=this.rebalanceNode(r);n?n.l===r?n.l=t:n.r===r&&(n.r=t):e=t}}return e}rebalanceNode(e){let t=e.getBalanceFactor();if(t>1){if(e.l&&e.l.getBalanceFactor()>=0)return e.rotateRight();if(e.l)return e.l=e.l.rotateLeft(),e.rotateRight()}if(t<-1){if(e.r&&e.r.getBalanceFactor()<=0)return e.rotateLeft();if(e.r)return e.r=e.r.rotateRight(),e.rotateLeft()}return e}find(e){let t=this.findNodeByKey(e);return t?t.v:null}contains(e){return this.find(e)!==null}getSize(){let e=0,t=[],n=this.root;for(;n||t.length>0;){for(;n;)t.push(n),n=n.l;n=t.pop(),e++,n=n.r}return e}isBalanced(){if(!this.root)return!0;let e=[this.root];for(;e.length>0;){let t=e.pop(),n=t.getBalanceFactor();if(Math.abs(n)>1)return!1;t.l&&e.push(t.l),t.r&&e.push(t.r)}return!0}remove(e){this.root=this.removeNode(this.root,e)}removeDocument(e,t){let n=this.findNodeByKey(e);n&&(n.v.size===1?this.root=this.removeNode(this.root,e):n.v=new Set([...n.v.values()].filter(e=>e!==t)))}findNodeByKey(e){let t=this.root;for(;t;)if(e<t.k)t=t.l;else if(e>t.k)t=t.r;else return t;return null}removeNode(e,t){if(e===null)return null;let n=[],r=e;for(;r!==null&&r.k!==t;)n.push(r),r=t<r.k?r.l:r.r;if(r===null)return e;if(r.l===null||r.r===null){let t=r.l?r.l:r.r;if(n.length===0)e=t;else{let e=n[n.length-1];e.l===r?e.l=t:e.r=t}}else{let e=r,t=r.r;for(;t.l!==null;)e=t,t=t.l;r.k=t.k,r.v=t.v,e.l===t?e.l=t.r:e.r=t.r,r=e}n.push(r);for(let t=n.length-1;t>=0;t--){let r=n[t];r.updateHeight();let i=this.rebalanceNode(r);if(t>0){let e=n[t-1];e.l===r?e.l=i:e.r===r&&(e.r=i)}else e=i}return e}rangeSearch(e,t){let n=new Set,r=[],i=this.root;for(;i||r.length>0;){for(;i;)r.push(i),i=i.l;if(i=r.pop(),i.k>=e&&i.k<=t)for(let e of i.v)n.add(e);if(i.k>t)break;i=i.r}return n}greaterThan(e,t=!1){let n=new Set,r=[],i=this.root;for(;i||r.length>0;){for(;i;)r.push(i),i=i.r;if(i=r.pop(),t&&i.k>=e||!t&&i.k>e)for(let e of i.v)n.add(e);else if(i.k<=e)break;i=i.l}return n}lessThan(e,t=!1){let n=new Set,r=[],i=this.root;for(;i||r.length>0;){for(;i;)r.push(i),i=i.l;if(i=r.pop(),t&&i.k<=e||!t&&i.k<e)for(let e of i.v)n.add(e);else if(i.k>e)break;i=i.r}return n}},YH=class e{numberToDocumentId;constructor(){this.numberToDocumentId=new Map}insert(e,t){this.numberToDocumentId.has(e)?this.numberToDocumentId.get(e).add(t):this.numberToDocumentId.set(e,new Set([t]))}find(e){let t=this.numberToDocumentId.get(e);return t?Array.from(t):null}remove(e){this.numberToDocumentId.delete(e)}removeDocument(e,t){let n=this.numberToDocumentId.get(t);n&&(n.delete(e),n.size===0&&this.numberToDocumentId.delete(t))}contains(e){return this.numberToDocumentId.has(e)}getSize(){let e=0;for(let t of this.numberToDocumentId.values())e+=t.size;return e}filter(e){let t=Object.keys(e);if(t.length!==1)throw Error(`Invalid operation`);let n=t[0];switch(n){case`eq`:{let t=e[n],r=this.numberToDocumentId.get(t);return r?Array.from(r):[]}case`in`:{let t=e[n],r=new Set;for(let e of t){let t=this.numberToDocumentId.get(e);if(t)for(let e of t)r.add(e)}return Array.from(r)}case`nin`:{let t=new Set(e[n]),r=new Set;for(let[e,n]of this.numberToDocumentId.entries())if(!t.has(e))for(let e of n)r.add(e);return Array.from(r)}default:throw Error(`Invalid operation`)}}filterArr(e){let t=Object.keys(e);if(t.length!==1)throw Error(`Invalid operation`);let n=t[0];switch(n){case`containsAll`:{let t=e[n].map(e=>this.numberToDocumentId.get(e)??new Set);if(t.length===0)return[];let r=t.reduce((e,t)=>new Set([...e].filter(e=>t.has(e))));return Array.from(r)}case`containsAny`:{let t=e[n].map(e=>this.numberToDocumentId.get(e)??new Set);if(t.length===0)return[];let r=t.reduce((e,t)=>new Set([...e,...t]));return Array.from(r)}default:throw Error(`Invalid operation`)}}static fromJSON(t){if(!t.numberToDocumentId)throw Error(`Invalid Flat Tree JSON`);let n=new e;for(let[e,r]of t.numberToDocumentId)n.numberToDocumentId.set(e,new Set(r));return n}toJSON(){return{numberToDocumentId:Array.from(this.numberToDocumentId.entries()).map(([e,t])=>[e,Array.from(t)])}}};function XH(e,t,n){if(n<0)return-1;if(e===t)return 0;let r=e.length,i=t.length;if(r===0)return i<=n?i:-1;if(i===0)return r<=n?r:-1;let a=Math.abs(r-i);if(e.startsWith(t))return a<=n?a:-1;if(t.startsWith(e))return 0;if(a>n)return-1;let o=[];for(let e=0;e<=r;e++){o[e]=[e];for(let t=1;t<=i;t++)o[e][t]=e===0?t:0}for(let a=1;a<=r;a++){let r=1/0;for(let n=1;n<=i;n++)e[a-1]===t[n-1]?o[a][n]=o[a-1][n-1]:o[a][n]=Math.min(o[a-1][n]+1,o[a][n-1]+1,o[a-1][n-1]+1),r=Math.min(r,o[a][n]);if(r>n)return-1}return o[r][i]<=n?o[r][i]:-1}function ZH(e,t,n){let r=XH(e,t,n);return{distance:r,isBounded:r>=0}}var QH=class e{k;s;c=new Map;d=new Set;e;w=``;constructor(e,t,n){this.k=e,this.s=t,this.e=n}updateParent(e){this.w=e.w+this.s}addDocument(e){this.d.add(e)}removeDocument(e){return this.d.delete(e)}findAllWords(e,t,n,r){let i=[this];for(;i.length>0;){let a=i.pop();if(a.e){let{w:i,d:o}=a;if(n&&i!==t)continue;if(XV(e,i)!==null)if(r)if(Math.abs(t.length-i.length)<=r&&ZH(t,i,r).isBounded)e[i]=[];else continue;else e[i]=[];if(XV(e,i)!=null&&o.size>0){let t=e[i];for(let e of o)t.includes(e)||t.push(e)}}a.c.size>0&&i.push(...a.c.values())}return e}insert(t,n){let r=this,i=0,a=t.length;for(;i<a;){let o=t[i],s=r.c.get(o);if(s){let o=s.s,c=o.length,l=0;for(;l<c&&i+l<a&&o[l]===t[i+l];)l++;if(l===c){if(r=s,i+=l,i===a){s.e||=!0,s.addDocument(n);return}continue}let u=o.slice(0,l),d=o.slice(l),f=t.slice(i+l),p=new e(u[0],u,!1);if(r.c.set(u[0],p),p.updateParent(r),s.s=d,s.k=d[0],p.c.set(d[0],s),s.updateParent(p),f){let t=new e(f[0],f,!0);t.addDocument(n),p.c.set(f[0],t),t.updateParent(p)}else p.e=!0,p.addDocument(n);return}else{let a=new e(o,t.slice(i),!0);a.addDocument(n),r.c.set(o,a),a.updateParent(r);return}}r.e||=!0,r.addDocument(n)}_findLevenshtein(e,t,n,r,i){let a=[{node:this,index:t,tolerance:n}];for(;a.length>0;){let{node:t,index:n,tolerance:o}=a.pop();if(t.w.startsWith(e)){t.findAllWords(i,e,!1,0);continue}if(o<0)continue;if(t.e){let{w:n,d:a}=t;if(n&&(ZH(e,n,r).isBounded&&(i[n]=[]),XV(i,n)!==void 0&&a.size>0)){let e=new Set(i[n]);for(let t of a)e.add(t);i[n]=Array.from(e)}}if(n>=e.length)continue;let s=e[n];if(t.c.has(s)){let e=t.c.get(s);a.push({node:e,index:n+1,tolerance:o})}a.push({node:t,index:n+1,tolerance:o-1});for(let[e,r]of t.c)a.push({node:r,index:n,tolerance:o-1}),e!==s&&a.push({node:r,index:n+1,tolerance:o-1})}}find(e){let{term:t,exact:n,tolerance:r}=e;if(r&&!n){let e={};return this._findLevenshtein(t,0,r,r,e),e}else{let e=this,i=0,a=t.length;for(;i<a;){let o=t[i],s=e.c.get(o);if(s){let o=s.s,c=o.length,l=0;for(;l<c&&i+l<a&&o[l]===t[i+l];)l++;if(l===c)e=s,i+=l;else if(i+l===a)if(l===a-i){if(n)return{};{let e={};return s.findAllWords(e,t,n,r),e}}else return{};else return{}}else return{}}let o={};return e.findAllWords(o,t,n,r),o}}contains(e){let t=this,n=0,r=e.length;for(;n<r;){let i=e[n],a=t.c.get(i);if(a){let i=a.s,o=i.length,s=0;for(;s<o&&n+s<r&&i[s]===e[n+s];)s++;if(s<o)return!1;n+=o,t=a}else return!1}return!0}removeWord(e){if(!e)return!1;let t=this,n=e.length,r=[];for(let i=0;i<n;i++){let n=e[i];if(t.c.has(n)){let e=t.c.get(n);r.push({parent:t,character:n}),i+=e.s.length-1,t=e}else return!1}for(t.d.clear(),t.e=!1;r.length>0&&t.c.size===0&&!t.e&&t.d.size===0;){let{parent:e,character:n}=r.pop();e.c.delete(n),t=e}return!0}removeDocumentByWord(e,t,n=!0){if(!e)return!0;let r=this,i=e.length;for(let a=0;a<i;a++){let i=e[a];if(r.c.has(i)){let o=r.c.get(i);a+=o.s.length-1,r=o,n&&r.w!==e||r.removeDocument(t)}else return!1}return!0}static getCommonPrefix(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e.charCodeAt(r)===t.charCodeAt(r);)r++;return e.slice(0,r)}toJSON(){return{w:this.w,s:this.s,e:this.e,k:this.k,d:Array.from(this.d),c:Array.from(this.c?.entries())?.map(([e,t])=>[e,t.toJSON()])}}static fromJSON(t){let n=new e(t.k,t.s,t.e);return n.w=t.w,n.d=new Set(t.d),n.c=new Map(t?.c?.map(([t,n])=>[t,e.fromJSON(n)])||[]),n}},$H=class e extends QH{constructor(){super(``,``,!1)}static fromJSON(t){let n=new e;return n.w=t.w,n.s=t.s,n.e=t.e,n.k=t.k,n.d=new Set(t.d),n.c=new Map(t?.c?.map(([e,t])=>[e,QH.fromJSON(t)])||[]),n}toJSON(){return super.toJSON()}},eU=class e{point;docIDs;left;right;parent;constructor(e,t){this.point=e,this.docIDs=new Set(t),this.left=null,this.right=null,this.parent=null}toJSON(){return{point:this.point,docIDs:Array.from(this.docIDs),left:this.left?this.left.toJSON():null,right:this.right?this.right.toJSON():null}}static fromJSON(t,n=null){let r=new e(t.point,t.docIDs);return r.parent=n,t.left&&(r.left=e.fromJSON(t.left,r)),t.right&&(r.right=e.fromJSON(t.right,r)),r}},tU=class e{root;nodeMap;constructor(){this.root=null,this.nodeMap=new Map}getPointKey(e){return`${e.lon},${e.lat}`}insert(e,t){let n=this.getPointKey(e),r=this.nodeMap.get(n);if(r){t.forEach(e=>r.docIDs.add(e));return}let i=new eU(e,t);if(this.nodeMap.set(n,i),this.root==null){this.root=i;return}let a=this.root,o=0;for(;;){if(o%2==0)if(e.lon<a.point.lon){if(a.left==null){a.left=i,i.parent=a;return}a=a.left}else{if(a.right==null){a.right=i,i.parent=a;return}a=a.right}else if(e.lat<a.point.lat){if(a.left==null){a.left=i,i.parent=a;return}a=a.left}else{if(a.right==null){a.right=i,i.parent=a;return}a=a.right}o++}}contains(e){let t=this.getPointKey(e);return this.nodeMap.has(t)}getDocIDsByCoordinates(e){let t=this.getPointKey(e),n=this.nodeMap.get(t);return n?Array.from(n.docIDs):null}removeDocByID(e,t){let n=this.getPointKey(e),r=this.nodeMap.get(n);r&&(r.docIDs.delete(t),r.docIDs.size===0&&(this.nodeMap.delete(n),this.deleteNode(r)))}deleteNode(e){let t=e.parent,n=e.left?e.left:e.right;n&&(n.parent=t),t?t.left===e?t.left=n:t.right===e&&(t.right=n):(this.root=n,this.root&&(this.root.parent=null))}searchByRadius(t,n,r=!0,i=`asc`,a=!1){let o=a?e.vincentyDistance:e.haversineDistance,s=[{node:this.root,depth:0}],c=[];for(;s.length>0;){let{node:e,depth:i}=s.pop();if(e==null)continue;let a=o(t,e.point);(r?a<=n:a>n)&&c.push({point:e.point,docIDs:Array.from(e.docIDs)}),e.left!=null&&s.push({node:e.left,depth:i+1}),e.right!=null&&s.push({node:e.right,depth:i+1})}return i&&c.sort((e,n)=>{let r=o(t,e.point),a=o(t,n.point);return i.toLowerCase()===`asc`?r-a:a-r}),c}searchByPolygon(t,n=!0,r=null,i=!1){let a=[{node:this.root,depth:0}],o=[];for(;a.length>0;){let{node:r,depth:i}=a.pop();if(r==null)continue;r.left!=null&&a.push({node:r.left,depth:i+1}),r.right!=null&&a.push({node:r.right,depth:i+1});let s=e.isPointInPolygon(t,r.point);(s&&n||!s&&!n)&&o.push({point:r.point,docIDs:Array.from(r.docIDs)})}let s=e.calculatePolygonCentroid(t);if(r){let t=i?e.vincentyDistance:e.haversineDistance;o.sort((e,n)=>{let i=t(s,e.point),a=t(s,n.point);return r.toLowerCase()===`asc`?i-a:a-i})}return o}toJSON(){return{root:this.root?this.root.toJSON():null}}static fromJSON(t){let n=new e;return t.root&&(n.root=eU.fromJSON(t.root),n.buildNodeMap(n.root)),n}buildNodeMap(e){if(e==null)return;let t=this.getPointKey(e.point);this.nodeMap.set(t,e),e.left&&this.buildNodeMap(e.left),e.right&&this.buildNodeMap(e.right)}static calculatePolygonCentroid(e){let t=0,n=0,r=0,i=e.length;for(let a=0,o=i-1;a<i;o=a++){let i=e[a].lon,s=e[a].lat,c=e[o].lon,l=e[o].lat,u=i*l-c*s;t+=u,n+=(i+c)*u,r+=(s+l)*u}t/=2;let a=6*t;return n/=a,r/=a,{lon:n,lat:r}}static isPointInPolygon(e,t){let n=!1,r=t.lon,i=t.lat,a=e.length;for(let t=0,o=a-1;t<a;o=t++){let a=e[t].lon,s=e[t].lat,c=e[o].lon,l=e[o].lat;s>i!=l>i&&r<(c-a)*(i-s)/(l-s)+a&&(n=!n)}return n}static haversineDistance(e,t){let n=Math.PI/180,r=e.lat*n,i=t.lat*n,a=(t.lat-e.lat)*n,o=(t.lon-e.lon)*n,s=Math.sin(a/2)*Math.sin(a/2)+Math.cos(r)*Math.cos(i)*Math.sin(o/2)*Math.sin(o/2);return 6371e3*(2*Math.atan2(Math.sqrt(s),Math.sqrt(1-s)))}static vincentyDistance(e,t){let n=6378137,r=1/298.257223563,i=(1-r)*n,a=Math.PI/180,o=e.lat*a,s=t.lat*a,c=(t.lon-e.lon)*a,l=Math.atan((1-r)*Math.tan(o)),u=Math.atan((1-r)*Math.tan(s)),d=Math.sin(l),f=Math.cos(l),p=Math.sin(u),m=Math.cos(u),h=c,g,_=1e3,v,y,b,x,S,C;do{let e=Math.sin(h),t=Math.cos(h);if(v=Math.sqrt(m*e*(m*e)+(f*p-d*m*t)*(f*p-d*m*t)),v===0)return 0;y=d*p+f*m*t,b=Math.atan2(v,y),x=f*m*e/v,S=1-x*x,C=y-2*d*p/S,isNaN(C)&&(C=0);let n=r/16*S*(4+r*(4-3*S));g=h,h=c+(1-n)*r*x*(b+n*v*(C+n*y*(-1+2*C*C)))}while(Math.abs(h-g)>1e-12&&--_>0);if(_===0)return NaN;let w=S*(n*n-i*i)/(i*i),T=1+w/16384*(4096+w*(-768+w*(320-175*w))),E=w/1024*(256+w*(-128+w*(74-47*w))),ee=E*v*(C+E/4*(y*(-1+2*C*C)-E/6*C*(-3+4*v*v)*(-3+4*C*C)));return i*T*(b-ee)}},nU=class e{true;false;constructor(){this.true=new Set,this.false=new Set}insert(e,t){t?this.true.add(e):this.false.add(e)}delete(e,t){t?this.true.delete(e):this.false.delete(e)}getSize(){return this.true.size+this.false.size}toJSON(){return{true:Array.from(this.true),false:Array.from(this.false)}}static fromJSON(t){let n=new e;return n.true=new Set(t.true),n.false=new Set(t.false),n}};function rU(e,t,n,r,i,{k:a,b:o,d:s}){return Math.log(1+(n-t+.5)/(t+.5))*(s+e*(a+1))/(e+a*(1-o+o*r/i))}var iU=class e{size;vectors=new Map;constructor(e){this.size=e}add(e,t){t instanceof Float32Array||(t=new Float32Array(t));let n=aU(t,this.size);this.vectors.set(e,[n,t])}remove(e){this.vectors.delete(e)}find(e,t,n){return e instanceof Float32Array||(e=new Float32Array(e)),oU(e,n,this.vectors,this.size,t)}toJSON(){let e=[];for(let[t,[n,r]]of this.vectors)e.push([t,[n,Array.from(r)]]);return{size:this.size,vectors:e}}static fromJSON(t){let n=t,r=new e(n.size);for(let[e,[t,i]]of n.vectors)r.vectors.set(e,[t,new Float32Array(i)]);return r}};function aU(e,t){let n=0;for(let r=0;r<t;r++)n+=e[r]*e[r];return Math.sqrt(n)}function oU(e,t,n,r,i){let a=aU(e,r),o=[],s=t||n.keys();for(let t of s){let s=n.get(t);if(!s)continue;let c=s[0],l=s[1],u=0;for(let t=0;t<r;t++)u+=e[t]*l[t];let d=u/(a*c);d>=i&&o.push([t,d])}return o}function sU(e,t,n,r,i){let a=EH(e.sharedInternalDocumentStore,n);e.avgFieldLength[t]=((e.avgFieldLength[t]??0)*(i-1)+r.length)/i,e.fieldLengths[t][a]=r.length,e.frequencies[t][a]={}}function cU(e,t,n,r,i){let a=0;for(let e of r)e===i&&a++;let o=EH(e.sharedInternalDocumentStore,n),s=a/r.length;e.frequencies[t][o][i]=s,i in e.tokenOccurrences[t]||(e.tokenOccurrences[t][i]=0),e.tokenOccurrences[t][i]=(e.tokenOccurrences[t][i]??0)+1}function lU(e,t,n,r){let i=EH(e.sharedInternalDocumentStore,n);r>1?e.avgFieldLength[t]=(e.avgFieldLength[t]*r-e.fieldLengths[t][i])/(r-1):e.avgFieldLength[t]=void 0,e.fieldLengths[t][i]=void 0,e.frequencies[t][i]=void 0}function uU(e,t,n){e.tokenOccurrences[t][n]--}function dU(e,t,n,r,i=``){r||={sharedInternalDocumentStore:t,indexes:{},vectorIndexes:{},searchableProperties:[],searchablePropertiesWithTypes:{},frequencies:{},tokenOccurrences:{},avgFieldLength:{},fieldLengths:{}};for(let[a,o]of Object.entries(n)){let n=`${i}${i?`.`:``}${a}`;if(typeof o==`object`&&!Array.isArray(o)){dU(e,t,o,r,n);continue}if(yH(o))r.searchableProperties.push(n),r.searchablePropertiesWithTypes[n]=o,r.vectorIndexes[n]={type:`Vector`,node:new iU(SH(o)),isArray:!1};else{let e=/\[/.test(o);switch(o){case`boolean`:case`boolean[]`:r.indexes[n]={type:`Bool`,node:new nU,isArray:e};break;case`number`:case`number[]`:r.indexes[n]={type:`AVL`,node:new JH(0,[]),isArray:e};break;case`string`:case`string[]`:r.indexes[n]={type:`Radix`,node:new $H,isArray:e},r.avgFieldLength[n]=0,r.frequencies[n]={},r.tokenOccurrences[n]={},r.fieldLengths[n]={};break;case`enum`:case`enum[]`:r.indexes[n]={type:`Flat`,node:new YH,isArray:e};break;case`geopoint`:r.indexes[n]={type:`BKD`,node:new tU,isArray:e};break;default:throw fH(`INVALID_SCHEMA_TYPE`,Array.isArray(o)?`array`:o,n)}r.searchableProperties.push(n),r.searchablePropertiesWithTypes[n]=o}}return r}function fU(e,t,n,r,i,a,o,s){return c=>{let{type:l,node:u}=t.indexes[n];switch(l){case`Bool`:u[c?`true`:`false`].add(r);break;case`AVL`:{let e=s?.avlRebalanceThreshold??1;u.insert(c,r,e);break}case`Radix`:{let s=a.tokenize(c,i,n,!1);e.insertDocumentScoreParameters(t,n,r,s,o);for(let i of s)e.insertTokenScoreParameters(t,n,r,s,i),u.insert(i,r);break}case`Flat`:u.insert(c,r);break;case`BKD`:u.insert(c,[r]);break}}}function pU(e,t,n,r,i,a,o,s,c,l,u){if(yH(o))return mU(t,n,a,r,i);let d=fU(e,t,n,i,s,c,l,u);if(!bH(o))return d(a);let f=a,p=f.length;for(let e=0;e<p;e++)d(f[e])}function mU(e,t,n,r,i){e.vectorIndexes[t].node.add(i,n)}function hU(e,t,n,r,i,a,o,s,c,l){if(yH(o))return t.vectorIndexes[n].node.remove(i),!0;let{type:u,node:d}=t.indexes[n];switch(u){case`AVL`:return d.removeDocument(a,i),!0;case`Bool`:return d[a?`true`:`false`].delete(i),!0;case`Radix`:{let o=c.tokenize(a,s,n);e.removeDocumentScoreParameters(t,n,r,l);for(let r of o)e.removeTokenScoreParameters(t,n,r),d.removeDocumentByWord(r,i);return!0}case`Flat`:return d.removeDocument(i,a),!0;case`BKD`:return d.removeDocByID(a,i),!1}}function gU(e,t,n,r,i,a,o,s,c,l){if(!bH(o))return hU(e,t,n,r,i,a,o,s,c,l);let u=xH(o),d=a,f=d.length;for(let a=0;a<f;a++)hU(e,t,n,r,i,d[a],u,s,c,l);return!0}function _U(e,t,n,r,i,a,o,s,c,l){let u=Array.from(r),d=e.avgFieldLength[t],f=e.fieldLengths[t],p=e.tokenOccurrences[t],m=e.frequencies[t],h=typeof p[n]==`number`?p[n]??0:0,g=u.length;for(let e=0;e<g;e++){let r=u[e];if(c&&!c.has(r))continue;l.has(r)||l.set(r,new Map);let p=l.get(r);p.set(t,(p.get(t)||0)+1);let g=rU(m?.[r]?.[n]??0,h,i,f[r],d,a);o.has(r)?o.set(r,o.get(r)+g*s):o.set(r,g*s)}}function vU(e,t,n,r,i,a,o,s,c,l,u,d=0){let f=n.tokenize(t,r),p=f.length||1,m=new Map,h=new Map,g=new Map;for(let n of i){if(!(n in e.indexes))continue;let r=e.indexes[n],{type:i}=r;if(i!==`Radix`)throw fH(`WRONG_SEARCH_PROPERTY_TYPE`,n);let d=s[n]??1;if(d<=0)throw fH(`INVALID_BOOST_VALUE`,d);f.length===0&&!t&&f.push(``);let p=f.length;for(let t=0;t<p;t++){let i=f[t],s=r.node.find({term:i,exact:a,tolerance:o}),p=Object.keys(s);p.length>0&&h.set(i,!0);let _=p.length;for(let t=0;t<_;t++){let r=p[t],i=s[r];_U(e,n,r,i,l,c,g,d,u,m)}}}let _=Array.from(g.entries()).map(([e,t])=>[e,t]).sort((e,t)=>t[1]-e[1]);if(_.length===0)return[];if(d===1)return _;if(d===0){if(p===1)return _;for(let e of f)if(!h.get(e))return[];return _.filter(([e])=>{let t=m.get(e);return t?Array.from(t.values()).some(e=>e===p):!1})}let v=_.filter(([e])=>{let t=m.get(e);return t?Array.from(t.values()).some(e=>e===p):!1});if(v.length>0){let e=_.filter(([e])=>!v.some(([t])=>t===e)),t=Math.ceil(e.length*d);return[...v,...e.slice(0,t)]}return _}function yU(e,t,n,r){if(`and`in n&&n.and&&Array.isArray(n.and)){let i=n.and;return i.length===0?new Set:oH(...i.map(n=>yU(e,t,n,r)))}if(`or`in n&&n.or&&Array.isArray(n.or)){let i=n.or;return i.length===0?new Set:i.map(n=>yU(e,t,n,r)).reduce((e,t)=>cH(e,t),new Set)}if(`not`in n&&n.not){let i=n.not,a=new Set,o=e.sharedInternalDocumentStore;for(let e=1;e<=o.internalIdToId.length;e++)a.add(e);return lH(a,yU(e,t,i,r))}let i=Object.keys(n),a=i.reduce((e,t)=>({[t]:new Set,...e}),{});for(let o of i){let i=n[o];if(e.indexes[o]===void 0)throw fH(`UNKNOWN_FILTER_PROPERTY`,o);let{node:s,type:c,isArray:l}=e.indexes[o];if(c===`Bool`){let e=s,t=i?e.true:e.false;a[o]=cH(a[o],t);continue}if(c===`BKD`){let e;if(`radius`in i)e=`radius`;else if(`polygon`in i)e=`polygon`;else throw Error(`Invalid operation ${i}`);if(e===`radius`){let{value:t,coordinates:n,unit:r=`m`,inside:c=!0,highPrecision:l=!1}=i[e],u=nH(t,r),d=s.searchByRadius(n,u,c,void 0,l);a[o]=TU(a[o],d)}else{let{coordinates:t,inside:n=!0,highPrecision:r=!1}=i[e],c=s.searchByPolygon(t,n,void 0,r);a[o]=TU(a[o],c)}continue}if(c===`Radix`&&(typeof i==`string`||Array.isArray(i))){for(let e of[i].flat()){let n=t.tokenize(e,r,o);for(let e of n){let t=s.find({term:e,exact:!0});a[o]=kU(a[o],t)}}continue}let u=Object.keys(i);if(u.length>1)throw fH(`INVALID_FILTER_OPERATION`,u.length);if(c===`Flat`){let e=new Set(l?s.filterArr(i):s.filter(i));a[o]=cH(a[o],e);continue}if(c===`AVL`){let e=u[0],t=i[e],n;switch(e){case`gt`:n=s.greaterThan(t,!1);break;case`gte`:n=s.greaterThan(t,!0);break;case`lt`:n=s.lessThan(t,!1);break;case`lte`:n=s.lessThan(t,!0);break;case`eq`:n=s.find(t)??new Set;break;case`between`:{let[e,r]=t;n=s.rangeSearch(e,r);break}default:throw fH(`INVALID_FILTER_OPERATION`,e)}a[o]=cH(a[o],n)}}return oH(...Object.values(a))}function bU(e){return e.searchableProperties}function xU(e){return e.searchablePropertiesWithTypes}function SU(e,t){let{indexes:n,vectorIndexes:r,searchableProperties:i,searchablePropertiesWithTypes:a,frequencies:o,tokenOccurrences:s,avgFieldLength:c,fieldLengths:l}=t,u={},d={};for(let e of Object.keys(n)){let{node:t,type:r,isArray:i}=n[e];switch(r){case`Radix`:u[e]={type:`Radix`,node:$H.fromJSON(t),isArray:i};break;case`Flat`:u[e]={type:`Flat`,node:YH.fromJSON(t),isArray:i};break;case`AVL`:u[e]={type:`AVL`,node:JH.fromJSON(t),isArray:i};break;case`BKD`:u[e]={type:`BKD`,node:tU.fromJSON(t),isArray:i};break;case`Bool`:u[e]={type:`Bool`,node:nU.fromJSON(t),isArray:i};break;default:u[e]=n[e]}}for(let e of Object.keys(r))d[e]={type:`Vector`,isArray:!1,node:iU.fromJSON(r[e])};return{sharedInternalDocumentStore:e,indexes:u,vectorIndexes:d,searchableProperties:i,searchablePropertiesWithTypes:a,frequencies:o,tokenOccurrences:s,avgFieldLength:c,fieldLengths:l}}function CU(e){let{indexes:t,vectorIndexes:n,searchableProperties:r,searchablePropertiesWithTypes:i,frequencies:a,tokenOccurrences:o,avgFieldLength:s,fieldLengths:c}=e,l={};for(let e of Object.keys(n))l[e]=n[e].node.toJSON();let u={};for(let e of Object.keys(t)){let{type:n,node:r,isArray:i}=t[e];n===`Flat`||n===`Radix`||n===`AVL`||n===`BKD`||n===`Bool`?u[e]={type:n,node:r.toJSON(),isArray:i}:(u[e]=t[e],u[e].node=u[e].node.toJSON())}return{indexes:u,vectorIndexes:l,searchableProperties:r,searchablePropertiesWithTypes:i,frequencies:a,tokenOccurrences:o,avgFieldLength:s,fieldLengths:c}}function wU(){return{create:dU,insert:pU,remove:gU,insertDocumentScoreParameters:sU,insertTokenScoreParameters:cU,removeDocumentScoreParameters:lU,removeTokenScoreParameters:uU,calculateResultScores:_U,search:vU,searchByWhereClause:yU,getSearchableProperties:bU,getSearchablePropertiesWithTypes:xU,load:SU,save:CU}}function TU(e,t){e||=new Set;let n=t.length;for(let r=0;r<n;r++){let n=t[r].docIDs,i=n.length;for(let t=0;t<i;t++)e.add(n[t])}return e}function EU(e,t,n=!1){let r=n?tU.vincentyDistance:tU.haversineDistance,i=[],a=[];for(let{point:n}of e)a.push(r(t,n));let o=Math.max(...a),s=0;for(let{docIDs:t}of e){let e=o-a[s]+1;for(let n of t)i.push([n,e]);s++}return i.sort((e,t)=>t[1]-e[1]),i}function DU(e,t){let n=Object.keys(e);if(n.length!==1)return{isGeoOnly:!1};let r=n[0],i=e[r];if(t.indexes[r]===void 0)return{isGeoOnly:!1};let{type:a}=t.indexes[r];return a===`BKD`&&i&&(`radius`in i||`polygon`in i)?{isGeoOnly:!0,geoProperty:r,geoOperation:i}:{isGeoOnly:!1}}function OU(e,t){let n=e,r=DU(t,n);if(!r.isGeoOnly||!r.geoProperty||!r.geoOperation)return null;let{node:i}=n.indexes[r.geoProperty],a=r.geoOperation,o=i,s;if(`radius`in a){let{value:e,coordinates:t,unit:n=`m`,inside:r=!0,highPrecision:i=!1}=a.radius,c=t,l=nH(e,n);return s=o.searchByRadius(c,l,r,`asc`,i),EU(s,c,i)}else if(`polygon`in a){let{coordinates:e,inside:t=!0,highPrecision:n=!1}=a.polygon;s=o.searchByPolygon(e,t,`asc`,n);let r=tU.calculatePolygonCentroid(e);return EU(s,r,n)}return null}function kU(e,t){e||=new Set;let n=Object.keys(t),r=n.length;for(let i=0;i<r;i++){let r=t[n[i]],a=r.length;for(let t=0;t<a;t++)e.add(r[t])}return e}function AU(e,t,n,r,i){let a={language:e.tokenizer.language,sharedInternalDocumentStore:t,enabled:!0,isSorted:!0,sortableProperties:[],sortablePropertiesWithTypes:{},sorts:{}};for(let[o,s]of Object.entries(n)){let n=`${i}${i?`.`:``}${o}`;if(!r.includes(n)){if(typeof s==`object`&&!Array.isArray(s)){let i=AU(e,t,s,r,n);HV(a.sortableProperties,i.sortableProperties),a.sorts={...a.sorts,...i.sorts},a.sortablePropertiesWithTypes={...a.sortablePropertiesWithTypes,...i.sortablePropertiesWithTypes};continue}if(!yH(s))switch(s){case`boolean`:case`number`:case`string`:a.sortableProperties.push(n),a.sortablePropertiesWithTypes[n]=s,a.sorts[n]={docs:new Map,orderedDocsToRemove:new Map,orderedDocs:[],type:s};break;case`geopoint`:case`enum`:continue;case`enum[]`:case`boolean[]`:case`number[]`:case`string[]`:continue;default:throw fH(`INVALID_SORT_SCHEMA_TYPE`,Array.isArray(s)?`array`:s,n)}}}return a}function jU(e,t,n,r){return r?.enabled===!1?{disabled:!0}:AU(e,t,n,(r||{}).unsortableProperties||[],``)}function MU(e,t,n,r){if(!e.enabled)return;e.isSorted=!1;let i=EH(e.sharedInternalDocumentStore,n),a=e.sorts[t];a.orderedDocsToRemove.has(i)&&zU(e,t),a.docs.set(i,a.orderedDocs.length),a.orderedDocs.push([i,r])}function NU(e){if(e.isSorted||!e.enabled)return;let t=Object.keys(e.sorts);for(let n of t)LU(e,n);e.isSorted=!0}function PU(e,t,n){return t[1].localeCompare(n[1],FV(e))}function FU(e,t){return e[1]-t[1]}function IU(e,t){return t[1]?-1:1}function LU(e,t){let n=e.sorts[t],r;switch(n.type){case`string`:r=PU.bind(null,e.language);break;case`number`:r=FU.bind(null);break;case`boolean`:r=IU.bind(null);break}n.orderedDocs.sort(r);let i=n.orderedDocs.length;for(let e=0;e<i;e++){let t=n.orderedDocs[e][0];n.docs.set(t,e)}}function RU(e){let t=Object.keys(e.sorts);for(let n of t)zU(e,n)}function zU(e,t){let n=e.sorts[t];n.orderedDocsToRemove.size&&(n.orderedDocs=n.orderedDocs.filter(e=>!n.orderedDocsToRemove.has(e[0])),n.orderedDocsToRemove.clear())}function BU(e,t,n){if(!e.enabled)return;let r=e.sorts[t],i=EH(e.sharedInternalDocumentStore,n);r.docs.get(i)&&(r.docs.delete(i),r.orderedDocsToRemove.set(i,!0))}function VU(e,t,n){if(!e.enabled)throw fH(`SORT_DISABLED`);let r=n.property,i=n.order===`DESC`,a=e.sorts[r];if(!a)throw fH(`UNABLE_TO_SORT_ON_UNKNOWN_FIELD`,r,e.sortableProperties.join(`, `));return zU(e,r),NU(e),t.sort((t,n)=>{let r=a.docs.get(EH(e.sharedInternalDocumentStore,t[0])),o=a.docs.get(EH(e.sharedInternalDocumentStore,n[0])),s=r!==void 0,c=o!==void 0;return!s&&!c?0:s?c?i?o-r:r-o:-1:1}),t}function HU(e){return e.enabled?e.sortableProperties:[]}function UU(e){return e.enabled?e.sortablePropertiesWithTypes:{}}function WU(e,t){let n=t;if(!n.enabled)return{enabled:!1};let r=Object.keys(n.sorts).reduce((e,t)=>{let{docs:r,orderedDocs:i,type:a}=n.sorts[t];return e[t]={docs:new Map(Object.entries(r).map(([e,t])=>[+e,t])),orderedDocsToRemove:new Map,orderedDocs:i,type:a},e},{});return{sharedInternalDocumentStore:e,language:n.language,sortableProperties:n.sortableProperties,sortablePropertiesWithTypes:n.sortablePropertiesWithTypes,sorts:r,enabled:!0,isSorted:n.isSorted}}function GU(e){if(!e.enabled)return{enabled:!1};RU(e),NU(e);let t=Object.keys(e.sorts).reduce((t,n)=>{let{docs:r,orderedDocs:i,type:a}=e.sorts[n];return t[n]={docs:Object.fromEntries(r.entries()),orderedDocs:i,type:a},t},{});return{language:e.language,sortableProperties:e.sortableProperties,sortablePropertiesWithTypes:e.sortablePropertiesWithTypes,sorts:t,enabled:e.enabled,isSorted:e.isSorted}}function KU(){return{create:jU,insert:MU,remove:BU,save:GU,load:WU,sortBy:VU,getSortableProperties:HU,getSortablePropertiesWithTypes:UU}}const qU=[65,65,65,65,65,65,65,67,69,69,69,69,73,73,73,73,69,78,79,79,79,79,79,null,79,85,85,85,85,89,80,115,97,97,97,97,97,97,97,99,101,101,101,101,105,105,105,105,101,110,111,111,111,111,111,null,111,117,117,117,117,121,112,121,65,97,65,97,65,97,67,99,67,99,67,99,67,99,68,100,68,100,69,101,69,101,69,101,69,101,69,101,71,103,71,103,71,103,71,103,72,104,72,104,73,105,73,105,73,105,73,105,73,105,73,105,74,106,75,107,107,76,108,76,108,76,108,76,108,76,108,78,110,78,110,78,110,110,78,110,79,111,79,111,79,111,79,111,82,114,82,114,82,114,83,115,83,115,83,115,83,115,84,116,84,116,84,116,85,117,85,117,85,117,85,117,85,117,85,117,87,119,89,121,89,90,122,90,122,90,122,115];function JU(e){return e<192||e>383?e:qU[e-192]||e}function YU(e){let t=[];for(let n=0;n<e.length;n++)t[n]=JU(e.charCodeAt(n));return String.fromCharCode(...t)}const XU={ational:`ate`,tional:`tion`,enci:`ence`,anci:`ance`,izer:`ize`,bli:`ble`,alli:`al`,entli:`ent`,eli:`e`,ousli:`ous`,ization:`ize`,ation:`ate`,ator:`ate`,alism:`al`,iveness:`ive`,fulness:`ful`,ousness:`ous`,aliti:`al`,iviti:`ive`,biliti:`ble`,logi:`log`},ZU={icate:`ic`,ative:``,alize:`al`,iciti:`ic`,ical:`ic`,ful:``,ness:``},QU=`[aeiouy]`,$U=`[^aeiou][^aeiouy]*`;QU+``;const eW=`^(`+$U+`)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*`;``+$U;const tW=`^(`+$U+`)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*[aeiouy][aeiou]*[^aeiou][^aeiouy]*`,nW=`^(`+$U+`)?[aeiouy]`;function rW(e){let t,n,r,i,a,o;if(e.length<3)return e;let s=e.substring(0,1);if(s==`y`&&(e=s.toUpperCase()+e.substring(1)),r=/^(.+?)(ss|i)es$/,i=/^(.+?)([^s])s$/,r.test(e)?e=e.replace(r,`$1$2`):i.test(e)&&(e=e.replace(i,`$1$2`)),r=/^(.+?)eed$/,i=/^(.+?)(ed|ing)$/,r.test(e)){let t=r.exec(e);r=new RegExp(eW),r.test(t[1])&&(r=/.$/,e=e.replace(r,``))}else i.test(e)&&(t=i.exec(e)[1],i=new RegExp(nW),i.test(t)&&(e=t,i=/(at|bl|iz)$/,a=RegExp(`([^aeiouylsz])\\1$`),o=RegExp(`^`+$U+QU+`[^aeiouwxy]$`),i.test(e)?e+=`e`:a.test(e)?(r=/.$/,e=e.replace(r,``)):o.test(e)&&(e+=`e`)));if(r=/^(.+?)y$/,r.test(e)&&(t=r.exec(e)?.[1],r=new RegExp(nW),t&&r.test(t)&&(e=t+`i`)),r=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,r.test(e)){let i=r.exec(e);t=i?.[1],n=i?.[2],r=new RegExp(eW),t&&r.test(t)&&(e=t+XU[n])}if(r=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,r.test(e)){let i=r.exec(e);t=i?.[1],n=i?.[2],r=new RegExp(eW),t&&r.test(t)&&(e=t+ZU[n])}if(r=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/,i=/^(.+?)(s|t)(ion)$/,r.test(e))t=r.exec(e)?.[1],r=new RegExp(tW),t&&r.test(t)&&(e=t);else if(i.test(e)){let n=i.exec(e);t=n?.[1]??``+n?.[2]??``,i=new RegExp(tW),i.test(t)&&(e=t)}return r=/^(.+?)e$/,r.test(e)&&(t=r.exec(e)?.[1],r=new RegExp(tW),i=RegExp(`^([^aeiou][^aeiouy]*)?[aeiouy][aeiou]*[^aeiou][^aeiouy]*([aeiouy][aeiou]*)?$`),a=RegExp(`^`+$U+QU+`[^aeiouwxy]$`),t&&(r.test(t)||i.test(t)&&!a.test(t))&&(e=t)),r=/ll$/,i=new RegExp(tW),r.test(e)&&i.test(e)&&(r=/.$/,e=e.replace(r,``)),s==`y`&&(e=s.toLowerCase()+e.substring(1)),e}function iW(e,t,n=!0){let r=`${this.language}:${e}:${t}`;return n&&this.normalizationCache.has(r)?this.normalizationCache.get(r):this.stopWords?.includes(t)?(n&&this.normalizationCache.set(r,``),``):(this.stemmer&&!this.stemmerSkipProperties.has(e)&&(t=this.stemmer(t)),t=YU(t),n&&this.normalizationCache.set(r,t),t)}function aW(e){for(;e[e.length-1]===``;)e.pop();for(;e[0]===``;)e.shift();return e}function oW(e,t,n,r=!0){if(t&&t!==this.language)throw fH(`LANGUAGE_NOT_SUPPORTED`,t);if(typeof e!=`string`)return[e];let i=this.normalizeToken.bind(this,n??``),a;if(n&&this.tokenizeSkipProperties.has(n))a=[i(e,r)];else{let t=NV[this.language];a=e.toLowerCase().split(t).map(e=>i(e,r)).filter(Boolean)}let o=aW(a);return this.allowDuplicates?o:Array.from(new Set(o))}function sW(e={}){if(!e.language)e.language=`english`;else if(!PV.includes(e.language))throw fH(`LANGUAGE_NOT_SUPPORTED`,e.language);let t;if(e.stemming||e.stemmer&&!(`stemming`in e))if(e.stemmer){if(typeof e.stemmer!=`function`)throw fH(`INVALID_STEMMER_FUNCTION_TYPE`);t=e.stemmer}else if(e.language===`english`)t=rW;else throw fH(`MISSING_STEMMER`,e.language);let n;if(e.stopWords!==!1){if(n=[],Array.isArray(e.stopWords))n=e.stopWords;else if(typeof e.stopWords==`function`)n=e.stopWords(n);else if(e.stopWords)throw fH(`CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY`);if(!Array.isArray(n))throw fH(`CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY`);for(let e of n)if(typeof e!=`string`)throw fH(`CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY`)}let r={tokenize:oW,language:e.language,stemmer:t,stemmerSkipProperties:new Set(e.stemmerSkipProperties?[e.stemmerSkipProperties].flat():[]),tokenizeSkipProperties:new Set(e.tokenizeSkipProperties?[e.tokenizeSkipProperties].flat():[]),stopWords:n,allowDuplicates:!!e.allowDuplicates,normalizeToken:iW,normalizationCache:new Map};return r.tokenize=oW.bind(r),r.normalizeToken=iW,r}function cW(e){return{sharedInternalDocumentStore:e,rules:new Map}}function lW(e,t){if(e.rules.has(t.id))throw Error(`PINNING_RULE_ALREADY_EXISTS: A pinning rule with id "${t.id}" already exists. Use updateRule to modify it.`);e.rules.set(t.id,t)}function uW(e,t){if(!e.rules.has(t.id))throw Error(`PINNING_RULE_NOT_FOUND: Cannot update pinning rule with id "${t.id}" because it does not exist. Use addRule to create it.`);e.rules.set(t.id,t)}function dW(e,t){return e.rules.delete(t)}function fW(e,t){return e.rules.get(t)}function pW(e){return Array.from(e.rules.values())}function mW(e,t){let n=e.toLowerCase().trim(),r=t.pattern.toLowerCase().trim();switch(t.anchoring){case`is`:return n===r;case`starts_with`:return n.startsWith(r);case`contains`:return n.includes(r);default:return!1}}function hW(e,t){return e?t.conditions.every(t=>mW(e,t)):!1}function gW(e,t){if(!t)return[];let n=[];for(let r of e.rules.values())hW(t,r)&&n.push(r);return n}function _W(e,t){return{sharedInternalDocumentStore:e,rules:new Map(t?.rules??[])}}function vW(e){return{rules:Array.from(e.rules.entries())}}function yW(){return{create:cW,addRule:lW,updateRule:uW,removeRule:dW,getRule:fW,getAllRules:pW,getMatchingRules:gW,load:_W,save:vW}}function bW(e){let t={formatElapsedTime:pH,getDocumentIndexId:mH,getDocumentProperties:$V,validateSchema:hH};for(let n of VH){let r=n;if(e[r]){if(typeof e[r]!=`function`)throw fH(`COMPONENT_MUST_BE_FUNCTION`,r)}else e[r]=t[r]}for(let t of Object.keys(e))if(!BH.includes(t)&&!VH.includes(t))throw fH(`UNSUPPORTED_COMPONENT`,t)}function xW({schema:e,sort:t,language:n,components:r,id:i,plugins:a}){r||={};for(let t of a??[]){if(!(`getComponents`in t)||typeof t.getComponents!=`function`)continue;let n=t.getComponents(e),i=Object.keys(n);for(let e of i)if(r[e])throw fH(`PLUGIN_COMPONENT_CONFLICT`,e,t.name);r={...r,...n}}i||=YV();let o=r.tokenizer,s=r.index,c=r.documentsStore,l=r.sorter,u=r.pinning;if(o=o?o.tokenize?o:sW(o):sW({language:n??`english`}),r.tokenizer&&n)throw fH(`NO_LANGUAGE_WITH_CUSTOM_TOKENIZER`);let d=CH();s||=wU(),l||=KU(),c||=LH(),u||=yW(),bW(r);let{getDocumentProperties:f,getDocumentIndexId:p,validateSchema:m,formatElapsedTime:h}=r,g={data:{},caches:{},schema:e,tokenizer:o,index:s,sorter:l,documentsStore:c,pinning:u,internalDocumentIDStore:d,getDocumentProperties:f,getDocumentIndexId:p,validateSchema:m,beforeInsert:[],afterInsert:[],beforeRemove:[],afterRemove:[],beforeUpdate:[],afterUpdate:[],beforeUpsert:[],afterUpsert:[],beforeSearch:[],afterSearch:[],beforeInsertMultiple:[],afterInsertMultiple:[],beforeRemoveMultiple:[],afterRemoveMultiple:[],beforeUpdateMultiple:[],afterUpdateMultiple:[],beforeUpsertMultiple:[],afterUpsertMultiple:[],afterCreate:[],formatElapsedTime:h,id:i,plugins:a,version:SW()};g.data={index:g.index.create(g,d,e),docs:g.documentsStore.create(g,d),sorting:g.sorter.create(g,d,e,t),pinning:g.pinning.create(d)};for(let e of RH)g[e]=(g[e]??[]).concat(zH(g,e));let _=g.afterCreate;return _&&KH(_,g),g}function SW(){return`{{VERSION}}`}function CW(e){return e.documentsStore.count(e.data.docs)}function wW(e,t,n,r,i){let a=e.validateSchema(t,e.schema);if(a)throw fH(`SCHEMA_VALIDATION_FAILURE`,a);return iH(e.beforeInsert)||iH(e.afterInsert)||iH(e.index.beforeInsert)||iH(e.index.insert)||iH(e.index.afterInsert)?DW(e,t,n,r,i):OW(e,t,n,r,i)}const TW=new Set([`enum`,`enum[]`]),EW=new Set([`string`,`number`]);async function DW(e,t,n,r,i){let{index:a,docs:o}=e.data,s=e.getDocumentIndexId(t);if(typeof s!=`string`)throw fH(`DOCUMENT_ID_MUST_BE_STRING`,typeof s);let c=EH(e.internalDocumentIDStore,s);if(r||await HH(e.beforeInsert,e,s,t),!e.documentsStore.store(o,s,c,t))throw fH(`DOCUMENT_ALREADY_EXISTS`,s);let l=e.documentsStore.count(o),u=e.index.getSearchableProperties(a),d=e.index.getSearchablePropertiesWithTypes(a),f=e.getDocumentProperties(t,u);for(let[e,t]of Object.entries(f)){if(t===void 0)continue;let n=typeof t,r=d[e];kW(n,r,e,t)}return await AW(e,s,u,f,l,n,t,i),r||await HH(e.afterInsert,e,s,t),s}function OW(e,t,n,r,i){let{index:a,docs:o}=e.data,s=e.getDocumentIndexId(t);if(typeof s!=`string`)throw fH(`DOCUMENT_ID_MUST_BE_STRING`,typeof s);let c=EH(e.internalDocumentIDStore,s);if(r||HH(e.beforeInsert,e,s,t),!e.documentsStore.store(o,s,c,t))throw fH(`DOCUMENT_ALREADY_EXISTS`,s);let l=e.documentsStore.count(o),u=e.index.getSearchableProperties(a),d=e.index.getSearchablePropertiesWithTypes(a),f=e.getDocumentProperties(t,u);for(let[e,t]of Object.entries(f)){if(t===void 0)continue;let n=typeof t,r=d[e];kW(n,r,e,t)}return jW(e,s,u,f,l,n,t,i),r||HH(e.afterInsert,e,s,t),s}function kW(e,t,n,r){if(!(vH(t)&&typeof r==`object`&&typeof r.lon==`number`&&typeof r.lat==`number`)&&!(yH(t)&&Array.isArray(r))&&!(bH(t)&&Array.isArray(r))&&!(TW.has(t)&&EW.has(e))&&e!==t)throw fH(`INVALID_DOCUMENT_PROPERTY`,n,t,e)}async function AW(e,t,n,r,i,a,o,s){for(let o of n){let n=r[o];if(n===void 0)continue;let c=e.index.getSearchablePropertiesWithTypes(e.data.index)[o];await e.index.beforeInsert?.(e.data.index,o,t,n,c,a,e.tokenizer,i);let l=e.internalDocumentIDStore.idToInternalId.get(t);await e.index.insert(e.index,e.data.index,o,t,l,n,c,a,e.tokenizer,i,s),await e.index.afterInsert?.(e.data.index,o,t,n,c,a,e.tokenizer,i)}let c=e.sorter.getSortableProperties(e.data.sorting),l=e.getDocumentProperties(o,c);for(let n of c){let r=l[n];if(r===void 0)continue;let i=e.sorter.getSortablePropertiesWithTypes(e.data.sorting)[n];e.sorter.insert(e.data.sorting,n,t,r,i,a)}}function jW(e,t,n,r,i,a,o,s){for(let o of n){let n=r[o];if(n===void 0)continue;let c=e.index.getSearchablePropertiesWithTypes(e.data.index)[o],l=EH(e.internalDocumentIDStore,t);e.index.beforeInsert?.(e.data.index,o,t,n,c,a,e.tokenizer,i),e.index.insert(e.index,e.data.index,o,t,l,n,c,a,e.tokenizer,i,s),e.index.afterInsert?.(e.data.index,o,t,n,c,a,e.tokenizer,i)}let c=e.sorter.getSortableProperties(e.data.sorting),l=e.getDocumentProperties(o,c);for(let n of c){let r=l[n];if(r===void 0)continue;let i=e.sorter.getSortablePropertiesWithTypes(e.data.sorting)[n];e.sorter.insert(e.data.sorting,n,t,r,i,a)}}function MW(e,t,n,r,i,a){return iH(e.afterInsertMultiple)||iH(e.beforeInsertMultiple)||iH(e.index.beforeInsert)||iH(e.index.insert)||iH(e.index.afterInsert)?NW(e,t,n,r,i,a):PW(e,t,n,r,i,a)}async function NW(e,t,n=1e3,r,i,a=0){let o=[],s=async a=>{let s=Math.min(a+n,t.length),c=t.slice(a,s);for(let t of c){let n=await wW(e,t,r,i,{avlRebalanceThreshold:c.length});o.push(n)}return s};return await(async()=>{let e=0;for(;e<t.length;){let t=Date.now();if(e=await s(e),a>0){let e=a-(Date.now()-t);e>0&&uH(e)}}})(),i||await UH(e.afterInsertMultiple,e,t),o}function PW(e,t,n=1e3,r,i,a=0){let o=[],s=0;function c(){let a=t.slice(s*n,(s+1)*n);if(a.length===0)return!1;for(let t of a){let n=wW(e,t,r,i,{avlRebalanceThreshold:a.length});o.push(n)}return s++,!0}function l(){let e=Date.now();for(;c();)if(a>0){let t=Date.now()-e;if(t>=a){let e=a-t%a;e>0&&uH(e)}}}return l(),i||UH(e.afterInsertMultiple,e,t),o}function FW(e,t){return e[1]-t[1]}function IW(e,t){return t[1]-e[1]}function LW(e=`desc`){return e.toLowerCase()===`asc`?FW:IW}function RW(e,t,n){let r={},i=t.map(([e])=>e),a=e.documentsStore.getMultiple(e.data.docs,i),o=Object.keys(n),s=e.index.getSearchablePropertiesWithTypes(e.data.index);for(let e of o){let t;if(s[e]===`number`){let{ranges:r}=n[e],i=r.length,a=Array.from({length:i});for(let e=0;e<i;e++){let t=r[e];a[e]=[`${t.from}-${t.to}`,0]}t=Object.fromEntries(a)}r[e]={count:0,values:t??{}}}let c=a.length;for(let e=0;e<c;e++){let t=a[e];for(let e of o){let i=e.includes(`.`)?eH(t,e):t[e],a=s[e],o=r[e].values;switch(a){case`number`:{let t=n[e].ranges;zW(t,o)(i);break}case`number[]`:{let t=new Set,r=n[e].ranges,a=zW(r,o,t);for(let e of i)a(e);break}case`boolean`:case`enum`:case`string`:BW(o,a)(i);break;case`boolean[]`:case`enum[]`:case`string[]`:{let e=BW(o,a===`boolean[]`?`boolean`:`string`,new Set);for(let t of i)e(t);break}default:throw fH(`FACET_NOT_SUPPORTED`,a)}}}for(let e of o){let t=r[e];if(t.count=Object.keys(t.values).length,s[e]===`string`){let r=n[e],i=LW(r.sort);t.values=Object.fromEntries(Object.entries(t.values).sort(i).slice(r.offset??0,r.limit??10))}}return r}function zW(e,t,n){return r=>{for(let i of e){let e=`${i.from}-${i.to}`;n?.has(e)||r>=i.from&&r<=i.to&&(t[e]===void 0?t[e]=1:(t[e]++,n?.add(e)))}}}function BW(e,t,n){let r=t===`boolean`?`false`:``;return t=>{let i=t?.toString()??r;n?.has(i)||(e[i]=(e[i]??0)+1,n?.add(i))}}const VW={reducer:(e,t,n,r)=>(t[r]=n,t),getInitialValue:e=>Array.from({length:e})},HW=[`string`,`number`,`boolean`];function UW(e,t,n){let r=n.properties,i=r.length,a=e.index.getSearchablePropertiesWithTypes(e.data.index);for(let e=0;e<i;e++){let t=r[e];if(a[t]===void 0)throw fH(`UNKNOWN_GROUP_BY_PROPERTY`,t);if(!HW.includes(a[t]))throw fH(`INVALID_GROUP_BY_PROPERTY`,t,HW.join(`, `),a[t])}let o=t.map(([t])=>DH(e.internalDocumentIDStore,t)),s=e.documentsStore.getMultiple(e.data.docs,o),c=s.length,l=n.maxResult||2**53-1,u=[],d={};for(let e=0;e<i;e++){let t=r[e],n={property:t,perValue:{}},i=new Set;for(let e=0;e<c;e++){let r=s[e],a=eH(r,t);if(a===void 0)continue;let o=typeof a==`boolean`?``+a:a,c=n.perValue[o]??{indexes:[],count:0};c.count>=l||(c.indexes.push(e),c.count++,n.perValue[o]=c,i.add(a))}u.push(Array.from(i)),d[t]=n}let f=WW(u),p=f.length,m=[];for(let e=0;e<p;e++){let t=f[e],n=t.length,i={values:[],indexes:[]},a=[];for(let e=0;e<n;e++){let n=t[e],o=r[e];a.push(d[o].perValue[typeof n==`boolean`?``+n:n].indexes),i.values.push(n)}i.indexes=QV(a).sort((e,t)=>e-t),i.indexes.length!==0&&m.push(i)}let h=m.length,g=Array.from({length:h});for(let e=0;e<h;e++){let r=m[e],i=n.reduce||VW,a=r.indexes.map(e=>({id:o[e],score:t[e][1],document:s[e]})),c=i.reducer.bind(null,r.values),l=i.getInitialValue(r.indexes.length),u=a.reduce(c,l);g[e]={values:r.values,result:u}}return g}function WW(e,t=0){if(t+1===e.length)return e[t].map(e=>[e]);let n=e[t],r=WW(e,t+1),i=[];for(let e of n)for(let t of r){let n=[e];HV(n,t),i.push(n)}return i}function GW(e,t,n,r){let i=gW(t,r);if(i.length===0)return n;let a=i.flatMap(e=>e.consequence.promote);a.sort((e,t)=>e.position-t.position);let o=new Set,s=new Map,c=new Set;for(let t of a){let n=EH(e.internalDocumentIDStore,t.doc_id);if(n!==void 0){if(s.has(n)){let e=s.get(n);t.position<e&&s.set(n,t.position);continue}c.has(t.position)||(o.add(n),s.set(n,t.position),c.add(t.position))}}if(s.size===0)return n;let l=n.filter(([e])=>!o.has(e)),u=[];for(let[t,r]of s.entries())n.find(([e])=>e===t)?u.push([t,1e6-r]):e.documentsStore.get(e.data.docs,t)&&u.push([t,0]);u.sort((e,t)=>(s.get(e[0])??1/0)-(s.get(t[0])??1/0));let d=[],f=new Map;for(let e of u){let t=s.get(e[0]);f.set(t,e)}let p=0,m=0;for(;m<l.length+u.length;)if(f.has(m))d.push(f.get(m)),m++;else if(p<l.length)d.push(l[p]),p++,m++;else break;for(let[e,t]of f.entries())e>=d.length&&d.push(t);return d}function KW(e,t,n){let{term:r,properties:i}=t,a=e.data.index,o=e.caches.propertiesToSearch;if(!o){let t=e.index.getSearchablePropertiesWithTypes(a);o=e.index.getSearchableProperties(a),o=o.filter(e=>t[e].startsWith(`string`)),e.caches.propertiesToSearch=o}if(i&&i!==`*`){for(let e of i)if(!o.includes(e))throw fH(`UNKNOWN_INDEX`,e,o.join(`, `));o=o.filter(e=>i.includes(e))}let s=Object.keys(t.where??{}).length>0,c;s&&(c=e.index.searchByWhereClause(a,e.tokenizer,t.where,n));let l,u=t.threshold!==void 0&&t.threshold!==null?t.threshold:1;if(r||i){let i=CW(e);if(l=e.index.search(a,r||``,e.tokenizer,n,o,t.exact||!1,t.tolerance||0,t.boost||{},ZW(t.relevance),i,c,u),t.exact&&r){let t=r.trim().split(/\s+/);l=l.filter(([n])=>{let r=e.documentsStore.get(e.data.docs,n);if(!r)return!1;for(let e of o){let n=JW(r,e);if(typeof n==`string`&&t.every(e=>RegExp(`\\b${qW(e)}\\b`).test(n)))return!0}return!1})}}else l=s?OU(a,t.where)||(c?Array.from(c):[]).map(e=>[+e,0]):Object.keys(e.documentsStore.getAll(e.data.docs)).map(e=>[+e,0]);return l}function qW(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function JW(e,t){let n=t.split(`.`),r=e;for(let e of n)if(r&&typeof r==`object`&&e in r)r=r[e];else return;return r}function YW(e,t,n){let r=JV();function i(){let i=Object.keys(e.data.index.vectorIndexes),a=t.facets&&Object.keys(t.facets).length>0,{limit:o=10,offset:s=0,distinctOn:c,includeVectors:l=!1}=t,u=t.preflight===!0,d=KW(e,t,n);if(t.sortBy)if(typeof t.sortBy==`function`){let n=d.map(([e])=>e),r=e.documentsStore.getMultiple(e.data.docs,n).map((e,t)=>[d[t][0],d[t][1],e]);r.sort(t.sortBy),d=r.map(([e,t])=>[e,t])}else d=e.sorter.sortBy(e.data.sorting,d,t.sortBy).map(([t,n])=>[EH(e.internalDocumentIDStore,t),n]);else d=d.sort(ZV);d=GW(e,e.data.pinning,d,t.term);let f;u||(f=c?lG(e,d,s,o,c):uG(e,d,s,o));let p={elapsed:{formatted:``,raw:0},hits:[],count:d.length};return f!==void 0&&(p.hits=f.filter(Boolean),l||rH(p,i)),a&&(p.facets=RW(e,d,t.facets)),t.groupBy&&(p.groups=UW(e,d,t.groupBy)),p.elapsed=e.formatElapsedTime(JV()-r),p}async function a(){e.beforeSearch&&await GH(e.beforeSearch,e,t,n);let r=i();return e.afterSearch&&await WH(e.afterSearch,e,t,n,r),r}return e.beforeSearch?.length||e.afterSearch?.length?a():i()}const XW={k:1.2,b:.75,d:.5};function ZW(e){let t=e??{};return t.k=t.k??XW.k,t.b=t.b??XW.b,t.d=t.d??XW.d,t}function QW(e,t,n){let r=t.vector;if(r&&(!(`value`in r)||!(`property`in r)))throw fH(`INVALID_VECTOR_INPUT`,Object.keys(r).join(`, `));let i=e.data.index.vectorIndexes[r.property];if(!i)throw fH(`UNKNOWN_VECTOR_PROPERTY`,r.property);let a=i.node.size;if(r?.value.length!==a)throw r?.property===void 0||r?.value.length===void 0?fH(`INVALID_INPUT_VECTOR`,`undefined`,a,`undefined`):fH(`INVALID_INPUT_VECTOR`,r.property,a,r.value.length);let o=e.data.index,s;return Object.keys(t.where??{}).length>0&&(s=e.index.searchByWhereClause(o,e.tokenizer,t.where,n)),i.node.find(r.value,t.similarity??.8,s)}function $W(e,t,n=`english`){let r=JV();function i(){let i=QW(e,t,n).sort(ZV);i=GW(e,e.data.pinning,i,void 0);let a=[];t.facets&&Object.keys(t.facets).length>0&&(a=RW(e,i,t.facets));let o=t.vector.property,s=t.includeVectors??!1,c=t.limit??10,l=t.offset??0,u=Array.from({length:c});for(let t=0;t<c;t++){let n=i[t+l];if(!n)break;let r=e.data.docs.docs[n[0]];r&&(s||(r[o]=null),u[t]={id:DH(e.internalDocumentIDStore,n[0]),score:n[1],document:r})}let d=[];t.groupBy&&(d=UW(e,i,t.groupBy));let f=JV()-r;return{count:i.length,hits:u.filter(Boolean),elapsed:{raw:Number(f),formatted:qV(f)},...a?{facets:a}:{},...d?{groups:d}:{}}}async function a(){e.beforeSearch&&await GH(e.beforeSearch,e,t,n);let r=i();return e.afterSearch&&await WH(e.afterSearch,e,t,n,r),r}return e.beforeSearch?.length||e.afterSearch?.length?a():i()}function eG(e,t,n){let r=rG(KW(e,t,n)),i=QW(e,t,n),a=t.hybridWeights;return oG(r,i,t.term??``,a)}function tG(e,t,n){let r=JV();function i(){let i=eG(e,t,n);i=GW(e,e.data.pinning,i,t.term);let a;t.facets&&Object.keys(t.facets).length>0&&(a=RW(e,i,t.facets));let o;t.groupBy&&(o=UW(e,i,t.groupBy));let s=t.offset??0,c=t.limit??10,l=uG(e,i,s,c).filter(Boolean),u=JV(),d={count:i.length,elapsed:{raw:Number(u-r),formatted:qV(u-r)},hits:l,...a?{facets:a}:{},...o?{groups:o}:{}};return(t.includeVectors??!1)||rH(d,Object.keys(e.data.index.vectorIndexes)),d}async function a(){e.beforeSearch&&await GH(e.beforeSearch,e,t,n);let r=i();return e.afterSearch&&await WH(e.afterSearch,e,t,n,r),r}return e.beforeSearch?.length||e.afterSearch?.length?a():i()}function nG(e){return e[1]}function rG(e){let t=Math.max.apply(Math,e.map(nG));return e.map(([e,n])=>[e,n/t])}function iG(e,t){return e/t}function aG(e,t){return(n,r)=>n*e+r*t}function oG(e,t,n,r){let i=Math.max.apply(Math,e.map(nG)),a=Math.max.apply(Math,t.map(nG)),{text:o,vector:s}=r&&r.text&&r.vector?r:sG(n),c=new Map,l=e.length,u=aG(o,s);for(let t=0;t<l;t++){let[n,r]=e[t],a=u(iG(r,i),0);c.set(n,a)}let d=t.length;for(let e=0;e<d;e++){let[n,r]=t[e],i=iG(r,a),o=c.get(n)??0;c.set(n,o+u(0,i))}return[...c].sort((e,t)=>t[1]-e[1])}function sG(e){return{text:.5,vector:.5}}function cG(e,t,n){let r=t.mode??`fulltext`;if(r===`fulltext`)return YW(e,t,n);if(r===`vector`)return $W(e,t);if(r===`hybrid`)return tG(e,t);throw fH(`INVALID_SEARCH_MODE`,r)}function lG(e,t,n,r,i){let a=e.data.docs,o=new Map,s=[],c=new Set,l=t.length,u=0;for(let d=0;d<l;d++){let l=t[d];if(l===void 0)continue;let[f,p]=l;if(c.has(f))continue;let m=e.documentsStore.get(a,f),h=eH(m,i);if(!(h===void 0||o.has(h))&&(o.set(h,!0),u++,!(u<=n)&&(s.push({id:DH(e.internalDocumentIDStore,f),score:p,document:m}),c.add(f),u>=n+r)))break}return s}function uG(e,t,n,r){let i=e.data.docs,a=Array.from({length:r}),o=new Set;for(let s=n;s<r+n;s++){let n=t[s];if(n===void 0)break;let[r,c]=n;if(!o.has(r)){let t=e.documentsStore.get(i,r);a[s]={id:DH(e.internalDocumentIDStore,r),score:c,document:t},o.add(r)}}return a}var dG=n(DV(),1);const fG=1,pG={protocol:`x-ok-client-protocol`,runtime:`x-ok-client-runtime`,kind:`x-ok-client-kind`};function mG({kind:e,runtimeVersion:t}){return{[pG.protocol]:`1`,[pG.runtime]:t,[pG.kind]:e}}const hG=`__system__`,gG=1,_G=`__config__/project`,vG=`__user__/config.yml`,yG=`__local__/project`,bG=`__config__/okignore`,xG=Object.freeze([_G,yG,vG,bG]),SG=`__skill__/`,CG=`__template__/`,wG=[`project`,`global`];function TG(e){return e.startsWith(`__skill__/`)||e.startsWith(`__template__/`)}const EG=`.ok/skills`;function DG(e){return`${EG}/${e}/SKILL`}const OG=[`references`,`scripts`];function kG(e,t){let n=/^(\.ok\/skills\/[^/]+)\/SKILL$/.exec(t);if(!n)return null;let r=n[1],i=e.trim().replace(/\.mdx?$/i,``).split(`/`).filter(e=>e!==``&&e!==`.`),[a]=i;return!a||!OG.includes(a)||i.includes(`..`)||i.length<2?null:`${r}/${i.join(`/`)}`}const AG=/^\.ok\/skills\/([^/]+)\/(SKILL|references\/.+)$/;function jG(e){let t=AG.exec(e);if(!t)return null;let n=t[1],r=t[2];return r===`SKILL`?{name:n,kind:`skill`,rel:null}:{name:n,kind:`reference`,rel:r.slice(11)}}const MG=/^__skill__\/global\/([^/]+)(?:\/(references\/.+))?$/;function NG(e){let t=MG.exec(e);if(!t)return null;let n=t[1],r=t[2];return r===void 0?{name:n,kind:`skill`,rel:null}:{name:n,kind:`reference`,rel:r.slice(11)}}function PG(e,t){return e===`project`?DG(t):`${SG}${e}/${t}`}function FG(e){if(e===``)return``;try{return e.split(`/`).map(e=>decodeURIComponent(e)).join(`/`)}catch{return e}}function IG(e){if(e.startsWith(`__skill__/`)){let t=e.slice(10),n=t.indexOf(`/`);if(n<0)return null;let r=t.slice(0,n);if(r!==`global`&&r!==`project`)return null;let i=t.slice(n+1);return i?{kind:`skill`,scope:r,name:FG(i)}:null}if(e.startsWith(`__template__/`)){let t=e.slice(13);if(!t)return null;let n=t.lastIndexOf(`/`),r=n<0?t:t.slice(n+1);return r?{kind:`template`,folder:FG(n<0?``:t.slice(0,n)),name:FG(r)}:null}return null}const LG=/^(?:(.+)\/)?\.ok\/templates\/([^/]+?)(?:\.mdx?)?$/;function RG(e){let t=LG.exec(e);if(t){let e=(t[1]??``).replace(/^\/+|\/+$/g,``);return`${CG}${e?`${e}/`:``}${t[2]}`}return null}const zG=[`.mdx`,`.md`],BG=`epoch`,VG=512*1024,HG=[`claude`,`claude-desktop`,`cursor`,`codex`,`opencode`,`openclaw`,`pi`],UG={claude:`Claude`,"claude-desktop":`Claude Desktop`,cursor:`Cursor`,codex:`Codex`,opencode:`OpenCode`,openclaw:`OpenClaw`,pi:`Pi`},WG={claude:`.claude/skills`,"claude-desktop":null,cursor:`.cursor/skills`,codex:`.codex/skills`,opencode:`.opencode/skills`,openclaw:null,pi:`.pi/skills`},GG=HG.filter(e=>WG[e]!==null),KG=GG.filter(e=>e!==`pi`).map(e=>({hostDir:(WG[e]??``).split(`/`)[0],editorId:e})),qG={claude:`.mcp.json`,"claude-desktop":null,cursor:`.cursor/mcp.json`,codex:`.codex/config.toml`,opencode:`opencode.json`,openclaw:null,pi:`.pi/extensions/open-knowledge.ts`},JG={cursor:/\bCursor(?:\([^)]+\))?\/\d/,codex:/\bCodex(?:\([^)]+\))?\/\d/,"claude-desktop":/\bClaude(?:\([^)]+\))?\/\d/},YG=`Ov23liqlSd0V1MwR6rhI`,XG=[`incoming`,`outgoing`,`both`];function ZG(e){return XG.includes(e)}const QG=`open-knowledge`,$G=[{id:`chart`,title:`Chart`,description:`A bar chart whose series colors track the OK chart palette.`,html:`<div style="font-family:system-ui,sans-serif;padding:20px;color:var(--foreground)">
|
|
305
305
|
<h3 style="margin:0 0 14px;font-size:15px;font-weight:600">Revenue by region</h3>
|
|
306
306
|
<div id="bars" style="display:flex;align-items:flex-end;gap:14px;height:170px"></div>
|
|
307
307
|
<script>
|
|
@@ -450,4 +450,4 @@ $2`).split(`
|
|
|
450
450
|
`);if(!(t[0]??``).startsWith(`template:`))return null;let n=[t[0]??``],r=1;for(;r<t.length;){let e=t[r]??``;if(/^[ \t]/.test(e)){n.push(e),r++;continue}if(e.trim()===``){let i=r+1;for(;i<t.length&&(t[i]??``).trim()===``;)i++;if(i<t.length&&/^[ \t]/.test(t[i]??``)){n.push(e),r++;continue}}break}let i=f6(n.join(`
|
|
451
451
|
`))[d6];return{identity:typeof i==`object`&&i&&!Array.isArray(i)?i:{},docFrontmatterText:t.slice(r).join(`
|
|
452
452
|
`).replace(/\n+$/,``)}}function g6(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,{frontmatter:n,body:r}=uK(t);if(n===``)return{identity:{},starterContent:t};let i=fK(n),a=h6(i);if(a)return{identity:a.identity,starterContent:p6(a.docFrontmatterText,r)};let{frontmatter:o}=uK(r);if(o!==``)return{identity:f6(i),starterContent:r};let s=f6(i);return typeof s.title==`string`?{identity:s,starterContent:r}:{identity:{},starterContent:p6(i,r)}}function _6(e,t){let{docFrontmatterText:n,markdown:r}=m6(t),i={};for(let[t,n]of Object.entries(e))n!==void 0&&(i[t]=n);let a=(0,Fc.stringify)({[d6]:i});return`---\n${n.trim()===``?a:`${a}${n}\n`}---\n${r}`}function v6(e){return g6(e).starterContent}function y6(){let e=!1,t=``,n=0;return r=>{let i=b6(r);return e?(i&&i.char===t&&i.len>=n&&!i.hasInfo&&(e=!1,t=``,n=0),!0):i?(e=!0,t=i.char,n=i.len,!0):!1}}function b6(e){let t=(e.endsWith(`\r`)?e.slice(0,-1):e).match(/^ {0,3}([`~])(\1{2,})(.*)$/);return t?{char:t[1],len:1+t[2].length,hasInfo:t[3].trim()!==``}:null}const x6=[`#D97757`,`#1B1912`,`#F9F3E9`,`#7A9DFF`,`#8534F3`,`#9663F0`,`#727CF3`],S6={claude:`#D97757`,cursor:`#1B1912`,windsurf:`#0B100F`,openai:`#7A9DFF`,github:`#8534F3`,cline:`#9663F0`,bot:`#727CF3`};function C6(e,t=x6){let n=0;for(let t of e)n=(n<<5)-n+t.charCodeAt(0)|0;return t[Math.abs(n)%t.length]}const w6={"claude-code":`claude`,"claude-ai":`claude`,cursor:`cursor`,"cursor-vscode":`cursor`,cascade:`windsurf`,codex:`openai`,"codex-mcp-client":`openai`,copilot:`github`,cline:`cline`};function T6(e){return e?w6[e]||(e.startsWith(`local-agent-mode-`)?`claude`:`bot`):`bot`}const E6={claude:`Claude`,cursor:`Cursor`,windsurf:`Windsurf`,openai:`Codex`,github:`Copilot`,cline:`Cline`};function D6(e){let t=e?.trim();return t?E6[T6(t)]??t:`Agent`}function O6(e,t){let n=e.trim();if(!n||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(n)||n.startsWith(`//`)||n.startsWith(`#`))return null;let r=n.indexOf(`#`),i=r>=0?n.slice(0,r):n,a=r>=0?n.slice(r+1):null,o=(i.split(`?`)[0]??``).trim();if(!o)return null;let s=(o.split(`/`).pop()??``).match(/\.([a-z0-9]+)$/i);if(s){let e=(s[1]??``).toLowerCase();if(e!==`md`&&e!==`mdx`)return null}let c=o.toLowerCase(),l=c.endsWith(`.mdx`)?o.slice(0,-4):c.endsWith(`.md`)?o.slice(0,-3):o,u=l.startsWith(`/`),d=u?l.slice(1):l,f=u?[]:t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of d.split(`/`))if(e===`..`){if(f.length===0)return null;f.pop()}else e!==`.`&&e!==``&&f.push(e);return f.length===0?null:{docName:f.join(`/`),anchor:a||null}}const k6=/^[a-zA-Z][a-zA-Z\d+\-.]*:/;function A6(e){let t=(e.split(/[?#]/)[0]??e).match(/\.([a-z0-9]+)$/i);return t?(t[1]??``).toLowerCase():null}function j6(e){let t=e.trim();return k6.test(t)||t.startsWith(`//`)}function M6(e,t){let n=e.trim();if(!n)return null;if(n.startsWith(`#`)){let e=n.slice(1).trim();return e?{kind:`anchor`,anchor:e}:null}if(j6(n))return{kind:`external`,url:n};let r=O6(n,t);if(r)return{kind:`doc`,docName:r.docName,anchor:r.anchor};let i=A6(n);return i&&i!==`md`&&i!==`mdx`?{kind:`asset`,url:n,ext:i}:null}function N6(e,t){let n=e.trim();if(!n)return null;if(j6(n))return{kind:`external`,url:t?`${n}#${t}`:n};let r=A6(n);return r&&r!==`md`&&r!==`mdx`?{kind:`asset`,url:n,ext:r}:{kind:`doc`,docName:n,anchor:t?.trim()||null}}function P6(e,t){let n=e.trim();if(!n||k6.test(n)||n.startsWith(`//`)||n.startsWith(`#`))return null;let r=n.indexOf(`#`),i=((r>=0?n.slice(0,r):n).split(`?`)[0]??``).trim();if(!i)return null;let a=i.startsWith(`/`),o=a?i.slice(1):i,s=a?[]:t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of o.split(`/`))if(e===`..`){if(s.length===0)return null;s.pop()}else e!==`.`&&e!==``&&s.push(e);return s.length===0?null:s.join(`/`)}function F6(e){let t=e;return t.startsWith(`./`)&&(t=t.slice(2)),t.startsWith(`/`)&&(t=t.slice(1)),t}function I6(e){let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function L6(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function R6(e){return e.split(`/`).filter(e=>e!==``)}function z6(e,t){let n=L6(t);return e===``||n===e?!0:n.startsWith(`${e}/`)}function B6(e,t){let n=L6(t);if(e===n)return 0;let r=e===``?n:n.slice(e.length+1);return r===``?0:R6(r).length}function V6(e,t){let n=R6(e),r=R6(t),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i++;return n.length-i+(r.length-i)}function H6(){let e=new Map;function t(t){let n=F6(t);if(n===``)return;let r=I6(n);if(r===``)return;let i=r.toLowerCase(),a=e.get(i);if(!a){e.set(i,[n]);return}a.includes(n)||a.push(n)}function n(t){let n=F6(t),r=I6(n).toLowerCase(),i=e.get(r);if(!i)return;let a=i.indexOf(n);a!==-1&&(i.splice(a,1),i.length===0&&e.delete(r))}function r(e,r){n(e),t(r)}function i(t,n){let r=t.toLowerCase(),i=e.get(r);if(!i||i.length===0)return null;if(i.length===1)return i[0];let a=L6(F6(n)),o=[],s=[];for(let e of i)z6(a,e)?o.push(e):s.push(e);return o.length>0?(e=>{let t=e[0],n=B6(a,t);for(let r=1;r<e.length;r++){let i=e[r],o=B6(a,i);(o<n||o===n&&i<t)&&(t=i,n=o)}return t})(o):(e=>{let t=e[0],n=V6(a,L6(t));for(let r=1;r<e.length;r++){let i=e[r],o=V6(a,L6(i));(o<n||o===n&&i<t)&&(t=i,n=o)}return t})(s)}function a(){let t=new Map;for(let[n,r]of e)t.set(n,[...r]);return t}function o(){e.clear()}return{add:t,remove:n,rename:r,resolveEmbed:i,clear:o,snapshot:a,size:()=>e.size}}function U6(e){if(!e)return[];let t=e.split(`/`),n=[],r=``;for(let e of t)r=r?`${r}/${e}`:e,n.push(r);return n}function W6(e,t){if(e.size===0)return new Set;if(t===``)return new Set(e);let n=new Set,r=`${t}/`;for(let i of e)(i===t||i.startsWith(r))&&n.add(i);return n}function G6(e){try{return process.kill(e,0),!0}catch(e){return!!(e&&typeof e==`object`&&`code`in e&&e.code===`EPERM`)}}function K6(e){return!(typeof e!=`number`||!Number.isInteger(e)||e<2||e>2147483647)}const q6=/^[A-Za-z0-9-]{8,64}$/;let J6=null;function Y6(e){return l(e??m(),`.ok`,`machine-id`)}function X6(e){if(e===void 0&&J6!==null)return J6;let t=Y6(e),n=null;try{let e=b(t,`utf-8`).trim();q6.test(e)&&(n=e)}catch{}if(n===null){n=w();try{v(c(t),{recursive:!0}),S(t,`${n}\n`,{encoding:`utf-8`,mode:384})}catch(e){console.warn(`[machine-id] Failed to persist ${t} — using an ephemeral per-process id; lock ownership checks will fail closed (collision) instead of recognizing this machine: ${e instanceof Error?e.message:String(e)}`)}}return e===void 0&&(J6=n),n}function Z6(){try{let e=u(c(f(import.meta.url)),`..`,`package.json`),t=JSON.parse(b(e,`utf-8`));if(typeof t.version==`string`&&t.version.length>0)return t.version}catch{}return`0.0.0-unknown`}const Q6=Z6(),$6=1;var e8=class extends Error{existing;lockPath;lockName;constructor(e,t,n){super(`OpenKnowledge ${n} already running on port ${e.port} (pid ${e.pid}, started ${e.startedAt}). Stop it first or use a different directory. Lock: ${t}`),this.name=`ProcessLockCollisionError`,this.existing=e,this.lockPath=t,this.lockName=n}};function t8(e,t){return u(e,`${t}.lock`)}const n8=new Map;function r8(e){n8.set(e,(n8.get(e)??0)+1)}function i8(e){let t=n8.get(e);return t===void 0||t<=1?(n8.delete(e),!0):(n8.set(e,t-1),!1)}function a8(e){return typeof e.machineId==`string`?e.machineId===X6():e.hostname===h()}const o8=new Set;let s8=!1;function c8(e){o8.add(e),!s8&&(s8=!0,process.on(`exit`,()=>{for(let e of o8)try{let t=JSON.parse(b(e,`utf-8`));if(t?.pid!==process.pid||typeof t.machineId==`string`&&t.machineId!==X6()||t.machineId===void 0&&typeof t.hostname==`string`&&t.hostname!==h())continue;x(e)}catch{}}))}function l8(e,t){try{let n=JSON.parse(b(e,`utf-8`));return n&&typeof n==`object`&&K6(n.pid)?n:(console.warn(`${t} Corrupt lock file at ${e} — replacing`),null)}catch{return console.warn(`${t} Corrupt lock file at ${e} — replacing`),null}}function u8(e){let{lockName:t,lockDir:n,metadata:r}=e,i=`[${t}-lock]`;v(n,{recursive:!0});let a=t8(n,t),o={pid:process.pid,hostname:h(),port:r.port,startedAt:new Date().toISOString(),worktreeRoot:r.worktreeRoot,machineId:X6(),...r.kind!==void 0&&{kind:r.kind},...r.parentPid!==void 0&&{parentPid:r.parentPid},...r.capabilities!==void 0&&{capabilities:r.capabilities},protocolVersion:r.protocolVersion??1,runtimeVersion:r.runtimeVersion??Q6},s=JSON.stringify(o,null,2);for(let e=0;e<3;e++){if(!_(a))try{let e=y(a,`wx`,384);try{C(e,s)}finally{g(e)}return r8(a),c8(a),d8({lockName:t,lockDir:n,lockPath:a})}catch(e){if(e.code!==`EEXIST`)throw e}let e=l8(a,i);if(e){if(a8(e)&&e.pid===process.pid)return S(a,s,{encoding:`utf-8`,mode:384}),r8(a),c8(a),d8({lockName:t,lockDir:n,lockPath:a});if(G6(e.pid))throw new e8(e,a,t);console.warn(`${i} Stale lock detected (pid=${e.pid}, host=${e.hostname}) — replacing`)}try{x(a)}catch{}}throw Error(`${i} Failed to acquire ${a} after 3 attempts (concurrent acquire contention).`)}function d8(e){let{lockName:t,lockDir:n,lockPath:r}=e;return{lockPath:r,release:()=>_8({lockName:t,lockDir:n}),updatePort:e=>f8({lockName:t,lockDir:n,port:e})}}function f8(e){let{lockName:t,lockDir:n,port:r}=e,i=`[${t}-lock]`,a=t8(n,t);if(!_(a)){console.warn(`${i} Lock file missing at ${a} during port update — skipping`);return}let o;try{let e=JSON.parse(b(a,`utf-8`));if(!e||typeof e!=`object`||!K6(e.pid)){console.warn(`${i} Corrupt lock at ${a} during port update — skipping`);return}o=e}catch{console.warn(`${i} Unreadable lock at ${a} during port update — skipping`);return}if(o.pid===process.pid&&a8(o)){o.port=r;try{S(a,JSON.stringify(o,null,2),{encoding:`utf-8`,mode:384})}catch(e){console.warn(`${i} Failed to update port in ${a}: ${e instanceof Error?e.message:String(e)}`)}}}function p8(e){let{lockName:t,lockDir:n}=e,r=`[${t}-lock]`,i=t8(n,t);if((n8.get(i)??0)>1)return;let a;try{let e=JSON.parse(b(i,`utf-8`));if(!e||typeof e!=`object`||!K6(e.pid)){console.warn(`${r} Corrupt lock at ${i} during draining mark — skipping`);return}a=e}catch(e){e.code!==`ENOENT`&&console.warn(`${r} Unreadable lock at ${i} during draining mark — skipping: ${e instanceof Error?e.message:String(e)}`);return}if(a.pid===process.pid&&a8(a)&&a.draining!==!0){a.draining=!0;try{S(i,JSON.stringify(a,null,2),{encoding:`utf-8`,mode:384})}catch(e){console.warn(`${r} Failed to mark ${i} draining: ${e instanceof Error?e.message:String(e)}`)}}}function m8(e){let{lockName:t,lockDir:n}=e,r=t8(n,t);if(!_(r))return null;let i;try{let e=JSON.parse(b(r,`utf-8`));if(!e||typeof e!=`object`||!K6(e.pid))return null;i=e}catch{return null}if(!a8(i))return null;if(!G6(i.pid)){try{x(r)}catch{}return null}return i}function h8(e){let{lockName:t,lockDir:n}=e,r=t8(n,t);if(!_(r))return{status:`absent`};let i;try{i=JSON.parse(b(r,`utf-8`))}catch{return{status:`incompatible`,reason:`corrupt`,raw:void 0}}if(!i||typeof i!=`object`)return{status:`incompatible`,reason:`corrupt`,raw:i};let a=i;if(!K6(a.pid)||typeof a.hostname!=`string`||typeof a.port!=`number`||typeof a.startedAt!=`string`||typeof a.worktreeRoot!=`string`)return{status:`incompatible`,reason:`corrupt`,raw:i};let o={pid:a.pid,hostname:a.hostname,port:a.port,startedAt:a.startedAt,worktreeRoot:a.worktreeRoot,machineId:typeof a.machineId==`string`?a.machineId:void 0,draining:a.draining===!0?!0:void 0,protocolVersion:typeof a.protocolVersion==`number`?a.protocolVersion:void 0,runtimeVersion:typeof a.runtimeVersion==`string`?a.runtimeVersion:void 0};if(!a8(o))return{status:`stale`,lock:o};if(!G6(o.pid)){try{x(r)}catch{}return{status:`stale`,lock:o}}return o.protocolVersion===void 0||o.runtimeVersion===void 0?{status:`incompatible`,reason:`missing-fields`,raw:i}:{status:`live`,lock:o}}async function g8(e){let{lockName:t,lockDir:n}=e,r=e.timeoutMs??1e4,i=e.pollIntervalMs??100,a=e.readLock??(()=>m8({lockName:t,lockDir:n})),o=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),s=a();if(s===null||s.draining!==!0)return`no-drain`;let c=Date.now()+r;for(;Date.now()<c;){await o(i);let e=a();if(e===null)return`released`;if(e.draining!==!0)return`no-drain`}return`timeout`}function _8(e){let{lockName:t,lockDir:n,deferUnlinkToExit:r=!1}=e,i=`[${t}-lock]`,a=t8(n,t);if(i8(a)){if(r){p8({lockName:t,lockDir:n});return}if(_(a))try{let e=JSON.parse(b(a,`utf-8`));if(!e||typeof e!=`object`||typeof e.pid!=`number`||e.pid!==process.pid||!a8(e))return;x(a),o8.delete(a)}catch(e){console.warn(`${i} Failed to release ${a}: ${e instanceof Error?e.message:String(e)}`)}}}var v8=class extends e8{constructor(e,t){super(e,t,`server`),this.name=`ServerLockCollisionError`}};function y8(e,t){try{return u8({lockName:`server`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof e8&&e.lockName===`server`?new v8(e.existing,e.lockPath):e}}function b8(e,t){f8({lockName:`server`,lockDir:e,port:t})}function x8(e){return m8({lockName:`server`,lockDir:e})}function S8(e,t){_8({lockName:`server`,lockDir:e,...t})}function C8(e){p8({lockName:`server`,lockDir:e})}function w8(e,t){return g8({lockName:`server`,lockDir:e,...t})}export{pG as $,$l as $a,g6 as $i,u2 as $n,JG as $r,D1 as $t,A$ as A,qc as Aa,d$ as Ai,a6 as An,Ka as Ao,x0 as Ar,H0 as At,V$ as B,Xc as Ba,TG as Bi,D0 as Bn,Dt as Bo,Y0 as Br,m3 as Bt,z$ as C,fK as Ca,s3 as Ci,_1 as Cn,A as Co,c2 as Cr,t0 as Ct,G$ as D,ap as Da,U6 as Di,$0 as Dn,Go as Do,cJ as Dr,u1 as Dt,j$ as E,hb as Ea,Z3 as Ei,EG as En,xs as Eo,K1 as Er,WG as Et,n1 as F,Cl as Fa,v6 as Fi,d1 as Fn,fn as Fo,b0 as Fr,T$ as Ft,U2 as G,Yc as Ga,S4 as Gi,Sq as Gn,J0 as Gr,BG as Gt,G2 as H,su as Ha,e3 as Hi,T0 as Hn,O as Ho,X0 as Hr,N0 as Ht,t1 as I,xl as Ia,Lq as Ii,f1 as In,mn as Io,d6 as Ir,KG as It,R2 as J,Ll as Ja,NG as Ji,kq as Jn,R1 as Jr,E1 as Jt,B2 as K,Jc as Ka,G4 as Ki,Tq as Kn,K0 as Kr,s1 as Kt,Kq as L,bl as La,O$ as Li,D2 as Ln,gn as Lo,n2 as Lr,m1 as Lt,k$ as M,El as Ma,sY as Mi,l3 as Mn,si as Mo,C0 as Mr,i1 as Mt,U$ as N,Zc as Na,sq as Ni,zG as Nn,br as No,v0 as Nr,q$ as Nt,M$ as O,L as Oa,p3 as Oi,n6 as On,Uo as Oo,S1 as Or,Y1 as Ot,tJ as P,Sl as Pa,T6 as Pi,hG as Pn,un as Po,y0 as Pr,J$ as Pt,gG as Q,Tl as Qa,L0 as Qi,Zq as Qn,d0 as Qr,O1 as Qt,g4 as R,yl as Ra,gq as Ri,j2 as Rn,cn as Ro,B0 as Rr,h1 as Rt,HG as S,r$ as Sa,D6 as Si,s0 as Sn,ac as So,x2 as Sr,e0 as St,I1 as T,a4 as Ta,u6 as Ti,p0 as Tn,Ks as To,a2 as Tr,qG as Tt,W2 as U,ou as Ua,Fq as Ui,A2 as Un,ht as Uo,Z0 as Ur,G1 as Ut,V2 as V,fl as Va,ZG as Vi,A0 as Vn,k as Vo,G0 as Vr,j0 as Vt,H2 as W,tu as Wa,RG as Wi,$q as Wn,mt as Wo,q0 as Wr,_3 as Wt,I2 as X,Yl as Xa,IG as Xi,Pq as Xn,L1 as Xr,A1 as Xt,L2 as Y,iu as Ya,y3 as Yi,Mq as Yn,z1 as Yr,k1 as Yt,P2 as Z,Kl as Za,jG as Zi,Xq as Zn,u0 as Zr,sJ as Zt,S8 as _,PG as _a,k3 as _i,i0 as _n,Zs as _o,S2 as _r,x1 as _t,u8 as a,l4 as aa,m4 as ai,QG as an,kl as ao,v2 as ar,qq as at,w8 as b,W6 as ba,K4 as bi,iJ as bn,dc as bo,I0 as br,$$ as bt,G6 as c,P6 as ca,M6 as ci,H1 as cn,F as co,d2 as cr,X$ as ct,p8 as d,kG as da,C6 as di,v1 as dn,N as do,s2 as dr,X1 as dt,dK as ea,oJ as ei,C1 as en,pl as eo,_2 as er,xG as et,C8 as f,J3 as fa,_6 as fi,q4 as fn,M as fo,T2 as fr,Z1 as ft,_8 as g,pq as ga,hZ as gi,fG as gn,I as go,F0 as gr,VG as gt,x8 as h,dq as ha,y6 as hi,GG as hn,rc as ho,c6 as hr,c3 as ht,v8 as i,DG as ia,X2 as ii,wG as in,Ol as io,i2 as ir,vG as it,W$ as j,au as ja,a$ as ji,P0 as jn,qa as jo,S0 as jr,U0 as jt,K$ as k,cu as ka,VQ as ki,r6 as kn,ma as ko,w0 as kr,V0 as kt,K6 as l,l6 as la,N6 as li,V1 as ln,Hs as lo,f2 as lr,Q1 as lt,h8 as m,o3 as ma,H6 as mi,tK as mn,tc as mo,Q0 as mr,nK as mt,Q6 as n,b$ as na,g1 as ni,SG as nn,Rl as no,m2 as nr,_G as nt,y8 as o,y4 as oa,rJ as oi,HQ as on,Ls as oo,N2 as or,Yq as ot,m8 as p,n4 as pa,t2 as pi,$G as pn,jc as po,E2 as pr,YG as pt,F2 as q,Al as qa,t4 as qi,Aq as qn,B1 as qr,j1 as qt,$6 as r,b4 as ra,Z2 as ri,CG as rn,Fl as ro,h2 as rr,yG as rt,X6 as s,x$ as sa,Uq as si,W1 as sn,uc as so,y2 as sr,Y$ as st,e8 as t,eK as ta,aJ as ti,T1 as tn,wl as to,g2 as tr,bG as tt,t8 as u,O6 as ua,mG as ui,XG as un,Ws as uo,o2 as ur,$1 as ut,f8 as v,v4 as va,D3 as vi,n0 as vn,j as vo,C2 as vr,c0 as vt,F1 as w,mq as wa,v3 as wi,f0 as wn,$s as wo,l2 as wr,UG as wt,S6 as x,h4 as xa,o4 as xi,o0 as xn,Pc as xo,b2 as xr,Q$ as xt,b8 as y,uK as ya,t3 as yi,eJ as yn,P as yo,w2 as yr,l0 as yt,T4 as z,Kc as za,Wq as zi,E0 as zn,zt as zo,R0 as zr,y1 as zt};
|
|
453
|
-
//# sourceMappingURL=server-lock-iLcBw_q0-
|
|
453
|
+
//# sourceMappingURL=server-lock-iLcBw_q0-CdrK5Xfo.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{s as e}from"./chunk-C94x7I9S.mjs";import{c as t,l as n,s as r,u as i}from"./server-lock-iLcBw_q0-
|
|
1
|
+
import{s as e}from"./chunk-C94x7I9S.mjs";import{c as t,l as n,s as r,u as i}from"./server-lock-iLcBw_q0-CdrK5Xfo.mjs";import{Mr as a,Nr as o,Tn as s,ii as c,pn as l,xn as u}from"./dist-CdVqgoPq.mjs";import{t as d}from"./esm-CsQUg9js.mjs";import"./gh-detect-KLjG6xCR.mjs";import{S as f,b as p}from"./init-DdgQk34k.mjs";import{l as m,n as ee}from"./write-project-skill-BEzL3S1a.mjs";import"./loader-XWkMJYxk.mjs";import{c as te}from"./colors-8SzMRIVy.mjs";import"./preview-BLauTAym.mjs";import{dirname as ne,isAbsolute as h,join as g,relative as _,resolve as v}from"node:path";import{hostname as re}from"node:os";import{existsSync as y,lstatSync as ie,readFileSync as b,readlinkSync as x,statSync as S}from"node:fs";import{readFile as C,realpath as w}from"node:fs/promises";function T(e,a,o={}){let s=i(e,a);if(!y(s))return{status:`missing`,lockPath:s};let c;try{c=JSON.parse(b(s,`utf-8`))}catch{return{status:`corrupt`,lockPath:s}}if(!c||typeof c!=`object`||!n(c.pid))return{status:`corrupt`,lockPath:s};let l=c;if(!(o.isAlive??t)(l.pid))return{status:`dead-pid`,lockPath:s,lock:l};if(typeof l.machineId==`string`)return l.machineId===(o.machineId??r())?{status:`alive`,lockPath:s,lock:l}:{status:`foreign-host`,lockPath:s,lock:l};let u=o.host??re();return l.hostname===u?{status:`alive`,lockPath:s,lock:l}:{status:`foreign-host`,lockPath:s,lock:l}}function E(e){return e.replace(/:\d+$/,``)}function D(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:E(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:E(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:E(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.-]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}function O(e){let t;try{t=new URL(e)}catch{return null}if(t.hostname!==`github.com`&&t.hostname!==`www.github.com`)return null;let n=t.pathname.split(`/`).filter(e=>e.length>0);if(n.length<5||n[2]!==`blob`)return null;let r,i,a,o;try{r=decodeURIComponent(n[0]),i=decodeURIComponent(n[1]),a=decodeURIComponent(n[3]),o=n.slice(4).map(e=>decodeURIComponent(e))}catch{return null}return!r||!i||!a||o.length===0||o.some(e=>e.length===0)?null:{owner:r,repo:i,branch:a,path:o.join(`/`)}}function k(e){let t;try{t=new URL(e)}catch{return null}if(t.hostname!==`github.com`&&t.hostname!==`www.github.com`)return null;let n=t.pathname.split(`/`);if(n.length<5||n[0]!==``||n[3]!==`tree`)return null;let r=n.slice(5);r.length===1&&r[0]===``&&r.pop();let i,a,o,s;try{i=decodeURIComponent(n[1]),a=decodeURIComponent(n[2]),o=decodeURIComponent(n[4]),s=r.map(e=>decodeURIComponent(e))}catch{return null}return!i||!a||!o||s.some(e=>e.length===0)?null:{owner:i,repo:a,branch:o,path:s.join(`/`)}}function ae(e){let t=O(e);if(t)return{kind:`doc`,...t};let n=k(e);return n?{kind:`folder`,...n}:null}const oe=`# >>> open-knowledge cli >>>`,se=`# <<< open-knowledge cli <<<`,A=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function j(e){return g(e,`Library`,`Application Support`,`OpenKnowledge`,`path-install.json`)}const M={existsSync:e=>y(e),readFileSync:(e,t)=>b(e,t),lstatSync:e=>ie(e),readlinkSync:e=>x(e)};function N(e,t=M){let n=j(e);if(!t.existsSync(n))return null;try{let e=JSON.parse(t.readFileSync(n,`utf8`));return e?.version===1?e:null}catch{return null}}function P(e){let t=e.replace(A,``);return{text:t,changed:t!==e,emptyAfter:t.trim()===``}}function F(e,t,n=M){try{return n.lstatSync(e).isSymbolicLink()?n.readlinkSync(e)===t:!1}catch{return!1}}const I=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`,`deinit`]);function L(e,t,n=s){if(e!==void 0&&!I.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let R=null;function z(e){R=e}function B(){return R??process.cwd()}var V=e(te(),1);function H(e){return e==null?!1:e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function U(e,t=Date.now()){let n=new Date(e).getTime();if(Number.isNaN(n))return`—`;let r=t-n,i=Math.floor(r/1e3);if(i<60)return`${i}s`;let a=Math.floor(i/60);if(a<60)return`${a}m ago`;let o=Math.floor(a/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function W(e,t,n,r,i,a){if(t.status===`missing`||t.status===`corrupt`)return null;let o=t.lock,s=null;if(n.status!==`missing`&&n.status!==`corrupt`){let e=n.lock;s={port:e.port,status:n.status,pid:e.pid,startedAt:e.startedAt,usage:a}}return{directory:o.worktreeRoot,server:{port:o.port,status:t.status,pid:o.pid,startedAt:o.startedAt,usage:i},ui:s,hostname:o.hostname,lockPath:t.lockPath,binary:r==null?null:u(r),command:r,isDesktop:H(r)}}function G(e){return e.ui==null?!1:e.ui.status===`alive`||e.ui.status===`foreign-host`}function K(e){let t=e.server.status;return t===`alive`||t===`foreign-host`?e.isDesktop?`desktop`:t===`alive`?`running`:`foreign`:t===`dead-pid`&&G(e)?`ui-orphan`:`stale`}const ce=new Set([`running`,`desktop`,`foreign`,`ui-orphan`]);function le(e){switch(e){case`running`:return V.default.green(e);case`desktop`:return V.default.blue(e);case`foreign`:return V.default.cyan(e);case`ui-orphan`:return V.default.magenta(e);case`stale`:return V.default.yellow(e)}}function q(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function ue(e){return`${q(e.server.usage)} | ${q(e.ui?.usage??null)}`}function de(e){return`${e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null||e.ui.status===`dead-pid`?`—`:String(e.ui.port)}`}function fe(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>{let t=K(e),n=t===`ui-orphan`&&e.ui!=null?e.ui.pid:e.server.pid;return[e.directory,de(e),ue(e),t,String(n),U(e.server.startedAt),e.binary??`—`]}),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=le(K(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=V.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
|
|
2
2
|
`)}async function J(e={}){let t=e.discover??l,n=e.inspect??T,r=e.log??(e=>console.log(e)),i=e.resolveCommand??a,s=e.resolveUsage??o,c=await t(),u=[];for(let e of c){let t=n(e,`server`),r=n(e,`ui`),a=W(e,t,r,t.status===`missing`||t.status===`corrupt`?null:i(t.lock.pid),t.status===`missing`||t.status===`corrupt`?null:s(t.lock.pid),r.status===`missing`||r.status===`corrupt`?null:s(r.lock.pid));a!=null&&u.push(a)}if(e.json){let e=u.map(e=>({...e,displayStatus:K(e)}));r(JSON.stringify(e,null,2));return}r(fe(e.all?u:u.filter(e=>ce.has(K(e)))))}function pe(){return new d(`ps`).description(`List all running open-knowledge servers`).argument(`[modifier]`,`"all" to include stale (dead-pid) entries`).option(`--all`,`Include stale (dead-pid) entries (foreign-host shows by default)`).option(`--json`,`Emit structured JSON (always includes all statuses)`).action(async(e,t)=>{await J({all:t.all===!0||e===`all`,json:t.json===!0})})}function me(e,n,r={}){let i=r.isAlive??t,a=[];for(let[t,r]of[[`server`,e],[`ui`,n]])(r.status===`alive`||r.status===`foreign-host`&&i(r.lock.pid))&&a.push({name:t,pid:r.lock.pid,port:r.lock.port});return{targets:a}}function Y(e){let t=e.inspect??(t=>T(e.lockDir,t)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=me(t(`server`),t(`ui`),{isAlive:e.isAlive});if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function X(e,t){return e.status===`alive`?!0:e.status===`foreign-host`?t(e.lock.pid):!1}async function he(e,n=t){let r=await l(),i=null;for(let t of r){let r=T(t,`server`),a=T(t,`ui`);if(X(r,n)&&r.lock.port===e||X(a,n)&&a.lock.port===e)return t;i===null&&(X(r,n)&&r.lock.pid===e||X(a,n)&&a.lock.pid===e)&&(i=t)}return i}function Z(e){let t=Y({lockDir:e});return t.failed.length>0&&(process.exitCode=1),t}function ge(e){return new d(`stop`).description(`Stop open-knowledge server(s). With no argument: stops the server for the current directory. Pass a port number, a directory path, or "all" to target globally.`).argument(`[target...]`,`port number, directory path (spaces OK), or "all"`).action(async n=>{let r=n.length===0?void 0:n.join(` `);if(r===void 0){e();let t=Y({lockDir:c(process.cwd()),log:()=>{}});if(t.hadTargets){if(t.stopped.length>0){let e=t.stopped.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `);console.log(`Stopped: ${e}`)}t.failed.length>0&&(process.exitCode=1)}else await J({});return}if(r===`all`){let e=await l();if(e.length===0){console.log(`No running open-knowledge servers found.`);return}let n=0;for(let r of e){let e=T(r,`server`),i=T(r,`ui`);!X(e,t)&&!X(i,t)||(Z(r),n++)}n===0&&console.log(`No running open-knowledge servers found.`);return}if(/^\d+$/.test(r)){let e=Number.parseInt(r,10),t=await he(e);if(t===null){console.log(`No running open-knowledge server found with port or PID ${e}.`);return}Z(t);return}Z(c(v(B(),r)))})}function _e(e){return{event:`mcp-config-decline`,scope:e.scope,surface:e.surface,editorId:e.editorId,reason:e.reason}}async function Q(e,t){let n,r;try{n=await w(v(e)),r=await w(v(ne(e)))}catch{return{kind:`not-git`}}if(!$(n,r))return{kind:`symlink-escape`};let i=g(n,`.git`),a;try{a=S(i)}catch{return{kind:`not-git`}}let o;if(a.isDirectory()){let e;try{e=await w(i)}catch{return{kind:`not-git`}}if(!$(e,n))return{kind:`symlink-escape`};o=e}else if(a.isFile()){let e;try{e=await C(i,`utf-8`)}catch{return{kind:`not-git`}}let t=/^gitdir:\s*(.+)$/m.exec(e.trim());if(!t)return{kind:`not-git`};let r=t[1].trim(),a=h(r)?r:v(n,r);try{o=await w(a)}catch{return{kind:`not-git`}}}else return{kind:`not-git`};let s=g(await ve(o),`config`),c;try{c=await C(s,`utf-8`)}catch{return{kind:`not-git`}}let l=be(c);if(l===null)return{kind:`no-origin`};let u=D(l);if(u===null||u.hostname!==`github.com`)return{kind:`non-github`};let d=u.owner.toLowerCase()===t.owner.toLowerCase(),f=u.name.toLowerCase()===t.repo.toLowerCase();return!d||!f?{kind:`wrong-repo`,actualOwner:u.owner,actualRepo:u.name}:{kind:`ok`,gitRemoteUrl:`https://github.com/${u.owner}/${u.name}.git`}}async function ve(e){let t;try{t=(await C(g(e,`commondir`),`utf-8`)).trim()}catch{return e}if(t.length===0)return e;let n=h(t)?t:v(e,t);try{return await w(n)}catch{return n}}function $(e,t){if(e===t)return!0;let n=_(t,e);return n.length>0&&!n.startsWith(`..`)&&!h(n)}function ye(e){let t=e.indexOf(`#`),n=e.indexOf(`;`),r=-1;return t>=0&&n>=0?r=Math.min(t,n):t>=0?r=t:n>=0&&(r=n),(r===-1?e:e.slice(0,r)).trim()}function be(e){let t=!1;for(let n of e.split(/\r?\n/)){let e=ye(n);if(e.length===0)continue;if(e.startsWith(`[`)){t=/^\[\s*remote\s+["']origin["']\s*\]$/.test(e);continue}if(!t)continue;let r=/^url\s*=\s*(.+)$/.exec(e);if(r)return xe(r[1])}return null}function xe(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}const Se=[{id:`mcp-config`,write(e,t,n){let r=e.projectConfigPath?.(t);if(!r)return{integration:`mcp-config`,editorId:e.id,action:`skipped-unsupported`};try{let i=f(e,t,n,void 0,r);return i.action===`written`||i.action===`overwritten`?{integration:`mcp-config`,editorId:e.id,action:i.action,path:i.configPath}:i.action===`failed`?{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:i.error??`unknown failure`}:i.action===`declined`?{integration:`mcp-config`,editorId:e.id,action:`declined`,path:i.configPath,...i.declineReason===void 0?{}:{reason:i.declineReason}}:{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:`unexpected project-scope action: ${i.action}`}}catch(t){return{integration:`mcp-config`,editorId:e.id,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}},{id:`project-skill`,write(e,t,n){try{let n=ee(e,t);return{integration:`project-skill`,editorId:e.id,action:n.action,...n.path?{path:n.path}:{},...n.error?{error:n.error}:{}}}catch(t){return{integration:`project-skill`,editorId:e.id,action:`failed`,error:t instanceof Error?t.message:String(t)}}}}];function Ce(e,t,n={},r=Se){let i=[];for(let a of t){let t=m[a];for(let a of r)i.push(a.write(t,e,n))}return i}function we(e,t,n={}){return{integrations:Ce(e,t,n),claudeLaunchJson:t.includes(`claude`)?p(e,n):void 0}}export{ae as _,ge as a,T as b,L as c,se as d,F as f,O as g,P as h,Y as i,oe as l,N as m,Q as n,pe as o,j as p,_e as r,z as s,we as t,A as u,k as v,D as y};
|
|
3
|
-
//# sourceMappingURL=src-
|
|
3
|
+
//# sourceMappingURL=src-D0hiW4nw.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Mn as e,ht as t}from"./server-lock-iLcBw_q0-BF_u0tGL.mjs";import{cr as n,jr as r,xr as i}from"./dist-CUbAo1yS.mjs";import{n as a,t as o}from"./esm-CsQUg9js.mjs";import{i as s,t as c}from"./gh-detect-BUJyWvGO.mjs";import{n as l}from"./constants-BfJcirqe.mjs";import{spawn as u}from"node:child_process";import{basename as d,dirname as f,join as p}from"node:path";import{homedir as m}from"node:os";import{closeSync as h,existsSync as g,mkdirSync as _,openSync as v,statSync as y}from"node:fs";import{rm as b}from"node:fs/promises";import{setTimeout as x}from"node:timers/promises";const S=`OpenKnowledge.app`,C=`/Applications/${S}`;function w(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return y(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function T(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(t?.[1])return t[1]}if(E(e,C))return C;let t=p(e.homeDir??m(),`Applications`,S);return E(e,t)?t:null}function E(e,t){try{let n=p(t,`Contents`,`MacOS`,`OpenKnowledge`),r=e.statSync(n);return r&&typeof r.isFile==`function`?r.isFile():!1}catch{return!1}}function D(e){if(e.env.OK_FORCE_BROWSER===`1`)return{available:!1,reason:`force-browser`};if(e.platform!==`darwin`)return{available:!1,reason:`darwin-only`};let t;try{t=T(e)}catch{return{available:!1,reason:`stat-error`}}return t?e.env.OK_FORCE_DESKTOP===`1`?{available:!0,reason:`available`,bundlePath:t}:e.isTTY!==!0||e.env.SSH_CONNECTION||e.env.SSH_TTY?{available:!1,reason:`headless`,bundlePath:t}:{available:!0,reason:`available`,bundlePath:t}:{available:!1,reason:`no-bundle`}}function O(e){(e.log??(e=>console.error(e)))("Launching OpenKnowledge desktop (use `ok start` for the browser server, or `OK_FORCE_BROWSER=1` to always skip)");let t={...process.env};delete t.ELECTRON_RUN_AS_NODE,e.spawn(`open`,[`-b`,`com.inkeep.open-knowledge`],{detached:!0,stdio:`ignore`,env:t}).unref()}function k(e=`no-bundle`){switch(e){case`no-bundle`:return`Desktop app not found at ${C}. Install via DMG, or omit --mode for browser mode.`;case`darwin-only`:return`Desktop app is macOS-only on this release. Use --mode=browser, or omit --mode for the server fallback.`;case`headless`:return`Desktop launch is gated in headless contexts (CI, SSH, non-TTY stdout). Set OK_FORCE_DESKTOP=1 to override, or use --mode=browser.`;case`force-browser`:return`OK_FORCE_BROWSER=1 is set — desktop dispatch is disabled. Unset it to use --mode=app.`;case`stat-error`:return`Failed to inspect desktop bundle at ${C} (filesystem error). Check permissions or use --mode=browser.`;case`available`:return`Desktop app appears available at ${C} but launch dispatch did not fire (caller bug).`}}function A(e){return p(f(e),`..`,`Frameworks`,`OpenKnowledge Server.app`,`Contents`,`MacOS`,`OpenKnowledge Helper`)}const j=/\/[^/]+\.app\/Contents\/MacOS\/[^/]+$/;function M(e){if(e.platform!==`darwin`||!j.test(e.execPath))return null;let t=A(e.execPath);return e.exists(t)?t:null}function N(e={}){let t=e.execPath??process.execPath,n=e.platform??process.platform,r=e.argv??process.argv,i=e.exists??g,a=r[1];return a?{command:M({execPath:t,platform:n,exists:i})??t,prefixArgs:[a]}:(console.warn(`[self-spawn] process.argv[1] is empty — falling back to \`npx -y @inkeep/open-knowledge@latest\`. This re-introduces the registry-fetch surface that re-exec was fixing. Observed argv: ${JSON.stringify(r)}`),{command:`npx`,prefixArgs:[`-y`,`@inkeep/open-knowledge@latest`]})}function P(e,t){return e.host??t.HOST??`127.0.0.1`}function F(e){let t=d(e).replace(/[^\x20-\x7E]/g,``).trim().slice(0,64);return`open-knowledge-server ${t.length>0?t:`unknown`}`}var I=class extends Error{cwd;constructor(e){super("This directory isn't set up yet. Run `ok init` first, then `ok start` again."),this.name=`OkDirMissingError`,this.cwd=e}};function L(e){return e.uiLock?e.isAlive(e.uiLock.pid)?{action:`skip`,reason:`alive`,pid:e.uiLock.pid,port:e.uiLock.port}:{action:`spawn`,reason:`stale`,stalePid:e.uiLock.pid}:{action:`spawn`,reason:`absent`}}function R(t){g(t.lockDir)||_(t.lockDir,{recursive:!0});let n=v(p(t.lockDir,e),`w`),r=t.spawn??u,{PORT:i,...a}=process.env,o=N();try{let e=r(o.command,[...o.prefixArgs,...t.args??[`ui`]],{detached:!0,stdio:[`ignore`,`ignore`,n],cwd:t.cwd,env:{...a,ELECTRON_RUN_AS_NODE:`1`}});return e.unref(),e}finally{try{h(n)}catch{}}}function z(e,t,n){return e??(n===void 0?t:void 0)}function B(e,t){return e!==void 0&&t!==null&&t.port>0&&t.draining!==!0}function V(e,t,n){return e??(t!=null&&!n?1:0)}async function H(e){let t=e.spawn??u,n=N(),{PORT:r,...i}=process.env,a=t(n.command,[...n.prefixArgs,`ui`,`--port`,String(e.uiPort)],{cwd:e.cwd,stdio:`inherit`,env:{...i,ELECTRON_RUN_AS_NODE:`1`}}),o=!1,s=e=>{o=!0;try{a.kill(e)}catch{}},c=()=>s(`SIGINT`),l=()=>s(`SIGTERM`);process.once(`SIGINT`,c),process.once(`SIGTERM`,l),await new Promise(e=>{a.on(`exit`,(t,n)=>{process.exitCode=V(t,n,o),e()}),a.on(`error`,t=>{console.error(`[start] connect fallback: failed to spawn ok ui — ${t instanceof Error?t.message:String(t)}`),process.exitCode=1,e()})}),process.removeListener(`SIGINT`,c),process.removeListener(`SIGTERM`,l)}async function U(e){let t=e.now()+e.timeoutMs;for(;e.now()<t;){let t=e.readUiLock();if(t&&t.port>0)return t.port;await e.sleep(e.pollIntervalMs)}let n=e.readUiLock();return n&&n.port>0?n.port:null}const W=t;function G(e,t,n=e=>b(e,{recursive:!0,force:!0})){return async()=>{try{await e()}finally{try{await n(t)}catch(e){process.stderr.write(`[start] ephemeral temp dir reap failed for ${t}: ${e instanceof Error?e.message:String(e)}\n`)}}}}function K(e,t={}){let n=t.exit??(e=>process.exit(e)),r=t.getActiveHandles??(()=>{let e=process._getActiveHandles;return e?e.call(process):null});return async()=>{let i=!1;try{await e()}catch(e){i=!0,t.log?.error({err:e},`idle-shutdown: destroy failed — exiting anyway`)}finally{let e=null;try{let t=r();if(t!==null){e={};for(let n of t){let t=n?.constructor?.name??`unknown`;e[t]=(e[t]??0)+1}}}catch{e=null}t.log?.info({event:`idle-shutdown-exit`,exitCode:i?1:0,openHandles:e??{},handlesAvailable:e!==null},`idle-shutdown: teardown finished — exiting process`),n(i?1:0)}}}function q(e){let t=e.sigtermGraceMs??W,n=e.sigtermPollIntervalMs??200,r=e.sleep??(e=>x(e));return async()=>{try{let i=e.readUiLock();if(i&&e.isAlive(i.pid))try{e.killPid(i.pid,`SIGTERM`),e.log?.info({pid:i.pid,port:i.port},`idle-shutdown: SIGTERM UI sibling`);let a=Date.now()+t;for(;Date.now()<a&&e.isAlive(i.pid);)await r(n);if(e.isAlive(i.pid))try{e.killPid(i.pid,`SIGKILL`),e.log?.warn({pid:i.pid,graceMs:t},`idle-shutdown: SIGTERM grace expired — escalated to SIGKILL`)}catch(t){e.log?.error({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: SIGKILL failed`)}}catch(t){e.log?.warn({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: failed to SIGTERM UI sibling`)}}catch(t){e.log?.warn({err:t instanceof Error?t.message:String(t)},`idle-shutdown: UI lookup failed; proceeding with destroy`)}await e.destroy()}}async function J(e){let{config:t,cwd:a,host:o}=e,l=e.skipAutoInit??!1,u=e.skipUiAutoSpawn??!1,d=e.idleThresholdMs??18e5,{existsSync:f,mkdirSync:p}=await import(`node:fs`),{basename:m,dirname:h}=await import(`node:path`),{bootServer:g,getLogger:_,isProcessAlive:v,readUiLock:y,resolveContentDir:b,resolveLockDir:S,waitForServerLockDrain:C}=await import(`./dist-D8lHZNr8.mjs`),w=e.log??_(`start`),T=e.singleFile!==void 0,E=e.projectDir??a,D=T?r(e.singleFile).canonicalFilePath:void 0,O=D?h(D):void 0,k=D?m(D):void 0;if(!T){if(!l&&!n(a))throw new I(a);let t=process.env.OK_RECLAIM_DISABLE??null,r=e=>{let t=typeof e.event==`string`?e.event:``;(t.endsWith(`-failed`)||t.endsWith(`-error`)||t.endsWith(`-missing`))&&w.warn({event:e},`[start] reclaim sweep reported a problem`)};try{(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-BYRhVChI.mjs`)).repairMcpConfigs)({projectDir:a,reclaimDisableEnv:t,logger:r})}catch(e){w.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json-CWUTx3IW.mjs`)).repairLaunchJson)({projectDir:a,reclaimDisableEnv:t,logger:r})}catch(e){w.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}try{await(e.repairSkillsFn??(await import(`./repair-skills-B8ePNziA.mjs`)).repairSkills)({projectDir:a,reclaimDisableEnv:t,logger:r})}catch(e){w.warn({err:e},`[start] skill repair sweep failed; continuing`)}}let A=O??b(t,a);!T&&!f(A)&&(p(A,{recursive:!0}),w.info({contentDir:A},`Created content directory`));let j=null,M=async({lockDir:t})=>{if(j=L({uiLock:y(t),isAlive:v}),j.action===`spawn`&&!u)try{let n=e.uiPort===void 0?void 0:[`ui`,`--port`,String(e.uiPort)];R({lockDir:t,cwd:a,spawn:e.spawn,args:n}),w.info({reason:j.reason,uiPort:e.uiPort},`[start] auto-spawned ok ui sibling`)}catch(e){console.warn(`[start] failed to auto-spawn ok ui: ${e instanceof Error?e.message:String(e)}`)}else j.action===`skip`&&w.info({port:j.port,pid:j.pid},`UI already running at port ${j.port}`)},N=e.reactShellDistDir===void 0,P=s(),F=i();{let e=S(T?E:a),t=Date.now(),n=await C(e);n!==`no-drain`&&w.info({event:`start-waited-for-draining-predecessor`,outcome:n,waitedMs:Date.now()-t,drainLockDir:e},n===`released`?`[start] predecessor server finished draining — proceeding`:`[start] predecessor server still draining after wait — proceeding to collide`)}let z=await g({config:t,contentDir:A,projectDir:T?E:a,contentRoot:T?void 0:t.content.dir,port:e.port,host:o,quiet:!1,detectGh:c,tokenStore:P,embeddingsKeyStore:F,...T?{ephemeral:!0,singleDocRelPath:k,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],attachUiSibling:N,idleShutdownMs:d,skipAutoInit:!0,...N?{spawnUiSiblingFn:M}:{},idleShutdownHandler:t=>{let n=q({readUiLock:()=>y(z.lockDir),isAlive:v,killPid:(e,t)=>{process.kill(e,t)},destroy:t,log:w});return K(T?G(n,E):n,{log:w,exit:e.idleExit})},log:w,...e.serveContentAssets?{serveContentAssets:!0}:{},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{}});j||={action:`skip`,reason:`alive`,pid:0,port:0};let B=j,V=null;if(B.action===`skip`)V=B.port>0?B.port:null;else if(!u){let t=e.uiBindTimeoutMs??3e3;V=await U({readUiLock:()=>y(z.lockDir),now:Date.now,sleep:e=>x(e),timeoutMs:t,pollIntervalMs:50}),V===null&&w.warn({timeoutMs:t},`[start] ok ui did not bind within timeout — banner falls back to API URL`)}return{httpServer:z.httpServer,destroy:z.destroy,lockDir:z.lockDir,contentDir:A,port:z.port,ready:z.ready,degraded:z.degraded,uiSpawnDecision:j,resolvedUiPort:V}}function ee(e){if(e===`browser`||e===`app`)return e;throw new a(`--mode must be 'browser' or 'app'`)}function te(e){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<1||t>65535)throw new a(`--ui-port must be a port number between 1 and 65535`);return t}function Y(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function X(e){let t=[`Stopping OpenKnowledge…`,`Saving pending changes and releasing the server lock — this can take a few seconds.`];return e===`SIGINT`&&t.push(`Press Ctrl+C again to force quit.`),t}async function Z(e,t){let n=Y(process.env);n!==null&&(process.env.OK_CONSOLE_LEVEL=n);let{renderBanner:r}=await import(`./banner-BxCFCyu8.mjs`),{accent:i,dim:a,error:o,warning:s}=await import(`./colors-CmkIIbww.mjs`),c=process.cwd(),u=e;process.title=F(c);let d=P(t,process.env),f=t.port===void 0?void 0:Number(t.port),p=process.env.PORT?Number(process.env.PORT):void 0,m=t.uiPort===void 0?void 0:Number(t.uiPort),h=z(f,p,m);if(m!==void 0){let{readServerLock:e,resolveLockDir:t}=await import(`./dist-D8lHZNr8.mjs`);if(B(m,e(t(c)))){await H({cwd:c,uiPort:m});return}}let g;try{g=await J({config:u,cwd:c,host:d,port:h,...m===void 0?{}:{uiPort:m},...t.serveContentAssets?{serveContentAssets:!0}:{},...t.reactShellDistDir?{reactShellDistDir:t.reactShellDistDir}:{},...t.singleFile?{singleFile:t.singleFile}:{},...t.projectDir?{projectDir:t.projectDir}:{}})}catch(e){e instanceof I&&(console.error(o(e.message)),process.exit(1));let t=await import(`./dist-D8lHZNr8.mjs`);if((e instanceof t.GitNotAvailableError||e instanceof t.GitTooOldError)&&process.exit(78),(e instanceof t.SingleFileNotFoundError||e instanceof t.SingleFileNotAFileError||e instanceof t.SingleFileNotMarkdownError)&&(console.error(o(e.message)),process.exit(1)),m!==void 0&&Q(e,t)){await H({cwd:c,uiPort:m});return}let n=$(e,c,t);n!==null&&(console.error(o(n)),process.exit(1)),console.error(`${o(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let _=!1,v=async e=>{if(_)return;_=!0;let[t,...n]=X(e);console.log(i(`\n${t}`));for(let e of n)console.log(a(` ${e}`));try{await g.destroy()}catch(e){console.error(`${o(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)};process.once(`SIGINT`,()=>{v(`SIGINT`)}),process.once(`SIGTERM`,()=>{v(`SIGTERM`)});let y=`http://${d}:${g.port}`,b=d===`0.0.0.0`||d===`::`?`http://0.0.0.0:${g.port}`:void 0,x=g.resolvedUiPort,S=x!==null&&x>0?`http://${d}:${x}`:y;console.log(r({name:`open-knowledge`,version:l,localUrl:S,apiUrl:S===y?void 0:y,networkUrl:b,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let C={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};g.ready.then(async()=>{if(g.degraded.length>0){console.log();for(let e of g.degraded){let t=C[e]??`${e} (check server logs for details)`;console.warn(` ${s(`⚠`)} ${s(e)}: ${a(t)}`)}console.log()}if(t.open){let{openBrowser:e}=await import(`./open-browser-DHTbHSqx.mjs`);e(S)}}).catch(e=>{console.error(` ${o(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}function Q(e,t){let n=t.ServerLockCollisionError;return n!==void 0&&e instanceof n}function $(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=p(t,`.ok`),r=n.readServerLock(e);return r?r.kind===`interactive`?`OpenKnowledge desktop is currently running on this project. Quit it or use --cwd to point elsewhere.`:r.kind===`mcp-spawned`?"An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`."}catch{return null}}function ne(e){return new o(`start`).description(`Start the knowledge base collab server`).option(`-p, --port <port>`,`Server port`,void 0).option(`--ui-port <port>`,`Pin the ok ui sibling to <port> and connect (not exit) if a server already runs here — the worktree-preview recipe path`,te).option(`-H, --host <host>`,`Server host`,void 0).option(`--open`,`Open browser after start`).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,ee).option(`--serve-content-assets`,`Serve content assets from this server`).option(`--react-shell-dist-dir <path>`,`Serve React shell from <path> (suppresses ok ui sibling)`).option(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).option(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).action(async t=>{let n=e();if(t.mode===`app`){t.open&&(process.stderr.write(`error: option '--mode=app' cannot be combined with '--open' (--open opens a browser tab against the local server, which app mode does not boot)
|
|
1
|
+
import{Mn as e,ht as t}from"./server-lock-iLcBw_q0-CdrK5Xfo.mjs";import{cr as n,jr as r,xr as i}from"./dist-CdVqgoPq.mjs";import{n as a,t as o}from"./esm-CsQUg9js.mjs";import{i as s,t as c}from"./gh-detect-KLjG6xCR.mjs";import{n as l}from"./constants-FPRBLLHv.mjs";import{spawn as u}from"node:child_process";import{basename as d,dirname as f,join as p}from"node:path";import{homedir as m}from"node:os";import{closeSync as h,existsSync as g,mkdirSync as _,openSync as v,statSync as y}from"node:fs";import{rm as b}from"node:fs/promises";import{setTimeout as x}from"node:timers/promises";const S=`OpenKnowledge.app`,C=`/Applications/${S}`;function w(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return y(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function T(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(t?.[1])return t[1]}if(E(e,C))return C;let t=p(e.homeDir??m(),`Applications`,S);return E(e,t)?t:null}function E(e,t){try{let n=p(t,`Contents`,`MacOS`,`OpenKnowledge`),r=e.statSync(n);return r&&typeof r.isFile==`function`?r.isFile():!1}catch{return!1}}function D(e){if(e.env.OK_FORCE_BROWSER===`1`)return{available:!1,reason:`force-browser`};if(e.platform!==`darwin`)return{available:!1,reason:`darwin-only`};let t;try{t=T(e)}catch{return{available:!1,reason:`stat-error`}}return t?e.env.OK_FORCE_DESKTOP===`1`?{available:!0,reason:`available`,bundlePath:t}:e.isTTY!==!0||e.env.SSH_CONNECTION||e.env.SSH_TTY?{available:!1,reason:`headless`,bundlePath:t}:{available:!0,reason:`available`,bundlePath:t}:{available:!1,reason:`no-bundle`}}function O(e){(e.log??(e=>console.error(e)))("Launching OpenKnowledge desktop (use `ok start` for the browser server, or `OK_FORCE_BROWSER=1` to always skip)");let t={...process.env};delete t.ELECTRON_RUN_AS_NODE,e.spawn(`open`,[`-b`,`com.inkeep.open-knowledge`],{detached:!0,stdio:`ignore`,env:t}).unref()}function k(e=`no-bundle`){switch(e){case`no-bundle`:return`Desktop app not found at ${C}. Install via DMG, or omit --mode for browser mode.`;case`darwin-only`:return`Desktop app is macOS-only on this release. Use --mode=browser, or omit --mode for the server fallback.`;case`headless`:return`Desktop launch is gated in headless contexts (CI, SSH, non-TTY stdout). Set OK_FORCE_DESKTOP=1 to override, or use --mode=browser.`;case`force-browser`:return`OK_FORCE_BROWSER=1 is set — desktop dispatch is disabled. Unset it to use --mode=app.`;case`stat-error`:return`Failed to inspect desktop bundle at ${C} (filesystem error). Check permissions or use --mode=browser.`;case`available`:return`Desktop app appears available at ${C} but launch dispatch did not fire (caller bug).`}}function A(e){return p(f(e),`..`,`Frameworks`,`OpenKnowledge Server.app`,`Contents`,`MacOS`,`OpenKnowledge Helper`)}const j=/\/[^/]+\.app\/Contents\/MacOS\/[^/]+$/;function M(e){if(e.platform!==`darwin`||!j.test(e.execPath))return null;let t=A(e.execPath);return e.exists(t)?t:null}function N(e={}){let t=e.execPath??process.execPath,n=e.platform??process.platform,r=e.argv??process.argv,i=e.exists??g,a=r[1];return a?{command:M({execPath:t,platform:n,exists:i})??t,prefixArgs:[a]}:(console.warn(`[self-spawn] process.argv[1] is empty — falling back to \`npx -y @inkeep/open-knowledge@latest\`. This re-introduces the registry-fetch surface that re-exec was fixing. Observed argv: ${JSON.stringify(r)}`),{command:`npx`,prefixArgs:[`-y`,`@inkeep/open-knowledge@latest`]})}function P(e,t){return e.host??t.HOST??`127.0.0.1`}function F(e){let t=d(e).replace(/[^\x20-\x7E]/g,``).trim().slice(0,64);return`open-knowledge-server ${t.length>0?t:`unknown`}`}var I=class extends Error{cwd;constructor(e){super("This directory isn't set up yet. Run `ok init` first, then `ok start` again."),this.name=`OkDirMissingError`,this.cwd=e}};function L(e){return e.uiLock?e.isAlive(e.uiLock.pid)?{action:`skip`,reason:`alive`,pid:e.uiLock.pid,port:e.uiLock.port}:{action:`spawn`,reason:`stale`,stalePid:e.uiLock.pid}:{action:`spawn`,reason:`absent`}}function R(t){g(t.lockDir)||_(t.lockDir,{recursive:!0});let n=v(p(t.lockDir,e),`w`),r=t.spawn??u,{PORT:i,...a}=process.env,o=N();try{let e=r(o.command,[...o.prefixArgs,...t.args??[`ui`]],{detached:!0,stdio:[`ignore`,`ignore`,n],cwd:t.cwd,env:{...a,ELECTRON_RUN_AS_NODE:`1`}});return e.unref(),e}finally{try{h(n)}catch{}}}function z(e,t,n){return e??(n===void 0?t:void 0)}function B(e,t){return e!==void 0&&t!==null&&t.port>0&&t.draining!==!0}function V(e,t,n){return e??(t!=null&&!n?1:0)}async function H(e){let t=e.spawn??u,n=N(),{PORT:r,...i}=process.env,a=t(n.command,[...n.prefixArgs,`ui`,`--port`,String(e.uiPort)],{cwd:e.cwd,stdio:`inherit`,env:{...i,ELECTRON_RUN_AS_NODE:`1`}}),o=!1,s=e=>{o=!0;try{a.kill(e)}catch{}},c=()=>s(`SIGINT`),l=()=>s(`SIGTERM`);process.once(`SIGINT`,c),process.once(`SIGTERM`,l),await new Promise(e=>{a.on(`exit`,(t,n)=>{process.exitCode=V(t,n,o),e()}),a.on(`error`,t=>{console.error(`[start] connect fallback: failed to spawn ok ui — ${t instanceof Error?t.message:String(t)}`),process.exitCode=1,e()})}),process.removeListener(`SIGINT`,c),process.removeListener(`SIGTERM`,l)}async function U(e){let t=e.now()+e.timeoutMs;for(;e.now()<t;){let t=e.readUiLock();if(t&&t.port>0)return t.port;await e.sleep(e.pollIntervalMs)}let n=e.readUiLock();return n&&n.port>0?n.port:null}const W=t;function G(e,t,n=e=>b(e,{recursive:!0,force:!0})){return async()=>{try{await e()}finally{try{await n(t)}catch(e){process.stderr.write(`[start] ephemeral temp dir reap failed for ${t}: ${e instanceof Error?e.message:String(e)}\n`)}}}}function K(e,t={}){let n=t.exit??(e=>process.exit(e)),r=t.getActiveHandles??(()=>{let e=process._getActiveHandles;return e?e.call(process):null});return async()=>{let i=!1;try{await e()}catch(e){i=!0,t.log?.error({err:e},`idle-shutdown: destroy failed — exiting anyway`)}finally{let e=null;try{let t=r();if(t!==null){e={};for(let n of t){let t=n?.constructor?.name??`unknown`;e[t]=(e[t]??0)+1}}}catch{e=null}t.log?.info({event:`idle-shutdown-exit`,exitCode:i?1:0,openHandles:e??{},handlesAvailable:e!==null},`idle-shutdown: teardown finished — exiting process`),n(i?1:0)}}}function q(e){let t=e.sigtermGraceMs??W,n=e.sigtermPollIntervalMs??200,r=e.sleep??(e=>x(e));return async()=>{try{let i=e.readUiLock();if(i&&e.isAlive(i.pid))try{e.killPid(i.pid,`SIGTERM`),e.log?.info({pid:i.pid,port:i.port},`idle-shutdown: SIGTERM UI sibling`);let a=Date.now()+t;for(;Date.now()<a&&e.isAlive(i.pid);)await r(n);if(e.isAlive(i.pid))try{e.killPid(i.pid,`SIGKILL`),e.log?.warn({pid:i.pid,graceMs:t},`idle-shutdown: SIGTERM grace expired — escalated to SIGKILL`)}catch(t){e.log?.error({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: SIGKILL failed`)}}catch(t){e.log?.warn({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: failed to SIGTERM UI sibling`)}}catch(t){e.log?.warn({err:t instanceof Error?t.message:String(t)},`idle-shutdown: UI lookup failed; proceeding with destroy`)}await e.destroy()}}async function J(e){let{config:t,cwd:a,host:o}=e,l=e.skipAutoInit??!1,u=e.skipUiAutoSpawn??!1,d=e.idleThresholdMs??18e5,{existsSync:f,mkdirSync:p}=await import(`node:fs`),{basename:m,dirname:h}=await import(`node:path`),{bootServer:g,getLogger:_,isProcessAlive:v,readUiLock:y,resolveContentDir:b,resolveLockDir:S,waitForServerLockDrain:C}=await import(`./dist-CZ4COUHS.mjs`),w=e.log??_(`start`),T=e.singleFile!==void 0,E=e.projectDir??a,D=T?r(e.singleFile).canonicalFilePath:void 0,O=D?h(D):void 0,k=D?m(D):void 0;if(!T){if(!l&&!n(a))throw new I(a);let t=process.env.OK_RECLAIM_DISABLE??null,r=e=>{let t=typeof e.event==`string`?e.event:``;(t.endsWith(`-failed`)||t.endsWith(`-error`)||t.endsWith(`-missing`))&&w.warn({event:e},`[start] reclaim sweep reported a problem`)};try{(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-D3XsTqKa.mjs`)).repairMcpConfigs)({projectDir:a,reclaimDisableEnv:t,logger:r})}catch(e){w.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json-Bk99TDG5.mjs`)).repairLaunchJson)({projectDir:a,reclaimDisableEnv:t,logger:r})}catch(e){w.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}try{await(e.repairSkillsFn??(await import(`./repair-skills-DCZqW9al.mjs`)).repairSkills)({projectDir:a,reclaimDisableEnv:t,logger:r})}catch(e){w.warn({err:e},`[start] skill repair sweep failed; continuing`)}}let A=O??b(t,a);!T&&!f(A)&&(p(A,{recursive:!0}),w.info({contentDir:A},`Created content directory`));let j=null,M=async({lockDir:t})=>{if(j=L({uiLock:y(t),isAlive:v}),j.action===`spawn`&&!u)try{let n=e.uiPort===void 0?void 0:[`ui`,`--port`,String(e.uiPort)];R({lockDir:t,cwd:a,spawn:e.spawn,args:n}),w.info({reason:j.reason,uiPort:e.uiPort},`[start] auto-spawned ok ui sibling`)}catch(e){console.warn(`[start] failed to auto-spawn ok ui: ${e instanceof Error?e.message:String(e)}`)}else j.action===`skip`&&w.info({port:j.port,pid:j.pid},`UI already running at port ${j.port}`)},N=e.reactShellDistDir===void 0,P=s(),F=i();{let e=S(T?E:a),t=Date.now(),n=await C(e);n!==`no-drain`&&w.info({event:`start-waited-for-draining-predecessor`,outcome:n,waitedMs:Date.now()-t,drainLockDir:e},n===`released`?`[start] predecessor server finished draining — proceeding`:`[start] predecessor server still draining after wait — proceeding to collide`)}let z=await g({config:t,contentDir:A,projectDir:T?E:a,contentRoot:T?void 0:t.content.dir,port:e.port,host:o,quiet:!1,detectGh:c,tokenStore:P,embeddingsKeyStore:F,...T?{ephemeral:!0,singleDocRelPath:k,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],attachUiSibling:N,idleShutdownMs:d,skipAutoInit:!0,...N?{spawnUiSiblingFn:M}:{},idleShutdownHandler:t=>{let n=q({readUiLock:()=>y(z.lockDir),isAlive:v,killPid:(e,t)=>{process.kill(e,t)},destroy:t,log:w});return K(T?G(n,E):n,{log:w,exit:e.idleExit})},log:w,...e.serveContentAssets?{serveContentAssets:!0}:{},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{}});j||={action:`skip`,reason:`alive`,pid:0,port:0};let B=j,V=null;if(B.action===`skip`)V=B.port>0?B.port:null;else if(!u){let t=e.uiBindTimeoutMs??3e3;V=await U({readUiLock:()=>y(z.lockDir),now:Date.now,sleep:e=>x(e),timeoutMs:t,pollIntervalMs:50}),V===null&&w.warn({timeoutMs:t},`[start] ok ui did not bind within timeout — banner falls back to API URL`)}return{httpServer:z.httpServer,destroy:z.destroy,lockDir:z.lockDir,contentDir:A,port:z.port,ready:z.ready,degraded:z.degraded,uiSpawnDecision:j,resolvedUiPort:V}}function ee(e){if(e===`browser`||e===`app`)return e;throw new a(`--mode must be 'browser' or 'app'`)}function te(e){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<1||t>65535)throw new a(`--ui-port must be a port number between 1 and 65535`);return t}function Y(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function X(e){let t=[`Stopping OpenKnowledge…`,`Saving pending changes and releasing the server lock — this can take a few seconds.`];return e===`SIGINT`&&t.push(`Press Ctrl+C again to force quit.`),t}async function Z(e,t){let n=Y(process.env);n!==null&&(process.env.OK_CONSOLE_LEVEL=n);let{renderBanner:r}=await import(`./banner-BxCFCyu8.mjs`),{accent:i,dim:a,error:o,warning:s}=await import(`./colors-CmkIIbww.mjs`),c=process.cwd(),u=e;process.title=F(c);let d=P(t,process.env),f=t.port===void 0?void 0:Number(t.port),p=process.env.PORT?Number(process.env.PORT):void 0,m=t.uiPort===void 0?void 0:Number(t.uiPort),h=z(f,p,m);if(m!==void 0){let{readServerLock:e,resolveLockDir:t}=await import(`./dist-CZ4COUHS.mjs`);if(B(m,e(t(c)))){await H({cwd:c,uiPort:m});return}}let g;try{g=await J({config:u,cwd:c,host:d,port:h,...m===void 0?{}:{uiPort:m},...t.serveContentAssets?{serveContentAssets:!0}:{},...t.reactShellDistDir?{reactShellDistDir:t.reactShellDistDir}:{},...t.singleFile?{singleFile:t.singleFile}:{},...t.projectDir?{projectDir:t.projectDir}:{}})}catch(e){e instanceof I&&(console.error(o(e.message)),process.exit(1));let t=await import(`./dist-CZ4COUHS.mjs`);if((e instanceof t.GitNotAvailableError||e instanceof t.GitTooOldError)&&process.exit(78),(e instanceof t.SingleFileNotFoundError||e instanceof t.SingleFileNotAFileError||e instanceof t.SingleFileNotMarkdownError)&&(console.error(o(e.message)),process.exit(1)),m!==void 0&&Q(e,t)){await H({cwd:c,uiPort:m});return}let n=$(e,c,t);n!==null&&(console.error(o(n)),process.exit(1)),console.error(`${o(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let _=!1,v=async e=>{if(_)return;_=!0;let[t,...n]=X(e);console.log(i(`\n${t}`));for(let e of n)console.log(a(` ${e}`));try{await g.destroy()}catch(e){console.error(`${o(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)};process.once(`SIGINT`,()=>{v(`SIGINT`)}),process.once(`SIGTERM`,()=>{v(`SIGTERM`)});let y=`http://${d}:${g.port}`,b=d===`0.0.0.0`||d===`::`?`http://0.0.0.0:${g.port}`:void 0,x=g.resolvedUiPort,S=x!==null&&x>0?`http://${d}:${x}`:y;console.log(r({name:`open-knowledge`,version:l,localUrl:S,apiUrl:S===y?void 0:y,networkUrl:b,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let C={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};g.ready.then(async()=>{if(g.degraded.length>0){console.log();for(let e of g.degraded){let t=C[e]??`${e} (check server logs for details)`;console.warn(` ${s(`⚠`)} ${s(e)}: ${a(t)}`)}console.log()}if(t.open){let{openBrowser:e}=await import(`./open-browser-DHTbHSqx.mjs`);e(S)}}).catch(e=>{console.error(` ${o(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}function Q(e,t){let n=t.ServerLockCollisionError;return n!==void 0&&e instanceof n}function $(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=p(t,`.ok`),r=n.readServerLock(e);return r?r.kind===`interactive`?`OpenKnowledge desktop is currently running on this project. Quit it or use --cwd to point elsewhere.`:r.kind===`mcp-spawned`?"An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`."}catch{return null}}function ne(e){return new o(`start`).description(`Start the knowledge base collab server`).option(`-p, --port <port>`,`Server port`,void 0).option(`--ui-port <port>`,`Pin the ok ui sibling to <port> and connect (not exit) if a server already runs here — the worktree-preview recipe path`,te).option(`-H, --host <host>`,`Server host`,void 0).option(`--open`,`Open browser after start`).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,ee).option(`--serve-content-assets`,`Serve content assets from this server`).option(`--react-shell-dist-dir <path>`,`Serve React shell from <path> (suppresses ok ui sibling)`).option(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).option(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).action(async t=>{let n=e();if(t.mode===`app`){t.open&&(process.stderr.write(`error: option '--mode=app' cannot be combined with '--open' (--open opens a browser tab against the local server, which app mode does not boot)
|
|
2
2
|
`),process.exit(2));let e=[];if(t.port!==void 0&&e.push(`--port`),t.uiPort!==void 0&&e.push(`--ui-port`),t.host!==void 0&&e.push(`--host`),e.length>0){let t=process.env.OK_LOG_LEVEL??`info`;(t===`debug`||t===`trace`)&&console.error(`--mode=app: ignoring ${e.join(`, `)}`)}let n=D(w());if(n.available){O({spawn:u});return}console.error(k(n.reason)),process.exit(1)}await Z(n,t)})}export{D as C,w as S,ne as _,V as a,K as b,F as c,z as d,P as f,R as g,B as h,q as i,X as l,Z as m,U as n,H as o,Y as p,J as r,L as s,I as t,Q as u,$ as v,O as w,N as x,G as y};
|
|
3
|
-
//# sourceMappingURL=start-
|
|
3
|
+
//# sourceMappingURL=start-B3yMZZZG.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{_ as e,f as t,r as n}from"./start-B3yMZZZG.mjs";export{n as bootStartServer,t as resolveHost,e as startCommand};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import{It as e,S as t,an as n,wt as r}from"./server-lock-iLcBw_q0-CdrK5Xfo.mjs";import{d as i,ei as a,ut as o}from"./dist-CdVqgoPq.mjs";import{basename as s,dirname as c,isAbsolute as l,join as u,posix as d,relative as ee,resolve as f,sep as p,win32 as m}from"node:path";import{homedir as h}from"node:os";import{cpSync as g,existsSync as _,lstatSync as v,mkdirSync as y,realpathSync as b,rmSync as x}from"node:fs";const S=t,C=r,w=e,T=`node`,E={MCP_DEBUG:`1`,OK_LOG_FILE:`/tmp/ok-mcp.log`},D=`# ok-mcp-v1`,O=`# ok-mcp-v1
|
|
2
|
+
USER_BUNDLE="$HOME/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh"
|
|
3
|
+
[ -f "$USER_BUNDLE" ] && [ -x "$USER_BUNDLE" ] && exec "$USER_BUNDLE" mcp
|
|
4
|
+
BUNDLE="/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh"
|
|
5
|
+
[ -f "$BUNDLE" ] && [ -x "$BUNDLE" ] && exec "$BUNDLE" mcp
|
|
6
|
+
command -v npx >/dev/null 2>&1 && exec npx -y @inkeep/open-knowledge@latest mcp
|
|
7
|
+
for d in "$HOME/.nvm/versions/node"/*/bin "$HOME/.fnm/node-versions"/*/installation/bin "$HOME/.asdf/installs/nodejs"/*/bin /opt/homebrew/bin /usr/local/bin "$HOME/.local/bin" "$HOME/.volta/bin"; do
|
|
8
|
+
[ -f "$d/npx" ] && [ -x "$d/npx" ] && exec "$d/npx" -y @inkeep/open-knowledge@latest mcp
|
|
9
|
+
done
|
|
10
|
+
echo "OpenKnowledge: install OK Desktop or Node.js 24+, then restart your editor" >&2
|
|
11
|
+
exit 127`,k=`# ok-mcp-win-v1`,A=`# ok-mcp-win-v1
|
|
12
|
+
if ($env:PATHEXT -notmatch 'CMD') { $env:PATHEXT = '.COM;.EXE;.BAT;.CMD;' + $env:PATHEXT }
|
|
13
|
+
if ($env:APPDATA) {
|
|
14
|
+
$shim = Join-Path $env:APPDATA 'npm\\ok.cmd'
|
|
15
|
+
if (Test-Path -LiteralPath $shim -PathType Leaf) { & $shim mcp; exit $LASTEXITCODE }
|
|
16
|
+
}
|
|
17
|
+
$ok = Get-Command ok.cmd -CommandType Application -ErrorAction SilentlyContinue
|
|
18
|
+
if ($ok) { & $ok.Source mcp; exit $LASTEXITCODE }
|
|
19
|
+
$npx = Get-Command npx.cmd -CommandType Application -ErrorAction SilentlyContinue
|
|
20
|
+
if ($npx) { & $npx.Source -y '@inkeep/open-knowledge@latest' mcp; exit $LASTEXITCODE }
|
|
21
|
+
$dirs = @()
|
|
22
|
+
if ($env:ProgramFiles) { $dirs += Join-Path $env:ProgramFiles 'nodejs' }
|
|
23
|
+
if ($env:NVM_SYMLINK) { $dirs += $env:NVM_SYMLINK }
|
|
24
|
+
if ($env:LOCALAPPDATA) {
|
|
25
|
+
$dirs += Join-Path $env:LOCALAPPDATA 'fnm\\aliases\\default'
|
|
26
|
+
$dirs += Join-Path $env:LOCALAPPDATA 'Volta\\bin'
|
|
27
|
+
$dirs += Join-Path $env:LOCALAPPDATA 'pnpm'
|
|
28
|
+
}
|
|
29
|
+
if ($env:USERPROFILE) { $dirs += Join-Path $env:USERPROFILE 'scoop\\shims' }
|
|
30
|
+
foreach ($d in $dirs) {
|
|
31
|
+
$probe = Join-Path $d 'npx.cmd'
|
|
32
|
+
if (Test-Path -LiteralPath $probe -PathType Leaf) { & $probe -y '@inkeep/open-knowledge@latest' mcp; exit $LASTEXITCODE }
|
|
33
|
+
}
|
|
34
|
+
[Console]::Error.WriteLine('OpenKnowledge: install Node.js 24+ (npm i -g @inkeep/open-knowledge), then restart your editor')
|
|
35
|
+
exit 127`,j=`// ok-pi-bridge`,M=`${j}-v1`,N=`ok-pi-managed-extension`;function P(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.command===`/bin/sh`){if(!Array.isArray(t.args)||t.args[0]!==`-l`||t.args[1]!==`-c`)return!1;let e=t.args[2];return typeof e==`string`&&e.includes(`# ok-mcp-v1`)}if(t.command===`powershell`){if(!Array.isArray(t.args)||t.args[0]!==`-NoProfile`||t.args[1]!==`-NonInteractive`||t.args[2]!==`-Command`)return!1;let e=t.args[3];return typeof e==`string`&&e.includes(`# ok-mcp-win-v1`)}if(t.type===`local`&&Array.isArray(t.command)){if(t.command[0]===`/bin/sh`){if(t.command[1]!==`-l`||t.command[2]!==`-c`)return!1;let e=t.command[3];return typeof e==`string`&&e.includes(`# ok-mcp-v1`)}if(t.command[0]===`powershell`){if(t.command[1]!==`-NoProfile`||t.command[2]!==`-NonInteractive`||t.command[3]!==`-Command`)return!1;let e=t.command[4];return typeof e==`string`&&e.includes(`# ok-mcp-win-v1`)}return!1}if(t.command===`ok-pi-managed-extension`){if(!Array.isArray(t.args))return!1;let e=t.args[0];return typeof e==`string`&&e.startsWith(M)}return!1}function F(e=process.argv[1]){if(!e)throw Error(`Cannot infer the local CLI entry for --dev-mcp because process.argv[1] is empty.`);let t=f(e);if(s(t)===`cli.mjs`&&s(c(t))===`dist`)return t;let n=t.split(p),r=n.lastIndexOf(`packages`);if(r===-1||n[r+1]!==`cli`)throw Error(`Cannot infer the repo root for --dev-mcp from ${t}. Run the local CLI from this repo so the built dist path can be derived.`);let i=n.slice(0,r);return u(i.length===0?p:i.join(p),`packages`,`cli`,`dist`,`cli.mjs`)}function I(e={}){return e.mode===`dev`?{command:T,args:[F(),`mcp`],env:{...E}}:(e.platformName??process.platform)===`win32`?{command:`powershell`,args:[`-NoProfile`,`-NonInteractive`,`-Command`,A]}:{command:`/bin/sh`,args:[`-l`,`-c`,O]}}function te(e={}){return e.mode===`dev`?{type:`local`,enabled:!0,command:[T,F(),`mcp`],environment:{...E}}:(e.platformName??process.platform)===`win32`?{type:`local`,enabled:!0,command:[`powershell`,`-NoProfile`,`-NonInteractive`,`-Command`,A]}:{type:`local`,enabled:!0,command:[`/bin/sh`,`-l`,`-c`,O]}}function L(e){if(typeof e!=`object`||!e)return!1;let t=e;return R(t,I({mode:`published`,platformName:`darwin`}))||R(t,I({mode:`published`,platformName:`win32`}))}function R(e,t){if(Object.keys(e).length!==Object.keys(t).length||e.command!==t.command)return!1;let n=t.args;return!Array.isArray(n)||!Array.isArray(e.args)||e.args.length!==n.length?!1:e.args.every((e,t)=>e===n[t])}function z(e){return e===`win32`?m:d}function B(e={}){let t=e.platformName??process.platform,n=e.home??h(),r=e.env??process.env,i=z(t);return t===`darwin`?i.join(n,`Library`,`Application Support`):t===`win32`?r.APPDATA??i.join(n,`AppData`,`Roaming`):r.XDG_CONFIG_HOME??i.join(n,`.config`)}function V(e={}){let t=e.platformName??process.platform,n=e.home??h();return z(t).join(n,`.claude.json`)}function H(e={}){let t=e.platformName??process.platform,n=e.home??h(),r=e.env??process.env;if(t===`darwin`)return d.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(t===`win32`){let e=r.APPDATA??m.join(n,`AppData`,`Roaming`);return m.join(e,`Claude`,`claude_desktop_config.json`)}throw Error(`Claude Desktop is not available on ${t}. Supported: macOS, Windows.`)}function U(e={}){let t=e.platformName??process.platform,n=e.home??h();return z(t).join(n,`.cursor`,`mcp.json`)}function W(e={}){let t=e.platformName??process.platform,n=e.home??h();return(e.env??process.env).CODEX_HOME??z(t).join(n,`.codex`)}function G(e={}){return z(e.platformName??process.platform).join(W(e),`config.toml`)}function K(e={}){let t=e.platformName??process.platform,n=e.home??h(),r=e.env??process.env,i=z(t);if(t===`win32`){let e=r.APPDATA??i.join(n,`AppData`,`Roaming`);return i.join(e,`opencode`)}let a=r.XDG_CONFIG_HOME??i.join(n,`.config`);return i.join(a,`opencode`)}function q(e={}){return z(e.platformName??process.platform).join(K(e),`opencode.json`)}function J(e={}){let t=e.platformName??process.platform,n=e.home??h();return z(t).join(n,`.openclaw`,`openclaw.json`)}function Y(e={}){let t=e.platformName??process.platform,n=e.home??h();return(e.env??process.env).PI_CODING_AGENT_DIR??z(t).join(n,`.pi`,`agent`)}const X={claude:{id:`claude`,label:C.claude,configPath:(e,t)=>V({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>n,buildEntry:(e,t)=>I(t),scope:`global`,detectPath:(e,t)=>u(t??h(),`.claude`),projectConfigPath:e=>u(e,`.mcp.json`),projectSkillPath:e=>u(e,`.claude`,`skills`,`open-knowledge`,`SKILL.md`)},"claude-desktop":{id:`claude-desktop`,label:C[`claude-desktop`],configPath:(e,t)=>H({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>n,buildEntry:(e,t)=>I(t),scope:`global`,detectPath:(e,t)=>c(H({home:t}))},cursor:{id:`cursor`,label:C.cursor,configPath:(e,t)=>U({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>n,buildEntry:(e,t)=>I(t),scope:`global`,detectPath:(e,t)=>c(U({home:t})),projectConfigPath:e=>u(e,`.cursor`,`mcp.json`),projectSkillPath:e=>u(e,`.cursor`,`skills`,`open-knowledge`,`SKILL.md`)},codex:{id:`codex`,label:C.codex,configPath:(e,t)=>G({home:t}),format:`toml`,topLevelKey:`mcp_servers`,serverName:()=>n,buildEntry:(e,t)=>I(t),scope:`global`,detectPath:(e,t)=>c(G({home:t})),projectConfigPath:e=>u(e,`.codex`,`config.toml`),projectSkillPath:e=>u(e,`.codex`,`skills`,`open-knowledge`,`SKILL.md`)},opencode:{id:`opencode`,label:C.opencode,configPath:(e,t)=>q({home:t}),format:`json`,topLevelKey:`mcp`,serverName:()=>n,buildEntry:(e,t)=>te(t),scope:`global`,detectPath:(e,t)=>c(q({home:t})),projectConfigPath:e=>u(e,`opencode.json`),projectSkillPath:e=>u(e,`.opencode`,`skills`,`open-knowledge`,`SKILL.md`)},openclaw:{id:`openclaw`,label:C.openclaw,configPath:(e,t)=>J({home:t}),format:`json`,topLevelKey:`mcp`,serverMapSubKey:`servers`,serverName:()=>n,buildEntry:(e,t)=>I(t),scope:`global`,detectPath:(e,t)=>u(t??h(),`.openclaw`),offerOnlyWhenDetected:!0},pi:{id:`pi`,label:C.pi,configPath:()=>{throw Error("Pi has no user-global MCP config; OK's integration is the project-scoped bridge extension at .pi/extensions/open-knowledge.ts (run `ok init` in the project).")},format:`file`,topLevelKey:`mcpServers`,serverName:()=>n,buildEntry:()=>{throw Error(`Pi has no MCP entry shape; the managed bridge file is built by buildPiExtensionSource (integrations/pi-extension.ts).`)},scope:`project`,detectPath:(e,t)=>Y({home:t}),projectConfigPath:e=>u(e,`.pi`,`extensions`,`open-knowledge.ts`),projectSkillPath:e=>u(e,`.pi`,`skills`,`open-knowledge`,`SKILL.md`)}};function Z(e){let t=e.filter(e=>!Object.hasOwn(X,e));if(t.length>0)throw Error(`Unknown editor(s): ${t.join(`, `)}. Valid options: ${S.join(`, `)}`);return e.map(e=>X[e])}function Q(e){let t=[];for(let n of o){let r=i[n];t.push({path:u(e,`.agents`,`skills`,r),bundleId:n,scope:`central`});for(let i of w)t.push({path:u(e,i.hostDir,`skills`,r),bundleId:n,scope:`host`,hostDir:i.hostDir})}return t}function ne(e,t){let n=[];for(let r of Q(e))if(r.bundleId===t)try{x(r.path,{recursive:!0,force:!0})}catch(e){n.push(e instanceof Error?e:Error(String(e)))}if(n.length>0)throw AggregateError(n,`Failed to remove ${n.length} path(s) for ${t}`)}function $(e,t){let n;try{n=b(t)}catch{n=f(t)}let r;try{r=v(e)}catch(e){if(e.code!==`ENOENT`)throw e}if(r?.isSymbolicLink())throw Error(`Refusing to write through a symbolic link at ${e}. Remove the symlink and re-run project setup.`);let i=c(e);for(;i.length>1&&i!==p;){let t;try{t=b(i)}catch(e){if(e.code===`ENOENT`){i=c(i);continue}throw e}let r=ee(n,t);if(r===``||!r.startsWith(`..`)&&!l(r))return;throw Error(`Refusing to write at ${e}: ancestor ${i} resolves to ${t}, which is outside the project directory ${n}. A symbolic link in the path likely escapes the project. Remove the symlink and re-run project setup.`)}}function re(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let r=a(`project`,{checkDesktop:!0}),i=c(n);$(i,t);let o=_(n)?`overwritten`:`written`;return x(i,{recursive:!0,force:!0}),y(c(i),{recursive:!0}),g(r,i,{recursive:!0}),{editorId:e.id,label:e.label,action:o,path:n}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}export{B as _,S as a,C as c,j as d,M as f,L as g,P as h,Q as i,X as l,I as m,re as n,D as o,N as p,ne as r,k as s,$ as t,w as u,F as v,Z as y};
|
|
36
|
+
//# sourceMappingURL=write-project-skill-BEzL3S1a.mjs.map
|
package/package.json
CHANGED
package/dist/init-9d1LNBPj.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{v as e}from"./init-Dvj0QJzs.mjs";export{e as runInit};
|