@redocly/replay 0.28.0-next.0 → 0.28.0-next.10

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.
Files changed (82) hide show
  1. package/dist/replay-AiChatProvider-BWL86hXh.js +6 -0
  2. package/dist/{replay-AiChatProvider-BZUzXfD-.js → replay-AiChatProvider-CY3b_ggu.js} +376 -376
  3. package/dist/{replay-AiChatSqliteDBStorage-CTVtufnx.js → replay-AiChatSqliteDBStorage-BtV53vvj.js} +1 -1
  4. package/dist/{replay-AiChatSqliteDBStorage-JpKE0iGm.js → replay-AiChatSqliteDBStorage-CjzLqUwK.js} +6 -6
  5. package/dist/{replay-AiPanel-DkR-vZTK.js → replay-AiPanel-B3HBaMPh.js} +706 -709
  6. package/dist/replay-AiPanel-BzaoPsXZ.js +742 -0
  7. package/dist/replay-FileWatcher-BFtAqsmL.js +1 -0
  8. package/dist/replay-FileWatcher-d1_qKRfS.js +364 -0
  9. package/dist/{replay-HistorySqliteDBStorage-CtF6-vY8.js → replay-HistorySqliteDBStorage-Bi5vBQ2T.js} +2 -2
  10. package/dist/replay-SemanticSearchService-CTWesmRy.js +1 -0
  11. package/dist/{replay-SemanticSearchService-CSsOmkV_.js → replay-SemanticSearchService-DcR4Q6w6.js} +27 -31
  12. package/dist/{replay-SqliteDBStorage-DpAEbsAQ.js → replay-SqliteDBStorage-BeDAsnlF.js} +1 -1
  13. package/dist/{replay-SqliteDBStorage-BSMAgfUS.js → replay-SqliteDBStorage-BlVDbZhU.js} +49 -49
  14. package/dist/{replay-StepContextSqliteDBStorage-BfAAKDwA.js → replay-StepContextSqliteDBStorage-BkB2NM27.js} +2 -2
  15. package/dist/replay-TauriFileSystemAdapter-B_VaAUfL.js +1 -0
  16. package/dist/replay-TauriFileSystemAdapter-Cu-Q6QS_.js +108 -0
  17. package/dist/replay-TauriRootStorage-Cidjagk-.js +1 -0
  18. package/dist/{replay-TauriRootStorage-g9zf2-FS.js → replay-TauriRootStorage-DVeU3RvV.js} +213 -210
  19. package/dist/{replay-agent-loop-be2meQsN.js → replay-agent-loop-B42P9R-q.js} +1 -1
  20. package/dist/{replay-agent-loop-ClVUvt0C.js → replay-agent-loop-DweKWrQp.js} +5 -5
  21. package/dist/{replay-ai-chat-mappers-JOZvaHV_.js → replay-ai-chat-mappers-Cno0s3T8.js} +1 -1
  22. package/dist/{replay-ai-chat-mappers-CwvRub6i.js → replay-ai-chat-mappers-DusPRQPG.js} +3 -3
  23. package/dist/{replay-ai-message-parts.schema-E9u9-nqr.js → replay-ai-message-parts.schema-DKLf0SiG.js} +1 -1
  24. package/dist/{replay-create-model-rzGPB8KT.js → replay-create-model-CeSlm24x.js} +4 -4
  25. package/dist/{replay-create-model-CJ3dsZg8.js → replay-create-model-DdPq1CIm.js} +3 -3
  26. package/dist/{replay-db-CW7044b2.js → replay-db-Bj8Qpvpw.js} +1 -1
  27. package/dist/{replay-db-zC1KPTH0.js → replay-db-he8XQjrM.js} +1 -1
  28. package/dist/{replay-external-resolver-BDPRz7Xd.js → replay-external-resolver-BRs5F07f.js} +7 -7
  29. package/dist/{replay-external-resolver-Dty0CDYE.js → replay-external-resolver-gQ0egbx7.js} +1 -1
  30. package/dist/{replay-history.schema-5ce6X0R1.js → replay-history.schema-B0lLwmdG.js} +3 -3
  31. package/dist/replay-index-B1qPs-GR.js +4 -0
  32. package/dist/replay-index-C2b91LJZ.js +7013 -0
  33. package/dist/{replay-index--hMZLQs8.js → replay-index-CA6OI1Qg.js} +1 -1
  34. package/dist/replay-index-CYphcClc.js +1 -0
  35. package/dist/{replay-index-F4GEOEUz.js → replay-index-DRb3mixV.js} +65311 -63618
  36. package/dist/replay-index-Dtxwps1s.js +574 -0
  37. package/dist/replay-index-NgGicGfR.js +1 -0
  38. package/dist/{replay-index-DZN7KzbY.js → replay-index-uF3nFq_Y.js} +1 -1
  39. package/dist/{replay-indexes-CfsvVMi_.js → replay-indexes-B3PJtgeh.js} +43 -43
  40. package/dist/replay-lint-C2hyYWRS.js +177 -0
  41. package/dist/{replay-lint-9YeYgRBU.js → replay-lint-gY_wyYPJ.js} +17581 -21140
  42. package/dist/{replay-lint-graphql-Dba0twW-.js → replay-lint-graphql-BA9t8-Ua.js} +1 -1
  43. package/dist/{replay-lint-graphql-BelJUl9-.js → replay-lint-graphql-DDrnrINc.js} +1 -1
  44. package/dist/replay-periodic-revalidation-BbAt74oL.js +21 -0
  45. package/dist/replay-periodic-revalidation-kmD2RQn1.js +1 -0
  46. package/dist/replay-resolve-BJ_AY-Mn.js +47 -0
  47. package/dist/{replay-resolve-RxCCaHXw.js → replay-resolve-_V8uYdTK.js} +470 -468
  48. package/dist/replay-respect-run-CLLZoRh1.js +8392 -0
  49. package/dist/replay-respect-run-qOz91QPQ.js +82 -0
  50. package/dist/replay-step-context.schema-BOprzd6Z.js +21 -0
  51. package/dist/{replay-tauri-path-hGM_JYax.js → replay-tauri-path-lH8t5rdX.js} +1 -1
  52. package/dist/replay-tauri-path-twTA2lKs.js +22 -0
  53. package/dist/replay-useAiChatQueries-BIqM2KQW.js +215 -0
  54. package/dist/{replay-useAiChatQueries-DD84oZan.js → replay-useAiChatQueries-yCsYY1j2.js} +1583 -1371
  55. package/dist/{replay-validate-key-xk-9xmJ6.js → replay-validate-key-Bh41yY9h.js} +2 -2
  56. package/dist/{replay-validate-key-PS5qrafQ.js → replay-validate-key-_oaOw5Jy.js} +1 -1
  57. package/dist/replay.cjs +1 -1
  58. package/dist/replay.d.ts +10 -3
  59. package/dist/replay.js +14 -14
  60. package/package.json +20 -13
  61. package/dist/replay-AiChatProvider-Dllh11wo.js +0 -6
  62. package/dist/replay-AiPanel-DruBN19L.js +0 -742
  63. package/dist/replay-FileWatcher-D3W6TGFC.js +0 -1
  64. package/dist/replay-FileWatcher-v7Qw29PS.js +0 -343
  65. package/dist/replay-SemanticSearchService-Dfx2W4Za.js +0 -1
  66. package/dist/replay-TauriFileSystemAdapter-BLPH1Vx3.js +0 -1
  67. package/dist/replay-TauriFileSystemAdapter-Ddq9xfo1.js +0 -99
  68. package/dist/replay-TauriRootStorage-l_sNXRNW.js +0 -1
  69. package/dist/replay-index-5UkXwLrd.js +0 -504
  70. package/dist/replay-index-9h4E2FR8.js +0 -1
  71. package/dist/replay-index-B7GU_aMu.js +0 -25
  72. package/dist/replay-index-DbWKCsKW.js +0 -6906
  73. package/dist/replay-index-ko78Z8QX.js +0 -1
  74. package/dist/replay-lint-DK6LCpO2.js +0 -184
  75. package/dist/replay-periodic-revalidation-BoyLQHtg.js +0 -1
  76. package/dist/replay-periodic-revalidation-Dsp-n7ui.js +0 -21
  77. package/dist/replay-resolve-CRBvIGPM.js +0 -47
  78. package/dist/replay-respect-run-BP5Q5L8N.js +0 -78
  79. package/dist/replay-respect-run-CRGPD-UQ.js +0 -8200
  80. package/dist/replay-step-context.schema-DBk4jufr.js +0 -21
  81. package/dist/replay-tauri-path-BmHpvlYp.js +0 -22
  82. package/dist/replay-useAiChatQueries-KVveua_P.js +0 -215
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./replay-index-DbWKCsKW.js"),u=require("./replay-SemanticSearchService-Dfx2W4Za.js");require("react");var m;(function(r){r.WINDOW_RESIZED="tauri://resize",r.WINDOW_MOVED="tauri://move",r.WINDOW_CLOSE_REQUESTED="tauri://close-requested",r.WINDOW_DESTROYED="tauri://destroyed",r.WINDOW_FOCUS="tauri://focus",r.WINDOW_BLUR="tauri://blur",r.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",r.WINDOW_THEME_CHANGED="tauri://theme-changed",r.WINDOW_CREATED="tauri://window-created",r.WEBVIEW_CREATED="tauri://webview-created",r.DRAG_ENTER="tauri://drag-enter",r.DRAG_OVER="tauri://drag-over",r.DRAG_DROP="tauri://drag-drop",r.DRAG_LEAVE="tauri://drag-leave"})(m||(m={}));async function v(r,e){await c.invoke("plugin:event|unlisten",{event:r,eventId:e})}async function w(r,e,a){var i;const t=(i=void 0)!==null&&i!==void 0?i:{kind:"Any"};return c.invoke("plugin:event|listen",{event:r,target:t,handler:c.transformCallback(e)}).then(s=>async()=>v(r,s))}class y{constructor(e,a,i,t){this.storage=e,this.state=a,this.projectDir=i,this.aiEnabled=t}storage;state;projectDir;aiEnabled;watchPath=null;unlistenEvent=null;get tauriStorage(){return this.storage}indexApis(e){!this.aiEnabled||e.length===0||u.getSemanticSearchService().indexApis(e).catch(a=>console.error("Semantic index (apis):",a))}indexCollections(e){!this.aiEnabled||e.length===0||u.getSemanticSearchService().indexCollections(e).catch(a=>console.error("Semantic index (collections):",a))}removeApis(e){if(!this.aiEnabled||e.length===0)return;const a=u.getSemanticSearchService();Promise.all(e.map(i=>a.removeApi(i))).catch(i=>console.error("Semantic remove (apis):",i))}removeCollections(e){if(!this.aiEnabled||e.length===0)return;const a=u.getSemanticSearchService();Promise.all(e.map(i=>a.removeCollection(i))).catch(i=>console.error("Semantic remove (collections):",i))}async start(){if(this.watchPath){console.warn("Watcher already started for:",this.watchPath);return}try{this.unlistenEvent=await w("fs-watch-event",async e=>{const a=e.payload;try{await this.handleEvent(a)}catch(i){console.error("Error handling file change:",i)}}),await c.invoke("fs_watch",{path:this.projectDir,options:{recursive:!0,delayMs:500}}),this.watchPath=this.projectDir}catch(e){throw console.error("Failed to start file watcher:",e),this.unlistenEvent&&(this.unlistenEvent(),this.unlistenEvent=null),e}}async stop(){if(this.watchPath)try{await c.invoke("fs_unwatch",{path:this.watchPath})}catch(e){console.error("Error stopping file watcher:",e)}finally{this.unlistenEvent&&(this.unlistenEvent(),this.unlistenEvent=null),this.watchPath=null}}async handleEvent(e){const{changeType:a,paths:i,pathTypes:t,type:s}=e;if(await this.isProjectFolderRemoved(i,a)){await this.handleProjectFolderRemoval();return}const n=this.filterSpecFiles(i,t);if(n.paths.length===0)return;const o=await this.toFileEntries(n.paths,n.pathTypes);switch(a){case"changed":(s.includes("Data")||s.includes("Name"))&&await this.handleModify(o);break;case"added":await this.handleCreate(o);break;case"deleted":await this.handleDelete(o);break;case"renamed":await this.handleRename(o);break;default:console.log("Unhandled change type:",a)}}filterSpecFiles(e,a){const i=[],t=[];for(let s=0;s<e.length;s++){const n=e[s],o=n.split(".").pop()?.toLowerCase();o&&["yaml","yml","json"].includes(o)&&(i.push(n),t.push(a[s]||"unknown"))}return{paths:i,pathTypes:t}}async toFileEntries(e,a){return Promise.all(e.map(async(i,t)=>({relative_path:await c.PathUtils.relative(this.projectDir,i),absolute_path:i,type:a[t]||"unknown"})))}consolidateFileEntries(e){const a=[],i=new Set;for(const t of e)i.has(t.relative_path)||(i.add(t.relative_path),this.storage.isWatchExcluded(t.relative_path)||a.push(t));return a}async handleModify(e){const a=!this.storage.isWatchExcluded("replay-environments.yaml")&&e.some(g=>g.relative_path==="replay-environments.yaml"),i=e.filter(g=>g.relative_path!=="replay-environments.yaml"),{newApiFiles:t,existingApiFiles:s}=this.categorizeApisFromFiles(i),{newCollectionFiles:n,existingCollectionFiles:o}=this.categorizeCollectionsFromFiles(i),h=await this.findApisToReload(e),f=await this.findCollectionsToReload(e),d=[...t,...n];d.length>0&&await this.handleCreate(d),a&&await this.reloadEnvironments();const p=this.consolidateFileEntries([...s,...h]),l=this.consolidateFileEntries([...o,...f]);await this.reloadApis(p),await this.reloadCollections(l)}async handleCreate(e){const a=e.filter(h=>h.type==="api"),i=e.filter(h=>h.type==="collection"),{newApiFiles:t,existingApiFiles:s}=this.categorizeApisFromFiles(a),{newCollectionFiles:n,existingCollectionFiles:o}=this.categorizeCollectionsFromFiles(i);if(t.length>0||n.length>0){t.forEach(l=>this.storage.addPersistExcludedId(l.relative_path)),n.forEach(l=>this.storage.addPersistExcludedId(l.relative_path));const h=t.length>0?await this.tauriStorage.loadAndParseApis(t,void 0,!0):[],f=n.length>0?await this.tauriStorage.loadAndParseCollections(n,void 0):[],d=h.filter(l=>l!==null),p=f.filter(l=>l!==null);this.state.apis.merge(d),this.state.collections.merge(p),this.indexApis(d),this.indexCollections(p),setTimeout(()=>{t.forEach(l=>this.storage.removePersistExcludedId(l.relative_path)),n.forEach(l=>this.storage.removePersistExcludedId(l.relative_path))},500)}s.length>0&&await this.reloadApis(s),o.length>0&&await this.reloadCollections(o)}categorizeApisFromFiles(e){const a=new Set,i=[],t=[];for(const s of e){if(a.has(s.relative_path))continue;a.add(s.relative_path),this.state.apis.get({noproxy:!0}).some(o=>o.id===s.relative_path)?t.push(s):s.type==="api"&&i.push(s)}return{newApiFiles:i,existingApiFiles:t}}categorizeCollectionsFromFiles(e){const a=new Set,i=[],t=[];for(const s of e){if(a.has(s.relative_path))continue;a.add(s.relative_path),this.state.collections.get({noproxy:!0}).some(o=>o.id===s.relative_path)?t.push(s):s.type==="collection"&&i.push(s)}return{newCollectionFiles:i,existingCollectionFiles:t}}async handleDelete(e){const a=[],i=[];for(const t of e){this.storage.addPersistExcludedId(t.relative_path);const s=this.state.apis.get({noproxy:!0}).findIndex(o=>o.id===t.relative_path);s>=0&&(this.state.apis[s].set(c.none),this.tauriStorage.deleteApiFromCache(t.relative_path),a.push(t.relative_path));const n=this.state.collections.get({noproxy:!0}).findIndex(o=>o.id===t.relative_path);n>=0&&(this.state.collections[n].set(c.none),i.push(t.relative_path)),setTimeout(()=>{this.storage.removePersistExcludedId(t.relative_path)},500)}this.removeApis(a),this.removeCollections(i)}async handleRename(e){if(e.length>=2){const[a,i]=e;await this.handleDelete([a]),await this.handleCreate([i])}else await this.handleCreate(e)}async isProjectFolderRemoved(e,a){if(e.length===0)return!1;if(a==="deleted"||a==="renamed"){for(const t of e)if(t===this.projectDir)return!0}return e.filter(t=>!t.startsWith(this.projectDir+"/")&&t!==this.projectDir).length>0&&a==="renamed"}async handleProjectFolderRemoval(){const e=this.state.apis.get({noproxy:!0}),a=e.map(s=>s.id);e.forEach(s=>{this.storage.addPersistExcludedId(s.id),this.tauriStorage.deleteApiFromCache(s.id)}),this.state.apis.set([]);const i=this.state.collections.get({noproxy:!0}),t=i.map(s=>s.id);i.forEach(s=>{this.storage.addPersistExcludedId(s.id)}),this.state.collections.set([]),setTimeout(()=>{e.forEach(s=>this.storage.removePersistExcludedId(s.id)),i.forEach(s=>this.storage.removePersistExcludedId(s.id))},500),this.removeApis(a),this.removeCollections(t),await this.stop()}async findApisToReload(e){const a=[];return await Promise.all(this.state.apis.map(async i=>{const t=i.fileDependencies?.get({noproxy:!0})??new Set,s=i.get({noproxy:!0}).id,n=e.find(o=>t.has(o.absolute_path));if(!this.storage.isWatchExcluded(s)&&n){const o=await c.PathUtils.join(this.projectDir,s);a.push({relative_path:s,absolute_path:o,type:"api"})}})),a}async findCollectionsToReload(e){const a=[];return await Promise.all(this.state.collections.map(async i=>{const t=i.fileDependencies?.get({noproxy:!0})??new Set,s=i.get({noproxy:!0}).id,n=e.find(o=>t.has(o.absolute_path));if(!this.storage.isWatchExcluded(s)&&n){const o=await c.PathUtils.join(this.projectDir,s);a.push({relative_path:s,absolute_path:o,type:"collection"})}})),a}async reloadEnvironments(){const e=await this.tauriStorage.readEnviroments();this.storage.addPersistExcludedId("replay-environments.yaml"),this.state.environments.set(e),setTimeout(()=>{this.storage.removePersistExcludedId("replay-environments.yaml")},500)}async reloadApis(e){if(e.length===0)return;const a=await this.tauriStorage.loadAndParseApis(e,void 0,!0),i=[];await Promise.all(a.map(async(t,s)=>{if(!t){await this.handleDelete([e[s]]);return}const n=this.state.apis.get({noproxy:!0}).findIndex(o=>o.id===t.id);n>=0?(this.storage.addPersistExcludedId(t.id),this.state.apis[n].set(t),i.push(t),setTimeout(()=>this.storage.removePersistExcludedId(t.id),500)):console.warn("API not found in state after reload:",t.id)})),i.length>0&&this.indexApis(i)}async reloadCollections(e){if(e.length===0)return;const a=await this.tauriStorage.loadAndParseCollections(e,void 0),i=[];await Promise.all(a.map(async(t,s)=>{if(!t){await this.handleDelete([e[s]]);return}const n=this.state.collections.get({noproxy:!0}).findIndex(o=>o.id===t.id);n>=0?(this.storage.addPersistExcludedId(t.id),this.state.collections[n].set(t),i.push(t),setTimeout(()=>this.storage.removePersistExcludedId(t.id),500)):console.warn("Collection not found in state after reload:",t.id)})),i.length>0&&this.indexCollections(i)}}exports.FileWatcher=y;
@@ -1,343 +0,0 @@
1
- import { i as u, t as y, P as m, n as v } from "./replay-index-F4GEOEUz.js";
2
- import { g as p } from "./replay-SemanticSearchService-CSsOmkV_.js";
3
- import "react";
4
- var w;
5
- (function(r) {
6
- r.WINDOW_RESIZED = "tauri://resize", r.WINDOW_MOVED = "tauri://move", r.WINDOW_CLOSE_REQUESTED = "tauri://close-requested", r.WINDOW_DESTROYED = "tauri://destroyed", r.WINDOW_FOCUS = "tauri://focus", r.WINDOW_BLUR = "tauri://blur", r.WINDOW_SCALE_FACTOR_CHANGED = "tauri://scale-change", r.WINDOW_THEME_CHANGED = "tauri://theme-changed", r.WINDOW_CREATED = "tauri://window-created", r.WEBVIEW_CREATED = "tauri://webview-created", r.DRAG_ENTER = "tauri://drag-enter", r.DRAG_OVER = "tauri://drag-over", r.DRAG_DROP = "tauri://drag-drop", r.DRAG_LEAVE = "tauri://drag-leave";
7
- })(w || (w = {}));
8
- async function E(r, e) {
9
- await u("plugin:event|unlisten", {
10
- event: r,
11
- eventId: e
12
- });
13
- }
14
- async function x(r, e, a) {
15
- var i;
16
- const t = (i = void 0) !== null && i !== void 0 ? i : { kind: "Any" };
17
- return u("plugin:event|listen", {
18
- event: r,
19
- target: t,
20
- handler: y(e)
21
- }).then((s) => async () => E(r, s));
22
- }
23
- class A {
24
- constructor(e, a, i, t) {
25
- this.storage = e, this.state = a, this.projectDir = i, this.aiEnabled = t;
26
- }
27
- storage;
28
- state;
29
- projectDir;
30
- aiEnabled;
31
- watchPath = null;
32
- unlistenEvent = null;
33
- get tauriStorage() {
34
- return this.storage;
35
- }
36
- indexApis(e) {
37
- !this.aiEnabled || e.length === 0 || p().indexApis(e).catch((a) => console.error("Semantic index (apis):", a));
38
- }
39
- indexCollections(e) {
40
- !this.aiEnabled || e.length === 0 || p().indexCollections(e).catch((a) => console.error("Semantic index (collections):", a));
41
- }
42
- removeApis(e) {
43
- if (!this.aiEnabled || e.length === 0) return;
44
- const a = p();
45
- Promise.all(e.map((i) => a.removeApi(i))).catch(
46
- (i) => console.error("Semantic remove (apis):", i)
47
- );
48
- }
49
- removeCollections(e) {
50
- if (!this.aiEnabled || e.length === 0) return;
51
- const a = p();
52
- Promise.all(e.map((i) => a.removeCollection(i))).catch(
53
- (i) => console.error("Semantic remove (collections):", i)
54
- );
55
- }
56
- /**
57
- * Starts watching the directory for changes.
58
- */
59
- async start() {
60
- if (this.watchPath) {
61
- console.warn("Watcher already started for:", this.watchPath);
62
- return;
63
- }
64
- try {
65
- this.unlistenEvent = await x("fs-watch-event", async (e) => {
66
- const a = e.payload;
67
- try {
68
- await this.handleEvent(a);
69
- } catch (i) {
70
- console.error("Error handling file change:", i);
71
- }
72
- }), await u("fs_watch", {
73
- path: this.projectDir,
74
- options: {
75
- recursive: !0,
76
- delayMs: 500
77
- }
78
- }), this.watchPath = this.projectDir;
79
- } catch (e) {
80
- throw console.error("Failed to start file watcher:", e), this.unlistenEvent && (this.unlistenEvent(), this.unlistenEvent = null), e;
81
- }
82
- }
83
- /**
84
- * Stops watching and cleans up resources.
85
- */
86
- async stop() {
87
- if (this.watchPath)
88
- try {
89
- await u("fs_unwatch", { path: this.watchPath });
90
- } catch (e) {
91
- console.error("Error stopping file watcher:", e);
92
- } finally {
93
- this.unlistenEvent && (this.unlistenEvent(), this.unlistenEvent = null), this.watchPath = null;
94
- }
95
- }
96
- /**
97
- * Main event handler - dispatches to specific handlers based on event type.
98
- */
99
- async handleEvent(e) {
100
- const { changeType: a, paths: i, pathTypes: t, type: s } = e;
101
- if (await this.isProjectFolderRemoved(i, a)) {
102
- await this.handleProjectFolderRemoval();
103
- return;
104
- }
105
- const n = this.filterSpecFiles(i, t);
106
- if (n.paths.length === 0)
107
- return;
108
- const o = await this.toFileEntries(n.paths, n.pathTypes);
109
- switch (a) {
110
- case "changed":
111
- (s.includes("Data") || s.includes("Name")) && await this.handleModify(o);
112
- break;
113
- case "added":
114
- await this.handleCreate(o);
115
- break;
116
- case "deleted":
117
- await this.handleDelete(o);
118
- break;
119
- case "renamed":
120
- await this.handleRename(o);
121
- break;
122
- default:
123
- console.log("Unhandled change type:", a);
124
- }
125
- }
126
- /**
127
- * Filter paths to only include yaml/json files.
128
- * Returns filtered paths and their corresponding pathTypes.
129
- */
130
- filterSpecFiles(e, a) {
131
- const i = [], t = [];
132
- for (let s = 0; s < e.length; s++) {
133
- const n = e[s], o = n.split(".").pop()?.toLowerCase();
134
- o && ["yaml", "yml", "json"].includes(o) && (i.push(n), t.push(a[s] || "unknown"));
135
- }
136
- return { paths: i, pathTypes: t };
137
- }
138
- /**
139
- * Convert absolute paths to file entry format with relative paths and types.
140
- */
141
- async toFileEntries(e, a) {
142
- return Promise.all(
143
- e.map(async (i, t) => ({
144
- relative_path: await m.relative(this.projectDir, i),
145
- absolute_path: i,
146
- type: a[t] || "unknown"
147
- }))
148
- );
149
- }
150
- consolidateFileEntries(e) {
151
- const a = [], i = /* @__PURE__ */ new Set();
152
- for (const t of e)
153
- i.has(t.relative_path) || (i.add(t.relative_path), this.storage.isWatchExcluded(t.relative_path) || a.push(t));
154
- return a;
155
- }
156
- /**
157
- * Handles file content modification events.
158
- * If file doesn't exist in state yet, treat as creation.
159
- */
160
- async handleModify(e) {
161
- const a = !this.storage.isWatchExcluded("replay-environments.yaml") && e.some((g) => g.relative_path === "replay-environments.yaml"), i = e.filter((g) => g.relative_path !== "replay-environments.yaml"), { newApiFiles: t, existingApiFiles: s } = this.categorizeApisFromFiles(i), { newCollectionFiles: n, existingCollectionFiles: o } = this.categorizeCollectionsFromFiles(i), c = await this.findApisToReload(e), f = await this.findCollectionsToReload(e), d = [...t, ...n];
162
- d.length > 0 && await this.handleCreate(d), a && await this.reloadEnvironments();
163
- const h = this.consolidateFileEntries([...s, ...c]), l = this.consolidateFileEntries([
164
- ...o,
165
- ...f
166
- ]);
167
- await this.reloadApis(h), await this.reloadCollections(l);
168
- }
169
- /**
170
- * Handles file creation events.
171
- * If file already exists in state, update it instead of creating duplicate.
172
- */
173
- async handleCreate(e) {
174
- const a = e.filter((c) => c.type === "api"), i = e.filter((c) => c.type === "collection"), { newApiFiles: t, existingApiFiles: s } = this.categorizeApisFromFiles(a), { newCollectionFiles: n, existingCollectionFiles: o } = this.categorizeCollectionsFromFiles(i);
175
- if (t.length > 0 || n.length > 0) {
176
- t.forEach((l) => this.storage.addPersistExcludedId(l.relative_path)), n.forEach((l) => this.storage.addPersistExcludedId(l.relative_path));
177
- const c = t.length > 0 ? await this.tauriStorage.loadAndParseApis(t, void 0, !0) : [], f = n.length > 0 ? await this.tauriStorage.loadAndParseCollections(n, void 0) : [], d = c.filter((l) => l !== null), h = f.filter((l) => l !== null);
178
- this.state.apis.merge(d), this.state.collections.merge(h), this.indexApis(d), this.indexCollections(h), setTimeout(() => {
179
- t.forEach((l) => this.storage.removePersistExcludedId(l.relative_path)), n.forEach(
180
- (l) => this.storage.removePersistExcludedId(l.relative_path)
181
- );
182
- }, 500);
183
- }
184
- s.length > 0 && await this.reloadApis(s), o.length > 0 && await this.reloadCollections(o);
185
- }
186
- /**
187
- * Categorize API paths into new vs existing
188
- */
189
- /**
190
- * Categorize API files into new vs existing
191
- */
192
- categorizeApisFromFiles(e) {
193
- const a = /* @__PURE__ */ new Set(), i = [], t = [];
194
- for (const s of e) {
195
- if (a.has(s.relative_path))
196
- continue;
197
- a.add(s.relative_path), this.state.apis.get({ noproxy: !0 }).some((o) => o.id === s.relative_path) ? t.push(s) : s.type === "api" && i.push(s);
198
- }
199
- return { newApiFiles: i, existingApiFiles: t };
200
- }
201
- /**
202
- * Categorize collection files into new vs existing
203
- */
204
- categorizeCollectionsFromFiles(e) {
205
- const a = /* @__PURE__ */ new Set(), i = [], t = [];
206
- for (const s of e) {
207
- if (a.has(s.relative_path))
208
- continue;
209
- a.add(s.relative_path), this.state.collections.get({ noproxy: !0 }).some((o) => o.id === s.relative_path) ? t.push(s) : s.type === "collection" && i.push(s);
210
- }
211
- return { newCollectionFiles: i, existingCollectionFiles: t };
212
- }
213
- /**
214
- * Handles file deletion events.
215
- */
216
- async handleDelete(e) {
217
- const a = [], i = [];
218
- for (const t of e) {
219
- this.storage.addPersistExcludedId(t.relative_path);
220
- const s = this.state.apis.get({ noproxy: !0 }).findIndex((o) => o.id === t.relative_path);
221
- s >= 0 && (this.state.apis[s].set(v), this.tauriStorage.deleteApiFromCache(t.relative_path), a.push(t.relative_path));
222
- const n = this.state.collections.get({ noproxy: !0 }).findIndex((o) => o.id === t.relative_path);
223
- n >= 0 && (this.state.collections[n].set(v), i.push(t.relative_path)), setTimeout(() => {
224
- this.storage.removePersistExcludedId(t.relative_path);
225
- }, 500);
226
- }
227
- this.removeApis(a), this.removeCollections(i);
228
- }
229
- /**
230
- * Handles file rename/move events.
231
- * For rename events, files typically contains [oldFile, newFile]
232
- */
233
- async handleRename(e) {
234
- if (e.length >= 2) {
235
- const [a, i] = e;
236
- await this.handleDelete([a]), await this.handleCreate([i]);
237
- } else
238
- await this.handleCreate(e);
239
- }
240
- /**
241
- * Checks if the project folder itself was renamed/moved/deleted.
242
- * This happens when:
243
- * - We get a rename/delete event for the project directory itself
244
- * - Or when paths no longer match the watched directory structure
245
- */
246
- async isProjectFolderRemoved(e, a) {
247
- if (e.length === 0)
248
- return !1;
249
- if (a === "deleted" || a === "renamed") {
250
- for (const t of e)
251
- if (t === this.projectDir)
252
- return !0;
253
- }
254
- return e.filter(
255
- (t) => !t.startsWith(this.projectDir + "/") && t !== this.projectDir
256
- ).length > 0 && a === "renamed";
257
- }
258
- /**
259
- * Handles the case when the entire project folder is renamed or deleted.
260
- * Clears all APIs and collections from state.
261
- */
262
- async handleProjectFolderRemoval() {
263
- const e = this.state.apis.get({ noproxy: !0 }), a = e.map((s) => s.id);
264
- e.forEach((s) => {
265
- this.storage.addPersistExcludedId(s.id), this.tauriStorage.deleteApiFromCache(s.id);
266
- }), this.state.apis.set([]);
267
- const i = this.state.collections.get({ noproxy: !0 }), t = i.map((s) => s.id);
268
- i.forEach((s) => {
269
- this.storage.addPersistExcludedId(s.id);
270
- }), this.state.collections.set([]), setTimeout(() => {
271
- e.forEach((s) => this.storage.removePersistExcludedId(s.id)), i.forEach((s) => this.storage.removePersistExcludedId(s.id));
272
- }, 500), this.removeApis(a), this.removeCollections(t), await this.stop();
273
- }
274
- async findApisToReload(e) {
275
- const a = [];
276
- return await Promise.all(
277
- this.state.apis.map(async (i) => {
278
- const t = i.fileDependencies?.get({ noproxy: !0 }) ?? /* @__PURE__ */ new Set(), s = i.get({ noproxy: !0 }).id, n = e.find((o) => t.has(o.absolute_path));
279
- if (!this.storage.isWatchExcluded(s) && n) {
280
- const o = await m.join(this.projectDir, s);
281
- a.push({
282
- relative_path: s,
283
- absolute_path: o,
284
- type: "api"
285
- });
286
- }
287
- })
288
- ), a;
289
- }
290
- async findCollectionsToReload(e) {
291
- const a = [];
292
- return await Promise.all(
293
- this.state.collections.map(async (i) => {
294
- const t = i.fileDependencies?.get({ noproxy: !0 }) ?? /* @__PURE__ */ new Set(), s = i.get({ noproxy: !0 }).id, n = e.find((o) => t.has(o.absolute_path));
295
- if (!this.storage.isWatchExcluded(s) && n) {
296
- const o = await m.join(this.projectDir, s);
297
- a.push({
298
- relative_path: s,
299
- absolute_path: o,
300
- type: "collection"
301
- });
302
- }
303
- })
304
- ), a;
305
- }
306
- async reloadEnvironments() {
307
- const e = await this.tauriStorage.readEnviroments();
308
- this.storage.addPersistExcludedId("replay-environments.yaml"), this.state.environments.set(e), setTimeout(() => {
309
- this.storage.removePersistExcludedId("replay-environments.yaml");
310
- }, 500);
311
- }
312
- async reloadApis(e) {
313
- if (e.length === 0) return;
314
- const a = await this.tauriStorage.loadAndParseApis(e, void 0, !0), i = [];
315
- await Promise.all(
316
- a.map(async (t, s) => {
317
- if (!t) {
318
- await this.handleDelete([e[s]]);
319
- return;
320
- }
321
- const n = this.state.apis.get({ noproxy: !0 }).findIndex((o) => o.id === t.id);
322
- n >= 0 ? (this.storage.addPersistExcludedId(t.id), this.state.apis[n].set(t), i.push(t), setTimeout(() => this.storage.removePersistExcludedId(t.id), 500)) : console.warn("API not found in state after reload:", t.id);
323
- })
324
- ), i.length > 0 && this.indexApis(i);
325
- }
326
- async reloadCollections(e) {
327
- if (e.length === 0) return;
328
- const a = await this.tauriStorage.loadAndParseCollections(e, void 0), i = [];
329
- await Promise.all(
330
- a.map(async (t, s) => {
331
- if (!t) {
332
- await this.handleDelete([e[s]]);
333
- return;
334
- }
335
- const n = this.state.collections.get({ noproxy: !0 }).findIndex((o) => o.id === t.id);
336
- n >= 0 ? (this.storage.addPersistExcludedId(t.id), this.state.collections[n].set(t), i.push(t), setTimeout(() => this.storage.removePersistExcludedId(t.id), 500)) : console.warn("Collection not found in state after reload:", t.id);
337
- })
338
- ), i.length > 0 && this.indexCollections(i);
339
- }
340
- }
341
- export {
342
- A as FileWatcher
343
- };
@@ -1 +0,0 @@
1
- "use strict";const d=require("./replay-index-DbWKCsKW.js"),J=require("./replay-Observable-bjJ6wkRB.js"),ee=require("./replay-promise-map-limit-DRDkHc-b.js");function g(t){return t==null?"":typeof t=="string"?t:typeof t=="object"&&"raw"in t&&typeof t.raw=="string"?t.raw:String(t)}function $(t){return t.replace(/\s+/g," ").trim()}function S(t){return typeof t=="object"&&t!==null&&"$ref"in t}function P(t){return S(t)?null:t}function q(t){try{return JSON.stringify(t)}catch{return String(t)}}function U(t){let e=`${t.name} (${t.in}`;return t.required&&(e+=", required"),t.type&&(e+=`, ${t.type}`),t.format&&(e+=`, format: ${t.format}`),t.enum&&(e+=`, enum: [${t.enum.join(",")}]`),t.pattern&&(e+=`, pattern: ${t.pattern}`),e+=")",e}function F(t){return t.type?Array.isArray(t.type)?t.type.join("|"):t.type:t.oneOf?"oneOf":t.anyOf?"anyOf":t.allOf?"allOf":"object"}function te(t){return t==="querystring"?"query":t==="query"||t==="header"||t==="path"||t==="cookie"?t:"query"}function ne(t){const e=t.schema&&!S(t.schema)?t.schema:null,n={name:t.name,in:te(t.in),required:t.required??!1};return e&&(n.type=F(e),e.format&&(n.format=e.format),e.enum&&(n.enum=e.enum.map(String)),e.pattern&&(n.pattern=e.pattern),e.example!==void 0&&(n.example=String(e.example))),t.description&&(n.description=g(t.description)),t.example!==void 0&&!n.example&&(n.example=String(t.example)),n}function ie(t,e){const n=new Set,o=[],s=i=>{for(const r of i){const c=P(r);if(!c||!c.name)continue;const a=`${c.in}:${c.name}`;n.has(a)||(n.add(a),o.push(ne(c)))}};return t.parameters&&s(t.parameters),e.parameters&&s(e.parameters),o}function L(t,e=2,n=0){if(n>=e||!t.properties)return[];const o=new Set(t.required??[]);return Object.entries(t.properties).map(([s,i])=>({name:s,type:F(i),required:o.has(s),readOnly:i.readOnly}))}function G(t){const e=t.components?.securitySchemes;if(!e)return[];const n=[];for(const[o,s]of Object.entries(e)){const i=P(s);i&&n.push(oe(o,i))}return n}function oe(t,e){const n={schemeName:t,type:e.type};if(e.in&&(n.in=e.in),e.name&&(n.name=e.name),e.scheme&&(n.scheme=e.scheme),e.bearerFormat&&(n.bearerFormat=e.bearerFormat),e.flows){const o=Object.keys(e.flows).filter(i=>e.flows[i]);o.length>0&&(n.flows=o.join(", "));const s=new Set;for(const i of o){const r=e.flows[i];r?.scopes&&Object.keys(r.scopes).forEach(c=>s.add(c))}s.size>0&&(n.scopes=[...s].join(", "))}return n}function se(t,e,n){const o=t??e;if(!o||n.length===0)return[];const s=new Set;for(const i of o)for(const r of Object.keys(i))s.add(r);return n.filter(i=>s.has(i.schemeName))}function re(t){return t.length===0?"":`Security: ${t.map(n=>{let o=`${n.schemeName} (${n.type}`;return n.scheme&&(o+=`, ${n.scheme}`),n.in&&n.name&&(o+=`, ${n.name} in ${n.in}`),o+=")",o}).join("; ")}.`}const ce=["get","put","post","delete","options","head","patch","trace"],ae=["query","x-query"];function le(t,e){const n=[],o=Object.keys(t.content??{});if(o.length===0)return{textPart:"",schemaJson:"{}",examples:n};const s=o.find(u=>u.includes("json"))??o[0],i=t.content?.[s],r=i?.schema&&!S(i.schema)?i.schema:null,a=(r?L(r):[]).filter(u=>!e.hideReadOnly||!u.readOnly),p=t.required?"required":"optional";let l=`Request body (${s}, ${p})`;if(a.length>0){const u=a.map(f=>`${f.name}: ${f.type}${f.required?" required":""}${f.readOnly?" readOnly":""}`);l+=`: {${u.join(", ")}}`}return i?.example!==void 0&&n.push(q(i.example)),{textPart:l,schemaJson:JSON.stringify(a),examples:n}}function de(t){const e=[],n=[];for(const[o,s]of Object.entries(t)){if(S(s))continue;const i=g(s.description??"");e.push(`${o} ${i}`.trim());const r={statusCode:o};i&&(r.description=i);const c=s.content;if(c){const a=Object.keys(c).find(l=>l.includes("json"))??Object.keys(c)[0],p=c[a]?.schema;if(p&&!S(p)){const l=L(p);l.length>0&&(r.schemaProperties=JSON.stringify(l))}}n.push(r)}return{textParts:e,summaries:n}}function D(t){const{apiId:e,apiTitle:n,path:o,method:s,op:i,pathItem:r,globalSchemes:c,apiSecurity:a}=t,p=i.summary??"",l=g(i.description??""),u=i.operationId??"",f=i.tags??[],m=s.toUpperCase(),I=ie(i,r),h=se(i.security,a,c),y=h.length>0?h.map(v=>`api_sec:${e}:${v.schemeName}`):void 0,x=[n,`${m} ${o}`,p,l];u&&x.push(`operationId: ${u}`),f.length>0&&x.push(`Tags: ${f.join(", ")}`),i.deprecated&&x.push("DEPRECATED"),I.length>0&&x.push(`Parameters: ${I.map(U).join(". ")}.`);let A;const _=[],B=i.requestBody;if(B){const v=P(B);if(v){const b=le(v,{hideReadOnly:m==="POST"||m==="PUT"||m==="PATCH"});b.textPart&&x.push(b.textPart),A=b.schemaJson,_.push(...b.examples)}}const{textParts:C,summaries:E}=de(i.responses??{});C.length>0&&x.push(`Responses: ${C.join(", ")}.`);const R=re(h);R&&x.push(R);const M=`api_op:${e}:${o}:${s}:${u||`${o}-${s}`}`,V={type:"api_operation",id:M,contentHash:"",title:p||`${m} ${o}`,description:l||void 0,apiId:e,path:o,method:m,operationId:u||void 0,tags:f.length>0?f:void 0,deprecated:i.deprecated||void 0,parameterDetails:I.length>0?I:void 0,requestBodySchema:A,responseSchemas:E.length>0?E:void 0,securitySchemeRefs:y,examples:_.length>0?_:void 0};return{id:M,text:$(x.filter(Boolean).join(" ")),payload:V}}function W(t){const e=t.info?.title??"Untitled API",n=g(t.info?.description??t.info?.summary??""),o=t.id;return{id:`api:${o}`,text:$([e,n].filter(Boolean).join(" ")),payload:{type:"api",id:`api:${o}`,contentHash:"",title:e,description:n||void 0,apiId:o}}}function T(t){const e=[];for(const n of t){e.push(W(n));const o=n.info?.title??"Untitled API",s=n.id,i=G(n);for(const c of i){const a=`api_sec:${s}:${c.schemeName}`,p=[`${c.schemeName}: type=${c.type}`,c.scheme?`scheme=${c.scheme}`:"",c.in&&c.name?`${c.name} in ${c.in}`:"",c.bearerFormat?`format=${c.bearerFormat}`:"",c.flows?`flows=[${c.flows}]`:"",c.scopes?`scopes=[${c.scopes}]`:""].filter(Boolean).join(" ");e.push({id:a,text:$(`${o} Authentication. ${c.schemeName}. ${p}.`),payload:{type:"api_security",id:a,contentHash:"",title:`${o} — ${c.schemeName}`,apiId:s,securityScheme:c}})}const r=n.paths??{};for(const[c,a]of Object.entries(r)){if(!a||typeof a!="object")continue;const p=[...ce.filter(u=>u in a),...ae.filter(u=>u in a)];for(const u of p){const f=a[u];!f||typeof f!="object"||e.push(D({apiId:s,apiTitle:o,path:c,method:u,op:f,pathItem:a,globalSchemes:i,apiSecurity:n.security}))}const l=a.additionalOperations;if(l&&typeof l=="object")for(const[u,f]of Object.entries(l))!f||typeof f!="object"||e.push(D({apiId:s,apiTitle:o,path:c,method:u,op:f,pathItem:a,globalSchemes:i,apiSecurity:n.security}))}}return e}function ue(t){const e=[],n=[{list:t.queryParameters,loc:"query"},{list:t.headers,loc:"header"},{list:t.cookies,loc:"cookie"},{list:t.pathParameters,loc:"path"}];for(const{list:o,loc:s}of n)for(const i of o)if("key"in i){const r=i;e.push({name:r.key,in:s,required:!1})}return e}function Q(t){const e=t.id,n=t.info?.title??"Untitled Collection",o=g(t.info?.description??t.info?.summary??"");return{id:`collection:${e}`,text:$([n,o].filter(Boolean).join(" ")),payload:{type:"collection",id:`collection:${e}`,contentHash:"",title:n,description:o||void 0,collectionId:e}}}function X(t){const{collectionId:e,collectionTitle:n,workflow:o}=t,s=o.workflowId??"",i=o.summary??s,r=g(o.description??""),c=[n,i,r];if(o.inputs&&c.push(`Inputs schema: ${q(o.inputs)}`),o.outputs?.length){const a=o.outputs.map(p=>p.key).filter(Boolean);a.length&&c.push(`Outputs: ${a.join(", ")}`)}return o.dependsOn?.length&&c.push(`Depends on: ${o.dependsOn.join(", ")}`),{id:`workflow:${e}:${s}`,text:$(c.filter(Boolean).join(" ")),payload:{type:"workflow",id:`workflow:${e}:${s}`,contentHash:"",title:i,description:r||void 0,collectionId:e,workflowId:s}}}function K(t){const{collectionId:e,collectionTitle:n,workflowId:o,workflowTitle:s,step:i}=t,r=i.stepId??"",c=g(i.description??""),a=i.operation,p=i.xOperation,l=[n,s,`step: ${r}`];c&&l.push(c),a?(l.push(`${a.method?.toUpperCase()} ${a.path}`),a.apiId&&l.push(`API: ${a.apiId}`),a.operationId&&l.push(`operationId: ${a.operationId}`)):p&&l.push(`${p.method?.toUpperCase()} ${p.url}`);const u=i.parameters?ue(i.parameters):[];u.length>0&&l.push(`Parameters: ${u.map(U).join(". ")}.`),i.requestBody?.type&&l.push(`Request body type: ${i.requestBody.type}`);const m=(i.successCriteria??[]).map(h=>{let y=h.condition;return h.context&&(y+=` context: ${h.context}`),h.type&&(y+=` (${h.type})`),y});if(m.length>0&&l.push(`Success criteria: ${m.join("; ")}`),i.outputs?.length){const h=i.outputs.map(y=>`${y.key}=${y.value}`).filter(Boolean);h.length&&l.push(`Outputs: ${h.join(", ")}`)}const I=`step:${e}:${o}:${r}`;return{id:I,text:$(l.filter(Boolean).join(" ")),payload:{type:"step",id:I,contentHash:"",title:r,description:c||void 0,collectionId:e,workflowId:o,stepId:r,path:a?.path??p?.url,method:(a?.method??p?.method)?.toUpperCase(),apiId:a?.apiId,operationId:a?.operationId,parameterDetails:u.length>0?u:void 0,successCriteria:m.length>0?m:void 0,requestBodySchema:i.requestBody?.type?q(i.requestBody):void 0}}}function j(t){const e=[];for(const n of t){const o=n.id,s=n.info?.title??"Untitled Collection";e.push(Q(n));for(const i of n.workflows??[]){e.push(X({collectionId:o,collectionTitle:s,workflow:i}));const r=i.workflowId??"",c=i.summary??r;for(const a of i.steps??[])e.push(K({collectionId:o,collectionTitle:s,workflowId:r,workflowTitle:c,step:a}))}}return e}function Y(t,e){return[...T(t),...j(e)]}const N=10,pe=4;function H(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n)|0;return e>>>0}function fe(t){return d.bytesToHex(d.md5(t))}const he={};class me extends J.Observable{constructor(e){super(),this.collectionName=e}collectionName;activeIndexJobs=0;getIndexingActivityState(){return{inProgress:this.activeIndexJobs>0}}beginIndexJob(){this.activeIndexJobs++,this.activeIndexJobs===1&&this.emit("indexing-activity",{inProgress:!0})}endIndexJob(){this.activeIndexJobs=Math.max(0,this.activeIndexJobs-1),this.activeIndexJobs===0&&this.emit("indexing-activity",{inProgress:!1})}async getIdsByPayload(e,n){return d.invoke("semantic_search_get_ids_by_payload",{collectionName:this.collectionName,field:e,value:n})}async getAllIds(){return d.invoke("semantic_search_get_all_ids",{collectionName:this.collectionName})}async getScopeHashes(e){const n=e.apiIds??[],o=e.collectionIds??[];let s;if(n.length===0&&o.length===0)s=await this.getAllIds();else{const r=[];for(const a of n)r.push(this.getIdsByPayload("apiId",a));for(const a of o)r.push(this.getIdsByPayload("collectionId",a));s=(await Promise.all(r)).flat()}const i=new Map;for(const r of s)i.set(r.id,r.contentHash);return i}async indexDocuments(e,n){if(e.length===0&&!n)return{added:0,updated:0,removed:0,unchanged:0};const o=await this.getScopeHashes(n??{}),s=[],i=new Set;let r=0,c=0;for(const l of e){const u=fe(l.text);l.payload.contentHash=u,i.add(l.id);const f=o.get(l.id);f===u?c++:(f||r++,s.push(l))}const a=s.length-r,p=[];for(const l of o.keys())i.has(l)||p.push(l);if(p.length>0||s.length>0){this.beginIndexJob();try{p.length>0&&await this.deletePoints(p.map(H)),s.length>0&&await this.embedAndUpsert(s),await this.flush()}finally{this.endIndexJob()}}return{added:r,updated:a,removed:p.length,unchanged:c}}async removeByPayloadFilter(e,n){return d.invoke("semantic_search_delete_by_payload",{collectionName:this.collectionName,field:e,value:n})}async getStoredDocumentCount(){try{return(await d.invoke("plugin:velesdb|list_collections"))?.find(o=>o.name===this.collectionName)?.count??0}catch{return 0}}async getDocumentsByIds(e){if(e.length===0)return new Map;const n=e.map(H),o=await d.invoke("plugin:velesdb|get_points",{request:{collection:this.collectionName,ids:n}}),s=new Map;for(const i of o??[])if(i?.payload){const r=i.payload;r.id&&s.set(r.id,r)}return s}async embedAndUpsert(e){const n=[],o=e.length;for(let s=0;s<o;s+=N)n.push({docs:e.slice(s,s+N),index:Math.floor(s/N)});await ee.promiseMapLimit(n,pe,async s=>{const i=s.docs.map(r=>({id:r.id,text:r.text||r.payload.title,payload:r.payload}));await d.invoke("semantic_search_embed_and_upsert",{collectionName:this.collectionName,documents:i})})}async deletePoints(e){e.length!==0&&await d.invoke("plugin:velesdb|delete_points",{request:{collection:this.collectionName,ids:e}})}async flush(){await d.invoke("plugin:velesdb|flush",{name:this.collectionName}),await d.invoke("semantic_search_write_hnsw_marker",{collectionName:this.collectionName}).catch(()=>{})}}const z="replay_search",ye=384,w={added:0,updated:0,removed:0,unchanged:0};function k(t){return t.added+t.updated>0}class Z extends J.Observable{initialized=!1;projectId=null;indexer=null;indexQueue=Promise.resolve();get collectionName(){return this.projectId?`${z}_${this.projectId}`:z}createIndexer(){const e=new me(this.collectionName);return e.subscribe("indexing-activity",n=>{this.emit("indexing-activity",n)}),e}getIndexer(){return this.indexer||(this.indexer=this.createIndexer()),this.indexer}getIndexingActivityState(){return this.getIndexer().getIndexingActivityState()}async ensureInitialized(){this.initialized||await this.init()}enqueueIndex(e,n){const s=this.indexQueue.then(()=>e()).then(async i=>(n(i)&&await this.unloadModel(),i)).catch(async i=>{throw console.error("Semantic index:",i),await this.unloadModel(),i});return this.indexQueue=s.catch(()=>{}),s}async unloadModel(){try{await d.invoke("semantic_search_unload_model")}catch{}}setProject(e){this.projectId!==e&&(this.projectId=e,this.initialized=!1,this.indexer=this.createIndexer())}async init(){if(d.isTauriApp()&&!this.initialized){try{if((await d.invoke("plugin:velesdb|list_collections"))?.some(n=>n.name===this.collectionName)){this.initialized=!0;return}}catch{}await d.invoke("plugin:velesdb|create_collection",{request:{name:this.collectionName,dimension:ye,metric:"cosine",storage_mode:"full"}}),this.initialized=!0}}async indexApis(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer(),s=T(e),i={apiIds:e.map(r=>r.id)};return await this.ensureInitialized(),this.enqueueIndex(async()=>this.collectionName!==n?w:o.indexDocuments(s,i),k)}async indexCollections(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer(),s=j(e),i={collectionIds:e.map(r=>r.id)};return await this.ensureInitialized(),this.enqueueIndex(async()=>this.collectionName!==n?w:o.indexDocuments(s,i),k)}async removeApi(e){if(!d.isTauriApp())return;const n=this.getIndexer();await this.ensureInitialized(),await this.enqueueIndex(()=>n.removeByPayloadFilter("apiId",e),()=>!1)}async removeCollection(e){if(!d.isTauriApp())return;const n=this.getIndexer();await this.ensureInitialized(),await this.enqueueIndex(()=>n.removeByPayloadFilter("collectionId",e),()=>!1)}async reindex(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer();return await this.ensureInitialized(),this.enqueueIndex(async()=>{if(this.collectionName!==n)return w;const{apis:s,collections:i}=e(),r=Y(s,i);return o.indexDocuments(r,he)},k)}async search(e,n=10,o){if(!d.isTauriApp())return[];try{await this.ensureInitialized();const s=o&&Object.keys(o).length>0?{type:o.type,apiId:o.apiId,collectionId:o.collectionId,path:o.path,method:o.method,operationId:o.operationId,workflowId:o.workflowId,stepId:o.stepId}:void 0,r=((await d.invoke("semantic_search_text",{collection:this.collectionName,query:e,topK:n,filters:s})).results??[]).map(c=>({...c.payload,score:c.score??0}));return await this.enrichWithRelatedSecurity(r),r}catch{return[]}}async enrichWithRelatedSecurity(e){const n=e.filter(i=>i.type==="api_operation"&&i.securitySchemeRefs?.length);if(n.length===0)return;const o=[...new Set(n.flatMap(i=>i.securitySchemeRefs??[]))],s=await this.getIndexer().getDocumentsByIds(o);for(const i of n){const r=[];for(const c of i.securitySchemeRefs??[]){const a=s.get(c);a?.securityScheme&&r.push(a.securityScheme)}r.length>0&&(i.relatedSecuritySchemes=r)}}async status(){if(!d.isTauriApp())return{indexed:0,modelLoaded:!1};const e=await this.getIndexer().getStoredDocumentCount();let n=!1;try{n=(await d.invoke("semantic_search_model_status")).loaded}catch{}return{indexed:e,modelLoaded:n}}async clear(){if(!(!d.isTauriApp()||!this.initialized))try{await d.invoke("plugin:velesdb|delete_collection",{name:this.collectionName}),this.initialized=!1}catch{}}async preloadModel(){if(d.isTauriApp())try{await d.invoke("semantic_search_preload_model")}catch{}}}let O=null;function xe(){return O||(O=new Z),O}exports.SemanticSearchService=Z;exports.extractAllDocuments=Y;exports.extractApiDocument=W;exports.extractApiDocuments=T;exports.extractCollectionDocument=Q;exports.extractCollectionDocuments=j;exports.extractGlobalSecuritySchemes=G;exports.extractOperationDocument=D;exports.extractStepDocument=K;exports.extractWorkflowDocument=X;exports.getSemanticSearchService=xe;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./replay-index-DbWKCsKW.js"),c=require("./replay-Observable-bjJ6wkRB.js"),o=new Set(["node_modules"]);class l extends c.Observable{constructor(e){super(),this.baseDir=e,this.initializeDirectory(e)}baseDir;writeExcludedKeys=new Set;writeEndTimers=new Map;async initializeDirectory(e){await s.mkdir(e,{recursive:!0})}setWriteExcludedKeys(e){this.writeExcludedKeys=e}async ls(e){const t=await this.getFullPath(e);return this.getDirEntryFilesRecursively(t)}async getDirEntryFilesRecursively(e){try{const t=[],i=await s.readDir(e);for(const r of i)if(r.isDirectory){if(o.has(r.name))continue;const n=await s.join(e,r.name),a=await this.getDirEntryFilesRecursively(n);t.push(...a)}else{const n=await s.join(e,r.name),a=await s.PathUtils.relative(this.baseDir,n);t.push(a)}return t}catch(t){return t.includes("forbidden path")||console.error(t),[]}}async get(e){const t=await this.getFullPath(e);try{return await s.readTextFile(t)}catch(i){return!i.includes("No such file or directory")&&!i.includes("forbidden path")&&console.error(i),null}}async has(e){const t=await this.getFullPath(e);return await s.exists(t)}async set(e,t){if(!this.writeExcludedKeys.has(e)){this.emit("write-start",e);try{const i=await this.getFullPath(e),r=s.sep(),n=i.split(r).slice(0,-1).join(r);await s.mkdir(n,{recursive:!0}),await s.writeTextFile(i,t)}finally{const i=this.writeEndTimers.get(e);i&&clearTimeout(i);const r=setTimeout(()=>{this.emit("write-end",e),this.writeEndTimers.delete(e)},1e3);this.writeEndTimers.set(e,r)}}}async remove(e){if(!this.writeExcludedKeys.has(e)){this.emit("write-start",e);try{const t=await this.getFullPath(e);await s.remove(t)}catch(t){!t.includes("No such file or directory")&&!t.includes("forbidden path")&&console.error(t)}finally{const t=this.writeEndTimers.get(e);t&&clearTimeout(t);const i=setTimeout(()=>{this.emit("write-end",e),this.writeEndTimers.delete(e)},1e3);this.writeEndTimers.set(e,i)}}}async rename(e,t){const i=await this.getFullPath(e),r=await this.getFullPath(t);await s.rename(i,r)}async getFullPath(e){return await s.join(this.baseDir,e??"")}}exports.TauriFileSystemAdapter=l;
@@ -1,99 +0,0 @@
1
- import { W as c, X as o, Y as n, P as l, Z as u, _ as h, $ as d, a0 as w, a1 as m, a2 as y } from "./replay-index-F4GEOEUz.js";
2
- import { O as f } from "./replay-Observable-D6wKbFwB.js";
3
- const E = /* @__PURE__ */ new Set(["node_modules"]);
4
- class p extends f {
5
- constructor(t) {
6
- super(), this.baseDir = t, this.initializeDirectory(t);
7
- }
8
- baseDir;
9
- writeExcludedKeys = /* @__PURE__ */ new Set();
10
- writeEndTimers = /* @__PURE__ */ new Map();
11
- async initializeDirectory(t) {
12
- await c(t, {
13
- recursive: !0
14
- });
15
- }
16
- setWriteExcludedKeys(t) {
17
- this.writeExcludedKeys = t;
18
- }
19
- async ls(t) {
20
- const e = await this.getFullPath(t);
21
- return this.getDirEntryFilesRecursively(e);
22
- }
23
- async getDirEntryFilesRecursively(t) {
24
- try {
25
- const e = [], i = await o(t);
26
- for (const s of i)
27
- if (s.isDirectory) {
28
- if (E.has(s.name))
29
- continue;
30
- const r = await n(t, s.name), a = await this.getDirEntryFilesRecursively(r);
31
- e.push(...a);
32
- } else {
33
- const r = await n(t, s.name), a = await l.relative(this.baseDir, r);
34
- e.push(a);
35
- }
36
- return e;
37
- } catch (e) {
38
- return e.includes("forbidden path") || console.error(e), [];
39
- }
40
- }
41
- async get(t) {
42
- const e = await this.getFullPath(t);
43
- try {
44
- return await u(e);
45
- } catch (i) {
46
- return !i.includes("No such file or directory") && !i.includes("forbidden path") && console.error(i), null;
47
- }
48
- }
49
- async has(t) {
50
- const e = await this.getFullPath(t);
51
- return await h(e);
52
- }
53
- async set(t, e) {
54
- if (!this.writeExcludedKeys.has(t)) {
55
- this.emit("write-start", t);
56
- try {
57
- const i = await this.getFullPath(t), s = d(), r = i.split(s).slice(0, -1).join(s);
58
- await c(r, {
59
- recursive: !0
60
- }), await w(i, e);
61
- } finally {
62
- const i = this.writeEndTimers.get(t);
63
- i && clearTimeout(i);
64
- const s = setTimeout(() => {
65
- this.emit("write-end", t), this.writeEndTimers.delete(t);
66
- }, 1e3);
67
- this.writeEndTimers.set(t, s);
68
- }
69
- }
70
- }
71
- async remove(t) {
72
- if (!this.writeExcludedKeys.has(t)) {
73
- this.emit("write-start", t);
74
- try {
75
- const e = await this.getFullPath(t);
76
- await m(e);
77
- } catch (e) {
78
- !e.includes("No such file or directory") && !e.includes("forbidden path") && console.error(e);
79
- } finally {
80
- const e = this.writeEndTimers.get(t);
81
- e && clearTimeout(e);
82
- const i = setTimeout(() => {
83
- this.emit("write-end", t), this.writeEndTimers.delete(t);
84
- }, 1e3);
85
- this.writeEndTimers.set(t, i);
86
- }
87
- }
88
- }
89
- async rename(t, e) {
90
- const i = await this.getFullPath(t), s = await this.getFullPath(e);
91
- await y(i, s);
92
- }
93
- async getFullPath(t) {
94
- return await n(this.baseDir, t ?? "");
95
- }
96
- }
97
- export {
98
- p as TauriFileSystemAdapter
99
- };
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./replay-index-DbWKCsKW.js"),Y=require("./replay-promise-map-limit-DRDkHc-b.js"),G=require("./replay-TauriFileSystemAdapter-BLPH1Vx3.js");var U={exports:{}},V;function oe(){return V||(V=1,(function(s){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function n(a,u,f){this.fn=a,this.context=u,this.once=f||!1}function o(a,u,f,l,g){if(typeof f!="function")throw new TypeError("The listener must be a function");var y=new n(f,l||a,g),m=t?t+u:u;return a._events[m]?a._events[m].fn?a._events[m]=[a._events[m],y]:a._events[m].push(y):(a._events[m]=y,a._eventsCount++),a}function d(a,u){--a._eventsCount===0?a._events=new r:delete a._events[u]}function h(){this._events=new r,this._eventsCount=0}h.prototype.eventNames=function(){var u=[],f,l;if(this._eventsCount===0)return u;for(l in f=this._events)e.call(f,l)&&u.push(t?l.slice(1):l);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(f)):u},h.prototype.listeners=function(u){var f=t?t+u:u,l=this._events[f];if(!l)return[];if(l.fn)return[l.fn];for(var g=0,y=l.length,m=new Array(y);g<y;g++)m[g]=l[g].fn;return m},h.prototype.listenerCount=function(u){var f=t?t+u:u,l=this._events[f];return l?l.fn?1:l.length:0},h.prototype.emit=function(u,f,l,g,y,m){var b=t?t+u:u;if(!this._events[b])return!1;var c=this._events[b],T=arguments.length,Q,w;if(c.fn){switch(c.once&&this.removeListener(u,c.fn,void 0,!0),T){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,f),!0;case 3:return c.fn.call(c.context,f,l),!0;case 4:return c.fn.call(c.context,f,l,g),!0;case 5:return c.fn.call(c.context,f,l,g,y),!0;case 6:return c.fn.call(c.context,f,l,g,y,m),!0}for(w=1,Q=new Array(T-1);w<T;w++)Q[w-1]=arguments[w];c.fn.apply(c.context,Q)}else{var ae=c.length,x;for(w=0;w<ae;w++)switch(c[w].once&&this.removeListener(u,c[w].fn,void 0,!0),T){case 1:c[w].fn.call(c[w].context);break;case 2:c[w].fn.call(c[w].context,f);break;case 3:c[w].fn.call(c[w].context,f,l);break;case 4:c[w].fn.call(c[w].context,f,l,g);break;default:if(!Q)for(x=1,Q=new Array(T-1);x<T;x++)Q[x-1]=arguments[x];c[w].fn.apply(c[w].context,Q)}}return!0},h.prototype.on=function(u,f,l){return o(this,u,f,l,!1)},h.prototype.once=function(u,f,l){return o(this,u,f,l,!0)},h.prototype.removeListener=function(u,f,l,g){var y=t?t+u:u;if(!this._events[y])return this;if(!f)return d(this,y),this;var m=this._events[y];if(m.fn)m.fn===f&&(!g||m.once)&&(!l||m.context===l)&&d(this,y);else{for(var b=0,c=[],T=m.length;b<T;b++)(m[b].fn!==f||g&&!m[b].once||l&&m[b].context!==l)&&c.push(m[b]);c.length?this._events[y]=c.length===1?c[0]:c:d(this,y)}return this},h.prototype.removeAllListeners=function(u){var f;return u?(f=t?t+u:u,this._events[f]&&d(this,f)):(this._events=new r,this._eventsCount=0),this},h.prototype.off=h.prototype.removeListener,h.prototype.addListener=h.prototype.on,h.prefixed=t,h.EventEmitter=h,s.exports=h})(U)),U.exports}var ue=oe();const le=p.getDefaultExportFromCjs(ue);class re extends Error{constructor(e){super(e),this.name="TimeoutError"}}let ce=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}};const J=s=>globalThis.DOMException===void 0?new ce(s):new DOMException(s),H=s=>{const e=s.reason===void 0?J("This operation was aborted."):s.reason;return e instanceof Error?e:J(e)};function he(s,e,t,r){let n;const o=new Promise((d,h)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){d(s);return}if(r={customTimers:{setTimeout,clearTimeout},...r},r.signal){const{signal:a}=r;a.aborted&&h(H(a)),a.addEventListener("abort",()=>{h(H(a))})}n=r.customTimers.setTimeout.call(void 0,()=>{const a=`Promise timed out after ${e} milliseconds`,u=t instanceof Error?t:new re(a);typeof s.cancel=="function"&&s.cancel(),h(u)},e),(async()=>{try{d(await s)}catch(a){h(a)}finally{r.customTimers.clearTimeout.call(void 0,n)}})()});return o.clear=()=>{clearTimeout(n),n=void 0},o}function fe(s,e,t){let r=0,n=s.length;for(;n>0;){const o=Math.trunc(n/2);let d=r+o;t(s[d],e)<=0?(r=++d,n-=o+1):n=o}return r}var F=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},A;class de{constructor(){A.set(this,[])}enqueue(e,t){t={priority:0,...t};const r={priority:t.priority,run:e};if(this.size&&F(this,A,"f")[this.size-1].priority>=t.priority){F(this,A,"f").push(r);return}const n=fe(F(this,A,"f"),r,(o,d)=>d.priority-o.priority);F(this,A,"f").splice(n,0,r)}dequeue(){const e=F(this,A,"f").shift();return e?.run}filter(e){return F(this,A,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return F(this,A,"f").length}}A=new WeakMap;var v=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},i=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},_,L,M,I,R,N,z,E,O,P,k,S,W,C,q,X,Z,ie,ee,te,D,B,K,$,se,j;class ne extends Error{}class pe extends le{constructor(e){var t,r,n,o;if(super(),_.add(this),L.set(this,void 0),M.set(this,void 0),I.set(this,0),R.set(this,void 0),N.set(this,void 0),z.set(this,0),E.set(this,void 0),O.set(this,void 0),P.set(this,void 0),k.set(this,void 0),S.set(this,0),W.set(this,void 0),C.set(this,void 0),q.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:de,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(r=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(o=(n=e.interval)===null||n===void 0?void 0:n.toString())!==null&&o!==void 0?o:""}\` (${typeof e.interval})`);v(this,L,e.carryoverConcurrencyCount,"f"),v(this,M,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),v(this,R,e.intervalCap,"f"),v(this,N,e.interval,"f"),v(this,P,new e.queueClass,"f"),v(this,k,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,v(this,q,e.throwOnTimeout===!0,"f"),v(this,C,e.autoStart===!1,"f")}get concurrency(){return i(this,W,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);v(this,W,e,"f"),i(this,_,"m",$).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:i(this,q,"f"),...t},new Promise((r,n)=>{i(this,P,"f").enqueue(async()=>{var o,d,h;v(this,S,(d=i(this,S,"f"),d++,d),"f"),v(this,I,(h=i(this,I,"f"),h++,h),"f");try{if(!((o=t.signal)===null||o===void 0)&&o.aborted)throw new ne("The task was aborted.");let a=e({signal:t.signal});t.timeout&&(a=he(Promise.resolve(a),t.timeout)),t.signal&&(a=Promise.race([a,i(this,_,"m",se).call(this,t.signal)]));const u=await a;r(u),this.emit("completed",u)}catch(a){if(a instanceof re&&!t.throwOnTimeout){r();return}n(a),this.emit("error",a)}finally{i(this,_,"m",ie).call(this)}},t),this.emit("add"),i(this,_,"m",D).call(this)})}async addAll(e,t){return Promise.all(e.map(async r=>this.add(r,t)))}start(){return i(this,C,"f")?(v(this,C,!1,"f"),i(this,_,"m",$).call(this),this):this}pause(){v(this,C,!0,"f")}clear(){v(this,P,new(i(this,k,"f")),"f")}async onEmpty(){i(this,P,"f").size!==0&&await i(this,_,"m",j).call(this,"empty")}async onSizeLessThan(e){i(this,P,"f").size<e||await i(this,_,"m",j).call(this,"next",()=>i(this,P,"f").size<e)}async onIdle(){i(this,S,"f")===0&&i(this,P,"f").size===0||await i(this,_,"m",j).call(this,"idle")}get size(){return i(this,P,"f").size}sizeBy(e){return i(this,P,"f").filter(e).length}get pending(){return i(this,S,"f")}get isPaused(){return i(this,C,"f")}}L=new WeakMap,M=new WeakMap,I=new WeakMap,R=new WeakMap,N=new WeakMap,z=new WeakMap,E=new WeakMap,O=new WeakMap,P=new WeakMap,k=new WeakMap,S=new WeakMap,W=new WeakMap,C=new WeakMap,q=new WeakMap,_=new WeakSet,X=function(){return i(this,M,"f")||i(this,I,"f")<i(this,R,"f")},Z=function(){return i(this,S,"f")<i(this,W,"f")},ie=function(){var e;v(this,S,(e=i(this,S,"f"),e--,e),"f"),i(this,_,"m",D).call(this),this.emit("next")},ee=function(){i(this,_,"m",K).call(this),i(this,_,"m",B).call(this),v(this,O,void 0,"f")},te=function(){const e=Date.now();if(i(this,E,"f")===void 0){const t=i(this,z,"f")-e;if(t<0)v(this,I,i(this,L,"f")?i(this,S,"f"):0,"f");else return i(this,O,"f")===void 0&&v(this,O,setTimeout(()=>{i(this,_,"m",ee).call(this)},t),"f"),!0}return!1},D=function(){if(i(this,P,"f").size===0)return i(this,E,"f")&&clearInterval(i(this,E,"f")),v(this,E,void 0,"f"),this.emit("empty"),i(this,S,"f")===0&&this.emit("idle"),!1;if(!i(this,C,"f")){const e=!i(this,_,"a",te);if(i(this,_,"a",X)&&i(this,_,"a",Z)){const t=i(this,P,"f").dequeue();return t?(this.emit("active"),t(),e&&i(this,_,"m",B).call(this),!0):!1}}return!1},B=function(){i(this,M,"f")||i(this,E,"f")!==void 0||(v(this,E,setInterval(()=>{i(this,_,"m",K).call(this)},i(this,N,"f")),"f"),v(this,z,Date.now()+i(this,N,"f"),"f"))},K=function(){i(this,I,"f")===0&&i(this,S,"f")===0&&i(this,E,"f")&&(clearInterval(i(this,E,"f")),v(this,E,void 0,"f")),v(this,I,i(this,L,"f")?i(this,S,"f"):0,"f"),i(this,_,"m",$).call(this)},$=function(){for(;i(this,_,"m",D).call(this););},se=async function(e){return new Promise((t,r)=>{e.addEventListener("abort",()=>{r(new ne("The task was aborted."))},{once:!0})})},j=async function(e,t){return new Promise(r=>{const n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)})};class me{constructor(e){this.apisStorage=e}apisStorage;data=new Map;loading=new Set;pQueue=new pe({concurrency:20});async get(e){return this.data.has(e)?this.data.get(e)??null:(await this.loadAndParse(e),this.data.get(e)??null)}async load(e,t=!1){this.data.has(e)&&!t||await this.loadAndParse(e,t)}async loadAndParse(e,t=!1){if(this.loading.has(e)){await this.pQueue.add(()=>this.get(e));return}t&&this.data.delete(e),this.loading.add(e),await this.pQueue.add(async()=>{const r=p.isWebUrl(e)?p.SourceType.WEB:p.SourceType.FS,n=r===p.SourceType.WEB?e:await this.apisStorage.getAbsolutePath(e);try{const{definition:o,fileDependencies:d}=await p.loadAndBundleDefinition(n);if(!o){this.data.set(e,null),await p.clearNotificationsForSource(e);return}const h=this.apisStorage.parse({uri:e,type:r,content:o});this.data.set(e,{...h,fileDependencies:d}),await p.clearNotificationsForSource(e)}catch(o){if(this.data.set(e,null),o instanceof Error&&(o.message.includes("Unsupported specification")||o.message.includes("File not found"))){await p.clearNotificationsForSource(e);return}console.info("Error loading api "+e,o),await p.reportParseError(e,o);return}}),this.loading.delete(e)}get size(){return this.data.size}delete(e){this.data.delete(e)}getAll(){return Array.from(this.data.values()).filter(e=>e!==null)}clear(){this.data.clear(),this.loading.clear()}}class ve extends p.RootStorage{apiLoader;constructor(e,t,r){const n=new G.TauriFileSystemAdapter(e.systemFilesDir),o=new G.TauriFileSystemAdapter(e.userFilesDir);super(n,o,e,!0,t,r),this.apiLoader=new me(this.apisStorage),this.setupWriteListeners(o)}setupWriteListeners(e){e.on("write-start",t=>{this.addWatchExcludedId(t)}),e.on("write-end",t=>{this.removeWatchExcludedId(t)})}async read(){const e=this.telemetry?.startSpan("com.redocly.storage.read",[p.createResource("storageOperation","read","storage")],void 0),t=this.telemetry?.startSpan("com.redocly.storage.loadUserState",[p.createResource("storageOperation","loadUserState","storage")],e?.parentCtx),[r,n,o]=await Promise.all([this.activeEnvironmentIdStorage.read(),this.tabsStateStorage.read(),this.environmentsStorage.read()]);t?.setAttribute("status","completed"),t?.setAttribute("environmentCount",o.length),t?.setStatus(p.SpanStatusCode.OK),t?.end();const{apiFiles:d,collectionFiles:h}=await this.detectProjectFiles(e);await this.loadAndParseApis(d,e);const u=(await this.loadAndParseCollections(h,e)).filter(l=>l!==null);this.collectionsStorage.setItemIds(u.map(l=>l.id));const f=this.apiLoader.getAll();return this.apisStorage.setItemIds(f.map(l=>l.id)),e?.setAttribute("status","completed"),e?.setStatus(p.SpanStatusCode.OK),e?.end(),{project:this.project,activeEnvironmentId:r,tabsState:n,environments:o,apis:f,collections:u}}async detectProjectFiles(e){const t=this.telemetry?.startSpan("com.redocly.storage.detectFiles",[p.createResource("storageOperation","detectFiles","storage")],e?.parentCtx),{api_files:r,collection_files:n}=await p.invoke("fs_scan",{dir:this.project.userFilesDir});return t?.setAttribute("status","completed"),t?.setAttribute("filesCount",r.length+n.length),t?.setAttribute("apiFilesCount",r.length),t?.setAttribute("collectionFilesCount",n.length),t?.setStatus(p.SpanStatusCode.OK),t?.end(),{apiFiles:r,collectionFiles:n}}readEnviroments(){return this.environmentsStorage.read()}deleteApiFromCache(e){this.apiLoader.delete(e)}async loadAndParseApis(e,t,r=!1){const n=this.telemetry?.startSpan("com.redocly.storage.parseApis",[{...p.createResource("storageOperation","parseApis","storage"),apisCount:e.length}],t?.parentCtx),o=await Y.promiseMapLimit(e,20,async d=>{try{return await this.apiLoader.load(d.relative_path,r),this.apiLoader.get(d.relative_path)}catch(h){return console.info(`Error parsing YAML/JSON file ${d.absolute_path}:`,h),await p.reportParseError(d.relative_path,h),null}});return n?.setAttribute("status","completed"),n?.setAttribute("parsedApisCount",this.apiLoader.size),n?.setStatus(p.SpanStatusCode.OK),n?.end(),o}async loadAndParseCollections(e,t){const r=this.telemetry?.startSpan("com.redocly.storage.parseCollections",[{...p.createResource("storageOperation","parseCollections","storage"),collectionsCount:e.length}],t?.parentCtx),n=await Y.promiseMapLimit(e,20,async o=>{try{const d=await this.userFilesStorage.get(o.relative_path);if(!d)return null;const h=p.yaml.load(d);if(typeof h!="object"||h===null||typeof h.arazzo!="string")return await p.clearNotificationsForSource(o.relative_path),null;const a=[];await Promise.all(h.sourceDescriptions?.map(async l=>{const g=l.type,y=l.url,m=!g||g==="openapi",b=await p.apiUrlToApiId({projectPath:this.project.userFilesDir,apiUrl:y,collectionId:o.relative_path});if(m){const c=await this.apiLoader.get(b);c&&a.push(c)}}));const u=await p.PathUtils.join(this.project.userFilesDir,o.relative_path),f=await this.collectionsStorage.parse({uri:o.relative_path,type:p.SourceType.FS,content:h,fileDependencies:new Set([u])},a);return await p.clearNotificationsForSource(o.relative_path),f}catch(d){return console.info(`Error parsing Arazzo file ${o.relative_path}:`,d),await p.reportParseError(o.relative_path,d),null}});return r?.setAttribute("status","completed"),r?.setAttribute("parsedCollectionsCount",n.length),r?.setStatus(p.SpanStatusCode.OK),r?.end(),n}}exports.TauriRootStorage=ve;