@redocly/replay 0.27.1 → 0.28.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/{replay-AiChatProvider-Cdve_kxz.js → replay-AiChatProvider-COJYrrQ6.js} +6 -6
  2. package/dist/{replay-AiChatProvider-IuOVaWMC.js → replay-AiChatProvider-DjEmmTbN.js} +1 -1
  3. package/dist/{replay-AiChatSqliteDBStorage-jEhfZgK3.js → replay-AiChatSqliteDBStorage-BenAoLmM.js} +1 -1
  4. package/dist/{replay-AiChatSqliteDBStorage-B3aaY0Uo.js → replay-AiChatSqliteDBStorage-CBeRerfX.js} +1 -1
  5. package/dist/{replay-AiPanel-BT_RLVeR.js → replay-AiPanel-BN1uduZr.js} +37 -37
  6. package/dist/{replay-AiPanel-0GXuobhF.js → replay-AiPanel-FAJJA4QT.js} +1 -1
  7. package/dist/replay-FileWatcher-DDlINC06.js +1 -0
  8. package/dist/replay-FileWatcher-paEMsDuu.js +352 -0
  9. package/dist/{replay-SemanticSearchService--QXHzf7_.js → replay-SemanticSearchService-DwIcsNYC.js} +1 -1
  10. package/dist/{replay-SemanticSearchService-DJ_jBUyi.js → replay-SemanticSearchService-OutwGWqD.js} +1 -1
  11. package/dist/{replay-SqliteDBStorage-0JYq0UPY.js → replay-SqliteDBStorage-Cn8L_KB1.js} +1 -1
  12. package/dist/{replay-SqliteDBStorage-ClD7MBeX.js → replay-SqliteDBStorage-CrB-WSIX.js} +1 -1
  13. package/dist/{replay-TauriFileSystemAdapter-BnSXgnQc.js → replay-TauriFileSystemAdapter-CocGBrH_.js} +1 -1
  14. package/dist/{replay-TauriFileSystemAdapter-BuHbmM-L.js → replay-TauriFileSystemAdapter-q89YsNXx.js} +1 -1
  15. package/dist/{replay-TauriRootStorage-B1vFT2Rg.js → replay-TauriRootStorage-CZXVp2Zw.js} +1 -1
  16. package/dist/{replay-TauriRootStorage-D6K0MuWv.js → replay-TauriRootStorage-DHVdmo5Z.js} +5 -3
  17. package/dist/{replay-agent-loop-jUYXZfye.js → replay-agent-loop-cbxVIXnO.js} +9 -9
  18. package/dist/{replay-agent-loop-X2MrvEk-.js → replay-agent-loop-vzQUCpCA.js} +1 -1
  19. package/dist/{replay-ai-chat-mappers-B0Ay6VKi.js → replay-ai-chat-mappers-BnAf2rpg.js} +1 -1
  20. package/dist/{replay-ai-chat-mappers-sgE5XiwA.js → replay-ai-chat-mappers-pb8lpkUD.js} +1 -1
  21. package/dist/{replay-create-model-DB6xE5Ap.js → replay-create-model-CqA612v0.js} +3 -3
  22. package/dist/{replay-create-model-NrGYVueM.js → replay-create-model-Dr80k74P.js} +4 -4
  23. package/dist/{replay-db-BZNR8xEd.js → replay-db-Bq7IGfIa.js} +1 -1
  24. package/dist/{replay-db-BiP6dME4.js → replay-db-C8RC-t2R.js} +1 -1
  25. package/dist/{replay-external-resolver-PLyV0HZs.js → replay-external-resolver-Bw7R-LTs.js} +1 -1
  26. package/dist/{replay-external-resolver-DPAdPRks.js → replay-external-resolver-D6WP4NJY.js} +2 -2
  27. package/dist/{replay-index-yAV5TCua.js → replay-index-B3sCvU48.js} +1 -1
  28. package/dist/{replay-index-HHtp5T42.js → replay-index-BFdS3tY7.js} +1 -1
  29. package/dist/{replay-index-B2RZCGOF.js → replay-index-BizzVzWT.js} +22420 -21604
  30. package/dist/{replay-index-DTD47ryK.js → replay-index-CI5L8ebr.js} +1 -1
  31. package/dist/{replay-index-D85qPcEF.js → replay-index-D3evrr0U.js} +1205 -1098
  32. package/dist/{replay-index-DDUSidTx.js → replay-index-DZwTSW3m.js} +2 -2
  33. package/dist/{replay-index-DmAVD_C4.js → replay-index-DsAn0c_r.js} +1 -1
  34. package/dist/{replay-index-DKNhWzy4.js → replay-index-bspotqBs.js} +5 -5
  35. package/dist/{replay-lint-DyUeemr_.js → replay-lint-D5d7AeDU.js} +3 -3
  36. package/dist/{replay-lint-graphql-D_p-TkyV.js → replay-lint-graphql-CYl9hbRz.js} +1 -1
  37. package/dist/{replay-lint-graphql-pt1vf5MX.js → replay-lint-graphql-C_f79j2l.js} +1 -1
  38. package/dist/{replay-lint-Bico-a-1.js → replay-lint-q7b2-PPR.js} +3 -3
  39. package/dist/{replay-resolve-CQzlNcS2.js → replay-resolve-CftMmcPx.js} +1 -1
  40. package/dist/{replay-resolve-IKJYgmPW.js → replay-resolve-Km_DObpf.js} +1 -1
  41. package/dist/{replay-respect-run-CtDn7oS8.js → replay-respect-run-CfbJ-uak.js} +3 -3
  42. package/dist/{replay-respect-run-rx_nPWZM.js → replay-respect-run-DBe6ZUcc.js} +1 -1
  43. package/dist/{replay-tauri-path-iA6pF5e0.js → replay-tauri-path-BrtMOZvF.js} +1 -1
  44. package/dist/{replay-tauri-path-DrwBKGJP.js → replay-tauri-path-Ek8BSAa0.js} +2 -2
  45. package/dist/{replay-useAiChatQueries-PECgHJpT.js → replay-useAiChatQueries-BR1eEjUB.js} +4 -4
  46. package/dist/{replay-useAiChatQueries-BIZfilWh.js → replay-useAiChatQueries-DjjzEorX.js} +1 -1
  47. package/dist/{replay-validate-key-CvZaTfXj.js → replay-validate-key-CZSwxFid.js} +2 -2
  48. package/dist/{replay-validate-key-CTJn216O.js → replay-validate-key-Cox-cRT6.js} +1 -1
  49. package/dist/replay.cjs +1 -1
  50. package/dist/replay.d.ts +9 -0
  51. package/dist/replay.js +6 -6
  52. package/package.json +2 -2
  53. package/dist/replay-FileWatcher-CtHVgewC.js +0 -343
  54. package/dist/replay-FileWatcher-NkpXJA-C.js +0 -1
@@ -0,0 +1,352 @@
1
+ import { i as m, t as x, P as E, n as v, c as F, D as y } from "./replay-index-BizzVzWT.js";
2
+ import { g as f } from "./replay-SemanticSearchService-OutwGWqD.js";
3
+ import "react";
4
+ var w;
5
+ (function(r) {
6
+ r.WINDOW_RESIZED = "tauri://resize", r.WINDOW_MOVED = "tauri://move", r.WINDOW_CLOSE_REQUESTED = "tauri://close-requested", r.WINDOW_DESTROYED = "tauri://destroyed", r.WINDOW_FOCUS = "tauri://focus", r.WINDOW_BLUR = "tauri://blur", r.WINDOW_SCALE_FACTOR_CHANGED = "tauri://scale-change", r.WINDOW_THEME_CHANGED = "tauri://theme-changed", r.WINDOW_CREATED = "tauri://window-created", r.WEBVIEW_CREATED = "tauri://webview-created", r.DRAG_ENTER = "tauri://drag-enter", r.DRAG_OVER = "tauri://drag-over", r.DRAG_DROP = "tauri://drag-drop", r.DRAG_LEAVE = "tauri://drag-leave";
7
+ })(w || (w = {}));
8
+ async function C(r, e) {
9
+ await m("plugin:event|unlisten", {
10
+ event: r,
11
+ eventId: e
12
+ });
13
+ }
14
+ async function _(r, e, s) {
15
+ var t;
16
+ const i = (t = void 0) !== null && t !== void 0 ? t : { kind: "Any" };
17
+ return m("plugin:event|listen", {
18
+ event: r,
19
+ target: i,
20
+ handler: x(e)
21
+ }).then((a) => async () => C(r, a));
22
+ }
23
+ const d = "replay-environments.yaml";
24
+ class I {
25
+ constructor(e, s, t, i) {
26
+ this.storage = e, this.state = s, this.projectDir = t, this.aiEnabled = i;
27
+ }
28
+ storage;
29
+ state;
30
+ projectDir;
31
+ aiEnabled;
32
+ watchPath = null;
33
+ unlistenEvent = null;
34
+ get tauriStorage() {
35
+ return this.storage;
36
+ }
37
+ indexApis(e) {
38
+ !this.aiEnabled || e.length === 0 || f().indexApis(e).catch((s) => console.error("Semantic index (apis):", s));
39
+ }
40
+ indexCollections(e) {
41
+ !this.aiEnabled || e.length === 0 || f().indexCollections(e).catch((s) => console.error("Semantic index (collections):", s));
42
+ }
43
+ removeApis(e) {
44
+ if (!this.aiEnabled || e.length === 0) return;
45
+ const s = f();
46
+ Promise.all(e.map((t) => s.removeApi(t))).catch(
47
+ (t) => console.error("Semantic remove (apis):", t)
48
+ );
49
+ }
50
+ removeCollections(e) {
51
+ if (!this.aiEnabled || e.length === 0) return;
52
+ const s = f();
53
+ Promise.all(e.map((t) => s.removeCollection(t))).catch(
54
+ (t) => console.error("Semantic remove (collections):", t)
55
+ );
56
+ }
57
+ /**
58
+ * Starts watching the directory for changes.
59
+ */
60
+ async start() {
61
+ if (this.watchPath) {
62
+ console.warn("Watcher already started for:", this.watchPath);
63
+ return;
64
+ }
65
+ try {
66
+ this.unlistenEvent = await _("fs-watch-event", async (e) => {
67
+ const s = e.payload;
68
+ try {
69
+ await this.handleEvent(s);
70
+ } catch (t) {
71
+ console.error("Error handling file change:", t);
72
+ }
73
+ }), await m("fs_watch", {
74
+ path: this.projectDir,
75
+ options: {
76
+ recursive: !0,
77
+ delayMs: 500
78
+ }
79
+ }), this.watchPath = this.projectDir;
80
+ } catch (e) {
81
+ throw console.error("Failed to start file watcher:", e), this.unlistenEvent && (this.unlistenEvent(), this.unlistenEvent = null), e;
82
+ }
83
+ }
84
+ /**
85
+ * Stops watching and cleans up resources.
86
+ */
87
+ async stop() {
88
+ if (this.watchPath)
89
+ try {
90
+ await m("fs_unwatch", { path: this.watchPath });
91
+ } catch (e) {
92
+ console.error("Error stopping file watcher:", e);
93
+ } finally {
94
+ this.unlistenEvent && (this.unlistenEvent(), this.unlistenEvent = null), this.watchPath = null;
95
+ }
96
+ }
97
+ /**
98
+ * Main event handler - dispatches to specific handlers based on event type.
99
+ */
100
+ async handleEvent(e) {
101
+ const { changeType: s, paths: t, pathTypes: i, type: a } = e;
102
+ if (await this.isProjectFolderRemoved(t, s)) {
103
+ await this.handleProjectFolderRemoval();
104
+ return;
105
+ }
106
+ const o = this.filterSpecFiles(t, i);
107
+ if (o.paths.length === 0)
108
+ return;
109
+ const n = await this.toFileEntries(o.paths, o.pathTypes);
110
+ switch (s) {
111
+ case "changed":
112
+ (a.includes("Data") || a.includes("Name")) && await this.handleModify(n);
113
+ break;
114
+ case "added":
115
+ await this.handleCreate(n);
116
+ break;
117
+ case "deleted":
118
+ await this.handleDelete(n);
119
+ break;
120
+ case "renamed":
121
+ await this.handleRename(n);
122
+ break;
123
+ default:
124
+ console.log("Unhandled change type:", s);
125
+ }
126
+ }
127
+ /**
128
+ * Filter paths to only include yaml/json files.
129
+ * Returns filtered paths and their corresponding pathTypes.
130
+ */
131
+ filterSpecFiles(e, s) {
132
+ const t = [], i = [];
133
+ for (let a = 0; a < e.length; a++) {
134
+ const o = e[a], n = o.split(".").pop()?.toLowerCase();
135
+ n && ["yaml", "yml", "json"].includes(n) && (t.push(o), i.push(s[a] || "unknown"));
136
+ }
137
+ return { paths: t, pathTypes: i };
138
+ }
139
+ /**
140
+ * Convert absolute paths to file entry format with relative paths and types.
141
+ */
142
+ async toFileEntries(e, s) {
143
+ return Promise.all(
144
+ e.map(async (t, i) => ({
145
+ relative_path: await E.relative(this.projectDir, t),
146
+ absolute_path: t,
147
+ type: s[i] || "unknown"
148
+ }))
149
+ );
150
+ }
151
+ hasEnvironmentsFileChange(e) {
152
+ return !this.storage.isWatchExcluded(d) && e.some((s) => s.relative_path === d);
153
+ }
154
+ withoutEnvironmentsFile(e) {
155
+ return e.filter((s) => s.relative_path !== d);
156
+ }
157
+ consolidateFileEntries(e) {
158
+ const s = [], t = /* @__PURE__ */ new Set();
159
+ for (const i of e)
160
+ t.has(i.relative_path) || (t.add(i.relative_path), this.storage.isWatchExcluded(i.relative_path) || s.push(i));
161
+ return s;
162
+ }
163
+ /**
164
+ * Handles file content modification events.
165
+ * If file doesn't exist in state yet, treat as creation.
166
+ */
167
+ async handleModify(e) {
168
+ const s = this.hasEnvironmentsFileChange(e), t = this.withoutEnvironmentsFile(e), { newApiFiles: i, existingApiFiles: a } = this.categorizeApisFromFiles(t), { newCollectionFiles: o, existingCollectionFiles: n } = this.categorizeCollectionsFromFiles(t), h = await this.findApisToReload(e), c = await this.findCollectionsToReload(e), p = [...i, ...o];
169
+ p.length > 0 && await this.handleCreate(p), s && await this.reloadEnvironments();
170
+ const u = this.consolidateFileEntries([...a, ...h]), g = this.consolidateFileEntries([
171
+ ...n,
172
+ ...c
173
+ ]);
174
+ await this.reloadApis(u), await this.reloadCollections(g);
175
+ }
176
+ /**
177
+ * Handles file creation events.
178
+ * If file already exists in state, update it instead of creating duplicate.
179
+ */
180
+ async handleCreate(e) {
181
+ this.hasEnvironmentsFileChange(e) && await this.reloadEnvironments();
182
+ const s = this.withoutEnvironmentsFile(e), t = s.filter((c) => c.type === "api"), i = s.filter((c) => c.type === "collection"), { newApiFiles: a, existingApiFiles: o } = this.categorizeApisFromFiles(t), { newCollectionFiles: n, existingCollectionFiles: h } = this.categorizeCollectionsFromFiles(i);
183
+ if (a.length > 0 || n.length > 0) {
184
+ a.forEach((l) => this.storage.addPersistExcludedId(l.relative_path)), n.forEach((l) => this.storage.addPersistExcludedId(l.relative_path));
185
+ const c = a.length > 0 ? await this.tauriStorage.loadAndParseApis(a, void 0, !0) : [], p = n.length > 0 ? await this.tauriStorage.loadAndParseCollections(n, void 0) : [], u = c.filter((l) => l !== null), g = p.filter((l) => l !== null);
186
+ this.state.apis.merge(u), this.state.collections.merge(g), this.indexApis(u), this.indexCollections(g), setTimeout(() => {
187
+ a.forEach((l) => this.storage.removePersistExcludedId(l.relative_path)), n.forEach(
188
+ (l) => this.storage.removePersistExcludedId(l.relative_path)
189
+ );
190
+ }, 500);
191
+ }
192
+ o.length > 0 && await this.reloadApis(o), h.length > 0 && await this.reloadCollections(h);
193
+ }
194
+ /**
195
+ * Categorize API paths into new vs existing
196
+ */
197
+ /**
198
+ * Categorize API files into new vs existing
199
+ */
200
+ categorizeApisFromFiles(e) {
201
+ const s = /* @__PURE__ */ new Set(), t = [], i = [];
202
+ for (const a of e) {
203
+ if (s.has(a.relative_path))
204
+ continue;
205
+ s.add(a.relative_path), this.state.apis.get({ noproxy: !0 }).some((n) => n.id === a.relative_path) ? i.push(a) : a.type === "api" && t.push(a);
206
+ }
207
+ return { newApiFiles: t, existingApiFiles: i };
208
+ }
209
+ /**
210
+ * Categorize collection files into new vs existing
211
+ */
212
+ categorizeCollectionsFromFiles(e) {
213
+ const s = /* @__PURE__ */ new Set(), t = [], i = [];
214
+ for (const a of e) {
215
+ if (s.has(a.relative_path))
216
+ continue;
217
+ s.add(a.relative_path), this.state.collections.get({ noproxy: !0 }).some((n) => n.id === a.relative_path) ? i.push(a) : a.type === "collection" && t.push(a);
218
+ }
219
+ return { newCollectionFiles: t, existingCollectionFiles: i };
220
+ }
221
+ /**
222
+ * Handles file deletion events.
223
+ */
224
+ async handleDelete(e) {
225
+ this.hasEnvironmentsFileChange(e) && await this.reloadEnvironments();
226
+ const s = [], t = [];
227
+ for (const i of this.withoutEnvironmentsFile(e)) {
228
+ this.storage.addPersistExcludedId(i.relative_path);
229
+ const a = this.state.apis.get({ noproxy: !0 }).findIndex((n) => n.id === i.relative_path);
230
+ a >= 0 && (this.state.apis[a].set(v), this.tauriStorage.deleteApiFromCache(i.relative_path), s.push(i.relative_path));
231
+ const o = this.state.collections.get({ noproxy: !0 }).findIndex((n) => n.id === i.relative_path);
232
+ o >= 0 && (this.state.collections[o].set(v), t.push(i.relative_path)), setTimeout(() => {
233
+ this.storage.removePersistExcludedId(i.relative_path);
234
+ }, 500);
235
+ }
236
+ this.removeApis(s), this.removeCollections(t);
237
+ }
238
+ /**
239
+ * Handles file rename/move events.
240
+ * For rename events, files typically contains [oldFile, newFile]
241
+ */
242
+ async handleRename(e) {
243
+ if (e.length >= 2) {
244
+ const [s, t] = e;
245
+ await this.handleDelete([s]), await this.handleCreate([t]);
246
+ } else
247
+ await this.handleCreate(e);
248
+ }
249
+ /**
250
+ * Checks if the project folder itself was renamed/moved/deleted.
251
+ * This happens when:
252
+ * - We get a rename/delete event for the project directory itself
253
+ * - Or when paths no longer match the watched directory structure
254
+ */
255
+ async isProjectFolderRemoved(e, s) {
256
+ if (e.length === 0)
257
+ return !1;
258
+ if (s === "deleted" || s === "renamed") {
259
+ for (const i of e)
260
+ if (i === this.projectDir)
261
+ return !0;
262
+ }
263
+ return e.filter(
264
+ (i) => !i.startsWith(this.projectDir + "/") && i !== this.projectDir
265
+ ).length > 0 && s === "renamed";
266
+ }
267
+ /**
268
+ * Handles the case when the entire project folder is renamed or deleted.
269
+ * Clears all APIs and collections from state.
270
+ */
271
+ async handleProjectFolderRemoval() {
272
+ const e = this.state.apis.get({ noproxy: !0 }), s = e.map((a) => a.id);
273
+ e.forEach((a) => {
274
+ this.storage.addPersistExcludedId(a.id), this.tauriStorage.deleteApiFromCache(a.id);
275
+ }), this.state.apis.set([]);
276
+ const t = this.state.collections.get({ noproxy: !0 }), i = t.map((a) => a.id);
277
+ t.forEach((a) => {
278
+ this.storage.addPersistExcludedId(a.id);
279
+ }), this.state.collections.set([]), setTimeout(() => {
280
+ e.forEach((a) => this.storage.removePersistExcludedId(a.id)), t.forEach((a) => this.storage.removePersistExcludedId(a.id));
281
+ }, 500), this.removeApis(s), this.removeCollections(i), await this.stop();
282
+ }
283
+ async findApisToReload(e) {
284
+ const s = [];
285
+ return await Promise.all(
286
+ this.state.apis.map(async (t) => {
287
+ const i = t.fileDependencies?.get({ noproxy: !0 }) ?? /* @__PURE__ */ new Set(), a = t.get({ noproxy: !0 }).id, o = e.find((n) => i.has(n.absolute_path));
288
+ if (!this.storage.isWatchExcluded(a) && o) {
289
+ const n = await E.join(this.projectDir, a);
290
+ s.push({
291
+ relative_path: a,
292
+ absolute_path: n,
293
+ type: "api"
294
+ });
295
+ }
296
+ })
297
+ ), s;
298
+ }
299
+ async findCollectionsToReload(e) {
300
+ const s = [];
301
+ return await Promise.all(
302
+ this.state.collections.map(async (t) => {
303
+ const i = t.fileDependencies?.get({ noproxy: !0 }) ?? /* @__PURE__ */ new Set(), a = t.get({ noproxy: !0 }).id, o = e.find((n) => i.has(n.absolute_path));
304
+ if (!this.storage.isWatchExcluded(a) && o) {
305
+ const n = await E.join(this.projectDir, a);
306
+ s.push({
307
+ relative_path: a,
308
+ absolute_path: n,
309
+ type: "collection"
310
+ });
311
+ }
312
+ })
313
+ ), s;
314
+ }
315
+ async reloadEnvironments() {
316
+ const e = await this.tauriStorage.readEnviroments();
317
+ this.storage.addPersistExcludedId(d), this.state.environments.set(e.length > 0 ? e : F(y)), this.state.configFileError.set(this.storage.getEnvironmentsConfigError()), setTimeout(() => {
318
+ this.storage.removePersistExcludedId(d);
319
+ }, 500);
320
+ }
321
+ async reloadApis(e) {
322
+ if (e.length === 0) return;
323
+ const s = await this.tauriStorage.loadAndParseApis(e, void 0, !0), t = [];
324
+ await Promise.all(
325
+ s.map(async (i, a) => {
326
+ if (!i) {
327
+ await this.handleDelete([e[a]]);
328
+ return;
329
+ }
330
+ const o = this.state.apis.get({ noproxy: !0 }).findIndex((n) => n.id === i.id);
331
+ o >= 0 ? (this.storage.addPersistExcludedId(i.id), this.state.apis[o].set(i), t.push(i), setTimeout(() => this.storage.removePersistExcludedId(i.id), 500)) : console.warn("API not found in state after reload:", i.id);
332
+ })
333
+ ), t.length > 0 && this.indexApis(t);
334
+ }
335
+ async reloadCollections(e) {
336
+ if (e.length === 0) return;
337
+ const s = await this.tauriStorage.loadAndParseCollections(e, void 0), t = [];
338
+ await Promise.all(
339
+ s.map(async (i, a) => {
340
+ if (!i) {
341
+ await this.handleDelete([e[a]]);
342
+ return;
343
+ }
344
+ const o = this.state.collections.get({ noproxy: !0 }).findIndex((n) => n.id === i.id);
345
+ o >= 0 ? (this.storage.addPersistExcludedId(i.id), this.state.collections[o].set(i), t.push(i), setTimeout(() => this.storage.removePersistExcludedId(i.id), 500)) : console.warn("Collection not found in state after reload:", i.id);
346
+ })
347
+ ), t.length > 0 && this.indexCollections(t);
348
+ }
349
+ }
350
+ export {
351
+ I as FileWatcher
352
+ };
@@ -1 +1 @@
1
- "use strict";const d=require("./replay-index-D85qPcEF.js"),J=require("./replay-Observable-bjJ6wkRB.js"),ee=require("./replay-promise-map-limit-DRDkHc-b.js");function g(t){return t==null?"":typeof t=="string"?t:typeof t=="object"&&"raw"in t&&typeof t.raw=="string"?t.raw:String(t)}function $(t){return t.replace(/\s+/g," ").trim()}function S(t){return typeof t=="object"&&t!==null&&"$ref"in t}function P(t){return S(t)?null:t}function q(t){try{return JSON.stringify(t)}catch{return String(t)}}function U(t){let e=`${t.name} (${t.in}`;return t.required&&(e+=", required"),t.type&&(e+=`, ${t.type}`),t.format&&(e+=`, format: ${t.format}`),t.enum&&(e+=`, enum: [${t.enum.join(",")}]`),t.pattern&&(e+=`, pattern: ${t.pattern}`),e+=")",e}function F(t){return t.type?Array.isArray(t.type)?t.type.join("|"):t.type:t.oneOf?"oneOf":t.anyOf?"anyOf":t.allOf?"allOf":"object"}function te(t){return t==="querystring"?"query":t==="query"||t==="header"||t==="path"||t==="cookie"?t:"query"}function ne(t){const e=t.schema&&!S(t.schema)?t.schema:null,n={name:t.name,in:te(t.in),required:t.required??!1};return e&&(n.type=F(e),e.format&&(n.format=e.format),e.enum&&(n.enum=e.enum.map(String)),e.pattern&&(n.pattern=e.pattern),e.example!==void 0&&(n.example=String(e.example))),t.description&&(n.description=g(t.description)),t.example!==void 0&&!n.example&&(n.example=String(t.example)),n}function ie(t,e){const n=new Set,o=[],s=i=>{for(const r of i){const c=P(r);if(!c||!c.name)continue;const a=`${c.in}:${c.name}`;n.has(a)||(n.add(a),o.push(ne(c)))}};return t.parameters&&s(t.parameters),e.parameters&&s(e.parameters),o}function L(t,e=2,n=0){if(n>=e||!t.properties)return[];const o=new Set(t.required??[]);return Object.entries(t.properties).map(([s,i])=>({name:s,type:F(i),required:o.has(s),readOnly:i.readOnly}))}function G(t){const e=t.components?.securitySchemes;if(!e)return[];const n=[];for(const[o,s]of Object.entries(e)){const i=P(s);i&&n.push(oe(o,i))}return n}function oe(t,e){const n={schemeName:t,type:e.type};if(e.in&&(n.in=e.in),e.name&&(n.name=e.name),e.scheme&&(n.scheme=e.scheme),e.bearerFormat&&(n.bearerFormat=e.bearerFormat),e.flows){const o=Object.keys(e.flows).filter(i=>e.flows[i]);o.length>0&&(n.flows=o.join(", "));const s=new Set;for(const i of o){const r=e.flows[i];r?.scopes&&Object.keys(r.scopes).forEach(c=>s.add(c))}s.size>0&&(n.scopes=[...s].join(", "))}return n}function se(t,e,n){const o=t??e;if(!o||n.length===0)return[];const s=new Set;for(const i of o)for(const r of Object.keys(i))s.add(r);return n.filter(i=>s.has(i.schemeName))}function re(t){return t.length===0?"":`Security: ${t.map(n=>{let o=`${n.schemeName} (${n.type}`;return n.scheme&&(o+=`, ${n.scheme}`),n.in&&n.name&&(o+=`, ${n.name} in ${n.in}`),o+=")",o}).join("; ")}.`}const ce=["get","put","post","delete","options","head","patch","trace"],ae=["query","x-query"];function le(t,e){const n=[],o=Object.keys(t.content??{});if(o.length===0)return{textPart:"",schemaJson:"{}",examples:n};const s=o.find(u=>u.includes("json"))??o[0],i=t.content?.[s],r=i?.schema&&!S(i.schema)?i.schema:null,a=(r?L(r):[]).filter(u=>!e.hideReadOnly||!u.readOnly),p=t.required?"required":"optional";let l=`Request body (${s}, ${p})`;if(a.length>0){const u=a.map(f=>`${f.name}: ${f.type}${f.required?" required":""}${f.readOnly?" readOnly":""}`);l+=`: {${u.join(", ")}}`}return i?.example!==void 0&&n.push(q(i.example)),{textPart:l,schemaJson:JSON.stringify(a),examples:n}}function de(t){const e=[],n=[];for(const[o,s]of Object.entries(t)){if(S(s))continue;const i=g(s.description??"");e.push(`${o} ${i}`.trim());const r={statusCode:o};i&&(r.description=i);const c=s.content;if(c){const a=Object.keys(c).find(l=>l.includes("json"))??Object.keys(c)[0],p=c[a]?.schema;if(p&&!S(p)){const l=L(p);l.length>0&&(r.schemaProperties=JSON.stringify(l))}}n.push(r)}return{textParts:e,summaries:n}}function D(t){const{apiId:e,apiTitle:n,path:o,method:s,op:i,pathItem:r,globalSchemes:c,apiSecurity:a}=t,p=i.summary??"",l=g(i.description??""),u=i.operationId??"",f=i.tags??[],m=s.toUpperCase(),I=ie(i,r),h=se(i.security,a,c),y=h.length>0?h.map(v=>`api_sec:${e}:${v.schemeName}`):void 0,x=[n,`${m} ${o}`,p,l];u&&x.push(`operationId: ${u}`),f.length>0&&x.push(`Tags: ${f.join(", ")}`),i.deprecated&&x.push("DEPRECATED"),I.length>0&&x.push(`Parameters: ${I.map(U).join(". ")}.`);let A;const _=[],B=i.requestBody;if(B){const v=P(B);if(v){const b=le(v,{hideReadOnly:m==="POST"||m==="PUT"||m==="PATCH"});b.textPart&&x.push(b.textPart),A=b.schemaJson,_.push(...b.examples)}}const{textParts:C,summaries:E}=de(i.responses??{});C.length>0&&x.push(`Responses: ${C.join(", ")}.`);const R=re(h);R&&x.push(R);const M=`api_op:${e}:${o}:${s}:${u||`${o}-${s}`}`,V={type:"api_operation",id:M,contentHash:"",title:p||`${m} ${o}`,description:l||void 0,apiId:e,path:o,method:m,operationId:u||void 0,tags:f.length>0?f:void 0,deprecated:i.deprecated||void 0,parameterDetails:I.length>0?I:void 0,requestBodySchema:A,responseSchemas:E.length>0?E:void 0,securitySchemeRefs:y,examples:_.length>0?_:void 0};return{id:M,text:$(x.filter(Boolean).join(" ")),payload:V}}function W(t){const e=t.info?.title??"Untitled API",n=g(t.info?.description??t.info?.summary??""),o=t.id;return{id:`api:${o}`,text:$([e,n].filter(Boolean).join(" ")),payload:{type:"api",id:`api:${o}`,contentHash:"",title:e,description:n||void 0,apiId:o}}}function T(t){const e=[];for(const n of t){e.push(W(n));const o=n.info?.title??"Untitled API",s=n.id,i=G(n);for(const c of i){const a=`api_sec:${s}:${c.schemeName}`,p=[`${c.schemeName}: type=${c.type}`,c.scheme?`scheme=${c.scheme}`:"",c.in&&c.name?`${c.name} in ${c.in}`:"",c.bearerFormat?`format=${c.bearerFormat}`:"",c.flows?`flows=[${c.flows}]`:"",c.scopes?`scopes=[${c.scopes}]`:""].filter(Boolean).join(" ");e.push({id:a,text:$(`${o} Authentication. ${c.schemeName}. ${p}.`),payload:{type:"api_security",id:a,contentHash:"",title:`${o} — ${c.schemeName}`,apiId:s,securityScheme:c}})}const r=n.paths??{};for(const[c,a]of Object.entries(r)){if(!a||typeof a!="object")continue;const p=[...ce.filter(u=>u in a),...ae.filter(u=>u in a)];for(const u of p){const f=a[u];!f||typeof f!="object"||e.push(D({apiId:s,apiTitle:o,path:c,method:u,op:f,pathItem:a,globalSchemes:i,apiSecurity:n.security}))}const l=a.additionalOperations;if(l&&typeof l=="object")for(const[u,f]of Object.entries(l))!f||typeof f!="object"||e.push(D({apiId:s,apiTitle:o,path:c,method:u,op:f,pathItem:a,globalSchemes:i,apiSecurity:n.security}))}}return e}function ue(t){const e=[],n=[{list:t.queryParameters,loc:"query"},{list:t.headers,loc:"header"},{list:t.cookies,loc:"cookie"},{list:t.pathParameters,loc:"path"}];for(const{list:o,loc:s}of n)for(const i of o)if("key"in i){const r=i;e.push({name:r.key,in:s,required:!1})}return e}function Q(t){const e=t.id,n=t.info?.title??"Untitled Collection",o=g(t.info?.description??t.info?.summary??"");return{id:`collection:${e}`,text:$([n,o].filter(Boolean).join(" ")),payload:{type:"collection",id:`collection:${e}`,contentHash:"",title:n,description:o||void 0,collectionId:e}}}function X(t){const{collectionId:e,collectionTitle:n,workflow:o}=t,s=o.workflowId??"",i=o.summary??s,r=g(o.description??""),c=[n,i,r];if(o.inputs&&c.push(`Inputs schema: ${q(o.inputs)}`),o.outputs?.length){const a=o.outputs.map(p=>p.key).filter(Boolean);a.length&&c.push(`Outputs: ${a.join(", ")}`)}return o.dependsOn?.length&&c.push(`Depends on: ${o.dependsOn.join(", ")}`),{id:`workflow:${e}:${s}`,text:$(c.filter(Boolean).join(" ")),payload:{type:"workflow",id:`workflow:${e}:${s}`,contentHash:"",title:i,description:r||void 0,collectionId:e,workflowId:s}}}function K(t){const{collectionId:e,collectionTitle:n,workflowId:o,workflowTitle:s,step:i}=t,r=i.stepId??"",c=g(i.description??""),a=i.operation,p=i.xOperation,l=[n,s,`step: ${r}`];c&&l.push(c),a?(l.push(`${a.method?.toUpperCase()} ${a.path}`),a.apiId&&l.push(`API: ${a.apiId}`),a.operationId&&l.push(`operationId: ${a.operationId}`)):p&&l.push(`${p.method?.toUpperCase()} ${p.url}`);const u=i.parameters?ue(i.parameters):[];u.length>0&&l.push(`Parameters: ${u.map(U).join(". ")}.`),i.requestBody?.type&&l.push(`Request body type: ${i.requestBody.type}`);const m=(i.successCriteria??[]).map(h=>{let y=h.condition;return h.context&&(y+=` context: ${h.context}`),h.type&&(y+=` (${h.type})`),y});if(m.length>0&&l.push(`Success criteria: ${m.join("; ")}`),i.outputs?.length){const h=i.outputs.map(y=>`${y.key}=${y.value}`).filter(Boolean);h.length&&l.push(`Outputs: ${h.join(", ")}`)}const I=`step:${e}:${o}:${r}`;return{id:I,text:$(l.filter(Boolean).join(" ")),payload:{type:"step",id:I,contentHash:"",title:r,description:c||void 0,collectionId:e,workflowId:o,stepId:r,path:a?.path??p?.url,method:(a?.method??p?.method)?.toUpperCase(),apiId:a?.apiId,operationId:a?.operationId,parameterDetails:u.length>0?u:void 0,successCriteria:m.length>0?m:void 0,requestBodySchema:i.requestBody?.type?q(i.requestBody):void 0}}}function j(t){const e=[];for(const n of t){const o=n.id,s=n.info?.title??"Untitled Collection";e.push(Q(n));for(const i of n.workflows??[]){e.push(X({collectionId:o,collectionTitle:s,workflow:i}));const r=i.workflowId??"",c=i.summary??r;for(const a of i.steps??[])e.push(K({collectionId:o,collectionTitle:s,workflowId:r,workflowTitle:c,step:a}))}}return e}function Y(t,e){return[...T(t),...j(e)]}const N=10,pe=4;function H(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n)|0;return e>>>0}function fe(t){return d.bytesToHex(d.md5(t))}const he={};class me extends J.Observable{constructor(e){super(),this.collectionName=e}collectionName;activeIndexJobs=0;getIndexingActivityState(){return{inProgress:this.activeIndexJobs>0}}beginIndexJob(){this.activeIndexJobs++,this.activeIndexJobs===1&&this.emit("indexing-activity",{inProgress:!0})}endIndexJob(){this.activeIndexJobs=Math.max(0,this.activeIndexJobs-1),this.activeIndexJobs===0&&this.emit("indexing-activity",{inProgress:!1})}async getIdsByPayload(e,n){return d.invoke("semantic_search_get_ids_by_payload",{collectionName:this.collectionName,field:e,value:n})}async getAllIds(){return d.invoke("semantic_search_get_all_ids",{collectionName:this.collectionName})}async getScopeHashes(e){const n=e.apiIds??[],o=e.collectionIds??[];let s;if(n.length===0&&o.length===0)s=await this.getAllIds();else{const r=[];for(const a of n)r.push(this.getIdsByPayload("apiId",a));for(const a of o)r.push(this.getIdsByPayload("collectionId",a));s=(await Promise.all(r)).flat()}const i=new Map;for(const r of s)i.set(r.id,r.contentHash);return i}async indexDocuments(e,n){if(e.length===0&&!n)return{added:0,updated:0,removed:0,unchanged:0};const o=await this.getScopeHashes(n??{}),s=[],i=new Set;let r=0,c=0;for(const l of e){const u=fe(l.text);l.payload.contentHash=u,i.add(l.id);const f=o.get(l.id);f===u?c++:(f||r++,s.push(l))}const a=s.length-r,p=[];for(const l of o.keys())i.has(l)||p.push(l);if(p.length>0||s.length>0){this.beginIndexJob();try{p.length>0&&await this.deletePoints(p.map(H)),s.length>0&&await this.embedAndUpsert(s),await this.flush()}finally{this.endIndexJob()}}return{added:r,updated:a,removed:p.length,unchanged:c}}async removeByPayloadFilter(e,n){return d.invoke("semantic_search_delete_by_payload",{collectionName:this.collectionName,field:e,value:n})}async getStoredDocumentCount(){try{return(await d.invoke("plugin:velesdb|list_collections"))?.find(o=>o.name===this.collectionName)?.count??0}catch{return 0}}async getDocumentsByIds(e){if(e.length===0)return new Map;const n=e.map(H),o=await d.invoke("plugin:velesdb|get_points",{request:{collection:this.collectionName,ids:n}}),s=new Map;for(const i of o??[])if(i?.payload){const r=i.payload;r.id&&s.set(r.id,r)}return s}async embedAndUpsert(e){const n=[],o=e.length;for(let s=0;s<o;s+=N)n.push({docs:e.slice(s,s+N),index:Math.floor(s/N)});await ee.promiseMapLimit(n,pe,async s=>{const i=s.docs.map(r=>({id:r.id,text:r.text||r.payload.title,payload:r.payload}));await d.invoke("semantic_search_embed_and_upsert",{collectionName:this.collectionName,documents:i})})}async deletePoints(e){e.length!==0&&await d.invoke("plugin:velesdb|delete_points",{request:{collection:this.collectionName,ids:e}})}async flush(){await d.invoke("plugin:velesdb|flush",{name:this.collectionName}),await d.invoke("semantic_search_write_hnsw_marker",{collectionName:this.collectionName}).catch(()=>{})}}const z="replay_search",ye=384,w={added:0,updated:0,removed:0,unchanged:0};function k(t){return t.added+t.updated>0}class Z extends J.Observable{initialized=!1;projectId=null;indexer=null;indexQueue=Promise.resolve();get collectionName(){return this.projectId?`${z}_${this.projectId}`:z}createIndexer(){const e=new me(this.collectionName);return e.subscribe("indexing-activity",n=>{this.emit("indexing-activity",n)}),e}getIndexer(){return this.indexer||(this.indexer=this.createIndexer()),this.indexer}getIndexingActivityState(){return this.getIndexer().getIndexingActivityState()}async ensureInitialized(){this.initialized||await this.init()}enqueueIndex(e,n){const s=this.indexQueue.then(()=>e()).then(async i=>(n(i)&&await this.unloadModel(),i)).catch(async i=>{throw console.error("Semantic index:",i),await this.unloadModel(),i});return this.indexQueue=s.catch(()=>{}),s}async unloadModel(){try{await d.invoke("semantic_search_unload_model")}catch{}}setProject(e){this.projectId!==e&&(this.projectId=e,this.initialized=!1,this.indexer=this.createIndexer())}async init(){if(d.isTauriApp()&&!this.initialized){try{if((await d.invoke("plugin:velesdb|list_collections"))?.some(n=>n.name===this.collectionName)){this.initialized=!0;return}}catch{}await d.invoke("plugin:velesdb|create_collection",{request:{name:this.collectionName,dimension:ye,metric:"cosine",storage_mode:"full"}}),this.initialized=!0}}async indexApis(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer(),s=T(e),i={apiIds:e.map(r=>r.id)};return await this.ensureInitialized(),this.enqueueIndex(async()=>this.collectionName!==n?w:o.indexDocuments(s,i),k)}async indexCollections(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer(),s=j(e),i={collectionIds:e.map(r=>r.id)};return await this.ensureInitialized(),this.enqueueIndex(async()=>this.collectionName!==n?w:o.indexDocuments(s,i),k)}async removeApi(e){if(!d.isTauriApp())return;const n=this.getIndexer();await this.ensureInitialized(),await this.enqueueIndex(()=>n.removeByPayloadFilter("apiId",e),()=>!1)}async removeCollection(e){if(!d.isTauriApp())return;const n=this.getIndexer();await this.ensureInitialized(),await this.enqueueIndex(()=>n.removeByPayloadFilter("collectionId",e),()=>!1)}async reindex(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer();return await this.ensureInitialized(),this.enqueueIndex(async()=>{if(this.collectionName!==n)return w;const{apis:s,collections:i}=e(),r=Y(s,i);return o.indexDocuments(r,he)},k)}async search(e,n=10,o){if(!d.isTauriApp())return[];try{await this.ensureInitialized();const s=o&&Object.keys(o).length>0?{type:o.type,apiId:o.apiId,collectionId:o.collectionId,path:o.path,method:o.method,operationId:o.operationId,workflowId:o.workflowId,stepId:o.stepId}:void 0,r=((await d.invoke("semantic_search_text",{collection:this.collectionName,query:e,topK:n,filters:s})).results??[]).map(c=>({...c.payload,score:c.score??0}));return await this.enrichWithRelatedSecurity(r),r}catch{return[]}}async enrichWithRelatedSecurity(e){const n=e.filter(i=>i.type==="api_operation"&&i.securitySchemeRefs?.length);if(n.length===0)return;const o=[...new Set(n.flatMap(i=>i.securitySchemeRefs??[]))],s=await this.getIndexer().getDocumentsByIds(o);for(const i of n){const r=[];for(const c of i.securitySchemeRefs??[]){const a=s.get(c);a?.securityScheme&&r.push(a.securityScheme)}r.length>0&&(i.relatedSecuritySchemes=r)}}async status(){if(!d.isTauriApp())return{indexed:0,modelLoaded:!1};const e=await this.getIndexer().getStoredDocumentCount();let n=!1;try{n=(await d.invoke("semantic_search_model_status")).loaded}catch{}return{indexed:e,modelLoaded:n}}async clear(){if(!(!d.isTauriApp()||!this.initialized))try{await d.invoke("plugin:velesdb|delete_collection",{name:this.collectionName}),this.initialized=!1}catch{}}async preloadModel(){if(d.isTauriApp())try{await d.invoke("semantic_search_preload_model")}catch{}}}let O=null;function xe(){return O||(O=new Z),O}exports.SemanticSearchService=Z;exports.extractAllDocuments=Y;exports.extractApiDocument=W;exports.extractApiDocuments=T;exports.extractCollectionDocument=Q;exports.extractCollectionDocuments=j;exports.extractGlobalSecuritySchemes=G;exports.extractOperationDocument=D;exports.extractStepDocument=K;exports.extractWorkflowDocument=X;exports.getSemanticSearchService=xe;
1
+ "use strict";const d=require("./replay-index-D3evrr0U.js"),J=require("./replay-Observable-bjJ6wkRB.js"),ee=require("./replay-promise-map-limit-DRDkHc-b.js");function g(t){return t==null?"":typeof t=="string"?t:typeof t=="object"&&"raw"in t&&typeof t.raw=="string"?t.raw:String(t)}function $(t){return t.replace(/\s+/g," ").trim()}function S(t){return typeof t=="object"&&t!==null&&"$ref"in t}function P(t){return S(t)?null:t}function q(t){try{return JSON.stringify(t)}catch{return String(t)}}function U(t){let e=`${t.name} (${t.in}`;return t.required&&(e+=", required"),t.type&&(e+=`, ${t.type}`),t.format&&(e+=`, format: ${t.format}`),t.enum&&(e+=`, enum: [${t.enum.join(",")}]`),t.pattern&&(e+=`, pattern: ${t.pattern}`),e+=")",e}function F(t){return t.type?Array.isArray(t.type)?t.type.join("|"):t.type:t.oneOf?"oneOf":t.anyOf?"anyOf":t.allOf?"allOf":"object"}function te(t){return t==="querystring"?"query":t==="query"||t==="header"||t==="path"||t==="cookie"?t:"query"}function ne(t){const e=t.schema&&!S(t.schema)?t.schema:null,n={name:t.name,in:te(t.in),required:t.required??!1};return e&&(n.type=F(e),e.format&&(n.format=e.format),e.enum&&(n.enum=e.enum.map(String)),e.pattern&&(n.pattern=e.pattern),e.example!==void 0&&(n.example=String(e.example))),t.description&&(n.description=g(t.description)),t.example!==void 0&&!n.example&&(n.example=String(t.example)),n}function ie(t,e){const n=new Set,o=[],s=i=>{for(const r of i){const c=P(r);if(!c||!c.name)continue;const a=`${c.in}:${c.name}`;n.has(a)||(n.add(a),o.push(ne(c)))}};return t.parameters&&s(t.parameters),e.parameters&&s(e.parameters),o}function L(t,e=2,n=0){if(n>=e||!t.properties)return[];const o=new Set(t.required??[]);return Object.entries(t.properties).map(([s,i])=>({name:s,type:F(i),required:o.has(s),readOnly:i.readOnly}))}function G(t){const e=t.components?.securitySchemes;if(!e)return[];const n=[];for(const[o,s]of Object.entries(e)){const i=P(s);i&&n.push(oe(o,i))}return n}function oe(t,e){const n={schemeName:t,type:e.type};if(e.in&&(n.in=e.in),e.name&&(n.name=e.name),e.scheme&&(n.scheme=e.scheme),e.bearerFormat&&(n.bearerFormat=e.bearerFormat),e.flows){const o=Object.keys(e.flows).filter(i=>e.flows[i]);o.length>0&&(n.flows=o.join(", "));const s=new Set;for(const i of o){const r=e.flows[i];r?.scopes&&Object.keys(r.scopes).forEach(c=>s.add(c))}s.size>0&&(n.scopes=[...s].join(", "))}return n}function se(t,e,n){const o=t??e;if(!o||n.length===0)return[];const s=new Set;for(const i of o)for(const r of Object.keys(i))s.add(r);return n.filter(i=>s.has(i.schemeName))}function re(t){return t.length===0?"":`Security: ${t.map(n=>{let o=`${n.schemeName} (${n.type}`;return n.scheme&&(o+=`, ${n.scheme}`),n.in&&n.name&&(o+=`, ${n.name} in ${n.in}`),o+=")",o}).join("; ")}.`}const ce=["get","put","post","delete","options","head","patch","trace"],ae=["query","x-query"];function le(t,e){const n=[],o=Object.keys(t.content??{});if(o.length===0)return{textPart:"",schemaJson:"{}",examples:n};const s=o.find(u=>u.includes("json"))??o[0],i=t.content?.[s],r=i?.schema&&!S(i.schema)?i.schema:null,a=(r?L(r):[]).filter(u=>!e.hideReadOnly||!u.readOnly),p=t.required?"required":"optional";let l=`Request body (${s}, ${p})`;if(a.length>0){const u=a.map(f=>`${f.name}: ${f.type}${f.required?" required":""}${f.readOnly?" readOnly":""}`);l+=`: {${u.join(", ")}}`}return i?.example!==void 0&&n.push(q(i.example)),{textPart:l,schemaJson:JSON.stringify(a),examples:n}}function de(t){const e=[],n=[];for(const[o,s]of Object.entries(t)){if(S(s))continue;const i=g(s.description??"");e.push(`${o} ${i}`.trim());const r={statusCode:o};i&&(r.description=i);const c=s.content;if(c){const a=Object.keys(c).find(l=>l.includes("json"))??Object.keys(c)[0],p=c[a]?.schema;if(p&&!S(p)){const l=L(p);l.length>0&&(r.schemaProperties=JSON.stringify(l))}}n.push(r)}return{textParts:e,summaries:n}}function D(t){const{apiId:e,apiTitle:n,path:o,method:s,op:i,pathItem:r,globalSchemes:c,apiSecurity:a}=t,p=i.summary??"",l=g(i.description??""),u=i.operationId??"",f=i.tags??[],m=s.toUpperCase(),I=ie(i,r),h=se(i.security,a,c),y=h.length>0?h.map(v=>`api_sec:${e}:${v.schemeName}`):void 0,x=[n,`${m} ${o}`,p,l];u&&x.push(`operationId: ${u}`),f.length>0&&x.push(`Tags: ${f.join(", ")}`),i.deprecated&&x.push("DEPRECATED"),I.length>0&&x.push(`Parameters: ${I.map(U).join(". ")}.`);let A;const _=[],B=i.requestBody;if(B){const v=P(B);if(v){const b=le(v,{hideReadOnly:m==="POST"||m==="PUT"||m==="PATCH"});b.textPart&&x.push(b.textPart),A=b.schemaJson,_.push(...b.examples)}}const{textParts:C,summaries:E}=de(i.responses??{});C.length>0&&x.push(`Responses: ${C.join(", ")}.`);const R=re(h);R&&x.push(R);const M=`api_op:${e}:${o}:${s}:${u||`${o}-${s}`}`,V={type:"api_operation",id:M,contentHash:"",title:p||`${m} ${o}`,description:l||void 0,apiId:e,path:o,method:m,operationId:u||void 0,tags:f.length>0?f:void 0,deprecated:i.deprecated||void 0,parameterDetails:I.length>0?I:void 0,requestBodySchema:A,responseSchemas:E.length>0?E:void 0,securitySchemeRefs:y,examples:_.length>0?_:void 0};return{id:M,text:$(x.filter(Boolean).join(" ")),payload:V}}function W(t){const e=t.info?.title??"Untitled API",n=g(t.info?.description??t.info?.summary??""),o=t.id;return{id:`api:${o}`,text:$([e,n].filter(Boolean).join(" ")),payload:{type:"api",id:`api:${o}`,contentHash:"",title:e,description:n||void 0,apiId:o}}}function T(t){const e=[];for(const n of t){e.push(W(n));const o=n.info?.title??"Untitled API",s=n.id,i=G(n);for(const c of i){const a=`api_sec:${s}:${c.schemeName}`,p=[`${c.schemeName}: type=${c.type}`,c.scheme?`scheme=${c.scheme}`:"",c.in&&c.name?`${c.name} in ${c.in}`:"",c.bearerFormat?`format=${c.bearerFormat}`:"",c.flows?`flows=[${c.flows}]`:"",c.scopes?`scopes=[${c.scopes}]`:""].filter(Boolean).join(" ");e.push({id:a,text:$(`${o} Authentication. ${c.schemeName}. ${p}.`),payload:{type:"api_security",id:a,contentHash:"",title:`${o} — ${c.schemeName}`,apiId:s,securityScheme:c}})}const r=n.paths??{};for(const[c,a]of Object.entries(r)){if(!a||typeof a!="object")continue;const p=[...ce.filter(u=>u in a),...ae.filter(u=>u in a)];for(const u of p){const f=a[u];!f||typeof f!="object"||e.push(D({apiId:s,apiTitle:o,path:c,method:u,op:f,pathItem:a,globalSchemes:i,apiSecurity:n.security}))}const l=a.additionalOperations;if(l&&typeof l=="object")for(const[u,f]of Object.entries(l))!f||typeof f!="object"||e.push(D({apiId:s,apiTitle:o,path:c,method:u,op:f,pathItem:a,globalSchemes:i,apiSecurity:n.security}))}}return e}function ue(t){const e=[],n=[{list:t.queryParameters,loc:"query"},{list:t.headers,loc:"header"},{list:t.cookies,loc:"cookie"},{list:t.pathParameters,loc:"path"}];for(const{list:o,loc:s}of n)for(const i of o)if("key"in i){const r=i;e.push({name:r.key,in:s,required:!1})}return e}function Q(t){const e=t.id,n=t.info?.title??"Untitled Collection",o=g(t.info?.description??t.info?.summary??"");return{id:`collection:${e}`,text:$([n,o].filter(Boolean).join(" ")),payload:{type:"collection",id:`collection:${e}`,contentHash:"",title:n,description:o||void 0,collectionId:e}}}function X(t){const{collectionId:e,collectionTitle:n,workflow:o}=t,s=o.workflowId??"",i=o.summary??s,r=g(o.description??""),c=[n,i,r];if(o.inputs&&c.push(`Inputs schema: ${q(o.inputs)}`),o.outputs?.length){const a=o.outputs.map(p=>p.key).filter(Boolean);a.length&&c.push(`Outputs: ${a.join(", ")}`)}return o.dependsOn?.length&&c.push(`Depends on: ${o.dependsOn.join(", ")}`),{id:`workflow:${e}:${s}`,text:$(c.filter(Boolean).join(" ")),payload:{type:"workflow",id:`workflow:${e}:${s}`,contentHash:"",title:i,description:r||void 0,collectionId:e,workflowId:s}}}function K(t){const{collectionId:e,collectionTitle:n,workflowId:o,workflowTitle:s,step:i}=t,r=i.stepId??"",c=g(i.description??""),a=i.operation,p=i.xOperation,l=[n,s,`step: ${r}`];c&&l.push(c),a?(l.push(`${a.method?.toUpperCase()} ${a.path}`),a.apiId&&l.push(`API: ${a.apiId}`),a.operationId&&l.push(`operationId: ${a.operationId}`)):p&&l.push(`${p.method?.toUpperCase()} ${p.url}`);const u=i.parameters?ue(i.parameters):[];u.length>0&&l.push(`Parameters: ${u.map(U).join(". ")}.`),i.requestBody?.type&&l.push(`Request body type: ${i.requestBody.type}`);const m=(i.successCriteria??[]).map(h=>{let y=h.condition;return h.context&&(y+=` context: ${h.context}`),h.type&&(y+=` (${h.type})`),y});if(m.length>0&&l.push(`Success criteria: ${m.join("; ")}`),i.outputs?.length){const h=i.outputs.map(y=>`${y.key}=${y.value}`).filter(Boolean);h.length&&l.push(`Outputs: ${h.join(", ")}`)}const I=`step:${e}:${o}:${r}`;return{id:I,text:$(l.filter(Boolean).join(" ")),payload:{type:"step",id:I,contentHash:"",title:r,description:c||void 0,collectionId:e,workflowId:o,stepId:r,path:a?.path??p?.url,method:(a?.method??p?.method)?.toUpperCase(),apiId:a?.apiId,operationId:a?.operationId,parameterDetails:u.length>0?u:void 0,successCriteria:m.length>0?m:void 0,requestBodySchema:i.requestBody?.type?q(i.requestBody):void 0}}}function j(t){const e=[];for(const n of t){const o=n.id,s=n.info?.title??"Untitled Collection";e.push(Q(n));for(const i of n.workflows??[]){e.push(X({collectionId:o,collectionTitle:s,workflow:i}));const r=i.workflowId??"",c=i.summary??r;for(const a of i.steps??[])e.push(K({collectionId:o,collectionTitle:s,workflowId:r,workflowTitle:c,step:a}))}}return e}function Y(t,e){return[...T(t),...j(e)]}const N=10,pe=4;function H(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n)|0;return e>>>0}function fe(t){return d.bytesToHex(d.md5(t))}const he={};class me extends J.Observable{constructor(e){super(),this.collectionName=e}collectionName;activeIndexJobs=0;getIndexingActivityState(){return{inProgress:this.activeIndexJobs>0}}beginIndexJob(){this.activeIndexJobs++,this.activeIndexJobs===1&&this.emit("indexing-activity",{inProgress:!0})}endIndexJob(){this.activeIndexJobs=Math.max(0,this.activeIndexJobs-1),this.activeIndexJobs===0&&this.emit("indexing-activity",{inProgress:!1})}async getIdsByPayload(e,n){return d.invoke("semantic_search_get_ids_by_payload",{collectionName:this.collectionName,field:e,value:n})}async getAllIds(){return d.invoke("semantic_search_get_all_ids",{collectionName:this.collectionName})}async getScopeHashes(e){const n=e.apiIds??[],o=e.collectionIds??[];let s;if(n.length===0&&o.length===0)s=await this.getAllIds();else{const r=[];for(const a of n)r.push(this.getIdsByPayload("apiId",a));for(const a of o)r.push(this.getIdsByPayload("collectionId",a));s=(await Promise.all(r)).flat()}const i=new Map;for(const r of s)i.set(r.id,r.contentHash);return i}async indexDocuments(e,n){if(e.length===0&&!n)return{added:0,updated:0,removed:0,unchanged:0};const o=await this.getScopeHashes(n??{}),s=[],i=new Set;let r=0,c=0;for(const l of e){const u=fe(l.text);l.payload.contentHash=u,i.add(l.id);const f=o.get(l.id);f===u?c++:(f||r++,s.push(l))}const a=s.length-r,p=[];for(const l of o.keys())i.has(l)||p.push(l);if(p.length>0||s.length>0){this.beginIndexJob();try{p.length>0&&await this.deletePoints(p.map(H)),s.length>0&&await this.embedAndUpsert(s),await this.flush()}finally{this.endIndexJob()}}return{added:r,updated:a,removed:p.length,unchanged:c}}async removeByPayloadFilter(e,n){return d.invoke("semantic_search_delete_by_payload",{collectionName:this.collectionName,field:e,value:n})}async getStoredDocumentCount(){try{return(await d.invoke("plugin:velesdb|list_collections"))?.find(o=>o.name===this.collectionName)?.count??0}catch{return 0}}async getDocumentsByIds(e){if(e.length===0)return new Map;const n=e.map(H),o=await d.invoke("plugin:velesdb|get_points",{request:{collection:this.collectionName,ids:n}}),s=new Map;for(const i of o??[])if(i?.payload){const r=i.payload;r.id&&s.set(r.id,r)}return s}async embedAndUpsert(e){const n=[],o=e.length;for(let s=0;s<o;s+=N)n.push({docs:e.slice(s,s+N),index:Math.floor(s/N)});await ee.promiseMapLimit(n,pe,async s=>{const i=s.docs.map(r=>({id:r.id,text:r.text||r.payload.title,payload:r.payload}));await d.invoke("semantic_search_embed_and_upsert",{collectionName:this.collectionName,documents:i})})}async deletePoints(e){e.length!==0&&await d.invoke("plugin:velesdb|delete_points",{request:{collection:this.collectionName,ids:e}})}async flush(){await d.invoke("plugin:velesdb|flush",{name:this.collectionName}),await d.invoke("semantic_search_write_hnsw_marker",{collectionName:this.collectionName}).catch(()=>{})}}const z="replay_search",ye=384,w={added:0,updated:0,removed:0,unchanged:0};function k(t){return t.added+t.updated>0}class Z extends J.Observable{initialized=!1;projectId=null;indexer=null;indexQueue=Promise.resolve();get collectionName(){return this.projectId?`${z}_${this.projectId}`:z}createIndexer(){const e=new me(this.collectionName);return e.subscribe("indexing-activity",n=>{this.emit("indexing-activity",n)}),e}getIndexer(){return this.indexer||(this.indexer=this.createIndexer()),this.indexer}getIndexingActivityState(){return this.getIndexer().getIndexingActivityState()}async ensureInitialized(){this.initialized||await this.init()}enqueueIndex(e,n){const s=this.indexQueue.then(()=>e()).then(async i=>(n(i)&&await this.unloadModel(),i)).catch(async i=>{throw console.error("Semantic index:",i),await this.unloadModel(),i});return this.indexQueue=s.catch(()=>{}),s}async unloadModel(){try{await d.invoke("semantic_search_unload_model")}catch{}}setProject(e){this.projectId!==e&&(this.projectId=e,this.initialized=!1,this.indexer=this.createIndexer())}async init(){if(d.isTauriApp()&&!this.initialized){try{if((await d.invoke("plugin:velesdb|list_collections"))?.some(n=>n.name===this.collectionName)){this.initialized=!0;return}}catch{}await d.invoke("plugin:velesdb|create_collection",{request:{name:this.collectionName,dimension:ye,metric:"cosine",storage_mode:"full"}}),this.initialized=!0}}async indexApis(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer(),s=T(e),i={apiIds:e.map(r=>r.id)};return await this.ensureInitialized(),this.enqueueIndex(async()=>this.collectionName!==n?w:o.indexDocuments(s,i),k)}async indexCollections(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer(),s=j(e),i={collectionIds:e.map(r=>r.id)};return await this.ensureInitialized(),this.enqueueIndex(async()=>this.collectionName!==n?w:o.indexDocuments(s,i),k)}async removeApi(e){if(!d.isTauriApp())return;const n=this.getIndexer();await this.ensureInitialized(),await this.enqueueIndex(()=>n.removeByPayloadFilter("apiId",e),()=>!1)}async removeCollection(e){if(!d.isTauriApp())return;const n=this.getIndexer();await this.ensureInitialized(),await this.enqueueIndex(()=>n.removeByPayloadFilter("collectionId",e),()=>!1)}async reindex(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer();return await this.ensureInitialized(),this.enqueueIndex(async()=>{if(this.collectionName!==n)return w;const{apis:s,collections:i}=e(),r=Y(s,i);return o.indexDocuments(r,he)},k)}async search(e,n=10,o){if(!d.isTauriApp())return[];try{await this.ensureInitialized();const s=o&&Object.keys(o).length>0?{type:o.type,apiId:o.apiId,collectionId:o.collectionId,path:o.path,method:o.method,operationId:o.operationId,workflowId:o.workflowId,stepId:o.stepId}:void 0,r=((await d.invoke("semantic_search_text",{collection:this.collectionName,query:e,topK:n,filters:s})).results??[]).map(c=>({...c.payload,score:c.score??0}));return await this.enrichWithRelatedSecurity(r),r}catch{return[]}}async enrichWithRelatedSecurity(e){const n=e.filter(i=>i.type==="api_operation"&&i.securitySchemeRefs?.length);if(n.length===0)return;const o=[...new Set(n.flatMap(i=>i.securitySchemeRefs??[]))],s=await this.getIndexer().getDocumentsByIds(o);for(const i of n){const r=[];for(const c of i.securitySchemeRefs??[]){const a=s.get(c);a?.securityScheme&&r.push(a.securityScheme)}r.length>0&&(i.relatedSecuritySchemes=r)}}async status(){if(!d.isTauriApp())return{indexed:0,modelLoaded:!1};const e=await this.getIndexer().getStoredDocumentCount();let n=!1;try{n=(await d.invoke("semantic_search_model_status")).loaded}catch{}return{indexed:e,modelLoaded:n}}async clear(){if(!(!d.isTauriApp()||!this.initialized))try{await d.invoke("plugin:velesdb|delete_collection",{name:this.collectionName}),this.initialized=!1}catch{}}async preloadModel(){if(d.isTauriApp())try{await d.invoke("semantic_search_preload_model")}catch{}}}let O=null;function xe(){return O||(O=new Z),O}exports.SemanticSearchService=Z;exports.extractAllDocuments=Y;exports.extractApiDocument=W;exports.extractApiDocuments=T;exports.extractCollectionDocument=Q;exports.extractCollectionDocuments=j;exports.extractGlobalSecuritySchemes=G;exports.extractOperationDocument=D;exports.extractStepDocument=K;exports.extractWorkflowDocument=X;exports.getSemanticSearchService=xe;
@@ -1,4 +1,4 @@
1
- import { i as f, aP as W, aQ as X, aN as y } from "./replay-index-B2RZCGOF.js";
1
+ import { i as f, aQ as W, aR as X, aO as y } from "./replay-index-BizzVzWT.js";
2
2
  import { O as z } from "./replay-Observable-D6wKbFwB.js";
3
3
  import { p as K } from "./replay-promise-map-limit-Db_42GvV.js";
4
4
  function w(t) {
@@ -1,4 +1,4 @@
1
- import { i as Qe } from "./replay-index-B2RZCGOF.js";
1
+ import { i as Qe } from "./replay-index-BizzVzWT.js";
2
2
  import { h as Ve } from "./replay-history.schema-5ce6X0R1.js";
3
3
  import { s as We } from "./replay-step-context.schema-DBk4jufr.js";
4
4
  import { b as J, c as X, a as ee } from "./replay-ai-message-parts.schema-E9u9-nqr.js";
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ie=require("./replay-index-D85qPcEF.js"),Te=require("./replay-history.schema-miM3Etuf.js"),Qe=require("./replay-step-context.schema-BuuXkAck.js"),C=require("./replay-ai-message-parts.schema-BBdjwldJ.js"),t=require("./replay-indexes-Dqjl8m6C.js");class Ce{static[t.entityKind]="ConsoleLogWriter";write(e){console.log(e)}}class ve{static[t.entityKind]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new Ce}logQuery(e,s){const i=s.map(n=>{try{return JSON.stringify(n)}catch{return String(n)}}),r=i.length?` -- params: [${i.join(", ")}]`:"";this.writer.write(`Query: ${e}${r}`)}}class Le{static[t.entityKind]="NoopLogger";logQuery(){}}const re=Symbol.for("drizzle:PgInlineForeignKeys"),ne=Symbol.for("drizzle:EnableRLS");class $e extends t.Table{static[t.entityKind]="PgTable";static Symbol=Object.assign({},t.Table.Symbol,{InlineForeignKeys:re,EnableRLS:ne});[re]=[];[ne]=!1;[t.Table.Symbol.ExtraConfigBuilder]=void 0;[t.Table.Symbol.ExtraConfigColumns]={}}class Ne{static[t.entityKind]="PgPrimaryKeyBuilder";columns;name;constructor(e,s){this.columns=e,this.name=s}build(e){return new xe(e,this.columns,this.name)}}class xe{constructor(e,s,i){this.table=e,this.columns=s,this.name=i}static[t.entityKind]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[$e.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}}class de{constructor(e,s,i){this.sourceTable=e,this.referencedTable=s,this.relationName=i,this.referencedTableName=s[t.Table.Symbol.Name]}static[t.entityKind]="Relation";referencedTableName;fieldName}class fe{constructor(e,s){this.table=e,this.config=s}static[t.entityKind]="Relations"}class A extends de{constructor(e,s,i,r){super(e,s,i?.relationName),this.config=i,this.isNullable=r}static[t.entityKind]="One";withFieldName(e){const s=new A(this.sourceTable,this.referencedTable,this.config,this.isNullable);return s.fieldName=e,s}}class J extends de{constructor(e,s,i){super(e,s,i?.relationName),this.config=i}static[t.entityKind]="Many";withFieldName(e){const s=new J(this.sourceTable,this.referencedTable,this.config);return s.fieldName=e,s}}function Re(){return{and:t.and,between:t.between,eq:t.eq,exists:t.exists,gt:t.gt,gte:t.gte,ilike:t.ilike,inArray:t.inArray,isNull:t.isNull,isNotNull:t.isNotNull,like:t.like,lt:t.lt,lte:t.lte,ne:t.ne,not:t.not,notBetween:t.notBetween,notExists:t.notExists,notLike:t.notLike,notIlike:t.notIlike,notInArray:t.notInArray,or:t.or,sql:t.sql}}function Be(){return{sql:t.sql,asc:t.asc,desc:t.desc}}function _e(o,e){Object.keys(o).length===1&&"default"in o&&!t.is(o.default,t.Table)&&(o=o.default);const s={},i={},r={};for(const[n,a]of Object.entries(o))if(t.is(a,t.Table)){const l=t.getTableUniqueName(a),c=i[l];s[l]=n,r[n]={tsName:n,dbName:a[t.Table.Symbol.Name],schema:a[t.Table.Symbol.Schema],columns:a[t.Table.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(const h of Object.values(a[t.Table.Symbol.Columns]))h.primary&&r[n].primaryKey.push(h);const u=a[t.Table.Symbol.ExtraConfigBuilder]?.(a[t.Table.Symbol.ExtraConfigColumns]);if(u)for(const h of Object.values(u))t.is(h,Ne)&&r[n].primaryKey.push(...h.columns)}else if(t.is(a,fe)){const l=t.getTableUniqueName(a.table),c=s[l],u=a.config(e(a.table));let h;for(const[f,w]of Object.entries(u))if(c){const q=r[c];q.relations[f]=w}else l in i||(i[l]={relations:{},primaryKey:h}),i[l].relations[f]=w}return{tables:r,tableNamesMap:s}}function Z(o,e){return new fe(o,s=>Object.fromEntries(Object.entries(e(s)).map(([i,r])=>[i,r.withFieldName(i)])))}function Oe(o){return function(s,i){return new A(o,s,i,i?.fields.reduce((r,n)=>r&&n.notNull,!0)??!1)}}function Me(o){return function(s,i){return new J(o,s,i)}}function Ae(o,e,s){if(t.is(s,A)&&s.config)return{fields:s.config.fields,references:s.config.references};const i=e[t.getTableUniqueName(s.referencedTable)];if(!i)throw new Error(`Table "${s.referencedTable[t.Table.Symbol.Name]}" not found in schema`);const r=o[i];if(!r)throw new Error(`Table "${i}" not found in schema`);const n=s.sourceTable,a=e[t.getTableUniqueName(n)];if(!a)throw new Error(`Table "${n[t.Table.Symbol.Name]}" not found in schema`);const l=[];for(const c of Object.values(r.relations))(s.relationName&&s!==c&&c.relationName===s.relationName||!s.relationName&&c.referencedTable===s.sourceTable)&&l.push(c);if(l.length>1)throw s.relationName?new Error(`There are multiple relations with name "${s.relationName}" in table "${i}"`):new Error(`There are multiple relations between "${i}" and "${s.sourceTable[t.Table.Symbol.Name]}". Please specify relation name`);if(l[0]&&t.is(l[0],A)&&l[0].config)return{fields:l[0].config.references,references:l[0].config.fields};throw new Error(`There is not enough information to infer relation "${a}.${s.fieldName}"`)}function Ke(o){return{one:Oe(o),many:Me(o)}}function Y(o,e,s,i,r=n=>n){const n={};for(const[a,l]of i.entries())if(l.isJson){const c=e.relations[l.tsKey],u=s[a],h=typeof u=="string"?JSON.parse(u):u;n[l.tsKey]=t.is(c,A)?h&&Y(o,o[l.relationTableTsKey],h,l.selection,r):h.map(f=>Y(o,o[l.relationTableTsKey],f,l.selection,r))}else{const c=r(s[a]),u=l.field;let h;t.is(u,t.Column)?h=u:t.is(u,t.SQL)?h=u.decoder:h=u.sql.decoder,n[l.tsKey]=c===null?null:h.mapFromDriverValue(c)}return n}class I{constructor(e){this.table=e}static[t.entityKind]="ColumnAliasProxyHandler";get(e,s){return s==="table"?this.table:e[s]}}class X{constructor(e,s){this.alias=e,this.replaceOriginalName=s}static[t.entityKind]="TableAliasProxyHandler";get(e,s){if(s===t.Table.Symbol.IsAlias)return!0;if(s===t.Table.Symbol.Name)return this.alias;if(this.replaceOriginalName&&s===t.Table.Symbol.OriginalName)return this.alias;if(s===t.ViewBaseConfig)return{...e[t.ViewBaseConfig],name:this.alias,isAlias:!0};if(s===t.Table.Symbol.Columns){const r=e[t.Table.Symbol.Columns];if(!r)return r;const n={};return Object.keys(r).map(a=>{n[a]=new Proxy(r[a],new I(new Proxy(e,this)))}),n}const i=e[s];return t.is(i,t.Column)?new Proxy(i,new I(new Proxy(e,this))):i}}function H(o,e){return new Proxy(o,new X(e,!1))}function B(o,e){return new Proxy(o,new I(new Proxy(o.table,new X(e,!1))))}function me(o,e){return new t.SQL.Aliased(k(o.sql,e),o.fieldAlias)}function k(o,e){return t.sql.join(o.queryChunks.map(s=>t.is(s,t.Column)?B(s,e):t.is(s,t.SQL)?k(s,e):t.is(s,t.SQL.Aliased)?me(s,e):s))}class Q{static[t.entityKind]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,s){if(s==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(s===t.ViewBaseConfig)return{...e[t.ViewBaseConfig],selectedFields:new Proxy(e[t.ViewBaseConfig].selectedFields,this)};if(typeof s=="symbol")return e[s];const r=(t.is(e,t.Subquery)?e._.selectedFields:t.is(e,t.View)?e[t.ViewBaseConfig].selectedFields:e)[s];if(t.is(r,t.SQL.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!r.isSelectionField)return r.sql;const n=r.clone();return n.isSelectionField=!0,n}if(t.is(r,t.SQL)){if(this.config.sqlBehavior==="sql")return r;throw new Error(`You tried to reference "${s}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return t.is(r,t.Column)?this.config.alias?new Proxy(r,new I(new Proxy(r.table,new X(this.config.alias,this.config.replaceOriginalName??!1)))):r:typeof r!="object"||r===null?r:new Proxy(r,new Q(this.config))}}class K{static[t.entityKind]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(s=>(e?.(),s),s=>{throw e?.(),s})}then(e,s){return this.execute().then(e,s)}}function M(o){return t.is(o,t.SQLiteTable)?[`${o[t.Table.Symbol.BaseName]}`]:t.is(o,t.Subquery)?o._.usedTables??[]:t.is(o,t.SQL)?o.usedTables??[]:[]}class ae extends K{constructor(e,s,i,r){super(),this.table=e,this.session=s,this.dialect=i,this.config={table:e,withList:r}}static[t.entityKind]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]=="function"){const s=e[0](new Proxy(this.config.table[t.Table.Symbol.Columns],new Q({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),i=Array.isArray(s)?s:[s];this.config.orderBy=i}else{const s=e;this.config.orderBy=s}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[t.SQLiteTable.Symbol.Columns]){return this.config.returning=t.orderSelectedFields(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){const{typings:e,...s}=this.dialect.sqlToQuery(this.getSQL());return s}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:M(this.config.table)})}prepare(){return this._prepare(!1)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(e){return this._prepare().execute(e)}$dynamic(){return this}}function Pe(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(s=>s.toLowerCase()).join("_")}function je(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((s,i,r)=>{const n=r===0?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`;return s+n},"")}function Ee(o){return o}class Fe{static[t.entityKind]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Pe:e==="camelCase"?je:Ee}getColumnCasing(e){if(!e.keyAsName)return e.name;const s=e.table[t.Table.Symbol.Schema]??"public",i=e.table[t.Table.Symbol.OriginalName],r=`${s}.${i}.${e.name}`;return this.cache[r]||this.cacheTable(e.table),this.cache[r]}cacheTable(e){const s=e[t.Table.Symbol.Schema]??"public",i=e[t.Table.Symbol.OriginalName],r=`${s}.${i}`;if(!this.cachedTables[r]){for(const n of Object.values(e[t.Table.Symbol.Columns])){const a=`${r}.${n.name}`;this.cache[a]=this.convert(n.name)}this.cachedTables[r]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class ee extends Error{static[t.entityKind]="DrizzleError";constructor({message:e,cause:s}){super(e),this.name="DrizzleError",this.cause=s}}class _ extends Error{constructor(e,s,i){super(`Failed query: ${e}
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ie=require("./replay-index-D3evrr0U.js"),Te=require("./replay-history.schema-miM3Etuf.js"),Qe=require("./replay-step-context.schema-BuuXkAck.js"),C=require("./replay-ai-message-parts.schema-BBdjwldJ.js"),t=require("./replay-indexes-Dqjl8m6C.js");class Ce{static[t.entityKind]="ConsoleLogWriter";write(e){console.log(e)}}class ve{static[t.entityKind]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new Ce}logQuery(e,s){const i=s.map(n=>{try{return JSON.stringify(n)}catch{return String(n)}}),r=i.length?` -- params: [${i.join(", ")}]`:"";this.writer.write(`Query: ${e}${r}`)}}class Le{static[t.entityKind]="NoopLogger";logQuery(){}}const re=Symbol.for("drizzle:PgInlineForeignKeys"),ne=Symbol.for("drizzle:EnableRLS");class $e extends t.Table{static[t.entityKind]="PgTable";static Symbol=Object.assign({},t.Table.Symbol,{InlineForeignKeys:re,EnableRLS:ne});[re]=[];[ne]=!1;[t.Table.Symbol.ExtraConfigBuilder]=void 0;[t.Table.Symbol.ExtraConfigColumns]={}}class Ne{static[t.entityKind]="PgPrimaryKeyBuilder";columns;name;constructor(e,s){this.columns=e,this.name=s}build(e){return new xe(e,this.columns,this.name)}}class xe{constructor(e,s,i){this.table=e,this.columns=s,this.name=i}static[t.entityKind]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[$e.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}}class de{constructor(e,s,i){this.sourceTable=e,this.referencedTable=s,this.relationName=i,this.referencedTableName=s[t.Table.Symbol.Name]}static[t.entityKind]="Relation";referencedTableName;fieldName}class fe{constructor(e,s){this.table=e,this.config=s}static[t.entityKind]="Relations"}class A extends de{constructor(e,s,i,r){super(e,s,i?.relationName),this.config=i,this.isNullable=r}static[t.entityKind]="One";withFieldName(e){const s=new A(this.sourceTable,this.referencedTable,this.config,this.isNullable);return s.fieldName=e,s}}class J extends de{constructor(e,s,i){super(e,s,i?.relationName),this.config=i}static[t.entityKind]="Many";withFieldName(e){const s=new J(this.sourceTable,this.referencedTable,this.config);return s.fieldName=e,s}}function Re(){return{and:t.and,between:t.between,eq:t.eq,exists:t.exists,gt:t.gt,gte:t.gte,ilike:t.ilike,inArray:t.inArray,isNull:t.isNull,isNotNull:t.isNotNull,like:t.like,lt:t.lt,lte:t.lte,ne:t.ne,not:t.not,notBetween:t.notBetween,notExists:t.notExists,notLike:t.notLike,notIlike:t.notIlike,notInArray:t.notInArray,or:t.or,sql:t.sql}}function Be(){return{sql:t.sql,asc:t.asc,desc:t.desc}}function _e(o,e){Object.keys(o).length===1&&"default"in o&&!t.is(o.default,t.Table)&&(o=o.default);const s={},i={},r={};for(const[n,a]of Object.entries(o))if(t.is(a,t.Table)){const l=t.getTableUniqueName(a),c=i[l];s[l]=n,r[n]={tsName:n,dbName:a[t.Table.Symbol.Name],schema:a[t.Table.Symbol.Schema],columns:a[t.Table.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(const h of Object.values(a[t.Table.Symbol.Columns]))h.primary&&r[n].primaryKey.push(h);const u=a[t.Table.Symbol.ExtraConfigBuilder]?.(a[t.Table.Symbol.ExtraConfigColumns]);if(u)for(const h of Object.values(u))t.is(h,Ne)&&r[n].primaryKey.push(...h.columns)}else if(t.is(a,fe)){const l=t.getTableUniqueName(a.table),c=s[l],u=a.config(e(a.table));let h;for(const[f,w]of Object.entries(u))if(c){const q=r[c];q.relations[f]=w}else l in i||(i[l]={relations:{},primaryKey:h}),i[l].relations[f]=w}return{tables:r,tableNamesMap:s}}function Z(o,e){return new fe(o,s=>Object.fromEntries(Object.entries(e(s)).map(([i,r])=>[i,r.withFieldName(i)])))}function Oe(o){return function(s,i){return new A(o,s,i,i?.fields.reduce((r,n)=>r&&n.notNull,!0)??!1)}}function Me(o){return function(s,i){return new J(o,s,i)}}function Ae(o,e,s){if(t.is(s,A)&&s.config)return{fields:s.config.fields,references:s.config.references};const i=e[t.getTableUniqueName(s.referencedTable)];if(!i)throw new Error(`Table "${s.referencedTable[t.Table.Symbol.Name]}" not found in schema`);const r=o[i];if(!r)throw new Error(`Table "${i}" not found in schema`);const n=s.sourceTable,a=e[t.getTableUniqueName(n)];if(!a)throw new Error(`Table "${n[t.Table.Symbol.Name]}" not found in schema`);const l=[];for(const c of Object.values(r.relations))(s.relationName&&s!==c&&c.relationName===s.relationName||!s.relationName&&c.referencedTable===s.sourceTable)&&l.push(c);if(l.length>1)throw s.relationName?new Error(`There are multiple relations with name "${s.relationName}" in table "${i}"`):new Error(`There are multiple relations between "${i}" and "${s.sourceTable[t.Table.Symbol.Name]}". Please specify relation name`);if(l[0]&&t.is(l[0],A)&&l[0].config)return{fields:l[0].config.references,references:l[0].config.fields};throw new Error(`There is not enough information to infer relation "${a}.${s.fieldName}"`)}function Ke(o){return{one:Oe(o),many:Me(o)}}function Y(o,e,s,i,r=n=>n){const n={};for(const[a,l]of i.entries())if(l.isJson){const c=e.relations[l.tsKey],u=s[a],h=typeof u=="string"?JSON.parse(u):u;n[l.tsKey]=t.is(c,A)?h&&Y(o,o[l.relationTableTsKey],h,l.selection,r):h.map(f=>Y(o,o[l.relationTableTsKey],f,l.selection,r))}else{const c=r(s[a]),u=l.field;let h;t.is(u,t.Column)?h=u:t.is(u,t.SQL)?h=u.decoder:h=u.sql.decoder,n[l.tsKey]=c===null?null:h.mapFromDriverValue(c)}return n}class I{constructor(e){this.table=e}static[t.entityKind]="ColumnAliasProxyHandler";get(e,s){return s==="table"?this.table:e[s]}}class X{constructor(e,s){this.alias=e,this.replaceOriginalName=s}static[t.entityKind]="TableAliasProxyHandler";get(e,s){if(s===t.Table.Symbol.IsAlias)return!0;if(s===t.Table.Symbol.Name)return this.alias;if(this.replaceOriginalName&&s===t.Table.Symbol.OriginalName)return this.alias;if(s===t.ViewBaseConfig)return{...e[t.ViewBaseConfig],name:this.alias,isAlias:!0};if(s===t.Table.Symbol.Columns){const r=e[t.Table.Symbol.Columns];if(!r)return r;const n={};return Object.keys(r).map(a=>{n[a]=new Proxy(r[a],new I(new Proxy(e,this)))}),n}const i=e[s];return t.is(i,t.Column)?new Proxy(i,new I(new Proxy(e,this))):i}}function H(o,e){return new Proxy(o,new X(e,!1))}function B(o,e){return new Proxy(o,new I(new Proxy(o.table,new X(e,!1))))}function me(o,e){return new t.SQL.Aliased(k(o.sql,e),o.fieldAlias)}function k(o,e){return t.sql.join(o.queryChunks.map(s=>t.is(s,t.Column)?B(s,e):t.is(s,t.SQL)?k(s,e):t.is(s,t.SQL.Aliased)?me(s,e):s))}class Q{static[t.entityKind]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,s){if(s==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(s===t.ViewBaseConfig)return{...e[t.ViewBaseConfig],selectedFields:new Proxy(e[t.ViewBaseConfig].selectedFields,this)};if(typeof s=="symbol")return e[s];const r=(t.is(e,t.Subquery)?e._.selectedFields:t.is(e,t.View)?e[t.ViewBaseConfig].selectedFields:e)[s];if(t.is(r,t.SQL.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!r.isSelectionField)return r.sql;const n=r.clone();return n.isSelectionField=!0,n}if(t.is(r,t.SQL)){if(this.config.sqlBehavior==="sql")return r;throw new Error(`You tried to reference "${s}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return t.is(r,t.Column)?this.config.alias?new Proxy(r,new I(new Proxy(r.table,new X(this.config.alias,this.config.replaceOriginalName??!1)))):r:typeof r!="object"||r===null?r:new Proxy(r,new Q(this.config))}}class K{static[t.entityKind]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(s=>(e?.(),s),s=>{throw e?.(),s})}then(e,s){return this.execute().then(e,s)}}function M(o){return t.is(o,t.SQLiteTable)?[`${o[t.Table.Symbol.BaseName]}`]:t.is(o,t.Subquery)?o._.usedTables??[]:t.is(o,t.SQL)?o.usedTables??[]:[]}class ae extends K{constructor(e,s,i,r){super(),this.table=e,this.session=s,this.dialect=i,this.config={table:e,withList:r}}static[t.entityKind]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]=="function"){const s=e[0](new Proxy(this.config.table[t.Table.Symbol.Columns],new Q({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),i=Array.isArray(s)?s:[s];this.config.orderBy=i}else{const s=e;this.config.orderBy=s}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[t.SQLiteTable.Symbol.Columns]){return this.config.returning=t.orderSelectedFields(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){const{typings:e,...s}=this.dialect.sqlToQuery(this.getSQL());return s}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:M(this.config.table)})}prepare(){return this._prepare(!1)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(e){return this._prepare().execute(e)}$dynamic(){return this}}function Pe(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(s=>s.toLowerCase()).join("_")}function je(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((s,i,r)=>{const n=r===0?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`;return s+n},"")}function Ee(o){return o}class Fe{static[t.entityKind]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Pe:e==="camelCase"?je:Ee}getColumnCasing(e){if(!e.keyAsName)return e.name;const s=e.table[t.Table.Symbol.Schema]??"public",i=e.table[t.Table.Symbol.OriginalName],r=`${s}.${i}.${e.name}`;return this.cache[r]||this.cacheTable(e.table),this.cache[r]}cacheTable(e){const s=e[t.Table.Symbol.Schema]??"public",i=e[t.Table.Symbol.OriginalName],r=`${s}.${i}`;if(!this.cachedTables[r]){for(const n of Object.values(e[t.Table.Symbol.Columns])){const a=`${r}.${n.name}`;this.cache[a]=this.convert(n.name)}this.cachedTables[r]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class ee extends Error{static[t.entityKind]="DrizzleError";constructor({message:e,cause:s}){super(e),this.name="DrizzleError",this.cause=s}}class _ extends Error{constructor(e,s,i){super(`Failed query: ${e}
2
2
  params: ${s}`),this.query=e,this.params=s,this.cause=i,Error.captureStackTrace(this,_),i&&(this.cause=i)}}class Ie extends ee{static[t.entityKind]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class te extends t.View{static[t.entityKind]="SQLiteViewBase"}class D{static[t.entityKind]="SQLiteDialect";casing;constructor(e){this.casing=new Fe(e?.casing)}escapeName(e){return`"${e.replace(/"/g,'""')}"`}escapeParam(e){return"?"}escapeString(e){return`'${e.replace(/'/g,"''")}'`}buildWithCTE(e){if(!e?.length)return;const s=[t.sql`with `];for(const[i,r]of e.entries())s.push(t.sql`${t.sql.identifier(r._.alias)} as (${r._.sql})`),i<e.length-1&&s.push(t.sql`, `);return s.push(t.sql` `),t.sql.join(s)}buildDeleteQuery({table:e,where:s,returning:i,withList:r,limit:n,orderBy:a}){const l=this.buildWithCTE(r),c=i?t.sql` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,u=s?t.sql` where ${s}`:void 0,h=this.buildOrderBy(a),f=this.buildLimit(n);return t.sql`${l}delete from ${e}${u}${c}${h}${f}`}buildUpdateSet(e,s){const i=e[t.Table.Symbol.Columns],r=Object.keys(i).filter(a=>s[a]!==void 0||i[a]?.onUpdateFn!==void 0),n=r.length;return t.sql.join(r.flatMap((a,l)=>{const c=i[a],u=c.onUpdateFn?.(),h=s[a]??(t.is(u,t.SQL)?u:t.sql.param(u,c)),f=t.sql`${t.sql.identifier(this.casing.getColumnCasing(c))} = ${h}`;return l<n-1?[f,t.sql.raw(", ")]:[f]}))}buildUpdateQuery({table:e,set:s,where:i,returning:r,withList:n,joins:a,from:l,limit:c,orderBy:u}){const h=this.buildWithCTE(n),f=this.buildUpdateSet(e,s),w=l&&t.sql.join([t.sql.raw(" from "),this.buildFromTable(l)]),q=this.buildJoins(a),S=r?t.sql` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,g=i?t.sql` where ${i}`:void 0,p=this.buildOrderBy(u),b=this.buildLimit(c);return t.sql`${h}update ${e} set ${f}${w}${q}${g}${S}${p}${b}`}buildSelection(e,{isSingleTable:s=!1}={}){const i=e.length,r=e.flatMap(({field:n},a)=>{const l=[];if(t.is(n,t.SQL.Aliased)&&n.isSelectionField)l.push(t.sql.identifier(n.fieldAlias));else if(t.is(n,t.SQL.Aliased)||t.is(n,t.SQL)){const c=t.is(n,t.SQL.Aliased)?n.sql:n;s?l.push(new t.SQL(c.queryChunks.map(u=>t.is(u,t.Column)?t.sql.identifier(this.casing.getColumnCasing(u)):u))):l.push(c),t.is(n,t.SQL.Aliased)&&l.push(t.sql` as ${t.sql.identifier(n.fieldAlias)}`)}else if(t.is(n,t.Column)){const c=n.table[t.Table.Symbol.Name];n.columnType==="SQLiteNumericBigInt"?s?l.push(t.sql`cast(${t.sql.identifier(this.casing.getColumnCasing(n))} as text)`):l.push(t.sql`cast(${t.sql.identifier(c)}.${t.sql.identifier(this.casing.getColumnCasing(n))} as text)`):s?l.push(t.sql.identifier(this.casing.getColumnCasing(n))):l.push(t.sql`${t.sql.identifier(c)}.${t.sql.identifier(this.casing.getColumnCasing(n))}`)}else if(t.is(n,t.Subquery)){const c=Object.entries(n._.selectedFields);if(c.length===1){const u=c[0][1],h=t.is(u,t.SQL)?u.decoder:t.is(u,t.Column)?{mapFromDriverValue:f=>u.mapFromDriverValue(f)}:u.sql.decoder;h&&(n._.sql.decoder=h)}l.push(n)}return a<i-1&&l.push(t.sql`, `),l});return t.sql.join(r)}buildJoins(e){if(!e||e.length===0)return;const s=[];if(e)for(const[i,r]of e.entries()){i===0&&s.push(t.sql` `);const n=r.table,a=r.on?t.sql` on ${r.on}`:void 0;if(t.is(n,t.SQLiteTable)){const l=n[t.SQLiteTable.Symbol.Name],c=n[t.SQLiteTable.Symbol.Schema],u=n[t.SQLiteTable.Symbol.OriginalName],h=l===u?void 0:r.alias;s.push(t.sql`${t.sql.raw(r.joinType)} join ${c?t.sql`${t.sql.identifier(c)}.`:void 0}${t.sql.identifier(u)}${h&&t.sql` ${t.sql.identifier(h)}`}${a}`)}else s.push(t.sql`${t.sql.raw(r.joinType)} join ${n}${a}`);i<e.length-1&&s.push(t.sql` `)}return t.sql.join(s)}buildLimit(e){return typeof e=="object"||typeof e=="number"&&e>=0?t.sql` limit ${e}`:void 0}buildOrderBy(e){const s=[];if(e)for(const[i,r]of e.entries())s.push(r),i<e.length-1&&s.push(t.sql`, `);return s.length>0?t.sql` order by ${t.sql.join(s)}`:void 0}buildFromTable(e){return t.is(e,t.Table)&&e[t.Table.Symbol.IsAlias]?t.sql`${t.sql`${t.sql.identifier(e[t.Table.Symbol.Schema]??"")}.`.if(e[t.Table.Symbol.Schema])}${t.sql.identifier(e[t.Table.Symbol.OriginalName])} ${t.sql.identifier(e[t.Table.Symbol.Name])}`:e}buildSelectQuery({withList:e,fields:s,fieldsFlat:i,where:r,having:n,table:a,joins:l,orderBy:c,groupBy:u,limit:h,offset:f,distinct:w,setOperators:q}){const S=i??t.orderSelectedFields(s);for(const $ of S)if(t.is($.field,t.Column)&&t.getTableName($.field.table)!==(t.is(a,t.Subquery)?a._.alias:t.is(a,te)?a[t.ViewBaseConfig].name:t.is(a,t.SQL)?void 0:t.getTableName(a))&&!(N=>l?.some(({alias:E})=>E===(N[t.Table.Symbol.IsAlias]?t.getTableName(N):N[t.Table.Symbol.BaseName])))($.field.table)){const N=t.getTableName($.field.table);throw new Error(`Your "${$.path.join("->")}" field references a column "${N}"."${$.field.name}", but the table "${N}" is not part of the query! Did you forget to join it?`)}const g=!l||l.length===0,p=this.buildWithCTE(e),b=w?t.sql` distinct`:void 0,v=this.buildSelection(S,{isSingleTable:g}),T=this.buildFromTable(a),m=this.buildJoins(l),x=r?t.sql` where ${r}`:void 0,L=n?t.sql` having ${n}`:void 0,d=[];if(u)for(const[$,N]of u.entries())d.push(N),$<u.length-1&&d.push(t.sql`, `);const y=d.length>0?t.sql` group by ${t.sql.join(d)}`:void 0,R=this.buildOrderBy(c),j=this.buildLimit(h),W=f?t.sql` offset ${f}`:void 0,P=t.sql`${p}select${b} ${v} from ${T}${m}${x}${y}${L}${R}${j}${W}`;return q.length>0?this.buildSetOperations(P,q):P}buildSetOperations(e,s){const[i,...r]=s;if(!i)throw new Error("Cannot pass undefined values to any set operator");return r.length===0?this.buildSetOperationQuery({leftSelect:e,setOperator:i}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:i}),r)}buildSetOperationQuery({leftSelect:e,setOperator:{type:s,isAll:i,rightSelect:r,limit:n,orderBy:a,offset:l}}){const c=t.sql`${e.getSQL()} `,u=t.sql`${r.getSQL()}`;let h;if(a&&a.length>0){const S=[];for(const g of a)if(t.is(g,t.SQLiteColumn))S.push(t.sql.identifier(g.name));else if(t.is(g,t.SQL)){for(let p=0;p<g.queryChunks.length;p++){const b=g.queryChunks[p];t.is(b,t.SQLiteColumn)&&(g.queryChunks[p]=t.sql.identifier(this.casing.getColumnCasing(b)))}S.push(t.sql`${g}`)}else S.push(t.sql`${g}`);h=t.sql` order by ${t.sql.join(S,t.sql`, `)}`}const f=typeof n=="object"||typeof n=="number"&&n>=0?t.sql` limit ${n}`:void 0,w=t.sql.raw(`${s} ${i?"all ":""}`),q=l?t.sql` offset ${l}`:void 0;return t.sql`${c}${w}${u}${h}${f}${q}`}buildInsertQuery({table:e,values:s,onConflict:i,returning:r,withList:n,select:a}){const l=[],c=e[t.Table.Symbol.Columns],u=Object.entries(c).filter(([g,p])=>!p.shouldDisableInsert()),h=u.map(([,g])=>t.sql.identifier(this.casing.getColumnCasing(g)));if(a){const g=s;t.is(g,t.SQL)?l.push(g):l.push(g.getSQL())}else{const g=s;l.push(t.sql.raw("values "));for(const[p,b]of g.entries()){const v=[];for(const[T,m]of u){const x=b[T];if(x===void 0||t.is(x,t.Param)&&x.value===void 0){let L;if(m.default!==null&&m.default!==void 0)L=t.is(m.default,t.SQL)?m.default:t.sql.param(m.default,m);else if(m.defaultFn!==void 0){const d=m.defaultFn();L=t.is(d,t.SQL)?d:t.sql.param(d,m)}else if(!m.default&&m.onUpdateFn!==void 0){const d=m.onUpdateFn();L=t.is(d,t.SQL)?d:t.sql.param(d,m)}else L=t.sql`null`;v.push(L)}else v.push(x)}l.push(v),p<g.length-1&&l.push(t.sql`, `)}}const f=this.buildWithCTE(n),w=t.sql.join(l),q=r?t.sql` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,S=i?.length?t.sql.join(i):void 0;return t.sql`${f}insert into ${e} ${h} ${w}${S}${q}`}sqlToQuery(e,s){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:s})}buildRelationalQuery({fullSchema:e,schema:s,tableNamesMap:i,table:r,tableConfig:n,queryConfig:a,tableAlias:l,nestedQueryRelation:c,joinOn:u}){let h=[],f,w,q=[],S;const g=[];if(a===!0)h=Object.entries(n.columns).map(([v,T])=>({dbKey:T.name,tsKey:v,field:B(T,l),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{const b=Object.fromEntries(Object.entries(n.columns).map(([d,y])=>[d,B(y,l)]));if(a.where){const d=typeof a.where=="function"?a.where(b,Re()):a.where;S=d&&k(d,l)}const v=[];let T=[];if(a.columns){let d=!1;for(const[y,R]of Object.entries(a.columns))R!==void 0&&y in n.columns&&(!d&&R===!0&&(d=!0),T.push(y));T.length>0&&(T=d?T.filter(y=>a.columns?.[y]===!0):Object.keys(n.columns).filter(y=>!T.includes(y)))}else T=Object.keys(n.columns);for(const d of T){const y=n.columns[d];v.push({tsKey:d,value:y})}let m=[];a.with&&(m=Object.entries(a.with).filter(d=>!!d[1]).map(([d,y])=>({tsKey:d,queryConfig:y,relation:n.relations[d]})));let x;if(a.extras){x=typeof a.extras=="function"?a.extras(b,{sql:t.sql}):a.extras;for(const[d,y]of Object.entries(x))v.push({tsKey:d,value:me(y,l)})}for(const{tsKey:d,value:y}of v)h.push({dbKey:t.is(y,t.SQL.Aliased)?y.fieldAlias:n.columns[d].name,tsKey:d,field:t.is(y,t.Column)?B(y,l):y,relationTableTsKey:void 0,isJson:!1,selection:[]});let L=typeof a.orderBy=="function"?a.orderBy(b,Be()):a.orderBy??[];Array.isArray(L)||(L=[L]),q=L.map(d=>t.is(d,t.Column)?B(d,l):k(d,l)),f=a.limit,w=a.offset;for(const{tsKey:d,queryConfig:y,relation:R}of m){const j=Ae(s,i,R),W=t.getTableUniqueName(R.referencedTable),P=i[W],$=`${l}_${d}`,N=t.and(...j.fields.map((we,qe)=>t.eq(B(j.references[qe],$),B(we,l)))),E=this.buildRelationalQuery({fullSchema:e,schema:s,tableNamesMap:i,table:e[P],tableConfig:s[P],queryConfig:t.is(R,A)?y===!0?{limit:1}:{...y,limit:1}:y,tableAlias:$,joinOn:N,nestedQueryRelation:R}),Se=t.sql`(${E.sql})`.as(d);h.push({dbKey:d,tsKey:d,field:Se,relationTableTsKey:P,isJson:!0,selection:E.selection})}}if(h.length===0)throw new ee({message:`No fields selected for table "${n.tsName}" ("${l}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let p;if(S=t.and(u,S),c){let b=t.sql`json_array(${t.sql.join(h.map(({field:m})=>t.is(m,t.SQLiteColumn)?t.sql.identifier(this.casing.getColumnCasing(m)):t.is(m,t.SQL.Aliased)?m.sql:m),t.sql`, `)})`;t.is(c,J)&&(b=t.sql`coalesce(json_group_array(${b}), json_array())`);const v=[{dbKey:"data",tsKey:"data",field:b.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:h}];f!==void 0||w!==void 0||q.length>0?(p=this.buildSelectQuery({table:H(r,l),fields:{},fieldsFlat:[{path:[],field:t.sql.raw("*")}],where:S,limit:f,offset:w,orderBy:q,setOperators:[]}),S=void 0,f=void 0,w=void 0,q=void 0):p=H(r,l),p=this.buildSelectQuery({table:t.is(p,t.SQLiteTable)?p:new t.Subquery(p,{},l),fields:{},fieldsFlat:v.map(({field:m})=>({path:[],field:t.is(m,t.Column)?B(m,l):m})),joins:g,where:S,limit:f,offset:w,orderBy:q,setOperators:[]})}else p=this.buildSelectQuery({table:H(r,l),fields:{},fieldsFlat:h.map(({field:b})=>({path:[],field:t.is(b,t.Column)?B(b,l):b})),joins:g,where:S,limit:f,offset:w,orderBy:q,setOperators:[]});return{tableTsKey:n.tsName,sql:p,selection:h}}}class ke extends D{static[t.entityKind]="SQLiteSyncDialect";migrate(e,s,i){const r=i===void 0||typeof i=="string"?"__drizzle_migrations":i.migrationsTable??"__drizzle_migrations",n=t.sql`
3
3
  CREATE TABLE IF NOT EXISTS ${t.sql.identifier(r)} (
4
4
  id SERIAL PRIMARY KEY,
@@ -1,4 +1,4 @@
1
- import { W as c, X as o, Y as n, P as l, Z as u, _ as h, $ as d, a0 as w, a1 as m, a2 as y } from "./replay-index-B2RZCGOF.js";
1
+ import { Y as c, Z as o, _ as n, P as l, $ as u, a0 as h, a1 as d, a2 as w, a3 as m, a4 as y } from "./replay-index-BizzVzWT.js";
2
2
  import { O as f } from "./replay-Observable-D6wKbFwB.js";
3
3
  const E = /* @__PURE__ */ new Set(["node_modules"]);
4
4
  class p extends f {
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./replay-index-D85qPcEF.js"),c=require("./replay-Observable-bjJ6wkRB.js"),o=new Set(["node_modules"]);class l extends c.Observable{constructor(e){super(),this.baseDir=e,this.initializeDirectory(e)}baseDir;writeExcludedKeys=new Set;writeEndTimers=new Map;async initializeDirectory(e){await s.mkdir(e,{recursive:!0})}setWriteExcludedKeys(e){this.writeExcludedKeys=e}async ls(e){const t=await this.getFullPath(e);return this.getDirEntryFilesRecursively(t)}async getDirEntryFilesRecursively(e){try{const t=[],i=await s.readDir(e);for(const r of i)if(r.isDirectory){if(o.has(r.name))continue;const n=await s.join(e,r.name),a=await this.getDirEntryFilesRecursively(n);t.push(...a)}else{const n=await s.join(e,r.name),a=await s.PathUtils.relative(this.baseDir,n);t.push(a)}return t}catch(t){return t.includes("forbidden path")||console.error(t),[]}}async get(e){const t=await this.getFullPath(e);try{return await s.readTextFile(t)}catch(i){return!i.includes("No such file or directory")&&!i.includes("forbidden path")&&console.error(i),null}}async has(e){const t=await this.getFullPath(e);return await s.exists(t)}async set(e,t){if(!this.writeExcludedKeys.has(e)){this.emit("write-start",e);try{const i=await this.getFullPath(e),r=s.sep(),n=i.split(r).slice(0,-1).join(r);await s.mkdir(n,{recursive:!0}),await s.writeTextFile(i,t)}finally{const i=this.writeEndTimers.get(e);i&&clearTimeout(i);const r=setTimeout(()=>{this.emit("write-end",e),this.writeEndTimers.delete(e)},1e3);this.writeEndTimers.set(e,r)}}}async remove(e){if(!this.writeExcludedKeys.has(e)){this.emit("write-start",e);try{const t=await this.getFullPath(e);await s.remove(t)}catch(t){!t.includes("No such file or directory")&&!t.includes("forbidden path")&&console.error(t)}finally{const t=this.writeEndTimers.get(e);t&&clearTimeout(t);const i=setTimeout(()=>{this.emit("write-end",e),this.writeEndTimers.delete(e)},1e3);this.writeEndTimers.set(e,i)}}}async rename(e,t){const i=await this.getFullPath(e),r=await this.getFullPath(t);await s.rename(i,r)}async getFullPath(e){return await s.join(this.baseDir,e??"")}}exports.TauriFileSystemAdapter=l;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./replay-index-D3evrr0U.js"),c=require("./replay-Observable-bjJ6wkRB.js"),o=new Set(["node_modules"]);class l extends c.Observable{constructor(e){super(),this.baseDir=e,this.initializeDirectory(e)}baseDir;writeExcludedKeys=new Set;writeEndTimers=new Map;async initializeDirectory(e){await s.mkdir(e,{recursive:!0})}setWriteExcludedKeys(e){this.writeExcludedKeys=e}async ls(e){const t=await this.getFullPath(e);return this.getDirEntryFilesRecursively(t)}async getDirEntryFilesRecursively(e){try{const t=[],i=await s.readDir(e);for(const r of i)if(r.isDirectory){if(o.has(r.name))continue;const n=await s.join(e,r.name),a=await this.getDirEntryFilesRecursively(n);t.push(...a)}else{const n=await s.join(e,r.name),a=await s.PathUtils.relative(this.baseDir,n);t.push(a)}return t}catch(t){return t.includes("forbidden path")||console.error(t),[]}}async get(e){const t=await this.getFullPath(e);try{return await s.readTextFile(t)}catch(i){return!i.includes("No such file or directory")&&!i.includes("forbidden path")&&console.error(i),null}}async has(e){const t=await this.getFullPath(e);return await s.exists(t)}async set(e,t){if(!this.writeExcludedKeys.has(e)){this.emit("write-start",e);try{const i=await this.getFullPath(e),r=s.sep(),n=i.split(r).slice(0,-1).join(r);await s.mkdir(n,{recursive:!0}),await s.writeTextFile(i,t)}finally{const i=this.writeEndTimers.get(e);i&&clearTimeout(i);const r=setTimeout(()=>{this.emit("write-end",e),this.writeEndTimers.delete(e)},1e3);this.writeEndTimers.set(e,r)}}}async remove(e){if(!this.writeExcludedKeys.has(e)){this.emit("write-start",e);try{const t=await this.getFullPath(e);await s.remove(t)}catch(t){!t.includes("No such file or directory")&&!t.includes("forbidden path")&&console.error(t)}finally{const t=this.writeEndTimers.get(e);t&&clearTimeout(t);const i=setTimeout(()=>{this.emit("write-end",e),this.writeEndTimers.delete(e)},1e3);this.writeEndTimers.set(e,i)}}}async rename(e,t){const i=await this.getFullPath(e),r=await this.getFullPath(t);await s.rename(i,r)}async getFullPath(e){return await s.join(this.baseDir,e??"")}}exports.TauriFileSystemAdapter=l;