@redocly/replay 0.29.0-next.6 → 0.29.0-next.8

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 (67) hide show
  1. package/dist/{replay-AiChatProvider-_4MWKqjh.js → replay-AiChatProvider-BhqlFxe5.js} +52 -52
  2. package/dist/{replay-AiChatProvider-Dp-0hM6u.js → replay-AiChatProvider-CQlLeJa7.js} +1 -1
  3. package/dist/{replay-AiChatSqliteDBStorage-UzxSiaa4.js → replay-AiChatSqliteDBStorage-DJ1YGOqe.js} +1 -1
  4. package/dist/{replay-AiChatSqliteDBStorage-Oa4hysNI.js → replay-AiChatSqliteDBStorage-DvYzbacG.js} +1 -1
  5. package/dist/{replay-AiPanel-Cng3cFVq.js → replay-AiPanel-D5TWvjvl.js} +31 -19
  6. package/dist/{replay-AiPanel-C7V7VEFK.js → replay-AiPanel-Dbl9bdI0.js} +2 -2
  7. package/dist/replay-FileWatcher-Ccyd4Ygp.js +1 -0
  8. package/dist/{replay-FileWatcher-B2REfBM5.js → replay-FileWatcher-DcTmOxd5.js} +2 -2
  9. package/dist/{replay-SemanticSearchService-B027vvCl.js → replay-SemanticSearchService-BYH-9ApH.js} +32 -32
  10. package/dist/{replay-SemanticSearchService-BhnCT7Z0.js → replay-SemanticSearchService-D0FEW-qe.js} +1 -1
  11. package/dist/{replay-SqliteDBStorage-SoY4qOnd.js → replay-SqliteDBStorage-dlLOcTaa.js} +2 -2
  12. package/dist/{replay-SqliteDBStorage-IZ7jCbkY.js → replay-SqliteDBStorage-ngC3Fd6F.js} +1 -1
  13. package/dist/{replay-TauriFileSystemAdapter-C8LC19nl.js → replay-TauriFileSystemAdapter-CLyMABdw.js} +1 -1
  14. package/dist/{replay-TauriFileSystemAdapter-BfH97cwK.js → replay-TauriFileSystemAdapter-CfhZ_lu4.js} +1 -1
  15. package/dist/{replay-TauriRootStorage-11a1y8Gt.js → replay-TauriRootStorage-Dw4S06W3.js} +15 -15
  16. package/dist/{replay-TauriRootStorage-BzJznVb7.js → replay-TauriRootStorage-qalQq2sK.js} +1 -1
  17. package/dist/{replay-agent-loop-BjoAr7G_.js → replay-agent-loop-Ch4vi4iC.js} +3 -3
  18. package/dist/{replay-agent-loop-Ck47szY-.js → replay-agent-loop-lW8cGWFV.js} +1 -1
  19. package/dist/{replay-ai-chat-mappers-DQMFqfm5.js → replay-ai-chat-mappers-CZyQUUm-.js} +1 -1
  20. package/dist/{replay-ai-chat-mappers-B7xdsJNR.js → replay-ai-chat-mappers-cLpAMe9s.js} +1 -1
  21. package/dist/{replay-create-model-Dsn4EnHO.js → replay-create-model-BcIMRKgW.js} +3 -3
  22. package/dist/{replay-create-model-Bli_v8yv.js → replay-create-model-GgeDi15a.js} +4 -4
  23. package/dist/{replay-db-CQ4ZMVoP.js → replay-db-CEOHtKri.js} +1 -1
  24. package/dist/{replay-db-CVwyQ9mx.js → replay-db-CbL8F9Gj.js} +6 -6
  25. package/dist/{replay-external-resolver-BeVOSP0e.js → replay-external-resolver-DPE-eBdK.js} +2 -2
  26. package/dist/{replay-external-resolver-BTxGCk8J.js → replay-external-resolver-DWPR21TU.js} +1 -1
  27. package/dist/{replay-index-jkDlU0Lx.js → replay-index-BIFx3qe_.js} +6 -6
  28. package/dist/{replay-index-BRATjW8A.js → replay-index-BIJDsghu.js} +1 -1
  29. package/dist/{replay-index-Cj1st_Mh.js → replay-index-BafdpO9k.js} +1 -1
  30. package/dist/replay-index-CEb-1y0c.js +1 -0
  31. package/dist/{replay-index-JSdiVy-s.js → replay-index-CMbUakrA.js} +1 -1
  32. package/dist/{replay-index-fAxVJ0Lp.js → replay-index-Cbk31wfc.js} +1162 -1162
  33. package/dist/replay-index-CcYwwH13.js +4 -0
  34. package/dist/{replay-index-DiSy_1OY.js → replay-index-CgZg_izl.js} +1 -1
  35. package/dist/{replay-index-DCXNHuqM.js → replay-index-CwCo614T.js} +55 -59
  36. package/dist/replay-index-DXFEOfL5.js +1 -0
  37. package/dist/replay-index-ROQcRTTa.js +1 -0
  38. package/dist/{replay-index-CZKbLR1Q.js → replay-index-xbsaDUTP.js} +19527 -19800
  39. package/dist/{replay-lint-B5Y0f_xB.js → replay-lint-BfdbISqI.js} +11410 -9532
  40. package/dist/replay-lint-CdPOA4Pr.js +130 -0
  41. package/dist/{replay-lint-graphql-BvBl_3l8.js → replay-lint-graphql-CIQ7_fq0.js} +15 -15
  42. package/dist/{replay-lint-graphql-DKWH5u_B.js → replay-lint-graphql-S4qk69dl.js} +1 -1
  43. package/dist/{replay-periodic-revalidation-COYMnQbs.js → replay-periodic-revalidation-B4K7kXe9.js} +1 -1
  44. package/dist/{replay-periodic-revalidation-VvJSzZwq.js → replay-periodic-revalidation-DrYYgXSd.js} +1 -1
  45. package/dist/{replay-resolve-BJBgR5ui.js → replay-resolve-C6cu60fT.js} +1 -1
  46. package/dist/{replay-resolve-DnJdXpgd.js → replay-resolve-Cab_bwUa.js} +8 -8
  47. package/dist/replay-respect-run-DNdF5qAL.js +73 -0
  48. package/dist/{replay-respect-run-B0VuZsRD.js → replay-respect-run-cnFxzDd7.js} +3515 -4982
  49. package/dist/{replay-tauri-path-CspwsPg-.js → replay-tauri-path-B0C8nL7l.js} +1 -1
  50. package/dist/{replay-tauri-path-2hh0ihN5.js → replay-tauri-path-CHACA8CH.js} +2 -2
  51. package/dist/{replay-useAiChatQueries-Mu7qBzg7.js → replay-useAiChatQueries-C4mH2gFV.js} +43 -43
  52. package/dist/{replay-useAiChatQueries-npA6uTpu.js → replay-useAiChatQueries-CEUh6Nj5.js} +460 -460
  53. package/dist/{replay-validate-key-BEKlKcuC.js → replay-validate-key-CDGgJHUA.js} +2 -2
  54. package/dist/{replay-validate-key-rnDZ0V6_.js → replay-validate-key-DCXaLvJK.js} +1 -1
  55. package/dist/replay.cjs +1 -1
  56. package/dist/replay.d.ts +24 -1
  57. package/dist/replay.js +9 -9
  58. package/package.json +5 -4
  59. package/dist/replay-FileWatcher-DlDB2pmS.js +0 -1
  60. package/dist/replay-core-BJmXmoC5.js +0 -1
  61. package/dist/replay-core-B_hiOZZr.js +0 -10
  62. package/dist/replay-index-3lwhSmvi.js +0 -1
  63. package/dist/replay-index-BUuiEmgb.js +0 -4
  64. package/dist/replay-index-GMdv2Mbb.js +0 -1
  65. package/dist/replay-index-Oct6Dygd.js +0 -1
  66. package/dist/replay-lint-D9lcI1vl.js +0 -121
  67. package/dist/replay-respect-run-DfeDqBey.js +0 -82
@@ -1,4 +1,4 @@
1
- import { i as f, Q as W, U as X, F as y } from "./replay-index-CZKbLR1Q.js";
1
+ import { q as f, V as Q, W as X, I as y } from "./replay-index-xbsaDUTP.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) {
@@ -10,10 +10,10 @@ function S(t) {
10
10
  function b(t) {
11
11
  return typeof t == "object" && t !== null && "$ref" in t;
12
12
  }
13
- function D(t) {
13
+ function q(t) {
14
14
  return b(t) ? null : t;
15
15
  }
16
- function q(t) {
16
+ function D(t) {
17
17
  try {
18
18
  return JSON.stringify(t);
19
19
  } catch {
@@ -27,24 +27,24 @@ function J(t) {
27
27
  function U(t) {
28
28
  return t.type ? Array.isArray(t.type) ? t.type.join("|") : t.type : t.oneOf ? "oneOf" : t.anyOf ? "anyOf" : t.allOf ? "allOf" : "object";
29
29
  }
30
- function Y(t) {
30
+ function V(t) {
31
31
  return t === "querystring" ? "query" : t === "query" || t === "header" || t === "path" || t === "cookie" ? t : "query";
32
32
  }
33
- function Z(t) {
33
+ function Y(t) {
34
34
  const e = t.schema && !b(t.schema) ? t.schema : null, n = {
35
35
  name: t.name,
36
- in: Y(t.in),
36
+ in: V(t.in),
37
37
  required: t.required ?? !1
38
38
  };
39
39
  return e && (n.type = U(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 = w(t.description)), t.example !== void 0 && !n.example && (n.example = String(t.example)), n;
40
40
  }
41
- function V(t, e) {
41
+ function Z(t, e) {
42
42
  const n = /* @__PURE__ */ new Set(), o = [], s = (i) => {
43
43
  for (const r of i) {
44
- const c = D(r);
44
+ const c = q(r);
45
45
  if (!c || !c.name) continue;
46
46
  const a = `${c.in}:${c.name}`;
47
- n.has(a) || (n.add(a), o.push(Z(c)));
47
+ n.has(a) || (n.add(a), o.push(Y(c)));
48
48
  }
49
49
  };
50
50
  return t.parameters && s(t.parameters), e.parameters && s(e.parameters), o;
@@ -64,7 +64,7 @@ function ee(t) {
64
64
  if (!e) return [];
65
65
  const n = [];
66
66
  for (const [o, s] of Object.entries(e)) {
67
- const i = D(s);
67
+ const i = q(s);
68
68
  i && n.push(te(o, i));
69
69
  }
70
70
  return n;
@@ -125,7 +125,7 @@ function re(t, e) {
125
125
  );
126
126
  l += `: {${d.join(", ")}}`;
127
127
  }
128
- return i?.example !== void 0 && n.push(q(i.example)), {
128
+ return i?.example !== void 0 && n.push(D(i.example)), {
129
129
  textPart: l,
130
130
  schemaJson: JSON.stringify(a),
131
131
  examples: n
@@ -152,25 +152,25 @@ function ce(t) {
152
152
  return { textParts: e, summaries: n };
153
153
  }
154
154
  function R(t) {
155
- const { apiId: e, apiTitle: n, path: o, method: s, op: i, pathItem: r, globalSchemes: c, apiSecurity: a } = t, u = i.summary ?? "", l = w(i.description ?? ""), d = i.operationId ?? "", p = i.tags ?? [], m = s.toUpperCase(), g = V(i, r), h = ne(i.security, a, c), x = h.length > 0 ? h.map((_) => `api_sec:${e}:${_.schemeName}`) : void 0, I = [n, `${m} ${o}`, u, l];
156
- d && I.push(`operationId: ${d}`), p.length > 0 && I.push(`Tags: ${p.join(", ")}`), i.deprecated && I.push("DEPRECATED"), g.length > 0 && I.push(`Parameters: ${g.map(J).join(". ")}.`);
155
+ const { apiId: e, apiTitle: n, path: o, method: s, op: i, pathItem: r, globalSchemes: c, apiSecurity: a } = t, u = i.summary ?? "", l = w(i.description ?? ""), d = i.operationId ?? "", p = i.tags ?? [], m = s.toUpperCase(), g = Z(i, r), h = ne(i.security, a, c), I = h.length > 0 ? h.map((_) => `api_sec:${e}:${_.schemeName}`) : void 0, x = [n, `${m} ${o}`, u, l];
156
+ d && x.push(`operationId: ${d}`), p.length > 0 && x.push(`Tags: ${p.join(", ")}`), i.deprecated && x.push("DEPRECATED"), g.length > 0 && x.push(`Parameters: ${g.map(J).join(". ")}.`);
157
157
  let k;
158
158
  const v = [], T = i.requestBody;
159
159
  if (T) {
160
- const _ = D(T);
160
+ const _ = q(T);
161
161
  if (_) {
162
162
  const N = re(_, {
163
163
  hideReadOnly: m === "POST" || m === "PUT" || m === "PATCH"
164
164
  });
165
- N.textPart && I.push(N.textPart), k = N.schemaJson, v.push(...N.examples);
165
+ N.textPart && x.push(N.textPart), k = N.schemaJson, v.push(...N.examples);
166
166
  }
167
167
  }
168
168
  const { textParts: B, summaries: A } = ce(
169
169
  i.responses ?? {}
170
170
  );
171
- B.length > 0 && I.push(`Responses: ${B.join(", ")}.`);
171
+ B.length > 0 && x.push(`Responses: ${B.join(", ")}.`);
172
172
  const C = ie(h);
173
- C && I.push(C);
173
+ C && x.push(C);
174
174
  const E = `api_op:${e}:${o}:${s}:${d || `${o}-${s}`}`, G = {
175
175
  type: "api_operation",
176
176
  id: E,
@@ -186,12 +186,12 @@ function R(t) {
186
186
  parameterDetails: g.length > 0 ? g : void 0,
187
187
  requestBodySchema: k,
188
188
  responseSchemas: A.length > 0 ? A : void 0,
189
- securitySchemeRefs: x,
189
+ securitySchemeRefs: I,
190
190
  examples: v.length > 0 ? v : void 0
191
191
  };
192
192
  return {
193
193
  id: E,
194
- text: S(I.filter(Boolean).join(" ")),
194
+ text: S(x.filter(Boolean).join(" ")),
195
195
  payload: G
196
196
  };
197
197
  }
@@ -314,7 +314,7 @@ function de(t) {
314
314
  }
315
315
  function ue(t) {
316
316
  const { collectionId: e, collectionTitle: n, workflow: o } = t, s = o.workflowId ?? "", i = o.summary ?? s, r = w(o.description ?? ""), c = [n, i, r];
317
- if (o.inputs && c.push(`Inputs schema: ${q(o.inputs)}`), o.outputs?.length) {
317
+ if (o.inputs && c.push(`Inputs schema: ${D(o.inputs)}`), o.outputs?.length) {
318
318
  const a = o.outputs.map((u) => u.key).filter(Boolean);
319
319
  a.length && c.push(`Outputs: ${a.join(", ")}`);
320
320
  }
@@ -338,11 +338,11 @@ function pe(t) {
338
338
  const d = i.parameters ? le(i.parameters) : [];
339
339
  d.length > 0 && l.push(`Parameters: ${d.map(J).join(". ")}.`), i.requestBody?.type && l.push(`Request body type: ${i.requestBody.type}`);
340
340
  const m = (i.successCriteria ?? []).map((h) => {
341
- let x = h.condition;
342
- return h.context && (x += ` context: ${h.context}`), h.type && (x += ` (${h.type})`), x;
341
+ let I = h.condition;
342
+ return h.context && (I += ` context: ${h.context}`), h.type && (I += ` (${h.type})`), I;
343
343
  });
344
344
  if (m.length > 0 && l.push(`Success criteria: ${m.join("; ")}`), i.outputs?.length) {
345
- const h = i.outputs.map((x) => `${x.key}=${x.value}`).filter(Boolean);
345
+ const h = i.outputs.map((I) => `${I.key}=${I.value}`).filter(Boolean);
346
346
  h.length && l.push(`Outputs: ${h.join(", ")}`);
347
347
  }
348
348
  const g = `step:${e}:${o}:${r}`;
@@ -364,11 +364,11 @@ function pe(t) {
364
364
  operationId: a?.operationId,
365
365
  parameterDetails: d.length > 0 ? d : void 0,
366
366
  successCriteria: m.length > 0 ? m : void 0,
367
- requestBodySchema: i.requestBody?.type ? q(i.requestBody) : void 0
367
+ requestBodySchema: i.requestBody?.type ? D(i.requestBody) : void 0
368
368
  }
369
369
  };
370
370
  }
371
- function Q(t) {
371
+ function W(t) {
372
372
  const e = [];
373
373
  for (const n of t) {
374
374
  const o = n.id, s = n.info?.title ?? "Untitled Collection";
@@ -385,7 +385,7 @@ function Q(t) {
385
385
  return e;
386
386
  }
387
387
  function fe(t, e) {
388
- return [...L(t), ...Q(e)];
388
+ return [...L(t), ...W(e)];
389
389
  }
390
390
  const O = 10, he = 4;
391
391
  function H(t) {
@@ -395,10 +395,10 @@ function H(t) {
395
395
  return e >>> 0;
396
396
  }
397
397
  function me(t) {
398
- return W(X(t));
398
+ return Q(X(t));
399
399
  }
400
400
  const ye = {};
401
- class xe extends z {
401
+ class Ie extends z {
402
402
  constructor(e) {
403
403
  super(), this.collectionName = e;
404
404
  }
@@ -535,7 +535,7 @@ class xe extends z {
535
535
  });
536
536
  }
537
537
  }
538
- const M = "replay_search", Ie = 384, $ = {
538
+ const M = "replay_search", xe = 384, $ = {
539
539
  added: 0,
540
540
  updated: 0,
541
541
  removed: 0,
@@ -553,7 +553,7 @@ class ge extends z {
553
553
  return this.projectId ? `${M}_${this.projectId}` : M;
554
554
  }
555
555
  createIndexer() {
556
- const e = new xe(this.collectionName);
556
+ const e = new Ie(this.collectionName);
557
557
  return e.subscribe("indexing-activity", (n) => {
558
558
  this.emit("indexing-activity", n);
559
559
  }), e;
@@ -595,7 +595,7 @@ class ge extends z {
595
595
  await f("plugin:velesdb|create_collection", {
596
596
  request: {
597
597
  name: this.collectionName,
598
- dimension: Ie,
598
+ dimension: xe,
599
599
  metric: "cosine",
600
600
  storage_mode: "full"
601
601
  }
@@ -609,7 +609,7 @@ class ge extends z {
609
609
  }
610
610
  async indexCollections(e) {
611
611
  if (!y()) return $;
612
- const n = this.collectionName, o = this.getIndexer(), s = Q(e), i = { collectionIds: e.map((r) => r.id) };
612
+ const n = this.collectionName, o = this.getIndexer(), s = W(e), i = { collectionIds: e.map((r) => r.id) };
613
613
  return await this.ensureInitialized(), this.enqueueIndex(async () => this.collectionName !== n ? $ : o.indexDocuments(s, i), P);
614
614
  }
615
615
  async removeApi(e) {
@@ -1 +1 @@
1
- "use strict";const d=require("./replay-index-fAxVJ0Lp.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-Cbk31wfc.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$1("semantic_search_get_ids_by_payload",{collectionName:this.collectionName,field:e,value:n})}async getAllIds(){return d.invoke$1("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$1("semantic_search_delete_by_payload",{collectionName:this.collectionName,field:e,value:n})}async getStoredDocumentCount(){try{return(await d.invoke$1("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$1("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$1("semantic_search_embed_and_upsert",{collectionName:this.collectionName,documents:i})})}async deletePoints(e){e.length!==0&&await d.invoke$1("plugin:velesdb|delete_points",{request:{collection:this.collectionName,ids:e}})}async flush(){await d.invoke$1("plugin:velesdb|flush",{name:this.collectionName}),await d.invoke$1("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$1("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$1("plugin:velesdb|list_collections"))?.some(n=>n.name===this.collectionName)){this.initialized=!0;return}}catch{}await d.invoke$1("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$1("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$1("semantic_search_model_status")).loaded}catch{}return{indexed:e,modelLoaded:n}}async clear(){if(!(!d.isTauriApp()||!this.initialized))try{await d.invoke$1("plugin:velesdb|delete_collection",{name:this.collectionName}),this.initialized=!1}catch{}}async preloadModel(){if(d.isTauriApp())try{await d.invoke$1("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,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ie=require("./replay-index-fAxVJ0Lp.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-Cbk31wfc.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,
@@ -11,4 +11,4 @@ params: ${s}`),this.query=e,this.params=s,this.cause=i,Error.captureStackTrace(t
11
11
  hash text NOT NULL,
12
12
  created_at numeric
13
13
  )
14
- `;await s.run(n);const l=(await s.values(t.sql`SELECT id, hash, created_at FROM ${t.sql.identifier(r)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await s.transaction(async c=>{for(const u of e)if(!l||Number(l[2])<u.folderMillis){for(const h of u.sql)await c.run(t.sql.raw(h));await c.run(t.sql`INSERT INTO ${t.sql.identifier(r)} ("hash", "created_at") VALUES(${u.hash}, ${u.folderMillis})`)}})}}class Ve{static[t.entityKind]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class O{static[t.entityKind]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){const s=!!this.fields;let i;return this.fields?i=this.fields:t.is(e,t.Subquery)?i=Object.fromEntries(Object.keys(e._.selectedFields).map(r=>[r,e[r]])):t.is(e,te)?i=e[t.ViewBaseConfig].selectedFields:t.is(e,t.SQL)?i={}:i=t.getTableColumns(e),new ye({table:e,fields:i,isPartialSelect:s,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class ze extends Ve{static[t.entityKind]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:s,isPartialSelect:i,session:r,dialect:n,withList:a,distinct:l}){super(),this.config={withList:a,table:e,fields:{...s},distinct:l,setOperators:[]},this.isPartialSelect=i,this.session=r,this.dialect=n,this._={selectedFields:s,config:this.config},this.tableName=t.getTableLikeName(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{};for(const c of M(e))this.usedTables.add(c)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(s,i)=>{const r=this.tableName,n=t.getTableLikeName(s);for(const a of M(s))this.usedTables.add(a);if(typeof n=="string"&&this.config.joins?.some(a=>a.alias===n))throw new Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof r=="string"&&(this.config.fields={[r]:this.config.fields}),typeof n=="string"&&!t.is(s,t.SQL))){const a=t.is(s,t.Subquery)?s._.selectedFields:t.is(s,t.View)?s[t.ViewBaseConfig].selectedFields:s[t.Table.Symbol.Columns];this.config.fields[n]=a}if(typeof i=="function"&&(i=i(new Proxy(this.config.fields,new Q({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:i,table:s,joinType:e,alias:n}),typeof n=="string")switch(e){case"left":{this.joinsNotNullableMap[n]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[n]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[n]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,s){return i=>{const r=typeof i=="function"?i(Je()):i;if(!t.haveSameKeys(this.getSelectedFields(),r.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:s,rightSelect:r}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new Q({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new Q({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){const s=e[0](new Proxy(this.config.fields,new Q({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(s)?s:[s]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){const s=e[0](new Proxy(this.config.fields,new Q({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),i=Array.isArray(s)?s:[s];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=i:this.config.orderBy=i}else{const s=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=s:this.config.orderBy=s}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:e,...s}=this.dialect.sqlToQuery(this.getSQL());return s}as(e){const s=[];if(s.push(...M(this.config.table)),this.config.joins)for(const i of this.config.joins)s.push(...M(i.table));return new Proxy(new t.Subquery(this.getSQL(),this.config.fields,e,!1,[...new Set(s)]),new Q({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Q({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class ye extends ze{static[t.entityKind]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");const s=t.orderSelectedFields(this.config.fields),i=this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),s,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return i.joinsNotNullableMap=this.joinsNotNullableMap,i}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}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(){return this.all()}}t.applyMixins(ye,[K]);function U(o,e){return(s,i,...r)=>{const n=[i,...r].map(a=>({type:o,isAll:e,rightSelect:a}));for(const a of n)if(!t.haveSameKeys(s.getSelectedFields(),a.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return s.addSetOperators(n)}}const Je=()=>({union:Ue,unionAll:We,intersect:He,except:Ye}),Ue=U("union",!1),We=U("union",!0),He=U("intersect",!1),Ye=U("except",!1);class ge{static[t.entityKind]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=t.is(e,D)?e:void 0,this.dialectConfig=t.is(e,D)?void 0:e}$with=(e,s)=>{const i=this;return{as:n=>(typeof n=="function"&&(n=n(i)),new Proxy(new t.WithSubquery(n.getSQL(),s??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new Q({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};with(...e){const s=this;function i(n){return new O({fields:n??void 0,session:void 0,dialect:s.getDialect(),withList:e})}function r(n){return new O({fields:n??void 0,session:void 0,dialect:s.getDialect(),withList:e,distinct:!0})}return{select:i,selectDistinct:r}}select(e){return new O({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new O({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){return this.dialect||(this.dialect=new ke(this.dialectConfig)),this.dialect}}class le{constructor(e,s,i,r){this.table=e,this.session=s,this.dialect=i,this.withList=r}static[t.entityKind]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw new Error("values() must be called with at least one value");const s=e.map(i=>{const r={},n=this.table[t.Table.Symbol.Columns];for(const a of Object.keys(i)){const l=i[a];r[a]=t.is(l,t.SQL)?l:new t.Param(l,n[a])}return r});return new oe(this.table,s,this.session,this.dialect,this.withList)}select(e){const s=typeof e=="function"?e(new ge):e;if(!t.is(s,t.SQL)&&!t.haveSameKeys(this.table[t.Columns],s._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new oe(this.table,s,this.session,this.dialect,this.withList,!0)}}class oe extends K{constructor(e,s,i,r,n,a){super(),this.session=i,this.dialect=r,this.config={table:e,values:s,withList:n,select:a}}static[t.entityKind]="SQLiteInsert";config;returning(e=this.config.table[t.SQLiteTable.Symbol.Columns]){return this.config.returning=t.orderSelectedFields(e),this}onConflictDoNothing(e={}){if(this.config.onConflict||(this.config.onConflict=[]),e.target===void 0)this.config.onConflict.push(t.sql` on conflict do nothing`);else{const s=Array.isArray(e.target)?t.sql`${e.target}`:t.sql`${[e.target]}`,i=e.where?t.sql` where ${e.where}`:t.sql``;this.config.onConflict.push(t.sql` on conflict ${s} do nothing${i}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');this.config.onConflict||(this.config.onConflict=[]);const s=e.where?t.sql` where ${e.where}`:void 0,i=e.targetWhere?t.sql` where ${e.targetWhere}`:void 0,r=e.setWhere?t.sql` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?t.sql`${e.target}`:t.sql`${[e.target]}`,a=this.dialect.buildUpdateSet(this.config.table,t.mapUpdateSet(this.config.table,e.set));return this.config.onConflict.push(t.sql` on conflict ${n}${i} do update set ${a}${s}${r}`),this}getSQL(){return this.dialect.buildInsertQuery(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:"insert",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(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}class ce{constructor(e,s,i,r){this.table=e,this.session=s,this.dialect=i,this.withList=r}static[t.entityKind]="SQLiteUpdateBuilder";set(e){return new Ge(this.table,t.mapUpdateSet(this.table,e),this.session,this.dialect,this.withList)}}class Ge extends K{constructor(e,s,i,r,n){super(),this.session=i,this.dialect=r,this.config={set:s,table:e,withList:n,joins:[]}}static[t.entityKind]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(s,i)=>{const r=t.getTableLikeName(s);if(typeof r=="string"&&this.config.joins.some(n=>n.alias===r))throw new Error(`Alias "${r}" is already used in this query`);if(typeof i=="function"){const n=this.config.from?t.is(s,t.SQLiteTable)?s[t.Table.Symbol.Columns]:t.is(s,t.Subquery)?s._.selectedFields:t.is(s,te)?s[t.ViewBaseConfig].selectedFields:void 0:void 0;i=i(new Proxy(this.config.table[t.Table.Symbol.Columns],new Q({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new Q({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:i,table:s,joinType:e,alias:r}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");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.config.table[t.SQLiteTable.Symbol.Columns]){return this.config.returning=t.orderSelectedFields(e),this}getSQL(){return this.dialect.buildUpdateQuery(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:"insert",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(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}class V extends t.SQL{constructor(e){super(V.buildEmbeddedCount(e.source,e.filters).queryChunks),this.params=e,this.session=e.session,this.sql=V.buildCount(e.source,e.filters)}sql;static[t.entityKind]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,s){return t.sql`(select count(*) from ${e}${t.sql.raw(" where ").if(s)}${s})`}static buildCount(e,s){return t.sql`select count(*) from ${e}${t.sql.raw(" where ").if(s)}${s}`}then(e,s){return Promise.resolve(this.session.count(this.sql)).then(e,s)}catch(e){return this.then(void 0,e)}finally(e){return this.then(s=>(e?.(),s),s=>{throw e?.(),s})}}class Ze{constructor(e,s,i,r,n,a,l,c){this.mode=e,this.fullSchema=s,this.schema=i,this.tableNamesMap=r,this.table=n,this.tableConfig=a,this.dialect=l,this.session=c}static[t.entityKind]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new ue(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},"many"):new G(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},"many")}findFirst(e){return this.mode==="sync"?new ue(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new G(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}}class G extends K{constructor(e,s,i,r,n,a,l,c,u){super(),this.fullSchema=e,this.schema=s,this.tableNamesMap=i,this.table=r,this.tableConfig=n,this.dialect=a,this.session=l,this.config=c,this.mode=u}static[t.entityKind]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){const{query:s,builtQuery:i}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](i,void 0,this.mode==="first"?"get":"all",!0,(r,n)=>{const a=r.map(l=>Y(this.schema,this.tableConfig,l,s.selection,n));return this.mode==="first"?a[0]:a})}prepare(){return this._prepare(!1)}_toSQL(){const e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),s=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:s}}toSQL(){return this._toSQL().builtQuery}executeRaw(){return this.mode==="first"?this._prepare(!1).get():this._prepare(!1).all()}async execute(){return this.executeRaw()}}class ue extends G{static[t.entityKind]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}class F extends K{constructor(e,s,i,r,n){super(),this.execute=e,this.getSQL=s,this.dialect=r,this.mapBatchResult=n,this.config={action:i}}static[t.entityKind]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,s){return s?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}}class pe{constructor(e,s,i,r){this.resultKind=e,this.dialect=s,this.session=i,this._=r?{schema:r.schema,fullSchema:r.fullSchema,tableNamesMap:r.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};const n=this.query;if(this._.schema)for(const[a,l]of Object.entries(this._.schema))n[a]=new Ze(e,r.fullSchema,this._.schema,this._.tableNamesMap,r.fullSchema[a],l,s,i);this.$cache={invalidate:async a=>{}}}static[t.entityKind]="BaseSQLiteDatabase";query;$with=(e,s)=>{const i=this;return{as:n=>(typeof n=="function"&&(n=n(new ge(i.dialect))),new Proxy(new t.WithSubquery(n.getSQL(),s??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new Q({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};$count(e,s){return new V({source:e,filters:s,session:this.session})}with(...e){const s=this;function i(c){return new O({fields:c??void 0,session:s.session,dialect:s.dialect,withList:e})}function r(c){return new O({fields:c??void 0,session:s.session,dialect:s.dialect,withList:e,distinct:!0})}function n(c){return new ce(c,s.session,s.dialect,e)}function a(c){return new le(c,s.session,s.dialect,e)}function l(c){return new ae(c,s.session,s.dialect,e)}return{select:i,selectDistinct:r,update:n,insert:a,delete:l}}select(e){return new O({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new O({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new ce(e,this.session,this.dialect)}$cache;insert(e){return new le(e,this.session,this.dialect)}delete(e){return new ae(e,this.session,this.dialect)}run(e){const s=typeof e=="string"?t.sql.raw(e):e.getSQL();return this.resultKind==="async"?new F(async()=>this.session.run(s),()=>s,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session)):this.session.run(s)}all(e){const s=typeof e=="string"?t.sql.raw(e):e.getSQL();return this.resultKind==="async"?new F(async()=>this.session.all(s),()=>s,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session)):this.session.all(s)}get(e){const s=typeof e=="string"?t.sql.raw(e):e.getSQL();return this.resultKind==="async"?new F(async()=>this.session.get(s),()=>s,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session)):this.session.get(s)}values(e){const s=typeof e=="string"?t.sql.raw(e):e.getSQL();return this.resultKind==="async"?new F(async()=>this.session.values(s),()=>s,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session)):this.session.values(s)}transaction(e,s){return this.session.transaction(e,s)}}class Xe{static[t.entityKind]="Cache"}class be extends Xe{strategy(){return"all"}static[t.entityKind]="NoopCache";async get(e){}async put(e,s,i,r){}async onMutate(e){}}async function he(o,e){const s=`${o}-${JSON.stringify(e)}`,r=new TextEncoder().encode(s),n=await crypto.subtle.digest("SHA-256",r);return[...new Uint8Array(n)].map(c=>c.toString(16).padStart(2,"0")).join("")}class et extends K{constructor(e){super(),this.resultCb=e}static[t.entityKind]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}}class tt{constructor(e,s,i,r,n,a){this.mode=e,this.executeMethod=s,this.query=i,this.cache=r,this.queryMetadata=n,this.cacheConfig=a,r&&r.strategy()==="all"&&a===void 0&&(this.cacheConfig={enable:!0,autoInvalidate:!0}),this.cacheConfig?.enable||(this.cacheConfig=void 0)}static[t.entityKind]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,s,i){if(this.cache===void 0||t.is(this.cache,be)||this.queryMetadata===void 0)try{return await i()}catch(r){throw new _(e,s,r)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await i()}catch(r){throw new _(e,s,r)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{const[r]=await Promise.all([i(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return r}catch(r){throw new _(e,s,r)}if(!this.cacheConfig)try{return await i()}catch(r){throw new _(e,s,r)}if(this.queryMetadata.type==="select"){const r=await this.cache.get(this.cacheConfig.tag??await he(e,s),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(r===void 0){let n;try{n=await i()}catch(a){throw new _(e,s,a)}return await this.cache.put(this.cacheConfig.tag??await he(e,s),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return r}try{return await i()}catch(r){throw new _(e,s,r)}}getQuery(){return this.query}mapRunResult(e,s){return e}mapAllResult(e,s){throw new Error("Not implemented")}mapGetResult(e,s){throw new Error("Not implemented")}execute(e){return this.mode==="async"?this[this.executeMethod](e):new et(()=>this[this.executeMethod](e))}mapResult(e,s){switch(this.executeMethod){case"run":return this.mapRunResult(e,s);case"all":return this.mapAllResult(e,s);case"get":return this.mapGetResult(e,s)}}}class st{constructor(e){this.dialect=e}static[t.entityKind]="SQLiteSession";prepareOneTimeQuery(e,s,i,r,n,a,l){return this.prepareQuery(e,s,i,r,n,a,l)}run(e){const s=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(s,void 0,"run",!1).run()}catch(i){throw new ee({cause:i,message:`Failed to run the query '${s.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(e){throw new Error("Not implemented")}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(e){throw new Error("Not implemented")}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).values()}async count(e){return(await this.values(e))[0][0]}extractRawValuesValueFromBatchResult(e){throw new Error("Not implemented")}}class it extends pe{constructor(e,s,i,r,n=0){super(e,s,i,r),this.schema=r,this.nestedIndex=n}static[t.entityKind]="SQLiteTransaction";rollback(){throw new Ie}}class rt extends st{constructor(e,s,i,r,n={}){super(s),this.client=e,this.schema=i,this.batchCLient=r,this.logger=n.logger??new Le,this.cache=n.cache??new be}static[t.entityKind]="SQLiteRemoteSession";logger;cache;prepareQuery(e,s,i,r,n,a,l){return new nt(this.client,e,this.logger,this.cache,a,l,s,i,r,n)}async batch(e){const s=[],i=[];for(const n of e){const a=n._prepare(),l=a.getQuery();s.push(a),i.push({sql:l.sql,params:l.params,method:l.method})}return(await this.batchCLient(i)).map((n,a)=>s[a].mapResult(n,!0))}async transaction(e,s){const i=new se("async",this.dialect,this,this.schema);await this.run(t.sql.raw(`begin${s?.behavior?" "+s.behavior:""}`));try{const r=await e(i);return await this.run(t.sql`commit`),r}catch(r){throw await this.run(t.sql`rollback`),r}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}}class se extends it{static[t.entityKind]="SQLiteProxyTransaction";async transaction(e){const s=`sp${this.nestedIndex}`,i=new se("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(t.sql.raw(`savepoint ${s}`));try{const r=await e(i);return await this.session.run(t.sql.raw(`release savepoint ${s}`)),r}catch(r){throw await this.session.run(t.sql.raw(`rollback to savepoint ${s}`)),r}}}class nt extends tt{constructor(e,s,i,r,n,a,l,c,u,h){super("async",c,s,r,n,a),this.client=e,this.logger=i,this.fields=l,this._isResponseInArrayMode=u,this.customResultMapper=h,this.customResultMapper=h,this.method=c}static[t.entityKind]="SQLiteProxyPreparedQuery";method;getQuery(){return{...this.query,method:this.method}}async run(e){const s=t.fillPlaceholders(this.query.params,e??{});return this.logger.logQuery(this.query.sql,s),await this.queryWithCache(this.query.sql,s,async()=>await this.client(this.query.sql,s,"run"))}mapAllResult(e,s){return s&&(e=e.rows),!this.fields&&!this.customResultMapper?e:this.customResultMapper?this.customResultMapper(e):e.map(i=>t.mapResultRow(this.fields,i,this.joinsNotNullableMap))}async all(e){const{query:s,logger:i,client:r}=this,n=t.fillPlaceholders(s.params,e??{});i.logQuery(s.sql,n);const{rows:a}=await this.queryWithCache(s.sql,n,async()=>await r(s.sql,n,"all"));return this.mapAllResult(a)}async get(e){const{query:s,logger:i,client:r}=this,n=t.fillPlaceholders(s.params,e??{});i.logQuery(s.sql,n);const a=await this.queryWithCache(s.sql,n,async()=>await r(s.sql,n,"get"));return this.mapGetResult(a.rows)}mapGetResult(e,s){s&&(e=e.rows);const i=e;if(!this.fields&&!this.customResultMapper)return i;if(i)return this.customResultMapper?this.customResultMapper([e]):t.mapResultRow(this.fields,i,this.joinsNotNullableMap)}async values(e){const s=t.fillPlaceholders(this.query.params,e??{});return this.logger.logQuery(this.query.sql,s),(await this.queryWithCache(this.query.sql,s,async()=>await this.client(this.query.sql,s,"values"))).rows}isResponseInArrayMode(){return this._isResponseInArrayMode}}class at extends pe{static[t.entityKind]="SqliteRemoteDatabase";async batch(e){return this.session.batch(e)}}function lt(o,e,s){const i=new De({casing:s?.casing});let r,n,a,l={};e&&(typeof e=="function"?(a=e,l={}):(a=void 0,l=e),l.logger===!0?r=new ve:l.logger!==!1&&(r=l.logger,n=l.cache));let c;if(l.schema){const f=_e(l.schema,Ke);c={fullSchema:l.schema,schema:f.tables,tableNamesMap:f.tableNamesMap}}const u=new rt(o,i,c,a,{logger:r,cache:n}),h=new at("async",i,u,c);return h.$cache=n,h.$cache&&(h.$cache.invalidate=n?.onMutate),h}const ot=Z(C.aiChats,({many:o})=>({messages:o(C.aiMessages)})),ct=Z(C.aiMessages,({one:o,many:e})=>({chat:o(C.aiChats,{fields:[C.aiMessages.aiChatId],references:[C.aiChats.id]}),parts:e(C.aiMessageParts)})),ut=Z(C.aiMessageParts,({one:o})=>({message:o(C.aiMessages,{fields:[C.aiMessageParts.aiMessageId],references:[C.aiMessages.id]})})),ht=Object.freeze(Object.defineProperty({__proto__:null,aiChats:C.aiChats,aiChatsRelations:ot,aiMessageParts:C.aiMessageParts,aiMessagePartsRelations:ut,aiMessages:C.aiMessages,aiMessagesRelations:ct,history:Te.history,stepContext:Qe.stepContext},Symbol.toStringTag,{value:"Module"}));function dt(o){return o.map(e=>e===""?null:e)}class z{constructor(e){this.dbPath=e,this.db=lt(async(s,i,r)=>{try{const a=(await ie.invoke("db_query",{params:{sql:s,params:i||[]}})).rows||[];if(a.length===0&&r==="get")return{};const l=a.map(dt);return{rows:r==="get"?l[0]:l}}catch(n){throw console.error("SQLite proxy error:",n),n}},{schema:ht})}dbPath;static instances=new Map;initPromise=null;db;static getInstance(e){let s=this.instances.get(e);return s||(s=new z(e),this.instances.set(e,s)),s}async initialize(){if(this.initPromise)return this.initPromise;this.initPromise=ie.invoke("db_init",{dbPath:this.dbPath});try{await this.initPromise}catch(e){throw this.initPromise=null,e}}async close(){z.instances.delete(this.dbPath)}}exports.SqliteDBStorage=z;
14
+ `;await s.run(n);const l=(await s.values(t.sql`SELECT id, hash, created_at FROM ${t.sql.identifier(r)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await s.transaction(async c=>{for(const u of e)if(!l||Number(l[2])<u.folderMillis){for(const h of u.sql)await c.run(t.sql.raw(h));await c.run(t.sql`INSERT INTO ${t.sql.identifier(r)} ("hash", "created_at") VALUES(${u.hash}, ${u.folderMillis})`)}})}}class Ve{static[t.entityKind]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class O{static[t.entityKind]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){const s=!!this.fields;let i;return this.fields?i=this.fields:t.is(e,t.Subquery)?i=Object.fromEntries(Object.keys(e._.selectedFields).map(r=>[r,e[r]])):t.is(e,te)?i=e[t.ViewBaseConfig].selectedFields:t.is(e,t.SQL)?i={}:i=t.getTableColumns(e),new ye({table:e,fields:i,isPartialSelect:s,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class ze extends Ve{static[t.entityKind]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:s,isPartialSelect:i,session:r,dialect:n,withList:a,distinct:l}){super(),this.config={withList:a,table:e,fields:{...s},distinct:l,setOperators:[]},this.isPartialSelect=i,this.session=r,this.dialect=n,this._={selectedFields:s,config:this.config},this.tableName=t.getTableLikeName(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{};for(const c of M(e))this.usedTables.add(c)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(s,i)=>{const r=this.tableName,n=t.getTableLikeName(s);for(const a of M(s))this.usedTables.add(a);if(typeof n=="string"&&this.config.joins?.some(a=>a.alias===n))throw new Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof r=="string"&&(this.config.fields={[r]:this.config.fields}),typeof n=="string"&&!t.is(s,t.SQL))){const a=t.is(s,t.Subquery)?s._.selectedFields:t.is(s,t.View)?s[t.ViewBaseConfig].selectedFields:s[t.Table.Symbol.Columns];this.config.fields[n]=a}if(typeof i=="function"&&(i=i(new Proxy(this.config.fields,new Q({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:i,table:s,joinType:e,alias:n}),typeof n=="string")switch(e){case"left":{this.joinsNotNullableMap[n]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[n]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[n]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,s){return i=>{const r=typeof i=="function"?i(Je()):i;if(!t.haveSameKeys(this.getSelectedFields(),r.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:s,rightSelect:r}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new Q({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new Q({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){const s=e[0](new Proxy(this.config.fields,new Q({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(s)?s:[s]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){const s=e[0](new Proxy(this.config.fields,new Q({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),i=Array.isArray(s)?s:[s];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=i:this.config.orderBy=i}else{const s=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=s:this.config.orderBy=s}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:e,...s}=this.dialect.sqlToQuery(this.getSQL());return s}as(e){const s=[];if(s.push(...M(this.config.table)),this.config.joins)for(const i of this.config.joins)s.push(...M(i.table));return new Proxy(new t.Subquery(this.getSQL(),this.config.fields,e,!1,[...new Set(s)]),new Q({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Q({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class ye extends ze{static[t.entityKind]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");const s=t.orderSelectedFields(this.config.fields),i=this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),s,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return i.joinsNotNullableMap=this.joinsNotNullableMap,i}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}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(){return this.all()}}t.applyMixins(ye,[K]);function U(o,e){return(s,i,...r)=>{const n=[i,...r].map(a=>({type:o,isAll:e,rightSelect:a}));for(const a of n)if(!t.haveSameKeys(s.getSelectedFields(),a.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return s.addSetOperators(n)}}const Je=()=>({union:Ue,unionAll:We,intersect:He,except:Ye}),Ue=U("union",!1),We=U("union",!0),He=U("intersect",!1),Ye=U("except",!1);class ge{static[t.entityKind]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=t.is(e,D)?e:void 0,this.dialectConfig=t.is(e,D)?void 0:e}$with=(e,s)=>{const i=this;return{as:n=>(typeof n=="function"&&(n=n(i)),new Proxy(new t.WithSubquery(n.getSQL(),s??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new Q({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};with(...e){const s=this;function i(n){return new O({fields:n??void 0,session:void 0,dialect:s.getDialect(),withList:e})}function r(n){return new O({fields:n??void 0,session:void 0,dialect:s.getDialect(),withList:e,distinct:!0})}return{select:i,selectDistinct:r}}select(e){return new O({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new O({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){return this.dialect||(this.dialect=new ke(this.dialectConfig)),this.dialect}}class le{constructor(e,s,i,r){this.table=e,this.session=s,this.dialect=i,this.withList=r}static[t.entityKind]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw new Error("values() must be called with at least one value");const s=e.map(i=>{const r={},n=this.table[t.Table.Symbol.Columns];for(const a of Object.keys(i)){const l=i[a];r[a]=t.is(l,t.SQL)?l:new t.Param(l,n[a])}return r});return new oe(this.table,s,this.session,this.dialect,this.withList)}select(e){const s=typeof e=="function"?e(new ge):e;if(!t.is(s,t.SQL)&&!t.haveSameKeys(this.table[t.Columns],s._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new oe(this.table,s,this.session,this.dialect,this.withList,!0)}}class oe extends K{constructor(e,s,i,r,n,a){super(),this.session=i,this.dialect=r,this.config={table:e,values:s,withList:n,select:a}}static[t.entityKind]="SQLiteInsert";config;returning(e=this.config.table[t.SQLiteTable.Symbol.Columns]){return this.config.returning=t.orderSelectedFields(e),this}onConflictDoNothing(e={}){if(this.config.onConflict||(this.config.onConflict=[]),e.target===void 0)this.config.onConflict.push(t.sql` on conflict do nothing`);else{const s=Array.isArray(e.target)?t.sql`${e.target}`:t.sql`${[e.target]}`,i=e.where?t.sql` where ${e.where}`:t.sql``;this.config.onConflict.push(t.sql` on conflict ${s} do nothing${i}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');this.config.onConflict||(this.config.onConflict=[]);const s=e.where?t.sql` where ${e.where}`:void 0,i=e.targetWhere?t.sql` where ${e.targetWhere}`:void 0,r=e.setWhere?t.sql` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?t.sql`${e.target}`:t.sql`${[e.target]}`,a=this.dialect.buildUpdateSet(this.config.table,t.mapUpdateSet(this.config.table,e.set));return this.config.onConflict.push(t.sql` on conflict ${n}${i} do update set ${a}${s}${r}`),this}getSQL(){return this.dialect.buildInsertQuery(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:"insert",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(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}class ce{constructor(e,s,i,r){this.table=e,this.session=s,this.dialect=i,this.withList=r}static[t.entityKind]="SQLiteUpdateBuilder";set(e){return new Ge(this.table,t.mapUpdateSet(this.table,e),this.session,this.dialect,this.withList)}}class Ge extends K{constructor(e,s,i,r,n){super(),this.session=i,this.dialect=r,this.config={set:s,table:e,withList:n,joins:[]}}static[t.entityKind]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(s,i)=>{const r=t.getTableLikeName(s);if(typeof r=="string"&&this.config.joins.some(n=>n.alias===r))throw new Error(`Alias "${r}" is already used in this query`);if(typeof i=="function"){const n=this.config.from?t.is(s,t.SQLiteTable)?s[t.Table.Symbol.Columns]:t.is(s,t.Subquery)?s._.selectedFields:t.is(s,te)?s[t.ViewBaseConfig].selectedFields:void 0:void 0;i=i(new Proxy(this.config.table[t.Table.Symbol.Columns],new Q({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new Q({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:i,table:s,joinType:e,alias:r}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");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.config.table[t.SQLiteTable.Symbol.Columns]){return this.config.returning=t.orderSelectedFields(e),this}getSQL(){return this.dialect.buildUpdateQuery(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:"insert",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(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}class V extends t.SQL{constructor(e){super(V.buildEmbeddedCount(e.source,e.filters).queryChunks),this.params=e,this.session=e.session,this.sql=V.buildCount(e.source,e.filters)}sql;static[t.entityKind]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,s){return t.sql`(select count(*) from ${e}${t.sql.raw(" where ").if(s)}${s})`}static buildCount(e,s){return t.sql`select count(*) from ${e}${t.sql.raw(" where ").if(s)}${s}`}then(e,s){return Promise.resolve(this.session.count(this.sql)).then(e,s)}catch(e){return this.then(void 0,e)}finally(e){return this.then(s=>(e?.(),s),s=>{throw e?.(),s})}}class Ze{constructor(e,s,i,r,n,a,l,c){this.mode=e,this.fullSchema=s,this.schema=i,this.tableNamesMap=r,this.table=n,this.tableConfig=a,this.dialect=l,this.session=c}static[t.entityKind]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new ue(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},"many"):new G(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},"many")}findFirst(e){return this.mode==="sync"?new ue(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new G(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}}class G extends K{constructor(e,s,i,r,n,a,l,c,u){super(),this.fullSchema=e,this.schema=s,this.tableNamesMap=i,this.table=r,this.tableConfig=n,this.dialect=a,this.session=l,this.config=c,this.mode=u}static[t.entityKind]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){const{query:s,builtQuery:i}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](i,void 0,this.mode==="first"?"get":"all",!0,(r,n)=>{const a=r.map(l=>Y(this.schema,this.tableConfig,l,s.selection,n));return this.mode==="first"?a[0]:a})}prepare(){return this._prepare(!1)}_toSQL(){const e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),s=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:s}}toSQL(){return this._toSQL().builtQuery}executeRaw(){return this.mode==="first"?this._prepare(!1).get():this._prepare(!1).all()}async execute(){return this.executeRaw()}}class ue extends G{static[t.entityKind]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}class F extends K{constructor(e,s,i,r,n){super(),this.execute=e,this.getSQL=s,this.dialect=r,this.mapBatchResult=n,this.config={action:i}}static[t.entityKind]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,s){return s?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}}class pe{constructor(e,s,i,r){this.resultKind=e,this.dialect=s,this.session=i,this._=r?{schema:r.schema,fullSchema:r.fullSchema,tableNamesMap:r.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};const n=this.query;if(this._.schema)for(const[a,l]of Object.entries(this._.schema))n[a]=new Ze(e,r.fullSchema,this._.schema,this._.tableNamesMap,r.fullSchema[a],l,s,i);this.$cache={invalidate:async a=>{}}}static[t.entityKind]="BaseSQLiteDatabase";query;$with=(e,s)=>{const i=this;return{as:n=>(typeof n=="function"&&(n=n(new ge(i.dialect))),new Proxy(new t.WithSubquery(n.getSQL(),s??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new Q({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};$count(e,s){return new V({source:e,filters:s,session:this.session})}with(...e){const s=this;function i(c){return new O({fields:c??void 0,session:s.session,dialect:s.dialect,withList:e})}function r(c){return new O({fields:c??void 0,session:s.session,dialect:s.dialect,withList:e,distinct:!0})}function n(c){return new ce(c,s.session,s.dialect,e)}function a(c){return new le(c,s.session,s.dialect,e)}function l(c){return new ae(c,s.session,s.dialect,e)}return{select:i,selectDistinct:r,update:n,insert:a,delete:l}}select(e){return new O({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new O({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new ce(e,this.session,this.dialect)}$cache;insert(e){return new le(e,this.session,this.dialect)}delete(e){return new ae(e,this.session,this.dialect)}run(e){const s=typeof e=="string"?t.sql.raw(e):e.getSQL();return this.resultKind==="async"?new F(async()=>this.session.run(s),()=>s,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session)):this.session.run(s)}all(e){const s=typeof e=="string"?t.sql.raw(e):e.getSQL();return this.resultKind==="async"?new F(async()=>this.session.all(s),()=>s,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session)):this.session.all(s)}get(e){const s=typeof e=="string"?t.sql.raw(e):e.getSQL();return this.resultKind==="async"?new F(async()=>this.session.get(s),()=>s,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session)):this.session.get(s)}values(e){const s=typeof e=="string"?t.sql.raw(e):e.getSQL();return this.resultKind==="async"?new F(async()=>this.session.values(s),()=>s,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session)):this.session.values(s)}transaction(e,s){return this.session.transaction(e,s)}}class Xe{static[t.entityKind]="Cache"}class be extends Xe{strategy(){return"all"}static[t.entityKind]="NoopCache";async get(e){}async put(e,s,i,r){}async onMutate(e){}}async function he(o,e){const s=`${o}-${JSON.stringify(e)}`,r=new TextEncoder().encode(s),n=await crypto.subtle.digest("SHA-256",r);return[...new Uint8Array(n)].map(c=>c.toString(16).padStart(2,"0")).join("")}class et extends K{constructor(e){super(),this.resultCb=e}static[t.entityKind]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}}class tt{constructor(e,s,i,r,n,a){this.mode=e,this.executeMethod=s,this.query=i,this.cache=r,this.queryMetadata=n,this.cacheConfig=a,r&&r.strategy()==="all"&&a===void 0&&(this.cacheConfig={enable:!0,autoInvalidate:!0}),this.cacheConfig?.enable||(this.cacheConfig=void 0)}static[t.entityKind]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,s,i){if(this.cache===void 0||t.is(this.cache,be)||this.queryMetadata===void 0)try{return await i()}catch(r){throw new _(e,s,r)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await i()}catch(r){throw new _(e,s,r)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{const[r]=await Promise.all([i(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return r}catch(r){throw new _(e,s,r)}if(!this.cacheConfig)try{return await i()}catch(r){throw new _(e,s,r)}if(this.queryMetadata.type==="select"){const r=await this.cache.get(this.cacheConfig.tag??await he(e,s),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(r===void 0){let n;try{n=await i()}catch(a){throw new _(e,s,a)}return await this.cache.put(this.cacheConfig.tag??await he(e,s),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return r}try{return await i()}catch(r){throw new _(e,s,r)}}getQuery(){return this.query}mapRunResult(e,s){return e}mapAllResult(e,s){throw new Error("Not implemented")}mapGetResult(e,s){throw new Error("Not implemented")}execute(e){return this.mode==="async"?this[this.executeMethod](e):new et(()=>this[this.executeMethod](e))}mapResult(e,s){switch(this.executeMethod){case"run":return this.mapRunResult(e,s);case"all":return this.mapAllResult(e,s);case"get":return this.mapGetResult(e,s)}}}class st{constructor(e){this.dialect=e}static[t.entityKind]="SQLiteSession";prepareOneTimeQuery(e,s,i,r,n,a,l){return this.prepareQuery(e,s,i,r,n,a,l)}run(e){const s=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(s,void 0,"run",!1).run()}catch(i){throw new ee({cause:i,message:`Failed to run the query '${s.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(e){throw new Error("Not implemented")}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(e){throw new Error("Not implemented")}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).values()}async count(e){return(await this.values(e))[0][0]}extractRawValuesValueFromBatchResult(e){throw new Error("Not implemented")}}class it extends pe{constructor(e,s,i,r,n=0){super(e,s,i,r),this.schema=r,this.nestedIndex=n}static[t.entityKind]="SQLiteTransaction";rollback(){throw new Ie}}class rt extends st{constructor(e,s,i,r,n={}){super(s),this.client=e,this.schema=i,this.batchCLient=r,this.logger=n.logger??new Le,this.cache=n.cache??new be}static[t.entityKind]="SQLiteRemoteSession";logger;cache;prepareQuery(e,s,i,r,n,a,l){return new nt(this.client,e,this.logger,this.cache,a,l,s,i,r,n)}async batch(e){const s=[],i=[];for(const n of e){const a=n._prepare(),l=a.getQuery();s.push(a),i.push({sql:l.sql,params:l.params,method:l.method})}return(await this.batchCLient(i)).map((n,a)=>s[a].mapResult(n,!0))}async transaction(e,s){const i=new se("async",this.dialect,this,this.schema);await this.run(t.sql.raw(`begin${s?.behavior?" "+s.behavior:""}`));try{const r=await e(i);return await this.run(t.sql`commit`),r}catch(r){throw await this.run(t.sql`rollback`),r}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}}class se extends it{static[t.entityKind]="SQLiteProxyTransaction";async transaction(e){const s=`sp${this.nestedIndex}`,i=new se("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(t.sql.raw(`savepoint ${s}`));try{const r=await e(i);return await this.session.run(t.sql.raw(`release savepoint ${s}`)),r}catch(r){throw await this.session.run(t.sql.raw(`rollback to savepoint ${s}`)),r}}}class nt extends tt{constructor(e,s,i,r,n,a,l,c,u,h){super("async",c,s,r,n,a),this.client=e,this.logger=i,this.fields=l,this._isResponseInArrayMode=u,this.customResultMapper=h,this.customResultMapper=h,this.method=c}static[t.entityKind]="SQLiteProxyPreparedQuery";method;getQuery(){return{...this.query,method:this.method}}async run(e){const s=t.fillPlaceholders(this.query.params,e??{});return this.logger.logQuery(this.query.sql,s),await this.queryWithCache(this.query.sql,s,async()=>await this.client(this.query.sql,s,"run"))}mapAllResult(e,s){return s&&(e=e.rows),!this.fields&&!this.customResultMapper?e:this.customResultMapper?this.customResultMapper(e):e.map(i=>t.mapResultRow(this.fields,i,this.joinsNotNullableMap))}async all(e){const{query:s,logger:i,client:r}=this,n=t.fillPlaceholders(s.params,e??{});i.logQuery(s.sql,n);const{rows:a}=await this.queryWithCache(s.sql,n,async()=>await r(s.sql,n,"all"));return this.mapAllResult(a)}async get(e){const{query:s,logger:i,client:r}=this,n=t.fillPlaceholders(s.params,e??{});i.logQuery(s.sql,n);const a=await this.queryWithCache(s.sql,n,async()=>await r(s.sql,n,"get"));return this.mapGetResult(a.rows)}mapGetResult(e,s){s&&(e=e.rows);const i=e;if(!this.fields&&!this.customResultMapper)return i;if(i)return this.customResultMapper?this.customResultMapper([e]):t.mapResultRow(this.fields,i,this.joinsNotNullableMap)}async values(e){const s=t.fillPlaceholders(this.query.params,e??{});return this.logger.logQuery(this.query.sql,s),(await this.queryWithCache(this.query.sql,s,async()=>await this.client(this.query.sql,s,"values"))).rows}isResponseInArrayMode(){return this._isResponseInArrayMode}}class at extends pe{static[t.entityKind]="SqliteRemoteDatabase";async batch(e){return this.session.batch(e)}}function lt(o,e,s){const i=new De({casing:s?.casing});let r,n,a,l={};e&&(typeof e=="function"?(a=e,l={}):(a=void 0,l=e),l.logger===!0?r=new ve:l.logger!==!1&&(r=l.logger,n=l.cache));let c;if(l.schema){const f=_e(l.schema,Ke);c={fullSchema:l.schema,schema:f.tables,tableNamesMap:f.tableNamesMap}}const u=new rt(o,i,c,a,{logger:r,cache:n}),h=new at("async",i,u,c);return h.$cache=n,h.$cache&&(h.$cache.invalidate=n?.onMutate),h}const ot=Z(C.aiChats,({many:o})=>({messages:o(C.aiMessages)})),ct=Z(C.aiMessages,({one:o,many:e})=>({chat:o(C.aiChats,{fields:[C.aiMessages.aiChatId],references:[C.aiChats.id]}),parts:e(C.aiMessageParts)})),ut=Z(C.aiMessageParts,({one:o})=>({message:o(C.aiMessages,{fields:[C.aiMessageParts.aiMessageId],references:[C.aiMessages.id]})})),ht=Object.freeze(Object.defineProperty({__proto__:null,aiChats:C.aiChats,aiChatsRelations:ot,aiMessageParts:C.aiMessageParts,aiMessagePartsRelations:ut,aiMessages:C.aiMessages,aiMessagesRelations:ct,history:Te.history,stepContext:Qe.stepContext},Symbol.toStringTag,{value:"Module"}));function dt(o){return o.map(e=>e===""?null:e)}class z{constructor(e){this.dbPath=e,this.db=lt(async(s,i,r)=>{try{const a=(await ie.invoke$1("db_query",{params:{sql:s,params:i||[]}})).rows||[];if(a.length===0&&r==="get")return{};const l=a.map(dt);return{rows:r==="get"?l[0]:l}}catch(n){throw console.error("SQLite proxy error:",n),n}},{schema:ht})}dbPath;static instances=new Map;initPromise=null;db;static getInstance(e){let s=this.instances.get(e);return s||(s=new z(e),this.instances.set(e,s)),s}async initialize(){if(this.initPromise)return this.initPromise;this.initPromise=ie.invoke$1("db_init",{dbPath:this.dbPath});try{await this.initPromise}catch(e){throw this.initPromise=null,e}}async close(){z.instances.delete(this.dbPath)}}exports.SqliteDBStorage=z;
@@ -1,4 +1,4 @@
1
- import { i as Qe } from "./replay-index-CZKbLR1Q.js";
1
+ import { q as Qe } from "./replay-index-xbsaDUTP.js";
2
2
  import { h as Ve } from "./replay-history.schema-B0lLwmdG.js";
3
3
  import { s as Ue } from "./replay-step-context.schema-BOprzd6Z.js";
4
4
  import { b as J, c as X, a as ee } from "./replay-ai-message-parts.schema-DKLf0SiG.js";
@@ -1,4 +1,4 @@
1
- import { m as o, r as u, j as c, P as d, b as h, e as l, s as w, w as y, d as m, f } from "./replay-index-CZKbLR1Q.js";
1
+ import { m as o, r as u, j as c, P as d, b as h, e as l, s as w, w as y, d as m, f } from "./replay-index-xbsaDUTP.js";
2
2
  import { O as E } from "./replay-Observable-D6wKbFwB.js";
3
3
  const F = /* @__PURE__ */ new Set(["node_modules"]), T = /\(os error [23]\)/;
4
4
  function g(r) {
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("./replay-index-fAxVJ0Lp.js"),o=require("./replay-Observable-bjJ6wkRB.js"),l=new Set(["node_modules"]),u=/\(os error [23]\)/;function d(n){return typeof n!="string"?!1:n.includes("No such file or directory")||n.includes("forbidden path")||u.test(n)}class h extends o.Observable{constructor(e){super(),this.baseDir=e,this.initializeDirectory(e)}baseDir;writeExcludedKeys=new Set;writeEndTimers=new Map;async initializeDirectory(e){await i.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=[],s=await i.readDir(e);for(const r of s)if(r.isDirectory){if(l.has(r.name))continue;const a=await i.join(e,r.name),c=await this.getDirEntryFilesRecursively(a);t.push(...c)}else{const a=await i.join(e,r.name),c=await i.PathUtils.relative(this.baseDir,a);t.push(c)}return t}catch(t){return t.includes("forbidden path")||console.error(t),[]}}async get(e){const t=await this.getFullPath(e);try{return await i.readTextFile(t)}catch(s){if(d(s))return null;try{if(!await i.exists(t))return null}catch{}throw console.error(s),s}}async has(e){const t=await this.getFullPath(e);return await i.exists(t)}async set(e,t){if(!this.writeExcludedKeys.has(e)){this.cancelWriteEndTimer(e),this.emit("write-start",e);try{const s=await this.getFullPath(e),r=i.sep(),a=s.split(r).slice(0,-1).join(r);await i.mkdir(a,{recursive:!0}),await i.writeTextFile(s,t)}finally{this.scheduleWriteEnd(e)}}}async remove(e){if(!this.writeExcludedKeys.has(e)){this.cancelWriteEndTimer(e),this.emit("write-start",e);try{const t=await this.getFullPath(e);await i.remove(t)}catch(t){!t.includes("No such file or directory")&&!t.includes("forbidden path")&&console.error(t)}finally{this.scheduleWriteEnd(e)}}}cancelWriteEndTimer(e){const t=this.writeEndTimers.get(e);t&&(clearTimeout(t),this.writeEndTimers.delete(e))}scheduleWriteEnd(e){this.cancelWriteEndTimer(e);const t=setTimeout(()=>{this.emit("write-end",e),this.writeEndTimers.delete(e)},1e3);this.writeEndTimers.set(e,t)}async rename(e,t){const s=await this.getFullPath(e),r=await this.getFullPath(t);await i.rename(s,r)}async getFullPath(e){return await i.join(this.baseDir,e??"")}}exports.TauriFileSystemAdapter=h;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("./replay-index-Cbk31wfc.js"),o=require("./replay-Observable-bjJ6wkRB.js"),l=new Set(["node_modules"]),u=/\(os error [23]\)/;function d(n){return typeof n!="string"?!1:n.includes("No such file or directory")||n.includes("forbidden path")||u.test(n)}class h extends o.Observable{constructor(e){super(),this.baseDir=e,this.initializeDirectory(e)}baseDir;writeExcludedKeys=new Set;writeEndTimers=new Map;async initializeDirectory(e){await i.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=[],s=await i.readDir(e);for(const r of s)if(r.isDirectory){if(l.has(r.name))continue;const a=await i.join(e,r.name),c=await this.getDirEntryFilesRecursively(a);t.push(...c)}else{const a=await i.join(e,r.name),c=await i.PathUtils.relative(this.baseDir,a);t.push(c)}return t}catch(t){return t.includes("forbidden path")||console.error(t),[]}}async get(e){const t=await this.getFullPath(e);try{return await i.readTextFile(t)}catch(s){if(d(s))return null;try{if(!await i.exists(t))return null}catch{}throw console.error(s),s}}async has(e){const t=await this.getFullPath(e);return await i.exists(t)}async set(e,t){if(!this.writeExcludedKeys.has(e)){this.cancelWriteEndTimer(e),this.emit("write-start",e);try{const s=await this.getFullPath(e),r=i.sep(),a=s.split(r).slice(0,-1).join(r);await i.mkdir(a,{recursive:!0}),await i.writeTextFile(s,t)}finally{this.scheduleWriteEnd(e)}}}async remove(e){if(!this.writeExcludedKeys.has(e)){this.cancelWriteEndTimer(e),this.emit("write-start",e);try{const t=await this.getFullPath(e);await i.remove(t)}catch(t){!t.includes("No such file or directory")&&!t.includes("forbidden path")&&console.error(t)}finally{this.scheduleWriteEnd(e)}}}cancelWriteEndTimer(e){const t=this.writeEndTimers.get(e);t&&(clearTimeout(t),this.writeEndTimers.delete(e))}scheduleWriteEnd(e){this.cancelWriteEndTimer(e);const t=setTimeout(()=>{this.emit("write-end",e),this.writeEndTimers.delete(e)},1e3);this.writeEndTimers.set(e,t)}async rename(e,t){const s=await this.getFullPath(e),r=await this.getFullPath(t);await i.rename(s,r)}async getFullPath(e){return await i.join(this.baseDir,e??"")}}exports.TauriFileSystemAdapter=h;