@redocly/replay 0.29.0-next.2 → 0.29.0-next.3

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 (59) hide show
  1. package/dist/{replay-AiChatProvider-CRI2UTsZ.js → replay-AiChatProvider-Bnz0LDFD.js} +52 -52
  2. package/dist/{replay-AiChatProvider-6XfGmlMO.js → replay-AiChatProvider-C5p3nTV1.js} +1 -1
  3. package/dist/{replay-AiChatSqliteDBStorage-DA-eJh6c.js → replay-AiChatSqliteDBStorage-DYxoSZak.js} +1 -1
  4. package/dist/{replay-AiChatSqliteDBStorage-BlEocJgY.js → replay-AiChatSqliteDBStorage-Dfbp6Mt_.js} +1 -1
  5. package/dist/{replay-AiPanel-DYVgRVdG.js → replay-AiPanel-BSg5Bap4.js} +1 -1
  6. package/dist/{replay-AiPanel-ZrR1tDqo.js → replay-AiPanel-C0E1A47H.js} +4 -4
  7. package/dist/{replay-FileWatcher-BNFHO596.js → replay-FileWatcher-Ba9Ob_Sy.js} +1 -1
  8. package/dist/{replay-FileWatcher-CELEsith.js → replay-FileWatcher-BiAGOR1Z.js} +2 -2
  9. package/dist/{replay-SemanticSearchService-Dooeje9n.js → replay-SemanticSearchService-IInvoSoP.js} +1 -1
  10. package/dist/{replay-SemanticSearchService-BEk_dTbd.js → replay-SemanticSearchService-sIjG5Wxe.js} +20 -20
  11. package/dist/{replay-SqliteDBStorage-CLSBc7bS.js → replay-SqliteDBStorage-C-ovuJna.js} +1 -1
  12. package/dist/{replay-SqliteDBStorage-3K7IPlJU.js → replay-SqliteDBStorage-DMoeVRXU.js} +1 -1
  13. package/dist/{replay-TauriFileSystemAdapter-D-IrcgXM.js → replay-TauriFileSystemAdapter-CB9S1PNT.js} +1 -1
  14. package/dist/{replay-TauriFileSystemAdapter-BvJ1azsj.js → replay-TauriFileSystemAdapter-DDo2h7gX.js} +1 -1
  15. package/dist/{replay-TauriRootStorage-DylcqkvS.js → replay-TauriRootStorage-BX-XrEN-.js} +1 -1
  16. package/dist/{replay-TauriRootStorage-b3tjVs4a.js → replay-TauriRootStorage-CR1PyBgZ.js} +12 -12
  17. package/dist/{replay-agent-loop-Dev3mG-o.js → replay-agent-loop-4YtdgkDh.js} +5 -5
  18. package/dist/{replay-agent-loop-DgP7lcS9.js → replay-agent-loop-BmoYEhOB.js} +1 -1
  19. package/dist/{replay-ai-chat-mappers-B6nh9aAX.js → replay-ai-chat-mappers-42FEVsfw.js} +1 -1
  20. package/dist/{replay-ai-chat-mappers-f3kvLmAu.js → replay-ai-chat-mappers-CgjhiNr7.js} +1 -1
  21. package/dist/{replay-create-model-CKCKpcry.js → replay-create-model-4Yknbfme.js} +3 -3
  22. package/dist/{replay-create-model-DWPoobaj.js → replay-create-model-kF4veQPK.js} +4 -4
  23. package/dist/{replay-db-C5zt3C9P.js → replay-db-B3tQE-B9.js} +6 -6
  24. package/dist/{replay-db-B6aY7_xq.js → replay-db-_hwn1n5t.js} +1 -1
  25. package/dist/{replay-external-resolver-vQRj5DBT.js → replay-external-resolver-DS7qAi0G.js} +2 -2
  26. package/dist/{replay-external-resolver-CnBhw18p.js → replay-external-resolver-DX5JrdGB.js} +1 -1
  27. package/dist/replay-index-BDRC1QoR.js +7199 -0
  28. package/dist/{replay-index-qjs9VMHC.js → replay-index-BYEUJTGe.js} +1 -1
  29. package/dist/{replay-index-CG98QK-s.js → replay-index-Bwbd4CsO.js} +31 -31
  30. package/dist/replay-index-CHdCQ_zw.js +4 -0
  31. package/dist/{replay-index-_gr2NUI6.js → replay-index-CtxNTrRQ.js} +1 -1
  32. package/dist/{replay-index-kTnSyklR.js → replay-index-DD1leCQo.js} +1 -1
  33. package/dist/{replay-index-DK7gbiWU.js → replay-index-KN9FLfwz.js} +54006 -39937
  34. package/dist/{replay-index-D5Z0mNdH.js → replay-index-r6bsSAe6.js} +1 -1
  35. package/dist/replay-lint-BvndGL38.js +121 -0
  36. package/dist/replay-lint-C3ireP5A.js +22803 -0
  37. package/dist/replay-lint-graphql-CK8-ZL5Q.js +1 -0
  38. package/dist/replay-lint-graphql-DKP9oX8y.js +99 -0
  39. package/dist/{replay-periodic-revalidation--AI8Odct.js → replay-periodic-revalidation-BcWBqn6g.js} +1 -1
  40. package/dist/{replay-periodic-revalidation-B3_dehdk.js → replay-periodic-revalidation-chHSyw20.js} +1 -1
  41. package/dist/{replay-resolve-CF2p-q2m.js → replay-resolve-B1Kvf3fM.js} +1 -1
  42. package/dist/{replay-resolve-CVaipzl1.js → replay-resolve-DC-rmKvK.js} +1 -1
  43. package/dist/{replay-respect-run-CMwBljW2.js → replay-respect-run-C24QylJ-.js} +1 -1
  44. package/dist/{replay-respect-run-D8MFUbGR.js → replay-respect-run-DDZ9eF0k.js} +3 -3
  45. package/dist/{replay-tauri-path-00tVitOG.js → replay-tauri-path-Bz_q3KUG.js} +2 -2
  46. package/dist/{replay-tauri-path-CNqnykPe.js → replay-tauri-path-DBSmio5_.js} +1 -1
  47. package/dist/{replay-useAiChatQueries-1FXgtUM0.js → replay-useAiChatQueries-C_GZ_b68.js} +1 -1
  48. package/dist/{replay-useAiChatQueries-B1lLdezQ.js → replay-useAiChatQueries-DQks2tVS.js} +4 -4
  49. package/dist/{replay-validate-key-BY6-63zj.js → replay-validate-key-DScTTPU4.js} +1 -1
  50. package/dist/{replay-validate-key-CQrY8WaE.js → replay-validate-key-c2nCLxiG.js} +2 -2
  51. package/dist/replay.cjs +1 -1
  52. package/dist/replay.js +11 -11
  53. package/package.json +5 -2
  54. package/dist/replay-index-CucrJtfX.js +0 -7026
  55. package/dist/replay-index-Ea2twOHC.js +0 -4
  56. package/dist/replay-lint-B27guSWl.js +0 -30232
  57. package/dist/replay-lint-BMx3SufP.js +0 -177
  58. package/dist/replay-lint-graphql-Ddb-P1_x.js +0 -1956
  59. package/dist/replay-lint-graphql-DttNVvr_.js +0 -3
@@ -1,12 +1,12 @@
1
1
  import { jsx as te } from "react/jsx-runtime";
2
2
  import { useRef as W, useCallback as f, useSyncExternalStore as re, useEffect as R, useMemo as I, useState as z } from "react";
3
- import { a0 as S, a1 as ce, K as _e, a2 as Re, a3 as $e, a4 as $, a5 as Pe, a6 as xe, c as De, a7 as We, a8 as Be, a as Oe, a9 as Ue, aa as Fe, ab as Le, ac as je, ad as fe, ae as Ne, af as Ke, ag as qe, ah as Ae, ai as se, aj as ue, ak as Te, al as Qe, am as Ve, an as Ge, ao as ye, z as ge, B as He, R as ne, ap as ze, aq as ae, ar as Ye, as as Je } from "./replay-index-DK7gbiWU.js";
4
- import { A as Xe, D as Ze, l as et } from "./replay-create-model-DWPoobaj.js";
5
- import { AgentLoop as tt } from "./replay-agent-loop-Dev3mG-o.js";
6
- import { s as nt } from "./replay-db-C5zt3C9P.js";
7
- import { r as st, g as rt, a as ot, o as at, s as it, w as lt, m as ct, b as ut, u as dt, c as ht, d as pt, e as ft, f as gt, h as mt, i as vt, A as wt, j as Ct, k as It } from "./replay-useAiChatQueries-B1lLdezQ.js";
3
+ import { a6 as S, a7 as ce, V as _e, a8 as Re, a9 as $e, aa as $, ab as Pe, ac as xe, c as De, ad as We, ae as Be, a as Oe, af as Ue, ag as Fe, ah as Le, ai as je, aj as fe, ak as Ne, al as qe, am as Ke, an as Ae, ao as se, ap as ue, aq as Te, ar as Ve, as as Qe, at as He, au as ye, H as ge, I as Ge, R as ne, av as ze, aw as ae, ax as Ye, ay as Je } from "./replay-index-KN9FLfwz.js";
4
+ import { A as Xe, D as Ze, l as et } from "./replay-create-model-kF4veQPK.js";
5
+ import { AgentLoop as tt } from "./replay-agent-loop-4YtdgkDh.js";
6
+ import { s as nt } from "./replay-db-B3tQE-B9.js";
7
+ import { r as st, g as rt, a as ot, o as at, s as it, w as lt, m as ct, b as ut, u as dt, c as ht, d as pt, e as ft, f as gt, h as mt, i as vt, A as wt, j as Ct, k as It } from "./replay-useAiChatQueries-DQks2tVS.js";
8
8
  import { useQueryClient as de, useMutation as he } from "@tanstack/react-query";
9
- import { d as Se, g as me } from "./replay-ai-chat-mappers-B6nh9aAX.js";
9
+ import { d as Se, g as me } from "./replay-ai-chat-mappers-42FEVsfw.js";
10
10
  class At {
11
11
  handlers = /* @__PURE__ */ new Map();
12
12
  middlewares;
@@ -149,9 +149,9 @@ var be = (e, t, n) => {
149
149
  function Mt(e, t) {
150
150
  return t != null ? bt(e, t) : e;
151
151
  }
152
- var C, Z, ee, V, G, H, F, ie, le, Et = class {
152
+ var C, Z, ee, Q, H, G, F, ie, le, Et = class {
153
153
  constructor(e = []) {
154
- T(this, C, void 0), T(this, Z, "ready"), T(this, ee, void 0), T(this, V, /* @__PURE__ */ new Set()), T(this, G, /* @__PURE__ */ new Set()), T(this, H, /* @__PURE__ */ new Set()), this.pushMessage = (t) => {
154
+ T(this, C, void 0), T(this, Z, "ready"), T(this, ee, void 0), T(this, Q, /* @__PURE__ */ new Set()), T(this, H, /* @__PURE__ */ new Set()), T(this, G, /* @__PURE__ */ new Set()), this.pushMessage = (t) => {
155
155
  _(this, C, c(this, C).concat(t)), c(this, F).call(this);
156
156
  }, this.popMessage = () => {
157
157
  _(this, C, c(this, C).slice(0, -1)), c(this, F).call(this);
@@ -164,19 +164,19 @@ var C, Z, ee, V, G, H, F, ie, le, Et = class {
164
164
  ]), c(this, F).call(this);
165
165
  }, this.snapshot = (t) => structuredClone(t), this["~registerMessagesCallback"] = (t, n) => {
166
166
  const s = n ? Mt(t, n) : t;
167
- return c(this, V).add(s), () => {
168
- c(this, V).delete(s);
167
+ return c(this, Q).add(s), () => {
168
+ c(this, Q).delete(s);
169
169
  };
170
- }, this["~registerStatusCallback"] = (t) => (c(this, G).add(t), () => {
171
- c(this, G).delete(t);
172
- }), this["~registerErrorCallback"] = (t) => (c(this, H).add(t), () => {
170
+ }, this["~registerStatusCallback"] = (t) => (c(this, H).add(t), () => {
173
171
  c(this, H).delete(t);
172
+ }), this["~registerErrorCallback"] = (t) => (c(this, G).add(t), () => {
173
+ c(this, G).delete(t);
174
174
  }), T(this, F, () => {
175
- c(this, V).forEach((t) => t());
175
+ c(this, Q).forEach((t) => t());
176
176
  }), T(this, ie, () => {
177
- c(this, G).forEach((t) => t());
178
- }), T(this, le, () => {
179
177
  c(this, H).forEach((t) => t());
178
+ }), T(this, le, () => {
179
+ c(this, G).forEach((t) => t());
180
180
  }), _(this, C, e);
181
181
  }
182
182
  get status() {
@@ -201,9 +201,9 @@ var C, Z, ee, V, G, H, F, ie, le, Et = class {
201
201
  C = /* @__PURE__ */ new WeakMap();
202
202
  Z = /* @__PURE__ */ new WeakMap();
203
203
  ee = /* @__PURE__ */ new WeakMap();
204
- V = /* @__PURE__ */ new WeakMap();
205
- G = /* @__PURE__ */ new WeakMap();
204
+ Q = /* @__PURE__ */ new WeakMap();
206
205
  H = /* @__PURE__ */ new WeakMap();
206
+ G = /* @__PURE__ */ new WeakMap();
207
207
  F = /* @__PURE__ */ new WeakMap();
208
208
  ie = /* @__PURE__ */ new WeakMap();
209
209
  le = /* @__PURE__ */ new WeakMap();
@@ -403,11 +403,11 @@ function Nt(e) {
403
403
  n.length > 0 ? `(${n.join(", ")})` : null
404
404
  ].filter(Boolean).join(" ");
405
405
  }
406
- const Kt = "Auto-attached snapshot of the user's current Replay UI state. Generated by Replay before each step; not written by the user. It is a shallow summary — use tools to read detailed tab contents when needed.";
407
- function qt(e) {
406
+ const qt = "Auto-attached snapshot of the user's current Replay UI state. Generated by Replay before each step; not written by the user. It is a shallow summary — use tools to read detailed tab contents when needed.";
407
+ function Kt(e) {
408
408
  const t = `
409
409
  `.repeat(2), n = [
410
- Kt,
410
+ qt,
411
411
  t,
412
412
  jt(e.tabs),
413
413
  t,
@@ -419,10 +419,10 @@ function qt(e) {
419
419
  ].join("");
420
420
  return nt("active_state", n);
421
421
  }
422
- function Qt(e) {
423
- return e.map(Vt);
424
- }
425
422
  function Vt(e) {
423
+ return e.map(Qt);
424
+ }
425
+ function Qt(e) {
426
426
  return {
427
427
  apiId: e.id,
428
428
  title: e.info?.title ?? "Untitled API",
@@ -430,10 +430,10 @@ function Vt(e) {
430
430
  primaryServer: e.servers?.[0]?.url
431
431
  };
432
432
  }
433
- function Gt(e) {
434
- return e.map(Ht);
435
- }
436
433
  function Ht(e) {
434
+ return e.map(Gt);
435
+ }
436
+ function Gt(e) {
437
437
  const t = (e.workflows ?? []).map((s) => ({
438
438
  workflowId: s.workflowId,
439
439
  summary: s.summary,
@@ -521,8 +521,8 @@ function en(e) {
521
521
  const t = e.get(De);
522
522
  return {
523
523
  tabs: Yt(e.get(Fe), e.get(Ue), t),
524
- apis: Qt(e.get(Oe)),
525
- collections: Gt(t),
524
+ apis: Vt(e.get(Oe)),
525
+ collections: Ht(t),
526
526
  environments: zt(
527
527
  e.get(Be),
528
528
  e.get(We)
@@ -536,7 +536,7 @@ function tn() {
536
536
  return null;
537
537
  switch (n.type) {
538
538
  case $.Collection: {
539
- const o = Ke(e, n.collectionId);
539
+ const o = qe(e, n.collectionId);
540
540
  return {
541
541
  ...n,
542
542
  collection: o
@@ -596,7 +596,7 @@ function sn() {
596
596
  return (e, t) => (n, s) => t(nn(n), s);
597
597
  }
598
598
  function rn() {
599
- const { getApiOperation: e } = qe(), t = Ae();
599
+ const { getApiOperation: e } = Ke(), t = Ae();
600
600
  return I(
601
601
  () => ({
602
602
  getApiOperation: e,
@@ -606,7 +606,7 @@ function rn() {
606
606
  );
607
607
  }
608
608
  function on(e) {
609
- const { convertOperationToReplayValue: t } = se(), n = tn(), s = rn(), o = ue(), r = Te(), { attachApiToCollection: a } = Qe(), { handleCloseByDataId: l } = Ae(), h = Ve(), u = W(n);
609
+ const { convertOperationToReplayValue: t } = se(), n = tn(), s = rn(), o = ue(), r = Te(), { attachApiToCollection: a } = Ve(), { handleCloseByDataId: l } = Ae(), h = Qe(), u = W(n);
610
610
  return u.current = n, { tools: I(() => {
611
611
  const w = new At({
612
612
  middlewares: [sn()]
@@ -644,20 +644,20 @@ function on(e) {
644
644
  ]) };
645
645
  }
646
646
  function an(e) {
647
- const { children: t, chatId: n, model: s, initialMessages: o, onChatFinish: r, onChatMessagesUpdated: a } = e, l = ue(), { getReuniteAuth: h } = se(), { tools: u } = on(s), { sendEvent: v } = Ge(), w = W(u), i = W(s), { isOpen: p, openPanel: d, closePanel: P } = ye(), x = W(void 0), j = Te();
647
+ const { children: t, chatId: n, model: s, initialMessages: o, onChatFinish: r, onChatMessagesUpdated: a } = e, l = ue(), { getReuniteAuth: h } = se(), { tools: u } = on(s), { sendEvent: v } = He(), w = W(u), i = W(s), { isOpen: p, openPanel: d, closePanel: P } = ye(), x = W(void 0), j = Te();
648
648
  w.current = u, i.current = s;
649
649
  const g = I(() => {
650
650
  x.current?.end();
651
651
  const M = ge.getTracer("replay-ai-chat").startSpan("ai.chat.session", { attributes: { conversation_id: n } });
652
652
  x.current = M;
653
- const E = ge.setSpan(He.active(), M);
653
+ const E = ge.setSpan(Ge.active(), M);
654
654
  return new tt({
655
655
  activeConversationId: n,
656
656
  model: i.current,
657
657
  tools: w.current,
658
658
  sendEvent: v,
659
659
  parentCtx: E,
660
- getActiveStateMessage: () => qt(en(j))
660
+ getActiveStateMessage: () => Kt(en(j))
661
661
  });
662
662
  }, [n, v, j]);
663
663
  R(() => () => x.current?.end(), []);
@@ -677,7 +677,7 @@ function an(e) {
677
677
  status: b,
678
678
  error: Y,
679
679
  stop: O,
680
- addToolApprovalResponse: K
680
+ addToolApprovalResponse: q
681
681
  } = _t({
682
682
  id: n,
683
683
  messages: o,
@@ -687,9 +687,9 @@ function an(e) {
687
687
  if (!r || !g) return;
688
688
  r({ agentLoop: g, chat: this }, M);
689
689
  }
690
- }), y = I(() => b === "streaming" || b === "submitted", [b]), q = f(() => {
690
+ }), y = I(() => b === "streaming" || b === "submitted", [b]), K = f(() => {
691
691
  l.aiEnabled === !0 && d();
692
- }, [d, l.aiEnabled]), Q = f(() => {
692
+ }, [d, l.aiEnabled]), V = f(() => {
693
693
  P();
694
694
  }, [P]), J = f(
695
695
  async (M) => {
@@ -732,10 +732,10 @@ function an(e) {
732
732
  sendMessage: J,
733
733
  updateMessages: U,
734
734
  stopGeneration: m,
735
- addToolApprovalResponse: K
735
+ addToolApprovalResponse: q
736
736
  }),
737
737
  [
738
- K,
738
+ q,
739
739
  Y,
740
740
  y,
741
741
  k,
@@ -747,10 +747,10 @@ function an(e) {
747
747
  ), Ee = I(
748
748
  () => ({
749
749
  isOpen: p,
750
- openPanel: q,
751
- closePanel: Q
750
+ openPanel: K,
751
+ closePanel: V
752
752
  }),
753
- [p, q, Q]
753
+ [p, K, V]
754
754
  );
755
755
  return /* @__PURE__ */ te(wt.Provider, { value: Me, children: /* @__PURE__ */ te(ze.Provider, { value: Ee, children: t }) });
756
756
  }
@@ -943,7 +943,7 @@ function _n(e) {
943
943
  N(...m);
944
944
  },
945
945
  [N]
946
- ), K = f(
946
+ ), q = f(
947
947
  (m) => {
948
948
  (o === m || n === m) && i(), k.mutate(m);
949
949
  },
@@ -952,9 +952,9 @@ function _n(e) {
952
952
  R(() => {
953
953
  y && y !== n && s(y);
954
954
  }, [y, o, n]);
955
- const q = f(() => {
955
+ const K = f(() => {
956
956
  l(null);
957
- }, []), Q = f(
957
+ }, []), V = f(
958
958
  (m) => {
959
959
  h.aiEnabled && (i(), l(m), v());
960
960
  },
@@ -970,11 +970,11 @@ function _n(e) {
970
970
  title: d?.title ?? Ye.title,
971
971
  isLoading: w,
972
972
  selectChat: p,
973
- removeChat: K,
973
+ removeChat: q,
974
974
  createNewChat: i,
975
- openAiChatWithPresetInput: Q,
975
+ openAiChatWithPresetInput: V,
976
976
  pendingComposerPreset: a,
977
- clearPendingComposerPreset: q
977
+ clearPendingComposerPreset: K
978
978
  }),
979
979
  [
980
980
  n,
@@ -983,11 +983,11 @@ function _n(e) {
983
983
  g,
984
984
  w,
985
985
  p,
986
- K,
986
+ q,
987
987
  i,
988
- Q,
988
+ V,
989
989
  a,
990
- q,
990
+ K,
991
991
  j,
992
992
  B,
993
993
  u.onSettingsOpen
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const X=require("react/jsx-runtime"),i=require("react"),a=require("./replay-index-CucrJtfX.js"),te=require("./replay-create-model-CKCKpcry.js"),fe=require("./replay-agent-loop-DgP7lcS9.js"),pe=require("./replay-db-B6aY7_xq.js"),v=require("./replay-useAiChatQueries-1FXgtUM0.js"),B=require("@tanstack/react-query"),Z=require("./replay-ai-chat-mappers-f3kvLmAu.js");class ge{handlers=new Map;middlewares;constructor(t){this.middlewares=t?.middlewares??[]}register(t){this.handlers.set(t.name,t)}getToolSet(){const t={};for(const[n,s]of this.handlers)t[n]=this.buildTool(s);return t}buildTool(t){return{...t.definition,execute:this.wrapExecutor(t)}}wrapExecutor(t){const n=(o,r)=>({isError:!0,error:{message:o,details:r}}),s=this.applyMiddlewares(t.name,t.execute);return(o,r)=>{if(r.abortSignal?.aborted)return n("Tool execution was aborted.");try{const l=s(o,r);return typeof l=="object"&&l!==null&&"then"in l?l.then(u=>u,u=>n(u instanceof Error?u.message:"Unknown tool execution error")):l}catch(l){return n(l instanceof Error?l.message:"Unknown tool execution error")}}}applyMiddlewares(t,n){return this.middlewares.length===0?n:this.middlewares.reduceRight((s,o)=>o(t,s),n)}}function ce(){const e=B.useQueryClient();return B.useMutation({async mutationFn(t){const n=Z.buildPersistableUiChat(t);await a.AiChatServiceFactory.getInstance().upsert(n)},onSuccess(){e.invalidateQueries({queryKey:a.aiChatKeys.all()})},onError(t){console.error("Failed to upsert ai chat item:",t)}})}function Ce(e){const t=B.useQueryClient(),n=a.aiChatKeys.detailTitle(e??"");return B.useMutation({mutationKey:n,async mutationFn(s){if(t.isMutating({mutationKey:n,exact:!0})>1)return;const o=Z.buildPersistableUiChat(s);await a.AiChatServiceFactory.getInstance().upsert(o)},onSuccess(){t.invalidateQueries({queryKey:a.aiChatKeys.all()})},onError(s){console.error("Failed to upsert ai chat item:",s)}})}function me(){const e=B.useQueryClient();return B.useMutation({async mutationFn(t){await a.AiChatServiceFactory.getInstance().remove(t)},onMutate:async t=>{await e.cancelQueries({queryKey:a.aiChatKeys.all()});const n=e.getQueryData(a.aiChatKeys.all());n&&e.setQueryData(a.aiChatKeys.all(),n.filter(s=>s.id!==t)),e.setQueryData(a.aiChatKeys.detail(t),null),e.setQueriesData({queryKey:a.aiChatKeys.infiniteHistories()},s=>s&&{...s,pages:s.pages.map(o=>({...o,items:o.items.filter(r=>r.id!==t)}))})},onError(t){console.error("Failed to remove ai chat:",t)},onSettled(){e.invalidateQueries({queryKey:a.aiChatKeys.all()})}})}var ee,oe;function ve(){if(oe)return ee;oe=1;function e(t,n){if(typeof t!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof t}\`.`);let s,o=0;return function(...l){clearTimeout(s);const u=Date.now(),p=u-o,h=n-p;h<=0?(o=u,t.apply(this,l)):s=setTimeout(()=>{o=Date.now(),t.apply(this,l)},h)}}return ee=e,ee}var we=ve();const Ie=a.getDefaultExportFromCjs(we);var ue=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},d=(e,t,n)=>(ue(e,t,"read from private field"),n?n.call(e):t.get(e)),A=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},R=(e,t,n,s)=>(ue(e,t,"write to private field"),t.set(e,n),n);function Te(e,t){return t!=null?Ie(e,t):e}var T,Y,J,j,Q,V,W,ne,se,ye=class{constructor(e=[]){A(this,T,void 0),A(this,Y,"ready"),A(this,J,void 0),A(this,j,new Set),A(this,Q,new Set),A(this,V,new Set),this.pushMessage=t=>{R(this,T,d(this,T).concat(t)),d(this,W).call(this)},this.popMessage=()=>{R(this,T,d(this,T).slice(0,-1)),d(this,W).call(this)},this.replaceMessage=(t,n)=>{R(this,T,[...d(this,T).slice(0,t),this.snapshot(n),...d(this,T).slice(t+1)]),d(this,W).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const s=n?Te(t,n):t;return d(this,j).add(s),()=>{d(this,j).delete(s)}},this["~registerStatusCallback"]=t=>(d(this,Q).add(t),()=>{d(this,Q).delete(t)}),this["~registerErrorCallback"]=t=>(d(this,V).add(t),()=>{d(this,V).delete(t)}),A(this,W,()=>{d(this,j).forEach(t=>t())}),A(this,ne,()=>{d(this,Q).forEach(t=>t())}),A(this,se,()=>{d(this,V).forEach(t=>t())}),R(this,T,e)}get status(){return d(this,Y)}set status(e){R(this,Y,e),d(this,ne).call(this)}get error(){return d(this,J)}set error(e){R(this,J,e),d(this,se).call(this)}get messages(){return d(this,T)}set messages(e){R(this,T,[...e]),d(this,W).call(this)}};T=new WeakMap;Y=new WeakMap;J=new WeakMap;j=new WeakMap;Q=new WeakMap;V=new WeakMap;W=new WeakMap;ne=new WeakMap;se=new WeakMap;var U,ae=class extends te.AbstractChat{constructor({messages:e,...t}){const n=new ye(e);super({...t,state:n}),A(this,U,void 0),this["~registerMessagesCallback"]=(s,o)=>d(this,U)["~registerMessagesCallback"](s,o),this["~registerStatusCallback"]=s=>d(this,U)["~registerStatusCallback"](s),this["~registerErrorCallback"]=s=>d(this,U)["~registerErrorCallback"](s),R(this,U,n)}};U=new WeakMap;function Ae({experimental_throttle:e,resume:t=!1,...n}={}){const s=i.useRef("chat"in n?{}:{onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen});"chat"in n||(s.current={onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen});const o={...n,onToolCall:c=>{var g,f;return(f=(g=s.current).onToolCall)==null?void 0:f.call(g,c)},onData:c=>{var g,f;return(f=(g=s.current).onData)==null?void 0:f.call(g,c)},onFinish:c=>{var g,f;return(f=(g=s.current).onFinish)==null?void 0:f.call(g,c)},onError:c=>{var g,f;return(f=(g=s.current).onError)==null?void 0:f.call(g,c)},sendAutomaticallyWhen:c=>{var g,f,_;return(_=(f=(g=s.current).sendAutomaticallyWhen)==null?void 0:f.call(g,c))!=null?_:!1}},r=i.useRef("chat"in n?n.chat:new ae(o));("chat"in n&&n.chat!==r.current||"id"in n&&n.id!=null&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new ae(o));const u=i.useCallback(c=>r.current["~registerMessagesCallback"](c,e),[e,r.current.id]),p=i.useSyncExternalStore(u,()=>r.current.messages,()=>r.current.messages),h=i.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),w=i.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),I=i.useCallback(c=>{typeof c=="function"&&(c=c(r.current.messages)),r.current.messages=c},[r]);return i.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:p,setMessages:I,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:w,resumeStream:r.current.resumeStream,status:h,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput,addToolApprovalResponse:r.current.addToolApprovalResponse}}const be=20;function Se(e){if(e.length===0)return"No OpenAPI specs loaded.";const t=e.slice(0,be),n=t.map(ke),s=e.length-t.length;return s>0&&n.push(` …and ${s} more API(s) not shown.`),[`Loaded APIs (${e.length}):`,...n].join(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const X=require("react/jsx-runtime"),i=require("react"),a=require("./replay-index-BDRC1QoR.js"),te=require("./replay-create-model-4Yknbfme.js"),fe=require("./replay-agent-loop-BmoYEhOB.js"),pe=require("./replay-db-_hwn1n5t.js"),v=require("./replay-useAiChatQueries-C_GZ_b68.js"),B=require("@tanstack/react-query"),Z=require("./replay-ai-chat-mappers-CgjhiNr7.js");class ge{handlers=new Map;middlewares;constructor(t){this.middlewares=t?.middlewares??[]}register(t){this.handlers.set(t.name,t)}getToolSet(){const t={};for(const[n,s]of this.handlers)t[n]=this.buildTool(s);return t}buildTool(t){return{...t.definition,execute:this.wrapExecutor(t)}}wrapExecutor(t){const n=(o,r)=>({isError:!0,error:{message:o,details:r}}),s=this.applyMiddlewares(t.name,t.execute);return(o,r)=>{if(r.abortSignal?.aborted)return n("Tool execution was aborted.");try{const l=s(o,r);return typeof l=="object"&&l!==null&&"then"in l?l.then(u=>u,u=>n(u instanceof Error?u.message:"Unknown tool execution error")):l}catch(l){return n(l instanceof Error?l.message:"Unknown tool execution error")}}}applyMiddlewares(t,n){return this.middlewares.length===0?n:this.middlewares.reduceRight((s,o)=>o(t,s),n)}}function ce(){const e=B.useQueryClient();return B.useMutation({async mutationFn(t){const n=Z.buildPersistableUiChat(t);await a.AiChatServiceFactory.getInstance().upsert(n)},onSuccess(){e.invalidateQueries({queryKey:a.aiChatKeys.all()})},onError(t){console.error("Failed to upsert ai chat item:",t)}})}function Ce(e){const t=B.useQueryClient(),n=a.aiChatKeys.detailTitle(e??"");return B.useMutation({mutationKey:n,async mutationFn(s){if(t.isMutating({mutationKey:n,exact:!0})>1)return;const o=Z.buildPersistableUiChat(s);await a.AiChatServiceFactory.getInstance().upsert(o)},onSuccess(){t.invalidateQueries({queryKey:a.aiChatKeys.all()})},onError(s){console.error("Failed to upsert ai chat item:",s)}})}function me(){const e=B.useQueryClient();return B.useMutation({async mutationFn(t){await a.AiChatServiceFactory.getInstance().remove(t)},onMutate:async t=>{await e.cancelQueries({queryKey:a.aiChatKeys.all()});const n=e.getQueryData(a.aiChatKeys.all());n&&e.setQueryData(a.aiChatKeys.all(),n.filter(s=>s.id!==t)),e.setQueryData(a.aiChatKeys.detail(t),null),e.setQueriesData({queryKey:a.aiChatKeys.infiniteHistories()},s=>s&&{...s,pages:s.pages.map(o=>({...o,items:o.items.filter(r=>r.id!==t)}))})},onError(t){console.error("Failed to remove ai chat:",t)},onSettled(){e.invalidateQueries({queryKey:a.aiChatKeys.all()})}})}var ee,oe;function ve(){if(oe)return ee;oe=1;function e(t,n){if(typeof t!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof t}\`.`);let s,o=0;return function(...l){clearTimeout(s);const u=Date.now(),p=u-o,h=n-p;h<=0?(o=u,t.apply(this,l)):s=setTimeout(()=>{o=Date.now(),t.apply(this,l)},h)}}return ee=e,ee}var we=ve();const Ie=a.getDefaultExportFromCjs(we);var ue=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},d=(e,t,n)=>(ue(e,t,"read from private field"),n?n.call(e):t.get(e)),A=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},R=(e,t,n,s)=>(ue(e,t,"write to private field"),t.set(e,n),n);function Te(e,t){return t!=null?Ie(e,t):e}var T,Y,J,j,Q,V,W,ne,se,ye=class{constructor(e=[]){A(this,T,void 0),A(this,Y,"ready"),A(this,J,void 0),A(this,j,new Set),A(this,Q,new Set),A(this,V,new Set),this.pushMessage=t=>{R(this,T,d(this,T).concat(t)),d(this,W).call(this)},this.popMessage=()=>{R(this,T,d(this,T).slice(0,-1)),d(this,W).call(this)},this.replaceMessage=(t,n)=>{R(this,T,[...d(this,T).slice(0,t),this.snapshot(n),...d(this,T).slice(t+1)]),d(this,W).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const s=n?Te(t,n):t;return d(this,j).add(s),()=>{d(this,j).delete(s)}},this["~registerStatusCallback"]=t=>(d(this,Q).add(t),()=>{d(this,Q).delete(t)}),this["~registerErrorCallback"]=t=>(d(this,V).add(t),()=>{d(this,V).delete(t)}),A(this,W,()=>{d(this,j).forEach(t=>t())}),A(this,ne,()=>{d(this,Q).forEach(t=>t())}),A(this,se,()=>{d(this,V).forEach(t=>t())}),R(this,T,e)}get status(){return d(this,Y)}set status(e){R(this,Y,e),d(this,ne).call(this)}get error(){return d(this,J)}set error(e){R(this,J,e),d(this,se).call(this)}get messages(){return d(this,T)}set messages(e){R(this,T,[...e]),d(this,W).call(this)}};T=new WeakMap;Y=new WeakMap;J=new WeakMap;j=new WeakMap;Q=new WeakMap;V=new WeakMap;W=new WeakMap;ne=new WeakMap;se=new WeakMap;var U,ae=class extends te.AbstractChat{constructor({messages:e,...t}){const n=new ye(e);super({...t,state:n}),A(this,U,void 0),this["~registerMessagesCallback"]=(s,o)=>d(this,U)["~registerMessagesCallback"](s,o),this["~registerStatusCallback"]=s=>d(this,U)["~registerStatusCallback"](s),this["~registerErrorCallback"]=s=>d(this,U)["~registerErrorCallback"](s),R(this,U,n)}};U=new WeakMap;function Ae({experimental_throttle:e,resume:t=!1,...n}={}){const s=i.useRef("chat"in n?{}:{onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen});"chat"in n||(s.current={onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen});const o={...n,onToolCall:c=>{var g,f;return(f=(g=s.current).onToolCall)==null?void 0:f.call(g,c)},onData:c=>{var g,f;return(f=(g=s.current).onData)==null?void 0:f.call(g,c)},onFinish:c=>{var g,f;return(f=(g=s.current).onFinish)==null?void 0:f.call(g,c)},onError:c=>{var g,f;return(f=(g=s.current).onError)==null?void 0:f.call(g,c)},sendAutomaticallyWhen:c=>{var g,f,_;return(_=(f=(g=s.current).sendAutomaticallyWhen)==null?void 0:f.call(g,c))!=null?_:!1}},r=i.useRef("chat"in n?n.chat:new ae(o));("chat"in n&&n.chat!==r.current||"id"in n&&n.id!=null&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new ae(o));const u=i.useCallback(c=>r.current["~registerMessagesCallback"](c,e),[e,r.current.id]),p=i.useSyncExternalStore(u,()=>r.current.messages,()=>r.current.messages),h=i.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),w=i.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),I=i.useCallback(c=>{typeof c=="function"&&(c=c(r.current.messages)),r.current.messages=c},[r]);return i.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:p,setMessages:I,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:w,resumeStream:r.current.resumeStream,status:h,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput,addToolApprovalResponse:r.current.addToolApprovalResponse}}const be=20;function Se(e){if(e.length===0)return"No OpenAPI specs loaded.";const t=e.slice(0,be),n=t.map(ke),s=e.length-t.length;return s>0&&n.push(` …and ${s} more API(s) not shown.`),[`Loaded APIs (${e.length}):`,...n].join(`
2
2
  `)}function ke(e){return[` apiId="${e.apiId}"`,`title="${e.title}"`,e.version?`version="${e.version}"`:null,e.primaryServer?`server="${e.primaryServer}"`:null].filter(Boolean).join(" ")}const Ee=30;function Me(e){if(e.length===0)return"No Arazzo collections loaded.";const t=[`Arazzo collections (${e.length}):`];let n=Ee,s=0,o=0;for(const l of e){if(n<=0){s+=l.workflows.length,o++;continue}if(t.push(Re(l)),n--,l.workflows.length===0)t.push(" (no workflows)");else if(n>=2){t.push(` workflows (${l.workflows.length}):`),n--;for(const u of l.workflows)n>0?(t.push(` ${_e(u)}`),n--):s++}else s+=l.workflows.length}const r=[s>0?`${s} more workflow(s)`:null,o>0?`${o} more collection(s)`:null].filter(Boolean);return r.length>0&&t.push(` …and ${r.join(", plus ")} not shown.`),t.join(`
3
3
  `)}function Re(e){const t=e.sourceApiIds.length>0?` apis=[${e.sourceApiIds.join(", ")}]`:"";return` collectionId="${e.collectionId}" title="${e.title}"${t}`}function _e(e){const t=`id="${e.workflowId}"`,n=e.summary?`label="${e.summary}"`:null,s=`[${e.stepCount} step${e.stepCount!==1?"s":""}]`;return[t,n,s].filter(Boolean).join(" ")}const Pe=20;function De(e){if(e.length===0)return"No environments configured.";const t=e.slice(0,Pe),n=t.map(xe),s=e.length-t.length;return s>0&&n.push(` …and ${s} more environment(s) not shown.`),[`Environments (${e.length}); * marks the active environment:`,...n].join(`
4
4
  `)}function xe(e){return[`${e.isActive?"*":" "} name="${e.name}"`,`inputs=${e.inputCount}`,`servers=${e.serverCount}`].join(" ")}const $e=30;function Oe(e){if(e.length===0)return"No tabs are open.";const t=e.slice(0,$e),n=t.map(We),s=e.length-t.length;return s>0&&n.push(` …and ${s} more tab(s) not shown.`),[`Open tabs (${e.length}), listed by tabIndex; * marks the active (focused) tab:`,...n].join(`
@@ -1,7 +1,7 @@
1
1
  import "./replay-history.schema-B0lLwmdG.js";
2
2
  import "./replay-step-context.schema-BOprzd6Z.js";
3
3
  import { a as h, b as r, c as n } from "./replay-ai-message-parts.schema-DKLf0SiG.js";
4
- import { c, a as u, b as m } from "./replay-ai-chat-mappers-B6nh9aAX.js";
4
+ import { c, a as u, b as m } from "./replay-ai-chat-mappers-42FEVsfw.js";
5
5
  import { b as l, e, c as b } from "./replay-indexes-B3PJtgeh.js";
6
6
  const g = {
7
7
  orderBy: [l(r.createdAt), l(r.indexWithinInsertBatch)],
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("./replay-history.schema-miM3Etuf.js");require("./replay-step-context.schema-BuuXkAck.js");const i=require("./replay-ai-message-parts.schema-BBdjwldJ.js"),h=require("./replay-ai-chat-mappers-f3kvLmAu.js"),s=require("./replay-indexes-Dqjl8m6C.js"),c={orderBy:[s.asc(i.aiMessages.createdAt),s.asc(i.aiMessages.indexWithinInsertBatch)],with:{parts:{orderBy:[s.asc(i.aiMessageParts.index)]}}};class g{constructor(e){this.sqliteDB=e}sqliteDB;async findAll(){return await this.initialize(),(await this.db.query.aiChats.findMany({with:{messages:c}})).map(h.convertAiChatRowToUiChat)}async findRecentChatsPage(e){await this.initialize();const a=e.limit+1,r=await this.db.query.aiChats.findMany({orderBy:(d,{desc:o})=>o(d.updatedAt),limit:a,offset:e.offset}),t=r.slice(0,e.limit),n=r.length>e.limit,w=e.offset+t.length;return{items:t.map(d=>{const o={...d,messages:[]};return h.convertAiChatRowToUiChat(o)}),hasMore:n,nextOffset:w}}async findOne(e){await this.initialize();const a=await this.db.query.aiChats.findFirst({where:s.eq(i.aiChats.id,e),with:{messages:c}});return a&&h.convertAiChatRowToUiChat(a)}async upsert(e){await this.initialize();const a=h.convertUiChatToAiChatRow(e);await this.db.query.aiChats.findFirst({where:s.eq(i.aiChats.id,a.id),columns:{id:!0}})?await this.db.update(i.aiChats).set(a).where(s.eq(i.aiChats.id,a.id)):await this.db.insert(i.aiChats).values(a);for(let t=0;t<e.messages.length;t++)await this.upsertMessageRowAndParts(e.id,t,e.messages[t])}async remove(e){await this.initialize(),await this.db.delete(i.aiChats).where(s.eq(i.aiChats.id,e))}async upsertMessageRowAndParts(e,a,r){const t=await this.db.query.aiMessages.findFirst({where:s.and(s.eq(i.aiMessages.aiChatId,e),s.eq(i.aiMessages.uiId,r.id))}),n=h.convertUiMessageToAiChatMessage(e,a,r,t?.id);t?await this.db.update(i.aiMessages).set({...n,indexWithinInsertBatch:t.indexWithinInsertBatch}).where(s.eq(i.aiMessages.id,t.id)):await this.db.insert(i.aiMessages).values(n),await this.db.delete(i.aiMessageParts).where(s.eq(i.aiMessageParts.aiMessageId,n.id)),n.parts.length>0&&await this.db.insert(i.aiMessageParts).values(n.parts)}get db(){return this.sqliteDB.db}async initialize(){await this.sqliteDB.initialize()}}exports.AiChatSqliteDBStorage=g;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("./replay-history.schema-miM3Etuf.js");require("./replay-step-context.schema-BuuXkAck.js");const i=require("./replay-ai-message-parts.schema-BBdjwldJ.js"),h=require("./replay-ai-chat-mappers-CgjhiNr7.js"),s=require("./replay-indexes-Dqjl8m6C.js"),c={orderBy:[s.asc(i.aiMessages.createdAt),s.asc(i.aiMessages.indexWithinInsertBatch)],with:{parts:{orderBy:[s.asc(i.aiMessageParts.index)]}}};class g{constructor(e){this.sqliteDB=e}sqliteDB;async findAll(){return await this.initialize(),(await this.db.query.aiChats.findMany({with:{messages:c}})).map(h.convertAiChatRowToUiChat)}async findRecentChatsPage(e){await this.initialize();const a=e.limit+1,r=await this.db.query.aiChats.findMany({orderBy:(d,{desc:o})=>o(d.updatedAt),limit:a,offset:e.offset}),t=r.slice(0,e.limit),n=r.length>e.limit,w=e.offset+t.length;return{items:t.map(d=>{const o={...d,messages:[]};return h.convertAiChatRowToUiChat(o)}),hasMore:n,nextOffset:w}}async findOne(e){await this.initialize();const a=await this.db.query.aiChats.findFirst({where:s.eq(i.aiChats.id,e),with:{messages:c}});return a&&h.convertAiChatRowToUiChat(a)}async upsert(e){await this.initialize();const a=h.convertUiChatToAiChatRow(e);await this.db.query.aiChats.findFirst({where:s.eq(i.aiChats.id,a.id),columns:{id:!0}})?await this.db.update(i.aiChats).set(a).where(s.eq(i.aiChats.id,a.id)):await this.db.insert(i.aiChats).values(a);for(let t=0;t<e.messages.length;t++)await this.upsertMessageRowAndParts(e.id,t,e.messages[t])}async remove(e){await this.initialize(),await this.db.delete(i.aiChats).where(s.eq(i.aiChats.id,e))}async upsertMessageRowAndParts(e,a,r){const t=await this.db.query.aiMessages.findFirst({where:s.and(s.eq(i.aiMessages.aiChatId,e),s.eq(i.aiMessages.uiId,r.id))}),n=h.convertUiMessageToAiChatMessage(e,a,r,t?.id);t?await this.db.update(i.aiMessages).set({...n,indexWithinInsertBatch:t.indexWithinInsertBatch}).where(s.eq(i.aiMessages.id,t.id)):await this.db.insert(i.aiMessages).values(n),await this.db.delete(i.aiMessageParts).where(s.eq(i.aiMessageParts.aiMessageId,n.id)),n.parts.length>0&&await this.db.insert(i.aiMessageParts).values(n.parts)}get db(){return this.sqliteDB.db}async initialize(){await this.sqliteDB.initialize()}}exports.AiChatSqliteDBStorage=g;
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("react/jsx-runtime"),h=require("react"),X=require("styled-components"),f=require("./replay-index-CucrJtfX.js"),x=require("./replay-useAiChatQueries-1FXgtUM0.js"),Ge=require("@redocly/theme/core/constants/search"),E=require("@redocly/theme/components/Button/Button"),Ue=require("@redocly/theme/icons/SendIcon/SendIcon"),We=require("@redocly/theme/icons/StopIcon/StopIcon"),M=require("./replay-db-B6aY7_xq.js"),Ye=require("@redocly/theme/icons/CheckboxIcon/CheckboxIcon"),Ke=require("@redocly/theme/icons/CheckmarkFilledIcon/CheckmarkFilledIcon"),Je=require("@redocly/theme/icons/CloseFilledIcon/CloseFilledIcon"),Xe=require("@redocly/theme/icons/AddIcon/AddIcon"),Ze=require("@redocly/theme/icons/SubtractIcon/SubtractIcon"),K=require("@redocly/theme/core/utils"),Qe=require("@redocly/theme/icons/ChevronDownIcon/ChevronDownIcon"),et=require("@redocly/theme/icons/ChevronRightIcon/ChevronRightIcon"),tt=require("@redocly/theme/components/Dropdown/Dropdown"),nt=require("@redocly/theme/components/Dropdown/DropdownMenu"),Ie=require("@redocly/theme/components/Dropdown/DropdownMenuItem"),rt=require("@redocly/theme/icons/CheckmarkIcon/CheckmarkIcon"),ot=require("@redocly/theme/icons/SettingsCogIcon/SettingsCogIcon"),it=require("@redocly/theme/icons/ChatGptIcon/ChatGptIcon"),st=require("@redocly/theme/icons/GeminiIcon/GeminiIcon"),at=require("@redocly/theme/icons/ClaudeIcon/ClaudeIcon"),B=require("@redocly/theme/components/Tooltip/Tooltip"),ae=require("./replay-SemanticSearchService-Dooeje9n.js");require("@tanstack/react-query");const G=require("@redocly/theme/components/Typography/Typography"),lt=require("@redocly/theme/icons/TrashCanIcon/TrashCanIcon"),ct=require("@redocly/theme/icons/AiStarsGradientIcon/AiStarsGradientIcon"),dt=require("@redocly/theme/icons/CloseIcon/CloseIcon"),ut=require("@redocly/theme/icons/NewChatIcon/NewChatIcon"),ft=require("@redocly/theme/icons/RecentlyViewedIcon/RecentlyViewedIcon"),pt=require("@redocly/theme/icons/ArrowLeftIcon/ArrowLeftIcon"),ht=e=>e&&e.__esModule?e:{default:e},l=ht(X);function xt({placeholder:e="Ask anything...",className:t,disabled:n,isStreaming:r=!1,onStop:o,modelSelector:s,value:a,onValueChange:c,onSubmit:d,textareaRef:u}){const p=a.trim(),v=!n&&p.length>0&&!r,g=!n&&p.length>0,w=A=>{c(A.target.value)},m=()=>{!p||n||r||d()},b=()=>{!r||!o||o()},C=A=>{A.key==="Enter"&&!A.shiftKey&&!A.nativeEvent.isComposing&&(A.preventDefault(),r&&o?b():m())};return i.jsxs(gt,{className:t,$isActive:g,children:[i.jsx(vt,{ref:u,rows:1,maxLength:Ge.AI_SEARCH_MAX_MESSAGE_LENGTH,placeholder:e,value:a,disabled:n,spellCheck:!1,onChange:w,onKeyDown:C}),i.jsxs(mt,{children:[s,r&&o?i.jsx(wt,{type:"button",size:"small","aria-label":"Stop generating",icon:i.jsx(We.StopIcon,{color:"var(--icon-color-on-color)"}),onClick:b}):i.jsx(yt,{type:"button",size:"small","aria-label":"Send message",icon:i.jsx(Ue.SendIcon,{color:"var(--icon-color-on-color)"}),onClick:m,disabled:!v})]})]})}const gt=l.default.div`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("react/jsx-runtime"),h=require("react"),X=require("styled-components"),f=require("./replay-index-BDRC1QoR.js"),x=require("./replay-useAiChatQueries-C_GZ_b68.js"),Ge=require("@redocly/theme/core/constants/search"),E=require("@redocly/theme/components/Button/Button"),Ue=require("@redocly/theme/icons/SendIcon/SendIcon"),We=require("@redocly/theme/icons/StopIcon/StopIcon"),M=require("./replay-db-_hwn1n5t.js"),Ye=require("@redocly/theme/icons/CheckboxIcon/CheckboxIcon"),Ke=require("@redocly/theme/icons/CheckmarkFilledIcon/CheckmarkFilledIcon"),Je=require("@redocly/theme/icons/CloseFilledIcon/CloseFilledIcon"),Xe=require("@redocly/theme/icons/AddIcon/AddIcon"),Ze=require("@redocly/theme/icons/SubtractIcon/SubtractIcon"),K=require("@redocly/theme/core/utils"),Qe=require("@redocly/theme/icons/ChevronDownIcon/ChevronDownIcon"),et=require("@redocly/theme/icons/ChevronRightIcon/ChevronRightIcon"),tt=require("@redocly/theme/components/Dropdown/Dropdown"),nt=require("@redocly/theme/components/Dropdown/DropdownMenu"),Ie=require("@redocly/theme/components/Dropdown/DropdownMenuItem"),rt=require("@redocly/theme/icons/CheckmarkIcon/CheckmarkIcon"),ot=require("@redocly/theme/icons/SettingsCogIcon/SettingsCogIcon"),it=require("@redocly/theme/icons/ChatGptIcon/ChatGptIcon"),st=require("@redocly/theme/icons/GeminiIcon/GeminiIcon"),at=require("@redocly/theme/icons/ClaudeIcon/ClaudeIcon"),B=require("@redocly/theme/components/Tooltip/Tooltip"),ae=require("./replay-SemanticSearchService-IInvoSoP.js");require("@tanstack/react-query");const G=require("@redocly/theme/components/Typography/Typography"),lt=require("@redocly/theme/icons/TrashCanIcon/TrashCanIcon"),ct=require("@redocly/theme/icons/AiStarsGradientIcon/AiStarsGradientIcon"),dt=require("@redocly/theme/icons/CloseIcon/CloseIcon"),ut=require("@redocly/theme/icons/NewChatIcon/NewChatIcon"),ft=require("@redocly/theme/icons/RecentlyViewedIcon/RecentlyViewedIcon"),pt=require("@redocly/theme/icons/ArrowLeftIcon/ArrowLeftIcon"),ht=e=>e&&e.__esModule?e:{default:e},l=ht(X);function xt({placeholder:e="Ask anything...",className:t,disabled:n,isStreaming:r=!1,onStop:o,modelSelector:s,value:a,onValueChange:c,onSubmit:d,textareaRef:u}){const p=a.trim(),v=!n&&p.length>0&&!r,g=!n&&p.length>0,w=A=>{c(A.target.value)},m=()=>{!p||n||r||d()},b=()=>{!r||!o||o()},C=A=>{A.key==="Enter"&&!A.shiftKey&&!A.nativeEvent.isComposing&&(A.preventDefault(),r&&o?b():m())};return i.jsxs(gt,{className:t,$isActive:g,children:[i.jsx(vt,{ref:u,rows:1,maxLength:Ge.AI_SEARCH_MAX_MESSAGE_LENGTH,placeholder:e,value:a,disabled:n,spellCheck:!1,onChange:w,onKeyDown:C}),i.jsxs(mt,{children:[s,r&&o?i.jsx(wt,{type:"button",size:"small","aria-label":"Stop generating",icon:i.jsx(We.StopIcon,{color:"var(--icon-color-on-color)"}),onClick:b}):i.jsx(yt,{type:"button",size:"small","aria-label":"Send message",icon:i.jsx(Ue.SendIcon,{color:"var(--icon-color-on-color)"}),onClick:m,disabled:!v})]})]})}const gt=l.default.div`
2
2
  display: flex;
3
3
  flex-direction: column;
4
4
  gap: var(--spacing-xs);
@@ -1,13 +1,13 @@
1
1
  import { jsxs as m, jsx as i, Fragment as Ne } from "react/jsx-runtime";
2
2
  import { useCallback as _, useMemo as A, useState as Y, Fragment as ht, useRef as F, useEffect as B, useLayoutEffect as je } from "react";
3
3
  import c, { css as ue } from "styled-components";
4
- import { a3 as be, at as Ce, au as mt, ag as gt, ah as vt, u as yt, av as fe, aw as pe, S as V, ax as xe, ay as xt, az as wt, aA as ke, c as bt, aB as Ct, aC as Ue, aD as kt, aE as Tt, R as he, A as le, aF as We, ao as Ge, aG as we, aH as U, aI as It } from "./replay-index-DK7gbiWU.js";
5
- import { l as At, n as St, p as Lt, q as Pt, T as Et, t as Rt, v as Ot, x as Ye, C as I, y as Dt, z as qe, L as Mt, B as Q, D as _t, E as zt, F as Vt, G as $t, H as N } from "./replay-useAiChatQueries-B1lLdezQ.js";
4
+ import { a9 as be, az as Ce, aA as mt, am as gt, an as vt, u as yt, aB as fe, aC as pe, C as V, aD as xe, aE as xt, aF as wt, aG as ke, c as bt, aH as Ct, aI as Ue, aJ as kt, aK as Tt, R as he, A as le, aL as We, au as Ge, aM as we, aN as U, aO as It } from "./replay-index-KN9FLfwz.js";
5
+ import { l as At, n as St, p as Lt, q as Pt, T as Et, t as Rt, v as Ot, x as Ye, C as I, y as Dt, z as qe, L as Mt, B as Q, D as _t, E as zt, F as Vt, G as $t, H as N } from "./replay-useAiChatQueries-DQks2tVS.js";
6
6
  import { AI_SEARCH_MAX_MESSAGE_LENGTH as Ht } from "@redocly/theme/core/constants/search";
7
7
  import { Button as P } from "@redocly/theme/components/Button/Button";
8
8
  import { SendIcon as Bt } from "@redocly/theme/icons/SendIcon/SendIcon";
9
9
  import { StopIcon as Ft } from "@redocly/theme/icons/StopIcon/StopIcon";
10
- import { M as z } from "./replay-db-C5zt3C9P.js";
10
+ import { M as z } from "./replay-db-B3tQE-B9.js";
11
11
  import { CheckboxIcon as Nt } from "@redocly/theme/icons/CheckboxIcon/CheckboxIcon";
12
12
  import { CheckmarkFilledIcon as jt } from "@redocly/theme/icons/CheckmarkFilledIcon/CheckmarkFilledIcon";
13
13
  import { CloseFilledIcon as Ut } from "@redocly/theme/icons/CloseFilledIcon/CloseFilledIcon";
@@ -25,7 +25,7 @@ import { ChatGptIcon as Qt } from "@redocly/theme/icons/ChatGptIcon/ChatGptIcon"
25
25
  import { GeminiIcon as en } from "@redocly/theme/icons/GeminiIcon/GeminiIcon";
26
26
  import { ClaudeIcon as tn } from "@redocly/theme/icons/ClaudeIcon/ClaudeIcon";
27
27
  import { Tooltip as W } from "@redocly/theme/components/Tooltip/Tooltip";
28
- import { g as Te } from "./replay-SemanticSearchService-BEk_dTbd.js";
28
+ import { g as Te } from "./replay-SemanticSearchService-sIjG5Wxe.js";
29
29
  import "@tanstack/react-query";
30
30
  import { Typography as Z } from "@redocly/theme/components/Typography/Typography";
31
31
  import { TrashCanIcon as nn } from "@redocly/theme/icons/TrashCanIcon/TrashCanIcon";
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("./replay-index-CucrJtfX.js"),f=require("./replay-SemanticSearchService-Dooeje9n.js");var v;(function(l){l.WINDOW_RESIZED="tauri://resize",l.WINDOW_MOVED="tauri://move",l.WINDOW_CLOSE_REQUESTED="tauri://close-requested",l.WINDOW_DESTROYED="tauri://destroyed",l.WINDOW_FOCUS="tauri://focus",l.WINDOW_BLUR="tauri://blur",l.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",l.WINDOW_THEME_CHANGED="tauri://theme-changed",l.WINDOW_CREATED="tauri://window-created",l.WEBVIEW_CREATED="tauri://webview-created",l.DRAG_ENTER="tauri://drag-enter",l.DRAG_OVER="tauri://drag-over",l.DRAG_DROP="tauri://drag-drop",l.DRAG_LEAVE="tauri://drag-leave"})(v||(v={}));async function m(l,e){await h.invoke("plugin:event|unlisten",{event:l,eventId:e})}async function E(l,e,i){var s;const n=(s=void 0)!==null&&s!==void 0?s:{kind:"Any"};return h.invoke("plugin:event|listen",{event:l,target:n,handler:h.transformCallback(e)}).then(t=>async()=>m(l,t))}class w{constructor(e,i,s,n,t,o){this.storage=e,this.projectDir=i,this.aiEnabled=s,this.environments=n,this.apis=t,this.collections=o}storage;projectDir;aiEnabled;environments;apis;collections;watchPath=null;unlistenEvent=null;pendingEnvironmentsReload=Promise.resolve();get tauriStorage(){return this.storage}indexApis(e){!this.aiEnabled||e.length===0||f.getSemanticSearchService().indexApis(e).catch(i=>console.error("Semantic index (apis):",i))}indexCollections(e){!this.aiEnabled||e.length===0||f.getSemanticSearchService().indexCollections(e).catch(i=>console.error("Semantic index (collections):",i))}removeApis(e){if(!this.aiEnabled||e.length===0)return;const i=f.getSemanticSearchService();Promise.all(e.map(s=>i.removeApi(s))).catch(s=>console.error("Semantic remove (apis):",s))}removeCollections(e){if(!this.aiEnabled||e.length===0)return;const i=f.getSemanticSearchService();Promise.all(e.map(s=>i.removeCollection(s))).catch(s=>console.error("Semantic remove (collections):",s))}async start(){if(this.watchPath){console.warn("Watcher already started for:",this.watchPath);return}try{this.unlistenEvent=await E("fs-watch-event",async e=>{const i=e.payload;try{await this.handleEvent(i)}catch(s){console.error("Error handling file change:",s)}}),await h.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 h.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:i,paths:s,pathTypes:n,type:t}=e;if(await this.isProjectFolderRemoved(s,i)){await this.handleProjectFolderRemoval();return}const o=this.filterSpecFiles(s,n);if(o.paths.length===0)return;const a=await this.toFileEntries(o.paths,o.pathTypes);switch(i){case"changed":{(t.includes("Data")||t.includes("Name"))&&await this.handleModify(a);break}case"added":await this.handleCreate(a);break;case"deleted":await this.handleDelete(a);break;case"renamed":await this.handleRename(a);break;default:console.log("Unhandled change type:",i)}}filterSpecFiles(e,i){const s=[],n=[];for(let t=0;t<e.length;t++){const o=e[t],a=o.split(".").pop()?.toLowerCase();a&&["yaml","yml","json"].includes(a)&&(s.push(o),n.push(i[t]||"unknown"))}return{paths:s,pathTypes:n}}async toFileEntries(e,i){return Promise.all(e.map(async(s,n)=>({relative_path:await h.PathUtils.relative(this.projectDir,s),absolute_path:s,type:i[n]||"unknown"})))}hasExternalConfigChange(e){return e.some(i=>h.isRedoclyConfigFile(i.relative_path)&&!this.storage.isWatchExcluded(i.relative_path))}withoutConfigFile(e){return e.filter(i=>!h.isRedoclyConfigFile(i.relative_path))}consolidateFileEntries(e){const i=[],s=new Set;for(const n of e)s.has(n.relative_path)||(s.add(n.relative_path),this.storage.isWatchExcluded(n.relative_path)||i.push(n));return i}async handleModify(e){const i=this.hasExternalConfigChange(e),s=this.withoutConfigFile(e),{newApiFiles:n,existingApiFiles:t}=this.categorizeApisFromFiles(s),{newCollectionFiles:o,existingCollectionFiles:a}=this.categorizeCollectionsFromFiles(s),c=await this.findApisToReload(e),r=await this.findCollectionsToReload(e),p=[...n,...o];p.length>0&&await this.handleCreate(p),i&&await this.reloadEnvironments();const u=this.consolidateFileEntries([...t,...c]),g=this.consolidateFileEntries([...a,...r]);await this.reloadApis(u),await this.reloadCollections(g)}async handleCreate(e){this.hasExternalConfigChange(e)&&await this.reloadEnvironments();const i=this.withoutConfigFile(e),s=i.filter(r=>r.type==="api"),n=i.filter(r=>r.type==="collection"),{newApiFiles:t,existingApiFiles:o}=this.categorizeApisFromFiles(s),{newCollectionFiles:a,existingCollectionFiles:c}=this.categorizeCollectionsFromFiles(n);if(t.length>0||a.length>0){t.forEach(d=>this.storage.addPersistExcludedId(d.relative_path)),a.forEach(d=>this.storage.addPersistExcludedId(d.relative_path));const r=t.length>0?await this.tauriStorage.loadAndParseApis(t,void 0,!0):[],p=a.length>0?await this.tauriStorage.loadAndParseCollections(a,void 0):[],u=r.filter(d=>d!==null),g=p.filter(d=>d!==null);this.apis.set([...this.apis.get(),...u]),this.collections.set([...this.collections.get(),...g]),this.indexApis(u),this.indexCollections(g),setTimeout(()=>{t.forEach(d=>this.storage.removePersistExcludedId(d.relative_path)),a.forEach(d=>this.storage.removePersistExcludedId(d.relative_path))},500)}o.length>0&&await this.reloadApis(o),c.length>0&&await this.reloadCollections(c)}categorizeApisFromFiles(e){const i=new Set,s=[],n=[];for(const t of e){if(i.has(t.relative_path))continue;i.add(t.relative_path),this.apis.get().some(a=>a.id===t.relative_path)?n.push(t):t.type==="api"&&s.push(t)}return{newApiFiles:s,existingApiFiles:n}}categorizeCollectionsFromFiles(e){const i=new Set,s=[],n=[];for(const t of e){if(i.has(t.relative_path))continue;i.add(t.relative_path),this.collections.get().some(a=>a.id===t.relative_path)?n.push(t):t.type==="collection"&&s.push(t)}return{newCollectionFiles:s,existingCollectionFiles:n}}async handleDelete(e){this.hasExternalConfigChange(e)&&await this.reloadEnvironments();const i=this.withoutConfigFile(e),s=[],n=[];for(const t of i){this.storage.addPersistExcludedId(t.relative_path);const o=this.apis.get();o.some(r=>r.id===t.relative_path)&&(this.apis.set(o.filter(r=>r.id!==t.relative_path)),this.tauriStorage.deleteApiFromCache(t.relative_path),s.push(t.relative_path));const a=this.collections.get(),c=a.findIndex(r=>r.id===t.relative_path);c>=0&&(this.collections.set(a.filter((r,p)=>p!==c)),n.push(t.relative_path)),setTimeout(()=>{this.storage.removePersistExcludedId(t.relative_path)},500)}this.removeApis(s),this.removeCollections(n)}async handleRename(e){if(e.length>=2){const[i,s]=e;await this.handleDelete([i]),await this.handleCreate([s])}else await this.handleCreate(e)}async isProjectFolderRemoved(e,i){if(e.length===0)return!1;if(i==="deleted"||i==="renamed"){for(const n of e)if(n===this.projectDir)return!0}return e.filter(n=>!n.startsWith(this.projectDir+"/")&&n!==this.projectDir).length>0&&i==="renamed"}async handleProjectFolderRemoval(){const e=this.apis.get(),i=e.map(t=>t.id);e.forEach(t=>{this.storage.addPersistExcludedId(t.id),this.tauriStorage.deleteApiFromCache(t.id)}),this.apis.set([]);const s=this.collections.get(),n=s.map(t=>t.id);s.forEach(t=>{this.storage.addPersistExcludedId(t.id)}),this.collections.set([]),setTimeout(()=>{e.forEach(t=>this.storage.removePersistExcludedId(t.id)),s.forEach(t=>this.storage.removePersistExcludedId(t.id))},500),this.removeApis(i),this.removeCollections(n),await this.stop()}async findApisToReload(e){const i=[];return await Promise.all(this.apis.get().map(async s=>{const n=s.fileDependencies??new Set,t=s.id,o=e.find(a=>n.has(a.absolute_path));if(!this.storage.isWatchExcluded(t)&&o){const a=await h.PathUtils.join(this.projectDir,t);i.push({relative_path:t,absolute_path:a,type:"api"})}})),i}async findCollectionsToReload(e){const i=[];return await Promise.all(this.collections.get().map(async s=>{const n=s.fileDependencies??new Set,t=s.id,o=e.find(a=>n.has(a.absolute_path));if(!this.storage.isWatchExcluded(t)&&o){const a=await h.PathUtils.join(this.projectDir,t);i.push({relative_path:t,absolute_path:a,type:"collection"})}})),i}reloadEnvironments(){const e=this.pendingEnvironmentsReload.then(()=>this.readAndPublishEnvironments());return this.pendingEnvironmentsReload=e.catch(()=>{}),e}async readAndPublishEnvironments(){const e=this.environments.get(),i=await this.tauriStorage.readEnvironments();!(this.environments.get()!==e)&&(i.length>0||!this.storage.getEnvironmentsConfigError())&&this.environments.set(i.length>0?i:h.cloneObject(h.DEFAULT_ENVIRONMENTS)),this.storage.publishEnvironmentsConfigError()}async reloadApis(e){if(e.length===0)return;const i=await this.tauriStorage.loadAndParseApis(e,void 0,!0),s=[];await Promise.all(i.map(async(n,t)=>{if(!n){await this.handleDelete([e[t]]);return}const o=this.apis.get();o.some(a=>a.id===n.id)?(this.storage.addPersistExcludedId(n.id),this.apis.set(o.map(a=>a.id===n.id?n:a)),s.push(n),setTimeout(()=>this.storage.removePersistExcludedId(n.id),500)):console.warn("API not found in state after reload:",n.id)})),s.length>0&&this.indexApis(s)}async reloadCollections(e){if(e.length===0)return;const i=await this.tauriStorage.loadAndParseCollections(e,void 0),s=[];await Promise.all(i.map(async(n,t)=>{if(!n){await this.handleDelete([e[t]]);return}const o=this.collections.get(),a=o.findIndex(c=>c.id===n.id);a>=0?(this.storage.addPersistExcludedId(n.id),this.collections.set(o.map((c,r)=>r===a?n:c)),s.push(n),setTimeout(()=>this.storage.removePersistExcludedId(n.id),500)):console.warn("Collection not found in state after reload:",n.id)})),s.length>0&&this.indexCollections(s)}}exports.FileWatcher=w;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("./replay-index-BDRC1QoR.js"),f=require("./replay-SemanticSearchService-IInvoSoP.js");var v;(function(l){l.WINDOW_RESIZED="tauri://resize",l.WINDOW_MOVED="tauri://move",l.WINDOW_CLOSE_REQUESTED="tauri://close-requested",l.WINDOW_DESTROYED="tauri://destroyed",l.WINDOW_FOCUS="tauri://focus",l.WINDOW_BLUR="tauri://blur",l.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",l.WINDOW_THEME_CHANGED="tauri://theme-changed",l.WINDOW_CREATED="tauri://window-created",l.WEBVIEW_CREATED="tauri://webview-created",l.DRAG_ENTER="tauri://drag-enter",l.DRAG_OVER="tauri://drag-over",l.DRAG_DROP="tauri://drag-drop",l.DRAG_LEAVE="tauri://drag-leave"})(v||(v={}));async function m(l,e){await h.invoke("plugin:event|unlisten",{event:l,eventId:e})}async function E(l,e,i){var s;const n=(s=void 0)!==null&&s!==void 0?s:{kind:"Any"};return h.invoke("plugin:event|listen",{event:l,target:n,handler:h.transformCallback(e)}).then(t=>async()=>m(l,t))}class w{constructor(e,i,s,n,t,o){this.storage=e,this.projectDir=i,this.aiEnabled=s,this.environments=n,this.apis=t,this.collections=o}storage;projectDir;aiEnabled;environments;apis;collections;watchPath=null;unlistenEvent=null;pendingEnvironmentsReload=Promise.resolve();get tauriStorage(){return this.storage}indexApis(e){!this.aiEnabled||e.length===0||f.getSemanticSearchService().indexApis(e).catch(i=>console.error("Semantic index (apis):",i))}indexCollections(e){!this.aiEnabled||e.length===0||f.getSemanticSearchService().indexCollections(e).catch(i=>console.error("Semantic index (collections):",i))}removeApis(e){if(!this.aiEnabled||e.length===0)return;const i=f.getSemanticSearchService();Promise.all(e.map(s=>i.removeApi(s))).catch(s=>console.error("Semantic remove (apis):",s))}removeCollections(e){if(!this.aiEnabled||e.length===0)return;const i=f.getSemanticSearchService();Promise.all(e.map(s=>i.removeCollection(s))).catch(s=>console.error("Semantic remove (collections):",s))}async start(){if(this.watchPath){console.warn("Watcher already started for:",this.watchPath);return}try{this.unlistenEvent=await E("fs-watch-event",async e=>{const i=e.payload;try{await this.handleEvent(i)}catch(s){console.error("Error handling file change:",s)}}),await h.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 h.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:i,paths:s,pathTypes:n,type:t}=e;if(await this.isProjectFolderRemoved(s,i)){await this.handleProjectFolderRemoval();return}const o=this.filterSpecFiles(s,n);if(o.paths.length===0)return;const a=await this.toFileEntries(o.paths,o.pathTypes);switch(i){case"changed":{(t.includes("Data")||t.includes("Name"))&&await this.handleModify(a);break}case"added":await this.handleCreate(a);break;case"deleted":await this.handleDelete(a);break;case"renamed":await this.handleRename(a);break;default:console.log("Unhandled change type:",i)}}filterSpecFiles(e,i){const s=[],n=[];for(let t=0;t<e.length;t++){const o=e[t],a=o.split(".").pop()?.toLowerCase();a&&["yaml","yml","json"].includes(a)&&(s.push(o),n.push(i[t]||"unknown"))}return{paths:s,pathTypes:n}}async toFileEntries(e,i){return Promise.all(e.map(async(s,n)=>({relative_path:await h.PathUtils.relative(this.projectDir,s),absolute_path:s,type:i[n]||"unknown"})))}hasExternalConfigChange(e){return e.some(i=>h.isRedoclyConfigFile(i.relative_path)&&!this.storage.isWatchExcluded(i.relative_path))}withoutConfigFile(e){return e.filter(i=>!h.isRedoclyConfigFile(i.relative_path))}consolidateFileEntries(e){const i=[],s=new Set;for(const n of e)s.has(n.relative_path)||(s.add(n.relative_path),this.storage.isWatchExcluded(n.relative_path)||i.push(n));return i}async handleModify(e){const i=this.hasExternalConfigChange(e),s=this.withoutConfigFile(e),{newApiFiles:n,existingApiFiles:t}=this.categorizeApisFromFiles(s),{newCollectionFiles:o,existingCollectionFiles:a}=this.categorizeCollectionsFromFiles(s),c=await this.findApisToReload(e),r=await this.findCollectionsToReload(e),p=[...n,...o];p.length>0&&await this.handleCreate(p),i&&await this.reloadEnvironments();const u=this.consolidateFileEntries([...t,...c]),g=this.consolidateFileEntries([...a,...r]);await this.reloadApis(u),await this.reloadCollections(g)}async handleCreate(e){this.hasExternalConfigChange(e)&&await this.reloadEnvironments();const i=this.withoutConfigFile(e),s=i.filter(r=>r.type==="api"),n=i.filter(r=>r.type==="collection"),{newApiFiles:t,existingApiFiles:o}=this.categorizeApisFromFiles(s),{newCollectionFiles:a,existingCollectionFiles:c}=this.categorizeCollectionsFromFiles(n);if(t.length>0||a.length>0){t.forEach(d=>this.storage.addPersistExcludedId(d.relative_path)),a.forEach(d=>this.storage.addPersistExcludedId(d.relative_path));const r=t.length>0?await this.tauriStorage.loadAndParseApis(t,void 0,!0):[],p=a.length>0?await this.tauriStorage.loadAndParseCollections(a,void 0):[],u=r.filter(d=>d!==null),g=p.filter(d=>d!==null);this.apis.set([...this.apis.get(),...u]),this.collections.set([...this.collections.get(),...g]),this.indexApis(u),this.indexCollections(g),setTimeout(()=>{t.forEach(d=>this.storage.removePersistExcludedId(d.relative_path)),a.forEach(d=>this.storage.removePersistExcludedId(d.relative_path))},500)}o.length>0&&await this.reloadApis(o),c.length>0&&await this.reloadCollections(c)}categorizeApisFromFiles(e){const i=new Set,s=[],n=[];for(const t of e){if(i.has(t.relative_path))continue;i.add(t.relative_path),this.apis.get().some(a=>a.id===t.relative_path)?n.push(t):t.type==="api"&&s.push(t)}return{newApiFiles:s,existingApiFiles:n}}categorizeCollectionsFromFiles(e){const i=new Set,s=[],n=[];for(const t of e){if(i.has(t.relative_path))continue;i.add(t.relative_path),this.collections.get().some(a=>a.id===t.relative_path)?n.push(t):t.type==="collection"&&s.push(t)}return{newCollectionFiles:s,existingCollectionFiles:n}}async handleDelete(e){this.hasExternalConfigChange(e)&&await this.reloadEnvironments();const i=this.withoutConfigFile(e),s=[],n=[];for(const t of i){this.storage.addPersistExcludedId(t.relative_path);const o=this.apis.get();o.some(r=>r.id===t.relative_path)&&(this.apis.set(o.filter(r=>r.id!==t.relative_path)),this.tauriStorage.deleteApiFromCache(t.relative_path),s.push(t.relative_path));const a=this.collections.get(),c=a.findIndex(r=>r.id===t.relative_path);c>=0&&(this.collections.set(a.filter((r,p)=>p!==c)),n.push(t.relative_path)),setTimeout(()=>{this.storage.removePersistExcludedId(t.relative_path)},500)}this.removeApis(s),this.removeCollections(n)}async handleRename(e){if(e.length>=2){const[i,s]=e;await this.handleDelete([i]),await this.handleCreate([s])}else await this.handleCreate(e)}async isProjectFolderRemoved(e,i){if(e.length===0)return!1;if(i==="deleted"||i==="renamed"){for(const n of e)if(n===this.projectDir)return!0}return e.filter(n=>!n.startsWith(this.projectDir+"/")&&n!==this.projectDir).length>0&&i==="renamed"}async handleProjectFolderRemoval(){const e=this.apis.get(),i=e.map(t=>t.id);e.forEach(t=>{this.storage.addPersistExcludedId(t.id),this.tauriStorage.deleteApiFromCache(t.id)}),this.apis.set([]);const s=this.collections.get(),n=s.map(t=>t.id);s.forEach(t=>{this.storage.addPersistExcludedId(t.id)}),this.collections.set([]),setTimeout(()=>{e.forEach(t=>this.storage.removePersistExcludedId(t.id)),s.forEach(t=>this.storage.removePersistExcludedId(t.id))},500),this.removeApis(i),this.removeCollections(n),await this.stop()}async findApisToReload(e){const i=[];return await Promise.all(this.apis.get().map(async s=>{const n=s.fileDependencies??new Set,t=s.id,o=e.find(a=>n.has(a.absolute_path));if(!this.storage.isWatchExcluded(t)&&o){const a=await h.PathUtils.join(this.projectDir,t);i.push({relative_path:t,absolute_path:a,type:"api"})}})),i}async findCollectionsToReload(e){const i=[];return await Promise.all(this.collections.get().map(async s=>{const n=s.fileDependencies??new Set,t=s.id,o=e.find(a=>n.has(a.absolute_path));if(!this.storage.isWatchExcluded(t)&&o){const a=await h.PathUtils.join(this.projectDir,t);i.push({relative_path:t,absolute_path:a,type:"collection"})}})),i}reloadEnvironments(){const e=this.pendingEnvironmentsReload.then(()=>this.readAndPublishEnvironments());return this.pendingEnvironmentsReload=e.catch(()=>{}),e}async readAndPublishEnvironments(){const e=this.environments.get(),i=await this.tauriStorage.readEnvironments();!(this.environments.get()!==e)&&(i.length>0||!this.storage.getEnvironmentsConfigError())&&this.environments.set(i.length>0?i:h.cloneObject(h.DEFAULT_ENVIRONMENTS)),this.storage.publishEnvironmentsConfigError()}async reloadApis(e){if(e.length===0)return;const i=await this.tauriStorage.loadAndParseApis(e,void 0,!0),s=[];await Promise.all(i.map(async(n,t)=>{if(!n){await this.handleDelete([e[t]]);return}const o=this.apis.get();o.some(a=>a.id===n.id)?(this.storage.addPersistExcludedId(n.id),this.apis.set(o.map(a=>a.id===n.id?n:a)),s.push(n),setTimeout(()=>this.storage.removePersistExcludedId(n.id),500)):console.warn("API not found in state after reload:",n.id)})),s.length>0&&this.indexApis(s)}async reloadCollections(e){if(e.length===0)return;const i=await this.tauriStorage.loadAndParseCollections(e,void 0),s=[];await Promise.all(i.map(async(n,t)=>{if(!n){await this.handleDelete([e[t]]);return}const o=this.collections.get(),a=o.findIndex(c=>c.id===n.id);a>=0?(this.storage.addPersistExcludedId(n.id),this.collections.set(o.map((c,r)=>r===a?n:c)),s.push(n),setTimeout(()=>this.storage.removePersistExcludedId(n.id),500)):console.warn("Collection not found in state after reload:",n.id)})),s.length>0&&this.indexCollections(s)}}exports.FileWatcher=w;
@@ -1,5 +1,5 @@
1
- import { i as f, t as w, P as m, q as v, u as C, D as F } from "./replay-index-DK7gbiWU.js";
2
- import { g } from "./replay-SemanticSearchService-BEk_dTbd.js";
1
+ import { i as f, t as w, P as m, q as v, u as C, D as F } from "./replay-index-KN9FLfwz.js";
2
+ import { g } from "./replay-SemanticSearchService-sIjG5Wxe.js";
3
3
  var E;
4
4
  (function(l) {
5
5
  l.WINDOW_RESIZED = "tauri://resize", l.WINDOW_MOVED = "tauri://move", l.WINDOW_CLOSE_REQUESTED = "tauri://close-requested", l.WINDOW_DESTROYED = "tauri://destroyed", l.WINDOW_FOCUS = "tauri://focus", l.WINDOW_BLUR = "tauri://blur", l.WINDOW_SCALE_FACTOR_CHANGED = "tauri://scale-change", l.WINDOW_THEME_CHANGED = "tauri://theme-changed", l.WINDOW_CREATED = "tauri://window-created", l.WEBVIEW_CREATED = "tauri://webview-created", l.DRAG_ENTER = "tauri://drag-enter", l.DRAG_OVER = "tauri://drag-over", l.DRAG_DROP = "tauri://drag-drop", l.DRAG_LEAVE = "tauri://drag-leave";
@@ -1 +1 @@
1
- "use strict";const d=require("./replay-index-CucrJtfX.js"),H=require("./replay-Observable-bjJ6wkRB.js"),Z=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 z(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 J(t){return t.type?Array.isArray(t.type)?t.type.join("|"):t.type:t.oneOf?"oneOf":t.anyOf?"anyOf":t.allOf?"allOf":"object"}function V(t){return t==="querystring"?"query":t==="query"||t==="header"||t==="path"||t==="cookie"?t:"query"}function ee(t){const e=t.schema&&!S(t.schema)?t.schema:null,n={name:t.name,in:V(t.in),required:t.required??!1};return e&&(n.type=J(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 te(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(ee(c)))}};return t.parameters&&s(t.parameters),e.parameters&&s(e.parameters),o}function U(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:J(i),required:o.has(s),readOnly:i.readOnly}))}function F(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(ne(o,i))}return n}function ne(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 ie(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 oe(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 se=["get","put","post","delete","options","head","patch","trace"],re=["query","x-query"];function ce(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?U(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 ae(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=U(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=te(i,r),h=ie(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(z).join(". ")}.`);let T;const _=[],j=i.requestBody;if(j){const v=P(j);if(v){const b=ce(v,{hideReadOnly:m==="POST"||m==="PUT"||m==="PATCH"});b.textPart&&x.push(b.textPart),T=b.schemaJson,_.push(...b.examples)}}const{textParts:A,summaries:B}=ae(i.responses??{});A.length>0&&x.push(`Responses: ${A.join(", ")}.`);const C=oe(h);C&&x.push(C);const E=`api_op:${e}:${o}:${s}:${u||`${o}-${s}`}`,Y={type:"api_operation",id:E,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:T,responseSchemas:B.length>0?B:void 0,securitySchemeRefs:y,examples:_.length>0?_:void 0};return{id:E,text:$(x.filter(Boolean).join(" ")),payload:Y}}function L(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 G(t){const e=[];for(const n of t){e.push(L(n));const o=n.info?.title??"Untitled API",s=n.id,i=F(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=[...se.filter(u=>u in a),...re.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 le(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 W(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 Q(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 X(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?le(i.parameters):[];u.length>0&&l.push(`Parameters: ${u.map(z).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 K(t){const e=[];for(const n of t){const o=n.id,s=n.info?.title??"Untitled Collection";e.push(W(n));for(const i of n.workflows??[]){e.push(Q({collectionId:o,collectionTitle:s,workflow:i}));const r=i.workflowId??"",c=i.summary??r;for(const a of i.steps??[])e.push(X({collectionId:o,collectionTitle:s,workflowId:r,workflowTitle:c,step:a}))}}return e}function de(t,e){return[...G(t),...K(e)]}const N=10,ue=4;function R(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n)|0;return e>>>0}function pe(t){return d.bytesToHex(d.md5(t))}const fe={};class he extends H.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=pe(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(R)),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(R),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 Z.promiseMapLimit(n,ue,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 M="replay_search",me=384,w={added:0,updated:0,removed:0,unchanged:0};function k(t){return t.added+t.updated>0}class ye extends H.Observable{initialized=!1;projectId=null;indexer=null;indexQueue=Promise.resolve();get collectionName(){return this.projectId?`${M}_${this.projectId}`:M}createIndexer(){const e=new he(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:me,metric:"cosine",storage_mode:"full"}}),this.initialized=!0}}async indexApis(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer(),s=G(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=K(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=de(s,i);return o.indexDocuments(r,fe)},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 ye),O}exports.extractApiDocument=L;exports.extractCollectionDocument=W;exports.extractGlobalSecuritySchemes=F;exports.extractOperationDocument=D;exports.extractStepDocument=X;exports.extractWorkflowDocument=Q;exports.getSemanticSearchService=xe;
1
+ "use strict";const d=require("./replay-index-BDRC1QoR.js"),H=require("./replay-Observable-bjJ6wkRB.js"),Z=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 z(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 J(t){return t.type?Array.isArray(t.type)?t.type.join("|"):t.type:t.oneOf?"oneOf":t.anyOf?"anyOf":t.allOf?"allOf":"object"}function V(t){return t==="querystring"?"query":t==="query"||t==="header"||t==="path"||t==="cookie"?t:"query"}function ee(t){const e=t.schema&&!S(t.schema)?t.schema:null,n={name:t.name,in:V(t.in),required:t.required??!1};return e&&(n.type=J(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 te(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(ee(c)))}};return t.parameters&&s(t.parameters),e.parameters&&s(e.parameters),o}function U(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:J(i),required:o.has(s),readOnly:i.readOnly}))}function F(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(ne(o,i))}return n}function ne(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 ie(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 oe(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 se=["get","put","post","delete","options","head","patch","trace"],re=["query","x-query"];function ce(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?U(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 ae(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=U(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=te(i,r),h=ie(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(z).join(". ")}.`);let T;const _=[],j=i.requestBody;if(j){const v=P(j);if(v){const b=ce(v,{hideReadOnly:m==="POST"||m==="PUT"||m==="PATCH"});b.textPart&&x.push(b.textPart),T=b.schemaJson,_.push(...b.examples)}}const{textParts:A,summaries:B}=ae(i.responses??{});A.length>0&&x.push(`Responses: ${A.join(", ")}.`);const C=oe(h);C&&x.push(C);const E=`api_op:${e}:${o}:${s}:${u||`${o}-${s}`}`,Y={type:"api_operation",id:E,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:T,responseSchemas:B.length>0?B:void 0,securitySchemeRefs:y,examples:_.length>0?_:void 0};return{id:E,text:$(x.filter(Boolean).join(" ")),payload:Y}}function L(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 G(t){const e=[];for(const n of t){e.push(L(n));const o=n.info?.title??"Untitled API",s=n.id,i=F(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=[...se.filter(u=>u in a),...re.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 le(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 W(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 Q(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 X(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?le(i.parameters):[];u.length>0&&l.push(`Parameters: ${u.map(z).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 K(t){const e=[];for(const n of t){const o=n.id,s=n.info?.title??"Untitled Collection";e.push(W(n));for(const i of n.workflows??[]){e.push(Q({collectionId:o,collectionTitle:s,workflow:i}));const r=i.workflowId??"",c=i.summary??r;for(const a of i.steps??[])e.push(X({collectionId:o,collectionTitle:s,workflowId:r,workflowTitle:c,step:a}))}}return e}function de(t,e){return[...G(t),...K(e)]}const N=10,ue=4;function R(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n)|0;return e>>>0}function pe(t){return d.bytesToHex(d.md5(t))}const fe={};class he extends H.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=pe(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(R)),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(R),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 Z.promiseMapLimit(n,ue,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 M="replay_search",me=384,w={added:0,updated:0,removed:0,unchanged:0};function k(t){return t.added+t.updated>0}class ye extends H.Observable{initialized=!1;projectId=null;indexer=null;indexQueue=Promise.resolve();get collectionName(){return this.projectId?`${M}_${this.projectId}`:M}createIndexer(){const e=new he(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:me,metric:"cosine",storage_mode:"full"}}),this.initialized=!0}}async indexApis(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer(),s=G(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=K(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=de(s,i);return o.indexDocuments(r,fe)},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 ye),O}exports.extractApiDocument=L;exports.extractCollectionDocument=W;exports.extractGlobalSecuritySchemes=F;exports.extractOperationDocument=D;exports.extractStepDocument=X;exports.extractWorkflowDocument=Q;exports.getSemanticSearchService=xe;